@tangle-network/agent-runtime 0.349.0 → 0.352.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 (139) hide show
  1. package/dist/{activation-wBipBkCf.d.ts → activation-BidzGkUQ.d.ts} +2 -24
  2. package/dist/{activation-tNGW73Y9.js → activation-C6zNC2kx.js} +12 -14
  3. package/dist/{activation-tNGW73Y9.js.map → activation-C6zNC2kx.js.map} +1 -1
  4. package/dist/agent.d.ts +8 -12
  5. package/dist/agent.js +9 -12
  6. package/dist/agent.js.map +1 -1
  7. package/dist/{analyst-loop-DZw5QWT9.js → analyst-loop-BZvXCDKy.js} +2 -3
  8. package/dist/{analyst-loop-DZw5QWT9.js.map → analyst-loop-BZvXCDKy.js.map} +1 -1
  9. package/dist/analyst-loop.d.ts +3 -5
  10. package/dist/analyst-loop.js +1 -2
  11. package/dist/{bundle-1xaJEgjq.js → bundle-DeDkJbsr.js} +3 -4
  12. package/dist/{bundle-1xaJEgjq.js.map → bundle-DeDkJbsr.js.map} +1 -1
  13. package/dist/candidate-execution/index.d.ts +13 -33
  14. package/dist/candidate-execution/index.js +16 -18
  15. package/dist/candidate-execution/index.js.map +1 -1
  16. package/dist/chat-turn.d.ts +2 -0
  17. package/dist/chat-turn.js +1 -0
  18. package/dist/{coordination-manager-B2Z_MmL9.js → coordination-manager-B7QadgrI.js} +101 -132
  19. package/dist/{coordination-manager-B2Z_MmL9.js.map → coordination-manager-B7QadgrI.js.map} +1 -1
  20. package/dist/{delegate-Dr-63jFl.js → delegate-CoscoyEo.js} +19 -21
  21. package/dist/delegate-CoscoyEo.js.map +1 -0
  22. package/dist/durable.d.ts +16 -149
  23. package/dist/durable.js +57 -980
  24. package/dist/durable.js.map +1 -1
  25. package/dist/{errors-DodWX-cb.js → errors-AzSuGI23.js} +5 -3
  26. package/dist/errors-AzSuGI23.js.map +1 -0
  27. package/dist/execution-handle-Bd2_nUB6.js +167 -0
  28. package/dist/execution-handle-Bd2_nUB6.js.map +1 -0
  29. package/dist/execution-handle-CujvqgCn.d.ts +130 -0
  30. package/dist/{graph-DPejYB3C.js → graph-mojMML8e.js} +192 -14
  31. package/dist/graph-mojMML8e.js.map +1 -0
  32. package/dist/{improve-DwSahPi1.js → improve-Dm5ZE8mr.js} +36 -53
  33. package/dist/{improve-DwSahPi1.js.map → improve-Dm5ZE8mr.js.map} +1 -1
  34. package/dist/{improvement-adapter-sIthWkcN.d.ts → improvement-adapter-D5GRU1eY.d.ts} +2 -6
  35. package/dist/index.d.ts +41 -89
  36. package/dist/index.js +45 -61
  37. package/dist/index.js.map +1 -1
  38. package/dist/intelligence.d.ts +39 -59
  39. package/dist/intelligence.js +24 -33
  40. package/dist/intelligence.js.map +1 -1
  41. package/dist/journal-store-BJPMUydp.js +3925 -0
  42. package/dist/journal-store-BJPMUydp.js.map +1 -0
  43. package/dist/kernel.d.ts +5 -5
  44. package/dist/kernel.js +12 -11
  45. package/dist/{loop-runner-CP6MfO1b.js → loop-runner-5cL_vZi0.js} +5 -6
  46. package/dist/{loop-runner-CP6MfO1b.js.map → loop-runner-5cL_vZi0.js.map} +1 -1
  47. package/dist/{loop-runner-C6pGq-2l.d.ts → loop-runner-DyLD-aNb.d.ts} +3 -5
  48. package/dist/loop-runner-bin.d.ts +5 -8
  49. package/dist/loop-runner-bin.js +2 -3
  50. package/dist/mcp/bin.js +6 -8
  51. package/dist/mcp/bin.js.map +1 -1
  52. package/dist/mcp/index.d.ts +8 -18
  53. package/dist/mcp/index.js +17 -25
  54. package/dist/mcp/index.js.map +1 -1
  55. package/dist/mcp/memory-bin.js +4 -6
  56. package/dist/mcp/memory-bin.js.map +1 -1
  57. package/dist/{model-policy-CyCUwHed.js → model-policy-C-RGAUW4.js} +11 -13
  58. package/dist/{model-policy-CyCUwHed.js.map → model-policy-C-RGAUW4.js.map} +1 -1
  59. package/dist/placement.d.ts +12 -14
  60. package/dist/placement.js +1 -2
  61. package/dist/platform.d.ts +7 -13
  62. package/dist/platform.js +3 -6
  63. package/dist/platform.js.map +1 -1
  64. package/dist/{prepare-B9wWffjO.js → prepare-XWwsOh8O.js} +50 -69
  65. package/dist/{prepare-B9wWffjO.js.map → prepare-XWwsOh8O.js.map} +1 -1
  66. package/dist/{profile-JLJd2wFG.js → profile-C01SQZKa.js} +58 -92
  67. package/dist/profile-C01SQZKa.js.map +1 -0
  68. package/dist/{profile-materialization-bPm0gGLO.d.ts → profile-materialization-BRY22Oh8.d.ts} +1 -3
  69. package/dist/profiles.d.ts +25 -12
  70. package/dist/profiles.js +52 -11
  71. package/dist/profiles.js.map +1 -1
  72. package/dist/{protected-model-port-DVVh-hEk.d.ts → protected-model-port-IKqhTypD.d.ts} +2 -14
  73. package/dist/{protected-redaction-DFCeo4vg.js → protected-redaction-DilFZch5.js} +2 -3
  74. package/dist/{protected-redaction-DFCeo4vg.js.map → protected-redaction-DilFZch5.js.map} +1 -1
  75. package/dist/{provision-supervisor-C4v2vqDo.js → provision-supervisor-D9pO-iPl.js} +11 -15
  76. package/dist/{provision-supervisor-C4v2vqDo.js.map → provision-supervisor-D9pO-iPl.js.map} +1 -1
  77. package/dist/{run-cancellation-CzFhQGMa.js → run-cancellation-CoJRKvih.js} +6 -7
  78. package/dist/{run-cancellation-CzFhQGMa.js.map → run-cancellation-CoJRKvih.js.map} +1 -1
  79. package/dist/{runtime-CsvGCQpl.js → runtime-BJPXHWbc.js} +652 -215
  80. package/dist/runtime-BJPXHWbc.js.map +1 -0
  81. package/dist/{runtime-hooks-tXpAarhW.js → runtime-hooks-CsW2pfFk.js} +2 -3
  82. package/dist/{runtime-hooks-tXpAarhW.js.map → runtime-hooks-CsW2pfFk.js.map} +1 -1
  83. package/dist/{runtime-hooks-nsqxSUFL.d.ts → runtime-hooks-ZQqPw-0g.d.ts} +1 -3
  84. package/dist/{sandbox-profile-compat-DtuJWFrM.js → sandbox-profile-compat-CXjozdWL.js} +52 -653
  85. package/dist/sandbox-profile-compat-CXjozdWL.js.map +1 -0
  86. package/dist/{search-executor-CCb82Umc.js → search-executor-CQEHMXoT.js} +12 -15
  87. package/dist/{search-executor-CCb82Umc.js.map → search-executor-CQEHMXoT.js.map} +1 -1
  88. package/dist/{server-CKPwZU-I.js → server-U9NGgudQ.js} +19 -30
  89. package/dist/{server-CKPwZU-I.js.map → server-U9NGgudQ.js.map} +1 -1
  90. package/dist/{structural-rollout-DylC_fwU.js → structural-rollout-wMSxE7bn.js} +71 -70
  91. package/dist/structural-rollout-wMSxE7bn.js.map +1 -0
  92. package/dist/{substrate-CGDFTSRh.js → substrate-Db2pp6y3.js} +2 -3
  93. package/dist/{substrate-CGDFTSRh.js.map → substrate-Db2pp6y3.js.map} +1 -1
  94. package/dist/{supervise-BGfm2GlY.js → supervise-CNNhX0ab.js} +460 -195
  95. package/dist/supervise-CNNhX0ab.js.map +1 -0
  96. package/dist/supervision-discovery-CewADdEs.js +772 -0
  97. package/dist/supervision-discovery-CewADdEs.js.map +1 -0
  98. package/dist/{supervisor-wS9Ehz_x.js → supervisor-rK5Y8en6.js} +521 -4320
  99. package/dist/supervisor-rK5Y8en6.js.map +1 -0
  100. package/dist/{task-queue-0fKkoweu.d.ts → task-queue-kefGy79U.d.ts} +1 -3
  101. package/dist/task-queue.d.ts +1 -1
  102. package/dist/task-queue.js +1 -2
  103. package/dist/testing.d.ts +7 -15
  104. package/dist/testing.js +241 -244
  105. package/dist/testing.js.map +1 -1
  106. package/dist/tool-loop.d.ts +16 -19
  107. package/dist/tool-loop.js +2 -3
  108. package/dist/{tool-server-XV4aJwoQ.js → tool-server-CZWd_Opp.js} +3 -4
  109. package/dist/{tool-server-XV4aJwoQ.js.map → tool-server-CZWd_Opp.js.map} +1 -1
  110. package/dist/{top-snapshot-CflmaDgk.js → top-snapshot-DcV7VG4m.js} +179 -163
  111. package/dist/top-snapshot-DcV7VG4m.js.map +1 -0
  112. package/dist/tui/bin.js +50 -81
  113. package/dist/tui/bin.js.map +1 -1
  114. package/dist/tui/index.d.ts +27 -58
  115. package/dist/tui/index.js +2 -2
  116. package/dist/{types-C8BGOCBn.d.ts → types-0uzVKtFW.d.ts} +388 -484
  117. package/dist/{types-Cwrea-bU.d.ts → types-qsqfyQoY.d.ts} +1 -3
  118. package/dist/util-ebWMWzY0.js +624 -0
  119. package/dist/util-ebWMWzY0.js.map +1 -0
  120. package/dist/workspace-store/index.d.ts +12 -22
  121. package/dist/workspace-store/index.js +13 -10
  122. package/dist/workspace-store/index.js.map +1 -1
  123. package/dist/{workspace-streams-BiS4ABah.d.ts → workspace-streams-Dq2Fzk3c.d.ts} +1 -11
  124. package/package.json +31 -26
  125. package/skills/agent-graphs/SKILL.md +17 -4
  126. package/skills/be-ambitious/SKILL.md +46 -0
  127. package/skills/graph-designer/SKILL.md +9 -2
  128. package/dist/delegate-Dr-63jFl.js.map +0 -1
  129. package/dist/errors-DodWX-cb.js.map +0 -1
  130. package/dist/graph-DPejYB3C.js.map +0 -1
  131. package/dist/profile-JLJd2wFG.js.map +0 -1
  132. package/dist/record-events-D93DkpAx.js +0 -263
  133. package/dist/record-events-D93DkpAx.js.map +0 -1
  134. package/dist/runtime-CsvGCQpl.js.map +0 -1
  135. package/dist/sandbox-profile-compat-DtuJWFrM.js.map +0 -1
  136. package/dist/structural-rollout-DylC_fwU.js.map +0 -1
  137. package/dist/supervise-BGfm2GlY.js.map +0 -1
  138. package/dist/supervisor-wS9Ehz_x.js.map +0 -1
  139. package/dist/top-snapshot-CflmaDgk.js.map +0 -1
