@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
@@ -7,12 +7,18 @@ import {
7
7
  } from "./pi-adapter.js";
8
8
  import { toErrorMessage } from "./turn-execution-error.js";
9
9
 
10
+ /** @internal */
10
11
  export type PromptGuardTimer = ReturnType<typeof setTimeout>;
11
12
 
13
+ /** @internal */
12
14
  export interface PromptGuardScheduler {
15
+ /** @internal */
13
16
  setTimeout(handler: () => void, delayMs: number): PromptGuardTimer;
17
+ /** @internal */
14
18
  clearTimeout(timer: PromptGuardTimer): void;
19
+ /** @internal */
15
20
  sleep(delayMs: number): Promise<void>;
21
+ /** @internal */
16
22
  now(): Date;
17
23
  }
18
24
 
@@ -121,8 +127,7 @@ export async function promptWithGuards(
121
127
  let maxDurationTimer: PromptGuardTimer | null = null;
122
128
  let inactivityTimer: PromptGuardTimer | null = null;
123
129
  let rejectTimeout: ((error: Error) => void) | null = null;
124
- let timedOut = false;
125
- let aborted = false;
130
+ let abortReason: PromptGuardTimeoutKind | "operator_abort" | null = null;
126
131
  let sawCompaction = false;
127
132
  let removeOperatorAbortListener: (() => void) | null = null;
128
133
  let removeSuspensionListener: (() => void) | null = null;
@@ -141,11 +146,44 @@ export async function promptWithGuards(
141
146
  }
142
147
  };
143
148
 
149
+ const abortWithinGracePeriod = async (timeoutKind?: PromptGuardTimeoutKind) => {
150
+ let abortCompleted = false;
151
+ try {
152
+ await Promise.race([
153
+ input.piHandle.abortTurn().then(() => {
154
+ abortCompleted = true;
155
+ }),
156
+ deps.scheduler.sleep(turnAbortGracePeriodMs),
157
+ ]);
158
+ if (!abortCompleted) {
159
+ reportError({
160
+ level: "error",
161
+ code: "guard.abort_grace_elapsed",
162
+ message: `${timeoutKind ? "Timed out" : "Operator-stopped"} turn '${input.turnId}' did not abort within ${turnAbortGracePeriodMs}ms`,
163
+ turnRecordId: input.turnRecordId,
164
+ turnId: input.turnId,
165
+ errorClass: "infrastructure",
166
+ details: { turnAbortGracePeriodMs, ...(timeoutKind ? { timeoutKind } : {}) },
167
+ });
168
+ }
169
+ } catch (error) {
170
+ reportError({
171
+ level: "error",
172
+ code: "guard.abort_failed",
173
+ message: `Failed to abort ${timeoutKind ? "timed out" : "operator-stopped"} turn '${input.turnId}': ${toErrorMessage(error)}`,
174
+ turnRecordId: input.turnRecordId,
175
+ turnId: input.turnId,
176
+ errorClass: "infrastructure",
177
+ ...(timeoutKind ? { details: { timeoutKind } } : {}),
178
+ });
179
+ }
180
+ };
181
+
144
182
  const requestAbortForTimeout = (timeoutKind: PromptGuardTimeoutKind, timeoutMs: number) => {
145
- if (timedOut || aborted) {
183
+ if (abortReason !== null) {
146
184
  return;
147
185
  }
148
- timedOut = true;
186
+ abortReason = timeoutKind;
149
187
  clearTimers();
150
188
  const error = new PromptTimeoutError(input.turnId, timeoutKind, timeoutMs);
151
189
  reportError({
@@ -171,45 +209,14 @@ export async function promptWithGuards(
171
209
  });
172
210
  rejectTimeout?.(error);
173
211
 
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
- })();
212
+ void abortWithinGracePeriod(timeoutKind);
206
213
  };
207
214
 
208
215
  const requestOperatorAbort = () => {
209
- if (timedOut || aborted) {
216
+ if (abortReason !== null) {
210
217
  return;
211
218
  }
212
- aborted = true;
219
+ abortReason = "operator_abort";
213
220
  clearTimers();
214
221
  const error = new OperatorAbortError(input.turnId);
215
222
  reportError({
@@ -231,37 +238,7 @@ export async function promptWithGuards(
231
238
  });
232
239
  rejectTimeout?.(error);
233
240
 
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
- })();
241
+ void abortWithinGracePeriod();
265
242
  };
