@leitwerk-dev/worker 0.1.9 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (234) hide show
  1. package/dist/automatic-turn-executor.d.ts +1 -0
  2. package/dist/automatic-turn-executor.d.ts.map +1 -1
  3. package/dist/{chunk-O6332GRG.js → chunk-Y7S2MZD3.js} +1349 -932
  4. package/dist/chunk-Y7S2MZD3.js.map +1 -0
  5. package/dist/connection-diagnostics.d.ts +5 -0
  6. package/dist/connection-diagnostics.d.ts.map +1 -0
  7. package/dist/container-entry-main.d.ts +2 -0
  8. package/dist/container-entry-main.d.ts.map +1 -0
  9. package/dist/container-entry-main.js +232 -0
  10. package/dist/container-entry-main.js.map +1 -0
  11. package/dist/container-entry.d.ts +14 -0
  12. package/dist/container-entry.d.ts.map +1 -0
  13. package/dist/development-tool-environment.d.ts +48 -0
  14. package/dist/development-tool-environment.d.ts.map +1 -0
  15. package/dist/diagnostics.d.ts +4 -0
  16. package/dist/diagnostics.d.ts.map +1 -1
  17. package/dist/docker-registry-credentials.d.ts +8 -0
  18. package/dist/docker-registry-credentials.d.ts.map +1 -0
  19. package/dist/entry-runtime.d.ts +1 -0
  20. package/dist/entry-runtime.d.ts.map +1 -1
  21. package/dist/index.d.ts +1 -0
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +44 -5
  24. package/dist/index.js.map +1 -1
  25. package/dist/input-consumer.d.ts +6 -11
  26. package/dist/input-consumer.d.ts.map +1 -1
  27. package/dist/ipc.d.ts +1 -0
  28. package/dist/ipc.d.ts.map +1 -1
  29. package/dist/logical-prompt-runner.d.ts.map +1 -1
  30. package/dist/managed-pi-bootstrap.d.ts.map +1 -1
  31. package/dist/missing-tool-recovery-runner.d.ts +4 -3
  32. package/dist/missing-tool-recovery-runner.d.ts.map +1 -1
  33. package/dist/pi-adapter.d.ts +1 -0
  34. package/dist/pi-adapter.d.ts.map +1 -1
  35. package/dist/pi-event-reporter.d.ts.map +1 -1
  36. package/dist/pi-resource-bundle.d.ts +11 -0
  37. package/dist/pi-resource-bundle.d.ts.map +1 -1
  38. package/dist/pre-turn-targeted-inputs.d.ts +8 -7
  39. package/dist/pre-turn-targeted-inputs.d.ts.map +1 -1
  40. package/dist/prompt-guards.d.ts.map +1 -1
  41. package/dist/repository-bash-tool.d.ts +4 -0
  42. package/dist/repository-bash-tool.d.ts.map +1 -0
  43. package/dist/resource-loader-factory.d.ts +1 -2
  44. package/dist/resource-loader-factory.d.ts.map +1 -1
  45. package/dist/result-image-upload.d.ts.map +1 -1
  46. package/dist/runtime/adapters.d.ts +2 -0
  47. package/dist/runtime/adapters.d.ts.map +1 -1
  48. package/dist/runtime/bootstrap-session.d.ts +8 -5
  49. package/dist/runtime/bootstrap-session.d.ts.map +1 -1
  50. package/dist/runtime/bootstrap.d.ts +14 -18
  51. package/dist/runtime/bootstrap.d.ts.map +1 -1
  52. package/dist/runtime/failure-policy.d.ts +1 -0
  53. package/dist/runtime/failure-policy.d.ts.map +1 -1
  54. package/dist/runtime/index.d.ts.map +1 -1
  55. package/dist/runtime/lifecycle-reducer.d.ts.map +1 -1
  56. package/dist/runtime/llm-turn-execution.d.ts +3 -8
  57. package/dist/runtime/llm-turn-execution.d.ts.map +1 -1
  58. package/dist/runtime/turn-execution.d.ts +2 -9
  59. package/dist/runtime/turn-execution.d.ts.map +1 -1
  60. package/dist/session-snapshot-exchange.d.ts +0 -4
  61. package/dist/session-snapshot-exchange.d.ts.map +1 -1
  62. package/dist/turn-continuation.d.ts.map +1 -1
  63. package/dist/turn-execution-error.d.ts +1 -1
  64. package/dist/turn-execution-error.d.ts.map +1 -1
  65. package/dist/turn-execution-result.d.ts +1 -0
  66. package/dist/turn-execution-result.d.ts.map +1 -1
  67. package/dist/turn-outcome-tool-session.d.ts +0 -2
  68. package/dist/turn-outcome-tool-session.d.ts.map +1 -1
  69. package/dist/turn-result-markdown.d.ts +2 -1
  70. package/dist/turn-result-markdown.d.ts.map +1 -1
  71. package/dist/turn-tree-strategy.d.ts +0 -1
  72. package/dist/turn-tree-strategy.d.ts.map +1 -1
  73. package/dist/worker-entry.js +16 -4
  74. package/dist/worker-entry.js.map +1 -1
  75. package/dist/worker-ipc-reporter.d.ts.map +1 -1
  76. package/dist/workspace/manifest.d.ts +4 -7
  77. package/dist/workspace/manifest.d.ts.map +1 -1
  78. package/dist/workspace/node-run-root-git-ops.d.ts +2 -2
  79. package/dist/workspace/node-run-root-git-ops.d.ts.map +1 -1
  80. package/dist/workspace/resource-aggregator.d.ts.map +1 -1
  81. package/dist/workspace/run-root.d.ts +9 -20
  82. package/dist/workspace/run-root.d.ts.map +1 -1
  83. package/package.json +8 -8
  84. package/src/automatic-turn-executor.ts +2 -0
  85. package/src/connection-diagnostics.ts +27 -0
  86. package/src/container-entry-main.ts +24 -0
  87. package/src/container-entry.ts +246 -0
  88. package/src/development-tool-environment.ts +452 -0
  89. package/src/diagnostics.ts +1 -0
  90. package/src/docker-registry-credentials.ts +65 -0
  91. package/src/entry-runtime.ts +5 -4
  92. package/src/index.ts +11 -0
  93. package/src/input-consumer.ts +7 -29
  94. package/src/ipc.ts +37 -2
  95. package/src/logical-prompt-runner.ts +23 -29
  96. package/src/managed-pi-bootstrap.ts +3 -3
  97. package/src/missing-tool-recovery-runner.ts +4 -18
  98. package/src/pi-adapter.ts +19 -50
  99. package/src/pi-event-reporter.ts +16 -38
  100. package/src/pi-resource-bundle.ts +67 -1
  101. package/src/pre-turn-targeted-inputs.ts +9 -11
  102. package/src/prompt-guards.ts +44 -75
  103. package/src/repository-bash-tool.ts +15 -0
  104. package/src/resource-loader-factory.ts +1 -18
  105. package/src/result-image-upload.ts +16 -27
  106. package/src/runtime/adapters.ts +2 -0
  107. package/src/runtime/bootstrap-session.ts +69 -39
  108. package/src/runtime/bootstrap.ts +160 -103
  109. package/src/runtime/failure-policy.ts +36 -42
  110. package/src/runtime/index.ts +43 -14
  111. package/src/runtime/lifecycle-reducer.ts +71 -173
  112. package/src/runtime/llm-turn-execution.ts +13 -30
  113. package/src/runtime/turn-execution.ts +78 -31
  114. package/src/session-snapshot-exchange.ts +23 -64
  115. package/src/turn-continuation.ts +9 -17
  116. package/src/turn-execution-error.ts +3 -11
  117. package/src/turn-execution-result.ts +1 -0
  118. package/src/turn-outcome-tool-session.ts +25 -21
  119. package/src/turn-result-markdown.ts +31 -34
  120. package/src/turn-tree-strategy.ts +6 -19
  121. package/src/worker-entry.ts +8 -0
  122. package/src/worker-ipc-reporter.ts +8 -16
  123. package/src/workspace/manifest.ts +5 -7
  124. package/src/workspace/node-run-root-git-ops.ts +65 -25
  125. package/src/workspace/resource-aggregator.ts +5 -16
  126. package/src/workspace/run-root.ts +38 -89
  127. package/dist/automatic-turn-executor.js +0 -58
  128. package/dist/automatic-turn-executor.js.map +0 -1
  129. package/dist/chunk-O6332GRG.js.map +0 -1
  130. package/dist/diagnostics.js +0 -51
  131. package/dist/diagnostics.js.map +0 -1
  132. package/dist/entry-runtime.js +0 -160
  133. package/dist/entry-runtime.js.map +0 -1
  134. package/dist/event-translator.js +0 -12
  135. package/dist/event-translator.js.map +0 -1
  136. package/dist/extension-entry-roots.js +0 -41
  137. package/dist/extension-entry-roots.js.map +0 -1
  138. package/dist/identified-pi-entry.js +0 -125
  139. package/dist/identified-pi-entry.js.map +0 -1
  140. package/dist/input-consumer.js +0 -34
  141. package/dist/input-consumer.js.map +0 -1
  142. package/dist/integration-tool-bridge.js +0 -53
  143. package/dist/integration-tool-bridge.js.map +0 -1
  144. package/dist/ipc.js +0 -192
  145. package/dist/ipc.js.map +0 -1
  146. package/dist/logical-prompt-runner.js +0 -225
  147. package/dist/logical-prompt-runner.js.map +0 -1
  148. package/dist/managed-pi-agent-dir.js +0 -66
  149. package/dist/managed-pi-agent-dir.js.map +0 -1
  150. package/dist/managed-pi-bootstrap.js +0 -135
  151. package/dist/managed-pi-bootstrap.js.map +0 -1
  152. package/dist/missing-tool-recovery-runner.js +0 -73
  153. package/dist/missing-tool-recovery-runner.js.map +0 -1
  154. package/dist/pi-adapter.js +0 -1648
  155. package/dist/pi-adapter.js.map +0 -1
  156. package/dist/pi-branch-guard.js +0 -75
  157. package/dist/pi-branch-guard.js.map +0 -1
  158. package/dist/pi-event-reporter.js +0 -136
  159. package/dist/pi-event-reporter.js.map +0 -1
  160. package/dist/pi-resource-bundle.js +0 -58
  161. package/dist/pi-resource-bundle.js.map +0 -1
  162. package/dist/pre-turn-targeted-inputs.js +0 -101
  163. package/dist/pre-turn-targeted-inputs.js.map +0 -1
  164. package/dist/prompt-guards.js +0 -318
  165. package/dist/prompt-guards.js.map +0 -1
  166. package/dist/question-bridge.js +0 -24
  167. package/dist/question-bridge.js.map +0 -1
  168. package/dist/question-tool.js +0 -54
  169. package/dist/question-tool.js.map +0 -1
  170. package/dist/replaying-request-bridge.js +0 -71
  171. package/dist/replaying-request-bridge.js.map +0 -1
  172. package/dist/resource-loader-factory.js +0 -87
  173. package/dist/resource-loader-factory.js.map +0 -1
  174. package/dist/result-image-upload.js +0 -183
  175. package/dist/result-image-upload.js.map +0 -1
  176. package/dist/runtime/adapters.js +0 -15
  177. package/dist/runtime/adapters.js.map +0 -1
  178. package/dist/runtime/bootstrap-session.js +0 -199
  179. package/dist/runtime/bootstrap-session.js.map +0 -1
  180. package/dist/runtime/bootstrap.js +0 -440
  181. package/dist/runtime/bootstrap.js.map +0 -1
  182. package/dist/runtime/failure-policy.js +0 -182
  183. package/dist/runtime/failure-policy.js.map +0 -1
  184. package/dist/runtime/index.js +0 -339
  185. package/dist/runtime/index.js.map +0 -1
  186. package/dist/runtime/lifecycle-reducer.js +0 -1142
  187. package/dist/runtime/lifecycle-reducer.js.map +0 -1
  188. package/dist/runtime/llm-turn-execution.js +0 -494
  189. package/dist/runtime/llm-turn-execution.js.map +0 -1
  190. package/dist/runtime/settings.js +0 -24
  191. package/dist/runtime/settings.js.map +0 -1
  192. package/dist/runtime/snapshot-policy.js +0 -16
  193. package/dist/runtime/snapshot-policy.js.map +0 -1
  194. package/dist/runtime/turn-execution.js +0 -151
  195. package/dist/runtime/turn-execution.js.map +0 -1
  196. package/dist/session-snapshot-exchange.js +0 -102
  197. package/dist/session-snapshot-exchange.js.map +0 -1
  198. package/dist/test-helpers/fake-websocket.js +0 -40
  199. package/dist/test-helpers/fake-websocket.js.map +0 -1
  200. package/dist/test-helpers/ipc-harness.d.ts +0 -11
  201. package/dist/test-helpers/ipc-harness.d.ts.map +0 -1
  202. package/dist/test-helpers/ipc-harness.js +0 -17
  203. package/dist/test-helpers/ipc-harness.js.map +0 -1
  204. package/dist/turn-continuation.js +0 -80
  205. package/dist/turn-continuation.js.map +0 -1
  206. package/dist/turn-execution-error.js +0 -64
  207. package/dist/turn-execution-error.js.map +0 -1
  208. package/dist/turn-execution-result.js +0 -21
  209. package/dist/turn-execution-result.js.map +0 -1
  210. package/dist/turn-outcome-tool-session.js +0 -210
  211. package/dist/turn-outcome-tool-session.js.map +0 -1
  212. package/dist/turn-record-id.js +0 -10
  213. package/dist/turn-record-id.js.map +0 -1
  214. package/dist/turn-result-markdown.js +0 -263
  215. package/dist/turn-result-markdown.js.map +0 -1
  216. package/dist/turn-tree-strategy.js +0 -80
  217. package/dist/turn-tree-strategy.js.map +0 -1
  218. package/dist/worker-http.js +0 -9
  219. package/dist/worker-http.js.map +0 -1
  220. package/dist/worker-ipc-reporter.js +0 -58
  221. package/dist/worker-ipc-reporter.js.map +0 -1
  222. package/dist/worker-payloads.js +0 -66
  223. package/dist/worker-payloads.js.map +0 -1
  224. package/dist/worker-start-payload.js +0 -5
  225. package/dist/worker-start-payload.js.map +0 -1
  226. package/dist/workspace/manifest.js +0 -79
  227. package/dist/workspace/manifest.js.map +0 -1
  228. package/dist/workspace/node-run-root-git-ops.js +0 -96
  229. package/dist/workspace/node-run-root-git-ops.js.map +0 -1
  230. package/dist/workspace/resource-aggregator.js +0 -39
  231. package/dist/workspace/resource-aggregator.js.map +0 -1
  232. package/dist/workspace/run-root.js +0 -209
  233. package/dist/workspace/run-root.js.map +0 -1
  234. package/src/test-helpers/ipc-harness.ts +0 -19
