@leitwerk-dev/worker 0.2.0 → 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 (54) hide show
  1. package/dist/{chunk-Y7S2MZD3.js → chunk-2LLFMCR6.js} +628 -605
  2. package/dist/chunk-2LLFMCR6.js.map +1 -0
  3. package/dist/development-tool-environment.d.ts +39 -3
  4. package/dist/development-tool-environment.d.ts.map +1 -1
  5. package/dist/entry-runtime.d.ts +18 -0
  6. package/dist/entry-runtime.d.ts.map +1 -1
  7. package/dist/index.d.ts +3 -6
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +3 -37
  10. package/dist/input-consumer.d.ts +1 -0
  11. package/dist/input-consumer.d.ts.map +1 -1
  12. package/dist/ipc.d.ts +9 -0
  13. package/dist/ipc.d.ts.map +1 -1
  14. package/dist/managed-pi-agent-dir.d.ts +8 -1
  15. package/dist/managed-pi-agent-dir.d.ts.map +1 -1
  16. package/dist/managed-pi-bootstrap.d.ts +1 -0
  17. package/dist/managed-pi-bootstrap.d.ts.map +1 -1
  18. package/dist/pi-adapter.d.ts +87 -1
  19. package/dist/pi-adapter.d.ts.map +1 -1
  20. package/dist/pi-resource-bundle.d.ts +6 -1
  21. package/dist/pi-resource-bundle.d.ts.map +1 -1
  22. package/dist/prompt-guards.d.ts +6 -0
  23. package/dist/prompt-guards.d.ts.map +1 -1
  24. package/dist/runtime/adapters.d.ts +36 -0
  25. package/dist/runtime/adapters.d.ts.map +1 -1
  26. package/dist/runtime/bootstrap-session.d.ts +1 -0
  27. package/dist/runtime/bootstrap-session.d.ts.map +1 -1
  28. package/dist/runtime/bootstrap.d.ts +24 -0
  29. package/dist/runtime/bootstrap.d.ts.map +1 -1
  30. package/dist/runtime/index.d.ts +4 -1
  31. package/dist/runtime/index.d.ts.map +1 -1
  32. package/dist/session-snapshot-exchange.d.ts +10 -0
  33. package/dist/session-snapshot-exchange.d.ts.map +1 -1
  34. package/dist/worker-entry.js +1 -1
  35. package/dist/workspace/run-root.d.ts +12 -0
  36. package/dist/workspace/run-root.d.ts.map +1 -1
  37. package/package.json +7 -7
  38. package/src/development-tool-environment.ts +42 -4
  39. package/src/entry-runtime.ts +24 -1
  40. package/src/index.ts +1 -50
  41. package/src/input-consumer.ts +1 -0
  42. package/src/ipc.ts +14 -1
  43. package/src/managed-pi-agent-dir.ts +8 -1
  44. package/src/managed-pi-bootstrap.ts +1 -0
  45. package/src/pi-adapter.ts +106 -6
  46. package/src/pi-resource-bundle.ts +10 -2
  47. package/src/prompt-guards.ts +6 -0
  48. package/src/runtime/adapters.ts +44 -4
  49. package/src/runtime/bootstrap-session.ts +1 -0
  50. package/src/runtime/bootstrap.ts +27 -1
  51. package/src/runtime/index.ts +4 -1
  52. package/src/session-snapshot-exchange.ts +23 -4
  53. package/src/workspace/run-root.ts +12 -0
  54. package/dist/chunk-Y7S2MZD3.js.map +0 -1