@@ -1,27 +1,28 @@
1
- import { s as writeAtomicDurableFile } from "./record-events-D93DkpAx.js";
2
- import { At as createExecutor, Ct as readCommittedJsonLines, Dt as createExecutorRegistry, Et as insideCursorNamespace, Ft as assertBoxlessPromptOptions, I as coordinationProfileToolPrefix, It as readPromptOptions, Jt as routerBrain, Li as detachedFrozen, Pr as runAbortable, Pt as runAgentRounds, Ri as detachedSnapshot, Rt as createSandboxLineage, Si as executableAgentSpecSnapshot, St as readCommittedJsonFile, Tt as withJsonlFileLock, Vt as defaultSelectWinner, W as rollingDispatch, _ as withDriverExecutor, _t as InMemorySpawnJournal, aa as notifySandboxEventObserver, b as isTraceAnalysisStore, bt as isNoEntError, dr as CheckUnavailableError, gt as InMemoryResultBlobStore, hn as createWorktreeCliExecutor, hr as verdictFromJudgeScore, mr as mapExecutorResult, n as createSupervisor, na as createSandboxTurnEventCollector, pr as gateOnDeliverable, wt as upsertCommittedJsonLine, xi as executableAgentProfileSnapshot, yt as appendCommittedJsonLine, z as settledToIteration, zi as contentAddress } from "./supervisor-wS9Ehz_x.js";
3
- import { i as ConfigError, m as ValidationError, n as AnalystError, s as PlannerError } from "./errors-DodWX-cb.js";
4
- import { D as runAgentic, E as refine, M as renderReport, N as profileChatClient, O as sample, j as observe, k as ObservationError, v as loadAuthoredStrategy, x as strategyAuthorContract, y as requestStrategySource } from "./structural-rollout-DylC_fwU.js";
5
- import { $ as isAbortError, B as sha256Bytes$1, C as WorkspaceScanLimitError, Ct as armDeadlineTimer, E as captureMaterializedWorkspace, K as chargedTokens, P as canonicalCandidateDigest$1, Q as hasCompleteCacheBreakdown, R as immutableCandidateValue, W as addSpend, X as errorMessage, Z as fnv1a32Hex, et as isAsyncIterable, ft as zeroSpend, h as markPutStreamVerified, ot as sleep, q as cloneSpend, rt as randomSuffix, st as stringifySafe, tt as mapWithConcurrency } from "./sandbox-profile-compat-DtuJWFrM.js";
6
- import { c as profileModelExecutionSettings, i as concreteModelId, l as profileProviderModel, o as enforceTokenLimits, p as canonicalObservedModelParts, t as assertExecutableAgentProfile, v as harnessRunsAgent } from "./model-policy-CyCUwHed.js";
7
- import { i as notifyRuntimeHookEvent } from "./runtime-hooks-tXpAarhW.js";
8
- import { a as reconcileInterruptedSearchCalls, c as searchExecutor, r as dedicatedLane, x as runtimeShipDecision } from "./search-executor-CCb82Umc.js";
9
- import { g as foldCoordinationRecords, p as createInMemoryRunContext } from "./coordination-manager-B2Z_MmL9.js";
10
- import { M as runBrainLoop, f as graphDigest, h as graphRunsFor, m as graphRegistry, p as graphFromStored, t as supervise, u as digestOfGraph, w as taskShapeDigest, x as recordGraphRun, y as lookupGraph } from "./supervise-BGfm2GlY.js";
11
- import "./run-cancellation-CzFhQGMa.js";
12
- import { i as redactProtectedValue, r as redactProtectedReason } from "./protected-redaction-DFCeo4vg.js";
13
- import "./provision-supervisor-C4v2vqDo.js";
14
- import "./delegate-Dr-63jFl.js";
15
- import "./graph-DPejYB3C.js";
1
+ import { O as runtimeFailureCauseSchema, Ut as notifySandboxEventObserver, a as isNoEntError, c as readCommittedJsonLines, et as detachedFrozen, i as appendCommittedJsonLine, l as upsertCommittedJsonLine, p as insideCursorNamespace, rt as contentAddress, s as readCommittedJsonFile, tt as detachedSnapshot, u as withJsonlFileLock, y as writeAtomicDurableFile, zt as createSandboxTurnEventCollector } from "./journal-store-BJPMUydp.js";
2
+ import { Dt as readPromptOptions, Et as assertBoxlessPromptOptions, F as coordinationProfileToolPrefix, Mt as defaultSelectWinner, R as settledToIteration, Tr as runAbortable, Tt as runAgentRounds, U as rollingDispatch, _ as withDriverExecutor, ar as mapExecutorResult, b as isTraceAnalysisStore, gt as InMemorySpawnJournal, ht as InMemoryResultBlobStore, ir as gateOnDeliverable, kt as createSandboxLineage, mi as executableAgentSpecSnapshot, n as createSupervisor, nr as CheckUnavailableError, on as createWorktreeCliExecutor, or as verdictFromJudgeScore, pi as executableAgentProfileSnapshot, vt as createExecutorRegistry, xt as createExecutor, zt as routerBrain } from "./supervisor-rK5Y8en6.js";
3
+ import { i as ConfigError, m as ValidationError, n as AnalystError, s as PlannerError } from "./errors-AzSuGI23.js";
4
+ import { D as runAgentic, E as refine, M as renderReport, N as profileChatClient, O as sample, j as observe, k as ObservationError, v as loadAuthoredStrategy, x as strategyAuthorContract, y as requestStrategySource } from "./structural-rollout-wMSxE7bn.js";
5
+ import { F as armDeadlineTimer, a as cloneSpend, c as errorMessage, d as isAbortError, f as isAsyncIterable, h as randomSuffix, i as chargedTokens, l as fnv1a32Hex, n as addSpend, p as mapWithConcurrency, u as hasCompleteCacheBreakdown, v as sleep, w as zeroSpend, y as stringifySafe } from "./util-ebWMWzY0.js";
6
+ import { a as concreteProfileModel, c as profileModelExecutionSettings, i as concreteModelId, l as profileProviderModel, o as enforceTokenLimits, p as canonicalObservedModelParts, t as assertExecutableAgentProfile, v as harnessRunsAgent } from "./model-policy-C-RGAUW4.js";
7
+ import { B as sha256Bytes$1, C as WorkspaceScanLimitError, E as captureMaterializedWorkspace, P as canonicalCandidateDigest$1, R as immutableCandidateValue, h as markPutStreamVerified } from "./sandbox-profile-compat-CXjozdWL.js";
8
+ import { i as notifyRuntimeHookEvent } from "./runtime-hooks-CsW2pfFk.js";
9
+ import { a as reconcileInterruptedSearchCalls, c as searchExecutor, r as dedicatedLane, x as runtimeShipDecision } from "./search-executor-CQEHMXoT.js";
10
+ import { a as downMessageRefusalReasons, h as createInMemoryRunContext, v as foldCoordinationRecords } from "./coordination-manager-B7QadgrI.js";
11
+ import { A as graphRouteWhenSchema, D as compileGraphParameters, E as bindGraphParameters, L as coordinationControlToolNames, O as graphTriggerBindingsSchema, T as assertGraphTriggerBindings, X as validateGraphTopology, f as graphDigest, h as graphRunsFor, k as graphFileSchema, m as graphRegistry, p as graphFromStored, q as validateFlowGraph, rt as kernelPromptRegistry, t as supervise, u as digestOfGraph, w as taskShapeDigest, x as recordGraphRun, y as lookupGraph, z as runBrainLoop } from "./supervise-CNNhX0ab.js";
12
+ import "./run-cancellation-CoJRKvih.js";
13
+ import { i as redactProtectedValue, r as redactProtectedReason } from "./protected-redaction-DilFZch5.js";
14
+ import "./provision-supervisor-D9pO-iPl.js";
15
+ import "./delegate-CoscoyEo.js";
16
+ import "./graph-mojMML8e.js";
16
17
  import { agentProfileSchema, canonicalAgentProfileDigest, canonicalCandidateDigest, sha256Bytes, validateAgentProfileSecurity } from "@tangle-network/agent-interface";
17
18
  import { CODING_HARNESSES, DEFAULT_TRACE_ANALYST_KINDS, InMemoryTraceStore, OUTPUT_VALUE, benjaminiHochberg, buildTrajectory, computeFindingId as computeFindingId$1, confidenceInterval, createTraceAnalyst, expandProfileAxes, makeFinding as makeFinding$1, pairedBootstrap, paretoFrontier, wilcoxonSignedRank, wilson } from "@tangle-network/agent-eval";
18
19
  import { createAgentRunOutcomeTracker } from "@tangle-network/sandbox/runtime";
19
20
  import { collectAgentResponseText } from "@tangle-network/sandbox";
20
- import { redact } from "@tangle-network/agent-eval/traces";
21
21
  import { z } from "zod";
22
+ import { redact } from "@tangle-network/agent-eval/traces";
22
23
  import { createHash, createHmac, randomUUID } from "node:crypto";
23
24
  import { appendFileSync, chmodSync, constants, copyFileSync, lstatSync, mkdirSync, mkdtempSync, readlinkSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
24
- import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
25
+ import { dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
25
26
  import { execFile, execFileSync, spawn, spawnSync } from "node:child_process";
26
27
  import { chmod, link, lstat, mkdir, mkdtemp, open, opendir, readFile, readdir, readlink, realpath, rename, rm, stat, symlink, unlink, writeFile } from "node:fs/promises";
27
28
  import { promisify } from "node:util";
@@ -32,9 +33,10 @@ import { defineEvaluationClaim, summarizeEvaluationUnits } from "@tangle-network
32
33
  import { createInterface } from "node:readline";
33
34
  import { Worker } from "node:worker_threads";
34
35
  import { gzipSync } from "node:zlib";
36
+ import { parseDocument } from "yaml";
35
37
  import { stuckLoopView, toolWasteView } from "@tangle-network/agent-eval/pipelines";
36
38
  import { sha256Hex } from "@tangle-network/agent-core/node";
37
- //#region src/durable/sql-run-store.ts
39
+ // src/durable/sql-run-store.ts
38
40
  /** Refuses a competing or stale SQL run owner before it can publish new work. */
39
41
  var SqlRunOwnershipError = class extends Error {
40
42
  constructor(message) {
@@ -293,8 +295,7 @@ function wait(ms, signal) {
293
295
  else signal?.addEventListener("abort", abort, { once: true });
294
296
  });
295
297
  }
296
- //#endregion
297
- //#region src/runtime/benchmark-report.ts
298
+ // src/runtime/benchmark-report.ts
298
299
  /**
299
300
  * benchmark-report — turn a fleet of `RunRecord`s into a publishable, multi-axis benchmark report:
300
301
  * a ranked leaderboard, the full profile×axis score matrix, the cost/latency/token columns, and
@@ -623,9 +624,9 @@ function renderLeaderboardSvg(report) {
623
624
  const x = labelW + c * cellW;
624
625
  const s = r.perAxis[a];
625
626
  if (s !== void 0) {
626
- out.push(`<rect x="${x}" y="${y}" width="${cellW - 3}" height="${rowH - 4}" fill="${ramp(s)}"/>`);
627
- out.push(`<text x="${x + (cellW - 3) / 2}" y="${y + 15}" text-anchor="middle" fill="white" font-size="10">${Math.round(100 * s)}</text>`);
628
- } else out.push(`<rect x="${x}" y="${y}" width="${cellW - 3}" height="${rowH - 4}" fill="#f3f4f6"/>`);
627
+ out.push(`<rect x="${x}" y="${y}" width="51" height="22" fill="${ramp(s)}"/>`);
628
+ out.push(`<text x="${x + 51 / 2}" y="${y + 15}" text-anchor="middle" fill="white" font-size="10">${Math.round(100 * s)}</text>`);
629
+ } else out.push(`<rect x="${x}" y="${y}" width="51" height="22" fill="#f3f4f6"/>`);
629
630
  });
630
631
  });
631
632
  out.push("</svg>");
@@ -658,8 +659,7 @@ ${rows}
658
659
  </tbody></table>
659
660
  </body></html>`;
660
661
  }
661
- //#endregion
662
- //#region src/runtime/completion.ts
662
+ // src/runtime/completion.ts
663
663
  /** Decide whether a `CompletionVerdict` may end the node under the policy: authority scales with the verdict's determinism, and probabilistic verdicts must clear `minConfidence`. */
664
664
  function completionAuthorizes(v, policy) {
665
665
  if (!v?.done) return false;
@@ -719,8 +719,7 @@ function deterministicCompletion(check) {
719
719
  };
720
720
  } };
721
721
  }
722
- //#endregion
723
- //#region src/runtime/isolated-checker.ts
722
+ // src/runtime/isolated-checker.ts
724
723
  const toolchains = [
725
724
  "/usr",
726
725
  "/bin",
@@ -856,7 +855,7 @@ var InputLimitError = class extends Error {};
856
855
  async function copyBoundedTree(source, destination, maxBytes, maxEntries) {
857
856
  let bytes = 0;
858
857
  let entries = 0;
859
- const buffer = Buffer.allocUnsafe(1024 * 1024);
858
+ const buffer = Buffer.allocUnsafe(1048576);
860
859
  const visit = async (from, to, isRoot = false) => {
861
860
  if (!isRoot && ++entries > (maxEntries ?? Number.MAX_SAFE_INTEGER)) throw new InputLimitError("Input tree exceeds maxInputEntries");
862
861
  const info = await lstat(from);
@@ -1248,8 +1247,7 @@ async function removeScratch(path) {
1248
1247
  throw new Error([permissionError, error].filter((value) => value !== void 0).map(String).join("; "));
1249
1248
  }
1250
1249
  }
1251
- //#endregion
1252
- //#region src/runtime/declared-check.ts
1250
+ // src/runtime/declared-check.ts
1253
1251
  /**
1254
1252
  * A declared check: the one frozen evaluator program that decides "done" for a run, named by
1255
1253
  * digest, run by Runtime in a fresh box on the check account.
@@ -1282,7 +1280,7 @@ async function removeScratch(path) {
1282
1280
  const INPUT_DIR = "_input";
1283
1281
  const STATE_DIR = "state";
1284
1282
  const SEALED_DIR = "_sealed";
1285
- const DEFAULT_TIMEOUT_MS = 15 * 6e4;
1283
+ const DEFAULT_TIMEOUT_MS = 9e5;
1286
1284
  /** Refuse a malformed declaration before any compute. */
1287
1285
  function assertDeclaredCheck(check, context) {
1288
1286
  const fail = (message) => {
@@ -1489,8 +1487,7 @@ async function writeFiles(files, to) {
1489
1487
  await writeFile(path, file.bytes, { mode: file.mode });
1490
1488
  }
1491
1489
  }
1492
- //#endregion
1493
- //#region src/runtime/loop-dispatch.ts
1490
+ // src/runtime/loop-dispatch.ts
1494
1491
  /** Bridge a campaign `DispatchContext.trace` to a `LoopTraceEmitter` so every
1495
1492
  * `loop.*` event lands as a span under the cell's scoped trace. */
1496
1493
  function campaignTraceToLoopEmitter(trace) {
@@ -1737,8 +1734,7 @@ function loopCampaignDispatch(opts) {
1737
1734
  function loopDispatch(opts) {
1738
1735
  return (profile, scenario, ctx) => runLoopForCell(opts, scenario, profile, ctx);
1739
1736
  }
1740
- //#endregion
1741
- //#region src/runtime/inline-sandbox-client.ts
1737
+ // src/runtime/inline-sandbox-client.ts
1742
1738
  /**
1743
1739
  * The ONE pseudo-box adapter: present any one-shot `Executor` (router / bridge /
1744
1740
  * BYO) as a `SandboxClient` so the round-synchronous `runAgentRounds` can drive it
@@ -1782,8 +1778,10 @@ function inlineSandboxClient(factory, defaults = {}) {
1782
1778
  const controller = new AbortController();
1783
1779
  const callerSignal = opts?.signal;
1784
1780
  const onAbort = () => controller.abort(callerSignal?.reason ?? /* @__PURE__ */ new Error("prompt aborted"));
1785
- if (callerSignal) if (callerSignal.aborted) onAbort();
1786
- else callerSignal.addEventListener("abort", onAbort, { once: true });
1781
+ if (callerSignal) {
1782
+ if (callerSignal.aborted) onAbort();
1783
+ else callerSignal.addEventListener("abort", onAbort, { once: true });
1784
+ }
1787
1785
  const requestedProfile = (options?.backend && typeof options.backend === "object" ? options.backend.profile : void 0) ?? capturedDefaultProfile;
1788
1786
  const parsedProfile = agentProfileSchema.safeParse(requestedProfile);
1789
1787
  if (!parsedProfile.success) throw new Error("inlineSandboxClient: an exact AgentProfile is required; pass defaults.profile or create({ backend: { profile } })");
@@ -1852,8 +1850,7 @@ function inlineSandboxClient(factory, defaults = {}) {
1852
1850
  };
1853
1851
  } };
1854
1852
  }
1855
- //#endregion
1856
- //#region src/runtime/http-mcp-client.ts
1853
+ // src/runtime/http-mcp-client.ts
1857
1854
  /**
1858
1855
  * `connectHttpMcp` — the remote (streamable HTTP) MCP client, sibling of
1859
1856
  * `connectStdioMcp`. Same connection contract (`tools`, `callTool`, `close`),
@@ -2012,8 +2009,7 @@ async function connectHttpMcp(spec) {
2012
2009
  throw error instanceof Error ? error : new Error(String(error));
2013
2010
  }
2014
2011
  }
2015
- //#endregion
2016
- //#region src/runtime/key-provider.ts
2012
+ // src/runtime/key-provider.ts
2017
2013
  /** The env-backed provider: reads the (dotenvx-loaded) process env. Empty /
2018
2014
  * whitespace-only values count as absent — fail loud, not with a blank key. */
2019
2015
  function envKeyProvider(env = process.env) {
@@ -2112,8 +2108,7 @@ async function resolveMcpServerLaunch(server, keys, label) {
2112
2108
  ...Object.keys(protectedEnv).length > 0 ? { protectedEnv } : {}
2113
2109
  };
2114
2110
  }
2115
- //#endregion
2116
- //#region src/runtime/mcp-environment.ts
2111
+ // src/runtime/mcp-environment.ts
2117
2112
  /** POST JSON-RPC and parse a JSON body OR the last `data:` line of an SSE stream.
2118
2113
  * Retries thrown fetches (transient network) with linear backoff; HTTP status and
2119
2114
  * JSON-RPC errors are returned to the caller, not retried. */
@@ -2217,8 +2212,7 @@ function createMcpEnvironment(opts) {
2217
2212
  }
2218
2213
  };
