@tangle-network/agent-runtime 0.185.1 → 0.187.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/dist/{activation-h6zO-0Rd.js → activation-CpEoQaj5.js} +3 -3
  2. package/dist/{activation-h6zO-0Rd.js.map → activation-CpEoQaj5.js.map} +1 -1
  3. package/dist/agent.d.ts +2 -2
  4. package/dist/agent.js +3 -3
  5. package/dist/{analyst-loop-DCTra9Qy.js → analyst-loop-CSH7P-Bf.js} +2 -2
  6. package/dist/{analyst-loop-DCTra9Qy.js.map → analyst-loop-CSH7P-Bf.js.map} +1 -1
  7. package/dist/analyst-loop.d.ts +1 -1
  8. package/dist/analyst-loop.js +1 -1
  9. package/dist/{authoring-BNQKWhto.js → authoring-fsUwd9hg.js} +2 -2
  10. package/dist/{authoring-BNQKWhto.js.map → authoring-fsUwd9hg.js.map} +1 -1
  11. package/dist/candidate-execution/index.js +4 -4
  12. package/dist/{candidate-execution-7lVEly33.js → candidate-execution-CehLeZmx.js} +4 -4
  13. package/dist/{candidate-execution-7lVEly33.js.map → candidate-execution-CehLeZmx.js.map} +1 -1
  14. package/dist/{conversation-BSgEebIo.js → conversation-DILnmy84.js} +3 -3
  15. package/dist/{conversation-BSgEebIo.js.map → conversation-DILnmy84.js.map} +1 -1
  16. package/dist/conversation.d.ts +1 -1
  17. package/dist/conversation.js +1 -1
  18. package/dist/{coordination-driver-Dh_0SvXr.js → coordination-driver-CtbyZv5d.js} +4 -4
  19. package/dist/{coordination-driver-Dh_0SvXr.js.map → coordination-driver-CtbyZv5d.js.map} +1 -1
  20. package/dist/durable.d.ts +24 -3
  21. package/dist/durable.js +12 -2
  22. package/dist/durable.js.map +1 -1
  23. package/dist/environment-provider-C4AQiUxj.d.ts +143 -0
  24. package/dist/{environment-provider-6QtI-u5j.js → environment-provider-DZxuH3E4.js} +56 -9
  25. package/dist/environment-provider-DZxuH3E4.js.map +1 -0
  26. package/dist/environment-provider.d.ts +2 -2
  27. package/dist/environment-provider.js +1 -1
  28. package/dist/{executable-spec-CkGvdPds.js → executable-spec-DxuiDFAU.js} +2 -2
  29. package/dist/{executable-spec-CkGvdPds.js.map → executable-spec-DxuiDFAU.js.map} +1 -1
  30. package/dist/{graph-VTmSuXNo.js → graph-Cox_7pht.js} +93 -5
  31. package/dist/graph-Cox_7pht.js.map +1 -0
  32. package/dist/graph.d.ts +3 -3
  33. package/dist/graph.js +5 -5
  34. package/dist/{improvement-cycle-Cmpe5Uev.js → improvement-cycle-BYHefgVo.js} +7 -7
  35. package/dist/{improvement-cycle-Cmpe5Uev.js.map → improvement-cycle-BYHefgVo.js.map} +1 -1
  36. package/dist/{index-DHSZjuLC.d.ts → index-DA9jKuJc.d.ts} +3 -3
  37. package/dist/{index-BhtdFMnG.d.ts → index-DVob1IA1.d.ts} +117 -14
  38. package/dist/{index-Dg2UXocB.d.ts → index-DdmozvB8.d.ts} +4 -4
  39. package/dist/index.d.ts +9 -9
  40. package/dist/index.js +13 -13
  41. package/dist/intelligence.d.ts +5 -5
  42. package/dist/intelligence.js +6 -6
  43. package/dist/kernel.d.ts +7 -7
  44. package/dist/kernel.js +14 -14
  45. package/dist/{knowledge-SVRitzcp.js → knowledge-Bj1rDycX.js} +7 -7
  46. package/dist/{knowledge-SVRitzcp.js.map → knowledge-Bj1rDycX.js.map} +1 -1
  47. package/dist/knowledge.d.ts +1 -1
  48. package/dist/knowledge.js +1 -1
  49. package/dist/{loop-runner-bin-D2A4NfN7.js → loop-runner-bin-DgmtU0F0.js} +4 -4
  50. package/dist/{loop-runner-bin-D2A4NfN7.js.map → loop-runner-bin-DgmtU0F0.js.map} +1 -1
  51. package/dist/{loop-runner-bin-NanoP_bG.d.ts → loop-runner-bin-g9fWDuOh.d.ts} +3 -3
  52. package/dist/loop-runner-bin.d.ts +1 -1
  53. package/dist/loop-runner-bin.js +1 -1
  54. package/dist/mcp/bin.js +3 -3
  55. package/dist/mcp/index.d.ts +6 -6
  56. package/dist/mcp/index.js +7 -7
  57. package/dist/{model-policy-Sw4ywhtL.js → model-policy-Wf2MxXJ9.js} +12 -4
  58. package/dist/model-policy-Wf2MxXJ9.js.map +1 -0
  59. package/dist/{openai-tools-Cbk5uBUu.d.ts → openai-tools-BDwAdxk5.d.ts} +2 -2
  60. package/dist/{openai-tools-DCorsAv3.js → openai-tools-Cz04RKfD.js} +2 -2
  61. package/dist/{openai-tools-DCorsAv3.js.map → openai-tools-Cz04RKfD.js.map} +1 -1
  62. package/dist/{prepare-Tip-2ZoZ.js → prepare-BpIGs5Tc.js} +123 -40
  63. package/dist/prepare-BpIGs5Tc.js.map +1 -0
  64. package/dist/primeintellect/index.d.ts +1 -1
  65. package/dist/profiles.d.ts +2 -2
  66. package/dist/profiles.js +1 -1
  67. package/dist/{protected-model-port-Dd3a1SRm.js → protected-model-port-YclORl0x.js} +2 -2
  68. package/dist/{protected-model-port-Dd3a1SRm.js.map → protected-model-port-YclORl0x.js.map} +1 -1
  69. package/dist/{provision-supervisor-ey6o68i7.js → provision-supervisor-B-_4I1In.js} +7 -7
  70. package/dist/{provision-supervisor-ey6o68i7.js.map → provision-supervisor-B-_4I1In.js.map} +1 -1
  71. package/dist/{redact-BYcuQ6R_.d.ts → redact-C9EWk1FT.d.ts} +3 -3
  72. package/dist/{researcher-BMFFPwKb.js → researcher-hgPa5p9i.js} +2 -2
  73. package/dist/{researcher-BMFFPwKb.js.map → researcher-hgPa5p9i.js.map} +1 -1
  74. package/dist/{runtime-C90NMh9Y.js → runtime-DN0SxAaM.js} +15 -15
  75. package/dist/{runtime-C90NMh9Y.js.map → runtime-DN0SxAaM.js.map} +1 -1
  76. package/dist/{runtime-B-DLSfE5.d.ts → runtime-EQgE3942.d.ts} +23 -7
  77. package/dist/{sandbox-events-DGXLxiuX.js → sandbox-events-DWeQRWxg.js} +4 -2
  78. package/dist/sandbox-events-DWeQRWxg.js.map +1 -0
  79. package/dist/{spawn-journal--N8Ten1q.js → spawn-journal-CxRa-NJ2.js} +2 -2
  80. package/dist/{spawn-journal--N8Ten1q.js.map → spawn-journal-CxRa-NJ2.js.map} +1 -1
  81. package/dist/{stream-agent-turn-DY-y9yW1.d.ts → stream-agent-turn-BomJ21AK.d.ts} +3 -3
  82. package/dist/{stream-agent-turn-B5Cmq-u3.js → stream-agent-turn-DWWe_7bh.js} +4 -4
  83. package/dist/{stream-agent-turn-B5Cmq-u3.js.map → stream-agent-turn-DWWe_7bh.js.map} +1 -1
  84. package/dist/{structural-rollout-CsHxVoVH.js → structural-rollout-DPmVZaLI.js} +6 -6
  85. package/dist/{structural-rollout-CsHxVoVH.js.map → structural-rollout-DPmVZaLI.js.map} +1 -1
  86. package/dist/{substrate-RrmNZoL3.d.ts → substrate-qLePHqvH.d.ts} +2 -2
  87. package/dist/{supervise-rbZ-ppOC.js → supervise-BUy1cr2L.js} +246 -30
  88. package/dist/supervise-BUy1cr2L.js.map +1 -0
  89. package/dist/{supervisor-DBUmrQsF.js → supervisor-BSNkaM2a.js} +154 -23
  90. package/dist/supervisor-BSNkaM2a.js.map +1 -0
  91. package/dist/testing.d.ts +2 -2
  92. package/dist/testing.js +13 -13
  93. package/dist/tui/index.d.ts +1 -1
  94. package/dist/tui/index.js +1 -1
  95. package/dist/{types-B-rWcun_.d.ts → types-BbkiJR1D.d.ts} +37 -4
  96. package/dist/{types-CrTTgig6.d.ts → types-BdolQ6Zi.d.ts} +20 -1
  97. package/dist/{util-D6ZEuBMi.js → util-BfoW6RU7.js} +53 -4
  98. package/dist/util-BfoW6RU7.js.map +1 -0
  99. package/dist/{workspace-archive-ByonPBl-.js → workspace-archive-5K72EnlT.js} +2 -2
  100. package/dist/{workspace-archive-ByonPBl-.js.map → workspace-archive-5K72EnlT.js.map} +1 -1
  101. package/package.json +8 -8
  102. package/dist/environment-provider-6QtI-u5j.js.map +0 -1
  103. package/dist/environment-provider-CzohJCuk.d.ts +0 -89
  104. package/dist/graph-VTmSuXNo.js.map +0 -1
  105. package/dist/model-policy-Sw4ywhtL.js.map +0 -1
  106. package/dist/prepare-Tip-2ZoZ.js.map +0 -1
  107. package/dist/sandbox-events-DGXLxiuX.js.map +0 -1
  108. package/dist/supervise-rbZ-ppOC.js.map +0 -1
  109. package/dist/supervisor-DBUmrQsF.js.map +0 -1
  110. package/dist/util-D6ZEuBMi.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"loop-runner-bin-D2A4NfN7.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 type { AgentProfile } from '@tangle-network/agent-interface'\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 /** Exact profile carried by the personified root that owns this fanout. */\n rootProfile: AgentProfile\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: options.rootProfile, 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":";;;;;;;AAyCA,MAAa,uBAAuB;CAAC;CAAQ;CAAU;CAAY;CAAS;AAAc;;AAM1F,SAAgB,oBAAoB,OAA4C;CAC9E,OAAO,OAAO,UAAU,YAAa,qBAA2C,SAAS,KAAK;AAChG;;;;;;;;;;AAoCA,eAAsB,iBACpB,MACA,UACA,UAAmC,CAAC,GACH;CACjC,MAAM,SAAS,SAAS;CACxB,IAAI,CAAC,QACH,MAAM,IAAI,YACR,oDAAoD,KAAK,iBACvD,OAAO,KAAK,QAAQ,CAAC,CAAC,KAAK,IAAI,KAAK,OACrC,EACH;CAEF,MAAM,MAAM,QAAQ,OAAO,KAAK;CAChC,MAAM,SAAS,QAAQ,UAAU,IAAI,gBAAgB,CAAC,CAAC;CACvD,MAAM,QAAQ,IAAI;CAClB,IAAI;EAEF,OAAO;GAAE;GAAM,IAAI;GAAM,QAAA,MADJ,OAAO,MAAM;GACD,YAAY,IAAI,IAAI;EAAM;CAC7D,SAAS,KAAK;EACZ,OAAO;GACL;GACA,IAAI;GACJ,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;GACtD,YAAY,IAAI,IAAI;EACtB;CACF;AACF;;;;;;;;;;;;;;;AA8CA,SAAgB,mBACd,SAC4C;CAC5C,MAAM,QAAQ,eAAuB;EACnC,UAAU,QAAQ;EAClB,YAAY,QAAQ;EACpB,WAAW,QAAQ;EACnB,GAAI,QAAQ,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AAK,UAAU,IAAI,UAAU,EAAE,OAAO,IAAI,MAAM,GAAG,MAAM,CAAC,EAAE,GAAG;CACvF,IAAI,IAAI,OAAO,QAAQ,OAAO,MAAM,GAAG,IAAI,MAAM,GAAG;CACpD,QAAQ,KAAK,IAAI,QAAQ;AAC3B;AAOA,MAAM,gBAAgB,OAAO,YAAY,cAAc,QAAQ,OAAO,KAAK,KAAA;AAC3E,IAAI,iBAAiB,gCAAgC,KAAK,aAAa,GACrE,KAAU"}