266
243
 
267
244
  const armMaxDurationTimer = () => {
@@ -270,8 +247,7 @@ export async function promptWithGuards(
270
247
  turnMaxDurationMs <= 0 ||
271
248
  maxDurationRemainingMs <= 0 ||
272
249
  guardsPaused ||
273
- timedOut ||
274
- aborted
250
+ abortReason !== null
275
251
  )
276
252
  return;
277
253
  maxDurationArmedAt = deps.scheduler.now().getTime();
@@ -285,8 +261,7 @@ export async function promptWithGuards(
285
261
  !turnInactivityTimeoutMs ||
286
262
  turnInactivityTimeoutMs <= 0 ||
287
263
  guardsPaused ||
288
- timedOut ||
289
- aborted
264
+ abortReason !== null
290
265
  ) {
291
266
  return;
292
267
  }
@@ -315,7 +290,7 @@ export async function promptWithGuards(
315
290
  });
316
291
  removeSuspensionListener =
317
292
  deps.guardSuspension?.subscribe((paused) => {
318
- if (guardsPaused === paused || timedOut || aborted) return;
293
+ if (guardsPaused === paused || abortReason !== null) return;
319
294
  guardsPaused = paused;
320
295
  if (paused) {
321
296
  if (maxDurationTimer !== null) {
@@ -358,7 +333,7 @@ export async function promptWithGuards(
358
333
  operatorAbortSignal !== undefined;
359
334
 
360
335
  try {
361
- if (aborted) {
336
+ if (abortReason === "operator_abort") {
362
337
  await guardPromise;
363
338
  }
364
339
  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";
@@ -9,11 +10,15 @@ import type { CredentialRefreshDescriptor } from "./bootstrap-session.js";
9
10
 
10
11
  export type WorkerRuntimeTimer = PromptGuardTimer;
11
12
 
13
+ /** @internal */
12
14
  export interface WorkerRuntimeScheduler extends PromptGuardScheduler {
15
+ /** @internal */
13
16
  sleep(delayMs: number): Promise<void>;
17
+ /** @internal */
14
18
  now(): Date;
15
19
  }
16
20
 
21
+ /** @internal */
17
22
  export const nodeWorkerRuntimeScheduler: WorkerRuntimeScheduler = {
18
23
  setTimeout(handler, delayMs) {
19
24
  return setTimeout(handler, delayMs);
@@ -29,43 +34,80 @@ export const nodeWorkerRuntimeScheduler: WorkerRuntimeScheduler = {
29
34
  },
30
35
  };
31
36
 
37
+ /** @internal */
32
38
  export interface WorkerRuntimeConfig {
39
+ /** @internal */
33
40
  instanceId: string;
41
+ /** @internal */
34
42
  workerId: string;
43
+ /** @internal */
35
44
  heartbeatIntervalMs?: number;
45
+ /** @internal */
36
46
  turnMaxDurationMs?: number;
47
+ /** @internal */
37
48
  turnInactivityTimeoutMs?: number;
49
+ /** @internal */
38
50
  turnAbortGracePeriodMs?: number;
39
51
  }
40
52
 
53
+ /** @internal */
41
54
  export interface ResultImageToolFactory {
55
+ /** @internal */
42
56
  create(input: {
57
+ /** @internal */
43
58
  workspaceRoot?: string;
59
+ /** @internal */
44
60
  instanceId: string;
61
+ /** @internal */
45
62
  turnRecordId: string;
46
63
  }): PiCustomTool | null;
47
64
  }
48
65
 
66
+ /** @internal */
49
67
  export interface WorkerRuntimeAdapters {
68
+ /** @internal */
50
69
  transport: WorkerIpc;
70
+ /** @internal */
51
71
  sessionSnapshots: WorkerSessionSnapshotExchange;
72
+ /** @internal */
52
73
  resultImageTools: ResultImageToolFactory;
74
+ /** @internal */
53
75
  piFactory: PiTreeHandleFactory;
76
+ /** @internal */
54
77
  gitOps: RunRootGitOps;
78
+ /** @internal */
79
+ developmentTools?: DevelopmentToolEnvironment;
80
+ /** @internal */
55
81
  scheduler: WorkerRuntimeScheduler;
82
+ /** @internal */
56
83
  exit(code: number): void;
84
+ /** @internal */
57
85
  stderr?: NodeJS.WritableStream;
86
+ /** @internal */
58
87
  extensionEvents?: EventBus;
59
- sampleCredentials?: (
60
- descriptor: CredentialRefreshDescriptor,
61
- ) => Promise<{ values: Record<string, string>; fingerprint: string }>;
88
+ /** @internal */
89
+ sampleCredentials?: (descriptor: CredentialRefreshDescriptor) => Promise<{
90
+ /** @internal */
91
+ values: Record<string, string>;
92
+ /** @internal */
93
+ fingerprint: string;
94
+ }>;
95
+ /** @internal */
62
96
  resolveWorkerProcess?: (
63
97
  processId: string,
64
- opts?: { paramsJson?: string | null; stateJson?: string | null },
98
+ opts?: {
99
+ /** @internal */
100
+ paramsJson?: string | null;
101
+ /** @internal */
102
+ stateJson?: string | null;
103
+ },
65
104
  ) => Promise<ResolvedWorkerProcess | undefined> | ResolvedWorkerProcess | undefined;
66
105
  }
67
106
 
107
+ /** @internal */
68
108
  export interface WorkerRuntimeOptions {
109
+ /** @internal */
69
110
  config: WorkerRuntimeConfig;
111
+ /** @internal */
70
112
  adapters: WorkerRuntimeAdapters;
71
113
  }
@@ -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,9 @@ 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
+ /** @internal */
63
+ export interface CredentialRefreshDescriptor
64
+ extends NonNullable<BootstrapWorkerRuntimeResult["credentialRefresh"]> {}
63
65
 
64
66
  export interface WorkerBootstrapCompletion {
65
67
  session: PreparedWorkerSession;
@@ -102,6 +104,8 @@ function validatePreparedSession(input: {
102
104
  proposedTurnRecordId: payload.turnStart.proposedTurnRecordId,
103
105
  acceptedTurnRecordId:
104
106
  payload.turnStart.state.kind === "accepted" ? payload.turnStart.state.turnRecordId : null,
107
+ startKind: payload.turnStart.startKind,
108
+ ...(payload.llmPreparation ? { llmPreparation: payload.llmPreparation } : {}),
105
109
  treeFile: payload.treePaths.primaryTreeFile,
106
110
  workspaceRoot: payload.treePaths.workspaceRoot,
107
111
  turnResultMarkdownBySemanticRef: payload.turnResultMarkdownBySemanticRef,
@@ -132,6 +136,7 @@ type WorkerLiveResourcesDeps = {
132
136
  instanceId: string;
133
137
  piFactory: PiTreeHandleFactory;
134
138
  gitOps: RunRootGitOps;
139
+ developmentTools: DevelopmentToolEnvironment;
135
140
  scheduler: WorkerRuntimeScheduler;
136
141
  sessionSnapshots?: WorkerSessionSnapshotExchange;
137
142
  resolveWorkerProcess?: (
@@ -139,12 +144,15 @@ type WorkerLiveResourcesDeps = {
139
144
  opts?: { paramsJson?: string | null; stateJson?: string | null },
140
145
  ) => Promise<ResolvedWorkerProcess | undefined> | ResolvedWorkerProcess | undefined;
141
146
  progress(payload: WorkerDiagnosticPayload): void;
147
+ diagnosticTrace(text: string): void;
142
148
  };
143
149
 
144
150
  /** Private concrete holder for provisional and active live resources. */
145
151
  export class WorkerLiveResources {
146
152
  #piHandle: PiTreeHandle | null = null;
153
+ #dockerCredentials = new DockerRegistryCredentials();
147
154
  #activeTurnAbort: AbortController | null = null;
155
+ #toolPreparationAbort: AbortController | null = null;
148
156
  #provisional = new Map<string, PreparedStartActivation>();
149
157
 
150
158
  constructor(private readonly deps: WorkerLiveResourcesDeps) {}
@@ -157,24 +165,46 @@ export class WorkerLiveResources {
157
165
  payload: WorkerStartPayload,
158
166
  settings: WorkerRuntimeSettings,
159
167
  ): 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
- };
168
+ const toolPreparationAbort = new AbortController();
169
+ this.#toolPreparationAbort = toolPreparationAbort;
170
+ try {
171
+ const bootstrapped = await bootstrapWorkerRuntime({
172
+ instanceId: this.deps.instanceId,
173
+ payload,
174
+ piFactory: this.deps.piFactory,
175
+ gitOps: this.deps.gitOps,
176
+ developmentTools: this.deps.developmentTools,
177
+ configureDockerCredentials: (credentials, enabled) =>
178
+ this.#dockerCredentials.install(credentials, enabled),
179
+ toolPreparationSignal: toolPreparationAbort.signal,
180
+ scheduler: this.deps.scheduler,
181
+ onToolPreparationProgress: (repositoryKey, phase) =>
182
+ this.deps.progress({
183
+ level: "info",
184
+ code: `development_tools.${phase}`,
185
+ message: `${phase === "installing" ? "Installing" : "Verifying"} development tools for ${repositoryKey}`,
186
+ details: { repositoryKey },
187
+ }),
188
+ onToolDiagnosticTrace: this.deps.diagnosticTrace,
189
+ resolveWorkerProcess: this.deps.resolveWorkerProcess,
190
+ });
191
+ const session = validatePreparedSession({ bootstrapped, payload, settings });
192
+ this.#provisional.set(payload.turnStart.id, bootstrapped.activation);
193
+ return {
194
+ session,
195
+ pendingInputs: bootstrapped.pendingInputs,
196
+ readyPayload: bootstrapped.readyPayload,
197
+ ...(bootstrapped.credentialRefresh
198
+ ? { credentialRefresh: bootstrapped.credentialRefresh }
199
+ : {}),
200
+ diagnostics: bootstrapped.diagnostics,
201
+ };
202
+ } catch (error) {
203
+ this.#dockerCredentials.dispose();
204
+ throw error;
205
+ } finally {
206
+ if (this.#toolPreparationAbort === toolPreparationAbort) this.#toolPreparationAbort = null;
207
+ }
178
208
  }
179
209
 
180
210
  async activate(startRecordId: string, turnRecordId: string, session: PreparedWorkerSession) {
@@ -237,6 +267,12 @@ export class WorkerLiveResources {
237
267
  }
238
268
  }
239
269
 
270
+ abortToolPreparation(): boolean {
271
+ if (!this.#toolPreparationAbort) return false;
272
+ this.#toolPreparationAbort.abort();
273
+ return true;
274
+ }
275
+
240
276
  abortActiveTurn(): boolean {
241
277
  if (!this.#activeTurnAbort) return false;
242
278
  this.#activeTurnAbort.abort();
@@ -248,6 +284,7 @@ export class WorkerLiveResources {
248
284
  }
249
285
 
250
286
  async cleanup(): Promise<void> {
287
+ this.#dockerCredentials.dispose();
251
288
  this.#provisional.clear();
252
289
  await this.#piHandle?.close();
253
290
  this.#piHandle = null;
@@ -255,17 +292,6 @@ export class WorkerLiveResources {
255
292
  }
256
293
  }
257
294
 
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
295
  /** Reads one credential sample. Values are transient command-result data. */
270
296
  export async function sampleCredentialFiles(
271
297
  descriptor: CredentialRefreshDescriptor,
@@ -273,10 +299,10 @@ export async function sampleCredentialFiles(
273
299
  const values: Record<string, string> = {};
274
300
  for (const credentialPath of descriptor.declaredCredentialPaths) {
275
301
  const json = JSON.parse(await readFile(path.join(descriptor.agentDir, credentialPath), "utf8"));
302
+ if (!json || typeof json !== "object" || Array.isArray(json)) {
303
+ throw new Error(`Credential file '${credentialPath}' must contain a JSON object`);
304
+ }
276
305
  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
306
  const selected = (json as Record<string, unknown>)[descriptor.providerId];
281
307
  if (selected && typeof selected === "object" && !Array.isArray(selected)) {
282
308
  for (const [key, value] of Object.entries(selected as Record<string, unknown>)) {
@@ -285,7 +311,12 @@ export async function sampleCredentialFiles(
285
311
  values[key] = String(value);
286
312
  }
287
313
  }
288
- } else Object.assign(values, strings(json, credentialPath));
314
+ } else {
315
+ Object.assign(
316
+ values,
317
+ Object.fromEntries(Object.entries(json).filter(([, value]) => typeof value === "string")),
318
+ );
319
+ }
289
320
  }
290
321
  const fingerprint = JSON.stringify(
291
322
  Object.keys(values)