2219
2214
  }
2220
- //#endregion
2221
- //#region src/runtime/stdio-mcp-client.ts
2215
+ // src/runtime/stdio-mcp-client.ts
2222
2216
  /**
2223
2217
  * Same-host stdio MCP: the ONE persistent newline-delimited JSON-RPC 2.0
2224
2218
  * connection to a spawned MCP server child process. This is the handshake
@@ -2454,7 +2448,10 @@ async function resolveRemoteMcpHeaders(server, keys, label) {
2454
2448
  */
2455
2449
  async function materializeLocalMcp(profile, opts = {}) {
2456
2450
  const security = validateAgentProfileSecurity(profile, opts.profileSecurityPolicy);
2457
- if (!security.ok) throw new ValidationError(`materializeLocalMcp: profile host execution refused: ${security.issues.filter((issue) => issue.level === "error").map((issue) => issue.message).join("; ")}`);
2451
+ if (!security.ok) {
2452
+ const reasons = security.issues.filter((issue) => issue.level === "error").map((issue) => issue.message).join("; ");
2453
+ throw new ValidationError(`materializeLocalMcp: profile host execution refused: ${reasons}`);
2454
+ }
2458
2455
  const maxResultChars = opts.maxResultChars ?? 2e3;
2459
2456
  const connections = [];
2460
2457
  const routes = /* @__PURE__ */ new Map();
@@ -2540,8 +2537,7 @@ async function materializeLocalMcp(profile, opts = {}) {
2540
2537
  close
2541
2538
  };
2542
2539
  }
2543
- //#endregion
2544
- //#region src/runtime/local-sandbox-client.ts
2540
+ // src/runtime/local-sandbox-client.ts
2545
2541
  /**
2546
2542
  * `localSandboxClient` — the SAME-HOST pseudo-box: a `SandboxClient` whose
2547
2543
  * `create()` MATERIALIZES the profile's stdio MCP servers as local child
@@ -2657,8 +2653,7 @@ function localSandboxClient(opts) {
2657
2653
  };
2658
2654
  } };
2659
2655
  }
2660
- //#endregion
2661
- //#region src/runtime/resolve-sandbox-client.ts
2656
+ // src/runtime/resolve-sandbox-client.ts
2662
2657
  /**
2663
2658
  * The product-facing backend selector: one call picks the execution transport a
2664
2659
  * `runAgentRounds` (or any consumer that drives a `SandboxClient`) runs on, from the
@@ -2719,8 +2714,7 @@ function resolveSandboxClient(opts) {
2719
2714
  }
2720
2715
  }
2721
2716
  }
2722
- //#endregion
2723
- //#region src/runtime/define-leaderboard.ts
2717
+ // src/runtime/define-leaderboard.ts
2724
2718
  /**
2725
2719
  * `defineLeaderboard` — the declarative eval-leaderboard facade.
2726
2720
  *
@@ -3069,8 +3063,7 @@ function defineLeaderboard(spec) {
3069
3063
  toBenchmarkAdapter: () => leaderboardBenchmarkAdapter(spec)
3070
3064
  };
3071
3065
  }
3072
- //#endregion
3073
- //#region src/runtime/harvest-corpus.ts
3066
+ // src/runtime/harvest-corpus.ts
3074
3067
  /**
3075
3068
  * Analyze completed runs through the selected observer and retain findings in a corpus.
3076
3069
  *
@@ -3167,8 +3160,7 @@ async function harvestCorpus(opts) {
3167
3160
  if (report.runsObserved === 0 && report.failures.length > 0) throw new HarvestError(report);
3168
3161
  return report;
3169
3162
  }
3170
- //#endregion
3171
- //#region src/runtime/in-process-sandbox-client.ts
3163
+ // src/runtime/in-process-sandbox-client.ts
3172
3164
  /**
3173
3165
  * The ONE in-process pseudo-box: present a plain user callback as a
3174
3166
  * `SandboxClient` so an example or test can drive `runAgentRounds` / `openSandboxRun`
@@ -3288,8 +3280,7 @@ function inProcessSandboxClient(options) {
3288
3280
  };
3289
3281
  } };
3290
3282
  }
3291
- //#endregion
3292
- //#region src/runtime/observation-registry.ts
3283
+ // src/runtime/observation-registry.ts
3293
3284
  /** Adapt any Eval analyst registry, including recursive engines, to observation and harvesting. */
3294
3285
  function observationFromRegistry(registry, options) {
3295
3286
  if (!["production", "search"].includes(options.proposalOrigin)) throw new TypeError("registry observation requires an explicit production or search origin");
@@ -3328,8 +3319,7 @@ function observationFromRegistry(registry, options) {
3328
3319
  }
3329
3320
  };
3330
3321
  }
3331
- //#endregion
3332
- //#region src/runtime/personify/analyst.ts
3322
+ // src/runtime/personify/analyst.ts
3333
3323
  /**
3334
3324
  * The diagnosis a combinator steers from must be TRACE-derived, never JUDGE-derived. A finding
3335
3325
  * whose evidence is a judge/verdict score (an `EvidenceRef` of `kind:'metric'` with a
@@ -3452,8 +3442,7 @@ function observedBestScore(settledSoFar) {
3452
3442
  }
3453
3443
  return best;
3454
3444
  }
3455
- //#endregion
3456
- //#region src/runtime/personify/combinators.ts
3445
+ // src/runtime/personify/combinators.ts
3457
3446
  /**
3458
3447
  *
3459
3448
  * The generic combinator library — the content-free act-bodies the wave's §1 contract froze.
@@ -3915,8 +3904,7 @@ function blocked(blockers) {
3915
3904
  blockers
3916
3905
  };
3917
3906
  }
3918
- //#endregion
3919
- //#region src/runtime/personify/corpus.ts
3907
+ // src/runtime/personify/corpus.ts
3920
3908
  const corpusSchemaVersion = "1.0.0";
3921
3909
  /**
3922
3910
  * Assert a value is a well-formed `CorpusRecord`. A PROVENANCE-and-shape check: every
@@ -4121,8 +4109,7 @@ async function renderCorpusToInstructions(opts) {
4121
4109
  function renderLine(record) {
4122
4110
  return record.rationale ? `${record.claim} (${record.rationale})` : record.claim;
4123
4111
  }
4124
- //#endregion
4125
- //#region src/runtime/personify/registry.ts
4112
+ // src/runtime/personify/registry.ts
4126
4113
  /**
4127
4114
  *
4128
4115
  * The loop-shape registry — the OPEN, content-free extension point for the personify layer.
@@ -4170,8 +4157,7 @@ function createShapeRegistry() {
4170
4157
  /** The default registry `runPersonified` resolves a shape name against. Empty by construction —
4171
4158
  * a caller registers its own composed shapes; the engine ships no domain shape. */
4172
4159
  const builtinShapes = createShapeRegistry();
4173
- //#endregion
4174
- //#region src/runtime/personify/persona.ts
4160
+ // src/runtime/personify/persona.ts
4175
4161
  /**
4176
4162
  *
4177
4163
  * The personify layer impl — `definePersona` (the thin builder) + `runPersonified` (composes
@@ -4353,8 +4339,7 @@ function mergeSeams(ctx, seams) {
4353
4339
  }
4354
4340
  };
4355
4341
  }
4356
- //#endregion
4357
- //#region src/runtime/personify/trajectory.ts
4342
+ // src/runtime/personify/trajectory.ts
4358
4343
  /**
4359
4344
  *
4360
4345
  * Trajectory trace + cost ledger — the post-hoc tree reconstructor (§4 of `wave-types`).
@@ -4581,8 +4566,7 @@ function requireSpend(rolled, id, root) {
4581
4566
  if (!spend) throw new Error(`trajectoryReport: node '${id}' was never rolled up in tree '${root}' (unreachable from root)`);
4582
4567
  return spend;
4583
4568
  }
4584
- //#endregion
4585
- //#region src/runtime/durable-sync.ts
4569
+ // src/runtime/durable-sync.ts
4586
4570
  /**
4587
4571
  * Threads that run fsync for the private CAS. Node runs every fs call on libuv's pool of four
4588
4572
  * threads, and an fsync on a busy disk holds its thread until the filesystem journal commits. On
@@ -4710,8 +4694,7 @@ async function syncDirectory(directory) {
4710
4694
  await handle.close();
4711
4695
  }
4712
4696
  }
4713
- //#endregion
4714
- //#region src/runtime/private-cas-objects.ts
4697
+ // src/runtime/private-cas-objects.ts
4715
4698
  /**
4716
4699
  * The local object store of a private CAS: where an object lives, how it is written, read back
4717
4700
  * and verified, and how a locator is checked. An object's name is published only after its bytes
@@ -4784,7 +4767,7 @@ async function* readObject(path, ref, signal) {
4784
4767
  if (!stats.isFile() || stats.size !== ref.byteLength) throw new Error("private CAS object failed digest or length verification");
4785
4768
  yield* checkedChunks(file.createReadStream({
4786
4769
  autoClose: false,
4787
- highWaterMark: 64 * 1024
4770
+ highWaterMark: 65536
4788
4771
  }), ref, signal);
4789
4772
  } finally {
4790
4773
  await file.close();
@@ -4966,8 +4949,7 @@ async function putPrivateCasBuffered(layout, offload, object, signal) {
4966
4949
  }, signal);
4967
4950
  return ref;
4968
4951
  }
4969
- //#endregion
4970
- //#region src/runtime/private-cas-offload.ts
4952
+ // src/runtime/private-cas-offload.ts
4971
4953
  /**
4972
4954
  * Durable copies of a private CAS, and the offload passes that make them: one object at a time to
4973
4955
  * the off-host store, with a stall bound, retries, a receipt on the host once the store holds the
@@ -5170,7 +5152,8 @@ var PrivateCasOffload = class {
5170
5152
  async copyObjects(objects) {
5171
5153
  const { durable } = this.layout;
5172
5154
  let refusal;
5173
- return mapWithConcurrency(objects, durable === void 0 || durable.putStream && durable.getStream ? OFFLOAD_COPIES_AT_ONCE : 1, async ({ hex, path, size }) => {
5155
+ const streams = durable === void 0 || durable.putStream && durable.getStream;
5156
+ return mapWithConcurrency(objects, streams ? OFFLOAD_COPIES_AT_ONCE : 1, async ({ hex, path, size }) => {
5174
5157
  await this.copier.waitForCopy(hex);
5175
5158
  if (await hasReceipt(this.layout, hex)) return {
5176
5159
  hex,
@@ -5364,8 +5347,7 @@ function createDurableCopier(layout) {
5364
5347
  }
5365
5348
  };
5366
5349
  }
5367
- //#endregion
5368
- //#region src/runtime/private-cas.ts
5350
+ // src/runtime/private-cas.ts
5369
5351
  const SAFE_NAMESPACE = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/u;
5370
5352
  const DURABLE_STALL_MS = 12e4;
5371
5353
  /**
@@ -5430,8 +5412,7 @@ function createPrivateCasArtifactPort(root, namespace, options = {}) {
5430
5412
  if (durable === void 0) markPutStreamVerified(putStream, readStream);
5431
5413
  return port;
5432
5414
  }
5433
- //#endregion
5434
- //#region src/runtime/run-benchmark.ts
5415
+ // src/runtime/run-benchmark.ts
5435
5416
  /**
5436
5417
  * runBenchmark — the packaged optimization suite. Define a domain by implementing an
5437
5418
  * `Environment` (open / tools / call / score / close); get the optimization strategies
@@ -5644,10 +5625,9 @@ function printBenchmarkReport(report) {
5644
5625
  console.log(` refine − sample: ${pp(l.mean)} CI [${pp(l.low)}, ${pp(l.high)}] (${sig})`);
5645
5626
  }
5646
5627
  }
5647
- //#endregion
5648
- //#region src/runtime/s3-private-cas-namespace.ts
5628
+ // src/runtime/s3-private-cas-namespace.ts
5649
5629
  const NAMESPACE$1 = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/u;
5650
- const MAX_PAGE_BYTES = 2 * 1024 * 1024;
5630
+ const MAX_PAGE_BYTES = 2097152;
5651
5631
  const fingerprint = (namespace, location, storeIdentity, objects) => `sha256:${createHash("sha256").update(JSON.stringify({
5652
5632
  namespace,
5653
5633
  location,
@@ -5827,8 +5807,7 @@ function privateCasNamespaceOperations({ request, refusal, prefix, location, sto
5827
5807
  }
5828
5808
  };
5829
5809
  }
5830
- //#endregion
5831
- //#region src/runtime/s3-private-cas-request.ts
5810
+ // src/runtime/s3-private-cas-request.ts
5832
5811
  const EMPTY_PAYLOAD = createHash("sha256").update("").digest("hex");
5833
5812
  const hex$1 = (value) => createHash("sha256").update(value).digest("hex");
5834
5813
  const hmac = (key, value) => createHmac("sha256", key).update(value).digest();
@@ -5861,14 +5840,15 @@ function createPrivateCasS3Transport(options, endpoint) {
5861
5840
  payloadHash
5862
5841
  ].join("\n");
5863
5842
  const scope = `${day}/${region}/s3/aws4_request`;
5864
- const signature = createHmac("sha256", hmac(hmac(hmac(hmac(`AWS4${options.secretAccessKey}`, day), region), "s3"), "aws4_request")).update([
5843
+ const signingKey = hmac(hmac(hmac(hmac(`AWS4${options.secretAccessKey}`, day), region), "s3"), "aws4_request");
5844
+ const signature = createHmac("sha256", signingKey).update([
5865
5845
  "AWS4-HMAC-SHA256",
5866
5846
  amzDate,
5867
5847
  scope,
5868
5848
  hex$1(canonical)
5869
5849
  ].join("\n")).digest("hex");
5870
5850
  const { host: _host, ...sent } = signed;
5871
- const deadline = AbortSignal.timeout(timeoutMs + Math.ceil((byteLength ?? (body instanceof Uint8Array ? body.byteLength : 0)) / (1024 * 1024)) * 1e3);
5851
+ const deadline = AbortSignal.timeout(timeoutMs + Math.ceil((byteLength ?? (body instanceof Uint8Array ? body.byteLength : 0)) / 1048576) * 1e3);
5872
5852
  return await send(url, {
5873
5853
  method,
5874
5854
  headers: {
@@ -5900,14 +5880,13 @@ function createPrivateCasS3Transport(options, endpoint) {
5900
5880
  refusal
5901
5881
  };
5902
5882
  }
5903
- //#endregion
5904
- //#region src/runtime/s3-private-cas-store.ts
5883
+ // src/runtime/s3-private-cas-store.ts
5905
5884
  const DIGEST = /^sha256:([0-9a-f]{64})$/u;
5906
5885
  const BUCKET = /^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/u;
5907
5886
  const PREFIX = /^(?:[A-Za-z0-9._-]+\/)*$/u;
5908
5887
  const NAMESPACE = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/u;
5909
5888
  const POINTER_NAME = /^(?!sha256\/)[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}(?:\/[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}){0,3}$/u;
5910
- const POINTER_MAX_BYTES = 1024 * 1024;
5889
+ const POINTER_MAX_BYTES = 1048576;
5911
5890
  const CONTENT_TYPE = "application/octet-stream";
5912
5891
  const METADATA_DIGEST = "x-amz-meta-sha256";
5913
5892
  const hex = (value) => createHash("sha256").update(value).digest("hex");
@@ -6073,8 +6052,7 @@ function createS3PrivateCasStore(options) {
6073
6052
  }
6074
6053
  };
6075
6054
  }
6076
- //#endregion
6077
- //#region src/runtime/box-read-retry.ts
6055
+ // src/runtime/box-read-retry.ts
6078
6056
  /**
6079
6057
  * One bounded-retry read over a sandbox box's filesystem, shared by every caller that reads a
6080
6058
  * path the agent may have just written.
@@ -6117,8 +6095,7 @@ async function readBoxPathWithRetry(read, path, options) {
6117
6095
  error: lastError
6118
6096
  };
6119
6097
  }
6120
- //#endregion
6121
- //#region src/runtime/sandbox-run.ts
6098
+ // src/runtime/sandbox-run.ts
6122
6099
  /**
6123
6100
  * Thrown when a turn is aborted/timed-out mid-settle. Carries the events drained
6124
6101
  * BEFORE the abort fired (and any in-progress `readError`) so an aborted run is
@@ -6386,8 +6363,7 @@ function hashText(value) {
6386
6363
  }
6387
6364
  return (hash >>> 0).toString(16).padStart(8, "0");
6388
6365
  }
6389
- //#endregion
6390
- //#region src/runtime/strategy-evolution-cells.ts
6366
+ // src/runtime/strategy-evolution-cells.ts
6391
6367
  /**
6392
6368
  * Cells run in this process on one dedicated lane of Runtime's search executor, which
6393
6369
  * records each finished attempt under its run id (a restarted search adopts it instead of
@@ -6543,7 +6519,8 @@ function unknownAccounting(reason) {
6543
6519
  }
6544
6520
  /** Free text as the ledger stores it: redacted with the share profile and bounded. */
