@leitwerk-dev/worker 0.1.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 (269) hide show
  1. package/dist/LICENSE +13 -0
  2. package/dist/automatic-turn-executor.d.ts +28 -0
  3. package/dist/automatic-turn-executor.d.ts.map +1 -0
  4. package/dist/automatic-turn-executor.js +58 -0
  5. package/dist/automatic-turn-executor.js.map +1 -0
  6. package/dist/chunk-N5HLJDWA.js +8124 -0
  7. package/dist/chunk-N5HLJDWA.js.map +1 -0
  8. package/dist/diagnostics.d.ts +23 -0
  9. package/dist/diagnostics.d.ts.map +1 -0
  10. package/dist/diagnostics.js +51 -0
  11. package/dist/diagnostics.js.map +1 -0
  12. package/dist/entry-runtime.d.ts +24 -0
  13. package/dist/entry-runtime.d.ts.map +1 -0
  14. package/dist/entry-runtime.js +160 -0
  15. package/dist/entry-runtime.js.map +1 -0
  16. package/dist/event-translator.d.ts +8 -0
  17. package/dist/event-translator.d.ts.map +1 -0
  18. package/dist/event-translator.js +12 -0
  19. package/dist/event-translator.js.map +1 -0
  20. package/dist/extension-entry-roots.d.ts +7 -0
  21. package/dist/extension-entry-roots.d.ts.map +1 -0
  22. package/dist/extension-entry-roots.js +41 -0
  23. package/dist/extension-entry-roots.js.map +1 -0
  24. package/dist/identified-pi-entry.d.ts +56 -0
  25. package/dist/identified-pi-entry.d.ts.map +1 -0
  26. package/dist/identified-pi-entry.js +125 -0
  27. package/dist/identified-pi-entry.js.map +1 -0
  28. package/dist/index.d.ts +7 -0
  29. package/dist/index.d.ts.map +1 -0
  30. package/dist/index.js +6 -0
  31. package/dist/index.js.map +1 -0
  32. package/dist/input-consumer.d.ts +24 -0
  33. package/dist/input-consumer.d.ts.map +1 -0
  34. package/dist/input-consumer.js +34 -0
  35. package/dist/input-consumer.js.map +1 -0
  36. package/dist/ipc.d.ts +22 -0
  37. package/dist/ipc.d.ts.map +1 -0
  38. package/dist/ipc.js +192 -0
  39. package/dist/ipc.js.map +1 -0
  40. package/dist/logical-prompt-runner.d.ts +49 -0
  41. package/dist/logical-prompt-runner.d.ts.map +1 -0
  42. package/dist/logical-prompt-runner.js +225 -0
  43. package/dist/logical-prompt-runner.js.map +1 -0
  44. package/dist/managed-pi-agent-dir.d.ts +13 -0
  45. package/dist/managed-pi-agent-dir.d.ts.map +1 -0
  46. package/dist/managed-pi-agent-dir.js +66 -0
  47. package/dist/managed-pi-agent-dir.js.map +1 -0
  48. package/dist/managed-pi-bootstrap.d.ts +24 -0
  49. package/dist/managed-pi-bootstrap.d.ts.map +1 -0
  50. package/dist/managed-pi-bootstrap.js +135 -0
  51. package/dist/managed-pi-bootstrap.js.map +1 -0
  52. package/dist/missing-tool-recovery-runner.d.ts +23 -0
  53. package/dist/missing-tool-recovery-runner.d.ts.map +1 -0
  54. package/dist/missing-tool-recovery-runner.js +73 -0
  55. package/dist/missing-tool-recovery-runner.js.map +1 -0
  56. package/dist/pi-adapter.d.ts +134 -0
  57. package/dist/pi-adapter.d.ts.map +1 -0
  58. package/dist/pi-adapter.js +1648 -0
  59. package/dist/pi-adapter.js.map +1 -0
  60. package/dist/pi-branch-guard.d.ts +39 -0
  61. package/dist/pi-branch-guard.d.ts.map +1 -0
  62. package/dist/pi-branch-guard.js +75 -0
  63. package/dist/pi-branch-guard.js.map +1 -0
  64. package/dist/pi-event-reporter.d.ts +15 -0
  65. package/dist/pi-event-reporter.d.ts.map +1 -0
  66. package/dist/pi-event-reporter.js +136 -0
  67. package/dist/pi-event-reporter.js.map +1 -0
  68. package/dist/pi-resource-bundle.d.ts +12 -0
  69. package/dist/pi-resource-bundle.d.ts.map +1 -0
  70. package/dist/pi-resource-bundle.js +58 -0
  71. package/dist/pi-resource-bundle.js.map +1 -0
  72. package/dist/pre-turn-targeted-inputs.d.ts +44 -0
  73. package/dist/pre-turn-targeted-inputs.d.ts.map +1 -0
  74. package/dist/pre-turn-targeted-inputs.js +101 -0
  75. package/dist/pre-turn-targeted-inputs.js.map +1 -0
  76. package/dist/prompt-guards.d.ts +52 -0
  77. package/dist/prompt-guards.d.ts.map +1 -0
  78. package/dist/prompt-guards.js +318 -0
  79. package/dist/prompt-guards.js.map +1 -0
  80. package/dist/question-bridge.d.ts +16 -0
  81. package/dist/question-bridge.d.ts.map +1 -0
  82. package/dist/question-bridge.js +55 -0
  83. package/dist/question-bridge.js.map +1 -0
  84. package/dist/question-tool.d.ts +14 -0
  85. package/dist/question-tool.d.ts.map +1 -0
  86. package/dist/question-tool.js +54 -0
  87. package/dist/question-tool.js.map +1 -0
  88. package/dist/resource-loader-factory.d.ts +11 -0
  89. package/dist/resource-loader-factory.d.ts.map +1 -0
  90. package/dist/resource-loader-factory.js +87 -0
  91. package/dist/resource-loader-factory.js.map +1 -0
  92. package/dist/result-image-upload.d.ts +14 -0
  93. package/dist/result-image-upload.d.ts.map +1 -0
  94. package/dist/result-image-upload.js +183 -0
  95. package/dist/result-image-upload.js.map +1 -0
  96. package/dist/runtime/adapters.d.ts +48 -0
  97. package/dist/runtime/adapters.d.ts.map +1 -0
  98. package/dist/runtime/adapters.js +15 -0
  99. package/dist/runtime/adapters.js.map +1 -0
  100. package/dist/runtime/bootstrap-session.d.ts +95 -0
  101. package/dist/runtime/bootstrap-session.d.ts.map +1 -0
  102. package/dist/runtime/bootstrap-session.js +198 -0
  103. package/dist/runtime/bootstrap-session.js.map +1 -0
  104. package/dist/runtime/bootstrap.d.ts +81 -0
  105. package/dist/runtime/bootstrap.d.ts.map +1 -0
  106. package/dist/runtime/bootstrap.js +440 -0
  107. package/dist/runtime/bootstrap.js.map +1 -0
  108. package/dist/runtime/failure-policy.d.ts +79 -0
  109. package/dist/runtime/failure-policy.d.ts.map +1 -0
  110. package/dist/runtime/failure-policy.js +182 -0
  111. package/dist/runtime/failure-policy.js.map +1 -0
  112. package/dist/runtime/index.d.ts +9 -0
  113. package/dist/runtime/index.d.ts.map +1 -0
  114. package/dist/runtime/index.js +326 -0
  115. package/dist/runtime/index.js.map +1 -0
  116. package/dist/runtime/lifecycle-reducer.d.ts +328 -0
  117. package/dist/runtime/lifecycle-reducer.d.ts.map +1 -0
  118. package/dist/runtime/lifecycle-reducer.js +1100 -0
  119. package/dist/runtime/lifecycle-reducer.js.map +1 -0
  120. package/dist/runtime/llm-turn-execution.d.ts +42 -0
  121. package/dist/runtime/llm-turn-execution.d.ts.map +1 -0
  122. package/dist/runtime/llm-turn-execution.js +472 -0
  123. package/dist/runtime/llm-turn-execution.js.map +1 -0
  124. package/dist/runtime/settings.d.ts +11 -0
  125. package/dist/runtime/settings.d.ts.map +1 -0
  126. package/dist/runtime/settings.js +23 -0
  127. package/dist/runtime/settings.js.map +1 -0
  128. package/dist/runtime/snapshot-policy.d.ts +11 -0
  129. package/dist/runtime/snapshot-policy.d.ts.map +1 -0
  130. package/dist/runtime/snapshot-policy.js +16 -0
  131. package/dist/runtime/snapshot-policy.js.map +1 -0
  132. package/dist/runtime/turn-execution.d.ts +49 -0
  133. package/dist/runtime/turn-execution.d.ts.map +1 -0
  134. package/dist/runtime/turn-execution.js +120 -0
  135. package/dist/runtime/turn-execution.js.map +1 -0
  136. package/dist/session-snapshot-exchange.d.ts +39 -0
  137. package/dist/session-snapshot-exchange.d.ts.map +1 -0
  138. package/dist/session-snapshot-exchange.js +102 -0
  139. package/dist/session-snapshot-exchange.js.map +1 -0
  140. package/dist/test-helpers/fake-websocket.d.ts +16 -0
  141. package/dist/test-helpers/fake-websocket.d.ts.map +1 -0
  142. package/dist/test-helpers/fake-websocket.js +40 -0
  143. package/dist/test-helpers/fake-websocket.js.map +1 -0
  144. package/dist/test-helpers/ipc-harness.d.ts +11 -0
  145. package/dist/test-helpers/ipc-harness.d.ts.map +1 -0
  146. package/dist/test-helpers/ipc-harness.js +17 -0
  147. package/dist/test-helpers/ipc-harness.js.map +1 -0
  148. package/dist/test-helpers/worker-message-builders.d.ts +21 -0
  149. package/dist/test-helpers/worker-message-builders.d.ts.map +1 -0
  150. package/dist/test-helpers/worker-message-builders.js +62 -0
  151. package/dist/test-helpers/worker-message-builders.js.map +1 -0
  152. package/dist/turn-continuation.d.ts +28 -0
  153. package/dist/turn-continuation.d.ts.map +1 -0
  154. package/dist/turn-continuation.js +80 -0
  155. package/dist/turn-continuation.js.map +1 -0
  156. package/dist/turn-execution-error.d.ts +39 -0
  157. package/dist/turn-execution-error.d.ts.map +1 -0
  158. package/dist/turn-execution-error.js +64 -0
  159. package/dist/turn-execution-error.js.map +1 -0
  160. package/dist/turn-execution-result.d.ts +35 -0
  161. package/dist/turn-execution-result.d.ts.map +1 -0
  162. package/dist/turn-execution-result.js +21 -0
  163. package/dist/turn-execution-result.js.map +1 -0
  164. package/dist/turn-outcome-tool-session.d.ts +50 -0
  165. package/dist/turn-outcome-tool-session.d.ts.map +1 -0
  166. package/dist/turn-outcome-tool-session.js +209 -0
  167. package/dist/turn-outcome-tool-session.js.map +1 -0
  168. package/dist/turn-record-id.d.ts +3 -0
  169. package/dist/turn-record-id.d.ts.map +1 -0
  170. package/dist/turn-record-id.js +10 -0
  171. package/dist/turn-record-id.js.map +1 -0
  172. package/dist/turn-result-markdown.d.ts +74 -0
  173. package/dist/turn-result-markdown.d.ts.map +1 -0
  174. package/dist/turn-result-markdown.js +263 -0
  175. package/dist/turn-result-markdown.js.map +1 -0
  176. package/dist/turn-tree-strategy.d.ts +29 -0
  177. package/dist/turn-tree-strategy.d.ts.map +1 -0
  178. package/dist/turn-tree-strategy.js +80 -0
  179. package/dist/turn-tree-strategy.js.map +1 -0
  180. package/dist/worker-entry.d.ts +2 -0
  181. package/dist/worker-entry.d.ts.map +1 -0
  182. package/dist/worker-entry.js +7 -0
  183. package/dist/worker-entry.js.map +1 -0
  184. package/dist/worker-http.d.ts +2 -0
  185. package/dist/worker-http.d.ts.map +1 -0
  186. package/dist/worker-http.js +9 -0
  187. package/dist/worker-http.js.map +1 -0
  188. package/dist/worker-ipc-reporter.d.ts +29 -0
  189. package/dist/worker-ipc-reporter.d.ts.map +1 -0
  190. package/dist/worker-ipc-reporter.js +58 -0
  191. package/dist/worker-ipc-reporter.js.map +1 -0
  192. package/dist/worker-payloads.d.ts +10 -0
  193. package/dist/worker-payloads.d.ts.map +1 -0
  194. package/dist/worker-payloads.js +66 -0
  195. package/dist/worker-payloads.js.map +1 -0
  196. package/dist/worker-start-payload.d.ts +7 -0
  197. package/dist/worker-start-payload.d.ts.map +1 -0
  198. package/dist/worker-start-payload.js +5 -0
  199. package/dist/worker-start-payload.js.map +1 -0
  200. package/dist/workspace/manifest.d.ts +35 -0
  201. package/dist/workspace/manifest.d.ts.map +1 -0
  202. package/dist/workspace/manifest.js +79 -0
  203. package/dist/workspace/manifest.js.map +1 -0
  204. package/dist/workspace/node-run-root-git-ops.d.ts +17 -0
  205. package/dist/workspace/node-run-root-git-ops.d.ts.map +1 -0
  206. package/dist/workspace/node-run-root-git-ops.js +96 -0
  207. package/dist/workspace/node-run-root-git-ops.js.map +1 -0
  208. package/dist/workspace/resource-aggregator.d.ts +15 -0
  209. package/dist/workspace/resource-aggregator.d.ts.map +1 -0
  210. package/dist/workspace/resource-aggregator.js +39 -0
  211. package/dist/workspace/resource-aggregator.js.map +1 -0
  212. package/dist/workspace/run-root.d.ts +52 -0
  213. package/dist/workspace/run-root.d.ts.map +1 -0
  214. package/dist/workspace/run-root.js +209 -0
  215. package/dist/workspace/run-root.js.map +1 -0
  216. package/package.json +55 -0
  217. package/src/automatic-turn-executor.ts +106 -0
  218. package/src/diagnostics.ts +82 -0
  219. package/src/entry-runtime.ts +235 -0
  220. package/src/event-translator.ts +22 -0
  221. package/src/extension-entry-roots.ts +43 -0
  222. package/src/identified-pi-entry.ts +188 -0
  223. package/src/index.ts +54 -0
  224. package/src/input-consumer.ts +71 -0
  225. package/src/ipc.ts +250 -0
  226. package/src/logical-prompt-runner.ts +320 -0
  227. package/src/managed-pi-agent-dir.ts +86 -0
  228. package/src/managed-pi-bootstrap.ts +208 -0
  229. package/src/missing-tool-recovery-runner.ts +112 -0
  230. package/src/pi-adapter.ts +2197 -0
  231. package/src/pi-branch-guard.ts +104 -0
  232. package/src/pi-event-reporter.ts +164 -0
  233. package/src/pi-resource-bundle.ts +90 -0
  234. package/src/pre-turn-targeted-inputs.ts +167 -0
  235. package/src/prompt-guards.ts +385 -0
  236. package/src/question-bridge.ts +69 -0
  237. package/src/question-tool.ts +65 -0
  238. package/src/resource-loader-factory.ts +115 -0
  239. package/src/result-image-upload.ts +256 -0
  240. package/src/runtime/adapters.ts +67 -0
  241. package/src/runtime/bootstrap-session.ts +294 -0
  242. package/src/runtime/bootstrap.ts +621 -0
  243. package/src/runtime/failure-policy.ts +274 -0
  244. package/src/runtime/index.ts +362 -0
  245. package/src/runtime/lifecycle-reducer.ts +1537 -0
  246. package/src/runtime/llm-turn-execution.ts +696 -0
  247. package/src/runtime/settings.ts +41 -0
  248. package/src/runtime/snapshot-policy.ts +28 -0
  249. package/src/runtime/turn-execution.ts +203 -0
  250. package/src/session-snapshot-exchange.ts +155 -0
  251. package/src/test-helpers/fake-websocket.ts +46 -0
  252. package/src/test-helpers/ipc-harness.ts +19 -0
  253. package/src/test-helpers/worker-message-builders.ts +92 -0
  254. package/src/turn-continuation.ts +147 -0
  255. package/src/turn-execution-error.ts +102 -0
  256. package/src/turn-execution-result.ts +48 -0
  257. package/src/turn-outcome-tool-session.ts +311 -0
  258. package/src/turn-record-id.ts +17 -0
  259. package/src/turn-result-markdown.ts +355 -0
  260. package/src/turn-tree-strategy.ts +141 -0
  261. package/src/worker-entry.ts +8 -0
  262. package/src/worker-http.ts +6 -0
  263. package/src/worker-ipc-reporter.ts +100 -0
  264. package/src/worker-payloads.ts +94 -0
  265. package/src/worker-start-payload.ts +10 -0
  266. package/src/workspace/manifest.ts +126 -0
  267. package/src/workspace/node-run-root-git-ops.ts +137 -0
  268. package/src/workspace/resource-aggregator.ts +43 -0
  269. package/src/workspace/run-root.ts +361 -0
