@tangle-network/agent-runtime 0.60.0 → 0.62.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 (58) hide show
  1. package/dist/agent.d.ts +3 -2
  2. package/dist/agent.js +2 -3
  3. package/dist/agent.js.map +1 -1
  4. package/dist/analyst-loop.d.ts +1 -1
  5. package/dist/chunk-DVQGYDN5.js +59 -0
  6. package/dist/chunk-DVQGYDN5.js.map +1 -0
  7. package/dist/{chunk-ZWGEA722.js → chunk-E4X4FNQZ.js} +2 -2
  8. package/dist/{chunk-45D64J7B.js → chunk-MT4XM3G6.js} +191 -100
  9. package/dist/chunk-MT4XM3G6.js.map +1 -0
  10. package/dist/{chunk-GLMFBUKT.js → chunk-O2UPHN7X.js} +1 -1
  11. package/dist/chunk-O2UPHN7X.js.map +1 -0
  12. package/dist/{chunk-MMDIORZY.js → chunk-RTNMMHWR.js} +4 -23
  13. package/dist/chunk-RTNMMHWR.js.map +1 -0
  14. package/dist/chunk-RYD7ND4A.js +475 -0
  15. package/dist/chunk-RYD7ND4A.js.map +1 -0
  16. package/dist/{chunk-IN7WHMGZ.js → chunk-YWO4H64E.js} +47 -7
  17. package/dist/chunk-YWO4H64E.js.map +1 -0
  18. package/dist/coder-2leJPOvC.d.ts +52 -0
  19. package/dist/coordination-Curpzeyc.d.ts +381 -0
  20. package/dist/{delegates-C94qchkz.d.ts → delegates-CLFNAKyi.d.ts} +650 -21
  21. package/dist/improvement.js +1 -1
  22. package/dist/index.d.ts +10 -6
  23. package/dist/index.js +10 -10
  24. package/dist/intelligence.d.ts +3 -2
  25. package/dist/intelligence.js.map +1 -1
  26. package/dist/{loop-runner-bin-Noz7P-mS.d.ts → loop-runner-bin-B6dzNZC8.d.ts} +46 -12
  27. package/dist/loop-runner-bin.d.ts +8 -4
  28. package/dist/loop-runner-bin.js +5 -5
  29. package/dist/loops.d.ts +8 -6
  30. package/dist/loops.js +18 -7
  31. package/dist/mcp/bin.js +11 -11
  32. package/dist/mcp/bin.js.map +1 -1
  33. package/dist/mcp/index.d.ts +13 -12
  34. package/dist/mcp/index.js +8 -8
  35. package/dist/{openai-tools-d4GKwgya.d.ts → openai-tools-CA2N3-Ak.d.ts} +1 -1
  36. package/dist/profiles.d.ts +9 -10
  37. package/dist/profiles.js +5 -7
  38. package/dist/profiles.js.map +1 -1
  39. package/dist/{run-loop-CcqfR_gy.d.ts → run-loop-D3PwlG7J.d.ts} +1 -1
  40. package/dist/runtime.d.ts +31 -1046
  41. package/dist/runtime.js +18 -7
  42. package/dist/{types-CUzjRFZ3.d.ts → types-Crxftafi.d.ts} +2 -2
  43. package/dist/workflow.d.ts +2 -2
  44. package/dist/workflow.js +2 -3
  45. package/dist/workflow.js.map +1 -1
  46. package/dist/worktree-fanout-DUiKPApb.d.ts +1099 -0
  47. package/package.json +6 -2
  48. package/dist/chunk-45D64J7B.js.map +0 -1
  49. package/dist/chunk-4FEUFYOY.js +0 -282
  50. package/dist/chunk-4FEUFYOY.js.map +0 -1
  51. package/dist/chunk-7QYOXFCD.js +0 -293
  52. package/dist/chunk-7QYOXFCD.js.map +0 -1
  53. package/dist/chunk-GLMFBUKT.js.map +0 -1
  54. package/dist/chunk-IN7WHMGZ.js.map +0 -1
  55. package/dist/chunk-MMDIORZY.js.map +0 -1
  56. package/dist/coder-CybltHEm.d.ts +0 -163
  57. package/dist/coordination-Biw19JzN.d.ts +0 -944
  58. /package/dist/{chunk-ZWGEA722.js.map → chunk-E4X4FNQZ.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/mcp/executor.ts","../src/mcp/detached-coder.ts","../src/mcp/delegates.ts"],"sourcesContent":["/**\n * @experimental\n *\n * Delegation executors — the layer between MCP delegates and the sandbox\n * substrate. Each executor exposes a {@link SandboxClient} the kernel\n * consumes plus a placement tag so the trace pipeline can correlate workers\n * with their physical placement.\n *\n * Two implementations ship in-box:\n *\n * - {@link createSiblingSandboxExecutor} — every delegation spawns a fresh\n * sandbox sibling to the caller. Default when the MCP server runs as a\n * standalone CLI mounted outside a fleet.\n *\n * - {@link createFleetWorkspaceExecutor} — delegations dispatch onto machines\n * in the caller's existing fleet so worker diffs land directly on the\n * caller's filesystem (the fleet's shared workspace). Selected when the\n * parent sandbox passes `TANGLE_FLEET_ID` into the MCP server's env.\n */\n\nimport type { CreateSandboxOptions, SandboxInstance } from '@tangle-network/sandbox'\nimport type { LoopSandboxPlacement, SandboxClient } from '../runtime'\n\n/** @experimental */\nexport interface DelegationExecutor {\n /** Sandbox client the kernel calls. Returned with `describePlacement` set. */\n readonly client: SandboxClient\n /** Best-effort one-liner used in stderr boot logs and diagnostics. */\n describe(): string\n /**\n * Where delegated work physically runs. `sibling` and `fleet` placements are\n * session-backed (boxes expose `driveTurn`, so detached dispatch + resume\n * apply); `in-process` spawns local harness CLIs with no sandbox session to\n * detach. Optional so consumer-implemented executors stay source-compatible;\n * absent means \"unknown\" and detached dispatch is not enabled for it.\n */\n readonly placement?: 'sibling' | 'fleet' | 'in-process'\n}\n\n/** @experimental */\nexport interface SiblingSandboxExecutorOptions {\n client: SandboxClient\n}\n\n/**\n * Wrap a raw sandbox SDK client so the kernel emits\n * `loop.iteration.dispatch` events with `{ placement: 'sibling', sandboxId }`.\n *\n * The returned client `.create()` delegates to the underlying client; the\n * only added behavior is a `describePlacement` tag the kernel reads.\n *\n * @experimental\n */\nexport function createSiblingSandboxExecutor(\n options: SiblingSandboxExecutorOptions,\n): DelegationExecutor {\n const underlying = options.client\n const client: SandboxClient = {\n create(opts?: CreateSandboxOptions): Promise<SandboxInstance> {\n return underlying.create(opts)\n },\n describePlacement(box: SandboxInstance): LoopSandboxPlacement {\n return { kind: 'sibling', sandboxId: readId(box) }\n },\n }\n return {\n client,\n placement: 'sibling',\n describe(): string {\n return 'sibling-sandbox (each delegation = fresh sandbox via client.create)'\n },\n }\n}\n\n/**\n * Minimal `SandboxFleet` surface the fleet executor calls. Declared\n * structurally so tests can pass an in-memory stub without instantiating the\n * sandbox SDK.\n *\n * @experimental\n */\nexport interface FleetHandle {\n readonly fleetId: string\n /** Machine ids in dispatch-eligible order. The executor round-robins. */\n readonly ids: ReadonlyArray<string>\n /** Resolve a machine id to its `SandboxInstance` — that machine is mounted\n * on the fleet's shared workspace, so any diff the worker writes lands on\n * every other fleet machine's filesystem too. */\n sandbox(machineId: string): Promise<SandboxInstance>\n}\n\n/** @experimental */\nexport interface FleetWorkspaceExecutorOptions {\n fleet: FleetHandle\n /**\n * Override the machine-selection policy. Default = round-robin across\n * `fleet.ids`, skipping the optional `excludeMachineIds` set (typically the\n * coordinator machine the MCP server is running on).\n */\n selectMachine?: (call: { callIndex: number; ids: ReadonlyArray<string> }) => string\n /**\n * Machine ids to skip during default round-robin. Set to the caller's own\n * machineId so workers don't compete with the orchestrator on the same VM.\n */\n excludeMachineIds?: ReadonlyArray<string>\n}\n\n/**\n * Build an executor that resolves each delegated iteration to an existing\n * machine in `fleet`. The fleet's shared-workspace policy means the worker\n * machine sees the caller's filesystem — diffs land in-place with no\n * cross-sandbox copy step.\n *\n * @experimental\n */\nexport function createFleetWorkspaceExecutor(\n options: FleetWorkspaceExecutorOptions,\n): DelegationExecutor {\n const fleet = options.fleet\n const exclude = new Set(options.excludeMachineIds ?? [])\n let callIndex = 0\n // machineId-by-sandboxId, populated as we resolve machines so\n // `describePlacement` can recover the assignment from the SandboxInstance\n // the kernel hands back.\n const placementBySandboxId = new Map<string, { machineId: string }>()\n\n const client: SandboxClient = {\n async create(): Promise<SandboxInstance> {\n const ids = fleet.ids.filter((id) => !exclude.has(id))\n if (ids.length === 0) {\n throw new Error(\n `agent-runtime: fleet ${fleet.fleetId} has no eligible worker machines (ids=[${fleet.ids.join(',')}], excluded=[${[...exclude].join(',')}])`,\n )\n }\n const selector = options.selectMachine\n const machineId = selector ? selector({ callIndex, ids }) : ids[callIndex % ids.length]\n callIndex += 1\n if (typeof machineId !== 'string' || machineId.length === 0) {\n throw new Error('agent-runtime: fleet executor selectMachine returned an empty machine id')\n }\n const box = await fleet.sandbox(machineId)\n const sandboxId = readId(box)\n if (sandboxId) placementBySandboxId.set(sandboxId, { machineId })\n return box\n },\n describePlacement(box: SandboxInstance): LoopSandboxPlacement {\n const sandboxId = readId(box)\n const recorded = sandboxId ? placementBySandboxId.get(sandboxId) : undefined\n return {\n kind: 'fleet',\n sandboxId,\n fleetId: fleet.fleetId,\n machineId: recorded?.machineId,\n }\n },\n }\n\n return {\n client,\n placement: 'fleet',\n describe(): string {\n const excluded = exclude.size > 0 ? ` (excluded=[${[...exclude].join(',')}])` : ''\n return `fleet-workspace (fleetId=${fleet.fleetId}, machines=[${fleet.ids.join(',')}]${excluded})`\n },\n }\n}\n\nfunction readId(box: SandboxInstance): string | undefined {\n const raw = (box as unknown as { id?: unknown }).id\n return typeof raw === 'string' && raw.length > 0 ? raw : undefined\n}\n","/**\n * @experimental\n *\n * Sandbox-session coder decode layer. The sandbox-session delegate (`./delegates`) and the\n * cross-restart resume driver (`./bin`) run the in-box harness over a `SandboxClient` and need to\n * (a) build an `AgentRunSpec` from the authored coder profile, (b) decode the harness event stream\n * into a structured `CoderOutput`, and (c) gate it with the shared mechanical checks. This is the\n * MCP server's built-in `delegate_code` path — it is the live default delegate, NOT dormant — and is\n * kept separate from the generic recursive path: `worktreeFanout` instead settles the raw\n * `WorktreePatchArtifact` and gates via `patchDelivered`. Only the OPTIONAL cross-restart resume\n * (the `driveTurn` tick) is opt-in (`MCP_ENABLE_DETACHED_RESUME`); the held-stream delegate is\n * always live. Prefer `worktreeFanout` / `worktreeLoopRunner` for NEW local-repo coding.\n *\n * The decode tolerates two `result`-event shapes:\n * 1. the in-process executor's raw worktree-harness result (`{ branch, patch, stats, checks }`),\n * projected onto `CoderOutput`; and\n * 2. an LLM-emitted JSON block (`{ branch, patch, testResult, typecheckResult, diffStats }`),\n * lifted onto `data.result` or scanned out of the assistant transcript (any harness shape).\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport type { SandboxEvent } from '@tangle-network/sandbox'\nimport { type CoderTask, coderProfile, coderTaskToPrompt } from '../profiles/coder'\nimport { type CoderCheckConstraints, runCoderChecks } from '../runtime/supervise/patch-checks'\nimport type { AgentRunSpec, Driver, OutputAdapter, Validator } from '../runtime/types'\n\nconst DEFAULT_MAX_DIFF_LINES = 400\n\n/** @experimental The structured coder result the sandbox-session path decodes + gates. */\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 Overrides for one authored coder run on the sandbox-session path. */\nexport interface CoderRunSpecOptions {\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 = the `coderProfile` constant's prompt. */\n systemPrompt?: string\n /** Stable name for `AgentRunSpec.name`. Default = `coder-${harness}`. */\n name?: string\n}\n\n/** Build the authored `AgentProfile` for one harness on the sandbox-session path, applying the\n * optional per-run overrides over the `coderProfile` constant. */\nfunction coderRunProfile(options: CoderRunSpecOptions): AgentProfile {\n const harness = options.harness ?? 'claude-code'\n const name = options.name ?? `coder-${harness}`\n return {\n ...coderProfile,\n name,\n ...(options.systemPrompt ? { prompt: { systemPrompt: options.systemPrompt } } : {}),\n model: options.model ? { default: options.model } : undefined,\n metadata: { ...coderProfile.metadata, backendType: harness },\n }\n}\n\n/** @experimental Build the `AgentRunSpec<CoderTask>` the sandbox-session `runLoop` path drives. */\nexport function coderRunSpec(options: CoderRunSpecOptions = {}): AgentRunSpec<CoderTask> {\n return {\n name: options.name ?? `coder-${options.harness ?? 'claude-code'}`,\n profile: coderRunProfile(options),\n taskToPrompt: coderTaskToPrompt,\n }\n}\n\n/** @experimental The output adapter the sandbox-session path decodes the harness stream with. */\nexport const coderOutputAdapter: OutputAdapter<CoderOutput> = { parse: parseCoderEvents }\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 the sandbox-session delegate's `variants>1` path.\n * (`worktreeFanout` is the local-repo generic counterpart for new code.)\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) => coderRunSpec({ harness, model: models[i] }))\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: coderOutputAdapter, validator: defaultCoderValidator(), driver }\n}\n\n/**\n * The sandbox `CoderOutput` validator. A thin shim over the shared {@link runCoderChecks} gate,\n * adapting the parsed `CoderOutput` into the gate inputs.\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 defaultCoderValidator(): Validator<CoderOutput> {\n return createCoderValidator({\n goal: '',\n repoRoot: '',\n forbiddenPaths: [],\n maxDiffLines: DEFAULT_MAX_DIFF_LINES,\n })\n}\n\n/**\n * Walk the event stream and return the structured coder payload.\n *\n * A `result` / `final` event lifts the structured payload onto `data.result`. That payload is\n * either the in-process executor's raw worktree-harness result (projected onto `CoderOutput`) or an\n * LLM-emitted `CoderOutput`-shaped JSON. When neither is present, the scan accumulates ALL assistant\n * text in stream order (any harness shape) and takes the last fenced JSON block that coerces —\n * claude-code lifts whole text onto `data.text`/`data.delta`; opencode streams `message.part.updated`\n * fragments, so the final block is split across many events and never whole in one.\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 payload = data.result ?? data.output ?? data\n const projected = projectWorktreeArtifact(payload)\n if (projected) return projected\n const direct = coerceCoderOutput(payload)\n if (direct) return direct\n }\n }\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/** Project the in-process executor's raw worktree-harness result (`{ branch, patch, stats, checks,\n * harness }`) onto `CoderOutput`. A check that did not run is treated as passing (the executor\n * simply didn't run that command). Returns undefined when the payload is not a worktree artifact. */\nfunction projectWorktreeArtifact(value: unknown): CoderOutput | undefined {\n if (!isRecord(value)) return undefined\n const stats = value.stats\n if (!isRecord(stats)) return undefined // not the raw artifact shape\n const branch = pickString(value.branch) ?? ''\n const patch = pickString(value.patch) ?? ''\n const checks = isRecord(value.checks) ? value.checks : {}\n const tests = isRecord(checks.tests) ? checks.tests : undefined\n const typecheck = isRecord(checks.typecheck) ? checks.typecheck : undefined\n const harness = isRecord(value.harness) ? value.harness : undefined\n const exitCode = harness ? toFiniteInt(harness.exitCode) : 0\n const timedOut = harness?.timedOut === true\n const harnessName = harness ? (pickString(harness.name) ?? 'harness') : 'harness'\n return {\n branch,\n patch,\n testResult: {\n passed: tests ? tests.passed === true : true,\n output: tail(pickString(tests?.output) ?? '', 4000),\n },\n typecheckResult: {\n passed: typecheck ? typecheck.passed === true : true,\n output: tail(pickString(typecheck?.output) ?? '', 4000),\n },\n diffStats: {\n filesChanged: toFiniteInt(stats.filesChanged),\n insertions: toFiniteInt(stats.insertions),\n deletions: toFiniteInt(stats.deletions),\n },\n ...(exitCode !== 0\n ? {\n reviewerNotes: `harness ${harnessName} exited ${exitCode}${timedOut ? ' (timed out)' : ''}`,\n }\n : {}),\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\n/** Keep the last `max` chars of a diagnostic string — harness stdout can be large; the gate reads\n * `passed`, not this text, so only the tail is retained for traces/logs. */\nfunction tail(text: string, max: number): string {\n return text.length <= max ? text : text.slice(text.length - max)\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, tolerating every harness\n * shape: claude-code lifts text onto `data.text`/`data.delta`; opencode streams\n * `message.part.updated` with `data.part.type === 'text'` carrying `data.delta`/`data.part.text`.\n * Reasoning/thinking parts are excluded — only the final answer text carries the result JSON.\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 block the agent emits\n * 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 return {\n branch,\n patch,\n testResult: coerceCmdResult(value.testResult),\n typecheckResult: coerceCmdResult(value.typecheckResult),\n diffStats: coerceDiffStats(value.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 { passed: value.passed === true, output: pickString(value.output) ?? '' }\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","/**\n * @experimental\n *\n * Delegate factories — the layer between MCP tool handlers and the\n * underlying `runLoop` runners.\n *\n * The MCP server is profile-agnostic: it owns the task queue + feedback\n * store + transport. Each `*Delegate` is the closure that the queue\n * invokes when a task runs. Consumers can override either delegate to\n * inject custom drivers, mocks, fleet-aware dispatchers, etc.\n *\n * The `detachedSessionDelegate` here is the built-in SANDBOX-SESSION coder path — the live default\n * `delegate_code` delegate: workers run the in-box harness over a `SandboxClient`. By default it\n * holds the stream; single-variant turns can OPTIONALLY dispatch DETACHED (`driveTurn` ticks) so a\n * durable queue resumes them across an MCP restart — that resume tick is the only part gated behind\n * `MCP_ENABLE_DETACHED_RESUME` (default off) in `bin.ts`, a capability the recursive\n * `Scope`/worktree-CLI leaf has no durable equivalent for yet. For NEW local-repo coding use\n * `worktreeFanout` / `worktreeLoopRunner`. The default researcher delegate is **not** wired in this\n * file — `agent-knowledge` cannot be imported from `agent-runtime` without inducing a cycle.\n * Consumers pass `researcherDelegate` explicitly.\n */\n\nimport type { CoderTask } from '../profiles/coder'\nimport type {\n AgentRunSpec,\n Iteration,\n LoopTraceEmitter,\n Outcome,\n SandboxClient,\n WinnerStrategy,\n} from '../runtime'\nimport { runLoop, selectValidWinner } from '../runtime'\nimport { composeLoopTraceEmitters } from './delegation-trace'\nimport {\n type CoderOutput,\n coderOutputAdapter,\n coderRunSpec,\n createCoderValidator,\n multiHarnessCoderFanout,\n} from './detached-coder'\nimport {\n type DetachedTurn,\n detachedTurnEvents,\n formatDetachedSessionRef,\n parseDetachedSessionRef,\n runDetachedTurn,\n} from './detached-turn'\nimport { createSiblingSandboxExecutor, type DelegationExecutor } from './executor'\nimport type {\n DelegateCodeArgs,\n DelegateResearchArgs,\n DelegateUiAuditArgs,\n DelegationProgress,\n ResearchOutputShape,\n UiAuditorDelegationOutput,\n} from './types'\n\n/** @experimental */\nexport interface DelegateRunCtx {\n signal: AbortSignal\n report(progress: DelegationProgress): void\n /**\n * Detached-run resume key recorded on the queue record at submit time\n * (`formatDetachedSessionRef`). Present only when the submit path requested\n * detached dispatch — its presence is what routes a session-backed delegate\n * onto the `driveTurn` tick path instead of holding a stream.\n */\n detachedSessionRef?: string\n /** Rebind the record's resume key (e.g. once the sandbox id is known). */\n updateDetachedSessionRef?(ref: string): void\n /**\n * Per-delegation trace sink supplied by the queue — loop events emitted\n * here land on the delegation record as a compact span tree. Delegates\n * compose it with their configured OTEL emitter so both sinks observe\n * the same stream.\n */\n traceEmitter?: LoopTraceEmitter\n}\n\n/** @experimental The server's coder-profile delegate slot — the closure the queue invokes for a\n * `delegate_code` task. `detachedSessionDelegate` is the built-in implementation. */\nexport type CoderDelegate = (args: DelegateCodeArgs, ctx: DelegateRunCtx) => Promise<CoderOutput>\n\n/** @experimental */\nexport type ResearcherDelegate = (\n args: DelegateResearchArgs,\n ctx: DelegateRunCtx,\n) => Promise<ResearchOutputShape>\n\n/**\n * UI-auditor delegate — fully consumer-injected. agent-runtime ships no\n * default factory because the inputs are workspace path + judge function\n * + (optionally) a `SandboxClient`, and the judge is the consumer's\n * model seam. See `createInProcessUiAuditClient` + `uiAuditorProfile` in\n * `@tangle-network/agent-runtime/profiles` for the canonical wiring.\n *\n * @experimental\n */\nexport type UiAuditorDelegate = (\n args: DelegateUiAuditArgs,\n ctx: DelegateRunCtx,\n) => Promise<UiAuditorDelegationOutput>\n\n/** @experimental Structured review verdict over a coder candidate. */\nexport interface CoderReview {\n /** Gate: only approved candidates are eligible to win. */\n approved: boolean\n /** Reviewer's recommendation — surfaced in traces. */\n recommendation: 'ship' | 'approve-with-nits' | 'changes-requested' | 'reject'\n /** Readiness 0..1, used by the `highest-readiness` winner-selection strategy. */\n readiness: number\n notes?: string\n}\n\n/**\n * @experimental\n *\n * Optional adversarial reviewer over a coder candidate that already passed\n * mechanical validation (tests/typecheck/forbidden/diff/no-op/secrets). Folded\n * from the ai-trading-blueprint delegation MCP: a candidate is only eligible to\n * win if the reviewer approves it. The reviewer is the consumer's seam — an LLM\n * judge, a `pnpm review` command, anything returning a `CoderReview`.\n */\nexport type CoderReviewer = (\n output: CoderOutput,\n task: CoderTask,\n ctx: { signal: AbortSignal },\n) => Promise<CoderReview> | CoderReview\n\n/**\n * @experimental Winner-selection strategy among validated (+ reviewed) candidates on the\n * sandbox-session path. The base strategies (`highest-score` / `smallest-diff` /\n * `first-approved`) delegate to the shared `selectValidWinner`; `highest-readiness` is the\n * reviewer-only strategy this path keeps that the generic selector does not express. Default\n * `highest-score`.\n */\nexport type DetachedWinnerSelection =\n | 'highest-score'\n | 'smallest-diff'\n | 'highest-readiness'\n | 'first-approved'\n\n/** @experimental */\nexport interface DetachedSessionDelegateOptions {\n /**\n * Execution placement. Pass a {@link DelegationExecutor} (sibling or fleet)\n * to control where worker iterations land. `sandboxClient` is a\n * convenience shorthand that wraps the client in a sibling executor — pass\n * one or the other, not both.\n */\n executor?: DelegationExecutor\n /**\n * Convenience shorthand for sibling placement. Equivalent to\n * `executor: createSiblingSandboxExecutor({ client: sandboxClient })`.\n */\n sandboxClient?: SandboxClient\n /** Backend harness for the single-coder path. Default comes from `coderProfile`. */\n harness?: string\n /** Model override for the single-coder path. */\n model?: string\n /**\n * The worker's authored system prompt (§1.5). Flows onto `coderProfile`'s\n * `profile.prompt.systemPrompt` → through `runLoop` → the executor's `harnessInvocation`, so the\n * harness runs under this stance, not just the default coder prompt. Omit to keep the default.\n */\n systemPrompt?: string\n /** Default `['claude-code', 'codex', 'opencode/zai-coding-plan/glm-5.1']` when variants > 1. */\n fanoutHarnesses?: string[]\n /** Optional per-harness model override for `variants > 1`. */\n fanoutModels?: (string | undefined)[]\n /** Hard cap on the kernel's per-batch concurrency. Default 4. */\n maxConcurrency?: number\n /**\n * Optional adversarial reviewer. When set, a candidate must pass mechanical\n * validation AND `reviewer.approved` to be eligible to win — empty/secret/\n * test-failing patches are already gone; this catches the \"compiles + passes\n * but wrong/unsafe\" class the deterministic validator can't see.\n */\n reviewer?: CoderReviewer\n /** Winner-selection strategy among eligible candidates. Default `highest-score`. */\n winnerSelection?: DetachedWinnerSelection\n /**\n * Loop trace emitter forwarded into every delegated `runLoop`. Wire\n * `createPropagatingTraceEmitter(readTraceContextFromEnv())` here (the bin\n * does) so delegated build-loops export their topology spans to the OTLP /\n * Tangle Intelligence sink when `OTEL_EXPORTER_OTLP_ENDPOINT` is set — and\n * are a cheap no-op when it isn't. Configurable by construction.\n *\n * Detached single-variant turns (taken when `ctx.detachedSessionRef` is set)\n * bypass `runLoop`; `runDetachedTurn` synthesizes a single-iteration loop\n * event stream for them so this emitter observes detached work too.\n */\n traceEmitter?: LoopTraceEmitter\n /** Tick cadence (ms) for the detached single-variant path. Default 5000. */\n detachedTickIntervalMs?: number\n /** Wall-clock cap (ms) forwarded to `driveTurn` for detached turns. */\n detachedWallCapMs?: number\n}\n\n/**\n * Build the sandbox-session coder delegate. It drives `runLoop` against the project's\n * sandbox client + coder profile; when `args.variants > 1` it switches to the multi-harness fanout\n * topology.\n *\n * This is the SANDBOX-SESSION coder path: workers run the in-box harness via the\n * `SandboxClient`'s `streamPrompt`, and single-variant turns can dispatch DETACHED\n * (driveTurn ticks) so a durable queue resumes them across an MCP restart — a substrate\n * the recursive worktree-CLI leaf does not yet have a journal-replay equivalent for.\n *\n * For NEW local-repo coding use `worktreeFanout` / `worktreeLoopRunner` (author an `AgentProfile`\n * per harness → `createWorktreeCliExecutor` leaves → `gateOnDeliverable`). This delegate stays as the\n * MCP server's built-in `delegate_code` path; it runs held-stream by default and only its OPTIONAL\n * cross-restart resume (the `driveTurn` tick) is opt-in behind `MCP_ENABLE_DETACHED_RESUME`.\n *\n * @experimental\n */\nexport function detachedSessionDelegate(options: DetachedSessionDelegateOptions): CoderDelegate {\n const executor = resolveExecutor(options)\n const sandboxClient = executor.client\n const fanoutHarnesses = options.fanoutHarnesses\n const maxConcurrency = options.maxConcurrency ?? 4\n const traceEmitter = options.traceEmitter\n return async (args, ctx) => {\n const task = coderTaskFromArgs(args)\n const variants = Math.max(1, Math.trunc(args.variants ?? 1))\n const loopEmitter = composeLoopTraceEmitters(traceEmitter, ctx.traceEmitter)\n ctx.report({ iteration: 0, phase: 'starting' })\n if (variants <= 1) {\n const agentRunSpec = coderRunSpec({\n ...(options.harness ? { harness: options.harness } : {}),\n ...(options.model ? { model: options.model } : {}),\n ...(options.systemPrompt ? { systemPrompt: options.systemPrompt } : {}),\n })\n const output = coderOutputAdapter\n const validator = createCoderValidator(task)\n // Detached dispatch: one session on one box, driven by `driveTurn` ticks\n // instead of a held stream, so the run survives an MCP-process restart\n // (the resume driver re-attaches via the persisted ref). Only the\n // single-variant path detaches — fanout needs N sessions + winner\n // selection over every candidate, which one resume key cannot express.\n if (ctx.detachedSessionRef !== undefined && ctx.updateDetachedSessionRef) {\n const { sessionId } = parseDetachedSessionRef(ctx.detachedSessionRef)\n const rebind = ctx.updateDetachedSessionRef\n const turn = await runDetachedTurn({\n client: sandboxClient,\n spec: agentRunSpec as AgentRunSpec<unknown>,\n prompt: agentRunSpec.taskToPrompt(task),\n sessionId,\n bindSandbox: (sandboxId) => rebind(formatDetachedSessionRef({ sandboxId, sessionId })),\n signal: ctx.signal,\n report: ctx.report,\n ...(loopEmitter ? { traceEmitter: loopEmitter } : {}),\n ...(executor.placement === 'fleet' ? { placement: 'fleet' as const } : {}),\n ...(options.detachedTickIntervalMs !== undefined\n ? { tickIntervalMs: options.detachedTickIntervalMs }\n : {}),\n ...(options.detachedWallCapMs !== undefined\n ? { wallCapMs: options.detachedWallCapMs }\n : {}),\n })\n const chosen = await settleDetachedCoderTurn(turn, {\n task,\n sessionId,\n signal: ctx.signal,\n ...(options.harness ? { harness: options.harness } : {}),\n ...(options.model ? { model: options.model } : {}),\n ...(options.reviewer ? { reviewer: options.reviewer } : {}),\n })\n ctx.report({ iteration: 1, phase: 'completed' })\n return chosen\n }\n const result = await runLoop({\n driver: singleShotDriver,\n agentRun: agentRunSpec,\n output,\n validator,\n task,\n ctx: {\n sandboxClient,\n signal: ctx.signal,\n ...(loopEmitter ? { traceEmitter: loopEmitter } : {}),\n },\n maxIterations: 1,\n maxConcurrency,\n })\n const chosen = await pickCoderWinner({\n iterations: result.iterations,\n reviewer: options.reviewer,\n selection: options.winnerSelection ?? 'highest-score',\n task,\n signal: ctx.signal,\n })\n if (!chosen) throw new Error(noWinnerMessage(options.reviewer))\n ctx.report({ iteration: 1, phase: 'completed' })\n return chosen\n }\n const fanout = multiHarnessCoderFanout({\n ...(fanoutHarnesses && fanoutHarnesses.length > 0\n ? { harnesses: fanoutHarnesses.slice(0, variants) }\n : {}),\n ...(options.fanoutModels ? { models: options.fanoutModels.slice(0, variants) } : {}),\n })\n const agentRuns = fanout.agentRuns.slice(0, variants)\n const result = await runLoop({\n driver: fanout.driver,\n agentRuns,\n output: fanout.output,\n validator: fanout.validator,\n task,\n ctx: {\n sandboxClient,\n signal: ctx.signal,\n ...(loopEmitter ? { traceEmitter: loopEmitter } : {}),\n },\n maxIterations: variants,\n maxConcurrency: Math.min(maxConcurrency, variants),\n })\n const chosen = await pickCoderWinner({\n iterations: result.iterations,\n reviewer: options.reviewer,\n selection: options.winnerSelection ?? 'highest-score',\n task,\n signal: ctx.signal,\n })\n if (!chosen) throw new Error(noWinnerMessage(options.reviewer))\n ctx.report({ iteration: agentRuns.length, phase: 'completed' })\n return chosen\n }\n}\n\ninterface PickCoderWinnerArgs {\n iterations: ReadonlyArray<Iteration<CoderTask, CoderOutput>>\n reviewer: CoderReviewer | undefined\n selection: DetachedWinnerSelection\n task: CoderTask\n signal: AbortSignal\n}\n\n/** A valid (and, when a reviewer is wired, approved) candidate kept for selection. */\ninterface EligibleCandidate {\n iter: Iteration<CoderTask, CoderOutput>\n /** Reviewer readiness (defaults to the verdict score when no reviewer ran). */\n readiness: number\n}\n\n/**\n * Pick the winning coder candidate from a finished loop's iterations:\n * 1. keep only mechanically-VALID candidates (the validator already gated\n * tests/typecheck/forbidden/diff/no-op/secrets),\n * 2. if a `reviewer` is wired, keep only those it APPROVES,\n * 3. select among survivors via the shared `selectValidWinner` (base strategies) or, for the\n * reviewer-only `highest-readiness`, a readiness sort (the one strategy the generic selector\n * does not express — a documented capability of this sandbox-session path).\n * Returns `undefined` when nothing survives — the delegate fails loud.\n */\nasync function pickCoderWinner(args: PickCoderWinnerArgs): Promise<CoderOutput | undefined> {\n const eligible: EligibleCandidate[] = []\n for (const iter of args.iterations) {\n if (iter.output === undefined || iter.error || iter.verdict?.valid !== true) continue\n const readiness = iter.verdict.score ?? 0\n if (args.reviewer) {\n const review = await args.reviewer(iter.output, args.task, { signal: args.signal })\n if (!review.approved) continue\n eligible.push({ iter, readiness: review.readiness })\n } else {\n eligible.push({ iter, readiness })\n }\n }\n if (eligible.length === 0) return undefined\n\n // `highest-readiness` ranks on the reviewer's readiness — a reviewer-only metric the generic\n // valid-only selector does not carry. Ties → earliest iteration.\n if (args.selection === 'highest-readiness') {\n const sorted = [...eligible].sort(\n (a, b) => b.readiness - a.readiness || a.iter.index - b.iter.index,\n )\n return sorted[0]!.iter.output\n }\n\n // Base strategies route through the SHARED valid-only selector. Wrap each survivor's raw\n // `CoderOutput` in the `Outcome<D>` shape `selectValidWinner` reads, preserving verdict/index.\n const wrapped: Iteration<unknown, Outcome<CoderOutput>>[] = eligible.map(({ iter }) => ({\n ...iter,\n output: { kind: 'done', deliverable: iter.output as CoderOutput },\n }))\n const winner = selectValidWinner<CoderOutput>({\n strategy: baseStrategy(args.selection),\n sizeOf: (o) => o.diffStats.insertions + o.diffStats.deletions,\n })(wrapped)\n const out = winner?.output\n if (!out || out.kind !== 'done') return undefined\n return out.deliverable\n}\n\n/** Map the detached-session selection enum onto the shared `WinnerStrategy`. `first-approved`\n * reduces to `first-valid` over the already-approved set; `smallest-diff` to `smallest-artifact`. */\nfunction baseStrategy(\n selection: Exclude<DetachedWinnerSelection, 'highest-readiness'>,\n): WinnerStrategy {\n switch (selection) {\n case 'smallest-diff':\n return 'smallest-artifact'\n case 'first-approved':\n return 'first-valid'\n default:\n return 'highest-score'\n }\n}\n\nfunction noWinnerMessage(reviewer: CoderReviewer | undefined): string {\n return reviewer\n ? 'coder delegate: no candidate passed validation + review'\n : 'coder delegate: no candidate passed validation'\n}\n\n/**\n * Canonical `DelegateCodeArgs` → `CoderTask` mapping — the single source for\n * the delegate's live dispatch AND the resume driver's settle/message\n * rebuilding, so a resumed record reproduces exactly the task the original\n * process dispatched.\n *\n * @experimental\n */\nexport function coderTaskFromArgs(args: DelegateCodeArgs): CoderTask {\n return {\n goal: buildCoderGoal(args),\n repoRoot: args.repoRoot,\n testCmd: args.config?.testCmd,\n typecheckCmd: args.config?.typecheckCmd,\n forbiddenPaths: args.config?.forbiddenPaths,\n maxDiffLines: args.config?.maxDiffLines,\n }\n}\n\n/** @experimental */\nexport interface SettleDetachedCoderTurnOptions {\n task: CoderTask\n /** Session id of the detached turn — used as the synthesized event id. */\n sessionId: string\n signal: AbortSignal\n harness?: string\n model?: string\n /** Same gate as the streaming path: an unapproved candidate cannot win. */\n reviewer?: CoderReviewer\n}\n\n/**\n * Settle a completed detached coder turn through the same gate the streaming\n * path applies: parse the terminal payload with the coder output adapter,\n * run the mechanical validator (tests/typecheck/forbidden/diff/no-op/secrets),\n * then the optional reviewer. Throws when nothing survives — a resumed or\n * detached run must not return an unvalidated patch.\n *\n * SCOPE NOTE (detached/resume): the detached `driveTurn`-tick + cross-restart resume path is\n * bound to the `runLoop` + sandbox-session substrate. The recursive `Scope`/worktree-CLI leaf has\n * journal→replay but no driveTurn-over-a-detached-sandbox-session equivalent yet, so resume is NOT\n * advertised on the generic `worktreeFanout` path. This helper (with `coderTaskFromArgs` and\n * `createDriveTurnResumeDriver`) stays as the resume seam `bin.ts` wires for in-flight records.\n *\n * @experimental\n */\nexport async function settleDetachedCoderTurn(\n turn: DetachedTurn,\n options: SettleDetachedCoderTurnOptions,\n): Promise<CoderOutput> {\n const parsed = coderOutputAdapter.parse(detachedTurnEvents(options.sessionId, turn))\n const validator = createCoderValidator(options.task)\n const verdict = await validator.validate(parsed, { iteration: 0, signal: options.signal })\n if (verdict.valid !== true) throw new Error(noWinnerMessage(options.reviewer))\n if (options.reviewer) {\n const review = await options.reviewer(parsed, options.task, { signal: options.signal })\n if (!review.approved) throw new Error(noWinnerMessage(options.reviewer))\n }\n return parsed\n}\n\nfunction buildCoderGoal(args: DelegateCodeArgs): string {\n if (!args.contextHint) return args.goal\n return [args.goal, '', '## Context', args.contextHint].join('\\n')\n}\n\nfunction resolveExecutor(options: DetachedSessionDelegateOptions): DelegationExecutor {\n if (options.executor && options.sandboxClient) {\n throw new Error('detachedSessionDelegate: pass exactly one of `executor` or `sandboxClient`')\n }\n if (options.executor) return options.executor\n if (options.sandboxClient) {\n return createSiblingSandboxExecutor({ client: options.sandboxClient })\n }\n throw new Error('detachedSessionDelegate: `executor` or `sandboxClient` is required')\n}\n\n/**\n * Single-shot driver — plan one task on iteration 0, stop after one\n * iteration. Used by the coder delegate when `variants <= 1`. Keeps the\n * runLoop kernel-level accounting (timing, cost, trace emission) while\n * skipping fanout/refine topology overhead.\n */\nconst singleShotDriver = {\n name: 'mcp-single-shot',\n async plan<Task>(task: Task, history: ReadonlyArray<unknown>): Promise<Task[]> {\n return history.length === 0 ? [task] : []\n },\n decide(history: ReadonlyArray<unknown>): 'pick-winner' | 'fail' {\n return history.length > 0 ? 'pick-winner' : 'fail'\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAqDO,SAAS,6BACd,SACoB;AACpB,QAAM,aAAa,QAAQ;AAC3B,QAAM,SAAwB;AAAA,IAC5B,OAAO,MAAuD;AAC5D,aAAO,WAAW,OAAO,IAAI;AAAA,IAC/B;AAAA,IACA,kBAAkB,KAA4C;AAC5D,aAAO,EAAE,MAAM,WAAW,WAAW,OAAO,GAAG,EAAE;AAAA,IACnD;AAAA,EACF;AACA,SAAO;AAAA,IACL;AAAA,IACA,WAAW;AAAA,IACX,WAAmB;AACjB,aAAO;AAAA,IACT;AAAA,EACF;AACF;AA2CO,SAAS,6BACd,SACoB;AACpB,QAAM,QAAQ,QAAQ;AACtB,QAAM,UAAU,IAAI,IAAI,QAAQ,qBAAqB,CAAC,CAAC;AACvD,MAAI,YAAY;AAIhB,QAAM,uBAAuB,oBAAI,IAAmC;AAEpE,QAAM,SAAwB;AAA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,EAAE,WAAW,GAAG,QAAQ,QAAQ,OAAO,CAAC;AACzF,MAAI,QAAQ,UAAU,KAAM,OAAM,IAAI,MAAM,gBAAgB,QAAQ,QAAQ,CAAC;AAC7E,MAAI,QAAQ,UAAU;AACpB,UAAM,SAAS,MAAM,QAAQ,SAAS,QAAQ,QAAQ,MAAM,EAAE,QAAQ,QAAQ,OAAO,CAAC;AACtF,QAAI,CAAC,OAAO,SAAU,OAAM,IAAI,MAAM,gBAAgB,QAAQ,QAAQ,CAAC;AAAA,EACzE;AACA,SAAO;AACT;AAEA,SAAS,eAAe,MAAgC;AACtD,MAAI,CAAC,KAAK,YAAa,QAAO,KAAK;AACnC,SAAO,CAAC,KAAK,MAAM,IAAI,cAAc,KAAK,WAAW,EAAE,KAAK,IAAI;AAClE;AAEA,SAAS,gBAAgB,SAA6D;AACpF,MAAI,QAAQ,YAAY,QAAQ,eAAe;AAC7C,UAAM,IAAI,MAAM,4EAA4E;AAAA,EAC9F;AACA,MAAI,QAAQ,SAAU,QAAO,QAAQ;AACrC,MAAI,QAAQ,eAAe;AACzB,WAAO,6BAA6B,EAAE,QAAQ,QAAQ,cAAc,CAAC;AAAA,EACvE;AACA,QAAM,IAAI,MAAM,oEAAoE;AACtF;AAQA,IAAM,mBAAmB;AAAA,EACvB,MAAM;AAAA,EACN,MAAM,KAAW,MAAY,SAAkD;AAC7E,WAAO,QAAQ,WAAW,IAAI,CAAC,IAAI,IAAI,CAAC;AAAA,EAC1C;AAAA,EACA,OAAO,SAAyD;AAC9D,WAAO,QAAQ,SAAS,IAAI,gBAAgB;AAAA,EAC9C;AACF;","names":["text","chosen","result"]}
@@ -2,11 +2,17 @@ import {
2
2
  createKbGate
3
3
  } from "./chunk-FNMGYYSS.js";
4
4
  import {
5
- createDefaultCoderDelegate
6
- } from "./chunk-4FEUFYOY.js";
5
+ detachedSessionDelegate
6
+ } from "./chunk-RYD7ND4A.js";
7
7
  import {
8
8
  runAnalystLoop
9
9
  } from "./chunk-P5OKDSLB.js";
10
+ import {
11
+ createExecutorRegistry,
12
+ definePersona,
13
+ runPersonified,
14
+ worktreeFanout
15
+ } from "./chunk-MT4XM3G6.js";
10
16
  import {
11
17
  ConfigError
12
18
  } from "./chunk-VLF5RHEQ.js";
@@ -42,7 +48,7 @@ async function runDelegatedLoop(mode, registry, options = {}) {
42
48
  }
43
49
  }
