@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
@@ -1,570 +0,0 @@
1
- import path from "node:path";
2
- import type { Usage } from "@earendil-works/pi-ai";
3
- import { Activation, type ActivationState } from "./activation.ts";
4
- import { loadAgentDefinitions } from "./agent-registry.ts";
5
- import {
6
- type ChildFailureKind,
7
- type ChildSessionResult,
8
- runChildSession,
9
- UsageAggregator,
10
- } from "./child-session.ts";
11
- import {
12
- type ChildFailure,
13
- LIMITS,
14
- type PacketEnvelope,
15
- validatePacketEnvelope,
16
- } from "./contracts.ts";
17
- import type { PackageContext } from "./model-source.ts";
18
- import { runtimeForWorkerRoute } from "./parent-provider.ts";
19
- import {
20
- loadRoutePolicy,
21
- type RoutePolicy,
22
- type WorkerRole,
23
- } from "./route-policy.ts";
24
- import {
25
- isTransportTimeoutCode,
26
- transportFailureError,
27
- } from "./transport-budget.ts";
28
- import { type BrokerActivityUpdate, RunWorkerBroker } from "./worker-broker.ts";
29
-
30
- export const PACKET_ACTIONS = ["run", "cancel", "finish"] as const;
31
- export type PacketAction = (typeof PACKET_ACTIONS)[number];
32
-
33
- import type {
34
- PacketActivityEvent,
35
- PacketActivityObserver,
36
- PacketActivityState,
37
- } from "./activity-contracts.ts";
38
-
39
- export type {
40
- PacketActivityEvent,
41
- PacketActivityObserver,
42
- PacketActivityState,
43
- PacketFailureReason,
44
- } from "./activity-contracts.ts";
45
-
46
- export type PacketDispatchResult =
47
- | {
48
- ok: true;
49
- action: PacketAction;
50
- result?: unknown;
51
- usage?: Usage;
52
- }
53
- | {
54
- ok: false;
55
- notReady?: true;
56
- error: string;
57
- failure?: ChildFailure;
58
- usage?: Usage;
59
- };
60
-
61
- export interface PacketRuntimeOptions {
62
- activation?: Activation;
63
- routePolicy?: RoutePolicy;
64
- routePolicyHome?: string;
65
- environment?: Readonly<Record<string, string | undefined>>;
66
- concurrency?: number;
67
- childRunner?: PacketChildRunner;
68
- }
69
-
70
- export type PacketContext = PackageContext;
71
-
72
- export type PacketChildRunner = (input: {
73
- packet: PacketEnvelope;
74
- context: PacketContext;
75
- signal: AbortSignal;
76
- }) => Promise<ChildSessionResult>;
77
-
78
- type PacketRouteResult =
79
- | {
80
- kind: "phase-failure";
81
- phase: Extract<
82
- Awaited<ReturnType<typeof runtimeForWorkerRoute>>,
83
- { ok: false }
84
- >;
85
- }
86
- | { kind: "child"; child: ChildSessionResult };
87
-
88
- interface WaitingPacket {
89
- controller: AbortController;
90
- resolve(acquired: boolean): void;
91
- onAbort(): void;
92
- }
93
-
94
- function cancelledResult(signal: AbortSignal): PacketDispatchResult {
95
- const reason = signal.reason;
96
- return {
97
- ok: false,
98
- error:
99
- reason instanceof Error
100
- ? reason.message
101
- : typeof reason === "string"
102
- ? reason
103
- : "packet cancelled",
104
- failure: { kind: "cancelled", code: "cancelled" },
105
- };
106
- }
107
-
108
- function failureState(kind: ChildFailureKind): PacketActivityState {
109
- return kind === "cancelled"
110
- ? "cancelled"
111
- : kind === "timed-out"
112
- ? "timed-out"
113
- : "failed";
114
- }
115
-
116
- function syntheticChildFailure(
117
- error: string,
118
- failure: ChildFailure,
119
- failureKind: ChildFailureKind = failure.kind === "cancelled"
120
- ? "cancelled"
121
- : "failed",
122
- ): ChildSessionResult {
123
- return {
124
- ok: false,
125
- error,
126
- failure,
127
- failureKind,
128
- transportFailure: failure.kind === "transport",
129
- disposeCount: 0,
130
- usage: new UsageAggregator().total(),
131
- classification: {
132
- finalCategory: "no-final-assistant",
133
- attempts: 0,
134
- schema: "invalid",
135
- identity: { request: false, role: false, task: false, phase: false },
136
- },
137
- };
138
- }
139
-
140
- export class PacketRuntime {
141
- readonly activation: Activation;
142
- readonly limits = LIMITS;
143
- readonly #routePolicy?: RoutePolicy;
144
- readonly #routePolicyHome?: string;
145
- readonly #environment: Readonly<Record<string, string | undefined>>;
146
- readonly #concurrency: number;
147
- readonly #childRunner?: PacketChildRunner;
148
- readonly #brokers = new Map<string, RunWorkerBroker>();
149
- readonly #brokerPolicies = new Map<string, string>();
150
- readonly #controllers = new Set<AbortController>();
151
- readonly #operations = new Set<Promise<PacketDispatchResult>>();
152
- readonly #waiting: WaitingPacket[] = [];
153
- #active = 0;
154
- #sequence = 0;
155
-
156
- constructor(options: PacketRuntimeOptions) {
157
- this.activation = options.activation ?? new Activation();
158
- this.#routePolicy = options.routePolicy;
159
- this.#routePolicyHome = options.routePolicyHome;
160
- this.#environment = options.environment ?? process.env;
161
- this.#childRunner = options.childRunner;
162
- this.#concurrency = Math.max(
163
- 1,
164
- Math.min(
165
- options.concurrency ?? LIMITS.maxActiveChildSessions,
166
- LIMITS.maxActiveChildSessions,
167
- ),
168
- );
169
- }
170
-
171
- validateRequest(value: unknown) {
172
- return validatePacketEnvelope(value);
173
- }
174
-
175
- async execute(
176
- action: string,
177
- params: { request?: unknown },
178
- context?: PacketContext,
179
- signal?: AbortSignal,
180
- observer?: PacketActivityObserver,
181
- ): Promise<PacketDispatchResult> {
182
- if (!(PACKET_ACTIONS as readonly string[]).includes(action)) {
183
- throw new Error(`unknown packet action: ${String(action)}`);
184
- }
185
- if (!this.activation.isActive()) {
186
- return { ok: false, notReady: true, error: "dispatcher is not active" };
187
- }
188
- if (action === "cancel") {
189
- await this.cancel();
190
- return { ok: true, action };
191
- }
192
- if (action === "finish") {
193
- await this.drain();
194
- return { ok: true, action };
195
- }
196
- const operation = this.#run(params.request, context, signal, observer);
197
- this.#operations.add(operation);
198
- try {
199
- return await operation;
200
- } finally {
201
- this.#operations.delete(operation);
202
- }
203
- }
204
-
205
- async #run(
206
- request: unknown,
207
- context?: PacketContext,
208
- parentSignal?: AbortSignal,
209
- observer?: PacketActivityObserver,
210
- ): Promise<PacketDispatchResult> {
211
- if (!context) return { ok: false, error: "run requires extension context" };
212
- const validation = validatePacketEnvelope(request);
213
- if (!validation.ok) return { ok: false, error: validation.reason };
214
- const packet = validation.value;
215
- const sequence = ++this.#sequence;
216
- this.#notify(packet, observer, sequence, "queued");
217
-
218
- const controller = new AbortController();
219
- this.#controllers.add(controller);
220
- const forwardCancellation = () => {
221
- if (!controller.signal.aborted) controller.abort(parentSignal?.reason);
222
- };
223
- if (parentSignal?.aborted) forwardCancellation();
224
- else
225
- parentSignal?.addEventListener("abort", forwardCancellation, {
226
- once: true,
227
- });
228
-
229
- let acquired = false;
230
- try {
231
- acquired = await this.#acquire(controller);
232
- if (!acquired || controller.signal.aborted) {
233
- this.#notify(packet, observer, sequence, "cancelled");
234
- return cancelledResult(controller.signal);
235
- }
236
- if (this.#childRunner) {
237
- this.#notify(packet, observer, sequence, "running");
238
- }
239
- const usage = new UsageAggregator();
240
- let child = await this.#dispatchChild(
241
- packet,
242
- context,
243
- controller.signal,
244
- (activity) =>
245
- this.#notifyBrokerActivity(packet, observer, sequence, activity),
246
- );
247
- usage.add("launch:0", child.usage);
248
- if (
249
- this.#childRunner &&
250
- !child.ok &&
251
- child.failure.kind === "artifact" &&
252
- !controller.signal.aborted
253
- ) {
254
- this.#notifyBrokerActivity(packet, observer, sequence, {
255
- state: "retrying",
256
- attempt: 1,
257
- maxAttempts: 2,
258
- code: child.failure.code,
259
- wait: "bounded-policy",
260
- });
261
- child = await this.#dispatchChild(
262
- packet,
263
- context,
264
- controller.signal,
265
- (activity) =>
266
- this.#notifyBrokerActivity(packet, observer, sequence, activity),
267
- );
268
- usage.add("launch:1", child.usage);
269
- }
270
- if (!child.ok) {
271
- const state = failureState(child.failureKind);
272
- this.#notify(packet, observer, sequence, state);
273
- return {
274
- ok: false,
275
- error: child.error,
276
- failure: child.failure,
277
- usage: usage.total(),
278
- };
279
- }
280
- this.#notify(packet, observer, sequence, "completed");
281
- return {
282
- ok: true,
283
- action: "run",
284
- result: child.result,
285
- usage: usage.total(),
286
- };
287
- } catch (error) {
288
- this.#notify(
289
- packet,
290
- observer,
291
- sequence,
292
- controller.signal.aborted ? "cancelled" : "failed",
293
- );
294
- throw error;
295
- } finally {
296
- parentSignal?.removeEventListener("abort", forwardCancellation);
297
- this.#controllers.delete(controller);
298
- if (acquired) this.#release();
299
- }
300
- }
301
-
302
- async #dispatchChild(
303
- packet: PacketEnvelope,
304
- context: PacketContext,
305
- signal: AbortSignal,
306
- onActivity?: (event: BrokerActivityUpdate) => void,
307
- ): Promise<ChildSessionResult> {
308
- if (signal.aborted) {
309
- const result = cancelledResult(signal);
310
- return syntheticChildFailure(
311
- result.ok ? "packet cancelled" : result.error,
312
- { kind: "cancelled", code: "cancelled" },
313
- "cancelled",
314
- );
315
- }
316
- if (this.#childRunner) {
317
- return this.#childRunner({
318
- packet: structuredClone(packet),
319
- context,
320
- signal,
321
- });
322
- }
323
- const agent = loadAgentDefinitions().find(
324
- (candidate) => candidate.role === packet.role,
325
- );
326
- if (!agent) {
327
- throw new Error("packet agent definition is unavailable");
328
- }
329
- const broker = this.#brokerFor(context);
330
- const brokerUsage = new UsageAggregator();
331
- let childAttempt = 0;
332
- const withBrokerUsage = (
333
- child: ChildSessionResult,
334
- ): ChildSessionResult => ({
335
- ...child,
336
- usage: brokerUsage.total(),
337
- });
338
- const routed = await broker.run<PacketRouteResult>({
339
- runId: `${packet.stage}:${packet.id}`,
340
- operationId: packet.id,
341
- role: packet.role as WorkerRole,
342
- signal,
343
- ...(onActivity ? { onActivity } : {}),
344
- classifyResult: (value) =>
345
- value.kind === "child" &&
346
- !value.child.ok &&
347
- value.child.failure.kind === "artifact"
348
- ? value.child.failure.code
349
- : undefined,
350
- execute: async (attempt) => {
351
- const phase = await runtimeForWorkerRoute(
352
- attempt.route,
353
- context,
354
- attempt.signal,
355
- this.#environment,
356
- );
357
- if (!phase.ok) {
358
- if (phase.failure.kind === "cancelled") {
359
- return { kind: "phase-failure" as const, phase };
360
- }
361
- throw new Error(phase.failure.code);
362
- }
363
- const child = await runChildSession({
364
- cwd: context.cwd,
365
- modelRuntime: phase.modelRuntime,
366
- model: phase.model,
367
- systemPrompt: [
368
- agent.content,
369
- packet.objective,
370
- packet.context.agents,
371
- packet.context.contract,
372
- `<packet-contract>${JSON.stringify({
373
- requestId: packet.id,
374
- phase: packet.phase,
375
- readSet: packet.declared.read,
376
- writeSet: packet.declared.write,
377
- output: packet.output,
378
- })}</packet-contract>`,
379
- ].join("\n\n"),
380
- requestId: packet.id,
381
- role: packet.role,
382
- phase: packet.phase,
383
- output: packet.output as "evidence" | "diff",
384
- ...(packet.role === "diagnosis-worker" && packet.output === "diff"
385
- ? {
386
- structuredPatch: {
387
- workspaceRoot: context.cwd,
388
- writePaths: packet.declared.write,
389
- deletePaths: packet.declared.write,
390
- },
391
- }
392
- : {}),
393
- roots: packet.roots.map((root) => path.resolve(context.cwd, root)),
394
- allowedPaths: [
395
- ...new Set([...packet.declared.read, ...packet.declared.write]),
396
- ],
397
- timeoutMs: LIMITS.phaseTimeoutMs,
398
- signal: attempt.signal,
399
- onStreamStart: attempt.onRequestStart,
400
- onStreamHeaders: attempt.onHeaders,
401
- onStreamProgress: attempt.onProgress,
402
- });
403
- brokerUsage.add(`attempt:${childAttempt++}`, child.usage);
404
- if (!child.ok && child.failure.kind === "transport") {
405
- throw transportFailureError(child.failure.code);
406
- }
407
- return { kind: "child" as const, child };
408
- },
409
- });
410
- if (!routed.ok) {
411
- const cancelled = routed.state === "cancelled" || signal.aborted;
412
- const timedOut =
413
- !cancelled &&
414
- (isTransportTimeoutCode(routed.code) ||
415
- routed.code === "phase-timeout");
416
- return withBrokerUsage(
417
- syntheticChildFailure(
418
- cancelled ? "packet cancelled" : routed.code,
419
- cancelled
420
- ? { kind: "cancelled", code: "cancelled" }
421
- : timedOut
422
- ? {
423
- kind: "transport",
424
- code: isTransportTimeoutCode(routed.code)
425
- ? routed.code
426
- : "timeout",
427
- stage: "child-timeout",
428
- }
429
- : {
430
- kind: "transport",
431
- code: "transport-failure",
432
- stage: "child-provider-stream",
433
- },
434
- cancelled ? "cancelled" : timedOut ? "timed-out" : "failed",
435
- ),
436
- );
437
- }
438
- if (routed.value.kind === "phase-failure") {
439
- const phase = routed.value.phase;
440
- return withBrokerUsage(syntheticChildFailure(phase.error, phase.failure));
441
- }
442
- return withBrokerUsage(routed.value.child);
443
- }
444
-
445
- #brokerFor(context: PacketContext): RunWorkerBroker {
446
- const root = path.resolve(context.cwd);
447
- const existing = this.#brokers.get(root);
448
- let policy = this.#routePolicy;
449
- if (policy && existing) return existing;
450
- if (!policy) {
451
- const resolution = loadRoutePolicy({
452
- cwd: root,
453
- ...(this.#routePolicyHome ? { home: this.#routePolicyHome } : {}),
454
- ...(context.model ? { parentModel: context.model } : {}),
455
- });
456
- if (!resolution.ok) {
457
- const code = resolution.diagnostics[0]?.code ?? "policy-invalid";
458
- throw new Error(`route-policy-unavailable:${code}`);
459
- }
460
- policy = resolution.policy;
461
- }
462
- const serializedPolicy = JSON.stringify(policy);
463
- if (existing && this.#brokerPolicies.get(root) === serializedPolicy) {
464
- return existing;
465
- }
466
- const broker = new RunWorkerBroker(policy);
467
- this.#brokers.set(root, broker);
468
- this.#brokerPolicies.set(root, serializedPolicy);
469
- return broker;
470
- }
471
-
472
- #notifyBrokerActivity(
473
- packet: PacketEnvelope,
474
- observer: PacketActivityObserver | undefined,
475
- sequence: number,
476
- activity: BrokerActivityUpdate,
477
- ): void {
478
- this.#notify(packet, observer, sequence, activity.state, {
479
- attempt: activity.attempt,
480
- maxAttempts: activity.maxAttempts,
481
- ...(activity.code ? { code: activity.code } : {}),
482
- ...(activity.wait ? { wait: activity.wait } : {}),
483
- });
484
- }
485
-
486
- #notify(
487
- packet: PacketEnvelope,
488
- observer: PacketActivityObserver | undefined,
489
- sequence: number,
490
- state: PacketActivityState,
491
- metadata: Pick<
492
- PacketActivityEvent,
493
- "attempt" | "maxAttempts" | "code" | "wait"
494
- > = {},
495
- ): void {
496
- if (!observer) return;
497
- const event: PacketActivityEvent = {
498
- state,
499
- requestId: packet.id,
500
- role: packet.role,
501
- phase: packet.phase,
502
- objective: packet.objective,
503
- sequence,
504
- ...metadata,
505
- ...(state === "cancelled"
506
- ? { failureReason: "subagent cancelled" as const }
507
- : state === "timed-out"
508
- ? { failureReason: "phase timed out" as const }
509
- : state === "failed"
510
- ? { failureReason: "subagent failed" as const }
511
- : {}),
512
- };
513
- try {
514
- const result = observer(event);
515
- if (result instanceof Promise) void result.catch(() => undefined);
516
- } catch {
517
- // Presentation observers cannot alter execution.
518
- }
519
- }
520
-
521
- #acquire(controller: AbortController): Promise<boolean> {
522
- if (controller.signal.aborted) return Promise.resolve(false);
523
- if (this.#active < this.#concurrency) {
524
- this.#active += 1;
525
- return Promise.resolve(true);
526
- }
527
- return new Promise<boolean>((resolve) => {
528
- let waiting: WaitingPacket;
529
- const onAbort = () => {
530
- const index = this.#waiting.indexOf(waiting);
531
- if (index >= 0) this.#waiting.splice(index, 1);
532
- resolve(false);
533
- };
534
- waiting = { controller, resolve, onAbort };
535
- this.#waiting.push(waiting);
536
- controller.signal.addEventListener("abort", onAbort, { once: true });
537
- });
538
- }
539
-
540
- #release(): void {
541
- this.#active -= 1;
542
- while (this.#waiting.length > 0) {
543
- const next = this.#waiting.shift();
544
- if (!next || next.controller.signal.aborted) continue;
545
- next.controller.signal.removeEventListener("abort", next.onAbort);
546
- this.#active += 1;
547
- next.resolve(true);
548
- break;
549
- }
550
- }
551
-
552
- async cancel(): Promise<void> {
553
- const reason = new Error("packet runtime cancelled");
554
- for (const controller of this.#controllers) {
555
- if (!controller.signal.aborted) controller.abort(reason);
556
- }
557
- await Promise.allSettled([...this.#operations]);
558
- }
559
-
560
- async drain(): Promise<void> {
561
- this.activation.drain();
562
- await this.cancel();
563
- this.#brokers.clear();
564
- this.#brokerPolicies.clear();
565
- }
566
-
567
- get state(): ActivationState {
568
- return this.activation.state;
569
- }
570
- }