@discovery-tree/runner 0.1.15 → 0.1.17
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 +89 -14
- package/dist/cli.js +2904 -1182
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
// src/cli.ts
|
|
4
4
|
import { hostname } from "node:os";
|
|
5
|
-
import { createInterface as
|
|
5
|
+
import { createInterface as createInterface3 } from "node:readline/promises";
|
|
6
6
|
import { parseArgs } from "node:util";
|
|
7
7
|
|
|
8
8
|
// ../contracts/src/agent-config.ts
|
|
@@ -48,6 +48,58 @@ 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/environments.ts
|
|
93
|
+
var ENV_SETUP_SCRIPT_MAX_LENGTH = 16 * 1024;
|
|
94
|
+
|
|
95
|
+
// ../contracts/src/shared-artifacts.ts
|
|
96
|
+
var SHARED_ARTIFACT_TEXT_MAX_BYTES = 1024 * 1024;
|
|
97
|
+
var SHARED_ARTIFACT_IMAGE_MAX_BYTES = 5 * 1024 * 1024;
|
|
98
|
+
var SHARED_ARTIFACT_TREE_MAX_BYTES = 200 * 1024 * 1024;
|
|
99
|
+
|
|
100
|
+
// ../contracts/src/artifact-block.ts
|
|
101
|
+
var MAX_ARTIFACT_BLOCKS_BYTES = 1024 * 1024;
|
|
102
|
+
|
|
51
103
|
// ../contracts/src/design-review-images.ts
|
|
52
104
|
var MAX_REVIEW_IMAGES_PER_RUN = 12;
|
|
53
105
|
var MAX_REVIEW_IMAGE_CAPTION_LENGTH = 300;
|
|
@@ -65,8 +117,10 @@ var RUNNER_SESSION_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-
|
|
|
65
117
|
function isRunnerSessionId(value) {
|
|
66
118
|
return typeof value === "string" && RUNNER_SESSION_ID_RE.test(value);
|
|
67
119
|
}
|
|
120
|
+
var RUNNER_TASK_IMAGES_DIR = ".dt-task-images";
|
|
68
121
|
var RUNNER_REVIEW_IMAGE_MAX_BYTES = 5e6;
|
|
69
122
|
var RUNNER_DELIVERABLE_FILE = "DELIVERABLE.md";
|
|
123
|
+
var RUNNER_REFERENCE_REPOSITORY_DIR = "repository";
|
|
70
124
|
var RUNNER_COMPLETION_MAX_TEXT = 2e5;
|
|
71
125
|
|
|
72
126
|
// ../contracts/src/agent-permissions.ts
|
|
@@ -115,7 +169,7 @@ function toolGrantRepositoryKey(url) {
|
|
|
115
169
|
}
|
|
116
170
|
|
|
117
171
|
// src/version.ts
|
|
118
|
-
var RUNNER_VERSION = true ? "0.1.
|
|
172
|
+
var RUNNER_VERSION = true ? "0.1.17" : "0.0.0-dev";
|
|
119
173
|
var RUNNER_PLATFORM = `${process.platform}-${process.arch}`;
|
|
120
174
|
|
|
121
175
|
// src/api.ts
|
|
@@ -198,6 +252,15 @@ var RunnerApi = class {
|
|
|
198
252
|
{ timeoutMs: Math.max(this.timeoutMs, 12e4) }
|
|
199
253
|
);
|
|
200
254
|
}
|
|
255
|
+
/** An image a session's prompt names (`start_session.promptImages`), to save for its agent. */
|
|
256
|
+
getPromptImage(sessionId, attachmentId) {
|
|
257
|
+
return this.request(
|
|
258
|
+
"GET",
|
|
259
|
+
`/runner/sessions/${encodeURIComponent(sessionId)}/prompt-images/${encodeURIComponent(attachmentId)}`,
|
|
260
|
+
void 0,
|
|
261
|
+
{ timeoutMs: Math.max(this.timeoutMs, 12e4) }
|
|
262
|
+
);
|
|
263
|
+
}
|
|
201
264
|
/** Unauthenticated reachability check (`dt-runner status`). */
|
|
202
265
|
async health() {
|
|
203
266
|
try {
|
|
@@ -248,15 +311,247 @@ import { tmpdir } from "node:os";
|
|
|
248
311
|
import { isAbsolute as isAbsolute2, join as join3 } from "node:path";
|
|
249
312
|
|
|
250
313
|
// src/exec.ts
|
|
251
|
-
import { spawn as
|
|
314
|
+
import { spawn as spawn3 } from "node:child_process";
|
|
252
315
|
import { access, constants } from "node:fs/promises";
|
|
253
316
|
import { delimiter, isAbsolute, join } from "node:path";
|
|
254
317
|
|
|
255
318
|
// src/process-tree.ts
|
|
256
|
-
import { spawn, spawnSync } from "node:child_process";
|
|
319
|
+
import { spawn as spawn2, spawnSync } from "node:child_process";
|
|
320
|
+
|
|
321
|
+
// src/windows-job.ts
|
|
322
|
+
import { spawn } from "node:child_process";
|
|
323
|
+
import { createInterface } from "node:readline";
|
|
324
|
+
var HELPER_SCRIPT = String.raw`
|
|
325
|
+
$ErrorActionPreference = 'Stop'
|
|
326
|
+
Add-Type -TypeDefinition @'
|
|
327
|
+
using System;
|
|
328
|
+
using System.Collections.Generic;
|
|
329
|
+
using System.Runtime.InteropServices;
|
|
330
|
+
public static class DtRunnerJobs {
|
|
331
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
332
|
+
struct Basic { public long A; public long B; public uint LimitFlags; public UIntPtr C; public UIntPtr D; public uint E; public UIntPtr F; public uint G; public uint H; }
|
|
333
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
334
|
+
struct Io { public ulong A, B, C, D, E, F; }
|
|
335
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
336
|
+
struct Extended { public Basic Basic; public Io Io; public UIntPtr A, B, C, D; }
|
|
337
|
+
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
|
338
|
+
static extern IntPtr CreateJobObjectW(IntPtr attributes, string name);
|
|
339
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
340
|
+
static extern bool SetInformationJobObject(IntPtr job, int infoClass, ref Extended info, uint size);
|
|
341
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
342
|
+
static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);
|
|
343
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
344
|
+
static extern bool TerminateJobObject(IntPtr job, uint exitCode);
|
|
345
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
346
|
+
static extern IntPtr OpenProcess(uint access, bool inherit, uint pid);
|
|
347
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
348
|
+
static extern bool GetProcessTimes(IntPtr process, out long creation, out long exit, out long kernel, out long user);
|
|
349
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
350
|
+
static extern bool CloseHandle(IntPtr handle);
|
|
351
|
+
static readonly Dictionary<string, IntPtr> jobs = new Dictionary<string, IntPtr>();
|
|
352
|
+
static string Assign(string id, uint pid, long notAfterMs) {
|
|
353
|
+
IntPtr job = CreateJobObjectW(IntPtr.Zero, null);
|
|
354
|
+
if (job == IntPtr.Zero) return "err " + id + " CreateJobObject " + Marshal.GetLastWin32Error();
|
|
355
|
+
Extended info = new Extended();
|
|
356
|
+
info.Basic.LimitFlags = 0x2000; // JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
|
|
357
|
+
if (!SetInformationJobObject(job, 9, ref info, (uint)Marshal.SizeOf(typeof(Extended)))) {
|
|
358
|
+
int e = Marshal.GetLastWin32Error();
|
|
359
|
+
CloseHandle(job);
|
|
360
|
+
return "err " + id + " SetInformationJobObject " + e;
|
|
361
|
+
}
|
|
362
|
+
// PROCESS_SET_QUOTA | PROCESS_TERMINATE | PROCESS_QUERY_LIMITED_INFORMATION
|
|
363
|
+
IntPtr process = OpenProcess(0x1101, false, pid);
|
|
364
|
+
if (process == IntPtr.Zero) {
|
|
365
|
+
int e = Marshal.GetLastWin32Error();
|
|
366
|
+
CloseHandle(job);
|
|
367
|
+
return "err " + id + " OpenProcess " + e;
|
|
368
|
+
}
|
|
369
|
+
// A process created after the one we were told about holds a reused pid: not ours.
|
|
370
|
+
long creation, exit, kernel, user;
|
|
371
|
+
if (!GetProcessTimes(process, out creation, out exit, out kernel, out user) ||
|
|
372
|
+
(DateTime.FromFileTimeUtc(creation) - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds > notAfterMs) {
|
|
373
|
+
CloseHandle(process);
|
|
374
|
+
CloseHandle(job);
|
|
375
|
+
return "err " + id + " not the process asked for";
|
|
376
|
+
}
|
|
377
|
+
bool ok = AssignProcessToJobObject(job, process);
|
|
378
|
+
int error = Marshal.GetLastWin32Error();
|
|
379
|
+
CloseHandle(process);
|
|
380
|
+
if (!ok) {
|
|
381
|
+
CloseHandle(job);
|
|
382
|
+
return "err " + id + " AssignProcessToJobObject " + error;
|
|
383
|
+
}
|
|
384
|
+
jobs[id] = job;
|
|
385
|
+
return "ok " + id;
|
|
386
|
+
}
|
|
387
|
+
static string Kill(string id) {
|
|
388
|
+
IntPtr job;
|
|
389
|
+
if (jobs.TryGetValue(id, out job)) {
|
|
390
|
+
jobs.Remove(id);
|
|
391
|
+
TerminateJobObject(job, 1);
|
|
392
|
+
CloseHandle(job);
|
|
393
|
+
}
|
|
394
|
+
return "killed " + id;
|
|
395
|
+
}
|
|
396
|
+
public static string Run(string line) {
|
|
397
|
+
string[] parts = line.Split(' ');
|
|
398
|
+
if (parts.Length == 4 && parts[0] == "assign") return Assign(parts[1], UInt32.Parse(parts[2]), Int64.Parse(parts[3]));
|
|
399
|
+
if (parts.Length == 2 && parts[0] == "kill") return Kill(parts[1]);
|
|
400
|
+
return "err ? unknown request";
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
'@
|
|
404
|
+
[Console]::Out.WriteLine('ready')
|
|
405
|
+
[Console]::Out.Flush()
|
|
406
|
+
while ($true) {
|
|
407
|
+
$line = [Console]::In.ReadLine()
|
|
408
|
+
if ($null -eq $line) { break }
|
|
409
|
+
try { $answer = [DtRunnerJobs]::Run($line) } catch { $answer = 'err ? ' + ($_ -replace '[\r\n]', ' ') }
|
|
410
|
+
[Console]::Out.WriteLine($answer)
|
|
411
|
+
[Console]::Out.Flush()
|
|
412
|
+
}
|
|
413
|
+
`;
|
|
414
|
+
var READY_TIMEOUT_MS = 3e4;
|
|
415
|
+
var ANSWER_TIMEOUT_MS = 1e4;
|
|
416
|
+
var JobHelper = class {
|
|
417
|
+
ready;
|
|
418
|
+
child;
|
|
419
|
+
waiting = /* @__PURE__ */ new Map();
|
|
420
|
+
exited = false;
|
|
421
|
+
constructor() {
|
|
422
|
+
this.child = spawn(
|
|
423
|
+
"powershell.exe",
|
|
424
|
+
[
|
|
425
|
+
"-NoLogo",
|
|
426
|
+
"-NoProfile",
|
|
427
|
+
"-NonInteractive",
|
|
428
|
+
"-ExecutionPolicy",
|
|
429
|
+
"Bypass",
|
|
430
|
+
"-EncodedCommand",
|
|
431
|
+
Buffer.from(HELPER_SCRIPT, "utf16le").toString("base64")
|
|
432
|
+
],
|
|
433
|
+
{ stdio: ["pipe", "pipe", "ignore"], windowsHide: true }
|
|
434
|
+
);
|
|
435
|
+
let onReady = () => void 0;
|
|
436
|
+
this.ready = new Promise((resolve2) => {
|
|
437
|
+
const timer = setTimeout(() => resolve2(false), READY_TIMEOUT_MS);
|
|
438
|
+
timer.unref();
|
|
439
|
+
onReady = (ok) => {
|
|
440
|
+
clearTimeout(timer);
|
|
441
|
+
resolve2(ok);
|
|
442
|
+
};
|
|
443
|
+
});
|
|
444
|
+
const lines = createInterface({ input: this.child.stdout, crlfDelay: Infinity });
|
|
445
|
+
lines.on("line", (line) => {
|
|
446
|
+
const text = line.trim();
|
|
447
|
+
if (text === "ready") return onReady(true);
|
|
448
|
+
const id = text.split(" ")[1];
|
|
449
|
+
const answer = id ? this.waiting.get(id) : void 0;
|
|
450
|
+
if (answer) {
|
|
451
|
+
this.waiting.delete(id);
|
|
452
|
+
answer(text);
|
|
453
|
+
}
|
|
454
|
+
});
|
|
455
|
+
const gone = () => {
|
|
456
|
+
if (this.exited) return;
|
|
457
|
+
this.exited = true;
|
|
458
|
+
onReady(false);
|
|
459
|
+
for (const answer of this.waiting.values()) answer("err gone");
|
|
460
|
+
this.waiting.clear();
|
|
461
|
+
if (helper === this) helper = null;
|
|
462
|
+
};
|
|
463
|
+
this.child.on("error", gone);
|
|
464
|
+
this.child.on("exit", gone);
|
|
465
|
+
this.child.stdin.on("error", () => void 0);
|
|
466
|
+
this.child.unref();
|
|
467
|
+
this.child.stdout.unref?.();
|
|
468
|
+
this.child.stdin.unref?.();
|
|
469
|
+
}
|
|
470
|
+
get alive() {
|
|
471
|
+
return !this.exited;
|
|
472
|
+
}
|
|
473
|
+
/** Puts the process in a job of its own; resolves to the job's id, or null when it could not. */
|
|
474
|
+
async assign(target, startedBy) {
|
|
475
|
+
if (!await this.ready) return null;
|
|
476
|
+
if (!target.pid || target.exitCode !== null || target.signalCode !== null) return null;
|
|
477
|
+
const id = `j${++jobSeq}`;
|
|
478
|
+
const answer = await this.ask(`assign ${id} ${target.pid} ${Math.ceil(startedBy)}`, id);
|
|
479
|
+
return answer.startsWith("ok ") ? id : null;
|
|
480
|
+
}
|
|
481
|
+
/** Ends every process in the job, and the job. */
|
|
482
|
+
async kill(id) {
|
|
483
|
+
if (!await this.ready) return;
|
|
484
|
+
await this.ask(`kill ${id}`, id);
|
|
485
|
+
}
|
|
486
|
+
/** Ends the helper, and with it every job it holds. Synchronous: safe in an exit hook. */
|
|
487
|
+
close() {
|
|
488
|
+
if (this.exited) return;
|
|
489
|
+
try {
|
|
490
|
+
this.child.kill();
|
|
491
|
+
} catch {
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
ask(request, id) {
|
|
495
|
+
if (this.exited) return Promise.resolve("err gone");
|
|
496
|
+
return new Promise((resolve2) => {
|
|
497
|
+
const timer = setTimeout(() => {
|
|
498
|
+
this.waiting.delete(id);
|
|
499
|
+
resolve2("err timeout");
|
|
500
|
+
}, ANSWER_TIMEOUT_MS);
|
|
501
|
+
timer.unref();
|
|
502
|
+
this.waiting.set(id, (answer) => {
|
|
503
|
+
clearTimeout(timer);
|
|
504
|
+
resolve2(answer);
|
|
505
|
+
});
|
|
506
|
+
this.child.stdin.write(request + "\n");
|
|
507
|
+
});
|
|
508
|
+
}
|
|
509
|
+
};
|
|
510
|
+
var helper = null;
|
|
511
|
+
var jobSeq = 0;
|
|
512
|
+
var disabled = process.platform !== "win32";
|
|
513
|
+
function current() {
|
|
514
|
+
if (disabled) return null;
|
|
515
|
+
if (!helper || !helper.alive) helper = new JobHelper();
|
|
516
|
+
return helper;
|
|
517
|
+
}
|
|
518
|
+
async function startJobHelper() {
|
|
519
|
+
const h = current();
|
|
520
|
+
if (!h) return false;
|
|
521
|
+
const ok = await h.ready;
|
|
522
|
+
if (!ok) {
|
|
523
|
+
disabled = true;
|
|
524
|
+
h.close();
|
|
525
|
+
}
|
|
526
|
+
return ok;
|
|
527
|
+
}
|
|
528
|
+
async function assignToJob(target, startedBy) {
|
|
529
|
+
const h = current();
|
|
530
|
+
if (!h) return null;
|
|
531
|
+
try {
|
|
532
|
+
return await h.assign(target, startedBy);
|
|
533
|
+
} catch {
|
|
534
|
+
return null;
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
async function terminateJob(id) {
|
|
538
|
+
if (!id || !helper) return;
|
|
539
|
+
try {
|
|
540
|
+
await helper.kill(id);
|
|
541
|
+
} catch {
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
function closeJobHelper() {
|
|
545
|
+
helper?.close();
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
// src/process-tree.ts
|
|
257
549
|
var OWN_PROCESS_GROUP = process.platform !== "win32";
|
|
258
550
|
var liveTrees = /* @__PURE__ */ new Map();
|
|
259
551
|
var exitHookInstalled = false;
|
|
552
|
+
var CENSUS_INTERVAL_MS = 3e4;
|
|
553
|
+
var censusTimer = null;
|
|
554
|
+
var censusRunning = false;
|
|
260
555
|
function trackTree(child, cwd) {
|
|
261
556
|
if (!child.pid) return null;
|
|
262
557
|
const tree = {
|
|
@@ -264,11 +559,20 @@ function trackTree(child, cwd) {
|
|
|
264
559
|
startedAt: Date.now() - 2e3,
|
|
265
560
|
...cwd ? { cwd } : {}
|
|
266
561
|
};
|
|
267
|
-
liveTrees.set(child.pid, {
|
|
562
|
+
liveTrees.set(child.pid, { tree, child });
|
|
563
|
+
if (!OWN_PROCESS_GROUP) {
|
|
564
|
+
const startedBy = Date.now() + 1e3;
|
|
565
|
+
tree.job = assignToJob(child, startedBy);
|
|
566
|
+
startCensus();
|
|
567
|
+
}
|
|
268
568
|
if (!exitHookInstalled) {
|
|
269
569
|
exitHookInstalled = true;
|
|
270
570
|
process.once("exit", () => {
|
|
271
|
-
|
|
571
|
+
closeJobHelper();
|
|
572
|
+
for (const {
|
|
573
|
+
tree: { pid },
|
|
574
|
+
child: root
|
|
575
|
+
} of liveTrees.values()) {
|
|
272
576
|
if (OWN_PROCESS_GROUP) signalGroup(pid, "SIGKILL");
|
|
273
577
|
else if (root.exitCode === null && root.signalCode === null) {
|
|
274
578
|
spawnSync("taskkill", ["/pid", String(pid), "/T", "/F"], {
|
|
@@ -289,7 +593,7 @@ function signalTree(child, signal) {
|
|
|
289
593
|
return;
|
|
290
594
|
}
|
|
291
595
|
if (signal === "SIGKILL") {
|
|
292
|
-
const tk =
|
|
596
|
+
const tk = spawn2("taskkill", ["/pid", String(child.pid), "/T", "/F"], {
|
|
293
597
|
stdio: "ignore",
|
|
294
598
|
windowsHide: true
|
|
295
599
|
});
|
|
@@ -320,14 +624,68 @@ async function reapTree(tree, graceMs = 2e3, deps = {}) {
|
|
|
320
624
|
signalGroup(tree.pid, "SIGKILL");
|
|
321
625
|
return;
|
|
322
626
|
}
|
|
627
|
+
await (deps.terminateJob ?? terminateJob)(await tree.job);
|
|
323
628
|
const rows = await (deps.listProcesses ?? listWindowsProcesses)();
|
|
324
629
|
const orphans = descendantsOf(tree, rows);
|
|
325
630
|
if (orphans.length) await (deps.kill ?? taskkillTrees)(orphans);
|
|
326
631
|
} catch {
|
|
327
632
|
} finally {
|
|
328
|
-
if (liveTrees.get(tree.pid)?.startedAt === tree.startedAt) liveTrees.delete(tree.pid);
|
|
633
|
+
if (liveTrees.get(tree.pid)?.tree.startedAt === tree.startedAt) liveTrees.delete(tree.pid);
|
|
634
|
+
if (liveTrees.size === 0) stopCensus();
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
function recordDescendants(tree, rows) {
|
|
638
|
+
const byPid = new Map(rows.map((r) => [r.pid, r]));
|
|
639
|
+
const seen = tree.seen ?? /* @__PURE__ */ new Map();
|
|
640
|
+
for (const [pid, createdAt] of seen) {
|
|
641
|
+
if (!sameProcess(byPid.get(pid), createdAt)) seen.delete(pid);
|
|
642
|
+
}
|
|
643
|
+
for (const pid of descendantsOf(tree, rows)) {
|
|
644
|
+
const row = byPid.get(pid);
|
|
645
|
+
if (row) seen.set(pid, row.createdAt);
|
|
646
|
+
}
|
|
647
|
+
tree.seen = seen;
|
|
648
|
+
}
|
|
649
|
+
async function snapshotTree(tree, deps = {}, timeoutMs = 5e3) {
|
|
650
|
+
if (!tree || OWN_PROCESS_GROUP) return;
|
|
651
|
+
let timer;
|
|
652
|
+
try {
|
|
653
|
+
const rows = await Promise.race([
|
|
654
|
+
(deps.listProcesses ?? listWindowsProcesses)(),
|
|
655
|
+
new Promise((r) => timer = setTimeout(() => r(null), timeoutMs))
|
|
656
|
+
]);
|
|
657
|
+
if (rows) recordDescendants(tree, rows);
|
|
658
|
+
} catch {
|
|
659
|
+
} finally {
|
|
660
|
+
if (timer) clearTimeout(timer);
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
function startCensus() {
|
|
664
|
+
if (censusTimer) return;
|
|
665
|
+
censusTimer = setInterval(() => void census(), CENSUS_INTERVAL_MS);
|
|
666
|
+
censusTimer.unref();
|
|
667
|
+
}
|
|
668
|
+
function stopCensus() {
|
|
669
|
+
if (!censusTimer) return;
|
|
670
|
+
clearInterval(censusTimer);
|
|
671
|
+
censusTimer = null;
|
|
672
|
+
}
|
|
673
|
+
async function census() {
|
|
674
|
+
if (censusRunning || liveTrees.size === 0) return;
|
|
675
|
+
censusRunning = true;
|
|
676
|
+
try {
|
|
677
|
+
const rows = await listWindowsProcesses();
|
|
678
|
+
for (const { tree, child } of liveTrees.values()) {
|
|
679
|
+
if (child.exitCode === null && child.signalCode === null) recordDescendants(tree, rows);
|
|
680
|
+
}
|
|
681
|
+
} catch {
|
|
682
|
+
} finally {
|
|
683
|
+
censusRunning = false;
|
|
329
684
|
}
|
|
330
685
|
}
|
|
686
|
+
function sameProcess(row, createdAt) {
|
|
687
|
+
return !!row && Math.abs(row.createdAt - createdAt) <= 1e3;
|
|
688
|
+
}
|
|
331
689
|
function descendantsOf(tree, rows) {
|
|
332
690
|
const byParent = /* @__PURE__ */ new Map();
|
|
333
691
|
const byPid = /* @__PURE__ */ new Map();
|
|
@@ -344,9 +702,18 @@ function descendantsOf(tree, rows) {
|
|
|
344
702
|
const queue = [
|
|
345
703
|
{ pid: tree.pid, since: tree.startedAt, until: reusedAt }
|
|
346
704
|
];
|
|
705
|
+
if (tree.seen) {
|
|
706
|
+
for (const [pid, createdAt] of tree.seen) {
|
|
707
|
+
const row = byPid.get(pid);
|
|
708
|
+
if (seen.has(pid) || !sameProcess(row, createdAt)) continue;
|
|
709
|
+
seen.add(pid);
|
|
710
|
+
out.push(pid);
|
|
711
|
+
queue.push({ pid, since: row.createdAt - 1e3, until: null });
|
|
712
|
+
}
|
|
713
|
+
}
|
|
347
714
|
if (tree.cwd) {
|
|
348
715
|
for (const row of rows) {
|
|
349
|
-
if (row.pid
|
|
716
|
+
if (seen.has(row.pid) || row.createdAt < tree.startedAt) continue;
|
|
350
717
|
const parent = byPid.get(row.ppid);
|
|
351
718
|
const orphaned = !parent || parent.createdAt > row.createdAt;
|
|
352
719
|
if (orphaned && namesPathIn(row.commandLine, tree.cwd)) {
|
|
@@ -386,7 +753,7 @@ function namesPathIn(commandLine, dir) {
|
|
|
386
753
|
function listWindowsProcesses() {
|
|
387
754
|
const script = `$ErrorActionPreference='SilentlyContinue';Get-CimInstance Win32_Process | ForEach-Object { if ($_.CreationDate) { "$($_.ProcessId) $($_.ParentProcessId) $(([DateTimeOffset]$_.CreationDate).ToUnixTimeMilliseconds()) $($_.CommandLine -replace "[\\r\\n]", " ")" } }`;
|
|
388
755
|
return new Promise((resolve2, reject) => {
|
|
389
|
-
const ps =
|
|
756
|
+
const ps = spawn2(
|
|
390
757
|
"powershell.exe",
|
|
391
758
|
["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script],
|
|
392
759
|
{ stdio: ["ignore", "pipe", "ignore"], windowsHide: true }
|
|
@@ -423,7 +790,7 @@ async function taskkillTrees(pids) {
|
|
|
423
790
|
for (let i = 0; i < pids.length; i += 50) {
|
|
424
791
|
const args = pids.slice(i, i + 50).flatMap((p) => ["/pid", String(p)]);
|
|
425
792
|
await new Promise((resolve2) => {
|
|
426
|
-
const tk =
|
|
793
|
+
const tk = spawn2("taskkill", [...args, "/T", "/F"], { stdio: "ignore", windowsHide: true });
|
|
427
794
|
tk.on("error", () => resolve2());
|
|
428
795
|
tk.on("close", () => resolve2());
|
|
429
796
|
});
|
|
@@ -441,7 +808,7 @@ function signalGroup(pgid, signal) {
|
|
|
441
808
|
// src/exec.ts
|
|
442
809
|
function exec(cmd, args, opts = {}) {
|
|
443
810
|
return new Promise((resolve2, reject) => {
|
|
444
|
-
const child =
|
|
811
|
+
const child = spawn3(cmd, args, {
|
|
445
812
|
cwd: opts.cwd,
|
|
446
813
|
env: opts.env ?? process.env,
|
|
447
814
|
stdio: ["pipe", "pipe", "pipe"],
|
|
@@ -621,6 +988,55 @@ function isLocked(err) {
|
|
|
621
988
|
function removeDir(path) {
|
|
622
989
|
return rm(path, { recursive: true, force: true, maxRetries: 8, retryDelay: 250 });
|
|
623
990
|
}
|
|
991
|
+
async function ensureRepoCache(repoDir, ref, protocol) {
|
|
992
|
+
if (!await exists(join2(repoDir, ".git"))) {
|
|
993
|
+
await mkdir(dirname(repoDir), { recursive: true });
|
|
994
|
+
await rm(repoDir, { recursive: true, force: true });
|
|
995
|
+
await git(dirname(repoDir), ["clone", "--no-checkout", cloneUrl(ref, protocol), repoDir]);
|
|
996
|
+
return;
|
|
997
|
+
}
|
|
998
|
+
const wanted = cloneUrl(ref, protocol);
|
|
999
|
+
const current2 = await exec("git", ["config", "--get", "remote.origin.url"], {
|
|
1000
|
+
cwd: repoDir,
|
|
1001
|
+
env: gitEnv()
|
|
1002
|
+
});
|
|
1003
|
+
if (current2.stdout.trim() !== wanted) {
|
|
1004
|
+
await git(repoDir, ["remote", "set-url", "origin", wanted]);
|
|
1005
|
+
}
|
|
1006
|
+
await git(repoDir, ["fetch", "--prune", "origin"]);
|
|
1007
|
+
}
|
|
1008
|
+
async function resolveBase(repoDir, wanted) {
|
|
1009
|
+
const baseRef = wanted ?? await defaultBranch(repoDir);
|
|
1010
|
+
let start2 = `origin/${baseRef}`;
|
|
1011
|
+
if (!await gitOk(repoDir, ["rev-parse", "--verify", "--quiet", `${start2}^{commit}`])) {
|
|
1012
|
+
if (!await gitOk(repoDir, ["rev-parse", "--verify", "--quiet", `${baseRef}^{commit}`])) {
|
|
1013
|
+
throw new Error(`Base branch ${baseRef} was not found on origin.`);
|
|
1014
|
+
}
|
|
1015
|
+
start2 = baseRef;
|
|
1016
|
+
}
|
|
1017
|
+
return { baseRef, start: start2 };
|
|
1018
|
+
}
|
|
1019
|
+
async function prepareReferenceCheckout(input) {
|
|
1020
|
+
const ref = parseRepoUrl(input.url);
|
|
1021
|
+
if (!ref) throw new Error(repositoryUrlError(input.url));
|
|
1022
|
+
if (input.baseRef) assertSafeRef(input.baseRef, "Base branch");
|
|
1023
|
+
const repoDir = join2(input.reposDir, ref.owner, ref.repo);
|
|
1024
|
+
return withRepoLock(repoDir, async () => {
|
|
1025
|
+
await ensureRepoCache(repoDir, ref, input.protocol);
|
|
1026
|
+
const { baseRef, start: start2 } = await resolveBase(repoDir, input.baseRef);
|
|
1027
|
+
const sha = await git(repoDir, ["rev-parse", `${start2}^{commit}`]);
|
|
1028
|
+
await exec("git", ["worktree", "remove", "--force", input.dir], {
|
|
1029
|
+
cwd: repoDir,
|
|
1030
|
+
env: gitEnv(),
|
|
1031
|
+
timeoutMs: 6e4
|
|
1032
|
+
});
|
|
1033
|
+
await removeDir(input.dir);
|
|
1034
|
+
await git(repoDir, ["worktree", "prune"]);
|
|
1035
|
+
await mkdir(dirname(input.dir), { recursive: true });
|
|
1036
|
+
await git(repoDir, ["worktree", "add", "--detach", input.dir, sha]);
|
|
1037
|
+
return { repoDir, dir: input.dir, baseRef, sha };
|
|
1038
|
+
});
|
|
1039
|
+
}
|
|
624
1040
|
async function prepareWorktree(input) {
|
|
625
1041
|
const ref = parseRepoUrl(input.url);
|
|
626
1042
|
if (!ref) throw new Error(repositoryUrlError(input.url));
|
|
@@ -631,34 +1047,8 @@ async function prepareWorktree(input) {
|
|
|
631
1047
|
let worktree = join2(input.worktreesDir, input.worktreeKey || input.sessionId);
|
|
632
1048
|
const remove = input.removeDir ?? removeDir;
|
|
633
1049
|
return withRepoLock(repoDir, async () => {
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
await rm(repoDir, { recursive: true, force: true });
|
|
637
|
-
await git(dirname(repoDir), [
|
|
638
|
-
"clone",
|
|
639
|
-
"--no-checkout",
|
|
640
|
-
cloneUrl(ref, input.protocol),
|
|
641
|
-
repoDir
|
|
642
|
-
]);
|
|
643
|
-
} else {
|
|
644
|
-
const wanted = cloneUrl(ref, input.protocol);
|
|
645
|
-
const current = await exec("git", ["config", "--get", "remote.origin.url"], {
|
|
646
|
-
cwd: repoDir,
|
|
647
|
-
env: gitEnv()
|
|
648
|
-
});
|
|
649
|
-
if (current.stdout.trim() !== wanted) {
|
|
650
|
-
await git(repoDir, ["remote", "set-url", "origin", wanted]);
|
|
651
|
-
}
|
|
652
|
-
await git(repoDir, ["fetch", "--prune", "origin"]);
|
|
653
|
-
}
|
|
654
|
-
const baseRef = input.baseRef ?? await defaultBranch(repoDir);
|
|
655
|
-
let start2 = `origin/${baseRef}`;
|
|
656
|
-
if (!await gitOk(repoDir, ["rev-parse", "--verify", "--quiet", `${start2}^{commit}`])) {
|
|
657
|
-
if (!await gitOk(repoDir, ["rev-parse", "--verify", "--quiet", `${baseRef}^{commit}`])) {
|
|
658
|
-
throw new Error(`Base branch ${baseRef} was not found on origin.`);
|
|
659
|
-
}
|
|
660
|
-
start2 = baseRef;
|
|
661
|
-
}
|
|
1050
|
+
await ensureRepoCache(repoDir, ref, input.protocol);
|
|
1051
|
+
const { baseRef, start: start2 } = await resolveBase(repoDir, input.baseRef);
|
|
662
1052
|
let baseSha = await git(repoDir, ["rev-parse", `${start2}^{commit}`]);
|
|
663
1053
|
let checkout = start2;
|
|
664
1054
|
let continuedFrom;
|
|
@@ -865,23 +1255,27 @@ function evidenceBranch(workBranch) {
|
|
|
865
1255
|
}
|
|
866
1256
|
async function ensureEvidenceDir(worktree) {
|
|
867
1257
|
await mkdir2(join3(worktree, EVIDENCE_DIR), { recursive: true });
|
|
1258
|
+
await excludeFromGit(
|
|
1259
|
+
worktree,
|
|
1260
|
+
EVIDENCE_DIR,
|
|
1261
|
+
"Screenshots dt-runner publishes on their own branch"
|
|
1262
|
+
);
|
|
1263
|
+
}
|
|
1264
|
+
async function excludeFromGit(worktree, dir, why) {
|
|
868
1265
|
const rel = await git(worktree, ["rev-parse", "--git-path", "info/exclude"]);
|
|
869
1266
|
const file = isAbsolute2(rel) ? rel : join3(worktree, rel);
|
|
870
|
-
const line = `/${
|
|
871
|
-
let
|
|
1267
|
+
const line = `/${dir}/`;
|
|
1268
|
+
let current2 = "";
|
|
872
1269
|
try {
|
|
873
|
-
|
|
1270
|
+
current2 = await readFile(file, "utf8");
|
|
874
1271
|
} catch {
|
|
875
1272
|
}
|
|
876
|
-
if (
|
|
1273
|
+
if (current2.split("\n").some((l) => l.trim() === line)) return;
|
|
877
1274
|
await mkdir2(join3(file, ".."), { recursive: true });
|
|
878
|
-
const sep2 =
|
|
879
|
-
await writeFile(
|
|
880
|
-
file,
|
|
881
|
-
`${current}${sep2}# Screenshots dt-runner publishes on their own branch
|
|
1275
|
+
const sep2 = current2 && !current2.endsWith("\n") ? "\n" : "";
|
|
1276
|
+
await writeFile(file, `${current2}${sep2}# ${why}
|
|
882
1277
|
${line}
|
|
883
|
-
`
|
|
884
|
-
);
|
|
1278
|
+
`);
|
|
885
1279
|
}
|
|
886
1280
|
async function publishEvidence(input) {
|
|
887
1281
|
const dir = join3(input.worktree, EVIDENCE_DIR);
|
|
@@ -1219,6 +1613,15 @@ function runnerSystemPrompt(input) {
|
|
|
1219
1613
|
"You are running a Discovery Tree task through the person\u2019s local Discovery Tree runner.",
|
|
1220
1614
|
"Your working directory is a scratch directory created for this task; it is not a git repository."
|
|
1221
1615
|
];
|
|
1616
|
+
if (input.reference) {
|
|
1617
|
+
scratch.push(
|
|
1618
|
+
`The repository this task concerns, ${input.reference.url}, is checked out at`,
|
|
1619
|
+
`\`${input.reference.dir}\` (\`${input.reference.baseRef}\` as it is now), for you to read.`,
|
|
1620
|
+
"Read it before you propose anything, so your work matches the product as it is: its",
|
|
1621
|
+
"screens, components, styles, words and data. It is for reading only: do not change it,",
|
|
1622
|
+
"commit or push. Nothing in it is kept, and this task\u2019s output is your response."
|
|
1623
|
+
);
|
|
1624
|
+
}
|
|
1222
1625
|
if (input.reviewImages) {
|
|
1223
1626
|
const folder = join4(input.cwd, EVIDENCE_DIR);
|
|
1224
1627
|
scratch.push(
|
|
@@ -1267,174 +1670,1716 @@ function runnerSystemPrompt(input) {
|
|
|
1267
1670
|
].join(" ");
|
|
1268
1671
|
}
|
|
1269
1672
|
|
|
1270
|
-
// src/
|
|
1271
|
-
import {
|
|
1673
|
+
// src/claude-code-rules.ts
|
|
1674
|
+
import { readFile as readFile2, stat as stat3 } from "node:fs/promises";
|
|
1272
1675
|
import { homedir } from "node:os";
|
|
1273
|
-
import { dirname as dirname2, join as join5 } from "node:path";
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
var
|
|
1277
|
-
function launchedByNpx(env = process.env, argv1 = process.argv[1]) {
|
|
1278
|
-
if (env.npm_command === "exec") return true;
|
|
1279
|
-
return /[\\/](_npx|dlx)[\\/]/.test(argv1 ?? "");
|
|
1280
|
-
}
|
|
1281
|
-
function runnerCommand(subcommand, viaNpx = launchedByNpx()) {
|
|
1282
|
-
return viaNpx ? `npx ${RUNNER_PACKAGE}@latest ${subcommand}` : `dt-runner ${subcommand}`;
|
|
1283
|
-
}
|
|
1284
|
-
|
|
1285
|
-
// src/config.ts
|
|
1286
|
-
function runnerPaths(env = process.env) {
|
|
1287
|
-
const home = homedir();
|
|
1288
|
-
if (process.platform === "win32") {
|
|
1289
|
-
const roaming = env.APPDATA || join5(home, "AppData", "Roaming");
|
|
1290
|
-
const local = env.LOCALAPPDATA || join5(home, "AppData", "Local");
|
|
1291
|
-
return {
|
|
1292
|
-
configFile: join5(roaming, "discovery-tree", "runner.json"),
|
|
1293
|
-
dataDir: join5(local, "discovery-tree", "runner"),
|
|
1294
|
-
stateDir: join5(local, "discovery-tree", "runner", "state")
|
|
1295
|
-
};
|
|
1296
|
-
}
|
|
1297
|
-
const config = env.XDG_CONFIG_HOME || join5(home, ".config");
|
|
1298
|
-
const data = env.XDG_DATA_HOME || join5(home, ".local", "share");
|
|
1299
|
-
const state = env.XDG_STATE_HOME || join5(home, ".local", "state");
|
|
1300
|
-
return {
|
|
1301
|
-
configFile: join5(config, "discovery-tree", "runner.json"),
|
|
1302
|
-
dataDir: join5(data, "discovery-tree", "runner"),
|
|
1303
|
-
stateDir: join5(state, "discovery-tree", "runner")
|
|
1304
|
-
};
|
|
1305
|
-
}
|
|
1306
|
-
var PERMISSION_MODES = [
|
|
1307
|
-
"acceptEdits",
|
|
1308
|
-
"auto",
|
|
1309
|
-
"default",
|
|
1310
|
-
"manual",
|
|
1311
|
-
"dontAsk",
|
|
1312
|
-
"plan",
|
|
1313
|
-
"bypassPermissions"
|
|
1314
|
-
];
|
|
1315
|
-
var DEFAULT_ALLOWED_TOOLS = [
|
|
1676
|
+
import { dirname as dirname2, isAbsolute as isAbsolute3, join as join5, resolve, sep } from "node:path";
|
|
1677
|
+
var EMPTY = { allow: [], deny: [], ask: [], sources: [] };
|
|
1678
|
+
var RULE_SHAPE2 = /^(?:mcp__[A-Za-z0-9_-]+__\*|[A-Za-z][A-Za-z0-9_.-]*(?:\([\s\S]*\))?)$/;
|
|
1679
|
+
var FILE_TOOLS = /* @__PURE__ */ new Set([
|
|
1316
1680
|
"Read",
|
|
1317
1681
|
"Edit",
|
|
1318
|
-
"MultiEdit",
|
|
1319
1682
|
"Write",
|
|
1683
|
+
"MultiEdit",
|
|
1684
|
+
"NotebookEdit",
|
|
1320
1685
|
"Glob",
|
|
1321
1686
|
"Grep",
|
|
1322
|
-
"LS"
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
"
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
"
|
|
1331
|
-
"
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1687
|
+
"LS"
|
|
1688
|
+
]);
|
|
1689
|
+
function usableRule(raw, kind, committed) {
|
|
1690
|
+
if (typeof raw !== "string") return null;
|
|
1691
|
+
const rule = raw.trim();
|
|
1692
|
+
if (!rule || rule.length > TOOL_GRANT_RULE_MAX_LENGTH) return null;
|
|
1693
|
+
if (/[\u0000-\u001f\u007f]/.test(rule) || !RULE_SHAPE2.test(rule)) return null;
|
|
1694
|
+
const tool = /^([A-Za-z][A-Za-z0-9_.-]*)/.exec(rule)?.[1] ?? "";
|
|
1695
|
+
if (kind === "allow" && FILE_TOOLS.has(tool)) return null;
|
|
1696
|
+
if (kind === "allow" && committed && toolGrantRuleProblem(rule) !== null) return null;
|
|
1697
|
+
return rule;
|
|
1698
|
+
}
|
|
1699
|
+
function remoteRepositoryKey(url) {
|
|
1700
|
+
const u = url.trim();
|
|
1701
|
+
const ssh = /^(?:ssh:\/\/)?git@github\.com[:/]([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/i.exec(u);
|
|
1702
|
+
if (ssh) return toolGrantRepositoryKey(`https://github.com/${ssh[1]}/${ssh[2]}`);
|
|
1703
|
+
const https = /^(?:https?|git):\/\/(?:[^@/]+@)?github\.com\/([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/i.exec(u);
|
|
1704
|
+
if (https) return toolGrantRepositoryKey(`https://github.com/${https[1]}/${https[2]}`);
|
|
1705
|
+
return null;
|
|
1706
|
+
}
|
|
1707
|
+
async function readText(file) {
|
|
1708
|
+
try {
|
|
1709
|
+
return await readFile2(file, "utf8");
|
|
1710
|
+
} catch {
|
|
1711
|
+
return null;
|
|
1712
|
+
}
|
|
1713
|
+
}
|
|
1714
|
+
async function readJsonFile(file) {
|
|
1715
|
+
const text = await readText(file);
|
|
1716
|
+
if (text === null) return null;
|
|
1717
|
+
try {
|
|
1718
|
+
return JSON.parse(text);
|
|
1719
|
+
} catch {
|
|
1720
|
+
return null;
|
|
1721
|
+
}
|
|
1722
|
+
}
|
|
1723
|
+
async function isDir(path) {
|
|
1724
|
+
try {
|
|
1725
|
+
return (await stat3(path)).isDirectory();
|
|
1726
|
+
} catch {
|
|
1727
|
+
return false;
|
|
1728
|
+
}
|
|
1729
|
+
}
|
|
1730
|
+
async function gitConfigOf(folder) {
|
|
1731
|
+
let dir = folder;
|
|
1732
|
+
for (let i = 0; i < 6; i++) {
|
|
1733
|
+
const dotGit = join5(dir, ".git");
|
|
1734
|
+
if (await isDir(dotGit)) return { config: join5(dotGit, "config"), roots: [dir] };
|
|
1735
|
+
const pointer = await readText(dotGit);
|
|
1736
|
+
const gitdir = pointer && /^gitdir:\s*(.+)\s*$/m.exec(pointer)?.[1];
|
|
1737
|
+
if (gitdir) {
|
|
1738
|
+
const linked = resolve(dir, gitdir);
|
|
1739
|
+
const common = (await readText(join5(linked, "commondir")))?.trim();
|
|
1740
|
+
const commonDir = common ? resolve(linked, common) : linked;
|
|
1741
|
+
return { config: join5(commonDir, "config"), roots: [dir, dirname2(commonDir)] };
|
|
1742
|
+
}
|
|
1743
|
+
const up = dirname2(dir);
|
|
1744
|
+
if (up === dir) break;
|
|
1745
|
+
dir = up;
|
|
1746
|
+
}
|
|
1747
|
+
return null;
|
|
1748
|
+
}
|
|
1749
|
+
function remoteKeys(config) {
|
|
1750
|
+
const keys = /* @__PURE__ */ new Set();
|
|
1751
|
+
let inRemote = false;
|
|
1752
|
+
for (const line of config.split(/\r?\n/)) {
|
|
1753
|
+
const section = /^\s*\[([^\]]*)\]/.exec(line);
|
|
1754
|
+
if (section) {
|
|
1755
|
+
inRemote = /^remote\s+"/i.test(section[1].trim());
|
|
1756
|
+
continue;
|
|
1757
|
+
}
|
|
1758
|
+
if (!inRemote) continue;
|
|
1759
|
+
const url = /^\s*url\s*=\s*(.+?)\s*$/i.exec(line);
|
|
1760
|
+
const key = url ? remoteRepositoryKey(url[1]) : null;
|
|
1761
|
+
if (key) keys.add(key);
|
|
1762
|
+
}
|
|
1763
|
+
return keys;
|
|
1764
|
+
}
|
|
1765
|
+
function rulesIn(settings, kind, committed) {
|
|
1766
|
+
const perms = settings?.permissions;
|
|
1767
|
+
const list = perms?.[kind];
|
|
1768
|
+
if (!Array.isArray(list)) return [];
|
|
1769
|
+
return list.map((r) => usableRule(r, kind, committed)).filter((r) => r !== null);
|
|
1770
|
+
}
|
|
1771
|
+
var ClaudeCodeRules = class {
|
|
1772
|
+
claudeJson;
|
|
1773
|
+
exclude;
|
|
1774
|
+
cacheMs;
|
|
1775
|
+
cache = /* @__PURE__ */ new Map();
|
|
1776
|
+
constructor(opts = {}) {
|
|
1777
|
+
this.claudeJson = opts.claudeJson ?? (process.env.CLAUDE_CONFIG_DIR ? join5(process.env.CLAUDE_CONFIG_DIR, ".claude.json") : join5(homedir(), ".claude.json"));
|
|
1778
|
+
this.exclude = (opts.exclude ?? []).map((p) => resolve(p));
|
|
1779
|
+
this.cacheMs = opts.cacheMs ?? 3e4;
|
|
1780
|
+
}
|
|
1781
|
+
/** The rules for a repository URL; none for a session without a GitHub repository. */
|
|
1782
|
+
rulesFor(repositoryUrl) {
|
|
1783
|
+
const key = toolGrantRepositoryKey(repositoryUrl);
|
|
1784
|
+
if (!key) return Promise.resolve(EMPTY);
|
|
1785
|
+
const hit = this.cache.get(key);
|
|
1786
|
+
if (hit && Date.now() - hit.at < this.cacheMs) return hit.rules;
|
|
1787
|
+
const rules = this.read(key).catch(() => EMPTY);
|
|
1788
|
+
this.cache.set(key, { at: Date.now(), rules });
|
|
1789
|
+
return rules;
|
|
1790
|
+
}
|
|
1791
|
+
excluded(folder) {
|
|
1792
|
+
const f = resolve(folder);
|
|
1793
|
+
return this.exclude.some((ex) => f === ex || f.startsWith(ex + sep));
|
|
1794
|
+
}
|
|
1795
|
+
async read(key) {
|
|
1796
|
+
const global = await readJsonFile(this.claudeJson);
|
|
1797
|
+
const projects = global?.projects;
|
|
1798
|
+
if (!projects || typeof projects !== "object") return EMPTY;
|
|
1799
|
+
const allow = /* @__PURE__ */ new Set();
|
|
1800
|
+
const deny = /* @__PURE__ */ new Set();
|
|
1801
|
+
const ask = /* @__PURE__ */ new Set();
|
|
1802
|
+
const sources = [];
|
|
1803
|
+
const checkouts = [];
|
|
1804
|
+
for (const [folder, entry] of Object.entries(projects)) {
|
|
1805
|
+
if (!entry || entry.hasTrustDialogAccepted !== true) continue;
|
|
1806
|
+
if (!isAbsolute3(folder) || this.excluded(folder)) continue;
|
|
1807
|
+
const git2 = await gitConfigOf(folder);
|
|
1808
|
+
const text = git2 ? await readText(git2.config) : null;
|
|
1809
|
+
if (!git2 || !text || !remoteKeys(text).has(key)) continue;
|
|
1810
|
+
const roots = [...new Set([folder, ...git2.roots].map((d) => resolve(d)))];
|
|
1811
|
+
const legacy = Array.isArray(entry.allowedTools) ? entry.allowedTools : [];
|
|
1812
|
+
checkouts.push({ folder, roots, legacy });
|
|
1813
|
+
}
|
|
1814
|
+
for (const { folder, roots, legacy } of checkouts) {
|
|
1815
|
+
const found = [];
|
|
1816
|
+
const denied = [];
|
|
1817
|
+
const asked = [];
|
|
1818
|
+
for (const dir of roots) {
|
|
1819
|
+
const local = await readJsonFile(join5(dir, ".claude", "settings.local.json"));
|
|
1820
|
+
const shared = await readJsonFile(join5(dir, ".claude", "settings.json"));
|
|
1821
|
+
found.push(...rulesIn(local, "allow", false), ...rulesIn(shared, "allow", true));
|
|
1822
|
+
denied.push(...rulesIn(local, "deny", false), ...rulesIn(shared, "deny", false));
|
|
1823
|
+
asked.push(...rulesIn(local, "ask", false), ...rulesIn(shared, "ask", false));
|
|
1824
|
+
}
|
|
1825
|
+
found.push(
|
|
1826
|
+
...legacy.map((r) => usableRule(r, "allow", false)).filter((r) => r !== null)
|
|
1827
|
+
);
|
|
1828
|
+
const kept = found;
|
|
1829
|
+
if (kept.length || denied.length || asked.length) sources.push(folder);
|
|
1830
|
+
for (const r of kept) allow.add(r);
|
|
1831
|
+
for (const r of denied) deny.add(r);
|
|
1832
|
+
for (const r of asked) ask.add(r);
|
|
1833
|
+
}
|
|
1834
|
+
return {
|
|
1835
|
+
allow: [...allow].filter((r) => !deny.has(r) && !ask.has(r)),
|
|
1836
|
+
deny: [...deny],
|
|
1837
|
+
ask: [...ask].filter((r) => !deny.has(r)),
|
|
1838
|
+
sources
|
|
1839
|
+
};
|
|
1840
|
+
}
|
|
1841
|
+
};
|
|
1842
|
+
function ruleHead(rule) {
|
|
1843
|
+
const m = /^([A-Za-z][A-Za-z0-9_.-]*(?:__\*)?)(?:\(([\s\S]*)\))?$/.exec(rule.trim());
|
|
1844
|
+
if (!m) return null;
|
|
1845
|
+
const spec = m[2];
|
|
1846
|
+
if (spec === void 0) return { tool: m[1], head: null };
|
|
1847
|
+
return { tool: m[1], head: spec.replace(/:\*$/, " *").split("*")[0] };
|
|
1848
|
+
}
|
|
1849
|
+
function sameTool(a, b) {
|
|
1850
|
+
if (a === b) return true;
|
|
1851
|
+
const wild = (w, t) => w.endsWith("__*") && t.startsWith(w.slice(0, -1));
|
|
1852
|
+
return wild(a, b) || wild(b, a);
|
|
1853
|
+
}
|
|
1854
|
+
function overlapsAsk(allowRule, askRules) {
|
|
1855
|
+
const a = ruleHead(allowRule);
|
|
1856
|
+
if (!a) return false;
|
|
1857
|
+
return askRules.some((rule) => {
|
|
1858
|
+
const q = ruleHead(rule);
|
|
1859
|
+
if (!q || !sameTool(a.tool, q.tool)) return false;
|
|
1860
|
+
if (a.head === null || q.head === null) return true;
|
|
1861
|
+
return a.head.startsWith(q.head) || q.head.startsWith(a.head);
|
|
1862
|
+
});
|
|
1863
|
+
}
|
|
1864
|
+
|
|
1865
|
+
// src/permissions.ts
|
|
1866
|
+
import { randomUUID } from "node:crypto";
|
|
1867
|
+
function parseCanUseTool(line) {
|
|
1868
|
+
if (line?.type !== "control_request") return null;
|
|
1869
|
+
const req = line.request;
|
|
1870
|
+
if (!req || req.subtype !== "can_use_tool") return null;
|
|
1871
|
+
if (typeof line.request_id !== "string" || !line.request_id) return null;
|
|
1872
|
+
const toolName = typeof req.tool_name === "string" && req.tool_name ? req.tool_name : "tool";
|
|
1873
|
+
return { controlRequestId: line.request_id, toolName, input: req.input ?? {} };
|
|
1874
|
+
}
|
|
1875
|
+
function parseControlCancel(line) {
|
|
1876
|
+
if (line?.type !== "control_cancel_request") return null;
|
|
1877
|
+
return typeof line.request_id === "string" ? line.request_id : null;
|
|
1878
|
+
}
|
|
1879
|
+
function summarizeToolInput(toolName, input) {
|
|
1880
|
+
const i = input && typeof input === "object" ? input : {};
|
|
1881
|
+
const s = (v) => typeof v === "string" && v.trim() ? v : null;
|
|
1882
|
+
let summary = null;
|
|
1883
|
+
switch (toolName) {
|
|
1884
|
+
case "Bash":
|
|
1885
|
+
summary = s(i.command);
|
|
1886
|
+
break;
|
|
1887
|
+
case "WebFetch":
|
|
1888
|
+
summary = s(i.url);
|
|
1889
|
+
break;
|
|
1890
|
+
case "WebSearch":
|
|
1891
|
+
summary = s(i.query);
|
|
1892
|
+
break;
|
|
1893
|
+
case "Read":
|
|
1894
|
+
case "Edit":
|
|
1895
|
+
case "MultiEdit":
|
|
1896
|
+
case "Write":
|
|
1897
|
+
summary = s(i.file_path);
|
|
1898
|
+
break;
|
|
1899
|
+
case "NotebookEdit":
|
|
1900
|
+
summary = s(i.notebook_path);
|
|
1901
|
+
break;
|
|
1902
|
+
case "Glob":
|
|
1903
|
+
case "Grep":
|
|
1904
|
+
summary = s(i.pattern) ? `${i.pattern}${s(i.path) ? ` in ${i.path}` : ""}` : null;
|
|
1905
|
+
break;
|
|
1906
|
+
}
|
|
1907
|
+
if (summary === null) {
|
|
1908
|
+
try {
|
|
1909
|
+
summary = JSON.stringify(input) ?? "";
|
|
1910
|
+
} catch {
|
|
1911
|
+
summary = "";
|
|
1912
|
+
}
|
|
1913
|
+
}
|
|
1914
|
+
return cut(summary, AGENT_PERMISSION_INPUT_SUMMARY_MAX_LENGTH);
|
|
1915
|
+
}
|
|
1916
|
+
function cut(text, max) {
|
|
1917
|
+
return text.length > max ? `${text.slice(0, max - 1)}\u2026` : text;
|
|
1918
|
+
}
|
|
1919
|
+
var PERMISSION_EXPIRED_TURN_ENDED = "The turn ended before anyone answered.";
|
|
1920
|
+
var PERMISSION_EXPIRED_INTERRUPTED = "The turn was interrupted before anyone answered.";
|
|
1921
|
+
var PERMISSION_EXPIRED_STOPPED = "Claude Code stopped before anyone answered.";
|
|
1922
|
+
var PERMISSION_EXPIRED_TIMEOUT = `Nobody answered within ${Math.round(
|
|
1923
|
+
RUNNER_PERMISSION_REQUEST_TIMEOUT_MS / 6e4
|
|
1924
|
+
)} minutes.`;
|
|
1925
|
+
var PERMISSION_EXPIRED_CANCELLED = "Claude Code stopped waiting for an answer.";
|
|
1926
|
+
var PERMISSION_EXPIRED_UNKNOWN = "The runner no longer has this request (it may have restarted), so the answer could not be applied.";
|
|
1927
|
+
var DENIED_MESSAGE = "The person denied permission for this tool call in Discovery Tree.";
|
|
1928
|
+
var SETTLED_KEPT = 200;
|
|
1929
|
+
var PermissionRelay = class {
|
|
1930
|
+
constructor(deps) {
|
|
1931
|
+
this.deps = deps;
|
|
1932
|
+
}
|
|
1933
|
+
pending = /* @__PURE__ */ new Map();
|
|
1934
|
+
byControlId = /* @__PURE__ */ new Map();
|
|
1935
|
+
settled = /* @__PURE__ */ new Map();
|
|
1936
|
+
get pendingCount() {
|
|
1937
|
+
return this.pending.size;
|
|
1938
|
+
}
|
|
1939
|
+
/** Claude Code asks; returns whether it was allowed at once or relayed. */
|
|
1940
|
+
request(req) {
|
|
1941
|
+
if (this.deps.alwaysAllowed().includes(req.toolName) || this.deps.grantedByRule?.(req.toolName, req.input)) {
|
|
1942
|
+
this.deps.respond(req.controlRequestId, { behavior: "allow", updatedInput: req.input });
|
|
1943
|
+
return "auto_allowed";
|
|
1944
|
+
}
|
|
1945
|
+
const id = (this.deps.newId ?? randomUUID)();
|
|
1946
|
+
const requestedAt = (this.deps.now?.() ?? /* @__PURE__ */ new Date()).toISOString();
|
|
1947
|
+
const timer = setTimeout(
|
|
1948
|
+
() => this.expire(id, PERMISSION_EXPIRED_TIMEOUT, true),
|
|
1949
|
+
this.deps.timeoutMs ?? RUNNER_PERMISSION_REQUEST_TIMEOUT_MS
|
|
1950
|
+
);
|
|
1951
|
+
timer.unref?.();
|
|
1952
|
+
const pending = {
|
|
1953
|
+
id,
|
|
1954
|
+
controlRequestId: req.controlRequestId,
|
|
1955
|
+
toolName: req.toolName,
|
|
1956
|
+
input: req.input,
|
|
1957
|
+
inputSummary: summarizeToolInput(req.toolName, req.input),
|
|
1958
|
+
requestedAt,
|
|
1959
|
+
timer
|
|
1960
|
+
};
|
|
1961
|
+
this.pending.set(id, pending);
|
|
1962
|
+
this.byControlId.set(req.controlRequestId, id);
|
|
1963
|
+
const suggestedRule = this.deps.suggestRule?.(req.toolName, req.input) ?? null;
|
|
1964
|
+
this.deps.emit({
|
|
1965
|
+
type: "permission_request",
|
|
1966
|
+
request: {
|
|
1967
|
+
id,
|
|
1968
|
+
toolName: pending.toolName,
|
|
1969
|
+
inputSummary: pending.inputSummary,
|
|
1970
|
+
...suggestedRule ? { suggestedRule } : {},
|
|
1971
|
+
requestedAt,
|
|
1972
|
+
status: "pending"
|
|
1973
|
+
}
|
|
1974
|
+
});
|
|
1975
|
+
return "relayed";
|
|
1976
|
+
}
|
|
1977
|
+
/** A person's decision, from the server. */
|
|
1978
|
+
decide(requestId, decision) {
|
|
1979
|
+
const pending = this.pending.get(requestId);
|
|
1980
|
+
if (!pending) {
|
|
1981
|
+
const settled = this.settled.get(requestId);
|
|
1982
|
+
if (settled === "decided") return "already_applied";
|
|
1983
|
+
if (settled === void 0) {
|
|
1984
|
+
this.settle(requestId, "expired");
|
|
1985
|
+
this.deps.emit({
|
|
1986
|
+
type: "permission_request",
|
|
1987
|
+
request: {
|
|
1988
|
+
id: requestId,
|
|
1989
|
+
toolName: "tool",
|
|
1990
|
+
inputSummary: "",
|
|
1991
|
+
requestedAt: (this.deps.now?.() ?? /* @__PURE__ */ new Date()).toISOString(),
|
|
1992
|
+
status: "expired",
|
|
1993
|
+
expiredReason: PERMISSION_EXPIRED_UNKNOWN
|
|
1994
|
+
}
|
|
1995
|
+
});
|
|
1996
|
+
}
|
|
1997
|
+
return "not_pending";
|
|
1998
|
+
}
|
|
1999
|
+
this.forget(pending);
|
|
2000
|
+
this.settle(requestId, "decided");
|
|
2001
|
+
if (decision.behavior === "allow") {
|
|
2002
|
+
if (decision.alwaysAllowTool && !this.deps.alwaysAllowed().includes(pending.toolName)) {
|
|
2003
|
+
this.deps.rememberAlwaysAllowed(pending.toolName);
|
|
2004
|
+
}
|
|
2005
|
+
const rule = decision.alwaysAllowRule?.trim();
|
|
2006
|
+
if (rule && toolGrantRuleProblem(rule) === null) this.deps.rememberRule?.(rule);
|
|
2007
|
+
this.deps.respond(pending.controlRequestId, {
|
|
2008
|
+
behavior: "allow",
|
|
2009
|
+
updatedInput: pending.input
|
|
2010
|
+
});
|
|
2011
|
+
} else {
|
|
2012
|
+
const message = decision.message?.trim();
|
|
2013
|
+
this.deps.respond(pending.controlRequestId, {
|
|
2014
|
+
behavior: "deny",
|
|
2015
|
+
message: message ? `${DENIED_MESSAGE} Their message: ${cut(message, AGENT_PERMISSION_MESSAGE_MAX_LENGTH)}` : DENIED_MESSAGE
|
|
2016
|
+
});
|
|
2017
|
+
}
|
|
2018
|
+
return "applied";
|
|
2019
|
+
}
|
|
2020
|
+
/** Claude Code withdrew a request (it stopped waiting): expired, nothing to answer. */
|
|
2021
|
+
cancel(controlRequestId) {
|
|
2022
|
+
const id = this.byControlId.get(controlRequestId);
|
|
2023
|
+
if (id) this.expire(id, PERMISSION_EXPIRED_CANCELLED, false);
|
|
2024
|
+
}
|
|
2025
|
+
/** Expire everything still waiting, answering Claude Code with a denial. */
|
|
2026
|
+
expireAll(reason) {
|
|
2027
|
+
for (const id of [...this.pending.keys()]) this.expire(id, reason, true);
|
|
2028
|
+
}
|
|
2029
|
+
expire(id, reason, answerClaude) {
|
|
2030
|
+
const pending = this.pending.get(id);
|
|
2031
|
+
if (!pending) return;
|
|
2032
|
+
this.forget(pending);
|
|
2033
|
+
this.settle(id, "expired");
|
|
2034
|
+
if (answerClaude) {
|
|
2035
|
+
this.deps.respond(pending.controlRequestId, {
|
|
2036
|
+
behavior: "deny",
|
|
2037
|
+
message: `Permission for this tool call was not granted: ${reason}`
|
|
2038
|
+
});
|
|
2039
|
+
}
|
|
2040
|
+
this.deps.emit({
|
|
2041
|
+
type: "permission_request",
|
|
2042
|
+
request: {
|
|
2043
|
+
id,
|
|
2044
|
+
toolName: pending.toolName,
|
|
2045
|
+
inputSummary: pending.inputSummary,
|
|
2046
|
+
requestedAt: pending.requestedAt,
|
|
2047
|
+
status: "expired",
|
|
2048
|
+
expiredReason: reason
|
|
2049
|
+
}
|
|
2050
|
+
});
|
|
2051
|
+
}
|
|
2052
|
+
forget(pending) {
|
|
2053
|
+
clearTimeout(pending.timer);
|
|
2054
|
+
this.pending.delete(pending.id);
|
|
2055
|
+
this.byControlId.delete(pending.controlRequestId);
|
|
2056
|
+
}
|
|
2057
|
+
settle(id, how) {
|
|
2058
|
+
this.settled.set(id, how);
|
|
2059
|
+
while (this.settled.size > SETTLED_KEPT) {
|
|
2060
|
+
this.settled.delete(this.settled.keys().next().value);
|
|
2061
|
+
}
|
|
2062
|
+
}
|
|
2063
|
+
};
|
|
2064
|
+
|
|
2065
|
+
// src/stream-mapper.ts
|
|
2066
|
+
function capText(text, max = RUNNER_EVENT_TEXT_MAX_LENGTH) {
|
|
2067
|
+
if (text.length <= max) return { text, truncated: false };
|
|
2068
|
+
const marker = "\n\u2026 [truncated by dt-runner]";
|
|
2069
|
+
return { text: text.slice(0, max - marker.length) + marker, truncated: true };
|
|
2070
|
+
}
|
|
2071
|
+
var ClaudeStreamMapper = class {
|
|
2072
|
+
/** Running offset of each live text block, by providerEventId. */
|
|
2073
|
+
deltaOffsets = /* @__PURE__ */ new Map();
|
|
2074
|
+
/** Stream block index → providerEventId for text blocks of the message streaming now. */
|
|
2075
|
+
streamTextKeys = /* @__PURE__ */ new Map();
|
|
2076
|
+
streamMessageId = null;
|
|
2077
|
+
streamTextCount = 0;
|
|
2078
|
+
/** Text blocks already seen in completed `assistant` lines, per message id. */
|
|
2079
|
+
completedTextCount = /* @__PURE__ */ new Map();
|
|
2080
|
+
/** Tool calls by id, for the name/input a result line does not repeat. */
|
|
2081
|
+
calls = /* @__PURE__ */ new Map();
|
|
2082
|
+
lastAssistantText = null;
|
|
2083
|
+
running = false;
|
|
2084
|
+
/** A new turn is starting (we wrote a user message); the next activity is not news. */
|
|
2085
|
+
markRunning() {
|
|
2086
|
+
this.running = true;
|
|
2087
|
+
}
|
|
2088
|
+
map(line) {
|
|
2089
|
+
const out = { events: [] };
|
|
2090
|
+
if (line.parent_tool_use_id) return out;
|
|
2091
|
+
switch (line.type) {
|
|
2092
|
+
case "system":
|
|
2093
|
+
if (line.subtype === "init" && typeof line.session_id === "string") {
|
|
2094
|
+
out.conversationId = line.session_id;
|
|
2095
|
+
this.ensureRunning(out);
|
|
2096
|
+
}
|
|
2097
|
+
break;
|
|
2098
|
+
case "stream_event":
|
|
2099
|
+
this.mapStreamEvent(line, out);
|
|
2100
|
+
break;
|
|
2101
|
+
case "assistant":
|
|
2102
|
+
this.mapAssistant(line, out);
|
|
2103
|
+
break;
|
|
2104
|
+
case "user":
|
|
2105
|
+
this.mapUser(line, out);
|
|
2106
|
+
break;
|
|
2107
|
+
case "result": {
|
|
2108
|
+
const resultText = typeof line.result === "string" && line.result ? line.result : null;
|
|
2109
|
+
out.turnEnd = {
|
|
2110
|
+
text: resultText ?? this.lastAssistantText,
|
|
2111
|
+
isError: line.is_error === true || (line.subtype ?? "success") !== "success",
|
|
2112
|
+
subtype: typeof line.subtype === "string" ? line.subtype : null
|
|
2113
|
+
};
|
|
2114
|
+
const denials = Array.isArray(line.permission_denials) ? line.permission_denials.filter((d) => d && typeof d.tool_name === "string").map((d) => ({
|
|
2115
|
+
callId: typeof d.tool_use_id === "string" ? d.tool_use_id : null,
|
|
2116
|
+
name: d.tool_name,
|
|
2117
|
+
input: d.tool_input ?? {}
|
|
2118
|
+
})) : [];
|
|
2119
|
+
if (denials.length) out.turnEnd.permissionDenials = denials;
|
|
2120
|
+
this.endTurn();
|
|
2121
|
+
break;
|
|
2122
|
+
}
|
|
2123
|
+
case "control_response": {
|
|
2124
|
+
const res = line.response ?? {};
|
|
2125
|
+
if (typeof res.request_id === "string") {
|
|
2126
|
+
out.controlResponse = { requestId: res.request_id, ok: res.subtype === "success" };
|
|
2127
|
+
}
|
|
2128
|
+
break;
|
|
2129
|
+
}
|
|
2130
|
+
}
|
|
2131
|
+
return out;
|
|
2132
|
+
}
|
|
2133
|
+
ensureRunning(out) {
|
|
2134
|
+
if (!this.running) {
|
|
2135
|
+
this.running = true;
|
|
2136
|
+
out.turnStarted = true;
|
|
2137
|
+
out.events.push({ type: "status", status: "running" });
|
|
2138
|
+
}
|
|
2139
|
+
}
|
|
2140
|
+
mapStreamEvent(line, out) {
|
|
2141
|
+
const ev = line.event ?? {};
|
|
2142
|
+
switch (ev.type) {
|
|
2143
|
+
case "message_start": {
|
|
2144
|
+
this.ensureRunning(out);
|
|
2145
|
+
const id = ev.message?.id ?? line.api_message_id ?? null;
|
|
2146
|
+
this.beginStreamMessage(typeof id === "string" ? id : null);
|
|
2147
|
+
break;
|
|
2148
|
+
}
|
|
2149
|
+
case "content_block_start": {
|
|
2150
|
+
const id = this.streamMessageIdFor(line);
|
|
2151
|
+
if (ev.content_block?.type === "text" && id && typeof ev.index === "number") {
|
|
2152
|
+
const key = textKey(id, this.streamTextCount++);
|
|
2153
|
+
this.streamTextKeys.set(ev.index, key);
|
|
2154
|
+
const initial = typeof ev.content_block.text === "string" ? ev.content_block.text : "";
|
|
2155
|
+
this.deltaOffsets.set(key, 0);
|
|
2156
|
+
if (initial) this.pushDelta(out, key, initial);
|
|
2157
|
+
}
|
|
2158
|
+
break;
|
|
2159
|
+
}
|
|
2160
|
+
case "content_block_delta": {
|
|
2161
|
+
if (ev.delta?.type !== "text_delta" || typeof ev.delta.text !== "string") break;
|
|
2162
|
+
if (!ev.delta.text) break;
|
|
2163
|
+
const key = this.streamTextKeys.get(ev.index);
|
|
2164
|
+
if (key) this.pushDelta(out, key, ev.delta.text);
|
|
2165
|
+
break;
|
|
2166
|
+
}
|
|
2167
|
+
}
|
|
2168
|
+
}
|
|
2169
|
+
streamMessageIdFor(line) {
|
|
2170
|
+
const id = typeof line.api_message_id === "string" ? line.api_message_id : null;
|
|
2171
|
+
if (id && id !== this.streamMessageId) this.beginStreamMessage(id);
|
|
2172
|
+
return this.streamMessageId;
|
|
2173
|
+
}
|
|
2174
|
+
beginStreamMessage(id) {
|
|
2175
|
+
if (id === this.streamMessageId) return;
|
|
2176
|
+
this.streamMessageId = id;
|
|
2177
|
+
this.streamTextKeys.clear();
|
|
2178
|
+
this.streamTextCount = 0;
|
|
2179
|
+
}
|
|
2180
|
+
pushDelta(out, key, text) {
|
|
2181
|
+
const offset = this.deltaOffsets.get(key) ?? 0;
|
|
2182
|
+
this.deltaOffsets.set(key, offset + text.length);
|
|
2183
|
+
out.events.push({ type: "assistant_delta", providerEventId: key, text, offset });
|
|
2184
|
+
}
|
|
2185
|
+
mapAssistant(line, out) {
|
|
2186
|
+
const msg = line.message ?? {};
|
|
2187
|
+
const id = typeof msg.id === "string" ? msg.id : `msg_${line.uuid ?? Date.now()}`;
|
|
2188
|
+
const content = Array.isArray(msg.content) ? msg.content : [];
|
|
2189
|
+
this.ensureRunning(out);
|
|
2190
|
+
for (const block of content) {
|
|
2191
|
+
switch (block?.type) {
|
|
2192
|
+
case "text": {
|
|
2193
|
+
const n = this.completedTextCount.get(id) ?? 0;
|
|
2194
|
+
this.completedTextCount.set(id, n + 1);
|
|
2195
|
+
const text = typeof block.text === "string" ? block.text : "";
|
|
2196
|
+
if (!text.trim()) break;
|
|
2197
|
+
const key = textKey(id, n);
|
|
2198
|
+
this.deltaOffsets.delete(key);
|
|
2199
|
+
this.lastAssistantText = text;
|
|
2200
|
+
out.events.push({
|
|
2201
|
+
type: "assistant_message",
|
|
2202
|
+
providerEventId: key,
|
|
2203
|
+
text: capText(text).text
|
|
2204
|
+
});
|
|
2205
|
+
break;
|
|
2206
|
+
}
|
|
2207
|
+
case "thinking":
|
|
2208
|
+
case "redacted_thinking": {
|
|
2209
|
+
const text = typeof block.thinking === "string" && block.thinking.trim() ? block.thinking : null;
|
|
2210
|
+
out.events.push({
|
|
2211
|
+
type: "thinking",
|
|
2212
|
+
providerEventId: `${id}:thinking:${this.thinkingIndex(id)}`,
|
|
2213
|
+
text: text === null ? null : capText(text).text
|
|
2214
|
+
});
|
|
2215
|
+
break;
|
|
2216
|
+
}
|
|
2217
|
+
case "tool_use":
|
|
2218
|
+
case "server_tool_use":
|
|
2219
|
+
case "mcp_tool_use": {
|
|
2220
|
+
if (typeof block.id !== "string") break;
|
|
2221
|
+
const name = block.type === "mcp_tool_use" && block.server_name ? `${block.server_name}.${block.name}` : String(block.name ?? "tool");
|
|
2222
|
+
this.calls.set(block.id, { name, input: block.input });
|
|
2223
|
+
out.events.push({
|
|
2224
|
+
type: "tool_call",
|
|
2225
|
+
providerEventId: block.id,
|
|
2226
|
+
tool: { callId: block.id, name, status: "running", input: block.input }
|
|
2227
|
+
});
|
|
2228
|
+
break;
|
|
2229
|
+
}
|
|
2230
|
+
}
|
|
2231
|
+
}
|
|
2232
|
+
}
|
|
2233
|
+
thinkingCounts = /* @__PURE__ */ new Map();
|
|
2234
|
+
thinkingIndex(id) {
|
|
2235
|
+
const n = this.thinkingCounts.get(id) ?? 0;
|
|
2236
|
+
this.thinkingCounts.set(id, n + 1);
|
|
2237
|
+
return n;
|
|
2238
|
+
}
|
|
2239
|
+
mapUser(line, out) {
|
|
2240
|
+
const content = line.message?.content;
|
|
2241
|
+
if (!Array.isArray(content)) return;
|
|
2242
|
+
for (const block of content) {
|
|
2243
|
+
if (block?.type !== "tool_result" || typeof block.tool_use_id !== "string") continue;
|
|
2244
|
+
const known = this.calls.get(block.tool_use_id);
|
|
2245
|
+
const full = toolResultText(block.content);
|
|
2246
|
+
const { text, truncated } = capText(full);
|
|
2247
|
+
if (block.is_error) {
|
|
2248
|
+
(out.failedTools ??= []).push({
|
|
2249
|
+
callId: block.tool_use_id,
|
|
2250
|
+
name: known?.name ?? "tool",
|
|
2251
|
+
input: known?.input ?? {},
|
|
2252
|
+
text: full
|
|
2253
|
+
});
|
|
2254
|
+
}
|
|
2255
|
+
const tool = {
|
|
2256
|
+
callId: block.tool_use_id,
|
|
2257
|
+
name: known?.name ?? "tool",
|
|
2258
|
+
status: block.is_error ? "failed" : "completed",
|
|
2259
|
+
...known ? { input: known.input } : {},
|
|
2260
|
+
output: text,
|
|
2261
|
+
...truncated ? { truncated: true } : {}
|
|
2262
|
+
};
|
|
2263
|
+
out.events.push({ type: "tool_call", providerEventId: block.tool_use_id, tool });
|
|
2264
|
+
}
|
|
2265
|
+
}
|
|
2266
|
+
endTurn() {
|
|
2267
|
+
this.running = false;
|
|
2268
|
+
this.lastAssistantText = null;
|
|
2269
|
+
this.deltaOffsets.clear();
|
|
2270
|
+
this.streamTextKeys.clear();
|
|
2271
|
+
this.streamMessageId = null;
|
|
2272
|
+
this.streamTextCount = 0;
|
|
2273
|
+
this.completedTextCount.clear();
|
|
2274
|
+
this.thinkingCounts.clear();
|
|
2275
|
+
if (this.calls.size > 500) this.calls.clear();
|
|
2276
|
+
}
|
|
2277
|
+
};
|
|
2278
|
+
function textKey(messageId, n) {
|
|
2279
|
+
return n === 0 ? messageId : `${messageId}:${n}`;
|
|
2280
|
+
}
|
|
2281
|
+
function toolResultText(content) {
|
|
2282
|
+
if (typeof content === "string") return content;
|
|
2283
|
+
if (!Array.isArray(content)) return content == null ? "" : JSON.stringify(content);
|
|
2284
|
+
return content.map((b) => {
|
|
2285
|
+
if (b?.type === "text" && typeof b.text === "string") return b.text;
|
|
2286
|
+
if (b?.type === "image") return "[image]";
|
|
2287
|
+
return "";
|
|
2288
|
+
}).filter(Boolean).join("\n");
|
|
2289
|
+
}
|
|
2290
|
+
|
|
2291
|
+
// src/drivers/claude.ts
|
|
2292
|
+
var claudeCodeDriver = {
|
|
2293
|
+
kind: "claude_code",
|
|
2294
|
+
displayName: "Claude Code",
|
|
2295
|
+
processModel: "persistent",
|
|
2296
|
+
resolveBinary: (env) => findClaude(env),
|
|
2297
|
+
notInstalledMessage: () => "Claude Code is not installed on the runner\u2019s computer (no `claude` on PATH).",
|
|
2298
|
+
readFeatures: (bin) => claudeFeatures(bin),
|
|
2299
|
+
probe: (env) => probeAgent(env),
|
|
2300
|
+
doctor,
|
|
2301
|
+
validateModel: (model) => assertValidModel(model),
|
|
2302
|
+
launch(input) {
|
|
2303
|
+
const features = input.features;
|
|
2304
|
+
const ask = input.askTools;
|
|
2305
|
+
const allowedTools = features.settingsFlag || ask.length === 0 ? input.allowedTools : input.allowedTools.filter((r) => !overlapsAsk(r, ask));
|
|
2306
|
+
return {
|
|
2307
|
+
bin: input.bin,
|
|
2308
|
+
args: claudeArgs({
|
|
2309
|
+
permissionMode: input.permissionMode,
|
|
2310
|
+
allowedTools,
|
|
2311
|
+
disallowedTools: input.disallowedTools,
|
|
2312
|
+
loadProjectSettings: input.loadProjectSettings,
|
|
2313
|
+
model: input.model,
|
|
2314
|
+
resume: input.resume,
|
|
2315
|
+
relayPermissions: input.relayPermissions,
|
|
2316
|
+
askTools: ask,
|
|
2317
|
+
appendSystemPrompt: input.systemPrompt,
|
|
2318
|
+
features
|
|
2319
|
+
})
|
|
2320
|
+
};
|
|
2321
|
+
},
|
|
2322
|
+
createMapper: () => new ClaudeStreamMapper(),
|
|
2323
|
+
encodeMessage: (content) => ({ type: "user", message: { role: "user", content } }),
|
|
2324
|
+
// As the Agent SDK sends it: Claude Code ends the turn with an `error_during_execution`.
|
|
2325
|
+
interruptMessage: (requestId) => ({
|
|
2326
|
+
type: "control_request",
|
|
2327
|
+
request_id: requestId,
|
|
2328
|
+
request: { subtype: "interrupt" }
|
|
2329
|
+
}),
|
|
2330
|
+
control: {
|
|
2331
|
+
relays: (input) => relaysPermissions({
|
|
2332
|
+
relayPermissions: input.relayPermissions,
|
|
2333
|
+
permissionMode: input.permissionMode,
|
|
2334
|
+
features: input.features
|
|
2335
|
+
}),
|
|
2336
|
+
parse(line) {
|
|
2337
|
+
if (line.type === "control_request") {
|
|
2338
|
+
const ask = parseCanUseTool(line);
|
|
2339
|
+
if (ask) return { kind: "permission", ask };
|
|
2340
|
+
return {
|
|
2341
|
+
kind: "unsupported",
|
|
2342
|
+
requestId: typeof line.request_id === "string" ? line.request_id : null
|
|
2343
|
+
};
|
|
2344
|
+
}
|
|
2345
|
+
const cancelled = parseControlCancel(line);
|
|
2346
|
+
return cancelled ? { kind: "cancel", controlRequestId: cancelled } : null;
|
|
2347
|
+
},
|
|
2348
|
+
permissionResponse: (controlRequestId, response) => ({
|
|
2349
|
+
type: "control_response",
|
|
2350
|
+
response: { subtype: "success", request_id: controlRequestId, response }
|
|
2351
|
+
}),
|
|
2352
|
+
unsupportedResponse: (requestId) => ({
|
|
2353
|
+
type: "control_response",
|
|
2354
|
+
response: {
|
|
2355
|
+
subtype: "error",
|
|
2356
|
+
request_id: requestId,
|
|
2357
|
+
error: "dt-runner does not handle this control request."
|
|
2358
|
+
}
|
|
2359
|
+
})
|
|
2360
|
+
},
|
|
2361
|
+
looksLikeSignInFailure,
|
|
2362
|
+
turnFailedToSignIn,
|
|
2363
|
+
signInFix,
|
|
2364
|
+
turnErrorMessage,
|
|
2365
|
+
startupHint,
|
|
2366
|
+
resumeNotFound: (stderr) => /No conversation found/i.test(stderr)
|
|
2367
|
+
};
|
|
2368
|
+
async function doctor(env = process.env) {
|
|
2369
|
+
const checks = [];
|
|
2370
|
+
const bin = await findClaude(env);
|
|
2371
|
+
if (!bin) {
|
|
2372
|
+
checks.push({
|
|
2373
|
+
name: "Claude Code",
|
|
2374
|
+
level: "fail",
|
|
2375
|
+
detail: env.DT_RUNNER_CLAUDE_BIN ? `DT_RUNNER_CLAUDE_BIN=${env.DT_RUNNER_CLAUDE_BIN} was not found` : "not installed: see https://docs.claude.com/en/docs/claude-code (no `claude` on PATH)"
|
|
2376
|
+
});
|
|
2377
|
+
} else {
|
|
2378
|
+
const version = await claudeVersion(bin);
|
|
2379
|
+
checks.push({
|
|
2380
|
+
name: "Claude Code",
|
|
2381
|
+
level: version ? "ok" : "fail",
|
|
2382
|
+
detail: version ? `${version} (${bin})` : `${bin} --version failed`
|
|
2383
|
+
});
|
|
2384
|
+
if (version) {
|
|
2385
|
+
const auth = await claudeAuthStatus(bin);
|
|
2386
|
+
checks.push(
|
|
2387
|
+
auth.loggedIn === true ? {
|
|
2388
|
+
name: "Claude sign-in",
|
|
2389
|
+
level: "ok",
|
|
2390
|
+
detail: `signed in${auth.authMethod ? ` (${auth.authMethod})` : ""}`
|
|
2391
|
+
} : auth.loggedIn === false ? {
|
|
2392
|
+
name: "Claude sign-in",
|
|
2393
|
+
level: "fail",
|
|
2394
|
+
detail: "not signed in: run `claude` and sign in with your Claude account"
|
|
2395
|
+
} : {
|
|
2396
|
+
name: "Claude sign-in",
|
|
2397
|
+
level: "warn",
|
|
2398
|
+
detail: "could not tell (this Claude Code has no `claude auth status`); update Claude Code"
|
|
2399
|
+
}
|
|
2400
|
+
);
|
|
2401
|
+
}
|
|
2402
|
+
}
|
|
2403
|
+
return checks;
|
|
2404
|
+
}
|
|
2405
|
+
function turnErrorMessage(turn) {
|
|
2406
|
+
switch (turn.subtype) {
|
|
2407
|
+
case "error_max_turns":
|
|
2408
|
+
return "Claude Code stopped: it reached its maximum number of turns.";
|
|
2409
|
+
case "error_max_budget_usd":
|
|
2410
|
+
return "Claude Code stopped: it reached its spending limit.";
|
|
2411
|
+
default:
|
|
2412
|
+
if (turnFailedToSignIn(turn)) {
|
|
2413
|
+
return `Claude Code could not sign in to Claude (${turn.text.slice(0, 200)}). ${signInFix()} Then send a message here to try again.`;
|
|
2414
|
+
}
|
|
2415
|
+
return turn.text ? `Claude Code reported an error: ${turn.text.slice(0, 500)}` : `Claude Code ended the turn with an error (${turn.subtype ?? "unknown"}).`;
|
|
2416
|
+
}
|
|
2417
|
+
}
|
|
2418
|
+
function startupHint(stderr) {
|
|
2419
|
+
if (looksLikeSignInFailure(stderr)) {
|
|
2420
|
+
return ` Claude Code does not seem to be signed in on the runner\u2019s computer. ${signInFix()}`;
|
|
2421
|
+
}
|
|
2422
|
+
if (/No conversation found|session.*not found/i.test(stderr)) {
|
|
2423
|
+
return " The Claude Code conversation to resume was not found on this computer.";
|
|
2424
|
+
}
|
|
2425
|
+
return "";
|
|
2426
|
+
}
|
|
2427
|
+
|
|
2428
|
+
// src/drivers/codex/codex.ts
|
|
2429
|
+
import { delimiter as delimiter2, join as join6 } from "node:path";
|
|
2430
|
+
|
|
2431
|
+
// src/drivers/launcher.ts
|
|
2432
|
+
import { access as access2 } from "node:fs/promises";
|
|
2433
|
+
async function exists2(file) {
|
|
2434
|
+
try {
|
|
2435
|
+
await access2(file);
|
|
2436
|
+
return true;
|
|
2437
|
+
} catch {
|
|
2438
|
+
return false;
|
|
2439
|
+
}
|
|
2440
|
+
}
|
|
2441
|
+
function isJsLauncher(bin) {
|
|
2442
|
+
return /\.[cm]?js$/i.test(bin);
|
|
2443
|
+
}
|
|
2444
|
+
function launcherCommand(bin, args) {
|
|
2445
|
+
return isJsLauncher(bin) ? { bin: process.execPath, args: [bin, ...args] } : { bin, args };
|
|
2446
|
+
}
|
|
2447
|
+
async function findOverride(override, env) {
|
|
2448
|
+
if (isJsLauncher(override)) return await exists2(override) ? override : null;
|
|
2449
|
+
return which(override, env);
|
|
2450
|
+
}
|
|
2451
|
+
|
|
2452
|
+
// src/drivers/codex/codex.ts
|
|
2453
|
+
async function findCodex(env = process.env) {
|
|
2454
|
+
const override = env.DT_RUNNER_CODEX_BIN?.trim();
|
|
2455
|
+
if (override) return findOverride(override, env);
|
|
2456
|
+
const found = await which("codex", env);
|
|
2457
|
+
if (found) return found;
|
|
2458
|
+
if (process.platform !== "win32") return null;
|
|
2459
|
+
for (const dir of (env.PATH ?? env.Path ?? "").split(delimiter2).filter(Boolean)) {
|
|
2460
|
+
if (!await exists2(join6(dir, "codex.cmd"))) continue;
|
|
2461
|
+
const script = join6(dir, "node_modules", "@openai", "codex", "bin", "codex.js");
|
|
2462
|
+
if (await exists2(script)) return script;
|
|
2463
|
+
}
|
|
2464
|
+
return null;
|
|
2465
|
+
}
|
|
2466
|
+
var codexCommand = launcherCommand;
|
|
2467
|
+
function runCodex(bin, args, timeoutMs, env) {
|
|
2468
|
+
const cmd = codexCommand(bin, args);
|
|
2469
|
+
return exec(cmd.bin, cmd.args, { timeoutMs, env });
|
|
2470
|
+
}
|
|
2471
|
+
async function codexVersion(bin, env = process.env) {
|
|
2472
|
+
try {
|
|
2473
|
+
const res = await runCodex(bin, ["--version"], 15e3, env);
|
|
2474
|
+
if (res.code !== 0) return null;
|
|
2475
|
+
return res.stdout.trim().split("\n")[0] || null;
|
|
2476
|
+
} catch {
|
|
2477
|
+
return null;
|
|
2478
|
+
}
|
|
2479
|
+
}
|
|
2480
|
+
async function codexAuthStatus(bin, env = process.env) {
|
|
2481
|
+
try {
|
|
2482
|
+
const res = await runCodex(bin, ["login", "status"], 2e4, env);
|
|
2483
|
+
const said = `${res.stdout}
|
|
2484
|
+
${res.stderr}`;
|
|
2485
|
+
if (res.code !== 0) return { loggedIn: false, authMethod: null };
|
|
2486
|
+
return {
|
|
2487
|
+
loggedIn: true,
|
|
2488
|
+
authMethod: /chatgpt/i.test(said) ? "ChatGPT" : /api key/i.test(said) ? "API key" : null
|
|
2489
|
+
};
|
|
2490
|
+
} catch {
|
|
2491
|
+
return { loggedIn: null, authMethod: null };
|
|
2492
|
+
}
|
|
2493
|
+
}
|
|
2494
|
+
function codexSignInFix(env = process.env) {
|
|
2495
|
+
const key = codexKeyVariable(env);
|
|
2496
|
+
if (key) {
|
|
2497
|
+
return `\`${key}\` is set where the runner runs, so Codex may use that key instead of your ChatGPT sign-in. Unset it (or replace it with a working key) and restart the runner, or run \`codex login\` on the runner\u2019s computer.`;
|
|
2498
|
+
}
|
|
2499
|
+
return "On the runner\u2019s computer, run `codex login` and sign in (with ChatGPT or an API key), and check that `codex login status` says you are logged in.";
|
|
2500
|
+
}
|
|
2501
|
+
function codexKeyVariable(env = process.env) {
|
|
2502
|
+
if (env.CODEX_API_KEY) return "CODEX_API_KEY";
|
|
2503
|
+
if (env.OPENAI_API_KEY) return "OPENAI_API_KEY";
|
|
2504
|
+
return null;
|
|
2505
|
+
}
|
|
2506
|
+
async function probeCodex(env = process.env) {
|
|
2507
|
+
const bin = await findCodex(env);
|
|
2508
|
+
if (!bin) {
|
|
2509
|
+
return {
|
|
2510
|
+
codexVersion: null,
|
|
2511
|
+
codexReady: false,
|
|
2512
|
+
codexProblem: env.DT_RUNNER_CODEX_BIN ? `DT_RUNNER_CODEX_BIN=${env.DT_RUNNER_CODEX_BIN} was not found.` : "Codex is not installed on this computer (no `codex` on PATH). Install it with `npm i -g @openai/codex`."
|
|
2513
|
+
};
|
|
2514
|
+
}
|
|
2515
|
+
const version = await codexVersion(bin, env);
|
|
2516
|
+
if (!version) {
|
|
2517
|
+
return {
|
|
2518
|
+
codexVersion: null,
|
|
2519
|
+
codexReady: false,
|
|
2520
|
+
codexProblem: "`codex --version` failed; reinstall or update Codex."
|
|
2521
|
+
};
|
|
2522
|
+
}
|
|
2523
|
+
const auth = await codexAuthStatus(bin, env);
|
|
2524
|
+
if (auth.loggedIn === false) {
|
|
2525
|
+
return {
|
|
2526
|
+
codexVersion: version,
|
|
2527
|
+
codexReady: false,
|
|
2528
|
+
codexProblem: "Codex is not signed in. Run `codex login` on this computer."
|
|
2529
|
+
};
|
|
2530
|
+
}
|
|
2531
|
+
return { codexVersion: version, codexReady: auth.loggedIn, codexProblem: null };
|
|
2532
|
+
}
|
|
2533
|
+
var SIGN_IN_FAILURE2 = /not logged in|please (run|use) `?codex login|401 unauthorized|status 401|invalid[_ ]api[_ ]key|incorrect api key|refresh token|token (has )?expired|token_expired|could not be refreshed/i;
|
|
2534
|
+
function looksLikeCodexSignInFailure(text) {
|
|
2535
|
+
return !!text && SIGN_IN_FAILURE2.test(text);
|
|
2536
|
+
}
|
|
2537
|
+
var MODEL_NAME2 = /^[A-Za-z0-9][\w.:@/-]{0,199}$/;
|
|
2538
|
+
function assertValidCodexModel(model) {
|
|
2539
|
+
if (model && !MODEL_NAME2.test(model)) {
|
|
2540
|
+
throw new Error(
|
|
2541
|
+
`The model "${model.slice(0, 80)}" is not a valid Codex model name; the runner refused to start it.`
|
|
2542
|
+
);
|
|
2543
|
+
}
|
|
2544
|
+
}
|
|
2545
|
+
function codexArgs(launch) {
|
|
2546
|
+
const args = ["exec", "--json", "--skip-git-repo-check", "--sandbox", launch.sandbox];
|
|
2547
|
+
if (launch.sandbox === "workspace-write" && launch.networkAccess) {
|
|
2548
|
+
args.push("-c", "sandbox_workspace_write.network_access=true");
|
|
2549
|
+
}
|
|
2550
|
+
if (launch.model) {
|
|
2551
|
+
assertValidCodexModel(launch.model);
|
|
2552
|
+
args.push(`--model=${launch.model}`);
|
|
2553
|
+
}
|
|
2554
|
+
args.push("-C", launch.cwd);
|
|
2555
|
+
if (launch.resume) args.push("resume", launch.resume);
|
|
2556
|
+
args.push("-");
|
|
2557
|
+
return args;
|
|
2558
|
+
}
|
|
2559
|
+
function codexFirstPrompt(systemPrompt, prompt) {
|
|
2560
|
+
return systemPrompt ? `${systemPrompt}
|
|
2561
|
+
|
|
2562
|
+
---
|
|
2563
|
+
|
|
2564
|
+
${prompt}` : prompt;
|
|
2565
|
+
}
|
|
2566
|
+
|
|
2567
|
+
// src/drivers/codex/codex-stream-mapper.ts
|
|
2568
|
+
import { randomBytes } from "node:crypto";
|
|
2569
|
+
var CodexStreamMapper = class {
|
|
2570
|
+
running = false;
|
|
2571
|
+
/** The turn's end was reported: what its process says afterwards is no news. */
|
|
2572
|
+
ended = false;
|
|
2573
|
+
turn = 0;
|
|
2574
|
+
turnKey = "";
|
|
2575
|
+
lastMessage = null;
|
|
2576
|
+
/** Error the turn reported before its end (`error` lines). */
|
|
2577
|
+
lastError = null;
|
|
2578
|
+
/** Each session's mapper has its own tag, so a restarted runner's turns are not taken for earlier ones. */
|
|
2579
|
+
tag = randomBytes(3).toString("hex");
|
|
2580
|
+
constructor() {
|
|
2581
|
+
this.beginTurn();
|
|
2582
|
+
}
|
|
2583
|
+
markRunning() {
|
|
2584
|
+
this.running = true;
|
|
2585
|
+
this.beginTurn();
|
|
2586
|
+
}
|
|
2587
|
+
beginTurn() {
|
|
2588
|
+
this.turn++;
|
|
2589
|
+
this.turnKey = `codex-${this.tag}-t${this.turn}`;
|
|
2590
|
+
this.ended = false;
|
|
2591
|
+
this.lastMessage = null;
|
|
2592
|
+
this.lastError = null;
|
|
2593
|
+
}
|
|
2594
|
+
map(line) {
|
|
2595
|
+
const out = { events: [] };
|
|
2596
|
+
if (this.ended) return out;
|
|
2597
|
+
switch (line.type) {
|
|
2598
|
+
case "thread.started":
|
|
2599
|
+
if (typeof line.thread_id === "string" && line.thread_id) {
|
|
2600
|
+
out.conversationId = line.thread_id;
|
|
2601
|
+
}
|
|
2602
|
+
this.ensureRunning(out);
|
|
2603
|
+
break;
|
|
2604
|
+
case "turn.started":
|
|
2605
|
+
this.ensureRunning(out);
|
|
2606
|
+
break;
|
|
2607
|
+
case "item.started":
|
|
2608
|
+
case "item.updated":
|
|
2609
|
+
case "item.completed":
|
|
2610
|
+
if (line.item && typeof line.item === "object") {
|
|
2611
|
+
this.ensureRunning(out);
|
|
2612
|
+
this.mapItem(line.type, line.item, out);
|
|
2613
|
+
}
|
|
2614
|
+
break;
|
|
2615
|
+
case "turn.completed":
|
|
2616
|
+
out.turnEnd = { text: this.lastMessage, isError: false, subtype: "success" };
|
|
2617
|
+
this.endTurn();
|
|
2618
|
+
break;
|
|
2619
|
+
case "turn.failed": {
|
|
2620
|
+
const message = errorMessage(line.error) ?? this.lastError;
|
|
2621
|
+
out.turnEnd = { text: message, isError: true, subtype: "turn_failed" };
|
|
2622
|
+
this.endTurn();
|
|
2623
|
+
break;
|
|
2624
|
+
}
|
|
2625
|
+
case "error": {
|
|
2626
|
+
const message = errorMessage(line) ?? "Codex reported an error.";
|
|
2627
|
+
if (/\b(retrying|reconnecting)\b/i.test(message)) break;
|
|
2628
|
+
out.turnEnd = { text: message, isError: true, subtype: "error" };
|
|
2629
|
+
this.endTurn();
|
|
2630
|
+
break;
|
|
2631
|
+
}
|
|
2632
|
+
}
|
|
2633
|
+
return out;
|
|
2634
|
+
}
|
|
2635
|
+
ensureRunning(out) {
|
|
2636
|
+
if (this.running) return;
|
|
2637
|
+
this.running = true;
|
|
2638
|
+
out.turnStarted = true;
|
|
2639
|
+
out.events.push({ type: "status", status: "running" });
|
|
2640
|
+
}
|
|
2641
|
+
endTurn() {
|
|
2642
|
+
this.running = false;
|
|
2643
|
+
this.ended = true;
|
|
2644
|
+
}
|
|
2645
|
+
mapItem(phase, item, out) {
|
|
2646
|
+
const id = typeof item.id === "string" && item.id ? item.id : null;
|
|
2647
|
+
if (!id) return;
|
|
2648
|
+
const key = `${this.turnKey}:${id}`;
|
|
2649
|
+
const done = phase === "item.completed";
|
|
2650
|
+
switch (item.type) {
|
|
2651
|
+
case "agent_message": {
|
|
2652
|
+
const text = typeof item.text === "string" ? item.text : "";
|
|
2653
|
+
if (!done || !text.trim()) break;
|
|
2654
|
+
this.lastMessage = text;
|
|
2655
|
+
out.events.push({
|
|
2656
|
+
type: "assistant_message",
|
|
2657
|
+
providerEventId: key,
|
|
2658
|
+
text: capText(text).text
|
|
2659
|
+
});
|
|
2660
|
+
break;
|
|
2661
|
+
}
|
|
2662
|
+
case "reasoning": {
|
|
2663
|
+
if (!done) break;
|
|
2664
|
+
const text = typeof item.text === "string" && item.text.trim() ? item.text : null;
|
|
2665
|
+
out.events.push({
|
|
2666
|
+
type: "thinking",
|
|
2667
|
+
providerEventId: key,
|
|
2668
|
+
text: text === null ? null : capText(text).text
|
|
2669
|
+
});
|
|
2670
|
+
break;
|
|
2671
|
+
}
|
|
2672
|
+
case "command_execution": {
|
|
2673
|
+
const command = typeof item.command === "string" ? item.command : "";
|
|
2674
|
+
const exitCode = typeof item.exit_code === "number" ? item.exit_code : null;
|
|
2675
|
+
const failed = item.status === "failed" || item.status === "declined" || exitCode !== null && exitCode !== 0;
|
|
2676
|
+
const status2 = done ? failed ? "failed" : "completed" : "running";
|
|
2677
|
+
const output = typeof item.aggregated_output === "string" ? item.aggregated_output : "";
|
|
2678
|
+
this.pushTool(out, key, "Bash", status2, { command }, done ? output : null);
|
|
2679
|
+
break;
|
|
2680
|
+
}
|
|
2681
|
+
case "file_change": {
|
|
2682
|
+
const changes = Array.isArray(item.changes) ? item.changes.filter((c) => c && typeof c.path === "string").map((c) => ({ path: c.path, kind: typeof c.kind === "string" ? c.kind : null })) : [];
|
|
2683
|
+
const failed = item.status === "failed";
|
|
2684
|
+
const status2 = done || item.status === "completed" ? failed ? "failed" : "completed" : "running";
|
|
2685
|
+
const summary = changes.map((c) => `${c.kind ?? "edit"} ${c.path}`).join("\n");
|
|
2686
|
+
this.pushTool(
|
|
2687
|
+
out,
|
|
2688
|
+
key,
|
|
2689
|
+
"Edit",
|
|
2690
|
+
status2,
|
|
2691
|
+
{ paths: changes.map((c) => c.path), changes },
|
|
2692
|
+
status2 === "running" ? null : summary
|
|
2693
|
+
);
|
|
2694
|
+
break;
|
|
2695
|
+
}
|
|
2696
|
+
case "mcp_tool_call": {
|
|
2697
|
+
const name = typeof item.server === "string" && typeof item.tool === "string" ? `${item.server}.${item.tool}` : String(item.tool ?? "mcp");
|
|
2698
|
+
const error = errorMessage(item.error);
|
|
2699
|
+
const failed = item.status === "failed" || !!error;
|
|
2700
|
+
const status2 = done ? failed ? "failed" : "completed" : "running";
|
|
2701
|
+
const output = error ?? (item.result !== void 0 ? mcpResultText(item.result) : null);
|
|
2702
|
+
this.pushTool(out, key, name, status2, item.arguments ?? {}, done ? output : null);
|
|
2703
|
+
break;
|
|
2704
|
+
}
|
|
2705
|
+
case "web_search": {
|
|
2706
|
+
const query = typeof item.query === "string" ? item.query : "";
|
|
2707
|
+
this.pushTool(out, key, "WebSearch", done ? "completed" : "running", { query }, null);
|
|
2708
|
+
break;
|
|
2709
|
+
}
|
|
2710
|
+
case "todo_list": {
|
|
2711
|
+
const todos = Array.isArray(item.items) ? item.items.filter((t) => t && typeof t.text === "string").map((t) => ({ text: t.text, completed: t.completed === true })) : [];
|
|
2712
|
+
this.pushTool(out, key, "TodoWrite", done ? "completed" : "running", { todos }, null);
|
|
2713
|
+
break;
|
|
2714
|
+
}
|
|
2715
|
+
case "error": {
|
|
2716
|
+
const message = errorMessage(item);
|
|
2717
|
+
if (done && message) {
|
|
2718
|
+
this.lastError = message;
|
|
2719
|
+
out.events.push({ type: "error", message: capText(message).text, retryable: false });
|
|
2720
|
+
}
|
|
2721
|
+
break;
|
|
2722
|
+
}
|
|
2723
|
+
}
|
|
2724
|
+
}
|
|
2725
|
+
pushTool(out, key, name, status2, input, output) {
|
|
2726
|
+
const tool = { callId: key, name, status: status2, input };
|
|
2727
|
+
if (output !== null) {
|
|
2728
|
+
const capped = capText(output);
|
|
2729
|
+
tool.output = capped.text;
|
|
2730
|
+
if (capped.truncated) tool.truncated = true;
|
|
2731
|
+
}
|
|
2732
|
+
out.events.push({ type: "tool_call", providerEventId: key, tool });
|
|
2733
|
+
}
|
|
2734
|
+
};
|
|
2735
|
+
function errorMessage(value) {
|
|
2736
|
+
if (typeof value === "string") return value.trim() || null;
|
|
2737
|
+
if (value && typeof value === "object") {
|
|
2738
|
+
const m = value.message;
|
|
2739
|
+
if (typeof m === "string" && m.trim()) return m;
|
|
2740
|
+
}
|
|
2741
|
+
return null;
|
|
2742
|
+
}
|
|
2743
|
+
function mcpResultText(result) {
|
|
2744
|
+
const content = result?.content;
|
|
2745
|
+
if (Array.isArray(content)) {
|
|
2746
|
+
const text = content.map((b) => b?.type === "text" && typeof b.text === "string" ? b.text : "").filter(Boolean).join("\n");
|
|
2747
|
+
if (text) return text;
|
|
2748
|
+
}
|
|
2749
|
+
return result == null ? "" : JSON.stringify(result);
|
|
2750
|
+
}
|
|
2751
|
+
|
|
2752
|
+
// src/drivers/codex.ts
|
|
2753
|
+
var codexDriver = {
|
|
2754
|
+
kind: "codex",
|
|
2755
|
+
displayName: "Codex",
|
|
2756
|
+
processModel: "per_turn",
|
|
2757
|
+
resolveBinary: (env) => findCodex(env),
|
|
2758
|
+
notInstalledMessage: () => "Codex is not installed on the runner\u2019s computer (no `codex` on PATH). Install it with `npm i -g @openai/codex` and run `codex login`.",
|
|
2759
|
+
readFeatures: async () => ({}),
|
|
2760
|
+
probe: async (env) => ({
|
|
2761
|
+
claudeVersion: null,
|
|
2762
|
+
claudeReady: null,
|
|
2763
|
+
...await probeCodex(env),
|
|
2764
|
+
runsCodex: true
|
|
2765
|
+
}),
|
|
2766
|
+
doctor: doctor2,
|
|
2767
|
+
validateModel: (model) => assertValidCodexModel(model),
|
|
2768
|
+
launch(input) {
|
|
2769
|
+
const prompt = input.resume ? input.prompt ?? "" : codexFirstPrompt(input.systemPrompt, input.prompt ?? "");
|
|
2770
|
+
const cmd = codexCommand(
|
|
2771
|
+
input.bin,
|
|
2772
|
+
codexArgs({
|
|
2773
|
+
cwd: input.cwd,
|
|
2774
|
+
model: input.model,
|
|
2775
|
+
sandbox: input.agentConfig?.codexSandbox ?? "workspace-write",
|
|
2776
|
+
networkAccess: input.agentConfig?.codexNetworkAccess === true,
|
|
2777
|
+
resume: input.resume
|
|
2778
|
+
})
|
|
2779
|
+
);
|
|
2780
|
+
return { ...cmd, stdin: prompt };
|
|
2781
|
+
},
|
|
2782
|
+
createMapper: () => new CodexStreamMapper(),
|
|
2783
|
+
looksLikeSignInFailure: looksLikeCodexSignInFailure,
|
|
2784
|
+
turnFailedToSignIn: (turn) => turn.isError && looksLikeCodexSignInFailure(turn.text),
|
|
2785
|
+
signInFix: (env) => codexSignInFix(env),
|
|
2786
|
+
turnErrorMessage: turnErrorMessage2,
|
|
2787
|
+
startupHint(stderr) {
|
|
2788
|
+
if (looksLikeCodexSignInFailure(stderr)) {
|
|
2789
|
+
return ` Codex does not seem to be signed in on the runner\u2019s computer. ${codexSignInFix()}`;
|
|
2790
|
+
}
|
|
2791
|
+
if (codexResumeNotFound(stderr)) {
|
|
2792
|
+
return " The Codex conversation to resume was not found on this computer.";
|
|
2793
|
+
}
|
|
2794
|
+
return "";
|
|
2795
|
+
},
|
|
2796
|
+
resumeNotFound: (stderr) => codexResumeNotFound(stderr)
|
|
2797
|
+
};
|
|
2798
|
+
function codexResumeNotFound(text) {
|
|
2799
|
+
return /no (rollout|session|thread|conversation)s? found|(thread|session|conversation|rollout)\b[^\n]{0,60}\bnot found/i.test(
|
|
2800
|
+
text
|
|
2801
|
+
);
|
|
2802
|
+
}
|
|
2803
|
+
function turnErrorMessage2(turn) {
|
|
2804
|
+
if (turn.isError && looksLikeCodexSignInFailure(turn.text)) {
|
|
2805
|
+
return `Codex could not sign in (${turn.text.slice(0, 200)}). ${codexSignInFix()} Then send a message here to try again.`;
|
|
2806
|
+
}
|
|
2807
|
+
return turn.text ? `Codex reported an error: ${turn.text.slice(0, 500)}` : "Codex ended the turn with an error.";
|
|
2808
|
+
}
|
|
2809
|
+
async function doctor2(env = process.env) {
|
|
2810
|
+
const checks = [];
|
|
2811
|
+
const bin = await findCodex(env);
|
|
2812
|
+
if (!bin) {
|
|
2813
|
+
checks.push({
|
|
2814
|
+
name: "Codex",
|
|
2815
|
+
level: env.DT_RUNNER_CODEX_BIN ? "fail" : "ok",
|
|
2816
|
+
detail: env.DT_RUNNER_CODEX_BIN ? `DT_RUNNER_CODEX_BIN=${env.DT_RUNNER_CODEX_BIN} was not found` : "not installed (optional): runs can use Codex once `npm i -g @openai/codex` and `codex login` are done"
|
|
2817
|
+
});
|
|
2818
|
+
return checks;
|
|
2819
|
+
}
|
|
2820
|
+
const version = await codexVersion(bin, env);
|
|
2821
|
+
checks.push({
|
|
2822
|
+
name: "Codex",
|
|
2823
|
+
level: version ? "ok" : "warn",
|
|
2824
|
+
detail: version ? `${version} (${bin})` : `${bin} --version failed: Codex runs will not start`
|
|
2825
|
+
});
|
|
2826
|
+
if (!version) return checks;
|
|
2827
|
+
const auth = await codexAuthStatus(bin, env);
|
|
2828
|
+
checks.push(
|
|
2829
|
+
auth.loggedIn === true ? {
|
|
2830
|
+
name: "Codex sign-in",
|
|
2831
|
+
level: "ok",
|
|
2832
|
+
detail: `signed in${auth.authMethod ? ` (${auth.authMethod})` : ""}`
|
|
2833
|
+
} : auth.loggedIn === false ? {
|
|
2834
|
+
name: "Codex sign-in",
|
|
2835
|
+
level: "warn",
|
|
2836
|
+
detail: "not signed in: run `codex login` before starting Codex runs"
|
|
2837
|
+
} : {
|
|
2838
|
+
name: "Codex sign-in",
|
|
2839
|
+
level: "warn",
|
|
2840
|
+
detail: "could not tell (`codex login status` failed)"
|
|
2841
|
+
}
|
|
2842
|
+
);
|
|
2843
|
+
const key = codexKeyVariable(env);
|
|
2844
|
+
if (key) {
|
|
2845
|
+
checks.push({
|
|
2846
|
+
name: key,
|
|
2847
|
+
level: "warn",
|
|
2848
|
+
detail: `is set: Codex runs may bill that API key instead of your ChatGPT plan. Unset it before starting the runner unless that is what you want.`
|
|
2849
|
+
});
|
|
2850
|
+
}
|
|
2851
|
+
return checks;
|
|
2852
|
+
}
|
|
2853
|
+
|
|
2854
|
+
// src/drivers/cursor/cursor.ts
|
|
2855
|
+
async function findCursor(env = process.env) {
|
|
2856
|
+
const override = env.DT_RUNNER_CURSOR_BIN?.trim();
|
|
2857
|
+
if (override) return findOverride(override, env);
|
|
2858
|
+
return await which("cursor-agent", env) ?? await which("agent", env);
|
|
2859
|
+
}
|
|
2860
|
+
function runCursor(bin, args, timeoutMs, env) {
|
|
2861
|
+
const cmd = launcherCommand(bin, args);
|
|
2862
|
+
return exec(cmd.bin, cmd.args, { timeoutMs, env });
|
|
2863
|
+
}
|
|
2864
|
+
async function cursorVersion(bin, env = process.env) {
|
|
2865
|
+
try {
|
|
2866
|
+
const res = await runCursor(bin, ["--version"], 15e3, env);
|
|
2867
|
+
if (res.code !== 0) return null;
|
|
2868
|
+
return res.stdout.trim().split("\n")[0] || null;
|
|
2869
|
+
} catch {
|
|
2870
|
+
return null;
|
|
2871
|
+
}
|
|
2872
|
+
}
|
|
2873
|
+
async function cursorAuthStatus(bin, env = process.env) {
|
|
2874
|
+
try {
|
|
2875
|
+
const res = await runCursor(bin, ["status"], 2e4, env);
|
|
2876
|
+
const said = `${res.stdout}
|
|
2877
|
+
${res.stderr}`;
|
|
2878
|
+
if (/not (logged|signed) in|not authenticated|login required|authentication required/i.test(said)) {
|
|
2879
|
+
return { loggedIn: false };
|
|
2880
|
+
}
|
|
2881
|
+
if (res.code === 0 && /logged in|signed in|authenticated/i.test(said))
|
|
2882
|
+
return { loggedIn: true };
|
|
2883
|
+
return { loggedIn: null };
|
|
2884
|
+
} catch {
|
|
2885
|
+
return { loggedIn: null };
|
|
2886
|
+
}
|
|
2887
|
+
}
|
|
2888
|
+
function cursorKeyVariable(env = process.env) {
|
|
2889
|
+
return env.CURSOR_API_KEY ? "CURSOR_API_KEY" : null;
|
|
2890
|
+
}
|
|
2891
|
+
function cursorSignInFix(env = process.env) {
|
|
2892
|
+
if (cursorKeyVariable(env)) {
|
|
2893
|
+
return "`CURSOR_API_KEY` is set where the runner runs, so the Cursor CLI signs in with that key. Unset it (or replace it with a working key) and restart the runner, or run `cursor-agent login` on the runner\u2019s computer.";
|
|
2894
|
+
}
|
|
2895
|
+
return "On the runner\u2019s computer, run `cursor-agent login` and sign in, and check that `cursor-agent status` says you are logged in.";
|
|
2896
|
+
}
|
|
2897
|
+
async function probeCursor(env = process.env) {
|
|
2898
|
+
const bin = await findCursor(env);
|
|
2899
|
+
if (!bin) {
|
|
2900
|
+
return {
|
|
2901
|
+
cursorVersion: null,
|
|
2902
|
+
cursorReady: false,
|
|
2903
|
+
cursorProblem: env.DT_RUNNER_CURSOR_BIN ? `DT_RUNNER_CURSOR_BIN=${env.DT_RUNNER_CURSOR_BIN} was not found.` : "The Cursor Agent CLI is not installed on this computer (no `cursor-agent` on PATH). Install it from https://cursor.com/cli."
|
|
2904
|
+
};
|
|
2905
|
+
}
|
|
2906
|
+
const version = await cursorVersion(bin, env);
|
|
2907
|
+
if (!version) {
|
|
2908
|
+
return {
|
|
2909
|
+
cursorVersion: null,
|
|
2910
|
+
cursorReady: false,
|
|
2911
|
+
cursorProblem: "`cursor-agent --version` failed; reinstall or update the Cursor Agent CLI."
|
|
2912
|
+
};
|
|
2913
|
+
}
|
|
2914
|
+
const auth = await cursorAuthStatus(bin, env);
|
|
2915
|
+
if (auth.loggedIn === false) {
|
|
2916
|
+
return {
|
|
2917
|
+
cursorVersion: version,
|
|
2918
|
+
cursorReady: false,
|
|
2919
|
+
cursorProblem: "The Cursor Agent CLI is not signed in. Run `cursor-agent login` on this computer."
|
|
2920
|
+
};
|
|
2921
|
+
}
|
|
2922
|
+
return { cursorVersion: version, cursorReady: auth.loggedIn, cursorProblem: null };
|
|
2923
|
+
}
|
|
2924
|
+
var SIGN_IN_FAILURE3 = /authentication required|not (logged|signed) in|please run `?(cursor-)?agent login|invalid api key|401 unauthorized|status 401|unauthenticated|session (has )?expired/i;
|
|
2925
|
+
function looksLikeCursorSignInFailure(text) {
|
|
2926
|
+
return !!text && SIGN_IN_FAILURE3.test(text);
|
|
2927
|
+
}
|
|
2928
|
+
var MODEL_NAME3 = /^[A-Za-z0-9][\w.:@/-]{0,199}$/;
|
|
2929
|
+
function assertValidCursorModel(model) {
|
|
2930
|
+
if (model && !MODEL_NAME3.test(model)) {
|
|
2931
|
+
throw new Error(
|
|
2932
|
+
`The model "${model.slice(0, 80)}" is not a valid Cursor model name; the runner refused to start it.`
|
|
2933
|
+
);
|
|
2934
|
+
}
|
|
2935
|
+
}
|
|
2936
|
+
function cursorArgs(launch) {
|
|
2937
|
+
const args = ["-p", "--output-format", "stream-json"];
|
|
2938
|
+
if (launch.model) {
|
|
2939
|
+
assertValidCursorModel(launch.model);
|
|
2940
|
+
args.push(`--model=${launch.model}`);
|
|
2941
|
+
}
|
|
2942
|
+
if (launch.resume) args.push(`--resume=${launch.resume}`);
|
|
2943
|
+
if (launch.force) args.push("--force");
|
|
2944
|
+
args.push(launch.prompt.startsWith("-") ? `
|
|
2945
|
+
${launch.prompt}` : launch.prompt);
|
|
2946
|
+
return args;
|
|
2947
|
+
}
|
|
2948
|
+
function cursorFirstPrompt(systemPrompt, prompt) {
|
|
2949
|
+
return systemPrompt ? `${systemPrompt}
|
|
2950
|
+
|
|
2951
|
+
---
|
|
2952
|
+
|
|
2953
|
+
${prompt}` : prompt;
|
|
2954
|
+
}
|
|
2955
|
+
|
|
2956
|
+
// src/drivers/cursor/cursor-stream-mapper.ts
|
|
2957
|
+
import { randomBytes as randomBytes2 } from "node:crypto";
|
|
2958
|
+
var CursorStreamMapper = class {
|
|
2959
|
+
running = false;
|
|
2960
|
+
/** The turn's end was reported: what its process says afterwards is no news. */
|
|
2961
|
+
ended = false;
|
|
2962
|
+
turn = 0;
|
|
2963
|
+
turnKey = "";
|
|
2964
|
+
messages = 0;
|
|
2965
|
+
lastMessage = null;
|
|
2966
|
+
/** Each session's mapper has its own tag, so a restarted runner's turns are not taken for earlier ones. */
|
|
2967
|
+
tag = randomBytes2(3).toString("hex");
|
|
2968
|
+
constructor() {
|
|
2969
|
+
this.beginTurn();
|
|
2970
|
+
}
|
|
2971
|
+
markRunning() {
|
|
2972
|
+
this.running = true;
|
|
2973
|
+
this.beginTurn();
|
|
2974
|
+
}
|
|
2975
|
+
beginTurn() {
|
|
2976
|
+
this.turn++;
|
|
2977
|
+
this.turnKey = `cursor-${this.tag}-t${this.turn}`;
|
|
2978
|
+
this.ended = false;
|
|
2979
|
+
this.messages = 0;
|
|
2980
|
+
this.lastMessage = null;
|
|
2981
|
+
}
|
|
2982
|
+
map(line) {
|
|
2983
|
+
const out = { events: [] };
|
|
2984
|
+
if (this.ended) return out;
|
|
2985
|
+
switch (line.type) {
|
|
2986
|
+
case "system":
|
|
2987
|
+
if (line.subtype === "init") {
|
|
2988
|
+
if (typeof line.session_id === "string" && line.session_id) {
|
|
2989
|
+
out.conversationId = line.session_id;
|
|
2990
|
+
}
|
|
2991
|
+
this.ensureRunning(out);
|
|
2992
|
+
}
|
|
2993
|
+
break;
|
|
2994
|
+
case "assistant": {
|
|
2995
|
+
this.ensureRunning(out);
|
|
2996
|
+
const content = Array.isArray(line.message?.content) ? line.message.content : [];
|
|
2997
|
+
const text = content.map((b) => b?.type === "text" && typeof b.text === "string" ? b.text : "").join("");
|
|
2998
|
+
if (!text.trim()) break;
|
|
2999
|
+
this.lastMessage = text;
|
|
3000
|
+
out.events.push({
|
|
3001
|
+
type: "assistant_message",
|
|
3002
|
+
providerEventId: `${this.turnKey}:msg:${this.messages++}`,
|
|
3003
|
+
text: capText(text).text
|
|
3004
|
+
});
|
|
3005
|
+
break;
|
|
3006
|
+
}
|
|
3007
|
+
case "tool_call":
|
|
3008
|
+
if (typeof line.call_id === "string" && line.call_id && line.tool_call) {
|
|
3009
|
+
this.ensureRunning(out);
|
|
3010
|
+
this.mapToolCall(line, out);
|
|
3011
|
+
}
|
|
3012
|
+
break;
|
|
3013
|
+
case "result": {
|
|
3014
|
+
const text = typeof line.result === "string" && line.result ? line.result : null;
|
|
3015
|
+
const subtype = typeof line.subtype === "string" ? line.subtype : null;
|
|
3016
|
+
out.turnEnd = {
|
|
3017
|
+
text: text ?? this.lastMessage,
|
|
3018
|
+
isError: line.is_error === true || (subtype ?? "success") !== "success",
|
|
3019
|
+
subtype
|
|
3020
|
+
};
|
|
3021
|
+
this.running = false;
|
|
3022
|
+
this.ended = true;
|
|
3023
|
+
break;
|
|
3024
|
+
}
|
|
3025
|
+
}
|
|
3026
|
+
return out;
|
|
3027
|
+
}
|
|
3028
|
+
ensureRunning(out) {
|
|
3029
|
+
if (this.running) return;
|
|
3030
|
+
this.running = true;
|
|
3031
|
+
out.turnStarted = true;
|
|
3032
|
+
out.events.push({ type: "status", status: "running" });
|
|
3033
|
+
}
|
|
3034
|
+
mapToolCall(line, out) {
|
|
3035
|
+
const [kind, call] = Object.entries(line.tool_call)[0] ?? [];
|
|
3036
|
+
if (!kind || !call || typeof call !== "object") return;
|
|
3037
|
+
const key = `${this.turnKey}:${line.call_id}`;
|
|
3038
|
+
const done = line.subtype === "completed";
|
|
3039
|
+
const { name, input } = toolNameAndInput(kind, call);
|
|
3040
|
+
const tool = { callId: key, name, status: "running", input };
|
|
3041
|
+
if (done) {
|
|
3042
|
+
const outcome = toolOutcome(kind, call.result);
|
|
3043
|
+
tool.status = outcome.failed ? "failed" : "completed";
|
|
3044
|
+
if (outcome.output !== null) {
|
|
3045
|
+
const capped = capText(outcome.output);
|
|
3046
|
+
tool.output = capped.text;
|
|
3047
|
+
if (capped.truncated) tool.truncated = true;
|
|
3048
|
+
}
|
|
3049
|
+
}
|
|
3050
|
+
out.events.push({ type: "tool_call", providerEventId: key, tool });
|
|
3051
|
+
}
|
|
3052
|
+
};
|
|
3053
|
+
var TOOL_NAMES = {
|
|
3054
|
+
shellToolCall: "Bash",
|
|
3055
|
+
readToolCall: "Read",
|
|
3056
|
+
editToolCall: "Edit",
|
|
3057
|
+
writeToolCall: "Write",
|
|
3058
|
+
deleteToolCall: "Delete",
|
|
3059
|
+
grepToolCall: "Grep",
|
|
3060
|
+
globToolCall: "Glob",
|
|
3061
|
+
lsToolCall: "LS",
|
|
3062
|
+
updateTodosToolCall: "TodoWrite",
|
|
3063
|
+
todoToolCall: "TodoWrite",
|
|
3064
|
+
webSearchToolCall: "WebSearch"
|
|
3065
|
+
};
|
|
3066
|
+
function toolNameAndInput(kind, call) {
|
|
3067
|
+
if (kind === "function") {
|
|
3068
|
+
let input = call.arguments ?? {};
|
|
3069
|
+
if (typeof input === "string") {
|
|
3070
|
+
try {
|
|
3071
|
+
input = JSON.parse(input);
|
|
3072
|
+
} catch {
|
|
3073
|
+
}
|
|
3074
|
+
}
|
|
3075
|
+
return { name: typeof call.name === "string" && call.name ? call.name : "tool", input };
|
|
3076
|
+
}
|
|
3077
|
+
return {
|
|
3078
|
+
name: TOOL_NAMES[kind] ?? kind.replace(/ToolCall$/, ""),
|
|
3079
|
+
input: call.args ?? {}
|
|
3080
|
+
};
|
|
3081
|
+
}
|
|
3082
|
+
function toolOutcome(kind, result) {
|
|
3083
|
+
if (!result || typeof result !== "object") return { failed: false, output: null };
|
|
3084
|
+
const r = result;
|
|
3085
|
+
const failure = r.error ?? r.failure ?? r.rejected;
|
|
3086
|
+
if (failure !== void 0) return { failed: true, output: describe(failure) };
|
|
3087
|
+
const success = r.success;
|
|
3088
|
+
if (success === void 0) return { failed: false, output: describe(r) };
|
|
3089
|
+
if (kind === "shellToolCall" && success && typeof success === "object") {
|
|
3090
|
+
const text = [success.stdout, success.stderr].filter((t) => typeof t === "string" && t).join("\n");
|
|
3091
|
+
const exitCode = typeof success.exitCode === "number" ? success.exitCode : 0;
|
|
3092
|
+
return { failed: exitCode !== 0, output: text };
|
|
3093
|
+
}
|
|
3094
|
+
if (kind === "readToolCall" && typeof success?.content === "string") {
|
|
3095
|
+
return { failed: false, output: success.content };
|
|
3096
|
+
}
|
|
3097
|
+
return { failed: false, output: describe(success) };
|
|
3098
|
+
}
|
|
3099
|
+
function describe(value) {
|
|
3100
|
+
if (typeof value === "string") return value;
|
|
3101
|
+
const message = value?.message ?? value?.reason;
|
|
3102
|
+
if (typeof message === "string" && message) return message;
|
|
3103
|
+
return value == null ? "" : JSON.stringify(value);
|
|
3104
|
+
}
|
|
3105
|
+
|
|
3106
|
+
// src/drivers/cursor.ts
|
|
3107
|
+
var cursorDriver = {
|
|
3108
|
+
kind: "cursor",
|
|
3109
|
+
displayName: "Cursor",
|
|
3110
|
+
processModel: "per_turn",
|
|
3111
|
+
resolveBinary: (env) => findCursor(env),
|
|
3112
|
+
notInstalledMessage: () => "The Cursor Agent CLI is not installed on the runner\u2019s computer (no `cursor-agent` on PATH). Install it from https://cursor.com/cli and run `cursor-agent login`.",
|
|
3113
|
+
readFeatures: async () => ({}),
|
|
3114
|
+
probe: async (env) => ({
|
|
3115
|
+
claudeVersion: null,
|
|
3116
|
+
claudeReady: null,
|
|
3117
|
+
...await probeCursor(env),
|
|
3118
|
+
runsCursor: true
|
|
3119
|
+
}),
|
|
3120
|
+
doctor: doctor3,
|
|
3121
|
+
validateModel: (model) => assertValidCursorModel(model),
|
|
3122
|
+
launch(input) {
|
|
3123
|
+
const prompt = input.resume ? input.prompt ?? "" : cursorFirstPrompt(input.systemPrompt, input.prompt ?? "");
|
|
3124
|
+
return launcherCommand(
|
|
3125
|
+
input.bin,
|
|
3126
|
+
cursorArgs({
|
|
3127
|
+
model: input.model,
|
|
3128
|
+
resume: input.resume,
|
|
3129
|
+
force: input.agentConfig?.cursorForce === true,
|
|
3130
|
+
prompt
|
|
3131
|
+
})
|
|
3132
|
+
);
|
|
3133
|
+
},
|
|
3134
|
+
createMapper: () => new CursorStreamMapper(),
|
|
3135
|
+
looksLikeSignInFailure: looksLikeCursorSignInFailure,
|
|
3136
|
+
turnFailedToSignIn: (turn) => turn.isError && looksLikeCursorSignInFailure(turn.text),
|
|
3137
|
+
signInFix: (env) => cursorSignInFix(env),
|
|
3138
|
+
turnErrorMessage: turnErrorMessage3,
|
|
3139
|
+
startupHint(stderr) {
|
|
3140
|
+
if (looksLikeCursorSignInFailure(stderr)) {
|
|
3141
|
+
return ` The Cursor Agent CLI does not seem to be signed in on the runner\u2019s computer. ${cursorSignInFix()}`;
|
|
3142
|
+
}
|
|
3143
|
+
if (cursorResumeNotFound(stderr)) {
|
|
3144
|
+
return " The Cursor chat to resume was not found on this computer.";
|
|
3145
|
+
}
|
|
3146
|
+
return "";
|
|
3147
|
+
},
|
|
3148
|
+
resumeNotFound: (stderr) => cursorResumeNotFound(stderr)
|
|
3149
|
+
};
|
|
3150
|
+
function cursorResumeNotFound(text) {
|
|
3151
|
+
return /no (chat|session|conversation)s? found|(chat|session|conversation)\b[^\n]{0,60}\bnot found/i.test(
|
|
3152
|
+
text
|
|
3153
|
+
);
|
|
3154
|
+
}
|
|
3155
|
+
function turnErrorMessage3(turn) {
|
|
3156
|
+
if (turn.isError && looksLikeCursorSignInFailure(turn.text)) {
|
|
3157
|
+
return `The Cursor Agent CLI could not sign in (${turn.text.slice(0, 200)}). ${cursorSignInFix()} Then send a message here to try again.`;
|
|
3158
|
+
}
|
|
3159
|
+
return turn.text ? `Cursor reported an error: ${turn.text.slice(0, 500)}` : `Cursor ended the turn with an error (${turn.subtype ?? "unknown"}).`;
|
|
3160
|
+
}
|
|
3161
|
+
async function doctor3(env = process.env) {
|
|
3162
|
+
const checks = [];
|
|
3163
|
+
const bin = await findCursor(env);
|
|
3164
|
+
if (!bin) {
|
|
3165
|
+
checks.push({
|
|
3166
|
+
name: "Cursor Agent CLI",
|
|
3167
|
+
level: env.DT_RUNNER_CURSOR_BIN ? "fail" : "ok",
|
|
3168
|
+
detail: env.DT_RUNNER_CURSOR_BIN ? `DT_RUNNER_CURSOR_BIN=${env.DT_RUNNER_CURSOR_BIN} was not found` : "not installed (optional): runs can use Cursor once the CLI (https://cursor.com/cli) is installed and `cursor-agent login` is done"
|
|
3169
|
+
});
|
|
3170
|
+
return checks;
|
|
3171
|
+
}
|
|
3172
|
+
const version = await cursorVersion(bin, env);
|
|
3173
|
+
checks.push({
|
|
3174
|
+
name: "Cursor Agent CLI",
|
|
3175
|
+
level: version ? "ok" : "warn",
|
|
3176
|
+
detail: version ? `${version} (${bin})` : `${bin} --version failed: Cursor runs will not start`
|
|
3177
|
+
});
|
|
3178
|
+
if (!version) return checks;
|
|
3179
|
+
const auth = await cursorAuthStatus(bin, env);
|
|
3180
|
+
checks.push(
|
|
3181
|
+
auth.loggedIn === true ? { name: "Cursor sign-in", level: "ok", detail: "signed in" } : auth.loggedIn === false ? {
|
|
3182
|
+
name: "Cursor sign-in",
|
|
3183
|
+
level: "warn",
|
|
3184
|
+
detail: "not signed in: run `cursor-agent login` before starting Cursor runs"
|
|
3185
|
+
} : {
|
|
3186
|
+
name: "Cursor sign-in",
|
|
3187
|
+
level: "warn",
|
|
3188
|
+
detail: "could not tell (`cursor-agent status` said nothing the runner reads)"
|
|
3189
|
+
}
|
|
3190
|
+
);
|
|
3191
|
+
if (cursorKeyVariable(env)) {
|
|
3192
|
+
checks.push({
|
|
3193
|
+
name: "CURSOR_API_KEY",
|
|
3194
|
+
level: "warn",
|
|
3195
|
+
detail: "is set: Cursor runs sign in with that API key instead of your `cursor-agent login`. Unset it before starting the runner unless that is what you want."
|
|
3196
|
+
});
|
|
3197
|
+
}
|
|
3198
|
+
return checks;
|
|
3199
|
+
}
|
|
3200
|
+
|
|
3201
|
+
// src/agent-driver.ts
|
|
3202
|
+
var DEFAULT_AGENT_KIND = "claude_code";
|
|
3203
|
+
var DRIVERS = new Map(
|
|
3204
|
+
[claudeCodeDriver, codexDriver, cursorDriver].map((d) => [d.kind, d])
|
|
3205
|
+
);
|
|
3206
|
+
function agentDriver(kind = DEFAULT_AGENT_KIND) {
|
|
3207
|
+
const driver = DRIVERS.get(kind || DEFAULT_AGENT_KIND);
|
|
3208
|
+
if (!driver) throw new Error(`This runner cannot run "${kind}" agents.`);
|
|
3209
|
+
return driver;
|
|
3210
|
+
}
|
|
3211
|
+
function agentDriverKinds() {
|
|
3212
|
+
return [...DRIVERS.keys()];
|
|
3213
|
+
}
|
|
3214
|
+
|
|
3215
|
+
// src/config.ts
|
|
3216
|
+
import { chmod, mkdir as mkdir3, readFile as readFile3, rm as rm3, writeFile as writeFile2 } from "node:fs/promises";
|
|
3217
|
+
import { homedir as homedir2 } from "node:os";
|
|
3218
|
+
import { dirname as dirname3, join as join7 } from "node:path";
|
|
3219
|
+
|
|
3220
|
+
// src/invocation.ts
|
|
3221
|
+
var RUNNER_PACKAGE = "@discovery-tree/runner";
|
|
3222
|
+
function launchedByNpx(env = process.env, argv1 = process.argv[1]) {
|
|
3223
|
+
if (env.npm_command === "exec") return true;
|
|
3224
|
+
return /[\\/](_npx|dlx)[\\/]/.test(argv1 ?? "");
|
|
3225
|
+
}
|
|
3226
|
+
function runnerCommand(subcommand, viaNpx = launchedByNpx()) {
|
|
3227
|
+
return viaNpx ? `npx ${RUNNER_PACKAGE}@latest ${subcommand}` : `dt-runner ${subcommand}`;
|
|
3228
|
+
}
|
|
3229
|
+
|
|
3230
|
+
// src/config.ts
|
|
3231
|
+
function runnerPaths(env = process.env) {
|
|
3232
|
+
const home = homedir2();
|
|
3233
|
+
if (process.platform === "win32") {
|
|
3234
|
+
const roaming = env.APPDATA || join7(home, "AppData", "Roaming");
|
|
3235
|
+
const local = env.LOCALAPPDATA || join7(home, "AppData", "Local");
|
|
3236
|
+
return {
|
|
3237
|
+
configFile: join7(roaming, "discovery-tree", "runner.json"),
|
|
3238
|
+
dataDir: join7(local, "discovery-tree", "runner"),
|
|
3239
|
+
stateDir: join7(local, "discovery-tree", "runner", "state")
|
|
3240
|
+
};
|
|
3241
|
+
}
|
|
3242
|
+
const config = env.XDG_CONFIG_HOME || join7(home, ".config");
|
|
3243
|
+
const data = env.XDG_DATA_HOME || join7(home, ".local", "share");
|
|
3244
|
+
const state = env.XDG_STATE_HOME || join7(home, ".local", "state");
|
|
3245
|
+
return {
|
|
3246
|
+
configFile: join7(config, "discovery-tree", "runner.json"),
|
|
3247
|
+
dataDir: join7(data, "discovery-tree", "runner"),
|
|
3248
|
+
stateDir: join7(state, "discovery-tree", "runner")
|
|
3249
|
+
};
|
|
3250
|
+
}
|
|
3251
|
+
var PERMISSION_MODES = [
|
|
3252
|
+
"acceptEdits",
|
|
3253
|
+
"auto",
|
|
3254
|
+
"default",
|
|
3255
|
+
"manual",
|
|
3256
|
+
"dontAsk",
|
|
3257
|
+
"plan",
|
|
3258
|
+
"bypassPermissions"
|
|
3259
|
+
];
|
|
3260
|
+
var DEFAULT_ALLOWED_TOOLS = [
|
|
3261
|
+
"Read",
|
|
3262
|
+
"Edit",
|
|
3263
|
+
"MultiEdit",
|
|
3264
|
+
"Write",
|
|
3265
|
+
"Glob",
|
|
3266
|
+
"Grep",
|
|
3267
|
+
"LS",
|
|
3268
|
+
"NotebookEdit",
|
|
3269
|
+
"TodoWrite",
|
|
3270
|
+
"Task",
|
|
3271
|
+
// Stops a command started with the Bash tool's background option (a dev server); its
|
|
3272
|
+
// output is a file the agent reads with Read.
|
|
3273
|
+
"TaskStop",
|
|
3274
|
+
"Bash(git status *)",
|
|
3275
|
+
"Bash(git diff *)",
|
|
3276
|
+
"Bash(git log *)",
|
|
3277
|
+
"Bash(git show *)",
|
|
3278
|
+
"Bash(git add *)",
|
|
3279
|
+
"Bash(git commit *)",
|
|
3280
|
+
"Bash(git restore *)",
|
|
3281
|
+
"Bash(git rm *)",
|
|
3282
|
+
"Bash(git mv *)",
|
|
3283
|
+
"Bash(git stash *)",
|
|
3284
|
+
"Bash(git blame *)",
|
|
3285
|
+
"Bash(git grep *)",
|
|
3286
|
+
"Bash(git rev-parse *)",
|
|
3287
|
+
"Bash(git ls-files *)",
|
|
3288
|
+
"Bash(git ls-tree *)",
|
|
3289
|
+
"Bash(git cat-file *)",
|
|
3290
|
+
"Bash(git describe *)",
|
|
3291
|
+
"Bash(git shortlog *)",
|
|
3292
|
+
"Bash(git reflog)",
|
|
3293
|
+
"Bash(git reflog show *)",
|
|
3294
|
+
"Bash(git show-ref *)",
|
|
3295
|
+
"Bash(git merge-base *)",
|
|
3296
|
+
// Not read-only on the network, and like `node *` it can run a command
|
|
3297
|
+
// (`--upload-pack`); on the list because agents fetch the base branch to compare with it.
|
|
3298
|
+
"Bash(git fetch *)",
|
|
3299
|
+
"Bash(git remote -v)",
|
|
3300
|
+
"Bash(git branch)",
|
|
3301
|
+
"Bash(git branch --show-current)",
|
|
3302
|
+
"Bash(git branch -a)",
|
|
3303
|
+
"Bash(git branch -r)",
|
|
3304
|
+
"Bash(git branch -v)",
|
|
3305
|
+
"Bash(git branch -vv)",
|
|
3306
|
+
"Bash(git branch --list *)",
|
|
3307
|
+
"Bash(git branch --contains *)",
|
|
3308
|
+
"Bash(git config --get *)",
|
|
3309
|
+
"Bash(git config --list *)",
|
|
3310
|
+
"Bash(git worktree list *)",
|
|
3311
|
+
"Bash(gh pr view *)",
|
|
3312
|
+
"Bash(gh pr diff *)",
|
|
3313
|
+
"Bash(gh pr checks *)",
|
|
3314
|
+
"Bash(gh pr list *)",
|
|
3315
|
+
"Bash(gh pr status *)",
|
|
3316
|
+
"Bash(gh run view *)",
|
|
3317
|
+
"Bash(gh run list *)",
|
|
3318
|
+
"Bash(gh issue view *)",
|
|
3319
|
+
"Bash(gh issue list *)",
|
|
3320
|
+
"Bash(gh repo view *)",
|
|
3321
|
+
"Bash(npm *)",
|
|
3322
|
+
"Bash(npx *)",
|
|
3323
|
+
"Bash(pnpm *)",
|
|
3324
|
+
"Bash(yarn *)",
|
|
3325
|
+
"Bash(node *)",
|
|
3326
|
+
"Bash(tsc *)",
|
|
3327
|
+
"Bash(python *)",
|
|
3328
|
+
"Bash(python3 *)",
|
|
3329
|
+
"Bash(pip *)",
|
|
3330
|
+
"Bash(pytest *)",
|
|
3331
|
+
"Bash(make *)",
|
|
3332
|
+
"Bash(cargo *)",
|
|
3333
|
+
"Bash(go *)",
|
|
3334
|
+
// The same, for other toolchains: they run the repository's code as npm and make do.
|
|
3335
|
+
"Bash(bun *)",
|
|
3336
|
+
"Bash(deno *)",
|
|
3337
|
+
"Bash(uv *)",
|
|
3338
|
+
"Bash(poetry *)",
|
|
3339
|
+
"Bash(ruby *)",
|
|
3340
|
+
"Bash(bundle *)",
|
|
3341
|
+
"Bash(rake *)",
|
|
3342
|
+
"Bash(rspec *)",
|
|
3343
|
+
"Bash(mvn *)",
|
|
3344
|
+
"Bash(gradle *)",
|
|
3345
|
+
"Bash(./gradlew *)",
|
|
3346
|
+
"Bash(dotnet *)",
|
|
3347
|
+
"Bash(swift *)",
|
|
3348
|
+
"Bash(java *)",
|
|
3349
|
+
"Bash(rustc *)",
|
|
3350
|
+
"Bash(jest *)",
|
|
3351
|
+
"Bash(vitest *)",
|
|
3352
|
+
"Bash(eslint *)",
|
|
3353
|
+
"Bash(prettier *)",
|
|
3354
|
+
"Bash(ruff *)",
|
|
3355
|
+
"Bash(mypy *)",
|
|
3356
|
+
"Bash(black *)",
|
|
3357
|
+
"Bash(ls *)",
|
|
3358
|
+
"Bash(cat *)",
|
|
3359
|
+
"Bash(head *)",
|
|
3360
|
+
"Bash(tail *)",
|
|
3361
|
+
"Bash(wc *)",
|
|
3362
|
+
"Bash(grep *)",
|
|
3363
|
+
"Bash(rg *)",
|
|
3364
|
+
"Bash(echo *)",
|
|
3365
|
+
"Bash(pwd)",
|
|
3366
|
+
"Bash(mkdir *)",
|
|
3367
|
+
"Bash(touch *)",
|
|
3368
|
+
"Bash(diff *)",
|
|
3369
|
+
"Bash(sort *)",
|
|
3370
|
+
"Bash(uniq *)",
|
|
3371
|
+
"Bash(which *)",
|
|
3372
|
+
// Read-only, and none prints a file's contents (which would get around the credential
|
|
3373
|
+
// deny rules below for a command Claude Code does not know reads files): metadata,
|
|
3374
|
+
// hashes, and what is piped to them.
|
|
3375
|
+
"Bash(tr *)",
|
|
3376
|
+
"Bash(stat *)",
|
|
3377
|
+
"Bash(du *)",
|
|
3378
|
+
"Bash(df *)",
|
|
3379
|
+
"Bash(ps *)",
|
|
3380
|
+
"Bash(basename *)",
|
|
3381
|
+
"Bash(dirname *)",
|
|
3382
|
+
"Bash(realpath *)",
|
|
1438
3383
|
"Bash(readlink *)",
|
|
1439
3384
|
"Bash(md5sum *)",
|
|
1440
3385
|
"Bash(sha256sum *)",
|
|
@@ -1495,7 +3440,7 @@ var DEFAULT_DISALLOWED_TOOLS = [
|
|
|
1495
3440
|
];
|
|
1496
3441
|
function configDirRules(configFile, platform = process.platform) {
|
|
1497
3442
|
if (platform === "win32") return [];
|
|
1498
|
-
const dir =
|
|
3443
|
+
const dir = dirname3(configFile);
|
|
1499
3444
|
if (!dir.startsWith("/")) return [];
|
|
1500
3445
|
return [`Read(/${dir}/**)`, `Edit(/${dir}/**)`];
|
|
1501
3446
|
}
|
|
@@ -1505,7 +3450,7 @@ var DEFAULT_IDLE_TIMEOUT_MINUTES = 15;
|
|
|
1505
3450
|
async function readConfigFile(file) {
|
|
1506
3451
|
let raw;
|
|
1507
3452
|
try {
|
|
1508
|
-
raw = await
|
|
3453
|
+
raw = await readFile3(file, "utf8");
|
|
1509
3454
|
} catch (err) {
|
|
1510
3455
|
if (err.code === "ENOENT") return null;
|
|
1511
3456
|
throw err;
|
|
@@ -1519,7 +3464,7 @@ async function readConfigFile(file) {
|
|
|
1519
3464
|
}
|
|
1520
3465
|
}
|
|
1521
3466
|
async function writeConfigFile(file, config) {
|
|
1522
|
-
await mkdir3(
|
|
3467
|
+
await mkdir3(dirname3(file), { recursive: true, mode: 448 });
|
|
1523
3468
|
await writeFile2(file, JSON.stringify(config, null, 2) + "\n", { mode: 384 });
|
|
1524
3469
|
await chmod(file, 384).catch(() => void 0);
|
|
1525
3470
|
}
|
|
@@ -1550,10 +3495,28 @@ function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPa
|
|
|
1550
3495
|
`maxSessions must be a whole number from 1 to ${MAX_SESSIONS_LIMIT} (got ${maxSessions}).`
|
|
1551
3496
|
);
|
|
1552
3497
|
}
|
|
1553
|
-
const inherit = file?.inheritClaudeCodePermissions;
|
|
1554
|
-
if (inherit !== void 0 && typeof inherit !== "boolean") {
|
|
3498
|
+
const inherit = file?.inheritClaudeCodePermissions;
|
|
3499
|
+
if (inherit !== void 0 && typeof inherit !== "boolean") {
|
|
3500
|
+
throw new Error(
|
|
3501
|
+
`inheritClaudeCodePermissions in ${paths.configFile} must be true or false (got ${JSON.stringify(inherit)}).`
|
|
3502
|
+
);
|
|
3503
|
+
}
|
|
3504
|
+
const codexSandbox = file?.codexSandbox ?? "workspace-write";
|
|
3505
|
+
if (codexSandbox !== "workspace-write" && codexSandbox !== "danger-full-access") {
|
|
3506
|
+
throw new Error(
|
|
3507
|
+
`codexSandbox "${String(codexSandbox)}" in ${paths.configFile} is not one of workspace-write, danger-full-access.`
|
|
3508
|
+
);
|
|
3509
|
+
}
|
|
3510
|
+
const codexNetwork = file?.codexNetworkAccess;
|
|
3511
|
+
if (codexNetwork !== void 0 && typeof codexNetwork !== "boolean") {
|
|
3512
|
+
throw new Error(
|
|
3513
|
+
`codexNetworkAccess in ${paths.configFile} must be true or false (got ${JSON.stringify(codexNetwork)}).`
|
|
3514
|
+
);
|
|
3515
|
+
}
|
|
3516
|
+
const cursorForce = file?.cursorForce;
|
|
3517
|
+
if (cursorForce !== void 0 && typeof cursorForce !== "boolean") {
|
|
1555
3518
|
throw new Error(
|
|
1556
|
-
`
|
|
3519
|
+
`cursorForce in ${paths.configFile} must be true or false (got ${JSON.stringify(cursorForce)}).`
|
|
1557
3520
|
);
|
|
1558
3521
|
}
|
|
1559
3522
|
const allowed = [
|
|
@@ -1573,8 +3536,8 @@ function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPa
|
|
|
1573
3536
|
token: env.DT_RUNNER_TOKEN || file?.token || null,
|
|
1574
3537
|
name: file?.name ?? null,
|
|
1575
3538
|
maxSessions,
|
|
1576
|
-
reposDir: overrides.reposDir ?? file?.reposDir ??
|
|
1577
|
-
worktreesDir: file?.worktreesDir ??
|
|
3539
|
+
reposDir: overrides.reposDir ?? file?.reposDir ?? join7(paths.dataDir, "repos"),
|
|
3540
|
+
worktreesDir: file?.worktreesDir ?? join7(paths.dataDir, "worktrees"),
|
|
1578
3541
|
permissionMode: mode,
|
|
1579
3542
|
allowedTools: [...new Set(allowed)],
|
|
1580
3543
|
disallowedTools: [...new Set(disallowed)],
|
|
@@ -1583,13 +3546,16 @@ function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPa
|
|
|
1583
3546
|
inheritClaudeCodePermissions: inherit !== false,
|
|
1584
3547
|
gitProtocol: file?.gitProtocol === "ssh" ? "ssh" : "https",
|
|
1585
3548
|
idleTimeoutMs: (file?.idleTimeoutMinutes ?? DEFAULT_IDLE_TIMEOUT_MINUTES) * 6e4,
|
|
3549
|
+
codexSandbox,
|
|
3550
|
+
codexNetworkAccess: codexNetwork === true,
|
|
3551
|
+
cursorForce: cursorForce === true,
|
|
1586
3552
|
stateDir: paths.stateDir,
|
|
1587
3553
|
configFile: paths.configFile
|
|
1588
3554
|
};
|
|
1589
3555
|
}
|
|
1590
3556
|
|
|
1591
3557
|
// src/daemon.ts
|
|
1592
|
-
import { join as
|
|
3558
|
+
import { join as join13 } from "node:path";
|
|
1593
3559
|
|
|
1594
3560
|
// src/backoff.ts
|
|
1595
3561
|
function backoffDelay(attempt, baseMs = 1e3, maxMs = 6e4) {
|
|
@@ -1612,7 +3578,7 @@ function sleep(ms, signal) {
|
|
|
1612
3578
|
// src/completion.ts
|
|
1613
3579
|
import { mkdtemp as mkdtemp2, rm as rm4 } from "node:fs/promises";
|
|
1614
3580
|
import { tmpdir as tmpdir2 } from "node:os";
|
|
1615
|
-
import { join as
|
|
3581
|
+
import { join as join8 } from "node:path";
|
|
1616
3582
|
var COMPLETION_DENIED_TOOLS = [
|
|
1617
3583
|
"Read",
|
|
1618
3584
|
"Glob",
|
|
@@ -1660,7 +3626,7 @@ async function answerCompletion(req, deps) {
|
|
|
1660
3626
|
try {
|
|
1661
3627
|
const { bin, features } = await deps.claude();
|
|
1662
3628
|
const args = completionArgs(req, features);
|
|
1663
|
-
cwd = await mkdtemp2(
|
|
3629
|
+
cwd = await mkdtemp2(join8(tmpdir2(), "dt-runner-completion-"));
|
|
1664
3630
|
const run = deps.run ?? ((b, a, o) => exec(b, a, { ...o, ownTree: true }));
|
|
1665
3631
|
const input = req.systemPrompt ? `<instructions>
|
|
1666
3632
|
${req.systemPrompt}
|
|
@@ -1712,21 +3678,79 @@ function reportableSessionIds(ids, onDropped = () => void 0) {
|
|
|
1712
3678
|
}
|
|
1713
3679
|
|
|
1714
3680
|
// src/session-manager.ts
|
|
1715
|
-
import { mkdir as
|
|
1716
|
-
import { join as
|
|
3681
|
+
import { mkdir as mkdir7, rm as rm6, writeFile as writeFile5 } from "node:fs/promises";
|
|
3682
|
+
import { join as join12 } from "node:path";
|
|
3683
|
+
|
|
3684
|
+
// src/prompt-images.ts
|
|
3685
|
+
import { mkdir as mkdir4, writeFile as writeFile3 } from "node:fs/promises";
|
|
3686
|
+
import { join as join9 } from "node:path";
|
|
3687
|
+
var EXTENSIONS = {
|
|
3688
|
+
"image/png": ".png",
|
|
3689
|
+
"image/jpeg": ".jpg",
|
|
3690
|
+
"image/gif": ".gif",
|
|
3691
|
+
"image/webp": ".webp"
|
|
3692
|
+
};
|
|
3693
|
+
function promptImageFileName(index, filename, mimeType) {
|
|
3694
|
+
const base = (filename.split(/[\\/]/).pop() ?? "").replace(/[\u0000-\u001f\u007f<>:"|?*]+/g, "_").replace(/^\.+/, "").trim().slice(0, 120);
|
|
3695
|
+
const ext = EXTENSIONS[mimeType] ?? "";
|
|
3696
|
+
const named = base || `image${ext}`;
|
|
3697
|
+
const withExt = ext && !named.toLowerCase().endsWith(ext) ? `${named}${ext}` : named;
|
|
3698
|
+
return `${String(index + 1).padStart(2, "0")}-${withExt}`;
|
|
3699
|
+
}
|
|
3700
|
+
async function savePromptImages(input) {
|
|
3701
|
+
const out = { saved: [], failed: [] };
|
|
3702
|
+
if (input.images.length === 0) return out;
|
|
3703
|
+
const dir = join9(input.cwd, RUNNER_TASK_IMAGES_DIR);
|
|
3704
|
+
await mkdir4(dir, { recursive: true });
|
|
3705
|
+
if (input.inRepository) {
|
|
3706
|
+
await excludeFromGit(
|
|
3707
|
+
input.cwd,
|
|
3708
|
+
RUNNER_TASK_IMAGES_DIR,
|
|
3709
|
+
"Task images dt-runner saves for its agent"
|
|
3710
|
+
);
|
|
3711
|
+
}
|
|
3712
|
+
for (const [index, image] of input.images.entries()) {
|
|
3713
|
+
try {
|
|
3714
|
+
const res = await input.fetcher.getPromptImage(input.sessionId, image.attachmentId);
|
|
3715
|
+
const path = join9(
|
|
3716
|
+
dir,
|
|
3717
|
+
promptImageFileName(index, image.filename, res.mimeType || image.mimeType)
|
|
3718
|
+
);
|
|
3719
|
+
await writeFile3(path, Buffer.from(res.dataBase64, "base64"));
|
|
3720
|
+
out.saved.push({ filename: image.filename, path });
|
|
3721
|
+
} catch {
|
|
3722
|
+
out.failed.push(image.filename);
|
|
3723
|
+
}
|
|
3724
|
+
}
|
|
3725
|
+
return out;
|
|
3726
|
+
}
|
|
3727
|
+
function promptWithImagePaths(prompt, images) {
|
|
3728
|
+
if (images.saved.length === 0 && images.failed.length === 0) return prompt;
|
|
3729
|
+
const lines = [
|
|
3730
|
+
"",
|
|
3731
|
+
"IMAGE FILES FOR THIS TASK \u2014 the images the attachment lists above refer to, saved as",
|
|
3732
|
+
"files. Open each one and look at it before you start (read it as an image).",
|
|
3733
|
+
...images.saved.map((i) => `- ${i.filename}: ${i.path}`),
|
|
3734
|
+
...images.failed.map(
|
|
3735
|
+
(name) => `- ${name}: could not be downloaded; say so rather than describing it`
|
|
3736
|
+
)
|
|
3737
|
+
];
|
|
3738
|
+
return `${prompt}
|
|
3739
|
+
${lines.join("\n")}`;
|
|
3740
|
+
}
|
|
1717
3741
|
|
|
1718
3742
|
// src/fsutil.ts
|
|
1719
|
-
import { mkdir as
|
|
1720
|
-
import { dirname as
|
|
3743
|
+
import { mkdir as mkdir5, readFile as readFile4, rename as rename2, writeFile as writeFile4 } from "node:fs/promises";
|
|
3744
|
+
import { dirname as dirname4 } from "node:path";
|
|
1721
3745
|
async function writeJsonAtomic(file, value) {
|
|
1722
|
-
await
|
|
3746
|
+
await mkdir5(dirname4(file), { recursive: true });
|
|
1723
3747
|
const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
1724
|
-
await
|
|
3748
|
+
await writeFile4(tmp, JSON.stringify(value), { mode: 384 });
|
|
1725
3749
|
await rename2(tmp, file);
|
|
1726
3750
|
}
|
|
1727
3751
|
async function readJson(file) {
|
|
1728
3752
|
try {
|
|
1729
|
-
return JSON.parse(await
|
|
3753
|
+
return JSON.parse(await readFile4(file, "utf8"));
|
|
1730
3754
|
} catch (err) {
|
|
1731
3755
|
if (err.code === "ENOENT") return null;
|
|
1732
3756
|
if (err instanceof SyntaxError) return null;
|
|
@@ -1918,262 +3942,62 @@ var SessionOutbox = class _SessionOutbox {
|
|
|
1918
3942
|
this.pending = this.pending.filter((e) => e.seq > maxSeq);
|
|
1919
3943
|
this.persist();
|
|
1920
3944
|
rejected = 0;
|
|
1921
|
-
continue;
|
|
1922
|
-
}
|
|
1923
|
-
} else {
|
|
1924
|
-
this.opts.logger.debug("posting session events failed; will retry", {
|
|
1925
|
-
session: this.opts.sessionId,
|
|
1926
|
-
error: err.message
|
|
1927
|
-
});
|
|
1928
|
-
}
|
|
1929
|
-
await sleep(
|
|
1930
|
-
backoffDelay(attempt++, this.opts.retryBaseMs ?? 1e3),
|
|
1931
|
-
this.stopController.signal
|
|
1932
|
-
);
|
|
1933
|
-
} finally {
|
|
1934
|
-
this.inFlightUpTo = 0;
|
|
1935
|
-
}
|
|
1936
|
-
}
|
|
1937
|
-
} finally {
|
|
1938
|
-
this.pumping = false;
|
|
1939
|
-
}
|
|
1940
|
-
if (!this.pending.length || this.closed) this.notifyIdle();
|
|
1941
|
-
else if (!this.stopped) this.schedulePump();
|
|
1942
|
-
}
|
|
1943
|
-
markClosed(reason) {
|
|
1944
|
-
this.opts.logger.info(`session ${this.opts.sessionId}: ${reason}`);
|
|
1945
|
-
this.discard();
|
|
1946
|
-
this.opts.onClosed?.();
|
|
1947
|
-
}
|
|
1948
|
-
notifyIdle() {
|
|
1949
|
-
const waiters = this.idleWaiters;
|
|
1950
|
-
this.idleWaiters = [];
|
|
1951
|
-
for (const w of waiters) w();
|
|
1952
|
-
}
|
|
1953
|
-
};
|
|
1954
|
-
function takeBatch(pending) {
|
|
1955
|
-
const budget = RUNNER_EVENTS_MAX_BODY_BYTES / 2;
|
|
1956
|
-
let bytes = 0;
|
|
1957
|
-
let n = 0;
|
|
1958
|
-
while (n < pending.length && n < RUNNER_EVENTS_MAX_BATCH) {
|
|
1959
|
-
const size = Buffer.byteLength(JSON.stringify(pending[n]));
|
|
1960
|
-
if (n > 0 && bytes + size > budget) break;
|
|
1961
|
-
bytes += size;
|
|
1962
|
-
n++;
|
|
1963
|
-
}
|
|
1964
|
-
return pending.slice(0, n);
|
|
1965
|
-
}
|
|
1966
|
-
|
|
1967
|
-
// src/session.ts
|
|
1968
|
-
import { spawn as spawn3 } from "node:child_process";
|
|
1969
|
-
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
1970
|
-
import { basename, dirname as dirname6 } from "node:path";
|
|
1971
|
-
import { createInterface } from "node:readline";
|
|
1972
|
-
|
|
1973
|
-
// src/permissions.ts
|
|
1974
|
-
import { randomUUID } from "node:crypto";
|
|
1975
|
-
function parseCanUseTool(line) {
|
|
1976
|
-
if (line?.type !== "control_request") return null;
|
|
1977
|
-
const req = line.request;
|
|
1978
|
-
if (!req || req.subtype !== "can_use_tool") return null;
|
|
1979
|
-
if (typeof line.request_id !== "string" || !line.request_id) return null;
|
|
1980
|
-
const toolName = typeof req.tool_name === "string" && req.tool_name ? req.tool_name : "tool";
|
|
1981
|
-
return { controlRequestId: line.request_id, toolName, input: req.input ?? {} };
|
|
1982
|
-
}
|
|
1983
|
-
function parseControlCancel(line) {
|
|
1984
|
-
if (line?.type !== "control_cancel_request") return null;
|
|
1985
|
-
return typeof line.request_id === "string" ? line.request_id : null;
|
|
1986
|
-
}
|
|
1987
|
-
function summarizeToolInput(toolName, input) {
|
|
1988
|
-
const i = input && typeof input === "object" ? input : {};
|
|
1989
|
-
const s = (v) => typeof v === "string" && v.trim() ? v : null;
|
|
1990
|
-
let summary = null;
|
|
1991
|
-
switch (toolName) {
|
|
1992
|
-
case "Bash":
|
|
1993
|
-
summary = s(i.command);
|
|
1994
|
-
break;
|
|
1995
|
-
case "WebFetch":
|
|
1996
|
-
summary = s(i.url);
|
|
1997
|
-
break;
|
|
1998
|
-
case "WebSearch":
|
|
1999
|
-
summary = s(i.query);
|
|
2000
|
-
break;
|
|
2001
|
-
case "Read":
|
|
2002
|
-
case "Edit":
|
|
2003
|
-
case "MultiEdit":
|
|
2004
|
-
case "Write":
|
|
2005
|
-
summary = s(i.file_path);
|
|
2006
|
-
break;
|
|
2007
|
-
case "NotebookEdit":
|
|
2008
|
-
summary = s(i.notebook_path);
|
|
2009
|
-
break;
|
|
2010
|
-
case "Glob":
|
|
2011
|
-
case "Grep":
|
|
2012
|
-
summary = s(i.pattern) ? `${i.pattern}${s(i.path) ? ` in ${i.path}` : ""}` : null;
|
|
2013
|
-
break;
|
|
2014
|
-
}
|
|
2015
|
-
if (summary === null) {
|
|
2016
|
-
try {
|
|
2017
|
-
summary = JSON.stringify(input) ?? "";
|
|
2018
|
-
} catch {
|
|
2019
|
-
summary = "";
|
|
2020
|
-
}
|
|
2021
|
-
}
|
|
2022
|
-
return cut(summary, AGENT_PERMISSION_INPUT_SUMMARY_MAX_LENGTH);
|
|
2023
|
-
}
|
|
2024
|
-
function cut(text, max) {
|
|
2025
|
-
return text.length > max ? `${text.slice(0, max - 1)}\u2026` : text;
|
|
2026
|
-
}
|
|
2027
|
-
var PERMISSION_EXPIRED_TURN_ENDED = "The turn ended before anyone answered.";
|
|
2028
|
-
var PERMISSION_EXPIRED_INTERRUPTED = "The turn was interrupted before anyone answered.";
|
|
2029
|
-
var PERMISSION_EXPIRED_STOPPED = "Claude Code stopped before anyone answered.";
|
|
2030
|
-
var PERMISSION_EXPIRED_TIMEOUT = `Nobody answered within ${Math.round(
|
|
2031
|
-
RUNNER_PERMISSION_REQUEST_TIMEOUT_MS / 6e4
|
|
2032
|
-
)} minutes.`;
|
|
2033
|
-
var PERMISSION_EXPIRED_CANCELLED = "Claude Code stopped waiting for an answer.";
|
|
2034
|
-
var PERMISSION_EXPIRED_UNKNOWN = "The runner no longer has this request (it may have restarted), so the answer could not be applied.";
|
|
2035
|
-
var DENIED_MESSAGE = "The person denied permission for this tool call in Discovery Tree.";
|
|
2036
|
-
var SETTLED_KEPT = 200;
|
|
2037
|
-
var PermissionRelay = class {
|
|
2038
|
-
constructor(deps) {
|
|
2039
|
-
this.deps = deps;
|
|
2040
|
-
}
|
|
2041
|
-
pending = /* @__PURE__ */ new Map();
|
|
2042
|
-
byControlId = /* @__PURE__ */ new Map();
|
|
2043
|
-
settled = /* @__PURE__ */ new Map();
|
|
2044
|
-
get pendingCount() {
|
|
2045
|
-
return this.pending.size;
|
|
2046
|
-
}
|
|
2047
|
-
/** Claude Code asks; returns whether it was allowed at once or relayed. */
|
|
2048
|
-
request(req) {
|
|
2049
|
-
if (this.deps.alwaysAllowed().includes(req.toolName) || this.deps.grantedByRule?.(req.toolName, req.input)) {
|
|
2050
|
-
this.deps.respond(req.controlRequestId, { behavior: "allow", updatedInput: req.input });
|
|
2051
|
-
return "auto_allowed";
|
|
2052
|
-
}
|
|
2053
|
-
const id = (this.deps.newId ?? randomUUID)();
|
|
2054
|
-
const requestedAt = (this.deps.now?.() ?? /* @__PURE__ */ new Date()).toISOString();
|
|
2055
|
-
const timer = setTimeout(
|
|
2056
|
-
() => this.expire(id, PERMISSION_EXPIRED_TIMEOUT, true),
|
|
2057
|
-
this.deps.timeoutMs ?? RUNNER_PERMISSION_REQUEST_TIMEOUT_MS
|
|
2058
|
-
);
|
|
2059
|
-
timer.unref?.();
|
|
2060
|
-
const pending = {
|
|
2061
|
-
id,
|
|
2062
|
-
controlRequestId: req.controlRequestId,
|
|
2063
|
-
toolName: req.toolName,
|
|
2064
|
-
input: req.input,
|
|
2065
|
-
inputSummary: summarizeToolInput(req.toolName, req.input),
|
|
2066
|
-
requestedAt,
|
|
2067
|
-
timer
|
|
2068
|
-
};
|
|
2069
|
-
this.pending.set(id, pending);
|
|
2070
|
-
this.byControlId.set(req.controlRequestId, id);
|
|
2071
|
-
const suggestedRule = this.deps.suggestRule?.(req.toolName, req.input) ?? null;
|
|
2072
|
-
this.deps.emit({
|
|
2073
|
-
type: "permission_request",
|
|
2074
|
-
request: {
|
|
2075
|
-
id,
|
|
2076
|
-
toolName: pending.toolName,
|
|
2077
|
-
inputSummary: pending.inputSummary,
|
|
2078
|
-
...suggestedRule ? { suggestedRule } : {},
|
|
2079
|
-
requestedAt,
|
|
2080
|
-
status: "pending"
|
|
2081
|
-
}
|
|
2082
|
-
});
|
|
2083
|
-
return "relayed";
|
|
2084
|
-
}
|
|
2085
|
-
/** A person's decision, from the server. */
|
|
2086
|
-
decide(requestId, decision) {
|
|
2087
|
-
const pending = this.pending.get(requestId);
|
|
2088
|
-
if (!pending) {
|
|
2089
|
-
const settled = this.settled.get(requestId);
|
|
2090
|
-
if (settled === "decided") return "already_applied";
|
|
2091
|
-
if (settled === void 0) {
|
|
2092
|
-
this.settle(requestId, "expired");
|
|
2093
|
-
this.deps.emit({
|
|
2094
|
-
type: "permission_request",
|
|
2095
|
-
request: {
|
|
2096
|
-
id: requestId,
|
|
2097
|
-
toolName: "tool",
|
|
2098
|
-
inputSummary: "",
|
|
2099
|
-
requestedAt: (this.deps.now?.() ?? /* @__PURE__ */ new Date()).toISOString(),
|
|
2100
|
-
status: "expired",
|
|
2101
|
-
expiredReason: PERMISSION_EXPIRED_UNKNOWN
|
|
2102
|
-
}
|
|
2103
|
-
});
|
|
2104
|
-
}
|
|
2105
|
-
return "not_pending";
|
|
2106
|
-
}
|
|
2107
|
-
this.forget(pending);
|
|
2108
|
-
this.settle(requestId, "decided");
|
|
2109
|
-
if (decision.behavior === "allow") {
|
|
2110
|
-
if (decision.alwaysAllowTool && !this.deps.alwaysAllowed().includes(pending.toolName)) {
|
|
2111
|
-
this.deps.rememberAlwaysAllowed(pending.toolName);
|
|
2112
|
-
}
|
|
2113
|
-
const rule = decision.alwaysAllowRule?.trim();
|
|
2114
|
-
if (rule && toolGrantRuleProblem(rule) === null) this.deps.rememberRule?.(rule);
|
|
2115
|
-
this.deps.respond(pending.controlRequestId, {
|
|
2116
|
-
behavior: "allow",
|
|
2117
|
-
updatedInput: pending.input
|
|
2118
|
-
});
|
|
2119
|
-
} else {
|
|
2120
|
-
const message = decision.message?.trim();
|
|
2121
|
-
this.deps.respond(pending.controlRequestId, {
|
|
2122
|
-
behavior: "deny",
|
|
2123
|
-
message: message ? `${DENIED_MESSAGE} Their message: ${cut(message, AGENT_PERMISSION_MESSAGE_MAX_LENGTH)}` : DENIED_MESSAGE
|
|
2124
|
-
});
|
|
2125
|
-
}
|
|
2126
|
-
return "applied";
|
|
2127
|
-
}
|
|
2128
|
-
/** Claude Code withdrew a request (it stopped waiting): expired, nothing to answer. */
|
|
2129
|
-
cancel(controlRequestId) {
|
|
2130
|
-
const id = this.byControlId.get(controlRequestId);
|
|
2131
|
-
if (id) this.expire(id, PERMISSION_EXPIRED_CANCELLED, false);
|
|
2132
|
-
}
|
|
2133
|
-
/** Expire everything still waiting, answering Claude Code with a denial. */
|
|
2134
|
-
expireAll(reason) {
|
|
2135
|
-
for (const id of [...this.pending.keys()]) this.expire(id, reason, true);
|
|
2136
|
-
}
|
|
2137
|
-
expire(id, reason, answerClaude) {
|
|
2138
|
-
const pending = this.pending.get(id);
|
|
2139
|
-
if (!pending) return;
|
|
2140
|
-
this.forget(pending);
|
|
2141
|
-
this.settle(id, "expired");
|
|
2142
|
-
if (answerClaude) {
|
|
2143
|
-
this.deps.respond(pending.controlRequestId, {
|
|
2144
|
-
behavior: "deny",
|
|
2145
|
-
message: `Permission for this tool call was not granted: ${reason}`
|
|
2146
|
-
});
|
|
2147
|
-
}
|
|
2148
|
-
this.deps.emit({
|
|
2149
|
-
type: "permission_request",
|
|
2150
|
-
request: {
|
|
2151
|
-
id,
|
|
2152
|
-
toolName: pending.toolName,
|
|
2153
|
-
inputSummary: pending.inputSummary,
|
|
2154
|
-
requestedAt: pending.requestedAt,
|
|
2155
|
-
status: "expired",
|
|
2156
|
-
expiredReason: reason
|
|
3945
|
+
continue;
|
|
3946
|
+
}
|
|
3947
|
+
} else {
|
|
3948
|
+
this.opts.logger.debug("posting session events failed; will retry", {
|
|
3949
|
+
session: this.opts.sessionId,
|
|
3950
|
+
error: err.message
|
|
3951
|
+
});
|
|
3952
|
+
}
|
|
3953
|
+
await sleep(
|
|
3954
|
+
backoffDelay(attempt++, this.opts.retryBaseMs ?? 1e3),
|
|
3955
|
+
this.stopController.signal
|
|
3956
|
+
);
|
|
3957
|
+
} finally {
|
|
3958
|
+
this.inFlightUpTo = 0;
|
|
3959
|
+
}
|
|
2157
3960
|
}
|
|
2158
|
-
}
|
|
3961
|
+
} finally {
|
|
3962
|
+
this.pumping = false;
|
|
3963
|
+
}
|
|
3964
|
+
if (!this.pending.length || this.closed) this.notifyIdle();
|
|
3965
|
+
else if (!this.stopped) this.schedulePump();
|
|
2159
3966
|
}
|
|
2160
|
-
|
|
2161
|
-
|
|
2162
|
-
this.
|
|
2163
|
-
this.
|
|
3967
|
+
markClosed(reason) {
|
|
3968
|
+
this.opts.logger.info(`session ${this.opts.sessionId}: ${reason}`);
|
|
3969
|
+
this.discard();
|
|
3970
|
+
this.opts.onClosed?.();
|
|
2164
3971
|
}
|
|
2165
|
-
|
|
2166
|
-
this.
|
|
2167
|
-
|
|
2168
|
-
|
|
2169
|
-
}
|
|
3972
|
+
notifyIdle() {
|
|
3973
|
+
const waiters = this.idleWaiters;
|
|
3974
|
+
this.idleWaiters = [];
|
|
3975
|
+
for (const w of waiters) w();
|
|
2170
3976
|
}
|
|
2171
3977
|
};
|
|
3978
|
+
function takeBatch(pending) {
|
|
3979
|
+
const budget = RUNNER_EVENTS_MAX_BODY_BYTES / 2;
|
|
3980
|
+
let bytes = 0;
|
|
3981
|
+
let n = 0;
|
|
3982
|
+
while (n < pending.length && n < RUNNER_EVENTS_MAX_BATCH) {
|
|
3983
|
+
const size = Buffer.byteLength(JSON.stringify(pending[n]));
|
|
3984
|
+
if (n > 0 && bytes + size > budget) break;
|
|
3985
|
+
bytes += size;
|
|
3986
|
+
n++;
|
|
3987
|
+
}
|
|
3988
|
+
return pending.slice(0, n);
|
|
3989
|
+
}
|
|
3990
|
+
|
|
3991
|
+
// src/session.ts
|
|
3992
|
+
import { spawn as spawn4 } from "node:child_process";
|
|
3993
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
3994
|
+
import { basename, dirname as dirname6 } from "node:path";
|
|
3995
|
+
import { createInterface as createInterface2 } from "node:readline";
|
|
2172
3996
|
|
|
2173
3997
|
// src/tool-grants.ts
|
|
2174
|
-
import { dirname as
|
|
3998
|
+
import { dirname as dirname5, join as join10, posix } from "node:path";
|
|
2175
3999
|
var isGrantableDenial = isGrantableToolDenial;
|
|
2176
|
-
var
|
|
4000
|
+
var FILE_TOOLS2 = /* @__PURE__ */ new Set(["Read", "Edit", "MultiEdit", "Write", "NotebookEdit"]);
|
|
2177
4001
|
var EDIT_TOOLS = /* @__PURE__ */ new Set(["Edit", "MultiEdit", "Write", "NotebookEdit"]);
|
|
2178
4002
|
function suggestRules(toolName, input, allowedTools = []) {
|
|
2179
4003
|
const i = input && typeof input === "object" ? input : {};
|
|
@@ -2185,7 +4009,7 @@ function suggestRules(toolName, input, allowedTools = []) {
|
|
|
2185
4009
|
} else if (toolName === "WebFetch") {
|
|
2186
4010
|
const host = hostOf(str(i.url));
|
|
2187
4011
|
if (host) out = same(`WebFetch(domain:${host})`);
|
|
2188
|
-
} else if (
|
|
4012
|
+
} else if (FILE_TOOLS2.has(toolName)) {
|
|
2189
4013
|
const file = str(i.file_path) ?? str(i.notebook_path);
|
|
2190
4014
|
const ruleTool = EDIT_TOOLS.has(toolName) ? "Edit" : "Read";
|
|
2191
4015
|
if (file) {
|
|
@@ -2278,7 +4102,7 @@ function ruleAllows(rule, toolName, input) {
|
|
|
2278
4102
|
if (toolName === "WebFetch" && parsed.spec.startsWith("domain:")) {
|
|
2279
4103
|
return hostOf(typeof i.url === "string" ? i.url : null) === parsed.spec.slice(7).toLowerCase();
|
|
2280
4104
|
}
|
|
2281
|
-
if (
|
|
4105
|
+
if (FILE_TOOLS2.has(toolName)) {
|
|
2282
4106
|
const file = typeof i.file_path === "string" ? i.file_path : typeof i.notebook_path === "string" ? i.notebook_path : "";
|
|
2283
4107
|
return filePatternMatches(parsed.spec, file);
|
|
2284
4108
|
}
|
|
@@ -2313,7 +4137,7 @@ function grantsCover(granted, base, toolName, input) {
|
|
|
2313
4137
|
function askedFor(rules, toolName, input) {
|
|
2314
4138
|
if (rules.length === 0) return false;
|
|
2315
4139
|
if (rules.some((rule) => rule.trim() === toolName)) return true;
|
|
2316
|
-
if (
|
|
4140
|
+
if (FILE_TOOLS2.has(toolName)) {
|
|
2317
4141
|
const family = EDIT_TOOLS.has(toolName) ? "Edit" : toolName;
|
|
2318
4142
|
const relative = rules.some((rule) => {
|
|
2319
4143
|
const parsed = parseRule(rule);
|
|
@@ -2369,7 +4193,7 @@ function filePatternMatches(spec, file) {
|
|
|
2369
4193
|
let pattern = spec.trim();
|
|
2370
4194
|
if (pattern.startsWith("~/")) {
|
|
2371
4195
|
if (!home) return false;
|
|
2372
|
-
pattern = rulePath(
|
|
4196
|
+
pattern = rulePath(join10(home, pattern.slice(2)).replace(/\\/g, "/"));
|
|
2373
4197
|
}
|
|
2374
4198
|
if (!pattern.startsWith("//")) return false;
|
|
2375
4199
|
const path = rulePath(file);
|
|
@@ -2390,7 +4214,7 @@ function shellPatternMatches(spec, command) {
|
|
|
2390
4214
|
return new RegExp(`^${re}${optionalTail ? "(?: .*)?" : ""}$`, "s").test(command);
|
|
2391
4215
|
}
|
|
2392
4216
|
function toolGrantsFile(configFile) {
|
|
2393
|
-
return
|
|
4217
|
+
return join10(dirname5(configFile), "tool-grants.json");
|
|
2394
4218
|
}
|
|
2395
4219
|
var ToolGrantStore = class {
|
|
2396
4220
|
constructor(file) {
|
|
@@ -2440,223 +4264,31 @@ var ToolGrantStore = class {
|
|
|
2440
4264
|
/** Applies the changes a heartbeat answer handed over; each failure is returned, not thrown. */
|
|
2441
4265
|
async apply(changes) {
|
|
2442
4266
|
const problems = [];
|
|
2443
|
-
for (const c of changes) {
|
|
2444
|
-
try {
|
|
2445
|
-
if (c?.op === "add" && c.grant) await this.add(c.grant);
|
|
2446
|
-
else if (c?.op === "revoke" && typeof c.id === "string") await this.revoke(c.id);
|
|
2447
|
-
} catch (err) {
|
|
2448
|
-
problems.push(err.message);
|
|
2449
|
-
}
|
|
2450
|
-
}
|
|
2451
|
-
return problems;
|
|
2452
|
-
}
|
|
2453
|
-
change(fn) {
|
|
2454
|
-
const run = this.chain.then(async () => {
|
|
2455
|
-
const
|
|
2456
|
-
const next = await fn(
|
|
2457
|
-
if (next ===
|
|
2458
|
-
await writeJsonAtomic(this.file, { version: 1, grants: next });
|
|
2459
|
-
this.cache = next;
|
|
2460
|
-
});
|
|
2461
|
-
this.chain = run.catch(() => void 0);
|
|
2462
|
-
return run;
|
|
2463
|
-
}
|
|
2464
|
-
};
|
|
2465
|
-
function isUsableGrant(g) {
|
|
2466
|
-
const x = g;
|
|
2467
|
-
return !!x && typeof x.id === "string" && typeof x.repository === "string" && typeof x.rule === "string" && toolGrantRuleProblem(x.rule) === null;
|
|
2468
|
-
}
|
|
2469
|
-
|
|
2470
|
-
// src/claude-code-rules.ts
|
|
2471
|
-
import { readFile as readFile4, stat as stat3 } from "node:fs/promises";
|
|
2472
|
-
import { homedir as homedir2 } from "node:os";
|
|
2473
|
-
import { dirname as dirname5, isAbsolute as isAbsolute3, join as join8, resolve, sep } from "node:path";
|
|
2474
|
-
var EMPTY = { allow: [], deny: [], ask: [], sources: [] };
|
|
2475
|
-
var RULE_SHAPE2 = /^(?:mcp__[A-Za-z0-9_-]+__\*|[A-Za-z][A-Za-z0-9_.-]*(?:\([\s\S]*\))?)$/;
|
|
2476
|
-
var FILE_TOOLS2 = /* @__PURE__ */ new Set([
|
|
2477
|
-
"Read",
|
|
2478
|
-
"Edit",
|
|
2479
|
-
"Write",
|
|
2480
|
-
"MultiEdit",
|
|
2481
|
-
"NotebookEdit",
|
|
2482
|
-
"Glob",
|
|
2483
|
-
"Grep",
|
|
2484
|
-
"LS"
|
|
2485
|
-
]);
|
|
2486
|
-
function usableRule(raw, kind, committed) {
|
|
2487
|
-
if (typeof raw !== "string") return null;
|
|
2488
|
-
const rule = raw.trim();
|
|
2489
|
-
if (!rule || rule.length > TOOL_GRANT_RULE_MAX_LENGTH) return null;
|
|
2490
|
-
if (/[\u0000-\u001f\u007f]/.test(rule) || !RULE_SHAPE2.test(rule)) return null;
|
|
2491
|
-
const tool = /^([A-Za-z][A-Za-z0-9_.-]*)/.exec(rule)?.[1] ?? "";
|
|
2492
|
-
if (kind === "allow" && FILE_TOOLS2.has(tool)) return null;
|
|
2493
|
-
if (kind === "allow" && committed && toolGrantRuleProblem(rule) !== null) return null;
|
|
2494
|
-
return rule;
|
|
2495
|
-
}
|
|
2496
|
-
function remoteRepositoryKey(url) {
|
|
2497
|
-
const u = url.trim();
|
|
2498
|
-
const ssh = /^(?:ssh:\/\/)?git@github\.com[:/]([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/i.exec(u);
|
|
2499
|
-
if (ssh) return toolGrantRepositoryKey(`https://github.com/${ssh[1]}/${ssh[2]}`);
|
|
2500
|
-
const https = /^(?:https?|git):\/\/(?:[^@/]+@)?github\.com\/([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/i.exec(u);
|
|
2501
|
-
if (https) return toolGrantRepositoryKey(`https://github.com/${https[1]}/${https[2]}`);
|
|
2502
|
-
return null;
|
|
2503
|
-
}
|
|
2504
|
-
async function readText(file) {
|
|
2505
|
-
try {
|
|
2506
|
-
return await readFile4(file, "utf8");
|
|
2507
|
-
} catch {
|
|
2508
|
-
return null;
|
|
2509
|
-
}
|
|
2510
|
-
}
|
|
2511
|
-
async function readJsonFile(file) {
|
|
2512
|
-
const text = await readText(file);
|
|
2513
|
-
if (text === null) return null;
|
|
2514
|
-
try {
|
|
2515
|
-
return JSON.parse(text);
|
|
2516
|
-
} catch {
|
|
2517
|
-
return null;
|
|
2518
|
-
}
|
|
2519
|
-
}
|
|
2520
|
-
async function isDir(path) {
|
|
2521
|
-
try {
|
|
2522
|
-
return (await stat3(path)).isDirectory();
|
|
2523
|
-
} catch {
|
|
2524
|
-
return false;
|
|
2525
|
-
}
|
|
2526
|
-
}
|
|
2527
|
-
async function gitConfigOf(folder) {
|
|
2528
|
-
let dir = folder;
|
|
2529
|
-
for (let i = 0; i < 6; i++) {
|
|
2530
|
-
const dotGit = join8(dir, ".git");
|
|
2531
|
-
if (await isDir(dotGit)) return { config: join8(dotGit, "config"), roots: [dir] };
|
|
2532
|
-
const pointer = await readText(dotGit);
|
|
2533
|
-
const gitdir = pointer && /^gitdir:\s*(.+)\s*$/m.exec(pointer)?.[1];
|
|
2534
|
-
if (gitdir) {
|
|
2535
|
-
const linked = resolve(dir, gitdir);
|
|
2536
|
-
const common = (await readText(join8(linked, "commondir")))?.trim();
|
|
2537
|
-
const commonDir = common ? resolve(linked, common) : linked;
|
|
2538
|
-
return { config: join8(commonDir, "config"), roots: [dir, dirname5(commonDir)] };
|
|
2539
|
-
}
|
|
2540
|
-
const up = dirname5(dir);
|
|
2541
|
-
if (up === dir) break;
|
|
2542
|
-
dir = up;
|
|
2543
|
-
}
|
|
2544
|
-
return null;
|
|
2545
|
-
}
|
|
2546
|
-
function remoteKeys(config) {
|
|
2547
|
-
const keys = /* @__PURE__ */ new Set();
|
|
2548
|
-
let inRemote = false;
|
|
2549
|
-
for (const line of config.split(/\r?\n/)) {
|
|
2550
|
-
const section = /^\s*\[([^\]]*)\]/.exec(line);
|
|
2551
|
-
if (section) {
|
|
2552
|
-
inRemote = /^remote\s+"/i.test(section[1].trim());
|
|
2553
|
-
continue;
|
|
2554
|
-
}
|
|
2555
|
-
if (!inRemote) continue;
|
|
2556
|
-
const url = /^\s*url\s*=\s*(.+?)\s*$/i.exec(line);
|
|
2557
|
-
const key = url ? remoteRepositoryKey(url[1]) : null;
|
|
2558
|
-
if (key) keys.add(key);
|
|
2559
|
-
}
|
|
2560
|
-
return keys;
|
|
2561
|
-
}
|
|
2562
|
-
function rulesIn(settings, kind, committed) {
|
|
2563
|
-
const perms = settings?.permissions;
|
|
2564
|
-
const list = perms?.[kind];
|
|
2565
|
-
if (!Array.isArray(list)) return [];
|
|
2566
|
-
return list.map((r) => usableRule(r, kind, committed)).filter((r) => r !== null);
|
|
2567
|
-
}
|
|
2568
|
-
var ClaudeCodeRules = class {
|
|
2569
|
-
claudeJson;
|
|
2570
|
-
exclude;
|
|
2571
|
-
cacheMs;
|
|
2572
|
-
cache = /* @__PURE__ */ new Map();
|
|
2573
|
-
constructor(opts = {}) {
|
|
2574
|
-
this.claudeJson = opts.claudeJson ?? (process.env.CLAUDE_CONFIG_DIR ? join8(process.env.CLAUDE_CONFIG_DIR, ".claude.json") : join8(homedir2(), ".claude.json"));
|
|
2575
|
-
this.exclude = (opts.exclude ?? []).map((p) => resolve(p));
|
|
2576
|
-
this.cacheMs = opts.cacheMs ?? 3e4;
|
|
2577
|
-
}
|
|
2578
|
-
/** The rules for a repository URL; none for a session without a GitHub repository. */
|
|
2579
|
-
rulesFor(repositoryUrl) {
|
|
2580
|
-
const key = toolGrantRepositoryKey(repositoryUrl);
|
|
2581
|
-
if (!key) return Promise.resolve(EMPTY);
|
|
2582
|
-
const hit = this.cache.get(key);
|
|
2583
|
-
if (hit && Date.now() - hit.at < this.cacheMs) return hit.rules;
|
|
2584
|
-
const rules = this.read(key).catch(() => EMPTY);
|
|
2585
|
-
this.cache.set(key, { at: Date.now(), rules });
|
|
2586
|
-
return rules;
|
|
2587
|
-
}
|
|
2588
|
-
excluded(folder) {
|
|
2589
|
-
const f = resolve(folder);
|
|
2590
|
-
return this.exclude.some((ex) => f === ex || f.startsWith(ex + sep));
|
|
2591
|
-
}
|
|
2592
|
-
async read(key) {
|
|
2593
|
-
const global = await readJsonFile(this.claudeJson);
|
|
2594
|
-
const projects = global?.projects;
|
|
2595
|
-
if (!projects || typeof projects !== "object") return EMPTY;
|
|
2596
|
-
const allow = /* @__PURE__ */ new Set();
|
|
2597
|
-
const deny = /* @__PURE__ */ new Set();
|
|
2598
|
-
const ask = /* @__PURE__ */ new Set();
|
|
2599
|
-
const sources = [];
|
|
2600
|
-
const checkouts = [];
|
|
2601
|
-
for (const [folder, entry] of Object.entries(projects)) {
|
|
2602
|
-
if (!entry || entry.hasTrustDialogAccepted !== true) continue;
|
|
2603
|
-
if (!isAbsolute3(folder) || this.excluded(folder)) continue;
|
|
2604
|
-
const git2 = await gitConfigOf(folder);
|
|
2605
|
-
const text = git2 ? await readText(git2.config) : null;
|
|
2606
|
-
if (!git2 || !text || !remoteKeys(text).has(key)) continue;
|
|
2607
|
-
const roots = [...new Set([folder, ...git2.roots].map((d) => resolve(d)))];
|
|
2608
|
-
const legacy = Array.isArray(entry.allowedTools) ? entry.allowedTools : [];
|
|
2609
|
-
checkouts.push({ folder, roots, legacy });
|
|
2610
|
-
}
|
|
2611
|
-
for (const { folder, roots, legacy } of checkouts) {
|
|
2612
|
-
const found = [];
|
|
2613
|
-
const denied = [];
|
|
2614
|
-
const asked = [];
|
|
2615
|
-
for (const dir of roots) {
|
|
2616
|
-
const local = await readJsonFile(join8(dir, ".claude", "settings.local.json"));
|
|
2617
|
-
const shared = await readJsonFile(join8(dir, ".claude", "settings.json"));
|
|
2618
|
-
found.push(...rulesIn(local, "allow", false), ...rulesIn(shared, "allow", true));
|
|
2619
|
-
denied.push(...rulesIn(local, "deny", false), ...rulesIn(shared, "deny", false));
|
|
2620
|
-
asked.push(...rulesIn(local, "ask", false), ...rulesIn(shared, "ask", false));
|
|
2621
|
-
}
|
|
2622
|
-
found.push(
|
|
2623
|
-
...legacy.map((r) => usableRule(r, "allow", false)).filter((r) => r !== null)
|
|
2624
|
-
);
|
|
2625
|
-
const kept = found;
|
|
2626
|
-
if (kept.length || denied.length || asked.length) sources.push(folder);
|
|
2627
|
-
for (const r of kept) allow.add(r);
|
|
2628
|
-
for (const r of denied) deny.add(r);
|
|
2629
|
-
for (const r of asked) ask.add(r);
|
|
2630
|
-
}
|
|
2631
|
-
return {
|
|
2632
|
-
allow: [...allow].filter((r) => !deny.has(r) && !ask.has(r)),
|
|
2633
|
-
deny: [...deny],
|
|
2634
|
-
ask: [...ask].filter((r) => !deny.has(r)),
|
|
2635
|
-
sources
|
|
2636
|
-
};
|
|
2637
|
-
}
|
|
2638
|
-
};
|
|
2639
|
-
function ruleHead(rule) {
|
|
2640
|
-
const m = /^([A-Za-z][A-Za-z0-9_.-]*(?:__\*)?)(?:\(([\s\S]*)\))?$/.exec(rule.trim());
|
|
2641
|
-
if (!m) return null;
|
|
2642
|
-
const spec = m[2];
|
|
2643
|
-
if (spec === void 0) return { tool: m[1], head: null };
|
|
2644
|
-
return { tool: m[1], head: spec.replace(/:\*$/, " *").split("*")[0] };
|
|
2645
|
-
}
|
|
2646
|
-
function sameTool(a, b) {
|
|
2647
|
-
if (a === b) return true;
|
|
2648
|
-
const wild = (w, t) => w.endsWith("__*") && t.startsWith(w.slice(0, -1));
|
|
2649
|
-
return wild(a, b) || wild(b, a);
|
|
2650
|
-
}
|
|
2651
|
-
function overlapsAsk(allowRule, askRules) {
|
|
2652
|
-
const a = ruleHead(allowRule);
|
|
2653
|
-
if (!a) return false;
|
|
2654
|
-
return askRules.some((rule) => {
|
|
2655
|
-
const q = ruleHead(rule);
|
|
2656
|
-
if (!q || !sameTool(a.tool, q.tool)) return false;
|
|
2657
|
-
if (a.head === null || q.head === null) return true;
|
|
2658
|
-
return a.head.startsWith(q.head) || q.head.startsWith(a.head);
|
|
2659
|
-
});
|
|
4267
|
+
for (const c of changes) {
|
|
4268
|
+
try {
|
|
4269
|
+
if (c?.op === "add" && c.grant) await this.add(c.grant);
|
|
4270
|
+
else if (c?.op === "revoke" && typeof c.id === "string") await this.revoke(c.id);
|
|
4271
|
+
} catch (err) {
|
|
4272
|
+
problems.push(err.message);
|
|
4273
|
+
}
|
|
4274
|
+
}
|
|
4275
|
+
return problems;
|
|
4276
|
+
}
|
|
4277
|
+
change(fn) {
|
|
4278
|
+
const run = this.chain.then(async () => {
|
|
4279
|
+
const current2 = await this.list();
|
|
4280
|
+
const next = await fn(current2);
|
|
4281
|
+
if (next === current2) return;
|
|
4282
|
+
await writeJsonAtomic(this.file, { version: 1, grants: next });
|
|
4283
|
+
this.cache = next;
|
|
4284
|
+
});
|
|
4285
|
+
this.chain = run.catch(() => void 0);
|
|
4286
|
+
return run;
|
|
4287
|
+
}
|
|
4288
|
+
};
|
|
4289
|
+
function isUsableGrant(g) {
|
|
4290
|
+
const x = g;
|
|
4291
|
+
return !!x && typeof x.id === "string" && typeof x.repository === "string" && typeof x.rule === "string" && toolGrantRuleProblem(x.rule) === null;
|
|
2660
4292
|
}
|
|
2661
4293
|
|
|
2662
4294
|
// src/pull-request.ts
|
|
@@ -2745,275 +4377,70 @@ function ghError(command, res) {
|
|
|
2745
4377
|
return "the GitHub CLI is not signed in; run `gh auth login` on this computer";
|
|
2746
4378
|
}
|
|
2747
4379
|
return scrubSecrets(`gh ${command} failed${detail ? `: ${detail}` : ""}`).slice(0, 300);
|
|
2748
|
-
}
|
|
2749
|
-
|
|
2750
|
-
// src/session-store.ts
|
|
2751
|
-
import { mkdir as
|
|
2752
|
-
import { join as
|
|
2753
|
-
var HANDLED_COMMAND_IDS_KEPT = 100;
|
|
2754
|
-
var
|
|
2755
|
-
|
|
2756
|
-
|
|
2757
|
-
|
|
2758
|
-
|
|
2759
|
-
|
|
2760
|
-
|
|
2761
|
-
|
|
2762
|
-
|
|
2763
|
-
|
|
2764
|
-
|
|
2765
|
-
|
|
2766
|
-
|
|
2767
|
-
|
|
2768
|
-
|
|
2769
|
-
|
|
2770
|
-
|
|
2771
|
-
|
|
2772
|
-
|
|
2773
|
-
|
|
2774
|
-
|
|
2775
|
-
|
|
2776
|
-
|
|
2777
|
-
|
|
2778
|
-
|
|
2779
|
-
|
|
2780
|
-
|
|
2781
|
-
|
|
2782
|
-
|
|
2783
|
-
|
|
2784
|
-
|
|
2785
|
-
|
|
2786
|
-
};
|
|
2787
|
-
|
|
2788
|
-
|
|
2789
|
-
|
|
2790
|
-
|
|
2791
|
-
|
|
2792
|
-
|
|
2793
|
-
// src/stream-mapper.ts
|
|
2794
|
-
function capText(text, max = RUNNER_EVENT_TEXT_MAX_LENGTH) {
|
|
2795
|
-
if (text.length <= max) return { text, truncated: false };
|
|
2796
|
-
const marker = "\n\u2026 [truncated by dt-runner]";
|
|
2797
|
-
return { text: text.slice(0, max - marker.length) + marker, truncated: true };
|
|
2798
|
-
}
|
|
2799
|
-
var ClaudeStreamMapper = class {
|
|
2800
|
-
/** Running offset of each live text block, by providerEventId. */
|
|
2801
|
-
deltaOffsets = /* @__PURE__ */ new Map();
|
|
2802
|
-
/** Stream block index → providerEventId for text blocks of the message streaming now. */
|
|
2803
|
-
streamTextKeys = /* @__PURE__ */ new Map();
|
|
2804
|
-
streamMessageId = null;
|
|
2805
|
-
streamTextCount = 0;
|
|
2806
|
-
/** Text blocks already seen in completed `assistant` lines, per message id. */
|
|
2807
|
-
completedTextCount = /* @__PURE__ */ new Map();
|
|
2808
|
-
/** Tool calls by id, for the name/input a result line does not repeat. */
|
|
2809
|
-
calls = /* @__PURE__ */ new Map();
|
|
2810
|
-
lastAssistantText = null;
|
|
2811
|
-
running = false;
|
|
2812
|
-
/** A new turn is starting (we wrote a user message); the next activity is not news. */
|
|
2813
|
-
markRunning() {
|
|
2814
|
-
this.running = true;
|
|
2815
|
-
}
|
|
2816
|
-
map(line) {
|
|
2817
|
-
const out = { events: [] };
|
|
2818
|
-
if (line.parent_tool_use_id) return out;
|
|
2819
|
-
switch (line.type) {
|
|
2820
|
-
case "system":
|
|
2821
|
-
if (line.subtype === "init" && typeof line.session_id === "string") {
|
|
2822
|
-
out.claudeSessionId = line.session_id;
|
|
2823
|
-
this.ensureRunning(out);
|
|
2824
|
-
}
|
|
2825
|
-
break;
|
|
2826
|
-
case "stream_event":
|
|
2827
|
-
this.mapStreamEvent(line, out);
|
|
2828
|
-
break;
|
|
2829
|
-
case "assistant":
|
|
2830
|
-
this.mapAssistant(line, out);
|
|
2831
|
-
break;
|
|
2832
|
-
case "user":
|
|
2833
|
-
this.mapUser(line, out);
|
|
2834
|
-
break;
|
|
2835
|
-
case "result": {
|
|
2836
|
-
const resultText = typeof line.result === "string" && line.result ? line.result : null;
|
|
2837
|
-
out.turnEnd = {
|
|
2838
|
-
text: resultText ?? this.lastAssistantText,
|
|
2839
|
-
isError: line.is_error === true || (line.subtype ?? "success") !== "success",
|
|
2840
|
-
subtype: typeof line.subtype === "string" ? line.subtype : null
|
|
2841
|
-
};
|
|
2842
|
-
const denials = Array.isArray(line.permission_denials) ? line.permission_denials.filter((d) => d && typeof d.tool_name === "string").map((d) => ({
|
|
2843
|
-
callId: typeof d.tool_use_id === "string" ? d.tool_use_id : null,
|
|
2844
|
-
name: d.tool_name,
|
|
2845
|
-
input: d.tool_input ?? {}
|
|
2846
|
-
})) : [];
|
|
2847
|
-
if (denials.length) out.turnEnd.permissionDenials = denials;
|
|
2848
|
-
this.endTurn();
|
|
2849
|
-
break;
|
|
2850
|
-
}
|
|
2851
|
-
case "control_response": {
|
|
2852
|
-
const res = line.response ?? {};
|
|
2853
|
-
if (typeof res.request_id === "string") {
|
|
2854
|
-
out.controlResponse = { requestId: res.request_id, ok: res.subtype === "success" };
|
|
2855
|
-
}
|
|
2856
|
-
break;
|
|
2857
|
-
}
|
|
2858
|
-
}
|
|
2859
|
-
return out;
|
|
2860
|
-
}
|
|
2861
|
-
ensureRunning(out) {
|
|
2862
|
-
if (!this.running) {
|
|
2863
|
-
this.running = true;
|
|
2864
|
-
out.turnStarted = true;
|
|
2865
|
-
out.events.push({ type: "status", status: "running" });
|
|
2866
|
-
}
|
|
2867
|
-
}
|
|
2868
|
-
mapStreamEvent(line, out) {
|
|
2869
|
-
const ev = line.event ?? {};
|
|
2870
|
-
switch (ev.type) {
|
|
2871
|
-
case "message_start": {
|
|
2872
|
-
this.ensureRunning(out);
|
|
2873
|
-
const id = ev.message?.id ?? line.api_message_id ?? null;
|
|
2874
|
-
this.beginStreamMessage(typeof id === "string" ? id : null);
|
|
2875
|
-
break;
|
|
2876
|
-
}
|
|
2877
|
-
case "content_block_start": {
|
|
2878
|
-
const id = this.streamMessageIdFor(line);
|
|
2879
|
-
if (ev.content_block?.type === "text" && id && typeof ev.index === "number") {
|
|
2880
|
-
const key = textKey(id, this.streamTextCount++);
|
|
2881
|
-
this.streamTextKeys.set(ev.index, key);
|
|
2882
|
-
const initial = typeof ev.content_block.text === "string" ? ev.content_block.text : "";
|
|
2883
|
-
this.deltaOffsets.set(key, 0);
|
|
2884
|
-
if (initial) this.pushDelta(out, key, initial);
|
|
2885
|
-
}
|
|
2886
|
-
break;
|
|
2887
|
-
}
|
|
2888
|
-
case "content_block_delta": {
|
|
2889
|
-
if (ev.delta?.type !== "text_delta" || typeof ev.delta.text !== "string") break;
|
|
2890
|
-
if (!ev.delta.text) break;
|
|
2891
|
-
const key = this.streamTextKeys.get(ev.index);
|
|
2892
|
-
if (key) this.pushDelta(out, key, ev.delta.text);
|
|
2893
|
-
break;
|
|
2894
|
-
}
|
|
2895
|
-
}
|
|
2896
|
-
}
|
|
2897
|
-
streamMessageIdFor(line) {
|
|
2898
|
-
const id = typeof line.api_message_id === "string" ? line.api_message_id : null;
|
|
2899
|
-
if (id && id !== this.streamMessageId) this.beginStreamMessage(id);
|
|
2900
|
-
return this.streamMessageId;
|
|
2901
|
-
}
|
|
2902
|
-
beginStreamMessage(id) {
|
|
2903
|
-
if (id === this.streamMessageId) return;
|
|
2904
|
-
this.streamMessageId = id;
|
|
2905
|
-
this.streamTextKeys.clear();
|
|
2906
|
-
this.streamTextCount = 0;
|
|
2907
|
-
}
|
|
2908
|
-
pushDelta(out, key, text) {
|
|
2909
|
-
const offset = this.deltaOffsets.get(key) ?? 0;
|
|
2910
|
-
this.deltaOffsets.set(key, offset + text.length);
|
|
2911
|
-
out.events.push({ type: "assistant_delta", providerEventId: key, text, offset });
|
|
2912
|
-
}
|
|
2913
|
-
mapAssistant(line, out) {
|
|
2914
|
-
const msg = line.message ?? {};
|
|
2915
|
-
const id = typeof msg.id === "string" ? msg.id : `msg_${line.uuid ?? Date.now()}`;
|
|
2916
|
-
const content = Array.isArray(msg.content) ? msg.content : [];
|
|
2917
|
-
this.ensureRunning(out);
|
|
2918
|
-
for (const block of content) {
|
|
2919
|
-
switch (block?.type) {
|
|
2920
|
-
case "text": {
|
|
2921
|
-
const n = this.completedTextCount.get(id) ?? 0;
|
|
2922
|
-
this.completedTextCount.set(id, n + 1);
|
|
2923
|
-
const text = typeof block.text === "string" ? block.text : "";
|
|
2924
|
-
if (!text.trim()) break;
|
|
2925
|
-
const key = textKey(id, n);
|
|
2926
|
-
this.deltaOffsets.delete(key);
|
|
2927
|
-
this.lastAssistantText = text;
|
|
2928
|
-
out.events.push({
|
|
2929
|
-
type: "assistant_message",
|
|
2930
|
-
providerEventId: key,
|
|
2931
|
-
text: capText(text).text
|
|
2932
|
-
});
|
|
2933
|
-
break;
|
|
2934
|
-
}
|
|
2935
|
-
case "thinking":
|
|
2936
|
-
case "redacted_thinking": {
|
|
2937
|
-
const text = typeof block.thinking === "string" && block.thinking.trim() ? block.thinking : null;
|
|
2938
|
-
out.events.push({
|
|
2939
|
-
type: "thinking",
|
|
2940
|
-
providerEventId: `${id}:thinking:${this.thinkingIndex(id)}`,
|
|
2941
|
-
text: text === null ? null : capText(text).text
|
|
2942
|
-
});
|
|
2943
|
-
break;
|
|
2944
|
-
}
|
|
2945
|
-
case "tool_use":
|
|
2946
|
-
case "server_tool_use":
|
|
2947
|
-
case "mcp_tool_use": {
|
|
2948
|
-
if (typeof block.id !== "string") break;
|
|
2949
|
-
const name = block.type === "mcp_tool_use" && block.server_name ? `${block.server_name}.${block.name}` : String(block.name ?? "tool");
|
|
2950
|
-
this.calls.set(block.id, { name, input: block.input });
|
|
2951
|
-
out.events.push({
|
|
2952
|
-
type: "tool_call",
|
|
2953
|
-
providerEventId: block.id,
|
|
2954
|
-
tool: { callId: block.id, name, status: "running", input: block.input }
|
|
2955
|
-
});
|
|
2956
|
-
break;
|
|
2957
|
-
}
|
|
2958
|
-
}
|
|
2959
|
-
}
|
|
2960
|
-
}
|
|
2961
|
-
thinkingCounts = /* @__PURE__ */ new Map();
|
|
2962
|
-
thinkingIndex(id) {
|
|
2963
|
-
const n = this.thinkingCounts.get(id) ?? 0;
|
|
2964
|
-
this.thinkingCounts.set(id, n + 1);
|
|
2965
|
-
return n;
|
|
2966
|
-
}
|
|
2967
|
-
mapUser(line, out) {
|
|
2968
|
-
const content = line.message?.content;
|
|
2969
|
-
if (!Array.isArray(content)) return;
|
|
2970
|
-
for (const block of content) {
|
|
2971
|
-
if (block?.type !== "tool_result" || typeof block.tool_use_id !== "string") continue;
|
|
2972
|
-
const known = this.calls.get(block.tool_use_id);
|
|
2973
|
-
const full = toolResultText(block.content);
|
|
2974
|
-
const { text, truncated } = capText(full);
|
|
2975
|
-
if (block.is_error) {
|
|
2976
|
-
(out.failedTools ??= []).push({
|
|
2977
|
-
callId: block.tool_use_id,
|
|
2978
|
-
name: known?.name ?? "tool",
|
|
2979
|
-
input: known?.input ?? {},
|
|
2980
|
-
text: full
|
|
2981
|
-
});
|
|
2982
|
-
}
|
|
2983
|
-
const tool = {
|
|
2984
|
-
callId: block.tool_use_id,
|
|
2985
|
-
name: known?.name ?? "tool",
|
|
2986
|
-
status: block.is_error ? "failed" : "completed",
|
|
2987
|
-
...known ? { input: known.input } : {},
|
|
2988
|
-
output: text,
|
|
2989
|
-
...truncated ? { truncated: true } : {}
|
|
2990
|
-
};
|
|
2991
|
-
out.events.push({ type: "tool_call", providerEventId: block.tool_use_id, tool });
|
|
4380
|
+
}
|
|
4381
|
+
|
|
4382
|
+
// src/session-store.ts
|
|
4383
|
+
import { mkdir as mkdir6, readdir as readdir2, rm as rm5 } from "node:fs/promises";
|
|
4384
|
+
import { join as join11 } from "node:path";
|
|
4385
|
+
var HANDLED_COMMAND_IDS_KEPT = 100;
|
|
4386
|
+
var pendingWrites = /* @__PURE__ */ new Map();
|
|
4387
|
+
var SessionStore = class {
|
|
4388
|
+
constructor(stateDir) {
|
|
4389
|
+
this.stateDir = stateDir;
|
|
4390
|
+
}
|
|
4391
|
+
dir(sessionId) {
|
|
4392
|
+
return join11(this.stateDir, "sessions", sessionId);
|
|
4393
|
+
}
|
|
4394
|
+
outboxFile(sessionId) {
|
|
4395
|
+
return join11(this.dir(sessionId), "outbox.json");
|
|
4396
|
+
}
|
|
4397
|
+
/**
|
|
4398
|
+
* Writes the record as it is now. A session's saves land in the order they were made:
|
|
4399
|
+
* two in flight at once (a turn's start and its quick result) could otherwise rename in
|
|
4400
|
+
* either order and leave the older state on disk, such as a turn still active, which a
|
|
4401
|
+
* restarted runner would then report as cut short.
|
|
4402
|
+
*/
|
|
4403
|
+
async save(record) {
|
|
4404
|
+
record.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
4405
|
+
const file = join11(this.dir(record.sessionId), "session.json");
|
|
4406
|
+
const snapshot = JSON.parse(JSON.stringify(record));
|
|
4407
|
+
const previous = pendingWrites.get(file) ?? Promise.resolve();
|
|
4408
|
+
const write = previous.then(() => writeJsonAtomic(file, snapshot));
|
|
4409
|
+
const settled = write.catch(() => void 0);
|
|
4410
|
+
pendingWrites.set(file, settled);
|
|
4411
|
+
void settled.then(() => {
|
|
4412
|
+
if (pendingWrites.get(file) === settled) pendingWrites.delete(file);
|
|
4413
|
+
});
|
|
4414
|
+
await write;
|
|
4415
|
+
}
|
|
4416
|
+
async list() {
|
|
4417
|
+
const root = join11(this.stateDir, "sessions");
|
|
4418
|
+
await mkdir6(root, { recursive: true });
|
|
4419
|
+
const out = [];
|
|
4420
|
+
for (const entry of await readdir2(root, { withFileTypes: true })) {
|
|
4421
|
+
if (!entry.isDirectory()) continue;
|
|
4422
|
+
const rec = await readJson(join11(root, entry.name, "session.json"));
|
|
4423
|
+
if (rec?.sessionId === entry.name) out.push(upgradeRecord(rec));
|
|
2992
4424
|
}
|
|
4425
|
+
return out;
|
|
2993
4426
|
}
|
|
2994
|
-
|
|
2995
|
-
this.
|
|
2996
|
-
this.
|
|
2997
|
-
|
|
2998
|
-
|
|
2999
|
-
|
|
3000
|
-
this.
|
|
3001
|
-
this.completedTextCount.clear();
|
|
3002
|
-
this.thinkingCounts.clear();
|
|
3003
|
-
if (this.calls.size > 500) this.calls.clear();
|
|
4427
|
+
async remove(sessionId) {
|
|
4428
|
+
await pendingWrites.get(join11(this.dir(sessionId), "session.json"));
|
|
4429
|
+
await rm5(this.dir(sessionId), { recursive: true, force: true });
|
|
4430
|
+
}
|
|
4431
|
+
/** Scratch working directory for a session without a repository. */
|
|
4432
|
+
scratchDir(sessionId) {
|
|
4433
|
+
return join11(this.stateDir, "scratch", sessionId);
|
|
3004
4434
|
}
|
|
3005
4435
|
};
|
|
3006
|
-
function
|
|
3007
|
-
|
|
4436
|
+
function upgradeRecord(stored) {
|
|
4437
|
+
const { claudeSessionId, ...rest } = stored;
|
|
4438
|
+
return { ...rest, conversationId: stored.conversationId ?? claudeSessionId ?? null };
|
|
3008
4439
|
}
|
|
3009
|
-
function
|
|
3010
|
-
if (
|
|
3011
|
-
|
|
3012
|
-
|
|
3013
|
-
if (b?.type === "text" && typeof b.text === "string") return b.text;
|
|
3014
|
-
if (b?.type === "image") return "[image]";
|
|
3015
|
-
return "";
|
|
3016
|
-
}).filter(Boolean).join("\n");
|
|
4440
|
+
function assertSafeSessionId(id) {
|
|
4441
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/.test(id) || id.includes("..")) {
|
|
4442
|
+
throw new Error(`Session id "${id}" is not usable as a directory name.`);
|
|
4443
|
+
}
|
|
3017
4444
|
}
|
|
3018
4445
|
|
|
3019
4446
|
// src/session.ts
|
|
@@ -3022,6 +4449,8 @@ var AgentSession = class {
|
|
|
3022
4449
|
constructor(record, deps) {
|
|
3023
4450
|
this.record = record;
|
|
3024
4451
|
this.deps = deps;
|
|
4452
|
+
this.driver = deps.driver;
|
|
4453
|
+
this.mapper = deps.driver.createMapper();
|
|
3025
4454
|
this.permissions = new PermissionRelay({
|
|
3026
4455
|
respond: (controlRequestId, response) => this.answerPermission(controlRequestId, response),
|
|
3027
4456
|
emit: (event) => this.emit(event),
|
|
@@ -3054,7 +4483,15 @@ var AgentSession = class {
|
|
|
3054
4483
|
});
|
|
3055
4484
|
}
|
|
3056
4485
|
child = null;
|
|
3057
|
-
|
|
4486
|
+
driver;
|
|
4487
|
+
mapper;
|
|
4488
|
+
/** per_turn agents: messages sent mid-turn, sent together as the next turn. */
|
|
4489
|
+
queuedTurns = [];
|
|
4490
|
+
/**
|
|
4491
|
+
* per_turn agents: a turn's process is being started. Claimed before the first await, so a
|
|
4492
|
+
* message arriving meanwhile is queued rather than starting a second process.
|
|
4493
|
+
*/
|
|
4494
|
+
startingTurn = false;
|
|
3058
4495
|
/** stdout lines are handled one at a time, in order, including the async turn end. */
|
|
3059
4496
|
lineChain = Promise.resolve();
|
|
3060
4497
|
stopping = null;
|
|
@@ -3063,7 +4500,7 @@ var AgentSession = class {
|
|
|
3063
4500
|
controlSeq = 0;
|
|
3064
4501
|
stderrTail = "";
|
|
3065
4502
|
sawResultSinceSpawn = false;
|
|
3066
|
-
/** The process was started
|
|
4503
|
+
/** The process was started to resume, and has not yet said it has the conversation. */
|
|
3067
4504
|
spawnedWithResume = false;
|
|
3068
4505
|
sawInitSinceSpawn = false;
|
|
3069
4506
|
/** The message that began the current turn, as the person wrote it (before any preface). */
|
|
@@ -3082,6 +4519,8 @@ var AgentSession = class {
|
|
|
3082
4519
|
exitWaiters = [];
|
|
3083
4520
|
/** Settles once the current process has exited and what it left in its tree is gone. */
|
|
3084
4521
|
treeReaped = Promise.resolve();
|
|
4522
|
+
/** The current process's tree, for the census taken before it is stopped. */
|
|
4523
|
+
tree = null;
|
|
3085
4524
|
/** How long what is left in the group gets after SIGTERM: a stop's grace, or the default. */
|
|
3086
4525
|
reapGraceMs;
|
|
3087
4526
|
lastActivity = Date.now();
|
|
@@ -3150,7 +4589,7 @@ var AgentSession = class {
|
|
|
3150
4589
|
outcome = `${saved} now: the agent may use it in this turn.`;
|
|
3151
4590
|
} else {
|
|
3152
4591
|
this.restartAfterTurn = true;
|
|
3153
|
-
outcome = `${saved}.
|
|
4592
|
+
outcome = `${saved}. ${this.driver.displayName} cannot change its permissions in the middle of a turn, so it takes effect when this turn ends.`;
|
|
3154
4593
|
}
|
|
3155
4594
|
this.deps.logger.info(`session ${this.sessionId}: granted ${rule} (${scope})`);
|
|
3156
4595
|
const denial = this.denials.get(denialId);
|
|
@@ -3193,7 +4632,7 @@ var AgentSession = class {
|
|
|
3193
4632
|
else this.seenFailedCalls.add(f.callId);
|
|
3194
4633
|
}
|
|
3195
4634
|
}
|
|
3196
|
-
/** Restarts
|
|
4635
|
+
/** Restarts the agent with the rules granted mid-turn, then sends what waited for it. */
|
|
3197
4636
|
async restartWithGrants() {
|
|
3198
4637
|
const texts = this.deferredMessages.splice(0);
|
|
3199
4638
|
try {
|
|
@@ -3203,7 +4642,7 @@ var AgentSession = class {
|
|
|
3203
4642
|
this.emit(
|
|
3204
4643
|
{
|
|
3205
4644
|
type: "error",
|
|
3206
|
-
message:
|
|
4645
|
+
message: `${this.driver.displayName} could not be started again with the permission you granted: ${err.message}`,
|
|
3207
4646
|
retryable: true
|
|
3208
4647
|
},
|
|
3209
4648
|
{ type: "result", status: "failed", text: null }
|
|
@@ -3224,24 +4663,28 @@ var AgentSession = class {
|
|
|
3224
4663
|
}
|
|
3225
4664
|
return outcome;
|
|
3226
4665
|
}
|
|
3227
|
-
/**
|
|
4666
|
+
/** The answer to a permission request; dropped when the process is already gone. */
|
|
3228
4667
|
answerPermission(controlRequestId, response) {
|
|
4668
|
+
const control = this.driver.control;
|
|
4669
|
+
if (!control) return;
|
|
3229
4670
|
try {
|
|
3230
|
-
this.write(
|
|
3231
|
-
type: "control_response",
|
|
3232
|
-
response: { subtype: "success", request_id: controlRequestId, response }
|
|
3233
|
-
});
|
|
4671
|
+
this.write(control.permissionResponse(controlRequestId, response));
|
|
3234
4672
|
} catch {
|
|
3235
4673
|
}
|
|
3236
4674
|
}
|
|
3237
4675
|
/**
|
|
3238
|
-
* A control
|
|
3239
|
-
*
|
|
3240
|
-
*
|
|
4676
|
+
* A control line from the agent: a permission prompt is relayed (or, for a session not set
|
|
4677
|
+
* up to relay, denied, which is what `--permission-prompts none` would have done), a
|
|
4678
|
+
* cancelled one is withdrawn. Any other request is answered as unsupported, so the agent
|
|
4679
|
+
* never waits on it.
|
|
3241
4680
|
*/
|
|
3242
|
-
async
|
|
3243
|
-
|
|
3244
|
-
|
|
4681
|
+
async handleControlLine(control, line) {
|
|
4682
|
+
if (line.kind === "cancel") {
|
|
4683
|
+
this.permissions.cancel(line.controlRequestId);
|
|
4684
|
+
return;
|
|
4685
|
+
}
|
|
4686
|
+
if (line.kind === "permission") {
|
|
4687
|
+
const ask = line.ask;
|
|
3245
4688
|
if (!this.record.relayPermissionRequests) {
|
|
3246
4689
|
this.answerPermission(ask.controlRequestId, {
|
|
3247
4690
|
behavior: "deny",
|
|
@@ -3253,21 +4696,14 @@ var AgentSession = class {
|
|
|
3253
4696
|
this.inheritedNow = await this.readInheritedRules();
|
|
3254
4697
|
if (this.permissions.request(ask) === "relayed") {
|
|
3255
4698
|
this.deps.logger.info(
|
|
3256
|
-
`session ${this.sessionId}:
|
|
4699
|
+
`session ${this.sessionId}: ${this.driver.displayName} asks permission for ${ask.toolName}; waiting for an answer in Discovery Tree`
|
|
3257
4700
|
);
|
|
3258
4701
|
}
|
|
3259
4702
|
return;
|
|
3260
4703
|
}
|
|
3261
|
-
if (
|
|
4704
|
+
if (line.requestId !== null) {
|
|
3262
4705
|
try {
|
|
3263
|
-
this.write(
|
|
3264
|
-
type: "control_response",
|
|
3265
|
-
response: {
|
|
3266
|
-
subtype: "error",
|
|
3267
|
-
request_id: line.request_id,
|
|
3268
|
-
error: "dt-runner does not handle this control request."
|
|
3269
|
-
}
|
|
3270
|
-
});
|
|
4706
|
+
this.write(control.unsupportedResponse(line.requestId));
|
|
3271
4707
|
} catch {
|
|
3272
4708
|
}
|
|
3273
4709
|
}
|
|
@@ -3297,7 +4733,8 @@ var AgentSession = class {
|
|
|
3297
4733
|
}
|
|
3298
4734
|
/**
|
|
3299
4735
|
* Delivers a person's message: written to the live process (mid-turn is fine), or the
|
|
3300
|
-
* process is started again
|
|
4736
|
+
* process is started again resuming the conversation first. A per_turn agent starts a
|
|
4737
|
+
* turn's process with it, or (mid-turn) takes it as the next turn.
|
|
3301
4738
|
*/
|
|
3302
4739
|
async sendMessage(text, commandId) {
|
|
3303
4740
|
if (this.restartAfterTurn && this.record.turnActive) {
|
|
@@ -3310,7 +4747,7 @@ var AgentSession = class {
|
|
|
3310
4747
|
this.emit({ type: "user_message_echo", providerEventId: commandId, text, delivered: true });
|
|
3311
4748
|
return;
|
|
3312
4749
|
}
|
|
3313
|
-
await this.ensureProcess();
|
|
4750
|
+
if (this.driver.processModel === "persistent") await this.ensureProcess();
|
|
3314
4751
|
const ids = this.record.handledCommandIds ??= [];
|
|
3315
4752
|
ids.push(commandId);
|
|
3316
4753
|
if (ids.length > HANDLED_COMMAND_IDS_KEPT) ids.splice(0, ids.length - HANDLED_COMMAND_IDS_KEPT);
|
|
@@ -3330,32 +4767,34 @@ var AgentSession = class {
|
|
|
3330
4767
|
}
|
|
3331
4768
|
}
|
|
3332
4769
|
/**
|
|
3333
|
-
* Stops the current turn.
|
|
3334
|
-
* the Agent SDK sends it) and ends the turn
|
|
3335
|
-
*
|
|
4770
|
+
* Stops the current turn. An agent that takes an interrupt request on stdin (Claude Code,
|
|
4771
|
+
* as the Agent SDK sends it) gets one and ends the turn itself; if it has not within the
|
|
4772
|
+
* grace period, or takes none, SIGINT does the same the hard way.
|
|
3336
4773
|
*/
|
|
3337
4774
|
interrupt() {
|
|
3338
4775
|
const child = this.child;
|
|
3339
4776
|
if (!child || !this.record.turnActive) return false;
|
|
3340
4777
|
this.interruptRequested = true;
|
|
3341
4778
|
this.permissions.expireAll(PERMISSION_EXPIRED_INTERRUPTED);
|
|
3342
|
-
|
|
3343
|
-
|
|
3344
|
-
|
|
3345
|
-
|
|
3346
|
-
|
|
4779
|
+
const sigint = () => child.kill("SIGINT");
|
|
4780
|
+
const message = this.driver.interruptMessage?.(`dt_interrupt_${++this.controlSeq}`);
|
|
4781
|
+
if (message === void 0) {
|
|
4782
|
+
sigint();
|
|
4783
|
+
return true;
|
|
4784
|
+
}
|
|
4785
|
+
this.write(message);
|
|
3347
4786
|
if (this.interruptTimer) clearTimeout(this.interruptTimer);
|
|
3348
4787
|
this.interruptTimer = setTimeout(() => {
|
|
3349
4788
|
this.interruptTimer = null;
|
|
3350
4789
|
if (this.child === child && this.record.turnActive) {
|
|
3351
4790
|
this.deps.logger.warn(`session ${this.sessionId}: no answer to interrupt; sending SIGINT`);
|
|
3352
|
-
|
|
4791
|
+
sigint();
|
|
3353
4792
|
}
|
|
3354
4793
|
}, this.deps.interruptGraceMs ?? 5e3);
|
|
3355
4794
|
return true;
|
|
3356
4795
|
}
|
|
3357
4796
|
/**
|
|
3358
|
-
* Ends the process (closing stdin first, so
|
|
4797
|
+
* Ends the process (closing stdin first, so the agent saves its session and exits), and
|
|
3359
4798
|
* with it everything it started: the background commands still in its process group are
|
|
3360
4799
|
* ended once it has exited, and SIGTERM and SIGKILL go to the whole group.
|
|
3361
4800
|
*/
|
|
@@ -3366,6 +4805,9 @@ var AgentSession = class {
|
|
|
3366
4805
|
this.stopping = reason;
|
|
3367
4806
|
this.reapGraceMs = graceMs;
|
|
3368
4807
|
const exited = new Promise((resolve2) => this.exitWaiters.push(resolve2));
|
|
4808
|
+
if (child.exitCode === null && child.signalCode === null) {
|
|
4809
|
+
await snapshotTree(this.tree, this.deps.reap);
|
|
4810
|
+
}
|
|
3369
4811
|
child.stdin.end();
|
|
3370
4812
|
const timedOut = await raceTimeout(exited, graceMs);
|
|
3371
4813
|
if (timedOut && this.child === child) {
|
|
@@ -3389,9 +4831,10 @@ var AgentSession = class {
|
|
|
3389
4831
|
* Writes a user message to a running process that is not being stopped (starting it, or
|
|
3390
4832
|
* waiting out a stop in progress and starting it again, first). The turn counts as active
|
|
3391
4833
|
* only once the message is written: a write that fails leaves no turn waiting for a
|
|
3392
|
-
* result that will never come.
|
|
4834
|
+
* result that will never come. A per_turn agent starts the turn's own process instead.
|
|
3393
4835
|
*/
|
|
3394
4836
|
async beginTurn(text, before) {
|
|
4837
|
+
if (this.driver.processModel === "per_turn") return this.beginProcessTurn(text, before);
|
|
3395
4838
|
while (!this.child || this.stopping || this.resumeDoomed) await this.ensureProcess();
|
|
3396
4839
|
let content = text;
|
|
3397
4840
|
const preface = this.record.freshPreface;
|
|
@@ -3404,7 +4847,66 @@ ${text}`;
|
|
|
3404
4847
|
this.record.freshPreface = null;
|
|
3405
4848
|
await this.deps.store.save(this.record);
|
|
3406
4849
|
}
|
|
3407
|
-
this.write(
|
|
4850
|
+
this.write(this.driver.encodeMessage(content));
|
|
4851
|
+
await this.turnBegun(text, before);
|
|
4852
|
+
}
|
|
4853
|
+
/**
|
|
4854
|
+
* A per_turn agent's turn: a process of its own, given the message and the conversation to
|
|
4855
|
+
* resume. A message sent while a turn runs (or starts) waits for it, and goes with any
|
|
4856
|
+
* others as the next turn; messages still waiting go ahead of this one, in order.
|
|
4857
|
+
*/
|
|
4858
|
+
async beginProcessTurn(text, before) {
|
|
4859
|
+
if (this.record.turnActive || this.startingTurn) {
|
|
4860
|
+
this.queuedTurns.push(text);
|
|
4861
|
+
this.lastActivity = Date.now();
|
|
4862
|
+
if (before) this.emit(before);
|
|
4863
|
+
return;
|
|
4864
|
+
}
|
|
4865
|
+
const waiting = this.queuedTurns.splice(0);
|
|
4866
|
+
try {
|
|
4867
|
+
await this.startProcessTurn([...waiting, text], before);
|
|
4868
|
+
} catch (err) {
|
|
4869
|
+
this.queuedTurns.unshift(...waiting);
|
|
4870
|
+
throw err;
|
|
4871
|
+
}
|
|
4872
|
+
}
|
|
4873
|
+
/** Starts a per_turn agent's process on these messages (oldest first), as one turn. */
|
|
4874
|
+
async startProcessTurn(texts, before) {
|
|
4875
|
+
this.startingTurn = true;
|
|
4876
|
+
try {
|
|
4877
|
+
while (this.child) await this.stop("idle");
|
|
4878
|
+
const text = texts.join("\n\n");
|
|
4879
|
+
const preface = this.record.freshPreface;
|
|
4880
|
+
const fresh = !this.record.conversationId;
|
|
4881
|
+
const prompt = preface && fresh ? `${preface}
|
|
4882
|
+
|
|
4883
|
+
---
|
|
4884
|
+
|
|
4885
|
+
${text}` : text;
|
|
4886
|
+
const previousTurnText = this.turnText;
|
|
4887
|
+
if (preface && fresh) this.record.freshPreface = null;
|
|
4888
|
+
this.turnText = text;
|
|
4889
|
+
this.record.turnActive = true;
|
|
4890
|
+
this.mapper.markRunning();
|
|
4891
|
+
this.lastActivity = Date.now();
|
|
4892
|
+
try {
|
|
4893
|
+
await this.deps.store.save(this.record);
|
|
4894
|
+
await this.spawnAgent(prompt);
|
|
4895
|
+
} catch (err) {
|
|
4896
|
+
this.record.turnActive = false;
|
|
4897
|
+
if (preface && fresh) this.record.freshPreface = preface;
|
|
4898
|
+
this.turnText = previousTurnText;
|
|
4899
|
+
await this.deps.store.save(this.record).catch(() => void 0);
|
|
4900
|
+
throw err;
|
|
4901
|
+
}
|
|
4902
|
+
if (before) this.emit(before);
|
|
4903
|
+
this.emit({ type: "status", status: "running" });
|
|
4904
|
+
} finally {
|
|
4905
|
+
this.startingTurn = false;
|
|
4906
|
+
}
|
|
4907
|
+
}
|
|
4908
|
+
/** The turn's message went to the agent: the turn is active, and said to be. */
|
|
4909
|
+
async turnBegun(text, before) {
|
|
3408
4910
|
if (!this.record.turnActive) this.turnText = text;
|
|
3409
4911
|
this.lastActivity = Date.now();
|
|
3410
4912
|
if (before) this.emit(before);
|
|
@@ -3415,9 +4917,31 @@ ${text}`;
|
|
|
3415
4917
|
await this.deps.store.save(this.record);
|
|
3416
4918
|
}
|
|
3417
4919
|
}
|
|
4920
|
+
/** per_turn agents: once the turn is over, however it ended, what waited for it goes next. */
|
|
4921
|
+
scheduleQueuedTurns() {
|
|
4922
|
+
if (this.driver.processModel !== "per_turn" || !this.queuedTurns.length) return;
|
|
4923
|
+
setTimeout(() => void this.runQueuedTurns(), 0);
|
|
4924
|
+
}
|
|
4925
|
+
/** per_turn agents: the messages that waited for the last turn, as the next one. */
|
|
4926
|
+
async runQueuedTurns() {
|
|
4927
|
+
if (!this.queuedTurns.length || this.record.turnActive || this.startingTurn) return;
|
|
4928
|
+
const texts = this.queuedTurns.splice(0);
|
|
4929
|
+
try {
|
|
4930
|
+
await this.startProcessTurn(texts);
|
|
4931
|
+
} catch (err) {
|
|
4932
|
+
this.emit(
|
|
4933
|
+
{
|
|
4934
|
+
type: "error",
|
|
4935
|
+
message: `${this.driver.displayName} could not be started for the next message: ${err.message}`,
|
|
4936
|
+
retryable: true
|
|
4937
|
+
},
|
|
4938
|
+
{ type: "result", status: "failed", text: null }
|
|
4939
|
+
);
|
|
4940
|
+
}
|
|
4941
|
+
}
|
|
3418
4942
|
write(message) {
|
|
3419
4943
|
if (!this.child || this.stopping || this.child.stdin.writableEnded) {
|
|
3420
|
-
throw new Error(
|
|
4944
|
+
throw new Error(`${this.driver.displayName} is not running for this session.`);
|
|
3421
4945
|
}
|
|
3422
4946
|
this.child.stdin.write(JSON.stringify(message) + "\n");
|
|
3423
4947
|
}
|
|
@@ -3426,15 +4950,19 @@ ${text}`;
|
|
|
3426
4950
|
if (!this.child) return Promise.resolve();
|
|
3427
4951
|
return new Promise((resolve2) => this.exitWaiters.push(resolve2));
|
|
3428
4952
|
}
|
|
4953
|
+
/** persistent agents: the session's process, started (resuming) when there is none. */
|
|
3429
4954
|
async ensureProcess() {
|
|
3430
4955
|
while (this.child && (this.stopping || this.resumeDoomed)) await this.waitForExit();
|
|
3431
4956
|
if (this.child) return;
|
|
4957
|
+
await this.spawnAgent();
|
|
4958
|
+
}
|
|
4959
|
+
/** Starts the agent's process (with a per_turn agent's prompt), and reads what it says. */
|
|
4960
|
+
async spawnAgent(prompt) {
|
|
3432
4961
|
await this.prepareEvidenceDir();
|
|
3433
|
-
const { bin, features } = await this.deps.
|
|
4962
|
+
const { bin, features } = await this.deps.resolveAgent();
|
|
3434
4963
|
const savedRules = await (this.deps.savedRules?.(this.record.repository) ?? []);
|
|
3435
4964
|
this.inheritedNow = await this.readInheritedRules();
|
|
3436
|
-
const
|
|
3437
|
-
const assembled = [
|
|
4965
|
+
const allowedTools = [
|
|
3438
4966
|
.../* @__PURE__ */ new Set([
|
|
3439
4967
|
...this.deps.allowedTools,
|
|
3440
4968
|
...this.inheritedNow.allow,
|
|
@@ -3442,30 +4970,34 @@ ${text}`;
|
|
|
3442
4970
|
...this.record.grantRules ?? []
|
|
3443
4971
|
])
|
|
3444
4972
|
];
|
|
3445
|
-
const allowedTools = features.settingsFlag || ask.length === 0 ? assembled : assembled.filter((r) => !overlapsAsk(r, ask));
|
|
3446
4973
|
const disallowedTools = [
|
|
3447
4974
|
.../* @__PURE__ */ new Set([...this.deps.disallowedTools ?? [], ...this.inheritedNow.deny])
|
|
3448
4975
|
];
|
|
3449
|
-
const
|
|
4976
|
+
const launch = this.driver.launch({
|
|
4977
|
+
bin,
|
|
4978
|
+
features,
|
|
4979
|
+
cwd: this.record.cwd,
|
|
3450
4980
|
permissionMode: this.deps.permissionMode,
|
|
3451
4981
|
allowedTools,
|
|
3452
4982
|
disallowedTools,
|
|
3453
|
-
|
|
4983
|
+
askTools: this.inheritedNow.ask,
|
|
4984
|
+
loadProjectSettings: !!this.deps.loadProjectSettings,
|
|
3454
4985
|
model: this.record.model,
|
|
3455
|
-
resume: this.record.
|
|
4986
|
+
resume: this.record.conversationId,
|
|
3456
4987
|
relayPermissions: !!this.record.relayPermissionRequests,
|
|
3457
|
-
|
|
3458
|
-
appendSystemPrompt: runnerSystemPrompt({
|
|
4988
|
+
systemPrompt: runnerSystemPrompt({
|
|
3459
4989
|
workBranch: this.record.workBranch,
|
|
3460
4990
|
baseRef: this.record.baseRef,
|
|
3461
4991
|
cwd: this.record.cwd,
|
|
3462
|
-
reviewImages: !!this.record.reviewImages
|
|
4992
|
+
reviewImages: !!this.record.reviewImages,
|
|
4993
|
+
reference: this.record.referenceRepository ?? null
|
|
3463
4994
|
}),
|
|
3464
|
-
|
|
4995
|
+
...prompt !== void 0 ? { prompt } : {},
|
|
4996
|
+
...this.deps.agentConfig ? { agentConfig: this.deps.agentConfig } : {}
|
|
3465
4997
|
});
|
|
3466
|
-
const child =
|
|
4998
|
+
const child = spawn4(launch.bin, launch.args, {
|
|
3467
4999
|
cwd: this.record.cwd,
|
|
3468
|
-
env: process.env,
|
|
5000
|
+
env: launch.env ? { ...process.env, ...launch.env } : process.env,
|
|
3469
5001
|
stdio: ["pipe", "pipe", "pipe"],
|
|
3470
5002
|
windowsHide: true,
|
|
3471
5003
|
// A process group of its own, so what it starts can be ended with it. It also means
|
|
@@ -3480,36 +5012,43 @@ ${text}`;
|
|
|
3480
5012
|
});
|
|
3481
5013
|
child.once(
|
|
3482
5014
|
"error",
|
|
3483
|
-
(err) => reject(
|
|
5015
|
+
(err) => reject(
|
|
5016
|
+
new Error(`Could not start ${this.driver.displayName} (${launch.bin}): ${err.message}`)
|
|
5017
|
+
)
|
|
3484
5018
|
);
|
|
3485
5019
|
});
|
|
3486
5020
|
this.child = child;
|
|
5021
|
+
this.tree = tree;
|
|
3487
5022
|
this.stopping = null;
|
|
3488
5023
|
this.resumeDoomed = false;
|
|
3489
5024
|
this.reapGraceMs = void 0;
|
|
3490
5025
|
this.stderrTail = "";
|
|
3491
5026
|
this.sawResultSinceSpawn = false;
|
|
3492
|
-
this.spawnedWithResume = !!this.record.
|
|
5027
|
+
this.spawnedWithResume = !!this.record.conversationId;
|
|
3493
5028
|
this.sawInitSinceSpawn = false;
|
|
3494
5029
|
this.deps.logger.info(
|
|
3495
|
-
`session ${this.sessionId}:
|
|
5030
|
+
`session ${this.sessionId}: ${this.driver.displayName} started${this.record.conversationId ? " (resumed)" : ""}`,
|
|
3496
5031
|
{ pid: child.pid }
|
|
3497
5032
|
);
|
|
3498
5033
|
this.treeReaped = new Promise(
|
|
3499
5034
|
(resolve2) => child.once("exit", () => void reapTree(tree, this.reapGraceMs, this.deps.reap).then(resolve2))
|
|
3500
5035
|
);
|
|
3501
5036
|
child.stdin.on("error", () => void 0);
|
|
5037
|
+
if (launch.stdin !== void 0) child.stdin.end(launch.stdin);
|
|
5038
|
+
else if (this.driver.processModel === "per_turn") child.stdin.end();
|
|
3502
5039
|
child.stderr.setEncoding("utf8").on("data", (d) => {
|
|
3503
5040
|
this.stderrTail = (this.stderrTail + d).slice(-4e3);
|
|
3504
5041
|
});
|
|
3505
|
-
const rl =
|
|
5042
|
+
const rl = createInterface2({ input: child.stdout, crlfDelay: Infinity });
|
|
3506
5043
|
rl.on("line", (line) => {
|
|
3507
5044
|
if (!line.trim()) return;
|
|
3508
5045
|
let parsed;
|
|
3509
5046
|
try {
|
|
3510
5047
|
parsed = JSON.parse(line);
|
|
3511
5048
|
} catch {
|
|
3512
|
-
this.deps.logger.debug(
|
|
5049
|
+
this.deps.logger.debug(
|
|
5050
|
+
`session ${this.sessionId}: non-JSON output from ${this.driver.displayName}`
|
|
5051
|
+
);
|
|
3513
5052
|
return;
|
|
3514
5053
|
}
|
|
3515
5054
|
this.lineChain = this.lineChain.then(() => this.handleLine(parsed)).catch((err) => {
|
|
@@ -3525,22 +5064,19 @@ ${text}`;
|
|
|
3525
5064
|
}
|
|
3526
5065
|
async handleLine(line) {
|
|
3527
5066
|
this.lastActivity = Date.now();
|
|
3528
|
-
|
|
3529
|
-
|
|
3530
|
-
|
|
3531
|
-
|
|
3532
|
-
const cancelled = parseControlCancel(line);
|
|
3533
|
-
if (cancelled) {
|
|
3534
|
-
this.permissions.cancel(cancelled);
|
|
5067
|
+
const control = this.driver.control;
|
|
5068
|
+
const controlLine = control?.parse(line);
|
|
5069
|
+
if (control && controlLine) {
|
|
5070
|
+
await this.handleControlLine(control, controlLine);
|
|
3535
5071
|
return;
|
|
3536
5072
|
}
|
|
3537
5073
|
const mapped = this.mapper.map(line);
|
|
3538
5074
|
let dirty = false;
|
|
3539
|
-
if (mapped.
|
|
5075
|
+
if (mapped.conversationId) this.sawInitSinceSpawn = true;
|
|
3540
5076
|
let learnedSessionId = null;
|
|
3541
|
-
if (mapped.
|
|
3542
|
-
this.record.
|
|
3543
|
-
learnedSessionId = mapped.
|
|
5077
|
+
if (mapped.conversationId && mapped.conversationId !== this.record.conversationId) {
|
|
5078
|
+
this.record.conversationId = mapped.conversationId;
|
|
5079
|
+
learnedSessionId = mapped.conversationId;
|
|
3544
5080
|
dirty = true;
|
|
3545
5081
|
}
|
|
3546
5082
|
if (mapped.turnStarted && !this.record.turnActive) {
|
|
@@ -3550,17 +5086,11 @@ ${text}`;
|
|
|
3550
5086
|
if (dirty) await this.deps.store.save(this.record);
|
|
3551
5087
|
if (learnedSessionId) {
|
|
3552
5088
|
const at = mapped.events.findIndex((e) => e.type === "status");
|
|
5089
|
+
const ids = this.conversationIds(learnedSessionId);
|
|
3553
5090
|
if (at >= 0) {
|
|
3554
|
-
mapped.events[at] = {
|
|
3555
|
-
...mapped.events[at],
|
|
3556
|
-
claudeSessionId: learnedSessionId
|
|
3557
|
-
};
|
|
5091
|
+
mapped.events[at] = { ...mapped.events[at], ...ids };
|
|
3558
5092
|
} else {
|
|
3559
|
-
mapped.events.push({
|
|
3560
|
-
type: "status",
|
|
3561
|
-
status: "running",
|
|
3562
|
-
claudeSessionId: learnedSessionId
|
|
3563
|
-
});
|
|
5093
|
+
mapped.events.push({ type: "status", status: "running", ...ids });
|
|
3564
5094
|
}
|
|
3565
5095
|
}
|
|
3566
5096
|
if (mapped.events.length) this.emit(...mapped.events);
|
|
@@ -3572,9 +5102,9 @@ ${text}`;
|
|
|
3572
5102
|
}
|
|
3573
5103
|
if (mapped.turnEnd && this.resumeFailedBeforeTurn(mapped.turnEnd.isError)) {
|
|
3574
5104
|
this.deps.logger.warn(
|
|
3575
|
-
`session ${this.sessionId}: the
|
|
5105
|
+
`session ${this.sessionId}: the ${this.driver.displayName} conversation to resume was not found; starting a fresh one`
|
|
3576
5106
|
);
|
|
3577
|
-
this.record.
|
|
5107
|
+
this.record.conversationId = null;
|
|
3578
5108
|
this.resumeDoomed = true;
|
|
3579
5109
|
await this.deps.store.save(this.record);
|
|
3580
5110
|
this.child?.stdin.end();
|
|
@@ -3587,7 +5117,7 @@ ${text}`;
|
|
|
3587
5117
|
}
|
|
3588
5118
|
/**
|
|
3589
5119
|
* The process was started to resume a conversation and failed before it said it had it
|
|
3590
|
-
* (no `system/init`):
|
|
5120
|
+
* (Claude Code: no `system/init`): the agent did not find the conversation on this computer.
|
|
3591
5121
|
*/
|
|
3592
5122
|
resumeNotFound(isError) {
|
|
3593
5123
|
return isError && this.spawnedWithResume && !this.sawInitSinceSpawn && !this.interruptRequested && this.record.turnActive && this.turnText !== null;
|
|
@@ -3595,12 +5125,19 @@ ${text}`;
|
|
|
3595
5125
|
resumeFailedBeforeTurn(isError) {
|
|
3596
5126
|
return isError && this.spawnedWithResume && !this.sawInitSinceSpawn && !this.interruptRequested && !this.record.turnActive;
|
|
3597
5127
|
}
|
|
5128
|
+
/**
|
|
5129
|
+
* How an event names the agent's conversation: `conversationId` for every agent, and
|
|
5130
|
+
* Claude Code's also as `claudeSessionId`, which servers that predate the neutral name read.
|
|
5131
|
+
*/
|
|
5132
|
+
conversationIds(id) {
|
|
5133
|
+
return this.driver.kind === DEFAULT_AGENT_KIND ? { claudeSessionId: id, conversationId: id } : { conversationId: id };
|
|
5134
|
+
}
|
|
3598
5135
|
planFreshRetry() {
|
|
3599
5136
|
this.deps.logger.warn(
|
|
3600
|
-
`session ${this.sessionId}: the
|
|
5137
|
+
`session ${this.sessionId}: the ${this.driver.displayName} conversation to resume was not found; starting a fresh one`
|
|
3601
5138
|
);
|
|
3602
5139
|
this.resumeRetry = this.turnText;
|
|
3603
|
-
this.record.
|
|
5140
|
+
this.record.conversationId = null;
|
|
3604
5141
|
}
|
|
3605
5142
|
async endTurn(turn) {
|
|
3606
5143
|
this.permissions.expireAll(PERMISSION_EXPIRED_TURN_ENDED);
|
|
@@ -3613,12 +5150,12 @@ ${text}`;
|
|
|
3613
5150
|
if (this.interruptTimer) clearTimeout(this.interruptTimer);
|
|
3614
5151
|
this.interruptTimer = null;
|
|
3615
5152
|
const turnFailed = turn.isError && !interrupted;
|
|
3616
|
-
if (turnFailed && turnFailedToSignIn(turn)) this.deps.
|
|
3617
|
-
else if (!turn.isError) this.deps.
|
|
5153
|
+
if (turnFailed && this.driver.turnFailedToSignIn(turn)) this.deps.onAgentSignIn?.(false);
|
|
5154
|
+
else if (!turn.isError) this.deps.onAgentSignIn?.(true);
|
|
3618
5155
|
if (turnFailed) {
|
|
3619
5156
|
this.emit({
|
|
3620
5157
|
type: "error",
|
|
3621
|
-
message: turnErrorMessage(turn),
|
|
5158
|
+
message: this.driver.turnErrorMessage(turn),
|
|
3622
5159
|
retryable: true
|
|
3623
5160
|
});
|
|
3624
5161
|
}
|
|
@@ -3653,12 +5190,14 @@ ${text}`;
|
|
|
3653
5190
|
...push.failed ? { unpushedWork: true } : {},
|
|
3654
5191
|
// So the server can have a later session resume this conversation (a run continued
|
|
3655
5192
|
// after it ended).
|
|
3656
|
-
...this.record.
|
|
5193
|
+
...this.record.conversationId ? this.conversationIds(this.record.conversationId) : {}
|
|
3657
5194
|
});
|
|
3658
5195
|
this.lastActivity = Date.now();
|
|
3659
5196
|
if (this.restartAfterTurn) {
|
|
3660
5197
|
this.restartAfterTurn = false;
|
|
3661
5198
|
setTimeout(() => void this.restartWithGrants(), 0);
|
|
5199
|
+
} else {
|
|
5200
|
+
this.scheduleQueuedTurns();
|
|
3662
5201
|
}
|
|
3663
5202
|
this.deps.logger.info(
|
|
3664
5203
|
`session ${this.sessionId}: turn ${interrupted ? "interrupted" : turnFailed ? "ended with an error" : push.failed ? "finished, but its work was not pushed" : "finished"}`,
|
|
@@ -3675,7 +5214,7 @@ ${text}`;
|
|
|
3675
5214
|
const repo = parseRepoUrl(repository ?? "");
|
|
3676
5215
|
if (!pullRequest || !workBranch || !repo) return null;
|
|
3677
5216
|
const body = [
|
|
3678
|
-
text?.trim() ||
|
|
5217
|
+
text?.trim() || `Work by the ${this.driver.displayName} (local) agent.`,
|
|
3679
5218
|
"",
|
|
3680
5219
|
"---",
|
|
3681
5220
|
pullRequest.footer
|
|
@@ -3831,21 +5370,25 @@ ${text}`;
|
|
|
3831
5370
|
const waiters = this.exitWaiters;
|
|
3832
5371
|
this.exitWaiters = [];
|
|
3833
5372
|
try {
|
|
3834
|
-
if (this.resumeRetry === null && !reason && this.record.turnActive && this.resumeNotFound(true) &&
|
|
5373
|
+
if (this.resumeRetry === null && !reason && this.record.turnActive && this.resumeNotFound(true) && this.driver.resumeNotFound(this.stderrTail)) {
|
|
3835
5374
|
this.planFreshRetry();
|
|
3836
5375
|
}
|
|
3837
5376
|
if (this.resumeRetry !== null) {
|
|
3838
5377
|
const text = this.resumeRetry;
|
|
3839
5378
|
this.resumeRetry = null;
|
|
5379
|
+
const perTurn = this.driver.processModel === "per_turn";
|
|
5380
|
+
if (perTurn) this.startingTurn = true;
|
|
3840
5381
|
this.record.turnActive = false;
|
|
3841
|
-
await this.deps.store.save(this.record);
|
|
3842
5382
|
try {
|
|
3843
|
-
await this.
|
|
5383
|
+
await this.deps.store.save(this.record);
|
|
5384
|
+
if (perTurn) await this.startProcessTurn([text]);
|
|
5385
|
+
else await this.beginTurn(text);
|
|
3844
5386
|
} catch (err) {
|
|
5387
|
+
this.startingTurn = false;
|
|
3845
5388
|
this.emit(
|
|
3846
5389
|
{
|
|
3847
5390
|
type: "error",
|
|
3848
|
-
message:
|
|
5391
|
+
message: `${this.driver.displayName} could not be started again for this message: ${err.message}`,
|
|
3849
5392
|
retryable: true
|
|
3850
5393
|
},
|
|
3851
5394
|
{ type: "result", status: "failed", text: null }
|
|
@@ -3854,11 +5397,13 @@ ${text}`;
|
|
|
3854
5397
|
return;
|
|
3855
5398
|
}
|
|
3856
5399
|
if (reason) {
|
|
3857
|
-
this.deps.logger.info(
|
|
5400
|
+
this.deps.logger.info(
|
|
5401
|
+
`session ${this.sessionId}: ${this.driver.displayName} stopped (${reason})`
|
|
5402
|
+
);
|
|
3858
5403
|
if (reason !== "shutdown" && this.record.turnActive) {
|
|
3859
5404
|
this.emit({
|
|
3860
5405
|
type: "error",
|
|
3861
|
-
message:
|
|
5406
|
+
message: `${this.driver.displayName} was stopped in the middle of this turn. Send a message to continue.`,
|
|
3862
5407
|
retryable: true
|
|
3863
5408
|
});
|
|
3864
5409
|
this.record.turnActive = false;
|
|
@@ -3868,10 +5413,12 @@ ${text}`;
|
|
|
3868
5413
|
return;
|
|
3869
5414
|
}
|
|
3870
5415
|
if (!this.record.turnActive) {
|
|
3871
|
-
this.
|
|
3872
|
-
|
|
3873
|
-
|
|
3874
|
-
|
|
5416
|
+
if (this.driver.processModel === "persistent") {
|
|
5417
|
+
this.deps.logger.info(
|
|
5418
|
+
`session ${this.sessionId}: ${this.driver.displayName} exited while idle`,
|
|
5419
|
+
{ code, signal }
|
|
5420
|
+
);
|
|
5421
|
+
}
|
|
3875
5422
|
return;
|
|
3876
5423
|
}
|
|
3877
5424
|
if (this.interruptRequested) {
|
|
@@ -3883,46 +5430,25 @@ ${text}`;
|
|
|
3883
5430
|
400
|
|
3884
5431
|
);
|
|
3885
5432
|
const how = signal ? `was killed (${signal})` : `exited with code ${code}`;
|
|
3886
|
-
const hint = this.sawResultSinceSpawn ? "" : startupHint(this.stderrTail);
|
|
3887
|
-
if (!this.sawResultSinceSpawn && looksLikeSignInFailure(this.stderrTail)) {
|
|
3888
|
-
this.deps.
|
|
5433
|
+
const hint = this.sawResultSinceSpawn ? "" : this.driver.startupHint(this.stderrTail);
|
|
5434
|
+
if (!this.sawResultSinceSpawn && this.driver.looksLikeSignInFailure(this.stderrTail)) {
|
|
5435
|
+
this.deps.onAgentSignIn?.(false);
|
|
3889
5436
|
}
|
|
3890
5437
|
this.emit({
|
|
3891
5438
|
type: "error",
|
|
3892
|
-
message:
|
|
5439
|
+
message: `${this.driver.displayName} ${how} in the middle of a turn.${hint}${tail ? ` ${tail}` : ""}`,
|
|
3893
5440
|
retryable: true
|
|
3894
5441
|
});
|
|
3895
5442
|
this.record.turnActive = false;
|
|
3896
5443
|
await this.deps.store.save(this.record);
|
|
3897
5444
|
this.emit({ type: "result", status: "failed", text: null });
|
|
3898
|
-
this.deps.logger.warn(`session ${this.sessionId}:
|
|
5445
|
+
this.deps.logger.warn(`session ${this.sessionId}: ${this.driver.displayName} ${how}`);
|
|
3899
5446
|
} finally {
|
|
5447
|
+
if (reason !== "shutdown" && reason !== "close") this.scheduleQueuedTurns();
|
|
3900
5448
|
for (const w of waiters) w();
|
|
3901
5449
|
}
|
|
3902
5450
|
}
|
|
3903
5451
|
};
|
|
3904
|
-
function turnErrorMessage(turn) {
|
|
3905
|
-
switch (turn.subtype) {
|
|
3906
|
-
case "error_max_turns":
|
|
3907
|
-
return "Claude Code stopped: it reached its maximum number of turns.";
|
|
3908
|
-
case "error_max_budget_usd":
|
|
3909
|
-
return "Claude Code stopped: it reached its spending limit.";
|
|
3910
|
-
default:
|
|
3911
|
-
if (turnFailedToSignIn(turn)) {
|
|
3912
|
-
return `Claude Code could not sign in to Claude (${turn.text.slice(0, 200)}). ${signInFix()} Then send a message here to try again.`;
|
|
3913
|
-
}
|
|
3914
|
-
return turn.text ? `Claude Code reported an error: ${turn.text.slice(0, 500)}` : `Claude Code ended the turn with an error (${turn.subtype ?? "unknown"}).`;
|
|
3915
|
-
}
|
|
3916
|
-
}
|
|
3917
|
-
function startupHint(stderr) {
|
|
3918
|
-
if (looksLikeSignInFailure(stderr)) {
|
|
3919
|
-
return ` Claude Code does not seem to be signed in on the runner\u2019s computer. ${signInFix()}`;
|
|
3920
|
-
}
|
|
3921
|
-
if (/No conversation found|session.*not found/i.test(stderr)) {
|
|
3922
|
-
return " The Claude Code conversation to resume was not found on this computer.";
|
|
3923
|
-
}
|
|
3924
|
-
return "";
|
|
3925
|
-
}
|
|
3926
5452
|
async function raceTimeout(done, ms) {
|
|
3927
5453
|
let timer;
|
|
3928
5454
|
const timeout = new Promise((resolve2) => {
|
|
@@ -4065,7 +5591,18 @@ var SessionManager = class {
|
|
|
4065
5591
|
if (cmd.repository && !parseRepoUrl(cmd.repository.url)) {
|
|
4066
5592
|
return { ok: false, error: repositoryUrlError(cmd.repository.url) };
|
|
4067
5593
|
}
|
|
4068
|
-
|
|
5594
|
+
const driver = this.driverFor(cmd.agent);
|
|
5595
|
+
driver.validateModel(cmd.model);
|
|
5596
|
+
const problem = await this.opts.agentProblem?.(driver);
|
|
5597
|
+
if (problem) {
|
|
5598
|
+
return {
|
|
5599
|
+
ok: false,
|
|
5600
|
+
error: `${driver.displayName} cannot run on this runner right now: ${problem}`
|
|
5601
|
+
};
|
|
5602
|
+
}
|
|
5603
|
+
if (this.sessions.has(cmd.sessionId)) return { ok: true };
|
|
5604
|
+
const checking = this.starting.get(cmd.sessionId);
|
|
5605
|
+
if (checking) return checking;
|
|
4069
5606
|
const max = this.opts.config.maxSessions;
|
|
4070
5607
|
if (this.liveCount() >= max) {
|
|
4071
5608
|
await this.stopOldestIdle(cmd.sessionId);
|
|
@@ -4093,7 +5630,13 @@ var SessionManager = class {
|
|
|
4093
5630
|
repo: cmd.repository?.url,
|
|
4094
5631
|
branch: cmd.repository?.workBranch
|
|
4095
5632
|
});
|
|
4096
|
-
|
|
5633
|
+
const driver = this.driverFor(cmd.agent);
|
|
5634
|
+
await this.opts.resolveAgent(driver);
|
|
5635
|
+
if (!driver.control && (cmd.relayPermissionRequests || cmd.reportToolDenials)) {
|
|
5636
|
+
this.opts.logger.info(
|
|
5637
|
+
`session ${cmd.sessionId}: ${driver.displayName} does not support relaying permission requests or reporting tool denials; its sandbox decides instead`
|
|
5638
|
+
);
|
|
5639
|
+
}
|
|
4097
5640
|
const resume = cmd.resume ?? null;
|
|
4098
5641
|
if (resume) {
|
|
4099
5642
|
for (const other of [...this.sessions.values()]) {
|
|
@@ -4103,7 +5646,7 @@ var SessionManager = class {
|
|
|
4103
5646
|
}
|
|
4104
5647
|
await Promise.allSettled([...this.closing.values()]);
|
|
4105
5648
|
this.opts.logger.info(`session ${cmd.sessionId}: continuing run ${cmd.runId}`, {
|
|
4106
|
-
resume: resume.claudeSessionId ? "conversation" : "fresh"
|
|
5649
|
+
resume: resume.conversationId ?? resume.claudeSessionId ? "conversation" : "fresh"
|
|
4107
5650
|
});
|
|
4108
5651
|
}
|
|
4109
5652
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
@@ -4117,7 +5660,8 @@ var SessionManager = class {
|
|
|
4117
5660
|
workBranch: null,
|
|
4118
5661
|
baseRef: null,
|
|
4119
5662
|
baseSha: null,
|
|
4120
|
-
|
|
5663
|
+
...driver.kind !== DEFAULT_AGENT_KIND ? { agentKind: driver.kind } : {},
|
|
5664
|
+
conversationId: null,
|
|
4121
5665
|
turnActive: false,
|
|
4122
5666
|
...cmd.relayPermissionRequests === true ? { relayPermissionRequests: true } : {},
|
|
4123
5667
|
...alwaysAllowTools(cmd).length ? { alwaysAllowedTools: alwaysAllowTools(cmd) } : {},
|
|
@@ -4165,18 +5709,41 @@ var SessionManager = class {
|
|
|
4165
5709
|
record.cwd = this.store.scratchDir(
|
|
4166
5710
|
resume ? safeWorktreeKey(resume.worktreeKey, cmd.sessionId) : cmd.sessionId
|
|
4167
5711
|
);
|
|
4168
|
-
await
|
|
5712
|
+
await mkdir7(record.cwd, { recursive: true });
|
|
4169
5713
|
if (cmd.reviewImages === true && this.opts.reviewImageUploader) {
|
|
4170
5714
|
record.reviewImages = true;
|
|
4171
|
-
await
|
|
5715
|
+
await mkdir7(join12(record.cwd, EVIDENCE_DIR), { recursive: true });
|
|
5716
|
+
}
|
|
5717
|
+
const reference = cmd.referenceRepository;
|
|
5718
|
+
if (reference?.url) {
|
|
5719
|
+
try {
|
|
5720
|
+
const checkout = await prepareReferenceCheckout({
|
|
5721
|
+
url: reference.url,
|
|
5722
|
+
baseRef: reference.baseRef ?? null,
|
|
5723
|
+
reposDir: this.opts.config.reposDir,
|
|
5724
|
+
dir: join12(record.cwd, RUNNER_REFERENCE_REPOSITORY_DIR),
|
|
5725
|
+
protocol: this.opts.config.gitProtocol
|
|
5726
|
+
});
|
|
5727
|
+
record.referenceRepository = {
|
|
5728
|
+
url: reference.url,
|
|
5729
|
+
baseRef: checkout.baseRef,
|
|
5730
|
+
dir: checkout.dir,
|
|
5731
|
+
repoDir: checkout.repoDir
|
|
5732
|
+
};
|
|
5733
|
+
} catch (err) {
|
|
5734
|
+
this.opts.logger.warn(
|
|
5735
|
+
`session ${cmd.sessionId}: could not check out ${reference.url} for the agent to read; it works without it`,
|
|
5736
|
+
{ error: safeError(err) }
|
|
5737
|
+
);
|
|
5738
|
+
}
|
|
4172
5739
|
}
|
|
4173
5740
|
const deliverable = resume?.deliverable;
|
|
4174
5741
|
if (typeof deliverable === "string" && deliverable.trim()) {
|
|
4175
|
-
await
|
|
5742
|
+
await writeFile5(join12(record.cwd, RUNNER_DELIVERABLE_FILE), deliverable, "utf8");
|
|
4176
5743
|
}
|
|
4177
5744
|
}
|
|
4178
5745
|
if (resume) {
|
|
4179
|
-
record.
|
|
5746
|
+
record.conversationId = (resume.conversationId ?? resume.claudeSessionId)?.trim() || null;
|
|
4180
5747
|
record.freshPreface = continuationPreface(cmd);
|
|
4181
5748
|
}
|
|
4182
5749
|
await this.store.save(record);
|
|
@@ -4191,7 +5758,7 @@ var SessionManager = class {
|
|
|
4191
5758
|
this.sessions.set(cmd.sessionId, session);
|
|
4192
5759
|
if (resume) return { ok: true };
|
|
4193
5760
|
try {
|
|
4194
|
-
await session.startFirstTurn(cmd
|
|
5761
|
+
await session.startFirstTurn(await this.promptWithImages(cmd, record));
|
|
4195
5762
|
} catch (err) {
|
|
4196
5763
|
const message = safeError(err);
|
|
4197
5764
|
this.opts.logger.error(`session ${cmd.sessionId}: ${message}`);
|
|
@@ -4330,6 +5897,36 @@ var SessionManager = class {
|
|
|
4330
5897
|
* session's folder), then the session is removed as a close would remove it. Called from
|
|
4331
5898
|
* inside the start, so it does not wait for the start as `close` does.
|
|
4332
5899
|
*/
|
|
5900
|
+
/**
|
|
5901
|
+
* The first turn's prompt, with the paths of the images it names (`promptImages`) saved in
|
|
5902
|
+
* the session's working directory. Never fails the start: an image that cannot be fetched
|
|
5903
|
+
* is listed as such, and so are all of them when there is nothing to fetch them with.
|
|
5904
|
+
*/
|
|
5905
|
+
async promptWithImages(cmd, record) {
|
|
5906
|
+
const images = Array.isArray(cmd.promptImages) ? cmd.promptImages : [];
|
|
5907
|
+
if (images.length === 0) return cmd.prompt;
|
|
5908
|
+
const fetcher = this.opts.promptImageFetcher;
|
|
5909
|
+
let saved = {
|
|
5910
|
+
saved: [],
|
|
5911
|
+
failed: images.map((i) => i.filename)
|
|
5912
|
+
};
|
|
5913
|
+
if (fetcher) {
|
|
5914
|
+
try {
|
|
5915
|
+
saved = await savePromptImages({
|
|
5916
|
+
sessionId: cmd.sessionId,
|
|
5917
|
+
cwd: record.cwd,
|
|
5918
|
+
inRepository: !!record.repoDir,
|
|
5919
|
+
images,
|
|
5920
|
+
fetcher
|
|
5921
|
+
});
|
|
5922
|
+
} catch (err) {
|
|
5923
|
+
this.opts.logger.warn(`session ${cmd.sessionId}: could not save the task's images`, {
|
|
5924
|
+
error: safeError(err)
|
|
5925
|
+
});
|
|
5926
|
+
}
|
|
5927
|
+
}
|
|
5928
|
+
return promptWithImagePaths(cmd.prompt, saved);
|
|
5929
|
+
}
|
|
4333
5930
|
async forgetFailedStart(session) {
|
|
4334
5931
|
const { sessionId } = session;
|
|
4335
5932
|
await session.outbox.flush(this.opts.failedStartFlushMs ?? 5e3);
|
|
@@ -4358,6 +5955,16 @@ var SessionManager = class {
|
|
|
4358
5955
|
})
|
|
4359
5956
|
);
|
|
4360
5957
|
} else if (record.cwd) {
|
|
5958
|
+
if (record.referenceRepository) {
|
|
5959
|
+
await removeWorktree(
|
|
5960
|
+
record.referenceRepository.repoDir,
|
|
5961
|
+
record.referenceRepository.dir
|
|
5962
|
+
).catch(
|
|
5963
|
+
(err) => this.opts.logger.warn(`session ${sessionId}: could not remove the checkout it read`, {
|
|
5964
|
+
error: safeError(err)
|
|
5965
|
+
})
|
|
5966
|
+
);
|
|
5967
|
+
}
|
|
4361
5968
|
await rm6(record.cwd, { recursive: true, force: true }).catch(() => void 0);
|
|
4362
5969
|
}
|
|
4363
5970
|
await session.outbox.settled();
|
|
@@ -4408,6 +6015,10 @@ var SessionManager = class {
|
|
|
4408
6015
|
await Promise.all(sessions.map((s) => s.outbox.flush(flushMs)));
|
|
4409
6016
|
await Promise.all(sessions.map((s) => s.outbox.stop()));
|
|
4410
6017
|
}
|
|
6018
|
+
/** The agent a session of this kind runs (the test override, else the registry's). */
|
|
6019
|
+
driverFor(kind) {
|
|
6020
|
+
return this.opts.driver ?? agentDriver(kind);
|
|
6021
|
+
}
|
|
4411
6022
|
async openSession(record) {
|
|
4412
6023
|
const outbox = await SessionOutbox.open({
|
|
4413
6024
|
sessionId: record.sessionId,
|
|
@@ -4421,17 +6032,24 @@ var SessionManager = class {
|
|
|
4421
6032
|
void this.close(record.sessionId);
|
|
4422
6033
|
}
|
|
4423
6034
|
});
|
|
6035
|
+
const driver = this.driverFor(record.agentKind);
|
|
4424
6036
|
return new AgentSession(record, {
|
|
4425
6037
|
store: this.store,
|
|
4426
6038
|
outbox,
|
|
4427
6039
|
logger: this.opts.logger,
|
|
4428
|
-
|
|
6040
|
+
driver,
|
|
6041
|
+
resolveAgent: () => this.opts.resolveAgent(driver),
|
|
4429
6042
|
permissionMode: this.opts.config.permissionMode,
|
|
4430
6043
|
allowedTools: this.opts.config.allowedTools,
|
|
4431
6044
|
disallowedTools: this.opts.config.disallowedTools ?? [],
|
|
4432
6045
|
loadProjectSettings: this.opts.config.loadProjectSettings ?? false,
|
|
6046
|
+
agentConfig: {
|
|
6047
|
+
codexSandbox: this.opts.config.codexSandbox ?? "workspace-write",
|
|
6048
|
+
codexNetworkAccess: this.opts.config.codexNetworkAccess === true,
|
|
6049
|
+
cursorForce: this.opts.config.cursorForce === true
|
|
6050
|
+
},
|
|
4433
6051
|
interruptGraceMs: this.opts.interruptGraceMs,
|
|
4434
|
-
|
|
6052
|
+
onAgentSignIn: this.opts.onAgentSignIn ? (ok) => this.opts.onAgentSignIn(ok, driver.kind) : void 0,
|
|
4435
6053
|
openPullRequest: this.opts.openPullRequest,
|
|
4436
6054
|
permissionTimeoutMs: this.opts.permissionTimeoutMs,
|
|
4437
6055
|
savedRules: async (url) => this.opts.grants ? await this.opts.grants.rulesFor(url) : [],
|
|
@@ -4498,11 +6116,13 @@ var RunnerDaemon = class {
|
|
|
4498
6116
|
config: opts.config,
|
|
4499
6117
|
poster: this.api,
|
|
4500
6118
|
logger: opts.logger,
|
|
4501
|
-
|
|
6119
|
+
resolveAgent: (driver) => this.resolveAgent(driver),
|
|
4502
6120
|
onUnauthorized: (err) => this.unauthorized(err),
|
|
4503
|
-
|
|
6121
|
+
onAgentSignIn: (ok, kind) => this.agentSignIn(ok, kind),
|
|
6122
|
+
agentProblem: (driver) => this.agentProblem(driver),
|
|
4504
6123
|
grants: this.grants,
|
|
4505
6124
|
reviewImageUploader: this.api,
|
|
6125
|
+
promptImageFetcher: this.api,
|
|
4506
6126
|
// What the person already allows in their own Claude Code for a repository.
|
|
4507
6127
|
inherited: opts.config.inheritClaudeCodePermissions ? new ClaudeCodeRules({
|
|
4508
6128
|
exclude: [opts.config.reposDir, opts.config.worktreesDir]
|
|
@@ -4516,12 +6136,17 @@ var RunnerDaemon = class {
|
|
|
4516
6136
|
exitReason = "stopped";
|
|
4517
6137
|
agentInfo = null;
|
|
4518
6138
|
/**
|
|
4519
|
-
*
|
|
4520
|
-
* is signed in (an expired sign-in it
|
|
4521
|
-
* later turn finishes.
|
|
6139
|
+
* The agents (`AgentDriver.kind`) a turn could not sign in. Claude Code's `claude auth
|
|
6140
|
+
* status` (or `codex login status`) may still say it is signed in (an expired sign-in it
|
|
6141
|
+
* cannot refresh), so this outranks the probe until a later turn finishes.
|
|
4522
6142
|
*/
|
|
4523
|
-
signInFailed =
|
|
4524
|
-
|
|
6143
|
+
signInFailed = /* @__PURE__ */ new Set();
|
|
6144
|
+
/** Each agent's binary and features, by `AgentDriver.kind`, trusted for the probe's TTL. */
|
|
6145
|
+
agentInstalls = /* @__PURE__ */ new Map();
|
|
6146
|
+
/** The agent the heartbeat's `claude*` fields report on: the default kind's. */
|
|
6147
|
+
driver = agentDriver();
|
|
6148
|
+
/** The optional agents (Codex, Cursor), each reported in its own heartbeat fields. */
|
|
6149
|
+
optional = OPTIONAL_AGENTS;
|
|
4525
6150
|
inFlight = /* @__PURE__ */ new Set();
|
|
4526
6151
|
/** The tail of each session's command queue (see `inSessionOrder`); never rejects. */
|
|
4527
6152
|
sessionQueues = /* @__PURE__ */ new Map();
|
|
@@ -4574,44 +6199,108 @@ var RunnerDaemon = class {
|
|
|
4574
6199
|
);
|
|
4575
6200
|
this.stop();
|
|
4576
6201
|
}
|
|
4577
|
-
async
|
|
6202
|
+
async resolveAgent(driver) {
|
|
4578
6203
|
const ttl = this.opts.agentProbeTtlMs ?? 5 * 6e4;
|
|
4579
|
-
|
|
4580
|
-
|
|
4581
|
-
|
|
4582
|
-
|
|
4583
|
-
|
|
4584
|
-
|
|
4585
|
-
|
|
4586
|
-
|
|
4587
|
-
|
|
6204
|
+
const cached = this.agentInstalls.get(driver.kind);
|
|
6205
|
+
if (cached && Date.now() - cached.at < ttl) return cached;
|
|
6206
|
+
const bin = await driver.resolveBinary();
|
|
6207
|
+
if (!bin) throw new Error(driver.notInstalledMessage());
|
|
6208
|
+
const install = { bin, features: await driver.readFeatures(bin), at: Date.now() };
|
|
6209
|
+
this.agentInstalls.set(driver.kind, install);
|
|
6210
|
+
return install;
|
|
6211
|
+
}
|
|
6212
|
+
/** Claude Code, for planning requests (answered by Claude Code only; see `completion.ts`). */
|
|
6213
|
+
async resolveClaude() {
|
|
6214
|
+
const { bin, features } = await this.resolveAgent(claudeCodeDriver);
|
|
6215
|
+
return { bin, features };
|
|
4588
6216
|
}
|
|
4589
6217
|
async agent() {
|
|
4590
6218
|
const ttl = this.opts.agentProbeTtlMs ?? 5 * 6e4;
|
|
4591
6219
|
if (!this.agentInfo || Date.now() - this.agentInfo.at > ttl) {
|
|
4592
|
-
const
|
|
6220
|
+
const [claude, ...others] = await Promise.all([
|
|
6221
|
+
this.driver.probe(),
|
|
6222
|
+
...this.optional.map((a) => a.driver.probe())
|
|
6223
|
+
]);
|
|
6224
|
+
let info2 = {
|
|
6225
|
+
claudeVersion: claude.claudeVersion,
|
|
6226
|
+
claudeReady: claude.claudeReady,
|
|
6227
|
+
claudeProblem: claude.claudeProblem ?? null
|
|
6228
|
+
};
|
|
6229
|
+
this.optional.forEach((a, i) => {
|
|
6230
|
+
info2 = { ...withAgentFields(info2, a, readAgentFields(others[i], a)), [a.runs]: true };
|
|
6231
|
+
});
|
|
4593
6232
|
if (info2.claudeProblem && info2.claudeProblem !== this.agentInfo?.info.claudeProblem) {
|
|
4594
6233
|
this.opts.logger.warn(info2.claudeProblem);
|
|
4595
6234
|
}
|
|
6235
|
+
for (const a of this.optional) {
|
|
6236
|
+
const now = readAgentFields(info2, a);
|
|
6237
|
+
const before = this.agentInfo ? readAgentFields(this.agentInfo.info, a) : null;
|
|
6238
|
+
if (now.version && now.problem && now.problem !== before?.problem) {
|
|
6239
|
+
this.opts.logger.warn(now.problem);
|
|
6240
|
+
}
|
|
6241
|
+
}
|
|
4596
6242
|
this.agentInfo = { info: info2, at: Date.now() };
|
|
4597
6243
|
}
|
|
4598
|
-
|
|
4599
|
-
if (
|
|
4600
|
-
|
|
4601
|
-
|
|
4602
|
-
|
|
4603
|
-
|
|
4604
|
-
|
|
6244
|
+
let { info } = this.agentInfo;
|
|
6245
|
+
if (this.signInFailed.has(this.driver.kind) && info.claudeVersion && info.claudeReady !== false) {
|
|
6246
|
+
info = {
|
|
6247
|
+
...info,
|
|
6248
|
+
claudeReady: false,
|
|
6249
|
+
claudeProblem: `A run could not sign in to Claude. ${this.driver.signInFix()}`
|
|
6250
|
+
};
|
|
6251
|
+
}
|
|
6252
|
+
for (const a of this.optional) {
|
|
6253
|
+
const now = readAgentFields(info, a);
|
|
6254
|
+
if (this.signInFailed.has(a.driver.kind) && now.version && now.ready !== false) {
|
|
6255
|
+
info = withAgentFields(info, a, {
|
|
6256
|
+
...now,
|
|
6257
|
+
ready: false,
|
|
6258
|
+
problem: `A run could not sign in to ${a.driver.displayName}. ${a.driver.signInFix()}`
|
|
6259
|
+
});
|
|
6260
|
+
}
|
|
6261
|
+
}
|
|
6262
|
+
return info;
|
|
4605
6263
|
}
|
|
4606
|
-
|
|
4607
|
-
|
|
4608
|
-
|
|
6264
|
+
/**
|
|
6265
|
+
* Why a session of this agent would not run now (see `SessionManagerOptions.agentProblem`).
|
|
6266
|
+
* Asked of the agent itself, not of the heartbeat's cached or overridden view: a person who
|
|
6267
|
+
* just installed it or signed in is not refused for a probe taken before, nor for a turn
|
|
6268
|
+
* that failed to sign in earlier (a new turn that fails says so in its own error).
|
|
6269
|
+
*/
|
|
6270
|
+
async agentProblem(driver) {
|
|
6271
|
+
const agent = this.optional.find((a) => a.driver.kind === driver.kind);
|
|
6272
|
+
if (!agent) return null;
|
|
6273
|
+
const fresh = readAgentFields(await agent.driver.probe(), agent);
|
|
6274
|
+
if (this.agentInfo) this.agentInfo.info = withAgentFields(this.agentInfo.info, agent, fresh);
|
|
6275
|
+
if (fresh.ready === true) this.signInFailed.delete(agent.driver.kind);
|
|
6276
|
+
if (fresh.ready !== false) return null;
|
|
6277
|
+
return fresh.problem || `${agent.driver.displayName} is not ready. ${agent.driver.signInFix()}`;
|
|
6278
|
+
}
|
|
6279
|
+
agentSignIn(ok, kind = this.driver.kind) {
|
|
6280
|
+
const cached = this.agentInfo?.info;
|
|
6281
|
+
const agent = this.optional.find((a) => a.driver.kind === kind);
|
|
6282
|
+
if (ok && cached) {
|
|
6283
|
+
if (kind === this.driver.kind && cached.claudeReady === false && cached.claudeVersion) {
|
|
6284
|
+
this.agentInfo.info = { ...cached, claudeReady: true, claudeProblem: null };
|
|
6285
|
+
} else if (agent) {
|
|
6286
|
+
const now = readAgentFields(cached, agent);
|
|
6287
|
+
if (now.ready === false && now.version) {
|
|
6288
|
+
this.agentInfo.info = withAgentFields(cached, agent, {
|
|
6289
|
+
...now,
|
|
6290
|
+
ready: true,
|
|
6291
|
+
problem: null
|
|
6292
|
+
});
|
|
6293
|
+
}
|
|
6294
|
+
}
|
|
4609
6295
|
}
|
|
4610
|
-
if (ok === !this.signInFailed) return;
|
|
4611
|
-
|
|
4612
|
-
|
|
4613
|
-
|
|
6296
|
+
if (ok === !this.signInFailed.has(kind)) return;
|
|
6297
|
+
if (ok) {
|
|
6298
|
+
this.signInFailed.delete(kind);
|
|
6299
|
+
return;
|
|
4614
6300
|
}
|
|
6301
|
+
this.signInFailed.add(kind);
|
|
6302
|
+
const driver = agent?.driver ?? this.driver;
|
|
6303
|
+
this.opts.logger.warn(`${driver.displayName} could not sign in. ${driver.signInFix()}`);
|
|
4615
6304
|
}
|
|
4616
6305
|
/**
|
|
4617
6306
|
* The runner's one heartbeat, for all of its sessions (each session's state rides in it).
|
|
@@ -4642,7 +6331,11 @@ var RunnerDaemon = class {
|
|
|
4642
6331
|
// And attaches a design proposal's rendered screens to its task (`reviewImages`).
|
|
4643
6332
|
uploadsReviewImages: true,
|
|
4644
6333
|
// And keeps a continued non-code run's deliverable whole (`resume.deliverable`).
|
|
4645
|
-
receivesDeliverable: true
|
|
6334
|
+
receivesDeliverable: true,
|
|
6335
|
+
// And saves the images a prompt names as files for its agent (`promptImages`).
|
|
6336
|
+
receivesPromptImages: true,
|
|
6337
|
+
// And checks out a non-code task's repository for it to read (`referenceRepository`).
|
|
6338
|
+
checksOutReferenceRepository: true
|
|
4646
6339
|
},
|
|
4647
6340
|
activeSessionIds: this.heartbeatSessionIds(),
|
|
4648
6341
|
maxConcurrentSessions: this.opts.config.maxSessions,
|
|
@@ -4751,7 +6444,7 @@ var RunnerDaemon = class {
|
|
|
4751
6444
|
if (this.droppedSessionIds.has(id)) return;
|
|
4752
6445
|
this.droppedSessionIds.add(id);
|
|
4753
6446
|
this.opts.logger.warn(
|
|
4754
|
-
`session ${id}: not a Discovery Tree session id, so it is left out of the heartbeat (its state is in ${
|
|
6447
|
+
`session ${id}: not a Discovery Tree session id, so it is left out of the heartbeat (its state is in ${join13(this.opts.config.stateDir, "sessions", id)})`
|
|
4755
6448
|
);
|
|
4756
6449
|
});
|
|
4757
6450
|
}
|
|
@@ -4857,8 +6550,8 @@ var RunnerDaemon = class {
|
|
|
4857
6550
|
error: result.error
|
|
4858
6551
|
});
|
|
4859
6552
|
}
|
|
4860
|
-
if (result.signInFailed) this.
|
|
4861
|
-
else if (result.ok) this.
|
|
6553
|
+
if (result.signInFailed) this.agentSignIn(false);
|
|
6554
|
+
else if (result.ok) this.agentSignIn(true);
|
|
4862
6555
|
for (let attempt = 0; attempt < 5; attempt++) {
|
|
4863
6556
|
try {
|
|
4864
6557
|
await this.api.postCompletion(req.id, result);
|
|
@@ -4897,6 +6590,37 @@ var RunnerDaemon = class {
|
|
|
4897
6590
|
});
|
|
4898
6591
|
}
|
|
4899
6592
|
};
|
|
6593
|
+
var OPTIONAL_AGENTS = [
|
|
6594
|
+
{
|
|
6595
|
+
driver: codexDriver,
|
|
6596
|
+
version: "codexVersion",
|
|
6597
|
+
ready: "codexReady",
|
|
6598
|
+
problem: "codexProblem",
|
|
6599
|
+
runs: "runsCodex"
|
|
6600
|
+
},
|
|
6601
|
+
{
|
|
6602
|
+
driver: cursorDriver,
|
|
6603
|
+
version: "cursorVersion",
|
|
6604
|
+
ready: "cursorReady",
|
|
6605
|
+
problem: "cursorProblem",
|
|
6606
|
+
runs: "runsCursor"
|
|
6607
|
+
}
|
|
6608
|
+
];
|
|
6609
|
+
function readAgentFields(info, agent) {
|
|
6610
|
+
return {
|
|
6611
|
+
version: info[agent.version] ?? null,
|
|
6612
|
+
ready: info[agent.ready] ?? null,
|
|
6613
|
+
problem: info[agent.problem] ?? null
|
|
6614
|
+
};
|
|
6615
|
+
}
|
|
6616
|
+
function withAgentFields(info, agent, fields) {
|
|
6617
|
+
return {
|
|
6618
|
+
...info,
|
|
6619
|
+
[agent.version]: fields.version,
|
|
6620
|
+
[agent.ready]: fields.ready,
|
|
6621
|
+
[agent.problem]: fields.problem
|
|
6622
|
+
};
|
|
6623
|
+
}
|
|
4900
6624
|
|
|
4901
6625
|
// src/doctor.ts
|
|
4902
6626
|
async function runDoctor(env = process.env) {
|
|
@@ -4931,39 +6655,7 @@ async function runDoctor(env = process.env) {
|
|
|
4931
6655
|
detail: "not installed (no `gh` on PATH): pull requests cannot be opened as you; see https://cli.github.com"
|
|
4932
6656
|
});
|
|
4933
6657
|
}
|
|
4934
|
-
const
|
|
4935
|
-
if (!bin) {
|
|
4936
|
-
checks.push({
|
|
4937
|
-
name: "Claude Code",
|
|
4938
|
-
level: "fail",
|
|
4939
|
-
detail: env.DT_RUNNER_CLAUDE_BIN ? `DT_RUNNER_CLAUDE_BIN=${env.DT_RUNNER_CLAUDE_BIN} was not found` : "not installed: see https://docs.claude.com/en/docs/claude-code (no `claude` on PATH)"
|
|
4940
|
-
});
|
|
4941
|
-
} else {
|
|
4942
|
-
const version = await claudeVersion(bin);
|
|
4943
|
-
checks.push({
|
|
4944
|
-
name: "Claude Code",
|
|
4945
|
-
level: version ? "ok" : "fail",
|
|
4946
|
-
detail: version ? `${version} (${bin})` : `${bin} --version failed`
|
|
4947
|
-
});
|
|
4948
|
-
if (version) {
|
|
4949
|
-
const auth = await claudeAuthStatus(bin);
|
|
4950
|
-
checks.push(
|
|
4951
|
-
auth.loggedIn === true ? {
|
|
4952
|
-
name: "Claude sign-in",
|
|
4953
|
-
level: "ok",
|
|
4954
|
-
detail: `signed in${auth.authMethod ? ` (${auth.authMethod})` : ""}`
|
|
4955
|
-
} : auth.loggedIn === false ? {
|
|
4956
|
-
name: "Claude sign-in",
|
|
4957
|
-
level: "fail",
|
|
4958
|
-
detail: "not signed in: run `claude` and sign in with your Claude account"
|
|
4959
|
-
} : {
|
|
4960
|
-
name: "Claude sign-in",
|
|
4961
|
-
level: "warn",
|
|
4962
|
-
detail: "could not tell (this Claude Code has no `claude auth status`); update Claude Code"
|
|
4963
|
-
}
|
|
4964
|
-
);
|
|
4965
|
-
}
|
|
4966
|
-
}
|
|
6658
|
+
for (const kind of agentDriverKinds()) checks.push(...await agentDriver(kind).doctor(env));
|
|
4967
6659
|
if (env.ANTHROPIC_API_KEY) {
|
|
4968
6660
|
checks.push({
|
|
4969
6661
|
name: "ANTHROPIC_API_KEY",
|
|
@@ -4979,10 +6671,10 @@ function formatChecks(checks) {
|
|
|
4979
6671
|
}
|
|
4980
6672
|
|
|
4981
6673
|
// src/lock.ts
|
|
4982
|
-
import { mkdir as
|
|
4983
|
-
import { join as
|
|
6674
|
+
import { mkdir as mkdir8, open, readFile as readFile5, rm as rm7 } from "node:fs/promises";
|
|
6675
|
+
import { join as join14 } from "node:path";
|
|
4984
6676
|
function lockFile(stateDir) {
|
|
4985
|
-
return
|
|
6677
|
+
return join14(stateDir, "daemon.pid");
|
|
4986
6678
|
}
|
|
4987
6679
|
function pidAlive(pid) {
|
|
4988
6680
|
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
@@ -5004,7 +6696,7 @@ async function lockHolder(stateDir) {
|
|
|
5004
6696
|
return pidAlive(pid) && pid !== process.pid ? pid : null;
|
|
5005
6697
|
}
|
|
5006
6698
|
async function acquireDaemonLock(stateDir, pid = process.pid) {
|
|
5007
|
-
await
|
|
6699
|
+
await mkdir8(stateDir, { recursive: true, mode: 448 });
|
|
5008
6700
|
const file = lockFile(stateDir);
|
|
5009
6701
|
for (let attempt = 0; attempt < 3; attempt++) {
|
|
5010
6702
|
try {
|
|
@@ -5020,8 +6712,8 @@ async function acquireDaemonLock(stateDir, pid = process.pid) {
|
|
|
5020
6712
|
lock: {
|
|
5021
6713
|
file,
|
|
5022
6714
|
async release() {
|
|
5023
|
-
const
|
|
5024
|
-
if (Number.parseInt(
|
|
6715
|
+
const current2 = await readFile5(file, "utf8").catch(() => "");
|
|
6716
|
+
if (Number.parseInt(current2.trim(), 10) === pid) await rm7(file, { force: true });
|
|
5025
6717
|
}
|
|
5026
6718
|
}
|
|
5027
6719
|
};
|
|
@@ -5038,7 +6730,7 @@ async function acquireDaemonLock(stateDir, pid = process.pid) {
|
|
|
5038
6730
|
}
|
|
5039
6731
|
|
|
5040
6732
|
// src/pairing.ts
|
|
5041
|
-
import { spawn as
|
|
6733
|
+
import { spawn as spawn5 } from "node:child_process";
|
|
5042
6734
|
async function pair(api, opts) {
|
|
5043
6735
|
const start2 = await api.startPairing({ name: opts.name, platform: RUNNER_PLATFORM });
|
|
5044
6736
|
opts.ui.showCode(start2.userCode, start2.verificationUrl, start2.expiresInSeconds);
|
|
@@ -5102,7 +6794,7 @@ function openUrl(url) {
|
|
|
5102
6794
|
if (!/^https?:\/\//i.test(url)) return;
|
|
5103
6795
|
const [cmd, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", url]] : ["xdg-open", [url]];
|
|
5104
6796
|
try {
|
|
5105
|
-
const child =
|
|
6797
|
+
const child = spawn5(cmd, args, { stdio: "ignore", detached: true, windowsHide: true });
|
|
5106
6798
|
child.on("error", () => void 0);
|
|
5107
6799
|
child.unref();
|
|
5108
6800
|
} catch {
|
|
@@ -5178,7 +6870,7 @@ async function main(argv) {
|
|
|
5178
6870
|
case "status":
|
|
5179
6871
|
return status();
|
|
5180
6872
|
case "doctor":
|
|
5181
|
-
return
|
|
6873
|
+
return doctor4();
|
|
5182
6874
|
case "logout":
|
|
5183
6875
|
return logout();
|
|
5184
6876
|
default:
|
|
@@ -5223,7 +6915,7 @@ async function login(server, name, openBrowser, yes) {
|
|
|
5223
6915
|
isTTY: process.stdin.isTTY === true,
|
|
5224
6916
|
print: (line) => console.log(line),
|
|
5225
6917
|
async ask(question) {
|
|
5226
|
-
const rl =
|
|
6918
|
+
const rl = createInterface3({ input: process.stdin, output: process.stdout });
|
|
5227
6919
|
try {
|
|
5228
6920
|
return await rl.question(question);
|
|
5229
6921
|
} finally {
|
|
@@ -5266,6 +6958,27 @@ async function start(opts) {
|
|
|
5266
6958
|
"ANTHROPIC_API_KEY is set: Claude Code will bill that API key, not your Claude subscription. Unset it unless that is what you want."
|
|
5267
6959
|
);
|
|
5268
6960
|
}
|
|
6961
|
+
const codexKey = codexKeyVariable(process.env);
|
|
6962
|
+
if (codexKey) {
|
|
6963
|
+
logger.warn(
|
|
6964
|
+
`${codexKey} is set: Codex runs may bill that API key, not your ChatGPT plan. Unset it unless that is what you want.`
|
|
6965
|
+
);
|
|
6966
|
+
}
|
|
6967
|
+
if (config.codexSandbox === "danger-full-access") {
|
|
6968
|
+
logger.warn(
|
|
6969
|
+
'codexSandbox is danger-full-access: Codex runs can run ANY command and edit ANY file on this computer. Remove "codexSandbox" from the config to go back to workspace-write.'
|
|
6970
|
+
);
|
|
6971
|
+
}
|
|
6972
|
+
if (cursorKeyVariable(process.env)) {
|
|
6973
|
+
logger.warn(
|
|
6974
|
+
"CURSOR_API_KEY is set: Cursor runs sign in with that API key, not your `cursor-agent login`. Unset it unless that is what you want."
|
|
6975
|
+
);
|
|
6976
|
+
}
|
|
6977
|
+
if (config.cursorForce) {
|
|
6978
|
+
logger.warn(
|
|
6979
|
+
'cursorForce is on: Cursor runs get --force and can run ANY command and edit ANY file on this computer without asking. Remove "cursorForce" from the config to turn it off.'
|
|
6980
|
+
);
|
|
6981
|
+
}
|
|
5269
6982
|
if (config.permissionMode === "bypassPermissions") {
|
|
5270
6983
|
logger.warn(
|
|
5271
6984
|
"!!! permissionMode is bypassPermissions: Claude Code will run ANY command and edit ANY file on this computer without asking. !!!"
|
|
@@ -5281,6 +6994,15 @@ async function start(opts) {
|
|
|
5281
6994
|
);
|
|
5282
6995
|
return 1;
|
|
5283
6996
|
}
|
|
6997
|
+
if (process.platform === "win32") {
|
|
6998
|
+
void startJobHelper().then((ok) => {
|
|
6999
|
+
if (!ok) {
|
|
7000
|
+
logger.warn(
|
|
7001
|
+
"Could not set up Windows job objects (PowerShell unavailable?); processes a run leaves behind are found by parent process id instead."
|
|
7002
|
+
);
|
|
7003
|
+
}
|
|
7004
|
+
});
|
|
7005
|
+
}
|
|
5284
7006
|
const daemon = new RunnerDaemon({ config, logger });
|
|
5285
7007
|
let signals = 0;
|
|
5286
7008
|
const onSignal = (sig) => {
|
|
@@ -5335,7 +7057,7 @@ async function status() {
|
|
|
5335
7057
|
}
|
|
5336
7058
|
console.log("Daemon: not running");
|
|
5337
7059
|
try {
|
|
5338
|
-
const agent = await
|
|
7060
|
+
const agent = await agentDriver().probe();
|
|
5339
7061
|
const res = await api.heartbeat({
|
|
5340
7062
|
protocolVersion: RUNNER_PROTOCOL_VERSION,
|
|
5341
7063
|
runnerVersion: RUNNER_VERSION,
|
|
@@ -5365,7 +7087,7 @@ async function status() {
|
|
|
5365
7087
|
return 1;
|
|
5366
7088
|
}
|
|
5367
7089
|
}
|
|
5368
|
-
async function
|
|
7090
|
+
async function doctor4() {
|
|
5369
7091
|
const checks = await runDoctor();
|
|
5370
7092
|
console.log(formatChecks(checks));
|
|
5371
7093
|
const failed = checks.some((c) => c.level === "fail");
|