@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,274 @@
1
+ import type { ProcessTurnRecordPathType, ProcessTurnType } from "@leitwerk-dev/domain";
2
+ import type {
3
+ WorkerFailedPayload,
4
+ WorkerLifecycleParkedPayload,
5
+ WorkerStartPayload,
6
+ WorkerTurnFailedPayload,
7
+ } from "@leitwerk-dev/worker-protocol";
8
+ import type { WorkerDiagnosticPayload } from "../diagnostics.js";
9
+ import { classifyRuntimeError, type TurnExecutionError } from "../turn-execution-error.js";
10
+ import type { WorkerRuntimeState } from "./lifecycle-reducer.js";
11
+ import type { WorkerSnapshotPoint } from "./snapshot-policy.js";
12
+
13
+ export interface WorkerFailureSessionContext {
14
+ selectedTurnId: string | null;
15
+ lifecycleStatus: string;
16
+ snapshotSource: WorkerFailureSnapshotRequest["source"];
17
+ }
18
+
19
+ export interface WorkerTurnFailureCorrelation {
20
+ turnRecordId: string;
21
+ turnId: string;
22
+ turnType?: ProcessTurnType;
23
+ pathType?: ProcessTurnRecordPathType;
24
+ forkPiEntryId?: string | null;
25
+ resultPiEntryId?: string | null;
26
+ }
27
+
28
+ export type WorkerFailure =
29
+ | { kind: "bootstrap"; error: unknown; payload: WorkerStartPayload }
30
+ | {
31
+ kind: "turn";
32
+ error: TurnExecutionError;
33
+ correlation: WorkerTurnFailureCorrelation;
34
+ session?: WorkerFailureSessionContext | null;
35
+ }
36
+ | {
37
+ kind: "mandatory_snapshot";
38
+ error: unknown;
39
+ point: WorkerSnapshotPoint;
40
+ correlation: WorkerTurnFailureCorrelation;
41
+ session?: WorkerFailureSessionContext | null;
42
+ }
43
+ | {
44
+ kind: "dispatch";
45
+ error: unknown;
46
+ state: WorkerRuntimeState;
47
+ session: WorkerFailureSessionContext | null;
48
+ }
49
+ | { kind: "cleanup"; error: unknown; session: WorkerFailureSessionContext | null }
50
+ | { kind: "transport"; error: unknown };
51
+
52
+ export type WorkerFailureTerminal =
53
+ | {
54
+ kind: "turn_failed";
55
+ payload: WorkerTurnFailedPayload;
56
+ park: WorkerLifecycleParkedPayload;
57
+ }
58
+ | { kind: "worker_failed"; payload: WorkerFailedPayload }
59
+ | { kind: "park"; payload: WorkerLifecycleParkedPayload }
60
+ | { kind: "transport_lost" };
61
+
62
+ export interface WorkerFailureSnapshotRequest {
63
+ point: "before_worker_failed";
64
+ source: {
65
+ kind: "automatic" | "llm";
66
+ treeFile: string;
67
+ };
68
+ }
69
+
70
+ export interface WorkerFailureDisposition {
71
+ diagnostic: WorkerDiagnosticPayload | null;
72
+ stderrMessage: string;
73
+ snapshot?: WorkerFailureSnapshotRequest;
74
+ terminal: WorkerFailureTerminal;
75
+ exitCode?: number;
76
+ }
77
+
78
+ export function extractSecretValuesFromPayload(
79
+ payload: WorkerStartPayload | null | undefined,
80
+ ): string[] {
81
+ if (!payload) return [];
82
+ const secrets = new Set<string>();
83
+ if (payload.bootstrap.kind === "llm" && payload.bootstrap.credential?.values) {
84
+ for (const value of Object.values(payload.bootstrap.credential.values)) {
85
+ if (typeof value === "string" && value.trim() !== "") secrets.add(value.trim());
86
+ }
87
+ }
88
+ return Array.from(secrets);
89
+ }
90
+
91
+ export function redactSecrets(message: string, secrets: readonly string[]): string {
92
+ let result = message;
93
+ for (const secret of secrets) {
94
+ if (secret) result = result.split(secret).join("<redacted>");
95
+ }
96
+ return result;
97
+ }
98
+
99
+ function bounded(message: string): string {
100
+ return message.length > 200 ? `${message.slice(0, 197)}...` : message;
101
+ }
102
+
103
+ function errorCode(error: unknown, fallback: string): string {
104
+ const code = (error as { code?: unknown })?.code;
105
+ return typeof code === "string" && code.trim() !== "" ? code.trim() : fallback;
106
+ }
107
+
108
+ function sessionContext(payload: WorkerStartPayload): WorkerFailureSessionContext {
109
+ return {
110
+ selectedTurnId: payload.processSnapshot.selectedTurnId ?? null,
111
+ lifecycleStatus: payload.processSnapshot.lifecycleStatus ?? "running",
112
+ snapshotSource: failureSnapshotSource(payload),
113
+ };
114
+ }
115
+
116
+ function failureSnapshotSource(payload: WorkerStartPayload) {
117
+ return {
118
+ kind: payload.bootstrap.kind,
119
+ treeFile: payload.treePaths.primaryTreeFile,
120
+ } as const;
121
+ }
122
+
123
+ /** Pure normalization boundary for every failure owned by the worker runtime. */
124
+ export function normalizeWorkerFailure(failure: WorkerFailure): WorkerFailureDisposition {
125
+ const session =
126
+ failure.kind === "bootstrap"
127
+ ? sessionContext(failure.payload)
128
+ : failure.kind === "dispatch" ||
129
+ failure.kind === "cleanup" ||
130
+ failure.kind === "turn" ||
131
+ failure.kind === "mandatory_snapshot"
132
+ ? (failure.session ?? null)
133
+ : null;
134
+ const secrets = extractSecretValuesFromPayload(
135
+ failure.kind === "bootstrap" ? failure.payload : null,
136
+ );
137
+ const classified = classifyRuntimeError(failure.error, "infrastructure");
138
+ const message = redactSecrets(classified.message, secrets);
139
+
140
+ if (failure.kind === "transport") {
141
+ return {
142
+ diagnostic: null,
143
+ stderrMessage: message,
144
+ terminal: { kind: "transport_lost" },
145
+ exitCode: 1,
146
+ };
147
+ }
148
+
149
+ if (failure.kind === "turn" || failure.kind === "mandatory_snapshot") {
150
+ const correlation = failure.correlation;
151
+ const turnError = failure.kind === "turn" ? failure.error : null;
152
+ const summary =
153
+ failure.kind === "mandatory_snapshot"
154
+ ? `Mandatory session snapshot upload failed before ${failure.point}: ${message}`
155
+ : redactSecrets(turnError?.message ?? message, secrets);
156
+ const errorClass =
157
+ failure.kind === "turn"
158
+ ? (turnError?.errorClass ?? classified.errorClass)
159
+ : classified.errorClass;
160
+ const payload: WorkerTurnFailedPayload = {
161
+ turnRecordId: correlation.turnRecordId,
162
+ turnId: correlation.turnId,
163
+ turnType: correlation.turnType ?? "llm",
164
+ pathType: correlation.pathType ?? "primary",
165
+ errorSummary: summary,
166
+ errorClass,
167
+ forkPiEntryId: correlation.forkPiEntryId ?? null,
168
+ resultPiEntryId: correlation.resultPiEntryId ?? null,
169
+ ...(turnError?.failureCode ? { failureCode: turnError.failureCode } : {}),
170
+ ...(failure.kind === "mandatory_snapshot"
171
+ ? { failureDetails: { reason: failure.point } }
172
+ : turnError?.failureDetails
173
+ ? { failureDetails: turnError.failureDetails }
174
+ : {}),
175
+ ...(turnError?.recoveryContext ? { recoveryContext: turnError.recoveryContext } : {}),
176
+ };
177
+ return {
178
+ diagnostic: {
179
+ level: "error",
180
+ code:
181
+ failure.kind === "mandatory_snapshot"
182
+ ? "session_snapshot.upload_failed"
183
+ : "turn.execution_failed",
184
+ message:
185
+ failure.kind === "mandatory_snapshot" ? summary : `Turn execution failed: ${summary}`,
186
+ errorClass,
187
+ turnRecordId: correlation.turnRecordId,
188
+ turnId: correlation.turnId,
189
+ },
190
+ stderrMessage: summary,
191
+ terminal: {
192
+ kind: "turn_failed",
193
+ payload,
194
+ park: {
195
+ selectedTurnId: session?.selectedTurnId ?? correlation.turnId,
196
+ reason: summary,
197
+ errorClass,
198
+ },
199
+ },
200
+ };
201
+ }
202
+
203
+ if (failure.kind === "bootstrap") {
204
+ const summary = `Worker bootstrap failed: ${message}`;
205
+ return {
206
+ diagnostic: {
207
+ level: "error",
208
+ code: "bootstrap.failed",
209
+ message: summary,
210
+ errorClass: "infrastructure",
211
+ },
212
+ stderrMessage: summary,
213
+ snapshot: { point: "before_worker_failed", source: failureSnapshotSource(failure.payload) },
214
+ terminal: {
215
+ kind: "worker_failed",
216
+ payload: {
217
+ state: "bootstrapping",
218
+ errorCode: errorCode(failure.error, "bootstrap_failed"),
219
+ message: bounded(summary),
220
+ errorClass: "infrastructure",
221
+ selectedTurnId: session?.selectedTurnId ?? null,
222
+ },
223
+ },
224
+ exitCode: 1,
225
+ };
226
+ }
227
+
228
+ if (failure.kind === "dispatch" && session && session.lifecycleStatus !== "error") {
229
+ return {
230
+ diagnostic: {
231
+ level: "error",
232
+ code: "runtime.dispatch_failed",
233
+ message: `Worker dispatch failed: ${message}`,
234
+ errorClass: classified.errorClass,
235
+ },
236
+ stderrMessage: message,
237
+ terminal: {
238
+ kind: "park",
239
+ payload: {
240
+ selectedTurnId: session.selectedTurnId,
241
+ reason: message,
242
+ errorClass: classified.errorClass,
243
+ },
244
+ },
245
+ };
246
+ }
247
+
248
+ const isCleanup = failure.kind === "cleanup";
249
+ const code = isCleanup ? "cleanup.failed" : "runtime.dispatch_failed";
250
+ const summary = `${isCleanup ? "Worker cleanup failed" : "Worker dispatch failed"}: ${message}`;
251
+ return {
252
+ diagnostic: { level: "error", code, message: summary, errorClass: classified.errorClass },
253
+ stderrMessage: summary,
254
+ ...(session
255
+ ? {
256
+ snapshot: {
257
+ point: "before_worker_failed" as const,
258
+ source: session.snapshotSource,
259
+ },
260
+ }
261
+ : {}),
262
+ terminal: {
263
+ kind: "worker_failed",
264
+ payload: {
265
+ state: isCleanup ? "cleanup" : failure.state,
266
+ errorCode: isCleanup ? "cleanup_failed" : "runtime_dispatch_failed",
267
+ message: bounded(message),
268
+ errorClass: classified.errorClass,
269
+ selectedTurnId: session?.selectedTurnId ?? null,
270
+ },
271
+ },
272
+ exitCode: 1,
273
+ };
274
+ }
@@ -0,0 +1,362 @@
1
+ import type { ServerToWorkerMessage } from "@leitwerk-dev/worker-protocol";
2
+ import { deliverBatch } from "../input-consumer.js";
3
+ import type { WorkerIpc } from "../ipc.js";
4
+ import { createPiEventReporter } from "../pi-event-reporter.js";
5
+ import { WorkerQuestionBridge } from "../question-bridge.js";
6
+ import { resolveRootEntryIdFromHandle } from "../turn-tree-strategy.js";
7
+ import { createWorkerIpcReporter } from "../worker-ipc-reporter.js";
8
+ import type { WorkerRuntimeOptions, WorkerRuntimeTimer } from "./adapters.js";
9
+ import { sampleCredentialFiles, WorkerLiveResources } from "./bootstrap-session.js";
10
+ import {
11
+ createInitialWorkerRuntimeState,
12
+ reduceWorkerRuntime,
13
+ type WorkerRuntimeCommand,
14
+ type WorkerRuntimeEvent,
15
+ type WorkerRuntimeOutput,
16
+ type WorkerRuntimeStateMachine,
17
+ type WorkerTimerName,
18
+ } from "./lifecycle-reducer.js";
19
+ import { resolveWorkerRuntimeSettings } from "./settings.js";
20
+ import { executeSelectedTurn } from "./turn-execution.js";
21
+
22
+ export {
23
+ nodeWorkerRuntimeScheduler,
24
+ type ResultImageToolFactory,
25
+ type WorkerRuntimeAdapters,
26
+ type WorkerRuntimeConfig,
27
+ type WorkerRuntimeOptions,
28
+ type WorkerRuntimeScheduler,
29
+ } from "./adapters.js";
30
+
31
+ export interface WorkerRuntime {
32
+ start(): Promise<void>;
33
+ stop(reason: string): Promise<void>;
34
+ }
35
+
36
+ /** One non-reentrant driver around the pure runtime reducer. */
37
+ export function createWorkerRuntime(options: WorkerRuntimeOptions): WorkerRuntime {
38
+ const { config, adapters } = options;
39
+ const ipc: WorkerIpc = adapters.transport;
40
+ const queue: WorkerRuntimeEvent[] = [];
41
+ const timers = new Map<WorkerTimerName, WorkerRuntimeTimer>();
42
+ let state: WorkerRuntimeStateMachine = createInitialWorkerRuntimeState();
43
+ let draining = false;
44
+ let started = false;
45
+ let invariantQueued = false;
46
+ let resolveClosed!: () => void;
47
+ const closed = new Promise<void>((resolve) => {
48
+ resolveClosed = resolve;
49
+ });
50
+
51
+ const reporter = createWorkerIpcReporter({
52
+ instanceId: config.instanceId,
53
+ workerId: config.workerId,
54
+ now: () => adapters.scheduler.now(),
55
+ send: (message) => ipc.send(message),
56
+ emitExtensionEvent: (event, payload) => adapters.extensionEvents?.emit(event, payload),
57
+ });
58
+ const questionBridge = new WorkerQuestionBridge(reporter);
59
+
60
+ let dispatch: (event: WorkerRuntimeEvent) => void;
61
+ const piEvents = createPiEventReporter({
62
+ reporter,
63
+ emitExtensionEvent: (event, payload) => adapters.extensionEvents?.emit(event, payload),
64
+ getCurrentSelectedTurnId: () => state.session?.selectedTurnId ?? null,
65
+ getSessionTainted: () => state.sessionTainted,
66
+ onLifecycleObservation(kind) {
67
+ dispatch({ kind });
68
+ },
69
+ });
70
+ const resources = new WorkerLiveResources({
71
+ instanceId: config.instanceId,
72
+ piFactory: adapters.piFactory,
73
+ gitOps: adapters.gitOps,
74
+ scheduler: adapters.scheduler,
75
+ sessionSnapshots: adapters.sessionSnapshots,
76
+ resolveWorkerProcess: adapters.resolveWorkerProcess,
77
+ progress(payload) {
78
+ reporter.workerTrace(payload, state.session?.selectedTurnId ?? null);
79
+ },
80
+ });
81
+
82
+ const invariant = (error: unknown): void => {
83
+ if (invariantQueued || state.phase.kind === "exited") return;
84
+ invariantQueued = true;
85
+ queue.push({ kind: "invariant_failed", error });
86
+ if (!draining) drain();
87
+ };
88
+
89
+ const complete = (event: WorkerRuntimeEvent): void => dispatch(event);
90
+ const launch = (command: WorkerRuntimeCommand): void => {
91
+ switch (command.kind) {
92
+ case "arm_timer": {
93
+ const existing = timers.get(command.name);
94
+ if (existing) adapters.scheduler.clearTimeout(existing);
95
+ const handle = adapters.scheduler.setTimeout(() => {
96
+ timers.delete(command.name);
97
+ complete({ kind: "timer_fired", name: command.name, correlation: command.correlation });
98
+ }, command.delayMs);
99
+ timers.set(command.name, handle);
100
+ return;
101
+ }
102
+ case "cancel_timer": {
103
+ const timer = timers.get(command.name);
104
+ if (timer) adapters.scheduler.clearTimeout(timer);
105
+ timers.delete(command.name);
106
+ return;
107
+ }
108
+ case "close_transport":
109
+ for (const timer of timers.values()) adapters.scheduler.clearTimeout(timer);
110
+ timers.clear();
111
+ ipc.stop();
112
+ resolveClosed();
113
+ return;
114
+ case "exit":
115
+ adapters.exit(command.code);
116
+ return;
117
+ case "bootstrap":
118
+ void resources
119
+ .bootstrap(command.payload, resolveWorkerRuntimeSettings(config, command.payload))
120
+ .then((completion) =>
121
+ complete({
122
+ kind: "bootstrap_succeeded",
123
+ startRecordId: command.startRecordId,
124
+ completion,
125
+ }),
126
+ )
127
+ .catch((error) =>
128
+ complete({
129
+ kind: "bootstrap_failed",
130
+ startRecordId: command.startRecordId,
131
+ error,
132
+ payload: command.payload,
133
+ }),
134
+ );
135
+ return;
136
+ case "activate":
137
+ void resources
138
+ .activate(command.startRecordId, command.turnRecordId, command.session)
139
+ .then((result) => {
140
+ if (resources.piHandle) piEvents.attach(resources.piHandle);
141
+ complete({
142
+ kind: "activation_succeeded",
143
+ startRecordId: command.startRecordId,
144
+ turnRecordId: command.turnRecordId,
145
+ ...result,
146
+ });
147
+ })
148
+ .catch((error) =>
149
+ complete({
150
+ kind: "activation_failed",
151
+ startRecordId: command.startRecordId,
152
+ turnRecordId: command.turnRecordId,
153
+ error,
154
+ }),
155
+ );
156
+ return;
157
+ case "deliver_inputs": {
158
+ const handle = resources.piHandle;
159
+ if (!handle) {
160
+ complete({
161
+ kind: "input_delivery_failed",
162
+ headSequence: command.headSequence,
163
+ error: new Error("Input delivery requires an active Pi handle"),
164
+ });
165
+ return;
166
+ }
167
+ void deliverBatch(handle, [...command.inputs], command.piTurnActive)
168
+ .then((delivered) => {
169
+ const prompted = delivered.some((item) => item.deliveryMode === "prompt");
170
+ complete({
171
+ kind: "inputs_delivered",
172
+ headSequence: command.headSequence,
173
+ delivered,
174
+ ...(prompted
175
+ ? {
176
+ meta: {
177
+ currentPrimaryPathLeafId: handle.getLeafId(),
178
+ rootEntryId: resolveRootEntryIdFromHandle(handle),
179
+ },
180
+ }
181
+ : {}),
182
+ });
183
+ })
184
+ .catch((error) =>
185
+ complete({ kind: "input_delivery_failed", headSequence: command.headSequence, error }),
186
+ );
187
+ return;
188
+ }
189
+ case "execute_turn":
190
+ void resources
191
+ .runTurn((signal) =>
192
+ executeSelectedTurn({
193
+ session: command.session,
194
+ requestQuestions: (request) => questionBridge.request(request),
195
+ piHandle: resources.piHandle,
196
+ turnRecordId: command.turnRecordId,
197
+ targetedInputs: command.targetedInputs,
198
+ scheduler: adapters.scheduler,
199
+ resultImageTools: adapters.resultImageTools,
200
+ signal,
201
+ emit(emission) {
202
+ if (emission.kind === "session_tainted") {
203
+ complete({ kind: "session_tainted", reason: emission.reason });
204
+ } else if (emission.kind === "trace") {
205
+ reporter.workerTrace(emission.payload, command.session.selectedTurnId);
206
+ } else reporter.workerError(emission.payload, command.session.selectedTurnId);
207
+ },
208
+ }),
209
+ )
210
+ .then((result) =>
211
+ complete({ kind: "turn_completed", turnRecordId: command.turnRecordId, result }),
212
+ )
213
+ .catch((error) =>
214
+ complete({ kind: "turn_defect", turnRecordId: command.turnRecordId, error }),
215
+ );
216
+ return;
217
+ case "upload_snapshot":
218
+ void resources
219
+ .uploadSnapshot(command.source, command.point, {
220
+ turnRecordId: command.turnRecordId,
221
+ required: command.required,
222
+ })
223
+ .then(() =>
224
+ complete({
225
+ kind: "snapshot_succeeded",
226
+ point: command.point,
227
+ turnRecordId: command.turnRecordId,
228
+ }),
229
+ )
230
+ .catch((error) =>
231
+ complete({
232
+ kind: "snapshot_failed",
233
+ point: command.point,
234
+ turnRecordId: command.turnRecordId,
235
+ error,
236
+ }),
237
+ );
238
+ return;
239
+ case "sample_credentials":
240
+ void sampleCredentialFiles(command.descriptor)
241
+ .then((sample) =>
242
+ complete({
243
+ kind: "credential_sampled",
244
+ providerId: command.descriptor.providerId,
245
+ ...sample,
246
+ }),
247
+ )
248
+ .catch((error) =>
249
+ complete({
250
+ kind: "credential_sample_failed",
251
+ providerId: command.descriptor.providerId,
252
+ error,
253
+ }),
254
+ );
255
+ return;
256
+ case "cleanup":
257
+ void resources
258
+ .cleanup()
259
+ .then(() => complete({ kind: "cleanup_succeeded" }))
260
+ .catch((error) => complete({ kind: "cleanup_failed", error }));
261
+ }
262
+ };
263
+
264
+ const processOutput = (output: WorkerRuntimeOutput): void => {
265
+ if (output.kind === "protocol") {
266
+ reporter.project(output);
267
+ return;
268
+ }
269
+ if (output.kind === "extension") {
270
+ const payload =
271
+ output.event === "worker.handle_ready"
272
+ ? {
273
+ instanceId: config.instanceId,
274
+ workerId: config.workerId,
275
+ ...(output.payload as object),
276
+ }
277
+ : output.payload;
278
+ adapters.extensionEvents?.emit(output.event, payload);
279
+ return;
280
+ }
281
+ if (output.kind === "diagnostic") {
282
+ reporter.workerTrace(output.payload, state.session?.selectedTurnId ?? null);
283
+ if (output.stderr) adapters.stderr?.write(`${output.stderr}\n`);
284
+ return;
285
+ }
286
+ if (output.kind === "stderr") {
287
+ adapters.stderr?.write(`${output.message}\n`);
288
+ return;
289
+ }
290
+ launch(output);
291
+ };
292
+
293
+ function drain(): void {
294
+ if (draining) return;
295
+ draining = true;
296
+ try {
297
+ while (queue.length > 0) {
298
+ const event = queue.shift();
299
+ if (!event) continue;
300
+ if (event.kind === "invariant_failed") invariantQueued = false;
301
+ let reduction: ReturnType<typeof reduceWorkerRuntime>;
302
+ try {
303
+ reduction = reduceWorkerRuntime(state, event);
304
+ } catch (error) {
305
+ invariant(error);
306
+ continue;
307
+ }
308
+ state = reduction.state;
309
+ for (const output of reduction.outputs) {
310
+ try {
311
+ processOutput(output);
312
+ } catch (error) {
313
+ invariant(error);
314
+ break;
315
+ }
316
+ }
317
+ }
318
+ } finally {
319
+ draining = false;
320
+ if (queue.length > 0) drain();
321
+ }
322
+ }
323
+
324
+ dispatch = (event) => {
325
+ queue.push(event);
326
+ drain();
327
+ };
328
+
329
+ const receive = (message: ServerToWorkerMessage): void => {
330
+ if (message.type === "worker.question_response") {
331
+ questionBridge.handle(message);
332
+ return;
333
+ }
334
+ if (message.type === "worker.abort_turn") {
335
+ if (!resources.abortActiveTurn()) void resources.abortTurn();
336
+ dispatch({ kind: "operator_abort_observed" });
337
+ return;
338
+ }
339
+ dispatch({ kind: "server_message", message });
340
+ };
341
+
342
+ return {
343
+ async start() {
344
+ if (started) throw new Error("Worker runtime already started");
345
+ started = true;
346
+ ipc.onMessage(receive);
347
+ ipc.onError((error) => dispatch({ kind: "transport_failed", error }));
348
+ ipc.onConnect?.(() => {
349
+ dispatch({ kind: "transport_connected" });
350
+ questionBridge.replay();
351
+ });
352
+ ipc.start();
353
+ dispatch({ kind: "runtime_started" });
354
+ },
355
+ async stop(reason: string) {
356
+ if (state.phase.kind === "exited") return;
357
+ questionBridge.cancelAll(`Question request cancelled: ${reason}`);
358
+ dispatch({ kind: "stop_requested", reason, exitAfterCleanup: false });
359
+ await closed;
360
+ },
361
+ };
362
+ }