@abelxiaoxing/cadence 1.8.3 → 2.0.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 (208) hide show
  1. package/README.md +324 -111
  2. package/THIRD_PARTY_NOTICES.md +15 -0
  3. package/agents/design-explorer.md +14 -26
  4. package/agents/diagnosis-worker.md +14 -25
  5. package/agents/implementation-worker.md +16 -35
  6. package/config/.env.example +2 -5
  7. package/config/workflow-task.example.json +7 -0
  8. package/docs/remote-access.md +60 -0
  9. package/docs/reuse-and-distribution.md +44 -0
  10. package/docs/service-management.md +108 -0
  11. package/licenses/bundled-web.txt +6245 -0
  12. package/licenses/pi-web-ui-MIT.txt +21 -0
  13. package/licenses/pi-web-ui-reuse.md +22 -0
  14. package/package.json +94 -21
  15. package/src/index.ts +22 -1807
  16. package/src/native-build.ts +6 -0
  17. package/src/native-client.ts +103 -0
  18. package/src/native-export.ts +58 -0
  19. package/src/native-history.ts +359 -0
  20. package/src/operator-cli.mjs +453 -1937
  21. package/src/plan-proposal.ts +87 -0
  22. package/src/sdk-worker.mjs +549 -0
  23. package/src/service/contracts/active.ts +82 -0
  24. package/src/service/contracts/budget.ts +148 -0
  25. package/src/service/contracts/build.ts +67 -0
  26. package/src/service/contracts/capture.ts +48 -0
  27. package/src/service/contracts/core.ts +33 -0
  28. package/src/service/contracts/current.ts +261 -0
  29. package/src/service/contracts/domain.ts +68 -0
  30. package/src/service/contracts/history.ts +2245 -0
  31. package/src/service/contracts/models.ts +139 -0
  32. package/src/service/coordination.ts +862 -0
  33. package/src/service/private-files.ts +204 -0
  34. package/src/service-cli.mjs +5592 -0
  35. package/src/service-client.ts +747 -0
  36. package/src/service-contract.ts +245 -0
  37. package/src/service-host.mjs +22382 -0
  38. package/src/service-http-client.ts +425 -0
  39. package/src/service-wire.ts +372 -0
  40. package/src/task-shell.ts +1045 -0
  41. package/src/task-store.ts +479 -0
  42. package/src/task-types.ts +184 -0
  43. package/src/verification-diagnostics.ts +29 -72
  44. package/src/worker-capture.mjs +1197 -0
  45. package/src/worker-public.mjs +1753 -0
  46. package/src/worker-redaction.mjs +608 -0
  47. package/src/worker-tools.mjs +202 -0
  48. package/web/dist/assets/KaTeX_AMS-Regular.ttf +0 -0
  49. package/web/dist/assets/KaTeX_AMS-Regular.woff +0 -0
  50. package/web/dist/assets/KaTeX_AMS-Regular.woff2 +0 -0
  51. package/web/dist/assets/KaTeX_Caligraphic-Bold.ttf +0 -0
  52. package/web/dist/assets/KaTeX_Caligraphic-Bold.woff +0 -0
  53. package/web/dist/assets/KaTeX_Caligraphic-Bold.woff2 +0 -0
  54. package/web/dist/assets/KaTeX_Caligraphic-Regular.ttf +0 -0
  55. package/web/dist/assets/KaTeX_Caligraphic-Regular.woff +0 -0
  56. package/web/dist/assets/KaTeX_Caligraphic-Regular.woff2 +0 -0
  57. package/web/dist/assets/KaTeX_Fraktur-Bold.ttf +0 -0
  58. package/web/dist/assets/KaTeX_Fraktur-Bold.woff +0 -0
  59. package/web/dist/assets/KaTeX_Fraktur-Bold.woff2 +0 -0
  60. package/web/dist/assets/KaTeX_Fraktur-Regular.ttf +0 -0
  61. package/web/dist/assets/KaTeX_Fraktur-Regular.woff +0 -0
  62. package/web/dist/assets/KaTeX_Fraktur-Regular.woff2 +0 -0
  63. package/web/dist/assets/KaTeX_Main-Bold.ttf +0 -0
  64. package/web/dist/assets/KaTeX_Main-Bold.woff +0 -0
  65. package/web/dist/assets/KaTeX_Main-Bold.woff2 +0 -0
  66. package/web/dist/assets/KaTeX_Main-BoldItalic.ttf +0 -0
  67. package/web/dist/assets/KaTeX_Main-BoldItalic.woff +0 -0
  68. package/web/dist/assets/KaTeX_Main-BoldItalic.woff2 +0 -0
  69. package/web/dist/assets/KaTeX_Main-Italic.ttf +0 -0
  70. package/web/dist/assets/KaTeX_Main-Italic.woff +0 -0
  71. package/web/dist/assets/KaTeX_Main-Italic.woff2 +0 -0
  72. package/web/dist/assets/KaTeX_Main-Regular.ttf +0 -0
  73. package/web/dist/assets/KaTeX_Main-Regular.woff +0 -0
  74. package/web/dist/assets/KaTeX_Main-Regular.woff2 +0 -0
  75. package/web/dist/assets/KaTeX_Math-BoldItalic.ttf +0 -0
  76. package/web/dist/assets/KaTeX_Math-BoldItalic.woff +0 -0
  77. package/web/dist/assets/KaTeX_Math-BoldItalic.woff2 +0 -0
  78. package/web/dist/assets/KaTeX_Math-Italic.ttf +0 -0
  79. package/web/dist/assets/KaTeX_Math-Italic.woff +0 -0
  80. package/web/dist/assets/KaTeX_Math-Italic.woff2 +0 -0
  81. package/web/dist/assets/KaTeX_SansSerif-Bold.ttf +0 -0
  82. package/web/dist/assets/KaTeX_SansSerif-Bold.woff +0 -0
  83. package/web/dist/assets/KaTeX_SansSerif-Bold.woff2 +0 -0
  84. package/web/dist/assets/KaTeX_SansSerif-Italic.ttf +0 -0
  85. package/web/dist/assets/KaTeX_SansSerif-Italic.woff +0 -0
  86. package/web/dist/assets/KaTeX_SansSerif-Italic.woff2 +0 -0
  87. package/web/dist/assets/KaTeX_SansSerif-Regular.ttf +0 -0
  88. package/web/dist/assets/KaTeX_SansSerif-Regular.woff +0 -0
  89. package/web/dist/assets/KaTeX_SansSerif-Regular.woff2 +0 -0
  90. package/web/dist/assets/KaTeX_Script-Regular.ttf +0 -0
  91. package/web/dist/assets/KaTeX_Script-Regular.woff +0 -0
  92. package/web/dist/assets/KaTeX_Script-Regular.woff2 +0 -0
  93. package/web/dist/assets/KaTeX_Size1-Regular.ttf +0 -0
  94. package/web/dist/assets/KaTeX_Size1-Regular.woff +0 -0
  95. package/web/dist/assets/KaTeX_Size1-Regular.woff2 +0 -0
  96. package/web/dist/assets/KaTeX_Size2-Regular.ttf +0 -0
  97. package/web/dist/assets/KaTeX_Size2-Regular.woff +0 -0
  98. package/web/dist/assets/KaTeX_Size2-Regular.woff2 +0 -0
  99. package/web/dist/assets/KaTeX_Size3-Regular.ttf +0 -0
  100. package/web/dist/assets/KaTeX_Size3-Regular.woff +0 -0
  101. package/web/dist/assets/KaTeX_Size3-Regular.woff2 +0 -0
  102. package/web/dist/assets/KaTeX_Size4-Regular.ttf +0 -0
  103. package/web/dist/assets/KaTeX_Size4-Regular.woff +0 -0
  104. package/web/dist/assets/KaTeX_Size4-Regular.woff2 +0 -0
  105. package/web/dist/assets/KaTeX_Typewriter-Regular.ttf +0 -0
  106. package/web/dist/assets/KaTeX_Typewriter-Regular.woff +0 -0
  107. package/web/dist/assets/KaTeX_Typewriter-Regular.woff2 +0 -0
  108. package/web/dist/assets/cadence.css +2 -0
  109. package/web/dist/assets/cadence.js +7 -0
  110. package/web/dist/assets/markdown.js +296 -0
  111. package/web/dist/assets/react.js +9 -0
  112. package/web/dist/assets/rolldown-runtime.js +1 -0
  113. package/web/dist/assets/timeline-client.js +41 -0
  114. package/web/dist/assets/vis-timeline.css +1274 -0
  115. package/web/dist/assets/vis-timeline.js +32 -0
  116. package/web/dist/index.html +18 -0
  117. package/web/dist/manifest.json +505 -0
  118. package/config/plan-draft.example.json +0 -125
  119. package/config/plan-draft.multiple-tasks.example.json +0 -375
  120. package/config/plan-draft.quick.example.json +0 -78
  121. package/config/routes.example.json +0 -39
  122. package/prompts/abel-design.md +0 -382
  123. package/prompts/abel-diagnose.md +0 -71
  124. package/prompts/abel-implement.md +0 -284
  125. package/prompts/abel-init.md +0 -52
  126. package/src/activation.ts +0 -44
  127. package/src/activity-contracts.ts +0 -82
  128. package/src/agent-registry.ts +0 -53
  129. package/src/apply-transaction.ts +0 -1437
  130. package/src/artifact-store.ts +0 -213
  131. package/src/build-windows-job.mjs +0 -95
  132. package/src/candidate-artifact.ts +0 -143
  133. package/src/candidate-patch.ts +0 -271
  134. package/src/candidate-workspace.ts +0 -80
  135. package/src/canonical.ts +0 -16
  136. package/src/change-contract-schema.ts +0 -191
  137. package/src/change-contract.ts +0 -324
  138. package/src/change-verification.ts +0 -1617
  139. package/src/child-budget.ts +0 -58
  140. package/src/child-model.ts +0 -142
  141. package/src/child-session.ts +0 -640
  142. package/src/contracts.ts +0 -2476
  143. package/src/control-contracts.ts +0 -382
  144. package/src/delivery-compiler.ts +0 -1805
  145. package/src/delivery-revision.ts +0 -42
  146. package/src/design-control.ts +0 -1299
  147. package/src/design-diagnostics.ts +0 -181
  148. package/src/design-journal.ts +0 -1773
  149. package/src/directory-sync.ts +0 -36
  150. package/src/durable-contracts.ts +0 -231
  151. package/src/durable-workflow.ts +0 -978
  152. package/src/evidence-draft.ts +0 -122
  153. package/src/execution-profile.ts +0 -64
  154. package/src/execution-retention.ts +0 -77
  155. package/src/file-snapshot.ts +0 -163
  156. package/src/implement-continuation.ts +0 -559
  157. package/src/implement-graph.ts +0 -690
  158. package/src/implement-plan.ts +0 -72
  159. package/src/install-config.d.mts +0 -6
  160. package/src/isolation-backend.ts +0 -353
  161. package/src/model-source.ts +0 -22
  162. package/src/openspec-cli.ts +0 -494
  163. package/src/operator-cli-entry.mjs +0 -24
  164. package/src/operator-tools.ts +0 -309
  165. package/src/package-candidate.ts +0 -227
  166. package/src/package-delivery.ts +0 -486
  167. package/src/package-state.ts +0 -320
  168. package/src/package-verification.ts +0 -635
  169. package/src/package-workflow.ts +0 -342
  170. package/src/packet-runtime.ts +0 -570
  171. package/src/parent-provider.ts +0 -375
  172. package/src/phase-execution.ts +0 -2259
  173. package/src/pi-adapter.ts +0 -19
  174. package/src/plan-draft-summary.ts +0 -527
  175. package/src/plan-draft.ts +0 -502
  176. package/src/remove-path.ts +0 -32
  177. package/src/route-policy.ts +0 -545
  178. package/src/run-state.ts +0 -420
  179. package/src/run-store.ts +0 -1179
  180. package/src/safe-path.ts +0 -77
  181. package/src/scoped-grep-worker.mjs +0 -23
  182. package/src/scoped-tools.ts +0 -775
  183. package/src/single-task-draft.ts +0 -142
  184. package/src/sqlite-schema.ts +0 -171
  185. package/src/state-root.ts +0 -215
  186. package/src/storage-schema.ts +0 -360
  187. package/src/subagent-activity.ts +0 -1417
  188. package/src/submit-tool.ts +0 -950
  189. package/src/task-ledger.ts +0 -1338
  190. package/src/transport-budget.ts +0 -52
  191. package/src/verification-capability.ts +0 -1191
  192. package/src/verification-environment-io.ts +0 -389
  193. package/src/verification-environment.ts +0 -162
  194. package/src/verification-identity.ts +0 -77
  195. package/src/verification-scan.ts +0 -64
  196. package/src/windows-job-backend.ts +0 -419
  197. package/src/windows-job.c +0 -149
  198. package/src/worker-broker.ts +0 -806
  199. package/src/workflow-engine.ts +0 -28
  200. package/src/workflow-policy.ts +0 -1679
  201. package/src/workflow-recovery-policy.ts +0 -97
  202. package/src/workflow-scheduling.ts +0 -105
  203. package/src/workflow-state-machine.ts +0 -4355
  204. package/src/workflow-status.ts +0 -576
  205. package/src/workspace-io-entry.mjs +0 -76
  206. package/src/workspace-io-worker.mjs +0 -1312
  207. package/src/workspace-io.ts +0 -89
  208. package/src/workspace-store.ts +0 -634
