@tangle-network/agent-runtime 9.0.9 → 9.0.10

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 (99) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/dist/{activation-CjS7d4_x.js → activation-BuKAzxZB.js} +4 -4
  3. package/dist/{activation-CjS7d4_x.js.map → activation-BuKAzxZB.js.map} +1 -1
  4. package/dist/{activation-OSYxeVWi.d.ts → activation-CVVpVGyG.d.ts} +2 -2
  5. package/dist/agent.d.ts +1 -1
  6. package/dist/agent.js +4 -4
  7. package/dist/{bundle-CcpL2lfr.js → bundle-9NLb1WO3.js} +2 -2
  8. package/dist/{bundle-CcpL2lfr.js.map → bundle-9NLb1WO3.js.map} +1 -1
  9. package/dist/candidate-execution/index.js +5 -4
  10. package/dist/candidate-execution/index.js.map +1 -1
  11. package/dist/{continuation-DDPfLw2w.js → continuation-CZaeHEzQ.js} +2 -2
  12. package/dist/{continuation-DDPfLw2w.js.map → continuation-CZaeHEzQ.js.map} +1 -1
  13. package/dist/{coordination-manager-C0OJ1T9V.js → coordination-manager-B-Ugh18D.js} +6 -6
  14. package/dist/{coordination-manager-C0OJ1T9V.js.map → coordination-manager-B-Ugh18D.js.map} +1 -1
  15. package/dist/deadline-CySmJ_0S.js +134 -0
  16. package/dist/deadline-CySmJ_0S.js.map +1 -0
  17. package/dist/{delegate-Ct_KCtwW.js → delegate-Dizy-1ZC.js} +2 -2
  18. package/dist/{delegate-Ct_KCtwW.js.map → delegate-Dizy-1ZC.js.map} +1 -1
  19. package/dist/durable.d.ts +1 -1
  20. package/dist/durable.js +13 -13
  21. package/dist/{failure-cause-W0o778qO.js → failure-cause-WifbY42M.js} +2 -2
  22. package/dist/{failure-cause-W0o778qO.js.map → failure-cause-WifbY42M.js.map} +1 -1
  23. package/dist/{graph-DHvP4C1q.js → graph-Bf3axJxp.js} +210 -300
  24. package/dist/graph-Bf3axJxp.js.map +1 -0
  25. package/dist/{graph-registry-Dbm8QhbA.js → graph-registry-B_1C7qye.js} +1 -1
  26. package/dist/{graph-registry-D0FE9VpR.js → graph-registry-BbZN5deo.js} +282 -6
  27. package/dist/graph-registry-BbZN5deo.js.map +1 -0
  28. package/dist/{improve-DIsur006.js → improve-JThdxpGB.js} +8 -9
  29. package/dist/{improve-DIsur006.js.map → improve-JThdxpGB.js.map} +1 -1
  30. package/dist/index.d.ts +3 -3
  31. package/dist/index.js +15 -102
  32. package/dist/index.js.map +1 -1
  33. package/dist/intelligence.d.ts +2 -2
  34. package/dist/intelligence.js +7 -7
  35. package/dist/{jsonl-file-DsxVI0E_.js → jsonl-file-BhuxeejY.js} +114 -2
  36. package/dist/jsonl-file-BhuxeejY.js.map +1 -0
  37. package/dist/kernel.d.ts +2 -2
  38. package/dist/kernel.js +17 -16
  39. package/dist/{loop-runner-CCdQ1pmE.d.ts → loop-runner-40_tD2d4.d.ts} +2 -2
  40. package/dist/{loop-runner-ku4_lGxf.js → loop-runner-D8FP4oEN.js} +2 -2
  41. package/dist/{loop-runner-ku4_lGxf.js.map → loop-runner-D8FP4oEN.js.map} +1 -1
  42. package/dist/loop-runner-bin.d.ts +1 -1
  43. package/dist/loop-runner-bin.js +1 -1
  44. package/dist/mcp/bin.js +3 -3
  45. package/dist/mcp/index.d.ts +1 -1
  46. package/dist/mcp/index.js +7 -7
  47. package/dist/mcp/memory-bin.js +1 -1
  48. package/dist/output-artifacts-AqkZ8lO2.js +331 -0
  49. package/dist/output-artifacts-AqkZ8lO2.js.map +1 -0
  50. package/dist/{prepare-D7WwIddG.js → prepare-Cw4ZaN01.js} +5 -4
  51. package/dist/{prepare-D7WwIddG.js.map → prepare-Cw4ZaN01.js.map} +1 -1
  52. package/dist/{profile-BT0X-dm5.js → profile-Cxl_Ajl2.js} +2 -2
  53. package/dist/{profile-BT0X-dm5.js.map → profile-Cxl_Ajl2.js.map} +1 -1
  54. package/dist/profiles.d.ts +1 -1
  55. package/dist/{provision-supervisor-la7aXbs3.js → provision-supervisor-BDAXc65B.js} +8 -6
  56. package/dist/{provision-supervisor-la7aXbs3.js.map → provision-supervisor-BDAXc65B.js.map} +1 -1
  57. package/dist/{run-cancellation-CfwQmkeG.js → run-cancellation-Cy9ie5cQ.js} +3 -3
  58. package/dist/{run-cancellation-CfwQmkeG.js.map → run-cancellation-Cy9ie5cQ.js.map} +1 -1
  59. package/dist/{run-state-BCfmjm6a.js → run-state-9FP-wBWK.js} +6 -6
  60. package/dist/{run-state-BCfmjm6a.js.map → run-state-9FP-wBWK.js.map} +1 -1
  61. package/dist/{runtime-DXkdY7VT.js → runtime-Czu2SSMy.js} +50 -25
  62. package/dist/{runtime-DXkdY7VT.js.map → runtime-Czu2SSMy.js.map} +1 -1
  63. package/dist/{search-executor-DQH_PWxu.js → search-executor-Dl_WUQeH.js} +6 -6
  64. package/dist/{search-executor-DQH_PWxu.js.map → search-executor-Dl_WUQeH.js.map} +1 -1
  65. package/dist/{server-D4nCyP5N.js → server-Dbge7VDj.js} +5 -5
  66. package/dist/{server-D4nCyP5N.js.map → server-Dbge7VDj.js.map} +1 -1
  67. package/dist/{settle-record-soq9tzaX.js → settle-record-tgpwk6QF.js} +3 -3
  68. package/dist/{settle-record-soq9tzaX.js.map → settle-record-tgpwk6QF.js.map} +1 -1
  69. package/dist/{structural-rollout-D5rtwNgB.js → structural-rollout-DUMYWwZ3.js} +7 -6
  70. package/dist/{structural-rollout-D5rtwNgB.js.map → structural-rollout-DUMYWwZ3.js.map} +1 -1
  71. package/dist/{supervise-G9tWVS7d.js → supervise-BpcWjDMr.js} +12 -10
  72. package/dist/{supervise-G9tWVS7d.js.map → supervise-BpcWjDMr.js.map} +1 -1
  73. package/dist/{supervision-discovery-DgkhVixZ.js → supervision-discovery-Hekh50FG.js} +5 -5
  74. package/dist/{supervision-discovery-DgkhVixZ.js.map → supervision-discovery-Hekh50FG.js.map} +1 -1
  75. package/dist/{supervisor-ByKjr-4D.js → supervisor-CdrDXnOJ.js} +9 -8
  76. package/dist/{supervisor-ByKjr-4D.js.map → supervisor-CdrDXnOJ.js.map} +1 -1
  77. package/dist/{supervisor-accounting-CvpkFhZU.js → supervisor-accounting-us4w7tG6.js} +8 -118
  78. package/dist/supervisor-accounting-us4w7tG6.js.map +1 -0
  79. package/dist/testing.d.ts +1 -1
  80. package/dist/testing.js +13 -13
  81. package/dist/{tool-server-Df-Uy99W.js → tool-server-CirrqFlr.js} +2 -2
  82. package/dist/{tool-server-Df-Uy99W.js.map → tool-server-CirrqFlr.js.map} +1 -1
  83. package/dist/{top-web-Cg5nyWlg.js → top-web-xSGEh02D.js} +7 -7
  84. package/dist/{top-web-Cg5nyWlg.js.map → top-web-xSGEh02D.js.map} +1 -1
  85. package/dist/tui/bin.js +3 -3
  86. package/dist/tui/index.d.ts +1 -1
  87. package/dist/tui/index.js +2 -2
  88. package/dist/{types-KQkbyDmn.d.ts → types-DRijOelA.d.ts} +189 -164
  89. package/dist/{util-fcckrkKp.js → util-qsH5cC9S.js} +3 -132
  90. package/dist/util-qsH5cC9S.js.map +1 -0
  91. package/dist/{workspace-streams-DA9R3j-p.js → workspace-streams-BakRr-Pl.js} +9 -330
  92. package/dist/workspace-streams-BakRr-Pl.js.map +1 -0
  93. package/package.json +1 -1
  94. package/dist/graph-DHvP4C1q.js.map +0 -1
  95. package/dist/graph-registry-D0FE9VpR.js.map +0 -1
  96. package/dist/jsonl-file-DsxVI0E_.js.map +0 -1
  97. package/dist/supervisor-accounting-CvpkFhZU.js.map +0 -1
  98. package/dist/util-fcckrkKp.js.map +0 -1
  99. package/dist/workspace-streams-DA9R3j-p.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"loop-runner-ku4_lGxf.js","names":[],"sources":["../src/loop-runner.ts"],"sourcesContent":["/**\n *\n * `runDelegatedLoop` — the configured delegated loop-runner.\n *\n * One typed entrypoint a worker agent (or a scheduled routine) calls to run a\n * disciplined loop in a chosen MODE, over agent-runtime's hardened engines:\n *\n * code → build-in-a-loop on the GENERIC recursive path (worktreeLoopRunner: author one\n * `AgentProfile` per harness → worktree-CLI leaves → `patchDelivered` gate)\n * review → caller-registered runner — a `code` runner with an approval gate over candidates\n * research → research-in-a-loop with valid-only KB growth (createKbGate)\n * audit → analyze trace/run data → findings (runAnalystLoop, caller-wired)\n * self-improve → caller-registered `improve(profile, options)` run\n *\n * It is intentionally a thin façade: the value is that EVERY product reuses the\n * one hardened engine instead of forking delegation logic. The dispatcher owns\n * mode routing, timing, fail-loud on an unregistered mode, and a uniform result\n * shape; each mode's engine is a pre-configured runner in the registry (build it\n * with the factories below, or inject your own / a stub).\n *\n * @experimental\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { runAnalystLoop } from './analyst-loop'\nimport type { RunAnalystLoopOpts, RunAnalystLoopResult } from './analyst-loop/types'\nimport { ConfigError } from './errors'\nimport { type CreateKbGateOptions, createKbGate, type FactCandidate } from './mcp/kb-gate'\nimport {\n type AuthoredHarness,\n type Budget,\n createExecutorRegistry,\n definePersona,\n runPersonified,\n type WinnerStrategy,\n type WorktreeFanoutOptions,\n type WorktreePatchArtifact,\n worktreeFanout,\n} from './runtime'\n\n/** All valid delegated-loop mode names — used for validation and CLI surfaces. @experimental */\nexport const DELEGATED_LOOP_MODES = ['code', 'review', 'research', 'audit', 'self-improve'] as const\n\n/** @experimental */\nexport type DelegatedLoopMode = (typeof DELEGATED_LOOP_MODES)[number]\n\n/** Type guard — returns true when `value` is a valid `DelegatedLoopMode` string. @experimental */\nexport function isDelegatedLoopMode(value: unknown): value is DelegatedLoopMode {\n return typeof value === 'string' && (DELEGATED_LOOP_MODES as readonly string[]).includes(value)\n}\n\n/** @experimental A pre-configured loop for one mode. Returns the mode's raw\n * output; the dispatcher wraps it in a `DelegatedLoopResult`. */\nexport type DelegatedLoopRunner<T = unknown> = (signal: AbortSignal) => Promise<T>\n\n/** @experimental Mode → configured runner. Partial: only register the modes a\n * given product/routine actually uses. */\nexport type DelegatedLoopRegistry = Partial<Record<DelegatedLoopMode, DelegatedLoopRunner>>\n\n/** @experimental Uniform result — never throws from a registered runner; a\n * thrown engine becomes `{ ok: false, error }` so a routine can record + move on. */\nexport interface DelegatedLoopResult<T = unknown> {\n mode: DelegatedLoopMode\n ok: boolean\n output?: T\n error?: string\n durationMs: number\n}\n\n/** @experimental */\ninterface RunDelegatedLoopOptions {\n signal?: AbortSignal\n /** Clock override for deterministic tests. */\n now?: () => number\n}\n\n/**\n *\n * Dispatch a configured loop by mode. Fails loud (throws `ConfigError`) when no\n * runner is registered for the mode — a routine pointed at an unwired mode is a\n * config bug, not a silent no-op. A runner that throws is captured as\n * `{ ok: false }` so unattended runs record the failure rather than crash.\n *\n * @experimental\n */\nexport async function runDelegatedLoop<T = unknown>(\n mode: DelegatedLoopMode,\n registry: DelegatedLoopRegistry,\n options: RunDelegatedLoopOptions = {},\n): Promise<DelegatedLoopResult<T>> {\n const runner = registry[mode] as DelegatedLoopRunner<T> | undefined\n if (!runner) {\n throw new ConfigError(\n `runDelegatedLoop: no runner registered for mode '${mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n )\n }\n const now = options.now ?? Date.now\n const signal = options.signal ?? new AbortController().signal\n const start = now()\n try {\n const output = await runner(signal)\n return { mode, ok: true, output, durationMs: now() - start }\n } catch (err) {\n return {\n mode,\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n durationMs: now() - start,\n }\n }\n}\n\n/** @experimental Options for the local-repo `code` runner over the GENERIC recursive path. */\ninterface WorktreeLoopRunnerOptions {\n /** Exact profile carried by the personified root that owns this fanout. */\n rootProfile: AgentProfile\n /** Absolute path to the local git checkout each worktree is cut from. */\n repoRoot: string\n /** The instruction handed to every authored harness (composed under each profile's systemPrompt). */\n taskPrompt: string\n /** The supervisor-authored harness profiles — one fanout item (one worktree-CLI leaf) each. */\n harnesses: ReadonlyArray<AuthoredHarness>\n /** Conserved budget pool bounding the fanout (equal-k holds by construction). */\n budget: Budget\n /** Shell command run in each worktree to derive the tests-PASS signal. */\n testCmd?: string\n /** Shell command run in each worktree to derive the typecheck-PASS signal. */\n typecheckCmd?: string\n /** Which verification signals the deliverable REQUIRES present-and-passing (default none). */\n require?: ReadonlyArray<'tests' | 'typecheck'>\n /** Diff-size cap (lines). */\n maxDiffLines?: number\n /** Literal path prefixes the patch must not touch (the secret-floor is always on regardless). */\n forbiddenPaths?: string[]\n /** Winner-selection strategy among gated candidates. Default `highest-score`. */\n winnerStrategy?: WinnerStrategy\n /** Test seams forwarded to the worktree-CLI leaves so the runner drives offline. */\n runGit?: WorktreeFanoutOptions['runGit']\n runHarness?: WorktreeFanoutOptions['runHarness']\n runCommand?: WorktreeFanoutOptions['runCommand']\n}\n\n/**\n *\n * `code` mode on the GENERIC recursive path: author one `AgentProfile` per harness, run them as a\n * `worktreeFanout` (N `createWorktreeCliExecutor` leaves, each `gateOnDeliverable`) through\n * `runPersonified` on the keystone Supervisor. The sandbox-session counterpart that drives the in-box\n * harness over a `SandboxClient` is `detachedSessionDelegate` (`./mcp/delegates`); here there is no\n * `runAgentRounds` driver, no role-coupled delegate — the harness list is the fanout, the gate is\n * `patchDelivered`,\n * the winner is the shared valid-only selector (NOT `defaultSelectWinner`, whose non-valid fallback\n * would surface an ungated patch). Equal-k holds by the conserved budget pool. Returns the winning\n * patch artifact, or throws when no candidate is delivered (fail loud, never a vacuous done).\n *\n * @experimental\n */\nexport function worktreeLoopRunner(\n options: WorktreeLoopRunnerOptions,\n): DelegatedLoopRunner<WorktreePatchArtifact> {\n const shape = worktreeFanout<string>({\n repoRoot: options.repoRoot,\n taskPrompt: options.taskPrompt,\n harnesses: options.harnesses,\n ...(options.testCmd !== undefined ? { testCmd: options.testCmd } : {}),\n ...(options.typecheckCmd !== undefined ? { typecheckCmd: options.typecheckCmd } : {}),\n ...(options.require !== undefined ? { require: options.require } : {}),\n ...(options.maxDiffLines !== undefined ? { maxDiffLines: options.maxDiffLines } : {}),\n ...(options.forbiddenPaths !== undefined ? { forbiddenPaths: options.forbiddenPaths } : {}),\n ...(options.winnerStrategy !== undefined ? { winnerStrategy: options.winnerStrategy } : {}),\n ...(options.runGit ? { runGit: options.runGit } : {}),\n ...(options.runHarness ? { runHarness: options.runHarness } : {}),\n ...(options.runCommand ? { runCommand: options.runCommand } : {}),\n })\n // The persona's only role here is to carry the fanout shape onto the Supervisor; each item's\n // executor is BYO (the gated worktree-CLI leaf), so the registry only needs to pass BYO through.\n const persona = definePersona<WorktreePatchArtifact>({\n name: 'worktree-coder',\n root: { profile: options.rootProfile, harness: null },\n directive: 'deliver a minimal validated patch on a fresh worktree',\n context: { role: 'coder' },\n executors: { registry: createExecutorRegistry() },\n })\n return async (signal) => {\n const result = await runPersonified<string, WorktreePatchArtifact>({\n persona,\n shape,\n task: options.taskPrompt,\n budget: options.budget,\n signal,\n })\n if (result.kind !== 'winner' || result.out.kind !== 'done') {\n const blockers =\n result.kind === 'winner' && result.out.kind === 'blocked'\n ? result.out.blockers.join('; ')\n : `supervisor settled ${result.kind}`\n throw new Error(`worktreeLoopRunner: no delivered patch (${blockers})`)\n }\n return result.out.deliverable\n }\n}\n\n/** @experimental A fact rejected at the KB gate — surfaced, never dropped. */\nexport interface VetoedFact {\n candidate: FactCandidate\n vetoedBy?: string\n reason?: string\n}\n\n/** @experimental */\ninterface ResearchLoopResult {\n /** Facts that passed the fail-closed gate — safe to write to the KB. */\n accepted: FactCandidate[]\n /** Facts the gate vetoed in the final round — escalate, do not silently drop. */\n vetoed: VetoedFact[]\n /** Research rounds actually run. */\n rounds: number\n}\n\n/** @experimental Options for the default `research` runner. */\ninterface ResearchLoopRunnerOptions {\n /**\n * The research engine (the consumer's web/doc searcher + extractor). Called\n * each round with the prior round's vetoes so it can re-research the gaps.\n * Returns fact candidates carrying their grounding (`verbatimPassage` +\n * `sourceText`).\n */\n research: (round: number, vetoed: VetoedFact[]) => Promise<FactCandidate[]>\n /** Gate config (extra judges, self-artifact kinds, …). The floor is always on. */\n gate?: CreateKbGateOptions\n /** Max research rounds (correct-on-veto remediation). Default 1. */\n maxRounds?: number\n}\n\n/**\n * `research` mode — research-in-a-loop with valid-only KB growth.\n *\n * Each round: research → gate every candidate (fail-closed; passage MUST be in\n * the source) → accept the clean ones → re-research the vetoed ones next round,\n * up to `maxRounds`. Vetoed facts in the final round are RETURNED (escalate,\n * never silently dropped) so the caller audits vs retries.\n *\n * @experimental\n */\nexport function researchLoopRunner(\n o: ResearchLoopRunnerOptions,\n): DelegatedLoopRunner<ResearchLoopResult> {\n const gate = createKbGate(o.gate)\n const maxRounds = Math.max(1, Math.trunc(o.maxRounds ?? 1))\n return async (signal) => {\n const accepted: FactCandidate[] = []\n let vetoed: VetoedFact[] = []\n let rounds = 0\n for (let round = 0; round < maxRounds; round += 1) {\n if (signal.aborted) break\n rounds += 1\n const candidates = await o.research(round, vetoed)\n if (candidates.length === 0) break\n vetoed = []\n for (const c of candidates) {\n const v = await gate(c)\n if (v.accepted) accepted.push(c)\n else vetoed.push({ candidate: c, vetoedBy: v.vetoedBy, reason: v.reason })\n }\n if (vetoed.length === 0) break\n }\n return { accepted, vetoed, rounds }\n }\n}\n\n/**\n * `audit` mode — analyst loop over captured trace/run data.\n *\n * @experimental\n */\nexport function auditLoopRunner<TProposal = unknown, TEdit = unknown>(\n options: RunAnalystLoopOpts,\n): DelegatedLoopRunner<RunAnalystLoopResult<TProposal, TEdit>> {\n return async () => runAnalystLoop<TProposal, TEdit>(options)\n}\n"],"mappings":";;;;;AAyCA,MAAa,uBAAuB;CAAC;CAAQ;CAAU;CAAY;CAAS;AAAc;;AAM1F,SAAgB,oBAAoB,OAA4C;CAC9E,OAAO,OAAO,UAAU,YAAa,qBAA2C,SAAS,KAAK;AAChG;;;;;;;;;;AAoCA,eAAsB,iBACpB,MACA,UACA,UAAmC,CAAC,GACH;CACjC,MAAM,SAAS,SAAS;CACxB,IAAI,CAAC,QACH,MAAM,IAAI,YACR,oDAAoD,KAAK,iBACvD,OAAO,KAAK,QAAQ,CAAC,CAAC,KAAK,IAAI,KAAK,OACrC,EACH;CAEF,MAAM,MAAM,QAAQ,OAAO,KAAK;CAChC,MAAM,SAAS,QAAQ,UAAU,IAAI,gBAAgB,CAAC,CAAC;CACvD,MAAM,QAAQ,IAAI;CAClB,IAAI;EAEF,OAAO;GAAE;GAAM,IAAI;GAAM,QAAA,MADJ,OAAO,MAAM;GACD,YAAY,IAAI,IAAI;EAAM;CAC7D,SAAS,KAAK;EACZ,OAAO;GACL;GACA,IAAI;GACJ,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;GACtD,YAAY,IAAI,IAAI;EACtB;CACF;AACF;;;;;;AAoKA,SAAgB,gBACd,SAC6D;CAC7D,OAAO,YAAY,eAAiC,OAAO;AAC7D"}
