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