@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,7 +1,8 @@
1
1
  // src/pi-adapter.ts
2
2
  import { access, mkdir, writeFile } from "fs/promises";
3
3
  import path2 from "path";
4
- import { retryAssistantCall } from "@earendil-works/pi-ai";
4
+ import { readFiniteNumber, readNonBlankString as readNonEmptyString } from "@leitwerk-dev/domain";
5
+ import { hasErrorCode, isEnoent } from "@leitwerk-dev/process-sdk";
5
6
  import { resolvePiAgentDir } from "@leitwerk-dev/process-sdk/pi-config";
6
7
  import { parseDurationMs } from "@leitwerk-dev/watcher-utils";
7
8
 
@@ -69,6 +70,18 @@ function assertResultStayedOnExecutionBranch(input) {
69
70
  }
70
71
  }
71
72
 
73
+ // src/repository-bash-tool.ts
74
+ import { sanitizeWorkerSubprocessEnv } from "@leitwerk-dev/process-sdk";
75
+ async function createRepositoryBashTool(cwd) {
76
+ const { createBashToolDefinition } = await import("@earendil-works/pi-coding-agent");
77
+ return createBashToolDefinition(cwd, {
78
+ spawnHook: (context) => ({
79
+ ...context,
80
+ env: sanitizeWorkerSubprocessEnv(context.env, { NODE_ENV: void 0 })
81
+ })
82
+ });
83
+ }
84
+
72
85
  // src/resource-loader-factory.ts
73
86
  import { existsSync, readdirSync, readFileSync } from "fs";
74
87
  import path from "path";