6545
6521
  function shareText(error) {
6546
- return redact(error instanceof Error ? error.message : String(error), { profile: "share" }).value.slice(0, 300);
6522
+ const text = error instanceof Error ? error.message : String(error);
6523
+ return redact(text, { profile: "share" }).value.slice(0, 300);
6547
6524
  }
6548
6525
  const STRATEGY_EVOLUTION_SOURCE = {
6549
6526
  uri: "npm:@tangle-network/agent-runtime#runStrategyEvolution",
@@ -6560,10 +6537,10 @@ const STRATEGY_EVOLUTION_SOURCE = {
6560
6537
  /** Check every option and derive the search's identity; throws `ConfigError` on a bad one. */
6561
6538
  function planStrategyEvolution(cfg) {
6562
6539
  const root = cfg.root ?? refine;
6563
- const budget = positiveInteger("budget", cfg.budget ?? 3);
6564
- const concurrency = positiveInteger("concurrency", cfg.concurrency ?? 3);
6540
+ const budget = positiveInteger$1("budget", cfg.budget ?? 3);
6541
+ const concurrency = positiveInteger$1("concurrency", cfg.concurrency ?? 3);
6565
6542
  const maxExpansions = nonNegativeInteger("maxExpansions", cfg.maxExpansions ?? 4);
6566
- const maxAttempts = positiveInteger("maxAttempts", cfg.maxAttempts ?? 3);
6543
+ const maxAttempts = positiveInteger$1("maxAttempts", cfg.maxAttempts ?? 3);
6567
6544
  const seed = nonNegativeInteger("seed", cfg.seed ?? 42);
6568
6545
  const cellUsd = dollars("cellUsd", cfg.cellUsd) ?? 0;
6569
6546
  const maxUsd = dollars("maxUsd", cfg.maxUsd);
@@ -6686,7 +6663,7 @@ function searchTasks(claim, tasks) {
6686
6663
  }
6687
6664
  }));
6688
6665
  }
6689
- function positiveInteger(name, value) {
6666
+ function positiveInteger$1(name, value) {
6690
6667
  if (!Number.isSafeInteger(value) || value < 1) throw new ConfigError(`evolution: ${name} must be a positive integer`);
6691
6668
  return value;
6692
6669
  }
@@ -6699,8 +6676,7 @@ function dollars(name, value) {
6699
6676
  if (!Number.isFinite(value) || value < 0) throw new ConfigError(`evolution: ${name} must be a finite non-negative number`);
6700
6677
  return value;
6701
6678
  }
6702
- //#endregion
6703
- //#region src/runtime/strategy-evolution.ts
6679
+ // src/runtime/strategy-evolution.ts
6704
6680
  /**
6705
6681
  * runStrategyEvolution: strategy search on Eval's search kernel (`runSearch`).
6706
6682
  *
@@ -7102,8 +7078,7 @@ function strategyNames(state, recorder, codec) {
7102
7078
  }
7103
7079
  return names;
7104
7080
  }
7105
- //#endregion
7106
- //#region src/runtime/supervise/chat-transport-executor.ts
7081
+ // src/runtime/supervise/chat-transport-executor.ts
7107
7082
  /**
7108
7083
  * A session-owning composition over Runtime's canonical Router tool-loop executor.
7109
7084
  *
@@ -7171,7 +7146,8 @@ function buildChatTransportExecutor(opts, context) {
7171
7146
  profile,
7172
7147
  harness: null
7173
7148
  };
7174
- return mapExecutorResult(createExecutor(config)(spec, context), (result) => {
7149
+ const inner = createExecutor(config)(spec, context);
7150
+ return mapExecutorResult(inner, (result) => {
7175
7151
  const raw = result.out;
7176
7152
  const content = typeof raw?.content === "string" ? raw.content : "";
7177
7153
  return {
@@ -7224,8 +7200,7 @@ function chatWorkerSeam(opts) {
7224
7200
  };
7225
7201
  };
7226
7202
  }
7227
- //#endregion
7228
- //#region src/runtime/supervise/designer-tools.ts
7203
+ // src/runtime/supervise/designer-tools.ts
7229
7204
  /**
7230
7205
  * `graphDesignerExtraTools` — the designer's toolset on the existing
7231
7206
  * `RunGraphOptions.extraTools` seam.
@@ -7353,7 +7328,7 @@ function graphDesignerExtraTools(env) {
7353
7328
  })();
7354
7329
  if (name === "designer_history") return (async () => {
7355
7330
  const args = asRecord(raw ?? {}, "designer_history");
7356
- const { listGraphRuns } = await import("./supervise-BGfm2GlY.js").then((n) => n.g);
7331
+ const { listGraphRuns } = await import("./supervise-CNNhX0ab.js").then((n) => n.g);
7357
7332
  const all = await listGraphRuns(registry);
7358
7333
  return { runs: (args.taskShape === void 0 ? all : all.filter((row) => row.taskDigest === taskShapeDigest(asRecord(args.taskShape, "designer_history.taskShape")))).map(summarize) };
7359
7334
  })();
@@ -7364,7 +7339,7 @@ function graphDesignerExtraTools(env) {
7364
7339
  if (mode === "replay") {
7365
7340
  const digest = args.graphDigest;
7366
7341
  if (typeof digest !== "string" || digest.length === 0) throw new ValidationError("designer_run_graph: replay mode requires graphDigest from lookup");
7367
- const { loadGraph } = await import("./supervise-BGfm2GlY.js").then((n) => n.g);
7342
+ const { loadGraph } = await import("./supervise-CNNhX0ab.js").then((n) => n.g);
7368
7343
  const stored = await loadGraph(registry, digest);
7369
7344
  if (!stored) throw new ValidationError(`designer_run_graph: no stored graph ${digest.slice(0, 12)} — re-lookup`);
7370
7345
  const graph = env.bindCheck(graphFromStored(stored, () => {
@@ -7403,8 +7378,272 @@ function graphDesignerExtraTools(env) {
7403
7378
  };
7404
7379
  }
7405
7380
  }
7406
- //#endregion
7407
- //#region src/runtime/supervise/graph-session-observation.ts
7381
+ // src/runtime/supervise/graph-file.ts
7382
+ /** A provider name in authored data needs an environment-owned canonical connection binding. */
7383
+ var GraphFileResolutionError = class extends Error {
7384
+ provider;
7385
+ node;
7386
+ code = "CONNECTION_REQUIRED";
7387
+ fixCommand = "tangle graph run --help";
7388
+ constructor(provider, node) {
7389
+ super(`loadGraphFile: node ${node} needs an environment binding for provider ${provider}`);
7390
+ this.provider = provider;
7391
+ this.node = node;
7392
+ this.name = "GraphFileResolutionError";
7393
+ }
7394
+ };
7395
+ function refuse$2(message) {
7396
+ throw new ValidationError(`loadGraphFile: ${message}`);
7397
+ }
7398
+ function jsonData(value, visiting = /* @__PURE__ */ new Set()) {
7399
+ if (value === null || typeof value === "string" || typeof value === "boolean") return;
7400
+ if (typeof value === "number" && Number.isFinite(value)) return;
7401
+ if (!value || typeof value !== "object" || visiting.has(value)) refuse$2("definition must be finite, acyclic JSON data");
7402
+ visiting.add(value);
7403
+ for (const child of Object.values(value)) jsonData(child, visiting);
7404
+ visiting.delete(value);
7405
+ }
7406
+ function bindParameters(raw, supplied) {
7407
+ const definitions = graphFileSchema.shape.params.parse(raw.params) ?? {};
7408
+ for (const key of Object.keys(supplied ?? {})) if (!Object.hasOwn(definitions, key)) refuse$2(`unknown parameter ${key}`);
7409
+ return Object.fromEntries(Object.entries(definitions).map(([key, definition]) => {
7410
+ let value = supplied && Object.hasOwn(supplied, key) ? supplied[key] : definition.default;
7411
+ if (value === void 0) refuse$2(`missing parameter ${key}`);
7412
+ const type = definition.type;
7413
+ if (typeof value === "string" && type && type !== "string") try {
7414
+ value = JSON.parse(value);
7415
+ } catch {
7416
+ refuse$2(`parameter ${key} must be ${type}`);
7417
+ }
7418
+ if (type) {
7419
+ if (!(type === "integer" ? Number.isSafeInteger(value) : type === "null" ? value === null : type === "array" ? Array.isArray(value) : type === "object" ? value !== null && typeof value === "object" && !Array.isArray(value) : typeof value === type)) refuse$2(`parameter ${key} must be ${type}`);
7420
+ }
7421
+ jsonData(value);
7422
+ return [key, value];
7423
+ }));
7424
+ }
7425
+ async function expandProfile(node, options) {
7426
+ if (node.id === "params" || node.id === "trigger") refuse$2(`reserved node id ${node.id}`);
7427
+ const authored = options.seat ?? options.nodeSeats?.[node.id] ?? node.seat;
7428
+ const resolveSeat = options.resolveSeat;
7429
+ const context = {
7430
+ node: node.id,
7431
+ cwd: options.cwd,
7432
+ signal: options.signal
7433
+ };
7434
+ let selected;
7435
+ if (authored !== void 0) {
7436
+ if (!resolveSeat) refuse$2(`node ${node.id} has unresolved seat shorthand; supply resolveSeat from Bridge login inventory or a canonical profile`);
7437
+ const candidates = typeof authored === "string" ? [authored] : authored;
7438
+ if (!candidates.length) refuse$2(`node ${node.id} has an empty seat preference list`);
7439
+ for (const [index, candidate] of candidates.entries()) {
7440
+ selected = await resolveSeat(candidate, {
7441
+ ...context,
7442
+ lastCandidate: index === candidates.length - 1
7443
+ });
7444
+ if (selected) break;
7445
+ }
7446
+ if (!selected) refuse$2(`node ${node.id} has no available Bridge seat; sign in through Bridge or choose another seat`);
7447
+ } else if (Array.isArray(node.profile?.seats)) {
7448
+ const parsed = agentProfileSchema.safeParse({
7449
+ ...node.profile,
7450
+ name: node.id
7451
+ });
7452
+ if (!parsed.success) refuse$2(`node ${node.id} has an invalid profile: ${parsed.error.message}`);
7453
+ } else if (!node.profile?.harness || !concreteProfileModel(node.profile) || !node.profile.model?.provider) {
7454
+ selected = options.seats?.[0] ?? await resolveSeat?.(void 0, {
7455
+ ...context,
7456
+ lastCandidate: true
7457
+ });
7458
+ if (!selected) refuse$2(`node ${node.id} needs a canonical profile or resolveSeat from Bridge login inventory`);
7459
+ }
7460
+ const connections = await Promise.all((node.needs ?? []).map(async (provider) => {
7461
+ if (options.needs && Object.hasOwn(options.needs, provider)) return options.needs[provider];
7462
+ const connection = await options.resolveNeed?.(provider, context);
7463
+ if (connection === void 0) throw new GraphFileResolutionError(provider, node.id);
7464
+ return connection;
7465
+ }));
7466
+ const profile = {
7467
+ ...node.profile,
7468
+ name: node.id
7469
+ };
7470
+ if (selected) {
7471
+ delete profile.seats;
7472
+ profile.harness = selected.harness;
7473
+ profile.model = {
7474
+ ...node.profile?.model,
7475
+ provider: selected.provider,
7476
+ default: selected.model,
7477
+ ...selected.reasoningEffort === void 0 ? {} : { reasoningEffort: selected.reasoningEffort }
7478
+ };
7479
+ }
7480
+ if (node.needs) profile.connections = [...node.profile?.connections ?? [], ...connections];
7481
+ const parsed = agentProfileSchema.safeParse(profile);
7482
+ if (!parsed.success) refuse$2(`node ${node.id} has an invalid profile: ${parsed.error.message}`);
7483
+ assertExecutableAgentProfile(parsed.data, `loadGraphFile node ${node.id}`);
7484
+ return parsed.data;
7485
+ }
7486
+ /** Compile canonical YAML/JSON to content-addressed graph data. Host resolvers may perform I/O. */
7487
+ async function loadGraphFile(file, options = {}) {
7488
+ const format = extname(file).toLowerCase();
7489
+ if (![
7490
+ ".yaml",
7491
+ ".yml",
7492
+ ".json"
7493
+ ].includes(format)) refuse$2("file must be YAML or JSON");
7494
+ const text = options.source ?? await readFile(file, "utf8");
7495
+ const document = parseDocument(text, {
7496
+ uniqueKeys: true,
7497
+ strict: true
7498
+ });
7499
+ if (document.errors.length) refuse$2(document.errors.map((error) => error.message).join("; "));
7500
+ if (document.warnings.length) refuse$2(document.warnings.map((warning) => warning.message).join("; "));
7501
+ const raw = format === ".json" ? JSON.parse(text) : document.toJS({ maxAliasCount: 100 });
7502
+ jsonData(raw);
7503
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) refuse$2("definition must be an object");
7504
+ const source = raw;
7505
+ if (Array.isArray(source.nodes) && source.nodes.some((node) => node && typeof node === "object" && "call" in node)) refuse$2("call vertices are not supported by this loader");
7506
+ const params = bindParameters(source, options.params);
7507
+ const { params: _definitions, on, ...authored } = source;
7508
+ const bindings = {
7509
+ params,
7510
+ trigger: options.trigger
7511
+ };
7512
+ const bindingOptions = options.trigger === void 0 ? { defer: ["trigger"] } : {};
7513
+ const compiled = compileGraphParameters(authored, bindings, bindingOptions);
7514
+ const bound = graphFileSchema.parse(compiled.value);
7515
+ const boundOn = on === void 0 ? void 0 : bindGraphParameters(on, bindings, bindingOptions);
7516
+ if (bound.check && bound.deliverable) refuse$2("use check or deliverable, not both");
7517
+ let deliverable = bound.deliverable;
7518
+ if (bound.check) {
7519
+ if ("command" in bound.check) deliverable = {
7520
+ ...(bound.check.describe ?? bound.describe) === void 0 ? {} : { describe: bound.check.describe ?? bound.describe },
7521
+ checkRef: "command",
7522
+ command: bound.check.command
7523
+ };
7524
+ else {
7525
+ const { describe, ...condition } = "describe" in bound.check ? bound.check : {
7526
+ ...bound.check,
7527
+ describe: void 0
7528
+ };
7529
+ deliverable = {
7530
+ ...(describe ?? bound.describe) === void 0 ? {} : { describe: describe ?? bound.describe },
7531
+ checkRef: "route",
7532
+ when: condition
7533
+ };
7534
+ }
7535
+ }
7536
+ if (!deliverable) refuse$2("check or deliverable is required");
7537
+ if (deliverable.checkRef === "route" && !deliverable.when) refuse$2("route deliverable requires when");
7538
+ if (deliverable.checkRef === "command" && !deliverable.command) refuse$2("command deliverable requires command");
7539
+ const nodes = await Promise.all(bound.nodes.map(async (node) => ({
7540
+ id: node.id,
7541
+ profile: await expandProfile(node, {
7542
+ ...options,
7543
+ cwd: options.cwd ?? dirname(file)
7544
+ })
7545
+ })));
7546
+ const nodeIds = new Set(nodes.map((node) => node.id));
7547
+ for (const id of Object.keys(options.nodeSeats ?? {})) if (!nodeIds.has(id)) refuse$2(`seat override references unknown node ${id}`);
7548
+ if (deliverable.when) {
7549
+ for (const condition of "all" in deliverable.when ? deliverable.when.all : [deliverable.when]) if (condition.node !== void 0 && !nodeIds.has(condition.node)) refuse$2(`check references unknown node ${condition.node}`);
7550
+ }
7551
+ const topology = {
7552
+ nodes,
7553
+ edges: bound.edges,
7554
+ budget: bound.budget,
7555
+ deliverable,
7556
+ ...bound.entry ? { entry: bound.entry.map((entry) => typeof entry === "string" ? {
7557
+ node: entry,
7558
+ task: {}
7559
+ } : entry) } : {},
7560
+ ...bound.gates ? { gates: bound.gates } : {}
7561
+ };
7562
+ const triggerBindings = compiled.triggerBindings.flatMap((slot) => {
7563
+ const [top, index, field, ...tail] = slot.path;
7564
+ if (top === "nodes") {
7565
+ if (field === "id") return [slot, {
7566
+ ...slot,
7567
+ path: [
7568
+ "nodes",
7569
+ index,
7570
+ "profile",
7571
+ "name"
7572
+ ]
7573
+ }];
7574
+ if (field === "profile") {
7575
+ if (tail[0] === "name") return [];
7576
+ if (tail[0] === "harness" || tail[0] === "model" && [
7577
+ "provider",
7578
+ "default",
7579
+ "reasoningEffort"
7580
+ ].includes(String(tail[1]))) {
7581
+ let before = bound.nodes[index].profile;
7582
+ let after = nodes[index].profile;
7583
+ for (const key of tail) {
7584
+ before = before?.[key];
7585
+ after = after?.[key];
7586
+ }
7587
+ if (before !== after) return [];
7588
+ }
7589
+ return [slot];
7590
+ }
7591
+ refuse$2("trigger slots in seat/needs must be supplied to loadGraphFile before profile resolution");
7592
+ }
7593
+ if (top === "check") {
7594
+ if (index === "describe") return [{
7595
+ ...slot,
7596
+ path: ["deliverable", "describe"]
7597
+ }];
7598
+ return [{
7599
+ ...slot,
7600
+ path: [
7601
+ "deliverable",
7602
+ index === "command" ? "command" : "when",
7603
+ ...index === "command" ? slot.path.slice(2) : slot.path.slice(1)
7604
+ ]
7605
+ }];
7606
+ }
7607
+ if (top === "describe") return bound.check?.describe !== void 0 || bound.deliverable ? [] : [{
7608
+ ...slot,
7609
+ path: ["deliverable", "describe"]
7610
+ }];
7611
+ if (top === "entry" && slot.path.length === 2) return [{
7612
+ ...slot,
7613
+ path: [
7614
+ "entry",
7615
+ index,
7616
+ "node"
7617
+ ]
7618
+ }];
7619
+ return [
7620
+ "edges",
7621
+ "budget",
7622
+ "gates",
7623
+ "entry",
7624
+ "deliverable"
7625
+ ].includes(String(top)) ? [slot] : [];
7626
+ });
7627
+ assertGraphTriggerBindings(topology, triggerBindings);
7628
+ const content = {
7629
+ ...topology,
7630
+ triggerBindings
7631
+ };
7632
+ const registry = options.registry ?? kernelPromptRegistry();
7633
+ if (content.entry) validateFlowGraph(content, registry, options.analysts);
7634
+ else validateGraphTopology(content.nodes, content.edges, registry, options.analysts);
7635
+ const digest = graphDigest(content);
7636
+ if (bound.digest !== void 0 && bound.digest !== digest) refuse$2("supplied digest does not match the materialized graph");
7637
+ return {
7638
+ graph: {
7639
+ ...content,
7640
+ digest
7641
+ },
7642
+ params,
7643
+ ...boundOn === void 0 ? {} : { on: boundOn }
7644
+ };
7645
+ }
7646
+ // src/runtime/supervise/graph-session-observation.ts
7408
7647
  function measured(fact) {
7409
7648
  return fact && !fact.partial && fact.value !== null ? fact.value : void 0;
7410
7649
  }
