@tangle-network/agent-runtime 0.59.0 → 0.61.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.
Files changed (53) hide show
  1. package/dist/agent.d.ts +1 -1
  2. package/dist/agent.js +1 -2
  3. package/dist/agent.js.map +1 -1
  4. package/dist/analyst-loop.d.ts +1 -1
  5. package/dist/{chunk-IN7WHMGZ.js → chunk-5V343QPB.js} +47 -7
  6. package/dist/chunk-5V343QPB.js.map +1 -0
  7. package/dist/chunk-7IXF3VUJ.js +59 -0
  8. package/dist/chunk-7IXF3VUJ.js.map +1 -0
  9. package/dist/{chunk-ZWGEA722.js → chunk-AU5MCNHO.js} +2 -2
  10. package/dist/chunk-IBRJTG7O.js +475 -0
  11. package/dist/chunk-IBRJTG7O.js.map +1 -0
  12. package/dist/{chunk-MMDIORZY.js → chunk-Q5R33I7Y.js} +4 -23
  13. package/dist/chunk-Q5R33I7Y.js.map +1 -0
  14. package/dist/{chunk-45D64J7B.js → chunk-VCOT7XEQ.js} +190 -99
  15. package/dist/chunk-VCOT7XEQ.js.map +1 -0
  16. package/dist/coder-DD5J5Onk.d.ts +52 -0
  17. package/dist/coordination-k29badiX.d.ts +381 -0
  18. package/dist/{delegates-C94qchkz.d.ts → delegates-CWMv_rKL.d.ts} +649 -21
  19. package/dist/index.d.ts +9 -6
  20. package/dist/index.js +9 -9
  21. package/dist/intelligence.d.ts +1 -1
  22. package/dist/{loop-runner-bin-Noz7P-mS.d.ts → loop-runner-bin-Bqt0hiNY.d.ts} +46 -12
  23. package/dist/loop-runner-bin.d.ts +7 -4
  24. package/dist/loop-runner-bin.js +4 -4
  25. package/dist/loops.d.ts +7 -6
  26. package/dist/loops.js +17 -6
  27. package/dist/mcp/bin.js +10 -10
  28. package/dist/mcp/bin.js.map +1 -1
  29. package/dist/mcp/index.d.ts +12 -12
  30. package/dist/mcp/index.js +7 -7
  31. package/dist/{openai-tools-d4GKwgya.d.ts → openai-tools-CA2N3-Ak.d.ts} +1 -1
  32. package/dist/profiles.d.ts +7 -9
  33. package/dist/profiles.js +5 -7
  34. package/dist/profiles.js.map +1 -1
  35. package/dist/{run-loop-CcqfR_gy.d.ts → run-loop-D3PwlG7J.d.ts} +1 -1
  36. package/dist/runtime.d.ts +30 -1046
  37. package/dist/runtime.js +17 -6
  38. package/dist/{types-CUzjRFZ3.d.ts → types-Crxftafi.d.ts} +2 -2
  39. package/dist/workflow.d.ts +2 -2
  40. package/dist/workflow.js +1 -2
  41. package/dist/workflow.js.map +1 -1
  42. package/dist/worktree-fanout-CBULEoVe.d.ts +1098 -0
  43. package/package.json +2 -2
  44. package/dist/chunk-45D64J7B.js.map +0 -1
  45. package/dist/chunk-4FEUFYOY.js +0 -282
  46. package/dist/chunk-4FEUFYOY.js.map +0 -1
  47. package/dist/chunk-7QYOXFCD.js +0 -293
  48. package/dist/chunk-7QYOXFCD.js.map +0 -1
  49. package/dist/chunk-IN7WHMGZ.js.map +0 -1
  50. package/dist/chunk-MMDIORZY.js.map +0 -1
  51. package/dist/coder-CybltHEm.d.ts +0 -163
  52. package/dist/coordination-Biw19JzN.d.ts +0 -944
  53. /package/dist/{chunk-ZWGEA722.js.map → chunk-AU5MCNHO.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/profiles/coder.ts"],"sourcesContent":["/**\n * @experimental\n *\n * `coderProfile` — opinionated preset for code-modification tasks.\n *\n * The agent is told to:\n * - work on a fresh branch inside the sandbox workspace\n * - keep the patch minimal (under `maxDiffLines`)\n * - avoid `forbiddenPaths`\n * - run `testCmd` and `typecheckCmd`\n * - emit a final JSON result the output adapter parses\n *\n * The profile is stateless and agent-agnostic — `harness` selects the\n * sandbox-SDK backend (`claude-code`, `codex`, `opencode/*`). For\n * heterogeneous fanout, use `multiHarnessCoderFanout`.\n */\n\nimport type { AgentProfile, SandboxEvent } from '@tangle-network/sandbox'\nimport type {\n AgentRunSpec,\n DefaultVerdict,\n Driver,\n OutputAdapter,\n Validator,\n} from '../runtime/types'\n\nconst DEFAULT_MAX_DIFF_LINES = 400\n\n/** @experimental */\nexport interface CoderTask {\n /** What the agent must accomplish. Free-form prose. */\n goal: string\n /** Absolute path inside the sandbox where the repo lives. */\n repoRoot: string\n /** Default `main`. The branch the agent diffs against. */\n baseBranch?: string\n /** Default `pnpm test --run`. */\n testCmd?: string\n /** Default `pnpm typecheck`. */\n typecheckCmd?: string\n /** Files the agent may inspect for context. Surfaced verbatim in the prompt. */\n contextFiles?: string[]\n /**\n * Paths the agent must not touch. Validator hard-fails on any match.\n * Use glob-free literal path prefixes for unambiguous enforcement.\n */\n forbiddenPaths?: string[]\n /** Default 400. Hard cap; validator hard-fails when exceeded. */\n maxDiffLines?: number\n}\n\n/** @experimental */\nexport interface CoderOutput {\n /** Branch the agent wrote the patch on. */\n branch: string\n /** Unified diff (`git diff <base>..HEAD`). */\n patch: string\n testResult: { passed: boolean; output: string }\n typecheckResult: { passed: boolean; output: string }\n diffStats: { filesChanged: number; insertions: number; deletions: number }\n /** Optional reviewer commentary surfaced by the agent. */\n reviewerNotes?: string\n}\n\n/** @experimental */\nexport interface CoderProfileOptions {\n /** Sandbox-SDK backend.type. Default `'claude-code'`. */\n harness?: string\n /** Default model id passed in `AgentProfile.model.default`. */\n model?: string\n /** Custom system prompt replacement. Default = built-in coder preset. */\n systemPrompt?: string\n /** Stable name for `AgentRunSpec.name`. Default = `coder-${harness}`. */\n name?: string\n}\n\n/**\n * Build a coder preset.\n *\n * `validator` enforces test + typecheck + a 400-line default diff cap. For\n * per-task `forbiddenPaths` / `maxDiffLines` enforcement, pass `task` here\n * — the returned validator closes over its constraints. Without a task\n * the validator falls back to the default cap and skips path enforcement.\n *\n * @experimental\n */\nexport function coderProfile(options: CoderProfileOptions & { task?: CoderTask } = {}): {\n profile: AgentProfile\n taskToPrompt: (task: CoderTask) => string\n output: OutputAdapter<CoderOutput>\n validator: Validator<CoderOutput>\n agentRunSpec: AgentRunSpec<CoderTask>\n} {\n const harness = options.harness ?? 'claude-code'\n const name = options.name ?? `coder-${harness}`\n const systemPrompt = options.systemPrompt ?? DEFAULT_CODER_SYSTEM_PROMPT\n const profile: AgentProfile = {\n name,\n description: 'Code-modification agent. Minimal-diff worktree-based coder.',\n prompt: { systemPrompt },\n model: options.model ? { default: options.model } : undefined,\n tools: { git: true, fs: true, shell: true, test_runner: true },\n metadata: { backendType: harness, role: 'coder' },\n }\n const output: OutputAdapter<CoderOutput> = { parse: parseCoderEvents }\n const validator: Validator<CoderOutput> = options.task\n ? createCoderValidator(options.task)\n : createCoderValidator({\n goal: '',\n repoRoot: '',\n forbiddenPaths: [],\n maxDiffLines: DEFAULT_MAX_DIFF_LINES,\n })\n const agentRunSpec: AgentRunSpec<CoderTask> = {\n name,\n profile,\n taskToPrompt: formatCoderPrompt,\n }\n return { profile, taskToPrompt: formatCoderPrompt, output, validator, agentRunSpec }\n}\n\n/** @experimental */\nexport interface MultiHarnessCoderFanoutOptions {\n /**\n * Sandbox-SDK backend.type identifiers, one per parallel agent. Default:\n * `['claude-code', 'codex', 'opencode/zai-coding-plan/glm-5.1']`.\n */\n harnesses?: string[]\n /** Optional per-harness model override. Indexed parallel to `harnesses`. */\n models?: (string | undefined)[]\n}\n\n/**\n * The multi-harness coder fanout driving `createDefaultCoderDelegate`'s `variants>1`\n * sandbox-session path. (`worktreeCoderFanout` is the local-repo generic counterpart for\n * new code; both are first-class.)\n *\n * @experimental\n */\nexport function multiHarnessCoderFanout(options: MultiHarnessCoderFanoutOptions = {}): {\n agentRuns: AgentRunSpec<CoderTask>[]\n output: OutputAdapter<CoderOutput>\n validator: Validator<CoderOutput>\n driver: Driver<CoderTask, CoderOutput, 'pick-winner' | 'fail'>\n} {\n const harnesses =\n options.harnesses && options.harnesses.length > 0\n ? options.harnesses\n : ['claude-code', 'codex', 'opencode/zai-coding-plan/glm-5.1']\n const models = options.models ?? []\n const agentRuns = harnesses.map((harness, i) => {\n const { agentRunSpec } = coderProfile({ harness, model: models[i] })\n return agentRunSpec\n })\n const { output, validator } = coderProfile()\n const driver: Driver<CoderTask, CoderOutput, 'pick-winner' | 'fail'> = {\n name: 'fanout',\n plan: async (task, history) => (history.length === 0 ? agentRuns.map(() => task) : []),\n decide: (history) => (history.some((i) => i.verdict?.valid === true) ? 'pick-winner' : 'fail'),\n }\n return { agentRuns, output, validator, driver }\n}\n\nconst DEFAULT_CODER_SYSTEM_PROMPT = [\n 'You are a coder agent operating inside an isolated sandbox workspace.',\n 'Your job is to deliver a minimal, correct patch for the user-supplied goal.',\n '',\n 'Hard rules:',\n ' 1. Work on a fresh branch off the supplied base. Do not mutate the base branch.',\n ' 2. Never touch a forbidden path. The user will list them explicitly.',\n ' 3. Keep the diff under the max-diff cap. Prefer the smallest change that ships.',\n ' 4. Run the supplied test and typecheck commands before declaring done.',\n ' 5. If either command fails, fix the cause — do not weaken the test or hide the error.',\n '',\n 'When you finish, emit a single final structured message of the shape:',\n ' ```json',\n ' { \"branch\": \"<branch-name>\",',\n ' \"patch\": \"<unified-diff>\",',\n ' \"testResult\": { \"passed\": <bool>, \"output\": \"<stdout/stderr>\" },',\n ' \"typecheckResult\": { \"passed\": <bool>, \"output\": \"<stdout/stderr>\" },',\n ' \"diffStats\": { \"filesChanged\": <int>, \"insertions\": <int>, \"deletions\": <int> },',\n ' \"reviewerNotes\": \"<optional commentary>\" }',\n ' ```',\n].join('\\n')\n\nfunction formatCoderPrompt(task: CoderTask): string {\n const base = task.baseBranch ?? 'main'\n const testCmd = task.testCmd ?? 'pnpm test --run'\n const typecheckCmd = task.typecheckCmd ?? 'pnpm typecheck'\n const maxDiff = task.maxDiffLines ?? DEFAULT_MAX_DIFF_LINES\n const forbidden = task.forbiddenPaths?.length ? task.forbiddenPaths.join(', ') : '(none)'\n const context = task.contextFiles?.length\n ? task.contextFiles.map((f) => ` - ${f}`).join('\\n')\n : ' (none)'\n return [\n `Goal: ${task.goal}`,\n `Repo: ${task.repoRoot}`,\n `Base branch: ${base}`,\n `Run tests with: ${testCmd}`,\n `Run typecheck with: ${typecheckCmd}`,\n `Forbidden paths: ${forbidden}`,\n `Max diff lines: ${maxDiff}`,\n 'Context files:',\n context,\n '',\n 'Produce a minimal patch on a fresh branch. Run tests and typecheck before',\n 'returning. Emit the final JSON result block exactly as instructed.',\n ].join('\\n')\n}\n\n/**\n * Walk the event stream and return the structured coder payload.\n *\n * The agent is instructed to emit a JSON block; in practice the sandbox SDK\n * lifts the structured payload onto `data.result` of a `result` / `final`\n * event. When the event stream does not contain a structured result, the\n * adapter scans the assistant's text output for a fenced JSON block matching\n * the expected keys.\n *\n * The text-scan is shape-tolerant and order-preserving: harnesses differ in\n * how they stream assistant text. claude-code lifts whole text onto\n * `data.text` / `data.delta`; opencode streams it as fragments inside\n * `message.part.updated` events (`data.part.text`, with incremental\n * `data.delta`). The final JSON result block is therefore split across many\n * fragments and never present in any single event — so the scan accumulates\n * ALL assistant text in stream order first, then scans the concatenation for\n * fenced blocks (last valid one wins). Scanning per-event (as before) found\n * nothing for opencode and yielded an empty `CoderOutput` for a run that\n * actually produced a patch.\n */\nfunction parseCoderEvents(events: SandboxEvent[]): CoderOutput {\n for (let i = events.length - 1; i >= 0; i -= 1) {\n const event = events[i]\n if (!event) continue\n const type = String(event.type ?? '')\n const data = isRecord(event.data) ? event.data : {}\n if (type === 'result' || type === 'final' || type === 'coder.result') {\n const direct = coerceCoderOutput(data.result ?? data.output ?? data)\n if (direct) return direct\n }\n }\n // Fallback: accumulate assistant text across the whole stream (any harness\n // shape), then take the last fenced JSON block that coerces.\n const transcript = collectAssistantText(events)\n for (const candidate of fencedJsonBlocks(transcript)) {\n const coerced = coerceCoderOutput(candidate)\n if (coerced) return coerced\n }\n return {\n branch: '',\n patch: '',\n testResult: { passed: false, output: '' },\n typecheckResult: { passed: false, output: '' },\n diffStats: { filesChanged: 0, insertions: 0, deletions: 0 },\n }\n}\n\n/**\n * Build a validator that closes over a specific `CoderTask`'s constraints.\n *\n * Checks in order:\n * 1. Forbidden-path: any `+++` / `---` header in the patch matching a\n * path prefix in `task.forbiddenPaths` fails hard.\n * 2. Diff size: line count above `task.maxDiffLines` (default 400) fails\n * hard; below cap, the score shrinks linearly.\n * 3. Tests: `output.testResult.passed` must be `true`.\n * 4. Typecheck: `output.typecheckResult.passed` must be `true`.\n *\n * Aggregate score: `0.5 * tests + 0.3 * typecheck + 0.2 * (1 - diffLines/maxDiff)`.\n * `valid` is the conjunction of all four.\n *\n * @experimental\n */\n/**\n * Default-on safety floor (folded from the ai-trading-blueprint delegation\n * MCP): a coder patch that touches a credential-shaped path is rejected\n * regardless of `forbiddenPaths` config. Catches `.env`, private keys,\n * keystores, wallets, and the common secret/credential JSON files.\n */\nconst SECRET_PATH_RE =\n /(^|\\/)(\\.env(\\.|$)|.*\\.(pem|key|p12|pfx|keystore|wallet)|id_rsa|id_ed25519|secrets?\\.json|credentials?\\.json)$/i\n\n/** @experimental Inputs the mechanical coder gate decides on — a captured patch plus the\n * test/typecheck PASS signals derived for it. Shared by `createCoderValidator` (sandbox-event\n * shape) and the generic worktree-CLI deliverable (which derives `testsPassed`/`typecheckPassed`\n * by running the commands in the worktree). */\nexport interface CoderCheckInput {\n /** The unified diff produced by the run. */\n patch: string\n /** Did `testCmd` exit clean? */\n testsPassed: boolean\n /** Did `typecheckCmd` exit clean? */\n typecheckPassed: boolean\n}\n\n/** @experimental The per-task constraints the mechanical gate enforces. */\nexport interface CoderCheckConstraints {\n /** Default 400. Hard cap; gate fails when exceeded. */\n maxDiffLines?: number\n /** Literal path prefixes the patch must not touch. */\n forbiddenPaths?: string[]\n}\n\n/**\n * @experimental\n *\n * The pure mechanical coder gate — the SINGLE source of the no-op / secret-path floor /\n * diff-size / forbidden-path / test / typecheck checks. No I/O: it scores a patch + its\n * already-derived pass signals. Both the `createCoderValidator` shim (sandbox `CoderOutput`)\n * and the generic worktree-CLI `coderDeliverable` (which runs the commands itself) call this,\n * so the gate logic never forks.\n *\n * Checks in order: (1) no-op rejection, (2) always-on secret-path floor (independent of\n * `forbiddenPaths`), (3) forbidden-path, (4) diff-size cap, (5) tests, (6) typecheck.\n * Aggregate score: `0.5*tests + 0.3*typecheck + 0.2*(1 - diffLines/maxDiff)`; `valid` is the\n * conjunction of all six.\n */\nexport function runCoderChecks(\n input: CoderCheckInput,\n constraints: CoderCheckConstraints = {},\n): DefaultVerdict {\n const maxDiff = constraints.maxDiffLines ?? DEFAULT_MAX_DIFF_LINES\n const forbidden = constraints.forbiddenPaths ?? []\n const scores: Record<string, number> = {}\n const notes: string[] = []\n let pass = true\n\n const touched = touchedPathsFromPatch(input.patch)\n\n // No-op rejection: an empty patch can trivially \"pass\" tests/typecheck\n // (nothing changed) yet does no work — never a valid coder result.\n if (touched.length === 0 || input.patch.trim().length === 0) {\n pass = false\n scores.nonEmpty = 0\n notes.push('empty patch — no files changed')\n } else {\n scores.nonEmpty = 1\n }\n\n // Secret-path floor: always-on, independent of `forbiddenPaths`.\n const touchedSecrets = touched.filter((p) => SECRET_PATH_RE.test(p))\n if (touchedSecrets.length > 0) {\n pass = false\n scores.noSecrets = 0\n notes.push(`touched secret-shaped paths: ${touchedSecrets.join(', ')}`)\n } else {\n scores.noSecrets = 1\n }\n\n const touchedForbidden = forbidden.filter((path) => {\n const prefix = path.endsWith('/') ? path : `${path}/`\n const exact = prefix.slice(0, -1)\n return touched.some((p) => p === exact || p.startsWith(prefix))\n })\n if (touchedForbidden.length > 0) {\n pass = false\n scores.forbiddenPath = 0\n notes.push(`touched forbidden paths: ${touchedForbidden.join(', ')}`)\n } else {\n scores.forbiddenPath = 1\n }\n\n const diffLines = countDiffLines(input.patch)\n if (diffLines > maxDiff) {\n pass = false\n scores.diffSize = 0\n notes.push(`diff ${diffLines} lines exceeds cap ${maxDiff}`)\n } else {\n scores.diffSize = maxDiff === 0 ? 0 : Math.max(0, 1 - diffLines / maxDiff)\n }\n\n scores.tests = input.testsPassed ? 1 : 0\n scores.typecheck = input.typecheckPassed ? 1 : 0\n if (!input.testsPassed) {\n pass = false\n notes.push('tests failed')\n }\n if (!input.typecheckPassed) {\n pass = false\n notes.push('typecheck failed')\n }\n\n const score = 0.5 * scores.tests + 0.3 * scores.typecheck + 0.2 * scores.diffSize\n const verdict: DefaultVerdict = {\n valid: pass,\n score: Number.isFinite(score) ? score : 0,\n scores,\n }\n if (notes.length > 0) verdict.notes = notes.join('; ')\n return verdict\n}\n\n/**\n * The sandbox `CoderOutput` validator. A thin shim over the shared {@link runCoderChecks} gate\n * (the single source of the no-op / secret-floor / forbidden / diff-size / test / typecheck logic),\n * adapting the sandbox-parsed `CoderOutput` into the gate inputs. On the generic recursive path the\n * same gate is reached via `coderDeliverable(...)` over the worktree-CLI artifact.\n *\n * @experimental\n */\nexport function createCoderValidator(task: CoderTask): Validator<CoderOutput> {\n const constraints: CoderCheckConstraints = {\n maxDiffLines: task.maxDiffLines ?? DEFAULT_MAX_DIFF_LINES,\n forbiddenPaths: task.forbiddenPaths ?? [],\n }\n return {\n async validate(output) {\n return runCoderChecks(\n {\n patch: output.patch,\n testsPassed: output.testResult.passed,\n typecheckPassed: output.typecheckResult.passed,\n },\n constraints,\n )\n },\n }\n}\n\nfunction touchedPathsFromPatch(patch: string): string[] {\n const out = new Set<string>()\n for (const line of patch.split(/\\r?\\n/)) {\n if (line.startsWith('+++ ') || line.startsWith('--- ')) {\n const rest = line.slice(4).trim()\n if (rest === '/dev/null') continue\n const stripped = rest.startsWith('a/') || rest.startsWith('b/') ? rest.slice(2) : rest\n out.add(stripped)\n }\n }\n return [...out]\n}\n\nfunction countDiffLines(patch: string): number {\n let count = 0\n for (const line of patch.split(/\\r?\\n/)) {\n if (\n (line.startsWith('+') || line.startsWith('-')) &&\n !line.startsWith('+++') &&\n !line.startsWith('---')\n ) {\n count += 1\n }\n }\n return count\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction pickString(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n\n/**\n * Concatenate assistant text across the event stream in arrival order,\n * tolerating every harness shape:\n * - claude-code: `data.text` / `data.delta` on text events.\n * - opencode: `message.part.updated` with `data.part.type === 'text'`\n * carrying `data.delta` (incremental) or `data.part.text` (snapshot).\n * Reasoning/thinking parts are excluded — only the final answer text can\n * carry the result JSON. Snapshot text replaces accumulated deltas for the\n * same part so a snapshot+delta mix doesn't double-count.\n */\nfunction collectAssistantText(events: SandboxEvent[]): string {\n const chunks: string[] = []\n for (const event of events) {\n if (!event) continue\n const data = isRecord(event.data) ? event.data : {}\n if (String(event.type ?? '') === 'message.part.updated') {\n const part = isRecord(data.part) ? data.part : {}\n const partType = String(part.type ?? '')\n if (partType !== 'text' && partType !== '') continue\n const text = pickString(data.delta) ?? pickString(part.text)\n if (text) chunks.push(text)\n continue\n }\n const text = pickString(data.text) ?? pickString(data.delta)\n if (text) chunks.push(text)\n }\n return chunks.join('')\n}\n\n/** All parseable fenced JSON blocks in `text`, last-first (the final result\n * block the agent emits is the one we want). */\nfunction fencedJsonBlocks(text: string): unknown[] {\n const out: unknown[] = []\n const matches = [...text.matchAll(/```(?:json)?\\s*([\\s\\S]*?)```/gi)]\n for (let i = matches.length - 1; i >= 0; i -= 1) {\n const body = (matches[i]?.[1] ?? '').trim()\n if (!body) continue\n try {\n out.push(JSON.parse(body))\n } catch {\n // not JSON — keep scanning earlier blocks\n }\n }\n return out\n}\n\nfunction coerceCoderOutput(value: unknown): CoderOutput | undefined {\n if (!isRecord(value)) return undefined\n const branch = pickString(value.branch)\n const patch = pickString(value.patch) ?? ''\n if (branch === undefined) return undefined\n const testResult = coerceCmdResult(value.testResult)\n const typecheckResult = coerceCmdResult(value.typecheckResult)\n const diffStats = coerceDiffStats(value.diffStats)\n return {\n branch,\n patch,\n testResult,\n typecheckResult,\n diffStats,\n reviewerNotes: pickString(value.reviewerNotes),\n }\n}\n\nfunction coerceCmdResult(value: unknown): { passed: boolean; output: string } {\n if (!isRecord(value)) return { passed: false, output: '' }\n return {\n passed: value.passed === true,\n output: pickString(value.output) ?? '',\n }\n}\n\nfunction coerceDiffStats(value: unknown): {\n filesChanged: number\n insertions: number\n deletions: number\n} {\n if (!isRecord(value)) return { filesChanged: 0, insertions: 0, deletions: 0 }\n return {\n filesChanged: toFiniteInt(value.filesChanged),\n insertions: toFiniteInt(value.insertions),\n deletions: toFiniteInt(value.deletions),\n }\n}\n\nfunction toFiniteInt(value: unknown): number {\n if (typeof value !== 'number') return 0\n if (!Number.isFinite(value)) return 0\n return Math.max(0, Math.trunc(value))\n}\n"],"mappings":";AA0BA,IAAM,yBAAyB;AA4DxB,SAAS,aAAa,UAAsD,CAAC,GAMlF;AACA,QAAM,UAAU,QAAQ,WAAW;AACnC,QAAM,OAAO,QAAQ,QAAQ,SAAS,OAAO;AAC7C,QAAM,eAAe,QAAQ,gBAAgB;AAC7C,QAAM,UAAwB;AAAA,IAC5B;AAAA,IACA,aAAa;AAAA,IACb,QAAQ,EAAE,aAAa;AAAA,IACvB,OAAO,QAAQ,QAAQ,EAAE,SAAS,QAAQ,MAAM,IAAI;AAAA,IACpD,OAAO,EAAE,KAAK,MAAM,IAAI,MAAM,OAAO,MAAM,aAAa,KAAK;AAAA,IAC7D,UAAU,EAAE,aAAa,SAAS,MAAM,QAAQ;AAAA,EAClD;AACA,QAAM,SAAqC,EAAE,OAAO,iBAAiB;AACrE,QAAM,YAAoC,QAAQ,OAC9C,qBAAqB,QAAQ,IAAI,IACjC,qBAAqB;AAAA,IACnB,MAAM;AAAA,IACN,UAAU;AAAA,IACV,gBAAgB,CAAC;AAAA,IACjB,cAAc;AAAA,EAChB,CAAC;AACL,QAAM,eAAwC;AAAA,IAC5C;AAAA,IACA;AAAA,IACA,cAAc;AAAA,EAChB;AACA,SAAO,EAAE,SAAS,cAAc,mBAAmB,QAAQ,WAAW,aAAa;AACrF;AAoBO,SAAS,wBAAwB,UAA0C,CAAC,GAKjF;AACA,QAAM,YACJ,QAAQ,aAAa,QAAQ,UAAU,SAAS,IA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IAC3B,QAAQ;AAAA,IAER;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,kBAAkB,OAAyC;AAClE,MAAI,CAAC,SAAS,KAAK,EAAG,QAAO;AAC7B,QAAM,SAAS,WAAW,MAAM,MAAM;AACtC,QAAM,QAAQ,WAAW,MAAM,KAAK,KAAK;AACzC,MAAI,WAAW,OAAW,QAAO;AACjC,QAAM,aAAa,gBAAgB,MAAM,UAAU;AACnD,QAAM,kBAAkB,gBAAgB,MAAM,eAAe;AAC7D,QAAM,YAAY,gBAAgB,MAAM,SAAS;AACjD,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,eAAe,WAAW,MAAM,aAAa;AAAA,EAC/C;AACF;AAEA,SAAS,gBAAgB,OAAqD;AAC5E,MAAI,CAAC,SAAS,KAAK,EAAG,QAAO,EAAE,QAAQ,OAAO,QAAQ,GAAG;AACzD,SAAO;AAAA,IACL,QAAQ,MAAM,WAAW;AAAA,IACzB,QAAQ,WAAW,MAAM,MAAM,KAAK;AAAA,EACtC;AACF;AAEA,SAAS,gBAAgB,OAIvB;AACA,MAAI,CAAC,SAAS,KAAK,EAAG,QAAO,EAAE,cAAc,GAAG,YAAY,GAAG,WAAW,EAAE;AAC5E,SAAO;AAAA,IACL,cAAc,YAAY,MAAM,YAAY;AAAA,IAC5C,YAAY,YAAY,MAAM,UAAU;AAAA,IACxC,WAAW,YAAY,MAAM,SAAS;AAAA,EACxC;AACF;AAEA,SAAS,YAAY,OAAwB;AAC3C,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,MAAI,CAAC,OAAO,SAAS,KAAK,EAAG,QAAO;AACpC,SAAO,KAAK,IAAI,GAAG,KAAK,MAAM,KAAK,CAAC;AACtC;","names":["text"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/loop-runner.ts","../src/loop-runner-bin.ts"],"sourcesContent":["/**\n * @experimental\n *\n * `runDelegatedLoop` — the configured delegated loop-runner.\n *\n * One typed entrypoint a worker agent (or a scheduled routine) calls to run a\n * disciplined loop in a chosen MODE, over agent-runtime's hardened engines:\n *\n * code → build-in-a-loop via the coder delegate (no-op + secret floor,\n * optional reviewer gate, winner-selection)\n * review → code mode with a REQUIRED reviewer (the gate is the point)\n * research → research-in-a-loop with valid-only KB growth (createKbGate)\n * audit → analyze trace/run data → findings (runAnalystLoop, caller-wired)\n * self-improve → closed-loop text/config optimization (selfImprove, held-out gated)\n *\n * It is intentionally a thin façade: the value is that EVERY product reuses the\n * one hardened engine instead of forking delegation logic. The dispatcher owns\n * mode routing, timing, fail-loud on an unregistered mode, and a uniform result\n * shape; each mode's engine is a pre-configured runner in the registry (build it\n * with the factories below, or inject your own / a stub).\n */\n\nimport type { Scenario } from '@tangle-network/agent-eval/campaign'\nimport {\n type SelfImproveOptions,\n type SelfImproveResult,\n selfImprove,\n} from '@tangle-network/agent-eval/contract'\nimport { runAnalystLoop } from './analyst-loop'\nimport type { RunAnalystLoopOpts, RunAnalystLoopResult } from './analyst-loop/types'\nimport { ConfigError } from './errors'\nimport {\n type CoderReviewer,\n type CoderWinnerSelection,\n createDefaultCoderDelegate,\n type DelegateRunCtx,\n} from './mcp/delegates'\nimport { type CreateKbGateOptions, createKbGate, type FactCandidate } from './mcp/kb-gate'\nimport type { DelegateCodeArgs } from './mcp/types'\nimport type { CoderOutput } from './profiles/coder'\nimport {\n type AuthoredCoderHarness,\n type Budget,\n type CoderWinnerStrategy,\n createExecutorRegistry,\n definePersona,\n runPersonified,\n type SandboxClient,\n type WorktreeCoderFanoutOptions,\n type WorktreePatchArtifact,\n worktreeCoderFanout,\n} from './runtime'\n\n/** @experimental Every delegated-loop mode, for validation + CLI surfaces. */\nexport const DELEGATED_LOOP_MODES = ['code', 'review', 'research', 'audit', 'self-improve'] as const\n\n/** @experimental */\nexport type DelegatedLoopMode = (typeof DELEGATED_LOOP_MODES)[number]\n\n/** @experimental Type guard for an untrusted mode string (CLI / config input). */\nexport function isDelegatedLoopMode(value: unknown): value is DelegatedLoopMode {\n return typeof value === 'string' && (DELEGATED_LOOP_MODES as readonly string[]).includes(value)\n}\n\n/** @experimental A pre-configured loop for one mode. Returns the mode's raw\n * output; the dispatcher wraps it in a {@link DelegatedLoopResult}. */\nexport type DelegatedLoopRunner<T = unknown> = (signal: AbortSignal) => Promise<T>\n\n/** @experimental Mode → configured runner. Partial: only register the modes a\n * given product/routine actually uses. */\nexport type DelegatedLoopRegistry = Partial<Record<DelegatedLoopMode, DelegatedLoopRunner>>\n\n/** @experimental Uniform result — never throws from a registered runner; a\n * thrown engine becomes `{ ok: false, error }` so a routine can record + move on. */\nexport interface DelegatedLoopResult<T = unknown> {\n mode: DelegatedLoopMode\n ok: boolean\n output?: T\n error?: string\n durationMs: number\n}\n\n/** @experimental */\nexport interface RunDelegatedLoopOptions {\n signal?: AbortSignal\n /** Clock override for deterministic tests. */\n now?: () => number\n}\n\n/**\n * @experimental\n *\n * Dispatch a configured loop by mode. Fails loud (throws `ConfigError`) when no\n * runner is registered for the mode — a routine pointed at an unwired mode is a\n * config bug, not a silent no-op. A runner that throws is captured as\n * `{ ok: false }` so unattended runs record the failure rather than crash.\n */\nexport async function runDelegatedLoop<T = unknown>(\n mode: DelegatedLoopMode,\n registry: DelegatedLoopRegistry,\n options: RunDelegatedLoopOptions = {},\n): Promise<DelegatedLoopResult<T>> {\n const runner = registry[mode] as DelegatedLoopRunner<T> | undefined\n if (!runner) {\n throw new ConfigError(\n `runDelegatedLoop: no runner registered for mode '${mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n )\n }\n const now = options.now ?? Date.now\n const signal = options.signal ?? new AbortController().signal\n const start = now()\n try {\n const output = await runner(signal)\n return { mode, ok: true, output, durationMs: now() - start }\n } catch (err) {\n return {\n mode,\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n durationMs: now() - start,\n }\n }\n}\n\n/** @experimental Options for the default `code`/`review` runner. */\nexport interface CoderLoopRunnerOptions {\n sandboxClient: SandboxClient\n /** What to build — the delegate args (goal, repoRoot, variants, config, …). */\n args: DelegateCodeArgs\n /** Adversarial reviewer. REQUIRED for `review` mode (see `reviewLoopRunner`). */\n reviewer?: CoderReviewer\n /** Winner-selection strategy. Default `highest-score`. */\n winnerSelection?: CoderWinnerSelection\n /** Harnesses for `variants > 1` fanout. */\n fanoutHarnesses?: string[]\n}\n\n/** @experimental Build a `code`-mode runner over the hardened coder delegate. */\nexport function coderLoopRunner(options: CoderLoopRunnerOptions): DelegatedLoopRunner<CoderOutput> {\n const delegate = createDefaultCoderDelegate({\n sandboxClient: options.sandboxClient,\n ...(options.reviewer ? { reviewer: options.reviewer } : {}),\n ...(options.winnerSelection ? { winnerSelection: options.winnerSelection } : {}),\n ...(options.fanoutHarnesses ? { fanoutHarnesses: options.fanoutHarnesses } : {}),\n })\n return async (signal) => {\n const ctx: DelegateRunCtx = { signal, report: () => {} }\n return delegate(options.args, ctx)\n }\n}\n\n/**\n * @experimental\n *\n * `review` mode = `code` with a REQUIRED reviewer. The gate is the whole point,\n * so the type forces a reviewer (a \"review loop\" with no reviewer is a code loop).\n */\nexport function reviewLoopRunner(\n options: CoderLoopRunnerOptions & { reviewer: CoderReviewer },\n): DelegatedLoopRunner<CoderOutput> {\n return coderLoopRunner(options)\n}\n\n/** @experimental Options for the local-repo `code` runner over the GENERIC recursive path. */\nexport interface WorktreeCoderLoopRunnerOptions {\n /** Absolute path to the local git checkout each worktree is cut from. */\n repoRoot: string\n /** The instruction handed to every authored harness (composed under each profile's systemPrompt). */\n taskPrompt: string\n /** The supervisor-authored harness profiles — one fanout item (one worktree-CLI leaf) each. */\n harnesses: ReadonlyArray<AuthoredCoderHarness>\n /** Conserved budget pool bounding the fanout (equal-k holds by construction). */\n budget: Budget\n /** Shell command run in each worktree to derive the tests-PASS signal. */\n testCmd?: string\n /** Shell command run in each worktree to derive the typecheck-PASS signal. */\n typecheckCmd?: string\n /** Which verification signals the deliverable REQUIRES present-and-passing (default none). */\n require?: ReadonlyArray<'tests' | 'typecheck'>\n /** Diff-size cap (lines). */\n maxDiffLines?: number\n /** Literal path prefixes the patch must not touch (the secret-floor is always on regardless). */\n forbiddenPaths?: string[]\n /** Winner-selection strategy among gated candidates. Default `highest-score`. */\n winnerStrategy?: CoderWinnerStrategy\n /** Test seams forwarded to the worktree-CLI leaves so the runner drives offline. */\n runGit?: WorktreeCoderFanoutOptions['runGit']\n runHarness?: WorktreeCoderFanoutOptions['runHarness']\n runCommand?: WorktreeCoderFanoutOptions['runCommand']\n}\n\n/**\n * @experimental\n *\n * `code` mode on the GENERIC recursive path: author one `AgentProfile` per harness, run them as a\n * `worktreeCoderFanout` (N `createWorktreeCliExecutor` leaves, each `gateOnDeliverable`) through\n * `runPersonified` on the keystone Supervisor. This is the local-repo counterpart to\n * {@link coderLoopRunner} (which drives the in-box harness over a `SandboxClient`): no `runLoop`\n * driver, no role-coupled delegate — the harness list is the fanout, the gate is `coderDeliverable`,\n * the winner is a valid-only selector (NOT `defaultSelectWinner`, whose non-valid fallback would surface an ungated patch). Equal-k holds by the conserved budget pool. Returns the\n * winning patch artifact, or throws when no candidate is delivered (fail loud, never a vacuous done).\n */\nexport function worktreeCoderLoopRunner(\n options: WorktreeCoderLoopRunnerOptions,\n): DelegatedLoopRunner<WorktreePatchArtifact> {\n const shape = worktreeCoderFanout<string>({\n repoRoot: options.repoRoot,\n taskPrompt: options.taskPrompt,\n harnesses: options.harnesses,\n ...(options.testCmd !== undefined ? { testCmd: options.testCmd } : {}),\n ...(options.typecheckCmd !== undefined ? { typecheckCmd: options.typecheckCmd } : {}),\n ...(options.require !== undefined ? { require: options.require } : {}),\n ...(options.maxDiffLines !== undefined ? { maxDiffLines: options.maxDiffLines } : {}),\n ...(options.forbiddenPaths !== undefined ? { forbiddenPaths: options.forbiddenPaths } : {}),\n ...(options.winnerStrategy !== undefined ? { winnerStrategy: options.winnerStrategy } : {}),\n ...(options.runGit ? { runGit: options.runGit } : {}),\n ...(options.runHarness ? { runHarness: options.runHarness } : {}),\n ...(options.runCommand ? { runCommand: options.runCommand } : {}),\n })\n // The persona's only role here is to carry the fanout shape onto the Supervisor; each item's\n // executor is BYO (the gated worktree-CLI leaf), so the registry only needs to pass BYO through.\n const persona = definePersona<WorktreePatchArtifact>({\n name: 'worktree-coder',\n root: { profile: { name: 'worktree-coder' }, harness: null },\n directive: 'deliver a minimal validated patch on a fresh worktree',\n context: { role: 'coder' },\n executors: { registry: createExecutorRegistry() },\n })\n return async (signal) => {\n const result = await runPersonified<string, WorktreePatchArtifact>({\n persona,\n shape,\n task: options.taskPrompt,\n budget: options.budget,\n signal,\n })\n if (result.kind !== 'winner' || result.out.kind !== 'done') {\n const blockers =\n result.kind === 'winner' && result.out.kind === 'blocked'\n ? result.out.blockers.join('; ')\n : `supervisor settled ${result.kind}`\n throw new Error(`worktreeCoderLoopRunner: no delivered patch (${blockers})`)\n }\n return result.out.deliverable\n }\n}\n\n/** @experimental A fact rejected at the KB gate — surfaced, never dropped. */\nexport interface VetoedFact {\n candidate: FactCandidate\n vetoedBy?: string\n reason?: string\n}\n\n/** @experimental */\nexport interface ResearchLoopResult {\n /** Facts that passed the fail-closed gate — safe to write to the KB. */\n accepted: FactCandidate[]\n /** Facts the gate vetoed in the final round — escalate, do not silently drop. */\n vetoed: VetoedFact[]\n /** Research rounds actually run. */\n rounds: number\n}\n\n/** @experimental Options for the default `research` runner. */\nexport interface ResearchLoopRunnerOptions {\n /**\n * The research engine (the consumer's web/doc searcher + extractor). Called\n * each round with the prior round's vetoes so it can re-research the gaps.\n * Returns fact candidates carrying their grounding (`verbatimPassage` +\n * `sourceText`).\n */\n research: (round: number, vetoed: VetoedFact[]) => Promise<FactCandidate[]>\n /** Gate config (extra judges, self-artifact kinds, …). The floor is always on. */\n gate?: CreateKbGateOptions\n /** Max research rounds (correct-on-veto remediation). Default 1. */\n maxRounds?: number\n}\n\n/**\n * @experimental `research` mode — research-in-a-loop with valid-only KB growth.\n *\n * Each round: research → gate every candidate (fail-closed; passage MUST be in\n * the source) → accept the clean ones → re-research the vetoed ones next round,\n * up to `maxRounds`. Vetoed facts in the final round are RETURNED (escalate,\n * never silently dropped) so the caller audits vs retries.\n */\nexport function researchLoopRunner(\n o: ResearchLoopRunnerOptions,\n): DelegatedLoopRunner<ResearchLoopResult> {\n const gate = createKbGate(o.gate)\n const maxRounds = Math.max(1, Math.trunc(o.maxRounds ?? 1))\n return async (signal) => {\n const accepted: FactCandidate[] = []\n let vetoed: VetoedFact[] = []\n let rounds = 0\n for (let round = 0; round < maxRounds; round += 1) {\n if (signal.aborted) break\n rounds += 1\n const candidates = await o.research(round, vetoed)\n if (candidates.length === 0) break\n vetoed = []\n for (const c of candidates) {\n const v = await gate(c)\n if (v.accepted) accepted.push(c)\n else vetoed.push({ candidate: c, vetoedBy: v.vetoedBy, reason: v.reason })\n }\n if (vetoed.length === 0) break\n }\n return { accepted, vetoed, rounds }\n }\n}\n\n/** @experimental `self-improve` mode — agent-eval's one-call closed loop (held-out gated). */\nexport function selfImproveLoopRunner<TScenario extends Scenario, TArtifact>(\n options: SelfImproveOptions<TScenario, TArtifact>,\n): DelegatedLoopRunner<SelfImproveResult<TScenario, TArtifact>> {\n return async () => selfImprove<TScenario, TArtifact>(options)\n}\n\n/** @experimental `audit` mode — analyst loop over captured trace/run data. */\nexport function auditLoopRunner<TProposal = unknown, TEdit = unknown>(\n options: RunAnalystLoopOpts,\n): DelegatedLoopRunner<RunAnalystLoopResult<TProposal, TEdit>> {\n return async () => runAnalystLoop<TProposal, TEdit>(options)\n}\n","#!/usr/bin/env node\n/**\n * @experimental\n *\n * `agent-runtime-loop` — the schedulable entrypoint for the configured\n * delegated loop-runner. A cron job / routine / Makefile target invokes:\n *\n * agent-runtime-loop --mode research --config ./loops.config.js\n *\n * The config module wires the registry (with full access to env / creds —\n * which is why the deps live there, not in this generic bin). It must default-\n * export a `DelegatedLoopRegistry`, or a `() => DelegatedLoopRegistry | Promise<…>`.\n * The bin runs the selected mode, prints the `DelegatedLoopResult` as JSON, and\n * exits 0 on `ok`, 1 on a recorded failure, 2 on a usage/config error.\n */\n\nimport {\n DELEGATED_LOOP_MODES,\n type DelegatedLoopMode,\n type DelegatedLoopRegistry,\n type DelegatedLoopResult,\n isDelegatedLoopMode,\n runDelegatedLoop,\n} from './loop-runner'\n\n/** @experimental Parsed CLI invocation. */\nexport interface LoopRunnerCliArgs {\n mode: string\n /** Loads the registry — the bin wires this from `--config`; tests inject a stub. */\n loadRegistry: () => Promise<DelegatedLoopRegistry> | DelegatedLoopRegistry\n now?: () => number\n}\n\n/** @experimental */\nexport interface LoopRunnerCliResult {\n exitCode: number\n result?: DelegatedLoopResult\n error?: string\n}\n\n/**\n * @experimental\n *\n * Pure CLI core (no process / argv / IO) so it's unit-testable: validate the\n * mode, load the registry, dispatch, map to an exit code (0 ok / 1 failed /\n * 2 usage). Exported for embedding in custom runners + tests.\n */\nexport async function runLoopRunnerCli(args: LoopRunnerCliArgs): Promise<LoopRunnerCliResult> {\n if (!isDelegatedLoopMode(args.mode)) {\n return {\n exitCode: 2,\n error: `unknown mode '${args.mode}' (expected one of: ${DELEGATED_LOOP_MODES.join(', ')})`,\n }\n }\n let registry: DelegatedLoopRegistry\n try {\n registry = await args.loadRegistry()\n } catch (err) {\n return { exitCode: 2, error: `failed to load registry: ${errMsg(err)}` }\n }\n if (!registry[args.mode]) {\n return {\n exitCode: 2,\n error: `config registers no runner for mode '${args.mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n }\n }\n // runDelegatedLoop throws only on a missing runner (guarded above); a failing\n // engine is captured as { ok: false } → exit 1, not a crash.\n const result = await runDelegatedLoop(args.mode as DelegatedLoopMode, registry, {\n ...(args.now ? { now: args.now } : {}),\n })\n return { exitCode: result.ok ? 0 : 1, result }\n}\n\n/** Parse `--mode X --config Y` from an argv tail (`process.argv.slice(2)`). */\nexport function parseLoopRunnerArgv(argv: string[]): { mode?: string; config?: string } {\n const out: { mode?: string; config?: string } = {}\n for (let i = 0; i < argv.length; i += 1) {\n const a = argv[i]\n if (a === '--mode') out.mode = argv[++i]\n else if (a === '--config') out.config = argv[++i]\n else if (a?.startsWith('--mode=')) out.mode = a.slice('--mode='.length)\n else if (a?.startsWith('--config=')) out.config = a.slice('--config='.length)\n }\n return out\n}\n\n/** Normalize a config module's default export → a registry. */\nfunction resolveRegistry(mod: unknown): DelegatedLoopRegistry {\n const def = (mod as { default?: unknown })?.default ?? mod\n const value = typeof def === 'function' ? (def as () => unknown)() : def\n return value as DelegatedLoopRegistry\n}\n\nfunction errMsg(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n\n/** The argv → IO → exit shell. Kept thin; logic lives in `runLoopRunnerCli`. */\nasync function main(): Promise<void> {\n const { mode, config } = parseLoopRunnerArgv(process.argv.slice(2))\n if (!mode || !config) {\n process.stderr.write(\n 'usage: agent-runtime-loop --mode <mode> --config <module>\\n' +\n ` modes: ${DELEGATED_LOOP_MODES.join(' | ')}\\n` +\n ' config: a JS/TS module default-exporting a DelegatedLoopRegistry (or a factory)\\n',\n )\n process.exit(2)\n }\n const { pathToFileURL } = await import('node:url')\n const { resolve } = await import('node:path')\n const cli = await runLoopRunnerCli({\n mode,\n loadRegistry: async () => resolveRegistry(await import(pathToFileURL(resolve(config)).href)),\n })\n process.stdout.write(`${JSON.stringify(cli.result ?? { error: cli.error }, null, 2)}\\n`)\n if (cli.error) process.stderr.write(`${cli.error}\\n`)\n process.exit(cli.exitCode)\n}\n\n// Run only when executed as the bin — never when imported for the testable\n// core, and never when bundled into a runtime that has no `process.argv`\n// (e.g. Cloudflare Workers, where `process` is a shim without `argv`). Reading\n// `process.argv[1]` directly would throw at module load there; `process.argv?.`\n// keeps the guard a no-op instead of crashing the Worker on startup.\nconst invokedScript = typeof process !== 'undefined' ? process.argv?.[1] : undefined\nif (invokedScript && /loop-runner-bin\\.(js|ts|mjs)$/.test(invokedScript)) {\n void main()\n}\n"],"mappings":";;;;;;;;;;;;;;AAuBA;AAAA,EAGE;AAAA,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KAAK,KAAK,CAAC;AAAA;AAAA;AAAA,IAEhD;AACA,YAAQ,KAAK,CAAC;AAAA,EAChB;AACA,QAAM,EAAE,cAAc,IAAI,MAAM,OAAO,KAAU;AACjD,QAAM,EAAE,QAAQ,IAAI,MAAM,OAAO,MAAW;AAC5C,QAAM,MAAM,MAAM,iBAAiB;AAAA,IACjC;AAAA,IACA,cAAc,YAAY,gBAAgB,MAAM,OAAO,cAAc,QAAQ,MAAM,CAAC,EAAE,KAAK;AAAA,EAC7F,CAAC;AACD,UAAQ,OAAO,MAAM,GAAG,KAAK,UAAU,IAAI,UAAU,EAAE,OAAO,IAAI,MAAM,GAAG,MAAM,CAAC,CAAC;AAAA,CAAI;AACvF,MAAI,IAAI,MAAO,SAAQ,OAAO,MAAM,GAAG,IAAI,KAAK;AAAA,CAAI;AACpD,UAAQ,KAAK,IAAI,QAAQ;AAC3B;AAOA,IAAM,gBAAgB,OAAO,YAAY,cAAc,QAAQ,OAAO,CAAC,IAAI;AAC3E,IAAI,iBAAiB,gCAAgC,KAAK,aAAa,GAAG;AACxE,OAAK,KAAK;AACZ;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/mcp/in-process-executor.ts","../src/mcp/bin-helpers.ts","../src/mcp/trace-propagation.ts"],"sourcesContent":["/**\n * @experimental\n *\n * In-process delegation executor — when `agent-runtime-mcp` runs inside a sandbox whose image\n * carries the local coding-harness CLIs (claude / codex / opencode), delegations spawn the harness\n * AS A SUBPROCESS against a git worktree on the SAME filesystem instead of provisioning a sibling\n * sandbox. Zero provisioning latency; worker diffs land in-place; multi-harness fanout = N parallel\n * subprocesses in N parallel worktrees (round-robin `harnesses`).\n *\n * This is a THIN adapter over `runWorktreeHarness` (`./worktree-harness`) — the SAME core the\n * `Scope` leaf `createWorktreeCliExecutor` uses. It only adapts the core to the `SandboxClient`\n * port: `create()` reads the authored profile from `CreateSandboxOptions.backend.profile`, and\n * `streamPrompt` runs the core then projects its result into the `CoderOutput`-shaped `result`\n * event the `coderProfile` parser reads. The §1.5 payload (systemPrompt + model) reaches the\n * harness inside the core — the prompt-only path that dropped it is gone.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport type {\n AgentProfile,\n CreateSandboxOptions,\n SandboxEvent,\n SandboxInstance,\n} from '@tangle-network/sandbox'\nimport type { LoopSandboxPlacement, SandboxClient } from '../runtime'\nimport type { DelegationExecutor } from './executor'\nimport type { LocalHarness } from './local-harness'\nimport type { GitRunner, WorktreeHandle } from './worktree'\nimport { runWorktreeHarness, type WorktreeHarnessResult } from './worktree-harness'\n\n/** @experimental */\nexport interface InProcessExecutorOptions {\n /** Absolute path to the git repo (the workspace). Worktrees go under `<repoRoot>/.coder-variants/`. */\n repoRoot: string\n /** Harnesses to round-robin across `create()` calls. One entry = no fanout. Default `['claude']`. */\n harnesses?: ReadonlyArray<LocalHarness>\n /** Optional per-delegation test command run in the worktree after the harness exits. */\n testCmd?: string\n /** Optional per-delegation typecheck command. Same shape as `testCmd`. */\n typecheckCmd?: string\n /** Wall-clock cap per harness subprocess (ms). Default 5min. */\n harnessTimeoutMs?: number\n /** Wall-clock cap per test/typecheck subprocess (ms). Default 2min. */\n postCheckTimeoutMs?: number\n /** Test seam — override the git runner used by the worktree helpers. */\n runGit?: GitRunner\n /** Test seam — override the harness runner (defaults to the real CLI via `runLocalHarness`). */\n runHarness?: typeof import('./local-harness').runLocalHarness\n /** Test seam — override the post-check runner (defaults to a `sh -c` spawn). A throw is folded\n * into a non-fatal `{exitCode:-1}` so a broken check command fails the signal, not the run. */\n runPostCheck?: (\n cmd: string,\n cwd: string,\n signal?: AbortSignal,\n ) => Promise<{ exitCode: number; stdout: string; stderr: string }>\n}\n\n/** @experimental */\nexport interface InProcessExecutorDescribePlacement extends LoopSandboxPlacement {\n /** Worktree path in the parent sandbox's filesystem (set so traces correlate to on-disk artifacts). */\n worktreePath?: string\n /** Which harness handled this delegation. */\n harness?: LocalHarness\n}\n\ninterface VirtualSandbox extends SandboxInstance {\n __inProcess: {\n runId: string\n harness: LocalHarness\n worktree?: WorktreeHandle\n }\n}\n\n/** The `CoderOutput` shape the `coderProfile` event parser reads off `data.result`. */\ninterface CoderOutput {\n branch: string\n patch: string\n testResult: { passed: boolean; output: string }\n typecheckResult: { passed: boolean; output: string }\n diffStats: { filesChanged: number; insertions: number; deletions: number }\n reviewerNotes?: string\n}\n\nconst DEFAULT_HARNESS_TIMEOUT_MS = 5 * 60 * 1000\nconst DEFAULT_POSTCHECK_TIMEOUT_MS = 2 * 60 * 1000\n\n/**\n * Build an in-process executor. Returns a {@link DelegationExecutor} whose `client.create()`\n * returns a minimal virtual `SandboxInstance`; the kernel calls `streamPrompt(msg)` on it, which\n * runs the shared worktree-harness core and emits one `result` event whose `data.result` is a\n * `CoderOutput`. The authored profile (`backend.profile`) threads its systemPrompt + model into\n * the harness via the core.\n *\n * @experimental\n */\nexport function createInProcessExecutor(options: InProcessExecutorOptions): DelegationExecutor {\n const harnesses =\n options.harnesses && options.harnesses.length > 0\n ? [...options.harnesses]\n : (['claude'] as const)\n const runPostCheck = options.runPostCheck ?? defaultRunPostCheck\n // The core speaks one `runCommand` seam ({exitCode, output}); adapt the post-check seam\n // ({exitCode, stdout, stderr}) onto it, folding a throw into a non-fatal failure signal so a\n // broken check command fails the signal rather than aborting the whole delegation.\n const runCommand = async ({\n command,\n cwd,\n signal,\n }: {\n command: string\n cwd: string\n timeoutMs: number\n signal?: AbortSignal\n }): Promise<{ exitCode: number | null; output: string }> => {\n try {\n const r = await runPostCheck(command, cwd, signal)\n return { exitCode: r.exitCode, output: r.stderr || r.stdout }\n } catch (err) {\n return { exitCode: -1, output: err instanceof Error ? err.message : String(err) }\n }\n }\n\n let callIndex = 0\n\n const client: SandboxClient = {\n async create(opts?: CreateSandboxOptions): Promise<SandboxInstance> {\n const runId = randomUUID()\n const harness = harnesses[callIndex % harnesses.length] as LocalHarness\n callIndex += 1\n // §1.5: the authored profile rides in `backend.profile` (set by `buildBackendOptions`).\n // Without one (a direct test `create()`), fall back to a name-only profile → the harness\n // sees the task prompt with no system prepend, the pre-fix behavior.\n const profile =\n ((opts?.backend as { profile?: AgentProfile } | undefined)?.profile as\n | AgentProfile\n | undefined) ?? ({ name: `in-process-${harness}` } as AgentProfile)\n\n const virtual: VirtualSandbox = {\n id: `in-process-${runId}`,\n __inProcess: { runId, harness },\n async *streamPrompt(\n this: VirtualSandbox,\n message: string | unknown[],\n promptOpts?: { signal?: AbortSignal },\n ): AsyncGenerator<SandboxEvent> {\n const taskPrompt =\n typeof message === 'string'\n ? message\n : message\n .map((p) =>\n typeof p === 'object' && p && 'text' in p\n ? String((p as { text: unknown }).text)\n : '',\n )\n .join('\\n')\n\n // The shared worktree-harness core: worktree → profile-aware harness → diff → checks.\n // A throw cleans up inside the core; on success we own the teardown (the finally).\n const run = await runWorktreeHarness({\n repoRoot: options.repoRoot,\n profile,\n harness,\n taskPrompt,\n runId,\n harnessTimeoutMs: options.harnessTimeoutMs ?? DEFAULT_HARNESS_TIMEOUT_MS,\n checkTimeoutMs: options.postCheckTimeoutMs ?? DEFAULT_POSTCHECK_TIMEOUT_MS,\n ...(options.testCmd !== undefined ? { testCmd: options.testCmd } : {}),\n ...(options.typecheckCmd !== undefined ? { typecheckCmd: options.typecheckCmd } : {}),\n ...(options.runGit ? { runGit: options.runGit } : {}),\n ...(options.runHarness ? { runHarness: options.runHarness } : {}),\n runCommand,\n ...(promptOpts?.signal ? { signal: promptOpts.signal } : {}),\n })\n this.__inProcess.worktree = run.worktree\n\n try {\n yield {\n type: 'in_process.harness.started',\n data: { runId, harness, worktreePath: run.worktree.path, command: harness },\n }\n const h = run.result.harness\n yield {\n type: 'in_process.harness.ended',\n data: {\n runId,\n exitCode: h.exitCode,\n durationMs: h.durationMs,\n killedBySignal: h.killedBySignal,\n timedOut: h.timedOut,\n stdoutBytes: h.stdout.length,\n stderrBytes: h.stderr.length,\n },\n }\n yield {\n type: 'result',\n data: {\n result: toCoderOutput(run.result, harness),\n source: 'in-process-executor',\n harness,\n runId,\n },\n }\n } finally {\n await run.cleanup()\n }\n },\n } as unknown as VirtualSandbox\n\n return virtual\n },\n describePlacement(box: SandboxInstance): InProcessExecutorDescribePlacement {\n const sandboxId = (box as unknown as { id?: string }).id\n const meta = (box as VirtualSandbox).__inProcess\n return {\n kind: 'sibling',\n sandboxId,\n worktreePath: meta?.worktree?.path,\n harness: meta?.harness,\n }\n },\n }\n\n return {\n client,\n placement: 'in-process',\n describe(): string {\n return `in-process (repoRoot=${options.repoRoot}, harnesses=[${harnesses.join(',')}]${\n options.testCmd ? `, testCmd=\"${options.testCmd}\"` : ''\n }${options.typecheckCmd ? `, typecheckCmd=\"${options.typecheckCmd}\"` : ''})`\n },\n }\n}\n\n/** Project the canonical worktree-harness result onto the `CoderOutput` the coder parser reads.\n * A check that did not run (no command configured) is treated as passing — the pre-refactor rule. */\nfunction toCoderOutput(result: WorktreeHarnessResult, harness: LocalHarness): CoderOutput {\n const tests = result.checks?.tests\n const typecheck = result.checks?.typecheck\n return {\n branch: result.branch,\n patch: result.patch,\n testResult: { passed: tests ? tests.passed : true, output: tail(tests?.output ?? '', 4000) },\n typecheckResult: {\n passed: typecheck ? typecheck.passed : true,\n output: tail(typecheck?.output ?? '', 4000),\n },\n diffStats: result.stats,\n reviewerNotes:\n result.harness.exitCode === 0\n ? undefined\n : `harness ${harness} exited ${result.harness.exitCode}${result.harness.timedOut ? ' (timed out)' : ''}`,\n }\n}\n\nasync function defaultRunPostCheck(\n cmd: string,\n cwd: string,\n signal?: AbortSignal,\n): Promise<{ exitCode: number; stdout: string; stderr: string }> {\n const { spawn } = await import('node:child_process')\n return new Promise((resolve, reject) => {\n const child = spawn('sh', ['-c', cmd], { cwd, stdio: 'pipe' })\n let stdout = ''\n let stderr = ''\n child.stdout?.on('data', (c) => {\n stdout += String(c)\n })\n child.stderr?.on('data', (c) => {\n stderr += String(c)\n })\n if (signal) {\n const onAbort = () => {\n if (!child.killed) child.kill('SIGTERM')\n }\n if (signal.aborted) onAbort()\n else signal.addEventListener('abort', onAbort, { once: true })\n }\n const killTimer = setTimeout(() => {\n if (!child.killed) child.kill('SIGTERM')\n }, DEFAULT_POSTCHECK_TIMEOUT_MS)\n if (typeof (killTimer as { unref?: () => void }).unref === 'function') {\n ;(killTimer as { unref: () => void }).unref()\n }\n child.on('error', (err) => {\n clearTimeout(killTimer)\n reject(err)\n })\n child.on('close', (code) => {\n clearTimeout(killTimer)\n resolve({ exitCode: code ?? -1, stdout, stderr })\n })\n })\n}\n\nfunction tail(text: string, max: number): string {\n if (text.length <= max) return text\n return text.slice(text.length - max)\n}\n","/**\n * @experimental\n *\n * Helpers extracted from `bin.ts` so the env-detection + executor-selection\n * logic is unit-testable without spawning a subprocess. The bin imports from\n * here; tests import from here directly.\n */\n\nimport type { SandboxClient } from '../runtime'\nimport {\n createFleetWorkspaceExecutor,\n createSiblingSandboxExecutor,\n type DelegationExecutor,\n type FleetHandle,\n} from './executor'\nimport { createInProcessExecutor } from './in-process-executor'\nimport type { LocalHarness } from './local-harness'\n\n/** @experimental */\nexport interface DetectExecutorArgs {\n sandboxClient: SandboxClient\n /** Raw env (defaults to `process.env`). Pass an explicit map for tests. */\n env?: Record<string, string | undefined>\n /**\n * Override how a fleet handle is resolved from the client + fleet id. The\n * default reads `client.fleets.get(fleetId)` and validates the returned\n * shape against the structural `FleetHandle` contract.\n */\n resolveFleet?: (client: SandboxClient, fleetId: string) => Promise<FleetHandle>\n}\n\n/**\n * Pick the right executor for an MCP server invocation based on env vars.\n *\n * - `TANGLE_FLEET_ID` set → fleet-workspace placement; resolves the handle\n * via `sandboxClient.fleets.get(...)`.\n * - Otherwise → sibling-sandbox placement; each delegation creates a fresh\n * sandbox via `sandboxClient.create(...)`.\n *\n * Fails loud (throws) when fleet mode is requested but the SDK shape is\n * incompatible — the operator chose fleet semantics, silently degrading to\n * sibling mode would lie about workspace topology.\n *\n * @experimental\n */\nexport async function detectExecutor(args: DetectExecutorArgs): Promise<DelegationExecutor> {\n const env = args.env ?? process.env\n\n // In-process (Phase 2.8): parent harness sets AGENT_RUNTIME_IN_SANDBOX=1\n // and points us at the workspace root. Highest-priority — when this is\n // set, delegations spawn local harness CLIs on git worktrees in the\n // SAME filesystem instead of provisioning sibling sandboxes.\n if (env.AGENT_RUNTIME_IN_SANDBOX === '1') {\n const repoRoot = env.AGENT_RUNTIME_REPO_ROOT?.trim()\n if (!repoRoot) {\n throw new Error(\n 'agent-runtime-mcp: AGENT_RUNTIME_IN_SANDBOX=1 requires AGENT_RUNTIME_REPO_ROOT to point at the workspace root',\n )\n }\n return createInProcessExecutor({\n repoRoot,\n harnesses: parseHarnesses(env.AGENT_RUNTIME_LOCAL_HARNESSES),\n testCmd: env.AGENT_RUNTIME_TEST_CMD?.trim() || undefined,\n typecheckCmd: env.AGENT_RUNTIME_TYPECHECK_CMD?.trim() || undefined,\n })\n }\n\n const fleetId = parseFleetId(env.TANGLE_FLEET_ID)\n if (!fleetId) {\n return createSiblingSandboxExecutor({ client: args.sandboxClient })\n }\n const resolveFleet = args.resolveFleet ?? defaultResolveFleet\n const fleet = await resolveFleet(args.sandboxClient, fleetId)\n const excludeMachineIds = parseList(env.TANGLE_FLEET_EXCLUDE_MACHINES)\n return createFleetWorkspaceExecutor({\n fleet,\n excludeMachineIds,\n })\n}\n\nconst KNOWN_HARNESSES: ReadonlyArray<LocalHarness> = ['claude', 'codex', 'opencode']\n\nfunction parseHarnesses(raw: string | undefined): ReadonlyArray<LocalHarness> | undefined {\n if (!raw) return undefined\n const parts = raw\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean)\n if (parts.length === 0) return undefined\n for (const part of parts) {\n if (!KNOWN_HARNESSES.includes(part as LocalHarness)) {\n throw new Error(\n `agent-runtime-mcp: AGENT_RUNTIME_LOCAL_HARNESSES contains unknown harness \"${part}\". Expected: ${KNOWN_HARNESSES.join(', ')}.`,\n )\n }\n }\n return parts as LocalHarness[]\n}\n\ninterface FleetsApi {\n get(fleetId: string): Promise<unknown>\n}\n\nasync function defaultResolveFleet(\n sandboxClient: SandboxClient,\n fleetId: string,\n): Promise<FleetHandle> {\n const fleets = (sandboxClient as unknown as { fleets?: FleetsApi }).fleets\n if (!fleets || typeof fleets.get !== 'function') {\n throw new Error(\n 'agent-runtime-mcp: the configured sandbox client does not expose `.fleets.get`; upgrade @tangle-network/sandbox to >= 0.2.1 or unset TANGLE_FLEET_ID.',\n )\n }\n const raw = await fleets.get(fleetId)\n if (!raw || typeof raw !== 'object') {\n throw new Error(`agent-runtime-mcp: fleets.get(${fleetId}) returned no handle`)\n }\n const handle = raw as Partial<FleetHandle>\n if (typeof handle.fleetId !== 'string' || !Array.isArray(handle.ids)) {\n throw new Error(\n `agent-runtime-mcp: fleet handle for ${fleetId} is missing fleetId/ids — incompatible sandbox SDK shape`,\n )\n }\n if (typeof handle.sandbox !== 'function') {\n throw new Error(\n `agent-runtime-mcp: fleet handle for ${fleetId} is missing sandbox(machineId) — incompatible sandbox SDK shape`,\n )\n }\n return handle as FleetHandle\n}\n\nfunction parseFleetId(raw: string | undefined): string | undefined {\n if (typeof raw !== 'string') return undefined\n const trimmed = raw.trim()\n return trimmed.length > 0 ? trimmed : undefined\n}\n\nfunction parseList(raw: string | undefined): string[] | undefined {\n if (!raw) return undefined\n const list = raw\n .split(',')\n .map((entry) => entry.trim())\n .filter(Boolean)\n return list.length > 0 ? list : undefined\n}\n","/**\n * @experimental\n *\n * Trace context propagation for MCP subprocess.\n *\n * When the MCP server is launched as a child process by a sandbox harness,\n * the parent passes trace context via environment variables:\n *\n * TRACE_ID=<current-run-trace-id>\n * PARENT_SPAN_ID=<span-that-dispatched-the-delegation>\n *\n * The MCP server reads these at startup and uses them as the root of its\n * internal trace tree. All spans emitted by `runLoop` invocations inside\n * the MCP are children of the parent's delegation span.\n *\n * When these env vars are absent, the MCP generates a fresh trace root —\n * the server operates standalone without trace joining.\n */\n\nimport type { OtelExporter } from '../otel-export'\nimport { buildLoopOtelSpans, createOtelExporter } from '../otel-export'\nimport type { LoopTraceEmitter, LoopTraceEvent } from '../runtime/types'\n\nexport interface TraceContext {\n /** Trace id inherited from the parent process, or a fresh one. */\n traceId: string\n /** Parent span id from the delegation that launched this MCP server. */\n parentSpanId?: string\n}\n\n/**\n * Read trace context from the process environment.\n * Returns a context with inherited ids or a freshly generated root.\n */\nexport function readTraceContextFromEnv(): TraceContext {\n const traceId = process.env.TRACE_ID || generateTraceId()\n const parentSpanId = process.env.PARENT_SPAN_ID || undefined\n return { traceId, parentSpanId }\n}\n\n/**\n * Create a LoopTraceEmitter that:\n * 1. Parents all spans under the inherited PARENT_SPAN_ID.\n * 2. Exports spans to OTEL when OTEL_EXPORTER_OTLP_ENDPOINT is set.\n *\n * Returns both the emitter and the optional exporter handle for shutdown.\n */\nexport function createPropagatingTraceEmitter(ctx: TraceContext): {\n emitter: LoopTraceEmitter\n exporter: OtelExporter | undefined\n context: TraceContext\n} {\n const exporter = createOtelExporter()\n\n // Buffer events per loop run, then emit the full nested span tree on\n // `loop.ended` so the topology hierarchy (loop → round → branch) reaches the\n // OTLP collector — not a flat list of zero-duration point spans. A run that\n // never reaches `loop.ended` (hard abort) drops its buffer; acceptable for\n // the short-lived MCP subprocess.\n const buffers = new Map<string, LoopTraceEvent[]>()\n\n const emitter: LoopTraceEmitter = {\n emit(event: LoopTraceEvent) {\n if (!exporter) return\n const buf = buffers.get(event.runId)\n if (buf) buf.push(event)\n else buffers.set(event.runId, [event])\n if (event.kind === 'loop.ended') {\n const events = buffers.get(event.runId) ?? [event]\n buffers.delete(event.runId)\n for (const span of buildLoopOtelSpans(events, ctx.traceId, ctx.parentSpanId)) {\n exporter.exportSpan(span)\n }\n }\n },\n }\n\n return { emitter, exporter, context: ctx }\n}\n\n/**\n * Build env vars to pass to a child MCP subprocess so it inherits the\n * current trace context.\n */\nexport function traceContextToEnv(ctx: TraceContext): Record<string, string> {\n const env: Record<string, string> = { TRACE_ID: ctx.traceId }\n if (ctx.parentSpanId) env.PARENT_SPAN_ID = ctx.parentSpanId\n return env\n}\n\nfunction generateTraceId(): string {\n const bytes = new Uint8Array(16)\n if (typeof globalThis.crypto?.getRandomValues === 'function') {\n globalThis.crypto.getRandomValues(bytes)\n } else {\n for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256)\n }\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('')\n}\n"],"mappings":";;;;;;;;;;;;;AAiBA,SAAS,kBAAkB;AAkE3B,IAAM,6BAA6B,IAAI,KAAK;AAC5C,IAAM,+BAA+B,IAAI,KAAK;AAWvC,SAAS,wBAAwB,SAAuD;AAC7F,QAAM,YACJ,QAAQ,aAAa,QAAQ,UAAU,SAAS,IAC5C,CAAC,GAAG,QAAQ,SAAS,IACpB,CAAC,QAAQ;AAChB,QAAM,eAAe,QAAQ,gBAAgB;AAI7C,QAAM,aAAa,OAAO;AAAA,IACxB;AAAA,IACA;AAAA,IACA;AAAA,EACF,MAK4D;AAC1D,QAAI;AACF,YAAM,IAAI,MAAM,aAAa,SAAS,KAAK,MAAM;AACjD,aAAO,EAAE,UAAU,EAAE,UAAU,QAAQ,EAAE,UAAU,EAAE,OAAO;AAAA,IAC9D,SAAS,KAAK;AACZ,aAAO,EAAE,UAAU,IAAI,QAAQ,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,EAAE;AAAA,IAClF;AAAA,EACF;AAEA,MAAI,YAAY;AAEhB,QAAM,SAAwB;AAAA,IAC5B,MAAM,OAAO,MAAuD;AAClE,YAAM,QAAQ,WAAW;AACzB,YAAM,UAAU,UAAU,YAAY,UAAU,MAAM;AACtD,mBAAa;AAIb,YAAM,UACF,MAAM,SAAoD,WAEzC,EAAE,MAAM,cAAc,OAAO,GAAG;AAErD,YAAM,UAA0B;AAAA,QAC9B,IAAI,cAAc,KAAK;AAAA,QACvB,aAAa,EAAE,OAAO,QAAQ;AAAA,QAC9B,OAAO,aAEL,SACA,YAC8B;AAC9B,gBAAM,aACJ,OAAO,YAAY,WACf,UACA,QACG;AAA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MAAM,KAAK;AAC1B,mBAAW,QAAQ,mBAAmB,QAAQ,IAAI,SAAS,IAAI,YAAY,GAAG;AAC5E,mBAAS,WAAW,IAAI;AAAA,QAC1B;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO,EAAE,SAAS,UAAU,SAAS,IAAI;AAC3C;AAMO,SAAS,kBAAkB,KAA2C;AAC3E,QAAM,MAA8B,EAAE,UAAU,IAAI,QAAQ;AAC5D,MAAI,IAAI,aAAc,KAAI,iBAAiB,IAAI;AAC/C,SAAO;AACT;AAEA,SAAS,kBAA0B;AACjC,QAAM,QAAQ,IAAI,WAAW,EAAE;AAC/B,MAAI,OAAO,WAAW,QAAQ,oBAAoB,YAAY;AAC5D,eAAW,OAAO,gBAAgB,KAAK;AAAA,EACzC,OAAO;AACL,aAAS,IAAI,GAAG,IAAI,IAAI,IAAK,OAAM,CAAC,IAAI,KAAK,MAAM,KAAK,OAAO,IAAI,GAAG;AAAA,EACxE;AACA,SAAO,MAAM,KAAK,KAAK,EACpB,IAAI,CAAC,MAAM,EAAE,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC,EAC1C,KAAK,EAAE;AACZ;","names":[]}
@@ -1,163 +0,0 @@
1
- import { AgentProfile } from '@tangle-network/sandbox';
2
- import { O as OutputAdapter, V as Validator, A as AgentRunSpec, D as Driver } from './types-CUzjRFZ3.js';
3
- import { DefaultVerdict } from '@tangle-network/agent-eval';
4
-
5
- /**
6
- * @experimental
7
- *
8
- * `coderProfile` — opinionated preset for code-modification tasks.
9
- *
10
- * The agent is told to:
11
- * - work on a fresh branch inside the sandbox workspace
12
- * - keep the patch minimal (under `maxDiffLines`)
13
- * - avoid `forbiddenPaths`
14
- * - run `testCmd` and `typecheckCmd`
15
- * - emit a final JSON result the output adapter parses
16
- *
17
- * The profile is stateless and agent-agnostic — `harness` selects the
18
- * sandbox-SDK backend (`claude-code`, `codex`, `opencode/*`). For
19
- * heterogeneous fanout, use `multiHarnessCoderFanout`.
20
- */
21
-
22
- /** @experimental */
23
- interface CoderTask {
24
- /** What the agent must accomplish. Free-form prose. */
25
- goal: string;
26
- /** Absolute path inside the sandbox where the repo lives. */
27
- repoRoot: string;
28
- /** Default `main`. The branch the agent diffs against. */
29
- baseBranch?: string;
30
- /** Default `pnpm test --run`. */
31
- testCmd?: string;
32
- /** Default `pnpm typecheck`. */
33
- typecheckCmd?: string;
34
- /** Files the agent may inspect for context. Surfaced verbatim in the prompt. */
35
- contextFiles?: string[];
36
- /**
37
- * Paths the agent must not touch. Validator hard-fails on any match.
38
- * Use glob-free literal path prefixes for unambiguous enforcement.
39
- */
40
- forbiddenPaths?: string[];
41
- /** Default 400. Hard cap; validator hard-fails when exceeded. */
42
- maxDiffLines?: number;
43
- }
44
- /** @experimental */
45
- interface CoderOutput {
46
- /** Branch the agent wrote the patch on. */
47
- branch: string;
48
- /** Unified diff (`git diff <base>..HEAD`). */
49
- patch: string;
50
- testResult: {
51
- passed: boolean;
52
- output: string;
53
- };
54
- typecheckResult: {
55
- passed: boolean;
56
- output: string;
57
- };
58
- diffStats: {
59
- filesChanged: number;
60
- insertions: number;
61
- deletions: number;
62
- };
63
- /** Optional reviewer commentary surfaced by the agent. */
64
- reviewerNotes?: string;
65
- }
66
- /** @experimental */
67
- interface CoderProfileOptions {
68
- /** Sandbox-SDK backend.type. Default `'claude-code'`. */
69
- harness?: string;
70
- /** Default model id passed in `AgentProfile.model.default`. */
71
- model?: string;
72
- /** Custom system prompt replacement. Default = built-in coder preset. */
73
- systemPrompt?: string;
74
- /** Stable name for `AgentRunSpec.name`. Default = `coder-${harness}`. */
75
- name?: string;
76
- }
77
- /**
78
- * Build a coder preset.
79
- *
80
- * `validator` enforces test + typecheck + a 400-line default diff cap. For
81
- * per-task `forbiddenPaths` / `maxDiffLines` enforcement, pass `task` here
82
- * — the returned validator closes over its constraints. Without a task
83
- * the validator falls back to the default cap and skips path enforcement.
84
- *
85
- * @experimental
86
- */
87
- declare function coderProfile(options?: CoderProfileOptions & {
88
- task?: CoderTask;
89
- }): {
90
- profile: AgentProfile;
91
- taskToPrompt: (task: CoderTask) => string;
92
- output: OutputAdapter<CoderOutput>;
93
- validator: Validator<CoderOutput>;
94
- agentRunSpec: AgentRunSpec<CoderTask>;
95
- };
96
- /** @experimental */
97
- interface MultiHarnessCoderFanoutOptions {
98
- /**
99
- * Sandbox-SDK backend.type identifiers, one per parallel agent. Default:
100
- * `['claude-code', 'codex', 'opencode/zai-coding-plan/glm-5.1']`.
101
- */
102
- harnesses?: string[];
103
- /** Optional per-harness model override. Indexed parallel to `harnesses`. */
104
- models?: (string | undefined)[];
105
- }
106
- /**
107
- * The multi-harness coder fanout driving `createDefaultCoderDelegate`'s `variants>1`
108
- * sandbox-session path. (`worktreeCoderFanout` is the local-repo generic counterpart for
109
- * new code; both are first-class.)
110
- *
111
- * @experimental
112
- */
113
- declare function multiHarnessCoderFanout(options?: MultiHarnessCoderFanoutOptions): {
114
- agentRuns: AgentRunSpec<CoderTask>[];
115
- output: OutputAdapter<CoderOutput>;
116
- validator: Validator<CoderOutput>;
117
- driver: Driver<CoderTask, CoderOutput, 'pick-winner' | 'fail'>;
118
- };
119
- /** @experimental Inputs the mechanical coder gate decides on — a captured patch plus the
120
- * test/typecheck PASS signals derived for it. Shared by `createCoderValidator` (sandbox-event
121
- * shape) and the generic worktree-CLI deliverable (which derives `testsPassed`/`typecheckPassed`
122
- * by running the commands in the worktree). */
123
- interface CoderCheckInput {
124
- /** The unified diff produced by the run. */
125
- patch: string;
126
- /** Did `testCmd` exit clean? */
127
- testsPassed: boolean;
128
- /** Did `typecheckCmd` exit clean? */
129
- typecheckPassed: boolean;
130
- }
131
- /** @experimental The per-task constraints the mechanical gate enforces. */
132
- interface CoderCheckConstraints {
133
- /** Default 400. Hard cap; gate fails when exceeded. */
134
- maxDiffLines?: number;
135
- /** Literal path prefixes the patch must not touch. */
136
- forbiddenPaths?: string[];
137
- }
138
- /**
139
- * @experimental
140
- *
141
- * The pure mechanical coder gate — the SINGLE source of the no-op / secret-path floor /
142
- * diff-size / forbidden-path / test / typecheck checks. No I/O: it scores a patch + its
143
- * already-derived pass signals. Both the `createCoderValidator` shim (sandbox `CoderOutput`)
144
- * and the generic worktree-CLI `coderDeliverable` (which runs the commands itself) call this,
145
- * so the gate logic never forks.
146
- *
147
- * Checks in order: (1) no-op rejection, (2) always-on secret-path floor (independent of
148
- * `forbiddenPaths`), (3) forbidden-path, (4) diff-size cap, (5) tests, (6) typecheck.
149
- * Aggregate score: `0.5*tests + 0.3*typecheck + 0.2*(1 - diffLines/maxDiff)`; `valid` is the
150
- * conjunction of all six.
151
- */
152
- declare function runCoderChecks(input: CoderCheckInput, constraints?: CoderCheckConstraints): DefaultVerdict;
153
- /**
154
- * The sandbox `CoderOutput` validator. A thin shim over the shared {@link runCoderChecks} gate
155
- * (the single source of the no-op / secret-floor / forbidden / diff-size / test / typecheck logic),
156
- * adapting the sandbox-parsed `CoderOutput` into the gate inputs. On the generic recursive path the
157
- * same gate is reached via `coderDeliverable(...)` over the worktree-CLI artifact.
158
- *
159
- * @experimental
160
- */
161
- declare function createCoderValidator(task: CoderTask): Validator<CoderOutput>;
162
-
163
- export { type CoderOutput as C, type MultiHarnessCoderFanoutOptions as M, type CoderCheckConstraints as a, type CoderCheckInput as b, type CoderProfileOptions as c, type CoderTask as d, coderProfile as e, createCoderValidator as f, multiHarnessCoderFanout as m, runCoderChecks as r };