@leitwerk-dev/worker 0.1.9 → 0.2.1

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 (240) hide show
  1. package/dist/automatic-turn-executor.d.ts +1 -0
  2. package/dist/automatic-turn-executor.d.ts.map +1 -1
  3. package/dist/{chunk-O6332GRG.js → chunk-2LLFMCR6.js} +1511 -1071
  4. package/dist/chunk-2LLFMCR6.js.map +1 -0
  5. package/dist/connection-diagnostics.d.ts +5 -0
  6. package/dist/connection-diagnostics.d.ts.map +1 -0
  7. package/dist/container-entry-main.d.ts +2 -0
  8. package/dist/container-entry-main.d.ts.map +1 -0
  9. package/dist/container-entry-main.js +232 -0
  10. package/dist/container-entry-main.js.map +1 -0
  11. package/dist/container-entry.d.ts +14 -0
  12. package/dist/container-entry.d.ts.map +1 -0
  13. package/dist/development-tool-environment.d.ts +84 -0
  14. package/dist/development-tool-environment.d.ts.map +1 -0
  15. package/dist/diagnostics.d.ts +4 -0
  16. package/dist/diagnostics.d.ts.map +1 -1
  17. package/dist/docker-registry-credentials.d.ts +8 -0
  18. package/dist/docker-registry-credentials.d.ts.map +1 -0
  19. package/dist/entry-runtime.d.ts +19 -0
  20. package/dist/entry-runtime.d.ts.map +1 -1
  21. package/dist/index.d.ts +3 -5
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +10 -5
  24. package/dist/index.js.map +1 -1
  25. package/dist/input-consumer.d.ts +7 -11
  26. package/dist/input-consumer.d.ts.map +1 -1
  27. package/dist/ipc.d.ts +10 -0
  28. package/dist/ipc.d.ts.map +1 -1
  29. package/dist/logical-prompt-runner.d.ts.map +1 -1
  30. package/dist/managed-pi-agent-dir.d.ts +8 -1
  31. package/dist/managed-pi-agent-dir.d.ts.map +1 -1
  32. package/dist/managed-pi-bootstrap.d.ts +1 -0
  33. package/dist/managed-pi-bootstrap.d.ts.map +1 -1
  34. package/dist/missing-tool-recovery-runner.d.ts +4 -3
  35. package/dist/missing-tool-recovery-runner.d.ts.map +1 -1
  36. package/dist/pi-adapter.d.ts +88 -1
  37. package/dist/pi-adapter.d.ts.map +1 -1
  38. package/dist/pi-event-reporter.d.ts.map +1 -1
  39. package/dist/pi-resource-bundle.d.ts +17 -1
  40. package/dist/pi-resource-bundle.d.ts.map +1 -1
  41. package/dist/pre-turn-targeted-inputs.d.ts +8 -7
  42. package/dist/pre-turn-targeted-inputs.d.ts.map +1 -1
  43. package/dist/prompt-guards.d.ts +6 -0
  44. package/dist/prompt-guards.d.ts.map +1 -1
  45. package/dist/repository-bash-tool.d.ts +4 -0
  46. package/dist/repository-bash-tool.d.ts.map +1 -0
  47. package/dist/resource-loader-factory.d.ts +1 -2
  48. package/dist/resource-loader-factory.d.ts.map +1 -1
  49. package/dist/result-image-upload.d.ts.map +1 -1
  50. package/dist/runtime/adapters.d.ts +38 -0
  51. package/dist/runtime/adapters.d.ts.map +1 -1
  52. package/dist/runtime/bootstrap-session.d.ts +9 -5
  53. package/dist/runtime/bootstrap-session.d.ts.map +1 -1
  54. package/dist/runtime/bootstrap.d.ts +38 -18
  55. package/dist/runtime/bootstrap.d.ts.map +1 -1
  56. package/dist/runtime/failure-policy.d.ts +1 -0
  57. package/dist/runtime/failure-policy.d.ts.map +1 -1
  58. package/dist/runtime/index.d.ts +4 -1
  59. package/dist/runtime/index.d.ts.map +1 -1
  60. package/dist/runtime/lifecycle-reducer.d.ts.map +1 -1
  61. package/dist/runtime/llm-turn-execution.d.ts +3 -8
  62. package/dist/runtime/llm-turn-execution.d.ts.map +1 -1
  63. package/dist/runtime/turn-execution.d.ts +2 -9
  64. package/dist/runtime/turn-execution.d.ts.map +1 -1
  65. package/dist/session-snapshot-exchange.d.ts +10 -4
  66. package/dist/session-snapshot-exchange.d.ts.map +1 -1
  67. package/dist/turn-continuation.d.ts.map +1 -1
  68. package/dist/turn-execution-error.d.ts +1 -1
  69. package/dist/turn-execution-error.d.ts.map +1 -1
  70. package/dist/turn-execution-result.d.ts +1 -0
  71. package/dist/turn-execution-result.d.ts.map +1 -1
  72. package/dist/turn-outcome-tool-session.d.ts +0 -2
  73. package/dist/turn-outcome-tool-session.d.ts.map +1 -1
  74. package/dist/turn-result-markdown.d.ts +2 -1
  75. package/dist/turn-result-markdown.d.ts.map +1 -1
  76. package/dist/turn-tree-strategy.d.ts +0 -1
  77. package/dist/turn-tree-strategy.d.ts.map +1 -1
  78. package/dist/worker-entry.js +16 -4
  79. package/dist/worker-entry.js.map +1 -1
  80. package/dist/worker-ipc-reporter.d.ts.map +1 -1
  81. package/dist/workspace/manifest.d.ts +4 -7
  82. package/dist/workspace/manifest.d.ts.map +1 -1
  83. package/dist/workspace/node-run-root-git-ops.d.ts +2 -2
  84. package/dist/workspace/node-run-root-git-ops.d.ts.map +1 -1
  85. package/dist/workspace/resource-aggregator.d.ts.map +1 -1
  86. package/dist/workspace/run-root.d.ts +21 -20
  87. package/dist/workspace/run-root.d.ts.map +1 -1
  88. package/package.json +8 -8
  89. package/src/automatic-turn-executor.ts +2 -0
  90. package/src/connection-diagnostics.ts +27 -0
  91. package/src/container-entry-main.ts +24 -0
  92. package/src/container-entry.ts +246 -0
  93. package/src/development-tool-environment.ts +490 -0
  94. package/src/diagnostics.ts +1 -0
  95. package/src/docker-registry-credentials.ts +65 -0
  96. package/src/entry-runtime.ts +29 -5
  97. package/src/index.ts +1 -39
  98. package/src/input-consumer.ts +8 -29
  99. package/src/ipc.ts +50 -2
  100. package/src/logical-prompt-runner.ts +23 -29
  101. package/src/managed-pi-agent-dir.ts +8 -1
  102. package/src/managed-pi-bootstrap.ts +4 -3
  103. package/src/missing-tool-recovery-runner.ts +4 -18
  104. package/src/pi-adapter.ts +125 -56
  105. package/src/pi-event-reporter.ts +16 -38
  106. package/src/pi-resource-bundle.ts +77 -3
  107. package/src/pre-turn-targeted-inputs.ts +9 -11
  108. package/src/prompt-guards.ts +50 -75
  109. package/src/repository-bash-tool.ts +15 -0
  110. package/src/resource-loader-factory.ts +1 -18
  111. package/src/result-image-upload.ts +16 -27
  112. package/src/runtime/adapters.ts +46 -4
  113. package/src/runtime/bootstrap-session.ts +70 -39
  114. package/src/runtime/bootstrap.ts +184 -101
  115. package/src/runtime/failure-policy.ts +36 -42
  116. package/src/runtime/index.ts +47 -15
  117. package/src/runtime/lifecycle-reducer.ts +71 -173
  118. package/src/runtime/llm-turn-execution.ts +13 -30
  119. package/src/runtime/turn-execution.ts +78 -31
  120. package/src/session-snapshot-exchange.ts +46 -68
  121. package/src/turn-continuation.ts +9 -17
  122. package/src/turn-execution-error.ts +3 -11
  123. package/src/turn-execution-result.ts +1 -0
  124. package/src/turn-outcome-tool-session.ts +25 -21
  125. package/src/turn-result-markdown.ts +31 -34
  126. package/src/turn-tree-strategy.ts +6 -19
  127. package/src/worker-entry.ts +8 -0
  128. package/src/worker-ipc-reporter.ts +8 -16
  129. package/src/workspace/manifest.ts +5 -7
  130. package/src/workspace/node-run-root-git-ops.ts +65 -25
  131. package/src/workspace/resource-aggregator.ts +5 -16
  132. package/src/workspace/run-root.ts +50 -89
  133. package/dist/automatic-turn-executor.js +0 -58
  134. package/dist/automatic-turn-executor.js.map +0 -1
  135. package/dist/chunk-O6332GRG.js.map +0 -1
  136. package/dist/diagnostics.js +0 -51
  137. package/dist/diagnostics.js.map +0 -1
  138. package/dist/entry-runtime.js +0 -160
  139. package/dist/entry-runtime.js.map +0 -1
  140. package/dist/event-translator.js +0 -12
  141. package/dist/event-translator.js.map +0 -1
  142. package/dist/extension-entry-roots.js +0 -41
  143. package/dist/extension-entry-roots.js.map +0 -1
  144. package/dist/identified-pi-entry.js +0 -125
  145. package/dist/identified-pi-entry.js.map +0 -1
  146. package/dist/input-consumer.js +0 -34
  147. package/dist/input-consumer.js.map +0 -1
  148. package/dist/integration-tool-bridge.js +0 -53
  149. package/dist/integration-tool-bridge.js.map +0 -1
  150. package/dist/ipc.js +0 -192
  151. package/dist/ipc.js.map +0 -1
  152. package/dist/logical-prompt-runner.js +0 -225
  153. package/dist/logical-prompt-runner.js.map +0 -1
  154. package/dist/managed-pi-agent-dir.js +0 -66
  155. package/dist/managed-pi-agent-dir.js.map +0 -1
  156. package/dist/managed-pi-bootstrap.js +0 -135
  157. package/dist/managed-pi-bootstrap.js.map +0 -1
  158. package/dist/missing-tool-recovery-runner.js +0 -73
  159. package/dist/missing-tool-recovery-runner.js.map +0 -1
  160. package/dist/pi-adapter.js +0 -1648
  161. package/dist/pi-adapter.js.map +0 -1
  162. package/dist/pi-branch-guard.js +0 -75
  163. package/dist/pi-branch-guard.js.map +0 -1
  164. package/dist/pi-event-reporter.js +0 -136
  165. package/dist/pi-event-reporter.js.map +0 -1
  166. package/dist/pi-resource-bundle.js +0 -58
  167. package/dist/pi-resource-bundle.js.map +0 -1
  168. package/dist/pre-turn-targeted-inputs.js +0 -101
  169. package/dist/pre-turn-targeted-inputs.js.map +0 -1
  170. package/dist/prompt-guards.js +0 -318
  171. package/dist/prompt-guards.js.map +0 -1
  172. package/dist/question-bridge.js +0 -24
  173. package/dist/question-bridge.js.map +0 -1
  174. package/dist/question-tool.js +0 -54
  175. package/dist/question-tool.js.map +0 -1
  176. package/dist/replaying-request-bridge.js +0 -71
  177. package/dist/replaying-request-bridge.js.map +0 -1
  178. package/dist/resource-loader-factory.js +0 -87
  179. package/dist/resource-loader-factory.js.map +0 -1
  180. package/dist/result-image-upload.js +0 -183
  181. package/dist/result-image-upload.js.map +0 -1
  182. package/dist/runtime/adapters.js +0 -15
  183. package/dist/runtime/adapters.js.map +0 -1
  184. package/dist/runtime/bootstrap-session.js +0 -199
  185. package/dist/runtime/bootstrap-session.js.map +0 -1
  186. package/dist/runtime/bootstrap.js +0 -440
  187. package/dist/runtime/bootstrap.js.map +0 -1
  188. package/dist/runtime/failure-policy.js +0 -182
  189. package/dist/runtime/failure-policy.js.map +0 -1
  190. package/dist/runtime/index.js +0 -339
  191. package/dist/runtime/index.js.map +0 -1
  192. package/dist/runtime/lifecycle-reducer.js +0 -1142
  193. package/dist/runtime/lifecycle-reducer.js.map +0 -1
  194. package/dist/runtime/llm-turn-execution.js +0 -494
  195. package/dist/runtime/llm-turn-execution.js.map +0 -1
  196. package/dist/runtime/settings.js +0 -24
  197. package/dist/runtime/settings.js.map +0 -1
  198. package/dist/runtime/snapshot-policy.js +0 -16
  199. package/dist/runtime/snapshot-policy.js.map +0 -1
  200. package/dist/runtime/turn-execution.js +0 -151
  201. package/dist/runtime/turn-execution.js.map +0 -1
  202. package/dist/session-snapshot-exchange.js +0 -102
  203. package/dist/session-snapshot-exchange.js.map +0 -1
  204. package/dist/test-helpers/fake-websocket.js +0 -40
  205. package/dist/test-helpers/fake-websocket.js.map +0 -1
  206. package/dist/test-helpers/ipc-harness.d.ts +0 -11
  207. package/dist/test-helpers/ipc-harness.d.ts.map +0 -1
  208. package/dist/test-helpers/ipc-harness.js +0 -17
  209. package/dist/test-helpers/ipc-harness.js.map +0 -1
  210. package/dist/turn-continuation.js +0 -80
  211. package/dist/turn-continuation.js.map +0 -1
  212. package/dist/turn-execution-error.js +0 -64
  213. package/dist/turn-execution-error.js.map +0 -1
  214. package/dist/turn-execution-result.js +0 -21
  215. package/dist/turn-execution-result.js.map +0 -1
  216. package/dist/turn-outcome-tool-session.js +0 -210
  217. package/dist/turn-outcome-tool-session.js.map +0 -1
  218. package/dist/turn-record-id.js +0 -10
  219. package/dist/turn-record-id.js.map +0 -1
  220. package/dist/turn-result-markdown.js +0 -263
  221. package/dist/turn-result-markdown.js.map +0 -1
  222. package/dist/turn-tree-strategy.js +0 -80
  223. package/dist/turn-tree-strategy.js.map +0 -1
  224. package/dist/worker-http.js +0 -9
  225. package/dist/worker-http.js.map +0 -1
  226. package/dist/worker-ipc-reporter.js +0 -58
  227. package/dist/worker-ipc-reporter.js.map +0 -1
  228. package/dist/worker-payloads.js +0 -66
  229. package/dist/worker-payloads.js.map +0 -1
  230. package/dist/worker-start-payload.js +0 -5
  231. package/dist/worker-start-payload.js.map +0 -1
  232. package/dist/workspace/manifest.js +0 -79
  233. package/dist/workspace/manifest.js.map +0 -1
  234. package/dist/workspace/node-run-root-git-ops.js +0 -96
  235. package/dist/workspace/node-run-root-git-ops.js.map +0 -1
  236. package/dist/workspace/resource-aggregator.js +0 -39
  237. package/dist/workspace/resource-aggregator.js.map +0 -1
  238. package/dist/workspace/run-root.js +0 -209
  239. package/dist/workspace/run-root.js.map +0 -1
  240. package/src/test-helpers/ipc-harness.ts +0 -19
