@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,680 +0,0 @@
1
- import {
2
- sealAgentCandidateBundle
3
- } from "./chunk-B7K7V22Y.js";
4
- import {
5
- RecoveryAgentCandidateTraceStore,
6
- applyExactAgentProfileDiff,
7
- assertPreparedCandidateIntegrity,
8
- assertRecoveryMatchesStaged,
9
- assertTerminalAllowedInPhase,
10
- assertTerminalMatchesClaim,
11
- assertTerminalMatchesStaged,
12
- beginPreparedCandidateDisposal,
13
- candidateClaimFileInternals,
14
- candidateCleanupDeadline,
15
- candidateCleanupTimeout,
16
- canonicalCandidateBytes,
17
- consumePreparedCandidateExecution,
18
- embeddedCandidateArtifact,
19
- freezeGenericAgentCandidateProfile,
20
- parseExactAgentProfile,
21
- parseExactAgentProfileDiff,
22
- parseExactCandidateProfile,
23
- persistCandidateModelSettlementEvidence,
24
- persistCandidateOutputArtifact,
25
- readVerifiedArtifact,
26
- recoveredTerminalRecord,
27
- rejectedFinish,
28
- rejectedStage,
29
- requireStagedTerminal,
30
- sealAgentCandidateExecutorStopAcknowledgement,
31
- sealAgentCandidateModelSettlement,
32
- sealTerminalDigest,
33
- terminalRecord,
34
- withinCandidateCleanupDeadline
35
- } from "./chunk-SBTWKPVR.js";
36
-
37
- // src/candidate-execution/builder.ts
38
- import { verifyCodeSurface } from "@tangle-network/agent-eval/campaign";
39
- function buildAgentCandidateBundle(input) {
40
- const bundle = {
41
- kind: "agent-candidate-bundle",
42
- digestAlgorithm: "rfc8785-sha256",
43
- profile: compileCandidateProfile(input.profile),
44
- code: compileCandidateCode(input.code),
45
- execution: input.execution,
46
- ...input.knowledge !== void 0 ? { knowledge: input.knowledge } : {},
47
- memory: input.memory
48
- };
49
- return sealAgentCandidateBundle(bundle);
50
- }
51
- function compileCandidateProfile(source) {
52
- if (source.kind === "candidate-profile") {
53
- return parseExactCandidateProfile(source.profile);
54
- }
55
- if (source.kind === "profile") {
56
- return freezeGenericAgentCandidateProfile(source.profile);
57
- }
58
- if (source.kind !== "profile-diffs") {
59
- throw new Error(
60
- `unsupported candidate profile source: ${String(source.kind)}`
61
- );
62
- }
63
- if (source.diffs.length === 0) {
64
- throw new Error("profile-diffs source requires at least one AgentProfileDiff");
65
- }
66
- let profile = parseExactAgentProfile(source.base, "base profile");
67
- for (const [index, inputDiff] of source.diffs.entries()) {
68
- const diff = parseExactAgentProfileDiff(inputDiff, `profile diff ${index}`);
69
- profile = applyExactAgentProfileDiff(profile, diff, `profile diff ${index}`);
70
- }
71
- return freezeGenericAgentCandidateProfile(profile);
72
- }
73
- function compileCandidateCode(source) {
74
- if (source.kind === "disabled" || source.kind === "no-op") return source;
75
- if (source.kind !== "code-surface") {
76
- throw new Error(
77
- `unsupported candidate code source: ${String(source.kind)}`
78
- );
79
- }
80
- const verified = verifyCodeSurface(source.surface, source.worktreeDir);
81
- const patch = embeddedCandidateArtifact(verified.patchBytes);
82
- if (patch.sha256 !== source.surface.patch.sha256 || patch.byteLength !== source.surface.patch.byteLength) {
83
- throw new Error("verified CodeSurface patch bytes do not match its content identity");
84
- }
85
- return {
86
- kind: "git-patch",
87
- repository: source.repository,
88
- baseCommit: source.surface.baseCommit,
89
- baseTree: source.surface.baseTree,
90
- candidateTree: source.surface.candidateTree,
91
- patch: { format: "git-diff-binary", artifact: patch }
92
- };
93
- }
94
-
95
- // src/candidate-execution/claim-file-store.ts
96
- import { randomUUID } from "crypto";
97
- import { linkSync } from "fs";
98
- import { mkdir, open, unlink } from "fs/promises";
99
- import { join } from "path";
100
- var {
101
- assertExpiredLease,
102
- assertLease,
103
- assertSameSlot,
104
- assertUnexpiredLease,
105
- attemptRecord,
106
- claimSlot,
107
- leaseDigest,
108
- newLease,
109
- readClaim,
110
- readClaimIfPresent,
111
- readTerminal,
112
- readTerminalIfPresent,
113
- readTransitionIfPresent,
114
- rejectedExistingClaim,
115
- rejectedRetry,
116
- retryRejection,
117
- sealAttemptRef,
118
- sealClaim,
119
- sealLease
120
- } = candidateClaimFileInternals;
121
- var FileAgentCandidateExecutionClaimStore = class {
122
- directory;
123
- now;
124
- constructor(options) {
125
- if (options.directory.length === 0) {
126
- throw new Error("candidate execution claim directory must not be empty");
127
- }
128
- this.directory = options.directory;
129
- this.now = options.now ?? Date.now;
130
- }
131
- async tryClaim(requested) {
132
- const claim = sealClaim(requested);
133
- await mkdir(this.directory, { recursive: true });
134
- const claimPath = this.claimPath(claim);
135
- const existing = await readClaimIfPresent(claimPath);
136
- if (existing) {
137
- assertSameSlot(existing.claim, claim, claimPath);
138
- return rejectedExistingClaim(existing.claim, claim);
139
- }
140
- assertUnexpiredLease(claim.leaseExpiresAtMs, this.now());
141
- const retryFailure = await this.retryFailure(claim);
142
- if (retryFailure) return rejectedRetry(claim, retryFailure);
143
- const lease = newLease(claim);
144
- const acquired = await writeRecordIfAbsent(this.directory, claimPath, {
145
- ...claim,
146
- phase: "claimed",
147
- leaseDigest: leaseDigest(lease)
148
- });
149
- if (acquired) return Object.freeze({ acquired: true, claim, lease });
150
- const winner = await readClaim(claimPath);
151
- assertSameSlot(winner.claim, claim, claimPath);
152
- return rejectedExistingClaim(winner.claim, claim);
153
- }
154
- async getAttempt(requestedAttempt) {
155
- return await this.storedAttempt(sealAttemptRef(requestedAttempt));
156
- }
157
- async markCandidateMayRun(requestedLease) {
158
- const lease = sealLease(requestedLease);
159
- const claimPath = this.claimPath(lease);
160
- const stored = await readClaim(claimPath);
161
- assertSameSlot(stored.claim, lease, claimPath);
162
- assertLease(stored.leaseDigest, stored.claim.leaseExpiresAtMs, lease);
163
- const state = await this.transitionState(stored.claim);
164
- if (state.phase === "candidate-may-run") {
165
- return Object.freeze({ marked: false, phase: "candidate-may-run" });
166
- }
167
- if (state.staged) {
168
- throw new Error("candidate execution terminal was staged before candidate-may-run phase");
169
- }
170
- assertUnexpiredLease(stored.claim.leaseExpiresAtMs, this.now());
171
- const marked = await writeRecordIfAbsent(
172
- this.directory,
173
- this.transitionPath(stored.claim, 1),
174
- {
175
- kind: "candidate-execution-phase",
176
- executionId: stored.claim.executionId,
177
- attempt: stored.claim.attempt,
178
- executionPlanDigest: stored.claim.executionPlanDigest,
179
- phase: "candidate-may-run"
180
- },
181
- this.ownerPublication(stored.claim)
182
- );
183
- if (marked) return Object.freeze({ marked: true, phase: "candidate-may-run" });
184
- const winner = await this.transitionState(stored.claim);
185
- if (winner.phase === "candidate-may-run") {
186
- return Object.freeze({ marked: false, phase: "candidate-may-run" });
187
- }
188
- throw new Error("candidate execution terminal was staged before candidate-may-run phase");
189
- }
190
- async stageTerminal(requestedLease, result) {
191
- const lease = sealLease(requestedLease);
192
- const claimPath = this.claimPath(lease);
193
- const stored = await readClaim(claimPath);
194
- assertSameSlot(stored.claim, lease, claimPath);
195
- assertLease(stored.leaseDigest, stored.claim.leaseExpiresAtMs, lease);
196
- const terminal = terminalRecord(stored.claim, result);
197
- const state = await this.transitionState(stored.claim);
198
- if (state.staged) return rejectedStage(state.staged, terminal);
199
- assertTerminalAllowedInPhase(state.phase, terminal);
200
- assertUnexpiredLease(stored.claim.leaseExpiresAtMs, this.now());
201
- const transition = state.phase === "claimed" ? 1 : 2;
202
- const staged = await writeRecordIfAbsent(
203
- this.directory,
204
- this.transitionPath(stored.claim, transition),
205
- {
206
- kind: "candidate-execution-pending-terminal",
207
- terminal
208
- },
209
- this.ownerPublication(stored.claim)
210
- );
211
- if (staged) return Object.freeze({ staged: true, terminal });
212
- const winner = await this.transitionState(stored.claim);
213
- if (!winner.staged) {
214
- throw new Error("candidate execution phase transition won while staging terminal");
215
- }
216
- return rejectedStage(winner.staged, terminal);
217
- }
218
- async finish(requestedLease, requestedTerminalDigest) {
219
- const lease = sealLease(requestedLease);
220
- const terminalDigest = sealTerminalDigest(requestedTerminalDigest);
221
- const claimPath = this.claimPath(lease);
222
- const stored = await readClaim(claimPath);
223
- assertSameSlot(stored.claim, lease, claimPath);
224
- assertLease(stored.leaseDigest, stored.claim.leaseExpiresAtMs, lease);
225
- const state = await this.transitionState(stored.claim);
226
- const staged = requireStagedTerminal(state.staged, terminalDigest);
227
- const terminalPath = this.terminalPath(lease);
228
- const existing = await readTerminalIfPresent(terminalPath);
229
- if (existing) {
230
- assertTerminalMatchesClaim(existing, stored.claim, terminalPath);
231
- assertTerminalMatchesStaged(existing, staged, terminalPath);
232
- return rejectedFinish(existing, terminalDigest);
233
- }
234
- assertUnexpiredLease(stored.claim.leaseExpiresAtMs, this.now());
235
- const finished = await writeRecordIfAbsent(
236
- this.directory,
237
- terminalPath,
238
- {
239
- terminal: staged
240
- },
241
- this.ownerPublication(stored.claim)
242
- );
243
- if (finished) return Object.freeze({ finished: true, terminal: staged });
244
- const winner = await readTerminal(terminalPath);
245
- assertSameSlot(winner, lease, terminalPath);
246
- assertTerminalMatchesClaim(winner, stored.claim, terminalPath);
247
- assertTerminalMatchesStaged(winner, staged, terminalPath);
248
- return rejectedFinish(winner, terminalDigest);
249
- }
250
- async recoverExpired(requestedAttempt, evidence) {
251
- const attempt = sealAttemptRef(requestedAttempt);
252
- const record = await this.storedAttempt(attempt);
253
- if (!record) throw new Error("candidate execution recovery does not name an acquired attempt");
254
- const recovered = recoveredTerminalRecord(record.claim, record.phase, evidence);
255
- if (record.staged) assertRecoveryMatchesStaged(record.staged, recovered);
256
- const requestedDigest = record.staged?.terminalDigest ?? recovered.terminalDigest;
257
- if (record.terminal) return rejectedFinish(record.terminal, requestedDigest);
258
- assertExpiredLease(record.claim.leaseExpiresAtMs, this.now());
259
- let staged = record.staged;
260
- if (!staged) {
261
- const transition = record.phase === "claimed" ? 1 : 2;
262
- const didStage = await writeRecordIfAbsent(
263
- this.directory,
264
- this.transitionPath(record.claim, transition),
265
- {
266
- kind: "candidate-execution-pending-terminal",
267
- terminal: recovered
268
- }
269
- );
270
- if (didStage) {
271
- staged = recovered;
272
- } else {
273
- const winner2 = await this.transitionState(record.claim);
274
- if (!winner2.staged) {
275
- throw new Error(
276
- "candidate execution recovery lost terminal staging to a phase transition"
277
- );
278
- }
279
- assertRecoveryMatchesStaged(winner2.staged, recovered);
280
- staged = winner2.staged;
281
- }
282
- }
283
- const terminalPath = this.terminalPath(attempt);
284
- const didFinish = await writeRecordIfAbsent(this.directory, terminalPath, {
285
- terminal: staged
286
- });
287
- if (didFinish) return Object.freeze({ finished: true, terminal: staged });
288
- const winner = await readTerminal(terminalPath);
289
- assertSameSlot(winner, attempt, terminalPath);
290
- assertTerminalMatchesClaim(winner, record.claim, terminalPath);
291
- assertTerminalMatchesStaged(winner, staged, terminalPath);
292
- return rejectedFinish(winner, staged.terminalDigest);
293
- }
294
- async storedAttempt(claim) {
295
- const claimPath = this.claimPath(claim);
296
- const stored = await readClaimIfPresent(claimPath);
297
- if (!stored) return void 0;
298
- assertSameSlot(stored.claim, claim, claimPath);
299
- const state = await this.transitionState(stored.claim);
300
- const terminalPath = this.terminalPath(claim);
301
- const terminal = await readTerminalIfPresent(terminalPath);
302
- if (terminal) {
303
- assertTerminalMatchesClaim(terminal, stored.claim, terminalPath);
304
- if (!state.staged) {
305
- throw new Error(
306
- `candidate execution terminal record at ${terminalPath} has no staged outbox`
307
- );
308
- }
309
- assertTerminalMatchesStaged(terminal, state.staged, terminalPath);
310
- }
311
- return attemptRecord(stored.claim, state.phase, state.staged, terminal);
312
- }
313
- async transitionState(claim) {
314
- const firstPath = this.transitionPath(claim, 1);
315
- const first = await readTransitionIfPresent(firstPath, claim);
316
- if (!first) return { phase: "claimed" };
317
- if (first.kind === "pending") return { phase: "claimed", staged: first.terminal };
318
- const secondPath = this.transitionPath(claim, 2);
319
- const second = await readTransitionIfPresent(secondPath, claim);
320
- if (!second) return { phase: "candidate-may-run" };
321
- if (second.kind !== "pending") {
322
- throw new Error(`candidate execution transition at ${secondPath} repeats the phase marker`);
323
- }
324
- return { phase: "candidate-may-run", staged: second.terminal };
325
- }
326
- async retryFailure(claim) {
327
- if (claim.attempt === 1) return void 0;
328
- return retryRejection(
329
- claim,
330
- await this.storedAttempt({
331
- executionId: claim.executionId,
332
- attempt: claim.attempt - 1
333
- })
334
- );
335
- }
336
- ownerPublication(claim) {
337
- return {
338
- authorizePublish: () => {
339
- assertUnexpiredLease(claim.leaseExpiresAtMs, this.now());
340
- return true;
341
- }
342
- };
343
- }
344
- claimPath(claim) {
345
- return join(this.directory, `${claimSlot(claim)}.claim.json`);
346
- }
347
- terminalPath(claim) {
348
- return join(this.directory, `${claimSlot(claim)}.terminal.json`);
349
- }
350
- transitionPath(claim, ordinal) {
351
- return join(this.directory, `${claimSlot(claim)}.transition-${ordinal}.json`);
352
- }
353
- };
354
- async function writeRecordIfAbsent(directory, destination, record, options = {}) {
355
- const temporaryPath = join(directory, `.candidate-execution-${process.pid}-${randomUUID()}.tmp`);
356
- const handle = await open(temporaryPath, "wx", 384);
357
- try {
358
- await handle.writeFile(
359
- Buffer.concat([Buffer.from(canonicalCandidateBytes(record)), Buffer.from("\n")])
360
- );
361
- await handle.sync();
362
- } finally {
363
- await handle.close();
364
- }
365
- let written = false;
366
- try {
367
- if (options.authorizePublish && options.authorizePublish() !== true) {
368
- throw new Error("candidate execution record publication was not authorized");
369
- }
370
- linkSync(temporaryPath, destination);
371
- written = true;
372
- await syncDirectory(directory);
373
- } catch (error) {
374
- if (!isNodeError(error, "EEXIST")) throw error;
375
- } finally {
376
- await unlink(temporaryPath).catch((error) => {
377
- if (!isNodeError(error, "ENOENT")) throw error;
378
- });
379
- }
380
- return written;
381
- }
382
- async function syncDirectory(directory) {
383
- const handle = await open(directory, "r");
384
- try {
385
- await handle.sync();
386
- } finally {
387
- await handle.close();
388
- }
389
- }
390
- function isNodeError(error, code) {
391
- return error !== null && typeof error === "object" && "code" in error && error.code === code;
392
- }
393
-
394
- // src/candidate-execution/dispose.ts
395
- async function disposePreparedAgentCandidateExecution(prepared, options = {}) {
396
- const initialState = assertPreparedCandidateIntegrity(prepared);
397
- const cleanupTimeoutMs = options.cleanupTimeoutMs ?? initialState.cleanupTimeoutMs;
398
- if (cleanupTimeoutMs > initialState.cleanupTimeoutMs) {
399
- throw new Error("disposal cleanup timeout exceeds the frozen preparation bound");
400
- }
401
- const cleanupDeadlineAtMs = candidateCleanupDeadline(cleanupTimeoutMs);
402
- const state = beginPreparedCandidateDisposal(prepared);
403
- const cleanup = [];
404
- if (state.memory.mode === "isolated") {
405
- const reservation = state.memoryReservation;
406
- if (!reservation) throw new Error("isolated memory reservation is missing");
407
- cleanup.push(
408
- withinCandidateCleanupDeadline(
409
- async () => {
410
- const closed = await state.ports.memory.close({
411
- executionId: state.executionId,
412
- preparationId: reservation.preparationId,
413
- accessDigest: reservation.accessDigest,
414
- effectiveNamespace: reservation.effectiveNamespace,
415
- reason: "abandoned"
416
- });
417
- if (closed.closed !== true || Object.keys(closed).some((key) => key !== "closed")) {
418
- throw new Error("abandoned isolated memory access did not acknowledge closure");
419
- }
420
- },
421
- cleanupDeadlineAtMs,
422
- "isolated memory disposal"
423
- )
424
- );
425
- }
426
- cleanup.push(
427
- withinCandidateCleanupDeadline(
428
- async () => {
429
- const settlement = sealAgentCandidateModelSettlement(
430
- await state.ports.models.settleGrant({
431
- executionId: state.executionId,
432
- preparationId: state.preparationId,
433
- grantDigest: state.modelReservation.digest,
434
- resolved: state.resolvedModel,
435
- reason: "abandoned"
436
- }),
437
- {
438
- preparationId: state.preparationId,
439
- grantDigest: state.modelReservation.digest,
440
- model: state.resolvedModel.model
441
- }
442
- );
443
- if (settlement.usage.modelCalls !== 0) {
444
- throw new Error("unexecuted model reservation unexpectedly contains calls");
445
- }
446
- },
447
- cleanupDeadlineAtMs,
448
- "model reservation disposal"
449
- )
450
- );
451
- const results = await Promise.allSettled(cleanup);
452
- const failures = results.filter((result) => result.status === "rejected").map((result) => result.reason);
453
- if (failures.length > 0) {
454
- consumePreparedCandidateExecution(prepared, "disposal-failed");
455
- throw new AggregateError(failures, "candidate preparation disposal failed");
456
- }
457
- consumePreparedCandidateExecution(prepared, "disposed");
458
- return Object.freeze({ disposed: true });
459
- }
460
-
461
- // src/candidate-execution/recover.ts
462
- import {
463
- agentCandidateExecutionPlanMaterialSchema,
464
- agentCandidateMaterializationReceiptSchema
465
- } from "@tangle-network/agent-interface";
466
- async function recoverExpiredAgentCandidateExecution(options) {
467
- const record = await options.claimStore.getAttempt(options.attempt);
468
- if (!record) throw new Error("candidate execution recovery attempt is missing");
469
- if (record.terminal) {
470
- return Object.freeze({ finished: false, terminal: record.terminal, exactReplay: true });
471
- }
472
- const cleanupTimeoutMs = candidateCleanupTimeout(
473
- options.cleanupTimeoutMs ?? record.claim.cleanup.cleanupTimeoutMs
474
- );
475
- if (cleanupTimeoutMs > record.claim.cleanup.cleanupTimeoutMs) {
476
- throw new Error("recovery cleanup timeout exceeds the frozen preparation bound");
477
- }
478
- const now = options.now ?? Date.now;
479
- if (now() < record.claim.leaseExpiresAtMs) {
480
- throw new Error("candidate execution lease has not expired");
481
- }
482
- const cleanupDeadlineAtMs = candidateCleanupDeadline(cleanupTimeoutMs);
483
- const recoveryTraceStore = new RecoveryAgentCandidateTraceStore(options.traceStore);
484
- const preparation = withinCandidateCleanupDeadline(
485
- () => readRecoveryPreparation(record.claim, options.outputArtifacts),
486
- cleanupDeadlineAtMs,
487
- "expired candidate preparation evidence read"
488
- );
489
- const processClosure = withinCandidateCleanupDeadline(
490
- async (cleanupSignal) => {
491
- const stopped = await options.executor.stop(
492
- {
493
- executionId: record.claim.executionId,
494
- executionPlanDigest: record.claim.executionPlanDigest
495
- },
496
- {
497
- traceStore: recoveryTraceStore,
498
- reason: "failed",
499
- signal: cleanupSignal,
500
- deadlineAtMs: cleanupDeadlineAtMs
501
- }
502
- );
503
- sealAgentCandidateExecutorStopAcknowledgement(stopped);
504
- if (options.executor.dispose) {
505
- const disposed = await options.executor.dispose(
506
- {
507
- executionId: record.claim.executionId,
508
- executionPlanDigest: record.claim.executionPlanDigest
509
- },
510
- { signal: cleanupSignal }
511
- );
512
- if (disposed.disposed !== true || Object.keys(disposed).some((key) => key !== "disposed")) {
513
- throw new Error("expired candidate executor did not acknowledge resource disposal");
514
- }
515
- }
516
- return { stopped: true };
517
- },
518
- cleanupDeadlineAtMs,
519
- "expired candidate process termination"
520
- );
521
- const modelClosure = withinCandidateCleanupDeadline(
522
- async () => sealAgentCandidateModelSettlement(
523
- await options.ports.models.settleGrant({
524
- executionId: record.claim.executionId,
525
- preparationId: record.claim.cleanup.preparationId,
526
- grantDigest: record.claim.cleanup.modelGrantDigest,
527
- resolved: record.claim.cleanup.resolvedModel,
528
- reason: "failed"
529
- }),
530
- {
531
- preparationId: record.claim.cleanup.preparationId,
532
- grantDigest: record.claim.cleanup.modelGrantDigest,
533
- model: record.claim.cleanup.resolvedModel.model
534
- }
535
- ),
536
- cleanupDeadlineAtMs,
537
- "expired candidate model settlement"
538
- );
539
- const memoryClosure = record.claim.cleanup.memory ? withinCandidateCleanupDeadline(
540
- async () => {
541
- const memory2 = record.claim.cleanup.memory;
542
- if (!memory2) throw new Error("expired candidate memory handle is missing");
543
- const closed = await options.ports.memory.close({
544
- executionId: record.claim.executionId,
545
- preparationId: record.claim.cleanup.preparationId,
546
- accessDigest: memory2.accessDigest,
547
- effectiveNamespace: memory2.effectiveNamespace,
548
- reason: "failed"
549
- });
550
- if (closed.closed !== true || Object.keys(closed).some((key) => key !== "closed")) {
551
- throw new Error("expired candidate memory did not acknowledge closure");
552
- }
553
- return { closed: true };
554
- },
555
- cleanupDeadlineAtMs,
556
- "expired candidate memory closure"
557
- ) : void 0;
558
- const closureOutcomes = Promise.allSettled([
559
- modelClosure,
560
- memoryClosure ?? Promise.resolve(void 0)
561
- ]);
562
- const [preparationOutcome, processOutcome] = await Promise.allSettled([
563
- preparation,
564
- processClosure
565
- ]);
566
- const failures = [preparationOutcome, processOutcome].filter((outcome) => outcome.status === "rejected").map((outcome) => outcome.reason);
567
- const [modelOutcome, memoryOutcome] = await closureOutcomes;
568
- for (const outcome of [modelOutcome, memoryOutcome]) {
569
- if (outcome.status === "rejected") failures.push(outcome.reason);
570
- }
571
- if (failures.length > 0) {
572
- throw new AggregateError(failures, "expired candidate cleanup could not be proven");
573
- }
574
- if (modelOutcome.status !== "fulfilled") {
575
- throw new Error("expired candidate model settlement was not recovered");
576
- }
577
- const model = modelOutcome.value;
578
- const modelSettlement = await withinCandidateCleanupDeadline(
579
- () => persistCandidateModelSettlementEvidence(
580
- {
581
- executionId: record.claim.executionId,
582
- executionPlanDigest: record.claim.executionPlanDigest,
583
- resolvedModel: record.claim.cleanup.resolvedModel
584
- },
585
- model,
586
- options.outputArtifacts
587
- ),
588
- cleanupDeadlineAtMs,
589
- "expired candidate model-settlement persistence"
590
- );
591
- const failureClass = record.phase === "claimed" && model.usage.modelCalls === 0 ? "pre-model-infrastructure" : "unknown";
592
- const failureEvidence = await withinCandidateCleanupDeadline(
593
- () => persistCandidateOutputArtifact(options.outputArtifacts, {
594
- executionId: record.claim.executionId,
595
- purpose: "failure-evidence",
596
- bytes: canonicalCandidateBytes({
597
- kind: "agent-candidate-recovery-failure",
598
- executionId: record.claim.executionId,
599
- attempt: record.claim.attempt,
600
- bundleDigest: record.claim.bundleDigest,
601
- executionPlanDigest: record.claim.executionPlanDigest,
602
- materializationReceiptDigest: record.claim.preparationEvidence.materializationReceipt.sha256,
603
- failureClass,
604
- processStopped: true,
605
- modelSettlementDigest: modelSettlement.digest,
606
- memoryClosed: record.claim.cleanup.memory !== void 0
607
- })
608
- }),
609
- cleanupDeadlineAtMs,
610
- "expired candidate failure-evidence persistence"
611
- );
612
- const memory = record.claim.cleanup.memory;
613
- return await options.claimStore.recoverExpired(options.attempt, {
614
- failureClass,
615
- usage: model.usage,
616
- modelSettlement: modelSettlement.artifact,
617
- failureEvidence,
618
- process: {
619
- stopped: true,
620
- executionPlanDigest: record.claim.executionPlanDigest
621
- },
622
- model: {
623
- closed: true,
624
- preparationId: record.claim.cleanup.preparationId,
625
- grantDigest: record.claim.cleanup.modelGrantDigest
626
- },
627
- ...memory ? {
628
- memory: {
629
- closed: true,
630
- preparationId: record.claim.cleanup.preparationId,
631
- accessDigest: memory.accessDigest,
632
- effectiveNamespace: memory.effectiveNamespace
633
- }
634
- } : {}
635
- });
636
- }
637
- async function readRecoveryPreparation(claim, artifacts) {
638
- const [planBytes, receiptBytes] = await Promise.all([
639
- readVerifiedArtifact(claim.preparationEvidence.executionPlan, artifacts),
640
- readVerifiedArtifact(claim.preparationEvidence.materializationReceipt, artifacts)
641
- ]);
642
- const plan = agentCandidateExecutionPlanMaterialSchema.parse(
643
- parseCanonicalBytes(planBytes, "plan")
644
- );
645
- if (claim.preparationEvidence.executionPlan.sha256 !== claim.executionPlanDigest) {
646
- throw new Error("recovery execution plan artifact does not match the claimed digest");
647
- }
648
- const receiptMaterial = parseCanonicalBytes(receiptBytes, "materialization receipt");
649
- const receipt = agentCandidateMaterializationReceiptSchema.parse({
650
- ...receiptMaterial,
651
- digest: claim.preparationEvidence.materializationReceipt.sha256
652
- });
653
- if (receipt.bundleDigest !== claim.bundleDigest || receipt.executionPlan.digest !== claim.executionPlanDigest || plan.runCell.bundleDigest !== claim.bundleDigest || plan.executionId !== claim.executionId) {
654
- throw new Error("recovery preparation evidence does not match the durable claim");
655
- }
656
- return { plan, receipt };
657
- }
658
- function parseCanonicalBytes(bytes, label) {
659
- let parsed;
660
- try {
661
- parsed = JSON.parse(Buffer.from(bytes).toString("utf8"));
662
- } catch (error) {
663
- throw new Error(`candidate recovery ${label} is not JSON`, { cause: error });
664
- }
665
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
666
- throw new Error(`candidate recovery ${label} must be an object`);
667
- }
668
- if (!Buffer.from(canonicalCandidateBytes(parsed)).equals(Buffer.from(bytes))) {
669
- throw new Error(`candidate recovery ${label} bytes are not canonical`);
670
- }
671
- return parsed;
672
- }
673
-
674
- export {
675
- buildAgentCandidateBundle,
676
- FileAgentCandidateExecutionClaimStore,
677
- disposePreparedAgentCandidateExecution,
678
- recoverExpiredAgentCandidateExecution
679
- };
680
- //# sourceMappingURL=chunk-SNSMRT6H.js.map