@tangle-network/agent-runtime 0.113.1 → 0.115.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/dist/{activation-UZ1JenNv.js → activation-BNQQO-bc.js} +3 -3
  2. package/dist/{activation-UZ1JenNv.js.map → activation-BNQQO-bc.js.map} +1 -1
  3. package/dist/agent.d.ts +18 -7
  4. package/dist/agent.js +123 -64
  5. package/dist/agent.js.map +1 -1
  6. package/dist/candidate-execution/index.js +4 -4
  7. package/dist/{candidate-execution-Co3sRC_7.js → candidate-execution-CfpJrd3o.js} +4 -4
  8. package/dist/{candidate-execution-Co3sRC_7.js.map → candidate-execution-CfpJrd3o.js.map} +1 -1
  9. package/dist/{environment-provider-BsHpW4Dp.js → environment-provider-CCaEhA-l.js} +38 -4
  10. package/dist/environment-provider-CCaEhA-l.js.map +1 -0
  11. package/dist/{environment-provider-DG-cSx89.d.ts → environment-provider-Cygthiy3.d.ts} +40 -1
  12. package/dist/environment-provider.d.ts +1 -1
  13. package/dist/environment-provider.js +1 -1
  14. package/dist/{improvement-cycle-C3CrNfcy.js → improvement-cycle-CBLOgfsQ.js} +4 -4
  15. package/dist/{improvement-cycle-C3CrNfcy.js.map → improvement-cycle-CBLOgfsQ.js.map} +1 -1
  16. package/dist/{index-Cr7QlEUL.d.ts → index-B_vcAAle.d.ts} +6 -6
  17. package/dist/{index-zMAqz53v.d.ts → index-BuzkRsOn.d.ts} +244 -9
  18. package/dist/{index-B6WclhZI.d.ts → index-I97xACXk.d.ts} +3 -3
  19. package/dist/index.d.ts +8 -8
  20. package/dist/index.js +13 -13
  21. package/dist/intelligence.d.ts +3 -3
  22. package/dist/intelligence.js +6 -6
  23. package/dist/kernel.d.ts +4 -4
  24. package/dist/kernel.js +7 -7
  25. package/dist/{knowledge-GAJFl_gz.js → knowledge-DcIKJaPd.js} +5 -5
  26. package/dist/{knowledge-GAJFl_gz.js.map → knowledge-DcIKJaPd.js.map} +1 -1
  27. package/dist/knowledge.d.ts +1 -1
  28. package/dist/knowledge.js +1 -1
  29. package/dist/{local-harness-Ce1emWJE.d.ts → local-harness-BnB1E9nM.d.ts} +82 -2
  30. package/dist/{loop-runner-bin-DvLdFo38.js → loop-runner-bin-C2GIqSUn.js} +3 -3
  31. package/dist/{loop-runner-bin-DvLdFo38.js.map → loop-runner-bin-C2GIqSUn.js.map} +1 -1
  32. package/dist/{loop-runner-bin-Cba5tsdb.d.ts → loop-runner-bin-DgAXgQCI.d.ts} +3 -3
  33. package/dist/loop-runner-bin.d.ts +1 -1
  34. package/dist/loop-runner-bin.js +1 -1
  35. package/dist/mcp/bin.js +2 -2
  36. package/dist/mcp/index.d.ts +2 -2
  37. package/dist/mcp/index.js +5 -5
  38. package/dist/{openai-tools-DftmzKLc.js → openai-tools-BWAEIHkZ.js} +2 -2
  39. package/dist/{openai-tools-DftmzKLc.js.map → openai-tools-BWAEIHkZ.js.map} +1 -1
  40. package/dist/{otel-export-D34IQW1C.js → otel-export-CPZTSADj.js} +16 -7
  41. package/dist/otel-export-CPZTSADj.js.map +1 -0
  42. package/dist/{prepare-BKVdOn0w.js → prepare-BHQBb02e.js} +2 -2
  43. package/dist/{prepare-BKVdOn0w.js.map → prepare-BHQBb02e.js.map} +1 -1
  44. package/dist/primeintellect/index.d.ts +1 -1
  45. package/dist/{protected-model-port-BtldAE9j.js → protected-model-port-DqAH1Z2M.js} +2 -2
  46. package/dist/{protected-model-port-BtldAE9j.js.map → protected-model-port-DqAH1Z2M.js.map} +1 -1
  47. package/dist/{redact-xZvPu9qe.d.ts → redact-BRaHUFMf.d.ts} +2 -2
  48. package/dist/{runtime-DlSPFm9o.js → runtime-C_g_SsXg.js} +8 -5
  49. package/dist/runtime-C_g_SsXg.js.map +1 -0
  50. package/dist/{spawn-journal-DLhnom3e.js → spawn-journal-DCPbicXB.js} +2 -1
  51. package/dist/{spawn-journal-DLhnom3e.js.map → spawn-journal-DCPbicXB.js.map} +1 -1
  52. package/dist/{structural-rollout-R_ZqFaB5.js → structural-rollout-Cqm1dKa7.js} +3 -3
  53. package/dist/{structural-rollout-R_ZqFaB5.js.map → structural-rollout-Cqm1dKa7.js.map} +1 -1
  54. package/dist/{supervise-BDvAFOTM.js → supervise-BcCHhLrz.js} +807 -35
  55. package/dist/supervise-BcCHhLrz.js.map +1 -0
  56. package/dist/{supervisor-DS278ICs.js → supervisor-CspDspod.js} +250 -22
  57. package/dist/supervisor-CspDspod.js.map +1 -0
  58. package/dist/testing.js +9 -9
  59. package/dist/{trace-propagation-CJJC7SVB.js → trace-propagation-B-pL7xn_.js} +2 -2
  60. package/dist/{trace-propagation-CJJC7SVB.js.map → trace-propagation-B-pL7xn_.js.map} +1 -1
  61. package/dist/{workspace-archive-CYYxZyA7.js → workspace-archive-DXzJq7WP.js} +2 -2
  62. package/dist/{workspace-archive-CYYxZyA7.js.map → workspace-archive-DXzJq7WP.js.map} +1 -1
  63. package/package.json +1 -1
  64. package/dist/environment-provider-BsHpW4Dp.js.map +0 -1
  65. package/dist/otel-export-D34IQW1C.js.map +0 -1
  66. package/dist/runtime-DlSPFm9o.js.map +0 -1
  67. package/dist/supervise-BDvAFOTM.js.map +0 -1
  68. package/dist/supervisor-DS278ICs.js.map +0 -1
@@ -117,6 +117,10 @@ type ToolLoopChat = (messages: ReadonlyArray<ToolLoopMessageRecord>, tools: Read
117
117
  /** The turn's inference cost (usd) when the provider priced it — for callers that meter usd
118
118
  * into a conserved pool (the supervisor brain). `runBrainLoop` itself ignores it. */
119
119
  costUsd?: number;
120
+ /** The turn ran but its usage was not reported when the transport EXPECTED one (the streamed
121
+ * router transport asks for usage and this says it never arrived). A metering caller records an
122
+ * unknown turn on it; `runBrainLoop` itself ignores it. */
123
+ usageUnknown?: true;
120
124
  }>;
121
125
  /** Self-compaction — bound the loop's OWN context window the way a fresh-respawn (dumb-Ralph) loop
122
126
  * does, but in place. A stateless chat API re-sends the WHOLE running conversation every turn, so an
@@ -174,6 +178,31 @@ interface RouterConfig {
174
178
  * lives here rather than on one call site.
175
179
  */
176
180
  maxTokens?: number;
181
+ /**
182
+ * Take the tool-calling completion over SSE instead of one buffered POST. Off by default —
183
+ * `routerChatWithTools` never streams, and every existing caller keeps the buffered transport
184
+ * byte for byte.
185
+ *
186
+ * Why it exists: a buffered POST holds one connection idle for the WHOLE completion, and a
187
+ * supervisor turn is the longest completion in the system. An intermediary gateway with an
188
+ * idle-read timeout kills that connection mid-completion (the 524/503 family). A streamed
189
+ * response puts bytes on the wire from the first generated token on, so the connection is only
190
+ * idle through prefill. It does NOT shorten prefill, so a gateway whose deadline is
191
+ * time-to-FIRST-byte is unaffected; only an idle-timeout gateway is.
192
+ *
193
+ * Mutually exclusive with `complete`: the injected transport returns one parsed JSON body and has
194
+ * no stream to read, so setting both throws rather than silently taking the buffered path.
195
+ *
196
+ * WHICH PATHS CAN OPT IN. This flag is read in exactly one place (the private `chatWithTools` transport switch), so
197
+ * every entry point that takes a caller-supplied `RouterConfig` honors it: `routerBrain`,
198
+ * `routerToolLoop`, and `supervisorAgent` (which spreads `deps.router` into the brain's config —
199
+ * the supervisor turn this exists for). Two production call sites build a `RouterConfig` literal
200
+ * from their own options and therefore CANNOT express it today: the bench strategy's
201
+ * `routerToolLoop` config in `strategy.ts` and the local sandbox client's `routerBrain` config in
202
+ * `local-sandbox-client.ts`. Neither drives a supervisor-length turn; setting `stream` on a
203
+ * config handed to either has no path to reach them, and they stay buffered.
204
+ */
205
+ stream?: boolean;
177
206
  }
