@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
@@ -121,8 +121,7 @@ export async function promptWithGuards(
121
121
  let maxDurationTimer: PromptGuardTimer | null = null;
122
122
  let inactivityTimer: PromptGuardTimer | null = null;
123
123
  let rejectTimeout: ((error: Error) => void) | null = null;
124
- let timedOut = false;
125
- let aborted = false;
124
+ let abortReason: PromptGuardTimeoutKind | "operator_abort" | null = null;
126
125
  let sawCompaction = false;
127
126
  let removeOperatorAbortListener: (() => void) | null = null;
128
127
  let removeSuspensionListener: (() => void) | null = null;
@@ -141,11 +140,44 @@ export async function promptWithGuards(
141
140
  }
142
141
  };
143
142
 
143
+ const abortWithinGracePeriod = async (timeoutKind?: PromptGuardTimeoutKind) => {
144
+ let abortCompleted = false;
145
+ try {
146
+ await Promise.race([
147
+ input.piHandle.abortTurn().then(() => {
148
+ abortCompleted = true;
149
+ }),
150
+ deps.scheduler.sleep(turnAbortGracePeriodMs),
151
+ ]);
152
+ if (!abortCompleted) {
153
+ reportError({
154
+ level: "error",
155
+ code: "guard.abort_grace_elapsed",
156
+ message: `${timeoutKind ? "Timed out" : "Operator-stopped"} turn '${input.turnId}' did not abort within ${turnAbortGracePeriodMs}ms`,
157
+ turnRecordId: input.turnRecordId,
158
+ turnId: input.turnId,
159
+ errorClass: "infrastructure",
160
+ details: { turnAbortGracePeriodMs, ...(timeoutKind ? { timeoutKind } : {}) },
161
+ });
162
+ }
163
+ } catch (error) {
164
+ reportError({
165
+ level: "error",
166
+ code: "guard.abort_failed",
167
+ message: `Failed to abort ${timeoutKind ? "timed out" : "operator-stopped"} turn '${input.turnId}': ${toErrorMessage(error)}`,
168
+ turnRecordId: input.turnRecordId,
169
+ turnId: input.turnId,
170
+ errorClass: "infrastructure",
171
+ ...(timeoutKind ? { details: { timeoutKind } } : {}),
172
+ });
173
+ }
174
+ };
175
+
144
176
  const requestAbortForTimeout = (timeoutKind: PromptGuardTimeoutKind, timeoutMs: number) => {
145
- if (timedOut || aborted) {
177
+ if (abortReason !== null) {
146
178
  return;
147
179
  }
148
- timedOut = true;
180
+ abortReason = timeoutKind;
149
181
  clearTimers();
150
182
  const error = new PromptTimeoutError(input.turnId, timeoutKind, timeoutMs);
151
183
  reportError({
@@ -171,45 +203,14 @@ export async function promptWithGuards(
171
203
  });
172
204
  rejectTimeout?.(error);
173
205
 
174
- void (async () => {
175
- let abortCompleted = false;
176
- try {
177
- await Promise.race([
178
- input.piHandle.abortTurn().then(() => {
179
- abortCompleted = true;
180
- }),
181
- deps.scheduler.sleep(turnAbortGracePeriodMs),
182
- ]);
183
- if (!abortCompleted) {
184
- reportError({
185
- level: "error",
186
- code: "guard.abort_grace_elapsed",
187
- message: `Timed out turn '${input.turnId}' did not abort within ${turnAbortGracePeriodMs}ms`,
188
- turnRecordId: input.turnRecordId,
189
- turnId: input.turnId,
190
- errorClass: "infrastructure",
191
- details: { turnAbortGracePeriodMs, timeoutKind },
192
- });
193
- }
194
- } catch (error) {
195
- reportError({
196
- level: "error",
197
- code: "guard.abort_failed",
198
- message: `Failed to abort timed out turn '${input.turnId}': ${toErrorMessage(error)}`,
199
- turnRecordId: input.turnRecordId,
200
- turnId: input.turnId,
201
- errorClass: "infrastructure",
202
- details: { timeoutKind },
203
- });
204
- }
205
- })();
206
+ void abortWithinGracePeriod(timeoutKind);
206
207
  };
207
208
 
208
209
  const requestOperatorAbort = () => {
209
- if (timedOut || aborted) {
210
+ if (abortReason !== null) {
210
211
  return;
211
212
  }
212
- aborted = true;
213
+ abortReason = "operator_abort";
213
214
  clearTimers();
214
215
  const error = new OperatorAbortError(input.turnId);
215
216
  reportError({
@@ -231,37 +232,7 @@ export async function promptWithGuards(
231
232
  });
232
233
  rejectTimeout?.(error);
233
234
 
234
- void (async () => {
235
- let abortCompleted = false;
236
- try {
237
- await Promise.race([
238
- input.piHandle.abortTurn().then(() => {
239
- abortCompleted = true;
240
- }),
241
- deps.scheduler.sleep(turnAbortGracePeriodMs),
242
- ]);
243
- if (!abortCompleted) {
244
- reportError({
245
- level: "error",
246
- code: "guard.abort_grace_elapsed",
247
- message: `Operator-stopped turn '${input.turnId}' did not abort within ${turnAbortGracePeriodMs}ms`,
248
- turnRecordId: input.turnRecordId,
249
- turnId: input.turnId,
250
- errorClass: "infrastructure",
251
- details: { turnAbortGracePeriodMs },
252
- });
253
- }
254
- } catch (error) {
255
- reportError({
256
- level: "error",
257
- code: "guard.abort_failed",
258
- message: `Failed to abort operator-stopped turn '${input.turnId}': ${toErrorMessage(error)}`,
259
- turnRecordId: input.turnRecordId,
260
- turnId: input.turnId,
261
- errorClass: "infrastructure",
262
- });
263
- }
264
- })();
235
+ void abortWithinGracePeriod();
265
236
  };
266
237
 
267
238
  const armMaxDurationTimer = () => {
@@ -270,8 +241,7 @@ export async function promptWithGuards(
270
241
  turnMaxDurationMs <= 0 ||
271
242
  maxDurationRemainingMs <= 0 ||
272
243
  guardsPaused ||
273
- timedOut ||
274
- aborted
244
+ abortReason !== null
275
245
  )
276
246
  return;
277
247
  maxDurationArmedAt = deps.scheduler.now().getTime();
@@ -285,8 +255,7 @@ export async function promptWithGuards(
285
255
  !turnInactivityTimeoutMs ||
286
256
  turnInactivityTimeoutMs <= 0 ||
287
257
  guardsPaused ||
288
- timedOut ||
289
- aborted
258
+ abortReason !== null
290
259
  ) {
291
260
  return;
292
261
  }
@@ -315,7 +284,7 @@ export async function promptWithGuards(
315
284
  });
316
285
  removeSuspensionListener =
317
286
  deps.guardSuspension?.subscribe((paused) => {
318
- if (guardsPaused === paused || timedOut || aborted) return;
287
+ if (guardsPaused === paused || abortReason !== null) return;
319
288
  guardsPaused = paused;
320
289
  if (paused) {
321
290
  if (maxDurationTimer !== null) {
@@ -358,7 +327,7 @@ export async function promptWithGuards(
358
327
  operatorAbortSignal !== undefined;
359
328
 
360
329
  try {
361
- if (aborted) {
330
+ if (abortReason === "operator_abort") {
362
331
  await guardPromise;
363
332
  }
364
333
  const result = !hasGuards
@@ -0,0 +1,15 @@
1
+ import type { createBashToolDefinition as createPiBashTool } from "@earendil-works/pi-coding-agent";
2
+ import { sanitizeWorkerSubprocessEnv } from "@leitwerk-dev/process-sdk";
3
+
4
+ /** Repository commands choose their own mode instead of inheriting the worker service mode. */
5
+ export async function createRepositoryBashTool(
6
+ cwd: string,
7
+ ): Promise<ReturnType<typeof createPiBashTool>> {
8
+ const { createBashToolDefinition } = await import("@earendil-works/pi-coding-agent");
9
+ return createBashToolDefinition(cwd, {
10
+ spawnHook: (context) => ({
11
+ ...context,
12
+ env: sanitizeWorkerSubprocessEnv(context.env, { NODE_ENV: undefined }),
13
+ }),
14
+ });
15
+ }
@@ -1,6 +1,6 @@
1
1
  import { existsSync, readdirSync, readFileSync } from "node:fs";
2
2
  import path from "node:path";
3
- import type { DefaultResourceLoader, SettingsManager } from "@earendil-works/pi-coding-agent";
3
+ import type { DefaultResourceLoader } from "@earendil-works/pi-coding-agent";
4
4
 
5
5
  const AGGREGATED_AGENTS_REL = "AGENTS.md";
6
6
  const AGGREGATED_SKILLS_DIR_REL = path.join(".leitwerk", "skills");
@@ -96,20 +96,3 @@ export async function buildLeitwerkResourceLoaderOptions(
96
96
  },
97
97
  };
98
98
  }
99
-
100
- export async function createResourceLoader(
101
- workspaceRoot: string,
102
- settingsManager: SettingsManager,
103
- agentDir: string,
104
- options: ResourceLoaderOptions = {},
105
- ): Promise<DefaultResourceLoader> {
106
- const { DefaultResourceLoader } = await import("@earendil-works/pi-coding-agent");
107
- const loader = new DefaultResourceLoader({
108
- cwd: workspaceRoot,
109
- agentDir,
110
- settingsManager,
111
- ...(await buildLeitwerkResourceLoaderOptions(workspaceRoot, agentDir, options)),
112
- });
113
- await loader.reload();
114
- return loader;
115
- }
@@ -1,6 +1,7 @@
1
1
  import { constants } from "node:fs";
2
2
  import { open, realpath, stat } from "node:fs/promises";
3
3
  import path from "node:path";
4
+ import { setTimeout as sleep } from "node:timers/promises";
4
5
  import type { PiCustomTool } from "@leitwerk-dev/process-sdk";
5
6
  import {
6
7
  buildWorkerResultImageUploadPath,
@@ -35,15 +36,6 @@ function isWithinRoot(rootReal: string, fileReal: string): boolean {
35
36
  return relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
36
37
  }
37
38
 
38
- function isRetryableResponse(response: Response): boolean {
39
- return response.status >= 500;
40
- }
41
-
42
- async function sleep(ms: number): Promise<void> {
43
- if (ms <= 0) return;
44
- await new Promise<void>((resolve) => setTimeout(resolve, ms));
45
- }
46
-
47
39
  async function readBoundedWorkspaceFile(
48
40
  entry: ImageEntry,
49
41
  workspaceRoot: string,
@@ -198,32 +190,29 @@ export function createUploadResultImagesTool(input: {
198
190
  if (response.ok) {
199
191
  try {
200
192
  const body = parseWorkerResultImageUploadResponse(await response.json());
201
- if (!body)
202
- return failure(
203
- entry,
204
- "upload_invalid_response",
205
- "Image upload response was invalid",
206
- );
207
- return {
208
- ...entry,
209
- status: "uploaded" as const,
210
- ...body,
211
- markdown: `![${entry.alt.replace(/[\\\]]/g, "\\$&")}](${body.url})`,
212
- };
193
+ if (body) {
194
+ return {
195
+ ...entry,
196
+ status: "uploaded" as const,
197
+ ...body,
198
+ markdown: `![${entry.alt.replace(/[\\\]]/g, "\\$&")}](${body.url})`,
199
+ };
200
+ }
213
201
  } catch {
214
- return failure(
215
- entry,
216
- "upload_invalid_response",
217
- "Image upload response was invalid",
218
- );
202
+ // Malformed JSON and invalid response fields have the same outcome.
219
203
  }
204
+ return failure(
205
+ entry,
206
+ "upload_invalid_response",
207
+ "Image upload response was invalid",
208
+ );
220
209
  }
221
210
  finalFailure = failure(
222
211
  entry,
223
212
  `upload_http_${response.status}`,
224
213
  `Image upload was rejected with HTTP ${response.status}`,
225
214
  );
226
- if (!isRetryableResponse(response)) return finalFailure;
215
+ if (response.status < 500) return finalFailure;
227
216
  }
228
217
  if (attempt + 1 < MAX_UPLOAD_ATTEMPTS) {
229
218
  await (input.sleepImpl ?? sleep)(RETRY_DELAY_MS);
@@ -1,5 +1,6 @@
1
1
  import type { ResolvedWorkerProcess } from "@leitwerk-dev/extension-runtime";
2
2
  import type { EventBus, PiCustomTool } from "@leitwerk-dev/process-sdk";
3
+ import type { DevelopmentToolEnvironment } from "../development-tool-environment.js";
3
4
  import type { WorkerIpc } from "../ipc.js";
4
5
  import type { PiTreeHandleFactory } from "../pi-adapter.js";
5
6
  import type { PromptGuardScheduler, PromptGuardTimer } from "../prompt-guards.js";
@@ -52,6 +53,7 @@ export interface WorkerRuntimeAdapters {
52
53
  resultImageTools: ResultImageToolFactory;
53
54
  piFactory: PiTreeHandleFactory;
54
55
  gitOps: RunRootGitOps;
56
+ developmentTools?: DevelopmentToolEnvironment;
55
57
  scheduler: WorkerRuntimeScheduler;
56
58
  exit(code: number): void;
57
59
  stderr?: NodeJS.WritableStream;
@@ -8,7 +8,9 @@ import type {
8
8
  } from "@leitwerk-dev/domain";
9
9
  import type { ResolvedWorkerProcess } from "@leitwerk-dev/extension-runtime";
10
10
  import type { WorkerReadyPayload, WorkerStartPayload } from "@leitwerk-dev/worker-protocol";
11
+ import type { DevelopmentToolEnvironment } from "../development-tool-environment.js";
11
12
  import type { WorkerDiagnosticPayload } from "../diagnostics.js";
13
+ import { DockerRegistryCredentials } from "../docker-registry-credentials.js";
12
14
  import type { InputItem } from "../input-consumer.js";
13
15
  import type { PiTreeHandle, PiTreeHandleFactory } from "../pi-adapter.js";
14
16
  import type { WorkerSessionSnapshotExchange } from "../session-snapshot-exchange.js";
@@ -17,6 +19,7 @@ import type { RunRootGitOps } from "../workspace/run-root.js";
17
19
  import type { WorkerRuntimeScheduler } from "./adapters.js";
18
20
  import {
19
21
  activatePreparedStart,
22
+ type BootstrapWorkerRuntimeResult,
20
23
  bootstrapWorkerRuntime,
21
24
  type PreparedStartActivation,
22
25
  } from "./bootstrap.js";
@@ -30,6 +33,8 @@ interface PreparedSessionBase {
30
33
  startRecordId: string;
31
34
  proposedTurnRecordId: string;
32
35
  acceptedTurnRecordId: string | null;
36
+ startKind: WorkerStartPayload["turnStart"]["startKind"];
37
+ llmPreparation?: NonNullable<WorkerStartPayload["llmPreparation"]>;
33
38
  treeFile: string;
34
39
  workspaceRoot: string;
35
40
  turnResultMarkdownBySemanticRef?: Partial<Record<ProcessSemanticEntryRefKey, string>>;
@@ -54,12 +59,8 @@ export interface PreparedLlmSession extends PreparedSessionBase {
54
59
 
55
60
  export type PreparedWorkerSession = PreparedAutomaticSession | PreparedLlmSession;
56
61
 
57
- export interface CredentialRefreshDescriptor {
58
- agentDir: string;
59
- declaredCredentialPaths: readonly string[];
60
- providerId: string;
61
- revision: number;
62
- }
62
+ export interface CredentialRefreshDescriptor
63
+ extends NonNullable<BootstrapWorkerRuntimeResult["credentialRefresh"]> {}
63
64
 
64
65
  export interface WorkerBootstrapCompletion {
65
66
  session: PreparedWorkerSession;
@@ -102,6 +103,8 @@ function validatePreparedSession(input: {
102
103
  proposedTurnRecordId: payload.turnStart.proposedTurnRecordId,
103
104
  acceptedTurnRecordId:
104
105
  payload.turnStart.state.kind === "accepted" ? payload.turnStart.state.turnRecordId : null,
106
+ startKind: payload.turnStart.startKind,
107
+ ...(payload.llmPreparation ? { llmPreparation: payload.llmPreparation } : {}),
105
108
  treeFile: payload.treePaths.primaryTreeFile,
106
109
  workspaceRoot: payload.treePaths.workspaceRoot,
107
110
  turnResultMarkdownBySemanticRef: payload.turnResultMarkdownBySemanticRef,
@@ -132,6 +135,7 @@ type WorkerLiveResourcesDeps = {
132
135
  instanceId: string;
133
136
  piFactory: PiTreeHandleFactory;
134
137
  gitOps: RunRootGitOps;
138
+ developmentTools: DevelopmentToolEnvironment;
135
139
  scheduler: WorkerRuntimeScheduler;
136
140
  sessionSnapshots?: WorkerSessionSnapshotExchange;
137
141
  resolveWorkerProcess?: (
@@ -139,12 +143,15 @@ type WorkerLiveResourcesDeps = {
139
143
  opts?: { paramsJson?: string | null; stateJson?: string | null },
140
144
  ) => Promise<ResolvedWorkerProcess | undefined> | ResolvedWorkerProcess | undefined;
141
145
  progress(payload: WorkerDiagnosticPayload): void;
146
+ diagnosticTrace(text: string): void;
142
147
  };
143
148
 
144
149
  /** Private concrete holder for provisional and active live resources. */
145
150
  export class WorkerLiveResources {
146
151
  #piHandle: PiTreeHandle | null = null;
152
+ #dockerCredentials = new DockerRegistryCredentials();
147
153
  #activeTurnAbort: AbortController | null = null;
154
+ #toolPreparationAbort: AbortController | null = null;
148
155
  #provisional = new Map<string, PreparedStartActivation>();
149
156
 
150
157
  constructor(private readonly deps: WorkerLiveResourcesDeps) {}
@@ -157,24 +164,46 @@ export class WorkerLiveResources {
157
164
  payload: WorkerStartPayload,
158
165
  settings: WorkerRuntimeSettings,
159
166
  ): Promise<WorkerBootstrapCompletion> {
160
- const bootstrapped = await bootstrapWorkerRuntime({
161
- instanceId: this.deps.instanceId,
162
- payload,
163
- piFactory: this.deps.piFactory,
164
- gitOps: this.deps.gitOps,
165
- scheduler: this.deps.scheduler,
166
- resolveWorkerProcess: this.deps.resolveWorkerProcess,
167
- });
168
- this.#provisional.set(payload.turnStart.id, bootstrapped.activation);
169
- return {
170
- session: validatePreparedSession({ bootstrapped, payload, settings }),
171
- pendingInputs: bootstrapped.pendingInputs,
172
- readyPayload: bootstrapped.readyPayload,
173
- ...(bootstrapped.credentialRefresh
174
- ? { credentialRefresh: bootstrapped.credentialRefresh }
175
- : {}),
176
- diagnostics: bootstrapped.diagnostics,
177
- };
167
+ const toolPreparationAbort = new AbortController();
168
+ this.#toolPreparationAbort = toolPreparationAbort;
169
+ try {
170
+ const bootstrapped = await bootstrapWorkerRuntime({
171
+ instanceId: this.deps.instanceId,
172
+ payload,
173
+ piFactory: this.deps.piFactory,
174
+ gitOps: this.deps.gitOps,
175
+ developmentTools: this.deps.developmentTools,
176
+ configureDockerCredentials: (credentials, enabled) =>
177
+ this.#dockerCredentials.install(credentials, enabled),
178
+ toolPreparationSignal: toolPreparationAbort.signal,
179
+ scheduler: this.deps.scheduler,
180
+ onToolPreparationProgress: (repositoryKey, phase) =>
181
+ this.deps.progress({
182
+ level: "info",
183
+ code: `development_tools.${phase}`,
184
+ message: `${phase === "installing" ? "Installing" : "Verifying"} development tools for ${repositoryKey}`,
185
+ details: { repositoryKey },
186
+ }),
187
+ onToolDiagnosticTrace: this.deps.diagnosticTrace,
188
+ resolveWorkerProcess: this.deps.resolveWorkerProcess,
189
+ });
190
+ const session = validatePreparedSession({ bootstrapped, payload, settings });
191
+ this.#provisional.set(payload.turnStart.id, bootstrapped.activation);
192
+ return {
193
+ session,
194
+ pendingInputs: bootstrapped.pendingInputs,
195
+ readyPayload: bootstrapped.readyPayload,
196
+ ...(bootstrapped.credentialRefresh
197
+ ? { credentialRefresh: bootstrapped.credentialRefresh }
198
+ : {}),
199
+ diagnostics: bootstrapped.diagnostics,
200
+ };
201
+ } catch (error) {
202
+ this.#dockerCredentials.dispose();
203
+ throw error;
204
+ } finally {
205
+ if (this.#toolPreparationAbort === toolPreparationAbort) this.#toolPreparationAbort = null;
206
+ }
178
207
  }
179
208
 
180
209
  async activate(startRecordId: string, turnRecordId: string, session: PreparedWorkerSession) {
@@ -237,6 +266,12 @@ export class WorkerLiveResources {
237
266
  }
238
267
  }
239
268
 
269
+ abortToolPreparation(): boolean {
270
+ if (!this.#toolPreparationAbort) return false;
271
+ this.#toolPreparationAbort.abort();
272
+ return true;
273
+ }
274
+
240
275
  abortActiveTurn(): boolean {
241
276
  if (!this.#activeTurnAbort) return false;
242
277
  this.#activeTurnAbort.abort();
@@ -248,6 +283,7 @@ export class WorkerLiveResources {
248
283
  }
249
284
 
250
285
  async cleanup(): Promise<void> {
286
+ this.#dockerCredentials.dispose();
251
287
  this.#provisional.clear();
252
288
  await this.#piHandle?.close();
253
289
  this.#piHandle = null;
@@ -255,17 +291,6 @@ export class WorkerLiveResources {
255
291
  }
256
292
  }
257
293
 
258
- function strings(value: unknown, name: string): Record<string, string> {
259
- if (!value || typeof value !== "object" || Array.isArray(value)) {
260
- throw new Error(`Credential file '${name}' must contain a JSON object`);
261
- }
262
- return Object.fromEntries(
263
- Object.entries(value).filter(
264
- (entry): entry is [string, string] => typeof entry[1] === "string",
265
- ),
266
- );
267
- }
268
-
269
294
  /** Reads one credential sample. Values are transient command-result data. */
270
295
  export async function sampleCredentialFiles(
271
296
  descriptor: CredentialRefreshDescriptor,
@@ -273,10 +298,10 @@ export async function sampleCredentialFiles(
273
298
  const values: Record<string, string> = {};
274
299
  for (const credentialPath of descriptor.declaredCredentialPaths) {
275
300
  const json = JSON.parse(await readFile(path.join(descriptor.agentDir, credentialPath), "utf8"));
301
+ if (!json || typeof json !== "object" || Array.isArray(json)) {
302
+ throw new Error(`Credential file '${credentialPath}' must contain a JSON object`);
303
+ }
276
304
  if (credentialPath === "auth.json") {
277
- if (!json || typeof json !== "object" || Array.isArray(json)) {
278
- throw new Error(`Credential file '${credentialPath}' must contain a JSON object`);
279
- }
280
305
  const selected = (json as Record<string, unknown>)[descriptor.providerId];
281
306
  if (selected && typeof selected === "object" && !Array.isArray(selected)) {
282
307
  for (const [key, value] of Object.entries(selected as Record<string, unknown>)) {
@@ -285,7 +310,12 @@ export async function sampleCredentialFiles(
285
310
  values[key] = String(value);
286
311
  }
287
312
  }
288
- } else Object.assign(values, strings(json, credentialPath));
313
+ } else {
314
+ Object.assign(
315
+ values,
316
+ Object.fromEntries(Object.entries(json).filter(([, value]) => typeof value === "string")),
317
+ );
318
+ }
289
319
  }
290
320
  const fingerprint = JSON.stringify(
291
321
  Object.keys(values)