@tangle-network/agent-runtime 0.105.0 → 0.106.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (218) hide show
  1. package/README.md +2 -2
  2. package/dist/activation-CRjVfOiy.js +203 -0
  3. package/dist/activation-CRjVfOiy.js.map +1 -0
  4. package/dist/activation-DyWB0K6E.d.ts +98 -0
  5. package/dist/agent.d.ts +216 -234
  6. package/dist/agent.js +615 -547
  7. package/dist/agent.js.map +1 -1
  8. package/dist/analyst-loop-DGdtVENg.js +517 -0
  9. package/dist/analyst-loop-DGdtVENg.js.map +1 -0
  10. package/dist/analyst-loop.d.ts +10 -43
  11. package/dist/analyst-loop.js +2 -11
  12. package/dist/backends-CiOCyRHb.js +743 -0
  13. package/dist/backends-CiOCyRHb.js.map +1 -0
  14. package/dist/candidate-execution/index.d.ts +4 -192
  15. package/dist/candidate-execution/index.js +5 -66
  16. package/dist/candidate-execution-DqMbv1rU.js +488 -0
  17. package/dist/candidate-execution-DqMbv1rU.js.map +1 -0
  18. package/dist/coder-yhVWbdWc.js +40 -0
  19. package/dist/coder-yhVWbdWc.js.map +1 -0
  20. package/dist/conversation-BpLQZGPH.js +1265 -0
  21. package/dist/conversation-BpLQZGPH.js.map +1 -0
  22. package/dist/conversation.d.ts +2 -804
  23. package/dist/conversation.js +2 -55
  24. package/dist/environment-provider-CfLUmKmf.js +1168 -0
  25. package/dist/environment-provider-CfLUmKmf.js.map +1 -0
  26. package/dist/environment-provider-IUGU3epE.d.ts +964 -0
  27. package/dist/environment-provider.d.ts +2 -78
  28. package/dist/environment-provider.js +2 -18
  29. package/dist/errors-DEAvWQPy.js +111 -0
  30. package/dist/errors-DEAvWQPy.js.map +1 -0
  31. package/dist/improvement-adapter-Cr5TBSji.d.ts +166 -0
  32. package/dist/improvement-cycle-C095kS_g.js +2624 -0
  33. package/dist/improvement-cycle-C095kS_g.js.map +1 -0
  34. package/dist/index-BGdxAwfO.d.ts +838 -0
  35. package/dist/index-C-FYUuFG.d.ts +193 -0
  36. package/dist/index-CbNM40xG.d.ts +140 -0
  37. package/dist/index-DruSKs3Z.d.ts +7224 -0
  38. package/dist/index-Efjb3nrQ.d.ts +671 -0
  39. package/dist/index.d.ts +14 -1058
  40. package/dist/index.js +2106 -2082
  41. package/dist/index.js.map +1 -1
  42. package/dist/intelligence.d.ts +768 -889
  43. package/dist/intelligence.js +1466 -1367
  44. package/dist/intelligence.js.map +1 -1
  45. package/dist/{kb-gate-CwHO0vz6.d.ts → kb-gate-C8z2juK8.d.ts} +33 -31
  46. package/dist/kb-gate-DpaSwXVx.js +80 -0
  47. package/dist/kb-gate-DpaSwXVx.js.map +1 -0
  48. package/dist/knowledge-Ku-mPP4f.js +433 -0
  49. package/dist/knowledge-Ku-mPP4f.js.map +1 -0
  50. package/dist/knowledge.d.ts +2 -150
  51. package/dist/knowledge.js +2 -40
  52. package/dist/local-harness-Dh8PJ0ot.d.ts +455 -0
  53. package/dist/loop-runner-bin-BXsFEUcf.d.ts +162 -0
  54. package/dist/loop-runner-bin-CRagyuNb.js +268 -0
  55. package/dist/loop-runner-bin-CRagyuNb.js.map +1 -0
  56. package/dist/loop-runner-bin.d.ts +2 -15
  57. package/dist/loop-runner-bin.js +2 -24
  58. package/dist/loops.d.ts +5 -4164
  59. package/dist/loops.js +8 -419
  60. package/dist/mcp/bin.d.ts +1 -1
  61. package/dist/mcp/bin.js +116 -146
  62. package/dist/mcp/bin.js.map +1 -1
  63. package/dist/mcp/index.d.ts +295 -436
  64. package/dist/mcp/index.js +1242 -1177
  65. package/dist/mcp/index.js.map +1 -1
  66. package/dist/mcp/memory-bin.d.ts +1 -1
  67. package/dist/mcp/memory-bin.js +37 -16
  68. package/dist/mcp/memory-bin.js.map +1 -1
  69. package/dist/memory-server-DL6cE2Ag.js +234 -0
  70. package/dist/memory-server-DL6cE2Ag.js.map +1 -0
  71. package/dist/model-resolution-Btd9iIKV.js +98 -0
  72. package/dist/model-resolution-Btd9iIKV.js.map +1 -0
  73. package/dist/openai-tools-B68JaOCx.d.ts +24 -0
  74. package/dist/openai-tools-CKLy1C7M.js +44 -0
  75. package/dist/openai-tools-CKLy1C7M.js.map +1 -0
  76. package/dist/otel-export-D34IQW1C.js +843 -0
  77. package/dist/otel-export-D34IQW1C.js.map +1 -0
  78. package/dist/platform.d.ts +188 -185
  79. package/dist/platform.js +185 -218
  80. package/dist/platform.js.map +1 -1
  81. package/dist/prepare-B53sPV7M.js +4292 -0
  82. package/dist/prepare-B53sPV7M.js.map +1 -0
  83. package/dist/primeintellect/index.d.ts +149 -145
  84. package/dist/primeintellect/index.js +626 -1003
  85. package/dist/primeintellect/index.js.map +1 -1
  86. package/dist/profiles.d.ts +296 -490
  87. package/dist/profiles.js +722 -749
  88. package/dist/profiles.js.map +1 -1
  89. package/dist/protected-model-port-BLPH5VVv.js +722 -0
  90. package/dist/protected-model-port-BLPH5VVv.js.map +1 -0
  91. package/dist/protected-model-port-BP6Z4eau.d.ts +283 -0
  92. package/dist/protected-redaction--F3v1oo8.js +200 -0
  93. package/dist/protected-redaction--F3v1oo8.js.map +1 -0
  94. package/dist/redact-D-u-rrcn.js +82 -0
  95. package/dist/redact-D-u-rrcn.js.map +1 -0
  96. package/dist/redact-kbIOjfjM.d.ts +452 -0
  97. package/dist/researcher-CoVqNhfI.js +433 -0
  98. package/dist/researcher-CoVqNhfI.js.map +1 -0
  99. package/dist/runtime-5zM5XxLr.js +5408 -0
  100. package/dist/runtime-5zM5XxLr.js.map +1 -0
  101. package/dist/sandbox-events-DeI5xX8P.js +316 -0
  102. package/dist/sandbox-events-DeI5xX8P.js.map +1 -0
  103. package/dist/spawn-journal-CwPvKUTa.js +456 -0
  104. package/dist/spawn-journal-CwPvKUTa.js.map +1 -0
  105. package/dist/structural-rollout-IXUEplky.js +1445 -0
  106. package/dist/structural-rollout-IXUEplky.js.map +1 -0
  107. package/dist/substrate-B0TYNrXn.js +27 -0
  108. package/dist/substrate-B0TYNrXn.js.map +1 -0
  109. package/dist/{substrate-Dyiqmd3o.d.ts → substrate-BcnuSHXm.d.ts} +57 -54
  110. package/dist/supervise-BiRutHS9.js +7321 -0
  111. package/dist/supervise-BiRutHS9.js.map +1 -0
  112. package/dist/supervisor-DTKhF-RV.js +3826 -0
  113. package/dist/supervisor-DTKhF-RV.js.map +1 -0
  114. package/dist/testing.d.ts +4 -3
  115. package/dist/testing.js +2478 -2637
  116. package/dist/testing.js.map +1 -1
  117. package/dist/tool-server-RcWgLIsL.js +141 -0
  118. package/dist/tool-server-RcWgLIsL.js.map +1 -0
  119. package/dist/trace-propagation-CJJC7SVB.js +57 -0
  120. package/dist/trace-propagation-CJJC7SVB.js.map +1 -0
  121. package/dist/types-BaIpb0XT.d.ts +492 -0
  122. package/dist/types-BevOjfTY.d.ts +765 -0
  123. package/dist/types-C9j4qg6l.d.ts +500 -0
  124. package/dist/types-Cja5OTGh.d.ts +190 -0
  125. package/dist/util-MVgdwuIS.js +145 -0
  126. package/dist/util-MVgdwuIS.js.map +1 -0
  127. package/dist/workspace-archive-BosQiotA.js +575 -0
  128. package/dist/workspace-archive-BosQiotA.js.map +1 -0
  129. package/package.json +44 -56
  130. package/skills/build-with-agent-runtime/SKILL.md +1 -0
  131. package/dist/activation-Cm-9MMX1.d.ts +0 -69
  132. package/dist/analyst-loop.js.map +0 -1
  133. package/dist/backends-BO4Jqoe2.d.ts +0 -134
  134. package/dist/candidate-execution/index.js.map +0 -1
  135. package/dist/chunk-2KGAN2HM.js +0 -1256
  136. package/dist/chunk-2KGAN2HM.js.map +0 -1
  137. package/dist/chunk-2VZYRB55.js +0 -834
  138. package/dist/chunk-2VZYRB55.js.map +0 -1
  139. package/dist/chunk-3MDZX7YU.js +0 -125
  140. package/dist/chunk-3MDZX7YU.js.map +0 -1
  141. package/dist/chunk-5IBQAPVB.js +0 -29
  142. package/dist/chunk-5IBQAPVB.js.map +0 -1
  143. package/dist/chunk-5QOB7H74.js +0 -387
  144. package/dist/chunk-5QOB7H74.js.map +0 -1
  145. package/dist/chunk-C5RTIBNZ.js +0 -48
  146. package/dist/chunk-C5RTIBNZ.js.map +0 -1
  147. package/dist/chunk-CTRA64LY.js +0 -680
  148. package/dist/chunk-CTRA64LY.js.map +0 -1
  149. package/dist/chunk-DPEUKJRO.js +0 -27
  150. package/dist/chunk-DPEUKJRO.js.map +0 -1
  151. package/dist/chunk-FD2MBMOH.js +0 -494
  152. package/dist/chunk-FD2MBMOH.js.map +0 -1
  153. package/dist/chunk-H5QPIZNX.js +0 -907
  154. package/dist/chunk-H5QPIZNX.js.map +0 -1
  155. package/dist/chunk-HLKC4UYB.js +0 -3514
  156. package/dist/chunk-HLKC4UYB.js.map +0 -1
  157. package/dist/chunk-HNP72PNU.js +0 -192
  158. package/dist/chunk-HNP72PNU.js.map +0 -1
  159. package/dist/chunk-ISPWRSEC.js +0 -408
  160. package/dist/chunk-ISPWRSEC.js.map +0 -1
  161. package/dist/chunk-KRBFHMV6.js +0 -1228
  162. package/dist/chunk-KRBFHMV6.js.map +0 -1
  163. package/dist/chunk-M22PL4GH.js +0 -171
  164. package/dist/chunk-M22PL4GH.js.map +0 -1
  165. package/dist/chunk-NURIQBJQ.js +0 -72
  166. package/dist/chunk-NURIQBJQ.js.map +0 -1
  167. package/dist/chunk-OPVWXJ2H.js +0 -75
  168. package/dist/chunk-OPVWXJ2H.js.map +0 -1
  169. package/dist/chunk-PZZKQVQV.js +0 -52
  170. package/dist/chunk-PZZKQVQV.js.map +0 -1
  171. package/dist/chunk-Q2JSAVQ3.js +0 -671
  172. package/dist/chunk-Q2JSAVQ3.js.map +0 -1
  173. package/dist/chunk-RDOAVVHY.js +0 -699
  174. package/dist/chunk-RDOAVVHY.js.map +0 -1
  175. package/dist/chunk-SGKPNBXE.js +0 -60
  176. package/dist/chunk-SGKPNBXE.js.map +0 -1
  177. package/dist/chunk-SMQXZGLZ.js +0 -351
  178. package/dist/chunk-SMQXZGLZ.js.map +0 -1
  179. package/dist/chunk-UHEZW5BU.js +0 -2918
  180. package/dist/chunk-UHEZW5BU.js.map +0 -1
  181. package/dist/chunk-UPWGXKXB.js +0 -254
  182. package/dist/chunk-UPWGXKXB.js.map +0 -1
  183. package/dist/chunk-VISA6CI3.js +0 -200
  184. package/dist/chunk-VISA6CI3.js.map +0 -1
  185. package/dist/chunk-WMTCUOQL.js +0 -474
  186. package/dist/chunk-WMTCUOQL.js.map +0 -1
  187. package/dist/chunk-WRTOVNN4.js +0 -4728
  188. package/dist/chunk-WRTOVNN4.js.map +0 -1
  189. package/dist/chunk-WSTRQZYQ.js +0 -5576
  190. package/dist/chunk-WSTRQZYQ.js.map +0 -1
  191. package/dist/chunk-XBG2W2VW.js +0 -6434
  192. package/dist/chunk-XBG2W2VW.js.map +0 -1
  193. package/dist/chunk-YEJR7IXO.js +0 -68
  194. package/dist/chunk-YEJR7IXO.js.map +0 -1
  195. package/dist/chunk-YJZA2BIK.js +0 -1338
  196. package/dist/chunk-YJZA2BIK.js.map +0 -1
  197. package/dist/completion-gate-BMy5LGoP.d.ts +0 -256
  198. package/dist/conversation.js.map +0 -1
  199. package/dist/coordination-BZZSVYpZ.d.ts +0 -2570
  200. package/dist/environment-provider.js.map +0 -1
  201. package/dist/improvement-adapter-HAZz-7vK.d.ts +0 -203
  202. package/dist/knowledge.js.map +0 -1
  203. package/dist/local-harness-BDNcl6jI.d.ts +0 -175
  204. package/dist/loop-runner-bin-68aoM9-7.d.ts +0 -199
  205. package/dist/loop-runner-bin.js.map +0 -1
  206. package/dist/loops.js.map +0 -1
  207. package/dist/openai-tools-fnj6SRVg.d.ts +0 -46
  208. package/dist/protected-model-port-B4t-OQjL.d.ts +0 -271
  209. package/dist/redact-BuFjxBUJ.d.ts +0 -481
  210. package/dist/sanitize-DEbPNtyI.d.ts +0 -328
  211. package/dist/structural-rollout-DEh6CEsa.d.ts +0 -446
  212. package/dist/supervise-4_48wwvy.d.ts +0 -379
  213. package/dist/types-BCoemcXU.d.ts +0 -802
  214. package/dist/types-BwoZWq-i.d.ts +0 -510
  215. package/dist/types-Cbp72qyu.d.ts +0 -491
  216. package/dist/types-CmYCMbFT.d.ts +0 -203
  217. package/dist/types-CvNwMzQt.d.ts +0 -957
  218. package/dist/worktree-fanout-DxhAWr5Z.d.ts +0 -999