@@ -0,0 +1,1753 @@
1
+ /** Maintained portable codec source. Shared by ordinary JS workers and the service facade.
2
+ * Public types live solely in worker-public.d.mts; the TS contract paths are re-export shims.
3
+ * Initially relocated mechanically from W1 core/domain/capture; not a generated build output. */
4
+ /** Portable service boundary. No SDK objects, credentials, filesystem paths as IDs, or execution owner. */
5
+ export const SERVICE_PROTOCOL = 1;
6
+ export const WORKER_PROTOCOL = 2;
7
+ export const GRAPH_SCHEMA = "cadence-graph/2";
8
+ export const HISTORY_SCHEMA = "cadence-history/2";
9
+ export const EXPORT_SCHEMA = "cadence-public-export/2";
10
+ export const LIMITS = Object.freeze({
11
+ controlBytes: 1024 * 1024,
12
+ // Admission-owned encoded-data ceilings, including unresolved original waits.
13
+ admissionCount: 16,
14
+ admissionBytes: 32 * 1024 * 1024,
15
+ cancelBytes: 64 * 1024,
16
+ headerBytes: 8 * 1024,
17
+ wsClientFrameBytes: 16 * 1024,
18
+ startWaitMs: 10_000,
19
+ stopWaitMs: 60_000,
20
+ authWaitMs: 30_000,
21
+ authValidityMarginMs: 120_000,
22
+ browserLifetimeMs: 12 * 60 * 60 * 1000,
23
+ terminateGraceMs: 1000,
24
+ unconfirmedStopMs: 3000,
25
+ graphBytes: 512 * 1024,
26
+ grantMs: 120_000,
27
+ assignments: 16,
28
+ instructionsBytes: 16 * 1024,
29
+ expectedOutputBytes: 2048,
30
+ workerRequestBytes: 128 * 1024,
31
+ publicRequestBytes: 96 * 1024,
32
+ predecessorBytes: 16 * 1024,
33
+ handoffBytes: 32 * 1024,
34
+ frameBytes: 64 * 1024,
35
+ chunkBytes: 8 * 1024,
36
+ detailBytes: 32 * 1024 * 1024,
37
+ childProtocolBytes: 128 * 1024 * 1024,
38
+ dataFrames: 100_000,
39
+ controlFrames: 256,
40
+ sdkEvents: 1_000_000,
41
+ workerQueueBytes: 4 * 1024 * 1024,
42
+ workerQueueFrames: 1024,
43
+ ownerQueueBytes: 8 * 1024 * 1024,
44
+ ownerQueueFrames: 2048,
45
+ // Transform queue headroom, not the separate per-episode disk reservation.
46
+ ownerControlBytes: 1024 * 1024,
47
+ ownerControlFrames: 256,
48
+ recordingStallMs: 5000,
49
+ episodes: 8,
50
+ queuedAssignments: 128,
51
+ childReservations: 2,
52
+ episodeMs: 6 * 60 * 60 * 1000,
53
+ readyWaitMs: 10 * 60 * 1000,
54
+ workerMs: 1_200_000,
55
+ artifactPartBytes: 256 * 1024,
56
+ progressBatchMs: 100,
57
+ progressBatchBytes: 256 * 1024,
58
+ segmentBytes: 8 * 1024 * 1024,
59
+ segmentRecords: 4096,
60
+ checkoutQuotaBytes: 10 * 1024 * 1024 * 1024,
61
+ episodeReservationBytes: 512 * 1024 * 1024,
62
+ freeSpaceFloorBytes: 256 * 1024 * 1024,
63
+ episodeControlBytes: 1024 * 1024,
64
+ searchReaders: 2,
65
+ exportReaders: 2,
66
+ downloadIdleMs: 120_000,
67
+ pageEntries: 50,
68
+ maxPageEntries: 200,
69
+ pageBytes: 512 * 1024,
70
+ detailPageBytes: 256 * 1024,
71
+ previewBytes: 4096,
72
+ searchBytes: 8 * 1024 * 1024,
73
+ searchMs: 100,
74
+ queryBytes: 1024,
75
+ navigationBytes: 8192,
76
+ ringEvents: 1024,
77
+ ringBytes: 2 * 1024 * 1024,
78
+ viewers: 16,
79
+ viewerMessages: 256,
80
+ viewerBytes: 1024 * 1024,
81
+ heartbeatMs: 5000,
82
+ staleMs: 15_000,
83
+ reconcileMs: 30_000,
84
+ });
85
+ export const ERROR_CODES = [
86
+ "invalid",
87
+ "oversize",
88
+ "unauthenticated",
89
+ "forbidden",
90
+ "stale",
91
+ "conflict",
92
+ "corrupt-selected",
93
+ "expired-grant",
94
+ "consumed-grant",
95
+ "unsupported-context",
96
+ "quarantine",
97
+ "capacity",
98
+ "unavailable",
99
+ "auth-unavailable",
100
+ "recording-exhausted",
101
+ "receipt-inconclusive",
102
+ ];
103
+ export class ContractError extends Error {
104
+ code;
105
+ constructor(code = "invalid") {
106
+ super(code);
107
+ this.code = code;
108
+ }
109
+ }
110
+ export function publicError(code, effect = "none") {
111
+ return {
112
+ code,
113
+ effect,
114
+ recovery:
115
+ effect !== "none" || code === "receipt-inconclusive"
116
+ ? "observe"
117
+ : ["stale", "expired-grant", "consumed-grant"].includes(code)
118
+ ? "fresh-confirmation"
119
+ : "operator",
120
+ };
121
+ }
122
+ export function errorStatus(code) {
123
+ switch (code) {
124
+ case "invalid":
125
+ return 400;
126
+ case "oversize":
127
+ return 413;
128
+ case "unauthenticated":
129
+ return 401;
130
+ case "forbidden":
131
+ return 403;
132
+ case "stale":
133
+ case "conflict":
134
+ case "corrupt-selected":
135
+ case "consumed-grant":
136
+ return 409;
137
+ case "expired-grant":
138
+ return 410;
139
+ case "unsupported-context":
140
+ return 422;
141
+ case "quarantine":
142
+ return 423;
143
+ case "capacity":
144
+ return 429;
145
+ case "recording-exhausted":
146
+ return 507;
147
+ default:
148
+ return 503;
149
+ }
150
+ }
151
+ export function invalid() {
152
+ throw new ContractError();
153
+ }
154
+ export function text(v, max, nonempty = false) {
155
+ if (
156
+ typeof v !== "string" ||
157
+ v.includes("\0") ||
158
+ /[\uD800-\uDFFF]/u.test(v) ||
159
+ (nonempty && !v.trim())
160
+ )
161
+ invalid();
162
+ if (utf8Bytes(v) > max) throw new ContractError("oversize");
163
+ return v;
164
+ }
165
+ export function utf8Bytes(v) {
166
+ return new TextEncoder().encode(v).length;
167
+ }
168
+ export function integer(v, min = 0, max = Number.MAX_SAFE_INTEGER) {
169
+ if (typeof v !== "number" || !Number.isSafeInteger(v) || v < min || v > max)
170
+ invalid();
171
+ return v;
172
+ }
173
+ export function bool(v) {
174
+ if (typeof v !== "boolean") invalid();
175
+ return v;
176
+ }
177
+ export function oneOf(v, values) {
178
+ if (typeof v !== "string" || !values.includes(v)) invalid();
179
+ return v;
180
+ }
181
+ export function literal(v, expected) {
182
+ if (v !== expected) invalid();
183
+ return expected;
184
+ }
185
+ export function nullable(v, read) {
186
+ return v === null ? null : read(v);
187
+ }
188
+ // Descriptor reads prevent accessors/toJSON from becoming implicit public-boundary effects.
189
+ export function closed(v, keys) {
190
+ if (
191
+ v === null ||
192
+ typeof v !== "object" ||
193
+ Array.isArray(v) ||
194
+ ![null, Object.prototype].includes(Object.getPrototypeOf(v))
195
+ )
196
+ invalid();
197
+ const names = Reflect.ownKeys(v);
198
+ if (
199
+ names.length !== keys.length ||
200
+ names.some((k) => typeof k !== "string" || !keys.includes(k))
201
+ )
202
+ invalid();
203
+ const out = Object.create(null);
204
+ for (const k of keys) {
205
+ const d = Object.getOwnPropertyDescriptor(v, k);
206
+ if (!d || !("value" in d) || !d.enumerable) invalid();
207
+ out[k] = d.value;
208
+ }
209
+ return out;
210
+ }
211
+ export function list(v, max, read) {
212
+ if (
213
+ !Array.isArray(v) ||
214
+ v.length > max ||
215
+ Reflect.ownKeys(v).length !== v.length + 1
216
+ )
217
+ invalid();
218
+ const out = [];
219
+ for (let i = 0; i < v.length; i++) {
220
+ const d = Object.getOwnPropertyDescriptor(v, String(i));
221
+ if (!d || !("value" in d)) invalid();
222
+ out.push(read(d.value));
223
+ }
224
+ return out;
225
+ }
226
+ export function decodeId(v) {
227
+ const s = text(v, 36);
228
+ if (
229
+ !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(
230
+ s,
231
+ )
232
+ )
233
+ invalid();
234
+ return s;
235
+ }
236
+ export function decodeHash(v) {
237
+ const s = text(v, 64);
238
+ if (!/^[0-9a-f]{64}$/.test(s)) invalid();
239
+ return s;
240
+ }
241
+ export function decodeSequence(v) {
242
+ const s = text(v, LIMITS.controlBytes);
243
+ if (!/^(0|[1-9][0-9]*)$/.test(s)) invalid();
244
+ return s;
245
+ }
246
+ export function compareSequence(a, b) {
247
+ decodeSequence(a);
248
+ decodeSequence(b);
249
+ return a.length === b.length
250
+ ? a === b
251
+ ? 0
252
+ : a < b
253
+ ? -1
254
+ : 1
255
+ : a.length < b.length
256
+ ? -1
257
+ : 1;
258
+ }
259
+ export function assignmentId(v) {
260
+ const s = text(v, 48);
261
+ if (!/^[a-z][a-z0-9-]{0,47}$/.test(s)) invalid();
262
+ return s;
263
+ }
264
+ /** Deterministic identity of decoded credential-free DTOs; never use this on authentication data. */
265
+ export function canonicalJson(value, maximum = LIMITS.controlBytes) {
266
+ let remaining = maximum;
267
+ const charge = (s) => {
268
+ remaining -= utf8Bytes(s);
269
+ if (remaining < 0) throw new ContractError("oversize");
270
+ return s;
271
+ };
272
+ function visit(v, depth) {
273
+ if (depth > 64) invalid();
274
+ if (v === null || typeof v === "boolean") return charge(String(v));
275
+ if (typeof v === "string") {
276
+ text(v, maximum);
277
+ return charge(JSON.stringify(v));
278
+ }
279
+ if (typeof v === "number") {
280
+ if (!Number.isFinite(v)) invalid();
281
+ return charge(JSON.stringify(v));
282
+ }
283
+ if (Array.isArray(v)) {
284
+ const items = list(v, maximum, (x) => x);
285
+ charge(`[]${",".repeat(Math.max(0, items.length - 1))}`);
286
+ return `[${items.map((x) => visit(x, depth + 1)).join(",")}]`;
287
+ }
288
+ if (v && typeof v === "object") {
289
+ const keys = Reflect.ownKeys(v);
290
+ if (keys.some((k) => typeof k !== "string")) invalid();
291
+ const names = keys.sort();
292
+ const o = closed(v, names);
293
+ charge(`{}${",".repeat(Math.max(0, names.length - 1))}`);
294
+ return `{${names.map((k) => `${charge(`${JSON.stringify(k)}:`)}${visit(o[k], depth + 1)}`).join(",")}}`;
295
+ }
296
+ return invalid();
297
+ }
298
+ return visit(value, 0);
299
+ }
300
+ /** JSON.parse alone loses duplicate keys. All HTTP/worker text adapters must use this before a DTO decoder. */
301
+ export function parseWireJson(source, maximum = LIMITS.controlBytes) {
302
+ text(source, maximum);
303
+ let at = 0;
304
+ const ws = () => {
305
+ while (/[\x20\t\r\n]/.test(source[at] ?? "!")) at++;
306
+ };
307
+ function string() {
308
+ const start = at++;
309
+ let escaped = false;
310
+ while (at < source.length) {
311
+ const c = source[at++];
312
+ if (!escaped && c === '"') {
313
+ try {
314
+ const s = JSON.parse(source.slice(start, at));
315
+ return text(s, maximum);
316
+ } catch {
317
+ return invalid();
318
+ }
319
+ }
320
+ if (!escaped && c === "\\") escaped = true;
321
+ else escaped = false;
322
+ }
323
+ return invalid();
324
+ }
325
+ function value(depth) {
326
+ if (depth > 64) invalid();
327
+ ws();
328
+ if (source[at] === '"') return string();
329
+ if (source[at] === "{" || source[at] === "[") {
330
+ const object = source[at++] === "{";
331
+ const end = object ? "}" : "]";
332
+ const out = Object.create(null);
333
+ const arr = [];
334
+ const keys = new Set();
335
+ ws();
336
+ if (source[at] === end) {
337
+ at++;
338
+ return object ? out : arr;
339
+ }
340
+ for (;;) {
341
+ ws();
342
+ let key = "";
343
+ if (object) {
344
+ if (source[at] !== '"') invalid();
345
+ key = string();
346
+ if (keys.has(key)) invalid();
347
+ keys.add(key);
348
+ ws();
349
+ if (source[at++] !== ":") invalid();
350
+ }
351
+ const item = value(depth + 1);
352
+ if (object) out[key] = item;
353
+ else arr.push(item);
354
+ ws();
355
+ const c = source[at++];
356
+ if (c === end) break;
357
+ if (c !== ",") invalid();
358
+ }
359
+ return object ? out : arr;
360
+ }
361
+ const token =
362
+ /^(?:true|false|null|-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?)/.exec(
363
+ source.slice(at),
364
+ )?.[0];
365
+ if (!token) invalid();
366
+ at += token.length;
367
+ const result = JSON.parse(token);
368
+ if (typeof result === "number" && !Number.isFinite(result)) invalid();
369
+ return result;
370
+ }
371
+ const result = value(0);
372
+ ws();
373
+ if (at !== source.length) invalid();
374
+ return result;
375
+ }
376
+ export function decodePublicError(v) {
377
+ const o = closed(v, ["code", "effect", "recovery"]);
378
+ return {
379
+ code: oneOf(o.code, ERROR_CODES),
380
+ effect: oneOf(o.effect, ["none", "accepted", "uncertain"]),
381
+ recovery: oneOf(o.recovery, ["observe", "fresh-confirmation", "operator"]),
382
+ };
383
+ }
384
+ export const fields = [
385
+ "plan",
386
+ "context",
387
+ "message",
388
+ "final-text",
389
+ "tool-args",
390
+ "tool-update",
391
+ "tool-result",
392
+ "check",
393
+ "changes",
394
+ "review",
395
+ ];
396
+ export const outcomes = [
397
+ "completed",
398
+ "failed",
399
+ "canceled",
400
+ "timeout",
401
+ "unknown",
402
+ "blocked",
403
+ ];
404
+ export const closures = ["not-launched", "direct-child-closed", "unconfirmed"];
405
+ export const modelApis = [
406
+ "openai-completions",
407
+ "openai-responses",
408
+ "openai-codex-responses",
409
+ "anthropic-messages",
410
+ "google-generative-ai",
411
+ "mistral-conversations",
412
+ "azure-openai-responses",
413
+ ];
414
+ export const thinkingLevels = [
415
+ "off",
416
+ "minimal",
417
+ "low",
418
+ "medium",
419
+ "high",
420
+ "xhigh",
421
+ ];
422
+ export function decodeModelSelector(v) {
423
+ const o = closed(v, ["provider", "model", "api", "thinking"]);
424
+ return {
425
+ provider: text(o.provider, 128, true),
426
+ model: text(o.model, 256, true),
427
+ api: oneOf(o.api, modelApis),
428
+ thinking: oneOf(o.thinking, thinkingLevels),
429
+ };
430
+ }
431
+ export function decodeModelSelection(v) {
432
+ const o = closed(v, [
433
+ "sourceSelectionId",
434
+ "provider",
435
+ "model",
436
+ "api",
437
+ "thinking",
438
+ ]);
439
+ const { sourceSelectionId, ...selector } = o;
440
+ return {
441
+ sourceSelectionId: decodeId(sourceSelectionId),
442
+ ...decodeModelSelector(selector),
443
+ };
444
+ }
445
+ export function role(v) {
446
+ const o = closed(v, ["role", "sha256"]);
447
+ return {
448
+ role: oneOf(o.role, [
449
+ "design-explorer",
450
+ "implementation-worker",
451
+ "diagnosis-worker",
452
+ ]),
453
+ sha256: decodeHash(o.sha256),
454
+ };
455
+ }
456
+ export function roleForPurpose(purpose) {
457
+ return purpose === "edit"
458
+ ? "implementation-worker"
459
+ : purpose === "diagnosis"
460
+ ? "diagnosis-worker"
461
+ : "design-explorer";
462
+ }
463
+ export function decodeContentRef(v) {
464
+ const o = closed(v, ["recordId", "version", "field", "bytes", "sha256"]);
465
+ return {
466
+ recordId: decodeId(o.recordId),
467
+ version: integer(o.version, 1),
468
+ field: oneOf(o.field, fields),
469
+ bytes: integer(o.bytes, 0, LIMITS.detailBytes),
470
+ sha256: decodeHash(o.sha256),
471
+ };
472
+ }
473
+ export function range(v) {
474
+ const o = closed(v, ["start", "end"]);
475
+ const start = integer(o.start);
476
+ return { start, end: integer(o.end, start + 1, LIMITS.detailBytes) };
477
+ }
478
+ export function dependency(v) {
479
+ const o = closed(v, ["source", "range", "requireCompleteObservation"]);
480
+ const kind = tag(o.source);
481
+ let source;
482
+ if (kind === "current") {
483
+ const s = closed(o.source, ["kind", "assignmentId"]);
484
+ source = { kind, assignmentId: assignmentId(s.assignmentId) };
485
+ } else {
486
+ const s = closed(o.source, ["kind", "runId", "childRunId", "result"]);
487
+ literal(kind, "historical");
488
+ const result = decodeContentRef(s.result);
489
+ literal(result.field, "final-text");
490
+ source = {
491
+ kind: "historical",
492
+ runId: decodeId(s.runId),
493
+ childRunId: decodeId(s.childRunId),
494
+ result,
495
+ };
496
+ }
497
+ const selected = nullable(o.range, range);
498
+ if (
499
+ source.kind === "historical" &&
500
+ selected &&
501
+ selected.end > source.result.bytes
502
+ )
503
+ invalid();
504
+ return {
505
+ source,
506
+ range: selected,
507
+ requireCompleteObservation: bool(o.requireCompleteObservation),
508
+ };
509
+ }
510
+ export function tag(v, key = "kind") {
511
+ if (v === null || typeof v !== "object") invalid();
512
+ const d = Object.getOwnPropertyDescriptor(v, key);
513
+ if (!d || !("value" in d)) invalid();
514
+ return text(d.value, 64, true);
515
+ }
516
+ export function decodeGraph(v) {
517
+ canonicalJson(v, LIMITS.graphBytes);
518
+ const o = closed(v, [
519
+ "schema",
520
+ "taskId",
521
+ "taskKind",
522
+ "taskRevision",
523
+ "revision",
524
+ "planRevision",
525
+ "plan",
526
+ "assignments",
527
+ ]);
528
+ const plan = decodeContentRef(o.plan);
529
+ literal(plan.field, "plan");
530
+ const planRevision = integer(o.planRevision, 1);
531
+ if (plan.version !== planRevision) invalid();
532
+ const graph = {
533
+ schema: literal(o.schema, GRAPH_SCHEMA),
534
+ taskId: decodeId(o.taskId),
535
+ taskKind: oneOf(o.taskKind, ["code", "research", "diagnosis"]),
536
+ taskRevision: integer(o.taskRevision, 1),
537
+ revision: integer(o.revision, 1),
538
+ planRevision,
539
+ plan,
540
+ assignments: list(o.assignments, LIMITS.assignments, (v) => {
541
+ const a = closed(v, [
542
+ "id",
543
+ "purpose",
544
+ "instructions",
545
+ "expectedOutput",
546
+ "role",
547
+ "model",
548
+ "dependencies",
549
+ ]);
550
+ return {
551
+ id: assignmentId(a.id),
552
+ purpose: oneOf(a.purpose, ["research", "diagnosis", "review", "edit"]),
553
+ instructions: text(a.instructions, LIMITS.instructionsBytes, true),
554
+ expectedOutput: text(
555
+ a.expectedOutput,
556
+ LIMITS.expectedOutputBytes,
557
+ true,
558
+ ),
559
+ role: role(a.role),
560
+ model: decodeModelSelection(a.model),
561
+ dependencies: list(a.dependencies, LIMITS.assignments, dependency),
562
+ };
563
+ }),
564
+ };
565
+ if (!graph.assignments.length) invalid();
566
+ const ids = new Map(graph.assignments.map((a) => [a.id, a]));
567
+ if (ids.size !== graph.assignments.length) invalid();
568
+ const visiting = new Set();
569
+ const visited = new Set();
570
+ function visit(a) {
571
+ if (visiting.has(a.id)) invalid();
572
+ if (visited.has(a.id)) return;
573
+ visiting.add(a.id);
574
+ const seen = new Set();
575
+ for (const d of a.dependencies) {
576
+ const key = canonicalJson(d.source);
577
+ if (seen.has(key)) invalid();
578
+ seen.add(key);
579
+ if (d.source.kind === "current") {
580
+ const prior = ids.get(d.source.assignmentId);
581
+ if (!prior) invalid();
582
+ visit(prior);
583
+ }
584
+ }
585
+ visiting.delete(a.id);
586
+ visited.add(a.id);
587
+ }
588
+ for (const a of graph.assignments) {
589
+ if (graph.taskKind !== "code" && a.purpose === "edit")
590
+ throw new ContractError("forbidden");
591
+ if (a.role.role !== roleForPurpose(a.purpose))
592
+ throw new ContractError("forbidden");
593
+ visit(a);
594
+ }
595
+ return graph;
596
+ }
597
+ export function taskVersion(v) {
598
+ const o = closed(v, [
599
+ "id",
600
+ "kind",
601
+ "revision",
602
+ "identity",
603
+ "graphRevision",
604
+ "graphIdentity",
605
+ ]);
606
+ const graphRevision = nullable(o.graphRevision, (v) => integer(v, 1));
607
+ const graphIdentity = nullable(o.graphIdentity, decodeHash);
608
+ if ((graphRevision === null) !== (graphIdentity === null)) invalid();
609
+ return {
610
+ id: decodeId(o.id),
611
+ kind: oneOf(o.kind, ["code", "research", "diagnosis"]),
612
+ revision: integer(o.revision, 1),
613
+ identity: decodeHash(o.identity),
614
+ graphRevision,
615
+ graphIdentity,
616
+ };
617
+ }
618
+ export function decodeContext(v) {
619
+ const o = closed(v, [
620
+ "epoch",
621
+ "accessGeneration",
622
+ "configRev",
623
+ "controlRev",
624
+ "workspaceId",
625
+ "cwdId",
626
+ "model",
627
+ "checkEnvGeneration",
628
+ "checkoutGeneration",
629
+ "observation",
630
+ "task",
631
+ ]);
632
+ const obs = closed(o.observation, ["identity", "complete"]);
633
+ return {
634
+ epoch: decodeId(o.epoch),
635
+ accessGeneration: integer(o.accessGeneration, 1),
636
+ configRev: integer(o.configRev, 1),
637
+ controlRev: integer(o.controlRev, 1),
638
+ workspaceId: decodeId(o.workspaceId),
639
+ cwdId: decodeId(o.cwdId),
640
+ model: decodeModelSelection(o.model),
641
+ checkEnvGeneration: integer(o.checkEnvGeneration, 1),
642
+ checkoutGeneration: integer(o.checkoutGeneration),
643
+ observation: {
644
+ identity: decodeHash(obs.identity),
645
+ complete: bool(obs.complete),
646
+ },
647
+ task: nullable(o.task, taskVersion),
648
+ };
649
+ }
650
+ export function checkSelection(v) {
651
+ const o = closed(v, ["kind", "name", "command", "timeoutMs"]);
652
+ const result = {
653
+ kind: oneOf(o.kind, ["configured", "manual"]),
654
+ name: text(o.name, 128, true),
655
+ command: text(o.command, 4096, true),
656
+ timeoutMs: integer(o.timeoutMs, 100, LIMITS.workerMs),
657
+ };
658
+ // Same visible-command policy as task-types; that legacy decoder uses Node Buffer and permits extra keys.
659
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: executable confirmations must be visibly representable
660
+ const controls = /[\x00-\x08\x0b-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]/u;
661
+ if (
662
+ controls.test(result.name) ||
663
+ controls.test(result.command) ||
664
+ /[\n\t]/.test(result.name) ||
665
+ result.name === "Manual command"
666
+ )
667
+ invalid();
668
+ if (
669
+ result.kind === "manual" &&
670
+ (result.name !== "Manual" || result.timeoutMs !== 120_000)
671
+ )
672
+ invalid();
673
+ return result;
674
+ }
675
+ export function decodeAction(v) {
676
+ canonicalJson(v);
677
+ switch (tag(v)) {
678
+ case "create": {
679
+ const o = closed(v, ["kind", "taskKind", "goal"]);
680
+ return {
681
+ kind: "create",
682
+ taskKind: oneOf(o.taskKind, ["code", "research", "diagnosis"]),
683
+ goal: text(o.goal, 8192, true),
684
+ };
685
+ }
686
+ case "save-plan": {
687
+ const o = closed(v, ["kind", "taskId", "plan", "graph"]);
688
+ const graph = decodeGraph(o.graph);
689
+ const taskId = decodeId(o.taskId);
690
+ if (graph.taskId !== taskId) invalid();
691
+ return { kind: "save-plan", taskId, plan: text(o.plan, 32768), graph };
692
+ }
693
+ case "generate-plan":
694
+ case "start": {
695
+ const kind = tag(v);
696
+ const o = closed(v, ["kind", "taskId"]);
697
+ return { kind, taskId: decodeId(o.taskId) };
698
+ }
699
+ case "check": {
700
+ const o = closed(v, ["kind", "taskId", "check"]);
701
+ return {
702
+ kind: "check",
703
+ taskId: decodeId(o.taskId),
704
+ check: checkSelection(o.check),
705
+ };
706
+ }
707
+ case "review": {
708
+ const o = closed(v, [
709
+ "kind",
710
+ "taskId",
711
+ "runId",
712
+ "changesIdentity",
713
+ "checksRevision",
714
+ "acceptIssues",
715
+ ]);
716
+ return {
717
+ kind: "review",
718
+ taskId: decodeId(o.taskId),
719
+ runId: decodeId(o.runId),
720
+ changesIdentity: decodeHash(o.changesIdentity),
721
+ checksRevision: integer(o.checksRevision),
722
+ acceptIssues: bool(o.acceptIssues),
723
+ };
724
+ }
725
+ default:
726
+ return invalid();
727
+ }
728
+ }
729
+ export function decodePreflightRequest(v) {
730
+ canonicalJson(v);
731
+ const o = closed(v, ["expected", "action"]);
732
+ return {
733
+ expected: decodeContext(o.expected),
734
+ action: decodeAction(o.action),
735
+ };
736
+ }
737
+ export function decodeCommand(v) {
738
+ canonicalJson(v);
739
+ const o = closed(v, ["commandId", "grant", "expected", "action"]);
740
+ return {
741
+ commandId: decodeId(o.commandId),
742
+ grant: decodeId(o.grant),
743
+ expected: decodeContext(o.expected),
744
+ action: decodeAction(o.action),
745
+ };
746
+ }
747
+ export function decodeCommandIdentity(v) {
748
+ canonicalJson(v);
749
+ if (tag(v) === "action") {
750
+ const o = closed(v, ["kind", "expected", "action"]);
751
+ return {
752
+ kind: "action",
753
+ expected: decodeContext(o.expected),
754
+ action: decodeAction(o.action),
755
+ };
756
+ }
757
+ const o = closed(v, ["kind", "epoch", "runId"]);
758
+ literal(o.kind, "cancel");
759
+ return { kind: "cancel", epoch: decodeId(o.epoch), runId: decodeId(o.runId) };
760
+ }
761
+ export function decodeCancel(v) {
762
+ const o = closed(v, ["commandId", "epoch", "runId"]);
763
+ return {
764
+ commandId: decodeId(o.commandId),
765
+ epoch: decodeId(o.epoch),
766
+ runId: decodeId(o.runId),
767
+ };
768
+ }
769
+ export function decodePreview(v) {
770
+ canonicalJson(v);
771
+ const hasCheckPolicy =
772
+ typeof v === "object" &&
773
+ v !== null &&
774
+ Object.hasOwn(v, "checkEnvironmentPolicy");
775
+ const o = closed(v, [
776
+ "version",
777
+ "action",
778
+ "rootLabel",
779
+ "cwdLabel",
780
+ "readablePlan",
781
+ "graph",
782
+ "activeRunId",
783
+ "issues",
784
+ "configuredChecks",
785
+ "checksRevision",
786
+ "reviewRunId",
787
+ ...(hasCheckPolicy ? ["checkEnvironmentPolicy"] : []),
788
+ ]);
789
+ const configuredChecks = list(o.configuredChecks, 32, checkSelection);
790
+ if (
791
+ configuredChecks.some((check) => check.kind !== "configured") ||
792
+ new Set(configuredChecks.map((check) => check.name)).size !==
793
+ configuredChecks.length
794
+ )
795
+ invalid();
796
+ return {
797
+ ...(hasCheckPolicy
798
+ ? {
799
+ checkEnvironmentPolicy: literal(
800
+ o.checkEnvironmentPolicy,
801
+ "service-launch-ordinary/1",
802
+ ),
803
+ }
804
+ : {}),
805
+ configuredChecks,
806
+ checksRevision: integer(o.checksRevision),
807
+ reviewRunId: nullable(o.reviewRunId, decodeId),
808
+ version: decodeContext(o.version),
809
+ action: decodeAction(o.action),
810
+ rootLabel: text(o.rootLabel, 4096, true),
811
+ cwdLabel: text(o.cwdLabel, 4096, true),
812
+ readablePlan: text(o.readablePlan, 32768),
813
+ graph: nullable(o.graph, decodeGraph),
814
+ activeRunId: nullable(o.activeRunId, decodeId),
815
+ issues: list(o.issues, 7, (v) =>
816
+ oneOf(v, [
817
+ "incomplete-observation",
818
+ "unrun-checks",
819
+ "stale-checks",
820
+ "failed-checks",
821
+ "partial-results",
822
+ "recording-incomplete",
823
+ "legacy-context",
824
+ ]),
825
+ ),
826
+ };
827
+ }
828
+ export function decodePreflight(v) {
829
+ canonicalJson(v);
830
+ const o = closed(v, ["grant", "expiresAt", "preview"]);
831
+ const expiresAt = text(o.expiresAt, 24);
832
+ if (
833
+ !/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/.test(expiresAt) ||
834
+ !Number.isFinite(Date.parse(expiresAt)) ||
835
+ new Date(expiresAt).toISOString() !== expiresAt
836
+ )
837
+ invalid();
838
+ return {
839
+ grant: decodeId(o.grant),
840
+ expiresAt,
841
+ preview: decodePreview(o.preview),
842
+ };
843
+ }
844
+ export function decodeCoverage(v) {
845
+ const o = closed(v, ["observed", "source", "redacted", "omissions"]);
846
+ const result = {
847
+ observed: oneOf(o.observed, ["complete", "incomplete"]),
848
+ source: oneOf(o.source, ["complete", "limited", "unavailable"]),
849
+ redacted: bool(o.redacted),
850
+ omissions: list(o.omissions, 6, (v) =>
851
+ oneOf(v, [
852
+ "binary",
853
+ "hidden-thinking",
854
+ "source-limit",
855
+ "capture-limit",
856
+ "gap",
857
+ "unsupported",
858
+ ]),
859
+ ),
860
+ };
861
+ if (
862
+ new Set(result.omissions).size !== result.omissions.length ||
863
+ (result.observed === "complete" &&
864
+ result.omissions.some((x) => x === "capture-limit" || x === "gap"))
865
+ )
866
+ invalid();
867
+ return result;
868
+ }
869
+ export function decodeHandoff(v) {
870
+ const o = closed(v, ["graphRevision", "inputs"]);
871
+ let total = 0;
872
+ const seen = new Set();
873
+ return {
874
+ graphRevision: integer(o.graphRevision, 1),
875
+ inputs: list(o.inputs, LIMITS.assignments, (v) => {
876
+ const i = closed(v, [
877
+ "assignmentId",
878
+ "dependencyIndex",
879
+ "runId",
880
+ "childRunId",
881
+ "result",
882
+ "range",
883
+ "text",
884
+ "coverage",
885
+ ]);
886
+ const result = decodeContentRef(i.result);
887
+ literal(result.field, "final-text");
888
+ const selected = nullable(i.range, range);
889
+ if (selected && selected.end > result.bytes) invalid();
890
+ const supplied = text(i.text, LIMITS.predecessorBytes);
891
+ total += utf8Bytes(supplied);
892
+ if (total > LIMITS.handoffBytes) throw new ContractError("oversize");
893
+ const dependencyIndex = integer(
894
+ i.dependencyIndex,
895
+ 0,
896
+ LIMITS.assignments - 1,
897
+ );
898
+ if (seen.has(dependencyIndex)) invalid();
899
+ seen.add(dependencyIndex);
900
+ // Range is in the committed sanitized source, not raw wire data. No clipping/synthesis allowed.
901
+ if (
902
+ utf8Bytes(supplied) !==
903
+ (selected ? selected.end - selected.start : result.bytes)
904
+ )
905
+ invalid();
906
+ return {
907
+ assignmentId: assignmentId(i.assignmentId),
908
+ dependencyIndex,
909
+ runId: decodeId(i.runId),
910
+ childRunId: decodeId(i.childRunId),
911
+ result,
912
+ range: selected,
913
+ text: supplied,
914
+ coverage: decodeCoverage(i.coverage),
915
+ };
916
+ }),
917
+ };
918
+ }
919
+ export function decodeWorkerPublicRequest(v) {
920
+ canonicalJson(v, LIMITS.publicRequestBytes);
921
+ const o = closed(v, [
922
+ "protocol",
923
+ "taskId",
924
+ "taskKind",
925
+ "runId",
926
+ "childRunId",
927
+ "assignmentId",
928
+ "purpose",
929
+ "model",
930
+ "role",
931
+ "context",
932
+ "instructions",
933
+ "prompt",
934
+ "handoff",
935
+ ]);
936
+ const result = {
937
+ protocol: literal(o.protocol, WORKER_PROTOCOL),
938
+ taskId: decodeId(o.taskId),
939
+ taskKind: oneOf(o.taskKind, ["code", "research", "diagnosis"]),
940
+ runId: decodeId(o.runId),
941
+ childRunId: decodeId(o.childRunId),
942
+ assignmentId: assignmentId(o.assignmentId),
943
+ purpose: oneOf(o.purpose, ["research", "diagnosis", "review", "edit"]),
944
+ model: decodeModelSelection(o.model),
945
+ role: role(o.role),
946
+ context: text(o.context, 32768),
947
+ instructions: text(o.instructions, LIMITS.instructionsBytes, true),
948
+ prompt: text(o.prompt, 32768, true),
949
+ handoff: decodeHandoff(o.handoff),
950
+ };
951
+ if (result.handoff.inputs.some((i) => i.assignmentId !== result.assignmentId))
952
+ invalid();
953
+ if (
954
+ (result.taskKind !== "code" && result.purpose === "edit") ||
955
+ result.role.role !== roleForPurpose(result.purpose)
956
+ )
957
+ throw new ContractError("forbidden");
958
+ return result;
959
+ }
960
+ /** Enforce on the actual serialized anonymous-stdin envelope AFTER owner-only auth insertion. Never log/return it. */
961
+ export function assertWorkerEnvelopeSize(serialized) {
962
+ if (utf8Bytes(serialized) > LIMITS.workerRequestBytes)
963
+ throw new ContractError("oversize");
964
+ }
965
+ export function decodeNativeSettlement(v) {
966
+ const o = closed(v, [
967
+ "outcome",
968
+ "closure",
969
+ "exitCode",
970
+ "signal",
971
+ "durationMs",
972
+ "stdin",
973
+ "final",
974
+ "cleanup",
975
+ "capture",
976
+ ]);
977
+ const r = {
978
+ outcome: oneOf(o.outcome, [
979
+ "completed",
980
+ "failed",
981
+ "canceled",
982
+ "timeout",
983
+ "unknown",
984
+ ]),
985
+ closure: oneOf(o.closure, closures),
986
+ // Windows reports DWORD exit statuses (including native exception codes).
987
+ // Retain the observed number rather than truncating/sign-coercing it.
988
+ exitCode: nullable(o.exitCode, (v) => integer(v, -2147483648, 4294967295)),
989
+ signal: nullable(o.signal, (v) => text(v, 32, true)),
990
+ durationMs: integer(o.durationMs),
991
+ stdin: oneOf(o.stdin, ["delivered", "failed", "not-required"]),
992
+ final: oneOf(o.final, ["valid", "missing", "invalid"]),
993
+ cleanup: oneOf(o.cleanup, ["settled", "failed", "unconfirmed"]),
994
+ capture: decodeCoverage(o.capture),
995
+ };
996
+ if (
997
+ r.closure === "not-launched" &&
998
+ (r.exitCode !== null || r.signal !== null)
999
+ )
1000
+ invalid();
1001
+ if (
1002
+ r.outcome === "completed" &&
1003
+ (r.closure !== "direct-child-closed" ||
1004
+ r.exitCode !== 0 ||
1005
+ r.signal !== null ||
1006
+ r.stdin !== "delivered" ||
1007
+ r.final !== "valid" ||
1008
+ r.cleanup !== "settled" ||
1009
+ r.capture.observed !== "complete")
1010
+ )
1011
+ invalid();
1012
+ return r;
1013
+ }
1014
+ export function decodeScope(v) {
1015
+ const o = closed(v, ["kind", "id"]);
1016
+ return { kind: oneOf(o.kind, ["task", "run", "child"]), id: decodeId(o.id) };
1017
+ }
1018
+ /** Opaque structural bound only. History authenticates progress after access checks. */
1019
+ export function decodeNavigation(v) {
1020
+ const value = text(v, LIMITS.navigationBytes, true);
1021
+ if (!/^[\x21-\x7e]+$/.test(value)) invalid();
1022
+ return value;
1023
+ }
1024
+ export function decodeCursor(v) {
1025
+ canonicalJson(v);
1026
+ const o = closed(v, [
1027
+ "storeId",
1028
+ "scope",
1029
+ "query",
1030
+ "snapshotSeq",
1031
+ "recordId",
1032
+ "recordVersion",
1033
+ "field",
1034
+ "offset",
1035
+ ...(Object.hasOwn(v ?? {}, "navigation") ? ["navigation"] : []),
1036
+ ]);
1037
+ const r = {
1038
+ storeId: decodeId(o.storeId),
1039
+ scope: decodeScope(o.scope),
1040
+ query: nullable(o.query, (v) => {
1041
+ const q = text(v, LIMITS.queryBytes);
1042
+ if (!q.length) invalid();
1043
+ return q;
1044
+ }),
1045
+ snapshotSeq: decodeSequence(o.snapshotSeq),
1046
+ recordId: nullable(o.recordId, decodeId),
1047
+ recordVersion: nullable(o.recordVersion, (v) => integer(v, 1)),
1048
+ field: nullable(o.field, (v) => oneOf(v, fields)),
1049
+ offset: integer(o.offset),
1050
+ ...(Object.hasOwn(o, "navigation")
1051
+ ? { navigation: decodeNavigation(o.navigation) }
1052
+ : {}),
1053
+ };
1054
+ if (
1055
+ (r.recordId === null) !== (r.recordVersion === null) ||
1056
+ (r.recordId === null) !== (r.field === null)
1057
+ )
1058
+ invalid();
1059
+ return r;
1060
+ }
1061
+ export function decodeSourceIdentity(v) {
1062
+ const o = closed(v, ["disposition", "value"]);
1063
+ const disposition = oneOf(o.disposition, [
1064
+ "observed",
1065
+ "unavailable",
1066
+ "redacted",
1067
+ ]);
1068
+ const value = sourceId(o.value);
1069
+ if ((disposition === "observed") !== (value !== null)) invalid();
1070
+ return { disposition, value };
1071
+ }
1072
+ export function callLink(v) {
1073
+ const o = closed(v, ["messageId", "blockId"]);
1074
+ return { messageId: decodeId(o.messageId), blockId: decodeId(o.blockId) };
1075
+ }
1076
+ export function decodeContentOwner(v) {
1077
+ const kind = tag(v);
1078
+ if (kind === "message-final") {
1079
+ const o = closed(v, ["kind", "messageId"]);
1080
+ return { kind, messageId: decodeId(o.messageId) };
1081
+ }
1082
+ if (kind === "context") {
1083
+ const o = closed(v, ["kind", "component"]);
1084
+ return {
1085
+ kind,
1086
+ component: oneOf(o.component, [
1087
+ "request-context",
1088
+ "request-prompt",
1089
+ "request-instructions",
1090
+ "role",
1091
+ "effective-system",
1092
+ ]),
1093
+ };
1094
+ }
1095
+ if (kind === "handoff") {
1096
+ const o = closed(v, ["kind", "dependencyIndex", "source"]);
1097
+ const source = decodeContentRef(o.source);
1098
+ literal(source.field, "final-text");
1099
+ return {
1100
+ kind,
1101
+ dependencyIndex: integer(o.dependencyIndex, 0, LIMITS.assignments - 1),
1102
+ source,
1103
+ };
1104
+ }
1105
+ if (kind === "message") {
1106
+ const o = closed(v, ["kind", "messageId", "blockId", "index", "stage"]);
1107
+ return {
1108
+ kind,
1109
+ messageId: decodeId(o.messageId),
1110
+ blockId: decodeId(o.blockId),
1111
+ index: integer(o.index, 0, LIMITS.dataFrames),
1112
+ stage: oneOf(o.stage, ["stream", "final"]),
1113
+ };
1114
+ }
1115
+ const o = closed(v, ["kind", "callId", "blockId", "index", "stage"]);
1116
+ literal(kind, "tool");
1117
+ return {
1118
+ kind: "tool",
1119
+ callId: decodeId(o.callId),
1120
+ blockId: decodeId(o.blockId),
1121
+ index: integer(o.index, 0, LIMITS.dataFrames),
1122
+ stage: oneOf(o.stage, [
1123
+ "arguments-partial",
1124
+ "arguments-final",
1125
+ "execution-arguments",
1126
+ "update-snapshot",
1127
+ "result",
1128
+ ]),
1129
+ };
1130
+ }
1131
+ export function decodeDetailDescriptor(v) {
1132
+ const o = closed(v, ["owner", "field", "encoding"]);
1133
+ const owner = decodeContentOwner(o.owner);
1134
+ const field = oneOf(o.field, [
1135
+ "context",
1136
+ "message",
1137
+ "final-text",
1138
+ "tool-args",
1139
+ "tool-update",
1140
+ "tool-result",
1141
+ ]);
1142
+ const encoding = oneOf(o.encoding, ["utf8", "canonical-json"]);
1143
+ const expected =
1144
+ owner.kind === "context" || owner.kind === "handoff"
1145
+ ? "context"
1146
+ : owner.kind === "message-final"
1147
+ ? "final-text"
1148
+ : owner.kind === "message"
1149
+ ? "message"
1150
+ : owner.stage === "result"
1151
+ ? "tool-result"
1152
+ : owner.stage === "update-snapshot"
1153
+ ? "tool-update"
1154
+ : "tool-args";
1155
+ if (
1156
+ field !== expected ||
1157
+ (owner.kind !== "tool" && encoding !== "utf8") ||
1158
+ (field === "tool-args" &&
1159
+ encoding !== "canonical-json" &&
1160
+ !(owner.kind === "tool" && owner.stage === "arguments-partial"))
1161
+ )
1162
+ invalid();
1163
+ // JSON bodies are sanitized canonical ordinary tool data, rendered as data;
1164
+ // they are NOT an additional object/protocol interpreted by readers.
1165
+ return { owner, field, encoding };
1166
+ }
1167
+ export function decodeOmittedBlock(v) {
1168
+ const o = closed(v, ["owner", "sourceType", "mimeType", "reason"]);
1169
+ const sourceType = oneOf(o.sourceType, [
1170
+ "image",
1171
+ "audio",
1172
+ "binary",
1173
+ "hidden-thinking",
1174
+ "unsupported",
1175
+ ]);
1176
+ const reason = oneOf(o.reason, ["binary", "hidden-thinking", "unsupported"]);
1177
+ const mimeType = nullable(o.mimeType, (v) => text(v, 128, true));
1178
+ if (
1179
+ reason !==
1180
+ (sourceType === "hidden-thinking"
1181
+ ? "hidden-thinking"
1182
+ : sourceType === "unsupported"
1183
+ ? "unsupported"
1184
+ : "binary") ||
1185
+ (mimeType !== null &&
1186
+ (sourceType === "hidden-thinking" ||
1187
+ !/^[a-z0-9.+-]+\/[a-z0-9.+-]+$/i.test(mimeType)))
1188
+ )
1189
+ invalid();
1190
+ return { owner: decodeContentOwner(o.owner), sourceType, mimeType, reason };
1191
+ }
1192
+ function sourceId(v) {
1193
+ if (v === null) return null;
1194
+ const s = text(v, 128, true);
1195
+ if (!/^[a-zA-Z0-9_-]+$/.test(s)) invalid();
1196
+ return s;
1197
+ }
1198
+ export function decodeCaptureEvent(v) {
1199
+ const kind = tag(v);
1200
+ switch (kind) {
1201
+ case "ready": {
1202
+ const o = closed(v, ["kind", "requestProtocol"]);
1203
+ return {
1204
+ kind,
1205
+ requestProtocol: literal(o.requestProtocol, WORKER_PROTOCOL),
1206
+ };
1207
+ }
1208
+ case "message-start": {
1209
+ const o = closed(v, [
1210
+ "kind",
1211
+ "messageId",
1212
+ "role",
1213
+ "source",
1214
+ "resultCallId",
1215
+ ]);
1216
+ const role = oneOf(o.role, ["user", "assistant", "tool-result"]);
1217
+ const resultCallId = nullable(o.resultCallId, decodeId);
1218
+ if (role !== "tool-result" && resultCallId !== null) invalid();
1219
+ return {
1220
+ kind,
1221
+ messageId: decodeId(o.messageId),
1222
+ role,
1223
+ source: decodeSourceIdentity(o.source),
1224
+ resultCallId,
1225
+ };
1226
+ }
1227
+ case "message-text": {
1228
+ const o = closed(v, ["kind", "messageId", "blockId", "detailId"]);
1229
+ return {
1230
+ kind,
1231
+ ...callLink({ messageId: o.messageId, blockId: o.blockId }),
1232
+ detailId: decodeId(o.detailId),
1233
+ };
1234
+ }
1235
+ case "message-end": {
1236
+ const o = closed(v, [
1237
+ "kind",
1238
+ "messageId",
1239
+ "finalDetailId",
1240
+ "finalBlockCount",
1241
+ "stopReason",
1242
+ ]);
1243
+ return {
1244
+ kind,
1245
+ messageId: decodeId(o.messageId),
1246
+ finalDetailId: nullable(o.finalDetailId, decodeId),
1247
+ finalBlockCount: integer(o.finalBlockCount, 0, LIMITS.dataFrames),
1248
+ stopReason: oneOf(o.stopReason, [
1249
+ "stop",
1250
+ "length",
1251
+ "toolUse",
1252
+ "error",
1253
+ "aborted",
1254
+ "unknown",
1255
+ ]),
1256
+ };
1257
+ }
1258
+ case "call-declaration": {
1259
+ const o = closed(v, [
1260
+ "kind",
1261
+ "callId",
1262
+ "declaration",
1263
+ "index",
1264
+ "source",
1265
+ "name",
1266
+ "argsDetailId",
1267
+ "stage",
1268
+ ]);
1269
+ return {
1270
+ kind,
1271
+ callId: decodeId(o.callId),
1272
+ declaration: callLink(o.declaration),
1273
+ index: integer(o.index, 0, LIMITS.dataFrames),
1274
+ source: decodeSourceIdentity(o.source),
1275
+ name: text(o.name, 128, true),
1276
+ argsDetailId: nullable(o.argsDetailId, decodeId),
1277
+ stage: oneOf(o.stage, ["partial", "final"]),
1278
+ };
1279
+ }
1280
+ case "tool-start": {
1281
+ const o = closed(v, [
1282
+ "kind",
1283
+ "callId",
1284
+ "declaration",
1285
+ "source",
1286
+ "name",
1287
+ "argsDetailId",
1288
+ ]);
1289
+ return {
1290
+ kind,
1291
+ callId: decodeId(o.callId),
1292
+ declaration: nullable(o.declaration, callLink),
1293
+ source: decodeSourceIdentity(o.source),
1294
+ name: text(o.name, 128, true),
1295
+ argsDetailId: nullable(o.argsDetailId, decodeId),
1296
+ };
1297
+ }
1298
+ case "tool-update": {
1299
+ const o = closed(v, ["kind", "callId", "detailId", "semantics"]);
1300
+ return {
1301
+ kind,
1302
+ callId: decodeId(o.callId),
1303
+ detailId: decodeId(o.detailId),
1304
+ semantics: literal(o.semantics, "snapshot"),
1305
+ };
1306
+ }
1307
+ case "tool-end": {
1308
+ const o = closed(v, [
1309
+ "kind",
1310
+ "callId",
1311
+ "declaration",
1312
+ "source",
1313
+ "name",
1314
+ "resultDetailId",
1315
+ "isError",
1316
+ "association",
1317
+ "startObserved",
1318
+ ]);
1319
+ const association = oneOf(o.association, [
1320
+ "declared",
1321
+ "execution-only",
1322
+ "orphan",
1323
+ "ambiguous",
1324
+ ]);
1325
+ const declaration = nullable(o.declaration, callLink);
1326
+ const startObserved = bool(o.startObserved);
1327
+ if (
1328
+ (association === "declared") !== (declaration !== null) ||
1329
+ (association === "execution-only" && !startObserved) ||
1330
+ ((association === "orphan" || association === "ambiguous") &&
1331
+ startObserved)
1332
+ )
1333
+ invalid();
1334
+ return {
1335
+ kind,
1336
+ callId: decodeId(o.callId),
1337
+ declaration,
1338
+ source: decodeSourceIdentity(o.source),
1339
+ name: text(o.name, 128, true),
1340
+ resultDetailId: decodeId(o.resultDetailId),
1341
+ isError: bool(o.isError),
1342
+ association,
1343
+ startObserved,
1344
+ };
1345
+ }
1346
+ case "omitted-block": {
1347
+ const o = closed(v, ["kind", "block"]);
1348
+ return { kind, block: decodeOmittedBlock(o.block) };
1349
+ }
1350
+ case "detail-begin": {
1351
+ const o = closed(v, ["kind", "detailId", "descriptor"]);
1352
+ return {
1353
+ kind,
1354
+ detailId: decodeId(o.detailId),
1355
+ descriptor: decodeDetailDescriptor(o.descriptor),
1356
+ };
1357
+ }
1358
+ case "detail-chunk": {
1359
+ const o = closed(v, ["kind", "detailId", "offset", "text"]);
1360
+ const chunk = text(o.text, LIMITS.chunkBytes);
1361
+ const offset = integer(o.offset, 0, LIMITS.detailBytes);
1362
+ if (offset + utf8Bytes(chunk) > LIMITS.detailBytes) invalid();
1363
+ return { kind, detailId: decodeId(o.detailId), offset, text: chunk };
1364
+ }
1365
+ case "detail-end": {
1366
+ const o = closed(v, ["kind", "detailId", "bytes", "sha256", "coverage"]);
1367
+ return {
1368
+ kind,
1369
+ detailId: decodeId(o.detailId),
1370
+ bytes: integer(o.bytes, 0, LIMITS.detailBytes),
1371
+ sha256: decodeHash(o.sha256),
1372
+ coverage: decodeCoverage(o.coverage),
1373
+ };
1374
+ }
1375
+ case "capture-status": {
1376
+ const o = closed(v, ["kind", "coverage"]);
1377
+ return { kind, coverage: decodeCoverage(o.coverage) };
1378
+ }
1379
+ case "worker-failure": {
1380
+ const o = closed(v, ["kind", "code"]);
1381
+ return {
1382
+ kind,
1383
+ code: oneOf(o.code, [
1384
+ "protocol",
1385
+ "capture",
1386
+ "model",
1387
+ "auth",
1388
+ "network",
1389
+ "cleanup",
1390
+ "prompt",
1391
+ ]),
1392
+ };
1393
+ }
1394
+ case "final": {
1395
+ const o = closed(v, ["kind", "messageId", "detailId", "stopReason"]);
1396
+ return {
1397
+ kind,
1398
+ messageId: decodeId(o.messageId),
1399
+ detailId: decodeId(o.detailId),
1400
+ stopReason: literal(o.stopReason, "stop"),
1401
+ };
1402
+ }
1403
+ default:
1404
+ return invalid();
1405
+ }
1406
+ }
1407
+ export function decodeCaptureFrame(v) {
1408
+ canonicalJson(v, LIMITS.frameBytes);
1409
+ const o = closed(v, [
1410
+ "protocol",
1411
+ "childRunId",
1412
+ "workerSeq",
1413
+ "observedMs",
1414
+ "event",
1415
+ ]);
1416
+ return {
1417
+ protocol: literal(o.protocol, WORKER_PROTOCOL),
1418
+ childRunId: decodeId(o.childRunId),
1419
+ workerSeq: integer(
1420
+ o.workerSeq,
1421
+ 1,
1422
+ LIMITS.dataFrames + LIMITS.controlFrames,
1423
+ ),
1424
+ observedMs: integer(o.observedMs),
1425
+ event: decodeCaptureEvent(o.event),
1426
+ };
1427
+ }
1428
+ /** Header ordering only; W2 must additionally verify detail associations, hashes,
1429
+ * control/data totals and native settlement. A final frame is never native success. */
1430
+ export function advanceCapture(position, input) {
1431
+ const frame = decodeCaptureFrame(input);
1432
+ if (
1433
+ position.final ||
1434
+ frame.childRunId !== position.childRunId ||
1435
+ frame.workerSeq !== position.workerSeq + 1 ||
1436
+ frame.observedMs < position.observedMs ||
1437
+ (frame.event.kind === "ready") !== (position.workerSeq === 0)
1438
+ )
1439
+ invalid();
1440
+ return {
1441
+ frame,
1442
+ position: {
1443
+ childRunId: frame.childRunId,
1444
+ workerSeq: frame.workerSeq,
1445
+ observedMs: frame.observedMs,
1446
+ final: frame.event.kind === "final",
1447
+ },
1448
+ };
1449
+ }
1450
+ export function decodeCheckNativeSettlement(v) {
1451
+ const o = closed(v, [
1452
+ "outcome",
1453
+ "closure",
1454
+ "exitCode",
1455
+ "signal",
1456
+ "durationMs",
1457
+ "stdin",
1458
+ ]);
1459
+ const r = {
1460
+ outcome: oneOf(o.outcome, [
1461
+ "completed",
1462
+ "failed",
1463
+ "canceled",
1464
+ "timeout",
1465
+ "unknown",
1466
+ ]),
1467
+ closure: oneOf(o.closure, closures),
1468
+ exitCode: nullable(o.exitCode, (v) => integer(v, -2147483648, 4294967295)),
1469
+ signal: nullable(o.signal, (v) => text(v, 32, true)),
1470
+ durationMs: integer(o.durationMs),
1471
+ stdin: literal(o.stdin, "not-required"),
1472
+ };
1473
+ if (
1474
+ (r.closure === "not-launched" &&
1475
+ (r.exitCode !== null || r.signal !== null)) ||
1476
+ (r.outcome === "completed" &&
1477
+ (r.closure !== "direct-child-closed" ||
1478
+ r.exitCode !== 0 ||
1479
+ r.signal !== null))
1480
+ )
1481
+ invalid();
1482
+ return r;
1483
+ }
1484
+ export function decodeFinalSelection(v) {
1485
+ const o = closed(v, ["messageId", "detailId"]);
1486
+ return { messageId: decodeId(o.messageId), detailId: decodeId(o.detailId) };
1487
+ }
1488
+ export function decodeDetailCommit(v) {
1489
+ const o = closed(v, ["childRunId", "detailId", "content", "committedSeq"]);
1490
+ const committedSeq = decodeSequence(o.committedSeq);
1491
+ if (committedSeq === "0") invalid();
1492
+ return {
1493
+ childRunId: decodeId(o.childRunId),
1494
+ detailId: decodeId(o.detailId),
1495
+ content: decodeContentRef(o.content),
1496
+ committedSeq,
1497
+ };
1498
+ }
1499
+ export function decodeFinalRecording(v) {
1500
+ const status = tag(v, "status");
1501
+ if (status === "committed") {
1502
+ const o = closed(v, ["status", "selected", "detail"]);
1503
+ const selected = decodeFinalSelection(o.selected),
1504
+ detail = decodeDetailCommit(o.detail);
1505
+ if (
1506
+ selected.detailId !== detail.detailId ||
1507
+ detail.content.field !== "final-text"
1508
+ )
1509
+ invalid();
1510
+ return { status, selected, detail };
1511
+ }
1512
+ if (status === "refused") {
1513
+ const o = closed(v, ["status", "selected", "error"]);
1514
+ return {
1515
+ status,
1516
+ selected: nullable(o.selected, decodeFinalSelection),
1517
+ error: decodePublicError(o.error),
1518
+ };
1519
+ }
1520
+ const o = closed(v, ["status", "selected"]);
1521
+ return {
1522
+ status: oneOf(status, ["pending", "uncertain"]),
1523
+ selected: nullable(o.selected, decodeFinalSelection),
1524
+ };
1525
+ }
1526
+ function decodeSettlementSeq(v, recording) {
1527
+ const seq = nullable(v, decodeSequence);
1528
+ if (
1529
+ seq === "0" ||
1530
+ (seq !== null &&
1531
+ recording.status === "committed" &&
1532
+ compareSequence(seq, recording.detail.committedSeq) < 0)
1533
+ )
1534
+ invalid();
1535
+ return seq;
1536
+ }
1537
+ export function childSatisfied(child) {
1538
+ return (
1539
+ child.native?.outcome === "completed" &&
1540
+ child.recording.status === "committed" &&
1541
+ child.settlementSeq !== null
1542
+ );
1543
+ }
1544
+ export function settlementOutcome(s) {
1545
+ if (s.kind === "parent") return s.outcome;
1546
+ if (s.native.outcome !== "completed") return s.native.outcome;
1547
+ return s.kind === "sdk"
1548
+ ? childSatisfied(s)
1549
+ ? "completed"
1550
+ : "failed"
1551
+ : s.capture.observed === "complete" && s.settlementSeq !== null
1552
+ ? "completed"
1553
+ : "failed";
1554
+ }
1555
+ export function decodeRunSettlement(v) {
1556
+ const kind = tag(v);
1557
+ if (kind === "sdk") {
1558
+ const o = closed(v, ["kind", "native", "recording", "settlementSeq"]);
1559
+ const recording = decodeFinalRecording(o.recording),
1560
+ settlementSeq = decodeSettlementSeq(o.settlementSeq, recording);
1561
+ return {
1562
+ kind,
1563
+ native: decodeNativeSettlement(o.native),
1564
+ recording,
1565
+ settlementSeq,
1566
+ };
1567
+ }
1568
+ if (kind === "check") {
1569
+ const o = closed(v, ["kind", "native", "capture", "settlementSeq"]);
1570
+ const settlementSeq = nullable(o.settlementSeq, decodeSequence);
1571
+ if (settlementSeq === "0") invalid();
1572
+ return {
1573
+ kind,
1574
+ native: decodeCheckNativeSettlement(o.native),
1575
+ capture: decodeCoverage(o.capture),
1576
+ settlementSeq,
1577
+ };
1578
+ }
1579
+ const o = closed(v, ["kind", "outcome", "required"]);
1580
+ literal(kind, "parent");
1581
+ const required = list(o.required, LIMITS.assignments, (v) => {
1582
+ const c = closed(v, [
1583
+ "assignmentId",
1584
+ "childRunId",
1585
+ "native",
1586
+ "recording",
1587
+ "settlementSeq",
1588
+ ]);
1589
+ const childRunId = decodeId(c.childRunId),
1590
+ recording = decodeFinalRecording(c.recording);
1591
+ if (
1592
+ recording.status === "committed" &&
1593
+ recording.detail.childRunId !== childRunId
1594
+ )
1595
+ invalid();
1596
+ return {
1597
+ assignmentId: assignmentId(c.assignmentId),
1598
+ childRunId,
1599
+ native: nullable(c.native, decodeNativeSettlement),
1600
+ recording,
1601
+ settlementSeq: decodeSettlementSeq(c.settlementSeq, recording),
1602
+ };
1603
+ });
1604
+ const outcome = oneOf(o.outcome, outcomes);
1605
+ if (
1606
+ !required.length ||
1607
+ new Set(required.map((c) => c.assignmentId)).size !== required.length ||
1608
+ new Set(required.map((c) => c.childRunId)).size !== required.length ||
1609
+ (outcome === "completed" && !required.every(childSatisfied))
1610
+ )
1611
+ invalid();
1612
+ // W4 resolves this exact required set against frozen graph, not merely the
1613
+ // completed subset. No process, exit code or descendant claim belongs to parent.
1614
+ return { kind: "parent", outcome, required };
1615
+ }
1616
+ export function decodeWorkerCompletion(v) {
1617
+ const o = closed(v, ["childRunId", "native", "selected", "recording"]);
1618
+ const r = {
1619
+ childRunId: decodeId(o.childRunId),
1620
+ native: decodeNativeSettlement(o.native),
1621
+ selected: nullable(o.selected, decodeFinalSelection),
1622
+ recording: decodeFinalRecording(o.recording),
1623
+ };
1624
+ if (
1625
+ (r.native.final === "valid") !== (r.selected !== null) ||
1626
+ canonicalJson(r.selected) !== canonicalJson(r.recording.selected) ||
1627
+ (r.recording.status === "committed" &&
1628
+ r.recording.detail.childRunId !== r.childRunId)
1629
+ )
1630
+ invalid();
1631
+ return r;
1632
+ }
1633
+ export function decodeSourceRange(v) {
1634
+ const o = closed(v, ["first", "last", "firstObservedMs", "lastObservedMs"]);
1635
+ const first = integer(o.first, 1, LIMITS.dataFrames + LIMITS.controlFrames);
1636
+ const last = integer(o.last, first, LIMITS.dataFrames + LIMITS.controlFrames);
1637
+ const firstObservedMs = integer(o.firstObservedMs);
1638
+ const lastObservedMs = integer(o.lastObservedMs, firstObservedMs);
1639
+ if (first === last && firstObservedMs !== lastObservedMs) invalid();
1640
+ return { first, last, firstObservedMs, lastObservedMs };
1641
+ }
1642
+ export function decodeRecordingEvent(v) {
1643
+ const o = closed(v, ["source", "event"]);
1644
+ const source = decodeSourceRange(o.source);
1645
+ const kind = tag(o.event);
1646
+ if (kind === "stored-chunk") {
1647
+ const e = closed(o.event, ["kind", "detailId", "text"]);
1648
+ return {
1649
+ source,
1650
+ event: {
1651
+ kind,
1652
+ detailId: decodeId(e.detailId),
1653
+ text: text(e.text, LIMITS.chunkBytes),
1654
+ },
1655
+ };
1656
+ }
1657
+ if (kind === "stored-end") {
1658
+ const e = closed(o.event, ["kind", "detailId", "coverage"]);
1659
+ return {
1660
+ source,
1661
+ event: {
1662
+ kind,
1663
+ detailId: decodeId(e.detailId),
1664
+ coverage: decodeCoverage(e.coverage),
1665
+ },
1666
+ };
1667
+ }
1668
+ const event = decodeCaptureEvent(o.event);
1669
+ if (event.kind === "detail-chunk" || event.kind === "detail-end") invalid();
1670
+ return { source, event };
1671
+ }
1672
+ export function decodeRecordingLink(v) {
1673
+ const o = closed(v, ["epoch", "taskId", "runId", "childRunId"]);
1674
+ return {
1675
+ epoch: decodeId(o.epoch),
1676
+ taskId: decodeId(o.taskId),
1677
+ runId: decodeId(o.runId),
1678
+ childRunId: decodeId(o.childRunId),
1679
+ };
1680
+ }
1681
+ export function decodeRecordingInput(v) {
1682
+ canonicalJson(v, LIMITS.ownerQueueBytes);
1683
+ const o = closed(v, ["link", "source", "events"]);
1684
+ const source = decodeSourceRange(o.source),
1685
+ events = list(o.events, LIMITS.ownerQueueFrames, decodeRecordingEvent);
1686
+ if (
1687
+ events.some(
1688
+ (e) =>
1689
+ e.source.first < source.first ||
1690
+ e.source.last > source.last ||
1691
+ e.source.firstObservedMs < source.firstObservedMs ||
1692
+ e.source.lastObservedMs > source.lastObservedMs,
1693
+ )
1694
+ )
1695
+ invalid();
1696
+ return { link: decodeRecordingLink(o.link), source, events };
1697
+ }
1698
+ export function decodeCaptureBudget(v) {
1699
+ const o = closed(v, [
1700
+ "sourceFrames",
1701
+ "retainedBytes",
1702
+ "outputBytes",
1703
+ "outputChunks",
1704
+ "lane",
1705
+ ]);
1706
+ const r = {
1707
+ sourceFrames: integer(o.sourceFrames, 0, LIMITS.ownerQueueFrames),
1708
+ retainedBytes: integer(o.retainedBytes, 0, LIMITS.ownerQueueBytes),
1709
+ outputBytes: integer(o.outputBytes, 0, LIMITS.ownerQueueBytes),
1710
+ outputChunks: integer(o.outputChunks, 0, LIMITS.ownerQueueFrames),
1711
+ lane: oneOf(o.lane, ["data", "control"]),
1712
+ };
1713
+ if (
1714
+ r.retainedBytes + r.outputBytes > LIMITS.ownerQueueBytes ||
1715
+ (!r.sourceFrames && !r.retainedBytes && !r.outputBytes && !r.outputChunks)
1716
+ )
1717
+ invalid();
1718
+ return r;
1719
+ }
1720
+ export function decodeCommittedBatch(v) {
1721
+ const o = closed(v, ["committedSeq", "details", "ownerDetails", "coverage"]);
1722
+ const committedSeq = decodeSequence(o.committedSeq),
1723
+ details = list(o.details, LIMITS.ownerQueueFrames, decodeDetailCommit);
1724
+ if (
1725
+ committedSeq === "0" ||
1726
+ details.some((d) => compareSequence(d.committedSeq, committedSeq) > 0) ||
1727
+ new Set(details.map((d) => `${d.childRunId}/${d.detailId}`)).size !==
1728
+ details.length
1729
+ )
1730
+ invalid();
1731
+ const ownerDetails = list(o.ownerDetails, LIMITS.ownerQueueFrames, (v) => {
1732
+ const d = closed(v, ["operationId", "detailId", "content", "committedSeq"]),
1733
+ seq = decodeSequence(d.committedSeq);
1734
+ if (seq === "0" || compareSequence(seq, committedSeq) > 0) invalid();
1735
+ return {
1736
+ operationId: decodeId(d.operationId),
1737
+ detailId: decodeId(d.detailId),
1738
+ content: decodeContentRef(d.content),
1739
+ committedSeq: seq,
1740
+ };
1741
+ });
1742
+ if (
1743
+ new Set(ownerDetails.map((d) => `${d.operationId}/${d.detailId}`)).size !==
1744
+ ownerDetails.length
1745
+ )
1746
+ invalid();
1747
+ return {
1748
+ committedSeq,
1749
+ details,
1750
+ ownerDetails,
1751
+ coverage: decodeCoverage(o.coverage),
1752
+ };
1753
+ }