@@ -1,367 +1,6 @@
1
- // src/development-tool-environment.ts
2
- import { statfsSync } from "fs";
3
- import { mkdir, rename, writeFile } from "fs/promises";
4
- import path from "path";
5
- import { execa } from "execa";
6
- var PINNED_MISE_VERSION = "2026.8.14";
7
- var OUTPUT_LIMIT_BYTES = 64 * 1024;
8
- var JSON_LIMIT_BYTES = 1024 * 1024;
9
- var TRACE_CHUNK_LENGTH = 16 * 1024;
10
- var DevelopmentToolPreparationError = class extends Error {
11
- constructor(message, code, diagnostics = "") {
12
- super(message);
13
- this.code = code;
14
- this.diagnostics = diagnostics;
15
- this.name = "DevelopmentToolPreparationError";
16
- }
17
- code;
18
- diagnostics;
19
- };
20
- function parseVersion(value) {
21
- const match = /(?:^|\s)(\d{4})\.(\d+)\.(\d+)(?:\s|$)/.exec(value);
22
- return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
23
- }
24
- function compareVersion(a, b) {
25
- for (let index = 0; index < 3; index++) {
26
- const difference = (a[index] ?? 0) - (b[index] ?? 0);
27
- if (difference !== 0) return difference;
28
- }
29
- return 0;
30
- }
31
- function validateMiseVersion(value, runner) {
32
- const parsed = parseVersion(value);
33
- const pinned = parseVersion(PINNED_MISE_VERSION);
34
- if (!parsed || !pinned) {
35
- throw new DevelopmentToolPreparationError(
36
- `Could not determine mise version from '${value.trim()}'`,
37
- "mise_unsupported"
38
- );
39
- }
40
- if (runner === "isolated" && compareVersion(parsed, pinned) !== 0 || runner === "local" && (parsed[0] !== pinned[0] || compareVersion(parsed, pinned) < 0)) {
41
- throw new DevelopmentToolPreparationError(
42
- `mise ${parsed.join(".")} is unsupported; expected ${runner === "isolated" ? PINNED_MISE_VERSION : `${PINNED_MISE_VERSION} or newer before ${pinned[0] + 1}.0.0`}`,
43
- "mise_unsupported"
44
- );
45
- }
46
- return parsed.join(".");
47
- }
48
- var SAFE_ENV_KEYS = /* @__PURE__ */ new Set([
49
- "HOME",
50
- "USER",
51
- "LOGNAME",
52
- "SHELL",
53
- "PATH",
54
- "TMPDIR",
55
- "TMP",
56
- "TEMP",
57
- "LANG",
58
- "TERM",
59
- "HTTP_PROXY",
60
- "HTTPS_PROXY",
61
- "ALL_PROXY",
62
- "NO_PROXY",
63
- "http_proxy",
64
- "https_proxy",
65
- "all_proxy",
66
- "no_proxy",
67
- "SSL_CERT_FILE",
68
- "SSL_CERT_DIR",
69
- "NODE_EXTRA_CA_CERTS",
70
- "XDG_CONFIG_HOME",
71
- "XDG_DATA_HOME",
72
- "XDG_CACHE_HOME",
73
- "XDG_STATE_HOME"
74
- ]);
75
- function buildMiseSubprocessEnvironment(base, config) {
76
- const env = {};
77
- for (const [key, value] of Object.entries(base)) {
78
- const safeMiseSetting = config.runner === "local" && key.startsWith("MISE_") && !/(?:TOKEN|PASSWORD|SECRET|AUTH|CREDENTIAL|API_KEY)/i.test(key);
79
- if (value !== void 0 && (SAFE_ENV_KEYS.has(key) || key.startsWith("LC_") || safeMiseSetting)) {
80
- env[key] = value;
81
- }
82
- }
83
- if (config.runner === "isolated") {
84
- const miseRoot = path.join(config.processStorageRoot, "tooling", "mise");
85
- env.MISE_DATA_DIR = miseRoot;
86
- env.MISE_INSTALLS_DIR = path.join(miseRoot, "installs");
87
- env.MISE_CACHE_DIR = path.join(miseRoot, "cache");
88
- env.MISE_STATE_DIR = path.join(miseRoot, "state");
89
- }
90
- return env;
91
- }
92
- function localShimDirectory(env) {
93
- if (env.MISE_DATA_DIR) return path.join(env.MISE_DATA_DIR, "shims");
94
- if (env.XDG_DATA_HOME) return path.join(env.XDG_DATA_HOME, "mise", "shims");
95
- return path.join(env.HOME ?? "", ".local", "share", "mise", "shims");
96
- }
97
- function emitDiagnosticTrace(trace, value) {
98
- if (!trace) return;
99
- for (let offset = 0; offset < value.length; offset += TRACE_CHUNK_LENGTH) {
100
- trace(value.slice(offset, offset + TRACE_CHUNK_LENGTH));
101
- }
102
- }
103
- function appendBounded(current, chunk, limit) {
104
- const combined = current + chunk.toString("utf8");
105
- return Buffer.byteLength(combined) <= limit ? combined : Buffer.from(combined).subarray(-limit).toString("utf8");
106
- }
107
- async function runCommand(input) {
108
- if (input.signal?.aborted) {
109
- throw new DevelopmentToolPreparationError("mise preparation was cancelled", "cancelled");
110
- }
111
- const child = execa(input.command, input.args, {
112
- cwd: input.cwd,
113
- env: input.env,
114
- extendEnv: false,
115
- stdin: "ignore",
116
- detached: true,
117
- timeout: input.timeoutMs,
118
- cancelSignal: input.signal,
119
- forceKillAfterDelay: 2e3,
120
- reject: false,
121
- stripFinalNewline: false
122
- });
123
- let stdout = "";
124
- let stderr = "";
125
- const outputLimit = input.outputLimit ?? OUTPUT_LIMIT_BYTES;
126
- const appendOutput = (target, chunk) => {
127
- const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
128
- const text = buffer.toString("utf8");
129
- emitDiagnosticTrace(input.onDiagnosticTrace, text);
130
- if (target === "stdout") stdout = appendBounded(stdout, buffer, outputLimit);
131
- else stderr = appendBounded(stderr, buffer, outputLimit);
132
- };
133
- child.stdout?.on("data", (chunk) => appendOutput("stdout", chunk));
134
- child.stderr?.on("data", (chunk) => appendOutput("stderr", chunk));
135
- let groupTermination = null;
136
- const killGroup = () => {
137
- if (!child.pid || groupTermination) return;
138
- const pid = child.pid;
139
- try {
140
- process.kill(-pid, "SIGTERM");
141
- } catch {
142
- child.kill("SIGTERM");
143
- }
144
- groupTermination = new Promise((resolve) => {
145
- setTimeout(() => {
146
- try {
147
- process.kill(-pid, "SIGKILL");
148
- } catch {
149
- }
150
- resolve();
151
- }, 2e3);
152
- });
153
- };
154
- const groupTimeout = setTimeout(killGroup, input.timeoutMs);
155
- input.signal?.addEventListener("abort", killGroup, { once: true });
156
- try {
157
- const result = await child;
158
- const diagnostics = `${stdout}
159
- ${stderr}`.trim();
160
- if (input.signal?.aborted || result.isCanceled) {
161
- throw new DevelopmentToolPreparationError(
162
- "mise preparation was cancelled",
163
- "cancelled",
164
- diagnostics
165
- );
166
- }
167
- if (result.timedOut) {
168
- throw new DevelopmentToolPreparationError(
169
- `mise exceeded its ${input.timeoutMs}ms deadline`,
170
- "timeout",
171
- diagnostics
172
- );
173
- }
174
- if (result.code === "ENOENT") {
175
- throw new DevelopmentToolPreparationError(
176
- `mise command '${input.command}' was not found`,
177
- "mise_missing",
178
- diagnostics
179
- );
180
- }
181
- if (result.failed) {
182
- throw new Error(`${result.shortMessage}
183
- ${diagnostics}`);
184
- }
185
- return { stdout, stderr };
186
- } finally {
187
- clearTimeout(groupTimeout);
188
- input.signal?.removeEventListener("abort", killGroup);
189
- await groupTermination;
190
- }
191
- }
192
- function toolPair(candidate, fallbackName) {
193
- if (!candidate || typeof candidate !== "object") return null;
194
- const item = candidate;
195
- const name = [item.tool, item.name, item.plugin, fallbackName].find(
196
- (value) => typeof value === "string" && value.trim() !== ""
197
- );
198
- const version = [item.version, item.installed_version, item.requested_version].find(
199
- (value) => typeof value === "string" && value.trim() !== ""
200
- );
201
- return name && version ? { name, version } : null;
202
- }
203
- function normalizeMiseEvidence(value) {
204
- const tools = [];
205
- if (Array.isArray(value)) {
206
- for (const item of value) {
207
- const pair = toolPair(item);
208
- if (pair) tools.push(pair);
209
- }
210
- } else if (value && typeof value === "object") {
211
- for (const [name, item] of Object.entries(value)) {
212
- for (const candidate of Array.isArray(item) ? item : [item]) {
213
- const pair = typeof candidate === "string" ? { name, version: candidate } : toolPair(candidate, name);
214
- if (pair) tools.push(pair);
215
- }
216
- }
217
- }
218
- return [...new Map(tools.map((tool) => [`${tool.name}\0${tool.version}`, tool])).values()].sort(
219
- (a, b) => a.name.localeCompare(b.name) || a.version.localeCompare(b.version)
220
- );
221
- }
222
- function availableSpace(root) {
223
- try {
224
- const stats = statfsSync(root);
225
- return `${Number(stats.bavail) * Number(stats.bsize)} bytes available`;
226
- } catch {
227
- return null;
228
- }
229
- }
230
- function translateCommandError(error, input) {
231
- if (error instanceof DevelopmentToolPreparationError) {
232
- if (error.code !== "timeout") return error;
233
- return new DevelopmentToolPreparationError(
234
- `mise ${input.operation} timed out for repository '${input.repositoryKey}' after ${input.timeoutMs}ms`,
235
- "timeout",
236
- error.diagnostics
237
- );
238
- }
239
- const space = input.operation === "install" ? availableSpace(input.root) : null;
240
- return new DevelopmentToolPreparationError(
241
- `${input.failureMessage} '${input.repositoryKey}'${space ? ` (${space})` : ""}`,
242
- input.operation === "install" ? "install_failed" : "verification_failed",
243
- error instanceof Error ? error.message : String(error)
244
- );
245
- }
246
- var MiseDevelopmentToolEnvironment = class {
247
- constructor(baseEnv = process.env) {
248
- this.baseEnv = baseEnv;
249
- }
250
- baseEnv;
251
- async prepare(input) {
252
- const env = buildMiseSubprocessEnvironment(this.baseEnv, input.config);
253
- const versionResult = await runCommand({
254
- command: input.config.miseCommand,
255
- args: ["--version"],
256
- cwd: input.config.processStorageRoot,
257
- env,
258
- timeoutMs: Math.min(input.config.installTimeoutMs, 3e4),
259
- signal: input.signal,
260
- onDiagnosticTrace: input.onDiagnosticTrace
261
- });
262
- const miseVersion = validateMiseVersion(
263
- versionResult.stdout || versionResult.stderr,
264
- input.config.runner
265
- );
266
- if (input.config.runner === "isolated") {
267
- await Promise.all(
268
- [env.MISE_DATA_DIR, env.MISE_INSTALLS_DIR, env.MISE_CACHE_DIR, env.MISE_STATE_DIR].filter((value) => Boolean(value)).map((directory) => mkdir(directory, { recursive: true }))
269
- );
270
- }
271
- const shimDirectory = input.config.runner === "isolated" ? path.join(env.MISE_DATA_DIR, "shims") : localShimDirectory({ ...this.baseEnv, ...env });
272
- env.PATH = [shimDirectory, env.PATH].filter(Boolean).join(path.delimiter);
273
- const repositories = [];
274
- const warnings = [];
275
- for (const repository of [...input.repositories].sort(
276
- (a, b) => a.repositoryKey.localeCompare(b.repositoryKey)
277
- )) {
278
- const repositoryStartedAt = Date.now();
279
- input.onProgress?.(repository.repositoryKey, "installing");
280
- try {
281
- const installed = await runCommand({
282
- command: input.config.miseCommand,
283
- args: ["install"],
284
- cwd: repository.workingDirectory,
285
- env,
286
- timeoutMs: input.config.installTimeoutMs,
287
- signal: input.signal,
288
- onDiagnosticTrace: input.onDiagnosticTrace
289
- });
290
- if (installed.stderr.trim()) {
291
- warnings.push(`${repository.repositoryKey}: ${installed.stderr.trim()}`);
292
- }
293
- } catch (error) {
294
- throw translateCommandError(error, {
295
- operation: "install",
296
- failureMessage: "mise install failed for repository",
297
- repositoryKey: repository.repositoryKey,
298
- timeoutMs: input.config.installTimeoutMs,
299
- root: input.config.processStorageRoot
300
- });
301
- }
302
- input.onProgress?.(repository.repositoryKey, "verifying");
303
- let current;
304
- try {
305
- current = await runCommand({
306
- command: input.config.miseCommand,
307
- args: ["ls", "--current", "--json"],
308
- cwd: repository.workingDirectory,
309
- env,
310
- timeoutMs: Math.max(
311
- 1,
312
- input.config.installTimeoutMs - (Date.now() - repositoryStartedAt)
313
- ),
314
- signal: input.signal,
315
- outputLimit: JSON_LIMIT_BYTES,
316
- onDiagnosticTrace: input.onDiagnosticTrace
317
- });
318
- } catch (error) {
319
- throw translateCommandError(error, {
320
- operation: "verification",
321
- failureMessage: "mise could not verify repository",
322
- repositoryKey: repository.repositoryKey,
323
- timeoutMs: input.config.installTimeoutMs,
324
- root: input.config.processStorageRoot
325
- });
326
- }
327
- let parsed;
328
- try {
329
- parsed = JSON.parse(current.stdout);
330
- } catch {
331
- throw new DevelopmentToolPreparationError(
332
- `mise returned invalid current-tool evidence for repository '${repository.repositoryKey}'`,
333
- "verification_failed"
334
- );
335
- }
336
- if (current.stderr.trim()) {
337
- warnings.push(`${repository.repositoryKey}: ${current.stderr.trim()}`);
338
- }
339
- repositories.push({ ...repository, tools: normalizeMiseEvidence(parsed) });
340
- }
341
- const commandEnvironment = {
342
- ...this.baseEnv,
343
- ...Object.fromEntries(Object.entries(env).filter(([key]) => key.startsWith("MISE_"))),
344
- PATH: [shimDirectory, this.baseEnv.PATH].filter(Boolean).join(path.delimiter)
345
- };
346
- const evidenceDir = path.join(input.config.processStorageRoot, "tooling", "mise-preparation");
347
- await mkdir(evidenceDir, { recursive: true });
348
- const evidence = {
349
- schemaVersion: 1,
350
- preparedAt: (/* @__PURE__ */ new Date()).toISOString(),
351
- miseVersion,
352
- repositories
353
- };
354
- const temporary = path.join(evidenceDir, `.latest-${process.pid}.json`);
355
- await writeFile(temporary, `${JSON.stringify(evidence, null, 2)}
356
- `, { mode: 384 });
357
- await rename(temporary, path.join(evidenceDir, "latest.json"));
358
- return { miseVersion, commandEnvironment, repositories, warnings };
359
- }
360
- };
361
-
362
1
  // src/pi-adapter.ts
363
- import { access, mkdir as mkdir2, writeFile as writeFile2 } from "fs/promises";
364
- import path3 from "path";
2
+ import { access, mkdir, writeFile } from "fs/promises";
3
+ import path2 from "path";
365
4
  import { readFiniteNumber, readNonBlankString as readNonEmptyString } from "@leitwerk-dev/domain";
366
5
  import { hasErrorCode, isEnoent } from "@leitwerk-dev/process-sdk";
367
6
  import { resolvePiAgentDir } from "@leitwerk-dev/process-sdk/pi-config";
