@tangle-network/agent-runtime 0.138.1 → 0.139.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/dist/{activation-AyIFaunX.js → activation-eLJ6uRlP.js} +3 -3
  2. package/dist/{activation-AyIFaunX.js.map → activation-eLJ6uRlP.js.map} +1 -1
  3. package/dist/agent.d.ts +4 -4
  4. package/dist/agent.js +3 -3
  5. package/dist/{analyst-loop-Dk6_xfhI.js → analyst-loop-DtOEXGzR.js} +3 -3
  6. package/dist/{analyst-loop-Dk6_xfhI.js.map → analyst-loop-DtOEXGzR.js.map} +1 -1
  7. package/dist/analyst-loop.d.ts +1 -1
  8. package/dist/analyst-loop.js +1 -1
  9. package/dist/{authoring-Cw6Ufsng.js → authoring-J93uFAwd.js} +3 -3
  10. package/dist/{authoring-Cw6Ufsng.js.map → authoring-J93uFAwd.js.map} +1 -1
  11. package/dist/candidate-execution/index.d.ts +3 -3
  12. package/dist/candidate-execution/index.js +4 -4
  13. package/dist/{candidate-execution-CN2hO-og.js → candidate-execution-uuUeFSc6.js} +5 -5
  14. package/dist/{candidate-execution-CN2hO-og.js.map → candidate-execution-uuUeFSc6.js.map} +1 -1
  15. package/dist/{conversation-DIUtiLkC.js → conversation-C3eZCvLd.js} +8 -6
  16. package/dist/conversation-C3eZCvLd.js.map +1 -0
  17. package/dist/conversation.d.ts +1 -1
  18. package/dist/conversation.js +1 -1
  19. package/dist/durable.d.ts +1 -1
  20. package/dist/{environment-provider-CLNVqp6H.js → environment-provider-BAO8wt1_.js} +147 -48
  21. package/dist/environment-provider-BAO8wt1_.js.map +1 -0
  22. package/dist/{environment-provider-DA8LqBV-.d.ts → environment-provider-Bu3S3v78.d.ts} +3 -3
  23. package/dist/environment-provider.d.ts +1 -1
  24. package/dist/environment-provider.js +1 -1
  25. package/dist/{errors-CVIDr7GQ.js → errors-CDZ8XsVj.js} +34 -9
  26. package/dist/errors-CDZ8XsVj.js.map +1 -0
  27. package/dist/{graph-DxU92LTL.js → graph-BbMjq7-x.js} +5 -5
  28. package/dist/{graph-DxU92LTL.js.map → graph-BbMjq7-x.js.map} +1 -1
  29. package/dist/{improvement-cycle-hIOGxDtV.js → improvement-cycle-D6rhMJR0.js} +67 -66
  30. package/dist/improvement-cycle-D6rhMJR0.js.map +1 -0
  31. package/dist/{index-Bdgpx2Dx.d.ts → index-C6yfz0QN.d.ts} +5 -5
  32. package/dist/{index-BOgzou1U.d.ts → index-COnuT0h7.d.ts} +263 -82
  33. package/dist/{index-CETQJlqT.d.ts → index-CTz17pH6.d.ts} +11 -11
  34. package/dist/{index-DQxQgKDs.d.ts → index-DQv7iCeE.d.ts} +6 -6
  35. package/dist/index.d.ts +16 -16
  36. package/dist/index.js +16 -16
  37. package/dist/intelligence.d.ts +736 -681
  38. package/dist/intelligence.js +113 -8
  39. package/dist/intelligence.js.map +1 -1
  40. package/dist/kernel.d.ts +7 -7
  41. package/dist/kernel.js +12 -12
  42. package/dist/{knowledge-C-JiS5Xg.js → knowledge-CD-_FbJT.js} +7 -7
  43. package/dist/{knowledge-C-JiS5Xg.js.map → knowledge-CD-_FbJT.js.map} +1 -1
  44. package/dist/knowledge.d.ts +1 -1
  45. package/dist/knowledge.js +1 -1
  46. package/dist/{loop-runner-bin-B_Ww2iqY.js → loop-runner-bin-BBz_ACfQ.js} +5 -5
  47. package/dist/{loop-runner-bin-B_Ww2iqY.js.map → loop-runner-bin-BBz_ACfQ.js.map} +1 -1
  48. package/dist/{loop-runner-bin-OH61zEVw.d.ts → loop-runner-bin-DUNxyuaG.d.ts} +3 -3
  49. package/dist/loop-runner-bin.d.ts +1 -1
  50. package/dist/loop-runner-bin.js +1 -1
  51. package/dist/{materialization-BP5zspr2.js → materialization-CrdcfWXp.js} +4 -4
  52. package/dist/{materialization-BP5zspr2.js.map → materialization-CrdcfWXp.js.map} +1 -1
  53. package/dist/mcp/bin.js +4 -4
  54. package/dist/mcp/index.d.ts +5 -5
  55. package/dist/mcp/index.js +8 -8
  56. package/dist/mcp/memory-bin.js +1 -1
  57. package/dist/{memory-server-Cdpy7Uu8.js → memory-server-DsKOhzGf.js} +3 -3
  58. package/dist/{memory-server-Cdpy7Uu8.js.map → memory-server-DsKOhzGf.js.map} +1 -1
  59. package/dist/{model-policy-UTTc9Z-A.js → model-policy-DgRJIJse.js} +2 -2
  60. package/dist/{model-policy-UTTc9Z-A.js.map → model-policy-DgRJIJse.js.map} +1 -1
  61. package/dist/{openai-tools-BKJqaQ1b.js → openai-tools-DIKr72_l.js} +2 -2
  62. package/dist/{openai-tools-BKJqaQ1b.js.map → openai-tools-DIKr72_l.js.map} +1 -1
  63. package/dist/{openai-tools-DU3TZvFY.d.ts → openai-tools-yoRRzAUW.d.ts} +2 -2
  64. package/dist/{prepare-CYqGSYza.js → prepare-DK1qnk7-.js} +3 -3
  65. package/dist/{prepare-CYqGSYza.js.map → prepare-DK1qnk7-.js.map} +1 -1
  66. package/dist/primeintellect/index.d.ts +1 -1
  67. package/dist/profiles.d.ts +1 -1
  68. package/dist/profiles.js +1 -1
  69. package/dist/{protected-model-port-DEsTWOFs.d.ts → protected-model-port-B8ssMyUg.d.ts} +7 -7
  70. package/dist/{protected-model-port-B6DW_x2I.js → protected-model-port-DHeCm_UF.js} +2 -2
  71. package/dist/{protected-model-port-B6DW_x2I.js.map → protected-model-port-DHeCm_UF.js.map} +1 -1
  72. package/dist/{redact-BwEdhuVH.d.ts → redact-CLw2B7Qj.d.ts} +9 -9
  73. package/dist/{researcher-DBfKdnAz.js → researcher-CiSY6Wzb.js} +3 -3
  74. package/dist/{researcher-DBfKdnAz.js.map → researcher-CiSY6Wzb.js.map} +1 -1
  75. package/dist/retained-run-binding-Dp2e8xne.js +268 -0
  76. package/dist/retained-run-binding-Dp2e8xne.js.map +1 -0
  77. package/dist/{runtime-DhPCNvuH.d.ts → runtime-CVNWEw16.d.ts} +4 -4
  78. package/dist/{runtime-CUpB4rEP.js → runtime-tTA2iCZQ.js} +650 -222
  79. package/dist/runtime-tTA2iCZQ.js.map +1 -0
  80. package/dist/{sandbox-events-CA2amHoA.js → sandbox-events-DPmXlcKw.js} +24 -2
  81. package/dist/sandbox-events-DPmXlcKw.js.map +1 -0
  82. package/dist/{snapshot-BOIprwBk.js → snapshot-cK9K420n.js} +2 -2
  83. package/dist/{snapshot-BOIprwBk.js.map → snapshot-cK9K420n.js.map} +1 -1
  84. package/dist/{spawn-journal-DVFqdzO9.js → spawn-journal-DGXei3xG.js} +3 -3
  85. package/dist/{spawn-journal-DVFqdzO9.js.map → spawn-journal-DGXei3xG.js.map} +1 -1
  86. package/dist/{stream-agent-turn-Q5ellSUu.js → stream-agent-turn-4kUH8Nnn.js} +77 -34
  87. package/dist/stream-agent-turn-4kUH8Nnn.js.map +1 -0
  88. package/dist/{stream-agent-turn-DhPlvHwp.d.ts → stream-agent-turn-RjrKGk6S.d.ts} +5 -8
  89. package/dist/{structural-rollout-CwtVIJf-.js → structural-rollout-7LP9Ex0F.js} +9 -9
  90. package/dist/structural-rollout-7LP9Ex0F.js.map +1 -0
  91. package/dist/{supervise-CUJRmx3s.js → supervise-Cx1QY_hj.js} +9 -9
  92. package/dist/{supervise-CUJRmx3s.js.map → supervise-Cx1QY_hj.js.map} +1 -1
  93. package/dist/{supervisor-BoC2tFgH.js → supervisor-BV72aDmP.js} +13 -9
  94. package/dist/supervisor-BV72aDmP.js.map +1 -0
  95. package/dist/testing.d.ts +2 -2
  96. package/dist/testing.js +12 -12
  97. package/dist/{tool-server-Dh-NcbHr.js → tool-server-DEmLr9YY.js} +2 -2
  98. package/dist/{tool-server-Dh-NcbHr.js.map → tool-server-DEmLr9YY.js.map} +1 -1
  99. package/dist/{types-CxU37Uzr.d.ts → types-19ZOddS3.d.ts} +2 -2
  100. package/dist/{types-BBwGSiAj.d.ts → types-C244Huc9.d.ts} +16 -7
  101. package/dist/{types-BCkweg3w.d.ts → types-D4arYjUl.d.ts} +6 -6
  102. package/dist/{workspace-archive-C7AvjSVb.js → workspace-archive-HYlsPhfm.js} +2 -2
  103. package/dist/{workspace-archive-C7AvjSVb.js.map → workspace-archive-HYlsPhfm.js.map} +1 -1
  104. package/package.json +1 -1
  105. package/dist/conversation-DIUtiLkC.js.map +0 -1
  106. package/dist/environment-provider-CLNVqp6H.js.map +0 -1
  107. package/dist/errors-CVIDr7GQ.js.map +0 -1
  108. package/dist/improvement-cycle-hIOGxDtV.js.map +0 -1
  109. package/dist/runtime-CUpB4rEP.js.map +0 -1
  110. package/dist/sandbox-events-CA2amHoA.js.map +0 -1
  111. package/dist/stream-agent-turn-Q5ellSUu.js.map +0 -1
  112. package/dist/structural-rollout-CwtVIJf-.js.map +0 -1
  113. package/dist/supervisor-BoC2tFgH.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"loop-runner-bin-B_Ww2iqY.js","names":[],"sources":["../src/loop-runner.ts","../src/loop-runner-bin.ts"],"sourcesContent":["/**\n *\n * `runDelegatedLoop` — the configured delegated loop-runner.\n *\n * One typed entrypoint a worker agent (or a scheduled routine) calls to run a\n * disciplined loop in a chosen MODE, over agent-runtime's hardened engines:\n *\n * code → build-in-a-loop on the GENERIC recursive path (worktreeLoopRunner: author one\n * `AgentProfile` per harness → worktree-CLI leaves → `patchDelivered` gate)\n * review → caller-registered runner — a `code` runner with an approval gate over candidates\n * research → research-in-a-loop with valid-only KB growth (createKbGate)\n * audit → analyze trace/run data → findings (runAnalystLoop, caller-wired)\n * self-improve → caller-registered `improve(profile, options)` run\n *\n * It is intentionally a thin façade: the value is that EVERY product reuses the\n * one hardened engine instead of forking delegation logic. The dispatcher owns\n * mode routing, timing, fail-loud on an unregistered mode, and a uniform result\n * shape; each mode's engine is a pre-configured runner in the registry (build it\n * with the factories below, or inject your own / a stub).\n *\n * @experimental\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { runAnalystLoop } from './analyst-loop'\nimport type { RunAnalystLoopOpts, RunAnalystLoopResult } from './analyst-loop/types'\nimport { ConfigError } from './errors'\nimport { type CreateKbGateOptions, createKbGate, type FactCandidate } from './mcp/kb-gate'\nimport {\n type AuthoredHarness,\n type Budget,\n createExecutorRegistry,\n definePersona,\n runPersonified,\n type WinnerStrategy,\n type WorktreeFanoutOptions,\n type WorktreePatchArtifact,\n worktreeFanout,\n} from './runtime'\n\n/** All valid delegated-loop mode names — used for validation and CLI surfaces. @experimental */\nexport const DELEGATED_LOOP_MODES = ['code', 'review', 'research', 'audit', 'self-improve'] as const\n\n/** @experimental */\nexport type DelegatedLoopMode = (typeof DELEGATED_LOOP_MODES)[number]\n\n/** Type guard — returns true when `value` is a valid `DelegatedLoopMode` string. @experimental */\nexport function isDelegatedLoopMode(value: unknown): value is DelegatedLoopMode {\n return typeof value === 'string' && (DELEGATED_LOOP_MODES as readonly string[]).includes(value)\n}\n\n/** @experimental A pre-configured loop for one mode. Returns the mode's raw\n * output; the dispatcher wraps it in a {@link DelegatedLoopResult}. */\nexport type DelegatedLoopRunner<T = unknown> = (signal: AbortSignal) => Promise<T>\n\n/** @experimental Mode → configured runner. Partial: only register the modes a\n * given product/routine actually uses. */\nexport type DelegatedLoopRegistry = Partial<Record<DelegatedLoopMode, DelegatedLoopRunner>>\n\n/** @experimental Uniform result — never throws from a registered runner; a\n * thrown engine becomes `{ ok: false, error }` so a routine can record + move on. */\nexport interface DelegatedLoopResult<T = unknown> {\n mode: DelegatedLoopMode\n ok: boolean\n output?: T\n error?: string\n durationMs: number\n}\n\n/** @experimental */\nexport interface RunDelegatedLoopOptions {\n signal?: AbortSignal\n /** Clock override for deterministic tests. */\n now?: () => number\n}\n\n/**\n *\n * Dispatch a configured loop by mode. Fails loud (throws `ConfigError`) when no\n * runner is registered for the mode — a routine pointed at an unwired mode is a\n * config bug, not a silent no-op. A runner that throws is captured as\n * `{ ok: false }` so unattended runs record the failure rather than crash.\n *\n * @experimental\n */\nexport async function runDelegatedLoop<T = unknown>(\n mode: DelegatedLoopMode,\n registry: DelegatedLoopRegistry,\n options: RunDelegatedLoopOptions = {},\n): Promise<DelegatedLoopResult<T>> {\n const runner = registry[mode] as DelegatedLoopRunner<T> | undefined\n if (!runner) {\n throw new ConfigError(\n `runDelegatedLoop: no runner registered for mode '${mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n )\n }\n const now = options.now ?? Date.now\n const signal = options.signal ?? new AbortController().signal\n const start = now()\n try {\n const output = await runner(signal)\n return { mode, ok: true, output, durationMs: now() - start }\n } catch (err) {\n return {\n mode,\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n durationMs: now() - start,\n }\n }\n}\n\n/** @experimental Options for the local-repo `code` runner over the GENERIC recursive path. */\nexport interface WorktreeLoopRunnerOptions {\n /** Exact profile carried by the personified root that owns this fanout. */\n rootProfile: AgentProfile\n /** Absolute path to the local git checkout each worktree is cut from. */\n repoRoot: string\n /** The instruction handed to every authored harness (composed under each profile's systemPrompt). */\n taskPrompt: string\n /** The supervisor-authored harness profiles — one fanout item (one worktree-CLI leaf) each. */\n harnesses: ReadonlyArray<AuthoredHarness>\n /** Conserved budget pool bounding the fanout (equal-k holds by construction). */\n budget: Budget\n /** Shell command run in each worktree to derive the tests-PASS signal. */\n testCmd?: string\n /** Shell command run in each worktree to derive the typecheck-PASS signal. */\n typecheckCmd?: string\n /** Which verification signals the deliverable REQUIRES present-and-passing (default none). */\n require?: ReadonlyArray<'tests' | 'typecheck'>\n /** Diff-size cap (lines). */\n maxDiffLines?: number\n /** Literal path prefixes the patch must not touch (the secret-floor is always on regardless). */\n forbiddenPaths?: string[]\n /** Winner-selection strategy among gated candidates. Default `highest-score`. */\n winnerStrategy?: WinnerStrategy\n /** Test seams forwarded to the worktree-CLI leaves so the runner drives offline. */\n runGit?: WorktreeFanoutOptions['runGit']\n runHarness?: WorktreeFanoutOptions['runHarness']\n runCommand?: WorktreeFanoutOptions['runCommand']\n}\n\n/**\n *\n * `code` mode on the GENERIC recursive path: author one `AgentProfile` per harness, run them as a\n * `worktreeFanout` (N `createWorktreeCliExecutor` leaves, each `gateOnDeliverable`) through\n * `runPersonified` on the keystone Supervisor. The sandbox-session counterpart that drives the in-box\n * harness over a `SandboxClient` is `detachedSessionDelegate` (`./mcp/delegates`); here there is no\n * `runAgentRounds` driver, no role-coupled delegate — the harness list is the fanout, the gate is\n * `patchDelivered`,\n * the winner is the shared valid-only selector (NOT `defaultSelectWinner`, whose non-valid fallback\n * would surface an ungated patch). Equal-k holds by the conserved budget pool. Returns the winning\n * patch artifact, or throws when no candidate is delivered (fail loud, never a vacuous done).\n *\n * @experimental\n */\nexport function worktreeLoopRunner(\n options: WorktreeLoopRunnerOptions,\n): DelegatedLoopRunner<WorktreePatchArtifact> {\n const shape = worktreeFanout<string>({\n repoRoot: options.repoRoot,\n taskPrompt: options.taskPrompt,\n harnesses: options.harnesses,\n ...(options.testCmd !== undefined ? { testCmd: options.testCmd } : {}),\n ...(options.typecheckCmd !== undefined ? { typecheckCmd: options.typecheckCmd } : {}),\n ...(options.require !== undefined ? { require: options.require } : {}),\n ...(options.maxDiffLines !== undefined ? { maxDiffLines: options.maxDiffLines } : {}),\n ...(options.forbiddenPaths !== undefined ? { forbiddenPaths: options.forbiddenPaths } : {}),\n ...(options.winnerStrategy !== undefined ? { winnerStrategy: options.winnerStrategy } : {}),\n ...(options.runGit ? { runGit: options.runGit } : {}),\n ...(options.runHarness ? { runHarness: options.runHarness } : {}),\n ...(options.runCommand ? { runCommand: options.runCommand } : {}),\n })\n // The persona's only role here is to carry the fanout shape onto the Supervisor; each item's\n // executor is BYO (the gated worktree-CLI leaf), so the registry only needs to pass BYO through.\n const persona = definePersona<WorktreePatchArtifact>({\n name: 'worktree-coder',\n root: { profile: options.rootProfile, harness: null },\n directive: 'deliver a minimal validated patch on a fresh worktree',\n context: { role: 'coder' },\n executors: { registry: createExecutorRegistry() },\n })\n return async (signal) => {\n const result = await runPersonified<string, WorktreePatchArtifact>({\n persona,\n shape,\n task: options.taskPrompt,\n budget: options.budget,\n signal,\n })\n if (result.kind !== 'winner' || result.out.kind !== 'done') {\n const blockers =\n result.kind === 'winner' && result.out.kind === 'blocked'\n ? result.out.blockers.join('; ')\n : `supervisor settled ${result.kind}`\n throw new Error(`worktreeLoopRunner: no delivered patch (${blockers})`)\n }\n return result.out.deliverable\n }\n}\n\n/** @experimental A fact rejected at the KB gate — surfaced, never dropped. */\nexport interface VetoedFact {\n candidate: FactCandidate\n vetoedBy?: string\n reason?: string\n}\n\n/** @experimental */\nexport interface ResearchLoopResult {\n /** Facts that passed the fail-closed gate — safe to write to the KB. */\n accepted: FactCandidate[]\n /** Facts the gate vetoed in the final round — escalate, do not silently drop. */\n vetoed: VetoedFact[]\n /** Research rounds actually run. */\n rounds: number\n}\n\n/** @experimental Options for the default `research` runner. */\nexport interface ResearchLoopRunnerOptions {\n /**\n * The research engine (the consumer's web/doc searcher + extractor). Called\n * each round with the prior round's vetoes so it can re-research the gaps.\n * Returns fact candidates carrying their grounding (`verbatimPassage` +\n * `sourceText`).\n */\n research: (round: number, vetoed: VetoedFact[]) => Promise<FactCandidate[]>\n /** Gate config (extra judges, self-artifact kinds, …). The floor is always on. */\n gate?: CreateKbGateOptions\n /** Max research rounds (correct-on-veto remediation). Default 1. */\n maxRounds?: number\n}\n\n/**\n * `research` mode — research-in-a-loop with valid-only KB growth.\n *\n * Each round: research → gate every candidate (fail-closed; passage MUST be in\n * the source) → accept the clean ones → re-research the vetoed ones next round,\n * up to `maxRounds`. Vetoed facts in the final round are RETURNED (escalate,\n * never silently dropped) so the caller audits vs retries.\n *\n * @experimental\n */\nexport function researchLoopRunner(\n o: ResearchLoopRunnerOptions,\n): DelegatedLoopRunner<ResearchLoopResult> {\n const gate = createKbGate(o.gate)\n const maxRounds = Math.max(1, Math.trunc(o.maxRounds ?? 1))\n return async (signal) => {\n const accepted: FactCandidate[] = []\n let vetoed: VetoedFact[] = []\n let rounds = 0\n for (let round = 0; round < maxRounds; round += 1) {\n if (signal.aborted) break\n rounds += 1\n const candidates = await o.research(round, vetoed)\n if (candidates.length === 0) break\n vetoed = []\n for (const c of candidates) {\n const v = await gate(c)\n if (v.accepted) accepted.push(c)\n else vetoed.push({ candidate: c, vetoedBy: v.vetoedBy, reason: v.reason })\n }\n if (vetoed.length === 0) break\n }\n return { accepted, vetoed, rounds }\n }\n}\n\n/**\n * `audit` mode — analyst loop over captured trace/run data.\n *\n * @experimental\n */\nexport function auditLoopRunner<TProposal = unknown, TEdit = unknown>(\n options: RunAnalystLoopOpts,\n): DelegatedLoopRunner<RunAnalystLoopResult<TProposal, TEdit>> {\n return async () => runAnalystLoop<TProposal, TEdit>(options)\n}\n","#!/usr/bin/env node\n/**\n *\n * `agent-runtime-loop` — the schedulable entrypoint for the configured\n * delegated loop-runner. A cron job / routine / Makefile target invokes:\n *\n * agent-runtime-loop --mode research --config ./loops.config.js\n *\n * The config module wires the registry (with full access to env / creds —\n * which is why the deps live there, not in this generic bin). It must default-\n * export a `DelegatedLoopRegistry`, or a `() => DelegatedLoopRegistry | Promise<…>`.\n * The bin runs the selected mode, prints the `DelegatedLoopResult` as JSON, and\n * exits 0 on `ok`, 1 on a recorded failure, 2 on a usage/config error.\n *\n * @experimental\n */\n\nimport {\n DELEGATED_LOOP_MODES,\n type DelegatedLoopMode,\n type DelegatedLoopRegistry,\n type DelegatedLoopResult,\n isDelegatedLoopMode,\n runDelegatedLoop,\n} from './loop-runner'\n\n/** @experimental Parsed CLI invocation. */\nexport interface LoopRunnerCliArgs {\n mode: string\n /** Loads the registry — the bin wires this from `--config`; tests inject a stub. */\n loadRegistry: () => Promise<DelegatedLoopRegistry> | DelegatedLoopRegistry\n now?: () => number\n}\n\n/** @experimental */\nexport interface LoopRunnerCliResult {\n exitCode: number\n result?: DelegatedLoopResult\n error?: string\n}\n\n/**\n *\n * Pure CLI core (no process / argv / IO) so it's unit-testable: validate the\n * mode, load the registry, dispatch, map to an exit code (0 ok / 1 failed /\n * 2 usage). Exported for embedding in custom runners + tests.\n *\n * @experimental\n */\nexport async function runLoopRunnerCli(args: LoopRunnerCliArgs): Promise<LoopRunnerCliResult> {\n if (!isDelegatedLoopMode(args.mode)) {\n return {\n exitCode: 2,\n error: `unknown mode '${args.mode}' (expected one of: ${DELEGATED_LOOP_MODES.join(', ')})`,\n }\n }\n let registry: DelegatedLoopRegistry\n try {\n registry = await args.loadRegistry()\n } catch (err) {\n return { exitCode: 2, error: `failed to load registry: ${errMsg(err)}` }\n }\n if (!registry[args.mode]) {\n return {\n exitCode: 2,\n error: `config registers no runner for mode '${args.mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n }\n }\n // runDelegatedLoop throws only on a missing runner (guarded above); a failing\n // engine is captured as { ok: false } → exit 1, not a crash.\n const result = await runDelegatedLoop(args.mode as DelegatedLoopMode, registry, {\n ...(args.now ? { now: args.now } : {}),\n })\n return { exitCode: result.ok ? 0 : 1, result }\n}\n\n/** Parse `--mode X --config Y` from an argv tail (`process.argv.slice(2)`). */\nexport function parseLoopRunnerArgv(argv: string[]): { mode?: string; config?: string } {\n const out: { mode?: string; config?: string } = {}\n for (let i = 0; i < argv.length; i += 1) {\n const a = argv[i]\n if (a === '--mode') out.mode = argv[++i]\n else if (a === '--config') out.config = argv[++i]\n else if (a?.startsWith('--mode=')) out.mode = a.slice('--mode='.length)\n else if (a?.startsWith('--config=')) out.config = a.slice('--config='.length)\n }\n return out\n}\n\n/** Normalize a config module's default export → a registry. */\nfunction resolveRegistry(mod: unknown): DelegatedLoopRegistry {\n const def = (mod as { default?: unknown })?.default ?? mod\n const value = typeof def === 'function' ? (def as () => unknown)() : def\n return value as DelegatedLoopRegistry\n}\n\nfunction errMsg(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n\n/** The argv → IO → exit shell. Kept thin; logic lives in `runLoopRunnerCli`. */\nasync function main(): Promise<void> {\n const { mode, config } = parseLoopRunnerArgv(process.argv.slice(2))\n if (!mode || !config) {\n process.stderr.write(\n 'usage: agent-runtime-loop --mode <mode> --config <module>\\n' +\n ` modes: ${DELEGATED_LOOP_MODES.join(' | ')}\\n` +\n ' config: a JS/TS module default-exporting a DelegatedLoopRegistry (or a factory)\\n',\n )\n process.exit(2)\n }\n const { pathToFileURL } = await import('node:url')\n const { resolve } = await import('node:path')\n const cli = await runLoopRunnerCli({\n mode,\n loadRegistry: async () => resolveRegistry(await import(pathToFileURL(resolve(config)).href)),\n })\n process.stdout.write(`${JSON.stringify(cli.result ?? { error: cli.error }, null, 2)}\\n`)\n if (cli.error) process.stderr.write(`${cli.error}\\n`)\n process.exit(cli.exitCode)\n}\n\n// Run only when executed as the bin — never when imported for the testable\n// core, and never when bundled into a runtime that has no `process.argv`\n// (e.g. Cloudflare Workers, where `process` is a shim without `argv`). Reading\n// `process.argv[1]` directly would throw at module load there; `process.argv?.`\n// keeps the guard a no-op instead of crashing the Worker on startup.\nconst invokedScript = typeof process !== 'undefined' ? process.argv?.[1] : undefined\nif (invokedScript && /loop-runner-bin\\.(js|ts|mjs)$/.test(invokedScript)) {\n void main()\n}\n"],"mappings":";;;;;;;AAyCA,MAAa,uBAAuB;CAAC;CAAQ;CAAU;CAAY;CAAS;AAAc;;AAM1F,SAAgB,oBAAoB,OAA4C;CAC9E,OAAO,OAAO,UAAU,YAAa,qBAA2C,SAAS,KAAK;AAChG;;;;;;;;;;AAoCA,eAAsB,iBACpB,MACA,UACA,UAAmC,CAAC,GACH;CACjC,MAAM,SAAS,SAAS;CACxB,IAAI,CAAC,QACH,MAAM,IAAI,YACR,oDAAoD,KAAK,iBACvD,OAAO,KAAK,QAAQ,CAAC,CAAC,KAAK,IAAI,KAAK,OACrC,EACH;CAEF,MAAM,MAAM,QAAQ,OAAO,KAAK;CAChC,MAAM,SAAS,QAAQ,UAAU,IAAI,gBAAgB,CAAC,CAAC;CACvD,MAAM,QAAQ,IAAI;CAClB,IAAI;EAEF,OAAO;GAAE;GAAM,IAAI;GAAM,QAAA,MADJ,OAAO,MAAM;GACD,YAAY,IAAI,IAAI;EAAM;CAC7D,SAAS,KAAK;EACZ,OAAO;G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AK,CAAC;CAChB;CACA,MAAM,EAAE,kBAAkB,MAAM,OAAO;CACvC,MAAM,EAAE,YAAY,MAAM,OAAO;CACjC,MAAM,MAAM,MAAM,iBAAiB;EACjC;EACA,cAAc,YAAY,gBAAgB,MAAM,OAAO,cAAc,QAAQ,MAAM,CAAC,CAAC,CAAC,KAAK;CAC7F,CAAC;CACD,QAAQ,OAAO,MAAM,GAAG,KAAK,UAAU,IAAI,UAAU,EAAE,OAAO,IAAI,MAAM,GAAG,MAAM,CAAC,EAAE,GAAG;CACvF,IAAI,IAAI,OAAO,QAAQ,OAAO,MAAM,GAAG,IAAI,MAAM,GAAG;CACpD,QAAQ,KAAK,IAAI,QAAQ;AAC3B;AAOA,MAAM,gBAAgB,OAAO,YAAY,cAAc,QAAQ,OAAO,KAAK,KAAA;AAC3E,IAAI,iBAAiB,gCAAgC,KAAK,aAAa,GACrE,KAAU"}