@@ -1,4 +1,5 @@
1
1
  import type { ServerToWorkerMessage } from "@leitwerk-dev/worker-protocol";
2
+ import { MiseDevelopmentToolEnvironment } from "../development-tool-environment.js";
2
3
  import { deliverBatch } from "../input-consumer.js";
3
4
  import { WorkerIntegrationToolBridge } from "../integration-tool-bridge.js";
4
5
  import type { WorkerIpc } from "../ipc.js";
@@ -8,6 +9,7 @@ import { resolveRootEntryIdFromHandle } from "../turn-tree-strategy.js";
8
9
  import { createWorkerIpcReporter } from "../worker-ipc-reporter.js";
9
10
  import type { WorkerRuntimeOptions, WorkerRuntimeTimer } from "./adapters.js";
10
11
  import { sampleCredentialFiles, WorkerLiveResources } from "./bootstrap-session.js";
12
+ import { extractDockerRegistrySecretValues, redactSecrets } from "./failure-policy.js";
11
13
  import {
12
14
  createInitialWorkerRuntimeState,
13
15
  reduceWorkerRuntime,
@@ -29,33 +31,52 @@ export {
29
31
  type WorkerRuntimeScheduler,
30
32
  } from "./adapters.js";
31
33
 
34
+ /** @internal */
32
35
  export interface WorkerRuntime {
36
+ /** @internal */
33
37
  start(): Promise<void>;
38
+ /** @internal */
34
39
  stop(reason: string): Promise<void>;
35
40
  }
36
41
 
37
- /** One non-reentrant driver around the pure runtime reducer. */
42
+ /** One non-reentrant driver around the pure runtime reducer. @internal */
38
43
  export function createWorkerRuntime(options: WorkerRuntimeOptions): WorkerRuntime {
39
44
  const { config, adapters } = options;
40
45
  const sampleCredentials = adapters.sampleCredentials ?? sampleCredentialFiles;
41
46
  const ipc: WorkerIpc = adapters.transport;
47
+ const deliveredSecrets = new Set<string>();
48
+ const redact = (text: string) =>
49
+ redactSecrets(
50
+ text,
51
+ [...deliveredSecrets].sort((a, b) => b.length - a.length),
52
+ );
53
+ function redactValue<T>(value: T): T {
54
+ if (deliveredSecrets.size === 0) return value;
55
+ if (typeof value === "string") return redact(value) as T;
56
+ if (Array.isArray(value)) return value.map(redactValue) as T;
57
+ if (value && typeof value === "object")
58
+ return Object.fromEntries(
59
+ Object.entries(value).map(([key, item]) => [key, redactValue(item)]),
60
+ ) as T;
61
+ return value;
62
+ }
63
+ const emitExtensionEvent = (event: string, payload: unknown) =>
64
+ adapters.extensionEvents?.emit(event, redactValue(payload));
65
+ const writeStderr = (text: string) => adapters.stderr?.write(`${redact(text)}\n`);
42
66
  const queue: WorkerRuntimeEvent[] = [];
43
67
  const timers = new Map<WorkerTimerName, WorkerRuntimeTimer>();
44
68
  let state: WorkerRuntimeStateMachine = createInitialWorkerRuntimeState();
45
69
  let draining = false;
46
70
  let started = false;
47
71
  let invariantQueued = false;
48
- let resolveClosed!: () => void;
49
- const closed = new Promise<void>((resolve) => {
50
- resolveClosed = resolve;
51
- });
72
+ const { promise: closed, resolve: resolveClosed } = Promise.withResolvers<void>();
52
73
 
53
74
  const reporter = createWorkerIpcReporter({
54
75
  instanceId: config.instanceId,
55
76
  workerId: config.workerId,
56
77
  now: () => adapters.scheduler.now(),
57
- send: (message) => ipc.send(message),
58
- emitExtensionEvent: (event, payload) => adapters.extensionEvents?.emit(event, payload),
78
+ send: (message) => ipc.send(redactValue(message)),
79
+ emitExtensionEvent,
59
80
  });
60
81
  const questionBridge = new WorkerQuestionBridge(reporter);
61
82
  const integrationToolBridge = new WorkerIntegrationToolBridge(reporter);
@@ -63,7 +84,7 @@ export function createWorkerRuntime(options: WorkerRuntimeOptions): WorkerRuntim
63
84
  let dispatch: (event: WorkerRuntimeEvent) => void;
64
85
  const piEvents = createPiEventReporter({
65
86
  reporter,
66
- emitExtensionEvent: (event, payload) => adapters.extensionEvents?.emit(event, payload),
87
+ emitExtensionEvent,
67
88
  getCurrentSelectedTurnId: () => state.session?.selectedTurnId ?? null,
68
89
  getSessionTainted: () => state.sessionTainted,
69
90
  onLifecycleObservation(kind) {
@@ -74,12 +95,16 @@ export function createWorkerRuntime(options: WorkerRuntimeOptions): WorkerRuntim
74
95
  instanceId: config.instanceId,
75
96
  piFactory: adapters.piFactory,
76
97
  gitOps: adapters.gitOps,
98
+ developmentTools: adapters.developmentTools ?? new MiseDevelopmentToolEnvironment(),
77
99
  scheduler: adapters.scheduler,
78
100
  sessionSnapshots: adapters.sessionSnapshots,
79
101
  resolveWorkerProcess: adapters.resolveWorkerProcess,
80
102
  progress(payload) {
81
103
  reporter.workerTrace(payload, state.session?.selectedTurnId ?? null);
82
104
  },
105
+ diagnosticTrace(text) {
106
+ reporter.project({ kind: "protocol", type: "worker.diagnostic_trace", payload: { text } });
107
+ },
83
108
  });
84
109
 
85
110
  const invariant = (error: unknown): void => {
@@ -216,6 +241,12 @@ export function createWorkerRuntime(options: WorkerRuntimeOptions): WorkerRuntim
216
241
  { turnRecordId: emission.turnRecordId, report: emission.report },
217
242
  command.session.selectedTurnId,
218
243
  );
244
+ } else if (emission.kind === "prepared") {
245
+ reporter.workerEvent(
246
+ "turn.prepared",
247
+ { turnRecordId: emission.turnRecordId, data: emission.data },
248
+ command.session.selectedTurnId,
249
+ );
219
250
  } else reporter.workerError(emission.payload, command.session.selectedTurnId);
220
251
  },
221
252
  }),
