@leitwerk-dev/worker 0.1.8 → 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 (235) 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-ZTJ7UAOC.js → chunk-Y7S2MZD3.js} +1423 -917
  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 +9 -1
  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 +4 -1
  56. package/dist/runtime/lifecycle-reducer.d.ts.map +1 -1
  57. package/dist/runtime/llm-turn-execution.d.ts +3 -8
  58. package/dist/runtime/llm-turn-execution.d.ts.map +1 -1
  59. package/dist/runtime/turn-execution.d.ts +2 -9
  60. package/dist/runtime/turn-execution.d.ts.map +1 -1
  61. package/dist/session-snapshot-exchange.d.ts +0 -4
  62. package/dist/session-snapshot-exchange.d.ts.map +1 -1
  63. package/dist/turn-continuation.d.ts.map +1 -1
  64. package/dist/turn-execution-error.d.ts +1 -1
  65. package/dist/turn-execution-error.d.ts.map +1 -1
  66. package/dist/turn-execution-result.d.ts +1 -0
  67. package/dist/turn-execution-result.d.ts.map +1 -1
  68. package/dist/turn-outcome-tool-session.d.ts +0 -2
  69. package/dist/turn-outcome-tool-session.d.ts.map +1 -1
  70. package/dist/turn-result-markdown.d.ts +2 -1
  71. package/dist/turn-result-markdown.d.ts.map +1 -1
  72. package/dist/turn-tree-strategy.d.ts +0 -1
  73. package/dist/turn-tree-strategy.d.ts.map +1 -1
  74. package/dist/worker-entry.js +16 -4
  75. package/dist/worker-entry.js.map +1 -1
  76. package/dist/worker-ipc-reporter.d.ts.map +1 -1
  77. package/dist/workspace/manifest.d.ts +4 -7
  78. package/dist/workspace/manifest.d.ts.map +1 -1
  79. package/dist/workspace/node-run-root-git-ops.d.ts +2 -2
  80. package/dist/workspace/node-run-root-git-ops.d.ts.map +1 -1
  81. package/dist/workspace/resource-aggregator.d.ts.map +1 -1
  82. package/dist/workspace/run-root.d.ts +9 -20
  83. package/dist/workspace/run-root.d.ts.map +1 -1
  84. package/package.json +8 -8
  85. package/src/automatic-turn-executor.ts +2 -0
  86. package/src/connection-diagnostics.ts +27 -0
  87. package/src/container-entry-main.ts +24 -0
  88. package/src/container-entry.ts +246 -0
  89. package/src/development-tool-environment.ts +452 -0
  90. package/src/diagnostics.ts +3 -1
  91. package/src/docker-registry-credentials.ts +65 -0
  92. package/src/entry-runtime.ts +5 -4
  93. package/src/index.ts +11 -0
  94. package/src/input-consumer.ts +7 -29
  95. package/src/ipc.ts +37 -2
  96. package/src/logical-prompt-runner.ts +23 -29
  97. package/src/managed-pi-bootstrap.ts +3 -3
  98. package/src/missing-tool-recovery-runner.ts +4 -18
  99. package/src/pi-adapter.ts +19 -50
  100. package/src/pi-event-reporter.ts +16 -38
  101. package/src/pi-resource-bundle.ts +67 -1
  102. package/src/pre-turn-targeted-inputs.ts +9 -11
  103. package/src/prompt-guards.ts +44 -75
  104. package/src/repository-bash-tool.ts +15 -0
  105. package/src/resource-loader-factory.ts +1 -18
  106. package/src/result-image-upload.ts +16 -27
  107. package/src/runtime/adapters.ts +2 -0
  108. package/src/runtime/bootstrap-session.ts +69 -39
  109. package/src/runtime/bootstrap.ts +160 -103
  110. package/src/runtime/failure-policy.ts +36 -42
  111. package/src/runtime/index.ts +49 -14
  112. package/src/runtime/lifecycle-reducer.ts +140 -173
  113. package/src/runtime/llm-turn-execution.ts +13 -30
  114. package/src/runtime/turn-execution.ts +91 -9
  115. package/src/session-snapshot-exchange.ts +23 -64
  116. package/src/turn-continuation.ts +9 -17
  117. package/src/turn-execution-error.ts +3 -11
  118. package/src/turn-execution-result.ts +1 -0
  119. package/src/turn-outcome-tool-session.ts +25 -21
  120. package/src/turn-result-markdown.ts +31 -34
  121. package/src/turn-tree-strategy.ts +6 -19
  122. package/src/worker-entry.ts +8 -0
  123. package/src/worker-ipc-reporter.ts +8 -16
  124. package/src/workspace/manifest.ts +5 -7
  125. package/src/workspace/node-run-root-git-ops.ts +65 -25
  126. package/src/workspace/resource-aggregator.ts +5 -16
  127. package/src/workspace/run-root.ts +38 -89
  128. package/dist/automatic-turn-executor.js +0 -58
  129. package/dist/automatic-turn-executor.js.map +0 -1
  130. package/dist/chunk-ZTJ7UAOC.js.map +0 -1
  131. package/dist/diagnostics.js +0 -51
  132. package/dist/diagnostics.js.map +0 -1
  133. package/dist/entry-runtime.js +0 -160
  134. package/dist/entry-runtime.js.map +0 -1
  135. package/dist/event-translator.js +0 -12
  136. package/dist/event-translator.js.map +0 -1
  137. package/dist/extension-entry-roots.js +0 -41
  138. package/dist/extension-entry-roots.js.map +0 -1
  139. package/dist/identified-pi-entry.js +0 -125
  140. package/dist/identified-pi-entry.js.map +0 -1
  141. package/dist/input-consumer.js +0 -34
  142. package/dist/input-consumer.js.map +0 -1
  143. package/dist/integration-tool-bridge.js +0 -53
  144. package/dist/integration-tool-bridge.js.map +0 -1
  145. package/dist/ipc.js +0 -192
  146. package/dist/ipc.js.map +0 -1
  147. package/dist/logical-prompt-runner.js +0 -225
  148. package/dist/logical-prompt-runner.js.map +0 -1
  149. package/dist/managed-pi-agent-dir.js +0 -66
  150. package/dist/managed-pi-agent-dir.js.map +0 -1
  151. package/dist/managed-pi-bootstrap.js +0 -135
  152. package/dist/managed-pi-bootstrap.js.map +0 -1
  153. package/dist/missing-tool-recovery-runner.js +0 -73
  154. package/dist/missing-tool-recovery-runner.js.map +0 -1
  155. package/dist/pi-adapter.js +0 -1648
  156. package/dist/pi-adapter.js.map +0 -1
  157. package/dist/pi-branch-guard.js +0 -75
  158. package/dist/pi-branch-guard.js.map +0 -1
  159. package/dist/pi-event-reporter.js +0 -136
  160. package/dist/pi-event-reporter.js.map +0 -1
  161. package/dist/pi-resource-bundle.js +0 -58
  162. package/dist/pi-resource-bundle.js.map +0 -1
  163. package/dist/pre-turn-targeted-inputs.js +0 -101
  164. package/dist/pre-turn-targeted-inputs.js.map +0 -1
  165. package/dist/prompt-guards.js +0 -318
  166. package/dist/prompt-guards.js.map +0 -1
  167. package/dist/question-bridge.js +0 -24
  168. package/dist/question-bridge.js.map +0 -1
  169. package/dist/question-tool.js +0 -54
  170. package/dist/question-tool.js.map +0 -1
  171. package/dist/replaying-request-bridge.js +0 -71
  172. package/dist/replaying-request-bridge.js.map +0 -1
  173. package/dist/resource-loader-factory.js +0 -87
  174. package/dist/resource-loader-factory.js.map +0 -1
  175. package/dist/result-image-upload.js +0 -183
  176. package/dist/result-image-upload.js.map +0 -1
  177. package/dist/runtime/adapters.js +0 -15
  178. package/dist/runtime/adapters.js.map +0 -1
  179. package/dist/runtime/bootstrap-session.js +0 -199
  180. package/dist/runtime/bootstrap-session.js.map +0 -1
  181. package/dist/runtime/bootstrap.js +0 -440
  182. package/dist/runtime/bootstrap.js.map +0 -1
  183. package/dist/runtime/failure-policy.js +0 -182
  184. package/dist/runtime/failure-policy.js.map +0 -1
  185. package/dist/runtime/index.js +0 -336
  186. package/dist/runtime/index.js.map +0 -1
  187. package/dist/runtime/lifecycle-reducer.js +0 -1100
  188. package/dist/runtime/lifecycle-reducer.js.map +0 -1
  189. package/dist/runtime/llm-turn-execution.js +0 -494
  190. package/dist/runtime/llm-turn-execution.js.map +0 -1
  191. package/dist/runtime/settings.js +0 -24
  192. package/dist/runtime/settings.js.map +0 -1
  193. package/dist/runtime/snapshot-policy.js +0 -16
  194. package/dist/runtime/snapshot-policy.js.map +0 -1
  195. package/dist/runtime/turn-execution.js +0 -121
  196. package/dist/runtime/turn-execution.js.map +0 -1
  197. package/dist/session-snapshot-exchange.js +0 -102
  198. package/dist/session-snapshot-exchange.js.map +0 -1
  199. package/dist/test-helpers/fake-websocket.js +0 -40
  200. package/dist/test-helpers/fake-websocket.js.map +0 -1
  201. package/dist/test-helpers/ipc-harness.d.ts +0 -11
  202. package/dist/test-helpers/ipc-harness.d.ts.map +0 -1
  203. package/dist/test-helpers/ipc-harness.js +0 -17
  204. package/dist/test-helpers/ipc-harness.js.map +0 -1
  205. package/dist/turn-continuation.js +0 -80
  206. package/dist/turn-continuation.js.map +0 -1
  207. package/dist/turn-execution-error.js +0 -64
  208. package/dist/turn-execution-error.js.map +0 -1
  209. package/dist/turn-execution-result.js +0 -21
  210. package/dist/turn-execution-result.js.map +0 -1
  211. package/dist/turn-outcome-tool-session.js +0 -210
  212. package/dist/turn-outcome-tool-session.js.map +0 -1
  213. package/dist/turn-record-id.js +0 -10
  214. package/dist/turn-record-id.js.map +0 -1
  215. package/dist/turn-result-markdown.js +0 -263
  216. package/dist/turn-result-markdown.js.map +0 -1
  217. package/dist/turn-tree-strategy.js +0 -80
  218. package/dist/turn-tree-strategy.js.map +0 -1
  219. package/dist/worker-http.js +0 -9
  220. package/dist/worker-http.js.map +0 -1
  221. package/dist/worker-ipc-reporter.js +0 -58
  222. package/dist/worker-ipc-reporter.js.map +0 -1
  223. package/dist/worker-payloads.js +0 -66
  224. package/dist/worker-payloads.js.map +0 -1
  225. package/dist/worker-start-payload.js +0 -5
  226. package/dist/worker-start-payload.js.map +0 -1
  227. package/dist/workspace/manifest.js +0 -79
  228. package/dist/workspace/manifest.js.map +0 -1
  229. package/dist/workspace/node-run-root-git-ops.js +0 -96
  230. package/dist/workspace/node-run-root-git-ops.js.map +0 -1
  231. package/dist/workspace/resource-aggregator.js +0 -39
  232. package/dist/workspace/resource-aggregator.js.map +0 -1
  233. package/dist/workspace/run-root.js +0 -209
  234. package/dist/workspace/run-root.js.map +0 -1
  235. package/src/test-helpers/ipc-harness.ts +0 -19
@@ -1,1100 +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: { 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