1
+ {"version":3,"file":"loop-runner-bin-BBz_ACfQ.js","names":[],"sources":["../src/loop-runner.ts","../src/loop-runner-bin.ts"],"sourcesContent":["/**\n *\n * `runDelegatedLoop` — the configured delegated loop-runner.\n *\n * One typed entrypoint a worker agent (or a scheduled routine) calls to run a\n * disciplined loop in a chosen MODE, over agent-runtime's hardened engines:\n *\n * code → build-in-a-loop on the GENERIC recursive path (worktreeLoopRunner: author one\n * `AgentProfile` per harness → worktree-CLI leaves → `patchDelivered` gate)\n * review → caller-registered runner — a `code` runner with an approval gate over candidates\n * research → research-in-a-loop with valid-only KB growth (createKbGate)\n * audit → analyze trace/run data → findings (runAnalystLoop, caller-wired)\n * self-improve → caller-registered `improve(profile, options)` run\n *\n * It is intentionally a thin façade: the value is that EVERY product reuses the\n * one hardened engine instead of forking delegation logic. The dispatcher owns\n * mode routing, timing, fail-loud on an unregistered mode, and a uniform result\n * shape; each mode's engine is a pre-configured runner in the registry (build it\n * with the factories below, or inject your own / a stub).\n *\n * @experimental\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { runAnalystLoop } from './analyst-loop'\nimport type { RunAnalystLoopOpts, RunAnalystLoopResult } from './analyst-loop/types'\nimport { ConfigError } from './errors'\nimport { type CreateKbGateOptions, createKbGate, type FactCandidate } from './mcp/kb-gate'\nimport {\n type AuthoredHarness,\n type Budget,\n createExecutorRegistry,\n definePersona,\n runPersonified,\n type WinnerStrategy,\n type WorktreeFanoutOptions,\n type WorktreePatchArtifact,\n worktreeFanout,\n} from './runtime'\n\n/** All valid delegated-loop mode names — used for validation and CLI surfaces. @experimental */\nexport const DELEGATED_LOOP_MODES = ['code', 'review', 'research', 'audit', 'self-improve'] as const\n\n/** @experimental */\nexport type DelegatedLoopMode = (typeof DELEGATED_LOOP_MODES)[number]\n\n/** Type guard — returns true when `value` is a valid `DelegatedLoopMode` string. @experimental */\nexport function isDelegatedLoopMode(value: unknown): value is DelegatedLoopMode {\n return typeof value === 'string' && (DELEGATED_LOOP_MODES as readonly string[]).includes(value)\n}\n\n/** @experimental A pre-configured loop for one mode. Returns the mode's raw\n * output; the dispatcher wraps it in a {@link DelegatedLoopResult}. */\nexport type DelegatedLoopRunner<T = unknown> = (signal: AbortSignal) => Promise<T>\n\n/** @experimental Mode → configured runner. Partial: only register the modes a\n * given product/routine actually uses. */\nexport type DelegatedLoopRegistry = Partial<Record<DelegatedLoopMode, DelegatedLoopRunner>>\n\n/** @experimental Uniform result — never throws from a registered runner; a\n * thrown engine becomes `{ ok: false, error }` so a routine can record + move on. */\nexport interface DelegatedLoopResult<T = unknown> {\n mode: DelegatedLoopMode\n ok: boolean\n output?: T\n error?: string\n durationMs: number\n}\n\n/** @experimental */\nexport interface RunDelegatedLoopOptions {\n signal?: AbortSignal\n /** Clock override for deterministic tests. */\n now?: () => number\n}\n\n/**\n *\n * Dispatch a configured loop by mode. Fails loud (throws `ConfigError`) when no\n * runner is registered for the mode — a routine pointed at an unwired mode is a\n * config bug, not a silent no-op. A runner that throws is captured as\n * `{ ok: false }` so unattended runs record the failure rather than crash.\n *\n * @experimental\n */\nexport async function runDelegatedLoop<T = unknown>(\n mode: DelegatedLoopMode,\n registry: DelegatedLoopRegistry,\n options: RunDelegatedLoopOptions = {},\n): Promise<DelegatedLoopResult<T>> {\n const runner = registry[mode] as DelegatedLoopRunner<T> | undefined\n if (!runner) {\n throw new ConfigError(\n `runDelegatedLoop: no runner registered for mode '${mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n )\n }\n const now = options.now ?? Date.now\n const signal = options.signal ?? new AbortController().signal\n const start = now()\n try {\n const output = await runner(signal)\n return { mode, ok: true, output, durationMs: now() - start }\n } catch (err) {\n return {\n mode,\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n durationMs: now() - start,\n }\n }\n}\n\n/** @experimental Options for the local-repo `code` runner over the GENERIC recursive path. */\nexport interface WorktreeLoopRunnerOptions {\n /** Exact profile carried by the personified root that owns this fanout. */\n rootProfile: AgentProfile\n /** Absolute path to the local git checkout each worktree is cut from. */\n repoRoot: string\n /** The instruction handed to every authored harness (composed under each profile's systemPrompt). */\n taskPrompt: string\n /** The supervisor-authored harness profiles — one fanout item (one worktree-CLI leaf) each. */\n harnesses: ReadonlyArray<AuthoredHarness>\n /** Conserved budget pool bounding the fanout (equal-k holds by construction). */\n budget: Budget\n /** Shell command run in each worktree to derive the tests-PASS signal. */\n testCmd?: string\n /** Shell command run in each worktree to derive the typecheck-PASS signal. */\n typecheckCmd?: string\n /** Which verification signals the deliverable REQUIRES present-and-passing (default none). */\n require?: ReadonlyArray<'tests' | 'typecheck'>\n /** Diff-size cap (lines). */\n maxDiffLines?: number\n /** Literal path prefixes the patch must not touch (the secret-floor is always on regardless). */\n forbiddenPaths?: string[]\n /** Winner-selection strategy among gated candidates. Default `highest-score`. */\n winnerStrategy?: WinnerStrategy\n /** Test seams forwarded to the worktree-CLI leaves so the runner drives offline. */\n runGit?: WorktreeFanoutOptions['runGit']\n runHarness?: WorktreeFanoutOptions['runHarness']\n runCommand?: WorktreeFanoutOptions['runCommand']\n}\n\n/**\n *\n * `code` mode on the GENERIC recursive path: author one `AgentProfile` per harness, run them as a\n * `worktreeFanout` (N `createWorktreeCliExecutor` leaves, each `gateOnDeliverable`) through\n * `runPersonified` on the keystone Supervisor. The sandbox-session counterpart that drives the in-box\n * harness over a `SandboxClient` is `detachedSessionDelegate` (`./mcp/delegates`); here there is no\n * `runAgentRounds` driver, no role-coupled delegate — the harness list is the fanout, the gate is\n * `patchDelivered`,\n * the winner is the shared valid-only selector (NOT `defaultSelectWinner`, whose non-valid fallback\n * would surface an ungated patch). Equal-k holds by the conserved budget pool. Returns the winning\n * patch artifact, or throws when no candidate is delivered (fail loud, never a vacuous done).\n *\n * @experimental\n */\nexport function worktreeLoopRunner(\n options: WorktreeLoopRunnerOptions,\n): DelegatedLoopRunner<WorktreePatchArtifact> {\n const shape = worktreeFanout<string>({\n repoRoot: options.repoRoot,\n taskPrompt: options.taskPrompt,\n harnesses: options.harnesses,\n ...(options.testCmd !== undefined ? { testCmd: options.testCmd } : {}),\n ...(options.typecheckCmd !== undefined ? { typecheckCmd: options.typecheckCmd } : {}),\n ...(options.require !== undefined ? { require: options.require } : {}),\n ...(options.maxDiffLines !== undefined ? { maxDiffLines: options.maxDiffLines } : {}),\n ...(options.forbiddenPaths !== undefined ? { forbiddenPaths: options.forbiddenPaths } : {}),\n ...(options.winnerStrategy !== undefined ? { winnerStrategy: options.winnerStrategy } : {}),\n ...(options.runGit ? { runGit: options.runGit } : {}),\n ...(options.runHarness ? { runHarness: options.runHarness } : {}),\n ...(options.runCommand ? { runCommand: options.runCommand } : {}),\n })\n // The persona's only role here is to carry the fanout shape onto the Supervisor; each item's\n // executor is BYO (the gated worktree-CLI leaf), so the registry only needs to pass BYO through.\n const persona = definePersona<WorktreePatchArtifact>({\n name: 'worktree-coder',\n root: { profile: options.rootProfile, harness: null },\n directive: 'deliver a minimal validated patch on a fresh worktree',\n context: { role: 'coder' },\n executors: { registry: createExecutorRegistry() },\n })\n return async (signal) => {\n const result = await runPersonified<string, WorktreePatchArtifact>({\n persona,\n shape,\n task: options.taskPrompt,\n budget: options.budget,\n signal,\n })\n if (result.kind !== 'winner' || result.out.kind !== 'done') {\n const blockers =\n result.kind === 'winner' && result.out.kind === 'blocked'\n ? result.out.blockers.join('; ')\n : `supervisor settled ${result.kind}`\n throw new Error(`worktreeLoopRunner: no delivered patch (${blockers})`)\n }\n return result.out.deliverable\n }\n}\n\n/** @experimental A fact rejected at the KB gate — surfaced, never dropped. */\nexport interface VetoedFact {\n candidate: FactCandidate\n vetoedBy?: string\n reason?: string\n}\n\n/** @experimental */\nexport interface ResearchLoopResult {\n /** Facts that passed the fail-closed gate — safe to write to the KB. */\n accepted: FactCandidate[]\n /** Facts the gate vetoed in the final round — escalate, do not silently drop. */\n vetoed: VetoedFact[]\n /** Research rounds actually run. */\n rounds: number\n}\n\n/** @experimental Options for the default `research` runner. */\nexport interface ResearchLoopRunnerOptions {\n /**\n * The research engine (the consumer's web/doc searcher + extractor). Called\n * each round with the prior round's vetoes so it can re-research the gaps.\n * Returns fact candidates carrying their grounding (`verbatimPassage` +\n * `sourceText`).\n */\n research: (round: number, vetoed: VetoedFact[]) => Promise<FactCandidate[]>\n /** Gate config (extra judges, self-artifact kinds, …). The floor is always on. */\n gate?: CreateKbGateOptions\n /** Max research rounds (correct-on-veto remediation). Default 1. */\n maxRounds?: number\n}\n\n/**\n * `research` mode — research-in-a-loop with valid-only KB growth.\n *\n * Each round: research → gate every candidate (fail-closed; passage MUST be in\n * the source) → accept the clean ones → re-research the vetoed ones next round,\n * up to `maxRounds`. Vetoed facts in the final round are RETURNED (escalate,\n * never silently dropped) so the caller audits vs retries.\n *\n * @experimental\n */\nexport function researchLoopRunner(\n o: ResearchLoopRunnerOptions,\n): DelegatedLoopRunner<ResearchLoopResult> {\n const gate = createKbGate(o.gate)\n const maxRounds = Math.max(1, Math.trunc(o.maxRounds ?? 1))\n return async (signal) => {\n const accepted: FactCandidate[] = []\n let vetoed: VetoedFact[] = []\n let rounds = 0\n for (let round = 0; round < maxRounds; round += 1) {\n if (signal.aborted) break\n rounds += 1\n const candidates = await o.research(round, vetoed)\n if (candidates.length === 0) break\n vetoed = []\n for (const c of candidates) {\n const v = await gate(c)\n if (v.accepted) accepted.push(c)\n else vetoed.push({ candidate: c, vetoedBy: v.vetoedBy, reason: v.reason })\n }\n if (vetoed.length === 0) break\n }\n return { accepted, vetoed, rounds }\n }\n}\n\n/**\n * `audit` mode — analyst loop over captured trace/run data.\n *\n * @experimental\n */\nexport function auditLoopRunner<TProposal = unknown, TEdit = unknown>(\n options: RunAnalystLoopOpts,\n): DelegatedLoopRunner<RunAnalystLoopResult<TProposal, TEdit>> {\n return async () => runAnalystLoop<TProposal, TEdit>(options)\n}\n","#!/usr/bin/env node\n/**\n *\n * `agent-runtime-loop` — the schedulable entrypoint for the configured\n * delegated loop-runner. A cron job / routine / Makefile target invokes:\n *\n * agent-runtime-loop --mode research --config ./loops.config.js\n *\n * The config module wires the registry (with full access to env / creds —\n * which is why the deps live there, not in this generic bin). It must default-\n * export a `DelegatedLoopRegistry`, or a `() => DelegatedLoopRegistry | Promise<…>`.\n * The bin runs the selected mode, prints the `DelegatedLoopResult` as JSON, and\n * exits 0 on `ok`, 1 on a recorded failure, 2 on a usage/config error.\n *\n * @experimental\n */\n\nimport {\n DELEGATED_LOOP_MODES,\n type DelegatedLoopMode,\n type DelegatedLoopRegistry,\n type DelegatedLoopResult,\n isDelegatedLoopMode,\n runDelegatedLoop,\n} from './loop-runner'\n\n/** @experimental Parsed CLI invocation. */\nexport interface LoopRunnerCliArgs {\n mode: string\n /** Loads the registry — the bin wires this from `--config`; tests inject a stub. */\n loadRegistry: () => Promise<DelegatedLoopRegistry> | DelegatedLoopRegistry\n now?: () => number\n}\n\n/** @experimental */\nexport interface LoopRunnerCliResult {\n exitCode: number\n result?: DelegatedLoopResult\n error?: string\n}\n\n/**\n *\n * Pure CLI core (no process / argv / IO) so it's unit-testable: validate the\n * mode, load the registry, dispatch, map to an exit code (0 ok / 1 failed /\n * 2 usage). Exported for embedding in custom runners + tests.\n *\n * @experimental\n */\nexport async function runLoopRunnerCli(args: LoopRunnerCliArgs): Promise<LoopRunnerCliResult> {\n if (!isDelegatedLoopMode(args.mode)) {\n return {\n exitCode: 2,\n error: `unknown mode '${args.mode}' (expected one of: ${DELEGATED_LOOP_MODES.join(', ')})`,\n }\n }\n let registry: DelegatedLoopRegistry\n try {\n registry = await args.loadRegistry()\n } catch (err) {\n return { exitCode: 2, error: `failed to load registry: ${errMsg(err)}` }\n }\n if (!registry[args.mode]) {\n return {\n exitCode: 2,\n error: `config registers no runner for mode '${args.mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n }\n }\n // runDelegatedLoop throws only on a missing runner (guarded above); a failing\n // engine is captured as { ok: false } → exit 1, not a crash.\n const result = await runDelegatedLoop(args.mode as DelegatedLoopMode, registry, {\n ...(args.now ? { now: args.now } : {}),\n })\n return { exitCode: result.ok ? 0 : 1, result }\n}\n\n/** Parse `--mode X --config Y` from an argv tail (`process.argv.slice(2)`). */\nexport function parseLoopRunnerArgv(argv: string[]): { mode?: string; config?: string } {\n const out: { mode?: string; config?: string } = {}\n for (let i = 0; i < argv.length; i += 1) {\n const a = argv[i]\n if (a === '--mode') out.mode = argv[++i]\n else if (a === '--config') out.config = argv[++i]\n else if (a?.startsWith('--mode=')) out.mode = a.slice('--mode='.length)\n else if (a?.startsWith('--config=')) out.config = a.slice('--config='.length)\n }\n return out\n}\n\n/** Normalize a config module's default export → a registry. */\nfunction resolveRegistry(mod: unknown): DelegatedLoopRegistry {\n const def = (mod as { default?: unknown })?.default ?? mod\n const value = typeof def === 'function' ? (def as () => unknown)() : def\n return value as DelegatedLoopRegistry\n}\n\nfunction errMsg(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n\n/** The argv → IO → exit shell. Kept thin; logic lives in `runLoopRunnerCli`. */\nasync function main(): Promise<void> {\n const { mode, config } = parseLoopRunnerArgv(process.argv.slice(2))\n if (!mode || !config) {\n process.stderr.write(\n 'usage: agent-runtime-loop --mode <mode> --config <module>\\n' +\n ` modes: ${DELEGATED_LOOP_MODES.join(' | ')}\\n` +\n ' config: a JS/TS module default-exporting a DelegatedLoopRegistry (or a factory)\\n',\n )\n process.exit(2)\n }\n const { pathToFileURL } = await import('node:url')\n const { resolve } = await import('node:path')\n const cli = await runLoopRunnerCli({\n mode,\n loadRegistry: async () => resolveRegistry(await import(pathToFileURL(resolve(config)).href)),\n })\n process.stdout.write(`${JSON.stringify(cli.result ?? { error: cli.error }, null, 2)}\\n`)\n if (cli.error) process.stderr.write(`${cli.error}\\n`)\n process.exit(cli.exitCode)\n}\n\n// Run only when executed as the bin — never when imported for the testable\n// core, and never when bundled into a runtime that has no `process.argv`\n// (e.g. Cloudflare Workers, where `process` is a shim without `argv`). Reading\n// `process.argv[1]` directly would throw at module load there; `process.argv?.`\n// keeps the guard a no-op instead of crashing the Worker on startup.\nconst invokedScript = typeof process !== 'undefined' ? process.argv?.[1] : undefined\nif (invokedScript && /loop-runner-bin\\.(js|ts|mjs)$/.test(invokedScript)) {\n void main()\n}\n"],"mappings":";;;;;;;AAyCA,MAAa,uBAAuB;CAAC;CAAQ;CAAU;CAAY;CAAS;AAAc;;AAM1F,SAAgB,oBAAoB,OAA4C;CAC9E,OAAO,OAAO,UAAU,YAAa,qBAA2C,SAAS,KAAK;AAChG;;;;;;;;;;AAoCA,eAAsB,iBACpB,MACA,UACA,UAAmC,CAAC,GACH;CACjC,MAAM,SAAS,SAAS;CACxB,IAAI,CAAC,QACH,MAAM,IAAI,YACR,oDAAoD,KAAK,iBACvD,OAAO,KAAK,QAAQ,CAAC,CAAC,KAAK,IAAI,KAAK,OACrC,EACH;CAEF,MAAM,MAAM,QAAQ,OAAO,KAAK;CAChC,MAAM,SAAS,QAAQ,UAAU,IAAI,gBAAgB,CAAC,CAAC;CACvD,MAAM,QAAQ,IAAI;CAClB,IAAI;EAEF,OAAO;GAAE;GAAM,IAAI;GAAM,QAAA,MAD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EACpB,QAAQ,OAAO,MACb;WACc,qBAAqB,KAAK,KAAK,EAAE;CAEjD;EACA,QAAQ,KAAK,CAAC;CAChB;CACA,MAAM,EAAE,kBAAkB,MAAM,OAAO;CACvC,MAAM,EAAE,YAAY,MAAM,OAAO;CACjC,MAAM,MAAM,MAAM,iBAAiB;EACjC;EACA,cAAc,YAAY,gBAAgB,MAAM,OAAO,cAAc,QAAQ,MAAM,CAAC,CAAC,CAAC,KAAK;CAC7F,CAAC;CACD,QAAQ,OAAO,MAAM,GAAG,KAAK,UAAU,IAAI,UAAU,EAAE,OAAO,IAAI,MAAM,GAAG,MAAM,CAAC,EAAE,GAAG;CACvF,IAAI,IAAI,OAAO,QAAQ,OAAO,MAAM,GAAG,IAAI,MAAM,GAAG;CACpD,QAAQ,KAAK,IAAI,QAAQ;AAC3B;AAOA,MAAM,gBAAgB,OAAO,YAAY,cAAc,QAAQ,OAAO,KAAK,KAAA;AAC3E,IAAI,iBAAiB,gCAAgC,KAAK,aAAa,GACrE,KAAU"}
@@ -1,6 +1,6 @@
1
1
  import { d as RunAnalystLoopOpts, f as RunAnalystLoopResult } from "./types-zWfqDjeL.js";