@@ -288,19 +319,16 @@ export function createWorkerRuntime(options: WorkerRuntimeOptions): WorkerRuntim
288
319
  ...(output.payload as object),
289
320
  }
290
321
  : output.payload;
291
- adapters.extensionEvents?.emit(output.event, payload);
322
+ emitExtensionEvent(output.event, payload);
292
323
  return;
293
324
  }
294
325
  if (output.kind === "diagnostic") {
295
326
  reporter.workerTrace(output.payload, state.session?.selectedTurnId ?? null);
296
- if (output.stderr) adapters.stderr?.write(`${output.stderr}\n`);
297
- return;
298
- }
299
- if (output.kind === "stderr") {
300
- adapters.stderr?.write(`${output.message}\n`);
327
+ if (output.stderr) writeStderr(output.stderr);
301
328
  return;
302
329
  }
303
- launch(output);
330
+ if (output.kind === "stderr") writeStderr(output.message);
331
+ else launch(output);
304
332
  };
305
333
 
306
334
  function drain(): void {
@@ -340,6 +368,9 @@ export function createWorkerRuntime(options: WorkerRuntimeOptions): WorkerRuntim
340
368
  };
341
369
 
342
370
  const receive = (message: ServerToWorkerMessage): void => {
371
+ if (message.type === "worker.start")
372
+ for (const secret of extractDockerRegistrySecretValues(message.payload))
373
+ deliveredSecrets.add(secret);
343
374
  if (message.type === "worker.integration_tool_result") {
344
375
  integrationToolBridge.handle(message);
345
376
  return;
@@ -353,6 +384,7 @@ export function createWorkerRuntime(options: WorkerRuntimeOptions): WorkerRuntim
353
384
  dispatch({ kind: "operator_abort_observed" });
354
385
  return;
355
386
  }
387
+ if (message.type === "worker.stop") resources.abortToolPreparation();
356
388
  dispatch({ kind: "server_message", message });
357
389
  };