@@ -1,192 +0,0 @@
1
- import {
2
- createKbGate
3
- } from "./chunk-SGKPNBXE.js";
4
- import {
5
- definePersona,
6
- runPersonified,
7
- worktreeFanout
8
- } from "./chunk-WRTOVNN4.js";
9
- import {
10
- createExecutorRegistry
11
- } from "./chunk-XBG2W2VW.js";
12
- import {
13
- runAnalystLoop
14
- } from "./chunk-FD2MBMOH.js";
15
- import {
16
- ConfigError
17
- } from "./chunk-YEJR7IXO.js";
18
-
19
- // src/loop-runner.ts
20
- var DELEGATED_LOOP_MODES = ["code", "review", "research", "audit", "self-improve"];
21
- function isDelegatedLoopMode(value) {
22
- return typeof value === "string" && DELEGATED_LOOP_MODES.includes(value);
23
- }
24
- async function runDelegatedLoop(mode, registry, options = {}) {
25
- const runner = registry[mode];
26
- if (!runner) {
27
- throw new ConfigError(
28
- `runDelegatedLoop: no runner registered for mode '${mode}' (registered: ${Object.keys(registry).join(", ") || "none"})`
29
- );
30
- }
31
- const now = options.now ?? Date.now;
32
- const signal = options.signal ?? new AbortController().signal;
33
- const start = now();
34
- try {
35
- const output = await runner(signal);
36
- return { mode, ok: true, output, durationMs: now() - start };
37
- } catch (err) {
38
- return {
39
- mode,
40
- ok: false,
41
- error: err instanceof Error ? err.message : String(err),
42
- durationMs: now() - start
43
- };
44
- }
45
- }
46
- function worktreeLoopRunner(options) {
47
- const shape = worktreeFanout({
48
- repoRoot: options.repoRoot,
49
- taskPrompt: options.taskPrompt,
50
- harnesses: options.harnesses,
51
- ...options.testCmd !== void 0 ? { testCmd: options.testCmd } : {},
52
- ...options.typecheckCmd !== void 0 ? { typecheckCmd: options.typecheckCmd } : {},
53
- ...options.require !== void 0 ? { require: options.require } : {},
54
- ...options.maxDiffLines !== void 0 ? { maxDiffLines: options.maxDiffLines } : {},
55
- ...options.forbiddenPaths !== void 0 ? { forbiddenPaths: options.forbiddenPaths } : {},
56
- ...options.winnerStrategy !== void 0 ? { winnerStrategy: options.winnerStrategy } : {},
57
- ...options.runGit ? { runGit: options.runGit } : {},
58
- ...options.runHarness ? { runHarness: options.runHarness } : {},
59
- ...options.runCommand ? { runCommand: options.runCommand } : {}
60
- });
61
- const persona = definePersona({
62
- name: "worktree-coder",
63
- root: { profile: { name: "worktree-coder" }, harness: null },
64
- directive: "deliver a minimal validated patch on a fresh worktree",
65
- context: { role: "coder" },
66
- executors: { registry: createExecutorRegistry() }
67
- });
68
- return async (signal) => {
69
- const result = await runPersonified({
70
- persona,
71
- shape,
72
- task: options.taskPrompt,
73
- budget: options.budget,
74
- signal
75
- });
76
- if (result.kind !== "winner" || result.out.kind !== "done") {
77
- const blockers = result.kind === "winner" && result.out.kind === "blocked" ? result.out.blockers.join("; ") : `supervisor settled ${result.kind}`;
78
- throw new Error(`worktreeLoopRunner: no delivered patch (${blockers})`);
79
- }
80
- return result.out.deliverable;
81
- };
82
- }
83
- function researchLoopRunner(o) {
84
- const gate = createKbGate(o.gate);
85
- const maxRounds = Math.max(1, Math.trunc(o.maxRounds ?? 1));
86
- return async (signal) => {
87
- const accepted = [];
88
- let vetoed = [];
89
- let rounds = 0;
90
- for (let round = 0; round < maxRounds; round += 1) {
91
- if (signal.aborted) break;
92
- rounds += 1;
93
- const candidates = await o.research(round, vetoed);
94
- if (candidates.length === 0) break;
95
- vetoed = [];
96
- for (const c of candidates) {
97
- const v = await gate(c);
98
- if (v.accepted) accepted.push(c);
99
- else vetoed.push({ candidate: c, vetoedBy: v.vetoedBy, reason: v.reason });
100
- }
101
- if (vetoed.length === 0) break;
102
- }
103
- return { accepted, vetoed, rounds };
104
- };
105
- }
106
- function auditLoopRunner(options) {
107
- return async () => runAnalystLoop(options);
108
- }
109
-
110
- // src/loop-runner-bin.ts
111
- async function runLoopRunnerCli(args) {
112
- if (!isDelegatedLoopMode(args.mode)) {
113
- return {
114
- exitCode: 2,
115
- error: `unknown mode '${args.mode}' (expected one of: ${DELEGATED_LOOP_MODES.join(", ")})`
116
- };
117
- }
118
- let registry;
119
- try {
120
- registry = await args.loadRegistry();
121
- } catch (err) {
122
- return { exitCode: 2, error: `failed to load registry: ${errMsg(err)}` };
123
- }
124
- if (!registry[args.mode]) {
125
- return {
126
- exitCode: 2,
127
- error: `config registers no runner for mode '${args.mode}' (registered: ${Object.keys(registry).join(", ") || "none"})`
128
- };
129
- }
130
- const result = await runDelegatedLoop(args.mode, registry, {
131
- ...args.now ? { now: args.now } : {}
132
- });
133
- return { exitCode: result.ok ? 0 : 1, result };
134
- }
135
- function parseLoopRunnerArgv(argv) {
136
- const out = {};
137
- for (let i = 0; i < argv.length; i += 1) {
138
- const a = argv[i];
139
- if (a === "--mode") out.mode = argv[++i];
140
- else if (a === "--config") out.config = argv[++i];
141
- else if (a?.startsWith("--mode=")) out.mode = a.slice("--mode=".length);
142
- else if (a?.startsWith("--config=")) out.config = a.slice("--config=".length);
143
- }
144
- return out;
145
- }
146
- function resolveRegistry(mod) {
147
- const def = mod?.default ?? mod;
148
- const value = typeof def === "function" ? def() : def;
149
- return value;
150
- }
151
- function errMsg(err) {
152
- return err instanceof Error ? err.message : String(err);
153
- }
154
- async function main() {
155
- const { mode, config } = parseLoopRunnerArgv(process.argv.slice(2));
156
- if (!mode || !config) {
157
- process.stderr.write(
158
- `usage: agent-runtime-loop --mode <mode> --config <module>
159
- modes: ${DELEGATED_LOOP_MODES.join(" | ")}
160
- config: a JS/TS module default-exporting a DelegatedLoopRegistry (or a factory)
161
- `
162
- );
163
- process.exit(2);
164
- }
165
- const { pathToFileURL } = await import("url");
166
- const { resolve } = await import("path");
167
- const cli = await runLoopRunnerCli({
168
- mode,
169
- loadRegistry: async () => resolveRegistry(await import(pathToFileURL(resolve(config)).href))
170
- });
171
- process.stdout.write(`${JSON.stringify(cli.result ?? { error: cli.error }, null, 2)}
172
- `);
173
- if (cli.error) process.stderr.write(`${cli.error}
174
- `);
175
- process.exit(cli.exitCode);
176
- }
177
- var invokedScript = typeof process !== "undefined" ? process.argv?.[1] : void 0;
178
- if (invokedScript && /loop-runner-bin\.(js|ts|mjs)$/.test(invokedScript)) {
179
- void main();
180
- }
181
-
182
- export {
183
- DELEGATED_LOOP_MODES,
184
- isDelegatedLoopMode,
185
- runDelegatedLoop,
186
- worktreeLoopRunner,
187
- researchLoopRunner,
188
- auditLoopRunner,
189
- runLoopRunnerCli,
190
- parseLoopRunnerArgv
191
- };
192
- //# sourceMappingURL=chunk-HNP72PNU.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/loop-runner.ts","../src/loop-runner-bin.ts"],"sourcesContent":["/**\n *\n * `runDelegatedLoop` — the configured delegated loop-runner.\n *\n * One typed entrypoint a worker agent (or a scheduled routine) calls to run a\n * disciplined loop in a chosen MODE, over agent-runtime's hardened engines:\n *\n * code → build-in-a-loop on the GENERIC recursive path (worktreeLoopRunner: author one\n * `AgentProfile` per harness → worktree-CLI leaves → `patchDelivered` gate)\n * review → caller-registered runner — a `code` runner with an approval gate over candidates\n * research → research-in-a-loop with valid-only KB growth (createKbGate)\n * audit → analyze trace/run data → findings (runAnalystLoop, caller-wired)\n * self-improve → caller-registered `improve(profile, options)` run\n *\n * It is intentionally a thin façade: the value is that EVERY product reuses the\n * one hardened engine instead of forking delegation logic. The dispatcher owns\n * mode routing, timing, fail-loud on an unregistered mode, and a uniform result\n * shape; each mode's engine is a pre-configured runner in the registry (build it\n * with the factories below, or inject your own / a stub).\n *\n * @experimental\n */\n\nimport { runAnalystLoop } from './analyst-loop'\nimport type { RunAnalystLoopOpts, RunAnalystLoopResult } from './analyst-loop/types'\nimport { ConfigError } from './errors'\nimport { type CreateKbGateOptions, createKbGate, type FactCandidate } from './mcp/kb-gate'\nimport {\n type AuthoredHarness,\n type Budget,\n createExecutorRegistry,\n definePersona,\n runPersonified,\n type WinnerStrategy,\n type WorktreeFanoutOptions,\n type WorktreePatchArtifact,\n worktreeFanout,\n} from './runtime'\n\n/** All valid delegated-loop mode names — used for validation and CLI surfaces. @experimental */\nexport const DELEGATED_LOOP_MODES = ['code', 'review', 'research', 'audit', 'self-improve'] as const\n\n/** @experimental */\nexport type DelegatedLoopMode = (typeof DELEGATED_LOOP_MODES)[number]\n\n/** Type guard — returns true when `value` is a valid `DelegatedLoopMode` string. @experimental */\nexport function isDelegatedLoopMode(value: unknown): value is DelegatedLoopMode {\n return typeof value === 'string' && (DELEGATED_LOOP_MODES as readonly string[]).includes(value)\n}\n\n/** @experimental A pre-configured loop for one mode. Returns the mode's raw\n * output; the dispatcher wraps it in a {@link DelegatedLoopResult}. */\nexport type DelegatedLoopRunner<T = unknown> = (signal: AbortSignal) => Promise<T>\n\n/** @experimental Mode → configured runner. Partial: only register the modes a\n * given product/routine actually uses. */\nexport type DelegatedLoopRegistry = Partial<Record<DelegatedLoopMode, DelegatedLoopRunner>>\n\n/** @experimental Uniform result — never throws from a registered runner; a\n * thrown engine becomes `{ ok: false, error }` so a routine can record + move on. */\nexport interface DelegatedLoopResult<T = unknown> {\n mode: DelegatedLoopMode\n ok: boolean\n output?: T\n error?: string\n durationMs: number\n}\n\n/** @experimental */\nexport interface RunDelegatedLoopOptions {\n signal?: AbortSignal\n /** Clock override for deterministic tests. */\n now?: () => number\n}\n\n/**\n *\n * Dispatch a configured loop by mode. Fails loud (throws `ConfigError`) when no\n * runner is registered for the mode — a routine pointed at an unwired mode is a\n * config bug, not a silent no-op. A runner that throws is captured as\n * `{ ok: false }` so unattended runs record the failure rather than crash.\n *\n * @experimental\n */\nexport async function runDelegatedLoop<T = unknown>(\n mode: DelegatedLoopMode,\n registry: DelegatedLoopRegistry,\n options: RunDelegatedLoopOptions = {},\n): Promise<DelegatedLoopResult<T>> {\n const runner = registry[mode] as DelegatedLoopRunner<T> | undefined\n if (!runner) {\n throw new ConfigError(\n `runDelegatedLoop: no runner registered for mode '${mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n )\n }\n const now = options.now ?? Date.now\n const signal = options.signal ?? new AbortController().signal\n const start = now()\n try {\n const output = await runner(signal)\n return { mode, ok: true, output, durationMs: now() - start }\n } catch (err) {\n return {\n mode,\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n durationMs: now() - start,\n }\n }\n}\n\n/** @experimental Options for the local-repo `code` runner over the GENERIC recursive path. */\nexport interface WorktreeLoopRunnerOptions {\n /** Absolute path to the local git checkout each worktree is cut from. */\n repoRoot: string\n /** The instruction handed to every authored harness (composed under each profile's systemPrompt). */\n taskPrompt: string\n /** The supervisor-authored harness profiles — one fanout item (one worktree-CLI leaf) each. */\n harnesses: ReadonlyArray<AuthoredHarness>\n /** Conserved budget pool bounding the fanout (equal-k holds by construction). */\n budget: Budget\n /** Shell command run in each worktree to derive the tests-PASS signal. */\n testCmd?: string\n /** Shell command run in each worktree to derive the typecheck-PASS signal. */\n typecheckCmd?: string\n /** Which verification signals the deliverable REQUIRES present-and-passing (default none). */\n require?: ReadonlyArray<'tests' | 'typecheck'>\n /** Diff-size cap (lines). */\n maxDiffLines?: number\n /** Literal path prefixes the patch must not touch (the secret-floor is always on regardless). */\n forbiddenPaths?: string[]\n /** Winner-selection strategy among gated candidates. Default `highest-score`. */\n winnerStrategy?: WinnerStrategy\n /** Test seams forwarded to the worktree-CLI leaves so the runner drives offline. */\n runGit?: WorktreeFanoutOptions['runGit']\n runHarness?: WorktreeFanoutOptions['runHarness']\n runCommand?: WorktreeFanoutOptions['runCommand']\n}\n\n/**\n *\n * `code` mode on the GENERIC recursive path: author one `AgentProfile` per harness, run them as a\n * `worktreeFanout` (N `createWorktreeCliExecutor` leaves, each `gateOnDeliverable`) through\n * `runPersonified` on the keystone Supervisor. The sandbox-session counterpart that drives the in-box\n * harness over a `SandboxClient` is `detachedSessionDelegate` (`./mcp/delegates`); here there is no\n * `runAgentRounds` driver, no role-coupled delegate — the harness list is the fanout, the gate is\n * `patchDelivered`,\n * the winner is the shared valid-only selector (NOT `defaultSelectWinner`, whose non-valid fallback\n * would surface an ungated patch). Equal-k holds by the conserved budget pool. Returns the winning\n * patch artifact, or throws when no candidate is delivered (fail loud, never a vacuous done).\n *\n * @experimental\n */\nexport function worktreeLoopRunner(\n options: WorktreeLoopRunnerOptions,\n): DelegatedLoopRunner<WorktreePatchArtifact> {\n const shape = worktreeFanout<string>({\n repoRoot: options.repoRoot,\n taskPrompt: options.taskPrompt,\n harnesses: options.harnesses,\n ...(options.testCmd !== undefined ? { testCmd: options.testCmd } : {}),\n ...(options.typecheckCmd !== undefined ? { typecheckCmd: options.typecheckCmd } : {}),\n ...(options.require !== undefined ? { require: options.require } : {}),\n ...(options.maxDiffLines !== undefined ? { maxDiffLines: options.maxDiffLines } : {}),\n ...(options.forbiddenPaths !== undefined ? { forbiddenPaths: options.forbiddenPaths } : {}),\n ...(options.winnerStrategy !== undefined ? { winnerStrategy: options.winnerStrategy } : {}),\n ...(options.runGit ? { runGit: options.runGit } : {}),\n ...(options.runHarness ? { runHarness: options.runHarness } : {}),\n ...(options.runCommand ? { runCommand: options.runCommand } : {}),\n })\n // The persona's only role here is to carry the fanout shape onto the Supervisor; each item's\n // executor is BYO (the gated worktree-CLI leaf), so the registry only needs to pass BYO through.\n const persona = definePersona<WorktreePatchArtifact>({\n name: 'worktree-coder',\n root: { profile: { name: 'worktree-coder' }, harness: null },\n directive: 'deliver a minimal validated patch on a fresh worktree',\n context: { role: 'coder' },\n executors: { registry: createExecutorRegistry() },\n })\n return async (signal) => {\n const result = await runPersonified<string, WorktreePatchArtifact>({\n persona,\n shape,\n task: options.taskPrompt,\n budget: options.budget,\n signal,\n })\n if (result.kind !== 'winner' || result.out.kind !== 'done') {\n const blockers =\n result.kind === 'winner' && result.out.kind === 'blocked'\n ? result.out.blockers.join('; ')\n : `supervisor settled ${result.kind}`\n throw new Error(`worktreeLoopRunner: no delivered patch (${blockers})`)\n }\n return result.out.deliverable\n }\n}\n\n/** @experimental A fact rejected at the KB gate — surfaced, never dropped. */\nexport interface VetoedFact {\n candidate: FactCandidate\n vetoedBy?: string\n reason?: string\n}\n\n/** @experimental */\nexport interface ResearchLoopResult {\n /** Facts that passed the fail-closed gate — safe to write to the KB. */\n accepted: FactCandidate[]\n /** Facts the gate vetoed in the final round — escalate, do not silently drop. */\n vetoed: VetoedFact[]\n /** Research rounds actually run. */\n rounds: number\n}\n\n/** @experimental Options for the default `research` runner. */\nexport interface ResearchLoopRunnerOptions {\n /**\n * The research engine (the consumer's web/doc searcher + extractor). Called\n * each round with the prior round's vetoes so it can re-research the gaps.\n * Returns fact candidates carrying their grounding (`verbatimPassage` +\n * `sourceText`).\n */\n research: (round: number, vetoed: VetoedFact[]) => Promise<FactCandidate[]>\n /** Gate config (extra judges, self-artifact kinds, …). The floor is always on. */\n gate?: CreateKbGateOptions\n /** Max research rounds (correct-on-veto remediation). Default 1. */\n maxRounds?: number\n}\n\n/**\n * `research` mode — research-in-a-loop with valid-only KB growth.\n *\n * Each round: research → gate every candidate (fail-closed; passage MUST be in\n * the source) → accept the clean ones → re-research the vetoed ones next round,\n * up to `maxRounds`. Vetoed facts in the final round are RETURNED (escalate,\n * never silently dropped) so the caller audits vs retries.\n *\n * @experimental\n */\nexport function researchLoopRunner(\n o: ResearchLoopRunnerOptions,\n): DelegatedLoopRunner<ResearchLoopResult> {\n const gate = createKbGate(o.gate)\n const maxRounds = Math.max(1, Math.trunc(o.maxRounds ?? 1))\n return async (signal) => {\n const accepted: FactCandidate[] = []\n let vetoed: VetoedFact[] = []\n let rounds = 0\n for (let round = 0; round < maxRounds; round += 1) {\n if (signal.aborted) break\n rounds += 1\n const candidates = await o.research(round, vetoed)\n if (candidates.length === 0) break\n vetoed = []\n for (const c of candidates) {\n const v = await gate(c)\n if (v.accepted) accepted.push(c)\n else vetoed.push({ candidate: c, vetoedBy: v.vetoedBy, reason: v.reason })\n }\n if (vetoed.length === 0) break\n }\n return { accepted, vetoed, rounds }\n }\n}\n\n/**\n * `audit` mode — analyst loop over captured trace/run data.\n *\n * @experimental\n */\nexport function auditLoopRunner<TProposal = unknown, TEdit = unknown>(\n options: RunAnalystLoopOpts,\n): DelegatedLoopRunner<RunAnalystLoopResult<TProposal, TEdit>> {\n return async () => runAnalystLoop<TProposal, TEdit>(options)\n}\n","#!/usr/bin/env node\n/**\n *\n * `agent-runtime-loop` — the schedulable entrypoint for the configured\n * delegated loop-runner. A cron job / routine / Makefile target invokes:\n *\n * agent-runtime-loop --mode research --config ./loops.config.js\n *\n * The config module wires the registry (with full access to env / creds —\n * which is why the deps live there, not in this generic bin). It must default-\n * export a `DelegatedLoopRegistry`, or a `() => DelegatedLoopRegistry | Promise<…>`.\n * The bin runs the selected mode, prints the `DelegatedLoopResult` as JSON, and\n * exits 0 on `ok`, 1 on a recorded failure, 2 on a usage/config error.\n *\n * @experimental\n */\n\nimport {\n DELEGATED_LOOP_MODES,\n type DelegatedLoopMode,\n type DelegatedLoopRegistry,\n type DelegatedLoopResult,\n isDelegatedLoopMode,\n runDelegatedLoop,\n} from './loop-runner'\n\n/** @experimental Parsed CLI invocation. */\nexport interface LoopRunnerCliArgs {\n mode: string\n /** Loads the registry — the bin wires this from `--config`; tests inject a stub. */\n loadRegistry: () => Promise<DelegatedLoopRegistry> | DelegatedLoopRegistry\n now?: () => number\n}\n\n/** @experimental */\nexport interface LoopRunnerCliResult {\n exitCode: number\n result?: DelegatedLoopResult\n error?: string\n}\n\n/**\n *\n * Pure CLI core (no process / argv / IO) so it's unit-testable: validate the\n * mode, load the registry, dispatch, map to an exit code (0 ok / 1 failed /\n * 2 usage). Exported for embedding in custom runners + tests.\n *\n * @experimental\n */\nexport async function runLoopRunnerCli(args: LoopRunnerCliArgs): Promise<LoopRunnerCliResult> {\n if (!isDelegatedLoopMode(args.mode)) {\n return {\n exitCode: 2,\n error: `unknown mode '${args.mode}' (expected one of: ${DELEGATED_LOOP_MODES.join(', ')})`,\n }\n }\n let registry: DelegatedLoopRegistry\n try {\n registry = await args.loadRegistry()\n } catch (err) {\n return { exitCode: 2, error: `failed to load registry: ${errMsg(err)}` }\n }\n if (!registry[args.mode]) {\n return {\n exitCode: 2,\n error: `config registers no runner for mode '${args.mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n }\n }\n // runDelegatedLoop throws only on a missing runner (guarded above); a failing\n // engine is captured as { ok: false } → exit 1, not a crash.\n const result = await runDelegatedLoop(args.mode as DelegatedLoopMode, registry, {\n ...(args.now ? { now: args.now } : {}),\n })\n return { exitCode: result.ok ? 0 : 1, result }\n}\n\n/** Parse `--mode X --config Y` from an argv tail (`process.argv.slice(2)`). */\nexport function parseLoopRunnerArgv(argv: string[]): { mode?: string; config?: string } {\n const out: { mode?: string; config?: string } = {}\n for (let i = 0; i < argv.length; i += 1) {\n const a = argv[i]\n if (a === '--mode') out.mode = argv[++i]\n else if (a === '--config') out.config = argv[++i]\n else if (a?.startsWith('--mode=')) out.mode = a.slice('--mode='.length)\n else if (a?.startsWith('--config=')) out.config = a.slice('--config='.length)\n }\n return out\n}\n\n/** Normalize a config module's default export → a registry. */\nfunction resolveRegistry(mod: unknown): DelegatedLoopRegistry {\n const def = (mod as { default?: unknown })?.default ?? mod\n const value = typeof def === 'function' ? (def as () => unknown)() : def\n return value as DelegatedLoopRegistry\n}\n\nfunction errMsg(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n\n/** The argv → IO → exit shell. Kept thin; logic lives in `runLoopRunnerCli`. */\nasync function main(): Promise<void> {\n const { mode, config } = parseLoopRunnerArgv(process.argv.slice(2))\n if (!mode || !config) {\n process.stderr.write(\n 'usage: agent-runtime-loop --mode <mode> --config <module>\\n' +\n ` modes: ${DELEGATED_LOOP_MODES.join(' | ')}\\n` +\n ' config: a JS/TS module default-exporting a DelegatedLoopRegistry (or a factory)\\n',\n )\n process.exit(2)\n }\n const { pathToFileURL } = await import('node:url')\n const { resolve } = await import('node:path')\n const cli = await runLoopRunnerCli({\n mode,\n loadRegistry: async () => resolveRegistry(await import(pathToFileURL(resolve(config)).href)),\n })\n process.stdout.write(`${JSON.stringify(cli.result ?? { error: cli.error }, null, 2)}\\n`)\n if (cli.error) process.stderr.write(`${cli.error}\\n`)\n process.exit(cli.exitCode)\n}\n\n// Run only when executed as the bin — never when imported for the testable\n// core, and never when bundled into a runtime that has no `process.argv`\n// (e.g. Cloudflare Workers, where `process` is a shim without `argv`). Reading\n// `process.argv[1]` directly would throw at module load there; `process.argv?.`\n// keeps the guard a no-op instead of crashing the Worker on startup.\nconst invokedScript = typeof process !== 'undefined' ? process.argv?.[1] : undefined\nif (invokedScript && /loop-runner-bin\\.(js|ts|mjs)$/.test(invokedScript)) {\n void main()\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAwCO,IAAM,uBAAuB,CAAC,QAAQ,UAAU,YAAY,SAAS,cAAc;AAMnF,SAAS,oBAAoB,OAA4C;AAC9E,SAAO,OAAO,UAAU,YAAa,qBAA2C,SAAS,KAAK;AAChG;AAoCA,eAAsB,iBACpB,MACA,UACA,UAAmC,CAAC,GACH;AACjC,QAAM,SAAS,SAAS,IAAI;AAC5B,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI;AAAA,MACR,oDAAoD,IAAI,kBACtD,OAAO,KAAK,QAAQ,EAAE,KAAK,IAAI,KAAK,MACtC;AAAA,IACF;AAAA,EACF;AACA,QAAM,MAAM,QAAQ,OAAO,KAAK;AAChC,QAAM,SAAS,QAAQ,UAAU,IAAI,gBAAgB,EAAE;AACvD,QAAM,QAAQ,IAAI;AAClB,MAAI;AACF,UAAM,SAAS,MAAM,OAAO,MAAM;AAClC,WAAO,EAAE,MAAM,IAAI,MAAM,QAAQ,YAAY,IAAI,IAAI,MAAM;AAAA,EAC7D,SAAS,KAAK;AACZ,WAAO;AAAA,MACL;AAAA,MACA,IAAI;AAAA,MACJ,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAAA,MACtD,YAAY,IAAI,IAAI;AAAA,IACtB;AAAA,EACF;AACF;AA4C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MAAM,CAAC,CAAC;AAClE,MAAI,CAAC,QAAQ,CAAC,QAAQ;AACpB,YAAQ,OAAO;AAAA,MACb;AAAA,WACc,qBAAqB,KAAK,KAAK,CAAC;AAAA;AAAA;AAAA,IAEhD;AACA,YAAQ,KAAK,CAAC;AAAA,EAChB;AACA,QAAM,EAAE,cAAc,IAAI,MAAM,OAAO,KAAU;AACjD,QAAM,EAAE,QAAQ,IAAI,MAAM,OAAO,MAAW;AAC5C,QAAM,MAAM,MAAM,iBAAiB;AAAA,IACjC;AAAA,IACA,cAAc,YAAY,gBAAgB,MAAM,OAAO,cAAc,QAAQ,MAAM,CAAC,EAAE,KAAK;AAAA,EAC7F,CAAC;AACD,UAAQ,OAAO,MAAM,GAAG,KAAK,UAAU,IAAI,UAAU,EAAE,OAAO,IAAI,MAAM,GAAG,MAAM,CAAC,CAAC;AAAA,CAAI;AACvF,MAAI,IAAI,MAAO,SAAQ,OAAO,MAAM,GAAG,IAAI,KAAK;AAAA,CAAI;AACpD,UAAQ,KAAK,IAAI,QAAQ;AAC3B;AAOA,IAAM,gBAAgB,OAAO,YAAY,cAAc,QAAQ,OAAO,CAAC,IAAI;AAC3E,IAAI,iBAAiB,gCAAgC,KAAK,aAAa,GAAG;AACxE,OAAK,KAAK;AACZ;","names":[]}
@@ -1,408 +0,0 @@
1
- import {
2
- zeroTokenUsage
3
- } from "./chunk-3MDZX7YU.js";
4
-
5
- // src/durable/spawn-journal.ts
6
- import { createHash } from "crypto";
7
- function contentAddress(artifact) {
8
- const hex = createHash("sha256").update(stableStringify(artifact), "utf-8").digest("hex");
9
- return `sha256:${hex}`;
10
- }
11
- function stableStringify(value) {
12
- if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
13
- if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
14
- const entries = Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
15
- return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(",")}}`;
16
- }
17
- var InMemoryResultBlobStore = class {
18
- blobs = /* @__PURE__ */ new Map();
19
- async put(outRef, artifact) {
20
- assertContentAddress(outRef, artifact);
21
- this.blobs.set(outRef, artifact);
22
- }
23
- async get(outRef) {
24
- return this.blobs.has(outRef) ? this.blobs.get(outRef) : void 0;
25
- }
26
- };
27
- var FileResultBlobStore = class {
28
- constructor(dir) {
29
- this.dir = dir;
30
- }
31
- dir;
32
- async put(outRef, artifact) {
33
- assertContentAddress(outRef, artifact);
34
- const fs = await import("fs/promises");
35
- await fs.mkdir(this.dir, { recursive: true });
36
- const fh = await fs.open(this.blobPath(outRef), "w");
37
- try {
38
- await fh.write(JSON.stringify(artifact));
39
- await fh.sync();
40
- } finally {
41
- await fh.close();
42
- }
43
- }
44
- async get(outRef) {
45
- const fs = await import("fs/promises");
46
- let text;
47
- try {
48
- text = await fs.readFile(this.blobPath(outRef), "utf8");
49
- } catch (err) {
50
- if (isNoEntError(err)) return void 0;
51
- throw err;
52
- }
53
- return JSON.parse(text);
54
- }
55
- blobPath(outRef) {
56
- return `${this.dir}/${outRef.replace(/:/g, "-")}.json`;
57
- }
58
- };
59
- function assertContentAddress(outRef, artifact) {
60
- const expected = contentAddress(artifact);
61
- if (outRef !== expected) {
62
- throw new Error(
63
- `blob outRef '${outRef}' does not match the artifact content hash '${expected}'; a content-addressed store refuses a mismatched ref (breaks the replay invariant)`
64
- );
65
- }
66
- }
67
- var InMemorySpawnJournal = class {
68
- trees = /* @__PURE__ */ new Map();
69
- async loadTree(root) {
70
- const tree = this.trees.get(root);
71
- if (!tree) return void 0;
72
- return tree.events.map((ev) => ({ ...ev }));
73
- }
74
- async beginTree(root, at) {
75
- const existing = this.trees.get(root);
76
- if (existing) {
77
- if (existing.begunAt !== at) {
78
- throw new Error(
79
- `spawn tree '${root}' already begun at ${existing.begunAt}; refusing to overwrite with ${at}`
80
- );
81
- }
82
- return;
83
- }
84
- this.trees.set(root, { begunAt: at, events: [] });
85
- }
86
- async appendEvent(root, ev) {
87
- const tree = this.trees.get(root);
88
- if (!tree) {
89
- throw new Error(`appendEvent called for unknown spawn tree '${root}'; call beginTree first`);
90
- }
91
- assertSeqUnique(root, tree.events, ev);
92
- tree.events.push({ ...ev });
93
- }
94
- };
95
- var FileSpawnJournal = class {
96
- constructor(path) {
97
- this.path = path;
98
- }
99
- path;
100
- async loadTree(root) {
101
- const fs = await import("fs/promises");
102
- let text;
103
- try {
104
- text = await fs.readFile(this.path, "utf8");
105
- } catch (err) {
106
- if (isNoEntError(err)) return void 0;
107
- throw err;
108
- }
109
- const lines = text.split("\n").filter((line) => line.length > 0);
110
- let begun = false;
111
- const events = [];
112
- for (const line of lines) {
113
- const record = JSON.parse(line);
114
- if (record.root !== root) continue;
115
- if (record.kind === "begin") {
116
- begun = true;
117
- } else {
118
- if (!begun) {
119
- throw new Error(
120
- `spawn journal corrupted: event for tree '${root}' precedes its begin record`
121
- );
122
- }
123
- assertSeqUnique(root, events, record.event);
124
- events.push(record.event);
125
- }
126
- }
127
- return begun ? events : void 0;
128
- }
129
- async beginTree(root, at) {
130
- const existing = await this.loadTreeBegin(root);
131
- if (existing) {
132
- if (existing !== at) {
133
- throw new Error(
134
- `spawn tree '${root}' already begun in ${this.path} at ${existing}; refusing to overwrite with ${at}`
135
- );
136
- }
137
- return;
138
- }
139
- await this.appendRecord({ kind: "begin", root, at });
140
- }
141
- async appendEvent(root, ev) {
142
- const events = await this.loadTree(root);
143
- if (events === void 0) {
144
- throw new Error(`appendEvent called for unknown spawn tree '${root}'; call beginTree first`);
145
- }
146
- assertSeqUnique(root, events, ev);
147
- await this.appendRecord({ kind: "event", root, event: ev });
148
- }
149
- async loadTreeBegin(root) {
150
- const fs = await import("fs/promises");
151
- let text;
152
- try {
153
- text = await fs.readFile(this.path, "utf8");
154
- } catch (err) {
155
- if (isNoEntError(err)) return void 0;
156
- throw err;
157
- }
158
- const lines = text.split("\n").filter((line) => line.length > 0);
159
- for (const line of lines) {
160
- const record = JSON.parse(line);
161
- if (record.root === root && record.kind === "begin") return record.at;
162
- }
163
- return void 0;
164
- }
165
- async appendRecord(record) {
166
- const fs = await import("fs/promises");
167
- const path = await import("path");
168
- await fs.mkdir(path.dirname(this.path), { recursive: true });
169
- const fh = await fs.open(this.path, "a");
170
- try {
171
- await fh.write(`${JSON.stringify(record)}
172
- `);
173
- await fh.sync();
174
- } finally {
175
- await fh.close();
176
- }
177
- }
178
- };
179
- function assertSeqUnique(root, events, ev) {
180
- if (outsideCursorNamespace(ev)) return;
181
- if (events.some((e) => !outsideCursorNamespace(e) && e.seq === ev.seq)) {
182
- throw new Error(
183
- `spawn journal corrupted: duplicate cursor seq ${ev.seq} in tree '${root}'; the cursor order replay relies on is not unique`
184
- );
185
- }
186
- }
187
- function outsideCursorNamespace(ev) {
188
- return ev.kind === "spawned" || ev.kind === "waiting" || ev.kind === "metered";
189
- }
190
- async function replaySpawnTree(journal, blobs, root) {
191
- const events = await journal.loadTree(root);
192
- if (events === void 0) {
193
- throw new Error(`replaySpawnTree: no journaled tree for root '${root}'`);
194
- }
195
- const ordered = [...events].sort((a, b) => a.seq - b.seq);
196
- const labels = /* @__PURE__ */ new Map();
197
- for (const ev of ordered) {
198
- if (ev.kind === "spawned" || ev.kind === "waiting") labels.set(ev.id, ev.label);
199
- }
200
- const settled = [];
201
- for (const ev of ordered) {
202
- if (ev.kind === "spawned") continue;
203
- if (ev.kind === "waiting") continue;
204
- if (ev.kind === "metered") continue;
205
- if (ev.kind === "woken") {
206
- if (ev.by === "cancelled" || ev.outRef === void 0) {
207
- settled.push({
208
- kind: "down",
209
- handle: replayHandle(ev.id, labels.get(ev.id) ?? ev.id, "cancelled"),
210
- reason: "wait cancelled",
211
- infra: false,
212
- restartCount: 0,
213
- seq: ev.seq
214
- });
215
- continue;
216
- }
217
- const outcome = await blobs.get(ev.outRef);
218
- if (outcome === void 0) {
219
- throw new Error(
220
- `replaySpawnTree: blob store has no wait outcome for outRef '${ev.outRef}' (node '${ev.id}', seq ${ev.seq})`
221
- );
222
- }
223
- settled.push({
224
- kind: "done",
225
- handle: replayHandle(ev.id, labels.get(ev.id) ?? ev.id, "done"),
226
- out: outcome,
227
- outRef: ev.outRef,
228
- spent: zeroSpend(),
229
- seq: ev.seq
230
- });
231
- continue;
232
- }
233
- if (ev.kind === "cancelled") {
234
- settled.push({
235
- kind: "down",
236
- handle: replayHandle(ev.id, labels.get(ev.id) ?? ev.id, "cancelled"),
237
- reason: ev.reason,
238
- infra: false,
239
- restartCount: 0,
240
- seq: ev.seq
241
- });
242
- continue;
243
- }
244
- if (ev.status === "down") {
245
- settled.push({
246
- kind: "down",
247
- handle: replayHandle(ev.id, labels.get(ev.id) ?? ev.id, "failed"),
248
- reason: ev.verdict?.notes ?? "child down",
249
- infra: ev.infra === true,
250
- restartCount: 0,
251
- seq: ev.seq
252
- });
253
- continue;
254
- }
255
- if (ev.outRef === void 0) {
256
- throw new Error(
257
- `replaySpawnTree: settled-done event for '${ev.id}' (seq ${ev.seq}) has no outRef; cannot rehydrate the result the driver branched on`
258
- );
259
- }
260
- const out = await blobs.get(ev.outRef);
261
- if (out === void 0) {
262
- throw new Error(
263
- `replaySpawnTree: blob store has no artifact for outRef '${ev.outRef}' (node '${ev.id}', seq ${ev.seq})`
264
- );
265
- }
266
- settled.push({
267
- kind: "done",
268
- handle: replayHandle(ev.id, labels.get(ev.id) ?? ev.id, "done"),
269
- out,
270
- outRef: ev.outRef,
271
- verdict: ev.verdict,
272
- spent: ev.spent,
273
- seq: ev.seq
274
- });
275
- }
276
- return settled;
277
- }
278
- function replayHandle(id, label, status) {
279
- return {
280
- id,
281
- label,
282
- status,
283
- abort() {
284
- throw new Error(`cannot abort node '${id}': replayed handles are terminal, not live`);
285
- }
286
- };
287
- }
288
- function materializeTreeView(events) {
289
- const nodes = /* @__PURE__ */ new Map();
290
- let root;
291
- const spawns = events.filter(
292
- (ev) => ev.kind === "spawned" || ev.kind === "waiting"
293
- ).sort((a, b) => a.seq - b.seq);
294
- const settlements = events.filter((ev) => ev.kind !== "spawned" && ev.kind !== "waiting" && ev.kind !== "metered").sort((a, b) => a.seq - b.seq);
295
- for (const ev of spawns) {
296
- if (ev.kind === "waiting") {
297
- nodes.set(ev.id, {
298
- id: ev.id,
299
- parent: ev.parent,
300
- label: ev.label,
301
- status: "waiting",
302
- runtime: "wait",
303
- budget: { maxIterations: 0, maxTokens: 0 },
304
- spent: zeroSpend()
305
- });
306
- continue;
307
- }
308
- if (ev.parent === void 0 && root === void 0) root = ev.id;
309
- nodes.set(ev.id, {
310
- id: ev.id,
311
- parent: ev.parent,
312
- label: ev.label,
313
- status: "pending",
314
- runtime: ev.runtime,
315
- budget: ev.budget,
316
- spent: zeroSpend()
317
- });
318
- }
319
- for (const ev of settlements) {
320
- if (ev.kind === "settled") {
321
- const node = requireNode(nodes, ev.id);
322
- node.status = ev.status === "done" ? "done" : "failed";
323
- node.spent = ev.spent;
324
- node.outRef = ev.outRef;
325
- } else if (ev.kind === "woken") {
326
- const node = requireNode(nodes, ev.id);
327
- node.status = ev.by === "cancelled" ? "cancelled" : "done";
328
- node.outRef = ev.outRef;
329
- } else {
330
- const node = requireNode(nodes, ev.id);
331
- node.status = "cancelled";
332
- }
333
- }
334
- for (const ev of events) {
335
- if (ev.kind !== "metered") continue;
336
- const node = requireNode(nodes, ev.id);
337
- node.spent = addJournalSpend(node.spent, ev.spend);
338
- }
339
- const snapshots = [...nodes.values()].map(freezeSnapshot);
340
- return {
341
- root: root ?? snapshots[0]?.id ?? "",
342
- nodes: snapshots,
343
- inFlight: snapshots.filter((n) => n.status === "running" || n.status === "acquiring").length,
344
- waiting: snapshots.filter((n) => n.status === "waiting").length
345
- };
346
- }
347
- function pendingWaits(events) {
348
- const woken = /* @__PURE__ */ new Set();
349
- for (const ev of events) if (ev.kind === "woken") woken.add(ev.id);
350
- const pending = [];
351
- for (const ev of events) {
352
- if (ev.kind !== "waiting" || woken.has(ev.id)) continue;
353
- pending.push({
354
- id: ev.id,
355
- label: ev.label,
356
- spec: ev.spec,
357
- armedAt: ev.armedAt,
358
- ordinal: ev.seq
359
- });
360
- }
361
- return pending.sort((a, b) => a.ordinal - b.ordinal);
362
- }
363
- function zeroSpend() {
364
- return { iterations: 0, tokens: zeroTokenUsage(), usd: 0, ms: 0 };
365
- }
366
- function addJournalSpend(a, b) {
367
- return {
368
- iterations: a.iterations + b.iterations,
369
- tokens: { input: a.tokens.input + b.tokens.input, output: a.tokens.output + b.tokens.output },
370
- usd: a.usd + b.usd,
371
- ...a.usdKnown === false || b.usdKnown === false ? { usdKnown: false } : {},
372
- ms: a.ms + b.ms
373
- };
374
- }
375
- function requireNode(nodes, id) {
376
- const node = nodes.get(id);
377
- if (!node) {
378
- throw new Error(`spawn journal corrupted: settle/cancel for node '${id}' with no prior spawn`);
379
- }
380
- return node;
381
- }
382
- function freezeSnapshot(node) {
383
- return {
384
- id: node.id,
385
- parent: node.parent,
386
- label: node.label,
387
- status: node.status,
388
- runtime: node.runtime,
389
- budget: node.budget,
390
- spent: node.spent,
391
- outRef: node.outRef
392
- };
393
- }
394
- function isNoEntError(err) {
395
- return typeof err === "object" && err !== null && "code" in err && err.code === "ENOENT";
396
- }
397
-
398
- export {
399
- contentAddress,
400
- InMemoryResultBlobStore,
401
- FileResultBlobStore,
402
- InMemorySpawnJournal,
403
- FileSpawnJournal,
404
- replaySpawnTree,
405
- materializeTreeView,
406
- pendingWaits
407
- };
408
- //# sourceMappingURL=chunk-ISPWRSEC.js.map