@tangle-network/agent-runtime 0.117.0 → 0.119.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 (80) hide show
  1. package/README.md +2 -0
  2. package/dist/{activation-BZ2FyX0O.js → activation-DdIpwQ0k.js} +3 -3
  3. package/dist/{activation-BZ2FyX0O.js.map → activation-DdIpwQ0k.js.map} +1 -1
  4. package/dist/agent.d.ts +1 -1
  5. package/dist/agent.js +3 -3
  6. package/dist/candidate-execution/index.d.ts +2 -2
  7. package/dist/candidate-execution/index.js +4 -4
  8. package/dist/{candidate-execution-PX61zXd2.js → candidate-execution-DDkSRPjY.js} +4 -4
  9. package/dist/{candidate-execution-PX61zXd2.js.map → candidate-execution-DDkSRPjY.js.map} +1 -1
  10. package/dist/{environment-provider-CTZjdIUg.d.ts → environment-provider-Bh4nX2qt.d.ts} +9 -1
  11. package/dist/{environment-provider-CzcEyRL7.js → environment-provider-Cr75N-rU.js} +2 -2
  12. package/dist/{environment-provider-CzcEyRL7.js.map → environment-provider-Cr75N-rU.js.map} +1 -1
  13. package/dist/environment-provider.d.ts +1 -1
  14. package/dist/environment-provider.js +1 -1
  15. package/dist/{improvement-cycle-Bcqz8rZI.js → improvement-cycle-zjR-MXwK.js} +7 -7
  16. package/dist/improvement-cycle-zjR-MXwK.js.map +1 -0
  17. package/dist/{index-X2YwyWkc.d.ts → index-B3bHsVLw.d.ts} +2 -2
  18. package/dist/{index-BHSYaWrC.d.ts → index-BLsKcxNd.d.ts} +3 -3
  19. package/dist/{index-DPWJxSRa.d.ts → index-CGADWaa_.d.ts} +20 -165
  20. package/dist/{index-BTUG4Xln.d.ts → index-I35151Fr.d.ts} +9 -9
  21. package/dist/index.d.ts +8 -8
  22. package/dist/index.js +12 -12
  23. package/dist/index.js.map +1 -1
  24. package/dist/intelligence.d.ts +4 -4
  25. package/dist/intelligence.js +6 -6
  26. package/dist/kernel.d.ts +4 -4
  27. package/dist/kernel.js +8 -7
  28. package/dist/{knowledge-CDlrayRc.js → knowledge-I1e9zQGj.js} +5 -5
  29. package/dist/{knowledge-CDlrayRc.js.map → knowledge-I1e9zQGj.js.map} +1 -1
  30. package/dist/knowledge.d.ts +1 -1
  31. package/dist/knowledge.js +1 -1
  32. package/dist/{local-harness-t6cDWDQ2.d.ts → local-harness-BIajef4A.d.ts} +29 -7
  33. package/dist/{loop-runner-bin-oyL7it5O.d.ts → loop-runner-bin-BeG9vTdE.d.ts} +3 -3
  34. package/dist/{loop-runner-bin-BxhhDtmG.js → loop-runner-bin-L996YVPS.js} +3 -3
  35. package/dist/{loop-runner-bin-BxhhDtmG.js.map → loop-runner-bin-L996YVPS.js.map} +1 -1
  36. package/dist/loop-runner-bin.d.ts +1 -1
  37. package/dist/loop-runner-bin.js +1 -1
  38. package/dist/mcp/bin.js +2 -2
  39. package/dist/mcp/bin.js.map +1 -1
  40. package/dist/mcp/index.d.ts +5 -5
  41. package/dist/mcp/index.js +8 -13
  42. package/dist/mcp/index.js.map +1 -1
  43. package/dist/{openai-tools-CO9X36zy.js → openai-tools-CvFEzw6f.js} +2 -2
  44. package/dist/{openai-tools-CO9X36zy.js.map → openai-tools-CvFEzw6f.js.map} +1 -1
  45. package/dist/{prepare-BbI6qGOW.js → prepare-DpV6np9e.js} +44 -34
  46. package/dist/{prepare-BbI6qGOW.js.map → prepare-DpV6np9e.js.map} +1 -1
  47. package/dist/primeintellect/index.d.ts +1 -1
  48. package/dist/{protected-model-port-B0yXMpLL.d.ts → protected-model-port-CoJOiINX.d.ts} +2 -2
  49. package/dist/{protected-model-port-COnyZfML.js → protected-model-port-vQLBRoAQ.js} +2 -2
  50. package/dist/{protected-model-port-COnyZfML.js.map → protected-model-port-vQLBRoAQ.js.map} +1 -1
  51. package/dist/{redact-BEtQtvd6.d.ts → redact-PQzmE1Jn.d.ts} +4 -4
  52. package/dist/run-layout-C2FGmZ3v.js +158 -0
  53. package/dist/run-layout-C2FGmZ3v.js.map +1 -0
  54. package/dist/{runtime-Ce39zfqn.js → runtime-D4e3GP5K.js} +7 -142
  55. package/dist/runtime-D4e3GP5K.js.map +1 -0
  56. package/dist/{spawn-journal-B_mu_oH2.js → spawn-journal-IeXpidO2.js} +2 -2
  57. package/dist/{spawn-journal-B_mu_oH2.js.map → spawn-journal-IeXpidO2.js.map} +1 -1
  58. package/dist/{structural-rollout-DLwW69R4.js → structural-rollout-DQHO3b2Y.js} +3 -3
  59. package/dist/{structural-rollout-DLwW69R4.js.map → structural-rollout-DQHO3b2Y.js.map} +1 -1
  60. package/dist/{supervise-U7_K5yuV.js → supervise-Cq50UT5-.js} +289 -1084
  61. package/dist/supervise-Cq50UT5-.js.map +1 -0
  62. package/dist/{supervisor-CAXiCKnX.js → supervisor-CpT9yAxL.js} +113 -35
  63. package/dist/supervisor-CpT9yAxL.js.map +1 -0
  64. package/dist/testing.js +10 -10
  65. package/dist/top-app-5unxqovu.js +1088 -0
  66. package/dist/top-app-5unxqovu.js.map +1 -0
  67. package/dist/tui/bin.d.ts +1 -0
  68. package/dist/tui/bin.js +19 -0
  69. package/dist/tui/bin.js.map +1 -0
  70. package/dist/tui/index.d.ts +209 -0
  71. package/dist/tui/index.js +2 -0
  72. package/dist/{util-Cc9g9Y-o.js → util-MVgdwuIS.js} +2 -2
  73. package/dist/{util-Cc9g9Y-o.js.map → util-MVgdwuIS.js.map} +1 -1
  74. package/dist/{workspace-archive-CqPIijFA.js → workspace-archive-B4SkNJjw.js} +2 -2
  75. package/dist/{workspace-archive-CqPIijFA.js.map → workspace-archive-B4SkNJjw.js.map} +1 -1
  76. package/package.json +8 -2
  77. package/dist/improvement-cycle-Bcqz8rZI.js.map +0 -1
  78. package/dist/runtime-Ce39zfqn.js.map +0 -1
  79. package/dist/supervise-U7_K5yuV.js.map +0 -1
  80. package/dist/supervisor-CAXiCKnX.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"loop-runner-bin-BxhhDtmG.js","names":[],"sources":["../src/loop-runner.ts","../src/loop-runner-bin.ts"],"sourcesContent":["/**\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 on the GENERIC recursive path (worktreeLoopRunner: author one\n * `AgentProfile` per harness → worktree-CLI leaves → `patchDelivered` gate)\n * review → caller-registered runner — a `code` runner with an approval gate over candidates\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 → caller-registered `improve(profile, options)` run\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 * @experimental\n */\n\nimport { runAnalystLoop } from './analyst-loop'\nimport type { RunAnalystLoopOpts, RunAnalystLoopResult } from './analyst-loop/types'\nimport { ConfigError } from './errors'\nimport { type CreateKbGateOptions, createKbGate, type FactCandidate } from './mcp/kb-gate'\nimport {\n type AuthoredHarness,\n type Budget,\n createExecutorRegistry,\n definePersona,\n runPersonified,\n type WinnerStrategy,\n type WorktreeFanoutOptions,\n type WorktreePatchArtifact,\n worktreeFanout,\n} from './runtime'\n\n/** All valid delegated-loop mode names — used for validation and CLI surfaces. @experimental */\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/** Type guard — returns true when `value` is a valid `DelegatedLoopMode` string. @experimental */\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 *\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 *\n * @experimental\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 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 *\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. The sandbox-session counterpart that drives the in-box\n * harness over a `SandboxClient` is `detachedSessionDelegate` (`./mcp/delegates`); here there is no\n * `runAgentRounds` driver, no role-coupled delegate — the harness list is the fanout, the gate is\n * `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 *\n * @experimental\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 * `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 *\n * @experimental\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/**\n * `audit` mode — analyst loop over captured trace/run data.\n *\n * @experimental\n */\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 *\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 * @experimental\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 *\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 *\n * @experimental\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":";;;;;;;;;;;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VPS.js","names":[],"sources":["../src/loop-runner.ts","../src/loop-runner-bin.ts"],"sourcesContent":["/**\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 on the GENERIC recursive path (worktreeLoopRunner: author one\n * `AgentProfile` per harness → worktree-CLI leaves → `patchDelivered` gate)\n * review → caller-registered runner — a `code` runner with an approval gate over candidates\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 → caller-registered `improve(profile, options)` run\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 * @experimental\n */\n\nimport { runAnalystLoop } from './analyst-loop'\nimport type { RunAnalystLoopOpts, RunAnalystLoopResult } from './analyst-loop/types'\nimport { ConfigError } from './errors'\nimport { type CreateKbGateOptions, createKbGate, type FactCandidate } from './mcp/kb-gate'\nimport {\n type AuthoredHarness,\n type Budget,\n createExecutorRegistry,\n definePersona,\n runPersonified,\n type WinnerStrategy,\n type WorktreeFanoutOptions,\n type WorktreePatchArtifact,\n worktreeFanout,\n} from './runtime'\n\n/** All valid delegated-loop mode names — used for validation and CLI surfaces. @experimental */\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/** Type guard — returns true when `value` is a valid `DelegatedLoopMode` string. @experimental */\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 *\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 *\n * @experimental\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 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 *\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. The sandbox-session counterpart that drives the in-box\n * harness over a `SandboxClient` is `detachedSessionDelegate` (`./mcp/delegates`); here there is no\n * `runAgentRounds` driver, no role-coupled delegate — the harness list is the fanout, the gate is\n * `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 *\n * @experimental\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 * `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 *\n * @experimental\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/**\n * `audit` mode — analyst loop over captured trace/run data.\n *\n * @experimental\n */\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 *\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 * @experimental\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 *\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 *\n * @experimental\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(invok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,KAAU"}
@@ -1,2 +1,2 @@
1
- import { i as runLoopRunnerCli, n as LoopRunnerCliResult, r as parseLoopRunnerArgv, t as LoopRunnerCliArgs } from "./loop-runner-bin-oyL7it5O.js";
1
+ import { i as runLoopRunnerCli, n as LoopRunnerCliResult, r as parseLoopRunnerArgv, t as LoopRunnerCliArgs } from "./loop-runner-bin-BeG9vTdE.js";
2
2
  export { LoopRunnerCliArgs, LoopRunnerCliResult, parseLoopRunnerArgv, runLoopRunnerCli };
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import { n as runLoopRunnerCli, t as parseLoopRunnerArgv } from "./loop-runner-bin-BxhhDtmG.js";
2
+ import { n as runLoopRunnerCli, t as parseLoopRunnerArgv } from "./loop-runner-bin-L996YVPS.js";
3
3
  export { parseLoopRunnerArgv, runLoopRunnerCli };
package/dist/mcp/bin.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { i as ConfigError } from "../errors-DEAvWQPy.js";
3
- import { y as readTraceContextFromEnv } from "../supervisor-CAXiCKnX.js";
4
- import { L as DelegationTaskQueue, l as createMcpServer, q as FileDelegationStore } from "../supervise-U7_K5yuV.js";
3
+ import { y as readTraceContextFromEnv } from "../supervisor-CpT9yAxL.js";
4
+ import { L as DelegationTaskQueue, l as createMcpServer, q as FileDelegationStore } from "../supervise-Cq50UT5-.js";
5
5
  import { a as resolveRouterBaseUrl } from "../model-resolution-Btd9iIKV.js";
6
6
  //#region src/mcp/delegate-supervisor-provisioning.ts
7
7
  const DEFAULT_WORKER_HARNESS = "opencode";
@@ -1 +1 @@
1
- {"version":3,"file":"bin.js","names":[],"sources":["../../src/mcp/delegate-supervisor-provisioning.ts","../../src/mcp/bin.ts"],"sourcesContent":["/**\n *\n * Resolve the `delegate` supervisor substrate (router brain + worker backend) from env, so the\n * `agent-runtime-mcp` bin can serve the ONE generic `delegate` verb by env, over the SAME stdio\n * invocation a consumer already mounts.\n *\n * `delegate` is wired into `createMcpServer` via `McpServerOptions.delegateSupervisor`, which needs a\n * router (the supervisor brain's substrate) and a backend (WHERE the authored workers run). Inside a\n * sandbox child the natural backend is `sandbox`: authored workers run as sub-sandboxes through the\n * SAME `SandboxClient` the bin already loads from `TANGLE_API_KEY`. The brain's router reuses the\n * repo's `resolveRouterBaseUrl` convention\n * (`TANGLE_ROUTER_URL` / `TANGLE_ROUTER_BASE_URL`), normalised to an OpenAI-compatible `/v1` endpoint,\n * keyed by `TANGLE_API_KEY`.\n *\n * @experimental\n */\n\nimport type { BackendType } from '@tangle-network/sandbox'\nimport { ConfigError } from '../errors'\nimport { type RouterEnv, resolveRouterBaseUrl } from '../model-resolution.js'\nimport type { SandboxClient } from '../runtime'\nimport type { RouterConfig } from '../runtime/router-client'\nimport type { ExecutorConfig } from '../runtime/supervise/runtime'\nimport type { DelegateHandlerOptions } from './tools/delegate'\n\nconst DEFAULT_WORKER_HARNESS = 'opencode'\n\nfunction trimmed(value: string | undefined): string | undefined {\n const v = value?.trim()\n return v ? v : undefined\n}\n\n/** True when the operator opted the generic `delegate` verb in (`MCP_ENABLE_DELEGATE=1`). Default off:\n * the wiring is additive, so consumers that do not enable it are unaffected. */\nexport function delegateEnabled(env: NodeJS.ProcessEnv = process.env): boolean {\n return env.MCP_ENABLE_DELEGATE === '1'\n}\n\n/**\n * Resolve the supervisor brain's router substrate from env. The base reuses `resolveRouterBaseUrl`,\n * normalised to `/v1`.\n *\n * The KEY is the one for INFERENCE, which inside a sandbox is not the one for the sandbox. A box\n * carries both: an inference credential for the OpenAI-compatible endpoint the brain calls, and\n * `TANGLE_API_KEY`, which authenticates the sandbox CONTROL API — create a box, run a process —\n * and which the router answers `403`. The brain therefore prefers the inference credential and\n * keeps the platform key as the last rung, for a host that runs one key for both.\n *\n * `TANGLE_INFERENCE_KEY` leads because it is Tangle's own name for that credential. `OPENAI_API_KEY`\n * holds the identical value and stays on the ladder for boxes provisioned before the Tangle-native\n * name existed, and for a BYO OpenAI key — but it is a vendor spelling of a Tangle credential, and\n * naming it first made this ladder read as \"prefer OpenAI over Tangle\" to the people who own the\n * product (agent-dev-container#4614). A name that needs a paragraph to disclaim is the wrong name.\n *\n * The order is not a preference between vendors. It is: what the caller explicitly set, then the\n * inference credential, then the control-plane key as a single-key-host fallback.\n *\n * The MODEL is NAMED, never guessed. Which ids a given router serves is deployment state this\n * package cannot know, and a wrong guess is invisible until the supervisor's first completion\n * rejects — after the tool has been advertised to an agent, from inside a child process whose\n * stderr nobody reads. `TANGLE_ROUTER_MODEL` is on the ladder because the sandbox platform sets it\n * on every box: a delegate child running there inherits the model its own host declared. When\n * nothing names one, fail at startup with the ladder in the message.\n */\nfunction resolveRouter(env: NodeJS.ProcessEnv): RouterConfig {\n const routerKey =\n trimmed(env.MCP_SUPERVISOR_ROUTER_KEY) ??\n trimmed(env.TANGLE_INFERENCE_KEY) ??\n trimmed(env.OPENAI_API_KEY) ??\n trimmed(env.TANGLE_API_KEY) ??\n ''\n const base = trimmed(env.MCP_SUPERVISOR_ROUTER_BASE_URL) ?? resolveRouterBaseUrl(env as RouterEnv)\n const routerBaseUrl = /\\/v\\d+\\/?$/.test(base)\n ? base.replace(/\\/$/, '')\n : `${base.replace(/\\/$/, '')}/v1`\n const model =\n trimmed(env.MCP_SUPERVISOR_MODEL) ??\n trimmed(env.MCP_WORKER_MODEL) ??\n trimmed(env.WORKER_MODEL) ??\n trimmed(env.TANGLE_ROUTER_MODEL)\n if (!model) {\n throw new ConfigError(\n 'agent-runtime-mcp: no supervisor brain model — set MCP_SUPERVISOR_MODEL (or MCP_WORKER_MODEL / ' +\n 'WORKER_MODEL / TANGLE_ROUTER_MODEL) to a tool-calling model the router serves.',\n )\n }\n return { routerBaseUrl, routerKey, model }\n}\n\n/**\n * Build the `delegateSupervisor` substrate for `createMcpServer` from env + the bin's loaded\n * `SandboxClient`. Returns `undefined` when `delegate` is not opted in, so the caller mounts it only\n * when asked. The worker backend is `sandbox` (authored workers run as sub-sandboxes via the same\n * client) on the harness named by `MCP_DELEGATE_WORKER_HARNESS` (default `opencode`).\n */\nexport function resolveDelegateSupervisor(\n sandboxClient: SandboxClient,\n env: NodeJS.ProcessEnv = process.env,\n): DelegateHandlerOptions | undefined {\n if (!delegateEnabled(env)) return undefined\n const router = resolveRouter(env)\n const harness = (trimmed(env.MCP_DELEGATE_WORKER_HARNESS) ??\n DEFAULT_WORKER_HARNESS) as BackendType\n const backend: ExecutorConfig = {\n backend: 'sandbox',\n harness,\n sandboxClient,\n }\n return {\n router,\n backend,\n model: router.model,\n }\n}\n","#!/usr/bin/env node\n\n/**\n *\n * `agent-runtime-mcp` — stdio MCP server entry point.\n *\n * Serves the ONE generic `delegate` verb (opt-in via `MCP_ENABLE_DELEGATE=1`): one intent → a\n * supervisor that authors + drives its own worker over `supervise()`, returning the delivered output\n * with its cost. The supervisor brain runs on the router; authored workers run as sub-sandboxes\n * through the same `SandboxClient` the bin loads from `TANGLE_API_KEY`. The queue-bound tools\n * (`delegate_feedback`, `delegation_status`, `delegation_history`) are always served.\n *\n * Environment variables:\n * TANGLE_API_KEY required — passed to `new Sandbox({ apiKey })`\n * SANDBOX_BASE_URL optional — sandbox-SDK base URL override\n * MCP_ENABLE_DELEGATE set to `1` to serve the generic `delegate` verb. Its authoring\n * supervisor runs the brain on the router and spawns authored\n * workers as sub-sandboxes via the same client; needs TANGLE_API_KEY.\n * MCP_SUPERVISOR_MODEL supervisor brain model id (falls back to MCP_WORKER_MODEL, then\n * WORKER_MODEL, then TANGLE_ROUTER_MODEL). Must be a tool-calling\n * model the router serves; with none named the bin exits 2.\n * MCP_SUPERVISOR_ROUTER_KEY router key for the supervisor brain (falls back to the box's\n * inference credential TANGLE_INFERENCE_KEY, then its vendor\n * spelling OPENAI_API_KEY, then TANGLE_API_KEY — which\n * authenticates the sandbox API, not the router)\n * MCP_SUPERVISOR_ROUTER_BASE_URL router base for the supervisor brain (defaults to the repo's\n * resolveRouterBaseUrl, normalized to `/v1`)\n * MCP_DELEGATE_WORKER_HARNESS harness the authored workers run on (default `opencode`)\n * AGENT_RUNTIME_DELEGATION_STATE_FILE\n * optional — absolute path of a JSON state\n * file. When set, delegation records persist\n * across MCP restarts (FileDelegationStore):\n * status/history survive and idempotency keys\n * dedupe across processes.\n * AGENT_RUNTIME_DELEGATION_STATE_RECOVER\n * set to `1` to archive a corrupt state file\n * (`<file>.corrupt-<ts>`) and start empty\n * instead of refusing to boot.\n * AGENT_RUNTIME_DELEGATION_RETAIN_TERMINAL\n * optional — positive integer cap on retained\n * terminal records. Unset = keep forever.\n *\n * @experimental\n */\n\nimport type { SandboxClient } from '../runtime'\nimport { delegateEnabled, resolveDelegateSupervisor } from './delegate-supervisor-provisioning'\nimport { FileDelegationStore } from './delegation-store'\nimport { createMcpServer } from './server'\nimport { DelegationTaskQueue } from './task-queue'\nimport type { DelegateHandlerOptions } from './tools/delegate'\nimport { readTraceContextFromEnv, type TraceContext } from './trace-propagation'\n\nconst DEFAULT_SANDBOX_BASE_URL = 'https://sandbox.tangle.tools'\n\nasync function main(): Promise<void> {\n const wantDelegate = delegateEnabled(process.env)\n\n // The generic `delegate` verb needs the sandbox client: its authored workers run as sub-sandboxes\n // (the `sandbox` backend). When `delegate` is not opted in, the server runs the queue-only subset\n // (feedback + status + history) with no sandbox.\n let sandboxClient: SandboxClient | undefined\n if (wantDelegate) {\n const apiKey = process.env.TANGLE_API_KEY\n if (!apiKey && !process.env.AGENT_RUNTIME_MCP_ALLOW_NO_KEY) {\n process.stderr.write(\n 'agent-runtime-mcp: TANGLE_API_KEY is required to serve `delegate`. Set AGENT_RUNTIME_MCP_ALLOW_NO_KEY=1 to run without it for diagnostics, or unset MCP_ENABLE_DELEGATE to run the queue-only subset.\\n',\n )\n process.exit(2)\n }\n sandboxClient = await loadSandboxClient(apiKey)\n }\n\n // The supervisor's loop topology spans export to the OTLP / Tangle Intelligence sink when\n // OTEL_EXPORTER_OTLP_ENDPOINT is set (+ TRACE_ID / PARENT_SPAN_ID for correlation). The same\n // context is stamped onto every delegation record so journal consumers join records into the\n // caller's trace.\n const traceContext = readTraceContextFromEnv()\n if (process.env.OTEL_EXPORTER_OTLP_ENDPOINT) {\n process.stderr.write(\n `agent-runtime-mcp: exporting loop topology → ${process.env.OTEL_EXPORTER_OTLP_ENDPOINT}\\n`,\n )\n }\n\n // The ONE generic `delegate` verb — opt-in via MCP_ENABLE_DELEGATE=1. Its authoring supervisor\n // runs the brain on the router and spawns authored workers as sub-sandboxes through the SAME\n // client, so it needs the loaded `sandboxClient`. Gated on the client resolving (no key → no\n // delegate, fail-closed).\n let delegateSupervisor: DelegateHandlerOptions | undefined\n if (wantDelegate && sandboxClient) {\n try {\n delegateSupervisor = resolveDelegateSupervisor(sandboxClient)\n } catch (error) {\n // Refuse to serve a verb that cannot work. Advertising `delegate` on an\n // unresolvable substrate spends an agent's turn on a tool whose first\n // inference is guaranteed to reject.\n process.stderr.write(`${error instanceof Error ? error.message : String(error)}\\n`)\n process.exit(2)\n }\n }\n if (delegateSupervisor) {\n process.stderr.write(\n `agent-runtime-mcp: delegate enabled — generic authoring supervisor on ${delegateSupervisor.router.model}\\n`,\n )\n }\n\n const durableQueue = await buildDurableQueueFromEnv(traceContext)\n const server = createMcpServer({\n ...(delegateSupervisor ? { delegateSupervisor } : {}),\n traceContext,\n ...(durableQueue ? { queue: durableQueue } : {}),\n })\n\n const shutdown = () => {\n server.stop()\n // Drain journal writes so the state file reflects the final record\n // states before the process exits. A persist failure already routed\n // through onPersistError; swallow the duplicate rejection here.\n if (durableQueue) {\n void durableQueue\n .flush()\n .catch(() => {})\n .finally(() => process.exit(0))\n return\n }\n process.exit(0)\n }\n process.on('SIGINT', shutdown)\n process.on('SIGTERM', shutdown)\n\n await server.serve()\n}\n\nasync function buildDurableQueueFromEnv(\n traceContext: TraceContext,\n): Promise<DelegationTaskQueue | undefined> {\n const stateFile = process.env.AGENT_RUNTIME_DELEGATION_STATE_FILE?.trim()\n if (!stateFile) return undefined\n const store = new FileDelegationStore({\n filePath: stateFile,\n recoverCorrupt: process.env.AGENT_RUNTIME_DELEGATION_STATE_RECOVER === '1',\n })\n const maxTerminalRecords = parseRetention(process.env.AGENT_RUNTIME_DELEGATION_RETAIN_TERMINAL)\n const queue = await DelegationTaskQueue.restore({\n store,\n traceContext,\n ...(maxTerminalRecords !== undefined ? { maxTerminalRecords } : {}),\n onPersistError: (error) => {\n // Durable mode that can no longer write is a broken contract: crash\n // loud instead of degrading to memory-only behind the caller's back.\n process.stderr.write(`agent-runtime-mcp: ${error.message}\\n`)\n process.exit(1)\n },\n })\n process.stderr.write(`agent-runtime-mcp: durable delegation state → ${stateFile}\\n`)\n return queue\n}\n\nfunction parseRetention(raw: string | undefined): number | undefined {\n if (raw === undefined || raw.trim() === '') return undefined\n const n = Number(raw)\n if (!Number.isInteger(n) || n < 1) {\n process.stderr.write(\n `agent-runtime-mcp: AGENT_RUNTIME_DELEGATION_RETAIN_TERMINAL must be a positive integer, got \"${raw}\"\\n`,\n )\n process.exit(2)\n }\n return n\n}\n\nasync function loadSandboxClient(apiKey: string | undefined): Promise<SandboxClient> {\n // Diagnostic mode: AGENT_RUNTIME_MCP_ALLOW_NO_KEY=1 enables tools/list + the\n // queue-bound tools (status / history / feedback) without sandbox creds.\n // `delegate` requires a real client; the stub fails loud at create() so the\n // agent observes the cause instead of silent success.\n if (!apiKey) {\n return {\n async create() {\n throw new Error(\n 'agent-runtime-mcp: TANGLE_API_KEY is unset; `delegate` is disabled in diagnostic mode. Set TANGLE_API_KEY or unset MCP_ENABLE_DELEGATE to remove the unsupported tool from the tool list.',\n )\n },\n } satisfies SandboxClient\n }\n // Dynamic import keeps the bin importable in environments that haven't\n // installed `@tangle-network/sandbox` yet (the runtime package lists it\n // as a peer dep, not a hard dep).\n const mod = await import('@tangle-network/sandbox').catch((err) => {\n process.stderr.write(\n `agent-runtime-mcp: failed to load @tangle-network/sandbox (${err.message}); install the peer dependency\\n`,\n )\n process.exit(2)\n })\n const SandboxCtor = (mod as { Sandbox?: new (config: unknown) => SandboxClient }).Sandbox\n if (!SandboxCtor) {\n process.stderr.write(\n 'agent-runtime-mcp: @tangle-network/sandbox does not export Sandbox; cannot construct client\\n',\n )\n process.exit(2)\n }\n // @tangle-network/sandbox ≥0.6 makes baseUrl required; default it so the MCP server\n // starts without forcing every caller to set SANDBOX_BASE_URL. Treat empty/whitespace as\n // unset (|| not ??) so `SANDBOX_BASE_URL=` still resolves to the default.\n const baseUrl = process.env.SANDBOX_BASE_URL?.trim() || DEFAULT_SANDBOX_BASE_URL\n return new SandboxCtor({ apiKey, baseUrl })\n}\n\nmain().catch((err) => {\n process.stderr.write(`agent-runtime-mcp: ${err instanceof Error ? err.stack : String(err)}\\n`)\n process.exit(1)\n})\n"],"mappings":";;;;;;AAyBA,MAAM,yBAAyB;AAE/B,SAAS,QAAQ,OAA+C;CAC9D,MAAM,IAAI,OAAO,KAAK;CACtB,OAAO,IAAI,IAAI,KAAA;AACjB;;;AAIA,SAAgB,gBAAgB,MAAyB,QAAQ,KAAc;CAC7E,OAAO,IAAI,wBAAwB;AACrC;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,SAAS,cAAc,KAAsC;CAC3D,MAAM,YACJ,QAAQ,IAAI,yBAAyB,KACrC,QAAQ,IAAI,oBAAoB,KAChC,QAAQ,IAAI,cAAc,KAC1B,QAAQ,IAAI,cAAc,KAC1B;CACF,MAAM,OAAO,QAAQ,IAAI,8BAA8B,KAAK,qBAAqB,GAAgB;CACjG,MAAM,gBAAgB,aAAa,KAAK,IAAI,IACxC,KAAK,QAAQ,OAAO,EAAE,IACtB,GAAG,KAAK,QAAQ,OAAO,EAAE,EAAE;CAC/B,MAAM,QACJ,QAAQ,IAAI,oBAAoB,KAChC,QAAQ,IAAI,gBAAgB,KAC5B,QAAQ,IAAI,YAAY,KACxB,QAAQ,IAAI,mBAAmB;CACjC,IAAI,CAAC,OACH,MAAM,IAAI,YACR,+KAEF;CAEF,OAAO;EAAE;EAAe;EAAW;CAAM;AAC3C;;;;;;;AAQA,S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AClF,IAAI,CAAC,aAAa;EAChB,QAAQ,OAAO,MACb,+FACF;EACA,QAAQ,KAAK,CAAC;CAChB;CAKA,OAAO,IAAI,YAAY;EAAE;EAAQ,SADjB,QAAQ,IAAI,kBAAkB,KAAK,KAAK;CACf,CAAC;AAC5C;AAEA,KAAK,CAAC,CAAC,OAAO,QAAQ;CACpB,QAAQ,OAAO,MAAM,sBAAsB,eAAe,QAAQ,IAAI,QAAQ,OAAO,GAAG,EAAE,GAAG;CAC7F,QAAQ,KAAK,CAAC;AAChB,CAAC"}
1
+ {"version":3,"file":"bin.js","names":[],"sources":["../../src/mcp/delegate-supervisor-provisioning.ts","../../src/mcp/bin.ts"],"sourcesContent":["/**\n *\n * Resolve the `delegate` supervisor substrate (router brain + worker backend) from env, so the\n * `agent-runtime-mcp` bin can serve the ONE generic `delegate` verb by env, over the SAME stdio\n * invocation a consumer already mounts.\n *\n * `delegate` is wired into `createMcpServer` via `McpServerOptions.delegateSupervisor`, which needs a\n * router (the supervisor brain's substrate) and a backend (WHERE the authored workers run). Inside a\n * sandbox child the natural backend is `sandbox`: authored workers run as sub-sandboxes through the\n * SAME `SandboxClient` the bin already loads from `TANGLE_API_KEY`. The brain's router reuses the\n * repo's `resolveRouterBaseUrl` convention\n * (`TANGLE_ROUTER_URL` / `TANGLE_ROUTER_BASE_URL`), normalised to an OpenAI-compatible `/v1` endpoint,\n * keyed by `TANGLE_API_KEY`.\n *\n * @experimental\n */\n\nimport type { BackendType } from '@tangle-network/sandbox'\nimport { ConfigError } from '../errors'\nimport { type RouterEnv, resolveRouterBaseUrl } from '../model-resolution.js'\nimport type { SandboxClient } from '../runtime'\nimport type { RouterConfig } from '../runtime/router-client'\nimport type { ExecutorConfig } from '../runtime/supervise/runtime'\nimport type { DelegateHandlerOptions } from './tools/delegate'\n\n// Composition-root default: a worker must run on SOME harness, and the router-backed one is the\n// least vendor-locked choice. Not a capability claim — nothing here branches on the name.\nconst DEFAULT_WORKER_HARNESS = 'opencode'\n\nfunction trimmed(value: string | undefined): string | undefined {\n const v = value?.trim()\n return v ? v : undefined\n}\n\n/** True when the operator opted the generic `delegate` verb in (`MCP_ENABLE_DELEGATE=1`). Default off:\n * the wiring is additive, so consumers that do not enable it are unaffected. */\nexport function delegateEnabled(env: NodeJS.ProcessEnv = process.env): boolean {\n return env.MCP_ENABLE_DELEGATE === '1'\n}\n\n/**\n * Resolve the supervisor brain's router substrate from env. The base reuses `resolveRouterBaseUrl`,\n * normalised to `/v1`.\n *\n * The KEY is the one for INFERENCE, which inside a sandbox is not the one for the sandbox. A box\n * carries both: an inference credential for the OpenAI-compatible endpoint the brain calls, and\n * `TANGLE_API_KEY`, which authenticates the sandbox CONTROL API — create a box, run a process —\n * and which the router answers `403`. The brain therefore prefers the inference credential and\n * keeps the platform key as the last rung, for a host that runs one key for both.\n *\n * `TANGLE_INFERENCE_KEY` leads because it is Tangle's own name for that credential. `OPENAI_API_KEY`\n * holds the identical value and stays on the ladder for boxes provisioned before the Tangle-native\n * name existed, and for a BYO OpenAI key — but it is a vendor spelling of a Tangle credential, and\n * naming it first made this ladder read as \"prefer OpenAI over Tangle\" to the people who own the\n * product (agent-dev-container#4614). A name that needs a paragraph to disclaim is the wrong name.\n *\n * The order is not a preference between vendors. It is: what the caller explicitly set, then the\n * inference credential, then the control-plane key as a single-key-host fallback.\n *\n * The MODEL is NAMED, never guessed. Which ids a given router serves is deployment state this\n * package cannot know, and a wrong guess is invisible until the supervisor's first completion\n * rejects — after the tool has been advertised to an agent, from inside a child process whose\n * stderr nobody reads. `TANGLE_ROUTER_MODEL` is on the ladder because the sandbox platform sets it\n * on every box: a delegate child running there inherits the model its own host declared. When\n * nothing names one, fail at startup with the ladder in the message.\n */\nfunction resolveRouter(env: NodeJS.ProcessEnv): RouterConfig {\n const routerKey =\n trimmed(env.MCP_SUPERVISOR_ROUTER_KEY) ??\n trimmed(env.TANGLE_INFERENCE_KEY) ??\n trimmed(env.OPENAI_API_KEY) ??\n trimmed(env.TANGLE_API_KEY) ??\n ''\n const base = trimmed(env.MCP_SUPERVISOR_ROUTER_BASE_URL) ?? resolveRouterBaseUrl(env as RouterEnv)\n const routerBaseUrl = /\\/v\\d+\\/?$/.test(base)\n ? base.replace(/\\/$/, '')\n : `${base.replace(/\\/$/, '')}/v1`\n const model =\n trimmed(env.MCP_SUPERVISOR_MODEL) ??\n trimmed(env.MCP_WORKER_MODEL) ??\n trimmed(env.WORKER_MODEL) ??\n trimmed(env.TANGLE_ROUTER_MODEL)\n if (!model) {\n throw new ConfigError(\n 'agent-runtime-mcp: no supervisor brain model — set MCP_SUPERVISOR_MODEL (or MCP_WORKER_MODEL / ' +\n 'WORKER_MODEL / TANGLE_ROUTER_MODEL) to a tool-calling model the router serves.',\n )\n }\n return { routerBaseUrl, routerKey, model }\n}\n\n/**\n * Build the `delegateSupervisor` substrate for `createMcpServer` from env + the bin's loaded\n * `SandboxClient`. Returns `undefined` when `delegate` is not opted in, so the caller mounts it only\n * when asked. The worker backend is `sandbox` (authored workers run as sub-sandboxes via the same\n * client) on the harness named by `MCP_DELEGATE_WORKER_HARNESS` (default `opencode`).\n */\nexport function resolveDelegateSupervisor(\n sandboxClient: SandboxClient,\n env: NodeJS.ProcessEnv = process.env,\n): DelegateHandlerOptions | undefined {\n if (!delegateEnabled(env)) return undefined\n const router = resolveRouter(env)\n const harness = (trimmed(env.MCP_DELEGATE_WORKER_HARNESS) ??\n DEFAULT_WORKER_HARNESS) as BackendType\n const backend: ExecutorConfig = {\n backend: 'sandbox',\n harness,\n sandboxClient,\n }\n return {\n router,\n backend,\n model: router.model,\n }\n}\n","#!/usr/bin/env node\n\n/**\n *\n * `agent-runtime-mcp` — stdio MCP server entry point.\n *\n * Serves the ONE generic `delegate` verb (opt-in via `MCP_ENABLE_DELEGATE=1`): one intent → a\n * supervisor that authors + drives its own worker over `supervise()`, returning the delivered output\n * with its cost. The supervisor brain runs on the router; authored workers run as sub-sandboxes\n * through the same `SandboxClient` the bin loads from `TANGLE_API_KEY`. The queue-bound tools\n * (`delegate_feedback`, `delegation_status`, `delegation_history`) are always served.\n *\n * Environment variables:\n * TANGLE_API_KEY required — passed to `new Sandbox({ apiKey })`\n * SANDBOX_BASE_URL optional — sandbox-SDK base URL override\n * MCP_ENABLE_DELEGATE set to `1` to serve the generic `delegate` verb. Its authoring\n * supervisor runs the brain on the router and spawns authored\n * workers as sub-sandboxes via the same client; needs TANGLE_API_KEY.\n * MCP_SUPERVISOR_MODEL supervisor brain model id (falls back to MCP_WORKER_MODEL, then\n * WORKER_MODEL, then TANGLE_ROUTER_MODEL). Must be a tool-calling\n * model the router serves; with none named the bin exits 2.\n * MCP_SUPERVISOR_ROUTER_KEY router key for the supervisor brain (falls back to the box's\n * inference credential TANGLE_INFERENCE_KEY, then its vendor\n * spelling OPENAI_API_KEY, then TANGLE_API_KEY — which\n * authenticates the sandbox API, not the router)\n * MCP_SUPERVISOR_ROUTER_BASE_URL router base for the supervisor brain (defaults to the repo's\n * resolveRouterBaseUrl, normalized to `/v1`)\n * MCP_DELEGATE_WORKER_HARNESS harness the authored workers run on (default `opencode`)\n * AGENT_RUNTIME_DELEGATION_STATE_FILE\n * optional — absolute path of a JSON state\n * file. When set, delegation records persist\n * across MCP restarts (FileDelegationStore):\n * status/history survive and idempotency keys\n * dedupe across processes.\n * AGENT_RUNTIME_DELEGATION_STATE_RECOVER\n * set to `1` to archive a corrupt state file\n * (`<file>.corrupt-<ts>`) and start empty\n * instead of refusing to boot.\n * AGENT_RUNTIME_DELEGATION_RETAIN_TERMINAL\n * optional — positive integer cap on retained\n * terminal records. Unset = keep forever.\n *\n * @experimental\n */\n\nimport type { SandboxClient } from '../runtime'\nimport { delegateEnabled, resolveDelegateSupervisor } from './delegate-supervisor-provisioning'\nimport { FileDelegationStore } from './delegation-store'\nimport { createMcpServer } from './server'\nimport { DelegationTaskQueue } from './task-queue'\nimport type { DelegateHandlerOptions } from './tools/delegate'\nimport { readTraceContextFromEnv, type TraceContext } from './trace-propagation'\n\nconst DEFAULT_SANDBOX_BASE_URL = 'https://sandbox.tangle.tools'\n\nasync function main(): Promise<void> {\n const wantDelegate = delegateEnabled(process.env)\n\n // The generic `delegate` verb needs the sandbox client: its authored workers run as sub-sandboxes\n // (the `sandbox` backend). When `delegate` is not opted in, the server runs the queue-only subset\n // (feedback + status + history) with no sandbox.\n let sandboxClient: SandboxClient | undefined\n if (wantDelegate) {\n const apiKey = process.env.TANGLE_API_KEY\n if (!apiKey && !process.env.AGENT_RUNTIME_MCP_ALLOW_NO_KEY) {\n process.stderr.write(\n 'agent-runtime-mcp: TANGLE_API_KEY is required to serve `delegate`. Set AGENT_RUNTIME_MCP_ALLOW_NO_KEY=1 to run without it for diagnostics, or unset MCP_ENABLE_DELEGATE to run the queue-only subset.\\n',\n )\n process.exit(2)\n }\n sandboxClient = await loadSandboxClient(apiKey)\n }\n\n // The supervisor's loop topology spans export to the OTLP / Tangle Intelligence sink when\n // OTEL_EXPORTER_OTLP_ENDPOINT is set (+ TRACE_ID / PARENT_SPAN_ID for correlation). The same\n // context is stamped onto every delegation record so journal consumers join records into the\n // caller's trace.\n const traceContext = readTraceContextFromEnv()\n if (process.env.OTEL_EXPORTER_OTLP_ENDPOINT) {\n process.stderr.write(\n `agent-runtime-mcp: exporting loop topology → ${process.env.OTEL_EXPORTER_OTLP_ENDPOINT}\\n`,\n )\n }\n\n // The ONE generic `delegate` verb — opt-in via MCP_ENABLE_DELEGATE=1. Its authoring supervisor\n // runs the brain on the router and spawns authored workers as sub-sandboxes through the SAME\n // client, so it needs the loaded `sandboxClient`. Gated on the client resolving (no key → no\n // delegate, fail-closed).\n let delegateSupervisor: DelegateHandlerOptions | undefined\n if (wantDelegate && sandboxClient) {\n try {\n delegateSupervisor = resolveDelegateSupervisor(sandboxClient)\n } catch (error) {\n // Refuse to serve a verb that cannot work. Advertising `delegate` on an\n // unresolvable substrate spends an agent's turn on a tool whose first\n // inference is guaranteed to reject.\n process.stderr.write(`${error instanceof Error ? error.message : String(error)}\\n`)\n process.exit(2)\n }\n }\n if (delegateSupervisor) {\n process.stderr.write(\n `agent-runtime-mcp: delegate enabled — generic authoring supervisor on ${delegateSupervisor.router.model}\\n`,\n )\n }\n\n const durableQueue = await buildDurableQueueFromEnv(traceContext)\n const server = createMcpServer({\n ...(delegateSupervisor ? { delegateSupervisor } : {}),\n traceContext,\n ...(durableQueue ? { queue: durableQueue } : {}),\n })\n\n const shutdown = () => {\n server.stop()\n // Drain journal writes so the state file reflects the final record\n // states before the process exits. A persist failure already routed\n // through onPersistError; swallow the duplicate rejection here.\n if (durableQueue) {\n void durableQueue\n .flush()\n .catch(() => {})\n .finally(() => process.exit(0))\n return\n }\n process.exit(0)\n }\n process.on('SIGINT', shutdown)\n process.on('SIGTERM', shutdown)\n\n await server.serve()\n}\n\nasync function buildDurableQueueFromEnv(\n traceContext: TraceContext,\n): Promise<DelegationTaskQueue | undefined> {\n const stateFile = process.env.AGENT_RUNTIME_DELEGATION_STATE_FILE?.trim()\n if (!stateFile) return undefined\n const store = new FileDelegationStore({\n filePath: stateFile,\n recoverCorrupt: process.env.AGENT_RUNTIME_DELEGATION_STATE_RECOVER === '1',\n })\n const maxTerminalRecords = parseRetention(process.env.AGENT_RUNTIME_DELEGATION_RETAIN_TERMINAL)\n const queue = await DelegationTaskQueue.restore({\n store,\n traceContext,\n ...(maxTerminalRecords !== undefined ? { maxTerminalRecords } : {}),\n onPersistError: (error) => {\n // Durable mode that can no longer write is a broken contract: crash\n // loud instead of degrading to memory-only behind the caller's back.\n process.stderr.write(`agent-runtime-mcp: ${error.message}\\n`)\n process.exit(1)\n },\n })\n process.stderr.write(`agent-runtime-mcp: durable delegation state → ${stateFile}\\n`)\n return queue\n}\n\nfunction parseRetention(raw: string | undefined): number | undefined {\n if (raw === undefined || raw.trim() === '') return undefined\n const n = Number(raw)\n if (!Number.isInteger(n) || n < 1) {\n process.stderr.write(\n `agent-runtime-mcp: AGENT_RUNTIME_DELEGATION_RETAIN_TERMINAL must be a positive integer, got \"${raw}\"\\n`,\n )\n process.exit(2)\n }\n return n\n}\n\nasync function loadSandboxClient(apiKey: string | undefined): Promise<SandboxClient> {\n // Diagnostic mode: AGENT_RUNTIME_MCP_ALLOW_NO_KEY=1 enables tools/list + the\n // queue-bound tools (status / history / feedback) without sandbox creds.\n // `delegate` requires a real client; the stub fails loud at create() so the\n // agent observes the cause instead of silent success.\n if (!apiKey) {\n return {\n async create() {\n throw new Error(\n 'agent-runtime-mcp: TANGLE_API_KEY is unset; `delegate` is disabled in diagnostic mode. Set TANGLE_API_KEY or unset MCP_ENABLE_DELEGATE to remove the unsupported tool from the tool list.',\n )\n },\n } satisfies SandboxClient\n }\n // Dynamic import keeps the bin importable in environments that haven't\n // installed `@tangle-network/sandbox` yet (the runtime package lists it\n // as a peer dep, not a hard dep).\n const mod = await import('@tangle-network/sandbox').catch((err) => {\n process.stderr.write(\n `agent-runtime-mcp: failed to load @tangle-network/sandbox (${err.message}); install the peer dependency\\n`,\n )\n process.exit(2)\n })\n const SandboxCtor = (mod as { Sandbox?: new (config: unknown) => SandboxClient }).Sandbox\n if (!SandboxCtor) {\n process.stderr.write(\n 'agent-runtime-mcp: @tangle-network/sandbox does not export Sandbox; cannot construct client\\n',\n )\n process.exit(2)\n }\n // @tangle-network/sandbox ≥0.6 makes baseUrl required; default it so the MCP server\n // starts without forcing every caller to set SANDBOX_BASE_URL. Treat empty/whitespace as\n // unset (|| not ??) so `SANDBOX_BASE_URL=` still resolves to the default.\n const baseUrl = process.env.SANDBOX_BASE_URL?.trim() || DEFAULT_SANDBOX_BASE_URL\n return new SandboxCtor({ apiKey, baseUrl })\n}\n\nmain().catch((err) => {\n process.stderr.write(`agent-runtime-mcp: ${err instanceof Error ? err.stack : String(err)}\\n`)\n process.exit(1)\n})\n"],"mappings":";;;;;;AA2BA,MAAM,yBAAyB;AAE/B,SAAS,QAAQ,OAA+C;CAC9D,MAAM,IAAI,OAAO,KAAK;CACtB,OAAO,IAAI,IAAI,KAAA;AACjB;;;AAIA,S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AQ,GAAG;GAC5D,QAAQ,KAAK,CAAC;EAChB;CACF,CAAC;CACD,QAAQ,OAAO,MAAM,iDAAiD,UAAU,GAAG;CACnF,OAAO;AACT;AAEA,SAAS,eAAe,KAA6C;CACnE,IAAI,QAAQ,KAAA,KAAa,IAAI,KAAK,MAAM,IAAI,OAAO,KAAA;CACnD,MAAM,IAAI,OAAO,GAAG;CACpB,IAAI,CAAC,OAAO,UAAU,CAAC,KAAK,IAAI,GAAG;EACjC,QAAQ,OAAO,MACb,gGAAgG,IAAI,IACtG;EACA,QAAQ,KAAK,CAAC;CAChB;CACA,OAAO;AACT;AAEA,eAAe,kBAAkB,QAAoD;CAKnF,IAAI,CAAC,QACH,OAAO,EACL,MAAM,SAAS;EACb,MAAM,IAAI,MACR,2LACF;CACF,EACF;CAWF,MAAM,eAAe,MANH,OAAO,0BAA0B,CAAC,OAAO,QAAQ;EACjE,QAAQ,OAAO,MACb,8DAA8D,IAAI,QAAQ,iCAC5E;EACA,QAAQ,KAAK,CAAC;CAChB,CAAC,EAAA,CACiF;CAClF,IAAI,CAAC,aAAa;EAChB,QAAQ,OAAO,MACb,+FACF;EACA,QAAQ,KAAK,CAAC;CAChB;CAKA,OAAO,IAAI,YAAY;EAAE;EAAQ,SADjB,QAAQ,IAAI,kBAAkB,KAAK,KAAK;CACf,CAAC;AAC5C;AAEA,KAAK,CAAC,CAAC,OAAO,QAAQ;CACpB,QAAQ,OAAO,MAAM,sBAAsB,eAAe,QAAQ,IAAI,QAAQ,OAAO,GAAG,EAAE,GAAG;CAC7F,QAAQ,KAAK,CAAC;AAChB,CAAC"}
@@ -1,8 +1,8 @@
1
- import { $c as McpServer, $d as CoderOutput, $l as DiffResult, $u as DelegateCodeArgs, Ac as AuthorizeDownMessage, Ad as DELEGATION_TRACE_MAX_SPANS, Au as createSiblingSandboxExecutor, Bc as DownMessageEvent, Bd as DelegationStore, Bu as parseDetachedSessionRef, Cd as FeedbackRefersTo, Cu as detachedSessionDelegate, Dd as UiAuditorDelegationOutput, Du as FleetWorkspaceExecutorOptions, Ed as UiAuditLensFilter, Eu as FleetHandle, Fc as CoordinationToolsOptions, Fd as capDelegationTrace, Fu as DriveTurnTick, Gc as QuestionOption, Gu as DelegationResumeDriver, Hc as Question, Hd as FileDelegationStoreOptions, Hu as DelegationArgs, Ic as DEFAULT_AWAIT_EVENT_TIMEOUT_MS, Id as composeLoopTraceEmitters, Iu as RunDetachedTurnOptions, Jc as QuestionUrgency, Ju as DelegationTaskQueue, Kc as QuestionPolicy, Ku as DelegationResumeTick, Lc as DownMessageAuthorizationInput, Ld as createDelegationTraceCollector, Lu as createDetachedTurnResumeDriver, Mc as ContinuationInstruction, Md as DelegationTraceCollector, Mu as DetachedTurn, Nc as CoordinationEvent, Nd as DelegationTraceSpan, Nu as DetachedTurnResumeDriverOptions, Oc as AnalystFindingEvent, Od as CappedDelegationTrace, Ou as SiblingSandboxExecutorOptions, Pc as CoordinationTools, Pd as buildDelegationTraceSpans, Pu as DriveTurnCapableBox, Qc as createCoordinationTools, Ql as DiffOptions, Qu as hashIdempotencyInput, Rc as DownMessageDeliveryAttempt, Rd as DelegationPersistenceError, Ru as detachedTurnEvents, Sd as FeedbackRating, Su as coderTaskFromArgs, Td as ResearchSource, Tu as DelegationExecutor, Uc as QuestionDecision, Ud as InMemoryDelegationStore, Uu as DelegationRecord, Vc as MakeWorkerAgent, Vd as FileDelegationStore, Vu as runDetachedTurn, Wc as QuestionLevel, Wu as DelegationResumeContext, Xc as WorkerSpawnContext, Xu as SubmitInput, Yc as SettledWorker, Yu as DelegationTaskQueueOptions, Zc as WorkerWatchOptions, Zl as CreateWorktreeOptions, Zu as SubmitOutput, _d as DelegationProgress, _u as DelegateRunCtx, ad as DelegateResearchConfig, al as DELEGATE_TOOL_NAME, au as removeWorktree, bd as DelegationStatusArgs, bu as SettleDetachedCoderTurnOptions, cd as DelegateUiAuditConfig, cl as DelegateHandlerOptions, cu as McpToolDescriptor, dd as DelegationError, dl as validateDelegateArgs, du as FeedbackStore, ed as DelegateCodeConfig, el as McpServerOptions, eu as GitRunner, fd as DelegationFeedbackSnapshot, fu as InMemoryFeedbackStore, gd as DelegationProfile, gu as CoderReviewer, hd as DelegationHistoryResult, hu as CoderReview, id as DelegateResearchArgs, il as DELEGATE_INPUT_SCHEMA, iu as createWorktree, jc as AuthorizedDownMessage, jd as DelegationTraceCaps, ju as DetachedSessionRefParts, kc as AnalystRegistry, kd as DELEGATION_TRACE_MAX_BYTES, ku as createFleetWorkspaceExecutor, ld as DelegateUiAuditResult, ll as DelegateResult, lu as McpTransport, md as DelegationHistoryEntry, mu as CoderDelegate, nd as DelegateFeedbackArgs, nl as createMcpServer, nu as WorktreeHandle, od as DelegateResearchResult, ol as DelegateArgs, ou as JsonRpcMessage, pd as DelegationHistoryArgs, pu as eventToSnapshot, qc as QuestionRecord, qu as DelegationRunContext, rd as DelegateFeedbackResult, rl as DELEGATE_DESCRIPTION, ru as captureWorktreeDiff, sd as DelegateUiAuditArgs, sl as DelegateError, su as JsonRpcResponse, td as DelegateCodeResult, tl as createInProcessTransport, tu as RemoveWorktreeOptions, ud as DelegateUiAuditRoute, ul as createDelegateHandler, uu as FeedbackEvent, vd as DelegationResultPayload, vu as DetachedSessionDelegateOptions, wd as ResearchOutputShape, wu as settleDetachedCoderTurn, xd as DelegationStatusResult, xu as UiAuditorDelegate, yd as DelegationStatus, yu as DetachedWinnerSelection, zc as DownMessageDeliveryOutcome, zd as DelegationStateCorruptError, zu as formatDetachedSessionRef } from "../index-DPWJxSRa.js";
1
+ import { $c as WorkerSpawnContext, $l as FeedbackStore, $u as DelegationError, Ad as FileDelegationStoreOptions, Au as DelegationArgs, Bc as DownMessageAuthorizationInput, Bl as DiffOptions, Bu as hashIdempotencyInput, Cd as capDelegationTrace, Cu as DriveTurnTick, Dd as DelegationStateCorruptError, Du as formatDetachedSessionRef, Ed as DelegationPersistenceError, Eu as detachedTurnEvents, Fc as ContinuationInstruction, Fu as DelegationRunContext, Gc as Question, Gl as captureWorktreeDiff, Gu as DelegateFeedbackResult, Hc as DownMessageDeliveryOutcome, Hl as GitRunner, Hu as DelegateCodeConfig, Ic as CoordinationEvent, Iu as DelegationTaskQueue, Jc as QuestionOption, Jl as JsonRpcMessage, Ju as DelegateResearchResult, Kc as QuestionDecision, Kl as createWorktree, Ku as DelegateResearchArgs, Lc as CoordinationTools, Lu as DelegationTaskQueueOptions, Mc as AnalystRegistry, Mu as DelegationResumeContext, Nc as AuthorizeDownMessage, Nu as DelegationResumeDriver, Od as DelegationStore, Ou as parseDetachedSessionRef, Pc as AuthorizedDownMessage, Pu as DelegationResumeTick, Qc as SettledWorker, Ql as FeedbackEvent, Qu as DelegateUiAuditRoute, Rc as CoordinationToolsOptions, Ru as SubmitInput, Sd as buildDelegationTraceSpans, Su as DriveTurnCapableBox, Td as createDelegationTraceCollector, Tu as createDetachedTurnResumeDriver, Uc as DownMessageEvent, Ul as RemoveWorktreeOptions, Uu as DelegateCodeResult, Vc as DownMessageDeliveryAttempt, Vd as CoderOutput, Vl as DiffResult, Vu as DelegateCodeArgs, Wc as MakeWorkerAgent, Wl as WorktreeHandle, Wu as DelegateFeedbackArgs, Xc as QuestionRecord, Xl as McpToolDescriptor, Xu as DelegateUiAuditConfig, Yc as QuestionPolicy, Yl as JsonRpcResponse, Yu as DelegateUiAuditArgs, Zc as QuestionUrgency, Zl as McpTransport, Zu as DelegateUiAuditResult, _d as DELEGATION_TRACE_MAX_BYTES, _u as createFleetWorkspaceExecutor, ad as DelegationProgress, al as createMcpServer, au as DelegateRunCtx, bd as DelegationTraceCollector, bu as DetachedTurn, cd as DelegationStatusArgs, cl as DELEGATE_TOOL_NAME, cu as SettleDetachedCoderTurnOptions, dd as FeedbackRefersTo, dl as DelegateHandlerOptions, du as detachedSessionDelegate, ed as DelegationFeedbackSnapshot, el as WorkerWatchOptions, eu as InMemoryFeedbackStore, fd as ResearchOutputShape, fl as DelegateResult, fu as settleDetachedCoderTurn, gd as CappedDelegationTrace, gu as SiblingSandboxExecutorOptions, hd as UiAuditorDelegationOutput, hu as FleetWorkspaceExecutorOptions, id as DelegationProfile, il as createInProcessTransport, iu as CoderReviewer, jc as AnalystFindingEvent, jd as InMemoryDelegationStore, ju as DelegationRecord, kd as FileDelegationStore, ku as runDetachedTurn, ld as DelegationStatusResult, ll as DelegateArgs, lu as UiAuditorDelegate, md as UiAuditLensFilter, ml as validateDelegateArgs, mu as FleetHandle, nd as DelegationHistoryEntry, nl as McpServer, nu as CoderDelegate, od as DelegationResultPayload, ol as DELEGATE_DESCRIPTION, ou as DetachedSessionDelegateOptions, pd as ResearchSource, pl as createDelegateHandler, pu as DelegationExecutor, qc as QuestionLevel, ql as removeWorktree, qu as DelegateResearchConfig, rd as DelegationHistoryResult, rl as McpServerOptions, ru as CoderReview, sd as DelegationStatus, sl as DELEGATE_INPUT_SCHEMA, su as DetachedWinnerSelection, td as DelegationHistoryArgs, tl as createCoordinationTools, tu as eventToSnapshot, ud as FeedbackRating, ul as DelegateError, uu as coderTaskFromArgs, vd as DELEGATION_TRACE_MAX_SPANS, vu as createSiblingSandboxExecutor, wd as composeLoopTraceEmitters, wu as RunDetachedTurnOptions, xd as DelegationTraceSpan, xu as DetachedTurnResumeDriverOptions, yd as DelegationTraceCaps, yu as DetachedSessionRefParts, zc as DEFAULT_AWAIT_EVENT_TIMEOUT_MS, zl as CreateWorktreeOptions, zu as SubmitOutput } from "../index-CGADWaa_.js";
2
2
  import { E as SandboxClient, h as LoopSandboxPlacement } from "../types-DnNGJ5Gz.js";
3
- import { Bt as readTraceContextFromEnv, Rt as TraceContext, Vt as traceContextToEnv, zt as createPropagatingTraceEmitter } from "../environment-provider-CTZjdIUg.js";
3
+ import { Bt as readTraceContextFromEnv, Rt as TraceContext, Vt as traceContextToEnv, zt as createPropagatingTraceEmitter } from "../environment-provider-Bh4nX2qt.js";
4
4
  import { o as UiLens } from "../substrate-BcnuSHXm.js";
5
- import { a as LocalHarnessResult, c as runLocalHarness, i as LocalHarness, n as CodexExecutionPolicy, o as RunLocalHarnessOptions, r as CodexTokenUsage, s as parseCodexTokenUsage, t as CodexExecutionEvidence } from "../local-harness-t6cDWDQ2.js";
5
+ import { a as LOCAL_HARNESSES, c as RunLocalHarnessOptions, d as parseCodexTokenUsage, f as runLocalHarness, i as DEFAULT_LOCAL_HARNESS, l as harnessSupportsReasoningEffort, n as CodexExecutionPolicy, o as LocalHarness, r as CodexTokenUsage, s as LocalHarnessResult, t as CodexExecutionEvidence, u as localHarnessExecutable } from "../local-harness-BIajef4A.js";
6
6
  import { a as KbGateResult, i as FactJudgeVerdict, n as FactCandidate, o as createKbGate, r as FactJudge, t as CreateKbGateOptions } from "../kb-gate-C8z2juK8.js";
7
7
  import { n as mcpToolsForRuntimeMcpSubset, t as mcpToolsForRuntimeMcp } from "../openai-tools-B68JaOCx.js";
8
8
  import { AgentProfileMcpServer } from "@tangle-network/agent-interface";
@@ -62,7 +62,7 @@ declare function detectExecutor(args: DetectExecutorArgs): Promise<DelegationExe
62
62
  interface InProcessExecutorOptions {
63
63
  /** Absolute path to the git repo (the workspace). Worktrees go under `<repoRoot>/.agent-worktrees/`. */
64
64
  repoRoot: string;
65
- /** Harnesses to round-robin across `create()` calls. One entry = no fanout. Default `['claude']`. */
65
+ /** Harnesses to round-robin across `create()` calls. One entry = no fanout. Default `['claude-code']`. */
66
66
  harnesses?: ReadonlyArray<LocalHarness>;
67
67
  /** Optional per-delegation test command run in the worktree after the harness exits. */
68
68
  testCmd?: string;
@@ -447,5 +447,5 @@ declare function createDelegationStatusHandler(options: DelegationStatusHandlerO
447
447
  /** @deprecated Use `McpToolDescriptor`; both names are the same protocol contract. */
448
448
  type StdioToolDescriptor = McpToolDescriptor;
449
449
  //#endregion
450
- export { type AgentMemorySpec, type AnalystFindingEvent, type AnalystRegistry, type AuthorizeDownMessage, type AuthorizedDownMessage, type CappedDelegationTrace, type CoderDelegate, type CoderOutput, type CoderReview, type CoderReviewer, CodexExecutionDiagnosticError, type CodexExecutionEvidence, type CodexExecutionFailureDiagnostic, type CodexExecutionPolicy, type CodexTokenUsage, type ContinuationInstruction, type CoordinationEvent, type CoordinationTools, type CoordinationToolsOptions, type CreateKbGateOptions, type CreateMemoryToolServerOptions, type CreateWorktreeOptions, DEFAULT_AWAIT_EVENT_TIMEOUT_MS, DELEGATE_DESCRIPTION, DELEGATE_FEEDBACK_DESCRIPTION, DELEGATE_FEEDBACK_INPUT_SCHEMA, DELEGATE_FEEDBACK_TOOL_NAME, DELEGATE_INPUT_SCHEMA, DELEGATE_TOOL_NAME, DELEGATE_UI_AUDIT_DESCRIPTION, DELEGATE_UI_AUDIT_INPUT_SCHEMA, DELEGATE_UI_AUDIT_TOOL_NAME, DELEGATION_HISTORY_DESCRIPTION, DELEGATION_HISTORY_INPUT_SCHEMA, DELEGATION_HISTORY_TOOL_NAME, DELEGATION_STATUS_DESCRIPTION, DELEGATION_STATUS_INPUT_SCHEMA, DELEGATION_STATUS_TOOL_NAME, DELEGATION_TRACE_MAX_BYTES, DELEGATION_TRACE_MAX_SPANS, type DelegateArgs, type DelegateCodeArgs, type DelegateCodeConfig, type DelegateCodeResult, type DelegateError, type DelegateFeedbackArgs, type DelegateFeedbackHandlerOptions, type DelegateFeedbackResult, type DelegateHandlerOptions, type DelegateResearchArgs, type DelegateResearchConfig, type DelegateResearchResult, type DelegateResult, type DelegateRunCtx, type DelegateUiAuditArgs, type DelegateUiAuditConfig, type DelegateUiAuditHandlerOptions, type DelegateUiAuditResult, type DelegateUiAuditRoute, type DelegationArgs, type DelegationError, type DelegationExecutor, type DelegationFeedbackSnapshot, type DelegationHistoryArgs, type DelegationHistoryEntry, type DelegationHistoryHandlerOptions, type DelegationHistoryResult, DelegationPersistenceError, type DelegationProfile, type DelegationProgress, type DelegationRecord, type DelegationResultPayload, type DelegationResumeContext, type DelegationResumeDriver, type DelegationResumeTick, type DelegationRunContext, DelegationStateCorruptError, type DelegationStatus, type DelegationStatusArgs, type DelegationStatusHandlerOptions, type DelegationStatusResult, type DelegationStore, DelegationTaskQueue, type DelegationTaskQueueOptions, type DelegationTraceCaps, type DelegationTraceCollector, type DelegationTraceSpan, type DetachedSessionDelegateOptions, type DetachedSessionRefParts, type DetachedTurn, type DetachedTurnResumeDriverOptions, type DetachedWinnerSelection, type DetectExecutorArgs, type DiffOptions, type DiffResult, type DownMessageAuthorizationInput, type DownMessageDeliveryAttempt, type DownMessageDeliveryOutcome, type DownMessageEvent, type DriveTurnCapableBox, type DriveTurnTick, type FactCandidate, type FactJudge, type FactJudgeVerdict, type FeedbackEvent, type FeedbackRating, type FeedbackRefersTo, type FeedbackStore, FileDelegationStore, type FileDelegationStoreOptions, type FleetHandle, type FleetWorkspaceExecutorOptions, type GitRunner, InMemoryDelegationStore, InMemoryFeedbackStore, type InProcessExecutorDescribePlacement, type InProcessExecutorOptions, type JsonRpcMessage, type JsonRpcResponse, type KbGateResult, type LocalHarness, type LocalHarnessResult, MEMORY_FILE_ENV, MEMORY_ITEMS_ENV, MEMORY_LOG_ENV, MEMORY_NAME_ENV, type MakeWorkerAgent, type McpServer, type McpServerOptions, type McpToolDescriptor, type McpTransport, type MemoryItem, type Question, type QuestionDecision, type QuestionLevel, type QuestionOption, type QuestionPolicy, type QuestionRecord, type QuestionUrgency, type RemoveWorktreeOptions, type ResearchOutputShape, type ResearchSource, type ResolvedMemoryEnv, type RunDetachedTurnOptions, type RunLocalHarnessOptions, type SettleDetachedCoderTurnOptions, type SettledWorker, type SiblingSandboxExecutorOptions, StdioToolDescriptor, type StdioToolServer, type StdioToolServerOptions, type SubmitInput, type SubmitOutput, type TraceContext, type UiAuditLensFilter, type UiAuditorDelegate, type UiAuditorDelegationOutput, type WorkerSpawnContext, type WorkerWatchOptions, type WorktreeHandle, buildDelegationTraceSpans, capDelegationTrace, captureWorktreeDiff, coderTaskFromArgs, composeLoopTraceEmitters, createCoordinationTools, createDelegateFeedbackHandler, createDelegateHandler, createDelegateUiAuditHandler, createDelegationHistoryHandler, createDelegationStatusHandler, createDelegationTraceCollector, createDetachedTurnResumeDriver, createFleetWorkspaceExecutor, createInProcessExecutor, createInProcessTransport, createKbGate, createMcpServer, createMemoryToolServer, createPropagatingTraceEmitter, createSiblingSandboxExecutor, createStdioToolServer, createWorktree, detachedSessionDelegate, detachedTurnEvents, detectExecutor, eventToSnapshot, formatDetachedSessionRef, hashIdempotencyInput, mcpToolsForRuntimeMcp, mcpToolsForRuntimeMcpSubset, parseCodexTokenUsage, parseDetachedSessionRef, parseMemoryItems, readMemoryItemsFile, readTraceContextFromEnv, removeWorktree, resolveMemoryFromEnv, runDetachedTurn, runLocalHarness, settleDetachedCoderTurn, traceContextToEnv, validateDelegateArgs, validateDelegateFeedbackArgs, validateDelegateUiAuditArgs, validateDelegationHistoryArgs, validateDelegationStatusArgs };
450
+ export { type AgentMemorySpec, type AnalystFindingEvent, type AnalystRegistry, type AuthorizeDownMessage, type AuthorizedDownMessage, type CappedDelegationTrace, type CoderDelegate, type CoderOutput, type CoderReview, type CoderReviewer, CodexExecutionDiagnosticError, type CodexExecutionEvidence, type CodexExecutionFailureDiagnostic, type CodexExecutionPolicy, type CodexTokenUsage, type ContinuationInstruction, type CoordinationEvent, type CoordinationTools, type CoordinationToolsOptions, type CreateKbGateOptions, type CreateMemoryToolServerOptions, type CreateWorktreeOptions, DEFAULT_AWAIT_EVENT_TIMEOUT_MS, DEFAULT_LOCAL_HARNESS, DELEGATE_DESCRIPTION, DELEGATE_FEEDBACK_DESCRIPTION, DELEGATE_FEEDBACK_INPUT_SCHEMA, DELEGATE_FEEDBACK_TOOL_NAME, DELEGATE_INPUT_SCHEMA, DELEGATE_TOOL_NAME, DELEGATE_UI_AUDIT_DESCRIPTION, DELEGATE_UI_AUDIT_INPUT_SCHEMA, DELEGATE_UI_AUDIT_TOOL_NAME, DELEGATION_HISTORY_DESCRIPTION, DELEGATION_HISTORY_INPUT_SCHEMA, DELEGATION_HISTORY_TOOL_NAME, DELEGATION_STATUS_DESCRIPTION, DELEGATION_STATUS_INPUT_SCHEMA, DELEGATION_STATUS_TOOL_NAME, DELEGATION_TRACE_MAX_BYTES, DELEGATION_TRACE_MAX_SPANS, type DelegateArgs, type DelegateCodeArgs, type DelegateCodeConfig, type DelegateCodeResult, type DelegateError, type DelegateFeedbackArgs, type DelegateFeedbackHandlerOptions, type DelegateFeedbackResult, type DelegateHandlerOptions, type DelegateResearchArgs, type DelegateResearchConfig, type DelegateResearchResult, type DelegateResult, type DelegateRunCtx, type DelegateUiAuditArgs, type DelegateUiAuditConfig, type DelegateUiAuditHandlerOptions, type DelegateUiAuditResult, type DelegateUiAuditRoute, type DelegationArgs, type DelegationError, type DelegationExecutor, type DelegationFeedbackSnapshot, type DelegationHistoryArgs, type DelegationHistoryEntry, type DelegationHistoryHandlerOptions, type DelegationHistoryResult, DelegationPersistenceError, type DelegationProfile, type DelegationProgress, type DelegationRecord, type DelegationResultPayload, type DelegationResumeContext, type DelegationResumeDriver, type DelegationResumeTick, type DelegationRunContext, DelegationStateCorruptError, type DelegationStatus, type DelegationStatusArgs, type DelegationStatusHandlerOptions, type DelegationStatusResult, type DelegationStore, DelegationTaskQueue, type DelegationTaskQueueOptions, type DelegationTraceCaps, type DelegationTraceCollector, type DelegationTraceSpan, type DetachedSessionDelegateOptions, type DetachedSessionRefParts, type DetachedTurn, type DetachedTurnResumeDriverOptions, type DetachedWinnerSelection, type DetectExecutorArgs, type DiffOptions, type DiffResult, type DownMessageAuthorizationInput, type DownMessageDeliveryAttempt, type DownMessageDeliveryOutcome, type DownMessageEvent, type DriveTurnCapableBox, type DriveTurnTick, type FactCandidate, type FactJudge, type FactJudgeVerdict, type FeedbackEvent, type FeedbackRating, type FeedbackRefersTo, type FeedbackStore, FileDelegationStore, type FileDelegationStoreOptions, type FleetHandle, type FleetWorkspaceExecutorOptions, type GitRunner, InMemoryDelegationStore, InMemoryFeedbackStore, type InProcessExecutorDescribePlacement, type InProcessExecutorOptions, type JsonRpcMessage, type JsonRpcResponse, type KbGateResult, LOCAL_HARNESSES, type LocalHarness, type LocalHarnessResult, MEMORY_FILE_ENV, MEMORY_ITEMS_ENV, MEMORY_LOG_ENV, MEMORY_NAME_ENV, type MakeWorkerAgent, type McpServer, type McpServerOptions, type McpToolDescriptor, type McpTransport, type MemoryItem, type Question, type QuestionDecision, type QuestionLevel, type QuestionOption, type QuestionPolicy, type QuestionRecord, type QuestionUrgency, type RemoveWorktreeOptions, type ResearchOutputShape, type ResearchSource, type ResolvedMemoryEnv, type RunDetachedTurnOptions, type RunLocalHarnessOptions, type SettleDetachedCoderTurnOptions, type SettledWorker, type SiblingSandboxExecutorOptions, StdioToolDescriptor, type StdioToolServer, type StdioToolServerOptions, type SubmitInput, type SubmitOutput, type TraceContext, type UiAuditLensFilter, type UiAuditorDelegate, type UiAuditorDelegationOutput, type WorkerSpawnContext, type WorkerWatchOptions, type WorktreeHandle, buildDelegationTraceSpans, capDelegationTrace, captureWorktreeDiff, coderTaskFromArgs, composeLoopTraceEmitters, createCoordinationTools, createDelegateFeedbackHandler, createDelegateHandler, createDelegateUiAuditHandler, createDelegationHistoryHandler, createDelegationStatusHandler, createDelegationTraceCollector, createDetachedTurnResumeDriver, createFleetWorkspaceExecutor, createInProcessExecutor, createInProcessTransport, createKbGate, createMcpServer, createMemoryToolServer, createPropagatingTraceEmitter, createSiblingSandboxExecutor, createStdioToolServer, createWorktree, detachedSessionDelegate, detachedTurnEvents, detectExecutor, eventToSnapshot, formatDetachedSessionRef, harnessSupportsReasoningEffort, hashIdempotencyInput, localHarnessExecutable, mcpToolsForRuntimeMcp, mcpToolsForRuntimeMcpSubset, parseCodexTokenUsage, parseDetachedSessionRef, parseMemoryItems, readMemoryItemsFile, readTraceContextFromEnv, removeWorktree, resolveMemoryFromEnv, runDetachedTurn, runLocalHarness, settleDetachedCoderTurn, traceContextToEnv, validateDelegateArgs, validateDelegateFeedbackArgs, validateDelegateUiAuditArgs, validateDelegationHistoryArgs, validateDelegationStatusArgs };
451
451
  //# sourceMappingURL=index.d.ts.map
package/dist/mcp/index.js CHANGED
@@ -1,11 +1,11 @@
1
1
  import { u as ValidationError } from "../errors-DEAvWQPy.js";
2
- import { c as sleep, d as throwIfAborted, r as deleteBoxSafe, u as throwAbort } from "../util-Cc9g9Y-o.js";
3
- import { It as parseCodexTokenUsage, Lt as runLocalHarness, Rt as CodexExecutionDiagnosticError, b as traceContextToEnv, bt as removeWorktree, gt as runWorktreeHarness, v as createPropagatingTraceEmitter, vt as captureWorktreeDiff, y as readTraceContextFromEnv, yt as createWorktree } from "../supervisor-CAXiCKnX.js";
4
- import { A as runCoderChecks, ot as selectValidWinner } from "../runtime-Ce39zfqn.js";
5
- import { A as DELEGATE_DESCRIPTION, B as DELEGATION_TRACE_MAX_SPANS, C as createDelegateUiAuditHandler, D as DELEGATE_FEEDBACK_TOOL_NAME, E as DELEGATE_FEEDBACK_INPUT_SCHEMA, G as DelegationPersistenceError, H as capDelegationTrace, J as InMemoryDelegationStore, K as DelegationStateCorruptError, L as DelegationTaskQueue, Lt as createSandboxForSpec, M as DELEGATE_TOOL_NAME, N as createDelegateHandler, O as createDelegateFeedbackHandler, P as validateDelegateArgs, R as hashIdempotencyInput, S as DELEGATE_UI_AUDIT_TOOL_NAME, T as DELEGATE_FEEDBACK_DESCRIPTION, U as composeLoopTraceEmitters, V as buildDelegationTraceSpans, W as createDelegationTraceCollector, X as eventToSnapshot, Y as InMemoryFeedbackStore, _ as DELEGATION_HISTORY_TOOL_NAME, b as DELEGATE_UI_AUDIT_DESCRIPTION, c as createInProcessTransport, d as DELEGATION_STATUS_INPUT_SCHEMA, dt as DEFAULT_AWAIT_EVENT_TIMEOUT_MS, f as DELEGATION_STATUS_TOOL_NAME, ft as createCoordinationTools, g as DELEGATION_HISTORY_INPUT_SCHEMA, h as DELEGATION_HISTORY_DESCRIPTION, j as DELEGATE_INPUT_SCHEMA, k as validateDelegateFeedbackArgs, l as createMcpServer, m as validateDelegationStatusArgs, p as createDelegationStatusHandler, q as FileDelegationStore, u as DELEGATION_STATUS_DESCRIPTION, v as createDelegationHistoryHandler, w as validateDelegateUiAuditArgs, x as DELEGATE_UI_AUDIT_INPUT_SCHEMA, y as validateDelegationHistoryArgs, z as DELEGATION_TRACE_MAX_BYTES, zt as runAgentRounds } from "../supervise-U7_K5yuV.js";
2
+ import { l as throwAbort, n as deleteBoxSafe, s as sleep, u as throwIfAborted } from "../util-MVgdwuIS.js";
3
+ import { Ct as removeWorktree, Gt as CodexExecutionDiagnosticError, Ht as localHarnessExecutable, Rt as DEFAULT_LOCAL_HARNESS, St as createWorktree, Ut as parseCodexTokenUsage, Vt as harnessSupportsReasoningEffort, Wt as runLocalHarness, b as traceContextToEnv, v as createPropagatingTraceEmitter, xt as captureWorktreeDiff, y as readTraceContextFromEnv, yt as runWorktreeHarness, zt as LOCAL_HARNESSES } from "../supervisor-CpT9yAxL.js";
4
+ import { Q as selectValidWinner, S as runCoderChecks } from "../runtime-D4e3GP5K.js";
5
+ import { A as DELEGATE_DESCRIPTION, At as runAgentRounds, B as DELEGATION_TRACE_MAX_SPANS, C as createDelegateUiAuditHandler, D as DELEGATE_FEEDBACK_TOOL_NAME, E as DELEGATE_FEEDBACK_INPUT_SCHEMA, G as DelegationPersistenceError, H as capDelegationTrace, J as InMemoryDelegationStore, K as DelegationStateCorruptError, L as DelegationTaskQueue, M as DELEGATE_TOOL_NAME, N as createDelegateHandler, O as createDelegateFeedbackHandler, Ot as createSandboxForSpec, P as validateDelegateArgs, R as hashIdempotencyInput, S as DELEGATE_UI_AUDIT_TOOL_NAME, T as DELEGATE_FEEDBACK_DESCRIPTION, U as composeLoopTraceEmitters, V as buildDelegationTraceSpans, W as createDelegationTraceCollector, X as eventToSnapshot, Y as InMemoryFeedbackStore, _ as DELEGATION_HISTORY_TOOL_NAME, b as DELEGATE_UI_AUDIT_DESCRIPTION, c as createInProcessTransport, d as DELEGATION_STATUS_INPUT_SCHEMA, dt as DEFAULT_AWAIT_EVENT_TIMEOUT_MS, f as DELEGATION_STATUS_TOOL_NAME, ft as createCoordinationTools, g as DELEGATION_HISTORY_INPUT_SCHEMA, h as DELEGATION_HISTORY_DESCRIPTION, j as DELEGATE_INPUT_SCHEMA, k as validateDelegateFeedbackArgs, l as createMcpServer, m as validateDelegationStatusArgs, p as createDelegationStatusHandler, q as FileDelegationStore, u as DELEGATION_STATUS_DESCRIPTION, v as createDelegationHistoryHandler, w as validateDelegateUiAuditArgs, x as DELEGATE_UI_AUDIT_INPUT_SCHEMA, y as validateDelegationHistoryArgs, z as DELEGATION_TRACE_MAX_BYTES } from "../supervise-Cq50UT5-.js";
6
6
  import { t as createStdioToolServer } from "../tool-server-RcWgLIsL.js";
7
7
  import { t as createKbGate } from "../kb-gate-DpaSwXVx.js";
8
- import { n as mcpToolsForRuntimeMcpSubset, t as mcpToolsForRuntimeMcp } from "../openai-tools-CO9X36zy.js";
8
+ import { n as mcpToolsForRuntimeMcpSubset, t as mcpToolsForRuntimeMcp } from "../openai-tools-CvFEzw6f.js";
9
9
  import { t as coderTaskToPrompt } from "../coder-yhVWbdWc.js";
10
10
  import { a as createMemoryToolServer, c as resolveMemoryFromEnv, i as MEMORY_NAME_ENV, n as MEMORY_ITEMS_ENV, o as parseMemoryItems, r as MEMORY_LOG_ENV, s as readMemoryItemsFile, t as MEMORY_FILE_ENV } from "../memory-server-DL6cE2Ag.js";
11
11
  import { randomUUID } from "node:crypto";
@@ -123,7 +123,7 @@ const DEFAULT_POSTCHECK_TIMEOUT_MS = 120 * 1e3;
123
123
  * @experimental
124
124
  */
125
125
  function createInProcessExecutor(options) {
126
- const harnesses = options.harnesses && options.harnesses.length > 0 ? [...options.harnesses] : ["claude"];
126
+ const harnesses = options.harnesses && options.harnesses.length > 0 ? [...options.harnesses] : [DEFAULT_LOCAL_HARNESS];
127
127
  const runPostCheck = options.runPostCheck ?? defaultRunPostCheck;
128
128
  const runCommand = async ({ command, cwd, signal }) => {
129
129
  try {
@@ -301,16 +301,11 @@ async function detectExecutor(args) {
301
301
  excludeMachineIds: parseList(env.TANGLE_FLEET_EXCLUDE_MACHINES)
302
302
  });
303
303
  }
304
- const KNOWN_HARNESSES = [
305
- "claude",
306
- "codex",
307
- "opencode"
308
- ];
309
304
  function parseHarnesses(raw) {
310
305
  if (!raw) return void 0;
311
306
  const parts = raw.split(",").map((s) => s.trim()).filter(Boolean);
312
307
  if (parts.length === 0) return void 0;
313
- for (const part of parts) if (!KNOWN_HARNESSES.includes(part)) throw new Error(`agent-runtime-mcp: AGENT_RUNTIME_LOCAL_HARNESSES contains unknown harness "${part}". Expected: ${KNOWN_HARNESSES.join(", ")}.`);
308
+ for (const part of parts) if (!LOCAL_HARNESSES.includes(part)) throw new Error(`agent-runtime-mcp: AGENT_RUNTIME_LOCAL_HARNESSES contains unknown harness "${part}". Expected: ${LOCAL_HARNESSES.join(", ")}.`);
314
309
  return parts;
315
310
  }
316
311
  async function defaultResolveFleet(sandboxClient, fleetId) {
@@ -1141,6 +1136,6 @@ const singleShotDriver = {
1141
1136
  }
1142
1137
  };
1143
1138
  //#endregion
1144
- export { CodexExecutionDiagnosticError, DEFAULT_AWAIT_EVENT_TIMEOUT_MS, DELEGATE_DESCRIPTION, DELEGATE_FEEDBACK_DESCRIPTION, DELEGATE_FEEDBACK_INPUT_SCHEMA, DELEGATE_FEEDBACK_TOOL_NAME, DELEGATE_INPUT_SCHEMA, DELEGATE_TOOL_NAME, DELEGATE_UI_AUDIT_DESCRIPTION, DELEGATE_UI_AUDIT_INPUT_SCHEMA, DELEGATE_UI_AUDIT_TOOL_NAME, DELEGATION_HISTORY_DESCRIPTION, DELEGATION_HISTORY_INPUT_SCHEMA, DELEGATION_HISTORY_TOOL_NAME, DELEGATION_STATUS_DESCRIPTION, DELEGATION_STATUS_INPUT_SCHEMA, DELEGATION_STATUS_TOOL_NAME, DELEGATION_TRACE_MAX_BYTES, DELEGATION_TRACE_MAX_SPANS, DelegationPersistenceError, DelegationStateCorruptError, DelegationTaskQueue, FileDelegationStore, InMemoryDelegationStore, InMemoryFeedbackStore, MEMORY_FILE_ENV, MEMORY_ITEMS_ENV, MEMORY_LOG_ENV, MEMORY_NAME_ENV, buildDelegationTraceSpans, capDelegationTrace, captureWorktreeDiff, coderTaskFromArgs, composeLoopTraceEmitters, createCoordinationTools, createDelegateFeedbackHandler, createDelegateHandler, createDelegateUiAuditHandler, createDelegationHistoryHandler, createDelegationStatusHandler, createDelegationTraceCollector, createDetachedTurnResumeDriver, createFleetWorkspaceExecutor, createInProcessExecutor, createInProcessTransport, createKbGate, createMcpServer, createMemoryToolServer, createPropagatingTraceEmitter, createSiblingSandboxExecutor, createStdioToolServer, createWorktree, detachedSessionDelegate, detachedTurnEvents, detectExecutor, eventToSnapshot, formatDetachedSessionRef, hashIdempotencyInput, mcpToolsForRuntimeMcp, mcpToolsForRuntimeMcpSubset, parseCodexTokenUsage, parseDetachedSessionRef, parseMemoryItems, readMemoryItemsFile, readTraceContextFromEnv, removeWorktree, resolveMemoryFromEnv, runDetachedTurn, runLocalHarness, settleDetachedCoderTurn, traceContextToEnv, validateDelegateArgs, validateDelegateFeedbackArgs, validateDelegateUiAuditArgs, validateDelegationHistoryArgs, validateDelegationStatusArgs };
1139
+ export { CodexExecutionDiagnosticError, DEFAULT_AWAIT_EVENT_TIMEOUT_MS, DEFAULT_LOCAL_HARNESS, DELEGATE_DESCRIPTION, DELEGATE_FEEDBACK_DESCRIPTION, DELEGATE_FEEDBACK_INPUT_SCHEMA, DELEGATE_FEEDBACK_TOOL_NAME, DELEGATE_INPUT_SCHEMA, DELEGATE_TOOL_NAME, DELEGATE_UI_AUDIT_DESCRIPTION, DELEGATE_UI_AUDIT_INPUT_SCHEMA, DELEGATE_UI_AUDIT_TOOL_NAME, DELEGATION_HISTORY_DESCRIPTION, DELEGATION_HISTORY_INPUT_SCHEMA, DELEGATION_HISTORY_TOOL_NAME, DELEGATION_STATUS_DESCRIPTION, DELEGATION_STATUS_INPUT_SCHEMA, DELEGATION_STATUS_TOOL_NAME, DELEGATION_TRACE_MAX_BYTES, DELEGATION_TRACE_MAX_SPANS, DelegationPersistenceError, DelegationStateCorruptError, DelegationTaskQueue, FileDelegationStore, InMemoryDelegationStore, InMemoryFeedbackStore, LOCAL_HARNESSES, MEMORY_FILE_ENV, MEMORY_ITEMS_ENV, MEMORY_LOG_ENV, MEMORY_NAME_ENV, buildDelegationTraceSpans, capDelegationTrace, captureWorktreeDiff, coderTaskFromArgs, composeLoopTraceEmitters, createCoordinationTools, createDelegateFeedbackHandler, createDelegateHandler, createDelegateUiAuditHandler, createDelegationHistoryHandler, createDelegationStatusHandler, createDelegationTraceCollector, createDetachedTurnResumeDriver, createFleetWorkspaceExecutor, createInProcessExecutor, createInProcessTransport, createKbGate, createMcpServer, createMemoryToolServer, createPropagatingTraceEmitter, createSiblingSandboxExecutor, createStdioToolServer, createWorktree, detachedSessionDelegate, detachedTurnEvents, detectExecutor, eventToSnapshot, formatDetachedSessionRef, harnessSupportsReasoningEffort, hashIdempotencyInput, localHarnessExecutable, mcpToolsForRuntimeMcp, mcpToolsForRuntimeMcpSubset, parseCodexTokenUsage, parseDetachedSessionRef, parseMemoryItems, readMemoryItemsFile, readTraceContextFromEnv, removeWorktree, resolveMemoryFromEnv, runDetachedTurn, runLocalHarness, settleDetachedCoderTurn, traceContextToEnv, validateDelegateArgs, validateDelegateFeedbackArgs, validateDelegateUiAuditArgs, validateDelegationHistoryArgs, validateDelegationStatusArgs };
1145
1140
 
1146
1141
  //# sourceMappingURL=index.js.map