@@ -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
  };
@@ -1,8 +1,4 @@
1
- import {
2
- failActiveTurnProgress,
3
- type ProcessSemanticEntryRefKey,
4
- type TurnProgressReport,
5
- } from "@leitwerk-dev/domain";
1
+ import type { TurnProgressReport } from "@leitwerk-dev/domain";
6
2
  import type {
7
3
  LlmTurnDefinition,
8
4
  TurnOptions,
@@ -14,7 +10,10 @@ import { assertValidLlmTurnDefinition } from "@leitwerk-dev/process-sdk";
14
10
  import { createAutomaticTurnExecutor } from "../automatic-turn-executor.js";
15
11
  import type { WorkerOperationEmitter } from "../diagnostics.js";
16
12
  import type { PiTreeHandle } from "../pi-adapter.js";
17
- import type { PreTurnTargetedInput } from "../pre-turn-targeted-inputs.js";
13
+ import type {
14
+ AppliedTargetedInputMetadata,
15
+ PreTurnTargetedInput,
16
+ } from "../pre-turn-targeted-inputs.js";
18
17
  import type { WorkerQuestionRequest } from "../question-tool.js";
19
18
  import { TurnExecutionError } from "../turn-execution-error.js";
20
19
  import { TurnExecutionFailure, type TurnExecutionMeta } from "../turn-execution-result.js";
@@ -25,13 +24,7 @@ import { executeLlmTurn } from "./llm-turn-execution.js";
25
24
  export interface AppliedTargetedInput {
26
25
  inputId: string;
27
26
  sequence: number;
28
- meta?: {
29
- currentPrimaryPathLeafId?: string | null;
30
- rootEntryId?: string | null;
31
- targetSemanticRef?: ProcessSemanticEntryRefKey | null;
32
- targetProductName?: string | null;
33
- targetEntryId?: string | null;
34
- };
27
+ meta?: AppliedTargetedInputMetadata;
35
28
  }
36
29
 
37
30
  export type SelectedTurnExecutionResult =
@@ -70,6 +63,22 @@ function failedResult(
70
63
  return { kind: "failed", failure, appliedTargetedInputs };
71
64
  }
72
65
 
66
+ function normalizePreparedData(value: unknown): unknown {
67
+ if (value === undefined) {
68
+ throw new Error("LLM turn preparation must return JSON-serializable data");
69
+ }
70
+ let serialized: string;
71
+ try {
72
+ serialized = JSON.stringify(value);
73
+ } catch {
74
+ throw new Error("LLM turn preparation must return JSON-serializable data");
75
+ }
76
+ if (Buffer.byteLength(serialized, "utf8") > 65_536) {
77
+ throw new Error("LLM turn preparation data exceeds 65536 bytes");
78
+ }
79
+ return JSON.parse(serialized) as unknown;
80
+ }
81
+
73
82
  /** Execute one accepted selected turn and return its single terminal fact. */
74
83
  export async function executeSelectedTurn(
75
84
  input: SelectedTurnExecutionInput,
@@ -89,6 +98,24 @@ export async function executeSelectedTurn(
89
98
  if (!handler) throw new Error(`Validated turn handler '${currentTurnId}' is unavailable`);
90
99
  let automaticIntegrationCallIndex = 0;
91
100
  let latestProgressReport: TurnProgressReport | null = null;
101
+ const reportProgress = (report: TurnProgressReport) => {
102
+ latestProgressReport = report;
103
+ input.emit({ kind: "progress", turnRecordId: input.turnRecordId, report });
104
+ };
105
+ const callIntegrationTool = async (name: string, args: Record<string, unknown>) => {
106
+ const tool = input.integrationTools?.find((candidate) => candidate.name === name);
107
+ if (!tool) {
108
+ throw new Error(`Integration tool '${name}' is not authorized for turn '${currentTurnId}'`);
109
+ }
110
+ automaticIntegrationCallIndex += 1;
111
+ return tool.execute(args, {
112
+ toolCallId:
113
+ selectedTurnType === "automatic"
114
+ ? `${input.turnRecordId}:${automaticIntegrationCallIndex}:${name}`
115
+ : `${input.turnRecordId}:prepare:${automaticIntegrationCallIndex}:${name}`,
116
+ signal: input.signal,
117
+ });
118
+ };
92
119
 
93
120
  const ctx = {
94
121
  process: processSnapshot,
@@ -100,23 +127,8 @@ export async function executeSelectedTurn(
100
127
  workspaceRoot: input.session.workspaceRoot,
101
128
  ...(selectedTurnType === "automatic"
102
129
  ? {
103
- reportProgress(report: TurnProgressReport) {
104
- latestProgressReport = report;
105
- input.emit({ kind: "progress", turnRecordId: input.turnRecordId, report });
106
- },
107
- async callIntegrationTool(name: string, args: Record<string, unknown>) {
108
- const tool = input.integrationTools?.find((candidate) => candidate.name === name);
109
- if (!tool) {
110
- throw new Error(
111
- `Integration tool '${name}' is not authorized for turn '${currentTurnId}'`,
112
- );
113
- }
114
- automaticIntegrationCallIndex += 1;
115
- return tool.execute(args, {
116
- toolCallId: `${input.turnRecordId}:${automaticIntegrationCallIndex}:${name}`,
117
- signal: input.signal,
118
- });
119
- },
130
+ reportProgress,
131
+ callIntegrationTool,
120
132
  }
121
133
  : {}),
122
134
  } as WorkerProcessContext;
@@ -156,9 +168,36 @@ export async function executeSelectedTurn(
156
168
  `Turn '${currentTurnId}' requires a Pi handle`,
157
169
  );
158
170
  }
171
+ let prepared = input.session.llmPreparation?.data;
172
+ if (turnDef.prepare && !input.session.llmPreparation) {
173
+ try {
174
+ prepared = normalizePreparedData(
175
+ await turnDef.prepare({
176
+ ...ctx,
177
+ reportProgress,
178
+ callIntegrationTool,
179
+ }),
180
+ );
181
+ input.emit({ kind: "prepared", turnRecordId: input.turnRecordId, data: prepared });
182
+ } catch (error) {
183
+ const message = error instanceof Error ? error.message : String(error);
184
+ throw new TurnExecutionFailure({
185
+ turnRecordId: input.turnRecordId,
186
+ turnId: currentTurnId,
187
+ turnType: "llm",
188
+ pathType: turnDef.branchType,
189
+ failure: new TurnExecutionError(
190
+ currentTurnId,
191
+ "infrastructure",
192
+ `Turn '${currentTurnId}' preparation failed: ${message}`,
193
+ ),
194
+ });
195
+ }
196
+ }
159
197
  const completed = await executeLlmTurn({
160
198
  resolvedWorkerProcess,
161
199
  ctx,
200
+ ...(turnDef.prepare ? { prepared } : {}),
162
201
  piHandle,
163
202
  turnDef,
164
203
  turnId: currentTurnId,
@@ -226,10 +265,18 @@ export async function executeSelectedTurn(
226
265
  } catch (error) {
227
266
  const failedProgressReport = latestProgressReport as TurnProgressReport | null;
228
267
  if (failedProgressReport) {
268
+ const message = error instanceof Error ? error.message : String(error);
269
+ const steps = failedProgressReport.steps.map((step) =>
270
+ step.status === "in_progress"
271
+ ? { ...step, status: "failed" as const, detail: message }
272
+ : step,
273
+ );
274
+ const report: TurnProgressReport = { ...failedProgressReport, steps };
275
+ latestProgressReport = report;
229
276
  input.emit({
230
277
  kind: "progress",
231
278
  turnRecordId: input.turnRecordId,
232
- report: failActiveTurnProgress(failedProgressReport),
279
+ report,
233
280
  });
234
281
  }
235
282
  if (error instanceof TurnExecutionFailure) return failedResult(error, appliedTargetedInputs);