1
+ {"version":3,"file":"loop-runner-D8FP4oEN.js","names":[],"sources":["../src/loop-runner.ts"],"sourcesContent":["/**\n *\n * `runDelegatedLoop` — the configured delegated loop-runner.\n *\n * One typed entrypoint a worker agent (or a scheduled routine) calls to run a\n * disciplined loop in a chosen MODE, over agent-runtime's hardened engines:\n *\n * code → build-in-a-loop on the GENERIC recursive path (worktreeLoopRunner: author one\n * `AgentProfile` per harness → worktree-CLI leaves → `patchDelivered` gate)\n * review → caller-registered runner — a `code` runner with an approval gate over candidates\n * research → research-in-a-loop with valid-only KB growth (createKbGate)\n * audit → analyze trace/run data → findings (runAnalystLoop, caller-wired)\n * self-improve → caller-registered `improve(profile, options)` run\n *\n * It is intentionally a thin façade: the value is that EVERY product reuses the\n * one hardened engine instead of forking delegation logic. The dispatcher owns\n * mode routing, timing, fail-loud on an unregistered mode, and a uniform result\n * shape; each mode's engine is a pre-configured runner in the registry (build it\n * with the factories below, or inject your own / a stub).\n *\n * @experimental\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { runAnalystLoop } from './analyst-loop'\nimport type { RunAnalystLoopOpts, RunAnalystLoopResult } from './analyst-loop/types'\nimport { ConfigError } from './errors'\nimport { type CreateKbGateOptions, createKbGate, type FactCandidate } from './mcp/kb-gate'\nimport {\n type AuthoredHarness,\n type Budget,\n createExecutorRegistry,\n definePersona,\n runPersonified,\n type WinnerStrategy,\n type WorktreeFanoutOptions,\n type WorktreePatchArtifact,\n worktreeFanout,\n} from './runtime'\n\n/** All valid delegated-loop mode names — used for validation and CLI surfaces. @experimental */\nexport const DELEGATED_LOOP_MODES = ['code', 'review', 'research', 'audit', 'self-improve'] as const\n\n/** @experimental */\nexport type DelegatedLoopMode = (typeof DELEGATED_LOOP_MODES)[number]\n\n/** Type guard — returns true when `value` is a valid `DelegatedLoopMode` string. @experimental */\nexport function isDelegatedLoopMode(value: unknown): value is DelegatedLoopMode {\n return typeof value === 'string' && (DELEGATED_LOOP_MODES as readonly string[]).includes(value)\n}\n\n/** @experimental A pre-configured loop for one mode. Returns the mode's raw\n * output; the dispatcher wraps it in a `DelegatedLoopResult`. */\nexport type DelegatedLoopRunner<T = unknown> = (signal: AbortSignal) => Promise<T>\n\n/** @experimental Mode → configured runner. Partial: only register the modes a\n * given product/routine actually uses. */\nexport type DelegatedLoopRegistry = Partial<Record<DelegatedLoopMode, DelegatedLoopRunner>>\n\n/** @experimental Uniform result — never throws from a registered runner; a\n * thrown engine becomes `{ ok: false, error }` so a routine can record + move on. */\nexport interface DelegatedLoopResult<T = unknown> {\n mode: DelegatedLoopMode\n ok: boolean\n output?: T\n error?: string\n durationMs: number\n}\n\n/** @experimental */\ninterface RunDelegatedLoopOptions {\n signal?: AbortSignal\n /** Clock override for deterministic tests. */\n now?: () => number\n}\n\n/**\n *\n * Dispatch a configured loop by mode. Fails loud (throws `ConfigError`) when no\n * runner is registered for the mode — a routine pointed at an unwired mode is a\n * config bug, not a silent no-op. A runner that throws is captured as\n * `{ ok: false }` so unattended runs record the failure rather than crash.\n *\n * @experimental\n */\nexport async function runDelegatedLoop<T = unknown>(\n mode: DelegatedLoopMode,\n registry: DelegatedLoopRegistry,\n options: RunDelegatedLoopOptions = {},\n): Promise<DelegatedLoopResult<T>> {\n const runner = registry[mode] as DelegatedLoopRunner<T> | undefined\n if (!runner) {\n throw new ConfigError(\n `runDelegatedLoop: no runner registered for mode '${mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n )\n }\n const now = options.now ?? Date.now\n const signal = options.signal ?? new AbortController().signal\n const start = now()\n try {\n const output = await runner(signal)\n return { mode, ok: true, output, durationMs: now() - start }\n } catch (err) {\n return {\n mode,\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n durationMs: now() - start,\n }\n }\n}\n\n/** @experimental Options for the local-repo `code` runner over the GENERIC recursive path. */\ninterface WorktreeLoopRunnerOptions {\n /** Exact profile carried by the personified root that owns this fanout. */\n rootProfile: AgentProfile\n /** Absolute path to the local git checkout each worktree is cut from. */\n repoRoot: string\n /** The instruction handed to every authored harness (composed under each profile's systemPrompt). */\n taskPrompt: string\n /** The supervisor-authored harness profiles — one fanout item (one worktree-CLI leaf) each. */\n harnesses: ReadonlyArray<AuthoredHarness>\n /** Conserved budget pool bounding the fanout (equal-k holds by construction). */\n budget: Budget\n /** Shell command run in each worktree to derive the tests-PASS signal. */\n testCmd?: string\n /** Shell command run in each worktree to derive the typecheck-PASS signal. */\n typecheckCmd?: string\n /** Which verification signals the deliverable REQUIRES present-and-passing (default none). */\n require?: ReadonlyArray<'tests' | 'typecheck'>\n /** Diff-size cap (lines). */\n maxDiffLines?: number\n /** Literal path prefixes the patch must not touch (the secret-floor is always on regardless). */\n forbiddenPaths?: string[]\n /** Winner-selection strategy among gated candidates. Default `highest-score`. */\n winnerStrategy?: WinnerStrategy\n /** Test seams forwarded to the worktree-CLI leaves so the runner drives offline. */\n runGit?: WorktreeFanoutOptions['runGit']\n runHarness?: WorktreeFanoutOptions['runHarness']\n runCommand?: WorktreeFanoutOptions['runCommand']\n}\n\n/**\n *\n * `code` mode on the GENERIC recursive path: author one `AgentProfile` per harness, run them as a\n * `worktreeFanout` (N `createWorktreeCliExecutor` leaves, each `gateOnDeliverable`) through\n * `runPersonified` on the keystone Supervisor. The sandbox-session counterpart that drives the in-box\n * harness over a `SandboxClient` is `detachedSessionDelegate` (`./mcp/delegates`); here there is no\n * `runAgentRounds` driver, no role-coupled delegate — the harness list is the fanout, the gate is\n * `patchDelivered`,\n * the winner is the shared valid-only selector (NOT `defaultSelectWinner`, whose non-valid fallback\n * would surface an ungated patch). Equal-k holds by the conserved budget pool. Returns the winning\n * patch artifact, or throws when no candidate is delivered (fail loud, never a vacuous done).\n *\n * @experimental\n */\nexport function worktreeLoopRunner(\n options: WorktreeLoopRunnerOptions,\n): DelegatedLoopRunner<WorktreePatchArtifact> {\n const shape = worktreeFanout<string>({\n repoRoot: options.repoRoot,\n taskPrompt: options.taskPrompt,\n harnesses: options.harnesses,\n ...(options.testCmd !== undefined ? { testCmd: options.testCmd } : {}),\n ...(options.typecheckCmd !== undefined ? { typecheckCmd: options.typecheckCmd } : {}),\n ...(options.require !== undefined ? { require: options.require } : {}),\n ...(options.maxDiffLines !== undefined ? { maxDiffLines: options.maxDiffLines } : {}),\n ...(options.forbiddenPaths !== undefined ? { forbiddenPaths: options.forbiddenPaths } : {}),\n ...(options.winnerStrategy !== undefined ? { winnerStrategy: options.winnerStrategy } : {}),\n ...(options.runGit ? { runGit: options.runGit } : {}),\n ...(options.runHarness ? { runHarness: options.runHarness } : {}),\n ...(options.runCommand ? { runCommand: options.runCommand } : {}),\n })\n // The persona's only role here is to carry the fanout shape onto the Supervisor; each item's\n // executor is BYO (the gated worktree-CLI leaf), so the registry only needs to pass BYO through.\n const persona = definePersona<WorktreePatchArtifact>({\n name: 'worktree-coder',\n root: { profile: options.rootProfile, harness: null },\n directive: 'deliver a minimal validated patch on a fresh worktree',\n context: { role: 'coder' },\n executors: { registry: createExecutorRegistry() },\n })\n return async (signal) => {\n const result = await runPersonified<string, WorktreePatchArtifact>({\n persona,\n shape,\n task: options.taskPrompt,\n budget: options.budget,\n signal,\n })\n if (result.kind !== 'winner' || result.out.kind !== 'done') {\n const blockers =\n result.kind === 'winner' && result.out.kind === 'blocked'\n ? result.out.blockers.join('; ')\n : `supervisor settled ${result.kind}`\n throw new Error(`worktreeLoopRunner: no delivered patch (${blockers})`)\n }\n return result.out.deliverable\n }\n}\n\n/** @experimental A fact rejected at the KB gate — surfaced, never dropped. */\nexport interface VetoedFact {\n candidate: FactCandidate\n vetoedBy?: string\n reason?: string\n}\n\n/** @experimental */\ninterface ResearchLoopResult {\n /** Facts that passed the fail-closed gate — safe to write to the KB. */\n accepted: FactCandidate[]\n /** Facts the gate vetoed in the final round — escalate, do not silently drop. */\n vetoed: VetoedFact[]\n /** Research rounds actually run. */\n rounds: number\n}\n\n/** @experimental Options for the default `research` runner. */\ninterface ResearchLoopRunnerOptions {\n /**\n * The research engine (the consumer's web/doc searcher + extractor). Called\n * each round with the prior round's vetoes so it can re-research the gaps.\n * Returns fact candidates carrying their grounding (`verbatimPassage` +\n * `sourceText`).\n */\n research: (round: number, vetoed: VetoedFact[]) => Promise<FactCandidate[]>\n /** Gate config (extra judges, self-artifact kinds, …). The floor is always on. */\n gate?: CreateKbGateOptions\n /** Max research rounds (correct-on-veto remediation). Default 1. */\n maxRounds?: number\n}\n\n/**\n * `research` mode — research-in-a-loop with valid-only KB growth.\n *\n * Each round: research → gate every candidate (fail-closed; passage MUST be in\n * the source) → accept the clean ones → re-research the vetoed ones next round,\n * up to `maxRounds`. Vetoed facts in the final round are RETURNED (escalate,\n * never silently dropped) so the caller audits vs retries.\n *\n * @experimental\n */\nexport function researchLoopRunner(\n o: ResearchLoopRunnerOptions,\n): DelegatedLoopRunner<ResearchLoopResult> {\n const gate = createKbGate(o.gate)\n const maxRounds = Math.max(1, Math.trunc(o.maxRounds ?? 1))\n return async (signal) => {\n const accepted: FactCandidate[] = []\n let vetoed: VetoedFact[] = []\n let rounds = 0\n for (let round = 0; round < maxRounds; round += 1) {\n if (signal.aborted) break\n rounds += 1\n const candidates = await o.research(round, vetoed)\n if (candidates.length === 0) break\n vetoed = []\n for (const c of candidates) {\n const v = await gate(c)\n if (v.accepted) accepted.push(c)\n else vetoed.push({ candidate: c, vetoedBy: v.vetoedBy, reason: v.reason })\n }\n if (vetoed.length === 0) break\n }\n return { accepted, vetoed, rounds }\n }\n}\n\n/**\n * `audit` mode — analyst loop over captured trace/run data.\n *\n * @experimental\n */\nexport function auditLoopRunner<TProposal = unknown, TEdit = unknown>(\n options: RunAnalystLoopOpts,\n): DelegatedLoopRunner<RunAnalystLoopResult<TProposal, TEdit>> {\n return async () => runAnalystLoop<TProposal, TEdit>(options)\n}\n"],"mappings":";;;;;AAyCA,MAAa,uBAAuB;CAAC;CAAQ;CAAU;CAAY;CAAS;AAAc;;AAM1F,SAAgB,oBAAoB,OAA4C;CAC9E,OAAO,OAAO,UAAU,YAAa,qBAA2C,SAAS,KAAK;AAChG;;;;;;;;;;AAoCA,eAAsB,iBACpB,MACA,UACA,UAAmC,CAAC,GACH;CACjC,MAAM,SAAS,SAAS;CACxB,IAAI,CAAC,QACH,MAAM,IAAI,YACR,oDAAoD,KAAK,iBACvD,OAAO,KAAK,QAAQ,CAAC,CAAC,KAAK,IAAI,KAAK,OACrC,EACH;CAEF,MAAM,MAAM,QAAQ,OAAO,KAAK;CAChC,MAAM,SAAS,QAAQ,UAAU,IAAI,gBAAgB,CAAC,CAAC;CACvD,MAAM,QAAQ,IAAI;CAClB,IAAI;EAEF,OAAO;GAAE;GAAM,IAAI;GAAM,QAAA,MADJ,OAAO,MAAM;GACD,YAAY,IAAI,IAAI;EAAM;CAC7D,SAAS,KAAK;EACZ,OAAO;GACL;GACA,IAAI;GACJ,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;GACtD,YAAY,IAAI,IAAI;EACtB;CACF;AACF;;;;;;AAoKA,SAAgB,gBACd,SAC6D;CAC7D,OAAO,YAAY,eAAiC,OAAO;AAC7D"}
@@ -1,4 +1,4 @@
1
- import { n as DelegatedLoopResult, t as DelegatedLoopRegistry } from "./loop-runner-CCdQ1pmE.js";
1
+ import { n as DelegatedLoopResult, t as DelegatedLoopRegistry } from "./loop-runner-40_tD2d4.js";
2
2
  /** @experimental Parsed CLI invocation. */
