@leitwerk-dev/worker 0.1.9 → 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 (234) hide show
  1. package/dist/automatic-turn-executor.d.ts +1 -0
  2. package/dist/automatic-turn-executor.d.ts.map +1 -1
  3. package/dist/{chunk-O6332GRG.js → chunk-Y7S2MZD3.js} +1349 -932
  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 +4 -0
  16. package/dist/diagnostics.d.ts.map +1 -1
  17. package/dist/docker-registry-credentials.d.ts +8 -0
  18. package/dist/docker-registry-credentials.d.ts.map +1 -0
  19. package/dist/entry-runtime.d.ts +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.map +1 -1
  56. package/dist/runtime/llm-turn-execution.d.ts +3 -8
  57. package/dist/runtime/llm-turn-execution.d.ts.map +1 -1
  58. package/dist/runtime/turn-execution.d.ts +2 -9
  59. package/dist/runtime/turn-execution.d.ts.map +1 -1
  60. package/dist/session-snapshot-exchange.d.ts +0 -4
  61. package/dist/session-snapshot-exchange.d.ts.map +1 -1
  62. package/dist/turn-continuation.d.ts.map +1 -1
  63. package/dist/turn-execution-error.d.ts +1 -1
  64. package/dist/turn-execution-error.d.ts.map +1 -1
  65. package/dist/turn-execution-result.d.ts +1 -0
  66. package/dist/turn-execution-result.d.ts.map +1 -1
  67. package/dist/turn-outcome-tool-session.d.ts +0 -2
  68. package/dist/turn-outcome-tool-session.d.ts.map +1 -1
  69. package/dist/turn-result-markdown.d.ts +2 -1
  70. package/dist/turn-result-markdown.d.ts.map +1 -1
  71. package/dist/turn-tree-strategy.d.ts +0 -1
  72. package/dist/turn-tree-strategy.d.ts.map +1 -1
  73. package/dist/worker-entry.js +16 -4
  74. package/dist/worker-entry.js.map +1 -1
  75. package/dist/worker-ipc-reporter.d.ts.map +1 -1
  76. package/dist/workspace/manifest.d.ts +4 -7
  77. package/dist/workspace/manifest.d.ts.map +1 -1
  78. package/dist/workspace/node-run-root-git-ops.d.ts +2 -2
  79. package/dist/workspace/node-run-root-git-ops.d.ts.map +1 -1
  80. package/dist/workspace/resource-aggregator.d.ts.map +1 -1
  81. package/dist/workspace/run-root.d.ts +9 -20
  82. package/dist/workspace/run-root.d.ts.map +1 -1
  83. package/package.json +8 -8
  84. package/src/automatic-turn-executor.ts +2 -0
  85. package/src/connection-diagnostics.ts +27 -0
  86. package/src/container-entry-main.ts +24 -0
  87. package/src/container-entry.ts +246 -0
  88. package/src/development-tool-environment.ts +452 -0
  89. package/src/diagnostics.ts +1 -0
  90. package/src/docker-registry-credentials.ts +65 -0
  91. package/src/entry-runtime.ts +5 -4
  92. package/src/index.ts +11 -0
  93. package/src/input-consumer.ts +7 -29
  94. package/src/ipc.ts +37 -2
  95. package/src/logical-prompt-runner.ts +23 -29
  96. package/src/managed-pi-bootstrap.ts +3 -3
  97. package/src/missing-tool-recovery-runner.ts +4 -18
  98. package/src/pi-adapter.ts +19 -50
  99. package/src/pi-event-reporter.ts +16 -38
  100. package/src/pi-resource-bundle.ts +67 -1
  101. package/src/pre-turn-targeted-inputs.ts +9 -11
  102. package/src/prompt-guards.ts +44 -75
  103. package/src/repository-bash-tool.ts +15 -0
  104. package/src/resource-loader-factory.ts +1 -18
  105. package/src/result-image-upload.ts +16 -27
  106. package/src/runtime/adapters.ts +2 -0
  107. package/src/runtime/bootstrap-session.ts +69 -39
  108. package/src/runtime/bootstrap.ts +160 -103
  109. package/src/runtime/failure-policy.ts +36 -42
  110. package/src/runtime/index.ts +43 -14
  111. package/src/runtime/lifecycle-reducer.ts +71 -173
  112. package/src/runtime/llm-turn-execution.ts +13 -30
  113. package/src/runtime/turn-execution.ts +78 -31
  114. package/src/session-snapshot-exchange.ts +23 -64
  115. package/src/turn-continuation.ts +9 -17
  116. package/src/turn-execution-error.ts +3 -11
  117. package/src/turn-execution-result.ts +1 -0
  118. package/src/turn-outcome-tool-session.ts +25 -21
  119. package/src/turn-result-markdown.ts +31 -34
  120. package/src/turn-tree-strategy.ts +6 -19
  121. package/src/worker-entry.ts +8 -0
  122. package/src/worker-ipc-reporter.ts +8 -16
  123. package/src/workspace/manifest.ts +5 -7
  124. package/src/workspace/node-run-root-git-ops.ts +65 -25
  125. package/src/workspace/resource-aggregator.ts +5 -16
  126. package/src/workspace/run-root.ts +38 -89
  127. package/dist/automatic-turn-executor.js +0 -58
  128. package/dist/automatic-turn-executor.js.map +0 -1
  129. package/dist/chunk-O6332GRG.js.map +0 -1
  130. package/dist/diagnostics.js +0 -51
  131. package/dist/diagnostics.js.map +0 -1
  132. package/dist/entry-runtime.js +0 -160
  133. package/dist/entry-runtime.js.map +0 -1
  134. package/dist/event-translator.js +0 -12
  135. package/dist/event-translator.js.map +0 -1
  136. package/dist/extension-entry-roots.js +0 -41
  137. package/dist/extension-entry-roots.js.map +0 -1
  138. package/dist/identified-pi-entry.js +0 -125
  139. package/dist/identified-pi-entry.js.map +0 -1
  140. package/dist/input-consumer.js +0 -34
  141. package/dist/input-consumer.js.map +0 -1
  142. package/dist/integration-tool-bridge.js +0 -53
  143. package/dist/integration-tool-bridge.js.map +0 -1
  144. package/dist/ipc.js +0 -192
  145. package/dist/ipc.js.map +0 -1
  146. package/dist/logical-prompt-runner.js +0 -225
  147. package/dist/logical-prompt-runner.js.map +0 -1
  148. package/dist/managed-pi-agent-dir.js +0 -66
  149. package/dist/managed-pi-agent-dir.js.map +0 -1
  150. package/dist/managed-pi-bootstrap.js +0 -135
  151. package/dist/managed-pi-bootstrap.js.map +0 -1
  152. package/dist/missing-tool-recovery-runner.js +0 -73
  153. package/dist/missing-tool-recovery-runner.js.map +0 -1
  154. package/dist/pi-adapter.js +0 -1648
  155. package/dist/pi-adapter.js.map +0 -1
  156. package/dist/pi-branch-guard.js +0 -75
  157. package/dist/pi-branch-guard.js.map +0 -1
  158. package/dist/pi-event-reporter.js +0 -136
  159. package/dist/pi-event-reporter.js.map +0 -1
  160. package/dist/pi-resource-bundle.js +0 -58
  161. package/dist/pi-resource-bundle.js.map +0 -1
  162. package/dist/pre-turn-targeted-inputs.js +0 -101
  163. package/dist/pre-turn-targeted-inputs.js.map +0 -1
  164. package/dist/prompt-guards.js +0 -318
  165. package/dist/prompt-guards.js.map +0 -1
  166. package/dist/question-bridge.js +0 -24
  167. package/dist/question-bridge.js.map +0 -1
  168. package/dist/question-tool.js +0 -54
  169. package/dist/question-tool.js.map +0 -1
  170. package/dist/replaying-request-bridge.js +0 -71
  171. package/dist/replaying-request-bridge.js.map +0 -1
  172. package/dist/resource-loader-factory.js +0 -87
  173. package/dist/resource-loader-factory.js.map +0 -1
  174. package/dist/result-image-upload.js +0 -183
  175. package/dist/result-image-upload.js.map +0 -1
  176. package/dist/runtime/adapters.js +0 -15
  177. package/dist/runtime/adapters.js.map +0 -1
  178. package/dist/runtime/bootstrap-session.js +0 -199
  179. package/dist/runtime/bootstrap-session.js.map +0 -1
  180. package/dist/runtime/bootstrap.js +0 -440
  181. package/dist/runtime/bootstrap.js.map +0 -1
  182. package/dist/runtime/failure-policy.js +0 -182
  183. package/dist/runtime/failure-policy.js.map +0 -1
  184. package/dist/runtime/index.js +0 -339
  185. package/dist/runtime/index.js.map +0 -1
  186. package/dist/runtime/lifecycle-reducer.js +0 -1142
  187. package/dist/runtime/lifecycle-reducer.js.map +0 -1
  188. package/dist/runtime/llm-turn-execution.js +0 -494
  189. package/dist/runtime/llm-turn-execution.js.map +0 -1
  190. package/dist/runtime/settings.js +0 -24
  191. package/dist/runtime/settings.js.map +0 -1
  192. package/dist/runtime/snapshot-policy.js +0 -16
  193. package/dist/runtime/snapshot-policy.js.map +0 -1
  194. package/dist/runtime/turn-execution.js +0 -151
  195. package/dist/runtime/turn-execution.js.map +0 -1
  196. package/dist/session-snapshot-exchange.js +0 -102
  197. package/dist/session-snapshot-exchange.js.map +0 -1
  198. package/dist/test-helpers/fake-websocket.js +0 -40
  199. package/dist/test-helpers/fake-websocket.js.map +0 -1
  200. package/dist/test-helpers/ipc-harness.d.ts +0 -11
  201. package/dist/test-helpers/ipc-harness.d.ts.map +0 -1
  202. package/dist/test-helpers/ipc-harness.js +0 -17
  203. package/dist/test-helpers/ipc-harness.js.map +0 -1
  204. package/dist/turn-continuation.js +0 -80
  205. package/dist/turn-continuation.js.map +0 -1
  206. package/dist/turn-execution-error.js +0 -64
  207. package/dist/turn-execution-error.js.map +0 -1
  208. package/dist/turn-execution-result.js +0 -21
  209. package/dist/turn-execution-result.js.map +0 -1
  210. package/dist/turn-outcome-tool-session.js +0 -210
  211. package/dist/turn-outcome-tool-session.js.map +0 -1
  212. package/dist/turn-record-id.js +0 -10
  213. package/dist/turn-record-id.js.map +0 -1
  214. package/dist/turn-result-markdown.js +0 -263
  215. package/dist/turn-result-markdown.js.map +0 -1
  216. package/dist/turn-tree-strategy.js +0 -80
  217. package/dist/turn-tree-strategy.js.map +0 -1
  218. package/dist/worker-http.js +0 -9
  219. package/dist/worker-http.js.map +0 -1
  220. package/dist/worker-ipc-reporter.js +0 -58
  221. package/dist/worker-ipc-reporter.js.map +0 -1
  222. package/dist/worker-payloads.js +0 -66
  223. package/dist/worker-payloads.js.map +0 -1
  224. package/dist/worker-start-payload.js +0 -5
  225. package/dist/worker-start-payload.js.map +0 -1
  226. package/dist/workspace/manifest.js +0 -79
  227. package/dist/workspace/manifest.js.map +0 -1
  228. package/dist/workspace/node-run-root-git-ops.js +0 -96
  229. package/dist/workspace/node-run-root-git-ops.js.map +0 -1
  230. package/dist/workspace/resource-aggregator.js +0 -39
  231. package/dist/workspace/resource-aggregator.js.map +0 -1
  232. package/dist/workspace/run-root.js +0 -209
  233. package/dist/workspace/run-root.js.map +0 -1
  234. package/src/test-helpers/ipc-harness.ts +0 -19
@@ -1,7 +1,369 @@
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
+
1
362
  // src/pi-adapter.ts
2
- import { access, mkdir, writeFile } from "fs/promises";
3
- import path2 from "path";
4
- import { retryAssistantCall } from "@earendil-works/pi-ai";
363
+ import { access, mkdir as mkdir2, writeFile as writeFile2 } from "fs/promises";
364
+ import path3 from "path";
365
+ import { readFiniteNumber, readNonBlankString as readNonEmptyString } from "@leitwerk-dev/domain";
366
+ import { hasErrorCode, isEnoent } from "@leitwerk-dev/process-sdk";
5
367
  import { resolvePiAgentDir } from "@leitwerk-dev/process-sdk/pi-config";
6
368
  import { parseDurationMs } from "@leitwerk-dev/watcher-utils";
7
369
 
@@ -69,20 +431,32 @@ function assertResultStayedOnExecutionBranch(input) {
69
431
  }
70
432
  }
71
433
 
434
+ // src/repository-bash-tool.ts
435
+ import { sanitizeWorkerSubprocessEnv } from "@leitwerk-dev/process-sdk";
436
+ async function createRepositoryBashTool(cwd) {
437
+ const { createBashToolDefinition } = await import("@earendil-works/pi-coding-agent");
438
+ return createBashToolDefinition(cwd, {
439
+ spawnHook: (context) => ({
440
+ ...context,
441
+ env: sanitizeWorkerSubprocessEnv(context.env, { NODE_ENV: void 0 })
442
+ })
443
+ });
444
+ }
445
+
72
446
  // src/resource-loader-factory.ts
73
447
  import { existsSync, readdirSync, readFileSync } from "fs";
74
- import path from "path";
448
+ import path2 from "path";
75
449
  var AGGREGATED_AGENTS_REL = "AGENTS.md";
76
- var AGGREGATED_SKILLS_DIR_REL = path.join(".leitwerk", "skills");
450
+ var AGGREGATED_SKILLS_DIR_REL = path2.join(".leitwerk", "skills");
77
451
  var PI_EXTENSION_SUFFIXES = /* @__PURE__ */ new Set([".js", ".mjs", ".cjs", ".ts", ".mts", ".cts"]);