@@ -445,18 +84,18 @@ async function createRepositoryBashTool(cwd) {
445
84
 
446
85
  // src/resource-loader-factory.ts
447
86
  import { existsSync, readdirSync, readFileSync } from "fs";
448
- import path2 from "path";
87
+ import path from "path";
449
88
  var AGGREGATED_AGENTS_REL = "AGENTS.md";
450
- var AGGREGATED_SKILLS_DIR_REL = path2.join(".leitwerk", "skills");
89
+ var AGGREGATED_SKILLS_DIR_REL = path.join(".leitwerk", "skills");
451
90
  var PI_EXTENSION_SUFFIXES = /* @__PURE__ */ new Set([".js", ".mjs", ".cjs", ".ts", ".mts", ".cts"]);
452
91
  function managedExtensionPaths(root) {
453
92
  if (!existsSync(root)) return [];
454
93
  const paths = [];
455
94
  const visit = (directory) => {
456
95
  for (const entry of readdirSync(directory, { withFileTypes: true })) {
457
- const entryPath = path2.join(directory, entry.name);
96
+ const entryPath = path.join(directory, entry.name);
458
97
  if (entry.isDirectory()) visit(entryPath);
459
- else if (entry.isFile() && PI_EXTENSION_SUFFIXES.has(path2.extname(entry.name))) {
98
+ else if (entry.isFile() && PI_EXTENSION_SUFFIXES.has(path.extname(entry.name))) {
460
99
  paths.push(entryPath);
461
100
  }
462
101
  }
@@ -466,11 +105,11 @@ function managedExtensionPaths(root) {
466
105
  }
467
106
  async function buildLeitwerkResourceLoaderOptions(workspaceRoot, agentDir, options = {}) {
468
107
  const { loadSkillsFromDir } = await import("@earendil-works/pi-coding-agent");
469
- const aggregatedAgentsPath = path2.join(workspaceRoot, AGGREGATED_AGENTS_REL);
470
- const aggregatedSkillsDir = path2.join(workspaceRoot, AGGREGATED_SKILLS_DIR_REL);
471
- const managedExtensionsDir = path2.join(agentDir, "extensions");
472
- const managedSkillsDir = path2.join(agentDir, "skills");
473
- const managedPromptsDir = path2.join(agentDir, "prompts");
108
+ const aggregatedAgentsPath = path.join(workspaceRoot, AGGREGATED_AGENTS_REL);
109
+ const aggregatedSkillsDir = path.join(workspaceRoot, AGGREGATED_SKILLS_DIR_REL);
110
+ const managedExtensionsDir = path.join(agentDir, "extensions");
111
+ const managedSkillsDir = path.join(agentDir, "skills");
112
+ const managedPromptsDir = path.join(agentDir, "prompts");
474
113
  return {
475
114
  // Disable cwd and ambient discovery. Only the immutable managed snapshot and
476
115
  // explicitly aggregated process-workspace inputs may reach Pi.
@@ -501,8 +140,8 @@ async function buildLeitwerkResourceLoaderOptions(workspaceRoot, agentDir, optio
501
140
  if (!existsSync(aggregatedAgentsPath)) {
502
141
  return base;
503
142
  }
504
- const normalizedAggregatedAgentsPath = path2.resolve(aggregatedAgentsPath);
505
- if (base.agentsFiles.some((file) => path2.resolve(file.path) === normalizedAggregatedAgentsPath)) {
143
+ const normalizedAggregatedAgentsPath = path.resolve(aggregatedAgentsPath);
144
+ if (base.agentsFiles.some((file) => path.resolve(file.path) === normalizedAggregatedAgentsPath)) {
506
145
  return base;
507
146
  }
508
147
  return {
@@ -532,7 +171,7 @@ async function inspectPiTreeForPlanning(input) {
532
171
  const { SessionManager } = await import("@earendil-works/pi-coding-agent");
533
172
  const manager = SessionManager.open(
534
173
  input.treeFile,
535
- path3.dirname(input.treeFile),
174
+ path2.dirname(input.treeFile),
536
175
  input.sessionCwd
537
176
  );
538
177
  const entries = [];
@@ -1439,6 +1078,7 @@ function translateAgentSessionEventEnvelope(event, state) {
1439
1078
  }
1440
1079
  }
1441
1080
  var SdkPiTreeHandle = class {
1081
+ /** @internal */
1442
1082
  constructor(session, options) {
1443
1083
  this.session = session;
1444
1084
  this.sessionId = session.sessionId;
@@ -1452,8 +1092,11 @@ var SdkPiTreeHandle = class {
1452
1092
  };
1453
1093
  }
1454
1094
  session;
1095
+ /** @internal */
1455
1096
  sessionId;
1097
+ /** @internal */
1456
1098
  treeFile;
1099
+ /** @internal */
1457
1100
  isResumed;
1458
1101
  eventState = { currentTurnId: null, turnSequence: 0 };
1459
1102
  eventHandlers = /* @__PURE__ */ new Set();
@@ -1462,6 +1105,7 @@ var SdkPiTreeHandle = class {
1462
1105
  continuationRetryAbortController = null;
1463
1106
  availableToolNames;
1464
1107
  runDetails;
1108
+ /** @internal */
1465
1109
  getRunDetails() {
1466
1110
  return {
1467
1111
  loadedAgentsFiles: this.runDetails.loadedAgentsFiles.map((file) => ({ ...file })),
@@ -1469,32 +1113,41 @@ var SdkPiTreeHandle = class {
1469
1113
  availableToolNames: [...this.runDetails.availableToolNames]
1470
1114
  };
1471
1115
  }
1116
+ /** @internal */
1472
1117
  getLeafId() {
1473
1118
  return this.session.sessionManager.getLeafId();
1474
1119
  }
1120
+ /** @internal */
1475
1121
  getEntry(id) {
1476
1122
  return this.session.sessionManager.getEntry(id);
1477
1123
  }
1124
+ /** @internal */
1478
1125
  getBranch(fromId) {
1479
1126
  return this.session.sessionManager.getBranch(fromId);
1480
1127
  }
1128
+ /** @internal */
1481
1129
  getChildren(parentId) {
1482
1130
  return this.session.sessionManager.getChildren(parentId);
1483
1131
  }
1132
+ /** @internal */
1484
1133
  getTree() {
1485
1134
  return this.session.sessionManager.getTree();
1486
1135
  }
1136
+ /** @internal */
1487
1137
  async branch(entryId) {
1488
1138
  this.session.sessionManager.branch(entryId);
1489
1139
  updateAgentMessagesForCurrentLeaf(this.session);
1490
1140
  }
1141
+ /** @internal */
1491
1142
  async branchFromRoot() {
1492
1143
  this.session.sessionManager.resetLeaf();
1493
1144
  updateAgentMessagesForCurrentLeaf(this.session);
1494
1145
  }
1146
+ /** @internal */
1495
1147
  async resetLeaf() {
1496
1148
  await this.branchFromRoot();
1497
1149
  }
1150
+ /** @internal */
1498
1151
  async compact(customInstructions, details) {
1499
1152
  if (details === void 0) {
1500
1153
  const result = await this.session.compact(customInstructions);
@@ -1745,12 +1398,15 @@ var SdkPiTreeHandle = class {
1745
1398
  options.terminalAcknowledgement
1746
1399
  );
1747
1400
  }
1401
+ /** @internal */
1748
1402
  async prompt(text, options = {}) {
1749
1403
  return await this.executePrompt(options, () => this.session.prompt(text));
1750
1404
  }
1405
+ /** @internal */
1751
1406
  async promptLiteral(text, options = {}) {
1752
1407
  return await this.executePrompt(options, () => this.session.sendUserMessage(text));
1753
1408
  }
1409
+ /** @internal */
1754
1410
  async promptCustom(input, options = {}) {
1755
1411
  return await this.executePrompt(
1756
1412
  options,
@@ -1760,6 +1416,7 @@ var SdkPiTreeHandle = class {
1760
1416
  )
1761
1417
  );
1762
1418
  }
1419
+ /** @internal */
1763
1420
  async continueTurn(options = {}) {
1764
1421
  updateAgentMessagesForCurrentLeaf(this.session);
1765
1422
  return await this.captureTurnExecutionResult(
@@ -1769,6 +1426,7 @@ var SdkPiTreeHandle = class {
1769
1426
  options.terminalAcknowledgement
1770
1427
  );
1771
1428
  }
1429
+ /** @internal */
1772
1430
  async appendCustomMessage(input) {
1773
1431
  const branch = this.createExecutionBranchSnapshot();
1774
1432
  const sessionManager = this.session.sessionManager;
@@ -1793,13 +1451,16 @@ var SdkPiTreeHandle = class {
1793
1451
  branch.assertResult("continue", entryId, entryId);
1794
1452
  return entryId;
1795
1453
  }
1454
+ /** @internal */
1796
1455
  async steer(text) {
1797
1456
  await this.session.steer(text);
1798
1457
  }
1458
+ /** @internal */
1799
1459
  async abortTurn() {
1800
1460
  this.continuationRetryAbortController?.abort(new Error("Retry cancelled"));
1801
1461
  await this.session.abort();
1802
1462
  }
1463
+ /** @internal */
1803
1464
  subscribe(handler) {
1804
1465
  this.eventHandlers.add(handler);
1805
1466
  this.ensureSessionSubscription();
@@ -1808,6 +1469,7 @@ var SdkPiTreeHandle = class {
1808
1469
  this.releaseSessionSubscriptionIfIdle();
1809
1470
  };
1810
1471
  }
1472
+ /** @internal */
1811
1473
  subscribeDiagnostics(handler) {
1812
1474
  this.diagnosticHandlers.add(handler);
1813
1475
  this.ensureSessionSubscription();
@@ -1853,6 +1515,7 @@ var SdkPiTreeHandle = class {
1853
1515
  }
1854
1516
  }
1855
1517
  }
1518
+ /** @internal */
1856
1519
  async close() {
1857
1520
  if (this.sessionUnsubscribe) {
1858
1521
  this.sessionUnsubscribe();
@@ -1886,14 +1549,14 @@ function collectPiRuntimeDiagnostics(services) {
1886
1549
  return [...services.diagnostics, ...extensionLoadDiagnostics, ...resourceDiagnostics];
1887
1550
  }
1888
1551
  function pathIsWithin(root, candidate) {
1889
- const relative = path3.relative(path3.resolve(root), path3.resolve(candidate));
1890
- return relative === "" || !relative.startsWith(`..${path3.sep}`) && relative !== "..";
1552
+ const relative = path2.relative(path2.resolve(root), path2.resolve(candidate));
1553
+ return relative === "" || !relative.startsWith(`..${path2.sep}`) && relative !== "..";
1891
1554
  }
1892
1555
  function assertLoadedPathAllowed(input) {
1893
1556
  if (pathIsWithin(input.agentDir, input.path)) return;
1894
- const aggregatedAgentsPath = path3.join(input.workspaceRoot, "AGENTS.md");
1895
- const aggregatedSkillsRoot = path3.join(input.workspaceRoot, ".leitwerk", "skills");
1896
- if (path3.resolve(input.path) === path3.resolve(aggregatedAgentsPath) || pathIsWithin(aggregatedSkillsRoot, input.path)) {
1557
+ const aggregatedAgentsPath = path2.join(input.workspaceRoot, "AGENTS.md");
1558
+ const aggregatedSkillsRoot = path2.join(input.workspaceRoot, ".leitwerk", "skills");
1559
+ if (path2.resolve(input.path) === path2.resolve(aggregatedAgentsPath) || pathIsWithin(aggregatedSkillsRoot, input.path)) {
1897
1560
  return;
1898
1561
  }
1899
1562
  throw new Error(
@@ -1939,16 +1602,16 @@ function validateManagedLoadedResources(input) {
1939
1602
  }
1940
1603
  const loadedResourceIds = [];
1941
1604
  for (const resource of input.manifest.provenance) {
1942
- const expectedPath = path3.resolve(input.agentDir, resource.snapshotPath);
1605
+ const expectedPath = path2.resolve(input.agentDir, resource.snapshotPath);
1943
1606
  let loaded = resource.kind === "generated";
1944
1607
  if (resource.kind === "extension") {
1945
1608
  loaded = extensions.some(
1946
- (extension) => path3.resolve(extension.resolvedPath) === expectedPath
1609
+ (extension) => path2.resolve(extension.resolvedPath) === expectedPath
1947
1610
  );
1948
1611
  } else if (resource.kind === "skill") {
1949
1612
  loaded = skills.some((skill) => pathIsWithin(skill.baseDir, expectedPath));
1950
1613
  } else if (resource.kind === "prompt") {
1951
- loaded = prompts.some((prompt) => path3.resolve(prompt.filePath) === expectedPath);
1614
+ loaded = prompts.some((prompt) => path2.resolve(prompt.filePath) === expectedPath);
1952
1615
  }
1953
1616
  if (!loaded) {
1954
1617
  throw new Error(
@@ -1963,8 +1626,8 @@ async function createManagedAgentSessionServices(input) {
1963
1626
  const { createAgentSessionServices, ModelRuntime, SettingsManager } = await import("@earendil-works/pi-coding-agent");
1964
1627
  const settingsManager = SettingsManager.create(input.sessionCwd, input.agentDir);
1965
1628
  const modelRuntime = await ModelRuntime.create({
1966
- authPath: path3.join(input.agentDir, "auth.json"),
1967
- modelsPath: path3.join(input.agentDir, "models.json")
1629
+ authPath: path2.join(input.agentDir, "auth.json"),
1630
+ modelsPath: path2.join(input.agentDir, "models.json")
1968
1631
  });
1969
1632
  return createAgentSessionServices({
1970
1633
  cwd: input.sessionCwd,
@@ -2010,7 +1673,7 @@ function resolveModelSelection(modelProfileId, configSnapshot, modelRuntime, dia
2010
1673
  };
2011
1674
  }
2012
1675
  async function ensureSessionFileExists(input) {
2013
- await mkdir2(path3.dirname(input.treeFile), { recursive: true });
1676
+ await mkdir(path2.dirname(input.treeFile), { recursive: true });
2014
1677
  const header = {
2015
1678
  type: "session",
2016
1679
  version: input.sessionVersion,
@@ -2019,7 +1682,7 @@ async function ensureSessionFileExists(input) {
2019
1682
  cwd: input.sessionCwd
2020
1683
  };
2021
1684
  try {
2022
- await writeFile2(input.treeFile, `${JSON.stringify(header)}
1685
+ await writeFile(input.treeFile, `${JSON.stringify(header)}
2023
1686
  `, { flag: "wx" });
2024
1687
  } catch (error) {
2025
1688
  if (hasErrorCode(error, "EEXIST")) {
@@ -2051,13 +1714,15 @@ function applyPiRetryOverrides(services, configSnapshot) {
2051
1714
  services.settingsManager.applyOverrides({ retry: retryOverrides });
2052
1715
  }
2053
1716
  function managedServicesKey(agentDir, sessionCwd) {
2054
- return `${path3.resolve(agentDir)}\0${path3.resolve(sessionCwd)}`;
1717
+ return `${path2.resolve(agentDir)}\0${path2.resolve(sessionCwd)}`;
2055
1718
  }
2056
1719
  var SdkPiTreeHandleFactory = class {
2057
1720
  preparedServices = /* @__PURE__ */ new Map();
1721
+ /** @internal */
2058
1722
  constructor() {
2059
1723
  void import("@earendil-works/pi-coding-agent").catch(() => void 0);
2060
1724
  }
1725
+ /** @internal */
2061
1726
  async prepareManagedBootstrap(opts) {
2062
1727
  const services = await createManagedAgentSessionServices({
2063
1728
  agentDir: opts.agentDir,
@@ -2107,9 +1772,11 @@ var SdkPiTreeHandleFactory = class {
2107
1772
  diagnostics: diagnostics.map((diagnostic) => diagnostic.message)
2108
1773
  };
2109
1774
  }
1775
+ /** @internal */
2110
1776
  async inspectPrimaryTree(opts) {
2111
1777
  return inspectPiTreeForPlanning(opts);
2112
1778
  }
1779
+ /** @internal */
2113
1780
  async createPrimaryTreeHandle(opts) {
2114
1781
  const { CURRENT_SESSION_VERSION, createAgentSessionFromServices, SessionManager } = await import("@earendil-works/pi-coding-agent");
2115
1782
  const agentDir = resolvePiAgentDir({
@@ -2137,7 +1804,7 @@ var SdkPiTreeHandleFactory = class {
2137
1804
  });
2138
1805
  const sessionManager = SessionManager.open(
2139
1806
  opts.treeFile,
2140
- path3.dirname(opts.treeFile),
1807
+ path2.dirname(opts.treeFile),
2141
1808
  sessionCwd
2142
1809
  );
2143
1810
  const modelSelection = resolveModelSelection(
@@ -2175,212 +1842,367 @@ var SdkPiTreeHandleFactory = class {
2175
1842
  }
2176
1843
  };
2177
1844
 
2178
- // src/managed-pi-agent-dir.ts
2179
- import { randomUUID } from "crypto";
2180
- import { chmod, lstat, mkdir as mkdir3, rename as rename2, writeFile as writeFile3 } from "fs/promises";
2181
- import { homedir } from "os";
2182
- import path4 from "path";
2183
- function safeSegment(value, name) {
2184
- if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(value)) {
2185
- throw new Error(`Invalid managed Pi ${name}`);
2186
- }
2187
- return value;
2188
- }
2189
- function resolveManagedPiAgentDir(input) {
2190
- const root = path4.resolve(input.agentDirRoot);
2191
- const ambient = path4.resolve(homedir(), ".pi", "agent");
2192
- if (root === ambient)
2193
- throw new Error("Managed Pi agent directory must not be ambient ~/.pi/agent");
2194
- return path4.join(
2195
- root,
2196
- safeSegment(input.instanceId, "instance id"),
2197
- safeSegment(input.startOrLeaseId, "start id")
2198
- );
2199
- }
2200
- function normalizeManagedPiCredentialPath(value) {
2201
- if (!value || path4.posix.isAbsolute(value) || value.includes("\\")) {
2202
- throw new Error(`Invalid credential file path '${value}'`);
2203
- }
2204
- const normalized = path4.posix.normalize(value);
2205
- if (normalized === "." || normalized === ".." || normalized.startsWith("../")) {
2206
- throw new Error(`Invalid credential file path '${value}'`);
1845
+ // src/development-tool-environment.ts
1846
+ import { statfsSync } from "fs";
1847
+ import { mkdir as mkdir2, rename, writeFile as writeFile2 } from "fs/promises";
1848
+ import path3 from "path";
1849
+ import { execa } from "execa";
1850
+ var PINNED_MISE_VERSION = "2026.8.14";
1851
+ var OUTPUT_LIMIT_BYTES = 64 * 1024;
1852
+ var JSON_LIMIT_BYTES = 1024 * 1024;
1853
+ var TRACE_CHUNK_LENGTH = 16 * 1024;
1854
+ var DevelopmentToolPreparationError = class extends Error {
1855
+ /** @internal */
1856
+ constructor(message, code, diagnostics = "") {
1857
+ super(message);
1858
+ this.code = code;
1859
+ this.diagnostics = diagnostics;
1860
+ this.name = "DevelopmentToolPreparationError";
2207
1861
  }
2208
- return normalized;
1862
+ code;
1863
+ diagnostics;
1864
+ };
1865
+ function parseVersion(value) {
1866
+ const match = /(?:^|\s)(\d{4})\.(\d+)\.(\d+)(?:\s|$)/.exec(value);
1867
+ return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
2209
1868
  }
2210
- async function assertNoSymlinkParents(root, target) {
2211
- let current = root;
2212
- for (const part of path4.relative(root, path4.dirname(target)).split(path4.sep).filter(Boolean)) {
2213
- current = path4.join(current, part);
2214
- try {
2215
- if ((await lstat(current)).isSymbolicLink())
2216
- throw new Error(`Credential parent is a symlink: ${current}`);
2217
- } catch (error) {
2218
- if (error.code !== "ENOENT") throw error;
2219
- await mkdir3(current, { recursive: false, mode: 448 });
2220
- }
1869
+ function compareVersion(a, b) {
1870
+ for (let index = 0; index < 3; index++) {
1871
+ const difference = (a[index] ?? 0) - (b[index] ?? 0);
1872
+ if (difference !== 0) return difference;
2221
1873
  }
1874
+ return 0;
2222
1875
  }
2223
- async function writeManagedPiCredentialFiles(agentDir, files) {
2224
- const root = path4.resolve(agentDir);
2225
- if ((await lstat(root)).isSymbolicLink()) {
2226
- throw new Error(`Managed Pi directory is a symlink: ${root}`);
1876
+ function validateMiseVersion(value, runner) {
1877
+ const parsed = parseVersion(value);
1878
+ const pinned = parseVersion(PINNED_MISE_VERSION);
1879
+ if (!parsed || !pinned) {
1880
+ throw new DevelopmentToolPreparationError(
1881
+ `Could not determine mise version from '${value.trim()}'`,
1882
+ "mise_unsupported"
1883
+ );
2227
1884
  }
2228
- const seen = /* @__PURE__ */ new Set();
2229
- for (const file of files) {
2230
- const relative = normalizeManagedPiCredentialPath(file.path);
2231
- if (seen.has(relative)) throw new Error(`Duplicate credential file path '${relative}'`);
2232
- seen.add(relative);
2233
- const target = path4.resolve(root, relative);
2234
- if (!target.startsWith(`${root}${path4.sep}`))
2235
- throw new Error(`Credential path escapes managed directory: ${relative}`);
2236
- await assertNoSymlinkParents(root, target);
2237
- const tmp = path4.join(
2238
- path4.dirname(target),
2239
- `.${path4.basename(target)}.tmp-${process.pid}-${randomUUID()}`
1885
+ if (runner === "isolated" && compareVersion(parsed, pinned) !== 0 || runner === "local" && (parsed[0] !== pinned[0] || compareVersion(parsed, pinned) < 0)) {
1886
+ throw new DevelopmentToolPreparationError(
1887
+ `mise ${parsed.join(".")} is unsupported; expected ${runner === "isolated" ? PINNED_MISE_VERSION : `${PINNED_MISE_VERSION} or newer before ${pinned[0] + 1}.0.0`}`,
1888
+ "mise_unsupported"
2240
1889
  );
2241
- await writeFile3(tmp, file.content, { mode: 384, flag: "wx" });
2242
- await chmod(tmp, 384);
2243
- await rename2(tmp, target);
2244
- await chmod(target, 384);
2245
1890
  }
1891
+ return parsed.join(".");
2246
1892
  }
2247
-
2248
- // src/pi-resource-bundle.ts
2249
- import { randomUUID as randomUUID2 } from "crypto";
2250
- import { mkdir as mkdir4, open, readFile, rename as rename3, rm, writeFile as writeFile4 } from "fs/promises";
2251
- import path5 from "path";
2252
- import {
2253
- createCanonicalPiResourceBundle,
2254
- sha256Digest,
2255
- validateResourceRelativePath,
2256
- verifyCanonicalPiResourceBundle
2257
- } from "@leitwerk-dev/worker-protocol";
2258
- function fail(message) {
2259
- throw new Error(`Invalid Pi resource bundle: ${message}`);
2260
- }
2261
- function requireStorageName(value, label) {
2262
- if (!/^[a-zA-Z0-9_-]+$/u.test(value)) fail(`unsafe ${label}: ${value}`);
2263
- return value;
2264
- }
2265
- async function atomicWrite(pathname, content, mode) {
2266
- const staging = `${pathname}.staging-${process.pid}-${randomUUID2()}`;
2267
- const handle = await open(staging, "wx", mode);
2268
- try {
2269
- await handle.writeFile(content);
2270
- await handle.sync();
2271
- } finally {
2272
- await handle.close();
1893
+ var SAFE_ENV_KEYS = /* @__PURE__ */ new Set([
1894
+ "HOME",
1895
+ "USER",
1896
+ "LOGNAME",
1897
+ "SHELL",
1898
+ "PATH",
1899
+ "TMPDIR",
1900
+ "TMP",
1901
+ "TEMP",
1902
+ "LANG",
1903
+ "TERM",
1904
+ "HTTP_PROXY",
1905
+ "HTTPS_PROXY",
1906
+ "ALL_PROXY",
1907
+ "NO_PROXY",
1908
+ "http_proxy",
1909
+ "https_proxy",
1910
+ "all_proxy",
1911
+ "no_proxy",
1912
+ "SSL_CERT_FILE",
1913
+ "SSL_CERT_DIR",
1914
+ "NODE_EXTRA_CA_CERTS",
1915
+ "XDG_CONFIG_HOME",
1916
+ "XDG_DATA_HOME",
1917
+ "XDG_CACHE_HOME",
1918
+ "XDG_STATE_HOME"
1919
+ ]);
1920
+ function buildMiseSubprocessEnvironment(base, config) {
1921
+ const env = {};
1922
+ for (const [key, value] of Object.entries(base)) {
1923
+ const safeMiseSetting = config.runner === "local" && key.startsWith("MISE_") && !/(?:TOKEN|PASSWORD|SECRET|AUTH|CREDENTIAL|API_KEY)/i.test(key);
1924
+ if (value !== void 0 && (SAFE_ENV_KEYS.has(key) || key.startsWith("LC_") || safeMiseSetting)) {
1925
+ env[key] = value;
1926
+ }
2273
1927
  }
2274
- try {
2275
- await rename3(staging, pathname);
2276
- } catch (error) {
2277
- await rm(staging, { force: true });
2278
- throw error;
1928
+ if (config.runner === "isolated") {
1929
+ const miseRoot = path3.join(config.processStorageRoot, "tooling", "mise");
1930
+ env.MISE_DATA_DIR = miseRoot;
1931
+ env.MISE_INSTALLS_DIR = path3.join(miseRoot, "installs");
1932
+ env.MISE_CACHE_DIR = path3.join(miseRoot, "cache");
1933
+ env.MISE_STATE_DIR = path3.join(miseRoot, "state");
1934
+ }
1935
+ return env;
1936
+ }
1937
+ function localShimDirectory(env) {
1938
+ if (env.MISE_DATA_DIR) return path3.join(env.MISE_DATA_DIR, "shims");
1939
+ if (env.XDG_DATA_HOME) return path3.join(env.XDG_DATA_HOME, "mise", "shims");
1940
+ return path3.join(env.HOME ?? "", ".local", "share", "mise", "shims");
1941
+ }
1942
+ function emitDiagnosticTrace(trace, value) {
1943
+ if (!trace) return;
1944
+ for (let offset = 0; offset < value.length; offset += TRACE_CHUNK_LENGTH) {
1945
+ trace(value.slice(offset, offset + TRACE_CHUNK_LENGTH));
2279
1946
  }
2280
1947
  }
2281
- async function persistPiResourceBundleForStart(input) {
2282
- const digest = requireStorageName(input.digest, "resource digest");
2283
- const startRecordId = requireStorageName(input.startRecordId, "turn-start id");
2284
- const bundlesDir = path5.resolve(input.bundlesDir);
2285
- const startsDir = path5.join(bundlesDir, "starts");
2286
- const bundlePath = path5.join(bundlesDir, `${digest}.tar`);
2287
- await mkdir4(startsDir, { recursive: true, mode: 448 });
2288
- let bundle = null;
2289
- let reused = false;
1948
+ function appendBounded(current, chunk, limit) {
1949
+ const combined = current + chunk.toString("utf8");
1950
+ return Buffer.byteLength(combined) <= limit ? combined : Buffer.from(combined).subarray(-limit).toString("utf8");
1951
+ }
1952
+ async function runCommand(input) {
1953
+ if (input.signal?.aborted) {
1954
+ throw new DevelopmentToolPreparationError("mise preparation was cancelled", "cancelled");
1955
+ }
1956
+ const child = execa(input.command, input.args, {
1957
+ cwd: input.cwd,
1958
+ env: input.env,
1959
+ extendEnv: false,
1960
+ stdin: "ignore",
1961
+ detached: true,
1962
+ timeout: input.timeoutMs,
1963
+ cancelSignal: input.signal,
1964
+ forceKillAfterDelay: 2e3,
1965
+ reject: false,
1966
+ stripFinalNewline: false
1967
+ });
1968
+ let stdout = "";
1969
+ let stderr = "";
1970
+ const outputLimit = input.outputLimit ?? OUTPUT_LIMIT_BYTES;
1971
+ const appendOutput = (target, chunk) => {
1972
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
1973
+ const text = buffer.toString("utf8");
1974
+ emitDiagnosticTrace(input.onDiagnosticTrace, text);
1975
+ if (target === "stdout") stdout = appendBounded(stdout, buffer, outputLimit);
1976
+ else stderr = appendBounded(stderr, buffer, outputLimit);
1977
+ };
1978
+ child.stdout?.on("data", (chunk) => appendOutput("stdout", chunk));
1979
+ child.stderr?.on("data", (chunk) => appendOutput("stderr", chunk));
1980
+ let groupTermination = null;
1981
+ const killGroup = () => {
1982
+ if (!child.pid || groupTermination) return;
1983
+ const pid = child.pid;
1984
+ try {
1985
+ process.kill(-pid, "SIGTERM");
1986
+ } catch {
1987
+ child.kill("SIGTERM");
1988
+ }
1989
+ groupTermination = new Promise((resolve) => {
1990
+ setTimeout(() => {
1991
+ try {
1992
+ process.kill(-pid, "SIGKILL");
1993
+ } catch {
1994
+ }
1995
+ resolve();
1996
+ }, 2e3);
1997
+ });
1998
+ };
1999
+ const groupTimeout = setTimeout(killGroup, input.timeoutMs);
2000
+ input.signal?.addEventListener("abort", killGroup, { once: true });
2290
2001
  try {
2291
- const existing = await readFile(bundlePath);
2292
- verifyCanonicalPiResourceBundle(existing, digest);
2293
- bundle = existing;
2294
- reused = true;
2295
- } catch (error) {
2296
- if (error.code !== "ENOENT" && input.archiveBase64 === void 0) {
2297
- throw error;
2002
+ const result = await child;
2003
+ const diagnostics = `${stdout}
2004
+ ${stderr}`.trim();
2005
+ if (input.signal?.aborted || result.isCanceled) {
2006
+ throw new DevelopmentToolPreparationError(
2007
+ "mise preparation was cancelled",
2008
+ "cancelled",
2009
+ diagnostics
2010
+ );
2298
2011
  }
2299
- }
2300
- if (!bundle) {
2301
- if (!input.deliveredBundle && input.archiveBase64 === void 0) {
2302
- throw new Error(`Pi resource bundle '${digest}' is unavailable on the process volume`);
2012
+ if (result.timedOut) {
2013
+ throw new DevelopmentToolPreparationError(
2014
+ `mise exceeded its ${input.timeoutMs}ms deadline`,
2015
+ "timeout",
2016
+ diagnostics
2017
+ );
2303
2018
  }
2304
- bundle = input.deliveredBundle ?? Buffer.from(input.archiveBase64, "base64");
2305
- verifyCanonicalPiResourceBundle(bundle, digest);
2306
- await atomicWrite(bundlePath, bundle, 384);
2019
+ if (result.code === "ENOENT") {
2020
+ throw new DevelopmentToolPreparationError(
2021
+ `mise command '${input.command}' was not found`,
2022
+ "mise_missing",
2023
+ diagnostics
2024
+ );
2025
+ }
2026
+ if (result.failed) {
2027
+ throw new Error(`${result.shortMessage}
2028
+ ${diagnostics}`);
2029
+ }
2030
+ return { stdout, stderr };
2031
+ } finally {
2032
+ clearTimeout(groupTimeout);
2033
+ input.signal?.removeEventListener("abort", killGroup);
2034
+ await groupTermination;
2307
2035
  }
2308
- const manifest = Buffer.from(
2309
- `${JSON.stringify({ startRecordId, digest, persistedAt: (/* @__PURE__ */ new Date()).toISOString() })}
2310
- `,
2311
- "utf8"
2036
+ }
2037
+ function toolPair(candidate, fallbackName) {
2038
+ if (!candidate || typeof candidate !== "object") return null;
2039
+ const item = candidate;
2040
+ const name = [item.tool, item.name, item.plugin, fallbackName].find(
2041
+ (value) => typeof value === "string" && value.trim() !== ""
2312
2042
  );
2313
- await atomicWrite(path5.join(startsDir, `${startRecordId}.json`), manifest, 384);
2314
- return { bundle, reused };
2043
+ const version = [item.version, item.installed_version, item.requested_version].find(
2044
+ (value) => typeof value === "string" && value.trim() !== ""
2045
+ );
2046
+ return name && version ? { name, version } : null;
2315
2047
  }
2316
- async function writeExtractedFiles(root, files) {
2317
- for (const file of files) {
2318
- const output = path5.resolve(root, file.path);
2319
- if (path5.relative(root, output).startsWith("..") || path5.isAbsolute(path5.relative(root, output))) {
2320
- fail(`path escapes materialization root: ${file.path}`);
2048
+ function normalizeMiseEvidence(value) {
2049
+ const tools = [];
2050
+ if (Array.isArray(value)) {
2051
+ for (const item of value) {
2052
+ const pair = toolPair(item);
2053
+ if (pair) tools.push(pair);
2054
+ }
2055
+ } else if (value && typeof value === "object") {
2056
+ for (const [name, item] of Object.entries(value)) {
2057
+ for (const candidate of Array.isArray(item) ? item : [item]) {
2058
+ const pair = typeof candidate === "string" ? { name, version: candidate } : toolPair(candidate, name);
2059
+ if (pair) tools.push(pair);
2060
+ }
2321
2061
  }
2322
- await mkdir4(path5.dirname(output), { recursive: true, mode: 448 });
2323
- await writeFile4(output, file.content, { mode: 420, flag: "wx" });
2324
2062
  }
2063
+ return [...new Map(tools.map((tool) => [`${tool.name}\0${tool.version}`, tool])).values()].sort(
2064
+ (a, b) => a.name.localeCompare(b.name) || a.version.localeCompare(b.version)
2065
+ );
2325
2066
  }
2326
- async function materializeCanonicalPiResourceBundle(input) {
2327
- const files = verifyCanonicalPiResourceBundle(input.bundle, input.digest);
2328
- const targetDir = path5.resolve(input.targetDir);
2329
- const parent = path5.dirname(targetDir);
2330
- await mkdir4(parent, { recursive: true, mode: 448 });
2331
- const marker = path5.join(targetDir, ".leitwerk-resource-digest");
2067
+ function availableSpace(root) {
2332
2068
  try {
2333
- const current = await import("fs/promises").then(
2334
- ({ readFile: readFile5 }) => readFile5(marker, "utf8")
2335
- );
2336
- if (current === `${input.digest}
2337
- `) return { targetDir, reused: true };
2338
- throw new Error(
2339
- `Managed Pi directory already exists with a different resource digest: ${targetDir}`
2069
+ const stats = statfsSync(root);
2070
+ return `${Number(stats.bavail) * Number(stats.bsize)} bytes available`;
2071
+ } catch {
2072
+ return null;
2073
+ }
2074
+ }
2075
+ function translateCommandError(error, input) {
2076
+ if (error instanceof DevelopmentToolPreparationError) {
2077
+ if (error.code !== "timeout") return error;
2078
+ return new DevelopmentToolPreparationError(
2079
+ `mise ${input.operation} timed out for repository '${input.repositoryKey}' after ${input.timeoutMs}ms`,
2080
+ "timeout",
2081
+ error.diagnostics
2340
2082
  );
2341
- } catch (error) {
2342
- if (error.code !== "ENOENT") throw error;
2343
2083
  }
2344
- const staging = path5.join(
2345
- parent,
2346
- `.${path5.basename(targetDir)}.staging-${process.pid}-${randomUUID2()}`
2084
+ const space = input.operation === "install" ? availableSpace(input.root) : null;
2085
+ return new DevelopmentToolPreparationError(
2086
+ `${input.failureMessage} '${input.repositoryKey}'${space ? ` (${space})` : ""}`,
2087
+ input.operation === "install" ? "install_failed" : "verification_failed",
2088
+ error instanceof Error ? error.message : String(error)
2347
2089
  );
2348
- try {
2349
- await mkdir4(staging, { mode: 448 });
2350
- await writeExtractedFiles(staging, files);
2351
- await writeFile4(path5.join(staging, ".leitwerk-resource-digest"), `${input.digest}
2352
- `, {
2353
- mode: 384,
2354
- flag: "wx"
2090
+ }
2091
+ var MiseDevelopmentToolEnvironment = class {
2092
+ /** @internal */
2093
+ constructor(baseEnv = process.env) {
2094
+ this.baseEnv = baseEnv;
2095
+ }
2096
+ baseEnv;
2097
+ /** @internal */
2098
+ async prepare(input) {
2099
+ const env = buildMiseSubprocessEnvironment(this.baseEnv, input.config);
2100
+ const versionResult = await runCommand({
2101
+ command: input.config.miseCommand,
2102
+ args: ["--version"],
2103
+ cwd: input.config.processStorageRoot,
2104
+ env,
2105
+ timeoutMs: Math.min(input.config.installTimeoutMs, 3e4),
2106
+ signal: input.signal,
2107
+ onDiagnosticTrace: input.onDiagnosticTrace
2355
2108
  });
2356
- await rename3(staging, targetDir);
2357
- return { targetDir, reused: false };
2358
- } catch (error) {
2359
- await rm(staging, { recursive: true, force: true });
2360
- if (error.code === "EEXIST") {
2361
- const current = await import("fs/promises").then(
2362
- ({ readFile: readFile5 }) => readFile5(marker, "utf8")
2109
+ const miseVersion = validateMiseVersion(
2110
+ versionResult.stdout || versionResult.stderr,
2111
+ input.config.runner
2112
+ );
2113
+ if (input.config.runner === "isolated") {
2114
+ await Promise.all(
2115
+ [env.MISE_DATA_DIR, env.MISE_INSTALLS_DIR, env.MISE_CACHE_DIR, env.MISE_STATE_DIR].filter((value) => Boolean(value)).map((directory) => mkdir2(directory, { recursive: true }))
2363
2116
  );
2364
- if (current === `${input.digest}
2365
- `) return { targetDir, reused: true };
2366
2117
  }
2367
- throw error;
2368
- }
2369
- }
2370
-
2371
- // src/runtime/adapters.ts
2372
- var nodeWorkerRuntimeScheduler = {
2373
- setTimeout(handler, delayMs) {
2374
- return setTimeout(handler, delayMs);
2375
- },
2376
- clearTimeout(timer) {
2377
- clearTimeout(timer);
2378
- },
2379
- sleep(delayMs) {
2380
- return new Promise((resolve) => setTimeout(resolve, delayMs));
2381
- },
2382
- now() {
2383
- return /* @__PURE__ */ new Date();
2118
+ const shimDirectory = input.config.runner === "isolated" ? path3.join(env.MISE_DATA_DIR, "shims") : localShimDirectory({ ...this.baseEnv, ...env });
2119
+ env.PATH = [shimDirectory, env.PATH].filter(Boolean).join(path3.delimiter);
2120
+ const repositories = [];
2121
+ const warnings = [];
2122
+ for (const repository of [...input.repositories].sort(
2123
+ (a, b) => a.repositoryKey.localeCompare(b.repositoryKey)
2124
+ )) {
2125
+ const repositoryStartedAt = Date.now();
2126
+ input.onProgress?.(repository.repositoryKey, "installing");
2127
+ try {
2128
+ const installed = await runCommand({
2129
+ command: input.config.miseCommand,
2130
+ args: ["install"],
2131
+ cwd: repository.workingDirectory,
2132
+ env,
2133
+ timeoutMs: input.config.installTimeoutMs,
2134
+ signal: input.signal,
2135
+ onDiagnosticTrace: input.onDiagnosticTrace
2136
+ });
2137
+ if (installed.stderr.trim()) {
2138
+ warnings.push(`${repository.repositoryKey}: ${installed.stderr.trim()}`);
2139
+ }
2140
+ } catch (error) {
2141
+ throw translateCommandError(error, {
2142
+ operation: "install",
2143
+ failureMessage: "mise install failed for repository",
2144
+ repositoryKey: repository.repositoryKey,
2145
+ timeoutMs: input.config.installTimeoutMs,
2146
+ root: input.config.processStorageRoot
2147
+ });
2148
+ }
2149
+ input.onProgress?.(repository.repositoryKey, "verifying");
2150
+ let current;
2151
+ try {
2152
+ current = await runCommand({
2153
+ command: input.config.miseCommand,
2154
+ args: ["ls", "--current", "--json"],
2155
+ cwd: repository.workingDirectory,
2156
+ env,
2157
+ timeoutMs: Math.max(
2158
+ 1,
2159
+ input.config.installTimeoutMs - (Date.now() - repositoryStartedAt)
2160
+ ),
2161
+ signal: input.signal,
2162
+ outputLimit: JSON_LIMIT_BYTES,
2163
+ onDiagnosticTrace: input.onDiagnosticTrace
2164
+ });
2165
+ } catch (error) {
2166
+ throw translateCommandError(error, {
2167
+ operation: "verification",
2168
+ failureMessage: "mise could not verify repository",
2169
+ repositoryKey: repository.repositoryKey,
2170
+ timeoutMs: input.config.installTimeoutMs,
2171
+ root: input.config.processStorageRoot
2172
+ });
2173
+ }
2174
+ let parsed;
2175
+ try {
2176
+ parsed = JSON.parse(current.stdout);
2177
+ } catch {
2178
+ throw new DevelopmentToolPreparationError(
2179
+ `mise returned invalid current-tool evidence for repository '${repository.repositoryKey}'`,
2180
+ "verification_failed"
2181
+ );
2182
+ }
2183
+ if (current.stderr.trim()) {
2184
+ warnings.push(`${repository.repositoryKey}: ${current.stderr.trim()}`);
2185
+ }
2186
+ repositories.push({ ...repository, tools: normalizeMiseEvidence(parsed) });
2187
+ }
2188
+ const commandEnvironment = {
2189
+ ...this.baseEnv,
2190
+ ...Object.fromEntries(Object.entries(env).filter(([key]) => key.startsWith("MISE_"))),
2191
+ PATH: [shimDirectory, this.baseEnv.PATH].filter(Boolean).join(path3.delimiter)
2192
+ };
2193
+ const evidenceDir = path3.join(input.config.processStorageRoot, "tooling", "mise-preparation");
2194
+ await mkdir2(evidenceDir, { recursive: true });
2195
+ const evidence = {
2196
+ schemaVersion: 1,
2197
+ preparedAt: (/* @__PURE__ */ new Date()).toISOString(),
2198
+ miseVersion,
2199
+ repositories
2200
+ };
2201
+ const temporary = path3.join(evidenceDir, `.latest-${process.pid}.json`);
2202
+ await writeFile2(temporary, `${JSON.stringify(evidence, null, 2)}
2203
+ `, { mode: 384 });
2204
+ await rename(temporary, path3.join(evidenceDir, "latest.json"));
2205
+ return { miseVersion, commandEnvironment, repositories, warnings };
2384
2206
  }
2385
2207
  };
2386
2208
 
@@ -2757,7 +2579,7 @@ async function restoreHandleAfterTurn(piHandle, plan) {
2757
2579
  }
2758
2580
 
2759
2581
  // src/worker-ipc-reporter.ts
2760
- import { randomUUID as randomUUID3 } from "crypto";
2582
+ import { randomUUID } from "crypto";
2761
2583
  import { createIpcMessage } from "@leitwerk-dev/worker-protocol";
2762
2584
 
2763
2585
  // src/diagnostics.ts
@@ -2829,7 +2651,7 @@ function createWorkerIpcReporter(options) {
2829
2651
  options.send(
2830
2652
  createIpcMessage({
2831
2653
  type: fact.type,
2832
- messageId: randomUUID3(),
2654
+ messageId: randomUUID(),
2833
2655
  instanceId: options.instanceId,
2834
2656
  workerId: options.workerId,
2835
2657
  sentAt: options.now().toISOString(),
@@ -2941,33 +2763,103 @@ import {
2941
2763
  import { repositoryHttpsUrl } from "@leitwerk-dev/process-sdk";
2942
2764
  import { createTemplateContext, resolveProcessPiConfig } from "@leitwerk-dev/process-sdk/pi-config";
2943
2765
 
2766
+ // src/managed-pi-agent-dir.ts
2767
+ import { randomUUID as randomUUID2 } from "crypto";
2768
+ import { chmod, lstat, mkdir as mkdir3, rename as rename2, writeFile as writeFile3 } from "fs/promises";
2769
+ import { homedir } from "os";
2770
+ import path4 from "path";
2771
+ function safeSegment(value, name) {
2772
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(value)) {
2773
+ throw new Error(`Invalid managed Pi ${name}`);
2774
+ }
2775
+ return value;
2776
+ }
2777
+ function resolveManagedPiAgentDir(input) {
2778
+ const root = path4.resolve(input.agentDirRoot);
2779
+ const ambient = path4.resolve(homedir(), ".pi", "agent");
2780
+ if (root === ambient)
2781
+ throw new Error("Managed Pi agent directory must not be ambient ~/.pi/agent");
2782
+ return path4.join(
2783
+ root,
2784
+ safeSegment(input.instanceId, "instance id"),
2785
+ safeSegment(input.startOrLeaseId, "start id")
2786
+ );
2787
+ }
2788
+ function normalizeManagedPiCredentialPath(value) {
2789
+ if (!value || path4.posix.isAbsolute(value) || value.includes("\\")) {
2790
+ throw new Error(`Invalid credential file path '${value}'`);
2791
+ }
2792
+ const normalized = path4.posix.normalize(value);
2793
+ if (normalized === "." || normalized === ".." || normalized.startsWith("../")) {
2794
+ throw new Error(`Invalid credential file path '${value}'`);
2795
+ }
2796
+ return normalized;
2797
+ }
2798
+ async function assertNoSymlinkParents(root, target) {
2799
+ let current = root;
2800
+ for (const part of path4.relative(root, path4.dirname(target)).split(path4.sep).filter(Boolean)) {
2801
+ current = path4.join(current, part);
2802
+ try {
2803
+ if ((await lstat(current)).isSymbolicLink())
2804
+ throw new Error(`Credential parent is a symlink: ${current}`);
2805
+ } catch (error) {
2806
+ if (error.code !== "ENOENT") throw error;
2807
+ await mkdir3(current, { recursive: false, mode: 448 });
2808
+ }
2809
+ }
2810
+ }
2811
+ async function writeManagedPiCredentialFiles(agentDir, files) {
2812
+ const root = path4.resolve(agentDir);
2813
+ if ((await lstat(root)).isSymbolicLink()) {
2814
+ throw new Error(`Managed Pi directory is a symlink: ${root}`);
2815
+ }
2816
+ const seen = /* @__PURE__ */ new Set();
2817
+ for (const file of files) {
2818
+ const relative = normalizeManagedPiCredentialPath(file.path);
2819
+ if (seen.has(relative)) throw new Error(`Duplicate credential file path '${relative}'`);
2820
+ seen.add(relative);
2821
+ const target = path4.resolve(root, relative);
2822
+ if (!target.startsWith(`${root}${path4.sep}`))
2823
+ throw new Error(`Credential path escapes managed directory: ${relative}`);
2824
+ await assertNoSymlinkParents(root, target);
2825
+ const tmp = path4.join(
2826
+ path4.dirname(target),
2827
+ `.${path4.basename(target)}.tmp-${process.pid}-${randomUUID2()}`
2828
+ );
2829
+ await writeFile3(tmp, file.content, { mode: 384, flag: "wx" });
2830
+ await chmod(tmp, 384);
2831
+ await rename2(tmp, target);
2832
+ await chmod(target, 384);
2833
+ }
2834
+ }
2835
+
2944
2836
  // src/managed-pi-bootstrap.ts
2945
- import { lstat as lstat2, readFile as readFile2 } from "fs/promises";
2946
- import path6 from "path";
2837
+ import { lstat as lstat2, readFile } from "fs/promises";
2838
+ import path5 from "path";
2947
2839
  import {
2948
2840
  canonicalJsonEqual,
2949
2841
  IPC_PROTOCOL_VERSION,
2950
2842
  parsePiResourceManifest,
2951
2843
  WORKER_API_VERSION
2952
2844
  } from "@leitwerk-dev/worker-protocol";
2953
- function fail2(message) {
2845
+ function fail(message) {
2954
2846
  throw new Error(`Invalid managed Pi resource snapshot: ${message}`);
2955
2847
  }
2956
2848
  function record(value, location) {
2957
2849
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
2958
- fail2(`${location} must be an object`);
2850
+ fail(`${location} must be an object`);
2959
2851
  }
2960
2852
  return value;
2961
2853
  }
2962
2854
  function assertJsonEqual(actual, expected, location) {
2963
2855
  if (!canonicalJsonEqual(actual, expected)) {
2964
- fail2(`${location} does not match the resolved LLM start`);
2856
+ fail(`${location} does not match the resolved LLM start`);
2965
2857
  }
2966
2858
  }
2967
2859
  function assertModelMatchesStart(manifest, start) {
2968
2860
  for (const key of ["profileId", "providerId", "modelId", "thinkingLevel"]) {
2969
2861
  if (manifest.model[key] !== start.model[key]) {
2970
- fail2(
2862
+ fail(
2971
2863
  `generated.json model ${key} '${manifest.model[key]}' does not match start '${start.model[key]}'`
2972
2864
  );
2973
2865
  }
@@ -2976,30 +2868,30 @@ function assertModelMatchesStart(manifest, start) {
2976
2868
  async function assertCompatibility(manifest) {
2977
2869
  const { VERSION: PI_VERSION } = await import("@earendil-works/pi-coding-agent");
2978
2870
  if (manifest.compatibility.workerApiVersion !== WORKER_API_VERSION) {
2979
- fail2(
2871
+ fail(
2980
2872
  `server snapshot worker API version '${manifest.compatibility.workerApiVersion}' does not match local worker API version '${WORKER_API_VERSION}'`
2981
2873
  );
2982
2874
  }
2983
2875
  if (manifest.compatibility.piVersion !== PI_VERSION) {
2984
- fail2(
2876
+ fail(
2985
2877
  `server snapshot Pi version '${manifest.compatibility.piVersion}' does not match local worker Pi version '${PI_VERSION}'`
2986
2878
  );
2987
2879
  }
2988
2880
  if (manifest.compatibility.protocolVersion !== void 0 && manifest.compatibility.protocolVersion !== IPC_PROTOCOL_VERSION) {
2989
- fail2(
2881
+ fail(
2990
2882
  `server snapshot protocol version '${manifest.compatibility.protocolVersion}' does not match local worker protocol version '${IPC_PROTOCOL_VERSION}'`
2991
2883
  );
2992
2884
  }
2993
2885
  }
2994
2886
  async function readAndValidateManagedPiResourceManifest(input) {
2995
- const marker = await readFile2(path6.join(input.agentDir, ".leitwerk-resource-digest"), "utf8");
2887
+ const marker = await readFile(path5.join(input.agentDir, ".leitwerk-resource-digest"), "utf8");
2996
2888
  if (marker !== `${input.resourceDigest}
2997
2889
  `) {
2998
- fail2("materialized resource digest marker does not match the delivered bundle");
2890
+ fail("materialized resource digest marker does not match the delivered bundle");
2999
2891
  }
3000
2892
  let parsed;
3001
2893
  try {
3002
- parsed = JSON.parse(await readFile2(path6.join(input.agentDir, "generated.json"), "utf8"));
2894
+ parsed = JSON.parse(await readFile(path5.join(input.agentDir, "generated.json"), "utf8"));
3003
2895
  } catch (error) {
3004
2896
  throw new Error("Invalid managed Pi resource snapshot: generated.json is unreadable", {
3005
2897
  cause: error
@@ -3016,7 +2908,7 @@ async function readAndValidateManagedPiResourceManifest(input) {
3016
2908
  );
3017
2909
  let settings;
3018
2910
  try {
3019
- settings = JSON.parse(await readFile2(path6.join(input.agentDir, "settings.json"), "utf8"));
2911
+ settings = JSON.parse(await readFile(path5.join(input.agentDir, "settings.json"), "utf8"));
3020
2912
  } catch (error) {
3021
2913
  throw new Error("Invalid managed Pi resource snapshot: settings.json is unreadable", {
3022
2914
  cause: error
@@ -3067,7 +2959,7 @@ function buildManagedPiCredentialFiles(input) {
3067
2959
  }
3068
2960
  async function assertManagedPiCredentialFiles(input) {
3069
2961
  for (const credentialPath of input.manifest.declaredCredentialPaths) {
3070
- const target = path6.join(input.agentDir, credentialPath);
2962
+ const target = path5.join(input.agentDir, credentialPath);
3071
2963
  const stat2 = await lstat2(target).catch(() => null);
3072
2964
  if (!stat2?.isFile() || stat2.isSymbolicLink()) {
3073
2965
  throw new Error(`Declared credential file '${credentialPath}' is missing or unsafe`);
@@ -3078,7 +2970,7 @@ async function assertManagedPiCredentialFiles(input) {
3078
2970
  }
3079
2971
  if (input.credential && input.manifest.declaredCredentialPaths.includes("auth.json")) {
3080
2972
  const auth = record(
3081
- JSON.parse(await readFile2(path6.join(input.agentDir, "auth.json"), "utf8")),
2973
+ JSON.parse(await readFile(path5.join(input.agentDir, "auth.json"), "utf8")),
3082
2974
  "auth.json"
3083
2975
  );
3084
2976
  if (input.credential.values.apiKey) {
@@ -3105,6 +2997,129 @@ async function assertManagedPiCredentialFiles(input) {
3105
2997
  }
3106
2998
  }
3107
2999
 
3000
+ // src/pi-resource-bundle.ts
3001
+ import { randomUUID as randomUUID3 } from "crypto";
3002
+ import { mkdir as mkdir4, open, readFile as readFile2, rename as rename3, rm, writeFile as writeFile4 } from "fs/promises";
3003
+ import path6 from "path";
3004
+ import {
3005
+ createCanonicalPiResourceBundle,
3006
+ sha256Digest,
3007
+ validateResourceRelativePath,
3008
+ verifyCanonicalPiResourceBundle
3009
+ } from "@leitwerk-dev/worker-protocol";
3010
+ function fail2(message) {
3011
+ throw new Error(`Invalid Pi resource bundle: ${message}`);
3012
+ }
3013
+ function requireStorageName(value, label) {
3014
+ if (!/^[a-zA-Z0-9_-]+$/u.test(value)) fail2(`unsafe ${label}: ${value}`);
3015
+ return value;
3016
+ }
3017
+ async function atomicWrite(pathname, content, mode) {
3018
+ const staging = `${pathname}.staging-${process.pid}-${randomUUID3()}`;
3019
+ const handle = await open(staging, "wx", mode);
3020
+ try {
3021
+ await handle.writeFile(content);
3022
+ await handle.sync();
3023
+ } finally {
3024
+ await handle.close();
3025
+ }
3026
+ try {
3027
+ await rename3(staging, pathname);
3028
+ } catch (error) {
3029
+ await rm(staging, { force: true });
3030
+ throw error;
3031
+ }
3032
+ }
3033
+ async function persistPiResourceBundleForStart(input) {
3034
+ const digest = requireStorageName(input.digest, "resource digest");
3035
+ const startRecordId = requireStorageName(input.startRecordId, "turn-start id");
3036
+ const bundlesDir = path6.resolve(input.bundlesDir);
3037
+ const startsDir = path6.join(bundlesDir, "starts");
3038
+ const bundlePath = path6.join(bundlesDir, `${digest}.tar`);
3039
+ await mkdir4(startsDir, { recursive: true, mode: 448 });
3040
+ let bundle = null;
3041
+ let reused = false;
3042
+ try {
3043
+ const existing = await readFile2(bundlePath);
3044
+ verifyCanonicalPiResourceBundle(existing, digest);
3045
+ bundle = existing;
3046
+ reused = true;
3047
+ } catch (error) {
3048
+ if (error.code !== "ENOENT" && input.archiveBase64 === void 0) {
3049
+ throw error;
3050
+ }
3051
+ }
3052
+ if (!bundle) {
3053
+ if (!input.deliveredBundle && input.archiveBase64 === void 0) {
3054
+ throw new Error(`Pi resource bundle '${digest}' is unavailable on the process volume`);
3055
+ }
3056
+ bundle = input.deliveredBundle ?? Buffer.from(input.archiveBase64, "base64");
3057
+ verifyCanonicalPiResourceBundle(bundle, digest);
3058
+ await atomicWrite(bundlePath, bundle, 384);
3059
+ }
3060
+ const manifest = Buffer.from(
3061
+ `${JSON.stringify({ startRecordId, digest, persistedAt: (/* @__PURE__ */ new Date()).toISOString() })}
3062
+ `,
3063
+ "utf8"
3064
+ );
3065
+ await atomicWrite(path6.join(startsDir, `${startRecordId}.json`), manifest, 384);
3066
+ return { bundle, reused };
3067
+ }
3068
+ async function writeExtractedFiles(root, files) {
3069
+ for (const file of files) {
3070
+ const output = path6.resolve(root, file.path);
3071
+ if (path6.relative(root, output).startsWith("..") || path6.isAbsolute(path6.relative(root, output))) {
3072
+ fail2(`path escapes materialization root: ${file.path}`);
3073
+ }
3074
+ await mkdir4(path6.dirname(output), { recursive: true, mode: 448 });
3075
+ await writeFile4(output, file.content, { mode: 420, flag: "wx" });
3076
+ }
3077
+ }
3078
+ async function materializeCanonicalPiResourceBundle(input) {
3079
+ const files = verifyCanonicalPiResourceBundle(input.bundle, input.digest);
3080
+ const targetDir = path6.resolve(input.targetDir);
3081
+ const parent = path6.dirname(targetDir);
3082
+ await mkdir4(parent, { recursive: true, mode: 448 });
3083
+ const marker = path6.join(targetDir, ".leitwerk-resource-digest");
3084
+ try {
3085
+ const current = await import("fs/promises").then(
3086
+ ({ readFile: readFile5 }) => readFile5(marker, "utf8")
3087
+ );
3088
+ if (current === `${input.digest}
3089
+ `) return { targetDir, reused: true };
3090
+ throw new Error(
3091
+ `Managed Pi directory already exists with a different resource digest: ${targetDir}`
3092
+ );
3093
+ } catch (error) {
3094
+ if (error.code !== "ENOENT") throw error;
3095
+ }
3096
+ const staging = path6.join(
3097
+ parent,
3098
+ `.${path6.basename(targetDir)}.staging-${process.pid}-${randomUUID3()}`
3099
+ );
3100
+ try {
3101
+ await mkdir4(staging, { mode: 448 });
3102
+ await writeExtractedFiles(staging, files);
3103
+ await writeFile4(path6.join(staging, ".leitwerk-resource-digest"), `${input.digest}
3104
+ `, {
3105
+ mode: 384,
3106
+ flag: "wx"
3107
+ });
3108
+ await rename3(staging, targetDir);
3109
+ return { targetDir, reused: false };
3110
+ } catch (error) {
3111
+ await rm(staging, { recursive: true, force: true });
3112
+ if (error.code === "EEXIST") {
3113
+ const current = await import("fs/promises").then(
3114
+ ({ readFile: readFile5 }) => readFile5(marker, "utf8")
3115
+ );
3116
+ if (current === `${input.digest}
3117
+ `) return { targetDir, reused: true };
3118
+ }
3119
+ throw error;
3120
+ }
3121
+ }
3122
+
3108
3123
  // src/pre-turn-targeted-inputs.ts
3109
3124
  import {
3110
3125
  resolveProcessProductRefEntryId,
@@ -7516,6 +7531,22 @@ async function executeSelectedTurn(input) {
7516
7531
  }
7517
7532
  }
7518
7533
 
7534
+ // src/runtime/adapters.ts
7535
+ var nodeWorkerRuntimeScheduler = {
7536
+ setTimeout(handler, delayMs) {
7537
+ return setTimeout(handler, delayMs);
7538
+ },
7539
+ clearTimeout(timer) {
7540
+ clearTimeout(timer);
7541
+ },
7542
+ sleep(delayMs) {
7543
+ return new Promise((resolve) => setTimeout(resolve, delayMs));
7544
+ },
7545
+ now() {
7546
+ return /* @__PURE__ */ new Date();
7547
+ }
7548
+ };
7549
+
7519
7550
  // src/runtime/index.ts
7520
7551
  function createWorkerRuntime(options) {
7521
7552
  const { config, adapters } = options;
@@ -8160,13 +8191,17 @@ function createWorkerIpcFromEnvironment(input) {
8160
8191
  if (!serverUrl || !token) {
8161
8192
  throw new Error("WebSocket worker IPC requires LEITWERK_SERVER_URL and worker token env");
8162
8193
  }
8194
+ const recordDiagnostic = createConnectionDiagnosticRecorder();
8163
8195
  return createWebSocketWorkerIpc({
8164
8196
  serverUrl,
8165
8197
  instanceId: input.instanceId,
8166
8198
  workerId: input.workerId,
8167
8199
  token,
8168
8200
  reconnect: env[WORKER_IPC_RECONNECT_ENV] === "1",
8169
- onDiagnostic: createConnectionDiagnosticRecorder()
8201
+ onDiagnostic(message) {
8202
+ recordDiagnostic(message);
8203
+ input.onDiagnostic?.(message);
8204
+ }
8170
8205
  });
8171
8206
  }
8172
8207
 
@@ -8684,7 +8719,12 @@ function createWorkerEntryRuntime(overrides = {}) {
8684
8719
  if (!instanceId || !workerId) {
8685
8720
  throw new Error("Missing required worker identity env");
8686
8721
  }
8687
- const transport = overrides.transport ?? createWorkerIpcFromEnvironment({ env: runtimeEnv, instanceId, workerId });
8722
+ const transport = overrides.transport ?? createWorkerIpcFromEnvironment({
8723
+ env: runtimeEnv,
8724
+ instanceId,
8725
+ workerId,
8726
+ onDiagnostic: overrides.onConnectionDiagnostic
8727
+ });
8688
8728
  const sessionSnapshots = overrides.sessionSnapshots ?? createWorkerSessionSnapshotExchangeFromEnv({ env: runtimeEnv, instanceId, workerId });
8689
8729
  const scheduler = overrides.scheduler ?? nodeWorkerRuntimeScheduler;
8690
8730
  const resultImageServerUrl = runtimeEnv[WORKER_IPC_SERVER_URL_ENV3];
@@ -8740,25 +8780,8 @@ function createWorkerEntryRuntime(overrides = {}) {
8740
8780
  }
8741
8781
 
8742
8782
  export {
8743
- PINNED_MISE_VERSION,
8744
- DevelopmentToolPreparationError,
8745
- validateMiseVersion,
8746
- buildMiseSubprocessEnvironment,
8747
- normalizeMiseEvidence,
8748
- MiseDevelopmentToolEnvironment,
8749
- doesPiEventResetInactivity,
8750
- translateAgentSessionEventEnvelope,
8751
- SdkPiTreeHandle,
8752
8783
  SdkPiTreeHandleFactory,
8753
- resolveManagedPiAgentDir,
8754
- writeManagedPiCredentialFiles,
8755
- createCanonicalPiResourceBundle,
8756
- sha256Digest,
8757
- validateResourceRelativePath,
8758
- verifyCanonicalPiResourceBundle,
8759
- materializeCanonicalPiResourceBundle,
8760
- nodeWorkerRuntimeScheduler,
8761
8784
  createWorkerRuntime,
8762
8785
  createWorkerEntryRuntime
8763
8786
  };
8764
- //# sourceMappingURL=chunk-Y7S2MZD3.js.map
8787
+ //# sourceMappingURL=chunk-2LLFMCR6.js.map