@abelxiaoxing/cadence 1.8.4 → 2.0.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 (202) hide show
  1. package/README.md +324 -117
  2. package/THIRD_PARTY_NOTICES.md +15 -0
  3. package/agents/design-explorer.md +14 -18
  4. package/agents/diagnosis-worker.md +14 -14
  5. package/agents/implementation-worker.md +16 -17
  6. package/config/workflow-task.example.json +7 -0
  7. package/docs/remote-access.md +60 -0
  8. package/docs/reuse-and-distribution.md +44 -0
  9. package/docs/service-management.md +108 -0
  10. package/licenses/bundled-web.txt +6245 -0
  11. package/licenses/pi-web-ui-MIT.txt +21 -0
  12. package/licenses/pi-web-ui-reuse.md +22 -0
  13. package/package.json +92 -20
  14. package/src/index.ts +21 -1802
  15. package/src/native-build.ts +6 -0
  16. package/src/native-client.ts +103 -0
  17. package/src/native-export.ts +58 -0
  18. package/src/native-history.ts +359 -0
  19. package/src/operator-cli.mjs +453 -1937
  20. package/src/plan-proposal.ts +87 -0
  21. package/src/sdk-worker.mjs +549 -0
  22. package/src/service/contracts/active.ts +82 -0
  23. package/src/service/contracts/budget.ts +148 -0
  24. package/src/service/contracts/build.ts +67 -0
  25. package/src/service/contracts/capture.ts +48 -0
  26. package/src/service/contracts/core.ts +33 -0
  27. package/src/service/contracts/current.ts +261 -0
  28. package/src/service/contracts/domain.ts +68 -0
  29. package/src/service/contracts/history.ts +2245 -0
  30. package/src/service/contracts/models.ts +139 -0
  31. package/src/service/coordination.ts +862 -0
  32. package/src/service/private-files.ts +204 -0
  33. package/src/service-cli.mjs +5592 -0
  34. package/src/service-client.ts +747 -0
  35. package/src/service-contract.ts +245 -0
  36. package/src/service-host.mjs +22382 -0
  37. package/src/service-http-client.ts +425 -0
  38. package/src/service-wire.ts +372 -0
  39. package/src/task-shell.ts +1045 -0
  40. package/src/task-store.ts +479 -0
  41. package/src/task-types.ts +184 -0
  42. package/src/verification-diagnostics.ts +29 -72
  43. package/src/worker-capture.mjs +1197 -0
  44. package/src/worker-public.mjs +1753 -0
  45. package/src/worker-redaction.mjs +608 -0
  46. package/src/worker-tools.mjs +202 -0
  47. package/web/dist/assets/KaTeX_AMS-Regular.ttf +0 -0
  48. package/web/dist/assets/KaTeX_AMS-Regular.woff +0 -0
  49. package/web/dist/assets/KaTeX_AMS-Regular.woff2 +0 -0
  50. package/web/dist/assets/KaTeX_Caligraphic-Bold.ttf +0 -0
  51. package/web/dist/assets/KaTeX_Caligraphic-Bold.woff +0 -0
  52. package/web/dist/assets/KaTeX_Caligraphic-Bold.woff2 +0 -0
  53. package/web/dist/assets/KaTeX_Caligraphic-Regular.ttf +0 -0
  54. package/web/dist/assets/KaTeX_Caligraphic-Regular.woff +0 -0
  55. package/web/dist/assets/KaTeX_Caligraphic-Regular.woff2 +0 -0
  56. package/web/dist/assets/KaTeX_Fraktur-Bold.ttf +0 -0
  57. package/web/dist/assets/KaTeX_Fraktur-Bold.woff +0 -0
  58. package/web/dist/assets/KaTeX_Fraktur-Bold.woff2 +0 -0
  59. package/web/dist/assets/KaTeX_Fraktur-Regular.ttf +0 -0
  60. package/web/dist/assets/KaTeX_Fraktur-Regular.woff +0 -0
  61. package/web/dist/assets/KaTeX_Fraktur-Regular.woff2 +0 -0
  62. package/web/dist/assets/KaTeX_Main-Bold.ttf +0 -0
  63. package/web/dist/assets/KaTeX_Main-Bold.woff +0 -0
  64. package/web/dist/assets/KaTeX_Main-Bold.woff2 +0 -0
  65. package/web/dist/assets/KaTeX_Main-BoldItalic.ttf +0 -0
  66. package/web/dist/assets/KaTeX_Main-BoldItalic.woff +0 -0
  67. package/web/dist/assets/KaTeX_Main-BoldItalic.woff2 +0 -0
  68. package/web/dist/assets/KaTeX_Main-Italic.ttf +0 -0
  69. package/web/dist/assets/KaTeX_Main-Italic.woff +0 -0
  70. package/web/dist/assets/KaTeX_Main-Italic.woff2 +0 -0
  71. package/web/dist/assets/KaTeX_Main-Regular.ttf +0 -0
  72. package/web/dist/assets/KaTeX_Main-Regular.woff +0 -0
  73. package/web/dist/assets/KaTeX_Main-Regular.woff2 +0 -0
  74. package/web/dist/assets/KaTeX_Math-BoldItalic.ttf +0 -0
  75. package/web/dist/assets/KaTeX_Math-BoldItalic.woff +0 -0
  76. package/web/dist/assets/KaTeX_Math-BoldItalic.woff2 +0 -0
  77. package/web/dist/assets/KaTeX_Math-Italic.ttf +0 -0
  78. package/web/dist/assets/KaTeX_Math-Italic.woff +0 -0
  79. package/web/dist/assets/KaTeX_Math-Italic.woff2 +0 -0
  80. package/web/dist/assets/KaTeX_SansSerif-Bold.ttf +0 -0
  81. package/web/dist/assets/KaTeX_SansSerif-Bold.woff +0 -0
  82. package/web/dist/assets/KaTeX_SansSerif-Bold.woff2 +0 -0
  83. package/web/dist/assets/KaTeX_SansSerif-Italic.ttf +0 -0
  84. package/web/dist/assets/KaTeX_SansSerif-Italic.woff +0 -0
  85. package/web/dist/assets/KaTeX_SansSerif-Italic.woff2 +0 -0
  86. package/web/dist/assets/KaTeX_SansSerif-Regular.ttf +0 -0
  87. package/web/dist/assets/KaTeX_SansSerif-Regular.woff +0 -0
  88. package/web/dist/assets/KaTeX_SansSerif-Regular.woff2 +0 -0
  89. package/web/dist/assets/KaTeX_Script-Regular.ttf +0 -0
  90. package/web/dist/assets/KaTeX_Script-Regular.woff +0 -0
  91. package/web/dist/assets/KaTeX_Script-Regular.woff2 +0 -0
  92. package/web/dist/assets/KaTeX_Size1-Regular.ttf +0 -0
  93. package/web/dist/assets/KaTeX_Size1-Regular.woff +0 -0
  94. package/web/dist/assets/KaTeX_Size1-Regular.woff2 +0 -0
  95. package/web/dist/assets/KaTeX_Size2-Regular.ttf +0 -0
  96. package/web/dist/assets/KaTeX_Size2-Regular.woff +0 -0
  97. package/web/dist/assets/KaTeX_Size2-Regular.woff2 +0 -0
  98. package/web/dist/assets/KaTeX_Size3-Regular.ttf +0 -0
  99. package/web/dist/assets/KaTeX_Size3-Regular.woff +0 -0
  100. package/web/dist/assets/KaTeX_Size3-Regular.woff2 +0 -0
  101. package/web/dist/assets/KaTeX_Size4-Regular.ttf +0 -0
  102. package/web/dist/assets/KaTeX_Size4-Regular.woff +0 -0
  103. package/web/dist/assets/KaTeX_Size4-Regular.woff2 +0 -0
  104. package/web/dist/assets/KaTeX_Typewriter-Regular.ttf +0 -0
  105. package/web/dist/assets/KaTeX_Typewriter-Regular.woff +0 -0
  106. package/web/dist/assets/KaTeX_Typewriter-Regular.woff2 +0 -0
  107. package/web/dist/assets/cadence.css +2 -0
  108. package/web/dist/assets/cadence.js +7 -0
  109. package/web/dist/assets/markdown.js +296 -0
  110. package/web/dist/assets/react.js +9 -0
  111. package/web/dist/assets/rolldown-runtime.js +1 -0
  112. package/web/dist/assets/timeline-client.js +41 -0
  113. package/web/dist/assets/vis-timeline.css +1274 -0
  114. package/web/dist/assets/vis-timeline.js +32 -0
  115. package/web/dist/index.html +18 -0
  116. package/web/dist/manifest.json +505 -0
  117. package/config/plan-draft.example.json +0 -125
  118. package/config/plan-draft.multiple-tasks.example.json +0 -375
  119. package/config/plan-draft.quick.example.json +0 -78
  120. package/prompts/abel-design.md +0 -382
  121. package/prompts/abel-diagnose.md +0 -71
  122. package/prompts/abel-implement.md +0 -284
  123. package/prompts/abel-init.md +0 -52
  124. package/src/activation.ts +0 -44
  125. package/src/activity-contracts.ts +0 -82
  126. package/src/agent-registry.ts +0 -53
  127. package/src/apply-transaction.ts +0 -1437
  128. package/src/artifact-store.ts +0 -213
  129. package/src/build-windows-job.mjs +0 -95
  130. package/src/candidate-artifact.ts +0 -143
  131. package/src/candidate-context.ts +0 -289
  132. package/src/candidate-patch.ts +0 -271
  133. package/src/candidate-workspace.ts +0 -80
  134. package/src/canonical.ts +0 -16
  135. package/src/change-contract-schema.ts +0 -191
  136. package/src/change-contract.ts +0 -324
  137. package/src/change-verification.ts +0 -1617
  138. package/src/contracts.ts +0 -2466
  139. package/src/control-contracts.ts +0 -382
  140. package/src/delivery-compiler.ts +0 -1805
  141. package/src/delivery-revision.ts +0 -42
  142. package/src/design-control.ts +0 -1299
  143. package/src/design-diagnostics.ts +0 -181
  144. package/src/design-journal.ts +0 -1773
  145. package/src/directory-sync.ts +0 -36
  146. package/src/durable-contracts.ts +0 -227
  147. package/src/durable-workflow.ts +0 -822
  148. package/src/evidence-draft.ts +0 -122
  149. package/src/execution-profile.ts +0 -64
  150. package/src/execution-retention.ts +0 -77
  151. package/src/file-snapshot.ts +0 -163
  152. package/src/implement-continuation.ts +0 -559
  153. package/src/implement-graph.ts +0 -690
  154. package/src/implement-plan.ts +0 -72
  155. package/src/install-config.d.mts +0 -6
  156. package/src/isolation-backend.ts +0 -353
  157. package/src/model-source.ts +0 -22
  158. package/src/openspec-cli.ts +0 -494
  159. package/src/operator-cli-entry.mjs +0 -24
  160. package/src/operator-tools.ts +0 -309
  161. package/src/package-candidate-process.ts +0 -206
  162. package/src/package-candidate.ts +0 -24
  163. package/src/package-delivery.ts +0 -486
  164. package/src/package-state.ts +0 -320
  165. package/src/package-verification.ts +0 -635
  166. package/src/package-workflow.ts +0 -305
  167. package/src/packet-runtime.ts +0 -459
  168. package/src/phase-execution.ts +0 -2163
  169. package/src/pi-adapter.ts +0 -19
  170. package/src/plan-draft-summary.ts +0 -527
  171. package/src/plan-draft.ts +0 -502
  172. package/src/remove-path.ts +0 -32
  173. package/src/run-state.ts +0 -420
  174. package/src/run-store.ts +0 -1179
  175. package/src/safe-path.ts +0 -77
  176. package/src/scoped-grep-worker.mjs +0 -23
  177. package/src/scoped-tools.ts +0 -775
  178. package/src/single-task-draft.ts +0 -142
  179. package/src/sqlite-schema.ts +0 -171
  180. package/src/state-root.ts +0 -215
  181. package/src/storage-schema.ts +0 -360
  182. package/src/subagent-activity.ts +0 -1417
  183. package/src/subagent-process.ts +0 -476
  184. package/src/task-ledger.ts +0 -1338
  185. package/src/transport-budget.ts +0 -50
  186. package/src/verification-capability.ts +0 -1191
  187. package/src/verification-environment-io.ts +0 -389
  188. package/src/verification-environment.ts +0 -162
  189. package/src/verification-identity.ts +0 -77
  190. package/src/verification-scan.ts +0 -64
  191. package/src/windows-job-backend.ts +0 -419
  192. package/src/windows-job.c +0 -149
  193. package/src/workflow-engine.ts +0 -28
  194. package/src/workflow-policy.ts +0 -1670
  195. package/src/workflow-recovery-policy.ts +0 -97
  196. package/src/workflow-scheduling.ts +0 -105
  197. package/src/workflow-state-machine.ts +0 -4341
  198. package/src/workflow-status.ts +0 -576
  199. package/src/workspace-io-entry.mjs +0 -76
  200. package/src/workspace-io-worker.mjs +0 -1312
  201. package/src/workspace-io.ts +0 -89
  202. package/src/workspace-store.ts +0 -634