44
50
  function coderLoopRunner(options) {
45
- const delegate = createDefaultCoderDelegate({
51
+ const delegate = detachedSessionDelegate({
46
52
  sandboxClient: options.sandboxClient,
47
53
  ...options.reviewer ? { reviewer: options.reviewer } : {},
48
54
  ...options.winnerSelection ? { winnerSelection: options.winnerSelection } : {},
@@ -54,8 +60,42 @@ function coderLoopRunner(options) {
54
60
  return delegate(options.args, ctx);
55
61
  };
56
62
  }
57
- function reviewLoopRunner(options) {
58
- return coderLoopRunner(options);
63
+ function worktreeLoopRunner(options) {
64
+ const shape = worktreeFanout({
65
+ repoRoot: options.repoRoot,
66
+ taskPrompt: options.taskPrompt,
67
+ harnesses: options.harnesses,
68
+ ...options.testCmd !== void 0 ? { testCmd: options.testCmd } : {},
69
+ ...options.typecheckCmd !== void 0 ? { typecheckCmd: options.typecheckCmd } : {},
70
+ ...options.require !== void 0 ? { require: options.require } : {},
71
+ ...options.maxDiffLines !== void 0 ? { maxDiffLines: options.maxDiffLines } : {},
72
+ ...options.forbiddenPaths !== void 0 ? { forbiddenPaths: options.forbiddenPaths } : {},
73
+ ...options.winnerStrategy !== void 0 ? { winnerStrategy: options.winnerStrategy } : {},
74
+ ...options.runGit ? { runGit: options.runGit } : {},
75
+ ...options.runHarness ? { runHarness: options.runHarness } : {},
76
+ ...options.runCommand ? { runCommand: options.runCommand } : {}
77
+ });
78
+ const persona = definePersona({
79
+ name: "worktree-coder",
80
+ root: { profile: { name: "worktree-coder" }, harness: null },
81
+ directive: "deliver a minimal validated patch on a fresh worktree",
82
+ context: { role: "coder" },
83
+ executors: { registry: createExecutorRegistry() }
84
+ });
85
+ return async (signal) => {
86
+ const result = await runPersonified({
87
+ persona,
88
+ shape,
89
+ task: options.taskPrompt,
90
+ budget: options.budget,
91
+ signal
92
+ });
93
+ if (result.kind !== "winner" || result.out.kind !== "done") {
94
+ const blockers = result.kind === "winner" && result.out.kind === "blocked" ? result.out.blockers.join("; ") : `supervisor settled ${result.kind}`;
95
+ throw new Error(`worktreeLoopRunner: no delivered patch (${blockers})`);
96
+ }
97
+ return result.out.deliverable;
98
+ };
59
99
  }
60
100
  function researchLoopRunner(o) {
61
101
  const gate = createKbGate(o.gate);
@@ -164,11 +204,11 @@ export {
164
204
  isDelegatedLoopMode,
165
205
  runDelegatedLoop,
166
206
  coderLoopRunner,
167
- reviewLoopRunner,
207
+ worktreeLoopRunner,
168
208
  researchLoopRunner,
169
209
  selfImproveLoopRunner,
170
210
  auditLoopRunner,
171
211
  runLoopRunnerCli,
172
212
  parseLoopRunnerArgv
173
213
  };
174
- //# sourceMappingURL=chunk-IN7WHMGZ.js.map
214
+ //# sourceMappingURL=chunk-YWO4H64E.js.map
@@ -0,0 +1 @@
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 DelegateRunCtx,\n type DetachedWinnerSelection,\n detachedSessionDelegate,\n} from './mcp/delegates'\nimport type { CoderOutput } from './mcp/detached-coder'\nimport { type CreateKbGateOptions, createKbGate, type FactCandidate } from './mcp/kb-gate'\nimport type { DelegateCodeArgs } from './mcp/types'\nimport {\n type AuthoredHarness,\n type Budget,\n createExecutorRegistry,\n definePersona,\n runPersonified,\n type SandboxClient,\n type WinnerStrategy,\n type WorktreeFanoutOptions,\n type WorktreePatchArtifact,\n worktreeFanout,\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. Pass one to run `review` mode (an approval gate over the candidate). */\n reviewer?: CoderReviewer\n /** Winner-selection strategy. Default `highest-score`. */\n winnerSelection?: DetachedWinnerSelection\n /** Harnesses for `variants > 1` fanout. */\n fanoutHarnesses?: string[]\n}\n\n/**\n * @experimental Build a `code`/`review`-mode runner over the sandbox-session coder delegate. Pass a\n * `reviewer` to run `review` mode — an approval gate over the validated candidate.\n */\nexport function coderLoopRunner(options: CoderLoopRunnerOptions): DelegatedLoopRunner<CoderOutput> {\n const delegate = detachedSessionDelegate({\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/** @experimental Options for the local-repo `code` runner over the GENERIC recursive path. */\nexport interface WorktreeLoopRunnerOptions {\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<AuthoredHarness>\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?: WinnerStrategy\n /** Test seams forwarded to the worktree-CLI leaves so the runner drives offline. */\n runGit?: WorktreeFanoutOptions['runGit']\n runHarness?: WorktreeFanoutOptions['runHarness']\n runCommand?: WorktreeFanoutOptions['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 * `worktreeFanout` (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 `patchDelivered`,\n * the winner is the shared valid-only selector (NOT `defaultSelectWinner`, whose non-valid fallback\n * would surface an ungated patch). Equal-k holds by the conserved budget pool. Returns the winning\n * patch artifact, or throws when no candidate is delivered (fail loud, never a vacuous done).\n */\nexport function worktreeLoopRunner(\n options: WorktreeLoopRunnerOptions,\n): DelegatedLoopRunner<WorktreePatchArtifact> {\n const shape = worktreeFanout<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(`worktreeLoopRunner: 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,OACK;AA2BA,IAAM,uBAAuB,CAAC,QAAQ,UAAU,YAAY,SAAS,cAAc;AAMnF,SAAS,oBAAoB,OAA4C;AAC9E,SAAO,OAAO,UAAU,YAAa,qBAA2C,SAAS,KAAK;AAChG;AAmCA,eAAsB,iBACpB,MACA,UACA,UAAmC,CAAC,GACH;AACjC,QAAM,SAAS,SAAS,IAAI;AAC5B,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI;AAAA,MACR,oDAAoD,IAAI,kBACtD,OAAO,KAAK,QAAQ,EAAE,KAAK,IAAI,KAAK,MACtC;AAAA,IACF;AAAA,EACF;AACA,QAAM,MAAM,QAAQ,OAAO,KAAK;AAChC,QAAM,SAAS,QAAQ,UAAU,IAAI,gBAAgB,EAAE;AACvD,QAAM,QAAQ,IAAI;AAClB,MAAI;AACF,UAAM,SAAS,MAAM,OAAO,MAAM;AAClC,WAAO,EAAE,MAAM,IAAI,MAAM,QAAQ,YAAY,IAAI,IAAI,MAAM;AAAA,EAC7D,SAAS,KAAK;AACZ,WAAO;AAAA,MACL;AAAA,MACA,IAAI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G,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":[]}
@@ -0,0 +1,52 @@
1
+ import { AgentProfile } from '@tangle-network/agent-interface';
2
+
3
+ /**
4
+ * @experimental
5
+ *
6
+ * `coderProfile` — the §1.5 author-the-profile DATA for code-modification tasks: an `AgentProfile`
7
+ * constant (the agent IS its profile) plus a pure `coderTaskToPrompt` formatter that renders a
8
+ * `CoderTask` into the per-task instruction. There is no factory, output adapter, or validator
9
+ * here — a domain customizes the worker by authoring a profile + handing it to a leaf executor
10
+ * (`createWorktreeCliExecutor`) or a fanout (`worktreeFanout`), and "is it delivered" is a
11
+ * `DeliverableSpec` (`patchDelivered`), not a bundled validator.
12
+ *
13
+ * The standing instruction tells the agent to work on a fresh branch, keep the patch minimal,
14
+ * avoid forbidden paths, and run the test + typecheck commands before declaring done.
15
+ */
16
+
17
+ /** @experimental The per-task inputs `coderTaskToPrompt` renders + the worktree gate enforces. */
18
+ interface CoderTask {
19
+ /** What the agent must accomplish. Free-form prose. */
20
+ goal: string;
21
+ /** Absolute path inside the sandbox where the repo lives. */
22
+ repoRoot: string;
23
+ /** Default `main`. The branch the agent diffs against. */
24
+ baseBranch?: string;
25
+ /** Default `pnpm test --run`. */
26
+ testCmd?: string;
27
+ /** Default `pnpm typecheck`. */
28
+ typecheckCmd?: string;
29
+ /** Files the agent may inspect for context. Surfaced verbatim in the prompt. */
30
+ contextFiles?: string[];
31
+ /**
32
+ * Paths the agent must not touch. The mechanical gate hard-fails on any match.
33
+ * Use glob-free literal path prefixes for unambiguous enforcement.
34
+ */
35
+ forbiddenPaths?: string[];
36
+ /** Default 400. Hard cap; the gate hard-fails when exceeded. */
37
+ maxDiffLines?: number;
38
+ }
39
+ /** @experimental The coder agent's standing instruction (its body lives in `coderProfile.prompt`). */
40
+ declare const DEFAULT_CODER_SYSTEM_PROMPT: string;
41
+ /**
42
+ * @experimental
43
+ *
44
+ * The coder `AgentProfile` — the §1.5 DATA the substrate materializes into a harness invocation.
45
+ * Stateless and harness-agnostic: a consumer overrides `model`/`metadata.backendType` by spreading
46
+ * a copy, never by a factory. `worktreeFanout` authors one such profile per harness leaf.
47
+ */
48
+ declare const coderProfile: AgentProfile;
49
+ /** @experimental Render a `CoderTask` into the per-task instruction handed to the coder profile. */
50
+ declare function coderTaskToPrompt(task: CoderTask): string;
51
+
52
+ export { type CoderTask as C, DEFAULT_CODER_SYSTEM_PROMPT as D, coderTaskToPrompt as a, coderProfile as c };