1
+ {"version":3,"file":"loop-runner-bin-DgmtU0F0.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 type { AgentProfile } from '@tangle-network/agent-interface'\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 /** Exact profile carried by the personified root that owns this fanout. */\n rootProfile: AgentProfile\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: options.rootProfile, 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":";;;;;;;AAyCA,MAAa,uBAAuB;CAAC;CAAQ;CAAU;CAAY;CAAS;AAAc;;AAM1F,SAAgB,oBAAoB,OAA4C;CAC9E,OAAO,OAAO,UAAU,YAAa,qBAA2C,SAAS,KAAK;AAChG;;;;;;;;;;AAoCA,eAAsB,iBACpB,MACA,UACA,UAAmC,CAAC,GACH;CACjC,MAAM,SAAS,SAAS;CACxB,IAAI,CAAC,QACH,MAAM,IAAI,YACR,oDAAoD,KAAK,iBACvD,OAAO,KAAK,QAAQ,CAAC,CAAC,KAAK,IAAI,KAAK,OACrC,EACH;CAEF,MAAM,MAAM,QAAQ,OAAO,KAAK;CAChC,MAAM,SAAS,QAAQ,UAAU,IAAI,gBAAgB,CAAC,CAAC;CACvD,MAAM,QAAQ,IAAI;CAClB,IAAI;EAEF,OAAO;GAAE;GAAM,IAAI;GAAM,QAAA,MADJ,OAAO,MAAM;GACD,YAAY,IAAI,IAAI;EAAM;CAC7D,SAAS,KAAK;EACZ,OAAO;GACL;GACA,IAAI;GACJ,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;GACtD,YAAY,IAAI,IAAI;EACtB;CACF;AACF;;;;;;;;;;;;;;;AA8CA,SAAgB,mBACd,SAC4C;CAC5C,MAAM,QAAQ,eAAuB;E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,MAAM,CAAC,CAAC,CAAC,KAAK;CAC7F,CAAC;CACD,QAAQ,OAAO,MAAM,GAAG,KAAK,UAAU,IAAI,UAAU,EAAE,OAAO,IAAI,MAAM,GAAG,MAAM,CAAC,EAAE,GAAG;CACvF,IAAI,IAAI,OAAO,QAAQ,OAAO,MAAM,GAAG,IAAI,MAAM,GAAG;CACpD,QAAQ,KAAK,IAAI,QAAQ;AAC3B;AAOA,MAAM,gBAAgB,OAAO,YAAY,cAAc,QAAQ,OAAO,KAAK,KAAA;AAC3E,IAAI,iBAAiB,gCAAgC,KAAK,aAAa,GACrE,KAAU"}
@@ -1,6 +1,6 @@
1
1
  import { d as RunAnalystLoopOpts, f as RunAnalystLoopResult } from "./types-zWfqDjeL.js";
2
- import { D as AuthoredHarness, O as WorktreeFanoutOptions, ln as WorktreePatchArtifact, ol as WinnerStrategy } from "./index-BhtdFMnG.js";
3
- import { i as Budget } from "./types-B-rWcun_.js";
2
+ import { D as AuthoredHarness, O as WorktreeFanoutOptions, hl as WinnerStrategy, ln as WorktreePatchArtifact } from "./index-DVob1IA1.js";
3
+ import { i as Budget } from "./types-BbkiJR1D.js";
4
4
  import { n as FactCandidate, t as CreateKbGateOptions } from "./kb-gate-C8z2juK8.js";
5
5
  import { AgentProfile } from "@tangle-network/agent-interface";
6
6
  //#region src/loop-runner.d.ts
@@ -162,4 +162,4 @@ declare function parseLoopRunnerArgv(argv: string[]): {
162
162
  };
163
163
  //#endregion
164
164
  export { researchLoopRunner as _, DELEGATED_LOOP_MODES as a, DelegatedLoopResult as c, ResearchLoopRunnerOptions as d, RunDelegatedLoopOptions as f, isDelegatedLoopMode as g, auditLoopRunner as h, runLoopRunnerCli as i, DelegatedLoopRunner as l, WorktreeLoopRunnerOptions as m, LoopRunnerCliResult as n, DelegatedLoopMode as o, VetoedFact as p, parseLoopRunnerArgv as r, DelegatedLoopRegistry as s, LoopRunnerCliArgs as t, ResearchLoopResult as u, runDelegatedLoop as v, worktreeLoopRunner as y };
165
- //# sourceMappingURL=loop-runner-bin-NanoP_bG.d.ts.map
165
+ //# sourceMappingURL=loop-runner-bin-g9fWDuOh.d.ts.map
@@ -1,2 +1,2 @@
1
- import { i as runLoopRunnerCli, n as LoopRunnerCliResult, r as parseLoopRunnerArgv, t as LoopRunnerCliArgs } from "./loop-runner-bin-NanoP_bG.js";
1
+ import { i as runLoopRunnerCli, n as LoopRunnerCliResult, r as parseLoopRunnerArgv, t as LoopRunnerCliArgs } from "./loop-runner-bin-g9fWDuOh.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-D2A4NfN7.js";
2
+ import { n as runLoopRunnerCli, t as parseLoopRunnerArgv } from "./loop-runner-bin-DgmtU0F0.js";
3
3
  export { parseLoopRunnerArgv, runLoopRunnerCli };
package/dist/mcp/bin.js CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  import { i as ConfigError } from "../errors-CDZ8XsVj.js";
3
- import { Zt as readTraceContextFromEnv } from "../supervisor-DBUmrQsF.js";
4
- import { C as createMcpServer, Q as DelegationTaskQueue, ct as FileDelegationStore } from "../supervise-rbZ-ppOC.js";
5
- import { a as supervisorInstructions } from "../authoring-BNQKWhto.js";
3
+ import { Zt as readTraceContextFromEnv } from "../supervisor-BSNkaM2a.js";
4
+ import { $ as DelegationTaskQueue, lt as FileDelegationStore, w as createMcpServer } from "../supervise-BUy1cr2L.js";
5
+ import { a as supervisorInstructions } from "../authoring-fsUwd9hg.js";
6
6
  //#region src/mcp/delegate-supervisor-provisioning.ts
