@tangle-network/agent-runtime 0.104.0 → 0.106.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 (217) hide show
  1. package/README.md +176 -42
  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-Dy8NujB4.js +713 -0
  13. package/dist/backends-Dy8NujB4.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-XucG_K3l.js +1265 -0
  21. package/dist/conversation-XucG_K3l.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 -1134
  40. package/dist/index.js +2134 -1972
  41. package/dist/index.js.map +1 -1
  42. package/dist/intelligence.d.ts +776 -888
  43. package/dist/intelligence.js +1466 -1410
  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-BwjQ1NfH.js +268 -0
  55. package/dist/loop-runner-bin-BwjQ1NfH.js.map +1 -0
  56. package/dist/loop-runner-bin.d.ts +2 -17
  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 -437
  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 +150 -147
  84. package/dist/primeintellect/index.js +626 -1004
  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-BG0BziaP.js +5408 -0
  100. package/dist/runtime-BG0BziaP.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 +43 -55
  130. package/skills/build-with-agent-runtime/SKILL.md +16 -9
  131. package/skills/loop-writer/SKILL.md +1 -1
  132. package/dist/activation-Cm-9MMX1.d.ts +0 -69
  133. package/dist/analyst-loop.js.map +0 -1
  134. package/dist/backends-BO4Jqoe2.d.ts +0 -134
  135. package/dist/candidate-execution/index.js.map +0 -1
  136. package/dist/chunk-2KGAN2HM.js +0 -1256
  137. package/dist/chunk-2KGAN2HM.js.map +0 -1
  138. package/dist/chunk-2QJSNOGK.js +0 -48
  139. package/dist/chunk-2QJSNOGK.js.map +0 -1
  140. package/dist/chunk-2UABGGUB.js +0 -474
  141. package/dist/chunk-2UABGGUB.js.map +0 -1
  142. package/dist/chunk-2VZYRB55.js +0 -834
  143. package/dist/chunk-2VZYRB55.js.map +0 -1
  144. package/dist/chunk-2X65HYMI.js +0 -3526
  145. package/dist/chunk-2X65HYMI.js.map +0 -1
  146. package/dist/chunk-3MDZX7YU.js +0 -125
  147. package/dist/chunk-3MDZX7YU.js.map +0 -1
  148. package/dist/chunk-3PPVCS75.js +0 -199
  149. package/dist/chunk-3PPVCS75.js.map +0 -1
  150. package/dist/chunk-5HNDYWUT.js +0 -6424
  151. package/dist/chunk-5HNDYWUT.js.map +0 -1
  152. package/dist/chunk-5IBQAPVB.js +0 -29
  153. package/dist/chunk-5IBQAPVB.js.map +0 -1
  154. package/dist/chunk-5QOB7H74.js +0 -387
  155. package/dist/chunk-5QOB7H74.js.map +0 -1
  156. package/dist/chunk-ATDFUJYI.js +0 -4728
  157. package/dist/chunk-ATDFUJYI.js.map +0 -1
  158. package/dist/chunk-B7K7V22Y.js +0 -699
  159. package/dist/chunk-B7K7V22Y.js.map +0 -1
  160. package/dist/chunk-DPEUKJRO.js +0 -27
  161. package/dist/chunk-DPEUKJRO.js.map +0 -1
  162. package/dist/chunk-FD2MBMOH.js +0 -494
  163. package/dist/chunk-FD2MBMOH.js.map +0 -1
  164. package/dist/chunk-FJI3EXU3.js +0 -2402
  165. package/dist/chunk-FJI3EXU3.js.map +0 -1
  166. package/dist/chunk-HAO4CXHP.js +0 -200
  167. package/dist/chunk-HAO4CXHP.js.map +0 -1
  168. package/dist/chunk-ISPWRSEC.js +0 -408
  169. package/dist/chunk-ISPWRSEC.js.map +0 -1
  170. package/dist/chunk-KRBFHMV6.js +0 -1228
  171. package/dist/chunk-KRBFHMV6.js.map +0 -1
  172. package/dist/chunk-L5DST3QC.js +0 -351
  173. package/dist/chunk-L5DST3QC.js.map +0 -1
  174. package/dist/chunk-M22PL4GH.js +0 -171
  175. package/dist/chunk-M22PL4GH.js.map +0 -1
  176. package/dist/chunk-NURIQBJQ.js +0 -72
  177. package/dist/chunk-NURIQBJQ.js.map +0 -1
  178. package/dist/chunk-PZZKQVQV.js +0 -52
  179. package/dist/chunk-PZZKQVQV.js.map +0 -1
  180. package/dist/chunk-Q2JSAVQ3.js +0 -671
  181. package/dist/chunk-Q2JSAVQ3.js.map +0 -1
  182. package/dist/chunk-SBTWKPVR.js +0 -5576
  183. package/dist/chunk-SBTWKPVR.js.map +0 -1
  184. package/dist/chunk-SGKPNBXE.js +0 -60
  185. package/dist/chunk-SGKPNBXE.js.map +0 -1
  186. package/dist/chunk-SNSMRT6H.js +0 -680
  187. package/dist/chunk-SNSMRT6H.js.map +0 -1
  188. package/dist/chunk-STJEHM5F.js +0 -1338
  189. package/dist/chunk-STJEHM5F.js.map +0 -1
  190. package/dist/chunk-UPWGXKXB.js +0 -254
  191. package/dist/chunk-UPWGXKXB.js.map +0 -1
  192. package/dist/chunk-YEJR7IXO.js +0 -68
  193. package/dist/chunk-YEJR7IXO.js.map +0 -1
  194. package/dist/chunk-ZXICDSAK.js +0 -907
  195. package/dist/chunk-ZXICDSAK.js.map +0 -1
  196. package/dist/completion-gate-Bv47cOnn.d.ts +0 -256
  197. package/dist/conversation.js.map +0 -1
  198. package/dist/coordination-CxtzMxSM.d.ts +0 -2570
  199. package/dist/environment-provider.js.map +0 -1
  200. package/dist/improve--2A0gK1-.d.ts +0 -440
  201. package/dist/improvement-adapter-HAZz-7vK.d.ts +0 -203
  202. package/dist/knowledge.js.map +0 -1
  203. package/dist/local-harness-CtK9dSny.d.ts +0 -175
  204. package/dist/loop-runner-bin-DUOGtvOl.d.ts +0 -207
  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-DzkUY3HQ.d.ts +0 -271
  209. package/dist/sanitize-DEbPNtyI.d.ts +0 -328
  210. package/dist/structural-rollout-C4mabf87.d.ts +0 -446
  211. package/dist/supervise-7q9F5brx.d.ts +0 -379
  212. package/dist/types-BCoemcXU.d.ts +0 -802
  213. package/dist/types-BwoZWq-i.d.ts +0 -510
  214. package/dist/types-Cbp72qyu.d.ts +0 -491
  215. package/dist/types-CmYCMbFT.d.ts +0 -203
  216. package/dist/types-CvNwMzQt.d.ts +0 -957
  217. package/dist/worktree-fanout-WsOzt8qu.d.ts +0 -999
