@discovery-tree/runner 0.1.16 → 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 +3240 -272
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -48,6 +48,214 @@ var AGENT_RUN_MAX_WALL_MS = 6 * 60 * 60 * 1e3;
|
|
|
48
48
|
var AGENT_RUN_ABANDONED_GRACE_MS = 30 * 60 * 1e3;
|
|
49
49
|
var AGENT_RUN_AUTO_RECOVER_MAX_MS = 5 * 6e4;
|
|
50
50
|
|
|
51
|
+
// ../contracts/src/discovered-work.ts
|
|
52
|
+
var MAX_DISCOVERED_TASKS_PER_TURN = 5;
|
|
53
|
+
var EXAMPLE_TITLE = "Return 404 instead of 500 when an invoice id is unknown";
|
|
54
|
+
var DISCOVERED_WORK_INSTRUCTION = `## Work you discover
|
|
55
|
+
|
|
56
|
+
While doing this task you may find work that needs doing but is not this task: a bug next to
|
|
57
|
+
the code you changed, a follow-up the change makes necessary, a missing piece the outcome
|
|
58
|
+
needs. Do not widen this task to do it, and do not leave it only in prose. Add it to the plan:
|
|
59
|
+
end your response with one block per task. Each is added to the tree, or proposed for a person
|
|
60
|
+
to accept, as the tree is set up; a person starts it.
|
|
61
|
+
|
|
62
|
+
<!-- DT-DISCOVERED
|
|
63
|
+
title: ${EXAMPLE_TITLE}
|
|
64
|
+
waits_on: nothing
|
|
65
|
+
channel: ai
|
|
66
|
+
complexity: low
|
|
67
|
+
impact: medium
|
|
68
|
+
model_reason: one handler and its test; callers show the raw 500 today
|
|
69
|
+
---
|
|
70
|
+
Goal: GET /api/invoices/:id answers 500 for an unknown id; it should answer 404.
|
|
71
|
+
Context: found while adding invoice export. \`InvoicesService.findOne\` throws a plain Error.
|
|
72
|
+
Files: backend/src/invoices/invoices.service.ts, invoices.service.spec.ts
|
|
73
|
+
Approach: throw NotFoundException when the row is missing, as OrdersService does.
|
|
74
|
+
Out of scope: other endpoints' error codes.
|
|
75
|
+
Verify: a spec for the unknown id; pnpm --filter backend test invoices.
|
|
76
|
+
-->
|
|
77
|
+
|
|
78
|
+
Rules:
|
|
79
|
+
- Only work you found by doing this task, that you are not doing, and that someone should do.
|
|
80
|
+
Not what you did, not a wish list, not this task restated. Most runs discover nothing; then
|
|
81
|
+
write no block.
|
|
82
|
+
- At most ${MAX_DISCOVERED_TASKS_PER_TURN} blocks. One block is one pull request's worth of work.
|
|
83
|
+
- \`title\` is the deliverable, one line. Below \`---\`, a brief another agent can carry out cold:
|
|
84
|
+
Goal, Context (what you found and where), Files, Approach, Out of scope, Verify.
|
|
85
|
+
- \`waits_on: this\` when it builds on this task's changes, so it starts after they land;
|
|
86
|
+
\`waits_on: nothing\` when it does not.
|
|
87
|
+
- Do not write \`-->\` inside a block: it ends the block.
|
|
88
|
+
- \`channel: human\` for a decision or approval only a person can give; otherwise \`ai\`.
|
|
89
|
+
- For an \`ai\` task, rate \`complexity\` and \`impact\` (low, medium, high) with a one-line
|
|
90
|
+
\`model_reason\`; they choose the model it runs on.`;
|
|
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
|
+
|
|
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;
|
|
246
|
+
var ENV_SETUP_SCRIPT_MAX_LENGTH = 16 * 1024;
|
|
247
|
+
|
|
248
|
+
// ../contracts/src/tree-autonomy.ts
|
|
249
|
+
var MAX_AUTO_RETRY_DELAY_MINUTES = 24 * 60;
|
|
250
|
+
|
|
251
|
+
// ../contracts/src/shared-artifacts.ts
|
|
252
|
+
var SHARED_ARTIFACT_TEXT_MAX_BYTES = 1024 * 1024;
|
|
253
|
+
var SHARED_ARTIFACT_IMAGE_MAX_BYTES = 5 * 1024 * 1024;
|
|
254
|
+
var SHARED_ARTIFACT_TREE_MAX_BYTES = 200 * 1024 * 1024;
|
|
255
|
+
|
|
256
|
+
// ../contracts/src/artifact-block.ts
|
|
257
|
+
var MAX_ARTIFACT_BLOCKS_BYTES = 1024 * 1024;
|
|
258
|
+
|
|
51
259
|
// ../contracts/src/design-review-images.ts
|
|
52
260
|
var MAX_REVIEW_IMAGES_PER_RUN = 12;
|
|
53
261
|
var MAX_REVIEW_IMAGE_CAPTION_LENGTH = 300;
|
|
@@ -56,7 +264,7 @@ var MAX_REVIEW_IMAGE_CAPTION_LENGTH = 300;
|
|
|
56
264
|
var REVIEW_AGENT_ROUND_STALE_MS = 30 * 6e4;
|
|
57
265
|
|
|
58
266
|
// ../contracts/src/agent-runner.ts
|
|
59
|
-
var RUNNER_PROTOCOL_VERSION =
|
|
267
|
+
var RUNNER_PROTOCOL_VERSION = 2;
|
|
60
268
|
var RUNNER_COMMAND_POLL_MAX_WAIT_MS = 25e3;
|
|
61
269
|
var RUNNER_EVENTS_MAX_BATCH = 200;
|
|
62
270
|
var RUNNER_EVENT_TEXT_MAX_LENGTH = 64e3;
|
|
@@ -65,8 +273,16 @@ var RUNNER_SESSION_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-
|
|
|
65
273
|
function isRunnerSessionId(value) {
|
|
66
274
|
return typeof value === "string" && RUNNER_SESSION_ID_RE.test(value);
|
|
67
275
|
}
|
|
276
|
+
var RUNNER_TASK_IMAGES_DIR = ".dt-task-images";
|
|
68
277
|
var RUNNER_REVIEW_IMAGE_MAX_BYTES = 5e6;
|
|
69
278
|
var RUNNER_DELIVERABLE_FILE = "DELIVERABLE.md";
|
|
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;
|
|
70
286
|
var RUNNER_COMPLETION_MAX_TEXT = 2e5;
|
|
71
287
|
|
|
72
288
|
// ../contracts/src/agent-permissions.ts
|
|
@@ -115,7 +331,7 @@ function toolGrantRepositoryKey(url) {
|
|
|
115
331
|
}
|
|
116
332
|
|
|
117
333
|
// src/version.ts
|
|
118
|
-
var RUNNER_VERSION = true ? "0.1.
|
|
334
|
+
var RUNNER_VERSION = true ? "0.1.18" : "0.0.0-dev";
|
|
119
335
|
var RUNNER_PLATFORM = `${process.platform}-${process.arch}`;
|
|
120
336
|
|
|
121
337
|
// src/api.ts
|
|
@@ -188,6 +404,10 @@ var RunnerApi = class {
|
|
|
188
404
|
postEvents(sessionId, body) {
|
|
189
405
|
return this.request("POST", `/runner/sessions/${encodeURIComponent(sessionId)}/events`, body);
|
|
190
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
|
+
}
|
|
191
411
|
/** An image the agent rendered of a design proposal, attached to the session's task. */
|
|
192
412
|
postReviewImage(sessionId, body) {
|
|
193
413
|
return this.request(
|
|
@@ -198,6 +418,15 @@ var RunnerApi = class {
|
|
|
198
418
|
{ timeoutMs: Math.max(this.timeoutMs, 12e4) }
|
|
199
419
|
);
|
|
200
420
|
}
|
|
421
|
+
/** An image a session's prompt names (`start_session.promptImages`), to save for its agent. */
|
|
422
|
+
getPromptImage(sessionId, attachmentId) {
|
|
423
|
+
return this.request(
|
|
424
|
+
"GET",
|
|
425
|
+
`/runner/sessions/${encodeURIComponent(sessionId)}/prompt-images/${encodeURIComponent(attachmentId)}`,
|
|
426
|
+
void 0,
|
|
427
|
+
{ timeoutMs: Math.max(this.timeoutMs, 12e4) }
|
|
428
|
+
);
|
|
429
|
+
}
|
|
201
430
|
/** Unauthenticated reachability check (`dt-runner status`). */
|
|
202
431
|
async health() {
|
|
203
432
|
try {
|
|
@@ -370,12 +599,12 @@ var JobHelper = class {
|
|
|
370
599
|
{ stdio: ["pipe", "pipe", "ignore"], windowsHide: true }
|
|
371
600
|
);
|
|
372
601
|
let onReady = () => void 0;
|
|
373
|
-
this.ready = new Promise((
|
|
374
|
-
const timer = setTimeout(() =>
|
|
602
|
+
this.ready = new Promise((resolve4) => {
|
|
603
|
+
const timer = setTimeout(() => resolve4(false), READY_TIMEOUT_MS);
|
|
375
604
|
timer.unref();
|
|
376
605
|
onReady = (ok) => {
|
|
377
606
|
clearTimeout(timer);
|
|
378
|
-
|
|
607
|
+
resolve4(ok);
|
|
379
608
|
};
|
|
380
609
|
});
|
|
381
610
|
const lines = createInterface({ input: this.child.stdout, crlfDelay: Infinity });
|
|
@@ -389,7 +618,7 @@ var JobHelper = class {
|
|
|
389
618
|
answer(text);
|
|
390
619
|
}
|
|
391
620
|
});
|
|
392
|
-
const
|
|
621
|
+
const gone2 = () => {
|
|
393
622
|
if (this.exited) return;
|
|
394
623
|
this.exited = true;
|
|
395
624
|
onReady(false);
|
|
@@ -397,8 +626,8 @@ var JobHelper = class {
|
|
|
397
626
|
this.waiting.clear();
|
|
398
627
|
if (helper === this) helper = null;
|
|
399
628
|
};
|
|
400
|
-
this.child.on("error",
|
|
401
|
-
this.child.on("exit",
|
|
629
|
+
this.child.on("error", gone2);
|
|
630
|
+
this.child.on("exit", gone2);
|
|
402
631
|
this.child.stdin.on("error", () => void 0);
|
|
403
632
|
this.child.unref();
|
|
404
633
|
this.child.stdout.unref?.();
|
|
@@ -430,15 +659,15 @@ var JobHelper = class {
|
|
|
430
659
|
}
|
|
431
660
|
ask(request, id) {
|
|
432
661
|
if (this.exited) return Promise.resolve("err gone");
|
|
433
|
-
return new Promise((
|
|
662
|
+
return new Promise((resolve4) => {
|
|
434
663
|
const timer = setTimeout(() => {
|
|
435
664
|
this.waiting.delete(id);
|
|
436
|
-
|
|
665
|
+
resolve4("err timeout");
|
|
437
666
|
}, ANSWER_TIMEOUT_MS);
|
|
438
667
|
timer.unref();
|
|
439
668
|
this.waiting.set(id, (answer) => {
|
|
440
669
|
clearTimeout(timer);
|
|
441
|
-
|
|
670
|
+
resolve4(answer);
|
|
442
671
|
});
|
|
443
672
|
this.child.stdin.write(request + "\n");
|
|
444
673
|
});
|
|
@@ -564,7 +793,7 @@ async function reapTree(tree, graceMs = 2e3, deps = {}) {
|
|
|
564
793
|
await (deps.terminateJob ?? terminateJob)(await tree.job);
|
|
565
794
|
const rows = await (deps.listProcesses ?? listWindowsProcesses)();
|
|
566
795
|
const orphans = descendantsOf(tree, rows);
|
|
567
|
-
if (orphans.length) await (deps.kill ??
|
|
796
|
+
if (orphans.length) await (deps.kill ?? killWindowsTrees)(orphans);
|
|
568
797
|
} catch {
|
|
569
798
|
} finally {
|
|
570
799
|
if (liveTrees.get(tree.pid)?.tree.startedAt === tree.startedAt) liveTrees.delete(tree.pid);
|
|
@@ -689,7 +918,7 @@ function namesPathIn(commandLine, dir) {
|
|
|
689
918
|
}
|
|
690
919
|
function listWindowsProcesses() {
|
|
691
920
|
const script = `$ErrorActionPreference='SilentlyContinue';Get-CimInstance Win32_Process | ForEach-Object { if ($_.CreationDate) { "$($_.ProcessId) $($_.ParentProcessId) $(([DateTimeOffset]$_.CreationDate).ToUnixTimeMilliseconds()) $($_.CommandLine -replace "[\\r\\n]", " ")" } }`;
|
|
692
|
-
return new Promise((
|
|
921
|
+
return new Promise((resolve4, reject) => {
|
|
693
922
|
const ps = spawn2(
|
|
694
923
|
"powershell.exe",
|
|
695
924
|
["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script],
|
|
@@ -704,7 +933,7 @@ function listWindowsProcesses() {
|
|
|
704
933
|
});
|
|
705
934
|
ps.on("close", () => {
|
|
706
935
|
clearTimeout(timer);
|
|
707
|
-
|
|
936
|
+
resolve4(parseProcessRows(out));
|
|
708
937
|
});
|
|
709
938
|
});
|
|
710
939
|
}
|
|
@@ -723,13 +952,13 @@ function parseProcessRows(text) {
|
|
|
723
952
|
}
|
|
724
953
|
return rows;
|
|
725
954
|
}
|
|
726
|
-
async function
|
|
955
|
+
async function killWindowsTrees(pids) {
|
|
727
956
|
for (let i = 0; i < pids.length; i += 50) {
|
|
728
957
|
const args = pids.slice(i, i + 50).flatMap((p) => ["/pid", String(p)]);
|
|
729
|
-
await new Promise((
|
|
958
|
+
await new Promise((resolve4) => {
|
|
730
959
|
const tk = spawn2("taskkill", [...args, "/T", "/F"], { stdio: "ignore", windowsHide: true });
|
|
731
|
-
tk.on("error", () =>
|
|
732
|
-
tk.on("close", () =>
|
|
960
|
+
tk.on("error", () => resolve4());
|
|
961
|
+
tk.on("close", () => resolve4());
|
|
733
962
|
});
|
|
734
963
|
}
|
|
735
964
|
}
|
|
@@ -744,7 +973,7 @@ function signalGroup(pgid, signal) {
|
|
|
744
973
|
|
|
745
974
|
// src/exec.ts
|
|
746
975
|
function exec(cmd, args, opts = {}) {
|
|
747
|
-
return new Promise((
|
|
976
|
+
return new Promise((resolve4, reject) => {
|
|
748
977
|
const child = spawn3(cmd, args, {
|
|
749
978
|
cwd: opts.cwd,
|
|
750
979
|
env: opts.env ?? process.env,
|
|
@@ -779,7 +1008,7 @@ function exec(cmd, args, opts = {}) {
|
|
|
779
1008
|
child.on("close", (code) => {
|
|
780
1009
|
if (timer) clearTimeout(timer);
|
|
781
1010
|
opts.signal?.removeEventListener("abort", onAbort);
|
|
782
|
-
void reaped.then(() =>
|
|
1011
|
+
void reaped.then(() => resolve4({ code, stdout, stderr }));
|
|
783
1012
|
});
|
|
784
1013
|
child.stdin.on("error", () => void 0);
|
|
785
1014
|
child.stdin.end(opts.input ?? "");
|
|
@@ -841,7 +1070,7 @@ function redactFields(fields) {
|
|
|
841
1070
|
return out;
|
|
842
1071
|
}
|
|
843
1072
|
function scrubSecrets(text) {
|
|
844
|
-
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, "***");
|
|
845
1074
|
}
|
|
846
1075
|
|
|
847
1076
|
// src/git.ts
|
|
@@ -925,6 +1154,55 @@ function isLocked(err) {
|
|
|
925
1154
|
function removeDir(path) {
|
|
926
1155
|
return rm(path, { recursive: true, force: true, maxRetries: 8, retryDelay: 250 });
|
|
927
1156
|
}
|
|
1157
|
+
async function ensureRepoCache(repoDir, ref, protocol) {
|
|
1158
|
+
if (!await exists(join2(repoDir, ".git"))) {
|
|
1159
|
+
await mkdir(dirname(repoDir), { recursive: true });
|
|
1160
|
+
await rm(repoDir, { recursive: true, force: true });
|
|
1161
|
+
await git(dirname(repoDir), ["clone", "--no-checkout", cloneUrl(ref, protocol), repoDir]);
|
|
1162
|
+
return;
|
|
1163
|
+
}
|
|
1164
|
+
const wanted = cloneUrl(ref, protocol);
|
|
1165
|
+
const current2 = await exec("git", ["config", "--get", "remote.origin.url"], {
|
|
1166
|
+
cwd: repoDir,
|
|
1167
|
+
env: gitEnv()
|
|
1168
|
+
});
|
|
1169
|
+
if (current2.stdout.trim() !== wanted) {
|
|
1170
|
+
await git(repoDir, ["remote", "set-url", "origin", wanted]);
|
|
1171
|
+
}
|
|
1172
|
+
await git(repoDir, ["fetch", "--prune", "origin"]);
|
|
1173
|
+
}
|
|
1174
|
+
async function resolveBase(repoDir, wanted) {
|
|
1175
|
+
const baseRef = wanted ?? await defaultBranch(repoDir);
|
|
1176
|
+
let start2 = `origin/${baseRef}`;
|
|
1177
|
+
if (!await gitOk(repoDir, ["rev-parse", "--verify", "--quiet", `${start2}^{commit}`])) {
|
|
1178
|
+
if (!await gitOk(repoDir, ["rev-parse", "--verify", "--quiet", `${baseRef}^{commit}`])) {
|
|
1179
|
+
throw new Error(`Base branch ${baseRef} was not found on origin.`);
|
|
1180
|
+
}
|
|
1181
|
+
start2 = baseRef;
|
|
1182
|
+
}
|
|
1183
|
+
return { baseRef, start: start2 };
|
|
1184
|
+
}
|
|
1185
|
+
async function prepareReferenceCheckout(input) {
|
|
1186
|
+
const ref = parseRepoUrl(input.url);
|
|
1187
|
+
if (!ref) throw new Error(repositoryUrlError(input.url));
|
|
1188
|
+
if (input.baseRef) assertSafeRef(input.baseRef, "Base branch");
|
|
1189
|
+
const repoDir = join2(input.reposDir, ref.owner, ref.repo);
|
|
1190
|
+
return withRepoLock(repoDir, async () => {
|
|
1191
|
+
await ensureRepoCache(repoDir, ref, input.protocol);
|
|
1192
|
+
const { baseRef, start: start2 } = await resolveBase(repoDir, input.baseRef);
|
|
1193
|
+
const sha = await git(repoDir, ["rev-parse", `${start2}^{commit}`]);
|
|
1194
|
+
await exec("git", ["worktree", "remove", "--force", input.dir], {
|
|
1195
|
+
cwd: repoDir,
|
|
1196
|
+
env: gitEnv(),
|
|
1197
|
+
timeoutMs: 6e4
|
|
1198
|
+
});
|
|
1199
|
+
await removeDir(input.dir);
|
|
1200
|
+
await git(repoDir, ["worktree", "prune"]);
|
|
1201
|
+
await mkdir(dirname(input.dir), { recursive: true });
|
|
1202
|
+
await git(repoDir, ["worktree", "add", "--detach", input.dir, sha]);
|
|
1203
|
+
return { repoDir, dir: input.dir, baseRef, sha };
|
|
1204
|
+
});
|
|
1205
|
+
}
|
|
928
1206
|
async function prepareWorktree(input) {
|
|
929
1207
|
const ref = parseRepoUrl(input.url);
|
|
930
1208
|
if (!ref) throw new Error(repositoryUrlError(input.url));
|
|
@@ -934,53 +1212,56 @@ async function prepareWorktree(input) {
|
|
|
934
1212
|
const ownWorktree = join2(input.worktreesDir, input.sessionId);
|
|
935
1213
|
let worktree = join2(input.worktreesDir, input.worktreeKey || input.sessionId);
|
|
936
1214
|
const remove = input.removeDir ?? removeDir;
|
|
1215
|
+
const keep = input.keepWorkspace === true && worktree !== ownWorktree;
|
|
937
1216
|
return withRepoLock(repoDir, async () => {
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
await rm(repoDir, { recursive: true, force: true });
|
|
941
|
-
await git(dirname(repoDir), [
|
|
942
|
-
"clone",
|
|
943
|
-
"--no-checkout",
|
|
944
|
-
cloneUrl(ref, input.protocol),
|
|
945
|
-
repoDir
|
|
946
|
-
]);
|
|
947
|
-
} else {
|
|
948
|
-
const wanted = cloneUrl(ref, input.protocol);
|
|
949
|
-
const current2 = await exec("git", ["config", "--get", "remote.origin.url"], {
|
|
950
|
-
cwd: repoDir,
|
|
951
|
-
env: gitEnv()
|
|
952
|
-
});
|
|
953
|
-
if (current2.stdout.trim() !== wanted) {
|
|
954
|
-
await git(repoDir, ["remote", "set-url", "origin", wanted]);
|
|
955
|
-
}
|
|
956
|
-
await git(repoDir, ["fetch", "--prune", "origin"]);
|
|
957
|
-
}
|
|
958
|
-
const baseRef = input.baseRef ?? await defaultBranch(repoDir);
|
|
959
|
-
let start2 = `origin/${baseRef}`;
|
|
960
|
-
if (!await gitOk(repoDir, ["rev-parse", "--verify", "--quiet", `${start2}^{commit}`])) {
|
|
961
|
-
if (!await gitOk(repoDir, ["rev-parse", "--verify", "--quiet", `${baseRef}^{commit}`])) {
|
|
962
|
-
throw new Error(`Base branch ${baseRef} was not found on origin.`);
|
|
963
|
-
}
|
|
964
|
-
start2 = baseRef;
|
|
965
|
-
}
|
|
1217
|
+
await ensureRepoCache(repoDir, ref, input.protocol);
|
|
1218
|
+
const { baseRef, start: start2 } = await resolveBase(repoDir, input.baseRef);
|
|
966
1219
|
let baseSha = await git(repoDir, ["rev-parse", `${start2}^{commit}`]);
|
|
967
1220
|
let checkout = start2;
|
|
968
1221
|
let continuedFrom;
|
|
969
1222
|
let setAside;
|
|
970
1223
|
let leftInPlace;
|
|
971
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
|
+
};
|
|
972
1252
|
const remoteWork = `refs/remotes/origin/${input.workBranch}`;
|
|
973
|
-
|
|
974
|
-
cwd:
|
|
1253
|
+
const reusable = async (dir) => input.continueBranch === true && await exists(dir) && await exec("git", ["rev-parse", "--abbrev-ref", "HEAD"], {
|
|
1254
|
+
cwd: dir,
|
|
975
1255
|
env: gitEnv(),
|
|
976
1256
|
timeoutMs: 6e4
|
|
977
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
|
|
978
1258
|
// behind (the run went on elsewhere) would have the agent work on stale code.
|
|
979
1259
|
(!await gitOk(repoDir, ["rev-parse", "--verify", "--quiet", `${remoteWork}^{commit}`]) || await exec("git", ["merge-base", "--is-ancestor", remoteWork, "HEAD"], {
|
|
980
|
-
cwd:
|
|
1260
|
+
cwd: dir,
|
|
981
1261
|
env: gitEnv(),
|
|
982
1262
|
timeoutMs: 6e4
|
|
983
|
-
}).then((r) => r.code === 0))
|
|
1263
|
+
}).then((r) => r.code === 0));
|
|
1264
|
+
if (await reusable(worktree)) {
|
|
984
1265
|
const forkPoint = await exec("git", ["merge-base", "HEAD", start2], {
|
|
985
1266
|
cwd: worktree,
|
|
986
1267
|
env: gitEnv(),
|
|
@@ -1024,7 +1305,8 @@ async function prepareWorktree(input) {
|
|
|
1024
1305
|
checkout = await git(repoDir, ["rev-parse", `${checkout}^{commit}`]);
|
|
1025
1306
|
}
|
|
1026
1307
|
}
|
|
1027
|
-
|
|
1308
|
+
const busy = keep || (input.inUse?.(worktree) ?? false);
|
|
1309
|
+
if (input.continueBranch && !busy && await exists(worktree)) {
|
|
1028
1310
|
const dirty = await exec("git", ["status", "--porcelain"], {
|
|
1029
1311
|
cwd: worktree,
|
|
1030
1312
|
env: gitEnv(),
|
|
@@ -1036,44 +1318,134 @@ async function prepareWorktree(input) {
|
|
|
1036
1318
|
else dirtyKept = true;
|
|
1037
1319
|
}
|
|
1038
1320
|
}
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
);
|
|
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]);
|
|
1050
1331
|
}
|
|
1051
|
-
|
|
1052
|
-
if (
|
|
1053
|
-
|
|
1332
|
+
for (const { dir, head, at } of released) {
|
|
1333
|
+
if (!head || !at || await revParse2(dir, "HEAD") !== at || await revParse2(null, head) !== at) {
|
|
1334
|
+
continue;
|
|
1054
1335
|
}
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
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) {
|
|
1059
1348
|
await gitOk(repoDir, ["worktree", "remove", "--force", worktree]);
|
|
1060
|
-
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
|
+
);
|
|
1061
1431
|
}
|
|
1062
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;
|
|
1063
1448
|
}
|
|
1064
|
-
await gitOk(repoDir, ["worktree", "prune"]);
|
|
1065
|
-
await mkdir(input.worktreesDir, { recursive: true });
|
|
1066
|
-
await git(repoDir, [
|
|
1067
|
-
"worktree",
|
|
1068
|
-
"add",
|
|
1069
|
-
"--no-track",
|
|
1070
|
-
// A folder left in place may still be registered with the work branch checked out.
|
|
1071
|
-
...leftInPlace ? ["--force"] : [],
|
|
1072
|
-
"-B",
|
|
1073
|
-
input.workBranch,
|
|
1074
|
-
worktree,
|
|
1075
|
-
checkout
|
|
1076
|
-
]);
|
|
1077
1449
|
return {
|
|
1078
1450
|
repoDir,
|
|
1079
1451
|
worktree,
|
|
@@ -1081,10 +1453,26 @@ async function prepareWorktree(input) {
|
|
|
1081
1453
|
baseSha,
|
|
1082
1454
|
...continuedFrom ? { continuedFrom } : {},
|
|
1083
1455
|
...setAside ? { setAside } : {},
|
|
1084
|
-
...leftInPlace ? { leftInPlace } : {}
|
|
1456
|
+
...leftInPlace ? { leftInPlace } : {},
|
|
1457
|
+
...keptRef ? { keptRef } : {}
|
|
1085
1458
|
};
|
|
1086
1459
|
});
|
|
1087
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
|
+
}
|
|
1088
1476
|
async function defaultBranch(repoDir) {
|
|
1089
1477
|
const read = async () => {
|
|
1090
1478
|
const res = await exec("git", ["symbolic-ref", "--short", "refs/remotes/origin/HEAD"], {
|
|
@@ -1169,9 +1557,16 @@ function evidenceBranch(workBranch) {
|
|
|
1169
1557
|
}
|
|
1170
1558
|
async function ensureEvidenceDir(worktree) {
|
|
1171
1559
|
await mkdir2(join3(worktree, EVIDENCE_DIR), { recursive: true });
|
|
1560
|
+
await excludeFromGit(
|
|
1561
|
+
worktree,
|
|
1562
|
+
EVIDENCE_DIR,
|
|
1563
|
+
"Screenshots dt-runner publishes on their own branch"
|
|
1564
|
+
);
|
|
1565
|
+
}
|
|
1566
|
+
async function excludeFromGit(worktree, dir, why) {
|
|
1172
1567
|
const rel = await git(worktree, ["rev-parse", "--git-path", "info/exclude"]);
|
|
1173
1568
|
const file = isAbsolute2(rel) ? rel : join3(worktree, rel);
|
|
1174
|
-
const line = `/${
|
|
1569
|
+
const line = `/${dir}/`;
|
|
1175
1570
|
let current2 = "";
|
|
1176
1571
|
try {
|
|
1177
1572
|
current2 = await readFile(file, "utf8");
|
|
@@ -1179,13 +1574,10 @@ async function ensureEvidenceDir(worktree) {
|
|
|
1179
1574
|
}
|
|
1180
1575
|
if (current2.split("\n").some((l) => l.trim() === line)) return;
|
|
1181
1576
|
await mkdir2(join3(file, ".."), { recursive: true });
|
|
1182
|
-
const
|
|
1183
|
-
await writeFile(
|
|
1184
|
-
file,
|
|
1185
|
-
`${current2}${sep2}# Screenshots dt-runner publishes on their own branch
|
|
1577
|
+
const sep3 = current2 && !current2.endsWith("\n") ? "\n" : "";
|
|
1578
|
+
await writeFile(file, `${current2}${sep3}# ${why}
|
|
1186
1579
|
${line}
|
|
1187
|
-
`
|
|
1188
|
-
);
|
|
1580
|
+
`);
|
|
1189
1581
|
}
|
|
1190
1582
|
async function publishEvidence(input) {
|
|
1191
1583
|
const dir = join3(input.worktree, EVIDENCE_DIR);
|
|
@@ -1518,11 +1910,21 @@ function claudeArgs(launch) {
|
|
|
1518
1910
|
return args;
|
|
1519
1911
|
}
|
|
1520
1912
|
function runnerSystemPrompt(input) {
|
|
1913
|
+
const env = environmentSentence(input.environment);
|
|
1521
1914
|
if (!input.workBranch) {
|
|
1522
1915
|
const scratch = [
|
|
1523
1916
|
"You are running a Discovery Tree task through the person\u2019s local Discovery Tree runner.",
|
|
1524
1917
|
"Your working directory is a scratch directory created for this task; it is not a git repository."
|
|
1525
1918
|
];
|
|
1919
|
+
if (input.reference) {
|
|
1920
|
+
scratch.push(
|
|
1921
|
+
`The repository this task concerns, ${input.reference.url}, is checked out at`,
|
|
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.`,
|
|
1923
|
+
"Read it before you propose anything, so your work matches the product as it is: its",
|
|
1924
|
+
"screens, components, styles, words and data. It is for reading only: do not change it,",
|
|
1925
|
+
"commit or push. Nothing in it is kept, and this task\u2019s output is your response."
|
|
1926
|
+
);
|
|
1927
|
+
}
|
|
1526
1928
|
if (input.reviewImages) {
|
|
1527
1929
|
const folder = join4(input.cwd, EVIDENCE_DIR);
|
|
1528
1930
|
scratch.push(
|
|
@@ -1535,6 +1937,7 @@ function runnerSystemPrompt(input) {
|
|
|
1535
1937
|
"Do not upload or link them yourself."
|
|
1536
1938
|
);
|
|
1537
1939
|
}
|
|
1940
|
+
if (env) scratch.push(env);
|
|
1538
1941
|
return scratch.join(" ");
|
|
1539
1942
|
}
|
|
1540
1943
|
const evidence = join4(input.cwd, EVIDENCE_DIR);
|
|
@@ -1567,9 +1970,16 @@ function runnerSystemPrompt(input) {
|
|
|
1567
1970
|
"Other runs may share this computer:",
|
|
1568
1971
|
"if the port is taken, start yours on another port; never stop a process you did not start.",
|
|
1569
1972
|
"Do not start databases, containers or other services yourself, directly or through a",
|
|
1570
|
-
"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] : []
|
|
1571
1975
|
].join(" ");
|
|
1572
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
|
+
}
|
|
1573
1983
|
|
|
1574
1984
|
// src/claude-code-rules.ts
|
|
1575
1985
|
import { readFile as readFile2, stat as stat3 } from "node:fs/promises";
|
|
@@ -1855,7 +2265,10 @@ var PermissionRelay = class {
|
|
|
1855
2265
|
controlRequestId: req.controlRequestId,
|
|
1856
2266
|
toolName: req.toolName,
|
|
1857
2267
|
input: req.input,
|
|
1858
|
-
inputSummary: summarizeToolInput(
|
|
2268
|
+
inputSummary: summarizeToolInput(
|
|
2269
|
+
req.toolName,
|
|
2270
|
+
this.deps.redactInput ? this.deps.redactInput(req.input) : req.input
|
|
2271
|
+
),
|
|
1859
2272
|
requestedAt,
|
|
1860
2273
|
timer
|
|
1861
2274
|
};
|
|
@@ -1964,10 +2377,13 @@ var PermissionRelay = class {
|
|
|
1964
2377
|
};
|
|
1965
2378
|
|
|
1966
2379
|
// src/stream-mapper.ts
|
|
2380
|
+
var CAP_TEXT_MARKER = "\n\u2026 [truncated by dt-runner]";
|
|
1967
2381
|
function capText(text, max = RUNNER_EVENT_TEXT_MAX_LENGTH) {
|
|
1968
2382
|
if (text.length <= max) return { text, truncated: false };
|
|
1969
|
-
|
|
1970
|
-
|
|
2383
|
+
return {
|
|
2384
|
+
text: text.slice(0, max - CAP_TEXT_MARKER.length) + CAP_TEXT_MARKER,
|
|
2385
|
+
truncated: true
|
|
2386
|
+
};
|
|
1971
2387
|
}
|
|
1972
2388
|
var ClaudeStreamMapper = class {
|
|
1973
2389
|
/** Running offset of each live text block, by providerEventId. */
|
|
@@ -3396,6 +3812,12 @@ function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPa
|
|
|
3396
3812
|
`maxSessions must be a whole number from 1 to ${MAX_SESSIONS_LIMIT} (got ${maxSessions}).`
|
|
3397
3813
|
);
|
|
3398
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
|
+
}
|
|
3399
3821
|
const inherit = file?.inheritClaudeCodePermissions;
|
|
3400
3822
|
if (inherit !== void 0 && typeof inherit !== "boolean") {
|
|
3401
3823
|
throw new Error(
|
|
@@ -3437,6 +3859,7 @@ function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPa
|
|
|
3437
3859
|
token: env.DT_RUNNER_TOKEN || file?.token || null,
|
|
3438
3860
|
name: file?.name ?? null,
|
|
3439
3861
|
maxSessions,
|
|
3862
|
+
maxJobs,
|
|
3440
3863
|
reposDir: overrides.reposDir ?? file?.reposDir ?? join7(paths.dataDir, "repos"),
|
|
3441
3864
|
worktreesDir: file?.worktreesDir ?? join7(paths.dataDir, "worktrees"),
|
|
3442
3865
|
permissionMode: mode,
|
|
@@ -3456,7 +3879,7 @@ function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPa
|
|
|
3456
3879
|
}
|
|
3457
3880
|
|
|
3458
3881
|
// src/daemon.ts
|
|
3459
|
-
import { join as
|
|
3882
|
+
import { join as join16 } from "node:path";
|
|
3460
3883
|
|
|
3461
3884
|
// src/backoff.ts
|
|
3462
3885
|
function backoffDelay(attempt, baseMs = 1e3, maxMs = 6e4) {
|
|
@@ -3464,13 +3887,13 @@ function backoffDelay(attempt, baseMs = 1e3, maxMs = 6e4) {
|
|
|
3464
3887
|
return Math.round(ceiling / 2 + Math.random() * ceiling / 2);
|
|
3465
3888
|
}
|
|
3466
3889
|
function sleep(ms, signal) {
|
|
3467
|
-
return new Promise((
|
|
3468
|
-
if (signal?.aborted) return
|
|
3890
|
+
return new Promise((resolve4) => {
|
|
3891
|
+
if (signal?.aborted) return resolve4();
|
|
3469
3892
|
const timer = setTimeout(done, ms);
|
|
3470
3893
|
function done() {
|
|
3471
3894
|
clearTimeout(timer);
|
|
3472
3895
|
signal?.removeEventListener("abort", done);
|
|
3473
|
-
|
|
3896
|
+
resolve4();
|
|
3474
3897
|
}
|
|
3475
3898
|
signal?.addEventListener("abort", done, { once: true });
|
|
3476
3899
|
});
|
|
@@ -3578,9 +4001,296 @@ function reportableSessionIds(ids, onDropped = () => void 0) {
|
|
|
3578
4001
|
return [...out];
|
|
3579
4002
|
}
|
|
3580
4003
|
|
|
3581
|
-
// src/
|
|
3582
|
-
import {
|
|
3583
|
-
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";
|
|
4009
|
+
|
|
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
|
+
};
|
|
4048
|
+
}
|
|
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;
|
|
4077
|
+
}
|
|
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))));
|
|
4089
|
+
}
|
|
4090
|
+
return this.replace(text);
|
|
4091
|
+
}
|
|
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") };
|
|
4279
|
+
}
|
|
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;
|
|
4293
|
+
}
|
|
3584
4294
|
|
|
3585
4295
|
// src/fsutil.ts
|
|
3586
4296
|
import { mkdir as mkdir4, readFile as readFile4, rename as rename2, writeFile as writeFile3 } from "node:fs/promises";
|
|
@@ -3601,63 +4311,1866 @@ async function readJson(file) {
|
|
|
3601
4311
|
}
|
|
3602
4312
|
}
|
|
3603
4313
|
|
|
3604
|
-
// 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
|
|
3605
4445
|
var MAX_REJECTED_ATTEMPTS = 3;
|
|
3606
|
-
var
|
|
4446
|
+
var JobOutbox = class _JobOutbox {
|
|
3607
4447
|
constructor(opts) {
|
|
3608
4448
|
this.opts = opts;
|
|
3609
4449
|
}
|
|
3610
4450
|
nextSeq = 1;
|
|
3611
4451
|
pending = [];
|
|
3612
|
-
|
|
3613
|
-
|
|
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;
|
|
3614
4458
|
pumping = false;
|
|
3615
4459
|
pumpTimer = null;
|
|
3616
4460
|
stopped = false;
|
|
3617
|
-
|
|
4461
|
+
discarded = false;
|
|
3618
4462
|
stopController = new AbortController();
|
|
3619
4463
|
persistChain = Promise.resolve();
|
|
3620
4464
|
persistQueued = false;
|
|
4465
|
+
/** Writes failed in a row, and the timer of the next try. */
|
|
4466
|
+
persistFailures = 0;
|
|
4467
|
+
persistRetry = null;
|
|
3621
4468
|
idleWaiters = [];
|
|
3622
|
-
|
|
4469
|
+
finishNotified = false;
|
|
3623
4470
|
static async open(opts) {
|
|
3624
|
-
const box = new
|
|
4471
|
+
const box = new _JobOutbox(opts);
|
|
3625
4472
|
const saved = await readJson(opts.file);
|
|
3626
4473
|
if (saved) {
|
|
3627
4474
|
box.pending = Array.isArray(saved.pending) ? saved.pending : [];
|
|
3628
|
-
const
|
|
3629
|
-
box.nextSeq = Math.max(saved.nextSeq || 1,
|
|
3630
|
-
|
|
3631
|
-
|
|
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();
|
|
3632
4484
|
return box;
|
|
3633
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
|
+
}
|
|
3634
4498
|
get size() {
|
|
3635
4499
|
return this.pending.length;
|
|
3636
4500
|
}
|
|
3637
|
-
|
|
3638
|
-
|
|
3639
|
-
|
|
3640
|
-
|
|
3641
|
-
|
|
3642
|
-
|
|
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();
|
|
3643
4513
|
}
|
|
3644
|
-
|
|
3645
|
-
|
|
3646
|
-
|
|
3647
|
-
|
|
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;
|
|
3648
4519
|
}
|
|
4520
|
+
this.status = { report, afterSeq: this.nextSeq };
|
|
4521
|
+
if (report.status !== "running") this.finished = true;
|
|
3649
4522
|
this.persist();
|
|
3650
4523
|
this.schedulePump();
|
|
3651
4524
|
}
|
|
3652
|
-
/**
|
|
3653
|
-
|
|
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). */
|
|
4534
|
+
async flush(timeoutMs) {
|
|
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) {
|
|
3654
6167
|
if (this.stopped) return this.pending.length === 0;
|
|
3655
6168
|
if (this.pumpTimer) {
|
|
3656
6169
|
clearTimeout(this.pumpTimer);
|
|
3657
6170
|
this.pumpTimer = null;
|
|
3658
6171
|
}
|
|
3659
6172
|
if (this.pending.length && !this.closed) void this.pump();
|
|
3660
|
-
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)));
|
|
3661
6174
|
const result = await Promise.race([drained, sleep(timeoutMs).then(() => false)]);
|
|
3662
6175
|
await this.persistChain;
|
|
3663
6176
|
return result || this.pending.length === 0;
|
|
@@ -3781,7 +6294,7 @@ var SessionOutbox = class _SessionOutbox {
|
|
|
3781
6294
|
error: err.message,
|
|
3782
6295
|
attempt: rejected
|
|
3783
6296
|
});
|
|
3784
|
-
if (rejected >=
|
|
6297
|
+
if (rejected >= MAX_REJECTED_ATTEMPTS2) {
|
|
3785
6298
|
this.pending = this.pending.filter((e) => e.seq > maxSeq);
|
|
3786
6299
|
this.persist();
|
|
3787
6300
|
rejected = 0;
|
|
@@ -3832,13 +6345,13 @@ function takeBatch(pending) {
|
|
|
3832
6345
|
}
|
|
3833
6346
|
|
|
3834
6347
|
// src/session.ts
|
|
3835
|
-
import { spawn as
|
|
6348
|
+
import { spawn as spawn5 } from "node:child_process";
|
|
3836
6349
|
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
3837
|
-
import { basename, dirname as
|
|
6350
|
+
import { basename as basename2, dirname as dirname8 } from "node:path";
|
|
3838
6351
|
import { createInterface as createInterface2 } from "node:readline";
|
|
3839
6352
|
|
|
3840
6353
|
// src/tool-grants.ts
|
|
3841
|
-
import { dirname as
|
|
6354
|
+
import { dirname as dirname7, join as join13, posix } from "node:path";
|
|
3842
6355
|
var isGrantableDenial = isGrantableToolDenial;
|
|
3843
6356
|
var FILE_TOOLS2 = /* @__PURE__ */ new Set(["Read", "Edit", "MultiEdit", "Write", "NotebookEdit"]);
|
|
3844
6357
|
var EDIT_TOOLS = /* @__PURE__ */ new Set(["Edit", "MultiEdit", "Write", "NotebookEdit"]);
|
|
@@ -4036,7 +6549,7 @@ function filePatternMatches(spec, file) {
|
|
|
4036
6549
|
let pattern = spec.trim();
|
|
4037
6550
|
if (pattern.startsWith("~/")) {
|
|
4038
6551
|
if (!home) return false;
|
|
4039
|
-
pattern = rulePath(
|
|
6552
|
+
pattern = rulePath(join13(home, pattern.slice(2)).replace(/\\/g, "/"));
|
|
4040
6553
|
}
|
|
4041
6554
|
if (!pattern.startsWith("//")) return false;
|
|
4042
6555
|
const path = rulePath(file);
|
|
@@ -4057,7 +6570,7 @@ function shellPatternMatches(spec, command) {
|
|
|
4057
6570
|
return new RegExp(`^${re}${optionalTail ? "(?: .*)?" : ""}$`, "s").test(command);
|
|
4058
6571
|
}
|
|
4059
6572
|
function toolGrantsFile(configFile) {
|
|
4060
|
-
return
|
|
6573
|
+
return join13(dirname7(configFile), "tool-grants.json");
|
|
4061
6574
|
}
|
|
4062
6575
|
var ToolGrantStore = class {
|
|
4063
6576
|
constructor(file) {
|
|
@@ -4223,40 +6736,57 @@ function ghError(command, res) {
|
|
|
4223
6736
|
}
|
|
4224
6737
|
|
|
4225
6738
|
// src/session-store.ts
|
|
4226
|
-
import { mkdir as
|
|
4227
|
-
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";
|
|
4228
6741
|
var HANDLED_COMMAND_IDS_KEPT = 100;
|
|
6742
|
+
var pendingWrites = /* @__PURE__ */ new Map();
|
|
4229
6743
|
var SessionStore = class {
|
|
4230
6744
|
constructor(stateDir) {
|
|
4231
6745
|
this.stateDir = stateDir;
|
|
4232
6746
|
}
|
|
4233
6747
|
dir(sessionId) {
|
|
4234
|
-
return
|
|
6748
|
+
return join14(this.stateDir, "sessions", sessionId);
|
|
4235
6749
|
}
|
|
4236
6750
|
outboxFile(sessionId) {
|
|
4237
|
-
return
|
|
6751
|
+
return join14(this.dir(sessionId), "outbox.json");
|
|
4238
6752
|
}
|
|
6753
|
+
/**
|
|
6754
|
+
* Writes the record as it is now. A session's saves land in the order they were made:
|
|
6755
|
+
* two in flight at once (a turn's start and its quick result) could otherwise rename in
|
|
6756
|
+
* either order and leave the older state on disk, such as a turn still active, which a
|
|
6757
|
+
* restarted runner would then report as cut short.
|
|
6758
|
+
*/
|
|
4239
6759
|
async save(record) {
|
|
4240
6760
|
record.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
4241
|
-
|
|
6761
|
+
const file = join14(this.dir(record.sessionId), "session.json");
|
|
6762
|
+
const snapshot = JSON.parse(JSON.stringify(record));
|
|
6763
|
+
const previous = pendingWrites.get(file) ?? Promise.resolve();
|
|
6764
|
+
const write = previous.then(() => writeJsonAtomic(file, snapshot));
|
|
6765
|
+
const settled = write.catch(() => void 0);
|
|
6766
|
+
pendingWrites.set(file, settled);
|
|
6767
|
+
void settled.then(() => {
|
|
6768
|
+
if (pendingWrites.get(file) === settled) pendingWrites.delete(file);
|
|
6769
|
+
});
|
|
6770
|
+
await write;
|
|
4242
6771
|
}
|
|
4243
6772
|
async list() {
|
|
4244
|
-
const root =
|
|
4245
|
-
await
|
|
6773
|
+
const root = join14(this.stateDir, "sessions");
|
|
6774
|
+
await mkdir8(root, { recursive: true });
|
|
4246
6775
|
const out = [];
|
|
4247
|
-
for (const entry of await
|
|
6776
|
+
for (const entry of await readdir3(root, { withFileTypes: true })) {
|
|
4248
6777
|
if (!entry.isDirectory()) continue;
|
|
4249
|
-
const rec = await readJson(
|
|
6778
|
+
const rec = await readJson(join14(root, entry.name, "session.json"));
|
|
4250
6779
|
if (rec?.sessionId === entry.name) out.push(upgradeRecord(rec));
|
|
4251
6780
|
}
|
|
4252
6781
|
return out;
|
|
4253
6782
|
}
|
|
4254
6783
|
async remove(sessionId) {
|
|
4255
|
-
await
|
|
6784
|
+
await pendingWrites.get(join14(this.dir(sessionId), "session.json"));
|
|
6785
|
+
await rm6(this.dir(sessionId), { recursive: true, force: true });
|
|
4256
6786
|
}
|
|
4257
6787
|
/** Scratch working directory for a session without a repository. */
|
|
4258
6788
|
scratchDir(sessionId) {
|
|
4259
|
-
return
|
|
6789
|
+
return join14(this.stateDir, "scratch", sessionId);
|
|
4260
6790
|
}
|
|
4261
6791
|
};
|
|
4262
6792
|
function upgradeRecord(stored) {
|
|
@@ -4274,7 +6804,7 @@ var DENIALS_KEPT = 200;
|
|
|
4274
6804
|
var AgentSession = class {
|
|
4275
6805
|
constructor(record, deps) {
|
|
4276
6806
|
this.record = record;
|
|
4277
|
-
this.deps = deps;
|
|
6807
|
+
this.deps = { ...deps, logger: redactingLogger(deps.logger, deps.environment?.redactor) };
|
|
4278
6808
|
this.driver = deps.driver;
|
|
4279
6809
|
this.mapper = deps.driver.createMapper();
|
|
4280
6810
|
this.permissions = new PermissionRelay({
|
|
@@ -4297,7 +6827,7 @@ var AgentSession = class {
|
|
|
4297
6827
|
input
|
|
4298
6828
|
),
|
|
4299
6829
|
// Only with a repository to save a rule for.
|
|
4300
|
-
suggestRule: (tool, input) => toolGrantRepositoryKey(this.record.repository) ?
|
|
6830
|
+
suggestRule: (tool, input) => toolGrantRepositoryKey(this.record.repository) ? this.suggestSafeRules(tool, input)?.suggestedRule ?? null : null,
|
|
4301
6831
|
rememberRule: (rule) => {
|
|
4302
6832
|
const rules = this.record.grantRules ??= [];
|
|
4303
6833
|
if (rules.includes(rule)) return;
|
|
@@ -4305,6 +6835,7 @@ var AgentSession = class {
|
|
|
4305
6835
|
void this.deps.store.save(this.record).catch(() => void 0);
|
|
4306
6836
|
this.deps.logger.info(`session ${this.sessionId}: allowed ${rule} for this repository`);
|
|
4307
6837
|
},
|
|
6838
|
+
redactInput: deps.environment?.redactor.active ? (input) => deps.environment.redactor.redactDeep(input) : void 0,
|
|
4308
6839
|
timeoutMs: deps.permissionTimeoutMs
|
|
4309
6840
|
});
|
|
4310
6841
|
}
|
|
@@ -4325,6 +6856,8 @@ var AgentSession = class {
|
|
|
4325
6856
|
interruptTimer = null;
|
|
4326
6857
|
controlSeq = 0;
|
|
4327
6858
|
stderrTail = "";
|
|
6859
|
+
/** `stderrTail` lost its start (it keeps the last 4,000 characters). */
|
|
6860
|
+
stderrCut = false;
|
|
4328
6861
|
sawResultSinceSpawn = false;
|
|
4329
6862
|
/** The process was started to resume, and has not yet said it has the conversation. */
|
|
4330
6863
|
spawnedWithResume = false;
|
|
@@ -4369,6 +6902,42 @@ var AgentSession = class {
|
|
|
4369
6902
|
inheritedNow = { allow: [], deny: [], ask: [], sources: [] };
|
|
4370
6903
|
/** The folders those rules came from, once logged. */
|
|
4371
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
|
+
}
|
|
4372
6941
|
/** The person's Claude Code rules for the repository; the last read if it fails. */
|
|
4373
6942
|
async readInheritedRules() {
|
|
4374
6943
|
try {
|
|
@@ -4426,18 +6995,22 @@ var AgentSession = class {
|
|
|
4426
6995
|
* Reports a tool call that was denied because nobody could answer for it, with the rules
|
|
4427
6996
|
* a person could grant. Each call once; nothing for sessions not asked to report them.
|
|
4428
6997
|
*/
|
|
4429
|
-
reportDenial(callId, toolName,
|
|
6998
|
+
reportDenial(callId, toolName, rawInput) {
|
|
4430
6999
|
if (!this.record.reportToolDenials) return;
|
|
4431
7000
|
if (callId) {
|
|
4432
7001
|
if (this.seenFailedCalls.size > 1e3) this.seenFailedCalls.clear();
|
|
4433
7002
|
this.seenFailedCalls.add(callId);
|
|
4434
7003
|
}
|
|
4435
|
-
const rules =
|
|
7004
|
+
const rules = this.suggestSafeRules(toolName, rawInput);
|
|
4436
7005
|
if (!rules) return;
|
|
7006
|
+
const redactor = this.deps.environment?.redactor;
|
|
4437
7007
|
const denial = {
|
|
4438
7008
|
id: randomUUID2(),
|
|
4439
7009
|
toolName,
|
|
4440
|
-
inputSummary: summarizeToolInput(
|
|
7010
|
+
inputSummary: summarizeToolInput(
|
|
7011
|
+
toolName,
|
|
7012
|
+
redactor?.active ? redactor.redactDeep(rawInput) : rawInput
|
|
7013
|
+
),
|
|
4441
7014
|
...rules,
|
|
4442
7015
|
deniedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
4443
7016
|
};
|
|
@@ -4546,8 +7119,36 @@ var AgentSession = class {
|
|
|
4546
7119
|
get turnActive() {
|
|
4547
7120
|
return this.record.turnActive;
|
|
4548
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
|
+
*/
|
|
4549
7126
|
emit(...events) {
|
|
4550
|
-
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
|
+
});
|
|
4551
7152
|
}
|
|
4552
7153
|
/** Starts the process on the session's task (first turn). */
|
|
4553
7154
|
async startFirstTurn(prompt) {
|
|
@@ -4630,7 +7231,7 @@ var AgentSession = class {
|
|
|
4630
7231
|
const reaped = this.treeReaped;
|
|
4631
7232
|
this.stopping = reason;
|
|
4632
7233
|
this.reapGraceMs = graceMs;
|
|
4633
|
-
const exited = new Promise((
|
|
7234
|
+
const exited = new Promise((resolve4) => this.exitWaiters.push(resolve4));
|
|
4634
7235
|
if (child.exitCode === null && child.signalCode === null) {
|
|
4635
7236
|
await snapshotTree(this.tree, this.deps.reap);
|
|
4636
7237
|
}
|
|
@@ -4774,7 +7375,7 @@ ${text}` : text;
|
|
|
4774
7375
|
/** Resolves once the current process has exited (and its exit has been handled). */
|
|
4775
7376
|
waitForExit() {
|
|
4776
7377
|
if (!this.child) return Promise.resolve();
|
|
4777
|
-
return new Promise((
|
|
7378
|
+
return new Promise((resolve4) => this.exitWaiters.push(resolve4));
|
|
4778
7379
|
}
|
|
4779
7380
|
/** persistent agents: the session's process, started (resuming) when there is none. */
|
|
4780
7381
|
async ensureProcess() {
|
|
@@ -4784,6 +7385,7 @@ ${text}` : text;
|
|
|
4784
7385
|
}
|
|
4785
7386
|
/** Starts the agent's process (with a per_turn agent's prompt), and reads what it says. */
|
|
4786
7387
|
async spawnAgent(prompt) {
|
|
7388
|
+
this.tellEnvironmentLost();
|
|
4787
7389
|
await this.prepareEvidenceDir();
|
|
4788
7390
|
const { bin, features } = await this.deps.resolveAgent();
|
|
4789
7391
|
const savedRules = await (this.deps.savedRules?.(this.record.repository) ?? []);
|
|
@@ -4815,14 +7417,17 @@ ${text}` : text;
|
|
|
4815
7417
|
workBranch: this.record.workBranch,
|
|
4816
7418
|
baseRef: this.record.baseRef,
|
|
4817
7419
|
cwd: this.record.cwd,
|
|
4818
|
-
reviewImages: !!this.record.reviewImages
|
|
7420
|
+
reviewImages: !!this.record.reviewImages,
|
|
7421
|
+
reference: this.record.referenceRepository ?? null,
|
|
7422
|
+
environment: this.deps.environment ? { names: this.deps.environment.names, secretNames: this.deps.environment.secretNames } : null
|
|
4819
7423
|
}),
|
|
4820
7424
|
...prompt !== void 0 ? { prompt } : {},
|
|
4821
7425
|
...this.deps.agentConfig ? { agentConfig: this.deps.agentConfig } : {}
|
|
4822
7426
|
});
|
|
4823
|
-
const
|
|
7427
|
+
const runEnv = this.deps.environment?.env;
|
|
7428
|
+
const child = spawn5(launch.bin, launch.args, {
|
|
4824
7429
|
cwd: this.record.cwd,
|
|
4825
|
-
env: launch.env ? { ...process.env, ...launch.env } : process.env,
|
|
7430
|
+
env: launch.env || runEnv ? { ...process.env, ...runEnv, ...launch.env } : process.env,
|
|
4826
7431
|
stdio: ["pipe", "pipe", "pipe"],
|
|
4827
7432
|
windowsHide: true,
|
|
4828
7433
|
// A process group of its own, so what it starts can be ended with it. It also means
|
|
@@ -4830,10 +7435,10 @@ ${text}` : text;
|
|
|
4830
7435
|
detached: OWN_PROCESS_GROUP
|
|
4831
7436
|
});
|
|
4832
7437
|
let tree = null;
|
|
4833
|
-
await new Promise((
|
|
7438
|
+
await new Promise((resolve4, reject) => {
|
|
4834
7439
|
child.once("spawn", () => {
|
|
4835
7440
|
tree = trackTree(child, this.record.cwd || void 0);
|
|
4836
|
-
|
|
7441
|
+
resolve4();
|
|
4837
7442
|
});
|
|
4838
7443
|
child.once(
|
|
4839
7444
|
"error",
|
|
@@ -4848,6 +7453,7 @@ ${text}` : text;
|
|
|
4848
7453
|
this.resumeDoomed = false;
|
|
4849
7454
|
this.reapGraceMs = void 0;
|
|
4850
7455
|
this.stderrTail = "";
|
|
7456
|
+
this.stderrCut = false;
|
|
4851
7457
|
this.sawResultSinceSpawn = false;
|
|
4852
7458
|
this.spawnedWithResume = !!this.record.conversationId;
|
|
4853
7459
|
this.sawInitSinceSpawn = false;
|
|
@@ -4856,13 +7462,15 @@ ${text}` : text;
|
|
|
4856
7462
|
{ pid: child.pid }
|
|
4857
7463
|
);
|
|
4858
7464
|
this.treeReaped = new Promise(
|
|
4859
|
-
(
|
|
7465
|
+
(resolve4) => child.once("exit", () => void reapTree(tree, this.reapGraceMs, this.deps.reap).then(resolve4))
|
|
4860
7466
|
);
|
|
4861
7467
|
child.stdin.on("error", () => void 0);
|
|
4862
7468
|
if (launch.stdin !== void 0) child.stdin.end(launch.stdin);
|
|
4863
7469
|
else if (this.driver.processModel === "per_turn") child.stdin.end();
|
|
4864
7470
|
child.stderr.setEncoding("utf8").on("data", (d) => {
|
|
4865
|
-
|
|
7471
|
+
const tail = this.stderrTail + d;
|
|
7472
|
+
if (tail.length > 4e3) this.stderrCut = true;
|
|
7473
|
+
this.stderrTail = tail.slice(-4e3);
|
|
4866
7474
|
});
|
|
4867
7475
|
const rl = createInterface2({ input: child.stdout, crlfDelay: Infinity });
|
|
4868
7476
|
rl.on("line", (line) => {
|
|
@@ -4964,7 +7572,9 @@ ${text}` : text;
|
|
|
4964
7572
|
this.resumeRetry = this.turnText;
|
|
4965
7573
|
this.record.conversationId = null;
|
|
4966
7574
|
}
|
|
4967
|
-
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;
|
|
4968
7578
|
this.permissions.expireAll(PERMISSION_EXPIRED_TURN_ENDED);
|
|
4969
7579
|
for (const d of turn.permissionDenials ?? []) {
|
|
4970
7580
|
if (d.callId && this.seenFailedCalls.has(d.callId)) continue;
|
|
@@ -4987,13 +7597,13 @@ ${text}` : text;
|
|
|
4987
7597
|
const push = await this.pushWork();
|
|
4988
7598
|
const screenshots = push.failed ? "" : await this.publishScreenshots().catch((err) => {
|
|
4989
7599
|
this.deps.logger.warn(`session ${this.sessionId}: publishing screenshots failed`, {
|
|
4990
|
-
error:
|
|
7600
|
+
error: this.safeError(err)
|
|
4991
7601
|
});
|
|
4992
7602
|
return "";
|
|
4993
7603
|
});
|
|
4994
7604
|
await this.uploadReviewImages().catch((err) => {
|
|
4995
7605
|
this.deps.logger.warn(`session ${this.sessionId}: uploading review images failed`, {
|
|
4996
|
-
error:
|
|
7606
|
+
error: this.safeError(err)
|
|
4997
7607
|
});
|
|
4998
7608
|
});
|
|
4999
7609
|
const failed = turnFailed || push.failed;
|
|
@@ -5038,8 +7648,10 @@ ${text}` : text;
|
|
|
5038
7648
|
const { pullRequest, workBranch, repository, baseRef } = this.record;
|
|
5039
7649
|
const repo = parseRepoUrl(repository ?? "");
|
|
5040
7650
|
if (!pullRequest || !workBranch || !repo) return null;
|
|
7651
|
+
const redactor = this.deps.environment?.redactor;
|
|
7652
|
+
const said = text && redactor ? redactor.redact(text) : text;
|
|
5041
7653
|
const body = [
|
|
5042
|
-
|
|
7654
|
+
said?.trim() || `Work by the ${this.driver.displayName} (local) agent.`,
|
|
5043
7655
|
"",
|
|
5044
7656
|
"---",
|
|
5045
7657
|
pullRequest.footer
|
|
@@ -5085,7 +7697,7 @@ ${text}` : text;
|
|
|
5085
7697
|
await ensureEvidenceDir(this.record.cwd);
|
|
5086
7698
|
} catch (err) {
|
|
5087
7699
|
this.deps.logger.warn(`session ${this.sessionId}: could not prepare the screenshot folder`, {
|
|
5088
|
-
error:
|
|
7700
|
+
error: this.safeError(err)
|
|
5089
7701
|
});
|
|
5090
7702
|
}
|
|
5091
7703
|
}
|
|
@@ -5125,7 +7737,7 @@ ${text}` : text;
|
|
|
5125
7737
|
async publishScreenshots() {
|
|
5126
7738
|
const { workBranch, repoDir, cwd, repository } = this.record;
|
|
5127
7739
|
const repo = parseRepoUrl(
|
|
5128
|
-
repository ?? (repoDir ? `https://github.com/${
|
|
7740
|
+
repository ?? (repoDir ? `https://github.com/${basename2(dirname8(repoDir))}/${basename2(repoDir)}` : "")
|
|
5129
7741
|
);
|
|
5130
7742
|
if (!workBranch || !repoDir || !repo) return "";
|
|
5131
7743
|
const res = await publishEvidence({ repoDir, worktree: cwd, workBranch, repo });
|
|
@@ -5250,10 +7862,10 @@ ${text}` : text;
|
|
|
5250
7862
|
await this.endTurn({ text: null, isError: true, subtype: "interrupted" });
|
|
5251
7863
|
return;
|
|
5252
7864
|
}
|
|
5253
|
-
const
|
|
5254
|
-
|
|
5255
|
-
|
|
5256
|
-
);
|
|
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);
|
|
5257
7869
|
const how = signal ? `was killed (${signal})` : `exited with code ${code}`;
|
|
5258
7870
|
const hint = this.sawResultSinceSpawn ? "" : this.driver.startupHint(this.stderrTail);
|
|
5259
7871
|
if (!this.sawResultSinceSpawn && this.driver.looksLikeSignInFailure(this.stderrTail)) {
|
|
@@ -5276,8 +7888,8 @@ ${text}` : text;
|
|
|
5276
7888
|
};
|
|
5277
7889
|
async function raceTimeout(done, ms) {
|
|
5278
7890
|
let timer;
|
|
5279
|
-
const timeout = new Promise((
|
|
5280
|
-
timer = setTimeout(() =>
|
|
7891
|
+
const timeout = new Promise((resolve4) => {
|
|
7892
|
+
timer = setTimeout(() => resolve4(true), ms);
|
|
5281
7893
|
});
|
|
5282
7894
|
try {
|
|
5283
7895
|
return await Promise.race([done.then(() => false), timeout]);
|
|
@@ -5327,6 +7939,23 @@ var SessionManager = class {
|
|
|
5327
7939
|
resuming = /* @__PURE__ */ new Set();
|
|
5328
7940
|
store;
|
|
5329
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();
|
|
5330
7959
|
/** Loads sessions a previous run left, ends turns it was in the middle of, resumes posting. */
|
|
5331
7960
|
async restore() {
|
|
5332
7961
|
for (const record of await this.store.list()) {
|
|
@@ -5364,6 +7993,20 @@ var SessionManager = class {
|
|
|
5364
7993
|
get(sessionId) {
|
|
5365
7994
|
return this.sessions.get(sessionId);
|
|
5366
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
|
+
}
|
|
5367
8010
|
async handle(cmd) {
|
|
5368
8011
|
try {
|
|
5369
8012
|
assertSafeSessionId(cmd.sessionId);
|
|
@@ -5388,8 +8031,10 @@ var SessionManager = class {
|
|
|
5388
8031
|
};
|
|
5389
8032
|
}
|
|
5390
8033
|
} catch (err) {
|
|
5391
|
-
|
|
5392
|
-
|
|
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 });
|
|
5393
8038
|
}
|
|
5394
8039
|
}
|
|
5395
8040
|
noteStart(sessionId, ack) {
|
|
@@ -5445,11 +8090,21 @@ var SessionManager = class {
|
|
|
5445
8090
|
error: `The runner is busy: it is already running ${max} session(s).`
|
|
5446
8091
|
};
|
|
5447
8092
|
}
|
|
5448
|
-
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
|
+
});
|
|
5449
8103
|
this.starting.set(cmd.sessionId, promise);
|
|
5450
8104
|
return promise;
|
|
5451
8105
|
}
|
|
5452
8106
|
async startSession(cmd) {
|
|
8107
|
+
await this.releasing?.catch(() => void 0);
|
|
5453
8108
|
const label = cmd.title ? `"${cmd.title.slice(0, 80)}"` : `run ${cmd.runId}`;
|
|
5454
8109
|
this.opts.logger.info(`session ${cmd.sessionId}: starting ${label}`, {
|
|
5455
8110
|
repo: cmd.repository?.url,
|
|
@@ -5463,17 +8118,41 @@ var SessionManager = class {
|
|
|
5463
8118
|
);
|
|
5464
8119
|
}
|
|
5465
8120
|
const resume = cmd.resume ?? null;
|
|
8121
|
+
const keepWorkspace = resume?.keepWorkspace === true;
|
|
8122
|
+
const earlier = [];
|
|
5466
8123
|
if (resume) {
|
|
5467
8124
|
for (const other of [...this.sessions.values()]) {
|
|
5468
|
-
if (other.record.runId
|
|
8125
|
+
if (other.record.runId !== cmd.runId || other.sessionId === cmd.sessionId) continue;
|
|
8126
|
+
if (!keepWorkspace) {
|
|
5469
8127
|
await this.close(other.sessionId);
|
|
8128
|
+
continue;
|
|
5470
8129
|
}
|
|
8130
|
+
if (other.record.cwd) this.takenOver.set(other.record.cwd, cmd.sessionId);
|
|
8131
|
+
earlier.push(other);
|
|
8132
|
+
await other.stop("idle");
|
|
5471
8133
|
}
|
|
5472
8134
|
await Promise.allSettled([...this.closing.values()]);
|
|
5473
8135
|
this.opts.logger.info(`session ${cmd.sessionId}: continuing run ${cmd.runId}`, {
|
|
5474
|
-
resume: resume.conversationId ?? resume.claudeSessionId ? "conversation" : "fresh"
|
|
8136
|
+
resume: resume.conversationId ?? resume.claudeSessionId ? "conversation" : "fresh",
|
|
8137
|
+
...keepWorkspace ? { keepWorkspace: true } : {}
|
|
5475
8138
|
});
|
|
5476
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
|
+
}
|
|
5477
8156
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
5478
8157
|
const record = {
|
|
5479
8158
|
sessionId: cmd.sessionId,
|
|
@@ -5492,11 +8171,23 @@ var SessionManager = class {
|
|
|
5492
8171
|
...alwaysAllowTools(cmd).length ? { alwaysAllowedTools: alwaysAllowTools(cmd) } : {},
|
|
5493
8172
|
...cmd.reportToolDenials === true ? { reportToolDenials: true } : {},
|
|
5494
8173
|
...grantRules(cmd).length ? { grantRules: grantRules(cmd) } : {},
|
|
8174
|
+
...environment?.names.length ? { environmentNames: environment.names } : {},
|
|
5495
8175
|
createdAt: now,
|
|
5496
8176
|
updatedAt: now
|
|
5497
8177
|
};
|
|
5498
8178
|
try {
|
|
5499
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
|
+
};
|
|
5500
8191
|
const wt = await prepareWorktree({
|
|
5501
8192
|
url: cmd.repository.url,
|
|
5502
8193
|
baseRef: cmd.repository.baseRef,
|
|
@@ -5506,8 +8197,13 @@ var SessionManager = class {
|
|
|
5506
8197
|
sessionId: cmd.sessionId,
|
|
5507
8198
|
protocol: this.opts.config.gitProtocol,
|
|
5508
8199
|
continueBranch: !!resume,
|
|
5509
|
-
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?.();
|
|
5510
8205
|
});
|
|
8206
|
+
await this.unkeep(wt.worktree);
|
|
5511
8207
|
Object.assign(record, {
|
|
5512
8208
|
cwd: wt.worktree,
|
|
5513
8209
|
repoDir: wt.repoDir,
|
|
@@ -5518,13 +8214,31 @@ var SessionManager = class {
|
|
|
5518
8214
|
baseSha: wt.baseSha,
|
|
5519
8215
|
// A reused kept worktree still holds the uncommitted changes it was kept for: keep
|
|
5520
8216
|
// protecting it until a turn commits them, or a close before then would delete them.
|
|
5521
|
-
|
|
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 } : {}
|
|
5522
8219
|
});
|
|
5523
|
-
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) {
|
|
5524
8233
|
this.opts.logger.warn(
|
|
5525
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}`
|
|
5526
8235
|
);
|
|
5527
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
|
+
}
|
|
5528
8242
|
if (wt.setAside) {
|
|
5529
8243
|
this.opts.logger.warn(
|
|
5530
8244
|
`session ${cmd.sessionId}: an earlier working copy with uncommitted changes could not be reused; it was moved to ${wt.setAside}`
|
|
@@ -5534,14 +8248,63 @@ var SessionManager = class {
|
|
|
5534
8248
|
record.cwd = this.store.scratchDir(
|
|
5535
8249
|
resume ? safeWorktreeKey(resume.worktreeKey, cmd.sessionId) : cmd.sessionId
|
|
5536
8250
|
);
|
|
5537
|
-
await
|
|
8251
|
+
const keptEntry = keepWorkspace ? await this.keptEntry(record.cwd) : null;
|
|
8252
|
+
await this.unkeep(record.cwd);
|
|
8253
|
+
await mkdir9(record.cwd, { recursive: true });
|
|
5538
8254
|
if (cmd.reviewImages === true && this.opts.reviewImageUploader) {
|
|
5539
8255
|
record.reviewImages = true;
|
|
5540
|
-
await
|
|
8256
|
+
await mkdir9(join15(record.cwd, EVIDENCE_DIR), { recursive: true });
|
|
8257
|
+
}
|
|
8258
|
+
const reference = cmd.referenceRepository;
|
|
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) {
|
|
8284
|
+
try {
|
|
8285
|
+
const checkout = await prepareReferenceCheckout({
|
|
8286
|
+
url: reference.url,
|
|
8287
|
+
baseRef: reference.baseRef ?? null,
|
|
8288
|
+
reposDir: this.opts.config.reposDir,
|
|
8289
|
+
dir: join15(record.cwd, RUNNER_REFERENCE_REPOSITORY_DIR),
|
|
8290
|
+
protocol: this.opts.config.gitProtocol
|
|
8291
|
+
}).finally(() => referenceHold?.());
|
|
8292
|
+
record.referenceRepository = {
|
|
8293
|
+
url: reference.url,
|
|
8294
|
+
baseRef: checkout.baseRef,
|
|
8295
|
+
dir: checkout.dir,
|
|
8296
|
+
repoDir: checkout.repoDir
|
|
8297
|
+
};
|
|
8298
|
+
} catch (err) {
|
|
8299
|
+
this.opts.logger.warn(
|
|
8300
|
+
`session ${cmd.sessionId}: could not check out ${reference.url} for the agent to read; it works without it`,
|
|
8301
|
+
{ error: safeError2(err, environment?.redactor) }
|
|
8302
|
+
);
|
|
8303
|
+
}
|
|
5541
8304
|
}
|
|
5542
8305
|
const deliverable = resume?.deliverable;
|
|
5543
8306
|
if (typeof deliverable === "string" && deliverable.trim()) {
|
|
5544
|
-
await
|
|
8307
|
+
await writeFile6(join15(record.cwd, RUNNER_DELIVERABLE_FILE), deliverable, "utf8");
|
|
5545
8308
|
}
|
|
5546
8309
|
}
|
|
5547
8310
|
if (resume) {
|
|
@@ -5550,19 +8313,21 @@ var SessionManager = class {
|
|
|
5550
8313
|
}
|
|
5551
8314
|
await this.store.save(record);
|
|
5552
8315
|
} catch (err) {
|
|
8316
|
+
const error = safeError2(err, environment?.redactor);
|
|
5553
8317
|
this.opts.logger.error(`session ${cmd.sessionId}: could not prepare the workspace`, {
|
|
5554
|
-
error
|
|
8318
|
+
error
|
|
5555
8319
|
});
|
|
5556
8320
|
await this.store.remove(cmd.sessionId).catch(() => void 0);
|
|
5557
|
-
return { ok: false, error
|
|
8321
|
+
return { ok: false, error };
|
|
5558
8322
|
}
|
|
5559
|
-
const session = await this.openSession(record);
|
|
8323
|
+
const session = await this.openSession(record, environment);
|
|
5560
8324
|
this.sessions.set(cmd.sessionId, session);
|
|
8325
|
+
for (const other of earlier) await this.close(other.sessionId);
|
|
5561
8326
|
if (resume) return { ok: true };
|
|
5562
8327
|
try {
|
|
5563
|
-
await session.startFirstTurn(cmd
|
|
8328
|
+
await session.startFirstTurn(await this.promptWithImages(cmd, record));
|
|
5564
8329
|
} catch (err) {
|
|
5565
|
-
const message =
|
|
8330
|
+
const message = safeError2(err, environment?.redactor);
|
|
5566
8331
|
this.opts.logger.error(`session ${cmd.sessionId}: ${message}`);
|
|
5567
8332
|
session.emit(
|
|
5568
8333
|
{ type: "error", message, retryable: false },
|
|
@@ -5570,7 +8335,7 @@ var SessionManager = class {
|
|
|
5570
8335
|
);
|
|
5571
8336
|
await this.forgetFailedStart(session).catch(
|
|
5572
8337
|
(e) => this.opts.logger.warn(`session ${cmd.sessionId}: could not clean up the failed start`, {
|
|
5573
|
-
error:
|
|
8338
|
+
error: safeError2(e, environment?.redactor)
|
|
5574
8339
|
})
|
|
5575
8340
|
);
|
|
5576
8341
|
return { ok: false, error: message };
|
|
@@ -5699,6 +8464,36 @@ var SessionManager = class {
|
|
|
5699
8464
|
* session's folder), then the session is removed as a close would remove it. Called from
|
|
5700
8465
|
* inside the start, so it does not wait for the start as `close` does.
|
|
5701
8466
|
*/
|
|
8467
|
+
/**
|
|
8468
|
+
* The first turn's prompt, with the paths of the images it names (`promptImages`) saved in
|
|
8469
|
+
* the session's working directory. Never fails the start: an image that cannot be fetched
|
|
8470
|
+
* is listed as such, and so are all of them when there is nothing to fetch them with.
|
|
8471
|
+
*/
|
|
8472
|
+
async promptWithImages(cmd, record) {
|
|
8473
|
+
const images = Array.isArray(cmd.promptImages) ? cmd.promptImages : [];
|
|
8474
|
+
if (images.length === 0) return cmd.prompt;
|
|
8475
|
+
const fetcher = this.opts.promptImageFetcher;
|
|
8476
|
+
let saved = {
|
|
8477
|
+
saved: [],
|
|
8478
|
+
failed: images.map((i) => i.filename)
|
|
8479
|
+
};
|
|
8480
|
+
if (fetcher) {
|
|
8481
|
+
try {
|
|
8482
|
+
saved = await savePromptImages({
|
|
8483
|
+
sessionId: cmd.sessionId,
|
|
8484
|
+
cwd: record.cwd,
|
|
8485
|
+
inRepository: !!record.repoDir,
|
|
8486
|
+
images,
|
|
8487
|
+
fetcher
|
|
8488
|
+
});
|
|
8489
|
+
} catch (err) {
|
|
8490
|
+
this.opts.logger.warn(`session ${cmd.sessionId}: could not save the task's images`, {
|
|
8491
|
+
error: safeError2(err)
|
|
8492
|
+
});
|
|
8493
|
+
}
|
|
8494
|
+
}
|
|
8495
|
+
return promptWithImagePaths(cmd.prompt, saved);
|
|
8496
|
+
}
|
|
5702
8497
|
async forgetFailedStart(session) {
|
|
5703
8498
|
const { sessionId } = session;
|
|
5704
8499
|
await session.outbox.flush(this.opts.failedStartFlushMs ?? 5e3);
|
|
@@ -5716,22 +8511,186 @@ var SessionManager = class {
|
|
|
5716
8511
|
await session.stop("close");
|
|
5717
8512
|
await this.opts.beforeWorktreeRemoved?.(sessionId);
|
|
5718
8513
|
const { record } = session;
|
|
5719
|
-
|
|
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) {
|
|
5720
8544
|
this.opts.logger.warn(
|
|
5721
8545
|
`session ${sessionId}: keeping the worktree ${record.cwd}, which holds changes that could not be committed`
|
|
5722
8546
|
);
|
|
5723
|
-
} else if (
|
|
5724
|
-
|
|
5725
|
-
|
|
5726
|
-
error: safeError(err)
|
|
5727
|
-
})
|
|
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`
|
|
5728
8550
|
);
|
|
5729
|
-
|
|
5730
|
-
await rm6(record.cwd, { recursive: true, force: true }).catch(() => void 0);
|
|
8551
|
+
await this.keep(workspace);
|
|
5731
8552
|
}
|
|
5732
8553
|
await session.outbox.settled();
|
|
5733
8554
|
await this.store.remove(sessionId);
|
|
5734
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)
|
|
8579
|
+
})
|
|
8580
|
+
);
|
|
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)
|
|
8586
|
+
})
|
|
8587
|
+
);
|
|
8588
|
+
}
|
|
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
|
+
}
|
|
8693
|
+
}
|
|
5735
8694
|
}
|
|
5736
8695
|
/** Ends Claude Code processes that have been idle too long; their sessions stay resumable. */
|
|
5737
8696
|
async stopIdle(now = Date.now()) {
|
|
@@ -5781,7 +8740,8 @@ var SessionManager = class {
|
|
|
5781
8740
|
driverFor(kind) {
|
|
5782
8741
|
return this.opts.driver ?? agentDriver(kind);
|
|
5783
8742
|
}
|
|
5784
|
-
|
|
8743
|
+
/** `environment`: a start's, in memory; none for a session restored from disk. */
|
|
8744
|
+
async openSession(record, environment = null) {
|
|
5785
8745
|
const outbox = await SessionOutbox.open({
|
|
5786
8746
|
sessionId: record.sessionId,
|
|
5787
8747
|
file: this.store.outboxFile(record.sessionId),
|
|
@@ -5816,7 +8776,8 @@ var SessionManager = class {
|
|
|
5816
8776
|
permissionTimeoutMs: this.opts.permissionTimeoutMs,
|
|
5817
8777
|
savedRules: async (url) => this.opts.grants ? await this.opts.grants.rulesFor(url) : [],
|
|
5818
8778
|
reviewImageUploader: this.opts.reviewImageUploader,
|
|
5819
|
-
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
|
|
5820
8781
|
});
|
|
5821
8782
|
}
|
|
5822
8783
|
};
|
|
@@ -5838,6 +8799,20 @@ function alwaysAllowTools(cmd) {
|
|
|
5838
8799
|
)
|
|
5839
8800
|
];
|
|
5840
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
|
+
}
|
|
5841
8816
|
function safeWorktreeKey(key, fallback) {
|
|
5842
8817
|
if (!key) return fallback;
|
|
5843
8818
|
try {
|
|
@@ -5859,8 +8834,9 @@ ${task.slice(0, 2e4)}` : "",
|
|
|
5859
8834
|
"The person\u2019s message follows."
|
|
5860
8835
|
].filter(Boolean).join("\n\n");
|
|
5861
8836
|
}
|
|
5862
|
-
function
|
|
5863
|
-
|
|
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);
|
|
5864
8840
|
}
|
|
5865
8841
|
|
|
5866
8842
|
// src/daemon.ts
|
|
@@ -5874,6 +8850,16 @@ var RunnerDaemon = class {
|
|
|
5874
8850
|
this.opts = opts;
|
|
5875
8851
|
this.api = opts.api ?? new RunnerApi({ server: opts.config.server, token: opts.config.token });
|
|
5876
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
|
+
});
|
|
5877
8863
|
this.manager = new SessionManager({
|
|
5878
8864
|
config: opts.config,
|
|
5879
8865
|
poster: this.api,
|
|
@@ -5884,6 +8870,8 @@ var RunnerDaemon = class {
|
|
|
5884
8870
|
agentProblem: (driver) => this.agentProblem(driver),
|
|
5885
8871
|
grants: this.grants,
|
|
5886
8872
|
reviewImageUploader: this.api,
|
|
8873
|
+
promptImageFetcher: this.api,
|
|
8874
|
+
jobs: this.jobs,
|
|
5887
8875
|
// What the person already allows in their own Claude Code for a repository.
|
|
5888
8876
|
inherited: opts.config.inheritClaudeCodePermissions ? new ClaudeCodeRules({
|
|
5889
8877
|
exclude: [opts.config.reposDir, opts.config.worktreesDir]
|
|
@@ -5893,6 +8881,7 @@ var RunnerDaemon = class {
|
|
|
5893
8881
|
}
|
|
5894
8882
|
api;
|
|
5895
8883
|
manager;
|
|
8884
|
+
jobs;
|
|
5896
8885
|
controller = new AbortController();
|
|
5897
8886
|
exitReason = "stopped";
|
|
5898
8887
|
agentInfo = null;
|
|
@@ -5937,15 +8926,19 @@ var RunnerDaemon = class {
|
|
|
5937
8926
|
/** Runs until stopped (signal) or the token is refused. */
|
|
5938
8927
|
async run() {
|
|
5939
8928
|
const { logger, config } = this.opts;
|
|
8929
|
+
await this.jobs.restore();
|
|
5940
8930
|
await this.manager.restore();
|
|
8931
|
+
await this.manager.releaseKeptForJobs();
|
|
5941
8932
|
logger.info(`dt-runner ${RUNNER_VERSION} connected to ${config.server}`, {
|
|
5942
8933
|
maxSessions: config.maxSessions,
|
|
8934
|
+
maxJobs: config.maxJobs,
|
|
5943
8935
|
permissionMode: config.permissionMode
|
|
5944
8936
|
});
|
|
5945
8937
|
const loops = [this.heartbeatLoop(), this.commandLoop(), this.idleLoop()];
|
|
5946
8938
|
await Promise.all(loops);
|
|
5947
8939
|
await Promise.allSettled([...this.inFlight]);
|
|
5948
8940
|
await this.manager.shutdown();
|
|
8941
|
+
await this.jobs.shutdown();
|
|
5949
8942
|
return this.exitReason;
|
|
5950
8943
|
}
|
|
5951
8944
|
/** Begins a graceful stop; `run()` resolves once sessions are wound down. */
|
|
@@ -6092,13 +9085,32 @@ var RunnerDaemon = class {
|
|
|
6092
9085
|
// And attaches a design proposal's rendered screens to its task (`reviewImages`).
|
|
6093
9086
|
uploadsReviewImages: true,
|
|
6094
9087
|
// And keeps a continued non-code run's deliverable whole (`resume.deliverable`).
|
|
6095
|
-
receivesDeliverable: true
|
|
9088
|
+
receivesDeliverable: true,
|
|
9089
|
+
// And saves the images a prompt names as files for its agent (`promptImages`).
|
|
9090
|
+
receivesPromptImages: true,
|
|
9091
|
+
// And checks out a non-code task's repository for it to read (`referenceRepository`).
|
|
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
|
|
6096
9104
|
},
|
|
6097
9105
|
activeSessionIds: this.heartbeatSessionIds(),
|
|
6098
9106
|
maxConcurrentSessions: this.opts.config.maxSessions,
|
|
6099
9107
|
activeCompletionIds: [...this.completionControllers.keys()],
|
|
6100
|
-
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()
|
|
6101
9112
|
});
|
|
9113
|
+
if (res?.stopJobIds?.length) this.jobs.stopJobs(res.stopJobIds);
|
|
6102
9114
|
if (res?.toolGrantChanges?.length) {
|
|
6103
9115
|
for (const problem of await this.grants.apply(res.toolGrantChanges)) {
|
|
6104
9116
|
this.opts.logger.warn(`a saved tool permission was not applied: ${problem}`);
|
|
@@ -6156,6 +9168,7 @@ var RunnerDaemon = class {
|
|
|
6156
9168
|
attempt = 0;
|
|
6157
9169
|
limited = 0;
|
|
6158
9170
|
for (const cmd of res?.commands ?? []) this.track(this.dispatch(cmd));
|
|
9171
|
+
for (const cmd of res?.jobCommands ?? []) this.track(this.dispatchJob(cmd));
|
|
6159
9172
|
for (const req of res?.completions ?? []) this.track(this.answer(req));
|
|
6160
9173
|
} catch (err) {
|
|
6161
9174
|
if (this.signal.aborted) break;
|
|
@@ -6201,7 +9214,7 @@ var RunnerDaemon = class {
|
|
|
6201
9214
|
if (this.droppedSessionIds.has(id)) return;
|
|
6202
9215
|
this.droppedSessionIds.add(id);
|
|
6203
9216
|
this.opts.logger.warn(
|
|
6204
|
-
`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)})`
|
|
6205
9218
|
);
|
|
6206
9219
|
});
|
|
6207
9220
|
}
|
|
@@ -6233,6 +9246,15 @@ var RunnerDaemon = class {
|
|
|
6233
9246
|
}
|
|
6234
9247
|
await this.ack(cmd.id, ack);
|
|
6235
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
|
+
}
|
|
6236
9258
|
/**
|
|
6237
9259
|
* A slot to run a completion in: at once while fewer than the runner's session limit run,
|
|
6238
9260
|
* else after the next one ends. False when `cancelled` fires first: the request leaves
|
|
@@ -6244,15 +9266,15 @@ var RunnerDaemon = class {
|
|
|
6244
9266
|
this.completionsRunning++;
|
|
6245
9267
|
return Promise.resolve(true);
|
|
6246
9268
|
}
|
|
6247
|
-
return new Promise((
|
|
9269
|
+
return new Promise((resolve4) => {
|
|
6248
9270
|
const handOver = () => {
|
|
6249
9271
|
cancelled.removeEventListener("abort", leave);
|
|
6250
|
-
|
|
9272
|
+
resolve4(true);
|
|
6251
9273
|
};
|
|
6252
9274
|
const leave = () => {
|
|
6253
9275
|
const at = this.completionWaiters.indexOf(handOver);
|
|
6254
9276
|
if (at >= 0) this.completionWaiters.splice(at, 1);
|
|
6255
|
-
|
|
9277
|
+
resolve4(false);
|
|
6256
9278
|
};
|
|
6257
9279
|
this.completionWaiters.push(handOver);
|
|
6258
9280
|
cancelled.addEventListener("abort", leave, { once: true });
|
|
@@ -6427,67 +9449,8 @@ function formatChecks(checks) {
|
|
|
6427
9449
|
return checks.map((c) => `${mark[c.level]} ${c.name}: ${c.detail}`).join("\n");
|
|
6428
9450
|
}
|
|
6429
9451
|
|
|
6430
|
-
// src/lock.ts
|
|
6431
|
-
import { mkdir as mkdir7, open, readFile as readFile5, rm as rm7 } from "node:fs/promises";
|
|
6432
|
-
import { join as join13 } from "node:path";
|
|
6433
|
-
function lockFile(stateDir) {
|
|
6434
|
-
return join13(stateDir, "daemon.pid");
|
|
6435
|
-
}
|
|
6436
|
-
function pidAlive(pid) {
|
|
6437
|
-
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
6438
|
-
try {
|
|
6439
|
-
process.kill(pid, 0);
|
|
6440
|
-
return true;
|
|
6441
|
-
} catch (err) {
|
|
6442
|
-
return err.code === "EPERM";
|
|
6443
|
-
}
|
|
6444
|
-
}
|
|
6445
|
-
async function lockHolder(stateDir) {
|
|
6446
|
-
let raw;
|
|
6447
|
-
try {
|
|
6448
|
-
raw = await readFile5(lockFile(stateDir), "utf8");
|
|
6449
|
-
} catch {
|
|
6450
|
-
return null;
|
|
6451
|
-
}
|
|
6452
|
-
const pid = Number.parseInt(raw.trim(), 10);
|
|
6453
|
-
return pidAlive(pid) && pid !== process.pid ? pid : null;
|
|
6454
|
-
}
|
|
6455
|
-
async function acquireDaemonLock(stateDir, pid = process.pid) {
|
|
6456
|
-
await mkdir7(stateDir, { recursive: true, mode: 448 });
|
|
6457
|
-
const file = lockFile(stateDir);
|
|
6458
|
-
for (let attempt = 0; attempt < 3; attempt++) {
|
|
6459
|
-
try {
|
|
6460
|
-
const handle = await open(file, "wx", 384);
|
|
6461
|
-
try {
|
|
6462
|
-
await handle.writeFile(`${pid}
|
|
6463
|
-
`);
|
|
6464
|
-
} finally {
|
|
6465
|
-
await handle.close();
|
|
6466
|
-
}
|
|
6467
|
-
return {
|
|
6468
|
-
ok: true,
|
|
6469
|
-
lock: {
|
|
6470
|
-
file,
|
|
6471
|
-
async release() {
|
|
6472
|
-
const current2 = await readFile5(file, "utf8").catch(() => "");
|
|
6473
|
-
if (Number.parseInt(current2.trim(), 10) === pid) await rm7(file, { force: true });
|
|
6474
|
-
}
|
|
6475
|
-
}
|
|
6476
|
-
};
|
|
6477
|
-
} catch (err) {
|
|
6478
|
-
if (err.code !== "EEXIST") throw err;
|
|
6479
|
-
}
|
|
6480
|
-
const raw = await readFile5(file, "utf8").catch(() => null);
|
|
6481
|
-
if (raw === null) continue;
|
|
6482
|
-
const holder = Number.parseInt(raw.trim(), 10);
|
|
6483
|
-
if (pidAlive(holder) && holder !== pid) return { ok: false, pid: holder };
|
|
6484
|
-
await rm7(file, { force: true });
|
|
6485
|
-
}
|
|
6486
|
-
return { ok: false, pid: null };
|
|
6487
|
-
}
|
|
6488
|
-
|
|
6489
9452
|
// src/pairing.ts
|
|
6490
|
-
import { spawn as
|
|
9453
|
+
import { spawn as spawn6 } from "node:child_process";
|
|
6491
9454
|
async function pair(api, opts) {
|
|
6492
9455
|
const start2 = await api.startPairing({ name: opts.name, platform: RUNNER_PLATFORM });
|
|
6493
9456
|
opts.ui.showCode(start2.userCode, start2.verificationUrl, start2.expiresInSeconds);
|
|
@@ -6551,7 +9514,7 @@ function openUrl(url) {
|
|
|
6551
9514
|
if (!/^https?:\/\//i.test(url)) return;
|
|
6552
9515
|
const [cmd, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", url]] : ["xdg-open", [url]];
|
|
6553
9516
|
try {
|
|
6554
|
-
const child =
|
|
9517
|
+
const child = spawn6(cmd, args, { stdio: "ignore", detached: true, windowsHide: true });
|
|
6555
9518
|
child.on("error", () => void 0);
|
|
6556
9519
|
child.unref();
|
|
6557
9520
|
} catch {
|
|
@@ -6567,8 +9530,9 @@ Usage:
|
|
|
6567
9530
|
dt-runner login [--server <url>] [--name <name>] [--no-browser] [--yes]
|
|
6568
9531
|
Pair this computer with your Discovery Tree account.
|
|
6569
9532
|
--yes skips the "is this your account?" question.
|
|
6570
|
-
dt-runner start [--max-sessions <n>] [--repos-dir <dir>] [--json] [--verbose]
|
|
6571
|
-
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).
|
|
6572
9536
|
dt-runner status Show the configuration and check the connection.
|
|
6573
9537
|
dt-runner doctor Check Node.js, git and Claude Code on this computer.
|
|
6574
9538
|
dt-runner logout Forget this runner's token (deletes the config file).
|
|
@@ -6598,6 +9562,7 @@ async function main(argv) {
|
|
|
6598
9562
|
"no-browser": { type: "boolean" },
|
|
6599
9563
|
yes: { type: "boolean", short: "y" },
|
|
6600
9564
|
"max-sessions": { type: "string" },
|
|
9565
|
+
"max-jobs": { type: "string" },
|
|
6601
9566
|
"repos-dir": { type: "string" },
|
|
6602
9567
|
json: { type: "boolean" },
|
|
6603
9568
|
verbose: { type: "boolean" },
|
|
@@ -6620,6 +9585,7 @@ async function main(argv) {
|
|
|
6620
9585
|
case "start":
|
|
6621
9586
|
return start({
|
|
6622
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,
|
|
6623
9589
|
reposDir: values["repos-dir"],
|
|
6624
9590
|
json: values.json,
|
|
6625
9591
|
verbose: values.verbose
|
|
@@ -6704,6 +9670,7 @@ async function start(opts) {
|
|
|
6704
9670
|
const paths = runnerPaths();
|
|
6705
9671
|
const config = resolveConfig(await readConfigFile(paths.configFile), {
|
|
6706
9672
|
maxSessions: opts.maxSessions,
|
|
9673
|
+
maxJobs: opts.maxJobs,
|
|
6707
9674
|
reposDir: opts.reposDir
|
|
6708
9675
|
});
|
|
6709
9676
|
if (!config.token) {
|
|
@@ -6766,7 +9733,7 @@ async function start(opts) {
|
|
|
6766
9733
|
signals++;
|
|
6767
9734
|
if (signals === 1) {
|
|
6768
9735
|
logger.info(
|
|
6769
|
-
`${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.`
|
|
6770
9737
|
);
|
|
6771
9738
|
daemon.stop();
|
|
6772
9739
|
} else {
|
|
@@ -6800,6 +9767,7 @@ async function status() {
|
|
|
6800
9767
|
console.log(
|
|
6801
9768
|
`Sessions: up to ${config.maxSessions} at once, permission mode ${config.permissionMode}`
|
|
6802
9769
|
);
|
|
9770
|
+
console.log(`Jobs: up to ${config.maxJobs} at once`);
|
|
6803
9771
|
console.log(`Repos: ${config.reposDir}`);
|
|
6804
9772
|
console.log(`Worktrees: ${config.worktreesDir}`);
|
|
6805
9773
|
console.log(`State: ${config.stateDir}`);
|