@@ -0,0 +1,1537 @@
1
+ import {
2
+ type ServerToWorkerMessage,
3
+ WORKER_API_VERSION,
4
+ type WorkerStartPayload,
5
+ type WorkerToServerMessage,
6
+ } from "@leitwerk-dev/worker-protocol";
7
+ import type { WorkerDiagnosticPayload } from "../diagnostics.js";
8
+ import type { DeliveredInput, InputItem, TargetedInputItem } from "../input-consumer.js";
9
+ import type { WorkerProtocolFact } from "../worker-ipc-reporter.js";
10
+ import { inputDeliveryToItem } from "../worker-payloads.js";
11
+ import type {
12
+ CredentialRefreshDescriptor,
13
+ PreparedWorkerSession,
14
+ WorkerBootstrapCompletion,
15
+ } from "./bootstrap-session.js";
16
+ import {
17
+ normalizeWorkerFailure,
18
+ type WorkerFailure,
19
+ type WorkerTurnFailureCorrelation,
20
+ } from "./failure-policy.js";
21
+ import { resolveWorkerSnapshotPolicy, type WorkerSnapshotPoint } from "./snapshot-policy.js";
22
+ import type { AppliedTargetedInput, SelectedTurnExecutionResult } from "./turn-execution.js";
23
+
24
+ export type WorkerRuntimeStateName =
25
+ | "init"
26
+ | "waiting_for_start"
27
+ | "bootstrapping"
28
+ | "idle"
29
+ | "busy"
30
+ | "draining"
31
+ | "cleanup"
32
+ | "exited";
33
+ /** Compatibility type used by pure failure normalization. */
34
+ export type WorkerRuntimeState = WorkerRuntimeStateName;
35
+ export type ReportedWorkerState = "idle" | "busy" | "draining";
36
+ export type WorkerTimerName = "heartbeat" | "acceptance_retry" | "credential_poll";
37
+
38
+ type ActiveTurnStatus = "pending" | "executing" | "completed";
39
+ type DrainingOperation =
40
+ | { kind: "bootstrap"; startRecordId: string; proposedTurnRecordId: string }
41
+ | { kind: "activation"; startRecordId: string; turnRecordId: string }
42
+ | { kind: "turn"; turnRecordId: string }
43
+ | null;
44
+ export type WorkerRuntimePhase =
45
+ | { kind: "init" }
46
+ | { kind: "waiting_for_start" }
47
+ | { kind: "bootstrapping"; startRecordId: string; proposedTurnRecordId: string }
48
+ | {
49
+ kind: "readying";
50
+ startRecordId: string;
51
+ proposedTurnRecordId: string;
52
+ acceptedId: string | null;
53
+ }
54
+ | { kind: "waiting_for_acceptance"; startRecordId: string; proposedTurnRecordId: string }
55
+ | { kind: "activating"; startRecordId: string; turnRecordId: string }
56
+ | { kind: "active"; startRecordId: string; turnRecordId: string; turnStatus: ActiveTurnStatus }
57
+ | {
58
+ kind: "draining";
59
+ reason: string;
60
+ exitAfterCleanup: boolean;
61
+ operation: DrainingOperation;
62
+ }
63
+ | {
64
+ kind: "cleaning";
65
+ reason: string;
66
+ exitAfterCleanup: boolean;
67
+ stage: "publication" | "resources";
68
+ }
69
+ | { kind: "exited" };
70
+
71
+ interface CredentialState {
72
+ descriptor: CredentialRefreshDescriptor;
73
+ baselineFingerprint: string | null;
74
+ pendingFingerprint: string | null;
75
+ revision: number;
76
+ sampling: boolean;
77
+ updatePending: boolean;
78
+ enabled: boolean;
79
+ }
80
+
81
+ interface PendingTerminal {
82
+ fact: WorkerProtocolFact<"worker.turn_outcome"> | WorkerProtocolFact<"worker.turn_failed">;
83
+ park: Extract<WorkerToServerMessage, { type: "worker.lifecycle_parked" }>["payload"] | null;
84
+ correlation: WorkerTurnFailureCorrelation;
85
+ }
86
+
87
+ interface PendingFatal {
88
+ payload: Extract<WorkerToServerMessage, { type: "worker.failed" }>["payload"];
89
+ exitCode?: number;
90
+ }
91
+
92
+ type PublicationState =
93
+ | { kind: "none" }
94
+ | {
95
+ kind: "ready_snapshot";
96
+ snapshot: {
97
+ point: "after_worker_ready";
98
+ turnRecordId: null;
99
+ required: false;
100
+ };
101
+ }
102
+ | {
103
+ kind: "terminal_snapshot";
104
+ snapshot: {
105
+ point: "before_turn_outcome" | "before_turn_failed";
106
+ turnRecordId: string;
107
+ required: true;
108
+ };
109
+ terminal: PendingTerminal;
110
+ }
111
+ | {
112
+ kind: "cleanup_snapshot";
113
+ snapshot: {
114
+ point: "before_cleanup_completed";
115
+ turnRecordId: null;
116
+ required: true;
117
+ };
118
+ }
119
+ | {
120
+ kind: "fatal_snapshot";
121
+ snapshot: {
122
+ point: "before_worker_failed";
123
+ turnRecordId: null;
124
+ required: false;
125
+ };
126
+ fatal: PendingFatal;
127
+ afterSnapshot: "exit" | "cleanup";
128
+ }
129
+ | { kind: "fatal_pending_cleanup"; fatal: PendingFatal };
130
+
131
+ interface ActiveWork {
132
+ deliveryHeadSequence: number | null;
133
+ publication: PublicationState;
134
+ }
135
+
136
+ export interface WorkerRuntimeStateMachine {
137
+ phase: WorkerRuntimePhase;
138
+ session: PreparedWorkerSession | null;
139
+ inputQueue: readonly InputItem[];
140
+ lastSequenceConsumed: number;
141
+ sessionTainted: boolean;
142
+ piTurnActive: boolean;
143
+ work: ActiveWork;
144
+ credential: CredentialState | null;
145
+ timers: Record<WorkerTimerName, string | null>;
146
+ }
147
+
148
+ export type WorkerExtensionFact = {
149
+ kind: "extension";
150
+ event: "worker.handle_ready" | "worker.session_tainted";
151
+ payload: unknown;
152
+ };
153
+ export type WorkerDiagnosticFact = {
154
+ kind: "diagnostic";
155
+ payload: WorkerDiagnosticPayload;
156
+ stderr?: string;
157
+ };
158
+ export type WorkerStderrFact = { kind: "stderr"; message: string };
159
+ export interface WorkerSnapshotSource {
160
+ kind: "automatic" | "llm";
161
+ treeFile: string;
162
+ }
163
+
164
+ export type WorkerRuntimeCommand =
165
+ | { kind: "bootstrap"; startRecordId: string; payload: WorkerStartPayload }
166
+ | {
167
+ kind: "activate";
168
+ startRecordId: string;
169
+ turnRecordId: string;
170
+ session: PreparedWorkerSession;
171
+ }
172
+ | {
173
+ kind: "deliver_inputs";
174
+ headSequence: number;
175
+ inputs: readonly InputItem[];
176
+ piTurnActive: boolean;
177
+ }
178
+ | {
179
+ kind: "execute_turn";
180
+ turnRecordId: string;
181
+ targetedInputs: readonly TargetedInputItem[];
182
+ session: PreparedWorkerSession;
183
+ }
184
+ | {
185
+ kind: "upload_snapshot";
186
+ point: WorkerSnapshotPoint;
187
+ turnRecordId: string | null;
188
+ required: boolean;
189
+ source: WorkerSnapshotSource;
190
+ }
191
+ | { kind: "sample_credentials"; descriptor: CredentialRefreshDescriptor; baseline: boolean }
192
+ | { kind: "cleanup" }
193
+ | { kind: "arm_timer"; name: WorkerTimerName; delayMs: number; correlation: string }
194
+ | { kind: "cancel_timer"; name: WorkerTimerName }
195
+ | { kind: "close_transport" }
196
+ | { kind: "exit"; code: number };
197
+
198
+ export type WorkerRuntimeOutput =
199
+ | WorkerProtocolFact
200
+ | WorkerExtensionFact
201
+ | WorkerDiagnosticFact
202
+ | WorkerStderrFact
203
+ | WorkerRuntimeCommand;
204
+
205
+ export type WorkerRuntimeEvent =
206
+ | { kind: "runtime_started" }
207
+ | { kind: "transport_connected" }
208
+ | { kind: "transport_failed"; error: Error }
209
+ | { kind: "server_message"; message: ServerToWorkerMessage }
210
+ | { kind: "stop_requested"; reason: string; exitAfterCleanup: boolean }
211
+ | { kind: "operator_abort_observed" }
212
+ | { kind: "pi_turn_started" }
213
+ | { kind: "pi_turn_ended" }
214
+ | { kind: "session_tainted"; reason: string }
215
+ | { kind: "timer_fired"; name: WorkerTimerName; correlation: string }
216
+ | { kind: "bootstrap_succeeded"; startRecordId: string; completion: WorkerBootstrapCompletion }
217
+ | {
218
+ kind: "bootstrap_failed";
219
+ startRecordId: string;
220
+ error: unknown;
221
+ payload: WorkerStartPayload;
222
+ }
223
+ | {
224
+ kind: "activation_succeeded";
225
+ startRecordId: string;
226
+ turnRecordId: string;
227
+ diagnostics: readonly string[];
228
+ }
229
+ | { kind: "activation_failed"; startRecordId: string; turnRecordId: string; error: unknown }
230
+ | {
231
+ kind: "inputs_delivered";
232
+ headSequence: number;
233
+ delivered: readonly DeliveredInput[];
234
+ meta?: { currentPrimaryPathLeafId?: string | null; rootEntryId?: string | null };
235
+ }
236
+ | { kind: "input_delivery_failed"; headSequence: number; error: unknown }
237
+ | { kind: "turn_completed"; turnRecordId: string; result: SelectedTurnExecutionResult }
238
+ | { kind: "turn_defect"; turnRecordId: string; error: unknown }
239
+ | { kind: "snapshot_succeeded"; point: WorkerSnapshotPoint; turnRecordId: string | null }
240
+ | {
241
+ kind: "snapshot_failed";
242
+ point: WorkerSnapshotPoint;
243
+ turnRecordId: string | null;
244
+ error: unknown;
245
+ }
246
+ | {
247
+ kind: "credential_sampled";
248
+ providerId: string;
249
+ values: Record<string, string>;
250
+ fingerprint: string;
251
+ }
252
+ | { kind: "credential_sample_failed"; providerId: string; error: unknown }
253
+ | { kind: "cleanup_succeeded" }
254
+ | { kind: "cleanup_failed"; error: unknown }
255
+ | { kind: "invariant_failed"; error: unknown };
256
+
257
+ export interface WorkerRuntimeReduction {
258
+ state: WorkerRuntimeStateMachine;
259
+ outputs: readonly WorkerRuntimeOutput[];
260
+ }
261
+
262
+ const HELLO = {
263
+ kind: "protocol",
264
+ type: "worker.hello",
265
+ payload: {
266
+ version: "0.1.0",
267
+ apiVersion: WORKER_API_VERSION,
268
+ capabilities: ["worker.ipc/v1", "input.batch", "worker.stop", "worker.abort_turn"],
269
+ },
270
+ } as unknown as WorkerProtocolFact<"worker.hello">;
271
+
272
+ export function createInitialWorkerRuntimeState(): WorkerRuntimeStateMachine {
273
+ return {
274
+ phase: { kind: "init" },
275
+ session: null,
276
+ inputQueue: [],
277
+ lastSequenceConsumed: 0,
278
+ sessionTainted: false,
279
+ piTurnActive: false,
280
+ work: {
281
+ deliveryHeadSequence: null,
282
+ publication: { kind: "none" },
283
+ },
284
+ credential: null,
285
+ timers: { heartbeat: null, acceptance_retry: null, credential_poll: null },
286
+ };
287
+ }
288
+
289
+ export function deriveReportedWorkerState(state: WorkerRuntimeStateMachine): ReportedWorkerState {
290
+ if (state.phase.kind === "draining" || state.phase.kind === "cleaning") return "draining";
291
+ if (
292
+ (state.phase.kind === "active" &&
293
+ (state.phase.turnStatus === "executing" ||
294
+ state.work.publication.kind === "terminal_snapshot")) ||
295
+ state.work.deliveryHeadSequence !== null
296
+ )
297
+ return "busy";
298
+ return "idle";
299
+ }
300
+
301
+ export type WorkerInputEffect =
302
+ | { kind: "none" }
303
+ | { kind: "blocked"; reason: "session_tainted" }
304
+ | { kind: "deliver"; inputs: readonly InputItem[] }
305
+ | { kind: "consume_ignored"; inputs: readonly InputItem[] }
306
+ | { kind: "start_turn"; inputs: readonly TargetedInputItem[] };
307
+
308
+ /** Pure FIFO policy. Queue storage remains reducer-owned. */
309
+ export function decideWorkerInputEffect(input: {
310
+ items: readonly InputItem[];
311
+ sessionTainted: boolean;
312
+ piAvailable: boolean;
313
+ mayStartTurn: boolean;
314
+ }): WorkerInputEffect {
315
+ const head = input.items[0];
316
+ if (!head)
317
+ return input.mayStartTurn && !input.sessionTainted
318
+ ? { kind: "start_turn", inputs: [] }
319
+ : { kind: "none" };
320
+ if (input.sessionTainted) return { kind: "blocked", reason: "session_tainted" };
321
+ if (head.target) {
322
+ if (!input.mayStartTurn) return { kind: "none" };
323
+ const targeted: TargetedInputItem[] = [];
324
+ for (const item of input.items) {
325
+ if (!item.target) break;
326
+ targeted.push(item as TargetedInputItem);
327
+ }
328
+ return { kind: "start_turn", inputs: targeted };
329
+ }
330
+ const ordinary: InputItem[] = [];
331
+ for (const item of input.items) {
332
+ if (item.target) break;
333
+ ordinary.push(item);
334
+ }
335
+ return input.piAvailable
336
+ ? { kind: "deliver", inputs: ordinary }
337
+ : { kind: "consume_ignored", inputs: ordinary };
338
+ }
339
+
340
+ function enqueueInputs(
341
+ current: readonly InputItem[],
342
+ incoming: readonly InputItem[],
343
+ ): readonly InputItem[] {
344
+ const byId = new Map(current.map((item) => [item.inputId, item]));
345
+ for (const item of incoming) byId.set(item.inputId, item);
346
+ return [...byId.values()].sort((left, right) => left.sequence - right.sequence);
347
+ }
348
+
349
+ function protocol<T extends WorkerToServerMessage["type"]>(
350
+ type: T,
351
+ payload: Extract<WorkerToServerMessage, { type: T }>["payload"],
352
+ ): WorkerProtocolFact<T> {
353
+ return { kind: "protocol", type, payload } as unknown as WorkerProtocolFact<T>;
354
+ }
355
+
356
+ function currentStateName(state: WorkerRuntimeStateMachine): WorkerRuntimeStateName {
357
+ switch (state.phase.kind) {
358
+ case "readying":
359
+ case "waiting_for_acceptance":
360
+ return "idle";
361
+ case "activating":
362
+ return "busy";
363
+ case "active":
364
+ return state.phase.turnStatus === "executing" ||
365
+ state.work.publication.kind === "terminal_snapshot"
366
+ ? "busy"
367
+ : "idle";
368
+ case "cleaning":
369
+ return "cleanup";
370
+ default:
371
+ return state.phase.kind;
372
+ }
373
+ }
374
+
375
+ function failureContext(state: WorkerRuntimeStateMachine) {
376
+ return state.session
377
+ ? {
378
+ selectedTurnId: state.session.selectedTurnId,
379
+ lifecycleStatus: state.session.processSnapshot.lifecycleStatus,
380
+ snapshotSource: sessionSnapshotSource(state.session),
381
+ }
382
+ : null;
383
+ }
384
+
385
+ function sessionSnapshotSource(session: PreparedWorkerSession): WorkerSnapshotSource {
386
+ return {
387
+ kind: session.kind,
388
+ treeFile: session.treeFile,
389
+ };
390
+ }
391
+
392
+ type SnapshotCompletionEvent = {
393
+ point: WorkerSnapshotPoint;
394
+ turnRecordId: string | null;
395
+ };
396
+
397
+ function snapshotMatches(
398
+ snapshot: { point: WorkerSnapshotPoint; turnRecordId: string | null },
399
+ event: SnapshotCompletionEvent,
400
+ ): boolean {
401
+ return snapshot.point === event.point && snapshot.turnRecordId === event.turnRecordId;
402
+ }
403
+
404
+ function hasActivePublication(state: WorkerRuntimeStateMachine): boolean {
405
+ return state.work.publication.kind !== "none";
406
+ }
407
+
408
+ function requireNoPublication(state: WorkerRuntimeStateMachine): void {
409
+ if (hasActivePublication(state)) throw new Error("Snapshot publication is already active");
410
+ }
411
+
412
+ function beginReadySnapshot(
413
+ state: WorkerRuntimeStateMachine,
414
+ source: WorkerSnapshotSource,
415
+ outputs: WorkerRuntimeOutput[],
416
+ ): WorkerRuntimeStateMachine {
417
+ requireNoPublication(state);
418
+ const snapshot = {
419
+ point: "after_worker_ready" as const,
420
+ turnRecordId: null,
421
+ required: false as const,
422
+ };
423
+ outputs.push({ kind: "upload_snapshot", ...snapshot, source });
424
+ return {
425
+ ...state,
426
+ work: { ...state.work, publication: { kind: "ready_snapshot", snapshot } },
427
+ };
428
+ }
429
+
430
+ function beginTerminalSnapshot(
431
+ state: WorkerRuntimeStateMachine,
432
+ point: "before_turn_outcome" | "before_turn_failed",
433
+ turnRecordId: string,
434
+ terminal: PendingTerminal,
435
+ source: WorkerSnapshotSource,
436
+ outputs: WorkerRuntimeOutput[],
437
+ ): WorkerRuntimeStateMachine {
438
+ requireNoPublication(state);
439
+ const snapshot = { point, turnRecordId, required: true as const };
440
+ outputs.push({ kind: "upload_snapshot", ...snapshot, source });
441
+ return {
442
+ ...state,
443
+ work: {
444
+ ...state.work,
445
+ publication: { kind: "terminal_snapshot", snapshot, terminal },
446
+ },
447
+ };
448
+ }
449
+
450
+ function beginCleanupSnapshot(
451
+ state: WorkerRuntimeStateMachine,
452
+ source: WorkerSnapshotSource,
453
+ outputs: WorkerRuntimeOutput[],
454
+ ): WorkerRuntimeStateMachine {
455
+ requireNoPublication(state);
456
+ const snapshot = {
457
+ point: "before_cleanup_completed" as const,
458
+ turnRecordId: null,
459
+ required: true as const,
460
+ };
461
+ outputs.push({ kind: "upload_snapshot", ...snapshot, source });
462
+ return {
463
+ ...state,
464
+ work: { ...state.work, publication: { kind: "cleanup_snapshot", snapshot } },
465
+ };
466
+ }
467
+
468
+ function beginFatalSnapshot(
469
+ state: WorkerRuntimeStateMachine,
470
+ fatal: PendingFatal,
471
+ source: WorkerSnapshotSource,
472
+ afterSnapshot: "exit" | "cleanup",
473
+ outputs: WorkerRuntimeOutput[],
474
+ ): WorkerRuntimeStateMachine {
475
+ requireNoPublication(state);
476
+ const snapshot = {
477
+ point: "before_worker_failed" as const,
478
+ turnRecordId: null,
479
+ required: false as const,
480
+ };
481
+ outputs.push({ kind: "upload_snapshot", ...snapshot, source });
482
+ return {
483
+ ...state,
484
+ work: {
485
+ ...state.work,
486
+ publication: { kind: "fatal_snapshot", snapshot, fatal, afterSnapshot },
487
+ },
488
+ };
489
+ }
490
+
491
+ function finishFatal(
492
+ state: WorkerRuntimeStateMachine,
493
+ fatal: PendingFatal,
494
+ ): { state: WorkerRuntimeStateMachine; outputs: WorkerRuntimeOutput[] } {
495
+ const outputs: WorkerRuntimeOutput[] = [
496
+ protocol("worker.failed", fatal.payload),
497
+ { kind: "close_transport" },
498
+ ];
499
+ if (fatal.exitCode !== undefined) outputs.push({ kind: "exit", code: fatal.exitCode });
500
+ return {
501
+ state: {
502
+ ...state,
503
+ work: { ...state.work, publication: { kind: "none" } },
504
+ phase: { kind: "exited" },
505
+ },
506
+ outputs,
507
+ };
508
+ }
509
+
510
+ function failureOutputs(
511
+ state: WorkerRuntimeStateMachine,
512
+ failure: WorkerFailure,
513
+ ): { state: WorkerRuntimeStateMachine; outputs: WorkerRuntimeOutput[] } {
514
+ const disposition = normalizeWorkerFailure(failure);
515
+ const outputs: WorkerRuntimeOutput[] = [];
516
+ if (disposition.diagnostic)
517
+ outputs.push({
518
+ kind: "diagnostic",
519
+ payload: disposition.diagnostic,
520
+ });
521
+ if (disposition.stderrMessage)
522
+ outputs.push({ kind: "stderr", message: disposition.stderrMessage });
523
+ let next = state;
524
+ switch (disposition.terminal.kind) {
525
+ case "turn_failed":
526
+ outputs.push(protocol("worker.turn_failed", disposition.terminal.payload));
527
+ outputs.push(protocol("worker.lifecycle_parked", disposition.terminal.park));
528
+ break;
529
+ case "park":
530
+ outputs.push(protocol("worker.lifecycle_parked", disposition.terminal.payload));
531
+ break;
532
+ case "worker_failed": {
533
+ const fatal = {
534
+ payload: disposition.terminal.payload,
535
+ ...(disposition.exitCode === undefined ? {} : { exitCode: disposition.exitCode }),
536
+ };
537
+ if (disposition.snapshot && !hasActivePublication(state)) {
538
+ const afterSnapshot =
539
+ state.phase.kind === "cleaning" && state.phase.stage === "publication"
540
+ ? "cleanup"
541
+ : "exit";
542
+ next = beginFatalSnapshot(next, fatal, disposition.snapshot.source, afterSnapshot, outputs);
543
+ break;
544
+ }
545
+ const finished = finishFatal(next, fatal);
546
+ next = finished.state;
547
+ outputs.push(...finished.outputs);
548
+ break;
549
+ }
550
+ case "transport_lost":
551
+ next = {
552
+ ...next,
553
+ work: { ...next.work, publication: { kind: "none" } },
554
+ phase: { kind: "exited" },
555
+ };
556
+ outputs.push({ kind: "close_transport" }, { kind: "exit", code: disposition.exitCode ?? 1 });
557
+ break;
558
+ }
559
+ return { state: next, outputs };
560
+ }
561
+
562
+ function matchesBootstrap(state: WorkerRuntimeStateMachine, startRecordId: string): boolean {
563
+ return (
564
+ (state.phase.kind === "bootstrapping" && state.phase.startRecordId === startRecordId) ||
565
+ (state.phase.kind === "draining" &&
566
+ state.phase.operation?.kind === "bootstrap" &&
567
+ state.phase.operation.startRecordId === startRecordId)
568
+ );
569
+ }
570
+
571
+ function matchesActivation(
572
+ state: WorkerRuntimeStateMachine,
573
+ startRecordId: string,
574
+ turnRecordId: string,
575
+ ): boolean {
576
+ if (state.phase.kind === "activating") {
577
+ return state.phase.startRecordId === startRecordId && state.phase.turnRecordId === turnRecordId;
578
+ }
579
+ const operation = state.phase.kind === "draining" ? state.phase.operation : null;
580
+ return (
581
+ operation?.kind === "activation" &&
582
+ operation.startRecordId === startRecordId &&
583
+ operation.turnRecordId === turnRecordId
584
+ );
585
+ }
586
+
587
+ function matchesTurn(state: WorkerRuntimeStateMachine, turnRecordId: string): boolean {
588
+ if (state.phase.kind === "active") {
589
+ return state.phase.turnStatus === "executing" && state.phase.turnRecordId === turnRecordId;
590
+ }
591
+ return (
592
+ state.phase.kind === "draining" &&
593
+ state.phase.operation?.kind === "turn" &&
594
+ state.phase.operation.turnRecordId === turnRecordId
595
+ );
596
+ }
597
+
598
+ function finishDrainingOperation(state: WorkerRuntimeStateMachine): WorkerRuntimeStateMachine {
599
+ return state.phase.kind === "draining"
600
+ ? { ...state, phase: { ...state.phase, operation: null } }
601
+ : state;
602
+ }
603
+
604
+ function noActiveWork(state: WorkerRuntimeStateMachine): boolean {
605
+ return (
606
+ state.phase.kind === "draining" &&
607
+ state.phase.operation === null &&
608
+ state.work.deliveryHeadSequence === null &&
609
+ state.work.publication.kind === "none"
610
+ );
611
+ }
612
+
613
+ function inputConsumedFact(
614
+ item: { inputId: string; sequence: number },
615
+ deliveryMode: string,
616
+ meta: Record<string, unknown> = {},
617
+ ): WorkerProtocolFact<"worker.input_consumed"> {
618
+ return protocol("worker.input_consumed", {
619
+ inputId: item.inputId,
620
+ sequence: item.sequence,
621
+ deliveryMode,
622
+ ...meta,
623
+ } as never);
624
+ }
625
+
626
+ function removeAppliedTargeted(
627
+ state: WorkerRuntimeStateMachine,
628
+ applied: readonly AppliedTargetedInput[],
629
+ outputs: WorkerRuntimeOutput[],
630
+ ): WorkerRuntimeStateMachine {
631
+ const queue = [...state.inputQueue];
632
+ let last = state.lastSequenceConsumed;
633
+ for (const item of applied) {
634
+ const head = queue[0];
635
+ if (!head || head.inputId !== item.inputId || head.sequence !== item.sequence || !head.target)
636
+ break;
637
+ queue.shift();
638
+ last = Math.max(last, item.sequence);
639
+ outputs.push(inputConsumedFact(item, "append_message", item.meta ?? {}));
640
+ }
641
+ return { ...state, inputQueue: queue, lastSequenceConsumed: last };
642
+ }
643
+
644
+ function armTimer(
645
+ state: WorkerRuntimeStateMachine,
646
+ outputs: WorkerRuntimeOutput[],
647
+ name: WorkerTimerName,
648
+ delayMs: number,
649
+ correlation: string,
650
+ ): WorkerRuntimeStateMachine {
651
+ outputs.push({ kind: "arm_timer", name, delayMs, correlation });
652
+ return { ...state, timers: { ...state.timers, [name]: correlation } };
653
+ }
654
+
655
+ function beginActivation(
656
+ state: WorkerRuntimeStateMachine,
657
+ startRecordId: string,
658
+ turnRecordId: string,
659
+ outputs: WorkerRuntimeOutput[],
660
+ ): WorkerRuntimeStateMachine {
661
+ if (!state.session) return state;
662
+ outputs.push({ kind: "cancel_timer", name: "acceptance_retry" });
663
+ outputs.push({ kind: "activate", startRecordId, turnRecordId, session: state.session });
664
+ return {
665
+ ...state,
666
+ phase: { kind: "activating", startRecordId, turnRecordId },
667
+ timers: { ...state.timers, acceptance_retry: null },
668
+ };
669
+ }
670
+
671
+ function finishReadying(
672
+ state: WorkerRuntimeStateMachine,
673
+ outputs: WorkerRuntimeOutput[],
674
+ ): WorkerRuntimeStateMachine {
675
+ if (state.phase.kind !== "readying" || state.credential?.sampling) return state;
676
+ const readying = state.phase;
677
+ const next = state;
678
+ if (hasActivePublication(next)) return next;
679
+ const { startRecordId, proposedTurnRecordId, acceptedId } = readying;
680
+ if (acceptedId) return beginActivation(next, startRecordId, acceptedId, outputs);
681
+ outputs.push(protocol("worker.turn_started", { startRecordId, proposedTurnRecordId }));
682
+ return armTimer(
683
+ { ...next, phase: { kind: "waiting_for_acceptance", startRecordId, proposedTurnRecordId } },
684
+ outputs,
685
+ "acceptance_retry",
686
+ 1_000,
687
+ startRecordId,
688
+ );
689
+ }
690
+
691
+ function advance(
692
+ state: WorkerRuntimeStateMachine,
693
+ outputs: WorkerRuntimeOutput[],
694
+ ): WorkerRuntimeStateMachine {
695
+ let next = finishReadying(state, outputs);
696
+ if (next.phase.kind === "draining" && noActiveWork(next)) {
697
+ const { reason, exitAfterCleanup } = next.phase;
698
+ outputs.push(protocol("worker.cleanup_started", { reason }));
699
+ const cleanupSnapshot = next.session
700
+ ? resolveWorkerSnapshotPolicy(
701
+ "before_cleanup_completed",
702
+ next.session.kind,
703
+ next.session.piAvailable,
704
+ )
705
+ : { upload: false as const };
706
+ if (cleanupSnapshot.upload && next.session) {
707
+ next = beginCleanupSnapshot(
708
+ {
709
+ ...next,
710
+ phase: { kind: "cleaning", reason, exitAfterCleanup, stage: "publication" },
711
+ },
712
+ sessionSnapshotSource(next.session),
713
+ outputs,
714
+ );
715
+ } else {
716
+ outputs.push({ kind: "cleanup" });
717
+ next = {
718
+ ...next,
719
+ phase: { kind: "cleaning", reason, exitAfterCleanup, stage: "resources" },
720
+ };
721
+ }
722
+ return next;
723
+ }
724
+ if (
725
+ (next.phase.kind !== "active" && next.phase.kind !== "waiting_for_acceptance") ||
726
+ next.work.deliveryHeadSequence !== null ||
727
+ hasActivePublication(next)
728
+ )
729
+ return next;
730
+ const mayStartTurn = next.phase.kind === "active" && next.phase.turnStatus === "pending";
731
+ if (next.phase.kind === "waiting_for_acceptance" && next.session?.kind === "llm") return next;
732
+ const decision = decideWorkerInputEffect({
733
+ items: next.inputQueue,
734
+ sessionTainted: next.sessionTainted,
735
+ piAvailable: next.session?.piAvailable ?? false,
736
+ mayStartTurn,
737
+ });
738
+ if (decision.kind === "blocked") {
739
+ outputs.push({
740
+ kind: "diagnostic",
741
+ payload: {
742
+ level: "warn",
743
+ code: "input.skipped_session_tainted",
744
+ message: "Skipping queued inputs because the Pi session is tainted",
745
+ details: { skippedInputCount: next.inputQueue.length },
746
+ },
747
+ });
748
+ return next;
749
+ }
750
+ if (decision.kind === "consume_ignored") {
751
+ const ids = new Set(decision.inputs.map((item) => item.inputId));
752
+ for (const item of decision.inputs) outputs.push(inputConsumedFact(item, "ignored"));
753
+ next = {
754
+ ...next,
755
+ inputQueue: next.inputQueue.filter((item) => !ids.has(item.inputId)),
756
+ lastSequenceConsumed: Math.max(
757
+ next.lastSequenceConsumed,
758
+ ...decision.inputs.map((item) => item.sequence),
759
+ ),
760
+ };
761
+ return advance(next, outputs);
762
+ }
763
+ if (decision.kind === "deliver") {
764
+ const headSequence = decision.inputs[0].sequence;
765
+ outputs.push({
766
+ kind: "deliver_inputs",
767
+ headSequence,
768
+ inputs: decision.inputs,
769
+ piTurnActive: next.piTurnActive,
770
+ });
771
+ return { ...next, work: { ...next.work, deliveryHeadSequence: headSequence } };
772
+ }
773
+ if (decision.kind === "start_turn" && next.session && next.phase.kind === "active") {
774
+ outputs.push({
775
+ kind: "execute_turn",
776
+ turnRecordId: next.phase.turnRecordId,
777
+ targetedInputs: decision.inputs,
778
+ session: next.session,
779
+ });
780
+ return {
781
+ ...next,
782
+ phase: { ...next.phase, turnStatus: "executing" },
783
+ };
784
+ }
785
+ return next;
786
+ }
787
+
788
+ function withReportedTransition(
789
+ previous: WorkerRuntimeStateMachine,
790
+ next: WorkerRuntimeStateMachine,
791
+ event: WorkerRuntimeEvent,
792
+ outputs: WorkerRuntimeOutput[],
793
+ ): WorkerRuntimeReduction {
794
+ const from = deriveReportedWorkerState(previous);
795
+ const to = deriveReportedWorkerState(next);
796
+ if (from !== to && next.phase.kind !== "exited") {
797
+ outputs.push(protocol("worker.state", { from, to, reason: event.kind }));
798
+ }
799
+ return { state: next, outputs };
800
+ }
801
+
802
+ /** The sole pure owner of worker lifecycle decisions and canonical facts. */
803
+ export function reduceWorkerRuntime(
804
+ state: WorkerRuntimeStateMachine,
805
+ event: WorkerRuntimeEvent,
806
+ ): WorkerRuntimeReduction {
807
+ let next = state;
808
+ const outputs: WorkerRuntimeOutput[] = [];
809
+
810
+ if (state.phase.kind === "exited" && event.kind !== "runtime_started") return { state, outputs };
811
+
812
+ switch (event.kind) {
813
+ case "runtime_started":
814
+ if (state.phase.kind !== "init") break;
815
+ next = { ...state, phase: { kind: "waiting_for_start" } };
816
+ outputs.push(HELLO);
817
+ break;
818
+ case "transport_connected":
819
+ outputs.push(HELLO);
820
+ if (state.session) {
821
+ outputs.push(
822
+ protocol("worker.heartbeat", {
823
+ state: deriveReportedWorkerState(state),
824
+ lastSequenceConsumed: state.lastSequenceConsumed,
825
+ currentSelectedTurnId: state.session.selectedTurnId,
826
+ }),
827
+ );
828
+ }
829
+ break;
830
+ case "transport_failed": {
831
+ const failed = failureOutputs(state, { kind: "transport", error: event.error });
832
+ next = failed.state;
833
+ outputs.push(...failed.outputs);
834
+ break;
835
+ }
836
+ case "stop_requested":
837
+ if (state.phase.kind === "cleaning" || state.phase.kind === "draining") break;
838
+ {
839
+ const operation: DrainingOperation =
840
+ state.phase.kind === "bootstrapping"
841
+ ? {
842
+ kind: "bootstrap",
843
+ startRecordId: state.phase.startRecordId,
844
+ proposedTurnRecordId: state.phase.proposedTurnRecordId,
845
+ }
846
+ : state.phase.kind === "activating"
847
+ ? {
848
+ kind: "activation",
849
+ startRecordId: state.phase.startRecordId,
850
+ turnRecordId: state.phase.turnRecordId,
851
+ }
852
+ : state.phase.kind === "active" && state.phase.turnStatus === "executing"
853
+ ? { kind: "turn", turnRecordId: state.phase.turnRecordId }
854
+ : null;
855
+ next = {
856
+ ...state,
857
+ phase: {
858
+ kind: "draining",
859
+ reason: event.reason,
860
+ exitAfterCleanup: event.exitAfterCleanup,
861
+ operation,
862
+ },
863
+ };
864
+ }
865
+ for (const name of Object.keys(state.timers) as WorkerTimerName[])
866
+ outputs.push({ kind: "cancel_timer", name });
867
+ next = {
868
+ ...next,
869
+ timers: { heartbeat: null, acceptance_retry: null, credential_poll: null },
870
+ credential: null,
871
+ };
872
+ break;
873
+ case "operator_abort_observed":
874
+ break;
875
+ case "pi_turn_started":
876
+ next = { ...state, piTurnActive: true };
877
+ break;
878
+ case "pi_turn_ended":
879
+ next = { ...state, piTurnActive: false };
880
+ break;
881
+ case "session_tainted":
882
+ if (!state.sessionTainted) {
883
+ next = { ...state, sessionTainted: true };
884
+ outputs.push({
885
+ kind: "extension",
886
+ event: "worker.session_tainted",
887
+ payload: { reason: event.reason },
888
+ });
889
+ }
890
+ break;
891
+ case "server_message": {
892
+ const message = event.message;
893
+ if (message.type === "worker.stop") {
894
+ return reduceWorkerRuntime(state, {
895
+ kind: "stop_requested",
896
+ reason: message.payload.reason,
897
+ exitAfterCleanup: true,
898
+ });
899
+ }
900
+ if (message.type === "worker.abort_turn") break;
901
+ if (message.type === "worker.start") {
902
+ if (state.phase.kind !== "waiting_for_start") break;
903
+ const startRecordId = message.payload.turnStart.id;
904
+ next = {
905
+ ...state,
906
+ phase: {
907
+ kind: "bootstrapping",
908
+ startRecordId,
909
+ proposedTurnRecordId: message.payload.turnStart.proposedTurnRecordId,
910
+ },
911
+ sessionTainted: false,
912
+ };
913
+ outputs.push({ kind: "bootstrap", startRecordId, payload: message.payload });
914
+ break;
915
+ }
916
+ if (message.type === "input.batch") {
917
+ if (state.phase.kind === "waiting_for_start" || state.phase.kind === "init") break;
918
+ const incoming = message.payload.inputs
919
+ .map(inputDeliveryToItem)
920
+ .filter((item) => item.sequence > state.lastSequenceConsumed);
921
+ next = { ...state, inputQueue: enqueueInputs(state.inputQueue, incoming) };
922
+ break;
923
+ }
924
+ if (message.type === "worker.turn_start_accepted") {
925
+ if (
926
+ state.phase.kind === "readying" &&
927
+ message.payload.startRecordId === state.phase.startRecordId
928
+ ) {
929
+ next = { ...state, phase: { ...state.phase, acceptedId: message.payload.turnRecordId } };
930
+ break;
931
+ }
932
+ if (
933
+ state.phase.kind !== "waiting_for_acceptance" ||
934
+ message.payload.startRecordId !== state.phase.startRecordId
935
+ )
936
+ break;
937
+ next = beginActivation(
938
+ state,
939
+ message.payload.startRecordId,
940
+ message.payload.turnRecordId,
941
+ outputs,
942
+ );
943
+ break;
944
+ }
945
+ if (message.type === "worker.credential_update_accepted") {
946
+ const credential = state.credential;
947
+ if (
948
+ !credential?.enabled ||
949
+ !credential.updatePending ||
950
+ message.payload.providerId !== credential.descriptor.providerId
951
+ )
952
+ break;
953
+ if (!message.payload.accepted || message.payload.currentRevision === null) {
954
+ next = {
955
+ ...state,
956
+ credential: {
957
+ ...credential,
958
+ enabled: false,
959
+ updatePending: false,
960
+ pendingFingerprint: null,
961
+ },
962
+ };
963
+ outputs.push({
964
+ kind: "diagnostic",
965
+ payload: {
966
+ level: "warn",
967
+ code: "credential.refresh_rejected",
968
+ message: message.payload.safeReason ?? "Credential refresh was rejected",
969
+ },
970
+ stderr: message.payload.safeReason,
971
+ });
972
+ } else {
973
+ next = {
974
+ ...state,
975
+ credential: {
976
+ ...credential,
977
+ revision: message.payload.currentRevision,
978
+ baselineFingerprint: credential.pendingFingerprint ?? credential.baselineFingerprint,
979
+ pendingFingerprint: null,
980
+ updatePending: false,
981
+ sampling: true,
982
+ },
983
+ };
984
+ outputs.push({
985
+ kind: "sample_credentials",
986
+ descriptor: credential.descriptor,
987
+ baseline: false,
988
+ });
989
+ }
990
+ }
991
+ break;
992
+ }
993
+ case "bootstrap_succeeded": {
994
+ if (!matchesBootstrap(state, event.startRecordId)) break;
995
+ const completion = event.completion;
996
+ const acceptedId = completion.session.acceptedTurnRecordId;
997
+ const credential = completion.credentialRefresh
998
+ ? {
999
+ descriptor: completion.credentialRefresh,
1000
+ baselineFingerprint: null,
1001
+ pendingFingerprint: null,
1002
+ revision: completion.credentialRefresh.revision,
1003
+ sampling: true,
1004
+ updatePending: false,
1005
+ enabled: true,
1006
+ }
1007
+ : null;
1008
+ const wasDraining = state.phase.kind === "draining";
1009
+ next = {
1010
+ ...state,
1011
+ phase:
1012
+ state.phase.kind === "draining"
1013
+ ? { ...state.phase, operation: null }
1014
+ : {
1015
+ kind: "readying",
1016
+ startRecordId: event.startRecordId,
1017
+ proposedTurnRecordId: completion.session.proposedTurnRecordId,
1018
+ acceptedId,
1019
+ },
1020
+ session: completion.session,
1021
+ inputQueue: enqueueInputs(
1022
+ state.inputQueue,
1023
+ completion.pendingInputs.filter((item) => item.sequence > state.lastSequenceConsumed),
1024
+ ),
1025
+ credential: wasDraining ? null : credential,
1026
+ };
1027
+ for (const message of completion.diagnostics)
1028
+ outputs.push({
1029
+ kind: "diagnostic",
1030
+ payload: { level: "warn", code: "bootstrap.diagnostic", message },
1031
+ });
1032
+ outputs.push(protocol("worker.ready", completion.readyPayload));
1033
+ if (wasDraining) break;
1034
+ const readySnapshot = resolveWorkerSnapshotPolicy(
1035
+ "after_worker_ready",
1036
+ completion.session.kind,
1037
+ completion.session.piAvailable,
1038
+ );
1039
+ if (readySnapshot.upload)
1040
+ next = beginReadySnapshot(next, sessionSnapshotSource(completion.session), outputs);
1041
+ next = armTimer(
1042
+ next,
1043
+ outputs,
1044
+ "heartbeat",
1045
+ completion.session.settings.heartbeatIntervalMs,
1046
+ event.startRecordId,
1047
+ );
1048
+ if (completion.credentialRefresh)
1049
+ outputs.push({
1050
+ kind: "sample_credentials",
1051
+ descriptor: completion.credentialRefresh,
1052
+ baseline: true,
1053
+ });
1054
+ break;
1055
+ }
1056
+ case "bootstrap_failed":
1057
+ if (!matchesBootstrap(state, event.startRecordId)) break;
1058
+ if (state.phase.kind === "draining") {
1059
+ next = finishDrainingOperation(state);
1060
+ break;
1061
+ }
1062
+ {
1063
+ const failed = failureOutputs(state, {
1064
+ kind: "bootstrap",
1065
+ error: event.error,
1066
+ payload: event.payload,
1067
+ });
1068
+ next = failed.state;
1069
+ outputs.push(...failed.outputs);
1070
+ }
1071
+ break;
1072
+ case "activation_succeeded":
1073
+ if (!matchesActivation(state, event.startRecordId, event.turnRecordId)) break;
1074
+ next = {
1075
+ ...state,
1076
+ phase:
1077
+ state.phase.kind === "draining"
1078
+ ? { ...state.phase, operation: null }
1079
+ : {
1080
+ kind: "active",
1081
+ startRecordId: event.startRecordId,
1082
+ turnRecordId: event.turnRecordId,
1083
+ turnStatus: "pending",
1084
+ },
1085
+ session:
1086
+ state.session?.kind === "llm"
1087
+ ? {
1088
+ ...state.session,
1089
+ piAvailable: true,
1090
+ activeModelProfileId:
1091
+ state.session.processSnapshot.selectedTurnModelProfileId ?? null,
1092
+ }
1093
+ : state.session,
1094
+ };
1095
+ for (const message of event.diagnostics)
1096
+ outputs.push({
1097
+ kind: "diagnostic",
1098
+ payload: { level: "warn", code: "bootstrap.diagnostic", message },
1099
+ });
1100
+ if (state.session?.kind === "llm" && state.phase.kind !== "draining")
1101
+ outputs.push({
1102
+ kind: "extension",
1103
+ event: "worker.handle_ready",
1104
+ payload: {
1105
+ treeFile: state.session.treeFile,
1106
+ workspaceRoot: state.session.workspaceRoot,
1107
+ },
1108
+ });
1109
+ break;
1110
+ case "activation_failed":
1111
+ if (!matchesActivation(state, event.startRecordId, event.turnRecordId)) break;
1112
+ if (state.phase.kind === "draining") {
1113
+ next = finishDrainingOperation(state);
1114
+ } else {
1115
+ const failed = failureOutputs(next, {
1116
+ kind: "dispatch",
1117
+ error: event.error,
1118
+ state: "busy",
1119
+ session: failureContext(state),
1120
+ });
1121
+ next = failed.state;
1122
+ outputs.push(...failed.outputs);
1123
+ }
1124
+ break;
1125
+ case "inputs_delivered": {
1126
+ if (
1127
+ state.work.deliveryHeadSequence !== event.headSequence ||
1128
+ state.inputQueue[0]?.sequence !== event.headSequence
1129
+ )
1130
+ break;
1131
+ const deliveredIds = new Set(event.delivered.map((item) => item.inputId));
1132
+ let last = state.lastSequenceConsumed;
1133
+ for (const delivered of event.delivered) {
1134
+ last = Math.max(last, delivered.sequence);
1135
+ outputs.push(inputConsumedFact(delivered, delivered.deliveryMode, event.meta ?? {}));
1136
+ }
1137
+ next = {
1138
+ ...state,
1139
+ inputQueue: state.inputQueue.filter((item) => !deliveredIds.has(item.inputId)),
1140
+ lastSequenceConsumed: last,
1141
+ work: { ...state.work, deliveryHeadSequence: null },
1142
+ };
1143
+ break;
1144
+ }
1145
+ case "input_delivery_failed":
1146
+ if (state.work.deliveryHeadSequence !== event.headSequence) break;
1147
+ next = { ...state, work: { ...state.work, deliveryHeadSequence: null } };
1148
+ if (state.phase.kind !== "draining") {
1149
+ const failed = failureOutputs(next, {
1150
+ kind: "dispatch",
1151
+ error: event.error,
1152
+ state: currentStateName(state),
1153
+ session: failureContext(state),
1154
+ });
1155
+ next = failed.state;
1156
+ outputs.push(...failed.outputs);
1157
+ }
1158
+ break;
1159
+ case "turn_completed": {
1160
+ if (!matchesTurn(state, event.turnRecordId)) break;
1161
+ next = removeAppliedTargeted(
1162
+ finishDrainingOperation(state),
1163
+ event.result.appliedTargetedInputs,
1164
+ outputs,
1165
+ );
1166
+ if (event.result.kind === "parked") {
1167
+ outputs.push(
1168
+ protocol("worker.lifecycle_parked", {
1169
+ selectedTurnId: state.session?.selectedTurnId ?? null,
1170
+ reason: event.result.reason,
1171
+ }),
1172
+ );
1173
+ next = {
1174
+ ...next,
1175
+ phase:
1176
+ state.phase.kind === "active"
1177
+ ? { ...state.phase, turnStatus: "completed" }
1178
+ : next.phase,
1179
+ };
1180
+ break;
1181
+ }
1182
+ let pending: PendingTerminal;
1183
+ if (event.result.kind === "outcome") {
1184
+ pending = {
1185
+ fact: protocol("worker.turn_outcome", {
1186
+ turnRecordId: event.result.meta.turnRecordId,
1187
+ turnId: event.result.turnId,
1188
+ turnType: event.result.meta.turnType ?? "llm",
1189
+ outcome: event.result.outcome,
1190
+ params: event.result.params,
1191
+ pathType: event.result.meta.pathType,
1192
+ forkPiEntryId: event.result.meta.forkPiEntryId ?? null,
1193
+ resultPiEntryId: event.result.meta.resultPiEntryId ?? null,
1194
+ turnResultMarkdown: event.result.meta.turnResultMarkdown ?? null,
1195
+ rootEntryId: event.result.meta.rootEntryId ?? null,
1196
+ } as never),
1197
+ park: null,
1198
+ correlation: {
1199
+ turnRecordId: event.result.meta.turnRecordId,
1200
+ turnId: event.result.turnId,
1201
+ turnType: event.result.meta.turnType,
1202
+ pathType: event.result.meta.pathType,
1203
+ forkPiEntryId: event.result.meta.forkPiEntryId,
1204
+ resultPiEntryId: event.result.meta.resultPiEntryId,
1205
+ },
1206
+ };
1207
+ } else {
1208
+ const disposition = normalizeWorkerFailure({
1209
+ kind: "turn",
1210
+ error: event.result.failure.failure,
1211
+ correlation: event.result.failure,
1212
+ session: failureContext(state),
1213
+ });
1214
+ if (disposition.terminal.kind !== "turn_failed")
1215
+ throw new Error("Turn failure policy did not produce a turn failure");
1216
+ pending = {
1217
+ fact: protocol("worker.turn_failed", disposition.terminal.payload),
1218
+ park: disposition.terminal.park,
1219
+ correlation: event.result.failure,
1220
+ };
1221
+ }
1222
+ next = {
1223
+ ...next,
1224
+ phase:
1225
+ state.phase.kind === "active" ? { ...state.phase, turnStatus: "completed" } : next.phase,
1226
+ };
1227
+ if (state.session?.kind === "automatic") {
1228
+ outputs.push(pending.fact);
1229
+ if (pending.park) outputs.push(protocol("worker.lifecycle_parked", pending.park));
1230
+ } else if (state.session) {
1231
+ const point =
1232
+ event.result.kind === "outcome" ? "before_turn_outcome" : "before_turn_failed";
1233
+ const snapshotPolicy = resolveWorkerSnapshotPolicy(
1234
+ point,
1235
+ state.session.kind,
1236
+ state.session.piAvailable,
1237
+ );
1238
+ if (!snapshotPolicy.upload)
1239
+ throw new Error("LLM terminal snapshot policy unexpectedly skipped upload");
1240
+ next = beginTerminalSnapshot(
1241
+ next,
1242
+ point,
1243
+ event.turnRecordId,
1244
+ pending,
1245
+ sessionSnapshotSource(state.session),
1246
+ outputs,
1247
+ );
1248
+ }
1249
+ break;
1250
+ }
1251
+ case "turn_defect":
1252
+ if (!matchesTurn(state, event.turnRecordId)) break;
1253
+ if (state.phase.kind === "draining") {
1254
+ next = finishDrainingOperation(state);
1255
+ } else {
1256
+ const failed = failureOutputs(next, {
1257
+ kind: "dispatch",
1258
+ error: event.error,
1259
+ state: "busy",
1260
+ session: failureContext(state),
1261
+ });
1262
+ next = failed.state;
1263
+ outputs.push(...failed.outputs);
1264
+ }
1265
+ break;
1266
+ case "snapshot_succeeded": {
1267
+ const publication = state.work.publication;
1268
+ switch (publication.kind) {
1269
+ case "none":
1270
+ case "fatal_pending_cleanup":
1271
+ break;
1272
+ case "ready_snapshot":
1273
+ if (!snapshotMatches(publication.snapshot, event)) break;
1274
+ next = { ...state, work: { ...state.work, publication: { kind: "none" } } };
1275
+ break;
1276
+ case "terminal_snapshot":
1277
+ if (!snapshotMatches(publication.snapshot, event)) break;
1278
+ outputs.push(publication.terminal.fact);
1279
+ if (publication.terminal.park)
1280
+ outputs.push(protocol("worker.lifecycle_parked", publication.terminal.park));
1281
+ next = { ...state, work: { ...state.work, publication: { kind: "none" } } };
1282
+ break;
1283
+ case "cleanup_snapshot":
1284
+ if (!snapshotMatches(publication.snapshot, event)) break;
1285
+ if (state.phase.kind !== "cleaning" || state.phase.stage !== "publication")
1286
+ throw new Error("Cleanup snapshot completed outside cleanup publication");
1287
+ outputs.push({ kind: "cleanup" });
1288
+ next = {
1289
+ ...state,
1290
+ phase: { ...state.phase, stage: "resources" },
1291
+ work: { ...state.work, publication: { kind: "none" } },
1292
+ };
1293
+ break;
1294
+ case "fatal_snapshot":
1295
+ if (!snapshotMatches(publication.snapshot, event)) break;
1296
+ if (publication.afterSnapshot === "exit") {
1297
+ const finished = finishFatal(state, publication.fatal);
1298
+ next = finished.state;
1299
+ outputs.push(...finished.outputs);
1300
+ } else {
1301
+ if (state.phase.kind !== "cleaning" || state.phase.stage !== "publication")
1302
+ throw new Error("Fatal snapshot completed outside cleanup publication");
1303
+ outputs.push({ kind: "cleanup" });
1304
+ next = {
1305
+ ...state,
1306
+ phase: { ...state.phase, stage: "resources" },
1307
+ work: {
1308
+ ...state.work,
1309
+ publication: {
1310
+ kind: "fatal_pending_cleanup",
1311
+ fatal: publication.fatal,
1312
+ },
1313
+ },
1314
+ };
1315
+ }
1316
+ break;
1317
+ }
1318
+ break;
1319
+ }
1320
+ case "snapshot_failed": {
1321
+ const publication = state.work.publication;
1322
+ switch (publication.kind) {
1323
+ case "none":
1324
+ case "fatal_pending_cleanup":
1325
+ break;
1326
+ case "ready_snapshot":
1327
+ if (!snapshotMatches(publication.snapshot, event)) break;
1328
+ next = { ...state, work: { ...state.work, publication: { kind: "none" } } };
1329
+ break;
1330
+ case "terminal_snapshot": {
1331
+ if (!snapshotMatches(publication.snapshot, event)) break;
1332
+ const cleared = {
1333
+ ...state,
1334
+ work: { ...state.work, publication: { kind: "none" } as const },
1335
+ };
1336
+ const failed = failureOutputs(cleared, {
1337
+ kind: "mandatory_snapshot",
1338
+ error: event.error,
1339
+ point: event.point,
1340
+ correlation: publication.terminal.correlation,
1341
+ session: failureContext(state),
1342
+ });
1343
+ next = failed.state;
1344
+ outputs.push(...failed.outputs);
1345
+ break;
1346
+ }
1347
+ case "cleanup_snapshot": {
1348
+ if (!snapshotMatches(publication.snapshot, event)) break;
1349
+ if (state.phase.kind !== "cleaning" || state.phase.stage !== "publication")
1350
+ throw new Error("Cleanup snapshot failed outside cleanup publication");
1351
+ const cleared = {
1352
+ ...state,
1353
+ work: { ...state.work, publication: { kind: "none" } as const },
1354
+ };
1355
+ const failed = failureOutputs(cleared, {
1356
+ kind: "cleanup",
1357
+ error: event.error,
1358
+ session: failureContext(state),
1359
+ });
1360
+ next = failed.state;
1361
+ outputs.push(...failed.outputs);
1362
+ break;
1363
+ }
1364
+ case "fatal_snapshot":
1365
+ if (!snapshotMatches(publication.snapshot, event)) break;
1366
+ if (publication.afterSnapshot === "exit") {
1367
+ const finished = finishFatal(state, publication.fatal);
1368
+ next = finished.state;
1369
+ outputs.push(...finished.outputs);
1370
+ } else {
1371
+ if (state.phase.kind !== "cleaning" || state.phase.stage !== "publication")
1372
+ throw new Error("Fatal snapshot failed outside cleanup publication");
1373
+ outputs.push({ kind: "cleanup" });
1374
+ next = {
1375
+ ...state,
1376
+ phase: { ...state.phase, stage: "resources" },
1377
+ work: {
1378
+ ...state.work,
1379
+ publication: {
1380
+ kind: "fatal_pending_cleanup",
1381
+ fatal: publication.fatal,
1382
+ },
1383
+ },
1384
+ };
1385
+ }
1386
+ break;
1387
+ }
1388
+ break;
1389
+ }
1390
+ case "timer_fired":
1391
+ if (state.timers[event.name] !== event.correlation) break;
1392
+ next = { ...state, timers: { ...state.timers, [event.name]: null } };
1393
+ if (event.name === "heartbeat" && state.session) {
1394
+ outputs.push(
1395
+ protocol("worker.heartbeat", {
1396
+ state: deriveReportedWorkerState(state),
1397
+ lastSequenceConsumed: state.lastSequenceConsumed,
1398
+ currentSelectedTurnId: state.session.selectedTurnId,
1399
+ }),
1400
+ );
1401
+ next = armTimer(
1402
+ next,
1403
+ outputs,
1404
+ "heartbeat",
1405
+ state.session.settings.heartbeatIntervalMs,
1406
+ event.correlation,
1407
+ );
1408
+ } else if (
1409
+ event.name === "acceptance_retry" &&
1410
+ state.phase.kind === "waiting_for_acceptance"
1411
+ ) {
1412
+ outputs.push(
1413
+ protocol("worker.turn_started", {
1414
+ startRecordId: state.phase.startRecordId,
1415
+ proposedTurnRecordId: state.phase.proposedTurnRecordId,
1416
+ }),
1417
+ );
1418
+ next = armTimer(next, outputs, "acceptance_retry", 1_000, event.correlation);
1419
+ } else if (
1420
+ event.name === "credential_poll" &&
1421
+ state.credential?.enabled &&
1422
+ !state.credential.sampling &&
1423
+ !state.credential.updatePending
1424
+ ) {
1425
+ outputs.push({
1426
+ kind: "sample_credentials",
1427
+ descriptor: state.credential.descriptor,
1428
+ baseline: false,
1429
+ });
1430
+ next = { ...next, credential: { ...state.credential, sampling: true } };
1431
+ }
1432
+ break;
1433
+ case "credential_sampled": {
1434
+ const credential = state.credential;
1435
+ if (!credential?.sampling || credential.descriptor.providerId !== event.providerId) break;
1436
+ if (
1437
+ credential.baselineFingerprint === null ||
1438
+ credential.baselineFingerprint === event.fingerprint
1439
+ ) {
1440
+ next = armTimer(
1441
+ {
1442
+ ...state,
1443
+ credential: {
1444
+ ...credential,
1445
+ baselineFingerprint: credential.baselineFingerprint ?? event.fingerprint,
1446
+ sampling: false,
1447
+ },
1448
+ },
1449
+ outputs,
1450
+ "credential_poll",
1451
+ 500,
1452
+ event.providerId,
1453
+ );
1454
+ } else {
1455
+ next = {
1456
+ ...state,
1457
+ credential: {
1458
+ ...credential,
1459
+ sampling: false,
1460
+ updatePending: true,
1461
+ pendingFingerprint: event.fingerprint,
1462
+ },
1463
+ };
1464
+ outputs.push(
1465
+ protocol("worker.credential_update", {
1466
+ providerId: event.providerId,
1467
+ expectedRevision: credential.revision,
1468
+ values: event.values,
1469
+ }),
1470
+ );
1471
+ }
1472
+ break;
1473
+ }
1474
+ case "credential_sample_failed":
1475
+ if (
1476
+ !state.credential?.sampling ||
1477
+ state.credential.descriptor.providerId !== event.providerId
1478
+ )
1479
+ break;
1480
+ next = { ...state, credential: { ...state.credential, sampling: false } };
1481
+ outputs.push({
1482
+ kind: "diagnostic",
1483
+ payload: {
1484
+ level: "warn",
1485
+ code: "credential.refresh_failed",
1486
+ message: event.error instanceof Error ? event.error.message : String(event.error),
1487
+ },
1488
+ });
1489
+ next = armTimer(next, outputs, "credential_poll", 500, event.providerId);
1490
+ break;
1491
+ case "cleanup_succeeded":
1492
+ if (state.phase.kind !== "cleaning" || state.phase.stage !== "resources") break;
1493
+ if (state.work.publication.kind === "fatal_pending_cleanup") {
1494
+ const finished = finishFatal(state, state.work.publication.fatal);
1495
+ next = finished.state;
1496
+ outputs.push(...finished.outputs);
1497
+ break;
1498
+ }
1499
+ outputs.push(
1500
+ protocol("worker.cleanup_completed", { releasedLocks: [], removedTransientPaths: [] }),
1501
+ );
1502
+ outputs.push({ kind: "close_transport" });
1503
+ if (state.phase.exitAfterCleanup) outputs.push({ kind: "exit", code: 0 });
1504
+ next = {
1505
+ ...state,
1506
+ phase: { kind: "exited" },
1507
+ session: null,
1508
+ inputQueue: [],
1509
+ };
1510
+ break;
1511
+ case "cleanup_failed": {
1512
+ if (state.phase.kind !== "cleaning" || state.phase.stage !== "resources") break;
1513
+ const failed = failureOutputs(state, {
1514
+ kind: "cleanup",
1515
+ error: event.error,
1516
+ session: failureContext(state),
1517
+ });
1518
+ next = failed.state;
1519
+ outputs.push(...failed.outputs);
1520
+ break;
1521
+ }
1522
+ case "invariant_failed": {
1523
+ const failed = failureOutputs(state, {
1524
+ kind: "dispatch",
1525
+ error: event.error,
1526
+ state: currentStateName(state),
1527
+ session: failureContext(state),
1528
+ });
1529
+ next = failed.state;
1530
+ outputs.push(...failed.outputs);
1531
+ break;
1532
+ }
1533
+ }
1534
+
1535
+ next = advance(next, outputs);
1536
+ return withReportedTransition(state, next, event, outputs);
1537
+ }