358
390
 
@@ -415,46 +415,15 @@ function hasActivePublication(state: WorkerRuntimeStateMachine): boolean {
415
415
  return state.work.publication.kind !== "none";
416
416
  }
417
417
 
418
- function requireNoPublication(state: WorkerRuntimeStateMachine): void {
419
- if (hasActivePublication(state)) throw new Error("Snapshot publication is already active");
420
- }
421
-
422
- function beginReadySnapshot(
423
- state: WorkerRuntimeStateMachine,
424
- source: WorkerSnapshotSource,
425
- outputs: WorkerRuntimeOutput[],
426
- ): WorkerRuntimeStateMachine {
427
- requireNoPublication(state);
428
- const snapshot = {
429
- point: "after_worker_ready" as const,
430
- turnRecordId: null,
431
- required: false as const,
432
- };
433
- outputs.push({ kind: "upload_snapshot", ...snapshot, source });
434
- return {
435
- ...state,
436
- work: { ...state.work, publication: { kind: "ready_snapshot", snapshot } },
437
- };
438
- }
439
-
440
- function beginTerminalSnapshot(
418
+ function beginSnapshot(
441
419
  state: WorkerRuntimeStateMachine,
442
- point: "before_turn_outcome" | "before_turn_failed",
443
- turnRecordId: string,
444
- terminal: PendingTerminal,
420
+ publication: Extract<PublicationState, { snapshot: SnapshotCompletionEvent }>,
445
421
  source: WorkerSnapshotSource,
446
422
  outputs: WorkerRuntimeOutput[],
447
423
  ): WorkerRuntimeStateMachine {
448
- requireNoPublication(state);
449
- const snapshot = { point, turnRecordId, required: true as const };
450
- outputs.push({ kind: "upload_snapshot", ...snapshot, source });
451
- return {
452
- ...state,
453
- work: {
454
- ...state.work,
455
- publication: { kind: "terminal_snapshot", snapshot, terminal },
456
- },
457
- };
424
+ if (hasActivePublication(state)) throw new Error("Snapshot publication is already active");
425
+ outputs.push({ kind: "upload_snapshot", ...publication.snapshot, source });
426
+ return { ...state, work: { ...state.work, publication } };
458
427
  }
459
428
 
460
429
  const TERMINAL_ACK_RETRY_MS = 5_000;
@@ -481,47 +450,6 @@ function publishTerminalAndAwaitAcknowledgement(
481
450
  );
482
451
  }
