@patchbay-nebius/agent 0.1.2 → 0.2.0

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.
@@ -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/fixtures-py-template.ts","../src/contract.ts","../src/syntax-check.ts","../src/prompts.ts","../src/lang.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\nimport type { Lang } from './types'\n\nexport interface AgentConfig {\n mock: boolean\n /** Target language of the generated connector. Default `ts`; `py` writes Python with pytest. */\n lang: Lang\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 /**\n * `repair` is the model used for the repair/retry step. It defaults to the same model as\n * `strong` (so single-model deployments keep working), but can be overridden independently\n * when the fine-tune was trained on red→green repair pairs — then `strong` stays as\n * Nemotron Ultra for the fresh-generation step, and `repair` points at the fine-tune.\n */\n models: { fast: ModelTier; mid: ModelTier; strong: ModelTier; repair: ModelTier }\n /** Per-tier endpoint override for `strong` (when strong lives on a dedicated endpoint). */\n strongOverride: { baseUrl: string; apiKey: string; provider: 'nebius' | 'openai' | 'generic' } | null\n /** Per-tier endpoint override for `repair`. Same shape; usually points at the fine-tune. */\n repairOverride: { baseUrl: string; apiKey: string; provider: 'nebius' | 'openai' | 'generic' } | null\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 lang: parseLang(env.PATCHBAY_LANG),\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 repair: { id: env.PATCHBAY_MODEL_REPAIR || env.PATCHBAY_MODEL_STRONG || defaultModels.strong, inputPrice: 1, outputPrice: 3 },\n },\n strongOverride: env.PATCHBAY_STRONG_LLM_BASE_URL\n ? {\n baseUrl: env.PATCHBAY_STRONG_LLM_BASE_URL,\n apiKey: env.PATCHBAY_STRONG_LLM_API_KEY || apiKey,\n provider: parseProvider(env.PATCHBAY_STRONG_LLM_PROVIDER),\n }\n : null,\n repairOverride: env.PATCHBAY_REPAIR_LLM_BASE_URL\n ? {\n baseUrl: env.PATCHBAY_REPAIR_LLM_BASE_URL,\n apiKey: env.PATCHBAY_REPAIR_LLM_API_KEY || apiKey,\n provider: parseProvider(env.PATCHBAY_REPAIR_LLM_PROVIDER),\n }\n : null,\n }\n}\n\nfunction parseProvider(raw: string | undefined): AgentConfig['llmProvider'] {\n if (raw === 'openai' || raw === 'generic') return raw\n return 'nebius'\n}\n\nfunction parseLang(raw: string | undefined): Lang {\n const normalized = (raw ?? '').toLowerCase().trim()\n if (normalized === 'py' || normalized === 'python') return 'py'\n return 'ts'\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 /**\n * Per-model overrides. Lets a specific model id (typically the \"strong\" tier when it's\n * been fine-tuned and self-hosted on a dedicated endpoint) use a different baseUrl /\n * apiKey / nemotron flag than the default. Lookup is by model id, no match → defaults.\n */\n modelOverrides?: Record<string, { baseUrl: string; apiKey: string; supportsNemotronThinking?: boolean; contextWindow?: number }>\n}): LlmClient {\n const doFetch = opts.fetch ?? fetch\n const retries = opts.retries ?? 2\n const nemotron = opts.supportsNemotronThinking ?? true\n const overrides = opts.modelOverrides ?? {}\n const ledger = new Map<string, Usage>()\n\n function approxTokens(messages: ChatMessage[]): number {\n // Rough char/4 heuristic — enough to decide whether to clip max_tokens below the context window.\n let chars = 0\n for (const m of messages) chars += m.content.length + m.role.length + 8\n return Math.ceil(chars / 4)\n }\n\n async function chat(model: ModelTier, messages: ChatMessage[], options: ChatOptions = {}): Promise<string> {\n const override = overrides[model.id]\n const baseUrl = override?.baseUrl ?? opts.baseUrl\n const apiKey = override?.apiKey ?? opts.apiKey\n const nemotronForCall = override ? (override.supportsNemotronThinking ?? false) : nemotron\n const contextWindow = override?.contextWindow\n let maxTokens = options.maxTokens ?? 4096\n if (contextWindow) {\n // vLLM strictly enforces input_tokens + max_tokens <= context_window. The char/4\n // approximation under-counts (BPE splits tend to be denser) and chat-template\n // overhead eats more tokens on top, so pad with 20% + 2048 absolute headroom.\n const promptTokens = Math.ceil(approxTokens(messages) * 1.2) + 2048\n const budget = contextWindow - promptTokens\n if (budget > 0 && budget < maxTokens) maxTokens = budget\n }\n const body = {\n model: model.id,\n messages,\n temperature: options.temperature ?? 0.2,\n max_tokens: maxTokens,\n ...(nemotronForCall && 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(`${baseUrl}/chat/completions`, {\n method: 'POST',\n headers: { Authorization: `Bearer ${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 { parsePytestOutput, parseTestOutput, PYC_MARKER, PYTEST_MARKER, TSC_MARKER, VITEST_MARKER } from './report'\nimport type { SandboxRunner } from './sandbox'\nimport type { GeneratedFile, TestReport } 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 OR py_compile + pytest in a temp\n * folder on this machine. Same commands and parsers as the Nebius sandbox, but NOT\n * isolated, so it is opt-in via PATCHBAY_RUNNER=local and never used by the hosted demo.\n *\n * TS builds use `tsc --noEmit` + `vitest run` from the repo's own node_modules.\n * Python builds probe the host for python 3.12+ and the three pytest-* deps; when\n * everything is present we run the same compileall + pytest --json-report sequence as\n * the sandbox and reuse parsePytestOutput. Missing deps raise a clear error with the\n * exact `pip install` line.\n */\nexport function createLocalRunner(opts: { root?: string; timeoutMs?: number; pythonBin?: string } = {}): 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 const pythonBin = opts.pythonBin ?? (process.platform === 'win32' ? 'python' : 'python3')\n\n return {\n async prepare(log) {\n log('Local runner: tests run on this machine, not in an isolated sandbox')\n // We don't know the language at prepare() time (prepare is called before any\n // files exist). The language-specific probe happens on first runTests call\n // when we actually see which files are coming in.\n return 'local'\n },\n\n async runTests(_base, files, log) {\n const isPy = files.some((f) => f.path.endsWith('.py'))\n return isPy\n ? runPythonTests(files, log, { root, pythonBin, timeout })\n : runTypeScriptTests(files, log, { root, tscEntry, vitestEntry, timeout })\n },\n }\n}\n\ninterface TsCtx {\n root: string\n tscEntry: string\n vitestEntry: string\n timeout: number\n}\n\nasync function runTypeScriptTests(files: GeneratedFile[], log: (m: string) => void, ctx: TsCtx): Promise<TestReport> {\n const workRoot = join(ctx.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(ctx.root, '.')}`)\n const tsc = await runNodeEntry(ctx.tscEntry, ['--noEmit', '-p', 'tsconfig.json'], work, ctx.timeout)\n await runNodeEntry(ctx.vitestEntry, ['run', '--reporter=json', '--outputFile=result.json'], work, ctx.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\ninterface PyCtx {\n root: string\n pythonBin: string\n timeout: number\n}\n\nasync function runPythonTests(files: GeneratedFile[], log: (m: string) => void, ctx: PyCtx): Promise<TestReport> {\n await probePythonEnv(ctx.pythonBin)\n const workRoot = join(ctx.root, '.fixture-tmp')\n mkdirSync(workRoot, { recursive: true })\n const work = mkdtempSync(join(workRoot, 'py-'))\n try {\n for (const file of files.filter((f) => f.path.endsWith('.py'))) write(work, file)\n writeFileSync(join(work, 'pytest.ini'), '[pytest]\\nasyncio_mode = auto\\n')\n log(`Running py_compile and pytest in ${work.replace(ctx.root, '.')}`)\n const pyc = await runCmd(ctx.pythonBin, ['-m', 'compileall', '-q', '.'], work, ctx.timeout)\n await runCmd(ctx.pythonBin, ['-m', 'pytest', '-q', '--json-report', '--json-report-file=result.json'], work, ctx.timeout)\n const json = existsSync(join(work, 'result.json')) ? await readText(join(work, 'result.json')) : ''\n const stdout = `${PYC_MARKER}\\n${pyc.code}\\n${pyc.output}\\n${PYTEST_MARKER}\\n${json}`\n return parsePytestOutput(stdout, 'local')\n } finally {\n rmSync(work, { recursive: true, force: true })\n }\n}\n\n/**\n * Verify the host has python >=3.12 and the three test deps we rely on\n * (pytest, pytest-asyncio, pytest-json-report). Throws with a precise error +\n * `pip install` line listing exactly which deps are missing.\n */\nexport async function probePythonEnv(pythonBin: string): Promise<void> {\n const versionOut = await runCmd(pythonBin, ['--version'], process.cwd(), 10_000).catch(() => ({ code: 1, output: '' }))\n if (versionOut.code !== 0 || !/^Python\\s+(\\d+)\\.(\\d+)/.test(versionOut.output)) {\n throw new Error(`Local runner (python): '${pythonBin}' not found on PATH. Install Python 3.12+ or set PATCHBAY_RUNNER=nebius.`)\n }\n const m = /^Python\\s+(\\d+)\\.(\\d+)/.exec(versionOut.output)\n const major = Number(m?.[1] ?? 0)\n const minor = Number(m?.[2] ?? 0)\n if (major < 3 || (major === 3 && minor < 12)) {\n throw new Error(`Local runner (python): found Python ${major}.${minor}, need >=3.12. Upgrade python or set PATCHBAY_RUNNER=nebius.`)\n }\n const missing: string[] = []\n const probe = async (mod: string, pkg: string) => {\n const res = await runCmd(pythonBin, ['-c', `import ${mod}`], process.cwd(), 10_000).catch(() => ({ code: 1, output: '' }))\n if (res.code !== 0) missing.push(pkg)\n }\n await probe('pytest', 'pytest')\n await probe('pytest_asyncio', 'pytest-asyncio')\n await probe('pytest_jsonreport', 'pytest-json-report')\n if (missing.length) {\n throw new Error(\n `Local runner (python): missing ${missing.join(', ')}. Install with:\\n` +\n ` ${pythonBin} -m pip install ${missing.join(' ')}\\n` +\n `Or set PATCHBAY_RUNNER=nebius to use the hosted sandbox.`,\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 runNodeEntry(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\n/** Runs an arbitrary external command (python, pytest, …) and captures combined stdout + stderr. */\nfunction runCmd(bin: string, args: string[], cwd: string, timeout: number): Promise<{ code: number; output: string }> {\n return new Promise((resolve) => {\n execFile(bin, 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@@'\nexport const PYC_MARKER = '@@PATCHBAY_PYC@@'\nexport const PYTEST_MARKER = '@@PATCHBAY_PYTEST@@'\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\n/**\n * Python counterpart of TEST_COMMAND. Compile every .py file with py_compile first (cheap\n * static check: syntax, undefined-name imports fail at module load), then pytest with the\n * JSON reporter. Both results print between markers so one stdout stream carries everything.\n */\nexport const TEST_COMMAND_PY = [\n 'cd /work',\n 'python -m compileall -q . > /tmp/pyc.txt 2>&1; echo $? > /tmp/pyc.code',\n 'python -m pytest -q --json-report --json-report-file=/tmp/pytest.json > /tmp/pytest.log 2>&1',\n `echo \"${PYC_MARKER}\"`,\n 'cat /tmp/pyc.code',\n 'head -c 6000 /tmp/pyc.txt',\n `echo \"${PYTEST_MARKER}\"`,\n 'cat /tmp/pytest.json 2>/dev/null || tail -c 6000 /tmp/pytest.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\ninterface PytestJson {\n created?: number\n duration?: number\n exitcode?: number\n summary?: { passed?: number; failed?: number; error?: number; skipped?: number; total?: number; collected?: number }\n tests?: {\n nodeid?: string\n outcome?: 'passed' | 'failed' | 'skipped' | 'error' | 'xfailed' | 'xpassed'\n call?: { longrepr?: string }\n setup?: { longrepr?: string }\n teardown?: { longrepr?: string }\n }[]\n collectors?: { nodeid?: string; outcome?: string; longrepr?: string }[]\n}\n\n/**\n * Parse the two-section Python output: py_compile exit code + pytest JSON report.\n * typecheckOk here means `python -m compileall` printed exit 0 — every .py file parsed.\n * A collection error (e.g. import failure in test_connector.py) still produces a report\n * with failed > 0 so the repair loop reacts to it.\n */\nexport function parsePytestOutput(stdout: string, ranOn: string): TestReport {\n const pycStart = stdout.indexOf(PYC_MARKER)\n const pytestStart = stdout.indexOf(PYTEST_MARKER)\n const pycSection = pycStart >= 0 ? stdout.slice(pycStart + PYC_MARKER.length, pytestStart >= 0 ? pytestStart : undefined).trim() : ''\n const pytestSection = pytestStart >= 0 ? stdout.slice(pytestStart + PYTEST_MARKER.length).trim() : stdout.trim()\n\n const [codeLine = '1', ...pycLines] = pycSection.split('\\n')\n const typecheckOk = codeLine.trim() === '0'\n const typecheckOutput = pycLines.join('\\n').trim()\n\n let json: PytestJson | null = null\n try {\n const start = pytestSection.indexOf('{')\n json = start >= 0 ? (JSON.parse(pytestSection.slice(start)) as PytestJson) : 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: 'pytest', message: truncate(pytestSection || 'pytest produced no output', 4000) }],\n durationMs: 0,\n ranOn,\n }\n }\n\n const failures: TestFailure[] = []\n const passedNames: string[] = []\n for (const collector of json.collectors ?? []) {\n if (collector.outcome === 'failed' && collector.longrepr) {\n failures.push({ name: `collection: ${collector.nodeid ?? 'unknown'}`, message: truncate(stripAnsi(collector.longrepr), 2000) })\n }\n }\n for (const test of json.tests ?? []) {\n const name = test.nodeid ?? 'unnamed test'\n if (test.outcome === 'passed' || test.outcome === 'xpassed') {\n passedNames.push(name)\n continue\n }\n if (test.outcome === 'failed' || test.outcome === 'error') {\n const detail = test.call?.longrepr ?? test.setup?.longrepr ?? test.teardown?.longrepr ?? '(no detail)'\n failures.push({ name, message: truncate(stripAnsi(detail), 2000) })\n }\n }\n\n const summary = json.summary ?? {}\n const passed = summary.passed ?? passedNames.length\n const summaryFailed = (summary.failed ?? 0) + (summary.error ?? 0)\n const failed = Math.max(summaryFailed, failures.length)\n const total = Math.max(summary.total ?? summary.collected ?? 0, passed + failed)\n return {\n typecheckOk,\n typecheckOutput,\n passed,\n failed,\n total,\n failures,\n durationMs: json.duration ? Math.round(json.duration * 1000) : 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', lang: 'ts' }\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","/**\n * Python fixtures runtime, exported as a string constant so webpack bundles it\n * into any downstream serverless build (Vercel, Lambda, Cloudflare Workers).\n *\n * The parallel .py file (fixtures-py.template.py) is kept for grep / linting /\n * tooling that wants to see the Python code as Python, but it is NOT read at\n * runtime — this constant is. Keep the two files in sync when editing: tests\n * will catch a mismatch.\n */\nexport const FIXTURES_PY_TEMPLATE = `# Written by patchbay from the API documentation. Regenerated on every attempt, do not edit.\n# {{PATCHBAY_DOCS_HEADER}}\n\n\"\"\"Contract fixtures for the connector under test.\n\nExports:\n SOURCE_EXAMPLE dict — documented event payload\n TARGET_ENDPOINTS list — endpoints the connector may call, in documented order\n contract_fetch() — fake async transport answering documented endpoints, raising otherwise\n fake_fetch(handler) — fake async transport driven by a user handler\n json_response(body, status=200, headers=None)\n\"\"\"\nfrom __future__ import annotations\n\nimport json as _json\nimport re as _re\nfrom typing import Any, Awaitable, Callable, TypedDict\n\n#: Example payload of the source event, as documented.\nSOURCE_EXAMPLE: dict[str, Any] = {{PATCHBAY_SOURCE_EXAMPLE}}\n\n\nclass DocumentedEndpoint(TypedDict):\n method: str\n url: str\n response: Any\n\n\n#: Target endpoints the connector may call, in the documented order, with documented responses.\nTARGET_ENDPOINTS: list[DocumentedEndpoint] = {{PATCHBAY_TARGET_ENDPOINTS}}\n\n\nclass RecordedCall(TypedDict):\n method: str\n url: str\n body: Any\n json: Any\n headers: dict[str, str]\n\n\nclass FakeResponse:\n \"\"\"Minimal response object: status_code, headers (dict), text, json(), raise_for_status().\"\"\"\n\n def __init__(self, body: Any, status: int = 200, headers: dict[str, str] | None = None) -> None:\n self.status_code = status\n self.status = status # alias\n self.headers = dict(headers or {})\n if status == 204:\n self._raw = b''\n elif isinstance(body, (bytes, bytearray)):\n self._raw = bytes(body)\n elif isinstance(body, str):\n self._raw = body.encode('utf-8')\n else:\n self._raw = _json.dumps(body).encode('utf-8')\n self.headers.setdefault('Content-Type', 'application/json')\n\n @property\n def content(self) -> bytes:\n return self._raw\n\n @property\n def text(self) -> str:\n return self._raw.decode('utf-8', errors='replace')\n\n def json(self) -> Any:\n return _json.loads(self._raw.decode('utf-8')) if self._raw else None\n\n def raise_for_status(self) -> None:\n if self.status_code >= 400:\n raise Exception(f\"HTTP {self.status_code}\")\n\n\nFetchHandler = Callable[[RecordedCall], FakeResponse | Awaitable[FakeResponse]]\n\n\ndef _parse_json(raw: Any) -> Any:\n if raw is None:\n return None\n # dict / list already parsed — most connectors pass body=<dict>, not body=json.dumps(dict)\n if isinstance(raw, (dict, list)):\n return raw\n if isinstance(raw, (bytes, bytearray)):\n try:\n return _json.loads(raw.decode('utf-8'))\n except Exception:\n return None\n if isinstance(raw, str):\n try:\n return _json.loads(raw)\n except Exception:\n return None\n return None\n\n\n_URL = _re.compile(r'^https?://([^/?#]+)([^?#]*)', _re.IGNORECASE)\n_PLACEHOLDER = _re.compile(r'^\\\\{[^}]+\\\\}$|^:[A-Za-z_]\\\\w*$|^<[^>]+>$')\n\n\ndef _split_url(url: str) -> tuple[str, str] | None:\n m = _URL.match(url)\n if not m:\n return None\n host = m.group(1).lower()\n path = m.group(2) or '/'\n return host, path\n\n\ndef _url_matches(template: str, actual: str) -> bool:\n t, a = _split_url(template), _split_url(actual)\n if not t or not a:\n return False\n t_host, t_path = t\n a_host, a_path = a\n if '.'.join(t_host.split('.')[-2:]) != '.'.join(a_host.split('.')[-2:]):\n return False\n t_segs = t_path.rstrip('/').split('/')\n a_segs = a_path.rstrip('/').split('/')\n if len(t_segs) != len(a_segs):\n return False\n for ts, as_ in zip(t_segs, a_segs):\n if _PLACEHOLDER.match(ts):\n continue\n if ts != as_:\n return False\n return True\n\n\ndef find_endpoint(method: str, url: str) -> DocumentedEndpoint | None:\n for ep in TARGET_ENDPOINTS:\n if ep['method'] == method.upper() and _url_matches(ep['url'], url):\n return ep\n return None\n\n\ndef fake_fetch(handler: FetchHandler) -> tuple[Callable[..., Awaitable[FakeResponse]], list[RecordedCall]]:\n \"\"\"A correctly-typed fake async fetch for every non-contract test.\n\n The handler receives the recorded request dict: method, url, body, json, headers.\n It may return a FakeResponse directly or an awaitable.\n \"\"\"\n calls: list[RecordedCall] = []\n\n async def fetch(url: str, method: str = 'GET', body: Any = None, headers: dict[str, str] | None = None, **_: Any) -> FakeResponse:\n call: RecordedCall = {\n 'method': method.upper(),\n 'url': url,\n 'body': body,\n 'json': _parse_json(body),\n 'headers': dict(headers or {}),\n }\n calls.append(call)\n result = handler(call)\n if hasattr(result, '__await__'):\n return await result # type: ignore[return-value]\n return result # type: ignore[return-value]\n\n return fetch, calls\n\n\ndef contract_fetch() -> tuple[Callable[..., Awaitable[FakeResponse]], list[RecordedCall]]:\n \"\"\"Fake async fetch that answers every documented endpoint with its documented response\n and raises on anything else. Use it in the contract test:\n\n fetch, calls = contract_fetch()\n await handle(SOURCE_EXAMPLE, { 'fetch': fetch, ... })\n assert len(calls) > 0\n \"\"\"\n\n def _handler(req: RecordedCall) -> FakeResponse:\n ep = find_endpoint(req['method'], req['url'])\n if not ep:\n raise AssertionError(f\"contract: {req['method']} {req['url']} is not a documented endpoint\")\n return json_response(ep['response'])\n\n return fake_fetch(_handler)\n\n\n_STATUS_TEXT: dict[int, str] = {\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\ndef json_response(body: Any, status: int = 200, headers: dict[str, str] | None = None) -> FakeResponse:\n \"\"\"A JSON FakeResponse with the standard status text and content-type.\n\n Extra response headers (Retry-After for 429 tests, Location for redirects, etc.) can be passed via\n the headers= kwarg and are merged on top of the content-type header.\n \"\"\"\n merged: dict[str, str] = {'Content-Type': 'application/json'}\n if headers:\n merged.update(headers)\n return FakeResponse(body, status, headers=merged)\n`\n","import type { ApiSpec, GeneratedFile, Lang, TestReport } from './types'\nimport { FIXTURES_PY_TEMPLATE as PY_TEMPLATE } from './fixtures-py-template'\n\nexport const FIXTURES_PATH = 'src/fixtures.ts'\nexport const FIXTURES_PATH_PY = 'fixtures.py'\n\n/**\n * Python fixtures runtime is imported as a TS-exported string constant from\n * fixtures-py-template.ts, so webpack bundles it into any downstream serverless\n * build (Vercel, Lambda). The companion fixtures-py.template.py file is kept\n * next to it for grep / Python tooling but is NOT read at runtime.\n */\n\nexport function fixturesPathFor(lang: Lang): string {\n return lang === 'py' ? FIXTURES_PATH_PY : FIXTURES_PATH\n}\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\n/**\n * Python counterpart of renderFixtures. Same contract: patchbay writes fixtures.py from\n * the researched API spec, the model writes a connector + test file that imports from it,\n * and the test suite must run a contract test (name starts with `test_contract`) that\n * passes SOURCE_EXAMPLE through handle() with contract_fetch injected.\n *\n * The runtime (FakeResponse / fake_fetch / contract_fetch / URL matcher) lives in\n * fixtures-py.template.py as real Python; we only inject the spec-specific pieces\n * (SOURCE_EXAMPLE, TARGET_ENDPOINTS, documentation URLs) via marker substitution.\n */\nexport function renderFixturesPy(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 = [...new Set([spec.source.docsUrl, ...spec.target.map((t) => t.docsUrl)].filter(Boolean))]\n // The template line is `# {{PATCHBAY_DOCS_HEADER}}` so we substitute the TEXT only.\n // Multi-line docs join with newline + `# ` so each line stays a comment.\n const docsHeader = docs.length ? docs.map((url) => `Source: ${url}`).join('\\n# ') : 'generated from the research step'\n const content = PY_TEMPLATE\n .replace('{{PATCHBAY_DOCS_HEADER}}', docsHeader)\n .replace('{{PATCHBAY_SOURCE_EXAMPLE}}', pythonRepr(spec.source.example ?? {}, 0))\n .replace('{{PATCHBAY_TARGET_ENDPOINTS}}', pythonRepr(endpoints, 0))\n return { path: FIXTURES_PATH_PY, content }\n}\n\n/**\n * Convert a JSON-safe value to its Python literal form. The spec examples come from the LLM\n * as JSON, so the only type-mismatch between JS and Python is: true/false/null → True/False/None.\n * Everything else is a 1:1 lift. Strings keep their JSON escapes, which Python also understands.\n */\nfunction pythonRepr(value: unknown, indent: number): string {\n const pad = (n: number) => ' '.repeat(n)\n if (value === null || value === undefined) return 'None'\n if (typeof value === 'boolean') return value ? 'True' : 'False'\n if (typeof value === 'number') return Number.isFinite(value) ? String(value) : 'None'\n if (typeof value === 'string') return JSON.stringify(value)\n if (Array.isArray(value)) {\n if (value.length === 0) return '[]'\n const items = value.map((v) => `${pad(indent + 1)}${pythonRepr(v, indent + 1)}`).join(',\\n')\n return `[\\n${items},\\n${pad(indent)}]`\n }\n if (typeof value === 'object') {\n const entries = Object.entries(value as Record<string, unknown>)\n if (entries.length === 0) return '{}'\n const items = entries\n .map(([k, v]) => `${pad(indent + 1)}${JSON.stringify(k)}: ${pythonRepr(v, indent + 1)}`)\n .join(',\\n')\n return `{\\n${items},\\n${pad(indent)}}`\n }\n return 'None'\n}\n\n/** Static half of the Python contract check: the suite must actually use fixtures.py. */\nexport function contractMissingPy(files: GeneratedFile[]): string | null {\n const tests = files.find((f) => f.path === 'test_connector.py')?.content ?? ''\n if (!/from\\s+fixtures\\s+import/.test(tests) && !/import\\s+fixtures/.test(tests)) {\n return 'test_connector.py does not import from fixtures'\n }\n if (!/\\bdef\\s+test_contract/.test(tests)) {\n return 'test_connector.py has no test_contract* function 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/** Dispatch: pick the right static contract check for the connector's language. */\nexport function contractMissingFor(lang: Lang, files: GeneratedFile[]): string | null {\n return lang === 'py' ? contractMissingPy(files) : contractMissing(files)\n}\n\n/** Dispatch: render fixtures for the connector's language. */\nexport function renderFixturesFor(lang: Lang, spec: ApiSpec): GeneratedFile {\n return lang === 'py' ? renderFixturesPy(spec) : renderFixtures(spec)\n}\n\n/** Language-aware fold of the static check + contract test results into the report. */\nexport function withContractFor(lang: Lang, report: TestReport, files: GeneratedFile[]): TestReport {\n const missing = contractMissingFor(lang, 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 const failed = report.failures.some((f) => /\\bcontract\\b/i.test(f.name) || /test_contract/.test(f.name))\n if (failed) return { ...report, contract: 'failed' }\n const ran = (report.passedNames ?? []).some((name) => /\\bcontract\\b/i.test(name) || /test_contract/.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","import { spawn } from 'node:child_process'\nimport { transform } from 'esbuild'\nimport type { GeneratedFile, Lang, 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 *\n * For Python, we probe the host for `python` and ask it to AST-parse each .py file.\n * If python is available (dev / CI machines usually have it) we catch syntax errors\n * offline the same way esbuild does for TS. If python is missing (hosted Vercel\n * builds, bare servers) we skip the preflight and let the sandbox's compileall\n * handle it — same behaviour as before, no regression.\n */\nexport async function preflightSyntax(files: GeneratedFile[], lang: Lang = 'ts'): Promise<TestReport | null> {\n if (lang === 'py') return preflightSyntaxPy(files)\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\n/**\n * Python preflight: ask the host's `python` to AST-parse each .py file. Saves a full\n * sandbox round when the strong model produces syntax-invalid Python. If python is\n * not installed on the host, we silently return null (same as the earlier no-op) so\n * the sandbox's compileall catches syntax errors instead.\n */\nlet pythonAvailable: boolean | null = null\nasync function preflightSyntaxPy(files: GeneratedFile[]): Promise<TestReport | null> {\n const pyFiles = files.filter((f) => f.path.endsWith('.py'))\n if (pyFiles.length === 0) return null\n if (pythonAvailable === null) pythonAvailable = await probePython()\n if (!pythonAvailable) return null\n\n const failures: { file: string; message: string; line?: number }[] = []\n await Promise.all(\n pyFiles.map(async (f) => {\n // Single python invocation per file: pipe stdin with `python -I` (isolated, no\n // path tricks) and `-c \"...\"` that reads stdin and calls ast.parse. Returns exit 0\n // on parse success, nonzero + a formatted traceback on failure.\n const script = [\n 'import sys, ast, json',\n 'src = sys.stdin.read()',\n 'try:',\n ' ast.parse(src, filename=sys.argv[1])',\n ' sys.exit(0)',\n 'except SyntaxError as e:',\n ` print(json.dumps({'line': e.lineno, 'col': e.offset, 'msg': str(e.msg)}))`,\n ' sys.exit(1)',\n ].join('\\n')\n const result = await runPython(['-I', '-c', script, f.path], f.content)\n if (result.exit === 0) return\n try {\n const parsed = JSON.parse(result.stdout.trim()) as { line?: number; col?: number; msg?: string }\n failures.push({ file: f.path, line: parsed.line, message: `${parsed.msg ?? 'SyntaxError'}${parsed.col ? ` (col ${parsed.col})` : ''}` })\n } catch {\n failures.push({ file: f.path, message: (result.stdout || result.stderr || 'SyntaxError').slice(0, 400) })\n }\n }),\n )\n if (failures.length === 0) return null\n\n return {\n typecheckOk: false,\n typecheckOutput: failures.map((f) => `${f.file}${f.line ? `:${f.line}` : ''}: ${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:ast',\n passedNames: [],\n }\n}\n\nasync function probePython(): Promise<boolean> {\n const { exit } = await runPython(['-c', 'import ast'], '')\n return exit === 0\n}\n\nfunction runPython(args: string[], stdin: string): Promise<{ exit: number; stdout: string; stderr: string }> {\n return new Promise((resolve) => {\n const cmd = process.platform === 'win32' ? 'python' : 'python3'\n const child = spawn(cmd, args, { stdio: ['pipe', 'pipe', 'pipe'] })\n let stdout = ''\n let stderr = ''\n child.stdout.on('data', (b) => (stdout += b.toString()))\n child.stderr.on('data', (b) => (stderr += b.toString()))\n child.on('error', () => resolve({ exit: 127, stdout, stderr: stderr || 'python not found' }))\n child.on('close', (code) => resolve({ exit: code ?? 1, stdout, stderr }))\n child.stdin.end(stdin)\n })\n}\n\n/** Reset the cached python-available flag; useful in tests. */\nexport function _resetPythonProbe(): void {\n pythonAvailable = null\n}\n","import type { ApiSpec, Lang, 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 const GENERATE_SYSTEM_PY = `You are the code-generation step of patchbay. Write a production-quality Python 3.12 connector and its tests.\n\nHard rules:\n- Exactly three files: connector.py, test_connector.py, README.md. Output each as\n <file path=\"connector.py\">\n ...code...\n </file>\n with no markdown fences and no prose outside the file blocks.\n- No third-party runtime dependencies beyond the Python standard library — use httpx ONLY\n via dependency injection, never imported at module scope. Accept an injected transport in\n the config so tests can pass a fake.\n- Secrets come from the config dict, never hard-coded. Document the env var names from the spec in the README.\n- connector.py exports: a typed \\`ConnectorConfig\\` TypedDict (or dataclass), a typed \\`SourcePayload\\`\n TypedDict for the event, and one async function named \\`handle(payload, config)\\` that returns\n a typed result dict with the created ids. Prefer async def throughout — the fake transport is async.\n- Validate the input: raise a descriptive ValueError when a required field is missing.\n- Non-2xx responses from the target must raise an Exception that includes the status code and the endpoint URL.\n- Follow the spec exactly for URLs, HTTP methods, auth header/query names and body shapes.\n- test_connector.py uses pytest with \\`pytest.mark.asyncio\\` for async tests (import pytest; the\n sandbox has pytest-asyncio installed in auto mode so no decorator is strictly required but you\n may use it). Use a fake transport callable that records calls. Cover at least: happy path with\n 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 sleeps, no real env vars.\n- fixtures.py is provided by patchbay, read-only, do not output it. It exports SOURCE_EXAMPLE (the\n documented source payload), TARGET_ENDPOINTS and contract_fetch(), a fake async transport that\n answers documented endpoints (URL placeholders like {id} or region hosts are handled) and raises on anything else.\n test_connector.py MUST contain this block, adapted to your types and config. Put it at the TOP LEVEL\n (not nested inside a class) and keep the function name starting with 'test_contract' so patchbay can detect it:\n import pytest\n from fixtures import SOURCE_EXAMPLE, contract_fetch\n from connector import handle\n\n @pytest.mark.asyncio\n async def test_contract_handles_documented_example():\n fetch, calls = contract_fetch()\n result = await handle(SOURCE_EXAMPLE, { <a valid config dict>, 'fetch': fetch })\n assert len(calls) > 0\n Configure the connector in that test so the documented example is valid input. If the example lacks\n a field the connector needs, make the connector handle that case (skip, fallback or clear error)\n rather than editing the example.\n- Do NOT reject SOURCE_EXAMPLE based on wall-clock time. If the connector guards against stale webhooks\n (timestamp age, signature expiry, nonce window), either freeze time in the contract test with\n freezegun or by monkeypatching time.time, 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- DON'T OVER-ENGINEER. Only add retry logic, pagination, HMAC verification, idempotency keys,\n or caching if the user prompt EXPLICITLY asks for it (words like \"retry\", \"429\", \"backoff\",\n \"paginate\", \"cursor\", \"verify signature\", \"HMAC\", \"idempotent\"). A simple \"when X happens, do Y\"\n prompt is one call per endpoint — do not invent retry tests the connector then has to pass.\n Fewer tests that pass > more tests that fail. The contract test is mandatory; everything else\n earns its keep by exercising something the prompt actually requested.\n- RETRY SEMANTICS (only when the prompt asks for retries). \"Retry up to N times\" means at most\n N retry attempts after the initial request, so total HTTP calls are at most N+1. On a 429 (or\n other retryable status), compute the next delay as\n \\`delay = max(parse_retry_after(res), base_ms * 2 ** retry_index)\\` where retry_index starts at 0\n for the first retry. Retry-After may be an integer-in-seconds OR an HTTP-date string — handle\n both and fall back to pure exponential backoff when the header is absent or unparseable.\n Worked pattern — connector sleeps via a monkeypatch-friendly sleep hook, tests patch it to a\n no-op so the full retry sequence completes instantly:\n\n # connector.py\n import asyncio\n async def _sleep(seconds: float) -> None:\n await asyncio.sleep(seconds)\n async def handle(payload, config):\n max_retries = config.get('max_retries', 3)\n base_ms = config.get('base_backoff_ms', 100)\n fetch = config['fetch']\n for attempt in range(max_retries + 1): # N retries → N+1 total calls\n res = await fetch(url, method='POST', body=body, headers=auth_headers)\n if res.status_code < 400:\n return {'ok': True, 'response': res.json()}\n if res.status_code != 429 or attempt == max_retries:\n raise Exception(f'HTTP {res.status_code} from {url}')\n retry_after_ms = _parse_retry_after(res.headers.get('Retry-After'))\n await _sleep(max(retry_after_ms, base_ms * 2 ** attempt) / 1000)\n\n # test_connector.py\n import connector as _c\n async def test_retry_on_429_then_success(monkeypatch):\n monkeypatch.setattr(_c, '_sleep', lambda s: _noop()) # see below\n calls_seen = []\n def handler(req):\n calls_seen.append(1)\n if len(calls_seen) == 1:\n return json_response({'error': 'rate limited'}, 429, headers={'Retry-After': '0'})\n return json_response({'id': 1}, 200)\n fetch, calls = fake_fetch(handler)\n result = await handle(SOURCE_EXAMPLE, { ..., 'fetch': fetch, 'max_retries': 2 })\n assert len(calls) == 2 # one 429, one success\n async def _noop():\n return None\n\n The tests MUST monkeypatch the module-level \\`_sleep\\` symbol you expose, not asyncio.sleep itself\n (patching asyncio.sleep globally breaks pytest-asyncio). Call counts are the contract: success\n on attempt K uses K+1 total calls; exhaustion of N retries uses N+1 total calls, never more.\n- CURSOR PAGINATION (only when the prompt asks for pagination). Terminate pagination loops on the\n API's explicit end signal — for GraphQL check pageInfo.hasNextPage is False, for REST check the\n absence or None of the cursor field (next_cursor, after, starting_after, page_info). Never loop\n while \"cursor is truthy\" alone — many APIs return an empty-string or placeholder cursor on the\n final page. Pass the cursor under the exact field name the vendor documents. Hard-cap every\n pagination loop at 50 iterations as a safety net.\n- URL FIDELITY (contract-critical). Your fetch calls MUST hit URLs that match the entries in\n TARGET_ENDPOINTS from fixtures.py. patchbay wrote that file from the researched spec and the\n URL matcher accepts placeholder segments ({id}, :id, <id>) + region subdomains — but NOT a\n different base host, a different path shape, or a different HTTP method. If a documented\n endpoint uses PATCH to \\`/sobjects/Account/Website__c/{website}\\`, do not POST to\n \\`/sobjects/Account\\` — contract_fetch will raise because that's a different endpoint.\n Build each call's URL by taking TARGET_ENDPOINTS[i]['url'] as the template and substituting\n placeholders with payload values at the SAME POSITIONS; do not reconstruct URLs from scratch.\n- IDEMPOTENT UPSERT PATTERNS. Vendors use distinctive URL shapes for upserts; use the exact one:\n\n # Mailchimp — PUT to subscriber-hash URL (md5(email.lower())):\n import hashlib\n subscriber_hash = hashlib.md5(email.lower().encode('utf-8')).hexdigest()\n url = f\"https://{dc}.api.mailchimp.com/3.0/lists/{list_id}/members/{subscriber_hash}\"\n await fetch(url, method='PUT', body={'email_address': email, 'status_if_new': 'subscribed', 'merge_fields': {...}}, headers=auth)\n\n # Salesforce — external-id upsert via PATCH on the field value in the path:\n from urllib.parse import quote\n url = f\"{instance}/services/data/v60.0/sobjects/Account/Website__c/{quote(website)}\"\n await fetch(url, method='PATCH', body={'Name': name, 'Industry': industry}, headers=auth)\n # response 201 (created) or 204 (updated); check status_code to distinguish\n\n # HubSpot — contact upsert by email (PATCH with idProperty=email):\n url = f\"https://api.hubapi.com/crm/v3/objects/contacts/{quote(email)}?idProperty=email\"\n await fetch(url, method='PATCH', body={'properties': {...}}, headers=auth)\n\n- MULTI-STEP CRUD / UPSERT PATTERN. When the integration needs to create several related objects\n in sequence (Pipedrive org → person → deal, Salesforce account → contact → opportunity, HubSpot\n contact → company → association), do them inside one handle() in order, carrying the id from\n each response into the next request. Each POST uses its own \\`url\\` from TARGET_ENDPOINTS;\n contract_fetch answers each one with the documented response.\n\n # connector.py — Pipedrive org/person/deal sequence\n org_res = await fetch(ORG_URL, method='POST', body={'name': org_name}, headers=auth)\n org_id = org_res.json()['data']['id']\n person_res = await fetch(PERSON_URL, method='POST',\n body={'name': person_name, 'org_id': org_id, 'email': [email]},\n headers=auth)\n person_id = person_res.json()['data']['id']\n deal_res = await fetch(DEAL_URL, method='POST',\n body={'title': title, 'person_id': person_id, 'org_id': org_id},\n headers=auth)\n return {'org_id': org_id, 'person_id': person_id, 'deal_id': deal_res.json()['data']['id']}\n\n Field names and nesting come from the fixtures' response examples — if the documented response\n is {\"data\": {\"id\": 123}}, read \\`.json()['data']['id']\\`, not \\`.json()['id']\\`.\n- URL-ENCODED QUERY PARAMETERS. When the API uses GET with a formula or filter in the query string\n (Airtable filterByFormula, HubSpot search, Linear GraphQL variables), build the query with\n urllib.parse.quote on the value, not string concatenation. Preserve the quoting style the vendor\n documents (Airtable wants \\`{Email}='x@y.co'\\`, with the braces literal and the single quotes\n URL-encoded):\n\n from urllib.parse import quote\n formula = \"{Email}='\" + email + \"'\"\n list_url = f\"{BASE}/{table}?filterByFormula={quote(formula)}&maxRecords=1\"\n list_res = await fetch(list_url, method='GET', headers=auth)\n records = list_res.json().get('records', [])\n if records:\n record_id = records[0]['id']\n patch_url = f\"{BASE}/{table}/{record_id}\"\n # PATCH only the fields the payload has\n only_set = {k: v for k, v in {'Status': status, 'Notes': notes}.items() if v}\n await fetch(patch_url, method='PATCH', body={'fields': only_set}, headers=auth)\n- For every other test use fake_fetch and json_response from fixtures instead of writing your own mock:\n from fixtures import fake_fetch, json_response\n def handler(req):\n if req['url'].endswith('/deals'):\n return json_response({'id': 2}, 201)\n return json_response({'error': 'x'}, 500)\n fetch, calls = fake_fetch(handler)\n Each recorded call is a dict: {'method', 'url', 'body' (bytes/str as sent), 'json' (parsed body or None),\n 'headers' (dict)}. Assert on calls[i]['json'], do not json.loads it again.\n json_response signature is \\`json_response(body, status=200, headers=None)\\`. Pass response headers\n via the \\`headers=\\` kwarg when a retry test needs Retry-After or when the connector reads a header\n off the response (e.g. \\`json_response({'ok': True}, 200, headers={'Retry-After': '2'})\\`).\n- Code must be clean Python 3.12: type hints on every function signature, no unused imports, no\n bare except. Standard library modules only in top-level imports.\n- CHAINED FLOWS. When spec.target has MORE THAN ONE endpoint, call them in the documented order\n inside handle(), using data from one response to shape the next request. The contract test must\n exercise every documented endpoint — contract_fetch answers each one with its documented response,\n so a chained flow like \"Zendesk ticket -> GitHub issue -> Zendesk ticket comment\" means handle()\n POSTs the GitHub issue, reads its html_url (or id) from the response, then POSTs the Zendesk\n comment carrying that URL. One auth header per vendor — read each vendor's env var / secret from\n config under distinct keys (github_token vs zendesk_api_token). The response-example fields the\n fixtures hand you are the ONLY fields you may assume present; a documented field missing from the\n response example is fine to read with .get(... , None).\n- README.md: what it does, config/env vars, a usage example (async code), and the assumptions from the plan.`\n\nexport function generateUser(plan: Plan, spec: ApiSpec, fixtures: string, lang: Lang = 'ts'): string {\n const fixturesLabel = lang === 'py' ? 'fixtures.py' : 'src/fixtures.ts'\n return `Plan:\\n${JSON.stringify(plan, null, 2)}\\n\\nAPI spec:\\n${JSON.stringify(spec, null, 2)}\\n\\n${fixturesLabel} (provided by patchbay, read-only):\\n${fixtures}\\n\\nWrite the three files now.`\n}\n\nexport function generateSystemFor(lang: Lang): string {\n return lang === 'py' ? GENERATE_SYSTEM_PY : GENERATE_SYSTEM\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, lang: Lang = 'ts'): string {\n const tcLabel = lang === 'py' ? 'py_compile' : 'tsc --noEmit'\n const runnerLabel = lang === 'py' ? 'pytest' : 'vitest'\n const tcPass = lang === 'py' ? 'Static check passed.' : 'Typecheck passed.'\n const tcFail = lang === 'py' ? 'Static check failed:' : 'Typecheck failed:'\n const tcLine = report.typecheckOk ? tcPass : `${tcFail}\\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 (${tcLabel}, then ${runnerLabel}).\n${header ? `\\n${header}\\n` : ''}\n${tcLine}\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 {\n contractMissing,\n contractMissingPy,\n FIXTURES_PATH,\n FIXTURES_PATH_PY,\n renderFixtures,\n renderFixturesPy,\n} from './contract'\nimport { GENERATE_SYSTEM, GENERATE_SYSTEM_PY } from './prompts'\nimport { parsePytestOutput, parseTestOutput, PYC_MARKER, PYTEST_MARKER, TEST_COMMAND, TEST_COMMAND_PY, TSC_MARKER, VITEST_MARKER } from './report'\nimport type { ApiSpec, GeneratedFile, Lang, TestReport } from './types'\n\n/**\n * Everything that varies by target language in one place.\n *\n * When a new language ships (Go, Rust, …), add an entry to LANG with the full\n * descriptor filled in. Every callsite reads `LANG[config.lang].X` instead of\n * forking on `lang === 'py'`, so support for the new language falls out\n * automatically — no scattered `if (lang === 'py')` edits across prompts.ts,\n * sandbox.ts, run.ts, contract.ts, cli.ts and syntax-check.ts.\n */\nexport interface LangDescriptor {\n /** Human label — \"TypeScript\", \"Python 3.12\". */\n readonly label: string\n\n /** The three files the generated connector must contain, in display order. */\n readonly requiredFiles: readonly string[]\n\n /** Where the authoritative test fixtures live inside the generated bundle. */\n readonly fixturesPath: string\n\n /** System prompt for the generate + repair steps. */\n readonly generateSystem: string\n\n /** Default source file the UI opens in the Code panel. */\n readonly defaultOpenFile: string\n\n /** Short label for the \"typecheck\" / \"syntax check\" step shown in UI + logs. */\n readonly typecheckLabel: string\n\n /** Short label for the test runner shown in UI + repair prompts (\"vitest\", \"pytest\"). */\n readonly testRunnerLabel: string\n\n /**\n * Base Docker image for the sandbox: a public registry URL plus the tag we\n * cache it under so the per-language checkpoint only has to install test deps.\n */\n readonly sandbox: {\n readonly registry: string\n readonly tag: string\n /** Shell command run once to install test deps on top of the base image. */\n readonly prepareCommand: string\n /** Shell command run on every attempt, prints marker-delimited stdout. */\n readonly testCommand: string\n }\n\n /** Render patchbay-authoritative fixtures for a researched API spec. */\n renderFixtures(spec: ApiSpec): GeneratedFile\n\n /** Static half of the contract check: inspect test file imports / shape. */\n contractMissing(files: GeneratedFile[]): string | null\n\n /** Parse the sandbox's marker-delimited stdout into a TestReport. */\n parseTestOutput(stdout: string, ranOn: string): TestReport\n}\n\nconst TS: LangDescriptor = {\n label: 'TypeScript',\n requiredFiles: ['src/connector.ts', 'src/connector.test.ts', 'README.md'],\n fixturesPath: FIXTURES_PATH,\n generateSystem: GENERATE_SYSTEM,\n defaultOpenFile: 'src/connector.ts',\n typecheckLabel: 'typecheck',\n testRunnerLabel: 'vitest',\n sandbox: {\n registry: 'docker://docker.io/library/node:22-slim',\n tag: 'patchbay-node:22',\n prepareCommand: [\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 testCommand: TEST_COMMAND,\n },\n renderFixtures,\n contractMissing,\n parseTestOutput,\n}\n\nconst PY: LangDescriptor = {\n label: 'Python 3.12',\n requiredFiles: ['connector.py', 'test_connector.py', 'README.md'],\n fixturesPath: FIXTURES_PATH_PY,\n generateSystem: GENERATE_SYSTEM_PY,\n defaultOpenFile: 'connector.py',\n typecheckLabel: 'syntax check',\n testRunnerLabel: 'pytest',\n sandbox: {\n registry: 'docker://docker.io/library/python:3.12-slim',\n tag: 'patchbay-python:3.12',\n prepareCommand: [\n 'mkdir -p /work',\n 'cd /work',\n 'pip install --quiet --no-cache-dir pytest==8.3.3 pytest-asyncio==0.24.0 pytest-json-report==1.5.0',\n // %b interprets \\n as a real newline; %s would write literal backslash-n.\n `printf '%b' '[pytest]\\\\nasyncio_mode = auto\\\\n' > pytest.ini`,\n ].join(' && '),\n testCommand: TEST_COMMAND_PY,\n },\n renderFixtures: renderFixturesPy,\n contractMissing: contractMissingPy,\n parseTestOutput: parsePytestOutput,\n}\n\n/** Lookup table: `LANG[config.lang]` returns the full language profile. */\nexport const LANG: Record<Lang, LangDescriptor> = { ts: TS, py: PY }\n\n/** Markers re-exported here for sandbox parsers that still read them by name. */\nexport { PYC_MARKER, PYTEST_MARKER, TSC_MARKER, VITEST_MARKER }\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 { withContractFor, withFixtures } from './contract'\nimport { preflightSyntax } from './syntax-check'\nimport { LANG } from './lang'\nimport type { LlmClient } from './llm'\nimport { extractJson, parseFileBlocks, renderFileBlocks } from './parse'\nimport {\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, Lang, 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\n// Required file lists live on the LangDescriptor (LANG[lang].requiredFiles).\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 lang: Lang = config.lang ?? 'ts'\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', lang }\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 = LANG[lang].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, lang)\n if (preflight) {\n report = withContractFor(lang, 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 = withContractFor(lang, 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, lang,\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 const lang: Lang = config.lang ?? 'ts'\n yield { type: 'mode', mode: 'live', lang }\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 const lang: Lang = config.lang ?? 'ts'\n yield { type: 'mode', mode: 'live', lang }\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, lang)\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, lang,\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 lang: Lang = config.lang ?? 'ts'\n const answer = await llm.chat(config.models.strong, [\n { role: 'system', content: LANG[lang].generateSystem },\n { role: 'user', content: generateUser(plan, spec, fixtures, lang) },\n ], { maxTokens: 24_000, temperature: 0.1 })\n return requireFiles(parseFileBlocks(answer), lang)\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 lang: Lang = config.lang ?? 'ts'\n const answer = await llm.chat(config.models.repair, [\n { role: 'system', content: LANG[lang].generateSystem },\n { role: 'user', content: repairUser(renderFileBlocks(files), report, options.context, lang) },\n ], { maxTokens: 24_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()], lang)\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 lang?: Lang\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 lang: Lang = deps.lang ?? deps.config.lang ?? 'ts'\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, lang)\n if (preflight) {\n log(`[branch ${c.branch}] preflight parse failed (${preflight.failed}), skipping sandbox`)\n return { ...c, report: withContractFor(lang, preflight, c.files) }\n }\n const branchReport = withContractFor(\n lang,\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[], lang: Lang = 'ts'): GeneratedFile[] {\n const required = LANG[lang].requiredFiles\n // PATCHBAY_OPTIONAL_README=1 relaxes the README.md requirement, used by the fine-tune\n // ablation benchmark: our Qwen3-30B fine-tune was trained on red→green repair pairs\n // (connector + test only), so it reliably skips README. Keep connector + test checks strict.\n const effective = process.env.PATCHBAY_OPTIONAL_README === '1'\n ? required.filter((p) => p !== 'README.md')\n : required\n const missing = effective.filter((path) => !files.some((f) => f.path === path))\n if (missing.length) throw new Error(`Model output is missing ${missing.join(', ')}`)\n return required\n .filter((p) => files.some((f) => f.path === p))\n .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 { LANG } from './lang'\nimport type { GeneratedFile, Lang, TestReport } from './types'\n\nexport interface SandboxRunner {\n /** Returns an image id prepared for the configured language (node+vitest, or python+pytest). */\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 PY_IMAGE_TAG = 'patchbay-python:3.12'\nconst PY_IMAGE_REGISTRY = 'docker://docker.io/library/python:3.12-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\n/**\n * Prepare Python 3.12 with the exact test deps we rely on. Keep the surface tiny:\n * - pytest (test runner)\n * - pytest-asyncio (async def test support, auto mode)\n * - pytest-json-report (machine-readable output for parsePytestOutput)\n * - httpx is NOT installed — generated code must use an injected fake transport, same\n * invariant as TS where fetch is injected and `node-fetch` is never pulled in.\n * conftest.py sets asyncio_mode = auto so bare `async def test_...` work without decorators.\n */\nconst PREPARE_COMMAND_PY = [\n 'mkdir -p /work',\n 'cd /work',\n 'pip install --quiet --no-cache-dir pytest==8.3.3 pytest-asyncio==0.24.0 pytest-json-report==1.5.0',\n // printf '%b' interprets \\n as a real newline; '%s' would write the literal \\n characters\n // and pytest.ini would be a one-line garble (\"unexpected value continuation\").\n `printf '%b' '[pytest]\\\\nasyncio_mode = auto\\\\n' > pytest.ini`,\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 the base image and installing test deps — happens once and\n * produces an image checkpoint. Every test attempt forks from that checkpoint with networking\n * disabled, so generated code can never reach the real APIs and each retry starts from the\n * same state. One checkpoint per language.\n */\nexport function createNebiusSandbox(opts: {\n apiKey: string\n project: string\n baseUrl: string\n preparedImage?: string\n /** Target language — `ts` (default) uses node:22-slim + vitest, `py` uses python:3.12-slim + pytest. */\n lang?: Lang\n fetch?: typeof fetch\n pollIntervalMs?: number\n}): SandboxRunner {\n const doFetch = opts.fetch ?? fetch\n const pollMs = opts.pollIntervalMs ?? 1500\n const lang: Lang = opts.lang ?? 'ts'\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 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 ensureBaseImage(log: (m: string) => void): Promise<string> {\n const { tag, registry } = LANG[lang].sandbox\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 === tag)\n if (existing) return existing.uuid\n log(`Importing ${registry.replace('docker://', '')} 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: registry }, 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 function filesForRun(files: GeneratedFile[]): GeneratedFile[] {\n if (lang === 'py') {\n return files.filter((f) => f.path.endsWith('.py'))\n }\n return [{ path: 'tsconfig.json', content: TSCONFIG }, ...files.filter((f) => f.path.endsWith('.ts'))]\n }\n\n function parse(stdout: string, operationId: string): TestReport {\n return LANG[lang].parseTestOutput(stdout, `nebius-sandbox:${operationId}`)\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 baseImage = await ensureBaseImage(log)\n const { prepareCommand } = LANG[lang].sandbox\n log(`Installing ${lang === 'py' ? 'pytest + pytest-asyncio + pytest-json-report' : '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: baseImage, command: prepareCommand, 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 = filesForRun(files)\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: LANG[lang].sandbox.testCommand,\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 parse(decode(op.metadata?.result?.stdout), 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\nfunction buildLlm(config: AgentConfig) {\n const modelOverrides: Record<string, { baseUrl: string; apiKey: string; supportsNemotronThinking?: boolean; contextWindow?: number }> = {}\n if (config.strongOverride) {\n modelOverrides[config.models.strong.id] = {\n baseUrl: config.strongOverride.baseUrl,\n apiKey: config.strongOverride.apiKey,\n supportsNemotronThinking: config.strongOverride.provider === 'nebius',\n // Fine-tune vLLM endpoints we deploy use --max-model-len 32768.\n contextWindow: 32768,\n }\n }\n if (config.repairOverride) {\n modelOverrides[config.models.repair.id] = {\n baseUrl: config.repairOverride.baseUrl,\n apiKey: config.repairOverride.apiKey,\n supportsNemotronThinking: config.repairOverride.provider === 'nebius',\n contextWindow: 32768,\n }\n }\n return createNebiusClient({\n apiKey: config.nebiusApiKey,\n baseUrl: config.nebiusBaseUrl,\n supportsNemotronThinking: config.llmProvider === 'nebius',\n modelOverrides: Object.keys(modelOverrides).length ? modelOverrides : undefined,\n })\n}\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, parsePytestOutput } from './report'\nexport { renderFixtures, renderFixturesPy, renderFixturesFor, contractMissing, contractMissingPy, contractMissingFor, withContract, withContractFor, withFixtures, FIXTURES_PATH, FIXTURES_PATH_PY } from './contract'\nexport { scanRepo, scanFiles, formatReport, type Opportunity, type ScanInputFile } from './scanner'\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: buildLlm(config),\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 lang: config.lang,\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: buildLlm(config),\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: buildLlm(config),\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 lang: config.lang,\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":";AA8CO,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,IAC5D,EAAE,MAAM,iCAAiC,KAAK,qCAAqC,QAAQ,oCAAoC;AACrI,SAAO;AAAA,IACL,MAAM,IAAI,kBAAkB;AAAA,IAC5B,MAAM,UAAU,IAAI,aAAa;AAAA,IACjC,QAAQ,IAAI,oBAAoB,UAAU,UAAU;AAAA,IACpD,cAAc;AAAA,IACd,eAAe,IAAI,qBAAqB;AAAA,IACxC,eAAe;AAAA,IACf,YAAY,IAAI,sBAAsB;AAAA,IACtC,cAAc,IAAI,kBAAkB;AAAA,IACpC,WAAW,IAAI,uBAAuB;AAAA,IACtC,aAAa,OAAO,IAAI,yBAAyB,CAAC;AAAA,IAClD,iBAAiB,MAAM,OAAO,IAAI,6BAA6B,CAAC,GAAG,GAAG,CAAC;AAAA,IACvE,aAAa;AAAA,IACb,QAAQ;AAAA,MACN,MAAM,EAAE,IAAI,IAAI,uBAAuB,cAAc,MAAM,YAAY,MAAM,aAAa,KAAK;AAAA,MAC/F,KAAK,EAAE,IAAI,IAAI,sBAAsB,cAAc,KAAK,YAAY,KAAK,aAAa,IAAI;AAAA,MAC1F,QAAQ,EAAE,IAAI,IAAI,yB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