@discovery-tree/runner 0.1.17 → 0.1.18
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/README.md +24 -0
- package/dist/cli.js +3033 -308
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -89,9 +89,165 @@ Rules:
|
|
|
89
89
|
- For an \`ai\` task, rate \`complexity\` and \`impact\` (low, medium, high) with a one-line
|
|
90
90
|
\`model_reason\`; they choose the model it runs on.`;
|
|
91
91
|
|
|
92
|
+
// ../contracts/src/run-result.ts
|
|
93
|
+
var MAX_RUN_RESULTS_PER_TURN = 5;
|
|
94
|
+
var MAX_RUN_RESULT_METRICS = 20;
|
|
95
|
+
var MAX_RUN_RESULT_SUMMARY_CHARS = 2e3;
|
|
96
|
+
var MAX_RUN_RESULT_METRIC_NAME_CHARS = 120;
|
|
97
|
+
var MAX_RUN_RESULT_METRIC_VALUE_CHARS = 120;
|
|
98
|
+
var MAX_RUN_RESULT_METRIC_UNIT_CHARS = 40;
|
|
99
|
+
var MAX_RUN_RESULT_METRIC_LINE_CHARS = MAX_RUN_RESULT_METRIC_NAME_CHARS + MAX_RUN_RESULT_METRIC_VALUE_CHARS + MAX_RUN_RESULT_METRIC_UNIT_CHARS + 20;
|
|
100
|
+
var EXAMPLE_TITLE2 = "Backtest of the four entry strategies, 2024 data";
|
|
101
|
+
var RUN_RESULT_INSTRUCTION = `## Results
|
|
102
|
+
|
|
103
|
+
When this run measured or checked something (ran a backtest, a benchmark, a load test, a
|
|
104
|
+
smoke run, a query that answers the task's question), record what it found as a result, so
|
|
105
|
+
the finding is kept as data on the task and the next round can be compared with it. End your
|
|
106
|
+
response with one block per result:
|
|
107
|
+
|
|
108
|
+
<!-- DT-RESULT
|
|
109
|
+
title: ${EXAMPLE_TITLE2}
|
|
110
|
+
about: this
|
|
111
|
+
verdict: not_met
|
|
112
|
+
metric: strategies rejected = 4
|
|
113
|
+
metric: orders placed = 0 orders
|
|
114
|
+
metric: spread = 10-50 fp
|
|
115
|
+
evidence: https://example.com/reports/backtest-2024 Backtest report
|
|
116
|
+
---
|
|
117
|
+
All four strategies were rejected by the risk filter before placing an order: spreads of
|
|
118
|
+
10-50 fp left no edge at the configured size.
|
|
119
|
+
-->
|
|
120
|
+
|
|
121
|
+
Rules:
|
|
122
|
+
- Only for something this run measured or checked. Writing code, opening a pull request or
|
|
123
|
+
reading files is not a result; most runs that only build write no block.
|
|
124
|
+
- At most ${MAX_RUN_RESULTS_PER_TURN} blocks, ${MAX_RUN_RESULT_METRICS} \`metric:\` lines each.
|
|
125
|
+
- \`title\`: what was measured or checked, one line.
|
|
126
|
+
- \`about: this\` for this task; or the id of a destination this task's work leads to, when the
|
|
127
|
+
result checks that destination's outcome.
|
|
128
|
+
- \`verdict\`: \`met\` (it holds), \`not_met\` (it does not), \`inconclusive\` (checked, could
|
|
129
|
+
not tell) or \`info\` (a measurement with no pass or fail).
|
|
130
|
+
- \`metric: name = value unit\`, one per line; the value a number where there is one.
|
|
131
|
+
- \`evidence:\` an http(s) URL (a report, a dashboard, a pull request), then an optional caption.
|
|
132
|
+
- Below \`---\`, a summary of what it showed, at most ${MAX_RUN_RESULT_SUMMARY_CHARS} characters.
|
|
133
|
+
- Do not write \`-->\` inside a block: it ends the block.`;
|
|
134
|
+
var NUM = String.raw`[-+]?[\d.,]*\d[\d.,]*(?:e[-+]?\d+)?`;
|
|
135
|
+
var NUMERIC_TOKEN = new RegExp(String.raw`^[~<>≈≤≥]?${NUM}(?:\s*(?:-|–|to)\s*${NUM})?%?$`, "i");
|
|
136
|
+
|
|
137
|
+
// ../contracts/src/tree-jobs.ts
|
|
138
|
+
var TREE_JOB_OUTPUT_KEPT_MS = 7 * 24 * 60 * 60 * 1e3;
|
|
139
|
+
var TREE_JOB_CWD_MAX_LENGTH = 1024;
|
|
140
|
+
function treeJobCwdProblem(cwd) {
|
|
141
|
+
if (!cwd.trim()) return "must not be empty";
|
|
142
|
+
if (cwd.length > TREE_JOB_CWD_MAX_LENGTH) {
|
|
143
|
+
return `must be at most ${TREE_JOB_CWD_MAX_LENGTH} characters`;
|
|
144
|
+
}
|
|
145
|
+
if (/[\u0000-\u001f\u007f]/.test(cwd)) return "must not contain control characters";
|
|
146
|
+
if (!/^(\/|[A-Za-z]:[\\/]|\\\\)/.test(cwd)) return "must be an absolute path";
|
|
147
|
+
if (cwd.split(/[\\/]/).includes("..")) return 'must not contain ".."';
|
|
148
|
+
return null;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// ../contracts/src/job-request.ts
|
|
152
|
+
var MAX_JOB_REQUEST_PURPOSE_CHARS = 2e3;
|
|
153
|
+
var MAX_JOB_REQUEST_EXPECT_SECONDS = 366 * 24 * 3600;
|
|
154
|
+
var EXAMPLE_NAME = "Record Polymarket order books for 6 hours";
|
|
155
|
+
var EXAMPLE_COMMAND = "python scripts/record_books.py --hours 6 --out data/books";
|
|
156
|
+
var EXAMPLE_CHECKOUT = "/absolute/path/of/your/checkout";
|
|
157
|
+
var JOB_REQUEST_INSTRUCTION = `## Jobs
|
|
158
|
+
|
|
159
|
+
When the task needs a command that keeps running after this run ends (recording data for
|
|
160
|
+
hours, a dev server, a bot, a dashboard), do not leave it to a person and do not wait for it.
|
|
161
|
+
Set it up, run it briefly to check it starts, then ask Discovery Tree to run it as a job on
|
|
162
|
+
this computer: end your response with one block.
|
|
163
|
+
|
|
164
|
+
<!-- DT-JOB
|
|
165
|
+
name: ${EXAMPLE_NAME}
|
|
166
|
+
command: ${EXAMPLE_COMMAND}
|
|
167
|
+
checkout: ${EXAMPLE_CHECKOUT}
|
|
168
|
+
cwd: .
|
|
169
|
+
url: http://localhost:8000
|
|
170
|
+
expect: 6h
|
|
171
|
+
---
|
|
172
|
+
Records the order books the backtest reads from data/books.
|
|
173
|
+
-->
|
|
174
|
+
|
|
175
|
+
Rules:
|
|
176
|
+
- At most one block per turn, and only for a command that must outlive this run. A command
|
|
177
|
+
that finishes in minutes, run yourself.
|
|
178
|
+
- Nothing runs until the owner of this computer approves it, seeing the exact command and
|
|
179
|
+
directory. Say in your answer what you asked for; do not wait for it to start.
|
|
180
|
+
- \`name\`: what it does, one line.
|
|
181
|
+
- \`command\`: one line, exactly as you would type it in a shell here.
|
|
182
|
+
- \`checkout\`: the absolute path of your checkout, as \`git rev-parse --show-toplevel\` prints
|
|
183
|
+
it (or \`pwd\` in the folder you started in, when there is no repository).
|
|
184
|
+
- \`cwd\`: where to run it, relative to \`checkout\`: \`.\` for its root. Never absolute, never
|
|
185
|
+
\`..\`: a directory outside your checkout is refused.
|
|
186
|
+
- \`url\`: where it serves, when it does: an http://localhost address. Leave it out otherwise.
|
|
187
|
+
- \`expect\`: how long it should run (\`45m\`, \`6h\`, \`2d\`); leave it out for one that runs
|
|
188
|
+
until stopped.
|
|
189
|
+
- Below \`---\`, what it is for and where its output goes, at most
|
|
190
|
+
${MAX_JOB_REQUEST_PURPOSE_CHARS} characters.
|
|
191
|
+
- The same job asked for again while it still waits or runs is not asked for twice.
|
|
192
|
+
- What the job writes in your checkout is kept for ${TREE_JOB_OUTPUT_KEPT_MS / 864e5} days after the job ends, then removed with
|
|
193
|
+
the checkout. Say where its output goes (below \`---\`), and when it is done record where to
|
|
194
|
+
find it, for example in a DT-RESULT block, so it is collected in time.
|
|
195
|
+
- Do not write \`-->\` inside a block: it ends the block.`;
|
|
196
|
+
|
|
92
197
|
// ../contracts/src/environments.ts
|
|
198
|
+
var ENV_NAME_PATTERN = /^[A-Z_][A-Z0-9_]{0,63}$/;
|
|
199
|
+
var ENV_RESERVED_NAMES = [
|
|
200
|
+
"PATH",
|
|
201
|
+
"HOME",
|
|
202
|
+
"SHELL",
|
|
203
|
+
"USER",
|
|
204
|
+
"LOGNAME",
|
|
205
|
+
"PWD",
|
|
206
|
+
"OLDPWD",
|
|
207
|
+
"TMPDIR",
|
|
208
|
+
"TERM",
|
|
209
|
+
"NODE_OPTIONS",
|
|
210
|
+
"NODE_PATH",
|
|
211
|
+
"NODE_EXTRA_CA_CERTS",
|
|
212
|
+
"LD_PRELOAD",
|
|
213
|
+
"LD_LIBRARY_PATH",
|
|
214
|
+
"GITHUB_TOKEN",
|
|
215
|
+
"GH_TOKEN",
|
|
216
|
+
"HTTP_PROXY",
|
|
217
|
+
"HTTPS_PROXY",
|
|
218
|
+
"NO_PROXY",
|
|
219
|
+
"ALL_PROXY",
|
|
220
|
+
"REQUESTS_CA_BUNDLE",
|
|
221
|
+
"CURL_CA_BUNDLE",
|
|
222
|
+
"PYTHONPATH",
|
|
223
|
+
"PYTHONSTARTUP",
|
|
224
|
+
"BASH_ENV",
|
|
225
|
+
"ENV",
|
|
226
|
+
"PROMPT_COMMAND"
|
|
227
|
+
];
|
|
228
|
+
var ENV_RESERVED_PREFIXES = [
|
|
229
|
+
"DYLD_",
|
|
230
|
+
"GIT_",
|
|
231
|
+
"SSL_CERT_",
|
|
232
|
+
"ANTHROPIC_",
|
|
233
|
+
"OPENAI_",
|
|
234
|
+
"CURSOR_",
|
|
235
|
+
"CLAUDE_",
|
|
236
|
+
"CODEX_",
|
|
237
|
+
"DT_RUNNER_"
|
|
238
|
+
];
|
|
239
|
+
function isReservedEnvName(name) {
|
|
240
|
+
return ENV_RESERVED_NAMES.includes(name) || ENV_RESERVED_PREFIXES.some((p) => name.startsWith(p));
|
|
241
|
+
}
|
|
242
|
+
var ENV_SECRET_VALUE_MAX_LENGTH = 8192;
|
|
243
|
+
var ENV_VARIABLE_VALUE_MAX_LENGTH = 8192;
|
|
244
|
+
var ENV_SECRETS_MAX = 50;
|
|
245
|
+
var ENV_VARIABLES_MAX = 50;
|
|
93
246
|
var ENV_SETUP_SCRIPT_MAX_LENGTH = 16 * 1024;
|
|
94
247
|
|
|
248
|
+
// ../contracts/src/tree-autonomy.ts
|
|
249
|
+
var MAX_AUTO_RETRY_DELAY_MINUTES = 24 * 60;
|
|
250
|
+
|
|
95
251
|
// ../contracts/src/shared-artifacts.ts
|
|
96
252
|
var SHARED_ARTIFACT_TEXT_MAX_BYTES = 1024 * 1024;
|
|
97
253
|
var SHARED_ARTIFACT_IMAGE_MAX_BYTES = 5 * 1024 * 1024;
|
|
@@ -108,7 +264,7 @@ var MAX_REVIEW_IMAGE_CAPTION_LENGTH = 300;
|
|
|
108
264
|
var REVIEW_AGENT_ROUND_STALE_MS = 30 * 6e4;
|
|
109
265
|
|
|
110
266
|
// ../contracts/src/agent-runner.ts
|
|
111
|
-
var RUNNER_PROTOCOL_VERSION =
|
|
267
|
+
var RUNNER_PROTOCOL_VERSION = 2;
|
|
112
268
|
var RUNNER_COMMAND_POLL_MAX_WAIT_MS = 25e3;
|
|
113
269
|
var RUNNER_EVENTS_MAX_BATCH = 200;
|
|
114
270
|
var RUNNER_EVENT_TEXT_MAX_LENGTH = 64e3;
|
|
@@ -121,6 +277,12 @@ var RUNNER_TASK_IMAGES_DIR = ".dt-task-images";
|
|
|
121
277
|
var RUNNER_REVIEW_IMAGE_MAX_BYTES = 5e6;
|
|
122
278
|
var RUNNER_DELIVERABLE_FILE = "DELIVERABLE.md";
|
|
123
279
|
var RUNNER_REFERENCE_REPOSITORY_DIR = "repository";
|
|
280
|
+
var RUNNER_DEFAULT_MAX_JOBS = 2;
|
|
281
|
+
var RUNNER_MAX_JOBS_LIMIT = 16;
|
|
282
|
+
var RUNNER_JOB_MISSING_GRACE_MS = 2 * 6e4;
|
|
283
|
+
var RUNNER_JOB_LOG_LINES_KEPT = 2e3;
|
|
284
|
+
var RUNNER_JOB_LOG_MAX_BATCH = 500;
|
|
285
|
+
var RUNNER_JOB_LOG_LINE_MAX_LENGTH = 4e3;
|
|
124
286
|
var RUNNER_COMPLETION_MAX_TEXT = 2e5;
|
|
125
287
|
|
|
126
288
|
// ../contracts/src/agent-permissions.ts
|
|
@@ -169,7 +331,7 @@ function toolGrantRepositoryKey(url) {
|
|
|
169
331
|
}
|
|
170
332
|
|
|
171
333
|
// src/version.ts
|
|
172
|
-
var RUNNER_VERSION = true ? "0.1.
|
|
334
|
+
var RUNNER_VERSION = true ? "0.1.18" : "0.0.0-dev";
|
|
173
335
|
var RUNNER_PLATFORM = `${process.platform}-${process.arch}`;
|
|
174
336
|
|
|
175
337
|
// src/api.ts
|
|
@@ -242,6 +404,10 @@ var RunnerApi = class {
|
|
|
242
404
|
postEvents(sessionId, body) {
|
|
243
405
|
return this.request("POST", `/runner/sessions/${encodeURIComponent(sessionId)}/events`, body);
|
|
244
406
|
}
|
|
407
|
+
/** A job's status and log lines (`docs/features/RUNNER_JOBS.md`). */
|
|
408
|
+
postJobEvents(jobId, body) {
|
|
409
|
+
return this.request("POST", `/runner/jobs/${encodeURIComponent(jobId)}/events`, body);
|
|
410
|
+
}
|
|
245
411
|
/** An image the agent rendered of a design proposal, attached to the session's task. */
|
|
246
412
|
postReviewImage(sessionId, body) {
|
|
247
413
|
return this.request(
|
|
@@ -433,12 +599,12 @@ var JobHelper = class {
|
|
|
433
599
|
{ stdio: ["pipe", "pipe", "ignore"], windowsHide: true }
|
|
434
600
|
);
|
|
435
601
|
let onReady = () => void 0;
|
|
436
|
-
this.ready = new Promise((
|
|
437
|
-
const timer = setTimeout(() =>
|
|
602
|
+
this.ready = new Promise((resolve4) => {
|
|
603
|
+
const timer = setTimeout(() => resolve4(false), READY_TIMEOUT_MS);
|
|
438
604
|
timer.unref();
|
|
439
605
|
onReady = (ok) => {
|
|
440
606
|
clearTimeout(timer);
|
|
441
|
-
|
|
607
|
+
resolve4(ok);
|
|
442
608
|
};
|
|
443
609
|
});
|
|
444
610
|
const lines = createInterface({ input: this.child.stdout, crlfDelay: Infinity });
|
|
@@ -452,7 +618,7 @@ var JobHelper = class {
|
|
|
452
618
|
answer(text);
|
|
453
619
|
}
|
|
454
620
|
});
|
|
455
|
-
const
|
|
621
|
+
const gone2 = () => {
|
|
456
622
|
if (this.exited) return;
|
|
457
623
|
this.exited = true;
|
|
458
624
|
onReady(false);
|
|
@@ -460,8 +626,8 @@ var JobHelper = class {
|
|
|
460
626
|
this.waiting.clear();
|
|
461
627
|
if (helper === this) helper = null;
|
|
462
628
|
};
|
|
463
|
-
this.child.on("error",
|
|
464
|
-
this.child.on("exit",
|
|
629
|
+
this.child.on("error", gone2);
|
|
630
|
+
this.child.on("exit", gone2);
|
|
465
631
|
this.child.stdin.on("error", () => void 0);
|
|
466
632
|
this.child.unref();
|
|
467
633
|
this.child.stdout.unref?.();
|
|
@@ -493,15 +659,15 @@ var JobHelper = class {
|
|
|
493
659
|
}
|
|
494
660
|
ask(request, id) {
|
|
495
661
|
if (this.exited) return Promise.resolve("err gone");
|
|
496
|
-
return new Promise((
|
|
662
|
+
return new Promise((resolve4) => {
|
|
497
663
|
const timer = setTimeout(() => {
|
|
498
664
|
this.waiting.delete(id);
|
|
499
|
-
|
|
665
|
+
resolve4("err timeout");
|
|
500
666
|
}, ANSWER_TIMEOUT_MS);
|
|
501
667
|
timer.unref();
|
|
502
668
|
this.waiting.set(id, (answer) => {
|
|
503
669
|
clearTimeout(timer);
|
|
504
|
-
|
|
670
|
+
resolve4(answer);
|
|
505
671
|
});
|
|
506
672
|
this.child.stdin.write(request + "\n");
|
|
507
673
|
});
|
|
@@ -627,7 +793,7 @@ async function reapTree(tree, graceMs = 2e3, deps = {}) {
|
|
|
627
793
|
await (deps.terminateJob ?? terminateJob)(await tree.job);
|
|
628
794
|
const rows = await (deps.listProcesses ?? listWindowsProcesses)();
|
|
629
795
|
const orphans = descendantsOf(tree, rows);
|
|
630
|
-
if (orphans.length) await (deps.kill ??
|
|
796
|
+
if (orphans.length) await (deps.kill ?? killWindowsTrees)(orphans);
|
|
631
797
|
} catch {
|
|
632
798
|
} finally {
|
|
633
799
|
if (liveTrees.get(tree.pid)?.tree.startedAt === tree.startedAt) liveTrees.delete(tree.pid);
|
|
@@ -752,7 +918,7 @@ function namesPathIn(commandLine, dir) {
|
|
|
752
918
|
}
|
|
753
919
|
function listWindowsProcesses() {
|
|
754
920
|
const script = `$ErrorActionPreference='SilentlyContinue';Get-CimInstance Win32_Process | ForEach-Object { if ($_.CreationDate) { "$($_.ProcessId) $($_.ParentProcessId) $(([DateTimeOffset]$_.CreationDate).ToUnixTimeMilliseconds()) $($_.CommandLine -replace "[\\r\\n]", " ")" } }`;
|
|
755
|
-
return new Promise((
|
|
921
|
+
return new Promise((resolve4, reject) => {
|
|
756
922
|
const ps = spawn2(
|
|
757
923
|
"powershell.exe",
|
|
758
924
|
["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script],
|
|
@@ -767,7 +933,7 @@ function listWindowsProcesses() {
|
|
|
767
933
|
});
|
|
768
934
|
ps.on("close", () => {
|
|
769
935
|
clearTimeout(timer);
|
|
770
|
-
|
|
936
|
+
resolve4(parseProcessRows(out));
|
|
771
937
|
});
|
|
772
938
|
});
|
|
773
939
|
}
|
|
@@ -786,13 +952,13 @@ function parseProcessRows(text) {
|
|
|
786
952
|
}
|
|
787
953
|
return rows;
|
|
788
954
|
}
|
|
789
|
-
async function
|
|
955
|
+
async function killWindowsTrees(pids) {
|
|
790
956
|
for (let i = 0; i < pids.length; i += 50) {
|
|
791
957
|
const args = pids.slice(i, i + 50).flatMap((p) => ["/pid", String(p)]);
|
|
792
|
-
await new Promise((
|
|
958
|
+
await new Promise((resolve4) => {
|
|
793
959
|
const tk = spawn2("taskkill", [...args, "/T", "/F"], { stdio: "ignore", windowsHide: true });
|
|
794
|
-
tk.on("error", () =>
|
|
795
|
-
tk.on("close", () =>
|
|
960
|
+
tk.on("error", () => resolve4());
|
|
961
|
+
tk.on("close", () => resolve4());
|
|
796
962
|
});
|
|
797
963
|
}
|
|
798
964
|
}
|
|
@@ -807,7 +973,7 @@ function signalGroup(pgid, signal) {
|
|
|
807
973
|
|
|
808
974
|
// src/exec.ts
|
|
809
975
|
function exec(cmd, args, opts = {}) {
|
|
810
|
-
return new Promise((
|
|
976
|
+
return new Promise((resolve4, reject) => {
|
|
811
977
|
const child = spawn3(cmd, args, {
|
|
812
978
|
cwd: opts.cwd,
|
|
813
979
|
env: opts.env ?? process.env,
|
|
@@ -842,7 +1008,7 @@ function exec(cmd, args, opts = {}) {
|
|
|
842
1008
|
child.on("close", (code) => {
|
|
843
1009
|
if (timer) clearTimeout(timer);
|
|
844
1010
|
opts.signal?.removeEventListener("abort", onAbort);
|
|
845
|
-
void reaped.then(() =>
|
|
1011
|
+
void reaped.then(() => resolve4({ code, stdout, stderr }));
|
|
846
1012
|
});
|
|
847
1013
|
child.stdin.on("error", () => void 0);
|
|
848
1014
|
child.stdin.end(opts.input ?? "");
|
|
@@ -904,7 +1070,7 @@ function redactFields(fields) {
|
|
|
904
1070
|
return out;
|
|
905
1071
|
}
|
|
906
1072
|
function scrubSecrets(text) {
|
|
907
|
-
return text.replace(/(https?:\/\/)[^/\s@]+@/gi, "$1***@").replace(/\bdtr_[A-Za-z0-9_-]+/g, "dtr_***").replace(/\b(gh[pousr]_[A-Za-z0-9]{10,})/g, "***");
|
|
1073
|
+
return text.replace(/(https?:\/\/)(?:\[secret: [A-Z0-9_]+\]|[^/\s@])+@/gi, "$1***@").replace(/\bdtr_[A-Za-z0-9_-]+/g, "dtr_***").replace(/\b(gh[pousr]_[A-Za-z0-9]{10,})/g, "***");
|
|
908
1074
|
}
|
|
909
1075
|
|
|
910
1076
|
// src/git.ts
|
|
@@ -1046,6 +1212,7 @@ async function prepareWorktree(input) {
|
|
|
1046
1212
|
const ownWorktree = join2(input.worktreesDir, input.sessionId);
|
|
1047
1213
|
let worktree = join2(input.worktreesDir, input.worktreeKey || input.sessionId);
|
|
1048
1214
|
const remove = input.removeDir ?? removeDir;
|
|
1215
|
+
const keep = input.keepWorkspace === true && worktree !== ownWorktree;
|
|
1049
1216
|
return withRepoLock(repoDir, async () => {
|
|
1050
1217
|
await ensureRepoCache(repoDir, ref, input.protocol);
|
|
1051
1218
|
const { baseRef, start: start2 } = await resolveBase(repoDir, input.baseRef);
|
|
@@ -1055,18 +1222,46 @@ async function prepareWorktree(input) {
|
|
|
1055
1222
|
let setAside;
|
|
1056
1223
|
let leftInPlace;
|
|
1057
1224
|
let dirtyKept = false;
|
|
1225
|
+
const released = [];
|
|
1226
|
+
let keptRef;
|
|
1227
|
+
let keptRefOwn = false;
|
|
1228
|
+
const revParse2 = async (dir, rev) => {
|
|
1229
|
+
const r = await exec(
|
|
1230
|
+
"git",
|
|
1231
|
+
[...dir ? ["-C", dir] : [], "rev-parse", "--verify", "--quiet", rev],
|
|
1232
|
+
{ cwd: repoDir, env: gitEnv(), timeoutMs: 6e4 }
|
|
1233
|
+
);
|
|
1234
|
+
return r.code === 0 ? r.stdout.trim() : null;
|
|
1235
|
+
};
|
|
1236
|
+
const readHead = async (dir) => {
|
|
1237
|
+
if (!await exists(join2(dir, ".git"))) return null;
|
|
1238
|
+
const r = await exec("git", ["-C", dir, "symbolic-ref", "--quiet", "HEAD"], {
|
|
1239
|
+
cwd: repoDir,
|
|
1240
|
+
env: gitEnv(),
|
|
1241
|
+
timeoutMs: 6e4
|
|
1242
|
+
});
|
|
1243
|
+
const branch = r.code === 0 ? r.stdout.trim() : r.code === 1 ? null : void 0;
|
|
1244
|
+
return { branch, at: await revParse2(dir, "HEAD") };
|
|
1245
|
+
};
|
|
1246
|
+
const release = async (dir, head) => {
|
|
1247
|
+
if (head.branch === null) return true;
|
|
1248
|
+
if (!await gitOk(repoDir, ["-C", dir, "checkout", "--quiet", "--detach"])) return false;
|
|
1249
|
+
released.push({ dir, head: head.branch ?? null, at: head.at });
|
|
1250
|
+
return true;
|
|
1251
|
+
};
|
|
1058
1252
|
const remoteWork = `refs/remotes/origin/${input.workBranch}`;
|
|
1059
|
-
|
|
1060
|
-
cwd:
|
|
1253
|
+
const reusable = async (dir) => input.continueBranch === true && await exists(dir) && await exec("git", ["rev-parse", "--abbrev-ref", "HEAD"], {
|
|
1254
|
+
cwd: dir,
|
|
1061
1255
|
env: gitEnv(),
|
|
1062
1256
|
timeoutMs: 6e4
|
|
1063
1257
|
}).then((r) => r.code === 0 && r.stdout.trim() === input.workBranch) && // Only when it already has everything pushed to the work branch since: one that fell
|
|
1064
1258
|
// behind (the run went on elsewhere) would have the agent work on stale code.
|
|
1065
1259
|
(!await gitOk(repoDir, ["rev-parse", "--verify", "--quiet", `${remoteWork}^{commit}`]) || await exec("git", ["merge-base", "--is-ancestor", remoteWork, "HEAD"], {
|
|
1066
|
-
cwd:
|
|
1260
|
+
cwd: dir,
|
|
1067
1261
|
env: gitEnv(),
|
|
1068
1262
|
timeoutMs: 6e4
|
|
1069
|
-
}).then((r) => r.code === 0))
|
|
1263
|
+
}).then((r) => r.code === 0));
|
|
1264
|
+
if (await reusable(worktree)) {
|
|
1070
1265
|
const forkPoint = await exec("git", ["merge-base", "HEAD", start2], {
|
|
1071
1266
|
cwd: worktree,
|
|
1072
1267
|
env: gitEnv(),
|
|
@@ -1110,7 +1305,8 @@ async function prepareWorktree(input) {
|
|
|
1110
1305
|
checkout = await git(repoDir, ["rev-parse", `${checkout}^{commit}`]);
|
|
1111
1306
|
}
|
|
1112
1307
|
}
|
|
1113
|
-
|
|
1308
|
+
const busy = keep || (input.inUse?.(worktree) ?? false);
|
|
1309
|
+
if (input.continueBranch && !busy && await exists(worktree)) {
|
|
1114
1310
|
const dirty = await exec("git", ["status", "--porcelain"], {
|
|
1115
1311
|
cwd: worktree,
|
|
1116
1312
|
env: gitEnv(),
|
|
@@ -1122,44 +1318,134 @@ async function prepareWorktree(input) {
|
|
|
1122
1318
|
else dirtyKept = true;
|
|
1123
1319
|
}
|
|
1124
1320
|
}
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
);
|
|
1321
|
+
const tipNow = await exec(
|
|
1322
|
+
"git",
|
|
1323
|
+
["rev-parse", "--verify", "--quiet", `refs/heads/${input.workBranch}^{commit}`],
|
|
1324
|
+
{ cwd: repoDir, env: gitEnv(), timeoutMs: 6e4 }
|
|
1325
|
+
);
|
|
1326
|
+
const old = tipNow.code === 0 ? tipNow.stdout.trim() : "";
|
|
1327
|
+
const target = await revParse2(null, `${checkout}^{commit}`);
|
|
1328
|
+
const giveBack = async () => {
|
|
1329
|
+
if (old && target) {
|
|
1330
|
+
await gitOk(repoDir, ["update-ref", `refs/heads/${input.workBranch}`, old, target]);
|
|
1136
1331
|
}
|
|
1137
|
-
|
|
1138
|
-
if (
|
|
1139
|
-
|
|
1332
|
+
for (const { dir, head, at } of released) {
|
|
1333
|
+
if (!head || !at || await revParse2(dir, "HEAD") !== at || await revParse2(null, head) !== at) {
|
|
1334
|
+
continue;
|
|
1140
1335
|
}
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1336
|
+
await gitOk(repoDir, ["-C", dir, "symbolic-ref", "HEAD", head]);
|
|
1337
|
+
}
|
|
1338
|
+
const branchAt = await revParse2(null, `refs/heads/${input.workBranch}`);
|
|
1339
|
+
if (keptRef && keptRefOwn && branchAt === old) {
|
|
1340
|
+
await gitOk(repoDir, ["update-ref", "-d", keptRef, old]);
|
|
1341
|
+
}
|
|
1342
|
+
};
|
|
1343
|
+
try {
|
|
1344
|
+
if (await exists(worktree)) {
|
|
1345
|
+
let failure = null;
|
|
1346
|
+
if (busy) dirtyKept = true;
|
|
1347
|
+
if (!dirtyKept) {
|
|
1145
1348
|
await gitOk(repoDir, ["worktree", "remove", "--force", worktree]);
|
|
1146
|
-
await remove(worktree)
|
|
1349
|
+
failure = await remove(worktree).then(
|
|
1350
|
+
() => null,
|
|
1351
|
+
(err) => {
|
|
1352
|
+
if (!isLocked(err)) throw err;
|
|
1353
|
+
return err;
|
|
1354
|
+
}
|
|
1355
|
+
);
|
|
1356
|
+
}
|
|
1357
|
+
if (dirtyKept || failure) {
|
|
1358
|
+
if (worktree === ownWorktree) {
|
|
1359
|
+
throw failure ?? new Error(`The working copy at ${worktree} could not be replaced.`);
|
|
1360
|
+
}
|
|
1361
|
+
if (input.inUse?.(ownWorktree)) {
|
|
1362
|
+
const first = keep ? `${worktree} is kept for the run's job` : busy ? `a job runs in ${worktree}` : `${worktree} could not be replaced (a program has it open)`;
|
|
1363
|
+
throw new Error(
|
|
1364
|
+
`This run cannot continue here: ${first}, and a job runs in ${ownWorktree}. Stop the job to continue.`
|
|
1365
|
+
);
|
|
1366
|
+
}
|
|
1367
|
+
leftInPlace = worktree;
|
|
1368
|
+
const head = await readHead(leftInPlace);
|
|
1369
|
+
const onWorkBranch = !keep || head !== null && (head.branch === void 0 || head.branch === `refs/heads/${input.workBranch}`);
|
|
1370
|
+
if (onWorkBranch && head && !await release(leftInPlace, head) && keep) {
|
|
1371
|
+
throw new Error(
|
|
1372
|
+
`This run cannot continue here right now: its work branch ${input.workBranch} is checked out in ${leftInPlace}, which could not let go of it (is a git command running there?). Try again.`
|
|
1373
|
+
);
|
|
1374
|
+
}
|
|
1375
|
+
worktree = ownWorktree;
|
|
1376
|
+
if (await exists(worktree)) {
|
|
1377
|
+
await gitOk(repoDir, ["worktree", "remove", "--force", worktree]);
|
|
1378
|
+
await remove(worktree);
|
|
1379
|
+
}
|
|
1380
|
+
}
|
|
1381
|
+
}
|
|
1382
|
+
await gitOk(repoDir, ["worktree", "prune"]);
|
|
1383
|
+
if (keep) {
|
|
1384
|
+
const stuck = [];
|
|
1385
|
+
const broken = [];
|
|
1386
|
+
for (const dir of await worktreesOnBranch(repoDir, input.workBranch)) {
|
|
1387
|
+
const head = await readHead(dir);
|
|
1388
|
+
if (!head) {
|
|
1389
|
+
broken.push(dir);
|
|
1390
|
+
continue;
|
|
1391
|
+
}
|
|
1392
|
+
const known = { branch: head.branch ?? `refs/heads/${input.workBranch}`, at: head.at };
|
|
1393
|
+
if (!await release(dir, known)) stuck.push(dir);
|
|
1394
|
+
}
|
|
1395
|
+
if (broken.length) {
|
|
1396
|
+
throw new Error(
|
|
1397
|
+
`This run cannot continue here: git still has its work branch ${input.workBranch} checked out in ${broken.join(", ")}, which is no longer a working copy. Remove that folder (and run \`git worktree prune\` in ${repoDir}), then try again.`
|
|
1398
|
+
);
|
|
1399
|
+
}
|
|
1400
|
+
if (stuck.length) {
|
|
1401
|
+
throw new Error(
|
|
1402
|
+
`This run cannot continue here right now: its work branch ${input.workBranch} is checked out in ${stuck.join(", ")}, which could not let go of it (is a git command running there?). Try again.`
|
|
1403
|
+
);
|
|
1404
|
+
}
|
|
1405
|
+
}
|
|
1406
|
+
if (keep && old && !await gitOk(repoDir, ["merge-base", "--is-ancestor", old, checkout])) {
|
|
1407
|
+
const ref2 = `refs/dt-runner/kept/${input.sessionId}`;
|
|
1408
|
+
const existing = await exec(
|
|
1409
|
+
"git",
|
|
1410
|
+
["for-each-ref", "--format=%(objectname) %(refname)", "refs/dt-runner/kept/"],
|
|
1411
|
+
{ cwd: repoDir, env: gitEnv(), timeoutMs: 6e4 }
|
|
1412
|
+
);
|
|
1413
|
+
const same2 = existing.stdout.split("\n").map((l) => l.trim().split(" ")).find(
|
|
1414
|
+
([sha, name]) => sha === old && (name === ref2 || !!name?.startsWith(`${ref2}-`) && /^\d+$/.test(name.slice(ref2.length + 1)))
|
|
1415
|
+
);
|
|
1416
|
+
if (same2) {
|
|
1417
|
+
keptRef = same2[1];
|
|
1418
|
+
} else {
|
|
1419
|
+
for (const candidate of [ref2, `${ref2}-${Date.now()}`]) {
|
|
1420
|
+
if (await gitOk(repoDir, ["update-ref", candidate, old, ""])) {
|
|
1421
|
+
keptRef = candidate;
|
|
1422
|
+
keptRefOwn = true;
|
|
1423
|
+
break;
|
|
1424
|
+
}
|
|
1425
|
+
}
|
|
1426
|
+
}
|
|
1427
|
+
if (!keptRef) {
|
|
1428
|
+
throw new Error(
|
|
1429
|
+
`This run cannot continue here right now: its work branch ${input.workBranch} has commits only this computer has, and they could not be kept aside. Try again.`
|
|
1430
|
+
);
|
|
1147
1431
|
}
|
|
1148
1432
|
}
|
|
1433
|
+
await mkdir(input.worktreesDir, { recursive: true });
|
|
1434
|
+
await git(repoDir, [
|
|
1435
|
+
"worktree",
|
|
1436
|
+
"add",
|
|
1437
|
+
"--no-track",
|
|
1438
|
+
// A folder left in place may still be registered with the work branch checked out.
|
|
1439
|
+
...leftInPlace ? ["--force"] : [],
|
|
1440
|
+
"-B",
|
|
1441
|
+
input.workBranch,
|
|
1442
|
+
worktree,
|
|
1443
|
+
checkout
|
|
1444
|
+
]);
|
|
1445
|
+
} catch (err) {
|
|
1446
|
+
await giveBack();
|
|
1447
|
+
throw err;
|
|
1149
1448
|
}
|
|
1150
|
-
await gitOk(repoDir, ["worktree", "prune"]);
|
|
1151
|
-
await mkdir(input.worktreesDir, { recursive: true });
|
|
1152
|
-
await git(repoDir, [
|
|
1153
|
-
"worktree",
|
|
1154
|
-
"add",
|
|
1155
|
-
"--no-track",
|
|
1156
|
-
// A folder left in place may still be registered with the work branch checked out.
|
|
1157
|
-
...leftInPlace ? ["--force"] : [],
|
|
1158
|
-
"-B",
|
|
1159
|
-
input.workBranch,
|
|
1160
|
-
worktree,
|
|
1161
|
-
checkout
|
|
1162
|
-
]);
|
|
1163
1449
|
return {
|
|
1164
1450
|
repoDir,
|
|
1165
1451
|
worktree,
|
|
@@ -1167,10 +1453,26 @@ async function prepareWorktree(input) {
|
|
|
1167
1453
|
baseSha,
|
|
1168
1454
|
...continuedFrom ? { continuedFrom } : {},
|
|
1169
1455
|
...setAside ? { setAside } : {},
|
|
1170
|
-
...leftInPlace ? { leftInPlace } : {}
|
|
1456
|
+
...leftInPlace ? { leftInPlace } : {},
|
|
1457
|
+
...keptRef ? { keptRef } : {}
|
|
1171
1458
|
};
|
|
1172
1459
|
});
|
|
1173
1460
|
}
|
|
1461
|
+
async function worktreesOnBranch(repoDir, branch) {
|
|
1462
|
+
const res = await exec("git", ["worktree", "list", "--porcelain"], {
|
|
1463
|
+
cwd: repoDir,
|
|
1464
|
+
env: gitEnv(),
|
|
1465
|
+
timeoutMs: 6e4
|
|
1466
|
+
});
|
|
1467
|
+
if (res.code !== 0) return [];
|
|
1468
|
+
const out = [];
|
|
1469
|
+
let dir = null;
|
|
1470
|
+
for (const line of res.stdout.split("\n")) {
|
|
1471
|
+
if (line.startsWith("worktree ")) dir = line.slice("worktree ".length).trim();
|
|
1472
|
+
else if (line.trim() === `branch refs/heads/${branch}` && dir) out.push(dir);
|
|
1473
|
+
}
|
|
1474
|
+
return out;
|
|
1475
|
+
}
|
|
1174
1476
|
async function defaultBranch(repoDir) {
|
|
1175
1477
|
const read = async () => {
|
|
1176
1478
|
const res = await exec("git", ["symbolic-ref", "--short", "refs/remotes/origin/HEAD"], {
|
|
@@ -1272,8 +1574,8 @@ async function excludeFromGit(worktree, dir, why) {
|
|
|
1272
1574
|
}
|
|
1273
1575
|
if (current2.split("\n").some((l) => l.trim() === line)) return;
|
|
1274
1576
|
await mkdir2(join3(file, ".."), { recursive: true });
|
|
1275
|
-
const
|
|
1276
|
-
await writeFile(file, `${current2}${
|
|
1577
|
+
const sep3 = current2 && !current2.endsWith("\n") ? "\n" : "";
|
|
1578
|
+
await writeFile(file, `${current2}${sep3}# ${why}
|
|
1277
1579
|
${line}
|
|
1278
1580
|
`);
|
|
1279
1581
|
}
|
|
@@ -1608,6 +1910,7 @@ function claudeArgs(launch) {
|
|
|
1608
1910
|
return args;
|
|
1609
1911
|
}
|
|
1610
1912
|
function runnerSystemPrompt(input) {
|
|
1913
|
+
const env = environmentSentence(input.environment);
|
|
1611
1914
|
if (!input.workBranch) {
|
|
1612
1915
|
const scratch = [
|
|
1613
1916
|
"You are running a Discovery Tree task through the person\u2019s local Discovery Tree runner.",
|
|
@@ -1616,7 +1919,7 @@ function runnerSystemPrompt(input) {
|
|
|
1616
1919
|
if (input.reference) {
|
|
1617
1920
|
scratch.push(
|
|
1618
1921
|
`The repository this task concerns, ${input.reference.url}, is checked out at`,
|
|
1619
|
-
`\`${input.reference.dir}\` (\`${input.reference.baseRef}\` as it is now), for you to read.`,
|
|
1922
|
+
input.reference.baseRef ? `\`${input.reference.dir}\` (\`${input.reference.baseRef}\` as it is now), for you to read.` : `\`${input.reference.dir}\`, for you to read.`,
|
|
1620
1923
|
"Read it before you propose anything, so your work matches the product as it is: its",
|
|
1621
1924
|
"screens, components, styles, words and data. It is for reading only: do not change it,",
|
|
1622
1925
|
"commit or push. Nothing in it is kept, and this task\u2019s output is your response."
|
|
@@ -1634,6 +1937,7 @@ function runnerSystemPrompt(input) {
|
|
|
1634
1937
|
"Do not upload or link them yourself."
|
|
1635
1938
|
);
|
|
1636
1939
|
}
|
|
1940
|
+
if (env) scratch.push(env);
|
|
1637
1941
|
return scratch.join(" ");
|
|
1638
1942
|
}
|
|
1639
1943
|
const evidence = join4(input.cwd, EVIDENCE_DIR);
|
|
@@ -1666,9 +1970,16 @@ function runnerSystemPrompt(input) {
|
|
|
1666
1970
|
"Other runs may share this computer:",
|
|
1667
1971
|
"if the port is taken, start yours on another port; never stop a process you did not start.",
|
|
1668
1972
|
"Do not start databases, containers or other services yourself, directly or through a",
|
|
1669
|
-
"package script, unless the task asks you to; if one the server needs is not running, say so."
|
|
1973
|
+
"package script, unless the task asks you to; if one the server needs is not running, say so.",
|
|
1974
|
+
...env ? [env] : []
|
|
1670
1975
|
].join(" ");
|
|
1671
1976
|
}
|
|
1977
|
+
function environmentSentence(env) {
|
|
1978
|
+
if (!env?.names.length) return "";
|
|
1979
|
+
const list = (names) => names.map((n) => `\`${n}\``).join(", ");
|
|
1980
|
+
const secrets = env.secretNames.length ? ` ${list(env.secretNames)} ${env.secretNames.length === 1 ? "is a secret" : "are secrets"}: never print, log, commit or echo ${env.secretNames.length === 1 ? "its value" : "their values"}, and do not write ${env.secretNames.length === 1 ? "it" : "them"} into files.` : "";
|
|
1981
|
+
return `The run's environment sets these environment variables for you: ${list(env.names)}.${secrets}`;
|
|
1982
|
+
}
|
|
1672
1983
|
|
|
1673
1984
|
// src/claude-code-rules.ts
|
|
1674
1985
|
import { readFile as readFile2, stat as stat3 } from "node:fs/promises";
|
|
@@ -1954,7 +2265,10 @@ var PermissionRelay = class {
|
|
|
1954
2265
|
controlRequestId: req.controlRequestId,
|
|
1955
2266
|
toolName: req.toolName,
|
|
1956
2267
|
input: req.input,
|
|
1957
|
-
inputSummary: summarizeToolInput(
|
|
2268
|
+
inputSummary: summarizeToolInput(
|
|
2269
|
+
req.toolName,
|
|
2270
|
+
this.deps.redactInput ? this.deps.redactInput(req.input) : req.input
|
|
2271
|
+
),
|
|
1958
2272
|
requestedAt,
|
|
1959
2273
|
timer
|
|
1960
2274
|
};
|
|
@@ -2063,10 +2377,13 @@ var PermissionRelay = class {
|
|
|
2063
2377
|
};
|
|
2064
2378
|
|
|
2065
2379
|
// src/stream-mapper.ts
|
|
2380
|
+
var CAP_TEXT_MARKER = "\n\u2026 [truncated by dt-runner]";
|
|
2066
2381
|
function capText(text, max = RUNNER_EVENT_TEXT_MAX_LENGTH) {
|
|
2067
2382
|
if (text.length <= max) return { text, truncated: false };
|
|
2068
|
-
|
|
2069
|
-
|
|
2383
|
+
return {
|
|
2384
|
+
text: text.slice(0, max - CAP_TEXT_MARKER.length) + CAP_TEXT_MARKER,
|
|
2385
|
+
truncated: true
|
|
2386
|
+
};
|
|
2070
2387
|
}
|
|
2071
2388
|
var ClaudeStreamMapper = class {
|
|
2072
2389
|
/** Running offset of each live text block, by providerEventId. */
|
|
@@ -3495,6 +3812,12 @@ function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPa
|
|
|
3495
3812
|
`maxSessions must be a whole number from 1 to ${MAX_SESSIONS_LIMIT} (got ${maxSessions}).`
|
|
3496
3813
|
);
|
|
3497
3814
|
}
|
|
3815
|
+
const maxJobs = overrides.maxJobs ?? file?.maxJobs ?? RUNNER_DEFAULT_MAX_JOBS;
|
|
3816
|
+
if (!Number.isInteger(maxJobs) || maxJobs < 1 || maxJobs > RUNNER_MAX_JOBS_LIMIT) {
|
|
3817
|
+
throw new Error(
|
|
3818
|
+
`maxJobs must be a whole number from 1 to ${RUNNER_MAX_JOBS_LIMIT} (got ${maxJobs}).`
|
|
3819
|
+
);
|
|
3820
|
+
}
|
|
3498
3821
|
const inherit = file?.inheritClaudeCodePermissions;
|
|
3499
3822
|
if (inherit !== void 0 && typeof inherit !== "boolean") {
|
|
3500
3823
|
throw new Error(
|
|
@@ -3536,6 +3859,7 @@ function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPa
|
|
|
3536
3859
|
token: env.DT_RUNNER_TOKEN || file?.token || null,
|
|
3537
3860
|
name: file?.name ?? null,
|
|
3538
3861
|
maxSessions,
|
|
3862
|
+
maxJobs,
|
|
3539
3863
|
reposDir: overrides.reposDir ?? file?.reposDir ?? join7(paths.dataDir, "repos"),
|
|
3540
3864
|
worktreesDir: file?.worktreesDir ?? join7(paths.dataDir, "worktrees"),
|
|
3541
3865
|
permissionMode: mode,
|
|
@@ -3555,7 +3879,7 @@ function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPa
|
|
|
3555
3879
|
}
|
|
3556
3880
|
|
|
3557
3881
|
// src/daemon.ts
|
|
3558
|
-
import { join as
|
|
3882
|
+
import { join as join16 } from "node:path";
|
|
3559
3883
|
|
|
3560
3884
|
// src/backoff.ts
|
|
3561
3885
|
function backoffDelay(attempt, baseMs = 1e3, maxMs = 6e4) {
|
|
@@ -3563,13 +3887,13 @@ function backoffDelay(attempt, baseMs = 1e3, maxMs = 6e4) {
|
|
|
3563
3887
|
return Math.round(ceiling / 2 + Math.random() * ceiling / 2);
|
|
3564
3888
|
}
|
|
3565
3889
|
function sleep(ms, signal) {
|
|
3566
|
-
return new Promise((
|
|
3567
|
-
if (signal?.aborted) return
|
|
3890
|
+
return new Promise((resolve4) => {
|
|
3891
|
+
if (signal?.aborted) return resolve4();
|
|
3568
3892
|
const timer = setTimeout(done, ms);
|
|
3569
3893
|
function done() {
|
|
3570
3894
|
clearTimeout(timer);
|
|
3571
3895
|
signal?.removeEventListener("abort", done);
|
|
3572
|
-
|
|
3896
|
+
resolve4();
|
|
3573
3897
|
}
|
|
3574
3898
|
signal?.addEventListener("abort", done, { once: true });
|
|
3575
3899
|
});
|
|
@@ -3677,75 +4001,304 @@ function reportableSessionIds(ids, onDropped = () => void 0) {
|
|
|
3677
4001
|
return [...out];
|
|
3678
4002
|
}
|
|
3679
4003
|
|
|
3680
|
-
// src/
|
|
3681
|
-
import {
|
|
3682
|
-
import {
|
|
4004
|
+
// src/jobs/job-manager.ts
|
|
4005
|
+
import { randomBytes as randomBytes3, scrypt, timingSafeEqual } from "node:crypto";
|
|
4006
|
+
import { realpathSync } from "node:fs";
|
|
4007
|
+
import { mkdir as mkdir6, readFile as readFile7, readdir as readdir2, stat as stat4 } from "node:fs/promises";
|
|
4008
|
+
import { basename, dirname as dirname6, isAbsolute as isAbsolute4, join as join11, resolve as resolve2, sep as sep2 } from "node:path";
|
|
3683
4009
|
|
|
3684
|
-
// src/
|
|
3685
|
-
|
|
3686
|
-
|
|
3687
|
-
|
|
3688
|
-
|
|
3689
|
-
|
|
3690
|
-
|
|
3691
|
-
|
|
3692
|
-
|
|
3693
|
-
|
|
3694
|
-
|
|
3695
|
-
|
|
3696
|
-
|
|
3697
|
-
|
|
3698
|
-
|
|
4010
|
+
// src/environment.ts
|
|
4011
|
+
function sessionEnvironment(raw) {
|
|
4012
|
+
if (!raw || typeof raw !== "object") return null;
|
|
4013
|
+
const { variables, secrets } = raw;
|
|
4014
|
+
const env = {};
|
|
4015
|
+
const secretValues = [];
|
|
4016
|
+
const skipped = [];
|
|
4017
|
+
const take = (from, max, maxLength, onTaken) => {
|
|
4018
|
+
if (!from || typeof from !== "object" || Array.isArray(from)) return;
|
|
4019
|
+
let n = 0;
|
|
4020
|
+
for (const [name, value] of Object.entries(from)) {
|
|
4021
|
+
const ok = ENV_NAME_PATTERN.test(name) && !isReservedEnvName(name) && typeof value === "string" && value.length <= maxLength && !value.includes("\0") && n < max;
|
|
4022
|
+
if (!ok) {
|
|
4023
|
+
skipped.push(ENV_NAME_PATTERN.test(name) ? name : "(an invalid name)");
|
|
4024
|
+
continue;
|
|
4025
|
+
}
|
|
4026
|
+
n++;
|
|
4027
|
+
env[name] = value;
|
|
4028
|
+
onTaken(name, value);
|
|
4029
|
+
}
|
|
4030
|
+
};
|
|
4031
|
+
take(variables, ENV_VARIABLES_MAX, ENV_VARIABLE_VALUE_MAX_LENGTH, () => void 0);
|
|
4032
|
+
take(
|
|
4033
|
+
secrets,
|
|
4034
|
+
ENV_SECRETS_MAX,
|
|
4035
|
+
ENV_SECRET_VALUE_MAX_LENGTH,
|
|
4036
|
+
(name, value) => secretValues.push({ name, value })
|
|
4037
|
+
);
|
|
4038
|
+
const names = Object.keys(env).sort();
|
|
4039
|
+
if (!names.length && !skipped.length) return null;
|
|
4040
|
+
return {
|
|
4041
|
+
env,
|
|
4042
|
+
names,
|
|
4043
|
+
secretNames: [...new Set(secretValues.map((s) => s.name))].sort(),
|
|
4044
|
+
skipped,
|
|
4045
|
+
unredacted: secretValues.filter((s) => s.value.length > 0 && s.value.length < SECRET_REDACTION_MIN_LENGTH).map((s) => s.name).sort(),
|
|
4046
|
+
redactor: new SecretRedactor(secretValues)
|
|
4047
|
+
};
|
|
3699
4048
|
}
|
|
3700
|
-
|
|
3701
|
-
|
|
3702
|
-
|
|
3703
|
-
|
|
3704
|
-
|
|
3705
|
-
|
|
3706
|
-
|
|
3707
|
-
|
|
3708
|
-
|
|
3709
|
-
|
|
3710
|
-
|
|
4049
|
+
var SECRET_REDACTION_MIN_LENGTH = 4;
|
|
4050
|
+
var RULE_PLACEHOLDER = "[secret:";
|
|
4051
|
+
var DELTA_STREAMS_KEPT = 64;
|
|
4052
|
+
var PROTOCOL_FIELDS = /* @__PURE__ */ new Set([
|
|
4053
|
+
"type",
|
|
4054
|
+
"status",
|
|
4055
|
+
"id",
|
|
4056
|
+
"providerEventId",
|
|
4057
|
+
"callId",
|
|
4058
|
+
"claudeSessionId",
|
|
4059
|
+
"conversationId",
|
|
4060
|
+
"requestedAt",
|
|
4061
|
+
"deniedAt"
|
|
4062
|
+
]);
|
|
4063
|
+
var FRAME_FIELDS = /* @__PURE__ */ new Set(["tool", "request", "denial"]);
|
|
4064
|
+
var SecretRedactor = class {
|
|
4065
|
+
secrets;
|
|
4066
|
+
/** `[secret: NAME]` for the session's own names: already redacted, left as it is. */
|
|
4067
|
+
placeholders;
|
|
4068
|
+
/** Per live message: what was held back, and the redacted text's length so far. */
|
|
4069
|
+
deltas = /* @__PURE__ */ new Map();
|
|
4070
|
+
constructor(secrets) {
|
|
4071
|
+
this.secrets = secrets.filter((s) => s.value.length >= SECRET_REDACTION_MIN_LENGTH).sort((a, b) => b.value.length - a.value.length);
|
|
4072
|
+
this.placeholders = [...new Set(this.secrets.map((s) => placeholder(s.name)))];
|
|
4073
|
+
}
|
|
4074
|
+
/** Whether there is anything to redact. */
|
|
4075
|
+
get active() {
|
|
4076
|
+
return this.secrets.length > 0;
|
|
3711
4077
|
}
|
|
3712
|
-
|
|
3713
|
-
|
|
3714
|
-
|
|
3715
|
-
|
|
3716
|
-
|
|
3717
|
-
|
|
3718
|
-
|
|
3719
|
-
|
|
3720
|
-
|
|
3721
|
-
|
|
3722
|
-
|
|
4078
|
+
/**
|
|
4079
|
+
* `text` with every secret value replaced. Values that overlap (one inside another, or
|
|
4080
|
+
* sharing characters) are replaced as one span, so no part of either is left. A text the
|
|
4081
|
+
* runner cut to length (`capText`) also loses what a value cut off at its end left before
|
|
4082
|
+
* the marker: a value missing its end would no longer be recognised.
|
|
4083
|
+
*/
|
|
4084
|
+
redact(text) {
|
|
4085
|
+
if (!this.active || !text) return text;
|
|
4086
|
+
if (text.endsWith(CAP_TEXT_MARKER)) {
|
|
4087
|
+
const raw = text.slice(0, -CAP_TEXT_MARKER.length);
|
|
4088
|
+
return fitEvent(this.replace(raw.slice(0, this.endOfWhole(raw))));
|
|
3723
4089
|
}
|
|
4090
|
+
return this.replace(text);
|
|
3724
4091
|
}
|
|
3725
|
-
|
|
4092
|
+
/**
|
|
4093
|
+
* {@link redact} on the end of a longer text (`cutAtStart`: its start was dropped, as a
|
|
4094
|
+
* rolling stderr tail's is). What a value cut off at the start left there is dropped too: a
|
|
4095
|
+
* value missing its beginning would no longer be recognised.
|
|
4096
|
+
*/
|
|
4097
|
+
redactWindow(text, cutAtStart) {
|
|
4098
|
+
if (!this.active) return text;
|
|
4099
|
+
return this.redact(cutAtStart ? text.slice(this.startOfWhole(text)) : text);
|
|
4100
|
+
}
|
|
4101
|
+
/**
|
|
4102
|
+
* {@link redact} on a text whose end was cut off (a job's log line past its length limit):
|
|
4103
|
+
* what a value cut off there left at its end is dropped as well, as no longer recognisable.
|
|
4104
|
+
*/
|
|
4105
|
+
redactCut(text) {
|
|
4106
|
+
if (!this.active || !text) return text;
|
|
4107
|
+
return this.replace(text.slice(0, this.endOfWhole(text)));
|
|
4108
|
+
}
|
|
4109
|
+
/**
|
|
4110
|
+
* Every place a value occurs, overlapping ones merged into one span (named for its longest
|
|
4111
|
+
* value), in order. Values inside a placeholder already written are not counted.
|
|
4112
|
+
*/
|
|
4113
|
+
spans(text) {
|
|
4114
|
+
const kept = [];
|
|
4115
|
+
for (const p of this.placeholders) {
|
|
4116
|
+
for (let i = text.indexOf(p); i >= 0; i = text.indexOf(p, i + 1))
|
|
4117
|
+
kept.push([i, i + p.length]);
|
|
4118
|
+
}
|
|
4119
|
+
const found = [];
|
|
4120
|
+
for (const { name, value } of this.secrets) {
|
|
4121
|
+
for (let i = text.indexOf(value); i >= 0; i = text.indexOf(value, i + 1)) {
|
|
4122
|
+
const end = i + value.length;
|
|
4123
|
+
if (kept.some(([a, b]) => a <= i && end <= b)) continue;
|
|
4124
|
+
const inside = kept.find(([a, b]) => a <= i && i < b);
|
|
4125
|
+
found.push({ start: inside ? inside[1] : i, end, name, len: value.length });
|
|
4126
|
+
}
|
|
4127
|
+
}
|
|
4128
|
+
found.sort((a, b) => a.start - b.start || b.len - a.len);
|
|
4129
|
+
const merged = [];
|
|
4130
|
+
for (const span of found) {
|
|
4131
|
+
const last = merged.at(-1);
|
|
4132
|
+
if (last && span.start < last.end) {
|
|
4133
|
+
if (span.len > last.len) Object.assign(last, { name: span.name, len: span.len });
|
|
4134
|
+
last.end = Math.max(last.end, span.end);
|
|
4135
|
+
} else {
|
|
4136
|
+
merged.push({ ...span });
|
|
4137
|
+
}
|
|
4138
|
+
}
|
|
4139
|
+
return merged;
|
|
4140
|
+
}
|
|
4141
|
+
replace(text) {
|
|
4142
|
+
const spans = this.spans(text);
|
|
4143
|
+
if (!spans.length) return text;
|
|
4144
|
+
let out = "";
|
|
4145
|
+
let at = 0;
|
|
4146
|
+
for (const span of spans) {
|
|
4147
|
+
out += text.slice(at, span.start) + placeholder(span.name);
|
|
4148
|
+
at = span.end;
|
|
4149
|
+
}
|
|
4150
|
+
return out + text.slice(at);
|
|
4151
|
+
}
|
|
4152
|
+
/** The span of a whole value that `cut` falls strictly inside, if any. */
|
|
4153
|
+
spanAcross(text, cut2) {
|
|
4154
|
+
return this.spans(text).find((s) => s.start < cut2 && cut2 < s.end);
|
|
4155
|
+
}
|
|
4156
|
+
/**
|
|
4157
|
+
* Where `text` stops being whole at its end: before the longest end that a value starts
|
|
4158
|
+
* with, unless that end belongs to a whole value, which is kept (and replaced).
|
|
4159
|
+
*/
|
|
4160
|
+
endOfWhole(text) {
|
|
4161
|
+
const cut2 = text.length - this.partialAtEnd(text);
|
|
4162
|
+
return this.spanAcross(text, cut2)?.end ?? cut2;
|
|
4163
|
+
}
|
|
4164
|
+
/**
|
|
4165
|
+
* Where `text` starts being whole: after the longest start that a value ends with (what a
|
|
4166
|
+
* value cut off at the start left), unless that start belongs to a whole value, kept.
|
|
4167
|
+
*/
|
|
4168
|
+
startOfWhole(text) {
|
|
4169
|
+
let cut2 = 0;
|
|
4170
|
+
for (const { value } of this.secrets) {
|
|
4171
|
+
for (let k = Math.min(value.length - 1, text.length); k > cut2; k--) {
|
|
4172
|
+
if (value.endsWith(text.slice(0, k))) {
|
|
4173
|
+
cut2 = k;
|
|
4174
|
+
break;
|
|
4175
|
+
}
|
|
4176
|
+
}
|
|
4177
|
+
}
|
|
4178
|
+
return this.spanAcross(text, cut2)?.start ?? cut2;
|
|
4179
|
+
}
|
|
4180
|
+
/**
|
|
4181
|
+
* A call's input as rules may be built from: redacted, with each placeholder written as
|
|
4182
|
+
* one word (`[secret:NAME]`, {@link RULE_PLACEHOLDER}), so a command splits into words as
|
|
4183
|
+
* it did.
|
|
4184
|
+
*/
|
|
4185
|
+
forRules(input) {
|
|
4186
|
+
if (!this.active) return input;
|
|
4187
|
+
const compact = (v) => {
|
|
4188
|
+
if (typeof v === "string") return this.redact(v).replace(/\[secret: /g, RULE_PLACEHOLDER);
|
|
4189
|
+
if (Array.isArray(v)) return v.map(compact);
|
|
4190
|
+
if (v && typeof v === "object") {
|
|
4191
|
+
return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, compact(x)]));
|
|
4192
|
+
}
|
|
4193
|
+
return v;
|
|
4194
|
+
};
|
|
4195
|
+
return compact(input);
|
|
4196
|
+
}
|
|
4197
|
+
/** {@link redact} through every string in a JSON-like value (tool inputs, outputs). */
|
|
4198
|
+
redactDeep(value) {
|
|
4199
|
+
if (!this.active) return value;
|
|
4200
|
+
if (typeof value === "string") return this.redact(value);
|
|
4201
|
+
if (Array.isArray(value)) return value.map((v) => this.redactDeep(v));
|
|
4202
|
+
if (value && typeof value === "object") {
|
|
4203
|
+
const out = {};
|
|
4204
|
+
for (const [k, v] of Object.entries(value)) {
|
|
4205
|
+
out[k] = this.redactDeep(v);
|
|
4206
|
+
}
|
|
4207
|
+
return out;
|
|
4208
|
+
}
|
|
4209
|
+
return value;
|
|
4210
|
+
}
|
|
4211
|
+
/**
|
|
4212
|
+
* The event as it may be posted, or null for a text delta that is all held back for now.
|
|
4213
|
+
*/
|
|
4214
|
+
event(event) {
|
|
4215
|
+
if (!this.active) return event;
|
|
4216
|
+
if (event.type === "assistant_delta") return this.delta(event);
|
|
4217
|
+
if (event.type === "assistant_message") this.deltas.delete(event.providerEventId);
|
|
4218
|
+
return this.redactFrame(event);
|
|
4219
|
+
}
|
|
4220
|
+
/**
|
|
4221
|
+
* {@link redactDeep} over an event, keeping its protocol fields as they are: a value that
|
|
4222
|
+
* happens to equal `finished` or `completed` must not turn a result's status or a call's
|
|
4223
|
+
* status into a placeholder the server refuses. Only the event itself and its `tool`,
|
|
4224
|
+
* `request` and `denial` are frames; anything inside them (a call's `input`) is content.
|
|
4225
|
+
*/
|
|
4226
|
+
redactFrame(frame) {
|
|
4227
|
+
const out = {};
|
|
4228
|
+
for (const [key, value] of Object.entries(frame)) {
|
|
4229
|
+
if (PROTOCOL_FIELDS.has(key) && typeof value === "string") out[key] = value;
|
|
4230
|
+
else if (FRAME_FIELDS.has(key) && value !== null && typeof value === "object" && !Array.isArray(value)) {
|
|
4231
|
+
out[key] = this.redactFrame(value);
|
|
4232
|
+
} else out[key] = this.redactDeep(value);
|
|
4233
|
+
}
|
|
4234
|
+
return out;
|
|
4235
|
+
}
|
|
4236
|
+
delta(event) {
|
|
4237
|
+
const key = event.providerEventId;
|
|
4238
|
+
const stream = this.deltas.get(key) ?? { held: "", offset: 0 };
|
|
4239
|
+
this.deltas.delete(key);
|
|
4240
|
+
this.deltas.set(key, stream);
|
|
4241
|
+
while (this.deltas.size > DELTA_STREAMS_KEPT) {
|
|
4242
|
+
this.deltas.delete(this.deltas.keys().next().value);
|
|
4243
|
+
}
|
|
4244
|
+
const text = stream.held + event.text;
|
|
4245
|
+
const end = text.length - this.partialAtEnd(text);
|
|
4246
|
+
const cut2 = this.spanAcross(text, end)?.start ?? end;
|
|
4247
|
+
stream.held = text.slice(cut2);
|
|
4248
|
+
const ready = this.replace(text.slice(0, cut2));
|
|
4249
|
+
if (!ready) return null;
|
|
4250
|
+
const offset = stream.offset;
|
|
4251
|
+
stream.offset += ready.length;
|
|
4252
|
+
return {
|
|
4253
|
+
...event,
|
|
4254
|
+
text: ready,
|
|
4255
|
+
...event.offset !== void 0 ? { offset } : {}
|
|
4256
|
+
};
|
|
4257
|
+
}
|
|
4258
|
+
/** The length of the longest end of `text` that a secret value starts with (not all of it). */
|
|
4259
|
+
partialAtEnd(text) {
|
|
4260
|
+
if (!text) return 0;
|
|
4261
|
+
const last = text.charCodeAt(text.length - 1);
|
|
4262
|
+
let best = 0;
|
|
4263
|
+
for (const { value } of this.secrets) {
|
|
4264
|
+
for (let k = Math.min(value.length - 1, text.length); k > best; k--) {
|
|
4265
|
+
if (value.charCodeAt(k - 1) !== last) continue;
|
|
4266
|
+
if (text.endsWith(value.slice(0, k))) {
|
|
4267
|
+
best = k;
|
|
4268
|
+
break;
|
|
4269
|
+
}
|
|
4270
|
+
}
|
|
4271
|
+
}
|
|
4272
|
+
return best;
|
|
4273
|
+
}
|
|
4274
|
+
};
|
|
4275
|
+
function redactingLogger(logger, redactor) {
|
|
4276
|
+
if (!redactor?.active) return logger;
|
|
4277
|
+
const wrap = (level) => (msg, fields) => logger[level](redactor.redact(msg), fields ? redactor.redactDeep(fields) : void 0);
|
|
4278
|
+
return { debug: wrap("debug"), info: wrap("info"), warn: wrap("warn"), error: wrap("error") };
|
|
3726
4279
|
}
|
|
3727
|
-
function
|
|
3728
|
-
|
|
3729
|
-
|
|
3730
|
-
|
|
3731
|
-
|
|
3732
|
-
|
|
3733
|
-
|
|
3734
|
-
|
|
3735
|
-
|
|
3736
|
-
)
|
|
3737
|
-
|
|
3738
|
-
|
|
3739
|
-
|
|
4280
|
+
function placeholder(name) {
|
|
4281
|
+
return `[secret: ${name}]`;
|
|
4282
|
+
}
|
|
4283
|
+
function fitEvent(body) {
|
|
4284
|
+
const room = RUNNER_EVENT_TEXT_MAX_LENGTH - CAP_TEXT_MARKER.length;
|
|
4285
|
+
if (body.length <= room) return body + CAP_TEXT_MARKER;
|
|
4286
|
+
let out = body.slice(0, room);
|
|
4287
|
+
const open3 = out.lastIndexOf("[");
|
|
4288
|
+
if (open3 >= 0 && out.indexOf("]", open3) < 0) {
|
|
4289
|
+
const rest = out.slice(open3);
|
|
4290
|
+
if (rest.startsWith("[secret: ") || "[secret: ".startsWith(rest)) out = out.slice(0, open3);
|
|
4291
|
+
}
|
|
4292
|
+
return out + CAP_TEXT_MARKER;
|
|
3740
4293
|
}
|
|
3741
4294
|
|
|
3742
4295
|
// src/fsutil.ts
|
|
3743
|
-
import { mkdir as
|
|
4296
|
+
import { mkdir as mkdir4, readFile as readFile4, rename as rename2, writeFile as writeFile3 } from "node:fs/promises";
|
|
3744
4297
|
import { dirname as dirname4 } from "node:path";
|
|
3745
4298
|
async function writeJsonAtomic(file, value) {
|
|
3746
|
-
await
|
|
4299
|
+
await mkdir4(dirname4(file), { recursive: true });
|
|
3747
4300
|
const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
3748
|
-
await
|
|
4301
|
+
await writeFile3(tmp, JSON.stringify(value), { mode: 384 });
|
|
3749
4302
|
await rename2(tmp, file);
|
|
3750
4303
|
}
|
|
3751
4304
|
async function readJson(file) {
|
|
@@ -3758,63 +4311,1866 @@ async function readJson(file) {
|
|
|
3758
4311
|
}
|
|
3759
4312
|
}
|
|
3760
4313
|
|
|
3761
|
-
// src/
|
|
4314
|
+
// src/jobs/job-log.ts
|
|
4315
|
+
import { open } from "node:fs/promises";
|
|
4316
|
+
function startCursor() {
|
|
4317
|
+
return { stdout: { offset: 0, skipping: false }, stderr: { offset: 0, skipping: false } };
|
|
4318
|
+
}
|
|
4319
|
+
var JOB_LINE_MAX_BYTES = 64 * 1024;
|
|
4320
|
+
var READ_CHUNK_BYTES = 1024 * 1024;
|
|
4321
|
+
var JOB_READ_MAX_BYTES = 8 * 1024 * 1024;
|
|
4322
|
+
var decoder = new TextDecoder("utf-8", { fatal: false });
|
|
4323
|
+
var LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g;
|
|
4324
|
+
function postableLineText(text) {
|
|
4325
|
+
const clean = text.replace(LONE_SURROGATE, "\uFFFD");
|
|
4326
|
+
const max = RUNNER_JOB_LOG_LINE_MAX_LENGTH;
|
|
4327
|
+
if (clean.length <= max) return clean;
|
|
4328
|
+
const code = clean.charCodeAt(max - 1);
|
|
4329
|
+
let cut2 = clean.slice(0, code >= 55296 && code <= 56319 ? max - 1 : max);
|
|
4330
|
+
const open3 = cut2.lastIndexOf("[secret:");
|
|
4331
|
+
if (open3 >= 0 && cut2.indexOf("]", open3) < 0) cut2 = cut2.slice(0, open3);
|
|
4332
|
+
return cut2;
|
|
4333
|
+
}
|
|
4334
|
+
function completeUtf8(bytes) {
|
|
4335
|
+
let lead = bytes.length - 1;
|
|
4336
|
+
while (lead >= 0 && bytes.length - lead <= 3 && (bytes[lead] & 192) === 128) lead--;
|
|
4337
|
+
if (lead < 0) return bytes.length;
|
|
4338
|
+
const b = bytes[lead];
|
|
4339
|
+
const size = b >= 240 ? 4 : b >= 224 ? 3 : b >= 192 ? 2 : 1;
|
|
4340
|
+
return bytes.length - lead < size ? lead : bytes.length;
|
|
4341
|
+
}
|
|
4342
|
+
var LogFileReader = class {
|
|
4343
|
+
constructor(file, stream, from) {
|
|
4344
|
+
this.file = file;
|
|
4345
|
+
this.stream = stream;
|
|
4346
|
+
this.cursor = { ...from };
|
|
4347
|
+
}
|
|
4348
|
+
handle = null;
|
|
4349
|
+
cursor;
|
|
4350
|
+
get position() {
|
|
4351
|
+
return { ...this.cursor };
|
|
4352
|
+
}
|
|
4353
|
+
/** The last read reached the end of what is written (false: there is more to read now). */
|
|
4354
|
+
atEnd = true;
|
|
4355
|
+
/**
|
|
4356
|
+
* The lines written since the last call, from at most about `maxBytes` of the file (a
|
|
4357
|
+
* backlog is read over several calls, never all at once); `final`: when the end is
|
|
4358
|
+
* reached, the partial last line too.
|
|
4359
|
+
*/
|
|
4360
|
+
async read(final = false, maxBytes = JOB_READ_MAX_BYTES) {
|
|
4361
|
+
if (!this.handle) {
|
|
4362
|
+
try {
|
|
4363
|
+
this.handle = await open(this.file, "r");
|
|
4364
|
+
} catch (err) {
|
|
4365
|
+
this.atEnd = true;
|
|
4366
|
+
if (err.code === "ENOENT") return [];
|
|
4367
|
+
throw err;
|
|
4368
|
+
}
|
|
4369
|
+
}
|
|
4370
|
+
const lines = [];
|
|
4371
|
+
const at = (/* @__PURE__ */ new Date()).toISOString();
|
|
4372
|
+
let pending = Buffer.alloc(0);
|
|
4373
|
+
let position = this.cursor.offset;
|
|
4374
|
+
const limit = this.cursor.offset + Math.max(maxBytes, READ_CHUNK_BYTES);
|
|
4375
|
+
this.atEnd = false;
|
|
4376
|
+
for (; ; ) {
|
|
4377
|
+
if (position >= limit) break;
|
|
4378
|
+
const chunk = Buffer.alloc(READ_CHUNK_BYTES);
|
|
4379
|
+
const { bytesRead } = await this.handle.read(chunk, 0, chunk.length, position);
|
|
4380
|
+
if (bytesRead === 0) {
|
|
4381
|
+
this.atEnd = true;
|
|
4382
|
+
break;
|
|
4383
|
+
}
|
|
4384
|
+
position += bytesRead;
|
|
4385
|
+
pending = pending.length ? Buffer.concat([pending, chunk.subarray(0, bytesRead)]) : chunk.subarray(0, bytesRead);
|
|
4386
|
+
let start2 = 0;
|
|
4387
|
+
for (; ; ) {
|
|
4388
|
+
const nl = pending.indexOf(10, start2);
|
|
4389
|
+
if (nl < 0) break;
|
|
4390
|
+
this.take(pending.subarray(start2, nl), lines, at);
|
|
4391
|
+
start2 = nl + 1;
|
|
4392
|
+
}
|
|
4393
|
+
this.cursor.offset += start2;
|
|
4394
|
+
pending = pending.subarray(start2);
|
|
4395
|
+
if (pending.length > JOB_LINE_MAX_BYTES) {
|
|
4396
|
+
if (!this.cursor.skipping) this.emitCut(pending, lines, at);
|
|
4397
|
+
this.cursor.skipping = true;
|
|
4398
|
+
this.cursor.offset += pending.length;
|
|
4399
|
+
pending = Buffer.alloc(0);
|
|
4400
|
+
}
|
|
4401
|
+
if (bytesRead < chunk.length) {
|
|
4402
|
+
this.atEnd = true;
|
|
4403
|
+
break;
|
|
4404
|
+
}
|
|
4405
|
+
}
|
|
4406
|
+
if (final && this.atEnd && pending.length) {
|
|
4407
|
+
if (this.cursor.skipping) this.cursor.skipping = false;
|
|
4408
|
+
else this.emit(pending.subarray(0, completeUtf8(pending)), lines, at, true);
|
|
4409
|
+
this.cursor.offset += pending.length;
|
|
4410
|
+
}
|
|
4411
|
+
return lines;
|
|
4412
|
+
}
|
|
4413
|
+
async close() {
|
|
4414
|
+
const h = this.handle;
|
|
4415
|
+
this.handle = null;
|
|
4416
|
+
await h?.close().catch(() => void 0);
|
|
4417
|
+
}
|
|
4418
|
+
/** A whole line (without its `\n`): emitted, unless it is the rest of one passed over. */
|
|
4419
|
+
take(bytes, lines, at) {
|
|
4420
|
+
if (this.cursor.skipping) {
|
|
4421
|
+
this.cursor.skipping = false;
|
|
4422
|
+
return;
|
|
4423
|
+
}
|
|
4424
|
+
if (bytes.length > JOB_LINE_MAX_BYTES) this.emitCut(bytes, lines, at);
|
|
4425
|
+
else this.emit(bytes, lines, at);
|
|
4426
|
+
}
|
|
4427
|
+
/**
|
|
4428
|
+
* The first {@link JOB_LINE_MAX_BYTES} of a longer line, cut where a character starts (not
|
|
4429
|
+
* inside one, which would leave U+FFFD where the end of a secret's prefix is), and marked
|
|
4430
|
+
* as cut, so its redaction drops what a value cut off there left.
|
|
4431
|
+
*/
|
|
4432
|
+
emitCut(bytes, lines, at) {
|
|
4433
|
+
let end = JOB_LINE_MAX_BYTES;
|
|
4434
|
+
while (end > 0 && (bytes[end] & 192) === 128) end--;
|
|
4435
|
+
this.emit(bytes.subarray(0, end), lines, at, true);
|
|
4436
|
+
}
|
|
4437
|
+
emit(bytes, lines, at, cut2 = false) {
|
|
4438
|
+
let text = decoder.decode(bytes);
|
|
4439
|
+
if (!cut2 && text.endsWith("\r")) text = text.slice(0, -1);
|
|
4440
|
+
lines.push({ stream: this.stream, text, at, ...cut2 ? { cut: true } : {} });
|
|
4441
|
+
}
|
|
4442
|
+
};
|
|
4443
|
+
|
|
4444
|
+
// src/jobs/job-outbox.ts
|
|
3762
4445
|
var MAX_REJECTED_ATTEMPTS = 3;
|
|
3763
|
-
var
|
|
4446
|
+
var JobOutbox = class _JobOutbox {
|
|
3764
4447
|
constructor(opts) {
|
|
3765
4448
|
this.opts = opts;
|
|
3766
4449
|
}
|
|
3767
4450
|
nextSeq = 1;
|
|
3768
4451
|
pending = [];
|
|
3769
|
-
|
|
3770
|
-
|
|
4452
|
+
status = null;
|
|
4453
|
+
tail = startCursor();
|
|
4454
|
+
finished = false;
|
|
4455
|
+
/** What the last completed write saved: only that much may be posted. */
|
|
4456
|
+
durableSeq = 0;
|
|
4457
|
+
durableStatus = null;
|
|
3771
4458
|
pumping = false;
|
|
3772
4459
|
pumpTimer = null;
|
|
3773
4460
|
stopped = false;
|
|
3774
|
-
|
|
4461
|
+
discarded = false;
|
|
3775
4462
|
stopController = new AbortController();
|
|
3776
4463
|
persistChain = Promise.resolve();
|
|
3777
4464
|
persistQueued = false;
|
|
4465
|
+
/** Writes failed in a row, and the timer of the next try. */
|
|
4466
|
+
persistFailures = 0;
|
|
4467
|
+
persistRetry = null;
|
|
3778
4468
|
idleWaiters = [];
|
|
3779
|
-
|
|
4469
|
+
finishNotified = false;
|
|
3780
4470
|
static async open(opts) {
|
|
3781
|
-
const box = new
|
|
4471
|
+
const box = new _JobOutbox(opts);
|
|
3782
4472
|
const saved = await readJson(opts.file);
|
|
3783
4473
|
if (saved) {
|
|
3784
4474
|
box.pending = Array.isArray(saved.pending) ? saved.pending : [];
|
|
3785
|
-
const
|
|
3786
|
-
box.nextSeq = Math.max(saved.nextSeq || 1,
|
|
3787
|
-
|
|
3788
|
-
|
|
4475
|
+
const last = box.pending.at(-1)?.seq ?? 0;
|
|
4476
|
+
box.nextSeq = Math.max(saved.nextSeq || 1, last + 1);
|
|
4477
|
+
box.status = saved.status ?? null;
|
|
4478
|
+
box.tail = saved.cursor ?? startCursor();
|
|
4479
|
+
box.finished = saved.finished === true;
|
|
4480
|
+
box.durableSeq = box.nextSeq - 1;
|
|
4481
|
+
box.durableStatus = box.status;
|
|
4482
|
+
}
|
|
4483
|
+
if (box.pending.length || box.status) box.schedulePump();
|
|
3789
4484
|
return box;
|
|
3790
4485
|
}
|
|
4486
|
+
/** Where reading the job's output got to, as last queued. */
|
|
4487
|
+
get cursor() {
|
|
4488
|
+
return this.tail;
|
|
4489
|
+
}
|
|
4490
|
+
/** Its last report is through (or there is none to give) and no line waits. */
|
|
4491
|
+
get isFinished() {
|
|
4492
|
+
return this.finished && this.pending.length === 0 && !this.status;
|
|
4493
|
+
}
|
|
4494
|
+
/** The job's last report is queued or sent (or it ended with none to give). */
|
|
4495
|
+
get hasFinalReport() {
|
|
4496
|
+
return this.finished;
|
|
4497
|
+
}
|
|
3791
4498
|
get size() {
|
|
3792
4499
|
return this.pending.length;
|
|
3793
4500
|
}
|
|
3794
|
-
|
|
3795
|
-
|
|
3796
|
-
|
|
3797
|
-
|
|
3798
|
-
|
|
3799
|
-
|
|
4501
|
+
/** Queues lines read up to `cursor` (none, when reading only moved past what is not sent). */
|
|
4502
|
+
add(lines, cursor) {
|
|
4503
|
+
if (this.discarded) return;
|
|
4504
|
+
const moved = JSON.stringify(cursor) !== JSON.stringify(this.tail);
|
|
4505
|
+
if (!lines.length && !moved) return;
|
|
4506
|
+
this.tail = cursor;
|
|
4507
|
+
for (const line of lines) this.pending.push({ seq: this.nextSeq++, ...line });
|
|
4508
|
+
if (this.pending.length > RUNNER_JOB_LOG_LINES_KEPT) {
|
|
4509
|
+
this.pending = this.pending.slice(-RUNNER_JOB_LOG_LINES_KEPT);
|
|
4510
|
+
}
|
|
4511
|
+
this.persist();
|
|
4512
|
+
if (lines.length) this.schedulePump();
|
|
3800
4513
|
}
|
|
3801
|
-
|
|
3802
|
-
|
|
3803
|
-
|
|
3804
|
-
|
|
4514
|
+
/** Queues a status; one that ends the job is its last report. */
|
|
4515
|
+
report(report) {
|
|
4516
|
+
if (this.discarded || this.finished) return;
|
|
4517
|
+
if (report.status === "running" && this.status && this.status.report.status !== "running") {
|
|
4518
|
+
return;
|
|
3805
4519
|
}
|
|
4520
|
+
this.status = { report, afterSeq: this.nextSeq };
|
|
4521
|
+
if (report.status !== "running") this.finished = true;
|
|
3806
4522
|
this.persist();
|
|
3807
4523
|
this.schedulePump();
|
|
3808
4524
|
}
|
|
3809
|
-
/**
|
|
4525
|
+
/** The job ended with nothing to say about how (it was lost): only its lines are left. */
|
|
4526
|
+
endWithoutReport() {
|
|
4527
|
+
if (this.discarded || this.finished) return;
|
|
4528
|
+
this.finished = true;
|
|
4529
|
+
if (this.status?.report.status === "running") this.status = null;
|
|
4530
|
+
this.persist();
|
|
4531
|
+
this.checkFinished();
|
|
4532
|
+
}
|
|
4533
|
+
/** Resolves once everything queued is posted (true), or the time is up (false). */
|
|
3810
4534
|
async flush(timeoutMs) {
|
|
3811
|
-
if (this.stopped) return this.
|
|
4535
|
+
if (this.stopped || this.discarded) return this.isDrained();
|
|
4536
|
+
if (this.pumpTimer) {
|
|
4537
|
+
clearTimeout(this.pumpTimer);
|
|
4538
|
+
this.pumpTimer = null;
|
|
4539
|
+
}
|
|
4540
|
+
await this.persistChain;
|
|
4541
|
+
if (!this.isDrained()) void this.pump();
|
|
4542
|
+
const drained = this.isDrained() ? Promise.resolve(true) : new Promise((resolve4) => this.idleWaiters.push(() => resolve4(true)));
|
|
4543
|
+
const done = await Promise.race([drained, sleep(timeoutMs).then(() => false)]);
|
|
4544
|
+
await this.persistChain;
|
|
4545
|
+
return done || this.isDrained();
|
|
4546
|
+
}
|
|
4547
|
+
/** Stops posting (the runner is stopping); what is unsent stays on disk. */
|
|
4548
|
+
async stop() {
|
|
4549
|
+
this.stopped = true;
|
|
4550
|
+
if (this.persistRetry) clearTimeout(this.persistRetry);
|
|
4551
|
+
this.persistRetry = null;
|
|
4552
|
+
this.stopController.abort();
|
|
4553
|
+
if (this.pumpTimer) clearTimeout(this.pumpTimer);
|
|
4554
|
+
this.pumpTimer = null;
|
|
4555
|
+
this.persist(true);
|
|
4556
|
+
await this.persistChain;
|
|
4557
|
+
}
|
|
4558
|
+
/** Nothing more is posted (the server does not know the job); saved as finished. */
|
|
4559
|
+
async discard() {
|
|
4560
|
+
if (this.discarded) return;
|
|
4561
|
+
this.pending = [];
|
|
4562
|
+
this.status = null;
|
|
4563
|
+
this.finished = true;
|
|
4564
|
+
this.persist();
|
|
4565
|
+
this.discarded = true;
|
|
4566
|
+
if (this.persistRetry) clearTimeout(this.persistRetry);
|
|
4567
|
+
this.persistRetry = null;
|
|
4568
|
+
this.stopController.abort();
|
|
4569
|
+
if (this.pumpTimer) clearTimeout(this.pumpTimer);
|
|
4570
|
+
this.pumpTimer = null;
|
|
4571
|
+
this.notifyIdle();
|
|
4572
|
+
await this.persistChain;
|
|
4573
|
+
}
|
|
4574
|
+
/** Resolves once no write is under way. */
|
|
4575
|
+
settled() {
|
|
4576
|
+
return this.persistChain;
|
|
4577
|
+
}
|
|
4578
|
+
isDrained() {
|
|
4579
|
+
return this.discarded || this.pending.length === 0 && !this.status;
|
|
4580
|
+
}
|
|
4581
|
+
/** `final`: the stop's own last write; after it, nothing more is written. */
|
|
4582
|
+
persist(final = false) {
|
|
4583
|
+
if (this.persistQueued || this.discarded) return;
|
|
4584
|
+
if (this.stopped && !final) return;
|
|
4585
|
+
this.persistQueued = true;
|
|
4586
|
+
this.persistChain = this.persistChain.then(async () => {
|
|
4587
|
+
this.persistQueued = false;
|
|
4588
|
+
const snapshot = {
|
|
4589
|
+
nextSeq: this.nextSeq,
|
|
4590
|
+
pending: [...this.pending],
|
|
4591
|
+
status: this.status,
|
|
4592
|
+
cursor: this.tail,
|
|
4593
|
+
finished: this.finished
|
|
4594
|
+
};
|
|
4595
|
+
try {
|
|
4596
|
+
await writeJsonAtomic(this.opts.file, snapshot);
|
|
4597
|
+
this.durableSeq = snapshot.nextSeq - 1;
|
|
4598
|
+
this.durableStatus = snapshot.status;
|
|
4599
|
+
this.persistFailures = 0;
|
|
4600
|
+
} catch (err) {
|
|
4601
|
+
this.persistFailures++;
|
|
4602
|
+
if (this.persistFailures === 1 || this.persistFailures % 10 === 0) {
|
|
4603
|
+
this.opts.logger.warn("could not save a job\u2019s log outbox; trying again", {
|
|
4604
|
+
job: this.opts.jobId,
|
|
4605
|
+
error: err.message,
|
|
4606
|
+
attempt: this.persistFailures
|
|
4607
|
+
});
|
|
4608
|
+
}
|
|
4609
|
+
if (!this.persistRetry && !this.discarded && !this.stopped) {
|
|
4610
|
+
this.persistRetry = setTimeout(
|
|
4611
|
+
() => {
|
|
4612
|
+
this.persistRetry = null;
|
|
4613
|
+
if (!this.stopped) this.persist();
|
|
4614
|
+
},
|
|
4615
|
+
backoffDelay(this.persistFailures - 1, this.opts.retryBaseMs ?? 1e3, 6e4)
|
|
4616
|
+
);
|
|
4617
|
+
this.persistRetry.unref?.();
|
|
4618
|
+
}
|
|
4619
|
+
}
|
|
4620
|
+
if (!this.pumping) this.schedulePump();
|
|
4621
|
+
});
|
|
4622
|
+
}
|
|
4623
|
+
schedulePump() {
|
|
4624
|
+
if (this.pumping || this.pumpTimer || this.stopped || this.discarded) return;
|
|
4625
|
+
if (!this.pending.length && !this.status) return;
|
|
4626
|
+
this.pumpTimer = setTimeout(() => {
|
|
4627
|
+
this.pumpTimer = null;
|
|
4628
|
+
void this.pump();
|
|
4629
|
+
}, this.opts.batchDelayMs ?? 500);
|
|
4630
|
+
this.pumpTimer.unref?.();
|
|
4631
|
+
}
|
|
4632
|
+
/** The next post: durable lines (by count and size), and the status once it may go. */
|
|
4633
|
+
nextBatch() {
|
|
4634
|
+
const durable = this.pending.filter((l) => l.seq <= this.durableSeq);
|
|
4635
|
+
const budget = RUNNER_EVENTS_MAX_BODY_BYTES / 2;
|
|
4636
|
+
let bytes = 0;
|
|
4637
|
+
let n = 0;
|
|
4638
|
+
while (n < durable.length && n < RUNNER_JOB_LOG_MAX_BATCH) {
|
|
4639
|
+
const size = Buffer.byteLength(JSON.stringify(durable[n])) + 1;
|
|
4640
|
+
if (n > 0 && bytes + size > budget) break;
|
|
4641
|
+
bytes += size;
|
|
4642
|
+
n++;
|
|
4643
|
+
}
|
|
4644
|
+
const lines = durable.slice(0, n);
|
|
4645
|
+
const status2 = this.status && this.durableStatus === this.status ? this.status : null;
|
|
4646
|
+
const sentUpTo = lines.at(-1)?.seq ?? 0;
|
|
4647
|
+
const before = this.pending.filter((l) => status2 && l.seq < status2.afterSeq);
|
|
4648
|
+
const ready = status2 && (before.length === 0 || before.at(-1).seq <= sentUpTo);
|
|
4649
|
+
return { lines, status: ready ? status2 : null };
|
|
4650
|
+
}
|
|
4651
|
+
async pump() {
|
|
4652
|
+
if (this.pumping) return;
|
|
4653
|
+
this.pumping = true;
|
|
4654
|
+
let attempt = 0;
|
|
4655
|
+
let rejected = 0;
|
|
4656
|
+
try {
|
|
4657
|
+
while (!this.stopped && !this.discarded) {
|
|
4658
|
+
const { lines, status: status2 } = this.nextBatch();
|
|
4659
|
+
if (!lines.length && !status2) break;
|
|
4660
|
+
const maxSeq = lines.at(-1)?.seq ?? 0;
|
|
4661
|
+
const body = {
|
|
4662
|
+
...status2 ? { status: status2.report } : {},
|
|
4663
|
+
...lines.length ? {
|
|
4664
|
+
lines: lines.map(({ seq, stream, text, at }) => ({ seq, stream, text, at }))
|
|
4665
|
+
} : {}
|
|
4666
|
+
};
|
|
4667
|
+
try {
|
|
4668
|
+
const res = await this.opts.poster.postJobEvents(this.opts.jobId, body);
|
|
4669
|
+
if (this.stopped || this.discarded) break;
|
|
4670
|
+
const lastSeq = typeof res?.lastSeq === "number" ? Math.max(res.lastSeq, maxSeq) : maxSeq;
|
|
4671
|
+
this.pending = this.pending.filter((l) => l.seq > lastSeq);
|
|
4672
|
+
if (status2 && this.status === status2) this.status = null;
|
|
4673
|
+
this.persist();
|
|
4674
|
+
attempt = 0;
|
|
4675
|
+
rejected = 0;
|
|
4676
|
+
if (res?.stop) this.opts.onStop?.();
|
|
4677
|
+
} catch (err) {
|
|
4678
|
+
if (err instanceof UnauthorizedError) {
|
|
4679
|
+
this.stopped = true;
|
|
4680
|
+
this.opts.onUnauthorized?.(err);
|
|
4681
|
+
break;
|
|
4682
|
+
}
|
|
4683
|
+
if (err instanceof ApiError && (err.status === 404 || err.status === 410)) {
|
|
4684
|
+
this.opts.logger.warn(
|
|
4685
|
+
`job ${this.opts.jobId}: Discovery Tree does not know this job (${err.status}); no longer reporting on it`
|
|
4686
|
+
);
|
|
4687
|
+
await this.discard();
|
|
4688
|
+
this.opts.onGone?.();
|
|
4689
|
+
break;
|
|
4690
|
+
}
|
|
4691
|
+
const tooLarge = err instanceof ApiError && err.status === 413;
|
|
4692
|
+
if (tooLarge || !isRetryable(err)) {
|
|
4693
|
+
rejected++;
|
|
4694
|
+
this.opts.logger.warn("the server refused a job\u2019s log lines", {
|
|
4695
|
+
job: this.opts.jobId,
|
|
4696
|
+
error: err.message,
|
|
4697
|
+
attempt: rejected
|
|
4698
|
+
});
|
|
4699
|
+
if (tooLarge || rejected >= MAX_REJECTED_ATTEMPTS) {
|
|
4700
|
+
this.pending = this.pending.filter((l) => l.seq > maxSeq);
|
|
4701
|
+
if (status2 && this.status === status2) this.status = null;
|
|
4702
|
+
this.persist();
|
|
4703
|
+
rejected = 0;
|
|
4704
|
+
continue;
|
|
4705
|
+
}
|
|
4706
|
+
} else {
|
|
4707
|
+
this.opts.logger.debug("posting a job\u2019s log lines failed; will retry", {
|
|
4708
|
+
job: this.opts.jobId,
|
|
4709
|
+
error: err.message
|
|
4710
|
+
});
|
|
4711
|
+
}
|
|
4712
|
+
await sleep(
|
|
4713
|
+
backoffDelay(attempt++, this.opts.retryBaseMs ?? 1e3, 6e4),
|
|
4714
|
+
this.stopController.signal
|
|
4715
|
+
);
|
|
4716
|
+
}
|
|
4717
|
+
}
|
|
4718
|
+
} finally {
|
|
4719
|
+
this.pumping = false;
|
|
4720
|
+
}
|
|
4721
|
+
if (this.isDrained()) {
|
|
4722
|
+
this.notifyIdle();
|
|
4723
|
+
this.checkFinished();
|
|
4724
|
+
} else if (!this.stopped && !this.discarded) {
|
|
4725
|
+
this.schedulePump();
|
|
4726
|
+
}
|
|
4727
|
+
}
|
|
4728
|
+
checkFinished() {
|
|
4729
|
+
if (!this.isFinished || this.discarded || this.finishNotified) return;
|
|
4730
|
+
this.finishNotified = true;
|
|
4731
|
+
this.opts.onFinished?.();
|
|
4732
|
+
}
|
|
4733
|
+
notifyIdle() {
|
|
4734
|
+
const waiters = this.idleWaiters;
|
|
4735
|
+
this.idleWaiters = [];
|
|
4736
|
+
for (const w of waiters) w();
|
|
4737
|
+
}
|
|
4738
|
+
};
|
|
4739
|
+
|
|
4740
|
+
// src/jobs/job-process.ts
|
|
4741
|
+
import { execFile, spawn as spawn4 } from "node:child_process";
|
|
4742
|
+
import { closeSync, openSync, readFileSync, readdirSync } from "node:fs";
|
|
4743
|
+
import { readFile as readFile6, writeFile as writeFile4 } from "node:fs/promises";
|
|
4744
|
+
import { dirname as dirname5, join as join10 } from "node:path";
|
|
4745
|
+
|
|
4746
|
+
// src/lock.ts
|
|
4747
|
+
import { mkdir as mkdir5, open as open2, readFile as readFile5, rm as rm5 } from "node:fs/promises";
|
|
4748
|
+
import { join as join9 } from "node:path";
|
|
4749
|
+
function lockFile(stateDir) {
|
|
4750
|
+
return join9(stateDir, "daemon.pid");
|
|
4751
|
+
}
|
|
4752
|
+
function pidAlive(pid) {
|
|
4753
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
4754
|
+
try {
|
|
4755
|
+
process.kill(pid, 0);
|
|
4756
|
+
return true;
|
|
4757
|
+
} catch (err) {
|
|
4758
|
+
return err.code === "EPERM";
|
|
4759
|
+
}
|
|
4760
|
+
}
|
|
4761
|
+
async function lockHolder(stateDir) {
|
|
4762
|
+
let raw;
|
|
4763
|
+
try {
|
|
4764
|
+
raw = await readFile5(lockFile(stateDir), "utf8");
|
|
4765
|
+
} catch {
|
|
4766
|
+
return null;
|
|
4767
|
+
}
|
|
4768
|
+
const pid = Number.parseInt(raw.trim(), 10);
|
|
4769
|
+
return pidAlive(pid) && pid !== process.pid ? pid : null;
|
|
4770
|
+
}
|
|
4771
|
+
async function acquireDaemonLock(stateDir, pid = process.pid) {
|
|
4772
|
+
await mkdir5(stateDir, { recursive: true, mode: 448 });
|
|
4773
|
+
const file = lockFile(stateDir);
|
|
4774
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
4775
|
+
try {
|
|
4776
|
+
const handle = await open2(file, "wx", 384);
|
|
4777
|
+
try {
|
|
4778
|
+
await handle.writeFile(`${pid}
|
|
4779
|
+
`);
|
|
4780
|
+
} finally {
|
|
4781
|
+
await handle.close();
|
|
4782
|
+
}
|
|
4783
|
+
return {
|
|
4784
|
+
ok: true,
|
|
4785
|
+
lock: {
|
|
4786
|
+
file,
|
|
4787
|
+
async release() {
|
|
4788
|
+
const current2 = await readFile5(file, "utf8").catch(() => "");
|
|
4789
|
+
if (Number.parseInt(current2.trim(), 10) === pid) await rm5(file, { force: true });
|
|
4790
|
+
}
|
|
4791
|
+
}
|
|
4792
|
+
};
|
|
4793
|
+
} catch (err) {
|
|
4794
|
+
if (err.code !== "EEXIST") throw err;
|
|
4795
|
+
}
|
|
4796
|
+
const raw = await readFile5(file, "utf8").catch(() => null);
|
|
4797
|
+
if (raw === null) continue;
|
|
4798
|
+
const holder = Number.parseInt(raw.trim(), 10);
|
|
4799
|
+
if (pidAlive(holder) && holder !== pid) return { ok: false, pid: holder };
|
|
4800
|
+
await rm5(file, { force: true });
|
|
4801
|
+
}
|
|
4802
|
+
return { ok: false, pid: null };
|
|
4803
|
+
}
|
|
4804
|
+
|
|
4805
|
+
// src/jobs/job-process.ts
|
|
4806
|
+
var JOB_IS_WINDOWS = process.platform === "win32";
|
|
4807
|
+
var POWERSHELL_FLAGS = [
|
|
4808
|
+
"-NoLogo",
|
|
4809
|
+
"-NoProfile",
|
|
4810
|
+
"-NonInteractive",
|
|
4811
|
+
"-ExecutionPolicy",
|
|
4812
|
+
"Bypass",
|
|
4813
|
+
// Plain text on its redirected streams, never CLIXML records.
|
|
4814
|
+
"-OutputFormat",
|
|
4815
|
+
"Text"
|
|
4816
|
+
];
|
|
4817
|
+
function encoded(script) {
|
|
4818
|
+
return Buffer.from(script, "utf16le").toString("base64");
|
|
4819
|
+
}
|
|
4820
|
+
function psQuote(s) {
|
|
4821
|
+
return `'${s.replace(/'/g, "''")}'`;
|
|
4822
|
+
}
|
|
4823
|
+
function posixLaunch(command, exitFile) {
|
|
4824
|
+
return {
|
|
4825
|
+
bin: "/bin/sh",
|
|
4826
|
+
args: [
|
|
4827
|
+
"-c",
|
|
4828
|
+
'/bin/sh -c "$1"; code=$?; printf %s "$code" > "$2.tmp" && mv -f "$2.tmp" "$2"; exit "$code"',
|
|
4829
|
+
"dt-job",
|
|
4830
|
+
command,
|
|
4831
|
+
exitFile
|
|
4832
|
+
]
|
|
4833
|
+
};
|
|
4834
|
+
}
|
|
4835
|
+
function powershellCommandScript(command) {
|
|
4836
|
+
return [
|
|
4837
|
+
"$ErrorActionPreference = 'Continue'",
|
|
4838
|
+
// No progress records, which would land in the log as noise.
|
|
4839
|
+
"$ProgressPreference = 'SilentlyContinue'",
|
|
4840
|
+
// Its own output as UTF-8 (the runner reads the log as UTF-8), not the OEM code page.
|
|
4841
|
+
"try { [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false } catch {}",
|
|
4842
|
+
command,
|
|
4843
|
+
"$dtRunnerOk = $?",
|
|
4844
|
+
"$dtRunnerLast = $LASTEXITCODE",
|
|
4845
|
+
"if ($dtRunnerOk) { exit 0 } elseif ($dtRunnerLast) { exit $dtRunnerLast } else { exit 1 }"
|
|
4846
|
+
].join("\n");
|
|
4847
|
+
}
|
|
4848
|
+
function powershellJobScript(commandFile, exitFile) {
|
|
4849
|
+
return [
|
|
4850
|
+
"$ErrorActionPreference = 'Continue'",
|
|
4851
|
+
"$ProgressPreference = 'SilentlyContinue'",
|
|
4852
|
+
"try { [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false } catch {}",
|
|
4853
|
+
`& powershell.exe ${POWERSHELL_FLAGS.join(" ")} -File ${psQuote(commandFile)}`,
|
|
4854
|
+
"$dtRunnerCode = $LASTEXITCODE",
|
|
4855
|
+
"if ($null -eq $dtRunnerCode) { $dtRunnerCode = 1 }",
|
|
4856
|
+
`try { [IO.File]::WriteAllText(${psQuote(exitFile)}, [string]$dtRunnerCode) } catch {}`,
|
|
4857
|
+
"exit $dtRunnerCode"
|
|
4858
|
+
].join("\n");
|
|
4859
|
+
}
|
|
4860
|
+
function psLiteralPath(path) {
|
|
4861
|
+
return `([WildcardPattern]::Escape(${psQuote(path)}))`;
|
|
4862
|
+
}
|
|
4863
|
+
function windowsLauncherScript(input) {
|
|
4864
|
+
const args = [...POWERSHELL_FLAGS, "-File", `"${input.scriptFile}"`].join(" ");
|
|
4865
|
+
return [
|
|
4866
|
+
"$ErrorActionPreference = 'Stop'",
|
|
4867
|
+
"$ProgressPreference = 'SilentlyContinue'",
|
|
4868
|
+
// Started here: Start-Process takes the current location as the job's directory.
|
|
4869
|
+
`Set-Location -LiteralPath ${psQuote(input.cwd)}`,
|
|
4870
|
+
`$p = Start-Process -FilePath 'powershell.exe' -ArgumentList ${psQuote(args)} -NoNewWindow -PassThru -RedirectStandardOutput ${psLiteralPath(input.stdoutFile)} -RedirectStandardError ${psLiteralPath(input.stderrFile)}`,
|
|
4871
|
+
// A command that is over already has no start time to read: now is close enough.
|
|
4872
|
+
"$dtRunnerAt = $null",
|
|
4873
|
+
"try { $dtRunnerAt = ([DateTimeOffset]$p.StartTime).ToUnixTimeMilliseconds() } catch { $dtRunnerAt = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() }",
|
|
4874
|
+
'[Console]::Out.WriteLine("pid " + $p.Id + " " + $dtRunnerAt)'
|
|
4875
|
+
].join("\n");
|
|
4876
|
+
}
|
|
4877
|
+
async function spawnJob(input) {
|
|
4878
|
+
if (JOB_IS_WINDOWS) return spawnWindowsJob(input);
|
|
4879
|
+
const { bin, args } = posixLaunch(input.command, input.exitFile);
|
|
4880
|
+
const out = openSync(input.stdoutFile, "a", 384);
|
|
4881
|
+
let err = null;
|
|
4882
|
+
let child;
|
|
4883
|
+
try {
|
|
4884
|
+
err = openSync(input.stderrFile, "a", 384);
|
|
4885
|
+
child = spawn4(bin, args, {
|
|
4886
|
+
cwd: input.cwd,
|
|
4887
|
+
env: input.env,
|
|
4888
|
+
stdio: ["ignore", out, err],
|
|
4889
|
+
detached: true
|
|
4890
|
+
});
|
|
4891
|
+
} finally {
|
|
4892
|
+
closeSync(out);
|
|
4893
|
+
if (err !== null) closeSync(err);
|
|
4894
|
+
}
|
|
4895
|
+
child.unref();
|
|
4896
|
+
const exited = new Promise(
|
|
4897
|
+
(done) => child.once("exit", (code, signal) => done({ code, signal }))
|
|
4898
|
+
);
|
|
4899
|
+
await new Promise((up, failed) => {
|
|
4900
|
+
child.once("spawn", up);
|
|
4901
|
+
child.once("error", failed);
|
|
4902
|
+
});
|
|
4903
|
+
return { pid: child.pid, startedAt: Date.now() - 500, child, exited };
|
|
4904
|
+
}
|
|
4905
|
+
async function spawnWindowsJob(input) {
|
|
4906
|
+
const dir = dirname5(input.exitFile);
|
|
4907
|
+
const scriptFile = join10(dir, "job.ps1");
|
|
4908
|
+
const commandFile = join10(dir, "command.ps1");
|
|
4909
|
+
const bom = "\uFEFF";
|
|
4910
|
+
await writeFile4(commandFile, bom + powershellCommandScript(input.command), { mode: 384 });
|
|
4911
|
+
for (const f of [input.stdoutFile, input.stderrFile]) await writeFile4(f, "", { flag: "a" });
|
|
4912
|
+
await writeFile4(scriptFile, bom + powershellJobScript(commandFile, input.exitFile), {
|
|
4913
|
+
mode: 384
|
|
4914
|
+
});
|
|
4915
|
+
const launcher = spawn4(
|
|
4916
|
+
"powershell.exe",
|
|
4917
|
+
[
|
|
4918
|
+
...POWERSHELL_FLAGS,
|
|
4919
|
+
"-EncodedCommand",
|
|
4920
|
+
encoded(windowsLauncherScript({ ...input, scriptFile }))
|
|
4921
|
+
],
|
|
4922
|
+
// Piped (nothing inherited), so Node gives it a console without a window.
|
|
4923
|
+
{ cwd: input.cwd, env: input.env, stdio: ["ignore", "pipe", "pipe"], windowsHide: true }
|
|
4924
|
+
);
|
|
4925
|
+
let out = "";
|
|
4926
|
+
let err = "";
|
|
4927
|
+
try {
|
|
4928
|
+
const started = await new Promise((done, failed) => {
|
|
4929
|
+
let settled = false;
|
|
4930
|
+
const timers = [];
|
|
4931
|
+
const settle = (fn) => {
|
|
4932
|
+
if (settled) return;
|
|
4933
|
+
settled = true;
|
|
4934
|
+
for (const t of timers) clearTimeout(t);
|
|
4935
|
+
fn();
|
|
4936
|
+
};
|
|
4937
|
+
const look = () => {
|
|
4938
|
+
const m = /pid (\d+) (-?\d+)\r?\n/.exec(out);
|
|
4939
|
+
if (m) settle(() => done({ pid: Number(m[1]), startedAt: Number(m[2]) }));
|
|
4940
|
+
};
|
|
4941
|
+
launcher.stdout.setEncoding("utf8").on("data", (d) => {
|
|
4942
|
+
out += d;
|
|
4943
|
+
look();
|
|
4944
|
+
});
|
|
4945
|
+
launcher.stderr.setEncoding("utf8").on("data", (d) => err += d);
|
|
4946
|
+
launcher.once("error", (e) => settle(() => failed(e)));
|
|
4947
|
+
launcher.once("exit", (code) => {
|
|
4948
|
+
if (settled) return;
|
|
4949
|
+
timers.push(
|
|
4950
|
+
setTimeout(() => {
|
|
4951
|
+
look();
|
|
4952
|
+
const why = err.replace(/\s+/g, " ").trim().slice(0, 400) || `exit code ${code}`;
|
|
4953
|
+
settle(() => failed(new Error(`PowerShell could not start it: ${why}`)));
|
|
4954
|
+
}, 2e3)
|
|
4955
|
+
);
|
|
4956
|
+
});
|
|
4957
|
+
timers.push(
|
|
4958
|
+
setTimeout(() => {
|
|
4959
|
+
if (launcher.pid) void taskkill(launcher.pid, true);
|
|
4960
|
+
const up = /pid (\d+) /.exec(out);
|
|
4961
|
+
if (up) void taskkill(Number(up[1]), true);
|
|
4962
|
+
settle(() => failed(new Error("PowerShell did not start the job within 60 seconds.")));
|
|
4963
|
+
}, 6e4)
|
|
4964
|
+
);
|
|
4965
|
+
});
|
|
4966
|
+
return { ...started, child: null, exited: null };
|
|
4967
|
+
} finally {
|
|
4968
|
+
launcher.stdout.destroy();
|
|
4969
|
+
launcher.stderr.destroy();
|
|
4970
|
+
launcher.unref();
|
|
4971
|
+
}
|
|
4972
|
+
}
|
|
4973
|
+
async function processStamp(pid) {
|
|
4974
|
+
if (JOB_IS_WINDOWS) return null;
|
|
4975
|
+
try {
|
|
4976
|
+
const stat5 = await readFile6(`/proc/${pid}/stat`, "utf8");
|
|
4977
|
+
const fields = stat5.slice(stat5.lastIndexOf(")") + 2).split(" ");
|
|
4978
|
+
if (fields[19]) return `ticks:${fields[19]}`;
|
|
4979
|
+
} catch {
|
|
4980
|
+
}
|
|
4981
|
+
return new Promise((resolve4) => {
|
|
4982
|
+
const env = { ...process.env, LC_ALL: "C", LANG: "C", TZ: "UTC" };
|
|
4983
|
+
execFile("ps", ["-o", "lstart=", "-p", String(pid)], { timeout: 5e3, env }, (e, stdout) => {
|
|
4984
|
+
const text = e ? "" : String(stdout).trim();
|
|
4985
|
+
resolve4(text ? `lstartutc:${text}` : null);
|
|
4986
|
+
});
|
|
4987
|
+
});
|
|
4988
|
+
}
|
|
4989
|
+
async function isJobProcess(pid, startedAt, rows, stamp) {
|
|
4990
|
+
if (!pidAlive(pid)) return false;
|
|
4991
|
+
if (JOB_IS_WINDOWS) {
|
|
4992
|
+
const table = rows ?? await listWindowsProcesses().catch(() => null);
|
|
4993
|
+
if (!table) return true;
|
|
4994
|
+
const row = table.find((r) => r.pid === pid);
|
|
4995
|
+
return !!row && Math.abs(row.createdAt - startedAt) <= START_TOLERANCE_MS;
|
|
4996
|
+
}
|
|
4997
|
+
if (await isZombie(pid)) return false;
|
|
4998
|
+
if (!groupAlive(pid)) return false;
|
|
4999
|
+
if (stamp && (stamp.startsWith("ticks:") || stamp.startsWith("lstartutc:"))) {
|
|
5000
|
+
const now = await processStamp(pid);
|
|
5001
|
+
if (now) return now === stamp;
|
|
5002
|
+
}
|
|
5003
|
+
const started = await posixStartTime(pid);
|
|
5004
|
+
return started === null || Math.abs(started - startedAt) <= START_TOLERANCE_MS;
|
|
5005
|
+
}
|
|
5006
|
+
var START_TOLERANCE_MS = 5e3;
|
|
5007
|
+
function posixStartTime(pid) {
|
|
5008
|
+
return new Promise((resolve4) => {
|
|
5009
|
+
execFile("ps", ["-o", "etime=", "-p", String(pid)], { timeout: 5e3 }, (err, stdout) => {
|
|
5010
|
+
const secs = err ? null : parseElapsed(String(stdout));
|
|
5011
|
+
resolve4(secs === null ? null : Date.now() - secs * 1e3);
|
|
5012
|
+
});
|
|
5013
|
+
});
|
|
5014
|
+
}
|
|
5015
|
+
function parseElapsed(text) {
|
|
5016
|
+
const m = /^\s*(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)\s*$/.exec(text);
|
|
5017
|
+
if (!m) return null;
|
|
5018
|
+
const [, d, h, min, s] = m;
|
|
5019
|
+
return ((Number(d ?? 0) * 24 + Number(h ?? 0)) * 60 + Number(min)) * 60 + Number(s);
|
|
5020
|
+
}
|
|
5021
|
+
function procStat(pid) {
|
|
5022
|
+
try {
|
|
5023
|
+
const stat5 = readFileSync(`/proc/${pid}/stat`, "utf8");
|
|
5024
|
+
return stat5.slice(stat5.lastIndexOf(")") + 2).split(" ");
|
|
5025
|
+
} catch {
|
|
5026
|
+
return null;
|
|
5027
|
+
}
|
|
5028
|
+
}
|
|
5029
|
+
async function isZombie(pid) {
|
|
5030
|
+
if (JOB_IS_WINDOWS) return false;
|
|
5031
|
+
const fields = procStat(pid);
|
|
5032
|
+
if (fields) return fields[0] === "Z";
|
|
5033
|
+
if (process.platform === "linux") return false;
|
|
5034
|
+
return new Promise((resolve4) => {
|
|
5035
|
+
execFile(
|
|
5036
|
+
"ps",
|
|
5037
|
+
["-o", "stat=", "-p", String(pid)],
|
|
5038
|
+
{ timeout: 5e3 },
|
|
5039
|
+
(e, out) => resolve4(!e && String(out).trim().startsWith("Z"))
|
|
5040
|
+
);
|
|
5041
|
+
});
|
|
5042
|
+
}
|
|
5043
|
+
function processRunning(pid) {
|
|
5044
|
+
if (!pidAlive(pid)) return false;
|
|
5045
|
+
return procStat(pid)?.[0] !== "Z";
|
|
5046
|
+
}
|
|
5047
|
+
function groupHasLiveMember(pgid) {
|
|
5048
|
+
if (!groupAlive(pgid)) return false;
|
|
5049
|
+
if (process.platform !== "linux") return true;
|
|
5050
|
+
let entries;
|
|
5051
|
+
try {
|
|
5052
|
+
entries = readdirSync("/proc");
|
|
5053
|
+
} catch {
|
|
5054
|
+
return true;
|
|
5055
|
+
}
|
|
5056
|
+
for (const entry of entries) {
|
|
5057
|
+
if (!/^\d+$/.test(entry)) continue;
|
|
5058
|
+
const fields = procStat(Number(entry));
|
|
5059
|
+
if (fields && fields[2] === String(pgid) && fields[0] !== "Z") return true;
|
|
5060
|
+
}
|
|
5061
|
+
return false;
|
|
5062
|
+
}
|
|
5063
|
+
function groupAlive(pgid) {
|
|
5064
|
+
return signalGroup2(pgid, 0);
|
|
5065
|
+
}
|
|
5066
|
+
function signalGroup2(pgid, signal) {
|
|
5067
|
+
if (!Number.isInteger(pgid) || pgid <= 1) return false;
|
|
5068
|
+
try {
|
|
5069
|
+
process.kill(-pgid, signal);
|
|
5070
|
+
return true;
|
|
5071
|
+
} catch {
|
|
5072
|
+
return false;
|
|
5073
|
+
}
|
|
5074
|
+
}
|
|
5075
|
+
function taskkill(pid, force) {
|
|
5076
|
+
return new Promise((resolve4) => {
|
|
5077
|
+
const tk = spawn4("taskkill", ["/pid", String(pid), "/T", ...force ? ["/F"] : []], {
|
|
5078
|
+
stdio: "ignore",
|
|
5079
|
+
windowsHide: true
|
|
5080
|
+
});
|
|
5081
|
+
tk.on("error", () => resolve4());
|
|
5082
|
+
tk.on("close", () => resolve4());
|
|
5083
|
+
});
|
|
5084
|
+
}
|
|
5085
|
+
async function censusJobs(trees) {
|
|
5086
|
+
if (!JOB_IS_WINDOWS || trees.length === 0) return;
|
|
5087
|
+
try {
|
|
5088
|
+
const rows = await listWindowsProcesses();
|
|
5089
|
+
for (const tree of trees) recordDescendants(tree, rows);
|
|
5090
|
+
} catch {
|
|
5091
|
+
}
|
|
5092
|
+
}
|
|
5093
|
+
async function askJobToStop(tree) {
|
|
5094
|
+
if (!JOB_IS_WINDOWS) {
|
|
5095
|
+
signalGroup2(tree.pid, "SIGTERM");
|
|
5096
|
+
return;
|
|
5097
|
+
}
|
|
5098
|
+
await censusJobs([tree]);
|
|
5099
|
+
await taskkill(tree.pid, false);
|
|
5100
|
+
}
|
|
5101
|
+
async function killJobTree(tree, rootRunning) {
|
|
5102
|
+
try {
|
|
5103
|
+
if (!JOB_IS_WINDOWS) {
|
|
5104
|
+
signalGroup2(tree.pid, "SIGKILL");
|
|
5105
|
+
return;
|
|
5106
|
+
}
|
|
5107
|
+
const rows = await listWindowsProcesses().catch(() => null);
|
|
5108
|
+
const pids = [...rootRunning ? [tree.pid] : [], ...rows ? descendantsOf(tree, rows) : []];
|
|
5109
|
+
if (pids.length) await killWindowsTrees(pids);
|
|
5110
|
+
} catch {
|
|
5111
|
+
}
|
|
5112
|
+
}
|
|
5113
|
+
|
|
5114
|
+
// src/jobs/job-manager.ts
|
|
5115
|
+
var JOB_STOP_GRACE_MS = 1e4;
|
|
5116
|
+
var LEFTOVER_GRACE_MS = 2e3;
|
|
5117
|
+
var CENSUS_INTERVAL_MS2 = 3e4;
|
|
5118
|
+
var JOB_SECRETS_WAIT_MS = 9e4;
|
|
5119
|
+
var JOB_SECRETS_END_WAIT_MS = 12e4;
|
|
5120
|
+
var JOB_LOST_POSTING_MS = RUNNER_JOB_MISSING_GRACE_MS + 3e4;
|
|
5121
|
+
function secretWait() {
|
|
5122
|
+
let end = () => void 0;
|
|
5123
|
+
const over = new Promise((resolve4) => end = resolve4);
|
|
5124
|
+
return { since: Date.now(), over, end };
|
|
5125
|
+
}
|
|
5126
|
+
var JobManager = class {
|
|
5127
|
+
constructor(opts) {
|
|
5128
|
+
this.opts = opts;
|
|
5129
|
+
this.root = join11(opts.stateDir, "jobs");
|
|
5130
|
+
}
|
|
5131
|
+
jobs = /* @__PURE__ */ new Map();
|
|
5132
|
+
/** Folders being removed now, with how many removals hold each (see `holdForRemoval`). */
|
|
5133
|
+
removing = /* @__PURE__ */ new Map();
|
|
5134
|
+
/** Ends being handled (`finish`), which a shutdown waits for. */
|
|
5135
|
+
finishing = /* @__PURE__ */ new Set();
|
|
5136
|
+
/** Starts under way, with their directories: a slot each, from the capacity check on. */
|
|
5137
|
+
starting = /* @__PURE__ */ new Map();
|
|
5138
|
+
/** The tail of each job's command queue; never rejects. */
|
|
5139
|
+
queues = /* @__PURE__ */ new Map();
|
|
5140
|
+
timer = null;
|
|
5141
|
+
censusTimer = null;
|
|
5142
|
+
ticking = false;
|
|
5143
|
+
shuttingDown = false;
|
|
5144
|
+
/** Resolves when the runner begins to stop: an end waiting for secrets waits no more. */
|
|
5145
|
+
stopped = secretWait();
|
|
5146
|
+
root;
|
|
5147
|
+
/** The folder a job's record, log and outbox live in. */
|
|
5148
|
+
jobDir(jobId) {
|
|
5149
|
+
return join11(this.root, jobId);
|
|
5150
|
+
}
|
|
5151
|
+
/**
|
|
5152
|
+
* Jobs the runner reports in `activeJobIds`: a live process, or an end not yet reported.
|
|
5153
|
+
* Not a start still under way: the server takes a listed job as up, settling its
|
|
5154
|
+
* `start_job` as acknowledged, so a start that then fails would show as running (then lost)
|
|
5155
|
+
* and its refusal, with the reason, would be dropped. Left out, it loses nothing: the
|
|
5156
|
+
* server marks only a `running` job lost for being missing, and a start is `starting` until
|
|
5157
|
+
* its ack says how it went.
|
|
5158
|
+
*/
|
|
5159
|
+
activeJobIds() {
|
|
5160
|
+
const ids = /* @__PURE__ */ new Set();
|
|
5161
|
+
for (const [id, job] of this.jobs) {
|
|
5162
|
+
if (job.phase !== "ended") ids.add(id);
|
|
5163
|
+
else if ((job.record.ended?.status !== "lost" || job.awaiting || job.closing || this.postingLost(job)) && !job.outbox.isFinished) {
|
|
5164
|
+
ids.add(id);
|
|
5165
|
+
}
|
|
5166
|
+
}
|
|
5167
|
+
return [...ids];
|
|
5168
|
+
}
|
|
5169
|
+
/**
|
|
5170
|
+
* Jobs taken up again whose output is held for want of their secrets, which a `job_secrets`
|
|
5171
|
+
* can bring back (the heartbeat's `jobsNeedingSecrets`). Not one whose secrets cannot be
|
|
5172
|
+
* checked (`unverifiable`), or that changed since its start. One that ended is listed while
|
|
5173
|
+
* its last output waits for them.
|
|
5174
|
+
*/
|
|
5175
|
+
jobsNeedingSecrets() {
|
|
5176
|
+
return [...this.jobs.entries()].filter(([, job]) => job.awaiting).map(([id]) => id);
|
|
5177
|
+
}
|
|
5178
|
+
/**
|
|
5179
|
+
* A lost job still has lines to post, for {@link JOB_LOST_POSTING_MS} after this process
|
|
5180
|
+
* queued its end (or took it up with its end queued): not for good, as an outbox that
|
|
5181
|
+
* cannot post, or cannot save, would keep a job with no process running on the server.
|
|
5182
|
+
*/
|
|
5183
|
+
postingLost(job) {
|
|
5184
|
+
return job.outbox.size > 0 && job.lastQueuedAt !== void 0 && performance.now() - job.lastQueuedAt < (this.opts.lostPostingMs ?? JOB_LOST_POSTING_MS);
|
|
5185
|
+
}
|
|
5186
|
+
/** Jobs with a process (or one starting), counted against `maxJobs`. */
|
|
5187
|
+
liveCount() {
|
|
5188
|
+
let n = this.starting.size;
|
|
5189
|
+
for (const job of this.jobs.values()) if (job.phase !== "ended") n++;
|
|
5190
|
+
return n;
|
|
5191
|
+
}
|
|
5192
|
+
/** For status and tests. */
|
|
5193
|
+
get(jobId) {
|
|
5194
|
+
return this.jobs.get(jobId.toLowerCase())?.record;
|
|
5195
|
+
}
|
|
5196
|
+
/** The pid of a job's process, while it has one. */
|
|
5197
|
+
pidOf(jobId) {
|
|
5198
|
+
const job = this.jobs.get(jobId.toLowerCase());
|
|
5199
|
+
return job && job.phase !== "ended" ? job.record.pid : null;
|
|
5200
|
+
}
|
|
5201
|
+
/**
|
|
5202
|
+
* Whether a running (or starting) job works in `dir` or a folder inside it: a session's
|
|
5203
|
+
* worktree such a job runs in must not be removed under it.
|
|
5204
|
+
*/
|
|
5205
|
+
usesPath(dir) {
|
|
5206
|
+
if (!dir) return false;
|
|
5207
|
+
const cwds = [...this.starting.values()];
|
|
5208
|
+
for (const job of this.jobs.values()) if (job.phase !== "ended") cwds.push(job.record.cwd);
|
|
5209
|
+
return cwds.some((cwd) => isInside(cwd, dir));
|
|
5210
|
+
}
|
|
5211
|
+
/**
|
|
5212
|
+
* Claims `dir` for removal, unless a job runs (or is starting) in it: null then, and it must
|
|
5213
|
+
* be kept. While claimed, a start in it is refused as `retryable`. Checked and claimed in one
|
|
5214
|
+
* step (no await), as a start checks and takes its slot, so a job never starts in a folder
|
|
5215
|
+
* being removed, nor is a folder removed under a job that has just started. Call the
|
|
5216
|
+
* returned function once the removal is over.
|
|
5217
|
+
*/
|
|
5218
|
+
holdForRemoval(dir) {
|
|
5219
|
+
if (!dir || this.usesPath(dir)) return null;
|
|
5220
|
+
const key = resolve2(dir);
|
|
5221
|
+
this.removing.set(key, (this.removing.get(key) ?? 0) + 1);
|
|
5222
|
+
let released = false;
|
|
5223
|
+
return () => {
|
|
5224
|
+
if (released) return;
|
|
5225
|
+
released = true;
|
|
5226
|
+
const left = (this.removing.get(key) ?? 1) - 1;
|
|
5227
|
+
if (left > 0) this.removing.set(key, left);
|
|
5228
|
+
else this.removing.delete(key);
|
|
5229
|
+
};
|
|
5230
|
+
}
|
|
5231
|
+
/**
|
|
5232
|
+
* Takes up the jobs a previous run of the runner left: those still running are watched
|
|
5233
|
+
* again, the others reported as they ended. Starts reading output.
|
|
5234
|
+
*/
|
|
5235
|
+
async restore() {
|
|
5236
|
+
let entries = [];
|
|
5237
|
+
try {
|
|
5238
|
+
entries = await readdir2(this.root);
|
|
5239
|
+
} catch (err) {
|
|
5240
|
+
if (err.code !== "ENOENT") throw err;
|
|
5241
|
+
}
|
|
5242
|
+
let table = null;
|
|
5243
|
+
for (const entry of entries) {
|
|
5244
|
+
if (!isRunnerSessionId(entry)) continue;
|
|
5245
|
+
const record = await readJson(join11(this.jobDir(entry), "job.json")).catch(
|
|
5246
|
+
() => null
|
|
5247
|
+
);
|
|
5248
|
+
if (!record || record.jobId !== entry || record.settled) continue;
|
|
5249
|
+
if (JOB_IS_WINDOWS && table === null && !record.ended && record.pid) {
|
|
5250
|
+
table = await listWindowsProcesses().catch(() => null);
|
|
5251
|
+
}
|
|
5252
|
+
try {
|
|
5253
|
+
await this.restoreJob(record, table);
|
|
5254
|
+
} catch (err) {
|
|
5255
|
+
this.opts.logger.warn(`job ${entry}: could not be taken up again`, {
|
|
5256
|
+
error: err.message
|
|
5257
|
+
});
|
|
5258
|
+
}
|
|
5259
|
+
}
|
|
5260
|
+
this.ensureTimers();
|
|
5261
|
+
}
|
|
5262
|
+
async restoreJob(record, table) {
|
|
5263
|
+
const job = await this.openJob(record, null, null);
|
|
5264
|
+
if (record.ended) {
|
|
5265
|
+
job.phase = "ended";
|
|
5266
|
+
this.jobs.set(record.jobId, job);
|
|
5267
|
+
if (job.outbox.hasFinalReport) {
|
|
5268
|
+
job.lastQueuedAt = performance.now();
|
|
5269
|
+
if (job.awaiting) await this.giveUpSecrets(job, null);
|
|
5270
|
+
if (job.outbox.isFinished) await this.settle(job);
|
|
5271
|
+
return;
|
|
5272
|
+
}
|
|
5273
|
+
const ended = record.ended;
|
|
5274
|
+
const close = async () => {
|
|
5275
|
+
job.closing = true;
|
|
5276
|
+
try {
|
|
5277
|
+
await closeEnd();
|
|
5278
|
+
} finally {
|
|
5279
|
+
job.closing = false;
|
|
5280
|
+
}
|
|
5281
|
+
};
|
|
5282
|
+
const closeEnd = async () => {
|
|
5283
|
+
if (job.awaiting) {
|
|
5284
|
+
await this.waitForSecrets(job);
|
|
5285
|
+
if (this.shuttingDown || this.jobs.get(job.record.jobId) !== job) return;
|
|
5286
|
+
if (job.awaiting) await this.giveUpSecrets(job, "gave_up");
|
|
5287
|
+
}
|
|
5288
|
+
await this.read(job, true);
|
|
5289
|
+
for (const r of job.readers) await r.close();
|
|
5290
|
+
queueEndReport(job.outbox, ended);
|
|
5291
|
+
job.lastQueuedAt = performance.now();
|
|
5292
|
+
if (job.outbox.isFinished) await this.settle(job);
|
|
5293
|
+
};
|
|
5294
|
+
if (!job.awaiting) return close();
|
|
5295
|
+
this.track(close(), record.jobId);
|
|
5296
|
+
return;
|
|
5297
|
+
}
|
|
5298
|
+
const alive = record.pid !== null && record.startedAt !== null && await isJobProcess(record.pid, record.startedAt, table, record.processStamp);
|
|
5299
|
+
this.jobs.set(record.jobId, job);
|
|
5300
|
+
if (job.withhold && (record.withheldNotice === "changed" || record.withheldNotice === "gave_up")) {
|
|
5301
|
+
this.opts.logger.warn(
|
|
5302
|
+
`job ${record.jobId}: its output stays withheld (${record.withheldNotice === "changed" ? "a secret changed since it started" : "its secrets were given up on"}); the whole log is in ${job.dir}`
|
|
5303
|
+
);
|
|
5304
|
+
} else if (job.withhold) {
|
|
5305
|
+
this.opts.logger.warn(
|
|
5306
|
+
`job ${record.jobId}: its output is no longer sent to Discovery Tree (the runner restarted, and the runner that started it kept nothing to check its secrets against); the whole log is in ${job.dir}`
|
|
5307
|
+
);
|
|
5308
|
+
await this.noticeWithheld(job, "unverifiable");
|
|
5309
|
+
} else if (job.awaiting) {
|
|
5310
|
+
this.opts.logger.info(
|
|
5311
|
+
`job ${record.jobId}: its output waits for its secrets to come back from Discovery Tree, to be redacted`
|
|
5312
|
+
);
|
|
5313
|
+
}
|
|
5314
|
+
if (!alive) {
|
|
5315
|
+
this.opts.logger.info(`job ${record.jobId}: ended while the runner was not running`);
|
|
5316
|
+
const ended = this.finish(job, await readExitFile(job.dir));
|
|
5317
|
+
if (!job.awaiting) await ended;
|
|
5318
|
+
else this.track(ended, record.jobId);
|
|
5319
|
+
return;
|
|
5320
|
+
}
|
|
5321
|
+
this.opts.logger.info(`job ${record.jobId}: taken up again (pid ${record.pid})`, {
|
|
5322
|
+
name: record.name
|
|
5323
|
+
});
|
|
5324
|
+
if (record.stopRequestedAt) {
|
|
5325
|
+
job.phase = "stopping";
|
|
5326
|
+
if (!record.stopSignalledAt && job.tree) {
|
|
5327
|
+
await askJobToStop(job.tree).catch(() => void 0);
|
|
5328
|
+
record.stopSignalledAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
5329
|
+
await saveRecord(job.dir, record).catch(() => void 0);
|
|
5330
|
+
}
|
|
5331
|
+
const asked = Date.parse(record.stopRequestedAt);
|
|
5332
|
+
const left = (this.opts.stopGraceMs ?? JOB_STOP_GRACE_MS) - (Date.now() - asked);
|
|
5333
|
+
job.killTimer = setTimeout(() => void this.forceKill(job), Math.max(0, left || 0));
|
|
5334
|
+
job.killTimer.unref?.();
|
|
5335
|
+
}
|
|
5336
|
+
}
|
|
5337
|
+
/** One job command, after the earlier ones for the same job. */
|
|
5338
|
+
handle(cmd) {
|
|
5339
|
+
const id = typeof cmd.jobId === "string" ? cmd.jobId.toLowerCase() : "";
|
|
5340
|
+
if (!isRunnerSessionId(id)) {
|
|
5341
|
+
return Promise.resolve({ ok: false, error: "The job id is malformed." });
|
|
5342
|
+
}
|
|
5343
|
+
const work = async () => {
|
|
5344
|
+
switch (cmd.type) {
|
|
5345
|
+
case "start_job":
|
|
5346
|
+
return this.start(id, cmd);
|
|
5347
|
+
case "stop_job":
|
|
5348
|
+
return this.stopCommand(id);
|
|
5349
|
+
case "job_secrets":
|
|
5350
|
+
return this.applySecrets(id, cmd);
|
|
5351
|
+
default:
|
|
5352
|
+
return {
|
|
5353
|
+
ok: false,
|
|
5354
|
+
error: `This runner does not know the job command "${cmd.type}". Update dt-runner.`
|
|
5355
|
+
};
|
|
5356
|
+
}
|
|
5357
|
+
};
|
|
5358
|
+
const previous = this.queues.get(id) ?? Promise.resolve();
|
|
5359
|
+
const result = previous.then(work, work);
|
|
5360
|
+
const tail = result.then(
|
|
5361
|
+
() => void 0,
|
|
5362
|
+
() => void 0
|
|
5363
|
+
);
|
|
5364
|
+
this.queues.set(id, tail);
|
|
5365
|
+
void tail.then(() => {
|
|
5366
|
+
if (this.queues.get(id) === tail) this.queues.delete(id);
|
|
5367
|
+
});
|
|
5368
|
+
return result;
|
|
5369
|
+
}
|
|
5370
|
+
/** The heartbeat's `stopJobIds`: stop each of them this runner still runs. */
|
|
5371
|
+
stopJobs(ids) {
|
|
5372
|
+
for (const raw of ids) {
|
|
5373
|
+
const job = this.jobs.get(String(raw).toLowerCase());
|
|
5374
|
+
if (job && job.phase === "running") {
|
|
5375
|
+
this.opts.logger.info(`job ${job.record.jobId}: Discovery Tree says to stop it`);
|
|
5376
|
+
void this.stop(job);
|
|
5377
|
+
}
|
|
5378
|
+
}
|
|
5379
|
+
}
|
|
5380
|
+
/**
|
|
5381
|
+
* The runner is stopping: the jobs keep running (they are taken up again when it starts),
|
|
5382
|
+
* what they wrote is read and given `flushMs` to post, and the rest stays on disk.
|
|
5383
|
+
*/
|
|
5384
|
+
async shutdown(flushMs = 5e3) {
|
|
5385
|
+
this.shuttingDown = true;
|
|
5386
|
+
this.stopped.end();
|
|
5387
|
+
if (this.timer) clearInterval(this.timer);
|
|
5388
|
+
if (this.censusTimer) clearInterval(this.censusTimer);
|
|
5389
|
+
this.timer = this.censusTimer = null;
|
|
5390
|
+
await Promise.allSettled([...this.queues.values()]);
|
|
5391
|
+
await Promise.allSettled([...this.finishing]);
|
|
5392
|
+
const jobs = [...this.jobs.values()];
|
|
5393
|
+
await Promise.allSettled(jobs.map((job) => this.read(job, false)));
|
|
5394
|
+
await Promise.allSettled(jobs.map((job) => job.outbox.flush(flushMs)));
|
|
5395
|
+
for (const job of jobs) {
|
|
5396
|
+
if (job.killTimer) clearTimeout(job.killTimer);
|
|
5397
|
+
job.killTimer = null;
|
|
5398
|
+
await job.outbox.stop();
|
|
5399
|
+
for (const r of job.readers) await r.close();
|
|
5400
|
+
}
|
|
5401
|
+
const running = jobs.filter((j) => j.phase === "running" || j.phase === "stopping").length;
|
|
5402
|
+
if (running) {
|
|
5403
|
+
this.opts.logger.info(
|
|
5404
|
+
`${running} job(s) keep running; dt-runner takes them up again when it starts`
|
|
5405
|
+
);
|
|
5406
|
+
}
|
|
5407
|
+
}
|
|
5408
|
+
/* -------------------------------------------------------------------------------- */
|
|
5409
|
+
async start(id, cmd) {
|
|
5410
|
+
if (this.jobs.has(id)) return { ok: true };
|
|
5411
|
+
const earlier = await readJson(join11(this.jobDir(id), "job.json")).catch(() => null);
|
|
5412
|
+
if (earlier) {
|
|
5413
|
+
return earlier.pid === null || earlier.ended?.status === "failed" ? { ok: false, error: "The job could not be started on this runner." } : { ok: true };
|
|
5414
|
+
}
|
|
5415
|
+
if (this.shuttingDown) {
|
|
5416
|
+
return { ok: false, retryable: true, error: "The runner is shutting down." };
|
|
5417
|
+
}
|
|
5418
|
+
const command = typeof cmd.command === "string" ? cmd.command : "";
|
|
5419
|
+
if (!command.trim() || command.includes("\0")) {
|
|
5420
|
+
return { ok: false, error: "The job has no command to run." };
|
|
5421
|
+
}
|
|
5422
|
+
const cwd = typeof cmd.cwd === "string" ? cmd.cwd : "";
|
|
5423
|
+
const cwdProblem = treeJobCwdProblem(cwd) ?? (isAbsolute4(cwd) ? null : "must be an absolute path");
|
|
5424
|
+
if (cwdProblem) return { ok: false, error: `The job's directory ${cwdProblem}.` };
|
|
5425
|
+
const isDir2 = await stat4(cwd).then(
|
|
5426
|
+
(s) => s.isDirectory(),
|
|
5427
|
+
() => false
|
|
5428
|
+
);
|
|
5429
|
+
if (!isDir2) {
|
|
5430
|
+
return { ok: false, error: `The directory ${cwd} does not exist on this computer.` };
|
|
5431
|
+
}
|
|
5432
|
+
if ([...this.removing.keys()].some((dir) => isInside(cwd, dir))) {
|
|
5433
|
+
return {
|
|
5434
|
+
ok: false,
|
|
5435
|
+
retryable: true,
|
|
5436
|
+
error: `The runner is removing or replacing the directory ${cwd} (a session's working copy) right now.`
|
|
5437
|
+
};
|
|
5438
|
+
}
|
|
5439
|
+
const max = this.opts.maxJobs;
|
|
5440
|
+
if (this.liveCount() >= max) {
|
|
5441
|
+
return {
|
|
5442
|
+
ok: false,
|
|
5443
|
+
retryable: true,
|
|
5444
|
+
error: `The runner is busy: it is already running ${max} job(s).`
|
|
5445
|
+
};
|
|
5446
|
+
}
|
|
5447
|
+
this.starting.set(id, cwd);
|
|
5448
|
+
try {
|
|
5449
|
+
await this.opts.beforeLaunch?.(id);
|
|
5450
|
+
return await this.launch(id, cmd, command, cwd);
|
|
5451
|
+
} finally {
|
|
5452
|
+
this.starting.delete(id);
|
|
5453
|
+
}
|
|
5454
|
+
}
|
|
5455
|
+
async launch(id, cmd, command, cwd) {
|
|
5456
|
+
const name = typeof cmd.name === "string" && cmd.name.trim() ? cmd.name.slice(0, 100) : id;
|
|
5457
|
+
const environment = sessionEnvironment(cmd.environment);
|
|
5458
|
+
const redactor = environment ? jobLineRedactor(environment) : null;
|
|
5459
|
+
const dir = this.jobDir(id);
|
|
5460
|
+
await mkdir6(dir, { recursive: true, mode: 448 });
|
|
5461
|
+
const record = {
|
|
5462
|
+
jobId: id,
|
|
5463
|
+
name,
|
|
5464
|
+
command,
|
|
5465
|
+
cwd,
|
|
5466
|
+
pid: null,
|
|
5467
|
+
startedAt: null,
|
|
5468
|
+
...environment?.names.length ? { environmentNames: environment.names } : {},
|
|
5469
|
+
...environment?.secretNames.length ? { secretNames: environment.secretNames } : {},
|
|
5470
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
5471
|
+
};
|
|
5472
|
+
if (environment?.secretNames.length) {
|
|
5473
|
+
try {
|
|
5474
|
+
record.secretCheck = await secretCheckOf(environment);
|
|
5475
|
+
} catch (err) {
|
|
5476
|
+
this.opts.logger.warn(
|
|
5477
|
+
`job ${id}: could not fingerprint its secrets; its output is not posted after a restart`,
|
|
5478
|
+
{ error: safeError(err, redactor) }
|
|
5479
|
+
);
|
|
5480
|
+
}
|
|
5481
|
+
}
|
|
5482
|
+
await saveRecord(dir, record);
|
|
5483
|
+
this.opts.logger.info(`job ${id}: starting "${name}"`, { cwd });
|
|
5484
|
+
const shortLines = environment ? secretsWithShortLines(environment) : [];
|
|
5485
|
+
if (environment?.unredacted.length || shortLines.length) {
|
|
5486
|
+
this.opts.logger.warn(
|
|
5487
|
+
`job ${id}: ${[...environment?.unredacted ?? [], ...shortLines].join(", ")} cannot be fully redacted from its log (values or lines under ${SECRET_REDACTION_MIN_LENGTH} characters)`
|
|
5488
|
+
);
|
|
5489
|
+
}
|
|
5490
|
+
if (environment?.skipped.length) {
|
|
5491
|
+
this.opts.logger.warn(
|
|
5492
|
+
`job ${id}: left out of the job's environment (not a name it may set): ${environment.skipped.slice(0, 20).join(", ")}`
|
|
5493
|
+
);
|
|
5494
|
+
}
|
|
5495
|
+
const env = { ...process.env, ...environment?.env };
|
|
5496
|
+
delete env.DT_RUNNER_TOKEN;
|
|
5497
|
+
let started;
|
|
5498
|
+
try {
|
|
5499
|
+
started = await spawnJob({
|
|
5500
|
+
command,
|
|
5501
|
+
cwd,
|
|
5502
|
+
env,
|
|
5503
|
+
stdoutFile: join11(dir, "stdout.log"),
|
|
5504
|
+
stderrFile: join11(dir, "stderr.log"),
|
|
5505
|
+
exitFile: join11(dir, "exit-code")
|
|
5506
|
+
});
|
|
5507
|
+
} catch (err) {
|
|
5508
|
+
const error = safeError(err, redactor);
|
|
5509
|
+
record.ended = {
|
|
5510
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
5511
|
+
status: "failed",
|
|
5512
|
+
exitCode: null,
|
|
5513
|
+
signal: null
|
|
5514
|
+
};
|
|
5515
|
+
record.settled = true;
|
|
5516
|
+
await saveRecord(dir, record).catch(() => void 0);
|
|
5517
|
+
this.opts.logger.error(`job ${id}: could not start`, { error });
|
|
5518
|
+
this.opts.onJobEnded?.(id);
|
|
5519
|
+
return { ok: false, error: `The job could not be started: ${error}` };
|
|
5520
|
+
}
|
|
5521
|
+
record.pid = started.pid;
|
|
5522
|
+
record.startedAt = started.startedAt;
|
|
5523
|
+
let job;
|
|
5524
|
+
try {
|
|
5525
|
+
record.processStamp = await processStamp(started.pid);
|
|
5526
|
+
await saveRecord(dir, record);
|
|
5527
|
+
job = await this.openJob(record, started.child, redactor);
|
|
5528
|
+
} catch (err) {
|
|
5529
|
+
await killJobTree({ pid: started.pid, startedAt: started.startedAt }, true);
|
|
5530
|
+
record.ended = {
|
|
5531
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
5532
|
+
status: "failed",
|
|
5533
|
+
exitCode: null,
|
|
5534
|
+
signal: null
|
|
5535
|
+
};
|
|
5536
|
+
record.settled = true;
|
|
5537
|
+
await saveRecord(dir, record).catch(() => void 0);
|
|
5538
|
+
const error = safeError(err, redactor);
|
|
5539
|
+
this.opts.logger.error(`job ${id}: could not be set up after it started; ended it`, {
|
|
5540
|
+
error
|
|
5541
|
+
});
|
|
5542
|
+
this.opts.onJobEnded?.(id);
|
|
5543
|
+
return { ok: false, error: `The job could not be started: ${error}` };
|
|
5544
|
+
}
|
|
5545
|
+
this.jobs.set(id, job);
|
|
5546
|
+
job.outbox.report({ status: "running" });
|
|
5547
|
+
void started.exited?.then((info) => this.finish(job, info));
|
|
5548
|
+
this.ensureTimers();
|
|
5549
|
+
this.opts.logger.info(`job ${id}: running (pid ${record.pid})`);
|
|
5550
|
+
return { ok: true };
|
|
5551
|
+
}
|
|
5552
|
+
/**
|
|
5553
|
+
* A job's secrets again, for one taken up after a restart: each checked against its
|
|
5554
|
+
* fingerprint from the start. All the same: the job's output is redacted with them and
|
|
5555
|
+
* posted from where the outbox got to. One changed or missing: it stays held back, one line
|
|
5556
|
+
* says why, and they are not asked for again.
|
|
5557
|
+
*/
|
|
5558
|
+
async applySecrets(id, cmd) {
|
|
5559
|
+
const job = this.jobs.get(id);
|
|
5560
|
+
if (!job?.awaiting) return { ok: true };
|
|
5561
|
+
const check = job.record.secretCheck;
|
|
5562
|
+
const names = job.record.secretNames ?? [];
|
|
5563
|
+
const given = sessionEnvironment({ variables: {}, secrets: cmd.environment?.secrets ?? {} });
|
|
5564
|
+
const values = {};
|
|
5565
|
+
const changed = [];
|
|
5566
|
+
const matched = await inPairs(names, async (name) => {
|
|
5567
|
+
const value = given?.secretNames.includes(name) ? given.env[name] : void 0;
|
|
5568
|
+
return typeof value === "string" && !!check && await secretMatches(check, name, value) ? value : null;
|
|
5569
|
+
});
|
|
5570
|
+
names.forEach((name, i) => {
|
|
5571
|
+
const value = matched[i];
|
|
5572
|
+
if (value === null) changed.push(name);
|
|
5573
|
+
else values[name] = value;
|
|
5574
|
+
});
|
|
5575
|
+
if (!job.awaiting) return { ok: true };
|
|
5576
|
+
if (changed.length) {
|
|
5577
|
+
this.opts.logger.warn(
|
|
5578
|
+
`job ${id}: ${changed.join(", ")} ${changed.length === 1 ? "is" : "are"} not what the job started with; its output stays in ${job.dir}`
|
|
5579
|
+
);
|
|
5580
|
+
await this.giveUpSecrets(job, "changed", changed);
|
|
5581
|
+
return {
|
|
5582
|
+
ok: false,
|
|
5583
|
+
error: `Not the values the job started with (changed or removed since, or not readable by Discovery Tree): ${changed.join(", ")}. Its output stays on the runner.`
|
|
5584
|
+
};
|
|
5585
|
+
}
|
|
5586
|
+
const environment = sessionEnvironment({ variables: {}, secrets: values });
|
|
5587
|
+
job.redactor = environment ? jobLineRedactor(environment) : null;
|
|
5588
|
+
const wait = job.awaiting;
|
|
5589
|
+
job.awaiting = null;
|
|
5590
|
+
if (job.record.withheldNotice || job.record.withheldNoticeQueued) {
|
|
5591
|
+
job.outbox.add([noticeLine(RESUMED_NOTICE)], job.outbox.cursor);
|
|
5592
|
+
job.record.withheldNotice = null;
|
|
5593
|
+
job.record.withheldNoticeQueued = false;
|
|
5594
|
+
await saveRecord(job.dir, job.record).catch(() => void 0);
|
|
5595
|
+
}
|
|
5596
|
+
wait.end();
|
|
5597
|
+
this.opts.logger.info(`job ${id}: got its secrets back; posting its output, redacted`);
|
|
5598
|
+
return { ok: true };
|
|
5599
|
+
}
|
|
5600
|
+
/**
|
|
5601
|
+
* Its secrets will not come back (`kind` says why, or null for no line): its output is no
|
|
5602
|
+
* longer waited for but read past, unposted, the line saying so queued once.
|
|
5603
|
+
*/
|
|
5604
|
+
async giveUpSecrets(job, kind, names = []) {
|
|
5605
|
+
const wait = job.awaiting;
|
|
5606
|
+
job.awaiting = null;
|
|
5607
|
+
job.withhold = true;
|
|
5608
|
+
if (kind) await this.noticeWithheld(job, kind, names);
|
|
5609
|
+
wait?.end();
|
|
5610
|
+
}
|
|
5611
|
+
/** Queues the line saying why the job's output is held back, unless it already went. */
|
|
5612
|
+
async noticeWithheld(job, kind, names = []) {
|
|
5613
|
+
const last = job.record.withheldNotice ?? (job.record.withheldNoticeQueued ? "unverifiable" : null);
|
|
5614
|
+
if (last === kind) return;
|
|
5615
|
+
job.outbox.add([noticeLine(withheldNoticeText(kind, names))], job.outbox.cursor);
|
|
5616
|
+
job.record.withheldNotice = kind;
|
|
5617
|
+
await saveRecord(job.dir, job.record).catch(() => void 0);
|
|
5618
|
+
}
|
|
5619
|
+
/** An end of a job whose secrets are to come back waits for them, for a while. */
|
|
5620
|
+
async waitForSecrets(job) {
|
|
5621
|
+
const wait = job.awaiting;
|
|
5622
|
+
if (!wait) return;
|
|
5623
|
+
const left = wait.since + (this.opts.secretsEndWaitMs ?? JOB_SECRETS_END_WAIT_MS) - Date.now();
|
|
5624
|
+
let timer = null;
|
|
5625
|
+
await Promise.race([
|
|
5626
|
+
wait.over,
|
|
5627
|
+
this.stopped.over,
|
|
5628
|
+
new Promise((resolve4) => {
|
|
5629
|
+
timer = setTimeout(resolve4, Math.max(0, left));
|
|
5630
|
+
timer.unref?.();
|
|
5631
|
+
})
|
|
5632
|
+
]);
|
|
5633
|
+
if (timer) clearTimeout(timer);
|
|
5634
|
+
}
|
|
5635
|
+
/** An end not awaited (it waits for secrets): a shutdown waits for it, a failure is logged. */
|
|
5636
|
+
track(work, jobId) {
|
|
5637
|
+
const tracked = work.catch(
|
|
5638
|
+
(err) => this.opts.logger.warn(`job ${jobId}: could not be ended`, {
|
|
5639
|
+
error: err?.message ?? String(err)
|
|
5640
|
+
})
|
|
5641
|
+
);
|
|
5642
|
+
this.finishing.add(tracked);
|
|
5643
|
+
void tracked.then(() => this.finishing.delete(tracked));
|
|
5644
|
+
}
|
|
5645
|
+
stopCommand(id) {
|
|
5646
|
+
const job = this.jobs.get(id);
|
|
5647
|
+
if (job && job.phase === "running") {
|
|
5648
|
+
this.opts.logger.info(`job ${id}: stopping`);
|
|
5649
|
+
void this.stop(job);
|
|
5650
|
+
}
|
|
5651
|
+
return { ok: true };
|
|
5652
|
+
}
|
|
5653
|
+
async openJob(record, child, redactor) {
|
|
5654
|
+
const dir = this.jobDir(record.jobId);
|
|
5655
|
+
const needsSecrets = !redactor && !!record.secretNames?.length;
|
|
5656
|
+
const verifiable = needsSecrets && record.withheldNotice !== "changed" && record.withheldNotice !== "gave_up" && checksEvery(record.secretCheck, record.secretNames ?? []);
|
|
5657
|
+
const job = {
|
|
5658
|
+
record,
|
|
5659
|
+
dir,
|
|
5660
|
+
outbox: null,
|
|
5661
|
+
readers: [],
|
|
5662
|
+
redactor,
|
|
5663
|
+
withhold: needsSecrets && !verifiable,
|
|
5664
|
+
awaiting: verifiable ? secretWait() : null,
|
|
5665
|
+
child,
|
|
5666
|
+
tree: record.pid && record.startedAt ? { pid: record.pid, startedAt: record.startedAt } : null,
|
|
5667
|
+
phase: "running",
|
|
5668
|
+
killTimer: null,
|
|
5669
|
+
reading: Promise.resolve()
|
|
5670
|
+
};
|
|
5671
|
+
job.outbox = await JobOutbox.open({
|
|
5672
|
+
jobId: record.jobId,
|
|
5673
|
+
file: join11(dir, "outbox.json"),
|
|
5674
|
+
poster: this.opts.poster,
|
|
5675
|
+
logger: this.opts.logger,
|
|
5676
|
+
batchDelayMs: this.opts.outboxBatchDelayMs,
|
|
5677
|
+
retryBaseMs: this.opts.outboxRetryBaseMs,
|
|
5678
|
+
onStop: () => {
|
|
5679
|
+
if (job.phase === "running") {
|
|
5680
|
+
this.opts.logger.info(`job ${record.jobId}: Discovery Tree says it is over; stopping it`);
|
|
5681
|
+
void this.stop(job);
|
|
5682
|
+
}
|
|
5683
|
+
},
|
|
5684
|
+
onGone: () => {
|
|
5685
|
+
if (job.phase === "running") void this.stop(job);
|
|
5686
|
+
if (job.phase === "ended") void this.settle(job);
|
|
5687
|
+
},
|
|
5688
|
+
onUnauthorized: (err) => this.opts.onUnauthorized?.(err),
|
|
5689
|
+
onFinished: () => {
|
|
5690
|
+
if (job.phase === "ended") void this.settle(job);
|
|
5691
|
+
}
|
|
5692
|
+
});
|
|
5693
|
+
const cursor = job.outbox.cursor ?? startCursor();
|
|
5694
|
+
job.readers = [
|
|
5695
|
+
new LogFileReader(join11(dir, "stdout.log"), "stdout", cursor.stdout),
|
|
5696
|
+
new LogFileReader(join11(dir, "stderr.log"), "stderr", cursor.stderr)
|
|
5697
|
+
];
|
|
5698
|
+
return job;
|
|
5699
|
+
}
|
|
5700
|
+
/** Reads what the job wrote since last time and queues it (redacted) to post. */
|
|
5701
|
+
read(job, final) {
|
|
5702
|
+
const next = job.reading.then(async () => {
|
|
5703
|
+
if (job.awaiting) return;
|
|
5704
|
+
for (; ; ) {
|
|
5705
|
+
let more = false;
|
|
5706
|
+
for (const reader of job.readers) {
|
|
5707
|
+
let lines;
|
|
5708
|
+
try {
|
|
5709
|
+
lines = await reader.read(final);
|
|
5710
|
+
} catch (err) {
|
|
5711
|
+
this.opts.logger.debug(`job ${job.record.jobId}: could not read its ${reader.stream}`, {
|
|
5712
|
+
error: err.message
|
|
5713
|
+
});
|
|
5714
|
+
continue;
|
|
5715
|
+
}
|
|
5716
|
+
if (!reader.atEnd) more = true;
|
|
5717
|
+
const cursor = { stdout: job.readers[0].position, stderr: job.readers[1].position };
|
|
5718
|
+
const posted = job.withhold ? [] : lines.map((l) => ({
|
|
5719
|
+
...l,
|
|
5720
|
+
// Redacted whole first, then cut to what is posted: a cut never splits a
|
|
5721
|
+
// value into a part redaction would not know. A line the reader cut is
|
|
5722
|
+
// redacted as cut (a value cut off at its end is dropped).
|
|
5723
|
+
text: postableLineText(redactLine(job.redactor, l.text, l.cut === true))
|
|
5724
|
+
}));
|
|
5725
|
+
job.outbox.add(posted, cursor);
|
|
5726
|
+
}
|
|
5727
|
+
if (!more || !final) break;
|
|
5728
|
+
}
|
|
5729
|
+
});
|
|
5730
|
+
job.reading = next.catch(() => void 0);
|
|
5731
|
+
return job.reading;
|
|
5732
|
+
}
|
|
5733
|
+
/** Asks the job to end; kills its tree once the grace is up. */
|
|
5734
|
+
async stop(job) {
|
|
5735
|
+
if (job.phase !== "running") return;
|
|
5736
|
+
job.phase = "stopping";
|
|
5737
|
+
job.record.stopRequestedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
5738
|
+
await saveRecord(job.dir, job.record).catch(() => void 0);
|
|
5739
|
+
job.killTimer = setTimeout(
|
|
5740
|
+
() => void this.forceKill(job),
|
|
5741
|
+
this.opts.stopGraceMs ?? JOB_STOP_GRACE_MS
|
|
5742
|
+
);
|
|
5743
|
+
job.killTimer.unref?.();
|
|
5744
|
+
if (job.tree) await askJobToStop(job.tree).catch(() => void 0);
|
|
5745
|
+
job.record.stopSignalledAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
5746
|
+
await saveRecord(job.dir, job.record).catch(() => void 0);
|
|
5747
|
+
}
|
|
5748
|
+
async forceKill(job) {
|
|
5749
|
+
job.killTimer = null;
|
|
5750
|
+
if (job.phase !== "stopping" || !job.tree) return;
|
|
5751
|
+
this.opts.logger.info(`job ${job.record.jobId}: did not stop in time; killing it`);
|
|
5752
|
+
await killJobTree(job.tree, await this.rootIsTheJob(job));
|
|
5753
|
+
}
|
|
5754
|
+
/** The job's root process is still running (and still the job's, not a later pid's). */
|
|
5755
|
+
async rootIsTheJob(job) {
|
|
5756
|
+
if (job.child) return job.child.exitCode === null && job.child.signalCode === null;
|
|
5757
|
+
const { pid, startedAt, processStamp: stamp } = job.record;
|
|
5758
|
+
return pid !== null && startedAt !== null && await isJobProcess(pid, startedAt, null, stamp);
|
|
5759
|
+
}
|
|
5760
|
+
/**
|
|
5761
|
+
* The job's process ended (`info` from Node, or from the exit-code file for one taken up
|
|
5762
|
+
* again; null when nothing says how): what it left running is ended, its last output read,
|
|
5763
|
+
* and how it ended queued as its last report.
|
|
5764
|
+
*/
|
|
5765
|
+
finish(job, info) {
|
|
5766
|
+
if (job.phase === "ending" || job.phase === "ended") return Promise.resolve();
|
|
5767
|
+
if (this.shuttingDown) return Promise.resolve();
|
|
5768
|
+
const work = this.finishJob(job, info);
|
|
5769
|
+
this.finishing.add(work);
|
|
5770
|
+
const done = () => this.finishing.delete(work);
|
|
5771
|
+
work.then(done, done);
|
|
5772
|
+
return work;
|
|
5773
|
+
}
|
|
5774
|
+
async finishJob(job, info) {
|
|
5775
|
+
const stopping = job.phase === "stopping" || !!job.record.stopRequestedAt;
|
|
5776
|
+
job.phase = "ending";
|
|
5777
|
+
if (job.killTimer) clearTimeout(job.killTimer);
|
|
5778
|
+
job.killTimer = null;
|
|
5779
|
+
const asked = stopping ? Date.parse(job.record.stopRequestedAt ?? "") : NaN;
|
|
5780
|
+
const left = Number.isNaN(asked) ? 0 : asked + (this.opts.stopGraceMs ?? JOB_STOP_GRACE_MS) - Date.now();
|
|
5781
|
+
if (job.tree) {
|
|
5782
|
+
await this.endLeftovers(
|
|
5783
|
+
job.tree,
|
|
5784
|
+
Math.max(LEFTOVER_GRACE_MS, left),
|
|
5785
|
+
!!job.record.stopSignalledAt
|
|
5786
|
+
);
|
|
5787
|
+
}
|
|
5788
|
+
if (job.awaiting) {
|
|
5789
|
+
await this.waitForSecrets(job);
|
|
5790
|
+
if (this.shuttingDown) return;
|
|
5791
|
+
if (job.awaiting) await this.giveUpSecrets(job, "gave_up");
|
|
5792
|
+
}
|
|
5793
|
+
await this.read(job, true);
|
|
5794
|
+
for (const r of job.readers) await r.close();
|
|
5795
|
+
let report;
|
|
5796
|
+
if (stopping) {
|
|
5797
|
+
report = { status: "stopped", exitCode: info?.code ?? null, signal: info?.signal ?? null };
|
|
5798
|
+
} else if (info) {
|
|
5799
|
+
report = { status: "exited", exitCode: info.code, signal: info.signal };
|
|
5800
|
+
} else {
|
|
5801
|
+
report = null;
|
|
5802
|
+
}
|
|
5803
|
+
job.record.ended = {
|
|
5804
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
5805
|
+
status: report ? report.status : "lost",
|
|
5806
|
+
exitCode: info?.code ?? null,
|
|
5807
|
+
signal: info?.signal ?? null
|
|
5808
|
+
};
|
|
5809
|
+
await saveRecord(job.dir, job.record).catch(() => void 0);
|
|
5810
|
+
job.phase = "ended";
|
|
5811
|
+
this.opts.logger.info(
|
|
5812
|
+
`job ${job.record.jobId}: ${report ? `${report.status}${info?.code !== null && info?.code !== void 0 ? ` (exit code ${info.code})` : info?.signal ? ` (${info.signal})` : ""}` : "its process is gone and nothing says how it ended; Discovery Tree will mark it lost"}`
|
|
5813
|
+
);
|
|
5814
|
+
if (report) job.outbox.report(report);
|
|
5815
|
+
else job.outbox.endWithoutReport();
|
|
5816
|
+
job.lastQueuedAt = performance.now();
|
|
5817
|
+
if (job.outbox.isFinished) await this.settle(job);
|
|
5818
|
+
if (!this.shuttingDown) this.opts.onJobEnded?.(job.record.jobId);
|
|
5819
|
+
}
|
|
5820
|
+
/**
|
|
5821
|
+
* What the job left running after its root exited: asked to end (unless a stop asked it
|
|
5822
|
+
* already: a second SIGTERM is "quit now" to many programs), then killed after `graceMs`.
|
|
5823
|
+
*/
|
|
5824
|
+
async endLeftovers(tree, graceMs, asked) {
|
|
5825
|
+
const deadline = Date.now() + graceMs;
|
|
5826
|
+
if (JOB_IS_WINDOWS) {
|
|
5827
|
+
if (graceMs > LEFTOVER_GRACE_MS) {
|
|
5828
|
+
while (Date.now() < deadline) {
|
|
5829
|
+
const rows = await listWindowsProcesses().catch(() => null);
|
|
5830
|
+
if (rows && descendantsOf(tree, rows).length === 0) return;
|
|
5831
|
+
await new Promise((r) => setTimeout(r, 1e3));
|
|
5832
|
+
}
|
|
5833
|
+
}
|
|
5834
|
+
await killJobTree(tree, false);
|
|
5835
|
+
return;
|
|
5836
|
+
}
|
|
5837
|
+
if (processRunning(tree.pid) || !groupAlive(tree.pid)) return;
|
|
5838
|
+
if (!asked) signalGroup2(tree.pid, "SIGTERM");
|
|
5839
|
+
while (Date.now() < deadline && groupHasLiveMember(tree.pid)) {
|
|
5840
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
5841
|
+
}
|
|
5842
|
+
signalGroup2(tree.pid, "SIGKILL");
|
|
5843
|
+
}
|
|
5844
|
+
/** Its last report is through: the job is let go (its folder and log stay). */
|
|
5845
|
+
async settle(job) {
|
|
5846
|
+
if (this.jobs.get(job.record.jobId) !== job || job.phase !== "ended") return;
|
|
5847
|
+
this.jobs.delete(job.record.jobId);
|
|
5848
|
+
job.record.settled = true;
|
|
5849
|
+
await job.outbox.settled();
|
|
5850
|
+
await saveRecord(job.dir, job.record).catch(() => void 0);
|
|
5851
|
+
}
|
|
5852
|
+
ensureTimers() {
|
|
5853
|
+
if (this.shuttingDown) return;
|
|
5854
|
+
if (!this.timer) {
|
|
5855
|
+
this.timer = setInterval(() => void this.tick(), this.opts.pollIntervalMs ?? 500);
|
|
5856
|
+
this.timer.unref?.();
|
|
5857
|
+
}
|
|
5858
|
+
if (JOB_IS_WINDOWS && !this.censusTimer) {
|
|
5859
|
+
this.censusTimer = setInterval(() => void this.census(), CENSUS_INTERVAL_MS2);
|
|
5860
|
+
this.censusTimer.unref?.();
|
|
5861
|
+
}
|
|
5862
|
+
}
|
|
5863
|
+
/**
|
|
5864
|
+
* Windows: one look at the process table for every job. What descends from each is
|
|
5865
|
+
* remembered (see `recordDescendants`), and a job watched by its pid whose pid now names a
|
|
5866
|
+
* later process (Windows hands pids out again quickly) is over: `tick` alone, seeing the pid
|
|
5867
|
+
* alive, would hold it as running for good.
|
|
5868
|
+
*/
|
|
5869
|
+
async census() {
|
|
5870
|
+
const live = [...this.jobs.values()].filter(
|
|
5871
|
+
(j) => (j.phase === "running" || j.phase === "stopping") && j.tree
|
|
5872
|
+
);
|
|
5873
|
+
if (!live.length) return;
|
|
5874
|
+
const rows = await listWindowsProcesses().catch(() => null);
|
|
5875
|
+
if (!rows) return;
|
|
5876
|
+
for (const job of live) {
|
|
5877
|
+
recordDescendants(job.tree, rows);
|
|
5878
|
+
if (job.child) continue;
|
|
5879
|
+
const row = rows.find((r) => r.pid === job.tree.pid);
|
|
5880
|
+
if (!row || Math.abs(row.createdAt - job.tree.startedAt) > 5e3) {
|
|
5881
|
+
void this.finish(job, await readExitFile(job.dir));
|
|
5882
|
+
}
|
|
5883
|
+
}
|
|
5884
|
+
}
|
|
5885
|
+
/** Reads every job's new output; notices an adopted job's process has gone. */
|
|
5886
|
+
async tick() {
|
|
5887
|
+
if (this.ticking || this.shuttingDown) return;
|
|
5888
|
+
this.ticking = true;
|
|
5889
|
+
try {
|
|
5890
|
+
for (const job of [...this.jobs.values()]) {
|
|
5891
|
+
if (job.phase !== "running" && job.phase !== "stopping") continue;
|
|
5892
|
+
const wait = job.awaiting;
|
|
5893
|
+
if (wait && Date.now() - wait.since > (this.opts.secretsWaitMs ?? JOB_SECRETS_WAIT_MS)) {
|
|
5894
|
+
await this.noticeWithheld(job, "waiting");
|
|
5895
|
+
}
|
|
5896
|
+
await this.read(job, false);
|
|
5897
|
+
if (!job.child && job.record.pid !== null && !processRunning(job.record.pid)) {
|
|
5898
|
+
void this.finish(job, await readExitFile(job.dir));
|
|
5899
|
+
}
|
|
5900
|
+
}
|
|
5901
|
+
} finally {
|
|
5902
|
+
this.ticking = false;
|
|
5903
|
+
}
|
|
5904
|
+
}
|
|
5905
|
+
};
|
|
5906
|
+
function samePath(a, b) {
|
|
5907
|
+
const fold = JOB_IS_WINDOWS || process.platform === "darwin";
|
|
5908
|
+
const norm = (p) => {
|
|
5909
|
+
const r = fold ? p.toLowerCase() : p;
|
|
5910
|
+
return r.length > 1 ? r.replace(/[\\/]+$/, "") : r;
|
|
5911
|
+
};
|
|
5912
|
+
return norm(resolve2(a)) === norm(resolve2(b)) || norm(canonical(a)) === norm(canonical(b));
|
|
5913
|
+
}
|
|
5914
|
+
function isInside(dir, parent) {
|
|
5915
|
+
const fold = JOB_IS_WINDOWS || process.platform === "darwin";
|
|
5916
|
+
const norm = (p) => {
|
|
5917
|
+
const r = fold ? p.toLowerCase() : p;
|
|
5918
|
+
return r.length > 1 ? r.replace(/[\\/]+$/, "") : r;
|
|
5919
|
+
};
|
|
5920
|
+
const inside = (d, p) => d === p || d.startsWith(p.endsWith(sep2) ? p : p + sep2);
|
|
5921
|
+
return inside(norm(resolve2(dir)), norm(resolve2(parent))) || inside(norm(canonical(dir)), norm(canonical(parent)));
|
|
5922
|
+
}
|
|
5923
|
+
function canonical(p) {
|
|
5924
|
+
const full = resolve2(p);
|
|
5925
|
+
let head = full;
|
|
5926
|
+
let tail = "";
|
|
5927
|
+
for (; ; ) {
|
|
5928
|
+
try {
|
|
5929
|
+
const real = realpathSync.native(head);
|
|
5930
|
+
return tail ? join11(real, tail) : real;
|
|
5931
|
+
} catch {
|
|
5932
|
+
const up = dirname6(head);
|
|
5933
|
+
if (up === head) return full;
|
|
5934
|
+
tail = tail ? join11(basename(head), tail) : basename(head);
|
|
5935
|
+
head = up;
|
|
5936
|
+
}
|
|
5937
|
+
}
|
|
5938
|
+
}
|
|
5939
|
+
function jobLineRedactor(environment) {
|
|
5940
|
+
const values = [];
|
|
5941
|
+
for (const name of environment.secretNames) {
|
|
5942
|
+
const value = environment.env[name];
|
|
5943
|
+
if (typeof value !== "string") continue;
|
|
5944
|
+
values.push({ name, value });
|
|
5945
|
+
const trimmed = value.trim();
|
|
5946
|
+
if (trimmed !== value && trimmed.length >= SECRET_REDACTION_MIN_LENGTH) {
|
|
5947
|
+
values.push({ name, value: trimmed });
|
|
5948
|
+
}
|
|
5949
|
+
if (!/[\r\n]/.test(value)) continue;
|
|
5950
|
+
for (const line of value.split(/\r?\n|\r/)) {
|
|
5951
|
+
for (const piece of /* @__PURE__ */ new Set([line, line.trim()])) {
|
|
5952
|
+
if (piece.length >= SECRET_REDACTION_MIN_LENGTH && !HARMLESS_SECRET_LINE.test(piece)) {
|
|
5953
|
+
values.push({ name, value: piece });
|
|
5954
|
+
}
|
|
5955
|
+
}
|
|
5956
|
+
}
|
|
5957
|
+
}
|
|
5958
|
+
return new SecretRedactor(values);
|
|
5959
|
+
}
|
|
5960
|
+
var HARMLESS_SECRET_LINE = /^(-----(BEGIN|END) [A-Z0-9 ]+-----|[\s{}[\],:]*(true|false|null)?[\s{}[\],:]*)$/;
|
|
5961
|
+
function secretsWithShortLines(environment) {
|
|
5962
|
+
return environment.secretNames.filter((name) => {
|
|
5963
|
+
const value = environment.env[name];
|
|
5964
|
+
if (typeof value !== "string" || !/[\r\n]/.test(value)) return false;
|
|
5965
|
+
return value.split(/\r?\n|\r/).map((l) => l.trim()).some(
|
|
5966
|
+
(l) => l.length > 0 && l.length < SECRET_REDACTION_MIN_LENGTH && !HARMLESS_SECRET_LINE.test(l)
|
|
5967
|
+
);
|
|
5968
|
+
});
|
|
5969
|
+
}
|
|
5970
|
+
async function secretCheckOf(environment) {
|
|
5971
|
+
const salt = randomBytes3(16).toString("base64");
|
|
5972
|
+
const hashes = {};
|
|
5973
|
+
await inPairs(environment.secretNames, async (name) => {
|
|
5974
|
+
const value = environment.env[name];
|
|
5975
|
+
if (typeof value === "string") {
|
|
5976
|
+
hashes[name] = (await fingerprint(salt, name, value)).toString("base64");
|
|
5977
|
+
}
|
|
5978
|
+
});
|
|
5979
|
+
return { v: 1, salt, hashes };
|
|
5980
|
+
}
|
|
5981
|
+
async function secretMatches(check, name, value) {
|
|
5982
|
+
const saved = check.hashes?.[name];
|
|
5983
|
+
if (typeof saved !== "string" || typeof check.salt !== "string") return false;
|
|
5984
|
+
const want = Buffer.from(saved, "base64");
|
|
5985
|
+
const got = await fingerprint(check.salt, name, value);
|
|
5986
|
+
return want.length === got.length && timingSafeEqual(want, got);
|
|
5987
|
+
}
|
|
5988
|
+
function checksEvery(check, names) {
|
|
5989
|
+
return !!check && check.v === 1 && typeof check.salt === "string" && !!check.hashes && names.every((n) => typeof check.hashes[n] === "string");
|
|
5990
|
+
}
|
|
5991
|
+
async function inPairs(items, fn) {
|
|
5992
|
+
const out = new Array(items.length);
|
|
5993
|
+
let next = 0;
|
|
5994
|
+
const worker = async () => {
|
|
5995
|
+
while (next < items.length) {
|
|
5996
|
+
const i = next++;
|
|
5997
|
+
out[i] = await fn(items[i]);
|
|
5998
|
+
}
|
|
5999
|
+
};
|
|
6000
|
+
await Promise.all([worker(), worker()]);
|
|
6001
|
+
return out;
|
|
6002
|
+
}
|
|
6003
|
+
function fingerprint(salt, name, value) {
|
|
6004
|
+
return new Promise(
|
|
6005
|
+
(resolve4, reject) => scrypt(value, `${salt}:${name}`, 32, (err, key) => err ? reject(err) : resolve4(key))
|
|
6006
|
+
);
|
|
6007
|
+
}
|
|
6008
|
+
var RESUMED_NOTICE = "[dt-runner] Discovery Tree handed this job\u2019s secrets back to the runner: its output from where it was held back follows, redacted.";
|
|
6009
|
+
function withheldNoticeText(kind, names) {
|
|
6010
|
+
const stays = "the job\u2019s output stays in its log on the runner\u2019s computer";
|
|
6011
|
+
switch (kind) {
|
|
6012
|
+
case "waiting":
|
|
6013
|
+
return `[dt-runner] The runner restarted and is waiting for Discovery Tree to hand back this job\u2019s secrets, so that it can redact them: until then, ${stays}.`;
|
|
6014
|
+
case "changed":
|
|
6015
|
+
return `[dt-runner] The runner restarted, and ${names.join(", ") || "a secret of this job"} ${names.length === 1 ? "is" : "are"} not the value the job started with (changed or removed since, or Discovery Tree could not read it): redacting another value would let the job\u2019s through, so from here on ${stays}.`;
|
|
6016
|
+
case "gave_up":
|
|
6017
|
+
return `[dt-runner] Discovery Tree did not hand back this job\u2019s secrets in time, so the runner cannot redact them: the rest of ${stays}.`;
|
|
6018
|
+
default:
|
|
6019
|
+
return `[dt-runner] The runner restarted and can no longer redact this job\u2019s secrets (the dt-runner that started it kept nothing to check them against): from here on ${stays}.`;
|
|
6020
|
+
}
|
|
6021
|
+
}
|
|
6022
|
+
function noticeLine(text) {
|
|
6023
|
+
return { stream: "stderr", text, at: (/* @__PURE__ */ new Date()).toISOString() };
|
|
6024
|
+
}
|
|
6025
|
+
function redactLine(redactor, text, cut2) {
|
|
6026
|
+
if (!redactor) return text;
|
|
6027
|
+
return cut2 ? redactor.redactCut(text) : redactor.redact(text);
|
|
6028
|
+
}
|
|
6029
|
+
function queueEndReport(outbox, ended) {
|
|
6030
|
+
if (ended.status === "lost" || ended.status === "failed") {
|
|
6031
|
+
outbox.endWithoutReport();
|
|
6032
|
+
return;
|
|
6033
|
+
}
|
|
6034
|
+
outbox.report(
|
|
6035
|
+
ended.status === "stopped" ? { status: "stopped", exitCode: ended.exitCode, signal: ended.signal } : { status: "exited", exitCode: ended.exitCode, signal: ended.signal }
|
|
6036
|
+
);
|
|
6037
|
+
}
|
|
6038
|
+
async function saveRecord(dir, record) {
|
|
6039
|
+
await writeJsonAtomic(join11(dir, "job.json"), record);
|
|
6040
|
+
}
|
|
6041
|
+
async function readExitFile(dir) {
|
|
6042
|
+
try {
|
|
6043
|
+
const code = Number.parseInt((await readFile7(join11(dir, "exit-code"), "utf8")).trim(), 10);
|
|
6044
|
+
return Number.isInteger(code) ? { code, signal: null } : null;
|
|
6045
|
+
} catch {
|
|
6046
|
+
return null;
|
|
6047
|
+
}
|
|
6048
|
+
}
|
|
6049
|
+
function safeError(err, redactor) {
|
|
6050
|
+
const raw = err instanceof Error ? err.message : String(err);
|
|
6051
|
+
return scrubSecrets(redactor ? redactor.redact(raw) : raw).slice(0, 600);
|
|
6052
|
+
}
|
|
6053
|
+
|
|
6054
|
+
// src/session-manager.ts
|
|
6055
|
+
import { existsSync, lstatSync } from "node:fs";
|
|
6056
|
+
import { mkdir as mkdir9, rm as rm7, writeFile as writeFile6 } from "node:fs/promises";
|
|
6057
|
+
import { basename as basename3, dirname as dirname9, join as join15, resolve as resolve3 } from "node:path";
|
|
6058
|
+
|
|
6059
|
+
// src/prompt-images.ts
|
|
6060
|
+
import { mkdir as mkdir7, writeFile as writeFile5 } from "node:fs/promises";
|
|
6061
|
+
import { join as join12 } from "node:path";
|
|
6062
|
+
var EXTENSIONS = {
|
|
6063
|
+
"image/png": ".png",
|
|
6064
|
+
"image/jpeg": ".jpg",
|
|
6065
|
+
"image/gif": ".gif",
|
|
6066
|
+
"image/webp": ".webp"
|
|
6067
|
+
};
|
|
6068
|
+
function promptImageFileName(index, filename, mimeType) {
|
|
6069
|
+
const base = (filename.split(/[\\/]/).pop() ?? "").replace(/[\u0000-\u001f\u007f<>:"|?*]+/g, "_").replace(/^\.+/, "").trim().slice(0, 120);
|
|
6070
|
+
const ext = EXTENSIONS[mimeType] ?? "";
|
|
6071
|
+
const named = base || `image${ext}`;
|
|
6072
|
+
const withExt = ext && !named.toLowerCase().endsWith(ext) ? `${named}${ext}` : named;
|
|
6073
|
+
return `${String(index + 1).padStart(2, "0")}-${withExt}`;
|
|
6074
|
+
}
|
|
6075
|
+
async function savePromptImages(input) {
|
|
6076
|
+
const out = { saved: [], failed: [] };
|
|
6077
|
+
if (input.images.length === 0) return out;
|
|
6078
|
+
const dir = join12(input.cwd, RUNNER_TASK_IMAGES_DIR);
|
|
6079
|
+
await mkdir7(dir, { recursive: true });
|
|
6080
|
+
if (input.inRepository) {
|
|
6081
|
+
await excludeFromGit(
|
|
6082
|
+
input.cwd,
|
|
6083
|
+
RUNNER_TASK_IMAGES_DIR,
|
|
6084
|
+
"Task images dt-runner saves for its agent"
|
|
6085
|
+
);
|
|
6086
|
+
}
|
|
6087
|
+
for (const [index, image] of input.images.entries()) {
|
|
6088
|
+
try {
|
|
6089
|
+
const res = await input.fetcher.getPromptImage(input.sessionId, image.attachmentId);
|
|
6090
|
+
const path = join12(
|
|
6091
|
+
dir,
|
|
6092
|
+
promptImageFileName(index, image.filename, res.mimeType || image.mimeType)
|
|
6093
|
+
);
|
|
6094
|
+
await writeFile5(path, Buffer.from(res.dataBase64, "base64"));
|
|
6095
|
+
out.saved.push({ filename: image.filename, path });
|
|
6096
|
+
} catch {
|
|
6097
|
+
out.failed.push(image.filename);
|
|
6098
|
+
}
|
|
6099
|
+
}
|
|
6100
|
+
return out;
|
|
6101
|
+
}
|
|
6102
|
+
function promptWithImagePaths(prompt, images) {
|
|
6103
|
+
if (images.saved.length === 0 && images.failed.length === 0) return prompt;
|
|
6104
|
+
const lines = [
|
|
6105
|
+
"",
|
|
6106
|
+
"IMAGE FILES FOR THIS TASK \u2014 the images the attachment lists above refer to, saved as",
|
|
6107
|
+
"files. Open each one and look at it before you start (read it as an image).",
|
|
6108
|
+
...images.saved.map((i) => `- ${i.filename}: ${i.path}`),
|
|
6109
|
+
...images.failed.map(
|
|
6110
|
+
(name) => `- ${name}: could not be downloaded; say so rather than describing it`
|
|
6111
|
+
)
|
|
6112
|
+
];
|
|
6113
|
+
return `${prompt}
|
|
6114
|
+
${lines.join("\n")}`;
|
|
6115
|
+
}
|
|
6116
|
+
|
|
6117
|
+
// src/outbox.ts
|
|
6118
|
+
var MAX_REJECTED_ATTEMPTS2 = 3;
|
|
6119
|
+
var SessionOutbox = class _SessionOutbox {
|
|
6120
|
+
constructor(opts) {
|
|
6121
|
+
this.opts = opts;
|
|
6122
|
+
}
|
|
6123
|
+
nextSeq = 1;
|
|
6124
|
+
pending = [];
|
|
6125
|
+
/** Highest seq in the batch being posted; entries up to it must not change. */
|
|
6126
|
+
inFlightUpTo = 0;
|
|
6127
|
+
pumping = false;
|
|
6128
|
+
pumpTimer = null;
|
|
6129
|
+
stopped = false;
|
|
6130
|
+
closed = false;
|
|
6131
|
+
stopController = new AbortController();
|
|
6132
|
+
persistChain = Promise.resolve();
|
|
6133
|
+
persistQueued = false;
|
|
6134
|
+
idleWaiters = [];
|
|
6135
|
+
/** Loads what a previous run left unsent, and resumes posting it. */
|
|
6136
|
+
static async open(opts) {
|
|
6137
|
+
const box = new _SessionOutbox(opts);
|
|
6138
|
+
const saved = await readJson(opts.file);
|
|
6139
|
+
if (saved) {
|
|
6140
|
+
box.pending = Array.isArray(saved.pending) ? saved.pending : [];
|
|
6141
|
+
const lastPending = box.pending.at(-1)?.seq ?? 0;
|
|
6142
|
+
box.nextSeq = Math.max(saved.nextSeq || 1, lastPending + 1);
|
|
6143
|
+
}
|
|
6144
|
+
if (box.pending.length) box.schedulePump();
|
|
6145
|
+
return box;
|
|
6146
|
+
}
|
|
6147
|
+
get size() {
|
|
6148
|
+
return this.pending.length;
|
|
6149
|
+
}
|
|
6150
|
+
get isClosed() {
|
|
6151
|
+
return this.closed;
|
|
6152
|
+
}
|
|
6153
|
+
/** The seq the next event will get (for tests and status). */
|
|
6154
|
+
get upcomingSeq() {
|
|
6155
|
+
return this.nextSeq;
|
|
6156
|
+
}
|
|
6157
|
+
enqueue(...events) {
|
|
6158
|
+
if (this.closed) return;
|
|
6159
|
+
for (const event of events) {
|
|
6160
|
+
if (!this.coalesce(event)) this.pending.push({ seq: this.nextSeq++, event });
|
|
6161
|
+
}
|
|
6162
|
+
this.persist();
|
|
6163
|
+
this.schedulePump();
|
|
6164
|
+
}
|
|
6165
|
+
/** Resolves once everything queued so far is posted (or the timeout passes). */
|
|
6166
|
+
async flush(timeoutMs) {
|
|
6167
|
+
if (this.stopped) return this.pending.length === 0;
|
|
3812
6168
|
if (this.pumpTimer) {
|
|
3813
6169
|
clearTimeout(this.pumpTimer);
|
|
3814
6170
|
this.pumpTimer = null;
|
|
3815
6171
|
}
|
|
3816
6172
|
if (this.pending.length && !this.closed) void this.pump();
|
|
3817
|
-
const drained = this.pending.length === 0 || this.closed ? Promise.resolve(true) : new Promise((
|
|
6173
|
+
const drained = this.pending.length === 0 || this.closed ? Promise.resolve(true) : new Promise((resolve4) => this.idleWaiters.push(() => resolve4(true)));
|
|
3818
6174
|
const result = await Promise.race([drained, sleep(timeoutMs).then(() => false)]);
|
|
3819
6175
|
await this.persistChain;
|
|
3820
6176
|
return result || this.pending.length === 0;
|
|
@@ -3938,7 +6294,7 @@ var SessionOutbox = class _SessionOutbox {
|
|
|
3938
6294
|
error: err.message,
|
|
3939
6295
|
attempt: rejected
|
|
3940
6296
|
});
|
|
3941
|
-
if (rejected >=
|
|
6297
|
+
if (rejected >= MAX_REJECTED_ATTEMPTS2) {
|
|
3942
6298
|
this.pending = this.pending.filter((e) => e.seq > maxSeq);
|
|
3943
6299
|
this.persist();
|
|
3944
6300
|
rejected = 0;
|
|
@@ -3989,13 +6345,13 @@ function takeBatch(pending) {
|
|
|
3989
6345
|
}
|
|
3990
6346
|
|
|
3991
6347
|
// src/session.ts
|
|
3992
|
-
import { spawn as
|
|
6348
|
+
import { spawn as spawn5 } from "node:child_process";
|
|
3993
6349
|
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
3994
|
-
import { basename, dirname as
|
|
6350
|
+
import { basename as basename2, dirname as dirname8 } from "node:path";
|
|
3995
6351
|
import { createInterface as createInterface2 } from "node:readline";
|
|
3996
6352
|
|
|
3997
6353
|
// src/tool-grants.ts
|
|
3998
|
-
import { dirname as
|
|
6354
|
+
import { dirname as dirname7, join as join13, posix } from "node:path";
|
|
3999
6355
|
var isGrantableDenial = isGrantableToolDenial;
|
|
4000
6356
|
var FILE_TOOLS2 = /* @__PURE__ */ new Set(["Read", "Edit", "MultiEdit", "Write", "NotebookEdit"]);
|
|
4001
6357
|
var EDIT_TOOLS = /* @__PURE__ */ new Set(["Edit", "MultiEdit", "Write", "NotebookEdit"]);
|
|
@@ -4193,7 +6549,7 @@ function filePatternMatches(spec, file) {
|
|
|
4193
6549
|
let pattern = spec.trim();
|
|
4194
6550
|
if (pattern.startsWith("~/")) {
|
|
4195
6551
|
if (!home) return false;
|
|
4196
|
-
pattern = rulePath(
|
|
6552
|
+
pattern = rulePath(join13(home, pattern.slice(2)).replace(/\\/g, "/"));
|
|
4197
6553
|
}
|
|
4198
6554
|
if (!pattern.startsWith("//")) return false;
|
|
4199
6555
|
const path = rulePath(file);
|
|
@@ -4214,7 +6570,7 @@ function shellPatternMatches(spec, command) {
|
|
|
4214
6570
|
return new RegExp(`^${re}${optionalTail ? "(?: .*)?" : ""}$`, "s").test(command);
|
|
4215
6571
|
}
|
|
4216
6572
|
function toolGrantsFile(configFile) {
|
|
4217
|
-
return
|
|
6573
|
+
return join13(dirname7(configFile), "tool-grants.json");
|
|
4218
6574
|
}
|
|
4219
6575
|
var ToolGrantStore = class {
|
|
4220
6576
|
constructor(file) {
|
|
@@ -4380,8 +6736,8 @@ function ghError(command, res) {
|
|
|
4380
6736
|
}
|
|
4381
6737
|
|
|
4382
6738
|
// src/session-store.ts
|
|
4383
|
-
import { mkdir as
|
|
4384
|
-
import { join as
|
|
6739
|
+
import { mkdir as mkdir8, readdir as readdir3, rm as rm6 } from "node:fs/promises";
|
|
6740
|
+
import { join as join14 } from "node:path";
|
|
4385
6741
|
var HANDLED_COMMAND_IDS_KEPT = 100;
|
|
4386
6742
|
var pendingWrites = /* @__PURE__ */ new Map();
|
|
4387
6743
|
var SessionStore = class {
|
|
@@ -4389,10 +6745,10 @@ var SessionStore = class {
|
|
|
4389
6745
|
this.stateDir = stateDir;
|
|
4390
6746
|
}
|
|
4391
6747
|
dir(sessionId) {
|
|
4392
|
-
return
|
|
6748
|
+
return join14(this.stateDir, "sessions", sessionId);
|
|
4393
6749
|
}
|
|
4394
6750
|
outboxFile(sessionId) {
|
|
4395
|
-
return
|
|
6751
|
+
return join14(this.dir(sessionId), "outbox.json");
|
|
4396
6752
|
}
|
|
4397
6753
|
/**
|
|
4398
6754
|
* Writes the record as it is now. A session's saves land in the order they were made:
|
|
@@ -4402,7 +6758,7 @@ var SessionStore = class {
|
|
|
4402
6758
|
*/
|
|
4403
6759
|
async save(record) {
|
|
4404
6760
|
record.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
4405
|
-
const file =
|
|
6761
|
+
const file = join14(this.dir(record.sessionId), "session.json");
|
|
4406
6762
|
const snapshot = JSON.parse(JSON.stringify(record));
|
|
4407
6763
|
const previous = pendingWrites.get(file) ?? Promise.resolve();
|
|
4408
6764
|
const write = previous.then(() => writeJsonAtomic(file, snapshot));
|
|
@@ -4414,23 +6770,23 @@ var SessionStore = class {
|
|
|
4414
6770
|
await write;
|
|
4415
6771
|
}
|
|
4416
6772
|
async list() {
|
|
4417
|
-
const root =
|
|
4418
|
-
await
|
|
6773
|
+
const root = join14(this.stateDir, "sessions");
|
|
6774
|
+
await mkdir8(root, { recursive: true });
|
|
4419
6775
|
const out = [];
|
|
4420
|
-
for (const entry of await
|
|
6776
|
+
for (const entry of await readdir3(root, { withFileTypes: true })) {
|
|
4421
6777
|
if (!entry.isDirectory()) continue;
|
|
4422
|
-
const rec = await readJson(
|
|
6778
|
+
const rec = await readJson(join14(root, entry.name, "session.json"));
|
|
4423
6779
|
if (rec?.sessionId === entry.name) out.push(upgradeRecord(rec));
|
|
4424
6780
|
}
|
|
4425
6781
|
return out;
|
|
4426
6782
|
}
|
|
4427
6783
|
async remove(sessionId) {
|
|
4428
|
-
await pendingWrites.get(
|
|
4429
|
-
await
|
|
6784
|
+
await pendingWrites.get(join14(this.dir(sessionId), "session.json"));
|
|
6785
|
+
await rm6(this.dir(sessionId), { recursive: true, force: true });
|
|
4430
6786
|
}
|
|
4431
6787
|
/** Scratch working directory for a session without a repository. */
|
|
4432
6788
|
scratchDir(sessionId) {
|
|
4433
|
-
return
|
|
6789
|
+
return join14(this.stateDir, "scratch", sessionId);
|
|
4434
6790
|
}
|
|
4435
6791
|
};
|
|
4436
6792
|
function upgradeRecord(stored) {
|
|
@@ -4448,7 +6804,7 @@ var DENIALS_KEPT = 200;
|
|
|
4448
6804
|
var AgentSession = class {
|
|
4449
6805
|
constructor(record, deps) {
|
|
4450
6806
|
this.record = record;
|
|
4451
|
-
this.deps = deps;
|
|
6807
|
+
this.deps = { ...deps, logger: redactingLogger(deps.logger, deps.environment?.redactor) };
|
|
4452
6808
|
this.driver = deps.driver;
|
|
4453
6809
|
this.mapper = deps.driver.createMapper();
|
|
4454
6810
|
this.permissions = new PermissionRelay({
|
|
@@ -4471,7 +6827,7 @@ var AgentSession = class {
|
|
|
4471
6827
|
input
|
|
4472
6828
|
),
|
|
4473
6829
|
// Only with a repository to save a rule for.
|
|
4474
|
-
suggestRule: (tool, input) => toolGrantRepositoryKey(this.record.repository) ?
|
|
6830
|
+
suggestRule: (tool, input) => toolGrantRepositoryKey(this.record.repository) ? this.suggestSafeRules(tool, input)?.suggestedRule ?? null : null,
|
|
4475
6831
|
rememberRule: (rule) => {
|
|
4476
6832
|
const rules = this.record.grantRules ??= [];
|
|
4477
6833
|
if (rules.includes(rule)) return;
|
|
@@ -4479,6 +6835,7 @@ var AgentSession = class {
|
|
|
4479
6835
|
void this.deps.store.save(this.record).catch(() => void 0);
|
|
4480
6836
|
this.deps.logger.info(`session ${this.sessionId}: allowed ${rule} for this repository`);
|
|
4481
6837
|
},
|
|
6838
|
+
redactInput: deps.environment?.redactor.active ? (input) => deps.environment.redactor.redactDeep(input) : void 0,
|
|
4482
6839
|
timeoutMs: deps.permissionTimeoutMs
|
|
4483
6840
|
});
|
|
4484
6841
|
}
|
|
@@ -4499,6 +6856,8 @@ var AgentSession = class {
|
|
|
4499
6856
|
interruptTimer = null;
|
|
4500
6857
|
controlSeq = 0;
|
|
4501
6858
|
stderrTail = "";
|
|
6859
|
+
/** `stderrTail` lost its start (it keeps the last 4,000 characters). */
|
|
6860
|
+
stderrCut = false;
|
|
4502
6861
|
sawResultSinceSpawn = false;
|
|
4503
6862
|
/** The process was started to resume, and has not yet said it has the conversation. */
|
|
4504
6863
|
spawnedWithResume = false;
|
|
@@ -4543,6 +6902,42 @@ var AgentSession = class {
|
|
|
4543
6902
|
inheritedNow = { allow: [], deny: [], ask: [], sources: [] };
|
|
4544
6903
|
/** The folders those rules came from, once logged. */
|
|
4545
6904
|
loggedInherited = "";
|
|
6905
|
+
deps;
|
|
6906
|
+
/** Said once: this session's environment was lost with a restart of the runner. */
|
|
6907
|
+
toldEnvironmentLost = false;
|
|
6908
|
+
/**
|
|
6909
|
+
* The rules to offer for a call. A call that holds none of the session's secret values gets
|
|
6910
|
+
* the usual ones. One that holds a value gets only a rule that names none of it (built from
|
|
6911
|
+
* the call with its values replaced, each placeholder one word so a command splits as it
|
|
6912
|
+
* did) and still covers the real call; one that cannot be offered so is replaced by the
|
|
6913
|
+
* other (an "Allow once" of a prefix, which the rule shown says). Rules are posted
|
|
6914
|
+
* and saved: one built around a value would write it down, and one with a placeholder in
|
|
6915
|
+
* it could never match. Null when no such rule exists: the call shows as failed, with no
|
|
6916
|
+
* offer to allow it.
|
|
6917
|
+
*/
|
|
6918
|
+
suggestSafeRules(toolName, input) {
|
|
6919
|
+
const redactor = this.deps.environment?.redactor;
|
|
6920
|
+
const allowed = this.deps.allowedTools;
|
|
6921
|
+
if (!redactor?.active) return suggestRules(toolName, input, allowed);
|
|
6922
|
+
if (JSON.stringify(redactor.redactDeep(input)) === JSON.stringify(input)) {
|
|
6923
|
+
return suggestRules(toolName, input, allowed);
|
|
6924
|
+
}
|
|
6925
|
+
const rules = suggestRules(toolName, redactor.forRules(input), allowed);
|
|
6926
|
+
if (!rules) return null;
|
|
6927
|
+
const ok = (rule) => !rule.includes(RULE_PLACEHOLDER) && grantsCover([rule], allowed, toolName, input);
|
|
6928
|
+
const suggested = ok(rules.suggestedRule) ? rules.suggestedRule : null;
|
|
6929
|
+
const once = ok(rules.onceRule) ? rules.onceRule : null;
|
|
6930
|
+
const fallback = once ?? suggested;
|
|
6931
|
+
return fallback ? { suggestedRule: suggested ?? fallback, onceRule: once ?? fallback } : null;
|
|
6932
|
+
}
|
|
6933
|
+
/**
|
|
6934
|
+
* An error's message for the log: the session's secrets replaced first, then credentials
|
|
6935
|
+
* in URLs (a value with an `@` in it would not survive that scrub whole).
|
|
6936
|
+
*/
|
|
6937
|
+
safeError(err) {
|
|
6938
|
+
const raw = err instanceof Error ? err.message : String(err);
|
|
6939
|
+
return scrubSecrets(this.deps.environment?.redactor.redact(raw) ?? raw);
|
|
6940
|
+
}
|
|
4546
6941
|
/** The person's Claude Code rules for the repository; the last read if it fails. */
|
|
4547
6942
|
async readInheritedRules() {
|
|
4548
6943
|
try {
|
|
@@ -4600,18 +6995,22 @@ var AgentSession = class {
|
|
|
4600
6995
|
* Reports a tool call that was denied because nobody could answer for it, with the rules
|
|
4601
6996
|
* a person could grant. Each call once; nothing for sessions not asked to report them.
|
|
4602
6997
|
*/
|
|
4603
|
-
reportDenial(callId, toolName,
|
|
6998
|
+
reportDenial(callId, toolName, rawInput) {
|
|
4604
6999
|
if (!this.record.reportToolDenials) return;
|
|
4605
7000
|
if (callId) {
|
|
4606
7001
|
if (this.seenFailedCalls.size > 1e3) this.seenFailedCalls.clear();
|
|
4607
7002
|
this.seenFailedCalls.add(callId);
|
|
4608
7003
|
}
|
|
4609
|
-
const rules =
|
|
7004
|
+
const rules = this.suggestSafeRules(toolName, rawInput);
|
|
4610
7005
|
if (!rules) return;
|
|
7006
|
+
const redactor = this.deps.environment?.redactor;
|
|
4611
7007
|
const denial = {
|
|
4612
7008
|
id: randomUUID2(),
|
|
4613
7009
|
toolName,
|
|
4614
|
-
inputSummary: summarizeToolInput(
|
|
7010
|
+
inputSummary: summarizeToolInput(
|
|
7011
|
+
toolName,
|
|
7012
|
+
redactor?.active ? redactor.redactDeep(rawInput) : rawInput
|
|
7013
|
+
),
|
|
4615
7014
|
...rules,
|
|
4616
7015
|
deniedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
4617
7016
|
};
|
|
@@ -4720,8 +7119,36 @@ var AgentSession = class {
|
|
|
4720
7119
|
get turnActive() {
|
|
4721
7120
|
return this.record.turnActive;
|
|
4722
7121
|
}
|
|
7122
|
+
/**
|
|
7123
|
+
* Queues events for the server, with the environment's secret values replaced first: the
|
|
7124
|
+
* outbox keeps them on disk until they are posted, and the server stores them.
|
|
7125
|
+
*/
|
|
4723
7126
|
emit(...events) {
|
|
4724
|
-
this.deps.
|
|
7127
|
+
const redactor = this.deps.environment?.redactor;
|
|
7128
|
+
if (!redactor?.active) {
|
|
7129
|
+
this.deps.outbox.enqueue(...events);
|
|
7130
|
+
return;
|
|
7131
|
+
}
|
|
7132
|
+
const safe = events.map((e) => redactor.event(e)).filter((e) => e !== null);
|
|
7133
|
+
if (safe.length) this.deps.outbox.enqueue(...safe);
|
|
7134
|
+
}
|
|
7135
|
+
/**
|
|
7136
|
+
* A session restored after the runner restarted had an environment whose values went with
|
|
7137
|
+
* the old process (they are never written to disk): said in the conversation, once, before
|
|
7138
|
+
* the agent starts without them.
|
|
7139
|
+
*/
|
|
7140
|
+
tellEnvironmentLost() {
|
|
7141
|
+
const names = this.record.environmentNames ?? [];
|
|
7142
|
+
if (this.deps.environment || !names.length || this.toldEnvironmentLost) return;
|
|
7143
|
+
this.toldEnvironmentLost = true;
|
|
7144
|
+
this.deps.logger.warn(
|
|
7145
|
+
`session ${this.sessionId}: the runner restarted, so the agent runs without the run's environment (${names.length} name(s))`
|
|
7146
|
+
);
|
|
7147
|
+
this.emit({
|
|
7148
|
+
type: "error",
|
|
7149
|
+
message: `The runner restarted since this session started, so ${this.driver.displayName} runs without the environment's variables and secrets (${names.join(", ").slice(0, 300)}): the runner keeps their values in memory only. To have them again, let this run end and continue it, which starts a new session with them.`,
|
|
7150
|
+
retryable: false
|
|
7151
|
+
});
|
|
4725
7152
|
}
|
|
4726
7153
|
/** Starts the process on the session's task (first turn). */
|
|
4727
7154
|
async startFirstTurn(prompt) {
|
|
@@ -4804,7 +7231,7 @@ var AgentSession = class {
|
|
|
4804
7231
|
const reaped = this.treeReaped;
|
|
4805
7232
|
this.stopping = reason;
|
|
4806
7233
|
this.reapGraceMs = graceMs;
|
|
4807
|
-
const exited = new Promise((
|
|
7234
|
+
const exited = new Promise((resolve4) => this.exitWaiters.push(resolve4));
|
|
4808
7235
|
if (child.exitCode === null && child.signalCode === null) {
|
|
4809
7236
|
await snapshotTree(this.tree, this.deps.reap);
|
|
4810
7237
|
}
|
|
@@ -4948,7 +7375,7 @@ ${text}` : text;
|
|
|
4948
7375
|
/** Resolves once the current process has exited (and its exit has been handled). */
|
|
4949
7376
|
waitForExit() {
|
|
4950
7377
|
if (!this.child) return Promise.resolve();
|
|
4951
|
-
return new Promise((
|
|
7378
|
+
return new Promise((resolve4) => this.exitWaiters.push(resolve4));
|
|
4952
7379
|
}
|
|
4953
7380
|
/** persistent agents: the session's process, started (resuming) when there is none. */
|
|
4954
7381
|
async ensureProcess() {
|
|
@@ -4958,6 +7385,7 @@ ${text}` : text;
|
|
|
4958
7385
|
}
|
|
4959
7386
|
/** Starts the agent's process (with a per_turn agent's prompt), and reads what it says. */
|
|
4960
7387
|
async spawnAgent(prompt) {
|
|
7388
|
+
this.tellEnvironmentLost();
|
|
4961
7389
|
await this.prepareEvidenceDir();
|
|
4962
7390
|
const { bin, features } = await this.deps.resolveAgent();
|
|
4963
7391
|
const savedRules = await (this.deps.savedRules?.(this.record.repository) ?? []);
|
|
@@ -4990,14 +7418,16 @@ ${text}` : text;
|
|
|
4990
7418
|
baseRef: this.record.baseRef,
|
|
4991
7419
|
cwd: this.record.cwd,
|
|
4992
7420
|
reviewImages: !!this.record.reviewImages,
|
|
4993
|
-
reference: this.record.referenceRepository ?? null
|
|
7421
|
+
reference: this.record.referenceRepository ?? null,
|
|
7422
|
+
environment: this.deps.environment ? { names: this.deps.environment.names, secretNames: this.deps.environment.secretNames } : null
|
|
4994
7423
|
}),
|
|
4995
7424
|
...prompt !== void 0 ? { prompt } : {},
|
|
4996
7425
|
...this.deps.agentConfig ? { agentConfig: this.deps.agentConfig } : {}
|
|
4997
7426
|
});
|
|
4998
|
-
const
|
|
7427
|
+
const runEnv = this.deps.environment?.env;
|
|
7428
|
+
const child = spawn5(launch.bin, launch.args, {
|
|
4999
7429
|
cwd: this.record.cwd,
|
|
5000
|
-
env: launch.env ? { ...process.env, ...launch.env } : process.env,
|
|
7430
|
+
env: launch.env || runEnv ? { ...process.env, ...runEnv, ...launch.env } : process.env,
|
|
5001
7431
|
stdio: ["pipe", "pipe", "pipe"],
|
|
5002
7432
|
windowsHide: true,
|
|
5003
7433
|
// A process group of its own, so what it starts can be ended with it. It also means
|
|
@@ -5005,10 +7435,10 @@ ${text}` : text;
|
|
|
5005
7435
|
detached: OWN_PROCESS_GROUP
|
|
5006
7436
|
});
|
|
5007
7437
|
let tree = null;
|
|
5008
|
-
await new Promise((
|
|
7438
|
+
await new Promise((resolve4, reject) => {
|
|
5009
7439
|
child.once("spawn", () => {
|
|
5010
7440
|
tree = trackTree(child, this.record.cwd || void 0);
|
|
5011
|
-
|
|
7441
|
+
resolve4();
|
|
5012
7442
|
});
|
|
5013
7443
|
child.once(
|
|
5014
7444
|
"error",
|
|
@@ -5023,6 +7453,7 @@ ${text}` : text;
|
|
|
5023
7453
|
this.resumeDoomed = false;
|
|
5024
7454
|
this.reapGraceMs = void 0;
|
|
5025
7455
|
this.stderrTail = "";
|
|
7456
|
+
this.stderrCut = false;
|
|
5026
7457
|
this.sawResultSinceSpawn = false;
|
|
5027
7458
|
this.spawnedWithResume = !!this.record.conversationId;
|
|
5028
7459
|
this.sawInitSinceSpawn = false;
|
|
@@ -5031,13 +7462,15 @@ ${text}` : text;
|
|
|
5031
7462
|
{ pid: child.pid }
|
|
5032
7463
|
);
|
|
5033
7464
|
this.treeReaped = new Promise(
|
|
5034
|
-
(
|
|
7465
|
+
(resolve4) => child.once("exit", () => void reapTree(tree, this.reapGraceMs, this.deps.reap).then(resolve4))
|
|
5035
7466
|
);
|
|
5036
7467
|
child.stdin.on("error", () => void 0);
|
|
5037
7468
|
if (launch.stdin !== void 0) child.stdin.end(launch.stdin);
|
|
5038
7469
|
else if (this.driver.processModel === "per_turn") child.stdin.end();
|
|
5039
7470
|
child.stderr.setEncoding("utf8").on("data", (d) => {
|
|
5040
|
-
|
|
7471
|
+
const tail = this.stderrTail + d;
|
|
7472
|
+
if (tail.length > 4e3) this.stderrCut = true;
|
|
7473
|
+
this.stderrTail = tail.slice(-4e3);
|
|
5041
7474
|
});
|
|
5042
7475
|
const rl = createInterface2({ input: child.stdout, crlfDelay: Infinity });
|
|
5043
7476
|
rl.on("line", (line) => {
|
|
@@ -5139,7 +7572,9 @@ ${text}` : text;
|
|
|
5139
7572
|
this.resumeRetry = this.turnText;
|
|
5140
7573
|
this.record.conversationId = null;
|
|
5141
7574
|
}
|
|
5142
|
-
async endTurn(
|
|
7575
|
+
async endTurn(rawTurn) {
|
|
7576
|
+
const redactor = this.deps.environment?.redactor;
|
|
7577
|
+
const turn = redactor?.active && rawTurn.text ? { ...rawTurn, text: redactor.redact(rawTurn.text) } : rawTurn;
|
|
5143
7578
|
this.permissions.expireAll(PERMISSION_EXPIRED_TURN_ENDED);
|
|
5144
7579
|
for (const d of turn.permissionDenials ?? []) {
|
|
5145
7580
|
if (d.callId && this.seenFailedCalls.has(d.callId)) continue;
|
|
@@ -5162,13 +7597,13 @@ ${text}` : text;
|
|
|
5162
7597
|
const push = await this.pushWork();
|
|
5163
7598
|
const screenshots = push.failed ? "" : await this.publishScreenshots().catch((err) => {
|
|
5164
7599
|
this.deps.logger.warn(`session ${this.sessionId}: publishing screenshots failed`, {
|
|
5165
|
-
error:
|
|
7600
|
+
error: this.safeError(err)
|
|
5166
7601
|
});
|
|
5167
7602
|
return "";
|
|
5168
7603
|
});
|
|
5169
7604
|
await this.uploadReviewImages().catch((err) => {
|
|
5170
7605
|
this.deps.logger.warn(`session ${this.sessionId}: uploading review images failed`, {
|
|
5171
|
-
error:
|
|
7606
|
+
error: this.safeError(err)
|
|
5172
7607
|
});
|
|
5173
7608
|
});
|
|
5174
7609
|
const failed = turnFailed || push.failed;
|
|
@@ -5213,8 +7648,10 @@ ${text}` : text;
|
|
|
5213
7648
|
const { pullRequest, workBranch, repository, baseRef } = this.record;
|
|
5214
7649
|
const repo = parseRepoUrl(repository ?? "");
|
|
5215
7650
|
if (!pullRequest || !workBranch || !repo) return null;
|
|
7651
|
+
const redactor = this.deps.environment?.redactor;
|
|
7652
|
+
const said = text && redactor ? redactor.redact(text) : text;
|
|
5216
7653
|
const body = [
|
|
5217
|
-
|
|
7654
|
+
said?.trim() || `Work by the ${this.driver.displayName} (local) agent.`,
|
|
5218
7655
|
"",
|
|
5219
7656
|
"---",
|
|
5220
7657
|
pullRequest.footer
|
|
@@ -5260,7 +7697,7 @@ ${text}` : text;
|
|
|
5260
7697
|
await ensureEvidenceDir(this.record.cwd);
|
|
5261
7698
|
} catch (err) {
|
|
5262
7699
|
this.deps.logger.warn(`session ${this.sessionId}: could not prepare the screenshot folder`, {
|
|
5263
|
-
error:
|
|
7700
|
+
error: this.safeError(err)
|
|
5264
7701
|
});
|
|
5265
7702
|
}
|
|
5266
7703
|
}
|
|
@@ -5300,7 +7737,7 @@ ${text}` : text;
|
|
|
5300
7737
|
async publishScreenshots() {
|
|
5301
7738
|
const { workBranch, repoDir, cwd, repository } = this.record;
|
|
5302
7739
|
const repo = parseRepoUrl(
|
|
5303
|
-
repository ?? (repoDir ? `https://github.com/${
|
|
7740
|
+
repository ?? (repoDir ? `https://github.com/${basename2(dirname8(repoDir))}/${basename2(repoDir)}` : "")
|
|
5304
7741
|
);
|
|
5305
7742
|
if (!workBranch || !repoDir || !repo) return "";
|
|
5306
7743
|
const res = await publishEvidence({ repoDir, worktree: cwd, workBranch, repo });
|
|
@@ -5425,10 +7862,10 @@ ${text}` : text;
|
|
|
5425
7862
|
await this.endTurn({ text: null, isError: true, subtype: "interrupted" });
|
|
5426
7863
|
return;
|
|
5427
7864
|
}
|
|
5428
|
-
const
|
|
5429
|
-
|
|
5430
|
-
|
|
5431
|
-
);
|
|
7865
|
+
const stderr = this.deps.environment?.redactor.redactWindow(this.stderrTail, this.stderrCut);
|
|
7866
|
+
const tail = scrubSecrets(
|
|
7867
|
+
(stderr ?? this.stderrTail).trim().split("\n").slice(-3).join(" ")
|
|
7868
|
+
).slice(0, 400);
|
|
5432
7869
|
const how = signal ? `was killed (${signal})` : `exited with code ${code}`;
|
|
5433
7870
|
const hint = this.sawResultSinceSpawn ? "" : this.driver.startupHint(this.stderrTail);
|
|
5434
7871
|
if (!this.sawResultSinceSpawn && this.driver.looksLikeSignInFailure(this.stderrTail)) {
|
|
@@ -5451,8 +7888,8 @@ ${text}` : text;
|
|
|
5451
7888
|
};
|
|
5452
7889
|
async function raceTimeout(done, ms) {
|
|
5453
7890
|
let timer;
|
|
5454
|
-
const timeout = new Promise((
|
|
5455
|
-
timer = setTimeout(() =>
|
|
7891
|
+
const timeout = new Promise((resolve4) => {
|
|
7892
|
+
timer = setTimeout(() => resolve4(true), ms);
|
|
5456
7893
|
});
|
|
5457
7894
|
try {
|
|
5458
7895
|
return await Promise.race([done.then(() => false), timeout]);
|
|
@@ -5502,6 +7939,23 @@ var SessionManager = class {
|
|
|
5502
7939
|
resuming = /* @__PURE__ */ new Set();
|
|
5503
7940
|
store;
|
|
5504
7941
|
shuttingDown = false;
|
|
7942
|
+
/** Writes of `kept-for-jobs.json`, one after another. */
|
|
7943
|
+
keptChain = Promise.resolve();
|
|
7944
|
+
/**
|
|
7945
|
+
* A release of the folders kept for jobs came while a session was starting, and waits for
|
|
7946
|
+
* the starts to end: a start may be about to continue in one of those folders.
|
|
7947
|
+
*/
|
|
7948
|
+
releaseDeferred = false;
|
|
7949
|
+
/** The release of kept folders under way: a session start waits for it to be through. */
|
|
7950
|
+
releasing = null;
|
|
7951
|
+
/** A release was asked for while one was under way: it makes one more pass. */
|
|
7952
|
+
releaseAgain = false;
|
|
7953
|
+
/**
|
|
7954
|
+
* Working copies of a run's earlier sessions that a start with `resume.keepWorkspace` is
|
|
7955
|
+
* taking over (by folder, the starting session's id): closing their session neither moves
|
|
7956
|
+
* nor removes them. Set from the start's first step until it is through.
|
|
7957
|
+
*/
|
|
7958
|
+
takenOver = /* @__PURE__ */ new Map();
|
|
5505
7959
|
/** Loads sessions a previous run left, ends turns it was in the middle of, resumes posting. */
|
|
5506
7960
|
async restore() {
|
|
5507
7961
|
for (const record of await this.store.list()) {
|
|
@@ -5539,6 +7993,20 @@ var SessionManager = class {
|
|
|
5539
7993
|
get(sessionId) {
|
|
5540
7994
|
return this.sessions.get(sessionId);
|
|
5541
7995
|
}
|
|
7996
|
+
/**
|
|
7997
|
+
* A job command (`jobCommands` on the poll). Jobs belong to no session: they run apart
|
|
7998
|
+
* from every session, its limit and its idle stop, and outlive the session that asked
|
|
7999
|
+
* for them.
|
|
8000
|
+
*/
|
|
8001
|
+
async handleJob(cmd) {
|
|
8002
|
+
if (!this.opts.jobs) return { ok: false, error: "This runner does not run jobs." };
|
|
8003
|
+
try {
|
|
8004
|
+
return await this.opts.jobs.handle(cmd);
|
|
8005
|
+
} catch (err) {
|
|
8006
|
+
const redactor = cmd.type === "start_job" || cmd.type === "job_secrets" ? sessionEnvironment(cmd.environment)?.redactor : null;
|
|
8007
|
+
return { ok: false, error: safeError2(err, redactor) };
|
|
8008
|
+
}
|
|
8009
|
+
}
|
|
5542
8010
|
async handle(cmd) {
|
|
5543
8011
|
try {
|
|
5544
8012
|
assertSafeSessionId(cmd.sessionId);
|
|
@@ -5563,8 +8031,10 @@ var SessionManager = class {
|
|
|
5563
8031
|
};
|
|
5564
8032
|
}
|
|
5565
8033
|
} catch (err) {
|
|
5566
|
-
|
|
5567
|
-
|
|
8034
|
+
if (cmd.type !== "start_session") return { ok: false, error: safeError2(err) };
|
|
8035
|
+
const redactor = sessionEnvironment(cmd.environment)?.redactor;
|
|
8036
|
+
const error = safeError2(err, redactor);
|
|
8037
|
+
return this.noteStart(cmd.sessionId, { ok: false, error });
|
|
5568
8038
|
}
|
|
5569
8039
|
}
|
|
5570
8040
|
noteStart(sessionId, ack) {
|
|
@@ -5620,11 +8090,21 @@ var SessionManager = class {
|
|
|
5620
8090
|
error: `The runner is busy: it is already running ${max} session(s).`
|
|
5621
8091
|
};
|
|
5622
8092
|
}
|
|
5623
|
-
const promise = this.startSession(cmd).finally(() =>
|
|
8093
|
+
const promise = this.startSession(cmd).finally(() => {
|
|
8094
|
+
this.starting.delete(cmd.sessionId);
|
|
8095
|
+
for (const [cwd, holder] of this.takenOver) {
|
|
8096
|
+
if (holder === cmd.sessionId) this.takenOver.delete(cwd);
|
|
8097
|
+
}
|
|
8098
|
+
if (this.releaseDeferred && this.starting.size === 0) {
|
|
8099
|
+
this.releaseDeferred = false;
|
|
8100
|
+
void this.releaseKeptForJobs();
|
|
8101
|
+
}
|
|
8102
|
+
});
|
|
5624
8103
|
this.starting.set(cmd.sessionId, promise);
|
|
5625
8104
|
return promise;
|
|
5626
8105
|
}
|
|
5627
8106
|
async startSession(cmd) {
|
|
8107
|
+
await this.releasing?.catch(() => void 0);
|
|
5628
8108
|
const label = cmd.title ? `"${cmd.title.slice(0, 80)}"` : `run ${cmd.runId}`;
|
|
5629
8109
|
this.opts.logger.info(`session ${cmd.sessionId}: starting ${label}`, {
|
|
5630
8110
|
repo: cmd.repository?.url,
|
|
@@ -5638,17 +8118,41 @@ var SessionManager = class {
|
|
|
5638
8118
|
);
|
|
5639
8119
|
}
|
|
5640
8120
|
const resume = cmd.resume ?? null;
|
|
8121
|
+
const keepWorkspace = resume?.keepWorkspace === true;
|
|
8122
|
+
const earlier = [];
|
|
5641
8123
|
if (resume) {
|
|
5642
8124
|
for (const other of [...this.sessions.values()]) {
|
|
5643
|
-
if (other.record.runId
|
|
8125
|
+
if (other.record.runId !== cmd.runId || other.sessionId === cmd.sessionId) continue;
|
|
8126
|
+
if (!keepWorkspace) {
|
|
5644
8127
|
await this.close(other.sessionId);
|
|
8128
|
+
continue;
|
|
5645
8129
|
}
|
|
8130
|
+
if (other.record.cwd) this.takenOver.set(other.record.cwd, cmd.sessionId);
|
|
8131
|
+
earlier.push(other);
|
|
8132
|
+
await other.stop("idle");
|
|
5646
8133
|
}
|
|
5647
8134
|
await Promise.allSettled([...this.closing.values()]);
|
|
5648
8135
|
this.opts.logger.info(`session ${cmd.sessionId}: continuing run ${cmd.runId}`, {
|
|
5649
|
-
resume: resume.conversationId ?? resume.claudeSessionId ? "conversation" : "fresh"
|
|
8136
|
+
resume: resume.conversationId ?? resume.claudeSessionId ? "conversation" : "fresh",
|
|
8137
|
+
...keepWorkspace ? { keepWorkspace: true } : {}
|
|
5650
8138
|
});
|
|
5651
8139
|
}
|
|
8140
|
+
const environment = sessionEnvironment(cmd.environment);
|
|
8141
|
+
if (environment) {
|
|
8142
|
+
this.opts.logger.info(
|
|
8143
|
+
`session ${cmd.sessionId}: the run's environment sets ${environment.names.length} variable(s), ${environment.secretNames.length} of them secret`
|
|
8144
|
+
);
|
|
8145
|
+
if (environment.unredacted.length) {
|
|
8146
|
+
this.opts.logger.warn(
|
|
8147
|
+
`session ${cmd.sessionId}: ${environment.unredacted.join(", ")} ${environment.unredacted.length === 1 ? "is" : "are"} too short to be redacted from what the session posts (under ${SECRET_REDACTION_MIN_LENGTH} characters)`
|
|
8148
|
+
);
|
|
8149
|
+
}
|
|
8150
|
+
if (environment.skipped.length) {
|
|
8151
|
+
this.opts.logger.warn(
|
|
8152
|
+
`session ${cmd.sessionId}: left out of the agent's environment (not a name it may set): ${environment.skipped.slice(0, 20).join(", ")}`
|
|
8153
|
+
);
|
|
8154
|
+
}
|
|
8155
|
+
}
|
|
5652
8156
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
5653
8157
|
const record = {
|
|
5654
8158
|
sessionId: cmd.sessionId,
|
|
@@ -5667,11 +8171,23 @@ var SessionManager = class {
|
|
|
5667
8171
|
...alwaysAllowTools(cmd).length ? { alwaysAllowedTools: alwaysAllowTools(cmd) } : {},
|
|
5668
8172
|
...cmd.reportToolDenials === true ? { reportToolDenials: true } : {},
|
|
5669
8173
|
...grantRules(cmd).length ? { grantRules: grantRules(cmd) } : {},
|
|
8174
|
+
...environment?.names.length ? { environmentNames: environment.names } : {},
|
|
5670
8175
|
createdAt: now,
|
|
5671
8176
|
updatedAt: now
|
|
5672
8177
|
};
|
|
5673
8178
|
try {
|
|
5674
8179
|
if (cmd.repository) {
|
|
8180
|
+
const holds = /* @__PURE__ */ new Map();
|
|
8181
|
+
const claim = (dir) => {
|
|
8182
|
+
if (!holds.get(dir)) {
|
|
8183
|
+
holds.set(dir, this.opts.jobs ? this.opts.jobs.holdForRemoval(dir) : () => void 0);
|
|
8184
|
+
}
|
|
8185
|
+
return holds.get(dir) ?? null;
|
|
8186
|
+
};
|
|
8187
|
+
const keptWorktreeMark = (dir) => {
|
|
8188
|
+
const from = keepWorkspace ? earlier.find((o) => o.record.cwd === dir) : void 0;
|
|
8189
|
+
return from ? from.record.keepWorktree === true : true;
|
|
8190
|
+
};
|
|
5675
8191
|
const wt = await prepareWorktree({
|
|
5676
8192
|
url: cmd.repository.url,
|
|
5677
8193
|
baseRef: cmd.repository.baseRef,
|
|
@@ -5681,8 +8197,13 @@ var SessionManager = class {
|
|
|
5681
8197
|
sessionId: cmd.sessionId,
|
|
5682
8198
|
protocol: this.opts.config.gitProtocol,
|
|
5683
8199
|
continueBranch: !!resume,
|
|
5684
|
-
worktreeKey: resume ? safeWorktreeKey(resume.worktreeKey, cmd.sessionId) : null
|
|
8200
|
+
worktreeKey: resume ? safeWorktreeKey(resume.worktreeKey, cmd.sessionId) : null,
|
|
8201
|
+
inUse: (dir) => claim(dir) === null,
|
|
8202
|
+
keepWorkspace
|
|
8203
|
+
}).finally(() => {
|
|
8204
|
+
for (const release of holds.values()) release?.();
|
|
5685
8205
|
});
|
|
8206
|
+
await this.unkeep(wt.worktree);
|
|
5686
8207
|
Object.assign(record, {
|
|
5687
8208
|
cwd: wt.worktree,
|
|
5688
8209
|
repoDir: wt.repoDir,
|
|
@@ -5693,13 +8214,31 @@ var SessionManager = class {
|
|
|
5693
8214
|
baseSha: wt.baseSha,
|
|
5694
8215
|
// A reused kept worktree still holds the uncommitted changes it was kept for: keep
|
|
5695
8216
|
// protecting it until a turn commits them, or a close before then would delete them.
|
|
5696
|
-
|
|
8217
|
+
// One continued in for a job is the earlier session's as it was: its mark carries over.
|
|
8218
|
+
...wt.continuedFrom === "worktree" && keptWorktreeMark(wt.worktree) ? { keepWorktree: true } : {}
|
|
5697
8219
|
});
|
|
5698
|
-
if (wt.leftInPlace) {
|
|
8220
|
+
if (wt.leftInPlace && keepWorkspace) {
|
|
8221
|
+
this.opts.logger.info(
|
|
8222
|
+
`session ${cmd.sessionId}: the earlier working copy at ${wt.leftInPlace} is kept for the run's job and cannot be continued in as it is (not on ${cmd.repository.workBranch}, or behind what was pushed); left as it is, and this session works in ${wt.worktree}`
|
|
8223
|
+
);
|
|
8224
|
+
if (!earlier.some((o) => o.record.cwd === wt.leftInPlace)) {
|
|
8225
|
+
await this.keep({
|
|
8226
|
+
sessionId: safeWorktreeKey(resume?.worktreeKey, cmd.sessionId),
|
|
8227
|
+
cwd: wt.leftInPlace,
|
|
8228
|
+
repoDir: wt.repoDir,
|
|
8229
|
+
heldBy: cmd.sessionId
|
|
8230
|
+
});
|
|
8231
|
+
}
|
|
8232
|
+
} else if (wt.leftInPlace) {
|
|
5699
8233
|
this.opts.logger.warn(
|
|
5700
8234
|
`session ${cmd.sessionId}: the earlier working copy at ${wt.leftInPlace} is in use (close any terminal, editor or program open in it) and was left as it is; this session works in ${wt.worktree}`
|
|
5701
8235
|
);
|
|
5702
8236
|
}
|
|
8237
|
+
if (wt.keptRef) {
|
|
8238
|
+
this.opts.logger.warn(
|
|
8239
|
+
`session ${cmd.sessionId}: the work branch had commits only this computer has; they are kept as ${wt.keptRef} in ${wt.repoDir}, and this session starts from the branch as pushed`
|
|
8240
|
+
);
|
|
8241
|
+
}
|
|
5703
8242
|
if (wt.setAside) {
|
|
5704
8243
|
this.opts.logger.warn(
|
|
5705
8244
|
`session ${cmd.sessionId}: an earlier working copy with uncommitted changes could not be reused; it was moved to ${wt.setAside}`
|
|
@@ -5709,21 +8248,47 @@ var SessionManager = class {
|
|
|
5709
8248
|
record.cwd = this.store.scratchDir(
|
|
5710
8249
|
resume ? safeWorktreeKey(resume.worktreeKey, cmd.sessionId) : cmd.sessionId
|
|
5711
8250
|
);
|
|
5712
|
-
await
|
|
8251
|
+
const keptEntry = keepWorkspace ? await this.keptEntry(record.cwd) : null;
|
|
8252
|
+
await this.unkeep(record.cwd);
|
|
8253
|
+
await mkdir9(record.cwd, { recursive: true });
|
|
5713
8254
|
if (cmd.reviewImages === true && this.opts.reviewImageUploader) {
|
|
5714
8255
|
record.reviewImages = true;
|
|
5715
|
-
await
|
|
8256
|
+
await mkdir9(join15(record.cwd, EVIDENCE_DIR), { recursive: true });
|
|
5716
8257
|
}
|
|
5717
8258
|
const reference = cmd.referenceRepository;
|
|
5718
|
-
|
|
8259
|
+
const referenceDir = join15(record.cwd, RUNNER_REFERENCE_REPOSITORY_DIR);
|
|
8260
|
+
const fromEntry = keptEntry?.reference;
|
|
8261
|
+
const entryUrl = () => fromEntry ? fromEntry.url ?? legacyUrl(fromEntry, this.opts.config.reposDir) : null;
|
|
8262
|
+
const fromSession = keepWorkspace ? earlier.find((o) => o.record.cwd === record.cwd)?.record.referenceRepository : void 0;
|
|
8263
|
+
const url = keepWorkspace && !fromSession ? entryUrl() : null;
|
|
8264
|
+
const candidate = !keepWorkspace ? void 0 : fromSession ?? (fromEntry && url ? {
|
|
8265
|
+
url,
|
|
8266
|
+
// Unknown for an older runner's entry: the preface then names no ref.
|
|
8267
|
+
baseRef: fromEntry.baseRef ?? "",
|
|
8268
|
+
dir: fromEntry.dir,
|
|
8269
|
+
repoDir: fromEntry.repoDir
|
|
8270
|
+
} : void 0);
|
|
8271
|
+
const keptReference = candidate && existsSync(candidate.dir) ? candidate : void 0;
|
|
8272
|
+
const referenceHold = !reference?.url ? null : this.opts.jobs ? this.opts.jobs.holdForRemoval(referenceDir) : () => void 0;
|
|
8273
|
+
if (reference?.url && keepWorkspace && (keptReference || existsSync(referenceDir))) {
|
|
8274
|
+
if (keptReference) record.referenceRepository = keptReference;
|
|
8275
|
+
referenceHold?.();
|
|
8276
|
+
this.opts.logger.info(
|
|
8277
|
+
`session ${cmd.sessionId}: the repository in ${referenceDir} is kept for the run's job, so it is left as it is`
|
|
8278
|
+
);
|
|
8279
|
+
} else if (reference?.url && !referenceHold) {
|
|
8280
|
+
this.opts.logger.warn(
|
|
8281
|
+
`session ${cmd.sessionId}: a job runs in ${referenceDir}, so the repository there is left as it is`
|
|
8282
|
+
);
|
|
8283
|
+
} else if (reference?.url) {
|
|
5719
8284
|
try {
|
|
5720
8285
|
const checkout = await prepareReferenceCheckout({
|
|
5721
8286
|
url: reference.url,
|
|
5722
8287
|
baseRef: reference.baseRef ?? null,
|
|
5723
8288
|
reposDir: this.opts.config.reposDir,
|
|
5724
|
-
dir:
|
|
8289
|
+
dir: join15(record.cwd, RUNNER_REFERENCE_REPOSITORY_DIR),
|
|
5725
8290
|
protocol: this.opts.config.gitProtocol
|
|
5726
|
-
});
|
|
8291
|
+
}).finally(() => referenceHold?.());
|
|
5727
8292
|
record.referenceRepository = {
|
|
5728
8293
|
url: reference.url,
|
|
5729
8294
|
baseRef: checkout.baseRef,
|
|
@@ -5733,13 +8298,13 @@ var SessionManager = class {
|
|
|
5733
8298
|
} catch (err) {
|
|
5734
8299
|
this.opts.logger.warn(
|
|
5735
8300
|
`session ${cmd.sessionId}: could not check out ${reference.url} for the agent to read; it works without it`,
|
|
5736
|
-
{ error:
|
|
8301
|
+
{ error: safeError2(err, environment?.redactor) }
|
|
5737
8302
|
);
|
|
5738
8303
|
}
|
|
5739
8304
|
}
|
|
5740
8305
|
const deliverable = resume?.deliverable;
|
|
5741
8306
|
if (typeof deliverable === "string" && deliverable.trim()) {
|
|
5742
|
-
await
|
|
8307
|
+
await writeFile6(join15(record.cwd, RUNNER_DELIVERABLE_FILE), deliverable, "utf8");
|
|
5743
8308
|
}
|
|
5744
8309
|
}
|
|
5745
8310
|
if (resume) {
|
|
@@ -5748,19 +8313,21 @@ var SessionManager = class {
|
|
|
5748
8313
|
}
|
|
5749
8314
|
await this.store.save(record);
|
|
5750
8315
|
} catch (err) {
|
|
8316
|
+
const error = safeError2(err, environment?.redactor);
|
|
5751
8317
|
this.opts.logger.error(`session ${cmd.sessionId}: could not prepare the workspace`, {
|
|
5752
|
-
error
|
|
8318
|
+
error
|
|
5753
8319
|
});
|
|
5754
8320
|
await this.store.remove(cmd.sessionId).catch(() => void 0);
|
|
5755
|
-
return { ok: false, error
|
|
8321
|
+
return { ok: false, error };
|
|
5756
8322
|
}
|
|
5757
|
-
const session = await this.openSession(record);
|
|
8323
|
+
const session = await this.openSession(record, environment);
|
|
5758
8324
|
this.sessions.set(cmd.sessionId, session);
|
|
8325
|
+
for (const other of earlier) await this.close(other.sessionId);
|
|
5759
8326
|
if (resume) return { ok: true };
|
|
5760
8327
|
try {
|
|
5761
8328
|
await session.startFirstTurn(await this.promptWithImages(cmd, record));
|
|
5762
8329
|
} catch (err) {
|
|
5763
|
-
const message =
|
|
8330
|
+
const message = safeError2(err, environment?.redactor);
|
|
5764
8331
|
this.opts.logger.error(`session ${cmd.sessionId}: ${message}`);
|
|
5765
8332
|
session.emit(
|
|
5766
8333
|
{ type: "error", message, retryable: false },
|
|
@@ -5768,7 +8335,7 @@ var SessionManager = class {
|
|
|
5768
8335
|
);
|
|
5769
8336
|
await this.forgetFailedStart(session).catch(
|
|
5770
8337
|
(e) => this.opts.logger.warn(`session ${cmd.sessionId}: could not clean up the failed start`, {
|
|
5771
|
-
error:
|
|
8338
|
+
error: safeError2(e, environment?.redactor)
|
|
5772
8339
|
})
|
|
5773
8340
|
);
|
|
5774
8341
|
return { ok: false, error: message };
|
|
@@ -5921,7 +8488,7 @@ var SessionManager = class {
|
|
|
5921
8488
|
});
|
|
5922
8489
|
} catch (err) {
|
|
5923
8490
|
this.opts.logger.warn(`session ${cmd.sessionId}: could not save the task's images`, {
|
|
5924
|
-
error:
|
|
8491
|
+
error: safeError2(err)
|
|
5925
8492
|
});
|
|
5926
8493
|
}
|
|
5927
8494
|
}
|
|
@@ -5944,32 +8511,186 @@ var SessionManager = class {
|
|
|
5944
8511
|
await session.stop("close");
|
|
5945
8512
|
await this.opts.beforeWorktreeRemoved?.(sessionId);
|
|
5946
8513
|
const { record } = session;
|
|
5947
|
-
|
|
8514
|
+
const workspace = {
|
|
8515
|
+
sessionId,
|
|
8516
|
+
cwd: record.cwd,
|
|
8517
|
+
repoDir: record.repoDir,
|
|
8518
|
+
reference: record.referenceRepository ? {
|
|
8519
|
+
repoDir: record.referenceRepository.repoDir,
|
|
8520
|
+
dir: record.referenceRepository.dir,
|
|
8521
|
+
url: record.referenceRepository.url,
|
|
8522
|
+
baseRef: record.referenceRepository.baseRef
|
|
8523
|
+
} : null
|
|
8524
|
+
};
|
|
8525
|
+
const holder = record.cwd ? this.takenOver.get(record.cwd) : void 0;
|
|
8526
|
+
if (holder) {
|
|
8527
|
+
await this.rehold(sessionId, holder);
|
|
8528
|
+
if (this.sessions.get(holder)?.record.cwd === record.cwd) {
|
|
8529
|
+
this.opts.logger.info(`session ${sessionId}: session ${holder} continues in ${record.cwd}`);
|
|
8530
|
+
} else {
|
|
8531
|
+
const uncommitted = !!record.repoDir && record.keepWorktree === true;
|
|
8532
|
+
if (uncommitted) {
|
|
8533
|
+
this.opts.logger.warn(
|
|
8534
|
+
`session ${sessionId}: keeping the worktree ${record.cwd}, which holds changes that could not be committed; session ${holder} works elsewhere`
|
|
8535
|
+
);
|
|
8536
|
+
} else {
|
|
8537
|
+
this.opts.logger.info(
|
|
8538
|
+
`session ${sessionId}: keeping ${record.cwd}, which the run's job may use, until session ${holder} closes`
|
|
8539
|
+
);
|
|
8540
|
+
}
|
|
8541
|
+
await this.keep({ ...workspace, heldBy: holder, ...uncommitted ? { uncommitted } : {} });
|
|
8542
|
+
}
|
|
8543
|
+
} else if (record.repoDir && record.keepWorktree) {
|
|
5948
8544
|
this.opts.logger.warn(
|
|
5949
8545
|
`session ${sessionId}: keeping the worktree ${record.cwd}, which holds changes that could not be committed`
|
|
5950
8546
|
);
|
|
5951
|
-
} else if (
|
|
5952
|
-
|
|
5953
|
-
|
|
5954
|
-
|
|
8547
|
+
} else if (!await this.removeUnlessInUse(workspace)) {
|
|
8548
|
+
this.opts.logger.info(
|
|
8549
|
+
`session ${sessionId}: keeping ${record.cwd} while a job runs in it; it is removed once the job ends`
|
|
8550
|
+
);
|
|
8551
|
+
await this.keep(workspace);
|
|
8552
|
+
}
|
|
8553
|
+
await session.outbox.settled();
|
|
8554
|
+
await this.store.remove(sessionId);
|
|
8555
|
+
this.opts.logger.info(`session ${sessionId}: closed`);
|
|
8556
|
+
void this.releaseKeptForJobs();
|
|
8557
|
+
}
|
|
8558
|
+
/**
|
|
8559
|
+
* Removes the workspace unless a job runs in it (false then: it is to be kept). The check
|
|
8560
|
+
* and the claim are one step (`holdForRemoval`), and no job starts in it while it goes.
|
|
8561
|
+
*/
|
|
8562
|
+
async removeUnlessInUse(w) {
|
|
8563
|
+
const jobs = this.opts.jobs;
|
|
8564
|
+
const hold = jobs && w.cwd ? jobs.holdForRemoval(w.cwd) : () => void 0;
|
|
8565
|
+
if (!hold) return false;
|
|
8566
|
+
try {
|
|
8567
|
+
await this.removeWorkspace(w);
|
|
8568
|
+
} finally {
|
|
8569
|
+
hold();
|
|
8570
|
+
}
|
|
8571
|
+
return true;
|
|
8572
|
+
}
|
|
8573
|
+
/** Removes a closed session's worktree (the branch stays) or scratch folder. */
|
|
8574
|
+
async removeWorkspace(w) {
|
|
8575
|
+
if (w.repoDir) {
|
|
8576
|
+
await removeWorktree(w.repoDir, w.cwd).catch(
|
|
8577
|
+
(err) => this.opts.logger.warn(`session ${w.sessionId}: could not remove the worktree`, {
|
|
8578
|
+
error: safeError2(err)
|
|
5955
8579
|
})
|
|
5956
8580
|
);
|
|
5957
|
-
} else if (
|
|
5958
|
-
if (
|
|
5959
|
-
await removeWorktree(
|
|
5960
|
-
|
|
5961
|
-
|
|
5962
|
-
).catch(
|
|
5963
|
-
(err) => this.opts.logger.warn(`session ${sessionId}: could not remove the checkout it read`, {
|
|
5964
|
-
error: safeError(err)
|
|
8581
|
+
} else if (w.cwd) {
|
|
8582
|
+
if (w.reference) {
|
|
8583
|
+
await removeWorktree(w.reference.repoDir, w.reference.dir).catch(
|
|
8584
|
+
(err) => this.opts.logger.warn(`session ${w.sessionId}: could not remove the checkout it read`, {
|
|
8585
|
+
error: safeError2(err)
|
|
5965
8586
|
})
|
|
5966
8587
|
);
|
|
5967
8588
|
}
|
|
5968
|
-
await
|
|
8589
|
+
await rm7(w.cwd, { recursive: true, force: true }).catch(() => void 0);
|
|
8590
|
+
}
|
|
8591
|
+
}
|
|
8592
|
+
keptFile() {
|
|
8593
|
+
return join15(this.opts.config.stateDir, "kept-for-jobs.json");
|
|
8594
|
+
}
|
|
8595
|
+
/** The entry kept for `cwd` in `kept-for-jobs.json`, if any. */
|
|
8596
|
+
async keptEntry(cwd) {
|
|
8597
|
+
await this.keptChain;
|
|
8598
|
+
const saved = await readJson(this.keptFile()).catch(() => null);
|
|
8599
|
+
return (Array.isArray(saved) ? saved : []).find((k) => k.cwd === cwd) ?? null;
|
|
8600
|
+
}
|
|
8601
|
+
/** Changes the list of workspaces kept for jobs, one change at a time. */
|
|
8602
|
+
changeKept(change) {
|
|
8603
|
+
const run = this.keptChain.then(async () => {
|
|
8604
|
+
const saved = await readJson(this.keptFile()).catch(() => null);
|
|
8605
|
+
const before = Array.isArray(saved) ? saved : [];
|
|
8606
|
+
const { list, result } = await change(before);
|
|
8607
|
+
if (list.length !== before.length || list.some((w, i) => w !== before[i])) {
|
|
8608
|
+
await writeJsonAtomic(this.keptFile(), list);
|
|
8609
|
+
}
|
|
8610
|
+
return result;
|
|
8611
|
+
});
|
|
8612
|
+
this.keptChain = run.catch(() => void 0);
|
|
8613
|
+
return run;
|
|
8614
|
+
}
|
|
8615
|
+
keep(w) {
|
|
8616
|
+
return this.changeKept(async (list) => {
|
|
8617
|
+
const was = list.find((k) => k.cwd === w.cwd);
|
|
8618
|
+
const entry = was?.uncommitted && !w.uncommitted ? { ...w, uncommitted: true } : w;
|
|
8619
|
+
return { list: [...list.filter((k) => k.cwd !== w.cwd), entry], result: void 0 };
|
|
8620
|
+
}).catch(
|
|
8621
|
+
(err) => this.opts.logger.warn(`session ${w.sessionId}: could not note the worktree kept for a job`, {
|
|
8622
|
+
error: safeError2(err)
|
|
8623
|
+
})
|
|
8624
|
+
);
|
|
8625
|
+
}
|
|
8626
|
+
/** Folders kept until `from` closed are kept until `to` closes instead. */
|
|
8627
|
+
rehold(from, to) {
|
|
8628
|
+
return this.changeKept(async (list) => ({
|
|
8629
|
+
list: list.map((k) => k.heldBy === from ? { ...k, heldBy: to } : k),
|
|
8630
|
+
result: void 0
|
|
8631
|
+
})).catch(
|
|
8632
|
+
(err) => this.opts.logger.warn(
|
|
8633
|
+
`session ${from}: could not hand the folders it kept over to session ${to}`,
|
|
8634
|
+
{ error: safeError2(err) }
|
|
8635
|
+
)
|
|
8636
|
+
);
|
|
8637
|
+
}
|
|
8638
|
+
/** A session now works in `cwd` again: it is no longer kept for a job. */
|
|
8639
|
+
unkeep(cwd) {
|
|
8640
|
+
return this.changeKept(async (list) => ({
|
|
8641
|
+
list: list.filter((k) => k.cwd !== cwd),
|
|
8642
|
+
result: void 0
|
|
8643
|
+
})).catch(() => void 0);
|
|
8644
|
+
}
|
|
8645
|
+
/**
|
|
8646
|
+
* Removes the closed sessions' worktrees kept for jobs that no job runs in any more (a job
|
|
8647
|
+
* ended, or the runner restarted and the job is gone). Never rejects.
|
|
8648
|
+
*/
|
|
8649
|
+
async releaseKeptForJobs() {
|
|
8650
|
+
if (this.starting.size > 0) {
|
|
8651
|
+
this.releaseDeferred = true;
|
|
8652
|
+
return;
|
|
8653
|
+
}
|
|
8654
|
+
if (this.releasing) {
|
|
8655
|
+
this.releaseAgain = true;
|
|
8656
|
+
return this.releasing;
|
|
8657
|
+
}
|
|
8658
|
+
this.releasing = (async () => {
|
|
8659
|
+
do {
|
|
8660
|
+
this.releaseAgain = false;
|
|
8661
|
+
await this.release();
|
|
8662
|
+
} while (this.releaseAgain && this.starting.size === 0);
|
|
8663
|
+
if (this.releaseAgain) this.releaseDeferred = true;
|
|
8664
|
+
})().finally(() => this.releasing = null);
|
|
8665
|
+
return this.releasing;
|
|
8666
|
+
}
|
|
8667
|
+
async release() {
|
|
8668
|
+
const free = await this.changeKept(async (list) => {
|
|
8669
|
+
const worked = (w) => [...this.sessions.values()].some((s) => s.record.cwd === w.cwd);
|
|
8670
|
+
const kept = list.filter((w) => !worked(w) && w.uncommitted === true && !gone(w.cwd));
|
|
8671
|
+
const rest = list.filter((w) => !worked(w) && !kept.includes(w));
|
|
8672
|
+
const held = (w) => !!w.heldBy && (this.sessions.has(w.heldBy) || this.starting.has(w.heldBy));
|
|
8673
|
+
const mine = rest.filter((w) => !held(w));
|
|
8674
|
+
const used = mine.map((w) => this.opts.jobs?.usesPath(w.cwd) ?? false);
|
|
8675
|
+
return {
|
|
8676
|
+
list: [...kept, ...rest.filter(held), ...mine.filter((_, i) => used[i])],
|
|
8677
|
+
result: mine.filter((_, i) => !used[i])
|
|
8678
|
+
};
|
|
8679
|
+
}).catch(() => []);
|
|
8680
|
+
for (const [i, w] of free.entries()) {
|
|
8681
|
+
if (this.starting.size > 0) {
|
|
8682
|
+
for (const rest of free.slice(i)) await this.keep(rest);
|
|
8683
|
+
this.releaseDeferred = true;
|
|
8684
|
+
return;
|
|
8685
|
+
}
|
|
8686
|
+
if (await this.removeUnlessInUse(w)) {
|
|
8687
|
+
this.opts.logger.info(
|
|
8688
|
+
`session ${w.sessionId}: no job ran in ${w.cwd} any more; removed it`
|
|
8689
|
+
);
|
|
8690
|
+
} else {
|
|
8691
|
+
await this.keep(w);
|
|
8692
|
+
}
|
|
5969
8693
|
}
|
|
5970
|
-
await session.outbox.settled();
|
|
5971
|
-
await this.store.remove(sessionId);
|
|
5972
|
-
this.opts.logger.info(`session ${sessionId}: closed`);
|
|
5973
8694
|
}
|
|
5974
8695
|
/** Ends Claude Code processes that have been idle too long; their sessions stay resumable. */
|
|
5975
8696
|
async stopIdle(now = Date.now()) {
|
|
@@ -6019,7 +8740,8 @@ var SessionManager = class {
|
|
|
6019
8740
|
driverFor(kind) {
|
|
6020
8741
|
return this.opts.driver ?? agentDriver(kind);
|
|
6021
8742
|
}
|
|
6022
|
-
|
|
8743
|
+
/** `environment`: a start's, in memory; none for a session restored from disk. */
|
|
8744
|
+
async openSession(record, environment = null) {
|
|
6023
8745
|
const outbox = await SessionOutbox.open({
|
|
6024
8746
|
sessionId: record.sessionId,
|
|
6025
8747
|
file: this.store.outboxFile(record.sessionId),
|
|
@@ -6054,7 +8776,8 @@ var SessionManager = class {
|
|
|
6054
8776
|
permissionTimeoutMs: this.opts.permissionTimeoutMs,
|
|
6055
8777
|
savedRules: async (url) => this.opts.grants ? await this.opts.grants.rulesFor(url) : [],
|
|
6056
8778
|
reviewImageUploader: this.opts.reviewImageUploader,
|
|
6057
|
-
inheritedRules: this.opts.inherited ? (url) => this.opts.inherited.rulesFor(url) : void 0
|
|
8779
|
+
inheritedRules: this.opts.inherited ? (url) => this.opts.inherited.rulesFor(url) : void 0,
|
|
8780
|
+
environment
|
|
6058
8781
|
});
|
|
6059
8782
|
}
|
|
6060
8783
|
};
|
|
@@ -6076,6 +8799,20 @@ function alwaysAllowTools(cmd) {
|
|
|
6076
8799
|
)
|
|
6077
8800
|
];
|
|
6078
8801
|
}
|
|
8802
|
+
function legacyUrl(entry, reposDir) {
|
|
8803
|
+
const repoDir = resolve3(entry.repoDir);
|
|
8804
|
+
if (!samePath(dirname9(dirname9(repoDir)), reposDir)) return null;
|
|
8805
|
+
const url = `https://github.com/${basename3(dirname9(repoDir))}/${basename3(repoDir)}`;
|
|
8806
|
+
return parseRepoUrl(url) ? url : null;
|
|
8807
|
+
}
|
|
8808
|
+
function gone(path) {
|
|
8809
|
+
try {
|
|
8810
|
+
lstatSync(path);
|
|
8811
|
+
return false;
|
|
8812
|
+
} catch (err) {
|
|
8813
|
+
return err.code === "ENOENT";
|
|
8814
|
+
}
|
|
8815
|
+
}
|
|
6079
8816
|
function safeWorktreeKey(key, fallback) {
|
|
6080
8817
|
if (!key) return fallback;
|
|
6081
8818
|
try {
|
|
@@ -6097,8 +8834,9 @@ ${task.slice(0, 2e4)}` : "",
|
|
|
6097
8834
|
"The person\u2019s message follows."
|
|
6098
8835
|
].filter(Boolean).join("\n\n");
|
|
6099
8836
|
}
|
|
6100
|
-
function
|
|
6101
|
-
|
|
8837
|
+
function safeError2(err, redactor) {
|
|
8838
|
+
const raw = err instanceof Error ? err.message : String(err);
|
|
8839
|
+
return scrubSecrets(redactor ? redactor.redact(raw) : raw).slice(0, 600);
|
|
6102
8840
|
}
|
|
6103
8841
|
|
|
6104
8842
|
// src/daemon.ts
|
|
@@ -6112,6 +8850,16 @@ var RunnerDaemon = class {
|
|
|
6112
8850
|
this.opts = opts;
|
|
6113
8851
|
this.api = opts.api ?? new RunnerApi({ server: opts.config.server, token: opts.config.token });
|
|
6114
8852
|
this.grants = opts.grants ?? new ToolGrantStore(toolGrantsFile(opts.config.configFile));
|
|
8853
|
+
this.jobs = new JobManager({
|
|
8854
|
+
stateDir: opts.config.stateDir,
|
|
8855
|
+
maxJobs: opts.config.maxJobs,
|
|
8856
|
+
poster: this.api,
|
|
8857
|
+
logger: opts.logger,
|
|
8858
|
+
onUnauthorized: (err) => this.unauthorized(err),
|
|
8859
|
+
// A worktree a closed session left for a job can go once no job uses it.
|
|
8860
|
+
onJobEnded: () => void this.manager.releaseKeptForJobs(),
|
|
8861
|
+
...opts.jobOverrides
|
|
8862
|
+
});
|
|
6115
8863
|
this.manager = new SessionManager({
|
|
6116
8864
|
config: opts.config,
|
|
6117
8865
|
poster: this.api,
|
|
@@ -6123,6 +8871,7 @@ var RunnerDaemon = class {
|
|
|
6123
8871
|
grants: this.grants,
|
|
6124
8872
|
reviewImageUploader: this.api,
|
|
6125
8873
|
promptImageFetcher: this.api,
|
|
8874
|
+
jobs: this.jobs,
|
|
6126
8875
|
// What the person already allows in their own Claude Code for a repository.
|
|
6127
8876
|
inherited: opts.config.inheritClaudeCodePermissions ? new ClaudeCodeRules({
|
|
6128
8877
|
exclude: [opts.config.reposDir, opts.config.worktreesDir]
|
|
@@ -6132,6 +8881,7 @@ var RunnerDaemon = class {
|
|
|
6132
8881
|
}
|
|
6133
8882
|
api;
|
|
6134
8883
|
manager;
|
|
8884
|
+
jobs;
|
|
6135
8885
|
controller = new AbortController();
|
|
6136
8886
|
exitReason = "stopped";
|
|
6137
8887
|
agentInfo = null;
|
|
@@ -6176,15 +8926,19 @@ var RunnerDaemon = class {
|
|
|
6176
8926
|
/** Runs until stopped (signal) or the token is refused. */
|
|
6177
8927
|
async run() {
|
|
6178
8928
|
const { logger, config } = this.opts;
|
|
8929
|
+
await this.jobs.restore();
|
|
6179
8930
|
await this.manager.restore();
|
|
8931
|
+
await this.manager.releaseKeptForJobs();
|
|
6180
8932
|
logger.info(`dt-runner ${RUNNER_VERSION} connected to ${config.server}`, {
|
|
6181
8933
|
maxSessions: config.maxSessions,
|
|
8934
|
+
maxJobs: config.maxJobs,
|
|
6182
8935
|
permissionMode: config.permissionMode
|
|
6183
8936
|
});
|
|
6184
8937
|
const loops = [this.heartbeatLoop(), this.commandLoop(), this.idleLoop()];
|
|
6185
8938
|
await Promise.all(loops);
|
|
6186
8939
|
await Promise.allSettled([...this.inFlight]);
|
|
6187
8940
|
await this.manager.shutdown();
|
|
8941
|
+
await this.jobs.shutdown();
|
|
6188
8942
|
return this.exitReason;
|
|
6189
8943
|
}
|
|
6190
8944
|
/** Begins a graceful stop; `run()` resolves once sessions are wound down. */
|
|
@@ -6335,13 +9089,28 @@ var RunnerDaemon = class {
|
|
|
6335
9089
|
// And saves the images a prompt names as files for its agent (`promptImages`).
|
|
6336
9090
|
receivesPromptImages: true,
|
|
6337
9091
|
// And checks out a non-code task's repository for it to read (`referenceRepository`).
|
|
6338
|
-
checksOutReferenceRepository: true
|
|
9092
|
+
checksOutReferenceRepository: true,
|
|
9093
|
+
// And sets the run's variables and secrets for its agent (`environment`), in
|
|
9094
|
+
// memory only, redacting the secrets from what it posts.
|
|
9095
|
+
receivesEnvironment: true,
|
|
9096
|
+
// And runs jobs outside any session; with it, `activeJobIds` is always sent.
|
|
9097
|
+
runsJobs: true,
|
|
9098
|
+
// And keeps a run's folder a job uses when the run is continued here
|
|
9099
|
+
// (`resume.keepWorkspace`): continued in, or left as it is.
|
|
9100
|
+
keepsJobWorkspaces: true,
|
|
9101
|
+
// And gets the secrets of a job it took up again back (`jobsNeedingSecrets`,
|
|
9102
|
+
// `job_secrets`), to post its output redacted.
|
|
9103
|
+
receivesJobSecrets: true
|
|
6339
9104
|
},
|
|
6340
9105
|
activeSessionIds: this.heartbeatSessionIds(),
|
|
6341
9106
|
maxConcurrentSessions: this.opts.config.maxSessions,
|
|
6342
9107
|
activeCompletionIds: [...this.completionControllers.keys()],
|
|
6343
|
-
toolGrants: await this.toolGrants()
|
|
9108
|
+
toolGrants: await this.toolGrants(),
|
|
9109
|
+
activeJobIds: this.jobs.activeJobIds(),
|
|
9110
|
+
maxJobs: this.opts.config.maxJobs,
|
|
9111
|
+
jobsNeedingSecrets: this.jobs.jobsNeedingSecrets()
|
|
6344
9112
|
});
|
|
9113
|
+
if (res?.stopJobIds?.length) this.jobs.stopJobs(res.stopJobIds);
|
|
6345
9114
|
if (res?.toolGrantChanges?.length) {
|
|
6346
9115
|
for (const problem of await this.grants.apply(res.toolGrantChanges)) {
|
|
6347
9116
|
this.opts.logger.warn(`a saved tool permission was not applied: ${problem}`);
|
|
@@ -6399,6 +9168,7 @@ var RunnerDaemon = class {
|
|
|
6399
9168
|
attempt = 0;
|
|
6400
9169
|
limited = 0;
|
|
6401
9170
|
for (const cmd of res?.commands ?? []) this.track(this.dispatch(cmd));
|
|
9171
|
+
for (const cmd of res?.jobCommands ?? []) this.track(this.dispatchJob(cmd));
|
|
6402
9172
|
for (const req of res?.completions ?? []) this.track(this.answer(req));
|
|
6403
9173
|
} catch (err) {
|
|
6404
9174
|
if (this.signal.aborted) break;
|
|
@@ -6444,7 +9214,7 @@ var RunnerDaemon = class {
|
|
|
6444
9214
|
if (this.droppedSessionIds.has(id)) return;
|
|
6445
9215
|
this.droppedSessionIds.add(id);
|
|
6446
9216
|
this.opts.logger.warn(
|
|
6447
|
-
`session ${id}: not a Discovery Tree session id, so it is left out of the heartbeat (its state is in ${
|
|
9217
|
+
`session ${id}: not a Discovery Tree session id, so it is left out of the heartbeat (its state is in ${join16(this.opts.config.stateDir, "sessions", id)})`
|
|
6448
9218
|
);
|
|
6449
9219
|
});
|
|
6450
9220
|
}
|
|
@@ -6476,6 +9246,15 @@ var RunnerDaemon = class {
|
|
|
6476
9246
|
}
|
|
6477
9247
|
await this.ack(cmd.id, ack);
|
|
6478
9248
|
}
|
|
9249
|
+
/** A job command: handled (in order, per job) and acknowledged. */
|
|
9250
|
+
async dispatchJob(cmd) {
|
|
9251
|
+
this.opts.logger.debug(`job command ${cmd.type}`, { id: cmd.id, job: cmd.jobId });
|
|
9252
|
+
const ack = await this.manager.handleJob(cmd);
|
|
9253
|
+
if (!ack.ok) {
|
|
9254
|
+
this.opts.logger.warn(`${cmd.type} for job ${cmd.jobId} refused`, { error: ack.error });
|
|
9255
|
+
}
|
|
9256
|
+
await this.ack(cmd.id, ack);
|
|
9257
|
+
}
|
|
6479
9258
|
/**
|
|
6480
9259
|
* A slot to run a completion in: at once while fewer than the runner's session limit run,
|
|
6481
9260
|
* else after the next one ends. False when `cancelled` fires first: the request leaves
|
|
@@ -6487,15 +9266,15 @@ var RunnerDaemon = class {
|
|
|
6487
9266
|
this.completionsRunning++;
|
|
6488
9267
|
return Promise.resolve(true);
|
|
6489
9268
|
}
|
|
6490
|
-
return new Promise((
|
|
9269
|
+
return new Promise((resolve4) => {
|
|
6491
9270
|
const handOver = () => {
|
|
6492
9271
|
cancelled.removeEventListener("abort", leave);
|
|
6493
|
-
|
|
9272
|
+
resolve4(true);
|
|
6494
9273
|
};
|
|
6495
9274
|
const leave = () => {
|
|
6496
9275
|
const at = this.completionWaiters.indexOf(handOver);
|
|
6497
9276
|
if (at >= 0) this.completionWaiters.splice(at, 1);
|
|
6498
|
-
|
|
9277
|
+
resolve4(false);
|
|
6499
9278
|
};
|
|
6500
9279
|
this.completionWaiters.push(handOver);
|
|
6501
9280
|
cancelled.addEventListener("abort", leave, { once: true });
|
|
@@ -6670,67 +9449,8 @@ function formatChecks(checks) {
|
|
|
6670
9449
|
return checks.map((c) => `${mark[c.level]} ${c.name}: ${c.detail}`).join("\n");
|
|
6671
9450
|
}
|
|
6672
9451
|
|
|
6673
|
-
// src/lock.ts
|
|
6674
|
-
import { mkdir as mkdir8, open, readFile as readFile5, rm as rm7 } from "node:fs/promises";
|
|
6675
|
-
import { join as join14 } from "node:path";
|
|
6676
|
-
function lockFile(stateDir) {
|
|
6677
|
-
return join14(stateDir, "daemon.pid");
|
|
6678
|
-
}
|
|
6679
|
-
function pidAlive(pid) {
|
|
6680
|
-
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
6681
|
-
try {
|
|
6682
|
-
process.kill(pid, 0);
|
|
6683
|
-
return true;
|
|
6684
|
-
} catch (err) {
|
|
6685
|
-
return err.code === "EPERM";
|
|
6686
|
-
}
|
|
6687
|
-
}
|
|
6688
|
-
async function lockHolder(stateDir) {
|
|
6689
|
-
let raw;
|
|
6690
|
-
try {
|
|
6691
|
-
raw = await readFile5(lockFile(stateDir), "utf8");
|
|
6692
|
-
} catch {
|
|
6693
|
-
return null;
|
|
6694
|
-
}
|
|
6695
|
-
const pid = Number.parseInt(raw.trim(), 10);
|
|
6696
|
-
return pidAlive(pid) && pid !== process.pid ? pid : null;
|
|
6697
|
-
}
|
|
6698
|
-
async function acquireDaemonLock(stateDir, pid = process.pid) {
|
|
6699
|
-
await mkdir8(stateDir, { recursive: true, mode: 448 });
|
|
6700
|
-
const file = lockFile(stateDir);
|
|
6701
|
-
for (let attempt = 0; attempt < 3; attempt++) {
|
|
6702
|
-
try {
|
|
6703
|
-
const handle = await open(file, "wx", 384);
|
|
6704
|
-
try {
|
|
6705
|
-
await handle.writeFile(`${pid}
|
|
6706
|
-
`);
|
|
6707
|
-
} finally {
|
|
6708
|
-
await handle.close();
|
|
6709
|
-
}
|
|
6710
|
-
return {
|
|
6711
|
-
ok: true,
|
|
6712
|
-
lock: {
|
|
6713
|
-
file,
|
|
6714
|
-
async release() {
|
|
6715
|
-
const current2 = await readFile5(file, "utf8").catch(() => "");
|
|
6716
|
-
if (Number.parseInt(current2.trim(), 10) === pid) await rm7(file, { force: true });
|
|
6717
|
-
}
|
|
6718
|
-
}
|
|
6719
|
-
};
|
|
6720
|
-
} catch (err) {
|
|
6721
|
-
if (err.code !== "EEXIST") throw err;
|
|
6722
|
-
}
|
|
6723
|
-
const raw = await readFile5(file, "utf8").catch(() => null);
|
|
6724
|
-
if (raw === null) continue;
|
|
6725
|
-
const holder = Number.parseInt(raw.trim(), 10);
|
|
6726
|
-
if (pidAlive(holder) && holder !== pid) return { ok: false, pid: holder };
|
|
6727
|
-
await rm7(file, { force: true });
|
|
6728
|
-
}
|
|
6729
|
-
return { ok: false, pid: null };
|
|
6730
|
-
}
|
|
6731
|
-
|
|
6732
9452
|
// src/pairing.ts
|
|
6733
|
-
import { spawn as
|
|
9453
|
+
import { spawn as spawn6 } from "node:child_process";
|
|
6734
9454
|
async function pair(api, opts) {
|
|
6735
9455
|
const start2 = await api.startPairing({ name: opts.name, platform: RUNNER_PLATFORM });
|
|
6736
9456
|
opts.ui.showCode(start2.userCode, start2.verificationUrl, start2.expiresInSeconds);
|
|
@@ -6794,7 +9514,7 @@ function openUrl(url) {
|
|
|
6794
9514
|
if (!/^https?:\/\//i.test(url)) return;
|
|
6795
9515
|
const [cmd, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", url]] : ["xdg-open", [url]];
|
|
6796
9516
|
try {
|
|
6797
|
-
const child =
|
|
9517
|
+
const child = spawn6(cmd, args, { stdio: "ignore", detached: true, windowsHide: true });
|
|
6798
9518
|
child.on("error", () => void 0);
|
|
6799
9519
|
child.unref();
|
|
6800
9520
|
} catch {
|
|
@@ -6810,8 +9530,9 @@ Usage:
|
|
|
6810
9530
|
dt-runner login [--server <url>] [--name <name>] [--no-browser] [--yes]
|
|
6811
9531
|
Pair this computer with your Discovery Tree account.
|
|
6812
9532
|
--yes skips the "is this your account?" question.
|
|
6813
|
-
dt-runner start [--max-sessions <n>] [--repos-dir <dir>] [--json] [--verbose]
|
|
6814
|
-
Run: wait for agent sessions and run them with Claude Code
|
|
9533
|
+
dt-runner start [--max-sessions <n>] [--max-jobs <n>] [--repos-dir <dir>] [--json] [--verbose]
|
|
9534
|
+
Run: wait for agent sessions and run them with Claude Code,
|
|
9535
|
+
and run the jobs you approve (up to --max-jobs at once).
|
|
6815
9536
|
dt-runner status Show the configuration and check the connection.
|
|
6816
9537
|
dt-runner doctor Check Node.js, git and Claude Code on this computer.
|
|
6817
9538
|
dt-runner logout Forget this runner's token (deletes the config file).
|
|
@@ -6841,6 +9562,7 @@ async function main(argv) {
|
|
|
6841
9562
|
"no-browser": { type: "boolean" },
|
|
6842
9563
|
yes: { type: "boolean", short: "y" },
|
|
6843
9564
|
"max-sessions": { type: "string" },
|
|
9565
|
+
"max-jobs": { type: "string" },
|
|
6844
9566
|
"repos-dir": { type: "string" },
|
|
6845
9567
|
json: { type: "boolean" },
|
|
6846
9568
|
verbose: { type: "boolean" },
|
|
@@ -6863,6 +9585,7 @@ async function main(argv) {
|
|
|
6863
9585
|
case "start":
|
|
6864
9586
|
return start({
|
|
6865
9587
|
maxSessions: values["max-sessions"] !== void 0 ? Number(values["max-sessions"]) : void 0,
|
|
9588
|
+
maxJobs: values["max-jobs"] !== void 0 ? Number(values["max-jobs"]) : void 0,
|
|
6866
9589
|
reposDir: values["repos-dir"],
|
|
6867
9590
|
json: values.json,
|
|
6868
9591
|
verbose: values.verbose
|
|
@@ -6947,6 +9670,7 @@ async function start(opts) {
|
|
|
6947
9670
|
const paths = runnerPaths();
|
|
6948
9671
|
const config = resolveConfig(await readConfigFile(paths.configFile), {
|
|
6949
9672
|
maxSessions: opts.maxSessions,
|
|
9673
|
+
maxJobs: opts.maxJobs,
|
|
6950
9674
|
reposDir: opts.reposDir
|
|
6951
9675
|
});
|
|
6952
9676
|
if (!config.token) {
|
|
@@ -7009,7 +9733,7 @@ async function start(opts) {
|
|
|
7009
9733
|
signals++;
|
|
7010
9734
|
if (signals === 1) {
|
|
7011
9735
|
logger.info(
|
|
7012
|
-
`${sig}: stopping (Claude Code processes end, sessions stay resumable). Press Ctrl+C again to force.`
|
|
9736
|
+
`${sig}: stopping (Claude Code processes end, sessions stay resumable, jobs keep running). Press Ctrl+C again to force.`
|
|
7013
9737
|
);
|
|
7014
9738
|
daemon.stop();
|
|
7015
9739
|
} else {
|
|
@@ -7043,6 +9767,7 @@ async function status() {
|
|
|
7043
9767
|
console.log(
|
|
7044
9768
|
`Sessions: up to ${config.maxSessions} at once, permission mode ${config.permissionMode}`
|
|
7045
9769
|
);
|
|
9770
|
+
console.log(`Jobs: up to ${config.maxJobs} at once`);
|
|
7046
9771
|
console.log(`Repos: ${config.reposDir}`);
|
|
7047
9772
|
console.log(`Worktrees: ${config.worktreesDir}`);
|
|
7048
9773
|
console.log(`State: ${config.stateDir}`);
|