483
452
 
484
- function beginCleanupSnapshot(
485
- state: WorkerRuntimeStateMachine,
486
- source: WorkerSnapshotSource,
487
- outputs: WorkerRuntimeOutput[],
488
- ): WorkerRuntimeStateMachine {
489
- requireNoPublication(state);
490
- const snapshot = {
491
- point: "before_cleanup_completed" as const,
492
- turnRecordId: null,
493
- required: true as const,
494
- };
495
- outputs.push({ kind: "upload_snapshot", ...snapshot, source });
496
- return {
497
- ...state,
498
- work: { ...state.work, publication: { kind: "cleanup_snapshot", snapshot } },
499
- };
500
- }
501
-
502
- function beginFatalSnapshot(
503
- state: WorkerRuntimeStateMachine,
504
- fatal: PendingFatal,
505
- source: WorkerSnapshotSource,
506
- afterSnapshot: "exit" | "cleanup",
507
- outputs: WorkerRuntimeOutput[],
508
- ): WorkerRuntimeStateMachine {
509
- requireNoPublication(state);
510
- const snapshot = {
511
- point: "before_worker_failed" as const,
512
- turnRecordId: null,
513
- required: false as const,
514
- };
515
- outputs.push({ kind: "upload_snapshot", ...snapshot, source });
516
- return {
517
- ...state,
518
- work: {
519
- ...state.work,
520
- publication: { kind: "fatal_snapshot", snapshot, fatal, afterSnapshot },
521
- },
522
- };
523
- }
524
-
525
453
  function finishFatal(
526
454
  state: WorkerRuntimeStateMachine,
527
455
  fatal: PendingFatal,
@@ -573,7 +501,17 @@ function failureOutputs(
573
501
  state.phase.kind === "cleaning" && state.phase.stage === "publication"
574
502
  ? "cleanup"
575
503
  : "exit";
576
- next = beginFatalSnapshot(next, fatal, disposition.snapshot.source, afterSnapshot, outputs);
504
+ next = beginSnapshot(
505
+ next,
506
+ {
507
+ kind: "fatal_snapshot",
508
+ snapshot: { point: "before_worker_failed", turnRecordId: null, required: false },
509
+ fatal,
510
+ afterSnapshot,
511
+ },
512
+ disposition.snapshot.source,
513
+ outputs,
514
+ );
577
515
  break;
578
516
  }
579
517
  const finished = finishFatal(next, fatal);
@@ -738,11 +676,15 @@ function advance(
738
676
  )
739
677
  : { upload: false as const };
740
678
  if (cleanupSnapshot.upload && next.session) {
741
- next = beginCleanupSnapshot(
679
+ next = beginSnapshot(
742
680
  {
743
681
  ...next,
744
682
  phase: { kind: "cleaning", reason, exitAfterCleanup, stage: "publication" },
745
683
  },
684
+ {
685
+ kind: "cleanup_snapshot",
686
+ snapshot: { point: "before_cleanup_completed", turnRecordId: null, required: true },
687
+ },
746
688
  sessionSnapshotSource(next.session),
747
689
  outputs,
748
690
  );
@@ -848,9 +790,11 @@ export function reduceWorkerRuntime(
848
790
  if (state.phase.kind !== "init") break;
849
791
  next = { ...state, phase: { kind: "waiting_for_start" } };
850
792
  outputs.push(HELLO);
793
+ outputs.push(protocol("worker.bootstrap_progress", { phase: "worker_connected" }));
851
794
  break;
852
795
  case "transport_connected":
853
796
  outputs.push(HELLO);
797
+ outputs.push(protocol("worker.bootstrap_progress", { phase: "worker_connected" }));
854
798
  if (state.session) {
855
799
  outputs.push(
856
800
  protocol("worker.heartbeat", {
@@ -956,6 +900,7 @@ export function reduceWorkerRuntime(
956
900
  },
957
901
  sessionTainted: false,
958
902
  };
903
+ outputs.push(protocol("worker.bootstrap_progress", { phase: "preparing_workspace" }));
959
904
  outputs.push({ kind: "bootstrap", startRecordId, payload: message.payload });
960
905
  break;
961
906
  }
@@ -1090,6 +1035,8 @@ export function reduceWorkerRuntime(
1090
1035
  kind: "diagnostic",
1091
1036
  payload: { level: "warn", code: "bootstrap.diagnostic", message },
1092
1037
  });
1038
+ outputs.push(protocol("worker.bootstrap_progress", { phase: "loading_resources" }));
1039
+ outputs.push(protocol("worker.bootstrap_progress", { phase: "preparing_turn" }));
1093
1040
  outputs.push(protocol("worker.ready", completion.readyPayload));
1094
1041
  if (wasDraining) break;
1095
1042
  const readySnapshot = resolveWorkerSnapshotPolicy(
@@ -1098,7 +1045,15 @@ export function reduceWorkerRuntime(
1098
1045
  completion.session.piAvailable,
1099
1046
  );
1100
1047
  if (readySnapshot.upload)
1101
- next = beginReadySnapshot(next, sessionSnapshotSource(completion.session), outputs);
1048
+ next = beginSnapshot(
1049
+ next,
1050
+ {
1051
+ kind: "ready_snapshot",
1052
+ snapshot: { point: "after_worker_ready", turnRecordId: null, required: false },
1053
+ },
1054
+ sessionSnapshotSource(completion.session),
1055
+ outputs,
1056
+ );
1102
1057
  next = armTimer(
1103
1058
  next,
1104
1059
  outputs,
@@ -1169,7 +1124,13 @@ export function reduceWorkerRuntime(
1169
1124
  });
1170
1125
  break;
1171
1126
  case "activation_failed":
1172
- if (!matchesActivation(state, event.startRecordId, event.turnRecordId)) break;
1127
+ case "turn_defect":
1128
+ if (
1129
+ event.kind === "activation_failed"
1130
+ ? !matchesActivation(state, event.startRecordId, event.turnRecordId)
1131
+ : !matchesTurn(state, event.turnRecordId)
1132
+ )
1133
+ break;
1173
1134
  if (state.phase.kind === "draining") {
1174
1135
  next = finishDrainingOperation(state);
1175
1136
  } else {
@@ -1253,6 +1214,7 @@ export function reduceWorkerRuntime(
1253
1214
  forkPiEntryId: event.result.meta.forkPiEntryId ?? null,
1254
1215
  resultPiEntryId: event.result.meta.resultPiEntryId ?? null,
1255
1216
  turnResultMarkdown: event.result.meta.turnResultMarkdown ?? null,
1217
+ resultSummary: event.result.meta.resultSummary,
1256
1218
  rootEntryId: event.result.meta.rootEntryId ?? null,
1257
1219
  } as never),
1258
1220
  park: null,
@@ -1297,97 +1259,33 @@ export function reduceWorkerRuntime(
1297
1259
  );
1298
1260
  if (!snapshotPolicy.upload)
1299
1261
  throw new Error("LLM terminal snapshot policy unexpectedly skipped upload");
1300
- next = beginTerminalSnapshot(
1262
+ next = beginSnapshot(
1301
1263
  next,
1302
- point,
1303
- event.turnRecordId,
1304
- pending,
1264
+ {
1265
+ kind: "terminal_snapshot",
1266
+ snapshot: { point, turnRecordId: event.turnRecordId, required: true },
1267
+ terminal: pending,
1268
+ },
1305
1269
  sessionSnapshotSource(state.session),
1306
1270
  outputs,
1307
1271
  );
1308
1272
  }
1309
1273
  break;
1310
1274
  }
1311
- case "turn_defect":
1312
- if (!matchesTurn(state, event.turnRecordId)) break;
1313
- if (state.phase.kind === "draining") {
1314
- next = finishDrainingOperation(state);
1315
- } else {
1316
- const failed = failureOutputs(next, {
1317
- kind: "dispatch",
1318
- error: event.error,
1319
- state: "busy",
1320
- session: failureContext(state),
1321
- });
1322
- next = failed.state;
1323
- outputs.push(...failed.outputs);
1324
- }
1325
- break;
1326
- case "snapshot_succeeded": {
1327
- const publication = state.work.publication;
1328
- switch (publication.kind) {
1329
- case "none":
1330
- case "terminal_pending_ack":
1331
- case "fatal_pending_cleanup":
1332
- break;
1333
- case "ready_snapshot":
1334
- if (!snapshotMatches(publication.snapshot, event)) break;
1335
- next = { ...state, work: { ...state.work, publication: { kind: "none" } } };
1336
- break;
1337
- case "terminal_snapshot":
1338
- if (!snapshotMatches(publication.snapshot, event)) break;
1339
- next = publishTerminalAndAwaitAcknowledgement(state, publication.terminal, outputs);
1340
- break;
1341
- case "cleanup_snapshot":
1342
- if (!snapshotMatches(publication.snapshot, event)) break;
1343
- if (state.phase.kind !== "cleaning" || state.phase.stage !== "publication")
1344
- throw new Error("Cleanup snapshot completed outside cleanup publication");
1345
- outputs.push({ kind: "cleanup" });
1346
- next = {
1347
- ...state,
1348
- phase: { ...state.phase, stage: "resources" },
1349
- work: { ...state.work, publication: { kind: "none" } },
1350
- };
1351
- break;
1352
- case "fatal_snapshot":
1353
- if (!snapshotMatches(publication.snapshot, event)) break;
1354
- if (publication.afterSnapshot === "exit") {
1355
- const finished = finishFatal(state, publication.fatal);
1356
- next = finished.state;
1357
- outputs.push(...finished.outputs);
1358
- } else {
1359
- if (state.phase.kind !== "cleaning" || state.phase.stage !== "publication")
1360
- throw new Error("Fatal snapshot completed outside cleanup publication");
1361
- outputs.push({ kind: "cleanup" });
1362
- next = {
1363
- ...state,
1364
- phase: { ...state.phase, stage: "resources" },
1365
- work: {
1366
- ...state.work,
1367
- publication: {
1368
- kind: "fatal_pending_cleanup",
1369
- fatal: publication.fatal,
1370
- },
1371
- },
1372
- };
1373
- }
1374
- break;
1375
- }
1376
- break;
1377
- }
1275
+ case "snapshot_succeeded":
1378
1276
  case "snapshot_failed": {
1379
1277
  const publication = state.work.publication;
1278
+ if (!("snapshot" in publication) || !snapshotMatches(publication.snapshot, event)) break;
1279
+ const completion = event.kind === "snapshot_succeeded" ? "completed" : "failed";
1380
1280
  switch (publication.kind) {
1381
- case "none":
1382
- case "terminal_pending_ack":
1383
- case "fatal_pending_cleanup":
1384
- break;
1385
1281
  case "ready_snapshot":
1386
- if (!snapshotMatches(publication.snapshot, event)) break;
1387
1282
  next = { ...state, work: { ...state.work, publication: { kind: "none" } } };
1388
1283
  break;
1389
1284
  case "terminal_snapshot": {
1390
- if (!snapshotMatches(publication.snapshot, event)) break;
1285
+ if (event.kind === "snapshot_succeeded") {
1286
+ next = publishTerminalAndAwaitAcknowledgement(state, publication.terminal, outputs);
1287
+ break;
1288
+ }
1391
1289
  const cleared = {
1392
1290
  ...state,
1393
1291
  work: { ...state.work, publication: { kind: "none" } as const },
@@ -1404,41 +1302,41 @@ export function reduceWorkerRuntime(
1404
1302
  break;
1405
1303
  }
1406
1304
  case "cleanup_snapshot": {
1407
- if (!snapshotMatches(publication.snapshot, event)) break;
1408
1305
  if (state.phase.kind !== "cleaning" || state.phase.stage !== "publication")
1409
- throw new Error("Cleanup snapshot failed outside cleanup publication");
1306
+ throw new Error(`Cleanup snapshot ${completion} outside cleanup publication`);
1410
1307
  const cleared = {
1411
1308
  ...state,
1412
1309
  work: { ...state.work, publication: { kind: "none" } as const },
1413
1310
  };
1414
- const failed = failureOutputs(cleared, {
1415
- kind: "cleanup",
1416
- error: event.error,
1417
- session: failureContext(state),
1418
- });
1419
- next = failed.state;
1420
- outputs.push(...failed.outputs);
1311
+ if (event.kind === "snapshot_succeeded") {
1312
+ outputs.push({ kind: "cleanup" });
1313
+ next = { ...cleared, phase: { ...state.phase, stage: "resources" } };
1314
+ } else {
1315
+ const failed = failureOutputs(cleared, {
1316
+ kind: "cleanup",
1317
+ error: event.error,
1318
+ session: failureContext(state),
1319
+ });
1320
+ next = failed.state;
1321
+ outputs.push(...failed.outputs);
1322
+ }
1421
1323
  break;
1422
1324
  }
1423
1325
  case "fatal_snapshot":
1424
- if (!snapshotMatches(publication.snapshot, event)) break;
1425
1326
  if (publication.afterSnapshot === "exit") {
1426
1327
  const finished = finishFatal(state, publication.fatal);
1427
1328
  next = finished.state;
1428
1329
  outputs.push(...finished.outputs);
1429
1330
  } else {
1430
1331
  if (state.phase.kind !== "cleaning" || state.phase.stage !== "publication")
1431
- throw new Error("Fatal snapshot failed outside cleanup publication");
1332
+ throw new Error(`Fatal snapshot ${completion} outside cleanup publication`);
1432
1333
  outputs.push({ kind: "cleanup" });
1433
1334
  next = {
1434
1335
  ...state,
1435
1336
  phase: { ...state.phase, stage: "resources" },
1436
1337
  work: {
1437
1338
  ...state.work,
1438
- publication: {
1439
- kind: "fatal_pending_cleanup",
1440
- fatal: publication.fatal,
1441
- },
1339
+ publication: { kind: "fatal_pending_cleanup", fatal: publication.fatal },
1442
1340
  },
1443
1341
  };
1444
1342
  }
@@ -30,6 +30,7 @@ import {
30
30
  } from "../missing-tool-recovery-runner.js";
31
31
  import type { PiTreeHandle } from "../pi-adapter.js";
32
32
  import {
33
+ type AppliedTargetedInputMetadata,
33
34
  applyPreTurnTargetedInputs,
34
35
  type PreTurnTargetedInput,
35
36
  resolvePreTurnTargetStartSelection,
@@ -108,13 +109,7 @@ export interface LlmTurnExecutorCallbacks {
108
109
  onPreTurnTargetedInputApplied?(
109
110
  inputId: string,
110
111
  sequence: number,
111
- meta?: {
112
- currentPrimaryPathLeafId?: string | null;
113
- rootEntryId?: string | null;
114
- targetSemanticRef?: import("@leitwerk-dev/domain").ProcessSemanticEntryRefKey | null;
115
- targetProductName?: string | null;
116
- targetEntryId?: string | null;
117
- },
112
+ meta?: AppliedTargetedInputMetadata,
118
113
  ): void;
119
114
  emit?: WorkerOperationEmitter;
120
115
  integrationTools?: readonly import("@leitwerk-dev/process-sdk").PiCustomTool[];
@@ -123,16 +118,6 @@ export interface LlmTurnExecutorCallbacks {
123
118
  /** Pi writes these on new sessions before any conversational content exists. */
124
119
  const PI_SESSION_BOOTSTRAP_ENTRY_TYPES = new Set(["model_change", "thinking_level_change"]);
125
120
 
126
- function visitPiTreeEntries(
127
- nodes: readonly PiTreeNode[],
128
- visit: (entryType: string) => void,
129
- ): void {
130
- for (const node of nodes) {
131
- visit(node.entry.type);
132
- visitPiTreeEntries(node.children, visit);
133
- }
134
- }
135
-
136
121
  /**
137
122
  * Empty-tree prepared starts mean "no conversational fork yet". Pi still appends
138
123
  * model/thinking bootstrap entries when activating a new session, so those alone
@@ -141,13 +126,9 @@ function visitPiTreeEntries(
141
126
  export function isPiTreeEmptyForPreparedEmptyPlan(
142
127
  piHandle: Pick<PiTreeHandle, "getTree">,
143
128
  ): boolean {
144
- let hasNonBootstrap = false;
145
- visitPiTreeEntries(piHandle.getTree(), (entryType) => {
146
- if (!PI_SESSION_BOOTSTRAP_ENTRY_TYPES.has(entryType)) {
147
- hasNonBootstrap = true;
148
- }
149
- });
150
- return !hasNonBootstrap;
129
+ const isBootstrapOnly = (node: PiTreeNode): boolean =>
130
+ PI_SESSION_BOOTSTRAP_ENTRY_TYPES.has(node.entry.type) && node.children.every(isBootstrapOnly);
131
+ return piHandle.getTree().every(isBootstrapOnly);
151
132
  }
152
133
 
153
134
  /**
@@ -210,6 +191,7 @@ function treePlanFromPreparedStart(input: {
210
191
  export async function executeLlmTurn<TOutcome extends string>(input: {
211
192
  resolvedWorkerProcess: ResolvedWorkerProcess;
212
193
  ctx: WorkerProcessContext;
194
+ prepared?: unknown;
213
195
  piHandle: PiTreeHandle;
214
196
  turnDef: LlmTurnDefinition<TOutcome, unknown, unknown>;
215
197
  turnId: string;
@@ -467,7 +449,7 @@ export async function executeLlmTurn<TOutcome extends string>(input: {
467
449
  initialPromptlessTurnResumeReason === "active_turn_resume"
468
450
  ) {
469
451
  try {
470
- promptText = await input.turnDef.prompt(input.ctx);
452
+ promptText = await input.turnDef.prompt({ ...input.ctx, prepared: input.prepared });
471
453
  } catch (error: unknown) {
472
454
  return failWithWorkerError(
473
455
  "turn.prompt_preparation_failed",
@@ -665,15 +647,15 @@ export async function executeLlmTurn<TOutcome extends string>(input: {
665
647
  const finalCompletionState = recoveryResult.finalAttempt.completionState;
666
648
  const finalPromptResult = recoveryResult.finalAttempt.promptResult;
667
649
  const finalResolvedOutcome = recoveryResult.finalAttempt.resolvedOutcome;
668
- if (!recoveryResult.recovered) {
650
+ if (recoveryResult.failure) {
651
+ const { recoveryContext, description } = recoveryResult.failure;
669
652
  return reportFailedTurn(
670
653
  "protocol_error",
671
- `Turn '${turnId}' completed without the required tool calls after ${MAX_MISSING_TOOL_CALL_RECOVERY_ATTEMPTS} automatic recovery attempts: ${recoveryResult.baseMissingToolRecoveryDescription}`,
654
+ `Turn '${turnId}' completed without the required tool calls after ${MAX_MISSING_TOOL_CALL_RECOVERY_ATTEMPTS} automatic recovery attempts: ${description}`,
672
655
  finalPromptResult.resultEntryId,
673
656
  {
674
- recoveryContext: recoveryResult.recoveryContext,
675
- restorePrimaryLeaf:
676
- recoveryResult.recoveryContext?.failureCode !== "missing_markdown_result",
657
+ recoveryContext,
658
+ restorePrimaryLeaf: recoveryContext.failureCode !== "missing_markdown_result",
677
659
  },
678
660
  );
679
661
  }
@@ -723,6 +705,7 @@ export async function executeLlmTurn<TOutcome extends string>(input: {
723
705
  forkPiEntryId: treePlan.forkPiEntryId,
724
706
  resultPiEntryId: finalPromptResult.resultEntryId,
725
707
  turnResultMarkdown: finalizedTurnResultMarkdown.markdown,
708
+ resultSummary: finalCompletionState.markdownState.resultSummary,
726
709
  rootEntryId: rootEntryIdAfterTurn,
727
710
  },
728
711
  };