7
7
  function trimmed(value) {
8
8
  const v = value?.trim();
@@ -1,10 +1,10 @@
1
- import { E as SandboxClient, h as LoopSandboxPlacement } from "../types-CrTTgig6.js";
2
- import { $d as DelegationRunContext, Ad as settleDetachedCoderTurn, Af as ResearchOutputShape, Au as CoordinationToolsOptions, Bd as DriveTurnCapableBox, Bf as buildDelegationTraceSpans, Bu as QuestionLevel, Cd as DelegateRunCtx, Cf as DelegationProgress, Cu as AuthorizeDownMessage, Dd as UiAuditorDelegate, Df as DelegationStatusResult, Du as CoordinationEvent, Ed as SettleDetachedCoderTurnOptions, Ef as DelegationStatusArgs, Fd as createFleetWorkspaceExecutor, Ff as DELEGATION_TRACE_MAX_BYTES, Fu as DownMessageEvent, Gd as formatDetachedSessionRef, Gf as DelegationStateCorruptError, Gu as SettledWorker, Hd as RunDetachedTurnOptions, Hf as composeLoopTraceEmitters, Hu as QuestionPolicy, Id as createSiblingSandboxExecutor, If as DELEGATION_TRACE_MAX_SPANS, Iu as MakeWorkerAgent, Jd as DelegationArgs, Jf as FileDelegationStoreOptions, Kd as parseDetachedSessionRef, Kf as DelegationStore, Ld as DetachedSessionRefParts, Lf as DelegationTraceCaps, Lu as Question, Md as FleetHandle, Mf as UiAuditorDelegationOutput, Mu as DownMessageAuthorizationInput, Nd as FleetWorkspaceExecutorOptions, Nf as delegationProfiles, Nu as DownMessageDeliveryAttempt, Od as coderTaskFromArgs, Of as FeedbackRating, Pd as SiblingSandboxExecutorOptions, Pf as CappedDelegationTrace, Pu as DownMessageDeliveryOutcome, Qd as DelegationResumeTick, Qu as WorkerWatchOptions, Rd as DetachedTurn, Rf as DelegationTraceCollector, Ru as QuestionDecision, Sd as CoderReviewer, Sf as DelegationProfile, Td as DetachedWinnerSelection, Tf as DelegationStatus, Tu as ContinuationInstruction, Ud as createDetachedTurnResumeDriver, Uf as createDelegationTraceCollector, Uu as QuestionRecord, Vd as DriveTurnTick, Vf as capDelegationTrace, Vu as QuestionOption, Wd as detachedTurnEvents, Wf as DelegationPersistenceError, Wu as QuestionUrgency, Xd as DelegationResumeContext, Yd as DelegationRecord, Yf as InMemoryDelegationStore, Zd as DelegationResumeDriver, Zu as WorkerSpawnContext, _d as FeedbackStore, _f as DelegationError, ad as createInProcessTransport, af as DelegateCodeArgs, bd as CoderDelegate, bf as DelegationHistoryEntry, cd as DELEGATE_INPUT_SCHEMA, cf as DelegateFeedbackArgs, dd as DelegateError, df as DelegateResearchConfig, ed as createCoordinationTools, ef as DelegationTaskQueue, fd as DelegateHandlerOptions, ff as DelegateResearchResult, gd as FeedbackEvent, gf as DelegateUiAuditRoute, hd as validateDelegateArgs, hf as DelegateUiAuditResult, id as McpServerOptions, if as hashIdempotencyInput, jd as DelegationExecutor, jf as UiAuditLensFilter, ju as DEFAULT_AWAIT_EVENT_TIMEOUT_MS, kd as detachedSessionDelegate, kf as FeedbackRefersTo, ku as CoordinationTools, ld as DELEGATE_TOOL_NAME, lf as DelegateFeedbackResult, lp as CoderOutput, md as createDelegateHandler, mf as DelegateUiAuditConfig, nd as questionEscalationTargets, nf as SubmitInput, od as createMcpServer, of as DelegateCodeConfig, pd as DelegateResult, pf as DelegateUiAuditArgs, qd as runDetachedTurn, qf as FileDelegationStore, rd as McpServer, rf as SubmitOutput, sd as DELEGATE_DESCRIPTION, sf as DelegateCodeResult, tf as DelegationTaskQueueOptions, ud as DelegateArgs, uf as DelegateResearchArgs, vd as InMemoryFeedbackStore, vf as DelegationFeedbackSnapshot, wd as DetachedSessionDelegateOptions, wf as DelegationResultPayload, wu as AuthorizedDownMessage, xd as CoderReview, xf as DelegationHistoryResult, xu as AnalystRegistry, yd as eventToSnapshot, yf as DelegationHistoryArgs, yu as AnalystFindingEvent, zd as DetachedTurnResumeDriverOptions, zf as DelegationTraceSpan, zu as QuestionEscalationTarget } from "../index-BhtdFMnG.js";
3
- import { _t as mergeTraceEnv, gt as createPropagatingTraceEmitter, ht as TraceContext, vt as readTraceContextFromEnv, yt as traceContextToEnv } from "../types-B-rWcun_.js";
4
- import { $ as DiffOptions, Gt as JsonRpcMessage, Jt as McpTransport, Kt as JsonRpcResponse, Q as CreateWorktreeOptions, _t as parseCodexTokenUsage, at as createWorktree, ct as CodexExecutionPolicy, dt as LOCAL_HARNESSES, et as DiffResult, ft as LocalHarness, gt as localHarnessExecutable, ht as harnessSupportsReasoningEffort, it as captureWorktreeDiff, lt as CodexTokenUsage, mt as RunLocalHarnessOptions, nt as RemoveWorktreeOptions, ot as removeWorktree, pt as LocalHarnessResult, qt as McpToolDescriptor, rt as WorktreeHandle, st as CodexExecutionEvidence, tt as GitRunner, ut as DEFAULT_LOCAL_HARNESS, vt as runLocalHarness } from "../runtime-B-DLSfE5.js";
5
- import { d as ResearchSource, o as UiLens } from "../substrate-RrmNZoL3.js";
1
+ import { E as SandboxClient, h as LoopSandboxPlacement } from "../types-BdolQ6Zi.js";
2
+ import { $d as detachedTurnEvents, $f as DelegationPersistenceError, $u as QuestionUrgency, Ad as CoderReview, Af as DelegationHistoryResult, Au as AnalystRegistry, Bd as DelegationExecutor, Bf as UiAuditLensFilter, Bu as DEFAULT_AWAIT_EVENT_TIMEOUT_MS, Cd as createDelegateHandler, Cf as DelegateUiAuditConfig, Dd as InMemoryFeedbackStore, Df as DelegationFeedbackSnapshot, Ed as FeedbackStore, Ef as DelegationError, Fd as SettleDetachedCoderTurnOptions, Ff as DelegationStatusArgs, Gd as createSiblingSandboxExecutor, Gf as DELEGATION_TRACE_MAX_SPANS, Gu as MakeWorkerAgent, Hd as FleetWorkspaceExecutorOptions, Hf as delegationProfiles, Hu as DownMessageDeliveryAttempt, Id as UiAuditorDelegate, If as DelegationStatusResult, Iu as CoordinationEvent, Jd as DetachedTurnResumeDriverOptions, Jf as DelegationTraceSpan, Ju as QuestionEscalationTarget, Kd as DetachedSessionRefParts, Kf as DelegationTraceCaps, Ku as Question, Ld as coderTaskFromArgs, Lf as FeedbackRating, Md as DelegateRunCtx, Mf as DelegationProgress, Mu as AuthorizeDownMessage, Nd as DetachedSessionDelegateOptions, Nf as DelegationResultPayload, Nu as AuthorizedDownMessage, Od as eventToSnapshot, Of as DelegationHistoryArgs, Ou as AnalystFindingEvent, Pd as DetachedWinnerSelection, Pf as DelegationStatus, Pu as ContinuationInstruction, Qd as createDetachedTurnResumeDriver, Qf as createDelegationTraceCollector, Qu as QuestionRecord, Rd as detachedSessionDelegate, Rf as FeedbackRefersTo, Ru as CoordinationTools, Sd as DelegateResult, Sf as DelegateUiAuditArgs, Td as FeedbackEvent, Tf as DelegateUiAuditRoute, Ud as SiblingSandboxExecutorOptions, Uf as CappedDelegationTrace, Uu as DownMessageDeliveryOutcome, Vd as FleetHandle, Vf as UiAuditorDelegationOutput, Vu as DownMessageAuthorizationInput, Wd as createFleetWorkspaceExecutor, Wf as DELEGATION_TRACE_MAX_BYTES, Wu as DownMessageEvent, Xd as DriveTurnTick, Xf as capDelegationTrace, Xu as QuestionOption, Yd as DriveTurnCapableBox, Yf as buildDelegationTraceSpans, Yu as QuestionLevel, Zd as RunDetachedTurnOptions, Zf as composeLoopTraceEmitters, Zu as QuestionPolicy, _d as DELEGATE_INPUT_SCHEMA, _f as DelegateFeedbackArgs, af as DelegationResumeContext, bd as DelegateError, bf as DelegateResearchConfig, cf as DelegationRunContext, dd as questionEscalationTargets, df as SubmitInput, ed as SettledWorker, ef as formatDetachedSessionRef, ep as DelegationStateCorruptError, fd as McpServer, ff as SubmitOutput, gd as DELEGATE_DESCRIPTION, gf as DelegateCodeResult, hd as createMcpServer, hf as DelegateCodeConfig, if as DelegationRecord, ip as InMemoryDelegationStore, jd as CoderReviewer, jf as DelegationProfile, kd as CoderDelegate, kf as DelegationHistoryEntry, ld as createCoordinationTools, lf as DelegationTaskQueue, md as createInProcessTransport, mf as DelegateCodeArgs, nf as runDetachedTurn, np as FileDelegationStore, od as WorkerSpawnContext, of as DelegationResumeDriver, pd as McpServerOptions, pf as hashIdempotencyInput, qd as DetachedTurn, qf as DelegationTraceCollector, qu as QuestionDecision, rf as DelegationArgs, rp as FileDelegationStoreOptions, sd as WorkerWatchOptions, sf as DelegationResumeTick, tf as parseDetachedSessionRef, tp as DelegationStore, uf as DelegationTaskQueueOptions, vd as DELEGATE_TOOL_NAME, vf as DelegateFeedbackResult, vp as CoderOutput, wd as validateDelegateArgs, wf as DelegateUiAuditResult, xd as DelegateHandlerOptions, xf as DelegateResearchResult, yd as DelegateArgs, yf as DelegateResearchArgs, zd as settleDetachedCoderTurn, zf as ResearchOutputShape, zu as CoordinationToolsOptions } from "../index-DVob1IA1.js";
3
+ import { _t as mergeTraceEnv, gt as createPropagatingTraceEmitter, ht as TraceContext, vt as readTraceContextFromEnv, yt as traceContextToEnv } from "../types-BbkiJR1D.js";
4
+ import { $ as DiffOptions, Gt as JsonRpcMessage, Jt as McpTransport, Kt as JsonRpcResponse, Q as CreateWorktreeOptions, _t as parseCodexTokenUsage, at as createWorktree, ct as CodexExecutionPolicy, dt as LOCAL_HARNESSES, et as DiffResult, ft as LocalHarness, gt as localHarnessExecutable, ht as harnessSupportsReasoningEffort, it as captureWorktreeDiff, lt as CodexTokenUsage, mt as RunLocalHarnessOptions, nt as RemoveWorktreeOptions, ot as removeWorktree, pt as LocalHarnessResult, qt as McpToolDescriptor, rt as WorktreeHandle, st as CodexExecutionEvidence, tt as GitRunner, ut as DEFAULT_LOCAL_HARNESS, vt as runLocalHarness } from "../runtime-EQgE3942.js";
5
+ import { d as ResearchSource, o as UiLens } from "../substrate-qLePHqvH.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
- import { n as mcpToolsForRuntimeMcpSubset, t as mcpToolsForRuntimeMcp } from "../openai-tools-Cbk5uBUu.js";
7
+ import { n as mcpToolsForRuntimeMcpSubset, t as mcpToolsForRuntimeMcp } from "../openai-tools-BDwAdxk5.js";
8
8
  import { AgentProfileMcpServer, HarnessType } from "@tangle-network/agent-interface";
9
9
  //#region src/mcp/codex-diagnostics.d.ts
10
10
  /** Bounded, credential-redacted process context attached when reproducible Codex output fails
package/dist/mcp/index.js CHANGED
@@ -1,13 +1,13 @@
1
1
  import { i as ConfigError, m as ValidationError } from "../errors-CDZ8XsVj.js";
2
- import { g as throwIfAborted, h as throwAbort, o as deleteBoxSafe, p as sleep } from "../util-D6ZEuBMi.js";
3
- import { t as assertExecutableAgentProfile } from "../model-policy-Sw4ywhtL.js";
4
- import { Cn as LOCAL_HARNESSES, Dn as CodexExecutionDiagnosticError, En as parseCodexTokenUsage, It as createSandboxForSpec, Qt as traceContextToEnv, Sn as DEFAULT_LOCAL_HARNESS, Tn as localHarnessExecutable, Ut as assertBoxlessPromptOptions, Xt as mergeTraceEnv, Yt as createPropagatingTraceEmitter, Zt as readTraceContextFromEnv, bn as createWorktree, vn as runWorktreeHarness, wn as harnessSupportsReasoningEffort, xn as removeWorktree, yn as captureWorktreeDiff, zt as runAgentRounds } from "../supervisor-DBUmrQsF.js";
5
- import { E as runCoderChecks, ot as selectValidWinner } from "../runtime-C90NMh9Y.js";
6
- import { E as questionEscalationTargets, w as createCoordinationTools, x as DEFAULT_AWAIT_EVENT_TIMEOUT_MS } from "../coordination-driver-Dh_0SvXr.js";
7
- import { $ as hashIdempotencyInput, A as DELEGATION_HISTORY_INPUT_SCHEMA, B as DELEGATE_FEEDBACK_DESCRIPTION, C as createMcpServer, D as createDelegationStatusHandler, E as DELEGATION_STATUS_TOOL_NAME, F as DELEGATE_UI_AUDIT_DESCRIPTION, G as DELEGATE_DESCRIPTION, H as DELEGATE_FEEDBACK_TOOL_NAME, I as DELEGATE_UI_AUDIT_INPUT_SCHEMA, J as createDelegateHandler, K as DELEGATE_INPUT_SCHEMA, L as DELEGATE_UI_AUDIT_TOOL_NAME, M as createDelegationHistoryHandler, N as validateDelegationHistoryArgs, O as validateDelegationStatusArgs, P as delegationProfiles, Q as DelegationTaskQueue, R as createDelegateUiAuditHandler, S as createInProcessTransport, T as DELEGATION_STATUS_INPUT_SCHEMA, U as createDelegateFeedbackHandler, V as DELEGATE_FEEDBACK_INPUT_SCHEMA, W as validateDelegateFeedbackArgs, Y as validateDelegateArgs, at as createDelegationTraceCollector, ct as FileDelegationStore, dt as eventToSnapshot, et as DELEGATION_TRACE_MAX_BYTES, it as composeLoopTraceEmitters, j as DELEGATION_HISTORY_TOOL_NAME, k as DELEGATION_HISTORY_DESCRIPTION, lt as InMemoryDelegationStore, nt as buildDelegationTraceSpans, ot as DelegationPersistenceError, q as DELEGATE_TOOL_NAME, rt as capDelegationTrace, st as DelegationStateCorruptError, tt as DELEGATION_TRACE_MAX_SPANS, ut as InMemoryFeedbackStore, w as DELEGATION_STATUS_DESCRIPTION, z as validateDelegateUiAuditArgs } from "../supervise-rbZ-ppOC.js";
2
+ import { _ as throwIfAborted, g as throwAbort, m as sleep, o as deleteBoxSafe } from "../util-BfoW6RU7.js";
3
+ import { t as assertExecutableAgentProfile } from "../model-policy-Wf2MxXJ9.js";
4
+ import { Cn as LOCAL_HARNESSES, Dn as CodexExecutionDiagnosticError, En as parseCodexTokenUsage, It as createSandboxForSpec, Qt as traceContextToEnv, Sn as DEFAULT_LOCAL_HARNESS, Tn as localHarnessExecutable, Ut as assertBoxlessPromptOptions, Xt as mergeTraceEnv, Yt as createPropagatingTraceEmitter, Zt as readTraceContextFromEnv, bn as createWorktree, vn as runWorktreeHarness, wn as harnessSupportsReasoningEffort, xn as removeWorktree, yn as captureWorktreeDiff, zt as runAgentRounds } from "../supervisor-BSNkaM2a.js";
5
+ import { E as runCoderChecks, ot as selectValidWinner } from "../runtime-DN0SxAaM.js";
6
+ import { E as questionEscalationTargets, w as createCoordinationTools, x as DEFAULT_AWAIT_EVENT_TIMEOUT_MS } from "../coordination-driver-CtbyZv5d.js";
7
+ import { $ as DelegationTaskQueue, A as DELEGATION_HISTORY_DESCRIPTION, B as validateDelegateUiAuditArgs, C as createInProcessTransport, D as DELEGATION_STATUS_TOOL_NAME, E as DELEGATION_STATUS_INPUT_SCHEMA, F as delegationProfiles, G as validateDelegateFeedbackArgs, H as DELEGATE_FEEDBACK_INPUT_SCHEMA, I as DELEGATE_UI_AUDIT_DESCRIPTION, J as DELEGATE_TOOL_NAME, K as DELEGATE_DESCRIPTION, L as DELEGATE_UI_AUDIT_INPUT_SCHEMA, M as DELEGATION_HISTORY_TOOL_NAME, N as createDelegationHistoryHandler, O as createDelegationStatusHandler, P as validateDelegationHistoryArgs, R as DELEGATE_UI_AUDIT_TOOL_NAME, T as DELEGATION_STATUS_DESCRIPTION, U as DELEGATE_FEEDBACK_TOOL_NAME, V as DELEGATE_FEEDBACK_DESCRIPTION, W as createDelegateFeedbackHandler, X as validateDelegateArgs, Y as createDelegateHandler, at as composeLoopTraceEmitters, ct as DelegationStateCorruptError, dt as InMemoryFeedbackStore, et as hashIdempotencyInput, ft as eventToSnapshot, it as capDelegationTrace, j as DELEGATION_HISTORY_INPUT_SCHEMA, k as validateDelegationStatusArgs, lt as FileDelegationStore, nt as DELEGATION_TRACE_MAX_SPANS, ot as createDelegationTraceCollector, q as DELEGATE_INPUT_SCHEMA, rt as buildDelegationTraceSpans, st as DelegationPersistenceError, tt as DELEGATION_TRACE_MAX_BYTES, ut as InMemoryDelegationStore, w as createMcpServer, z as createDelegateUiAuditHandler } from "../supervise-BUy1cr2L.js";
8
8
  import { t as createStdioToolServer } from "../tool-server-DEmLr9YY.js";
9
9
  import { t as createKbGate } from "../kb-gate-DpaSwXVx.js";
10
- import { n as mcpToolsForRuntimeMcpSubset, t as mcpToolsForRuntimeMcp } from "../openai-tools-DCorsAv3.js";
10
+ import { n as mcpToolsForRuntimeMcpSubset, t as mcpToolsForRuntimeMcp } from "../openai-tools-Cz04RKfD.js";
11
11
  import { t as coderTaskToPrompt } from "../coder-yhVWbdWc.js";
12
12
  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-DsKOhzGf.js";
13
13
  import { agentProfileSchema } from "@tangle-network/agent-interface";
@@ -117,10 +117,18 @@ function isHarnessNativeModel(model) {
117
117
  function concreteProfileModel(profile) {
118
118
  return concreteModelId(profile.model?.default);
119
119
  }
120
- /** The provider-facing model id declared by a profile. Direct Router execution uses this form:
121
- * the endpoint already selects the provider, so the model id itself is not harness-prefixed. */
120
+ /**
121
+ * Return the model id for a direct provider request.
122
+ *
123
+ * A portable profile can qualify its model with the selected provider. The direct endpoint already
124
+ * selects that provider, so remove only the exact matching prefix. Preserve every other prefix
125
+ * because it can identify a provider-owned nested route, such as `anthropic/claude-sonnet`.
126
+ */
122
127
  function profileProviderModel(profile) {
123
- return concreteProfileModel(profile);
128
+ const model = concreteProfileModel(profile);
129
+ const provider = profile.model?.provider?.trim();
130
+ if (!model || !provider || !model.startsWith(`${provider}/`)) return model;
131
+ return concreteModelId(model.slice(provider.length + 1));
124
132
  }
125
133
  /** The full cli-bridge wire id declared by a profile: harness/provider/model. */
126
134
  function profileBridgeWireModel(profile) {
@@ -292,4 +300,4 @@ function assertProfileModelsAllowed(profile, allowed) {
292
300
  //#endregion
293
301
  export { concreteProfileModel as a, profileModelExecutionSettings as c, agentHarness as d, harnessRunsAgent as f, concreteModelId as i, profileProviderModel as l, assertModelAllowed as n, enforceTokenLimits as o, assertProfileModelsAllowed as r, profileBridgeWireModel as s, assertExecutableAgentProfile as t, resolveRouterRetryPolicy as u };
294
302
 
295
- //# sourceMappingURL=model-policy-Sw4ywhtL.js.map
303
+ //# sourceMappingURL=model-policy-Wf2MxXJ9.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"model-policy-Wf2MxXJ9.js","names":["positiveInteger"],"sources":["../src/runtime/harness-role.ts","../src/runtime/router-retry-policy.ts","../src/runtime/supervise/model-policy.ts"],"sourcesContent":["/**\n * Which `HarnessType` values name a real coding-agent runtime, and which name a MODE that has no\n * agent behind it.\n *\n * `cli-base` is the router-backed mode — a plain multi-turn router call with no coding-agent\n * harness (`@tangle-network/agent-interface`'s `HarnessType` doc, and the same table's\n * `harnessReasoningCeiling['cli-base'] = 'none'` commented \"cli-base has no agent\"). The\n * distinction is REAL; what was accidental is that three call sites each spelled the test\n * themselves, so a second no-agent mode would have to be remembered in three places.\n *\n * SHOULD UPSTREAM: this belongs next to `harnessHonorsEffort` in agent-interface's\n * `harness-capabilities.ts`, which already encodes the fact but exports no predicate for it.\n * Until it does, this is the one local copy — extend the set here, never re-test the name.\n */\n\nimport type { HarnessType } from '@tangle-network/agent-interface'\n\n/**\n * Harness ids that select a router/no-agent mode rather than a coding-agent runtime.\n *\n * `nanoclaw` is deliberately ABSENT: the shared capability table clamps its reasoning ceiling the\n * same way it clamps `cli-base`, but nanoclaw does run an agent (a socket-bridge runner to the\n * NanoClaw daemon) and every caller here treats it as a full harness. Add a row only with the\n * behavior change stated, never to make the two clamps look symmetric.\n */\nconst NO_AGENT_HARNESSES: ReadonlySet<string> = new Set<string>(['cli-base' satisfies HarnessType])\n\n/** Whether this profile harness selects a real coding-agent runtime (vs. the router/no-agent mode\n * or no preference at all). Accepts the looser `string` some local profile shapes declare, and\n * preserves the caller's own harness type when it is narrower. */\nexport function harnessRunsAgent<T extends string>(harness: T | null | undefined): harness is T {\n return harness != null && !NO_AGENT_HARNESSES.has(harness)\n}\n\n/** The coding-agent harness this profile selects, or `undefined` when it selects none — the shape\n * callers want when a no-agent mode must fall through to the router arm. */\nexport function agentHarness<T extends string>(harness: T | null | undefined): T | undefined {\n return harnessRunsAgent(harness) ? harness : undefined\n}\n","import { ValidationError } from '../errors'\n\n/** Exact retry controls accepted at `AgentProfile.model.metadata.retry`. */\nexport interface RouterRetryPolicy {\n /** Total attempts, including the first request. */\n readonly maxAttempts?: number\n /** Delay before the second attempt. Later delays grow exponentially. */\n readonly initialBackoffMs?: number\n /** Maximum delay between attempts. */\n readonly maxBackoffMs?: number\n /** Symmetric random variation around each delay, from 0 through 1. */\n readonly jitter?: number\n /** HTTP statuses that may be retried. */\n readonly retryStatuses?: ReadonlyArray<number>\n /** Deadline for receiving one attempt's response headers. Zero disables it. */\n readonly requestTimeoutMs?: number\n}\n\nexport interface ResolvedRouterRetryPolicy {\n readonly maxAttempts: number\n readonly initialBackoffMs: number\n readonly maxBackoffMs: number\n readonly jitter: number\n readonly retryStatuses: ReadonlyArray<number>\n readonly requestTimeoutMs: number\n}\n\nconst maximumTimerMs = 2_147_483_647\nconst defaultRetryStatuses = Object.freeze([408, 425, 429, 500, 502, 503, 504, 520, 522, 524])\nconst retryPolicyKeys = new Set([\n 'initialBackoffMs',\n 'jitter',\n 'maxAttempts',\n 'maxBackoffMs',\n 'requestTimeoutMs',\n 'retryStatuses',\n])\n\n/** Parse untrusted profile/config data once and return an immutable complete policy. */\nexport function resolveRouterRetryPolicy(\n input: unknown,\n context: string,\n): ResolvedRouterRetryPolicy {\n if (\n input !== undefined &&\n (typeof input !== 'object' || input === null || Array.isArray(input))\n ) {\n throw new ValidationError(`${context} must be an object`)\n }\n const policy = input === undefined ? {} : Object.fromEntries(Object.entries(input))\n const unknown = Object.keys(policy).filter((key) => !retryPolicyKeys.has(key))\n if (unknown.length > 0) {\n throw new ValidationError(`${context} has unsupported fields: ${unknown.join(', ')}`)\n }\n const maxAttempts = positiveInteger(policy.maxAttempts, 5, `${context}.maxAttempts`)\n const initialBackoffMs = timerInteger(\n policy.initialBackoffMs,\n 1_000,\n `${context}.initialBackoffMs`,\n )\n const maxBackoffMs = timerInteger(policy.maxBackoffMs, 30_000, `${context}.maxBackoffMs`)\n const requestTimeoutMs = timerInteger(policy.requestTimeoutMs, 0, `${context}.requestTimeoutMs`)\n const jitter = policy.jitter ?? 0.25\n if (typeof jitter !== 'number' || !Number.isFinite(jitter) || jitter < 0 || jitter > 1) {\n throw new ValidationError(`${context}.jitter must be a finite number from 0 through 1`)\n }\n const retryStatuses = parseRetryStatuses(policy.retryStatuses, context)\n return Object.freeze({\n maxAttempts,\n initialBackoffMs,\n maxBackoffMs,\n jitter,\n retryStatuses,\n requestTimeoutMs,\n })\n}\n\nfunction parseRetryStatuses(value: unknown, context: string): ReadonlyArray<number> {\n if (value === undefined) return defaultRetryStatuses\n if (!Array.isArray(value)) {\n throw new ValidationError(`${context}.retryStatuses must be an array of HTTP statuses`)\n }\n const statuses: number[] = []\n const seen = new Set<number>()\n for (const status of value) {\n if (!Number.isSafeInteger(status) || status < 100 || status > 599) {\n throw new ValidationError(\n `${context}.retryStatuses must contain integer HTTP statuses from 100 through 599`,\n )\n }\n if (seen.has(status)) {\n throw new ValidationError(`${context}.retryStatuses must not contain duplicates`)\n }\n seen.add(status)\n statuses.push(status)\n }\n return Object.freeze(statuses)\n}\n\nfunction positiveInteger(value: unknown, fallback: number, context: string): number {\n const parsed = value ?? fallback\n if (typeof parsed !== 'number' || !Number.isSafeInteger(parsed) || parsed < 1) {\n throw new ValidationError(`${context} must be a positive safe integer`)\n }\n return parsed\n}\n\nfunction timerInteger(value: unknown, fallback: number, context: string): number {\n const parsed = value ?? fallback\n if (\n typeof parsed !== 'number' ||\n !Number.isSafeInteger(parsed) ||\n parsed < 0 ||\n parsed > maximumTimerMs\n ) {\n throw new ValidationError(\n `${context} must be a nonnegative safe integer no greater than ${maximumTimerMs}`,\n )\n }\n return parsed\n}\n","/**\n * `assertModelAllowed` — a fail-loud guard that restricts a run to a chosen subset of\n * models. The two front doors (`supervise()` / `improve()`) call it once per configured\n * model at resolve time, so a run that names a model outside the allowed set throws before\n * any compute is spent — never silently swapped or silently allowed.\n */\nimport { HARNESS_NATIVE_MODEL } from '@tangle-network/agent-eval'\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { ConfigError } from '../../errors'\nimport { agentHarness } from '../harness-role'\nimport { type ResolvedRouterRetryPolicy, resolveRouterRetryPolicy } from '../router-retry-policy'\n\n/**\n * Return the model id an executor may send to a provider.\n *\n * Eval stamps {@link HARNESS_NATIVE_MODEL} into a profile when model selection is deliberately\n * delegated to the configured runtime. That marker belongs in experiment identity and cost\n * admission; it is not a provider model id.\n */\nexport function concreteModelId(model: string | undefined): string | undefined {\n if (model === undefined) return undefined\n const id = model.trim()\n return id.length > 0 && !isHarnessNativeModel(id) ? id : undefined\n}\n\n/** Whether a model value delegates selection to the chosen execution system. */\nexport function isHarnessNativeModel(model: string | undefined): boolean {\n return model?.trim() === HARNESS_NATIVE_MODEL\n}\n\n/** Return a profile's explicitly selected provider model, if it has one. */\nexport function concreteProfileModel(profile: Pick<AgentProfile, 'model'>): string | undefined {\n return concreteModelId(profile.model?.default)\n}\n\n/**\n * Return the model id for a direct provider request.\n *\n * A portable profile can qualify its model with the selected provider. The direct endpoint already\n * selects that provider, so remove only the exact matching prefix. Preserve every other prefix\n * because it can identify a provider-owned nested route, such as `anthropic/claude-sonnet`.\n */\nexport function profileProviderModel(profile: Pick<AgentProfile, 'model'>): string | undefined {\n const model = concreteProfileModel(profile)\n const provider = profile.model?.provider?.trim()\n if (!model || !provider || !model.startsWith(`${provider}/`)) return model\n return concreteModelId(model.slice(provider.length + 1))\n}\n\n/** The full cli-bridge wire id declared by a profile: harness/provider/model. */\nexport function profileBridgeWireModel(\n profile: Pick<AgentProfile, 'harness' | 'model'>,\n): string | undefined {\n const model = concreteProfileModel(profile)\n const provider = profile.model?.provider\n const harness = agentHarness(profile.harness)\n const modelWithoutHarness =\n model && harness && model.startsWith(`${harness}/`) ? model.slice(harness.length + 1) : model\n const providerModel = modelWithoutHarness\n ? provider && !modelWithoutHarness.startsWith(`${provider}/`)\n ? `${provider}/${modelWithoutHarness}`\n : modelWithoutHarness\n : undefined\n if (!harness) return providerModel\n if (!providerModel) return harness\n return providerModel.startsWith(`${harness}/`) ? providerModel : `${harness}/${providerModel}`\n}\n\n/**\n * Refuse an incomplete execution identity before any backend may fill it from ambient config.\n * `AgentProfile` is the sole behavioral authority: harness, provider, and concrete model all\n * participate in its digest. Eval's runtime-selected marker is a matrix-planning value, never an\n * executable model.\n */\nexport function assertExecutableAgentProfile(profile: AgentProfile, context: string): void {\n if (profile.harness === undefined) {\n throw new ConfigError(`${context}: AgentProfile.harness must be explicit before execution`)\n }\n const declared = profile.model?.default\n const model = concreteModelId(declared)\n if (!model) {\n const reason = isHarnessNativeModel(declared) ? 'runtime-selected' : 'missing'\n throw new ConfigError(\n `${context}: AgentProfile.model.default is ${reason}; execution requires a concrete model`,\n )\n }\n if (!profile.model?.provider?.trim()) {\n throw new ConfigError(\n `${context}: AgentProfile.model.provider must be explicit before execution`,\n )\n }\n}\n\n/**\n * Separate completion ceilings an exact profile may request.\n *\n * They are distinct because providers do not share one meaning for a single number: measured\n * through the Tangle Router on 2026-08-10, `glm-5.2` accepted `max_tokens: 8` and still billed 135\n * completion tokens — 132 reasoning, 3 visible — while `max_completion_tokens: 256` bounded the\n * total. A path that cannot enforce a requested ceiling refuses the run instead of sending a\n * number that means something else there.\n */\nexport interface ProfileTokenLimits {\n /** Visible answer tokens, from `AgentProfile.model.maxVisibleOutputTokens`. */\n readonly visible?: number\n /** Hidden reasoning tokens, from `AgentProfile.model.maxReasoningTokens`. */\n readonly reasoning?: number\n /** Visible and reasoning tokens together, from `AgentProfile.model.maxTotalOutputTokens`. */\n readonly total?: number\n}\n\n/** The ceilings one execution path actually sends, in the request fields it sends them as. */\nexport interface AppliedTokenLimits {\n /** Sent as `max_tokens`. */\n readonly maxTokens?: number\n /** Sent as `max_completion_tokens`. */\n readonly maxCompletionTokens?: number\n}\n\n/** What a path was asked to enforce and what it sent, for the execution receipt. */\nexport interface TokenLimitDecision {\n readonly requested: ProfileTokenLimits\n readonly applied: AppliedTokenLimits\n}\n\n/** The execution paths that lower a profile into a provider request. */\nexport type ModelExecutionPath = 'router' | 'bridge' | 'sandbox' | 'provider'\n\n/** Generation and loop controls that may affect one model execution. */\nexport interface ProfileModelExecutionSettings {\n readonly temperature?: number\n /** Completion ceilings the profile requested. Empty when it requested none. */\n readonly tokenLimits: ProfileTokenLimits\n readonly retry?: ResolvedRouterRetryPolicy\n readonly seed?: number\n readonly toolChoice?: 'auto' | 'required' | 'none'\n readonly extraBody?: Readonly<Record<string, unknown>>\n /** Zero means no turn-count cap; conserved budgets and deadlines still apply. */\n readonly maxTurns?: number\n readonly stream?: boolean\n}\n\nconst PROFILE_MODEL_METADATA_KEYS = new Set([\n 'extraBody',\n 'maxTurns',\n 'retry',\n 'seed',\n 'stream',\n 'temperature',\n 'toolChoice',\n])\n\n/**\n * Read every Router-affecting control from the exact profile and reject unknown controls.\n * Backends receive endpoint/auth and executable ports only; they cannot silently alter behavior.\n */\nexport function profileModelExecutionSettings(\n profile: Pick<AgentProfile, 'model'>,\n context: string,\n): ProfileModelExecutionSettings {\n const metadata = profile.model?.metadata ?? {}\n if (metadata.maxTokens !== undefined) {\n throw new ConfigError(\n `${context}: AgentProfile.model.metadata.maxTokens is ambiguous across providers; declare AgentProfile.model.maxVisibleOutputTokens, maxReasoningTokens, or maxTotalOutputTokens instead`,\n )\n }\n const unknown = Object.keys(metadata).filter((key) => !PROFILE_MODEL_METADATA_KEYS.has(key))\n if (unknown.length > 0) {\n throw new ConfigError(\n `${context}: unsupported AgentProfile.model.metadata fields: ${unknown.join(', ')}`,\n )\n }\n const temperature = finiteNumber(metadata.temperature, `${context}: temperature`)\n const tokenLimits = profileTokenLimits(profile, context)\n const retryInput = metadata.retry\n const retry =\n retryInput === undefined\n ? undefined\n : resolveRouterRetryPolicy(retryInput, `${context}: AgentProfile.model.metadata.retry`)\n const seed = safeInteger(metadata.seed, `${context}: seed`)\n const maxTurns = nonnegativeInteger(metadata.maxTurns, `${context}: maxTurns`)\n const stream = optionalBoolean(metadata.stream, `${context}: stream`)\n const toolChoice = metadata.toolChoice\n if (\n toolChoice !== undefined &&\n toolChoice !== 'auto' &&\n toolChoice !== 'required' &&\n toolChoice !== 'none'\n ) {\n throw new ConfigError(`${context}: toolChoice must be auto, required, or none`)\n }\n const extraBody = metadata.extraBody\n if (\n extraBody !== undefined &&\n (typeof extraBody !== 'object' || extraBody === null || Array.isArray(extraBody))\n ) {\n throw new ConfigError(`${context}: extraBody must be an object`)\n }\n return {\n ...(temperature !== undefined ? { temperature } : {}),\n tokenLimits,\n ...(retry !== undefined ? { retry } : {}),\n ...(seed !== undefined ? { seed } : {}),\n ...(toolChoice !== undefined ? { toolChoice } : {}),\n ...(extraBody !== undefined\n ? { extraBody: Object.freeze({ ...(extraBody as Record<string, unknown>) }) }\n : {}),\n ...(maxTurns !== undefined ? { maxTurns } : {}),\n ...(stream !== undefined ? { stream } : {}),\n }\n}\n\n/**\n * Read the completion ceilings an exact profile declares. The Interface schema already refines\n * these fields, but a profile can reach an executor without a parse, so the same rules are\n * enforced here: positive integers, and no single ceiling above the total.\n */\nexport function profileTokenLimits(\n profile: Pick<AgentProfile, 'model'>,\n context: string,\n): ProfileTokenLimits {\n const model = profile.model\n const visible = positiveInteger(\n model?.maxVisibleOutputTokens,\n `${context}: maxVisibleOutputTokens`,\n )\n const reasoning = positiveInteger(model?.maxReasoningTokens, `${context}: maxReasoningTokens`)\n const total = positiveInteger(model?.maxTotalOutputTokens, `${context}: maxTotalOutputTokens`)\n if (total !== undefined) {\n for (const [name, value] of [\n ['maxVisibleOutputTokens', visible],\n ['maxReasoningTokens', reasoning],\n ] as const) {\n if (value !== undefined && value > total) {\n throw new ConfigError(\n `${context}: AgentProfile.model.${name} (${value}) exceeds maxTotalOutputTokens (${total})`,\n )\n }\n }\n }\n return {\n ...(visible !== undefined ? { visible } : {}),\n ...(reasoning !== undefined ? { reasoning } : {}),\n ...(total !== undefined ? { total } : {}),\n }\n}\n\n/**\n * Lower the requested ceilings onto one execution path, or refuse the run before any paid\n * transport.\n *\n * - Router and OpenAI-compatible routes send the visible ceiling as `max_tokens` and the total as\n * `max_completion_tokens`.\n * - The CLI Bridge lowers ONE completion cap into the run's model catalog, so it carries the total\n * as `max_tokens` and cannot bound the visible half on its own.\n * - The Sandbox and environment-provider paths expose no completion cap at all.\n * - No route publishes a reasoning-token budget, so a reasoning ceiling is refused everywhere.\n * `AgentProfile.model.reasoningEffort` is an intensity dial, not a token bound.\n */\nexport function enforceTokenLimits(\n limits: ProfileTokenLimits,\n path: ModelExecutionPath,\n context: string,\n): TokenLimitDecision {\n const refuse = (field: string, reason: string): never => {\n throw new ConfigError(\n `${context}: AgentProfile.model.${field} cannot be enforced on the ${path} path (${reason}); remove the ceiling or select a path that enforces it`,\n )\n }\n if (limits.reasoning !== undefined) {\n refuse('maxReasoningTokens', 'no route exposes a reasoning-token budget')\n }\n if (path === 'router') {\n return {\n requested: limits,\n applied: {\n ...(limits.visible !== undefined ? { maxTokens: limits.visible } : {}),\n ...(limits.total !== undefined ? { maxCompletionTokens: limits.total } : {}),\n },\n }\n }\n if (path === 'bridge') {\n if (limits.visible !== undefined) {\n refuse('maxVisibleOutputTokens', 'the bridge lowers one completion cap covering both halves')\n }\n return {\n requested: limits,\n applied: {\n ...(limits.total !== undefined ? { maxTokens: limits.total } : {}),\n },\n }\n }\n if (limits.visible !== undefined) refuse('maxVisibleOutputTokens', 'the backend accepts no cap')\n if (limits.total !== undefined) refuse('maxTotalOutputTokens', 'the backend accepts no cap')\n return { requested: limits, applied: {} }\n}\n\n/** The receipt form of one path's ceilings: what was asked for, and what was sent. */\nexport function tokenLimitReceipt(decision: TokenLimitDecision): {\n readonly requested: ProfileTokenLimits\n readonly applied: AppliedTokenLimits\n} {\n return { requested: decision.requested, applied: decision.applied }\n}\n\nfunction finiteNumber(value: unknown, context: string): number | undefined {\n if (value === undefined) return undefined\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n throw new ConfigError(`${context} must be a finite number`)\n }\n return value\n}\n\nfunction safeInteger(value: unknown, context: string): number | undefined {\n if (value === undefined) return undefined\n if (!Number.isSafeInteger(value)) throw new ConfigError(`${context} must be a safe integer`)\n return value as number\n}\n\nfunction positiveInteger(value: unknown, context: string): number | undefined {\n const parsed = safeInteger(value, context)\n if (parsed !== undefined && parsed < 1) {\n throw new ConfigError(`${context} must be positive`)\n }\n return parsed\n}\n\nfunction nonnegativeInteger(value: unknown, context: string): number | undefined {\n const parsed = safeInteger(value, context)\n if (parsed !== undefined && parsed < 0) {\n throw new ConfigError(`${context} must be nonnegative`)\n }\n return parsed\n}\n\nfunction optionalBoolean(value: unknown, context: string): boolean | undefined {\n if (value === undefined) return undefined\n if (typeof value !== 'boolean') throw new ConfigError(`${context} must be boolean`)\n return value\n}\n\n/**\n * Throw a `ConfigError` when `allowed` is set, `model` is defined, and `model` is not a\n * member of `allowed`. No-op when `allowed` is unset (the unrestricted default) or when\n * `model` is undefined (nothing was configured to check).\n */\nexport function assertModelAllowed(\n model: string | undefined,\n allowed: readonly string[] | undefined,\n): void {\n if (!allowed || model === undefined) return\n if (!allowed.includes(model)) {\n throw new ConfigError(\n `model ${JSON.stringify(model)} is not in the allowed set ${JSON.stringify([...allowed])}`,\n )\n }\n}\n\n/** Check every canonical model-bearing field in a complete profile, including the models a\n * backend may select for cheap work, named subagents, or modes.\n *\n * Every compared value is a bare model id. The composed `harness/provider/model` wire id\n * (`profileBridgeWireModel`) is neither built nor compared here, so this admits any route that\n * declares an allowed id, and a qualified entry in `allowed` matches nothing. Route pinning\n * belongs to `SuperviseOptions.authorizeSpawn`. */\nexport function assertProfileModelsAllowed(\n profile: AgentProfile,\n allowed: readonly string[] | undefined,\n): void {\n assertModelAllowed(profile.model?.default, allowed)\n assertModelAllowed(profile.model?.small, allowed)\n for (const subagent of Object.values(profile.subagents ?? {})) {\n assertModelAllowed(subagent.model, allowed)\n }\n for (const mode of Object.values(profile.modes ?? {})) {\n assertModelAllowed(mode.model, allowed)\n }\n}\n"],"mappings":";;;;;;;;;;;AAyBA,MAAM,qCAA0C,IAAI,IAAY,CAAC,UAAgC,CAAC;;;;AAKlG,SAAgB,iBAAmC,SAA6C;CAC9F,OAAO,WAAW,QAAQ,CAAC,mBAAmB,IAAI,OAAO;AAC3D;;;AAIA,SAAgB,aAA+B,SAA8C;CAC3F,OAAO,iBAAiB,OAAO,IAAI,UAAU,KAAA;AAC/C;;;ACXA,MAAM,iBAAiB;AACvB,MAAM,uBAAuB,OAAO,OAAO;CAAC;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;AAAG,CAAC;AAC7F,MAAM,kCAAkB,IAAI,IAAI;CAC9B;CACA;CACA;CACA;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C,QAAQ,SAAS,KAAK,GACzB,MAAM,IAAI,YACR,SAAS,KAAK,UAAU,KAAK,EAAE,6BAA6B,KAAK,UAAU,CAAC,GAAG,OAAO,CAAC,GACzF;AAEJ;;;;;;;;AASA,SAAgB,2BACd,SACA,SACM;CACN,mBAAmB,QAAQ,OAAO,SAAS,OAAO;CAClD,mBAAmB,QAAQ,OAAO,OAAO,OAAO;CAChD,KAAK,MAAM,YAAY,OAAO,OAAO,QAAQ,aAAa,CAAC,CAAC,GAC1D,mBAAmB,SAAS,OAAO,OAAO;CAE5C,KAAK,MAAM,QAAQ,OAAO,OAAO,QAAQ,SAAS,CAAC,CAAC,GAClD,mBAAmB,KAAK,OAAO,OAAO;AAE1C"}
@@ -1,4 +1,4 @@
1
- import { Q as OpenAIChatTool } from "./types-CrTTgig6.js";
1
+ import { Q as OpenAIChatTool } from "./types-BdolQ6Zi.js";
2
2
  //#region src/mcp/openai-tools.d.ts
3
3
  /**
4
4
  *
@@ -21,4 +21,4 @@ declare function mcpToolsForRuntimeMcp(): OpenAIChatTool[];
21
21
  declare function mcpToolsForRuntimeMcpSubset(names: ReadonlyArray<string>): OpenAIChatTool[];
22
22
  //#endregion
23
23
  export { mcpToolsForRuntimeMcpSubset as n, mcpToolsForRuntimeMcp as t };
24
- //# sourceMappingURL=openai-tools-Cbk5uBUu.d.ts.map
24
+ //# sourceMappingURL=openai-tools-BDwAdxk5.d.ts.map
@@ -1,4 +1,4 @@
1
- import { A as DELEGATION_HISTORY_INPUT_SCHEMA, B as DELEGATE_FEEDBACK_DESCRIPTION, E as DELEGATION_STATUS_TOOL_NAME, H as DELEGATE_FEEDBACK_TOOL_NAME, T as DELEGATION_STATUS_INPUT_SCHEMA, V as DELEGATE_FEEDBACK_INPUT_SCHEMA, j as DELEGATION_HISTORY_TOOL_NAME, k as DELEGATION_HISTORY_DESCRIPTION, w as DELEGATION_STATUS_DESCRIPTION } from "./supervise-rbZ-ppOC.js";
1
+ import { A as DELEGATION_HISTORY_DESCRIPTION, D as DELEGATION_STATUS_TOOL_NAME, E as DELEGATION_STATUS_INPUT_SCHEMA, H as DELEGATE_FEEDBACK_INPUT_SCHEMA, M as DELEGATION_HISTORY_TOOL_NAME, T as DELEGATION_STATUS_DESCRIPTION, U as DELEGATE_FEEDBACK_TOOL_NAME, V as DELEGATE_FEEDBACK_DESCRIPTION, j as DELEGATION_HISTORY_INPUT_SCHEMA } from "./supervise-BUy1cr2L.js";
2
2
  //#region src/mcp/openai-tools.ts
3
3
  function buildTool(name, description, parameters) {
4
4
  return {
@@ -41,4 +41,4 @@ function mcpToolsForRuntimeMcpSubset(names) {
41
41
  //#endregion
42
42
  export { mcpToolsForRuntimeMcpSubset as n, mcpToolsForRuntimeMcp as t };
43
43
 
44
- //# sourceMappingURL=openai-tools-DCorsAv3.js.map
44
+ //# sourceMappingURL=openai-tools-Cz04RKfD.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"openai-tools-DCorsAv3.js","names":[],"sources":["../src/mcp/openai-tools.ts"],"sourcesContent":["/**\n *\n * OpenAI Chat Completions `tools[]` projection of the queue-bound agent-runtime\n * MCP delegation tools.\n *\n * Use when a caller-owned OpenAI-compatible transport needs the model to call\n * `delegate_feedback`, `delegation_status`, and `delegation_history`. Execution\n * is the caller's responsibility (typically the parent sandbox runtime's MCP\n * mount); Runtime's profile-bound model path materializes profile tools through\n * its executor instead.\n *\n * Sandbox-SDK callers do NOT need this helper: the sandbox runtime mounts\n * MCP servers natively and the in-sandbox harness discovers tools via the\n * runtime, not via an OpenAI tools array.\n *\n * Tool name + description + JSON-schema are pulled from the canonical\n * `DELEGATE_*` constants exported by `./tools/*` so the projection cannot\n * drift from the server's own validators.\n *\n * @experimental\n */\n\nimport type { OpenAIChatTool } from '../types'\nimport {\n DELEGATE_FEEDBACK_DESCRIPTION,\n DELEGATE_FEEDBACK_INPUT_SCHEMA,\n DELEGATE_FEEDBACK_TOOL_NAME,\n} from './tools/delegate-feedback'\nimport {\n DELEGATION_HISTORY_DESCRIPTION,\n DELEGATION_HISTORY_INPUT_SCHEMA,\n DELEGATION_HISTORY_TOOL_NAME,\n} from './tools/delegation-history'\nimport {\n DELEGATION_STATUS_DESCRIPTION,\n DELEGATION_STATUS_INPUT_SCHEMA,\n DELEGATION_STATUS_TOOL_NAME,\n} from './tools/delegation-status'\n\nfunction buildTool(\n name: string,\n description: string,\n parameters: Readonly<Record<string, unknown>>,\n): OpenAIChatTool {\n // `parameters` arrives as a deeply-readonly `as const` literal. The\n // OpenAI-compatible transports JSON-serialize the body, so a shallow copy\n // into a plain object is sufficient and shields callers that mutate\n // the returned descriptor from corrupting the source constant.\n return {\n type: 'function',\n function: { name, description, parameters: { ...parameters } },\n }\n}\n\n/**\n *\n * Returns the queue-bound delegation tools projected into OpenAI Chat\n * Completions `tools[]` shape. The order is stable: `delegate_feedback`,\n * `delegation_status`, `delegation_history`.\n *\n * @experimental\n */\nexport function mcpToolsForRuntimeMcp(): OpenAIChatTool[] {\n return [\n buildTool(\n DELEGATE_FEEDBACK_TOOL_NAME,\n DELEGATE_FEEDBACK_DESCRIPTION,\n DELEGATE_FEEDBACK_INPUT_SCHEMA as Readonly<Record<string, unknown>>,\n ),\n buildTool(\n DELEGATION_STATUS_TOOL_NAME,\n DELEGATION_STATUS_DESCRIPTION,\n DELEGATION_STATUS_INPUT_SCHEMA as Readonly<Record<string, unknown>>,\n ),\n buildTool(\n DELEGATION_HISTORY_TOOL_NAME,\n DELEGATION_HISTORY_DESCRIPTION,\n DELEGATION_HISTORY_INPUT_SCHEMA as Readonly<Record<string, unknown>>,\n ),\n ]\n}\n\n/**\n *\n * Subset filter — return only the projected tools whose `function.name`\n * appears in `names`. Useful for curated mounts (e.g. only the queue-bound\n * delegation tools, omitting `delegate_feedback`). Unknown names are\n * silently ignored; pass an empty array to get an empty result.\n *\n * @experimental\n */\nexport function mcpToolsForRuntimeMcpSubset(names: ReadonlyArray<string>): OpenAIChatTool[] {\n const allowed = new Set(names)\n return mcpToolsForRuntimeMcp().filter((tool) => allowed.has(tool.function.name))\n}\n"],"mappings":";;AAuCA,SAAS,UACP,MACA,aACA,YACgB;CAKhB,OAAO;EACL,MAAM;EACN,UAAU;GAAE;GAAM;GAAa,YAAY,EAAE,GAAG,WAAW;EAAE;CAC/D;AACF;;;;;;;;;AAUA,SAAgB,wBAA0C;CACxD,OAAO;EACL,UACE,6BACA,+BACA,8BACF;EACA,UACE,6BACA,+BACA,8BACF;EACA,UACE,8BACA,gCACA,+BACF;CACF;AACF;;;;;;;;;;AAWA,SAAgB,4BAA4B,OAAgD;CAC1F,MAAM,UAAU,IAAI,IAAI,KAAK;CAC7B,OAAO,sBAAsB,CAAC,CAAC,QAAQ,SAAS,QAAQ,IAAI,KAAK,SAAS,IAAI,CAAC;AACjF"}
1
+ {"version":3,"file":"openai-tools-Cz04RKfD.js","names":[],"sources":["../src/mcp/openai-tools.ts"],"sourcesContent":["/**\n *\n * OpenAI Chat Completions `tools[]` projection of the queue-bound agent-runtime\n * MCP delegation tools.\n *\n * Use when a caller-owned OpenAI-compatible transport needs the model to call\n * `delegate_feedback`, `delegation_status`, and `delegation_history`. Execution\n * is the caller's responsibility (typically the parent sandbox runtime's MCP\n * mount); Runtime's profile-bound model path materializes profile tools through\n * its executor instead.\n *\n * Sandbox-SDK callers do NOT need this helper: the sandbox runtime mounts\n * MCP servers natively and the in-sandbox harness discovers tools via the\n * runtime, not via an OpenAI tools array.\n *\n * Tool name + description + JSON-schema are pulled from the canonical\n * `DELEGATE_*` constants exported by `./tools/*` so the projection cannot\n * drift from the server's own validators.\n *\n * @experimental\n */\n\nimport type { OpenAIChatTool } from '../types'\nimport {\n DELEGATE_FEEDBACK_DESCRIPTION,\n DELEGATE_FEEDBACK_INPUT_SCHEMA,\n DELEGATE_FEEDBACK_TOOL_NAME,\n} from './tools/delegate-feedback'\nimport {\n DELEGATION_HISTORY_DESCRIPTION,\n DELEGATION_HISTORY_INPUT_SCHEMA,\n DELEGATION_HISTORY_TOOL_NAME,\n} from './tools/delegation-history'\nimport {\n DELEGATION_STATUS_DESCRIPTION,\n DELEGATION_STATUS_INPUT_SCHEMA,\n DELEGATION_STATUS_TOOL_NAME,\n} from './tools/delegation-status'\n\nfunction buildTool(\n name: string,\n description: string,\n parameters: Readonly<Record<string, unknown>>,\n): OpenAIChatTool {\n // `parameters` arrives as a deeply-readonly `as const` literal. The\n // OpenAI-compatible transports JSON-serialize the body, so a shallow copy\n // into a plain object is sufficient and shields callers that mutate\n // the returned descriptor from corrupting the source constant.\n return {\n type: 'function',\n function: { name, description, parameters: { ...parameters } },\n }\n}\n\n/**\n *\n * Returns the queue-bound delegation tools projected into OpenAI Chat\n * Completions `tools[]` shape. The order is stable: `delegate_feedback`,\n * `delegation_status`, `delegation_history`.\n *\n * @experimental\n */\nexport function mcpToolsForRuntimeMcp(): OpenAIChatTool[] {\n return [\n buildTool(\n DELEGATE_FEEDBACK_TOOL_NAME,\n DELEGATE_FEEDBACK_DESCRIPTION,\n DELEGATE_FEEDBACK_INPUT_SCHEMA as Readonly<Record<string, unknown>>,\n ),\n buildTool(\n DELEGATION_STATUS_TOOL_NAME,\n DELEGATION_STATUS_DESCRIPTION,\n DELEGATION_STATUS_INPUT_SCHEMA as Readonly<Record<string, unknown>>,\n ),\n buildTool(\n DELEGATION_HISTORY_TOOL_NAME,\n DELEGATION_HISTORY_DESCRIPTION,\n DELEGATION_HISTORY_INPUT_SCHEMA as Readonly<Record<string, unknown>>,\n ),\n ]\n}\n\n/**\n *\n * Subset filter — return only the projected tools whose `function.name`\n * appears in `names`. Useful for curated mounts (e.g. only the queue-bound\n * delegation tools, omitting `delegate_feedback`). Unknown names are\n * silently ignored; pass an empty array to get an empty result.\n *\n * @experimental\n */\nexport function mcpToolsForRuntimeMcpSubset(names: ReadonlyArray<string>): OpenAIChatTool[] {\n const allowed = new Set(names)\n return mcpToolsForRuntimeMcp().filter((tool) => allowed.has(tool.function.name))\n}\n"],"mappings":";;AAuCA,SAAS,UACP,MACA,aACA,YACgB;CAKhB,OAAO;EACL,MAAM;EACN,UAAU;GAAE;GAAM;GAAa,YAAY,EAAE,GAAG,WAAW;EAAE;CAC/D;AACF;;;;;;;;;AAUA,SAAgB,wBAA0C;CACxD,OAAO;EACL,UACE,6BACA,+BACA,8BACF;EACA,UACE,6BACA,+BACA,8BACF;EACA,UACE,8BACA,gCACA,+BACF;CACF;AACF;;;;;;;;;;AAWA,SAAgB,4BAA4B,OAAgD;CAC1F,MAAM,UAAU,IAAI,IAAI,KAAK;CAC7B,OAAO,sBAAsB,CAAC,CAAC,QAAQ,SAAS,QAAQ,IAAI,KAAK,SAAS,IAAI,CAAC;AACjF"}