2
- import { D as WorktreeFanoutOptions, E as AuthoredHarness, Ft as WorktreePatchArtifact, _c as WinnerStrategy } from "./index-BOgzou1U.js";
3
- import { i as Budget } from "./types-BCkweg3w.js";
2
+ import { D as WorktreeFanoutOptions, E as AuthoredHarness, Ft as WorktreePatchArtifact, kc as WinnerStrategy } from "./index-COnuT0h7.js";
3
+ import { i as Budget } from "./types-D4arYjUl.js";
4
4
  import { n as FactCandidate, t as CreateKbGateOptions } from "./kb-gate-C8z2juK8.js";
5
5
  import { AgentProfile } from "@tangle-network/agent-interface";
6
6
  //#region src/loop-runner.d.ts
@@ -162,4 +162,4 @@ declare function parseLoopRunnerArgv(argv: string[]): {
162
162
  };
163
163
  //#endregion
164
164
  export { researchLoopRunner as _, DELEGATED_LOOP_MODES as a, DelegatedLoopResult as c, ResearchLoopRunnerOptions as d, RunDelegatedLoopOptions as f, isDelegatedLoopMode as g, auditLoopRunner as h, runLoopRunnerCli as i, DelegatedLoopRunner as l, WorktreeLoopRunnerOptions as m, LoopRunnerCliResult as n, DelegatedLoopMode as o, VetoedFact as p, parseLoopRunnerArgv as r, DelegatedLoopRegistry as s, LoopRunnerCliArgs as t, ResearchLoopResult as u, runDelegatedLoop as v, worktreeLoopRunner as y };
165
- //# sourceMappingURL=loop-runner-bin-OH61zEVw.d.ts.map
165
+ //# sourceMappingURL=loop-runner-bin-DUNxyuaG.d.ts.map
@@ -1,2 +1,2 @@
1
- import { i as runLoopRunnerCli, n as LoopRunnerCliResult, r as parseLoopRunnerArgv, t as LoopRunnerCliArgs } from "./loop-runner-bin-OH61zEVw.js";
1
+ import { i as runLoopRunnerCli, n as LoopRunnerCliResult, r as parseLoopRunnerArgv, t as LoopRunnerCliArgs } from "./loop-runner-bin-DUNxyuaG.js";
2
2
  export { LoopRunnerCliArgs, LoopRunnerCliResult, parseLoopRunnerArgv, runLoopRunnerCli };
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import { n as runLoopRunnerCli, t as parseLoopRunnerArgv } from "./loop-runner-bin-B_Ww2iqY.js";
2
+ import { n as runLoopRunnerCli, t as parseLoopRunnerArgv } from "./loop-runner-bin-BBz_ACfQ.js";
3
3
  export { parseLoopRunnerArgv, runLoopRunnerCli };
@@ -1,6 +1,6 @@
1
- import { f as ValidationError } from "./errors-CVIDr7GQ.js";
2
- import { t as detachedSnapshot } from "./snapshot-BOIprwBk.js";
3
- import { t as assertExecutableAgentProfile } from "./model-policy-UTTc9Z-A.js";
1
+ import { m as ValidationError } from "./errors-CDZ8XsVj.js";
2
+ import { t as detachedSnapshot } from "./snapshot-cK9K420n.js";
3
+ import { t as assertExecutableAgentProfile } from "./model-policy-DgRJIJse.js";
4
4
  import { agentProfileSchema, canonicalAgentProfileDigest, canonicalCandidateDigest } from "@tangle-network/agent-interface";
5
5
  import { randomUUID } from "node:crypto";
6
6
  //#region src/runtime/supervise/executable-spec.ts