178
207
  interface RouterChatResult {
179
208
  /** The final answer, with any inline `<think>...</think>` block stripped into `reasoning`. */
@@ -228,6 +257,29 @@ interface RouterChatToolsResult {
228
257
  output: number;
229
258
  };
230
259
  costUsd?: number;
260
+ /**
261
+ * Thinking-model reasoning, normalized the way `RouterChatResult.reasoning` is (a separate
262
+ * `reasoning_content`/`reasoning` field, or an inline `<think>` block split out of `content`).
263
+ * Populated by the STREAMED path only — `routerChatWithTools` discards reasoning today and its
264
+ * behavior is preserved unchanged, so a buffered turn still leaves this undefined.
265
+ */
266
+ reasoning?: string;
267
+ /**
268
+ * The provider's `finish_reason` for the turn (`'stop'`, `'tool_calls'`, `'length'`, …).
269
+ * Populated by the STREAMED path only. `'length'` is the truncation signal the buffered path
270
+ * cannot surface: it says the turn hit `max_tokens`, not that the model chose to stop.
271
+ */
272
+ finishReason?: string;
273
+ /**
274
+ * The turn happened and its token usage is UNKNOWN — not zero, not free. Set by the STREAMED
275
+ * transport when the stream ran to completion without a single usage-bearing chunk, which means
276
+ * the `stream_options.include_usage` contract was not honored upstream.
277
+ *
278
+ * It exists so a bare `usage: undefined` cannot read as a free turn: a metering caller branches
279
+ * on this marker and records an UNKNOWN turn (see the coordination driver's `meteredBrain`),
280
+ * rather than skipping the turn and letting a conserved budget pool believe it cost nothing.
281
+ */
282
+ usageUnknown?: true;
231
283
  }