@@ -150,7 +163,7 @@ async function inspectPiTreeForPlanning(input) {
150
163
  try {
151
164
  await access(input.treeFile);
152
165
  } catch (error) {
153
- if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") {
166
+ if (isEnoent(error)) {
154
167
  return { currentLeafId: null, entries: [] };
155
168
  }
156
169
  throw error;
@@ -310,21 +323,6 @@ function updateAgentMessagesForCurrentLeaf(session) {
310
323
  function activeTurnId(state) {
311
324
  return state.currentTurnId ?? `turn-${state.turnSequence}`;
312
325
  }
313
- function readNonEmptyString(value) {
314
- return typeof value === "string" && value.trim() !== "" ? value : null;
315
- }
316
- function readFiniteNumber(value) {
317
- if (typeof value === "number" && Number.isFinite(value)) {
318
- return value;
319
- }
320
- if (typeof value === "string" && value.trim() !== "") {
321
- const parsed = Number(value);
322
- if (Number.isFinite(parsed)) {
323
- return parsed;
324
- }
325
- }
326
- return null;
327
- }
328
326
  function listRecordKeys(value) {
329
327
  return Object.keys(value).slice(0, 12);
330
328
  }
@@ -1080,6 +1078,7 @@ function translateAgentSessionEventEnvelope(event, state) {
1080
1078
  }
1081
1079
  }
1082
1080
  var SdkPiTreeHandle = class {
1081
+ /** @internal */
1083
1082
  constructor(session, options) {
1084
1083
  this.session = session;
1085
1084
  this.sessionId = session.sessionId;
@@ -1093,8 +1092,11 @@ var SdkPiTreeHandle = class {
1093
1092
  };
1094
1093
  }
1095
1094
  session;
1095
+ /** @internal */
1096
1096
  sessionId;
1097
+ /** @internal */
1097
1098
  treeFile;
1099
+ /** @internal */
1098
1100
  isResumed;
1099
1101
  eventState = { currentTurnId: null, turnSequence: 0 };
1100
1102
  eventHandlers = /* @__PURE__ */ new Set();
@@ -1103,6 +1105,7 @@ var SdkPiTreeHandle = class {
1103
1105
  continuationRetryAbortController = null;
1104
1106
  availableToolNames;
1105
1107
  runDetails;
1108
+ /** @internal */
1106
1109
  getRunDetails() {
1107
1110
  return {
1108
1111
  loadedAgentsFiles: this.runDetails.loadedAgentsFiles.map((file) => ({ ...file })),
@@ -1110,32 +1113,41 @@ var SdkPiTreeHandle = class {
1110
1113
  availableToolNames: [...this.runDetails.availableToolNames]
1111
1114
  };
1112
1115
  }
1116
+ /** @internal */
1113
1117
  getLeafId() {
1114
1118
  return this.session.sessionManager.getLeafId();
1115
1119
  }
1120
+ /** @internal */
1116
1121
  getEntry(id) {
1117
1122
  return this.session.sessionManager.getEntry(id);
1118
1123
  }
1124
+ /** @internal */
1119
1125
  getBranch(fromId) {
1120
1126
  return this.session.sessionManager.getBranch(fromId);
1121
1127
  }
1128
+ /** @internal */
1122
1129
  getChildren(parentId) {
1123
1130
  return this.session.sessionManager.getChildren(parentId);
1124
1131
  }
1132
+ /** @internal */
1125
1133
  getTree() {
1126
1134
  return this.session.sessionManager.getTree();
1127
1135
  }
1136
+ /** @internal */
1128
1137
  async branch(entryId) {
1129
1138
  this.session.sessionManager.branch(entryId);
1130
1139
  updateAgentMessagesForCurrentLeaf(this.session);
1131
1140
  }
1141
+ /** @internal */
1132
1142
  async branchFromRoot() {
1133
1143
  this.session.sessionManager.resetLeaf();
1134
1144
  updateAgentMessagesForCurrentLeaf(this.session);
1135
1145
  }
1146
+ /** @internal */
1136
1147
  async resetLeaf() {
1137
1148
  await this.branchFromRoot();
1138
1149
  }
1150
+ /** @internal */
1139
1151
  async compact(customInstructions, details) {
1140
1152
  if (details === void 0) {
1141
1153
  const result = await this.session.compact(customInstructions);
@@ -1267,6 +1279,7 @@ var SdkPiTreeHandle = class {
1267
1279
  const controller = new AbortController();
1268
1280
  this.continuationRetryAbortController = controller;
1269
1281
  try {
1282
+ const { retryAssistantCall } = await import("@earendil-works/pi-ai");
1270
1283
  await retryAssistantCall(
1271
1284
  async () => {
1272
1285
  await this.session.agent.continue();
@@ -1385,12 +1398,15 @@ var SdkPiTreeHandle = class {
1385
1398
  options.terminalAcknowledgement
1386
1399
  );
1387
1400
  }
1401
+ /** @internal */
1388
1402
  async prompt(text, options = {}) {
1389
1403
  return await this.executePrompt(options, () => this.session.prompt(text));
1390
1404
  }
1405
+ /** @internal */
1391
1406
  async promptLiteral(text, options = {}) {
1392
1407
  return await this.executePrompt(options, () => this.session.sendUserMessage(text));
1393
1408
  }
1409
+ /** @internal */
1394
1410
  async promptCustom(input, options = {}) {
1395
1411
  return await this.executePrompt(
1396
1412
  options,
@@ -1400,6 +1416,7 @@ var SdkPiTreeHandle = class {
1400
1416
  )
1401
1417
  );
1402
1418
  }
1419
+ /** @internal */
1403
1420
  async continueTurn(options = {}) {
1404
1421
  updateAgentMessagesForCurrentLeaf(this.session);
1405
1422
  return await this.captureTurnExecutionResult(
@@ -1409,6 +1426,7 @@ var SdkPiTreeHandle = class {
1409
1426
  options.terminalAcknowledgement
1410
1427
  );
1411
1428
  }
1429
+ /** @internal */
1412
1430
  async appendCustomMessage(input) {
1413
1431
  const branch = this.createExecutionBranchSnapshot();
1414
1432
  const sessionManager = this.session.sessionManager;
@@ -1433,13 +1451,16 @@ var SdkPiTreeHandle = class {
1433
1451
  branch.assertResult("continue", entryId, entryId);
1434
1452
  return entryId;
1435
1453
  }
1454
+ /** @internal */
1436
1455
  async steer(text) {
1437
1456
  await this.session.steer(text);
1438
1457
  }
1458
+ /** @internal */
1439
1459
  async abortTurn() {
1440
1460
  this.continuationRetryAbortController?.abort(new Error("Retry cancelled"));
1441
1461
  await this.session.abort();
1442
1462
  }
1463
+ /** @internal */
1443
1464
  subscribe(handler) {
1444
1465
  this.eventHandlers.add(handler);
1445
1466
  this.ensureSessionSubscription();
@@ -1448,6 +1469,7 @@ var SdkPiTreeHandle = class {
1448
1469
  this.releaseSessionSubscriptionIfIdle();
1449
1470
  };
1450
1471
  }
1472
+ /** @internal */
1451
1473
  subscribeDiagnostics(handler) {
1452
1474
  this.diagnosticHandlers.add(handler);
1453
1475
  this.ensureSessionSubscription();
@@ -1493,6 +1515,7 @@ var SdkPiTreeHandle = class {
1493
1515
  }
1494
1516
  }
1495
1517
  }
1518
+ /** @internal */
1496
1519
  async close() {
1497
1520
  if (this.sessionUnsubscribe) {
1498
1521
  this.sessionUnsubscribe();
@@ -1649,9 +1672,6 @@ function resolveModelSelection(modelProfileId, configSnapshot, modelRuntime, dia
1649
1672
  thinkingLevel: profile.thinking_level
1650
1673
  };
1651
1674
  }
1652
- function isAlreadyExistsError(error) {
1653
- return typeof error === "object" && error !== null && "code" in error && error.code === "EEXIST";
1654
- }
1655
1675
  async function ensureSessionFileExists(input) {
1656
1676
  await mkdir(path2.dirname(input.treeFile), { recursive: true });
1657
1677
  const header = {
@@ -1665,7 +1685,7 @@ async function ensureSessionFileExists(input) {
1665
1685
  await writeFile(input.treeFile, `${JSON.stringify(header)}
1666
1686
  `, { flag: "wx" });
1667
1687
  } catch (error) {
1668
- if (isAlreadyExistsError(error)) {
1688
+ if (hasErrorCode(error, "EEXIST")) {
1669
1689
  return;
1670
1690
  }
1671
1691
  throw error;
@@ -1698,6 +1718,11 @@ function managedServicesKey(agentDir, sessionCwd) {
1698
1718
  }
1699
1719
  var SdkPiTreeHandleFactory = class {
1700
1720
  preparedServices = /* @__PURE__ */ new Map();
1721
+ /** @internal */
1722
+ constructor() {
1723
+ void import("@earendil-works/pi-coding-agent").catch(() => void 0);
1724
+ }
1725
+ /** @internal */
1701
1726
  async prepareManagedBootstrap(opts) {
1702
1727
  const services = await createManagedAgentSessionServices({
1703
1728
  agentDir: opts.agentDir,
@@ -1747,9 +1772,11 @@ var SdkPiTreeHandleFactory = class {
1747
1772
  diagnostics: diagnostics.map((diagnostic) => diagnostic.message)
1748
1773
  };
1749
1774
  }
1775
+ /** @internal */
1750
1776
  async inspectPrimaryTree(opts) {
1751
1777
  return inspectPiTreeForPlanning(opts);
1752
1778
  }
1779
+ /** @internal */
1753
1780
  async createPrimaryTreeHandle(opts) {
1754
1781
  const { CURRENT_SESSION_VERSION, createAgentSessionFromServices, SessionManager } = await import("@earendil-works/pi-coding-agent");
1755
1782
  const agentDir = resolvePiAgentDir({
@@ -1791,7 +1818,10 @@ var SdkPiTreeHandleFactory = class {
1791
1818
  sessionManager,
1792
1819
  ...modelSelection.model ? { model: modelSelection.model } : {},
1793
1820
  ...modelSelection.thinkingLevel ? { thinkingLevel: modelSelection.thinkingLevel } : {},
1794
- customTools: [LEITWERK_TOOL_BOOTSTRAP],
1821
+ customTools: [
1822
+ LEITWERK_TOOL_BOOTSTRAP,
1823
+ await createRepositoryBashTool(sessionCwd)
1824
+ ],
1795
1825
  noTools: "builtin"
1796
1826
  });
1797
1827
  getMutableSession(session)._refreshToolRegistry({ activeToolNames: [] });
@@ -1812,176 +1842,376 @@ var SdkPiTreeHandleFactory = class {
1812
1842
  }
1813
1843
  };
1814
1844
 
1815
- // src/managed-pi-agent-dir.ts
1816
- import { randomUUID } from "crypto";
1817
- import { chmod, lstat, mkdir as mkdir2, rename, writeFile as writeFile2 } from "fs/promises";
1818
- import { homedir } from "os";
1845
+ // src/development-tool-environment.ts
1846
+ import { statfsSync } from "fs";
1847
+ import { mkdir as mkdir2, rename, writeFile as writeFile2 } from "fs/promises";
1819
1848
  import path3 from "path";
1820
- function safeSegment(value, name) {
1821
- if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(value)) {
1822
- throw new Error(`Invalid managed Pi ${name}`);
1849
+ import { execa } from "execa";
1850
+ var PINNED_MISE_VERSION = "2026.8.14";
1851
+ var OUTPUT_LIMIT_BYTES = 64 * 1024;
1852
+ var JSON_LIMIT_BYTES = 1024 * 1024;
1853
+ var TRACE_CHUNK_LENGTH = 16 * 1024;
1854
+ var DevelopmentToolPreparationError = class extends Error {
1855
+ /** @internal */
1856
+ constructor(message, code, diagnostics = "") {
1857
+ super(message);
1858
+ this.code = code;
1859
+ this.diagnostics = diagnostics;
1860
+ this.name = "DevelopmentToolPreparationError";
1823
1861
  }
1824
- return value;
1825
- }
1826
- function resolveManagedPiAgentDir(input) {
1827
- const root = path3.resolve(input.agentDirRoot);
1828
- const ambient = path3.resolve(homedir(), ".pi", "agent");
1829
- if (root === ambient)
1830
- throw new Error("Managed Pi agent directory must not be ambient ~/.pi/agent");
1831
- return path3.join(
1832
- root,
1833
- safeSegment(input.instanceId, "instance id"),
1834
- safeSegment(input.startOrLeaseId, "start id")
1835
- );
1836
- }
1837
- function normalizeManagedPiCredentialPath(value) {
1838
- if (!value || path3.posix.isAbsolute(value) || value.includes("\\")) {
1839
- throw new Error(`Invalid credential file path '${value}'`);
1862
+ code;
1863
+ diagnostics;
1864
+ };
1865
+ function parseVersion(value) {
1866
+ const match = /(?:^|\s)(\d{4})\.(\d+)\.(\d+)(?:\s|$)/.exec(value);
1867
+ return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
1868
+ }
1869
+ function compareVersion(a, b) {
1870
+ for (let index = 0; index < 3; index++) {
1871
+ const difference = (a[index] ?? 0) - (b[index] ?? 0);
1872
+ if (difference !== 0) return difference;
1873
+ }
1874
+ return 0;
1875
+ }
1876
+ function validateMiseVersion(value, runner) {
1877
+ const parsed = parseVersion(value);
1878
+ const pinned = parseVersion(PINNED_MISE_VERSION);
1879
+ if (!parsed || !pinned) {
1880
+ throw new DevelopmentToolPreparationError(
1881
+ `Could not determine mise version from '${value.trim()}'`,
1882
+ "mise_unsupported"
1883
+ );
1840
1884
  }
1841
- const normalized = path3.posix.normalize(value);
1842
- if (normalized === "." || normalized === ".." || normalized.startsWith("../")) {
1843
- throw new Error(`Invalid credential file path '${value}'`);
1885
+ if (runner === "isolated" && compareVersion(parsed, pinned) !== 0 || runner === "local" && (parsed[0] !== pinned[0] || compareVersion(parsed, pinned) < 0)) {
1886
+ throw new DevelopmentToolPreparationError(
1887
+ `mise ${parsed.join(".")} is unsupported; expected ${runner === "isolated" ? PINNED_MISE_VERSION : `${PINNED_MISE_VERSION} or newer before ${pinned[0] + 1}.0.0`}`,
1888
+ "mise_unsupported"
1889
+ );
1844
1890
  }
1845
- return normalized;
1846
- }
1847
- async function assertNoSymlinkParents(root, target) {
1848
- let current = root;
1849
- for (const part of path3.relative(root, path3.dirname(target)).split(path3.sep).filter(Boolean)) {
1850
- current = path3.join(current, part);
1891
+ return parsed.join(".");
1892
+ }
1893
+ var SAFE_ENV_KEYS = /* @__PURE__ */ new Set([
1894
+ "HOME",
1895
+ "USER",
1896
+ "LOGNAME",
1897
+ "SHELL",
1898
+ "PATH",
1899
+ "TMPDIR",
1900
+ "TMP",
1901
+ "TEMP",
1902
+ "LANG",
1903
+ "TERM",
1904
+ "HTTP_PROXY",
1905
+ "HTTPS_PROXY",
1906
+ "ALL_PROXY",
1907
+ "NO_PROXY",
1908
+ "http_proxy",
1909
+ "https_proxy",
1910
+ "all_proxy",
1911
+ "no_proxy",
1912
+ "SSL_CERT_FILE",
1913
+ "SSL_CERT_DIR",
1914
+ "NODE_EXTRA_CA_CERTS",
1915
+ "XDG_CONFIG_HOME",
1916
+ "XDG_DATA_HOME",
1917
+ "XDG_CACHE_HOME",
1918
+ "XDG_STATE_HOME"
1919
+ ]);
1920
+ function buildMiseSubprocessEnvironment(base, config) {
1921
+ const env = {};
1922
+ for (const [key, value] of Object.entries(base)) {
1923
+ const safeMiseSetting = config.runner === "local" && key.startsWith("MISE_") && !/(?:TOKEN|PASSWORD|SECRET|AUTH|CREDENTIAL|API_KEY)/i.test(key);
1924
+ if (value !== void 0 && (SAFE_ENV_KEYS.has(key) || key.startsWith("LC_") || safeMiseSetting)) {
1925
+ env[key] = value;
1926
+ }
1927
+ }
1928
+ if (config.runner === "isolated") {
1929
+ const miseRoot = path3.join(config.processStorageRoot, "tooling", "mise");
1930
+ env.MISE_DATA_DIR = miseRoot;
1931
+ env.MISE_INSTALLS_DIR = path3.join(miseRoot, "installs");
1932
+ env.MISE_CACHE_DIR = path3.join(miseRoot, "cache");
1933
+ env.MISE_STATE_DIR = path3.join(miseRoot, "state");
1934
+ }
1935
+ return env;
1936
+ }
1937
+ function localShimDirectory(env) {
1938
+ if (env.MISE_DATA_DIR) return path3.join(env.MISE_DATA_DIR, "shims");
1939
+ if (env.XDG_DATA_HOME) return path3.join(env.XDG_DATA_HOME, "mise", "shims");
1940
+ return path3.join(env.HOME ?? "", ".local", "share", "mise", "shims");
1941
+ }
1942
+ function emitDiagnosticTrace(trace, value) {
1943
+ if (!trace) return;
1944
+ for (let offset = 0; offset < value.length; offset += TRACE_CHUNK_LENGTH) {
1945
+ trace(value.slice(offset, offset + TRACE_CHUNK_LENGTH));
1946
+ }
1947
+ }
1948
+ function appendBounded(current, chunk, limit) {
1949
+ const combined = current + chunk.toString("utf8");
1950
+ return Buffer.byteLength(combined) <= limit ? combined : Buffer.from(combined).subarray(-limit).toString("utf8");
1951
+ }
1952
+ async function runCommand(input) {
1953
+ if (input.signal?.aborted) {
1954
+ throw new DevelopmentToolPreparationError("mise preparation was cancelled", "cancelled");
1955
+ }
1956
+ const child = execa(input.command, input.args, {
1957
+ cwd: input.cwd,
1958
+ env: input.env,
1959
+ extendEnv: false,
1960
+ stdin: "ignore",
1961
+ detached: true,
1962
+ timeout: input.timeoutMs,
1963
+ cancelSignal: input.signal,
1964
+ forceKillAfterDelay: 2e3,
1965
+ reject: false,
1966
+ stripFinalNewline: false
1967
+ });
1968
+ let stdout = "";
1969
+ let stderr = "";
1970
+ const outputLimit = input.outputLimit ?? OUTPUT_LIMIT_BYTES;
1971
+ const appendOutput = (target, chunk) => {
1972
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
1973
+ const text = buffer.toString("utf8");
1974
+ emitDiagnosticTrace(input.onDiagnosticTrace, text);
1975
+ if (target === "stdout") stdout = appendBounded(stdout, buffer, outputLimit);
1976
+ else stderr = appendBounded(stderr, buffer, outputLimit);
1977
+ };
1978
+ child.stdout?.on("data", (chunk) => appendOutput("stdout", chunk));
1979
+ child.stderr?.on("data", (chunk) => appendOutput("stderr", chunk));
1980
+ let groupTermination = null;
1981
+ const killGroup = () => {
1982
+ if (!child.pid || groupTermination) return;
1983
+ const pid = child.pid;
1851
1984
  try {
1852
- if ((await lstat(current)).isSymbolicLink())
1853
- throw new Error(`Credential parent is a symlink: ${current}`);
1854
- } catch (error) {
1855
- if (error.code !== "ENOENT") throw error;
1856
- await mkdir2(current, { recursive: false, mode: 448 });
1985
+ process.kill(-pid, "SIGTERM");
1986
+ } catch {
1987
+ child.kill("SIGTERM");
1857
1988
  }
1989
+ groupTermination = new Promise((resolve) => {
1990
+ setTimeout(() => {
1991
+ try {
1992
+ process.kill(-pid, "SIGKILL");
1993
+ } catch {
1994
+ }
1995
+ resolve();
1996
+ }, 2e3);
1997
+ });
1998
+ };
1999
+ const groupTimeout = setTimeout(killGroup, input.timeoutMs);
2000
+ input.signal?.addEventListener("abort", killGroup, { once: true });
2001
+ try {
2002
+ const result = await child;
2003
+ const diagnostics = `${stdout}
2004
+ ${stderr}`.trim();
2005
+ if (input.signal?.aborted || result.isCanceled) {
2006
+ throw new DevelopmentToolPreparationError(
2007
+ "mise preparation was cancelled",
2008
+ "cancelled",
2009
+ diagnostics
2010
+ );
2011
+ }
2012
+ if (result.timedOut) {
2013
+ throw new DevelopmentToolPreparationError(
2014
+ `mise exceeded its ${input.timeoutMs}ms deadline`,
2015
+ "timeout",
2016
+ diagnostics
2017
+ );
2018
+ }
2019
+ if (result.code === "ENOENT") {
2020
+ throw new DevelopmentToolPreparationError(
2021
+ `mise command '${input.command}' was not found`,
2022
+ "mise_missing",
2023
+ diagnostics
2024
+ );
2025
+ }
2026
+ if (result.failed) {
2027
+ throw new Error(`${result.shortMessage}
2028
+ ${diagnostics}`);
2029
+ }
2030
+ return { stdout, stderr };
2031
+ } finally {
2032
+ clearTimeout(groupTimeout);
2033
+ input.signal?.removeEventListener("abort", killGroup);
2034
+ await groupTermination;
1858
2035
  }
1859
2036
  }
1860
- async function writeManagedPiCredentialFiles(agentDir, files) {
1861
- const root = path3.resolve(agentDir);
1862
- if ((await lstat(root)).isSymbolicLink()) {
1863
- throw new Error(`Managed Pi directory is a symlink: ${root}`);
1864
- }
1865
- const seen = /* @__PURE__ */ new Set();
1866
- for (const file of files) {
1867
- const relative = normalizeManagedPiCredentialPath(file.path);
1868
- if (seen.has(relative)) throw new Error(`Duplicate credential file path '${relative}'`);
1869
- seen.add(relative);
1870
- const target = path3.resolve(root, relative);
1871
- if (!target.startsWith(`${root}${path3.sep}`))
1872
- throw new Error(`Credential path escapes managed directory: ${relative}`);
1873
- await assertNoSymlinkParents(root, target);
1874
- const tmp = path3.join(
1875
- path3.dirname(target),
1876
- `.${path3.basename(target)}.tmp-${process.pid}-${randomUUID()}`
1877
- );
1878
- await writeFile2(tmp, file.content, { mode: 384, flag: "wx" });
1879
- await chmod(tmp, 384);
1880
- await rename(tmp, target);
1881
- await chmod(target, 384);
1882
- }
1883
- }
1884
-
1885
- // src/pi-resource-bundle.ts
1886
- import { randomUUID as randomUUID2 } from "crypto";
1887
- import { mkdir as mkdir3, rename as rename2, rm, writeFile as writeFile3 } from "fs/promises";
1888
- import path4 from "path";
1889
- import {
1890
- createCanonicalPiResourceBundle,
1891
- sha256Digest,
1892
- validateResourceRelativePath,
1893
- verifyCanonicalPiResourceBundle
1894
- } from "@leitwerk-dev/worker-protocol";
1895
- function fail(message) {
1896
- throw new Error(`Invalid Pi resource bundle: ${message}`);
1897
- }
1898
- async function writeExtractedFiles(root, files) {
1899
- for (const file of files) {
1900
- const output = path4.resolve(root, file.path);
1901
- if (path4.relative(root, output).startsWith("..") || path4.isAbsolute(path4.relative(root, output))) {
1902
- fail(`path escapes materialization root: ${file.path}`);
2037
+ function toolPair(candidate, fallbackName) {
2038
+ if (!candidate || typeof candidate !== "object") return null;
2039
+ const item = candidate;
2040
+ const name = [item.tool, item.name, item.plugin, fallbackName].find(
2041
+ (value) => typeof value === "string" && value.trim() !== ""
2042
+ );
2043
+ const version = [item.version, item.installed_version, item.requested_version].find(
2044
+ (value) => typeof value === "string" && value.trim() !== ""
2045
+ );
2046
+ return name && version ? { name, version } : null;
2047
+ }
2048
+ function normalizeMiseEvidence(value) {
2049
+ const tools = [];
2050
+ if (Array.isArray(value)) {
2051
+ for (const item of value) {
2052
+ const pair = toolPair(item);
2053
+ if (pair) tools.push(pair);
2054
+ }
2055
+ } else if (value && typeof value === "object") {
2056
+ for (const [name, item] of Object.entries(value)) {
2057
+ for (const candidate of Array.isArray(item) ? item : [item]) {
2058
+ const pair = typeof candidate === "string" ? { name, version: candidate } : toolPair(candidate, name);
2059
+ if (pair) tools.push(pair);
2060
+ }
1903
2061
  }
1904
- await mkdir3(path4.dirname(output), { recursive: true, mode: 448 });
1905
- await writeFile3(output, file.content, { mode: 420, flag: "wx" });
1906
2062
  }
2063
+ return [...new Map(tools.map((tool) => [`${tool.name}\0${tool.version}`, tool])).values()].sort(
2064
+ (a, b) => a.name.localeCompare(b.name) || a.version.localeCompare(b.version)
2065
+ );
1907
2066
  }
1908
- async function materializeCanonicalPiResourceBundle(input) {
1909
- const files = verifyCanonicalPiResourceBundle(input.bundle, input.digest);
1910
- const targetDir = path4.resolve(input.targetDir);
1911
- const parent = path4.dirname(targetDir);
1912
- await mkdir3(parent, { recursive: true, mode: 448 });
1913
- const marker = path4.join(targetDir, ".leitwerk-resource-digest");
2067
+ function availableSpace(root) {
1914
2068
  try {
1915
- const current = await import("fs/promises").then(
1916
- ({ readFile: readFile4 }) => readFile4(marker, "utf8")
1917
- );
1918
- if (current === `${input.digest}
1919
- `) return { targetDir, reused: true };
1920
- throw new Error(
1921
- `Managed Pi directory already exists with a different resource digest: ${targetDir}`
2069
+ const stats = statfsSync(root);
2070
+ return `${Number(stats.bavail) * Number(stats.bsize)} bytes available`;
2071
+ } catch {
2072
+ return null;
2073
+ }
2074
+ }
2075
+ function translateCommandError(error, input) {
2076
+ if (error instanceof DevelopmentToolPreparationError) {
2077
+ if (error.code !== "timeout") return error;
2078
+ return new DevelopmentToolPreparationError(
2079
+ `mise ${input.operation} timed out for repository '${input.repositoryKey}' after ${input.timeoutMs}ms`,
2080
+ "timeout",
2081
+ error.diagnostics
1922
2082
  );
1923
- } catch (error) {
1924
- if (error.code !== "ENOENT") throw error;
1925
2083
  }
1926
- const staging = path4.join(
1927
- parent,
1928
- `.${path4.basename(targetDir)}.staging-${process.pid}-${randomUUID2()}`
2084
+ const space = input.operation === "install" ? availableSpace(input.root) : null;
2085
+ return new DevelopmentToolPreparationError(
2086
+ `${input.failureMessage} '${input.repositoryKey}'${space ? ` (${space})` : ""}`,
2087
+ input.operation === "install" ? "install_failed" : "verification_failed",
2088
+ error instanceof Error ? error.message : String(error)
1929
2089
  );
1930
- try {
1931
- await mkdir3(staging, { mode: 448 });
1932
- await writeExtractedFiles(staging, files);
1933
- await writeFile3(path4.join(staging, ".leitwerk-resource-digest"), `${input.digest}
1934
- `, {
1935
- mode: 384,
1936
- flag: "wx"
2090
+ }
2091
+ var MiseDevelopmentToolEnvironment = class {
2092
+ /** @internal */
2093
+ constructor(baseEnv = process.env) {
2094
+ this.baseEnv = baseEnv;
2095
+ }
2096
+ baseEnv;
2097
+ /** @internal */
2098
+ async prepare(input) {
2099
+ const env = buildMiseSubprocessEnvironment(this.baseEnv, input.config);
2100
+ const versionResult = await runCommand({
2101
+ command: input.config.miseCommand,
2102
+ args: ["--version"],
2103
+ cwd: input.config.processStorageRoot,
2104
+ env,
2105
+ timeoutMs: Math.min(input.config.installTimeoutMs, 3e4),
2106
+ signal: input.signal,
2107
+ onDiagnosticTrace: input.onDiagnosticTrace
1937
2108
  });
1938
- await rename2(staging, targetDir);
1939
- return { targetDir, reused: false };
1940
- } catch (error) {
1941
- await rm(staging, { recursive: true, force: true });
1942
- if (error.code === "EEXIST") {
1943
- const current = await import("fs/promises").then(
1944
- ({ readFile: readFile4 }) => readFile4(marker, "utf8")
2109
+ const miseVersion = validateMiseVersion(
2110
+ versionResult.stdout || versionResult.stderr,
2111
+ input.config.runner
2112
+ );
2113
+ if (input.config.runner === "isolated") {
2114
+ await Promise.all(
2115
+ [env.MISE_DATA_DIR, env.MISE_INSTALLS_DIR, env.MISE_CACHE_DIR, env.MISE_STATE_DIR].filter((value) => Boolean(value)).map((directory) => mkdir2(directory, { recursive: true }))
1945
2116
  );
1946
- if (current === `${input.digest}
1947
- `) return { targetDir, reused: true };
1948
2117
  }
1949
- throw error;
1950
- }
1951
- }
1952
-
1953
- // src/runtime/adapters.ts
1954
- var nodeWorkerRuntimeScheduler = {
1955
- setTimeout(handler, delayMs) {
1956
- return setTimeout(handler, delayMs);
1957
- },
1958
- clearTimeout(timer) {
1959
- clearTimeout(timer);
1960
- },
1961
- sleep(delayMs) {
1962
- return new Promise((resolve) => setTimeout(resolve, delayMs));
1963
- },
1964
- now() {
1965
- return /* @__PURE__ */ new Date();
2118
+ const shimDirectory = input.config.runner === "isolated" ? path3.join(env.MISE_DATA_DIR, "shims") : localShimDirectory({ ...this.baseEnv, ...env });
2119
+ env.PATH = [shimDirectory, env.PATH].filter(Boolean).join(path3.delimiter);
2120
+ const repositories = [];
2121
+ const warnings = [];
2122
+ for (const repository of [...input.repositories].sort(
2123
+ (a, b) => a.repositoryKey.localeCompare(b.repositoryKey)
2124
+ )) {
2125
+ const repositoryStartedAt = Date.now();
2126
+ input.onProgress?.(repository.repositoryKey, "installing");
2127
+ try {
2128
+ const installed = await runCommand({
2129
+ command: input.config.miseCommand,
2130
+ args: ["install"],
2131
+ cwd: repository.workingDirectory,
2132
+ env,
2133
+ timeoutMs: input.config.installTimeoutMs,
2134
+ signal: input.signal,
2135
+ onDiagnosticTrace: input.onDiagnosticTrace
2136
+ });
2137
+ if (installed.stderr.trim()) {
2138
+ warnings.push(`${repository.repositoryKey}: ${installed.stderr.trim()}`);
2139
+ }
2140
+ } catch (error) {
2141
+ throw translateCommandError(error, {
2142
+ operation: "install",
2143
+ failureMessage: "mise install failed for repository",
2144
+ repositoryKey: repository.repositoryKey,
2145
+ timeoutMs: input.config.installTimeoutMs,
2146
+ root: input.config.processStorageRoot
2147
+ });
2148
+ }
2149
+ input.onProgress?.(repository.repositoryKey, "verifying");
2150
+ let current;
2151
+ try {
2152
+ current = await runCommand({
2153
+ command: input.config.miseCommand,
2154
+ args: ["ls", "--current", "--json"],
2155
+ cwd: repository.workingDirectory,
2156
+ env,
2157
+ timeoutMs: Math.max(
2158
+ 1,
2159
+ input.config.installTimeoutMs - (Date.now() - repositoryStartedAt)
2160
+ ),
2161
+ signal: input.signal,
2162
+ outputLimit: JSON_LIMIT_BYTES,
2163
+ onDiagnosticTrace: input.onDiagnosticTrace
2164
+ });
2165
+ } catch (error) {
2166
+ throw translateCommandError(error, {
2167
+ operation: "verification",
2168
+ failureMessage: "mise could not verify repository",
2169
+ repositoryKey: repository.repositoryKey,
2170
+ timeoutMs: input.config.installTimeoutMs,
2171
+ root: input.config.processStorageRoot
2172
+ });
2173
+ }
2174
+ let parsed;
2175
+ try {
2176
+ parsed = JSON.parse(current.stdout);
2177
+ } catch {
2178
+ throw new DevelopmentToolPreparationError(
2179
+ `mise returned invalid current-tool evidence for repository '${repository.repositoryKey}'`,
2180
+ "verification_failed"
2181
+ );
2182
+ }
2183
+ if (current.stderr.trim()) {
2184
+ warnings.push(`${repository.repositoryKey}: ${current.stderr.trim()}`);
2185
+ }
2186
+ repositories.push({ ...repository, tools: normalizeMiseEvidence(parsed) });
2187
+ }
2188
+ const commandEnvironment = {
2189
+ ...this.baseEnv,
2190
+ ...Object.fromEntries(Object.entries(env).filter(([key]) => key.startsWith("MISE_"))),
2191
+ PATH: [shimDirectory, this.baseEnv.PATH].filter(Boolean).join(path3.delimiter)
2192
+ };
2193
+ const evidenceDir = path3.join(input.config.processStorageRoot, "tooling", "mise-preparation");
2194
+ await mkdir2(evidenceDir, { recursive: true });
2195
+ const evidence = {
2196
+ schemaVersion: 1,
2197
+ preparedAt: (/* @__PURE__ */ new Date()).toISOString(),
2198
+ miseVersion,
2199
+ repositories
2200
+ };
2201
+ const temporary = path3.join(evidenceDir, `.latest-${process.pid}.json`);
2202
+ await writeFile2(temporary, `${JSON.stringify(evidence, null, 2)}
2203
+ `, { mode: 384 });
2204
+ await rename(temporary, path3.join(evidenceDir, "latest.json"));
2205
+ return { miseVersion, commandEnvironment, repositories, warnings };
1966
2206
  }
1967
2207
  };
1968
2208
 
1969
2209
  // src/input-consumer.ts
1970
2210
  function classifyDeliveryMode(input, sessionHasActiveTurn) {
1971
- if (input.kind === "system_event") {
1972
- return "steer";
1973
- }
1974
- if (sessionHasActiveTurn) {
1975
- return "steer";
1976
- }
1977
- return "prompt";
2211
+ return input.kind === "system_event" || sessionHasActiveTurn ? "steer" : "prompt";
1978
2212
  }
1979
2213
  async function deliverInput(session, input, mode) {
1980
- if (mode === "prompt") {
1981
- await session.prompt(input.bodyMarkdown);
1982
- } else {
1983
- await session.steer(input.bodyMarkdown);
1984
- }
2214
+ await session[mode](input.bodyMarkdown);
1985
2215
  return {
1986
2216
  inputId: input.inputId,
1987
2217
  sequence: input.sequence,
@@ -2122,6 +2352,9 @@ var WorkerIntegrationToolBridge = class {
2122
2352
  }
2123
2353
  };
2124
2354
 
2355
+ // src/pi-event-reporter.ts
2356
+ import { readFiniteNumber as readFiniteNumber2, readNonBlankString } from "@leitwerk-dev/domain";
2357
+
2125
2358
  // src/event-translator.ts
2126
2359
  function translatePiEvent(piEvent, currentSelectedTurnId) {
2127
2360
  return {
@@ -2136,23 +2369,6 @@ function translatePiEvent(piEvent, currentSelectedTurnId) {
2136
2369
  }
2137
2370
 
2138
2371
  // src/pi-event-reporter.ts
2139
- function readPiEventString(data, key) {
2140
- const value = data[key];
2141
- return typeof value === "string" && value.trim() !== "" ? value : null;
2142
- }
2143
- function readPiEventNumber(data, key) {
2144
- const value = data[key];
2145
- if (typeof value === "number" && Number.isFinite(value)) {
2146
- return value;
2147
- }
2148
- if (typeof value === "string" && value.trim() !== "") {
2149
- const parsed = Number(value);
2150
- if (Number.isFinite(parsed)) {
2151
- return parsed;
2152
- }
2153
- }
2154
- return null;
2155
- }
2156
2372
  function createPiEventReporter(options) {
2157
2373
  let currentPiAttempt = 1;
2158
2374
  let currentPiMaxAttempts = null;
@@ -2161,12 +2377,12 @@ function createPiEventReporter(options) {
2161
2377
  currentPiMaxAttempts = null;
2162
2378
  };
2163
2379
  const reportPiError = (event) => {
2164
- const message = readPiEventString(event.data, "message") ?? readPiEventString(event.data, "errorMessage") ?? "Pi reported an error";
2165
- const toolName = readPiEventString(event.data, "toolName");
2166
- const source = readPiEventString(event.data, "source");
2167
- const provider = readPiEventString(event.data, "provider");
2168
- const model = readPiEventString(event.data, "model");
2169
- const stopReason = readPiEventString(event.data, "stopReason");
2380
+ const message = readNonBlankString(event.data.message) ?? readNonBlankString(event.data.errorMessage) ?? "Pi reported an error";
2381
+ const toolName = readNonBlankString(event.data.toolName);
2382
+ const source = readNonBlankString(event.data.source);
2383
+ const provider = readNonBlankString(event.data.provider);
2384
+ const model = readNonBlankString(event.data.model);
2385
+ const stopReason = readNonBlankString(event.data.stopReason);
2170
2386
  options.reporter.workerError({
2171
2387
  level: "error",
2172
2388
  code: toolName || source === "tool" ? "pi.tool_error" : "pi.request_failed",
@@ -2186,12 +2402,12 @@ function createPiEventReporter(options) {
2186
2402
  });
2187
2403
  };
2188
2404
  const reportPiRetryLifecycle = (event) => {
2189
- const attempt = readPiEventNumber(event.data, "attempt");
2190
- const maxAttempts = readPiEventNumber(event.data, "maxAttempts");
2191
- const delayMs = readPiEventNumber(event.data, "delayMs");
2192
- const errorMessage = readPiEventString(event.data, "errorMessage");
2193
- const finalError = readPiEventString(event.data, "finalError");
2194
- const message = readPiEventString(event.data, "message") ?? (event.type === "retry.start" ? "Pi scheduled an automatic retry" : event.data.success === true ? "Pi retry sequence succeeded" : "Pi retry sequence ended");
2405
+ const attempt = readFiniteNumber2(event.data.attempt);
2406
+ const maxAttempts = readFiniteNumber2(event.data.maxAttempts);
2407
+ const delayMs = readFiniteNumber2(event.data.delayMs);
2408
+ const errorMessage = readNonBlankString(event.data.errorMessage);
2409
+ const finalError = readNonBlankString(event.data.finalError);
2410
+ const message = readNonBlankString(event.data.message) ?? (event.type === "retry.start" ? "Pi scheduled an automatic retry" : event.data.success === true ? "Pi retry sequence succeeded" : "Pi retry sequence ended");
2195
2411
  const success = event.data.success === true;
2196
2412
  options.reporter.workerTrace({
2197
2413
  level: event.type === "retry.end" && success ? "info" : "warn",
@@ -2253,13 +2469,9 @@ function createPiEventReporter(options) {
2253
2469
  );
2254
2470
  options.emitExtensionEvent?.("worker.pi_event", payload);
2255
2471
  });
2256
- piHandle.subscribeDiagnostics?.((diagnostic) => {
2257
- reportPiDiagnostic(diagnostic);
2258
- });
2472
+ piHandle.subscribeDiagnostics?.(reportPiDiagnostic);
2259
2473
  },
2260
- resetRetryState() {
2261
- resetPiRetryState();
2262
- }
2474
+ resetRetryState: resetPiRetryState
2263
2475
  };
2264
2476
  }
2265
2477
 
@@ -2312,7 +2524,7 @@ function resolveRootEntryIdFromHandle(piHandle) {
2312
2524
  const currentLeafId = piHandle.getLeafId();
2313
2525
  const currentBranch = piHandle.getBranch(currentLeafId ?? void 0);
2314
2526
  const topLevelNodes = piHandle.getTree();
2315
- return resolveRootEntryId({ currentLeafId, currentBranch, topLevelNodes });
2527
+ return resolveRootEntryId({ currentBranch, topLevelNodes });
2316
2528
  }
2317
2529
  function resolveContextAwareTurnStartSelection(input) {
2318
2530
  const authoredSelection = resolveProcessTurnStartSelection(input.turnDef);
@@ -2332,11 +2544,7 @@ function resolveContextAwareTurnStartSelection(input) {
2332
2544
  }
2333
2545
  function planTurnTreeExecution(input) {
2334
2546
  const startTarget = resolveProcessTurnStartTarget({
2335
- selection: resolveContextAwareTurnStartSelection({
2336
- turnDef: input.turnDef,
2337
- preTurnStartSelection: input.preTurnStartSelection,
2338
- hasPreTurnTargetedInputs: input.hasPreTurnTargetedInputs
2339
- }),
2547
+ selection: resolveContextAwareTurnStartSelection(input),
2340
2548
  branchType: input.turnDef.branchType,
2341
2549
  currentLeafId: input.currentLeafId,
2342
2550
  rootEntryId: input.rootEntryId,
@@ -2353,18 +2561,10 @@ function planTurnTreeExecution(input) {
2353
2561
  };
2354
2562
  }
2355
2563
  async function positionHandleForTurn(piHandle, plan) {
2356
- switch (plan.startTarget.kind) {
2357
- case "current_leaf": {
2358
- return;
2359
- }
2360
- case "entry": {
2361
- await piHandle.branch(plan.startTarget.entryId);
2362
- return;
2363
- }
2364
- case "root": {
2365
- await piHandle.branchFromRoot();
2366
- return;
2367
- }
2564
+ if (plan.startTarget.kind === "entry") {
2565
+ await piHandle.branch(plan.startTarget.entryId);
2566
+ } else if (plan.startTarget.kind === "root") {
2567
+ await piHandle.branchFromRoot();
2368
2568
  }
2369
2569
  }
2370
2570
  async function restoreHandleAfterTurn(piHandle, plan) {
@@ -2379,7 +2579,7 @@ async function restoreHandleAfterTurn(piHandle, plan) {
2379
2579
  }
2380
2580
 
2381
2581
  // src/worker-ipc-reporter.ts
2382
- import { randomUUID as randomUUID3 } from "crypto";
2582
+ import { randomUUID } from "crypto";
2383
2583
  import { createIpcMessage } from "@leitwerk-dev/worker-protocol";
2384
2584
 
2385
2585
  // src/diagnostics.ts
@@ -2451,7 +2651,7 @@ function createWorkerIpcReporter(options) {
2451
2651
  options.send(
2452
2652
  createIpcMessage({
2453
2653
  type: fact.type,
2454
- messageId: randomUUID3(),
2654
+ messageId: randomUUID(),
2455
2655
  instanceId: options.instanceId,
2456
2656
  workerId: options.workerId,
2457
2657
  sentAt: options.now().toISOString(),
@@ -2473,31 +2673,82 @@ function createWorkerIpcReporter(options) {
2473
2673
  options.emitExtensionEvent?.("worker.event", payload);
2474
2674
  return payload;
2475
2675
  };
2676
+ const diagnosticReporter = (eventType) => (input, selectedTurnId = null) => {
2677
+ const payload = workerEvent(eventType, buildWorkerDiagnosticPayload(input), selectedTurnId);
2678
+ options.emitExtensionEvent?.(eventType, payload);
2679
+ };
2476
2680
  return {
2477
2681
  project,
2478
2682
  workerEvent,
2479
- workerTrace(input, selectedTurnId = null) {
2480
- const payload = workerEvent(
2481
- "worker.trace",
2482
- buildWorkerDiagnosticPayload(input),
2483
- selectedTurnId
2484
- );
2485
- options.emitExtensionEvent?.("worker.trace", payload);
2486
- },
2487
- workerError(input, selectedTurnId = null) {
2488
- const payload = workerEvent(
2489
- "worker.error",
2490
- buildWorkerDiagnosticPayload(input),
2491
- selectedTurnId
2492
- );
2493
- options.emitExtensionEvent?.("worker.error", payload);
2494
- }
2683
+ workerTrace: diagnosticReporter("worker.trace"),
2684
+ workerError: diagnosticReporter("worker.error")
2495
2685
  };
2496
2686
  }
2497
2687
 
2498
2688
  // src/runtime/bootstrap-session.ts
2499
- import { readFile as readFile2 } from "fs/promises";
2500
- import path8 from "path";
2689
+ import { readFile as readFile3 } from "fs/promises";
2690
+ import path9 from "path";
2691
+
2692
+ // src/docker-registry-credentials.ts
2693
+ import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "fs";
2694
+ import {
2695
+ dockerRegistryCredentialSchema
2696
+ } from "@leitwerk-dev/worker-protocol";
2697
+ import { is } from "valibot";
2698
+ var DockerRegistryCredentials = class {
2699
+ #directory;
2700
+ #previousConfig;
2701
+ #onExit = () => this.dispose();
2702
+ install(credentials, dockerEnabled) {
2703
+ this.dispose();
2704
+ if (!dockerEnabled) {
2705
+ if (credentials.length)
2706
+ throw new Error("Docker credentials require a Docker-enabled process");
2707
+ return;
2708
+ }
2709
+ const auths = /* @__PURE__ */ Object.create(null);
2710
+ for (const credential of credentials) {
2711
+ if (!is(dockerRegistryCredentialSchema, credential))
2712
+ throw new Error("Invalid Docker registry credentials");
2713
+ if (Object.hasOwn(auths, credential.registry))
2714
+ throw new Error("Duplicate Docker registry credentials");
2715
+ auths[credential.registry] = {
2716
+ auth: Buffer.from(`${credential.username}:${credential.password}`).toString("base64")
2717
+ };
2718
+ }
2719
+ try {
2720
+ this.#directory = mkdtempSync("/tmp/leitwerk-docker-auth-");
2721
+ chmodSync(this.#directory, 448);
2722
+ mkdirSync(`${this.#directory}/auth`, { mode: 448 });
2723
+ writeFileSync(`${this.#directory}/auth/config.json`, JSON.stringify({ auths }), {
2724
+ mode: 384,
2725
+ flag: "wx"
2726
+ });
2727
+ this.#previousConfig = process.env.DOCKER_CONFIG;
2728
+ process.env.DOCKER_CONFIG = `${this.#directory}/auth`;
2729
+ if (!process.env.BUILDX_CONFIG) {
2730
+ mkdirSync(`${this.#directory}/buildx`, { mode: 448 });
2731
+ process.env.BUILDX_CONFIG = `${this.#directory}/buildx`;
2732
+ }
2733
+ process.once("exit", this.#onExit);
2734
+ } catch {
2735
+ this.dispose();
2736
+ throw new Error("Cannot materialize private Docker credentials");
2737
+ }
2738
+ }
2739
+ dispose() {
2740
+ process.off("exit", this.#onExit);
2741
+ if (!this.#directory) return;
2742
+ if (process.env.BUILDX_CONFIG === `${this.#directory}/buildx`) delete process.env.BUILDX_CONFIG;
2743
+ if (process.env.DOCKER_CONFIG === `${this.#directory}/auth`) {
2744
+ if (this.#previousConfig === void 0) delete process.env.DOCKER_CONFIG;
2745
+ else process.env.DOCKER_CONFIG = this.#previousConfig;
2746
+ }
2747
+ rmSync(this.#directory, { recursive: true, force: true });
2748
+ this.#directory = void 0;
2749
+ this.#previousConfig = void 0;
2750
+ }
2751
+ };
2501
2752
 
2502
2753
  // src/worker-start-payload.ts
2503
2754
  function isLlmWorkerStartPayload(payload) {
@@ -2505,55 +2756,129 @@ function isLlmWorkerStartPayload(payload) {
2505
2756
  }
2506
2757
 
2507
2758
  // src/runtime/bootstrap.ts
2508
- import path7 from "path";
2759
+ import path8 from "path";
2760
+ import {
2761
+ readNonBlankString as readNonEmptyString2
2762
+ } from "@leitwerk-dev/domain";
2763
+ import { repositoryHttpsUrl } from "@leitwerk-dev/process-sdk";
2509
2764
  import { createTemplateContext, resolveProcessPiConfig } from "@leitwerk-dev/process-sdk/pi-config";
2510
2765
 
2511
- // src/managed-pi-bootstrap.ts
2512
- import { lstat as lstat2, readFile } from "fs/promises";
2513
- import path5 from "path";
2514
- import { VERSION as PI_VERSION } from "@earendil-works/pi-coding-agent";
2515
- import {
2516
- canonicalJsonEqual,
2517
- IPC_PROTOCOL_VERSION,
2518
- parsePiResourceManifest,
2519
- WORKER_API_VERSION
2520
- } from "@leitwerk-dev/worker-protocol";
2521
- function fail2(message) {
2522
- throw new Error(`Invalid managed Pi resource snapshot: ${message}`);
2523
- }
2524
- function record(value, location) {
2525
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
2526
- fail2(`${location} must be an object`);
2766
+ // src/managed-pi-agent-dir.ts
2767
+ import { randomUUID as randomUUID2 } from "crypto";
2768
+ import { chmod, lstat, mkdir as mkdir3, rename as rename2, writeFile as writeFile3 } from "fs/promises";
2769
+ import { homedir } from "os";
2770
+ import path4 from "path";
2771
+ function safeSegment(value, name) {
2772
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(value)) {
2773
+ throw new Error(`Invalid managed Pi ${name}`);
2527
2774
  }
2528
2775
  return value;
2529
2776
  }
2530
- function assertJsonEqual(actual, expected, location) {
2531
- if (!canonicalJsonEqual(actual, expected)) {
2532
- fail2(`${location} does not match the resolved LLM start`);
2533
- }
2534
- }
2535
- function assertModelMatchesStart(manifest, start) {
2536
- for (const key of ["profileId", "providerId", "modelId", "thinkingLevel"]) {
2537
- if (manifest.model[key] !== start.model[key]) {
2538
- fail2(
2539
- `generated.json model ${key} '${manifest.model[key]}' does not match start '${start.model[key]}'`
2540
- );
2777
+ function resolveManagedPiAgentDir(input) {
2778
+ const root = path4.resolve(input.agentDirRoot);
2779
+ const ambient = path4.resolve(homedir(), ".pi", "agent");
2780
+ if (root === ambient)
2781
+ throw new Error("Managed Pi agent directory must not be ambient ~/.pi/agent");
2782
+ return path4.join(
2783
+ root,
2784
+ safeSegment(input.instanceId, "instance id"),
2785
+ safeSegment(input.startOrLeaseId, "start id")
2786
+ );
2787
+ }
2788
+ function normalizeManagedPiCredentialPath(value) {
2789
+ if (!value || path4.posix.isAbsolute(value) || value.includes("\\")) {
2790
+ throw new Error(`Invalid credential file path '${value}'`);
2791
+ }
2792
+ const normalized = path4.posix.normalize(value);
2793
+ if (normalized === "." || normalized === ".." || normalized.startsWith("../")) {
2794
+ throw new Error(`Invalid credential file path '${value}'`);
2795
+ }
2796
+ return normalized;
2797
+ }
2798
+ async function assertNoSymlinkParents(root, target) {
2799
+ let current = root;
2800
+ for (const part of path4.relative(root, path4.dirname(target)).split(path4.sep).filter(Boolean)) {
2801
+ current = path4.join(current, part);
2802
+ try {
2803
+ if ((await lstat(current)).isSymbolicLink())
2804
+ throw new Error(`Credential parent is a symlink: ${current}`);
2805
+ } catch (error) {
2806
+ if (error.code !== "ENOENT") throw error;
2807
+ await mkdir3(current, { recursive: false, mode: 448 });
2808
+ }
2809
+ }
2810
+ }
2811
+ async function writeManagedPiCredentialFiles(agentDir, files) {
2812
+ const root = path4.resolve(agentDir);
2813
+ if ((await lstat(root)).isSymbolicLink()) {
2814
+ throw new Error(`Managed Pi directory is a symlink: ${root}`);
2815
+ }
2816
+ const seen = /* @__PURE__ */ new Set();
2817
+ for (const file of files) {
2818
+ const relative = normalizeManagedPiCredentialPath(file.path);
2819
+ if (seen.has(relative)) throw new Error(`Duplicate credential file path '${relative}'`);
2820
+ seen.add(relative);
2821
+ const target = path4.resolve(root, relative);
2822
+ if (!target.startsWith(`${root}${path4.sep}`))
2823
+ throw new Error(`Credential path escapes managed directory: ${relative}`);
2824
+ await assertNoSymlinkParents(root, target);
2825
+ const tmp = path4.join(
2826
+ path4.dirname(target),
2827
+ `.${path4.basename(target)}.tmp-${process.pid}-${randomUUID2()}`
2828
+ );
2829
+ await writeFile3(tmp, file.content, { mode: 384, flag: "wx" });
2830
+ await chmod(tmp, 384);
2831
+ await rename2(tmp, target);
2832
+ await chmod(target, 384);
2833
+ }
2834
+ }
2835
+
2836
+ // src/managed-pi-bootstrap.ts
2837
+ import { lstat as lstat2, readFile } from "fs/promises";
2838
+ import path5 from "path";
2839
+ import {
2840
+ canonicalJsonEqual,
2841
+ IPC_PROTOCOL_VERSION,
2842
+ parsePiResourceManifest,
2843
+ WORKER_API_VERSION
2844
+ } from "@leitwerk-dev/worker-protocol";
2845
+ function fail(message) {
2846
+ throw new Error(`Invalid managed Pi resource snapshot: ${message}`);
2847
+ }
2848
+ function record(value, location) {
2849
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
2850
+ fail(`${location} must be an object`);
2851
+ }
2852
+ return value;
2853
+ }
2854
+ function assertJsonEqual(actual, expected, location) {
2855
+ if (!canonicalJsonEqual(actual, expected)) {
2856
+ fail(`${location} does not match the resolved LLM start`);
2857
+ }
2858
+ }
2859
+ function assertModelMatchesStart(manifest, start) {
2860
+ for (const key of ["profileId", "providerId", "modelId", "thinkingLevel"]) {
2861
+ if (manifest.model[key] !== start.model[key]) {
2862
+ fail(
2863
+ `generated.json model ${key} '${manifest.model[key]}' does not match start '${start.model[key]}'`
2864
+ );
2541
2865
  }
2542
2866
  }
2543
2867
  }
2544
- function assertCompatibility(manifest) {
2868
+ async function assertCompatibility(manifest) {
2869
+ const { VERSION: PI_VERSION } = await import("@earendil-works/pi-coding-agent");
2545
2870
  if (manifest.compatibility.workerApiVersion !== WORKER_API_VERSION) {
2546
- fail2(
2871
+ fail(
2547
2872
  `server snapshot worker API version '${manifest.compatibility.workerApiVersion}' does not match local worker API version '${WORKER_API_VERSION}'`
2548
2873
  );
2549
2874
  }
2550
2875
  if (manifest.compatibility.piVersion !== PI_VERSION) {
2551
- fail2(
2876
+ fail(
2552
2877
  `server snapshot Pi version '${manifest.compatibility.piVersion}' does not match local worker Pi version '${PI_VERSION}'`
2553
2878
  );
2554
2879
  }
2555
2880
  if (manifest.compatibility.protocolVersion !== void 0 && manifest.compatibility.protocolVersion !== IPC_PROTOCOL_VERSION) {
2556
- fail2(
2881
+ fail(
2557
2882
  `server snapshot protocol version '${manifest.compatibility.protocolVersion}' does not match local worker protocol version '${IPC_PROTOCOL_VERSION}'`
2558
2883
  );
2559
2884
  }
@@ -2562,7 +2887,7 @@ async function readAndValidateManagedPiResourceManifest(input) {
2562
2887
  const marker = await readFile(path5.join(input.agentDir, ".leitwerk-resource-digest"), "utf8");
2563
2888
  if (marker !== `${input.resourceDigest}
2564
2889
  `) {
2565
- fail2("materialized resource digest marker does not match the delivered bundle");
2890
+ fail("materialized resource digest marker does not match the delivered bundle");
2566
2891
  }
2567
2892
  let parsed;
2568
2893
  try {
@@ -2574,7 +2899,7 @@ async function readAndValidateManagedPiResourceManifest(input) {
2574
2899
  }
2575
2900
  const manifest = parsePiResourceManifest(parsed);
2576
2901
  assertModelMatchesStart(manifest, input.start);
2577
- assertCompatibility(manifest);
2902
+ await assertCompatibility(manifest);
2578
2903
  assertJsonEqual(manifest.providerOptions, input.start.providerOptions, "providerOptions");
2579
2904
  assertJsonEqual(
2580
2905
  manifest.providerWorkerConfig,
@@ -2635,11 +2960,11 @@ function buildManagedPiCredentialFiles(input) {
2635
2960
  async function assertManagedPiCredentialFiles(input) {
2636
2961
  for (const credentialPath of input.manifest.declaredCredentialPaths) {
2637
2962
  const target = path5.join(input.agentDir, credentialPath);
2638
- const stat3 = await lstat2(target).catch(() => null);
2639
- if (!stat3?.isFile() || stat3.isSymbolicLink()) {
2963
+ const stat2 = await lstat2(target).catch(() => null);
2964
+ if (!stat2?.isFile() || stat2.isSymbolicLink()) {
2640
2965
  throw new Error(`Declared credential file '${credentialPath}' is missing or unsafe`);
2641
2966
  }
2642
- if ((stat3.mode & 511) !== 384) {
2967
+ if ((stat2.mode & 511) !== 384) {
2643
2968
  throw new Error(`Declared credential file '${credentialPath}' must have mode 0600`);
2644
2969
  }
2645
2970
  }
@@ -2672,6 +2997,129 @@ async function assertManagedPiCredentialFiles(input) {
2672
2997
  }
2673
2998
  }
2674
2999
 
3000
+ // src/pi-resource-bundle.ts
3001
+ import { randomUUID as randomUUID3 } from "crypto";
3002
+ import { mkdir as mkdir4, open, readFile as readFile2, rename as rename3, rm, writeFile as writeFile4 } from "fs/promises";
3003
+ import path6 from "path";
3004
+ import {
3005
+ createCanonicalPiResourceBundle,
3006
+ sha256Digest,
3007
+ validateResourceRelativePath,
3008
+ verifyCanonicalPiResourceBundle
3009
+ } from "@leitwerk-dev/worker-protocol";
3010
+ function fail2(message) {
3011
+ throw new Error(`Invalid Pi resource bundle: ${message}`);
3012
+ }
3013
+ function requireStorageName(value, label) {
3014
+ if (!/^[a-zA-Z0-9_-]+$/u.test(value)) fail2(`unsafe ${label}: ${value}`);
3015
+ return value;
3016
+ }
3017
+ async function atomicWrite(pathname, content, mode) {
3018
+ const staging = `${pathname}.staging-${process.pid}-${randomUUID3()}`;
3019
+ const handle = await open(staging, "wx", mode);
3020
+ try {
3021
+ await handle.writeFile(content);
3022
+ await handle.sync();
3023
+ } finally {
3024
+ await handle.close();
3025
+ }
3026
+ try {
3027
+ await rename3(staging, pathname);
3028
+ } catch (error) {
3029
+ await rm(staging, { force: true });
3030
+ throw error;
3031
+ }
3032
+ }
3033
+ async function persistPiResourceBundleForStart(input) {
3034
+ const digest = requireStorageName(input.digest, "resource digest");
3035
+ const startRecordId = requireStorageName(input.startRecordId, "turn-start id");
3036
+ const bundlesDir = path6.resolve(input.bundlesDir);
3037
+ const startsDir = path6.join(bundlesDir, "starts");
3038
+ const bundlePath = path6.join(bundlesDir, `${digest}.tar`);
3039
+ await mkdir4(startsDir, { recursive: true, mode: 448 });
3040
+ let bundle = null;
3041
+ let reused = false;
3042
+ try {
3043
+ const existing = await readFile2(bundlePath);
3044
+ verifyCanonicalPiResourceBundle(existing, digest);
3045
+ bundle = existing;
3046
+ reused = true;
3047
+ } catch (error) {
3048
+ if (error.code !== "ENOENT" && input.archiveBase64 === void 0) {
3049
+ throw error;
3050
+ }
3051
+ }
3052
+ if (!bundle) {
3053
+ if (!input.deliveredBundle && input.archiveBase64 === void 0) {
3054
+ throw new Error(`Pi resource bundle '${digest}' is unavailable on the process volume`);
3055
+ }
3056
+ bundle = input.deliveredBundle ?? Buffer.from(input.archiveBase64, "base64");
3057
+ verifyCanonicalPiResourceBundle(bundle, digest);
3058
+ await atomicWrite(bundlePath, bundle, 384);
3059
+ }
3060
+ const manifest = Buffer.from(
3061
+ `${JSON.stringify({ startRecordId, digest, persistedAt: (/* @__PURE__ */ new Date()).toISOString() })}
3062
+ `,
3063
+ "utf8"
3064
+ );
3065
+ await atomicWrite(path6.join(startsDir, `${startRecordId}.json`), manifest, 384);
3066
+ return { bundle, reused };
3067
+ }
3068
+ async function writeExtractedFiles(root, files) {
3069
+ for (const file of files) {
3070
+ const output = path6.resolve(root, file.path);
3071
+ if (path6.relative(root, output).startsWith("..") || path6.isAbsolute(path6.relative(root, output))) {
3072
+ fail2(`path escapes materialization root: ${file.path}`);
3073
+ }
3074
+ await mkdir4(path6.dirname(output), { recursive: true, mode: 448 });
3075
+ await writeFile4(output, file.content, { mode: 420, flag: "wx" });
3076
+ }
3077
+ }
3078
+ async function materializeCanonicalPiResourceBundle(input) {
3079
+ const files = verifyCanonicalPiResourceBundle(input.bundle, input.digest);
3080
+ const targetDir = path6.resolve(input.targetDir);
3081
+ const parent = path6.dirname(targetDir);
3082
+ await mkdir4(parent, { recursive: true, mode: 448 });
3083
+ const marker = path6.join(targetDir, ".leitwerk-resource-digest");
3084
+ try {
3085
+ const current = await import("fs/promises").then(
3086
+ ({ readFile: readFile5 }) => readFile5(marker, "utf8")
3087
+ );
3088
+ if (current === `${input.digest}
3089
+ `) return { targetDir, reused: true };
3090
+ throw new Error(
3091
+ `Managed Pi directory already exists with a different resource digest: ${targetDir}`
3092
+ );
3093
+ } catch (error) {
3094
+ if (error.code !== "ENOENT") throw error;
3095
+ }
3096
+ const staging = path6.join(
3097
+ parent,
3098
+ `.${path6.basename(targetDir)}.staging-${process.pid}-${randomUUID3()}`
3099
+ );
3100
+ try {
3101
+ await mkdir4(staging, { mode: 448 });
3102
+ await writeExtractedFiles(staging, files);
3103
+ await writeFile4(path6.join(staging, ".leitwerk-resource-digest"), `${input.digest}
3104
+ `, {
3105
+ mode: 384,
3106
+ flag: "wx"
3107
+ });
3108
+ await rename3(staging, targetDir);
3109
+ return { targetDir, reused: false };
3110
+ } catch (error) {
3111
+ await rm(staging, { recursive: true, force: true });
3112
+ if (error.code === "EEXIST") {
3113
+ const current = await import("fs/promises").then(
3114
+ ({ readFile: readFile5 }) => readFile5(marker, "utf8")
3115
+ );
3116
+ if (current === `${input.digest}
3117
+ `) return { targetDir, reused: true };
3118
+ }
3119
+ throw error;
3120
+ }
3121
+ }
3122
+
2675
3123
  // src/pre-turn-targeted-inputs.ts
2676
3124
  import {
2677
3125
  resolveProcessProductRefEntryId,
@@ -2950,7 +3398,8 @@ function parseProcessSemanticEntryRefsFromStateJson(stateJson) {
2950
3398
  }
2951
3399
 
2952
3400
  // src/workspace/run-root.ts
2953
- import path6 from "path";
3401
+ import path7 from "path";
3402
+ import { isPathInside } from "@leitwerk-dev/process-sdk";
2954
3403
 
2955
3404
  // src/workspace/manifest.ts
2956
3405
  import * as v from "valibot";
@@ -2985,14 +3434,14 @@ var componentManifestJsonSchema = v.pipe(v.string(), v.parseJson(), componentMan
2985
3434
  function formatManifestValidationError(issues) {
2986
3435
  const issue = issues[0];
2987
3436
  if (issue?.type === "parse_json") return "Invalid JSON";
2988
- const path13 = issue ? v.getDotPath(issue) : null;
2989
- if (!path13) return "Manifest must be a JSON object";
2990
- if (path13 === "version") return "Unsupported manifest version";
2991
- if (path13 === "instanceId") return "Invalid instanceId";
2992
- if (path13 === "createdAt") return "Invalid createdAt";
2993
- if (path13 === "components") return "components must be an array";
2994
- if (path13.match(/^components\.\d+$/)) return "Invalid component entry";
2995
- const componentField = path13.match(/^components\.\d+\.([^.]*)$/)?.[1];
3437
+ const path14 = issue ? v.getDotPath(issue) : null;
3438
+ if (!path14) return "Manifest must be a JSON object";
3439
+ if (path14 === "version") return "Unsupported manifest version";
3440
+ if (path14 === "instanceId") return "Invalid instanceId";
3441
+ if (path14 === "createdAt") return "Invalid createdAt";
3442
+ if (path14 === "components") return "components must be an array";
3443
+ if (path14.match(/^components\.\d+$/)) return "Invalid component entry";
3444
+ const componentField = path14.match(/^components\.\d+\.([^.]*)$/)?.[1];
2996
3445
  if (componentField) return `Invalid component field: ${componentField}`;
2997
3446
  return issue?.message ? `Invalid manifest: ${issue.message}` : "Invalid manifest";
2998
3447
  }
@@ -3049,48 +3498,38 @@ function aggregateAgentsMd(sources) {
3049
3498
  `;
3050
3499
  }
3051
3500
  function collectSkills(sources) {
3052
- const byId = /* @__PURE__ */ new Map();
3053
- for (const s of sources) {
3054
- const list = byId.get(s.skillId);
3055
- if (list) {
3056
- list.push(s);
3057
- } else {
3058
- byId.set(s.skillId, [s]);
3059
- }
3060
- }
3061
3501
  const out = /* @__PURE__ */ new Map();
3062
- for (const [skillId, group] of byId) {
3063
- group.sort((a, b) => a.componentKey.localeCompare(b.componentKey));
3064
- const winner = group[0];
3065
- out.set(skillId, {
3066
- content: winner.content,
3067
- source: winner.componentKey
3068
- });
3502
+ for (const { skillId, componentKey, content } of sources) {
3503
+ const winner = out.get(skillId);
3504
+ if (!winner || componentKey.localeCompare(winner.source) < 0) {
3505
+ out.set(skillId, { content, source: componentKey });
3506
+ }
3069
3507
  }
3070
3508
  return out;
3071
3509
  }
3072
3510
 
3073
3511
  // src/workspace/run-root.ts
3074
- var MANIFEST_REL = path6.join(".leitwerk", "components.json");
3512
+ var RunRootPreparationError = class extends Error {
3513
+ errors;
3514
+ constructor(errors) {
3515
+ super(`Workspace preparation failed: ${errors.join("; ")}`);
3516
+ this.name = "RunRootPreparationError";
3517
+ this.errors = [...errors];
3518
+ }
3519
+ };
3520
+ var MANIFEST_REL = path7.join(".leitwerk", "components.json");
3075
3521
  var AGGREGATED_AGENTS_REL2 = "AGENTS.md";
3076
- var SKILLS_DIR_REL = path6.join(".leitwerk", "skills");
3522
+ var SKILLS_DIR_REL = path7.join(".leitwerk", "skills");
3077
3523
  var SKILL_GLOB = "**/.cursor/skills/**/SKILL.md";
3078
3524
  var AGENTS_GLOB = "**/AGENTS.md";
3079
- function isPathInside(parent, child) {
3080
- const relative = path6.relative(parent, child);
3081
- return relative !== "" && relative !== ".." && !relative.startsWith(`..${path6.sep}`) && !path6.isAbsolute(relative);
3082
- }
3083
- function safeJoinInsideWorkspace(workspaceRoot, childPath) {
3084
- const root = path6.resolve(workspaceRoot);
3085
- const target = path6.resolve(root, childPath);
3525
+ function componentDir(workspaceRoot, childPath) {
3526
+ const root = path7.resolve(workspaceRoot);
3527
+ const target = path7.resolve(root, childPath);
3086
3528
  if (!isPathInside(root, target)) {
3087
3529
  throw new Error(`Component key '${childPath}' resolves outside workspace root '${root}'`);
3088
3530
  }
3089
3531
  return target;
3090
3532
  }
3091
- function componentDir(workspaceRoot, key) {
3092
- return safeJoinInsideWorkspace(workspaceRoot, key);
3093
- }
3094
3533
  function skillIdFromSkillPath(filePath) {
3095
3534
  const normalized = filePath.replace(/\\/g, "/");
3096
3535
  const m = normalized.match(/\.cursor\/skills\/([^/]+)\/SKILL\.md$/);
@@ -3107,12 +3546,10 @@ async function materializeComponentEntry(plan, comp, git) {
3107
3546
  const dir = componentDir(plan.workspaceRoot, comp.key);
3108
3547
  await git.clone(comp.repoLocator, dir);
3109
3548
  await git.checkout(dir, comp.baseBranch);
3110
- if (await git.branchExists(dir, comp.workBranch)) {
3111
- await git.checkout(dir, comp.workBranch);
3112
- } else {
3549
+ if (!await git.branchExists(dir, comp.workBranch)) {
3113
3550
  await git.createBranch(dir, comp.workBranch, comp.baseBranch);
3114
- await git.checkout(dir, comp.workBranch);
3115
3551
  }
3552
+ await git.checkout(dir, comp.workBranch);
3116
3553
  return {
3117
3554
  key: comp.key,
3118
3555
  repoLocator: comp.repoLocator,
@@ -3183,7 +3620,7 @@ async function writeAggregatedArtifacts(plan, git, manifest, agentsMd, skillsMap
3183
3620
  await git.writeFile(root, MANIFEST_REL, serializeManifest(manifest));
3184
3621
  await git.writeFile(root, AGGREGATED_AGENTS_REL2, agentsMd);
3185
3622
  for (const [skillId, { content }] of skillsMap) {
3186
- const rel = path6.join(SKILLS_DIR_REL, `${skillId}.md`);
3623
+ const rel = path7.join(SKILLS_DIR_REL, `${skillId}.md`);
3187
3624
  await git.writeFile(root, rel, content);
3188
3625
  }
3189
3626
  }
@@ -3201,42 +3638,28 @@ async function finalizeRunRoot(plan, git, entries, errors) {
3201
3638
  } catch (e) {
3202
3639
  errors.push(`write: ${e instanceof Error ? e.message : String(e)}`);
3203
3640
  }
3204
- return { manifest, aggregatedAgentsMdSources, loadedSkills };
3205
- }
3206
- async function materializeRunRoot(plan, git) {
3207
- const errors = [];
3208
- const entries = await collectMaterializedEntries(plan, git, errors);
3209
- const { manifest, aggregatedAgentsMdSources, loadedSkills } = await finalizeRunRoot(
3210
- plan,
3211
- git,
3212
- entries,
3213
- errors
3214
- );
3215
- const ok = errors.length === 0 && plan.components.length === entries.length;
3641
+ const expectedKeys = new Set(plan.components.map((component) => component.key));
3642
+ const hasAllExpectedEntries = entries.length === expectedKeys.size && [...expectedKeys].every((key) => entries.some((entry) => entry.key === key));
3643
+ if (errors.length > 0 || !hasAllExpectedEntries) {
3644
+ throw new RunRootPreparationError(errors);
3645
+ }
3216
3646
  return {
3217
- ok,
3647
+ ok: true,
3218
3648
  manifest,
3219
3649
  aggregatedAgentsMdSources,
3220
3650
  loadedSkills,
3221
3651
  errors
3222
3652
  };
3223
3653
  }
3654
+ async function materializeRunRoot(plan, git) {
3655
+ const errors = [];
3656
+ const entries = await collectMaterializedEntries(plan, git, errors);
3657
+ return finalizeRunRoot(plan, git, entries, errors);
3658
+ }
3224
3659
  async function validateRunRoot(workspaceRoot, serverProjects, git) {
3225
3660
  const raw = await git.readFile(workspaceRoot, MANIFEST_REL);
3226
- if (raw === null) {
3227
- return {
3228
- valid: false,
3229
- diff: {
3230
- stale: [],
3231
- missing: serverProjects.map((p) => p.key),
3232
- extra: [],
3233
- unchanged: []
3234
- },
3235
- existingManifest: null
3236
- };
3237
- }
3238
- const parsed = deserializeManifest(raw);
3239
- if (!parsed.ok) {
3661
+ const parsed = raw === null ? null : deserializeManifest(raw);
3662
+ if (!parsed?.ok) {
3240
3663
  return {
3241
3664
  valid: false,
3242
3665
  diff: {
@@ -3266,54 +3689,45 @@ async function repairRunRoot(_workspaceRoot, validation, plan, git) {
3266
3689
  (componentKey) => toRepair.has(componentKey),
3267
3690
  (componentKey) => validation.existingManifest?.components.find((component) => component.key === componentKey) ?? null
3268
3691
  );
3269
- const { manifest, aggregatedAgentsMdSources, loadedSkills } = await finalizeRunRoot(
3270
- plan,
3271
- git,
3272
- manifestEntries,
3273
- errors
3274
- );
3275
- const expectedKeys = new Set(plan.components.map((c) => c.key));
3276
- const ok = errors.length === 0 && manifestEntries.length === plan.components.length && [...expectedKeys].every((k) => manifestEntries.some((e) => e.key === k));
3277
- return {
3278
- ok,
3279
- manifest,
3280
- aggregatedAgentsMdSources,
3281
- loadedSkills,
3282
- errors
3283
- };
3692
+ return finalizeRunRoot(plan, git, manifestEntries, errors);
3284
3693
  }
3285
3694
 
3286
3695
  // src/runtime/bootstrap.ts
3287
- function readNonEmptyString2(value) {
3288
- return typeof value === "string" && value.trim() !== "" ? value : null;
3289
- }
3290
3696
  function withoutCredentialValues(payload) {
3291
- const withoutRepositoryCredentials = {
3697
+ const withoutCredentials = {
3292
3698
  ...payload,
3293
- repositoryCredentials: void 0
3699
+ repositoryCredentials: void 0,
3700
+ dockerRegistryCredentials: void 0
3294
3701
  };
3295
- if (!isLlmWorkerStartPayload(payload) || !payload.bootstrap.credential) {
3296
- return withoutRepositoryCredentials;
3702
+ if (!isLlmWorkerStartPayload(withoutCredentials) || !withoutCredentials.bootstrap.credential) {
3703
+ return withoutCredentials;
3297
3704
  }
3298
3705
  return {
3299
- ...payload,
3300
- repositoryCredentials: void 0,
3706
+ ...withoutCredentials,
3301
3707
  bootstrap: {
3302
- ...payload.bootstrap,
3303
- credential: { ...payload.bootstrap.credential, values: {} }
3708
+ ...withoutCredentials.bootstrap,
3709
+ credential: { ...withoutCredentials.bootstrap.credential, values: {} }
3304
3710
  }
3305
3711
  };
3306
3712
  }
3307
3713
  function validateRepositoryCredentials(input) {
3308
3714
  const credentialKeys = /* @__PURE__ */ new Set();
3309
3715
  for (const credential of input.credentials) {
3310
- if (!input.projectKeys.has(credential.projectKey) || credential.kind !== "git_ssh") {
3716
+ if (!input.projectKeys.has(credential.projectKey) || !["git_ssh", "git_https"].includes(credential.kind)) {
3311
3717
  throw new Error(`Repository credential does not match project '${credential.projectKey}'`);
3312
3718
  }
3313
3719
  if (credentialKeys.has(credential.projectKey)) {
3314
3720
  throw new Error(`Duplicate repository credential for project '${credential.projectKey}'`);
3315
3721
  }
3316
3722
  credentialKeys.add(credential.projectKey);
3723
+ if (credential.kind === "git_https") {
3724
+ const project = input.projects?.find((project2) => project2.key === credential.projectKey);
3725
+ if (!project || repositoryHttpsUrl(credential.repositoryUrl).href !== project.repoLocator || !credential.username || !credential.password || /[\r\n\0]/.test(credential.username + credential.password)) {
3726
+ throw new Error(
3727
+ `Invalid HTTPS credential scope or material for project '${credential.projectKey}'`
3728
+ );
3729
+ }
3730
+ }
3317
3731
  }
3318
3732
  const identities = (items) => new Set(items.map((item) => `${item.projectKey}:${item.kind}:${item.credentialRef}`));
3319
3733
  const delivered = identities(input.credentials);
@@ -3323,41 +3737,27 @@ function validateRepositoryCredentials(input) {
3323
3737
  }
3324
3738
  }
3325
3739
  function shouldPreservePersistedLeafForActiveTurnResume(input) {
3326
- if (!input.payload.resume) {
3327
- return false;
3328
- }
3329
- if (!readNonEmptyString2(input.processSnapshot.selectedTurnId)) {
3330
- return false;
3331
- }
3332
- if (input.processSnapshot.currentExecution?.kind !== "worker_start" || input.processSnapshot.currentExecution.id !== input.payload.turnStart.id || input.payload.turnStart.state.kind !== "accepted" || !readNonEmptyString2(input.payload.turnStart.state.turnRecordId)) {
3333
- return false;
3334
- }
3335
- if (readNonEmptyString2(input.processSnapshot.metadata?.continueFromPiEntryId)) {
3336
- return false;
3337
- }
3338
- if (readNonEmptyString2(input.processSnapshot.metadata?.retryForkPiEntryId)) {
3339
- return false;
3340
- }
3341
- return true;
3740
+ const { payload, processSnapshot } = input;
3741
+ return payload.resume && readNonEmptyString2(processSnapshot.selectedTurnId) !== null && processSnapshot.currentExecution?.kind === "worker_start" && processSnapshot.currentExecution.id === payload.turnStart.id && payload.turnStart.state.kind === "accepted" && readNonEmptyString2(payload.turnStart.state.turnRecordId) !== null && readNonEmptyString2(processSnapshot.metadata?.continueFromPiEntryId) === null && readNonEmptyString2(processSnapshot.metadata?.retryForkPiEntryId) === null;
3342
3742
  }
3343
3743
  function resolveResumeLeafEntryCandidates(processSnapshot, payload) {
3344
- const candidates = [];
3345
- const continueFromPiEntryId = typeof processSnapshot.metadata?.continueFromPiEntryId === "string" ? processSnapshot.metadata.continueFromPiEntryId : null;
3346
- if (continueFromPiEntryId) {
3347
- candidates.push({ entryId: continueFromPiEntryId, source: "continue" });
3348
- }
3349
- const retryForkPiEntryId = typeof processSnapshot.metadata?.retryForkPiEntryId === "string" ? processSnapshot.metadata.retryForkPiEntryId : null;
3350
- if (retryForkPiEntryId && retryForkPiEntryId !== continueFromPiEntryId) {
3351
- candidates.push({ entryId: retryForkPiEntryId, source: "retry" });
3352
- }
3353
3744
  const semanticEntryRefs = parseProcessSemanticEntryRefsFromStateJson(processSnapshot.stateJson);
3354
- const stateLeafId = payload.resume ? semanticEntryRefs.currentPrimaryPathLeaf?.entryId ?? null : null;
3355
- if (stateLeafId && stateLeafId !== continueFromPiEntryId && stateLeafId !== retryForkPiEntryId) {
3356
- candidates.push({ entryId: stateLeafId, source: "state" });
3357
- }
3358
- const payloadLeafId = payload.resume ? payload.resumeLeafEntryId ?? null : null;
3359
- if (payloadLeafId && payloadLeafId !== continueFromPiEntryId && payloadLeafId !== retryForkPiEntryId && payloadLeafId !== stateLeafId) {
3360
- candidates.push({ entryId: payloadLeafId, source: "payload" });
3745
+ const candidates = [];
3746
+ for (const [source, entryId] of [
3747
+ [
3748
+ "continue",
3749
+ typeof processSnapshot.metadata?.continueFromPiEntryId === "string" ? processSnapshot.metadata.continueFromPiEntryId : null
3750
+ ],
3751
+ [
3752
+ "retry",
3753
+ typeof processSnapshot.metadata?.retryForkPiEntryId === "string" ? processSnapshot.metadata.retryForkPiEntryId : null
3754
+ ],
3755
+ ["state", payload.resume ? semanticEntryRefs.currentPrimaryPathLeaf?.entryId : null],
3756
+ ["payload", payload.resume ? payload.resumeLeafEntryId : null]
3757
+ ]) {
3758
+ if (entryId && !candidates.some((candidate) => candidate.entryId === entryId)) {
3759
+ candidates.push({ entryId, source });
3760
+ }
3361
3761
  }
3362
3762
  return candidates;
3363
3763
  }
@@ -3491,6 +3891,13 @@ async function bootstrapWorkerRuntime(deps) {
3491
3891
  const paramsJson = deps.payload.processSnapshot.paramsJson ?? null;
3492
3892
  const stateJson = deps.payload.processSnapshot.stateJson ?? null;
3493
3893
  const resolvedWorkerProcess = deps.resolveWorkerProcess ? await deps.resolveWorkerProcess(processId, { paramsJson, stateJson }) : void 0;
3894
+ const dockerCredentials = deps.payload.dockerRegistryCredentials ?? [];
3895
+ if (dockerCredentials.length && !deps.configureDockerCredentials)
3896
+ throw new Error("Docker credential delivery is unavailable");
3897
+ deps.configureDockerCredentials?.(
3898
+ dockerCredentials,
3899
+ resolvedWorkerProcess?.runtime?.docker === true
3900
+ );
3494
3901
  const projectSnapshots = projectSnapshotsFromPayload(deps.payload.projectSnapshots);
3495
3902
  const repositoryCredentials = deps.payload.repositoryCredentials ?? [];
3496
3903
  const declaredRequirements = resolvedWorkerProcess?.repositoryCredentials?.({
@@ -3500,7 +3907,8 @@ async function bootstrapWorkerRuntime(deps) {
3500
3907
  validateRepositoryCredentials({
3501
3908
  credentials: repositoryCredentials,
3502
3909
  requirements: declaredRequirements,
3503
- projectKeys: new Set(projectSnapshots.map((project) => project.key))
3910
+ projectKeys: new Set(projectSnapshots.map((project) => project.key)),
3911
+ projects: projectSnapshots
3504
3912
  });
3505
3913
  deps.gitOps.configureRepositoryCredentials?.(repositoryCredentials);
3506
3914
  const processSnapshot = buildProcessSnapshotSeed(processId, deps.payload.processSnapshot);
@@ -3513,18 +3921,9 @@ async function bootstrapWorkerRuntime(deps) {
3513
3921
  workBranch: project.workBranch ?? ""
3514
3922
  }));
3515
3923
  const plan = planRunRoot(workspaceRoot, deps.instanceId, runRootProjects);
3516
- let aggregatedAgentsMdSources = [];
3517
- let loadedSkills = [];
3518
- if (!deps.payload.resume) {
3519
- const materialized = await materializeRunRoot(plan, deps.gitOps);
3520
- aggregatedAgentsMdSources = materialized.aggregatedAgentsMdSources;
3521
- loadedSkills = materialized.loadedSkills;
3522
- } else {
3523
- const validation = await validateRunRoot(workspaceRoot, runRootProjects, deps.gitOps);
3524
- const repaired = await repairRunRoot(workspaceRoot, validation, plan, deps.gitOps);
3525
- aggregatedAgentsMdSources = repaired.aggregatedAgentsMdSources;
3526
- loadedSkills = repaired.loadedSkills;
3527
- }
3924
+ const runRootPreparation = deps.payload.resume ? validateRunRoot(workspaceRoot, runRootProjects, deps.gitOps).then(
3925
+ (validation) => repairRunRoot(workspaceRoot, validation, plan, deps.gitOps)
3926
+ ) : materializeRunRoot(plan, deps.gitOps);
3528
3927
  const resolvedPiConfig = llmPayload ? resolveProcessPiConfig({
3529
3928
  processId,
3530
3929
  processPiConfig: resolvedWorkerProcess?.piConfig,
@@ -3536,7 +3935,7 @@ async function bootstrapWorkerRuntime(deps) {
3536
3935
  projects: projectSnapshots
3537
3936
  })
3538
3937
  }) : { systemPrompt: "", availableToolNames: [] };
3539
- const sessionCwd = resolvedPiConfig.sessionCwd ? path7.resolve(workspaceRoot, resolvedPiConfig.sessionCwd) : workspaceRoot;
3938
+ const sessionCwd = resolvedPiConfig.sessionCwd ? path8.resolve(workspaceRoot, resolvedPiConfig.sessionCwd) : workspaceRoot;
3540
3939
  const pendingInputs = (deps.payload.pendingInputs ?? []).map(inputDeliveryToItem);
3541
3940
  const diagnostics = [];
3542
3941
  let managedAgentDir = null;
@@ -3545,6 +3944,26 @@ async function bootstrapWorkerRuntime(deps) {
3545
3944
  let loadedAgentsFiles = [];
3546
3945
  let loadedSkillFiles = [];
3547
3946
  let receipt;
3947
+ const runRoot = await runRootPreparation;
3948
+ let preparedTools;
3949
+ if (resolvedWorkerProcess?.runtime?.developmentTools) {
3950
+ if (!deps.payload.developmentTools) {
3951
+ throw new Error("Development-tool settings are unavailable for an opted-in process");
3952
+ }
3953
+ preparedTools = await (deps.developmentTools ?? new MiseDevelopmentToolEnvironment()).prepare({
3954
+ config: deps.payload.developmentTools,
3955
+ repositories: projectSnapshots.map((project) => ({
3956
+ repositoryKey: project.key,
3957
+ workingDirectory: path8.join(workspaceRoot, project.key)
3958
+ })),
3959
+ signal: deps.toolPreparationSignal,
3960
+ onProgress: deps.onToolPreparationProgress,
3961
+ onDiagnosticTrace: deps.onToolDiagnosticTrace
3962
+ });
3963
+ for (const [key, value] of Object.entries(preparedTools.commandEnvironment)) {
3964
+ if (key === "PATH" || key.startsWith("MISE_")) process.env[key] = value;
3965
+ }
3966
+ }
3548
3967
  if (llmPayload) {
3549
3968
  const start = deps.payload.turnStart.state.kind === "starting" || deps.payload.turnStart.state.kind === "accepted" ? deps.payload.turnStart.state.start : null;
3550
3969
  if (!start || start.kind !== "llm")
@@ -3568,11 +3987,29 @@ async function bootstrapWorkerRuntime(deps) {
3568
3987
  instanceId: deps.instanceId,
3569
3988
  startOrLeaseId: deps.payload.workerLeaseId
3570
3989
  });
3571
- await materializeCanonicalPiResourceBundle({
3572
- bundle: Buffer.from(llmPayload.bootstrap.resourceBundle.archiveBase64, "base64"),
3990
+ const deliveredBundle = llmPayload.bootstrap.resourceBundle.archiveBase64 === void 0 ? void 0 : Buffer.from(llmPayload.bootstrap.resourceBundle.archiveBase64, "base64");
3991
+ if (deliveredBundle) {
3992
+ verifyCanonicalPiResourceBundle(deliveredBundle, llmPayload.bootstrap.resourceBundle.digest);
3993
+ }
3994
+ const resourceBundleInput = {
3995
+ bundlesDir: deps.payload.treePaths.piResourceBundlesDir,
3996
+ startRecordId: deps.payload.turnStart.id,
3573
3997
  digest: llmPayload.bootstrap.resourceBundle.digest,
3574
- targetDir: managedAgentDir
3998
+ archiveBase64: llmPayload.bootstrap.resourceBundle.archiveBase64
3999
+ };
4000
+ const persistedResourceBundle = persistPiResourceBundleForStart({
4001
+ ...resourceBundleInput,
4002
+ ...deliveredBundle ? { deliveredBundle } : {}
3575
4003
  });
4004
+ const bundle = deliveredBundle ?? (await persistedResourceBundle).bundle;
4005
+ await Promise.all([
4006
+ persistedResourceBundle,
4007
+ materializeCanonicalPiResourceBundle({
4008
+ bundle,
4009
+ digest: llmPayload.bootstrap.resourceBundle.digest,
4010
+ targetDir: managedAgentDir
4011
+ })
4012
+ ]);
3576
4013
  const manifest = await readAndValidateManagedPiResourceManifest({
3577
4014
  agentDir: managedAgentDir,
3578
4015
  resourceDigest: llmPayload.bootstrap.resourceBundle.digest,
@@ -3670,12 +4107,22 @@ async function bootstrapWorkerRuntime(deps) {
3670
4107
  resumed: deps.payload.resume,
3671
4108
  primaryTreeFile: deps.payload.treePaths.primaryTreeFile,
3672
4109
  workspaceRoot: deps.payload.treePaths.workspaceRoot,
3673
- aggregatedAgentsSources: aggregatedAgentsMdSources,
3674
- loadedSkills,
4110
+ aggregatedAgentsSources: runRoot.aggregatedAgentsMdSources,
4111
+ loadedSkills: runRoot.loadedSkills,
3675
4112
  loadedAgentsFiles,
3676
4113
  loadedSkillFiles,
3677
4114
  rootEntryId: null,
3678
- receipt
4115
+ receipt,
4116
+ ...preparedTools ? {
4117
+ developmentTools: {
4118
+ miseVersion: preparedTools.miseVersion,
4119
+ repositories: preparedTools.repositories.map((repository) => ({
4120
+ repositoryKey: repository.repositoryKey,
4121
+ tools: repository.tools
4122
+ })),
4123
+ warnings: preparedTools.warnings
4124
+ }
4125
+ } : {}
3679
4126
  },
3680
4127
  pendingInputs,
3681
4128
  ...credentialRefresh ? { credentialRefresh } : {}
@@ -3710,6 +4157,8 @@ function validatePreparedSession(input) {
3710
4157
  startRecordId: payload.turnStart.id,
3711
4158
  proposedTurnRecordId: payload.turnStart.proposedTurnRecordId,
3712
4159
  acceptedTurnRecordId: payload.turnStart.state.kind === "accepted" ? payload.turnStart.state.turnRecordId : null,
4160
+ startKind: payload.turnStart.startKind,
4161
+ ...payload.llmPreparation ? { llmPreparation: payload.llmPreparation } : {},
3713
4162
  treeFile: payload.treePaths.primaryTreeFile,
3714
4163
  workspaceRoot: payload.treePaths.workspaceRoot,
3715
4164
  turnResultMarkdownBySemanticRef: payload.turnResultMarkdownBySemanticRef,
@@ -3741,28 +4190,50 @@ var WorkerLiveResources = class {
3741
4190
  }
3742
4191
  deps;
3743
4192
  #piHandle = null;
4193
+ #dockerCredentials = new DockerRegistryCredentials();
3744
4194
  #activeTurnAbort = null;
4195
+ #toolPreparationAbort = null;
3745
4196
  #provisional = /* @__PURE__ */ new Map();
3746
4197
  get piHandle() {
3747
4198
  return this.#piHandle;
3748
4199
  }
3749
4200
  async bootstrap(payload, settings) {
3750
- const bootstrapped = await bootstrapWorkerRuntime({
3751
- instanceId: this.deps.instanceId,
3752
- payload,
3753
- piFactory: this.deps.piFactory,
3754
- gitOps: this.deps.gitOps,
3755
- scheduler: this.deps.scheduler,
3756
- resolveWorkerProcess: this.deps.resolveWorkerProcess
3757
- });
3758
- this.#provisional.set(payload.turnStart.id, bootstrapped.activation);
3759
- return {
3760
- session: validatePreparedSession({ bootstrapped, payload, settings }),
3761
- pendingInputs: bootstrapped.pendingInputs,
3762
- readyPayload: bootstrapped.readyPayload,
3763
- ...bootstrapped.credentialRefresh ? { credentialRefresh: bootstrapped.credentialRefresh } : {},
3764
- diagnostics: bootstrapped.diagnostics
3765
- };
4201
+ const toolPreparationAbort = new AbortController();
4202
+ this.#toolPreparationAbort = toolPreparationAbort;
4203
+ try {
4204
+ const bootstrapped = await bootstrapWorkerRuntime({
4205
+ instanceId: this.deps.instanceId,
4206
+ payload,
4207
+ piFactory: this.deps.piFactory,
4208
+ gitOps: this.deps.gitOps,
4209
+ developmentTools: this.deps.developmentTools,
4210
+ configureDockerCredentials: (credentials, enabled) => this.#dockerCredentials.install(credentials, enabled),
4211
+ toolPreparationSignal: toolPreparationAbort.signal,
4212
+ scheduler: this.deps.scheduler,
4213
+ onToolPreparationProgress: (repositoryKey, phase) => this.deps.progress({
4214
+ level: "info",
4215
+ code: `development_tools.${phase}`,
4216
+ message: `${phase === "installing" ? "Installing" : "Verifying"} development tools for ${repositoryKey}`,
4217
+ details: { repositoryKey }
4218
+ }),
4219
+ onToolDiagnosticTrace: this.deps.diagnosticTrace,
4220
+ resolveWorkerProcess: this.deps.resolveWorkerProcess
4221
+ });
4222
+ const session = validatePreparedSession({ bootstrapped, payload, settings });
4223
+ this.#provisional.set(payload.turnStart.id, bootstrapped.activation);
4224
+ return {
4225
+ session,
4226
+ pendingInputs: bootstrapped.pendingInputs,
4227
+ readyPayload: bootstrapped.readyPayload,
4228
+ ...bootstrapped.credentialRefresh ? { credentialRefresh: bootstrapped.credentialRefresh } : {},
4229
+ diagnostics: bootstrapped.diagnostics
4230
+ };
4231
+ } catch (error) {
4232
+ this.#dockerCredentials.dispose();
4233
+ throw error;
4234
+ } finally {
4235
+ if (this.#toolPreparationAbort === toolPreparationAbort) this.#toolPreparationAbort = null;
4236
+ }
3766
4237
  }
3767
4238
  async activate(startRecordId, turnRecordId, session) {
3768
4239
  if (session.proposedTurnRecordId !== turnRecordId) {
@@ -3817,6 +4288,11 @@ var WorkerLiveResources = class {
3817
4288
  if (this.#activeTurnAbort === controller) this.#activeTurnAbort = null;
3818
4289
  }
3819
4290
  }
4291
+ abortToolPreparation() {
4292
+ if (!this.#toolPreparationAbort) return false;
4293
+ this.#toolPreparationAbort.abort();
4294
+ return true;
4295
+ }
3820
4296
  abortActiveTurn() {
3821
4297
  if (!this.#activeTurnAbort) return false;
3822
4298
  this.#activeTurnAbort.abort();
@@ -3826,30 +4302,21 @@ var WorkerLiveResources = class {
3826
4302
  await this.#piHandle?.abortTurn();
3827
4303
  }
3828
4304
  async cleanup() {
4305
+ this.#dockerCredentials.dispose();
3829
4306
  this.#provisional.clear();
3830
4307
  await this.#piHandle?.close();
3831
4308
  this.#piHandle = null;
3832
4309
  this.deps.gitOps.cleanupRepositoryCredentials?.();
3833
4310
  }
3834
4311
  };
3835
- function strings(value, name) {
3836
- if (!value || typeof value !== "object" || Array.isArray(value)) {
3837
- throw new Error(`Credential file '${name}' must contain a JSON object`);
3838
- }
3839
- return Object.fromEntries(
3840
- Object.entries(value).filter(
3841
- (entry) => typeof entry[1] === "string"
3842
- )
3843
- );
3844
- }
3845
4312
  async function sampleCredentialFiles(descriptor) {
3846
4313
  const values = {};
3847
4314
  for (const credentialPath of descriptor.declaredCredentialPaths) {
3848
- const json = JSON.parse(await readFile2(path8.join(descriptor.agentDir, credentialPath), "utf8"));
4315
+ const json = JSON.parse(await readFile3(path9.join(descriptor.agentDir, credentialPath), "utf8"));
4316
+ if (!json || typeof json !== "object" || Array.isArray(json)) {
4317
+ throw new Error(`Credential file '${credentialPath}' must contain a JSON object`);
4318
+ }
3849
4319
  if (credentialPath === "auth.json") {
3850
- if (!json || typeof json !== "object" || Array.isArray(json)) {
3851
- throw new Error(`Credential file '${credentialPath}' must contain a JSON object`);
3852
- }
3853
4320
  const selected = json[descriptor.providerId];
3854
4321
  if (selected && typeof selected === "object" && !Array.isArray(selected)) {
3855
4322
  for (const [key, value] of Object.entries(selected)) {
@@ -3858,7 +4325,12 @@ async function sampleCredentialFiles(descriptor) {
3858
4325
  values[key] = String(value);
3859
4326
  }
3860
4327
  }
3861
- } else Object.assign(values, strings(json, credentialPath));
4328
+ } else {
4329
+ Object.assign(
4330
+ values,
4331
+ Object.fromEntries(Object.entries(json).filter(([, value]) => typeof value === "string"))
4332
+ );
4333
+ }
3862
4334
  }
3863
4335
  const fingerprint = JSON.stringify(
3864
4336
  Object.keys(values).sort().map((key) => [key, values[key]])
@@ -3866,13 +4338,9 @@ async function sampleCredentialFiles(descriptor) {
3866
4338
  return { values, fingerprint };
3867
4339
  }
3868
4340
 
3869
- // src/runtime/lifecycle-reducer.ts
3870
- import {
3871
- WORKER_API_VERSION as WORKER_API_VERSION2
3872
- } from "@leitwerk-dev/worker-protocol";
3873
-
3874
4341
  // src/turn-execution-error.ts
3875
- import { isWorkerErrorClass } from "@leitwerk-dev/domain";
4342
+ import { isWorkerErrorClass, toErrorMessage } from "@leitwerk-dev/domain";
4343
+ import { toErrorMessage as toErrorMessage2 } from "@leitwerk-dev/domain";
3876
4344
  var TurnExecutionError = class extends Error {
3877
4345
  errorClass;
3878
4346
  turnId;
@@ -3900,10 +4368,7 @@ function classifyRuntimeError(error, fallbackErrorClass = "infrastructure") {
3900
4368
  message: typeof customError.message === "string" && customError.message.trim() !== "" ? customError.message : String(error)
3901
4369
  };
3902
4370
  }
3903
- if (error instanceof Error && error.message.trim() !== "") {
3904
- return { errorClass: fallbackErrorClass, message: error.message };
3905
- }
3906
- return { errorClass: fallbackErrorClass, message: String(error) };
4371
+ return { errorClass: fallbackErrorClass, message: toErrorMessage(error) };
3907
4372
  }
3908
4373
  function buildTurnFailureReport(error, input) {
3909
4374
  const classified = classifyRuntimeError(error, input.fallbackErrorClass);
@@ -3919,12 +4384,6 @@ function buildTurnFailureReport(error, input) {
3919
4384
  } : {}
3920
4385
  };
3921
4386
  }
3922
- function toErrorMessage(error) {
3923
- if (error instanceof Error && error.message.trim() !== "") {
3924
- return error.message;
3925
- }
3926
- return String(error);
3927
- }
3928
4387
 
3929
4388
  // src/runtime/failure-policy.ts
3930
4389
  function extractSecretValuesFromPayload(payload) {
@@ -3935,8 +4394,19 @@ function extractSecretValuesFromPayload(payload) {
3935
4394
  if (typeof value === "string" && value.trim() !== "") secrets.add(value.trim());
3936
4395
  }
3937
4396
  }
4397
+ for (const value of extractDockerRegistrySecretValues(payload)) secrets.add(value);
3938
4398
  return Array.from(secrets);
3939
4399
  }
4400
+ function extractDockerRegistrySecretValues(payload) {
4401
+ const secrets = /* @__PURE__ */ new Set();
4402
+ for (const credential of payload.dockerRegistryCredentials ?? []) {
4403
+ secrets.add(credential.password);
4404
+ secrets.add(Buffer.from(`${credential.username}:${credential.password}`).toString("base64"));
4405
+ secrets.add(Buffer.from(credential.password).toString("base64"));
4406
+ secrets.add(encodeURIComponent(credential.password));
4407
+ }
4408
+ return Array.from(secrets).filter(Boolean).sort((a, b) => b.length - a.length);
4409
+ }
3940
4410
  function redactSecrets(message, secrets) {
3941
4411
  let result = message;
3942
4412
  for (const secret of secrets) {
@@ -3951,21 +4421,7 @@ function errorCode(error, fallback) {
3951
4421
  const code = error?.code;
3952
4422
  return typeof code === "string" && code.trim() !== "" ? code.trim() : fallback;
3953
4423
  }
3954
- function sessionContext(payload) {
3955
- return {
3956
- selectedTurnId: payload.processSnapshot.selectedTurnId ?? null,
3957
- lifecycleStatus: payload.processSnapshot.lifecycleStatus ?? "running",
3958
- snapshotSource: failureSnapshotSource(payload)
3959
- };
3960
- }
3961
- function failureSnapshotSource(payload) {
3962
- return {
3963
- kind: payload.bootstrap.kind,
3964
- treeFile: payload.treePaths.primaryTreeFile
3965
- };
3966
- }
3967
4424
  function normalizeWorkerFailure(failure2) {
3968
- const session = failure2.kind === "bootstrap" ? sessionContext(failure2.payload) : failure2.kind === "dispatch" || failure2.kind === "cleanup" || failure2.kind === "turn" || failure2.kind === "mandatory_snapshot" ? failure2.session ?? null : null;
3969
4425
  const secrets = extractSecretValuesFromPayload(
3970
4426
  failure2.kind === "bootstrap" ? failure2.payload : null
3971
4427
  );
@@ -3982,8 +4438,8 @@ function normalizeWorkerFailure(failure2) {
3982
4438
  if (failure2.kind === "turn" || failure2.kind === "mandatory_snapshot") {
3983
4439
  const correlation = failure2.correlation;
3984
4440
  const turnError = failure2.kind === "turn" ? failure2.error : null;
3985
- const summary2 = failure2.kind === "mandatory_snapshot" ? `Mandatory session snapshot upload failed before ${failure2.point}: ${message}` : redactSecrets(turnError?.message ?? message, secrets);
3986
- const errorClass = failure2.kind === "turn" ? turnError?.errorClass ?? classified.errorClass : classified.errorClass;
4441
+ const summary2 = failure2.kind === "mandatory_snapshot" ? `Mandatory session snapshot upload failed before ${failure2.point}: ${message}` : turnError?.message ?? message;
4442
+ const errorClass = turnError?.errorClass ?? classified.errorClass;
3987
4443
  const payload = {
3988
4444
  turnRecordId: correlation.turnRecordId,
3989
4445
  turnId: correlation.turnId,
@@ -4011,7 +4467,7 @@ function normalizeWorkerFailure(failure2) {
4011
4467
  kind: "turn_failed",
4012
4468
  payload,
4013
4469
  park: {
4014
- selectedTurnId: session?.selectedTurnId ?? correlation.turnId,
4470
+ selectedTurnId: failure2.session?.selectedTurnId ?? correlation.turnId,
4015
4471
  reason: summary2,
4016
4472
  errorClass
4017
4473
  }
@@ -4028,7 +4484,13 @@ function normalizeWorkerFailure(failure2) {
4028
4484
  errorClass: "infrastructure"
4029
4485
  },
4030
4486
  stderrMessage: summary2,
4031
- snapshot: { point: "before_worker_failed", source: failureSnapshotSource(failure2.payload) },
4487
+ snapshot: {
4488
+ point: "before_worker_failed",
4489
+ source: {
4490
+ kind: failure2.payload.bootstrap.kind,
4491
+ treeFile: failure2.payload.treePaths.primaryTreeFile
4492
+ }
4493
+ },
4032
4494
  terminal: {
4033
4495
  kind: "worker_failed",
4034
4496
  payload: {
@@ -4036,20 +4498,24 @@ function normalizeWorkerFailure(failure2) {
4036
4498
  errorCode: errorCode(failure2.error, "bootstrap_failed"),
4037
4499
  message: bounded(summary2),
4038
4500
  errorClass: "infrastructure",
4039
- selectedTurnId: session?.selectedTurnId ?? null
4501
+ selectedTurnId: failure2.payload.processSnapshot.selectedTurnId ?? null
4040
4502
  }
4041
4503
  },
4042
4504
  exitCode: 1
4043
4505
  };
4044
4506
  }
4507
+ const { session } = failure2;
4508
+ const isCleanup = failure2.kind === "cleanup";
4509
+ const summary = `${isCleanup ? "Worker cleanup failed" : "Worker dispatch failed"}: ${message}`;
4510
+ const diagnostic = {
4511
+ level: "error",
4512
+ code: isCleanup ? "cleanup.failed" : "runtime.dispatch_failed",
4513
+ message: summary,
4514
+ errorClass: classified.errorClass
4515
+ };
4045
4516
  if (failure2.kind === "dispatch" && session && session.lifecycleStatus !== "error") {
4046
4517
  return {
4047
- diagnostic: {
4048
- level: "error",
4049
- code: "runtime.dispatch_failed",
4050
- message: `Worker dispatch failed: ${message}`,
4051
- errorClass: classified.errorClass
4052
- },
4518
+ diagnostic,
4053
4519
  stderrMessage: message,
4054
4520
  terminal: {
4055
4521
  kind: "park",
@@ -4061,11 +4527,8 @@ function normalizeWorkerFailure(failure2) {
4061
4527
  }
4062
4528
  };
4063
4529
  }
4064
- const isCleanup = failure2.kind === "cleanup";
4065
- const code = isCleanup ? "cleanup.failed" : "runtime.dispatch_failed";
4066
- const summary = `${isCleanup ? "Worker cleanup failed" : "Worker dispatch failed"}: ${message}`;
4067
4530
  return {
4068
- diagnostic: { level: "error", code, message: summary, errorClass: classified.errorClass },
4531
+ diagnostic,
4069
4532
  stderrMessage: summary,
4070
4533
  ...session ? {
4071
4534
  snapshot: {
@@ -4087,6 +4550,11 @@ function normalizeWorkerFailure(failure2) {
4087
4550
  };
4088
4551
  }
4089
4552
 
4553
+ // src/runtime/lifecycle-reducer.ts
4554
+ import {
4555
+ WORKER_API_VERSION as WORKER_API_VERSION2
4556
+ } from "@leitwerk-dev/worker-protocol";
4557
+
4090
4558
  // src/runtime/snapshot-policy.ts
4091
4559
  function resolveWorkerSnapshotPolicy(point, sessionKind, piAvailable) {
4092
4560
  if (sessionKind === "automatic") return { upload: false };
@@ -4201,33 +4669,10 @@ function snapshotMatches(snapshot, event) {
4201
4669
  function hasActivePublication(state) {
4202
4670
  return state.work.publication.kind !== "none";
4203
4671
  }
4204
- function requireNoPublication(state) {
4672
+ function beginSnapshot(state, publication, source, outputs) {
4205
4673
  if (hasActivePublication(state)) throw new Error("Snapshot publication is already active");
4206
- }
4207
- function beginReadySnapshot(state, source, outputs) {
4208
- requireNoPublication(state);
4209
- const snapshot = {
4210
- point: "after_worker_ready",
4211
- turnRecordId: null,
4212
- required: false
4213
- };
4214
- outputs.push({ kind: "upload_snapshot", ...snapshot, source });
4215
- return {
4216
- ...state,
4217
- work: { ...state.work, publication: { kind: "ready_snapshot", snapshot } }
4218
- };
4219
- }
4220
- function beginTerminalSnapshot(state, point, turnRecordId, terminal, source, outputs) {
4221
- requireNoPublication(state);
4222
- const snapshot = { point, turnRecordId, required: true };
4223
- outputs.push({ kind: "upload_snapshot", ...snapshot, source });
4224
- return {
4225
- ...state,
4226
- work: {
4227
- ...state.work,
4228
- publication: { kind: "terminal_snapshot", snapshot, terminal }
4229
- }
4230
- };
4674
+ outputs.push({ kind: "upload_snapshot", ...publication.snapshot, source });
4675
+ return { ...state, work: { ...state.work, publication } };
4231
4676
  }
4232
4677
  var TERMINAL_ACK_RETRY_MS = 5e3;
4233
4678
  function publishTerminalAndAwaitAcknowledgement(state, terminal, outputs) {
@@ -4247,35 +4692,6 @@ function publishTerminalAndAwaitAcknowledgement(state, terminal, outputs) {
4247
4692
  terminal.correlation.turnRecordId
4248
4693
  );
4249
4694
  }
4250
- function beginCleanupSnapshot(state, source, outputs) {
4251
- requireNoPublication(state);
4252
- const snapshot = {
4253
- point: "before_cleanup_completed",
4254
- turnRecordId: null,
4255
- required: true
4256
- };
4257
- outputs.push({ kind: "upload_snapshot", ...snapshot, source });
4258
- return {
4259
- ...state,
4260
- work: { ...state.work, publication: { kind: "cleanup_snapshot", snapshot } }
4261
- };
4262
- }
4263
- function beginFatalSnapshot(state, fatal, source, afterSnapshot, outputs) {
4264
- requireNoPublication(state);
4265
- const snapshot = {
4266
- point: "before_worker_failed",
4267
- turnRecordId: null,
4268
- required: false
4269
- };
4270
- outputs.push({ kind: "upload_snapshot", ...snapshot, source });
4271
- return {
4272
- ...state,
4273
- work: {
4274
- ...state.work,
4275
- publication: { kind: "fatal_snapshot", snapshot, fatal, afterSnapshot }
4276
- }
4277
- };
4278
- }
4279
4695
  function finishFatal(state, fatal) {
4280
4696
  const outputs = [
4281
4697
  protocol("worker.failed", fatal.payload),
@@ -4317,7 +4733,17 @@ function failureOutputs(state, failure2) {
4317
4733
  };
4318
4734
  if (disposition.snapshot && !hasActivePublication(state)) {
4319
4735
  const afterSnapshot = state.phase.kind === "cleaning" && state.phase.stage === "publication" ? "cleanup" : "exit";
4320
- next = beginFatalSnapshot(next, fatal, disposition.snapshot.source, afterSnapshot, outputs);
4736
+ next = beginSnapshot(
4737
+ next,
4738
+ {
4739
+ kind: "fatal_snapshot",
4740
+ snapshot: { point: "before_worker_failed", turnRecordId: null, required: false },
4741
+ fatal,
4742
+ afterSnapshot
4743
+ },
4744
+ disposition.snapshot.source,
4745
+ outputs
4746
+ );
4321
4747
  break;
4322
4748
  }
4323
4749
  const finished = finishFatal(next, fatal);
@@ -4420,11 +4846,15 @@ function advance(state, outputs) {
4420
4846
  next.session.piAvailable
4421
4847
  ) : { upload: false };
4422
4848
  if (cleanupSnapshot.upload && next.session) {
4423
- next = beginCleanupSnapshot(
4849
+ next = beginSnapshot(
4424
4850
  {
4425
4851
  ...next,
4426
4852
  phase: { kind: "cleaning", reason, exitAfterCleanup, stage: "publication" }
4427
4853
  },
4854
+ {
4855
+ kind: "cleanup_snapshot",
4856
+ snapshot: { point: "before_cleanup_completed", turnRecordId: null, required: true }
4857
+ },
4428
4858
  sessionSnapshotSource(next.session),
4429
4859
  outputs
4430
4860
  );
@@ -4513,9 +4943,11 @@ function reduceWorkerRuntime(state, event) {
4513
4943
  if (state.phase.kind !== "init") break;
4514
4944
  next = { ...state, phase: { kind: "waiting_for_start" } };
4515
4945
  outputs.push(HELLO);
4946
+ outputs.push(protocol("worker.bootstrap_progress", { phase: "worker_connected" }));
4516
4947
  break;
4517
4948
  case "transport_connected":
4518
4949
  outputs.push(HELLO);
4950
+ outputs.push(protocol("worker.bootstrap_progress", { phase: "worker_connected" }));
4519
4951
  if (state.session) {
4520
4952
  outputs.push(
4521
4953
  protocol("worker.heartbeat", {
@@ -4614,6 +5046,7 @@ function reduceWorkerRuntime(state, event) {
4614
5046
  },
4615
5047
  sessionTainted: false
4616
5048
  };
5049
+ outputs.push(protocol("worker.bootstrap_progress", { phase: "preparing_workspace" }));
4617
5050
  outputs.push({ kind: "bootstrap", startRecordId, payload: message.payload });
4618
5051
  break;
4619
5052
  }
@@ -4728,6 +5161,8 @@ function reduceWorkerRuntime(state, event) {
4728
5161
  kind: "diagnostic",
4729
5162
  payload: { level: "warn", code: "bootstrap.diagnostic", message }
4730
5163
  });
5164
+ outputs.push(protocol("worker.bootstrap_progress", { phase: "loading_resources" }));
5165
+ outputs.push(protocol("worker.bootstrap_progress", { phase: "preparing_turn" }));
4731
5166
  outputs.push(protocol("worker.ready", completion.readyPayload));
4732
5167
  if (wasDraining) break;
4733
5168
  const readySnapshot = resolveWorkerSnapshotPolicy(
@@ -4736,7 +5171,15 @@ function reduceWorkerRuntime(state, event) {
4736
5171
  completion.session.piAvailable
4737
5172
  );
4738
5173
  if (readySnapshot.upload)
4739
- next = beginReadySnapshot(next, sessionSnapshotSource(completion.session), outputs);
5174
+ next = beginSnapshot(
5175
+ next,
5176
+ {
5177
+ kind: "ready_snapshot",
5178
+ snapshot: { point: "after_worker_ready", turnRecordId: null, required: false }
5179
+ },
5180
+ sessionSnapshotSource(completion.session),
5181
+ outputs
5182
+ );
4740
5183
  next = armTimer(
4741
5184
  next,
4742
5185
  outputs,
@@ -4800,7 +5243,9 @@ function reduceWorkerRuntime(state, event) {
4800
5243
  });
4801
5244
  break;
4802
5245
  case "activation_failed":
4803
- if (!matchesActivation(state, event.startRecordId, event.turnRecordId)) break;
5246
+ case "turn_defect":
5247
+ if (event.kind === "activation_failed" ? !matchesActivation(state, event.startRecordId, event.turnRecordId) : !matchesTurn(state, event.turnRecordId))
5248
+ break;
4804
5249
  if (state.phase.kind === "draining") {
4805
5250
  next = finishDrainingOperation(state);
4806
5251
  } else {
@@ -4878,6 +5323,7 @@ function reduceWorkerRuntime(state, event) {
4878
5323
  forkPiEntryId: event.result.meta.forkPiEntryId ?? null,
4879
5324
  resultPiEntryId: event.result.meta.resultPiEntryId ?? null,
4880
5325
  turnResultMarkdown: event.result.meta.turnResultMarkdown ?? null,
5326
+ resultSummary: event.result.meta.resultSummary,
4881
5327
  rootEntryId: event.result.meta.rootEntryId ?? null
4882
5328
  }),
4883
5329
  park: null,
@@ -4892,125 +5338,61 @@ function reduceWorkerRuntime(state, event) {
4892
5338
  };
4893
5339
  } else {
4894
5340
  const disposition = normalizeWorkerFailure({
4895
- kind: "turn",
4896
- error: event.result.failure.failure,
4897
- correlation: event.result.failure,
4898
- session: failureContext(state)
4899
- });
4900
- if (disposition.terminal.kind !== "turn_failed")
4901
- throw new Error("Turn failure policy did not produce a turn failure");
4902
- pending = {
4903
- fact: protocol("worker.turn_failed", disposition.terminal.payload),
4904
- park: disposition.terminal.park,
4905
- correlation: event.result.failure
4906
- };
4907
- }
4908
- next = {
4909
- ...next,
4910
- phase: state.phase.kind === "active" ? { ...state.phase, turnStatus: "completed" } : next.phase
4911
- };
4912
- if (state.session?.kind === "automatic") {
4913
- next = publishTerminalAndAwaitAcknowledgement(next, pending, outputs);
4914
- } else if (state.session) {
4915
- const point = event.result.kind === "outcome" ? "before_turn_outcome" : "before_turn_failed";
4916
- const snapshotPolicy = resolveWorkerSnapshotPolicy(
4917
- point,
4918
- state.session.kind,
4919
- state.session.piAvailable
4920
- );
4921
- if (!snapshotPolicy.upload)
4922
- throw new Error("LLM terminal snapshot policy unexpectedly skipped upload");
4923
- next = beginTerminalSnapshot(
4924
- next,
4925
- point,
4926
- event.turnRecordId,
4927
- pending,
4928
- sessionSnapshotSource(state.session),
4929
- outputs
4930
- );
4931
- }
4932
- break;
4933
- }
4934
- case "turn_defect":
4935
- if (!matchesTurn(state, event.turnRecordId)) break;
4936
- if (state.phase.kind === "draining") {
4937
- next = finishDrainingOperation(state);
4938
- } else {
4939
- const failed = failureOutputs(next, {
4940
- kind: "dispatch",
4941
- error: event.error,
4942
- state: "busy",
4943
- session: failureContext(state)
4944
- });
4945
- next = failed.state;
4946
- outputs.push(...failed.outputs);
4947
- }
4948
- break;
4949
- case "snapshot_succeeded": {
4950
- const publication = state.work.publication;
4951
- switch (publication.kind) {
4952
- case "none":
4953
- case "terminal_pending_ack":
4954
- case "fatal_pending_cleanup":
4955
- break;
4956
- case "ready_snapshot":
4957
- if (!snapshotMatches(publication.snapshot, event)) break;
4958
- next = { ...state, work: { ...state.work, publication: { kind: "none" } } };
4959
- break;
4960
- case "terminal_snapshot":
4961
- if (!snapshotMatches(publication.snapshot, event)) break;
4962
- next = publishTerminalAndAwaitAcknowledgement(state, publication.terminal, outputs);
4963
- break;
4964
- case "cleanup_snapshot":
4965
- if (!snapshotMatches(publication.snapshot, event)) break;
4966
- if (state.phase.kind !== "cleaning" || state.phase.stage !== "publication")
4967
- throw new Error("Cleanup snapshot completed outside cleanup publication");
4968
- outputs.push({ kind: "cleanup" });
4969
- next = {
4970
- ...state,
4971
- phase: { ...state.phase, stage: "resources" },
4972
- work: { ...state.work, publication: { kind: "none" } }
4973
- };
4974
- break;
4975
- case "fatal_snapshot":
4976
- if (!snapshotMatches(publication.snapshot, event)) break;
4977
- if (publication.afterSnapshot === "exit") {
4978
- const finished = finishFatal(state, publication.fatal);
4979
- next = finished.state;
4980
- outputs.push(...finished.outputs);
4981
- } else {
4982
- if (state.phase.kind !== "cleaning" || state.phase.stage !== "publication")
4983
- throw new Error("Fatal snapshot completed outside cleanup publication");
4984
- outputs.push({ kind: "cleanup" });
4985
- next = {
4986
- ...state,
4987
- phase: { ...state.phase, stage: "resources" },
4988
- work: {
4989
- ...state.work,
4990
- publication: {
4991
- kind: "fatal_pending_cleanup",
4992
- fatal: publication.fatal
4993
- }
4994
- }
4995
- };
4996
- }
4997
- break;
5341
+ kind: "turn",
5342
+ error: event.result.failure.failure,
5343
+ correlation: event.result.failure,
5344
+ session: failureContext(state)
5345
+ });
5346
+ if (disposition.terminal.kind !== "turn_failed")
5347
+ throw new Error("Turn failure policy did not produce a turn failure");
5348
+ pending = {
5349
+ fact: protocol("worker.turn_failed", disposition.terminal.payload),
5350
+ park: disposition.terminal.park,
5351
+ correlation: event.result.failure
5352
+ };
5353
+ }
5354
+ next = {
5355
+ ...next,
5356
+ phase: state.phase.kind === "active" ? { ...state.phase, turnStatus: "completed" } : next.phase
5357
+ };
5358
+ if (state.session?.kind === "automatic") {
5359
+ next = publishTerminalAndAwaitAcknowledgement(next, pending, outputs);
5360
+ } else if (state.session) {
5361
+ const point = event.result.kind === "outcome" ? "before_turn_outcome" : "before_turn_failed";
5362
+ const snapshotPolicy = resolveWorkerSnapshotPolicy(
5363
+ point,
5364
+ state.session.kind,
5365
+ state.session.piAvailable
5366
+ );
5367
+ if (!snapshotPolicy.upload)
5368
+ throw new Error("LLM terminal snapshot policy unexpectedly skipped upload");
5369
+ next = beginSnapshot(
5370
+ next,
5371
+ {
5372
+ kind: "terminal_snapshot",
5373
+ snapshot: { point, turnRecordId: event.turnRecordId, required: true },
5374
+ terminal: pending
5375
+ },
5376
+ sessionSnapshotSource(state.session),
5377
+ outputs
5378
+ );
4998
5379
  }
4999
5380
  break;
5000
5381
  }
5382
+ case "snapshot_succeeded":
5001
5383
  case "snapshot_failed": {
5002
5384
  const publication = state.work.publication;
5385
+ if (!("snapshot" in publication) || !snapshotMatches(publication.snapshot, event)) break;
5386
+ const completion = event.kind === "snapshot_succeeded" ? "completed" : "failed";
5003
5387
  switch (publication.kind) {
5004
- case "none":
5005
- case "terminal_pending_ack":
5006
- case "fatal_pending_cleanup":
5007
- break;
5008
5388
  case "ready_snapshot":
5009
- if (!snapshotMatches(publication.snapshot, event)) break;
5010
5389
  next = { ...state, work: { ...state.work, publication: { kind: "none" } } };
5011
5390
  break;
5012
5391
  case "terminal_snapshot": {
5013
- if (!snapshotMatches(publication.snapshot, event)) break;
5392
+ if (event.kind === "snapshot_succeeded") {
5393
+ next = publishTerminalAndAwaitAcknowledgement(state, publication.terminal, outputs);
5394
+ break;
5395
+ }
5014
5396
  const cleared = {
5015
5397
  ...state,
5016
5398
  work: { ...state.work, publication: { kind: "none" } }
@@ -5027,41 +5409,41 @@ function reduceWorkerRuntime(state, event) {
5027
5409
  break;
5028
5410
  }
5029
5411
  case "cleanup_snapshot": {
5030
- if (!snapshotMatches(publication.snapshot, event)) break;
5031
5412
  if (state.phase.kind !== "cleaning" || state.phase.stage !== "publication")
5032
- throw new Error("Cleanup snapshot failed outside cleanup publication");
5413
+ throw new Error(`Cleanup snapshot ${completion} outside cleanup publication`);
5033
5414
  const cleared = {
5034
5415
  ...state,
5035
5416
  work: { ...state.work, publication: { kind: "none" } }
5036
5417
  };
5037
- const failed = failureOutputs(cleared, {
5038
- kind: "cleanup",
5039
- error: event.error,
5040
- session: failureContext(state)
5041
- });
5042
- next = failed.state;
5043
- outputs.push(...failed.outputs);
5418
+ if (event.kind === "snapshot_succeeded") {
5419
+ outputs.push({ kind: "cleanup" });
5420
+ next = { ...cleared, phase: { ...state.phase, stage: "resources" } };
5421
+ } else {
5422
+ const failed = failureOutputs(cleared, {
5423
+ kind: "cleanup",
5424
+ error: event.error,
5425
+ session: failureContext(state)
5426
+ });
5427
+ next = failed.state;
5428
+ outputs.push(...failed.outputs);
5429
+ }
5044
5430
  break;
5045
5431
  }
5046
5432
  case "fatal_snapshot":
5047
- if (!snapshotMatches(publication.snapshot, event)) break;
5048
5433
  if (publication.afterSnapshot === "exit") {
5049
5434
  const finished = finishFatal(state, publication.fatal);
5050
5435
  next = finished.state;
5051
5436
  outputs.push(...finished.outputs);
5052
5437
  } else {
5053
5438
  if (state.phase.kind !== "cleaning" || state.phase.stage !== "publication")
5054
- throw new Error("Fatal snapshot failed outside cleanup publication");
5439
+ throw new Error(`Fatal snapshot ${completion} outside cleanup publication`);
5055
5440
  outputs.push({ kind: "cleanup" });
5056
5441
  next = {
5057
5442
  ...state,
5058
5443
  phase: { ...state.phase, stage: "resources" },
5059
5444
  work: {
5060
5445
  ...state.work,
5061
- publication: {
5062
- kind: "fatal_pending_cleanup",
5063
- fatal: publication.fatal
5064
- }
5446
+ publication: { kind: "fatal_pending_cleanup", fatal: publication.fatal }
5065
5447
  }
5066
5448
  };
5067
5449
  }
@@ -5229,9 +5611,6 @@ function resolveWorkerRuntimeSettings(config, payload) {
5229
5611
  }
5230
5612
 
5231
5613
  // src/runtime/turn-execution.ts
5232
- import {
5233
- failActiveTurnProgress
5234
- } from "@leitwerk-dev/domain";
5235
5614
  import { assertValidLlmTurnDefinition } from "@leitwerk-dev/process-sdk";
5236
5615
 
5237
5616
  // src/turn-execution-result.ts
@@ -5310,6 +5689,7 @@ function createAutomaticTurnExecutor(input) {
5310
5689
  forkPiEntryId: null,
5311
5690
  resultPiEntryId: null,
5312
5691
  turnResultMarkdown: completeInput.markdown ?? null,
5692
+ resultSummary: completeInput.resultSummary,
5313
5693
  rootEntryId: input.piHandle ? resolveRootEntryIdFromHandle(input.piHandle) : readProcessSemanticEntryRefs(input.state)?.rootEntry?.entryId ?? null
5314
5694
  }
5315
5695
  };
@@ -5403,8 +5783,7 @@ async function promptWithGuards(deps, input) {
5403
5783
  let maxDurationTimer = null;
5404
5784
  let inactivityTimer = null;
5405
5785
  let rejectTimeout = null;
5406
- let timedOut = false;
5407
- let aborted = false;
5786
+ let abortReason = null;
5408
5787
  let sawCompaction = false;
5409
5788
  let removeOperatorAbortListener = null;
5410
5789
  let removeSuspensionListener = null;
@@ -5421,11 +5800,43 @@ async function promptWithGuards(deps, input) {
5421
5800
  inactivityTimer = null;
5422
5801
  }
5423
5802
  };
5803
+ const abortWithinGracePeriod = async (timeoutKind) => {
5804
+ let abortCompleted = false;
5805
+ try {
5806
+ await Promise.race([
5807
+ input.piHandle.abortTurn().then(() => {
5808
+ abortCompleted = true;
5809
+ }),
5810
+ deps.scheduler.sleep(turnAbortGracePeriodMs)
5811
+ ]);
5812
+ if (!abortCompleted) {
5813
+ reportError({
5814
+ level: "error",
5815
+ code: "guard.abort_grace_elapsed",
5816
+ message: `${timeoutKind ? "Timed out" : "Operator-stopped"} turn '${input.turnId}' did not abort within ${turnAbortGracePeriodMs}ms`,
5817
+ turnRecordId: input.turnRecordId,
5818
+ turnId: input.turnId,
5819
+ errorClass: "infrastructure",
5820
+ details: { turnAbortGracePeriodMs, ...timeoutKind ? { timeoutKind } : {} }
5821
+ });
5822
+ }
5823
+ } catch (error) {
5824
+ reportError({
5825
+ level: "error",
5826
+ code: "guard.abort_failed",
5827
+ message: `Failed to abort ${timeoutKind ? "timed out" : "operator-stopped"} turn '${input.turnId}': ${toErrorMessage2(error)}`,
5828
+ turnRecordId: input.turnRecordId,
5829
+ turnId: input.turnId,
5830
+ errorClass: "infrastructure",
5831
+ ...timeoutKind ? { details: { timeoutKind } } : {}
5832
+ });
5833
+ }
5834
+ };
5424
5835
  const requestAbortForTimeout = (timeoutKind, timeoutMs) => {
5425
- if (timedOut || aborted) {
5836
+ if (abortReason !== null) {
5426
5837
  return;
5427
5838
  }
5428
- timedOut = true;
5839
+ abortReason = timeoutKind;
5429
5840
  clearTimers();
5430
5841
  const error = new PromptTimeoutError(input.turnId, timeoutKind, timeoutMs);
5431
5842
  reportError({
@@ -5447,44 +5858,13 @@ async function promptWithGuards(deps, input) {
5447
5858
  details: { turnAbortGracePeriodMs, timeoutMs, timeoutKind }
5448
5859
  });
5449
5860
  rejectTimeout?.(error);
5450
- void (async () => {
5451
- let abortCompleted = false;
5452
- try {
5453
- await Promise.race([
5454
- input.piHandle.abortTurn().then(() => {
5455
- abortCompleted = true;
5456
- }),
5457
- deps.scheduler.sleep(turnAbortGracePeriodMs)
5458
- ]);
5459
- if (!abortCompleted) {
5460
- reportError({
5461
- level: "error",
5462
- code: "guard.abort_grace_elapsed",
5463
- message: `Timed out turn '${input.turnId}' did not abort within ${turnAbortGracePeriodMs}ms`,
5464
- turnRecordId: input.turnRecordId,
5465
- turnId: input.turnId,
5466
- errorClass: "infrastructure",
5467
- details: { turnAbortGracePeriodMs, timeoutKind }
5468
- });
5469
- }
5470
- } catch (error2) {
5471
- reportError({
5472
- level: "error",
5473
- code: "guard.abort_failed",
5474
- message: `Failed to abort timed out turn '${input.turnId}': ${toErrorMessage(error2)}`,
5475
- turnRecordId: input.turnRecordId,
5476
- turnId: input.turnId,
5477
- errorClass: "infrastructure",
5478
- details: { timeoutKind }
5479
- });
5480
- }
5481
- })();
5861
+ void abortWithinGracePeriod(timeoutKind);
5482
5862
  };
5483
5863
  const requestOperatorAbort = () => {
5484
- if (timedOut || aborted) {
5864
+ if (abortReason !== null) {
5485
5865
  return;
5486
5866
  }
5487
- aborted = true;
5867
+ abortReason = "operator_abort";
5488
5868
  clearTimers();
5489
5869
  const error = new OperatorAbortError(input.turnId);
5490
5870
  reportError({
@@ -5505,40 +5885,10 @@ async function promptWithGuards(deps, input) {
5505
5885
  details: { turnAbortGracePeriodMs }
5506
5886
  });
5507
5887
  rejectTimeout?.(error);
5508
- void (async () => {
5509
- let abortCompleted = false;
5510
- try {
5511
- await Promise.race([
5512
- input.piHandle.abortTurn().then(() => {
5513
- abortCompleted = true;
5514
- }),
5515
- deps.scheduler.sleep(turnAbortGracePeriodMs)
5516
- ]);
5517
- if (!abortCompleted) {
5518
- reportError({
5519
- level: "error",
5520
- code: "guard.abort_grace_elapsed",
5521
- message: `Operator-stopped turn '${input.turnId}' did not abort within ${turnAbortGracePeriodMs}ms`,
5522
- turnRecordId: input.turnRecordId,
5523
- turnId: input.turnId,
5524
- errorClass: "infrastructure",
5525
- details: { turnAbortGracePeriodMs }
5526
- });
5527
- }
5528
- } catch (error2) {
5529
- reportError({
5530
- level: "error",
5531
- code: "guard.abort_failed",
5532
- message: `Failed to abort operator-stopped turn '${input.turnId}': ${toErrorMessage(error2)}`,
5533
- turnRecordId: input.turnRecordId,
5534
- turnId: input.turnId,
5535
- errorClass: "infrastructure"
5536
- });
5537
- }
5538
- })();
5888
+ void abortWithinGracePeriod();
5539
5889
  };
5540
5890
  const armMaxDurationTimer = () => {
5541
- if (!turnMaxDurationMs || turnMaxDurationMs <= 0 || maxDurationRemainingMs <= 0 || guardsPaused || timedOut || aborted)
5891
+ if (!turnMaxDurationMs || turnMaxDurationMs <= 0 || maxDurationRemainingMs <= 0 || guardsPaused || abortReason !== null)
5542
5892
  return;
5543
5893
  maxDurationArmedAt = deps.scheduler.now().getTime();
5544
5894
  maxDurationTimer = deps.scheduler.setTimeout(() => {
@@ -5546,7 +5896,7 @@ async function promptWithGuards(deps, input) {
5546
5896
  }, maxDurationRemainingMs);
5547
5897
  };
5548
5898
  const resetInactivityTimer = () => {
5549
- if (!turnInactivityTimeoutMs || turnInactivityTimeoutMs <= 0 || guardsPaused || timedOut || aborted) {
5899
+ if (!turnInactivityTimeoutMs || turnInactivityTimeoutMs <= 0 || guardsPaused || abortReason !== null) {
5550
5900
  return;
5551
5901
  }
5552
5902
  if (inactivityTimer !== null) {
@@ -5571,7 +5921,7 @@ async function promptWithGuards(deps, input) {
5571
5921
  resetInactivityTimer();
5572
5922
  });
5573
5923
  removeSuspensionListener = deps.guardSuspension?.subscribe((paused) => {
5574
- if (guardsPaused === paused || timedOut || aborted) return;
5924
+ if (guardsPaused === paused || abortReason !== null) return;
5575
5925
  guardsPaused = paused;
5576
5926
  if (paused) {
5577
5927
  if (maxDurationTimer !== null) {
@@ -5604,7 +5954,7 @@ async function promptWithGuards(deps, input) {
5604
5954
  }
5605
5955
  const hasGuards = turnMaxDurationMs !== void 0 && turnMaxDurationMs > 0 || turnInactivityTimeoutMs !== void 0 && turnInactivityTimeoutMs > 0 || operatorAbortSignal !== void 0;
5606
5956
  try {
5607
- if (aborted) {
5957
+ if (abortReason === "operator_abort") {
5608
5958
  await guardPromise;
5609
5959
  }
5610
5960
  const result = !hasGuards ? await input.runPrompt() : await Promise.race([input.runPrompt(), guardPromise]);
@@ -5629,7 +5979,11 @@ async function promptWithGuards(deps, input) {
5629
5979
  }
5630
5980
 
5631
5981
  // src/turn-continuation.ts
5632
- import { DEFAULT_CONTINUE_PROMPT, normalizeContinuePrompt } from "@leitwerk-dev/domain";
5982
+ import {
5983
+ DEFAULT_CONTINUE_PROMPT,
5984
+ normalizeContinuePrompt,
5985
+ readNonBlankString as readNonBlankString2
5986
+ } from "@leitwerk-dev/domain";
5633
5987
  function readCurrentLeafMessage(piHandle) {
5634
5988
  const leafId = piHandle.getLeafId();
5635
5989
  if (!leafId) {
@@ -5683,21 +6037,13 @@ async function prepareContinuationUserPrompt(input) {
5683
6037
  }
5684
6038
  return normalizedPrompt;
5685
6039
  }
5686
- function readNonEmptyMetadataString(metadata, key) {
5687
- const value = metadata?.[key];
5688
- return typeof value === "string" && value.trim() !== "" ? value : null;
5689
- }
5690
6040
  function resolveTurnContinuationState(input) {
5691
6041
  if (input.process.selectedTurnId !== input.turnId) {
5692
6042
  return null;
5693
6043
  }
5694
- const continueFromPiEntryId = readNonEmptyMetadataString(
5695
- input.process.metadata,
5696
- "continueFromPiEntryId"
5697
- );
5698
- const continueFromTurnRecordId = readNonEmptyMetadataString(
5699
- input.process.metadata,
5700
- "continueFromTurnRecordId"
6044
+ const continueFromPiEntryId = readNonBlankString2(input.process.metadata?.continueFromPiEntryId);
6045
+ const continueFromTurnRecordId = readNonBlankString2(
6046
+ input.process.metadata?.continueFromTurnRecordId
5701
6047
  );
5702
6048
  if (!continueFromPiEntryId || !continueFromTurnRecordId) {
5703
6049
  return null;
@@ -5705,7 +6051,7 @@ function resolveTurnContinuationState(input) {
5705
6051
  return {
5706
6052
  continueFromPiEntryId,
5707
6053
  continuePrompt: normalizeContinuePrompt(input.process.metadata?.continuePrompt) ?? DEFAULT_CONTINUE_PROMPT,
5708
- savedPrimaryLeafId: readNonEmptyMetadataString(input.process.metadata, "continueSavedPrimaryLeafEntryId") ?? readProcessSemanticEntryRefs(input.state)?.currentPrimaryPathLeaf?.entryId ?? null
6054
+ savedPrimaryLeafId: readNonBlankString2(input.process.metadata?.continueSavedPrimaryLeafEntryId) ?? readProcessSemanticEntryRefs(input.state)?.currentPrimaryPathLeaf?.entryId ?? null
5709
6055
  };
5710
6056
  }
5711
6057
  function resolvePromptlessTurnResumeReason(input) {
@@ -5828,7 +6174,7 @@ function createTurnResultMarkdownState() {
5828
6174
  publicationCount: 0
5829
6175
  };
5830
6176
  }
5831
- function publishTurnResultMarkdownValue(state, value) {
6177
+ function publishTurnResultMarkdownValue(state, value, resultSummary) {
5832
6178
  const validation = validateTurnResultMarkdownValue(value);
5833
6179
  if (!validation.ok) {
5834
6180
  return {
@@ -5843,6 +6189,7 @@ function publishTurnResultMarkdownValue(state, value) {
5843
6189
  }
5844
6190
  const nextState = {
5845
6191
  markdown: validation.markdown,
6192
+ ...typeof resultSummary === "string" && resultSummary.trim() ? { resultSummary: resultSummary.trim() } : {},
5846
6193
  publicationCount: state.publicationCount + 1
5847
6194
  };
5848
6195
  return {
@@ -5863,13 +6210,21 @@ function createMarkdownResultTool(stateRef) {
5863
6210
  name: MARKDOWN_RESULT_TOOL_NAME,
5864
6211
  description: "Publish the operator-facing markdown result for this turn. Pass raw markdown only and do not wrap the entire markdown in triple backticks.",
5865
6212
  parameters: {
6213
+ resultSummary: {
6214
+ type: "string",
6215
+ description: "Concise summary of this attempt\u2019s result, based on completed work."
6216
+ },
5866
6217
  markdown: {
5867
6218
  type: "string",
5868
6219
  description: "Raw markdown content to render for this turn. Do not wrap the entire markdown in triple backticks."
5869
6220
  }
5870
6221
  },
5871
6222
  execute: async (args) => {
5872
- const published = publishTurnResultMarkdownValue(stateRef.current, args.markdown);
6223
+ const published = publishTurnResultMarkdownValue(
6224
+ stateRef.current,
6225
+ args.markdown,
6226
+ args.resultSummary
6227
+ );
5873
6228
  stateRef.current = published.state;
5874
6229
  return published.response;
5875
6230
  }
@@ -6018,35 +6373,14 @@ function finalizeTurnResultMarkdown(input) {
6018
6373
  if (!input.behavior || input.behavior.mode === "none") {
6019
6374
  return { markdown: input.state.markdown ?? null, errorMessage: null };
6020
6375
  }
6021
- if (input.behavior.mode === "assistant_output") {
6022
- const markdown = typeof input.assistantMarkdown === "string" ? input.assistantMarkdown.trim() : "";
6023
- if (markdown.length > 0) {
6024
- return { markdown, errorMessage: null };
6025
- }
6026
- return input.behavior.required ? {
6027
- markdown: null,
6028
- errorMessage: "Turn requires non-empty assistant output to publish turn result markdown"
6029
- } : { markdown: null, errorMessage: null };
6030
- }
6031
- if (input.behavior.mode === "outcome_tool_argument") {
6032
- if (input.state.markdown) {
6033
- return { markdown: input.state.markdown, errorMessage: null };
6034
- }
6035
- return input.behavior.required ? {
6036
- markdown: null,
6037
- errorMessage: `Turn requires a successful outcome tool call with a non-empty '${input.behavior.parameterName}' markdown argument`
6038
- } : { markdown: null, errorMessage: null };
6039
- }
6040
- if (input.state.markdown) {
6041
- return { markdown: input.state.markdown, errorMessage: null };
6042
- }
6043
- if (input.behavior.required) {
6044
- return {
6045
- markdown: null,
6046
- errorMessage: `Turn requires a successful '${input.behavior.toolName}' tool call to publish turn result markdown`
6047
- };
6376
+ const markdown = input.behavior.mode === "assistant_output" ? typeof input.assistantMarkdown === "string" ? input.assistantMarkdown.trim() : null : input.state.markdown;
6377
+ if (markdown || !input.behavior.required) {
6378
+ return { markdown: markdown || null, errorMessage: null };
6048
6379
  }
6049
- return { markdown: null, errorMessage: null };
6380
+ return {
6381
+ markdown: null,
6382
+ errorMessage: input.behavior.mode === "assistant_output" ? "Turn requires non-empty assistant output to publish turn result markdown" : input.behavior.mode === "outcome_tool_argument" ? `Turn requires a successful outcome tool call with a non-empty '${input.behavior.parameterName}' markdown argument` : `Turn requires a successful '${input.behavior.toolName}' tool call to publish turn result markdown`
6383
+ };
6050
6384
  }
6051
6385
 
6052
6386
  // src/turn-outcome-tool-session.ts
@@ -6057,15 +6391,10 @@ function cloneSelectedOutcome(value) {
6057
6391
  function cloneTurnResultMarkdownState(state) {
6058
6392
  return {
6059
6393
  markdown: state.markdown,
6394
+ ...state.resultSummary ? { resultSummary: state.resultSummary } : {},
6060
6395
  publicationCount: state.publicationCount
6061
6396
  };
6062
6397
  }
6063
- function snapshotToolCompletionState(value) {
6064
- return {
6065
- selectedOutcome: cloneSelectedOutcome(value.selectedOutcome),
6066
- markdownState: cloneTurnResultMarkdownState(value.markdownState)
6067
- };
6068
- }
6069
6398
  function createTurnOutcomeToolSession(input) {
6070
6399
  let selectedOutcome = null;
6071
6400
  let terminalAcknowledgement = { kind: "open" };
@@ -6085,7 +6414,13 @@ function createTurnOutcomeToolSession(input) {
6085
6414
  name: outcome,
6086
6415
  description: spec.description,
6087
6416
  parameters: {
6088
- ...Object.fromEntries(Object.entries(spec.parameters).map(([key, value]) => [key, value])),
6417
+ ...Object.fromEntries(Object.entries(spec.parameters)),
6418
+ ...injectsGlobalMarkdownParameter ? {
6419
+ resultSummary: {
6420
+ type: "string",
6421
+ description: "Concise result summary for this attempt."
6422
+ }
6423
+ } : {},
6089
6424
  ...injectsGlobalMarkdownParameter && outcomeToolMarkdownParameterName ? {
6090
6425
  [outcomeToolMarkdownParameterName]: {
6091
6426
  type: "string",
@@ -6101,10 +6436,15 @@ function createTurnOutcomeToolSession(input) {
6101
6436
  const acceptsOutcome = selectedOutcome === null;
6102
6437
  if (acceptsOutcome) {
6103
6438
  let outcomeParams = args;
6439
+ if (spec.resultSummaryParameter && typeof args[spec.resultSummaryParameter] === "string")
6440
+ turnResultMarkdownStateRef.current.resultSummary = String(
6441
+ args[spec.resultSummaryParameter]
6442
+ ).trim();
6104
6443
  if (markdownParameterName) {
6105
6444
  const published = publishTurnResultMarkdownValue(
6106
6445
  turnResultMarkdownStateRef.current,
6107
- args[markdownParameterName]
6446
+ args[markdownParameterName],
6447
+ spec.resultSummaryParameter ? args[spec.resultSummaryParameter] : injectsGlobalMarkdownParameter ? args.resultSummary : void 0
6108
6448
  );
6109
6449
  if (!published.response.ok) {
6110
6450
  return published.response;
@@ -6113,6 +6453,7 @@ function createTurnOutcomeToolSession(input) {
6113
6453
  if (injectsGlobalMarkdownParameter) {
6114
6454
  outcomeParams = { ...args };
6115
6455
  delete outcomeParams[markdownParameterName];
6456
+ delete outcomeParams.resultSummary;
6116
6457
  }
6117
6458
  }
6118
6459
  selectedOutcome = { outcome, params: outcomeParams };
@@ -6161,9 +6502,7 @@ function createTurnOutcomeToolSession(input) {
6161
6502
  failureReason: () => terminalAcknowledgement.kind === "acknowledgement_failed_ignored" ? terminalAcknowledgement.reason : null
6162
6503
  };
6163
6504
  return {
6164
- outcomeToolNames,
6165
6505
  usesOutcomeTools,
6166
- requiresMarkdownResultToolCall,
6167
6506
  tools,
6168
6507
  activeTools,
6169
6508
  terminalAcknowledgement: terminalAcknowledgementControl,
@@ -6189,10 +6528,10 @@ function createTurnOutcomeToolSession(input) {
6189
6528
  );
6190
6529
  },
6191
6530
  getCompletionState() {
6192
- return snapshotToolCompletionState({
6193
- selectedOutcome,
6194
- markdownState: turnResultMarkdownStateRef.current
6195
- });
6531
+ return {
6532
+ selectedOutcome: cloneSelectedOutcome(selectedOutcome),
6533
+ markdownState: cloneTurnResultMarkdownState(turnResultMarkdownStateRef.current)
6534
+ };
6196
6535
  },
6197
6536
  shouldBlockToolCall(toolName) {
6198
6537
  if (selectedOutcome === null) {
@@ -6228,9 +6567,7 @@ function createTurnOutcomeToolSession(input) {
6228
6567
  ...recovery.missingToolNames.length > 0 ? { missingToolNames: recovery.missingToolNames } : {}
6229
6568
  };
6230
6569
  },
6231
- describeRecovery(recovery) {
6232
- return describeMissingTurnToolCallRecovery(recovery);
6233
- },
6570
+ describeRecovery: describeMissingTurnToolCallRecovery,
6234
6571
  finalizeMarkdown(completionState, assistantMarkdown) {
6235
6572
  return finalizeTurnResultMarkdown({
6236
6573
  behavior: input.turnDef.turnResultMarkdown,
@@ -6244,13 +6581,7 @@ function createTurnOutcomeToolSession(input) {
6244
6581
  // src/logical-prompt-runner.ts
6245
6582
  var MAX_COMPACTION_CONTINUE_ATTEMPTS = 3;
6246
6583
  function shouldAutoContinueAfterPromptReturn(input) {
6247
- if (input.resolvedOutcome) {
6248
- return false;
6249
- }
6250
- if (!input.sawCompaction) {
6251
- return false;
6252
- }
6253
- return input.compactionContinueAttempts < MAX_COMPACTION_CONTINUE_ATTEMPTS;
6584
+ return !input.resolvedOutcome && input.sawCompaction && input.compactionContinueAttempts < MAX_COMPACTION_CONTINUE_ATTEMPTS;
6254
6585
  }
6255
6586
  function isContextWindowError(error) {
6256
6587
  const message = error instanceof Error ? error.message : String(error);
@@ -6314,9 +6645,7 @@ async function executeLogicalPromptPlan(input) {
6314
6645
  );
6315
6646
  };
6316
6647
  for (; ; ) {
6317
- const continuePlan = currentPlan.kind === "continue" ? currentPlan : null;
6318
- const promptPlan = currentPlan.kind === "prompt" ? currentPlan : null;
6319
- const usingContinueThisAttempt = continuePlan !== null;
6648
+ const plan = currentPlan;
6320
6649
  const guardSuspension = new PromptGuardSuspension();
6321
6650
  const promptOptions = input.toolSession.tools.length > 0 ? {
6322
6651
  tools: input.toolSession.tools,
@@ -6329,13 +6658,13 @@ async function executeLogicalPromptPlan(input) {
6329
6658
  isOperatorAbortRequested: () => input.operatorAbortSignal?.aborted === true
6330
6659
  }
6331
6660
  } : { activeTools: input.toolSession.activeTools };
6332
- let preparedPromptRun = null;
6333
- if (continuePlan) {
6661
+ let runPrompt = () => plan.kind === "continue" ? input.piHandle.continueTurn(promptOptions) : input.piHandle.prompt(plan.promptText ?? "", promptOptions);
6662
+ if (plan.kind === "continue") {
6334
6663
  try {
6335
- await continuePlan.prepareForContinuation?.();
6336
- if (continuePlan.continueUserPrompt !== null) {
6337
- const content = continuePlan.continueUserPrompt;
6338
- const identity = continuePlan.identifiedPrompt;
6664
+ await plan.prepareForContinuation?.();
6665
+ if (plan.continueUserPrompt !== null) {
6666
+ const content = plan.continueUserPrompt;
6667
+ const identity = plan.identifiedPrompt;
6339
6668
  if (identity) {
6340
6669
  const expectedParentId = input.piHandle.getLeafId();
6341
6670
  if (findIdentifiedPrompt(input.piHandle, identity)) {
@@ -6346,7 +6675,7 @@ async function executeLogicalPromptPlan(input) {
6346
6675
  expectedParentId
6347
6676
  });
6348
6677
  } else {
6349
- preparedPromptRun = () => input.piHandle.promptCustom({ content, details: identity }, promptOptions);
6678
+ runPrompt = () => input.piHandle.promptCustom({ content, details: identity }, promptOptions);
6350
6679
  }
6351
6680
  } else {
6352
6681
  const promptText = await prepareContinuationUserPrompt({
@@ -6355,7 +6684,7 @@ async function executeLogicalPromptPlan(input) {
6355
6684
  promptText: content
6356
6685
  });
6357
6686
  if (promptText) {
6358
- preparedPromptRun = () => input.piHandle.promptLiteral(promptText, promptOptions);
6687
+ runPrompt = () => input.piHandle.promptLiteral(promptText, promptOptions);
6359
6688
  }
6360
6689
  }
6361
6690
  }
@@ -6378,13 +6707,7 @@ async function executeLogicalPromptPlan(input) {
6378
6707
  piHandle: input.piHandle,
6379
6708
  turnRecordId: input.turnRecordId,
6380
6709
  turnId: input.turnId,
6381
- runPrompt: () => {
6382
- if (preparedPromptRun) return preparedPromptRun();
6383
- if (continuePlan) {
6384
- return input.piHandle.continueTurn(promptOptions);
6385
- }
6386
- return input.piHandle.prompt(promptPlan?.promptText ?? "", promptOptions);
6387
- }
6710
+ runPrompt
6388
6711
  }
6389
6712
  );
6390
6713
  if (input.toolSession.terminalAcknowledgement.state() === "outcome_accepted") {
@@ -6451,10 +6774,10 @@ async function executeLogicalPromptPlan(input) {
6451
6774
  continue;
6452
6775
  }
6453
6776
  return reportFailure(error, {
6454
- code: usingContinueThisAttempt ? "turn.continue_failed" : "turn.prompt_failed",
6777
+ code: plan.kind === "continue" ? "turn.continue_failed" : "turn.prompt_failed",
6455
6778
  emitWorkerError: !(error instanceof PromptTimeoutError || error instanceof OperatorAbortError),
6456
6779
  fallbackErrorClass: "llm_error",
6457
- messagePrefix: usingContinueThisAttempt ? `Turn '${input.turnId}' continuation failed` : `Turn '${input.turnId}' prompt failed`
6780
+ messagePrefix: plan.kind === "continue" ? `Turn '${input.turnId}' continuation failed` : `Turn '${input.turnId}' prompt failed`
6458
6781
  });
6459
6782
  }
6460
6783
  }
@@ -6469,12 +6792,7 @@ async function runMissingToolRecovery(input) {
6469
6792
  input.initialAttempt.completionState
6470
6793
  );
6471
6794
  if (!baseMissingToolRecovery) {
6472
- return {
6473
- recovered: true,
6474
- finalAttempt: input.initialAttempt,
6475
- recoveryContext: null,
6476
- baseMissingToolRecoveryDescription: null
6477
- };
6795
+ return { finalAttempt: input.initialAttempt };
6478
6796
  }
6479
6797
  const recoveryContext = input.toolSession.buildRecoveryContext(baseMissingToolRecovery);
6480
6798
  const description = input.toolSession.describeRecovery(baseMissingToolRecovery);
@@ -6512,12 +6830,7 @@ async function runMissingToolRecovery(input) {
6512
6830
  { baseState: input.initialAttempt.completionState }
6513
6831
  );
6514
6832
  if (!input.toolSession.resolveMissingToolRecovery(finalAttempt.completionState)) {
6515
- return {
6516
- recovered: true,
6517
- finalAttempt,
6518
- recoveryContext,
6519
- baseMissingToolRecoveryDescription: description
6520
- };
6833
+ return { finalAttempt };
6521
6834
  }
6522
6835
  }
6523
6836
  reportError({
@@ -6532,10 +6845,8 @@ async function runMissingToolRecovery(input) {
6532
6845
  }
6533
6846
  });
6534
6847
  return {
6535
- recovered: false,
6536
6848
  finalAttempt,
6537
- recoveryContext,
6538
- baseMissingToolRecoveryDescription: description
6849
+ failure: { recoveryContext, description }
6539
6850
  };
6540
6851
  }
6541
6852
 
@@ -6566,20 +6877,9 @@ ${guidance}`
6566
6877
  );
6567
6878
  }
6568
6879
  var PI_SESSION_BOOTSTRAP_ENTRY_TYPES = /* @__PURE__ */ new Set(["model_change", "thinking_level_change"]);
6569
- function visitPiTreeEntries(nodes, visit) {
6570
- for (const node of nodes) {
6571
- visit(node.entry.type);
6572
- visitPiTreeEntries(node.children, visit);
6573
- }
6574
- }
6575
6880
  function isPiTreeEmptyForPreparedEmptyPlan(piHandle) {
6576
- let hasNonBootstrap = false;
6577
- visitPiTreeEntries(piHandle.getTree(), (entryType) => {
6578
- if (!PI_SESSION_BOOTSTRAP_ENTRY_TYPES.has(entryType)) {
6579
- hasNonBootstrap = true;
6580
- }
6581
- });
6582
- return !hasNonBootstrap;
6881
+ const isBootstrapOnly = (node) => PI_SESSION_BOOTSTRAP_ENTRY_TYPES.has(node.entry.type) && node.children.every(isBootstrapOnly);
6882
+ return piHandle.getTree().every(isBootstrapOnly);
6583
6883
  }
6584
6884
  function treePlanFromPreparedStart(input) {
6585
6885
  const { preparedStart, turnDef, piHandle } = input;
@@ -6749,7 +7049,7 @@ async function executeLlmTurn(input) {
6749
7049
  reportError({
6750
7050
  level: "error",
6751
7051
  code: "turn.primary_leaf_restore_failed",
6752
- message: `Failed to restore the primary path leaf after turn '${turnId}': ${toErrorMessage(restoreError)}`,
7052
+ message: `Failed to restore the primary path leaf after turn '${turnId}': ${toErrorMessage2(restoreError)}`,
6753
7053
  turnRecordId,
6754
7054
  turnId,
6755
7055
  errorClass: "infrastructure"
@@ -6757,7 +7057,7 @@ async function executeLlmTurn(input) {
6757
7057
  failure2 = new TurnExecutionError(
6758
7058
  turnId,
6759
7059
  "infrastructure",
6760
- `${message}. Failed to restore the primary path leaf: ${toErrorMessage(restoreError)}`,
7060
+ `${message}. Failed to restore the primary path leaf: ${toErrorMessage2(restoreError)}`,
6761
7061
  { recoveryContext: null }
6762
7062
  );
6763
7063
  }
@@ -6801,12 +7101,12 @@ async function executeLlmTurn(input) {
6801
7101
  let promptText = null;
6802
7102
  if (initialPromptlessTurnResumeReason === null || initialPromptlessTurnResumeReason === "active_turn_resume") {
6803
7103
  try {
6804
- promptText = await input.turnDef.prompt(input.ctx);
7104
+ promptText = await input.turnDef.prompt({ ...input.ctx, prepared: input.prepared });
6805
7105
  } catch (error) {
6806
7106
  return failWithWorkerError(
6807
7107
  "turn.prompt_preparation_failed",
6808
7108
  "infrastructure",
6809
- `Turn '${turnId}' prompt preparation failed: ${toErrorMessage(error)}`,
7109
+ `Turn '${turnId}' prompt preparation failed: ${toErrorMessage2(error)}`,
6810
7110
  null,
6811
7111
  { restorePrimaryLeaf: false }
6812
7112
  );
@@ -6964,14 +7264,15 @@ async function executeLlmTurn(input) {
6964
7264
  const finalCompletionState = recoveryResult.finalAttempt.completionState;
6965
7265
  const finalPromptResult = recoveryResult.finalAttempt.promptResult;
6966
7266
  const finalResolvedOutcome = recoveryResult.finalAttempt.resolvedOutcome;
6967
- if (!recoveryResult.recovered) {
7267
+ if (recoveryResult.failure) {
7268
+ const { recoveryContext, description } = recoveryResult.failure;
6968
7269
  return reportFailedTurn(
6969
7270
  "protocol_error",
6970
- `Turn '${turnId}' completed without the required tool calls after ${MAX_MISSING_TOOL_CALL_RECOVERY_ATTEMPTS} automatic recovery attempts: ${recoveryResult.baseMissingToolRecoveryDescription}`,
7271
+ `Turn '${turnId}' completed without the required tool calls after ${MAX_MISSING_TOOL_CALL_RECOVERY_ATTEMPTS} automatic recovery attempts: ${description}`,
6971
7272
  finalPromptResult.resultEntryId,
6972
7273
  {
6973
- recoveryContext: recoveryResult.recoveryContext,
6974
- restorePrimaryLeaf: recoveryResult.recoveryContext?.failureCode !== "missing_markdown_result"
7274
+ recoveryContext,
7275
+ restorePrimaryLeaf: recoveryContext.failureCode !== "missing_markdown_result"
6975
7276
  }
6976
7277
  );
6977
7278
  }
@@ -7017,6 +7318,7 @@ async function executeLlmTurn(input) {
7017
7318
  forkPiEntryId: treePlan.forkPiEntryId,
7018
7319
  resultPiEntryId: finalPromptResult.resultEntryId,
7019
7320
  turnResultMarkdown: finalizedTurnResultMarkdown.markdown,
7321
+ resultSummary: finalCompletionState.markdownState.resultSummary,
7020
7322
  rootEntryId: rootEntryIdAfterTurn
7021
7323
  }
7022
7324
  };
@@ -7026,6 +7328,21 @@ async function executeLlmTurn(input) {
7026
7328
  function failedResult(failure2, appliedTargetedInputs) {
7027
7329
  return { kind: "failed", failure: failure2, appliedTargetedInputs };
7028
7330
  }
7331
+ function normalizePreparedData(value) {
7332
+ if (value === void 0) {
7333
+ throw new Error("LLM turn preparation must return JSON-serializable data");
7334
+ }
7335
+ let serialized;
7336
+ try {
7337
+ serialized = JSON.stringify(value);
7338
+ } catch {
7339
+ throw new Error("LLM turn preparation must return JSON-serializable data");
7340
+ }
7341
+ if (Buffer.byteLength(serialized, "utf8") > 65536) {
7342
+ throw new Error("LLM turn preparation data exceeds 65536 bytes");
7343
+ }
7344
+ return JSON.parse(serialized);
7345
+ }
7029
7346
  async function executeSelectedTurn(input) {
7030
7347
  const { resolvedWorkerProcess, processSnapshot, projectSnapshots } = input.session;
7031
7348
  const { piHandle } = input;
@@ -7042,6 +7359,21 @@ async function executeSelectedTurn(input) {
7042
7359
  if (!handler) throw new Error(`Validated turn handler '${currentTurnId}' is unavailable`);
7043
7360
  let automaticIntegrationCallIndex = 0;
7044
7361
  let latestProgressReport = null;
7362
+ const reportProgress = (report) => {
7363
+ latestProgressReport = report;
7364
+ input.emit({ kind: "progress", turnRecordId: input.turnRecordId, report });
7365
+ };
7366
+ const callIntegrationTool = async (name, args) => {
7367
+ const tool = input.integrationTools?.find((candidate) => candidate.name === name);
7368
+ if (!tool) {
7369
+ throw new Error(`Integration tool '${name}' is not authorized for turn '${currentTurnId}'`);
7370
+ }
7371
+ automaticIntegrationCallIndex += 1;
7372
+ return tool.execute(args, {
7373
+ toolCallId: selectedTurnType === "automatic" ? `${input.turnRecordId}:${automaticIntegrationCallIndex}:${name}` : `${input.turnRecordId}:prepare:${automaticIntegrationCallIndex}:${name}`,
7374
+ signal: input.signal
7375
+ });
7376
+ };
7045
7377
  const ctx = {
7046
7378
  process: processSnapshot,
7047
7379
  projects: projectSnapshots,
@@ -7051,23 +7383,8 @@ async function executeSelectedTurn(input) {
7051
7383
  turnResultMarkdownByProduct: input.session.turnResultMarkdownByProduct,
7052
7384
  workspaceRoot: input.session.workspaceRoot,
7053
7385
  ...selectedTurnType === "automatic" ? {
7054
- reportProgress(report) {
7055
- latestProgressReport = report;
7056
- input.emit({ kind: "progress", turnRecordId: input.turnRecordId, report });
7057
- },
7058
- async callIntegrationTool(name, args) {
7059
- const tool = input.integrationTools?.find((candidate) => candidate.name === name);
7060
- if (!tool) {
7061
- throw new Error(
7062
- `Integration tool '${name}' is not authorized for turn '${currentTurnId}'`
7063
- );
7064
- }
7065
- automaticIntegrationCallIndex += 1;
7066
- return tool.execute(args, {
7067
- toolCallId: `${input.turnRecordId}:${automaticIntegrationCallIndex}:${name}`,
7068
- signal: input.signal
7069
- });
7070
- }
7386
+ reportProgress,
7387
+ callIntegrationTool
7071
7388
  } : {}
7072
7389
  };
7073
7390
  let terminal = null;
@@ -7099,9 +7416,36 @@ async function executeSelectedTurn(input) {
7099
7416
  `Turn '${currentTurnId}' requires a Pi handle`
7100
7417
  );
7101
7418
  }
7419
+ let prepared = input.session.llmPreparation?.data;
7420
+ if (turnDef.prepare && !input.session.llmPreparation) {
7421
+ try {
7422
+ prepared = normalizePreparedData(
7423
+ await turnDef.prepare({
7424
+ ...ctx,
7425
+ reportProgress,
7426
+ callIntegrationTool
7427
+ })
7428
+ );
7429
+ input.emit({ kind: "prepared", turnRecordId: input.turnRecordId, data: prepared });
7430
+ } catch (error) {
7431
+ const message = error instanceof Error ? error.message : String(error);
7432
+ throw new TurnExecutionFailure({
7433
+ turnRecordId: input.turnRecordId,
7434
+ turnId: currentTurnId,
7435
+ turnType: "llm",
7436
+ pathType: turnDef.branchType,
7437
+ failure: new TurnExecutionError(
7438
+ currentTurnId,
7439
+ "infrastructure",
7440
+ `Turn '${currentTurnId}' preparation failed: ${message}`
7441
+ )
7442
+ });
7443
+ }
7444
+ }
7102
7445
  const completed = await executeLlmTurn({
7103
7446
  resolvedWorkerProcess,
7104
7447
  ctx,
7448
+ ...turnDef.prepare ? { prepared } : {},
7105
7449
  piHandle,
7106
7450
  turnDef,
7107
7451
  turnId: currentTurnId,
@@ -7168,10 +7512,16 @@ async function executeSelectedTurn(input) {
7168
7512
  } catch (error) {
7169
7513
  const failedProgressReport = latestProgressReport;
7170
7514
  if (failedProgressReport) {
7515
+ const message = error instanceof Error ? error.message : String(error);
7516
+ const steps = failedProgressReport.steps.map(
7517
+ (step) => step.status === "in_progress" ? { ...step, status: "failed", detail: message } : step
7518
+ );
7519
+ const report = { ...failedProgressReport, steps };
7520
+ latestProgressReport = report;
7171
7521
  input.emit({
7172
7522
  kind: "progress",
7173
7523
  turnRecordId: input.turnRecordId,
7174
- report: failActiveTurnProgress(failedProgressReport)
7524
+ report
7175
7525
  });
7176
7526
  }
7177
7527
  if (error instanceof TurnExecutionFailure) return failedResult(error, appliedTargetedInputs);
@@ -7181,34 +7531,65 @@ async function executeSelectedTurn(input) {
7181
7531
  }
7182
7532
  }
7183
7533
 
7534
+ // src/runtime/adapters.ts
7535
+ var nodeWorkerRuntimeScheduler = {
7536
+ setTimeout(handler, delayMs) {
7537
+ return setTimeout(handler, delayMs);
7538
+ },
7539
+ clearTimeout(timer) {
7540
+ clearTimeout(timer);
7541
+ },
7542
+ sleep(delayMs) {
7543
+ return new Promise((resolve) => setTimeout(resolve, delayMs));
7544
+ },
7545
+ now() {
7546
+ return /* @__PURE__ */ new Date();
7547
+ }
7548
+ };
7549
+
7184
7550
  // src/runtime/index.ts
7185
7551
  function createWorkerRuntime(options) {
7186
7552
  const { config, adapters } = options;
7187
7553
  const sampleCredentials = adapters.sampleCredentials ?? sampleCredentialFiles;
7188
7554
  const ipc = adapters.transport;
7555
+ const deliveredSecrets = /* @__PURE__ */ new Set();
7556
+ const redact = (text) => redactSecrets(
7557
+ text,
7558
+ [...deliveredSecrets].sort((a, b) => b.length - a.length)
7559
+ );
7560
+ function redactValue(value) {
7561
+ if (deliveredSecrets.size === 0) return value;
7562
+ if (typeof value === "string") return redact(value);
7563
+ if (Array.isArray(value)) return value.map(redactValue);
7564
+ if (value && typeof value === "object")
7565
+ return Object.fromEntries(
7566
+ Object.entries(value).map(([key, item]) => [key, redactValue(item)])
7567
+ );
7568
+ return value;
7569
+ }
7570
+ const emitExtensionEvent = (event, payload) => adapters.extensionEvents?.emit(event, redactValue(payload));
7571
+ const writeStderr = (text) => adapters.stderr?.write(`${redact(text)}
7572
+ `);
7189
7573
  const queue = [];
7190
7574
  const timers = /* @__PURE__ */ new Map();
7191
7575
  let state = createInitialWorkerRuntimeState();
7192
7576
  let draining = false;
7193
7577
  let started = false;
7194
7578
  let invariantQueued = false;
7195
- let resolveClosed;
7196
- const closed = new Promise((resolve) => {
7197
- resolveClosed = resolve;
7198
- });
7579
+ const { promise: closed, resolve: resolveClosed } = Promise.withResolvers();
7199
7580
  const reporter = createWorkerIpcReporter({
7200
7581
  instanceId: config.instanceId,
7201
7582
  workerId: config.workerId,
7202
7583
  now: () => adapters.scheduler.now(),
7203
- send: (message) => ipc.send(message),
7204
- emitExtensionEvent: (event, payload) => adapters.extensionEvents?.emit(event, payload)
7584
+ send: (message) => ipc.send(redactValue(message)),
7585
+ emitExtensionEvent
7205
7586
  });
7206
7587
  const questionBridge = new WorkerQuestionBridge(reporter);
7207
7588
  const integrationToolBridge = new WorkerIntegrationToolBridge(reporter);
7208
7589
  let dispatch;
7209
7590
  const piEvents = createPiEventReporter({
7210
7591
  reporter,
7211
- emitExtensionEvent: (event, payload) => adapters.extensionEvents?.emit(event, payload),
7592
+ emitExtensionEvent,
7212
7593
  getCurrentSelectedTurnId: () => state.session?.selectedTurnId ?? null,
7213
7594
  getSessionTainted: () => state.sessionTainted,
7214
7595
  onLifecycleObservation(kind) {
@@ -7219,11 +7600,15 @@ function createWorkerRuntime(options) {
7219
7600
  instanceId: config.instanceId,
7220
7601
  piFactory: adapters.piFactory,
7221
7602
  gitOps: adapters.gitOps,
7603
+ developmentTools: adapters.developmentTools ?? new MiseDevelopmentToolEnvironment(),
7222
7604
  scheduler: adapters.scheduler,
7223
7605
  sessionSnapshots: adapters.sessionSnapshots,
7224
7606
  resolveWorkerProcess: adapters.resolveWorkerProcess,
7225
7607
  progress(payload) {
7226
7608
  reporter.workerTrace(payload, state.session?.selectedTurnId ?? null);
7609
+ },
7610
+ diagnosticTrace(text) {
7611
+ reporter.project({ kind: "protocol", type: "worker.diagnostic_trace", payload: { text } });
7227
7612
  }
7228
7613
  });
7229
7614
  const invariant = (error) => {
@@ -7348,6 +7733,12 @@ function createWorkerRuntime(options) {
7348
7733
  { turnRecordId: emission.turnRecordId, report: emission.report },
7349
7734
  command.session.selectedTurnId
7350
7735
  );
7736
+ } else if (emission.kind === "prepared") {
7737
+ reporter.workerEvent(
7738
+ "turn.prepared",
7739
+ { turnRecordId: emission.turnRecordId, data: emission.data },
7740
+ command.session.selectedTurnId
7741
+ );
7351
7742
  } else reporter.workerError(emission.payload, command.session.selectedTurnId);
7352
7743
  }
7353
7744
  })
@@ -7406,21 +7797,16 @@ function createWorkerRuntime(options) {
7406
7797
  workerId: config.workerId,
7407
7798
  ...output.payload
7408
7799
  } : output.payload;
7409
- adapters.extensionEvents?.emit(output.event, payload);
7800
+ emitExtensionEvent(output.event, payload);
7410
7801
  return;
7411
7802
  }
7412
7803
  if (output.kind === "diagnostic") {
7413
7804
  reporter.workerTrace(output.payload, state.session?.selectedTurnId ?? null);
7414
- if (output.stderr) adapters.stderr?.write(`${output.stderr}
7415
- `);
7416
- return;
7417
- }
7418
- if (output.kind === "stderr") {
7419
- adapters.stderr?.write(`${output.message}
7420
- `);
7805
+ if (output.stderr) writeStderr(output.stderr);
7421
7806
  return;
7422
7807
  }
7423
- launch(output);
7808
+ if (output.kind === "stderr") writeStderr(output.message);
7809
+ else launch(output);
7424
7810
  };
7425
7811
  function drain() {
7426
7812
  if (draining) return;
@@ -7457,6 +7843,9 @@ function createWorkerRuntime(options) {
7457
7843
  drain();
7458
7844
  };
7459
7845
  const receive = (message) => {
7846
+ if (message.type === "worker.start")
7847
+ for (const secret of extractDockerRegistrySecretValues(message.payload))
7848
+ deliveredSecrets.add(secret);
7460
7849
  if (message.type === "worker.integration_tool_result") {
7461
7850
  integrationToolBridge.handle(message);
7462
7851
  return;
@@ -7470,6 +7859,7 @@ function createWorkerRuntime(options) {
7470
7859
  dispatch({ kind: "operator_abort_observed" });
7471
7860
  return;
7472
7861
  }
7862
+ if (message.type === "worker.stop") resources.abortToolPreparation();
7473
7863
  dispatch({ kind: "server_message", message });
7474
7864
  };
7475
7865
  return {
@@ -7497,8 +7887,9 @@ function createWorkerRuntime(options) {
7497
7887
  }
7498
7888
 
7499
7889
  // src/entry-runtime.ts
7500
- import { existsSync as existsSync4, readFileSync as readFileSync3 } from "fs";
7501
- import path12 from "path";
7890
+ import { existsSync as existsSync5, readFileSync as readFileSync3 } from "fs";
7891
+ import path13 from "path";
7892
+ import { isUnknownRecord as isRecord } from "@leitwerk-dev/domain";
7502
7893
  import {
7503
7894
  buildExtensionCatalog,
7504
7895
  createCatalogWorkerDefinitionResolver,
@@ -7524,10 +7915,10 @@ import {
7524
7915
 
7525
7916
  // src/extension-entry-roots.ts
7526
7917
  import { existsSync as existsSync2, realpathSync } from "fs";
7527
- import path9 from "path";
7918
+ import path10 from "path";
7528
7919
  function isWithinDirectory(parentDir, candidatePath) {
7529
- const relative = path9.relative(parentDir, candidatePath);
7530
- return relative === "" || !relative.startsWith("..") && !path9.isAbsolute(relative);
7920
+ const relative = path10.relative(parentDir, candidatePath);
7921
+ return relative === "" || !relative.startsWith("..") && !path10.isAbsolute(relative);
7531
7922
  }
7532
7923
  function parseExtensionAllowedRoots(value) {
7533
7924
  if (!value) return [];
@@ -7539,7 +7930,7 @@ function parseExtensionAllowedRoots(value) {
7539
7930
  }
7540
7931
  if (!Array.isArray(parsed) || parsed.some((entry) => typeof entry !== "string")) return [];
7541
7932
  return parsed.flatMap((entry) => {
7542
- if (!path9.isAbsolute(entry) || !existsSync2(entry)) return [];
7933
+ if (!path10.isAbsolute(entry) || !existsSync2(entry)) return [];
7543
7934
  return [realpathSync(entry)];
7544
7935
  });
7545
7936
  }
@@ -7566,6 +7957,32 @@ import {
7566
7957
  WORKER_IPC_RECONNECT_ENV,
7567
7958
  WORKER_IPC_SERVER_URL_ENV
7568
7959
  } from "@leitwerk-dev/worker-protocol";
7960
+
7961
+ // src/connection-diagnostics.ts
7962
+ import { existsSync as existsSync3, writeFileSync as writeFileSync2 } from "fs";
7963
+ function createConnectionDiagnosticRecorder(deps = {
7964
+ log: (message) => console.error(message),
7965
+ persist: (message) => {
7966
+ if (existsSync3("/dev/termination-log")) writeFileSync2("/dev/termination-log", message);
7967
+ }
7968
+ }) {
7969
+ let first = "";
7970
+ return (message) => {
7971
+ if (!message) {
7972
+ first = "";
7973
+ } else {
7974
+ first ||= message;
7975
+ deps.log(message);
7976
+ }
7977
+ try {
7978
+ deps.persist(message && first !== message ? `${first}
7979
+ ${message}` : message);
7980
+ } catch {
7981
+ }
7982
+ };
7983
+ }
7984
+
7985
+ // src/ipc.ts
7569
7986
  function toError(error) {
7570
7987
  return error instanceof Error ? error : new Error(String(error));
7571
7988
  }
@@ -7591,6 +8008,27 @@ function webSocketDataToText(data) {
7591
8008
  }
7592
8009
  return data.toString("utf8");
7593
8010
  }
8011
+ var connectionErrorCodes = /* @__PURE__ */ new Set([
8012
+ "ECONNREFUSED",
8013
+ "ECONNRESET",
8014
+ "ENOTFOUND",
8015
+ "EAI_AGAIN",
8016
+ "ETIMEDOUT",
8017
+ "ENETUNREACH",
8018
+ "EHOSTUNREACH",
8019
+ "CERT_HAS_EXPIRED",
8020
+ "DEPTH_ZERO_SELF_SIGNED_CERT"
8021
+ ]);
8022
+ function connectionErrorCode(value) {
8023
+ for (let depth = 0; depth < 4 && value && typeof value === "object"; depth += 1) {
8024
+ const error = value;
8025
+ if (typeof error.code === "string" && connectionErrorCodes.has(error.code)) {
8026
+ return error.code;
8027
+ }
8028
+ value = error.error ?? error.cause;
8029
+ }
8030
+ return "websocket_error";
8031
+ }
7594
8032
  function createWebSocketWorkerIpc(input) {
7595
8033
  let messageHandler;
7596
8034
  let errorHandler;
@@ -7604,6 +8042,7 @@ function createWebSocketWorkerIpc(input) {
7604
8042
  const outbound = [];
7605
8043
  const reconnectEnabled = input.reconnect === true;
7606
8044
  const emitError = (error) => errorHandler?.(toError(error));
8045
+ const diagnostic = (detail) => `Worker connection ${openedOnce ? "reconnecting" : "initial_connect"}: attempt=${reconnectAttempt + 1}; ${detail}`;
7607
8046
  const clearReconnectTimer = () => {
7608
8047
  if (reconnectTimer) {
7609
8048
  clearTimeout(reconnectTimer);
@@ -7662,7 +8101,6 @@ function createWebSocketWorkerIpc(input) {
7662
8101
  reconnectTimer = null;
7663
8102
  connect();
7664
8103
  }, delayMs);
7665
- reconnectTimer.unref?.();
7666
8104
  };
7667
8105
  return {
7668
8106
  send(message) {
@@ -7700,12 +8138,15 @@ function createWebSocketWorkerIpc(input) {
7700
8138
  }
7701
8139
  socket = new WebSocketImpl(toWebSocketUrl(input));
7702
8140
  socket.addEventListener("open", () => {
8141
+ input.onDiagnostic?.("");
7703
8142
  reconnectAttempt = 0;
7704
8143
  flushOutbound();
7705
8144
  });
7706
8145
  socket.addEventListener("message", (event) => deliverText(webSocketDataToText(event.data)));
7707
8146
  socket.addEventListener("error", (event) => {
7708
- if (!stopping && !reconnectEnabled) {
8147
+ if (stopping) return;
8148
+ input.onDiagnostic?.(diagnostic(`error=${connectionErrorCode(event)}`));
8149
+ if (!reconnectEnabled) {
7709
8150
  emitError(event instanceof Error ? event : new Error("Worker WebSocket error"));
7710
8151
  }
7711
8152
  });
@@ -7713,6 +8154,9 @@ function createWebSocketWorkerIpc(input) {
7713
8154
  if (stopping) {
7714
8155
  return;
7715
8156
  }
8157
+ input.onDiagnostic?.(
8158
+ diagnostic(`close=${Number.isInteger(event?.code) ? event?.code : "unknown"}`)
8159
+ );
7716
8160
  socket = null;
7717
8161
  if (reconnectEnabled && event?.code !== 1008) {
7718
8162
  scheduleReconnect(connect);
@@ -7747,19 +8191,25 @@ function createWorkerIpcFromEnvironment(input) {
7747
8191
  if (!serverUrl || !token) {
7748
8192
  throw new Error("WebSocket worker IPC requires LEITWERK_SERVER_URL and worker token env");
7749
8193
  }
8194
+ const recordDiagnostic = createConnectionDiagnosticRecorder();
7750
8195
  return createWebSocketWorkerIpc({
7751
8196
  serverUrl,
7752
8197
  instanceId: input.instanceId,
7753
8198
  workerId: input.workerId,
7754
8199
  token,
7755
- reconnect: env[WORKER_IPC_RECONNECT_ENV] === "1"
8200
+ reconnect: env[WORKER_IPC_RECONNECT_ENV] === "1",
8201
+ onDiagnostic(message) {
8202
+ recordDiagnostic(message);
8203
+ input.onDiagnostic?.(message);
8204
+ }
7756
8205
  });
7757
8206
  }
7758
8207
 
7759
8208
  // src/result-image-upload.ts
7760
8209
  import { constants } from "fs";
7761
- import { open, realpath, stat } from "fs/promises";
7762
- import path10 from "path";
8210
+ import { open as open2, realpath, stat } from "fs/promises";
8211
+ import path11 from "path";
8212
+ import { setTimeout as sleep } from "timers/promises";
7763
8213
  import {
7764
8214
  buildWorkerResultImageUploadPath,
7765
8215
  parseWorkerResultImageUploadResponse,
@@ -7782,19 +8232,12 @@ function failure(entry, code, message) {
7782
8232
  return { ...entry, status: "failed", code, message };
7783
8233
  }
7784
8234
  function isWithinRoot(rootReal, fileReal) {
7785
- const relative = path10.relative(rootReal, fileReal);
7786
- return relative !== ".." && !relative.startsWith(`..${path10.sep}`) && !path10.isAbsolute(relative);
7787
- }
7788
- function isRetryableResponse(response) {
7789
- return response.status >= 500;
7790
- }
7791
- async function sleep(ms) {
7792
- if (ms <= 0) return;
7793
- await new Promise((resolve) => setTimeout(resolve, ms));
8235
+ const relative = path11.relative(rootReal, fileReal);
8236
+ return relative !== ".." && !relative.startsWith(`..${path11.sep}`) && !path11.isAbsolute(relative);
7794
8237
  }
7795
8238
  async function readBoundedWorkspaceFile(entry, workspaceRoot, maxSizeBytes) {
7796
8239
  const rootReal = await realpath(workspaceRoot);
7797
- const candidatePath = path10.resolve(workspaceRoot, entry.path);
8240
+ const candidatePath = path11.resolve(workspaceRoot, entry.path);
7798
8241
  const fileReal = await realpath(candidatePath);
7799
8242
  if (!isWithinRoot(rootReal, fileReal)) {
7800
8243
  return failure(
@@ -7803,7 +8246,7 @@ async function readBoundedWorkspaceFile(entry, workspaceRoot, maxSizeBytes) {
7803
8246
  "Image path resolves outside the process workspace"
7804
8247
  );
7805
8248
  }
7806
- const handle = await open(fileReal, constants.O_RDONLY | constants.O_NOFOLLOW);
8249
+ const handle = await open2(fileReal, constants.O_RDONLY | constants.O_NOFOLLOW);
7807
8250
  try {
7808
8251
  const before = await handle.stat();
7809
8252
  if (!before.isFile()) return failure(entry, "not_a_file", "Image path is not a regular file");
@@ -7911,32 +8354,28 @@ function createUploadResultImagesTool(input) {
7911
8354
  if (response.ok) {
7912
8355
  try {
7913
8356
  const body = parseWorkerResultImageUploadResponse(await response.json());
7914
- if (!body)
7915
- return failure(
7916
- entry,
7917
- "upload_invalid_response",
7918
- "Image upload response was invalid"
7919
- );
7920
- return {
7921
- ...entry,
7922
- status: "uploaded",
7923
- ...body,
7924
- markdown: `![${entry.alt.replace(/[\\\]]/g, "\\$&")}](${body.url})`
7925
- };
8357
+ if (body) {
8358
+ return {
8359
+ ...entry,
8360
+ status: "uploaded",
8361
+ ...body,
8362
+ markdown: `![${entry.alt.replace(/[\\\]]/g, "\\$&")}](${body.url})`
8363
+ };
8364
+ }
7926
8365
  } catch {
7927
- return failure(
7928
- entry,
7929
- "upload_invalid_response",
7930
- "Image upload response was invalid"
7931
- );
7932
8366
  }
8367
+ return failure(
8368
+ entry,
8369
+ "upload_invalid_response",
8370
+ "Image upload response was invalid"
8371
+ );
7933
8372
  }
7934
8373
  finalFailure = failure(
7935
8374
  entry,
7936
8375
  `upload_http_${response.status}`,
7937
8376
  `Image upload was rejected with HTTP ${response.status}`
7938
8377
  );
7939
- if (!isRetryableResponse(response)) return finalFailure;
8378
+ if (response.status < 500) return finalFailure;
7940
8379
  }
7941
8380
  if (attempt + 1 < MAX_UPLOAD_ATTEMPTS) {
7942
8381
  await (input.sleepImpl ?? sleep)(RETRY_DELAY_MS);
@@ -7961,8 +8400,8 @@ function createUploadResultImagesTool(input) {
7961
8400
  }
7962
8401
 
7963
8402
  // src/session-snapshot-exchange.ts
7964
- import { readFile as readFile3, stat as stat2 } from "fs/promises";
7965
- import { isEnoent } from "@leitwerk-dev/process-sdk";
8403
+ import { readFile as readFile4 } from "fs/promises";
8404
+ import { isEnoent as isEnoent2 } from "@leitwerk-dev/process-sdk";
7966
8405
  import {
7967
8406
  buildWorkerSessionSnapshotPath,
7968
8407
  WORKER_IPC_SERVER_URL_ENV as WORKER_IPC_SERVER_URL_ENV2,
@@ -7972,70 +8411,40 @@ import {
7972
8411
  WORKER_SESSION_SNAPSHOT_WORKER_ID_HEADER,
7973
8412
  WORKER_SNAPSHOT_TOKEN_ENV
7974
8413
  } from "@leitwerk-dev/worker-protocol";
7975
- function resolveWorkerSessionSnapshotUrl(input) {
7976
- return resolveWorkerHttpUrl(input.serverUrl, buildWorkerSessionSnapshotPath(input.instanceId));
7977
- }
7978
- async function localFileSize(filePath) {
7979
- try {
7980
- return (await stat2(filePath)).size;
7981
- } catch (error) {
7982
- if (isEnoent(error)) {
7983
- return null;
7984
- }
7985
- throw error;
7986
- }
7987
- }
7988
- async function fetchWithTimeout(input) {
7989
- const controller = new AbortController();
7990
- const timeout = setTimeout(() => controller.abort(), input.timeoutMs);
7991
- timeout.unref?.();
7992
- try {
7993
- return await input.fetchImpl(input.url, { ...input.init, signal: controller.signal });
7994
- } finally {
7995
- clearTimeout(timeout);
7996
- }
7997
- }
7998
8414
  function createWorkerSessionSnapshotExchange(input) {
7999
8415
  const fetchImpl = input.fetchImpl ?? globalThis.fetch;
8000
8416
  if (!fetchImpl) {
8001
8417
  return disabledWorkerSessionSnapshotExchange;
8002
8418
  }
8003
8419
  const timeoutMs = input.timeoutMs ?? 3e4;
8004
- const snapshotUrl = resolveWorkerSessionSnapshotUrl({
8005
- serverUrl: input.serverUrl,
8006
- instanceId: input.instanceId
8007
- });
8420
+ const snapshotUrl = resolveWorkerHttpUrl(
8421
+ input.serverUrl,
8422
+ buildWorkerSessionSnapshotPath(input.instanceId)
8423
+ );
8008
8424
  const authHeaders = {
8009
8425
  authorization: `Bearer ${input.token}`,
8010
8426
  [WORKER_SESSION_SNAPSHOT_WORKER_ID_HEADER]: input.workerId
8011
8427
  };
8012
8428
  return {
8013
8429
  async uploadSnapshot(treeFile, reason, metadata = {}) {
8014
- const size = await localFileSize(treeFile);
8015
- if (size === null) {
8016
- return { kind: "missing" };
8017
- }
8018
- if (size === 0) {
8019
- return { kind: "empty" };
8020
- }
8021
- const content = await readFile3(treeFile, "utf8");
8022
- if (content.length === 0) {
8023
- return { kind: "empty" };
8430
+ let content;
8431
+ try {
8432
+ content = await readFile4(treeFile, "utf8");
8433
+ } catch (error) {
8434
+ if (isEnoent2(error)) return { kind: "missing" };
8435
+ throw error;
8024
8436
  }
8025
- const response = await fetchWithTimeout({
8026
- fetchImpl,
8027
- url: snapshotUrl,
8028
- timeoutMs,
8029
- init: {
8030
- method: "PUT",
8031
- headers: {
8032
- ...authHeaders,
8033
- "content-type": WORKER_SESSION_SNAPSHOT_CONTENT_TYPE,
8034
- [WORKER_SESSION_SNAPSHOT_REASON_HEADER]: reason,
8035
- ...metadata.turnRecordId ? { [WORKER_SESSION_SNAPSHOT_TURN_RECORD_ID_HEADER]: metadata.turnRecordId } : {}
8036
- },
8037
- body: content
8038
- }
8437
+ if (content.length === 0) return { kind: "empty" };
8438
+ const response = await fetchImpl(snapshotUrl, {
8439
+ method: "PUT",
8440
+ headers: {
8441
+ ...authHeaders,
8442
+ "content-type": WORKER_SESSION_SNAPSHOT_CONTENT_TYPE,
8443
+ [WORKER_SESSION_SNAPSHOT_REASON_HEADER]: reason,
8444
+ ...metadata.turnRecordId ? { [WORKER_SESSION_SNAPSHOT_TURN_RECORD_ID_HEADER]: metadata.turnRecordId } : {}
8445
+ },
8446
+ body: content,
8447
+ signal: AbortSignal.timeout(timeoutMs)
8039
8448
  });
8040
8449
  if (!response.ok) {
8041
8450
  throw new Error(`Session snapshot upload failed with HTTP ${response.status}`);
@@ -8068,64 +8477,87 @@ function createWorkerSessionSnapshotExchangeFromEnv(input) {
8068
8477
 
8069
8478
  // src/workspace/node-run-root-git-ops.ts
8070
8479
  import {
8071
- chmodSync,
8072
- existsSync as existsSync3,
8073
- mkdirSync,
8074
- mkdtempSync,
8480
+ chmodSync as chmodSync2,
8481
+ existsSync as existsSync4,
8482
+ mkdirSync as mkdirSync2,
8483
+ mkdtempSync as mkdtempSync2,
8075
8484
  readFileSync as readFileSync2,
8076
- rmSync,
8077
- writeFileSync
8485
+ rmSync as rmSync2,
8486
+ writeFileSync as writeFileSync3
8078
8487
  } from "fs";
8079
8488
  import { tmpdir } from "os";
8080
- import path11 from "path";
8489
+ import path12 from "path";
8081
8490
  import {
8491
+ clearRepositoryGitHttpsHelpers,
8082
8492
  clearRepositoryGitSshWrappers,
8083
8493
  repositoryGitArgs,
8084
8494
  repositoryGitSubprocessEnv,
8495
+ repositoryHttpsUrl as repositoryHttpsUrl2,
8496
+ setRepositoryGitHttpsHelper,
8085
8497
  setRepositoryGitSshWrapper
8086
8498
  } from "@leitwerk-dev/process-sdk";
8087
8499
  import { resolveGitBinary } from "@leitwerk-dev/process-sdk/git-binary";
8088
- import { execa } from "execa";
8500
+ import { execa as execa2 } from "execa";
8089
8501
  import fg from "fast-glob";
8090
- function toAbsolute(targetPath) {
8091
- return path11.resolve(targetPath);
8092
- }
8093
8502
  var NodeRunRootGitOps = class {
8094
8503
  #credentialDir = null;
8095
8504
  configureRepositoryCredentials(credentials) {
8096
8505
  this.cleanupRepositoryCredentials();
8097
8506
  if (credentials.length === 0) return;
8098
- const root = mkdtempSync(path11.join(tmpdir(), "leitwerk-repo-auth-"));
8099
- chmodSync(root, 448);
8507
+ const root = mkdtempSync2(path12.join(tmpdir(), "leitwerk-repo-auth-"));
8508
+ chmodSync2(root, 448);
8100
8509
  this.#credentialDir = root;
8101
- for (const credential of credentials) {
8102
- const dir = path11.join(root, encodeURIComponent(credential.projectKey));
8103
- mkdirSync(dir, { mode: 448 });
8104
- const key = path11.join(dir, "identity");
8105
- const hosts = path11.join(dir, "known_hosts");
8106
- const wrapper = path11.join(dir, "ssh");
8107
- writeFileSync(key, `${credential.privateKey.trim()}
8510
+ try {
8511
+ for (const credential of credentials) {
8512
+ const dir = path12.join(root, encodeURIComponent(credential.projectKey));
8513
+ mkdirSync2(dir, { mode: 448 });
8514
+ if (credential.kind === "git_https") {
8515
+ const url = repositoryHttpsUrl2(credential.repositoryUrl);
8516
+ writeFileSync3(
8517
+ path12.join(dir, "credential.json"),
8518
+ JSON.stringify({
8519
+ host: url.host,
8520
+ path: url.pathname.slice(1),
8521
+ username: credential.username,
8522
+ password: credential.password
8523
+ }),
8524
+ { mode: 384 }
8525
+ );
8526
+ const helper = path12.join(dir, "credential.cjs");
8527
+ writeFileSync3(helper, HTTPS_CREDENTIAL_HELPER, { mode: 448 });
8528
+ setRepositoryGitHttpsHelper(credential.projectKey, helper);
8529
+ continue;
8530
+ }
8531
+ const key = path12.join(dir, "identity");
8532
+ const hosts = path12.join(dir, "known_hosts");
8533
+ const wrapper = path12.join(dir, "ssh");
8534
+ writeFileSync3(key, `${credential.privateKey.trim()}
8108
8535
  `, { mode: 384 });
8109
- writeFileSync(hosts, `${credential.knownHosts.trim()}
8536
+ writeFileSync3(hosts, `${credential.knownHosts.trim()}
8110
8537
  `, { mode: 384 });
8111
- writeFileSync(
8112
- wrapper,
8113
- `#!/bin/sh
8538
+ writeFileSync3(
8539
+ wrapper,
8540
+ `#!/bin/sh
8114
8541
  exec ssh -F /dev/null -o IdentitiesOnly=yes -o IdentityFile="${key}" -o UserKnownHostsFile="${hosts}" -o StrictHostKeyChecking=yes -o BatchMode=yes "$@"
8115
8542
  `,
8116
- { mode: 448 }
8117
- );
8118
- setRepositoryGitSshWrapper(credential.projectKey, wrapper);
8543
+ { mode: 448 }
8544
+ );
8545
+ setRepositoryGitSshWrapper(credential.projectKey, wrapper);
8546
+ }
8547
+ } catch (error) {
8548
+ this.cleanupRepositoryCredentials();
8549
+ throw error;
8119
8550
  }
8120
8551
  }
8121
8552
  cleanupRepositoryCredentials() {
8122
8553
  clearRepositoryGitSshWrappers();
8123
- if (this.#credentialDir) rmSync(this.#credentialDir, { recursive: true, force: true });
8554
+ clearRepositoryGitHttpsHelpers();
8555
+ if (this.#credentialDir) rmSync2(this.#credentialDir, { recursive: true, force: true });
8124
8556
  this.#credentialDir = null;
8125
8557
  }
8126
8558
  async runGit(args, cwd, projectKey) {
8127
- const result = await execa(resolveGitBinary(), repositoryGitArgs(args), {
8128
- ...cwd ? { cwd: toAbsolute(cwd) } : {},
8559
+ const result = await execa2(resolveGitBinary(), repositoryGitArgs(args), {
8560
+ ...cwd ? { cwd: path12.resolve(cwd) } : {},
8129
8561
  env: repositoryGitSubprocessEnv(projectKey ?? "", { GIT_TERMINAL_PROMPT: "0" }),
8130
8562
  extendEnv: false,
8131
8563
  stdin: "ignore"
@@ -8133,25 +8565,25 @@ exec ssh -F /dev/null -o IdentitiesOnly=yes -o IdentityFile="${key}" -o UserKnow
8133
8565
  return result.stdout;
8134
8566
  }
8135
8567
  async writeFile(repoDir, filePath, content) {
8136
- const absolutePath = toAbsolute(path11.join(repoDir, filePath));
8137
- mkdirSync(path11.dirname(absolutePath), { recursive: true });
8138
- writeFileSync(absolutePath, content, "utf8");
8568
+ const absolutePath = path12.resolve(path12.join(repoDir, filePath));
8569
+ mkdirSync2(path12.dirname(absolutePath), { recursive: true });
8570
+ writeFileSync3(absolutePath, content, "utf8");
8139
8571
  }
8140
8572
  async readFile(repoDir, filePath) {
8141
- const absolutePath = toAbsolute(path11.join(repoDir, filePath));
8142
- if (!existsSync3(absolutePath)) {
8573
+ const absolutePath = path12.resolve(path12.join(repoDir, filePath));
8574
+ if (!existsSync4(absolutePath)) {
8143
8575
  return null;
8144
8576
  }
8145
8577
  return readFileSync2(absolutePath, "utf8");
8146
8578
  }
8147
8579
  async clone(repoLocator, targetDir) {
8148
- const absoluteTargetDir = toAbsolute(targetDir);
8149
- rmSync(absoluteTargetDir, { recursive: true, force: true });
8150
- mkdirSync(path11.dirname(absoluteTargetDir), { recursive: true });
8580
+ const absoluteTargetDir = path12.resolve(targetDir);
8581
+ rmSync2(absoluteTargetDir, { recursive: true, force: true });
8582
+ mkdirSync2(path12.dirname(absoluteTargetDir), { recursive: true });
8151
8583
  await this.runGit(
8152
8584
  ["clone", repoLocator, absoluteTargetDir],
8153
8585
  void 0,
8154
- path11.basename(absoluteTargetDir)
8586
+ path12.basename(absoluteTargetDir)
8155
8587
  );
8156
8588
  }
8157
8589
  async checkout(repoDir, branch) {
@@ -8175,8 +8607,8 @@ exec ssh -F /dev/null -o IdentitiesOnly=yes -o IdentityFile="${key}" -o UserKnow
8175
8607
  return (await this.runGit(["rev-parse", "HEAD"], repoDir)).trim();
8176
8608
  }
8177
8609
  async listFiles(repoDir, pattern) {
8178
- const absoluteRoot = toAbsolute(repoDir);
8179
- if (!existsSync3(absoluteRoot)) {
8610
+ const absoluteRoot = path12.resolve(repoDir);
8611
+ if (!existsSync4(absoluteRoot)) {
8180
8612
  return [];
8181
8613
  }
8182
8614
  return (await fg(pattern, {
@@ -8187,12 +8619,25 @@ exec ssh -F /dev/null -o IdentitiesOnly=yes -o IdentityFile="${key}" -o UserKnow
8187
8619
  })).sort((a, b) => a.localeCompare(b));
8188
8620
  }
8189
8621
  };
8622
+ var HTTPS_CREDENTIAL_HELPER = `const fs = require('node:fs');
8623
+ if (process.argv[2] !== 'get') process.exit(0);
8624
+ const input = fs.readFileSync(0, 'utf8');
8625
+ const fields = Object.create(null);
8626
+ for (const line of input.split('\\n')) {
8627
+ const i = line.indexOf('=');
8628
+ if (i < 0) continue;
8629
+ const key = line.slice(0, i);
8630
+ if (Object.hasOwn(fields, key)) process.exit(0);
8631
+ fields[key] = line.slice(i + 1);
8632
+ }
8633
+ const c = JSON.parse(fs.readFileSync(require('node:path').join(__dirname, 'credential.json'), 'utf8'));
8634
+ if (fields.protocol !== 'https' || fields.host !== c.host || fields.path !== c.path ||
8635
+ (fields.username && fields.username !== c.username)) process.exit(0);
8636
+ process.stdout.write('username=' + c.username + '\\npassword=' + c.password + '\\n\\n');
8637
+ `;
8190
8638
 
8191
8639
  // src/entry-runtime.ts
8192
8640
  var runtimeCatalogPromise = null;
8193
- function isRecord(value) {
8194
- return typeof value === "object" && value !== null && !Array.isArray(value);
8195
- }
8196
8641
  function listWorkspacePatterns(workspaces) {
8197
8642
  if (Array.isArray(workspaces)) {
8198
8643
  return workspaces.filter((value) => typeof value === "string");
@@ -8203,10 +8648,10 @@ function listWorkspacePatterns(workspaces) {
8203
8648
  return [];
8204
8649
  }
8205
8650
  function findWorkspaceRoot(startDir) {
8206
- let current = path12.resolve(startDir);
8651
+ let current = path13.resolve(startDir);
8207
8652
  while (true) {
8208
- const packageJsonPath = path12.join(current, "package.json");
8209
- if (existsSync4(packageJsonPath)) {
8653
+ const packageJsonPath = path13.join(current, "package.json");
8654
+ if (existsSync5(packageJsonPath)) {
8210
8655
  try {
8211
8656
  const parsed = JSON.parse(readFileSync3(packageJsonPath, "utf8"));
8212
8657
  if (listWorkspacePatterns(parsed.workspaces).length > 0) {
@@ -8215,7 +8660,7 @@ function findWorkspaceRoot(startDir) {
8215
8660
  } catch {
8216
8661
  }
8217
8662
  }
8218
- const parent = path12.dirname(current);
8663
+ const parent = path13.dirname(current);
8219
8664
  if (parent === current) {
8220
8665
  return null;
8221
8666
  }
@@ -8274,7 +8719,12 @@ function createWorkerEntryRuntime(overrides = {}) {
8274
8719
  if (!instanceId || !workerId) {
8275
8720
  throw new Error("Missing required worker identity env");
8276
8721
  }
8277
- const transport = overrides.transport ?? createWorkerIpcFromEnvironment({ env: runtimeEnv, instanceId, workerId });
8722
+ const transport = overrides.transport ?? createWorkerIpcFromEnvironment({
8723
+ env: runtimeEnv,
8724
+ instanceId,
8725
+ workerId,
8726
+ onDiagnostic: overrides.onConnectionDiagnostic
8727
+ });
8278
8728
  const sessionSnapshots = overrides.sessionSnapshots ?? createWorkerSessionSnapshotExchangeFromEnv({ env: runtimeEnv, instanceId, workerId });
8279
8729
  const scheduler = overrides.scheduler ?? nodeWorkerRuntimeScheduler;
8280
8730
  const resultImageServerUrl = runtimeEnv[WORKER_IPC_SERVER_URL_ENV3];
@@ -8319,6 +8769,7 @@ function createWorkerEntryRuntime(overrides = {}) {
8319
8769
  resultImageTools,
8320
8770
  piFactory: overrides.piFactory ?? resolveDefaultPiFactory(),
8321
8771
  gitOps: overrides.gitOps ?? new NodeRunRootGitOps(),
8772
+ developmentTools: overrides.developmentTools ?? new MiseDevelopmentToolEnvironment(runtimeEnv),
8322
8773
  resolveWorkerProcess,
8323
8774
  extensionEvents: workerExtensionApi.events,
8324
8775
  stderr: overrides.stderr,
@@ -8329,19 +8780,8 @@ function createWorkerEntryRuntime(overrides = {}) {
8329
8780
  }
8330
8781
 
8331
8782
  export {
8332
- doesPiEventResetInactivity,
8333
- translateAgentSessionEventEnvelope,
8334
- SdkPiTreeHandle,
8335
8783
  SdkPiTreeHandleFactory,
8336
- resolveManagedPiAgentDir,
8337
- writeManagedPiCredentialFiles,
8338
- createCanonicalPiResourceBundle,
8339
- sha256Digest,
8340
- validateResourceRelativePath,
8341
- verifyCanonicalPiResourceBundle,
8342
- materializeCanonicalPiResourceBundle,
8343
- nodeWorkerRuntimeScheduler,
8344
8784
  createWorkerRuntime,
8345
8785
  createWorkerEntryRuntime
8346
8786
  };
8347
- //# sourceMappingURL=chunk-O6332GRG.js.map
8787
+ //# sourceMappingURL=chunk-2LLFMCR6.js.map