78
452
  function managedExtensionPaths(root) {
79
453
  if (!existsSync(root)) return [];
80
454
  const paths = [];
81
455
  const visit = (directory) => {
82
456
  for (const entry of readdirSync(directory, { withFileTypes: true })) {
83
- const entryPath = path.join(directory, entry.name);
457
+ const entryPath = path2.join(directory, entry.name);
84
458
  if (entry.isDirectory()) visit(entryPath);
85
- else if (entry.isFile() && PI_EXTENSION_SUFFIXES.has(path.extname(entry.name))) {
459
+ else if (entry.isFile() && PI_EXTENSION_SUFFIXES.has(path2.extname(entry.name))) {
86
460
  paths.push(entryPath);
87
461
  }
88
462
  }
@@ -92,11 +466,11 @@ function managedExtensionPaths(root) {
92
466
  }
93
467
  async function buildLeitwerkResourceLoaderOptions(workspaceRoot, agentDir, options = {}) {
94
468
  const { loadSkillsFromDir } = await import("@earendil-works/pi-coding-agent");
95
- const aggregatedAgentsPath = path.join(workspaceRoot, AGGREGATED_AGENTS_REL);
96
- const aggregatedSkillsDir = path.join(workspaceRoot, AGGREGATED_SKILLS_DIR_REL);
97
- const managedExtensionsDir = path.join(agentDir, "extensions");
98
- const managedSkillsDir = path.join(agentDir, "skills");
99
- const managedPromptsDir = path.join(agentDir, "prompts");
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");
100
474
  return {
101
475
  // Disable cwd and ambient discovery. Only the immutable managed snapshot and
102
476
  // explicitly aggregated process-workspace inputs may reach Pi.
@@ -127,8 +501,8 @@ async function buildLeitwerkResourceLoaderOptions(workspaceRoot, agentDir, optio
127
501
  if (!existsSync(aggregatedAgentsPath)) {
128
502
  return base;
129
503
  }
130
- const normalizedAggregatedAgentsPath = path.resolve(aggregatedAgentsPath);
131
- if (base.agentsFiles.some((file) => path.resolve(file.path) === normalizedAggregatedAgentsPath)) {
504
+ const normalizedAggregatedAgentsPath = path2.resolve(aggregatedAgentsPath);
505
+ if (base.agentsFiles.some((file) => path2.resolve(file.path) === normalizedAggregatedAgentsPath)) {
132
506
  return base;
133
507
  }
134
508
  return {
@@ -150,7 +524,7 @@ async function inspectPiTreeForPlanning(input) {
150
524
  try {
151
525
  await access(input.treeFile);
152
526
  } catch (error) {
153
- if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") {
527
+ if (isEnoent(error)) {
154
528
  return { currentLeafId: null, entries: [] };
155
529
  }
156
530
  throw error;
@@ -158,7 +532,7 @@ async function inspectPiTreeForPlanning(input) {
158
532
  const { SessionManager } = await import("@earendil-works/pi-coding-agent");
159
533
  const manager = SessionManager.open(
160
534
  input.treeFile,
161
- path2.dirname(input.treeFile),
535
+ path3.dirname(input.treeFile),
162
536
  input.sessionCwd
163
537
  );
164
538
  const entries = [];
@@ -310,21 +684,6 @@ function updateAgentMessagesForCurrentLeaf(session) {
310
684
  function activeTurnId(state) {
311
685
  return state.currentTurnId ?? `turn-${state.turnSequence}`;
312
686
  }
313
- function readNonEmptyString(value) {
314
- return typeof value === "string" && value.trim() !== "" ? value : null;
315
- }
316
- function readFiniteNumber(value) {
317
- if (typeof value === "number" && Number.isFinite(value)) {
318
- return value;
319
- }
320
- if (typeof value === "string" && value.trim() !== "") {
321
- const parsed = Number(value);
322
- if (Number.isFinite(parsed)) {
323
- return parsed;
324
- }
325
- }
326
- return null;
327
- }
328
687
  function listRecordKeys(value) {
329
688
  return Object.keys(value).slice(0, 12);
330
689
  }
@@ -1267,6 +1626,7 @@ var SdkPiTreeHandle = class {
1267
1626
  const controller = new AbortController();
1268
1627
  this.continuationRetryAbortController = controller;
1269
1628
  try {
1629
+ const { retryAssistantCall } = await import("@earendil-works/pi-ai");
1270
1630
  await retryAssistantCall(
1271
1631
  async () => {
1272
1632
  await this.session.agent.continue();
@@ -1526,14 +1886,14 @@ function collectPiRuntimeDiagnostics(services) {
1526
1886
  return [...services.diagnostics, ...extensionLoadDiagnostics, ...resourceDiagnostics];
1527
1887
  }
1528
1888
  function pathIsWithin(root, candidate) {
1529
- const relative = path2.relative(path2.resolve(root), path2.resolve(candidate));
1530
- return relative === "" || !relative.startsWith(`..${path2.sep}`) && relative !== "..";
1889
+ const relative = path3.relative(path3.resolve(root), path3.resolve(candidate));
1890
+ return relative === "" || !relative.startsWith(`..${path3.sep}`) && relative !== "..";
1531
1891
  }
1532
1892
  function assertLoadedPathAllowed(input) {
1533
1893
  if (pathIsWithin(input.agentDir, input.path)) return;
1534
- const aggregatedAgentsPath = path2.join(input.workspaceRoot, "AGENTS.md");
1535
- const aggregatedSkillsRoot = path2.join(input.workspaceRoot, ".leitwerk", "skills");
1536
- if (path2.resolve(input.path) === path2.resolve(aggregatedAgentsPath) || pathIsWithin(aggregatedSkillsRoot, input.path)) {
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)) {
1537
1897
  return;
1538
1898
  }
1539
1899
  throw new Error(
@@ -1579,16 +1939,16 @@ function validateManagedLoadedResources(input) {
1579
1939
  }
1580
1940
  const loadedResourceIds = [];
1581
1941
  for (const resource of input.manifest.provenance) {
1582
- const expectedPath = path2.resolve(input.agentDir, resource.snapshotPath);
1942
+ const expectedPath = path3.resolve(input.agentDir, resource.snapshotPath);
1583
1943
  let loaded = resource.kind === "generated";
1584
1944
  if (resource.kind === "extension") {
1585
1945
  loaded = extensions.some(
1586
- (extension) => path2.resolve(extension.resolvedPath) === expectedPath
1946
+ (extension) => path3.resolve(extension.resolvedPath) === expectedPath
1587
1947
  );
1588
1948
  } else if (resource.kind === "skill") {
1589
1949
  loaded = skills.some((skill) => pathIsWithin(skill.baseDir, expectedPath));
1590
1950
  } else if (resource.kind === "prompt") {
1591
- loaded = prompts.some((prompt) => path2.resolve(prompt.filePath) === expectedPath);
1951
+ loaded = prompts.some((prompt) => path3.resolve(prompt.filePath) === expectedPath);
1592
1952
  }
1593
1953
  if (!loaded) {
1594
1954
  throw new Error(
@@ -1603,8 +1963,8 @@ async function createManagedAgentSessionServices(input) {
1603
1963
  const { createAgentSessionServices, ModelRuntime, SettingsManager } = await import("@earendil-works/pi-coding-agent");
1604
1964
  const settingsManager = SettingsManager.create(input.sessionCwd, input.agentDir);
1605
1965
  const modelRuntime = await ModelRuntime.create({
1606
- authPath: path2.join(input.agentDir, "auth.json"),
1607
- modelsPath: path2.join(input.agentDir, "models.json")
1966
+ authPath: path3.join(input.agentDir, "auth.json"),
1967
+ modelsPath: path3.join(input.agentDir, "models.json")
1608
1968
  });
1609
1969
  return createAgentSessionServices({
1610
1970
  cwd: input.sessionCwd,
@@ -1649,11 +2009,8 @@ function resolveModelSelection(modelProfileId, configSnapshot, modelRuntime, dia
1649
2009
  thinkingLevel: profile.thinking_level
1650
2010
  };
1651
2011
  }
1652
- function isAlreadyExistsError(error) {
1653
- return typeof error === "object" && error !== null && "code" in error && error.code === "EEXIST";
1654
- }
1655
2012
  async function ensureSessionFileExists(input) {
1656
- await mkdir(path2.dirname(input.treeFile), { recursive: true });
2013
+ await mkdir2(path3.dirname(input.treeFile), { recursive: true });
1657
2014
  const header = {
1658
2015
  type: "session",
1659
2016
  version: input.sessionVersion,
@@ -1662,10 +2019,10 @@ async function ensureSessionFileExists(input) {
1662
2019
  cwd: input.sessionCwd
1663
2020
  };
1664
2021
  try {
1665
- await writeFile(input.treeFile, `${JSON.stringify(header)}
2022
+ await writeFile2(input.treeFile, `${JSON.stringify(header)}
1666
2023
  `, { flag: "wx" });
1667
2024
  } catch (error) {
1668
- if (isAlreadyExistsError(error)) {
2025
+ if (hasErrorCode(error, "EEXIST")) {
1669
2026
  return;
1670
2027
  }
1671
2028
  throw error;
@@ -1694,10 +2051,13 @@ function applyPiRetryOverrides(services, configSnapshot) {
1694
2051
  services.settingsManager.applyOverrides({ retry: retryOverrides });
1695
2052
  }
1696
2053
  function managedServicesKey(agentDir, sessionCwd) {
1697
- return `${path2.resolve(agentDir)}\0${path2.resolve(sessionCwd)}`;
2054
+ return `${path3.resolve(agentDir)}\0${path3.resolve(sessionCwd)}`;
1698
2055
  }
1699
2056
  var SdkPiTreeHandleFactory = class {
1700
2057
  preparedServices = /* @__PURE__ */ new Map();
2058
+ constructor() {
2059
+ void import("@earendil-works/pi-coding-agent").catch(() => void 0);
2060
+ }
1701
2061
  async prepareManagedBootstrap(opts) {
1702
2062
  const services = await createManagedAgentSessionServices({
1703
2063
  agentDir: opts.agentDir,
@@ -1777,7 +2137,7 @@ var SdkPiTreeHandleFactory = class {
1777
2137
  });
1778
2138
  const sessionManager = SessionManager.open(
1779
2139
  opts.treeFile,
1780
- path2.dirname(opts.treeFile),
2140
+ path3.dirname(opts.treeFile),
1781
2141
  sessionCwd
1782
2142
  );
1783
2143
  const modelSelection = resolveModelSelection(
@@ -1791,7 +2151,10 @@ var SdkPiTreeHandleFactory = class {
1791
2151
  sessionManager,
1792
2152
  ...modelSelection.model ? { model: modelSelection.model } : {},
1793
2153
  ...modelSelection.thinkingLevel ? { thinkingLevel: modelSelection.thinkingLevel } : {},
1794
- customTools: [LEITWERK_TOOL_BOOTSTRAP],
2154
+ customTools: [
2155
+ LEITWERK_TOOL_BOOTSTRAP,
2156
+ await createRepositoryBashTool(sessionCwd)
2157
+ ],
1795
2158
  noTools: "builtin"
1796
2159
  });
1797
2160
  getMutableSession(session)._refreshToolRegistry({ activeToolNames: [] });
@@ -1814,9 +2177,9 @@ var SdkPiTreeHandleFactory = class {
1814
2177
 
1815
2178
  // src/managed-pi-agent-dir.ts
1816
2179
  import { randomUUID } from "crypto";
1817
- import { chmod, lstat, mkdir as mkdir2, rename, writeFile as writeFile2 } from "fs/promises";
2180
+ import { chmod, lstat, mkdir as mkdir3, rename as rename2, writeFile as writeFile3 } from "fs/promises";
1818
2181
  import { homedir } from "os";
1819
- import path3 from "path";
2182
+ import path4 from "path";
1820
2183
  function safeSegment(value, name) {
1821
2184
  if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(value)) {
1822
2185
  throw new Error(`Invalid managed Pi ${name}`);
@@ -1824,21 +2187,21 @@ function safeSegment(value, name) {
1824
2187
  return value;
1825
2188
  }
1826
2189
  function resolveManagedPiAgentDir(input) {
1827
- const root = path3.resolve(input.agentDirRoot);
1828
- const ambient = path3.resolve(homedir(), ".pi", "agent");
2190
+ const root = path4.resolve(input.agentDirRoot);
2191
+ const ambient = path4.resolve(homedir(), ".pi", "agent");
1829
2192
  if (root === ambient)
1830
2193
  throw new Error("Managed Pi agent directory must not be ambient ~/.pi/agent");
1831
- return path3.join(
2194
+ return path4.join(
1832
2195
  root,
1833
2196
  safeSegment(input.instanceId, "instance id"),
1834
2197
  safeSegment(input.startOrLeaseId, "start id")
1835
2198
  );
1836
2199
  }
1837
2200
  function normalizeManagedPiCredentialPath(value) {
1838
- if (!value || path3.posix.isAbsolute(value) || value.includes("\\")) {
2201
+ if (!value || path4.posix.isAbsolute(value) || value.includes("\\")) {
1839
2202
  throw new Error(`Invalid credential file path '${value}'`);
1840
2203
  }
1841
- const normalized = path3.posix.normalize(value);
2204
+ const normalized = path4.posix.normalize(value);
1842
2205
  if (normalized === "." || normalized === ".." || normalized.startsWith("../")) {
1843
2206
  throw new Error(`Invalid credential file path '${value}'`);
1844
2207
  }
@@ -1846,19 +2209,19 @@ function normalizeManagedPiCredentialPath(value) {
1846
2209
  }
1847
2210
  async function assertNoSymlinkParents(root, target) {
1848
2211
  let current = root;
1849
- for (const part of path3.relative(root, path3.dirname(target)).split(path3.sep).filter(Boolean)) {
1850
- current = path3.join(current, part);
2212
+ for (const part of path4.relative(root, path4.dirname(target)).split(path4.sep).filter(Boolean)) {
2213
+ current = path4.join(current, part);
1851
2214
  try {
1852
2215
  if ((await lstat(current)).isSymbolicLink())
1853
2216
  throw new Error(`Credential parent is a symlink: ${current}`);
1854
2217
  } catch (error) {
1855
2218
  if (error.code !== "ENOENT") throw error;
1856
- await mkdir2(current, { recursive: false, mode: 448 });
2219
+ await mkdir3(current, { recursive: false, mode: 448 });
1857
2220
  }
1858
2221
  }
1859
2222
  }
1860
2223
  async function writeManagedPiCredentialFiles(agentDir, files) {
1861
- const root = path3.resolve(agentDir);
2224
+ const root = path4.resolve(agentDir);
1862
2225
  if ((await lstat(root)).isSymbolicLink()) {
1863
2226
  throw new Error(`Managed Pi directory is a symlink: ${root}`);
1864
2227
  }
@@ -1867,25 +2230,25 @@ async function writeManagedPiCredentialFiles(agentDir, files) {
1867
2230
  const relative = normalizeManagedPiCredentialPath(file.path);
1868
2231
  if (seen.has(relative)) throw new Error(`Duplicate credential file path '${relative}'`);
1869
2232
  seen.add(relative);
1870
- const target = path3.resolve(root, relative);
1871
- if (!target.startsWith(`${root}${path3.sep}`))
2233
+ const target = path4.resolve(root, relative);
2234
+ if (!target.startsWith(`${root}${path4.sep}`))
1872
2235
  throw new Error(`Credential path escapes managed directory: ${relative}`);
1873
2236
  await assertNoSymlinkParents(root, target);
1874
- const tmp = path3.join(
1875
- path3.dirname(target),
1876
- `.${path3.basename(target)}.tmp-${process.pid}-${randomUUID()}`
2237
+ const tmp = path4.join(
2238
+ path4.dirname(target),
2239
+ `.${path4.basename(target)}.tmp-${process.pid}-${randomUUID()}`
1877
2240
  );
1878
- await writeFile2(tmp, file.content, { mode: 384, flag: "wx" });
2241
+ await writeFile3(tmp, file.content, { mode: 384, flag: "wx" });
1879
2242
  await chmod(tmp, 384);
1880
- await rename(tmp, target);
2243
+ await rename2(tmp, target);
1881
2244
  await chmod(target, 384);
1882
2245
  }
1883
2246
  }
1884
2247
 
1885
2248
  // src/pi-resource-bundle.ts
1886
2249
  import { randomUUID as randomUUID2 } from "crypto";
1887
- import { mkdir as mkdir3, rename as rename2, rm, writeFile as writeFile3 } from "fs/promises";
1888
- import path4 from "path";
2250
+ import { mkdir as mkdir4, open, readFile, rename as rename3, rm, writeFile as writeFile4 } from "fs/promises";
2251
+ import path5 from "path";
1889
2252
  import {
1890
2253
  createCanonicalPiResourceBundle,
1891
2254
  sha256Digest,
@@ -1895,25 +2258,80 @@ import {
1895
2258
  function fail(message) {
1896
2259
  throw new Error(`Invalid Pi resource bundle: ${message}`);
1897
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();
2273
+ }
2274
+ try {
2275
+ await rename3(staging, pathname);
2276
+ } catch (error) {
2277
+ await rm(staging, { force: true });
2278
+ throw error;
2279
+ }
2280
+ }
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;
2290
+ 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;
2298
+ }
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`);
2303
+ }
2304
+ bundle = input.deliveredBundle ?? Buffer.from(input.archiveBase64, "base64");
2305
+ verifyCanonicalPiResourceBundle(bundle, digest);
2306
+ await atomicWrite(bundlePath, bundle, 384);
2307
+ }
2308
+ const manifest = Buffer.from(
2309
+ `${JSON.stringify({ startRecordId, digest, persistedAt: (/* @__PURE__ */ new Date()).toISOString() })}
2310
+ `,
2311
+ "utf8"
2312
+ );
2313
+ await atomicWrite(path5.join(startsDir, `${startRecordId}.json`), manifest, 384);
2314
+ return { bundle, reused };
2315
+ }
1898
2316
  async function writeExtractedFiles(root, files) {
1899
2317
  for (const file of files) {
1900
- const output = path4.resolve(root, file.path);
1901
- if (path4.relative(root, output).startsWith("..") || path4.isAbsolute(path4.relative(root, output))) {
2318
+ const output = path5.resolve(root, file.path);
2319
+ if (path5.relative(root, output).startsWith("..") || path5.isAbsolute(path5.relative(root, output))) {
1902
2320
  fail(`path escapes materialization root: ${file.path}`);
1903
2321
  }
1904
- await mkdir3(path4.dirname(output), { recursive: true, mode: 448 });
1905
- await writeFile3(output, file.content, { mode: 420, flag: "wx" });
2322
+ await mkdir4(path5.dirname(output), { recursive: true, mode: 448 });
2323
+ await writeFile4(output, file.content, { mode: 420, flag: "wx" });
1906
2324
  }
1907
2325
  }
1908
2326
  async function materializeCanonicalPiResourceBundle(input) {
1909
2327
  const files = verifyCanonicalPiResourceBundle(input.bundle, input.digest);
1910
- const targetDir = path4.resolve(input.targetDir);
1911
- const parent = path4.dirname(targetDir);
1912
- await mkdir3(parent, { recursive: true, mode: 448 });
1913
- const marker = path4.join(targetDir, ".leitwerk-resource-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");
1914
2332
  try {
1915
2333
  const current = await import("fs/promises").then(
1916
- ({ readFile: readFile4 }) => readFile4(marker, "utf8")
2334
+ ({ readFile: readFile5 }) => readFile5(marker, "utf8")
1917
2335
  );
1918
2336
  if (current === `${input.digest}
1919
2337
  `) return { targetDir, reused: true };
@@ -1923,25 +2341,25 @@ async function materializeCanonicalPiResourceBundle(input) {
1923
2341
  } catch (error) {
1924
2342
  if (error.code !== "ENOENT") throw error;
1925
2343
  }
1926
- const staging = path4.join(
2344
+ const staging = path5.join(
1927
2345
  parent,
1928
- `.${path4.basename(targetDir)}.staging-${process.pid}-${randomUUID2()}`
2346
+ `.${path5.basename(targetDir)}.staging-${process.pid}-${randomUUID2()}`
1929
2347
  );
1930
2348
  try {
1931
- await mkdir3(staging, { mode: 448 });
2349
+ await mkdir4(staging, { mode: 448 });
1932
2350
  await writeExtractedFiles(staging, files);
1933
- await writeFile3(path4.join(staging, ".leitwerk-resource-digest"), `${input.digest}
2351
+ await writeFile4(path5.join(staging, ".leitwerk-resource-digest"), `${input.digest}
1934
2352
  `, {
1935
2353
  mode: 384,
1936
2354
  flag: "wx"
1937
2355
  });
1938
- await rename2(staging, targetDir);
2356
+ await rename3(staging, targetDir);
1939
2357
  return { targetDir, reused: false };
1940
2358
  } catch (error) {
1941
2359
  await rm(staging, { recursive: true, force: true });
1942
2360
  if (error.code === "EEXIST") {
1943
2361
  const current = await import("fs/promises").then(
1944
- ({ readFile: readFile4 }) => readFile4(marker, "utf8")
2362
+ ({ readFile: readFile5 }) => readFile5(marker, "utf8")
1945
2363
  );
1946
2364
  if (current === `${input.digest}
1947
2365
  `) return { targetDir, reused: true };
@@ -1968,20 +2386,10 @@ var nodeWorkerRuntimeScheduler = {
1968
2386
 
1969
2387
  // src/input-consumer.ts
1970
2388
  function classifyDeliveryMode(input, sessionHasActiveTurn) {
1971
- if (input.kind === "system_event") {
1972
- return "steer";
1973
- }
1974
- if (sessionHasActiveTurn) {
1975
- return "steer";
1976
- }
1977
- return "prompt";
2389
+ return input.kind === "system_event" || sessionHasActiveTurn ? "steer" : "prompt";
1978
2390
  }
1979
2391
  async function deliverInput(session, input, mode) {
1980
- if (mode === "prompt") {
1981
- await session.prompt(input.bodyMarkdown);
1982
- } else {
1983
- await session.steer(input.bodyMarkdown);
1984
- }
2392
+ await session[mode](input.bodyMarkdown);
1985
2393
  return {
1986
2394
  inputId: input.inputId,
1987
2395
  sequence: input.sequence,
@@ -2122,6 +2530,9 @@ var WorkerIntegrationToolBridge = class {
2122
2530
  }
2123
2531
  };
2124
2532
 
2533
+ // src/pi-event-reporter.ts
2534
+ import { readFiniteNumber as readFiniteNumber2, readNonBlankString } from "@leitwerk-dev/domain";
2535
+
2125
2536
  // src/event-translator.ts
2126
2537
  function translatePiEvent(piEvent, currentSelectedTurnId) {
2127
2538
  return {
@@ -2136,23 +2547,6 @@ function translatePiEvent(piEvent, currentSelectedTurnId) {
2136
2547
  }
2137
2548
 
2138
2549
  // src/pi-event-reporter.ts
2139
- function readPiEventString(data, key) {
2140
- const value = data[key];
2141
- return typeof value === "string" && value.trim() !== "" ? value : null;
2142
- }
2143
- function readPiEventNumber(data, key) {
2144
- const value = data[key];
2145
- if (typeof value === "number" && Number.isFinite(value)) {
2146
- return value;
2147
- }
2148
- if (typeof value === "string" && value.trim() !== "") {
2149
- const parsed = Number(value);
2150
- if (Number.isFinite(parsed)) {
2151
- return parsed;
2152
- }
2153
- }
2154
- return null;
2155
- }
2156
2550
  function createPiEventReporter(options) {
2157
2551
  let currentPiAttempt = 1;
2158
2552
  let currentPiMaxAttempts = null;
@@ -2161,12 +2555,12 @@ function createPiEventReporter(options) {
2161
2555
  currentPiMaxAttempts = null;
2162
2556
  };
2163
2557
  const reportPiError = (event) => {
2164
- const message = readPiEventString(event.data, "message") ?? readPiEventString(event.data, "errorMessage") ?? "Pi reported an error";
2165
- const toolName = readPiEventString(event.data, "toolName");
2166
- const source = readPiEventString(event.data, "source");
2167
- const provider = readPiEventString(event.data, "provider");
2168
- const model = readPiEventString(event.data, "model");
2169
- const stopReason = readPiEventString(event.data, "stopReason");
2558
+ const message = readNonBlankString(event.data.message) ?? readNonBlankString(event.data.errorMessage) ?? "Pi reported an error";
2559
+ const toolName = readNonBlankString(event.data.toolName);
2560
+ const source = readNonBlankString(event.data.source);
2561
+ const provider = readNonBlankString(event.data.provider);
2562
+ const model = readNonBlankString(event.data.model);
2563
+ const stopReason = readNonBlankString(event.data.stopReason);
2170
2564
  options.reporter.workerError({
2171
2565
  level: "error",
2172
2566
  code: toolName || source === "tool" ? "pi.tool_error" : "pi.request_failed",
@@ -2186,12 +2580,12 @@ function createPiEventReporter(options) {
2186
2580
  });
2187
2581
  };
2188
2582
  const reportPiRetryLifecycle = (event) => {
2189
- const attempt = readPiEventNumber(event.data, "attempt");
2190
- const maxAttempts = readPiEventNumber(event.data, "maxAttempts");
2191
- const delayMs = readPiEventNumber(event.data, "delayMs");
2192
- const errorMessage = readPiEventString(event.data, "errorMessage");
2193
- const finalError = readPiEventString(event.data, "finalError");
2194
- const message = readPiEventString(event.data, "message") ?? (event.type === "retry.start" ? "Pi scheduled an automatic retry" : event.data.success === true ? "Pi retry sequence succeeded" : "Pi retry sequence ended");
2583
+ const attempt = readFiniteNumber2(event.data.attempt);
2584
+ const maxAttempts = readFiniteNumber2(event.data.maxAttempts);
2585
+ const delayMs = readFiniteNumber2(event.data.delayMs);
2586
+ const errorMessage = readNonBlankString(event.data.errorMessage);
2587
+ const finalError = readNonBlankString(event.data.finalError);
2588
+ const message = readNonBlankString(event.data.message) ?? (event.type === "retry.start" ? "Pi scheduled an automatic retry" : event.data.success === true ? "Pi retry sequence succeeded" : "Pi retry sequence ended");
2195
2589
  const success = event.data.success === true;
2196
2590
  options.reporter.workerTrace({
2197
2591
  level: event.type === "retry.end" && success ? "info" : "warn",
@@ -2253,13 +2647,9 @@ function createPiEventReporter(options) {
2253
2647
  );
2254
2648
  options.emitExtensionEvent?.("worker.pi_event", payload);
2255
2649
  });
2256
- piHandle.subscribeDiagnostics?.((diagnostic) => {
2257
- reportPiDiagnostic(diagnostic);
2258
- });
2650
+ piHandle.subscribeDiagnostics?.(reportPiDiagnostic);
2259
2651
  },
2260
- resetRetryState() {
2261
- resetPiRetryState();
2262
- }
2652
+ resetRetryState: resetPiRetryState
2263
2653
  };
2264
2654
  }
2265
2655
 
@@ -2312,7 +2702,7 @@ function resolveRootEntryIdFromHandle(piHandle) {
2312
2702
  const currentLeafId = piHandle.getLeafId();
2313
2703
  const currentBranch = piHandle.getBranch(currentLeafId ?? void 0);
2314
2704
  const topLevelNodes = piHandle.getTree();
2315
- return resolveRootEntryId({ currentLeafId, currentBranch, topLevelNodes });
2705
+ return resolveRootEntryId({ currentBranch, topLevelNodes });
2316
2706
  }
2317
2707
  function resolveContextAwareTurnStartSelection(input) {
2318
2708
  const authoredSelection = resolveProcessTurnStartSelection(input.turnDef);
@@ -2332,11 +2722,7 @@ function resolveContextAwareTurnStartSelection(input) {
2332
2722
  }
2333
2723
  function planTurnTreeExecution(input) {
2334
2724
  const startTarget = resolveProcessTurnStartTarget({
2335
- selection: resolveContextAwareTurnStartSelection({
2336
- turnDef: input.turnDef,
2337
- preTurnStartSelection: input.preTurnStartSelection,
2338
- hasPreTurnTargetedInputs: input.hasPreTurnTargetedInputs
2339
- }),
2725
+ selection: resolveContextAwareTurnStartSelection(input),
2340
2726
  branchType: input.turnDef.branchType,
2341
2727
  currentLeafId: input.currentLeafId,
2342
2728
  rootEntryId: input.rootEntryId,
@@ -2353,18 +2739,10 @@ function planTurnTreeExecution(input) {
2353
2739
  };
2354
2740
  }
2355
2741
  async function positionHandleForTurn(piHandle, plan) {
2356
- switch (plan.startTarget.kind) {
2357
- case "current_leaf": {
2358
- return;
2359
- }
2360
- case "entry": {
2361
- await piHandle.branch(plan.startTarget.entryId);
2362
- return;
2363
- }
2364
- case "root": {
2365
- await piHandle.branchFromRoot();
2366
- return;
2367
- }
2742
+ if (plan.startTarget.kind === "entry") {
2743
+ await piHandle.branch(plan.startTarget.entryId);
2744
+ } else if (plan.startTarget.kind === "root") {
2745
+ await piHandle.branchFromRoot();
2368
2746
  }
2369
2747
  }
2370
2748
  async function restoreHandleAfterTurn(piHandle, plan) {
@@ -2473,31 +2851,82 @@ function createWorkerIpcReporter(options) {
2473
2851
  options.emitExtensionEvent?.("worker.event", payload);
2474
2852
  return payload;
2475
2853
  };
2854
+ const diagnosticReporter = (eventType) => (input, selectedTurnId = null) => {
2855
+ const payload = workerEvent(eventType, buildWorkerDiagnosticPayload(input), selectedTurnId);
2856
+ options.emitExtensionEvent?.(eventType, payload);
2857
+ };
2476
2858
  return {
2477
2859
  project,
2478
2860
  workerEvent,
2479
- workerTrace(input, selectedTurnId = null) {
2480
- const payload = workerEvent(
2481
- "worker.trace",
2482
- buildWorkerDiagnosticPayload(input),
2483
- selectedTurnId
2484
- );
2485
- options.emitExtensionEvent?.("worker.trace", payload);
2486
- },
2487
- workerError(input, selectedTurnId = null) {
2488
- const payload = workerEvent(
2489
- "worker.error",
2490
- buildWorkerDiagnosticPayload(input),
2491
- selectedTurnId
2492
- );
2493
- options.emitExtensionEvent?.("worker.error", payload);
2494
- }
2861
+ workerTrace: diagnosticReporter("worker.trace"),
2862
+ workerError: diagnosticReporter("worker.error")
2495
2863
  };
2496
2864
  }
2497
2865
 
2498
2866
  // src/runtime/bootstrap-session.ts
2499
- import { readFile as readFile2 } from "fs/promises";
2500
- import path8 from "path";
2867
+ import { readFile as readFile3 } from "fs/promises";
2868
+ import path9 from "path";
2869
+
2870
+ // src/docker-registry-credentials.ts
2871
+ import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "fs";
2872
+ import {
2873
+ dockerRegistryCredentialSchema
2874
+ } from "@leitwerk-dev/worker-protocol";
2875
+ import { is } from "valibot";
2876
+ var DockerRegistryCredentials = class {
2877
+ #directory;
2878
+ #previousConfig;
2879
+ #onExit = () => this.dispose();
2880
+ install(credentials, dockerEnabled) {
2881
+ this.dispose();
2882
+ if (!dockerEnabled) {
2883
+ if (credentials.length)
2884
+ throw new Error("Docker credentials require a Docker-enabled process");
2885
+ return;
2886
+ }
2887
+ const auths = /* @__PURE__ */ Object.create(null);
2888
+ for (const credential of credentials) {
2889
+ if (!is(dockerRegistryCredentialSchema, credential))
2890
+ throw new Error("Invalid Docker registry credentials");
2891
+ if (Object.hasOwn(auths, credential.registry))
2892
+ throw new Error("Duplicate Docker registry credentials");
2893
+ auths[credential.registry] = {
2894
+ auth: Buffer.from(`${credential.username}:${credential.password}`).toString("base64")
2895
+ };
2896
+ }
2897
+ try {
2898
+ this.#directory = mkdtempSync("/tmp/leitwerk-docker-auth-");
2899
+ chmodSync(this.#directory, 448);
2900
+ mkdirSync(`${this.#directory}/auth`, { mode: 448 });
2901
+ writeFileSync(`${this.#directory}/auth/config.json`, JSON.stringify({ auths }), {
2902
+ mode: 384,
2903
+ flag: "wx"
2904
+ });
2905
+ this.#previousConfig = process.env.DOCKER_CONFIG;
2906
+ process.env.DOCKER_CONFIG = `${this.#directory}/auth`;
2907
+ if (!process.env.BUILDX_CONFIG) {
2908
+ mkdirSync(`${this.#directory}/buildx`, { mode: 448 });
2909
+ process.env.BUILDX_CONFIG = `${this.#directory}/buildx`;
2910
+ }
2911
+ process.once("exit", this.#onExit);
2912
+ } catch {
2913
+ this.dispose();
2914
+ throw new Error("Cannot materialize private Docker credentials");
2915
+ }
2916
+ }
2917
+ dispose() {
2918
+ process.off("exit", this.#onExit);
2919
+ if (!this.#directory) return;
2920
+ if (process.env.BUILDX_CONFIG === `${this.#directory}/buildx`) delete process.env.BUILDX_CONFIG;
2921
+ if (process.env.DOCKER_CONFIG === `${this.#directory}/auth`) {
2922
+ if (this.#previousConfig === void 0) delete process.env.DOCKER_CONFIG;
2923
+ else process.env.DOCKER_CONFIG = this.#previousConfig;
2924
+ }
2925
+ rmSync(this.#directory, { recursive: true, force: true });
2926
+ this.#directory = void 0;
2927
+ this.#previousConfig = void 0;
2928
+ }
2929
+ };
2501
2930
 
2502
2931
  // src/worker-start-payload.ts
2503
2932
  function isLlmWorkerStartPayload(payload) {
@@ -2505,13 +2934,16 @@ function isLlmWorkerStartPayload(payload) {
2505
2934
  }
2506
2935
 
2507
2936
  // src/runtime/bootstrap.ts
2508
- import path7 from "path";
2937
+ import path8 from "path";
2938
+ import {
2939
+ readNonBlankString as readNonEmptyString2
2940
+ } from "@leitwerk-dev/domain";
2941
+ import { repositoryHttpsUrl } from "@leitwerk-dev/process-sdk";
2509
2942
  import { createTemplateContext, resolveProcessPiConfig } from "@leitwerk-dev/process-sdk/pi-config";
2510
2943
 
2511
2944
  // src/managed-pi-bootstrap.ts
2512
- import { lstat as lstat2, readFile } from "fs/promises";
2513
- import path5 from "path";
2514
- import { VERSION as PI_VERSION } from "@earendil-works/pi-coding-agent";
2945
+ import { lstat as lstat2, readFile as readFile2 } from "fs/promises";
2946
+ import path6 from "path";
2515
2947
  import {
2516
2948
  canonicalJsonEqual,
2517
2949
  IPC_PROTOCOL_VERSION,
@@ -2541,7 +2973,8 @@ function assertModelMatchesStart(manifest, start) {
2541
2973
  }
2542
2974
  }
2543
2975
  }
2544
- function assertCompatibility(manifest) {
2976
+ async function assertCompatibility(manifest) {
2977
+ const { VERSION: PI_VERSION } = await import("@earendil-works/pi-coding-agent");
2545
2978
  if (manifest.compatibility.workerApiVersion !== WORKER_API_VERSION) {
2546
2979
  fail2(
2547
2980
  `server snapshot worker API version '${manifest.compatibility.workerApiVersion}' does not match local worker API version '${WORKER_API_VERSION}'`
@@ -2559,14 +2992,14 @@ function assertCompatibility(manifest) {
2559
2992
  }
2560
2993
  }
2561
2994
  async function readAndValidateManagedPiResourceManifest(input) {
2562
- const marker = await readFile(path5.join(input.agentDir, ".leitwerk-resource-digest"), "utf8");
2995
+ const marker = await readFile2(path6.join(input.agentDir, ".leitwerk-resource-digest"), "utf8");
2563
2996
  if (marker !== `${input.resourceDigest}
2564
2997
  `) {
2565
2998
  fail2("materialized resource digest marker does not match the delivered bundle");
2566
2999
  }
2567
3000
  let parsed;
2568
3001
  try {
2569
- parsed = JSON.parse(await readFile(path5.join(input.agentDir, "generated.json"), "utf8"));
3002
+ parsed = JSON.parse(await readFile2(path6.join(input.agentDir, "generated.json"), "utf8"));
2570
3003
  } catch (error) {
2571
3004
  throw new Error("Invalid managed Pi resource snapshot: generated.json is unreadable", {
2572
3005
  cause: error
@@ -2574,7 +3007,7 @@ async function readAndValidateManagedPiResourceManifest(input) {
2574
3007
  }
2575
3008
  const manifest = parsePiResourceManifest(parsed);
2576
3009
  assertModelMatchesStart(manifest, input.start);
2577
- assertCompatibility(manifest);
3010
+ await assertCompatibility(manifest);
2578
3011
  assertJsonEqual(manifest.providerOptions, input.start.providerOptions, "providerOptions");
2579
3012
  assertJsonEqual(
2580
3013
  manifest.providerWorkerConfig,
@@ -2583,7 +3016,7 @@ async function readAndValidateManagedPiResourceManifest(input) {
2583
3016
  );
2584
3017
  let settings;
2585
3018
  try {
2586
- settings = JSON.parse(await readFile(path5.join(input.agentDir, "settings.json"), "utf8"));
3019
+ settings = JSON.parse(await readFile2(path6.join(input.agentDir, "settings.json"), "utf8"));
2587
3020
  } catch (error) {
2588
3021
  throw new Error("Invalid managed Pi resource snapshot: settings.json is unreadable", {
2589
3022
  cause: error
@@ -2634,18 +3067,18 @@ function buildManagedPiCredentialFiles(input) {
2634
3067
  }
2635
3068
  async function assertManagedPiCredentialFiles(input) {
2636
3069
  for (const credentialPath of input.manifest.declaredCredentialPaths) {
2637
- const target = path5.join(input.agentDir, credentialPath);
2638
- const stat3 = await lstat2(target).catch(() => null);
2639
- if (!stat3?.isFile() || stat3.isSymbolicLink()) {
3070
+ const target = path6.join(input.agentDir, credentialPath);
3071
+ const stat2 = await lstat2(target).catch(() => null);
3072
+ if (!stat2?.isFile() || stat2.isSymbolicLink()) {
2640
3073
  throw new Error(`Declared credential file '${credentialPath}' is missing or unsafe`);
2641
3074
  }
2642
- if ((stat3.mode & 511) !== 384) {
3075
+ if ((stat2.mode & 511) !== 384) {
2643
3076
  throw new Error(`Declared credential file '${credentialPath}' must have mode 0600`);
2644
3077
  }
2645
3078
  }
2646
3079
  if (input.credential && input.manifest.declaredCredentialPaths.includes("auth.json")) {
2647
3080
  const auth = record(
2648
- JSON.parse(await readFile(path5.join(input.agentDir, "auth.json"), "utf8")),
3081
+ JSON.parse(await readFile2(path6.join(input.agentDir, "auth.json"), "utf8")),
2649
3082
  "auth.json"
2650
3083
  );
2651
3084
  if (input.credential.values.apiKey) {
@@ -2950,7 +3383,8 @@ function parseProcessSemanticEntryRefsFromStateJson(stateJson) {
2950
3383
  }
2951
3384
 
2952
3385
  // src/workspace/run-root.ts
2953
- import path6 from "path";
3386
+ import path7 from "path";
3387
+ import { isPathInside } from "@leitwerk-dev/process-sdk";
2954
3388
 
2955
3389
  // src/workspace/manifest.ts
2956
3390
  import * as v from "valibot";
@@ -2985,14 +3419,14 @@ var componentManifestJsonSchema = v.pipe(v.string(), v.parseJson(), componentMan
2985
3419
  function formatManifestValidationError(issues) {
2986
3420
  const issue = issues[0];
2987
3421
  if (issue?.type === "parse_json") return "Invalid JSON";
2988
- const path13 = issue ? v.getDotPath(issue) : null;
2989
- if (!path13) return "Manifest must be a JSON object";
2990
- if (path13 === "version") return "Unsupported manifest version";
2991
- if (path13 === "instanceId") return "Invalid instanceId";
2992
- if (path13 === "createdAt") return "Invalid createdAt";
2993
- if (path13 === "components") return "components must be an array";
2994
- if (path13.match(/^components\.\d+$/)) return "Invalid component entry";
2995
- const componentField = path13.match(/^components\.\d+\.([^.]*)$/)?.[1];
3422
+ const path14 = issue ? v.getDotPath(issue) : null;
3423
+ if (!path14) return "Manifest must be a JSON object";
3424
+ if (path14 === "version") return "Unsupported manifest version";
3425
+ if (path14 === "instanceId") return "Invalid instanceId";
3426
+ if (path14 === "createdAt") return "Invalid createdAt";
3427
+ if (path14 === "components") return "components must be an array";
3428
+ if (path14.match(/^components\.\d+$/)) return "Invalid component entry";
3429
+ const componentField = path14.match(/^components\.\d+\.([^.]*)$/)?.[1];
2996
3430
  if (componentField) return `Invalid component field: ${componentField}`;
2997
3431
  return issue?.message ? `Invalid manifest: ${issue.message}` : "Invalid manifest";
2998
3432
  }
@@ -3049,48 +3483,38 @@ function aggregateAgentsMd(sources) {
3049
3483
  `;
3050
3484
  }
3051
3485
  function collectSkills(sources) {
3052
- const byId = /* @__PURE__ */ new Map();
3053
- for (const s of sources) {
3054
- const list = byId.get(s.skillId);
3055
- if (list) {
3056
- list.push(s);
3057
- } else {
3058
- byId.set(s.skillId, [s]);
3059
- }
3060
- }
3061
3486
  const out = /* @__PURE__ */ new Map();
3062
- for (const [skillId, group] of byId) {
3063
- group.sort((a, b) => a.componentKey.localeCompare(b.componentKey));
3064
- const winner = group[0];
3065
- out.set(skillId, {
3066
- content: winner.content,
3067
- source: winner.componentKey
3068
- });
3487
+ for (const { skillId, componentKey, content } of sources) {
3488
+ const winner = out.get(skillId);
3489
+ if (!winner || componentKey.localeCompare(winner.source) < 0) {
3490
+ out.set(skillId, { content, source: componentKey });
3491
+ }
3069
3492
  }
3070
3493
  return out;
3071
3494
  }
3072
3495
 
3073
3496
  // src/workspace/run-root.ts
3074
- var MANIFEST_REL = path6.join(".leitwerk", "components.json");
3497
+ var RunRootPreparationError = class extends Error {
3498
+ errors;
3499
+ constructor(errors) {
3500
+ super(`Workspace preparation failed: ${errors.join("; ")}`);
3501
+ this.name = "RunRootPreparationError";
3502
+ this.errors = [...errors];
3503
+ }
3504
+ };
3505
+ var MANIFEST_REL = path7.join(".leitwerk", "components.json");
3075
3506
  var AGGREGATED_AGENTS_REL2 = "AGENTS.md";
3076
- var SKILLS_DIR_REL = path6.join(".leitwerk", "skills");
3507
+ var SKILLS_DIR_REL = path7.join(".leitwerk", "skills");
3077
3508
  var SKILL_GLOB = "**/.cursor/skills/**/SKILL.md";
3078
3509
  var AGENTS_GLOB = "**/AGENTS.md";
3079
- function isPathInside(parent, child) {
3080
- const relative = path6.relative(parent, child);
3081
- return relative !== "" && relative !== ".." && !relative.startsWith(`..${path6.sep}`) && !path6.isAbsolute(relative);
3082
- }
3083
- function safeJoinInsideWorkspace(workspaceRoot, childPath) {
3084
- const root = path6.resolve(workspaceRoot);
3085
- const target = path6.resolve(root, childPath);
3510
+ function componentDir(workspaceRoot, childPath) {
3511
+ const root = path7.resolve(workspaceRoot);
3512
+ const target = path7.resolve(root, childPath);
3086
3513
  if (!isPathInside(root, target)) {
3087
3514
  throw new Error(`Component key '${childPath}' resolves outside workspace root '${root}'`);
3088
3515
  }
3089
3516
  return target;
3090
3517
  }
3091
- function componentDir(workspaceRoot, key) {
3092
- return safeJoinInsideWorkspace(workspaceRoot, key);
3093
- }
3094
3518
  function skillIdFromSkillPath(filePath) {
3095
3519
  const normalized = filePath.replace(/\\/g, "/");
3096
3520
  const m = normalized.match(/\.cursor\/skills\/([^/]+)\/SKILL\.md$/);
@@ -3107,12 +3531,10 @@ async function materializeComponentEntry(plan, comp, git) {
3107
3531
  const dir = componentDir(plan.workspaceRoot, comp.key);
3108
3532
  await git.clone(comp.repoLocator, dir);
3109
3533
  await git.checkout(dir, comp.baseBranch);
3110
- if (await git.branchExists(dir, comp.workBranch)) {
3111
- await git.checkout(dir, comp.workBranch);
3112
- } else {
3534
+ if (!await git.branchExists(dir, comp.workBranch)) {
3113
3535
  await git.createBranch(dir, comp.workBranch, comp.baseBranch);
3114
- await git.checkout(dir, comp.workBranch);
3115
3536
  }
3537
+ await git.checkout(dir, comp.workBranch);
3116
3538
  return {
3117
3539
  key: comp.key,
3118
3540
  repoLocator: comp.repoLocator,
@@ -3183,7 +3605,7 @@ async function writeAggregatedArtifacts(plan, git, manifest, agentsMd, skillsMap
3183
3605
  await git.writeFile(root, MANIFEST_REL, serializeManifest(manifest));
3184
3606
  await git.writeFile(root, AGGREGATED_AGENTS_REL2, agentsMd);
3185
3607
  for (const [skillId, { content }] of skillsMap) {
3186
- const rel = path6.join(SKILLS_DIR_REL, `${skillId}.md`);
3608
+ const rel = path7.join(SKILLS_DIR_REL, `${skillId}.md`);
3187
3609
  await git.writeFile(root, rel, content);
3188
3610
  }
3189
3611
  }
@@ -3201,42 +3623,28 @@ async function finalizeRunRoot(plan, git, entries, errors) {
3201
3623
  } catch (e) {
3202
3624
  errors.push(`write: ${e instanceof Error ? e.message : String(e)}`);
3203
3625
  }
3204
- return { manifest, aggregatedAgentsMdSources, loadedSkills };
3205
- }
3206
- async function materializeRunRoot(plan, git) {
3207
- const errors = [];
3208
- const entries = await collectMaterializedEntries(plan, git, errors);
3209
- const { manifest, aggregatedAgentsMdSources, loadedSkills } = await finalizeRunRoot(
3210
- plan,
3211
- git,
3212
- entries,
3213
- errors
3214
- );
3215
- const ok = errors.length === 0 && plan.components.length === entries.length;
3626
+ const expectedKeys = new Set(plan.components.map((component) => component.key));
3627
+ const hasAllExpectedEntries = entries.length === expectedKeys.size && [...expectedKeys].every((key) => entries.some((entry) => entry.key === key));
3628
+ if (errors.length > 0 || !hasAllExpectedEntries) {
3629
+ throw new RunRootPreparationError(errors);
3630
+ }
3216
3631
  return {
3217
- ok,
3632
+ ok: true,
3218
3633
  manifest,
3219
3634
  aggregatedAgentsMdSources,
3220
3635
  loadedSkills,
3221
3636
  errors
3222
3637
  };
3223
3638
  }
3639
+ async function materializeRunRoot(plan, git) {
3640
+ const errors = [];
3641
+ const entries = await collectMaterializedEntries(plan, git, errors);
3642
+ return finalizeRunRoot(plan, git, entries, errors);
3643
+ }
3224
3644
  async function validateRunRoot(workspaceRoot, serverProjects, git) {
3225
3645
  const raw = await git.readFile(workspaceRoot, MANIFEST_REL);
3226
- if (raw === null) {
3227
- return {
3228
- valid: false,
3229
- diff: {
3230
- stale: [],
3231
- missing: serverProjects.map((p) => p.key),
3232
- extra: [],
3233
- unchanged: []
3234
- },
3235
- existingManifest: null
3236
- };
3237
- }
3238
- const parsed = deserializeManifest(raw);
3239
- if (!parsed.ok) {
3646
+ const parsed = raw === null ? null : deserializeManifest(raw);
3647
+ if (!parsed?.ok) {
3240
3648
  return {
3241
3649
  valid: false,
3242
3650
  diff: {
@@ -3266,54 +3674,45 @@ async function repairRunRoot(_workspaceRoot, validation, plan, git) {
3266
3674
  (componentKey) => toRepair.has(componentKey),
3267
3675
  (componentKey) => validation.existingManifest?.components.find((component) => component.key === componentKey) ?? null
3268
3676
  );
3269
- const { manifest, aggregatedAgentsMdSources, loadedSkills } = await finalizeRunRoot(
3270
- plan,
3271
- git,
3272
- manifestEntries,
3273
- errors
3274
- );
3275
- const expectedKeys = new Set(plan.components.map((c) => c.key));
3276
- const ok = errors.length === 0 && manifestEntries.length === plan.components.length && [...expectedKeys].every((k) => manifestEntries.some((e) => e.key === k));
3277
- return {
3278
- ok,
3279
- manifest,
3280
- aggregatedAgentsMdSources,
3281
- loadedSkills,
3282
- errors
3283
- };
3677
+ return finalizeRunRoot(plan, git, manifestEntries, errors);
3284
3678
  }
3285
3679
 
3286
3680
  // src/runtime/bootstrap.ts
3287
- function readNonEmptyString2(value) {
3288
- return typeof value === "string" && value.trim() !== "" ? value : null;
3289
- }
3290
3681
  function withoutCredentialValues(payload) {
3291
- const withoutRepositoryCredentials = {
3682
+ const withoutCredentials = {
3292
3683
  ...payload,
3293
- repositoryCredentials: void 0
3684
+ repositoryCredentials: void 0,
3685
+ dockerRegistryCredentials: void 0
3294
3686
  };
3295
- if (!isLlmWorkerStartPayload(payload) || !payload.bootstrap.credential) {
3296
- return withoutRepositoryCredentials;
3687
+ if (!isLlmWorkerStartPayload(withoutCredentials) || !withoutCredentials.bootstrap.credential) {
3688
+ return withoutCredentials;
3297
3689
  }
3298
3690
  return {
3299
- ...payload,
3300
- repositoryCredentials: void 0,
3691
+ ...withoutCredentials,
3301
3692
  bootstrap: {
3302
- ...payload.bootstrap,
3303
- credential: { ...payload.bootstrap.credential, values: {} }
3693
+ ...withoutCredentials.bootstrap,
3694
+ credential: { ...withoutCredentials.bootstrap.credential, values: {} }
3304
3695
  }
3305
3696
  };
3306
3697
  }
3307
3698
  function validateRepositoryCredentials(input) {
3308
3699
  const credentialKeys = /* @__PURE__ */ new Set();
3309
3700
  for (const credential of input.credentials) {
3310
- if (!input.projectKeys.has(credential.projectKey) || credential.kind !== "git_ssh") {
3701
+ if (!input.projectKeys.has(credential.projectKey) || !["git_ssh", "git_https"].includes(credential.kind)) {
3311
3702
  throw new Error(`Repository credential does not match project '${credential.projectKey}'`);
3312
3703
  }
3313
3704
  if (credentialKeys.has(credential.projectKey)) {
3314
3705
  throw new Error(`Duplicate repository credential for project '${credential.projectKey}'`);
3315
3706
  }
3316
3707
  credentialKeys.add(credential.projectKey);
3708
+ if (credential.kind === "git_https") {
3709
+ const project = input.projects?.find((project2) => project2.key === credential.projectKey);
3710
+ if (!project || repositoryHttpsUrl(credential.repositoryUrl).href !== project.repoLocator || !credential.username || !credential.password || /[\r\n\0]/.test(credential.username + credential.password)) {
3711
+ throw new Error(
3712
+ `Invalid HTTPS credential scope or material for project '${credential.projectKey}'`
3713
+ );
3714
+ }
3715
+ }
3317
3716
  }
3318
3717
  const identities = (items) => new Set(items.map((item) => `${item.projectKey}:${item.kind}:${item.credentialRef}`));
3319
3718
  const delivered = identities(input.credentials);
@@ -3323,41 +3722,27 @@ function validateRepositoryCredentials(input) {
3323
3722
  }
3324
3723
  }
3325
3724
  function shouldPreservePersistedLeafForActiveTurnResume(input) {
3326
- if (!input.payload.resume) {
3327
- return false;
3328
- }
3329
- if (!readNonEmptyString2(input.processSnapshot.selectedTurnId)) {
3330
- return false;
3331
- }
3332
- if (input.processSnapshot.currentExecution?.kind !== "worker_start" || input.processSnapshot.currentExecution.id !== input.payload.turnStart.id || input.payload.turnStart.state.kind !== "accepted" || !readNonEmptyString2(input.payload.turnStart.state.turnRecordId)) {
3333
- return false;
3334
- }
3335
- if (readNonEmptyString2(input.processSnapshot.metadata?.continueFromPiEntryId)) {
3336
- return false;
3337
- }
3338
- if (readNonEmptyString2(input.processSnapshot.metadata?.retryForkPiEntryId)) {
3339
- return false;
3340
- }
3341
- return true;
3725
+ const { payload, processSnapshot } = input;
3726
+ return payload.resume && readNonEmptyString2(processSnapshot.selectedTurnId) !== null && processSnapshot.currentExecution?.kind === "worker_start" && processSnapshot.currentExecution.id === payload.turnStart.id && payload.turnStart.state.kind === "accepted" && readNonEmptyString2(payload.turnStart.state.turnRecordId) !== null && readNonEmptyString2(processSnapshot.metadata?.continueFromPiEntryId) === null && readNonEmptyString2(processSnapshot.metadata?.retryForkPiEntryId) === null;
3342
3727
  }
3343
3728
  function resolveResumeLeafEntryCandidates(processSnapshot, payload) {
3344
- const candidates = [];
3345
- const continueFromPiEntryId = typeof processSnapshot.metadata?.continueFromPiEntryId === "string" ? processSnapshot.metadata.continueFromPiEntryId : null;
3346
- if (continueFromPiEntryId) {
3347
- candidates.push({ entryId: continueFromPiEntryId, source: "continue" });
3348
- }
3349
- const retryForkPiEntryId = typeof processSnapshot.metadata?.retryForkPiEntryId === "string" ? processSnapshot.metadata.retryForkPiEntryId : null;
3350
- if (retryForkPiEntryId && retryForkPiEntryId !== continueFromPiEntryId) {
3351
- candidates.push({ entryId: retryForkPiEntryId, source: "retry" });
3352
- }
3353
3729
  const semanticEntryRefs = parseProcessSemanticEntryRefsFromStateJson(processSnapshot.stateJson);
3354
- const stateLeafId = payload.resume ? semanticEntryRefs.currentPrimaryPathLeaf?.entryId ?? null : null;
3355
- if (stateLeafId && stateLeafId !== continueFromPiEntryId && stateLeafId !== retryForkPiEntryId) {
3356
- candidates.push({ entryId: stateLeafId, source: "state" });
3357
- }
3358
- const payloadLeafId = payload.resume ? payload.resumeLeafEntryId ?? null : null;
3359
- if (payloadLeafId && payloadLeafId !== continueFromPiEntryId && payloadLeafId !== retryForkPiEntryId && payloadLeafId !== stateLeafId) {
3360
- candidates.push({ entryId: payloadLeafId, source: "payload" });
3730
+ const candidates = [];
3731
+ for (const [source, entryId] of [
3732
+ [
3733
+ "continue",
3734
+ typeof processSnapshot.metadata?.continueFromPiEntryId === "string" ? processSnapshot.metadata.continueFromPiEntryId : null
3735
+ ],
3736
+ [
3737
+ "retry",
3738
+ typeof processSnapshot.metadata?.retryForkPiEntryId === "string" ? processSnapshot.metadata.retryForkPiEntryId : null
3739
+ ],
3740
+ ["state", payload.resume ? semanticEntryRefs.currentPrimaryPathLeaf?.entryId : null],
3741
+ ["payload", payload.resume ? payload.resumeLeafEntryId : null]
3742
+ ]) {
3743
+ if (entryId && !candidates.some((candidate) => candidate.entryId === entryId)) {
3744
+ candidates.push({ entryId, source });
3745
+ }
3361
3746
  }
3362
3747
  return candidates;
3363
3748
  }
@@ -3491,6 +3876,13 @@ async function bootstrapWorkerRuntime(deps) {
3491
3876
  const paramsJson = deps.payload.processSnapshot.paramsJson ?? null;
3492
3877
  const stateJson = deps.payload.processSnapshot.stateJson ?? null;
3493
3878
  const resolvedWorkerProcess = deps.resolveWorkerProcess ? await deps.resolveWorkerProcess(processId, { paramsJson, stateJson }) : void 0;
3879
+ const dockerCredentials = deps.payload.dockerRegistryCredentials ?? [];
3880
+ if (dockerCredentials.length && !deps.configureDockerCredentials)
3881
+ throw new Error("Docker credential delivery is unavailable");
3882
+ deps.configureDockerCredentials?.(
3883
+ dockerCredentials,
3884
+ resolvedWorkerProcess?.runtime?.docker === true
3885
+ );
3494
3886
  const projectSnapshots = projectSnapshotsFromPayload(deps.payload.projectSnapshots);
3495
3887
  const repositoryCredentials = deps.payload.repositoryCredentials ?? [];
3496
3888
  const declaredRequirements = resolvedWorkerProcess?.repositoryCredentials?.({
@@ -3500,7 +3892,8 @@ async function bootstrapWorkerRuntime(deps) {
3500
3892
  validateRepositoryCredentials({
3501
3893
  credentials: repositoryCredentials,
3502
3894
  requirements: declaredRequirements,
3503
- projectKeys: new Set(projectSnapshots.map((project) => project.key))
3895
+ projectKeys: new Set(projectSnapshots.map((project) => project.key)),
3896
+ projects: projectSnapshots
3504
3897
  });
3505
3898
  deps.gitOps.configureRepositoryCredentials?.(repositoryCredentials);
3506
3899
  const processSnapshot = buildProcessSnapshotSeed(processId, deps.payload.processSnapshot);
@@ -3513,18 +3906,9 @@ async function bootstrapWorkerRuntime(deps) {
3513
3906
  workBranch: project.workBranch ?? ""
3514
3907
  }));
3515
3908
  const plan = planRunRoot(workspaceRoot, deps.instanceId, runRootProjects);
3516
- let aggregatedAgentsMdSources = [];
3517
- let loadedSkills = [];
3518
- if (!deps.payload.resume) {
3519
- const materialized = await materializeRunRoot(plan, deps.gitOps);
3520
- aggregatedAgentsMdSources = materialized.aggregatedAgentsMdSources;
3521
- loadedSkills = materialized.loadedSkills;
3522
- } else {
3523
- const validation = await validateRunRoot(workspaceRoot, runRootProjects, deps.gitOps);
3524
- const repaired = await repairRunRoot(workspaceRoot, validation, plan, deps.gitOps);
3525
- aggregatedAgentsMdSources = repaired.aggregatedAgentsMdSources;
3526
- loadedSkills = repaired.loadedSkills;
3527
- }
3909
+ const runRootPreparation = deps.payload.resume ? validateRunRoot(workspaceRoot, runRootProjects, deps.gitOps).then(
3910
+ (validation) => repairRunRoot(workspaceRoot, validation, plan, deps.gitOps)
3911
+ ) : materializeRunRoot(plan, deps.gitOps);
3528
3912
  const resolvedPiConfig = llmPayload ? resolveProcessPiConfig({
3529
3913
  processId,
3530
3914
  processPiConfig: resolvedWorkerProcess?.piConfig,
@@ -3536,7 +3920,7 @@ async function bootstrapWorkerRuntime(deps) {
3536
3920
  projects: projectSnapshots
3537
3921
  })
3538
3922
  }) : { systemPrompt: "", availableToolNames: [] };
3539
- const sessionCwd = resolvedPiConfig.sessionCwd ? path7.resolve(workspaceRoot, resolvedPiConfig.sessionCwd) : workspaceRoot;
3923
+ const sessionCwd = resolvedPiConfig.sessionCwd ? path8.resolve(workspaceRoot, resolvedPiConfig.sessionCwd) : workspaceRoot;
3540
3924
  const pendingInputs = (deps.payload.pendingInputs ?? []).map(inputDeliveryToItem);
3541
3925
  const diagnostics = [];
3542
3926
  let managedAgentDir = null;
@@ -3545,6 +3929,26 @@ async function bootstrapWorkerRuntime(deps) {
3545
3929
  let loadedAgentsFiles = [];
3546
3930
  let loadedSkillFiles = [];
3547
3931
  let receipt;
3932
+ const runRoot = await runRootPreparation;
3933
+ let preparedTools;
3934
+ if (resolvedWorkerProcess?.runtime?.developmentTools) {
3935
+ if (!deps.payload.developmentTools) {
3936
+ throw new Error("Development-tool settings are unavailable for an opted-in process");
3937
+ }
3938
+ preparedTools = await (deps.developmentTools ?? new MiseDevelopmentToolEnvironment()).prepare({
3939
+ config: deps.payload.developmentTools,
3940
+ repositories: projectSnapshots.map((project) => ({
3941
+ repositoryKey: project.key,
3942
+ workingDirectory: path8.join(workspaceRoot, project.key)
3943
+ })),
3944
+ signal: deps.toolPreparationSignal,
3945
+ onProgress: deps.onToolPreparationProgress,
3946
+ onDiagnosticTrace: deps.onToolDiagnosticTrace
3947
+ });
3948
+ for (const [key, value] of Object.entries(preparedTools.commandEnvironment)) {
3949
+ if (key === "PATH" || key.startsWith("MISE_")) process.env[key] = value;
3950
+ }
3951
+ }
3548
3952
  if (llmPayload) {
3549
3953
  const start = deps.payload.turnStart.state.kind === "starting" || deps.payload.turnStart.state.kind === "accepted" ? deps.payload.turnStart.state.start : null;
3550
3954
  if (!start || start.kind !== "llm")
@@ -3568,11 +3972,29 @@ async function bootstrapWorkerRuntime(deps) {
3568
3972
  instanceId: deps.instanceId,
3569
3973
  startOrLeaseId: deps.payload.workerLeaseId
3570
3974
  });
3571
- await materializeCanonicalPiResourceBundle({
3572
- bundle: Buffer.from(llmPayload.bootstrap.resourceBundle.archiveBase64, "base64"),
3975
+ const deliveredBundle = llmPayload.bootstrap.resourceBundle.archiveBase64 === void 0 ? void 0 : Buffer.from(llmPayload.bootstrap.resourceBundle.archiveBase64, "base64");
3976
+ if (deliveredBundle) {
3977
+ verifyCanonicalPiResourceBundle(deliveredBundle, llmPayload.bootstrap.resourceBundle.digest);
3978
+ }
3979
+ const resourceBundleInput = {
3980
+ bundlesDir: deps.payload.treePaths.piResourceBundlesDir,
3981
+ startRecordId: deps.payload.turnStart.id,
3573
3982
  digest: llmPayload.bootstrap.resourceBundle.digest,
3574
- targetDir: managedAgentDir
3983
+ archiveBase64: llmPayload.bootstrap.resourceBundle.archiveBase64
3984
+ };
3985
+ const persistedResourceBundle = persistPiResourceBundleForStart({
3986
+ ...resourceBundleInput,
3987
+ ...deliveredBundle ? { deliveredBundle } : {}
3575
3988
  });
3989
+ const bundle = deliveredBundle ?? (await persistedResourceBundle).bundle;
3990
+ await Promise.all([
3991
+ persistedResourceBundle,
3992
+ materializeCanonicalPiResourceBundle({
3993
+ bundle,
3994
+ digest: llmPayload.bootstrap.resourceBundle.digest,
3995
+ targetDir: managedAgentDir
3996
+ })
3997
+ ]);
3576
3998
  const manifest = await readAndValidateManagedPiResourceManifest({
3577
3999
  agentDir: managedAgentDir,
3578
4000
  resourceDigest: llmPayload.bootstrap.resourceBundle.digest,
@@ -3670,12 +4092,22 @@ async function bootstrapWorkerRuntime(deps) {
3670
4092
  resumed: deps.payload.resume,
3671
4093
  primaryTreeFile: deps.payload.treePaths.primaryTreeFile,
3672
4094
  workspaceRoot: deps.payload.treePaths.workspaceRoot,
3673
- aggregatedAgentsSources: aggregatedAgentsMdSources,
3674
- loadedSkills,
4095
+ aggregatedAgentsSources: runRoot.aggregatedAgentsMdSources,
4096
+ loadedSkills: runRoot.loadedSkills,
3675
4097
  loadedAgentsFiles,
3676
4098
  loadedSkillFiles,
3677
4099
  rootEntryId: null,
3678
- receipt
4100
+ receipt,
4101
+ ...preparedTools ? {
4102
+ developmentTools: {
4103
+ miseVersion: preparedTools.miseVersion,
4104
+ repositories: preparedTools.repositories.map((repository) => ({
4105
+ repositoryKey: repository.repositoryKey,
4106
+ tools: repository.tools
4107
+ })),
4108
+ warnings: preparedTools.warnings
4109
+ }
4110
+ } : {}
3679
4111
  },
3680
4112
  pendingInputs,
3681
4113
  ...credentialRefresh ? { credentialRefresh } : {}
@@ -3710,6 +4142,8 @@ function validatePreparedSession(input) {
3710
4142
  startRecordId: payload.turnStart.id,
3711
4143
  proposedTurnRecordId: payload.turnStart.proposedTurnRecordId,
3712
4144
  acceptedTurnRecordId: payload.turnStart.state.kind === "accepted" ? payload.turnStart.state.turnRecordId : null,
4145
+ startKind: payload.turnStart.startKind,
4146
+ ...payload.llmPreparation ? { llmPreparation: payload.llmPreparation } : {},
3713
4147
  treeFile: payload.treePaths.primaryTreeFile,
3714
4148
  workspaceRoot: payload.treePaths.workspaceRoot,
3715
4149
  turnResultMarkdownBySemanticRef: payload.turnResultMarkdownBySemanticRef,
@@ -3741,28 +4175,50 @@ var WorkerLiveResources = class {
3741
4175
  }
3742
4176
  deps;
3743
4177
  #piHandle = null;
4178
+ #dockerCredentials = new DockerRegistryCredentials();
3744
4179
  #activeTurnAbort = null;
4180
+ #toolPreparationAbort = null;
3745
4181
  #provisional = /* @__PURE__ */ new Map();
3746
4182
  get piHandle() {
3747
4183
  return this.#piHandle;
3748
4184
  }
3749
4185
  async bootstrap(payload, settings) {
3750
- const bootstrapped = await bootstrapWorkerRuntime({
3751
- instanceId: this.deps.instanceId,
3752
- payload,
3753
- piFactory: this.deps.piFactory,
3754
- gitOps: this.deps.gitOps,
3755
- scheduler: this.deps.scheduler,
3756
- resolveWorkerProcess: this.deps.resolveWorkerProcess
3757
- });
3758
- this.#provisional.set(payload.turnStart.id, bootstrapped.activation);
3759
- return {
3760
- session: validatePreparedSession({ bootstrapped, payload, settings }),
3761
- pendingInputs: bootstrapped.pendingInputs,
3762
- readyPayload: bootstrapped.readyPayload,
3763
- ...bootstrapped.credentialRefresh ? { credentialRefresh: bootstrapped.credentialRefresh } : {},
3764
- diagnostics: bootstrapped.diagnostics
3765
- };
4186
+ const toolPreparationAbort = new AbortController();
4187
+ this.#toolPreparationAbort = toolPreparationAbort;
4188
+ try {
4189
+ const bootstrapped = await bootstrapWorkerRuntime({
4190
+ instanceId: this.deps.instanceId,
4191
+ payload,
4192
+ piFactory: this.deps.piFactory,
4193
+ gitOps: this.deps.gitOps,
4194
+ developmentTools: this.deps.developmentTools,
4195
+ configureDockerCredentials: (credentials, enabled) => this.#dockerCredentials.install(credentials, enabled),
4196
+ toolPreparationSignal: toolPreparationAbort.signal,
4197
+ scheduler: this.deps.scheduler,
4198
+ onToolPreparationProgress: (repositoryKey, phase) => this.deps.progress({
4199
+ level: "info",
4200
+ code: `development_tools.${phase}`,
4201
+ message: `${phase === "installing" ? "Installing" : "Verifying"} development tools for ${repositoryKey}`,
4202
+ details: { repositoryKey }
4203
+ }),
4204
+ onToolDiagnosticTrace: this.deps.diagnosticTrace,
4205
+ resolveWorkerProcess: this.deps.resolveWorkerProcess
4206
+ });
4207
+ const session = validatePreparedSession({ bootstrapped, payload, settings });
4208
+ this.#provisional.set(payload.turnStart.id, bootstrapped.activation);
4209
+ return {
4210
+ session,
4211
+ pendingInputs: bootstrapped.pendingInputs,
4212
+ readyPayload: bootstrapped.readyPayload,
4213
+ ...bootstrapped.credentialRefresh ? { credentialRefresh: bootstrapped.credentialRefresh } : {},
4214
+ diagnostics: bootstrapped.diagnostics
4215
+ };
4216
+ } catch (error) {
4217
+ this.#dockerCredentials.dispose();
4218
+ throw error;
4219
+ } finally {
4220
+ if (this.#toolPreparationAbort === toolPreparationAbort) this.#toolPreparationAbort = null;
4221
+ }
3766
4222
  }
3767
4223
  async activate(startRecordId, turnRecordId, session) {
3768
4224
  if (session.proposedTurnRecordId !== turnRecordId) {
@@ -3817,6 +4273,11 @@ var WorkerLiveResources = class {
3817
4273
  if (this.#activeTurnAbort === controller) this.#activeTurnAbort = null;
3818
4274
  }
3819
4275
  }
4276
+ abortToolPreparation() {
4277
+ if (!this.#toolPreparationAbort) return false;
4278
+ this.#toolPreparationAbort.abort();
4279
+ return true;
4280
+ }
3820
4281
  abortActiveTurn() {
3821
4282
  if (!this.#activeTurnAbort) return false;
3822
4283
  this.#activeTurnAbort.abort();
@@ -3826,30 +4287,21 @@ var WorkerLiveResources = class {
3826
4287
  await this.#piHandle?.abortTurn();
3827
4288
  }
3828
4289
  async cleanup() {
4290
+ this.#dockerCredentials.dispose();
3829
4291
  this.#provisional.clear();
3830
4292
  await this.#piHandle?.close();
3831
4293
  this.#piHandle = null;
3832
4294
  this.deps.gitOps.cleanupRepositoryCredentials?.();
3833
4295
  }
3834
4296
  };
3835
- function strings(value, name) {
3836
- if (!value || typeof value !== "object" || Array.isArray(value)) {
3837
- throw new Error(`Credential file '${name}' must contain a JSON object`);
3838
- }
3839
- return Object.fromEntries(
3840
- Object.entries(value).filter(
3841
- (entry) => typeof entry[1] === "string"
3842
- )
3843
- );
3844
- }
3845
4297
  async function sampleCredentialFiles(descriptor) {
3846
4298
  const values = {};
3847
4299
  for (const credentialPath of descriptor.declaredCredentialPaths) {
3848
- const json = JSON.parse(await readFile2(path8.join(descriptor.agentDir, credentialPath), "utf8"));
4300
+ const json = JSON.parse(await readFile3(path9.join(descriptor.agentDir, credentialPath), "utf8"));
4301
+ if (!json || typeof json !== "object" || Array.isArray(json)) {
4302
+ throw new Error(`Credential file '${credentialPath}' must contain a JSON object`);
4303
+ }
3849
4304
  if (credentialPath === "auth.json") {
3850
- if (!json || typeof json !== "object" || Array.isArray(json)) {
3851
- throw new Error(`Credential file '${credentialPath}' must contain a JSON object`);
3852
- }
3853
4305
  const selected = json[descriptor.providerId];
3854
4306
  if (selected && typeof selected === "object" && !Array.isArray(selected)) {
3855
4307
  for (const [key, value] of Object.entries(selected)) {
@@ -3858,7 +4310,12 @@ async function sampleCredentialFiles(descriptor) {
3858
4310
  values[key] = String(value);
3859
4311
  }
3860
4312
  }
3861
- } else Object.assign(values, strings(json, credentialPath));
4313
+ } else {
4314
+ Object.assign(
4315
+ values,
4316
+ Object.fromEntries(Object.entries(json).filter(([, value]) => typeof value === "string"))
4317
+ );
4318
+ }
3862
4319
  }
3863
4320
  const fingerprint = JSON.stringify(
3864
4321
  Object.keys(values).sort().map((key) => [key, values[key]])
@@ -3866,13 +4323,9 @@ async function sampleCredentialFiles(descriptor) {
3866
4323
  return { values, fingerprint };
3867
4324
  }
3868
4325
 
3869
- // src/runtime/lifecycle-reducer.ts
3870
- import {
3871
- WORKER_API_VERSION as WORKER_API_VERSION2
3872
- } from "@leitwerk-dev/worker-protocol";
3873
-
3874
4326
  // src/turn-execution-error.ts
3875
- import { isWorkerErrorClass } from "@leitwerk-dev/domain";
4327
+ import { isWorkerErrorClass, toErrorMessage } from "@leitwerk-dev/domain";
4328
+ import { toErrorMessage as toErrorMessage2 } from "@leitwerk-dev/domain";
3876
4329
  var TurnExecutionError = class extends Error {
3877
4330
  errorClass;
3878
4331
  turnId;
@@ -3900,10 +4353,7 @@ function classifyRuntimeError(error, fallbackErrorClass = "infrastructure") {
3900
4353
  message: typeof customError.message === "string" && customError.message.trim() !== "" ? customError.message : String(error)
3901
4354
  };
3902
4355
  }
3903
- if (error instanceof Error && error.message.trim() !== "") {
3904
- return { errorClass: fallbackErrorClass, message: error.message };
3905
- }
3906
- return { errorClass: fallbackErrorClass, message: String(error) };
4356
+ return { errorClass: fallbackErrorClass, message: toErrorMessage(error) };
3907
4357
  }
3908
4358
  function buildTurnFailureReport(error, input) {
3909
4359
  const classified = classifyRuntimeError(error, input.fallbackErrorClass);
@@ -3919,12 +4369,6 @@ function buildTurnFailureReport(error, input) {
3919
4369
  } : {}
3920
4370
  };
3921
4371
  }
3922
- function toErrorMessage(error) {
3923
- if (error instanceof Error && error.message.trim() !== "") {
3924
- return error.message;
3925
- }
3926
- return String(error);
3927
- }
3928
4372
 
3929
4373
  // src/runtime/failure-policy.ts
3930
4374
  function extractSecretValuesFromPayload(payload) {
@@ -3935,8 +4379,19 @@ function extractSecretValuesFromPayload(payload) {
3935
4379
  if (typeof value === "string" && value.trim() !== "") secrets.add(value.trim());
3936
4380
  }
3937
4381
  }
4382
+ for (const value of extractDockerRegistrySecretValues(payload)) secrets.add(value);
3938
4383
  return Array.from(secrets);
3939
4384
  }
4385
+ function extractDockerRegistrySecretValues(payload) {
4386
+ const secrets = /* @__PURE__ */ new Set();
4387
+ for (const credential of payload.dockerRegistryCredentials ?? []) {
4388
+ secrets.add(credential.password);
4389
+ secrets.add(Buffer.from(`${credential.username}:${credential.password}`).toString("base64"));
4390
+ secrets.add(Buffer.from(credential.password).toString("base64"));
4391
+ secrets.add(encodeURIComponent(credential.password));
4392
+ }
4393
+ return Array.from(secrets).filter(Boolean).sort((a, b) => b.length - a.length);
4394
+ }
3940
4395
  function redactSecrets(message, secrets) {
3941
4396
  let result = message;
3942
4397
  for (const secret of secrets) {
@@ -3951,21 +4406,7 @@ function errorCode(error, fallback) {
3951
4406
  const code = error?.code;
3952
4407
  return typeof code === "string" && code.trim() !== "" ? code.trim() : fallback;
3953
4408
  }
3954
- function sessionContext(payload) {
3955
- return {
3956
- selectedTurnId: payload.processSnapshot.selectedTurnId ?? null,
3957
- lifecycleStatus: payload.processSnapshot.lifecycleStatus ?? "running",
3958
- snapshotSource: failureSnapshotSource(payload)
3959
- };
3960
- }
3961
- function failureSnapshotSource(payload) {
3962
- return {
3963
- kind: payload.bootstrap.kind,
3964
- treeFile: payload.treePaths.primaryTreeFile
3965
- };
3966
- }
3967
4409
  function normalizeWorkerFailure(failure2) {
3968
- const session = failure2.kind === "bootstrap" ? sessionContext(failure2.payload) : failure2.kind === "dispatch" || failure2.kind === "cleanup" || failure2.kind === "turn" || failure2.kind === "mandatory_snapshot" ? failure2.session ?? null : null;
3969
4410
  const secrets = extractSecretValuesFromPayload(
3970
4411
  failure2.kind === "bootstrap" ? failure2.payload : null
3971
4412
  );
@@ -3982,8 +4423,8 @@ function normalizeWorkerFailure(failure2) {
3982
4423
  if (failure2.kind === "turn" || failure2.kind === "mandatory_snapshot") {
3983
4424
  const correlation = failure2.correlation;
3984
4425
  const turnError = failure2.kind === "turn" ? failure2.error : null;
3985
- const summary2 = failure2.kind === "mandatory_snapshot" ? `Mandatory session snapshot upload failed before ${failure2.point}: ${message}` : redactSecrets(turnError?.message ?? message, secrets);
3986
- const errorClass = failure2.kind === "turn" ? turnError?.errorClass ?? classified.errorClass : classified.errorClass;
4426
+ const summary2 = failure2.kind === "mandatory_snapshot" ? `Mandatory session snapshot upload failed before ${failure2.point}: ${message}` : turnError?.message ?? message;
4427
+ const errorClass = turnError?.errorClass ?? classified.errorClass;
3987
4428
  const payload = {
3988
4429
  turnRecordId: correlation.turnRecordId,
3989
4430
  turnId: correlation.turnId,
@@ -4011,7 +4452,7 @@ function normalizeWorkerFailure(failure2) {
4011
4452
  kind: "turn_failed",
4012
4453
  payload,
4013
4454
  park: {
4014
- selectedTurnId: session?.selectedTurnId ?? correlation.turnId,
4455
+ selectedTurnId: failure2.session?.selectedTurnId ?? correlation.turnId,
4015
4456
  reason: summary2,
4016
4457
  errorClass
4017
4458
  }
@@ -4028,7 +4469,13 @@ function normalizeWorkerFailure(failure2) {
4028
4469
  errorClass: "infrastructure"
4029
4470
  },
4030
4471
  stderrMessage: summary2,
4031
- snapshot: { point: "before_worker_failed", source: failureSnapshotSource(failure2.payload) },
4472
+ snapshot: {
4473
+ point: "before_worker_failed",
4474
+ source: {
4475
+ kind: failure2.payload.bootstrap.kind,
4476
+ treeFile: failure2.payload.treePaths.primaryTreeFile
4477
+ }
4478
+ },
4032
4479
  terminal: {
4033
4480
  kind: "worker_failed",
4034
4481
  payload: {
@@ -4036,20 +4483,24 @@ function normalizeWorkerFailure(failure2) {
4036
4483
  errorCode: errorCode(failure2.error, "bootstrap_failed"),
4037
4484
  message: bounded(summary2),
4038
4485
  errorClass: "infrastructure",
4039
- selectedTurnId: session?.selectedTurnId ?? null
4486
+ selectedTurnId: failure2.payload.processSnapshot.selectedTurnId ?? null
4040
4487
  }
4041
4488
  },
4042
4489
  exitCode: 1
4043
4490
  };
4044
4491
  }
4492
+ const { session } = failure2;
4493
+ const isCleanup = failure2.kind === "cleanup";
4494
+ const summary = `${isCleanup ? "Worker cleanup failed" : "Worker dispatch failed"}: ${message}`;
4495
+ const diagnostic = {
4496
+ level: "error",
4497
+ code: isCleanup ? "cleanup.failed" : "runtime.dispatch_failed",
4498
+ message: summary,
4499
+ errorClass: classified.errorClass
4500
+ };
4045
4501
  if (failure2.kind === "dispatch" && session && session.lifecycleStatus !== "error") {
4046
4502
  return {
4047
- diagnostic: {
4048
- level: "error",
4049
- code: "runtime.dispatch_failed",
4050
- message: `Worker dispatch failed: ${message}`,
4051
- errorClass: classified.errorClass
4052
- },
4503
+ diagnostic,
4053
4504
  stderrMessage: message,
4054
4505
  terminal: {
4055
4506
  kind: "park",
@@ -4061,11 +4512,8 @@ function normalizeWorkerFailure(failure2) {
4061
4512
  }
4062
4513
  };
4063
4514
  }
4064
- const isCleanup = failure2.kind === "cleanup";
4065
- const code = isCleanup ? "cleanup.failed" : "runtime.dispatch_failed";
4066
- const summary = `${isCleanup ? "Worker cleanup failed" : "Worker dispatch failed"}: ${message}`;
4067
4515
  return {
4068
- diagnostic: { level: "error", code, message: summary, errorClass: classified.errorClass },
4516
+ diagnostic,
4069
4517
  stderrMessage: summary,
4070
4518
  ...session ? {
4071
4519
  snapshot: {
@@ -4087,6 +4535,11 @@ function normalizeWorkerFailure(failure2) {
4087
4535
  };
4088
4536
  }
4089
4537
 
4538
+ // src/runtime/lifecycle-reducer.ts
4539
+ import {
4540
+ WORKER_API_VERSION as WORKER_API_VERSION2
4541
+ } from "@leitwerk-dev/worker-protocol";
4542
+
4090
4543
  // src/runtime/snapshot-policy.ts
4091
4544
  function resolveWorkerSnapshotPolicy(point, sessionKind, piAvailable) {
4092
4545
  if (sessionKind === "automatic") return { upload: false };
@@ -4201,33 +4654,10 @@ function snapshotMatches(snapshot, event) {
4201
4654
  function hasActivePublication(state) {
4202
4655
  return state.work.publication.kind !== "none";
4203
4656
  }
4204
- function requireNoPublication(state) {
4657
+ function beginSnapshot(state, publication, source, outputs) {
4205
4658
  if (hasActivePublication(state)) throw new Error("Snapshot publication is already active");
4206
- }
4207
- function beginReadySnapshot(state, source, outputs) {
4208
- requireNoPublication(state);
4209
- const snapshot = {
4210
- point: "after_worker_ready",
4211
- turnRecordId: null,
4212
- required: false
4213
- };
4214
- outputs.push({ kind: "upload_snapshot", ...snapshot, source });
4215
- return {
4216
- ...state,
4217
- work: { ...state.work, publication: { kind: "ready_snapshot", snapshot } }
4218
- };
4219
- }
4220
- function beginTerminalSnapshot(state, point, turnRecordId, terminal, source, outputs) {
4221
- requireNoPublication(state);
4222
- const snapshot = { point, turnRecordId, required: true };
4223
- outputs.push({ kind: "upload_snapshot", ...snapshot, source });
4224
- return {
4225
- ...state,
4226
- work: {
4227
- ...state.work,
4228
- publication: { kind: "terminal_snapshot", snapshot, terminal }
4229
- }
4230
- };
4659
+ outputs.push({ kind: "upload_snapshot", ...publication.snapshot, source });
4660
+ return { ...state, work: { ...state.work, publication } };
4231
4661
  }
4232
4662
  var TERMINAL_ACK_RETRY_MS = 5e3;
4233
4663
  function publishTerminalAndAwaitAcknowledgement(state, terminal, outputs) {
@@ -4247,35 +4677,6 @@ function publishTerminalAndAwaitAcknowledgement(state, terminal, outputs) {
4247
4677
  terminal.correlation.turnRecordId
4248
4678
  );
4249
4679
  }
4250
- function beginCleanupSnapshot(state, source, outputs) {
4251
- requireNoPublication(state);
4252
- const snapshot = {
4253
- point: "before_cleanup_completed",
4254
- turnRecordId: null,
4255
- required: true
4256
- };
4257
- outputs.push({ kind: "upload_snapshot", ...snapshot, source });
4258
- return {
4259
- ...state,
4260
- work: { ...state.work, publication: { kind: "cleanup_snapshot", snapshot } }
4261
- };
4262
- }
4263
- function beginFatalSnapshot(state, fatal, source, afterSnapshot, outputs) {
4264
- requireNoPublication(state);
4265
- const snapshot = {
4266
- point: "before_worker_failed",
4267
- turnRecordId: null,
4268
- required: false
4269
- };
4270
- outputs.push({ kind: "upload_snapshot", ...snapshot, source });
4271
- return {
4272
- ...state,
4273
- work: {
4274
- ...state.work,
4275
- publication: { kind: "fatal_snapshot", snapshot, fatal, afterSnapshot }
4276
- }
4277
- };
4278
- }
4279
4680
  function finishFatal(state, fatal) {
4280
4681
  const outputs = [
4281
4682
  protocol("worker.failed", fatal.payload),
@@ -4317,7 +4718,17 @@ function failureOutputs(state, failure2) {
4317
4718
  };
4318
4719
  if (disposition.snapshot && !hasActivePublication(state)) {
4319
4720
  const afterSnapshot = state.phase.kind === "cleaning" && state.phase.stage === "publication" ? "cleanup" : "exit";
4320
- next = beginFatalSnapshot(next, fatal, disposition.snapshot.source, afterSnapshot, outputs);
4721
+ next = beginSnapshot(
4722
+ next,
4723
+ {
4724
+ kind: "fatal_snapshot",
4725
+ snapshot: { point: "before_worker_failed", turnRecordId: null, required: false },
4726
+ fatal,
4727
+ afterSnapshot
4728
+ },
4729
+ disposition.snapshot.source,
4730
+ outputs
4731
+ );
4321
4732
  break;
4322
4733
  }
4323
4734
  const finished = finishFatal(next, fatal);
@@ -4420,11 +4831,15 @@ function advance(state, outputs) {
4420
4831
  next.session.piAvailable
4421
4832
  ) : { upload: false };
4422
4833
  if (cleanupSnapshot.upload && next.session) {
4423
- next = beginCleanupSnapshot(
4834
+ next = beginSnapshot(
4424
4835
  {
4425
4836
  ...next,
4426
4837
  phase: { kind: "cleaning", reason, exitAfterCleanup, stage: "publication" }
4427
4838
  },
4839
+ {
4840
+ kind: "cleanup_snapshot",
4841
+ snapshot: { point: "before_cleanup_completed", turnRecordId: null, required: true }
4842
+ },
4428
4843
  sessionSnapshotSource(next.session),
4429
4844
  outputs
4430
4845
  );
@@ -4513,9 +4928,11 @@ function reduceWorkerRuntime(state, event) {
4513
4928
  if (state.phase.kind !== "init") break;
4514
4929
  next = { ...state, phase: { kind: "waiting_for_start" } };
4515
4930
  outputs.push(HELLO);
4931
+ outputs.push(protocol("worker.bootstrap_progress", { phase: "worker_connected" }));
4516
4932
  break;
4517
4933
  case "transport_connected":
4518
4934
  outputs.push(HELLO);
4935
+ outputs.push(protocol("worker.bootstrap_progress", { phase: "worker_connected" }));
4519
4936
  if (state.session) {
4520
4937
  outputs.push(
4521
4938
  protocol("worker.heartbeat", {
@@ -4614,6 +5031,7 @@ function reduceWorkerRuntime(state, event) {
4614
5031
  },
4615
5032
  sessionTainted: false
4616
5033
  };
5034
+ outputs.push(protocol("worker.bootstrap_progress", { phase: "preparing_workspace" }));
4617
5035
  outputs.push({ kind: "bootstrap", startRecordId, payload: message.payload });
4618
5036
  break;
4619
5037
  }
@@ -4728,6 +5146,8 @@ function reduceWorkerRuntime(state, event) {
4728
5146
  kind: "diagnostic",
4729
5147
  payload: { level: "warn", code: "bootstrap.diagnostic", message }
4730
5148
  });
5149
+ outputs.push(protocol("worker.bootstrap_progress", { phase: "loading_resources" }));
5150
+ outputs.push(protocol("worker.bootstrap_progress", { phase: "preparing_turn" }));
4731
5151
  outputs.push(protocol("worker.ready", completion.readyPayload));
4732
5152
  if (wasDraining) break;
4733
5153
  const readySnapshot = resolveWorkerSnapshotPolicy(
@@ -4736,7 +5156,15 @@ function reduceWorkerRuntime(state, event) {
4736
5156
  completion.session.piAvailable
4737
5157
  );
4738
5158
  if (readySnapshot.upload)
4739
- next = beginReadySnapshot(next, sessionSnapshotSource(completion.session), outputs);
5159
+ next = beginSnapshot(
5160
+ next,
5161
+ {
5162
+ kind: "ready_snapshot",
5163
+ snapshot: { point: "after_worker_ready", turnRecordId: null, required: false }
5164
+ },
5165
+ sessionSnapshotSource(completion.session),
5166
+ outputs
5167
+ );
4740
5168
  next = armTimer(
4741
5169
  next,
4742
5170
  outputs,
@@ -4800,7 +5228,9 @@ function reduceWorkerRuntime(state, event) {
4800
5228
  });
4801
5229
  break;
4802
5230
  case "activation_failed":
4803
- if (!matchesActivation(state, event.startRecordId, event.turnRecordId)) break;
5231
+ case "turn_defect":
5232
+ if (event.kind === "activation_failed" ? !matchesActivation(state, event.startRecordId, event.turnRecordId) : !matchesTurn(state, event.turnRecordId))
5233
+ break;
4804
5234
  if (state.phase.kind === "draining") {
4805
5235
  next = finishDrainingOperation(state);
4806
5236
  } else {
@@ -4878,6 +5308,7 @@ function reduceWorkerRuntime(state, event) {
4878
5308
  forkPiEntryId: event.result.meta.forkPiEntryId ?? null,
4879
5309
  resultPiEntryId: event.result.meta.resultPiEntryId ?? null,
4880
5310
  turnResultMarkdown: event.result.meta.turnResultMarkdown ?? null,
5311
+ resultSummary: event.result.meta.resultSummary,
4881
5312
  rootEntryId: event.result.meta.rootEntryId ?? null
4882
5313
  }),
4883
5314
  park: null,
@@ -4920,97 +5351,33 @@ function reduceWorkerRuntime(state, event) {
4920
5351
  );
4921
5352
  if (!snapshotPolicy.upload)
4922
5353
  throw new Error("LLM terminal snapshot policy unexpectedly skipped upload");
4923
- next = beginTerminalSnapshot(
5354
+ next = beginSnapshot(
4924
5355
  next,
4925
- point,
4926
- event.turnRecordId,
4927
- pending,
5356
+ {
5357
+ kind: "terminal_snapshot",
5358
+ snapshot: { point, turnRecordId: event.turnRecordId, required: true },
5359
+ terminal: pending
5360
+ },
4928
5361
  sessionSnapshotSource(state.session),
4929
5362
  outputs
4930
5363
  );
4931
5364
  }
4932
5365
  break;
4933
5366
  }
4934
- case "turn_defect":
4935
- if (!matchesTurn(state, event.turnRecordId)) break;
4936
- if (state.phase.kind === "draining") {
4937
- next = finishDrainingOperation(state);
4938
- } else {
4939
- const failed = failureOutputs(next, {
4940
- kind: "dispatch",
4941
- error: event.error,
4942
- state: "busy",
4943
- session: failureContext(state)
4944
- });
4945
- next = failed.state;
4946
- outputs.push(...failed.outputs);
4947
- }
4948
- break;
4949
- case "snapshot_succeeded": {
4950
- const publication = state.work.publication;
4951
- switch (publication.kind) {
4952
- case "none":
4953
- case "terminal_pending_ack":
4954
- case "fatal_pending_cleanup":
4955
- break;
4956
- case "ready_snapshot":
4957
- if (!snapshotMatches(publication.snapshot, event)) break;
4958
- next = { ...state, work: { ...state.work, publication: { kind: "none" } } };
4959
- break;
4960
- case "terminal_snapshot":
4961
- if (!snapshotMatches(publication.snapshot, event)) break;
4962
- next = publishTerminalAndAwaitAcknowledgement(state, publication.terminal, outputs);
4963
- break;
4964
- case "cleanup_snapshot":
4965
- if (!snapshotMatches(publication.snapshot, event)) break;
4966
- if (state.phase.kind !== "cleaning" || state.phase.stage !== "publication")
4967
- throw new Error("Cleanup snapshot completed outside cleanup publication");
4968
- outputs.push({ kind: "cleanup" });
4969
- next = {
4970
- ...state,
4971
- phase: { ...state.phase, stage: "resources" },
4972
- work: { ...state.work, publication: { kind: "none" } }
4973
- };
4974
- break;
4975
- case "fatal_snapshot":
4976
- if (!snapshotMatches(publication.snapshot, event)) break;
4977
- if (publication.afterSnapshot === "exit") {
4978
- const finished = finishFatal(state, publication.fatal);
4979
- next = finished.state;
4980
- outputs.push(...finished.outputs);
4981
- } else {
4982
- if (state.phase.kind !== "cleaning" || state.phase.stage !== "publication")
4983
- throw new Error("Fatal snapshot completed outside cleanup publication");
4984
- outputs.push({ kind: "cleanup" });
4985
- next = {
4986
- ...state,
4987
- phase: { ...state.phase, stage: "resources" },
4988
- work: {
4989
- ...state.work,
4990
- publication: {
4991
- kind: "fatal_pending_cleanup",
4992
- fatal: publication.fatal
4993
- }
4994
- }
4995
- };
4996
- }
4997
- break;
4998
- }
4999
- break;
5000
- }
5367
+ case "snapshot_succeeded":
5001
5368
  case "snapshot_failed": {
5002
5369
  const publication = state.work.publication;
5370
+ if (!("snapshot" in publication) || !snapshotMatches(publication.snapshot, event)) break;
5371
+ const completion = event.kind === "snapshot_succeeded" ? "completed" : "failed";
5003
5372
  switch (publication.kind) {
5004
- case "none":
5005
- case "terminal_pending_ack":
5006
- case "fatal_pending_cleanup":
5007
- break;
5008
5373
  case "ready_snapshot":
5009
- if (!snapshotMatches(publication.snapshot, event)) break;
5010
5374
  next = { ...state, work: { ...state.work, publication: { kind: "none" } } };
5011
5375
  break;
5012
5376
  case "terminal_snapshot": {
5013
- if (!snapshotMatches(publication.snapshot, event)) break;
5377
+ if (event.kind === "snapshot_succeeded") {
5378
+ next = publishTerminalAndAwaitAcknowledgement(state, publication.terminal, outputs);
5379
+ break;
5380
+ }
5014
5381
  const cleared = {
5015
5382
  ...state,
5016
5383
  work: { ...state.work, publication: { kind: "none" } }
@@ -5027,41 +5394,41 @@ function reduceWorkerRuntime(state, event) {
5027
5394
  break;
5028
5395
  }
5029
5396
  case "cleanup_snapshot": {
5030
- if (!snapshotMatches(publication.snapshot, event)) break;
5031
5397
  if (state.phase.kind !== "cleaning" || state.phase.stage !== "publication")
5032
- throw new Error("Cleanup snapshot failed outside cleanup publication");
5398
+ throw new Error(`Cleanup snapshot ${completion} outside cleanup publication`);
5033
5399
  const cleared = {
5034
5400
  ...state,
5035
5401
  work: { ...state.work, publication: { kind: "none" } }
5036
5402
  };
5037
- const failed = failureOutputs(cleared, {
5038
- kind: "cleanup",
5039
- error: event.error,
5040
- session: failureContext(state)
5041
- });
5042
- next = failed.state;
5043
- outputs.push(...failed.outputs);
5403
+ if (event.kind === "snapshot_succeeded") {
5404
+ outputs.push({ kind: "cleanup" });
5405
+ next = { ...cleared, phase: { ...state.phase, stage: "resources" } };
5406
+ } else {
5407
+ const failed = failureOutputs(cleared, {
5408
+ kind: "cleanup",
5409
+ error: event.error,
5410
+ session: failureContext(state)
5411
+ });
5412
+ next = failed.state;
5413
+ outputs.push(...failed.outputs);
5414
+ }
5044
5415
  break;
5045
5416
  }
5046
5417
  case "fatal_snapshot":
5047
- if (!snapshotMatches(publication.snapshot, event)) break;
5048
5418
  if (publication.afterSnapshot === "exit") {
5049
5419
  const finished = finishFatal(state, publication.fatal);
5050
5420
  next = finished.state;
5051
5421
  outputs.push(...finished.outputs);
5052
5422
  } else {
5053
5423
  if (state.phase.kind !== "cleaning" || state.phase.stage !== "publication")
5054
- throw new Error("Fatal snapshot failed outside cleanup publication");
5424
+ throw new Error(`Fatal snapshot ${completion} outside cleanup publication`);
5055
5425
  outputs.push({ kind: "cleanup" });
5056
5426
  next = {
5057
5427
  ...state,
5058
5428
  phase: { ...state.phase, stage: "resources" },
5059
5429
  work: {
5060
5430
  ...state.work,
5061
- publication: {
5062
- kind: "fatal_pending_cleanup",
5063
- fatal: publication.fatal
5064
- }
5431
+ publication: { kind: "fatal_pending_cleanup", fatal: publication.fatal }
5065
5432
  }
5066
5433
  };
5067
5434
  }
@@ -5229,9 +5596,6 @@ function resolveWorkerRuntimeSettings(config, payload) {
5229
5596
  }
5230
5597
 
5231
5598
  // src/runtime/turn-execution.ts
5232
- import {
5233
- failActiveTurnProgress
5234
- } from "@leitwerk-dev/domain";
5235
5599
  import { assertValidLlmTurnDefinition } from "@leitwerk-dev/process-sdk";
5236
5600
 
5237
5601
  // src/turn-execution-result.ts
@@ -5310,6 +5674,7 @@ function createAutomaticTurnExecutor(input) {
5310
5674
  forkPiEntryId: null,
5311
5675
  resultPiEntryId: null,
5312
5676
  turnResultMarkdown: completeInput.markdown ?? null,
5677
+ resultSummary: completeInput.resultSummary,
5313
5678
  rootEntryId: input.piHandle ? resolveRootEntryIdFromHandle(input.piHandle) : readProcessSemanticEntryRefs(input.state)?.rootEntry?.entryId ?? null
5314
5679
  }
5315
5680
  };
@@ -5403,8 +5768,7 @@ async function promptWithGuards(deps, input) {
5403
5768
  let maxDurationTimer = null;
5404
5769
  let inactivityTimer = null;
5405
5770
  let rejectTimeout = null;
5406
- let timedOut = false;
5407
- let aborted = false;
5771
+ let abortReason = null;
5408
5772
  let sawCompaction = false;
5409
5773
  let removeOperatorAbortListener = null;
5410
5774
  let removeSuspensionListener = null;
@@ -5421,11 +5785,43 @@ async function promptWithGuards(deps, input) {
5421
5785
  inactivityTimer = null;
5422
5786
  }
5423
5787
  };
5788
+ const abortWithinGracePeriod = async (timeoutKind) => {
5789
+ let abortCompleted = false;
5790
+ try {
5791
+ await Promise.race([
5792
+ input.piHandle.abortTurn().then(() => {
5793
+ abortCompleted = true;
5794
+ }),
5795
+ deps.scheduler.sleep(turnAbortGracePeriodMs)
5796
+ ]);
5797
+ if (!abortCompleted) {
5798
+ reportError({
5799
+ level: "error",
5800
+ code: "guard.abort_grace_elapsed",
5801
+ message: `${timeoutKind ? "Timed out" : "Operator-stopped"} turn '${input.turnId}' did not abort within ${turnAbortGracePeriodMs}ms`,
5802
+ turnRecordId: input.turnRecordId,
5803
+ turnId: input.turnId,
5804
+ errorClass: "infrastructure",
5805
+ details: { turnAbortGracePeriodMs, ...timeoutKind ? { timeoutKind } : {} }
5806
+ });
5807
+ }
5808
+ } catch (error) {
5809
+ reportError({
5810
+ level: "error",
5811
+ code: "guard.abort_failed",
5812
+ message: `Failed to abort ${timeoutKind ? "timed out" : "operator-stopped"} turn '${input.turnId}': ${toErrorMessage2(error)}`,
5813
+ turnRecordId: input.turnRecordId,
5814
+ turnId: input.turnId,
5815
+ errorClass: "infrastructure",
5816
+ ...timeoutKind ? { details: { timeoutKind } } : {}
5817
+ });
5818
+ }
5819
+ };
5424
5820
  const requestAbortForTimeout = (timeoutKind, timeoutMs) => {
5425
- if (timedOut || aborted) {
5821
+ if (abortReason !== null) {
5426
5822
  return;
5427
5823
  }
5428
- timedOut = true;
5824
+ abortReason = timeoutKind;
5429
5825
  clearTimers();
5430
5826
  const error = new PromptTimeoutError(input.turnId, timeoutKind, timeoutMs);
5431
5827
  reportError({
@@ -5447,44 +5843,13 @@ async function promptWithGuards(deps, input) {
5447
5843
  details: { turnAbortGracePeriodMs, timeoutMs, timeoutKind }
5448
5844
  });
5449
5845
  rejectTimeout?.(error);
5450
- void (async () => {
5451
- let abortCompleted = false;
5452
- try {
5453
- await Promise.race([
5454
- input.piHandle.abortTurn().then(() => {
5455
- abortCompleted = true;
5456
- }),
5457
- deps.scheduler.sleep(turnAbortGracePeriodMs)
5458
- ]);
5459
- if (!abortCompleted) {
5460
- reportError({
5461
- level: "error",
5462
- code: "guard.abort_grace_elapsed",
5463
- message: `Timed out turn '${input.turnId}' did not abort within ${turnAbortGracePeriodMs}ms`,
5464
- turnRecordId: input.turnRecordId,
5465
- turnId: input.turnId,
5466
- errorClass: "infrastructure",
5467
- details: { turnAbortGracePeriodMs, timeoutKind }
5468
- });
5469
- }
5470
- } catch (error2) {
5471
- reportError({
5472
- level: "error",
5473
- code: "guard.abort_failed",
5474
- message: `Failed to abort timed out turn '${input.turnId}': ${toErrorMessage(error2)}`,
5475
- turnRecordId: input.turnRecordId,
5476
- turnId: input.turnId,
5477
- errorClass: "infrastructure",
5478
- details: { timeoutKind }
5479
- });
5480
- }
5481
- })();
5846
+ void abortWithinGracePeriod(timeoutKind);
5482
5847
  };
5483
5848
  const requestOperatorAbort = () => {
5484
- if (timedOut || aborted) {
5849
+ if (abortReason !== null) {
5485
5850
  return;
5486
5851
  }
5487
- aborted = true;
5852
+ abortReason = "operator_abort";
5488
5853
  clearTimers();
5489
5854
  const error = new OperatorAbortError(input.turnId);
5490
5855
  reportError({
@@ -5505,40 +5870,10 @@ async function promptWithGuards(deps, input) {
5505
5870
  details: { turnAbortGracePeriodMs }
5506
5871
  });
5507
5872
  rejectTimeout?.(error);
5508
- void (async () => {
5509
- let abortCompleted = false;
5510
- try {
5511
- await Promise.race([
5512
- input.piHandle.abortTurn().then(() => {
5513
- abortCompleted = true;
5514
- }),
5515
- deps.scheduler.sleep(turnAbortGracePeriodMs)
5516
- ]);
5517
- if (!abortCompleted) {
5518
- reportError({
5519
- level: "error",
5520
- code: "guard.abort_grace_elapsed",
5521
- message: `Operator-stopped turn '${input.turnId}' did not abort within ${turnAbortGracePeriodMs}ms`,
5522
- turnRecordId: input.turnRecordId,
5523
- turnId: input.turnId,
5524
- errorClass: "infrastructure",
5525
- details: { turnAbortGracePeriodMs }
5526
- });
5527
- }
5528
- } catch (error2) {
5529
- reportError({
5530
- level: "error",
5531
- code: "guard.abort_failed",
5532
- message: `Failed to abort operator-stopped turn '${input.turnId}': ${toErrorMessage(error2)}`,
5533
- turnRecordId: input.turnRecordId,
5534
- turnId: input.turnId,
5535
- errorClass: "infrastructure"
5536
- });
5537
- }
5538
- })();
5873
+ void abortWithinGracePeriod();
5539
5874
  };
5540
5875
  const armMaxDurationTimer = () => {
5541
- if (!turnMaxDurationMs || turnMaxDurationMs <= 0 || maxDurationRemainingMs <= 0 || guardsPaused || timedOut || aborted)
5876
+ if (!turnMaxDurationMs || turnMaxDurationMs <= 0 || maxDurationRemainingMs <= 0 || guardsPaused || abortReason !== null)
5542
5877
  return;
5543
5878
  maxDurationArmedAt = deps.scheduler.now().getTime();
5544
5879
  maxDurationTimer = deps.scheduler.setTimeout(() => {
@@ -5546,7 +5881,7 @@ async function promptWithGuards(deps, input) {
5546
5881
  }, maxDurationRemainingMs);
5547
5882
  };
5548
5883
  const resetInactivityTimer = () => {
5549
- if (!turnInactivityTimeoutMs || turnInactivityTimeoutMs <= 0 || guardsPaused || timedOut || aborted) {
5884
+ if (!turnInactivityTimeoutMs || turnInactivityTimeoutMs <= 0 || guardsPaused || abortReason !== null) {
5550
5885
  return;
5551
5886
  }
5552
5887
  if (inactivityTimer !== null) {
@@ -5571,7 +5906,7 @@ async function promptWithGuards(deps, input) {
5571
5906
  resetInactivityTimer();
5572
5907
  });
5573
5908
  removeSuspensionListener = deps.guardSuspension?.subscribe((paused) => {
5574
- if (guardsPaused === paused || timedOut || aborted) return;
5909
+ if (guardsPaused === paused || abortReason !== null) return;
5575
5910
  guardsPaused = paused;
5576
5911
  if (paused) {
5577
5912
  if (maxDurationTimer !== null) {
@@ -5604,7 +5939,7 @@ async function promptWithGuards(deps, input) {
5604
5939
  }
5605
5940
  const hasGuards = turnMaxDurationMs !== void 0 && turnMaxDurationMs > 0 || turnInactivityTimeoutMs !== void 0 && turnInactivityTimeoutMs > 0 || operatorAbortSignal !== void 0;
5606
5941
  try {
5607
- if (aborted) {
5942
+ if (abortReason === "operator_abort") {
5608
5943
  await guardPromise;
5609
5944
  }
5610
5945
  const result = !hasGuards ? await input.runPrompt() : await Promise.race([input.runPrompt(), guardPromise]);
@@ -5629,7 +5964,11 @@ async function promptWithGuards(deps, input) {
5629
5964
  }
5630
5965
 
5631
5966
  // src/turn-continuation.ts
5632
- import { DEFAULT_CONTINUE_PROMPT, normalizeContinuePrompt } from "@leitwerk-dev/domain";
5967
+ import {
5968
+ DEFAULT_CONTINUE_PROMPT,
5969
+ normalizeContinuePrompt,
5970
+ readNonBlankString as readNonBlankString2
5971
+ } from "@leitwerk-dev/domain";
5633
5972
  function readCurrentLeafMessage(piHandle) {
5634
5973
  const leafId = piHandle.getLeafId();
5635
5974
  if (!leafId) {
@@ -5683,21 +6022,13 @@ async function prepareContinuationUserPrompt(input) {
5683
6022
  }
5684
6023
  return normalizedPrompt;
5685
6024
  }
5686
- function readNonEmptyMetadataString(metadata, key) {
5687
- const value = metadata?.[key];
5688
- return typeof value === "string" && value.trim() !== "" ? value : null;
5689
- }
5690
6025
  function resolveTurnContinuationState(input) {
5691
6026
  if (input.process.selectedTurnId !== input.turnId) {
5692
6027
  return null;
5693
6028
  }
5694
- const continueFromPiEntryId = readNonEmptyMetadataString(
5695
- input.process.metadata,
5696
- "continueFromPiEntryId"
5697
- );
5698
- const continueFromTurnRecordId = readNonEmptyMetadataString(
5699
- input.process.metadata,
5700
- "continueFromTurnRecordId"
6029
+ const continueFromPiEntryId = readNonBlankString2(input.process.metadata?.continueFromPiEntryId);
6030
+ const continueFromTurnRecordId = readNonBlankString2(
6031
+ input.process.metadata?.continueFromTurnRecordId
5701
6032
  );
5702
6033
  if (!continueFromPiEntryId || !continueFromTurnRecordId) {
5703
6034
  return null;
@@ -5705,7 +6036,7 @@ function resolveTurnContinuationState(input) {
5705
6036
  return {
5706
6037
  continueFromPiEntryId,
5707
6038
  continuePrompt: normalizeContinuePrompt(input.process.metadata?.continuePrompt) ?? DEFAULT_CONTINUE_PROMPT,
5708
- savedPrimaryLeafId: readNonEmptyMetadataString(input.process.metadata, "continueSavedPrimaryLeafEntryId") ?? readProcessSemanticEntryRefs(input.state)?.currentPrimaryPathLeaf?.entryId ?? null
6039
+ savedPrimaryLeafId: readNonBlankString2(input.process.metadata?.continueSavedPrimaryLeafEntryId) ?? readProcessSemanticEntryRefs(input.state)?.currentPrimaryPathLeaf?.entryId ?? null
5709
6040
  };
5710
6041
  }
5711
6042
  function resolvePromptlessTurnResumeReason(input) {
@@ -5828,7 +6159,7 @@ function createTurnResultMarkdownState() {
5828
6159
  publicationCount: 0
5829
6160
  };
5830
6161
  }
5831
- function publishTurnResultMarkdownValue(state, value) {
6162
+ function publishTurnResultMarkdownValue(state, value, resultSummary) {
5832
6163
  const validation = validateTurnResultMarkdownValue(value);
5833
6164
  if (!validation.ok) {
5834
6165
  return {
@@ -5843,6 +6174,7 @@ function publishTurnResultMarkdownValue(state, value) {
5843
6174
  }
5844
6175
  const nextState = {
5845
6176
  markdown: validation.markdown,
6177
+ ...typeof resultSummary === "string" && resultSummary.trim() ? { resultSummary: resultSummary.trim() } : {},
5846
6178
  publicationCount: state.publicationCount + 1
5847
6179
  };
5848
6180
  return {
@@ -5863,13 +6195,21 @@ function createMarkdownResultTool(stateRef) {
5863
6195
  name: MARKDOWN_RESULT_TOOL_NAME,
5864
6196
  description: "Publish the operator-facing markdown result for this turn. Pass raw markdown only and do not wrap the entire markdown in triple backticks.",
5865
6197
  parameters: {
6198
+ resultSummary: {
6199
+ type: "string",
6200
+ description: "Concise summary of this attempt\u2019s result, based on completed work."
6201
+ },
5866
6202
  markdown: {
5867
6203
  type: "string",
5868
6204
  description: "Raw markdown content to render for this turn. Do not wrap the entire markdown in triple backticks."
5869
6205
  }
5870
6206
  },
5871
6207
  execute: async (args) => {
5872
- const published = publishTurnResultMarkdownValue(stateRef.current, args.markdown);
6208
+ const published = publishTurnResultMarkdownValue(
6209
+ stateRef.current,
6210
+ args.markdown,
6211
+ args.resultSummary
6212
+ );
5873
6213
  stateRef.current = published.state;
5874
6214
  return published.response;
5875
6215
  }
@@ -6018,35 +6358,14 @@ function finalizeTurnResultMarkdown(input) {
6018
6358
  if (!input.behavior || input.behavior.mode === "none") {
6019
6359
  return { markdown: input.state.markdown ?? null, errorMessage: null };
6020
6360
  }
6021
- if (input.behavior.mode === "assistant_output") {
6022
- const markdown = typeof input.assistantMarkdown === "string" ? input.assistantMarkdown.trim() : "";
6023
- if (markdown.length > 0) {
6024
- return { markdown, errorMessage: null };
6025
- }
6026
- return input.behavior.required ? {
6027
- markdown: null,
6028
- errorMessage: "Turn requires non-empty assistant output to publish turn result markdown"
6029
- } : { markdown: null, errorMessage: null };
6030
- }
6031
- if (input.behavior.mode === "outcome_tool_argument") {
6032
- if (input.state.markdown) {
6033
- return { markdown: input.state.markdown, errorMessage: null };
6034
- }
6035
- return input.behavior.required ? {
6036
- markdown: null,
6037
- errorMessage: `Turn requires a successful outcome tool call with a non-empty '${input.behavior.parameterName}' markdown argument`
6038
- } : { markdown: null, errorMessage: null };
6039
- }
6040
- if (input.state.markdown) {
6041
- return { markdown: input.state.markdown, errorMessage: null };
6042
- }
6043
- if (input.behavior.required) {
6044
- return {
6045
- markdown: null,
6046
- errorMessage: `Turn requires a successful '${input.behavior.toolName}' tool call to publish turn result markdown`
6047
- };
6361
+ const markdown = input.behavior.mode === "assistant_output" ? typeof input.assistantMarkdown === "string" ? input.assistantMarkdown.trim() : null : input.state.markdown;
6362
+ if (markdown || !input.behavior.required) {
6363
+ return { markdown: markdown || null, errorMessage: null };
6048
6364
  }
6049
- return { markdown: null, errorMessage: null };
6365
+ return {
6366
+ markdown: null,
6367
+ errorMessage: input.behavior.mode === "assistant_output" ? "Turn requires non-empty assistant output to publish turn result markdown" : input.behavior.mode === "outcome_tool_argument" ? `Turn requires a successful outcome tool call with a non-empty '${input.behavior.parameterName}' markdown argument` : `Turn requires a successful '${input.behavior.toolName}' tool call to publish turn result markdown`
6368
+ };
6050
6369
  }
6051
6370
 
6052
6371
  // src/turn-outcome-tool-session.ts
@@ -6057,15 +6376,10 @@ function cloneSelectedOutcome(value) {
6057
6376
  function cloneTurnResultMarkdownState(state) {
6058
6377
  return {
6059
6378
  markdown: state.markdown,
6379
+ ...state.resultSummary ? { resultSummary: state.resultSummary } : {},
6060
6380
  publicationCount: state.publicationCount
6061
6381
  };
6062
6382
  }
6063
- function snapshotToolCompletionState(value) {
6064
- return {
6065
- selectedOutcome: cloneSelectedOutcome(value.selectedOutcome),
6066
- markdownState: cloneTurnResultMarkdownState(value.markdownState)
6067
- };
6068
- }
6069
6383
  function createTurnOutcomeToolSession(input) {
6070
6384
  let selectedOutcome = null;
6071
6385
  let terminalAcknowledgement = { kind: "open" };
@@ -6085,7 +6399,13 @@ function createTurnOutcomeToolSession(input) {
6085
6399
  name: outcome,
6086
6400
  description: spec.description,
6087
6401
  parameters: {
6088
- ...Object.fromEntries(Object.entries(spec.parameters).map(([key, value]) => [key, value])),
6402
+ ...Object.fromEntries(Object.entries(spec.parameters)),
6403
+ ...injectsGlobalMarkdownParameter ? {
6404
+ resultSummary: {
6405
+ type: "string",
6406
+ description: "Concise result summary for this attempt."
6407
+ }
6408
+ } : {},
6089
6409
  ...injectsGlobalMarkdownParameter && outcomeToolMarkdownParameterName ? {
6090
6410
  [outcomeToolMarkdownParameterName]: {
6091
6411
  type: "string",
@@ -6101,10 +6421,15 @@ function createTurnOutcomeToolSession(input) {
6101
6421
  const acceptsOutcome = selectedOutcome === null;
6102
6422
  if (acceptsOutcome) {
6103
6423
  let outcomeParams = args;
6424
+ if (spec.resultSummaryParameter && typeof args[spec.resultSummaryParameter] === "string")
6425
+ turnResultMarkdownStateRef.current.resultSummary = String(
6426
+ args[spec.resultSummaryParameter]
6427
+ ).trim();
6104
6428
  if (markdownParameterName) {
6105
6429
  const published = publishTurnResultMarkdownValue(
6106
6430
  turnResultMarkdownStateRef.current,
6107
- args[markdownParameterName]
6431
+ args[markdownParameterName],
6432
+ spec.resultSummaryParameter ? args[spec.resultSummaryParameter] : injectsGlobalMarkdownParameter ? args.resultSummary : void 0
6108
6433
  );
6109
6434
  if (!published.response.ok) {
6110
6435
  return published.response;
@@ -6113,6 +6438,7 @@ function createTurnOutcomeToolSession(input) {
6113
6438
  if (injectsGlobalMarkdownParameter) {
6114
6439
  outcomeParams = { ...args };
6115
6440
  delete outcomeParams[markdownParameterName];
6441
+ delete outcomeParams.resultSummary;
6116
6442
  }
6117
6443
  }
6118
6444
  selectedOutcome = { outcome, params: outcomeParams };
@@ -6161,9 +6487,7 @@ function createTurnOutcomeToolSession(input) {
6161
6487
  failureReason: () => terminalAcknowledgement.kind === "acknowledgement_failed_ignored" ? terminalAcknowledgement.reason : null
6162
6488
  };
6163
6489
  return {
6164
- outcomeToolNames,
6165
6490
  usesOutcomeTools,
6166
- requiresMarkdownResultToolCall,
6167
6491
  tools,
6168
6492
  activeTools,
6169
6493
  terminalAcknowledgement: terminalAcknowledgementControl,
@@ -6189,10 +6513,10 @@ function createTurnOutcomeToolSession(input) {
6189
6513
  );
6190
6514
  },
6191
6515
  getCompletionState() {
6192
- return snapshotToolCompletionState({
6193
- selectedOutcome,
6194
- markdownState: turnResultMarkdownStateRef.current
6195
- });
6516
+ return {
6517
+ selectedOutcome: cloneSelectedOutcome(selectedOutcome),
6518
+ markdownState: cloneTurnResultMarkdownState(turnResultMarkdownStateRef.current)
6519
+ };
6196
6520
  },
6197
6521
  shouldBlockToolCall(toolName) {
6198
6522
  if (selectedOutcome === null) {
@@ -6228,9 +6552,7 @@ function createTurnOutcomeToolSession(input) {
6228
6552
  ...recovery.missingToolNames.length > 0 ? { missingToolNames: recovery.missingToolNames } : {}
6229
6553
  };
6230
6554
  },
6231
- describeRecovery(recovery) {
6232
- return describeMissingTurnToolCallRecovery(recovery);
6233
- },
6555
+ describeRecovery: describeMissingTurnToolCallRecovery,
6234
6556
  finalizeMarkdown(completionState, assistantMarkdown) {
6235
6557
  return finalizeTurnResultMarkdown({
6236
6558
  behavior: input.turnDef.turnResultMarkdown,
@@ -6244,13 +6566,7 @@ function createTurnOutcomeToolSession(input) {
6244
6566
  // src/logical-prompt-runner.ts
6245
6567
  var MAX_COMPACTION_CONTINUE_ATTEMPTS = 3;
6246
6568
  function shouldAutoContinueAfterPromptReturn(input) {
6247
- if (input.resolvedOutcome) {
6248
- return false;
6249
- }
6250
- if (!input.sawCompaction) {
6251
- return false;
6252
- }
6253
- return input.compactionContinueAttempts < MAX_COMPACTION_CONTINUE_ATTEMPTS;
6569
+ return !input.resolvedOutcome && input.sawCompaction && input.compactionContinueAttempts < MAX_COMPACTION_CONTINUE_ATTEMPTS;
6254
6570
  }
6255
6571
  function isContextWindowError(error) {
6256
6572
  const message = error instanceof Error ? error.message : String(error);
@@ -6314,9 +6630,7 @@ async function executeLogicalPromptPlan(input) {
6314
6630
  );
6315
6631
  };
6316
6632
  for (; ; ) {
6317
- const continuePlan = currentPlan.kind === "continue" ? currentPlan : null;
6318
- const promptPlan = currentPlan.kind === "prompt" ? currentPlan : null;
6319
- const usingContinueThisAttempt = continuePlan !== null;
6633
+ const plan = currentPlan;
6320
6634
  const guardSuspension = new PromptGuardSuspension();
6321
6635
  const promptOptions = input.toolSession.tools.length > 0 ? {
6322
6636
  tools: input.toolSession.tools,
@@ -6329,13 +6643,13 @@ async function executeLogicalPromptPlan(input) {
6329
6643
  isOperatorAbortRequested: () => input.operatorAbortSignal?.aborted === true
6330
6644
  }
6331
6645
  } : { activeTools: input.toolSession.activeTools };
6332
- let preparedPromptRun = null;
6333
- if (continuePlan) {
6646
+ let runPrompt = () => plan.kind === "continue" ? input.piHandle.continueTurn(promptOptions) : input.piHandle.prompt(plan.promptText ?? "", promptOptions);
6647
+ if (plan.kind === "continue") {
6334
6648
  try {
6335
- await continuePlan.prepareForContinuation?.();
6336
- if (continuePlan.continueUserPrompt !== null) {
6337
- const content = continuePlan.continueUserPrompt;
6338
- const identity = continuePlan.identifiedPrompt;
6649
+ await plan.prepareForContinuation?.();
6650
+ if (plan.continueUserPrompt !== null) {
6651
+ const content = plan.continueUserPrompt;
6652
+ const identity = plan.identifiedPrompt;
6339
6653
  if (identity) {
6340
6654
  const expectedParentId = input.piHandle.getLeafId();
6341
6655
  if (findIdentifiedPrompt(input.piHandle, identity)) {
@@ -6346,7 +6660,7 @@ async function executeLogicalPromptPlan(input) {
6346
6660
  expectedParentId
6347
6661
  });
6348
6662
  } else {
6349
- preparedPromptRun = () => input.piHandle.promptCustom({ content, details: identity }, promptOptions);
6663
+ runPrompt = () => input.piHandle.promptCustom({ content, details: identity }, promptOptions);
6350
6664
  }
6351
6665
  } else {
6352
6666
  const promptText = await prepareContinuationUserPrompt({
@@ -6355,7 +6669,7 @@ async function executeLogicalPromptPlan(input) {
6355
6669
  promptText: content
6356
6670
  });
6357
6671
  if (promptText) {
6358
- preparedPromptRun = () => input.piHandle.promptLiteral(promptText, promptOptions);
6672
+ runPrompt = () => input.piHandle.promptLiteral(promptText, promptOptions);
6359
6673
  }
6360
6674
  }
6361
6675
  }
@@ -6378,13 +6692,7 @@ async function executeLogicalPromptPlan(input) {
6378
6692
  piHandle: input.piHandle,
6379
6693
  turnRecordId: input.turnRecordId,
6380
6694
  turnId: input.turnId,
6381
- runPrompt: () => {
6382
- if (preparedPromptRun) return preparedPromptRun();
6383
- if (continuePlan) {
6384
- return input.piHandle.continueTurn(promptOptions);
6385
- }
6386
- return input.piHandle.prompt(promptPlan?.promptText ?? "", promptOptions);
6387
- }
6695
+ runPrompt
6388
6696
  }
6389
6697
  );
6390
6698
  if (input.toolSession.terminalAcknowledgement.state() === "outcome_accepted") {
@@ -6451,10 +6759,10 @@ async function executeLogicalPromptPlan(input) {
6451
6759
  continue;
6452
6760
  }
6453
6761
  return reportFailure(error, {
6454
- code: usingContinueThisAttempt ? "turn.continue_failed" : "turn.prompt_failed",
6762
+ code: plan.kind === "continue" ? "turn.continue_failed" : "turn.prompt_failed",
6455
6763
  emitWorkerError: !(error instanceof PromptTimeoutError || error instanceof OperatorAbortError),
6456
6764
  fallbackErrorClass: "llm_error",
6457
- messagePrefix: usingContinueThisAttempt ? `Turn '${input.turnId}' continuation failed` : `Turn '${input.turnId}' prompt failed`
6765
+ messagePrefix: plan.kind === "continue" ? `Turn '${input.turnId}' continuation failed` : `Turn '${input.turnId}' prompt failed`
6458
6766
  });
6459
6767
  }
6460
6768
  }
@@ -6469,12 +6777,7 @@ async function runMissingToolRecovery(input) {
6469
6777
  input.initialAttempt.completionState
6470
6778
  );
6471
6779
  if (!baseMissingToolRecovery) {
6472
- return {
6473
- recovered: true,
6474
- finalAttempt: input.initialAttempt,
6475
- recoveryContext: null,
6476
- baseMissingToolRecoveryDescription: null
6477
- };
6780
+ return { finalAttempt: input.initialAttempt };
6478
6781
  }
6479
6782
  const recoveryContext = input.toolSession.buildRecoveryContext(baseMissingToolRecovery);
6480
6783
  const description = input.toolSession.describeRecovery(baseMissingToolRecovery);
@@ -6512,12 +6815,7 @@ async function runMissingToolRecovery(input) {
6512
6815
  { baseState: input.initialAttempt.completionState }
6513
6816
  );
6514
6817
  if (!input.toolSession.resolveMissingToolRecovery(finalAttempt.completionState)) {
6515
- return {
6516
- recovered: true,
6517
- finalAttempt,
6518
- recoveryContext,
6519
- baseMissingToolRecoveryDescription: description
6520
- };
6818
+ return { finalAttempt };
6521
6819
  }
6522
6820
  }
6523
6821
  reportError({
@@ -6532,10 +6830,8 @@ async function runMissingToolRecovery(input) {
6532
6830
  }
6533
6831
  });
6534
6832
  return {
6535
- recovered: false,
6536
6833
  finalAttempt,
6537
- recoveryContext,
6538
- baseMissingToolRecoveryDescription: description
6834
+ failure: { recoveryContext, description }
6539
6835
  };
6540
6836
  }
6541
6837
 
@@ -6566,20 +6862,9 @@ ${guidance}`
6566
6862
  );
6567
6863
  }
6568
6864
  var PI_SESSION_BOOTSTRAP_ENTRY_TYPES = /* @__PURE__ */ new Set(["model_change", "thinking_level_change"]);
6569
- function visitPiTreeEntries(nodes, visit) {
6570
- for (const node of nodes) {
6571
- visit(node.entry.type);
6572
- visitPiTreeEntries(node.children, visit);
6573
- }
6574
- }
6575
6865
  function isPiTreeEmptyForPreparedEmptyPlan(piHandle) {
6576
- let hasNonBootstrap = false;
6577
- visitPiTreeEntries(piHandle.getTree(), (entryType) => {
6578
- if (!PI_SESSION_BOOTSTRAP_ENTRY_TYPES.has(entryType)) {
6579
- hasNonBootstrap = true;
6580
- }
6581
- });
6582
- return !hasNonBootstrap;
6866
+ const isBootstrapOnly = (node) => PI_SESSION_BOOTSTRAP_ENTRY_TYPES.has(node.entry.type) && node.children.every(isBootstrapOnly);
6867
+ return piHandle.getTree().every(isBootstrapOnly);
6583
6868
  }
6584
6869
  function treePlanFromPreparedStart(input) {
6585
6870
  const { preparedStart, turnDef, piHandle } = input;
@@ -6749,7 +7034,7 @@ async function executeLlmTurn(input) {
6749
7034
  reportError({
6750
7035
  level: "error",
6751
7036
  code: "turn.primary_leaf_restore_failed",
6752
- message: `Failed to restore the primary path leaf after turn '${turnId}': ${toErrorMessage(restoreError)}`,
7037
+ message: `Failed to restore the primary path leaf after turn '${turnId}': ${toErrorMessage2(restoreError)}`,
6753
7038
  turnRecordId,
6754
7039
  turnId,
6755
7040
  errorClass: "infrastructure"
@@ -6757,7 +7042,7 @@ async function executeLlmTurn(input) {
6757
7042
  failure2 = new TurnExecutionError(
6758
7043
  turnId,
6759
7044
  "infrastructure",
6760
- `${message}. Failed to restore the primary path leaf: ${toErrorMessage(restoreError)}`,
7045
+ `${message}. Failed to restore the primary path leaf: ${toErrorMessage2(restoreError)}`,
6761
7046
  { recoveryContext: null }
6762
7047
  );
6763
7048
  }
@@ -6801,12 +7086,12 @@ async function executeLlmTurn(input) {
6801
7086
  let promptText = null;
6802
7087
  if (initialPromptlessTurnResumeReason === null || initialPromptlessTurnResumeReason === "active_turn_resume") {
6803
7088
  try {
6804
- promptText = await input.turnDef.prompt(input.ctx);
7089
+ promptText = await input.turnDef.prompt({ ...input.ctx, prepared: input.prepared });
6805
7090
  } catch (error) {
6806
7091
  return failWithWorkerError(
6807
7092
  "turn.prompt_preparation_failed",
6808
7093
  "infrastructure",
6809
- `Turn '${turnId}' prompt preparation failed: ${toErrorMessage(error)}`,
7094
+ `Turn '${turnId}' prompt preparation failed: ${toErrorMessage2(error)}`,
6810
7095
  null,
6811
7096
  { restorePrimaryLeaf: false }
6812
7097
  );
@@ -6964,14 +7249,15 @@ async function executeLlmTurn(input) {
6964
7249
  const finalCompletionState = recoveryResult.finalAttempt.completionState;
6965
7250
  const finalPromptResult = recoveryResult.finalAttempt.promptResult;
6966
7251
  const finalResolvedOutcome = recoveryResult.finalAttempt.resolvedOutcome;
6967
- if (!recoveryResult.recovered) {
7252
+ if (recoveryResult.failure) {
7253
+ const { recoveryContext, description } = recoveryResult.failure;
6968
7254
  return reportFailedTurn(
6969
7255
  "protocol_error",
6970
- `Turn '${turnId}' completed without the required tool calls after ${MAX_MISSING_TOOL_CALL_RECOVERY_ATTEMPTS} automatic recovery attempts: ${recoveryResult.baseMissingToolRecoveryDescription}`,
7256
+ `Turn '${turnId}' completed without the required tool calls after ${MAX_MISSING_TOOL_CALL_RECOVERY_ATTEMPTS} automatic recovery attempts: ${description}`,
6971
7257
  finalPromptResult.resultEntryId,
6972
7258
  {
6973
- recoveryContext: recoveryResult.recoveryContext,
6974
- restorePrimaryLeaf: recoveryResult.recoveryContext?.failureCode !== "missing_markdown_result"
7259
+ recoveryContext,
7260
+ restorePrimaryLeaf: recoveryContext.failureCode !== "missing_markdown_result"
6975
7261
  }
6976
7262
  );
6977
7263
  }
@@ -7017,6 +7303,7 @@ async function executeLlmTurn(input) {
7017
7303
  forkPiEntryId: treePlan.forkPiEntryId,
7018
7304
  resultPiEntryId: finalPromptResult.resultEntryId,
7019
7305
  turnResultMarkdown: finalizedTurnResultMarkdown.markdown,
7306
+ resultSummary: finalCompletionState.markdownState.resultSummary,
7020
7307
  rootEntryId: rootEntryIdAfterTurn
7021
7308
  }
7022
7309
  };
@@ -7026,6 +7313,21 @@ async function executeLlmTurn(input) {
7026
7313
  function failedResult(failure2, appliedTargetedInputs) {
7027
7314
  return { kind: "failed", failure: failure2, appliedTargetedInputs };
7028
7315
  }
7316
+ function normalizePreparedData(value) {
7317
+ if (value === void 0) {
7318
+ throw new Error("LLM turn preparation must return JSON-serializable data");
7319
+ }
7320
+ let serialized;
7321
+ try {
7322
+ serialized = JSON.stringify(value);
7323
+ } catch {
7324
+ throw new Error("LLM turn preparation must return JSON-serializable data");
7325
+ }
7326
+ if (Buffer.byteLength(serialized, "utf8") > 65536) {
7327
+ throw new Error("LLM turn preparation data exceeds 65536 bytes");
7328
+ }
7329
+ return JSON.parse(serialized);
7330
+ }
7029
7331
  async function executeSelectedTurn(input) {
7030
7332
  const { resolvedWorkerProcess, processSnapshot, projectSnapshots } = input.session;
7031
7333
  const { piHandle } = input;
@@ -7042,6 +7344,21 @@ async function executeSelectedTurn(input) {
7042
7344
  if (!handler) throw new Error(`Validated turn handler '${currentTurnId}' is unavailable`);
7043
7345
  let automaticIntegrationCallIndex = 0;
7044
7346
  let latestProgressReport = null;
7347
+ const reportProgress = (report) => {
7348
+ latestProgressReport = report;
7349
+ input.emit({ kind: "progress", turnRecordId: input.turnRecordId, report });
7350
+ };
7351
+ const callIntegrationTool = async (name, args) => {
7352
+ const tool = input.integrationTools?.find((candidate) => candidate.name === name);
7353
+ if (!tool) {
7354
+ throw new Error(`Integration tool '${name}' is not authorized for turn '${currentTurnId}'`);
7355
+ }
7356
+ automaticIntegrationCallIndex += 1;
7357
+ return tool.execute(args, {
7358
+ toolCallId: selectedTurnType === "automatic" ? `${input.turnRecordId}:${automaticIntegrationCallIndex}:${name}` : `${input.turnRecordId}:prepare:${automaticIntegrationCallIndex}:${name}`,
7359
+ signal: input.signal
7360
+ });
7361
+ };
7045
7362
  const ctx = {
7046
7363
  process: processSnapshot,
7047
7364
  projects: projectSnapshots,
@@ -7051,23 +7368,8 @@ async function executeSelectedTurn(input) {
7051
7368
  turnResultMarkdownByProduct: input.session.turnResultMarkdownByProduct,
7052
7369
  workspaceRoot: input.session.workspaceRoot,
7053
7370
  ...selectedTurnType === "automatic" ? {
7054
- reportProgress(report) {
7055
- latestProgressReport = report;
7056
- input.emit({ kind: "progress", turnRecordId: input.turnRecordId, report });
7057
- },
7058
- async callIntegrationTool(name, args) {
7059
- const tool = input.integrationTools?.find((candidate) => candidate.name === name);
7060
- if (!tool) {
7061
- throw new Error(
7062
- `Integration tool '${name}' is not authorized for turn '${currentTurnId}'`
7063
- );
7064
- }
7065
- automaticIntegrationCallIndex += 1;
7066
- return tool.execute(args, {
7067
- toolCallId: `${input.turnRecordId}:${automaticIntegrationCallIndex}:${name}`,
7068
- signal: input.signal
7069
- });
7070
- }
7371
+ reportProgress,
7372
+ callIntegrationTool
7071
7373
  } : {}
7072
7374
  };
7073
7375
  let terminal = null;
@@ -7099,9 +7401,36 @@ async function executeSelectedTurn(input) {
7099
7401
  `Turn '${currentTurnId}' requires a Pi handle`
7100
7402
  );
7101
7403
  }
7404
+ let prepared = input.session.llmPreparation?.data;
7405
+ if (turnDef.prepare && !input.session.llmPreparation) {
7406
+ try {
7407
+ prepared = normalizePreparedData(
7408
+ await turnDef.prepare({
7409
+ ...ctx,
7410
+ reportProgress,
7411
+ callIntegrationTool
7412
+ })
7413
+ );
7414
+ input.emit({ kind: "prepared", turnRecordId: input.turnRecordId, data: prepared });
7415
+ } catch (error) {
7416
+ const message = error instanceof Error ? error.message : String(error);
7417
+ throw new TurnExecutionFailure({
7418
+ turnRecordId: input.turnRecordId,
7419
+ turnId: currentTurnId,
7420
+ turnType: "llm",
7421
+ pathType: turnDef.branchType,
7422
+ failure: new TurnExecutionError(
7423
+ currentTurnId,
7424
+ "infrastructure",
7425
+ `Turn '${currentTurnId}' preparation failed: ${message}`
7426
+ )
7427
+ });
7428
+ }
7429
+ }
7102
7430
  const completed = await executeLlmTurn({
7103
7431
  resolvedWorkerProcess,
7104
7432
  ctx,
7433
+ ...turnDef.prepare ? { prepared } : {},
7105
7434
  piHandle,
7106
7435
  turnDef,
7107
7436
  turnId: currentTurnId,
@@ -7168,10 +7497,16 @@ async function executeSelectedTurn(input) {
7168
7497
  } catch (error) {
7169
7498
  const failedProgressReport = latestProgressReport;
7170
7499
  if (failedProgressReport) {
7500
+ const message = error instanceof Error ? error.message : String(error);
7501
+ const steps = failedProgressReport.steps.map(
7502
+ (step) => step.status === "in_progress" ? { ...step, status: "failed", detail: message } : step
7503
+ );
7504
+ const report = { ...failedProgressReport, steps };
7505
+ latestProgressReport = report;
7171
7506
  input.emit({
7172
7507
  kind: "progress",
7173
7508
  turnRecordId: input.turnRecordId,
7174
- report: failActiveTurnProgress(failedProgressReport)
7509
+ report
7175
7510
  });
7176
7511
  }
7177
7512
  if (error instanceof TurnExecutionFailure) return failedResult(error, appliedTargetedInputs);
@@ -7186,29 +7521,44 @@ function createWorkerRuntime(options) {
7186
7521
  const { config, adapters } = options;
7187
7522
  const sampleCredentials = adapters.sampleCredentials ?? sampleCredentialFiles;
7188
7523
  const ipc = adapters.transport;
7524
+ const deliveredSecrets = /* @__PURE__ */ new Set();
7525
+ const redact = (text) => redactSecrets(
7526
+ text,
7527
+ [...deliveredSecrets].sort((a, b) => b.length - a.length)
7528
+ );
7529
+ function redactValue(value) {
7530
+ if (deliveredSecrets.size === 0) return value;
7531
+ if (typeof value === "string") return redact(value);
7532
+ if (Array.isArray(value)) return value.map(redactValue);
7533
+ if (value && typeof value === "object")
7534
+ return Object.fromEntries(
7535
+ Object.entries(value).map(([key, item]) => [key, redactValue(item)])
7536
+ );
7537
+ return value;
7538
+ }
7539
+ const emitExtensionEvent = (event, payload) => adapters.extensionEvents?.emit(event, redactValue(payload));
7540
+ const writeStderr = (text) => adapters.stderr?.write(`${redact(text)}
7541
+ `);
7189
7542
  const queue = [];
7190
7543
  const timers = /* @__PURE__ */ new Map();
7191
7544
  let state = createInitialWorkerRuntimeState();
7192
7545
  let draining = false;
7193
7546
  let started = false;
7194
7547
  let invariantQueued = false;
7195
- let resolveClosed;
7196
- const closed = new Promise((resolve) => {
7197
- resolveClosed = resolve;
7198
- });
7548
+ const { promise: closed, resolve: resolveClosed } = Promise.withResolvers();
7199
7549
  const reporter = createWorkerIpcReporter({
7200
7550
  instanceId: config.instanceId,
7201
7551
  workerId: config.workerId,
7202
7552
  now: () => adapters.scheduler.now(),
7203
- send: (message) => ipc.send(message),
7204
- emitExtensionEvent: (event, payload) => adapters.extensionEvents?.emit(event, payload)
7553
+ send: (message) => ipc.send(redactValue(message)),
7554
+ emitExtensionEvent
7205
7555
  });
7206
7556
  const questionBridge = new WorkerQuestionBridge(reporter);
7207
7557
  const integrationToolBridge = new WorkerIntegrationToolBridge(reporter);
7208
7558
  let dispatch;
7209
7559
  const piEvents = createPiEventReporter({
7210
7560
  reporter,
7211
- emitExtensionEvent: (event, payload) => adapters.extensionEvents?.emit(event, payload),
7561
+ emitExtensionEvent,
7212
7562
  getCurrentSelectedTurnId: () => state.session?.selectedTurnId ?? null,
7213
7563
  getSessionTainted: () => state.sessionTainted,
7214
7564
  onLifecycleObservation(kind) {
@@ -7219,11 +7569,15 @@ function createWorkerRuntime(options) {
7219
7569
  instanceId: config.instanceId,
7220
7570
  piFactory: adapters.piFactory,
7221
7571
  gitOps: adapters.gitOps,
7572
+ developmentTools: adapters.developmentTools ?? new MiseDevelopmentToolEnvironment(),
7222
7573
  scheduler: adapters.scheduler,
7223
7574
  sessionSnapshots: adapters.sessionSnapshots,
7224
7575
  resolveWorkerProcess: adapters.resolveWorkerProcess,
7225
7576
  progress(payload) {
7226
7577
  reporter.workerTrace(payload, state.session?.selectedTurnId ?? null);
7578
+ },
7579
+ diagnosticTrace(text) {
7580
+ reporter.project({ kind: "protocol", type: "worker.diagnostic_trace", payload: { text } });
7227
7581
  }
7228
7582
  });
7229
7583
  const invariant = (error) => {
@@ -7348,6 +7702,12 @@ function createWorkerRuntime(options) {
7348
7702
  { turnRecordId: emission.turnRecordId, report: emission.report },
7349
7703
  command.session.selectedTurnId
7350
7704
  );
7705
+ } else if (emission.kind === "prepared") {
7706
+ reporter.workerEvent(
7707
+ "turn.prepared",
7708
+ { turnRecordId: emission.turnRecordId, data: emission.data },
7709
+ command.session.selectedTurnId
7710
+ );
7351
7711
  } else reporter.workerError(emission.payload, command.session.selectedTurnId);
7352
7712
  }
7353
7713
  })
@@ -7406,21 +7766,16 @@ function createWorkerRuntime(options) {
7406
7766
  workerId: config.workerId,
7407
7767
  ...output.payload
7408
7768
  } : output.payload;
7409
- adapters.extensionEvents?.emit(output.event, payload);
7769
+ emitExtensionEvent(output.event, payload);
7410
7770
  return;
7411
7771
  }
7412
7772
  if (output.kind === "diagnostic") {
7413
7773
  reporter.workerTrace(output.payload, state.session?.selectedTurnId ?? null);
7414
- if (output.stderr) adapters.stderr?.write(`${output.stderr}
7415
- `);
7416
- return;
7417
- }
7418
- if (output.kind === "stderr") {
7419
- adapters.stderr?.write(`${output.message}
7420
- `);
7774
+ if (output.stderr) writeStderr(output.stderr);
7421
7775
  return;
7422
7776
  }
7423
- launch(output);
7777
+ if (output.kind === "stderr") writeStderr(output.message);
7778
+ else launch(output);
7424
7779
  };
7425
7780
  function drain() {
7426
7781
  if (draining) return;
@@ -7457,6 +7812,9 @@ function createWorkerRuntime(options) {
7457
7812
  drain();
7458
7813
  };
7459
7814
  const receive = (message) => {
7815
+ if (message.type === "worker.start")
7816
+ for (const secret of extractDockerRegistrySecretValues(message.payload))
7817
+ deliveredSecrets.add(secret);
7460
7818
  if (message.type === "worker.integration_tool_result") {
7461
7819
  integrationToolBridge.handle(message);
7462
7820
  return;
@@ -7470,6 +7828,7 @@ function createWorkerRuntime(options) {
7470
7828
  dispatch({ kind: "operator_abort_observed" });
7471
7829
  return;
7472
7830
  }
7831
+ if (message.type === "worker.stop") resources.abortToolPreparation();
7473
7832
  dispatch({ kind: "server_message", message });
7474
7833
  };
7475
7834
  return {
@@ -7497,8 +7856,9 @@ function createWorkerRuntime(options) {
7497
7856
  }
7498
7857
 
7499
7858
  // src/entry-runtime.ts
7500
- import { existsSync as existsSync4, readFileSync as readFileSync3 } from "fs";
7501
- import path12 from "path";
7859
+ import { existsSync as existsSync5, readFileSync as readFileSync3 } from "fs";
7860
+ import path13 from "path";
7861
+ import { isUnknownRecord as isRecord } from "@leitwerk-dev/domain";
7502
7862
  import {
7503
7863
  buildExtensionCatalog,
7504
7864
  createCatalogWorkerDefinitionResolver,
@@ -7524,10 +7884,10 @@ import {
7524
7884
 
7525
7885
  // src/extension-entry-roots.ts
7526
7886
  import { existsSync as existsSync2, realpathSync } from "fs";
7527
- import path9 from "path";
7887
+ import path10 from "path";
7528
7888
  function isWithinDirectory(parentDir, candidatePath) {
7529
- const relative = path9.relative(parentDir, candidatePath);
7530
- return relative === "" || !relative.startsWith("..") && !path9.isAbsolute(relative);
7889
+ const relative = path10.relative(parentDir, candidatePath);
7890
+ return relative === "" || !relative.startsWith("..") && !path10.isAbsolute(relative);
7531
7891
  }
7532
7892
  function parseExtensionAllowedRoots(value) {
7533
7893
  if (!value) return [];
@@ -7539,7 +7899,7 @@ function parseExtensionAllowedRoots(value) {
7539
7899
  }
7540
7900
  if (!Array.isArray(parsed) || parsed.some((entry) => typeof entry !== "string")) return [];
7541
7901
  return parsed.flatMap((entry) => {
7542
- if (!path9.isAbsolute(entry) || !existsSync2(entry)) return [];
7902
+ if (!path10.isAbsolute(entry) || !existsSync2(entry)) return [];
7543
7903
  return [realpathSync(entry)];
7544
7904
  });
7545
7905
  }
@@ -7566,6 +7926,32 @@ import {
7566
7926
  WORKER_IPC_RECONNECT_ENV,
7567
7927
  WORKER_IPC_SERVER_URL_ENV
7568
7928
  } from "@leitwerk-dev/worker-protocol";
7929
+
7930
+ // src/connection-diagnostics.ts
7931
+ import { existsSync as existsSync3, writeFileSync as writeFileSync2 } from "fs";
7932
+ function createConnectionDiagnosticRecorder(deps = {
7933
+ log: (message) => console.error(message),
7934
+ persist: (message) => {
7935
+ if (existsSync3("/dev/termination-log")) writeFileSync2("/dev/termination-log", message);
7936
+ }
7937
+ }) {
7938
+ let first = "";
7939
+ return (message) => {
7940
+ if (!message) {
7941
+ first = "";
7942
+ } else {
7943
+ first ||= message;
7944
+ deps.log(message);
7945
+ }
7946
+ try {
7947
+ deps.persist(message && first !== message ? `${first}
7948
+ ${message}` : message);
7949
+ } catch {
7950
+ }
7951
+ };
7952
+ }
7953
+
7954
+ // src/ipc.ts
7569
7955
  function toError(error) {
7570
7956
  return error instanceof Error ? error : new Error(String(error));
7571
7957
  }
@@ -7591,6 +7977,27 @@ function webSocketDataToText(data) {
7591
7977
  }
7592
7978
  return data.toString("utf8");
7593
7979
  }
7980
+ var connectionErrorCodes = /* @__PURE__ */ new Set([
7981
+ "ECONNREFUSED",
7982
+ "ECONNRESET",
7983
+ "ENOTFOUND",
7984
+ "EAI_AGAIN",
7985
+ "ETIMEDOUT",
7986
+ "ENETUNREACH",
7987
+ "EHOSTUNREACH",
7988
+ "CERT_HAS_EXPIRED",
7989
+ "DEPTH_ZERO_SELF_SIGNED_CERT"
7990
+ ]);
7991
+ function connectionErrorCode(value) {
7992
+ for (let depth = 0; depth < 4 && value && typeof value === "object"; depth += 1) {
7993
+ const error = value;
7994
+ if (typeof error.code === "string" && connectionErrorCodes.has(error.code)) {
7995
+ return error.code;
7996
+ }
7997
+ value = error.error ?? error.cause;
7998
+ }
7999
+ return "websocket_error";
8000
+ }
7594
8001
  function createWebSocketWorkerIpc(input) {
7595
8002
  let messageHandler;
7596
8003
  let errorHandler;
@@ -7604,6 +8011,7 @@ function createWebSocketWorkerIpc(input) {
7604
8011
  const outbound = [];
7605
8012
  const reconnectEnabled = input.reconnect === true;
7606
8013
  const emitError = (error) => errorHandler?.(toError(error));
8014
+ const diagnostic = (detail) => `Worker connection ${openedOnce ? "reconnecting" : "initial_connect"}: attempt=${reconnectAttempt + 1}; ${detail}`;
7607
8015
  const clearReconnectTimer = () => {
7608
8016
  if (reconnectTimer) {
7609
8017
  clearTimeout(reconnectTimer);
@@ -7662,7 +8070,6 @@ function createWebSocketWorkerIpc(input) {
7662
8070
  reconnectTimer = null;
7663
8071
  connect();
7664
8072
  }, delayMs);
7665
- reconnectTimer.unref?.();
7666
8073
  };
7667
8074
  return {
7668
8075
  send(message) {
@@ -7700,12 +8107,15 @@ function createWebSocketWorkerIpc(input) {
7700
8107
  }
7701
8108
  socket = new WebSocketImpl(toWebSocketUrl(input));
7702
8109
  socket.addEventListener("open", () => {
8110
+ input.onDiagnostic?.("");
7703
8111
  reconnectAttempt = 0;
7704
8112
  flushOutbound();
7705
8113
  });
7706
8114
  socket.addEventListener("message", (event) => deliverText(webSocketDataToText(event.data)));
7707
8115
  socket.addEventListener("error", (event) => {
7708
- if (!stopping && !reconnectEnabled) {
8116
+ if (stopping) return;
8117
+ input.onDiagnostic?.(diagnostic(`error=${connectionErrorCode(event)}`));
8118
+ if (!reconnectEnabled) {
7709
8119
  emitError(event instanceof Error ? event : new Error("Worker WebSocket error"));
7710
8120
  }
7711
8121
  });
@@ -7713,6 +8123,9 @@ function createWebSocketWorkerIpc(input) {
7713
8123
  if (stopping) {
7714
8124
  return;
7715
8125
  }
8126
+ input.onDiagnostic?.(
8127
+ diagnostic(`close=${Number.isInteger(event?.code) ? event?.code : "unknown"}`)
8128
+ );
7716
8129
  socket = null;
7717
8130
  if (reconnectEnabled && event?.code !== 1008) {
7718
8131
  scheduleReconnect(connect);
@@ -7752,14 +8165,16 @@ function createWorkerIpcFromEnvironment(input) {
7752
8165
  instanceId: input.instanceId,
7753
8166
  workerId: input.workerId,
7754
8167
  token,
7755
- reconnect: env[WORKER_IPC_RECONNECT_ENV] === "1"
8168
+ reconnect: env[WORKER_IPC_RECONNECT_ENV] === "1",
8169
+ onDiagnostic: createConnectionDiagnosticRecorder()
7756
8170
  });
7757
8171
  }
7758
8172
 
7759
8173
  // src/result-image-upload.ts
7760
8174
  import { constants } from "fs";
7761
- import { open, realpath, stat } from "fs/promises";
7762
- import path10 from "path";
8175
+ import { open as open2, realpath, stat } from "fs/promises";
8176
+ import path11 from "path";
8177
+ import { setTimeout as sleep } from "timers/promises";
7763
8178
  import {
7764
8179
  buildWorkerResultImageUploadPath,
7765
8180
  parseWorkerResultImageUploadResponse,
@@ -7782,19 +8197,12 @@ function failure(entry, code, message) {
7782
8197
  return { ...entry, status: "failed", code, message };
7783
8198
  }
7784
8199
  function isWithinRoot(rootReal, fileReal) {
7785
- const relative = path10.relative(rootReal, fileReal);
7786
- return relative !== ".." && !relative.startsWith(`..${path10.sep}`) && !path10.isAbsolute(relative);
7787
- }
7788
- function isRetryableResponse(response) {
7789
- return response.status >= 500;
7790
- }
7791
- async function sleep(ms) {
7792
- if (ms <= 0) return;
7793
- await new Promise((resolve) => setTimeout(resolve, ms));
8200
+ const relative = path11.relative(rootReal, fileReal);
8201
+ return relative !== ".." && !relative.startsWith(`..${path11.sep}`) && !path11.isAbsolute(relative);
7794
8202
  }
7795
8203
  async function readBoundedWorkspaceFile(entry, workspaceRoot, maxSizeBytes) {
7796
8204
  const rootReal = await realpath(workspaceRoot);
7797
- const candidatePath = path10.resolve(workspaceRoot, entry.path);
8205
+ const candidatePath = path11.resolve(workspaceRoot, entry.path);
7798
8206
  const fileReal = await realpath(candidatePath);
7799
8207
  if (!isWithinRoot(rootReal, fileReal)) {
7800
8208
  return failure(
@@ -7803,7 +8211,7 @@ async function readBoundedWorkspaceFile(entry, workspaceRoot, maxSizeBytes) {
7803
8211
  "Image path resolves outside the process workspace"
7804
8212
  );
7805
8213
  }
7806
- const handle = await open(fileReal, constants.O_RDONLY | constants.O_NOFOLLOW);
8214
+ const handle = await open2(fileReal, constants.O_RDONLY | constants.O_NOFOLLOW);
7807
8215
  try {
7808
8216
  const before = await handle.stat();
7809
8217
  if (!before.isFile()) return failure(entry, "not_a_file", "Image path is not a regular file");
@@ -7911,32 +8319,28 @@ function createUploadResultImagesTool(input) {
7911
8319
  if (response.ok) {
7912
8320
  try {
7913
8321
  const body = parseWorkerResultImageUploadResponse(await response.json());
7914
- if (!body)
7915
- return failure(
7916
- entry,
7917
- "upload_invalid_response",
7918
- "Image upload response was invalid"
7919
- );
7920
- return {
7921
- ...entry,
7922
- status: "uploaded",
7923
- ...body,
7924
- markdown: `![${entry.alt.replace(/[\\\]]/g, "\\$&")}](${body.url})`
7925
- };
8322
+ if (body) {
8323
+ return {
8324
+ ...entry,
8325
+ status: "uploaded",
8326
+ ...body,
8327
+ markdown: `![${entry.alt.replace(/[\\\]]/g, "\\$&")}](${body.url})`
8328
+ };
8329
+ }
7926
8330
  } catch {
7927
- return failure(
7928
- entry,
7929
- "upload_invalid_response",
7930
- "Image upload response was invalid"
7931
- );
7932
8331
  }
8332
+ return failure(
8333
+ entry,
8334
+ "upload_invalid_response",
8335
+ "Image upload response was invalid"
8336
+ );
7933
8337
  }
7934
8338
  finalFailure = failure(
7935
8339
  entry,
7936
8340
  `upload_http_${response.status}`,
7937
8341
  `Image upload was rejected with HTTP ${response.status}`
7938
8342
  );
7939
- if (!isRetryableResponse(response)) return finalFailure;
8343
+ if (response.status < 500) return finalFailure;
7940
8344
  }
7941
8345
  if (attempt + 1 < MAX_UPLOAD_ATTEMPTS) {
7942
8346
  await (input.sleepImpl ?? sleep)(RETRY_DELAY_MS);
@@ -7961,8 +8365,8 @@ function createUploadResultImagesTool(input) {
7961
8365
  }
7962
8366
 
7963
8367
  // src/session-snapshot-exchange.ts
7964
- import { readFile as readFile3, stat as stat2 } from "fs/promises";
7965
- import { isEnoent } from "@leitwerk-dev/process-sdk";
8368
+ import { readFile as readFile4 } from "fs/promises";
8369
+ import { isEnoent as isEnoent2 } from "@leitwerk-dev/process-sdk";
7966
8370
  import {
7967
8371
  buildWorkerSessionSnapshotPath,
7968
8372
  WORKER_IPC_SERVER_URL_ENV as WORKER_IPC_SERVER_URL_ENV2,
@@ -7972,70 +8376,40 @@ import {
7972
8376
  WORKER_SESSION_SNAPSHOT_WORKER_ID_HEADER,
7973
8377
  WORKER_SNAPSHOT_TOKEN_ENV
7974
8378
  } from "@leitwerk-dev/worker-protocol";
7975
- function resolveWorkerSessionSnapshotUrl(input) {
7976
- return resolveWorkerHttpUrl(input.serverUrl, buildWorkerSessionSnapshotPath(input.instanceId));
7977
- }
7978
- async function localFileSize(filePath) {
7979
- try {
7980
- return (await stat2(filePath)).size;
7981
- } catch (error) {
7982
- if (isEnoent(error)) {
7983
- return null;
7984
- }
7985
- throw error;
7986
- }
7987
- }
7988
- async function fetchWithTimeout(input) {
7989
- const controller = new AbortController();
7990
- const timeout = setTimeout(() => controller.abort(), input.timeoutMs);
7991
- timeout.unref?.();
7992
- try {
7993
- return await input.fetchImpl(input.url, { ...input.init, signal: controller.signal });
7994
- } finally {
7995
- clearTimeout(timeout);
7996
- }
7997
- }
7998
8379
  function createWorkerSessionSnapshotExchange(input) {
7999
8380
  const fetchImpl = input.fetchImpl ?? globalThis.fetch;
8000
8381
  if (!fetchImpl) {
8001
8382
  return disabledWorkerSessionSnapshotExchange;
8002
8383
  }
8003
8384
  const timeoutMs = input.timeoutMs ?? 3e4;
8004
- const snapshotUrl = resolveWorkerSessionSnapshotUrl({
8005
- serverUrl: input.serverUrl,
8006
- instanceId: input.instanceId
8007
- });
8385
+ const snapshotUrl = resolveWorkerHttpUrl(
8386
+ input.serverUrl,
8387
+ buildWorkerSessionSnapshotPath(input.instanceId)
8388
+ );
8008
8389
  const authHeaders = {
8009
8390
  authorization: `Bearer ${input.token}`,
8010
8391
  [WORKER_SESSION_SNAPSHOT_WORKER_ID_HEADER]: input.workerId
8011
8392
  };
8012
8393
  return {
8013
8394
  async uploadSnapshot(treeFile, reason, metadata = {}) {
8014
- const size = await localFileSize(treeFile);
8015
- if (size === null) {
8016
- return { kind: "missing" };
8017
- }
8018
- if (size === 0) {
8019
- return { kind: "empty" };
8020
- }
8021
- const content = await readFile3(treeFile, "utf8");
8022
- if (content.length === 0) {
8023
- return { kind: "empty" };
8395
+ let content;
8396
+ try {
8397
+ content = await readFile4(treeFile, "utf8");
8398
+ } catch (error) {
8399
+ if (isEnoent2(error)) return { kind: "missing" };
8400
+ throw error;
8024
8401
  }
8025
- const response = await fetchWithTimeout({
8026
- fetchImpl,
8027
- url: snapshotUrl,
8028
- timeoutMs,
8029
- init: {
8030
- method: "PUT",
8031
- headers: {
8032
- ...authHeaders,
8033
- "content-type": WORKER_SESSION_SNAPSHOT_CONTENT_TYPE,
8034
- [WORKER_SESSION_SNAPSHOT_REASON_HEADER]: reason,
8035
- ...metadata.turnRecordId ? { [WORKER_SESSION_SNAPSHOT_TURN_RECORD_ID_HEADER]: metadata.turnRecordId } : {}
8036
- },
8037
- body: content
8038
- }
8402
+ if (content.length === 0) return { kind: "empty" };
8403
+ const response = await fetchImpl(snapshotUrl, {
8404
+ method: "PUT",
8405
+ headers: {
8406
+ ...authHeaders,
8407
+ "content-type": WORKER_SESSION_SNAPSHOT_CONTENT_TYPE,
8408
+ [WORKER_SESSION_SNAPSHOT_REASON_HEADER]: reason,
8409
+ ...metadata.turnRecordId ? { [WORKER_SESSION_SNAPSHOT_TURN_RECORD_ID_HEADER]: metadata.turnRecordId } : {}
8410
+ },
8411
+ body: content,
8412
+ signal: AbortSignal.timeout(timeoutMs)
8039
8413
  });
8040
8414
  if (!response.ok) {
8041
8415
  throw new Error(`Session snapshot upload failed with HTTP ${response.status}`);
@@ -8068,64 +8442,87 @@ function createWorkerSessionSnapshotExchangeFromEnv(input) {
8068
8442
 
8069
8443
  // src/workspace/node-run-root-git-ops.ts
8070
8444
  import {
8071
- chmodSync,
8072
- existsSync as existsSync3,
8073
- mkdirSync,
8074
- mkdtempSync,
8445
+ chmodSync as chmodSync2,
8446
+ existsSync as existsSync4,
8447
+ mkdirSync as mkdirSync2,
8448
+ mkdtempSync as mkdtempSync2,
8075
8449
  readFileSync as readFileSync2,
8076
- rmSync,
8077
- writeFileSync
8450
+ rmSync as rmSync2,
8451
+ writeFileSync as writeFileSync3
8078
8452
  } from "fs";
8079
8453
  import { tmpdir } from "os";
8080
- import path11 from "path";
8454
+ import path12 from "path";
8081
8455
  import {
8456
+ clearRepositoryGitHttpsHelpers,
8082
8457
  clearRepositoryGitSshWrappers,
8083
8458
  repositoryGitArgs,
8084
8459
  repositoryGitSubprocessEnv,
8460
+ repositoryHttpsUrl as repositoryHttpsUrl2,
8461
+ setRepositoryGitHttpsHelper,
8085
8462
  setRepositoryGitSshWrapper
8086
8463
  } from "@leitwerk-dev/process-sdk";
8087
8464
  import { resolveGitBinary } from "@leitwerk-dev/process-sdk/git-binary";
8088
- import { execa } from "execa";
8465
+ import { execa as execa2 } from "execa";
8089
8466
  import fg from "fast-glob";
8090
- function toAbsolute(targetPath) {
8091
- return path11.resolve(targetPath);
8092
- }
8093
8467
  var NodeRunRootGitOps = class {
8094
8468
  #credentialDir = null;
8095
8469
  configureRepositoryCredentials(credentials) {
8096
8470
  this.cleanupRepositoryCredentials();
8097
8471
  if (credentials.length === 0) return;
8098
- const root = mkdtempSync(path11.join(tmpdir(), "leitwerk-repo-auth-"));
8099
- chmodSync(root, 448);
8472
+ const root = mkdtempSync2(path12.join(tmpdir(), "leitwerk-repo-auth-"));
8473
+ chmodSync2(root, 448);
8100
8474
  this.#credentialDir = root;
8101
- for (const credential of credentials) {
8102
- const dir = path11.join(root, encodeURIComponent(credential.projectKey));
8103
- mkdirSync(dir, { mode: 448 });
8104
- const key = path11.join(dir, "identity");
8105
- const hosts = path11.join(dir, "known_hosts");
8106
- const wrapper = path11.join(dir, "ssh");
8107
- writeFileSync(key, `${credential.privateKey.trim()}
8475
+ try {
8476
+ for (const credential of credentials) {
8477
+ const dir = path12.join(root, encodeURIComponent(credential.projectKey));
8478
+ mkdirSync2(dir, { mode: 448 });
8479
+ if (credential.kind === "git_https") {
8480
+ const url = repositoryHttpsUrl2(credential.repositoryUrl);
8481
+ writeFileSync3(
8482
+ path12.join(dir, "credential.json"),
8483
+ JSON.stringify({
8484
+ host: url.host,
8485
+ path: url.pathname.slice(1),
8486
+ username: credential.username,
8487
+ password: credential.password
8488
+ }),
8489
+ { mode: 384 }
8490
+ );
8491
+ const helper = path12.join(dir, "credential.cjs");
8492
+ writeFileSync3(helper, HTTPS_CREDENTIAL_HELPER, { mode: 448 });
8493
+ setRepositoryGitHttpsHelper(credential.projectKey, helper);
8494
+ continue;
8495
+ }
8496
+ const key = path12.join(dir, "identity");
8497
+ const hosts = path12.join(dir, "known_hosts");
8498
+ const wrapper = path12.join(dir, "ssh");
8499
+ writeFileSync3(key, `${credential.privateKey.trim()}
8108
8500
  `, { mode: 384 });
8109
- writeFileSync(hosts, `${credential.knownHosts.trim()}
8501
+ writeFileSync3(hosts, `${credential.knownHosts.trim()}
8110
8502
  `, { mode: 384 });
8111
- writeFileSync(
8112
- wrapper,
8113
- `#!/bin/sh
8503
+ writeFileSync3(
8504
+ wrapper,
8505
+ `#!/bin/sh
8114
8506
  exec ssh -F /dev/null -o IdentitiesOnly=yes -o IdentityFile="${key}" -o UserKnownHostsFile="${hosts}" -o StrictHostKeyChecking=yes -o BatchMode=yes "$@"
8115
8507
  `,
8116
- { mode: 448 }
8117
- );
8118
- setRepositoryGitSshWrapper(credential.projectKey, wrapper);
8508
+ { mode: 448 }
8509
+ );
8510
+ setRepositoryGitSshWrapper(credential.projectKey, wrapper);
8511
+ }
8512
+ } catch (error) {
8513
+ this.cleanupRepositoryCredentials();
8514
+ throw error;
8119
8515
  }
8120
8516
  }
8121
8517
  cleanupRepositoryCredentials() {
8122
8518
  clearRepositoryGitSshWrappers();
8123
- if (this.#credentialDir) rmSync(this.#credentialDir, { recursive: true, force: true });
8519
+ clearRepositoryGitHttpsHelpers();
8520
+ if (this.#credentialDir) rmSync2(this.#credentialDir, { recursive: true, force: true });
8124
8521
  this.#credentialDir = null;
8125
8522
  }
8126
8523
  async runGit(args, cwd, projectKey) {
8127
- const result = await execa(resolveGitBinary(), repositoryGitArgs(args), {
8128
- ...cwd ? { cwd: toAbsolute(cwd) } : {},
8524
+ const result = await execa2(resolveGitBinary(), repositoryGitArgs(args), {
8525
+ ...cwd ? { cwd: path12.resolve(cwd) } : {},
8129
8526
  env: repositoryGitSubprocessEnv(projectKey ?? "", { GIT_TERMINAL_PROMPT: "0" }),
8130
8527
  extendEnv: false,
8131
8528
  stdin: "ignore"
@@ -8133,25 +8530,25 @@ exec ssh -F /dev/null -o IdentitiesOnly=yes -o IdentityFile="${key}" -o UserKnow
8133
8530
  return result.stdout;
8134
8531
  }
8135
8532
  async writeFile(repoDir, filePath, content) {
8136
- const absolutePath = toAbsolute(path11.join(repoDir, filePath));
8137
- mkdirSync(path11.dirname(absolutePath), { recursive: true });
8138
- writeFileSync(absolutePath, content, "utf8");
8533
+ const absolutePath = path12.resolve(path12.join(repoDir, filePath));
8534
+ mkdirSync2(path12.dirname(absolutePath), { recursive: true });
8535
+ writeFileSync3(absolutePath, content, "utf8");
8139
8536
  }
8140
8537
  async readFile(repoDir, filePath) {
8141
- const absolutePath = toAbsolute(path11.join(repoDir, filePath));
8142
- if (!existsSync3(absolutePath)) {
8538
+ const absolutePath = path12.resolve(path12.join(repoDir, filePath));
8539
+ if (!existsSync4(absolutePath)) {
8143
8540
  return null;
8144
8541
  }
8145
8542
  return readFileSync2(absolutePath, "utf8");
8146
8543
  }
8147
8544
  async clone(repoLocator, targetDir) {
8148
- const absoluteTargetDir = toAbsolute(targetDir);
8149
- rmSync(absoluteTargetDir, { recursive: true, force: true });
8150
- mkdirSync(path11.dirname(absoluteTargetDir), { recursive: true });
8545
+ const absoluteTargetDir = path12.resolve(targetDir);
8546
+ rmSync2(absoluteTargetDir, { recursive: true, force: true });
8547
+ mkdirSync2(path12.dirname(absoluteTargetDir), { recursive: true });
8151
8548
  await this.runGit(
8152
8549
  ["clone", repoLocator, absoluteTargetDir],
8153
8550
  void 0,
8154
- path11.basename(absoluteTargetDir)
8551
+ path12.basename(absoluteTargetDir)
8155
8552
  );
8156
8553
  }
8157
8554
  async checkout(repoDir, branch) {
@@ -8175,8 +8572,8 @@ exec ssh -F /dev/null -o IdentitiesOnly=yes -o IdentityFile="${key}" -o UserKnow
8175
8572
  return (await this.runGit(["rev-parse", "HEAD"], repoDir)).trim();
8176
8573
  }
8177
8574
  async listFiles(repoDir, pattern) {
8178
- const absoluteRoot = toAbsolute(repoDir);
8179
- if (!existsSync3(absoluteRoot)) {
8575
+ const absoluteRoot = path12.resolve(repoDir);
8576
+ if (!existsSync4(absoluteRoot)) {
8180
8577
  return [];
8181
8578
  }
8182
8579
  return (await fg(pattern, {
@@ -8187,12 +8584,25 @@ exec ssh -F /dev/null -o IdentitiesOnly=yes -o IdentityFile="${key}" -o UserKnow
8187
8584
  })).sort((a, b) => a.localeCompare(b));
8188
8585
  }
8189
8586
  };
8587
+ var HTTPS_CREDENTIAL_HELPER = `const fs = require('node:fs');
8588
+ if (process.argv[2] !== 'get') process.exit(0);
8589
+ const input = fs.readFileSync(0, 'utf8');
8590
+ const fields = Object.create(null);
8591
+ for (const line of input.split('\\n')) {
8592
+ const i = line.indexOf('=');
8593
+ if (i < 0) continue;
8594
+ const key = line.slice(0, i);
8595
+ if (Object.hasOwn(fields, key)) process.exit(0);
8596
+ fields[key] = line.slice(i + 1);
8597
+ }
8598
+ const c = JSON.parse(fs.readFileSync(require('node:path').join(__dirname, 'credential.json'), 'utf8'));
8599
+ if (fields.protocol !== 'https' || fields.host !== c.host || fields.path !== c.path ||
8600
+ (fields.username && fields.username !== c.username)) process.exit(0);
8601
+ process.stdout.write('username=' + c.username + '\\npassword=' + c.password + '\\n\\n');
8602
+ `;
8190
8603
 
8191
8604
  // src/entry-runtime.ts
8192
8605
  var runtimeCatalogPromise = null;
8193
- function isRecord(value) {
8194
- return typeof value === "object" && value !== null && !Array.isArray(value);
8195
- }
8196
8606
  function listWorkspacePatterns(workspaces) {
8197
8607
  if (Array.isArray(workspaces)) {
8198
8608
  return workspaces.filter((value) => typeof value === "string");
@@ -8203,10 +8613,10 @@ function listWorkspacePatterns(workspaces) {
8203
8613
  return [];
8204
8614
  }
8205
8615
  function findWorkspaceRoot(startDir) {
8206
- let current = path12.resolve(startDir);
8616
+ let current = path13.resolve(startDir);
8207
8617
  while (true) {
8208
- const packageJsonPath = path12.join(current, "package.json");
8209
- if (existsSync4(packageJsonPath)) {
8618
+ const packageJsonPath = path13.join(current, "package.json");
8619
+ if (existsSync5(packageJsonPath)) {
8210
8620
  try {
8211
8621
  const parsed = JSON.parse(readFileSync3(packageJsonPath, "utf8"));
8212
8622
  if (listWorkspacePatterns(parsed.workspaces).length > 0) {
@@ -8215,7 +8625,7 @@ function findWorkspaceRoot(startDir) {
8215
8625
  } catch {
8216
8626
  }
8217
8627
  }
8218
- const parent = path12.dirname(current);
8628
+ const parent = path13.dirname(current);
8219
8629
  if (parent === current) {
8220
8630
  return null;
8221
8631
  }
@@ -8319,6 +8729,7 @@ function createWorkerEntryRuntime(overrides = {}) {
8319
8729
  resultImageTools,
8320
8730
  piFactory: overrides.piFactory ?? resolveDefaultPiFactory(),
8321
8731
  gitOps: overrides.gitOps ?? new NodeRunRootGitOps(),
8732
+ developmentTools: overrides.developmentTools ?? new MiseDevelopmentToolEnvironment(runtimeEnv),
8322
8733
  resolveWorkerProcess,
8323
8734
  extensionEvents: workerExtensionApi.events,
8324
8735
  stderr: overrides.stderr,
@@ -8329,6 +8740,12 @@ function createWorkerEntryRuntime(overrides = {}) {
8329
8740
  }
8330
8741
 
8331
8742
  export {
8743
+ PINNED_MISE_VERSION,
8744
+ DevelopmentToolPreparationError,
8745
+ validateMiseVersion,
8746
+ buildMiseSubprocessEnvironment,
8747
+ normalizeMiseEvidence,
8748
+ MiseDevelopmentToolEnvironment,
8332
8749
  doesPiEventResetInactivity,
8333
8750
  translateAgentSessionEventEnvelope,
8334
8751
  SdkPiTreeHandle,
@@ -8344,4 +8761,4 @@ export {
8344
8761
  createWorkerRuntime,
8345
8762
  createWorkerEntryRuntime
8346
8763
  };
8347
- //# sourceMappingURL=chunk-O6332GRG.js.map
8764
+ //# sourceMappingURL=chunk-Y7S2MZD3.js.map