@leitwerk-dev/worker 0.1.8 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (235) 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-ZTJ7UAOC.js → chunk-Y7S2MZD3.js} +1423 -917
  4. package/dist/chunk-Y7S2MZD3.js.map +1 -0
  5. package/dist/connection-diagnostics.d.ts +5 -0
  6. package/dist/connection-diagnostics.d.ts.map +1 -0
  7. package/dist/container-entry-main.d.ts +2 -0
  8. package/dist/container-entry-main.d.ts.map +1 -0
  9. package/dist/container-entry-main.js +232 -0
  10. package/dist/container-entry-main.js.map +1 -0
  11. package/dist/container-entry.d.ts +14 -0
  12. package/dist/container-entry.d.ts.map +1 -0
  13. package/dist/development-tool-environment.d.ts +48 -0
  14. package/dist/development-tool-environment.d.ts.map +1 -0
  15. package/dist/diagnostics.d.ts +9 -1
  16. package/dist/diagnostics.d.ts.map +1 -1
  17. package/dist/docker-registry-credentials.d.ts +8 -0
  18. package/dist/docker-registry-credentials.d.ts.map +1 -0
  19. package/dist/entry-runtime.d.ts +1 -0
  20. package/dist/entry-runtime.d.ts.map +1 -1
  21. package/dist/index.d.ts +1 -0
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +44 -5
  24. package/dist/index.js.map +1 -1
  25. package/dist/input-consumer.d.ts +6 -11
  26. package/dist/input-consumer.d.ts.map +1 -1
  27. package/dist/ipc.d.ts +1 -0
  28. package/dist/ipc.d.ts.map +1 -1
  29. package/dist/logical-prompt-runner.d.ts.map +1 -1
  30. package/dist/managed-pi-bootstrap.d.ts.map +1 -1
  31. package/dist/missing-tool-recovery-runner.d.ts +4 -3
  32. package/dist/missing-tool-recovery-runner.d.ts.map +1 -1
  33. package/dist/pi-adapter.d.ts +1 -0
  34. package/dist/pi-adapter.d.ts.map +1 -1
  35. package/dist/pi-event-reporter.d.ts.map +1 -1
  36. package/dist/pi-resource-bundle.d.ts +11 -0
  37. package/dist/pi-resource-bundle.d.ts.map +1 -1
  38. package/dist/pre-turn-targeted-inputs.d.ts +8 -7
  39. package/dist/pre-turn-targeted-inputs.d.ts.map +1 -1
  40. package/dist/prompt-guards.d.ts.map +1 -1
  41. package/dist/repository-bash-tool.d.ts +4 -0
  42. package/dist/repository-bash-tool.d.ts.map +1 -0
  43. package/dist/resource-loader-factory.d.ts +1 -2
  44. package/dist/resource-loader-factory.d.ts.map +1 -1
  45. package/dist/result-image-upload.d.ts.map +1 -1
  46. package/dist/runtime/adapters.d.ts +2 -0
  47. package/dist/runtime/adapters.d.ts.map +1 -1
  48. package/dist/runtime/bootstrap-session.d.ts +8 -5
  49. package/dist/runtime/bootstrap-session.d.ts.map +1 -1
  50. package/dist/runtime/bootstrap.d.ts +14 -18
  51. package/dist/runtime/bootstrap.d.ts.map +1 -1
  52. package/dist/runtime/failure-policy.d.ts +1 -0
  53. package/dist/runtime/failure-policy.d.ts.map +1 -1
  54. package/dist/runtime/index.d.ts.map +1 -1
  55. package/dist/runtime/lifecycle-reducer.d.ts +4 -1
  56. package/dist/runtime/lifecycle-reducer.d.ts.map +1 -1
  57. package/dist/runtime/llm-turn-execution.d.ts +3 -8
  58. package/dist/runtime/llm-turn-execution.d.ts.map +1 -1
  59. package/dist/runtime/turn-execution.d.ts +2 -9
  60. package/dist/runtime/turn-execution.d.ts.map +1 -1
  61. package/dist/session-snapshot-exchange.d.ts +0 -4
  62. package/dist/session-snapshot-exchange.d.ts.map +1 -1
  63. package/dist/turn-continuation.d.ts.map +1 -1
  64. package/dist/turn-execution-error.d.ts +1 -1
  65. package/dist/turn-execution-error.d.ts.map +1 -1
  66. package/dist/turn-execution-result.d.ts +1 -0
  67. package/dist/turn-execution-result.d.ts.map +1 -1
  68. package/dist/turn-outcome-tool-session.d.ts +0 -2
  69. package/dist/turn-outcome-tool-session.d.ts.map +1 -1
  70. package/dist/turn-result-markdown.d.ts +2 -1
  71. package/dist/turn-result-markdown.d.ts.map +1 -1
  72. package/dist/turn-tree-strategy.d.ts +0 -1
  73. package/dist/turn-tree-strategy.d.ts.map +1 -1
  74. package/dist/worker-entry.js +16 -4
  75. package/dist/worker-entry.js.map +1 -1
  76. package/dist/worker-ipc-reporter.d.ts.map +1 -1
  77. package/dist/workspace/manifest.d.ts +4 -7
  78. package/dist/workspace/manifest.d.ts.map +1 -1
  79. package/dist/workspace/node-run-root-git-ops.d.ts +2 -2
  80. package/dist/workspace/node-run-root-git-ops.d.ts.map +1 -1
  81. package/dist/workspace/resource-aggregator.d.ts.map +1 -1
  82. package/dist/workspace/run-root.d.ts +9 -20
  83. package/dist/workspace/run-root.d.ts.map +1 -1
  84. package/package.json +8 -8
  85. package/src/automatic-turn-executor.ts +2 -0
  86. package/src/connection-diagnostics.ts +27 -0
  87. package/src/container-entry-main.ts +24 -0
  88. package/src/container-entry.ts +246 -0
  89. package/src/development-tool-environment.ts +452 -0
  90. package/src/diagnostics.ts +3 -1
  91. package/src/docker-registry-credentials.ts +65 -0
  92. package/src/entry-runtime.ts +5 -4
  93. package/src/index.ts +11 -0
  94. package/src/input-consumer.ts +7 -29
  95. package/src/ipc.ts +37 -2
  96. package/src/logical-prompt-runner.ts +23 -29
  97. package/src/managed-pi-bootstrap.ts +3 -3
  98. package/src/missing-tool-recovery-runner.ts +4 -18
  99. package/src/pi-adapter.ts +19 -50
  100. package/src/pi-event-reporter.ts +16 -38
  101. package/src/pi-resource-bundle.ts +67 -1
  102. package/src/pre-turn-targeted-inputs.ts +9 -11
  103. package/src/prompt-guards.ts +44 -75
  104. package/src/repository-bash-tool.ts +15 -0
  105. package/src/resource-loader-factory.ts +1 -18
  106. package/src/result-image-upload.ts +16 -27
  107. package/src/runtime/adapters.ts +2 -0
  108. package/src/runtime/bootstrap-session.ts +69 -39
  109. package/src/runtime/bootstrap.ts +160 -103
  110. package/src/runtime/failure-policy.ts +36 -42
  111. package/src/runtime/index.ts +49 -14
  112. package/src/runtime/lifecycle-reducer.ts +140 -173
  113. package/src/runtime/llm-turn-execution.ts +13 -30
  114. package/src/runtime/turn-execution.ts +91 -9
  115. package/src/session-snapshot-exchange.ts +23 -64
  116. package/src/turn-continuation.ts +9 -17
  117. package/src/turn-execution-error.ts +3 -11
  118. package/src/turn-execution-result.ts +1 -0
  119. package/src/turn-outcome-tool-session.ts +25 -21
  120. package/src/turn-result-markdown.ts +31 -34
  121. package/src/turn-tree-strategy.ts +6 -19
  122. package/src/worker-entry.ts +8 -0
  123. package/src/worker-ipc-reporter.ts +8 -16
  124. package/src/workspace/manifest.ts +5 -7
  125. package/src/workspace/node-run-root-git-ops.ts +65 -25
  126. package/src/workspace/resource-aggregator.ts +5 -16
  127. package/src/workspace/run-root.ts +38 -89
  128. package/dist/automatic-turn-executor.js +0 -58
  129. package/dist/automatic-turn-executor.js.map +0 -1
  130. package/dist/chunk-ZTJ7UAOC.js.map +0 -1
  131. package/dist/diagnostics.js +0 -51
  132. package/dist/diagnostics.js.map +0 -1
  133. package/dist/entry-runtime.js +0 -160
  134. package/dist/entry-runtime.js.map +0 -1
  135. package/dist/event-translator.js +0 -12
  136. package/dist/event-translator.js.map +0 -1
  137. package/dist/extension-entry-roots.js +0 -41
  138. package/dist/extension-entry-roots.js.map +0 -1
  139. package/dist/identified-pi-entry.js +0 -125
  140. package/dist/identified-pi-entry.js.map +0 -1
  141. package/dist/input-consumer.js +0 -34
  142. package/dist/input-consumer.js.map +0 -1
  143. package/dist/integration-tool-bridge.js +0 -53
  144. package/dist/integration-tool-bridge.js.map +0 -1
  145. package/dist/ipc.js +0 -192
  146. package/dist/ipc.js.map +0 -1
  147. package/dist/logical-prompt-runner.js +0 -225
  148. package/dist/logical-prompt-runner.js.map +0 -1
  149. package/dist/managed-pi-agent-dir.js +0 -66
  150. package/dist/managed-pi-agent-dir.js.map +0 -1
  151. package/dist/managed-pi-bootstrap.js +0 -135
  152. package/dist/managed-pi-bootstrap.js.map +0 -1
  153. package/dist/missing-tool-recovery-runner.js +0 -73
  154. package/dist/missing-tool-recovery-runner.js.map +0 -1
  155. package/dist/pi-adapter.js +0 -1648
  156. package/dist/pi-adapter.js.map +0 -1
  157. package/dist/pi-branch-guard.js +0 -75
  158. package/dist/pi-branch-guard.js.map +0 -1
  159. package/dist/pi-event-reporter.js +0 -136
  160. package/dist/pi-event-reporter.js.map +0 -1
  161. package/dist/pi-resource-bundle.js +0 -58
  162. package/dist/pi-resource-bundle.js.map +0 -1
  163. package/dist/pre-turn-targeted-inputs.js +0 -101
  164. package/dist/pre-turn-targeted-inputs.js.map +0 -1
  165. package/dist/prompt-guards.js +0 -318
  166. package/dist/prompt-guards.js.map +0 -1
  167. package/dist/question-bridge.js +0 -24
  168. package/dist/question-bridge.js.map +0 -1
  169. package/dist/question-tool.js +0 -54
  170. package/dist/question-tool.js.map +0 -1
  171. package/dist/replaying-request-bridge.js +0 -71
  172. package/dist/replaying-request-bridge.js.map +0 -1
  173. package/dist/resource-loader-factory.js +0 -87
  174. package/dist/resource-loader-factory.js.map +0 -1
  175. package/dist/result-image-upload.js +0 -183
  176. package/dist/result-image-upload.js.map +0 -1
  177. package/dist/runtime/adapters.js +0 -15
  178. package/dist/runtime/adapters.js.map +0 -1
  179. package/dist/runtime/bootstrap-session.js +0 -199
  180. package/dist/runtime/bootstrap-session.js.map +0 -1
  181. package/dist/runtime/bootstrap.js +0 -440
  182. package/dist/runtime/bootstrap.js.map +0 -1
  183. package/dist/runtime/failure-policy.js +0 -182
  184. package/dist/runtime/failure-policy.js.map +0 -1
  185. package/dist/runtime/index.js +0 -336
  186. package/dist/runtime/index.js.map +0 -1
  187. package/dist/runtime/lifecycle-reducer.js +0 -1100
  188. package/dist/runtime/lifecycle-reducer.js.map +0 -1
  189. package/dist/runtime/llm-turn-execution.js +0 -494
  190. package/dist/runtime/llm-turn-execution.js.map +0 -1
  191. package/dist/runtime/settings.js +0 -24
  192. package/dist/runtime/settings.js.map +0 -1
  193. package/dist/runtime/snapshot-policy.js +0 -16
  194. package/dist/runtime/snapshot-policy.js.map +0 -1
  195. package/dist/runtime/turn-execution.js +0 -121
  196. package/dist/runtime/turn-execution.js.map +0 -1
  197. package/dist/session-snapshot-exchange.js +0 -102
  198. package/dist/session-snapshot-exchange.js.map +0 -1
  199. package/dist/test-helpers/fake-websocket.js +0 -40
  200. package/dist/test-helpers/fake-websocket.js.map +0 -1
  201. package/dist/test-helpers/ipc-harness.d.ts +0 -11
  202. package/dist/test-helpers/ipc-harness.d.ts.map +0 -1
  203. package/dist/test-helpers/ipc-harness.js +0 -17
  204. package/dist/test-helpers/ipc-harness.js.map +0 -1
  205. package/dist/turn-continuation.js +0 -80
  206. package/dist/turn-continuation.js.map +0 -1
  207. package/dist/turn-execution-error.js +0 -64
  208. package/dist/turn-execution-error.js.map +0 -1
  209. package/dist/turn-execution-result.js +0 -21
  210. package/dist/turn-execution-result.js.map +0 -1
  211. package/dist/turn-outcome-tool-session.js +0 -210
  212. package/dist/turn-outcome-tool-session.js.map +0 -1
  213. package/dist/turn-record-id.js +0 -10
  214. package/dist/turn-record-id.js.map +0 -1
  215. package/dist/turn-result-markdown.js +0 -263
  216. package/dist/turn-result-markdown.js.map +0 -1
  217. package/dist/turn-tree-strategy.js +0 -80
  218. package/dist/turn-tree-strategy.js.map +0 -1
  219. package/dist/worker-http.js +0 -9
  220. package/dist/worker-http.js.map +0 -1
  221. package/dist/worker-ipc-reporter.js +0 -58
  222. package/dist/worker-ipc-reporter.js.map +0 -1
  223. package/dist/worker-payloads.js +0 -66
  224. package/dist/worker-payloads.js.map +0 -1
  225. package/dist/worker-start-payload.js +0 -5
  226. package/dist/worker-start-payload.js.map +0 -1
  227. package/dist/workspace/manifest.js +0 -79
  228. package/dist/workspace/manifest.js.map +0 -1
  229. package/dist/workspace/node-run-root-git-ops.js +0 -96
  230. package/dist/workspace/node-run-root-git-ops.js.map +0 -1
  231. package/dist/workspace/resource-aggregator.js +0 -39
  232. package/dist/workspace/resource-aggregator.js.map +0 -1
  233. package/dist/workspace/run-root.js +0 -209
  234. package/dist/workspace/run-root.js.map +0 -1
  235. package/src/test-helpers/ipc-harness.ts +0 -19
