@patchbay-nebius/agent 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +66 -2
- package/dist/chunk-JVXVCXNZ.js +2356 -0
- package/dist/chunk-JVXVCXNZ.js.map +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +391 -0
- package/dist/cli.js.map +1 -0
- package/dist/fixtures/typeform-pipedrive/attempt-1/README.md +41 -0
- package/dist/fixtures/typeform-pipedrive/attempt-1/src/connector.test.ts +111 -0
- package/dist/fixtures/typeform-pipedrive/attempt-1/src/connector.ts +93 -0
- package/dist/fixtures/typeform-pipedrive/attempt-1/src/fixtures.ts +173 -0
- package/dist/fixtures/typeform-pipedrive/final/README.md +41 -0
- package/dist/fixtures/typeform-pipedrive/final/src/connector.test.ts +111 -0
- package/dist/fixtures/typeform-pipedrive/final/src/connector.ts +94 -0
- package/dist/fixtures/typeform-pipedrive/final/src/fixtures.ts +173 -0
- package/dist/fixtures/typeform-pipedrive/meta.json +192 -0
- package/dist/fixtures/typeform-pipedrive/run.json +444 -0
- package/dist/index.d.ts +302 -0
- package/dist/index.js +39 -0
- package/dist/index.js.map +1 -0
- package/dist/scanner-IPBNTPNM.js +247 -0
- package/dist/scanner-IPBNTPNM.js.map +1 -0
- package/package.json +61 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/config.ts","../src/parse.ts","../src/llm.ts","../src/local-runner.ts","../src/report.ts","../src/fixtures/typeform-pipedrive/run.json","../src/replay.ts","../src/contract.ts","../src/syntax-check.ts","../src/prompts.ts","../src/sources.ts","../src/run.ts","../src/sandbox.ts","../src/tavily.ts","../src/index.ts"],"sourcesContent":["export interface ModelTier {\n id: string\n /** USD per million tokens, used for the cost readout. */\n inputPrice: number\n outputPrice: number\n}\n\nexport interface AgentConfig {\n mock: boolean\n /** `nebius` (isolated sandbox, default) or `local` (dev fallback, not isolated). */\n runner: 'nebius' | 'local'\n nebiusApiKey: string\n nebiusProject: string\n nebiusBaseUrl: string\n sandboxUrl: string\n tavilyApiKey: string\n baseImage: string | undefined\n maxAttempts: number\n /** How many repair variants to try in parallel per attempt. 1 = classic sequential repair. */\n parallelRepairs: number\n /**\n * LLM provider identity, chosen by setting PATCHBAY_LLM_PROVIDER. Default `nebius` keeps\n * the Nemotron-specific `chat_template_kwargs: { enable_thinking: false }` field in requests;\n * `openai` / `generic` strip it so any other OpenAI-compatible endpoint (OpenAI, Groq,\n * Together, Fireworks, OpenRouter, self-hosted vLLM) stops rejecting it.\n */\n llmProvider: 'nebius' | 'openai' | 'generic'\n models: { fast: ModelTier; mid: ModelTier; strong: ModelTier }\n}\n\ntype Env = Record<string, string | undefined>\n\nexport function loadConfig(env: Env = process.env): AgentConfig {\n const provider = parseProvider(env.PATCHBAY_LLM_PROVIDER)\n // When pointing at OpenAI (or any other provider) directly, reuse the Nebius env vars so\n // existing deployments don't have to re-wire everything — just override LLM_BASE_URL / etc.\n const apiKey = env.PATCHBAY_LLM_API_KEY || env.NEBIUS_API_KEY || env.OPENAI_API_KEY || ''\n const baseUrl =\n env.PATCHBAY_LLM_BASE_URL ||\n env.NEBIUS_BASE_URL ||\n (provider === 'openai' ? 'https://api.openai.com/v1' : 'https://api.tokenfactory.nebius.com/v1')\n const defaultModels =\n provider === 'openai'\n ? { fast: 'gpt-4o-mini', mid: 'gpt-4o-mini', strong: 'gpt-4o' }\n : { fast: 'nvidia/Nemotron-3_5-Lightning', mid: 'nvidia/nemotron-3-super-120b-a12b', strong: 'nvidia/Nemotron-3-Ultra-550b-a55b' }\n return {\n mock: env.PATCHBAY_MOCK !== 'false',\n runner: env.PATCHBAY_RUNNER === 'local' ? 'local' : 'nebius',\n nebiusApiKey: apiKey,\n nebiusProject: env.NEBIUS_AI_PROJECT ?? '',\n nebiusBaseUrl: baseUrl,\n sandboxUrl: env.NEBIUS_SANDBOX_URL || 'https://api.tokenfactory.nebius.com/sandboxes/v1',\n tavilyApiKey: env.TAVILY_API_KEY ?? '',\n baseImage: env.PATCHBAY_BASE_IMAGE || undefined,\n maxAttempts: Number(env.PATCHBAY_MAX_ATTEMPTS || 4),\n parallelRepairs: clamp(Number(env.PATCHBAY_PARALLEL_REPAIRS || 2), 1, 4),\n llmProvider: provider,\n models: {\n fast: { id: env.PATCHBAY_MODEL_FAST || defaultModels.fast, inputPrice: 0.06, outputPrice: 0.24 },\n mid: { id: env.PATCHBAY_MODEL_MID || defaultModels.mid, inputPrice: 0.3, outputPrice: 0.9 },\n strong: { id: env.PATCHBAY_MODEL_STRONG || defaultModels.strong, inputPrice: 1, outputPrice: 3 },\n },\n }\n}\n\nfunction parseProvider(raw: string | undefined): AgentConfig['llmProvider'] {\n if (raw === 'openai' || raw === 'generic') return raw\n return 'nebius'\n}\n\nfunction clamp(n: number, min: number, max: number): number {\n return Number.isFinite(n) ? Math.min(max, Math.max(min, Math.round(n))) : min\n}\n\nexport function missingLiveKeys(config: AgentConfig): string[] {\n const missing: string[] = []\n if (!config.nebiusApiKey) missing.push('NEBIUS_API_KEY')\n if (config.runner === 'nebius' && !config.nebiusProject) missing.push('NEBIUS_AI_PROJECT')\n if (!config.tavilyApiKey) missing.push('TAVILY_API_KEY')\n return missing\n}\n","import type { GeneratedFile } from './types'\n\n/** Reasoning models may prepend a `<think>` block; it never belongs in the answer. */\nexport function stripReasoning(text: string): string {\n return text.replace(/<think>[\\s\\S]*?<\\/think>/gi, '').replace(/^[\\s\\S]*?<\\/think>/i, '').trim()\n}\n\n/** Pulls the first JSON object out of a model answer, tolerating code fences and prose around it. */\nexport function extractJson<T>(text: string): T {\n const clean = stripReasoning(text)\n const fenced = clean.match(/```(?:json)?\\s*([\\s\\S]*?)```/)\n const candidate = fenced?.[1] ?? clean\n const start = candidate.indexOf('{')\n const end = candidate.lastIndexOf('}')\n if (start === -1 || end <= start) throw new Error('model answer contained no JSON object')\n return JSON.parse(candidate.slice(start, end + 1)) as T\n}\n\n/**\n * Code is exchanged as `<file path=\"...\">...</file>` blocks instead of JSON, so the\n * model never has to escape source code inside a JSON string.\n */\nexport function parseFileBlocks(text: string): GeneratedFile[] {\n const clean = stripReasoning(text)\n const files: GeneratedFile[] = []\n const pattern = /<file\\s+path=\"([^\"]+)\">\\s*\\n?([\\s\\S]*?)\\n?<\\/file>/g\n for (const match of clean.matchAll(pattern)) {\n const path = normalizePath(match[1] ?? '')\n const content = stripFence(match[2] ?? '')\n if (path) files.push({ path, content: content.endsWith('\\n') ? content : `${content}\\n` })\n }\n return files\n}\n\nexport function renderFileBlocks(files: GeneratedFile[]): string {\n return files.map((f) => `<file path=\"${f.path}\">\\n${f.content.trimEnd()}\\n</file>`).join('\\n\\n')\n}\n\nfunction stripFence(content: string): string {\n const fenced = content.match(/^\\s*```[a-zA-Z]*\\n([\\s\\S]*?)\\n```\\s*$/)\n return fenced?.[1] ?? content\n}\n\nfunction normalizePath(path: string): string {\n const slashed = path.trim().replace(/\\\\/g, '/')\n if (slashed.startsWith('/') || /^[a-zA-Z]:/.test(slashed)) return ''\n const clean = slashed.replace(/^\\.\\//, '')\n if (clean.split('/').includes('..')) return ''\n return clean\n}\n","import type { ModelTier } from './config'\nimport { stripReasoning } from './parse'\nimport type { Usage } from './types'\n\nexport interface ChatMessage {\n role: 'system' | 'user' | 'assistant'\n content: string\n}\n\nexport interface ChatOptions {\n temperature?: number\n /** Includes reasoning tokens when thinking is on, so leave generous headroom. */\n maxTokens?: number\n /**\n * Nemotron reasons before answering by default. Structured steps (plan, spec) turn it off:\n * the answer is immediate and the token budget goes to the JSON, not to deliberation.\n */\n thinking?: boolean\n}\n\nexport interface LlmClient {\n chat(model: ModelTier, messages: ChatMessage[], options?: ChatOptions): Promise<string>\n usage(): Usage[]\n}\n\ninterface NebiusChatResponse {\n choices?: { message?: { content?: string | null; reasoning_content?: string | null } }[]\n usage?: { prompt_tokens?: number; completion_tokens?: number }\n error?: { message?: string }\n}\n\n/**\n * OpenAI-compatible chat client. Default endpoint is Nebius Token Factory, but any\n * OpenAI-compatible base URL works (OpenAI itself, Groq, Together, Fireworks, OpenRouter,\n * a self-hosted vLLM, …). `supportsNemotronThinking` controls whether the Nemotron-specific\n * `chat_template_kwargs: { enable_thinking: false }` flag is sent for structured steps —\n * leave it on for Nebius, off for everything else (OpenAI rejects unknown fields).\n */\nexport function createNebiusClient(opts: {\n apiKey: string\n baseUrl: string\n fetch?: typeof fetch\n retries?: number\n supportsNemotronThinking?: boolean\n}): LlmClient {\n const doFetch = opts.fetch ?? fetch\n const retries = opts.retries ?? 2\n const nemotron = opts.supportsNemotronThinking ?? true\n const ledger = new Map<string, Usage>()\n\n async function chat(model: ModelTier, messages: ChatMessage[], options: ChatOptions = {}): Promise<string> {\n const body = {\n model: model.id,\n messages,\n temperature: options.temperature ?? 0.2,\n max_tokens: options.maxTokens ?? 4096,\n ...(nemotron && options.thinking === false ? { chat_template_kwargs: { enable_thinking: false } } : {}),\n }\n\n let lastError: unknown\n for (let attempt = 0; attempt <= retries; attempt++) {\n try {\n const res = await doFetch(`${opts.baseUrl}/chat/completions`, {\n method: 'POST',\n headers: { Authorization: `Bearer ${opts.apiKey}`, 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n })\n const data = (await res.json().catch(() => ({}))) as NebiusChatResponse\n if (!res.ok) {\n const message = data.error?.message ?? `HTTP ${res.status}`\n if (res.status === 429 || res.status >= 500) throw new RetryableError(message)\n throw new Error(`Nebius ${model.id}: ${message}`)\n }\n record(model, data.usage)\n const content = data.choices?.[0]?.message?.content ?? ''\n return stripReasoning(content)\n } catch (error) {\n lastError = error\n if (!(error instanceof RetryableError) && !isTransientFetchError(error)) break\n if (attempt === retries) break\n await sleep(800 * 2 ** attempt)\n }\n }\n throw lastError instanceof Error ? lastError : new Error(String(lastError))\n }\n\n function record(model: ModelTier, usage: NebiusChatResponse['usage']) {\n const current = ledger.get(model.id) ?? { model: model.id, promptTokens: 0, completionTokens: 0, costUsd: 0 }\n current.promptTokens += usage?.prompt_tokens ?? 0\n current.completionTokens += usage?.completion_tokens ?? 0\n current.costUsd =\n (current.promptTokens / 1e6) * model.inputPrice + (current.completionTokens / 1e6) * model.outputPrice\n ledger.set(model.id, current)\n }\n\n return { chat, usage: () => [...ledger.values()] }\n}\n\nclass RetryableError extends Error {}\n\n/**\n * Undici (Node's built-in fetch) throws TypeError('fetch failed') with a transient\n * network cause on Vercel serverless more often than you'd like — stale keep-alive\n * sockets, upstream TCP resets, DNS flakes. Treat those as retryable so a single\n * dropped socket doesn't kill the whole run.\n */\nfunction isTransientFetchError(error: unknown): boolean {\n if (!(error instanceof Error)) return false\n const cause = (error as Error & { cause?: unknown }).cause as { code?: string; name?: string } | undefined\n const code = cause?.code ?? ''\n const name = cause?.name ?? ''\n return (\n error.message === 'fetch failed' ||\n name === 'SocketError' ||\n ['UND_ERR_SOCKET', 'ECONNRESET', 'ECONNREFUSED', 'ETIMEDOUT', 'EAI_AGAIN', 'ENOTFOUND', 'EPIPE'].includes(code)\n )\n}\n\nconst sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))\n","import { execFile } from 'node:child_process'\nimport { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { parseTestOutput, TSC_MARKER, VITEST_MARKER } from './report'\nimport type { SandboxRunner } from './sandbox'\nimport type { GeneratedFile } from './types'\n\nconst TSCONFIG = {\n compilerOptions: {\n target: 'ES2022',\n module: 'ESNext',\n moduleResolution: 'Bundler',\n strict: true,\n skipLibCheck: true,\n types: ['node'],\n lib: ['ES2022', 'DOM'],\n },\n include: ['src/**/*.ts'],\n}\n\n/**\n * Fallback runner for development: typecheck + vitest in a temp folder on this machine.\n * Same command and parser as the Nebius sandbox, but NOT isolated, so it is opt-in via\n * PATCHBAY_RUNNER=local and never used by the hosted demo.\n */\nexport function createLocalRunner(opts: { root?: string; timeoutMs?: number } = {}): SandboxRunner {\n const root = opts.root ?? findRepoRoot(process.cwd())\n const tscEntry = join(root, 'node_modules', 'typescript', 'bin', 'tsc')\n const vitestEntry = join(root, 'node_modules', 'vitest', 'vitest.mjs')\n const timeout = opts.timeoutMs ?? 120_000\n\n return {\n async prepare(log) {\n log('Local runner: typecheck and tests run on this machine, not in an isolated sandbox')\n return 'local'\n },\n\n async runTests(_base, files, log) {\n const workRoot = join(root, '.fixture-tmp')\n mkdirSync(workRoot, { recursive: true })\n const work = mkdtempSync(join(workRoot, 'run-'))\n try {\n for (const file of files.filter((f) => f.path.endsWith('.ts'))) write(work, file)\n writeFileSync(join(work, 'tsconfig.json'), JSON.stringify(TSCONFIG))\n writeFileSync(join(work, 'vitest.config.mjs'), 'export default { test: { include: [\"src/**/*.test.ts\"] } }\\n')\n log(`Running tsc and vitest in ${work.replace(root, '.')}`)\n const tsc = await run(tscEntry, ['--noEmit', '-p', 'tsconfig.json'], work, timeout)\n await run(vitestEntry, ['run', '--reporter=json', '--outputFile=result.json'], work, timeout)\n const json = existsSync(join(work, 'result.json')) ? await readText(join(work, 'result.json')) : ''\n const stdout = `${TSC_MARKER}\\n${tsc.code}\\n${tsc.output}\\n${VITEST_MARKER}\\n${json}`\n return parseTestOutput(stdout, 'local')\n } finally {\n rmSync(work, { recursive: true, force: true })\n }\n },\n }\n}\n\nfunction write(dir: string, file: GeneratedFile) {\n const path = join(dir, file.path)\n mkdirSync(dirname(path), { recursive: true })\n writeFileSync(path, file.content)\n}\n\n/** Runs a JS entry point with the current node binary, so no shell and no platform-specific wrappers. */\nfunction run(entry: string, args: string[], cwd: string, timeout: number): Promise<{ code: number; output: string }> {\n return new Promise((resolve) => {\n execFile(process.execPath, [entry, ...args], { cwd, timeout, maxBuffer: 10_000_000 }, (error, stdout, stderr) => {\n const code = error ? (typeof error.code === 'number' ? error.code : 1) : 0\n resolve({ code, output: `${stdout}${stderr}`.slice(0, 6000) })\n })\n })\n}\n\nasync function readText(path: string): Promise<string> {\n const { readFile } = await import('node:fs/promises')\n return readFile(path, 'utf8')\n}\n\nfunction findRepoRoot(start: string): string {\n let dir = start\n for (;;) {\n if (existsSync(join(dir, 'node_modules', 'vitest'))) return dir\n const parent = dirname(dir)\n if (parent === dir) return start\n dir = parent\n }\n}\n","import type { TestFailure, TestReport } from './types'\n\nexport const TSC_MARKER = '@@PATCHBAY_TSC@@'\nexport const VITEST_MARKER = '@@PATCHBAY_VITEST@@'\n\n/**\n * Shell run inside the sandbox. Type-checks, runs vitest with the JSON reporter and\n * prints both results between markers so a single stdout carries everything.\n */\nexport const TEST_COMMAND = [\n 'cd /work',\n 'npx tsc --noEmit -p tsconfig.json > /tmp/tsc.txt 2>&1; echo $? > /tmp/tsc.code',\n 'npx vitest run --reporter=json --outputFile=/tmp/vitest.json > /tmp/vitest.log 2>&1',\n `echo \"${TSC_MARKER}\"`,\n 'cat /tmp/tsc.code',\n 'head -c 6000 /tmp/tsc.txt',\n `echo \"${VITEST_MARKER}\"`,\n 'cat /tmp/vitest.json 2>/dev/null || tail -c 6000 /tmp/vitest.log',\n].join('; ')\n\ninterface VitestJson {\n numTotalTests?: number\n numPassedTests?: number\n numFailedTests?: number\n startTime?: number\n testResults?: {\n endTime?: number\n message?: string\n assertionResults?: { fullName?: string; title?: string; status?: string; failureMessages?: string[] }[]\n }[]\n}\n\nexport function parseTestOutput(stdout: string, ranOn: string): TestReport {\n const tscStart = stdout.indexOf(TSC_MARKER)\n const vitestStart = stdout.indexOf(VITEST_MARKER)\n const tscSection = tscStart >= 0 ? stdout.slice(tscStart + TSC_MARKER.length, vitestStart >= 0 ? vitestStart : undefined).trim() : ''\n const vitestSection = vitestStart >= 0 ? stdout.slice(vitestStart + VITEST_MARKER.length).trim() : stdout.trim()\n\n const [codeLine = '1', ...tscLines] = tscSection.split('\\n')\n const typecheckOk = codeLine.trim() === '0'\n const typecheckOutput = tscLines.join('\\n').trim()\n\n let json: VitestJson | null = null\n try {\n const start = vitestSection.indexOf('{')\n json = start >= 0 ? (JSON.parse(vitestSection.slice(start)) as VitestJson) : null\n } catch {\n json = null\n }\n\n if (!json) {\n return {\n typecheckOk,\n typecheckOutput,\n passed: 0,\n failed: 1,\n total: 1,\n failures: [{ name: 'vitest', message: truncate(vitestSection || 'vitest produced no output', 4000) }],\n durationMs: 0,\n ranOn,\n }\n }\n\n const failures: TestFailure[] = []\n const passedNames: string[] = []\n let endTime = json.startTime ?? 0\n for (const file of json.testResults ?? []) {\n endTime = Math.max(endTime, file.endTime ?? 0)\n if ((file.assertionResults ?? []).length === 0 && file.message) {\n failures.push({ name: 'test file', message: truncate(stripAnsi(file.message), 2000) })\n }\n for (const assertion of file.assertionResults ?? []) {\n if (assertion.status === 'passed') passedNames.push(assertion.fullName || assertion.title || '')\n if (assertion.status === 'failed') {\n failures.push({\n name: assertion.fullName || assertion.title || 'unnamed test',\n message: truncate(stripAnsi((assertion.failureMessages ?? []).join('\\n')), 2000),\n })\n }\n }\n }\n\n const total = json.numTotalTests ?? 0\n const failed = Math.max(json.numFailedTests ?? 0, failures.length)\n return {\n typecheckOk,\n typecheckOutput,\n passed: json.numPassedTests ?? Math.max(0, total - failed),\n failed,\n total: Math.max(total, failed),\n failures,\n durationMs: json.startTime && endTime ? Math.max(0, endTime - json.startTime) : 0,\n ranOn,\n passedNames,\n }\n}\n\nexport function isGreen(report: TestReport): boolean {\n const contractOk = report.contract === undefined || report.contract === 'passed'\n return report.typecheckOk && report.failed === 0 && report.total > 0 && contractOk\n}\n\nconst stripAnsi = (s: string) => s.replace(/\\u001b\\[[0-9;]*m/g, '')\nconst truncate = (s: string, max: number) => (s.length > max ? `${s.slice(0, max)}\\n…` : s)\n","{\n \"prompt\": \"When someone submits our Typeform contact form, create the lead in Pipedrive as organization, person and deal.\",\n \"origin\": \"fixture\",\n \"events\": [\n {\n \"type\": \"mode\",\n \"mode\": \"live\"\n },\n {\n \"type\": \"step\",\n \"step\": \"plan\",\n \"status\": \"start\"\n },\n {\n \"type\": \"plan\",\n \"plan\": {\n \"summary\": \"On every Typeform form_response webhook, create a Pipedrive organization (if a company was given), a person linked to it, and a deal for that person.\",\n \"source\": {\n \"app\": \"Typeform\",\n \"trigger\": \"form_response webhook\",\n \"docsQuery\": \"Typeform webhooks form_response payload answers field ref\"\n },\n \"target\": {\n \"app\": \"Pipedrive\",\n \"action\": \"create organization, person and deal\",\n \"docsQuery\": \"Pipedrive API v1 add person add deal add organization request body api token\"\n },\n \"fieldMapping\": [\n {\n \"from\": \"answer with field ref lead_name (text)\",\n \"to\": \"person.name\"\n },\n {\n \"from\": \"answer with field ref lead_email (email)\",\n \"to\": \"person.email[0].value\"\n },\n {\n \"from\": \"answer with field ref lead_phone (phone_number)\",\n \"to\": \"person.phone[0].value\"\n },\n {\n \"from\": \"answer with field ref lead_company (text)\",\n \"to\": \"organization.name, deal title\"\n }\n ],\n \"assumptions\": [\n \"Field refs are configurable because every Typeform form uses different refs.\",\n \"Webhook signature verification happens before the connector is called.\",\n \"Every submission is a new lead; no deduplication against existing persons.\"\n ]\n }\n },\n {\n \"type\": \"step\",\n \"step\": \"plan\",\n \"status\": \"done\",\n \"detail\": \"On every Typeform form_response webhook, create a Pipedrive organization (if a company was given), a person linked to it, and a deal for that person.\"\n },\n {\n \"type\": \"step\",\n \"step\": \"research\",\n \"status\": \"start\"\n },\n {\n \"type\": \"log\",\n \"step\": \"research\",\n \"message\": \"Searched \\\"Typeform webhooks form_response payload answers field ref\\\": 5 results\"\n },\n {\n \"type\": \"log\",\n \"step\": \"research\",\n \"message\": \"Searched \\\"Pipedrive API v1 add person add deal add organization request body api token\\\": 5 results\"\n },\n {\n \"type\": \"log\",\n \"step\": \"research\",\n \"message\": \"Extracted 4 documentation pages\"\n },\n {\n \"type\": \"sources\",\n \"sources\": [\n {\n \"title\": \"Webhooks payload | Typeform Developer Platform\",\n \"url\": \"https://www.typeform.com/developers/webhooks/example-payload/\",\n \"official\": true\n },\n {\n \"title\": \"Webhooks | Typeform Developer Platform\",\n \"url\": \"https://www.typeform.com/developers/webhooks/\",\n \"official\": true\n },\n {\n \"title\": \"Persons - Pipedrive API Reference\",\n \"url\": \"https://developers.pipedrive.com/docs/api/v1/Persons\",\n \"official\": true\n },\n {\n \"title\": \"Deals - Pipedrive API Reference\",\n \"url\": \"https://developers.pipedrive.com/docs/api/v1/Deals\",\n \"official\": true\n }\n ]\n },\n {\n \"type\": \"spec\",\n \"spec\": {\n \"source\": {\n \"app\": \"Typeform\",\n \"role\": \"source\",\n \"method\": \"POST\",\n \"url\": \"(your webhook endpoint)\",\n \"auth\": {\n \"type\": \"none\",\n \"envVar\": \"TYPEFORM_WEBHOOK_SECRET\"\n },\n \"example\": {\n \"event_id\": \"01H...\",\n \"event_type\": \"form_response\",\n \"form_response\": {\n \"form_id\": \"lT4Z3j\",\n \"token\": \"a3a12ec67a1365927098a606107fac15\",\n \"submitted_at\": \"2026-10-01T09:00:00Z\",\n \"answers\": [\n {\n \"type\": \"text\",\n \"field\": {\n \"id\": \"f1\",\n \"ref\": \"lead_name\",\n \"type\": \"short_text\"\n },\n \"text\": \"Ada Lovelace\"\n },\n {\n \"type\": \"email\",\n \"field\": {\n \"id\": \"f2\",\n \"ref\": \"lead_email\",\n \"type\": \"email\"\n },\n \"email\": \"ada@example.com\"\n }\n ]\n }\n },\n \"docsUrl\": \"https://www.typeform.com/developers/webhooks/example-payload/\",\n \"notes\": [\n \"Each answer carries its value under a key named after its type (text, email, phone_number, ...).\",\n \"Answers are matched by field.ref, which the form owner can set; field ids are generated.\"\n ]\n },\n \"target\": [\n {\n \"app\": \"Pipedrive\",\n \"role\": \"target\",\n \"method\": \"POST\",\n \"url\": \"https://api.pipedrive.com/v1/organizations\",\n \"auth\": {\n \"type\": \"header\",\n \"name\": \"x-api-token\",\n \"envVar\": \"PIPEDRIVE_API_TOKEN\"\n },\n \"example\": {\n \"name\": \"Analytical Engines Ltd\"\n },\n \"responseExample\": {\n \"success\": true,\n \"data\": {\n \"id\": 11\n }\n },\n \"docsUrl\": \"https://developers.pipedrive.com/docs/api/v1/Organizations\",\n \"notes\": [\n \"Only call when a company was answered.\"\n ]\n },\n {\n \"app\": \"Pipedrive\",\n \"role\": \"target\",\n \"method\": \"POST\",\n \"url\": \"https://api.pipedrive.com/v1/persons\",\n \"auth\": {\n \"type\": \"header\",\n \"name\": \"x-api-token\",\n \"envVar\": \"PIPEDRIVE_API_TOKEN\"\n },\n \"example\": {\n \"name\": \"Ada Lovelace\",\n \"email\": [\n {\n \"value\": \"ada@example.com\",\n \"primary\": true,\n \"label\": \"work\"\n }\n ],\n \"org_id\": 11\n },\n \"responseExample\": {\n \"success\": true,\n \"data\": {\n \"id\": 22\n }\n },\n \"docsUrl\": \"https://developers.pipedrive.com/docs/api/v1/Persons\",\n \"notes\": [\n \"email and phone are arrays of { value, primary, label }.\",\n \"The API token can be sent as the x-api-token header instead of the api_token query parameter.\"\n ]\n },\n {\n \"app\": \"Pipedrive\",\n \"role\": \"target\",\n \"method\": \"POST\",\n \"url\": \"https://api.pipedrive.com/v1/deals\",\n \"auth\": {\n \"type\": \"header\",\n \"name\": \"x-api-token\",\n \"envVar\": \"PIPEDRIVE_API_TOKEN\"\n },\n \"example\": {\n \"title\": \"Website lead: Analytical Engines Ltd\",\n \"person_id\": 22,\n \"org_id\": 11\n },\n \"responseExample\": {\n \"success\": true,\n \"data\": {\n \"id\": 33\n }\n },\n \"docsUrl\": \"https://developers.pipedrive.com/docs/api/v1/Deals\",\n \"notes\": [\n \"title is required. Link both person_id and org_id so the deal shows up on the organization.\"\n ]\n }\n ]\n }\n },\n {\n \"type\": \"step\",\n \"step\": \"research\",\n \"status\": \"done\",\n \"detail\": \"4 endpoints from 4 pages\"\n },\n {\n \"type\": \"step\",\n \"step\": \"generate\",\n \"status\": \"start\"\n },\n {\n \"type\": \"files\",\n \"attempt\": 1,\n \"files\": [\n {\n \"path\": \"src/connector.ts\",\n \"content\": \"export interface ConnectorConfig {\\n /** Pipedrive personal API token (env: PIPEDRIVE_API_TOKEN). */\\n pipedriveApiToken: string\\n /** Defaults to https://api.pipedrive.com/v1 */\\n pipedriveBaseUrl?: string\\n /** Typeform field refs that hold the lead's data. */\\n fieldRefs: { name: string; email: string; company?: string; phone?: string }\\n /** Prefix for the deal title, e.g. \\\"Website lead\\\". */\\n dealTitlePrefix?: string\\n fetch?: typeof fetch\\n}\\n\\nexport interface TypeformAnswer {\\n type: string\\n field: { id: string; ref: string; type: string }\\n text?: string\\n email?: string\\n phone_number?: string\\n}\\n\\nexport interface TypeformWebhook {\\n event_id: string\\n event_type: 'form_response'\\n form_response: {\\n form_id: string\\n token: string\\n submitted_at: string\\n answers: TypeformAnswer[]\\n }\\n}\\n\\nexport interface HandleResult {\\n personId: number\\n organizationId: number | null\\n dealId: number\\n}\\n\\ninterface PipedriveResponse {\\n success: boolean\\n data?: { id: number }\\n error?: string\\n}\\n\\nexport async function handle(payload: TypeformWebhook, config: ConnectorConfig): Promise<HandleResult> {\\n if (payload?.event_type !== 'form_response') {\\n throw new Error(`Unsupported Typeform event: ${String(payload?.event_type)}`)\\n }\\n const answers = payload.form_response.answers ?? []\\n const name = answerValue(answers, config.fieldRefs.name)\\n const email = answerValue(answers, config.fieldRefs.email)\\n if (!name) throw new Error(`Missing required answer for field ref \\\"${config.fieldRefs.name}\\\" (name)`)\\n if (!email) throw new Error(`Missing required answer for field ref \\\"${config.fieldRefs.email}\\\" (email)`)\\n const company = config.fieldRefs.company ? answerValue(answers, config.fieldRefs.company) : undefined\\n const phone = config.fieldRefs.phone ? answerValue(answers, config.fieldRefs.phone) : undefined\\n\\n const organizationId = company ? (await post(config, '/organizations', { name: company })).id : null\\n\\n const person = await post(config, '/persons', {\\n name,\\n email: [{ value: email, primary: true, label: 'work' }],\\n ...(phone ? { phone: [{ value: phone, primary: true, label: 'work' }] } : {}),\\n ...(organizationId ? { org_id: organizationId } : {}),\\n })\\n\\n const deal = await post(config, '/deals', {\\n title: `${config.dealTitlePrefix ?? 'Typeform lead'}: ${company ?? name}`,\\n person_id: person.id,\\n })\\n\\n return { personId: person.id, organizationId, dealId: deal.id }\\n}\\n\\nfunction answerValue(answers: TypeformAnswer[], ref: string): string | undefined {\\n const answer = answers.find((a) => a.field?.ref === ref)\\n if (!answer) return undefined\\n const value = answer.email ?? answer.phone_number ?? answer.text\\n return value?.trim() || undefined\\n}\\n\\nasync function post(config: ConnectorConfig, path: string, body: Record<string, unknown>): Promise<{ id: number }> {\\n const doFetch = config.fetch ?? fetch\\n const url = `${config.pipedriveBaseUrl ?? 'https://api.pipedrive.com/v1'}${path}`\\n const res = await doFetch(url, {\\n method: 'POST',\\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${config.pipedriveApiToken}` },\\n body: JSON.stringify(body),\\n })\\n const data = (await res.json().catch(() => ({}))) as PipedriveResponse\\n if (!res.ok || !data.success || !data.data) {\\n throw new Error(`Pipedrive POST ${path} failed with ${res.status}: ${data.error ?? 'no error message'}`)\\n }\\n return data.data\\n}\\n\"\n },\n {\n \"path\": \"src/connector.test.ts\",\n \"content\": \"import { describe, it, expect, vi } from 'vitest'\\nimport { handle, type ConnectorConfig, type TypeformWebhook } from './connector'\\nimport { SOURCE_EXAMPLE, contractFetch } from './fixtures'\\n\\nfunction fakeFetch(responses: Record<string, { status?: number; body: unknown }>) {\\n return vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {\\n const url = String(input)\\n const path = Object.keys(responses).find((p) => url.endsWith(p))\\n const response = path ? responses[path] : undefined\\n if (!response) throw new Error(`unexpected request to ${url} ${init?.method}`)\\n return new Response(JSON.stringify(response.body), { status: response.status ?? 201 })\\n })\\n}\\n\\nconst ok = (id: number) => ({ body: { success: true, data: { id } } })\\n\\nfunction payload(overrides: Partial<Record<'name' | 'email' | 'company' | 'phone', string | null>> = {}): TypeformWebhook {\\n const values = { name: 'Ada Lovelace', email: 'ada@example.com', company: 'Analytical Engines Ltd', phone: '+44 20 7946 0000', ...overrides }\\n const answers = [\\n values.name !== null && { type: 'text', field: { id: 'f1', ref: 'lead_name', type: 'short_text' }, text: values.name },\\n values.email !== null && { type: 'email', field: { id: 'f2', ref: 'lead_email', type: 'email' }, email: values.email },\\n values.company !== null && { type: 'text', field: { id: 'f3', ref: 'lead_company', type: 'short_text' }, text: values.company },\\n values.phone !== null && { type: 'phone_number', field: { id: 'f4', ref: 'lead_phone', type: 'phone_number' }, phone_number: values.phone },\\n ].filter(Boolean) as TypeformWebhook['form_response']['answers']\\n return {\\n event_id: 'evt_1',\\n event_type: 'form_response',\\n form_response: { form_id: 'frm_1', token: 'tok_1', submitted_at: '2026-10-01T09:00:00Z', answers },\\n }\\n}\\n\\nfunction config(fetch: typeof globalThis.fetch): ConnectorConfig {\\n return {\\n pipedriveApiToken: 'test-token',\\n fieldRefs: { name: 'lead_name', email: 'lead_email', company: 'lead_company', phone: 'lead_phone' },\\n dealTitlePrefix: 'Website lead',\\n fetch,\\n }\\n}\\n\\ndescribe('handle', () => {\\n it('creates organization, person and deal with the mapped fields', async () => {\\n const fetch = fakeFetch({ '/organizations': ok(11), '/persons': ok(22), '/deals': ok(33) })\\n const result = await handle(payload(), config(fetch))\\n\\n expect(result).toEqual({ personId: 22, organizationId: 11, dealId: 33 })\\n const bodies = fetch.mock.calls.map(([url, init]) => [String(url), JSON.parse(String(init?.body))])\\n expect(bodies).toEqual([\\n ['https://api.pipedrive.com/v1/organizations', { name: 'Analytical Engines Ltd' }],\\n ['https://api.pipedrive.com/v1/persons', {\\n name: 'Ada Lovelace',\\n email: [{ value: 'ada@example.com', primary: true, label: 'work' }],\\n phone: [{ value: '+44 20 7946 0000', primary: true, label: 'work' }],\\n org_id: 11,\\n }],\\n ['https://api.pipedrive.com/v1/deals', { title: 'Website lead: Analytical Engines Ltd', person_id: 22, org_id: 11 }],\\n ])\\n })\\n\\n it('authenticates every call with the x-api-token header', async () => {\\n const fetch = fakeFetch({ '/organizations': ok(1), '/persons': ok(2), '/deals': ok(3) })\\n await handle(payload(), config(fetch))\\n for (const [, init] of fetch.mock.calls) {\\n expect(new Headers(init?.headers).get('x-api-token')).toBe('test-token')\\n expect(init?.method).toBe('POST')\\n }\\n })\\n\\n it('skips the organization when no company was answered', async () => {\\n const fetch = fakeFetch({ '/persons': ok(2), '/deals': ok(3) })\\n const result = await handle(payload({ company: null }), config(fetch))\\n expect(result.organizationId).toBeNull()\\n expect(fetch).toHaveBeenCalledTimes(2)\\n const deal = JSON.parse(String(fetch.mock.calls[1]?.[1]?.body))\\n expect(deal).toEqual({ title: 'Website lead: Ada Lovelace', person_id: 2 })\\n })\\n\\n it('rejects a response without an email answer', async () => {\\n const fetch = fakeFetch({})\\n await expect(handle(payload({ email: null }), config(fetch))).rejects.toThrow(/lead_email/)\\n expect(fetch).not.toHaveBeenCalled()\\n })\\n\\n it('surfaces Pipedrive errors with status and endpoint', async () => {\\n const fetch = fakeFetch({\\n '/organizations': ok(1),\\n '/persons': { status: 401, body: { success: false, error: 'unauthorized access' } },\\n })\\n await expect(handle(payload(), config(fetch))).rejects.toThrow('Pipedrive POST /persons failed with 401: unauthorized access')\\n })\\n\\n it('ignores events that are not form responses', async () => {\\n const fetch = fakeFetch({})\\n const event = { ...payload(), event_type: 'form_deleted' } as unknown as TypeformWebhook\\n await expect(handle(event, config(fetch))).rejects.toThrow(/Unsupported Typeform event/)\\n })\\n})\\n\\ndescribe('contract', () => {\\n it('handles the documented Typeform payload against the documented Pipedrive responses', async () => {\\n const { fetch, calls } = contractFetch()\\n const result = await handle(SOURCE_EXAMPLE as unknown as TypeformWebhook, {\\n pipedriveApiToken: 'contract-token',\\n fieldRefs: { name: 'lead_name', email: 'lead_email' },\\n fetch,\\n })\\n expect(result.personId).toBeGreaterThan(0)\\n expect(result.dealId).toBeGreaterThan(0)\\n expect(calls.map((c) => c.url)).toEqual(['https://api.pipedrive.com/v1/persons', 'https://api.pipedrive.com/v1/deals'])\\n })\\n})\\n\"\n },\n {\n \"path\": \"README.md\",\n \"content\": \"# Typeform → Pipedrive connector\\n\\nTurns a Typeform `form_response` webhook into a Pipedrive organization, person and deal.\\n\\n## Configuration\\n\\n| Env var | Used as | Notes |\\n| --- | --- | --- |\\n| `PIPEDRIVE_API_TOKEN` | `pipedriveApiToken` | Personal API token, sent as the `x-api-token` header |\\n\\n`fieldRefs` maps your Typeform field refs to the lead fields. `name` and `email` are required; `company` and `phone` are optional.\\n\\n## Usage\\n\\n```ts\\nimport { handle } from './src/connector'\\n\\nexport async function POST(request: Request) {\\n const payload = await request.json()\\n const result = await handle(payload, {\\n pipedriveApiToken: process.env.PIPEDRIVE_API_TOKEN!,\\n fieldRefs: { name: 'lead_name', email: 'lead_email', company: 'lead_company', phone: 'lead_phone' },\\n dealTitlePrefix: 'Website lead',\\n })\\n return Response.json(result)\\n}\\n```\\n\\n## Behaviour\\n\\n1. Reads the answers by field ref, rejects the event when name or email is missing.\\n2. Creates an organization when a company was answered (`POST /v1/organizations`).\\n3. Creates the person with email and phone, linked to the organization (`POST /v1/persons`).\\n4. Creates a deal for the person (`POST /v1/deals`).\\n\\nAny non-2xx or `success: false` response throws with the status code and endpoint, so the webhook caller can retry.\\n\\n## Assumptions\\n\\n- Typeform webhook signature verification happens before `handle` is called.\\n- Every submission is a new lead; the connector does not search for existing persons.\\n\"\n },\n {\n \"path\": \"src/fixtures.ts\",\n \"content\": \"// Written by patchbay from the API documentation. Regenerated on every attempt, do not edit.\\n// Source: https://www.typeform.com/developers/webhooks/example-payload/\\n// Source: https://developers.pipedrive.com/docs/api/v1/Organizations\\n// Source: https://developers.pipedrive.com/docs/api/v1/Persons\\n// Source: https://developers.pipedrive.com/docs/api/v1/Deals\\n\\n/** Example payload of the source event, as documented. */\\nexport const SOURCE_EXAMPLE = {\\n \\\"event_id\\\": \\\"01H...\\\",\\n \\\"event_type\\\": \\\"form_response\\\",\\n \\\"form_response\\\": {\\n \\\"form_id\\\": \\\"lT4Z3j\\\",\\n \\\"token\\\": \\\"a3a12ec67a1365927098a606107fac15\\\",\\n \\\"submitted_at\\\": \\\"2026-10-01T09:00:00Z\\\",\\n \\\"answers\\\": [\\n {\\n \\\"type\\\": \\\"text\\\",\\n \\\"field\\\": {\\n \\\"id\\\": \\\"f1\\\",\\n \\\"ref\\\": \\\"lead_name\\\",\\n \\\"type\\\": \\\"short_text\\\"\\n },\\n \\\"text\\\": \\\"Ada Lovelace\\\"\\n },\\n {\\n \\\"type\\\": \\\"email\\\",\\n \\\"field\\\": {\\n \\\"id\\\": \\\"f2\\\",\\n \\\"ref\\\": \\\"lead_email\\\",\\n \\\"type\\\": \\\"email\\\"\\n },\\n \\\"email\\\": \\\"ada@example.com\\\"\\n }\\n ]\\n }\\n}\\n\\nexport interface DocumentedEndpoint {\\n method: string\\n /** As documented; may contain placeholders such as {id}, :id, <id> or a region host like usX. */\\n url: string\\n response: unknown\\n}\\n\\n/** Target endpoints the connector may call, in the documented order, with their documented responses. */\\nexport const TARGET_ENDPOINTS: DocumentedEndpoint[] = [\\n {\\n \\\"method\\\": \\\"POST\\\",\\n \\\"url\\\": \\\"https://api.pipedrive.com/v1/organizations\\\",\\n \\\"response\\\": {\\n \\\"success\\\": true,\\n \\\"data\\\": {\\n \\\"id\\\": 11\\n }\\n }\\n },\\n {\\n \\\"method\\\": \\\"POST\\\",\\n \\\"url\\\": \\\"https://api.pipedrive.com/v1/persons\\\",\\n \\\"response\\\": {\\n \\\"success\\\": true,\\n \\\"data\\\": {\\n \\\"id\\\": 22\\n }\\n }\\n },\\n {\\n \\\"method\\\": \\\"POST\\\",\\n \\\"url\\\": \\\"https://api.pipedrive.com/v1/deals\\\",\\n \\\"response\\\": {\\n \\\"success\\\": true,\\n \\\"data\\\": {\\n \\\"id\\\": 33\\n }\\n }\\n }\\n]\\n\\nexport interface RecordedCall {\\n method: string\\n url: string\\n /** The request body exactly as sent (usually a JSON string). */\\n body: string | undefined\\n /** The body parsed as JSON, or undefined when it is not JSON. */\\n json: unknown\\n headers: Headers\\n}\\n\\n/** The documented endpoint a request matches, placeholders and region subdomains included. */\\nexport function findEndpoint(method: string, url: string): DocumentedEndpoint | undefined {\\n return TARGET_ENDPOINTS.find((endpoint) => endpoint.method === method.toUpperCase() && urlMatches(endpoint.url, url))\\n}\\n\\n/**\\n * A fake fetch that answers every documented endpoint with its documented response and\\n * rejects anything else. Use it in the contract test:\\n *\\n * const { fetch, calls } = contractFetch()\\n * await handle(SOURCE_EXAMPLE as MyInput, { ...config, fetch })\\n * expect(calls.length).toBeGreaterThan(0)\\n */\\nexport function contractFetch(): { fetch: typeof fetch; calls: RecordedCall[] } {\\n return fakeFetch((request) => {\\n const endpoint = findEndpoint(request.method, request.url)\\n if (!endpoint) throw new Error(`contract: ${request.method} ${request.url} is not a documented endpoint`)\\n return jsonResponse(endpoint.response)\\n })\\n}\\n\\n/**\\n * A correctly typed fake fetch for every other test. The handler receives the recorded\\n * request: { method, url, body (string as sent), json (parsed body), headers (Headers) }.\\n *\\n * const { fetch, calls } = fakeFetch((req) => req.url.endsWith('/deals') ? jsonResponse({ id: 1 }, 201) : jsonResponse({}, 404))\\n */\\nexport function fakeFetch(\\n handler: (request: RecordedCall) => Response | Promise<Response>,\\n): { fetch: typeof fetch; calls: RecordedCall[] } {\\n const calls: RecordedCall[] = []\\n const fake = async (input: string | URL | Request, init: RequestInit = {}): Promise<Response> => {\\n const url = input instanceof Request ? input.url : String(input)\\n const method = (init.method ?? (input instanceof Request ? input.method : 'GET')).toUpperCase()\\n const body = typeof init.body === 'string' ? init.body : init.body == null ? undefined : String(init.body)\\n const call: RecordedCall = { method, url, body, json: parseJson(body), headers: new Headers(init.headers) }\\n calls.push(call)\\n return handler(call)\\n }\\n return { fetch: fake as typeof fetch, calls }\\n}\\n\\nconst STATUS_TEXT: Record<number, string> = {\\n 200: 'OK', 201: 'Created', 202: 'Accepted', 204: 'No Content',\\n 400: 'Bad Request', 401: 'Unauthorized', 403: 'Forbidden', 404: 'Not Found', 409: 'Conflict',\\n 422: 'Unprocessable Entity', 429: 'Too Many Requests',\\n 500: 'Internal Server Error', 502: 'Bad Gateway', 503: 'Service Unavailable',\\n}\\n\\n/** A JSON Response with the standard status text, e.g. jsonResponse({ error: 'nope' }, 401) -> \\\"401 Unauthorized\\\". */\\nexport function jsonResponse(body: unknown, status = 200): Response {\\n const init = { status, statusText: STATUS_TEXT[status] ?? '', headers: { 'Content-Type': 'application/json' } }\\n return new Response(status === 204 ? null : JSON.stringify(body), init)\\n}\\n\\nfunction parseJson(raw: string | undefined): unknown {\\n if (raw === undefined) return undefined\\n try {\\n return JSON.parse(raw)\\n } catch {\\n return undefined\\n }\\n}\\n\\nfunction urlMatches(template: string, actual: string): boolean {\\n const t = splitUrl(template)\\n const a = splitUrl(actual)\\n if (!t || !a) return false\\n const tHost = t.host.split('.')\\n const aHost = a.host.split('.')\\n if (tHost.slice(-2).join('.') !== aHost.slice(-2).join('.')) return false\\n const tPath = t.path.replace(/\\\\/+$/, '').split('/')\\n const aPath = a.path.replace(/\\\\/+$/, '').split('/')\\n if (tPath.length !== aPath.length) return false\\n return tPath.every((segment, i) => isPlaceholder(segment) || segment === aPath[i])\\n}\\n\\nfunction splitUrl(url: string): { host: string; path: string } | null {\\n const match = url.match(/^https?:\\\\/\\\\/([^/?#]+)([^?#]*)/i)\\n return match ? { host: (match[1] ?? '').toLowerCase(), path: match[2] || '/' } : null\\n}\\n\\nfunction isPlaceholder(segment: string): boolean {\\n return /^\\\\{[^}]+\\\\}$|^:[A-Za-z_]\\\\w*$|^<[^>]+>$/.test(segment)\\n}\\n\"\n }\n ]\n },\n {\n \"type\": \"step\",\n \"step\": \"generate\",\n \"status\": \"done\",\n \"detail\": \"src/connector.ts, src/connector.test.ts, README.md\"\n },\n {\n \"type\": \"log\",\n \"step\": \"generate\",\n \"message\": \"Wrote src/fixtures.ts from the documented example payload and responses\"\n },\n {\n \"type\": \"step\",\n \"step\": \"verify\",\n \"status\": \"start\"\n },\n {\n \"type\": \"log\",\n \"step\": \"verify\",\n \"message\": \"Reusing prepared sandbox image (node 22, typescript, vitest)\"\n },\n {\n \"type\": \"log\",\n \"step\": \"verify\",\n \"message\": \"Forking checkpoint with 4 files, network off\"\n },\n {\n \"type\": \"tests\",\n \"attempt\": 1,\n \"report\": {\n \"typecheckOk\": true,\n \"typecheckOutput\": \"\",\n \"passed\": 5,\n \"failed\": 2,\n \"total\": 7,\n \"failures\": [\n {\n \"name\": \"handle creates organization, person and deal with the mapped fields\",\n \"message\": \"AssertionError: expected [ [ …(2) ], [ …(2) ], [ …(2) ] ] to deeply equal [ [ …(2) ], [ …(2) ], [ …(2) ] ]\\n at /work/src/connector.test.ts:48:20\\n at processTicksAndRejections (node:internal/process/task_queues:104:5)\\n at file:///C:/Users/vogel/Desktop/patchbay/node_modules/@vitest/runner/dist/chunk-artifact.js:1903:20\"\n },\n {\n \"name\": \"handle authenticates every call with the x-api-token header\",\n \"message\": \"AssertionError: expected null to be 'test-token' // Object.is equality\\n at /work/src/connector.test.ts:64:61\\n at processTicksAndRejections (node:internal/process/task_queues:104:5)\\n at file:///C:/Users/vogel/Desktop/patchbay/node_modules/@vitest/runner/dist/chunk-artifact.js:1903:20\"\n }\n ],\n \"durationMs\": 199.913818359375,\n \"ranOn\": \"replay\",\n \"passedNames\": [\n \"handle skips the organization when no company was answered\",\n \"handle rejects a response without an email answer\",\n \"handle surfaces Pipedrive errors with status and endpoint\",\n \"handle ignores events that are not form responses\",\n \"contract handles the documented Typeform payload against the documented Pipedrive responses\"\n ],\n \"contract\": \"passed\"\n }\n },\n {\n \"type\": \"log\",\n \"step\": \"verify\",\n \"message\": \"Attempt 1 failed (2 tests, typecheck ok), repairing\"\n },\n {\n \"type\": \"files\",\n \"attempt\": 2,\n \"files\": [\n {\n \"path\": \"src/connector.ts\",\n \"content\": \"export interface ConnectorConfig {\\n /** Pipedrive personal API token (env: PIPEDRIVE_API_TOKEN). */\\n pipedriveApiToken: string\\n /** Defaults to https://api.pipedrive.com/v1 */\\n pipedriveBaseUrl?: string\\n /** Typeform field refs that hold the lead's data. */\\n fieldRefs: { name: string; email: string; company?: string; phone?: string }\\n /** Prefix for the deal title, e.g. \\\"Website lead\\\". */\\n dealTitlePrefix?: string\\n fetch?: typeof fetch\\n}\\n\\nexport interface TypeformAnswer {\\n type: string\\n field: { id: string; ref: string; type: string }\\n text?: string\\n email?: string\\n phone_number?: string\\n}\\n\\nexport interface TypeformWebhook {\\n event_id: string\\n event_type: 'form_response'\\n form_response: {\\n form_id: string\\n token: string\\n submitted_at: string\\n answers: TypeformAnswer[]\\n }\\n}\\n\\nexport interface HandleResult {\\n personId: number\\n organizationId: number | null\\n dealId: number\\n}\\n\\ninterface PipedriveResponse {\\n success: boolean\\n data?: { id: number }\\n error?: string\\n}\\n\\nexport async function handle(payload: TypeformWebhook, config: ConnectorConfig): Promise<HandleResult> {\\n if (payload?.event_type !== 'form_response') {\\n throw new Error(`Unsupported Typeform event: ${String(payload?.event_type)}`)\\n }\\n const answers = payload.form_response.answers ?? []\\n const name = answerValue(answers, config.fieldRefs.name)\\n const email = answerValue(answers, config.fieldRefs.email)\\n if (!name) throw new Error(`Missing required answer for field ref \\\"${config.fieldRefs.name}\\\" (name)`)\\n if (!email) throw new Error(`Missing required answer for field ref \\\"${config.fieldRefs.email}\\\" (email)`)\\n const company = config.fieldRefs.company ? answerValue(answers, config.fieldRefs.company) : undefined\\n const phone = config.fieldRefs.phone ? answerValue(answers, config.fieldRefs.phone) : undefined\\n\\n const organizationId = company ? (await post(config, '/organizations', { name: company })).id : null\\n\\n const person = await post(config, '/persons', {\\n name,\\n email: [{ value: email, primary: true, label: 'work' }],\\n ...(phone ? { phone: [{ value: phone, primary: true, label: 'work' }] } : {}),\\n ...(organizationId ? { org_id: organizationId } : {}),\\n })\\n\\n const deal = await post(config, '/deals', {\\n title: `${config.dealTitlePrefix ?? 'Typeform lead'}: ${company ?? name}`,\\n person_id: person.id,\\n ...(organizationId ? { org_id: organizationId } : {}),\\n })\\n\\n return { personId: person.id, organizationId, dealId: deal.id }\\n}\\n\\nfunction answerValue(answers: TypeformAnswer[], ref: string): string | undefined {\\n const answer = answers.find((a) => a.field?.ref === ref)\\n if (!answer) return undefined\\n const value = answer.email ?? answer.phone_number ?? answer.text\\n return value?.trim() || undefined\\n}\\n\\nasync function post(config: ConnectorConfig, path: string, body: Record<string, unknown>): Promise<{ id: number }> {\\n const doFetch = config.fetch ?? fetch\\n const url = `${config.pipedriveBaseUrl ?? 'https://api.pipedrive.com/v1'}${path}`\\n const res = await doFetch(url, {\\n method: 'POST',\\n headers: { 'Content-Type': 'application/json', 'x-api-token': config.pipedriveApiToken },\\n body: JSON.stringify(body),\\n })\\n const data = (await res.json().catch(() => ({}))) as PipedriveResponse\\n if (!res.ok || !data.success || !data.data) {\\n throw new Error(`Pipedrive POST ${path} failed with ${res.status}: ${data.error ?? 'no error message'}`)\\n }\\n return data.data\\n}\\n\"\n },\n {\n \"path\": \"src/connector.test.ts\",\n \"content\": \"import { describe, it, expect, vi } from 'vitest'\\nimport { handle, type ConnectorConfig, type TypeformWebhook } from './connector'\\nimport { SOURCE_EXAMPLE, contractFetch } from './fixtures'\\n\\nfunction fakeFetch(responses: Record<string, { status?: number; body: unknown }>) {\\n return vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {\\n const url = String(input)\\n const path = Object.keys(responses).find((p) => url.endsWith(p))\\n const response = path ? responses[path] : undefined\\n if (!response) throw new Error(`unexpected request to ${url} ${init?.method}`)\\n return new Response(JSON.stringify(response.body), { status: response.status ?? 201 })\\n })\\n}\\n\\nconst ok = (id: number) => ({ body: { success: true, data: { id } } })\\n\\nfunction payload(overrides: Partial<Record<'name' | 'email' | 'company' | 'phone', string | null>> = {}): TypeformWebhook {\\n const values = { name: 'Ada Lovelace', email: 'ada@example.com', company: 'Analytical Engines Ltd', phone: '+44 20 7946 0000', ...overrides }\\n const answers = [\\n values.name !== null && { type: 'text', field: { id: 'f1', ref: 'lead_name', type: 'short_text' }, text: values.name },\\n values.email !== null && { type: 'email', field: { id: 'f2', ref: 'lead_email', type: 'email' }, email: values.email },\\n values.company !== null && { type: 'text', field: { id: 'f3', ref: 'lead_company', type: 'short_text' }, text: values.company },\\n values.phone !== null && { type: 'phone_number', field: { id: 'f4', ref: 'lead_phone', type: 'phone_number' }, phone_number: values.phone },\\n ].filter(Boolean) as TypeformWebhook['form_response']['answers']\\n return {\\n event_id: 'evt_1',\\n event_type: 'form_response',\\n form_response: { form_id: 'frm_1', token: 'tok_1', submitted_at: '2026-10-01T09:00:00Z', answers },\\n }\\n}\\n\\nfunction config(fetch: typeof globalThis.fetch): ConnectorConfig {\\n return {\\n pipedriveApiToken: 'test-token',\\n fieldRefs: { name: 'lead_name', email: 'lead_email', company: 'lead_company', phone: 'lead_phone' },\\n dealTitlePrefix: 'Website lead',\\n fetch,\\n }\\n}\\n\\ndescribe('handle', () => {\\n it('creates organization, person and deal with the mapped fields', async () => {\\n const fetch = fakeFetch({ '/organizations': ok(11), '/persons': ok(22), '/deals': ok(33) })\\n const result = await handle(payload(), config(fetch))\\n\\n expect(result).toEqual({ personId: 22, organizationId: 11, dealId: 33 })\\n const bodies = fetch.mock.calls.map(([url, init]) => [String(url), JSON.parse(String(init?.body))])\\n expect(bodies).toEqual([\\n ['https://api.pipedrive.com/v1/organizations', { name: 'Analytical Engines Ltd' }],\\n ['https://api.pipedrive.com/v1/persons', {\\n name: 'Ada Lovelace',\\n email: [{ value: 'ada@example.com', primary: true, label: 'work' }],\\n phone: [{ value: '+44 20 7946 0000', primary: true, label: 'work' }],\\n org_id: 11,\\n }],\\n ['https://api.pipedrive.com/v1/deals', { title: 'Website lead: Analytical Engines Ltd', person_id: 22, org_id: 11 }],\\n ])\\n })\\n\\n it('authenticates every call with the x-api-token header', async () => {\\n const fetch = fakeFetch({ '/organizations': ok(1), '/persons': ok(2), '/deals': ok(3) })\\n await handle(payload(), config(fetch))\\n for (const [, init] of fetch.mock.calls) {\\n expect(new Headers(init?.headers).get('x-api-token')).toBe('test-token')\\n expect(init?.method).toBe('POST')\\n }\\n })\\n\\n it('skips the organization when no company was answered', async () => {\\n const fetch = fakeFetch({ '/persons': ok(2), '/deals': ok(3) })\\n const result = await handle(payload({ company: null }), config(fetch))\\n expect(result.organizationId).toBeNull()\\n expect(fetch).toHaveBeenCalledTimes(2)\\n const deal = JSON.parse(String(fetch.mock.calls[1]?.[1]?.body))\\n expect(deal).toEqual({ title: 'Website lead: Ada Lovelace', person_id: 2 })\\n })\\n\\n it('rejects a response without an email answer', async () => {\\n const fetch = fakeFetch({})\\n await expect(handle(payload({ email: null }), config(fetch))).rejects.toThrow(/lead_email/)\\n expect(fetch).not.toHaveBeenCalled()\\n })\\n\\n it('surfaces Pipedrive errors with status and endpoint', async () => {\\n const fetch = fakeFetch({\\n '/organizations': ok(1),\\n '/persons': { status: 401, body: { success: false, error: 'unauthorized access' } },\\n })\\n await expect(handle(payload(), config(fetch))).rejects.toThrow('Pipedrive POST /persons failed with 401: unauthorized access')\\n })\\n\\n it('ignores events that are not form responses', async () => {\\n const fetch = fakeFetch({})\\n const event = { ...payload(), event_type: 'form_deleted' } as unknown as TypeformWebhook\\n await expect(handle(event, config(fetch))).rejects.toThrow(/Unsupported Typeform event/)\\n })\\n})\\n\\ndescribe('contract', () => {\\n it('handles the documented Typeform payload against the documented Pipedrive responses', async () => {\\n const { fetch, calls } = contractFetch()\\n const result = await handle(SOURCE_EXAMPLE as unknown as TypeformWebhook, {\\n pipedriveApiToken: 'contract-token',\\n fieldRefs: { name: 'lead_name', email: 'lead_email' },\\n fetch,\\n })\\n expect(result.personId).toBeGreaterThan(0)\\n expect(result.dealId).toBeGreaterThan(0)\\n expect(calls.map((c) => c.url)).toEqual(['https://api.pipedrive.com/v1/persons', 'https://api.pipedrive.com/v1/deals'])\\n })\\n})\\n\"\n },\n {\n \"path\": \"README.md\",\n \"content\": \"# Typeform → Pipedrive connector\\n\\nTurns a Typeform `form_response` webhook into a Pipedrive organization, person and deal.\\n\\n## Configuration\\n\\n| Env var | Used as | Notes |\\n| --- | --- | --- |\\n| `PIPEDRIVE_API_TOKEN` | `pipedriveApiToken` | Personal API token, sent as the `x-api-token` header |\\n\\n`fieldRefs` maps your Typeform field refs to the lead fields. `name` and `email` are required; `company` and `phone` are optional.\\n\\n## Usage\\n\\n```ts\\nimport { handle } from './src/connector'\\n\\nexport async function POST(request: Request) {\\n const payload = await request.json()\\n const result = await handle(payload, {\\n pipedriveApiToken: process.env.PIPEDRIVE_API_TOKEN!,\\n fieldRefs: { name: 'lead_name', email: 'lead_email', company: 'lead_company', phone: 'lead_phone' },\\n dealTitlePrefix: 'Website lead',\\n })\\n return Response.json(result)\\n}\\n```\\n\\n## Behaviour\\n\\n1. Reads the answers by field ref, rejects the event when name or email is missing.\\n2. Creates an organization when a company was answered (`POST /v1/organizations`).\\n3. Creates the person with email and phone, linked to the organization (`POST /v1/persons`).\\n4. Creates a deal for the person (`POST /v1/deals`).\\n\\nAny non-2xx or `success: false` response throws with the status code and endpoint, so the webhook caller can retry.\\n\\n## Assumptions\\n\\n- Typeform webhook signature verification happens before `handle` is called.\\n- Every submission is a new lead; the connector does not search for existing persons.\\n\"\n },\n {\n \"path\": \"src/fixtures.ts\",\n \"content\": \"// Written by patchbay from the API documentation. Regenerated on every attempt, do not edit.\\n// Source: https://www.typeform.com/developers/webhooks/example-payload/\\n// Source: https://developers.pipedrive.com/docs/api/v1/Organizations\\n// Source: https://developers.pipedrive.com/docs/api/v1/Persons\\n// Source: https://developers.pipedrive.com/docs/api/v1/Deals\\n\\n/** Example payload of the source event, as documented. */\\nexport const SOURCE_EXAMPLE = {\\n \\\"event_id\\\": \\\"01H...\\\",\\n \\\"event_type\\\": \\\"form_response\\\",\\n \\\"form_response\\\": {\\n \\\"form_id\\\": \\\"lT4Z3j\\\",\\n \\\"token\\\": \\\"a3a12ec67a1365927098a606107fac15\\\",\\n \\\"submitted_at\\\": \\\"2026-10-01T09:00:00Z\\\",\\n \\\"answers\\\": [\\n {\\n \\\"type\\\": \\\"text\\\",\\n \\\"field\\\": {\\n \\\"id\\\": \\\"f1\\\",\\n \\\"ref\\\": \\\"lead_name\\\",\\n \\\"type\\\": \\\"short_text\\\"\\n },\\n \\\"text\\\": \\\"Ada Lovelace\\\"\\n },\\n {\\n \\\"type\\\": \\\"email\\\",\\n \\\"field\\\": {\\n \\\"id\\\": \\\"f2\\\",\\n \\\"ref\\\": \\\"lead_email\\\",\\n \\\"type\\\": \\\"email\\\"\\n },\\n \\\"email\\\": \\\"ada@example.com\\\"\\n }\\n ]\\n }\\n}\\n\\nexport interface DocumentedEndpoint {\\n method: string\\n /** As documented; may contain placeholders such as {id}, :id, <id> or a region host like usX. */\\n url: string\\n response: unknown\\n}\\n\\n/** Target endpoints the connector may call, in the documented order, with their documented responses. */\\nexport const TARGET_ENDPOINTS: DocumentedEndpoint[] = [\\n {\\n \\\"method\\\": \\\"POST\\\",\\n \\\"url\\\": \\\"https://api.pipedrive.com/v1/organizations\\\",\\n \\\"response\\\": {\\n \\\"success\\\": true,\\n \\\"data\\\": {\\n \\\"id\\\": 11\\n }\\n }\\n },\\n {\\n \\\"method\\\": \\\"POST\\\",\\n \\\"url\\\": \\\"https://api.pipedrive.com/v1/persons\\\",\\n \\\"response\\\": {\\n \\\"success\\\": true,\\n \\\"data\\\": {\\n \\\"id\\\": 22\\n }\\n }\\n },\\n {\\n \\\"method\\\": \\\"POST\\\",\\n \\\"url\\\": \\\"https://api.pipedrive.com/v1/deals\\\",\\n \\\"response\\\": {\\n \\\"success\\\": true,\\n \\\"data\\\": {\\n \\\"id\\\": 33\\n }\\n }\\n }\\n]\\n\\nexport interface RecordedCall {\\n method: string\\n url: string\\n /** The request body exactly as sent (usually a JSON string). */\\n body: string | undefined\\n /** The body parsed as JSON, or undefined when it is not JSON. */\\n json: unknown\\n headers: Headers\\n}\\n\\n/** The documented endpoint a request matches, placeholders and region subdomains included. */\\nexport function findEndpoint(method: string, url: string): DocumentedEndpoint | undefined {\\n return TARGET_ENDPOINTS.find((endpoint) => endpoint.method === method.toUpperCase() && urlMatches(endpoint.url, url))\\n}\\n\\n/**\\n * A fake fetch that answers every documented endpoint with its documented response and\\n * rejects anything else. Use it in the contract test:\\n *\\n * const { fetch, calls } = contractFetch()\\n * await handle(SOURCE_EXAMPLE as MyInput, { ...config, fetch })\\n * expect(calls.length).toBeGreaterThan(0)\\n */\\nexport function contractFetch(): { fetch: typeof fetch; calls: RecordedCall[] } {\\n return fakeFetch((request) => {\\n const endpoint = findEndpoint(request.method, request.url)\\n if (!endpoint) throw new Error(`contract: ${request.method} ${request.url} is not a documented endpoint`)\\n return jsonResponse(endpoint.response)\\n })\\n}\\n\\n/**\\n * A correctly typed fake fetch for every other test. The handler receives the recorded\\n * request: { method, url, body (string as sent), json (parsed body), headers (Headers) }.\\n *\\n * const { fetch, calls } = fakeFetch((req) => req.url.endsWith('/deals') ? jsonResponse({ id: 1 }, 201) : jsonResponse({}, 404))\\n */\\nexport function fakeFetch(\\n handler: (request: RecordedCall) => Response | Promise<Response>,\\n): { fetch: typeof fetch; calls: RecordedCall[] } {\\n const calls: RecordedCall[] = []\\n const fake = async (input: string | URL | Request, init: RequestInit = {}): Promise<Response> => {\\n const url = input instanceof Request ? input.url : String(input)\\n const method = (init.method ?? (input instanceof Request ? input.method : 'GET')).toUpperCase()\\n const body = typeof init.body === 'string' ? init.body : init.body == null ? undefined : String(init.body)\\n const call: RecordedCall = { method, url, body, json: parseJson(body), headers: new Headers(init.headers) }\\n calls.push(call)\\n return handler(call)\\n }\\n return { fetch: fake as typeof fetch, calls }\\n}\\n\\nconst STATUS_TEXT: Record<number, string> = {\\n 200: 'OK', 201: 'Created', 202: 'Accepted', 204: 'No Content',\\n 400: 'Bad Request', 401: 'Unauthorized', 403: 'Forbidden', 404: 'Not Found', 409: 'Conflict',\\n 422: 'Unprocessable Entity', 429: 'Too Many Requests',\\n 500: 'Internal Server Error', 502: 'Bad Gateway', 503: 'Service Unavailable',\\n}\\n\\n/** A JSON Response with the standard status text, e.g. jsonResponse({ error: 'nope' }, 401) -> \\\"401 Unauthorized\\\". */\\nexport function jsonResponse(body: unknown, status = 200): Response {\\n const init = { status, statusText: STATUS_TEXT[status] ?? '', headers: { 'Content-Type': 'application/json' } }\\n return new Response(status === 204 ? null : JSON.stringify(body), init)\\n}\\n\\nfunction parseJson(raw: string | undefined): unknown {\\n if (raw === undefined) return undefined\\n try {\\n return JSON.parse(raw)\\n } catch {\\n return undefined\\n }\\n}\\n\\nfunction urlMatches(template: string, actual: string): boolean {\\n const t = splitUrl(template)\\n const a = splitUrl(actual)\\n if (!t || !a) return false\\n const tHost = t.host.split('.')\\n const aHost = a.host.split('.')\\n if (tHost.slice(-2).join('.') !== aHost.slice(-2).join('.')) return false\\n const tPath = t.path.replace(/\\\\/+$/, '').split('/')\\n const aPath = a.path.replace(/\\\\/+$/, '').split('/')\\n if (tPath.length !== aPath.length) return false\\n return tPath.every((segment, i) => isPlaceholder(segment) || segment === aPath[i])\\n}\\n\\nfunction splitUrl(url: string): { host: string; path: string } | null {\\n const match = url.match(/^https?:\\\\/\\\\/([^/?#]+)([^?#]*)/i)\\n return match ? { host: (match[1] ?? '').toLowerCase(), path: match[2] || '/' } : null\\n}\\n\\nfunction isPlaceholder(segment: string): boolean {\\n return /^\\\\{[^}]+\\\\}$|^:[A-Za-z_]\\\\w*$|^<[^>]+>$/.test(segment)\\n}\\n\"\n }\n ]\n },\n {\n \"type\": \"log\",\n \"step\": \"verify\",\n \"message\": \"Forking checkpoint with 4 files, network off\"\n },\n {\n \"type\": \"tests\",\n \"attempt\": 2,\n \"report\": {\n \"typecheckOk\": true,\n \"typecheckOutput\": \"\",\n \"passed\": 7,\n \"failed\": 0,\n \"total\": 7,\n \"failures\": [],\n \"durationMs\": 202.9775390625,\n \"ranOn\": \"replay\",\n \"passedNames\": [\n \"handle creates organization, person and deal with the mapped fields\",\n \"handle authenticates every call with the x-api-token header\",\n \"handle skips the organization when no company was answered\",\n \"handle rejects a response without an email answer\",\n \"handle surfaces Pipedrive errors with status and endpoint\",\n \"handle ignores events that are not form responses\",\n \"contract handles the documented Typeform payload against the documented Pipedrive responses\"\n ],\n \"contract\": \"passed\"\n }\n },\n {\n \"type\": \"step\",\n \"step\": \"verify\",\n \"status\": \"done\",\n \"detail\": \"7/7 tests after 2 attempts\"\n },\n {\n \"type\": \"step\",\n \"step\": \"package\",\n \"status\": \"start\"\n },\n {\n \"type\": \"result\",\n \"ok\": true,\n \"attempts\": 2,\n \"files\": [\n {\n \"path\": \"src/connector.ts\",\n \"content\": \"export interface ConnectorConfig {\\n /** Pipedrive personal API token (env: PIPEDRIVE_API_TOKEN). */\\n pipedriveApiToken: string\\n /** Defaults to https://api.pipedrive.com/v1 */\\n pipedriveBaseUrl?: string\\n /** Typeform field refs that hold the lead's data. */\\n fieldRefs: { name: string; email: string; company?: string; phone?: string }\\n /** Prefix for the deal title, e.g. \\\"Website lead\\\". */\\n dealTitlePrefix?: string\\n fetch?: typeof fetch\\n}\\n\\nexport interface TypeformAnswer {\\n type: string\\n field: { id: string; ref: string; type: string }\\n text?: string\\n email?: string\\n phone_number?: string\\n}\\n\\nexport interface TypeformWebhook {\\n event_id: string\\n event_type: 'form_response'\\n form_response: {\\n form_id: string\\n token: string\\n submitted_at: string\\n answers: TypeformAnswer[]\\n }\\n}\\n\\nexport interface HandleResult {\\n personId: number\\n organizationId: number | null\\n dealId: number\\n}\\n\\ninterface PipedriveResponse {\\n success: boolean\\n data?: { id: number }\\n error?: string\\n}\\n\\nexport async function handle(payload: TypeformWebhook, config: ConnectorConfig): Promise<HandleResult> {\\n if (payload?.event_type !== 'form_response') {\\n throw new Error(`Unsupported Typeform event: ${String(payload?.event_type)}`)\\n }\\n const answers = payload.form_response.answers ?? []\\n const name = answerValue(answers, config.fieldRefs.name)\\n const email = answerValue(answers, config.fieldRefs.email)\\n if (!name) throw new Error(`Missing required answer for field ref \\\"${config.fieldRefs.name}\\\" (name)`)\\n if (!email) throw new Error(`Missing required answer for field ref \\\"${config.fieldRefs.email}\\\" (email)`)\\n const company = config.fieldRefs.company ? answerValue(answers, config.fieldRefs.company) : undefined\\n const phone = config.fieldRefs.phone ? answerValue(answers, config.fieldRefs.phone) : undefined\\n\\n const organizationId = company ? (await post(config, '/organizations', { name: company })).id : null\\n\\n const person = await post(config, '/persons', {\\n name,\\n email: [{ value: email, primary: true, label: 'work' }],\\n ...(phone ? { phone: [{ value: phone, primary: true, label: 'work' }] } : {}),\\n ...(organizationId ? { org_id: organizationId } : {}),\\n })\\n\\n const deal = await post(config, '/deals', {\\n title: `${config.dealTitlePrefix ?? 'Typeform lead'}: ${company ?? name}`,\\n person_id: person.id,\\n ...(organizationId ? { org_id: organizationId } : {}),\\n })\\n\\n return { personId: person.id, organizationId, dealId: deal.id }\\n}\\n\\nfunction answerValue(answers: TypeformAnswer[], ref: string): string | undefined {\\n const answer = answers.find((a) => a.field?.ref === ref)\\n if (!answer) return undefined\\n const value = answer.email ?? answer.phone_number ?? answer.text\\n return value?.trim() || undefined\\n}\\n\\nasync function post(config: ConnectorConfig, path: string, body: Record<string, unknown>): Promise<{ id: number }> {\\n const doFetch = config.fetch ?? fetch\\n const url = `${config.pipedriveBaseUrl ?? 'https://api.pipedrive.com/v1'}${path}`\\n const res = await doFetch(url, {\\n method: 'POST',\\n headers: { 'Content-Type': 'application/json', 'x-api-token': config.pipedriveApiToken },\\n body: JSON.stringify(body),\\n })\\n const data = (await res.json().catch(() => ({}))) as PipedriveResponse\\n if (!res.ok || !data.success || !data.data) {\\n throw new Error(`Pipedrive POST ${path} failed with ${res.status}: ${data.error ?? 'no error message'}`)\\n }\\n return data.data\\n}\\n\"\n },\n {\n \"path\": \"src/connector.test.ts\",\n \"content\": \"import { describe, it, expect, vi } from 'vitest'\\nimport { handle, type ConnectorConfig, type TypeformWebhook } from './connector'\\nimport { SOURCE_EXAMPLE, contractFetch } from './fixtures'\\n\\nfunction fakeFetch(responses: Record<string, { status?: number; body: unknown }>) {\\n return vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {\\n const url = String(input)\\n const path = Object.keys(responses).find((p) => url.endsWith(p))\\n const response = path ? responses[path] : undefined\\n if (!response) throw new Error(`unexpected request to ${url} ${init?.method}`)\\n return new Response(JSON.stringify(response.body), { status: response.status ?? 201 })\\n })\\n}\\n\\nconst ok = (id: number) => ({ body: { success: true, data: { id } } })\\n\\nfunction payload(overrides: Partial<Record<'name' | 'email' | 'company' | 'phone', string | null>> = {}): TypeformWebhook {\\n const values = { name: 'Ada Lovelace', email: 'ada@example.com', company: 'Analytical Engines Ltd', phone: '+44 20 7946 0000', ...overrides }\\n const answers = [\\n values.name !== null && { type: 'text', field: { id: 'f1', ref: 'lead_name', type: 'short_text' }, text: values.name },\\n values.email !== null && { type: 'email', field: { id: 'f2', ref: 'lead_email', type: 'email' }, email: values.email },\\n values.company !== null && { type: 'text', field: { id: 'f3', ref: 'lead_company', type: 'short_text' }, text: values.company },\\n values.phone !== null && { type: 'phone_number', field: { id: 'f4', ref: 'lead_phone', type: 'phone_number' }, phone_number: values.phone },\\n ].filter(Boolean) as TypeformWebhook['form_response']['answers']\\n return {\\n event_id: 'evt_1',\\n event_type: 'form_response',\\n form_response: { form_id: 'frm_1', token: 'tok_1', submitted_at: '2026-10-01T09:00:00Z', answers },\\n }\\n}\\n\\nfunction config(fetch: typeof globalThis.fetch): ConnectorConfig {\\n return {\\n pipedriveApiToken: 'test-token',\\n fieldRefs: { name: 'lead_name', email: 'lead_email', company: 'lead_company', phone: 'lead_phone' },\\n dealTitlePrefix: 'Website lead',\\n fetch,\\n }\\n}\\n\\ndescribe('handle', () => {\\n it('creates organization, person and deal with the mapped fields', async () => {\\n const fetch = fakeFetch({ '/organizations': ok(11), '/persons': ok(22), '/deals': ok(33) })\\n const result = await handle(payload(), config(fetch))\\n\\n expect(result).toEqual({ personId: 22, organizationId: 11, dealId: 33 })\\n const bodies = fetch.mock.calls.map(([url, init]) => [String(url), JSON.parse(String(init?.body))])\\n expect(bodies).toEqual([\\n ['https://api.pipedrive.com/v1/organizations', { name: 'Analytical Engines Ltd' }],\\n ['https://api.pipedrive.com/v1/persons', {\\n name: 'Ada Lovelace',\\n email: [{ value: 'ada@example.com', primary: true, label: 'work' }],\\n phone: [{ value: '+44 20 7946 0000', primary: true, label: 'work' }],\\n org_id: 11,\\n }],\\n ['https://api.pipedrive.com/v1/deals', { title: 'Website lead: Analytical Engines Ltd', person_id: 22, org_id: 11 }],\\n ])\\n })\\n\\n it('authenticates every call with the x-api-token header', async () => {\\n const fetch = fakeFetch({ '/organizations': ok(1), '/persons': ok(2), '/deals': ok(3) })\\n await handle(payload(), config(fetch))\\n for (const [, init] of fetch.mock.calls) {\\n expect(new Headers(init?.headers).get('x-api-token')).toBe('test-token')\\n expect(init?.method).toBe('POST')\\n }\\n })\\n\\n it('skips the organization when no company was answered', async () => {\\n const fetch = fakeFetch({ '/persons': ok(2), '/deals': ok(3) })\\n const result = await handle(payload({ company: null }), config(fetch))\\n expect(result.organizationId).toBeNull()\\n expect(fetch).toHaveBeenCalledTimes(2)\\n const deal = JSON.parse(String(fetch.mock.calls[1]?.[1]?.body))\\n expect(deal).toEqual({ title: 'Website lead: Ada Lovelace', person_id: 2 })\\n })\\n\\n it('rejects a response without an email answer', async () => {\\n const fetch = fakeFetch({})\\n await expect(handle(payload({ email: null }), config(fetch))).rejects.toThrow(/lead_email/)\\n expect(fetch).not.toHaveBeenCalled()\\n })\\n\\n it('surfaces Pipedrive errors with status and endpoint', async () => {\\n const fetch = fakeFetch({\\n '/organizations': ok(1),\\n '/persons': { status: 401, body: { success: false, error: 'unauthorized access' } },\\n })\\n await expect(handle(payload(), config(fetch))).rejects.toThrow('Pipedrive POST /persons failed with 401: unauthorized access')\\n })\\n\\n it('ignores events that are not form responses', async () => {\\n const fetch = fakeFetch({})\\n const event = { ...payload(), event_type: 'form_deleted' } as unknown as TypeformWebhook\\n await expect(handle(event, config(fetch))).rejects.toThrow(/Unsupported Typeform event/)\\n })\\n})\\n\\ndescribe('contract', () => {\\n it('handles the documented Typeform payload against the documented Pipedrive responses', async () => {\\n const { fetch, calls } = contractFetch()\\n const result = await handle(SOURCE_EXAMPLE as unknown as TypeformWebhook, {\\n pipedriveApiToken: 'contract-token',\\n fieldRefs: { name: 'lead_name', email: 'lead_email' },\\n fetch,\\n })\\n expect(result.personId).toBeGreaterThan(0)\\n expect(result.dealId).toBeGreaterThan(0)\\n expect(calls.map((c) => c.url)).toEqual(['https://api.pipedrive.com/v1/persons', 'https://api.pipedrive.com/v1/deals'])\\n })\\n})\\n\"\n },\n {\n \"path\": \"README.md\",\n \"content\": \"# Typeform → Pipedrive connector\\n\\nTurns a Typeform `form_response` webhook into a Pipedrive organization, person and deal.\\n\\n## Configuration\\n\\n| Env var | Used as | Notes |\\n| --- | --- | --- |\\n| `PIPEDRIVE_API_TOKEN` | `pipedriveApiToken` | Personal API token, sent as the `x-api-token` header |\\n\\n`fieldRefs` maps your Typeform field refs to the lead fields. `name` and `email` are required; `company` and `phone` are optional.\\n\\n## Usage\\n\\n```ts\\nimport { handle } from './src/connector'\\n\\nexport async function POST(request: Request) {\\n const payload = await request.json()\\n const result = await handle(payload, {\\n pipedriveApiToken: process.env.PIPEDRIVE_API_TOKEN!,\\n fieldRefs: { name: 'lead_name', email: 'lead_email', company: 'lead_company', phone: 'lead_phone' },\\n dealTitlePrefix: 'Website lead',\\n })\\n return Response.json(result)\\n}\\n```\\n\\n## Behaviour\\n\\n1. Reads the answers by field ref, rejects the event when name or email is missing.\\n2. Creates an organization when a company was answered (`POST /v1/organizations`).\\n3. Creates the person with email and phone, linked to the organization (`POST /v1/persons`).\\n4. Creates a deal for the person (`POST /v1/deals`).\\n\\nAny non-2xx or `success: false` response throws with the status code and endpoint, so the webhook caller can retry.\\n\\n## Assumptions\\n\\n- Typeform webhook signature verification happens before `handle` is called.\\n- Every submission is a new lead; the connector does not search for existing persons.\\n\"\n },\n {\n \"path\": \"src/fixtures.ts\",\n \"content\": \"// Written by patchbay from the API documentation. Regenerated on every attempt, do not edit.\\n// Source: https://www.typeform.com/developers/webhooks/example-payload/\\n// Source: https://developers.pipedrive.com/docs/api/v1/Organizations\\n// Source: https://developers.pipedrive.com/docs/api/v1/Persons\\n// Source: https://developers.pipedrive.com/docs/api/v1/Deals\\n\\n/** Example payload of the source event, as documented. */\\nexport const SOURCE_EXAMPLE = {\\n \\\"event_id\\\": \\\"01H...\\\",\\n \\\"event_type\\\": \\\"form_response\\\",\\n \\\"form_response\\\": {\\n \\\"form_id\\\": \\\"lT4Z3j\\\",\\n \\\"token\\\": \\\"a3a12ec67a1365927098a606107fac15\\\",\\n \\\"submitted_at\\\": \\\"2026-10-01T09:00:00Z\\\",\\n \\\"answers\\\": [\\n {\\n \\\"type\\\": \\\"text\\\",\\n \\\"field\\\": {\\n \\\"id\\\": \\\"f1\\\",\\n \\\"ref\\\": \\\"lead_name\\\",\\n \\\"type\\\": \\\"short_text\\\"\\n },\\n \\\"text\\\": \\\"Ada Lovelace\\\"\\n },\\n {\\n \\\"type\\\": \\\"email\\\",\\n \\\"field\\\": {\\n \\\"id\\\": \\\"f2\\\",\\n \\\"ref\\\": \\\"lead_email\\\",\\n \\\"type\\\": \\\"email\\\"\\n },\\n \\\"email\\\": \\\"ada@example.com\\\"\\n }\\n ]\\n }\\n}\\n\\nexport interface DocumentedEndpoint {\\n method: string\\n /** As documented; may contain placeholders such as {id}, :id, <id> or a region host like usX. */\\n url: string\\n response: unknown\\n}\\n\\n/** Target endpoints the connector may call, in the documented order, with their documented responses. */\\nexport const TARGET_ENDPOINTS: DocumentedEndpoint[] = [\\n {\\n \\\"method\\\": \\\"POST\\\",\\n \\\"url\\\": \\\"https://api.pipedrive.com/v1/organizations\\\",\\n \\\"response\\\": {\\n \\\"success\\\": true,\\n \\\"data\\\": {\\n \\\"id\\\": 11\\n }\\n }\\n },\\n {\\n \\\"method\\\": \\\"POST\\\",\\n \\\"url\\\": \\\"https://api.pipedrive.com/v1/persons\\\",\\n \\\"response\\\": {\\n \\\"success\\\": true,\\n \\\"data\\\": {\\n \\\"id\\\": 22\\n }\\n }\\n },\\n {\\n \\\"method\\\": \\\"POST\\\",\\n \\\"url\\\": \\\"https://api.pipedrive.com/v1/deals\\\",\\n \\\"response\\\": {\\n \\\"success\\\": true,\\n \\\"data\\\": {\\n \\\"id\\\": 33\\n }\\n }\\n }\\n]\\n\\nexport interface RecordedCall {\\n method: string\\n url: string\\n /** The request body exactly as sent (usually a JSON string). */\\n body: string | undefined\\n /** The body parsed as JSON, or undefined when it is not JSON. */\\n json: unknown\\n headers: Headers\\n}\\n\\n/** The documented endpoint a request matches, placeholders and region subdomains included. */\\nexport function findEndpoint(method: string, url: string): DocumentedEndpoint | undefined {\\n return TARGET_ENDPOINTS.find((endpoint) => endpoint.method === method.toUpperCase() && urlMatches(endpoint.url, url))\\n}\\n\\n/**\\n * A fake fetch that answers every documented endpoint with its documented response and\\n * rejects anything else. Use it in the contract test:\\n *\\n * const { fetch, calls } = contractFetch()\\n * await handle(SOURCE_EXAMPLE as MyInput, { ...config, fetch })\\n * expect(calls.length).toBeGreaterThan(0)\\n */\\nexport function contractFetch(): { fetch: typeof fetch; calls: RecordedCall[] } {\\n return fakeFetch((request) => {\\n const endpoint = findEndpoint(request.method, request.url)\\n if (!endpoint) throw new Error(`contract: ${request.method} ${request.url} is not a documented endpoint`)\\n return jsonResponse(endpoint.response)\\n })\\n}\\n\\n/**\\n * A correctly typed fake fetch for every other test. The handler receives the recorded\\n * request: { method, url, body (string as sent), json (parsed body), headers (Headers) }.\\n *\\n * const { fetch, calls } = fakeFetch((req) => req.url.endsWith('/deals') ? jsonResponse({ id: 1 }, 201) : jsonResponse({}, 404))\\n */\\nexport function fakeFetch(\\n handler: (request: RecordedCall) => Response | Promise<Response>,\\n): { fetch: typeof fetch; calls: RecordedCall[] } {\\n const calls: RecordedCall[] = []\\n const fake = async (input: string | URL | Request, init: RequestInit = {}): Promise<Response> => {\\n const url = input instanceof Request ? input.url : String(input)\\n const method = (init.method ?? (input instanceof Request ? input.method : 'GET')).toUpperCase()\\n const body = typeof init.body === 'string' ? init.body : init.body == null ? undefined : String(init.body)\\n const call: RecordedCall = { method, url, body, json: parseJson(body), headers: new Headers(init.headers) }\\n calls.push(call)\\n return handler(call)\\n }\\n return { fetch: fake as typeof fetch, calls }\\n}\\n\\nconst STATUS_TEXT: Record<number, string> = {\\n 200: 'OK', 201: 'Created', 202: 'Accepted', 204: 'No Content',\\n 400: 'Bad Request', 401: 'Unauthorized', 403: 'Forbidden', 404: 'Not Found', 409: 'Conflict',\\n 422: 'Unprocessable Entity', 429: 'Too Many Requests',\\n 500: 'Internal Server Error', 502: 'Bad Gateway', 503: 'Service Unavailable',\\n}\\n\\n/** A JSON Response with the standard status text, e.g. jsonResponse({ error: 'nope' }, 401) -> \\\"401 Unauthorized\\\". */\\nexport function jsonResponse(body: unknown, status = 200): Response {\\n const init = { status, statusText: STATUS_TEXT[status] ?? '', headers: { 'Content-Type': 'application/json' } }\\n return new Response(status === 204 ? null : JSON.stringify(body), init)\\n}\\n\\nfunction parseJson(raw: string | undefined): unknown {\\n if (raw === undefined) return undefined\\n try {\\n return JSON.parse(raw)\\n } catch {\\n return undefined\\n }\\n}\\n\\nfunction urlMatches(template: string, actual: string): boolean {\\n const t = splitUrl(template)\\n const a = splitUrl(actual)\\n if (!t || !a) return false\\n const tHost = t.host.split('.')\\n const aHost = a.host.split('.')\\n if (tHost.slice(-2).join('.') !== aHost.slice(-2).join('.')) return false\\n const tPath = t.path.replace(/\\\\/+$/, '').split('/')\\n const aPath = a.path.replace(/\\\\/+$/, '').split('/')\\n if (tPath.length !== aPath.length) return false\\n return tPath.every((segment, i) => isPlaceholder(segment) || segment === aPath[i])\\n}\\n\\nfunction splitUrl(url: string): { host: string; path: string } | null {\\n const match = url.match(/^https?:\\\\/\\\\/([^/?#]+)([^?#]*)/i)\\n return match ? { host: (match[1] ?? '').toLowerCase(), path: match[2] || '/' } : null\\n}\\n\\nfunction isPlaceholder(segment: string): boolean {\\n return /^\\\\{[^}]+\\\\}$|^:[A-Za-z_]\\\\w*$|^<[^>]+>$/.test(segment)\\n}\\n\"\n }\n ],\n \"report\": {\n \"typecheckOk\": true,\n \"typecheckOutput\": \"\",\n \"passed\": 7,\n \"failed\": 0,\n \"total\": 7,\n \"failures\": [],\n \"durationMs\": 202.9775390625,\n \"ranOn\": \"replay\",\n \"passedNames\": [\n \"handle creates organization, person and deal with the mapped fields\",\n \"handle authenticates every call with the x-api-token header\",\n \"handle skips the organization when no company was answered\",\n \"handle rejects a response without an email answer\",\n \"handle surfaces Pipedrive errors with status and endpoint\",\n \"handle ignores events that are not form responses\",\n \"contract handles the documented Typeform payload against the documented Pipedrive responses\"\n ],\n \"contract\": \"passed\"\n }\n },\n {\n \"type\": \"step\",\n \"step\": \"package\",\n \"status\": \"done\"\n }\n ]\n}\n","import recorded from './fixtures/typeform-pipedrive/run.json'\nimport type { RunEvent } from './types'\n\nexport interface RecordedRun {\n prompt: string\n /** `fixture` for the bundled example, `live` for runs captured with `npm run agent -- --record`. */\n origin: 'fixture' | 'live'\n events: RunEvent[]\n}\n\nexport const REPLAY_RUN = recorded as RecordedRun\n\n/** Streams a recorded run with short pauses so the UI shows the same progression as a live run. */\nexport async function* replayRun(run: RecordedRun = REPLAY_RUN, pace = 1): AsyncGenerator<RunEvent> {\n yield { type: 'mode', mode: 'replay' }\n for (const event of run.events) {\n if (event.type === 'mode') continue\n await sleep(delayFor(event) * pace)\n yield event\n }\n}\n\nfunction delayFor(event: RunEvent): number {\n switch (event.type) {\n case 'step':\n return event.status === 'start' ? 250 : 700\n case 'files':\n return 1200\n case 'tests':\n return 1500\n default:\n return 180\n }\n}\n\nconst sleep = (ms: number) => (ms > 0 ? new Promise((resolve) => setTimeout(resolve, ms)) : Promise.resolve())\n","import type { ApiSpec, GeneratedFile, TestReport } from './types'\n\nexport const FIXTURES_PATH = 'src/fixtures.ts'\n\n/**\n * The model writes the connector and most of its tests, so those tests share its\n * assumptions. The contract fixtures break that loop: patchbay writes them from the\n * documentation the research step extracted, overwrites them on every attempt, and the\n * test suite must run the connector against them unchanged.\n *\n * Documented URLs are often templates (`https://usX.api.mailchimp.com/3.0/lists/{list_id}`),\n * so the file ships its own matcher and a ready-made fake fetch instead of asking the model\n * to compare URLs.\n */\nexport function renderFixtures(spec: ApiSpec): GeneratedFile {\n const endpoints = spec.target.map((target) => ({\n method: target.method.toUpperCase(),\n url: target.url,\n response: target.responseExample ?? {},\n }))\n const docs = [spec.source.docsUrl, ...spec.target.map((t) => t.docsUrl)].filter(Boolean)\n const content = `// Written by patchbay from the API documentation. Regenerated on every attempt, do not edit.\n${[...new Set(docs)].map((url) => `// Source: ${url}`).join('\\n')}\n\n/** Example payload of the source event, as documented. */\nexport const SOURCE_EXAMPLE = ${JSON.stringify(spec.source.example ?? {}, null, 2)}\n\nexport interface DocumentedEndpoint {\n method: string\n /** As documented; may contain placeholders such as {id}, :id, <id> or a region host like usX. */\n url: string\n response: unknown\n}\n\n/** Target endpoints the connector may call, in the documented order, with their documented responses. */\nexport const TARGET_ENDPOINTS: DocumentedEndpoint[] = ${JSON.stringify(endpoints, null, 2)}\n\nexport interface RecordedCall {\n method: string\n url: string\n /** The request body exactly as sent (usually a JSON string). */\n body: string | undefined\n /** The body parsed as JSON, or undefined when it is not JSON. */\n json: unknown\n headers: Headers\n}\n\n/** The documented endpoint a request matches, placeholders and region subdomains included. */\nexport function findEndpoint(method: string, url: string): DocumentedEndpoint | undefined {\n return TARGET_ENDPOINTS.find((endpoint) => endpoint.method === method.toUpperCase() && urlMatches(endpoint.url, url))\n}\n\n/**\n * A fake fetch that answers every documented endpoint with its documented response and\n * rejects anything else. Use it in the contract test:\n *\n * const { fetch, calls } = contractFetch()\n * await handle(SOURCE_EXAMPLE as MyInput, { ...config, fetch })\n * expect(calls.length).toBeGreaterThan(0)\n */\nexport function contractFetch(): { fetch: typeof fetch; calls: RecordedCall[] } {\n return fakeFetch((request) => {\n const endpoint = findEndpoint(request.method, request.url)\n if (!endpoint) throw new Error(\\`contract: \\${request.method} \\${request.url} is not a documented endpoint\\`)\n return jsonResponse(endpoint.response)\n })\n}\n\n/**\n * A correctly typed fake fetch for every other test. The handler receives the recorded\n * request: { method, url, body (string as sent), json (parsed body), headers (Headers) }.\n *\n * const { fetch, calls } = fakeFetch((req) => req.url.endsWith('/deals') ? jsonResponse({ id: 1 }, 201) : jsonResponse({}, 404))\n */\nexport function fakeFetch(\n handler: (request: RecordedCall) => Response | Promise<Response>,\n): { fetch: typeof fetch; calls: RecordedCall[] } {\n const calls: RecordedCall[] = []\n const fake = async (input: string | URL | Request, init: RequestInit = {}): Promise<Response> => {\n const url = input instanceof Request ? input.url : String(input)\n const method = (init.method ?? (input instanceof Request ? input.method : 'GET')).toUpperCase()\n const body = typeof init.body === 'string' ? init.body : init.body == null ? undefined : String(init.body)\n const call: RecordedCall = { method, url, body, json: parseJson(body), headers: new Headers(init.headers) }\n calls.push(call)\n return handler(call)\n }\n return { fetch: fake as typeof fetch, calls }\n}\n\nconst STATUS_TEXT: Record<number, string> = {\n 200: 'OK', 201: 'Created', 202: 'Accepted', 204: 'No Content',\n 400: 'Bad Request', 401: 'Unauthorized', 403: 'Forbidden', 404: 'Not Found', 409: 'Conflict',\n 422: 'Unprocessable Entity', 429: 'Too Many Requests',\n 500: 'Internal Server Error', 502: 'Bad Gateway', 503: 'Service Unavailable',\n}\n\n/** A JSON Response with the standard status text, e.g. jsonResponse({ error: 'nope' }, 401) -> \"401 Unauthorized\". */\nexport function jsonResponse(body: unknown, status = 200): Response {\n const init = { status, statusText: STATUS_TEXT[status] ?? '', headers: { 'Content-Type': 'application/json' } }\n return new Response(status === 204 ? null : JSON.stringify(body), init)\n}\n\nfunction parseJson(raw: string | undefined): unknown {\n if (raw === undefined) return undefined\n try {\n return JSON.parse(raw)\n } catch {\n return undefined\n }\n}\n\nfunction urlMatches(template: string, actual: string): boolean {\n const t = splitUrl(template)\n const a = splitUrl(actual)\n if (!t || !a) return false\n const tHost = t.host.split('.')\n const aHost = a.host.split('.')\n if (tHost.slice(-2).join('.') !== aHost.slice(-2).join('.')) return false\n const tPath = t.path.replace(/\\\\/+$/, '').split('/')\n const aPath = a.path.replace(/\\\\/+$/, '').split('/')\n if (tPath.length !== aPath.length) return false\n return tPath.every((segment, i) => isPlaceholder(segment) || segment === aPath[i])\n}\n\nfunction splitUrl(url: string): { host: string; path: string } | null {\n const match = url.match(/^https?:\\\\/\\\\/([^/?#]+)([^?#]*)/i)\n return match ? { host: (match[1] ?? '').toLowerCase(), path: match[2] || '/' } : null\n}\n\nfunction isPlaceholder(segment: string): boolean {\n return /^\\\\{[^}]+\\\\}$|^:[A-Za-z_]\\\\w*$|^<[^>]+>$/.test(segment)\n}\n`\n return { path: FIXTURES_PATH, content }\n}\n\nexport type ContractStatus = NonNullable<TestReport['contract']>\n\n/** Static half of the contract check: the suite must actually use the fixtures. */\nexport function contractMissing(files: GeneratedFile[]): string | null {\n const tests = files.find((f) => f.path === 'src/connector.test.ts')?.content ?? ''\n if (!/from\\s+['\"]\\.\\/fixtures['\"]/.test(tests)) {\n return 'src/connector.test.ts does not import SOURCE_EXAMPLE and contractFetch from ./fixtures'\n }\n if (!/describe\\(\\s*['\"`]contract/.test(tests)) {\n return 'src/connector.test.ts has no describe(\"contract\", ...) block running handle on SOURCE_EXAMPLE'\n }\n if (!tests.includes('SOURCE_EXAMPLE')) {\n return 'the contract tests never pass SOURCE_EXAMPLE to handle'\n }\n return null\n}\n\n/** Folds the static check and the contract test results into the report. */\nexport function withContract(report: TestReport, files: GeneratedFile[]): TestReport {\n const missing = contractMissing(files)\n if (missing) {\n return {\n ...report,\n contract: 'missing',\n failed: report.failed + 1,\n total: report.total + 1,\n failures: [...report.failures, { name: 'contract (static check)', message: missing }],\n }\n }\n // Vitest's fullName joins every surrounding describe title with a space, so a nested\n // describe('contract', ...) inside describe('connector', ...) shows up as\n // \"connector contract handles the documented example payload\". A word-boundary match\n // catches that as well as top-level contract blocks.\n const failed = report.failures.some((f) => /\\bcontract\\b/i.test(f.name))\n if (failed) return { ...report, contract: 'failed' }\n const ran = (report.passedNames ?? []).some((name) => /\\bcontract\\b/i.test(name))\n if (!ran) {\n return {\n ...report,\n contract: 'failed',\n failed: report.failed + 1,\n total: report.total + 1,\n failures: [\n ...report.failures,\n { name: 'contract (did not run)', message: 'The contract test never passed; the test file probably failed to load.' },\n ],\n }\n }\n return { ...report, contract: 'passed' }\n}\n\n/** Keeps the model's files and puts the authoritative fixtures next to them. */\nexport function withFixtures(files: GeneratedFile[], fixtures: GeneratedFile): GeneratedFile[] {\n return [...files.filter((f) => f.path !== FIXTURES_PATH), fixtures]\n}\n","import { transform } from 'esbuild'\nimport type { GeneratedFile, TestReport } from './types'\n\n/**\n * The strong model occasionally produces TypeScript that fails to parse: a stray paren,\n * an unterminated string, a misplaced comma. The sandbox catches it, but burns 15-30s\n * on the fork and a whole repair attempt. Running an esbuild parse here first catches\n * the same class of error offline in milliseconds and returns a report shaped like a\n * sandbox failure, so the repair loop reacts to it the same way.\n *\n * Returns null when every .ts file parses cleanly; otherwise a synthetic TestReport\n * the loop can treat as a failed attempt.\n */\nexport async function preflightSyntax(files: GeneratedFile[]): Promise<TestReport | null> {\n const tsFiles = files.filter((f) => f.path.endsWith('.ts'))\n const failures: { file: string; message: string; line?: number }[] = []\n await Promise.all(\n tsFiles.map(async (f) => {\n try {\n await transform(f.content, {\n loader: 'ts',\n sourcefile: f.path,\n sourcemap: false,\n target: 'es2022',\n })\n } catch (error) {\n const errs = (error as { errors?: { text?: string; location?: { line?: number; column?: number } }[] }).errors ?? []\n for (const e of errs) {\n failures.push({\n file: f.path,\n line: e.location?.line,\n message: e.text ? `${e.text}${e.location ? ` at ${f.path}:${e.location.line}:${e.location.column ?? 0}` : ''}` : String(error),\n })\n }\n if (!errs.length) failures.push({ file: f.path, message: error instanceof Error ? error.message : String(error) })\n }\n }),\n )\n if (failures.length === 0) return null\n\n return {\n typecheckOk: false,\n typecheckOutput: failures.map((f) => `${f.file}: ${f.message}`).join('\\n'),\n passed: 0,\n failed: failures.length,\n total: failures.length,\n failures: failures.map((f) => ({\n name: `syntax (${f.file}${f.line ? `:${f.line}` : ''})`,\n message: f.message,\n })),\n durationMs: 0,\n ranOn: 'preflight:esbuild',\n passedNames: [],\n }\n}\n","import type { ApiSpec, Plan, TestReport } from './types'\n\nexport const PLAN_SYSTEM = `You are the planning step of patchbay, an agent that builds API integrations.\nTurn the user's request into a precise integration plan. Answer with a single JSON object and nothing else:\n{\n \"summary\": string, // one sentence describing this specific integration\n \"source\": { \"app\": string, \"trigger\": string, \"docsQuery\": string },\n \"target\": { \"app\": string, \"action\": string, \"docsQuery\": string },\n \"additionalTargets\"?: [ { \"app\": string, \"action\": string, \"docsQuery\": string } ],\n \"fieldMapping\": [ { \"from\": string, \"to\": string, \"note\"?: string } ],\n \"assumptions\": [ string ] // concrete assumptions you made about this request\n}\nThe source is where data comes from (usually a webhook payload), the \"target\" is the PRIMARY API the connector calls.\nUse \"additionalTargets\" when the request calls two or more distinct external services in sequence — for example\n\"refresh an OAuth token at Google then write to Google Sheets\" (additionalTargets: Google OAuth), or\n\"open a GitHub issue then post a comment back on the Zendesk ticket\" (additionalTargets: Zendesk comment),\nor \"find a HubSpot engagement, delete it, log to Google Sheets\" (additionalTargets: Google Sheets). List them\nin the order they are called. Do NOT split one app into multiple entries — a single app with several endpoints\nstays under its primary target or additionalTarget entry and the endpoints come out of research.\ndocsQuery values are web search queries that find the official API reference for exactly that endpoint.\nList every field the user's request implies in fieldMapping, using the real field names of both APIs.\n\nExample of the shape (for a different request, do not copy its content):\n{\"summary\":\"When a Shopify order is paid, append a row with the order number, customer email and total to an Airtable table.\",\n \"source\":{\"app\":\"Shopify\",\"trigger\":\"orders/paid webhook\",\"docsQuery\":\"Shopify orders/paid webhook payload order fields\"},\n \"target\":{\"app\":\"Airtable\",\"action\":\"create record\",\"docsQuery\":\"Airtable Web API create records request body personal access token\"},\n \"fieldMapping\":[{\"from\":\"name\",\"to\":\"fields['Order']\"},{\"from\":\"email\",\"to\":\"fields['Email']\"},{\"from\":\"total_price\",\"to\":\"fields['Total']\",\"note\":\"string in the payload, number in Airtable\"}],\n \"assumptions\":[\"The Airtable table already has the columns Order, Email and Total.\"]}\n\nChained-flow example (two distinct target services):\n{\"summary\":\"When a Zendesk ticket is created, open a GitHub issue and post the issue URL back as a Zendesk ticket comment.\",\n \"source\":{\"app\":\"Zendesk\",\"trigger\":\"ticket.created webhook\",\"docsQuery\":\"Zendesk ticket webhook payload fields\"},\n \"target\":{\"app\":\"GitHub\",\"action\":\"create issue\",\"docsQuery\":\"GitHub REST API create an issue repo owner title body\"},\n \"additionalTargets\":[{\"app\":\"Zendesk\",\"action\":\"add ticket comment\",\"docsQuery\":\"Zendesk API add comment to ticket request body\"}],\n \"fieldMapping\":[{\"from\":\"ticket.subject\",\"to\":\"issue.title\"},{\"from\":\"ticket.description\",\"to\":\"issue.body\"},{\"from\":\"issue.html_url\",\"to\":\"comment.body\",\"note\":\"after the GitHub issue is created, write its URL into a Zendesk ticket comment\"}],\n \"assumptions\":[\"The Zendesk account has a webhook configured for ticket.created.\"]}`\n\nexport const SPEC_SYSTEM = `You are the research step of patchbay. You receive a plan and raw text of API documentation pages.\nExtract the concrete endpoint facts the connector needs. Only state what the docs support; if something is not in the docs, add a note instead of guessing.\nWhen plan.additionalTargets is set, the connector talks to MORE THAN ONE target service in sequence —\nlist every call in spec.target[] in call order (primary target first, then additionalTargets in the order\ngiven), each with its own \"app\" field. The contract test runs the connector against the SOURCE_EXAMPLE and\nevery documented endpoint must either be called or clearly optional, so do not include an endpoint the\nconnector will not actually hit.\nAnswer with a single JSON object:\n{\n \"source\": {\n \"app\": \"...\", \"role\": \"source\", \"method\": \"POST\", \"url\": \"(where the webhook is delivered, or the polling URL)\",\n \"auth\": { \"type\": \"none|header|bearer|query|basic\", \"name\": \"header or query name if any\", \"envVar\": \"SCREAMING_SNAKE env var name\" },\n \"example\": { \"a realistic example payload with the fields the plan maps\" },\n \"docsUrl\": \"https://...\", \"notes\": [\"pitfalls, required fields, formats\"]\n },\n \"target\": [\n { \"app\": \"...\", \"role\": \"target\", \"method\": \"POST\", \"url\": \"https://full endpoint url\",\n \"auth\": { \"type\": \"...\", \"name\": \"...\", \"envVar\": \"...\" },\n \"example\": { \"minimal valid request body\" }, \"responseExample\": { \"the part of the response the connector needs\" },\n \"docsUrl\": \"https://...\", \"notes\": [\"...\"] }\n ]\n}\nList target endpoints in the order the connector must call them.\n\nWhen any endpoint is documented as paginated (cursor, offset, page, has_more, next_url,\nnext_page_token, \"endCursor\"), capture the pagination mechanism in notes[] on that endpoint\nso the connector follows it correctly, e.g. \"paginate with ?after=cursor; stop when\nresponse.pagination.next is null\".\n\nURL path templates: when the docs describe the endpoint with placeholders — numeric ids,\nUUIDs, slugs, external-id upserts, composite keys — write the full documented template as\nthe \"url\" value, keeping the placeholder syntax from the docs. Examples:\n\n \"https://api.hubspot.com/crm/v3/objects/contacts/{contactId}\"\n \"https://na1.salesforce.com/services/data/v60.0/sobjects/Account/Website__c/{website}\"\n \"https://api.notion.com/v1/pages/{page_id}\"\n \"https://api.linear.app/graphql\" (single POST, variables carry the id)\n\nDo NOT substitute a sample value into the url (so no acme.com in the Salesforce example,\nno abc123 in the HubSpot example). The connector constructs the final URL from the input\npayload at runtime; the spec URL stays the template so the contract check accepts both\nthe documented endpoint and the generated call.\n\nFor upsert / idempotent-create endpoints (Salesforce external-id upsert via PATCH,\nStripe Idempotency-Key, HubSpot updateOrCreate), add a note describing which header or\nURL segment carries the idempotency token so the connector sends it correctly.`\n\nexport const GENERATE_SYSTEM = `You are the code-generation step of patchbay. Write a production-quality TypeScript connector and its tests.\n\nHard rules:\n- Exactly three files: src/connector.ts, src/connector.test.ts, README.md. Output each as\n <file path=\"src/connector.ts\">\n ...code...\n </file>\n with no markdown fences and no prose outside the file blocks.\n- No runtime dependencies. Use the global fetch, but ALWAYS accept an injected \\`fetch\\` in the config so tests can pass a fake.\n- Secrets come from the config object, never hard-coded. Document the env var names from the spec in the README.\n- src/connector.ts exports: a \\`ConnectorConfig\\` interface, a typed input type for the source payload, and one async\n entry function named \\`handle\\` that takes (payload, config) and returns a typed result with the created ids.\n- Validate the input: throw a descriptive Error when a required field is missing.\n- Non-2xx responses from the target must throw an Error that includes the status code and the endpoint.\n- Follow the spec exactly for URLs, HTTP methods, auth header/query names and body shapes.\n- src/connector.test.ts uses vitest (\\`import { describe, it, expect, vi } from 'vitest'\\`) and a fake fetch that records calls.\n Cover at least: happy path with the exact request bodies, the auth mechanism, the field mapping, a missing required field,\n and a non-2xx target response. Tests must be hermetic: no network, no timers, no real env vars.\n- src/fixtures.ts is provided by patchbay, read-only, do not output it. It exports SOURCE_EXAMPLE (the documented\n source payload), TARGET_ENDPOINTS and contractFetch(), a fake fetch that answers documented endpoints (URL\n placeholders like {id} or region hosts are handled) and throws on anything else.\n src/connector.test.ts MUST contain this block, adapted to your types and config. Put it at\n the TOP LEVEL of the test file — not nested inside another describe — and keep the title\n exactly 'contract' so patchbay can detect it:\n describe('contract', () => {\n it('handles the documented example payload', async () => {\n const { fetch, calls } = contractFetch()\n const result = await handle(SOURCE_EXAMPLE as unknown as <your input type>, { <a valid config object>, fetch })\n expect(calls.length).toBeGreaterThan(0)\n })\n })\n Configure the connector in that test so the documented example is valid input. If the example lacks a field the\n connector needs, make the connector handle that case (skip, fallback or clear error) rather than editing the example.\n- Do NOT reject SOURCE_EXAMPLE based on wall-clock time. If the connector guards against\n stale webhooks (timestamp age, signature expiry, nonce window), either freeze time in the\n contract test with vi.useFakeTimers() + vi.setSystemTime(new Date(<a date compatible with\n SOURCE_EXAMPLE's timestamps>)), or make the guard window large enough that the documented\n example always validates. The contract test must never fail with \"timestamp too old\".\n- RETRY SEMANTICS. \"Retry up to N times\" means at most N retry attempts after the initial\n request, so total HTTP calls are at most N+1. On a 429 (or other retryable status), compute\n the next delay as delay = Math.max(parseRetryAfter(res), baseMs * 2 ** retryIndex) where\n retryIndex starts at 0 for the first retry. Retry-After may be an integer in seconds OR an\n HTTP-date string — handle both and fall back to pure exponential backoff when the header is\n absent, malformed, or parses as NaN. Never call setTimeout(NaN). Tests will assert the mock\n fetch is called exactly (successfulAttempt + 1) times on success and exactly (N + 1) times\n on exhaustion; the loop must match this count exactly.\n- CURSOR PAGINATION. Terminate pagination loops on the API's explicit end signal — for\n GraphQL (Linear, Shopify GraphQL, GitHub v4) check pageInfo.hasNextPage === false, for REST\n check the absence or null of the cursor field (next_cursor, after, starting_after, page_info).\n Never loop while \"cursor is truthy\" alone — many APIs return an empty-string or placeholder\n cursor on the final page. Pass the cursor under the exact field name the vendor documents\n (after for Linear, starting_after for Intercom and Stripe, page_info for Shopify REST).\n Hard-cap every pagination loop at 50 iterations as a safety net against runaway loops.\n- For every other test use fakeFetch and jsonResponse from './fixtures' instead of writing your own fetch mock:\n const { fetch, calls } = fakeFetch((req) => req.url.endsWith('/deals') ? jsonResponse({ id: 2 }, 201) : jsonResponse({ error: 'x' }, 500))\n Each recorded call is { method, url, body (the string as sent), json (the parsed body), headers (a Headers object,\n use headers.get('authorization')) }. Assert on calls[i].json, do not JSON.parse it again. jsonResponse(body, status)\n sets the standard status text (401 -> 'Unauthorized'). Never declare a fetch type yourself.\n- TypeScript strict mode must pass. Import from './connector' and './fixtures' without an extension.\n- README.md: what it does, config/env vars, a usage example, and the assumptions from the plan.`\n\nexport function planUser(prompt: string): string {\n return `Request: ${prompt}`\n}\n\nexport function specUser(plan: Plan, docs: { url: string; content: string }[]): string {\n const pages = docs\n .map((d) => `=== ${d.url} ===\\n${d.content.slice(0, 14_000)}`)\n .join('\\n\\n')\n return `Plan:\\n${JSON.stringify(plan, null, 2)}\\n\\nDocumentation pages:\\n${pages}`\n}\n\nexport function generateUser(plan: Plan, spec: ApiSpec, fixtures: string): string {\n return `Plan:\\n${JSON.stringify(plan, null, 2)}\\n\\nAPI spec:\\n${JSON.stringify(spec, null, 2)}\\n\\nsrc/fixtures.ts (provided by patchbay, read-only):\\n${fixtures}\\n\\nWrite the three files now.`\n}\n\nexport interface RepairContext {\n /** 1-based: the attempt we are producing the fix FOR (so the repair output will be verified as this attempt). */\n attempt: number\n /** The absolute cap; the agent gives up after this many attempts. */\n maxAttempts: number\n /** Short lines describing what previous attempts tried and still failed on. Chronological. */\n previousAttempts?: Array<{ attempt: number; summary: string }>\n}\n\nexport function repairUser(filesBlock: string, report: TestReport, context?: RepairContext): string {\n const tsc = report.typecheckOk ? 'Typecheck passed.' : `Typecheck failed:\\n${report.typecheckOutput.slice(0, 4000)}`\n const failures = report.failures.map((f) => `- ${f.name}\\n${f.message}`).join('\\n\\n')\n const header = context\n ? `This is repair attempt ${context.attempt} of ${context.maxAttempts}. Produce something materially different from the earlier attempts${context.previousAttempts?.length ? ' listed below' : ''}.`\n : ''\n const history = context?.previousAttempts?.length\n ? `\\nPrevious attempts:\\n${context.previousAttempts.map((a) => ` attempt ${a.attempt}: ${a.summary}`).join('\\n')}\\n`\n : ''\n return `These files were run in an isolated sandbox (tsc --noEmit, then vitest).\n${header ? `\\n${header}\\n` : ''}\n${tsc}\n\nTests: ${report.passed} passed, ${report.failed} failed of ${report.total}.\n${failures ? `Failures:\\n${failures}` : ''}\n${history}\nCurrent files:\n${filesBlock}\n\nFix the code so everything passes. Fix the connector when it contradicts the spec; fix a test only when the test itself is wrong.\nReturn all three files again in full, using the same <file path=\"...\"> format.`\n}\n","import type { SearchHit } from './tavily'\n\nconst THIRD_PARTY = [\n 'medium.com',\n 'dev.to',\n 'stackoverflow.com',\n 'reddit.com',\n 'youtube.com',\n 'github.com',\n 'endgrate.com',\n 'cotera.co',\n 'zapier.com',\n 'make.com',\n 'n8n.io',\n 'pipedream.com',\n 'rollout.com',\n 'apidog.com',\n 'postman.com',\n]\n\nconst DOC_PATH = /\\/(docs?|developers?|reference|api)(\\/|$|-)/i\n\n/**\n * Tavily ranks by relevance, not authority, so an integration blog can outrank the vendor's\n * own reference. Official pages are the ones whose host names the app and whose path looks\n * like documentation; aggregators and forums are pushed down.\n */\nexport function rankOfficial(hits: SearchHit[], app: string): SearchHit[] {\n const slug = app.toLowerCase().replace(/[^a-z0-9]/g, '')\n const score = (hit: SearchHit) => {\n let host = ''\n let path = ''\n try {\n const url = new URL(hit.url)\n host = url.hostname.toLowerCase()\n path = url.pathname\n } catch {\n return hit.score - 1\n }\n const official = slug.length > 2 && host.replace(/[^a-z0-9.]/g, '').replace(/\\./g, '').includes(slug)\n const thirdParty = THIRD_PARTY.some((domain) => host === domain || host.endsWith(`.${domain}`))\n return hit.score + (official ? 1 : 0) + (official && DOC_PATH.test(path) ? 0.5 : 0) - (thirdParty ? 1 : 0)\n }\n return [...hits].sort((a, b) => score(b) - score(a))\n}\n\nexport function isOfficial(url: string, app: string): boolean {\n const slug = app.toLowerCase().replace(/[^a-z0-9]/g, '')\n try {\n return new URL(url).hostname.toLowerCase().replace(/[^a-z0-9]/g, '').includes(slug)\n } catch {\n return false\n }\n}\n","import type { AgentConfig } from './config'\nimport { renderFixtures, withContract, withFixtures } from './contract'\nimport { preflightSyntax } from './syntax-check'\nimport type { LlmClient } from './llm'\nimport { extractJson, parseFileBlocks, renderFileBlocks } from './parse'\nimport {\n GENERATE_SYSTEM,\n PLAN_SYSTEM,\n SPEC_SYSTEM,\n generateUser,\n planUser,\n repairUser,\n specUser,\n type RepairContext,\n} from './prompts'\nimport { isGreen } from './report'\nimport type { SandboxRunner } from './sandbox'\nimport { isOfficial, rankOfficial } from './sources'\nimport type { SearchClient } from './tavily'\nimport type { ApiSpec, GeneratedFile, Plan, RunEvent, Source, StepId, TestReport } from './types'\n\nexport interface AgentDeps {\n config: AgentConfig\n llm: LlmClient\n search: SearchClient\n sandbox: SandboxRunner\n}\n\nconst REQUIRED_FILES = ['src/connector.ts', 'src/connector.test.ts', 'README.md']\n\n/**\n * plan (fast model) → research (Tavily + mid model) → generate (strong model)\n * → verify in a Nebius sandbox → repair with the failures, up to maxAttempts.\n */\nexport async function* runAgent(prompt: string, deps: AgentDeps): AsyncGenerator<RunEvent> {\n const { config, llm, search, sandbox } = deps\n const queue: RunEvent[] = []\n const log = (step: StepId) => (message: string) => queue.push({ type: 'log', step, message })\n const drain = function* () {\n while (queue.length) yield queue.shift() as RunEvent\n }\n\n yield { type: 'mode', mode: 'live' }\n let current: StepId = 'plan'\n try {\n yield { type: 'step', step: 'plan', status: 'start' }\n const plan = await makePlan(prompt, llm, config)\n yield { type: 'plan', plan }\n yield { type: 'step', step: 'plan', status: 'done', detail: plan.summary }\n\n current = 'research'\n yield { type: 'step', step: 'research', status: 'start' }\n const prepared = sandbox.prepare(log('verify')).catch((error: unknown) => error as Error)\n const { spec, sources } = await research(plan, search, llm, config, log('research'))\n yield* drain()\n yield { type: 'sources', sources }\n yield { type: 'spec', spec }\n yield { type: 'step', step: 'research', status: 'done', detail: `${spec.target.length + 1} endpoints from ${sources.length} pages` }\n\n current = 'generate'\n yield { type: 'step', step: 'generate', status: 'start' }\n const fixtures = renderFixtures(spec)\n let files = withFixtures(await generate(plan, spec, fixtures.content, llm, config), fixtures)\n yield { type: 'files', attempt: 1, files }\n yield { type: 'step', step: 'generate', status: 'done', detail: files.map((f) => f.path).join(', ') }\n\n current = 'verify'\n yield { type: 'step', step: 'verify', status: 'start' }\n const baseImage = await prepared\n yield* drain()\n if (baseImage instanceof Error) throw baseImage\n\n let report: TestReport | null = null\n let bestFiles = files\n let bestReport: TestReport | null = null\n let attempt = 1\n let skipInitialTest = false\n const history: Array<{ attempt: number; summary: string }> = []\n for (;;) {\n if (!skipInitialTest) {\n const preflight = await preflightSyntax(files)\n if (preflight) {\n report = withContract(preflight, files)\n queue.push({ type: 'log', step: 'verify', message: `Preflight parse failed (${preflight.failed} file${preflight.failed > 1 ? 's' : ''}), skipping sandbox` })\n } else {\n report = withContract(await sandbox.runTests(baseImage, files, log('verify')), files)\n }\n yield* drain()\n yield { type: 'tests', attempt, report: report! }\n }\n skipInitialTest = false\n ;({ files, report, bestFiles, bestReport } = keepBest({ attempt, files, report: report!, bestFiles, bestReport, log: (m) => queue.push({ type: 'log', step: 'verify', message: m }) }))\n yield* drain()\n if (isGreen(report) || attempt >= config.maxAttempts) break\n history.push({ attempt, summary: summariseReport(report) })\n attempt++\n yield { type: 'log', step: 'verify', message: `Attempt ${attempt - 1} failed (${report.failed} tests, typecheck ${report.typecheckOk ? 'ok' : 'failed'}), repairing` }\n const repairCtx: RepairContext = { attempt, maxAttempts: config.maxAttempts, previousAttempts: history.slice() }\n if (config.parallelRepairs > 1) {\n const r = await repairParallel(files, report, {\n llm, sandbox, config, baseImage,\n withFixtures: (next) => withFixtures(next, fixtures),\n context: repairCtx,\n }, log('verify'))\n yield* drain()\n files = r.files\n report = r.report\n yield { type: 'files', attempt, files }\n yield { type: 'tests', attempt, report, branches: r.branches }\n skipInitialTest = true\n } else {\n files = withFixtures(await repair(files, report, llm, config, { context: repairCtx }), fixtures)\n yield { type: 'files', attempt, files }\n }\n }\n // Hand the caller the best attempt, not necessarily the last one.\n files = bestFiles\n report = bestReport ?? report\n const ok = report !== null && isGreen(report)\n yield { type: 'step', step: 'verify', status: ok ? 'done' : 'error', detail: `${report!.passed}/${report!.total} tests after ${attempt} attempt${attempt > 1 ? 's' : ''}` }\n\n current = 'package'\n yield { type: 'step', step: 'package', status: 'start' }\n yield { type: 'usage', usage: llm.usage() }\n yield { type: 'result', ok, attempts: attempt, files, report }\n yield { type: 'step', step: 'package', status: 'done' }\n } catch (error) {\n yield* drain()\n yield { type: 'step', step: current, status: 'error', detail: messageOf(error) }\n yield { type: 'usage', usage: llm.usage() }\n yield { type: 'error', message: messageOf(error) }\n }\n}\n\n/** plan → research only, ends with the spec. No code generation, no sandbox. */\nexport async function* researchAgent(prompt: string, deps: Omit<AgentDeps, 'sandbox'>): AsyncGenerator<RunEvent> {\n const { config, llm, search } = deps\n yield { type: 'mode', mode: 'live' }\n let current: StepId = 'plan'\n try {\n yield { type: 'step', step: 'plan', status: 'start' }\n const plan = await makePlan(prompt, llm, config)\n yield { type: 'plan', plan }\n yield { type: 'step', step: 'plan', status: 'done', detail: plan.summary }\n\n current = 'research'\n yield { type: 'step', step: 'research', status: 'start' }\n const queue: RunEvent[] = []\n const { spec, sources } = await research(plan, search, llm, config, (m) =>\n queue.push({ type: 'log', step: 'research', message: m }),\n )\n while (queue.length) yield queue.shift() as RunEvent\n yield { type: 'sources', sources }\n yield { type: 'spec', spec }\n yield { type: 'step', step: 'research', status: 'done', detail: `${spec.target.length + 1} endpoints from ${sources.length} pages` }\n yield { type: 'usage', usage: llm.usage() }\n } catch (error) {\n yield { type: 'step', step: current, status: 'error', detail: messageOf(error) }\n yield { type: 'usage', usage: llm.usage() }\n yield { type: 'error', message: messageOf(error) }\n }\n}\n\n/** verify + repair loop for already-generated files. Uses sandbox + strong model. */\nexport async function* verifyAgent(\n files: GeneratedFile[],\n deps: Omit<AgentDeps, 'search'>,\n): AsyncGenerator<RunEvent> {\n const { config, llm, sandbox } = deps\n yield { type: 'mode', mode: 'live' }\n const queue: RunEvent[] = []\n const log = (message: string) => queue.push({ type: 'log', step: 'verify', message })\n const drain = function* () {\n while (queue.length) yield queue.shift() as RunEvent\n }\n\n try {\n yield { type: 'step', step: 'verify', status: 'start' }\n const baseImage = await sandbox.prepare(log)\n yield* drain()\n\n let current = files\n let report: TestReport | null = null\n let bestFiles = current\n let bestReport: TestReport | null = null\n let attempt = 1\n let skipInitialTest = false\n const history: Array<{ attempt: number; summary: string }> = []\n for (;;) {\n if (!skipInitialTest) {\n const preflight = await preflightSyntax(current)\n if (preflight) {\n report = preflight\n queue.push({ type: 'log', step: 'verify', message: `Preflight parse failed (${preflight.failed} file${preflight.failed > 1 ? 's' : ''}), skipping sandbox` })\n } else {\n report = await sandbox.runTests(baseImage, current, log)\n }\n yield* drain()\n yield { type: 'tests', attempt, report: report! }\n }\n skipInitialTest = false\n ;({ files: current, report, bestFiles, bestReport } = keepBest({ attempt, files: current, report: report!, bestFiles, bestReport, log: (m) => queue.push({ type: 'log', step: 'verify', message: m }) }))\n yield* drain()\n if (isGreen(report) || attempt >= config.maxAttempts) break\n history.push({ attempt, summary: summariseReport(report) })\n attempt++\n yield { type: 'log', step: 'verify', message: `Attempt ${attempt - 1} failed (${report.failed} tests, typecheck ${report.typecheckOk ? 'ok' : 'failed'}), repairing` }\n const repairCtx: RepairContext = { attempt, maxAttempts: config.maxAttempts, previousAttempts: history.slice() }\n if (config.parallelRepairs > 1) {\n const r = await repairParallel(current, report, {\n llm, sandbox, config, baseImage,\n withFixtures: (next) => next,\n context: repairCtx,\n }, log)\n yield* drain()\n current = r.files\n report = r.report\n yield { type: 'files', attempt, files: current }\n yield { type: 'tests', attempt, report, branches: r.branches }\n skipInitialTest = true\n } else {\n current = await repair(current, report, llm, config, { context: repairCtx })\n yield { type: 'files', attempt, files: current }\n }\n }\n current = bestFiles\n report = bestReport ?? report\n const ok = report !== null && isGreen(report)\n yield { type: 'step', step: 'verify', status: ok ? 'done' : 'error', detail: `${report!.passed}/${report!.total} tests after ${attempt} attempt${attempt > 1 ? 's' : ''}` }\n yield { type: 'usage', usage: llm.usage() }\n yield { type: 'result', ok, attempts: attempt, files: current, report }\n } catch (error) {\n yield* drain()\n yield { type: 'step', step: 'verify', status: 'error', detail: messageOf(error) }\n yield { type: 'usage', usage: llm.usage() }\n yield { type: 'error', message: messageOf(error) }\n }\n}\n\nexport async function makePlan(prompt: string, llm: LlmClient, config: AgentConfig): Promise<Plan> {\n const answer = await llm.chat(config.models.fast, [\n { role: 'system', content: PLAN_SYSTEM },\n { role: 'user', content: planUser(prompt) },\n ], { thinking: false, maxTokens: 2000 })\n const plan = await parseJsonOrAsk<Plan>(answer, llm, config.models.fast, PLAN_SYSTEM)\n if (!plan.source?.app || !plan.target?.app) throw new Error('Could not identify a source and a target app in the request')\n plan.fieldMapping ??= []\n plan.assumptions ??= []\n return plan\n}\n\nexport async function research(\n plan: Plan,\n search: SearchClient,\n llm: LlmClient,\n config: AgentConfig,\n log: (m: string) => void,\n): Promise<{ spec: ApiSpec; sources: Source[] }> {\n // Source + primary target + any additional target services (chained flows).\n // Each gets its own search so research covers every API the connector will call.\n const sides = [plan.source, plan.target, ...(plan.additionalTargets ?? [])]\n const hits = await Promise.all(\n sides.map(async (side) => {\n let list = await search.search(side.docsQuery, { maxResults: 8 })\n if (!list.some((h) => isOfficial(h.url, side.app))) {\n const domain = guessDomain(side.app)\n const focused = await search.search(side.docsQuery, { maxResults: 5, includeDomains: [domain] })\n log(`No ${side.app} page in the results, searched ${domain} directly: ${focused.length} results`)\n list = [...focused, ...list]\n }\n const ranked = rankOfficial(list, side.app).slice(0, 2)\n const official = ranked.filter((h) => isOfficial(h.url, side.app)).length\n log(`Searched \"${side.docsQuery}\": ${official} of 2 picked from ${side.app}'s own docs`)\n return ranked.map((h) => ({ ...h, app: side.app }))\n }),\n )\n const picked = hits.flat()\n const urls = [...new Set(picked.map((h) => h.url))]\n const pages = await search.extract(urls)\n log(`Extracted ${pages.length} documentation pages`)\n const docs = pages.length ? pages : picked.map((h) => ({ url: h.url, content: h.content }))\n\n const answer = await llm.chat(config.models.mid, [\n { role: 'system', content: SPEC_SYSTEM },\n { role: 'user', content: specUser(plan, docs) },\n ], { thinking: false, maxTokens: 6000 })\n const spec = await parseJsonOrAsk<ApiSpec>(answer, llm, config.models.mid, SPEC_SYSTEM)\n if (!spec.source || !Array.isArray(spec.target) || spec.target.length === 0) {\n throw new Error('Research did not produce a usable API spec')\n }\n return { spec, sources: picked.map((h) => ({ title: h.title, url: h.url, official: isOfficial(h.url, h.app) })) }\n}\n\nexport async function generate(plan: Plan, spec: ApiSpec, fixtures: string, llm: LlmClient, config: AgentConfig): Promise<GeneratedFile[]> {\n const answer = await llm.chat(config.models.strong, [\n { role: 'system', content: GENERATE_SYSTEM },\n { role: 'user', content: generateUser(plan, spec, fixtures) },\n ], { maxTokens: 32_000, temperature: 0.1 })\n return requireFiles(parseFileBlocks(answer))\n}\n\nexport async function repair(\n files: GeneratedFile[],\n report: TestReport,\n llm: LlmClient,\n config: AgentConfig,\n options: { temperature?: number; context?: RepairContext } = {},\n): Promise<GeneratedFile[]> {\n const answer = await llm.chat(config.models.strong, [\n { role: 'system', content: GENERATE_SYSTEM },\n { role: 'user', content: repairUser(renderFileBlocks(files), report, options.context) },\n ], { maxTokens: 32_000, temperature: options.temperature ?? 0.1 })\n const repaired = parseFileBlocks(answer)\n const merged = new Map(files.map((f) => [f.path, f]))\n for (const file of repaired) merged.set(file.path, file)\n return requireFiles([...merged.values()])\n}\n\n/** Varied temperatures so N parallel repair calls diverge instead of returning near-identical output. */\nconst REPAIR_TEMPERATURES = [0.1, 0.4, 0.7, 0.9]\n\n/**\n * Generates up to N repair variants in parallel (different temperatures), verifies all of them\n * in parallel sandbox forks of the same checkpoint, and picks the first green one (or the one\n * with the most passed tests when none is green).\n */\nexport async function repairParallel(\n files: GeneratedFile[],\n report: TestReport,\n deps: {\n llm: LlmClient\n sandbox: SandboxRunner\n config: AgentConfig\n baseImage: string\n withFixtures: (files: GeneratedFile[]) => GeneratedFile[]\n context?: RepairContext\n },\n log: (m: string) => void,\n): Promise<{ files: GeneratedFile[]; report: TestReport; branches: Array<{ branch: number; passed: number; total: number; typecheckOk: boolean; green: boolean }> }> {\n const n = Math.max(1, Math.min(REPAIR_TEMPERATURES.length, deps.config.parallelRepairs))\n const temperatures = REPAIR_TEMPERATURES.slice(0, n)\n log(`Repairing with ${n} parallel branch${n > 1 ? 'es' : ''} (temperatures ${temperatures.join(', ')})`)\n\n const candidates = await Promise.all(\n temperatures.map(async (temperature, i) => {\n const generated = await repair(files, report, deps.llm, deps.config, { temperature, context: deps.context })\n return { branch: i + 1, files: deps.withFixtures(generated) }\n }),\n )\n\n const results = await Promise.all(\n candidates.map(async (c) => {\n const preflight = await preflightSyntax(c.files)\n if (preflight) {\n log(`[branch ${c.branch}] preflight parse failed (${preflight.failed}), skipping sandbox`)\n return { ...c, report: withContract(preflight, c.files) }\n }\n const branchReport = withContract(\n await deps.sandbox.runTests(deps.baseImage, c.files, (m) => log(`[branch ${c.branch}] ${m}`)),\n c.files,\n )\n return { ...c, report: branchReport }\n }),\n )\n\n for (const r of results) {\n log(\n `branch ${r.branch}: ${r.report.passed}/${r.report.total}, typecheck ${r.report.typecheckOk ? 'ok' : 'failed'}, contract ${r.report.contract}`,\n )\n }\n\n const green = results.find((r) => isGreen(r.report))\n // Tie-breaker when two branches are both not-green: prefer the one whose typecheck passed,\n // then the one with more net-passed. Prevents a 10/12 (tc=false) branch beating a 10/12\n // (tc=true) branch purely because they appeared in that order.\n const winner = green ?? results.reduce((best, r) => (isBetter(r.report, best.report) ? r : best))\n log(`Chose branch ${winner.branch}${green ? ' (first green)' : ' (best overall)'}`)\n\n return {\n files: winner.files,\n report: winner.report,\n branches: results.map((r) => ({\n branch: r.branch,\n passed: r.report.passed,\n total: r.report.total,\n typecheckOk: r.report.typecheckOk,\n green: isGreen(r.report),\n })),\n }\n}\n\nfunction requireFiles(files: GeneratedFile[]): GeneratedFile[] {\n const missing = REQUIRED_FILES.filter((path) => !files.some((f) => f.path === path))\n if (missing.length) throw new Error(`Model output is missing ${missing.join(', ')}`)\n return REQUIRED_FILES.map((path) => files.find((f) => f.path === path) as GeneratedFile)\n}\n\n/** One retry for structured steps: invalid JSON goes back to the same model once to be fixed. */\nasync function parseJsonOrAsk<T>(answer: string, llm: LlmClient, model: AgentConfig['models']['fast'], system: string): Promise<T> {\n try {\n return extractJson<T>(answer)\n } catch (error) {\n const fixed = await llm.chat(model, [\n { role: 'system', content: system },\n { role: 'user', content: `This answer is not valid JSON (${messageOf(error)}). Return the same content as strict JSON: double quotes, no comments, no trailing commas.\\n\\n${answer.slice(0, 12_000)}` },\n ], { thinking: false, maxTokens: 6000 })\n return extractJson<T>(fixed)\n }\n}\n\nfunction guessDomain(app: string): string {\n return `${app.toLowerCase().replace(/[^a-z0-9]/g, '')}.com`\n}\n\n/**\n * Monotonic repair: track the best attempt so far by (passed tests - failed tests), prefer\n * a green report over anything else, and roll the current state back when the latest attempt\n * regressed. Prevents the strong model from running away with a worse-than-previous rewrite\n * (seen in bench: HubSpot->Salesforce a2 was 13/14, a3 regressed to a 0/2 syntax error).\n */\nfunction keepBest(args: {\n attempt: number\n files: GeneratedFile[]\n report: TestReport\n bestFiles: GeneratedFile[]\n bestReport: TestReport | null\n log: (m: string) => void\n}): { files: GeneratedFile[]; report: TestReport; bestFiles: GeneratedFile[]; bestReport: TestReport } {\n const { attempt, report, files, bestFiles, bestReport, log } = args\n if (bestReport === null || isBetter(report, bestReport)) {\n return { files, report, bestFiles: files, bestReport: report }\n }\n if (attempt > 1) {\n const strictlyWorse = (report.passed - report.failed) < (bestReport.passed - bestReport.failed)\n const verb = strictlyWorse ? 'regressed' : 'did not improve'\n log(`Attempt ${attempt} ${verb} (${report.passed}/${report.total} vs best ${bestReport.passed}/${bestReport.total}), rolling back for repair`)\n }\n return { files: bestFiles, report: bestReport, bestFiles, bestReport }\n}\n\n/**\n * Ordering for keepBest: green always beats non-green, then more passed-minus-failed wins,\n * then typecheck-ok wins the tie. Keeps a 13/13 contract-passed attempt from being discarded\n * for a 15/16 attempt that still fails the contract test.\n */\nfunction isBetter(a: TestReport, b: TestReport): boolean {\n const greenA = isGreen(a), greenB = isGreen(b)\n if (greenA !== greenB) return greenA\n const diff = (a.passed - a.failed) - (b.passed - b.failed)\n if (diff !== 0) return diff > 0\n if (a.typecheckOk !== b.typecheckOk) return a.typecheckOk\n return false\n}\n\nconst messageOf = (error: unknown): string => {\n if (!(error instanceof Error)) return String(error)\n const cause = (error as Error & { cause?: unknown }).cause\n if (cause instanceof Error) return `${error.message} — cause: ${cause.name}${cause.message ? `: ${cause.message}` : ''}${(cause as Error & { code?: string }).code ? ` (${(cause as Error & { code?: string }).code})` : ''}`\n if (cause && typeof cause === 'object') {\n const c = cause as { code?: string; message?: string }\n return `${error.message} — cause: ${c.code ?? ''}${c.message ? ` ${c.message}` : ''}`.trim()\n }\n return error.message\n}\n\n/** One-line summary of an attempt, used so repair prompts know what the previous passes already tried. */\nfunction summariseReport(report: TestReport): string {\n const bits: string[] = []\n bits.push(`${report.passed}/${report.total} tests`)\n bits.push(report.typecheckOk ? 'typecheck ok' : 'typecheck failed')\n if (report.contract) bits.push(`contract ${report.contract}`)\n const firstFailure = report.failures[0]\n if (firstFailure) bits.push(`e.g. \"${firstFailure.name}: ${firstFailure.message.slice(0, 160).replace(/\\s+/g, ' ')}\"`)\n return bits.join(', ')\n}\n","import { parseTestOutput, TEST_COMMAND } from './report'\nimport type { GeneratedFile, TestReport } from './types'\n\nexport interface SandboxRunner {\n /** Returns an image id that has node, typescript and vitest installed under /work. */\n prepare(log: (message: string) => void): Promise<string>\n /** Runs typecheck + tests for the given files on a fresh branch of the prepared image. */\n runTests(baseImage: string, files: GeneratedFile[], log: (message: string) => void): Promise<TestReport>\n}\n\ninterface Operation {\n uuid: string\n status: 'PENDING' | 'ASSIGNED' | 'EXECUTING' | 'SUCCESS' | 'FAILED' | 'CANCELLED'\n error?: string | null\n result_image_uuid?: string | null\n result?: { image?: string | null; tag?: string | null }\n metadata?: {\n result?: {\n state?: { exit_code?: number; timed_out?: boolean }\n stdout?: { value: string; encoding: 'ascii' | 'base64' }\n stderr?: { value: string; encoding: 'ascii' | 'base64' }\n }\n }\n}\n\nconst NODE_IMAGE_TAG = 'patchbay-node:22'\nconst NODE_IMAGE_REGISTRY = 'docker://docker.io/library/node:22-slim'\n\nconst PREPARE_COMMAND = [\n 'mkdir -p /work/src',\n 'cd /work',\n `printf '%s' '{\"name\":\"connector\",\"private\":true,\"type\":\"module\"}' > package.json`,\n 'npm install --no-audit --no-fund --loglevel=error -D vitest@3.2.4 typescript@5.6.3 @types/node@22',\n].join(' && ')\n\nconst TSCONFIG = JSON.stringify(\n {\n compilerOptions: {\n target: 'ES2022',\n module: 'ESNext',\n moduleResolution: 'Bundler',\n strict: true,\n skipLibCheck: true,\n types: ['node'],\n lib: ['ES2022', 'DOM'],\n },\n include: ['src/**/*.ts'],\n },\n null,\n 2,\n)\n\n/**\n * Nebius Token Factory Sandboxes (ConTree REST API).\n *\n * The expensive part — pulling node and installing vitest — happens once and produces an\n * image checkpoint. Every test attempt forks from that checkpoint with networking disabled,\n * so generated code can never reach the real APIs and each retry starts from the same state.\n */\nexport function createNebiusSandbox(opts: {\n apiKey: string\n project: string\n baseUrl: string\n preparedImage?: string\n fetch?: typeof fetch\n pollIntervalMs?: number\n}): SandboxRunner {\n const doFetch = opts.fetch ?? fetch\n const pollMs = opts.pollIntervalMs ?? 1500\n let cachedImage = opts.preparedImage\n\n const headers = (extra: Record<string, string> = {}) => ({\n Authorization: `Bearer ${opts.apiKey}`,\n Project: opts.project,\n ...extra,\n })\n\n async function request<T>(path: string, init: RequestInit = {}): Promise<{ body: T; location: string | null }> {\n const method = (init.method ?? 'GET').toUpperCase()\n // Retry 5xx and transient network errors on idempotent calls. POST /instances is retried too\n // because our body is deterministic (same files, same command) — a duplicate instance costs\n // one wasted sandbox, which is cheaper than burning a whole plan+research+generate run.\n const maxTries = 3\n let lastError: unknown\n for (let attempt = 0; attempt < maxTries; attempt++) {\n try {\n const res = await doFetch(`${opts.baseUrl}${path}`, { ...init, headers: headers(init.headers as Record<string, string>) })\n const text = await res.text()\n if (res.status >= 500 && res.status < 600 && attempt < maxTries - 1) {\n lastError = new Error(`HTTP ${res.status} ${text.slice(0, 120)}`)\n await sleep(500 * Math.pow(2, attempt))\n continue\n }\n if (!res.ok) throw new Error(`Sandbox ${method} ${path}: HTTP ${res.status} ${text.slice(0, 300)}`)\n return { body: (text ? JSON.parse(text) : {}) as T, location: res.headers.get('location') }\n } catch (error) {\n lastError = error\n if (attempt >= maxTries - 1) break\n await sleep(500 * Math.pow(2, attempt))\n }\n }\n throw lastError instanceof Error ? lastError : new Error(`Sandbox ${method} ${path}: ${String(lastError)}`)\n }\n\n async function uploadFile(content: string): Promise<string> {\n const { body } = await request<{ uuid: string }>('/files', {\n method: 'POST',\n headers: { 'Content-Type': 'application/octet-stream' },\n body: content,\n })\n return body.uuid\n }\n\n async function waitFor(operationId: string, timeoutMs: number): Promise<Operation> {\n const deadline = Date.now() + timeoutMs\n for (;;) {\n const { body } = await request<Operation>(`/operations/${operationId}`)\n if (body.status === 'SUCCESS' || body.status === 'FAILED' || body.status === 'CANCELLED') return body\n if (Date.now() > deadline) throw new Error(`Sandbox operation ${operationId} did not finish in ${timeoutMs / 1000}s`)\n await sleep(pollMs)\n }\n }\n\n function operationIdFrom(location: string | null, body: { uuid?: string }): string {\n const fromLocation = location?.split('/').filter(Boolean).pop()\n const id = fromLocation ?? body.uuid\n if (!id) throw new Error('Sandbox did not return an operation id')\n return id\n }\n\n async function ensureNodeImage(log: (m: string) => void): Promise<string> {\n const { body } = await request<{ images?: { uuid: string; tag?: string | null }[] }>('/images?tagged=1&limit=200')\n const existing = (body.images ?? []).find((image) => image.tag === NODE_IMAGE_TAG)\n if (existing) return existing.uuid\n log('Importing node:22-slim into the sandbox registry (one-time)')\n const started = await request<{ uuid?: string }>('/images/import', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ registry: { url: NODE_IMAGE_REGISTRY }, tag: NODE_IMAGE_TAG, timeout: 600 }),\n })\n const op = await waitFor(operationIdFrom(started.location, started.body), 660_000)\n const image = op.result?.image ?? op.result_image_uuid\n if (op.status !== 'SUCCESS' || !image) throw new Error(`Image import failed: ${op.error ?? op.status}`)\n return image\n }\n\n return {\n async prepare(log) {\n if (cachedImage) {\n log(`Reusing prepared sandbox image ${cachedImage.slice(0, 8)}`)\n return cachedImage\n }\n const nodeImage = await ensureNodeImage(log)\n log('Installing typescript + vitest in a sandbox checkpoint')\n const started = await request<{ uuid?: string }>('/instances', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ image: nodeImage, command: PREPARE_COMMAND, shell: true, timeout: 300, networking: { enabled: true } }),\n })\n const op = await waitFor(operationIdFrom(started.location, started.body), 330_000)\n const exit = op.metadata?.result?.state?.exit_code\n if (op.status !== 'SUCCESS' || !op.result_image_uuid || exit !== 0) {\n throw new Error(`Sandbox preparation failed (exit ${exit ?? '?'}): ${decode(op.metadata?.result?.stderr).slice(0, 500)}`)\n }\n cachedImage = op.result_image_uuid\n log(`Checkpoint ready: ${cachedImage.slice(0, 8)}`)\n return cachedImage\n },\n\n async runTests(baseImage, files, log) {\n const all: GeneratedFile[] = [{ path: 'tsconfig.json', content: TSCONFIG }, ...files.filter((f) => f.path.endsWith('.ts'))]\n const mapped: Record<string, { uuid: string; mode: string }> = {}\n for (const file of all) {\n mapped[`/work/${file.path}`] = { uuid: await uploadFile(file.content), mode: '0644' }\n }\n log(`Forking checkpoint ${baseImage.slice(0, 8)} with ${all.length} files, network off`)\n const started = await request<{ uuid?: string }>('/instances', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n image: baseImage,\n command: TEST_COMMAND,\n shell: true,\n disposable: true,\n timeout: 120,\n files: mapped,\n networking: { enabled: false },\n }),\n })\n const operationId = operationIdFrom(started.location, started.body)\n const op = await waitFor(operationId, 180_000)\n if (op.status !== 'SUCCESS' && !op.metadata?.result) {\n throw new Error(`Sandbox test run ${op.status}: ${op.error ?? 'no result'}`)\n }\n return parseTestOutput(decode(op.metadata?.result?.stdout), `nebius-sandbox:${operationId}`)\n },\n }\n}\n\nfunction decode(stream?: { value: string; encoding: 'ascii' | 'base64' }): string {\n if (!stream?.value) return ''\n return stream.encoding === 'base64' ? Buffer.from(stream.value, 'base64').toString('utf8') : stream.value\n}\n\nconst sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))\n","export interface SearchHit {\n title: string\n url: string\n content: string\n score: number\n}\n\nexport interface ExtractedPage {\n url: string\n content: string\n}\n\nexport interface SearchClient {\n search(query: string, options?: { maxResults?: number; includeDomains?: string[] }): Promise<SearchHit[]>\n extract(urls: string[]): Promise<ExtractedPage[]>\n}\n\n/** Tavily: web search for API docs plus clean-text extraction of the chosen pages. */\nexport function createTavilyClient(opts: { apiKey: string; fetch?: typeof fetch }): SearchClient {\n const doFetch = opts.fetch ?? fetch\n\n async function post<T>(path: string, body: unknown): Promise<T> {\n const res = await doFetch(`https://api.tavily.com${path}`, {\n method: 'POST',\n headers: { Authorization: `Bearer ${opts.apiKey}`, 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n })\n if (!res.ok) throw new Error(`Tavily ${path}: HTTP ${res.status} ${await res.text().catch(() => '')}`)\n return (await res.json()) as T\n }\n\n return {\n async search(query, options = {}) {\n const data = await post<{ results?: SearchHit[] }>('/search', {\n query,\n search_depth: 'advanced',\n max_results: options.maxResults ?? 5,\n include_answer: false,\n ...(options.includeDomains?.length ? { include_domains: options.includeDomains } : {}),\n })\n return (data.results ?? []).map((r) => ({ title: r.title, url: r.url, content: r.content, score: r.score }))\n },\n async extract(urls) {\n if (urls.length === 0) return []\n const data = await post<{ results?: { url: string; raw_content?: string }[] }>('/extract', {\n urls,\n extract_depth: 'advanced',\n })\n return (data.results ?? []).map((r) => ({ url: r.url, content: r.raw_content ?? '' }))\n },\n }\n}\n","import { loadConfig, missingLiveKeys, type AgentConfig } from './config'\nimport { createNebiusClient } from './llm'\nimport { createLocalRunner } from './local-runner'\nimport { replayRun } from './replay'\nimport { researchAgent, runAgent, verifyAgent } from './run'\nimport { createNebiusSandbox } from './sandbox'\nimport { createTavilyClient } from './tavily'\nimport type { GeneratedFile, RunEvent } from './types'\n\nexport * from './types'\nexport { loadConfig, missingLiveKeys } from './config'\nexport { REPLAY_RUN, replayRun, type RecordedRun } from './replay'\nexport { runAgent, researchAgent, verifyAgent, makePlan, research, generate, repair, repairParallel, type AgentDeps } from './run'\nexport { isGreen, parseTestOutput } from './report'\n\n/** Live run when keys are configured and mock mode is off, otherwise the recorded replay. */\nexport function startRun(prompt: string, config: AgentConfig = loadConfig()): AsyncGenerator<RunEvent> {\n if (config.mock || missingLiveKeys(config).length > 0) return replayRun()\n return runAgent(prompt, {\n config,\n llm: createNebiusClient({ apiKey: config.nebiusApiKey, baseUrl: config.nebiusBaseUrl, supportsNemotronThinking: config.llmProvider === 'nebius' }),\n search: createTavilyClient({ apiKey: config.tavilyApiKey }),\n sandbox:\n config.runner === 'local'\n ? createLocalRunner()\n : createNebiusSandbox({\n apiKey: config.nebiusApiKey,\n project: config.nebiusProject,\n baseUrl: config.sandboxUrl,\n preparedImage: config.baseImage,\n }),\n })\n}\n\n/** Plan + research only. Live if keys are set; the replay stream truncated after `spec` otherwise. */\nexport function startResearch(prompt: string, config: AgentConfig = loadConfig()): AsyncGenerator<RunEvent> {\n if (config.mock || missingLiveKeys(config).length > 0) return truncateAt(replayRun(), 'spec')\n return researchAgent(prompt, {\n config,\n llm: createNebiusClient({ apiKey: config.nebiusApiKey, baseUrl: config.nebiusBaseUrl, supportsNemotronThinking: config.llmProvider === 'nebius' }),\n search: createTavilyClient({ apiKey: config.tavilyApiKey }),\n })\n}\n\n/** Verify + repair for given files. Requires live keys; throws in mock mode. */\nexport function startVerify(files: GeneratedFile[], config: AgentConfig = loadConfig()): AsyncGenerator<RunEvent> {\n if (config.mock || missingLiveKeys(config).length > 0) {\n throw new Error('Verify needs live keys (NEBIUS_API_KEY, NEBIUS_AI_PROJECT). Set PATCHBAY_MOCK=false and provide credentials.')\n }\n return verifyAgent(files, {\n config,\n llm: createNebiusClient({ apiKey: config.nebiusApiKey, baseUrl: config.nebiusBaseUrl, supportsNemotronThinking: config.llmProvider === 'nebius' }),\n sandbox:\n config.runner === 'local'\n ? createLocalRunner()\n : createNebiusSandbox({\n apiKey: config.nebiusApiKey,\n project: config.nebiusProject,\n baseUrl: config.sandboxUrl,\n preparedImage: config.baseImage,\n }),\n })\n}\n\nasync function* truncateAt(stream: AsyncGenerator<RunEvent>, lastType: RunEvent['type']): AsyncGenerator<RunEvent> {\n for await (const event of stream) {\n yield event\n if (event.type === lastType) return\n }\n}\n"],"mappings":";AAgCO,SAAS,WAAW,MAAW,QAAQ,KAAkB;AAC9D,QAAM,WAAW,cAAc,IAAI,qBAAqB;AAGxD,QAAM,SAAS,IAAI,wBAAwB,IAAI,kBAAkB,IAAI,kBAAkB;AACvF,QAAM,UACJ,IAAI,yBACJ,IAAI,oBACH,aAAa,WAAW,8BAA8B;AACzD,QAAM,gBACJ,aAAa,WACT,EAAE,MAAM,eAAe,KAAK,eAAe,QAAQ,SAAS,IA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