232
284
  /**
233
285
  * A router completion WITH tool-calling — the operator driver's LLM seam. Passes OpenAI-shape
@@ -248,6 +300,31 @@ declare function routerChatWithTools(cfg: RouterConfig, messages: ReadonlyArray<
248
300
  toolChoice?: 'auto' | 'required' | 'none';
249
301
  maxTokens?: number;
250
302
  }): Promise<RouterChatToolsResult>;
303
+ /**
304
+ * The SAME completion as `routerChatWithTools`, taken over SSE (`stream: true`) and reassembled
305
+ * into the identical `RouterChatToolsResult`. Opt in with `RouterConfig.stream` — the buffered
306
+ * function is untouched and stays the default for every existing caller.
307
+ *
308
+ * What it buys: a buffered POST holds one connection idle for the whole completion, and that idle
309
+ * window is what an intermediary gateway kills (524/503). Streaming puts bytes on the wire from the
310
+ * first generated token, so the connection is only idle through prefill.
311
+ *
312
+ * Usage accounting is preserved exactly: `stream_options.include_usage` asks the provider for a
313
+ * terminal usage chunk, and those tokens run through the same `meterTurn` the buffered path uses.
314
+ *
315
+ * When NO chunk reported usage, `usage`/`costUsd` stay undefined (never a fabricated 0) AND
316
+ * `usageUnknown: true` is set. A stream that finishes with no usage chunk means the
317
+ * `include_usage` request was not honored upstream, and returning a quiet `undefined` for it is
318
+ * indistinguishable from a free turn — the marker is what lets a metering caller record an UNKNOWN
319
+ * turn instead. Streaming raises the odds of this (one dropped terminal frame is enough), which is
320
+ * why the streamed transport says so explicitly and the buffered one has no equivalent claim to make.
321
+ */
322
+ declare function streamRouterChatWithTools(cfg: RouterConfig, messages: ReadonlyArray<Record<string, unknown>>, tools: ReadonlyArray<ToolSpec>, opts?: {
323
+ temperature?: number;
324
+ signal?: AbortSignal;
325
+ toolChoice?: 'auto' | 'required' | 'none';
326
+ maxTokens?: number;
327
+ }): Promise<RouterChatToolsResult>;
251
328
  interface ToolSpec {
252
329
  type: 'function';
253
330
  function: {
@@ -302,6 +379,9 @@ declare function routerToolLoop(cfg: RouterConfig, system: string, user: string,
302
379
  * tool-calling. The driver's spawn/observe/steer/await/stop turns become real router tool-calls.
303
380
  * The turnkey production brain — tests script a mock `ToolLoopChat`; production passes
304
381
  * `routerBrain(cfg)`. No message translation: the loop already speaks the router's OpenAI shape.
382
+ *
383
+ * Transport follows `cfg.stream`: buffered by default, SSE when the caller opts in. A supervisor
384
+ * turn is the longest completion in the system, so it is the call site streaming exists for.
305
385
  */
306
386
  declare function routerBrain(cfg: RouterConfig, opts?: {
307
387
  temperature?: number;
@@ -461,5 +541,5 @@ declare function runLocalHarness(options: RunLocalHarnessOptions): Promise<Local
461
541
  /** Parse and validate the one terminal usage event emitted by `codex exec --json`. */
462
542
  declare function parseCodexTokenUsage(stdout: string): CodexTokenUsage;
463
543
  //#endregion
464
- export { createRuntimeEventCollector as A, RuntimeEventCollector as C, RuntimeTelemetryOptions as D, RuntimeStreamEventSummary as E, sanitizeAgentRuntimeEvent as M, sanitizeKnowledgeReadinessReport as N, SanitizedKnowledgeReadinessReport as O, sanitizeRuntimeStreamEvent as P, ToolLoopMessageRecord as S, RuntimeStreamEventSink as T, routerChatWithUsage as _, LocalHarnessResult as a, ToolLoopCompaction as b, runLocalHarness as c, RouterConfig as d, RouterToolCall as f, routerChatWithTools as g, routerBrain as h, LocalHarness as i, createRuntimeStreamEventCollector as j, SanitizedKnowledgeRequirement as k, RouterChatResult as l, ToolSpec as m, CodexExecutionPolicy as n, RunLocalHarnessOptions as o, RouterToolLoopResult as p, CodexTokenUsage as r, parseCodexTokenUsage as s, CodexExecutionEvidence as t, RouterChatToolsResult as u, routerToolLoop as v, RuntimeStreamEventCollector as w, ToolLoopCompactionOptions as x, ToolLoopChat as y };
465
- //# sourceMappingURL=local-harness-Ce1emWJE.d.ts.map
544
+ export { SanitizedKnowledgeRequirement as A, ToolLoopMessageRecord as C, RuntimeStreamEventSummary as D, RuntimeStreamEventSink as E, sanitizeRuntimeStreamEvent as F, createRuntimeStreamEventCollector as M, sanitizeAgentRuntimeEvent as N, RuntimeTelemetryOptions as O, sanitizeKnowledgeReadinessReport as P, ToolLoopCompactionOptions as S, RuntimeStreamEventCollector as T, routerChatWithUsage as _, LocalHarnessResult as a, ToolLoopChat as b, runLocalHarness as c, RouterConfig as d, RouterToolCall as f, routerChatWithTools as g, routerBrain as h, LocalHarness as i, createRuntimeEventCollector as j, SanitizedKnowledgeReadinessReport as k, RouterChatResult as l, ToolSpec as m, CodexExecutionPolicy as n, RunLocalHarnessOptions as o, RouterToolLoopResult as p, CodexTokenUsage as r, parseCodexTokenUsage as s, CodexExecutionEvidence as t, RouterChatToolsResult as u, routerToolLoop as v, RuntimeEventCollector as w, ToolLoopCompaction as x, streamRouterChatWithTools as y };
545
+ //# sourceMappingURL=local-harness-BnB1E9nM.d.ts.map
@@ -1,7 +1,7 @@
1
1
  import { i as ConfigError } from "./errors-DEAvWQPy.js";
2
- import { J as runPersonified, d as worktreeFanout, q as definePersona } from "./runtime-DlSPFm9o.js";
2
+ import { J as runPersonified, d as worktreeFanout, q as definePersona } from "./runtime-C_g_SsXg.js";
3
3
  import { t as runAnalystLoop } from "./analyst-loop-BoNIG2hA.js";
4
- import { kt as createExecutorRegistry } from "./supervise-BDvAFOTM.js";
4
+ import { kt as createExecutorRegistry } from "./supervise-BcCHhLrz.js";
5
5
  import { t as createKbGate } from "./kb-gate-DpaSwXVx.js";
6
6
  //#region src/loop-runner.ts
7
7
  /**
@@ -265,4 +265,4 @@ if (invokedScript && /loop-runner-bin\.(js|ts|mjs)$/.test(invokedScript)) main()
265
265
  //#endregion
266
266
  export { isDelegatedLoopMode as a, worktreeLoopRunner as c, auditLoopRunner as i, runLoopRunnerCli as n, researchLoopRunner as o, DELEGATED_LOOP_MODES as r, runDelegatedLoop as s, parseLoopRunnerArgv as t };
267
267
 
268
- //# sourceMappingURL=loop-runner-bin-DvLdFo38.js.map
268
+ //# sourceMappingURL=loop-runner-bin-C2GIqSUn.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"loop-runner-bin-DvLdFo38.js","names":[],"sources":["../src/loop-runner.ts","../src/loop-runner-bin.ts"],"sourcesContent":["/**\n *\n * `runDelegatedLoop` — the configured delegated loop-runner.\n *\n * One typed entrypoint a worker agent (or a scheduled routine) calls to run a\n * disciplined loop in a chosen MODE, over agent-runtime's hardened engines:\n *\n * code → build-in-a-loop on the GENERIC recursive path (worktreeLoopRunner: author one\n * `AgentProfile` per harness → worktree-CLI leaves → `patchDelivered` gate)\n * review → caller-registered runner — a `code` runner with an approval gate over candidates\n * research → research-in-a-loop with valid-only KB growth (createKbGate)\n * audit → analyze trace/run data → findings (runAnalystLoop, caller-wired)\n * self-improve → caller-registered `improve(profile, options)` run\n *\n * It is intentionally a thin façade: the value is that EVERY product reuses the\n * one hardened engine instead of forking delegation logic. The dispatcher owns\n * mode routing, timing, fail-loud on an unregistered mode, and a uniform result\n * shape; each mode's engine is a pre-configured runner in the registry (build it\n * with the factories below, or inject your own / a stub).\n *\n * @experimental\n */\n\nimport { runAnalystLoop } from './analyst-loop'\nimport type { RunAnalystLoopOpts, RunAnalystLoopResult } from './analyst-loop/types'\nimport { ConfigError } from './errors'\nimport { type CreateKbGateOptions, createKbGate, type FactCandidate } from './mcp/kb-gate'\nimport {\n type AuthoredHarness,\n type Budget,\n createExecutorRegistry,\n definePersona,\n runPersonified,\n type WinnerStrategy,\n type WorktreeFanoutOptions,\n type WorktreePatchArtifact,\n worktreeFanout,\n} from './runtime'\n\n/** All valid delegated-loop mode names — used for validation and CLI surfaces. @experimental */\nexport const DELEGATED_LOOP_MODES = ['code', 'review', 'research', 'audit', 'self-improve'] as const\n\n/** @experimental */\nexport type DelegatedLoopMode = (typeof DELEGATED_LOOP_MODES)[number]\n\n/** Type guard — returns true when `value` is a valid `DelegatedLoopMode` string. @experimental */\nexport function isDelegatedLoopMode(value: unknown): value is DelegatedLoopMode {\n return typeof value === 'string' && (DELEGATED_LOOP_MODES as readonly string[]).includes(value)\n}\n\n/** @experimental A pre-configured loop for one mode. Returns the mode's raw\n * output; the dispatcher wraps it in a {@link DelegatedLoopResult}. */\nexport type DelegatedLoopRunner<T = unknown> = (signal: AbortSignal) => Promise<T>\n\n/** @experimental Mode → configured runner. Partial: only register the modes a\n * given product/routine actually uses. */\nexport type DelegatedLoopRegistry = Partial<Record<DelegatedLoopMode, DelegatedLoopRunner>>\n\n/** @experimental Uniform result — never throws from a registered runner; a\n * thrown engine becomes `{ ok: false, error }` so a routine can record + move on. */\nexport interface DelegatedLoopResult<T = unknown> {\n mode: DelegatedLoopMode\n ok: boolean\n output?: T\n error?: string\n durationMs: number\n}\n\n/** @experimental */\nexport interface RunDelegatedLoopOptions {\n signal?: AbortSignal\n /** Clock override for deterministic tests. */\n now?: () => number\n}\n\n/**\n *\n * Dispatch a configured loop by mode. Fails loud (throws `ConfigError`) when no\n * runner is registered for the mode — a routine pointed at an unwired mode is a\n * config bug, not a silent no-op. A runner that throws is captured as\n * `{ ok: false }` so unattended runs record the failure rather than crash.\n *\n * @experimental\n */\nexport async function runDelegatedLoop<T = unknown>(\n mode: DelegatedLoopMode,\n registry: DelegatedLoopRegistry,\n options: RunDelegatedLoopOptions = {},\n): Promise<DelegatedLoopResult<T>> {\n const runner = registry[mode] as DelegatedLoopRunner<T> | undefined\n if (!runner) {\n throw new ConfigError(\n `runDelegatedLoop: no runner registered for mode '${mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n )\n }\n const now = options.now ?? Date.now\n const signal = options.signal ?? new AbortController().signal\n const start = now()\n try {\n const output = await runner(signal)\n return { mode, ok: true, output, durationMs: now() - start }\n } catch (err) {\n return {\n mode,\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n durationMs: now() - start,\n }\n }\n}\n\n/** @experimental Options for the local-repo `code` runner over the GENERIC recursive path. */\nexport interface WorktreeLoopRunnerOptions {\n /** Absolute path to the local git checkout each worktree is cut from. */\n repoRoot: string\n /** The instruction handed to every authored harness (composed under each profile's systemPrompt). */\n taskPrompt: string\n /** The supervisor-authored harness profiles — one fanout item (one worktree-CLI leaf) each. */\n harnesses: ReadonlyArray<AuthoredHarness>\n /** Conserved budget pool bounding the fanout (equal-k holds by construction). */\n budget: Budget\n /** Shell command run in each worktree to derive the tests-PASS signal. */\n testCmd?: string\n /** Shell command run in each worktree to derive the typecheck-PASS signal. */\n typecheckCmd?: string\n /** Which verification signals the deliverable REQUIRES present-and-passing (default none). */\n require?: ReadonlyArray<'tests' | 'typecheck'>\n /** Diff-size cap (lines). */\n maxDiffLines?: number\n /** Literal path prefixes the patch must not touch (the secret-floor is always on regardless). */\n forbiddenPaths?: string[]\n /** Winner-selection strategy among gated candidates. Default `highest-score`. */\n winnerStrategy?: WinnerStrategy\n /** Test seams forwarded to the worktree-CLI leaves so the runner drives offline. */\n runGit?: WorktreeFanoutOptions['runGit']\n runHarness?: WorktreeFanoutOptions['runHarness']\n runCommand?: WorktreeFanoutOptions['runCommand']\n}\n\n/**\n *\n * `code` mode on the GENERIC recursive path: author one `AgentProfile` per harness, run them as a\n * `worktreeFanout` (N `createWorktreeCliExecutor` leaves, each `gateOnDeliverable`) through\n * `runPersonified` on the keystone Supervisor. The sandbox-session counterpart that drives the in-box\n * harness over a `SandboxClient` is `detachedSessionDelegate` (`./mcp/delegates`); here there is no\n * `runAgentRounds` driver, no role-coupled delegate — the harness list is the fanout, the gate is\n * `patchDelivered`,\n * the winner is the shared valid-only selector (NOT `defaultSelectWinner`, whose non-valid fallback\n * would surface an ungated patch). Equal-k holds by the conserved budget pool. Returns the winning\n * patch artifact, or throws when no candidate is delivered (fail loud, never a vacuous done).\n *\n * @experimental\n */\nexport function worktreeLoopRunner(\n options: WorktreeLoopRunnerOptions,\n): DelegatedLoopRunner<WorktreePatchArtifact> {\n const shape = worktreeFanout<string>({\n repoRoot: options.repoRoot,\n taskPrompt: options.taskPrompt,\n harnesses: options.harnesses,\n ...(options.testCmd !== undefined ? { testCmd: options.testCmd } : {}),\n ...(options.typecheckCmd !== undefined ? { typecheckCmd: options.typecheckCmd } : {}),\n ...(options.require !== undefined ? { require: options.require } : {}),\n ...(options.maxDiffLines !== undefined ? { maxDiffLines: options.maxDiffLines } : {}),\n ...(options.forbiddenPaths !== undefined ? { forbiddenPaths: options.forbiddenPaths } : {}),\n ...(options.winnerStrategy !== undefined ? { winnerStrategy: options.winnerStrategy } : {}),\n ...(options.runGit ? { runGit: options.runGit } : {}),\n ...(options.runHarness ? { runHarness: options.runHarness } : {}),\n ...(options.runCommand ? { runCommand: options.runCommand } : {}),\n })\n // The persona's only role here is to carry the fanout shape onto the Supervisor; each item's\n // executor is BYO (the gated worktree-CLI leaf), so the registry only needs to pass BYO through.\n const persona = definePersona<WorktreePatchArtifact>({\n name: 'worktree-coder',\n root: { profile: { name: 'worktree-coder' }, harness: null },\n directive: 'deliver a minimal validated patch on a fresh worktree',\n context: { role: 'coder' },\n executors: { registry: createExecutorRegistry() },\n })\n return async (signal) => {\n const result = await runPersonified<string, WorktreePatchArtifact>({\n persona,\n shape,\n task: options.taskPrompt,\n budget: options.budget,\n signal,\n })\n if (result.kind !== 'winner' || result.out.kind !== 'done') {\n const blockers =\n result.kind === 'winner' && result.out.kind === 'blocked'\n ? result.out.blockers.join('; ')\n : `supervisor settled ${result.kind}`\n throw new Error(`worktreeLoopRunner: no delivered patch (${blockers})`)\n }\n return result.out.deliverable\n }\n}\n\n/** @experimental A fact rejected at the KB gate — surfaced, never dropped. */\nexport interface VetoedFact {\n candidate: FactCandidate\n vetoedBy?: string\n reason?: string\n}\n\n/** @experimental */\nexport interface ResearchLoopResult {\n /** Facts that passed the fail-closed gate — safe to write to the KB. */\n accepted: FactCandidate[]\n /** Facts the gate vetoed in the final round — escalate, do not silently drop. */\n vetoed: VetoedFact[]\n /** Research rounds actually run. */\n rounds: number\n}\n\n/** @experimental Options for the default `research` runner. */\nexport interface ResearchLoopRunnerOptions {\n /**\n * The research engine (the consumer's web/doc searcher + extractor). Called\n * each round with the prior round's vetoes so it can re-research the gaps.\n * Returns fact candidates carrying their grounding (`verbatimPassage` +\n * `sourceText`).\n */\n research: (round: number, vetoed: VetoedFact[]) => Promise<FactCandidate[]>\n /** Gate config (extra judges, self-artifact kinds, …). The floor is always on. */\n gate?: CreateKbGateOptions\n /** Max research rounds (correct-on-veto remediation). Default 1. */\n maxRounds?: number\n}\n\n/**\n * `research` mode — research-in-a-loop with valid-only KB growth.\n *\n * Each round: research → gate every candidate (fail-closed; passage MUST be in\n * the source) → accept the clean ones → re-research the vetoed ones next round,\n * up to `maxRounds`. Vetoed facts in the final round are RETURNED (escalate,\n * never silently dropped) so the caller audits vs retries.\n *\n * @experimental\n */\nexport function researchLoopRunner(\n o: ResearchLoopRunnerOptions,\n): DelegatedLoopRunner<ResearchLoopResult> {\n const gate = createKbGate(o.gate)\n const maxRounds = Math.max(1, Math.trunc(o.maxRounds ?? 1))\n return async (signal) => {\n const accepted: FactCandidate[] = []\n let vetoed: VetoedFact[] = []\n let rounds = 0\n for (let round = 0; round < maxRounds; round += 1) {\n if (signal.aborted) break\n rounds += 1\n const candidates = await o.research(round, vetoed)\n if (candidates.length === 0) break\n vetoed = []\n for (const c of candidates) {\n const v = await gate(c)\n if (v.accepted) accepted.push(c)\n else vetoed.push({ candidate: c, vetoedBy: v.vetoedBy, reason: v.reason })\n }\n if (vetoed.length === 0) break\n }\n return { accepted, vetoed, rounds }\n }\n}\n\n/**\n * `audit` mode — analyst loop over captured trace/run data.\n *\n * @experimental\n */\nexport function auditLoopRunner<TProposal = unknown, TEdit = unknown>(\n options: RunAnalystLoopOpts,\n): DelegatedLoopRunner<RunAnalystLoopResult<TProposal, TEdit>> {\n return async () => runAnalystLoop<TProposal, TEdit>(options)\n}\n","#!/usr/bin/env node\n/**\n *\n * `agent-runtime-loop` — the schedulable entrypoint for the configured\n * delegated loop-runner. A cron job / routine / Makefile target invokes:\n *\n * agent-runtime-loop --mode research --config ./loops.config.js\n *\n * The config module wires the registry (with full access to env / creds —\n * which is why the deps live there, not in this generic bin). It must default-\n * export a `DelegatedLoopRegistry`, or a `() => DelegatedLoopRegistry | Promise<…>`.\n * The bin runs the selected mode, prints the `DelegatedLoopResult` as JSON, and\n * exits 0 on `ok`, 1 on a recorded failure, 2 on a usage/config error.\n *\n * @experimental\n */\n\nimport {\n DELEGATED_LOOP_MODES,\n type DelegatedLoopMode,\n type DelegatedLoopRegistry,\n type DelegatedLoopResult,\n isDelegatedLoopMode,\n runDelegatedLoop,\n} from './loop-runner'\n\n/** @experimental Parsed CLI invocation. */\nexport interface LoopRunnerCliArgs {\n mode: string\n /** Loads the registry — the bin wires this from `--config`; tests inject a stub. */\n loadRegistry: () => Promise<DelegatedLoopRegistry> | DelegatedLoopRegistry\n now?: () => number\n}\n\n/** @experimental */\nexport interface LoopRunnerCliResult {\n exitCode: number\n result?: DelegatedLoopResult\n error?: string\n}\n\n/**\n *\n * Pure CLI core (no process / argv / IO) so it's unit-testable: validate the\n * mode, load the registry, dispatch, map to an exit code (0 ok / 1 failed /\n * 2 usage). Exported for embedding in custom runners + tests.\n *\n * @experimental\n */\nexport async function runLoopRunnerCli(args: LoopRunnerCliArgs): Promise<LoopRunnerCliResult> {\n if (!isDelegatedLoopMode(args.mode)) {\n return {\n exitCode: 2,\n error: `unknown mode '${args.mode}' (expected one of: ${DELEGATED_LOOP_MODES.join(', ')})`,\n }\n }\n let registry: DelegatedLoopRegistry\n try {\n registry = await args.loadRegistry()\n } catch (err) {\n return { exitCode: 2, error: `failed to load registry: ${errMsg(err)}` }\n }\n if (!registry[args.mode]) {\n return {\n exitCode: 2,\n error: `config registers no runner for mode '${args.mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n }\n }\n // runDelegatedLoop throws only on a missing runner (guarded above); a failing\n // engine is captured as { ok: false } → exit 1, not a crash.\n const result = await runDelegatedLoop(args.mode as DelegatedLoopMode, registry, {\n ...(args.now ? { now: args.now } : {}),\n })\n return { exitCode: result.ok ? 0 : 1, result }\n}\n\n/** Parse `--mode X --config Y` from an argv tail (`process.argv.slice(2)`). */\nexport function parseLoopRunnerArgv(argv: string[]): { mode?: string; config?: string } {\n const out: { mode?: string; config?: string } = {}\n for (let i = 0; i < argv.length; i += 1) {\n const a = argv[i]\n if (a === '--mode') out.mode = argv[++i]\n else if (a === '--config') out.config = argv[++i]\n else if (a?.startsWith('--mode=')) out.mode = a.slice('--mode='.length)\n else if (a?.startsWith('--config=')) out.config = a.slice('--config='.length)\n }\n return out\n}\n\n/** Normalize a config module's default export → a registry. */\nfunction resolveRegistry(mod: unknown): DelegatedLoopRegistry {\n const def = (mod as { default?: unknown })?.default ?? mod\n const value = typeof def === 'function' ? (def as () => unknown)() : def\n return value as DelegatedLoopRegistry\n}\n\nfunction errMsg(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n\n/** The argv → IO → exit shell. Kept thin; logic lives in `runLoopRunnerCli`. */\nasync function main(): Promise<void> {\n const { mode, config } = parseLoopRunnerArgv(process.argv.slice(2))\n if (!mode || !config) {\n process.stderr.write(\n 'usage: agent-runtime-loop --mode <mode> --config <module>\\n' +\n ` modes: ${DELEGATED_LOOP_MODES.join(' | ')}\\n` +\n ' config: a JS/TS module default-exporting a DelegatedLoopRegistry (or a factory)\\n',\n )\n process.exit(2)\n }\n const { pathToFileURL } = await import('node:url')\n const { resolve } = await import('node:path')\n const cli = await runLoopRunnerCli({\n mode,\n loadRegistry: async () => resolveRegistry(await import(pathToFileURL(resolve(config)).href)),\n })\n process.stdout.write(`${JSON.stringify(cli.result ?? { error: cli.error }, null, 2)}\\n`)\n if (cli.error) process.stderr.write(`${cli.error}\\n`)\n process.exit(cli.exitCode)\n}\n\n// Run only when executed as the bin — never when imported for the testable\n// core, and never when bundled into a runtime that has no `process.argv`\n// (e.g. Cloudflare Workers, where `process` is a shim without `argv`). Reading\n// `process.argv[1]` directly would throw at module load there; `process.argv?.`\n// keeps the guard a no-op instead of crashing the Worker on startup.\nconst invokedScript = typeof process !== 'undefined' ? process.argv?.[1] : undefined\nif (invokedScript && /loop-runner-bin\\.(js|ts|mjs)$/.test(invokedScript)) {\n void main()\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,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;;;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jC,MAAM,MAAM,MAAM,iBAAiB;EACjC;EACA,cAAc,YAAY,gBAAgB,MAAM,OAAO,cAAc,QAAQ,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
+ {"version":3,"file":"loop-runner-bin-C2GIqSUn.js","names":[],"sources":["../src/loop-runner.ts","../src/loop-runner-bin.ts"],"sourcesContent":["/**\n *\n * `runDelegatedLoop` — the configured delegated loop-runner.\n *\n * One typed entrypoint a worker agent (or a scheduled routine) calls to run a\n * disciplined loop in a chosen MODE, over agent-runtime's hardened engines:\n *\n * code → build-in-a-loop on the GENERIC recursive path (worktreeLoopRunner: author one\n * `AgentProfile` per harness → worktree-CLI leaves → `patchDelivered` gate)\n * review → caller-registered runner — a `code` runner with an approval gate over candidates\n * research → research-in-a-loop with valid-only KB growth (createKbGate)\n * audit → analyze trace/run data → findings (runAnalystLoop, caller-wired)\n * self-improve → caller-registered `improve(profile, options)` run\n *\n * It is intentionally a thin façade: the value is that EVERY product reuses the\n * one hardened engine instead of forking delegation logic. The dispatcher owns\n * mode routing, timing, fail-loud on an unregistered mode, and a uniform result\n * shape; each mode's engine is a pre-configured runner in the registry (build it\n * with the factories below, or inject your own / a stub).\n *\n * @experimental\n */\n\nimport { runAnalystLoop } from './analyst-loop'\nimport type { RunAnalystLoopOpts, RunAnalystLoopResult } from './analyst-loop/types'\nimport { ConfigError } from './errors'\nimport { type CreateKbGateOptions, createKbGate, type FactCandidate } from './mcp/kb-gate'\nimport {\n type AuthoredHarness,\n type Budget,\n createExecutorRegistry,\n definePersona,\n runPersonified,\n type WinnerStrategy,\n type WorktreeFanoutOptions,\n type WorktreePatchArtifact,\n worktreeFanout,\n} from './runtime'\n\n/** All valid delegated-loop mode names — used for validation and CLI surfaces. @experimental */\nexport const DELEGATED_LOOP_MODES = ['code', 'review', 'research', 'audit', 'self-improve'] as const\n\n/** @experimental */\nexport type DelegatedLoopMode = (typeof DELEGATED_LOOP_MODES)[number]\n\n/** Type guard — returns true when `value` is a valid `DelegatedLoopMode` string. @experimental */\nexport function isDelegatedLoopMode(value: unknown): value is DelegatedLoopMode {\n return typeof value === 'string' && (DELEGATED_LOOP_MODES as readonly string[]).includes(value)\n}\n\n/** @experimental A pre-configured loop for one mode. Returns the mode's raw\n * output; the dispatcher wraps it in a {@link DelegatedLoopResult}. */\nexport type DelegatedLoopRunner<T = unknown> = (signal: AbortSignal) => Promise<T>\n\n/** @experimental Mode → configured runner. Partial: only register the modes a\n * given product/routine actually uses. */\nexport type DelegatedLoopRegistry = Partial<Record<DelegatedLoopMode, DelegatedLoopRunner>>\n\n/** @experimental Uniform result — never throws from a registered runner; a\n * thrown engine becomes `{ ok: false, error }` so a routine can record + move on. */\nexport interface DelegatedLoopResult<T = unknown> {\n mode: DelegatedLoopMode\n ok: boolean\n output?: T\n error?: string\n durationMs: number\n}\n\n/** @experimental */\nexport interface RunDelegatedLoopOptions {\n signal?: AbortSignal\n /** Clock override for deterministic tests. */\n now?: () => number\n}\n\n/**\n *\n * Dispatch a configured loop by mode. Fails loud (throws `ConfigError`) when no\n * runner is registered for the mode — a routine pointed at an unwired mode is a\n * config bug, not a silent no-op. A runner that throws is captured as\n * `{ ok: false }` so unattended runs record the failure rather than crash.\n *\n * @experimental\n */\nexport async function runDelegatedLoop<T = unknown>(\n mode: DelegatedLoopMode,\n registry: DelegatedLoopRegistry,\n options: RunDelegatedLoopOptions = {},\n): Promise<DelegatedLoopResult<T>> {\n const runner = registry[mode] as DelegatedLoopRunner<T> | undefined\n if (!runner) {\n throw new ConfigError(\n `runDelegatedLoop: no runner registered for mode '${mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n )\n }\n const now = options.now ?? Date.now\n const signal = options.signal ?? new AbortController().signal\n const start = now()\n try {\n const output = await runner(signal)\n return { mode, ok: true, output, durationMs: now() - start }\n } catch (err) {\n return {\n mode,\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n durationMs: now() - start,\n }\n }\n}\n\n/** @experimental Options for the local-repo `code` runner over the GENERIC recursive path. */\nexport interface WorktreeLoopRunnerOptions {\n /** Absolute path to the local git checkout each worktree is cut from. */\n repoRoot: string\n /** The instruction handed to every authored harness (composed under each profile's systemPrompt). */\n taskPrompt: string\n /** The supervisor-authored harness profiles — one fanout item (one worktree-CLI leaf) each. */\n harnesses: ReadonlyArray<AuthoredHarness>\n /** Conserved budget pool bounding the fanout (equal-k holds by construction). */\n budget: Budget\n /** Shell command run in each worktree to derive the tests-PASS signal. */\n testCmd?: string\n /** Shell command run in each worktree to derive the typecheck-PASS signal. */\n typecheckCmd?: string\n /** Which verification signals the deliverable REQUIRES present-and-passing (default none). */\n require?: ReadonlyArray<'tests' | 'typecheck'>\n /** Diff-size cap (lines). */\n maxDiffLines?: number\n /** Literal path prefixes the patch must not touch (the secret-floor is always on regardless). */\n forbiddenPaths?: string[]\n /** Winner-selection strategy among gated candidates. Default `highest-score`. */\n winnerStrategy?: WinnerStrategy\n /** Test seams forwarded to the worktree-CLI leaves so the runner drives offline. */\n runGit?: WorktreeFanoutOptions['runGit']\n runHarness?: WorktreeFanoutOptions['runHarness']\n runCommand?: WorktreeFanoutOptions['runCommand']\n}\n\n/**\n *\n * `code` mode on the GENERIC recursive path: author one `AgentProfile` per harness, run them as a\n * `worktreeFanout` (N `createWorktreeCliExecutor` leaves, each `gateOnDeliverable`) through\n * `runPersonified` on the keystone Supervisor. The sandbox-session counterpart that drives the in-box\n * harness over a `SandboxClient` is `detachedSessionDelegate` (`./mcp/delegates`); here there is no\n * `runAgentRounds` driver, no role-coupled delegate — the harness list is the fanout, the gate is\n * `patchDelivered`,\n * the winner is the shared valid-only selector (NOT `defaultSelectWinner`, whose non-valid fallback\n * would surface an ungated patch). Equal-k holds by the conserved budget pool. Returns the winning\n * patch artifact, or throws when no candidate is delivered (fail loud, never a vacuous done).\n *\n * @experimental\n */\nexport function worktreeLoopRunner(\n options: WorktreeLoopRunnerOptions,\n): DelegatedLoopRunner<WorktreePatchArtifact> {\n const shape = worktreeFanout<string>({\n repoRoot: options.repoRoot,\n taskPrompt: options.taskPrompt,\n harnesses: options.harnesses,\n ...(options.testCmd !== undefined ? { testCmd: options.testCmd } : {}),\n ...(options.typecheckCmd !== undefined ? { typecheckCmd: options.typecheckCmd } : {}),\n ...(options.require !== undefined ? { require: options.require } : {}),\n ...(options.maxDiffLines !== undefined ? { maxDiffLines: options.maxDiffLines } : {}),\n ...(options.forbiddenPaths !== undefined ? { forbiddenPaths: options.forbiddenPaths } : {}),\n ...(options.winnerStrategy !== undefined ? { winnerStrategy: options.winnerStrategy } : {}),\n ...(options.runGit ? { runGit: options.runGit } : {}),\n ...(options.runHarness ? { runHarness: options.runHarness } : {}),\n ...(options.runCommand ? { runCommand: options.runCommand } : {}),\n })\n // The persona's only role here is to carry the fanout shape onto the Supervisor; each item's\n // executor is BYO (the gated worktree-CLI leaf), so the registry only needs to pass BYO through.\n const persona = definePersona<WorktreePatchArtifact>({\n name: 'worktree-coder',\n root: { profile: { name: 'worktree-coder' }, harness: null },\n directive: 'deliver a minimal validated patch on a fresh worktree',\n context: { role: 'coder' },\n executors: { registry: createExecutorRegistry() },\n })\n return async (signal) => {\n const result = await runPersonified<string, WorktreePatchArtifact>({\n persona,\n shape,\n task: options.taskPrompt,\n budget: options.budget,\n signal,\n })\n if (result.kind !== 'winner' || result.out.kind !== 'done') {\n const blockers =\n result.kind === 'winner' && result.out.kind === 'blocked'\n ? result.out.blockers.join('; ')\n : `supervisor settled ${result.kind}`\n throw new Error(`worktreeLoopRunner: no delivered patch (${blockers})`)\n }\n return result.out.deliverable\n }\n}\n\n/** @experimental A fact rejected at the KB gate — surfaced, never dropped. */\nexport interface VetoedFact {\n candidate: FactCandidate\n vetoedBy?: string\n reason?: string\n}\n\n/** @experimental */\nexport interface ResearchLoopResult {\n /** Facts that passed the fail-closed gate — safe to write to the KB. */\n accepted: FactCandidate[]\n /** Facts the gate vetoed in the final round — escalate, do not silently drop. */\n vetoed: VetoedFact[]\n /** Research rounds actually run. */\n rounds: number\n}\n\n/** @experimental Options for the default `research` runner. */\nexport interface ResearchLoopRunnerOptions {\n /**\n * The research engine (the consumer's web/doc searcher + extractor). Called\n * each round with the prior round's vetoes so it can re-research the gaps.\n * Returns fact candidates carrying their grounding (`verbatimPassage` +\n * `sourceText`).\n */\n research: (round: number, vetoed: VetoedFact[]) => Promise<FactCandidate[]>\n /** Gate config (extra judges, self-artifact kinds, …). The floor is always on. */\n gate?: CreateKbGateOptions\n /** Max research rounds (correct-on-veto remediation). Default 1. */\n maxRounds?: number\n}\n\n/**\n * `research` mode — research-in-a-loop with valid-only KB growth.\n *\n * Each round: research → gate every candidate (fail-closed; passage MUST be in\n * the source) → accept the clean ones → re-research the vetoed ones next round,\n * up to `maxRounds`. Vetoed facts in the final round are RETURNED (escalate,\n * never silently dropped) so the caller audits vs retries.\n *\n * @experimental\n */\nexport function researchLoopRunner(\n o: ResearchLoopRunnerOptions,\n): DelegatedLoopRunner<ResearchLoopResult> {\n const gate = createKbGate(o.gate)\n const maxRounds = Math.max(1, Math.trunc(o.maxRounds ?? 1))\n return async (signal) => {\n const accepted: FactCandidate[] = []\n let vetoed: VetoedFact[] = []\n let rounds = 0\n for (let round = 0; round < maxRounds; round += 1) {\n if (signal.aborted) break\n rounds += 1\n const candidates = await o.research(round, vetoed)\n if (candidates.length === 0) break\n vetoed = []\n for (const c of candidates) {\n const v = await gate(c)\n if (v.accepted) accepted.push(c)\n else vetoed.push({ candidate: c, vetoedBy: v.vetoedBy, reason: v.reason })\n }\n if (vetoed.length === 0) break\n }\n return { accepted, vetoed, rounds }\n }\n}\n\n/**\n * `audit` mode — analyst loop over captured trace/run data.\n *\n * @experimental\n */\nexport function auditLoopRunner<TProposal = unknown, TEdit = unknown>(\n options: RunAnalystLoopOpts,\n): DelegatedLoopRunner<RunAnalystLoopResult<TProposal, TEdit>> {\n return async () => runAnalystLoop<TProposal, TEdit>(options)\n}\n","#!/usr/bin/env node\n/**\n *\n * `agent-runtime-loop` — the schedulable entrypoint for the configured\n * delegated loop-runner. A cron job / routine / Makefile target invokes:\n *\n * agent-runtime-loop --mode research --config ./loops.config.js\n *\n * The config module wires the registry (with full access to env / creds —\n * which is why the deps live there, not in this generic bin). It must default-\n * export a `DelegatedLoopRegistry`, or a `() => DelegatedLoopRegistry | Promise<…>`.\n * The bin runs the selected mode, prints the `DelegatedLoopResult` as JSON, and\n * exits 0 on `ok`, 1 on a recorded failure, 2 on a usage/config error.\n *\n * @experimental\n */\n\nimport {\n DELEGATED_LOOP_MODES,\n type DelegatedLoopMode,\n type DelegatedLoopRegistry,\n type DelegatedLoopResult,\n isDelegatedLoopMode,\n runDelegatedLoop,\n} from './loop-runner'\n\n/** @experimental Parsed CLI invocation. */\nexport interface LoopRunnerCliArgs {\n mode: string\n /** Loads the registry — the bin wires this from `--config`; tests inject a stub. */\n loadRegistry: () => Promise<DelegatedLoopRegistry> | DelegatedLoopRegistry\n now?: () => number\n}\n\n/** @experimental */\nexport interface LoopRunnerCliResult {\n exitCode: number\n result?: DelegatedLoopResult\n error?: string\n}\n\n/**\n *\n * Pure CLI core (no process / argv / IO) so it's unit-testable: validate the\n * mode, load the registry, dispatch, map to an exit code (0 ok / 1 failed /\n * 2 usage). Exported for embedding in custom runners + tests.\n *\n * @experimental\n */\nexport async function runLoopRunnerCli(args: LoopRunnerCliArgs): Promise<LoopRunnerCliResult> {\n if (!isDelegatedLoopMode(args.mode)) {\n return {\n exitCode: 2,\n error: `unknown mode '${args.mode}' (expected one of: ${DELEGATED_LOOP_MODES.join(', ')})`,\n }\n }\n let registry: DelegatedLoopRegistry\n try {\n registry = await args.loadRegistry()\n } catch (err) {\n return { exitCode: 2, error: `failed to load registry: ${errMsg(err)}` }\n }\n if (!registry[args.mode]) {\n return {\n exitCode: 2,\n error: `config registers no runner for mode '${args.mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n }\n }\n // runDelegatedLoop throws only on a missing runner (guarded above); a failing\n // engine is captured as { ok: false } → exit 1, not a crash.\n const result = await runDelegatedLoop(args.mode as DelegatedLoopMode, registry, {\n ...(args.now ? { now: args.now } : {}),\n })\n return { exitCode: result.ok ? 0 : 1, result }\n}\n\n/** Parse `--mode X --config Y` from an argv tail (`process.argv.slice(2)`). */\nexport function parseLoopRunnerArgv(argv: string[]): { mode?: string; config?: string } {\n const out: { mode?: string; config?: string } = {}\n for (let i = 0; i < argv.length; i += 1) {\n const a = argv[i]\n if (a === '--mode') out.mode = argv[++i]\n else if (a === '--config') out.config = argv[++i]\n else if (a?.startsWith('--mode=')) out.mode = a.slice('--mode='.length)\n else if (a?.startsWith('--config=')) out.config = a.slice('--config='.length)\n }\n return out\n}\n\n/** Normalize a config module's default export → a registry. */\nfunction resolveRegistry(mod: unknown): DelegatedLoopRegistry {\n const def = (mod as { default?: unknown })?.default ?? mod\n const value = typeof def === 'function' ? (def as () => unknown)() : def\n return value as DelegatedLoopRegistry\n}\n\nfunction errMsg(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n\n/** The argv → IO → exit shell. Kept thin; logic lives in `runLoopRunnerCli`. */\nasync function main(): Promise<void> {\n const { mode, config } = parseLoopRunnerArgv(process.argv.slice(2))\n if (!mode || !config) {\n process.stderr.write(\n 'usage: agent-runtime-loop --mode <mode> --config <module>\\n' +\n ` modes: ${DELEGATED_LOOP_MODES.join(' | ')}\\n` +\n ' config: a JS/TS module default-exporting a DelegatedLoopRegistry (or a factory)\\n',\n )\n process.exit(2)\n }\n const { pathToFileURL } = await import('node:url')\n const { resolve } = await import('node:path')\n const cli = await runLoopRunnerCli({\n mode,\n loadRegistry: async () => resolveRegistry(await import(pathToFileURL(resolve(config)).href)),\n })\n process.stdout.write(`${JSON.stringify(cli.result ?? { error: cli.error }, null, 2)}\\n`)\n if (cli.error) process.stderr.write(`${cli.error}\\n`)\n process.exit(cli.exitCode)\n}\n\n// Run only when executed as the bin — never when imported for the testable\n// core, and never when bundled into a runtime that has no `process.argv`\n// (e.g. Cloudflare Workers, where `process` is a shim without `argv`). Reading\n// `process.argv[1]` directly would throw at module load there; `process.argv?.`\n// keeps the guard a no-op instead of crashing the Worker on startup.\nconst invokedScript = typeof process !== 'undefined' ? process.argv?.[1] : undefined\nif (invokedScript && /loop-runner-bin\\.(js|ts|mjs)$/.test(invokedScript)) {\n void main()\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,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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AAO;CACvC,MAAM,EAAE,YAAY,MAAM,OAAO;CACjC,MAAM,MAAM,MAAM,iBAAiB;EACjC;EACA,cAAc,YAAY,gBAAgB,MAAM,OAAO,cAAc,QAAQ,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 { R as Budget } from "./environment-provider-DG-cSx89.js";
3
- import { Uo as WinnerStrategy, _ as WorktreeFanoutOptions, g as AuthoredHarness, pt as WorktreePatchArtifact } from "./index-zMAqz53v.js";
2
+ import { R as Budget } from "./environment-provider-Cygthiy3.js";
3
+ import { Jo as WinnerStrategy, _ as WorktreeFanoutOptions, g as AuthoredHarness, pt as WorktreePatchArtifact } from "./index-BuzkRsOn.js";
4
4
  import { n as FactCandidate, t as CreateKbGateOptions } from "./kb-gate-C8z2juK8.js";
5
5
  //#region src/loop-runner.d.ts
6
6
  /** All valid delegated-loop mode names — used for validation and CLI surfaces. @experimental */
@@ -159,4 +159,4 @@ declare function parseLoopRunnerArgv(argv: string[]): {
159
159
  };
160
160
  //#endregion
161
161
  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 };
162
- //# sourceMappingURL=loop-runner-bin-Cba5tsdb.d.ts.map
162
+ //# sourceMappingURL=loop-runner-bin-DgAXgQCI.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-Cba5tsdb.js";
1
+ import { i as runLoopRunnerCli, n as LoopRunnerCliResult, r as parseLoopRunnerArgv, t as LoopRunnerCliArgs } from "./loop-runner-bin-DgAXgQCI.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-DvLdFo38.js";
2
+ import { n as runLoopRunnerCli, t as parseLoopRunnerArgv } from "./loop-runner-bin-C2GIqSUn.js";
3
3
  export { parseLoopRunnerArgv, runLoopRunnerCli };
package/dist/mcp/bin.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import { H as DelegationTaskQueue, Q as FileDelegationStore, c as createMcpServer } from "../supervise-BDvAFOTM.js";
2
+ import { H as DelegationTaskQueue, Q as FileDelegationStore, c as createMcpServer } from "../supervise-BcCHhLrz.js";
3
3
  import { a as resolveRouterBaseUrl } from "../model-resolution-Btd9iIKV.js";
4
- import { n as readTraceContextFromEnv } from "../trace-propagation-CJJC7SVB.js";
4
+ import { n as readTraceContextFromEnv } from "../trace-propagation-B-pL7xn_.js";
5
5
  //#region src/mcp/delegate-supervisor-provisioning.ts
6
6
  const DEFAULT_SUPERVISOR_MODEL = "moonshotai/kimi-k2.6";
7
7
  const DEFAULT_WORKER_HARNESS = "opencode";
@@ -1,7 +1,7 @@
1
1
  import { E as SandboxClient, h as LoopSandboxPlacement } from "../types-DnNGJ5Gz.js";
2
- import { $l as DelegationResumeTick, Al as detachedSessionDelegate, Au as FeedbackRefersTo, Bl as DetachedTurnResumeDriverOptions, Cc as DELEGATE_INPUT_SCHEMA, Cl as CoderReviewer, Cu as DelegationProfile, Dc as DelegateResult, Dd as CoderOutput, Dl as SettleDetachedCoderTurnOptions, Du as DelegationStatusArgs, Ec as DelegateHandlerOptions, El as DetachedWinnerSelection, Eu as DelegationStatus, Fl as SiblingSandboxExecutorOptions, Fu as TraceContext, Gl as detachedTurnEvents, Hl as DriveTurnTick, Il as createFleetWorkspaceExecutor, Iu as createPropagatingTraceEmitter, Jl as runDetachedTurn, Kl as formatDetachedSessionRef, Ll as createSiblingSandboxExecutor, Lu as readTraceContextFromEnv, Ml as DelegationExecutor, Mu as ResearchSource, Nl as FleetHandle, Nu as UiAuditLensFilter, Oc as createDelegateHandler, Ol as UiAuditorDelegate, Ou as DelegationStatusResult, Pl as FleetWorkspaceExecutorOptions, Pu as UiAuditorDelegationOutput, Ql as DelegationResumeDriver, Rl as DetachedSessionRefParts, Ru as traceContextToEnv, Sc as DELEGATE_DESCRIPTION, Sl as CoderReview, Su as DelegationHistoryResult, Tc as DelegateArgs, Tl as DetachedSessionDelegateOptions, Tu as DelegationResultPayload, Ul as RunDetachedTurnOptions, Vl as DriveTurnCapableBox, Wl as createDetachedTurnResumeDriver, Xl as DelegationRecord, Yl as DelegationArgs, Zl as DelegationResumeContext, _c as createCoordinationTools, _d as InMemoryDelegationStore, _l as FeedbackEvent, _u as DelegateUiAuditRoute, ac as DEFAULT_AWAIT_EVENT_TIMEOUT_MS, ad as DelegationTraceCaps, al as DiffOptions, au as hashIdempotencyInput, bc as createInProcessTransport, bl as eventToSnapshot, bu as DelegationHistoryArgs, cc as Question, cd as buildDelegationTraceSpans, cl as RemoveWorktreeOptions, cu as DelegateCodeResult, dc as QuestionOption, dd as createDelegationTraceCollector, dl as createWorktree, du as DelegateResearchArgs, ec as AnalystFindingEvent, eu as DelegationRunContext, fc as QuestionPolicy, fd as DelegationPersistenceError, fl as removeWorktree, fu as DelegateResearchConfig, gc as WorkerWatchOptions, gd as FileDelegationStoreOptions, gl as McpTransport, gu as DelegateUiAuditResult, hc as SettledWorker, hd as FileDelegationStore, hl as McpToolDescriptor, hu as DelegateUiAuditConfig, ic as CoordinationToolsOptions, id as DELEGATION_TRACE_MAX_SPANS, il as CreateWorktreeOptions, iu as SubmitOutput, jl as settleDetachedCoderTurn, ju as ResearchOutputShape, kc as validateDelegateArgs, kl as coderTaskFromArgs, ku as FeedbackRating, lc as QuestionDecision, ld as capDelegationTrace, ll as WorktreeHandle, lu as DelegateFeedbackArgs, mc as QuestionUrgency, md as DelegationStore, ml as JsonRpcResponse, mu as DelegateUiAuditArgs, nc as CoordinationEvent, nd as CappedDelegationTrace, nu as DelegationTaskQueueOptions, oc as DownMessageEvent, od as DelegationTraceCollector, ol as DiffResult, ou as DelegateCodeArgs, pc as QuestionRecord, pd as DelegationStateCorruptError, pl as JsonRpcMessage, pu as DelegateResearchResult, ql as parseDetachedSessionRef, rc as CoordinationTools, rd as DELEGATION_TRACE_MAX_BYTES, ru as SubmitInput, sc as MakeWorkerAgent, sd as DelegationTraceSpan, sl as GitRunner, su as DelegateCodeConfig, tc as AnalystRegistry, tu as DelegationTaskQueue, uc as QuestionLevel, ud as composeLoopTraceEmitters, ul as captureWorktreeDiff, uu as DelegateFeedbackResult, vc as McpServer, vl as FeedbackStore, vu as DelegationError, wc as DELEGATE_TOOL_NAME, wl as DelegateRunCtx, wu as DelegationProgress, xc as createMcpServer, xl as CoderDelegate, xu as DelegationHistoryEntry, yc as McpServerOptions, yl as InMemoryFeedbackStore, yu as DelegationFeedbackSnapshot, zl as DetachedTurn } from "../index-zMAqz53v.js";
2
+ import { $l as createSiblingSandboxExecutor, $u as readTraceContextFromEnv, Ac as DelegateArgs, Ad as DelegationPersistenceError, Al as JsonRpcResponse, Au as DelegateUiAuditArgs, Bl as DelegateRunCtx, Bu as DelegationProgress, Cc as McpServer, Cd as DelegationTraceCaps, Cl as GitRunner, Cu as DelegateCodeConfig, Dc as DELEGATE_DESCRIPTION, Dd as capDelegationTrace, Dl as createWorktree, Du as DelegateResearchArgs, Ec as createMcpServer, Ed as buildDelegationTraceSpans, El as captureWorktreeDiff, Eu as DelegateFeedbackResult, Fd as InMemoryDelegationStore, Fl as InMemoryFeedbackStore, Fu as DelegationFeedbackSnapshot, Gd as CoderOutput, Gl as coderTaskFromArgs, Gu as FeedbackRating, Hl as DetachedWinnerSelection, Hu as DelegationStatus, Il as eventToSnapshot, Iu as DelegationHistoryArgs, Jl as DelegationExecutor, Ju as ResearchSource, Kl as detachedSessionDelegate, Ku as FeedbackRefersTo, Ll as CoderDelegate, Lu as DelegationHistoryEntry, Mc as DelegateResult, Md as DelegationStore, Ml as McpTransport, Mu as DelegateUiAuditResult, Nc as createDelegateHandler, Nd as FileDelegationStore, Nl as FeedbackEvent, Nu as DelegateUiAuditRoute, Oc as DELEGATE_INPUT_SCHEMA, Od as composeLoopTraceEmitters, Ol as removeWorktree, Ou as DelegateResearchConfig, Pc as validateDelegateArgs, Pd as FileDelegationStoreOptions, Pl as FeedbackStore, Pu as DelegationError, Ql as createFleetWorkspaceExecutor, Qu as createPropagatingTraceEmitter, Rl as CoderReview, Ru as DelegationHistoryResult, Sc as createCoordinationTools, Sd as DELEGATION_TRACE_MAX_SPANS, Sl as DiffResult, Su as DelegateCodeArgs, Tc as createInProcessTransport, Td as DelegationTraceSpan, Tl as WorktreeHandle, Tu as DelegateFeedbackArgs, Ul as SettleDetachedCoderTurnOptions, Uu as DelegationStatusArgs, Vl as DetachedSessionDelegateOptions, Vu as DelegationResultPayload, Wl as UiAuditorDelegate, Wu as DelegationStatusResult, Xl as FleetWorkspaceExecutorOptions, Xu as UiAuditorDelegationOutput, Yl as FleetHandle, Yu as UiAuditLensFilter, Zl as SiblingSandboxExecutorOptions, Zu as TraceContext, _c as QuestionPolicy, _u as DelegationTaskQueue, ac as AnalystFindingEvent, au as RunDetachedTurnOptions, bc as SettledWorker, bd as CappedDelegationTrace, bl as CreateWorktreeOptions, bu as SubmitOutput, cc as CoordinationTools, cu as formatDetachedSessionRef, dc as DownMessageEvent, du as DelegationArgs, ed as traceContextToEnv, eu as DetachedSessionRefParts, fc as MakeWorkerAgent, fu as DelegationRecord, gc as QuestionOption, gu as DelegationRunContext, hc as QuestionLevel, hu as DelegationResumeTick, iu as DriveTurnTick, jc as DelegateHandlerOptions, jd as DelegationStateCorruptError, jl as McpToolDescriptor, ju as DelegateUiAuditConfig, kc as DELEGATE_TOOL_NAME, kd as createDelegationTraceCollector, kl as JsonRpcMessage, ku as DelegateResearchResult, lc as CoordinationToolsOptions, lu as parseDetachedSessionRef, mc as QuestionDecision, mu as DelegationResumeDriver, nu as DetachedTurnResumeDriverOptions, oc as AnalystRegistry, ou as createDetachedTurnResumeDriver, pc as Question, pu as DelegationResumeContext, ql as settleDetachedCoderTurn, qu as ResearchOutputShape, ru as DriveTurnCapableBox, sc as CoordinationEvent, su as detachedTurnEvents, tu as DetachedTurn, uc as DEFAULT_AWAIT_EVENT_TIMEOUT_MS, uu as runDetachedTurn, vc as QuestionRecord, vu as DelegationTaskQueueOptions, wc as McpServerOptions, wd as DelegationTraceCollector, wl as RemoveWorktreeOptions, wu as DelegateCodeResult, xc as WorkerWatchOptions, xd as DELEGATION_TRACE_MAX_BYTES, xl as DiffOptions, xu as hashIdempotencyInput, yc as QuestionUrgency, yu as SubmitInput, zl as CoderReviewer, zu as DelegationProfile } from "../index-BuzkRsOn.js";
3
3
  import { o as UiLens } from "../substrate-BcnuSHXm.js";
4
- import { a as LocalHarnessResult, c as runLocalHarness, i as LocalHarness, n as CodexExecutionPolicy, o as RunLocalHarnessOptions, r as CodexTokenUsage, s as parseCodexTokenUsage, t as CodexExecutionEvidence } from "../local-harness-Ce1emWJE.js";
4
+ import { a as LocalHarnessResult, c as runLocalHarness, i as LocalHarness, n as CodexExecutionPolicy, o as RunLocalHarnessOptions, r as CodexTokenUsage, s as parseCodexTokenUsage, t as CodexExecutionEvidence } from "../local-harness-BnB1E9nM.js";
5
5
  import { a as KbGateResult, i as FactJudgeVerdict, n as FactCandidate, o as createKbGate, r as FactJudge, t as CreateKbGateOptions } from "../kb-gate-C8z2juK8.js";
6
6
  import { n as mcpToolsForRuntimeMcpSubset, t as mcpToolsForRuntimeMcp } from "../openai-tools-B68JaOCx.js";
7
7
  import { AnalystFinding } from "@tangle-network/agent-eval";
package/dist/mcp/index.js CHANGED
@@ -1,14 +1,14 @@
1
1
  import { u as ValidationError } from "../errors-DEAvWQPy.js";
2
2
  import { c as sleep, d as throwIfAborted, r as deleteBoxSafe, u as throwAbort } from "../util-Cc9g9Y-o.js";
3
- import { A as createWorktree, F as CodexExecutionDiagnosticError, N as parseCodexTokenUsage, O as runWorktreeHarness, P as runLocalHarness, j as removeWorktree, k as captureWorktreeDiff } from "../supervisor-DS278ICs.js";
4
- import { A as runCoderChecks, lt as assertTraceDerivedFindings, ot as selectValidWinner } from "../runtime-DlSPFm9o.js";
5
- import { $ as InMemoryDelegationStore, A as DELEGATE_INPUT_SCHEMA, Bt as createSandboxForSpec, C as validateDelegateUiAuditArgs, D as createDelegateFeedbackHandler, E as DELEGATE_FEEDBACK_TOOL_NAME, G as DELEGATION_TRACE_MAX_SPANS, H as DelegationTaskQueue, Ht as runAgentRounds, J as composeLoopTraceEmitters, K as buildDelegationTraceSpans, M as createDelegateHandler, N as validateDelegateArgs, O as validateDelegateFeedbackArgs, Q as FileDelegationStore, S as createDelegateUiAuditHandler, T as DELEGATE_FEEDBACK_INPUT_SCHEMA, U as hashIdempotencyInput, W as DELEGATION_TRACE_MAX_BYTES, X as DelegationPersistenceError, Y as createDelegationTraceCollector, Z as DelegationStateCorruptError, _ as createDelegationHistoryHandler, _t as createCoordinationTools, b as DELEGATE_UI_AUDIT_INPUT_SCHEMA, c as createMcpServer, d as DELEGATION_STATUS_TOOL_NAME, et as InMemoryFeedbackStore, f as createDelegationStatusHandler, g as DELEGATION_HISTORY_TOOL_NAME, gt as DEFAULT_AWAIT_EVENT_TIMEOUT_MS, h as DELEGATION_HISTORY_INPUT_SCHEMA, j as DELEGATE_TOOL_NAME, k as DELEGATE_DESCRIPTION, l as DELEGATION_STATUS_DESCRIPTION, m as DELEGATION_HISTORY_DESCRIPTION, p as validateDelegationStatusArgs, q as capDelegationTrace, s as createInProcessTransport, tt as eventToSnapshot, u as DELEGATION_STATUS_INPUT_SCHEMA, v as validateDelegationHistoryArgs, w as DELEGATE_FEEDBACK_DESCRIPTION, x as DELEGATE_UI_AUDIT_TOOL_NAME, y as DELEGATE_UI_AUDIT_DESCRIPTION } from "../supervise-BDvAFOTM.js";
3
+ import { A as captureWorktreeDiff, F as runLocalHarness, I as CodexExecutionDiagnosticError, M as removeWorktree, P as parseCodexTokenUsage, j as createWorktree, k as runWorktreeHarness } from "../supervisor-CspDspod.js";
4
+ import { A as runCoderChecks, lt as assertTraceDerivedFindings, ot as selectValidWinner } from "../runtime-C_g_SsXg.js";
5
+ import { $ as InMemoryDelegationStore, A as DELEGATE_INPUT_SCHEMA, C as validateDelegateUiAuditArgs, D as createDelegateFeedbackHandler, E as DELEGATE_FEEDBACK_TOOL_NAME, G as DELEGATION_TRACE_MAX_SPANS, H as DelegationTaskQueue, J as composeLoopTraceEmitters, Jt as runAgentRounds, K as buildDelegationTraceSpans, Kt as createSandboxForSpec, M as createDelegateHandler, N as validateDelegateArgs, O as validateDelegateFeedbackArgs, Q as FileDelegationStore, S as createDelegateUiAuditHandler, T as DELEGATE_FEEDBACK_INPUT_SCHEMA, U as hashIdempotencyInput, W as DELEGATION_TRACE_MAX_BYTES, X as DelegationPersistenceError, Y as createDelegationTraceCollector, Z as DelegationStateCorruptError, _ as createDelegationHistoryHandler, _t as createCoordinationTools, b as DELEGATE_UI_AUDIT_INPUT_SCHEMA, c as createMcpServer, d as DELEGATION_STATUS_TOOL_NAME, et as InMemoryFeedbackStore, f as createDelegationStatusHandler, g as DELEGATION_HISTORY_TOOL_NAME, gt as DEFAULT_AWAIT_EVENT_TIMEOUT_MS, h as DELEGATION_HISTORY_INPUT_SCHEMA, j as DELEGATE_TOOL_NAME, k as DELEGATE_DESCRIPTION, l as DELEGATION_STATUS_DESCRIPTION, m as DELEGATION_HISTORY_DESCRIPTION, p as validateDelegationStatusArgs, q as capDelegationTrace, s as createInProcessTransport, tt as eventToSnapshot, u as DELEGATION_STATUS_INPUT_SCHEMA, v as validateDelegationHistoryArgs, w as DELEGATE_FEEDBACK_DESCRIPTION, x as DELEGATE_UI_AUDIT_TOOL_NAME, y as DELEGATE_UI_AUDIT_DESCRIPTION } from "../supervise-BcCHhLrz.js";
6
6
  import { t as createStdioToolServer } from "../tool-server-RcWgLIsL.js";
7
7
  import { t as createKbGate } from "../kb-gate-DpaSwXVx.js";
8
- import { n as mcpToolsForRuntimeMcpSubset, t as mcpToolsForRuntimeMcp } from "../openai-tools-DftmzKLc.js";
8
+ import { n as mcpToolsForRuntimeMcpSubset, t as mcpToolsForRuntimeMcp } from "../openai-tools-BWAEIHkZ.js";
9
9
  import { t as coderTaskToPrompt } from "../coder-yhVWbdWc.js";
10
10
  import { a as createMemoryToolServer, c as resolveMemoryFromEnv, i as MEMORY_NAME_ENV, n as MEMORY_ITEMS_ENV, o as parseMemoryItems, r as MEMORY_LOG_ENV, s as readMemoryItemsFile, t as MEMORY_FILE_ENV } from "../memory-server-DL6cE2Ag.js";
11
- import { n as readTraceContextFromEnv, r as traceContextToEnv, t as createPropagatingTraceEmitter } from "../trace-propagation-CJJC7SVB.js";
11
+ import { n as readTraceContextFromEnv, r as traceContextToEnv, t as createPropagatingTraceEmitter } from "../trace-propagation-B-pL7xn_.js";
12
12
  import { makeFinding } from "@tangle-network/agent-eval";
13
13
  import { randomUUID } from "node:crypto";
14
14
  //#region src/mcp/executor.ts
@@ -1,4 +1,4 @@
1
- import { E as DELEGATE_FEEDBACK_TOOL_NAME, T as DELEGATE_FEEDBACK_INPUT_SCHEMA, d as DELEGATION_STATUS_TOOL_NAME, g as DELEGATION_HISTORY_TOOL_NAME, h as DELEGATION_HISTORY_INPUT_SCHEMA, l as DELEGATION_STATUS_DESCRIPTION, m as DELEGATION_HISTORY_DESCRIPTION, u as DELEGATION_STATUS_INPUT_SCHEMA, w as DELEGATE_FEEDBACK_DESCRIPTION } from "./supervise-BDvAFOTM.js";
1
+ import { E as DELEGATE_FEEDBACK_TOOL_NAME, T as DELEGATE_FEEDBACK_INPUT_SCHEMA, d as DELEGATION_STATUS_TOOL_NAME, g as DELEGATION_HISTORY_TOOL_NAME, h as DELEGATION_HISTORY_INPUT_SCHEMA, l as DELEGATION_STATUS_DESCRIPTION, m as DELEGATION_HISTORY_DESCRIPTION, u as DELEGATION_STATUS_INPUT_SCHEMA, w as DELEGATE_FEEDBACK_DESCRIPTION } from "./supervise-BcCHhLrz.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-DftmzKLc.js.map
44
+ //# sourceMappingURL=openai-tools-BWAEIHkZ.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"openai-tools-DftmzKLc.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 configuring `createOpenAICompatibleBackend({ tools: ... })` so the\n * model can call `delegate_feedback`, `delegation_status`, and\n * `delegation_history` through the OpenAI-compat transport (tcloud, OpenRouter,\n * OpenAI direct, cli-bridge). The runtime surfaces tool calls as `tool_call`\n * stream events — execution is the caller's responsibility (typically the\n * parent sandbox runtime's MCP mount).\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-compat backend JSON-serializes 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":";;AAwCA,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-BWAEIHkZ.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 configuring `createOpenAICompatibleBackend({ tools: ... })` so the\n * model can call `delegate_feedback`, `delegation_status`, and\n * `delegation_history` through the OpenAI-compat transport (tcloud, OpenRouter,\n * OpenAI direct, cli-bridge). The runtime surfaces tool calls as `tool_call`\n * stream events — execution is the caller's responsibility (typically the\n * parent sandbox runtime's MCP mount).\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-compat backend JSON-serializes 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":";;AAwCA,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"}
@@ -430,7 +430,7 @@ function createOtelExporter(config) {
430
430
  if (pending.length === 0) return;
431
431
  const batch = pending.splice(0);
432
432
  const body = { resourceSpans: [{
433
- resource: { attributes: toAttributes({
433
+ resource: { attributes: toOtelAttributes({
434
434
  "service.name": serviceName,
435
435
  ...resourceAttrs
436
436
  }) },
@@ -472,7 +472,7 @@ function loopEventToOtelSpan(event, traceId, parentSpanId) {
472
472
  kind: 1,
473
473
  startTimeUnixNano: ts,
474
474
  endTimeUnixNano: ts,
475
- attributes: toAttributes(attrs),
475
+ attributes: toOtelAttributes(attrs),
476
476
  status: { code: 1 }
477
477
  };
478
478
  }
@@ -495,7 +495,7 @@ function flatOtelSpan(name, attributes, traceId, timestampMs, parentSpanId, endT
495
495
  kind: 1,
496
496
  startTimeUnixNano: start,
497
497
  endTimeUnixNano: end,
498
- attributes: toAttributes(attributes),
498
+ attributes: toOtelAttributes(attributes),
499
499
  status: { code: 1 }
500
500
  };
501
501
  }
@@ -596,7 +596,7 @@ function buildLoopOtelSpans(events, traceId, rootParentSpanId) {
596
596
  kind: 1,
597
597
  startTimeUnixNano: msToNs(node.startMs),
598
598
  endTimeUnixNano: msToNs(node.endMs),
599
- attributes: toAttributes(node.attrs),
599
+ attributes: toOtelAttributes(node.attrs),
600
600
  status: { code: node.error ? 2 : 1 }
601
601
  }));
602
602
  }
@@ -770,7 +770,13 @@ function parseHeadersFromEnv() {
770
770
  }
771
771
  return out;
772
772
  }
773
- function toAttributes(record) {
773
+ /**
774
+ * Convert a flat record into the OTLP attribute list. Non-finite numbers are DROPPED (an OTLP
775
+ * `doubleValue` of `NaN`/`Infinity` is not representable), integers ride as `intValue`. Exported so
776
+ * a producer that mints its own `OtelSpan` (the supervisor span recorder) builds attributes exactly
777
+ * the way every span in this file does, rather than re-deriving the encoding.
778
+ */
779
+ function toOtelAttributes(record) {
774
780
  return Object.entries(record).flatMap(([key, value]) => {
775
781
  if (typeof value === "number" && !Number.isFinite(value)) return [];
776
782
  return [{
@@ -788,6 +794,9 @@ function padSpanId(id) {
788
794
  function padTraceId(id) {
789
795
  return id.replace(/-/g, "").slice(0, 32).padEnd(32, "0");
790
796
  }
797
+ /** Mint a fresh 16-hex-character OTLP span id. Exported so a producer that must know a span's id
798
+ * BEFORE the span closes (a node opened at spawn and parented by its children) uses this one
799
+ * generator instead of a second copy of it. */
791
800
  function generateSpanId() {
792
801
  const bytes = /* @__PURE__ */ new Uint8Array(8);
793
802
  if (typeof globalThis.crypto?.getRandomValues === "function") globalThis.crypto.getRandomValues(bytes);
@@ -838,6 +847,6 @@ async function exportEvalRuns(events, config) {
838
847
  };
839
848
  }
840
849
  //#endregion
841
- export { createOtelExporter as a, loopEventToOtelSpan as c, sanitizeAgentRuntimeEvent as d, sanitizeKnowledgeReadinessReport as f, buildRuntimeEventOtelSpans as i, createRuntimeEventCollector as l, buildLoopOtelSpans as n, exportEvalRuns as o, sanitizeRuntimeStreamEvent as p, buildLoopSpanNodes as r, flatOtelSpan as s, INTELLIGENCE_WIRE_VERSION as t, createRuntimeStreamEventCollector as u };
850
+ export { createOtelExporter as a, generateSpanId as c, createRuntimeEventCollector as d, createRuntimeStreamEventCollector as f, sanitizeRuntimeStreamEvent as h, buildRuntimeEventOtelSpans as i, loopEventToOtelSpan as l, sanitizeKnowledgeReadinessReport as m, buildLoopOtelSpans as n, exportEvalRuns as o, sanitizeAgentRuntimeEvent as p, buildLoopSpanNodes as r, flatOtelSpan as s, INTELLIGENCE_WIRE_VERSION as t, toOtelAttributes as u };
842
851
 
843
- //# sourceMappingURL=otel-export-D34IQW1C.js.map
852
+ //# sourceMappingURL=otel-export-CPZTSADj.js.map