@leitwerk-dev/worker 0.1.2 → 0.1.3

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 (213) hide show
  1. package/dist/automatic-turn-executor.d.ts +28 -0
  2. package/dist/automatic-turn-executor.d.ts.map +1 -0
  3. package/dist/automatic-turn-executor.js +58 -0
  4. package/dist/automatic-turn-executor.js.map +1 -0
  5. package/dist/diagnostics.d.ts +23 -0
  6. package/dist/diagnostics.d.ts.map +1 -0
  7. package/dist/diagnostics.js +51 -0
  8. package/dist/diagnostics.js.map +1 -0
  9. package/dist/entry-runtime.d.ts +24 -0
  10. package/dist/entry-runtime.d.ts.map +1 -0
  11. package/dist/entry-runtime.js +160 -0
  12. package/dist/entry-runtime.js.map +1 -0
  13. package/dist/event-translator.d.ts +8 -0
  14. package/dist/event-translator.d.ts.map +1 -0
  15. package/dist/event-translator.js +12 -0
  16. package/dist/event-translator.js.map +1 -0
  17. package/dist/extension-entry-roots.d.ts +7 -0
  18. package/dist/extension-entry-roots.d.ts.map +1 -0
  19. package/dist/extension-entry-roots.js +41 -0
  20. package/dist/extension-entry-roots.js.map +1 -0
  21. package/dist/identified-pi-entry.d.ts +56 -0
  22. package/dist/identified-pi-entry.d.ts.map +1 -0
  23. package/dist/identified-pi-entry.js +125 -0
  24. package/dist/identified-pi-entry.js.map +1 -0
  25. package/dist/index.d.ts +7 -283
  26. package/dist/index.d.ts.map +1 -0
  27. package/dist/index.js +5 -32
  28. package/dist/index.js.map +1 -1
  29. package/dist/input-consumer.d.ts +24 -0
  30. package/dist/input-consumer.d.ts.map +1 -0
  31. package/dist/input-consumer.js +34 -0
  32. package/dist/input-consumer.js.map +1 -0
  33. package/dist/ipc.d.ts +22 -0
  34. package/dist/ipc.d.ts.map +1 -0
  35. package/dist/ipc.js +192 -0
  36. package/dist/ipc.js.map +1 -0
  37. package/dist/logical-prompt-runner.d.ts +49 -0
  38. package/dist/logical-prompt-runner.d.ts.map +1 -0
  39. package/dist/logical-prompt-runner.js +225 -0
  40. package/dist/logical-prompt-runner.js.map +1 -0
  41. package/dist/managed-pi-agent-dir.d.ts +13 -0
  42. package/dist/managed-pi-agent-dir.d.ts.map +1 -0
  43. package/dist/managed-pi-agent-dir.js +66 -0
  44. package/dist/managed-pi-agent-dir.js.map +1 -0
  45. package/dist/managed-pi-bootstrap.d.ts +24 -0
  46. package/dist/managed-pi-bootstrap.d.ts.map +1 -0
  47. package/dist/managed-pi-bootstrap.js +135 -0
  48. package/dist/managed-pi-bootstrap.js.map +1 -0
  49. package/dist/missing-tool-recovery-runner.d.ts +23 -0
  50. package/dist/missing-tool-recovery-runner.d.ts.map +1 -0
  51. package/dist/missing-tool-recovery-runner.js +73 -0
  52. package/dist/missing-tool-recovery-runner.js.map +1 -0
  53. package/dist/pi-adapter.d.ts +134 -0
  54. package/dist/pi-adapter.d.ts.map +1 -0
  55. package/dist/pi-adapter.js +1648 -0
  56. package/dist/pi-adapter.js.map +1 -0
  57. package/dist/pi-branch-guard.d.ts +39 -0
  58. package/dist/pi-branch-guard.d.ts.map +1 -0
  59. package/dist/pi-branch-guard.js +75 -0
  60. package/dist/pi-branch-guard.js.map +1 -0
  61. package/dist/pi-event-reporter.d.ts +15 -0
  62. package/dist/pi-event-reporter.d.ts.map +1 -0
  63. package/dist/pi-event-reporter.js +136 -0
  64. package/dist/pi-event-reporter.js.map +1 -0
  65. package/dist/pi-resource-bundle.d.ts +12 -0
  66. package/dist/pi-resource-bundle.d.ts.map +1 -0
  67. package/dist/pi-resource-bundle.js +58 -0
  68. package/dist/pi-resource-bundle.js.map +1 -0
  69. package/dist/pre-turn-targeted-inputs.d.ts +44 -0
  70. package/dist/pre-turn-targeted-inputs.d.ts.map +1 -0
  71. package/dist/pre-turn-targeted-inputs.js +101 -0
  72. package/dist/pre-turn-targeted-inputs.js.map +1 -0
  73. package/dist/prompt-guards.d.ts +52 -0
  74. package/dist/prompt-guards.d.ts.map +1 -0
  75. package/dist/prompt-guards.js +318 -0
  76. package/dist/prompt-guards.js.map +1 -0
  77. package/dist/question-bridge.d.ts +16 -0
  78. package/dist/question-bridge.d.ts.map +1 -0
  79. package/dist/question-bridge.js +55 -0
  80. package/dist/question-bridge.js.map +1 -0
  81. package/dist/question-tool.d.ts +14 -0
  82. package/dist/question-tool.d.ts.map +1 -0
  83. package/dist/question-tool.js +54 -0
  84. package/dist/question-tool.js.map +1 -0
  85. package/dist/resource-loader-factory.d.ts +11 -0
  86. package/dist/resource-loader-factory.d.ts.map +1 -0
  87. package/dist/resource-loader-factory.js +87 -0
  88. package/dist/resource-loader-factory.js.map +1 -0
  89. package/dist/result-image-upload.d.ts +14 -0
  90. package/dist/result-image-upload.d.ts.map +1 -0
  91. package/dist/result-image-upload.js +183 -0
  92. package/dist/result-image-upload.js.map +1 -0
  93. package/dist/runtime/adapters.d.ts +53 -0
  94. package/dist/runtime/adapters.d.ts.map +1 -0
  95. package/dist/runtime/adapters.js +15 -0
  96. package/dist/runtime/adapters.js.map +1 -0
  97. package/dist/runtime/bootstrap-session.d.ts +95 -0
  98. package/dist/runtime/bootstrap-session.d.ts.map +1 -0
  99. package/dist/runtime/bootstrap-session.js +198 -0
  100. package/dist/runtime/bootstrap-session.js.map +1 -0
  101. package/dist/runtime/bootstrap.d.ts +81 -0
  102. package/dist/runtime/bootstrap.d.ts.map +1 -0
  103. package/dist/runtime/bootstrap.js +440 -0
  104. package/dist/runtime/bootstrap.js.map +1 -0
  105. package/dist/runtime/failure-policy.d.ts +79 -0
  106. package/dist/runtime/failure-policy.d.ts.map +1 -0
  107. package/dist/runtime/failure-policy.js +182 -0
  108. package/dist/runtime/failure-policy.js.map +1 -0
  109. package/dist/runtime/index.d.ts +9 -0
  110. package/dist/runtime/index.d.ts.map +1 -0
  111. package/dist/runtime/index.js +327 -0
  112. package/dist/runtime/index.js.map +1 -0
  113. package/dist/runtime/lifecycle-reducer.d.ts +328 -0
  114. package/dist/runtime/lifecycle-reducer.d.ts.map +1 -0
  115. package/dist/runtime/lifecycle-reducer.js +1100 -0
  116. package/dist/runtime/lifecycle-reducer.js.map +1 -0
  117. package/dist/runtime/llm-turn-execution.d.ts +42 -0
  118. package/dist/runtime/llm-turn-execution.d.ts.map +1 -0
  119. package/dist/runtime/llm-turn-execution.js +472 -0
  120. package/dist/runtime/llm-turn-execution.js.map +1 -0
  121. package/dist/runtime/settings.d.ts +11 -0
  122. package/dist/runtime/settings.d.ts.map +1 -0
  123. package/dist/runtime/settings.js +23 -0
  124. package/dist/runtime/settings.js.map +1 -0
  125. package/dist/runtime/snapshot-policy.d.ts +11 -0
  126. package/dist/runtime/snapshot-policy.d.ts.map +1 -0
  127. package/dist/runtime/snapshot-policy.js +16 -0
  128. package/dist/runtime/snapshot-policy.js.map +1 -0
  129. package/dist/runtime/turn-execution.d.ts +49 -0
  130. package/dist/runtime/turn-execution.d.ts.map +1 -0
  131. package/dist/runtime/turn-execution.js +120 -0
  132. package/dist/runtime/turn-execution.js.map +1 -0
  133. package/dist/session-snapshot-exchange.d.ts +39 -0
  134. package/dist/session-snapshot-exchange.d.ts.map +1 -0
  135. package/dist/session-snapshot-exchange.js +102 -0
  136. package/dist/session-snapshot-exchange.js.map +1 -0
  137. package/dist/test-helpers/fake-websocket.d.ts +16 -0
  138. package/dist/test-helpers/fake-websocket.d.ts.map +1 -0
  139. package/dist/test-helpers/fake-websocket.js +40 -0
  140. package/dist/test-helpers/fake-websocket.js.map +1 -0
  141. package/dist/test-helpers/ipc-harness.d.ts +11 -0
  142. package/dist/test-helpers/ipc-harness.d.ts.map +1 -0
  143. package/dist/test-helpers/ipc-harness.js +17 -0
  144. package/dist/test-helpers/ipc-harness.js.map +1 -0
  145. package/dist/test-helpers/worker-message-builders.d.ts +21 -0
  146. package/dist/test-helpers/worker-message-builders.d.ts.map +1 -0
  147. package/dist/test-helpers/worker-message-builders.js +62 -0
  148. package/dist/test-helpers/worker-message-builders.js.map +1 -0
  149. package/dist/turn-continuation.d.ts +28 -0
  150. package/dist/turn-continuation.d.ts.map +1 -0
  151. package/dist/turn-continuation.js +80 -0
  152. package/dist/turn-continuation.js.map +1 -0
  153. package/dist/turn-execution-error.d.ts +39 -0
  154. package/dist/turn-execution-error.d.ts.map +1 -0
  155. package/dist/turn-execution-error.js +64 -0
  156. package/dist/turn-execution-error.js.map +1 -0
  157. package/dist/turn-execution-result.d.ts +35 -0
  158. package/dist/turn-execution-result.d.ts.map +1 -0
  159. package/dist/turn-execution-result.js +21 -0
  160. package/dist/turn-execution-result.js.map +1 -0
  161. package/dist/turn-outcome-tool-session.d.ts +50 -0
  162. package/dist/turn-outcome-tool-session.d.ts.map +1 -0
  163. package/dist/turn-outcome-tool-session.js +209 -0
  164. package/dist/turn-outcome-tool-session.js.map +1 -0
  165. package/dist/turn-record-id.d.ts +3 -0
  166. package/dist/turn-record-id.d.ts.map +1 -0
  167. package/dist/turn-record-id.js +10 -0
  168. package/dist/turn-record-id.js.map +1 -0
  169. package/dist/turn-result-markdown.d.ts +74 -0
  170. package/dist/turn-result-markdown.d.ts.map +1 -0
  171. package/dist/turn-result-markdown.js +263 -0
  172. package/dist/turn-result-markdown.js.map +1 -0
  173. package/dist/turn-tree-strategy.d.ts +29 -0
  174. package/dist/turn-tree-strategy.d.ts.map +1 -0
  175. package/dist/turn-tree-strategy.js +80 -0
  176. package/dist/turn-tree-strategy.js.map +1 -0
  177. package/dist/worker-entry.d.ts +2 -2
  178. package/dist/worker-entry.d.ts.map +1 -0
  179. package/dist/worker-entry.js +4 -8
  180. package/dist/worker-entry.js.map +1 -1
  181. package/dist/worker-http.d.ts +2 -0
  182. package/dist/worker-http.d.ts.map +1 -0
  183. package/dist/worker-http.js +9 -0
  184. package/dist/worker-http.js.map +1 -0
  185. package/dist/worker-ipc-reporter.d.ts +29 -0
  186. package/dist/worker-ipc-reporter.d.ts.map +1 -0
  187. package/dist/worker-ipc-reporter.js +58 -0
  188. package/dist/worker-ipc-reporter.js.map +1 -0
  189. package/dist/worker-payloads.d.ts +10 -0
  190. package/dist/worker-payloads.d.ts.map +1 -0
  191. package/dist/worker-payloads.js +66 -0
  192. package/dist/worker-payloads.js.map +1 -0
  193. package/dist/worker-start-payload.d.ts +7 -0
  194. package/dist/worker-start-payload.d.ts.map +1 -0
  195. package/dist/worker-start-payload.js +5 -0
  196. package/dist/worker-start-payload.js.map +1 -0
  197. package/dist/workspace/manifest.d.ts +35 -0
  198. package/dist/workspace/manifest.d.ts.map +1 -0
  199. package/dist/workspace/manifest.js +79 -0
  200. package/dist/workspace/manifest.js.map +1 -0
  201. package/dist/workspace/node-run-root-git-ops.d.ts +17 -0
  202. package/dist/workspace/node-run-root-git-ops.d.ts.map +1 -0
  203. package/dist/workspace/node-run-root-git-ops.js +96 -0
  204. package/dist/workspace/node-run-root-git-ops.js.map +1 -0
  205. package/dist/workspace/resource-aggregator.d.ts +15 -0
  206. package/dist/workspace/resource-aggregator.d.ts.map +1 -0
  207. package/dist/workspace/resource-aggregator.js +39 -0
  208. package/dist/workspace/resource-aggregator.js.map +1 -0
  209. package/dist/workspace/run-root.d.ts +52 -0
  210. package/dist/workspace/run-root.d.ts.map +1 -0
  211. package/dist/workspace/run-root.js +209 -0
  212. package/dist/workspace/run-root.js.map +1 -0
  213. package/package.json +7 -7
