import deepline from 'deepline'; function emailFromResult(value: unknown): string | null { if (!value || typeof value !== 'object' || !('email' in value)) { throw new Error('Work-email Play returned no email field.'); } if (value.email !== null && typeof value.email !== 'string') { throw new Error('Work-email Play returned an invalid email field.'); } return value.email; } // Pipeline: company list -> company_titles -> LLM ICP filter -> search_contact. // Optional email reveal runs only when reveal_tier is "email". // // Run: // deepline plays run companies-to-contacts-icp-titles.play.ts \ // --input '{"csv":"companies.csv","icp_criteria":"VP or Head of Sales, Revenue, GTM at B2B SaaS 50-500 employees","max_results":50,"reveal_tier":"linkedin"}' \ // --watch // // Input CSV columns: domain (required), company_name (optional), company_linkedin (optional) type CompanyRow = { domain: string; company_name?: string; company_linkedin?: string; }; type MatchedTitles = { matched_titles: string[]; reasoning: string; }; type RevealTier = 'linkedin' | 'email'; const asString = (v: unknown): string => typeof v === 'string' && v.trim() ? v.trim() : ''; // rawV2 is unknown; inspect its observed envelope and narrow before reading fields. const asRecord = (v: unknown): Record => v && typeof v === 'object' ? (v as Record) : {}; function providerData(value: unknown): Record { const response = asRecord(asRecord(value).toolResponse); if (!Object.prototype.hasOwnProperty.call(response, 'rawV2')) { throw new Error( 'Tool response has no rawV2; upgrade the SDK and rebundle this Play.', ); } const canonical = asRecord(response.rawV2); return response.view === 'data' ? asRecord(canonical.data) : canonical; } function titlesFromResult(value: unknown): string[] { const data = providerData(value); if (data.status === 'no_result') return []; const titles = asRecord(data.output).titles; if ( !Array.isArray(titles) || !titles.every( (title): title is string => typeof title === 'string' && title.trim().length > 0, ) ) { throw new Error('Company title lookup returned no valid titles array.'); } return titles; } function matchedTitlesFromResult( value: unknown, roster: string[], ): MatchedTitles { const result = asRecord(asRecord(providerData(value).result).object); const titles = result.matched_titles; if ( !Array.isArray(titles) || !titles.every((title): title is string => typeof title === 'string') || typeof result.reasoning !== 'string' ) { throw new Error( 'AI title selection returned an invalid structured result.', ); } const rosterTitles = new Set(roster); if (titles.some((title) => !rosterTitles.has(title))) { throw new Error('AI selected a title that is not in the company roster.'); } // This example sends one title list. A larger selection needs an explicitly // scoped batching workflow, not silent truncation to the first 100 titles. if (titles.length > 100) { throw new Error( 'AI selected more than 100 titles; narrow the criteria or explicitly batch the selection.', ); } return { matched_titles: [...new Set(titles)], reasoning: result.reasoning }; } // Accept the whole title after trimming, collapsing whitespace, and ignoring // case. Substrings, prefixes, and additional role text do not count as matches. const normalizedTitle = (title: string): string => title.trim().replace(/\s+/g, ' ').toLowerCase(); // --- Flatten to one row per contact --- // search_contact returns output.persons[] (LinkedIn-only - email/phone are // redacted, so email is filled by the downstream waterfall below). type ContactRow = CompanyRow & { first_name: string; last_name: string; title: string; email: string | null; email_status: string | null; linkedin_url: string | null; matched_titles: string[]; icp_reasoning: string; }; export const config = { description: 'Find contacts with matching titles', compatibility: { authoringContract: 'explicit-freshness' }, }; export default async function (input: { csv: string; icp_criteria: string; max_results?: number; reveal_tier?: RevealTier; }) { // One bounded candidate page per company, not every matching contact. // search_contact can return broader titles; the local acceptance check below // runs before optional paid email lookup. Complete coverage needs pagination. const maxResults = input.max_results ?? 50; const icpCriteria = input.icp_criteria; const revealTier: RevealTier = input.reveal_tier ?? 'linkedin'; const companies = await deepline.csv(input.csv); // --- Step 1: Get all current titles at each company --- const withTitles = await deepline .dataset('titles', companies) .withColumn('company_titles', (company) => deepline.tools.execute({ id: 'get_titles', tool: 'company_titles', input: { domain: company.domain, ...(company.company_linkedin ? { company_linkedin: company.company_linkedin } : {}), }, description: `Get all job titles at ${company.domain}`, staleAfterSeconds: 0, }), ) .run({ key: 'domain', description: 'Fetch live title list per company.', }); // --- Step 2: LLM filters titles against ICP criteria --- const withMatchedTitles = await deepline .dataset('icp_filter', withTitles) .withColumn('icp_match', (row) => { // Inspect the canonical company_titles response in a bounded pilot; // this example reads the observed provider body's output.titles. const titles = titlesFromResult(row.company_titles); if (!titles.length) return null; return deepline.tools.execute({ id: 'match_icp_titles', tool: 'deeplineagent', input: { prompt: [ `ICP criteria: ${icpCriteria}`, '', 'From the list of job titles below, return only the titles that match the ICP criteria.', 'Return exact strings from the list - do not paraphrase or invent new titles.', 'If none match, return an empty array.', '', 'Titles:', titles.map((t) => `- ${t}`).join('\n'), '', 'Return JSON: { "matched_titles": string[], "reasoning": "one sentence" }', ].join('\n'), jsonSchema: { type: 'object', properties: { matched_titles: { type: 'array', items: { type: 'string' }, }, reasoning: { type: 'string' }, }, required: ['matched_titles', 'reasoning'], additionalProperties: false, }, }, description: `Filter titles at ${row.domain} against ICP criteria.`, staleAfterSeconds: 0, }); }) .run({ key: 'domain', description: 'LLM ICP title matching per company.', }); // --- Step 3: Find a candidate page for the selected roster titles --- // search_contact (not prospector) because title_lists is only supported by // search_contact (prospector returns 422 on title_lists; it takes boolean // title_filters + `limit`). Provider title matching is not guaranteed exact. // LinkedIn URLs only; email/phone are redacted, so enrich those downstream // only for contacts whose returned titles pass the local acceptance check. const withContacts = await deepline .dataset('prospecting', withMatchedTitles) .withColumn('contacts', (row) => { if (row.icp_match === null) return null; const matchResult = matchedTitlesFromResult( row.icp_match, titlesFromResult(row.company_titles), ); const matchedTitles = matchResult.matched_titles; if (!matchedTitles.length) return null; return deepline.tools.execute({ id: 'find_contacts', tool: 'deepline_native_search_contact', input: { domain: row.domain, title_lists: [{ name: 'icp', titles: matchedTitles }], page_size: maxResults, }, description: `Find contacts matching ICP titles at ${row.domain}`, staleAfterSeconds: 0, }); }) .run({ key: 'domain', description: 'Fetch a bounded contact candidate page per company.', }); const allContacts: ContactRow[] = []; // Counts rejected candidates in the returned page, not unseen provider rows. let rejectedTitleCount = 0; for await (const row of withContacts) { if (row.contacts === null) continue; const contactsOutput = asRecord(providerData(row.contacts).output) as { persons?: Array>; }; const matchResult = matchedTitlesFromResult( row.icp_match, titlesFromResult(row.company_titles), ); const acceptedTitles = new Set( matchResult.matched_titles.map(normalizedTitle), ); for (const person of contactsOutput.persons ?? []) { const title = asString(person.title); if (!acceptedTitles.has(normalizedTitle(title))) { rejectedTitleCount += 1; continue; } allContacts.push({ domain: row.domain, company_name: row.company_name, first_name: asString(person.first_name), last_name: asString(person.last_name), title, // search_contact redacts contact channels; left null for the // downstream email waterfall to fill. email: null, email_status: null, linkedin_url: asString(person.linkedin_url) || null, matched_titles: matchResult.matched_titles, icp_reasoning: matchResult.reasoning, }); } } if (!allContacts.length) { return { rows: [], contact_count: 0, rejected_title_count: rejectedTitleCount, reveal_tier: revealTier, }; } if (revealTier === 'linkedin') { return { rows: allContacts, contact_count: allContacts.length, rejected_title_count: rejectedTitleCount, reveal_tier: revealTier, }; } // --- Step 4: Email enrichment --- // search_contact is LinkedIn-only, so email lookup is a separate paid tier. // This branch runs only when reveal_tier is "email"; keep the default // LinkedIn-only so route exploration does not buy email by accident. const withEmails = await deepline .dataset('email_enrichment', allContacts) .withColumn('email_result', (contact) => deepline.runPlay( 'get_email', 'name-and-domain-to-email-waterfall', { first_name: contact.first_name, last_name: contact.last_name, domain: contact.domain, }, { description: 'Find verified work email.' }, ), ) .withColumn('email', (contact) => emailFromResult(contact.email_result)) .run({ key: (c) => `${c.domain}::${c.first_name}_${c.last_name}`, description: 'Enrich email per contact.', }); return { rows: withEmails, contact_count: allContacts.length, rejected_title_count: rejectedTitleCount, reveal_tier: revealTier, }; }