package/src/ipc.ts CHANGED
@@ -8,6 +8,7 @@ import {
8
8
  WORKER_IPC_SERVER_URL_ENV,
9
9
  type WorkerToServerMessage,
10
10
  } from "@leitwerk-dev/worker-protocol";
11
+ import { createConnectionDiagnosticRecorder } from "./connection-diagnostics.js";
11
12
 
12
13
  export interface WorkerIpc {
13
14
  send(message: WorkerToServerMessage): void;
@@ -69,12 +70,36 @@ function webSocketDataToText(data: WebSocketMessageEventLike["data"]): string {
69
70
  return data.toString("utf8");
70
71
  }
71
72
 
73
+ // Only known transport codes are safe to retain: native error messages may contain URLs.
74
+ const connectionErrorCodes = new Set([
75
+ "ECONNREFUSED",
76
+ "ECONNRESET",
77
+ "ENOTFOUND",
78
+ "EAI_AGAIN",
79
+ "ETIMEDOUT",
80
+ "ENETUNREACH",
81
+ "EHOSTUNREACH",
82
+ "CERT_HAS_EXPIRED",
83
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
84
+ ]);
85
+ function connectionErrorCode(value: unknown): string {
86
+ for (let depth = 0; depth < 4 && value && typeof value === "object"; depth += 1) {
87
+ const error = value as { code?: unknown; error?: unknown; cause?: unknown };
88
+ if (typeof error.code === "string" && connectionErrorCodes.has(error.code)) {
89
+ return error.code;
90
+ }
91
+ value = error.error ?? error.cause;
92
+ }
93
+ return "websocket_error";
94
+ }
95
+
72
96
  export function createWebSocketWorkerIpc(input: {
73
97
  serverUrl: string;
74
98
  instanceId: string;
75
99
  workerId: string;
76
100
  token: string;
77
101
  reconnect?: boolean;
102
+ onDiagnostic?: (message: string) => void;
78
103
  }): WorkerIpc {
79
104
  let messageHandler: ((message: ServerToWorkerMessage) => void) | undefined;
80
105
  let errorHandler: ((error: Error) => void) | undefined;
@@ -89,6 +114,8 @@ export function createWebSocketWorkerIpc(input: {
89
114
 
90
115
  const reconnectEnabled = input.reconnect === true;
91
116
  const emitError = (error: unknown) => errorHandler?.(toError(error));
117
+ const diagnostic = (detail: string) =>
118
+ `Worker connection ${openedOnce ? "reconnecting" : "initial_connect"}: attempt=${reconnectAttempt + 1}; ${detail}`;
92
119
  const clearReconnectTimer = () => {
93
120
  if (reconnectTimer) {
94
121
  clearTimeout(reconnectTimer);
@@ -147,7 +174,8 @@ export function createWebSocketWorkerIpc(input: {
147
174
  reconnectTimer = null;
148
175
  connect();
149
176
  }, delayMs);
150
- reconnectTimer.unref?.();
177
+ // A pending connection must keep the worker alive, including before bootstrap.
178
+ // stop() clears this timer; the server owns the startup deadline.
151
179
  };
152
180
 
153
181
  return {
@@ -186,12 +214,15 @@ export function createWebSocketWorkerIpc(input: {
186
214
  }
187
215
  socket = new WebSocketImpl(toWebSocketUrl(input));
188
216
  socket.addEventListener("open", () => {
217
+ input.onDiagnostic?.("");
189
218
  reconnectAttempt = 0;
190
219
  flushOutbound();
191
220
  });
192
221
  socket.addEventListener("message", (event) => deliverText(webSocketDataToText(event.data)));
193
222
  socket.addEventListener("error", (event) => {
194
- if (!stopping && !reconnectEnabled) {
223
+ if (stopping) return;
224
+ input.onDiagnostic?.(diagnostic(`error=${connectionErrorCode(event)}`));
225
+ if (!reconnectEnabled) {
195
226
  emitError(event instanceof Error ? event : new Error("Worker WebSocket error"));
196
227
  }
197
228
  });
@@ -199,6 +230,9 @@ export function createWebSocketWorkerIpc(input: {
199
230
  if (stopping) {
200
231
  return;
201
232
  }
233
+ input.onDiagnostic?.(
234
+ diagnostic(`close=${Number.isInteger(event?.code) ? event?.code : "unknown"}`),
235
+ );
202
236
  socket = null;
203
237
  if (reconnectEnabled && event?.code !== 1008) {
204
238
  scheduleReconnect(connect);
@@ -246,5 +280,6 @@ export function createWorkerIpcFromEnvironment(input: {
246
280
  workerId: input.workerId,
247
281
  token,
248
282
  reconnect: env[WORKER_IPC_RECONNECT_ENV] === "1",
283
+ onDiagnostic: createConnectionDiagnosticRecorder(),
249
284
  });
250
285
  }
@@ -30,13 +30,11 @@ export function shouldAutoContinueAfterPromptReturn(input: {
30
30
  sawCompaction: boolean;
31
31
  compactionContinueAttempts: number;
32
32
  }): boolean {
33
- if (input.resolvedOutcome) {
34
- return false;
35
- }
36
- if (!input.sawCompaction) {
37
- return false;
38
- }
39
- return input.compactionContinueAttempts < MAX_COMPACTION_CONTINUE_ATTEMPTS;
33
+ return (
34
+ !input.resolvedOutcome &&
35
+ input.sawCompaction &&
36
+ input.compactionContinueAttempts < MAX_COMPACTION_CONTINUE_ATTEMPTS
37
+ );
40
38
  }
41
39
 
42
40
  function isContextWindowError(error: unknown): boolean {
@@ -158,9 +156,7 @@ export async function executeLogicalPromptPlan<TOutcome extends string>(input: {
158
156
  };
159
157
 
160
158
  for (;;) {
161
- const continuePlan = currentPlan.kind === "continue" ? currentPlan : null;
162
- const promptPlan = currentPlan.kind === "prompt" ? currentPlan : null;
163
- const usingContinueThisAttempt = continuePlan !== null;
159
+ const plan = currentPlan;
164
160
  const guardSuspension = new PromptGuardSuspension();
165
161
  const promptOptions =
166
162
  input.toolSession.tools.length > 0
@@ -178,13 +174,16 @@ export async function executeLogicalPromptPlan<TOutcome extends string>(input: {
178
174
  }
179
175
  : { activeTools: input.toolSession.activeTools };
180
176
 
181
- let preparedPromptRun: (() => Promise<PiTurnExecutionResult>) | null = null;
182
- if (continuePlan) {
177
+ let runPrompt = () =>
178
+ plan.kind === "continue"
179
+ ? input.piHandle.continueTurn(promptOptions)
180
+ : input.piHandle.prompt(plan.promptText ?? "", promptOptions);
181
+ if (plan.kind === "continue") {
183
182
  try {
184
- await continuePlan.prepareForContinuation?.();
185
- if (continuePlan.continueUserPrompt !== null) {
186
- const content = continuePlan.continueUserPrompt;
187
- const identity = continuePlan.identifiedPrompt;
183
+ await plan.prepareForContinuation?.();
184
+ if (plan.continueUserPrompt !== null) {
185
+ const content = plan.continueUserPrompt;
186
+ const identity = plan.identifiedPrompt;
188
187
  if (identity) {
189
188
  const expectedParentId = input.piHandle.getLeafId();
190
189
  if (findIdentifiedPrompt(input.piHandle, identity)) {
@@ -195,7 +194,7 @@ export async function executeLogicalPromptPlan<TOutcome extends string>(input: {
195
194
  expectedParentId,
196
195
  });
197
196
  } else {
198
- preparedPromptRun = () =>
197
+ runPrompt = () =>
199
198
  input.piHandle.promptCustom({ content, details: identity }, promptOptions);
200
199
  }
201
200
  } else {
@@ -205,7 +204,7 @@ export async function executeLogicalPromptPlan<TOutcome extends string>(input: {
205
204
  promptText: content,
206
205
  });
207
206
  if (promptText) {
208
- preparedPromptRun = () => input.piHandle.promptLiteral(promptText, promptOptions);
207
+ runPrompt = () => input.piHandle.promptLiteral(promptText, promptOptions);
209
208
  }
210
209
  }
211
210
  }
@@ -229,13 +228,7 @@ export async function executeLogicalPromptPlan<TOutcome extends string>(input: {
229
228
  piHandle: input.piHandle,
230
229
  turnRecordId: input.turnRecordId,
231
230
  turnId: input.turnId,
232
- runPrompt: () => {
233
- if (preparedPromptRun) return preparedPromptRun();
234
- if (continuePlan) {
235
- return input.piHandle.continueTurn(promptOptions);
236
- }
237
- return input.piHandle.prompt(promptPlan?.promptText ?? "", promptOptions);
238
- },
231
+ runPrompt,
239
232
  },
240
233
  );
241
234
  if (input.toolSession.terminalAcknowledgement.state() === "outcome_accepted") {
@@ -306,14 +299,15 @@ export async function executeLogicalPromptPlan<TOutcome extends string>(input: {
306
299
  continue;
307
300
  }
308
301
  return reportFailure(error, {
309
- code: usingContinueThisAttempt ? "turn.continue_failed" : "turn.prompt_failed",
302
+ code: plan.kind === "continue" ? "turn.continue_failed" : "turn.prompt_failed",
310
303
  emitWorkerError: !(
311
304
  error instanceof PromptTimeoutError || error instanceof OperatorAbortError
312
305
  ),
313
306
  fallbackErrorClass: "llm_error",
314
- messagePrefix: usingContinueThisAttempt
315
- ? `Turn '${input.turnId}' continuation failed`
316
- : `Turn '${input.turnId}' prompt failed`,
307
+ messagePrefix:
308
+ plan.kind === "continue"
309
+ ? `Turn '${input.turnId}' continuation failed`
310
+ : `Turn '${input.turnId}' prompt failed`,
317
311
  });
318
312
  }
319
313
  }
@@ -1,6 +1,5 @@
1
1
  import { lstat, readFile } from "node:fs/promises";
2
2
  import path from "node:path";
3
- import { VERSION as PI_VERSION } from "@earendil-works/pi-coding-agent";
4
3
  import type { ResolvedTurnStart } from "@leitwerk-dev/domain";
5
4
  import {
6
5
  canonicalJsonEqual,
@@ -48,7 +47,8 @@ function assertModelMatchesStart(
48
47
  }
49
48
  }
50
49
 
51
- function assertCompatibility(manifest: ManagedPiResourceManifest): void {
50
+ async function assertCompatibility(manifest: ManagedPiResourceManifest): Promise<void> {
51
+ const { VERSION: PI_VERSION } = await import("@earendil-works/pi-coding-agent");
52
52
  if (manifest.compatibility.workerApiVersion !== WORKER_API_VERSION) {
53
53
  fail(
54
54
  `server snapshot worker API version '${manifest.compatibility.workerApiVersion}' does not match local worker API version '${WORKER_API_VERSION}'`,
@@ -88,7 +88,7 @@ export async function readAndValidateManagedPiResourceManifest(input: {
88
88
  }
89
89
  const manifest = parsePiResourceManifest(parsed);
90
90
  assertModelMatchesStart(manifest, input.start);
91
- assertCompatibility(manifest);
91
+ await assertCompatibility(manifest);
92
92
  assertJsonEqual(manifest.providerOptions, input.start.providerOptions, "providerOptions");
93
93
  assertJsonEqual(
94
94
  manifest.providerWorkerConfig,
@@ -21,10 +21,8 @@ export async function runMissingToolRecovery<TOutcome extends string>(input: {
21
21
  options?: { baseState?: ToolCompletionSnapshot<TOutcome> },
22
22
  ): Promise<LogicalPromptAttempt<TOutcome>>;
23
23
  }): Promise<{
24
- recovered: boolean;
25
24
  finalAttempt: LogicalPromptAttempt<TOutcome>;
26
- recoveryContext: FailedTurnRecoveryContext | null;
27
- baseMissingToolRecoveryDescription: string | null;
25
+ failure?: { recoveryContext: FailedTurnRecoveryContext; description: string };
28
26
  }> {
29
27
  const trace = (payload: WorkerDiagnosticPayload) => input.emit?.({ kind: "trace", payload });
30
28
  const reportError = (payload: WorkerDiagnosticPayload) =>
@@ -33,12 +31,7 @@ export async function runMissingToolRecovery<TOutcome extends string>(input: {
33
31
  input.initialAttempt.completionState,
34
32
  );
35
33
  if (!baseMissingToolRecovery) {
36
- return {
37
- recovered: true,
38
- finalAttempt: input.initialAttempt,
39
- recoveryContext: null,
40
- baseMissingToolRecoveryDescription: null,
41
- };
34
+ return { finalAttempt: input.initialAttempt };
42
35
  }
43
36
 
44
37
  const recoveryContext = input.toolSession.buildRecoveryContext(baseMissingToolRecovery);
@@ -83,12 +76,7 @@ export async function runMissingToolRecovery<TOutcome extends string>(input: {
83
76
  { baseState: input.initialAttempt.completionState },
84
77
  );
85
78
  if (!input.toolSession.resolveMissingToolRecovery(finalAttempt.completionState)) {
86
- return {
87
- recovered: true,
88
- finalAttempt,
89
- recoveryContext,
90
- baseMissingToolRecoveryDescription: description,
91
- };
79
+ return { finalAttempt };
92
80
  }
93
81
  }
94
82
 
@@ -104,9 +92,7 @@ export async function runMissingToolRecovery<TOutcome extends string>(input: {
104
92
  },
105
93
  });
106
94
  return {
107
- recovered: false,
108
95
  finalAttempt,
109
- recoveryContext,
110
- baseMissingToolRecoveryDescription: description,
96
+ failure: { recoveryContext, description },
111
97
  };
112
98
  }
package/src/pi-adapter.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { access, mkdir, writeFile } from "node:fs/promises";
2
2
  import path from "node:path";
3
- import { type AssistantMessage, retryAssistantCall } from "@earendil-works/pi-ai";
3
+ import type { AssistantMessage } from "@earendil-works/pi-ai";
4
4
  import type {
5
5
  AgentSession,
6
6
  AgentSessionEvent,
@@ -8,6 +8,7 @@ import type {
8
8
  ModelRuntime,
9
9
  ToolDefinition,
10
10
  } from "@earendil-works/pi-coding-agent";
11
+ import { readFiniteNumber, readNonBlankString as readNonEmptyString } from "@leitwerk-dev/domain";
11
12
  import type {
12
13
  PiCustomMessageInput,
13
14
  PiCustomTool,
@@ -22,7 +23,9 @@ import type {
22
23
  PiTreeHandle,
23
24
  PiTreeNode,
24
25
  PiTurnExecutionResult,
26
+ PiUsageData,
25
27
  } from "@leitwerk-dev/process-sdk";
28
+ import { hasErrorCode, isEnoent } from "@leitwerk-dev/process-sdk";
26
29
  import { resolvePiAgentDir } from "@leitwerk-dev/process-sdk/pi-config";
27
30
  import type { ConfigSnapshot } from "@leitwerk-dev/protocol";
28
31
  import { parseDurationMs } from "@leitwerk-dev/watcher-utils";
@@ -34,6 +37,7 @@ import {
34
37
  type PiBranchOperation,
35
38
  resolveExecutionAnchorEntryId,
36
39
  } from "./pi-branch-guard.js";
40
+ import { createRepositoryBashTool } from "./repository-bash-tool.js";
37
41
  import { buildLeitwerkResourceLoaderOptions } from "./resource-loader-factory.js";
38
42
 
39
43
  const LEITWERK_TOOL_BOOTSTRAP_NAME = "__leitwerk_runtime_bootstrap__";
@@ -113,12 +117,7 @@ export async function inspectPiTreeForPlanning(
113
117
  try {
114
118
  await access(input.treeFile);
115
119
  } catch (error) {
116
- if (
117
- typeof error === "object" &&
118
- error !== null &&
119
- "code" in error &&
120
- (error as { code?: unknown }).code === "ENOENT"
121
- ) {
120
+ if (isEnoent(error)) {
122
121
  return { currentLeafId: null, entries: [] };
123
122
  }
124
123
  throw error;
@@ -364,23 +363,6 @@ function activeTurnId(state: { currentTurnId: string | null; turnSequence: numbe
364
363
  return state.currentTurnId ?? `turn-${state.turnSequence}`;
365
364
  }
366
365
 
367
- function readNonEmptyString(value: unknown): string | null {
368
- return typeof value === "string" && value.trim() !== "" ? value : null;
369
- }
370
-
371
- function readFiniteNumber(value: unknown): number | null {
372
- if (typeof value === "number" && Number.isFinite(value)) {
373
- return value;
374
- }
375
- if (typeof value === "string" && value.trim() !== "") {
376
- const parsed = Number(value);
377
- if (Number.isFinite(parsed)) {
378
- return parsed;
379
- }
380
- }
381
- return null;
382
- }
383
-
384
366
  function listRecordKeys(value: Record<string, unknown>): string[] {
385
367
  return Object.keys(value).slice(0, 12);
386
368
  }
@@ -1064,21 +1046,7 @@ export function translateAgentSessionEventEnvelope(
1064
1046
  provider: string;
1065
1047
  model: string;
1066
1048
  timestamp: unknown;
1067
- usage: {
1068
- input: number;
1069
- output: number;
1070
- reasoning?: number;
1071
- cacheRead: number;
1072
- cacheWrite: number;
1073
- totalTokens: number;
1074
- cost: {
1075
- input: number;
1076
- output: number;
1077
- cacheRead: number;
1078
- cacheWrite: number;
1079
- total: number;
1080
- };
1081
- };
1049
+ usage: Omit<PiUsageData, "cacheHitRate">;
1082
1050
  }>;
1083
1051
  const timestamp = toIsoTimestamp(assistantMessage.timestamp);
1084
1052
  const piEvents: PiEvent[] = [];
@@ -1531,6 +1499,7 @@ export class SdkPiTreeHandle implements PiTreeHandle {
1531
1499
  const controller = new AbortController();
1532
1500
  this.continuationRetryAbortController = controller;
1533
1501
  try {
1502
+ const { retryAssistantCall } = await import("@earendil-works/pi-ai");
1534
1503
  await retryAssistantCall(
1535
1504
  async () => {
1536
1505
  await this.session.agent.continue();
@@ -2002,15 +1971,6 @@ function resolveModelSelection(
2002
1971
  };
2003
1972
  }
2004
1973
 
2005
- function isAlreadyExistsError(error: unknown): boolean {
2006
- return (
2007
- typeof error === "object" &&
2008
- error !== null &&
2009
- "code" in error &&
2010
- (error as { code?: unknown }).code === "EEXIST"
2011
- );
2012
- }
2013
-
2014
1974
  async function ensureSessionFileExists(input: {
2015
1975
  treeFile: string;
2016
1976
  instanceId: string;
@@ -2028,7 +1988,7 @@ async function ensureSessionFileExists(input: {
2028
1988
  try {
2029
1989
  await writeFile(input.treeFile, `${JSON.stringify(header)}\n`, { flag: "wx" });
2030
1990
  } catch (error) {
2031
- if (isAlreadyExistsError(error)) {
1991
+ if (hasErrorCode(error, "EEXIST")) {
2032
1992
  return;
2033
1993
  }
2034
1994
  throw error;
@@ -2073,6 +2033,12 @@ function managedServicesKey(agentDir: string, sessionCwd: string): string {
2073
2033
  export class SdkPiTreeHandleFactory implements PiTreeHandleFactory {
2074
2034
  private readonly preparedServices = new Map<string, AgentSessionServices>();
2075
2035
 
2036
+ constructor() {
2037
+ // Module loading can overlap IPC connection and workspace materialization.
2038
+ // Bootstrap awaits the same module and reports any import failure.
2039
+ void import("@earendil-works/pi-coding-agent").catch(() => undefined);
2040
+ }
2041
+
2076
2042
  async prepareManagedBootstrap(
2077
2043
  opts: PiManagedBootstrapOptions,
2078
2044
  ): Promise<PiManagedBootstrapResult> {
@@ -2175,7 +2141,10 @@ export class SdkPiTreeHandleFactory implements PiTreeHandleFactory {
2175
2141
  ...(modelSelection.thinkingLevel
2176
2142
  ? { thinkingLevel: modelSelection.thinkingLevel as never }
2177
2143
  : {}),
2178
- customTools: [LEITWERK_TOOL_BOOTSTRAP],
2144
+ customTools: [
2145
+ LEITWERK_TOOL_BOOTSTRAP,
2146
+ (await createRepositoryBashTool(sessionCwd)) as ToolDefinition,
2147
+ ],
2179
2148
  noTools: "builtin",
2180
2149
  });
2181
2150
  getMutableSession(session)._refreshToolRegistry({ activeToolNames: [] });
@@ -1,3 +1,4 @@
1
+ import { readFiniteNumber, readNonBlankString } from "@leitwerk-dev/domain";
1
2
  import { translatePiEvent } from "./event-translator.js";
2
3
  import type { PiEvent, PiSessionDiagnostic, PiTreeHandle } from "./pi-adapter.js";
3
4
  import type { WorkerIpcReporter } from "./worker-ipc-reporter.js";
@@ -15,25 +16,6 @@ export interface PiEventReporterOptions {
15
16
  onLifecycleObservation?(kind: "pi_turn_started" | "pi_turn_ended"): void;
16
17
  }
17
18
 
18
- function readPiEventString(data: Record<string, unknown>, key: string): string | null {
19
- const value = data[key];
20
- return typeof value === "string" && value.trim() !== "" ? value : null;
21
- }
22
-
23
- function readPiEventNumber(data: Record<string, unknown>, key: string): number | null {
24
- const value = data[key];
25
- if (typeof value === "number" && Number.isFinite(value)) {
26
- return value;
27
- }
28
- if (typeof value === "string" && value.trim() !== "") {
29
- const parsed = Number(value);
30
- if (Number.isFinite(parsed)) {
31
- return parsed;
32
- }
33
- }
34
- return null;
35
- }
36
-
37
19
  export function createPiEventReporter(options: PiEventReporterOptions): PiEventReporter {
38
20
  let currentPiAttempt = 1;
39
21
  let currentPiMaxAttempts: number | null = null;
@@ -45,14 +27,14 @@ export function createPiEventReporter(options: PiEventReporterOptions): PiEventR
45
27
 
46
28
  const reportPiError = (event: PiEvent) => {
47
29
  const message =
48
- readPiEventString(event.data, "message") ??
49
- readPiEventString(event.data, "errorMessage") ??
30
+ readNonBlankString(event.data.message) ??
31
+ readNonBlankString(event.data.errorMessage) ??
50
32
  "Pi reported an error";
51
- const toolName = readPiEventString(event.data, "toolName");
52
- const source = readPiEventString(event.data, "source");
53
- const provider = readPiEventString(event.data, "provider");
54
- const model = readPiEventString(event.data, "model");
55
- const stopReason = readPiEventString(event.data, "stopReason");
33
+ const toolName = readNonBlankString(event.data.toolName);
34
+ const source = readNonBlankString(event.data.source);
35
+ const provider = readNonBlankString(event.data.provider);
36
+ const model = readNonBlankString(event.data.model);
37
+ const stopReason = readNonBlankString(event.data.stopReason);
56
38
  options.reporter.workerError({
57
39
  level: "error",
58
40
  code: toolName || source === "tool" ? "pi.tool_error" : "pi.request_failed",
@@ -73,13 +55,13 @@ export function createPiEventReporter(options: PiEventReporterOptions): PiEventR
73
55
  };
74
56
 
75
57
  const reportPiRetryLifecycle = (event: PiEvent) => {
76
- const attempt = readPiEventNumber(event.data, "attempt");
77
- const maxAttempts = readPiEventNumber(event.data, "maxAttempts");
78
- const delayMs = readPiEventNumber(event.data, "delayMs");
79
- const errorMessage = readPiEventString(event.data, "errorMessage");
80
- const finalError = readPiEventString(event.data, "finalError");
58
+ const attempt = readFiniteNumber(event.data.attempt);
59
+ const maxAttempts = readFiniteNumber(event.data.maxAttempts);
60
+ const delayMs = readFiniteNumber(event.data.delayMs);
61
+ const errorMessage = readNonBlankString(event.data.errorMessage);
62
+ const finalError = readNonBlankString(event.data.finalError);
81
63
  const message =
82
- readPiEventString(event.data, "message") ??
64
+ readNonBlankString(event.data.message) ??
83
65
  (event.type === "retry.start"
84
66
  ? "Pi scheduled an automatic retry"
85
67
  : event.data.success === true
@@ -153,12 +135,8 @@ export function createPiEventReporter(options: PiEventReporterOptions): PiEventR
153
135
  );
154
136
  options.emitExtensionEvent?.("worker.pi_event", payload);
155
137
  });
156
- piHandle.subscribeDiagnostics?.((diagnostic) => {
157
- reportPiDiagnostic(diagnostic);
158
- });
159
- },
160
- resetRetryState() {
161
- resetPiRetryState();
138
+ piHandle.subscribeDiagnostics?.(reportPiDiagnostic);
162
139
  },
140
+ resetRetryState: resetPiRetryState,
163
141
  };
164
142
  }
@@ -1,5 +1,5 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { mkdir, rename, rm, writeFile } from "node:fs/promises";
2
+ import { mkdir, open, readFile, rename, rm, writeFile } from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import {
5
5
  createCanonicalPiResourceBundle,
@@ -25,6 +25,72 @@ function fail(message: string): never {
25
25
  throw new Error(`Invalid Pi resource bundle: ${message}`);
26
26
  }
27
27
 
28
+ function requireStorageName(value: string, label: string): string {
29
+ if (!/^[a-zA-Z0-9_-]+$/u.test(value)) fail(`unsafe ${label}: ${value}`);
30
+ return value;
31
+ }
32
+
33
+ async function atomicWrite(pathname: string, content: Uint8Array, mode: number): Promise<void> {
34
+ const staging = `${pathname}.staging-${process.pid}-${randomUUID()}`;
35
+ const handle = await open(staging, "wx", mode);
36
+ try {
37
+ await handle.writeFile(content);
38
+ await handle.sync();
39
+ } finally {
40
+ await handle.close();
41
+ }
42
+ try {
43
+ await rename(staging, pathname);
44
+ } catch (error) {
45
+ await rm(staging, { force: true });
46
+ throw error;
47
+ }
48
+ }
49
+
50
+ /** Resolves an immutable bundle from delivered bytes or the process volume and records its start. */
51
+ export async function persistPiResourceBundleForStart(input: {
52
+ bundlesDir: string;
53
+ startRecordId: string;
54
+ digest: string;
55
+ archiveBase64?: string;
56
+ deliveredBundle?: Uint8Array;
57
+ }): Promise<{ bundle: Uint8Array; reused: boolean }> {
58
+ const digest = requireStorageName(input.digest, "resource digest");
59
+ const startRecordId = requireStorageName(input.startRecordId, "turn-start id");
60
+ const bundlesDir = path.resolve(input.bundlesDir);
61
+ const startsDir = path.join(bundlesDir, "starts");
62
+ const bundlePath = path.join(bundlesDir, `${digest}.tar`);
63
+ await mkdir(startsDir, { recursive: true, mode: 0o700 });
64
+
65
+ let bundle: Uint8Array | null = null;
66
+ let reused = false;
67
+ try {
68
+ const existing = await readFile(bundlePath);
69
+ verifyCanonicalPiResourceBundle(existing, digest);
70
+ bundle = existing;
71
+ reused = true;
72
+ } catch (error) {
73
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT" && input.archiveBase64 === undefined) {
74
+ throw error;
75
+ }
76
+ }
77
+ if (!bundle) {
78
+ if (!input.deliveredBundle && input.archiveBase64 === undefined) {
79
+ throw new Error(`Pi resource bundle '${digest}' is unavailable on the process volume`);
80
+ }
81
+ bundle = input.deliveredBundle ?? Buffer.from(input.archiveBase64 as string, "base64");
82
+ verifyCanonicalPiResourceBundle(bundle, digest);
83
+ await atomicWrite(bundlePath, bundle, 0o600);
84
+ }
85
+
86
+ const manifest = Buffer.from(
87
+ `${JSON.stringify({ startRecordId, digest, persistedAt: new Date().toISOString() })}\n`,
88
+ "utf8",
89
+ );
90
+ await atomicWrite(path.join(startsDir, `${startRecordId}.json`), manifest, 0o600);
91
+ return { bundle, reused };
92
+ }
93
+
28
94
  async function writeExtractedFiles(
29
95
  root: string,
30
96
  files: readonly ExtractedPiResourceFile[],
@@ -18,6 +18,14 @@ export type PreTurnTargetedInput = Pick<
18
18
  target: NonNullable<InputItem["target"]>;
19
19
  };
20
20
 
21
+ export type AppliedTargetedInputMetadata = {
22
+ currentPrimaryPathLeafId?: string | null;
23
+ rootEntryId?: string | null;
24
+ targetSemanticRef?: ProcessSemanticEntryRefKey | null;
25
+ targetProductName?: string | null;
26
+ targetEntryId?: string | null;
27
+ };
28
+
21
29
  function resolveTargetSemanticRef(
22
30
  target: PreTurnTargetedInput["target"],
23
31
  ): ProcessSemanticEntryRefKey | null {
@@ -128,17 +136,7 @@ export async function applyPreTurnTargetedInputs(input: {
128
136
  recoveryBaseEntryId?: string | null;
129
137
  reuseExistingWithoutBranching?: boolean;
130
138
  requireExisting?: boolean;
131
- onApplied?(
132
- inputId: string,
133
- sequence: number,
134
- meta?: {
135
- currentPrimaryPathLeafId?: string | null;
136
- rootEntryId?: string | null;
137
- targetSemanticRef?: ProcessSemanticEntryRefKey | null;
138
- targetProductName?: string | null;
139
- targetEntryId?: string | null;
140
- },
141
- ): void;
139
+ onApplied?(inputId: string, sequence: number, meta?: AppliedTargetedInputMetadata): void;
142
140
  }): Promise<void> {
143
141
  if (input.inputs.length === 0) {
144
142
  return;