import { Deepline, DeeplineClient } from 'deepline'; type StoredRun = { runId: string; status: 'running' | 'completed' | 'failed' | 'cancelled'; }; // Demonstration stores only: these Maps do not survive a process restart. // Replace them with durable application storage before deployment. // The production result write needs an atomic uniqueness check keyed by runId. const runs = new Map(); const persistedResults = new Map(); const terminalStatuses = new Set(['completed', 'failed', 'cancelled']); async function saveRun(run: StoredRun): Promise { runs.set(run.runId, run); } async function writeResultOnce(runId: string, result: unknown): Promise { if (!persistedResults.has(runId)) { persistedResults.set(runId, result); } } export async function startEnrichment(input: { company_domain: string; job_title: string; }): Promise { // The caller must persist launch intent before invoking this function. // Reconcile a lost launch response before submitting replacement work. const deepline = await Deepline.connect(); const job = await deepline .play<{ domain: string; roles: string[] }>('prebuilt/company-to-contact') .run({ domain: input.company_domain, roles: [input.job_title], }); // Persist the public run id before waiting for completion. await saveRun({ runId: job.id, status: 'running' }); return job.id; } export async function recoverEnrichment(runId: string): Promise { const client = new DeeplineClient(); const status = await client.getPlayStatus(runId, { full: true }); if (!terminalStatuses.has(status.status)) { const running = { runId, status: 'running' } as const; await saveRun(running); return running; } if (status.status === 'completed') { await writeResultOnce(runId, status.result); } const terminal = { runId, status: status.status } as StoredRun; await saveRun(terminal); return terminal; } export async function stopEnrichment( runId: string, ): Promise<'stopped' | 'cancelling'> { const client = new DeeplineClient(); const result = await client.stopPlay(runId, { reason: 'Request cancelled by the user', }); if (result.stopped) return 'stopped'; if (result.state === 'cancelling' || result.cancelling) return 'cancelling'; throw new Error(result.error ?? `Could not confirm stop for ${runId}`); }