@@ -7588,8 +7827,7 @@ function graphFromSessionFacts(facts, options) {
7588
7827
  }
7589
7828
  };
7590
7829
  }
7591
- //#endregion
7592
- //#region src/runtime/supervise/profile-registry.ts
7830
+ // src/runtime/supervise/profile-registry.ts
7593
7831
  /**
7594
7832
  * `profile-registry` — named AgentProfiles with run receipts: the missing
7595
7833
  * bottom layer of the designer's memory.
@@ -7641,7 +7879,8 @@ async function recordProfileRun(reg, profile, record) {
7641
7879
  await withJsonlFileLock(join(reg.root, RECORDS_FILE), async (canonicalPath) => {
7642
7880
  const file = join(reg.root, PROFILES_DIR, `${digest}.json`);
7643
7881
  try {
7644
- if (canonicalAgentProfileDigest(JSON.parse(await readFile(file, "utf8"))) !== digest) throw new ValidationError(`profile-registry: revision ${digest.slice(0, 12)} is immutable but its stored copy differs — refusing to overwrite`);
7882
+ const existing = JSON.parse(await readFile(file, "utf8"));
7883
+ if (canonicalAgentProfileDigest(existing) !== digest) throw new ValidationError(`profile-registry: revision ${digest.slice(0, 12)} is immutable but its stored copy differs — refusing to overwrite`);
7645
7884
  } catch (error) {
7646
7885
  if (!isNoEntError(error)) throw error;
7647
7886
  writeAtomicDurableFile(file, JSON.stringify(profile));
@@ -7689,14 +7928,14 @@ async function bestProfileFor(reg, name) {
7689
7928
  record: best
7690
7929
  } : void 0;
7691
7930
  }
7692
- //#endregion
7693
- //#region src/runtime/supervise/remote-supervisor.ts
7931
+ // src/runtime/supervise/remote-supervisor.ts
7694
7932
  const agentSchema = z.object({
7695
7933
  id: z.string(),
7696
7934
  parent: z.string().optional(),
7697
7935
  label: z.string(),
7698
7936
  status: z.string(),
7699
- runtime: z.string()
7937
+ runtime: z.string(),
7938
+ failure: runtimeFailureCauseSchema.optional()
7700
7939
  }).passthrough();
7701
7940
  const treeSchema = z.object({
7702
7941
  root: z.string(),
@@ -7722,38 +7961,98 @@ const eventPageSchema = z.discriminatedUnion("status", [z.object({
7722
7961
  historyExpired: z.boolean(),
7723
7962
  remaining: z.number().int().nonnegative()
7724
7963
  })]);
7725
- /** Connect with the server's readOnly URL and protected headers; credentials never enter a profile. */
7726
- async function connectRemoteSupervisor(spec) {
7727
- const connection = await connectHttpMcp(spec);
7728
- if (!connection.tools.some((tool) => tool.name === "observe_agent")) {
7729
- await connection.close();
7730
- throw new ValidationError("remote supervisor does not expose observe_agent");
7731
- }
7732
- const call = async (args) => {
7733
- const text = await connection.callTool("observe_agent", args);
7734
- if (text.startsWith("ERROR:")) throw new ValidationError(text);
7735
- const result = z.record(z.string(), z.unknown()).parse(JSON.parse(text));
7964
+ const steerSchema = z.discriminatedUnion("delivered", [z.object({
7965
+ delivered: z.literal(true),
7966
+ progress: z.record(z.string(), z.unknown()).nullable()
7967
+ }), z.object({
7968
+ delivered: z.literal(false),
7969
+ outcome: z.custom((value) => typeof value === "string" && value !== "delivered" && Object.hasOwn(downMessageRefusalReasons, value)),
7970
+ reason: z.string(),
7971
+ progress: z.record(z.string(), z.unknown()).nullable()
7972
+ })]);
7973
+ const workerCounts = {
7974
+ live: z.number().int().nonnegative(),
7975
+ queued: z.number().int().nonnegative()
7976
+ };
7977
+ const cancelSchema = z.union([
7978
+ z.object({
7979
+ cancelled: z.literal(true),
7980
+ workerId: z.string(),
7981
+ label: z.string(),
7982
+ ...workerCounts
7983
+ }),
7984
+ z.object({
7985
+ released: z.literal(true),
7986
+ workerId: z.string(),
7987
+ ...workerCounts
7988
+ }),
7989
+ z.object({
7990
+ error: z.literal("not-live"),
7991
+ reason: z.string(),
7992
+ ...workerCounts
7993
+ })
7994
+ ]);
7995
+ async function callRemoteSupervisor(connection, tool, args) {
7996
+ const text = await connection.callTool(tool, args);
7997
+ if (text.startsWith("ERROR:")) throw new ValidationError(text);
7998
+ return z.record(z.string(), z.unknown()).parse(JSON.parse(text));
7999
+ }
8000
+ function supervisorReader(connection) {
8001
+ const observe = async (args) => {
8002
+ const result = await callRemoteSupervisor(connection, "observe_agent", args);
7736
8003
  if (result.error) throw new ValidationError(`remote supervisor refused observation: ${String(result.error)}`);
7737
8004
  return result;
7738
8005
  };
7739
8006
  return {
7740
- tree: async () => treeSchema.parse((await call({ tree: true })).tree),
8007
+ tree: async () => treeSchema.parse((await observe({ tree: true })).tree),
7741
8008
  observe: async (workerId, cursor) => {
7742
- const agent = await call({
8009
+ const agent = await observe({
7743
8010
  workerId,
7744
8011
  events: true,
7745
8012
  ...cursor ? { eventCursor: cursor } : {}
7746
8013
  });
7747
8014
  return {
7748
- agent,
8015
+ agent: agentSchema.parse(agent),
7749
8016
  events: eventPageSchema.parse(agent.events)
7750
8017
  };
7751
8018
  },
7752
8019
  close: () => connection.close()
7753
8020
  };
7754
8021
  }
7755
- //#endregion
7756
- //#region src/runtime/supervise/search-spec.ts
8022
+ /** Connect with the server's readOnly URL and protected headers; credentials never enter a profile. */
8023
+ async function connectRemoteSupervisor(spec) {
8024
+ const connection = await connectHttpMcp(spec);
8025
+ if (!connection.tools.some((tool) => tool.name === "observe_agent")) {
8026
+ await connection.close();
8027
+ throw new ValidationError("remote supervisor does not expose observe_agent");
8028
+ }
8029
+ return supervisorReader(connection);
8030
+ }
8031
+ /** Connect with the dedicated /control capability, keeping credentials on the protected transport. */
8032
+ async function connectRemoteSupervisorControl(access) {
8033
+ const connection = await connectHttpMcp({
8034
+ url: access.url,
8035
+ protectedHeaders: { ...access.headers }
8036
+ });
8037
+ const granted = new Set(connection.tools.map((tool) => tool.name));
8038
+ if (granted.size !== coordinationControlToolNames.length || !coordinationControlToolNames.every((tool) => granted.has(tool))) {
8039
+ await connection.close();
8040
+ throw new ValidationError("remote supervisor control requires the exact operator tool set");
8041
+ }
8042
+ return {
8043
+ ...supervisorReader(connection),
8044
+ steer: async (workerId, instruction, options = {}) => steerSchema.parse(await callRemoteSupervisor(connection, "steer_agent", {
8045
+ workerId,
8046
+ instruction,
8047
+ ...options.interrupt === void 0 ? {} : { interrupt: options.interrupt }
8048
+ })),
8049
+ cancel: async (workerId, reason) => cancelSchema.parse(await callRemoteSupervisor(connection, "cancel_worker", {
8050
+ workerId,
8051
+ ...reason === void 0 ? {} : { reason }
8052
+ }))
8053
+ };
8054
+ }
8055
+ // src/runtime/supervise/search-spec.ts
7757
8056
  /**
7758
8057
  * SearchSpec: one data value for a multi-agent research configuration, and the compiler that maps
7759
8058
  * it onto exactly one existing call, `supervise(profile, task, options)` or `runGraph(graph,
@@ -7773,32 +8072,32 @@ async function connectRemoteSupervisor(spec) {
7773
8072
  * caller that supplies it is refused. */
7774
8073
  const SEARCH_SPEC_CORRELATION_KEY = "searchSpecDigest";
7775
8074
  const SPAWN_GRANT = `${coordinationProfileToolPrefix}spawn_worker`;
7776
- function refuse(message) {
8075
+ function refuse$1(message) {
7777
8076
  throw new ValidationError(`SearchSpec: ${message}`);
7778
8077
  }
7779
8078
  const quoted = (values) => values.map((v) => `'${v}'`).join(", ");
7780
8079
  function record(value, where, required, optional = []) {
7781
- if (typeof value !== "object" || value === null || Array.isArray(value)) refuse(`${where} must be an object`);
8080
+ if (typeof value !== "object" || value === null || Array.isArray(value)) refuse$1(`${where} must be an object`);
7782
8081
  const fields = value;
7783
8082
  const known = /* @__PURE__ */ new Set([...required, ...optional]);
7784
8083
  const unknown = Object.keys(fields).filter((key) => !known.has(key));
7785
- if (unknown.length > 0) refuse(`${where} has unknown ${unknown.length === 1 ? "key" : "keys"} ${quoted(unknown)}; it takes ${quoted([...required, ...optional])}`);
8084
+ if (unknown.length > 0) refuse$1(`${where} has unknown ${unknown.length === 1 ? "key" : "keys"} ${quoted(unknown)}; it takes ${quoted([...required, ...optional])}`);
7786
8085
  const missing = required.filter((key) => fields[key] === void 0);
7787
- if (missing.length > 0) refuse(`${where} is missing ${quoted(missing)}`);
8086
+ if (missing.length > 0) refuse$1(`${where} is missing ${quoted(missing)}`);
7788
8087
  return fields;
7789
8088
  }
7790
8089
  function oneOf(value, where, values) {
7791
8090
  if (typeof value === "string" && values.includes(value)) return value;
7792
- return refuse(`${where} is ${JSON.stringify(value)}; it must be one of ${quoted(values)}`);
8091
+ return refuse$1(`${where} is ${JSON.stringify(value)}; it must be one of ${quoted(values)}`);
7793
8092
  }
7794
8093
  function names(value, where) {
7795
- if (!Array.isArray(value) || value.length === 0 || !value.every((item) => typeof item === "string" && item.trim() !== "")) refuse(`${where} must be a non-empty list of non-empty strings`);
8094
+ if (!Array.isArray(value) || value.length === 0 || !value.every((item) => typeof item === "string" && item.trim() !== "")) refuse$1(`${where} must be a non-empty list of non-empty strings`);
7796
8095
  const list = value;
7797
- if (new Set(list).size !== list.length) refuse(`${where} lists a name twice`);
8096
+ if (new Set(list).size !== list.length) refuse$1(`${where} lists a name twice`);
7798
8097
  return Object.freeze([...list].sort());
7799
8098
  }
7800
8099
  function integer(value, where, min) {
7801
- if (!Number.isSafeInteger(value) || value < min) refuse(`${where} must be an integer >= ${min}`);
8100
+ if (!Number.isSafeInteger(value) || value < min) refuse$1(`${where} must be an integer >= ${min}`);
7802
8101
  return value;
7803
8102
  }
7804
8103
  /**
@@ -7815,13 +8114,13 @@ function assertSearchSpec(spec) {
7815
8114
  "evaluate",
7816
8115
  "stop"
7817
8116
  ];
7818
- if (typeof spec !== "object" || spec === null || Array.isArray(spec)) refuse("a spec must be an object with the axes state, context, select, workers, comms, evaluate and stop");
8117
+ if (typeof spec !== "object" || spec === null || Array.isArray(spec)) refuse$1("a spec must be an object with the axes state, context, select, workers, comms, evaluate and stop");
7819
8118
  const top = spec;
7820
8119
  const unknownAxes = Object.keys(top).filter((key) => !axes.includes(key));
7821
- if (unknownAxes.length > 0) refuse(`unknown axis ${quoted(unknownAxes)}; the axes are ${quoted(axes)}`);
8120
+ if (unknownAxes.length > 0) refuse$1(`unknown axis ${quoted(unknownAxes)}; the axes are ${quoted(axes)}`);
7822
8121
  const missingAxes = axes.filter((axis) => top[axis] === void 0);
7823
- if (missingAxes.length > 0) refuse(`axis ${quoted(missingAxes)} is missing`);
7824
- if (top.state === "conversation") refuse("state 'conversation' is not a value: research memory that lives only in a harness conversation cannot be checkpointed, inspected or ablated; it is always harness");
8122
+ if (missingAxes.length > 0) refuse$1(`axis ${quoted(missingAxes)} is missing`);
8123
+ if (top.state === "conversation") refuse$1("state 'conversation' is not a value: research memory that lives only in a harness conversation cannot be checkpointed, inspected or ablated; it is always harness");
7825
8124
  const state = oneOf(top.state, "state", ["harness"]);
7826
8125
  const context = oneOf(top.context, "context", ["fresh", "native"]);
7827
8126
  const select = oneOf(top.select, "select", [
@@ -7850,21 +8149,21 @@ function assertSearchSpec(spec) {
7850
8149
  if (stopIn.plateau !== void 0) {
7851
8150
  const plateauIn = record(stopIn.plateau, "stop.plateau", ["window", "minDelta"]);
7852
8151
  const minDelta = plateauIn.minDelta;
7853
- if (typeof minDelta !== "number" || !Number.isFinite(minDelta) || minDelta < 0) refuse("stop.plateau.minDelta must be a finite number >= 0");
8152
+ if (typeof minDelta !== "number" || !Number.isFinite(minDelta) || minDelta < 0) refuse$1("stop.plateau.minDelta must be a finite number >= 0");
7854
8153
  plateau = Object.freeze({
7855
8154
  window: integer(plateauIn.window, "stop.plateau.window", 1),
7856
8155
  minDelta
7857
8156
  });
7858
8157
  }
7859
- if (select === "advisor" && context === "native") refuse("select 'advisor' sees each epoch only through the coordinator's projection, so it needs context 'fresh'; with 'native' its earlier turns would stay in its context");
7860
- if (select === "code" && context === "fresh") refuse("select 'code' runs the root in your brain, in process; it has no harness session for context 'fresh' to renew");
7861
- if (select === "advisor" && count === 0) refuse("select 'advisor' only assigns work, so workers.count must be at least 1");
7862
- if (count === 0 && comms !== "none") refuse(`workers.count 0 runs the root alone, so comms must be 'none', not '${comms}'`);
7863
- if (count > 0 && comms === "none") refuse(`comms 'none' leaves ${count} worker(s) with no channel; use 'assignments' or 'messages'`);
7864
- if (comms === "messages" && count < 2) refuse(`comms 'messages' needs at least two peers to message each other; workers.count is ${count}`);
7865
- if (select === "self" && comms !== "messages") refuse("select 'self' lets the peers divide the work by messages, so comms must be 'messages'; use select 'fixed' for independent attempts");
7866
- if (count === 0 && isolation === "shared") refuse("workers.isolation 'shared' places workers in shared boxes, and workers.count is 0");
7867
- if (count === 0 && models !== void 0) refuse("workers.models lists the models workers may use, and workers.count is 0");
8158
+ if (select === "advisor" && context === "native") refuse$1("select 'advisor' sees each epoch only through the coordinator's projection, so it needs context 'fresh'; with 'native' its earlier turns would stay in its context");
8159
+ if (select === "code" && context === "fresh") refuse$1("select 'code' runs the root in your brain, in process; it has no harness session for context 'fresh' to renew");
8160
+ if (select === "advisor" && count === 0) refuse$1("select 'advisor' only assigns work, so workers.count must be at least 1");
8161
+ if (count === 0 && comms !== "none") refuse$1(`workers.count 0 runs the root alone, so comms must be 'none', not '${comms}'`);
8162
+ if (count > 0 && comms === "none") refuse$1(`comms 'none' leaves ${count} worker(s) with no channel; use 'assignments' or 'messages'`);
8163
+ if (comms === "messages" && count < 2) refuse$1(`comms 'messages' needs at least two peers to message each other; workers.count is ${count}`);
8164
+ if (select === "self" && comms !== "messages") refuse$1("select 'self' lets the peers divide the work by messages, so comms must be 'messages'; use select 'fixed' for independent attempts");
8165
+ if (count === 0 && isolation === "shared") refuse$1("workers.isolation 'shared' places workers in shared boxes, and workers.count is 0");
8166
+ if (count === 0 && models !== void 0) refuse$1("workers.models lists the models workers may use, and workers.count is 0");
7868
8167
  return Object.freeze({
7869
8168
  state,
7870
8169
  context,
@@ -7993,8 +8292,8 @@ function profileTable(entries) {
7993
8292
  for (const item of entries) {
7994
8293
  const entry = "profile" in item ? item : { profile: item };
7995
8294
  const name = entry.profile.name;
7996
- if (typeof name !== "string" || name.trim() === "") refuse("every profile in inputs.workers needs a name, which the root spawns it by");
7997
- if (table.has(name)) refuse(`inputs.workers names profile '${name}' twice`);
8295
+ if (typeof name !== "string" || name.trim() === "") refuse$1("every profile in inputs.workers needs a name, which the root spawns it by");
8296
+ if (table.has(name)) refuse$1(`inputs.workers names profile '${name}' twice`);
7998
8297
  table.set(name, entry);
7999
8298
  }
8000
8299
  const listed = Object.freeze([...table.keys()]);
@@ -8008,12 +8307,12 @@ function placedBackend(spec, inputs) {
8008
8307
  const backend = inputs.options?.backend;
8009
8308
  const sharedAlready = backend?.backend === "provider" && backend.shared !== void 0;
8010
8309
  if (spec.workers.isolation === "isolated") {
8011
- if (inputs.sharedPlacement !== void 0 || sharedAlready) refuse("workers.isolation 'isolated' gives every worker its own environment; drop the shared placement or use isolation 'shared'");
8310
+ if (inputs.sharedPlacement !== void 0 || sharedAlready) refuse$1("workers.isolation 'isolated' gives every worker its own environment; drop the shared placement or use isolation 'shared'");
8012
8311
  return backend;
8013
8312
  }
8014
8313
  if (inputs.sharedPlacement === void 0) return backend;
8015
- if (backend?.backend !== "provider") refuse(`inputs.sharedPlacement places workers through a 'provider' backend; options.backend is ${backend === void 0 ? "absent" : `'${backend.backend}'`}`);
8016
- if (sharedAlready) refuse("options.backend already carries a shared placement; pass it once");
8314
+ if (backend?.backend !== "provider") refuse$1(`inputs.sharedPlacement places workers through a 'provider' backend; options.backend is ${backend === void 0 ? "absent" : `'${backend.backend}'`}`);
8315
+ if (sharedAlready) refuse$1("options.backend already carries a shared placement; pass it once");
8017
8316
  return Object.freeze({
8018
8317
  ...backend,
8019
8318
  shared: inputs.sharedPlacement
@@ -8042,10 +8341,10 @@ function compileSearchSpec(raw, inputs) {
8042
8341
  const spec = assertSearchSpec(raw);
8043
8342
  const digest = searchSpecDigest(spec);
8044
8343
  const passed = inputs.options ?? {};
8045
- for (const [key, axis] of Object.entries(ownedBy)) if (passed[key] !== void 0) refuse(`options.${key} is decided by ${axis}; change the spec or that input instead`);
8046
- if (inputs.deliverable === void 0) refuse("inputs.deliverable is required: a spec run is sent back by its check");
8344
+ for (const [key, axis] of Object.entries(ownedBy)) if (passed[key] !== void 0) refuse$1(`options.${key} is decided by ${axis}; change the spec or that input instead`);
8345
+ if (inputs.deliverable === void 0) refuse$1("inputs.deliverable is required: a spec run is sent back by its check");
8047
8346
  const correlation = passed.execution?.correlation ?? {};
8048
- if (Object.hasOwn(correlation, "searchSpecDigest")) refuse(`options.execution.correlation cannot set ${SEARCH_SPEC_CORRELATION_KEY}; Runtime records it`);
8347
+ if (Object.hasOwn(correlation, "searchSpecDigest")) refuse$1(`options.execution.correlation cannot set ${SEARCH_SPEC_CORRELATION_KEY}; Runtime records it`);
8049
8348
  const execution = Object.freeze({
8050
8349
  ...passed.execution,
8051
8350
  correlation: Object.freeze({
@@ -8066,9 +8365,9 @@ function compileSearchSpec(raw, inputs) {
8066
8365
  };
8067
8366
  const backend = placedBackend(spec, inputs);
8068
8367
  const callerOwnsLeaves = passed.makeLeafAgent !== void 0 || passed.makeWorkerAgent !== void 0;
8069
- if (spec.comms === "messages" && backend !== void 0 && backend.backend !== "bridge" && backend.backend !== "provider" && !callerOwnsLeaves) refuse(`comms 'messages' needs workers that can call peer mail: Runtime mounts it on 'bridge' or capable 'provider' workers, and '${backend.backend}' workers run no client for it. Run the workers on a bridge, or mount WorkerSpawnContext.peerMailUrl through makeLeafAgent`);
8368
+ if (spec.comms === "messages" && backend !== void 0 && backend.backend !== "bridge" && backend.backend !== "provider" && !callerOwnsLeaves) refuse$1(`comms 'messages' needs workers that can call peer mail: Runtime mounts it on 'bridge' or capable 'provider' workers, and '${backend.backend}' workers run no client for it. Run the workers on a bridge, or mount WorkerSpawnContext.peerMailUrl through makeLeafAgent`);
8070
8369
  const analystKinds = spec.evaluate.analysts ?? [];
8071
- if (analystKinds.length > 0 && inputs.analysts === void 0) refuse("evaluate.analysts names analyst kinds, and inputs.analysts holds no registry to run them");
8370
+ if (analystKinds.length > 0 && inputs.analysts === void 0) refuse$1("evaluate.analysts names analyst kinds, and inputs.analysts holds no registry to run them");
8072
8371
  const axisOptions = {
8073
8372
  continuation,
8074
8373
  execution,
@@ -8079,15 +8378,15 @@ function compileSearchSpec(raw, inputs) {
8079
8378
  ...backend === void 0 ? {} : { backend }
8080
8379
  };
8081
8380
  if (spec.select === "code" || spec.select === "fixed") {
8082
- const graph = inputs.graph ?? refuse(`select '${spec.select}' needs inputs.graph`);
8083
- if (inputs.profile !== void 0 || inputs.task !== void 0) refuse(`select '${spec.select}' runs inputs.graph, whose root is its own node and whose task is the deliverable's description; drop inputs.profile and inputs.task`);
8084
- if (inputs.workers !== void 0) refuse(`select '${spec.select}' spawns the graph's nodes; drop inputs.workers`);
8085
- if (analystKinds.length > 0) refuse(`select '${spec.select}' declares a graph's analysts as analyzes edges, not evaluate.analysts`);
8086
- if (spec.workers.count === 0) refuse(`select '${spec.select}' runs a graph's worker nodes, so workers.count must be at least 1`);
8087
- if (spec.select === "code" && inputs.brain === void 0) refuse("select 'code' needs inputs.brain, the caller's brain that drives the root");
8088
- if (spec.select === "fixed" && inputs.brain !== void 0) refuse("select 'fixed' runs the graph's root profile; a brain is select 'code'");
8089
- if (passed.registry !== void 0) refuse("options.registry is supervise's name table, which a graph cannot read; pass the graph's directive registry as inputs.directives");
8090
- if (spec.context === "fresh" && !harnessRunsAgent(graphRoot(graph)?.harness)) refuse("context 'fresh' renews an external harness root's session at each re-entry, and the graph's root runs on the router brain");
8381
+ const graph = inputs.graph ?? refuse$1(`select '${spec.select}' needs inputs.graph`);
8382
+ if (inputs.profile !== void 0 || inputs.task !== void 0) refuse$1(`select '${spec.select}' runs inputs.graph, whose root is its own node and whose task is the deliverable's description; drop inputs.profile and inputs.task`);
8383
+ if (inputs.workers !== void 0) refuse$1(`select '${spec.select}' spawns the graph's nodes; drop inputs.workers`);
8384
+ if (analystKinds.length > 0) refuse$1(`select '${spec.select}' declares a graph's analysts as analyzes edges, not evaluate.analysts`);
8385
+ if (spec.workers.count === 0) refuse$1(`select '${spec.select}' runs a graph's worker nodes, so workers.count must be at least 1`);
8386
+ if (spec.select === "code" && inputs.brain === void 0) refuse$1("select 'code' needs inputs.brain, the caller's brain that drives the root");
8387
+ if (spec.select === "fixed" && inputs.brain !== void 0) refuse$1("select 'fixed' runs the graph's root profile; a brain is select 'code'");
8388
+ if (passed.registry !== void 0) refuse$1("options.registry is supervise's name table, which a graph cannot read; pass the graph's directive registry as inputs.directives");
8389
+ if (spec.context === "fresh" && !harnessRunsAgent(graphRoot(graph)?.harness)) refuse$1("context 'fresh' renews an external harness root's session at each re-entry, and the graph's root runs on the router brain");
8091
8390
  return Object.freeze({
8092
8391
  call: "runGraph",
8093
8392
  spec,
@@ -8107,14 +8406,14 @@ function compileSearchSpec(raw, inputs) {
8107
8406
  })
8108
8407
  });
8109
8408
  }
8110
- const profile = inputs.profile ?? refuse(`select '${spec.select}' needs inputs.profile, the root`);
8111
- if (inputs.task === void 0) refuse(`select '${spec.select}' needs inputs.task`);
8112
- if (inputs.graph !== void 0 || inputs.brain !== void 0 || inputs.directives !== void 0) refuse(`select '${spec.select}' runs inputs.profile; a graph, brain or directives is select 'code' or 'fixed'`);
8113
- if (!harnessRunsAgent(profile.harness)) refuse(`select '${spec.select}' runs the root under Runtime's continuation (context, evaluate and stop), which drives an external harness; profile '${profile.name}' runs on the router brain. Give it a harness such as claude-code or codex, or use select 'code'`);
8114
- if (spec.workers.count === 0 && grantsSpawn(profile)) refuse(`workers.count 0 runs the root alone, but profile '${profile.name}' grants ${SPAWN_GRANT}`);
8115
- if (spec.workers.count > 0 && !grantsSpawn(profile)) refuse(`workers.count ${spec.workers.count} needs a root that spawns, and profile '${profile.name}' does not grant ${SPAWN_GRANT}`);
8116
- if (spec.select === "self" && inputs.workers?.length !== spec.workers.count) refuse(`select 'self' starts exactly workers.count peers; inputs.workers holds ${inputs.workers?.length ?? 0}, and workers.count is ${spec.workers.count}`);
8117
- if (inputs.workers !== void 0 && passed.registry?.profiles !== void 0) refuse("inputs.workers and options.registry.profiles both name spawnable profiles; pass them once");
8409
+ const profile = inputs.profile ?? refuse$1(`select '${spec.select}' needs inputs.profile, the root`);
8410
+ if (inputs.task === void 0) refuse$1(`select '${spec.select}' needs inputs.task`);
8411
+ if (inputs.graph !== void 0 || inputs.brain !== void 0 || inputs.directives !== void 0) refuse$1(`select '${spec.select}' runs inputs.profile; a graph, brain or directives is select 'code' or 'fixed'`);
8412
+ if (!harnessRunsAgent(profile.harness)) refuse$1(`select '${spec.select}' runs the root under Runtime's continuation (context, evaluate and stop), which drives an external harness; profile '${profile.name}' runs on the router brain. Give it a harness such as claude-code or codex, or use select 'code'`);
8413
+ if (spec.workers.count === 0 && grantsSpawn(profile)) refuse$1(`workers.count 0 runs the root alone, but profile '${profile.name}' grants ${SPAWN_GRANT}`);
8414
+ if (spec.workers.count > 0 && !grantsSpawn(profile)) refuse$1(`workers.count ${spec.workers.count} needs a root that spawns, and profile '${profile.name}' does not grant ${SPAWN_GRANT}`);
8415
+ if (spec.select === "self" && inputs.workers?.length !== spec.workers.count) refuse$1(`select 'self' starts exactly workers.count peers; inputs.workers holds ${inputs.workers?.length ?? 0}, and workers.count is ${spec.workers.count}`);
8416
+ if (inputs.workers !== void 0 && passed.registry?.profiles !== void 0) refuse$1("inputs.workers and options.registry.profiles both name spawnable profiles; pass them once");
8118
8417
  const registry = inputs.workers === void 0 ? passed.registry : Object.freeze({
8119
8418
  ...passed.registry,
8120
8419
  profiles: profileTable(inputs.workers)
@@ -8140,8 +8439,7 @@ function compileSearchSpec(raw, inputs) {
8140
8439
  })
8141
8440
  });
8142
8441
  }
8143
- //#endregion
8144
- //#region src/runtime/supervise/sql-run-context.ts
8442
+ // src/runtime/supervise/sql-run-context.ts
8145
8443
  /**
8146
8444
  * A cross-machine run context on the existing autocommit SqlAdapter. Reuse the same database,
8147
8445
  * tablePrefix and runId on every host; no runDir or shared filesystem is required.
@@ -8314,8 +8612,158 @@ async function projection(entries) {
8314
8612
  }
8315
8613
  };
8316
8614
  }
8317
- //#endregion
8318
- //#region src/runtime/supervise/trajectory-recorder.ts
8615
+ // src/runtime/supervise/stored-graph-validation.ts
8616
+ const name = z.string().min(1);
8617
+ const positiveInteger = z.number().int().positive();
8618
+ const directive = z.strictObject({
8619
+ surface: name,
8620
+ version: z.number().int().nonnegative()
8621
+ });
8622
+ const node = z.strictObject({
8623
+ id: name,
8624
+ profile: agentProfileSchema
8625
+ });
8626
+ const entry = z.array(z.strictObject({
8627
+ node: name,
8628
+ task: z.unknown().refine((value) => value !== void 0, "task must be explicit JSON data")
8629
+ })).min(1);
8630
+ const gates = z.array(z.strictObject({
8631
+ id: name,
8632
+ question: name,
8633
+ choices: z.array(name).min(1)
8634
+ }));
8635
+ const continuity = z.enum(["fresh", "resume"]).optional();
8636
+ const topology = z.lazy(() => z.strictObject({
8637
+ nodes: z.array(node).min(1),
8638
+ edges: z.array(edge),
8639
+ entry: entry.optional(),
8640
+ gates: gates.optional()
8641
+ }));
8642
+ const edge = z.lazy(() => z.discriminatedUnion("kind", [
8643
+ z.strictObject({
8644
+ kind: z.literal("delegates"),
8645
+ from: name,
8646
+ to: name,
8647
+ directive,
8648
+ maxTraversals: positiveInteger.optional(),
8649
+ continuity
8650
+ }),
8651
+ z.strictObject({
8652
+ kind: z.literal("analyzes"),
8653
+ analyst: name,
8654
+ over: z.array(name).min(1),
8655
+ to: name,
8656
+ directive,
8657
+ maxTraversals: positiveInteger.optional()
8658
+ }),
8659
+ z.strictObject({
8660
+ kind: z.literal("maps"),
8661
+ from: name,
8662
+ pointer: z.string(),
8663
+ to: name.optional(),
8664
+ graph: topology.optional(),
8665
+ join: name,
8666
+ directive,
8667
+ maxItems: positiveInteger,
8668
+ concurrency: positiveInteger,
8669
+ onItemFailure: z.enum(["all-or-refuse", "settled-subset"]),
8670
+ itemBudget: graphFileSchema.shape.budget.partial().optional()
8671
+ }),
8672
+ z.strictObject({
8673
+ kind: z.literal("routes"),
8674
+ from: z.union([name, z.array(name).min(2)]),
8675
+ to: z.union([
8676
+ name,
8677
+ z.array(name).min(2),
8678
+ z.strictObject({ stop: name }),
8679
+ z.strictObject({ finish: name })
8680
+ ]),
8681
+ directive,
8682
+ when: graphRouteWhenSchema.optional(),
8683
+ evidence: z.array(name).optional(),
8684
+ maxTraversals: positiveInteger.optional(),
8685
+ continuity
8686
+ })
8687
+ ]));
8688
+ const storedGraphSchema = graphFileSchema.pick({
8689
+ digest: true,
8690
+ budget: true,
8691
+ deliverable: true
8692
+ }).required().extend({
8693
+ observed: z.literal(false).optional(),
8694
+ triggerBindings: graphTriggerBindingsSchema.optional(),
8695
+ nodes: z.array(node).min(1),
8696
+ edges: z.array(edge),
8697
+ entry: entry.optional(),
8698
+ gates: gates.optional()
8699
+ });
8700
+ function refuse(message) {
8701
+ throw new ValidationError(`validateStoredGraph: ${message}`);
8702
+ }
8703
+ /** Inspect descriptors instead of invoking accessors; JSON has no getters, symbols, prototypes,
8704
+ * sparse arrays, undefined, closures or cycles. Repeated non-cyclic references remain JSON data. */
8705
+ function assertJsonData(value, visiting = /* @__PURE__ */ new Set()) {
8706
+ if (value === null || typeof value === "string" || typeof value === "boolean") return;
8707
+ if (typeof value === "number" && Number.isFinite(value)) return;
8708
+ if (!value || typeof value !== "object" || visiting.has(value)) refuse("expected finite, acyclic JSON data without executable values");
8709
+ const array = Array.isArray(value);
8710
+ const prototype = Object.getPrototypeOf(value);
8711
+ if (array ? prototype !== Array.prototype : prototype !== Object.prototype && prototype !== null) refuse("expected plain JSON objects and arrays");
8712
+ visiting.add(value);
8713
+ const descriptors = Object.getOwnPropertyDescriptors(value);
8714
+ const keys = Reflect.ownKeys(descriptors);
8715
+ if (array && keys.length !== value.length + 1) refuse("sparse arrays are not canonical JSON");
8716
+ for (const key of keys) {
8717
+ if (array && key === "length") continue;
8718
+ const property = typeof key === "string" ? descriptors[key] : void 0;
8719
+ if (!property || !property.enumerable || !("value" in property)) refuse("JSON data cannot contain symbols, hidden properties or accessors");
8720
+ if (array && (!/^(0|[1-9]\d*)$/.test(key) || Number(key) >= value.length)) refuse("arrays may contain only indexed JSON values");
8721
+ assertJsonData(property.value, visiting);
8722
+ }
8723
+ visiting.delete(value);
8724
+ }
8725
+ function assertExecutableNodes(graph) {
8726
+ for (const item of graph.nodes) assertExecutableAgentProfile(item.profile, `validateStoredGraph node ${item.id}`);
8727
+ for (const item of graph.edges) if (item.kind === "maps" && item.graph) assertExecutableNodes(item.graph);
8728
+ }
8729
+ /** Validate compiled, runnable StoredGraph data. Authored params/seats/on envelopes belong to
8730
+ * loadGraphFile; observations belong to the registry's observation importer, never this entry.
8731
+ * No check function or model call is executed while validating environment-owned references. */
8732
+ function validateStoredGraph(value, options = {}) {
8733
+ assertJsonData(value);
8734
+ const parsed = storedGraphSchema.safeParse(value);
8735
+ if (!parsed.success) refuse(parsed.error.message);
8736
+ const graph = parsed.data;
8737
+ if (graph.triggerBindings !== void 0) assertGraphTriggerBindings(graph, graph.triggerBindings);
8738
+ const check = graph.deliverable;
8739
+ if (check.checkRef === "command") {
8740
+ if (!check.command?.command.trim() || check.when) refuse("command check requires only command data");
8741
+ } else if (check.checkRef === "route") {
8742
+ if (!check.when || check.command) refuse("route check requires only when data");
8743
+ } else {
8744
+ if (check.command || check.when) refuse("custom checkRef cannot carry builtin command/route data");
8745
+ const selected = options.checks && Object.hasOwn(options.checks, check.checkRef) ? options.checks[check.checkRef] : void 0;
8746
+ if (selected === void 0) refuse(`unknown checkRef ${check.checkRef}; supply an environment checks binding`);
8747
+ if (typeof selected !== "function") {
8748
+ const command = graphFileSchema.shape.deliverable.unwrap().shape.command.unwrap().safeParse(selected);
8749
+ if (!command.success || !command.data.command.trim()) refuse(`invalid checks binding ${check.checkRef}`);
8750
+ }
8751
+ }
8752
+ if (check.when) {
8753
+ const ids = new Set(graph.nodes.map((item) => item.id));
8754
+ for (const condition of "all" in check.when ? check.when.all : [check.when]) if (condition.node !== void 0 && !ids.has(condition.node)) refuse(`check references unknown node ${condition.node}`);
8755
+ }
8756
+ assertExecutableNodes(graph);
8757
+ const registry = options.registry ?? kernelPromptRegistry();
8758
+ if (graph.entry) validateFlowGraph(graph, registry, options.analysts);
8759
+ else validateGraphTopology(graph.nodes, graph.edges, registry, options.analysts);
8760
+ const { digest: provided, ...rawContent } = value;
8761
+ if (graphDigest(rawContent) !== provided) refuse("supplied digest does not match the input graph");
8762
+ const { digest, ...content } = graph;
8763
+ if (graphDigest(content) !== digest) refuse("supplied digest does not match the canonical graph");
8764
+ return detachedSnapshot(graph, "validated stored graph");
8765
+ }
8766
+ // src/runtime/supervise/trajectory-recorder.ts
8319
8767
  /**
8320
8768
  *
8321
8769
  * The SETTLE-time analyst: when a worker finishes, collect its tool spans from a `TraceSource` and run
@@ -8376,8 +8824,7 @@ async function analyzeTrace(source, runId = "worker") {
8376
8824
  toolWaste
8377
8825
  };
8378
8826
  }
8379
- //#endregion
8380
- //#region src/runtime/supervise/untracked-clone.ts
8827
+ // src/runtime/supervise/untracked-clone.ts
8381
8828
  /**
8382
8829
  * Worker-clone preparation: make each worker's fresh clone a FAITHFUL copy of the
8383
8830
  * shared workspace's working tree, not just of its git history.
@@ -8420,7 +8867,7 @@ const SKIPPED_TOP_LEVEL = /* @__PURE__ */ new Set([
8420
8867
  ".claude"
8421
8868
  ]);
8422
8869
  /** Warn (and copy anyway) past this untracked payload size. */
8423
- const DEFAULT_WARN_BYTES = 2 * 1024 * 1024 * 1024;
8870
+ const DEFAULT_WARN_BYTES = 2147483648;
8424
8871
  /**
8425
8872
  * Copy every untracked file of `sourceDir`'s working tree — including git-ignored
8426
8873
  * build outputs (`git ls-files --others` with NO exclude flags lists both) — into
@@ -8441,7 +8888,7 @@ function copyUntrackedIntoClone(sourceDir, cloneDir, opts = {}) {
8441
8888
  "-z"
8442
8889
  ], {
8443
8890
  encoding: "utf8",
8444
- maxBuffer: 256 * 1024 * 1024
8891
+ maxBuffer: 268435456
8445
8892
  });
8446
8893
  if (ls.status !== 0) throw new Error(`git ls-files --others failed in ${src}: ${(ls.stderr ?? "").trim() || `exit ${ls.status}`}`);
8447
8894
  const plan = [];
@@ -8527,8 +8974,7 @@ function withUntrackedArtifacts(ws, sourceDir, log) {
8527
8974
  head: () => ws.head()
8528
8975
  };
8529
8976
  }
8530
- //#endregion
8531
- //#region src/runtime/supervise/worker-evidence.ts
8977
+ // src/runtime/supervise/worker-evidence.ts
8532
8978
  /**
8533
8979
  * Evidence-rich worker settlement.
8534
8980
  *
@@ -8603,8 +9049,7 @@ function diffSummary(patch) {
8603
9049
  const omitted = lines.length - head.length;
8604
9050
  return `${`--- diff: ${filesChanged} file(s) changed, ${Buffer.byteLength(patch)} bytes; first ${head.length} line(s) ---`}\n${head.join("\n")}${omitted > 0 ? `\n... (${omitted} more patch lines; full patch persisted per worker)` : ""}`;
8605
9051
  }
8606
- //#endregion
8607
- //#region src/runtime/supervise/patch-checks.ts
9052
+ // src/runtime/supervise/patch-checks.ts
8608
9053
  const DEFAULT_MAX_DIFF_LINES = 400;
8609
9054
  /**
8610
9055
  * Default-on credential-path floor: a patch that touches a credential-shaped path is rejected
@@ -8696,8 +9141,7 @@ function runCoderChecks(input, constraints = {}) {
8696
9141
  if (notes.length > 0) verdict.notes = notes.join("; ");
8697
9142
  return verdict;
8698
9143
  }
8699
- //#endregion
8700
- //#region src/runtime/supervise/patch-deliverable.ts
9144
+ // src/runtime/supervise/patch-deliverable.ts
8701
9145
  /**
8702
9146
  * Build the `DeliverableSpec<WorktreePatchArtifact>`: `check(artifact)` runs the shared mechanical
8703
9147
  * gate (`runCoderChecks`) over the captured patch + the worktree-derived pass signals and returns
@@ -8732,8 +9176,7 @@ function signalPass(value, required) {
8732
9176
  if (value !== void 0) return value;
8733
9177
  return !required;
8734
9178
  }
8735
- //#endregion
8736
- //#region src/runtime/supervise/worktree-fanout.ts
9179
+ // src/runtime/supervise/worktree-fanout.ts
8737
9180
  /**
8738
9181
  * Build the worktree fanout combinator. Run it with `runPersonified({ persona, shape, task, budget })`
8739
9182
  * — equal-k holds by construction (the conserved budget pool bounds the N leaves), and selection is
@@ -8785,8 +9228,7 @@ function worktreeFanout(options) {
8785
9228
  selectWinner
8786
9229
  });
8787
9230
  }
8788
- //#endregion
8789
- //#region src/runtime/supervise-analysts.ts
9231
+ // src/runtime/supervise-analysts.ts
8790
9232
  /**
8791
9233
  * Analyst lenses a supervised manager reads: the agent-eval trace-analyst registry adapted to the
8792
9234
  * `analysts` option (`analystsFromRegistry`), and `failuresAnalyst`, which reports the tests still
@@ -8973,8 +9415,7 @@ function allTestsPassed(report) {
8973
9415
  function missingRunTestsEvidence() {
8974
9416
  return { summary: "Missing structured run_tests span evidence. Refusing to infer failing-test names from worker prose." };
8975
9417
  }
8976
- //#endregion
8977
- //#region src/runtime/surface-diff.ts
9418
+ // src/runtime/surface-diff.ts
8978
9419
  /**
8979
9420
  *
8980
9421
  * Settle-time surface-diff harvest — the read-back dual of the mount manifest.
@@ -9171,8 +9612,7 @@ function fsSurfaceReader(root) {
9171
9612
  }
9172
9613
  };
9173
9614
  }
9174
- //#endregion
9175
- //#region src/runtime/verifier-environment.ts
9615
+ // src/runtime/verifier-environment.ts
9176
9616
  const submitTool = {
9177
9617
  type: "function",
9178
9618
  function: {
@@ -9250,8 +9690,7 @@ function createVerifierEnvironment(opts) {
9250
9690
  }
9251
9691
  };
9252
9692
  }
9253
- //#endregion
9254
- //#region src/runtime/waterfall.ts
9693
+ // src/runtime/waterfall.ts
9255
9694
  /** Build a `WaterfallCollector` that records agent spans and renders them as an ASCII timeline. */
9256
9695
  function createWaterfallCollector() {
9257
9696
  let spans = /* @__PURE__ */ new Map();
@@ -9370,8 +9809,7 @@ function createWaterfallCollector() {
9370
9809
  }
9371
9810
  };
9372
9811
  }
9373
- //#endregion
9374
- //#region src/runtime/workspace.ts
9812
+ // src/runtime/workspace.ts
9375
9813
  /** Host-process `Shell`: run a command via `execFile`, resolving `{ stdout, stderr, code }` (never throws on non-zero exit). */
9376
9814
  function localShell() {
9377
9815
  return async (args, cwd) => {
@@ -9381,7 +9819,7 @@ function localShell() {
9381
9819
  execFile(bin ?? "", rest, {
9382
9820
  cwd,
9383
9821
  encoding: "utf-8",
9384
- maxBuffer: 64 * 1024 * 1024
9822
+ maxBuffer: 67108864
9385
9823
  }, (err, stdout, stderr) => {
9386
9824
  resolve({
9387
9825
  stdout: stdout ?? "",
@@ -9590,7 +10028,6 @@ async function runInWorkspace(ws, body, opts = {}) {
9590
10028
  function tail(s) {
9591
10029
  return s.slice(-400);
9592
10030
  }
9593
- //#endregion
9594
- export { definePersona as $, SqlRunOwnershipError as $t, searchSpecDigest as A, resolveSecretEnv as At, chatTransportExecutor as B, declaredCheckJudge as Bt, withUntrackedArtifacts as C, connectStdioMcp as Ct, assertSearchSpec as D, envKeyProvider as Dt, SEARCH_SPEC_CORRELATION_KEY as E, sanitizeMcpToolSchema as Et, profileRegistry as F, superviseDispatch as Ft, SandboxRunAbortError as G, sentinelCompletion as Gt, createChatSessionStore as H, runIsolatedCheck as Ht, profileRunsForName as I, assertDeclaredCheck as It, printBenchmarkReport as J, pairwiseSignificance as Jt, openSandboxRun as K, stopSentinel as Kt, recordProfileRun as L, checkProgramDigest as Lt, bestProfileFor as M, inlineSandboxClient as Mt, loadProfile as N, loopCampaignDispatch as Nt, compileSearchSpec as O, mcpSecretEnvMetadataKey as Ot, pickBestProfile as P, loopDispatch as Pt, trajectoryReport as Q, renderPairwiseMarkdown as Qt, graphFromSessionFacts as R, declaredCheckDeliverable as Rt, copyUntrackedIntoClone as S, McpSpawnFault as St, createFencedSqlRunContext as T, createMcpEnvironment as Tt, runStrategyEvolution as U, completionAuthorizes as Ut, chatWorkerSeam as V, readDeclaredCheck as Vt, strategyTournament as W, deterministicCompletion as Wt, createPrivateCasArtifactPort as X, renderLeaderboardMarkdown as Xt, runBenchmark as Y, renderLeaderboardHtml as Yt, equalKOnCost as Z, renderLeaderboardSvg as Zt, NOTE_MAX_CHARS as _, inProcessSandboxClient as _t, localShell as a, flatWidenGate as at, composeWorkerEvidence as b, defineLeaderboard as bt, createVerifierEnvironment as c, pipeline as ct, harvestSurfaceDiffs as d, widen as dt, openSqlRunStore as en, runPersonified as et, analystsFromRegistry as f, assertTraceDerivedFindings as ft, EVIDENCE_MAX_CHARS as g, observationFromRegistry as gt, runCoderChecks as h, registryScopeAnalyst as ht, jjWorkspace as i, fanout as it, connectRemoteSupervisor as j, secretEnvOfMcpServer as jt, searchPresets as k, resolveMcpServerLaunch as kt, boxSurfaceReader as l, selectValidWinner as lt, worktreeFanout as m, createScopeAnalyst as mt, makeFinding$1 as n, InMemoryCorpus as nt, runInWorkspace as o, loopUntil as ot, failuresAnalyst as p, buildSteerContext as pt, createS3PrivateCasStore as q, leaderboard as qt, gitWorkspace as r, renderCorpusToInstructions as rt, createWaterfallCollector as s, panel as st, computeFindingId$1 as t, FileCorpus as tt, fsSurfaceReader as u, verify as ut, VERIFY_TAIL_CHARS as v, HarvestError as vt, analyzeTrace as w, materializeLocalMcp as wt, settledWorkerOut as x, resolveSandboxClient as xt, closingWorkerNote as y, harvestCorpus as yt, graphDesignerExtraTools as z, declaredCheckDigest as zt };
10031
+ export { runBenchmark as $, renderLeaderboardHtml as $t, searchPresets as A, sanitizeMcpToolSchema as At, graphFromSessionFacts as B, assertDeclaredCheck as Bt, withUntrackedArtifacts as C, harvestCorpus as Ct, SEARCH_SPEC_CORRELATION_KEY as D, connectStdioMcp as Dt, createFencedSqlRunContext as E, McpSpawnFault as Et, loadProfile as F, secretEnvOfMcpServer as Ft, chatWorkerSeam as G, readDeclaredCheck as Gt, loadGraphFile as H, declaredCheckDeliverable as Ht, pickBestProfile as I, inlineSandboxClient as It, strategyTournament as J, deterministicCompletion as Jt, createChatSessionStore as K, runIsolatedCheck as Kt, profileRegistry as L, loopCampaignDispatch as Lt, connectRemoteSupervisor as M, mcpSecretEnvMetadataKey as Mt, connectRemoteSupervisorControl as N, resolveMcpServerLaunch as Nt, assertSearchSpec as O, materializeLocalMcp as Ot, bestProfileFor as P, resolveSecretEnv as Pt, printBenchmarkReport as Q, pairwiseSignificance as Qt, profileRunsForName as R, loopDispatch as Rt, copyUntrackedIntoClone as S, HarvestError as St, validateStoredGraph as T, resolveSandboxClient as Tt, graphDesignerExtraTools as U, declaredCheckDigest as Ut, GraphFileResolutionError as V, checkProgramDigest as Vt, chatTransportExecutor as W, declaredCheckJudge as Wt, openSandboxRun as X, stopSentinel as Xt, SandboxRunAbortError as Y, sentinelCompletion as Yt, createS3PrivateCasStore as Z, leaderboard as Zt, NOTE_MAX_CHARS as _, buildSteerContext as _t, localShell as a, FileCorpus as at, composeWorkerEvidence as b, observationFromRegistry as bt, createVerifierEnvironment as c, fanout as ct, harvestSurfaceDiffs as d, panel as dt, renderLeaderboardMarkdown as en, createPrivateCasArtifactPort as et, analystsFromRegistry as f, pipeline as ft, EVIDENCE_MAX_CHARS as g, assertTraceDerivedFindings as gt, runCoderChecks as h, widen as ht, jjWorkspace as i, openSqlRunStore as in, runPersonified as it, searchSpecDigest as j, envKeyProvider as jt, compileSearchSpec as k, createMcpEnvironment as kt, boxSurfaceReader as l, flatWidenGate as lt, worktreeFanout as m, verify as mt, makeFinding$1 as n, renderPairwiseMarkdown as nn, trajectoryReport as nt, runInWorkspace as o, InMemoryCorpus as ot, failuresAnalyst as p, selectValidWinner as pt, runStrategyEvolution as q, completionAuthorizes as qt, gitWorkspace as r, SqlRunOwnershipError as rn, definePersona as rt, createWaterfallCollector as s, renderCorpusToInstructions as st, computeFindingId$1 as t, renderLeaderboardSvg as tn, equalKOnCost as tt, fsSurfaceReader as u, loopUntil as ut, VERIFY_TAIL_CHARS as v, createScopeAnalyst as vt, analyzeTrace as w, defineLeaderboard as wt, settledWorkerOut as x, inProcessSandboxClient as xt, closingWorkerNote as y, registryScopeAnalyst as yt, recordProfileRun as z, superviseDispatch as zt };
9595
10032
 
9596
- //# sourceMappingURL=runtime-CsvGCQpl.js.map
10033
+ //# sourceMappingURL=runtime-BJPXHWbc.js.map