3
3
  export interface LoopRunnerCliArgs {
4
4
  mode: string;
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { i as runDelegatedLoop, r as isDelegatedLoopMode, t as DELEGATED_LOOP_MODES } from "./loop-runner-ku4_lGxf.js";
2
+ import { i as runDelegatedLoop, r as isDelegatedLoopMode, t as DELEGATED_LOOP_MODES } from "./loop-runner-D8FP4oEN.js";
3
3
  // src/loop-runner-bin.ts
4
4
  /**
5
5
  *
package/dist/mcp/bin.js CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import { Dn as FileObserverJournal, It as coordinationProfileToolPrefix, Rn as readTraceContextFromEnv } from "../supervisor-accounting-CvpkFhZU.js";
2
+ import { Dn as FileObserverJournal, It as coordinationProfileToolPrefix, Rn as readTraceContextFromEnv } from "../supervisor-accounting-us4w7tG6.js";
3
3
  import { i as ConfigError } from "../errors-DG8yufqX.js";
4
- import { s as supervisorInstructions } from "../delegate-Ct_KCtwW.js";
5
- import { a as DelegationTaskQueue, n as observerJournalEventSource, o as FileDelegationStore, r as rootStreamEventSource, t as createMcpServer } from "../server-D4nCyP5N.js";
4
+ import { s as supervisorInstructions } from "../delegate-Dizy-1ZC.js";
5
+ import { a as DelegationTaskQueue, n as observerJournalEventSource, o as FileDelegationStore, r as rootStreamEventSource, t as createMcpServer } from "../server-Dbge7VDj.js";
6
6
  import { basename, isAbsolute } from "node:path";
7
7
  // src/mcp/delegate-supervisor-provisioning.ts
8
8
  function trimmed(value) {
@@ -1,4 +1,4 @@
1
- import { $f as McpEventSource, $m as DelegateResearchArgs, Ah as DelegationPersistenceError, Am as UiAuditorDelegate, Bf as ResolveSpawnResourcePathsResult, Bm as runDetachedTurn, Cm as FeedbackStore, Dm as DelegateRunCtx, E_ as QuestionOption, Ef as CheckRead, Em as CoderReviewer, F as CoordinationTools, Fh as CoderTask, Fm as SiblingSandboxExecutorOptions, Fv as LOCAL_HARNESSES, G as SpawnRefusalCause, Gf as environmentReader, Gm as DelegationResumeTick, Hf as SpawnResourceBytes, Hm as DelegationRecord, I as CoordinationToolsOptions, Im as createFleetWorkspaceExecutor, Iv as LocalHarness, Jf as McpServerOptions, Jm as DelegationTaskQueueOptions, Kf as resolveSpawnResourcePaths, Km as DelegationRunContext, Lm as createSiblingSandboxExecutor, Mh as FileDelegationStore, Mm as DelegationExecutor, Nh as FileDelegationStoreOptions, Nm as FleetHandle, Nv as RunLocalHarnessOptions, Oh as DelegationTraceSpan, Om as DetachedSessionDelegateOptions, P as CoordinationStats, Ph as CoderOutput, Pm as FleetWorkspaceExecutorOptions, Pv as runLocalHarness, Qf as McpEventRecord, Qm as DelegateCodeConfig, Rm as DetachedTurn, Sm as FeedbackEvent, Sy as readTraceContextFromEnv, T_ as QuestionLevel, Tm as CoderReview, Tv as AnalystRegistry, Uf as SpawnResourceRead, Um as DelegationResumeContext, Vf as ResolvedSpawnResourcePath, Vm as DelegationArgs, Wf as SpawnResourceReader, Wm as DelegationResumeDriver, Xf as EventSubscription, Xm as SubmitOutput, Yf as createMcpServer, Ym as SubmitInput, Zf as EventSubscriptionStore, Zm as DelegateCodeArgs, ah as DelegationFeedbackSnapshot, b_ as Question, by as TraceContext, ch as DelegationProgress, cv as JsonRpcResponse, dh as DelegationStatusResult, dv as McpTransport, e_ as GitRunner, eh as DelegateResearchConfig, ep as DelegateError, fh as FeedbackRating, gh as UiAuditorDelegationOutput, hh as UiAuditLensFilter, ih as DelegationError, jh as DelegationStore, jm as detachedSessionDelegate, k_ as QuestionUrgency, kh as composeLoopTraceEmitters, km as DetachedWinnerSelection, lh as DelegationResultPayload, lv as McpToolAnnotations, mh as ResearchOutputShape, n_ as CoordinationEvent, nh as DelegateUiAuditConfig, np as DelegateResult, o_ as ManagerWake, oh as DelegationHistoryArgs, ph as FeedbackRefersTo, q as WorkerSpawnContext, qf as McpServer, qm as DelegationTaskQueue, rh as DelegateUiAuditRoute, rp as createDelegateHandler, sh as DelegationHistoryEntry, sv as JsonRpcMessage, t_ as AwaitWakeInput, th as DelegateUiAuditArgs, tp as DelegateHandlerOptions, uh as DelegationStatus, uv as McpToolDescriptor, wm as CoderDelegate, xy as createPropagatingTraceEmitter, z as MakeWorkerAgent, zm as RunDetachedTurnOptions } from "../types-KQkbyDmn.js";
1
+ import { $f as EventSubscriptionStore, $m as DelegateCodeArgs, Ah as DelegationTraceSpan, Am as DetachedSessionDelegateOptions, Bm as DetachedTurn, Cy as createPropagatingTraceEmitter, D_ as QuestionLevel, Dm as CoderReview, Dv as AnalystRegistry, Em as CoderDelegate, F as CoordinationTools, Fh as FileDelegationStoreOptions, Fm as FleetHandle, Fv as RunLocalHarnessOptions, G as SpawnRefusalCause, Gf as SpawnResourceRead, Gm as DelegationResumeContext, Hf as ResolveSpawnResourcePathsResult, Hm as runDetachedTurn, I as CoordinationToolsOptions, Ih as CoderOutput, Im as FleetWorkspaceExecutorOptions, Iv as runLocalHarness, Jf as resolveSpawnResourcePaths, Jm as DelegationRunContext, Kf as SpawnResourceReader, Km as DelegationResumeDriver, Lh as CoderTask, Lm as SiblingSandboxExecutorOptions, Lv as LOCAL_HARNESSES, Mh as DelegationPersistenceError, Mm as UiAuditorDelegate, Nh as DelegationStore, Nm as detachedSessionDelegate, O_ as QuestionOption, Of as CheckRead, Om as CoderReviewer, P as CoordinationStats, Ph as FileDelegationStore, Pm as DelegationExecutor, Qf as EventSubscription, Qm as SubmitOutput, Rm as createFleetWorkspaceExecutor, Rv as LocalHarness, S_ as Question, Sy as TraceContext, Tm as FeedbackStore, Uf as ResolvedSpawnResourcePath, Um as DelegationArgs, Vm as RunDetachedTurnOptions, Wf as SpawnResourceBytes, Wm as DelegationRecord, Xf as McpServerOptions, Xm as DelegationTaskQueueOptions, Yf as McpServer, Ym as DelegationTaskQueue, Zf as createMcpServer, Zm as SubmitInput, _h as UiAuditLensFilter, ah as DelegateUiAuditRoute, ap as createDelegateHandler, c_ as ManagerWake, ch as DelegationHistoryArgs, dh as DelegationResultPayload, dv as McpToolAnnotations, eh as DelegateCodeConfig, ep as McpEventRecord, fh as DelegationStatus, fv as McpToolDescriptor, gh as ResearchOutputShape, hh as FeedbackRefersTo, i_ as CoordinationEvent, ih as DelegateUiAuditConfig, ip as DelegateResult, j_ as QuestionUrgency, jh as composeLoopTraceEmitters, jm as DetachedWinnerSelection, km as DelegateRunCtx, lh as DelegationHistoryEntry, lv as JsonRpcMessage, mh as FeedbackRating, n_ as GitRunner, nh as DelegateResearchConfig, np as DelegateError, oh as DelegationError, ph as DelegationStatusResult, pv as McpTransport, q as WorkerSpawnContext, qf as environmentReader, qm as DelegationResumeTick, r_ as AwaitWakeInput, rh as DelegateUiAuditArgs, rp as DelegateHandlerOptions, sh as DelegationFeedbackSnapshot, th as DelegateResearchArgs, tp as McpEventSource, uh as DelegationProgress, uv as JsonRpcResponse, vh as UiAuditorDelegationOutput, wm as FeedbackEvent, wy as readTraceContextFromEnv, z as MakeWorkerAgent, zm as createSiblingSandboxExecutor } from "../types-DRijOelA.js";
2
2
  import { HarnessType } from "@tangle-network/agent-interface";
3
3
  /**
4
4
  *
package/dist/mcp/index.js CHANGED
@@ -1,12 +1,12 @@
1
1
  import { i as ConfigError, m as ValidationError } from "../errors-DG8yufqX.js";
2
- import { gt as selectValidWinner, h as runCoderChecks } from "../runtime-DXkdY7VT.js";
3
- import { a as DelegationTaskQueue, i as createDelegateHandler, o as FileDelegationStore, s as composeLoopTraceEmitters, t as createMcpServer } from "../server-D4nCyP5N.js";
2
+ import { gt as selectValidWinner, h as runCoderChecks } from "../runtime-Czu2SSMy.js";
3
+ import { a as DelegationTaskQueue, i as createDelegateHandler, o as FileDelegationStore, s as composeLoopTraceEmitters, t as createMcpServer } from "../server-Dbge7VDj.js";
4
4
  import { t as assertExecutableAgentProfile } from "../model-policy-CZwhXp8O.js";
5
- import { Ft as runWorktreeHarness, It as LOCAL_HARNESSES, O as runAgentRounds, j as createSandboxForSpec, k as assertBoxlessPromptOptions } from "../supervisor-ByKjr-4D.js";
6
- import { s as deleteBoxSafe, v as sleep, x as throwIfAborted } from "../util-fcckrkKp.js";
7
- import { n as createStdioToolServer } from "../tool-server-Df-Uy99W.js";
8
- import { t as createCoordinationTools } from "../coordination-manager-C0OJ1T9V.js";
9
- import { In as createPropagatingTraceEmitter, Rn as readTraceContextFromEnv, St as resolveSpawnResourcePaths, xt as environmentReader } from "../supervisor-accounting-CvpkFhZU.js";
5
+ import { Ft as runWorktreeHarness, It as LOCAL_HARNESSES, O as runAgentRounds, j as createSandboxForSpec, k as assertBoxlessPromptOptions } from "../supervisor-CdrDXnOJ.js";
6
+ import { s as deleteBoxSafe, v as sleep, x as throwIfAborted } from "../util-qsH5cC9S.js";
7
+ import { n as createStdioToolServer } from "../tool-server-CirrqFlr.js";
8
+ import { t as createCoordinationTools } from "../coordination-manager-B-Ugh18D.js";
9
+ import { In as createPropagatingTraceEmitter, Rn as readTraceContextFromEnv, St as resolveSpawnResourcePaths, xt as environmentReader } from "../supervisor-accounting-us4w7tG6.js";
10
10
  import { agentProfileSchema } from "@tangle-network/agent-interface";
11
11
  import { isRecord } from "@tangle-network/agent-core";
12
12
  import { randomUUID } from "node:crypto";
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { m as ValidationError } from "../errors-DG8yufqX.js";
3
- import { n as createStdioToolServer } from "../tool-server-Df-Uy99W.js";
3
+ import { n as createStdioToolServer } from "../tool-server-CirrqFlr.js";
4
4
  import { appendFileSync, mkdirSync, readFileSync } from "node:fs";
5
5
  import { dirname } from "node:path";
6
6
  // src/mcp/memory-server.ts
@@ -0,0 +1,331 @@
1
+ import { agentCandidateArtifactRefSchema, canonicalCandidateBytes as canonicalCandidateBytes$1 } from "@tangle-network/agent-interface";
2
+ import { createHash } from "node:crypto";
3
+ import { constants } from "node:fs";
4
+ import { dirname, isAbsolute, relative, resolve, sep } from "node:path";
5
+ import { lstat, open, readdir, readlink, realpath } from "node:fs/promises";
6
+ // src/candidate-execution/digest.ts
7
+ /** Use native hashing for workspace archives. */
8
+ function sha256Bytes$1(bytes) {
9
+ return `sha256:${createHash("sha256").update(bytes).digest("hex")}`;
10
+ }
11
+ function canonicalCandidateDigest$1(value) {
12
+ return sha256Bytes$1(canonicalCandidateBytes$1(value));
13
+ }
14
+ /** Returns a detached, deeply frozen JSON value with canonical number normalization. */
15
+ function immutableCandidateValue(value) {
16
+ return deepFreezeCandidate(JSON.parse(Buffer.from(canonicalCandidateBytes$1(value)).toString("utf8")));
17
+ }
18
+ function canonicalCandidateDocument(valueWithoutDigest) {
19
+ const bytes = canonicalCandidateBytes$1(valueWithoutDigest);
20
+ const digest = sha256Bytes$1(bytes);
21
+ const value = deepFreezeCandidate({
22
+ ...JSON.parse(Buffer.from(bytes).toString("utf8")),
23
+ digest
24
+ });
25
+ return Object.freeze({
26
+ value,
27
+ get bytes() {
28
+ return Uint8Array.from(bytes);
29
+ },
30
+ digest
31
+ });
32
+ }
33
+ function verifyCanonicalCandidateDocument(value, label) {
34
+ if (canonicalCandidateDigest$1(omitTopLevelDigest(value)) !== value.digest) throw new Error(`${label} digest does not match`);
35
+ return immutableCandidateValue(value);
36
+ }
37
+ function embeddedCandidateArtifact(bytes) {
38
+ return {
39
+ encoding: "base64",
40
+ content: Buffer.from(bytes).toString("base64"),
41
+ sha256: sha256Bytes$1(bytes),
42
+ byteLength: bytes.byteLength
43
+ };
44
+ }
45
+ function omitTopLevelDigest(value) {
46
+ const { digest: _digest, ...rest } = value;
47
+ return rest;
48
+ }
49
+ function deepFreezeCandidate(value, seen = /* @__PURE__ */ new Set()) {
50
+ if (value === null || typeof value !== "object" || ArrayBuffer.isView(value) || seen.has(value)) return value;
51
+ seen.add(value);
52
+ for (const child of Object.values(value)) deepFreezeCandidate(child, seen);
53
+ return Object.freeze(value);
54
+ }
55
+ // src/candidate-execution/artifacts.ts
56
+ function artifactCacheKey(artifact) {
57
+ return `${artifact.sha256}:${artifact.byteLength}`;
58
+ }
59
+ async function readVerifiedArtifact(artifact, port) {
60
+ const bytes = "content" in artifact ? Buffer.from(artifact.content, "base64") : await port.read(artifact);
61
+ verifyBytes(bytes, artifact.sha256, artifact.byteLength, "candidate artifact");
62
+ return Uint8Array.from(bytes);
63
+ }
64
+ function verifyBytes(bytes, digest, byteLength, label) {
65
+ if (bytes.byteLength !== byteLength) throw new Error(`${label} byte length ${bytes.byteLength} does not match ${byteLength}`);
66
+ const actual = sha256Bytes$1(bytes);
67
+ if (actual !== digest) throw new Error(`${label} digest ${actual} does not match ${digest}`);
68
+ }
69
+ async function verifyWorkspaceSnapshotArtifacts(snapshot, port) {
70
+ const [manifest, archive] = await Promise.all([readVerifiedArtifact(snapshot.manifest, port), readVerifiedArtifact(snapshot.archive, port)]);
71
+ const canonicalManifest = canonicalCandidateBytes$1(snapshot.material);
72
+ if (!Buffer.from(manifest).equals(Buffer.from(canonicalManifest))) throw new Error("workspace manifest artifact is not the exact canonical manifest material");
73
+ if (sha256Bytes$1(canonicalManifest) !== snapshot.digest) throw new Error("workspace snapshot digest does not match its canonical manifest material");
74
+ return {
75
+ manifest,
76
+ archive
77
+ };
78
+ }
79
+ /** A configured file-count or byte limit stopped workspace capture. */
80
+ var WorkspaceScanLimitError = class extends Error {};
81
+ /**
82
+ * Refuse a materialized workspace whose files, modes, or bytes are not the signed manifest.
83
+ *
84
+ * The scan streams, so the size of the largest file does not decide whether the check can run, and
85
+ * the refusal names the one mismatch a caller can produce on its own: a capture and a verify that
86
+ * disagree about `portableTree`.
87
+ */
88
+ async function verifyMaterializedWorkspace(root, expected, options = {}) {
89
+ assertWorkspaceManifest(await scanMaterializedWorkspaceManifest(root, options), expected);
90
+ }
91
+ /**
92
+ * The canonical manifest of one materialized workspace, read without holding any file.
93
+ *
94
+ * Every file is digested by streaming, so the size of the largest file does not decide whether the
95
+ * workspace can be described. `FileHandle.readFile` refuses anything above 2 GiB with
96
+ * `ERR_FS_FILE_TOO_LARGE`, which made a workspace holding one such artifact impossible to verify
97
+ * against a manifest it already matched. The digest is sha-256 over the same bytes either way, so
98
+ * a manifest a buffered read produced is reproduced exactly.
99
+ */
100
+ async function scanMaterializedWorkspaceManifest(root, options = {}) {
101
+ return workspaceManifestFromEntries(await walkWorkspace(root, options, false));
102
+ }
103
+ async function captureMaterializedWorkspace(root, options = {}) {
104
+ const entries = await walkWorkspace(root, options, true);
105
+ return {
106
+ manifest: workspaceManifestFromEntries(entries),
107
+ files: entries.map((entry) => ({
108
+ path: entry.path,
109
+ mode: entry.mode,
110
+ bytes: Uint8Array.from(capturedBytes(entry))
111
+ }))
112
+ };
113
+ }
114
+ /** Capture exact verified regular-file bytes for fresh isolated materialization. */
115
+ async function readMaterializedWorkspaceFiles(root, expected, options = {}) {
116
+ const observed = await captureMaterializedWorkspace(root, options);
117
+ assertWorkspaceManifest(observed.manifest, expected);
118
+ return observed.files.map((file) => Object.freeze({
119
+ path: file.path,
120
+ mode: file.mode,
121
+ bytes: Uint8Array.from(file.bytes)
122
+ }));
123
+ }
124
+ /**
125
+ * Build the canonical manifest for files a caller already holds — the shape a remote executor
126
+ * returns. Pass `portableTree` to record Git's two file modes instead of exact permission bits, and
127
+ * pass the same flag to every verify that reads the result.
128
+ */
129
+ function candidateWorkspaceManifest(files, options = {}) {
130
+ return workspaceManifestFromEntries(files.map((file) => ({
131
+ path: file.path,
132
+ mode: options.portableTree === true ? portableFileMode(file.mode) : file.mode,
133
+ sha256: sha256Bytes$1(file.bytes),
134
+ byteLength: file.bytes.byteLength
135
+ })));
136
+ }
137
+ function workspaceManifestFromEntries(entries) {
138
+ return {
139
+ kind: "agent-candidate-workspace-manifest",
140
+ files: entries.map((entry) => ({
141
+ path: entry.path,
142
+ mode: entry.mode,
143
+ sha256: entry.sha256,
144
+ byteLength: entry.byteLength
145
+ })).sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0)
146
+ };
147
+ }
148
+ /** Git records exactly two file modes, and a portable-tree scan records the same two. */
149
+ function portableFileMode(mode) {
150
+ return (mode & 73) !== 0 ? 493 : 420;
151
+ }
152
+ function capturedBytes(entry) {
153
+ if (!entry.bytes) throw new Error(`workspace file was digested without its bytes: ${entry.path}`);
154
+ return entry.bytes;
155
+ }
156
+ function assertWorkspaceManifest(observed, expected) {
157
+ if (Buffer.from(canonicalCandidateBytes$1(observed)).equals(canonicalCandidateBytes$1(expected))) return;
158
+ if (Buffer.from(canonicalCandidateBytes$1(withPortableModes(observed))).equals(canonicalCandidateBytes$1(withPortableModes(expected)))) throw new Error("materialized workspace files do not match the signed manifest: only the file modes differ, so the capture and this verify disagree about portableTree");
159
+ throw new Error("materialized workspace files, modes, or bytes do not match the signed manifest");
160
+ }
161
+ function withPortableModes(material) {
162
+ return {
163
+ ...material,
164
+ files: material.files.map((file) => ({
165
+ ...file,
166
+ mode: portableFileMode(file.mode)
167
+ }))
168
+ };
169
+ }
170
+ async function verifyMaterializedProfileWorkspace(root, expected, fileRoot = "workspace") {
171
+ const observedProfile = (await scanMaterializedWorkspaceManifest(root)).files.map(({ path, mode, sha256 }) => ({
172
+ relPath: path,
173
+ mode,
174
+ contentSha256: sha256
175
+ }));
176
+ const expectedFiles = expected.files.filter((file) => (file.root ?? "workspace") === fileRoot).map(({ root: _root, ...file }) => file);
177
+ if (!Buffer.from(canonicalCandidateBytes$1(observedProfile)).equals(canonicalCandidateBytes$1(expectedFiles))) throw new Error(`profile ${fileRoot} staging files, modes, or bytes do not match the signed profile plan`);
178
+ }
179
+ async function walkWorkspace(root, options, keepBytes) {
180
+ const ignoredProtectedRootEntries = new Set(options.ignoredProtectedRootEntries ?? []);
181
+ const excluded = new Set(options.excludedPaths ?? []);
182
+ for (const path of excluded) if (!path || path.includes("\\") || path.includes("\0") || isAbsolute(path) || path.split("/").some((part) => !part || part === "." || part === "..")) throw new Error("workspace excluded path must be a safe relative path");
183
+ const limits = options.limits;
184
+ const selected = options.selectedPaths ? new Set(options.selectedPaths) : void 0;
185
+ const selectedDirectories = /* @__PURE__ */ new Set();
186
+ for (const path of selected ?? []) {
187
+ if (!path || path.includes("\\") || path.includes("\0") || isAbsolute(path) || path.split("/").some((part) => !part || part === "." || part === "..")) throw new Error("workspace selected path must be a safe relative file path");
188
+ let parent = dirname(path);
189
+ while (parent !== ".") {
190
+ selectedDirectories.add(parent);
191
+ parent = dirname(parent);
192
+ }
193
+ }
194
+ const requestedRoot = resolve(root);
195
+ const rootStats = await lstat(requestedRoot);
196
+ if (!rootStats.isDirectory() || rootStats.isSymbolicLink()) throw new Error("workspace root must be a real directory");
197
+ const absoluteRoot = await realpath(requestedRoot);
198
+ const resolvedStats = await lstat(absoluteRoot);
199
+ if (!resolvedStats.isDirectory() || resolvedStats.isSymbolicLink()) throw new Error("workspace root must resolve to a real directory");
200
+ const scanned = [];
201
+ let totalBytes = 0;
202
+ async function visit(directory) {
203
+ options.signal?.throwIfAborted();
204
+ const entries = await readdir(directory, { withFileTypes: true });
205
+ entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
206
+ for (const entry of entries) {
207
+ options.signal?.throwIfAborted();
208
+ if (directory === absoluteRoot && ignoredProtectedRootEntries.has(entry.name)) continue;
209
+ if (options.skipPythonBytecode === true && (entry.isDirectory() && entry.name === "__pycache__" || entry.isFile() && entry.name.endsWith(".pyc"))) continue;
210
+ const absolute = resolve(directory, entry.name);
211
+ const relPath = relative(absoluteRoot, absolute).split(sep).join("/");
212
+ if (!relPath || relPath.startsWith("../") || relPath.includes("/../")) throw new Error(`workspace entry escapes root: ${relPath}`);
213
+ if (excluded.has(relPath)) continue;
214
+ if (selected && !selected.has(relPath) && !selectedDirectories.has(relPath)) continue;
215
+ const stats = await lstat(absolute);
216
+ if (stats.isSymbolicLink()) throw new Error(await symlinkRefusal(absolute, relPath, absoluteRoot));
217
+ if (stats.isDirectory()) {
218
+ if (selected?.has(relPath)) throw new Error(`workspace selected file is a directory: ${relPath}`);
219
+ await visit(absolute);
220
+ continue;
221
+ }
222
+ if (!stats.isFile()) throw new Error(`workspace contains a non-regular entry: ${relPath}`);
223
+ if (limits && scanned.length >= limits.maxFiles) throw new WorkspaceScanLimitError("workspace exceeds maxFiles");
224
+ const descriptor = await open(absolute, constants.O_RDONLY | (typeof constants.O_NOFOLLOW === "number" ? constants.O_NOFOLLOW : 0));
225
+ try {
226
+ const openedStats = await descriptor.stat();
227
+ if (!openedStats.isFile()) throw new Error(`workspace contains a non-regular entry: ${relPath}`);
228
+ if (openedStats.nlink !== 1) throw new Error(`workspace contains a hard-linked file: ${relPath}`);
229
+ const mode = options.portableTree === true ? portableFileMode(openedStats.mode) : openedStats.mode & 511;
230
+ if (limits && openedStats.size > limits.maxFileBytes) throw new WorkspaceScanLimitError(`workspace file exceeds maxFileBytes: ${relPath}`);
231
+ const remainingBytes = limits ? limits.maxTotalFileBytes - totalBytes : void 0;
232
+ if (remainingBytes !== void 0 && openedStats.size > remainingBytes) throw new WorkspaceScanLimitError("workspace exceeds maxTotalFileBytes");
233
+ const read = await readWorkspaceFile(descriptor, limits ? Math.min(limits.maxFileBytes, remainingBytes ?? limits.maxFileBytes) : void 0, keepBytes, relPath, options.signal);
234
+ totalBytes += read.byteLength;
235
+ scanned.push({
236
+ path: relPath,
237
+ mode,
238
+ sha256: read.sha256,
239
+ byteLength: read.byteLength,
240
+ ...read.bytes === void 0 ? {} : { bytes: read.bytes }
241
+ });
242
+ } finally {
243
+ await descriptor.close();
244
+ }
245
+ }
246
+ }
247
+ await visit(absoluteRoot);
248
+ if (selected && scanned.length !== selected.size) throw new Error("workspace selected files changed during capture");
249
+ return scanned;
250
+ }
251
+ /**
252
+ * Why one symbolic link is refused, in the terms that separate a portable link from a link that
253
+ * reaches outside the tree.
254
+ *
255
+ * Every link is refused, in both mode policies. `AgentCandidateWorkspaceManifestMaterial` has no
256
+ * representation for one — `mode`, `sha256` and `byteLength` describe a regular file — so a link
257
+ * recorded as a file would let two different trees share one digest. The reason says which kind of
258
+ * link it was, so a caller can tell a link it can rewrite from one it cannot.
259
+ */
260
+ async function symlinkRefusal(absolute, relPath, absoluteRoot) {
261
+ const target = await readlink(absolute);
262
+ if (isAbsolute(target)) return `workspace contains an absolute symlink: ${relPath} -> ${target}`;
263
+ if (!isWithin(absoluteRoot, resolve(dirname(absolute), target))) return `workspace contains a symlink that escapes its tree: ${relPath} -> ${target}`;
264
+ let physical;
265
+ try {
266
+ physical = await realpath(absolute);
267
+ } catch {
268
+ return `workspace contains an unresolved symlink: ${relPath} -> ${target}`;
269
+ }
270
+ if (!isWithin(absoluteRoot, physical)) return `workspace contains a symlink that resolves outside its tree: ${relPath} -> ${target}`;
271
+ return `workspace contains a symlink: ${relPath} -> ${target}`;
272
+ }
273
+ function isWithin(root, path) {
274
+ return path === root || path.startsWith(`${root}${sep}`);
275
+ }
276
+ /**
277
+ * Read one open regular file into its digest, keeping the bytes only when the caller needs them.
278
+ *
279
+ * The content reaches the hash in 1 MiB chunks and is never held whole for a digest-only walk, so
280
+ * the size of the largest file does not decide whether a workspace can be described.
281
+ * `FileHandle.readFile` refuses anything above 2 GiB with `ERR_FS_FILE_TOO_LARGE`. Hashing the
282
+ * chunks in order equals hashing the whole buffer, so a manifest a buffered read produced is
283
+ * reproduced byte for byte.
284
+ */
285
+ async function readWorkspaceFile(descriptor, maxBytes, keepBytes, path, signal) {
286
+ const hash = createHash("sha256");
287
+ const buffer = Buffer.allocUnsafe(1048576);
288
+ const chunks = [];
289
+ let total = 0;
290
+ while (true) {
291
+ signal?.throwIfAborted();
292
+ const { bytesRead } = await descriptor.read(buffer, 0, buffer.byteLength, null);
293
+ if (bytesRead === 0) break;
294
+ total += bytesRead;
295
+ if (maxBytes !== void 0 && total > maxBytes) throw new WorkspaceScanLimitError(`workspace file exceeds its capture limit: ${path}`);
296
+ const chunk = buffer.subarray(0, bytesRead);
297
+ hash.update(chunk);
298
+ if (keepBytes) chunks.push(Buffer.from(chunk));
299
+ }
300
+ const sha256 = `sha256:${hash.digest("hex")}`;
301
+ return keepBytes ? {
302
+ sha256,
303
+ byteLength: total,
304
+ bytes: Buffer.concat(chunks, total)
305
+ } : {
306
+ sha256,
307
+ byteLength: total
308
+ };
309
+ }
310
+ // src/candidate-execution/output-artifacts.ts
311
+ /** Persist evaluator evidence, read it back, and bind the returned locator to the exact bytes. */
312
+ async function persistCandidateOutputArtifact(port, input) {
313
+ input.signal?.throwIfAborted();
314
+ const bytes = Uint8Array.from(input.bytes);
315
+ const expectedDigest = sha256Bytes$1(bytes);
316
+ const ref = agentCandidateArtifactRefSchema.parse(await port.put({
317
+ executionId: input.executionId,
318
+ purpose: input.purpose,
319
+ bytes: Uint8Array.from(bytes),
320
+ ...input.signal ? { signal: input.signal } : {}
321
+ }));
322
+ input.signal?.throwIfAborted();
323
+ if (ref.sha256 !== expectedDigest || ref.byteLength !== bytes.byteLength) throw new Error("candidate output locator does not identify the submitted bytes");
324
+ const stored = await port.read(ref);
325
+ input.signal?.throwIfAborted();
326
+ verifyBytes(stored, expectedDigest, bytes.byteLength, "persisted candidate output");
327
+ return immutableCandidateValue(ref);
328
+ }
329
+ export { embeddedCandidateArtifact as _, captureMaterializedWorkspace as a, sha256Bytes$1 as b, scanMaterializedWorkspaceManifest as c, verifyMaterializedWorkspace as d, verifyWorkspaceSnapshotArtifacts as f, deepFreezeCandidate as g, canonicalCandidateDocument as h, candidateWorkspaceManifest as i, verifyBytes as l, canonicalCandidateDigest$1 as m, WorkspaceScanLimitError as n, readMaterializedWorkspaceFiles as o, canonicalCandidateBytes$1 as p, artifactCacheKey as r, readVerifiedArtifact as s, persistCandidateOutputArtifact as t, verifyMaterializedProfileWorkspace as u, immutableCandidateValue as v, verifyCanonicalCandidateDocument as x, omitTopLevelDigest as y };
330
+
331
+ //# sourceMappingURL=output-artifacts-AqkZ8lO2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"output-artifacts-AqkZ8lO2.js","names":["sha256Bytes","canonicalCandidateDigest","canonicalCandidateBytes","sha256Bytes","canonicalCandidateBytes","fsConstants","sha256Bytes"],"sources":["../src/candidate-execution/digest.ts","../src/candidate-execution/artifacts.ts","../src/candidate-execution/output-artifacts.ts"],"sourcesContent":["import { createHash } from 'node:crypto'\nimport {\n type AgentCandidateEmbeddedArtifact,\n canonicalCandidateBytes,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\n\nimport type { CanonicalCandidateDocument } from './types'\n\nexport { canonicalCandidateBytes }\n\n/** Use native hashing for workspace archives. */\nexport function sha256Bytes(bytes: Uint8Array): Sha256Digest {\n return `sha256:${createHash('sha256').update(bytes).digest('hex')}`\n}\n\nexport function canonicalCandidateDigest(value: unknown): Sha256Digest {\n return sha256Bytes(canonicalCandidateBytes(value))\n}\n\n/** Returns a detached, deeply frozen JSON value with canonical number normalization. */\nexport function immutableCandidateValue<T>(value: T): T {\n return deepFreezeCandidate(\n JSON.parse(Buffer.from(canonicalCandidateBytes(value)).toString('utf8')) as T,\n )\n}\n\nexport function canonicalCandidateDocument<T extends { digest: Sha256Digest }>(\n valueWithoutDigest: Omit<T, 'digest'>,\n): CanonicalCandidateDocument<T> {\n const bytes = canonicalCandidateBytes(valueWithoutDigest)\n const digest = sha256Bytes(bytes)\n const value = deepFreezeCandidate({\n ...JSON.parse(Buffer.from(bytes).toString('utf8')),\n digest,\n }) as T\n return Object.freeze({\n value,\n get bytes(): Uint8Array {\n return Uint8Array.from(bytes)\n },\n digest,\n })\n}\n\nexport function verifyCanonicalCandidateDocument<T extends { digest: Sha256Digest }>(\n value: T,\n label: string,\n): T {\n if (canonicalCandidateDigest(omitTopLevelDigest(value)) !== value.digest) {\n throw new Error(`${label} digest does not match`)\n }\n return immutableCandidateValue(value)\n}\n\nexport function embeddedCandidateArtifact(bytes: Uint8Array): AgentCandidateEmbeddedArtifact {\n return {\n encoding: 'base64',\n content: Buffer.from(bytes).toString('base64'),\n sha256: sha256Bytes(bytes),\n byteLength: bytes.byteLength,\n }\n}\n\nexport function omitTopLevelDigest<T extends { digest: Sha256Digest }>(\n value: T,\n): Omit<T, 'digest'> {\n const { digest: _digest, ...rest } = value\n return rest\n}\n\nexport function deepFreezeCandidate<T>(value: T, seen = new Set<object>()): T {\n if (\n value === null ||\n typeof value !== 'object' ||\n ArrayBuffer.isView(value) ||\n seen.has(value as object)\n ) {\n return value\n }\n seen.add(value as object)\n for (const child of Object.values(value as Record<string, unknown>)) {\n deepFreezeCandidate(child, seen)\n }\n return Object.freeze(value)\n}\n","import { createHash } from 'node:crypto'\nimport { constants as fsConstants } from 'node:fs'\nimport { lstat, open, readdir, readlink, realpath } from 'node:fs/promises'\nimport { dirname, isAbsolute, relative, resolve, sep } from 'node:path'\n\nimport type {\n AgentCandidateArtifactRef,\n AgentCandidateCapturedArtifact,\n AgentCandidateProfilePlanMaterial,\n AgentCandidateWorkspaceManifestMaterial,\n AgentCandidateWorkspaceSnapshotEvidence,\n Sha256Digest,\n} from '@tangle-network/agent-interface'\n\nimport { canonicalCandidateBytes, sha256Bytes } from './digest'\nimport type { AgentCandidateArtifactPort } from './types'\n\nexport function artifactCacheKey(artifact: AgentCandidateCapturedArtifact): string {\n return `${artifact.sha256}:${artifact.byteLength}`\n}\n\nexport async function readVerifiedArtifact(\n artifact: AgentCandidateCapturedArtifact,\n port: AgentCandidateArtifactPort,\n): Promise<Uint8Array> {\n const bytes =\n 'content' in artifact\n ? Buffer.from(artifact.content, 'base64')\n : await port.read(artifact as AgentCandidateArtifactRef)\n verifyBytes(bytes, artifact.sha256, artifact.byteLength, 'candidate artifact')\n return Uint8Array.from(bytes)\n}\n\nexport function verifyBytes(\n bytes: Uint8Array,\n digest: string,\n byteLength: number,\n label: string,\n): void {\n if (bytes.byteLength !== byteLength) {\n throw new Error(`${label} byte length ${bytes.byteLength} does not match ${byteLength}`)\n }\n const actual = sha256Bytes(bytes)\n if (actual !== digest) {\n throw new Error(`${label} digest ${actual} does not match ${digest}`)\n }\n}\n\nexport async function verifyWorkspaceSnapshotArtifacts(\n snapshot: AgentCandidateWorkspaceSnapshotEvidence,\n port: AgentCandidateArtifactPort,\n): Promise<{ manifest: Uint8Array; archive: Uint8Array }> {\n const [manifest, archive] = await Promise.all([\n readVerifiedArtifact(snapshot.manifest, port),\n readVerifiedArtifact(snapshot.archive, port),\n ])\n const canonicalManifest = canonicalCandidateBytes(snapshot.material)\n if (!Buffer.from(manifest).equals(Buffer.from(canonicalManifest))) {\n throw new Error('workspace manifest artifact is not the exact canonical manifest material')\n }\n if (sha256Bytes(canonicalManifest) !== snapshot.digest) {\n throw new Error('workspace snapshot digest does not match its canonical manifest material')\n }\n return { manifest, archive }\n}\n\n/** The per-scan caps a bounded capture applies. */\nexport interface WorkspaceScanLimits {\n readonly maxFiles: number\n readonly maxFileBytes: number\n readonly maxTotalFileBytes: number\n}\n\n/** A configured file-count or byte limit stopped workspace capture. */\nexport class WorkspaceScanLimitError extends Error {}\n\n/** What a workspace scan reads and how it records a file's permission bits. */\nexport interface WorkspaceScanOptions {\n readonly signal?: AbortSignal\n readonly ignoredProtectedRootEntries?: readonly ('.git' | '.sidecar')[]\n /**\n * Root-relative files or directories left out, each by its exact path (`__retention__` or\n * `__retention__/sessions/<id>`). A verify of the same root must name the same paths.\n */\n readonly excludedPaths?: readonly string[]\n readonly limits?: WorkspaceScanLimits\n /** Scan only these root-relative files, pruning every unrelated directory. */\n readonly selectedPaths?: readonly string[]\n /**\n * Record Git's two file modes instead of the filesystem's exact permission bits: `0o755` when\n * any execute bit is set, `0o644` otherwise. A checkout umask then cannot move a manifest\n * digest, while a real permission change still does.\n *\n * This is the normalization `readCandidateGitTreeFiles` already applies to a Git tree\n * (`100644`/`100755`), so one tree scanned from disk and the same tree read out of Git produce\n * the same manifest. Off by default: the flag changes the digest, so a capture and the verify\n * that checks it must agree on it.\n */\n readonly portableTree?: boolean\n}\n\n/**\n * Refuse a materialized workspace whose files, modes, or bytes are not the signed manifest.\n *\n * The scan streams, so the size of the largest file does not decide whether the check can run, and\n * the refusal names the one mismatch a caller can produce on its own: a capture and a verify that\n * disagree about `portableTree`.\n */\nexport async function verifyMaterializedWorkspace(\n root: string,\n expected: AgentCandidateWorkspaceManifestMaterial,\n options: Omit<WorkspaceScanOptions, 'limits'> = {},\n): Promise<void> {\n assertWorkspaceManifest(await scanMaterializedWorkspaceManifest(root, options), expected)\n}\n\n/**\n * The canonical manifest of one materialized workspace, read without holding any file.\n *\n * Every file is digested by streaming, so the size of the largest file does not decide whether the\n * workspace can be described. `FileHandle.readFile` refuses anything above 2 GiB with\n * `ERR_FS_FILE_TOO_LARGE`, which made a workspace holding one such artifact impossible to verify\n * against a manifest it already matched. The digest is sha-256 over the same bytes either way, so\n * a manifest a buffered read produced is reproduced exactly.\n */\nexport async function scanMaterializedWorkspaceManifest(\n root: string,\n options: WorkspaceScanOptions = {},\n): Promise<AgentCandidateWorkspaceManifestMaterial> {\n return workspaceManifestFromEntries(await walkWorkspace(root, options, false))\n}\n\n/**\n * Capture settings Runtime's own callers may add. `skipPythonBytecode` leaves out `__pycache__/`\n * directories and `*.pyc` files: the interpreter writes them beside the sources it runs, Git\n * ignores them, and each carries its source's modification time, so a digest that covered them\n * would change when a program was merely run and could not be reproduced from any checkout.\n */\ninterface WorkspaceCaptureOptions extends WorkspaceScanOptions {\n readonly skipPythonBytecode?: boolean\n}\n\nexport async function captureMaterializedWorkspace(\n root: string,\n options: WorkspaceCaptureOptions = {},\n): Promise<{\n manifest: AgentCandidateWorkspaceManifestMaterial\n files: ReadonlyArray<{ path: string; mode: number; bytes: Uint8Array }>\n}> {\n const entries = await walkWorkspace(root, options, true)\n return {\n manifest: workspaceManifestFromEntries(entries),\n files: entries.map((entry) => ({\n path: entry.path,\n mode: entry.mode,\n bytes: Uint8Array.from(capturedBytes(entry)),\n })),\n }\n}\n\n/** Capture exact verified regular-file bytes for fresh isolated materialization. */\nexport async function readMaterializedWorkspaceFiles(\n root: string,\n expected: AgentCandidateWorkspaceManifestMaterial,\n options: WorkspaceScanOptions = {},\n): Promise<ReadonlyArray<{ path: string; mode: number; bytes: Uint8Array }>> {\n const observed = await captureMaterializedWorkspace(root, options)\n assertWorkspaceManifest(observed.manifest, expected)\n return observed.files.map((file) =>\n Object.freeze({ path: file.path, mode: file.mode, bytes: Uint8Array.from(file.bytes) }),\n )\n}\n\n/**\n * Build the canonical manifest for files a caller already holds — the shape a remote executor\n * returns. Pass `portableTree` to record Git's two file modes instead of exact permission bits, and\n * pass the same flag to every verify that reads the result.\n */\nexport function candidateWorkspaceManifest(\n files: ReadonlyArray<{ path: string; mode: number; bytes: Uint8Array }>,\n options: { portableTree?: boolean } = {},\n): AgentCandidateWorkspaceManifestMaterial {\n return workspaceManifestFromEntries(\n files.map((file) => ({\n path: file.path,\n mode: options.portableTree === true ? portableFileMode(file.mode) : file.mode,\n sha256: sha256Bytes(file.bytes),\n byteLength: file.bytes.byteLength,\n })),\n )\n}\n\nfunction workspaceManifestFromEntries(\n entries: ReadonlyArray<{\n path: string\n mode: number\n sha256: Sha256Digest\n byteLength: number\n }>,\n): AgentCandidateWorkspaceManifestMaterial {\n return {\n kind: 'agent-candidate-workspace-manifest',\n files: entries\n .map((entry) => ({\n path: entry.path,\n mode: entry.mode,\n sha256: entry.sha256,\n byteLength: entry.byteLength,\n }))\n .sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0)),\n }\n}\n\n/** Git records exactly two file modes, and a portable-tree scan records the same two. */\nfunction portableFileMode(mode: number): number {\n return (mode & 0o111) !== 0 ? 0o755 : 0o644\n}\n\nfunction capturedBytes(entry: ScannedWorkspaceEntry): Buffer {\n if (!entry.bytes) throw new Error(`workspace file was digested without its bytes: ${entry.path}`)\n return entry.bytes\n}\n\nfunction assertWorkspaceManifest(\n observed: AgentCandidateWorkspaceManifestMaterial,\n expected: AgentCandidateWorkspaceManifestMaterial,\n): void {\n if (Buffer.from(canonicalCandidateBytes(observed)).equals(canonicalCandidateBytes(expected))) {\n return\n }\n // The one mismatch a caller can produce by passing `portableTree` on one side of a\n // capture/verify pair and not the other. Named, because the general refusal below reads as\n // changed bytes and would send a reader looking for a file that never changed. Comparing the\n // two manifests already in hand costs no second walk.\n if (\n Buffer.from(canonicalCandidateBytes(withPortableModes(observed))).equals(\n canonicalCandidateBytes(withPortableModes(expected)),\n )\n ) {\n throw new Error(\n 'materialized workspace files do not match the signed manifest: only the file modes differ, ' +\n 'so the capture and this verify disagree about portableTree',\n )\n }\n throw new Error('materialized workspace files, modes, or bytes do not match the signed manifest')\n}\n\nfunction withPortableModes(\n material: AgentCandidateWorkspaceManifestMaterial,\n): AgentCandidateWorkspaceManifestMaterial {\n return {\n ...material,\n files: material.files.map((file) => ({ ...file, mode: portableFileMode(file.mode) })),\n }\n}\n\nexport async function verifyMaterializedProfileWorkspace(\n root: string,\n expected: AgentCandidateProfilePlanMaterial,\n fileRoot: 'workspace' | 'agent' = 'workspace',\n): Promise<void> {\n const observed = await scanMaterializedWorkspaceManifest(root)\n const observedProfile = observed.files.map(({ path, mode, sha256 }) => ({\n relPath: path,\n mode,\n contentSha256: sha256,\n }))\n const expectedFiles = expected.files\n .filter((file) => (file.root ?? 'workspace') === fileRoot)\n .map(({ root: _root, ...file }) => file)\n if (\n !Buffer.from(canonicalCandidateBytes(observedProfile)).equals(\n canonicalCandidateBytes(expectedFiles),\n )\n ) {\n throw new Error(\n `profile ${fileRoot} staging files, modes, or bytes do not match the signed profile plan`,\n )\n }\n}\n\ninterface ScannedWorkspaceEntry {\n readonly path: string\n readonly mode: number\n readonly sha256: Sha256Digest\n readonly byteLength: number\n /** Present only when the walk was asked to keep bytes. */\n readonly bytes?: Buffer\n}\n\nasync function walkWorkspace(\n root: string,\n options: WorkspaceCaptureOptions,\n keepBytes: boolean,\n): Promise<ScannedWorkspaceEntry[]> {\n const ignoredProtectedRootEntries = new Set<string>(options.ignoredProtectedRootEntries ?? [])\n const excluded = new Set(options.excludedPaths ?? [])\n for (const path of excluded) {\n if (\n !path ||\n path.includes('\\\\') ||\n path.includes('\\0') ||\n isAbsolute(path) ||\n path.split('/').some((part) => !part || part === '.' || part === '..')\n ) {\n throw new Error('workspace excluded path must be a safe relative path')\n }\n }\n const limits = options.limits\n const selected = options.selectedPaths ? new Set(options.selectedPaths) : undefined\n const selectedDirectories = new Set<string>()\n for (const path of selected ?? []) {\n if (\n !path ||\n path.includes('\\\\') ||\n path.includes('\\0') ||\n isAbsolute(path) ||\n path.split('/').some((part) => !part || part === '.' || part === '..')\n ) {\n throw new Error('workspace selected path must be a safe relative file path')\n }\n let parent = dirname(path)\n while (parent !== '.') {\n selectedDirectories.add(parent)\n parent = dirname(parent)\n }\n }\n // Scan the RESOLVED root. The property this guards is that every captured path lies under\n // one real directory with no aliasing, which resolving satisfies directly — rejecting a\n // symlinked prefix outright does not, and makes the scan impossible on macOS, where the\n // OS itself hands out temp paths under /var, a symlink to /private/var. Symlinks INSIDE\n // the workspace are still refused entry by entry below, with O_NOFOLLOW on every open.\n const requestedRoot = resolve(root)\n const rootStats = await lstat(requestedRoot)\n if (!rootStats.isDirectory() || rootStats.isSymbolicLink()) {\n throw new Error('workspace root must be a real directory')\n }\n const absoluteRoot = await realpath(requestedRoot)\n const resolvedStats = await lstat(absoluteRoot)\n if (!resolvedStats.isDirectory() || resolvedStats.isSymbolicLink()) {\n throw new Error('workspace root must resolve to a real directory')\n }\n const scanned: ScannedWorkspaceEntry[] = []\n let totalBytes = 0\n\n async function visit(directory: string): Promise<void> {\n options.signal?.throwIfAborted()\n const entries = await readdir(directory, { withFileTypes: true })\n entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))\n for (const entry of entries) {\n options.signal?.throwIfAborted()\n if (directory === absoluteRoot && ignoredProtectedRootEntries.has(entry.name)) {\n continue\n }\n if (\n options.skipPythonBytecode === true &&\n ((entry.isDirectory() && entry.name === '__pycache__') ||\n (entry.isFile() && entry.name.endsWith('.pyc')))\n ) {\n continue\n }\n const absolute = resolve(directory, entry.name)\n const relPath = relative(absoluteRoot, absolute).split(sep).join('/')\n if (!relPath || relPath.startsWith('../') || relPath.includes('/../')) {\n throw new Error(`workspace entry escapes root: ${relPath}`)\n }\n if (excluded.has(relPath)) continue\n if (selected && !selected.has(relPath) && !selectedDirectories.has(relPath)) continue\n const stats = await lstat(absolute)\n if (stats.isSymbolicLink()) {\n throw new Error(await symlinkRefusal(absolute, relPath, absoluteRoot))\n }\n if (stats.isDirectory()) {\n if (selected?.has(relPath))\n throw new Error(`workspace selected file is a directory: ${relPath}`)\n await visit(absolute)\n continue\n }\n if (!stats.isFile()) {\n throw new Error(`workspace contains a non-regular entry: ${relPath}`)\n }\n if (limits && scanned.length >= limits.maxFiles) {\n throw new WorkspaceScanLimitError('workspace exceeds maxFiles')\n }\n const descriptor = await open(\n absolute,\n fsConstants.O_RDONLY |\n (typeof fsConstants.O_NOFOLLOW === 'number' ? fsConstants.O_NOFOLLOW : 0),\n )\n try {\n const openedStats = await descriptor.stat()\n if (!openedStats.isFile()) {\n throw new Error(`workspace contains a non-regular entry: ${relPath}`)\n }\n if (openedStats.nlink !== 1) {\n throw new Error(`workspace contains a hard-linked file: ${relPath}`)\n }\n const mode =\n options.portableTree === true\n ? portableFileMode(openedStats.mode)\n : openedStats.mode & 0o777\n if (limits && openedStats.size > limits.maxFileBytes) {\n throw new WorkspaceScanLimitError(`workspace file exceeds maxFileBytes: ${relPath}`)\n }\n const remainingBytes = limits ? limits.maxTotalFileBytes - totalBytes : undefined\n if (remainingBytes !== undefined && openedStats.size > remainingBytes) {\n throw new WorkspaceScanLimitError('workspace exceeds maxTotalFileBytes')\n }\n const read = await readWorkspaceFile(\n descriptor,\n limits ? Math.min(limits.maxFileBytes, remainingBytes ?? limits.maxFileBytes) : undefined,\n keepBytes,\n relPath,\n options.signal,\n )\n totalBytes += read.byteLength\n scanned.push({\n path: relPath,\n mode,\n sha256: read.sha256,\n byteLength: read.byteLength,\n ...(read.bytes === undefined ? {} : { bytes: read.bytes }),\n })\n } finally {\n await descriptor.close()\n }\n }\n }\n\n await visit(absoluteRoot)\n if (selected && scanned.length !== selected.size) {\n throw new Error('workspace selected files changed during capture')\n }\n return scanned\n}\n\n/**\n * Why one symbolic link is refused, in the terms that separate a portable link from a link that\n * reaches outside the tree.\n *\n * Every link is refused, in both mode policies. `AgentCandidateWorkspaceManifestMaterial` has no\n * representation for one — `mode`, `sha256` and `byteLength` describe a regular file — so a link\n * recorded as a file would let two different trees share one digest. The reason says which kind of\n * link it was, so a caller can tell a link it can rewrite from one it cannot.\n */\nasync function symlinkRefusal(\n absolute: string,\n relPath: string,\n absoluteRoot: string,\n): Promise<string> {\n const target = await readlink(absolute)\n if (isAbsolute(target)) {\n return `workspace contains an absolute symlink: ${relPath} -> ${target}`\n }\n if (!isWithin(absoluteRoot, resolve(dirname(absolute), target))) {\n return `workspace contains a symlink that escapes its tree: ${relPath} -> ${target}`\n }\n let physical: string\n try {\n physical = await realpath(absolute)\n } catch {\n return `workspace contains an unresolved symlink: ${relPath} -> ${target}`\n }\n if (!isWithin(absoluteRoot, physical)) {\n return `workspace contains a symlink that resolves outside its tree: ${relPath} -> ${target}`\n }\n return `workspace contains a symlink: ${relPath} -> ${target}`\n}\n\nfunction isWithin(root: string, path: string): boolean {\n return path === root || path.startsWith(`${root}${sep}`)\n}\n\n/**\n * Read one open regular file into its digest, keeping the bytes only when the caller needs them.\n *\n * The content reaches the hash in 1 MiB chunks and is never held whole for a digest-only walk, so\n * the size of the largest file does not decide whether a workspace can be described.\n * `FileHandle.readFile` refuses anything above 2 GiB with `ERR_FS_FILE_TOO_LARGE`. Hashing the\n * chunks in order equals hashing the whole buffer, so a manifest a buffered read produced is\n * reproduced byte for byte.\n */\nasync function readWorkspaceFile(\n descriptor: Awaited<ReturnType<typeof open>>,\n maxBytes: number | undefined,\n keepBytes: boolean,\n path: string,\n signal?: AbortSignal,\n): Promise<{ sha256: Sha256Digest; byteLength: number; bytes?: Buffer }> {\n const hash = createHash('sha256')\n const buffer = Buffer.allocUnsafe(1024 * 1024)\n const chunks: Buffer[] = []\n let total = 0\n while (true) {\n signal?.throwIfAborted()\n const { bytesRead } = await descriptor.read(buffer, 0, buffer.byteLength, null)\n if (bytesRead === 0) break\n total += bytesRead\n if (maxBytes !== undefined && total > maxBytes) {\n throw new WorkspaceScanLimitError(`workspace file exceeds its capture limit: ${path}`)\n }\n const chunk = buffer.subarray(0, bytesRead)\n hash.update(chunk)\n // The read buffer is reused, so a kept chunk has to be copied out of it.\n if (keepBytes) chunks.push(Buffer.from(chunk))\n }\n const sha256 = `sha256:${hash.digest('hex')}` as Sha256Digest\n return keepBytes\n ? { sha256, byteLength: total, bytes: Buffer.concat(chunks, total) }\n : { sha256, byteLength: total }\n}\n","import {\n type AgentCandidateArtifactRef,\n agentCandidateArtifactRefSchema,\n} from '@tangle-network/agent-interface'\n\nimport { verifyBytes } from './artifacts'\nimport { immutableCandidateValue, sha256Bytes } from './digest'\nimport type { AgentCandidateOutputArtifactPort, AgentCandidateOutputPurpose } from './types'\n\n/** Persist evaluator evidence, read it back, and bind the returned locator to the exact bytes. */\nexport async function persistCandidateOutputArtifact(\n port: AgentCandidateOutputArtifactPort,\n input: {\n executionId: string\n purpose: AgentCandidateOutputPurpose\n bytes: Uint8Array\n signal?: AbortSignal\n },\n): Promise<AgentCandidateArtifactRef> {\n input.signal?.throwIfAborted()\n const bytes = Uint8Array.from(input.bytes)\n const expectedDigest = sha256Bytes(bytes)\n const ref = agentCandidateArtifactRefSchema.parse(\n await port.put({\n executionId: input.executionId,\n purpose: input.purpose,\n bytes: Uint8Array.from(bytes),\n ...(input.signal ? { signal: input.signal } : {}),\n }),\n )\n input.signal?.throwIfAborted()\n if (ref.sha256 !== expectedDigest || ref.byteLength !== bytes.byteLength) {\n throw new Error('candidate output locator does not identify the submitted bytes')\n }\n const stored = await port.read(ref)\n input.signal?.throwIfAborted()\n verifyBytes(stored, expectedDigest, bytes.byteLength, 'persisted candidate output')\n return immutableCandidateValue(ref)\n}\n"],"mappings":";;;;;;;AAYA,SAAgBA,cAAY,OAAiC;CAC3D,OAAO,UAAU,WAAW,QAAQ,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,OAAO,KAAK;AAClE;AAE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AClF,OAAO,wBAAwB,GAAG;AACpC"}
@@ -1,6 +1,7 @@
1
- import { c as errorMessage } from "./util-fcckrkKp.js";
2
- import { C as readMaterializedWorkspaceFiles, D as verifyMaterializedProfileWorkspace, E as verifyBytes, F as deepFreezeCandidate, I as embeddedCandidateArtifact, L as immutableCandidateValue, M as canonicalCandidateBytes$1, N as canonicalCandidateDigest$1, O as verifyMaterializedWorkspace, P as canonicalCandidateDocument, R as omitTopLevelDigest, V as hasControlCharacter, _ as assertExactObjectKeys, b as artifactCacheKey, d as verifyTaskCheckout, f as verifyTaskOutcomePatch, g as persistCandidateOutputArtifact, k as verifyWorkspaceSnapshotArtifacts, l as readCandidateGitHubResource, u as verifyCandidateCode, v as isWellFormedUnicode, w as readVerifiedArtifact, z as sha256Bytes$1 } from "./workspace-streams-DA9R3j-p.js";
3
- import { _ as parseAgentCandidateProfileActivation, c as buildLaunch, f as exactProfileExecutorFiles, h as modelRoutes, l as candidateEntrypointReceipt, m as materializeAgentCandidateProfilePlan, n as PI_CANDIDATE_SESSION_DIR_ENV, r as absoluteExecutionCwd, s as assertCandidateProfileExecutionSupport, t as PI_CANDIDATE_AGENT_DIR_ENV, u as candidateProfileAgentPaths, x as requirePublicCandidateConfigValue } from "./profile-BT0X-dm5.js";
1
+ import { c as errorMessage } from "./util-qsH5cC9S.js";
2
+ import { _ as isWellFormedUnicode, b as hasControlCharacter, d as verifyTaskCheckout, f as verifyTaskOutcomePatch, g as assertExactObjectKeys, l as readCandidateGitHubResource, u as verifyCandidateCode } from "./workspace-streams-BakRr-Pl.js";
3
+ import { _ as embeddedCandidateArtifact, b as sha256Bytes$1, d as verifyMaterializedWorkspace, f as verifyWorkspaceSnapshotArtifacts, g as deepFreezeCandidate, h as canonicalCandidateDocument, l as verifyBytes, m as canonicalCandidateDigest$1, o as readMaterializedWorkspaceFiles, p as canonicalCandidateBytes$1, r as artifactCacheKey, s as readVerifiedArtifact, t as persistCandidateOutputArtifact, u as verifyMaterializedProfileWorkspace, v as immutableCandidateValue, y as omitTopLevelDigest } from "./output-artifacts-AqkZ8lO2.js";
4
+ import { _ as parseAgentCandidateProfileActivation, c as buildLaunch, f as exactProfileExecutorFiles, h as modelRoutes, l as candidateEntrypointReceipt, m as materializeAgentCandidateProfilePlan, n as PI_CANDIDATE_SESSION_DIR_ENV, r as absoluteExecutionCwd, s as assertCandidateProfileExecutionSupport, t as PI_CANDIDATE_AGENT_DIR_ENV, u as candidateProfileAgentPaths, x as requirePublicCandidateConfigValue } from "./profile-Cxl_Ajl2.js";
4
5
  import { i as redactProtectedValue, n as createProtectedRecordRedactor, r as redactProtectedReason, t as assertNoProtectedBytes } from "./protected-redaction-DilFZch5.js";
