@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
@@ -0,0 +1,452 @@
1
+ import { statfsSync } from "node:fs";
2
+ import { mkdir, rename, writeFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import type { DevelopmentToolsStartConfig } from "@leitwerk-dev/worker-protocol";
5
+ import { execa } from "execa";
6
+
7
+ export const PINNED_MISE_VERSION = "2026.8.14";
8
+ const OUTPUT_LIMIT_BYTES = 64 * 1024;
9
+ const JSON_LIMIT_BYTES = 1024 * 1024;
10
+ const TRACE_CHUNK_LENGTH = 16 * 1024;
11
+
12
+ export interface ToolPreparationRepository {
13
+ repositoryKey: string;
14
+ workingDirectory: string;
15
+ }
16
+
17
+ export interface ToolPreparationInput {
18
+ config: DevelopmentToolsStartConfig;
19
+ repositories: readonly ToolPreparationRepository[];
20
+ signal?: AbortSignal;
21
+ onProgress?(repositoryKey: string, phase: "installing" | "verifying"): void;
22
+ onDiagnosticTrace?(text: string): void;
23
+ }
24
+
25
+ export interface PreparedToolEnvironment {
26
+ miseVersion: string;
27
+ commandEnvironment: NodeJS.ProcessEnv;
28
+ repositories: Array<{
29
+ repositoryKey: string;
30
+ workingDirectory: string;
31
+ tools: Array<{ name: string; version: string }>;
32
+ }>;
33
+ warnings: string[];
34
+ }
35
+
36
+ export interface DevelopmentToolEnvironment {
37
+ prepare(input: ToolPreparationInput): Promise<PreparedToolEnvironment>;
38
+ }
39
+
40
+ export class DevelopmentToolPreparationError extends Error {
41
+ constructor(
42
+ message: string,
43
+ readonly code:
44
+ | "mise_missing"
45
+ | "mise_unsupported"
46
+ | "install_failed"
47
+ | "verification_failed"
48
+ | "timeout"
49
+ | "cancelled",
50
+ readonly diagnostics = "",
51
+ ) {
52
+ super(message);
53
+ this.name = "DevelopmentToolPreparationError";
54
+ }
55
+ }
56
+
57
+ function parseVersion(value: string): [number, number, number] | null {
58
+ const match = /(?:^|\s)(\d{4})\.(\d+)\.(\d+)(?:\s|$)/.exec(value);
59
+ return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
60
+ }
61
+
62
+ function compareVersion(a: readonly number[], b: readonly number[]): number {
63
+ for (let index = 0; index < 3; index++) {
64
+ const difference = (a[index] ?? 0) - (b[index] ?? 0);
65
+ if (difference !== 0) return difference;
66
+ }
67
+ return 0;
68
+ }
69
+
70
+ export function validateMiseVersion(value: string, runner: "local" | "isolated"): string {
71
+ const parsed = parseVersion(value);
72
+ const pinned = parseVersion(PINNED_MISE_VERSION);
73
+ if (!parsed || !pinned) {
74
+ throw new DevelopmentToolPreparationError(
75
+ `Could not determine mise version from '${value.trim()}'`,
76
+ "mise_unsupported",
77
+ );
78
+ }
79
+ if (
80
+ (runner === "isolated" && compareVersion(parsed, pinned) !== 0) ||
81
+ (runner === "local" && (parsed[0] !== pinned[0] || compareVersion(parsed, pinned) < 0))
82
+ ) {
83
+ throw new DevelopmentToolPreparationError(
84
+ `mise ${parsed.join(".")} is unsupported; expected ${runner === "isolated" ? PINNED_MISE_VERSION : `${PINNED_MISE_VERSION} or newer before ${pinned[0] + 1}.0.0`}`,
85
+ "mise_unsupported",
86
+ );
87
+ }
88
+ return parsed.join(".");
89
+ }
90
+
91
+ const SAFE_ENV_KEYS = new Set([
92
+ "HOME",
93
+ "USER",
94
+ "LOGNAME",
95
+ "SHELL",
96
+ "PATH",
97
+ "TMPDIR",
98
+ "TMP",
99
+ "TEMP",
100
+ "LANG",
101
+ "TERM",
102
+ "HTTP_PROXY",
103
+ "HTTPS_PROXY",
104
+ "ALL_PROXY",
105
+ "NO_PROXY",
106
+ "http_proxy",
107
+ "https_proxy",
108
+ "all_proxy",
109
+ "no_proxy",
110
+ "SSL_CERT_FILE",
111
+ "SSL_CERT_DIR",
112
+ "NODE_EXTRA_CA_CERTS",
113
+ "XDG_CONFIG_HOME",
114
+ "XDG_DATA_HOME",
115
+ "XDG_CACHE_HOME",
116
+ "XDG_STATE_HOME",
117
+ ]);
118
+
119
+ /** Keep OS, network, and mise discovery settings while excluding application credentials. */
120
+ export function buildMiseSubprocessEnvironment(
121
+ base: NodeJS.ProcessEnv,
122
+ config: DevelopmentToolsStartConfig,
123
+ ): NodeJS.ProcessEnv {
124
+ const env: NodeJS.ProcessEnv = {};
125
+ for (const [key, value] of Object.entries(base)) {
126
+ const safeMiseSetting =
127
+ config.runner === "local" &&
128
+ key.startsWith("MISE_") &&
129
+ !/(?:TOKEN|PASSWORD|SECRET|AUTH|CREDENTIAL|API_KEY)/i.test(key);
130
+ if (
131
+ value !== undefined &&
132
+ (SAFE_ENV_KEYS.has(key) || key.startsWith("LC_") || safeMiseSetting)
133
+ ) {
134
+ env[key] = value;
135
+ }
136
+ }
137
+ if (config.runner === "isolated") {
138
+ const miseRoot = path.join(config.processStorageRoot, "tooling", "mise");
139
+ env.MISE_DATA_DIR = miseRoot;
140
+ env.MISE_INSTALLS_DIR = path.join(miseRoot, "installs");
141
+ env.MISE_CACHE_DIR = path.join(miseRoot, "cache");
142
+ env.MISE_STATE_DIR = path.join(miseRoot, "state");
143
+ }
144
+ return env;
145
+ }
146
+
147
+ function localShimDirectory(env: NodeJS.ProcessEnv): string {
148
+ if (env.MISE_DATA_DIR) return path.join(env.MISE_DATA_DIR, "shims");
149
+ if (env.XDG_DATA_HOME) return path.join(env.XDG_DATA_HOME, "mise", "shims");
150
+ return path.join(env.HOME ?? "", ".local", "share", "mise", "shims");
151
+ }
152
+
153
+ function emitDiagnosticTrace(trace: ((text: string) => void) | undefined, value: string): void {
154
+ if (!trace) return;
155
+ for (let offset = 0; offset < value.length; offset += TRACE_CHUNK_LENGTH) {
156
+ trace(value.slice(offset, offset + TRACE_CHUNK_LENGTH));
157
+ }
158
+ }
159
+
160
+ function appendBounded(current: string, chunk: Buffer, limit: number): string {
161
+ const combined = current + chunk.toString("utf8");
162
+ return Buffer.byteLength(combined) <= limit
163
+ ? combined
164
+ : Buffer.from(combined).subarray(-limit).toString("utf8");
165
+ }
166
+
167
+ async function runCommand(input: {
168
+ command: string;
169
+ args: string[];
170
+ cwd: string;
171
+ env: NodeJS.ProcessEnv;
172
+ timeoutMs: number;
173
+ signal?: AbortSignal;
174
+ outputLimit?: number;
175
+ onDiagnosticTrace?(text: string): void;
176
+ }): Promise<{ stdout: string; stderr: string }> {
177
+ if (input.signal?.aborted) {
178
+ throw new DevelopmentToolPreparationError("mise preparation was cancelled", "cancelled");
179
+ }
180
+
181
+ const child = execa(input.command, input.args, {
182
+ cwd: input.cwd,
183
+ env: input.env,
184
+ extendEnv: false,
185
+ stdin: "ignore",
186
+ detached: true,
187
+ timeout: input.timeoutMs,
188
+ cancelSignal: input.signal,
189
+ forceKillAfterDelay: 2_000,
190
+ reject: false,
191
+ stripFinalNewline: false,
192
+ });
193
+ let stdout = "";
194
+ let stderr = "";
195
+ const outputLimit = input.outputLimit ?? OUTPUT_LIMIT_BYTES;
196
+ const appendOutput = (target: "stdout" | "stderr", chunk: Buffer | string) => {
197
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
198
+ const text = buffer.toString("utf8");
199
+ emitDiagnosticTrace(input.onDiagnosticTrace, text);
200
+ if (target === "stdout") stdout = appendBounded(stdout, buffer, outputLimit);
201
+ else stderr = appendBounded(stderr, buffer, outputLimit);
202
+ };
203
+ child.stdout?.on("data", (chunk: Buffer | string) => appendOutput("stdout", chunk));
204
+ child.stderr?.on("data", (chunk: Buffer | string) => appendOutput("stderr", chunk));
205
+
206
+ // Wait for process-group termination even when mise itself exits before its children.
207
+ let groupTermination: Promise<void> | null = null;
208
+ const killGroup = () => {
209
+ if (!child.pid || groupTermination) return;
210
+ const pid = child.pid;
211
+ try {
212
+ process.kill(-pid, "SIGTERM");
213
+ } catch {
214
+ child.kill("SIGTERM");
215
+ }
216
+ groupTermination = new Promise<void>((resolve) => {
217
+ setTimeout(() => {
218
+ try {
219
+ process.kill(-pid, "SIGKILL");
220
+ } catch {
221
+ /* The process group has already exited. */
222
+ }
223
+ resolve();
224
+ }, 2_000);
225
+ });
226
+ };
227
+ const groupTimeout = setTimeout(killGroup, input.timeoutMs);
228
+ input.signal?.addEventListener("abort", killGroup, { once: true });
229
+ try {
230
+ const result = await child;
231
+ const diagnostics = `${stdout}\n${stderr}`.trim();
232
+ if (input.signal?.aborted || result.isCanceled) {
233
+ throw new DevelopmentToolPreparationError(
234
+ "mise preparation was cancelled",
235
+ "cancelled",
236
+ diagnostics,
237
+ );
238
+ }
239
+ if (result.timedOut) {
240
+ throw new DevelopmentToolPreparationError(
241
+ `mise exceeded its ${input.timeoutMs}ms deadline`,
242
+ "timeout",
243
+ diagnostics,
244
+ );
245
+ }
246
+ if (result.code === "ENOENT") {
247
+ throw new DevelopmentToolPreparationError(
248
+ `mise command '${input.command}' was not found`,
249
+ "mise_missing",
250
+ diagnostics,
251
+ );
252
+ }
253
+ if (result.failed) {
254
+ throw new Error(`${result.shortMessage}\n${diagnostics}`);
255
+ }
256
+ return { stdout, stderr };
257
+ } finally {
258
+ clearTimeout(groupTimeout);
259
+ input.signal?.removeEventListener("abort", killGroup);
260
+ await groupTermination;
261
+ }
262
+ }
263
+
264
+ function toolPair(
265
+ candidate: unknown,
266
+ fallbackName?: string,
267
+ ): { name: string; version: string } | null {
268
+ if (!candidate || typeof candidate !== "object") return null;
269
+ const item = candidate as Record<string, unknown>;
270
+ const name = [item.tool, item.name, item.plugin, fallbackName].find(
271
+ (value): value is string => typeof value === "string" && value.trim() !== "",
272
+ );
273
+ const version = [item.version, item.installed_version, item.requested_version].find(
274
+ (value): value is string => typeof value === "string" && value.trim() !== "",
275
+ );
276
+ return name && version ? { name, version } : null;
277
+ }
278
+
279
+ /** Normalize the mise JSON adapter boundary without retaining backend-specific fields. */
280
+ export function normalizeMiseEvidence(value: unknown): Array<{ name: string; version: string }> {
281
+ const tools: Array<{ name: string; version: string }> = [];
282
+ if (Array.isArray(value)) {
283
+ for (const item of value) {
284
+ const pair = toolPair(item);
285
+ if (pair) tools.push(pair);
286
+ }
287
+ } else if (value && typeof value === "object") {
288
+ for (const [name, item] of Object.entries(value as Record<string, unknown>)) {
289
+ for (const candidate of Array.isArray(item) ? item : [item]) {
290
+ const pair =
291
+ typeof candidate === "string" ? { name, version: candidate } : toolPair(candidate, name);
292
+ if (pair) tools.push(pair);
293
+ }
294
+ }
295
+ }
296
+ return [...new Map(tools.map((tool) => [`${tool.name}\0${tool.version}`, tool])).values()].sort(
297
+ (a, b) => a.name.localeCompare(b.name) || a.version.localeCompare(b.version),
298
+ );
299
+ }
300
+
301
+ function availableSpace(root: string): string | null {
302
+ try {
303
+ const stats = statfsSync(root);
304
+ return `${Number(stats.bavail) * Number(stats.bsize)} bytes available`;
305
+ } catch {
306
+ return null;
307
+ }
308
+ }
309
+
310
+ function translateCommandError(
311
+ error: unknown,
312
+ input: {
313
+ operation: "install" | "verification";
314
+ failureMessage: string;
315
+ repositoryKey: string;
316
+ timeoutMs: number;
317
+ root: string;
318
+ },
319
+ ): DevelopmentToolPreparationError {
320
+ if (error instanceof DevelopmentToolPreparationError) {
321
+ if (error.code !== "timeout") return error;
322
+ return new DevelopmentToolPreparationError(
323
+ `mise ${input.operation} timed out for repository '${input.repositoryKey}' after ${input.timeoutMs}ms`,
324
+ "timeout",
325
+ error.diagnostics,
326
+ );
327
+ }
328
+ const space = input.operation === "install" ? availableSpace(input.root) : null;
329
+ return new DevelopmentToolPreparationError(
330
+ `${input.failureMessage} '${input.repositoryKey}'${space ? ` (${space})` : ""}`,
331
+ input.operation === "install" ? "install_failed" : "verification_failed",
332
+ error instanceof Error ? error.message : String(error),
333
+ );
334
+ }
335
+
336
+ export class MiseDevelopmentToolEnvironment implements DevelopmentToolEnvironment {
337
+ constructor(private readonly baseEnv: NodeJS.ProcessEnv = process.env) {}
338
+
339
+ async prepare(input: ToolPreparationInput): Promise<PreparedToolEnvironment> {
340
+ const env = buildMiseSubprocessEnvironment(this.baseEnv, input.config);
341
+ const versionResult = await runCommand({
342
+ command: input.config.miseCommand,
343
+ args: ["--version"],
344
+ cwd: input.config.processStorageRoot,
345
+ env,
346
+ timeoutMs: Math.min(input.config.installTimeoutMs, 30_000),
347
+ signal: input.signal,
348
+ onDiagnosticTrace: input.onDiagnosticTrace,
349
+ });
350
+ const miseVersion = validateMiseVersion(
351
+ versionResult.stdout || versionResult.stderr,
352
+ input.config.runner,
353
+ );
354
+ if (input.config.runner === "isolated") {
355
+ await Promise.all(
356
+ [env.MISE_DATA_DIR, env.MISE_INSTALLS_DIR, env.MISE_CACHE_DIR, env.MISE_STATE_DIR]
357
+ .filter((value): value is string => Boolean(value))
358
+ .map((directory) => mkdir(directory, { recursive: true })),
359
+ );
360
+ }
361
+ const shimDirectory =
362
+ input.config.runner === "isolated"
363
+ ? path.join(env.MISE_DATA_DIR as string, "shims")
364
+ : localShimDirectory({ ...this.baseEnv, ...env });
365
+ env.PATH = [shimDirectory, env.PATH].filter(Boolean).join(path.delimiter);
366
+ const repositories: PreparedToolEnvironment["repositories"] = [];
367
+ const warnings: string[] = [];
368
+ for (const repository of [...input.repositories].sort((a, b) =>
369
+ a.repositoryKey.localeCompare(b.repositoryKey),
370
+ )) {
371
+ const repositoryStartedAt = Date.now();
372
+ input.onProgress?.(repository.repositoryKey, "installing");
373
+ try {
374
+ const installed = await runCommand({
375
+ command: input.config.miseCommand,
376
+ args: ["install"],
377
+ cwd: repository.workingDirectory,
378
+ env,
379
+ timeoutMs: input.config.installTimeoutMs,
380
+ signal: input.signal,
381
+ onDiagnosticTrace: input.onDiagnosticTrace,
382
+ });
383
+ if (installed.stderr.trim()) {
384
+ warnings.push(`${repository.repositoryKey}: ${installed.stderr.trim()}`);
385
+ }
386
+ } catch (error) {
387
+ throw translateCommandError(error, {
388
+ operation: "install",
389
+ failureMessage: "mise install failed for repository",
390
+ repositoryKey: repository.repositoryKey,
391
+ timeoutMs: input.config.installTimeoutMs,
392
+ root: input.config.processStorageRoot,
393
+ });
394
+ }
395
+ input.onProgress?.(repository.repositoryKey, "verifying");
396
+ let current: { stdout: string; stderr: string };
397
+ try {
398
+ current = await runCommand({
399
+ command: input.config.miseCommand,
400
+ args: ["ls", "--current", "--json"],
401
+ cwd: repository.workingDirectory,
402
+ env,
403
+ timeoutMs: Math.max(
404
+ 1,
405
+ input.config.installTimeoutMs - (Date.now() - repositoryStartedAt),
406
+ ),
407
+ signal: input.signal,
408
+ outputLimit: JSON_LIMIT_BYTES,
409
+ onDiagnosticTrace: input.onDiagnosticTrace,
410
+ });
411
+ } catch (error) {
412
+ throw translateCommandError(error, {
413
+ operation: "verification",
414
+ failureMessage: "mise could not verify repository",
415
+ repositoryKey: repository.repositoryKey,
416
+ timeoutMs: input.config.installTimeoutMs,
417
+ root: input.config.processStorageRoot,
418
+ });
419
+ }
420
+ let parsed: unknown;
421
+ try {
422
+ parsed = JSON.parse(current.stdout);
423
+ } catch {
424
+ throw new DevelopmentToolPreparationError(
425
+ `mise returned invalid current-tool evidence for repository '${repository.repositoryKey}'`,
426
+ "verification_failed",
427
+ );
428
+ }
429
+ if (current.stderr.trim()) {
430
+ warnings.push(`${repository.repositoryKey}: ${current.stderr.trim()}`);
431
+ }
432
+ repositories.push({ ...repository, tools: normalizeMiseEvidence(parsed) });
433
+ }
434
+ const commandEnvironment = {
435
+ ...this.baseEnv,
436
+ ...Object.fromEntries(Object.entries(env).filter(([key]) => key.startsWith("MISE_"))),
437
+ PATH: [shimDirectory, this.baseEnv.PATH].filter(Boolean).join(path.delimiter),
438
+ };
439
+ const evidenceDir = path.join(input.config.processStorageRoot, "tooling", "mise-preparation");
440
+ await mkdir(evidenceDir, { recursive: true });
441
+ const evidence = {
442
+ schemaVersion: 1,
443
+ preparedAt: new Date().toISOString(),
444
+ miseVersion,
445
+ repositories,
446
+ };
447
+ const temporary = path.join(evidenceDir, `.latest-${process.pid}.json`);
448
+ await writeFile(temporary, `${JSON.stringify(evidence, null, 2)}\n`, { mode: 0o600 });
449
+ await rename(temporary, path.join(evidenceDir, "latest.json"));
450
+ return { miseVersion, commandEnvironment, repositories, warnings };
451
+ }
452
+ }
@@ -1,4 +1,4 @@
1
- import type { WorkerErrorClass } from "@leitwerk-dev/domain";
1
+ import type { TurnProgressReport, WorkerErrorClass } from "@leitwerk-dev/domain";
2
2
 
3
3
  export type WorkerDiagnosticLevel = "debug" | "info" | "warn" | "error";
4
4
 
@@ -16,6 +16,8 @@ export interface WorkerDiagnosticPayload {
16
16
 
17
17
  export type WorkerOperationEmission =
18
18
  | { kind: "trace" | "error"; payload: WorkerDiagnosticPayload }
19
+ | { kind: "progress"; turnRecordId: string; report: TurnProgressReport }
20
+ | { kind: "prepared"; turnRecordId: string; data: unknown }
19
21
  | { kind: "session_tainted"; reason: string };
20
22
 
21
23
  export type WorkerOperationEmitter = (emission: WorkerOperationEmission) => void;
@@ -0,0 +1,65 @@
1
+ import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
2
+ import {
3
+ dockerRegistryCredentialSchema,
4
+ type WorkerDockerRegistryCredential,
5
+ } from "@leitwerk-dev/worker-protocol";
6
+ import { is } from "valibot";
7
+
8
+ /** Credentials live outside every process volume and session export root. */
9
+ export class DockerRegistryCredentials {
10
+ #directory: string | undefined;
11
+ #previousConfig: string | undefined;
12
+ #onExit = () => this.dispose();
13
+
14
+ install(credentials: readonly WorkerDockerRegistryCredential[], dockerEnabled: boolean): void {
15
+ this.dispose();
16
+ if (!dockerEnabled) {
17
+ if (credentials.length)
18
+ throw new Error("Docker credentials require a Docker-enabled process");
19
+ return;
20
+ }
21
+ const auths: Record<string, { auth: string }> = Object.create(null);
22
+ for (const credential of credentials) {
23
+ if (!is(dockerRegistryCredentialSchema, credential))
24
+ throw new Error("Invalid Docker registry credentials");
25
+ if (Object.hasOwn(auths, credential.registry))
26
+ throw new Error("Duplicate Docker registry credentials");
27
+ auths[credential.registry] = {
28
+ auth: Buffer.from(`${credential.username}:${credential.password}`).toString("base64"),
29
+ };
30
+ }
31
+ try {
32
+ // Do not honor TMPDIR: it can point into retained process storage.
33
+ this.#directory = mkdtempSync("/tmp/leitwerk-docker-auth-");
34
+ chmodSync(this.#directory, 0o700);
35
+ mkdirSync(`${this.#directory}/auth`, { mode: 0o700 });
36
+ writeFileSync(`${this.#directory}/auth/config.json`, JSON.stringify({ auths }), {
37
+ mode: 0o600,
38
+ flag: "wx",
39
+ });
40
+ this.#previousConfig = process.env.DOCKER_CONFIG;
41
+ process.env.DOCKER_CONFIG = `${this.#directory}/auth`;
42
+ if (!process.env.BUILDX_CONFIG) {
43
+ mkdirSync(`${this.#directory}/buildx`, { mode: 0o700 });
44
+ process.env.BUILDX_CONFIG = `${this.#directory}/buildx`;
45
+ }
46
+ process.once("exit", this.#onExit);
47
+ } catch {
48
+ this.dispose();
49
+ throw new Error("Cannot materialize private Docker credentials");
50
+ }
51
+ }
52
+
53
+ dispose(): void {
54
+ process.off("exit", this.#onExit);
55
+ if (!this.#directory) return;
56
+ if (process.env.BUILDX_CONFIG === `${this.#directory}/buildx`) delete process.env.BUILDX_CONFIG;
57
+ if (process.env.DOCKER_CONFIG === `${this.#directory}/auth`) {
58
+ if (this.#previousConfig === undefined) delete process.env.DOCKER_CONFIG;
59
+ else process.env.DOCKER_CONFIG = this.#previousConfig;
60
+ }
61
+ rmSync(this.#directory, { recursive: true, force: true });
62
+ this.#directory = undefined;
63
+ this.#previousConfig = undefined;
64
+ }
65
+ }
@@ -1,5 +1,6 @@
1
1
  import { existsSync, readFileSync } from "node:fs";
2
2
  import path from "node:path";
3
+ import { isUnknownRecord as isRecord } from "@leitwerk-dev/domain";
3
4
  import {
4
5
  buildExtensionCatalog,
5
6
  createCatalogWorkerDefinitionResolver,
@@ -24,6 +25,7 @@ import {
24
25
  WORKER_IPC_SERVER_URL_ENV,
25
26
  WORKER_SNAPSHOT_TOKEN_ENV,
26
27
  } from "@leitwerk-dev/worker-protocol";
28
+ import { MiseDevelopmentToolEnvironment } from "./development-tool-environment.js";
27
29
  import {
28
30
  entriesExistWithinAllowedRoots,
29
31
  parseExtensionAllowedRoots,
@@ -48,10 +50,6 @@ import type { RunRootGitOps } from "./workspace/run-root.js";
48
50
 
49
51
  let runtimeCatalogPromise: Promise<ExtensionCatalog> | null = null;
50
52
 
51
- function isRecord(value: unknown): value is Record<string, unknown> {
52
- return typeof value === "object" && value !== null && !Array.isArray(value);
53
- }
54
-
55
53
  function listWorkspacePatterns(workspaces: unknown): string[] {
56
54
  if (Array.isArray(workspaces)) {
57
55
  return workspaces.filter((value): value is string => typeof value === "string");
@@ -124,6 +122,7 @@ function getRuntimeCatalog(): Promise<ExtensionCatalog> {
124
122
  export interface WorkerEntryRuntimeOverrides extends Partial<WorkerRuntimeConfig> {
125
123
  piFactory?: PiTreeHandleFactory;
126
124
  gitOps?: RunRootGitOps;
125
+ developmentTools?: WorkerRuntimeAdapters["developmentTools"];
127
126
  transport?: WorkerIpc;
128
127
  sessionSnapshots?: WorkerSessionSnapshotExchange;
129
128
  resultImageTools?: WorkerRuntimeAdapters["resultImageTools"];
@@ -225,6 +224,8 @@ export function createWorkerEntryRuntime(
225
224
  resultImageTools,
226
225
  piFactory: overrides.piFactory ?? resolveDefaultPiFactory(),
227
226
  gitOps: overrides.gitOps ?? new NodeRunRootGitOps(),
227
+ developmentTools:
228
+ overrides.developmentTools ?? new MiseDevelopmentToolEnvironment(runtimeEnv),
228
229
  resolveWorkerProcess,
229
230
  extensionEvents: workerExtensionApi.events,
230
231
  stderr: overrides.stderr,
package/src/index.ts CHANGED
@@ -1,3 +1,14 @@
1
+ export {
2
+ buildMiseSubprocessEnvironment,
3
+ type DevelopmentToolEnvironment,
4
+ DevelopmentToolPreparationError,
5
+ MiseDevelopmentToolEnvironment,
6
+ normalizeMiseEvidence,
7
+ PINNED_MISE_VERSION,
8
+ type PreparedToolEnvironment,
9
+ type ToolPreparationInput,
10
+ validateMiseVersion,
11
+ } from "./development-tool-environment.js";
1
12
  export { createWorkerEntryRuntime } from "./entry-runtime.js";
2
13
  export {
3
14
  type DeclaredCredentialFile,
@@ -1,4 +1,4 @@
1
- import type { ProcessInputTarget } from "@leitwerk-dev/domain";
1
+ import type { InputDelivery } from "@leitwerk-dev/worker-protocol";
2
2
  import type { PiTreeHandle } from "./pi-adapter.js";
3
3
 
4
4
  export type InputDeliveryMode = "prompt" | "steer";
@@ -9,47 +9,25 @@ export interface DeliveredInput {
9
9
  deliveryMode: InputDeliveryMode;
10
10
  }
11
11
 
12
- export interface InputItem {
13
- inputId: string;
14
- sequence: number;
15
- source: string;
16
- kind: string;
17
- target: ProcessInputTarget | null;
18
- bodyMarkdown: string;
19
- }
12
+ export interface InputItem extends Omit<InputDelivery, "receivedAt"> {}
20
13
 
21
14
  export type TargetedInputItem = InputItem & { target: NonNullable<InputItem["target"]> };
22
15
 
23
- export function filterInputsAfterConsumedSequence(
24
- inputs: readonly InputItem[],
25
- lastSequenceConsumed: number,
26
- ): InputItem[] {
27
- return inputs.filter((input) => input.sequence > lastSequenceConsumed);
28
- }
16
+ type InputDeliverySession = Pick<PiTreeHandle, "prompt" | "steer">;
29
17
 
30
18
  export function classifyDeliveryMode(
31
19
  input: InputItem,
32
20
  sessionHasActiveTurn: boolean,
33
21
  ): InputDeliveryMode {
34
- if (input.kind === "system_event") {
35
- return "steer";
36
- }
37
- if (sessionHasActiveTurn) {
38
- return "steer";
39
- }
40
- return "prompt";
22
+ return input.kind === "system_event" || sessionHasActiveTurn ? "steer" : "prompt";
41
23
  }
42
24
 
43
25
  export async function deliverInput(
44
- session: PiTreeHandle,
26
+ session: InputDeliverySession,
45
27
  input: InputItem,
46
28
  mode: InputDeliveryMode,
47
29
  ): Promise<DeliveredInput> {
48
- if (mode === "prompt") {
49
- await session.prompt(input.bodyMarkdown);
50
- } else {
51
- await session.steer(input.bodyMarkdown);
52
- }
30
+ await session[mode](input.bodyMarkdown);
53
31
  return {
54
32
  inputId: input.inputId,
55
33
  sequence: input.sequence,
@@ -58,7 +36,7 @@ export async function deliverInput(
58
36
  }
59
37
 
60
38
  export async function deliverBatch(
61
- session: PiTreeHandle,
39
+ session: InputDeliverySession,
62
40
  inputs: InputItem[],
63
41
  hasActiveTurn: boolean,
64
42
  ): Promise<DeliveredInput[]> {