@@ -0,0 +1,1100 @@
1
+ import { WORKER_API_VERSION, } from "@leitwerk-dev/worker-protocol";
2
+ import { inputDeliveryToItem } from "../worker-payloads.js";
3
+ import { normalizeWorkerFailure, } from "./failure-policy.js";
4
+ import { resolveWorkerSnapshotPolicy } from "./snapshot-policy.js";
5
+ const HELLO = {
6
+ kind: "protocol",
7
+ type: "worker.hello",
8
+ payload: {
9
+ version: "0.1.0",
10
+ apiVersion: WORKER_API_VERSION,
11
+ capabilities: ["worker.ipc/v1", "input.batch", "worker.stop", "worker.abort_turn"],
12
+ },
13
+ };
14
+ export function createInitialWorkerRuntimeState() {
15
+ return {
16
+ phase: { kind: "init" },
17
+ session: null,
18
+ inputQueue: [],
19
+ lastSequenceConsumed: 0,
20
+ sessionTainted: false,
21
+ piTurnActive: false,
22
+ work: {
23
+ deliveryHeadSequence: null,
24
+ publication: { kind: "none" },
25
+ },
26
+ credential: null,
27
+ timers: { heartbeat: null, acceptance_retry: null, credential_poll: null },
28
+ };
29
+ }
30
+ export function deriveReportedWorkerState(state) {
31
+ if (state.phase.kind === "draining" || state.phase.kind === "cleaning")
32
+ return "draining";
33
+ if ((state.phase.kind === "active" &&
34
+ (state.phase.turnStatus === "executing" ||
35
+ state.work.publication.kind === "terminal_snapshot")) ||
36
+ state.work.deliveryHeadSequence !== null)
37
+ return "busy";
38
+ return "idle";
39
+ }
40
+ /** Pure FIFO policy. Queue storage remains reducer-owned. */
41
+ export function decideWorkerInputEffect(input) {
42
+ const head = input.items[0];
43
+ if (!head)
44
+ return input.mayStartTurn && !input.sessionTainted
45
+ ? { kind: "start_turn", inputs: [] }
46
+ : { kind: "none" };
47
+ if (input.sessionTainted)
48
+ return { kind: "blocked", reason: "session_tainted" };
49
+ if (head.target) {
50
+ if (!input.mayStartTurn)
51
+ return { kind: "none" };
52
+ const targeted = [];
53
+ for (const item of input.items) {
54
+ if (!item.target)
55
+ break;
56
+ targeted.push(item);
57
+ }
58
+ return { kind: "start_turn", inputs: targeted };
59
+ }
60
+ const ordinary = [];
61
+ for (const item of input.items) {
62
+ if (item.target)
63
+ break;
64
+ ordinary.push(item);
65
+ }
66
+ return input.piAvailable
67
+ ? { kind: "deliver", inputs: ordinary }
68
+ : { kind: "consume_ignored", inputs: ordinary };
69
+ }
70
+ function enqueueInputs(current, incoming) {
71
+ const byId = new Map(current.map((item) => [item.inputId, item]));
72
+ for (const item of incoming)
73
+ byId.set(item.inputId, item);
74
+ return [...byId.values()].sort((left, right) => left.sequence - right.sequence);
75
+ }
76
+ function protocol(type, payload) {
77
+ return { kind: "protocol", type, payload };
78
+ }
79
+ function currentStateName(state) {
80
+ switch (state.phase.kind) {
81
+ case "readying":
82
+ case "waiting_for_acceptance":
83
+ return "idle";
84
+ case "activating":
85
+ return "busy";
86
+ case "active":
87
+ return state.phase.turnStatus === "executing" ||
88
+ state.work.publication.kind === "terminal_snapshot"
89
+ ? "busy"
90
+ : "idle";
91
+ case "cleaning":
92
+ return "cleanup";
93
+ default:
94
+ return state.phase.kind;
95
+ }
96
+ }
97
+ function failureContext(state) {
98
+ return state.session
99
+ ? {
100
+ selectedTurnId: state.session.selectedTurnId,
101
+ lifecycleStatus: state.session.processSnapshot.lifecycleStatus,
102
+ snapshotSource: sessionSnapshotSource(state.session),
103
+ }
104
+ : null;
105
+ }
106
+ function sessionSnapshotSource(session) {
107
+ return {
108
+ kind: session.kind,
109
+ treeFile: session.treeFile,
110
+ };
111
+ }
112
+ function snapshotMatches(snapshot, event) {
113
+ return snapshot.point === event.point && snapshot.turnRecordId === event.turnRecordId;
114
+ }
115
+ function hasActivePublication(state) {
116
+ return state.work.publication.kind !== "none";
117
+ }
118
+ function requireNoPublication(state) {
119
+ if (hasActivePublication(state))
120
+ throw new Error("Snapshot publication is already active");
121
+ }
122
+ function beginReadySnapshot(state, source, outputs) {
123
+ requireNoPublication(state);
124
+ const snapshot = {
125
+ point: "after_worker_ready",
126
+ turnRecordId: null,
127
+ required: false,
128
+ };
129
+ outputs.push({ kind: "upload_snapshot", ...snapshot, source });
130
+ return {
131
+ ...state,
132
+ work: { ...state.work, publication: { kind: "ready_snapshot", snapshot } },
133
+ };
134
+ }
135
+ function beginTerminalSnapshot(state, point, turnRecordId, terminal, source, outputs) {
136
+ requireNoPublication(state);
137
+ const snapshot = { point, turnRecordId, required: true };
138
+ outputs.push({ kind: "upload_snapshot", ...snapshot, source });
139
+ return {
140
+ ...state,
141
+ work: {
142
+ ...state.work,
143
+ publication: { kind: "terminal_snapshot", snapshot, terminal },
144
+ },
145
+ };
146
+ }
147
+ function beginCleanupSnapshot(state, source, outputs) {
148
+ requireNoPublication(state);
149
+ const snapshot = {
150
+ point: "before_cleanup_completed",
151
+ turnRecordId: null,
152
+ required: true,
153
+ };
154
+ outputs.push({ kind: "upload_snapshot", ...snapshot, source });
155
+ return {
156
+ ...state,
157
+ work: { ...state.work, publication: { kind: "cleanup_snapshot", snapshot } },
158
+ };
159
+ }
160
+ function beginFatalSnapshot(state, fatal, source, afterSnapshot, outputs) {
161
+ requireNoPublication(state);
162
+ const snapshot = {
163
+ point: "before_worker_failed",
164
+ turnRecordId: null,
165
+ required: false,
166
+ };
167
+ outputs.push({ kind: "upload_snapshot", ...snapshot, source });
168
+ return {
169
+ ...state,
170
+ work: {
171
+ ...state.work,
172
+ publication: { kind: "fatal_snapshot", snapshot, fatal, afterSnapshot },
173
+ },
174
+ };
175
+ }
176
+ function finishFatal(state, fatal) {
177
+ const outputs = [
178
+ protocol("worker.failed", fatal.payload),
179
+ { kind: "close_transport" },
180
+ ];
181
+ if (fatal.exitCode !== undefined)
182
+ outputs.push({ kind: "exit", code: fatal.exitCode });
183
+ return {
184
+ state: {
185
+ ...state,
186
+ work: { ...state.work, publication: { kind: "none" } },
187
+ phase: { kind: "exited" },
188
+ },
189
+ outputs,
190
+ };
191
+ }
192
+ function failureOutputs(state, failure) {
193
+ const disposition = normalizeWorkerFailure(failure);
194
+ const outputs = [];
195
+ if (disposition.diagnostic)
196
+ outputs.push({
197
+ kind: "diagnostic",
198
+ payload: disposition.diagnostic,
199
+ });
200
+ if (disposition.stderrMessage)
201
+ outputs.push({ kind: "stderr", message: disposition.stderrMessage });
202
+ let next = state;
203
+ switch (disposition.terminal.kind) {
204
+ case "turn_failed":
205
+ outputs.push(protocol("worker.turn_failed", disposition.terminal.payload));
206
+ outputs.push(protocol("worker.lifecycle_parked", disposition.terminal.park));
207
+ break;
208
+ case "park":
209
+ outputs.push(protocol("worker.lifecycle_parked", disposition.terminal.payload));
210
+ break;
211
+ case "worker_failed": {
212
+ const fatal = {
213
+ payload: disposition.terminal.payload,
214
+ ...(disposition.exitCode === undefined ? {} : { exitCode: disposition.exitCode }),
215
+ };
216
+ if (disposition.snapshot && !hasActivePublication(state)) {
217
+ const afterSnapshot = state.phase.kind === "cleaning" && state.phase.stage === "publication"
218
+ ? "cleanup"
219
+ : "exit";
220
+ next = beginFatalSnapshot(next, fatal, disposition.snapshot.source, afterSnapshot, outputs);
221
+ break;
222
+ }
223
+ const finished = finishFatal(next, fatal);
224
+ next = finished.state;
225
+ outputs.push(...finished.outputs);
226
+ break;
227
+ }
228
+ case "transport_lost":
229
+ next = {
230
+ ...next,
231
+ work: { ...next.work, publication: { kind: "none" } },
232
+ phase: { kind: "exited" },
233
+ };
234
+ outputs.push({ kind: "close_transport" }, { kind: "exit", code: disposition.exitCode ?? 1 });
235
+ break;
236
+ }
237
+ return { state: next, outputs };
238
+ }
239
+ function matchesBootstrap(state, startRecordId) {
240
+ return ((state.phase.kind === "bootstrapping" && state.phase.startRecordId === startRecordId) ||
241
+ (state.phase.kind === "draining" &&
242
+ state.phase.operation?.kind === "bootstrap" &&
243
+ state.phase.operation.startRecordId === startRecordId));
244
+ }
245
+ function matchesActivation(state, startRecordId, turnRecordId) {
246
+ if (state.phase.kind === "activating") {
247
+ return state.phase.startRecordId === startRecordId && state.phase.turnRecordId === turnRecordId;
248
+ }
249
+ const operation = state.phase.kind === "draining" ? state.phase.operation : null;
250
+ return (operation?.kind === "activation" &&
251
+ operation.startRecordId === startRecordId &&
252
+ operation.turnRecordId === turnRecordId);
253
+ }
254
+ function matchesTurn(state, turnRecordId) {
255
+ if (state.phase.kind === "active") {
256
+ return state.phase.turnStatus === "executing" && state.phase.turnRecordId === turnRecordId;
257
+ }
258
+ return (state.phase.kind === "draining" &&
259
+ state.phase.operation?.kind === "turn" &&
260
+ state.phase.operation.turnRecordId === turnRecordId);
261
+ }
262
+ function finishDrainingOperation(state) {
263
+ return state.phase.kind === "draining"
264
+ ? { ...state, phase: { ...state.phase, operation: null } }
265
+ : state;
266
+ }
267
+ function noActiveWork(state) {
268
+ return (state.phase.kind === "draining" &&
269
+ state.phase.operation === null &&
270
+ state.work.deliveryHeadSequence === null &&
271
+ state.work.publication.kind === "none");
272
+ }
273
+ function inputConsumedFact(item, deliveryMode, meta = {}) {
274
+ return protocol("worker.input_consumed", {
275
+ inputId: item.inputId,
276
+ sequence: item.sequence,
277
+ deliveryMode,
278
+ ...meta,
279
+ });
280
+ }
281
+ function removeAppliedTargeted(state, applied, outputs) {
282
+ const queue = [...state.inputQueue];
283
+ let last = state.lastSequenceConsumed;
284
+ for (const item of applied) {
285
+ const head = queue[0];
286
+ if (!head || head.inputId !== item.inputId || head.sequence !== item.sequence || !head.target)
287
+ break;
288
+ queue.shift();
289
+ last = Math.max(last, item.sequence);
290
+ outputs.push(inputConsumedFact(item, "append_message", item.meta ?? {}));
291
+ }
292
+ return { ...state, inputQueue: queue, lastSequenceConsumed: last };
293
+ }
294
+ function armTimer(state, outputs, name, delayMs, correlation) {
295
+ outputs.push({ kind: "arm_timer", name, delayMs, correlation });
296
+ return { ...state, timers: { ...state.timers, [name]: correlation } };
297
+ }
298
+ function beginActivation(state, startRecordId, turnRecordId, outputs) {
299
+ if (!state.session)
300
+ return state;
301
+ outputs.push({ kind: "cancel_timer", name: "acceptance_retry" });
302
+ outputs.push({ kind: "activate", startRecordId, turnRecordId, session: state.session });
303
+ return {
304
+ ...state,
305
+ phase: { kind: "activating", startRecordId, turnRecordId },
306
+ timers: { ...state.timers, acceptance_retry: null },
307
+ };
308
+ }
309
+ function finishReadying(state, outputs) {
310
+ if (state.phase.kind !== "readying" || state.credential?.sampling)
311
+ return state;
312
+ const readying = state.phase;
313
+ const next = state;
314
+ if (hasActivePublication(next))
315
+ return next;
316
+ const { startRecordId, proposedTurnRecordId, acceptedId } = readying;
317
+ if (acceptedId)
318
+ return beginActivation(next, startRecordId, acceptedId, outputs);
319
+ outputs.push(protocol("worker.turn_started", { startRecordId, proposedTurnRecordId }));
320
+ return armTimer({ ...next, phase: { kind: "waiting_for_acceptance", startRecordId, proposedTurnRecordId } }, outputs, "acceptance_retry", 1_000, startRecordId);
321
+ }
322
+ function advance(state, outputs) {
323
+ let next = finishReadying(state, outputs);
324
+ if (next.phase.kind === "draining" && noActiveWork(next)) {
325
+ const { reason, exitAfterCleanup } = next.phase;
326
+ outputs.push(protocol("worker.cleanup_started", { reason }));
327
+ const cleanupSnapshot = next.session
328
+ ? resolveWorkerSnapshotPolicy("before_cleanup_completed", next.session.kind, next.session.piAvailable)
329
+ : { upload: false };
330
+ if (cleanupSnapshot.upload && next.session) {
331
+ next = beginCleanupSnapshot({
332
+ ...next,
333
+ phase: { kind: "cleaning", reason, exitAfterCleanup, stage: "publication" },
334
+ }, sessionSnapshotSource(next.session), outputs);
335
+ }
336
+ else {
337
+ outputs.push({ kind: "cleanup" });
338
+ next = {
339
+ ...next,
340
+ phase: { kind: "cleaning", reason, exitAfterCleanup, stage: "resources" },
341
+ };
342
+ }
343
+ return next;
344
+ }
345
+ if ((next.phase.kind !== "active" && next.phase.kind !== "waiting_for_acceptance") ||
346
+ next.work.deliveryHeadSequence !== null ||
347
+ hasActivePublication(next))
348
+ return next;
349
+ const mayStartTurn = next.phase.kind === "active" && next.phase.turnStatus === "pending";
350
+ if (next.phase.kind === "waiting_for_acceptance" && next.session?.kind === "llm")
351
+ return next;
352
+ const decision = decideWorkerInputEffect({
353
+ items: next.inputQueue,
354
+ sessionTainted: next.sessionTainted,
355
+ piAvailable: next.session?.piAvailable ?? false,
356
+ mayStartTurn,
357
+ });
358
+ if (decision.kind === "blocked") {
359
+ outputs.push({
360
+ kind: "diagnostic",
361
+ payload: {
362
+ level: "warn",
363
+ code: "input.skipped_session_tainted",
364
+ message: "Skipping queued inputs because the Pi session is tainted",
365
+ details: { skippedInputCount: next.inputQueue.length },
366
+ },
367
+ });
368
+ return next;
369
+ }
370
+ if (decision.kind === "consume_ignored") {
371
+ const ids = new Set(decision.inputs.map((item) => item.inputId));
372
+ for (const item of decision.inputs)
373
+ outputs.push(inputConsumedFact(item, "ignored"));
374
+ next = {
375
+ ...next,
376
+ inputQueue: next.inputQueue.filter((item) => !ids.has(item.inputId)),
377
+ lastSequenceConsumed: Math.max(next.lastSequenceConsumed, ...decision.inputs.map((item) => item.sequence)),
378
+ };
379
+ return advance(next, outputs);
380
+ }
381
+ if (decision.kind === "deliver") {
382
+ const headSequence = decision.inputs[0].sequence;
383
+ outputs.push({
384
+ kind: "deliver_inputs",
385
+ headSequence,
386
+ inputs: decision.inputs,
387
+ piTurnActive: next.piTurnActive,
388
+ });
389
+ return { ...next, work: { ...next.work, deliveryHeadSequence: headSequence } };
390
+ }
391
+ if (decision.kind === "start_turn" && next.session && next.phase.kind === "active") {
392
+ outputs.push({
393
+ kind: "execute_turn",
394
+ turnRecordId: next.phase.turnRecordId,
395
+ targetedInputs: decision.inputs,
396
+ session: next.session,
397
+ });
398
+ return {
399
+ ...next,
400
+ phase: { ...next.phase, turnStatus: "executing" },
401
+ };
402
+ }
403
+ return next;
404
+ }
405
+ function withReportedTransition(previous, next, event, outputs) {
406
+ const from = deriveReportedWorkerState(previous);
407
+ const to = deriveReportedWorkerState(next);
408
+ if (from !== to && next.phase.kind !== "exited") {
409
+ outputs.push(protocol("worker.state", { from, to, reason: event.kind }));
410
+ }
411
+ return { state: next, outputs };
412
+ }
413
+ /** The sole pure owner of worker lifecycle decisions and canonical facts. */
414
+ export function reduceWorkerRuntime(state, event) {
415
+ let next = state;
416
+ const outputs = [];
417
+ if (state.phase.kind === "exited" && event.kind !== "runtime_started")
418
+ return { state, outputs };
419
+ switch (event.kind) {
420
+ case "runtime_started":
421
+ if (state.phase.kind !== "init")
422
+ break;
423
+ next = { ...state, phase: { kind: "waiting_for_start" } };
424
+ outputs.push(HELLO);
425
+ break;
426
+ case "transport_connected":
427
+ outputs.push(HELLO);
428
+ if (state.session) {
429
+ outputs.push(protocol("worker.heartbeat", {
430
+ state: deriveReportedWorkerState(state),
431
+ lastSequenceConsumed: state.lastSequenceConsumed,
432
+ currentSelectedTurnId: state.session.selectedTurnId,
433
+ }));
434
+ }
435
+ break;
436
+ case "transport_failed": {
437
+ const failed = failureOutputs(state, { kind: "transport", error: event.error });
438
+ next = failed.state;
439
+ outputs.push(...failed.outputs);
440
+ break;
441
+ }
442
+ case "stop_requested":
443
+ if (state.phase.kind === "cleaning" || state.phase.kind === "draining")
444
+ break;
445
+ {
446
+ const operation = state.phase.kind === "bootstrapping"
447
+ ? {
448
+ kind: "bootstrap",
449
+ startRecordId: state.phase.startRecordId,
450
+ proposedTurnRecordId: state.phase.proposedTurnRecordId,
451
+ }
452
+ : state.phase.kind === "activating"
453
+ ? {
454
+ kind: "activation",
455
+ startRecordId: state.phase.startRecordId,
456
+ turnRecordId: state.phase.turnRecordId,
457
+ }
458
+ : state.phase.kind === "active" && state.phase.turnStatus === "executing"
459
+ ? { kind: "turn", turnRecordId: state.phase.turnRecordId }
460
+ : null;
461
+ next = {
462
+ ...state,
463
+ phase: {
464
+ kind: "draining",
465
+ reason: event.reason,
466
+ exitAfterCleanup: event.exitAfterCleanup,
467
+ operation,
468
+ },
469
+ };
470
+ }
471
+ for (const name of Object.keys(state.timers))
472
+ outputs.push({ kind: "cancel_timer", name });
473
+ next = {
474
+ ...next,
475
+ timers: { heartbeat: null, acceptance_retry: null, credential_poll: null },
476
+ credential: null,
477
+ };
478
+ break;
479
+ case "operator_abort_observed":
480
+ break;
481
+ case "pi_turn_started":
482
+ next = { ...state, piTurnActive: true };
483
+ break;
484
+ case "pi_turn_ended":
485
+ next = { ...state, piTurnActive: false };
486
+ break;
487
+ case "session_tainted":
488
+ if (!state.sessionTainted) {
489
+ next = { ...state, sessionTainted: true };
490
+ outputs.push({
491
+ kind: "extension",
492
+ event: "worker.session_tainted",
493
+ payload: { reason: event.reason },
494
+ });
495
+ }
496
+ break;
497
+ case "server_message": {
498
+ const message = event.message;
499
+ if (message.type === "worker.stop") {
500
+ return reduceWorkerRuntime(state, {
501
+ kind: "stop_requested",
502
+ reason: message.payload.reason,
503
+ exitAfterCleanup: true,
504
+ });
505
+ }
506
+ if (message.type === "worker.abort_turn")
507
+ break;
508
+ if (message.type === "worker.start") {
509
+ if (state.phase.kind !== "waiting_for_start")
510
+ break;
511
+ const startRecordId = message.payload.turnStart.id;
512
+ next = {
513
+ ...state,
514
+ phase: {
515
+ kind: "bootstrapping",
516
+ startRecordId,
517
+ proposedTurnRecordId: message.payload.turnStart.proposedTurnRecordId,
518
+ },
519
+ sessionTainted: false,
520
+ };
521
+ outputs.push({ kind: "bootstrap", startRecordId, payload: message.payload });
522
+ break;
523
+ }
524
+ if (message.type === "input.batch") {
525
+ if (state.phase.kind === "waiting_for_start" || state.phase.kind === "init")
526
+ break;
527
+ const incoming = message.payload.inputs
528
+ .map(inputDeliveryToItem)
529
+ .filter((item) => item.sequence > state.lastSequenceConsumed);
530
+ next = { ...state, inputQueue: enqueueInputs(state.inputQueue, incoming) };
531
+ break;
532
+ }
533
+ if (message.type === "worker.turn_start_accepted") {
534
+ if (state.phase.kind === "readying" &&
535
+ message.payload.startRecordId === state.phase.startRecordId) {
536
+ next = { ...state, phase: { ...state.phase, acceptedId: message.payload.turnRecordId } };
537
+ break;
538
+ }
539
+ if (state.phase.kind !== "waiting_for_acceptance" ||
540
+ message.payload.startRecordId !== state.phase.startRecordId)
541
+ break;
542
+ next = beginActivation(state, message.payload.startRecordId, message.payload.turnRecordId, outputs);
543
+ break;
544
+ }
545
+ if (message.type === "worker.credential_update_accepted") {
546
+ const credential = state.credential;
547
+ if (!credential?.enabled ||
548
+ !credential.updatePending ||
549
+ message.payload.providerId !== credential.descriptor.providerId)
550
+ break;
551
+ if (!message.payload.accepted || message.payload.currentRevision === null) {
552
+ next = {
553
+ ...state,
554
+ credential: {
555
+ ...credential,
556
+ enabled: false,
557
+ updatePending: false,
558
+ pendingFingerprint: null,
559
+ },
560
+ };
561
+ outputs.push({
562
+ kind: "diagnostic",
563
+ payload: {
564
+ level: "warn",
565
+ code: "credential.refresh_rejected",
566
+ message: message.payload.safeReason ?? "Credential refresh was rejected",
567
+ },
568
+ stderr: message.payload.safeReason,
569
+ });
570
+ }
571
+ else {
572
+ next = {
573
+ ...state,
574
+ credential: {
575
+ ...credential,
576
+ revision: message.payload.currentRevision,
577
+ baselineFingerprint: credential.pendingFingerprint ?? credential.baselineFingerprint,
578
+ pendingFingerprint: null,
579
+ updatePending: false,
580
+ sampling: true,
581
+ },
582
+ };
583
+ outputs.push({
584
+ kind: "sample_credentials",
585
+ descriptor: credential.descriptor,
586
+ baseline: false,
587
+ });
588
+ }
589
+ }
590
+ break;
591
+ }
592
+ case "bootstrap_succeeded": {
593
+ if (!matchesBootstrap(state, event.startRecordId))
594
+ break;
595
+ const completion = event.completion;
596
+ const acceptedId = completion.session.acceptedTurnRecordId;
597
+ const credential = completion.credentialRefresh
598
+ ? {
599
+ descriptor: completion.credentialRefresh,
600
+ baselineFingerprint: null,
601
+ pendingFingerprint: null,
602
+ revision: completion.credentialRefresh.revision,
603
+ sampling: true,
604
+ updatePending: false,
605
+ enabled: true,
606
+ }
607
+ : null;
608
+ const wasDraining = state.phase.kind === "draining";
609
+ next = {
610
+ ...state,
611
+ phase: state.phase.kind === "draining"
612
+ ? { ...state.phase, operation: null }
613
+ : {
614
+ kind: "readying",
615
+ startRecordId: event.startRecordId,
616
+ proposedTurnRecordId: completion.session.proposedTurnRecordId,
617
+ acceptedId,
618
+ },
619
+ session: completion.session,
620
+ inputQueue: enqueueInputs(state.inputQueue, completion.pendingInputs.filter((item) => item.sequence > state.lastSequenceConsumed)),
621
+ credential: wasDraining ? null : credential,
622
+ };
623
+ for (const message of completion.diagnostics)
624
+ outputs.push({
625
+ kind: "diagnostic",
626
+ payload: { level: "warn", code: "bootstrap.diagnostic", message },
627
+ });
628
+ outputs.push(protocol("worker.ready", completion.readyPayload));
629
+ if (wasDraining)
630
+ break;
631
+ const readySnapshot = resolveWorkerSnapshotPolicy("after_worker_ready", completion.session.kind, completion.session.piAvailable);
632
+ if (readySnapshot.upload)
633
+ next = beginReadySnapshot(next, sessionSnapshotSource(completion.session), outputs);
634
+ next = armTimer(next, outputs, "heartbeat", completion.session.settings.heartbeatIntervalMs, event.startRecordId);
635
+ if (completion.credentialRefresh)
636
+ outputs.push({
637
+ kind: "sample_credentials",
638
+ descriptor: completion.credentialRefresh,
639
+ baseline: true,
640
+ });
641
+ break;
642
+ }
643
+ case "bootstrap_failed":
644
+ if (!matchesBootstrap(state, event.startRecordId))
645
+ break;
646
+ if (state.phase.kind === "draining") {
647
+ next = finishDrainingOperation(state);
648
+ break;
649
+ }
650
+ {
651
+ const failed = failureOutputs(state, {
652
+ kind: "bootstrap",
653
+ error: event.error,
654
+ payload: event.payload,
655
+ });
656
+ next = failed.state;
657
+ outputs.push(...failed.outputs);
658
+ }
659
+ break;
660
+ case "activation_succeeded":
661
+ if (!matchesActivation(state, event.startRecordId, event.turnRecordId))
662
+ break;
663
+ next = {
664
+ ...state,
665
+ phase: state.phase.kind === "draining"
666
+ ? { ...state.phase, operation: null }
667
+ : {
668
+ kind: "active",
669
+ startRecordId: event.startRecordId,
670
+ turnRecordId: event.turnRecordId,
671
+ turnStatus: "pending",
672
+ },
673
+ session: state.session?.kind === "llm"
674
+ ? {
675
+ ...state.session,
676
+ piAvailable: true,
677
+ activeModelProfileId: state.session.processSnapshot.selectedTurnModelProfileId ?? null,
678
+ }
679
+ : state.session,
680
+ };
681
+ for (const message of event.diagnostics)
682
+ outputs.push({
683
+ kind: "diagnostic",
684
+ payload: { level: "warn", code: "bootstrap.diagnostic", message },
685
+ });
686
+ if (state.session?.kind === "llm" && state.phase.kind !== "draining")
687
+ outputs.push({
688
+ kind: "extension",
689
+ event: "worker.handle_ready",
690
+ payload: {
691
+ treeFile: state.session.treeFile,
692
+ workspaceRoot: state.session.workspaceRoot,
693
+ },
694
+ });
695
+ break;
696
+ case "activation_failed":
697
+ if (!matchesActivation(state, event.startRecordId, event.turnRecordId))
698
+ break;
699
+ if (state.phase.kind === "draining") {
700
+ next = finishDrainingOperation(state);
701
+ }
702
+ else {
703
+ const failed = failureOutputs(next, {
704
+ kind: "dispatch",
705
+ error: event.error,
706
+ state: "busy",
707
+ session: failureContext(state),
708
+ });
709
+ next = failed.state;
710
+ outputs.push(...failed.outputs);
711
+ }
712
+ break;
713
+ case "inputs_delivered": {
714
+ if (state.work.deliveryHeadSequence !== event.headSequence ||
715
+ state.inputQueue[0]?.sequence !== event.headSequence)
716
+ break;
717
+ const deliveredIds = new Set(event.delivered.map((item) => item.inputId));
718
+ let last = state.lastSequenceConsumed;
719
+ for (const delivered of event.delivered) {
720
+ last = Math.max(last, delivered.sequence);
721
+ outputs.push(inputConsumedFact(delivered, delivered.deliveryMode, event.meta ?? {}));
722
+ }
723
+ next = {
724
+ ...state,
725
+ inputQueue: state.inputQueue.filter((item) => !deliveredIds.has(item.inputId)),
726
+ lastSequenceConsumed: last,
727
+ work: { ...state.work, deliveryHeadSequence: null },
728
+ };
729
+ break;
730
+ }
731
+ case "input_delivery_failed":
732
+ if (state.work.deliveryHeadSequence !== event.headSequence)
733
+ break;
734
+ next = { ...state, work: { ...state.work, deliveryHeadSequence: null } };
735
+ if (state.phase.kind !== "draining") {
736
+ const failed = failureOutputs(next, {
737
+ kind: "dispatch",
738
+ error: event.error,
739
+ state: currentStateName(state),
740
+ session: failureContext(state),
741
+ });
742
+ next = failed.state;
743
+ outputs.push(...failed.outputs);
744
+ }
745
+ break;
746
+ case "turn_completed": {
747
+ if (!matchesTurn(state, event.turnRecordId))
748
+ break;
749
+ next = removeAppliedTargeted(finishDrainingOperation(state), event.result.appliedTargetedInputs, outputs);
750
+ if (event.result.kind === "parked") {
751
+ outputs.push(protocol("worker.lifecycle_parked", {
752
+ selectedTurnId: state.session?.selectedTurnId ?? null,
753
+ reason: event.result.reason,
754
+ }));
755
+ next = {
756
+ ...next,
757
+ phase: state.phase.kind === "active"
758
+ ? { ...state.phase, turnStatus: "completed" }
759
+ : next.phase,
760
+ };
761
+ break;
762
+ }
763
+ let pending;
764
+ if (event.result.kind === "outcome") {
765
+ pending = {
766
+ fact: protocol("worker.turn_outcome", {
767
+ turnRecordId: event.result.meta.turnRecordId,
768
+ turnId: event.result.turnId,
769
+ turnType: event.result.meta.turnType ?? "llm",
770
+ outcome: event.result.outcome,
771
+ params: event.result.params,
772
+ pathType: event.result.meta.pathType,
773
+ forkPiEntryId: event.result.meta.forkPiEntryId ?? null,
774
+ resultPiEntryId: event.result.meta.resultPiEntryId ?? null,
775
+ turnResultMarkdown: event.result.meta.turnResultMarkdown ?? null,
776
+ rootEntryId: event.result.meta.rootEntryId ?? null,
777
+ }),
778
+ park: null,
779
+ correlation: {
780
+ turnRecordId: event.result.meta.turnRecordId,
781
+ turnId: event.result.turnId,
782
+ turnType: event.result.meta.turnType,
783
+ pathType: event.result.meta.pathType,
784
+ forkPiEntryId: event.result.meta.forkPiEntryId,
785
+ resultPiEntryId: event.result.meta.resultPiEntryId,
786
+ },
787
+ };
788
+ }
789
+ else {
790
+ const disposition = normalizeWorkerFailure({
791
+ kind: "turn",
792
+ error: event.result.failure.failure,
793
+ correlation: event.result.failure,
794
+ session: failureContext(state),
795
+ });
796
+ if (disposition.terminal.kind !== "turn_failed")
797
+ throw new Error("Turn failure policy did not produce a turn failure");
798
+ pending = {
799
+ fact: protocol("worker.turn_failed", disposition.terminal.payload),
800
+ park: disposition.terminal.park,
801
+ correlation: event.result.failure,
802
+ };
803
+ }
804
+ next = {
805
+ ...next,
806
+ phase: state.phase.kind === "active" ? { ...state.phase, turnStatus: "completed" } : next.phase,
807
+ };
808
+ if (state.session?.kind === "automatic") {
809
+ outputs.push(pending.fact);
810
+ if (pending.park)
811
+ outputs.push(protocol("worker.lifecycle_parked", pending.park));
812
+ }
813
+ else if (state.session) {
814
+ const point = event.result.kind === "outcome" ? "before_turn_outcome" : "before_turn_failed";
815
+ const snapshotPolicy = resolveWorkerSnapshotPolicy(point, state.session.kind, state.session.piAvailable);
816
+ if (!snapshotPolicy.upload)
817
+ throw new Error("LLM terminal snapshot policy unexpectedly skipped upload");
818
+ next = beginTerminalSnapshot(next, point, event.turnRecordId, pending, sessionSnapshotSource(state.session), outputs);
819
+ }
820
+ break;
821
+ }
822
+ case "turn_defect":
823
+ if (!matchesTurn(state, event.turnRecordId))
824
+ break;
825
+ if (state.phase.kind === "draining") {
826
+ next = finishDrainingOperation(state);
827
+ }
828
+ else {
829
+ const failed = failureOutputs(next, {
830
+ kind: "dispatch",
831
+ error: event.error,
832
+ state: "busy",
833
+ session: failureContext(state),
834
+ });
835
+ next = failed.state;
836
+ outputs.push(...failed.outputs);
837
+ }
838
+ break;
839
+ case "snapshot_succeeded": {
840
+ const publication = state.work.publication;
841
+ switch (publication.kind) {
842
+ case "none":
843
+ case "fatal_pending_cleanup":
844
+ break;
845
+ case "ready_snapshot":
846
+ if (!snapshotMatches(publication.snapshot, event))
847
+ break;
848
+ next = { ...state, work: { ...state.work, publication: { kind: "none" } } };
849
+ break;
850
+ case "terminal_snapshot":
851
+ if (!snapshotMatches(publication.snapshot, event))
852
+ break;
853
+ outputs.push(publication.terminal.fact);
854
+ if (publication.terminal.park)
855
+ outputs.push(protocol("worker.lifecycle_parked", publication.terminal.park));
856
+ next = { ...state, work: { ...state.work, publication: { kind: "none" } } };
857
+ break;
858
+ case "cleanup_snapshot":
859
+ if (!snapshotMatches(publication.snapshot, event))
860
+ break;
861
+ if (state.phase.kind !== "cleaning" || state.phase.stage !== "publication")
862
+ throw new Error("Cleanup snapshot completed outside cleanup publication");
863
+ outputs.push({ kind: "cleanup" });
864
+ next = {
865
+ ...state,
866
+ phase: { ...state.phase, stage: "resources" },
867
+ work: { ...state.work, publication: { kind: "none" } },
868
+ };
869
+ break;
870
+ case "fatal_snapshot":
871
+ if (!snapshotMatches(publication.snapshot, event))
872
+ break;
873
+ if (publication.afterSnapshot === "exit") {
874
+ const finished = finishFatal(state, publication.fatal);
875
+ next = finished.state;
876
+ outputs.push(...finished.outputs);
877
+ }
878
+ else {
879
+ if (state.phase.kind !== "cleaning" || state.phase.stage !== "publication")
880
+ throw new Error("Fatal snapshot completed outside cleanup publication");
881
+ outputs.push({ kind: "cleanup" });
882
+ next = {
883
+ ...state,
884
+ phase: { ...state.phase, stage: "resources" },
885
+ work: {
886
+ ...state.work,
887
+ publication: {
888
+ kind: "fatal_pending_cleanup",
889
+ fatal: publication.fatal,
890
+ },
891
+ },
892
+ };
893
+ }
894
+ break;
895
+ }
896
+ break;
897
+ }
898
+ case "snapshot_failed": {
899
+ const publication = state.work.publication;
900
+ switch (publication.kind) {
901
+ case "none":
902
+ case "fatal_pending_cleanup":
903
+ break;
904
+ case "ready_snapshot":
905
+ if (!snapshotMatches(publication.snapshot, event))
906
+ break;
907
+ next = { ...state, work: { ...state.work, publication: { kind: "none" } } };
908
+ break;
909
+ case "terminal_snapshot": {
910
+ if (!snapshotMatches(publication.snapshot, event))
911
+ break;
912
+ const cleared = {
913
+ ...state,
914
+ work: { ...state.work, publication: { kind: "none" } },
915
+ };
916
+ const failed = failureOutputs(cleared, {
917
+ kind: "mandatory_snapshot",
918
+ error: event.error,
919
+ point: event.point,
920
+ correlation: publication.terminal.correlation,
921
+ session: failureContext(state),
922
+ });
923
+ next = failed.state;
924
+ outputs.push(...failed.outputs);
925
+ break;
926
+ }
927
+ case "cleanup_snapshot": {
928
+ if (!snapshotMatches(publication.snapshot, event))
929
+ break;
930
+ if (state.phase.kind !== "cleaning" || state.phase.stage !== "publication")
931
+ throw new Error("Cleanup snapshot failed outside cleanup publication");
932
+ const cleared = {
933
+ ...state,
934
+ work: { ...state.work, publication: { kind: "none" } },
935
+ };
936
+ const failed = failureOutputs(cleared, {
937
+ kind: "cleanup",
938
+ error: event.error,
939
+ session: failureContext(state),
940
+ });
941
+ next = failed.state;
942
+ outputs.push(...failed.outputs);
943
+ break;
944
+ }
945
+ case "fatal_snapshot":
946
+ if (!snapshotMatches(publication.snapshot, event))
947
+ break;
948
+ if (publication.afterSnapshot === "exit") {
949
+ const finished = finishFatal(state, publication.fatal);
950
+ next = finished.state;
951
+ outputs.push(...finished.outputs);
952
+ }
953
+ else {
954
+ if (state.phase.kind !== "cleaning" || state.phase.stage !== "publication")
955
+ throw new Error("Fatal snapshot failed outside cleanup publication");
956
+ outputs.push({ kind: "cleanup" });
957
+ next = {
958
+ ...state,
959
+ phase: { ...state.phase, stage: "resources" },
960
+ work: {
961
+ ...state.work,
962
+ publication: {
963
+ kind: "fatal_pending_cleanup",
964
+ fatal: publication.fatal,
965
+ },
966
+ },
967
+ };
968
+ }
969
+ break;
970
+ }
971
+ break;
972
+ }
973
+ case "timer_fired":
974
+ if (state.timers[event.name] !== event.correlation)
975
+ break;
976
+ next = { ...state, timers: { ...state.timers, [event.name]: null } };
977
+ if (event.name === "heartbeat" && state.session) {
978
+ outputs.push(protocol("worker.heartbeat", {
979
+ state: deriveReportedWorkerState(state),
980
+ lastSequenceConsumed: state.lastSequenceConsumed,
981
+ currentSelectedTurnId: state.session.selectedTurnId,
982
+ }));
983
+ next = armTimer(next, outputs, "heartbeat", state.session.settings.heartbeatIntervalMs, event.correlation);
984
+ }
985
+ else if (event.name === "acceptance_retry" &&
986
+ state.phase.kind === "waiting_for_acceptance") {
987
+ outputs.push(protocol("worker.turn_started", {
988
+ startRecordId: state.phase.startRecordId,
989
+ proposedTurnRecordId: state.phase.proposedTurnRecordId,
990
+ }));
991
+ next = armTimer(next, outputs, "acceptance_retry", 1_000, event.correlation);
992
+ }
993
+ else if (event.name === "credential_poll" &&
994
+ state.credential?.enabled &&
995
+ !state.credential.sampling &&
996
+ !state.credential.updatePending) {
997
+ outputs.push({
998
+ kind: "sample_credentials",
999
+ descriptor: state.credential.descriptor,
1000
+ baseline: false,
1001
+ });
1002
+ next = { ...next, credential: { ...state.credential, sampling: true } };
1003
+ }
1004
+ break;
1005
+ case "credential_sampled": {
1006
+ const credential = state.credential;
1007
+ if (!credential?.sampling || credential.descriptor.providerId !== event.providerId)
1008
+ break;
1009
+ if (credential.baselineFingerprint === null ||
1010
+ credential.baselineFingerprint === event.fingerprint) {
1011
+ next = armTimer({
1012
+ ...state,
1013
+ credential: {
1014
+ ...credential,
1015
+ baselineFingerprint: credential.baselineFingerprint ?? event.fingerprint,
1016
+ sampling: false,
1017
+ },
1018
+ }, outputs, "credential_poll", 500, event.providerId);
1019
+ }
1020
+ else {
1021
+ next = {
1022
+ ...state,
1023
+ credential: {
1024
+ ...credential,
1025
+ sampling: false,
1026
+ updatePending: true,
1027
+ pendingFingerprint: event.fingerprint,
1028
+ },
1029
+ };
1030
+ outputs.push(protocol("worker.credential_update", {
1031
+ providerId: event.providerId,
1032
+ expectedRevision: credential.revision,
1033
+ values: event.values,
1034
+ }));
1035
+ }
1036
+ break;
1037
+ }
1038
+ case "credential_sample_failed":
1039
+ if (!state.credential?.sampling ||
1040
+ state.credential.descriptor.providerId !== event.providerId)
1041
+ break;
1042
+ next = { ...state, credential: { ...state.credential, sampling: false } };
1043
+ outputs.push({
1044
+ kind: "diagnostic",
1045
+ payload: {
1046
+ level: "warn",
1047
+ code: "credential.refresh_failed",
1048
+ message: event.error instanceof Error ? event.error.message : String(event.error),
1049
+ },
1050
+ });
1051
+ next = armTimer(next, outputs, "credential_poll", 500, event.providerId);
1052
+ break;
1053
+ case "cleanup_succeeded":
1054
+ if (state.phase.kind !== "cleaning" || state.phase.stage !== "resources")
1055
+ break;
1056
+ if (state.work.publication.kind === "fatal_pending_cleanup") {
1057
+ const finished = finishFatal(state, state.work.publication.fatal);
1058
+ next = finished.state;
1059
+ outputs.push(...finished.outputs);
1060
+ break;
1061
+ }
1062
+ outputs.push(protocol("worker.cleanup_completed", { releasedLocks: [], removedTransientPaths: [] }));
1063
+ outputs.push({ kind: "close_transport" });
1064
+ if (state.phase.exitAfterCleanup)
1065
+ outputs.push({ kind: "exit", code: 0 });
1066
+ next = {
1067
+ ...state,
1068
+ phase: { kind: "exited" },
1069
+ session: null,
1070
+ inputQueue: [],
1071
+ };
1072
+ break;
1073
+ case "cleanup_failed": {
1074
+ if (state.phase.kind !== "cleaning" || state.phase.stage !== "resources")
1075
+ break;
1076
+ const failed = failureOutputs(state, {
1077
+ kind: "cleanup",
1078
+ error: event.error,
1079
+ session: failureContext(state),
1080
+ });
1081
+ next = failed.state;
1082
+ outputs.push(...failed.outputs);
1083
+ break;
1084
+ }
1085
+ case "invariant_failed": {
1086
+ const failed = failureOutputs(state, {
1087
+ kind: "dispatch",
1088
+ error: event.error,
1089
+ state: currentStateName(state),
1090
+ session: failureContext(state),
1091
+ });
1092
+ next = failed.state;
1093
+ outputs.push(...failed.outputs);
1094
+ break;
1095
+ }
1096
+ }
1097
+ next = advance(next, outputs);
1098
+ return withReportedTransition(state, next, event, outputs);
1099
+ }
1100
+ //# sourceMappingURL=lifecycle-reducer.js.map