5
6
  import { agentCandidateArtifactRefSchema, agentCandidateBenchmarkResultEvidenceSchema, agentCandidateBenchmarkSuiteSchema, agentCandidateBenchmarkTaskSchema, agentCandidateBundleSchema, agentCandidateContainerSchema, agentCandidateExecutionLimitsSchema, agentCandidateExecutionPlanEvidenceSchema, agentCandidateExecutionPlanMaterialSchema, agentCandidateMaterializationReceiptSchema, agentCandidateModelAccessNetworkSchema, agentCandidateModelSettlementEvidenceSchema, agentCandidateProfilePlanEvidenceSchema, agentCandidateResolvedModelSchema, agentCandidateRunCellSchema, agentCandidateRunReceiptSchema, agentCandidateTaskOutcomeEvidenceSchema, agentCandidateTaskOutcomeSpecSchema, agentCandidateTerminationSchema, agentCandidateWorkspaceManifestMaterialSchema, agentCandidateWorkspaceSnapshotEvidenceSchema, sha256DigestSchema } from "@tangle-network/agent-interface";
6
7
  import { REDACTION_VERSION, isLlmSpan } from "@tangle-network/agent-eval";
@@ -4319,4 +4320,4 @@ async function cleanupFailedPreparation(held, error) {
4319
4320
  }
4320
4321
  export { verifiedResourceTextByDigest as C, AGENT_CANDIDATE_EXECUTION_SUPPORT as S, sealTerminalDigest as _, consumePreparedCandidateExecution as a, sealAgentCandidateModelSettlement as b, withinCandidateCleanupDeadline as c, assertTerminalMatchesClaim as d, assertTerminalMatchesStaged as f, requireStagedTerminal as g, rejectedStage as h, beginPreparedCandidateDisposal as i, assertRecoveryMatchesStaged as l, rejectedFinish as m, executePreparedAgentCandidate as n, candidateClaimFileInternals as o, recoveredTerminalRecord as p, assertPreparedCandidateIntegrity as r, candidateCleanupDeadline as s, prepareAgentCandidateExecution as t, assertTerminalAllowedInPhase as u, terminalRecord as v, verifyAgentCandidateBundle as w, exactProcessProviderAsCandidateExecutor as x, createProtectedAgentCandidateModelPort as y };
4321
4322
 
4322
- //# sourceMappingURL=prepare-D7WwIddG.js.map
4323
+ //# sourceMappingURL=prepare-Cw4ZaN01.js.map