@@ -0,0 +1,1197 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { performance } from "node:perf_hooks";
3
+ import {
4
+ advanceCapture,
5
+ ContractError,
6
+ canonicalJson,
7
+ decodeId,
8
+ decodeSourceIdentity,
9
+ LIMITS,
10
+ parseWireJson,
11
+ utf8Bytes,
12
+ } from "./worker-public.mjs";
13
+ import {
14
+ DetailSanitizer,
15
+ own,
16
+ ownArray,
17
+ sanitizedJsonChunks,
18
+ sanitizeText,
19
+ TextSanitizer,
20
+ } from "./worker-redaction.mjs";
21
+
22
+ export const completeCoverage = () => ({
23
+ observed: "complete",
24
+ source: "complete",
25
+ redacted: false,
26
+ omissions: [],
27
+ });
28
+ export const controlEvent = (kind) =>
29
+ ["ready", "capture-status", "worker-failure", "final"].includes(kind);
30
+ export function* chunks(text) {
31
+ // At most 8KiB decoded, including four-byte Unicode; never split surrogates.
32
+ for (let at = 0; at < text.length; ) {
33
+ let end = Math.min(at + 2048, text.length);
34
+ if (end < text.length && /[\uD800-\uDBFF]/.test(text[end - 1])) end--;
35
+ yield text.slice(at, end);
36
+ at = end;
37
+ }
38
+ }
39
+ function requireFact(condition) {
40
+ if (!condition) throw new ContractError();
41
+ }
42
+ /** Stateful original-wire validator. The emitter and native owner use this same
43
+ * implementation. Hashes are checked before any owner transformation. */
44
+ export class CaptureState {
45
+ constructor(childRunId, request) {
46
+ this.position = {
47
+ childRunId: decodeId(childRunId),
48
+ workerSeq: 0,
49
+ observedMs: 0,
50
+ final: false,
51
+ };
52
+ this.details = new Map();
53
+ this.messages = new Map();
54
+ this.calls = new Map();
55
+ this.blocks = new Map();
56
+ this.dataFrames = 0;
57
+ this.controlFrames = 0;
58
+ this.bytes = 0;
59
+ this.coverage = completeCoverage();
60
+ this.selected = null;
61
+ this.failed = false;
62
+ this.request = request;
63
+ this.contexts = new Set();
64
+ this.handoffs = new Set();
65
+ }
66
+ accept(input, encodedBytes) {
67
+ const { frame, position } = advanceCapture(this.position, input);
68
+ const e = frame.event;
69
+ const control = controlEvent(e.kind);
70
+ this.bytes += encodedBytes ?? utf8Bytes(canonicalJson(frame)) + 1;
71
+ if (
72
+ ++this[control ? "controlFrames" : "dataFrames"] >
73
+ (control ? LIMITS.controlFrames : LIMITS.dataFrames) ||
74
+ this.bytes >
75
+ LIMITS.childProtocolBytes - (control ? 0 : LIMITS.ownerControlBytes)
76
+ )
77
+ throw new ContractError("oversize");
78
+ const message = (id) => {
79
+ const m = this.messages.get(id);
80
+ requireFact(m);
81
+ return m;
82
+ };
83
+ const detail = (id, field, ownerId) => {
84
+ const d = this.details.get(id);
85
+ requireFact(d?.ended && d.descriptor.field === field);
86
+ if (ownerId)
87
+ requireFact(
88
+ (d.descriptor.owner.messageId ?? d.descriptor.owner.callId) ===
89
+ ownerId,
90
+ );
91
+ return d;
92
+ };
93
+ const owner = (o) => {
94
+ if (o.kind === "message" || o.kind === "message-final")
95
+ requireFact(!message(o.messageId).ended);
96
+ // Execution args may precede their tool-start; validate at the reference.
97
+ if (o.blockId) {
98
+ const previous = this.blocks.get(o.blockId);
99
+ const key = canonicalJson(o);
100
+ requireFact(previous === undefined || previous === key);
101
+ this.blocks.set(o.blockId, key);
102
+ }
103
+ };
104
+ switch (e.kind) {
105
+ case "ready":
106
+ break;
107
+ case "message-start":
108
+ requireFact(!this.messages.has(e.messageId));
109
+ if (e.resultCallId !== null)
110
+ requireFact(this.calls.get(e.resultCallId)?.ended);
111
+ this.messages.set(e.messageId, {
112
+ role: e.role,
113
+ ended: false,
114
+ final: null,
115
+ stopReason: null,
116
+ finalIndices: new Set(),
117
+ finalHash: createHash("sha256"),
118
+ finalBytes: 0,
119
+ finalIndex: -1,
120
+ });
121
+ break;
122
+ case "detail-begin":
123
+ requireFact(!this.details.has(e.detailId));
124
+ owner(e.descriptor.owner);
125
+ if (e.descriptor.owner.kind === "context") {
126
+ requireFact(!this.contexts.has(e.descriptor.owner.component));
127
+ this.contexts.add(e.descriptor.owner.component);
128
+ }
129
+ if (e.descriptor.owner.kind === "handoff") {
130
+ const o = e.descriptor.owner;
131
+ requireFact(!this.handoffs.has(o.dependencyIndex));
132
+ if (this.request)
133
+ requireFact(
134
+ this.request.handoff.inputs.some(
135
+ (input) =>
136
+ input.dependencyIndex === o.dependencyIndex &&
137
+ canonicalJson(input.result) === canonicalJson(o.source),
138
+ ),
139
+ );
140
+ this.handoffs.add(o.dependencyIndex);
141
+ }
142
+ if (
143
+ e.descriptor.owner.kind === "message" &&
144
+ e.descriptor.owner.stage === "final"
145
+ ) {
146
+ const m = message(e.descriptor.owner.messageId);
147
+ requireFact(
148
+ e.descriptor.owner.index > m.finalIndex &&
149
+ !m.finalIndices.has(e.descriptor.owner.index),
150
+ );
151
+ m.finalIndex = e.descriptor.owner.index;
152
+ m.finalIndices.add(e.descriptor.owner.index);
153
+ }
154
+ this.details.set(e.detailId, {
155
+ descriptor: e.descriptor,
156
+ hash: createHash("sha256"),
157
+ bytes: 0,
158
+ ended: false,
159
+ preview: "",
160
+ });
161
+ break;
162
+ case "detail-chunk": {
163
+ const d = this.details.get(e.detailId);
164
+ requireFact(d && !d.ended && e.offset === d.bytes);
165
+ d.bytes += utf8Bytes(e.text);
166
+ d.hash.update(e.text);
167
+ if (
168
+ d.descriptor.owner.kind === "message" &&
169
+ d.descriptor.owner.stage === "final"
170
+ ) {
171
+ const m = message(d.descriptor.owner.messageId);
172
+ m.finalHash.update(e.text);
173
+ m.finalBytes += utf8Bytes(e.text);
174
+ }
175
+ if (d.descriptor.field === "final-text" && utf8Bytes(d.preview) < 16384)
176
+ d.preview += e.text.slice(0, 16384 - utf8Bytes(d.preview));
177
+ break;
178
+ }
179
+ case "detail-end": {
180
+ const d = this.details.get(e.detailId);
181
+ requireFact(
182
+ d &&
183
+ !d.ended &&
184
+ d.bytes === e.bytes &&
185
+ d.hash.digest("hex") === e.sha256,
186
+ );
187
+ if (d.descriptor.owner.kind === "message-final") {
188
+ const m = message(d.descriptor.owner.messageId);
189
+ requireFact(
190
+ m.finalBytes === e.bytes &&
191
+ m.finalHash.copy().digest("hex") === e.sha256,
192
+ );
193
+ }
194
+ d.hash = null;
195
+ d.ended = true;
196
+ this.mergeCoverage(e.coverage);
197
+ break;
198
+ }
199
+ case "message-text": {
200
+ const d = this.details.get(e.detailId);
201
+ const o = d?.descriptor.owner;
202
+ requireFact(
203
+ !message(e.messageId).ended &&
204
+ d &&
205
+ o.kind === "message" &&
206
+ o.messageId === e.messageId &&
207
+ o.blockId === e.blockId,
208
+ );
209
+ break;
210
+ }
211
+ case "call-declaration": {
212
+ const m = message(e.declaration.messageId);
213
+ requireFact(!m.ended && m.role === "assistant");
214
+ const old = this.calls.get(e.callId);
215
+ requireFact(
216
+ !old ||
217
+ (!old.started &&
218
+ !old.ended &&
219
+ old.stage === "partial" &&
220
+ canonicalJson(old.declaration) === canonicalJson(e.declaration)),
221
+ );
222
+ if (e.argsDetailId)
223
+ requireFact(
224
+ detail(e.argsDetailId, "tool-args", e.callId).descriptor.owner
225
+ .stage ===
226
+ (e.stage === "partial" ? "arguments-partial" : "arguments-final"),
227
+ );
228
+ if (e.stage === "final") {
229
+ requireFact(!m.finalIndices.has(e.index));
230
+ m.finalIndices.add(e.index);
231
+ }
232
+ this.calls.set(e.callId, { ...e, started: false, ended: false });
233
+ break;
234
+ }
235
+ case "tool-start": {
236
+ const old = this.calls.get(e.callId);
237
+ requireFact(
238
+ !old ||
239
+ (!old.started &&
240
+ !old.ended &&
241
+ canonicalJson(old.declaration) === canonicalJson(e.declaration) &&
242
+ canonicalJson(old.source) === canonicalJson(e.source) &&
243
+ old.name === e.name),
244
+ );
245
+ requireFact(old || e.declaration === null);
246
+ if (e.argsDetailId)
247
+ requireFact(
248
+ detail(e.argsDetailId, "tool-args", e.callId).descriptor.owner
249
+ .stage === "execution-arguments",
250
+ );
251
+ this.calls.set(e.callId, { ...old, ...e, started: true, ended: false });
252
+ break;
253
+ }
254
+ case "tool-update":
255
+ requireFact(
256
+ this.calls.get(e.callId)?.started && !this.calls.get(e.callId)?.ended,
257
+ );
258
+ requireFact(
259
+ detail(e.detailId, "tool-update", e.callId).descriptor.owner.stage ===
260
+ "update-snapshot",
261
+ );
262
+ break;
263
+ case "tool-end": {
264
+ const c = this.calls.get(e.callId);
265
+ requireFact(!c?.ended && e.startObserved === !!c?.started);
266
+ if (e.declaration)
267
+ requireFact(
268
+ c && canonicalJson(c.declaration) === canonicalJson(e.declaration),
269
+ );
270
+ if (c)
271
+ requireFact(
272
+ c.name === e.name &&
273
+ canonicalJson(c.source) === canonicalJson(e.source),
274
+ );
275
+ requireFact(
276
+ detail(e.resultDetailId, "tool-result", e.callId).descriptor.owner
277
+ .stage === "result",
278
+ );
279
+ this.calls.set(e.callId, {
280
+ ...c,
281
+ ...e,
282
+ started: e.startObserved,
283
+ ended: true,
284
+ });
285
+ break;
286
+ }
287
+ case "message-end": {
288
+ const m = message(e.messageId);
289
+ requireFact(!m.ended);
290
+ if (e.finalDetailId) {
291
+ const d = detail(e.finalDetailId, "final-text", e.messageId);
292
+ requireFact(
293
+ m.role === "assistant" &&
294
+ d.descriptor.owner.kind === "message-final",
295
+ );
296
+ }
297
+ for (const d of this.details.values())
298
+ if (d.descriptor.owner.messageId === e.messageId) {
299
+ requireFact(d.ended);
300
+ if (d.descriptor.owner.stage === "final")
301
+ requireFact(d.descriptor.owner.index < e.finalBlockCount);
302
+ }
303
+ requireFact(
304
+ m.finalIndices.size === e.finalBlockCount &&
305
+ [...m.finalIndices].every((i) => i < e.finalBlockCount),
306
+ );
307
+ m.ended = true;
308
+ m.final = e.finalDetailId;
309
+ m.stopReason = e.stopReason;
310
+ break;
311
+ }
312
+ case "omitted-block":
313
+ owner(e.block.owner);
314
+ if (
315
+ e.block.owner.kind === "message" &&
316
+ e.block.owner.stage === "final"
317
+ ) {
318
+ const m = message(e.block.owner.messageId);
319
+ requireFact(!m.finalIndices.has(e.block.owner.index));
320
+ m.finalIndices.add(e.block.owner.index);
321
+ }
322
+ this.mergeCoverage({
323
+ observed: "complete",
324
+ source: "limited",
325
+ redacted: false,
326
+ omissions: [e.block.reason],
327
+ });
328
+ break;
329
+ case "capture-status":
330
+ this.mergeCoverage(e.coverage);
331
+ break;
332
+ case "worker-failure":
333
+ this.failed = true;
334
+ break;
335
+ case "final": {
336
+ if (this.request)
337
+ requireFact(
338
+ [
339
+ "request-context",
340
+ "request-prompt",
341
+ "request-instructions",
342
+ "role",
343
+ "effective-system",
344
+ ].every((name) => this.contexts.has(name)) &&
345
+ this.handoffs.size === this.request.handoff.inputs.length,
346
+ );
347
+ const m = message(e.messageId);
348
+ requireFact(
349
+ !this.failed &&
350
+ m.ended &&
351
+ m.role === "assistant" &&
352
+ m.stopReason === "stop" &&
353
+ m.final === e.detailId &&
354
+ this.coverage.observed === "complete",
355
+ );
356
+ requireFact(
357
+ [...this.details.values()].every((d) => d.ended) &&
358
+ [...this.messages.values()].every((v) => v.ended) &&
359
+ [...this.calls.values()].every((c) => !c.started || c.ended),
360
+ );
361
+ detail(e.detailId, "final-text", e.messageId);
362
+ this.selected = { messageId: e.messageId, detailId: e.detailId };
363
+ break;
364
+ }
365
+ }
366
+ this.position = position;
367
+ return frame;
368
+ }
369
+ mergeCoverage(c) {
370
+ this.coverage.observed =
371
+ c.observed === "incomplete" ? "incomplete" : this.coverage.observed;
372
+ if (c.source !== "complete") this.coverage.source = c.source;
373
+ this.coverage.redacted ||= c.redacted;
374
+ this.coverage.omissions = [
375
+ ...new Set([...this.coverage.omissions, ...c.omissions]),
376
+ ];
377
+ }
378
+ get preview() {
379
+ return this.selected
380
+ ? this.details.get(this.selected.detailId).preview
381
+ : "";
382
+ }
383
+ }
384
+ /** One worker-owned accounting domain for output, source update copies and
385
+ * sanitizer retention. A reporting timeout never releases a live write lease. */
386
+ export class CaptureQueue {
387
+ constructor() {
388
+ this.bytes = 0;
389
+ this.frames = 0;
390
+ this.dataBytes = 0;
391
+ this.dataFrames = 0;
392
+ }
393
+ reserveSource() {
394
+ const bytes = Math.min(
395
+ LIMITS.workerQueueBytes - this.bytes,
396
+ LIMITS.workerQueueBytes - LIMITS.ownerControlBytes - this.dataBytes,
397
+ );
398
+ if (bytes <= 0) throw new ContractError("capacity");
399
+ return { bytes, lease: this.reserve(bytes) };
400
+ }
401
+ reserve(bytes, lane = "data") {
402
+ if (
403
+ !Number.isSafeInteger(bytes) ||
404
+ bytes < 0 ||
405
+ this.bytes + bytes > LIMITS.workerQueueBytes ||
406
+ this.frames + 1 > LIMITS.workerQueueFrames ||
407
+ (lane === "data" &&
408
+ (this.dataBytes + bytes >
409
+ LIMITS.workerQueueBytes - LIMITS.ownerControlBytes ||
410
+ this.dataFrames + 1 >
411
+ LIMITS.workerQueueFrames - LIMITS.controlFrames))
412
+ )
413
+ throw new ContractError("capacity");
414
+ this.bytes += bytes;
415
+ this.frames++;
416
+ if (lane === "data") {
417
+ this.dataBytes += bytes;
418
+ this.dataFrames++;
419
+ }
420
+ let held = bytes,
421
+ live = true;
422
+ return {
423
+ get bytes() {
424
+ return held;
425
+ },
426
+ grow: (size) => {
427
+ if (
428
+ !live ||
429
+ !Number.isSafeInteger(size) ||
430
+ size < 0 ||
431
+ this.bytes + size > LIMITS.workerQueueBytes ||
432
+ (lane === "data" &&
433
+ this.dataBytes + size >
434
+ LIMITS.workerQueueBytes - LIMITS.ownerControlBytes)
435
+ )
436
+ throw new ContractError("capacity");
437
+ held += size;
438
+ this.bytes += size;
439
+ if (lane === "data") this.dataBytes += size;
440
+ },
441
+ shrink: (size) => {
442
+ if (!live || size < 0 || size > held) throw new ContractError();
443
+ this.bytes -= held - size;
444
+ if (lane === "data") this.dataBytes -= held - size;
445
+ held = size;
446
+ },
447
+ release: () => {
448
+ if (!live) throw new ContractError();
449
+ live = false;
450
+ this.bytes -= held;
451
+ this.frames--;
452
+ if (lane === "data") {
453
+ this.dataBytes -= held;
454
+ this.dataFrames--;
455
+ }
456
+ },
457
+ };
458
+ }
459
+ }
460
+ /** Callback-backed writes retain their original charge until settlement. */
461
+ export class CaptureEmitter {
462
+ constructor(childRunId, output, onFailure, request) {
463
+ this.state = new CaptureState(childRunId, request);
464
+ this.output = output;
465
+ this.onFailure = onFailure;
466
+ this.started = performance.now();
467
+ this.pending = new Set();
468
+ this.queuedBytes = 0;
469
+ this.broken = false;
470
+ this.queue = new CaptureQueue();
471
+ }
472
+ emit(event) {
473
+ const lease = this.queue.reserve(
474
+ LIMITS.frameBytes * 3,
475
+ controlEvent(event.kind) ? "control" : "data",
476
+ );
477
+ let line, bytes;
478
+ try {
479
+ const frame = {
480
+ protocol: 2,
481
+ childRunId: this.state.position.childRunId,
482
+ workerSeq: this.state.position.workerSeq + 1,
483
+ observedMs: Math.floor(performance.now() - this.started),
484
+ event,
485
+ };
486
+ line = `${canonicalJson(frame, LIMITS.frameBytes - 1)}\n`;
487
+ bytes = utf8Bytes(line);
488
+ this.state.accept(frame, bytes);
489
+ lease.shrink(bytes);
490
+ this.queuedBytes += bytes;
491
+ } catch (error) {
492
+ lease.release();
493
+ throw error;
494
+ }
495
+ let timer;
496
+ const original = new Promise((resolve, reject) => {
497
+ this.output.write(line, (error) =>
498
+ error ? reject(new ContractError("unavailable")) : resolve(),
499
+ );
500
+ });
501
+ this.pending.add(original);
502
+ const settled = original.then(
503
+ () => {
504
+ clearTimeout(timer);
505
+ this.queuedBytes -= bytes;
506
+ lease.release();
507
+ this.pending.delete(original);
508
+ },
509
+ () => {
510
+ clearTimeout(timer);
511
+ this.queuedBytes -= bytes;
512
+ lease.release();
513
+ this.pending.delete(original);
514
+ this.broken = true;
515
+ this.onFailure();
516
+ },
517
+ );
518
+ // Reporting timeout never refunds an outstanding original write.
519
+ const wait = Promise.race([
520
+ original,
521
+ new Promise((_, reject) => {
522
+ timer = setTimeout(() => {
523
+ this.onFailure();
524
+ reject(new ContractError("recording-exhausted"));
525
+ }, LIMITS.recordingStallMs);
526
+ }),
527
+ ]);
528
+ wait.catch(() => {});
529
+ settled.catch(() => {});
530
+ return wait;
531
+ }
532
+ async drain() {
533
+ await Promise.allSettled([...this.pending]);
534
+ }
535
+ }
536
+ function source(value, secrets) {
537
+ if (value === undefined || value === null)
538
+ return { disposition: "unavailable", value: null };
539
+ if (typeof value !== "string") throw new ContractError();
540
+ try {
541
+ if (sanitizeText(value, secrets) !== value) throw new ContractError();
542
+ return decodeSourceIdentity({ disposition: "observed", value });
543
+ } catch {
544
+ return { disposition: "redacted", value: null };
545
+ }
546
+ }
547
+ /** Actual awaited core-agent event adapter. Core emits one message occurrence
548
+ * at a time; concurrent open occurrences refuse, never join by a nearest ID.
549
+ * Tool joins require a unique raw ID AND name among genuine declarations/starts. */
550
+ export class SdkCapture {
551
+ constructor(emitter, secrets = []) {
552
+ this.emitter = emitter;
553
+ this.secrets = secrets;
554
+ this.current = null;
555
+ this.calls = [];
556
+ this.selected = null;
557
+ this.events = 0;
558
+ this.updates = new WeakMap();
559
+ }
560
+ emit(e) {
561
+ return this.emitter.emit(e);
562
+ }
563
+ prefix() {
564
+ const literals = this.secrets.reduce((n, value) => n + utf8Bytes(value), 0);
565
+ // Text/known-literal prefix and bounded UTF-8/escaping expansion. Canonical
566
+ // traversal keys and slices acquire their own incremental leases below;
567
+ // a tiny overlapping update must not prepay a hypothetical 1MiB key stack.
568
+ return this.emitter.queue.reserve(literals * 4 + 65536);
569
+ }
570
+ dispose() {
571
+ for (const stream of this.current?.streams.values() ?? [])
572
+ if (stream.lease) {
573
+ stream.lease.release();
574
+ stream.lease = null;
575
+ }
576
+ }
577
+ async detail(descriptor, input, coverage = completeCoverage()) {
578
+ if (
579
+ (typeof input === "string"
580
+ ? Buffer.byteLength(input)
581
+ : Array.isArray(input)
582
+ ? input.reduce((n, s) => n + Buffer.byteLength(s), 0)
583
+ : 0) > LIMITS.detailBytes
584
+ )
585
+ throw new ContractError("oversize");
586
+ const lease = this.prefix(descriptor.encoding);
587
+ try {
588
+ const id = randomUUID();
589
+ await this.emit({ kind: "detail-begin", detailId: id, descriptor });
590
+ let sanitizer = new TextSanitizer(this.secrets);
591
+ let redacted = false;
592
+ let bytes = 0;
593
+ const hash = createHash("sha256");
594
+ const append = async (value) => {
595
+ for (const part of chunks(value)) {
596
+ if (bytes + utf8Bytes(part) > LIMITS.detailBytes)
597
+ throw new ContractError("oversize");
598
+ await this.emit({
599
+ kind: "detail-chunk",
600
+ detailId: id,
601
+ offset: bytes,
602
+ text: part,
603
+ });
604
+ bytes += utf8Bytes(part);
605
+ hash.update(part);
606
+ }
607
+ };
608
+ // Canonical JSON was structurally sanitized before serialization. Re-sanitizing
609
+ // serialized escapes as text would corrupt JSON and miss decoded literals.
610
+ for (const value of typeof input === "string" ? [input] : input) {
611
+ if (typeof value !== "string") throw new ContractError();
612
+ for (const part of chunks(value))
613
+ await append(
614
+ descriptor.encoding === "canonical-json"
615
+ ? part
616
+ : sanitizer.write(part),
617
+ );
618
+ // Final selection concatenates the finalized FIELD projections, not a
619
+ // second cross-field sanitization that can change their hashes/bytes.
620
+ if (descriptor.owner.kind === "message-final") {
621
+ await append(sanitizer.end());
622
+ redacted ||= sanitizer.redacted;
623
+ sanitizer = new TextSanitizer(this.secrets);
624
+ }
625
+ }
626
+ if (descriptor.encoding === "utf8") await append(sanitizer.end());
627
+ coverage = {
628
+ ...coverage,
629
+ redacted: coverage.redacted || sanitizer.redacted || redacted,
630
+ };
631
+ await this.emit({
632
+ kind: "detail-end",
633
+ detailId: id,
634
+ bytes,
635
+ sha256: hash.digest("hex"),
636
+ coverage,
637
+ });
638
+ return id;
639
+ } finally {
640
+ lease.release();
641
+ }
642
+ }
643
+ async openStream(descriptor) {
644
+ // Partial JSON carries bounded incremental lexical state, not a prepaid
645
+ // megabyte for every (often tiny) simultaneously open declaration.
646
+ const lease = this.prefix(descriptor.encoding);
647
+ try {
648
+ const stream = {
649
+ lease,
650
+ id: randomUUID(),
651
+ descriptor,
652
+ sanitizer:
653
+ descriptor.owner.stage === "arguments-partial"
654
+ ? new DetailSanitizer("canonical-json", this.secrets, true)
655
+ : new TextSanitizer(this.secrets),
656
+ bytes: 0,
657
+ hash: createHash("sha256"),
658
+ };
659
+ await this.emit({
660
+ kind: "detail-begin",
661
+ detailId: stream.id,
662
+ descriptor,
663
+ });
664
+ return stream;
665
+ } catch (error) {
666
+ lease.release();
667
+ throw error;
668
+ }
669
+ }
670
+ async streamWrite(stream, value, final = false) {
671
+ if (
672
+ typeof value !== "string" ||
673
+ Buffer.byteLength(value) + stream.bytes > LIMITS.detailBytes
674
+ )
675
+ throw new ContractError("oversize");
676
+ for (const input of final ? [value] : chunks(value)) {
677
+ // Source/expansion charge precedes projection. Transfer any growing
678
+ // lexical retention before releasing this source reservation.
679
+ const sourceLease = this.emitter.queue.reserve(utf8Bytes(input) * 12);
680
+ try {
681
+ const clean = stream.sanitizer.write(input, final);
682
+ const extra = stream.sanitizer.retainedBytes - stream.lease.bytes;
683
+ if (extra > 0) stream.lease.grow(extra);
684
+ for (const part of chunks(clean)) {
685
+ await this.emit({
686
+ kind: "detail-chunk",
687
+ detailId: stream.id,
688
+ offset: stream.bytes,
689
+ text: part,
690
+ });
691
+ stream.bytes += utf8Bytes(part);
692
+ stream.hash.update(part);
693
+ }
694
+ } finally {
695
+ sourceLease.release();
696
+ }
697
+ }
698
+ if (final) {
699
+ try {
700
+ await this.emit({
701
+ kind: "detail-end",
702
+ detailId: stream.id,
703
+ bytes: stream.bytes,
704
+ sha256: stream.hash.digest("hex"),
705
+ coverage: {
706
+ ...completeCoverage(),
707
+ redacted: stream.sanitizer.redacted,
708
+ source: stream.sanitizer.limited ? "limited" : "complete",
709
+ omissions: stream.sanitizer.limited ? ["unsupported"] : [],
710
+ },
711
+ });
712
+ } finally {
713
+ stream.lease.release();
714
+ stream.lease = null;
715
+ }
716
+ }
717
+ }
718
+ async context(request, system) {
719
+ for (const [component, value] of [
720
+ ["request-context", request.context],
721
+ ["request-prompt", request.prompt],
722
+ ["request-instructions", request.instructions],
723
+ ["role", canonicalJson(request.role)],
724
+ ["effective-system", system],
725
+ ])
726
+ await this.detail(
727
+ {
728
+ owner: { kind: "context", component },
729
+ field: "context",
730
+ encoding: "utf8",
731
+ },
732
+ value,
733
+ );
734
+ for (const input of request.handoff.inputs)
735
+ await this.detail(
736
+ {
737
+ owner: {
738
+ kind: "handoff",
739
+ dependencyIndex: input.dependencyIndex,
740
+ source: input.result,
741
+ },
742
+ field: "context",
743
+ encoding: "utf8",
744
+ },
745
+ input.text,
746
+ input.coverage,
747
+ );
748
+ }
749
+ toolOwner(call, stage, index = 0) {
750
+ return {
751
+ kind: "tool",
752
+ callId: call.id,
753
+ blockId: randomUUID(),
754
+ index,
755
+ stage,
756
+ };
757
+ }
758
+ async args(call, value, stage) {
759
+ return this.detail(
760
+ {
761
+ owner: this.toolOwner(call, stage),
762
+ field: "tool-args",
763
+ encoding: "canonical-json",
764
+ },
765
+ sanitizedJsonChunks(value, this.secrets, (bytes) =>
766
+ this.emitter.queue.reserve(bytes),
767
+ ),
768
+ { ...completeCoverage(), redacted: true },
769
+ );
770
+ }
771
+ matches(raw, name, predicate) {
772
+ return this.calls.filter(
773
+ (c) =>
774
+ typeof raw === "string" &&
775
+ raw.length > 0 &&
776
+ c.raw === raw &&
777
+ c.rawName === name &&
778
+ predicate(c),
779
+ );
780
+ }
781
+ newCall(raw, name, declaration = null) {
782
+ if (typeof name !== "string" || !name.trim() || utf8Bytes(name) > 128)
783
+ throw new ContractError();
784
+ const call = {
785
+ id: randomUUID(),
786
+ raw,
787
+ rawName: name,
788
+ name: sanitizeText(name, this.secrets) || "redacted",
789
+ source: source(raw, this.secrets),
790
+ declaration,
791
+ started: false,
792
+ ended: false,
793
+ resultLinked: false,
794
+ };
795
+ this.calls.push(call);
796
+ return call;
797
+ }
798
+ async blocks(message, content, stage) {
799
+ const blocks =
800
+ typeof content === "string"
801
+ ? [{ type: "text", text: content }]
802
+ : ownArray(content);
803
+ const texts = [];
804
+ for (let index = 0; index < blocks.length; index++) {
805
+ const block = blocks[index];
806
+ const type = own(block, "type");
807
+ const blockId = randomUUID();
808
+ const owner = {
809
+ kind: "message",
810
+ messageId: message.id,
811
+ blockId,
812
+ index,
813
+ stage,
814
+ };
815
+ if (type === "text") {
816
+ const value = own(block, "text");
817
+ if (typeof value !== "string") throw new ContractError();
818
+ const detailId = await this.detail(
819
+ { owner, field: "message", encoding: "utf8" },
820
+ value,
821
+ );
822
+ await this.emit({
823
+ kind: "message-text",
824
+ messageId: message.id,
825
+ blockId,
826
+ detailId,
827
+ });
828
+ texts.push(value);
829
+ } else if (type === "toolCall" && message.role === "assistant") {
830
+ const raw = own(block, "id"),
831
+ name = own(block, "name");
832
+ const partial = message.declarations.get(index);
833
+ const call =
834
+ partial ??
835
+ this.newCall(raw, name, { messageId: message.id, blockId });
836
+ if (partial) {
837
+ if (typeof name !== "string" || !name.trim() || utf8Bytes(name) > 128)
838
+ throw new ContractError();
839
+ call.raw = raw;
840
+ call.rawName = name;
841
+ call.name = sanitizeText(name, this.secrets) || "redacted";
842
+ call.source = source(raw, this.secrets);
843
+ }
844
+ const argsDetailId = await this.args(
845
+ call,
846
+ own(block, "arguments"),
847
+ "arguments-final",
848
+ );
849
+ await this.emit({
850
+ kind: "call-declaration",
851
+ callId: call.id,
852
+ declaration: call.declaration,
853
+ index,
854
+ source: call.source,
855
+ name: call.name,
856
+ argsDetailId,
857
+ stage: "final",
858
+ });
859
+ } else {
860
+ const reason =
861
+ type === "thinking"
862
+ ? "hidden-thinking"
863
+ : ["image", "audio", "binary"].includes(type)
864
+ ? "binary"
865
+ : "unsupported";
866
+ let mimeType =
867
+ reason === "hidden-thinking" ? null : own(block, "mimeType");
868
+ if (
869
+ typeof mimeType !== "string" ||
870
+ !/^[a-z0-9.+-]+\/[a-z0-9.+-]+$/i.test(mimeType) ||
871
+ sanitizeText(mimeType, this.secrets) !== mimeType
872
+ )
873
+ mimeType = null;
874
+ await this.emit({
875
+ kind: "omitted-block",
876
+ block: {
877
+ owner,
878
+ sourceType:
879
+ reason === "hidden-thinking"
880
+ ? reason
881
+ : reason === "unsupported"
882
+ ? reason
883
+ : type,
884
+ mimeType: reason === "hidden-thinking" ? null : mimeType,
885
+ reason,
886
+ },
887
+ });
888
+ }
889
+ }
890
+ return { texts, count: blocks.length };
891
+ }
892
+ async toolResult(call, result, stage) {
893
+ // Explicit public content projection; never copy arbitrary details/envelopes.
894
+ const content = ownArray(own(result, "content"));
895
+ const values = [];
896
+ for (let index = 0; index < content.length; index++) {
897
+ const block = content[index];
898
+ const type = own(block, "type");
899
+ if (type === "text")
900
+ values.push({ type: "text", text: own(block, "text") });
901
+ else
902
+ await this.emit({
903
+ kind: "omitted-block",
904
+ block: {
905
+ owner: this.toolOwner(call, stage, index),
906
+ sourceType: type === "thinking" ? "hidden-thinking" : "binary",
907
+ mimeType: null,
908
+ reason: type === "thinking" ? "hidden-thinking" : "binary",
909
+ },
910
+ });
911
+ }
912
+ const details = own(result, "details");
913
+ const limited =
914
+ details &&
915
+ (own(details, "truncation") !== undefined ||
916
+ own(details, "fullOutputPath") !== undefined);
917
+ const coverage = {
918
+ ...completeCoverage(),
919
+ redacted: true,
920
+ source: limited ? "limited" : "complete",
921
+ omissions: limited ? ["source-limit"] : [],
922
+ };
923
+ const detailId = await this.detail(
924
+ {
925
+ owner: this.toolOwner(call, stage),
926
+ field: stage === "result" ? "tool-result" : "tool-update",
927
+ encoding: "canonical-json",
928
+ },
929
+ sanitizedJsonChunks(
930
+ details === undefined
931
+ ? { content: values }
932
+ : { content: values, details },
933
+ this.secrets,
934
+ (bytes) => this.emitter.queue.reserve(bytes),
935
+ ),
936
+ coverage,
937
+ );
938
+ return detailId;
939
+ }
940
+ async event(event) {
941
+ if (++this.events > LIMITS.sdkEvents) throw new ContractError("oversize");
942
+ const type = own(event, "type");
943
+ if (typeof type !== "string") throw new ContractError();
944
+ switch (type) {
945
+ case "message_start": {
946
+ requireFact(this.current === null);
947
+ const message = own(event, "message");
948
+ const rawRole = own(message, "role");
949
+ const role = rawRole === "toolResult" ? "tool-result" : rawRole;
950
+ requireFact(["user", "assistant", "tool-result"].includes(role));
951
+ const matches =
952
+ role === "tool-result"
953
+ ? this.matches(
954
+ own(message, "toolCallId"),
955
+ own(message, "toolName"),
956
+ (c) => c.ended && !c.resultLinked,
957
+ )
958
+ : [];
959
+ const call = matches.length === 1 ? matches[0] : null;
960
+ if (call) call.resultLinked = true;
961
+ this.current = {
962
+ id: randomUUID(),
963
+ role,
964
+ streams: new Map(),
965
+ declarations: new Map(),
966
+ };
967
+ await this.emit({
968
+ kind: "message-start",
969
+ messageId: this.current.id,
970
+ role,
971
+ source: source(own(message, "responseId"), this.secrets),
972
+ resultCallId: call?.id ?? null,
973
+ });
974
+ break;
975
+ }
976
+ case "message_update": {
977
+ const m = this.current;
978
+ requireFact(m?.role === "assistant");
979
+ const update = own(event, "assistantMessageEvent"),
980
+ type = own(update, "type");
981
+ const index = own(update, "contentIndex");
982
+ if (["text_delta", "toolcall_start", "toolcall_delta"].includes(type))
983
+ requireFact(
984
+ Number.isSafeInteger(index) &&
985
+ index >= 0 &&
986
+ index <= LIMITS.dataFrames,
987
+ );
988
+ if (type === "text_delta") {
989
+ let stream = m.streams.get(index);
990
+ if (!stream) {
991
+ const blockId = randomUUID();
992
+ stream = await this.openStream({
993
+ owner: {
994
+ kind: "message",
995
+ messageId: m.id,
996
+ blockId,
997
+ index,
998
+ stage: "stream",
999
+ },
1000
+ field: "message",
1001
+ encoding: "utf8",
1002
+ });
1003
+ m.streams.set(index, stream);
1004
+ await this.emit({
1005
+ kind: "message-text",
1006
+ messageId: m.id,
1007
+ blockId,
1008
+ detailId: stream.id,
1009
+ });
1010
+ }
1011
+ await this.streamWrite(stream, own(update, "delta"));
1012
+ } else if (type === "toolcall_start" || type === "toolcall_delta") {
1013
+ const partial = own(update, "partial");
1014
+ const block = ownArray(own(partial, "content"))[index];
1015
+ if (!m.declarations.has(index)) {
1016
+ const call = this.newCall(own(block, "id"), own(block, "name"), {
1017
+ messageId: m.id,
1018
+ blockId: randomUUID(),
1019
+ });
1020
+ m.declarations.set(index, call);
1021
+ await this.emit({
1022
+ kind: "call-declaration",
1023
+ callId: call.id,
1024
+ declaration: call.declaration,
1025
+ index,
1026
+ source: call.source,
1027
+ name: call.name,
1028
+ argsDetailId: null,
1029
+ stage: "partial",
1030
+ });
1031
+ }
1032
+ if (type === "toolcall_delta") {
1033
+ const call = m.declarations.get(index);
1034
+ let stream = m.streams.get(`args-${index}`);
1035
+ if (!stream) {
1036
+ stream = await this.openStream({
1037
+ owner: this.toolOwner(call, "arguments-partial", index),
1038
+ field: "tool-args",
1039
+ encoding: "utf8",
1040
+ });
1041
+ m.streams.set(`args-${index}`, stream);
1042
+ }
1043
+ await this.streamWrite(stream, own(update, "delta"));
1044
+ }
1045
+ }
1046
+ break;
1047
+ }
1048
+ case "message_end": {
1049
+ const m = this.current;
1050
+ requireFact(m);
1051
+ const message = own(event, "message");
1052
+ requireFact(
1053
+ (own(message, "role") === "toolResult"
1054
+ ? "tool-result"
1055
+ : own(message, "role")) === m.role,
1056
+ );
1057
+ for (const stream of m.streams.values())
1058
+ await this.streamWrite(stream, "", true);
1059
+ const { texts, count } = await this.blocks(
1060
+ m,
1061
+ own(message, "content"),
1062
+ "final",
1063
+ );
1064
+ const finalDetailId =
1065
+ m.role === "assistant"
1066
+ ? await this.detail(
1067
+ {
1068
+ owner: { kind: "message-final", messageId: m.id },
1069
+ field: "final-text",
1070
+ encoding: "utf8",
1071
+ },
1072
+ texts,
1073
+ )
1074
+ : null;
1075
+ const reason = own(message, "stopReason");
1076
+ const stopReason = [
1077
+ "stop",
1078
+ "length",
1079
+ "toolUse",
1080
+ "error",
1081
+ "aborted",
1082
+ ].includes(reason)
1083
+ ? reason
1084
+ : "unknown";
1085
+ await this.emit({
1086
+ kind: "message-end",
1087
+ messageId: m.id,
1088
+ finalDetailId,
1089
+ finalBlockCount: count,
1090
+ stopReason,
1091
+ });
1092
+ if (m.role === "assistant")
1093
+ this.selected =
1094
+ stopReason === "stop"
1095
+ ? { messageId: m.id, detailId: finalDetailId }
1096
+ : null;
1097
+ this.current = null;
1098
+ break;
1099
+ }
1100
+ case "tool_execution_start": {
1101
+ const raw = own(event, "toolCallId"),
1102
+ name = own(event, "toolName");
1103
+ const matches = this.matches(raw, name, (c) => !c.started && !c.ended);
1104
+ const call =
1105
+ matches.length === 1 ? matches[0] : this.newCall(raw, name);
1106
+ const argsDetailId = await this.args(
1107
+ call,
1108
+ own(event, "args"),
1109
+ "execution-arguments",
1110
+ );
1111
+ call.started = true;
1112
+ await this.emit({
1113
+ kind: "tool-start",
1114
+ callId: call.id,
1115
+ declaration: call.declaration,
1116
+ source: call.source,
1117
+ name: call.name,
1118
+ argsDetailId,
1119
+ });
1120
+ break;
1121
+ }
1122
+ case "tool_execution_update": {
1123
+ const matches = this.matches(
1124
+ own(event, "toolCallId"),
1125
+ own(event, "toolName"),
1126
+ (c) => c.started && !c.ended,
1127
+ );
1128
+ requireFact(matches.length === 1);
1129
+ const call = matches[0];
1130
+ const detailId = await this.toolResult(
1131
+ call,
1132
+ own(event, "partialResult"),
1133
+ "update-snapshot",
1134
+ );
1135
+ await this.emit({
1136
+ kind: "tool-update",
1137
+ callId: call.id,
1138
+ detailId,
1139
+ semantics: "snapshot",
1140
+ });
1141
+ break;
1142
+ }
1143
+ case "tool_execution_end": {
1144
+ const raw = own(event, "toolCallId"),
1145
+ name = own(event, "toolName");
1146
+ const matches = this.matches(raw, name, (c) => c.started && !c.ended);
1147
+ const call =
1148
+ matches.length === 1 ? matches[0] : this.newCall(raw, name);
1149
+ const resultDetailId = await this.toolResult(
1150
+ call,
1151
+ own(event, "result"),
1152
+ "result",
1153
+ );
1154
+ const isError = own(event, "isError");
1155
+ requireFact(typeof isError === "boolean");
1156
+ call.ended = true;
1157
+ await this.emit({
1158
+ kind: "tool-end",
1159
+ callId: call.id,
1160
+ declaration: call.declaration,
1161
+ source: call.source,
1162
+ name: call.name,
1163
+ resultDetailId,
1164
+ isError,
1165
+ association:
1166
+ matches.length === 0
1167
+ ? "orphan"
1168
+ : matches.length > 1
1169
+ ? "ambiguous"
1170
+ : call.declaration
1171
+ ? "declared"
1172
+ : "execution-only",
1173
+ startObserved: call.started,
1174
+ });
1175
+ break;
1176
+ }
1177
+ case "agent_start":
1178
+ case "agent_end":
1179
+ case "turn_start":
1180
+ case "turn_end":
1181
+ break;
1182
+ default:
1183
+ throw new ContractError();
1184
+ }
1185
+ }
1186
+ async final() {
1187
+ requireFact(this.selected && !this.current);
1188
+ await this.emit({
1189
+ kind: "capture-status",
1190
+ coverage: this.emitter.state.coverage,
1191
+ });
1192
+ await this.emit({ kind: "final", ...this.selected, stopReason: "stop" });
1193
+ }
1194
+ }
1195
+ export function parseCaptureLine(line) {
1196
+ return parseWireJson(line, LIMITS.frameBytes);
1197
+ }