@@ -361,4 +361,4 @@ function jsonWireSnapshot(value, path = "$") {
361
361
  //#endregion
362
362
  export { unknownExecutionBindingReceipt as C, executableAgentSpecSnapshot as E, runtimeOwnedScopeOwnerRuntime as S, executableAgentProfileSnapshot as T, runtimeOwnedDriveHarnessProviderEvidence as _, authoredProfileDigest as a, runtimeOwnedExecutorProviderEvidence as b, knownExecutionBindingReceipt as c, recordRuntimeOwnedDriveHarnessProviderEvidence as d, recordRuntimeOwnedProviderAttemptStart as f, runtimeOwnedDeferredExecutorRuntime as g, recordRuntimeOwnedProviderModel as h, attestRuntimeOwnedScopeOwner as i, knownMaterializationReceipt as l, recordRuntimeOwnedProviderIdentityConflict as m, attestRuntimeOwnedExecutor as n, finalizeRuntimeOwnedPendingExecutor as o, recordRuntimeOwnedProviderDispatchNotStarted as p, attestRuntimeOwnedPendingExecutor as r, inheritRuntimeOwnedExecutorAttestation as s, attestRuntimeOwnedDeferredExecutor as t, newExecutionAttemptId as u, runtimeOwnedExecutorExecutionBinding as v, unknownMaterializationReceipt as w, runtimeOwnedPendingExecutorMaterialization as x, runtimeOwnedExecutorMaterialization as y };
363
363
 
364
- //# sourceMappingURL=materialization-BP5zspr2.js.map
364
+ //# sourceMappingURL=materialization-CrdcfWXp.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"materialization-BP5zspr2.js","names":[],"sources":["../src/runtime/supervise/executable-spec.ts","../src/runtime/supervise/materialization.ts"],"sourcesContent":["import { type AgentProfile, agentProfileSchema } from '@tangle-network/agent-interface'\nimport { assertExecutableAgentProfile } from './model-policy'\nimport { detachedSnapshot } from './snapshot'\nimport type { AgentSpec } from './types'\n\n/**\n * Parse one untrusted profile into the exact immutable value execution may consume.\n *\n * Snapshotting before schema parsing reads caller-owned fields once. Snapshotting the parsed\n * result prevents downstream custom code from changing any identity or authority field.\n */\nexport function executableAgentProfileSnapshot(raw: unknown, context: string): AgentProfile {\n const input = detachedSnapshot(raw, `${context}: AgentProfile input`)\n const profile = agentProfileSchema.parse(input)\n assertExecutableAgentProfile(profile, context)\n return detachedSnapshot(profile, `${context}: parsed AgentProfile`)\n}\n\n/** Snapshot an executable spec while retaining trusted callbacks by reference. */\nexport function executableAgentSpecSnapshot(raw: AgentSpec, context: string): AgentSpec {\n const {\n profile: rawProfile,\n harness,\n execution: rawExecution,\n ...runtimeExtensions\n } = raw as AgentSpec & Readonly<Record<string, unknown>>\n const profile = executableAgentProfileSnapshot(rawProfile, context)\n const execution =\n rawExecution === undefined\n ? undefined\n : detachedSnapshot(rawExecution, `${context}: execution attribution`)\n return Object.freeze({\n ...runtimeExtensions,\n profile,\n harness,\n ...(execution === undefined ? {} : { execution }),\n }) as AgentSpec\n}\n","import { randomUUID } from 'node:crypto'\nimport {\n agentProfileSchema,\n canonicalAgentProfileDigest,\n canonicalCandidateDigest,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport { ValidationError } from '../../errors'\nimport { detachedSnapshot } from './snapshot'\nimport type {\n ExecutionBindingReceipt,\n Executor,\n ExecutorExecutionBinding,\n ExecutorMaterialization,\n ProfileMaterializationReceipt,\n ProviderModelAttemptEvidence,\n ProviderModelExecutionEvidence,\n Runtime,\n UnknownMaterializationReason,\n} from './types'\n\ntype RuntimeOwnedExecutorMaterialization =\n | {\n readonly kind: 'known'\n readonly declaration: ExecutorMaterialization\n readonly binding?: ExecutorExecutionBinding\n }\n | {\n /** A Runtime-owned external executor whose exact launch is known, but whose remote\n * materializer has not yet returned its terminal acknowledgement. This private state lets\n * Runtime validate the planned authority before execution without presenting it as proof\n * that the remote process actually used that plan. */\n readonly kind: 'pending'\n readonly runtime: Runtime\n readonly declaration: ExecutorMaterialization\n readonly binding: ExecutorExecutionBinding\n }\n | { readonly kind: 'deferred'; readonly runtime: Runtime }\n\ninterface RuntimeOwnedExecutorMaterializationRef {\n current: RuntimeOwnedExecutorMaterialization\n}\n\nconst runtimeOwnedExecutorMaterializations = new WeakMap<\n object,\n RuntimeOwnedExecutorMaterializationRef\n>()\nconst runtimeOwnedScopeOwners = new WeakMap<object, Runtime>()\nconst runtimeOwnedExecutorProviderEvidenceState = new WeakMap<\n object,\n {\n readonly attempts: Array<{\n readonly observations: string[]\n identityConflict?: boolean\n providerDispatch?: 'not_started'\n }>\n }\n>()\nconst runtimeOwnedDriveHarnessProviderEvidenceState = new WeakMap<\n object,\n ProviderModelExecutionEvidence\n>()\n\ninterface KnownReceiptInput {\n readonly authoredProfileDigest: Sha256Digest\n readonly runtime: Runtime\n readonly declaration: ExecutorMaterialization\n}\n\ninterface UnknownReceiptInput {\n readonly authoredProfileDigest?: Sha256Digest\n readonly runtime: Runtime\n readonly reason: UnknownMaterializationReason\n}\n\nconst declarationKeys = new Set([\n 'effectiveProfile',\n 'backend',\n 'model',\n 'execution',\n 'materializer',\n 'plan',\n 'platformAttachments',\n])\n\n/**\n * Bind a declaration to a runtime-owned executor without putting an attestable method on the\n * public Executor interface. This module is not a package export: arbitrary caller executors stay\n * unknown even if they add a lookalike `materialization()` property.\n */\nexport function attestRuntimeOwnedExecutor<Out>(\n executor: Executor<Out>,\n declaration: ExecutorMaterialization,\n binding?: ExecutorExecutionBinding,\n): Executor<Out> {\n runtimeOwnedExecutorMaterializations.set(executor as object, {\n current: Object.freeze({\n kind: 'known',\n declaration: detachedSnapshot(declaration, 'runtime-owned executor materialization'),\n ...(binding === undefined\n ? {}\n : {\n binding: detachedSnapshot(binding, 'runtime-owned executor execution binding'),\n }),\n }),\n })\n ensureProviderEvidenceState(executor)\n return executor\n}\n\n/** Brand an external Runtime executor whose exact remote materialization is provable only after\n * its terminal protocol acknowledgement. The declaration is a planned authority check, never a\n * known receipt; callers must finalize this same object after validating the acknowledgement. */\nexport function attestRuntimeOwnedPendingExecutor<Out>(\n executor: Executor<Out>,\n runtime: Runtime,\n declaration: ExecutorMaterialization,\n binding: ExecutorExecutionBinding,\n): Executor<Out> {\n runtimeOwnedExecutorMaterializations.set(executor as object, {\n current: Object.freeze({\n kind: 'pending',\n runtime,\n declaration: detachedSnapshot(declaration, 'pending executor materialization'),\n binding: detachedSnapshot(binding, 'pending executor execution binding'),\n }),\n })\n return executor\n}\n\n/** Replace a private pending brand with terminally acknowledged evidence. A caller-owned executor\n * cannot enter this path because only this module can create the pending WeakMap entry. */\nexport function finalizeRuntimeOwnedPendingExecutor<Out>(\n executor: Executor<Out>,\n declaration: ExecutorMaterialization,\n binding: ExecutorExecutionBinding,\n): Executor<Out> {\n const ref = runtimeOwnedExecutorMaterializations.get(executor as object)\n if (ref?.current.kind !== 'pending' || ref.current.runtime !== executor.runtime) {\n throw new ValidationError(\n 'executor materialization: terminal acknowledgement has no matching Runtime-owned pending executor',\n )\n }\n ref.current = Object.freeze({\n kind: 'known',\n declaration: detachedSnapshot(declaration, 'runtime-owned executor materialization'),\n binding: detachedSnapshot(binding, 'runtime-owned executor execution binding'),\n })\n return executor\n}\n\n/** Mark a runtime-owned orchestration executor whose exact leaf declaration is published through\n * its private nested Scope before the first backend inference. Arbitrary executors cannot opt in. */\nexport function attestRuntimeOwnedDeferredExecutor<Out>(\n executor: Executor<Out>,\n runtime: Runtime,\n): Executor<Out> {\n runtimeOwnedExecutorMaterializations.set(executor as object, {\n current: Object.freeze({ kind: 'deferred', runtime }),\n })\n return executor\n}\n\n/** Preserve the runtime-owned attestation when a trusted wrapper changes result semantics only. */\nexport function inheritRuntimeOwnedExecutorAttestation<In, Out>(\n source: Executor<In>,\n wrapper: Executor<Out>,\n): Executor<Out> {\n const ref = runtimeOwnedExecutorMaterializations.get(source as object)\n if (ref !== undefined) {\n runtimeOwnedExecutorMaterializations.set(wrapper as object, ref)\n }\n const providerState = ensureProviderEvidenceState(source)\n runtimeOwnedExecutorProviderEvidenceState.set(wrapper as object, providerState)\n return wrapper\n}\n\nfunction ensureProviderEvidenceState<Out>(executor: Executor<Out>): {\n readonly attempts: Array<{\n readonly observations: string[]\n identityConflict?: boolean\n providerDispatch?: 'not_started'\n }>\n} {\n const existing = runtimeOwnedExecutorProviderEvidenceState.get(executor as object)\n if (existing !== undefined) return existing\n const state = { attempts: [] }\n runtimeOwnedExecutorProviderEvidenceState.set(executor as object, state)\n return state\n}\n\n/** Read a declaration only when Runtime itself branded this exact executor object. */\nexport function runtimeOwnedExecutorMaterialization<Out>(\n executor: Executor<Out>,\n): ExecutorMaterialization | undefined {\n const attestation = runtimeOwnedExecutorMaterializations.get(executor as object)?.current\n return attestation?.kind === 'known' ? attestation.declaration : undefined\n}\n\n/** Read one attempt binding only from the private brand on this exact executor object. */\nexport function runtimeOwnedExecutorExecutionBinding<Out>(\n executor: Executor<Out>,\n): ExecutorExecutionBinding | undefined {\n const attestation = runtimeOwnedExecutorMaterializations.get(executor as object)?.current\n return attestation?.kind === 'known' ? attestation.binding : undefined\n}\n\n/** Read a planned external declaration only for Runtime's private pending brand. This is useful for\n * pre-execution authority checks, but must never be turned into a known durable receipt. */\nexport function runtimeOwnedPendingExecutorMaterialization<Out>(executor: Executor<Out>):\n | {\n readonly runtime: Runtime\n readonly declaration: ExecutorMaterialization\n readonly binding: ExecutorExecutionBinding\n }\n | undefined {\n const attestation = runtimeOwnedExecutorMaterializations.get(executor as object)?.current\n return attestation?.kind === 'pending'\n ? {\n runtime: attestation.runtime,\n declaration: attestation.declaration,\n binding: attestation.binding,\n }\n : undefined\n}\n\n/** Read the expected leaf runtime only for a privately branded deferred orchestration executor. */\nexport function runtimeOwnedDeferredExecutorRuntime<Out>(\n executor: Executor<Out>,\n): Runtime | undefined {\n const attestation = runtimeOwnedExecutorMaterializations.get(executor as object)?.current\n return attestation?.kind === 'deferred' ? attestation.runtime : undefined\n}\n\n/** Propagate trust from a built-in driver adapter to the Agent and recursive executor it owns. */\nexport function attestRuntimeOwnedScopeOwner<T extends object>(owner: T, runtime: Runtime): T {\n runtimeOwnedScopeOwners.set(owner, runtime)\n return owner\n}\n\n/** Return a built-in scope owner's expected concrete leaf runtime; caller-owned functions/Agents\n * deliberately have no entry even if they add lookalike fields. */\nexport function runtimeOwnedScopeOwnerRuntime(owner: object): Runtime | undefined {\n return runtimeOwnedScopeOwners.get(owner)\n}\n\n/** Mark one provider inference attempt on a Runtime-owned executor. */\nexport function recordRuntimeOwnedProviderAttemptStart<Out>(executor: Executor<Out>): void {\n const state = ensureProviderEvidenceState(executor)\n state.attempts.push({ observations: [] })\n}\n\n/** Mark the current attempt as rejected before provider dispatch.\n *\n * The caller may use this only after consuming the Router-owned\n * `provider_dispatch: \"not_started\"` fact. Any other error stays an empty,\n * unknown attempt and must not be upgraded here.\n */\nexport function recordRuntimeOwnedProviderDispatchNotStarted<Out>(executor: Executor<Out>): void {\n const state = ensureProviderEvidenceState(executor)\n const attempt = state.attempts.at(-1)\n if (attempt === undefined) {\n throw new ValidationError('provider dispatch rejection arrived before an attempt started')\n }\n if (attempt.observations.length > 0 || attempt.identityConflict === true) {\n throw new ValidationError(\n 'provider dispatch rejection arrived after provider identity evidence was observed',\n )\n }\n attempt.providerDispatch = 'not_started'\n}\n\n/** Record a trusted served model on the current provider attempt. */\nexport function recordRuntimeOwnedProviderModel<Out>(executor: Executor<Out>, model: string): void {\n const state = runtimeOwnedExecutorProviderEvidenceState.get(executor as object)\n const attempt = state?.attempts.at(-1)\n if (attempt === undefined) {\n throw new ValidationError('provider model observation arrived before an attempt started')\n }\n if (attempt.observations.at(-1) !== model) attempt.observations.push(model)\n}\n\n/** Convert process-local provider observations into a frozen, replayable evidence value. */\nexport function runtimeOwnedExecutorProviderEvidence<Out>(\n executor: Executor<Out>,\n): ProviderModelExecutionEvidence | undefined {\n const state = runtimeOwnedExecutorProviderEvidenceState.get(executor as object)\n if (state === undefined || state.attempts.length === 0) return undefined\n const attempts: ReadonlyArray<ProviderModelAttemptEvidence> = Object.freeze(\n state.attempts.map((attempt) =>\n Object.freeze({\n observations: Object.freeze([...attempt.observations]),\n ...(attempt.identityConflict ? { identityConflict: true } : {}),\n ...(attempt.providerDispatch === 'not_started'\n ? { providerDispatch: 'not_started' as const }\n : {}),\n }),\n ),\n )\n const models = Object.freeze([...new Set(attempts.flatMap((attempt) => attempt.observations))])\n const missing = attempts.some(\n (attempt) => attempt.observations.length === 0 && attempt.providerDispatch !== 'not_started',\n )\n const conflict = attempts.some((attempt) => attempt.identityConflict === true)\n const served = attempts.some((attempt) => attempt.observations.length > 0)\n return Object.freeze(\n missing || conflict || !served\n ? {\n status: 'unknown' as const,\n attempts,\n models,\n reason: conflict\n ? ('provider-model-conflict' as const)\n : ('provider-model-missing' as const),\n }\n : { status: 'known' as const, attempts, models },\n )\n}\n\n/** Mark the current provider attempt unusable after conflicting served identity metadata. */\nexport function recordRuntimeOwnedProviderIdentityConflict<Out>(executor: Executor<Out>): void {\n const state = ensureProviderEvidenceState(executor)\n const attempt = state.attempts.at(-1)\n if (attempt === undefined) {\n throw new ValidationError('provider identity conflict arrived before an attempt started')\n }\n attempt.identityConflict = true\n}\n\n/** Attach one executor's provider evidence to a Runtime-owned root drive for final projection. */\nexport function recordRuntimeOwnedDriveHarnessProviderEvidence(\n owner: object,\n evidence: ProviderModelExecutionEvidence | undefined,\n): void {\n if (evidence === undefined) return\n const prior = runtimeOwnedDriveHarnessProviderEvidenceState.get(owner)\n if (prior === undefined) {\n runtimeOwnedDriveHarnessProviderEvidenceState.set(owner, evidence)\n return\n }\n const attempts = Object.freeze([...prior.attempts, ...evidence.attempts])\n const models = Object.freeze([...new Set([...prior.models, ...evidence.models])])\n const missing = attempts.some(\n (attempt) => attempt.observations.length === 0 && attempt.providerDispatch !== 'not_started',\n )\n const conflict = attempts.some((attempt) => attempt.identityConflict === true)\n const served = attempts.some((attempt) => attempt.observations.length > 0)\n runtimeOwnedDriveHarnessProviderEvidenceState.set(\n owner,\n Object.freeze(\n missing || conflict || !served\n ? {\n status: 'unknown' as const,\n attempts,\n models,\n reason: conflict\n ? ('provider-model-conflict' as const)\n : ('provider-model-missing' as const),\n }\n : { status: 'known' as const, attempts, models },\n ),\n )\n}\n\n/** Read provider evidence recorded by a Runtime-owned root drive. */\nexport function runtimeOwnedDriveHarnessProviderEvidence(\n owner: object,\n): ProviderModelExecutionEvidence | undefined {\n return runtimeOwnedDriveHarnessProviderEvidenceState.get(owner)\n}\n\n/** Build one kernel-owned known receipt from a data-only executor declaration. */\nexport function knownMaterializationReceipt(\n input: KnownReceiptInput,\n): ProfileMaterializationReceipt {\n const declaration = detachedSnapshot(input.declaration, 'executor materialization')\n assertExactDeclaration(declaration)\n const effectiveProfile = agentProfileSchema.safeParse(declaration.effectiveProfile)\n if (!effectiveProfile.success) {\n throw new ValidationError('executor materialization: effectiveProfile must be an AgentProfile')\n }\n assertNonEmpty(declaration.backend, 'backend')\n assertNonEmpty(declaration.materializer, 'materializer')\n assertNonEmpty(declaration.execution?.kind, 'execution.kind')\n assertNonEmpty(declaration.execution?.id, 'execution.id')\n assertModel(declaration.model)\n\n let effectiveProfileDigest: Sha256Digest\n let materializationPlanDigest: Sha256Digest\n let platformAttachmentsDigest: Sha256Digest | undefined\n try {\n effectiveProfileDigest = canonicalAgentProfileDigest(effectiveProfile.data)\n materializationPlanDigest = canonicalCandidateDigest(jsonWireSnapshot(declaration.plan))\n platformAttachmentsDigest =\n declaration.platformAttachments === undefined\n ? undefined\n : canonicalCandidateDigest(jsonWireSnapshot(declaration.platformAttachments))\n } catch (error) {\n throw new ValidationError(\n 'executor materialization: profile, plan, and attachments must be finite RFC 8785 JSON',\n { cause: error },\n )\n }\n\n return Object.freeze({\n status: 'known' as const,\n authoredProfileDigest: input.authoredProfileDigest,\n effectiveProfileDigest,\n materializationPlanDigest,\n ...(platformAttachmentsDigest === undefined ? {} : { platformAttachmentsDigest }),\n runtime: input.runtime,\n backend: declaration.backend,\n model: declaration.model,\n execution: declaration.execution,\n materializer: declaration.materializer,\n })\n}\n\n/** Build an explicit unknown receipt without fabricating any executor-owned identity. */\nexport function unknownMaterializationReceipt(\n input: UnknownReceiptInput,\n): ProfileMaterializationReceipt {\n return Object.freeze({\n status: 'unknown' as const,\n ...(input.authoredProfileDigest === undefined\n ? {}\n : { authoredProfileDigest: input.authoredProfileDigest }),\n runtime: input.runtime,\n reason: input.reason,\n })\n}\n\n/** Mint a process-unique attempt id before executor construction. */\nexport function newExecutionAttemptId(nodeId: string): string {\n return `${nodeId}:attempt:${randomUUID()}`\n}\n\n/** Build the immutable safe receipt for a full, transient execution binding. */\nexport function knownExecutionBindingReceipt(\n materialization: ProfileMaterializationReceipt,\n bindingInput: ExecutorExecutionBinding,\n): ExecutionBindingReceipt {\n const binding = detachedSnapshot(bindingInput, 'executor execution binding')\n assertNonEmpty(binding.attemptId, 'binding.attemptId')\n assertSafeDescriptor(binding.descriptor)\n let materializationReceiptDigest: Sha256Digest\n let bindingDigest: Sha256Digest\n try {\n materializationReceiptDigest = canonicalCandidateDigest(materialization)\n // Bind the exact JSON document a backend receives. Optional AgentProfile fields are represented\n // as `undefined` in memory but omitted by JSON transport; normalize that one distinction while\n // rejecting every non-finite/non-data value instead of silently coercing it.\n bindingDigest = canonicalCandidateDigest(jsonWireSnapshot(binding.binding))\n } catch (error) {\n throw new ValidationError('executor binding must be finite RFC 8785 JSON', { cause: error })\n }\n return Object.freeze({\n status: 'known' as const,\n attemptId: binding.attemptId,\n materializationReceiptDigest,\n bindingDigest,\n descriptor: binding.descriptor,\n })\n}\n\n/** Preserve an attempt boundary even when its caller-owned transport cannot be attested. */\nexport function unknownExecutionBindingReceipt(\n materialization: ProfileMaterializationReceipt,\n attemptId: string,\n reason: UnknownMaterializationReason,\n): ExecutionBindingReceipt {\n assertNonEmpty(attemptId, 'binding.attemptId')\n return Object.freeze({\n status: 'unknown' as const,\n attemptId,\n materializationReceiptDigest: canonicalCandidateDigest(materialization),\n reason,\n })\n}\n\n/** Derive an authored-profile digest without turning non-canonical input into a fake identity. */\nexport function authoredProfileDigest(profile: unknown): Sha256Digest | undefined {\n try {\n return canonicalAgentProfileDigest(agentProfileSchema.parse(profile))\n } catch {\n return undefined\n }\n}\n\nfunction assertExactDeclaration(value: ExecutorMaterialization): void {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new ValidationError('executor materialization: declaration must be an object')\n }\n const unknown = Object.keys(value).filter((key) => !declarationKeys.has(key))\n if (unknown.length > 0) {\n throw new ValidationError(\n `executor materialization: unknown declaration fields: ${unknown.sort().join(', ')}`,\n )\n }\n if (!Object.hasOwn(value, 'plan')) {\n throw new ValidationError('executor materialization: plan is required')\n }\n}\n\nfunction assertModel(model: ExecutorMaterialization['model']): void {\n if (typeof model !== 'object' || model === null || Array.isArray(model)) {\n throw new ValidationError('executor materialization: model must be a known/unknown identity')\n }\n const keys = Object.keys(model).sort()\n if (model.status === 'known') {\n if (keys.join(',') !== 'id,status') {\n throw new ValidationError('executor materialization: known model accepts only status and id')\n }\n assertNonEmpty(model.id, 'model.id')\n return\n }\n if (model.status === 'unknown') {\n if (keys.join(',') !== 'reason,status') {\n throw new ValidationError(\n 'executor materialization: unknown model accepts only status and reason',\n )\n }\n assertNonEmpty(model.reason, 'model.reason')\n return\n }\n throw new ValidationError('executor materialization: model.status must be known or unknown')\n}\n\nfunction assertNonEmpty(value: unknown, field: string): asserts value is string {\n if (typeof value !== 'string' || value.trim().length === 0) {\n throw new ValidationError(`executor materialization: ${field} must be a non-empty string`)\n }\n}\n\nfunction assertSafeDescriptor(descriptor: ExecutorExecutionBinding['descriptor']): void {\n if (typeof descriptor !== 'object' || descriptor === null || Array.isArray(descriptor)) {\n throw new ValidationError('executor binding: descriptor must be an object')\n }\n for (const [key, value] of Object.entries(descriptor)) {\n if (/(url|uri|token|key|secret|bearer|credential|authorization)/i.test(key)) {\n throw new ValidationError(`executor binding: unsafe descriptor key ${JSON.stringify(key)}`)\n }\n if (\n value !== null &&\n typeof value !== 'string' &&\n typeof value !== 'number' &&\n typeof value !== 'boolean'\n ) {\n throw new ValidationError(\n `executor binding: descriptor ${JSON.stringify(key)} must be scalar`,\n )\n }\n if (typeof value === 'string' && (value.includes('://') || value.includes('@'))) {\n throw new ValidationError(\n `executor binding: descriptor ${JSON.stringify(key)} contains transport or credential text`,\n )\n }\n }\n}\n\nfunction jsonWireSnapshot(value: unknown, path = '$'): unknown {\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return value\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) {\n throw new ValidationError(`executor binding: ${path} must be finite`)\n }\n return value\n }\n if (Array.isArray(value)) {\n return value.map((item, index) => {\n if (item === undefined) {\n throw new ValidationError(`executor binding: ${path}[${index}] cannot be undefined`)\n }\n return jsonWireSnapshot(item, `${path}[${index}]`)\n })\n }\n if (typeof value !== 'object' || value === null) {\n throw new ValidationError(`executor binding: ${path} must be JSON data`)\n }\n const prototype = Object.getPrototypeOf(value)\n if (prototype !== Object.prototype && prototype !== null) {\n throw new ValidationError(`executor binding: ${path} must be a plain object`)\n }\n const out: Record<string, unknown> = {}\n for (const [key, item] of Object.entries(value as Record<string, unknown>)) {\n if (item === undefined) continue\n out[key] = jsonWireSnapshot(item, `${path}.${key}`)\n }\n return out\n}\n"],"mappings":";;;;;;;;;;;;AAWA,SAAgB,+BAA+B,KAAc,SAA+B;CAC1F,MAAM,QAAQ,iBAAiB,KAAK,GAAG,QAAQ,qBAAqB;CACpE,MAAM,UAAU,mBAAmB,MAAM,KAAK;CAC9C,6BAA6B,SAAS,OAAO;CAC7C,OAAO,iBAAiB,SAAS,GAAG,QAAQ,sBAAsB;AACpE;;AAGA,SAAgB,4BAA4B,KAAgB,SAA4B;CACtF,MAAM,EACJ,SAAS,YACT,SACA,WAAW,cACX,GAAG,sBACD;CACJ,MAAM,UAAU,+BAA+B,YAAY,OAAO;CAClE,MAAM,YACJ,iBAAiB,KAAA,IACb,KAAA,IACA,iBAAiB,cAAc,GAAG,QAAQ,wBAAwB;CACxE,OAAO,OAAO,OAAO;EACnB,GAAG;EACH;EACA;EACA,GAAI,cAAc,KAAA,IAAY,CAAC,IAAI,EAAE,UAAU;CACjD,CAAC;AACH;;;ACMA,MAAM,uDAAuC,IAAI,QAG/C;AACF,MAAM,0CAA0B,IAAI,QAAyB;AAC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;EAErF,OAAO,iBAAiB,MAAM,GAAG,KAAK,GAAG,MAAM,EAAE;CACnD,CAAC;CAEH,IAAI,OAAO,UAAU,YAAY,UAAU,MACzC,MAAM,IAAI,gBAAgB,qBAAqB,KAAK,mBAAmB;CAEzE,MAAM,YAAY,OAAO,eAAe,KAAK;CAC7C,IAAI,cAAc,OAAO,aAAa,cAAc,MAClD,MAAM,IAAI,gBAAgB,qBAAqB,KAAK,wBAAwB;CAE9E,MAAM,MAA+B,CAAC;CACtC,KAAK,MAAM,CAAC,KAAK,SAAS,OAAO,QAAQ,KAAgC,GAAG;EAC1E,IAAI,SAAS,KAAA,GAAW;EACxB,IAAI,OAAO,iBAAiB,MAAM,GAAG,KAAK,GAAG,KAAK;CACpD;CACA,OAAO;AACT"}
1
+ {"version":3,"file":"materialization-CrdcfWXp.js","names":[],"sources":["../src/runtime/supervise/executable-spec.ts","../src/runtime/supervise/materialization.ts"],"sourcesContent":["import { type AgentProfile, agentProfileSchema } from '@tangle-network/agent-interface'\nimport { assertExecutableAgentProfile } from './model-policy'\nimport { detachedSnapshot } from './snapshot'\nimport type { AgentSpec } from './types'\n\n/**\n * Parse one untrusted profile into the exact immutable value execution may consume.\n *\n * Snapshotting before schema parsing reads caller-owned fields once. Snapshotting the parsed\n * result prevents downstream custom code from changing any identity or authority field.\n */\nexport function executableAgentProfileSnapshot(raw: unknown, context: string): AgentProfile {\n const input = detachedSnapshot(raw, `${context}: AgentProfile input`)\n const profile = agentProfileSchema.parse(input)\n assertExecutableAgentProfile(profile, context)\n return detachedSnapshot(profile, `${context}: parsed AgentProfile`)\n}\n\n/** Snapshot an executable spec while retaining trusted callbacks by reference. */\nexport function executableAgentSpecSnapshot(raw: AgentSpec, context: string): AgentSpec {\n const {\n profile: rawProfile,\n harness,\n execution: rawExecution,\n ...runtimeExtensions\n } = raw as AgentSpec & Readonly<Record<string, unknown>>\n const profile = executableAgentProfileSnapshot(rawProfile, context)\n const execution =\n rawExecution === undefined\n ? undefined\n : detachedSnapshot(rawExecution, `${context}: execution attribution`)\n return Object.freeze({\n ...runtimeExtensions,\n profile,\n harness,\n ...(execution === undefined ? {} : { execution }),\n }) as AgentSpec\n}\n","import { randomUUID } from 'node:crypto'\nimport {\n agentProfileSchema,\n canonicalAgentProfileDigest,\n canonicalCandidateDigest,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport { ValidationError } from '../../errors'\nimport { detachedSnapshot } from './snapshot'\nimport type {\n ExecutionBindingReceipt,\n Executor,\n ExecutorExecutionBinding,\n ExecutorMaterialization,\n ProfileMaterializationReceipt,\n ProviderModelAttemptEvidence,\n ProviderModelExecutionEvidence,\n Runtime,\n UnknownMaterializationReason,\n} from './types'\n\ntype RuntimeOwnedExecutorMaterialization =\n | {\n readonly kind: 'known'\n readonly declaration: ExecutorMaterialization\n readonly binding?: ExecutorExecutionBinding\n }\n | {\n /** A Runtime-owned external executor whose exact launch is known, but whose remote\n * materializer has not yet returned its terminal acknowledgement. This private state lets\n * Runtime validate the planned authority before execution without presenting it as proof\n * that the remote process actually used that plan. */\n readonly kind: 'pending'\n readonly runtime: Runtime\n readonly declaration: ExecutorMaterialization\n readonly binding: ExecutorExecutionBinding\n }\n | { readonly kind: 'deferred'; readonly runtime: Runtime }\n\ninterface RuntimeOwnedExecutorMaterializationRef {\n current: RuntimeOwnedExecutorMaterialization\n}\n\nconst runtimeOwnedExecutorMaterializations = new WeakMap<\n object,\n RuntimeOwnedExecutorMaterializationRef\n>()\nconst runtimeOwnedScopeOwners = new WeakMap<object, Runtime>()\nconst runtimeOwnedExecutorProviderEvidenceState = new WeakMap<\n object,\n {\n readonly attempts: Array<{\n readonly observations: string[]\n identityConflict?: boolean\n providerDispatch?: 'not_started'\n }>\n }\n>()\nconst runtimeOwnedDriveHarnessProviderEvidenceState = new WeakMap<\n object,\n ProviderModelExecutionEvidence\n>()\n\ninterface KnownReceiptInput {\n readonly authoredProfileDigest: Sha256Digest\n readonly runtime: Runtime\n readonly declaration: ExecutorMaterialization\n}\n\ninterface UnknownReceiptInput {\n readonly authoredProfileDigest?: Sha256Digest\n readonly runtime: Runtime\n readonly reason: UnknownMaterializationReason\n}\n\nconst declarationKeys = new Set([\n 'effectiveProfile',\n 'backend',\n 'model',\n 'execution',\n 'materializer',\n 'plan',\n 'platformAttachments',\n])\n\n/**\n * Bind a declaration to a runtime-owned executor without putting an attestable method on the\n * public Executor interface. This module is not a package export: arbitrary caller executors stay\n * unknown even if they add a lookalike `materialization()` property.\n */\nexport function attestRuntimeOwnedExecutor<Out>(\n executor: Executor<Out>,\n declaration: ExecutorMaterialization,\n binding?: ExecutorExecutionBinding,\n): Executor<Out> {\n runtimeOwnedExecutorMaterializations.set(executor as object, {\n current: Object.freeze({\n kind: 'known',\n declaration: detachedSnapshot(declaration, 'runtime-owned executor materialization'),\n ...(binding === undefined\n ? {}\n : {\n binding: detachedSnapshot(binding, 'runtime-owned executor execution binding'),\n }),\n }),\n })\n ensureProviderEvidenceState(executor)\n return executor\n}\n\n/** Brand an external Runtime executor whose exact remote materialization is provable only after\n * its terminal protocol acknowledgement. The declaration is a planned authority check, never a\n * known receipt; callers must finalize this same object after validating the acknowledgement. */\nexport function attestRuntimeOwnedPendingExecutor<Out>(\n executor: Executor<Out>,\n runtime: Runtime,\n declaration: ExecutorMaterialization,\n binding: ExecutorExecutionBinding,\n): Executor<Out> {\n runtimeOwnedExecutorMaterializations.set(executor as object, {\n current: Object.freeze({\n kind: 'pending',\n runtime,\n declaration: detachedSnapshot(declaration, 'pending executor materialization'),\n binding: detachedSnapshot(binding, 'pending executor execution binding'),\n }),\n })\n return executor\n}\n\n/** Replace a private pending brand with terminally acknowledged evidence. A caller-owned executor\n * cannot enter this path because only this module can create the pending WeakMap entry. */\nexport function finalizeRuntimeOwnedPendingExecutor<Out>(\n executor: Executor<Out>,\n declaration: ExecutorMaterialization,\n binding: ExecutorExecutionBinding,\n): Executor<Out> {\n const ref = runtimeOwnedExecutorMaterializations.get(executor as object)\n if (ref?.current.kind !== 'pending' || ref.current.runtime !== executor.runtime) {\n throw new ValidationError(\n 'executor materialization: terminal acknowledgement has no matching Runtime-owned pending executor',\n )\n }\n ref.current = Object.freeze({\n kind: 'known',\n declaration: detachedSnapshot(declaration, 'runtime-owned executor materialization'),\n binding: detachedSnapshot(binding, 'runtime-owned executor execution binding'),\n })\n return executor\n}\n\n/** Mark a runtime-owned orchestration executor whose exact leaf declaration is published through\n * its private nested Scope before the first backend inference. Arbitrary executors cannot opt in. */\nexport function attestRuntimeOwnedDeferredExecutor<Out>(\n executor: Executor<Out>,\n runtime: Runtime,\n): Executor<Out> {\n runtimeOwnedExecutorMaterializations.set(executor as object, {\n current: Object.freeze({ kind: 'deferred', runtime }),\n })\n return executor\n}\n\n/** Preserve the runtime-owned attestation when a trusted wrapper changes result semantics only. */\nexport function inheritRuntimeOwnedExecutorAttestation<In, Out>(\n source: Executor<In>,\n wrapper: Executor<Out>,\n): Executor<Out> {\n const ref = runtimeOwnedExecutorMaterializations.get(source as object)\n if (ref !== undefined) {\n runtimeOwnedExecutorMaterializations.set(wrapper as object, ref)\n }\n const providerState = ensureProviderEvidenceState(source)\n runtimeOwnedExecutorProviderEvidenceState.set(wrapper as object, providerState)\n return wrapper\n}\n\nfunction ensureProviderEvidenceState<Out>(executor: Executor<Out>): {\n readonly attempts: Array<{\n readonly observations: string[]\n identityConflict?: boolean\n providerDispatch?: 'not_started'\n }>\n} {\n const existing = runtimeOwnedExecutorProviderEvidenceState.get(executor as object)\n if (existing !== undefined) return existing\n const state = { attempts: [] }\n runtimeOwnedExecutorProviderEvidenceState.set(executor as object, state)\n return state\n}\n\n/** Read a declaration only when Runtime itself branded this exact executor object. */\nexport function runtimeOwnedExecutorMaterialization<Out>(\n executor: Executor<Out>,\n): ExecutorMaterialization | undefined {\n const attestation = runtimeOwnedExecutorMaterializations.get(executor as object)?.current\n return attestation?.kind === 'known' ? attestation.declaration : undefined\n}\n\n/** Read one attempt binding only from the private brand on this exact executor object. */\nexport function runtimeOwnedExecutorExecutionBinding<Out>(\n executor: Executor<Out>,\n): ExecutorExecutionBinding | undefined {\n const attestation = runtimeOwnedExecutorMaterializations.get(executor as object)?.current\n return attestation?.kind === 'known' ? attestation.binding : undefined\n}\n\n/** Read a planned external declaration only for Runtime's private pending brand. This is useful for\n * pre-execution authority checks, but must never be turned into a known durable receipt. */\nexport function runtimeOwnedPendingExecutorMaterialization<Out>(executor: Executor<Out>):\n | {\n readonly runtime: Runtime\n readonly declaration: ExecutorMaterialization\n readonly binding: ExecutorExecutionBinding\n }\n | undefined {\n const attestation = runtimeOwnedExecutorMaterializations.get(executor as object)?.current\n return attestation?.kind === 'pending'\n ? {\n runtime: attestation.runtime,\n declaration: attestation.declaration,\n binding: attestation.binding,\n }\n : undefined\n}\n\n/** Read the expected leaf runtime only for a privately branded deferred orchestration executor. */\nexport function runtimeOwnedDeferredExecutorRuntime<Out>(\n executor: Executor<Out>,\n): Runtime | undefined {\n const attestation = runtimeOwnedExecutorMaterializations.get(executor as object)?.current\n return attestation?.kind === 'deferred' ? attestation.runtime : undefined\n}\n\n/** Propagate trust from a built-in driver adapter to the Agent and recursive executor it owns. */\nexport function attestRuntimeOwnedScopeOwner<T extends object>(owner: T, runtime: Runtime): T {\n runtimeOwnedScopeOwners.set(owner, runtime)\n return owner\n}\n\n/** Return a built-in scope owner's expected concrete leaf runtime; caller-owned functions/Agents\n * deliberately have no entry even if they add lookalike fields. */\nexport function runtimeOwnedScopeOwnerRuntime(owner: object): Runtime | undefined {\n return runtimeOwnedScopeOwners.get(owner)\n}\n\n/** Mark one provider inference attempt on a Runtime-owned executor. */\nexport function recordRuntimeOwnedProviderAttemptStart<Out>(executor: Executor<Out>): void {\n const state = ensureProviderEvidenceState(executor)\n state.attempts.push({ observations: [] })\n}\n\n/** Mark the current attempt as rejected before provider dispatch.\n *\n * The caller may use this only after consuming the Router-owned\n * `provider_dispatch: \"not_started\"` fact. Any other error stays an empty,\n * unknown attempt and must not be upgraded here.\n */\nexport function recordRuntimeOwnedProviderDispatchNotStarted<Out>(executor: Executor<Out>): void {\n const state = ensureProviderEvidenceState(executor)\n const attempt = state.attempts.at(-1)\n if (attempt === undefined) {\n throw new ValidationError('provider dispatch rejection arrived before an attempt started')\n }\n if (attempt.observations.length > 0 || attempt.identityConflict === true) {\n throw new ValidationError(\n 'provider dispatch rejection arrived after provider identity evidence was observed',\n )\n }\n attempt.providerDispatch = 'not_started'\n}\n\n/** Record a trusted served model on the current provider attempt. */\nexport function recordRuntimeOwnedProviderModel<Out>(executor: Executor<Out>, model: string): void {\n const state = runtimeOwnedExecutorProviderEvidenceState.get(executor as object)\n const attempt = state?.attempts.at(-1)\n if (attempt === undefined) {\n throw new ValidationError('provider model observation arrived before an attempt started')\n }\n if (attempt.observations.at(-1) !== model) attempt.observations.push(model)\n}\n\n/** Convert process-local provider observations into a frozen, replayable evidence value. */\nexport function runtimeOwnedExecutorProviderEvidence<Out>(\n executor: Executor<Out>,\n): ProviderModelExecutionEvidence | undefined {\n const state = runtimeOwnedExecutorProviderEvidenceState.get(executor as object)\n if (state === undefined || state.attempts.length === 0) return undefined\n const attempts: ReadonlyArray<ProviderModelAttemptEvidence> = Object.freeze(\n state.attempts.map((attempt) =>\n Object.freeze({\n observations: Object.freeze([...attempt.observations]),\n ...(attempt.identityConflict ? { identityConflict: true } : {}),\n ...(attempt.providerDispatch === 'not_started'\n ? { providerDispatch: 'not_started' as const }\n : {}),\n }),\n ),\n )\n const models = Object.freeze([...new Set(attempts.flatMap((attempt) => attempt.observations))])\n const missing = attempts.some(\n (attempt) => attempt.observations.length === 0 && attempt.providerDispatch !== 'not_started',\n )\n const conflict = attempts.some((attempt) => attempt.identityConflict === true)\n const served = attempts.some((attempt) => attempt.observations.length > 0)\n return Object.freeze(\n missing || conflict || !served\n ? {\n status: 'unknown' as const,\n attempts,\n models,\n reason: conflict\n ? ('provider-model-conflict' as const)\n : ('provider-model-missing' as const),\n }\n : { status: 'known' as const, attempts, models },\n )\n}\n\n/** Mark the current provider attempt unusable after conflicting served identity metadata. */\nexport function recordRuntimeOwnedProviderIdentityConflict<Out>(executor: Executor<Out>): void {\n const state = ensureProviderEvidenceState(executor)\n const attempt = state.attempts.at(-1)\n if (attempt === undefined) {\n throw new ValidationError('provider identity conflict arrived before an attempt started')\n }\n attempt.identityConflict = true\n}\n\n/** Attach one executor's provider evidence to a Runtime-owned root drive for final projection. */\nexport function recordRuntimeOwnedDriveHarnessProviderEvidence(\n owner: object,\n evidence: ProviderModelExecutionEvidence | undefined,\n): void {\n if (evidence === undefined) return\n const prior = runtimeOwnedDriveHarnessProviderEvidenceState.get(owner)\n if (prior === undefined) {\n runtimeOwnedDriveHarnessProviderEvidenceState.set(owner, evidence)\n return\n }\n const attempts = Object.freeze([...prior.attempts, ...evidence.attempts])\n const models = Object.freeze([...new Set([...prior.models, ...evidence.models])])\n const missing = attempts.some(\n (attempt) => attempt.observations.length === 0 && attempt.providerDispatch !== 'not_started',\n )\n const conflict = attempts.some((attempt) => attempt.identityConflict === true)\n const served = attempts.some((attempt) => attempt.observations.length > 0)\n runtimeOwnedDriveHarnessProviderEvidenceState.set(\n owner,\n Object.freeze(\n missing || conflict || !served\n ? {\n status: 'unknown' as const,\n attempts,\n models,\n reason: conflict\n ? ('provider-model-conflict' as const)\n : ('provider-model-missing' as const),\n }\n : { status: 'known' as const, attempts, models },\n ),\n )\n}\n\n/** Read provider evidence recorded by a Runtime-owned root drive. */\nexport function runtimeOwnedDriveHarnessProviderEvidence(\n owner: object,\n): ProviderModelExecutionEvidence | undefined {\n return runtimeOwnedDriveHarnessProviderEvidenceState.get(owner)\n}\n\n/** Build one kernel-owned known receipt from a data-only executor declaration. */\nexport function knownMaterializationReceipt(\n input: KnownReceiptInput,\n): ProfileMaterializationReceipt {\n const declaration = detachedSnapshot(input.declaration, 'executor materialization')\n assertExactDeclaration(declaration)\n const effectiveProfile = agentProfileSchema.safeParse(declaration.effectiveProfile)\n if (!effectiveProfile.success) {\n throw new ValidationError('executor materialization: effectiveProfile must be an AgentProfile')\n }\n assertNonEmpty(declaration.backend, 'backend')\n assertNonEmpty(declaration.materializer, 'materializer')\n assertNonEmpty(declaration.execution?.kind, 'execution.kind')\n assertNonEmpty(declaration.execution?.id, 'execution.id')\n assertModel(declaration.model)\n\n let effectiveProfileDigest: Sha256Digest\n let materializationPlanDigest: Sha256Digest\n let platformAttachmentsDigest: Sha256Digest | undefined\n try {\n effectiveProfileDigest = canonicalAgentProfileDigest(effectiveProfile.data)\n materializationPlanDigest = canonicalCandidateDigest(jsonWireSnapshot(declaration.plan))\n platformAttachmentsDigest =\n declaration.platformAttachments === undefined\n ? undefined\n : canonicalCandidateDigest(jsonWireSnapshot(declaration.platformAttachments))\n } catch (error) {\n throw new ValidationError(\n 'executor materialization: profile, plan, and attachments must be finite RFC 8785 JSON',\n { cause: error },\n )\n }\n\n return Object.freeze({\n status: 'known' as const,\n authoredProfileDigest: input.authoredProfileDigest,\n effectiveProfileDigest,\n materializationPlanDigest,\n ...(platformAttachmentsDigest === undefined ? {} : { platformAttachmentsDigest }),\n runtime: input.runtime,\n backend: declaration.backend,\n model: declaration.model,\n execution: declaration.execution,\n materializer: declaration.materializer,\n })\n}\n\n/** Build an explicit unknown receipt without fabricating any executor-owned identity. */\nexport function unknownMaterializationReceipt(\n input: UnknownReceiptInput,\n): ProfileMaterializationReceipt {\n return Object.freeze({\n status: 'unknown' as const,\n ...(input.authoredProfileDigest === undefined\n ? {}\n : { authoredProfileDigest: input.authoredProfileDigest }),\n runtime: input.runtime,\n reason: input.reason,\n })\n}\n\n/** Mint a process-unique attempt id before executor construction. */\nexport function newExecutionAttemptId(nodeId: string): string {\n return `${nodeId}:attempt:${randomUUID()}`\n}\n\n/** Build the immutable safe receipt for a full, transient execution binding. */\nexport function knownExecutionBindingReceipt(\n materialization: ProfileMaterializationReceipt,\n bindingInput: ExecutorExecutionBinding,\n): ExecutionBindingReceipt {\n const binding = detachedSnapshot(bindingInput, 'executor execution binding')\n assertNonEmpty(binding.attemptId, 'binding.attemptId')\n assertSafeDescriptor(binding.descriptor)\n let materializationReceiptDigest: Sha256Digest\n let bindingDigest: Sha256Digest\n try {\n materializationReceiptDigest = canonicalCandidateDigest(materialization)\n // Bind the exact JSON document a backend receives. Optional AgentProfile fields are represented\n // as `undefined` in memory but omitted by JSON transport; normalize that one distinction while\n // rejecting every non-finite/non-data value instead of silently coercing it.\n bindingDigest = canonicalCandidateDigest(jsonWireSnapshot(binding.binding))\n } catch (error) {\n throw new ValidationError('executor binding must be finite RFC 8785 JSON', { cause: error })\n }\n return Object.freeze({\n status: 'known' as const,\n attemptId: binding.attemptId,\n materializationReceiptDigest,\n bindingDigest,\n descriptor: binding.descriptor,\n })\n}\n\n/** Preserve an attempt boundary even when its caller-owned transport cannot be attested. */\nexport function unknownExecutionBindingReceipt(\n materialization: ProfileMaterializationReceipt,\n attemptId: string,\n reason: UnknownMaterializationReason,\n): ExecutionBindingReceipt {\n assertNonEmpty(attemptId, 'binding.attemptId')\n return Object.freeze({\n status: 'unknown' as const,\n attemptId,\n materializationReceiptDigest: canonicalCandidateDigest(materialization),\n reason,\n })\n}\n\n/** Derive an authored-profile digest without turning non-canonical input into a fake identity. */\nexport function authoredProfileDigest(profile: unknown): Sha256Digest | undefined {\n try {\n return canonicalAgentProfileDigest(agentProfileSchema.parse(profile))\n } catch {\n return undefined\n }\n}\n\nfunction assertExactDeclaration(value: ExecutorMaterialization): void {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new ValidationError('executor materialization: declaration must be an object')\n }\n const unknown = Object.keys(value).filter((key) => !declarationKeys.has(key))\n if (unknown.length > 0) {\n throw new ValidationError(\n `executor materialization: unknown declaration fields: ${unknown.sort().join(', ')}`,\n )\n }\n if (!Object.hasOwn(value, 'plan')) {\n throw new ValidationError('executor materialization: plan is required')\n }\n}\n\nfunction assertModel(model: ExecutorMaterialization['model']): void {\n if (typeof model !== 'object' || model === null || Array.isArray(model)) {\n throw new ValidationError('executor materialization: model must be a known/unknown identity')\n }\n const keys = Object.keys(model).sort()\n if (model.status === 'known') {\n if (keys.join(',') !== 'id,status') {\n throw new ValidationError('executor materialization: known model accepts only status and id')\n }\n assertNonEmpty(model.id, 'model.id')\n return\n }\n if (model.status === 'unknown') {\n if (keys.join(',') !== 'reason,status') {\n throw new ValidationError(\n 'executor materialization: unknown model accepts only status and reason',\n )\n }\n assertNonEmpty(model.reason, 'model.reason')\n return\n }\n throw new ValidationError('executor materialization: model.status must be known or unknown')\n}\n\nfunction assertNonEmpty(value: unknown, field: string): asserts value is string {\n if (typeof value !== 'string' || value.trim().length === 0) {\n throw new ValidationError(`executor materialization: ${field} must be a non-empty string`)\n }\n}\n\nfunction assertSafeDescriptor(descriptor: ExecutorExecutionBinding['descriptor']): void {\n if (typeof descriptor !== 'object' || descriptor === null || Array.isArray(descriptor)) {\n throw new ValidationError('executor binding: descriptor must be an object')\n }\n for (const [key, value] of Object.entries(descriptor)) {\n if (/(url|uri|token|key|secret|bearer|credential|authorization)/i.test(key)) {\n throw new ValidationError(`executor binding: unsafe descriptor key ${JSON.stringify(key)}`)\n }\n if (\n value !== null &&\n typeof value !== 'string' &&\n typeof value !== 'number' &&\n typeof value !== 'boolean'\n ) {\n throw new ValidationError(\n `executor binding: descriptor ${JSON.stringify(key)} must be scalar`,\n )\n }\n if (typeof value === 'string' && (value.includes('://') || value.includes('@'))) {\n throw new ValidationError(\n `executor binding: descriptor ${JSON.stringify(key)} contains transport or credential text`,\n )\n }\n }\n}\n\nfunction jsonWireSnapshot(value: unknown, path = '$'): unknown {\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return value\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) {\n throw new ValidationError(`executor binding: ${path} must be finite`)\n }\n return value\n }\n if (Array.isArray(value)) {\n return value.map((item, index) => {\n if (item === undefined) {\n throw new ValidationError(`executor binding: ${path}[${index}] cannot be undefined`)\n }\n return jsonWireSnapshot(item, `${path}[${index}]`)\n })\n }\n if (typeof value !== 'object' || value === null) {\n throw new ValidationError(`executor binding: ${path} must be JSON data`)\n }\n const prototype = Object.getPrototypeOf(value)\n if (prototype !== Object.prototype && prototype !== null) {\n throw new ValidationError(`executor binding: ${path} must be a plain object`)\n }\n const out: Record<string, unknown> = {}\n for (const [key, item] of Object.entries(value as Record<string, unknown>)) {\n if (item === undefined) continue\n out[key] = jsonWireSnapshot(item, `${path}.${key}`)\n }\n return out\n}\n"],"mappings":";;;;;;;;;;;;AAWA,SAAgB,+BAA+B,KAAc,SAA+B;CAC1F,MAAM,QAAQ,iBAAiB,KAAK,GAAG,QAAQ,qBAAqB;CACpE,MAAM,UAAU,mBAAmB,MAAM,KAAK;CAC9C,6BAA6B,SAAS,OAAO;CAC7C,OAAO,iBAAiB,SAAS,GAAG,QAAQ,sBAAsB;AACpE;;AAGA,SAAgB,4BAA4B,KAAgB,SAA4B;CACtF,MAAM,EACJ,SAAS,YACT,SACA,WAAW,cACX,GAAG,sBACD;CACJ,MAAM,UAAU,+BAA+B,YAAY,OAAO;CAClE,MAAM,YACJ,iBAAiB,KAAA,IACb,KAAA,IACA,iBAAiB,cAAc,GAAG,QAAQ,wBAAwB;CACxE,OAAO,OAAO,OAAO;EACnB,GAAG;EACH;EACA;EACA,GAAI,cAAc,KAAA,IAAY,CAAC,IAAI,EAAE,UAAU;CACjD,CAAC;AACH;;;ACMA,MAAM,uDAAuC,IAAI,QAG/C;AACF,MAAM,0CAA0B,IAAI,QAAyB;AAC7D,MAAM,4DAA4C,IAAI,QASpD;AACF,MAAM,gEAAgD,IAAI,QAGxD;AAcF,MAAM,kCAAkB,IAAI,IAAI;CAC9B;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;;AAOD,SAAgB,2BACd,UACA,aACA,SACe;CACf,qCAAqC,IAAI,UAAoB,EAC3D,SAAS,OAAO,OAAO;EACrB,MAAM;EACN,aAAa,iBAAiB,aAAa,wCAAwC;EACnF,GAAI,YAAY,KAAA,IACZ,CAAC,IACD,EACE,SAAS,iBAAiB,SAAS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AO,QAAQ,KAAgC,GAAG;EAC1E,IAAI,SAAS,KAAA,GAAW;EACxB,IAAI,OAAO,iBAAiB,MAAM,GAAG,KAAK,GAAG,KAAK;CACpD;CACA,OAAO;AACT"}
package/dist/mcp/bin.js CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import { i as ConfigError } from "../errors-CVIDr7GQ.js";
3
- import { St as readTraceContextFromEnv } from "../supervisor-BoC2tFgH.js";
4
- import { C as createMcpServer, Z as DelegationTaskQueue, st as FileDelegationStore } from "../supervise-CUJRmx3s.js";
5
- import { a as supervisorInstructions } from "../authoring-Cw6Ufsng.js";
2
+ import { i as ConfigError } from "../errors-CDZ8XsVj.js";
3
+ import { St as readTraceContextFromEnv } from "../supervisor-BV72aDmP.js";
4
+ import { C as createMcpServer, Z as DelegationTaskQueue, st as FileDelegationStore } from "../supervise-Cx1QY_hj.js";
5
+ import { a as supervisorInstructions } from "../authoring-J93uFAwd.js";
6
6
  //#region src/mcp/delegate-supervisor-provisioning.ts
7
7
  function trimmed(value) {
8
8
  const v = value?.trim();
@@ -1,10 +1,10 @@
1
- import { E as SandboxClient, h as LoopSandboxPlacement } from "../types-BBwGSiAj.js";
2
- import { $l as WorkerSpawnContext, $u as DelegationResumeTick, Ad as FeedbackRefersTo, Au as detachedSessionDelegate, Bd as DelegationTraceSpan, Bl as DownMessageDeliveryAttempt, Bu as DetachedTurnResumeDriverOptions, Cd as DelegationProfile, Cu as CoderReviewer, Dd as DelegationStatusArgs, Du as SettleDetachedCoderTurnOptions, Ed as DelegationStatus, Ef as CoderOutput, Eu as DetachedWinnerSelection, Fd as CappedDelegationTrace, Fl as CoordinationEvent, Fu as SiblingSandboxExecutorOptions, Gd as DelegationPersistenceError, Gl as QuestionDecision, Gu as detachedTurnEvents, Hd as capDelegationTrace, Hl as DownMessageEvent, Hu as DriveTurnTick, Id as DELEGATION_TRACE_MAX_BYTES, Il as CoordinationTools, Iu as createFleetWorkspaceExecutor, Jd as FileDelegationStore, Jl as QuestionPolicy, Ju as runDetachedTurn, Kd as DelegationStateCorruptError, Kl as QuestionLevel, Ku as formatDetachedSessionRef, Ld as DELEGATION_TRACE_MAX_SPANS, Ll as CoordinationToolsOptions, Lu as createSiblingSandboxExecutor, Md as ResearchSource, Ml as AuthorizedDownMessage, Mu as DelegationExecutor, Nd as UiAuditLensFilter, Nl as ContinuationInstruction, Nu as FleetHandle, Od as DelegationStatusResult, Ol as AnalystFindingEvent, Ou as UiAuditorDelegate, Pd as UiAuditorDelegationOutput, Pu as FleetWorkspaceExecutorOptions, Qu as DelegationResumeDriver, Rd as DelegationTraceCaps, Rl as DEFAULT_AWAIT_EVENT_TIMEOUT_MS, Ru as DetachedSessionRefParts, Sd as DelegationHistoryResult, Su as CoderReview, Td as DelegationResultPayload, Tu as DetachedSessionDelegateOptions, Ud as composeLoopTraceEmitters, Ul as MakeWorkerAgent, Uu as RunDetachedTurnOptions, Vd as buildDelegationTraceSpans, Vl as DownMessageDeliveryOutcome, Vu as DriveTurnCapableBox, Wd as createDelegationTraceCollector, Wl as Question, Wu as createDetachedTurnResumeDriver, Xd as InMemoryDelegationStore, Xl as QuestionUrgency, Xu as DelegationRecord, Yd as FileDelegationStoreOptions, Yl as QuestionRecord, Yu as DelegationArgs, Zl as SettledWorker, Zu as DelegationResumeContext, _d as DelegateUiAuditRoute, _u as FeedbackEvent, ad as hashIdempotencyInput, au as McpServerOptions, bd as DelegationHistoryArgs, bu as eventToSnapshot, cd as DelegateCodeResult, cu as DELEGATE_DESCRIPTION, dd as DelegateResearchArgs, du as DelegateArgs, ed as DelegationRunContext, eu as WorkerWatchOptions, fd as DelegateResearchConfig, fu as DelegateError, gd as DelegateUiAuditResult, gu as validateDelegateArgs, hd as DelegateUiAuditConfig, hu as createDelegateHandler, id as SubmitOutput, iu as McpServer, jd as ResearchOutputShape, jl as AuthorizeDownMessage, ju as settleDetachedCoderTurn, kd as FeedbackRating, kl as AnalystRegistry, ku as coderTaskFromArgs, ld as DelegateFeedbackArgs, lu as DELEGATE_INPUT_SCHEMA, md as DelegateUiAuditArgs, mu as DelegateResult, nd as DelegationTaskQueueOptions, nu as createCoordinationTools, od as DelegateCodeArgs, ou as createInProcessTransport, pd as DelegateResearchResult, pu as DelegateHandlerOptions, qd as DelegationStore, ql as QuestionOption, qu as parseDetachedSessionRef, rd as SubmitInput, sd as DelegateCodeConfig, su as createMcpServer, td as DelegationTaskQueue, ud as DelegateFeedbackResult, uu as DELEGATE_TOOL_NAME, vd as DelegationError, vu as FeedbackStore, wd as DelegationProgress, wu as DelegateRunCtx, xd as DelegationHistoryEntry, xu as CoderDelegate, yd as DelegationFeedbackSnapshot, yu as InMemoryFeedbackStore, zd as DelegationTraceCollector, zl as DownMessageAuthorizationInput, zu as DetachedTurn } from "../index-BOgzou1U.js";
3
- import { dt as mergeTraceEnv, ft as readTraceContextFromEnv, lt as TraceContext, pt as traceContextToEnv, ut as createPropagatingTraceEmitter } from "../types-BCkweg3w.js";
4
- import { $ as WorktreeHandle, At as JsonRpcResponse, B as LOCAL_HARNESSES, G as localHarnessExecutable, H as LocalHarnessResult, I as CodexExecutionEvidence, J as CreateWorktreeOptions, K as parseCodexTokenUsage, L as CodexExecutionPolicy, Mt as McpTransport, Q as RemoveWorktreeOptions, R as CodexTokenUsage, U as RunLocalHarnessOptions, V as LocalHarness, W as harnessSupportsReasoningEffort, X as DiffResult, Y as DiffOptions, Z as GitRunner, et as captureWorktreeDiff, jt as McpToolDescriptor, kt as JsonRpcMessage, nt as removeWorktree, q as runLocalHarness, tt as createWorktree, z as DEFAULT_LOCAL_HARNESS } from "../runtime-DhPCNvuH.js";
1
+ import { E as SandboxClient, h as LoopSandboxPlacement } from "../types-C244Huc9.js";
2
+ import { $d as buildDelegationTraceSpans, $l as DownMessageDeliveryOutcome, $u as DriveTurnCapableBox, Ad as DelegationError, Au as FeedbackStore, Bd as DelegationStatusResult, Bl as AnalystFindingEvent, Bu as UiAuditorDelegate, Cd as DelegateResearchArgs, Cu as DelegateArgs, Dd as DelegateUiAuditConfig, Du as createDelegateHandler, Ed as DelegateUiAuditArgs, Eu as DelegateResult, Fd as DelegationProfile, Fu as CoderReviewer, Gd as UiAuditLensFilter, Gl as ContinuationInstruction, Gu as FleetHandle, Hd as FeedbackRefersTo, Hu as detachedSessionDelegate, Id as DelegationProgress, Iu as DelegateRunCtx, Jd as DELEGATION_TRACE_MAX_BYTES, Jl as CoordinationTools, Ju as createFleetWorkspaceExecutor, Kd as UiAuditorDelegationOutput, Ku as FleetWorkspaceExecutorOptions, Ld as DelegationResultPayload, Lu as DetachedSessionDelegateOptions, Md as DelegationHistoryArgs, Mu as eventToSnapshot, Nd as DelegationHistoryEntry, Nu as CoderDelegate, Od as DelegateUiAuditResult, Ou as validateDelegateArgs, Pd as DelegationHistoryResult, Pu as CoderReview, Qd as DelegationTraceSpan, Ql as DownMessageDeliveryAttempt, Qu as DetachedTurnResumeDriverOptions, Rd as DelegationStatus, Ru as DetachedWinnerSelection, Sd as DelegateFeedbackResult, Su as DELEGATE_TOOL_NAME, Td as DelegateResearchResult, Tu as DelegateHandlerOptions, Ud as ResearchOutputShape, Ul as AuthorizeDownMessage, Uu as settleDetachedCoderTurn, Vd as FeedbackRating, Vl as AnalystRegistry, Vu as coderTaskFromArgs, Wd as ResearchSource, Wl as AuthorizedDownMessage, Wu as DelegationExecutor, Xd as DelegationTraceCaps, Xl as DEFAULT_AWAIT_EVENT_TIMEOUT_MS, Xu as DetachedSessionRefParts, Yd as DELEGATION_TRACE_MAX_SPANS, Yl as CoordinationToolsOptions, Yu as createSiblingSandboxExecutor, Zd as DelegationTraceCollector, Zl as DownMessageAuthorizationInput, Zu as DetachedTurn, _d as hashIdempotencyInput, _u as McpServerOptions, ad as parseDetachedSessionRef, af as DelegationStore, au as QuestionOption, bd as DelegateCodeResult, bu as DELEGATE_DESCRIPTION, cd as DelegationRecord, cf as InMemoryDelegationStore, cu as QuestionUrgency, dd as DelegationResumeTick, du as WorkerSpawnContext, ed as DriveTurnTick, ef as capDelegationTrace, eu as DownMessageEvent, fd as DelegationRunContext, fu as WorkerWatchOptions, gd as SubmitOutput, gu as McpServer, hd as SubmitInput, id as formatDetachedSessionRef, if as DelegationStateCorruptError, iu as QuestionLevel, jd as DelegationFeedbackSnapshot, ju as InMemoryFeedbackStore, kd as DelegateUiAuditRoute, ku as FeedbackEvent, ld as DelegationResumeContext, lu as SettledWorker, md as DelegationTaskQueueOptions, mu as createCoordinationTools, nd as createDetachedTurnResumeDriver, nf as createDelegationTraceCollector, nu as Question, od as runDetachedTurn, of as FileDelegationStore, ou as QuestionPolicy, pd as DelegationTaskQueue, qd as CappedDelegationTrace, qf as CoderOutput, ql as CoordinationEvent, qu as SiblingSandboxExecutorOptions, rd as detachedTurnEvents, rf as DelegationPersistenceError, ru as QuestionDecision, sd as DelegationArgs, sf as FileDelegationStoreOptions, su as QuestionRecord, td as RunDetachedTurnOptions, tf as composeLoopTraceEmitters, tu as MakeWorkerAgent, ud as DelegationResumeDriver, vd as DelegateCodeArgs, vu as createInProcessTransport, wd as DelegateResearchConfig, wu as DelegateError, xd as DelegateFeedbackArgs, xu as DELEGATE_INPUT_SCHEMA, yd as DelegateCodeConfig, yu as createMcpServer, zd as DelegationStatusArgs, zu as SettleDetachedCoderTurnOptions } from "../index-COnuT0h7.js";
3
+ import { dt as mergeTraceEnv, ft as readTraceContextFromEnv, lt as TraceContext, pt as traceContextToEnv, ut as createPropagatingTraceEmitter } from "../types-D4arYjUl.js";
4
+ import { $ as WorktreeHandle, At as JsonRpcResponse, B as LOCAL_HARNESSES, G as localHarnessExecutable, H as LocalHarnessResult, I as CodexExecutionEvidence, J as CreateWorktreeOptions, K as parseCodexTokenUsage, L as CodexExecutionPolicy, Mt as McpTransport, Q as RemoveWorktreeOptions, R as CodexTokenUsage, U as RunLocalHarnessOptions, V as LocalHarness, W as harnessSupportsReasoningEffort, X as DiffResult, Y as DiffOptions, Z as GitRunner, et as captureWorktreeDiff, jt as McpToolDescriptor, kt as JsonRpcMessage, nt as removeWorktree, q as runLocalHarness, tt as createWorktree, z as DEFAULT_LOCAL_HARNESS } from "../runtime-CVNWEw16.js";
5
5
  import { o as UiLens } from "../substrate-BcnuSHXm.js";
6
6
  import { a as KbGateResult, i as FactJudgeVerdict, n as FactCandidate, o as createKbGate, r as FactJudge, t as CreateKbGateOptions } from "../kb-gate-C8z2juK8.js";
7
- import { n as mcpToolsForRuntimeMcpSubset, t as mcpToolsForRuntimeMcp } from "../openai-tools-DU3TZvFY.js";
7
+ import { n as mcpToolsForRuntimeMcpSubset, t as mcpToolsForRuntimeMcp } from "../openai-tools-yoRRzAUW.js";
8
8
  import { AgentProfileMcpServer } from "@tangle-network/agent-interface";
9
9
  //#region src/mcp/codex-diagnostics.d.ts
10
10
  /** Bounded, credential-redacted process context attached when reproducible Codex output fails
package/dist/mcp/index.js CHANGED
@@ -1,14 +1,14 @@
1
- import { f as ValidationError, i as ConfigError } from "../errors-CVIDr7GQ.js";
1
+ import { i as ConfigError, m as ValidationError } from "../errors-CDZ8XsVj.js";
2
2
  import { d as sleep, i as deleteBoxSafe, m as throwIfAborted, p as throwAbort } from "../util-C1bv6yog.js";
3
- import { t as assertExecutableAgentProfile } from "../model-policy-UTTc9Z-A.js";
4
- import { Ct as traceContextToEnv, Gt as createWorktree, Jt as LOCAL_HARNESSES, Kt as removeWorktree, Qt as CodexExecutionDiagnosticError, St as readTraceContextFromEnv, Ut as runWorktreeHarness, Wt as captureWorktreeDiff, Xt as localHarnessExecutable, Yt as harnessSupportsReasoningEffort, Zt as parseCodexTokenUsage, bt as createPropagatingTraceEmitter, ft as runAgentRounds, lt as createSandboxForSpec, qt as DEFAULT_LOCAL_HARNESS, xt as mergeTraceEnv } from "../supervisor-BoC2tFgH.js";
5
- import { T as runCoderChecks, st as selectValidWinner } from "../runtime-CUpB4rEP.js";
6
- import { $ as DELEGATION_TRACE_MAX_BYTES, A as DELEGATION_HISTORY_INPUT_SCHEMA, B as DELEGATE_FEEDBACK_INPUT_SCHEMA, C as createMcpServer, D as createDelegationStatusHandler, Dt as createCoordinationTools, E as DELEGATION_STATUS_TOOL_NAME, F as DELEGATE_UI_AUDIT_INPUT_SCHEMA, G as DELEGATE_INPUT_SCHEMA, H as createDelegateFeedbackHandler, I as DELEGATE_UI_AUDIT_TOOL_NAME, J as validateDelegateArgs, K as DELEGATE_TOOL_NAME, L as createDelegateUiAuditHandler, M as createDelegationHistoryHandler, N as validateDelegationHistoryArgs, O as validateDelegationStatusArgs, P as DELEGATE_UI_AUDIT_DESCRIPTION, Q as hashIdempotencyInput, R as validateDelegateUiAuditArgs, S as createInProcessTransport, T as DELEGATION_STATUS_INPUT_SCHEMA, Tt as DEFAULT_AWAIT_EVENT_TIMEOUT_MS, U as validateDelegateFeedbackArgs, V as DELEGATE_FEEDBACK_TOOL_NAME, W as DELEGATE_DESCRIPTION, Z as DelegationTaskQueue, at as DelegationPersistenceError, ct as InMemoryDelegationStore, et as DELEGATION_TRACE_MAX_SPANS, it as createDelegationTraceCollector, j as DELEGATION_HISTORY_TOOL_NAME, k as DELEGATION_HISTORY_DESCRIPTION, lt as InMemoryFeedbackStore, nt as capDelegationTrace, ot as DelegationStateCorruptError, q as createDelegateHandler, rt as composeLoopTraceEmitters, st as FileDelegationStore, tt as buildDelegationTraceSpans, ut as eventToSnapshot, w as DELEGATION_STATUS_DESCRIPTION, z as DELEGATE_FEEDBACK_DESCRIPTION } from "../supervise-CUJRmx3s.js";
7
- import { t as createStdioToolServer } from "../tool-server-Dh-NcbHr.js";
3
+ import { t as assertExecutableAgentProfile } from "../model-policy-DgRJIJse.js";
4
+ import { Ct as traceContextToEnv, Gt as createWorktree, Jt as LOCAL_HARNESSES, Kt as removeWorktree, Qt as CodexExecutionDiagnosticError, St as readTraceContextFromEnv, Ut as runWorktreeHarness, Wt as captureWorktreeDiff, Xt as localHarnessExecutable, Yt as harnessSupportsReasoningEffort, Zt as parseCodexTokenUsage, bt as createPropagatingTraceEmitter, ft as runAgentRounds, lt as createSandboxForSpec, qt as DEFAULT_LOCAL_HARNESS, xt as mergeTraceEnv } from "../supervisor-BV72aDmP.js";
5
+ import { T as runCoderChecks, dt as selectValidWinner } from "../runtime-tTA2iCZQ.js";
6
+ import { $ as DELEGATION_TRACE_MAX_BYTES, A as DELEGATION_HISTORY_INPUT_SCHEMA, B as DELEGATE_FEEDBACK_INPUT_SCHEMA, C as createMcpServer, D as createDelegationStatusHandler, Dt as createCoordinationTools, E as DELEGATION_STATUS_TOOL_NAME, F as DELEGATE_UI_AUDIT_INPUT_SCHEMA, G as DELEGATE_INPUT_SCHEMA, H as createDelegateFeedbackHandler, I as DELEGATE_UI_AUDIT_TOOL_NAME, J as validateDelegateArgs, K as DELEGATE_TOOL_NAME, L as createDelegateUiAuditHandler, M as createDelegationHistoryHandler, N as validateDelegationHistoryArgs, O as validateDelegationStatusArgs, P as DELEGATE_UI_AUDIT_DESCRIPTION, Q as hashIdempotencyInput, R as validateDelegateUiAuditArgs, S as createInProcessTransport, T as DELEGATION_STATUS_INPUT_SCHEMA, Tt as DEFAULT_AWAIT_EVENT_TIMEOUT_MS, U as validateDelegateFeedbackArgs, V as DELEGATE_FEEDBACK_TOOL_NAME, W as DELEGATE_DESCRIPTION, Z as DelegationTaskQueue, at as DelegationPersistenceError, ct as InMemoryDelegationStore, et as DELEGATION_TRACE_MAX_SPANS, it as createDelegationTraceCollector, j as DELEGATION_HISTORY_TOOL_NAME, k as DELEGATION_HISTORY_DESCRIPTION, lt as InMemoryFeedbackStore, nt as capDelegationTrace, ot as DelegationStateCorruptError, q as createDelegateHandler, rt as composeLoopTraceEmitters, st as FileDelegationStore, tt as buildDelegationTraceSpans, ut as eventToSnapshot, w as DELEGATION_STATUS_DESCRIPTION, z as DELEGATE_FEEDBACK_DESCRIPTION } from "../supervise-Cx1QY_hj.js";
7
+ import { t as createStdioToolServer } from "../tool-server-DEmLr9YY.js";
8
8
  import { t as createKbGate } from "../kb-gate-DpaSwXVx.js";
9
- import { n as mcpToolsForRuntimeMcpSubset, t as mcpToolsForRuntimeMcp } from "../openai-tools-BKJqaQ1b.js";
9
+ import { n as mcpToolsForRuntimeMcpSubset, t as mcpToolsForRuntimeMcp } from "../openai-tools-DIKr72_l.js";
10
10
  import { t as coderTaskToPrompt } from "../coder-yhVWbdWc.js";
11
- import { a as createMemoryToolServer, c as resolveMemoryFromEnv, i as MEMORY_NAME_ENV, n as MEMORY_ITEMS_ENV, o as parseMemoryItems, r as MEMORY_LOG_ENV, s as readMemoryItemsFile, t as MEMORY_FILE_ENV } from "../memory-server-Cdpy7Uu8.js";
11
+ import { a as createMemoryToolServer, c as resolveMemoryFromEnv, i as MEMORY_NAME_ENV, n as MEMORY_ITEMS_ENV, o as parseMemoryItems, r as MEMORY_LOG_ENV, s as readMemoryItemsFile, t as MEMORY_FILE_ENV } from "../memory-server-DsKOhzGf.js";
12
12
  import { agentProfileSchema } from "@tangle-network/agent-interface";
13
13
  import { randomUUID } from "node:crypto";
14
14
  //#region src/mcp/executor.ts
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { a as createMemoryToolServer, c as resolveMemoryFromEnv } from "../memory-server-Cdpy7Uu8.js";
2
+ import { a as createMemoryToolServer, c as resolveMemoryFromEnv } from "../memory-server-DsKOhzGf.js";
3
3
  //#region src/mcp/memory-bin.ts
4
4
  /**
5
5
  * `agent-runtime-memory-mcp` — stdio memory MCP server entry point.
@@ -1,5 +1,5 @@
1
- import { f as ValidationError } from "./errors-CVIDr7GQ.js";
2
- import { t as createStdioToolServer } from "./tool-server-Dh-NcbHr.js";
1
+ import { m as ValidationError } from "./errors-CDZ8XsVj.js";
2
+ import { t as createStdioToolServer } from "./tool-server-DEmLr9YY.js";
3
3
  import { dirname } from "node:path";
4
4
  import { appendFileSync, mkdirSync, readFileSync } from "node:fs";
5
5
  //#region src/mcp/memory-server.ts
@@ -231,4 +231,4 @@ function scoreItem(queryTokens, item) {
231
231
  //#endregion
232
232
  export { createMemoryToolServer as a, resolveMemoryFromEnv as c, MEMORY_NAME_ENV as i, MEMORY_ITEMS_ENV as n, parseMemoryItems as o, MEMORY_LOG_ENV as r, readMemoryItemsFile as s, MEMORY_FILE_ENV as t };
233
233
 
234
- //# sourceMappingURL=memory-server-Cdpy7Uu8.js.map
234
+ //# sourceMappingURL=memory-server-DsKOhzGf.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"memory-server-Cdpy7Uu8.js","names":[],"sources":["../src/mcp/memory-server.ts"],"sourcesContent":["/**\n * Memory MCP server — the LIVE serving half of the `memory` profile surface\n * (Phase 5). A curated memory (lessons distilled from prior runs) is only\n * real if the DRIVEN agent can query it mid-task; this module serves a flat\n * store of `MemoryItem` rows as `memory_search` / `memory_get` tools over the\n * ONE in-repo stdio JSON-RPC core (`createStdioToolServer`), so the exact\n * wire protocol the same-host client (`connectStdioMcp` /\n * `materializeLocalMcp`, runtime/stdio-mcp-client.ts) speaks is guaranteed by\n * construction — serve and consume cannot drift.\n *\n * Retrieval is DETERMINISTIC lexical overlap (no vectors, no LLM): a lift\n * measured with this memory mounted is attributable to the lessons\n * themselves, never to retrieval-model noise. Every\n * `memory_search` can append one JSONL row to a retrieval log (`logPath`) —\n * the per-query record an off-policy retrieval estimator (agent-knowledge's\n * `RetrievalHoldout`) consumes. agent-knowledge is NOT a dependency of this\n * repo, so the log file is the flagged cross-package seam, not an import.\n *\n * Fail-loud discipline (mirrors `materializeLocalMcp`): an EMPTY memory is\n * never served — a profile without memory simply omits the artifact, and\n * silently serving zero rows would fake the with/without ablation.\n *\n * @experimental\n */\n\nimport { appendFileSync, mkdirSync, readFileSync } from 'node:fs'\nimport { dirname } from 'node:path'\nimport type { AgentProfileMcpServer } from '@tangle-network/agent-interface'\nimport { ValidationError } from '../errors'\nimport { createStdioToolServer, type McpToolDescriptor, type StdioToolServer } from './tool-server'\n\n/** One row of agent memory: a crisp lesson/fact with provenance. */\nexport interface MemoryItem {\n /** Stable id (content-hash by convention; see `memoryArtifactFromLessons`). */\n id: string\n /** The lesson itself — one imperative or observation the agent should recall. */\n text: string\n /** Optional retrieval tags, matched by `memory_search` alongside the text. */\n tags?: string[]\n /** Provenance: the finding / trace / curation pass this row came from. */\n source?: string\n}\n\n/**\n * The `memory` artifact payload — HOW a profile's memory is stored and served:\n *\n * - `store: 'file'` — served by the in-repo memory bin\n * (`agent-runtime-memory-mcp`, src/mcp/memory-bin.ts): rows load from\n * `path` (a JSON array or JSONL file of `MemoryItem`) and/or the inline\n * `items` seed (inline wins on id collision). At least one of\n * `path`/`items` is required.\n * - `store: 'mcp'` — an EXTERNAL, already-runnable MCP server that exposes\n * the memory tools itself; `server` is required and mounts verbatim.\n *\n * `logPath` makes the served memory append one JSONL row per `memory_search`\n * — the retrieval log a holdout estimator reads (see module doc).\n */\nexport interface AgentMemorySpec {\n store: 'file' | 'mcp'\n /** `store:'file'` — host path to the durable row store (JSON array or JSONL). */\n path?: string\n /** Inline seed rows, served alongside (and winning over) `path` rows. */\n items?: MemoryItem[]\n /** `store:'mcp'` — the external server that already serves memory tools. */\n server?: AgentProfileMcpServer\n /** JSONL retrieval log: one row per `memory_search` (ts, query, k, returned). */\n logPath?: string\n}\n\n/** Env var naming the durable row store file the memory bin loads (the\n * `memoryMcpServer` ↔ memory-bin contract). */\nexport const MEMORY_FILE_ENV = 'AGENT_MEMORY_FILE'\n/** Env var carrying inline JSON `MemoryItem` rows (win over file rows on id). */\nexport const MEMORY_ITEMS_ENV = 'AGENT_MEMORY_ITEMS'\n/** Env var naming the JSONL retrieval log (one row per `memory_search`). */\nexport const MEMORY_LOG_ENV = 'AGENT_MEMORY_LOG'\n/** Env var overriding the served display name (default 'agent-memory'). */\nexport const MEMORY_NAME_ENV = 'AGENT_MEMORY_NAME'\n\nexport interface CreateMemoryToolServerOptions {\n /** The rows to serve. MUST be non-empty (an empty memory is never served). */\n items: readonly MemoryItem[]\n /** Server display name surfaced via `initialize`. Default 'agent-memory'. */\n serverName?: string\n /** Server version surfaced via `initialize`. Default '0'. */\n serverVersion?: string\n /** Default result count for `memory_search`. Default 5. */\n defaultK?: number\n /** Append one JSONL row per `memory_search` (the retrieval-holdout seam). */\n logPath?: string\n}\n\n/**\n * Build the memory MCP server: `memory_search` (lexical top-k over the rows)\n * and `memory_get` (one row by id) on the generic stdio JSON-RPC core.\n */\nexport function createMemoryToolServer(opts: CreateMemoryToolServerOptions): StdioToolServer {\n if (opts.items.length === 0) {\n throw new ValidationError(\n 'createMemoryToolServer: refusing to serve an EMPTY memory — a profile without memory omits the artifact; serving zero rows would fake the with/without ablation',\n )\n }\n const byId = new Map<string, MemoryItem>()\n for (const item of opts.items) {\n if (byId.has(item.id)) {\n throw new ValidationError(`createMemoryToolServer: duplicate memory item id '${item.id}'`)\n }\n byId.set(item.id, item)\n }\n const items = [...byId.values()]\n const defaultK = opts.defaultK ?? 5\n const logPath = opts.logPath\n if (logPath) mkdirSync(dirname(logPath), { recursive: true })\n\n const search: McpToolDescriptor = {\n name: 'memory_search',\n description:\n 'Search the agent memory of lessons learned from prior runs. Give what you are about to do or the problem you face; returns the top-k lessons ranked by relevance. Consult it BEFORE repeating work a prior run already learned from.',\n inputSchema: {\n type: 'object',\n properties: {\n query: {\n type: 'string',\n description: 'The task/problem at hand — matched against lesson text and tags.',\n },\n k: { type: 'number', description: `Max results (default ${defaultK}).` },\n tags: {\n type: 'array',\n items: { type: 'string' },\n description: 'Only return items carrying at least one of these tags.',\n },\n },\n required: ['query'],\n },\n handler: async (raw) => {\n const args = (raw ?? {}) as { query?: unknown; k?: unknown; tags?: unknown }\n if (typeof args.query !== 'string' || args.query.trim().length === 0) {\n throw new TypeError('memory_search: query must be a non-empty string')\n }\n const k = args.k === undefined ? defaultK : Math.floor(Number(args.k))\n if (!Number.isFinite(k) || k < 1) {\n throw new TypeError('memory_search: k must be a positive integer')\n }\n let tagFilter: string[] | undefined\n if (args.tags !== undefined) {\n if (!Array.isArray(args.tags) || args.tags.some((t) => typeof t !== 'string')) {\n throw new TypeError('memory_search: tags must be an array of strings')\n }\n tagFilter = args.tags as string[]\n }\n const queryTokens = tokenize(args.query)\n const pool = tagFilter\n ? items.filter((i) => (i.tags ?? []).some((t) => tagFilter.includes(t)))\n : items\n const results = pool\n .map((item) => ({ item, score: scoreItem(queryTokens, item) }))\n .filter((r) => r.score > 0)\n // Highest score first; stable on ties (curation order is the tiebreak).\n .sort((a, b) => b.score - a.score)\n .slice(0, k)\n .map(({ item, score }) => ({\n id: item.id,\n text: item.text,\n score: Number(score.toFixed(4)),\n ...(item.tags ? { tags: item.tags } : {}),\n ...(item.source ? { source: item.source } : {}),\n }))\n if (logPath) {\n // The retrieval log: what was asked, what came back, at what rank —\n // exactly the per-query record an off-policy estimator needs.\n appendFileSync(\n logPath,\n `${JSON.stringify({\n ts: new Date().toISOString(),\n query: args.query,\n k,\n returned: results.map((r) => ({ id: r.id, score: r.score })),\n })}\\n`,\n )\n }\n return { query: args.query, results }\n },\n }\n\n const get: McpToolDescriptor = {\n name: 'memory_get',\n description: 'Fetch one memory item verbatim by its id (ids come from memory_search results).',\n inputSchema: {\n type: 'object',\n properties: { id: { type: 'string', description: 'The memory item id.' } },\n required: ['id'],\n },\n handler: async (raw) => {\n const args = (raw ?? {}) as { id?: unknown }\n if (typeof args.id !== 'string' || args.id.trim().length === 0) {\n throw new TypeError('memory_get: id must be a non-empty string')\n }\n const item = byId.get(args.id)\n if (!item) throw new Error(`memory_get: no memory item with id '${args.id}'`)\n return item\n },\n }\n\n return createStdioToolServer({\n serverName: opts.serverName ?? 'agent-memory',\n serverVersion: opts.serverVersion ?? '0',\n tools: [search, get],\n })\n}\n\n/** Coerce an untrusted JSON array into validated `MemoryItem` rows. */\nexport function parseMemoryItems(value: unknown, source: string): MemoryItem[] {\n if (!Array.isArray(value)) {\n throw new ValidationError(`${source}: expected a JSON array of memory items`)\n }\n return value.map((row, i) => coerceMemoryItem(row, `${source}[${i}]`))\n}\n\n/** Read a memory store file: a JSON array, or JSONL (one `MemoryItem` per line). */\nexport function readMemoryItemsFile(path: string): MemoryItem[] {\n let raw: string\n try {\n raw = readFileSync(path, 'utf8')\n } catch (err) {\n throw new ValidationError(\n `readMemoryItemsFile: cannot read '${path}': ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n const trimmed = raw.trim()\n if (trimmed.length === 0) return []\n if (trimmed.startsWith('[')) {\n let parsed: unknown\n try {\n parsed = JSON.parse(trimmed)\n } catch (err) {\n throw new ValidationError(\n `readMemoryItemsFile: '${path}' is not valid JSON: ${(err as Error).message}`,\n )\n }\n return parseMemoryItems(parsed, path)\n }\n return trimmed\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line.length > 0)\n .map((line, i) => {\n let parsed: unknown\n try {\n parsed = JSON.parse(line)\n } catch (err) {\n throw new ValidationError(\n `readMemoryItemsFile: '${path}' line ${i + 1} is not valid JSON: ${(err as Error).message}`,\n )\n }\n return coerceMemoryItem(parsed, `${path}:${i + 1}`)\n })\n}\n\n/** What the memory bin resolved from its environment. */\nexport interface ResolvedMemoryEnv {\n items: MemoryItem[]\n serverName?: string\n logPath?: string\n}\n\n/**\n * Resolve the bin's memory from `AGENT_MEMORY_FILE` (durable store) and/or\n * `AGENT_MEMORY_ITEMS` (inline JSON rows; wins on id collision). Zero rows is\n * a boot FAILURE, matching the fail-closed materialization discipline.\n */\nexport function resolveMemoryFromEnv(env: Record<string, string | undefined>): ResolvedMemoryEnv {\n const filePath = env[MEMORY_FILE_ENV]\n const inlineRaw = env[MEMORY_ITEMS_ENV]\n const fromFile = filePath ? readMemoryItemsFile(filePath) : []\n let inline: MemoryItem[] = []\n if (inlineRaw) {\n let parsed: unknown\n try {\n parsed = JSON.parse(inlineRaw)\n } catch (err) {\n throw new ValidationError(\n `${MEMORY_ITEMS_ENV} is not valid JSON: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n inline = parseMemoryItems(parsed, MEMORY_ITEMS_ENV)\n }\n const byId = new Map<string, MemoryItem>()\n for (const item of fromFile) byId.set(item.id, item)\n for (const item of inline) byId.set(item.id, item)\n if (byId.size === 0) {\n throw new ValidationError(\n `memory bin: no memory items — set ${MEMORY_FILE_ENV} and/or ${MEMORY_ITEMS_ENV}; an EMPTY memory must never be served (a profile without memory omits the artifact)`,\n )\n }\n const serverName = env[MEMORY_NAME_ENV]\n const logPath = env[MEMORY_LOG_ENV]\n return {\n items: [...byId.values()],\n ...(serverName ? { serverName } : {}),\n ...(logPath ? { logPath } : {}),\n }\n}\n\nfunction coerceMemoryItem(row: unknown, at: string): MemoryItem {\n if (!row || typeof row !== 'object' || Array.isArray(row)) {\n throw new ValidationError(`${at}: memory item must be an object`)\n }\n const r = row as Record<string, unknown>\n if (typeof r.id !== 'string' || r.id.trim().length === 0) {\n throw new ValidationError(`${at}: 'id' must be a non-empty string`)\n }\n if (typeof r.text !== 'string' || r.text.trim().length === 0) {\n throw new ValidationError(`${at}: 'text' must be a non-empty string`)\n }\n let tags: string[] | undefined\n if (r.tags !== undefined) {\n if (!Array.isArray(r.tags) || r.tags.some((t) => typeof t !== 'string')) {\n throw new ValidationError(`${at}: 'tags' must be an array of strings`)\n }\n tags = r.tags as string[]\n }\n if (r.source !== undefined && typeof r.source !== 'string') {\n throw new ValidationError(`${at}: 'source' must be a string`)\n }\n return {\n id: r.id,\n text: r.text,\n ...(tags ? { tags } : {}),\n ...(typeof r.source === 'string' ? { source: r.source } : {}),\n }\n}\n\n/** Unique lowercase alphanumeric tokens of length >= 2. */\nfunction tokenize(text: string): string[] {\n return [\n ...new Set(\n text\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter((t) => t.length >= 2),\n ),\n ]\n}\n\n/** Fraction of query tokens present in the item's text + tags (0..1). */\nfunction scoreItem(queryTokens: readonly string[], item: MemoryItem): number {\n if (queryTokens.length === 0) return 0\n const hay = new Set(tokenize(`${item.text} ${(item.tags ?? []).join(' ')}`))\n let hit = 0\n for (const t of queryTokens) if (hay.has(t)) hit += 1\n return hit / queryTokens.length\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuE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ACrD,MAAM,IAAI,gBAAgB,GAAG,GAAG,kCAAkC;CAEpE,IAAI,OAAO,EAAE,SAAS,YAAY,EAAE,KAAK,KAAK,CAAC,CAAC,WAAW,GACzD,MAAM,IAAI,gBAAgB,GAAG,GAAG,oCAAoC;CAEtE,IAAI;CACJ,IAAI,EAAE,SAAS,KAAA,GAAW;EACxB,IAAI,CAAC,MAAM,QAAQ,EAAE,IAAI,KAAK,EAAE,KAAK,MAAM,MAAM,OAAO,MAAM,QAAQ,GACpE,MAAM,IAAI,gBAAgB,GAAG,GAAG,qCAAqC;EAEvE,OAAO,EAAE;CACX;CACA,IAAI,EAAE,WAAW,KAAA,KAAa,OAAO,EAAE,WAAW,UAChD,MAAM,IAAI,gBAAgB,GAAG,GAAG,4BAA4B;CAE9D,OAAO;EACL,IAAI,EAAE;EACN,MAAM,EAAE;EACR,GAAI,OAAO,EAAE,KAAK,IAAI,CAAC;EACvB,GAAI,OAAO,EAAE,WAAW,WAAW,EAAE,QAAQ,EAAE,OAAO,IAAI,CAAC;CAC7D;AACF;;AAGA,SAAS,SAAS,MAAwB;CACxC,OAAO,CACL,GAAG,IAAI,IACL,KACG,YAAY,CAAC,CACb,MAAM,YAAY,CAAC,CACnB,QAAQ,MAAM,EAAE,UAAU,CAAC,CAChC,CACF;AACF;;AAGA,SAAS,UAAU,aAAgC,MAA0B;CAC3E,IAAI,YAAY,WAAW,GAAG,OAAO;CACrC,MAAM,MAAM,IAAI,IAAI,SAAS,GAAG,KAAK,KAAK,IAAI,KAAK,QAAQ,CAAC,EAAA,CAAG,KAAK,GAAG,GAAG,CAAC;CAC3E,IAAI,MAAM;CACV,KAAK,MAAM,KAAK,aAAa,IAAI,IAAI,IAAI,CAAC,GAAG,OAAO;CACpD,OAAO,MAAM,YAAY;AAC3B"}
1
+ {"version":3,"file":"memory-server-DsKOhzGf.js","names":[],"sources":["../src/mcp/memory-server.ts"],"sourcesContent":["/**\n * Memory MCP server — the LIVE serving half of the `memory` profile surface\n * (Phase 5). A curated memory (lessons distilled from prior runs) is only\n * real if the DRIVEN agent can query it mid-task; this module serves a flat\n * store of `MemoryItem` rows as `memory_search` / `memory_get` tools over the\n * ONE in-repo stdio JSON-RPC core (`createStdioToolServer`), so the exact\n * wire protocol the same-host client (`connectStdioMcp` /\n * `materializeLocalMcp`, runtime/stdio-mcp-client.ts) speaks is guaranteed by\n * construction — serve and consume cannot drift.\n *\n * Retrieval is DETERMINISTIC lexical overlap (no vectors, no LLM): a lift\n * measured with this memory mounted is attributable to the lessons\n * themselves, never to retrieval-model noise. Every\n * `memory_search` can append one JSONL row to a retrieval log (`logPath`) —\n * the per-query record an off-policy retrieval estimator (agent-knowledge's\n * `RetrievalHoldout`) consumes. agent-knowledge is NOT a dependency of this\n * repo, so the log file is the flagged cross-package seam, not an import.\n *\n * Fail-loud discipline (mirrors `materializeLocalMcp`): an EMPTY memory is\n * never served — a profile without memory simply omits the artifact, and\n * silently serving zero rows would fake the with/without ablation.\n *\n * @experimental\n */\n\nimport { appendFileSync, mkdirSync, readFileSync } from 'node:fs'\nimport { dirname } from 'node:path'\nimport type { AgentProfileMcpServer } from '@tangle-network/agent-interface'\nimport { ValidationError } from '../errors'\nimport { createStdioToolServer, type McpToolDescriptor, type StdioToolServer } from './tool-server'\n\n/** One row of agent memory: a crisp lesson/fact with provenance. */\nexport interface MemoryItem {\n /** Stable id (content-hash by convention; see `memoryArtifactFromLessons`). */\n id: string\n /** The lesson itself — one imperative or observation the agent should recall. */\n text: string\n /** Optional retrieval tags, matched by `memory_search` alongside the text. */\n tags?: string[]\n /** Provenance: the finding / trace / curation pass this row came from. */\n source?: string\n}\n\n/**\n * The `memory` artifact payload — HOW a profile's memory is stored and served:\n *\n * - `store: 'file'` — served by the in-repo memory bin\n * (`agent-runtime-memory-mcp`, src/mcp/memory-bin.ts): rows load from\n * `path` (a JSON array or JSONL file of `MemoryItem`) and/or the inline\n * `items` seed (inline wins on id collision). At least one of\n * `path`/`items` is required.\n * - `store: 'mcp'` — an EXTERNAL, already-runnable MCP server that exposes\n * the memory tools itself; `server` is required and mounts verbatim.\n *\n * `logPath` makes the served memory append one JSONL row per `memory_search`\n * — the retrieval log a holdout estimator reads (see module doc).\n */\nexport interface AgentMemorySpec {\n store: 'file' | 'mcp'\n /** `store:'file'` — host path to the durable row store (JSON array or JSONL). */\n path?: string\n /** Inline seed rows, served alongside (and winning over) `path` rows. */\n items?: MemoryItem[]\n /** `store:'mcp'` — the external server that already serves memory tools. */\n server?: AgentProfileMcpServer\n /** JSONL retrieval log: one row per `memory_search` (ts, query, k, returned). */\n logPath?: string\n}\n\n/** Env var naming the durable row store file the memory bin loads (the\n * `memoryMcpServer` ↔ memory-bin contract). */\nexport const MEMORY_FILE_ENV = 'AGENT_MEMORY_FILE'\n/** Env var carrying inline JSON `MemoryItem` rows (win over file rows on id). */\nexport const MEMORY_ITEMS_ENV = 'AGENT_MEMORY_ITEMS'\n/** Env var naming the JSONL retrieval log (one row per `memory_search`). */\nexport const MEMORY_LOG_ENV = 'AGENT_MEMORY_LOG'\n/** Env var overriding the served display name (default 'agent-memory'). */\nexport const MEMORY_NAME_ENV = 'AGENT_MEMORY_NAME'\n\nexport interface CreateMemoryToolServerOptions {\n /** The rows to serve. MUST be non-empty (an empty memory is never served). */\n items: readonly MemoryItem[]\n /** Server display name surfaced via `initialize`. Default 'agent-memory'. */\n serverName?: string\n /** Server version surfaced via `initialize`. Default '0'. */\n serverVersion?: string\n /** Default result count for `memory_search`. Default 5. */\n defaultK?: number\n /** Append one JSONL row per `memory_search` (the retrieval-holdout seam). */\n logPath?: string\n}\n\n/**\n * Build the memory MCP server: `memory_search` (lexical top-k over the rows)\n * and `memory_get` (one row by id) on the generic stdio JSON-RPC core.\n */\nexport function createMemoryToolServer(opts: CreateMemoryToolServerOptions): StdioToolServer {\n if (opts.items.length === 0) {\n throw new ValidationError(\n 'createMemoryToolServer: refusing to serve an EMPTY memory — a profile without memory omits the artifact; serving zero rows would fake the with/without ablation',\n )\n }\n const byId = new Map<string, MemoryItem>()\n for (const item of opts.items) {\n if (byId.has(item.id)) {\n throw new ValidationError(`createMemoryToolServer: duplicate memory item id '${item.id}'`)\n }\n byId.set(item.id, item)\n }\n const items = [...byId.values()]\n const defaultK = opts.defaultK ?? 5\n const logPath = opts.logPath\n if (logPath) mkdirSync(dirname(logPath), { recursive: true })\n\n const search: McpToolDescriptor = {\n name: 'memory_search',\n description:\n 'Search the agent memory of lessons learned from prior runs. Give what you are about to do or the problem you face; returns the top-k lessons ranked by relevance. Consult it BEFORE repeating work a prior run already learned from.',\n inputSchema: {\n type: 'object',\n properties: {\n query: {\n type: 'string',\n description: 'The task/problem at hand — matched against lesson text and tags.',\n },\n k: { type: 'number', description: `Max results (default ${defaultK}).` },\n tags: {\n type: 'array',\n items: { type: 'string' },\n description: 'Only return items carrying at least one of these tags.',\n },\n },\n required: ['query'],\n },\n handler: async (raw) => {\n const args = (raw ?? {}) as { query?: unknown; k?: unknown; tags?: unknown }\n if (typeof args.query !== 'string' || args.query.trim().length === 0) {\n throw new TypeError('memory_search: query must be a non-empty string')\n }\n const k = args.k === undefined ? defaultK : Math.floor(Number(args.k))\n if (!Number.isFinite(k) || k < 1) {\n throw new TypeError('memory_search: k must be a positive integer')\n }\n let tagFilter: string[] | undefined\n if (args.tags !== undefined) {\n if (!Array.isArray(args.tags) || args.tags.some((t) => typeof t !== 'string')) {\n throw new TypeError('memory_search: tags must be an array of strings')\n }\n tagFilter = args.tags as string[]\n }\n const queryTokens = tokenize(args.query)\n const pool = tagFilter\n ? items.filter((i) => (i.tags ?? []).some((t) => tagFilter.includes(t)))\n : items\n const results = pool\n .map((item) => ({ item, score: scoreItem(queryTokens, item) }))\n .filter((r) => r.score > 0)\n // Highest score first; stable on ties (curation order is the tiebreak).\n .sort((a, b) => b.score - a.score)\n .slice(0, k)\n .map(({ item, score }) => ({\n id: item.id,\n text: item.text,\n score: Number(score.toFixed(4)),\n ...(item.tags ? { tags: item.tags } : {}),\n ...(item.source ? { source: item.source } : {}),\n }))\n if (logPath) {\n // The retrieval log: what was asked, what came back, at what rank —\n // exactly the per-query record an off-policy estimator needs.\n appendFileSync(\n logPath,\n `${JSON.stringify({\n ts: new Date().toISOString(),\n query: args.query,\n k,\n returned: results.map((r) => ({ id: r.id, score: r.score })),\n })}\\n`,\n )\n }\n return { query: args.query, results }\n },\n }\n\n const get: McpToolDescriptor = {\n name: 'memory_get',\n description: 'Fetch one memory item verbatim by its id (ids come from memory_search results).',\n inputSchema: {\n type: 'object',\n properties: { id: { type: 'string', description: 'The memory item id.' } },\n required: ['id'],\n },\n handler: async (raw) => {\n const args = (raw ?? {}) as { id?: unknown }\n if (typeof args.id !== 'string' || args.id.trim().length === 0) {\n throw new TypeError('memory_get: id must be a non-empty string')\n }\n const item = byId.get(args.id)\n if (!item) throw new Error(`memory_get: no memory item with id '${args.id}'`)\n return item\n },\n }\n\n return createStdioToolServer({\n serverName: opts.serverName ?? 'agent-memory',\n serverVersion: opts.serverVersion ?? '0',\n tools: [search, get],\n })\n}\n\n/** Coerce an untrusted JSON array into validated `MemoryItem` rows. */\nexport function parseMemoryItems(value: unknown, source: string): MemoryItem[] {\n if (!Array.isArray(value)) {\n throw new ValidationError(`${source}: expected a JSON array of memory items`)\n }\n return value.map((row, i) => coerceMemoryItem(row, `${source}[${i}]`))\n}\n\n/** Read a memory store file: a JSON array, or JSONL (one `MemoryItem` per line). */\nexport function readMemoryItemsFile(path: string): MemoryItem[] {\n let raw: string\n try {\n raw = readFileSync(path, 'utf8')\n } catch (err) {\n throw new ValidationError(\n `readMemoryItemsFile: cannot read '${path}': ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n const trimmed = raw.trim()\n if (trimmed.length === 0) return []\n if (trimmed.startsWith('[')) {\n let parsed: unknown\n try {\n parsed = JSON.parse(trimmed)\n } catch (err) {\n throw new ValidationError(\n `readMemoryItemsFile: '${path}' is not valid JSON: ${(err as Error).message}`,\n )\n }\n return parseMemoryItems(parsed, path)\n }\n return trimmed\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line.length > 0)\n .map((line, i) => {\n let parsed: unknown\n try {\n parsed = JSON.parse(line)\n } catch (err) {\n throw new ValidationError(\n `readMemoryItemsFile: '${path}' line ${i + 1} is not valid JSON: ${(err as Error).message}`,\n )\n }\n return coerceMemoryItem(parsed, `${path}:${i + 1}`)\n })\n}\n\n/** What the memory bin resolved from its environment. */\nexport interface ResolvedMemoryEnv {\n items: MemoryItem[]\n serverName?: string\n logPath?: string\n}\n\n/**\n * Resolve the bin's memory from `AGENT_MEMORY_FILE` (durable store) and/or\n * `AGENT_MEMORY_ITEMS` (inline JSON rows; wins on id collision). Zero rows is\n * a boot FAILURE, matching the fail-closed materialization discipline.\n */\nexport function resolveMemoryFromEnv(env: Record<string, string | undefined>): ResolvedMemoryEnv {\n const filePath = env[MEMORY_FILE_ENV]\n const inlineRaw = env[MEMORY_ITEMS_ENV]\n const fromFile = filePath ? readMemoryItemsFile(filePath) : []\n let inline: MemoryItem[] = []\n if (inlineRaw) {\n let parsed: unknown\n try {\n parsed = JSON.parse(inlineRaw)\n } catch (err) {\n throw new ValidationError(\n `${MEMORY_ITEMS_ENV} is not valid JSON: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n inline = parseMemoryItems(parsed, MEMORY_ITEMS_ENV)\n }\n const byId = new Map<string, MemoryItem>()\n for (const item of fromFile) byId.set(item.id, item)\n for (const item of inline) byId.set(item.id, item)\n if (byId.size === 0) {\n throw new ValidationError(\n `memory bin: no memory items — set ${MEMORY_FILE_ENV} and/or ${MEMORY_ITEMS_ENV}; an EMPTY memory must never be served (a profile without memory omits the artifact)`,\n )\n }\n const serverName = env[MEMORY_NAME_ENV]\n const logPath = env[MEMORY_LOG_ENV]\n return {\n items: [...byId.values()],\n ...(serverName ? { serverName } : {}),\n ...(logPath ? { logPath } : {}),\n }\n}\n\nfunction coerceMemoryItem(row: unknown, at: string): MemoryItem {\n if (!row || typeof row !== 'object' || Array.isArray(row)) {\n throw new ValidationError(`${at}: memory item must be an object`)\n }\n const r = row as Record<string, unknown>\n if (typeof r.id !== 'string' || r.id.trim().length === 0) {\n throw new ValidationError(`${at}: 'id' must be a non-empty string`)\n }\n if (typeof r.text !== 'string' || r.text.trim().length === 0) {\n throw new ValidationError(`${at}: 'text' must be a non-empty string`)\n }\n let tags: string[] | undefined\n if (r.tags !== undefined) {\n if (!Array.isArray(r.tags) || r.tags.some((t) => typeof t !== 'string')) {\n throw new ValidationError(`${at}: 'tags' must be an array of strings`)\n }\n tags = r.tags as string[]\n }\n if (r.source !== undefined && typeof r.source !== 'string') {\n throw new ValidationError(`${at}: 'source' must be a string`)\n }\n return {\n id: r.id,\n text: r.text,\n ...(tags ? { tags } : {}),\n ...(typeof r.source === 'string' ? { source: r.source } : {}),\n }\n}\n\n/** Unique lowercase alphanumeric tokens of length >= 2. */\nfunction tokenize(text: string): string[] {\n return [\n ...new Set(\n text\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter((t) => t.length >= 2),\n ),\n ]\n}\n\n/** Fraction of query tokens present in the item's text + tags (0..1). */\nfunction scoreItem(queryTokens: readonly string[], item: MemoryItem): number {\n if (queryTokens.length === 0) return 0\n const hay = new Set(tokenize(`${item.text} ${(item.tags ?? []).join(' ')}`))\n let hit = 0\n for (const t of queryTokens) if (hay.has(t)) hit += 1\n return hit / queryTokens.length\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuEA,MAAa,kBAAkB;;AAE/B,MAAa,mBAAmB;;AAEhC,MAAa,iBAAiB;;AAE9B,MAAa,kBAAkB;;;;;AAmB/B,SAAgB,uBAAuB,MAAsD;CAC3F,IAAI,KAAK,MAAM,WAAW,GACxB,MAAM,IAAI,gBACR,iKACF;CAEF,MAAM,uBAAO,IAAI,IAAwB;CACzC,KAAK,MAAM,QAAQ,KAAK,OAAO;EAC7B,IAAI,KAAK,IAAI,KAAK,EAAE,GAClB,MAAM,IAAI,gBAAgB,qDAAqD,KAAK,GAAG,EA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,GAAG,qCAAqC;EAEvE,OAAO,EAAE;CACX;CACA,IAAI,EAAE,WAAW,KAAA,KAAa,OAAO,EAAE,WAAW,UAChD,MAAM,IAAI,gBAAgB,GAAG,GAAG,4BAA4B;CAE9D,OAAO;EACL,IAAI,EAAE;EACN,MAAM,EAAE;EACR,GAAI,OAAO,EAAE,KAAK,IAAI,CAAC;EACvB,GAAI,OAAO,EAAE,WAAW,WAAW,EAAE,QAAQ,EAAE,OAAO,IAAI,CAAC;CAC7D;AACF;;AAGA,SAAS,SAAS,MAAwB;CACxC,OAAO,CACL,GAAG,IAAI,IACL,KACG,YAAY,CAAC,CACb,MAAM,YAAY,CAAC,CACnB,QAAQ,MAAM,EAAE,UAAU,CAAC,CAChC,CACF;AACF;;AAGA,SAAS,UAAU,aAAgC,MAA0B;CAC3E,IAAI,YAAY,WAAW,GAAG,OAAO;CACrC,MAAM,MAAM,IAAI,IAAI,SAAS,GAAG,KAAK,KAAK,IAAI,KAAK,QAAQ,CAAC,EAAA,CAAG,KAAK,GAAG,GAAG,CAAC;CAC3E,IAAI,MAAM;CACV,KAAK,MAAM,KAAK,aAAa,IAAI,IAAI,IAAI,CAAC,GAAG,OAAO;CACpD,OAAO,MAAM,YAAY;AAC3B"}
@@ -1,4 +1,4 @@
1
- import { f as ValidationError, i as ConfigError } from "./errors-CVIDr7GQ.js";
1
+ import { i as ConfigError, m as ValidationError } from "./errors-CDZ8XsVj.js";
2
2
  import { HARNESS_NATIVE_MODEL } from "@tangle-network/agent-eval";
3
3
  //#region src/runtime/harness-role.ts
4
4
  /**
@@ -230,4 +230,4 @@ function assertProfileModelsAllowed(profile, allowed) {
230
230
  //#endregion
231
231
  export { concreteProfileModel as a, profileProviderModel as c, harnessRunsAgent as d, concreteModelId as i, resolveRouterRetryPolicy as l, assertModelAllowed as n, profileBridgeWireModel as o, assertProfileModelsAllowed as r, profileModelExecutionSettings as s, assertExecutableAgentProfile as t, agentHarness as u };
232
232
 
233
- //# sourceMappingURL=model-policy-UTTc9Z-A.js.map
233
+ //# sourceMappingURL=model-policy-DgRJIJse.js.map