@leitwerk-dev/worker 0.1.8 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/automatic-turn-executor.d.ts +1 -0
- package/dist/automatic-turn-executor.d.ts.map +1 -1
- package/dist/{chunk-ZTJ7UAOC.js → chunk-Y7S2MZD3.js} +1423 -917
- package/dist/chunk-Y7S2MZD3.js.map +1 -0
- package/dist/connection-diagnostics.d.ts +5 -0
- package/dist/connection-diagnostics.d.ts.map +1 -0
- package/dist/container-entry-main.d.ts +2 -0
- package/dist/container-entry-main.d.ts.map +1 -0
- package/dist/container-entry-main.js +232 -0
- package/dist/container-entry-main.js.map +1 -0
- package/dist/container-entry.d.ts +14 -0
- package/dist/container-entry.d.ts.map +1 -0
- package/dist/development-tool-environment.d.ts +48 -0
- package/dist/development-tool-environment.d.ts.map +1 -0
- package/dist/diagnostics.d.ts +9 -1
- package/dist/diagnostics.d.ts.map +1 -1
- package/dist/docker-registry-credentials.d.ts +8 -0
- package/dist/docker-registry-credentials.d.ts.map +1 -0
- package/dist/entry-runtime.d.ts +1 -0
- package/dist/entry-runtime.d.ts.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +44 -5
- package/dist/index.js.map +1 -1
- package/dist/input-consumer.d.ts +6 -11
- package/dist/input-consumer.d.ts.map +1 -1
- package/dist/ipc.d.ts +1 -0
- package/dist/ipc.d.ts.map +1 -1
- package/dist/logical-prompt-runner.d.ts.map +1 -1
- package/dist/managed-pi-bootstrap.d.ts.map +1 -1
- package/dist/missing-tool-recovery-runner.d.ts +4 -3
- package/dist/missing-tool-recovery-runner.d.ts.map +1 -1
- package/dist/pi-adapter.d.ts +1 -0
- package/dist/pi-adapter.d.ts.map +1 -1
- package/dist/pi-event-reporter.d.ts.map +1 -1
- package/dist/pi-resource-bundle.d.ts +11 -0
- package/dist/pi-resource-bundle.d.ts.map +1 -1
- package/dist/pre-turn-targeted-inputs.d.ts +8 -7
- package/dist/pre-turn-targeted-inputs.d.ts.map +1 -1
- package/dist/prompt-guards.d.ts.map +1 -1
- package/dist/repository-bash-tool.d.ts +4 -0
- package/dist/repository-bash-tool.d.ts.map +1 -0
- package/dist/resource-loader-factory.d.ts +1 -2
- package/dist/resource-loader-factory.d.ts.map +1 -1
- package/dist/result-image-upload.d.ts.map +1 -1
- package/dist/runtime/adapters.d.ts +2 -0
- package/dist/runtime/adapters.d.ts.map +1 -1
- package/dist/runtime/bootstrap-session.d.ts +8 -5
- package/dist/runtime/bootstrap-session.d.ts.map +1 -1
- package/dist/runtime/bootstrap.d.ts +14 -18
- package/dist/runtime/bootstrap.d.ts.map +1 -1
- package/dist/runtime/failure-policy.d.ts +1 -0
- package/dist/runtime/failure-policy.d.ts.map +1 -1
- package/dist/runtime/index.d.ts.map +1 -1
- package/dist/runtime/lifecycle-reducer.d.ts +4 -1
- package/dist/runtime/lifecycle-reducer.d.ts.map +1 -1
- package/dist/runtime/llm-turn-execution.d.ts +3 -8
- package/dist/runtime/llm-turn-execution.d.ts.map +1 -1
- package/dist/runtime/turn-execution.d.ts +2 -9
- package/dist/runtime/turn-execution.d.ts.map +1 -1
- package/dist/session-snapshot-exchange.d.ts +0 -4
- package/dist/session-snapshot-exchange.d.ts.map +1 -1
- package/dist/turn-continuation.d.ts.map +1 -1
- package/dist/turn-execution-error.d.ts +1 -1
- package/dist/turn-execution-error.d.ts.map +1 -1
- package/dist/turn-execution-result.d.ts +1 -0
- package/dist/turn-execution-result.d.ts.map +1 -1
- package/dist/turn-outcome-tool-session.d.ts +0 -2
- package/dist/turn-outcome-tool-session.d.ts.map +1 -1
- package/dist/turn-result-markdown.d.ts +2 -1
- package/dist/turn-result-markdown.d.ts.map +1 -1
- package/dist/turn-tree-strategy.d.ts +0 -1
- package/dist/turn-tree-strategy.d.ts.map +1 -1
- package/dist/worker-entry.js +16 -4
- package/dist/worker-entry.js.map +1 -1
- package/dist/worker-ipc-reporter.d.ts.map +1 -1
- package/dist/workspace/manifest.d.ts +4 -7
- package/dist/workspace/manifest.d.ts.map +1 -1
- package/dist/workspace/node-run-root-git-ops.d.ts +2 -2
- package/dist/workspace/node-run-root-git-ops.d.ts.map +1 -1
- package/dist/workspace/resource-aggregator.d.ts.map +1 -1
- package/dist/workspace/run-root.d.ts +9 -20
- package/dist/workspace/run-root.d.ts.map +1 -1
- package/package.json +8 -8
- package/src/automatic-turn-executor.ts +2 -0
- package/src/connection-diagnostics.ts +27 -0
- package/src/container-entry-main.ts +24 -0
- package/src/container-entry.ts +246 -0
- package/src/development-tool-environment.ts +452 -0
- package/src/diagnostics.ts +3 -1
- package/src/docker-registry-credentials.ts +65 -0
- package/src/entry-runtime.ts +5 -4
- package/src/index.ts +11 -0
- package/src/input-consumer.ts +7 -29
- package/src/ipc.ts +37 -2
- package/src/logical-prompt-runner.ts +23 -29
- package/src/managed-pi-bootstrap.ts +3 -3
- package/src/missing-tool-recovery-runner.ts +4 -18
- package/src/pi-adapter.ts +19 -50
- package/src/pi-event-reporter.ts +16 -38
- package/src/pi-resource-bundle.ts +67 -1
- package/src/pre-turn-targeted-inputs.ts +9 -11
- package/src/prompt-guards.ts +44 -75
- package/src/repository-bash-tool.ts +15 -0
- package/src/resource-loader-factory.ts +1 -18
- package/src/result-image-upload.ts +16 -27
- package/src/runtime/adapters.ts +2 -0
- package/src/runtime/bootstrap-session.ts +69 -39
- package/src/runtime/bootstrap.ts +160 -103
- package/src/runtime/failure-policy.ts +36 -42
- package/src/runtime/index.ts +49 -14
- package/src/runtime/lifecycle-reducer.ts +140 -173
- package/src/runtime/llm-turn-execution.ts +13 -30
- package/src/runtime/turn-execution.ts +91 -9
- package/src/session-snapshot-exchange.ts +23 -64
- package/src/turn-continuation.ts +9 -17
- package/src/turn-execution-error.ts +3 -11
- package/src/turn-execution-result.ts +1 -0
- package/src/turn-outcome-tool-session.ts +25 -21
- package/src/turn-result-markdown.ts +31 -34
- package/src/turn-tree-strategy.ts +6 -19
- package/src/worker-entry.ts +8 -0
- package/src/worker-ipc-reporter.ts +8 -16
- package/src/workspace/manifest.ts +5 -7
- package/src/workspace/node-run-root-git-ops.ts +65 -25
- package/src/workspace/resource-aggregator.ts +5 -16
- package/src/workspace/run-root.ts +38 -89
- package/dist/automatic-turn-executor.js +0 -58
- package/dist/automatic-turn-executor.js.map +0 -1
- package/dist/chunk-ZTJ7UAOC.js.map +0 -1
- package/dist/diagnostics.js +0 -51
- package/dist/diagnostics.js.map +0 -1
- package/dist/entry-runtime.js +0 -160
- package/dist/entry-runtime.js.map +0 -1
- package/dist/event-translator.js +0 -12
- package/dist/event-translator.js.map +0 -1
- package/dist/extension-entry-roots.js +0 -41
- package/dist/extension-entry-roots.js.map +0 -1
- package/dist/identified-pi-entry.js +0 -125
- package/dist/identified-pi-entry.js.map +0 -1
- package/dist/input-consumer.js +0 -34
- package/dist/input-consumer.js.map +0 -1
- package/dist/integration-tool-bridge.js +0 -53
- package/dist/integration-tool-bridge.js.map +0 -1
- package/dist/ipc.js +0 -192
- package/dist/ipc.js.map +0 -1
- package/dist/logical-prompt-runner.js +0 -225
- package/dist/logical-prompt-runner.js.map +0 -1
- package/dist/managed-pi-agent-dir.js +0 -66
- package/dist/managed-pi-agent-dir.js.map +0 -1
- package/dist/managed-pi-bootstrap.js +0 -135
- package/dist/managed-pi-bootstrap.js.map +0 -1
- package/dist/missing-tool-recovery-runner.js +0 -73
- package/dist/missing-tool-recovery-runner.js.map +0 -1
- package/dist/pi-adapter.js +0 -1648
- package/dist/pi-adapter.js.map +0 -1
- package/dist/pi-branch-guard.js +0 -75
- package/dist/pi-branch-guard.js.map +0 -1
- package/dist/pi-event-reporter.js +0 -136
- package/dist/pi-event-reporter.js.map +0 -1
- package/dist/pi-resource-bundle.js +0 -58
- package/dist/pi-resource-bundle.js.map +0 -1
- package/dist/pre-turn-targeted-inputs.js +0 -101
- package/dist/pre-turn-targeted-inputs.js.map +0 -1
- package/dist/prompt-guards.js +0 -318
- package/dist/prompt-guards.js.map +0 -1
- package/dist/question-bridge.js +0 -24
- package/dist/question-bridge.js.map +0 -1
- package/dist/question-tool.js +0 -54
- package/dist/question-tool.js.map +0 -1
- package/dist/replaying-request-bridge.js +0 -71
- package/dist/replaying-request-bridge.js.map +0 -1
- package/dist/resource-loader-factory.js +0 -87
- package/dist/resource-loader-factory.js.map +0 -1
- package/dist/result-image-upload.js +0 -183
- package/dist/result-image-upload.js.map +0 -1
- package/dist/runtime/adapters.js +0 -15
- package/dist/runtime/adapters.js.map +0 -1
- package/dist/runtime/bootstrap-session.js +0 -199
- package/dist/runtime/bootstrap-session.js.map +0 -1
- package/dist/runtime/bootstrap.js +0 -440
- package/dist/runtime/bootstrap.js.map +0 -1
- package/dist/runtime/failure-policy.js +0 -182
- package/dist/runtime/failure-policy.js.map +0 -1
- package/dist/runtime/index.js +0 -336
- package/dist/runtime/index.js.map +0 -1
- package/dist/runtime/lifecycle-reducer.js +0 -1100
- package/dist/runtime/lifecycle-reducer.js.map +0 -1
- package/dist/runtime/llm-turn-execution.js +0 -494
- package/dist/runtime/llm-turn-execution.js.map +0 -1
- package/dist/runtime/settings.js +0 -24
- package/dist/runtime/settings.js.map +0 -1
- package/dist/runtime/snapshot-policy.js +0 -16
- package/dist/runtime/snapshot-policy.js.map +0 -1
- package/dist/runtime/turn-execution.js +0 -121
- package/dist/runtime/turn-execution.js.map +0 -1
- package/dist/session-snapshot-exchange.js +0 -102
- package/dist/session-snapshot-exchange.js.map +0 -1
- package/dist/test-helpers/fake-websocket.js +0 -40
- package/dist/test-helpers/fake-websocket.js.map +0 -1
- package/dist/test-helpers/ipc-harness.d.ts +0 -11
- package/dist/test-helpers/ipc-harness.d.ts.map +0 -1
- package/dist/test-helpers/ipc-harness.js +0 -17
- package/dist/test-helpers/ipc-harness.js.map +0 -1
- package/dist/turn-continuation.js +0 -80
- package/dist/turn-continuation.js.map +0 -1
- package/dist/turn-execution-error.js +0 -64
- package/dist/turn-execution-error.js.map +0 -1
- package/dist/turn-execution-result.js +0 -21
- package/dist/turn-execution-result.js.map +0 -1
- package/dist/turn-outcome-tool-session.js +0 -210
- package/dist/turn-outcome-tool-session.js.map +0 -1
- package/dist/turn-record-id.js +0 -10
- package/dist/turn-record-id.js.map +0 -1
- package/dist/turn-result-markdown.js +0 -263
- package/dist/turn-result-markdown.js.map +0 -1
- package/dist/turn-tree-strategy.js +0 -80
- package/dist/turn-tree-strategy.js.map +0 -1
- package/dist/worker-http.js +0 -9
- package/dist/worker-http.js.map +0 -1
- package/dist/worker-ipc-reporter.js +0 -58
- package/dist/worker-ipc-reporter.js.map +0 -1
- package/dist/worker-payloads.js +0 -66
- package/dist/worker-payloads.js.map +0 -1
- package/dist/worker-start-payload.js +0 -5
- package/dist/worker-start-payload.js.map +0 -1
- package/dist/workspace/manifest.js +0 -79
- package/dist/workspace/manifest.js.map +0 -1
- package/dist/workspace/node-run-root-git-ops.js +0 -96
- package/dist/workspace/node-run-root-git-ops.js.map +0 -1
- package/dist/workspace/resource-aggregator.js +0 -39
- package/dist/workspace/resource-aggregator.js.map +0 -1
- package/dist/workspace/run-root.js +0 -209
- package/dist/workspace/run-root.js.map +0 -1
- 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
|
|
4
|
-
import {
|
|
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
|
|
448
|
+
import path2 from "path";
|
|
75
449
|
var AGGREGATED_AGENTS_REL = "AGENTS.md";
|
|
76
|
-
var AGGREGATED_SKILLS_DIR_REL =
|
|
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 =
|
|
457
|
+
const entryPath = path2.join(directory, entry.name);
|
|
84
458
|
if (entry.isDirectory()) visit(entryPath);
|
|
85
|
-
else if (entry.isFile() && PI_EXTENSION_SUFFIXES.has(
|
|
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 =
|
|
96
|
-
const aggregatedSkillsDir =
|
|
97
|
-
const managedExtensionsDir =
|
|
98
|
-
const managedSkillsDir =
|
|
99
|
-
const managedPromptsDir =
|
|
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 =
|
|
131
|
-
if (base.agentsFiles.some((file) =>
|
|
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 (
|
|
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
|
-
|
|
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 =
|
|
1530
|
-
return relative === "" || !relative.startsWith(`..${
|
|
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 =
|
|
1535
|
-
const aggregatedSkillsRoot =
|
|
1536
|
-
if (
|
|
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 =
|
|
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) =>
|
|
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) =>
|
|
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:
|
|
1607
|
-
modelsPath:
|
|
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
|
|
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
|
|
2022
|
+
await writeFile2(input.treeFile, `${JSON.stringify(header)}
|
|
1666
2023
|
`, { flag: "wx" });
|
|
1667
2024
|
} catch (error) {
|
|
1668
|
-
if (
|
|
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 `${
|
|
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
|
-
|
|
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: [
|
|
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
|
|
2180
|
+
import { chmod, lstat, mkdir as mkdir3, rename as rename2, writeFile as writeFile3 } from "fs/promises";
|
|
1818
2181
|
import { homedir } from "os";
|
|
1819
|
-
import
|
|
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 =
|
|
1828
|
-
const ambient =
|
|
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
|
|
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 ||
|
|
2201
|
+
if (!value || path4.posix.isAbsolute(value) || value.includes("\\")) {
|
|
1839
2202
|
throw new Error(`Invalid credential file path '${value}'`);
|
|
1840
2203
|
}
|
|
1841
|
-
const normalized =
|
|
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
|
|
1850
|
-
current =
|
|
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
|
|
2219
|
+
await mkdir3(current, { recursive: false, mode: 448 });
|
|
1857
2220
|
}
|
|
1858
2221
|
}
|
|
1859
2222
|
}
|
|
1860
2223
|
async function writeManagedPiCredentialFiles(agentDir, files) {
|
|
1861
|
-
const root =
|
|
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 =
|
|
1871
|
-
if (!target.startsWith(`${root}${
|
|
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 =
|
|
1875
|
-
|
|
1876
|
-
`.${
|
|
2237
|
+
const tmp = path4.join(
|
|
2238
|
+
path4.dirname(target),
|
|
2239
|
+
`.${path4.basename(target)}.tmp-${process.pid}-${randomUUID()}`
|
|
1877
2240
|
);
|
|
1878
|
-
await
|
|
2241
|
+
await writeFile3(tmp, file.content, { mode: 384, flag: "wx" });
|
|
1879
2242
|
await chmod(tmp, 384);
|
|
1880
|
-
await
|
|
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
|
|
1888
|
-
import
|
|
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 =
|
|
1901
|
-
if (
|
|
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
|
|
1905
|
-
await
|
|
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 =
|
|
1911
|
-
const parent =
|
|
1912
|
-
await
|
|
1913
|
-
const marker =
|
|
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:
|
|
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 =
|
|
2344
|
+
const staging = path5.join(
|
|
1927
2345
|
parent,
|
|
1928
|
-
`.${
|
|
2346
|
+
`.${path5.basename(targetDir)}.staging-${process.pid}-${randomUUID2()}`
|
|
1929
2347
|
);
|
|
1930
2348
|
try {
|
|
1931
|
-
await
|
|
2349
|
+
await mkdir4(staging, { mode: 448 });
|
|
1932
2350
|
await writeExtractedFiles(staging, files);
|
|
1933
|
-
await
|
|
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
|
|
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:
|
|
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
|
-
|
|
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
|
-
|
|
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 =
|
|
2165
|
-
const toolName =
|
|
2166
|
-
const source =
|
|
2167
|
-
const provider =
|
|
2168
|
-
const model =
|
|
2169
|
-
const 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 =
|
|
2190
|
-
const maxAttempts =
|
|
2191
|
-
const delayMs =
|
|
2192
|
-
const errorMessage =
|
|
2193
|
-
const finalError =
|
|
2194
|
-
const message =
|
|
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?.(
|
|
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({
|
|
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
|
-
|
|
2357
|
-
|
|
2358
|
-
|
|
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(
|
|
2480
|
-
|
|
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
|
|
2500
|
-
import
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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 =
|
|
2638
|
-
const
|
|
2639
|
-
if (!
|
|
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 ((
|
|
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
|
|
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
|
|
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
|
|
2989
|
-
if (!
|
|
2990
|
-
if (
|
|
2991
|
-
if (
|
|
2992
|
-
if (
|
|
2993
|
-
if (
|
|
2994
|
-
if (
|
|
2995
|
-
const componentField =
|
|
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
|
|
3063
|
-
|
|
3064
|
-
|
|
3065
|
-
|
|
3066
|
-
|
|
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
|
|
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 =
|
|
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
|
|
3080
|
-
const
|
|
3081
|
-
|
|
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 =
|
|
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
|
-
|
|
3205
|
-
|
|
3206
|
-
|
|
3207
|
-
|
|
3208
|
-
|
|
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
|
-
|
|
3227
|
-
|
|
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
|
-
|
|
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
|
|
3682
|
+
const withoutCredentials = {
|
|
3292
3683
|
...payload,
|
|
3293
|
-
repositoryCredentials: void 0
|
|
3684
|
+
repositoryCredentials: void 0,
|
|
3685
|
+
dockerRegistryCredentials: void 0
|
|
3294
3686
|
};
|
|
3295
|
-
if (!isLlmWorkerStartPayload(
|
|
3296
|
-
return
|
|
3687
|
+
if (!isLlmWorkerStartPayload(withoutCredentials) || !withoutCredentials.bootstrap.credential) {
|
|
3688
|
+
return withoutCredentials;
|
|
3297
3689
|
}
|
|
3298
3690
|
return {
|
|
3299
|
-
...
|
|
3300
|
-
repositoryCredentials: void 0,
|
|
3691
|
+
...withoutCredentials,
|
|
3301
3692
|
bootstrap: {
|
|
3302
|
-
...
|
|
3303
|
-
credential: { ...
|
|
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
|
|
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
|
-
|
|
3327
|
-
|
|
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
|
|
3355
|
-
|
|
3356
|
-
|
|
3357
|
-
|
|
3358
|
-
|
|
3359
|
-
|
|
3360
|
-
|
|
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
|
-
|
|
3517
|
-
|
|
3518
|
-
|
|
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 ?
|
|
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
|
-
|
|
3572
|
-
|
|
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
|
-
|
|
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
|
|
3751
|
-
|
|
3752
|
-
|
|
3753
|
-
|
|
3754
|
-
|
|
3755
|
-
|
|
3756
|
-
|
|
3757
|
-
|
|
3758
|
-
|
|
3759
|
-
|
|
3760
|
-
|
|
3761
|
-
|
|
3762
|
-
|
|
3763
|
-
|
|
3764
|
-
|
|
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
|
|
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
|
|
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
|
-
|
|
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}` :
|
|
3986
|
-
const 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: {
|
|
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:
|
|
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
|
|
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 };
|
|
@@ -4124,12 +4577,17 @@ function createInitialWorkerRuntimeState() {
|
|
|
4124
4577
|
publication: { kind: "none" }
|
|
4125
4578
|
},
|
|
4126
4579
|
credential: null,
|
|
4127
|
-
timers: {
|
|
4580
|
+
timers: {
|
|
4581
|
+
heartbeat: null,
|
|
4582
|
+
acceptance_retry: null,
|
|
4583
|
+
credential_poll: null,
|
|
4584
|
+
terminal_ack: null
|
|
4585
|
+
}
|
|
4128
4586
|
};
|
|
4129
4587
|
}
|
|
4130
4588
|
function deriveReportedWorkerState(state) {
|
|
4131
4589
|
if (state.phase.kind === "draining" || state.phase.kind === "cleaning") return "draining";
|
|
4132
|
-
if (state.phase.kind === "active" && (state.phase.turnStatus === "executing" || state.work.publication.kind === "terminal_snapshot") || state.work.deliveryHeadSequence !== null)
|
|
4590
|
+
if (state.phase.kind === "active" && (state.phase.turnStatus === "executing" || state.work.publication.kind === "terminal_snapshot" || state.work.publication.kind === "terminal_pending_ack") || state.work.deliveryHeadSequence !== null)
|
|
4133
4591
|
return "busy";
|
|
4134
4592
|
return "idle";
|
|
4135
4593
|
}
|
|
@@ -4196,62 +4654,28 @@ function snapshotMatches(snapshot, event) {
|
|
|
4196
4654
|
function hasActivePublication(state) {
|
|
4197
4655
|
return state.work.publication.kind !== "none";
|
|
4198
4656
|
}
|
|
4199
|
-
function
|
|
4657
|
+
function beginSnapshot(state, publication, source, outputs) {
|
|
4200
4658
|
if (hasActivePublication(state)) throw new Error("Snapshot publication is already active");
|
|
4659
|
+
outputs.push({ kind: "upload_snapshot", ...publication.snapshot, source });
|
|
4660
|
+
return { ...state, work: { ...state.work, publication } };
|
|
4201
4661
|
}
|
|
4202
|
-
|
|
4203
|
-
|
|
4204
|
-
|
|
4205
|
-
|
|
4206
|
-
|
|
4207
|
-
|
|
4208
|
-
|
|
4209
|
-
|
|
4210
|
-
|
|
4211
|
-
|
|
4212
|
-
|
|
4213
|
-
|
|
4214
|
-
|
|
4215
|
-
|
|
4216
|
-
|
|
4217
|
-
|
|
4218
|
-
|
|
4219
|
-
return {
|
|
4220
|
-
...state,
|
|
4221
|
-
work: {
|
|
4222
|
-
...state.work,
|
|
4223
|
-
publication: { kind: "terminal_snapshot", snapshot, terminal }
|
|
4224
|
-
}
|
|
4225
|
-
};
|
|
4226
|
-
}
|
|
4227
|
-
function beginCleanupSnapshot(state, source, outputs) {
|
|
4228
|
-
requireNoPublication(state);
|
|
4229
|
-
const snapshot = {
|
|
4230
|
-
point: "before_cleanup_completed",
|
|
4231
|
-
turnRecordId: null,
|
|
4232
|
-
required: true
|
|
4233
|
-
};
|
|
4234
|
-
outputs.push({ kind: "upload_snapshot", ...snapshot, source });
|
|
4235
|
-
return {
|
|
4236
|
-
...state,
|
|
4237
|
-
work: { ...state.work, publication: { kind: "cleanup_snapshot", snapshot } }
|
|
4238
|
-
};
|
|
4239
|
-
}
|
|
4240
|
-
function beginFatalSnapshot(state, fatal, source, afterSnapshot, outputs) {
|
|
4241
|
-
requireNoPublication(state);
|
|
4242
|
-
const snapshot = {
|
|
4243
|
-
point: "before_worker_failed",
|
|
4244
|
-
turnRecordId: null,
|
|
4245
|
-
required: false
|
|
4246
|
-
};
|
|
4247
|
-
outputs.push({ kind: "upload_snapshot", ...snapshot, source });
|
|
4248
|
-
return {
|
|
4249
|
-
...state,
|
|
4250
|
-
work: {
|
|
4251
|
-
...state.work,
|
|
4252
|
-
publication: { kind: "fatal_snapshot", snapshot, fatal, afterSnapshot }
|
|
4253
|
-
}
|
|
4254
|
-
};
|
|
4662
|
+
var TERMINAL_ACK_RETRY_MS = 5e3;
|
|
4663
|
+
function publishTerminalAndAwaitAcknowledgement(state, terminal, outputs) {
|
|
4664
|
+
outputs.push(terminal.fact);
|
|
4665
|
+
if (terminal.park) outputs.push(protocol("worker.lifecycle_parked", terminal.park));
|
|
4666
|
+
return armTimer(
|
|
4667
|
+
{
|
|
4668
|
+
...state,
|
|
4669
|
+
work: {
|
|
4670
|
+
...state.work,
|
|
4671
|
+
publication: { kind: "terminal_pending_ack", terminal }
|
|
4672
|
+
}
|
|
4673
|
+
},
|
|
4674
|
+
outputs,
|
|
4675
|
+
"terminal_ack",
|
|
4676
|
+
TERMINAL_ACK_RETRY_MS,
|
|
4677
|
+
terminal.correlation.turnRecordId
|
|
4678
|
+
);
|
|
4255
4679
|
}
|
|
4256
4680
|
function finishFatal(state, fatal) {
|
|
4257
4681
|
const outputs = [
|
|
@@ -4294,7 +4718,17 @@ function failureOutputs(state, failure2) {
|
|
|
4294
4718
|
};
|
|
4295
4719
|
if (disposition.snapshot && !hasActivePublication(state)) {
|
|
4296
4720
|
const afterSnapshot = state.phase.kind === "cleaning" && state.phase.stage === "publication" ? "cleanup" : "exit";
|
|
4297
|
-
next =
|
|
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
|
+
);
|
|
4298
4732
|
break;
|
|
4299
4733
|
}
|
|
4300
4734
|
const finished = finishFatal(next, fatal);
|
|
@@ -4397,11 +4831,15 @@ function advance(state, outputs) {
|
|
|
4397
4831
|
next.session.piAvailable
|
|
4398
4832
|
) : { upload: false };
|
|
4399
4833
|
if (cleanupSnapshot.upload && next.session) {
|
|
4400
|
-
next =
|
|
4834
|
+
next = beginSnapshot(
|
|
4401
4835
|
{
|
|
4402
4836
|
...next,
|
|
4403
4837
|
phase: { kind: "cleaning", reason, exitAfterCleanup, stage: "publication" }
|
|
4404
4838
|
},
|
|
4839
|
+
{
|
|
4840
|
+
kind: "cleanup_snapshot",
|
|
4841
|
+
snapshot: { point: "before_cleanup_completed", turnRecordId: null, required: true }
|
|
4842
|
+
},
|
|
4405
4843
|
sessionSnapshotSource(next.session),
|
|
4406
4844
|
outputs
|
|
4407
4845
|
);
|
|
@@ -4490,9 +4928,11 @@ function reduceWorkerRuntime(state, event) {
|
|
|
4490
4928
|
if (state.phase.kind !== "init") break;
|
|
4491
4929
|
next = { ...state, phase: { kind: "waiting_for_start" } };
|
|
4492
4930
|
outputs.push(HELLO);
|
|
4931
|
+
outputs.push(protocol("worker.bootstrap_progress", { phase: "worker_connected" }));
|
|
4493
4932
|
break;
|
|
4494
4933
|
case "transport_connected":
|
|
4495
4934
|
outputs.push(HELLO);
|
|
4935
|
+
outputs.push(protocol("worker.bootstrap_progress", { phase: "worker_connected" }));
|
|
4496
4936
|
if (state.session) {
|
|
4497
4937
|
outputs.push(
|
|
4498
4938
|
protocol("worker.heartbeat", {
|
|
@@ -4502,6 +4942,13 @@ function reduceWorkerRuntime(state, event) {
|
|
|
4502
4942
|
})
|
|
4503
4943
|
);
|
|
4504
4944
|
}
|
|
4945
|
+
if (state.work.publication.kind === "terminal_pending_ack") {
|
|
4946
|
+
next = publishTerminalAndAwaitAcknowledgement(
|
|
4947
|
+
state,
|
|
4948
|
+
state.work.publication.terminal,
|
|
4949
|
+
outputs
|
|
4950
|
+
);
|
|
4951
|
+
}
|
|
4505
4952
|
break;
|
|
4506
4953
|
case "transport_failed": {
|
|
4507
4954
|
const failed = failureOutputs(state, { kind: "transport", error: event.error });
|
|
@@ -4535,7 +4982,12 @@ function reduceWorkerRuntime(state, event) {
|
|
|
4535
4982
|
outputs.push({ kind: "cancel_timer", name });
|
|
4536
4983
|
next = {
|
|
4537
4984
|
...next,
|
|
4538
|
-
timers: {
|
|
4985
|
+
timers: {
|
|
4986
|
+
heartbeat: null,
|
|
4987
|
+
acceptance_retry: null,
|
|
4988
|
+
credential_poll: null,
|
|
4989
|
+
terminal_ack: null
|
|
4990
|
+
},
|
|
4539
4991
|
credential: null
|
|
4540
4992
|
};
|
|
4541
4993
|
break;
|
|
@@ -4579,6 +5031,7 @@ function reduceWorkerRuntime(state, event) {
|
|
|
4579
5031
|
},
|
|
4580
5032
|
sessionTainted: false
|
|
4581
5033
|
};
|
|
5034
|
+
outputs.push(protocol("worker.bootstrap_progress", { phase: "preparing_workspace" }));
|
|
4582
5035
|
outputs.push({ kind: "bootstrap", startRecordId, payload: message.payload });
|
|
4583
5036
|
break;
|
|
4584
5037
|
}
|
|
@@ -4603,6 +5056,18 @@ function reduceWorkerRuntime(state, event) {
|
|
|
4603
5056
|
);
|
|
4604
5057
|
break;
|
|
4605
5058
|
}
|
|
5059
|
+
if (message.type === "worker.turn_terminal_recorded") {
|
|
5060
|
+
const publication = state.work.publication;
|
|
5061
|
+
if (publication.kind !== "terminal_pending_ack" || publication.terminal.correlation.turnRecordId !== message.payload.turnRecordId)
|
|
5062
|
+
break;
|
|
5063
|
+
outputs.push({ kind: "cancel_timer", name: "terminal_ack" });
|
|
5064
|
+
next = {
|
|
5065
|
+
...state,
|
|
5066
|
+
work: { ...state.work, publication: { kind: "none" } },
|
|
5067
|
+
timers: { ...state.timers, terminal_ack: null }
|
|
5068
|
+
};
|
|
5069
|
+
break;
|
|
5070
|
+
}
|
|
4606
5071
|
if (message.type === "worker.credential_update_accepted") {
|
|
4607
5072
|
const credential = state.credential;
|
|
4608
5073
|
if (!credential?.enabled || !credential.updatePending || message.payload.providerId !== credential.descriptor.providerId)
|
|
@@ -4681,6 +5146,8 @@ function reduceWorkerRuntime(state, event) {
|
|
|
4681
5146
|
kind: "diagnostic",
|
|
4682
5147
|
payload: { level: "warn", code: "bootstrap.diagnostic", message }
|
|
4683
5148
|
});
|
|
5149
|
+
outputs.push(protocol("worker.bootstrap_progress", { phase: "loading_resources" }));
|
|
5150
|
+
outputs.push(protocol("worker.bootstrap_progress", { phase: "preparing_turn" }));
|
|
4684
5151
|
outputs.push(protocol("worker.ready", completion.readyPayload));
|
|
4685
5152
|
if (wasDraining) break;
|
|
4686
5153
|
const readySnapshot = resolveWorkerSnapshotPolicy(
|
|
@@ -4689,7 +5156,15 @@ function reduceWorkerRuntime(state, event) {
|
|
|
4689
5156
|
completion.session.piAvailable
|
|
4690
5157
|
);
|
|
4691
5158
|
if (readySnapshot.upload)
|
|
4692
|
-
next =
|
|
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
|
+
);
|
|
4693
5168
|
next = armTimer(
|
|
4694
5169
|
next,
|
|
4695
5170
|
outputs,
|
|
@@ -4753,7 +5228,9 @@ function reduceWorkerRuntime(state, event) {
|
|
|
4753
5228
|
});
|
|
4754
5229
|
break;
|
|
4755
5230
|
case "activation_failed":
|
|
4756
|
-
|
|
5231
|
+
case "turn_defect":
|
|
5232
|
+
if (event.kind === "activation_failed" ? !matchesActivation(state, event.startRecordId, event.turnRecordId) : !matchesTurn(state, event.turnRecordId))
|
|
5233
|
+
break;
|
|
4757
5234
|
if (state.phase.kind === "draining") {
|
|
4758
5235
|
next = finishDrainingOperation(state);
|
|
4759
5236
|
} else {
|
|
@@ -4831,6 +5308,7 @@ function reduceWorkerRuntime(state, event) {
|
|
|
4831
5308
|
forkPiEntryId: event.result.meta.forkPiEntryId ?? null,
|
|
4832
5309
|
resultPiEntryId: event.result.meta.resultPiEntryId ?? null,
|
|
4833
5310
|
turnResultMarkdown: event.result.meta.turnResultMarkdown ?? null,
|
|
5311
|
+
resultSummary: event.result.meta.resultSummary,
|
|
4834
5312
|
rootEntryId: event.result.meta.rootEntryId ?? null
|
|
4835
5313
|
}),
|
|
4836
5314
|
park: null,
|
|
@@ -4863,8 +5341,7 @@ function reduceWorkerRuntime(state, event) {
|
|
|
4863
5341
|
phase: state.phase.kind === "active" ? { ...state.phase, turnStatus: "completed" } : next.phase
|
|
4864
5342
|
};
|
|
4865
5343
|
if (state.session?.kind === "automatic") {
|
|
4866
|
-
|
|
4867
|
-
if (pending.park) outputs.push(protocol("worker.lifecycle_parked", pending.park));
|
|
5344
|
+
next = publishTerminalAndAwaitAcknowledgement(next, pending, outputs);
|
|
4868
5345
|
} else if (state.session) {
|
|
4869
5346
|
const point = event.result.kind === "outcome" ? "before_turn_outcome" : "before_turn_failed";
|
|
4870
5347
|
const snapshotPolicy = resolveWorkerSnapshotPolicy(
|
|
@@ -4874,98 +5351,33 @@ function reduceWorkerRuntime(state, event) {
|
|
|
4874
5351
|
);
|
|
4875
5352
|
if (!snapshotPolicy.upload)
|
|
4876
5353
|
throw new Error("LLM terminal snapshot policy unexpectedly skipped upload");
|
|
4877
|
-
next =
|
|
5354
|
+
next = beginSnapshot(
|
|
4878
5355
|
next,
|
|
4879
|
-
|
|
4880
|
-
|
|
4881
|
-
|
|
5356
|
+
{
|
|
5357
|
+
kind: "terminal_snapshot",
|
|
5358
|
+
snapshot: { point, turnRecordId: event.turnRecordId, required: true },
|
|
5359
|
+
terminal: pending
|
|
5360
|
+
},
|
|
4882
5361
|
sessionSnapshotSource(state.session),
|
|
4883
5362
|
outputs
|
|
4884
5363
|
);
|
|
4885
5364
|
}
|
|
4886
5365
|
break;
|
|
4887
5366
|
}
|
|
4888
|
-
case "
|
|
4889
|
-
if (!matchesTurn(state, event.turnRecordId)) break;
|
|
4890
|
-
if (state.phase.kind === "draining") {
|
|
4891
|
-
next = finishDrainingOperation(state);
|
|
4892
|
-
} else {
|
|
4893
|
-
const failed = failureOutputs(next, {
|
|
4894
|
-
kind: "dispatch",
|
|
4895
|
-
error: event.error,
|
|
4896
|
-
state: "busy",
|
|
4897
|
-
session: failureContext(state)
|
|
4898
|
-
});
|
|
4899
|
-
next = failed.state;
|
|
4900
|
-
outputs.push(...failed.outputs);
|
|
4901
|
-
}
|
|
4902
|
-
break;
|
|
4903
|
-
case "snapshot_succeeded": {
|
|
4904
|
-
const publication = state.work.publication;
|
|
4905
|
-
switch (publication.kind) {
|
|
4906
|
-
case "none":
|
|
4907
|
-
case "fatal_pending_cleanup":
|
|
4908
|
-
break;
|
|
4909
|
-
case "ready_snapshot":
|
|
4910
|
-
if (!snapshotMatches(publication.snapshot, event)) break;
|
|
4911
|
-
next = { ...state, work: { ...state.work, publication: { kind: "none" } } };
|
|
4912
|
-
break;
|
|
4913
|
-
case "terminal_snapshot":
|
|
4914
|
-
if (!snapshotMatches(publication.snapshot, event)) break;
|
|
4915
|
-
outputs.push(publication.terminal.fact);
|
|
4916
|
-
if (publication.terminal.park)
|
|
4917
|
-
outputs.push(protocol("worker.lifecycle_parked", publication.terminal.park));
|
|
4918
|
-
next = { ...state, work: { ...state.work, publication: { kind: "none" } } };
|
|
4919
|
-
break;
|
|
4920
|
-
case "cleanup_snapshot":
|
|
4921
|
-
if (!snapshotMatches(publication.snapshot, event)) break;
|
|
4922
|
-
if (state.phase.kind !== "cleaning" || state.phase.stage !== "publication")
|
|
4923
|
-
throw new Error("Cleanup snapshot completed outside cleanup publication");
|
|
4924
|
-
outputs.push({ kind: "cleanup" });
|
|
4925
|
-
next = {
|
|
4926
|
-
...state,
|
|
4927
|
-
phase: { ...state.phase, stage: "resources" },
|
|
4928
|
-
work: { ...state.work, publication: { kind: "none" } }
|
|
4929
|
-
};
|
|
4930
|
-
break;
|
|
4931
|
-
case "fatal_snapshot":
|
|
4932
|
-
if (!snapshotMatches(publication.snapshot, event)) break;
|
|
4933
|
-
if (publication.afterSnapshot === "exit") {
|
|
4934
|
-
const finished = finishFatal(state, publication.fatal);
|
|
4935
|
-
next = finished.state;
|
|
4936
|
-
outputs.push(...finished.outputs);
|
|
4937
|
-
} else {
|
|
4938
|
-
if (state.phase.kind !== "cleaning" || state.phase.stage !== "publication")
|
|
4939
|
-
throw new Error("Fatal snapshot completed outside cleanup publication");
|
|
4940
|
-
outputs.push({ kind: "cleanup" });
|
|
4941
|
-
next = {
|
|
4942
|
-
...state,
|
|
4943
|
-
phase: { ...state.phase, stage: "resources" },
|
|
4944
|
-
work: {
|
|
4945
|
-
...state.work,
|
|
4946
|
-
publication: {
|
|
4947
|
-
kind: "fatal_pending_cleanup",
|
|
4948
|
-
fatal: publication.fatal
|
|
4949
|
-
}
|
|
4950
|
-
}
|
|
4951
|
-
};
|
|
4952
|
-
}
|
|
4953
|
-
break;
|
|
4954
|
-
}
|
|
4955
|
-
break;
|
|
4956
|
-
}
|
|
5367
|
+
case "snapshot_succeeded":
|
|
4957
5368
|
case "snapshot_failed": {
|
|
4958
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";
|
|
4959
5372
|
switch (publication.kind) {
|
|
4960
|
-
case "none":
|
|
4961
|
-
case "fatal_pending_cleanup":
|
|
4962
|
-
break;
|
|
4963
5373
|
case "ready_snapshot":
|
|
4964
|
-
if (!snapshotMatches(publication.snapshot, event)) break;
|
|
4965
5374
|
next = { ...state, work: { ...state.work, publication: { kind: "none" } } };
|
|
4966
5375
|
break;
|
|
4967
5376
|
case "terminal_snapshot": {
|
|
4968
|
-
if (
|
|
5377
|
+
if (event.kind === "snapshot_succeeded") {
|
|
5378
|
+
next = publishTerminalAndAwaitAcknowledgement(state, publication.terminal, outputs);
|
|
5379
|
+
break;
|
|
5380
|
+
}
|
|
4969
5381
|
const cleared = {
|
|
4970
5382
|
...state,
|
|
4971
5383
|
work: { ...state.work, publication: { kind: "none" } }
|
|
@@ -4982,41 +5394,41 @@ function reduceWorkerRuntime(state, event) {
|
|
|
4982
5394
|
break;
|
|
4983
5395
|
}
|
|
4984
5396
|
case "cleanup_snapshot": {
|
|
4985
|
-
if (!snapshotMatches(publication.snapshot, event)) break;
|
|
4986
5397
|
if (state.phase.kind !== "cleaning" || state.phase.stage !== "publication")
|
|
4987
|
-
throw new Error(
|
|
5398
|
+
throw new Error(`Cleanup snapshot ${completion} outside cleanup publication`);
|
|
4988
5399
|
const cleared = {
|
|
4989
5400
|
...state,
|
|
4990
5401
|
work: { ...state.work, publication: { kind: "none" } }
|
|
4991
5402
|
};
|
|
4992
|
-
|
|
4993
|
-
kind: "cleanup"
|
|
4994
|
-
|
|
4995
|
-
|
|
4996
|
-
|
|
4997
|
-
|
|
4998
|
-
|
|
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
|
+
}
|
|
4999
5415
|
break;
|
|
5000
5416
|
}
|
|
5001
5417
|
case "fatal_snapshot":
|
|
5002
|
-
if (!snapshotMatches(publication.snapshot, event)) break;
|
|
5003
5418
|
if (publication.afterSnapshot === "exit") {
|
|
5004
5419
|
const finished = finishFatal(state, publication.fatal);
|
|
5005
5420
|
next = finished.state;
|
|
5006
5421
|
outputs.push(...finished.outputs);
|
|
5007
5422
|
} else {
|
|
5008
5423
|
if (state.phase.kind !== "cleaning" || state.phase.stage !== "publication")
|
|
5009
|
-
throw new Error(
|
|
5424
|
+
throw new Error(`Fatal snapshot ${completion} outside cleanup publication`);
|
|
5010
5425
|
outputs.push({ kind: "cleanup" });
|
|
5011
5426
|
next = {
|
|
5012
5427
|
...state,
|
|
5013
5428
|
phase: { ...state.phase, stage: "resources" },
|
|
5014
5429
|
work: {
|
|
5015
5430
|
...state.work,
|
|
5016
|
-
publication: {
|
|
5017
|
-
kind: "fatal_pending_cleanup",
|
|
5018
|
-
fatal: publication.fatal
|
|
5019
|
-
}
|
|
5431
|
+
publication: { kind: "fatal_pending_cleanup", fatal: publication.fatal }
|
|
5020
5432
|
}
|
|
5021
5433
|
};
|
|
5022
5434
|
}
|
|
@@ -5050,6 +5462,12 @@ function reduceWorkerRuntime(state, event) {
|
|
|
5050
5462
|
})
|
|
5051
5463
|
);
|
|
5052
5464
|
next = armTimer(next, outputs, "acceptance_retry", 1e3, event.correlation);
|
|
5465
|
+
} else if (event.name === "terminal_ack" && state.work.publication.kind === "terminal_pending_ack" && state.work.publication.terminal.correlation.turnRecordId === event.correlation) {
|
|
5466
|
+
next = publishTerminalAndAwaitAcknowledgement(
|
|
5467
|
+
next,
|
|
5468
|
+
state.work.publication.terminal,
|
|
5469
|
+
outputs
|
|
5470
|
+
);
|
|
5053
5471
|
} else if (event.name === "credential_poll" && state.credential?.enabled && !state.credential.sampling && !state.credential.updatePending) {
|
|
5054
5472
|
outputs.push({
|
|
5055
5473
|
kind: "sample_credentials",
|
|
@@ -5256,6 +5674,7 @@ function createAutomaticTurnExecutor(input) {
|
|
|
5256
5674
|
forkPiEntryId: null,
|
|
5257
5675
|
resultPiEntryId: null,
|
|
5258
5676
|
turnResultMarkdown: completeInput.markdown ?? null,
|
|
5677
|
+
resultSummary: completeInput.resultSummary,
|
|
5259
5678
|
rootEntryId: input.piHandle ? resolveRootEntryIdFromHandle(input.piHandle) : readProcessSemanticEntryRefs(input.state)?.rootEntry?.entryId ?? null
|
|
5260
5679
|
}
|
|
5261
5680
|
};
|
|
@@ -5349,8 +5768,7 @@ async function promptWithGuards(deps, input) {
|
|
|
5349
5768
|
let maxDurationTimer = null;
|
|
5350
5769
|
let inactivityTimer = null;
|
|
5351
5770
|
let rejectTimeout = null;
|
|
5352
|
-
let
|
|
5353
|
-
let aborted = false;
|
|
5771
|
+
let abortReason = null;
|
|
5354
5772
|
let sawCompaction = false;
|
|
5355
5773
|
let removeOperatorAbortListener = null;
|
|
5356
5774
|
let removeSuspensionListener = null;
|
|
@@ -5367,11 +5785,43 @@ async function promptWithGuards(deps, input) {
|
|
|
5367
5785
|
inactivityTimer = null;
|
|
5368
5786
|
}
|
|
5369
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
|
+
};
|
|
5370
5820
|
const requestAbortForTimeout = (timeoutKind, timeoutMs) => {
|
|
5371
|
-
if (
|
|
5821
|
+
if (abortReason !== null) {
|
|
5372
5822
|
return;
|
|
5373
5823
|
}
|
|
5374
|
-
|
|
5824
|
+
abortReason = timeoutKind;
|
|
5375
5825
|
clearTimers();
|
|
5376
5826
|
const error = new PromptTimeoutError(input.turnId, timeoutKind, timeoutMs);
|
|
5377
5827
|
reportError({
|
|
@@ -5393,44 +5843,13 @@ async function promptWithGuards(deps, input) {
|
|
|
5393
5843
|
details: { turnAbortGracePeriodMs, timeoutMs, timeoutKind }
|
|
5394
5844
|
});
|
|
5395
5845
|
rejectTimeout?.(error);
|
|
5396
|
-
void (
|
|
5397
|
-
let abortCompleted = false;
|
|
5398
|
-
try {
|
|
5399
|
-
await Promise.race([
|
|
5400
|
-
input.piHandle.abortTurn().then(() => {
|
|
5401
|
-
abortCompleted = true;
|
|
5402
|
-
}),
|
|
5403
|
-
deps.scheduler.sleep(turnAbortGracePeriodMs)
|
|
5404
|
-
]);
|
|
5405
|
-
if (!abortCompleted) {
|
|
5406
|
-
reportError({
|
|
5407
|
-
level: "error",
|
|
5408
|
-
code: "guard.abort_grace_elapsed",
|
|
5409
|
-
message: `Timed out turn '${input.turnId}' did not abort within ${turnAbortGracePeriodMs}ms`,
|
|
5410
|
-
turnRecordId: input.turnRecordId,
|
|
5411
|
-
turnId: input.turnId,
|
|
5412
|
-
errorClass: "infrastructure",
|
|
5413
|
-
details: { turnAbortGracePeriodMs, timeoutKind }
|
|
5414
|
-
});
|
|
5415
|
-
}
|
|
5416
|
-
} catch (error2) {
|
|
5417
|
-
reportError({
|
|
5418
|
-
level: "error",
|
|
5419
|
-
code: "guard.abort_failed",
|
|
5420
|
-
message: `Failed to abort timed out turn '${input.turnId}': ${toErrorMessage(error2)}`,
|
|
5421
|
-
turnRecordId: input.turnRecordId,
|
|
5422
|
-
turnId: input.turnId,
|
|
5423
|
-
errorClass: "infrastructure",
|
|
5424
|
-
details: { timeoutKind }
|
|
5425
|
-
});
|
|
5426
|
-
}
|
|
5427
|
-
})();
|
|
5846
|
+
void abortWithinGracePeriod(timeoutKind);
|
|
5428
5847
|
};
|
|
5429
5848
|
const requestOperatorAbort = () => {
|
|
5430
|
-
if (
|
|
5849
|
+
if (abortReason !== null) {
|
|
5431
5850
|
return;
|
|
5432
5851
|
}
|
|
5433
|
-
|
|
5852
|
+
abortReason = "operator_abort";
|
|
5434
5853
|
clearTimers();
|
|
5435
5854
|
const error = new OperatorAbortError(input.turnId);
|
|
5436
5855
|
reportError({
|
|
@@ -5451,40 +5870,10 @@ async function promptWithGuards(deps, input) {
|
|
|
5451
5870
|
details: { turnAbortGracePeriodMs }
|
|
5452
5871
|
});
|
|
5453
5872
|
rejectTimeout?.(error);
|
|
5454
|
-
void (
|
|
5455
|
-
let abortCompleted = false;
|
|
5456
|
-
try {
|
|
5457
|
-
await Promise.race([
|
|
5458
|
-
input.piHandle.abortTurn().then(() => {
|
|
5459
|
-
abortCompleted = true;
|
|
5460
|
-
}),
|
|
5461
|
-
deps.scheduler.sleep(turnAbortGracePeriodMs)
|
|
5462
|
-
]);
|
|
5463
|
-
if (!abortCompleted) {
|
|
5464
|
-
reportError({
|
|
5465
|
-
level: "error",
|
|
5466
|
-
code: "guard.abort_grace_elapsed",
|
|
5467
|
-
message: `Operator-stopped turn '${input.turnId}' did not abort within ${turnAbortGracePeriodMs}ms`,
|
|
5468
|
-
turnRecordId: input.turnRecordId,
|
|
5469
|
-
turnId: input.turnId,
|
|
5470
|
-
errorClass: "infrastructure",
|
|
5471
|
-
details: { turnAbortGracePeriodMs }
|
|
5472
|
-
});
|
|
5473
|
-
}
|
|
5474
|
-
} catch (error2) {
|
|
5475
|
-
reportError({
|
|
5476
|
-
level: "error",
|
|
5477
|
-
code: "guard.abort_failed",
|
|
5478
|
-
message: `Failed to abort operator-stopped turn '${input.turnId}': ${toErrorMessage(error2)}`,
|
|
5479
|
-
turnRecordId: input.turnRecordId,
|
|
5480
|
-
turnId: input.turnId,
|
|
5481
|
-
errorClass: "infrastructure"
|
|
5482
|
-
});
|
|
5483
|
-
}
|
|
5484
|
-
})();
|
|
5873
|
+
void abortWithinGracePeriod();
|
|
5485
5874
|
};
|
|
5486
5875
|
const armMaxDurationTimer = () => {
|
|
5487
|
-
if (!turnMaxDurationMs || turnMaxDurationMs <= 0 || maxDurationRemainingMs <= 0 || guardsPaused ||
|
|
5876
|
+
if (!turnMaxDurationMs || turnMaxDurationMs <= 0 || maxDurationRemainingMs <= 0 || guardsPaused || abortReason !== null)
|
|
5488
5877
|
return;
|
|
5489
5878
|
maxDurationArmedAt = deps.scheduler.now().getTime();
|
|
5490
5879
|
maxDurationTimer = deps.scheduler.setTimeout(() => {
|
|
@@ -5492,7 +5881,7 @@ async function promptWithGuards(deps, input) {
|
|
|
5492
5881
|
}, maxDurationRemainingMs);
|
|
5493
5882
|
};
|
|
5494
5883
|
const resetInactivityTimer = () => {
|
|
5495
|
-
if (!turnInactivityTimeoutMs || turnInactivityTimeoutMs <= 0 || guardsPaused ||
|
|
5884
|
+
if (!turnInactivityTimeoutMs || turnInactivityTimeoutMs <= 0 || guardsPaused || abortReason !== null) {
|
|
5496
5885
|
return;
|
|
5497
5886
|
}
|
|
5498
5887
|
if (inactivityTimer !== null) {
|
|
@@ -5517,7 +5906,7 @@ async function promptWithGuards(deps, input) {
|
|
|
5517
5906
|
resetInactivityTimer();
|
|
5518
5907
|
});
|
|
5519
5908
|
removeSuspensionListener = deps.guardSuspension?.subscribe((paused) => {
|
|
5520
|
-
if (guardsPaused === paused ||
|
|
5909
|
+
if (guardsPaused === paused || abortReason !== null) return;
|
|
5521
5910
|
guardsPaused = paused;
|
|
5522
5911
|
if (paused) {
|
|
5523
5912
|
if (maxDurationTimer !== null) {
|
|
@@ -5550,7 +5939,7 @@ async function promptWithGuards(deps, input) {
|
|
|
5550
5939
|
}
|
|
5551
5940
|
const hasGuards = turnMaxDurationMs !== void 0 && turnMaxDurationMs > 0 || turnInactivityTimeoutMs !== void 0 && turnInactivityTimeoutMs > 0 || operatorAbortSignal !== void 0;
|
|
5552
5941
|
try {
|
|
5553
|
-
if (
|
|
5942
|
+
if (abortReason === "operator_abort") {
|
|
5554
5943
|
await guardPromise;
|
|
5555
5944
|
}
|
|
5556
5945
|
const result = !hasGuards ? await input.runPrompt() : await Promise.race([input.runPrompt(), guardPromise]);
|
|
@@ -5575,7 +5964,11 @@ async function promptWithGuards(deps, input) {
|
|
|
5575
5964
|
}
|
|
5576
5965
|
|
|
5577
5966
|
// src/turn-continuation.ts
|
|
5578
|
-
import {
|
|
5967
|
+
import {
|
|
5968
|
+
DEFAULT_CONTINUE_PROMPT,
|
|
5969
|
+
normalizeContinuePrompt,
|
|
5970
|
+
readNonBlankString as readNonBlankString2
|
|
5971
|
+
} from "@leitwerk-dev/domain";
|
|
5579
5972
|
function readCurrentLeafMessage(piHandle) {
|
|
5580
5973
|
const leafId = piHandle.getLeafId();
|
|
5581
5974
|
if (!leafId) {
|
|
@@ -5629,21 +6022,13 @@ async function prepareContinuationUserPrompt(input) {
|
|
|
5629
6022
|
}
|
|
5630
6023
|
return normalizedPrompt;
|
|
5631
6024
|
}
|
|
5632
|
-
function readNonEmptyMetadataString(metadata, key) {
|
|
5633
|
-
const value = metadata?.[key];
|
|
5634
|
-
return typeof value === "string" && value.trim() !== "" ? value : null;
|
|
5635
|
-
}
|
|
5636
6025
|
function resolveTurnContinuationState(input) {
|
|
5637
6026
|
if (input.process.selectedTurnId !== input.turnId) {
|
|
5638
6027
|
return null;
|
|
5639
6028
|
}
|
|
5640
|
-
const continueFromPiEntryId =
|
|
5641
|
-
|
|
5642
|
-
|
|
5643
|
-
);
|
|
5644
|
-
const continueFromTurnRecordId = readNonEmptyMetadataString(
|
|
5645
|
-
input.process.metadata,
|
|
5646
|
-
"continueFromTurnRecordId"
|
|
6029
|
+
const continueFromPiEntryId = readNonBlankString2(input.process.metadata?.continueFromPiEntryId);
|
|
6030
|
+
const continueFromTurnRecordId = readNonBlankString2(
|
|
6031
|
+
input.process.metadata?.continueFromTurnRecordId
|
|
5647
6032
|
);
|
|
5648
6033
|
if (!continueFromPiEntryId || !continueFromTurnRecordId) {
|
|
5649
6034
|
return null;
|
|
@@ -5651,7 +6036,7 @@ function resolveTurnContinuationState(input) {
|
|
|
5651
6036
|
return {
|
|
5652
6037
|
continueFromPiEntryId,
|
|
5653
6038
|
continuePrompt: normalizeContinuePrompt(input.process.metadata?.continuePrompt) ?? DEFAULT_CONTINUE_PROMPT,
|
|
5654
|
-
savedPrimaryLeafId:
|
|
6039
|
+
savedPrimaryLeafId: readNonBlankString2(input.process.metadata?.continueSavedPrimaryLeafEntryId) ?? readProcessSemanticEntryRefs(input.state)?.currentPrimaryPathLeaf?.entryId ?? null
|
|
5655
6040
|
};
|
|
5656
6041
|
}
|
|
5657
6042
|
function resolvePromptlessTurnResumeReason(input) {
|
|
@@ -5774,7 +6159,7 @@ function createTurnResultMarkdownState() {
|
|
|
5774
6159
|
publicationCount: 0
|
|
5775
6160
|
};
|
|
5776
6161
|
}
|
|
5777
|
-
function publishTurnResultMarkdownValue(state, value) {
|
|
6162
|
+
function publishTurnResultMarkdownValue(state, value, resultSummary) {
|
|
5778
6163
|
const validation = validateTurnResultMarkdownValue(value);
|
|
5779
6164
|
if (!validation.ok) {
|
|
5780
6165
|
return {
|
|
@@ -5789,6 +6174,7 @@ function publishTurnResultMarkdownValue(state, value) {
|
|
|
5789
6174
|
}
|
|
5790
6175
|
const nextState = {
|
|
5791
6176
|
markdown: validation.markdown,
|
|
6177
|
+
...typeof resultSummary === "string" && resultSummary.trim() ? { resultSummary: resultSummary.trim() } : {},
|
|
5792
6178
|
publicationCount: state.publicationCount + 1
|
|
5793
6179
|
};
|
|
5794
6180
|
return {
|
|
@@ -5809,13 +6195,21 @@ function createMarkdownResultTool(stateRef) {
|
|
|
5809
6195
|
name: MARKDOWN_RESULT_TOOL_NAME,
|
|
5810
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.",
|
|
5811
6197
|
parameters: {
|
|
6198
|
+
resultSummary: {
|
|
6199
|
+
type: "string",
|
|
6200
|
+
description: "Concise summary of this attempt\u2019s result, based on completed work."
|
|
6201
|
+
},
|
|
5812
6202
|
markdown: {
|
|
5813
6203
|
type: "string",
|
|
5814
6204
|
description: "Raw markdown content to render for this turn. Do not wrap the entire markdown in triple backticks."
|
|
5815
6205
|
}
|
|
5816
6206
|
},
|
|
5817
6207
|
execute: async (args) => {
|
|
5818
|
-
const published = publishTurnResultMarkdownValue(
|
|
6208
|
+
const published = publishTurnResultMarkdownValue(
|
|
6209
|
+
stateRef.current,
|
|
6210
|
+
args.markdown,
|
|
6211
|
+
args.resultSummary
|
|
6212
|
+
);
|
|
5819
6213
|
stateRef.current = published.state;
|
|
5820
6214
|
return published.response;
|
|
5821
6215
|
}
|
|
@@ -5964,35 +6358,14 @@ function finalizeTurnResultMarkdown(input) {
|
|
|
5964
6358
|
if (!input.behavior || input.behavior.mode === "none") {
|
|
5965
6359
|
return { markdown: input.state.markdown ?? null, errorMessage: null };
|
|
5966
6360
|
}
|
|
5967
|
-
|
|
5968
|
-
|
|
5969
|
-
|
|
5970
|
-
return { markdown, errorMessage: null };
|
|
5971
|
-
}
|
|
5972
|
-
return input.behavior.required ? {
|
|
5973
|
-
markdown: null,
|
|
5974
|
-
errorMessage: "Turn requires non-empty assistant output to publish turn result markdown"
|
|
5975
|
-
} : { markdown: null, errorMessage: null };
|
|
5976
|
-
}
|
|
5977
|
-
if (input.behavior.mode === "outcome_tool_argument") {
|
|
5978
|
-
if (input.state.markdown) {
|
|
5979
|
-
return { markdown: input.state.markdown, errorMessage: null };
|
|
5980
|
-
}
|
|
5981
|
-
return input.behavior.required ? {
|
|
5982
|
-
markdown: null,
|
|
5983
|
-
errorMessage: `Turn requires a successful outcome tool call with a non-empty '${input.behavior.parameterName}' markdown argument`
|
|
5984
|
-
} : { markdown: null, errorMessage: null };
|
|
5985
|
-
}
|
|
5986
|
-
if (input.state.markdown) {
|
|
5987
|
-
return { markdown: input.state.markdown, errorMessage: null };
|
|
5988
|
-
}
|
|
5989
|
-
if (input.behavior.required) {
|
|
5990
|
-
return {
|
|
5991
|
-
markdown: null,
|
|
5992
|
-
errorMessage: `Turn requires a successful '${input.behavior.toolName}' tool call to publish turn result markdown`
|
|
5993
|
-
};
|
|
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 };
|
|
5994
6364
|
}
|
|
5995
|
-
return {
|
|
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
|
+
};
|
|
5996
6369
|
}
|
|
5997
6370
|
|
|
5998
6371
|
// src/turn-outcome-tool-session.ts
|
|
@@ -6003,15 +6376,10 @@ function cloneSelectedOutcome(value) {
|
|
|
6003
6376
|
function cloneTurnResultMarkdownState(state) {
|
|
6004
6377
|
return {
|
|
6005
6378
|
markdown: state.markdown,
|
|
6379
|
+
...state.resultSummary ? { resultSummary: state.resultSummary } : {},
|
|
6006
6380
|
publicationCount: state.publicationCount
|
|
6007
6381
|
};
|
|
6008
6382
|
}
|
|
6009
|
-
function snapshotToolCompletionState(value) {
|
|
6010
|
-
return {
|
|
6011
|
-
selectedOutcome: cloneSelectedOutcome(value.selectedOutcome),
|
|
6012
|
-
markdownState: cloneTurnResultMarkdownState(value.markdownState)
|
|
6013
|
-
};
|
|
6014
|
-
}
|
|
6015
6383
|
function createTurnOutcomeToolSession(input) {
|
|
6016
6384
|
let selectedOutcome = null;
|
|
6017
6385
|
let terminalAcknowledgement = { kind: "open" };
|
|
@@ -6031,7 +6399,13 @@ function createTurnOutcomeToolSession(input) {
|
|
|
6031
6399
|
name: outcome,
|
|
6032
6400
|
description: spec.description,
|
|
6033
6401
|
parameters: {
|
|
6034
|
-
...Object.fromEntries(Object.entries(spec.parameters)
|
|
6402
|
+
...Object.fromEntries(Object.entries(spec.parameters)),
|
|
6403
|
+
...injectsGlobalMarkdownParameter ? {
|
|
6404
|
+
resultSummary: {
|
|
6405
|
+
type: "string",
|
|
6406
|
+
description: "Concise result summary for this attempt."
|
|
6407
|
+
}
|
|
6408
|
+
} : {},
|
|
6035
6409
|
...injectsGlobalMarkdownParameter && outcomeToolMarkdownParameterName ? {
|
|
6036
6410
|
[outcomeToolMarkdownParameterName]: {
|
|
6037
6411
|
type: "string",
|
|
@@ -6047,10 +6421,15 @@ function createTurnOutcomeToolSession(input) {
|
|
|
6047
6421
|
const acceptsOutcome = selectedOutcome === null;
|
|
6048
6422
|
if (acceptsOutcome) {
|
|
6049
6423
|
let outcomeParams = args;
|
|
6424
|
+
if (spec.resultSummaryParameter && typeof args[spec.resultSummaryParameter] === "string")
|
|
6425
|
+
turnResultMarkdownStateRef.current.resultSummary = String(
|
|
6426
|
+
args[spec.resultSummaryParameter]
|
|
6427
|
+
).trim();
|
|
6050
6428
|
if (markdownParameterName) {
|
|
6051
6429
|
const published = publishTurnResultMarkdownValue(
|
|
6052
6430
|
turnResultMarkdownStateRef.current,
|
|
6053
|
-
args[markdownParameterName]
|
|
6431
|
+
args[markdownParameterName],
|
|
6432
|
+
spec.resultSummaryParameter ? args[spec.resultSummaryParameter] : injectsGlobalMarkdownParameter ? args.resultSummary : void 0
|
|
6054
6433
|
);
|
|
6055
6434
|
if (!published.response.ok) {
|
|
6056
6435
|
return published.response;
|
|
@@ -6059,6 +6438,7 @@ function createTurnOutcomeToolSession(input) {
|
|
|
6059
6438
|
if (injectsGlobalMarkdownParameter) {
|
|
6060
6439
|
outcomeParams = { ...args };
|
|
6061
6440
|
delete outcomeParams[markdownParameterName];
|
|
6441
|
+
delete outcomeParams.resultSummary;
|
|
6062
6442
|
}
|
|
6063
6443
|
}
|
|
6064
6444
|
selectedOutcome = { outcome, params: outcomeParams };
|
|
@@ -6107,9 +6487,7 @@ function createTurnOutcomeToolSession(input) {
|
|
|
6107
6487
|
failureReason: () => terminalAcknowledgement.kind === "acknowledgement_failed_ignored" ? terminalAcknowledgement.reason : null
|
|
6108
6488
|
};
|
|
6109
6489
|
return {
|
|
6110
|
-
outcomeToolNames,
|
|
6111
6490
|
usesOutcomeTools,
|
|
6112
|
-
requiresMarkdownResultToolCall,
|
|
6113
6491
|
tools,
|
|
6114
6492
|
activeTools,
|
|
6115
6493
|
terminalAcknowledgement: terminalAcknowledgementControl,
|
|
@@ -6135,10 +6513,10 @@ function createTurnOutcomeToolSession(input) {
|
|
|
6135
6513
|
);
|
|
6136
6514
|
},
|
|
6137
6515
|
getCompletionState() {
|
|
6138
|
-
return
|
|
6139
|
-
selectedOutcome,
|
|
6140
|
-
markdownState: turnResultMarkdownStateRef.current
|
|
6141
|
-
}
|
|
6516
|
+
return {
|
|
6517
|
+
selectedOutcome: cloneSelectedOutcome(selectedOutcome),
|
|
6518
|
+
markdownState: cloneTurnResultMarkdownState(turnResultMarkdownStateRef.current)
|
|
6519
|
+
};
|
|
6142
6520
|
},
|
|
6143
6521
|
shouldBlockToolCall(toolName) {
|
|
6144
6522
|
if (selectedOutcome === null) {
|
|
@@ -6174,9 +6552,7 @@ function createTurnOutcomeToolSession(input) {
|
|
|
6174
6552
|
...recovery.missingToolNames.length > 0 ? { missingToolNames: recovery.missingToolNames } : {}
|
|
6175
6553
|
};
|
|
6176
6554
|
},
|
|
6177
|
-
describeRecovery
|
|
6178
|
-
return describeMissingTurnToolCallRecovery(recovery);
|
|
6179
|
-
},
|
|
6555
|
+
describeRecovery: describeMissingTurnToolCallRecovery,
|
|
6180
6556
|
finalizeMarkdown(completionState, assistantMarkdown) {
|
|
6181
6557
|
return finalizeTurnResultMarkdown({
|
|
6182
6558
|
behavior: input.turnDef.turnResultMarkdown,
|
|
@@ -6190,13 +6566,7 @@ function createTurnOutcomeToolSession(input) {
|
|
|
6190
6566
|
// src/logical-prompt-runner.ts
|
|
6191
6567
|
var MAX_COMPACTION_CONTINUE_ATTEMPTS = 3;
|
|
6192
6568
|
function shouldAutoContinueAfterPromptReturn(input) {
|
|
6193
|
-
|
|
6194
|
-
return false;
|
|
6195
|
-
}
|
|
6196
|
-
if (!input.sawCompaction) {
|
|
6197
|
-
return false;
|
|
6198
|
-
}
|
|
6199
|
-
return input.compactionContinueAttempts < MAX_COMPACTION_CONTINUE_ATTEMPTS;
|
|
6569
|
+
return !input.resolvedOutcome && input.sawCompaction && input.compactionContinueAttempts < MAX_COMPACTION_CONTINUE_ATTEMPTS;
|
|
6200
6570
|
}
|
|
6201
6571
|
function isContextWindowError(error) {
|
|
6202
6572
|
const message = error instanceof Error ? error.message : String(error);
|
|
@@ -6260,9 +6630,7 @@ async function executeLogicalPromptPlan(input) {
|
|
|
6260
6630
|
);
|
|
6261
6631
|
};
|
|
6262
6632
|
for (; ; ) {
|
|
6263
|
-
const
|
|
6264
|
-
const promptPlan = currentPlan.kind === "prompt" ? currentPlan : null;
|
|
6265
|
-
const usingContinueThisAttempt = continuePlan !== null;
|
|
6633
|
+
const plan = currentPlan;
|
|
6266
6634
|
const guardSuspension = new PromptGuardSuspension();
|
|
6267
6635
|
const promptOptions = input.toolSession.tools.length > 0 ? {
|
|
6268
6636
|
tools: input.toolSession.tools,
|
|
@@ -6275,13 +6643,13 @@ async function executeLogicalPromptPlan(input) {
|
|
|
6275
6643
|
isOperatorAbortRequested: () => input.operatorAbortSignal?.aborted === true
|
|
6276
6644
|
}
|
|
6277
6645
|
} : { activeTools: input.toolSession.activeTools };
|
|
6278
|
-
let
|
|
6279
|
-
if (
|
|
6646
|
+
let runPrompt = () => plan.kind === "continue" ? input.piHandle.continueTurn(promptOptions) : input.piHandle.prompt(plan.promptText ?? "", promptOptions);
|
|
6647
|
+
if (plan.kind === "continue") {
|
|
6280
6648
|
try {
|
|
6281
|
-
await
|
|
6282
|
-
if (
|
|
6283
|
-
const content =
|
|
6284
|
-
const identity =
|
|
6649
|
+
await plan.prepareForContinuation?.();
|
|
6650
|
+
if (plan.continueUserPrompt !== null) {
|
|
6651
|
+
const content = plan.continueUserPrompt;
|
|
6652
|
+
const identity = plan.identifiedPrompt;
|
|
6285
6653
|
if (identity) {
|
|
6286
6654
|
const expectedParentId = input.piHandle.getLeafId();
|
|
6287
6655
|
if (findIdentifiedPrompt(input.piHandle, identity)) {
|
|
@@ -6292,7 +6660,7 @@ async function executeLogicalPromptPlan(input) {
|
|
|
6292
6660
|
expectedParentId
|
|
6293
6661
|
});
|
|
6294
6662
|
} else {
|
|
6295
|
-
|
|
6663
|
+
runPrompt = () => input.piHandle.promptCustom({ content, details: identity }, promptOptions);
|
|
6296
6664
|
}
|
|
6297
6665
|
} else {
|
|
6298
6666
|
const promptText = await prepareContinuationUserPrompt({
|
|
@@ -6301,7 +6669,7 @@ async function executeLogicalPromptPlan(input) {
|
|
|
6301
6669
|
promptText: content
|
|
6302
6670
|
});
|
|
6303
6671
|
if (promptText) {
|
|
6304
|
-
|
|
6672
|
+
runPrompt = () => input.piHandle.promptLiteral(promptText, promptOptions);
|
|
6305
6673
|
}
|
|
6306
6674
|
}
|
|
6307
6675
|
}
|
|
@@ -6324,13 +6692,7 @@ async function executeLogicalPromptPlan(input) {
|
|
|
6324
6692
|
piHandle: input.piHandle,
|
|
6325
6693
|
turnRecordId: input.turnRecordId,
|
|
6326
6694
|
turnId: input.turnId,
|
|
6327
|
-
runPrompt
|
|
6328
|
-
if (preparedPromptRun) return preparedPromptRun();
|
|
6329
|
-
if (continuePlan) {
|
|
6330
|
-
return input.piHandle.continueTurn(promptOptions);
|
|
6331
|
-
}
|
|
6332
|
-
return input.piHandle.prompt(promptPlan?.promptText ?? "", promptOptions);
|
|
6333
|
-
}
|
|
6695
|
+
runPrompt
|
|
6334
6696
|
}
|
|
6335
6697
|
);
|
|
6336
6698
|
if (input.toolSession.terminalAcknowledgement.state() === "outcome_accepted") {
|
|
@@ -6397,10 +6759,10 @@ async function executeLogicalPromptPlan(input) {
|
|
|
6397
6759
|
continue;
|
|
6398
6760
|
}
|
|
6399
6761
|
return reportFailure(error, {
|
|
6400
|
-
code:
|
|
6762
|
+
code: plan.kind === "continue" ? "turn.continue_failed" : "turn.prompt_failed",
|
|
6401
6763
|
emitWorkerError: !(error instanceof PromptTimeoutError || error instanceof OperatorAbortError),
|
|
6402
6764
|
fallbackErrorClass: "llm_error",
|
|
6403
|
-
messagePrefix:
|
|
6765
|
+
messagePrefix: plan.kind === "continue" ? `Turn '${input.turnId}' continuation failed` : `Turn '${input.turnId}' prompt failed`
|
|
6404
6766
|
});
|
|
6405
6767
|
}
|
|
6406
6768
|
}
|
|
@@ -6415,12 +6777,7 @@ async function runMissingToolRecovery(input) {
|
|
|
6415
6777
|
input.initialAttempt.completionState
|
|
6416
6778
|
);
|
|
6417
6779
|
if (!baseMissingToolRecovery) {
|
|
6418
|
-
return {
|
|
6419
|
-
recovered: true,
|
|
6420
|
-
finalAttempt: input.initialAttempt,
|
|
6421
|
-
recoveryContext: null,
|
|
6422
|
-
baseMissingToolRecoveryDescription: null
|
|
6423
|
-
};
|
|
6780
|
+
return { finalAttempt: input.initialAttempt };
|
|
6424
6781
|
}
|
|
6425
6782
|
const recoveryContext = input.toolSession.buildRecoveryContext(baseMissingToolRecovery);
|
|
6426
6783
|
const description = input.toolSession.describeRecovery(baseMissingToolRecovery);
|
|
@@ -6458,12 +6815,7 @@ async function runMissingToolRecovery(input) {
|
|
|
6458
6815
|
{ baseState: input.initialAttempt.completionState }
|
|
6459
6816
|
);
|
|
6460
6817
|
if (!input.toolSession.resolveMissingToolRecovery(finalAttempt.completionState)) {
|
|
6461
|
-
return {
|
|
6462
|
-
recovered: true,
|
|
6463
|
-
finalAttempt,
|
|
6464
|
-
recoveryContext,
|
|
6465
|
-
baseMissingToolRecoveryDescription: description
|
|
6466
|
-
};
|
|
6818
|
+
return { finalAttempt };
|
|
6467
6819
|
}
|
|
6468
6820
|
}
|
|
6469
6821
|
reportError({
|
|
@@ -6478,10 +6830,8 @@ async function runMissingToolRecovery(input) {
|
|
|
6478
6830
|
}
|
|
6479
6831
|
});
|
|
6480
6832
|
return {
|
|
6481
|
-
recovered: false,
|
|
6482
6833
|
finalAttempt,
|
|
6483
|
-
recoveryContext,
|
|
6484
|
-
baseMissingToolRecoveryDescription: description
|
|
6834
|
+
failure: { recoveryContext, description }
|
|
6485
6835
|
};
|
|
6486
6836
|
}
|
|
6487
6837
|
|
|
@@ -6512,20 +6862,9 @@ ${guidance}`
|
|
|
6512
6862
|
);
|
|
6513
6863
|
}
|
|
6514
6864
|
var PI_SESSION_BOOTSTRAP_ENTRY_TYPES = /* @__PURE__ */ new Set(["model_change", "thinking_level_change"]);
|
|
6515
|
-
function visitPiTreeEntries(nodes, visit) {
|
|
6516
|
-
for (const node of nodes) {
|
|
6517
|
-
visit(node.entry.type);
|
|
6518
|
-
visitPiTreeEntries(node.children, visit);
|
|
6519
|
-
}
|
|
6520
|
-
}
|
|
6521
6865
|
function isPiTreeEmptyForPreparedEmptyPlan(piHandle) {
|
|
6522
|
-
|
|
6523
|
-
|
|
6524
|
-
if (!PI_SESSION_BOOTSTRAP_ENTRY_TYPES.has(entryType)) {
|
|
6525
|
-
hasNonBootstrap = true;
|
|
6526
|
-
}
|
|
6527
|
-
});
|
|
6528
|
-
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);
|
|
6529
6868
|
}
|
|
6530
6869
|
function treePlanFromPreparedStart(input) {
|
|
6531
6870
|
const { preparedStart, turnDef, piHandle } = input;
|
|
@@ -6695,7 +7034,7 @@ async function executeLlmTurn(input) {
|
|
|
6695
7034
|
reportError({
|
|
6696
7035
|
level: "error",
|
|
6697
7036
|
code: "turn.primary_leaf_restore_failed",
|
|
6698
|
-
message: `Failed to restore the primary path leaf after turn '${turnId}': ${
|
|
7037
|
+
message: `Failed to restore the primary path leaf after turn '${turnId}': ${toErrorMessage2(restoreError)}`,
|
|
6699
7038
|
turnRecordId,
|
|
6700
7039
|
turnId,
|
|
6701
7040
|
errorClass: "infrastructure"
|
|
@@ -6703,7 +7042,7 @@ async function executeLlmTurn(input) {
|
|
|
6703
7042
|
failure2 = new TurnExecutionError(
|
|
6704
7043
|
turnId,
|
|
6705
7044
|
"infrastructure",
|
|
6706
|
-
`${message}. Failed to restore the primary path leaf: ${
|
|
7045
|
+
`${message}. Failed to restore the primary path leaf: ${toErrorMessage2(restoreError)}`,
|
|
6707
7046
|
{ recoveryContext: null }
|
|
6708
7047
|
);
|
|
6709
7048
|
}
|
|
@@ -6747,12 +7086,12 @@ async function executeLlmTurn(input) {
|
|
|
6747
7086
|
let promptText = null;
|
|
6748
7087
|
if (initialPromptlessTurnResumeReason === null || initialPromptlessTurnResumeReason === "active_turn_resume") {
|
|
6749
7088
|
try {
|
|
6750
|
-
promptText = await input.turnDef.prompt(input.ctx);
|
|
7089
|
+
promptText = await input.turnDef.prompt({ ...input.ctx, prepared: input.prepared });
|
|
6751
7090
|
} catch (error) {
|
|
6752
7091
|
return failWithWorkerError(
|
|
6753
7092
|
"turn.prompt_preparation_failed",
|
|
6754
7093
|
"infrastructure",
|
|
6755
|
-
`Turn '${turnId}' prompt preparation failed: ${
|
|
7094
|
+
`Turn '${turnId}' prompt preparation failed: ${toErrorMessage2(error)}`,
|
|
6756
7095
|
null,
|
|
6757
7096
|
{ restorePrimaryLeaf: false }
|
|
6758
7097
|
);
|
|
@@ -6910,14 +7249,15 @@ async function executeLlmTurn(input) {
|
|
|
6910
7249
|
const finalCompletionState = recoveryResult.finalAttempt.completionState;
|
|
6911
7250
|
const finalPromptResult = recoveryResult.finalAttempt.promptResult;
|
|
6912
7251
|
const finalResolvedOutcome = recoveryResult.finalAttempt.resolvedOutcome;
|
|
6913
|
-
if (
|
|
7252
|
+
if (recoveryResult.failure) {
|
|
7253
|
+
const { recoveryContext, description } = recoveryResult.failure;
|
|
6914
7254
|
return reportFailedTurn(
|
|
6915
7255
|
"protocol_error",
|
|
6916
|
-
`Turn '${turnId}' completed without the required tool calls after ${MAX_MISSING_TOOL_CALL_RECOVERY_ATTEMPTS} automatic recovery attempts: ${
|
|
7256
|
+
`Turn '${turnId}' completed without the required tool calls after ${MAX_MISSING_TOOL_CALL_RECOVERY_ATTEMPTS} automatic recovery attempts: ${description}`,
|
|
6917
7257
|
finalPromptResult.resultEntryId,
|
|
6918
7258
|
{
|
|
6919
|
-
recoveryContext
|
|
6920
|
-
restorePrimaryLeaf:
|
|
7259
|
+
recoveryContext,
|
|
7260
|
+
restorePrimaryLeaf: recoveryContext.failureCode !== "missing_markdown_result"
|
|
6921
7261
|
}
|
|
6922
7262
|
);
|
|
6923
7263
|
}
|
|
@@ -6963,6 +7303,7 @@ async function executeLlmTurn(input) {
|
|
|
6963
7303
|
forkPiEntryId: treePlan.forkPiEntryId,
|
|
6964
7304
|
resultPiEntryId: finalPromptResult.resultEntryId,
|
|
6965
7305
|
turnResultMarkdown: finalizedTurnResultMarkdown.markdown,
|
|
7306
|
+
resultSummary: finalCompletionState.markdownState.resultSummary,
|
|
6966
7307
|
rootEntryId: rootEntryIdAfterTurn
|
|
6967
7308
|
}
|
|
6968
7309
|
};
|
|
@@ -6972,6 +7313,21 @@ async function executeLlmTurn(input) {
|
|
|
6972
7313
|
function failedResult(failure2, appliedTargetedInputs) {
|
|
6973
7314
|
return { kind: "failed", failure: failure2, appliedTargetedInputs };
|
|
6974
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
|
+
}
|
|
6975
7331
|
async function executeSelectedTurn(input) {
|
|
6976
7332
|
const { resolvedWorkerProcess, processSnapshot, projectSnapshots } = input.session;
|
|
6977
7333
|
const { piHandle } = input;
|
|
@@ -6986,6 +7342,23 @@ async function executeSelectedTurn(input) {
|
|
|
6986
7342
|
}
|
|
6987
7343
|
const handler = resolvedWorkerProcess.definition.turns.get(currentTurnId);
|
|
6988
7344
|
if (!handler) throw new Error(`Validated turn handler '${currentTurnId}' is unavailable`);
|
|
7345
|
+
let automaticIntegrationCallIndex = 0;
|
|
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
|
+
};
|
|
6989
7362
|
const ctx = {
|
|
6990
7363
|
process: processSnapshot,
|
|
6991
7364
|
projects: projectSnapshots,
|
|
@@ -6993,7 +7366,11 @@ async function executeSelectedTurn(input) {
|
|
|
6993
7366
|
state: resolvedWorkerProcess.state,
|
|
6994
7367
|
turnResultMarkdownBySemanticRef: input.session.turnResultMarkdownBySemanticRef,
|
|
6995
7368
|
turnResultMarkdownByProduct: input.session.turnResultMarkdownByProduct,
|
|
6996
|
-
workspaceRoot: input.session.workspaceRoot
|
|
7369
|
+
workspaceRoot: input.session.workspaceRoot,
|
|
7370
|
+
...selectedTurnType === "automatic" ? {
|
|
7371
|
+
reportProgress,
|
|
7372
|
+
callIntegrationTool
|
|
7373
|
+
} : {}
|
|
6997
7374
|
};
|
|
6998
7375
|
let terminal = null;
|
|
6999
7376
|
const appliedTargetedInputs = [];
|
|
@@ -7024,9 +7401,36 @@ async function executeSelectedTurn(input) {
|
|
|
7024
7401
|
`Turn '${currentTurnId}' requires a Pi handle`
|
|
7025
7402
|
);
|
|
7026
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
|
+
}
|
|
7027
7430
|
const completed = await executeLlmTurn({
|
|
7028
7431
|
resolvedWorkerProcess,
|
|
7029
7432
|
ctx,
|
|
7433
|
+
...turnDef.prepare ? { prepared } : {},
|
|
7030
7434
|
piHandle,
|
|
7031
7435
|
turnDef,
|
|
7032
7436
|
turnId: currentTurnId,
|
|
@@ -7091,6 +7495,20 @@ async function executeSelectedTurn(input) {
|
|
|
7091
7495
|
}
|
|
7092
7496
|
return terminal;
|
|
7093
7497
|
} catch (error) {
|
|
7498
|
+
const failedProgressReport = latestProgressReport;
|
|
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;
|
|
7506
|
+
input.emit({
|
|
7507
|
+
kind: "progress",
|
|
7508
|
+
turnRecordId: input.turnRecordId,
|
|
7509
|
+
report
|
|
7510
|
+
});
|
|
7511
|
+
}
|
|
7094
7512
|
if (error instanceof TurnExecutionFailure) return failedResult(error, appliedTargetedInputs);
|
|
7095
7513
|
if (automaticExecutor)
|
|
7096
7514
|
return failedResult(automaticExecutor.failure(error), appliedTargetedInputs);
|
|
@@ -7103,29 +7521,44 @@ function createWorkerRuntime(options) {
|
|
|
7103
7521
|
const { config, adapters } = options;
|
|
7104
7522
|
const sampleCredentials = adapters.sampleCredentials ?? sampleCredentialFiles;
|
|
7105
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
|
+
`);
|
|
7106
7542
|
const queue = [];
|
|
7107
7543
|
const timers = /* @__PURE__ */ new Map();
|
|
7108
7544
|
let state = createInitialWorkerRuntimeState();
|
|
7109
7545
|
let draining = false;
|
|
7110
7546
|
let started = false;
|
|
7111
7547
|
let invariantQueued = false;
|
|
7112
|
-
|
|
7113
|
-
const closed = new Promise((resolve) => {
|
|
7114
|
-
resolveClosed = resolve;
|
|
7115
|
-
});
|
|
7548
|
+
const { promise: closed, resolve: resolveClosed } = Promise.withResolvers();
|
|
7116
7549
|
const reporter = createWorkerIpcReporter({
|
|
7117
7550
|
instanceId: config.instanceId,
|
|
7118
7551
|
workerId: config.workerId,
|
|
7119
7552
|
now: () => adapters.scheduler.now(),
|
|
7120
|
-
send: (message) => ipc.send(message),
|
|
7121
|
-
emitExtensionEvent
|
|
7553
|
+
send: (message) => ipc.send(redactValue(message)),
|
|
7554
|
+
emitExtensionEvent
|
|
7122
7555
|
});
|
|
7123
7556
|
const questionBridge = new WorkerQuestionBridge(reporter);
|
|
7124
7557
|
const integrationToolBridge = new WorkerIntegrationToolBridge(reporter);
|
|
7125
7558
|
let dispatch;
|
|
7126
7559
|
const piEvents = createPiEventReporter({
|
|
7127
7560
|
reporter,
|
|
7128
|
-
emitExtensionEvent
|
|
7561
|
+
emitExtensionEvent,
|
|
7129
7562
|
getCurrentSelectedTurnId: () => state.session?.selectedTurnId ?? null,
|
|
7130
7563
|
getSessionTainted: () => state.sessionTainted,
|
|
7131
7564
|
onLifecycleObservation(kind) {
|
|
@@ -7136,11 +7569,15 @@ function createWorkerRuntime(options) {
|
|
|
7136
7569
|
instanceId: config.instanceId,
|
|
7137
7570
|
piFactory: adapters.piFactory,
|
|
7138
7571
|
gitOps: adapters.gitOps,
|
|
7572
|
+
developmentTools: adapters.developmentTools ?? new MiseDevelopmentToolEnvironment(),
|
|
7139
7573
|
scheduler: adapters.scheduler,
|
|
7140
7574
|
sessionSnapshots: adapters.sessionSnapshots,
|
|
7141
7575
|
resolveWorkerProcess: adapters.resolveWorkerProcess,
|
|
7142
7576
|
progress(payload) {
|
|
7143
7577
|
reporter.workerTrace(payload, state.session?.selectedTurnId ?? null);
|
|
7578
|
+
},
|
|
7579
|
+
diagnosticTrace(text) {
|
|
7580
|
+
reporter.project({ kind: "protocol", type: "worker.diagnostic_trace", payload: { text } });
|
|
7144
7581
|
}
|
|
7145
7582
|
});
|
|
7146
7583
|
const invariant = (error) => {
|
|
@@ -7259,6 +7696,18 @@ function createWorkerRuntime(options) {
|
|
|
7259
7696
|
complete({ kind: "session_tainted", reason: emission.reason });
|
|
7260
7697
|
} else if (emission.kind === "trace") {
|
|
7261
7698
|
reporter.workerTrace(emission.payload, command.session.selectedTurnId);
|
|
7699
|
+
} else if (emission.kind === "progress") {
|
|
7700
|
+
reporter.workerEvent(
|
|
7701
|
+
"turn.progress",
|
|
7702
|
+
{ turnRecordId: emission.turnRecordId, report: emission.report },
|
|
7703
|
+
command.session.selectedTurnId
|
|
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
|
+
);
|
|
7262
7711
|
} else reporter.workerError(emission.payload, command.session.selectedTurnId);
|
|
7263
7712
|
}
|
|
7264
7713
|
})
|
|
@@ -7317,21 +7766,16 @@ function createWorkerRuntime(options) {
|
|
|
7317
7766
|
workerId: config.workerId,
|
|
7318
7767
|
...output.payload
|
|
7319
7768
|
} : output.payload;
|
|
7320
|
-
|
|
7769
|
+
emitExtensionEvent(output.event, payload);
|
|
7321
7770
|
return;
|
|
7322
7771
|
}
|
|
7323
7772
|
if (output.kind === "diagnostic") {
|
|
7324
7773
|
reporter.workerTrace(output.payload, state.session?.selectedTurnId ?? null);
|
|
7325
|
-
if (output.stderr)
|
|
7326
|
-
`);
|
|
7327
|
-
return;
|
|
7328
|
-
}
|
|
7329
|
-
if (output.kind === "stderr") {
|
|
7330
|
-
adapters.stderr?.write(`${output.message}
|
|
7331
|
-
`);
|
|
7774
|
+
if (output.stderr) writeStderr(output.stderr);
|
|
7332
7775
|
return;
|
|
7333
7776
|
}
|
|
7334
|
-
|
|
7777
|
+
if (output.kind === "stderr") writeStderr(output.message);
|
|
7778
|
+
else launch(output);
|
|
7335
7779
|
};
|
|
7336
7780
|
function drain() {
|
|
7337
7781
|
if (draining) return;
|
|
@@ -7368,6 +7812,9 @@ function createWorkerRuntime(options) {
|
|
|
7368
7812
|
drain();
|
|
7369
7813
|
};
|
|
7370
7814
|
const receive = (message) => {
|
|
7815
|
+
if (message.type === "worker.start")
|
|
7816
|
+
for (const secret of extractDockerRegistrySecretValues(message.payload))
|
|
7817
|
+
deliveredSecrets.add(secret);
|
|
7371
7818
|
if (message.type === "worker.integration_tool_result") {
|
|
7372
7819
|
integrationToolBridge.handle(message);
|
|
7373
7820
|
return;
|
|
@@ -7381,6 +7828,7 @@ function createWorkerRuntime(options) {
|
|
|
7381
7828
|
dispatch({ kind: "operator_abort_observed" });
|
|
7382
7829
|
return;
|
|
7383
7830
|
}
|
|
7831
|
+
if (message.type === "worker.stop") resources.abortToolPreparation();
|
|
7384
7832
|
dispatch({ kind: "server_message", message });
|
|
7385
7833
|
};
|
|
7386
7834
|
return {
|
|
@@ -7408,8 +7856,9 @@ function createWorkerRuntime(options) {
|
|
|
7408
7856
|
}
|
|
7409
7857
|
|
|
7410
7858
|
// src/entry-runtime.ts
|
|
7411
|
-
import { existsSync as
|
|
7412
|
-
import
|
|
7859
|
+
import { existsSync as existsSync5, readFileSync as readFileSync3 } from "fs";
|
|
7860
|
+
import path13 from "path";
|
|
7861
|
+
import { isUnknownRecord as isRecord } from "@leitwerk-dev/domain";
|
|
7413
7862
|
import {
|
|
7414
7863
|
buildExtensionCatalog,
|
|
7415
7864
|
createCatalogWorkerDefinitionResolver,
|
|
@@ -7435,10 +7884,10 @@ import {
|
|
|
7435
7884
|
|
|
7436
7885
|
// src/extension-entry-roots.ts
|
|
7437
7886
|
import { existsSync as existsSync2, realpathSync } from "fs";
|
|
7438
|
-
import
|
|
7887
|
+
import path10 from "path";
|
|
7439
7888
|
function isWithinDirectory(parentDir, candidatePath) {
|
|
7440
|
-
const relative =
|
|
7441
|
-
return relative === "" || !relative.startsWith("..") && !
|
|
7889
|
+
const relative = path10.relative(parentDir, candidatePath);
|
|
7890
|
+
return relative === "" || !relative.startsWith("..") && !path10.isAbsolute(relative);
|
|
7442
7891
|
}
|
|
7443
7892
|
function parseExtensionAllowedRoots(value) {
|
|
7444
7893
|
if (!value) return [];
|
|
@@ -7450,7 +7899,7 @@ function parseExtensionAllowedRoots(value) {
|
|
|
7450
7899
|
}
|
|
7451
7900
|
if (!Array.isArray(parsed) || parsed.some((entry) => typeof entry !== "string")) return [];
|
|
7452
7901
|
return parsed.flatMap((entry) => {
|
|
7453
|
-
if (!
|
|
7902
|
+
if (!path10.isAbsolute(entry) || !existsSync2(entry)) return [];
|
|
7454
7903
|
return [realpathSync(entry)];
|
|
7455
7904
|
});
|
|
7456
7905
|
}
|
|
@@ -7477,6 +7926,32 @@ import {
|
|
|
7477
7926
|
WORKER_IPC_RECONNECT_ENV,
|
|
7478
7927
|
WORKER_IPC_SERVER_URL_ENV
|
|
7479
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
|
|
7480
7955
|
function toError(error) {
|
|
7481
7956
|
return error instanceof Error ? error : new Error(String(error));
|
|
7482
7957
|
}
|
|
@@ -7502,6 +7977,27 @@ function webSocketDataToText(data) {
|
|
|
7502
7977
|
}
|
|
7503
7978
|
return data.toString("utf8");
|
|
7504
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
|
+
}
|
|
7505
8001
|
function createWebSocketWorkerIpc(input) {
|
|
7506
8002
|
let messageHandler;
|
|
7507
8003
|
let errorHandler;
|
|
@@ -7515,6 +8011,7 @@ function createWebSocketWorkerIpc(input) {
|
|
|
7515
8011
|
const outbound = [];
|
|
7516
8012
|
const reconnectEnabled = input.reconnect === true;
|
|
7517
8013
|
const emitError = (error) => errorHandler?.(toError(error));
|
|
8014
|
+
const diagnostic = (detail) => `Worker connection ${openedOnce ? "reconnecting" : "initial_connect"}: attempt=${reconnectAttempt + 1}; ${detail}`;
|
|
7518
8015
|
const clearReconnectTimer = () => {
|
|
7519
8016
|
if (reconnectTimer) {
|
|
7520
8017
|
clearTimeout(reconnectTimer);
|
|
@@ -7573,7 +8070,6 @@ function createWebSocketWorkerIpc(input) {
|
|
|
7573
8070
|
reconnectTimer = null;
|
|
7574
8071
|
connect();
|
|
7575
8072
|
}, delayMs);
|
|
7576
|
-
reconnectTimer.unref?.();
|
|
7577
8073
|
};
|
|
7578
8074
|
return {
|
|
7579
8075
|
send(message) {
|
|
@@ -7611,12 +8107,15 @@ function createWebSocketWorkerIpc(input) {
|
|
|
7611
8107
|
}
|
|
7612
8108
|
socket = new WebSocketImpl(toWebSocketUrl(input));
|
|
7613
8109
|
socket.addEventListener("open", () => {
|
|
8110
|
+
input.onDiagnostic?.("");
|
|
7614
8111
|
reconnectAttempt = 0;
|
|
7615
8112
|
flushOutbound();
|
|
7616
8113
|
});
|
|
7617
8114
|
socket.addEventListener("message", (event) => deliverText(webSocketDataToText(event.data)));
|
|
7618
8115
|
socket.addEventListener("error", (event) => {
|
|
7619
|
-
if (
|
|
8116
|
+
if (stopping) return;
|
|
8117
|
+
input.onDiagnostic?.(diagnostic(`error=${connectionErrorCode(event)}`));
|
|
8118
|
+
if (!reconnectEnabled) {
|
|
7620
8119
|
emitError(event instanceof Error ? event : new Error("Worker WebSocket error"));
|
|
7621
8120
|
}
|
|
7622
8121
|
});
|
|
@@ -7624,6 +8123,9 @@ function createWebSocketWorkerIpc(input) {
|
|
|
7624
8123
|
if (stopping) {
|
|
7625
8124
|
return;
|
|
7626
8125
|
}
|
|
8126
|
+
input.onDiagnostic?.(
|
|
8127
|
+
diagnostic(`close=${Number.isInteger(event?.code) ? event?.code : "unknown"}`)
|
|
8128
|
+
);
|
|
7627
8129
|
socket = null;
|
|
7628
8130
|
if (reconnectEnabled && event?.code !== 1008) {
|
|
7629
8131
|
scheduleReconnect(connect);
|
|
@@ -7663,14 +8165,16 @@ function createWorkerIpcFromEnvironment(input) {
|
|
|
7663
8165
|
instanceId: input.instanceId,
|
|
7664
8166
|
workerId: input.workerId,
|
|
7665
8167
|
token,
|
|
7666
|
-
reconnect: env[WORKER_IPC_RECONNECT_ENV] === "1"
|
|
8168
|
+
reconnect: env[WORKER_IPC_RECONNECT_ENV] === "1",
|
|
8169
|
+
onDiagnostic: createConnectionDiagnosticRecorder()
|
|
7667
8170
|
});
|
|
7668
8171
|
}
|
|
7669
8172
|
|
|
7670
8173
|
// src/result-image-upload.ts
|
|
7671
8174
|
import { constants } from "fs";
|
|
7672
|
-
import { open, realpath, stat } from "fs/promises";
|
|
7673
|
-
import
|
|
8175
|
+
import { open as open2, realpath, stat } from "fs/promises";
|
|
8176
|
+
import path11 from "path";
|
|
8177
|
+
import { setTimeout as sleep } from "timers/promises";
|
|
7674
8178
|
import {
|
|
7675
8179
|
buildWorkerResultImageUploadPath,
|
|
7676
8180
|
parseWorkerResultImageUploadResponse,
|
|
@@ -7693,19 +8197,12 @@ function failure(entry, code, message) {
|
|
|
7693
8197
|
return { ...entry, status: "failed", code, message };
|
|
7694
8198
|
}
|
|
7695
8199
|
function isWithinRoot(rootReal, fileReal) {
|
|
7696
|
-
const relative =
|
|
7697
|
-
return relative !== ".." && !relative.startsWith(`..${
|
|
7698
|
-
}
|
|
7699
|
-
function isRetryableResponse(response) {
|
|
7700
|
-
return response.status >= 500;
|
|
7701
|
-
}
|
|
7702
|
-
async function sleep(ms) {
|
|
7703
|
-
if (ms <= 0) return;
|
|
7704
|
-
await new Promise((resolve) => setTimeout(resolve, ms));
|
|
8200
|
+
const relative = path11.relative(rootReal, fileReal);
|
|
8201
|
+
return relative !== ".." && !relative.startsWith(`..${path11.sep}`) && !path11.isAbsolute(relative);
|
|
7705
8202
|
}
|
|
7706
8203
|
async function readBoundedWorkspaceFile(entry, workspaceRoot, maxSizeBytes) {
|
|
7707
8204
|
const rootReal = await realpath(workspaceRoot);
|
|
7708
|
-
const candidatePath =
|
|
8205
|
+
const candidatePath = path11.resolve(workspaceRoot, entry.path);
|
|
7709
8206
|
const fileReal = await realpath(candidatePath);
|
|
7710
8207
|
if (!isWithinRoot(rootReal, fileReal)) {
|
|
7711
8208
|
return failure(
|
|
@@ -7714,7 +8211,7 @@ async function readBoundedWorkspaceFile(entry, workspaceRoot, maxSizeBytes) {
|
|
|
7714
8211
|
"Image path resolves outside the process workspace"
|
|
7715
8212
|
);
|
|
7716
8213
|
}
|
|
7717
|
-
const handle = await
|
|
8214
|
+
const handle = await open2(fileReal, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
7718
8215
|
try {
|
|
7719
8216
|
const before = await handle.stat();
|
|
7720
8217
|
if (!before.isFile()) return failure(entry, "not_a_file", "Image path is not a regular file");
|
|
@@ -7822,32 +8319,28 @@ function createUploadResultImagesTool(input) {
|
|
|
7822
8319
|
if (response.ok) {
|
|
7823
8320
|
try {
|
|
7824
8321
|
const body = parseWorkerResultImageUploadResponse(await response.json());
|
|
7825
|
-
if (
|
|
7826
|
-
return
|
|
7827
|
-
entry,
|
|
7828
|
-
"
|
|
7829
|
-
|
|
7830
|
-
|
|
7831
|
-
|
|
7832
|
-
|
|
7833
|
-
status: "uploaded",
|
|
7834
|
-
...body,
|
|
7835
|
-
markdown: `![${entry.alt.replace(/[\\\]]/g, "\\$&")}](${body.url})`
|
|
7836
|
-
};
|
|
8322
|
+
if (body) {
|
|
8323
|
+
return {
|
|
8324
|
+
...entry,
|
|
8325
|
+
status: "uploaded",
|
|
8326
|
+
...body,
|
|
8327
|
+
markdown: `![${entry.alt.replace(/[\\\]]/g, "\\$&")}](${body.url})`
|
|
8328
|
+
};
|
|
8329
|
+
}
|
|
7837
8330
|
} catch {
|
|
7838
|
-
return failure(
|
|
7839
|
-
entry,
|
|
7840
|
-
"upload_invalid_response",
|
|
7841
|
-
"Image upload response was invalid"
|
|
7842
|
-
);
|
|
7843
8331
|
}
|
|
8332
|
+
return failure(
|
|
8333
|
+
entry,
|
|
8334
|
+
"upload_invalid_response",
|
|
8335
|
+
"Image upload response was invalid"
|
|
8336
|
+
);
|
|
7844
8337
|
}
|
|
7845
8338
|
finalFailure = failure(
|
|
7846
8339
|
entry,
|
|
7847
8340
|
`upload_http_${response.status}`,
|
|
7848
8341
|
`Image upload was rejected with HTTP ${response.status}`
|
|
7849
8342
|
);
|
|
7850
|
-
if (
|
|
8343
|
+
if (response.status < 500) return finalFailure;
|
|
7851
8344
|
}
|
|
7852
8345
|
if (attempt + 1 < MAX_UPLOAD_ATTEMPTS) {
|
|
7853
8346
|
await (input.sleepImpl ?? sleep)(RETRY_DELAY_MS);
|
|
@@ -7872,8 +8365,8 @@ function createUploadResultImagesTool(input) {
|
|
|
7872
8365
|
}
|
|
7873
8366
|
|
|
7874
8367
|
// src/session-snapshot-exchange.ts
|
|
7875
|
-
import { readFile as
|
|
7876
|
-
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";
|
|
7877
8370
|
import {
|
|
7878
8371
|
buildWorkerSessionSnapshotPath,
|
|
7879
8372
|
WORKER_IPC_SERVER_URL_ENV as WORKER_IPC_SERVER_URL_ENV2,
|
|
@@ -7883,70 +8376,40 @@ import {
|
|
|
7883
8376
|
WORKER_SESSION_SNAPSHOT_WORKER_ID_HEADER,
|
|
7884
8377
|
WORKER_SNAPSHOT_TOKEN_ENV
|
|
7885
8378
|
} from "@leitwerk-dev/worker-protocol";
|
|
7886
|
-
function resolveWorkerSessionSnapshotUrl(input) {
|
|
7887
|
-
return resolveWorkerHttpUrl(input.serverUrl, buildWorkerSessionSnapshotPath(input.instanceId));
|
|
7888
|
-
}
|
|
7889
|
-
async function localFileSize(filePath) {
|
|
7890
|
-
try {
|
|
7891
|
-
return (await stat2(filePath)).size;
|
|
7892
|
-
} catch (error) {
|
|
7893
|
-
if (isEnoent(error)) {
|
|
7894
|
-
return null;
|
|
7895
|
-
}
|
|
7896
|
-
throw error;
|
|
7897
|
-
}
|
|
7898
|
-
}
|
|
7899
|
-
async function fetchWithTimeout(input) {
|
|
7900
|
-
const controller = new AbortController();
|
|
7901
|
-
const timeout = setTimeout(() => controller.abort(), input.timeoutMs);
|
|
7902
|
-
timeout.unref?.();
|
|
7903
|
-
try {
|
|
7904
|
-
return await input.fetchImpl(input.url, { ...input.init, signal: controller.signal });
|
|
7905
|
-
} finally {
|
|
7906
|
-
clearTimeout(timeout);
|
|
7907
|
-
}
|
|
7908
|
-
}
|
|
7909
8379
|
function createWorkerSessionSnapshotExchange(input) {
|
|
7910
8380
|
const fetchImpl = input.fetchImpl ?? globalThis.fetch;
|
|
7911
8381
|
if (!fetchImpl) {
|
|
7912
8382
|
return disabledWorkerSessionSnapshotExchange;
|
|
7913
8383
|
}
|
|
7914
8384
|
const timeoutMs = input.timeoutMs ?? 3e4;
|
|
7915
|
-
const snapshotUrl =
|
|
7916
|
-
|
|
7917
|
-
|
|
7918
|
-
|
|
8385
|
+
const snapshotUrl = resolveWorkerHttpUrl(
|
|
8386
|
+
input.serverUrl,
|
|
8387
|
+
buildWorkerSessionSnapshotPath(input.instanceId)
|
|
8388
|
+
);
|
|
7919
8389
|
const authHeaders = {
|
|
7920
8390
|
authorization: `Bearer ${input.token}`,
|
|
7921
8391
|
[WORKER_SESSION_SNAPSHOT_WORKER_ID_HEADER]: input.workerId
|
|
7922
8392
|
};
|
|
7923
8393
|
return {
|
|
7924
8394
|
async uploadSnapshot(treeFile, reason, metadata = {}) {
|
|
7925
|
-
|
|
7926
|
-
|
|
7927
|
-
|
|
7928
|
-
}
|
|
7929
|
-
|
|
7930
|
-
|
|
7931
|
-
}
|
|
7932
|
-
const content = await readFile3(treeFile, "utf8");
|
|
7933
|
-
if (content.length === 0) {
|
|
7934
|
-
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;
|
|
7935
8401
|
}
|
|
7936
|
-
|
|
7937
|
-
|
|
7938
|
-
|
|
7939
|
-
|
|
7940
|
-
|
|
7941
|
-
|
|
7942
|
-
|
|
7943
|
-
|
|
7944
|
-
|
|
7945
|
-
|
|
7946
|
-
|
|
7947
|
-
},
|
|
7948
|
-
body: content
|
|
7949
|
-
}
|
|
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)
|
|
7950
8413
|
});
|
|
7951
8414
|
if (!response.ok) {
|
|
7952
8415
|
throw new Error(`Session snapshot upload failed with HTTP ${response.status}`);
|
|
@@ -7979,64 +8442,87 @@ function createWorkerSessionSnapshotExchangeFromEnv(input) {
|
|
|
7979
8442
|
|
|
7980
8443
|
// src/workspace/node-run-root-git-ops.ts
|
|
7981
8444
|
import {
|
|
7982
|
-
chmodSync,
|
|
7983
|
-
existsSync as
|
|
7984
|
-
mkdirSync,
|
|
7985
|
-
mkdtempSync,
|
|
8445
|
+
chmodSync as chmodSync2,
|
|
8446
|
+
existsSync as existsSync4,
|
|
8447
|
+
mkdirSync as mkdirSync2,
|
|
8448
|
+
mkdtempSync as mkdtempSync2,
|
|
7986
8449
|
readFileSync as readFileSync2,
|
|
7987
|
-
rmSync,
|
|
7988
|
-
writeFileSync
|
|
8450
|
+
rmSync as rmSync2,
|
|
8451
|
+
writeFileSync as writeFileSync3
|
|
7989
8452
|
} from "fs";
|
|
7990
8453
|
import { tmpdir } from "os";
|
|
7991
|
-
import
|
|
8454
|
+
import path12 from "path";
|
|
7992
8455
|
import {
|
|
8456
|
+
clearRepositoryGitHttpsHelpers,
|
|
7993
8457
|
clearRepositoryGitSshWrappers,
|
|
7994
8458
|
repositoryGitArgs,
|
|
7995
8459
|
repositoryGitSubprocessEnv,
|
|
8460
|
+
repositoryHttpsUrl as repositoryHttpsUrl2,
|
|
8461
|
+
setRepositoryGitHttpsHelper,
|
|
7996
8462
|
setRepositoryGitSshWrapper
|
|
7997
8463
|
} from "@leitwerk-dev/process-sdk";
|
|
7998
8464
|
import { resolveGitBinary } from "@leitwerk-dev/process-sdk/git-binary";
|
|
7999
|
-
import { execa } from "execa";
|
|
8465
|
+
import { execa as execa2 } from "execa";
|
|
8000
8466
|
import fg from "fast-glob";
|
|
8001
|
-
function toAbsolute(targetPath) {
|
|
8002
|
-
return path11.resolve(targetPath);
|
|
8003
|
-
}
|
|
8004
8467
|
var NodeRunRootGitOps = class {
|
|
8005
8468
|
#credentialDir = null;
|
|
8006
8469
|
configureRepositoryCredentials(credentials) {
|
|
8007
8470
|
this.cleanupRepositoryCredentials();
|
|
8008
8471
|
if (credentials.length === 0) return;
|
|
8009
|
-
const root =
|
|
8010
|
-
|
|
8472
|
+
const root = mkdtempSync2(path12.join(tmpdir(), "leitwerk-repo-auth-"));
|
|
8473
|
+
chmodSync2(root, 448);
|
|
8011
8474
|
this.#credentialDir = root;
|
|
8012
|
-
|
|
8013
|
-
const
|
|
8014
|
-
|
|
8015
|
-
|
|
8016
|
-
|
|
8017
|
-
|
|
8018
|
-
|
|
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()}
|
|
8019
8500
|
`, { mode: 384 });
|
|
8020
|
-
|
|
8501
|
+
writeFileSync3(hosts, `${credential.knownHosts.trim()}
|
|
8021
8502
|
`, { mode: 384 });
|
|
8022
|
-
|
|
8023
|
-
|
|
8024
|
-
|
|
8503
|
+
writeFileSync3(
|
|
8504
|
+
wrapper,
|
|
8505
|
+
`#!/bin/sh
|
|
8025
8506
|
exec ssh -F /dev/null -o IdentitiesOnly=yes -o IdentityFile="${key}" -o UserKnownHostsFile="${hosts}" -o StrictHostKeyChecking=yes -o BatchMode=yes "$@"
|
|
8026
8507
|
`,
|
|
8027
|
-
|
|
8028
|
-
|
|
8029
|
-
|
|
8508
|
+
{ mode: 448 }
|
|
8509
|
+
);
|
|
8510
|
+
setRepositoryGitSshWrapper(credential.projectKey, wrapper);
|
|
8511
|
+
}
|
|
8512
|
+
} catch (error) {
|
|
8513
|
+
this.cleanupRepositoryCredentials();
|
|
8514
|
+
throw error;
|
|
8030
8515
|
}
|
|
8031
8516
|
}
|
|
8032
8517
|
cleanupRepositoryCredentials() {
|
|
8033
8518
|
clearRepositoryGitSshWrappers();
|
|
8034
|
-
|
|
8519
|
+
clearRepositoryGitHttpsHelpers();
|
|
8520
|
+
if (this.#credentialDir) rmSync2(this.#credentialDir, { recursive: true, force: true });
|
|
8035
8521
|
this.#credentialDir = null;
|
|
8036
8522
|
}
|
|
8037
8523
|
async runGit(args, cwd, projectKey) {
|
|
8038
|
-
const result = await
|
|
8039
|
-
...cwd ? { cwd:
|
|
8524
|
+
const result = await execa2(resolveGitBinary(), repositoryGitArgs(args), {
|
|
8525
|
+
...cwd ? { cwd: path12.resolve(cwd) } : {},
|
|
8040
8526
|
env: repositoryGitSubprocessEnv(projectKey ?? "", { GIT_TERMINAL_PROMPT: "0" }),
|
|
8041
8527
|
extendEnv: false,
|
|
8042
8528
|
stdin: "ignore"
|
|
@@ -8044,25 +8530,25 @@ exec ssh -F /dev/null -o IdentitiesOnly=yes -o IdentityFile="${key}" -o UserKnow
|
|
|
8044
8530
|
return result.stdout;
|
|
8045
8531
|
}
|
|
8046
8532
|
async writeFile(repoDir, filePath, content) {
|
|
8047
|
-
const absolutePath =
|
|
8048
|
-
|
|
8049
|
-
|
|
8533
|
+
const absolutePath = path12.resolve(path12.join(repoDir, filePath));
|
|
8534
|
+
mkdirSync2(path12.dirname(absolutePath), { recursive: true });
|
|
8535
|
+
writeFileSync3(absolutePath, content, "utf8");
|
|
8050
8536
|
}
|
|
8051
8537
|
async readFile(repoDir, filePath) {
|
|
8052
|
-
const absolutePath =
|
|
8053
|
-
if (!
|
|
8538
|
+
const absolutePath = path12.resolve(path12.join(repoDir, filePath));
|
|
8539
|
+
if (!existsSync4(absolutePath)) {
|
|
8054
8540
|
return null;
|
|
8055
8541
|
}
|
|
8056
8542
|
return readFileSync2(absolutePath, "utf8");
|
|
8057
8543
|
}
|
|
8058
8544
|
async clone(repoLocator, targetDir) {
|
|
8059
|
-
const absoluteTargetDir =
|
|
8060
|
-
|
|
8061
|
-
|
|
8545
|
+
const absoluteTargetDir = path12.resolve(targetDir);
|
|
8546
|
+
rmSync2(absoluteTargetDir, { recursive: true, force: true });
|
|
8547
|
+
mkdirSync2(path12.dirname(absoluteTargetDir), { recursive: true });
|
|
8062
8548
|
await this.runGit(
|
|
8063
8549
|
["clone", repoLocator, absoluteTargetDir],
|
|
8064
8550
|
void 0,
|
|
8065
|
-
|
|
8551
|
+
path12.basename(absoluteTargetDir)
|
|
8066
8552
|
);
|
|
8067
8553
|
}
|
|
8068
8554
|
async checkout(repoDir, branch) {
|
|
@@ -8086,8 +8572,8 @@ exec ssh -F /dev/null -o IdentitiesOnly=yes -o IdentityFile="${key}" -o UserKnow
|
|
|
8086
8572
|
return (await this.runGit(["rev-parse", "HEAD"], repoDir)).trim();
|
|
8087
8573
|
}
|
|
8088
8574
|
async listFiles(repoDir, pattern) {
|
|
8089
|
-
const absoluteRoot =
|
|
8090
|
-
if (!
|
|
8575
|
+
const absoluteRoot = path12.resolve(repoDir);
|
|
8576
|
+
if (!existsSync4(absoluteRoot)) {
|
|
8091
8577
|
return [];
|
|
8092
8578
|
}
|
|
8093
8579
|
return (await fg(pattern, {
|
|
@@ -8098,12 +8584,25 @@ exec ssh -F /dev/null -o IdentitiesOnly=yes -o IdentityFile="${key}" -o UserKnow
|
|
|
8098
8584
|
})).sort((a, b) => a.localeCompare(b));
|
|
8099
8585
|
}
|
|
8100
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
|
+
`;
|
|
8101
8603
|
|
|
8102
8604
|
// src/entry-runtime.ts
|
|
8103
8605
|
var runtimeCatalogPromise = null;
|
|
8104
|
-
function isRecord(value) {
|
|
8105
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
8106
|
-
}
|
|
8107
8606
|
function listWorkspacePatterns(workspaces) {
|
|
8108
8607
|
if (Array.isArray(workspaces)) {
|
|
8109
8608
|
return workspaces.filter((value) => typeof value === "string");
|
|
@@ -8114,10 +8613,10 @@ function listWorkspacePatterns(workspaces) {
|
|
|
8114
8613
|
return [];
|
|
8115
8614
|
}
|
|
8116
8615
|
function findWorkspaceRoot(startDir) {
|
|
8117
|
-
let current =
|
|
8616
|
+
let current = path13.resolve(startDir);
|
|
8118
8617
|
while (true) {
|
|
8119
|
-
const packageJsonPath =
|
|
8120
|
-
if (
|
|
8618
|
+
const packageJsonPath = path13.join(current, "package.json");
|
|
8619
|
+
if (existsSync5(packageJsonPath)) {
|
|
8121
8620
|
try {
|
|
8122
8621
|
const parsed = JSON.parse(readFileSync3(packageJsonPath, "utf8"));
|
|
8123
8622
|
if (listWorkspacePatterns(parsed.workspaces).length > 0) {
|
|
@@ -8126,7 +8625,7 @@ function findWorkspaceRoot(startDir) {
|
|
|
8126
8625
|
} catch {
|
|
8127
8626
|
}
|
|
8128
8627
|
}
|
|
8129
|
-
const parent =
|
|
8628
|
+
const parent = path13.dirname(current);
|
|
8130
8629
|
if (parent === current) {
|
|
8131
8630
|
return null;
|
|
8132
8631
|
}
|
|
@@ -8230,6 +8729,7 @@ function createWorkerEntryRuntime(overrides = {}) {
|
|
|
8230
8729
|
resultImageTools,
|
|
8231
8730
|
piFactory: overrides.piFactory ?? resolveDefaultPiFactory(),
|
|
8232
8731
|
gitOps: overrides.gitOps ?? new NodeRunRootGitOps(),
|
|
8732
|
+
developmentTools: overrides.developmentTools ?? new MiseDevelopmentToolEnvironment(runtimeEnv),
|
|
8233
8733
|
resolveWorkerProcess,
|
|
8234
8734
|
extensionEvents: workerExtensionApi.events,
|
|
8235
8735
|
stderr: overrides.stderr,
|
|
@@ -8240,6 +8740,12 @@ function createWorkerEntryRuntime(overrides = {}) {
|
|
|
8240
8740
|
}
|
|
8241
8741
|
|
|
8242
8742
|
export {
|
|
8743
|
+
PINNED_MISE_VERSION,
|
|
8744
|
+
DevelopmentToolPreparationError,
|
|
8745
|
+
validateMiseVersion,
|
|
8746
|
+
buildMiseSubprocessEnvironment,
|
|
8747
|
+
normalizeMiseEvidence,
|
|
8748
|
+
MiseDevelopmentToolEnvironment,
|
|
8243
8749
|
doesPiEventResetInactivity,
|
|
8244
8750
|
translateAgentSessionEventEnvelope,
|
|
8245
8751
|
SdkPiTreeHandle,
|
|
@@ -8255,4 +8761,4 @@ export {
|
|
|
8255
8761
|
createWorkerRuntime,
|
|
8256
8762
|
createWorkerEntryRuntime
|
|
8257
8763
|
};
|
|
8258
|
-
//# sourceMappingURL=chunk-
|
|
8764
|
+
//# sourceMappingURL=chunk-Y7S2MZD3.js.map
|