@@ -1,200 +0,0 @@
1
- import {
2
- agentImprovementTargetDigest,
3
- agentImprovementTargetInput,
4
- verifyAgentImprovementActivation,
5
- verifyAgentImprovementProposal
6
- } from "./chunk-FJI3EXU3.js";
7
- import {
8
- canonicalCandidateDigest,
9
- canonicalCandidateDocument,
10
- immutableCandidateValue,
11
- verifyCanonicalCandidateDocument
12
- } from "./chunk-SBTWKPVR.js";
13
-
14
- // src/intelligence/activation.ts
15
- import {
16
- agentImprovementActivationResultSchema,
17
- agentImprovementActivationSchema
18
- } from "@tangle-network/agent-interface";
19
- function createAgentImprovementActivationResult(transition, options) {
20
- const activation = verifyCanonicalCandidateDocument(
21
- agentImprovementActivationSchema.parse(transition.activation),
22
- "agent improvement activation"
23
- );
24
- assertTransitionInput(activation, transition);
25
- const result = agentImprovementActivationResultSchema.parse(
26
- canonicalCandidateDocument({
27
- kind: "agent-improvement-activation-result",
28
- idempotencyKey: activation.digest,
29
- attemptedAt: transition.attemptedAt,
30
- completedAt: options.completedAt,
31
- outcome: options.outcome
32
- }).value
33
- );
34
- assertResultAgainstActivation(activation, result);
35
- assertOutcomeDesiredState(
36
- activation,
37
- result,
38
- new Map(transition.targets.map((target) => [targetIdentity(target), target.desiredDigest]))
39
- );
40
- return immutableCandidateValue(result);
41
- }
42
- function verifyAgentImprovementActivationResult(input) {
43
- const proposal = verifyAgentImprovementProposal(input.proposal);
44
- const activation = verifyAgentImprovementActivation(input);
45
- const result = verifyCanonicalCandidateDocument(
46
- agentImprovementActivationResultSchema.parse(input.result),
47
- "agent improvement activation result"
48
- );
49
- assertResultAgainstActivation(activation, result);
50
- assertResultDesiredState(proposal, activation, result);
51
- return result;
52
- }
53
- async function executeAgentImprovementActivation(input, options) {
54
- const proposal = verifyAgentImprovementProposal(input.proposal);
55
- const activation = verifyAgentImprovementActivation(input);
56
- const experiment = proposal.evaluation.experiment;
57
- const targetArm = activation.intent === "activate-candidate" ? "candidate" : "baseline";
58
- const observedAt = (options.now ?? (() => /* @__PURE__ */ new Date()))().toISOString();
59
- const attemptedAt = Date.parse(observedAt) < Date.parse(activation.authorizedAt) ? activation.authorizedAt : observedAt;
60
- const transition = immutableCandidateValue({
61
- activation,
62
- candidateBundle: experiment.candidate,
63
- bundle: experiment[targetArm],
64
- targets: activation.targets.map((target) => ({
65
- ...target,
66
- desiredDigest: agentImprovementTargetDigest(experiment, targetArm, target.surface),
67
- desiredInput: agentImprovementTargetInput(experiment[targetArm], target.surface)
68
- })),
69
- attemptedAt,
70
- expired: Date.parse(attemptedAt) >= Date.parse(activation.expiresAt)
71
- });
72
- if (transition.expired) {
73
- if (!options.reconcile) {
74
- return uncertainActivationResult(transition, "RECONCILIATION_UNAVAILABLE");
75
- }
76
- let reconciled;
77
- try {
78
- reconciled = await options.reconcile(transition);
79
- } catch {
80
- return uncertainActivationResult(transition, "RECONCILIATION_THROW");
81
- }
82
- if (reconciled === void 0) {
83
- return createAgentImprovementActivationResult(transition, {
84
- completedAt: transition.attemptedAt,
85
- outcome: { status: "expired" }
86
- });
87
- }
88
- try {
89
- return verifyAgentImprovementActivationResult({ ...input, result: reconciled });
90
- } catch {
91
- return uncertainActivationResult(transition, "INVALID_RECONCILIATION");
92
- }
93
- }
94
- let rawResult;
95
- try {
96
- rawResult = await options.transition(transition);
97
- } catch {
98
- return uncertainActivationResult(transition, "TRANSITION_THROW");
99
- }
100
- try {
101
- return verifyAgentImprovementActivationResult({ ...input, result: rawResult });
102
- } catch {
103
- return uncertainActivationResult(transition, "INVALID_RESULT");
104
- }
105
- }
106
- function uncertainActivationResult(transition, code) {
107
- return createAgentImprovementActivationResult(transition, {
108
- completedAt: transition.attemptedAt,
109
- outcome: {
110
- status: "indeterminate",
111
- code,
112
- message: "The product transition did not return a trustworthy commit result."
113
- }
114
- });
115
- }
116
- function assertTransitionInput(activation, transition) {
117
- const authorized = targetMap(activation.targets);
118
- const planned = targetMap(transition.targets);
119
- const desiredInputsMatch = transition.targets.every(
120
- (target) => canonicalCandidateDigest(target.desiredInput) === canonicalCandidateDigest(agentImprovementTargetInput(transition.bundle, target.surface))
121
- );
122
- if (authorized.size !== planned.size || [...authorized.entries()].some(
123
- ([identity, target]) => planned.get(identity)?.expectedBaseDigest !== target.expectedBaseDigest
124
- ) || transition.expired !== Date.parse(transition.attemptedAt) >= Date.parse(activation.expiresAt) || transition.candidateBundle.digest !== activation.candidateBundleDigest || !desiredInputsMatch || activation.intent === "activate-candidate" && transition.bundle.digest !== transition.candidateBundle.digest) {
125
- throw new Error("activation transition does not match its authorization");
126
- }
127
- }
128
- function assertResultAgainstActivation(activation, result) {
129
- const attemptedAt = Date.parse(result.attemptedAt);
130
- const completedAt = Date.parse(result.completedAt);
131
- const expiresAt = Date.parse(activation.expiresAt);
132
- if (result.idempotencyKey !== activation.digest || attemptedAt < Date.parse(activation.authorizedAt) || completedAt < attemptedAt) {
133
- throw new Error("activation result does not bind its authorization");
134
- }
135
- const expired = attemptedAt >= expiresAt;
136
- if (result.outcome.status === "expired" && !expired || expired && !["expired", "indeterminate", "already-applied"].includes(result.outcome.status)) {
137
- throw new Error("activation result does not honor its authorization expiry");
138
- }
139
- if (!("targets" in result.outcome)) return;
140
- const authorized = targetMap(activation.targets);
141
- const observed = new Set(result.outcome.targets.map(targetIdentity));
142
- if (authorized.size !== observed.size || [...authorized.keys()].some((identity) => !observed.has(identity))) {
143
- throw new Error("activation result must cover every authorized target exactly once");
144
- }
145
- if (result.outcome.status === "applied" && result.outcome.targets.some(
146
- (target) => target.beforeDigest !== authorized.get(targetIdentity(target))?.expectedBaseDigest
147
- )) {
148
- throw new Error("applied activation did not start from its authorized base state");
149
- }
150
- }
151
- function assertResultDesiredState(proposal, activation, result) {
152
- if (!("targets" in result.outcome)) return;
153
- const experiment = proposal.evaluation.experiment;
154
- const targetArm = activation.intent === "activate-candidate" ? "candidate" : "baseline";
155
- const desired = new Map(
156
- activation.targets.map((target) => [
157
- targetIdentity(target),
158
- agentImprovementTargetDigest(experiment, targetArm, target.surface)
159
- ])
160
- );
161
- assertOutcomeDesiredState(activation, result, desired);
162
- }
163
- function assertOutcomeDesiredState(activation, result, desired) {
164
- if (!("targets" in result.outcome)) return;
165
- if (result.outcome.status === "applied") {
166
- if (result.outcome.targets.some(
167
- (target) => target.afterDigest !== desired.get(targetIdentity(target))
168
- )) {
169
- throw new Error("applied activation does not match the requested bundle");
170
- }
171
- return;
172
- }
173
- const allDesired = result.outcome.targets.every(
174
- (target) => target.currentDigest === desired.get(targetIdentity(target))
175
- );
176
- if (result.outcome.status === "already-applied") {
177
- if (!allDesired) throw new Error("already-applied activation is not at the requested state");
178
- return;
179
- }
180
- const authorized = targetMap(activation.targets);
181
- const hasStaleTarget = result.outcome.targets.some(
182
- (target) => target.currentDigest !== authorized.get(targetIdentity(target))?.expectedBaseDigest
183
- );
184
- if (allDesired || !hasStaleTarget) {
185
- throw new Error("activation conflict does not identify stale target state");
186
- }
187
- }
188
- function targetMap(targets) {
189
- return new Map(targets.map((target) => [targetIdentity(target), target]));
190
- }
191
- function targetIdentity(target) {
192
- return `${target.surface}\0${target.identity}`;
193
- }
194
-
195
- export {
196
- createAgentImprovementActivationResult,
197
- verifyAgentImprovementActivationResult,
198
- executeAgentImprovementActivation
199
- };
200
- //# sourceMappingURL=chunk-HAO4CXHP.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/intelligence/activation.ts"],"sourcesContent":["import type {\n AgentCandidateBundle,\n AgentImprovementActivation,\n AgentImprovementActivationOutcome,\n AgentImprovementActivationResult,\n AgentImprovementActivationTarget,\n AgentImprovementProposal,\n AgentImprovementReview,\n AgentImprovementSurface,\n Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport {\n agentImprovementActivationResultSchema,\n agentImprovementActivationSchema,\n} from '@tangle-network/agent-interface'\n\nimport {\n canonicalCandidateDigest,\n canonicalCandidateDocument,\n immutableCandidateValue,\n verifyCanonicalCandidateDocument,\n} from '../candidate-execution/digest'\nimport {\n verifyAgentImprovementActivation,\n verifyAgentImprovementProposal,\n} from './improvement-cycle'\nimport { agentImprovementTargetDigest, agentImprovementTargetInput } from './improvement-surfaces'\n\nexport interface CreateAgentImprovementActivationResultOptions {\n completedAt: string\n outcome: AgentImprovementActivationOutcome\n}\n\nexport interface AgentImprovementActivationTargetPlan extends AgentImprovementActivationTarget {\n desiredDigest: Sha256Digest\n /**\n * Exact measured input the product must apply to reach `desiredDigest`.\n * Transition surfaces such as code and knowledge are applied operations, so\n * their resulting state digest is not the digest of this input document.\n */\n desiredInput: unknown\n}\n\nexport interface AgentImprovementActivationTransitionInput {\n activation: AgentImprovementActivation\n candidateBundle: AgentCandidateBundle\n bundle: AgentCandidateBundle\n targets: [AgentImprovementActivationTargetPlan, ...AgentImprovementActivationTargetPlan[]]\n attemptedAt: string\n expired: boolean\n}\n\nexport interface AgentImprovementActivationResultStore {\n load(idempotencyKey: Sha256Digest): Promise<unknown | undefined>\n putIfAbsent(result: AgentImprovementActivationResult): Promise<unknown>\n}\n\n/**\n * Product-owned or Runtime-composed transition.\n *\n * Implementations resolve a stored result for `activation.digest`, compare\n * every target, and make the write durably idempotent. Co-located targets store\n * the all-or-none write with its result. Other targets throw when result\n * storage fails so a retry can reconcile it. Runtime never invokes this write\n * function after authorization expires.\n */\nexport type AgentImprovementActivationTransition = (\n input: AgentImprovementActivationTransitionInput,\n) => Promise<unknown>\n\n/**\n * Target-read-only check for a prior exact write.\n * It may persist recovered result metadata, but must not change an activation target.\n * Return undefined only when no target write can have committed.\n */\nexport type AgentImprovementActivationReconciliation = (\n input: AgentImprovementActivationTransitionInput,\n) => Promise<unknown | undefined>\n\nexport interface ExecuteAgentImprovementActivationInput {\n proposal: AgentImprovementProposal\n review: AgentImprovementReview\n activation: AgentImprovementActivation\n}\n\nexport interface ExecuteAgentImprovementActivationOptions {\n transition: AgentImprovementActivationTransition\n reconcile?: AgentImprovementActivationReconciliation\n now?: () => Date\n}\n\n/** Create the exact result a product stores in the same transaction as its target write. */\nexport function createAgentImprovementActivationResult(\n transition: AgentImprovementActivationTransitionInput,\n options: CreateAgentImprovementActivationResultOptions,\n): AgentImprovementActivationResult {\n const activation = verifyCanonicalCandidateDocument(\n agentImprovementActivationSchema.parse(transition.activation),\n 'agent improvement activation',\n )\n assertTransitionInput(activation, transition)\n const result = agentImprovementActivationResultSchema.parse(\n canonicalCandidateDocument<AgentImprovementActivationResult>({\n kind: 'agent-improvement-activation-result',\n idempotencyKey: activation.digest,\n attemptedAt: transition.attemptedAt,\n completedAt: options.completedAt,\n outcome: options.outcome,\n }).value,\n )\n assertResultAgainstActivation(activation, result)\n assertOutcomeDesiredState(\n activation,\n result,\n new Map(transition.targets.map((target) => [targetIdentity(target), target.desiredDigest])),\n )\n return immutableCandidateValue(result)\n}\n\n/**\n * Recompute one historical activation result against the exact measured proposal and authority.\n * The result records that attempt; it is not a query of the target's current state.\n */\nexport function verifyAgentImprovementActivationResult(input: {\n proposal: unknown\n review: unknown\n activation: unknown\n result: unknown\n}): AgentImprovementActivationResult {\n const proposal = verifyAgentImprovementProposal(input.proposal)\n const activation = verifyAgentImprovementActivation(input)\n const result = verifyCanonicalCandidateDocument(\n agentImprovementActivationResultSchema.parse(input.result),\n 'agent improvement activation result',\n )\n assertResultAgainstActivation(activation, result)\n assertResultDesiredState(proposal, activation, result)\n return result\n}\n\n/** Validate and execute one product-owned activation transition. */\nexport async function executeAgentImprovementActivation(\n input: ExecuteAgentImprovementActivationInput,\n options: ExecuteAgentImprovementActivationOptions,\n): Promise<AgentImprovementActivationResult> {\n const proposal = verifyAgentImprovementProposal(input.proposal)\n const activation = verifyAgentImprovementActivation(input)\n const experiment = proposal.evaluation.experiment\n const targetArm = activation.intent === 'activate-candidate' ? 'candidate' : 'baseline'\n const observedAt = (options.now ?? (() => new Date()))().toISOString()\n const attemptedAt =\n Date.parse(observedAt) < Date.parse(activation.authorizedAt)\n ? activation.authorizedAt\n : observedAt\n const transition = immutableCandidateValue<AgentImprovementActivationTransitionInput>({\n activation,\n candidateBundle: experiment.candidate,\n bundle: experiment[targetArm],\n targets: activation.targets.map((target) => ({\n ...target,\n desiredDigest: agentImprovementTargetDigest(experiment, targetArm, target.surface),\n desiredInput: agentImprovementTargetInput(experiment[targetArm], target.surface),\n })) as AgentImprovementActivationTransitionInput['targets'],\n attemptedAt,\n expired: Date.parse(attemptedAt) >= Date.parse(activation.expiresAt),\n })\n\n if (transition.expired) {\n if (!options.reconcile) {\n return uncertainActivationResult(transition, 'RECONCILIATION_UNAVAILABLE')\n }\n let reconciled: unknown\n try {\n reconciled = await options.reconcile(transition)\n } catch {\n return uncertainActivationResult(transition, 'RECONCILIATION_THROW')\n }\n if (reconciled === undefined) {\n return createAgentImprovementActivationResult(transition, {\n completedAt: transition.attemptedAt,\n outcome: { status: 'expired' },\n })\n }\n try {\n return verifyAgentImprovementActivationResult({ ...input, result: reconciled })\n } catch {\n return uncertainActivationResult(transition, 'INVALID_RECONCILIATION')\n }\n }\n\n let rawResult: unknown\n try {\n rawResult = await options.transition(transition)\n } catch {\n return uncertainActivationResult(transition, 'TRANSITION_THROW')\n }\n try {\n return verifyAgentImprovementActivationResult({ ...input, result: rawResult })\n } catch {\n return uncertainActivationResult(transition, 'INVALID_RESULT')\n }\n}\n\nfunction uncertainActivationResult(\n transition: AgentImprovementActivationTransitionInput,\n code: string,\n): AgentImprovementActivationResult {\n return createAgentImprovementActivationResult(transition, {\n completedAt: transition.attemptedAt,\n outcome: {\n status: 'indeterminate',\n code,\n message: 'The product transition did not return a trustworthy commit result.',\n },\n })\n}\n\nfunction assertTransitionInput(\n activation: AgentImprovementActivation,\n transition: AgentImprovementActivationTransitionInput,\n): void {\n const authorized = targetMap(activation.targets)\n const planned = targetMap(transition.targets)\n const desiredInputsMatch = transition.targets.every(\n (target) =>\n canonicalCandidateDigest(target.desiredInput) ===\n canonicalCandidateDigest(agentImprovementTargetInput(transition.bundle, target.surface)),\n )\n if (\n authorized.size !== planned.size ||\n [...authorized.entries()].some(\n ([identity, target]) =>\n planned.get(identity)?.expectedBaseDigest !== target.expectedBaseDigest,\n ) ||\n transition.expired !== Date.parse(transition.attemptedAt) >= Date.parse(activation.expiresAt) ||\n transition.candidateBundle.digest !== activation.candidateBundleDigest ||\n !desiredInputsMatch ||\n (activation.intent === 'activate-candidate' &&\n transition.bundle.digest !== transition.candidateBundle.digest)\n ) {\n throw new Error('activation transition does not match its authorization')\n }\n}\n\nfunction assertResultAgainstActivation(\n activation: AgentImprovementActivation,\n result: AgentImprovementActivationResult,\n): void {\n const attemptedAt = Date.parse(result.attemptedAt)\n const completedAt = Date.parse(result.completedAt)\n const expiresAt = Date.parse(activation.expiresAt)\n if (\n result.idempotencyKey !== activation.digest ||\n attemptedAt < Date.parse(activation.authorizedAt) ||\n completedAt < attemptedAt\n ) {\n throw new Error('activation result does not bind its authorization')\n }\n const expired = attemptedAt >= expiresAt\n if (\n (result.outcome.status === 'expired' && !expired) ||\n (expired && !['expired', 'indeterminate', 'already-applied'].includes(result.outcome.status))\n ) {\n throw new Error('activation result does not honor its authorization expiry')\n }\n if (!('targets' in result.outcome)) return\n const authorized = targetMap(activation.targets)\n const observed = new Set(result.outcome.targets.map(targetIdentity))\n if (\n authorized.size !== observed.size ||\n [...authorized.keys()].some((identity) => !observed.has(identity))\n ) {\n throw new Error('activation result must cover every authorized target exactly once')\n }\n if (\n result.outcome.status === 'applied' &&\n result.outcome.targets.some(\n (target) =>\n target.beforeDigest !== authorized.get(targetIdentity(target))?.expectedBaseDigest,\n )\n ) {\n throw new Error('applied activation did not start from its authorized base state')\n }\n}\n\nfunction assertResultDesiredState(\n proposal: AgentImprovementProposal,\n activation: AgentImprovementActivation,\n result: AgentImprovementActivationResult,\n): void {\n if (!('targets' in result.outcome)) return\n const experiment = proposal.evaluation.experiment\n const targetArm = activation.intent === 'activate-candidate' ? 'candidate' : 'baseline'\n const desired = new Map(\n activation.targets.map((target) => [\n targetIdentity(target),\n agentImprovementTargetDigest(experiment, targetArm, target.surface),\n ]),\n )\n assertOutcomeDesiredState(activation, result, desired)\n}\n\nfunction assertOutcomeDesiredState(\n activation: AgentImprovementActivation,\n result: AgentImprovementActivationResult,\n desired: ReadonlyMap<string, Sha256Digest>,\n): void {\n if (!('targets' in result.outcome)) return\n if (result.outcome.status === 'applied') {\n if (\n result.outcome.targets.some(\n (target) => target.afterDigest !== desired.get(targetIdentity(target)),\n )\n ) {\n throw new Error('applied activation does not match the requested bundle')\n }\n return\n }\n const allDesired = result.outcome.targets.every(\n (target) => target.currentDigest === desired.get(targetIdentity(target)),\n )\n if (result.outcome.status === 'already-applied') {\n if (!allDesired) throw new Error('already-applied activation is not at the requested state')\n return\n }\n const authorized = targetMap(activation.targets)\n const hasStaleTarget = result.outcome.targets.some(\n (target) => target.currentDigest !== authorized.get(targetIdentity(target))?.expectedBaseDigest,\n )\n if (allDesired || !hasStaleTarget) {\n throw new Error('activation conflict does not identify stale target state')\n }\n}\n\nfunction targetMap<T extends { surface: AgentImprovementSurface; identity: string }>(\n targets: readonly T[],\n): Map<string, T> {\n return new Map(targets.map((target) => [targetIdentity(target), target]))\n}\n\nfunction targetIdentity(target: { surface: AgentImprovementSurface; identity: string }): string {\n return `${target.surface}\\u0000${target.identity}`\n}\n"],"mappings":";;;;;;;;;;;;;;AAWA;AAAA,EACE;AAAA,EACA;AAAA,OACK;AA8EA,SAAS,uCACd,YACA,SACkC;AAClC,QAAM,aAAa;AAAA,IACjB,iCAAiC,MAAM,WAAW,UAAU;AAAA,IAC5D;AAAA,EACF;AACA,wBAAsB,YAAY,UAAU;AAC5C,QAAM,SAAS,uCAAuC;AAAA,IACpD,2BAA6D;AAAA,MAC3D,MAAM;AAAA,MACN,gBAAgB,WAAW;AAAA,MAC3B,aAAa,WAAW;AAAA,MACxB,aAAa,QAAQ;AAAA,MACrB,SAAS,QAAQ;AAAA,IACnB,CAAC,EAAE;AAAA,EACL;AACA,gCAA8B,YAAY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MAAM,GAAG,MAAM,CAAC,CAAC;AAC1E;AAEA,SAAS,eAAe,QAAwE;AAC9F,SAAO,GAAG,OAAO,OAAO,KAAS,OAAO,QAAQ;AAClD;","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