@discovery-tree/runner 0.1.14 → 0.1.16
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 +97 -17
- package/dist/cli.js +2741 -1145
- 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,10 @@ 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/design-review-images.ts
|
|
52
|
+
var MAX_REVIEW_IMAGES_PER_RUN = 12;
|
|
53
|
+
var MAX_REVIEW_IMAGE_CAPTION_LENGTH = 300;
|
|
54
|
+
|
|
51
55
|
// ../contracts/src/automated-review.ts
|
|
52
56
|
var REVIEW_AGENT_ROUND_STALE_MS = 30 * 6e4;
|
|
53
57
|
|
|
@@ -61,6 +65,7 @@ var RUNNER_SESSION_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-
|
|
|
61
65
|
function isRunnerSessionId(value) {
|
|
62
66
|
return typeof value === "string" && RUNNER_SESSION_ID_RE.test(value);
|
|
63
67
|
}
|
|
68
|
+
var RUNNER_REVIEW_IMAGE_MAX_BYTES = 5e6;
|
|
64
69
|
var RUNNER_DELIVERABLE_FILE = "DELIVERABLE.md";
|
|
65
70
|
var RUNNER_COMPLETION_MAX_TEXT = 2e5;
|
|
66
71
|
|
|
@@ -110,7 +115,7 @@ function toolGrantRepositoryKey(url) {
|
|
|
110
115
|
}
|
|
111
116
|
|
|
112
117
|
// src/version.ts
|
|
113
|
-
var RUNNER_VERSION = true ? "0.1.
|
|
118
|
+
var RUNNER_VERSION = true ? "0.1.16" : "0.0.0-dev";
|
|
114
119
|
var RUNNER_PLATFORM = `${process.platform}-${process.arch}`;
|
|
115
120
|
|
|
116
121
|
// src/api.ts
|
|
@@ -183,6 +188,16 @@ var RunnerApi = class {
|
|
|
183
188
|
postEvents(sessionId, body) {
|
|
184
189
|
return this.request("POST", `/runner/sessions/${encodeURIComponent(sessionId)}/events`, body);
|
|
185
190
|
}
|
|
191
|
+
/** An image the agent rendered of a design proposal, attached to the session's task. */
|
|
192
|
+
postReviewImage(sessionId, body) {
|
|
193
|
+
return this.request(
|
|
194
|
+
"POST",
|
|
195
|
+
`/runner/sessions/${encodeURIComponent(sessionId)}/review-images`,
|
|
196
|
+
body,
|
|
197
|
+
// A few megabytes each way on a home connection.
|
|
198
|
+
{ timeoutMs: Math.max(this.timeoutMs, 12e4) }
|
|
199
|
+
);
|
|
200
|
+
}
|
|
186
201
|
/** Unauthenticated reachability check (`dt-runner status`). */
|
|
187
202
|
async health() {
|
|
188
203
|
try {
|
|
@@ -233,15 +248,247 @@ import { tmpdir } from "node:os";
|
|
|
233
248
|
import { isAbsolute as isAbsolute2, join as join3 } from "node:path";
|
|
234
249
|
|
|
235
250
|
// src/exec.ts
|
|
236
|
-
import { spawn as
|
|
251
|
+
import { spawn as spawn3 } from "node:child_process";
|
|
237
252
|
import { access, constants } from "node:fs/promises";
|
|
238
253
|
import { delimiter, isAbsolute, join } from "node:path";
|
|
239
254
|
|
|
240
255
|
// src/process-tree.ts
|
|
241
|
-
import { spawn, spawnSync } from "node:child_process";
|
|
256
|
+
import { spawn as spawn2, spawnSync } from "node:child_process";
|
|
257
|
+
|
|
258
|
+
// src/windows-job.ts
|
|
259
|
+
import { spawn } from "node:child_process";
|
|
260
|
+
import { createInterface } from "node:readline";
|
|
261
|
+
var HELPER_SCRIPT = String.raw`
|
|
262
|
+
$ErrorActionPreference = 'Stop'
|
|
263
|
+
Add-Type -TypeDefinition @'
|
|
264
|
+
using System;
|
|
265
|
+
using System.Collections.Generic;
|
|
266
|
+
using System.Runtime.InteropServices;
|
|
267
|
+
public static class DtRunnerJobs {
|
|
268
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
269
|
+
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; }
|
|
270
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
271
|
+
struct Io { public ulong A, B, C, D, E, F; }
|
|
272
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
273
|
+
struct Extended { public Basic Basic; public Io Io; public UIntPtr A, B, C, D; }
|
|
274
|
+
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
|
275
|
+
static extern IntPtr CreateJobObjectW(IntPtr attributes, string name);
|
|
276
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
277
|
+
static extern bool SetInformationJobObject(IntPtr job, int infoClass, ref Extended info, uint size);
|
|
278
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
279
|
+
static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);
|
|
280
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
281
|
+
static extern bool TerminateJobObject(IntPtr job, uint exitCode);
|
|
282
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
283
|
+
static extern IntPtr OpenProcess(uint access, bool inherit, uint pid);
|
|
284
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
285
|
+
static extern bool GetProcessTimes(IntPtr process, out long creation, out long exit, out long kernel, out long user);
|
|
286
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
287
|
+
static extern bool CloseHandle(IntPtr handle);
|
|
288
|
+
static readonly Dictionary<string, IntPtr> jobs = new Dictionary<string, IntPtr>();
|
|
289
|
+
static string Assign(string id, uint pid, long notAfterMs) {
|
|
290
|
+
IntPtr job = CreateJobObjectW(IntPtr.Zero, null);
|
|
291
|
+
if (job == IntPtr.Zero) return "err " + id + " CreateJobObject " + Marshal.GetLastWin32Error();
|
|
292
|
+
Extended info = new Extended();
|
|
293
|
+
info.Basic.LimitFlags = 0x2000; // JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
|
|
294
|
+
if (!SetInformationJobObject(job, 9, ref info, (uint)Marshal.SizeOf(typeof(Extended)))) {
|
|
295
|
+
int e = Marshal.GetLastWin32Error();
|
|
296
|
+
CloseHandle(job);
|
|
297
|
+
return "err " + id + " SetInformationJobObject " + e;
|
|
298
|
+
}
|
|
299
|
+
// PROCESS_SET_QUOTA | PROCESS_TERMINATE | PROCESS_QUERY_LIMITED_INFORMATION
|
|
300
|
+
IntPtr process = OpenProcess(0x1101, false, pid);
|
|
301
|
+
if (process == IntPtr.Zero) {
|
|
302
|
+
int e = Marshal.GetLastWin32Error();
|
|
303
|
+
CloseHandle(job);
|
|
304
|
+
return "err " + id + " OpenProcess " + e;
|
|
305
|
+
}
|
|
306
|
+
// A process created after the one we were told about holds a reused pid: not ours.
|
|
307
|
+
long creation, exit, kernel, user;
|
|
308
|
+
if (!GetProcessTimes(process, out creation, out exit, out kernel, out user) ||
|
|
309
|
+
(DateTime.FromFileTimeUtc(creation) - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds > notAfterMs) {
|
|
310
|
+
CloseHandle(process);
|
|
311
|
+
CloseHandle(job);
|
|
312
|
+
return "err " + id + " not the process asked for";
|
|
313
|
+
}
|
|
314
|
+
bool ok = AssignProcessToJobObject(job, process);
|
|
315
|
+
int error = Marshal.GetLastWin32Error();
|
|
316
|
+
CloseHandle(process);
|
|
317
|
+
if (!ok) {
|
|
318
|
+
CloseHandle(job);
|
|
319
|
+
return "err " + id + " AssignProcessToJobObject " + error;
|
|
320
|
+
}
|
|
321
|
+
jobs[id] = job;
|
|
322
|
+
return "ok " + id;
|
|
323
|
+
}
|
|
324
|
+
static string Kill(string id) {
|
|
325
|
+
IntPtr job;
|
|
326
|
+
if (jobs.TryGetValue(id, out job)) {
|
|
327
|
+
jobs.Remove(id);
|
|
328
|
+
TerminateJobObject(job, 1);
|
|
329
|
+
CloseHandle(job);
|
|
330
|
+
}
|
|
331
|
+
return "killed " + id;
|
|
332
|
+
}
|
|
333
|
+
public static string Run(string line) {
|
|
334
|
+
string[] parts = line.Split(' ');
|
|
335
|
+
if (parts.Length == 4 && parts[0] == "assign") return Assign(parts[1], UInt32.Parse(parts[2]), Int64.Parse(parts[3]));
|
|
336
|
+
if (parts.Length == 2 && parts[0] == "kill") return Kill(parts[1]);
|
|
337
|
+
return "err ? unknown request";
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
'@
|
|
341
|
+
[Console]::Out.WriteLine('ready')
|
|
342
|
+
[Console]::Out.Flush()
|
|
343
|
+
while ($true) {
|
|
344
|
+
$line = [Console]::In.ReadLine()
|
|
345
|
+
if ($null -eq $line) { break }
|
|
346
|
+
try { $answer = [DtRunnerJobs]::Run($line) } catch { $answer = 'err ? ' + ($_ -replace '[\r\n]', ' ') }
|
|
347
|
+
[Console]::Out.WriteLine($answer)
|
|
348
|
+
[Console]::Out.Flush()
|
|
349
|
+
}
|
|
350
|
+
`;
|
|
351
|
+
var READY_TIMEOUT_MS = 3e4;
|
|
352
|
+
var ANSWER_TIMEOUT_MS = 1e4;
|
|
353
|
+
var JobHelper = class {
|
|
354
|
+
ready;
|
|
355
|
+
child;
|
|
356
|
+
waiting = /* @__PURE__ */ new Map();
|
|
357
|
+
exited = false;
|
|
358
|
+
constructor() {
|
|
359
|
+
this.child = spawn(
|
|
360
|
+
"powershell.exe",
|
|
361
|
+
[
|
|
362
|
+
"-NoLogo",
|
|
363
|
+
"-NoProfile",
|
|
364
|
+
"-NonInteractive",
|
|
365
|
+
"-ExecutionPolicy",
|
|
366
|
+
"Bypass",
|
|
367
|
+
"-EncodedCommand",
|
|
368
|
+
Buffer.from(HELPER_SCRIPT, "utf16le").toString("base64")
|
|
369
|
+
],
|
|
370
|
+
{ stdio: ["pipe", "pipe", "ignore"], windowsHide: true }
|
|
371
|
+
);
|
|
372
|
+
let onReady = () => void 0;
|
|
373
|
+
this.ready = new Promise((resolve2) => {
|
|
374
|
+
const timer = setTimeout(() => resolve2(false), READY_TIMEOUT_MS);
|
|
375
|
+
timer.unref();
|
|
376
|
+
onReady = (ok) => {
|
|
377
|
+
clearTimeout(timer);
|
|
378
|
+
resolve2(ok);
|
|
379
|
+
};
|
|
380
|
+
});
|
|
381
|
+
const lines = createInterface({ input: this.child.stdout, crlfDelay: Infinity });
|
|
382
|
+
lines.on("line", (line) => {
|
|
383
|
+
const text = line.trim();
|
|
384
|
+
if (text === "ready") return onReady(true);
|
|
385
|
+
const id = text.split(" ")[1];
|
|
386
|
+
const answer = id ? this.waiting.get(id) : void 0;
|
|
387
|
+
if (answer) {
|
|
388
|
+
this.waiting.delete(id);
|
|
389
|
+
answer(text);
|
|
390
|
+
}
|
|
391
|
+
});
|
|
392
|
+
const gone = () => {
|
|
393
|
+
if (this.exited) return;
|
|
394
|
+
this.exited = true;
|
|
395
|
+
onReady(false);
|
|
396
|
+
for (const answer of this.waiting.values()) answer("err gone");
|
|
397
|
+
this.waiting.clear();
|
|
398
|
+
if (helper === this) helper = null;
|
|
399
|
+
};
|
|
400
|
+
this.child.on("error", gone);
|
|
401
|
+
this.child.on("exit", gone);
|
|
402
|
+
this.child.stdin.on("error", () => void 0);
|
|
403
|
+
this.child.unref();
|
|
404
|
+
this.child.stdout.unref?.();
|
|
405
|
+
this.child.stdin.unref?.();
|
|
406
|
+
}
|
|
407
|
+
get alive() {
|
|
408
|
+
return !this.exited;
|
|
409
|
+
}
|
|
410
|
+
/** Puts the process in a job of its own; resolves to the job's id, or null when it could not. */
|
|
411
|
+
async assign(target, startedBy) {
|
|
412
|
+
if (!await this.ready) return null;
|
|
413
|
+
if (!target.pid || target.exitCode !== null || target.signalCode !== null) return null;
|
|
414
|
+
const id = `j${++jobSeq}`;
|
|
415
|
+
const answer = await this.ask(`assign ${id} ${target.pid} ${Math.ceil(startedBy)}`, id);
|
|
416
|
+
return answer.startsWith("ok ") ? id : null;
|
|
417
|
+
}
|
|
418
|
+
/** Ends every process in the job, and the job. */
|
|
419
|
+
async kill(id) {
|
|
420
|
+
if (!await this.ready) return;
|
|
421
|
+
await this.ask(`kill ${id}`, id);
|
|
422
|
+
}
|
|
423
|
+
/** Ends the helper, and with it every job it holds. Synchronous: safe in an exit hook. */
|
|
424
|
+
close() {
|
|
425
|
+
if (this.exited) return;
|
|
426
|
+
try {
|
|
427
|
+
this.child.kill();
|
|
428
|
+
} catch {
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
ask(request, id) {
|
|
432
|
+
if (this.exited) return Promise.resolve("err gone");
|
|
433
|
+
return new Promise((resolve2) => {
|
|
434
|
+
const timer = setTimeout(() => {
|
|
435
|
+
this.waiting.delete(id);
|
|
436
|
+
resolve2("err timeout");
|
|
437
|
+
}, ANSWER_TIMEOUT_MS);
|
|
438
|
+
timer.unref();
|
|
439
|
+
this.waiting.set(id, (answer) => {
|
|
440
|
+
clearTimeout(timer);
|
|
441
|
+
resolve2(answer);
|
|
442
|
+
});
|
|
443
|
+
this.child.stdin.write(request + "\n");
|
|
444
|
+
});
|
|
445
|
+
}
|
|
446
|
+
};
|
|
447
|
+
var helper = null;
|
|
448
|
+
var jobSeq = 0;
|
|
449
|
+
var disabled = process.platform !== "win32";
|
|
450
|
+
function current() {
|
|
451
|
+
if (disabled) return null;
|
|
452
|
+
if (!helper || !helper.alive) helper = new JobHelper();
|
|
453
|
+
return helper;
|
|
454
|
+
}
|
|
455
|
+
async function startJobHelper() {
|
|
456
|
+
const h = current();
|
|
457
|
+
if (!h) return false;
|
|
458
|
+
const ok = await h.ready;
|
|
459
|
+
if (!ok) {
|
|
460
|
+
disabled = true;
|
|
461
|
+
h.close();
|
|
462
|
+
}
|
|
463
|
+
return ok;
|
|
464
|
+
}
|
|
465
|
+
async function assignToJob(target, startedBy) {
|
|
466
|
+
const h = current();
|
|
467
|
+
if (!h) return null;
|
|
468
|
+
try {
|
|
469
|
+
return await h.assign(target, startedBy);
|
|
470
|
+
} catch {
|
|
471
|
+
return null;
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
async function terminateJob(id) {
|
|
475
|
+
if (!id || !helper) return;
|
|
476
|
+
try {
|
|
477
|
+
await helper.kill(id);
|
|
478
|
+
} catch {
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
function closeJobHelper() {
|
|
482
|
+
helper?.close();
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
// src/process-tree.ts
|
|
242
486
|
var OWN_PROCESS_GROUP = process.platform !== "win32";
|
|
243
487
|
var liveTrees = /* @__PURE__ */ new Map();
|
|
244
488
|
var exitHookInstalled = false;
|
|
489
|
+
var CENSUS_INTERVAL_MS = 3e4;
|
|
490
|
+
var censusTimer = null;
|
|
491
|
+
var censusRunning = false;
|
|
245
492
|
function trackTree(child, cwd) {
|
|
246
493
|
if (!child.pid) return null;
|
|
247
494
|
const tree = {
|
|
@@ -249,11 +496,20 @@ function trackTree(child, cwd) {
|
|
|
249
496
|
startedAt: Date.now() - 2e3,
|
|
250
497
|
...cwd ? { cwd } : {}
|
|
251
498
|
};
|
|
252
|
-
liveTrees.set(child.pid, {
|
|
499
|
+
liveTrees.set(child.pid, { tree, child });
|
|
500
|
+
if (!OWN_PROCESS_GROUP) {
|
|
501
|
+
const startedBy = Date.now() + 1e3;
|
|
502
|
+
tree.job = assignToJob(child, startedBy);
|
|
503
|
+
startCensus();
|
|
504
|
+
}
|
|
253
505
|
if (!exitHookInstalled) {
|
|
254
506
|
exitHookInstalled = true;
|
|
255
507
|
process.once("exit", () => {
|
|
256
|
-
|
|
508
|
+
closeJobHelper();
|
|
509
|
+
for (const {
|
|
510
|
+
tree: { pid },
|
|
511
|
+
child: root
|
|
512
|
+
} of liveTrees.values()) {
|
|
257
513
|
if (OWN_PROCESS_GROUP) signalGroup(pid, "SIGKILL");
|
|
258
514
|
else if (root.exitCode === null && root.signalCode === null) {
|
|
259
515
|
spawnSync("taskkill", ["/pid", String(pid), "/T", "/F"], {
|
|
@@ -274,7 +530,7 @@ function signalTree(child, signal) {
|
|
|
274
530
|
return;
|
|
275
531
|
}
|
|
276
532
|
if (signal === "SIGKILL") {
|
|
277
|
-
const tk =
|
|
533
|
+
const tk = spawn2("taskkill", ["/pid", String(child.pid), "/T", "/F"], {
|
|
278
534
|
stdio: "ignore",
|
|
279
535
|
windowsHide: true
|
|
280
536
|
});
|
|
@@ -305,14 +561,68 @@ async function reapTree(tree, graceMs = 2e3, deps = {}) {
|
|
|
305
561
|
signalGroup(tree.pid, "SIGKILL");
|
|
306
562
|
return;
|
|
307
563
|
}
|
|
564
|
+
await (deps.terminateJob ?? terminateJob)(await tree.job);
|
|
308
565
|
const rows = await (deps.listProcesses ?? listWindowsProcesses)();
|
|
309
566
|
const orphans = descendantsOf(tree, rows);
|
|
310
567
|
if (orphans.length) await (deps.kill ?? taskkillTrees)(orphans);
|
|
311
568
|
} catch {
|
|
312
569
|
} finally {
|
|
313
|
-
if (liveTrees.get(tree.pid)?.startedAt === tree.startedAt) liveTrees.delete(tree.pid);
|
|
570
|
+
if (liveTrees.get(tree.pid)?.tree.startedAt === tree.startedAt) liveTrees.delete(tree.pid);
|
|
571
|
+
if (liveTrees.size === 0) stopCensus();
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
function recordDescendants(tree, rows) {
|
|
575
|
+
const byPid = new Map(rows.map((r) => [r.pid, r]));
|
|
576
|
+
const seen = tree.seen ?? /* @__PURE__ */ new Map();
|
|
577
|
+
for (const [pid, createdAt] of seen) {
|
|
578
|
+
if (!sameProcess(byPid.get(pid), createdAt)) seen.delete(pid);
|
|
579
|
+
}
|
|
580
|
+
for (const pid of descendantsOf(tree, rows)) {
|
|
581
|
+
const row = byPid.get(pid);
|
|
582
|
+
if (row) seen.set(pid, row.createdAt);
|
|
583
|
+
}
|
|
584
|
+
tree.seen = seen;
|
|
585
|
+
}
|
|
586
|
+
async function snapshotTree(tree, deps = {}, timeoutMs = 5e3) {
|
|
587
|
+
if (!tree || OWN_PROCESS_GROUP) return;
|
|
588
|
+
let timer;
|
|
589
|
+
try {
|
|
590
|
+
const rows = await Promise.race([
|
|
591
|
+
(deps.listProcesses ?? listWindowsProcesses)(),
|
|
592
|
+
new Promise((r) => timer = setTimeout(() => r(null), timeoutMs))
|
|
593
|
+
]);
|
|
594
|
+
if (rows) recordDescendants(tree, rows);
|
|
595
|
+
} catch {
|
|
596
|
+
} finally {
|
|
597
|
+
if (timer) clearTimeout(timer);
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
function startCensus() {
|
|
601
|
+
if (censusTimer) return;
|
|
602
|
+
censusTimer = setInterval(() => void census(), CENSUS_INTERVAL_MS);
|
|
603
|
+
censusTimer.unref();
|
|
604
|
+
}
|
|
605
|
+
function stopCensus() {
|
|
606
|
+
if (!censusTimer) return;
|
|
607
|
+
clearInterval(censusTimer);
|
|
608
|
+
censusTimer = null;
|
|
609
|
+
}
|
|
610
|
+
async function census() {
|
|
611
|
+
if (censusRunning || liveTrees.size === 0) return;
|
|
612
|
+
censusRunning = true;
|
|
613
|
+
try {
|
|
614
|
+
const rows = await listWindowsProcesses();
|
|
615
|
+
for (const { tree, child } of liveTrees.values()) {
|
|
616
|
+
if (child.exitCode === null && child.signalCode === null) recordDescendants(tree, rows);
|
|
617
|
+
}
|
|
618
|
+
} catch {
|
|
619
|
+
} finally {
|
|
620
|
+
censusRunning = false;
|
|
314
621
|
}
|
|
315
622
|
}
|
|
623
|
+
function sameProcess(row, createdAt) {
|
|
624
|
+
return !!row && Math.abs(row.createdAt - createdAt) <= 1e3;
|
|
625
|
+
}
|
|
316
626
|
function descendantsOf(tree, rows) {
|
|
317
627
|
const byParent = /* @__PURE__ */ new Map();
|
|
318
628
|
const byPid = /* @__PURE__ */ new Map();
|
|
@@ -329,9 +639,18 @@ function descendantsOf(tree, rows) {
|
|
|
329
639
|
const queue = [
|
|
330
640
|
{ pid: tree.pid, since: tree.startedAt, until: reusedAt }
|
|
331
641
|
];
|
|
642
|
+
if (tree.seen) {
|
|
643
|
+
for (const [pid, createdAt] of tree.seen) {
|
|
644
|
+
const row = byPid.get(pid);
|
|
645
|
+
if (seen.has(pid) || !sameProcess(row, createdAt)) continue;
|
|
646
|
+
seen.add(pid);
|
|
647
|
+
out.push(pid);
|
|
648
|
+
queue.push({ pid, since: row.createdAt - 1e3, until: null });
|
|
649
|
+
}
|
|
650
|
+
}
|
|
332
651
|
if (tree.cwd) {
|
|
333
652
|
for (const row of rows) {
|
|
334
|
-
if (row.pid
|
|
653
|
+
if (seen.has(row.pid) || row.createdAt < tree.startedAt) continue;
|
|
335
654
|
const parent = byPid.get(row.ppid);
|
|
336
655
|
const orphaned = !parent || parent.createdAt > row.createdAt;
|
|
337
656
|
if (orphaned && namesPathIn(row.commandLine, tree.cwd)) {
|
|
@@ -371,7 +690,7 @@ function namesPathIn(commandLine, dir) {
|
|
|
371
690
|
function listWindowsProcesses() {
|
|
372
691
|
const script = `$ErrorActionPreference='SilentlyContinue';Get-CimInstance Win32_Process | ForEach-Object { if ($_.CreationDate) { "$($_.ProcessId) $($_.ParentProcessId) $(([DateTimeOffset]$_.CreationDate).ToUnixTimeMilliseconds()) $($_.CommandLine -replace "[\\r\\n]", " ")" } }`;
|
|
373
692
|
return new Promise((resolve2, reject) => {
|
|
374
|
-
const ps =
|
|
693
|
+
const ps = spawn2(
|
|
375
694
|
"powershell.exe",
|
|
376
695
|
["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script],
|
|
377
696
|
{ stdio: ["ignore", "pipe", "ignore"], windowsHide: true }
|
|
@@ -408,7 +727,7 @@ async function taskkillTrees(pids) {
|
|
|
408
727
|
for (let i = 0; i < pids.length; i += 50) {
|
|
409
728
|
const args = pids.slice(i, i + 50).flatMap((p) => ["/pid", String(p)]);
|
|
410
729
|
await new Promise((resolve2) => {
|
|
411
|
-
const tk =
|
|
730
|
+
const tk = spawn2("taskkill", [...args, "/T", "/F"], { stdio: "ignore", windowsHide: true });
|
|
412
731
|
tk.on("error", () => resolve2());
|
|
413
732
|
tk.on("close", () => resolve2());
|
|
414
733
|
});
|
|
@@ -426,7 +745,7 @@ function signalGroup(pgid, signal) {
|
|
|
426
745
|
// src/exec.ts
|
|
427
746
|
function exec(cmd, args, opts = {}) {
|
|
428
747
|
return new Promise((resolve2, reject) => {
|
|
429
|
-
const child =
|
|
748
|
+
const child = spawn3(cmd, args, {
|
|
430
749
|
cwd: opts.cwd,
|
|
431
750
|
env: opts.env ?? process.env,
|
|
432
751
|
stdio: ["pipe", "pipe", "pipe"],
|
|
@@ -627,11 +946,11 @@ async function prepareWorktree(input) {
|
|
|
627
946
|
]);
|
|
628
947
|
} else {
|
|
629
948
|
const wanted = cloneUrl(ref, input.protocol);
|
|
630
|
-
const
|
|
949
|
+
const current2 = await exec("git", ["config", "--get", "remote.origin.url"], {
|
|
631
950
|
cwd: repoDir,
|
|
632
951
|
env: gitEnv()
|
|
633
952
|
});
|
|
634
|
-
if (
|
|
953
|
+
if (current2.stdout.trim() !== wanted) {
|
|
635
954
|
await git(repoDir, ["remote", "set-url", "origin", wanted]);
|
|
636
955
|
}
|
|
637
956
|
await git(repoDir, ["fetch", "--prune", "origin"]);
|
|
@@ -853,17 +1172,17 @@ async function ensureEvidenceDir(worktree) {
|
|
|
853
1172
|
const rel = await git(worktree, ["rev-parse", "--git-path", "info/exclude"]);
|
|
854
1173
|
const file = isAbsolute2(rel) ? rel : join3(worktree, rel);
|
|
855
1174
|
const line = `/${EVIDENCE_DIR}/`;
|
|
856
|
-
let
|
|
1175
|
+
let current2 = "";
|
|
857
1176
|
try {
|
|
858
|
-
|
|
1177
|
+
current2 = await readFile(file, "utf8");
|
|
859
1178
|
} catch {
|
|
860
1179
|
}
|
|
861
|
-
if (
|
|
1180
|
+
if (current2.split("\n").some((l) => l.trim() === line)) return;
|
|
862
1181
|
await mkdir2(join3(file, ".."), { recursive: true });
|
|
863
|
-
const sep2 =
|
|
1182
|
+
const sep2 = current2 && !current2.endsWith("\n") ? "\n" : "";
|
|
864
1183
|
await writeFile(
|
|
865
1184
|
file,
|
|
866
|
-
`${
|
|
1185
|
+
`${current2}${sep2}# Screenshots dt-runner publishes on their own branch
|
|
867
1186
|
${line}
|
|
868
1187
|
`
|
|
869
1188
|
);
|
|
@@ -982,6 +1301,50 @@ function safeName(name) {
|
|
|
982
1301
|
const cleaned = name.replace(/[^\w.-]+/g, "-").replace(/^[.-]+/, "");
|
|
983
1302
|
return cleaned || "screenshot.png";
|
|
984
1303
|
}
|
|
1304
|
+
async function uploadReviewImages(input) {
|
|
1305
|
+
const dir = join3(input.worktree, EVIDENCE_DIR);
|
|
1306
|
+
let found;
|
|
1307
|
+
try {
|
|
1308
|
+
found = await waitingImages(dir);
|
|
1309
|
+
} catch (err) {
|
|
1310
|
+
const why = err instanceof Error ? err.message : String(err);
|
|
1311
|
+
return { uploaded: [], skipped: [], error: `Reading the review images failed: ${why}` };
|
|
1312
|
+
}
|
|
1313
|
+
const skipped = found.filter((f) => f.size > RUNNER_REVIEW_IMAGE_MAX_BYTES).map((f) => f.name);
|
|
1314
|
+
const fitting = found.filter((f) => f.size <= RUNNER_REVIEW_IMAGE_MAX_BYTES);
|
|
1315
|
+
skipped.push(...fitting.slice(MAX_REVIEW_IMAGES_PER_RUN).map((f) => f.name));
|
|
1316
|
+
const uploaded = [];
|
|
1317
|
+
for (const f of fitting.slice(0, MAX_REVIEW_IMAGES_PER_RUN)) {
|
|
1318
|
+
try {
|
|
1319
|
+
const bytes = await readFile(join3(dir, f.name));
|
|
1320
|
+
await input.uploader.postReviewImage(input.sessionId, {
|
|
1321
|
+
filename: f.path,
|
|
1322
|
+
caption: await reviewImageCaption(dir, f.name),
|
|
1323
|
+
dataBase64: bytes.toString("base64")
|
|
1324
|
+
});
|
|
1325
|
+
} catch (err) {
|
|
1326
|
+
if (err instanceof ApiError && !isRetryable(err)) {
|
|
1327
|
+
skipped.push(f.name);
|
|
1328
|
+
continue;
|
|
1329
|
+
}
|
|
1330
|
+
const why = err instanceof Error ? err.message : String(err);
|
|
1331
|
+
return { uploaded, skipped, error: `Uploading the review image ${f.name} failed: ${why}` };
|
|
1332
|
+
}
|
|
1333
|
+
uploaded.push(f.name);
|
|
1334
|
+
await mkdir2(join3(dir, PUBLISHED_DIR), { recursive: true });
|
|
1335
|
+
await rename(join3(dir, f.name), join3(dir, PUBLISHED_DIR, f.name)).catch(() => void 0);
|
|
1336
|
+
}
|
|
1337
|
+
return { uploaded, skipped, error: null };
|
|
1338
|
+
}
|
|
1339
|
+
async function reviewImageCaption(dir, imageName) {
|
|
1340
|
+
const sidecar = join3(dir, imageName.replace(/\.[^.]+$/, "") + ".txt");
|
|
1341
|
+
try {
|
|
1342
|
+
const line = (await readFile(sidecar, "utf8")).split(/\r?\n/).find((l) => l.trim());
|
|
1343
|
+
if (line?.trim()) return line.trim().slice(0, MAX_REVIEW_IMAGE_CAPTION_LENGTH);
|
|
1344
|
+
} catch {
|
|
1345
|
+
}
|
|
1346
|
+
return captionFor(imageName).replace(/^\d+\s+/, "") || captionFor(imageName);
|
|
1347
|
+
}
|
|
985
1348
|
function captionFor(name) {
|
|
986
1349
|
return name.replace(/\.[^.]+$/, "").replace(/[-_]+/g, " ").replace(/[[\]]/g, "").trim();
|
|
987
1350
|
}
|
|
@@ -1043,26 +1406,24 @@ async function claudeAuthStatus(bin) {
|
|
|
1043
1406
|
return { loggedIn: null, authMethod: null };
|
|
1044
1407
|
}
|
|
1045
1408
|
}
|
|
1409
|
+
function parseClaudeHelp(help) {
|
|
1410
|
+
const modes = /--permission-mode\b[^\n]*(?:\n\s+[^-\s][^\n]*)*/.exec(help)?.[0] ?? "";
|
|
1411
|
+
return {
|
|
1412
|
+
permissionPrompts: help.includes("--permission-prompts"),
|
|
1413
|
+
settingSources: help.includes("--setting-sources"),
|
|
1414
|
+
maxTurns: help.includes("--max-turns"),
|
|
1415
|
+
strictMcpConfig: help.includes("--strict-mcp-config"),
|
|
1416
|
+
permissionPromptTool: help.includes("--permission-prompt-tool"),
|
|
1417
|
+
settingsFlag: /--settings <file-or-json>/.test(help),
|
|
1418
|
+
autoMode: /"auto"/.test(modes)
|
|
1419
|
+
};
|
|
1420
|
+
}
|
|
1046
1421
|
async function claudeFeatures(bin) {
|
|
1047
1422
|
try {
|
|
1048
1423
|
const res = await exec(bin, ["--help"], { timeoutMs: 15e3 });
|
|
1049
|
-
return
|
|
1050
|
-
permissionPrompts: res.stdout.includes("--permission-prompts"),
|
|
1051
|
-
settingSources: res.stdout.includes("--setting-sources"),
|
|
1052
|
-
maxTurns: res.stdout.includes("--max-turns"),
|
|
1053
|
-
strictMcpConfig: res.stdout.includes("--strict-mcp-config"),
|
|
1054
|
-
permissionPromptTool: res.stdout.includes("--permission-prompt-tool"),
|
|
1055
|
-
settingsFlag: /--settings <file-or-json>/.test(res.stdout)
|
|
1056
|
-
};
|
|
1424
|
+
return parseClaudeHelp(res.stdout);
|
|
1057
1425
|
} catch {
|
|
1058
|
-
return
|
|
1059
|
-
permissionPrompts: false,
|
|
1060
|
-
settingSources: false,
|
|
1061
|
-
maxTurns: false,
|
|
1062
|
-
strictMcpConfig: false,
|
|
1063
|
-
permissionPromptTool: false,
|
|
1064
|
-
settingsFlag: false
|
|
1065
|
-
};
|
|
1426
|
+
return parseClaudeHelp("");
|
|
1066
1427
|
}
|
|
1067
1428
|
}
|
|
1068
1429
|
async function probeAgent(env = process.env) {
|
|
@@ -1132,7 +1493,8 @@ function claudeArgs(launch) {
|
|
|
1132
1493
|
if (launch.permissionMode === "bypassPermissions") {
|
|
1133
1494
|
args.push("--dangerously-skip-permissions");
|
|
1134
1495
|
} else {
|
|
1135
|
-
|
|
1496
|
+
const mode = launch.permissionMode === "auto" && !launch.features.autoMode ? "acceptEdits" : launch.permissionMode;
|
|
1497
|
+
args.push("--permission-mode", mode);
|
|
1136
1498
|
}
|
|
1137
1499
|
if (relaysPermissions(launch)) {
|
|
1138
1500
|
args.push("--permission-prompt-tool", "stdio");
|
|
@@ -1157,10 +1519,23 @@ function claudeArgs(launch) {
|
|
|
1157
1519
|
}
|
|
1158
1520
|
function runnerSystemPrompt(input) {
|
|
1159
1521
|
if (!input.workBranch) {
|
|
1160
|
-
|
|
1522
|
+
const scratch = [
|
|
1161
1523
|
"You are running a Discovery Tree task through the person\u2019s local Discovery Tree runner.",
|
|
1162
1524
|
"Your working directory is a scratch directory created for this task; it is not a git repository."
|
|
1163
|
-
]
|
|
1525
|
+
];
|
|
1526
|
+
if (input.reviewImages) {
|
|
1527
|
+
const folder = join4(input.cwd, EVIDENCE_DIR);
|
|
1528
|
+
scratch.push(
|
|
1529
|
+
"This task is a design proposal. Save the images you render of it (PNG, JPEG, GIF or",
|
|
1530
|
+
`WebP, under 5 MB each, at most 12) in \`${folder}/\`, also after a \`cd\`, for example with`,
|
|
1531
|
+
`\`npx playwright screenshot --viewport-size=1280,800 <file-or-url> "${folder}/01-<name>.png"\`,`,
|
|
1532
|
+
"with a one-line caption for each in a text file of the same name (`01-<name>.txt`).",
|
|
1533
|
+
"At the end of every turn the runner attaches them to the task in Discovery Tree for",
|
|
1534
|
+
"review; an image saved again under the same name replaces the one attached before.",
|
|
1535
|
+
"Do not upload or link them yourself."
|
|
1536
|
+
);
|
|
1537
|
+
}
|
|
1538
|
+
return scratch.join(" ");
|
|
1164
1539
|
}
|
|
1165
1540
|
const evidence = join4(input.cwd, EVIDENCE_DIR);
|
|
1166
1541
|
return [
|
|
@@ -1196,185 +1571,1727 @@ function runnerSystemPrompt(input) {
|
|
|
1196
1571
|
].join(" ");
|
|
1197
1572
|
}
|
|
1198
1573
|
|
|
1199
|
-
// src/
|
|
1200
|
-
import {
|
|
1574
|
+
// src/claude-code-rules.ts
|
|
1575
|
+
import { readFile as readFile2, stat as stat3 } from "node:fs/promises";
|
|
1201
1576
|
import { homedir } from "node:os";
|
|
1202
|
-
import { dirname as dirname2, join as join5 } from "node:path";
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
var
|
|
1206
|
-
function launchedByNpx(env = process.env, argv1 = process.argv[1]) {
|
|
1207
|
-
if (env.npm_command === "exec") return true;
|
|
1208
|
-
return /[\\/](_npx|dlx)[\\/]/.test(argv1 ?? "");
|
|
1209
|
-
}
|
|
1210
|
-
function runnerCommand(subcommand, viaNpx = launchedByNpx()) {
|
|
1211
|
-
return viaNpx ? `npx ${RUNNER_PACKAGE}@latest ${subcommand}` : `dt-runner ${subcommand}`;
|
|
1212
|
-
}
|
|
1213
|
-
|
|
1214
|
-
// src/config.ts
|
|
1215
|
-
function runnerPaths(env = process.env) {
|
|
1216
|
-
const home = homedir();
|
|
1217
|
-
if (process.platform === "win32") {
|
|
1218
|
-
const roaming = env.APPDATA || join5(home, "AppData", "Roaming");
|
|
1219
|
-
const local = env.LOCALAPPDATA || join5(home, "AppData", "Local");
|
|
1220
|
-
return {
|
|
1221
|
-
configFile: join5(roaming, "discovery-tree", "runner.json"),
|
|
1222
|
-
dataDir: join5(local, "discovery-tree", "runner"),
|
|
1223
|
-
stateDir: join5(local, "discovery-tree", "runner", "state")
|
|
1224
|
-
};
|
|
1225
|
-
}
|
|
1226
|
-
const config = env.XDG_CONFIG_HOME || join5(home, ".config");
|
|
1227
|
-
const data = env.XDG_DATA_HOME || join5(home, ".local", "share");
|
|
1228
|
-
const state = env.XDG_STATE_HOME || join5(home, ".local", "state");
|
|
1229
|
-
return {
|
|
1230
|
-
configFile: join5(config, "discovery-tree", "runner.json"),
|
|
1231
|
-
dataDir: join5(data, "discovery-tree", "runner"),
|
|
1232
|
-
stateDir: join5(state, "discovery-tree", "runner")
|
|
1233
|
-
};
|
|
1234
|
-
}
|
|
1235
|
-
var PERMISSION_MODES = [
|
|
1236
|
-
"acceptEdits",
|
|
1237
|
-
"auto",
|
|
1238
|
-
"default",
|
|
1239
|
-
"manual",
|
|
1240
|
-
"dontAsk",
|
|
1241
|
-
"plan",
|
|
1242
|
-
"bypassPermissions"
|
|
1243
|
-
];
|
|
1244
|
-
var DEFAULT_ALLOWED_TOOLS = [
|
|
1577
|
+
import { dirname as dirname2, isAbsolute as isAbsolute3, join as join5, resolve, sep } from "node:path";
|
|
1578
|
+
var EMPTY = { allow: [], deny: [], ask: [], sources: [] };
|
|
1579
|
+
var RULE_SHAPE2 = /^(?:mcp__[A-Za-z0-9_-]+__\*|[A-Za-z][A-Za-z0-9_.-]*(?:\([\s\S]*\))?)$/;
|
|
1580
|
+
var FILE_TOOLS = /* @__PURE__ */ new Set([
|
|
1245
1581
|
"Read",
|
|
1246
1582
|
"Edit",
|
|
1247
|
-
"MultiEdit",
|
|
1248
1583
|
"Write",
|
|
1584
|
+
"MultiEdit",
|
|
1585
|
+
"NotebookEdit",
|
|
1249
1586
|
"Glob",
|
|
1250
1587
|
"Grep",
|
|
1251
|
-
"LS"
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
"
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
"
|
|
1260
|
-
"
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
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
|
-
|
|
1588
|
+
"LS"
|
|
1589
|
+
]);
|
|
1590
|
+
function usableRule(raw, kind, committed) {
|
|
1591
|
+
if (typeof raw !== "string") return null;
|
|
1592
|
+
const rule = raw.trim();
|
|
1593
|
+
if (!rule || rule.length > TOOL_GRANT_RULE_MAX_LENGTH) return null;
|
|
1594
|
+
if (/[\u0000-\u001f\u007f]/.test(rule) || !RULE_SHAPE2.test(rule)) return null;
|
|
1595
|
+
const tool = /^([A-Za-z][A-Za-z0-9_.-]*)/.exec(rule)?.[1] ?? "";
|
|
1596
|
+
if (kind === "allow" && FILE_TOOLS.has(tool)) return null;
|
|
1597
|
+
if (kind === "allow" && committed && toolGrantRuleProblem(rule) !== null) return null;
|
|
1598
|
+
return rule;
|
|
1599
|
+
}
|
|
1600
|
+
function remoteRepositoryKey(url) {
|
|
1601
|
+
const u = url.trim();
|
|
1602
|
+
const ssh = /^(?:ssh:\/\/)?git@github\.com[:/]([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/i.exec(u);
|
|
1603
|
+
if (ssh) return toolGrantRepositoryKey(`https://github.com/${ssh[1]}/${ssh[2]}`);
|
|
1604
|
+
const https = /^(?:https?|git):\/\/(?:[^@/]+@)?github\.com\/([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/i.exec(u);
|
|
1605
|
+
if (https) return toolGrantRepositoryKey(`https://github.com/${https[1]}/${https[2]}`);
|
|
1606
|
+
return null;
|
|
1607
|
+
}
|
|
1608
|
+
async function readText(file) {
|
|
1609
|
+
try {
|
|
1610
|
+
return await readFile2(file, "utf8");
|
|
1611
|
+
} catch {
|
|
1612
|
+
return null;
|
|
1613
|
+
}
|
|
1614
|
+
}
|
|
1615
|
+
async function readJsonFile(file) {
|
|
1616
|
+
const text = await readText(file);
|
|
1617
|
+
if (text === null) return null;
|
|
1618
|
+
try {
|
|
1619
|
+
return JSON.parse(text);
|
|
1620
|
+
} catch {
|
|
1621
|
+
return null;
|
|
1622
|
+
}
|
|
1623
|
+
}
|
|
1624
|
+
async function isDir(path) {
|
|
1625
|
+
try {
|
|
1626
|
+
return (await stat3(path)).isDirectory();
|
|
1627
|
+
} catch {
|
|
1628
|
+
return false;
|
|
1629
|
+
}
|
|
1630
|
+
}
|
|
1631
|
+
async function gitConfigOf(folder) {
|
|
1632
|
+
let dir = folder;
|
|
1633
|
+
for (let i = 0; i < 6; i++) {
|
|
1634
|
+
const dotGit = join5(dir, ".git");
|
|
1635
|
+
if (await isDir(dotGit)) return { config: join5(dotGit, "config"), roots: [dir] };
|
|
1636
|
+
const pointer = await readText(dotGit);
|
|
1637
|
+
const gitdir = pointer && /^gitdir:\s*(.+)\s*$/m.exec(pointer)?.[1];
|
|
1638
|
+
if (gitdir) {
|
|
1639
|
+
const linked = resolve(dir, gitdir);
|
|
1640
|
+
const common = (await readText(join5(linked, "commondir")))?.trim();
|
|
1641
|
+
const commonDir = common ? resolve(linked, common) : linked;
|
|
1642
|
+
return { config: join5(commonDir, "config"), roots: [dir, dirname2(commonDir)] };
|
|
1643
|
+
}
|
|
1644
|
+
const up = dirname2(dir);
|
|
1645
|
+
if (up === dir) break;
|
|
1646
|
+
dir = up;
|
|
1647
|
+
}
|
|
1648
|
+
return null;
|
|
1649
|
+
}
|
|
1650
|
+
function remoteKeys(config) {
|
|
1651
|
+
const keys = /* @__PURE__ */ new Set();
|
|
1652
|
+
let inRemote = false;
|
|
1653
|
+
for (const line of config.split(/\r?\n/)) {
|
|
1654
|
+
const section = /^\s*\[([^\]]*)\]/.exec(line);
|
|
1655
|
+
if (section) {
|
|
1656
|
+
inRemote = /^remote\s+"/i.test(section[1].trim());
|
|
1657
|
+
continue;
|
|
1658
|
+
}
|
|
1659
|
+
if (!inRemote) continue;
|
|
1660
|
+
const url = /^\s*url\s*=\s*(.+?)\s*$/i.exec(line);
|
|
1661
|
+
const key = url ? remoteRepositoryKey(url[1]) : null;
|
|
1662
|
+
if (key) keys.add(key);
|
|
1663
|
+
}
|
|
1664
|
+
return keys;
|
|
1665
|
+
}
|
|
1666
|
+
function rulesIn(settings, kind, committed) {
|
|
1667
|
+
const perms = settings?.permissions;
|
|
1668
|
+
const list = perms?.[kind];
|
|
1669
|
+
if (!Array.isArray(list)) return [];
|
|
1670
|
+
return list.map((r) => usableRule(r, kind, committed)).filter((r) => r !== null);
|
|
1671
|
+
}
|
|
1672
|
+
var ClaudeCodeRules = class {
|
|
1673
|
+
claudeJson;
|
|
1674
|
+
exclude;
|
|
1675
|
+
cacheMs;
|
|
1676
|
+
cache = /* @__PURE__ */ new Map();
|
|
1677
|
+
constructor(opts = {}) {
|
|
1678
|
+
this.claudeJson = opts.claudeJson ?? (process.env.CLAUDE_CONFIG_DIR ? join5(process.env.CLAUDE_CONFIG_DIR, ".claude.json") : join5(homedir(), ".claude.json"));
|
|
1679
|
+
this.exclude = (opts.exclude ?? []).map((p) => resolve(p));
|
|
1680
|
+
this.cacheMs = opts.cacheMs ?? 3e4;
|
|
1681
|
+
}
|
|
1682
|
+
/** The rules for a repository URL; none for a session without a GitHub repository. */
|
|
1683
|
+
rulesFor(repositoryUrl) {
|
|
1684
|
+
const key = toolGrantRepositoryKey(repositoryUrl);
|
|
1685
|
+
if (!key) return Promise.resolve(EMPTY);
|
|
1686
|
+
const hit = this.cache.get(key);
|
|
1687
|
+
if (hit && Date.now() - hit.at < this.cacheMs) return hit.rules;
|
|
1688
|
+
const rules = this.read(key).catch(() => EMPTY);
|
|
1689
|
+
this.cache.set(key, { at: Date.now(), rules });
|
|
1690
|
+
return rules;
|
|
1691
|
+
}
|
|
1692
|
+
excluded(folder) {
|
|
1693
|
+
const f = resolve(folder);
|
|
1694
|
+
return this.exclude.some((ex) => f === ex || f.startsWith(ex + sep));
|
|
1695
|
+
}
|
|
1696
|
+
async read(key) {
|
|
1697
|
+
const global = await readJsonFile(this.claudeJson);
|
|
1698
|
+
const projects = global?.projects;
|
|
1699
|
+
if (!projects || typeof projects !== "object") return EMPTY;
|
|
1700
|
+
const allow = /* @__PURE__ */ new Set();
|
|
1701
|
+
const deny = /* @__PURE__ */ new Set();
|
|
1702
|
+
const ask = /* @__PURE__ */ new Set();
|
|
1703
|
+
const sources = [];
|
|
1704
|
+
const checkouts = [];
|
|
1705
|
+
for (const [folder, entry] of Object.entries(projects)) {
|
|
1706
|
+
if (!entry || entry.hasTrustDialogAccepted !== true) continue;
|
|
1707
|
+
if (!isAbsolute3(folder) || this.excluded(folder)) continue;
|
|
1708
|
+
const git2 = await gitConfigOf(folder);
|
|
1709
|
+
const text = git2 ? await readText(git2.config) : null;
|
|
1710
|
+
if (!git2 || !text || !remoteKeys(text).has(key)) continue;
|
|
1711
|
+
const roots = [...new Set([folder, ...git2.roots].map((d) => resolve(d)))];
|
|
1712
|
+
const legacy = Array.isArray(entry.allowedTools) ? entry.allowedTools : [];
|
|
1713
|
+
checkouts.push({ folder, roots, legacy });
|
|
1714
|
+
}
|
|
1715
|
+
for (const { folder, roots, legacy } of checkouts) {
|
|
1716
|
+
const found = [];
|
|
1717
|
+
const denied = [];
|
|
1718
|
+
const asked = [];
|
|
1719
|
+
for (const dir of roots) {
|
|
1720
|
+
const local = await readJsonFile(join5(dir, ".claude", "settings.local.json"));
|
|
1721
|
+
const shared = await readJsonFile(join5(dir, ".claude", "settings.json"));
|
|
1722
|
+
found.push(...rulesIn(local, "allow", false), ...rulesIn(shared, "allow", true));
|
|
1723
|
+
denied.push(...rulesIn(local, "deny", false), ...rulesIn(shared, "deny", false));
|
|
1724
|
+
asked.push(...rulesIn(local, "ask", false), ...rulesIn(shared, "ask", false));
|
|
1725
|
+
}
|
|
1726
|
+
found.push(
|
|
1727
|
+
...legacy.map((r) => usableRule(r, "allow", false)).filter((r) => r !== null)
|
|
1728
|
+
);
|
|
1729
|
+
const kept = found;
|
|
1730
|
+
if (kept.length || denied.length || asked.length) sources.push(folder);
|
|
1731
|
+
for (const r of kept) allow.add(r);
|
|
1732
|
+
for (const r of denied) deny.add(r);
|
|
1733
|
+
for (const r of asked) ask.add(r);
|
|
1734
|
+
}
|
|
1735
|
+
return {
|
|
1736
|
+
allow: [...allow].filter((r) => !deny.has(r) && !ask.has(r)),
|
|
1737
|
+
deny: [...deny],
|
|
1738
|
+
ask: [...ask].filter((r) => !deny.has(r)),
|
|
1739
|
+
sources
|
|
1740
|
+
};
|
|
1741
|
+
}
|
|
1742
|
+
};
|
|
1743
|
+
function ruleHead(rule) {
|
|
1744
|
+
const m = /^([A-Za-z][A-Za-z0-9_.-]*(?:__\*)?)(?:\(([\s\S]*)\))?$/.exec(rule.trim());
|
|
1745
|
+
if (!m) return null;
|
|
1746
|
+
const spec = m[2];
|
|
1747
|
+
if (spec === void 0) return { tool: m[1], head: null };
|
|
1748
|
+
return { tool: m[1], head: spec.replace(/:\*$/, " *").split("*")[0] };
|
|
1749
|
+
}
|
|
1750
|
+
function sameTool(a, b) {
|
|
1751
|
+
if (a === b) return true;
|
|
1752
|
+
const wild = (w, t) => w.endsWith("__*") && t.startsWith(w.slice(0, -1));
|
|
1753
|
+
return wild(a, b) || wild(b, a);
|
|
1754
|
+
}
|
|
1755
|
+
function overlapsAsk(allowRule, askRules) {
|
|
1756
|
+
const a = ruleHead(allowRule);
|
|
1757
|
+
if (!a) return false;
|
|
1758
|
+
return askRules.some((rule) => {
|
|
1759
|
+
const q = ruleHead(rule);
|
|
1760
|
+
if (!q || !sameTool(a.tool, q.tool)) return false;
|
|
1761
|
+
if (a.head === null || q.head === null) return true;
|
|
1762
|
+
return a.head.startsWith(q.head) || q.head.startsWith(a.head);
|
|
1763
|
+
});
|
|
1764
|
+
}
|
|
1765
|
+
|
|
1766
|
+
// src/permissions.ts
|
|
1767
|
+
import { randomUUID } from "node:crypto";
|
|
1768
|
+
function parseCanUseTool(line) {
|
|
1769
|
+
if (line?.type !== "control_request") return null;
|
|
1770
|
+
const req = line.request;
|
|
1771
|
+
if (!req || req.subtype !== "can_use_tool") return null;
|
|
1772
|
+
if (typeof line.request_id !== "string" || !line.request_id) return null;
|
|
1773
|
+
const toolName = typeof req.tool_name === "string" && req.tool_name ? req.tool_name : "tool";
|
|
1774
|
+
return { controlRequestId: line.request_id, toolName, input: req.input ?? {} };
|
|
1775
|
+
}
|
|
1776
|
+
function parseControlCancel(line) {
|
|
1777
|
+
if (line?.type !== "control_cancel_request") return null;
|
|
1778
|
+
return typeof line.request_id === "string" ? line.request_id : null;
|
|
1779
|
+
}
|
|
1780
|
+
function summarizeToolInput(toolName, input) {
|
|
1781
|
+
const i = input && typeof input === "object" ? input : {};
|
|
1782
|
+
const s = (v) => typeof v === "string" && v.trim() ? v : null;
|
|
1783
|
+
let summary = null;
|
|
1784
|
+
switch (toolName) {
|
|
1785
|
+
case "Bash":
|
|
1786
|
+
summary = s(i.command);
|
|
1787
|
+
break;
|
|
1788
|
+
case "WebFetch":
|
|
1789
|
+
summary = s(i.url);
|
|
1790
|
+
break;
|
|
1791
|
+
case "WebSearch":
|
|
1792
|
+
summary = s(i.query);
|
|
1793
|
+
break;
|
|
1794
|
+
case "Read":
|
|
1795
|
+
case "Edit":
|
|
1796
|
+
case "MultiEdit":
|
|
1797
|
+
case "Write":
|
|
1798
|
+
summary = s(i.file_path);
|
|
1799
|
+
break;
|
|
1800
|
+
case "NotebookEdit":
|
|
1801
|
+
summary = s(i.notebook_path);
|
|
1802
|
+
break;
|
|
1803
|
+
case "Glob":
|
|
1804
|
+
case "Grep":
|
|
1805
|
+
summary = s(i.pattern) ? `${i.pattern}${s(i.path) ? ` in ${i.path}` : ""}` : null;
|
|
1806
|
+
break;
|
|
1807
|
+
}
|
|
1808
|
+
if (summary === null) {
|
|
1809
|
+
try {
|
|
1810
|
+
summary = JSON.stringify(input) ?? "";
|
|
1811
|
+
} catch {
|
|
1812
|
+
summary = "";
|
|
1813
|
+
}
|
|
1814
|
+
}
|
|
1815
|
+
return cut(summary, AGENT_PERMISSION_INPUT_SUMMARY_MAX_LENGTH);
|
|
1816
|
+
}
|
|
1817
|
+
function cut(text, max) {
|
|
1818
|
+
return text.length > max ? `${text.slice(0, max - 1)}\u2026` : text;
|
|
1819
|
+
}
|
|
1820
|
+
var PERMISSION_EXPIRED_TURN_ENDED = "The turn ended before anyone answered.";
|
|
1821
|
+
var PERMISSION_EXPIRED_INTERRUPTED = "The turn was interrupted before anyone answered.";
|
|
1822
|
+
var PERMISSION_EXPIRED_STOPPED = "Claude Code stopped before anyone answered.";
|
|
1823
|
+
var PERMISSION_EXPIRED_TIMEOUT = `Nobody answered within ${Math.round(
|
|
1824
|
+
RUNNER_PERMISSION_REQUEST_TIMEOUT_MS / 6e4
|
|
1825
|
+
)} minutes.`;
|
|
1826
|
+
var PERMISSION_EXPIRED_CANCELLED = "Claude Code stopped waiting for an answer.";
|
|
1827
|
+
var PERMISSION_EXPIRED_UNKNOWN = "The runner no longer has this request (it may have restarted), so the answer could not be applied.";
|
|
1828
|
+
var DENIED_MESSAGE = "The person denied permission for this tool call in Discovery Tree.";
|
|
1829
|
+
var SETTLED_KEPT = 200;
|
|
1830
|
+
var PermissionRelay = class {
|
|
1831
|
+
constructor(deps) {
|
|
1832
|
+
this.deps = deps;
|
|
1833
|
+
}
|
|
1834
|
+
pending = /* @__PURE__ */ new Map();
|
|
1835
|
+
byControlId = /* @__PURE__ */ new Map();
|
|
1836
|
+
settled = /* @__PURE__ */ new Map();
|
|
1837
|
+
get pendingCount() {
|
|
1838
|
+
return this.pending.size;
|
|
1839
|
+
}
|
|
1840
|
+
/** Claude Code asks; returns whether it was allowed at once or relayed. */
|
|
1841
|
+
request(req) {
|
|
1842
|
+
if (this.deps.alwaysAllowed().includes(req.toolName) || this.deps.grantedByRule?.(req.toolName, req.input)) {
|
|
1843
|
+
this.deps.respond(req.controlRequestId, { behavior: "allow", updatedInput: req.input });
|
|
1844
|
+
return "auto_allowed";
|
|
1845
|
+
}
|
|
1846
|
+
const id = (this.deps.newId ?? randomUUID)();
|
|
1847
|
+
const requestedAt = (this.deps.now?.() ?? /* @__PURE__ */ new Date()).toISOString();
|
|
1848
|
+
const timer = setTimeout(
|
|
1849
|
+
() => this.expire(id, PERMISSION_EXPIRED_TIMEOUT, true),
|
|
1850
|
+
this.deps.timeoutMs ?? RUNNER_PERMISSION_REQUEST_TIMEOUT_MS
|
|
1851
|
+
);
|
|
1852
|
+
timer.unref?.();
|
|
1853
|
+
const pending = {
|
|
1854
|
+
id,
|
|
1855
|
+
controlRequestId: req.controlRequestId,
|
|
1856
|
+
toolName: req.toolName,
|
|
1857
|
+
input: req.input,
|
|
1858
|
+
inputSummary: summarizeToolInput(req.toolName, req.input),
|
|
1859
|
+
requestedAt,
|
|
1860
|
+
timer
|
|
1861
|
+
};
|
|
1862
|
+
this.pending.set(id, pending);
|
|
1863
|
+
this.byControlId.set(req.controlRequestId, id);
|
|
1864
|
+
const suggestedRule = this.deps.suggestRule?.(req.toolName, req.input) ?? null;
|
|
1865
|
+
this.deps.emit({
|
|
1866
|
+
type: "permission_request",
|
|
1867
|
+
request: {
|
|
1868
|
+
id,
|
|
1869
|
+
toolName: pending.toolName,
|
|
1870
|
+
inputSummary: pending.inputSummary,
|
|
1871
|
+
...suggestedRule ? { suggestedRule } : {},
|
|
1872
|
+
requestedAt,
|
|
1873
|
+
status: "pending"
|
|
1874
|
+
}
|
|
1875
|
+
});
|
|
1876
|
+
return "relayed";
|
|
1877
|
+
}
|
|
1878
|
+
/** A person's decision, from the server. */
|
|
1879
|
+
decide(requestId, decision) {
|
|
1880
|
+
const pending = this.pending.get(requestId);
|
|
1881
|
+
if (!pending) {
|
|
1882
|
+
const settled = this.settled.get(requestId);
|
|
1883
|
+
if (settled === "decided") return "already_applied";
|
|
1884
|
+
if (settled === void 0) {
|
|
1885
|
+
this.settle(requestId, "expired");
|
|
1886
|
+
this.deps.emit({
|
|
1887
|
+
type: "permission_request",
|
|
1888
|
+
request: {
|
|
1889
|
+
id: requestId,
|
|
1890
|
+
toolName: "tool",
|
|
1891
|
+
inputSummary: "",
|
|
1892
|
+
requestedAt: (this.deps.now?.() ?? /* @__PURE__ */ new Date()).toISOString(),
|
|
1893
|
+
status: "expired",
|
|
1894
|
+
expiredReason: PERMISSION_EXPIRED_UNKNOWN
|
|
1895
|
+
}
|
|
1896
|
+
});
|
|
1897
|
+
}
|
|
1898
|
+
return "not_pending";
|
|
1899
|
+
}
|
|
1900
|
+
this.forget(pending);
|
|
1901
|
+
this.settle(requestId, "decided");
|
|
1902
|
+
if (decision.behavior === "allow") {
|
|
1903
|
+
if (decision.alwaysAllowTool && !this.deps.alwaysAllowed().includes(pending.toolName)) {
|
|
1904
|
+
this.deps.rememberAlwaysAllowed(pending.toolName);
|
|
1905
|
+
}
|
|
1906
|
+
const rule = decision.alwaysAllowRule?.trim();
|
|
1907
|
+
if (rule && toolGrantRuleProblem(rule) === null) this.deps.rememberRule?.(rule);
|
|
1908
|
+
this.deps.respond(pending.controlRequestId, {
|
|
1909
|
+
behavior: "allow",
|
|
1910
|
+
updatedInput: pending.input
|
|
1911
|
+
});
|
|
1912
|
+
} else {
|
|
1913
|
+
const message = decision.message?.trim();
|
|
1914
|
+
this.deps.respond(pending.controlRequestId, {
|
|
1915
|
+
behavior: "deny",
|
|
1916
|
+
message: message ? `${DENIED_MESSAGE} Their message: ${cut(message, AGENT_PERMISSION_MESSAGE_MAX_LENGTH)}` : DENIED_MESSAGE
|
|
1917
|
+
});
|
|
1918
|
+
}
|
|
1919
|
+
return "applied";
|
|
1920
|
+
}
|
|
1921
|
+
/** Claude Code withdrew a request (it stopped waiting): expired, nothing to answer. */
|
|
1922
|
+
cancel(controlRequestId) {
|
|
1923
|
+
const id = this.byControlId.get(controlRequestId);
|
|
1924
|
+
if (id) this.expire(id, PERMISSION_EXPIRED_CANCELLED, false);
|
|
1925
|
+
}
|
|
1926
|
+
/** Expire everything still waiting, answering Claude Code with a denial. */
|
|
1927
|
+
expireAll(reason) {
|
|
1928
|
+
for (const id of [...this.pending.keys()]) this.expire(id, reason, true);
|
|
1929
|
+
}
|
|
1930
|
+
expire(id, reason, answerClaude) {
|
|
1931
|
+
const pending = this.pending.get(id);
|
|
1932
|
+
if (!pending) return;
|
|
1933
|
+
this.forget(pending);
|
|
1934
|
+
this.settle(id, "expired");
|
|
1935
|
+
if (answerClaude) {
|
|
1936
|
+
this.deps.respond(pending.controlRequestId, {
|
|
1937
|
+
behavior: "deny",
|
|
1938
|
+
message: `Permission for this tool call was not granted: ${reason}`
|
|
1939
|
+
});
|
|
1940
|
+
}
|
|
1941
|
+
this.deps.emit({
|
|
1942
|
+
type: "permission_request",
|
|
1943
|
+
request: {
|
|
1944
|
+
id,
|
|
1945
|
+
toolName: pending.toolName,
|
|
1946
|
+
inputSummary: pending.inputSummary,
|
|
1947
|
+
requestedAt: pending.requestedAt,
|
|
1948
|
+
status: "expired",
|
|
1949
|
+
expiredReason: reason
|
|
1950
|
+
}
|
|
1951
|
+
});
|
|
1952
|
+
}
|
|
1953
|
+
forget(pending) {
|
|
1954
|
+
clearTimeout(pending.timer);
|
|
1955
|
+
this.pending.delete(pending.id);
|
|
1956
|
+
this.byControlId.delete(pending.controlRequestId);
|
|
1957
|
+
}
|
|
1958
|
+
settle(id, how) {
|
|
1959
|
+
this.settled.set(id, how);
|
|
1960
|
+
while (this.settled.size > SETTLED_KEPT) {
|
|
1961
|
+
this.settled.delete(this.settled.keys().next().value);
|
|
1962
|
+
}
|
|
1963
|
+
}
|
|
1964
|
+
};
|
|
1965
|
+
|
|
1966
|
+
// src/stream-mapper.ts
|
|
1967
|
+
function capText(text, max = RUNNER_EVENT_TEXT_MAX_LENGTH) {
|
|
1968
|
+
if (text.length <= max) return { text, truncated: false };
|
|
1969
|
+
const marker = "\n\u2026 [truncated by dt-runner]";
|
|
1970
|
+
return { text: text.slice(0, max - marker.length) + marker, truncated: true };
|
|
1971
|
+
}
|
|
1972
|
+
var ClaudeStreamMapper = class {
|
|
1973
|
+
/** Running offset of each live text block, by providerEventId. */
|
|
1974
|
+
deltaOffsets = /* @__PURE__ */ new Map();
|
|
1975
|
+
/** Stream block index → providerEventId for text blocks of the message streaming now. */
|
|
1976
|
+
streamTextKeys = /* @__PURE__ */ new Map();
|
|
1977
|
+
streamMessageId = null;
|
|
1978
|
+
streamTextCount = 0;
|
|
1979
|
+
/** Text blocks already seen in completed `assistant` lines, per message id. */
|
|
1980
|
+
completedTextCount = /* @__PURE__ */ new Map();
|
|
1981
|
+
/** Tool calls by id, for the name/input a result line does not repeat. */
|
|
1982
|
+
calls = /* @__PURE__ */ new Map();
|
|
1983
|
+
lastAssistantText = null;
|
|
1984
|
+
running = false;
|
|
1985
|
+
/** A new turn is starting (we wrote a user message); the next activity is not news. */
|
|
1986
|
+
markRunning() {
|
|
1987
|
+
this.running = true;
|
|
1988
|
+
}
|
|
1989
|
+
map(line) {
|
|
1990
|
+
const out = { events: [] };
|
|
1991
|
+
if (line.parent_tool_use_id) return out;
|
|
1992
|
+
switch (line.type) {
|
|
1993
|
+
case "system":
|
|
1994
|
+
if (line.subtype === "init" && typeof line.session_id === "string") {
|
|
1995
|
+
out.conversationId = line.session_id;
|
|
1996
|
+
this.ensureRunning(out);
|
|
1997
|
+
}
|
|
1998
|
+
break;
|
|
1999
|
+
case "stream_event":
|
|
2000
|
+
this.mapStreamEvent(line, out);
|
|
2001
|
+
break;
|
|
2002
|
+
case "assistant":
|
|
2003
|
+
this.mapAssistant(line, out);
|
|
2004
|
+
break;
|
|
2005
|
+
case "user":
|
|
2006
|
+
this.mapUser(line, out);
|
|
2007
|
+
break;
|
|
2008
|
+
case "result": {
|
|
2009
|
+
const resultText = typeof line.result === "string" && line.result ? line.result : null;
|
|
2010
|
+
out.turnEnd = {
|
|
2011
|
+
text: resultText ?? this.lastAssistantText,
|
|
2012
|
+
isError: line.is_error === true || (line.subtype ?? "success") !== "success",
|
|
2013
|
+
subtype: typeof line.subtype === "string" ? line.subtype : null
|
|
2014
|
+
};
|
|
2015
|
+
const denials = Array.isArray(line.permission_denials) ? line.permission_denials.filter((d) => d && typeof d.tool_name === "string").map((d) => ({
|
|
2016
|
+
callId: typeof d.tool_use_id === "string" ? d.tool_use_id : null,
|
|
2017
|
+
name: d.tool_name,
|
|
2018
|
+
input: d.tool_input ?? {}
|
|
2019
|
+
})) : [];
|
|
2020
|
+
if (denials.length) out.turnEnd.permissionDenials = denials;
|
|
2021
|
+
this.endTurn();
|
|
2022
|
+
break;
|
|
2023
|
+
}
|
|
2024
|
+
case "control_response": {
|
|
2025
|
+
const res = line.response ?? {};
|
|
2026
|
+
if (typeof res.request_id === "string") {
|
|
2027
|
+
out.controlResponse = { requestId: res.request_id, ok: res.subtype === "success" };
|
|
2028
|
+
}
|
|
2029
|
+
break;
|
|
2030
|
+
}
|
|
2031
|
+
}
|
|
2032
|
+
return out;
|
|
2033
|
+
}
|
|
2034
|
+
ensureRunning(out) {
|
|
2035
|
+
if (!this.running) {
|
|
2036
|
+
this.running = true;
|
|
2037
|
+
out.turnStarted = true;
|
|
2038
|
+
out.events.push({ type: "status", status: "running" });
|
|
2039
|
+
}
|
|
2040
|
+
}
|
|
2041
|
+
mapStreamEvent(line, out) {
|
|
2042
|
+
const ev = line.event ?? {};
|
|
2043
|
+
switch (ev.type) {
|
|
2044
|
+
case "message_start": {
|
|
2045
|
+
this.ensureRunning(out);
|
|
2046
|
+
const id = ev.message?.id ?? line.api_message_id ?? null;
|
|
2047
|
+
this.beginStreamMessage(typeof id === "string" ? id : null);
|
|
2048
|
+
break;
|
|
2049
|
+
}
|
|
2050
|
+
case "content_block_start": {
|
|
2051
|
+
const id = this.streamMessageIdFor(line);
|
|
2052
|
+
if (ev.content_block?.type === "text" && id && typeof ev.index === "number") {
|
|
2053
|
+
const key = textKey(id, this.streamTextCount++);
|
|
2054
|
+
this.streamTextKeys.set(ev.index, key);
|
|
2055
|
+
const initial = typeof ev.content_block.text === "string" ? ev.content_block.text : "";
|
|
2056
|
+
this.deltaOffsets.set(key, 0);
|
|
2057
|
+
if (initial) this.pushDelta(out, key, initial);
|
|
2058
|
+
}
|
|
2059
|
+
break;
|
|
2060
|
+
}
|
|
2061
|
+
case "content_block_delta": {
|
|
2062
|
+
if (ev.delta?.type !== "text_delta" || typeof ev.delta.text !== "string") break;
|
|
2063
|
+
if (!ev.delta.text) break;
|
|
2064
|
+
const key = this.streamTextKeys.get(ev.index);
|
|
2065
|
+
if (key) this.pushDelta(out, key, ev.delta.text);
|
|
2066
|
+
break;
|
|
2067
|
+
}
|
|
2068
|
+
}
|
|
2069
|
+
}
|
|
2070
|
+
streamMessageIdFor(line) {
|
|
2071
|
+
const id = typeof line.api_message_id === "string" ? line.api_message_id : null;
|
|
2072
|
+
if (id && id !== this.streamMessageId) this.beginStreamMessage(id);
|
|
2073
|
+
return this.streamMessageId;
|
|
2074
|
+
}
|
|
2075
|
+
beginStreamMessage(id) {
|
|
2076
|
+
if (id === this.streamMessageId) return;
|
|
2077
|
+
this.streamMessageId = id;
|
|
2078
|
+
this.streamTextKeys.clear();
|
|
2079
|
+
this.streamTextCount = 0;
|
|
2080
|
+
}
|
|
2081
|
+
pushDelta(out, key, text) {
|
|
2082
|
+
const offset = this.deltaOffsets.get(key) ?? 0;
|
|
2083
|
+
this.deltaOffsets.set(key, offset + text.length);
|
|
2084
|
+
out.events.push({ type: "assistant_delta", providerEventId: key, text, offset });
|
|
2085
|
+
}
|
|
2086
|
+
mapAssistant(line, out) {
|
|
2087
|
+
const msg = line.message ?? {};
|
|
2088
|
+
const id = typeof msg.id === "string" ? msg.id : `msg_${line.uuid ?? Date.now()}`;
|
|
2089
|
+
const content = Array.isArray(msg.content) ? msg.content : [];
|
|
2090
|
+
this.ensureRunning(out);
|
|
2091
|
+
for (const block of content) {
|
|
2092
|
+
switch (block?.type) {
|
|
2093
|
+
case "text": {
|
|
2094
|
+
const n = this.completedTextCount.get(id) ?? 0;
|
|
2095
|
+
this.completedTextCount.set(id, n + 1);
|
|
2096
|
+
const text = typeof block.text === "string" ? block.text : "";
|
|
2097
|
+
if (!text.trim()) break;
|
|
2098
|
+
const key = textKey(id, n);
|
|
2099
|
+
this.deltaOffsets.delete(key);
|
|
2100
|
+
this.lastAssistantText = text;
|
|
2101
|
+
out.events.push({
|
|
2102
|
+
type: "assistant_message",
|
|
2103
|
+
providerEventId: key,
|
|
2104
|
+
text: capText(text).text
|
|
2105
|
+
});
|
|
2106
|
+
break;
|
|
2107
|
+
}
|
|
2108
|
+
case "thinking":
|
|
2109
|
+
case "redacted_thinking": {
|
|
2110
|
+
const text = typeof block.thinking === "string" && block.thinking.trim() ? block.thinking : null;
|
|
2111
|
+
out.events.push({
|
|
2112
|
+
type: "thinking",
|
|
2113
|
+
providerEventId: `${id}:thinking:${this.thinkingIndex(id)}`,
|
|
2114
|
+
text: text === null ? null : capText(text).text
|
|
2115
|
+
});
|
|
2116
|
+
break;
|
|
2117
|
+
}
|
|
2118
|
+
case "tool_use":
|
|
2119
|
+
case "server_tool_use":
|
|
2120
|
+
case "mcp_tool_use": {
|
|
2121
|
+
if (typeof block.id !== "string") break;
|
|
2122
|
+
const name = block.type === "mcp_tool_use" && block.server_name ? `${block.server_name}.${block.name}` : String(block.name ?? "tool");
|
|
2123
|
+
this.calls.set(block.id, { name, input: block.input });
|
|
2124
|
+
out.events.push({
|
|
2125
|
+
type: "tool_call",
|
|
2126
|
+
providerEventId: block.id,
|
|
2127
|
+
tool: { callId: block.id, name, status: "running", input: block.input }
|
|
2128
|
+
});
|
|
2129
|
+
break;
|
|
2130
|
+
}
|
|
2131
|
+
}
|
|
2132
|
+
}
|
|
2133
|
+
}
|
|
2134
|
+
thinkingCounts = /* @__PURE__ */ new Map();
|
|
2135
|
+
thinkingIndex(id) {
|
|
2136
|
+
const n = this.thinkingCounts.get(id) ?? 0;
|
|
2137
|
+
this.thinkingCounts.set(id, n + 1);
|
|
2138
|
+
return n;
|
|
2139
|
+
}
|
|
2140
|
+
mapUser(line, out) {
|
|
2141
|
+
const content = line.message?.content;
|
|
2142
|
+
if (!Array.isArray(content)) return;
|
|
2143
|
+
for (const block of content) {
|
|
2144
|
+
if (block?.type !== "tool_result" || typeof block.tool_use_id !== "string") continue;
|
|
2145
|
+
const known = this.calls.get(block.tool_use_id);
|
|
2146
|
+
const full = toolResultText(block.content);
|
|
2147
|
+
const { text, truncated } = capText(full);
|
|
2148
|
+
if (block.is_error) {
|
|
2149
|
+
(out.failedTools ??= []).push({
|
|
2150
|
+
callId: block.tool_use_id,
|
|
2151
|
+
name: known?.name ?? "tool",
|
|
2152
|
+
input: known?.input ?? {},
|
|
2153
|
+
text: full
|
|
2154
|
+
});
|
|
2155
|
+
}
|
|
2156
|
+
const tool = {
|
|
2157
|
+
callId: block.tool_use_id,
|
|
2158
|
+
name: known?.name ?? "tool",
|
|
2159
|
+
status: block.is_error ? "failed" : "completed",
|
|
2160
|
+
...known ? { input: known.input } : {},
|
|
2161
|
+
output: text,
|
|
2162
|
+
...truncated ? { truncated: true } : {}
|
|
2163
|
+
};
|
|
2164
|
+
out.events.push({ type: "tool_call", providerEventId: block.tool_use_id, tool });
|
|
2165
|
+
}
|
|
2166
|
+
}
|
|
2167
|
+
endTurn() {
|
|
2168
|
+
this.running = false;
|
|
2169
|
+
this.lastAssistantText = null;
|
|
2170
|
+
this.deltaOffsets.clear();
|
|
2171
|
+
this.streamTextKeys.clear();
|
|
2172
|
+
this.streamMessageId = null;
|
|
2173
|
+
this.streamTextCount = 0;
|
|
2174
|
+
this.completedTextCount.clear();
|
|
2175
|
+
this.thinkingCounts.clear();
|
|
2176
|
+
if (this.calls.size > 500) this.calls.clear();
|
|
2177
|
+
}
|
|
2178
|
+
};
|
|
2179
|
+
function textKey(messageId, n) {
|
|
2180
|
+
return n === 0 ? messageId : `${messageId}:${n}`;
|
|
2181
|
+
}
|
|
2182
|
+
function toolResultText(content) {
|
|
2183
|
+
if (typeof content === "string") return content;
|
|
2184
|
+
if (!Array.isArray(content)) return content == null ? "" : JSON.stringify(content);
|
|
2185
|
+
return content.map((b) => {
|
|
2186
|
+
if (b?.type === "text" && typeof b.text === "string") return b.text;
|
|
2187
|
+
if (b?.type === "image") return "[image]";
|
|
2188
|
+
return "";
|
|
2189
|
+
}).filter(Boolean).join("\n");
|
|
2190
|
+
}
|
|
2191
|
+
|
|
2192
|
+
// src/drivers/claude.ts
|
|
2193
|
+
var claudeCodeDriver = {
|
|
2194
|
+
kind: "claude_code",
|
|
2195
|
+
displayName: "Claude Code",
|
|
2196
|
+
processModel: "persistent",
|
|
2197
|
+
resolveBinary: (env) => findClaude(env),
|
|
2198
|
+
notInstalledMessage: () => "Claude Code is not installed on the runner\u2019s computer (no `claude` on PATH).",
|
|
2199
|
+
readFeatures: (bin) => claudeFeatures(bin),
|
|
2200
|
+
probe: (env) => probeAgent(env),
|
|
2201
|
+
doctor,
|
|
2202
|
+
validateModel: (model) => assertValidModel(model),
|
|
2203
|
+
launch(input) {
|
|
2204
|
+
const features = input.features;
|
|
2205
|
+
const ask = input.askTools;
|
|
2206
|
+
const allowedTools = features.settingsFlag || ask.length === 0 ? input.allowedTools : input.allowedTools.filter((r) => !overlapsAsk(r, ask));
|
|
2207
|
+
return {
|
|
2208
|
+
bin: input.bin,
|
|
2209
|
+
args: claudeArgs({
|
|
2210
|
+
permissionMode: input.permissionMode,
|
|
2211
|
+
allowedTools,
|
|
2212
|
+
disallowedTools: input.disallowedTools,
|
|
2213
|
+
loadProjectSettings: input.loadProjectSettings,
|
|
2214
|
+
model: input.model,
|
|
2215
|
+
resume: input.resume,
|
|
2216
|
+
relayPermissions: input.relayPermissions,
|
|
2217
|
+
askTools: ask,
|
|
2218
|
+
appendSystemPrompt: input.systemPrompt,
|
|
2219
|
+
features
|
|
2220
|
+
})
|
|
2221
|
+
};
|
|
2222
|
+
},
|
|
2223
|
+
createMapper: () => new ClaudeStreamMapper(),
|
|
2224
|
+
encodeMessage: (content) => ({ type: "user", message: { role: "user", content } }),
|
|
2225
|
+
// As the Agent SDK sends it: Claude Code ends the turn with an `error_during_execution`.
|
|
2226
|
+
interruptMessage: (requestId) => ({
|
|
2227
|
+
type: "control_request",
|
|
2228
|
+
request_id: requestId,
|
|
2229
|
+
request: { subtype: "interrupt" }
|
|
2230
|
+
}),
|
|
2231
|
+
control: {
|
|
2232
|
+
relays: (input) => relaysPermissions({
|
|
2233
|
+
relayPermissions: input.relayPermissions,
|
|
2234
|
+
permissionMode: input.permissionMode,
|
|
2235
|
+
features: input.features
|
|
2236
|
+
}),
|
|
2237
|
+
parse(line) {
|
|
2238
|
+
if (line.type === "control_request") {
|
|
2239
|
+
const ask = parseCanUseTool(line);
|
|
2240
|
+
if (ask) return { kind: "permission", ask };
|
|
2241
|
+
return {
|
|
2242
|
+
kind: "unsupported",
|
|
2243
|
+
requestId: typeof line.request_id === "string" ? line.request_id : null
|
|
2244
|
+
};
|
|
2245
|
+
}
|
|
2246
|
+
const cancelled = parseControlCancel(line);
|
|
2247
|
+
return cancelled ? { kind: "cancel", controlRequestId: cancelled } : null;
|
|
2248
|
+
},
|
|
2249
|
+
permissionResponse: (controlRequestId, response) => ({
|
|
2250
|
+
type: "control_response",
|
|
2251
|
+
response: { subtype: "success", request_id: controlRequestId, response }
|
|
2252
|
+
}),
|
|
2253
|
+
unsupportedResponse: (requestId) => ({
|
|
2254
|
+
type: "control_response",
|
|
2255
|
+
response: {
|
|
2256
|
+
subtype: "error",
|
|
2257
|
+
request_id: requestId,
|
|
2258
|
+
error: "dt-runner does not handle this control request."
|
|
2259
|
+
}
|
|
2260
|
+
})
|
|
2261
|
+
},
|
|
2262
|
+
looksLikeSignInFailure,
|
|
2263
|
+
turnFailedToSignIn,
|
|
2264
|
+
signInFix,
|
|
2265
|
+
turnErrorMessage,
|
|
2266
|
+
startupHint,
|
|
2267
|
+
resumeNotFound: (stderr) => /No conversation found/i.test(stderr)
|
|
2268
|
+
};
|
|
2269
|
+
async function doctor(env = process.env) {
|
|
2270
|
+
const checks = [];
|
|
2271
|
+
const bin = await findClaude(env);
|
|
2272
|
+
if (!bin) {
|
|
2273
|
+
checks.push({
|
|
2274
|
+
name: "Claude Code",
|
|
2275
|
+
level: "fail",
|
|
2276
|
+
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)"
|
|
2277
|
+
});
|
|
2278
|
+
} else {
|
|
2279
|
+
const version = await claudeVersion(bin);
|
|
2280
|
+
checks.push({
|
|
2281
|
+
name: "Claude Code",
|
|
2282
|
+
level: version ? "ok" : "fail",
|
|
2283
|
+
detail: version ? `${version} (${bin})` : `${bin} --version failed`
|
|
2284
|
+
});
|
|
2285
|
+
if (version) {
|
|
2286
|
+
const auth = await claudeAuthStatus(bin);
|
|
2287
|
+
checks.push(
|
|
2288
|
+
auth.loggedIn === true ? {
|
|
2289
|
+
name: "Claude sign-in",
|
|
2290
|
+
level: "ok",
|
|
2291
|
+
detail: `signed in${auth.authMethod ? ` (${auth.authMethod})` : ""}`
|
|
2292
|
+
} : auth.loggedIn === false ? {
|
|
2293
|
+
name: "Claude sign-in",
|
|
2294
|
+
level: "fail",
|
|
2295
|
+
detail: "not signed in: run `claude` and sign in with your Claude account"
|
|
2296
|
+
} : {
|
|
2297
|
+
name: "Claude sign-in",
|
|
2298
|
+
level: "warn",
|
|
2299
|
+
detail: "could not tell (this Claude Code has no `claude auth status`); update Claude Code"
|
|
2300
|
+
}
|
|
2301
|
+
);
|
|
2302
|
+
}
|
|
2303
|
+
}
|
|
2304
|
+
return checks;
|
|
2305
|
+
}
|
|
2306
|
+
function turnErrorMessage(turn) {
|
|
2307
|
+
switch (turn.subtype) {
|
|
2308
|
+
case "error_max_turns":
|
|
2309
|
+
return "Claude Code stopped: it reached its maximum number of turns.";
|
|
2310
|
+
case "error_max_budget_usd":
|
|
2311
|
+
return "Claude Code stopped: it reached its spending limit.";
|
|
2312
|
+
default:
|
|
2313
|
+
if (turnFailedToSignIn(turn)) {
|
|
2314
|
+
return `Claude Code could not sign in to Claude (${turn.text.slice(0, 200)}). ${signInFix()} Then send a message here to try again.`;
|
|
2315
|
+
}
|
|
2316
|
+
return turn.text ? `Claude Code reported an error: ${turn.text.slice(0, 500)}` : `Claude Code ended the turn with an error (${turn.subtype ?? "unknown"}).`;
|
|
2317
|
+
}
|
|
2318
|
+
}
|
|
2319
|
+
function startupHint(stderr) {
|
|
2320
|
+
if (looksLikeSignInFailure(stderr)) {
|
|
2321
|
+
return ` Claude Code does not seem to be signed in on the runner\u2019s computer. ${signInFix()}`;
|
|
2322
|
+
}
|
|
2323
|
+
if (/No conversation found|session.*not found/i.test(stderr)) {
|
|
2324
|
+
return " The Claude Code conversation to resume was not found on this computer.";
|
|
2325
|
+
}
|
|
2326
|
+
return "";
|
|
2327
|
+
}
|
|
2328
|
+
|
|
2329
|
+
// src/drivers/codex/codex.ts
|
|
2330
|
+
import { delimiter as delimiter2, join as join6 } from "node:path";
|
|
2331
|
+
|
|
2332
|
+
// src/drivers/launcher.ts
|
|
2333
|
+
import { access as access2 } from "node:fs/promises";
|
|
2334
|
+
async function exists2(file) {
|
|
2335
|
+
try {
|
|
2336
|
+
await access2(file);
|
|
2337
|
+
return true;
|
|
2338
|
+
} catch {
|
|
2339
|
+
return false;
|
|
2340
|
+
}
|
|
2341
|
+
}
|
|
2342
|
+
function isJsLauncher(bin) {
|
|
2343
|
+
return /\.[cm]?js$/i.test(bin);
|
|
2344
|
+
}
|
|
2345
|
+
function launcherCommand(bin, args) {
|
|
2346
|
+
return isJsLauncher(bin) ? { bin: process.execPath, args: [bin, ...args] } : { bin, args };
|
|
2347
|
+
}
|
|
2348
|
+
async function findOverride(override, env) {
|
|
2349
|
+
if (isJsLauncher(override)) return await exists2(override) ? override : null;
|
|
2350
|
+
return which(override, env);
|
|
2351
|
+
}
|
|
2352
|
+
|
|
2353
|
+
// src/drivers/codex/codex.ts
|
|
2354
|
+
async function findCodex(env = process.env) {
|
|
2355
|
+
const override = env.DT_RUNNER_CODEX_BIN?.trim();
|
|
2356
|
+
if (override) return findOverride(override, env);
|
|
2357
|
+
const found = await which("codex", env);
|
|
2358
|
+
if (found) return found;
|
|
2359
|
+
if (process.platform !== "win32") return null;
|
|
2360
|
+
for (const dir of (env.PATH ?? env.Path ?? "").split(delimiter2).filter(Boolean)) {
|
|
2361
|
+
if (!await exists2(join6(dir, "codex.cmd"))) continue;
|
|
2362
|
+
const script = join6(dir, "node_modules", "@openai", "codex", "bin", "codex.js");
|
|
2363
|
+
if (await exists2(script)) return script;
|
|
2364
|
+
}
|
|
2365
|
+
return null;
|
|
2366
|
+
}
|
|
2367
|
+
var codexCommand = launcherCommand;
|
|
2368
|
+
function runCodex(bin, args, timeoutMs, env) {
|
|
2369
|
+
const cmd = codexCommand(bin, args);
|
|
2370
|
+
return exec(cmd.bin, cmd.args, { timeoutMs, env });
|
|
2371
|
+
}
|
|
2372
|
+
async function codexVersion(bin, env = process.env) {
|
|
2373
|
+
try {
|
|
2374
|
+
const res = await runCodex(bin, ["--version"], 15e3, env);
|
|
2375
|
+
if (res.code !== 0) return null;
|
|
2376
|
+
return res.stdout.trim().split("\n")[0] || null;
|
|
2377
|
+
} catch {
|
|
2378
|
+
return null;
|
|
2379
|
+
}
|
|
2380
|
+
}
|
|
2381
|
+
async function codexAuthStatus(bin, env = process.env) {
|
|
2382
|
+
try {
|
|
2383
|
+
const res = await runCodex(bin, ["login", "status"], 2e4, env);
|
|
2384
|
+
const said = `${res.stdout}
|
|
2385
|
+
${res.stderr}`;
|
|
2386
|
+
if (res.code !== 0) return { loggedIn: false, authMethod: null };
|
|
2387
|
+
return {
|
|
2388
|
+
loggedIn: true,
|
|
2389
|
+
authMethod: /chatgpt/i.test(said) ? "ChatGPT" : /api key/i.test(said) ? "API key" : null
|
|
2390
|
+
};
|
|
2391
|
+
} catch {
|
|
2392
|
+
return { loggedIn: null, authMethod: null };
|
|
2393
|
+
}
|
|
2394
|
+
}
|
|
2395
|
+
function codexSignInFix(env = process.env) {
|
|
2396
|
+
const key = codexKeyVariable(env);
|
|
2397
|
+
if (key) {
|
|
2398
|
+
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.`;
|
|
2399
|
+
}
|
|
2400
|
+
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.";
|
|
2401
|
+
}
|
|
2402
|
+
function codexKeyVariable(env = process.env) {
|
|
2403
|
+
if (env.CODEX_API_KEY) return "CODEX_API_KEY";
|
|
2404
|
+
if (env.OPENAI_API_KEY) return "OPENAI_API_KEY";
|
|
2405
|
+
return null;
|
|
2406
|
+
}
|
|
2407
|
+
async function probeCodex(env = process.env) {
|
|
2408
|
+
const bin = await findCodex(env);
|
|
2409
|
+
if (!bin) {
|
|
2410
|
+
return {
|
|
2411
|
+
codexVersion: null,
|
|
2412
|
+
codexReady: false,
|
|
2413
|
+
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`."
|
|
2414
|
+
};
|
|
2415
|
+
}
|
|
2416
|
+
const version = await codexVersion(bin, env);
|
|
2417
|
+
if (!version) {
|
|
2418
|
+
return {
|
|
2419
|
+
codexVersion: null,
|
|
2420
|
+
codexReady: false,
|
|
2421
|
+
codexProblem: "`codex --version` failed; reinstall or update Codex."
|
|
2422
|
+
};
|
|
2423
|
+
}
|
|
2424
|
+
const auth = await codexAuthStatus(bin, env);
|
|
2425
|
+
if (auth.loggedIn === false) {
|
|
2426
|
+
return {
|
|
2427
|
+
codexVersion: version,
|
|
2428
|
+
codexReady: false,
|
|
2429
|
+
codexProblem: "Codex is not signed in. Run `codex login` on this computer."
|
|
2430
|
+
};
|
|
2431
|
+
}
|
|
2432
|
+
return { codexVersion: version, codexReady: auth.loggedIn, codexProblem: null };
|
|
2433
|
+
}
|
|
2434
|
+
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;
|
|
2435
|
+
function looksLikeCodexSignInFailure(text) {
|
|
2436
|
+
return !!text && SIGN_IN_FAILURE2.test(text);
|
|
2437
|
+
}
|
|
2438
|
+
var MODEL_NAME2 = /^[A-Za-z0-9][\w.:@/-]{0,199}$/;
|
|
2439
|
+
function assertValidCodexModel(model) {
|
|
2440
|
+
if (model && !MODEL_NAME2.test(model)) {
|
|
2441
|
+
throw new Error(
|
|
2442
|
+
`The model "${model.slice(0, 80)}" is not a valid Codex model name; the runner refused to start it.`
|
|
2443
|
+
);
|
|
2444
|
+
}
|
|
2445
|
+
}
|
|
2446
|
+
function codexArgs(launch) {
|
|
2447
|
+
const args = ["exec", "--json", "--skip-git-repo-check", "--sandbox", launch.sandbox];
|
|
2448
|
+
if (launch.sandbox === "workspace-write" && launch.networkAccess) {
|
|
2449
|
+
args.push("-c", "sandbox_workspace_write.network_access=true");
|
|
2450
|
+
}
|
|
2451
|
+
if (launch.model) {
|
|
2452
|
+
assertValidCodexModel(launch.model);
|
|
2453
|
+
args.push(`--model=${launch.model}`);
|
|
2454
|
+
}
|
|
2455
|
+
args.push("-C", launch.cwd);
|
|
2456
|
+
if (launch.resume) args.push("resume", launch.resume);
|
|
2457
|
+
args.push("-");
|
|
2458
|
+
return args;
|
|
2459
|
+
}
|
|
2460
|
+
function codexFirstPrompt(systemPrompt, prompt) {
|
|
2461
|
+
return systemPrompt ? `${systemPrompt}
|
|
2462
|
+
|
|
2463
|
+
---
|
|
2464
|
+
|
|
2465
|
+
${prompt}` : prompt;
|
|
2466
|
+
}
|
|
2467
|
+
|
|
2468
|
+
// src/drivers/codex/codex-stream-mapper.ts
|
|
2469
|
+
import { randomBytes } from "node:crypto";
|
|
2470
|
+
var CodexStreamMapper = class {
|
|
2471
|
+
running = false;
|
|
2472
|
+
/** The turn's end was reported: what its process says afterwards is no news. */
|
|
2473
|
+
ended = false;
|
|
2474
|
+
turn = 0;
|
|
2475
|
+
turnKey = "";
|
|
2476
|
+
lastMessage = null;
|
|
2477
|
+
/** Error the turn reported before its end (`error` lines). */
|
|
2478
|
+
lastError = null;
|
|
2479
|
+
/** Each session's mapper has its own tag, so a restarted runner's turns are not taken for earlier ones. */
|
|
2480
|
+
tag = randomBytes(3).toString("hex");
|
|
2481
|
+
constructor() {
|
|
2482
|
+
this.beginTurn();
|
|
2483
|
+
}
|
|
2484
|
+
markRunning() {
|
|
2485
|
+
this.running = true;
|
|
2486
|
+
this.beginTurn();
|
|
2487
|
+
}
|
|
2488
|
+
beginTurn() {
|
|
2489
|
+
this.turn++;
|
|
2490
|
+
this.turnKey = `codex-${this.tag}-t${this.turn}`;
|
|
2491
|
+
this.ended = false;
|
|
2492
|
+
this.lastMessage = null;
|
|
2493
|
+
this.lastError = null;
|
|
2494
|
+
}
|
|
2495
|
+
map(line) {
|
|
2496
|
+
const out = { events: [] };
|
|
2497
|
+
if (this.ended) return out;
|
|
2498
|
+
switch (line.type) {
|
|
2499
|
+
case "thread.started":
|
|
2500
|
+
if (typeof line.thread_id === "string" && line.thread_id) {
|
|
2501
|
+
out.conversationId = line.thread_id;
|
|
2502
|
+
}
|
|
2503
|
+
this.ensureRunning(out);
|
|
2504
|
+
break;
|
|
2505
|
+
case "turn.started":
|
|
2506
|
+
this.ensureRunning(out);
|
|
2507
|
+
break;
|
|
2508
|
+
case "item.started":
|
|
2509
|
+
case "item.updated":
|
|
2510
|
+
case "item.completed":
|
|
2511
|
+
if (line.item && typeof line.item === "object") {
|
|
2512
|
+
this.ensureRunning(out);
|
|
2513
|
+
this.mapItem(line.type, line.item, out);
|
|
2514
|
+
}
|
|
2515
|
+
break;
|
|
2516
|
+
case "turn.completed":
|
|
2517
|
+
out.turnEnd = { text: this.lastMessage, isError: false, subtype: "success" };
|
|
2518
|
+
this.endTurn();
|
|
2519
|
+
break;
|
|
2520
|
+
case "turn.failed": {
|
|
2521
|
+
const message = errorMessage(line.error) ?? this.lastError;
|
|
2522
|
+
out.turnEnd = { text: message, isError: true, subtype: "turn_failed" };
|
|
2523
|
+
this.endTurn();
|
|
2524
|
+
break;
|
|
2525
|
+
}
|
|
2526
|
+
case "error": {
|
|
2527
|
+
const message = errorMessage(line) ?? "Codex reported an error.";
|
|
2528
|
+
if (/\b(retrying|reconnecting)\b/i.test(message)) break;
|
|
2529
|
+
out.turnEnd = { text: message, isError: true, subtype: "error" };
|
|
2530
|
+
this.endTurn();
|
|
2531
|
+
break;
|
|
2532
|
+
}
|
|
2533
|
+
}
|
|
2534
|
+
return out;
|
|
2535
|
+
}
|
|
2536
|
+
ensureRunning(out) {
|
|
2537
|
+
if (this.running) return;
|
|
2538
|
+
this.running = true;
|
|
2539
|
+
out.turnStarted = true;
|
|
2540
|
+
out.events.push({ type: "status", status: "running" });
|
|
2541
|
+
}
|
|
2542
|
+
endTurn() {
|
|
2543
|
+
this.running = false;
|
|
2544
|
+
this.ended = true;
|
|
2545
|
+
}
|
|
2546
|
+
mapItem(phase, item, out) {
|
|
2547
|
+
const id = typeof item.id === "string" && item.id ? item.id : null;
|
|
2548
|
+
if (!id) return;
|
|
2549
|
+
const key = `${this.turnKey}:${id}`;
|
|
2550
|
+
const done = phase === "item.completed";
|
|
2551
|
+
switch (item.type) {
|
|
2552
|
+
case "agent_message": {
|
|
2553
|
+
const text = typeof item.text === "string" ? item.text : "";
|
|
2554
|
+
if (!done || !text.trim()) break;
|
|
2555
|
+
this.lastMessage = text;
|
|
2556
|
+
out.events.push({
|
|
2557
|
+
type: "assistant_message",
|
|
2558
|
+
providerEventId: key,
|
|
2559
|
+
text: capText(text).text
|
|
2560
|
+
});
|
|
2561
|
+
break;
|
|
2562
|
+
}
|
|
2563
|
+
case "reasoning": {
|
|
2564
|
+
if (!done) break;
|
|
2565
|
+
const text = typeof item.text === "string" && item.text.trim() ? item.text : null;
|
|
2566
|
+
out.events.push({
|
|
2567
|
+
type: "thinking",
|
|
2568
|
+
providerEventId: key,
|
|
2569
|
+
text: text === null ? null : capText(text).text
|
|
2570
|
+
});
|
|
2571
|
+
break;
|
|
2572
|
+
}
|
|
2573
|
+
case "command_execution": {
|
|
2574
|
+
const command = typeof item.command === "string" ? item.command : "";
|
|
2575
|
+
const exitCode = typeof item.exit_code === "number" ? item.exit_code : null;
|
|
2576
|
+
const failed = item.status === "failed" || item.status === "declined" || exitCode !== null && exitCode !== 0;
|
|
2577
|
+
const status2 = done ? failed ? "failed" : "completed" : "running";
|
|
2578
|
+
const output = typeof item.aggregated_output === "string" ? item.aggregated_output : "";
|
|
2579
|
+
this.pushTool(out, key, "Bash", status2, { command }, done ? output : null);
|
|
2580
|
+
break;
|
|
2581
|
+
}
|
|
2582
|
+
case "file_change": {
|
|
2583
|
+
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 })) : [];
|
|
2584
|
+
const failed = item.status === "failed";
|
|
2585
|
+
const status2 = done || item.status === "completed" ? failed ? "failed" : "completed" : "running";
|
|
2586
|
+
const summary = changes.map((c) => `${c.kind ?? "edit"} ${c.path}`).join("\n");
|
|
2587
|
+
this.pushTool(
|
|
2588
|
+
out,
|
|
2589
|
+
key,
|
|
2590
|
+
"Edit",
|
|
2591
|
+
status2,
|
|
2592
|
+
{ paths: changes.map((c) => c.path), changes },
|
|
2593
|
+
status2 === "running" ? null : summary
|
|
2594
|
+
);
|
|
2595
|
+
break;
|
|
2596
|
+
}
|
|
2597
|
+
case "mcp_tool_call": {
|
|
2598
|
+
const name = typeof item.server === "string" && typeof item.tool === "string" ? `${item.server}.${item.tool}` : String(item.tool ?? "mcp");
|
|
2599
|
+
const error = errorMessage(item.error);
|
|
2600
|
+
const failed = item.status === "failed" || !!error;
|
|
2601
|
+
const status2 = done ? failed ? "failed" : "completed" : "running";
|
|
2602
|
+
const output = error ?? (item.result !== void 0 ? mcpResultText(item.result) : null);
|
|
2603
|
+
this.pushTool(out, key, name, status2, item.arguments ?? {}, done ? output : null);
|
|
2604
|
+
break;
|
|
2605
|
+
}
|
|
2606
|
+
case "web_search": {
|
|
2607
|
+
const query = typeof item.query === "string" ? item.query : "";
|
|
2608
|
+
this.pushTool(out, key, "WebSearch", done ? "completed" : "running", { query }, null);
|
|
2609
|
+
break;
|
|
2610
|
+
}
|
|
2611
|
+
case "todo_list": {
|
|
2612
|
+
const todos = Array.isArray(item.items) ? item.items.filter((t) => t && typeof t.text === "string").map((t) => ({ text: t.text, completed: t.completed === true })) : [];
|
|
2613
|
+
this.pushTool(out, key, "TodoWrite", done ? "completed" : "running", { todos }, null);
|
|
2614
|
+
break;
|
|
2615
|
+
}
|
|
2616
|
+
case "error": {
|
|
2617
|
+
const message = errorMessage(item);
|
|
2618
|
+
if (done && message) {
|
|
2619
|
+
this.lastError = message;
|
|
2620
|
+
out.events.push({ type: "error", message: capText(message).text, retryable: false });
|
|
2621
|
+
}
|
|
2622
|
+
break;
|
|
2623
|
+
}
|
|
2624
|
+
}
|
|
2625
|
+
}
|
|
2626
|
+
pushTool(out, key, name, status2, input, output) {
|
|
2627
|
+
const tool = { callId: key, name, status: status2, input };
|
|
2628
|
+
if (output !== null) {
|
|
2629
|
+
const capped = capText(output);
|
|
2630
|
+
tool.output = capped.text;
|
|
2631
|
+
if (capped.truncated) tool.truncated = true;
|
|
2632
|
+
}
|
|
2633
|
+
out.events.push({ type: "tool_call", providerEventId: key, tool });
|
|
2634
|
+
}
|
|
2635
|
+
};
|
|
2636
|
+
function errorMessage(value) {
|
|
2637
|
+
if (typeof value === "string") return value.trim() || null;
|
|
2638
|
+
if (value && typeof value === "object") {
|
|
2639
|
+
const m = value.message;
|
|
2640
|
+
if (typeof m === "string" && m.trim()) return m;
|
|
2641
|
+
}
|
|
2642
|
+
return null;
|
|
2643
|
+
}
|
|
2644
|
+
function mcpResultText(result) {
|
|
2645
|
+
const content = result?.content;
|
|
2646
|
+
if (Array.isArray(content)) {
|
|
2647
|
+
const text = content.map((b) => b?.type === "text" && typeof b.text === "string" ? b.text : "").filter(Boolean).join("\n");
|
|
2648
|
+
if (text) return text;
|
|
2649
|
+
}
|
|
2650
|
+
return result == null ? "" : JSON.stringify(result);
|
|
2651
|
+
}
|
|
2652
|
+
|
|
2653
|
+
// src/drivers/codex.ts
|
|
2654
|
+
var codexDriver = {
|
|
2655
|
+
kind: "codex",
|
|
2656
|
+
displayName: "Codex",
|
|
2657
|
+
processModel: "per_turn",
|
|
2658
|
+
resolveBinary: (env) => findCodex(env),
|
|
2659
|
+
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`.",
|
|
2660
|
+
readFeatures: async () => ({}),
|
|
2661
|
+
probe: async (env) => ({
|
|
2662
|
+
claudeVersion: null,
|
|
2663
|
+
claudeReady: null,
|
|
2664
|
+
...await probeCodex(env),
|
|
2665
|
+
runsCodex: true
|
|
2666
|
+
}),
|
|
2667
|
+
doctor: doctor2,
|
|
2668
|
+
validateModel: (model) => assertValidCodexModel(model),
|
|
2669
|
+
launch(input) {
|
|
2670
|
+
const prompt = input.resume ? input.prompt ?? "" : codexFirstPrompt(input.systemPrompt, input.prompt ?? "");
|
|
2671
|
+
const cmd = codexCommand(
|
|
2672
|
+
input.bin,
|
|
2673
|
+
codexArgs({
|
|
2674
|
+
cwd: input.cwd,
|
|
2675
|
+
model: input.model,
|
|
2676
|
+
sandbox: input.agentConfig?.codexSandbox ?? "workspace-write",
|
|
2677
|
+
networkAccess: input.agentConfig?.codexNetworkAccess === true,
|
|
2678
|
+
resume: input.resume
|
|
2679
|
+
})
|
|
2680
|
+
);
|
|
2681
|
+
return { ...cmd, stdin: prompt };
|
|
2682
|
+
},
|
|
2683
|
+
createMapper: () => new CodexStreamMapper(),
|
|
2684
|
+
looksLikeSignInFailure: looksLikeCodexSignInFailure,
|
|
2685
|
+
turnFailedToSignIn: (turn) => turn.isError && looksLikeCodexSignInFailure(turn.text),
|
|
2686
|
+
signInFix: (env) => codexSignInFix(env),
|
|
2687
|
+
turnErrorMessage: turnErrorMessage2,
|
|
2688
|
+
startupHint(stderr) {
|
|
2689
|
+
if (looksLikeCodexSignInFailure(stderr)) {
|
|
2690
|
+
return ` Codex does not seem to be signed in on the runner\u2019s computer. ${codexSignInFix()}`;
|
|
2691
|
+
}
|
|
2692
|
+
if (codexResumeNotFound(stderr)) {
|
|
2693
|
+
return " The Codex conversation to resume was not found on this computer.";
|
|
2694
|
+
}
|
|
2695
|
+
return "";
|
|
2696
|
+
},
|
|
2697
|
+
resumeNotFound: (stderr) => codexResumeNotFound(stderr)
|
|
2698
|
+
};
|
|
2699
|
+
function codexResumeNotFound(text) {
|
|
2700
|
+
return /no (rollout|session|thread|conversation)s? found|(thread|session|conversation|rollout)\b[^\n]{0,60}\bnot found/i.test(
|
|
2701
|
+
text
|
|
2702
|
+
);
|
|
2703
|
+
}
|
|
2704
|
+
function turnErrorMessage2(turn) {
|
|
2705
|
+
if (turn.isError && looksLikeCodexSignInFailure(turn.text)) {
|
|
2706
|
+
return `Codex could not sign in (${turn.text.slice(0, 200)}). ${codexSignInFix()} Then send a message here to try again.`;
|
|
2707
|
+
}
|
|
2708
|
+
return turn.text ? `Codex reported an error: ${turn.text.slice(0, 500)}` : "Codex ended the turn with an error.";
|
|
2709
|
+
}
|
|
2710
|
+
async function doctor2(env = process.env) {
|
|
2711
|
+
const checks = [];
|
|
2712
|
+
const bin = await findCodex(env);
|
|
2713
|
+
if (!bin) {
|
|
2714
|
+
checks.push({
|
|
2715
|
+
name: "Codex",
|
|
2716
|
+
level: env.DT_RUNNER_CODEX_BIN ? "fail" : "ok",
|
|
2717
|
+
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"
|
|
2718
|
+
});
|
|
2719
|
+
return checks;
|
|
2720
|
+
}
|
|
2721
|
+
const version = await codexVersion(bin, env);
|
|
2722
|
+
checks.push({
|
|
2723
|
+
name: "Codex",
|
|
2724
|
+
level: version ? "ok" : "warn",
|
|
2725
|
+
detail: version ? `${version} (${bin})` : `${bin} --version failed: Codex runs will not start`
|
|
2726
|
+
});
|
|
2727
|
+
if (!version) return checks;
|
|
2728
|
+
const auth = await codexAuthStatus(bin, env);
|
|
2729
|
+
checks.push(
|
|
2730
|
+
auth.loggedIn === true ? {
|
|
2731
|
+
name: "Codex sign-in",
|
|
2732
|
+
level: "ok",
|
|
2733
|
+
detail: `signed in${auth.authMethod ? ` (${auth.authMethod})` : ""}`
|
|
2734
|
+
} : auth.loggedIn === false ? {
|
|
2735
|
+
name: "Codex sign-in",
|
|
2736
|
+
level: "warn",
|
|
2737
|
+
detail: "not signed in: run `codex login` before starting Codex runs"
|
|
2738
|
+
} : {
|
|
2739
|
+
name: "Codex sign-in",
|
|
2740
|
+
level: "warn",
|
|
2741
|
+
detail: "could not tell (`codex login status` failed)"
|
|
2742
|
+
}
|
|
2743
|
+
);
|
|
2744
|
+
const key = codexKeyVariable(env);
|
|
2745
|
+
if (key) {
|
|
2746
|
+
checks.push({
|
|
2747
|
+
name: key,
|
|
2748
|
+
level: "warn",
|
|
2749
|
+
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.`
|
|
2750
|
+
});
|
|
2751
|
+
}
|
|
2752
|
+
return checks;
|
|
2753
|
+
}
|
|
2754
|
+
|
|
2755
|
+
// src/drivers/cursor/cursor.ts
|
|
2756
|
+
async function findCursor(env = process.env) {
|
|
2757
|
+
const override = env.DT_RUNNER_CURSOR_BIN?.trim();
|
|
2758
|
+
if (override) return findOverride(override, env);
|
|
2759
|
+
return await which("cursor-agent", env) ?? await which("agent", env);
|
|
2760
|
+
}
|
|
2761
|
+
function runCursor(bin, args, timeoutMs, env) {
|
|
2762
|
+
const cmd = launcherCommand(bin, args);
|
|
2763
|
+
return exec(cmd.bin, cmd.args, { timeoutMs, env });
|
|
2764
|
+
}
|
|
2765
|
+
async function cursorVersion(bin, env = process.env) {
|
|
2766
|
+
try {
|
|
2767
|
+
const res = await runCursor(bin, ["--version"], 15e3, env);
|
|
2768
|
+
if (res.code !== 0) return null;
|
|
2769
|
+
return res.stdout.trim().split("\n")[0] || null;
|
|
2770
|
+
} catch {
|
|
2771
|
+
return null;
|
|
2772
|
+
}
|
|
2773
|
+
}
|
|
2774
|
+
async function cursorAuthStatus(bin, env = process.env) {
|
|
2775
|
+
try {
|
|
2776
|
+
const res = await runCursor(bin, ["status"], 2e4, env);
|
|
2777
|
+
const said = `${res.stdout}
|
|
2778
|
+
${res.stderr}`;
|
|
2779
|
+
if (/not (logged|signed) in|not authenticated|login required|authentication required/i.test(said)) {
|
|
2780
|
+
return { loggedIn: false };
|
|
2781
|
+
}
|
|
2782
|
+
if (res.code === 0 && /logged in|signed in|authenticated/i.test(said))
|
|
2783
|
+
return { loggedIn: true };
|
|
2784
|
+
return { loggedIn: null };
|
|
2785
|
+
} catch {
|
|
2786
|
+
return { loggedIn: null };
|
|
2787
|
+
}
|
|
2788
|
+
}
|
|
2789
|
+
function cursorKeyVariable(env = process.env) {
|
|
2790
|
+
return env.CURSOR_API_KEY ? "CURSOR_API_KEY" : null;
|
|
2791
|
+
}
|
|
2792
|
+
function cursorSignInFix(env = process.env) {
|
|
2793
|
+
if (cursorKeyVariable(env)) {
|
|
2794
|
+
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.";
|
|
2795
|
+
}
|
|
2796
|
+
return "On the runner\u2019s computer, run `cursor-agent login` and sign in, and check that `cursor-agent status` says you are logged in.";
|
|
2797
|
+
}
|
|
2798
|
+
async function probeCursor(env = process.env) {
|
|
2799
|
+
const bin = await findCursor(env);
|
|
2800
|
+
if (!bin) {
|
|
2801
|
+
return {
|
|
2802
|
+
cursorVersion: null,
|
|
2803
|
+
cursorReady: false,
|
|
2804
|
+
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."
|
|
2805
|
+
};
|
|
2806
|
+
}
|
|
2807
|
+
const version = await cursorVersion(bin, env);
|
|
2808
|
+
if (!version) {
|
|
2809
|
+
return {
|
|
2810
|
+
cursorVersion: null,
|
|
2811
|
+
cursorReady: false,
|
|
2812
|
+
cursorProblem: "`cursor-agent --version` failed; reinstall or update the Cursor Agent CLI."
|
|
2813
|
+
};
|
|
2814
|
+
}
|
|
2815
|
+
const auth = await cursorAuthStatus(bin, env);
|
|
2816
|
+
if (auth.loggedIn === false) {
|
|
2817
|
+
return {
|
|
2818
|
+
cursorVersion: version,
|
|
2819
|
+
cursorReady: false,
|
|
2820
|
+
cursorProblem: "The Cursor Agent CLI is not signed in. Run `cursor-agent login` on this computer."
|
|
2821
|
+
};
|
|
2822
|
+
}
|
|
2823
|
+
return { cursorVersion: version, cursorReady: auth.loggedIn, cursorProblem: null };
|
|
2824
|
+
}
|
|
2825
|
+
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;
|
|
2826
|
+
function looksLikeCursorSignInFailure(text) {
|
|
2827
|
+
return !!text && SIGN_IN_FAILURE3.test(text);
|
|
2828
|
+
}
|
|
2829
|
+
var MODEL_NAME3 = /^[A-Za-z0-9][\w.:@/-]{0,199}$/;
|
|
2830
|
+
function assertValidCursorModel(model) {
|
|
2831
|
+
if (model && !MODEL_NAME3.test(model)) {
|
|
2832
|
+
throw new Error(
|
|
2833
|
+
`The model "${model.slice(0, 80)}" is not a valid Cursor model name; the runner refused to start it.`
|
|
2834
|
+
);
|
|
2835
|
+
}
|
|
2836
|
+
}
|
|
2837
|
+
function cursorArgs(launch) {
|
|
2838
|
+
const args = ["-p", "--output-format", "stream-json"];
|
|
2839
|
+
if (launch.model) {
|
|
2840
|
+
assertValidCursorModel(launch.model);
|
|
2841
|
+
args.push(`--model=${launch.model}`);
|
|
2842
|
+
}
|
|
2843
|
+
if (launch.resume) args.push(`--resume=${launch.resume}`);
|
|
2844
|
+
if (launch.force) args.push("--force");
|
|
2845
|
+
args.push(launch.prompt.startsWith("-") ? `
|
|
2846
|
+
${launch.prompt}` : launch.prompt);
|
|
2847
|
+
return args;
|
|
2848
|
+
}
|
|
2849
|
+
function cursorFirstPrompt(systemPrompt, prompt) {
|
|
2850
|
+
return systemPrompt ? `${systemPrompt}
|
|
2851
|
+
|
|
2852
|
+
---
|
|
2853
|
+
|
|
2854
|
+
${prompt}` : prompt;
|
|
2855
|
+
}
|
|
2856
|
+
|
|
2857
|
+
// src/drivers/cursor/cursor-stream-mapper.ts
|
|
2858
|
+
import { randomBytes as randomBytes2 } from "node:crypto";
|
|
2859
|
+
var CursorStreamMapper = class {
|
|
2860
|
+
running = false;
|
|
2861
|
+
/** The turn's end was reported: what its process says afterwards is no news. */
|
|
2862
|
+
ended = false;
|
|
2863
|
+
turn = 0;
|
|
2864
|
+
turnKey = "";
|
|
2865
|
+
messages = 0;
|
|
2866
|
+
lastMessage = null;
|
|
2867
|
+
/** Each session's mapper has its own tag, so a restarted runner's turns are not taken for earlier ones. */
|
|
2868
|
+
tag = randomBytes2(3).toString("hex");
|
|
2869
|
+
constructor() {
|
|
2870
|
+
this.beginTurn();
|
|
2871
|
+
}
|
|
2872
|
+
markRunning() {
|
|
2873
|
+
this.running = true;
|
|
2874
|
+
this.beginTurn();
|
|
2875
|
+
}
|
|
2876
|
+
beginTurn() {
|
|
2877
|
+
this.turn++;
|
|
2878
|
+
this.turnKey = `cursor-${this.tag}-t${this.turn}`;
|
|
2879
|
+
this.ended = false;
|
|
2880
|
+
this.messages = 0;
|
|
2881
|
+
this.lastMessage = null;
|
|
2882
|
+
}
|
|
2883
|
+
map(line) {
|
|
2884
|
+
const out = { events: [] };
|
|
2885
|
+
if (this.ended) return out;
|
|
2886
|
+
switch (line.type) {
|
|
2887
|
+
case "system":
|
|
2888
|
+
if (line.subtype === "init") {
|
|
2889
|
+
if (typeof line.session_id === "string" && line.session_id) {
|
|
2890
|
+
out.conversationId = line.session_id;
|
|
2891
|
+
}
|
|
2892
|
+
this.ensureRunning(out);
|
|
2893
|
+
}
|
|
2894
|
+
break;
|
|
2895
|
+
case "assistant": {
|
|
2896
|
+
this.ensureRunning(out);
|
|
2897
|
+
const content = Array.isArray(line.message?.content) ? line.message.content : [];
|
|
2898
|
+
const text = content.map((b) => b?.type === "text" && typeof b.text === "string" ? b.text : "").join("");
|
|
2899
|
+
if (!text.trim()) break;
|
|
2900
|
+
this.lastMessage = text;
|
|
2901
|
+
out.events.push({
|
|
2902
|
+
type: "assistant_message",
|
|
2903
|
+
providerEventId: `${this.turnKey}:msg:${this.messages++}`,
|
|
2904
|
+
text: capText(text).text
|
|
2905
|
+
});
|
|
2906
|
+
break;
|
|
2907
|
+
}
|
|
2908
|
+
case "tool_call":
|
|
2909
|
+
if (typeof line.call_id === "string" && line.call_id && line.tool_call) {
|
|
2910
|
+
this.ensureRunning(out);
|
|
2911
|
+
this.mapToolCall(line, out);
|
|
2912
|
+
}
|
|
2913
|
+
break;
|
|
2914
|
+
case "result": {
|
|
2915
|
+
const text = typeof line.result === "string" && line.result ? line.result : null;
|
|
2916
|
+
const subtype = typeof line.subtype === "string" ? line.subtype : null;
|
|
2917
|
+
out.turnEnd = {
|
|
2918
|
+
text: text ?? this.lastMessage,
|
|
2919
|
+
isError: line.is_error === true || (subtype ?? "success") !== "success",
|
|
2920
|
+
subtype
|
|
2921
|
+
};
|
|
2922
|
+
this.running = false;
|
|
2923
|
+
this.ended = true;
|
|
2924
|
+
break;
|
|
2925
|
+
}
|
|
2926
|
+
}
|
|
2927
|
+
return out;
|
|
2928
|
+
}
|
|
2929
|
+
ensureRunning(out) {
|
|
2930
|
+
if (this.running) return;
|
|
2931
|
+
this.running = true;
|
|
2932
|
+
out.turnStarted = true;
|
|
2933
|
+
out.events.push({ type: "status", status: "running" });
|
|
2934
|
+
}
|
|
2935
|
+
mapToolCall(line, out) {
|
|
2936
|
+
const [kind, call] = Object.entries(line.tool_call)[0] ?? [];
|
|
2937
|
+
if (!kind || !call || typeof call !== "object") return;
|
|
2938
|
+
const key = `${this.turnKey}:${line.call_id}`;
|
|
2939
|
+
const done = line.subtype === "completed";
|
|
2940
|
+
const { name, input } = toolNameAndInput(kind, call);
|
|
2941
|
+
const tool = { callId: key, name, status: "running", input };
|
|
2942
|
+
if (done) {
|
|
2943
|
+
const outcome = toolOutcome(kind, call.result);
|
|
2944
|
+
tool.status = outcome.failed ? "failed" : "completed";
|
|
2945
|
+
if (outcome.output !== null) {
|
|
2946
|
+
const capped = capText(outcome.output);
|
|
2947
|
+
tool.output = capped.text;
|
|
2948
|
+
if (capped.truncated) tool.truncated = true;
|
|
2949
|
+
}
|
|
2950
|
+
}
|
|
2951
|
+
out.events.push({ type: "tool_call", providerEventId: key, tool });
|
|
2952
|
+
}
|
|
2953
|
+
};
|
|
2954
|
+
var TOOL_NAMES = {
|
|
2955
|
+
shellToolCall: "Bash",
|
|
2956
|
+
readToolCall: "Read",
|
|
2957
|
+
editToolCall: "Edit",
|
|
2958
|
+
writeToolCall: "Write",
|
|
2959
|
+
deleteToolCall: "Delete",
|
|
2960
|
+
grepToolCall: "Grep",
|
|
2961
|
+
globToolCall: "Glob",
|
|
2962
|
+
lsToolCall: "LS",
|
|
2963
|
+
updateTodosToolCall: "TodoWrite",
|
|
2964
|
+
todoToolCall: "TodoWrite",
|
|
2965
|
+
webSearchToolCall: "WebSearch"
|
|
2966
|
+
};
|
|
2967
|
+
function toolNameAndInput(kind, call) {
|
|
2968
|
+
if (kind === "function") {
|
|
2969
|
+
let input = call.arguments ?? {};
|
|
2970
|
+
if (typeof input === "string") {
|
|
2971
|
+
try {
|
|
2972
|
+
input = JSON.parse(input);
|
|
2973
|
+
} catch {
|
|
2974
|
+
}
|
|
2975
|
+
}
|
|
2976
|
+
return { name: typeof call.name === "string" && call.name ? call.name : "tool", input };
|
|
2977
|
+
}
|
|
2978
|
+
return {
|
|
2979
|
+
name: TOOL_NAMES[kind] ?? kind.replace(/ToolCall$/, ""),
|
|
2980
|
+
input: call.args ?? {}
|
|
2981
|
+
};
|
|
2982
|
+
}
|
|
2983
|
+
function toolOutcome(kind, result) {
|
|
2984
|
+
if (!result || typeof result !== "object") return { failed: false, output: null };
|
|
2985
|
+
const r = result;
|
|
2986
|
+
const failure = r.error ?? r.failure ?? r.rejected;
|
|
2987
|
+
if (failure !== void 0) return { failed: true, output: describe(failure) };
|
|
2988
|
+
const success = r.success;
|
|
2989
|
+
if (success === void 0) return { failed: false, output: describe(r) };
|
|
2990
|
+
if (kind === "shellToolCall" && success && typeof success === "object") {
|
|
2991
|
+
const text = [success.stdout, success.stderr].filter((t) => typeof t === "string" && t).join("\n");
|
|
2992
|
+
const exitCode = typeof success.exitCode === "number" ? success.exitCode : 0;
|
|
2993
|
+
return { failed: exitCode !== 0, output: text };
|
|
2994
|
+
}
|
|
2995
|
+
if (kind === "readToolCall" && typeof success?.content === "string") {
|
|
2996
|
+
return { failed: false, output: success.content };
|
|
2997
|
+
}
|
|
2998
|
+
return { failed: false, output: describe(success) };
|
|
2999
|
+
}
|
|
3000
|
+
function describe(value) {
|
|
3001
|
+
if (typeof value === "string") return value;
|
|
3002
|
+
const message = value?.message ?? value?.reason;
|
|
3003
|
+
if (typeof message === "string" && message) return message;
|
|
3004
|
+
return value == null ? "" : JSON.stringify(value);
|
|
3005
|
+
}
|
|
3006
|
+
|
|
3007
|
+
// src/drivers/cursor.ts
|
|
3008
|
+
var cursorDriver = {
|
|
3009
|
+
kind: "cursor",
|
|
3010
|
+
displayName: "Cursor",
|
|
3011
|
+
processModel: "per_turn",
|
|
3012
|
+
resolveBinary: (env) => findCursor(env),
|
|
3013
|
+
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`.",
|
|
3014
|
+
readFeatures: async () => ({}),
|
|
3015
|
+
probe: async (env) => ({
|
|
3016
|
+
claudeVersion: null,
|
|
3017
|
+
claudeReady: null,
|
|
3018
|
+
...await probeCursor(env),
|
|
3019
|
+
runsCursor: true
|
|
3020
|
+
}),
|
|
3021
|
+
doctor: doctor3,
|
|
3022
|
+
validateModel: (model) => assertValidCursorModel(model),
|
|
3023
|
+
launch(input) {
|
|
3024
|
+
const prompt = input.resume ? input.prompt ?? "" : cursorFirstPrompt(input.systemPrompt, input.prompt ?? "");
|
|
3025
|
+
return launcherCommand(
|
|
3026
|
+
input.bin,
|
|
3027
|
+
cursorArgs({
|
|
3028
|
+
model: input.model,
|
|
3029
|
+
resume: input.resume,
|
|
3030
|
+
force: input.agentConfig?.cursorForce === true,
|
|
3031
|
+
prompt
|
|
3032
|
+
})
|
|
3033
|
+
);
|
|
3034
|
+
},
|
|
3035
|
+
createMapper: () => new CursorStreamMapper(),
|
|
3036
|
+
looksLikeSignInFailure: looksLikeCursorSignInFailure,
|
|
3037
|
+
turnFailedToSignIn: (turn) => turn.isError && looksLikeCursorSignInFailure(turn.text),
|
|
3038
|
+
signInFix: (env) => cursorSignInFix(env),
|
|
3039
|
+
turnErrorMessage: turnErrorMessage3,
|
|
3040
|
+
startupHint(stderr) {
|
|
3041
|
+
if (looksLikeCursorSignInFailure(stderr)) {
|
|
3042
|
+
return ` The Cursor Agent CLI does not seem to be signed in on the runner\u2019s computer. ${cursorSignInFix()}`;
|
|
3043
|
+
}
|
|
3044
|
+
if (cursorResumeNotFound(stderr)) {
|
|
3045
|
+
return " The Cursor chat to resume was not found on this computer.";
|
|
3046
|
+
}
|
|
3047
|
+
return "";
|
|
3048
|
+
},
|
|
3049
|
+
resumeNotFound: (stderr) => cursorResumeNotFound(stderr)
|
|
3050
|
+
};
|
|
3051
|
+
function cursorResumeNotFound(text) {
|
|
3052
|
+
return /no (chat|session|conversation)s? found|(chat|session|conversation)\b[^\n]{0,60}\bnot found/i.test(
|
|
3053
|
+
text
|
|
3054
|
+
);
|
|
3055
|
+
}
|
|
3056
|
+
function turnErrorMessage3(turn) {
|
|
3057
|
+
if (turn.isError && looksLikeCursorSignInFailure(turn.text)) {
|
|
3058
|
+
return `The Cursor Agent CLI could not sign in (${turn.text.slice(0, 200)}). ${cursorSignInFix()} Then send a message here to try again.`;
|
|
3059
|
+
}
|
|
3060
|
+
return turn.text ? `Cursor reported an error: ${turn.text.slice(0, 500)}` : `Cursor ended the turn with an error (${turn.subtype ?? "unknown"}).`;
|
|
3061
|
+
}
|
|
3062
|
+
async function doctor3(env = process.env) {
|
|
3063
|
+
const checks = [];
|
|
3064
|
+
const bin = await findCursor(env);
|
|
3065
|
+
if (!bin) {
|
|
3066
|
+
checks.push({
|
|
3067
|
+
name: "Cursor Agent CLI",
|
|
3068
|
+
level: env.DT_RUNNER_CURSOR_BIN ? "fail" : "ok",
|
|
3069
|
+
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"
|
|
3070
|
+
});
|
|
3071
|
+
return checks;
|
|
3072
|
+
}
|
|
3073
|
+
const version = await cursorVersion(bin, env);
|
|
3074
|
+
checks.push({
|
|
3075
|
+
name: "Cursor Agent CLI",
|
|
3076
|
+
level: version ? "ok" : "warn",
|
|
3077
|
+
detail: version ? `${version} (${bin})` : `${bin} --version failed: Cursor runs will not start`
|
|
3078
|
+
});
|
|
3079
|
+
if (!version) return checks;
|
|
3080
|
+
const auth = await cursorAuthStatus(bin, env);
|
|
3081
|
+
checks.push(
|
|
3082
|
+
auth.loggedIn === true ? { name: "Cursor sign-in", level: "ok", detail: "signed in" } : auth.loggedIn === false ? {
|
|
3083
|
+
name: "Cursor sign-in",
|
|
3084
|
+
level: "warn",
|
|
3085
|
+
detail: "not signed in: run `cursor-agent login` before starting Cursor runs"
|
|
3086
|
+
} : {
|
|
3087
|
+
name: "Cursor sign-in",
|
|
3088
|
+
level: "warn",
|
|
3089
|
+
detail: "could not tell (`cursor-agent status` said nothing the runner reads)"
|
|
3090
|
+
}
|
|
3091
|
+
);
|
|
3092
|
+
if (cursorKeyVariable(env)) {
|
|
3093
|
+
checks.push({
|
|
3094
|
+
name: "CURSOR_API_KEY",
|
|
3095
|
+
level: "warn",
|
|
3096
|
+
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."
|
|
3097
|
+
});
|
|
3098
|
+
}
|
|
3099
|
+
return checks;
|
|
3100
|
+
}
|
|
3101
|
+
|
|
3102
|
+
// src/agent-driver.ts
|
|
3103
|
+
var DEFAULT_AGENT_KIND = "claude_code";
|
|
3104
|
+
var DRIVERS = new Map(
|
|
3105
|
+
[claudeCodeDriver, codexDriver, cursorDriver].map((d) => [d.kind, d])
|
|
3106
|
+
);
|
|
3107
|
+
function agentDriver(kind = DEFAULT_AGENT_KIND) {
|
|
3108
|
+
const driver = DRIVERS.get(kind || DEFAULT_AGENT_KIND);
|
|
3109
|
+
if (!driver) throw new Error(`This runner cannot run "${kind}" agents.`);
|
|
3110
|
+
return driver;
|
|
3111
|
+
}
|
|
3112
|
+
function agentDriverKinds() {
|
|
3113
|
+
return [...DRIVERS.keys()];
|
|
3114
|
+
}
|
|
3115
|
+
|
|
3116
|
+
// src/config.ts
|
|
3117
|
+
import { chmod, mkdir as mkdir3, readFile as readFile3, rm as rm3, writeFile as writeFile2 } from "node:fs/promises";
|
|
3118
|
+
import { homedir as homedir2 } from "node:os";
|
|
3119
|
+
import { dirname as dirname3, join as join7 } from "node:path";
|
|
3120
|
+
|
|
3121
|
+
// src/invocation.ts
|
|
3122
|
+
var RUNNER_PACKAGE = "@discovery-tree/runner";
|
|
3123
|
+
function launchedByNpx(env = process.env, argv1 = process.argv[1]) {
|
|
3124
|
+
if (env.npm_command === "exec") return true;
|
|
3125
|
+
return /[\\/](_npx|dlx)[\\/]/.test(argv1 ?? "");
|
|
3126
|
+
}
|
|
3127
|
+
function runnerCommand(subcommand, viaNpx = launchedByNpx()) {
|
|
3128
|
+
return viaNpx ? `npx ${RUNNER_PACKAGE}@latest ${subcommand}` : `dt-runner ${subcommand}`;
|
|
3129
|
+
}
|
|
3130
|
+
|
|
3131
|
+
// src/config.ts
|
|
3132
|
+
function runnerPaths(env = process.env) {
|
|
3133
|
+
const home = homedir2();
|
|
3134
|
+
if (process.platform === "win32") {
|
|
3135
|
+
const roaming = env.APPDATA || join7(home, "AppData", "Roaming");
|
|
3136
|
+
const local = env.LOCALAPPDATA || join7(home, "AppData", "Local");
|
|
3137
|
+
return {
|
|
3138
|
+
configFile: join7(roaming, "discovery-tree", "runner.json"),
|
|
3139
|
+
dataDir: join7(local, "discovery-tree", "runner"),
|
|
3140
|
+
stateDir: join7(local, "discovery-tree", "runner", "state")
|
|
3141
|
+
};
|
|
3142
|
+
}
|
|
3143
|
+
const config = env.XDG_CONFIG_HOME || join7(home, ".config");
|
|
3144
|
+
const data = env.XDG_DATA_HOME || join7(home, ".local", "share");
|
|
3145
|
+
const state = env.XDG_STATE_HOME || join7(home, ".local", "state");
|
|
3146
|
+
return {
|
|
3147
|
+
configFile: join7(config, "discovery-tree", "runner.json"),
|
|
3148
|
+
dataDir: join7(data, "discovery-tree", "runner"),
|
|
3149
|
+
stateDir: join7(state, "discovery-tree", "runner")
|
|
3150
|
+
};
|
|
3151
|
+
}
|
|
3152
|
+
var PERMISSION_MODES = [
|
|
3153
|
+
"acceptEdits",
|
|
3154
|
+
"auto",
|
|
3155
|
+
"default",
|
|
3156
|
+
"manual",
|
|
3157
|
+
"dontAsk",
|
|
3158
|
+
"plan",
|
|
3159
|
+
"bypassPermissions"
|
|
3160
|
+
];
|
|
3161
|
+
var DEFAULT_ALLOWED_TOOLS = [
|
|
3162
|
+
"Read",
|
|
3163
|
+
"Edit",
|
|
3164
|
+
"MultiEdit",
|
|
3165
|
+
"Write",
|
|
3166
|
+
"Glob",
|
|
3167
|
+
"Grep",
|
|
3168
|
+
"LS",
|
|
3169
|
+
"NotebookEdit",
|
|
3170
|
+
"TodoWrite",
|
|
3171
|
+
"Task",
|
|
3172
|
+
// Stops a command started with the Bash tool's background option (a dev server); its
|
|
3173
|
+
// output is a file the agent reads with Read.
|
|
3174
|
+
"TaskStop",
|
|
3175
|
+
"Bash(git status *)",
|
|
3176
|
+
"Bash(git diff *)",
|
|
3177
|
+
"Bash(git log *)",
|
|
3178
|
+
"Bash(git show *)",
|
|
3179
|
+
"Bash(git add *)",
|
|
3180
|
+
"Bash(git commit *)",
|
|
3181
|
+
"Bash(git restore *)",
|
|
3182
|
+
"Bash(git rm *)",
|
|
3183
|
+
"Bash(git mv *)",
|
|
3184
|
+
"Bash(git stash *)",
|
|
3185
|
+
"Bash(git blame *)",
|
|
3186
|
+
"Bash(git grep *)",
|
|
3187
|
+
"Bash(git rev-parse *)",
|
|
3188
|
+
"Bash(git ls-files *)",
|
|
3189
|
+
"Bash(git ls-tree *)",
|
|
3190
|
+
"Bash(git cat-file *)",
|
|
3191
|
+
"Bash(git describe *)",
|
|
3192
|
+
"Bash(git shortlog *)",
|
|
3193
|
+
"Bash(git reflog)",
|
|
3194
|
+
"Bash(git reflog show *)",
|
|
3195
|
+
"Bash(git show-ref *)",
|
|
3196
|
+
"Bash(git merge-base *)",
|
|
3197
|
+
// Not read-only on the network, and like `node *` it can run a command
|
|
3198
|
+
// (`--upload-pack`); on the list because agents fetch the base branch to compare with it.
|
|
3199
|
+
"Bash(git fetch *)",
|
|
3200
|
+
"Bash(git remote -v)",
|
|
3201
|
+
"Bash(git branch)",
|
|
3202
|
+
"Bash(git branch --show-current)",
|
|
3203
|
+
"Bash(git branch -a)",
|
|
3204
|
+
"Bash(git branch -r)",
|
|
3205
|
+
"Bash(git branch -v)",
|
|
3206
|
+
"Bash(git branch -vv)",
|
|
3207
|
+
"Bash(git branch --list *)",
|
|
3208
|
+
"Bash(git branch --contains *)",
|
|
3209
|
+
"Bash(git config --get *)",
|
|
3210
|
+
"Bash(git config --list *)",
|
|
3211
|
+
"Bash(git worktree list *)",
|
|
3212
|
+
"Bash(gh pr view *)",
|
|
3213
|
+
"Bash(gh pr diff *)",
|
|
3214
|
+
"Bash(gh pr checks *)",
|
|
3215
|
+
"Bash(gh pr list *)",
|
|
3216
|
+
"Bash(gh pr status *)",
|
|
3217
|
+
"Bash(gh run view *)",
|
|
3218
|
+
"Bash(gh run list *)",
|
|
3219
|
+
"Bash(gh issue view *)",
|
|
3220
|
+
"Bash(gh issue list *)",
|
|
3221
|
+
"Bash(gh repo view *)",
|
|
3222
|
+
"Bash(npm *)",
|
|
3223
|
+
"Bash(npx *)",
|
|
3224
|
+
"Bash(pnpm *)",
|
|
3225
|
+
"Bash(yarn *)",
|
|
3226
|
+
"Bash(node *)",
|
|
3227
|
+
"Bash(tsc *)",
|
|
3228
|
+
"Bash(python *)",
|
|
3229
|
+
"Bash(python3 *)",
|
|
3230
|
+
"Bash(pip *)",
|
|
3231
|
+
"Bash(pytest *)",
|
|
3232
|
+
"Bash(make *)",
|
|
3233
|
+
"Bash(cargo *)",
|
|
3234
|
+
"Bash(go *)",
|
|
3235
|
+
// The same, for other toolchains: they run the repository's code as npm and make do.
|
|
3236
|
+
"Bash(bun *)",
|
|
3237
|
+
"Bash(deno *)",
|
|
3238
|
+
"Bash(uv *)",
|
|
3239
|
+
"Bash(poetry *)",
|
|
3240
|
+
"Bash(ruby *)",
|
|
3241
|
+
"Bash(bundle *)",
|
|
3242
|
+
"Bash(rake *)",
|
|
3243
|
+
"Bash(rspec *)",
|
|
3244
|
+
"Bash(mvn *)",
|
|
3245
|
+
"Bash(gradle *)",
|
|
3246
|
+
"Bash(./gradlew *)",
|
|
3247
|
+
"Bash(dotnet *)",
|
|
3248
|
+
"Bash(swift *)",
|
|
3249
|
+
"Bash(java *)",
|
|
3250
|
+
"Bash(rustc *)",
|
|
3251
|
+
"Bash(jest *)",
|
|
3252
|
+
"Bash(vitest *)",
|
|
3253
|
+
"Bash(eslint *)",
|
|
3254
|
+
"Bash(prettier *)",
|
|
3255
|
+
"Bash(ruff *)",
|
|
3256
|
+
"Bash(mypy *)",
|
|
3257
|
+
"Bash(black *)",
|
|
3258
|
+
"Bash(ls *)",
|
|
3259
|
+
"Bash(cat *)",
|
|
3260
|
+
"Bash(head *)",
|
|
3261
|
+
"Bash(tail *)",
|
|
3262
|
+
"Bash(wc *)",
|
|
3263
|
+
"Bash(grep *)",
|
|
3264
|
+
"Bash(rg *)",
|
|
3265
|
+
"Bash(echo *)",
|
|
3266
|
+
"Bash(pwd)",
|
|
3267
|
+
"Bash(mkdir *)",
|
|
3268
|
+
"Bash(touch *)",
|
|
3269
|
+
"Bash(diff *)",
|
|
3270
|
+
"Bash(sort *)",
|
|
3271
|
+
"Bash(uniq *)",
|
|
3272
|
+
"Bash(which *)",
|
|
3273
|
+
// Read-only, and none prints a file's contents (which would get around the credential
|
|
3274
|
+
// deny rules below for a command Claude Code does not know reads files): metadata,
|
|
3275
|
+
// hashes, and what is piped to them.
|
|
3276
|
+
"Bash(tr *)",
|
|
3277
|
+
"Bash(stat *)",
|
|
3278
|
+
"Bash(du *)",
|
|
3279
|
+
"Bash(df *)",
|
|
3280
|
+
"Bash(ps *)",
|
|
3281
|
+
"Bash(basename *)",
|
|
3282
|
+
"Bash(dirname *)",
|
|
3283
|
+
"Bash(realpath *)",
|
|
3284
|
+
"Bash(readlink *)",
|
|
3285
|
+
"Bash(md5sum *)",
|
|
3286
|
+
"Bash(sha256sum *)",
|
|
3287
|
+
"Bash(shasum *)",
|
|
3288
|
+
"Bash(seq *)",
|
|
3289
|
+
"Bash(printf *)",
|
|
3290
|
+
"Bash(date *)",
|
|
3291
|
+
"Bash(uname *)",
|
|
3292
|
+
"Bash(whoami)",
|
|
3293
|
+
"Bash(id)",
|
|
3294
|
+
"Bash(type *)",
|
|
1378
3295
|
"Bash(command -v *)",
|
|
1379
3296
|
"Bash(test *)",
|
|
1380
3297
|
"Bash(true)",
|
|
@@ -1424,7 +3341,7 @@ var DEFAULT_DISALLOWED_TOOLS = [
|
|
|
1424
3341
|
];
|
|
1425
3342
|
function configDirRules(configFile, platform = process.platform) {
|
|
1426
3343
|
if (platform === "win32") return [];
|
|
1427
|
-
const dir =
|
|
3344
|
+
const dir = dirname3(configFile);
|
|
1428
3345
|
if (!dir.startsWith("/")) return [];
|
|
1429
3346
|
return [`Read(/${dir}/**)`, `Edit(/${dir}/**)`];
|
|
1430
3347
|
}
|
|
@@ -1434,7 +3351,7 @@ var DEFAULT_IDLE_TIMEOUT_MINUTES = 15;
|
|
|
1434
3351
|
async function readConfigFile(file) {
|
|
1435
3352
|
let raw;
|
|
1436
3353
|
try {
|
|
1437
|
-
raw = await
|
|
3354
|
+
raw = await readFile3(file, "utf8");
|
|
1438
3355
|
} catch (err) {
|
|
1439
3356
|
if (err.code === "ENOENT") return null;
|
|
1440
3357
|
throw err;
|
|
@@ -1448,7 +3365,7 @@ async function readConfigFile(file) {
|
|
|
1448
3365
|
}
|
|
1449
3366
|
}
|
|
1450
3367
|
async function writeConfigFile(file, config) {
|
|
1451
|
-
await mkdir3(
|
|
3368
|
+
await mkdir3(dirname3(file), { recursive: true, mode: 448 });
|
|
1452
3369
|
await writeFile2(file, JSON.stringify(config, null, 2) + "\n", { mode: 384 });
|
|
1453
3370
|
await chmod(file, 384).catch(() => void 0);
|
|
1454
3371
|
}
|
|
@@ -1467,7 +3384,7 @@ function normalizeServerUrl(url) {
|
|
|
1467
3384
|
}
|
|
1468
3385
|
var MAX_SESSIONS_LIMIT = 64;
|
|
1469
3386
|
function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPaths(env)) {
|
|
1470
|
-
const mode = file?.permissionMode ?? "
|
|
3387
|
+
const mode = file?.permissionMode ?? "auto";
|
|
1471
3388
|
if (!PERMISSION_MODES.includes(mode)) {
|
|
1472
3389
|
throw new Error(
|
|
1473
3390
|
`permissionMode "${mode}" in ${paths.configFile} is not one of ${PERMISSION_MODES.join(", ")}.`
|
|
@@ -1485,6 +3402,24 @@ function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPa
|
|
|
1485
3402
|
`inheritClaudeCodePermissions in ${paths.configFile} must be true or false (got ${JSON.stringify(inherit)}).`
|
|
1486
3403
|
);
|
|
1487
3404
|
}
|
|
3405
|
+
const codexSandbox = file?.codexSandbox ?? "workspace-write";
|
|
3406
|
+
if (codexSandbox !== "workspace-write" && codexSandbox !== "danger-full-access") {
|
|
3407
|
+
throw new Error(
|
|
3408
|
+
`codexSandbox "${String(codexSandbox)}" in ${paths.configFile} is not one of workspace-write, danger-full-access.`
|
|
3409
|
+
);
|
|
3410
|
+
}
|
|
3411
|
+
const codexNetwork = file?.codexNetworkAccess;
|
|
3412
|
+
if (codexNetwork !== void 0 && typeof codexNetwork !== "boolean") {
|
|
3413
|
+
throw new Error(
|
|
3414
|
+
`codexNetworkAccess in ${paths.configFile} must be true or false (got ${JSON.stringify(codexNetwork)}).`
|
|
3415
|
+
);
|
|
3416
|
+
}
|
|
3417
|
+
const cursorForce = file?.cursorForce;
|
|
3418
|
+
if (cursorForce !== void 0 && typeof cursorForce !== "boolean") {
|
|
3419
|
+
throw new Error(
|
|
3420
|
+
`cursorForce in ${paths.configFile} must be true or false (got ${JSON.stringify(cursorForce)}).`
|
|
3421
|
+
);
|
|
3422
|
+
}
|
|
1488
3423
|
const allowed = [
|
|
1489
3424
|
...file?.allowedTools ?? DEFAULT_ALLOWED_TOOLS,
|
|
1490
3425
|
...file?.extraAllowedTools ?? []
|
|
@@ -1502,8 +3437,8 @@ function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPa
|
|
|
1502
3437
|
token: env.DT_RUNNER_TOKEN || file?.token || null,
|
|
1503
3438
|
name: file?.name ?? null,
|
|
1504
3439
|
maxSessions,
|
|
1505
|
-
reposDir: overrides.reposDir ?? file?.reposDir ??
|
|
1506
|
-
worktreesDir: file?.worktreesDir ??
|
|
3440
|
+
reposDir: overrides.reposDir ?? file?.reposDir ?? join7(paths.dataDir, "repos"),
|
|
3441
|
+
worktreesDir: file?.worktreesDir ?? join7(paths.dataDir, "worktrees"),
|
|
1507
3442
|
permissionMode: mode,
|
|
1508
3443
|
allowedTools: [...new Set(allowed)],
|
|
1509
3444
|
disallowedTools: [...new Set(disallowed)],
|
|
@@ -1512,13 +3447,16 @@ function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPa
|
|
|
1512
3447
|
inheritClaudeCodePermissions: inherit !== false,
|
|
1513
3448
|
gitProtocol: file?.gitProtocol === "ssh" ? "ssh" : "https",
|
|
1514
3449
|
idleTimeoutMs: (file?.idleTimeoutMinutes ?? DEFAULT_IDLE_TIMEOUT_MINUTES) * 6e4,
|
|
3450
|
+
codexSandbox,
|
|
3451
|
+
codexNetworkAccess: codexNetwork === true,
|
|
3452
|
+
cursorForce: cursorForce === true,
|
|
1515
3453
|
stateDir: paths.stateDir,
|
|
1516
3454
|
configFile: paths.configFile
|
|
1517
3455
|
};
|
|
1518
3456
|
}
|
|
1519
3457
|
|
|
1520
3458
|
// src/daemon.ts
|
|
1521
|
-
import { join as
|
|
3459
|
+
import { join as join12 } from "node:path";
|
|
1522
3460
|
|
|
1523
3461
|
// src/backoff.ts
|
|
1524
3462
|
function backoffDelay(attempt, baseMs = 1e3, maxMs = 6e4) {
|
|
@@ -1541,7 +3479,7 @@ function sleep(ms, signal) {
|
|
|
1541
3479
|
// src/completion.ts
|
|
1542
3480
|
import { mkdtemp as mkdtemp2, rm as rm4 } from "node:fs/promises";
|
|
1543
3481
|
import { tmpdir as tmpdir2 } from "node:os";
|
|
1544
|
-
import { join as
|
|
3482
|
+
import { join as join8 } from "node:path";
|
|
1545
3483
|
var COMPLETION_DENIED_TOOLS = [
|
|
1546
3484
|
"Read",
|
|
1547
3485
|
"Glob",
|
|
@@ -1589,7 +3527,7 @@ async function answerCompletion(req, deps) {
|
|
|
1589
3527
|
try {
|
|
1590
3528
|
const { bin, features } = await deps.claude();
|
|
1591
3529
|
const args = completionArgs(req, features);
|
|
1592
|
-
cwd = await mkdtemp2(
|
|
3530
|
+
cwd = await mkdtemp2(join8(tmpdir2(), "dt-runner-completion-"));
|
|
1593
3531
|
const run = deps.run ?? ((b, a, o) => exec(b, a, { ...o, ownTree: true }));
|
|
1594
3532
|
const input = req.systemPrompt ? `<instructions>
|
|
1595
3533
|
${req.systemPrompt}
|
|
@@ -1642,20 +3580,20 @@ function reportableSessionIds(ids, onDropped = () => void 0) {
|
|
|
1642
3580
|
|
|
1643
3581
|
// src/session-manager.ts
|
|
1644
3582
|
import { mkdir as mkdir6, rm as rm6, writeFile as writeFile4 } from "node:fs/promises";
|
|
1645
|
-
import { join as
|
|
3583
|
+
import { join as join11 } from "node:path";
|
|
1646
3584
|
|
|
1647
3585
|
// src/fsutil.ts
|
|
1648
|
-
import { mkdir as mkdir4, readFile as
|
|
1649
|
-
import { dirname as
|
|
3586
|
+
import { mkdir as mkdir4, readFile as readFile4, rename as rename2, writeFile as writeFile3 } from "node:fs/promises";
|
|
3587
|
+
import { dirname as dirname4 } from "node:path";
|
|
1650
3588
|
async function writeJsonAtomic(file, value) {
|
|
1651
|
-
await mkdir4(
|
|
3589
|
+
await mkdir4(dirname4(file), { recursive: true });
|
|
1652
3590
|
const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
1653
3591
|
await writeFile3(tmp, JSON.stringify(value), { mode: 384 });
|
|
1654
3592
|
await rename2(tmp, file);
|
|
1655
3593
|
}
|
|
1656
3594
|
async function readJson(file) {
|
|
1657
3595
|
try {
|
|
1658
|
-
return JSON.parse(await
|
|
3596
|
+
return JSON.parse(await readFile4(file, "utf8"));
|
|
1659
3597
|
} catch (err) {
|
|
1660
3598
|
if (err.code === "ENOENT") return null;
|
|
1661
3599
|
if (err instanceof SyntaxError) return null;
|
|
@@ -1851,258 +3789,58 @@ var SessionOutbox = class _SessionOutbox {
|
|
|
1851
3789
|
}
|
|
1852
3790
|
} else {
|
|
1853
3791
|
this.opts.logger.debug("posting session events failed; will retry", {
|
|
1854
|
-
session: this.opts.sessionId,
|
|
1855
|
-
error: err.message
|
|
1856
|
-
});
|
|
1857
|
-
}
|
|
1858
|
-
await sleep(
|
|
1859
|
-
backoffDelay(attempt++, this.opts.retryBaseMs ?? 1e3),
|
|
1860
|
-
this.stopController.signal
|
|
1861
|
-
);
|
|
1862
|
-
} finally {
|
|
1863
|
-
this.inFlightUpTo = 0;
|
|
1864
|
-
}
|
|
1865
|
-
}
|
|
1866
|
-
} finally {
|
|
1867
|
-
this.pumping = false;
|
|
1868
|
-
}
|
|
1869
|
-
if (!this.pending.length || this.closed) this.notifyIdle();
|
|
1870
|
-
else if (!this.stopped) this.schedulePump();
|
|
1871
|
-
}
|
|
1872
|
-
markClosed(reason) {
|
|
1873
|
-
this.opts.logger.info(`session ${this.opts.sessionId}: ${reason}`);
|
|
1874
|
-
this.discard();
|
|
1875
|
-
this.opts.onClosed?.();
|
|
1876
|
-
}
|
|
1877
|
-
notifyIdle() {
|
|
1878
|
-
const waiters = this.idleWaiters;
|
|
1879
|
-
this.idleWaiters = [];
|
|
1880
|
-
for (const w of waiters) w();
|
|
1881
|
-
}
|
|
1882
|
-
};
|
|
1883
|
-
function takeBatch(pending) {
|
|
1884
|
-
const budget = RUNNER_EVENTS_MAX_BODY_BYTES / 2;
|
|
1885
|
-
let bytes = 0;
|
|
1886
|
-
let n = 0;
|
|
1887
|
-
while (n < pending.length && n < RUNNER_EVENTS_MAX_BATCH) {
|
|
1888
|
-
const size = Buffer.byteLength(JSON.stringify(pending[n]));
|
|
1889
|
-
if (n > 0 && bytes + size > budget) break;
|
|
1890
|
-
bytes += size;
|
|
1891
|
-
n++;
|
|
1892
|
-
}
|
|
1893
|
-
return pending.slice(0, n);
|
|
1894
|
-
}
|
|
1895
|
-
|
|
1896
|
-
// src/session.ts
|
|
1897
|
-
import { spawn as spawn3 } from "node:child_process";
|
|
1898
|
-
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
1899
|
-
import { basename, dirname as dirname6 } from "node:path";
|
|
1900
|
-
import { createInterface } from "node:readline";
|
|
1901
|
-
|
|
1902
|
-
// src/permissions.ts
|
|
1903
|
-
import { randomUUID } from "node:crypto";
|
|
1904
|
-
function parseCanUseTool(line) {
|
|
1905
|
-
if (line?.type !== "control_request") return null;
|
|
1906
|
-
const req = line.request;
|
|
1907
|
-
if (!req || req.subtype !== "can_use_tool") return null;
|
|
1908
|
-
if (typeof line.request_id !== "string" || !line.request_id) return null;
|
|
1909
|
-
const toolName = typeof req.tool_name === "string" && req.tool_name ? req.tool_name : "tool";
|
|
1910
|
-
return { controlRequestId: line.request_id, toolName, input: req.input ?? {} };
|
|
1911
|
-
}
|
|
1912
|
-
function parseControlCancel(line) {
|
|
1913
|
-
if (line?.type !== "control_cancel_request") return null;
|
|
1914
|
-
return typeof line.request_id === "string" ? line.request_id : null;
|
|
1915
|
-
}
|
|
1916
|
-
function summarizeToolInput(toolName, input) {
|
|
1917
|
-
const i = input && typeof input === "object" ? input : {};
|
|
1918
|
-
const s = (v) => typeof v === "string" && v.trim() ? v : null;
|
|
1919
|
-
let summary = null;
|
|
1920
|
-
switch (toolName) {
|
|
1921
|
-
case "Bash":
|
|
1922
|
-
summary = s(i.command);
|
|
1923
|
-
break;
|
|
1924
|
-
case "WebFetch":
|
|
1925
|
-
summary = s(i.url);
|
|
1926
|
-
break;
|
|
1927
|
-
case "WebSearch":
|
|
1928
|
-
summary = s(i.query);
|
|
1929
|
-
break;
|
|
1930
|
-
case "Read":
|
|
1931
|
-
case "Edit":
|
|
1932
|
-
case "MultiEdit":
|
|
1933
|
-
case "Write":
|
|
1934
|
-
summary = s(i.file_path);
|
|
1935
|
-
break;
|
|
1936
|
-
case "NotebookEdit":
|
|
1937
|
-
summary = s(i.notebook_path);
|
|
1938
|
-
break;
|
|
1939
|
-
case "Glob":
|
|
1940
|
-
case "Grep":
|
|
1941
|
-
summary = s(i.pattern) ? `${i.pattern}${s(i.path) ? ` in ${i.path}` : ""}` : null;
|
|
1942
|
-
break;
|
|
1943
|
-
}
|
|
1944
|
-
if (summary === null) {
|
|
1945
|
-
try {
|
|
1946
|
-
summary = JSON.stringify(input) ?? "";
|
|
1947
|
-
} catch {
|
|
1948
|
-
summary = "";
|
|
1949
|
-
}
|
|
1950
|
-
}
|
|
1951
|
-
return cut(summary, AGENT_PERMISSION_INPUT_SUMMARY_MAX_LENGTH);
|
|
1952
|
-
}
|
|
1953
|
-
function cut(text, max) {
|
|
1954
|
-
return text.length > max ? `${text.slice(0, max - 1)}\u2026` : text;
|
|
1955
|
-
}
|
|
1956
|
-
var PERMISSION_EXPIRED_TURN_ENDED = "The turn ended before anyone answered.";
|
|
1957
|
-
var PERMISSION_EXPIRED_INTERRUPTED = "The turn was interrupted before anyone answered.";
|
|
1958
|
-
var PERMISSION_EXPIRED_STOPPED = "Claude Code stopped before anyone answered.";
|
|
1959
|
-
var PERMISSION_EXPIRED_TIMEOUT = `Nobody answered within ${Math.round(
|
|
1960
|
-
RUNNER_PERMISSION_REQUEST_TIMEOUT_MS / 6e4
|
|
1961
|
-
)} minutes.`;
|
|
1962
|
-
var PERMISSION_EXPIRED_CANCELLED = "Claude Code stopped waiting for an answer.";
|
|
1963
|
-
var PERMISSION_EXPIRED_UNKNOWN = "The runner no longer has this request (it may have restarted), so the answer could not be applied.";
|
|
1964
|
-
var DENIED_MESSAGE = "The person denied permission for this tool call in Discovery Tree.";
|
|
1965
|
-
var SETTLED_KEPT = 200;
|
|
1966
|
-
var PermissionRelay = class {
|
|
1967
|
-
constructor(deps) {
|
|
1968
|
-
this.deps = deps;
|
|
1969
|
-
}
|
|
1970
|
-
pending = /* @__PURE__ */ new Map();
|
|
1971
|
-
byControlId = /* @__PURE__ */ new Map();
|
|
1972
|
-
settled = /* @__PURE__ */ new Map();
|
|
1973
|
-
get pendingCount() {
|
|
1974
|
-
return this.pending.size;
|
|
1975
|
-
}
|
|
1976
|
-
/** Claude Code asks; returns whether it was allowed at once or relayed. */
|
|
1977
|
-
request(req) {
|
|
1978
|
-
if (this.deps.alwaysAllowed().includes(req.toolName) || this.deps.grantedByRule?.(req.toolName, req.input)) {
|
|
1979
|
-
this.deps.respond(req.controlRequestId, { behavior: "allow", updatedInput: req.input });
|
|
1980
|
-
return "auto_allowed";
|
|
1981
|
-
}
|
|
1982
|
-
const id = (this.deps.newId ?? randomUUID)();
|
|
1983
|
-
const requestedAt = (this.deps.now?.() ?? /* @__PURE__ */ new Date()).toISOString();
|
|
1984
|
-
const timer = setTimeout(
|
|
1985
|
-
() => this.expire(id, PERMISSION_EXPIRED_TIMEOUT, true),
|
|
1986
|
-
this.deps.timeoutMs ?? RUNNER_PERMISSION_REQUEST_TIMEOUT_MS
|
|
1987
|
-
);
|
|
1988
|
-
timer.unref?.();
|
|
1989
|
-
const pending = {
|
|
1990
|
-
id,
|
|
1991
|
-
controlRequestId: req.controlRequestId,
|
|
1992
|
-
toolName: req.toolName,
|
|
1993
|
-
input: req.input,
|
|
1994
|
-
inputSummary: summarizeToolInput(req.toolName, req.input),
|
|
1995
|
-
requestedAt,
|
|
1996
|
-
timer
|
|
1997
|
-
};
|
|
1998
|
-
this.pending.set(id, pending);
|
|
1999
|
-
this.byControlId.set(req.controlRequestId, id);
|
|
2000
|
-
const suggestedRule = this.deps.suggestRule?.(req.toolName, req.input) ?? null;
|
|
2001
|
-
this.deps.emit({
|
|
2002
|
-
type: "permission_request",
|
|
2003
|
-
request: {
|
|
2004
|
-
id,
|
|
2005
|
-
toolName: pending.toolName,
|
|
2006
|
-
inputSummary: pending.inputSummary,
|
|
2007
|
-
...suggestedRule ? { suggestedRule } : {},
|
|
2008
|
-
requestedAt,
|
|
2009
|
-
status: "pending"
|
|
2010
|
-
}
|
|
2011
|
-
});
|
|
2012
|
-
return "relayed";
|
|
2013
|
-
}
|
|
2014
|
-
/** A person's decision, from the server. */
|
|
2015
|
-
decide(requestId, decision) {
|
|
2016
|
-
const pending = this.pending.get(requestId);
|
|
2017
|
-
if (!pending) {
|
|
2018
|
-
const settled = this.settled.get(requestId);
|
|
2019
|
-
if (settled === "decided") return "already_applied";
|
|
2020
|
-
if (settled === void 0) {
|
|
2021
|
-
this.settle(requestId, "expired");
|
|
2022
|
-
this.deps.emit({
|
|
2023
|
-
type: "permission_request",
|
|
2024
|
-
request: {
|
|
2025
|
-
id: requestId,
|
|
2026
|
-
toolName: "tool",
|
|
2027
|
-
inputSummary: "",
|
|
2028
|
-
requestedAt: (this.deps.now?.() ?? /* @__PURE__ */ new Date()).toISOString(),
|
|
2029
|
-
status: "expired",
|
|
2030
|
-
expiredReason: PERMISSION_EXPIRED_UNKNOWN
|
|
2031
|
-
}
|
|
2032
|
-
});
|
|
2033
|
-
}
|
|
2034
|
-
return "not_pending";
|
|
2035
|
-
}
|
|
2036
|
-
this.forget(pending);
|
|
2037
|
-
this.settle(requestId, "decided");
|
|
2038
|
-
if (decision.behavior === "allow") {
|
|
2039
|
-
if (decision.alwaysAllowTool && !this.deps.alwaysAllowed().includes(pending.toolName)) {
|
|
2040
|
-
this.deps.rememberAlwaysAllowed(pending.toolName);
|
|
3792
|
+
session: this.opts.sessionId,
|
|
3793
|
+
error: err.message
|
|
3794
|
+
});
|
|
3795
|
+
}
|
|
3796
|
+
await sleep(
|
|
3797
|
+
backoffDelay(attempt++, this.opts.retryBaseMs ?? 1e3),
|
|
3798
|
+
this.stopController.signal
|
|
3799
|
+
);
|
|
3800
|
+
} finally {
|
|
3801
|
+
this.inFlightUpTo = 0;
|
|
3802
|
+
}
|
|
2041
3803
|
}
|
|
2042
|
-
|
|
2043
|
-
|
|
2044
|
-
this.deps.respond(pending.controlRequestId, {
|
|
2045
|
-
behavior: "allow",
|
|
2046
|
-
updatedInput: pending.input
|
|
2047
|
-
});
|
|
2048
|
-
} else {
|
|
2049
|
-
const message = decision.message?.trim();
|
|
2050
|
-
this.deps.respond(pending.controlRequestId, {
|
|
2051
|
-
behavior: "deny",
|
|
2052
|
-
message: message ? `${DENIED_MESSAGE} Their message: ${cut(message, AGENT_PERMISSION_MESSAGE_MAX_LENGTH)}` : DENIED_MESSAGE
|
|
2053
|
-
});
|
|
2054
|
-
}
|
|
2055
|
-
return "applied";
|
|
2056
|
-
}
|
|
2057
|
-
/** Claude Code withdrew a request (it stopped waiting): expired, nothing to answer. */
|
|
2058
|
-
cancel(controlRequestId) {
|
|
2059
|
-
const id = this.byControlId.get(controlRequestId);
|
|
2060
|
-
if (id) this.expire(id, PERMISSION_EXPIRED_CANCELLED, false);
|
|
2061
|
-
}
|
|
2062
|
-
/** Expire everything still waiting, answering Claude Code with a denial. */
|
|
2063
|
-
expireAll(reason) {
|
|
2064
|
-
for (const id of [...this.pending.keys()]) this.expire(id, reason, true);
|
|
2065
|
-
}
|
|
2066
|
-
expire(id, reason, answerClaude) {
|
|
2067
|
-
const pending = this.pending.get(id);
|
|
2068
|
-
if (!pending) return;
|
|
2069
|
-
this.forget(pending);
|
|
2070
|
-
this.settle(id, "expired");
|
|
2071
|
-
if (answerClaude) {
|
|
2072
|
-
this.deps.respond(pending.controlRequestId, {
|
|
2073
|
-
behavior: "deny",
|
|
2074
|
-
message: `Permission for this tool call was not granted: ${reason}`
|
|
2075
|
-
});
|
|
3804
|
+
} finally {
|
|
3805
|
+
this.pumping = false;
|
|
2076
3806
|
}
|
|
2077
|
-
this.
|
|
2078
|
-
|
|
2079
|
-
request: {
|
|
2080
|
-
id,
|
|
2081
|
-
toolName: pending.toolName,
|
|
2082
|
-
inputSummary: pending.inputSummary,
|
|
2083
|
-
requestedAt: pending.requestedAt,
|
|
2084
|
-
status: "expired",
|
|
2085
|
-
expiredReason: reason
|
|
2086
|
-
}
|
|
2087
|
-
});
|
|
3807
|
+
if (!this.pending.length || this.closed) this.notifyIdle();
|
|
3808
|
+
else if (!this.stopped) this.schedulePump();
|
|
2088
3809
|
}
|
|
2089
|
-
|
|
2090
|
-
|
|
2091
|
-
this.
|
|
2092
|
-
this.
|
|
3810
|
+
markClosed(reason) {
|
|
3811
|
+
this.opts.logger.info(`session ${this.opts.sessionId}: ${reason}`);
|
|
3812
|
+
this.discard();
|
|
3813
|
+
this.opts.onClosed?.();
|
|
2093
3814
|
}
|
|
2094
|
-
|
|
2095
|
-
this.
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
}
|
|
3815
|
+
notifyIdle() {
|
|
3816
|
+
const waiters = this.idleWaiters;
|
|
3817
|
+
this.idleWaiters = [];
|
|
3818
|
+
for (const w of waiters) w();
|
|
2099
3819
|
}
|
|
2100
3820
|
};
|
|
3821
|
+
function takeBatch(pending) {
|
|
3822
|
+
const budget = RUNNER_EVENTS_MAX_BODY_BYTES / 2;
|
|
3823
|
+
let bytes = 0;
|
|
3824
|
+
let n = 0;
|
|
3825
|
+
while (n < pending.length && n < RUNNER_EVENTS_MAX_BATCH) {
|
|
3826
|
+
const size = Buffer.byteLength(JSON.stringify(pending[n]));
|
|
3827
|
+
if (n > 0 && bytes + size > budget) break;
|
|
3828
|
+
bytes += size;
|
|
3829
|
+
n++;
|
|
3830
|
+
}
|
|
3831
|
+
return pending.slice(0, n);
|
|
3832
|
+
}
|
|
3833
|
+
|
|
3834
|
+
// src/session.ts
|
|
3835
|
+
import { spawn as spawn4 } from "node:child_process";
|
|
3836
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
3837
|
+
import { basename, dirname as dirname6 } from "node:path";
|
|
3838
|
+
import { createInterface as createInterface2 } from "node:readline";
|
|
2101
3839
|
|
|
2102
3840
|
// src/tool-grants.ts
|
|
2103
|
-
import { dirname as
|
|
3841
|
+
import { dirname as dirname5, join as join9, posix } from "node:path";
|
|
2104
3842
|
var isGrantableDenial = isGrantableToolDenial;
|
|
2105
|
-
var
|
|
3843
|
+
var FILE_TOOLS2 = /* @__PURE__ */ new Set(["Read", "Edit", "MultiEdit", "Write", "NotebookEdit"]);
|
|
2106
3844
|
var EDIT_TOOLS = /* @__PURE__ */ new Set(["Edit", "MultiEdit", "Write", "NotebookEdit"]);
|
|
2107
3845
|
function suggestRules(toolName, input, allowedTools = []) {
|
|
2108
3846
|
const i = input && typeof input === "object" ? input : {};
|
|
@@ -2114,7 +3852,7 @@ function suggestRules(toolName, input, allowedTools = []) {
|
|
|
2114
3852
|
} else if (toolName === "WebFetch") {
|
|
2115
3853
|
const host = hostOf(str(i.url));
|
|
2116
3854
|
if (host) out = same(`WebFetch(domain:${host})`);
|
|
2117
|
-
} else if (
|
|
3855
|
+
} else if (FILE_TOOLS2.has(toolName)) {
|
|
2118
3856
|
const file = str(i.file_path) ?? str(i.notebook_path);
|
|
2119
3857
|
const ruleTool = EDIT_TOOLS.has(toolName) ? "Edit" : "Read";
|
|
2120
3858
|
if (file) {
|
|
@@ -2207,7 +3945,7 @@ function ruleAllows(rule, toolName, input) {
|
|
|
2207
3945
|
if (toolName === "WebFetch" && parsed.spec.startsWith("domain:")) {
|
|
2208
3946
|
return hostOf(typeof i.url === "string" ? i.url : null) === parsed.spec.slice(7).toLowerCase();
|
|
2209
3947
|
}
|
|
2210
|
-
if (
|
|
3948
|
+
if (FILE_TOOLS2.has(toolName)) {
|
|
2211
3949
|
const file = typeof i.file_path === "string" ? i.file_path : typeof i.notebook_path === "string" ? i.notebook_path : "";
|
|
2212
3950
|
return filePatternMatches(parsed.spec, file);
|
|
2213
3951
|
}
|
|
@@ -2242,7 +3980,7 @@ function grantsCover(granted, base, toolName, input) {
|
|
|
2242
3980
|
function askedFor(rules, toolName, input) {
|
|
2243
3981
|
if (rules.length === 0) return false;
|
|
2244
3982
|
if (rules.some((rule) => rule.trim() === toolName)) return true;
|
|
2245
|
-
if (
|
|
3983
|
+
if (FILE_TOOLS2.has(toolName)) {
|
|
2246
3984
|
const family = EDIT_TOOLS.has(toolName) ? "Edit" : toolName;
|
|
2247
3985
|
const relative = rules.some((rule) => {
|
|
2248
3986
|
const parsed = parseRule(rule);
|
|
@@ -2298,7 +4036,7 @@ function filePatternMatches(spec, file) {
|
|
|
2298
4036
|
let pattern = spec.trim();
|
|
2299
4037
|
if (pattern.startsWith("~/")) {
|
|
2300
4038
|
if (!home) return false;
|
|
2301
|
-
pattern = rulePath(
|
|
4039
|
+
pattern = rulePath(join9(home, pattern.slice(2)).replace(/\\/g, "/"));
|
|
2302
4040
|
}
|
|
2303
4041
|
if (!pattern.startsWith("//")) return false;
|
|
2304
4042
|
const path = rulePath(file);
|
|
@@ -2319,7 +4057,7 @@ function shellPatternMatches(spec, command) {
|
|
|
2319
4057
|
return new RegExp(`^${re}${optionalTail ? "(?: .*)?" : ""}$`, "s").test(command);
|
|
2320
4058
|
}
|
|
2321
4059
|
function toolGrantsFile(configFile) {
|
|
2322
|
-
return
|
|
4060
|
+
return join9(dirname5(configFile), "tool-grants.json");
|
|
2323
4061
|
}
|
|
2324
4062
|
var ToolGrantStore = class {
|
|
2325
4063
|
constructor(file) {
|
|
@@ -2381,211 +4119,19 @@ var ToolGrantStore = class {
|
|
|
2381
4119
|
}
|
|
2382
4120
|
change(fn) {
|
|
2383
4121
|
const run = this.chain.then(async () => {
|
|
2384
|
-
const
|
|
2385
|
-
const next = await fn(
|
|
2386
|
-
if (next ===
|
|
4122
|
+
const current2 = await this.list();
|
|
4123
|
+
const next = await fn(current2);
|
|
4124
|
+
if (next === current2) return;
|
|
2387
4125
|
await writeJsonAtomic(this.file, { version: 1, grants: next });
|
|
2388
4126
|
this.cache = next;
|
|
2389
4127
|
});
|
|
2390
4128
|
this.chain = run.catch(() => void 0);
|
|
2391
|
-
return run;
|
|
2392
|
-
}
|
|
2393
|
-
};
|
|
2394
|
-
function isUsableGrant(g) {
|
|
2395
|
-
const x = g;
|
|
2396
|
-
return !!x && typeof x.id === "string" && typeof x.repository === "string" && typeof x.rule === "string" && toolGrantRuleProblem(x.rule) === null;
|
|
2397
|
-
}
|
|
2398
|
-
|
|
2399
|
-
// src/claude-code-rules.ts
|
|
2400
|
-
import { readFile as readFile4, stat as stat3 } from "node:fs/promises";
|
|
2401
|
-
import { homedir as homedir2 } from "node:os";
|
|
2402
|
-
import { dirname as dirname5, isAbsolute as isAbsolute3, join as join8, resolve, sep } from "node:path";
|
|
2403
|
-
var EMPTY = { allow: [], deny: [], ask: [], sources: [] };
|
|
2404
|
-
var RULE_SHAPE2 = /^(?:mcp__[A-Za-z0-9_-]+__\*|[A-Za-z][A-Za-z0-9_.-]*(?:\([\s\S]*\))?)$/;
|
|
2405
|
-
var FILE_TOOLS2 = /* @__PURE__ */ new Set([
|
|
2406
|
-
"Read",
|
|
2407
|
-
"Edit",
|
|
2408
|
-
"Write",
|
|
2409
|
-
"MultiEdit",
|
|
2410
|
-
"NotebookEdit",
|
|
2411
|
-
"Glob",
|
|
2412
|
-
"Grep",
|
|
2413
|
-
"LS"
|
|
2414
|
-
]);
|
|
2415
|
-
function usableRule(raw, kind, committed) {
|
|
2416
|
-
if (typeof raw !== "string") return null;
|
|
2417
|
-
const rule = raw.trim();
|
|
2418
|
-
if (!rule || rule.length > TOOL_GRANT_RULE_MAX_LENGTH) return null;
|
|
2419
|
-
if (/[\u0000-\u001f\u007f]/.test(rule) || !RULE_SHAPE2.test(rule)) return null;
|
|
2420
|
-
const tool = /^([A-Za-z][A-Za-z0-9_.-]*)/.exec(rule)?.[1] ?? "";
|
|
2421
|
-
if (kind === "allow" && FILE_TOOLS2.has(tool)) return null;
|
|
2422
|
-
if (kind === "allow" && committed && toolGrantRuleProblem(rule) !== null) return null;
|
|
2423
|
-
return rule;
|
|
2424
|
-
}
|
|
2425
|
-
function remoteRepositoryKey(url) {
|
|
2426
|
-
const u = url.trim();
|
|
2427
|
-
const ssh = /^(?:ssh:\/\/)?git@github\.com[:/]([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/i.exec(u);
|
|
2428
|
-
if (ssh) return toolGrantRepositoryKey(`https://github.com/${ssh[1]}/${ssh[2]}`);
|
|
2429
|
-
const https = /^(?:https?|git):\/\/(?:[^@/]+@)?github\.com\/([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/i.exec(u);
|
|
2430
|
-
if (https) return toolGrantRepositoryKey(`https://github.com/${https[1]}/${https[2]}`);
|
|
2431
|
-
return null;
|
|
2432
|
-
}
|
|
2433
|
-
async function readText(file) {
|
|
2434
|
-
try {
|
|
2435
|
-
return await readFile4(file, "utf8");
|
|
2436
|
-
} catch {
|
|
2437
|
-
return null;
|
|
2438
|
-
}
|
|
2439
|
-
}
|
|
2440
|
-
async function readJsonFile(file) {
|
|
2441
|
-
const text = await readText(file);
|
|
2442
|
-
if (text === null) return null;
|
|
2443
|
-
try {
|
|
2444
|
-
return JSON.parse(text);
|
|
2445
|
-
} catch {
|
|
2446
|
-
return null;
|
|
2447
|
-
}
|
|
2448
|
-
}
|
|
2449
|
-
async function isDir(path) {
|
|
2450
|
-
try {
|
|
2451
|
-
return (await stat3(path)).isDirectory();
|
|
2452
|
-
} catch {
|
|
2453
|
-
return false;
|
|
2454
|
-
}
|
|
2455
|
-
}
|
|
2456
|
-
async function gitConfigOf(folder) {
|
|
2457
|
-
let dir = folder;
|
|
2458
|
-
for (let i = 0; i < 6; i++) {
|
|
2459
|
-
const dotGit = join8(dir, ".git");
|
|
2460
|
-
if (await isDir(dotGit)) return { config: join8(dotGit, "config"), roots: [dir] };
|
|
2461
|
-
const pointer = await readText(dotGit);
|
|
2462
|
-
const gitdir = pointer && /^gitdir:\s*(.+)\s*$/m.exec(pointer)?.[1];
|
|
2463
|
-
if (gitdir) {
|
|
2464
|
-
const linked = resolve(dir, gitdir);
|
|
2465
|
-
const common = (await readText(join8(linked, "commondir")))?.trim();
|
|
2466
|
-
const commonDir = common ? resolve(linked, common) : linked;
|
|
2467
|
-
return { config: join8(commonDir, "config"), roots: [dir, dirname5(commonDir)] };
|
|
2468
|
-
}
|
|
2469
|
-
const up = dirname5(dir);
|
|
2470
|
-
if (up === dir) break;
|
|
2471
|
-
dir = up;
|
|
2472
|
-
}
|
|
2473
|
-
return null;
|
|
2474
|
-
}
|
|
2475
|
-
function remoteKeys(config) {
|
|
2476
|
-
const keys = /* @__PURE__ */ new Set();
|
|
2477
|
-
let inRemote = false;
|
|
2478
|
-
for (const line of config.split(/\r?\n/)) {
|
|
2479
|
-
const section = /^\s*\[([^\]]*)\]/.exec(line);
|
|
2480
|
-
if (section) {
|
|
2481
|
-
inRemote = /^remote\s+"/i.test(section[1].trim());
|
|
2482
|
-
continue;
|
|
2483
|
-
}
|
|
2484
|
-
if (!inRemote) continue;
|
|
2485
|
-
const url = /^\s*url\s*=\s*(.+?)\s*$/i.exec(line);
|
|
2486
|
-
const key = url ? remoteRepositoryKey(url[1]) : null;
|
|
2487
|
-
if (key) keys.add(key);
|
|
2488
|
-
}
|
|
2489
|
-
return keys;
|
|
2490
|
-
}
|
|
2491
|
-
function rulesIn(settings, kind, committed) {
|
|
2492
|
-
const perms = settings?.permissions;
|
|
2493
|
-
const list = perms?.[kind];
|
|
2494
|
-
if (!Array.isArray(list)) return [];
|
|
2495
|
-
return list.map((r) => usableRule(r, kind, committed)).filter((r) => r !== null);
|
|
2496
|
-
}
|
|
2497
|
-
var ClaudeCodeRules = class {
|
|
2498
|
-
claudeJson;
|
|
2499
|
-
exclude;
|
|
2500
|
-
cacheMs;
|
|
2501
|
-
cache = /* @__PURE__ */ new Map();
|
|
2502
|
-
constructor(opts = {}) {
|
|
2503
|
-
this.claudeJson = opts.claudeJson ?? (process.env.CLAUDE_CONFIG_DIR ? join8(process.env.CLAUDE_CONFIG_DIR, ".claude.json") : join8(homedir2(), ".claude.json"));
|
|
2504
|
-
this.exclude = (opts.exclude ?? []).map((p) => resolve(p));
|
|
2505
|
-
this.cacheMs = opts.cacheMs ?? 3e4;
|
|
2506
|
-
}
|
|
2507
|
-
/** The rules for a repository URL; none for a session without a GitHub repository. */
|
|
2508
|
-
rulesFor(repositoryUrl) {
|
|
2509
|
-
const key = toolGrantRepositoryKey(repositoryUrl);
|
|
2510
|
-
if (!key) return Promise.resolve(EMPTY);
|
|
2511
|
-
const hit = this.cache.get(key);
|
|
2512
|
-
if (hit && Date.now() - hit.at < this.cacheMs) return hit.rules;
|
|
2513
|
-
const rules = this.read(key).catch(() => EMPTY);
|
|
2514
|
-
this.cache.set(key, { at: Date.now(), rules });
|
|
2515
|
-
return rules;
|
|
2516
|
-
}
|
|
2517
|
-
excluded(folder) {
|
|
2518
|
-
const f = resolve(folder);
|
|
2519
|
-
return this.exclude.some((ex) => f === ex || f.startsWith(ex + sep));
|
|
2520
|
-
}
|
|
2521
|
-
async read(key) {
|
|
2522
|
-
const global = await readJsonFile(this.claudeJson);
|
|
2523
|
-
const projects = global?.projects;
|
|
2524
|
-
if (!projects || typeof projects !== "object") return EMPTY;
|
|
2525
|
-
const allow = /* @__PURE__ */ new Set();
|
|
2526
|
-
const deny = /* @__PURE__ */ new Set();
|
|
2527
|
-
const ask = /* @__PURE__ */ new Set();
|
|
2528
|
-
const sources = [];
|
|
2529
|
-
const checkouts = [];
|
|
2530
|
-
for (const [folder, entry] of Object.entries(projects)) {
|
|
2531
|
-
if (!entry || entry.hasTrustDialogAccepted !== true) continue;
|
|
2532
|
-
if (!isAbsolute3(folder) || this.excluded(folder)) continue;
|
|
2533
|
-
const git2 = await gitConfigOf(folder);
|
|
2534
|
-
const text = git2 ? await readText(git2.config) : null;
|
|
2535
|
-
if (!git2 || !text || !remoteKeys(text).has(key)) continue;
|
|
2536
|
-
const roots = [...new Set([folder, ...git2.roots].map((d) => resolve(d)))];
|
|
2537
|
-
const legacy = Array.isArray(entry.allowedTools) ? entry.allowedTools : [];
|
|
2538
|
-
checkouts.push({ folder, roots, legacy });
|
|
2539
|
-
}
|
|
2540
|
-
for (const { folder, roots, legacy } of checkouts) {
|
|
2541
|
-
const found = [];
|
|
2542
|
-
const denied = [];
|
|
2543
|
-
const asked = [];
|
|
2544
|
-
for (const dir of roots) {
|
|
2545
|
-
const local = await readJsonFile(join8(dir, ".claude", "settings.local.json"));
|
|
2546
|
-
const shared = await readJsonFile(join8(dir, ".claude", "settings.json"));
|
|
2547
|
-
found.push(...rulesIn(local, "allow", false), ...rulesIn(shared, "allow", true));
|
|
2548
|
-
denied.push(...rulesIn(local, "deny", false), ...rulesIn(shared, "deny", false));
|
|
2549
|
-
asked.push(...rulesIn(local, "ask", false), ...rulesIn(shared, "ask", false));
|
|
2550
|
-
}
|
|
2551
|
-
found.push(
|
|
2552
|
-
...legacy.map((r) => usableRule(r, "allow", false)).filter((r) => r !== null)
|
|
2553
|
-
);
|
|
2554
|
-
const kept = found;
|
|
2555
|
-
if (kept.length || denied.length || asked.length) sources.push(folder);
|
|
2556
|
-
for (const r of kept) allow.add(r);
|
|
2557
|
-
for (const r of denied) deny.add(r);
|
|
2558
|
-
for (const r of asked) ask.add(r);
|
|
2559
|
-
}
|
|
2560
|
-
return {
|
|
2561
|
-
allow: [...allow].filter((r) => !deny.has(r) && !ask.has(r)),
|
|
2562
|
-
deny: [...deny],
|
|
2563
|
-
ask: [...ask].filter((r) => !deny.has(r)),
|
|
2564
|
-
sources
|
|
2565
|
-
};
|
|
4129
|
+
return run;
|
|
2566
4130
|
}
|
|
2567
4131
|
};
|
|
2568
|
-
function
|
|
2569
|
-
const
|
|
2570
|
-
|
|
2571
|
-
const spec = m[2];
|
|
2572
|
-
if (spec === void 0) return { tool: m[1], head: null };
|
|
2573
|
-
return { tool: m[1], head: spec.replace(/:\*$/, " *").split("*")[0] };
|
|
2574
|
-
}
|
|
2575
|
-
function sameTool(a, b) {
|
|
2576
|
-
if (a === b) return true;
|
|
2577
|
-
const wild = (w, t) => w.endsWith("__*") && t.startsWith(w.slice(0, -1));
|
|
2578
|
-
return wild(a, b) || wild(b, a);
|
|
2579
|
-
}
|
|
2580
|
-
function overlapsAsk(allowRule, askRules) {
|
|
2581
|
-
const a = ruleHead(allowRule);
|
|
2582
|
-
if (!a) return false;
|
|
2583
|
-
return askRules.some((rule) => {
|
|
2584
|
-
const q = ruleHead(rule);
|
|
2585
|
-
if (!q || !sameTool(a.tool, q.tool)) return false;
|
|
2586
|
-
if (a.head === null || q.head === null) return true;
|
|
2587
|
-
return a.head.startsWith(q.head) || q.head.startsWith(a.head);
|
|
2588
|
-
});
|
|
4132
|
+
function isUsableGrant(g) {
|
|
4133
|
+
const x = g;
|
|
4134
|
+
return !!x && typeof x.id === "string" && typeof x.repository === "string" && typeof x.rule === "string" && toolGrantRuleProblem(x.rule) === null;
|
|
2589
4135
|
}
|
|
2590
4136
|
|
|
2591
4137
|
// src/pull-request.ts
|
|
@@ -2678,271 +4224,49 @@ function ghError(command, res) {
|
|
|
2678
4224
|
|
|
2679
4225
|
// src/session-store.ts
|
|
2680
4226
|
import { mkdir as mkdir5, readdir as readdir2, rm as rm5 } from "node:fs/promises";
|
|
2681
|
-
import { join as
|
|
2682
|
-
var HANDLED_COMMAND_IDS_KEPT = 100;
|
|
2683
|
-
var SessionStore = class {
|
|
2684
|
-
constructor(stateDir) {
|
|
2685
|
-
this.stateDir = stateDir;
|
|
2686
|
-
}
|
|
2687
|
-
dir(sessionId) {
|
|
2688
|
-
return
|
|
2689
|
-
}
|
|
2690
|
-
outboxFile(sessionId) {
|
|
2691
|
-
return
|
|
2692
|
-
}
|
|
2693
|
-
async save(record) {
|
|
2694
|
-
record.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
2695
|
-
await writeJsonAtomic(
|
|
2696
|
-
}
|
|
2697
|
-
async list() {
|
|
2698
|
-
const root =
|
|
2699
|
-
await mkdir5(root, { recursive: true });
|
|
2700
|
-
const out = [];
|
|
2701
|
-
for (const entry of await readdir2(root, { withFileTypes: true })) {
|
|
2702
|
-
if (!entry.isDirectory()) continue;
|
|
2703
|
-
const rec = await readJson(
|
|
2704
|
-
if (rec?.sessionId === entry.name) out.push(rec);
|
|
2705
|
-
}
|
|
2706
|
-
return out;
|
|
2707
|
-
}
|
|
2708
|
-
async remove(sessionId) {
|
|
2709
|
-
await rm5(this.dir(sessionId), { recursive: true, force: true });
|
|
2710
|
-
}
|
|
2711
|
-
/** Scratch working directory for a session without a repository. */
|
|
2712
|
-
scratchDir(sessionId) {
|
|
2713
|
-
return join9(this.stateDir, "scratch", sessionId);
|
|
2714
|
-
}
|
|
2715
|
-
};
|
|
2716
|
-
function assertSafeSessionId(id) {
|
|
2717
|
-
if (!/^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/.test(id) || id.includes("..")) {
|
|
2718
|
-
throw new Error(`Session id "${id}" is not usable as a directory name.`);
|
|
2719
|
-
}
|
|
2720
|
-
}
|
|
2721
|
-
|
|
2722
|
-
// src/stream-mapper.ts
|
|
2723
|
-
function capText(text, max = RUNNER_EVENT_TEXT_MAX_LENGTH) {
|
|
2724
|
-
if (text.length <= max) return { text, truncated: false };
|
|
2725
|
-
const marker = "\n\u2026 [truncated by dt-runner]";
|
|
2726
|
-
return { text: text.slice(0, max - marker.length) + marker, truncated: true };
|
|
2727
|
-
}
|
|
2728
|
-
var ClaudeStreamMapper = class {
|
|
2729
|
-
/** Running offset of each live text block, by providerEventId. */
|
|
2730
|
-
deltaOffsets = /* @__PURE__ */ new Map();
|
|
2731
|
-
/** Stream block index → providerEventId for text blocks of the message streaming now. */
|
|
2732
|
-
streamTextKeys = /* @__PURE__ */ new Map();
|
|
2733
|
-
streamMessageId = null;
|
|
2734
|
-
streamTextCount = 0;
|
|
2735
|
-
/** Text blocks already seen in completed `assistant` lines, per message id. */
|
|
2736
|
-
completedTextCount = /* @__PURE__ */ new Map();
|
|
2737
|
-
/** Tool calls by id, for the name/input a result line does not repeat. */
|
|
2738
|
-
calls = /* @__PURE__ */ new Map();
|
|
2739
|
-
lastAssistantText = null;
|
|
2740
|
-
running = false;
|
|
2741
|
-
/** A new turn is starting (we wrote a user message); the next activity is not news. */
|
|
2742
|
-
markRunning() {
|
|
2743
|
-
this.running = true;
|
|
2744
|
-
}
|
|
2745
|
-
map(line) {
|
|
2746
|
-
const out = { events: [] };
|
|
2747
|
-
if (line.parent_tool_use_id) return out;
|
|
2748
|
-
switch (line.type) {
|
|
2749
|
-
case "system":
|
|
2750
|
-
if (line.subtype === "init" && typeof line.session_id === "string") {
|
|
2751
|
-
out.claudeSessionId = line.session_id;
|
|
2752
|
-
this.ensureRunning(out);
|
|
2753
|
-
}
|
|
2754
|
-
break;
|
|
2755
|
-
case "stream_event":
|
|
2756
|
-
this.mapStreamEvent(line, out);
|
|
2757
|
-
break;
|
|
2758
|
-
case "assistant":
|
|
2759
|
-
this.mapAssistant(line, out);
|
|
2760
|
-
break;
|
|
2761
|
-
case "user":
|
|
2762
|
-
this.mapUser(line, out);
|
|
2763
|
-
break;
|
|
2764
|
-
case "result": {
|
|
2765
|
-
const resultText = typeof line.result === "string" && line.result ? line.result : null;
|
|
2766
|
-
out.turnEnd = {
|
|
2767
|
-
text: resultText ?? this.lastAssistantText,
|
|
2768
|
-
isError: line.is_error === true || (line.subtype ?? "success") !== "success",
|
|
2769
|
-
subtype: typeof line.subtype === "string" ? line.subtype : null
|
|
2770
|
-
};
|
|
2771
|
-
const denials = Array.isArray(line.permission_denials) ? line.permission_denials.filter((d) => d && typeof d.tool_name === "string").map((d) => ({
|
|
2772
|
-
callId: typeof d.tool_use_id === "string" ? d.tool_use_id : null,
|
|
2773
|
-
name: d.tool_name,
|
|
2774
|
-
input: d.tool_input ?? {}
|
|
2775
|
-
})) : [];
|
|
2776
|
-
if (denials.length) out.turnEnd.permissionDenials = denials;
|
|
2777
|
-
this.endTurn();
|
|
2778
|
-
break;
|
|
2779
|
-
}
|
|
2780
|
-
case "control_response": {
|
|
2781
|
-
const res = line.response ?? {};
|
|
2782
|
-
if (typeof res.request_id === "string") {
|
|
2783
|
-
out.controlResponse = { requestId: res.request_id, ok: res.subtype === "success" };
|
|
2784
|
-
}
|
|
2785
|
-
break;
|
|
2786
|
-
}
|
|
2787
|
-
}
|
|
2788
|
-
return out;
|
|
2789
|
-
}
|
|
2790
|
-
ensureRunning(out) {
|
|
2791
|
-
if (!this.running) {
|
|
2792
|
-
this.running = true;
|
|
2793
|
-
out.turnStarted = true;
|
|
2794
|
-
out.events.push({ type: "status", status: "running" });
|
|
2795
|
-
}
|
|
2796
|
-
}
|
|
2797
|
-
mapStreamEvent(line, out) {
|
|
2798
|
-
const ev = line.event ?? {};
|
|
2799
|
-
switch (ev.type) {
|
|
2800
|
-
case "message_start": {
|
|
2801
|
-
this.ensureRunning(out);
|
|
2802
|
-
const id = ev.message?.id ?? line.api_message_id ?? null;
|
|
2803
|
-
this.beginStreamMessage(typeof id === "string" ? id : null);
|
|
2804
|
-
break;
|
|
2805
|
-
}
|
|
2806
|
-
case "content_block_start": {
|
|
2807
|
-
const id = this.streamMessageIdFor(line);
|
|
2808
|
-
if (ev.content_block?.type === "text" && id && typeof ev.index === "number") {
|
|
2809
|
-
const key = textKey(id, this.streamTextCount++);
|
|
2810
|
-
this.streamTextKeys.set(ev.index, key);
|
|
2811
|
-
const initial = typeof ev.content_block.text === "string" ? ev.content_block.text : "";
|
|
2812
|
-
this.deltaOffsets.set(key, 0);
|
|
2813
|
-
if (initial) this.pushDelta(out, key, initial);
|
|
2814
|
-
}
|
|
2815
|
-
break;
|
|
2816
|
-
}
|
|
2817
|
-
case "content_block_delta": {
|
|
2818
|
-
if (ev.delta?.type !== "text_delta" || typeof ev.delta.text !== "string") break;
|
|
2819
|
-
if (!ev.delta.text) break;
|
|
2820
|
-
const key = this.streamTextKeys.get(ev.index);
|
|
2821
|
-
if (key) this.pushDelta(out, key, ev.delta.text);
|
|
2822
|
-
break;
|
|
2823
|
-
}
|
|
2824
|
-
}
|
|
2825
|
-
}
|
|
2826
|
-
streamMessageIdFor(line) {
|
|
2827
|
-
const id = typeof line.api_message_id === "string" ? line.api_message_id : null;
|
|
2828
|
-
if (id && id !== this.streamMessageId) this.beginStreamMessage(id);
|
|
2829
|
-
return this.streamMessageId;
|
|
2830
|
-
}
|
|
2831
|
-
beginStreamMessage(id) {
|
|
2832
|
-
if (id === this.streamMessageId) return;
|
|
2833
|
-
this.streamMessageId = id;
|
|
2834
|
-
this.streamTextKeys.clear();
|
|
2835
|
-
this.streamTextCount = 0;
|
|
2836
|
-
}
|
|
2837
|
-
pushDelta(out, key, text) {
|
|
2838
|
-
const offset = this.deltaOffsets.get(key) ?? 0;
|
|
2839
|
-
this.deltaOffsets.set(key, offset + text.length);
|
|
2840
|
-
out.events.push({ type: "assistant_delta", providerEventId: key, text, offset });
|
|
2841
|
-
}
|
|
2842
|
-
mapAssistant(line, out) {
|
|
2843
|
-
const msg = line.message ?? {};
|
|
2844
|
-
const id = typeof msg.id === "string" ? msg.id : `msg_${line.uuid ?? Date.now()}`;
|
|
2845
|
-
const content = Array.isArray(msg.content) ? msg.content : [];
|
|
2846
|
-
this.ensureRunning(out);
|
|
2847
|
-
for (const block of content) {
|
|
2848
|
-
switch (block?.type) {
|
|
2849
|
-
case "text": {
|
|
2850
|
-
const n = this.completedTextCount.get(id) ?? 0;
|
|
2851
|
-
this.completedTextCount.set(id, n + 1);
|
|
2852
|
-
const text = typeof block.text === "string" ? block.text : "";
|
|
2853
|
-
if (!text.trim()) break;
|
|
2854
|
-
const key = textKey(id, n);
|
|
2855
|
-
this.deltaOffsets.delete(key);
|
|
2856
|
-
this.lastAssistantText = text;
|
|
2857
|
-
out.events.push({
|
|
2858
|
-
type: "assistant_message",
|
|
2859
|
-
providerEventId: key,
|
|
2860
|
-
text: capText(text).text
|
|
2861
|
-
});
|
|
2862
|
-
break;
|
|
2863
|
-
}
|
|
2864
|
-
case "thinking":
|
|
2865
|
-
case "redacted_thinking": {
|
|
2866
|
-
const text = typeof block.thinking === "string" && block.thinking.trim() ? block.thinking : null;
|
|
2867
|
-
out.events.push({
|
|
2868
|
-
type: "thinking",
|
|
2869
|
-
providerEventId: `${id}:thinking:${this.thinkingIndex(id)}`,
|
|
2870
|
-
text: text === null ? null : capText(text).text
|
|
2871
|
-
});
|
|
2872
|
-
break;
|
|
2873
|
-
}
|
|
2874
|
-
case "tool_use":
|
|
2875
|
-
case "server_tool_use":
|
|
2876
|
-
case "mcp_tool_use": {
|
|
2877
|
-
if (typeof block.id !== "string") break;
|
|
2878
|
-
const name = block.type === "mcp_tool_use" && block.server_name ? `${block.server_name}.${block.name}` : String(block.name ?? "tool");
|
|
2879
|
-
this.calls.set(block.id, { name, input: block.input });
|
|
2880
|
-
out.events.push({
|
|
2881
|
-
type: "tool_call",
|
|
2882
|
-
providerEventId: block.id,
|
|
2883
|
-
tool: { callId: block.id, name, status: "running", input: block.input }
|
|
2884
|
-
});
|
|
2885
|
-
break;
|
|
2886
|
-
}
|
|
2887
|
-
}
|
|
2888
|
-
}
|
|
2889
|
-
}
|
|
2890
|
-
thinkingCounts = /* @__PURE__ */ new Map();
|
|
2891
|
-
thinkingIndex(id) {
|
|
2892
|
-
const n = this.thinkingCounts.get(id) ?? 0;
|
|
2893
|
-
this.thinkingCounts.set(id, n + 1);
|
|
2894
|
-
return n;
|
|
2895
|
-
}
|
|
2896
|
-
mapUser(line, out) {
|
|
2897
|
-
const content = line.message?.content;
|
|
2898
|
-
if (!Array.isArray(content)) return;
|
|
2899
|
-
for (const block of content) {
|
|
2900
|
-
if (block?.type !== "tool_result" || typeof block.tool_use_id !== "string") continue;
|
|
2901
|
-
const known = this.calls.get(block.tool_use_id);
|
|
2902
|
-
const full = toolResultText(block.content);
|
|
2903
|
-
const { text, truncated } = capText(full);
|
|
2904
|
-
if (block.is_error) {
|
|
2905
|
-
(out.failedTools ??= []).push({
|
|
2906
|
-
callId: block.tool_use_id,
|
|
2907
|
-
name: known?.name ?? "tool",
|
|
2908
|
-
input: known?.input ?? {},
|
|
2909
|
-
text: full
|
|
2910
|
-
});
|
|
2911
|
-
}
|
|
2912
|
-
const tool = {
|
|
2913
|
-
callId: block.tool_use_id,
|
|
2914
|
-
name: known?.name ?? "tool",
|
|
2915
|
-
status: block.is_error ? "failed" : "completed",
|
|
2916
|
-
...known ? { input: known.input } : {},
|
|
2917
|
-
output: text,
|
|
2918
|
-
...truncated ? { truncated: true } : {}
|
|
2919
|
-
};
|
|
2920
|
-
out.events.push({ type: "tool_call", providerEventId: block.tool_use_id, tool });
|
|
4227
|
+
import { join as join10 } from "node:path";
|
|
4228
|
+
var HANDLED_COMMAND_IDS_KEPT = 100;
|
|
4229
|
+
var SessionStore = class {
|
|
4230
|
+
constructor(stateDir) {
|
|
4231
|
+
this.stateDir = stateDir;
|
|
4232
|
+
}
|
|
4233
|
+
dir(sessionId) {
|
|
4234
|
+
return join10(this.stateDir, "sessions", sessionId);
|
|
4235
|
+
}
|
|
4236
|
+
outboxFile(sessionId) {
|
|
4237
|
+
return join10(this.dir(sessionId), "outbox.json");
|
|
4238
|
+
}
|
|
4239
|
+
async save(record) {
|
|
4240
|
+
record.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
4241
|
+
await writeJsonAtomic(join10(this.dir(record.sessionId), "session.json"), record);
|
|
4242
|
+
}
|
|
4243
|
+
async list() {
|
|
4244
|
+
const root = join10(this.stateDir, "sessions");
|
|
4245
|
+
await mkdir5(root, { recursive: true });
|
|
4246
|
+
const out = [];
|
|
4247
|
+
for (const entry of await readdir2(root, { withFileTypes: true })) {
|
|
4248
|
+
if (!entry.isDirectory()) continue;
|
|
4249
|
+
const rec = await readJson(join10(root, entry.name, "session.json"));
|
|
4250
|
+
if (rec?.sessionId === entry.name) out.push(upgradeRecord(rec));
|
|
2921
4251
|
}
|
|
4252
|
+
return out;
|
|
2922
4253
|
}
|
|
2923
|
-
|
|
2924
|
-
this.
|
|
2925
|
-
|
|
2926
|
-
|
|
2927
|
-
|
|
2928
|
-
this.
|
|
2929
|
-
this.streamTextCount = 0;
|
|
2930
|
-
this.completedTextCount.clear();
|
|
2931
|
-
this.thinkingCounts.clear();
|
|
2932
|
-
if (this.calls.size > 500) this.calls.clear();
|
|
4254
|
+
async remove(sessionId) {
|
|
4255
|
+
await rm5(this.dir(sessionId), { recursive: true, force: true });
|
|
4256
|
+
}
|
|
4257
|
+
/** Scratch working directory for a session without a repository. */
|
|
4258
|
+
scratchDir(sessionId) {
|
|
4259
|
+
return join10(this.stateDir, "scratch", sessionId);
|
|
2933
4260
|
}
|
|
2934
4261
|
};
|
|
2935
|
-
function
|
|
2936
|
-
|
|
4262
|
+
function upgradeRecord(stored) {
|
|
4263
|
+
const { claudeSessionId, ...rest } = stored;
|
|
4264
|
+
return { ...rest, conversationId: stored.conversationId ?? claudeSessionId ?? null };
|
|
2937
4265
|
}
|
|
2938
|
-
function
|
|
2939
|
-
if (
|
|
2940
|
-
|
|
2941
|
-
|
|
2942
|
-
if (b?.type === "text" && typeof b.text === "string") return b.text;
|
|
2943
|
-
if (b?.type === "image") return "[image]";
|
|
2944
|
-
return "";
|
|
2945
|
-
}).filter(Boolean).join("\n");
|
|
4266
|
+
function assertSafeSessionId(id) {
|
|
4267
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/.test(id) || id.includes("..")) {
|
|
4268
|
+
throw new Error(`Session id "${id}" is not usable as a directory name.`);
|
|
4269
|
+
}
|
|
2946
4270
|
}
|
|
2947
4271
|
|
|
2948
4272
|
// src/session.ts
|
|
@@ -2951,6 +4275,8 @@ var AgentSession = class {
|
|
|
2951
4275
|
constructor(record, deps) {
|
|
2952
4276
|
this.record = record;
|
|
2953
4277
|
this.deps = deps;
|
|
4278
|
+
this.driver = deps.driver;
|
|
4279
|
+
this.mapper = deps.driver.createMapper();
|
|
2954
4280
|
this.permissions = new PermissionRelay({
|
|
2955
4281
|
respond: (controlRequestId, response) => this.answerPermission(controlRequestId, response),
|
|
2956
4282
|
emit: (event) => this.emit(event),
|
|
@@ -2983,7 +4309,15 @@ var AgentSession = class {
|
|
|
2983
4309
|
});
|
|
2984
4310
|
}
|
|
2985
4311
|
child = null;
|
|
2986
|
-
|
|
4312
|
+
driver;
|
|
4313
|
+
mapper;
|
|
4314
|
+
/** per_turn agents: messages sent mid-turn, sent together as the next turn. */
|
|
4315
|
+
queuedTurns = [];
|
|
4316
|
+
/**
|
|
4317
|
+
* per_turn agents: a turn's process is being started. Claimed before the first await, so a
|
|
4318
|
+
* message arriving meanwhile is queued rather than starting a second process.
|
|
4319
|
+
*/
|
|
4320
|
+
startingTurn = false;
|
|
2987
4321
|
/** stdout lines are handled one at a time, in order, including the async turn end. */
|
|
2988
4322
|
lineChain = Promise.resolve();
|
|
2989
4323
|
stopping = null;
|
|
@@ -2992,7 +4326,7 @@ var AgentSession = class {
|
|
|
2992
4326
|
controlSeq = 0;
|
|
2993
4327
|
stderrTail = "";
|
|
2994
4328
|
sawResultSinceSpawn = false;
|
|
2995
|
-
/** The process was started
|
|
4329
|
+
/** The process was started to resume, and has not yet said it has the conversation. */
|
|
2996
4330
|
spawnedWithResume = false;
|
|
2997
4331
|
sawInitSinceSpawn = false;
|
|
2998
4332
|
/** The message that began the current turn, as the person wrote it (before any preface). */
|
|
@@ -3011,6 +4345,8 @@ var AgentSession = class {
|
|
|
3011
4345
|
exitWaiters = [];
|
|
3012
4346
|
/** Settles once the current process has exited and what it left in its tree is gone. */
|
|
3013
4347
|
treeReaped = Promise.resolve();
|
|
4348
|
+
/** The current process's tree, for the census taken before it is stopped. */
|
|
4349
|
+
tree = null;
|
|
3014
4350
|
/** How long what is left in the group gets after SIGTERM: a stop's grace, or the default. */
|
|
3015
4351
|
reapGraceMs;
|
|
3016
4352
|
lastActivity = Date.now();
|
|
@@ -3079,7 +4415,7 @@ var AgentSession = class {
|
|
|
3079
4415
|
outcome = `${saved} now: the agent may use it in this turn.`;
|
|
3080
4416
|
} else {
|
|
3081
4417
|
this.restartAfterTurn = true;
|
|
3082
|
-
outcome = `${saved}.
|
|
4418
|
+
outcome = `${saved}. ${this.driver.displayName} cannot change its permissions in the middle of a turn, so it takes effect when this turn ends.`;
|
|
3083
4419
|
}
|
|
3084
4420
|
this.deps.logger.info(`session ${this.sessionId}: granted ${rule} (${scope})`);
|
|
3085
4421
|
const denial = this.denials.get(denialId);
|
|
@@ -3122,7 +4458,7 @@ var AgentSession = class {
|
|
|
3122
4458
|
else this.seenFailedCalls.add(f.callId);
|
|
3123
4459
|
}
|
|
3124
4460
|
}
|
|
3125
|
-
/** Restarts
|
|
4461
|
+
/** Restarts the agent with the rules granted mid-turn, then sends what waited for it. */
|
|
3126
4462
|
async restartWithGrants() {
|
|
3127
4463
|
const texts = this.deferredMessages.splice(0);
|
|
3128
4464
|
try {
|
|
@@ -3132,7 +4468,7 @@ var AgentSession = class {
|
|
|
3132
4468
|
this.emit(
|
|
3133
4469
|
{
|
|
3134
4470
|
type: "error",
|
|
3135
|
-
message:
|
|
4471
|
+
message: `${this.driver.displayName} could not be started again with the permission you granted: ${err.message}`,
|
|
3136
4472
|
retryable: true
|
|
3137
4473
|
},
|
|
3138
4474
|
{ type: "result", status: "failed", text: null }
|
|
@@ -3153,24 +4489,28 @@ var AgentSession = class {
|
|
|
3153
4489
|
}
|
|
3154
4490
|
return outcome;
|
|
3155
4491
|
}
|
|
3156
|
-
/**
|
|
4492
|
+
/** The answer to a permission request; dropped when the process is already gone. */
|
|
3157
4493
|
answerPermission(controlRequestId, response) {
|
|
4494
|
+
const control = this.driver.control;
|
|
4495
|
+
if (!control) return;
|
|
3158
4496
|
try {
|
|
3159
|
-
this.write(
|
|
3160
|
-
type: "control_response",
|
|
3161
|
-
response: { subtype: "success", request_id: controlRequestId, response }
|
|
3162
|
-
});
|
|
4497
|
+
this.write(control.permissionResponse(controlRequestId, response));
|
|
3163
4498
|
} catch {
|
|
3164
4499
|
}
|
|
3165
4500
|
}
|
|
3166
4501
|
/**
|
|
3167
|
-
* A control
|
|
3168
|
-
*
|
|
3169
|
-
*
|
|
4502
|
+
* A control line from the agent: a permission prompt is relayed (or, for a session not set
|
|
4503
|
+
* up to relay, denied, which is what `--permission-prompts none` would have done), a
|
|
4504
|
+
* cancelled one is withdrawn. Any other request is answered as unsupported, so the agent
|
|
4505
|
+
* never waits on it.
|
|
3170
4506
|
*/
|
|
3171
|
-
async
|
|
3172
|
-
|
|
3173
|
-
|
|
4507
|
+
async handleControlLine(control, line) {
|
|
4508
|
+
if (line.kind === "cancel") {
|
|
4509
|
+
this.permissions.cancel(line.controlRequestId);
|
|
4510
|
+
return;
|
|
4511
|
+
}
|
|
4512
|
+
if (line.kind === "permission") {
|
|
4513
|
+
const ask = line.ask;
|
|
3174
4514
|
if (!this.record.relayPermissionRequests) {
|
|
3175
4515
|
this.answerPermission(ask.controlRequestId, {
|
|
3176
4516
|
behavior: "deny",
|
|
@@ -3182,21 +4522,14 @@ var AgentSession = class {
|
|
|
3182
4522
|
this.inheritedNow = await this.readInheritedRules();
|
|
3183
4523
|
if (this.permissions.request(ask) === "relayed") {
|
|
3184
4524
|
this.deps.logger.info(
|
|
3185
|
-
`session ${this.sessionId}:
|
|
4525
|
+
`session ${this.sessionId}: ${this.driver.displayName} asks permission for ${ask.toolName}; waiting for an answer in Discovery Tree`
|
|
3186
4526
|
);
|
|
3187
4527
|
}
|
|
3188
4528
|
return;
|
|
3189
4529
|
}
|
|
3190
|
-
if (
|
|
4530
|
+
if (line.requestId !== null) {
|
|
3191
4531
|
try {
|
|
3192
|
-
this.write(
|
|
3193
|
-
type: "control_response",
|
|
3194
|
-
response: {
|
|
3195
|
-
subtype: "error",
|
|
3196
|
-
request_id: line.request_id,
|
|
3197
|
-
error: "dt-runner does not handle this control request."
|
|
3198
|
-
}
|
|
3199
|
-
});
|
|
4532
|
+
this.write(control.unsupportedResponse(line.requestId));
|
|
3200
4533
|
} catch {
|
|
3201
4534
|
}
|
|
3202
4535
|
}
|
|
@@ -3226,7 +4559,8 @@ var AgentSession = class {
|
|
|
3226
4559
|
}
|
|
3227
4560
|
/**
|
|
3228
4561
|
* Delivers a person's message: written to the live process (mid-turn is fine), or the
|
|
3229
|
-
* process is started again
|
|
4562
|
+
* process is started again resuming the conversation first. A per_turn agent starts a
|
|
4563
|
+
* turn's process with it, or (mid-turn) takes it as the next turn.
|
|
3230
4564
|
*/
|
|
3231
4565
|
async sendMessage(text, commandId) {
|
|
3232
4566
|
if (this.restartAfterTurn && this.record.turnActive) {
|
|
@@ -3239,7 +4573,7 @@ var AgentSession = class {
|
|
|
3239
4573
|
this.emit({ type: "user_message_echo", providerEventId: commandId, text, delivered: true });
|
|
3240
4574
|
return;
|
|
3241
4575
|
}
|
|
3242
|
-
await this.ensureProcess();
|
|
4576
|
+
if (this.driver.processModel === "persistent") await this.ensureProcess();
|
|
3243
4577
|
const ids = this.record.handledCommandIds ??= [];
|
|
3244
4578
|
ids.push(commandId);
|
|
3245
4579
|
if (ids.length > HANDLED_COMMAND_IDS_KEPT) ids.splice(0, ids.length - HANDLED_COMMAND_IDS_KEPT);
|
|
@@ -3259,32 +4593,34 @@ var AgentSession = class {
|
|
|
3259
4593
|
}
|
|
3260
4594
|
}
|
|
3261
4595
|
/**
|
|
3262
|
-
* Stops the current turn.
|
|
3263
|
-
* the Agent SDK sends it) and ends the turn
|
|
3264
|
-
*
|
|
4596
|
+
* Stops the current turn. An agent that takes an interrupt request on stdin (Claude Code,
|
|
4597
|
+
* as the Agent SDK sends it) gets one and ends the turn itself; if it has not within the
|
|
4598
|
+
* grace period, or takes none, SIGINT does the same the hard way.
|
|
3265
4599
|
*/
|
|
3266
4600
|
interrupt() {
|
|
3267
4601
|
const child = this.child;
|
|
3268
4602
|
if (!child || !this.record.turnActive) return false;
|
|
3269
4603
|
this.interruptRequested = true;
|
|
3270
4604
|
this.permissions.expireAll(PERMISSION_EXPIRED_INTERRUPTED);
|
|
3271
|
-
|
|
3272
|
-
|
|
3273
|
-
|
|
3274
|
-
|
|
3275
|
-
|
|
4605
|
+
const sigint = () => child.kill("SIGINT");
|
|
4606
|
+
const message = this.driver.interruptMessage?.(`dt_interrupt_${++this.controlSeq}`);
|
|
4607
|
+
if (message === void 0) {
|
|
4608
|
+
sigint();
|
|
4609
|
+
return true;
|
|
4610
|
+
}
|
|
4611
|
+
this.write(message);
|
|
3276
4612
|
if (this.interruptTimer) clearTimeout(this.interruptTimer);
|
|
3277
4613
|
this.interruptTimer = setTimeout(() => {
|
|
3278
4614
|
this.interruptTimer = null;
|
|
3279
4615
|
if (this.child === child && this.record.turnActive) {
|
|
3280
4616
|
this.deps.logger.warn(`session ${this.sessionId}: no answer to interrupt; sending SIGINT`);
|
|
3281
|
-
|
|
4617
|
+
sigint();
|
|
3282
4618
|
}
|
|
3283
4619
|
}, this.deps.interruptGraceMs ?? 5e3);
|
|
3284
4620
|
return true;
|
|
3285
4621
|
}
|
|
3286
4622
|
/**
|
|
3287
|
-
* Ends the process (closing stdin first, so
|
|
4623
|
+
* Ends the process (closing stdin first, so the agent saves its session and exits), and
|
|
3288
4624
|
* with it everything it started: the background commands still in its process group are
|
|
3289
4625
|
* ended once it has exited, and SIGTERM and SIGKILL go to the whole group.
|
|
3290
4626
|
*/
|
|
@@ -3295,6 +4631,9 @@ var AgentSession = class {
|
|
|
3295
4631
|
this.stopping = reason;
|
|
3296
4632
|
this.reapGraceMs = graceMs;
|
|
3297
4633
|
const exited = new Promise((resolve2) => this.exitWaiters.push(resolve2));
|
|
4634
|
+
if (child.exitCode === null && child.signalCode === null) {
|
|
4635
|
+
await snapshotTree(this.tree, this.deps.reap);
|
|
4636
|
+
}
|
|
3298
4637
|
child.stdin.end();
|
|
3299
4638
|
const timedOut = await raceTimeout(exited, graceMs);
|
|
3300
4639
|
if (timedOut && this.child === child) {
|
|
@@ -3318,9 +4657,10 @@ var AgentSession = class {
|
|
|
3318
4657
|
* Writes a user message to a running process that is not being stopped (starting it, or
|
|
3319
4658
|
* waiting out a stop in progress and starting it again, first). The turn counts as active
|
|
3320
4659
|
* only once the message is written: a write that fails leaves no turn waiting for a
|
|
3321
|
-
* result that will never come.
|
|
4660
|
+
* result that will never come. A per_turn agent starts the turn's own process instead.
|
|
3322
4661
|
*/
|
|
3323
4662
|
async beginTurn(text, before) {
|
|
4663
|
+
if (this.driver.processModel === "per_turn") return this.beginProcessTurn(text, before);
|
|
3324
4664
|
while (!this.child || this.stopping || this.resumeDoomed) await this.ensureProcess();
|
|
3325
4665
|
let content = text;
|
|
3326
4666
|
const preface = this.record.freshPreface;
|
|
@@ -3333,7 +4673,66 @@ ${text}`;
|
|
|
3333
4673
|
this.record.freshPreface = null;
|
|
3334
4674
|
await this.deps.store.save(this.record);
|
|
3335
4675
|
}
|
|
3336
|
-
this.write(
|
|
4676
|
+
this.write(this.driver.encodeMessage(content));
|
|
4677
|
+
await this.turnBegun(text, before);
|
|
4678
|
+
}
|
|
4679
|
+
/**
|
|
4680
|
+
* A per_turn agent's turn: a process of its own, given the message and the conversation to
|
|
4681
|
+
* resume. A message sent while a turn runs (or starts) waits for it, and goes with any
|
|
4682
|
+
* others as the next turn; messages still waiting go ahead of this one, in order.
|
|
4683
|
+
*/
|
|
4684
|
+
async beginProcessTurn(text, before) {
|
|
4685
|
+
if (this.record.turnActive || this.startingTurn) {
|
|
4686
|
+
this.queuedTurns.push(text);
|
|
4687
|
+
this.lastActivity = Date.now();
|
|
4688
|
+
if (before) this.emit(before);
|
|
4689
|
+
return;
|
|
4690
|
+
}
|
|
4691
|
+
const waiting = this.queuedTurns.splice(0);
|
|
4692
|
+
try {
|
|
4693
|
+
await this.startProcessTurn([...waiting, text], before);
|
|
4694
|
+
} catch (err) {
|
|
4695
|
+
this.queuedTurns.unshift(...waiting);
|
|
4696
|
+
throw err;
|
|
4697
|
+
}
|
|
4698
|
+
}
|
|
4699
|
+
/** Starts a per_turn agent's process on these messages (oldest first), as one turn. */
|
|
4700
|
+
async startProcessTurn(texts, before) {
|
|
4701
|
+
this.startingTurn = true;
|
|
4702
|
+
try {
|
|
4703
|
+
while (this.child) await this.stop("idle");
|
|
4704
|
+
const text = texts.join("\n\n");
|
|
4705
|
+
const preface = this.record.freshPreface;
|
|
4706
|
+
const fresh = !this.record.conversationId;
|
|
4707
|
+
const prompt = preface && fresh ? `${preface}
|
|
4708
|
+
|
|
4709
|
+
---
|
|
4710
|
+
|
|
4711
|
+
${text}` : text;
|
|
4712
|
+
const previousTurnText = this.turnText;
|
|
4713
|
+
if (preface && fresh) this.record.freshPreface = null;
|
|
4714
|
+
this.turnText = text;
|
|
4715
|
+
this.record.turnActive = true;
|
|
4716
|
+
this.mapper.markRunning();
|
|
4717
|
+
this.lastActivity = Date.now();
|
|
4718
|
+
try {
|
|
4719
|
+
await this.deps.store.save(this.record);
|
|
4720
|
+
await this.spawnAgent(prompt);
|
|
4721
|
+
} catch (err) {
|
|
4722
|
+
this.record.turnActive = false;
|
|
4723
|
+
if (preface && fresh) this.record.freshPreface = preface;
|
|
4724
|
+
this.turnText = previousTurnText;
|
|
4725
|
+
await this.deps.store.save(this.record).catch(() => void 0);
|
|
4726
|
+
throw err;
|
|
4727
|
+
}
|
|
4728
|
+
if (before) this.emit(before);
|
|
4729
|
+
this.emit({ type: "status", status: "running" });
|
|
4730
|
+
} finally {
|
|
4731
|
+
this.startingTurn = false;
|
|
4732
|
+
}
|
|
4733
|
+
}
|
|
4734
|
+
/** The turn's message went to the agent: the turn is active, and said to be. */
|
|
4735
|
+
async turnBegun(text, before) {
|
|
3337
4736
|
if (!this.record.turnActive) this.turnText = text;
|
|
3338
4737
|
this.lastActivity = Date.now();
|
|
3339
4738
|
if (before) this.emit(before);
|
|
@@ -3344,9 +4743,31 @@ ${text}`;
|
|
|
3344
4743
|
await this.deps.store.save(this.record);
|
|
3345
4744
|
}
|
|
3346
4745
|
}
|
|
4746
|
+
/** per_turn agents: once the turn is over, however it ended, what waited for it goes next. */
|
|
4747
|
+
scheduleQueuedTurns() {
|
|
4748
|
+
if (this.driver.processModel !== "per_turn" || !this.queuedTurns.length) return;
|
|
4749
|
+
setTimeout(() => void this.runQueuedTurns(), 0);
|
|
4750
|
+
}
|
|
4751
|
+
/** per_turn agents: the messages that waited for the last turn, as the next one. */
|
|
4752
|
+
async runQueuedTurns() {
|
|
4753
|
+
if (!this.queuedTurns.length || this.record.turnActive || this.startingTurn) return;
|
|
4754
|
+
const texts = this.queuedTurns.splice(0);
|
|
4755
|
+
try {
|
|
4756
|
+
await this.startProcessTurn(texts);
|
|
4757
|
+
} catch (err) {
|
|
4758
|
+
this.emit(
|
|
4759
|
+
{
|
|
4760
|
+
type: "error",
|
|
4761
|
+
message: `${this.driver.displayName} could not be started for the next message: ${err.message}`,
|
|
4762
|
+
retryable: true
|
|
4763
|
+
},
|
|
4764
|
+
{ type: "result", status: "failed", text: null }
|
|
4765
|
+
);
|
|
4766
|
+
}
|
|
4767
|
+
}
|
|
3347
4768
|
write(message) {
|
|
3348
4769
|
if (!this.child || this.stopping || this.child.stdin.writableEnded) {
|
|
3349
|
-
throw new Error(
|
|
4770
|
+
throw new Error(`${this.driver.displayName} is not running for this session.`);
|
|
3350
4771
|
}
|
|
3351
4772
|
this.child.stdin.write(JSON.stringify(message) + "\n");
|
|
3352
4773
|
}
|
|
@@ -3355,15 +4776,19 @@ ${text}`;
|
|
|
3355
4776
|
if (!this.child) return Promise.resolve();
|
|
3356
4777
|
return new Promise((resolve2) => this.exitWaiters.push(resolve2));
|
|
3357
4778
|
}
|
|
4779
|
+
/** persistent agents: the session's process, started (resuming) when there is none. */
|
|
3358
4780
|
async ensureProcess() {
|
|
3359
4781
|
while (this.child && (this.stopping || this.resumeDoomed)) await this.waitForExit();
|
|
3360
4782
|
if (this.child) return;
|
|
4783
|
+
await this.spawnAgent();
|
|
4784
|
+
}
|
|
4785
|
+
/** Starts the agent's process (with a per_turn agent's prompt), and reads what it says. */
|
|
4786
|
+
async spawnAgent(prompt) {
|
|
3361
4787
|
await this.prepareEvidenceDir();
|
|
3362
|
-
const { bin, features } = await this.deps.
|
|
4788
|
+
const { bin, features } = await this.deps.resolveAgent();
|
|
3363
4789
|
const savedRules = await (this.deps.savedRules?.(this.record.repository) ?? []);
|
|
3364
4790
|
this.inheritedNow = await this.readInheritedRules();
|
|
3365
|
-
const
|
|
3366
|
-
const assembled = [
|
|
4791
|
+
const allowedTools = [
|
|
3367
4792
|
.../* @__PURE__ */ new Set([
|
|
3368
4793
|
...this.deps.allowedTools,
|
|
3369
4794
|
...this.inheritedNow.allow,
|
|
@@ -3371,29 +4796,33 @@ ${text}`;
|
|
|
3371
4796
|
...this.record.grantRules ?? []
|
|
3372
4797
|
])
|
|
3373
4798
|
];
|
|
3374
|
-
const allowedTools = features.settingsFlag || ask.length === 0 ? assembled : assembled.filter((r) => !overlapsAsk(r, ask));
|
|
3375
4799
|
const disallowedTools = [
|
|
3376
4800
|
.../* @__PURE__ */ new Set([...this.deps.disallowedTools ?? [], ...this.inheritedNow.deny])
|
|
3377
4801
|
];
|
|
3378
|
-
const
|
|
4802
|
+
const launch = this.driver.launch({
|
|
4803
|
+
bin,
|
|
4804
|
+
features,
|
|
4805
|
+
cwd: this.record.cwd,
|
|
3379
4806
|
permissionMode: this.deps.permissionMode,
|
|
3380
4807
|
allowedTools,
|
|
3381
4808
|
disallowedTools,
|
|
3382
|
-
|
|
4809
|
+
askTools: this.inheritedNow.ask,
|
|
4810
|
+
loadProjectSettings: !!this.deps.loadProjectSettings,
|
|
3383
4811
|
model: this.record.model,
|
|
3384
|
-
resume: this.record.
|
|
4812
|
+
resume: this.record.conversationId,
|
|
3385
4813
|
relayPermissions: !!this.record.relayPermissionRequests,
|
|
3386
|
-
|
|
3387
|
-
appendSystemPrompt: runnerSystemPrompt({
|
|
4814
|
+
systemPrompt: runnerSystemPrompt({
|
|
3388
4815
|
workBranch: this.record.workBranch,
|
|
3389
4816
|
baseRef: this.record.baseRef,
|
|
3390
|
-
cwd: this.record.cwd
|
|
4817
|
+
cwd: this.record.cwd,
|
|
4818
|
+
reviewImages: !!this.record.reviewImages
|
|
3391
4819
|
}),
|
|
3392
|
-
|
|
4820
|
+
...prompt !== void 0 ? { prompt } : {},
|
|
4821
|
+
...this.deps.agentConfig ? { agentConfig: this.deps.agentConfig } : {}
|
|
3393
4822
|
});
|
|
3394
|
-
const child =
|
|
4823
|
+
const child = spawn4(launch.bin, launch.args, {
|
|
3395
4824
|
cwd: this.record.cwd,
|
|
3396
|
-
env: process.env,
|
|
4825
|
+
env: launch.env ? { ...process.env, ...launch.env } : process.env,
|
|
3397
4826
|
stdio: ["pipe", "pipe", "pipe"],
|
|
3398
4827
|
windowsHide: true,
|
|
3399
4828
|
// A process group of its own, so what it starts can be ended with it. It also means
|
|
@@ -3408,36 +4837,43 @@ ${text}`;
|
|
|
3408
4837
|
});
|
|
3409
4838
|
child.once(
|
|
3410
4839
|
"error",
|
|
3411
|
-
(err) => reject(
|
|
4840
|
+
(err) => reject(
|
|
4841
|
+
new Error(`Could not start ${this.driver.displayName} (${launch.bin}): ${err.message}`)
|
|
4842
|
+
)
|
|
3412
4843
|
);
|
|
3413
4844
|
});
|
|
3414
4845
|
this.child = child;
|
|
4846
|
+
this.tree = tree;
|
|
3415
4847
|
this.stopping = null;
|
|
3416
4848
|
this.resumeDoomed = false;
|
|
3417
4849
|
this.reapGraceMs = void 0;
|
|
3418
4850
|
this.stderrTail = "";
|
|
3419
4851
|
this.sawResultSinceSpawn = false;
|
|
3420
|
-
this.spawnedWithResume = !!this.record.
|
|
4852
|
+
this.spawnedWithResume = !!this.record.conversationId;
|
|
3421
4853
|
this.sawInitSinceSpawn = false;
|
|
3422
4854
|
this.deps.logger.info(
|
|
3423
|
-
`session ${this.sessionId}:
|
|
4855
|
+
`session ${this.sessionId}: ${this.driver.displayName} started${this.record.conversationId ? " (resumed)" : ""}`,
|
|
3424
4856
|
{ pid: child.pid }
|
|
3425
4857
|
);
|
|
3426
4858
|
this.treeReaped = new Promise(
|
|
3427
4859
|
(resolve2) => child.once("exit", () => void reapTree(tree, this.reapGraceMs, this.deps.reap).then(resolve2))
|
|
3428
4860
|
);
|
|
3429
4861
|
child.stdin.on("error", () => void 0);
|
|
4862
|
+
if (launch.stdin !== void 0) child.stdin.end(launch.stdin);
|
|
4863
|
+
else if (this.driver.processModel === "per_turn") child.stdin.end();
|
|
3430
4864
|
child.stderr.setEncoding("utf8").on("data", (d) => {
|
|
3431
4865
|
this.stderrTail = (this.stderrTail + d).slice(-4e3);
|
|
3432
4866
|
});
|
|
3433
|
-
const rl =
|
|
4867
|
+
const rl = createInterface2({ input: child.stdout, crlfDelay: Infinity });
|
|
3434
4868
|
rl.on("line", (line) => {
|
|
3435
4869
|
if (!line.trim()) return;
|
|
3436
4870
|
let parsed;
|
|
3437
4871
|
try {
|
|
3438
4872
|
parsed = JSON.parse(line);
|
|
3439
4873
|
} catch {
|
|
3440
|
-
this.deps.logger.debug(
|
|
4874
|
+
this.deps.logger.debug(
|
|
4875
|
+
`session ${this.sessionId}: non-JSON output from ${this.driver.displayName}`
|
|
4876
|
+
);
|
|
3441
4877
|
return;
|
|
3442
4878
|
}
|
|
3443
4879
|
this.lineChain = this.lineChain.then(() => this.handleLine(parsed)).catch((err) => {
|
|
@@ -3453,22 +4889,19 @@ ${text}`;
|
|
|
3453
4889
|
}
|
|
3454
4890
|
async handleLine(line) {
|
|
3455
4891
|
this.lastActivity = Date.now();
|
|
3456
|
-
|
|
3457
|
-
|
|
3458
|
-
|
|
3459
|
-
|
|
3460
|
-
const cancelled = parseControlCancel(line);
|
|
3461
|
-
if (cancelled) {
|
|
3462
|
-
this.permissions.cancel(cancelled);
|
|
4892
|
+
const control = this.driver.control;
|
|
4893
|
+
const controlLine = control?.parse(line);
|
|
4894
|
+
if (control && controlLine) {
|
|
4895
|
+
await this.handleControlLine(control, controlLine);
|
|
3463
4896
|
return;
|
|
3464
4897
|
}
|
|
3465
4898
|
const mapped = this.mapper.map(line);
|
|
3466
4899
|
let dirty = false;
|
|
3467
|
-
if (mapped.
|
|
4900
|
+
if (mapped.conversationId) this.sawInitSinceSpawn = true;
|
|
3468
4901
|
let learnedSessionId = null;
|
|
3469
|
-
if (mapped.
|
|
3470
|
-
this.record.
|
|
3471
|
-
learnedSessionId = mapped.
|
|
4902
|
+
if (mapped.conversationId && mapped.conversationId !== this.record.conversationId) {
|
|
4903
|
+
this.record.conversationId = mapped.conversationId;
|
|
4904
|
+
learnedSessionId = mapped.conversationId;
|
|
3472
4905
|
dirty = true;
|
|
3473
4906
|
}
|
|
3474
4907
|
if (mapped.turnStarted && !this.record.turnActive) {
|
|
@@ -3478,17 +4911,11 @@ ${text}`;
|
|
|
3478
4911
|
if (dirty) await this.deps.store.save(this.record);
|
|
3479
4912
|
if (learnedSessionId) {
|
|
3480
4913
|
const at = mapped.events.findIndex((e) => e.type === "status");
|
|
4914
|
+
const ids = this.conversationIds(learnedSessionId);
|
|
3481
4915
|
if (at >= 0) {
|
|
3482
|
-
mapped.events[at] = {
|
|
3483
|
-
...mapped.events[at],
|
|
3484
|
-
claudeSessionId: learnedSessionId
|
|
3485
|
-
};
|
|
4916
|
+
mapped.events[at] = { ...mapped.events[at], ...ids };
|
|
3486
4917
|
} else {
|
|
3487
|
-
mapped.events.push({
|
|
3488
|
-
type: "status",
|
|
3489
|
-
status: "running",
|
|
3490
|
-
claudeSessionId: learnedSessionId
|
|
3491
|
-
});
|
|
4918
|
+
mapped.events.push({ type: "status", status: "running", ...ids });
|
|
3492
4919
|
}
|
|
3493
4920
|
}
|
|
3494
4921
|
if (mapped.events.length) this.emit(...mapped.events);
|
|
@@ -3500,9 +4927,9 @@ ${text}`;
|
|
|
3500
4927
|
}
|
|
3501
4928
|
if (mapped.turnEnd && this.resumeFailedBeforeTurn(mapped.turnEnd.isError)) {
|
|
3502
4929
|
this.deps.logger.warn(
|
|
3503
|
-
`session ${this.sessionId}: the
|
|
4930
|
+
`session ${this.sessionId}: the ${this.driver.displayName} conversation to resume was not found; starting a fresh one`
|
|
3504
4931
|
);
|
|
3505
|
-
this.record.
|
|
4932
|
+
this.record.conversationId = null;
|
|
3506
4933
|
this.resumeDoomed = true;
|
|
3507
4934
|
await this.deps.store.save(this.record);
|
|
3508
4935
|
this.child?.stdin.end();
|
|
@@ -3515,7 +4942,7 @@ ${text}`;
|
|
|
3515
4942
|
}
|
|
3516
4943
|
/**
|
|
3517
4944
|
* The process was started to resume a conversation and failed before it said it had it
|
|
3518
|
-
* (no `system/init`):
|
|
4945
|
+
* (Claude Code: no `system/init`): the agent did not find the conversation on this computer.
|
|
3519
4946
|
*/
|
|
3520
4947
|
resumeNotFound(isError) {
|
|
3521
4948
|
return isError && this.spawnedWithResume && !this.sawInitSinceSpawn && !this.interruptRequested && this.record.turnActive && this.turnText !== null;
|
|
@@ -3523,12 +4950,19 @@ ${text}`;
|
|
|
3523
4950
|
resumeFailedBeforeTurn(isError) {
|
|
3524
4951
|
return isError && this.spawnedWithResume && !this.sawInitSinceSpawn && !this.interruptRequested && !this.record.turnActive;
|
|
3525
4952
|
}
|
|
4953
|
+
/**
|
|
4954
|
+
* How an event names the agent's conversation: `conversationId` for every agent, and
|
|
4955
|
+
* Claude Code's also as `claudeSessionId`, which servers that predate the neutral name read.
|
|
4956
|
+
*/
|
|
4957
|
+
conversationIds(id) {
|
|
4958
|
+
return this.driver.kind === DEFAULT_AGENT_KIND ? { claudeSessionId: id, conversationId: id } : { conversationId: id };
|
|
4959
|
+
}
|
|
3526
4960
|
planFreshRetry() {
|
|
3527
4961
|
this.deps.logger.warn(
|
|
3528
|
-
`session ${this.sessionId}: the
|
|
4962
|
+
`session ${this.sessionId}: the ${this.driver.displayName} conversation to resume was not found; starting a fresh one`
|
|
3529
4963
|
);
|
|
3530
4964
|
this.resumeRetry = this.turnText;
|
|
3531
|
-
this.record.
|
|
4965
|
+
this.record.conversationId = null;
|
|
3532
4966
|
}
|
|
3533
4967
|
async endTurn(turn) {
|
|
3534
4968
|
this.permissions.expireAll(PERMISSION_EXPIRED_TURN_ENDED);
|
|
@@ -3541,12 +4975,12 @@ ${text}`;
|
|
|
3541
4975
|
if (this.interruptTimer) clearTimeout(this.interruptTimer);
|
|
3542
4976
|
this.interruptTimer = null;
|
|
3543
4977
|
const turnFailed = turn.isError && !interrupted;
|
|
3544
|
-
if (turnFailed && turnFailedToSignIn(turn)) this.deps.
|
|
3545
|
-
else if (!turn.isError) this.deps.
|
|
4978
|
+
if (turnFailed && this.driver.turnFailedToSignIn(turn)) this.deps.onAgentSignIn?.(false);
|
|
4979
|
+
else if (!turn.isError) this.deps.onAgentSignIn?.(true);
|
|
3546
4980
|
if (turnFailed) {
|
|
3547
4981
|
this.emit({
|
|
3548
4982
|
type: "error",
|
|
3549
|
-
message: turnErrorMessage(turn),
|
|
4983
|
+
message: this.driver.turnErrorMessage(turn),
|
|
3550
4984
|
retryable: true
|
|
3551
4985
|
});
|
|
3552
4986
|
}
|
|
@@ -3557,6 +4991,11 @@ ${text}`;
|
|
|
3557
4991
|
});
|
|
3558
4992
|
return "";
|
|
3559
4993
|
});
|
|
4994
|
+
await this.uploadReviewImages().catch((err) => {
|
|
4995
|
+
this.deps.logger.warn(`session ${this.sessionId}: uploading review images failed`, {
|
|
4996
|
+
error: scrubSecrets(err instanceof Error ? err.message : String(err))
|
|
4997
|
+
});
|
|
4998
|
+
});
|
|
3560
4999
|
const failed = turnFailed || push.failed;
|
|
3561
5000
|
const text = withScreenshots(
|
|
3562
5001
|
interrupted ? turn.isError ? null : turn.text : turn.text,
|
|
@@ -3576,12 +5015,14 @@ ${text}`;
|
|
|
3576
5015
|
...push.failed ? { unpushedWork: true } : {},
|
|
3577
5016
|
// So the server can have a later session resume this conversation (a run continued
|
|
3578
5017
|
// after it ended).
|
|
3579
|
-
...this.record.
|
|
5018
|
+
...this.record.conversationId ? this.conversationIds(this.record.conversationId) : {}
|
|
3580
5019
|
});
|
|
3581
5020
|
this.lastActivity = Date.now();
|
|
3582
5021
|
if (this.restartAfterTurn) {
|
|
3583
5022
|
this.restartAfterTurn = false;
|
|
3584
5023
|
setTimeout(() => void this.restartWithGrants(), 0);
|
|
5024
|
+
} else {
|
|
5025
|
+
this.scheduleQueuedTurns();
|
|
3585
5026
|
}
|
|
3586
5027
|
this.deps.logger.info(
|
|
3587
5028
|
`session ${this.sessionId}: turn ${interrupted ? "interrupted" : turnFailed ? "ended with an error" : push.failed ? "finished, but its work was not pushed" : "finished"}`,
|
|
@@ -3598,7 +5039,7 @@ ${text}`;
|
|
|
3598
5039
|
const repo = parseRepoUrl(repository ?? "");
|
|
3599
5040
|
if (!pullRequest || !workBranch || !repo) return null;
|
|
3600
5041
|
const body = [
|
|
3601
|
-
text?.trim() ||
|
|
5042
|
+
text?.trim() || `Work by the ${this.driver.displayName} (local) agent.`,
|
|
3602
5043
|
"",
|
|
3603
5044
|
"---",
|
|
3604
5045
|
pullRequest.footer
|
|
@@ -3648,6 +5089,38 @@ ${text}`;
|
|
|
3648
5089
|
});
|
|
3649
5090
|
}
|
|
3650
5091
|
}
|
|
5092
|
+
/**
|
|
5093
|
+
* Uploads the turn's review images (a design proposal with no repository). What could not
|
|
5094
|
+
* go is said in the conversation; an upload that failed leaves the rest for the next turn.
|
|
5095
|
+
*/
|
|
5096
|
+
async uploadReviewImages() {
|
|
5097
|
+
const uploader = this.deps.reviewImageUploader;
|
|
5098
|
+
if (!this.record.reviewImages || this.record.workBranch || !uploader) return;
|
|
5099
|
+
const res = await uploadReviewImages({
|
|
5100
|
+
worktree: this.record.cwd,
|
|
5101
|
+
sessionId: this.sessionId,
|
|
5102
|
+
uploader
|
|
5103
|
+
});
|
|
5104
|
+
if (res.skipped.length) {
|
|
5105
|
+
this.emit({
|
|
5106
|
+
type: "error",
|
|
5107
|
+
message: `Review images not attached (not a readable image, over 5 MB, or past the first ${MAX_REVIEW_IMAGES_PER_RUN}): ${res.skipped.join(", ").slice(0, 300)}`,
|
|
5108
|
+
retryable: false
|
|
5109
|
+
});
|
|
5110
|
+
}
|
|
5111
|
+
if (res.error) {
|
|
5112
|
+
this.emit({
|
|
5113
|
+
type: "error",
|
|
5114
|
+
message: `${res.error} The rest are still in ${EVIDENCE_DIR}/ for the next turn.`,
|
|
5115
|
+
retryable: false
|
|
5116
|
+
});
|
|
5117
|
+
}
|
|
5118
|
+
if (res.uploaded.length) {
|
|
5119
|
+
this.deps.logger.info(
|
|
5120
|
+
`session ${this.sessionId}: attached ${res.uploaded.length} review image(s) to the task`
|
|
5121
|
+
);
|
|
5122
|
+
}
|
|
5123
|
+
}
|
|
3651
5124
|
/** Publishes the turn's screenshots; their markdown, or '' when there were none. */
|
|
3652
5125
|
async publishScreenshots() {
|
|
3653
5126
|
const { workBranch, repoDir, cwd, repository } = this.record;
|
|
@@ -3722,21 +5195,25 @@ ${text}`;
|
|
|
3722
5195
|
const waiters = this.exitWaiters;
|
|
3723
5196
|
this.exitWaiters = [];
|
|
3724
5197
|
try {
|
|
3725
|
-
if (this.resumeRetry === null && !reason && this.record.turnActive && this.resumeNotFound(true) &&
|
|
5198
|
+
if (this.resumeRetry === null && !reason && this.record.turnActive && this.resumeNotFound(true) && this.driver.resumeNotFound(this.stderrTail)) {
|
|
3726
5199
|
this.planFreshRetry();
|
|
3727
5200
|
}
|
|
3728
5201
|
if (this.resumeRetry !== null) {
|
|
3729
5202
|
const text = this.resumeRetry;
|
|
3730
5203
|
this.resumeRetry = null;
|
|
5204
|
+
const perTurn = this.driver.processModel === "per_turn";
|
|
5205
|
+
if (perTurn) this.startingTurn = true;
|
|
3731
5206
|
this.record.turnActive = false;
|
|
3732
|
-
await this.deps.store.save(this.record);
|
|
3733
5207
|
try {
|
|
3734
|
-
await this.
|
|
5208
|
+
await this.deps.store.save(this.record);
|
|
5209
|
+
if (perTurn) await this.startProcessTurn([text]);
|
|
5210
|
+
else await this.beginTurn(text);
|
|
3735
5211
|
} catch (err) {
|
|
5212
|
+
this.startingTurn = false;
|
|
3736
5213
|
this.emit(
|
|
3737
5214
|
{
|
|
3738
5215
|
type: "error",
|
|
3739
|
-
message:
|
|
5216
|
+
message: `${this.driver.displayName} could not be started again for this message: ${err.message}`,
|
|
3740
5217
|
retryable: true
|
|
3741
5218
|
},
|
|
3742
5219
|
{ type: "result", status: "failed", text: null }
|
|
@@ -3745,11 +5222,13 @@ ${text}`;
|
|
|
3745
5222
|
return;
|
|
3746
5223
|
}
|
|
3747
5224
|
if (reason) {
|
|
3748
|
-
this.deps.logger.info(
|
|
5225
|
+
this.deps.logger.info(
|
|
5226
|
+
`session ${this.sessionId}: ${this.driver.displayName} stopped (${reason})`
|
|
5227
|
+
);
|
|
3749
5228
|
if (reason !== "shutdown" && this.record.turnActive) {
|
|
3750
5229
|
this.emit({
|
|
3751
5230
|
type: "error",
|
|
3752
|
-
message:
|
|
5231
|
+
message: `${this.driver.displayName} was stopped in the middle of this turn. Send a message to continue.`,
|
|
3753
5232
|
retryable: true
|
|
3754
5233
|
});
|
|
3755
5234
|
this.record.turnActive = false;
|
|
@@ -3759,10 +5238,12 @@ ${text}`;
|
|
|
3759
5238
|
return;
|
|
3760
5239
|
}
|
|
3761
5240
|
if (!this.record.turnActive) {
|
|
3762
|
-
this.
|
|
3763
|
-
|
|
3764
|
-
|
|
3765
|
-
|
|
5241
|
+
if (this.driver.processModel === "persistent") {
|
|
5242
|
+
this.deps.logger.info(
|
|
5243
|
+
`session ${this.sessionId}: ${this.driver.displayName} exited while idle`,
|
|
5244
|
+
{ code, signal }
|
|
5245
|
+
);
|
|
5246
|
+
}
|
|
3766
5247
|
return;
|
|
3767
5248
|
}
|
|
3768
5249
|
if (this.interruptRequested) {
|
|
@@ -3774,46 +5255,25 @@ ${text}`;
|
|
|
3774
5255
|
400
|
|
3775
5256
|
);
|
|
3776
5257
|
const how = signal ? `was killed (${signal})` : `exited with code ${code}`;
|
|
3777
|
-
const hint = this.sawResultSinceSpawn ? "" : startupHint(this.stderrTail);
|
|
3778
|
-
if (!this.sawResultSinceSpawn && looksLikeSignInFailure(this.stderrTail)) {
|
|
3779
|
-
this.deps.
|
|
5258
|
+
const hint = this.sawResultSinceSpawn ? "" : this.driver.startupHint(this.stderrTail);
|
|
5259
|
+
if (!this.sawResultSinceSpawn && this.driver.looksLikeSignInFailure(this.stderrTail)) {
|
|
5260
|
+
this.deps.onAgentSignIn?.(false);
|
|
3780
5261
|
}
|
|
3781
5262
|
this.emit({
|
|
3782
5263
|
type: "error",
|
|
3783
|
-
message:
|
|
5264
|
+
message: `${this.driver.displayName} ${how} in the middle of a turn.${hint}${tail ? ` ${tail}` : ""}`,
|
|
3784
5265
|
retryable: true
|
|
3785
5266
|
});
|
|
3786
5267
|
this.record.turnActive = false;
|
|
3787
5268
|
await this.deps.store.save(this.record);
|
|
3788
5269
|
this.emit({ type: "result", status: "failed", text: null });
|
|
3789
|
-
this.deps.logger.warn(`session ${this.sessionId}:
|
|
5270
|
+
this.deps.logger.warn(`session ${this.sessionId}: ${this.driver.displayName} ${how}`);
|
|
3790
5271
|
} finally {
|
|
5272
|
+
if (reason !== "shutdown" && reason !== "close") this.scheduleQueuedTurns();
|
|
3791
5273
|
for (const w of waiters) w();
|
|
3792
5274
|
}
|
|
3793
5275
|
}
|
|
3794
5276
|
};
|
|
3795
|
-
function turnErrorMessage(turn) {
|
|
3796
|
-
switch (turn.subtype) {
|
|
3797
|
-
case "error_max_turns":
|
|
3798
|
-
return "Claude Code stopped: it reached its maximum number of turns.";
|
|
3799
|
-
case "error_max_budget_usd":
|
|
3800
|
-
return "Claude Code stopped: it reached its spending limit.";
|
|
3801
|
-
default:
|
|
3802
|
-
if (turnFailedToSignIn(turn)) {
|
|
3803
|
-
return `Claude Code could not sign in to Claude (${turn.text.slice(0, 200)}). ${signInFix()} Then send a message here to try again.`;
|
|
3804
|
-
}
|
|
3805
|
-
return turn.text ? `Claude Code reported an error: ${turn.text.slice(0, 500)}` : `Claude Code ended the turn with an error (${turn.subtype ?? "unknown"}).`;
|
|
3806
|
-
}
|
|
3807
|
-
}
|
|
3808
|
-
function startupHint(stderr) {
|
|
3809
|
-
if (looksLikeSignInFailure(stderr)) {
|
|
3810
|
-
return ` Claude Code does not seem to be signed in on the runner\u2019s computer. ${signInFix()}`;
|
|
3811
|
-
}
|
|
3812
|
-
if (/No conversation found|session.*not found/i.test(stderr)) {
|
|
3813
|
-
return " The Claude Code conversation to resume was not found on this computer.";
|
|
3814
|
-
}
|
|
3815
|
-
return "";
|
|
3816
|
-
}
|
|
3817
5277
|
async function raceTimeout(done, ms) {
|
|
3818
5278
|
let timer;
|
|
3819
5279
|
const timeout = new Promise((resolve2) => {
|
|
@@ -3956,7 +5416,18 @@ var SessionManager = class {
|
|
|
3956
5416
|
if (cmd.repository && !parseRepoUrl(cmd.repository.url)) {
|
|
3957
5417
|
return { ok: false, error: repositoryUrlError(cmd.repository.url) };
|
|
3958
5418
|
}
|
|
3959
|
-
|
|
5419
|
+
const driver = this.driverFor(cmd.agent);
|
|
5420
|
+
driver.validateModel(cmd.model);
|
|
5421
|
+
const problem = await this.opts.agentProblem?.(driver);
|
|
5422
|
+
if (problem) {
|
|
5423
|
+
return {
|
|
5424
|
+
ok: false,
|
|
5425
|
+
error: `${driver.displayName} cannot run on this runner right now: ${problem}`
|
|
5426
|
+
};
|
|
5427
|
+
}
|
|
5428
|
+
if (this.sessions.has(cmd.sessionId)) return { ok: true };
|
|
5429
|
+
const checking = this.starting.get(cmd.sessionId);
|
|
5430
|
+
if (checking) return checking;
|
|
3960
5431
|
const max = this.opts.config.maxSessions;
|
|
3961
5432
|
if (this.liveCount() >= max) {
|
|
3962
5433
|
await this.stopOldestIdle(cmd.sessionId);
|
|
@@ -3984,7 +5455,13 @@ var SessionManager = class {
|
|
|
3984
5455
|
repo: cmd.repository?.url,
|
|
3985
5456
|
branch: cmd.repository?.workBranch
|
|
3986
5457
|
});
|
|
3987
|
-
|
|
5458
|
+
const driver = this.driverFor(cmd.agent);
|
|
5459
|
+
await this.opts.resolveAgent(driver);
|
|
5460
|
+
if (!driver.control && (cmd.relayPermissionRequests || cmd.reportToolDenials)) {
|
|
5461
|
+
this.opts.logger.info(
|
|
5462
|
+
`session ${cmd.sessionId}: ${driver.displayName} does not support relaying permission requests or reporting tool denials; its sandbox decides instead`
|
|
5463
|
+
);
|
|
5464
|
+
}
|
|
3988
5465
|
const resume = cmd.resume ?? null;
|
|
3989
5466
|
if (resume) {
|
|
3990
5467
|
for (const other of [...this.sessions.values()]) {
|
|
@@ -3994,7 +5471,7 @@ var SessionManager = class {
|
|
|
3994
5471
|
}
|
|
3995
5472
|
await Promise.allSettled([...this.closing.values()]);
|
|
3996
5473
|
this.opts.logger.info(`session ${cmd.sessionId}: continuing run ${cmd.runId}`, {
|
|
3997
|
-
resume: resume.claudeSessionId ? "conversation" : "fresh"
|
|
5474
|
+
resume: resume.conversationId ?? resume.claudeSessionId ? "conversation" : "fresh"
|
|
3998
5475
|
});
|
|
3999
5476
|
}
|
|
4000
5477
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
@@ -4008,7 +5485,8 @@ var SessionManager = class {
|
|
|
4008
5485
|
workBranch: null,
|
|
4009
5486
|
baseRef: null,
|
|
4010
5487
|
baseSha: null,
|
|
4011
|
-
|
|
5488
|
+
...driver.kind !== DEFAULT_AGENT_KIND ? { agentKind: driver.kind } : {},
|
|
5489
|
+
conversationId: null,
|
|
4012
5490
|
turnActive: false,
|
|
4013
5491
|
...cmd.relayPermissionRequests === true ? { relayPermissionRequests: true } : {},
|
|
4014
5492
|
...alwaysAllowTools(cmd).length ? { alwaysAllowedTools: alwaysAllowTools(cmd) } : {},
|
|
@@ -4057,13 +5535,17 @@ var SessionManager = class {
|
|
|
4057
5535
|
resume ? safeWorktreeKey(resume.worktreeKey, cmd.sessionId) : cmd.sessionId
|
|
4058
5536
|
);
|
|
4059
5537
|
await mkdir6(record.cwd, { recursive: true });
|
|
5538
|
+
if (cmd.reviewImages === true && this.opts.reviewImageUploader) {
|
|
5539
|
+
record.reviewImages = true;
|
|
5540
|
+
await mkdir6(join11(record.cwd, EVIDENCE_DIR), { recursive: true });
|
|
5541
|
+
}
|
|
4060
5542
|
const deliverable = resume?.deliverable;
|
|
4061
5543
|
if (typeof deliverable === "string" && deliverable.trim()) {
|
|
4062
|
-
await writeFile4(
|
|
5544
|
+
await writeFile4(join11(record.cwd, RUNNER_DELIVERABLE_FILE), deliverable, "utf8");
|
|
4063
5545
|
}
|
|
4064
5546
|
}
|
|
4065
5547
|
if (resume) {
|
|
4066
|
-
record.
|
|
5548
|
+
record.conversationId = (resume.conversationId ?? resume.claudeSessionId)?.trim() || null;
|
|
4067
5549
|
record.freshPreface = continuationPreface(cmd);
|
|
4068
5550
|
}
|
|
4069
5551
|
await this.store.save(record);
|
|
@@ -4295,6 +5777,10 @@ var SessionManager = class {
|
|
|
4295
5777
|
await Promise.all(sessions.map((s) => s.outbox.flush(flushMs)));
|
|
4296
5778
|
await Promise.all(sessions.map((s) => s.outbox.stop()));
|
|
4297
5779
|
}
|
|
5780
|
+
/** The agent a session of this kind runs (the test override, else the registry's). */
|
|
5781
|
+
driverFor(kind) {
|
|
5782
|
+
return this.opts.driver ?? agentDriver(kind);
|
|
5783
|
+
}
|
|
4298
5784
|
async openSession(record) {
|
|
4299
5785
|
const outbox = await SessionOutbox.open({
|
|
4300
5786
|
sessionId: record.sessionId,
|
|
@@ -4308,20 +5794,28 @@ var SessionManager = class {
|
|
|
4308
5794
|
void this.close(record.sessionId);
|
|
4309
5795
|
}
|
|
4310
5796
|
});
|
|
5797
|
+
const driver = this.driverFor(record.agentKind);
|
|
4311
5798
|
return new AgentSession(record, {
|
|
4312
5799
|
store: this.store,
|
|
4313
5800
|
outbox,
|
|
4314
5801
|
logger: this.opts.logger,
|
|
4315
|
-
|
|
5802
|
+
driver,
|
|
5803
|
+
resolveAgent: () => this.opts.resolveAgent(driver),
|
|
4316
5804
|
permissionMode: this.opts.config.permissionMode,
|
|
4317
5805
|
allowedTools: this.opts.config.allowedTools,
|
|
4318
5806
|
disallowedTools: this.opts.config.disallowedTools ?? [],
|
|
4319
5807
|
loadProjectSettings: this.opts.config.loadProjectSettings ?? false,
|
|
5808
|
+
agentConfig: {
|
|
5809
|
+
codexSandbox: this.opts.config.codexSandbox ?? "workspace-write",
|
|
5810
|
+
codexNetworkAccess: this.opts.config.codexNetworkAccess === true,
|
|
5811
|
+
cursorForce: this.opts.config.cursorForce === true
|
|
5812
|
+
},
|
|
4320
5813
|
interruptGraceMs: this.opts.interruptGraceMs,
|
|
4321
|
-
|
|
5814
|
+
onAgentSignIn: this.opts.onAgentSignIn ? (ok) => this.opts.onAgentSignIn(ok, driver.kind) : void 0,
|
|
4322
5815
|
openPullRequest: this.opts.openPullRequest,
|
|
4323
5816
|
permissionTimeoutMs: this.opts.permissionTimeoutMs,
|
|
4324
5817
|
savedRules: async (url) => this.opts.grants ? await this.opts.grants.rulesFor(url) : [],
|
|
5818
|
+
reviewImageUploader: this.opts.reviewImageUploader,
|
|
4325
5819
|
inheritedRules: this.opts.inherited ? (url) => this.opts.inherited.rulesFor(url) : void 0
|
|
4326
5820
|
});
|
|
4327
5821
|
}
|
|
@@ -4384,10 +5878,12 @@ var RunnerDaemon = class {
|
|
|
4384
5878
|
config: opts.config,
|
|
4385
5879
|
poster: this.api,
|
|
4386
5880
|
logger: opts.logger,
|
|
4387
|
-
|
|
5881
|
+
resolveAgent: (driver) => this.resolveAgent(driver),
|
|
4388
5882
|
onUnauthorized: (err) => this.unauthorized(err),
|
|
4389
|
-
|
|
5883
|
+
onAgentSignIn: (ok, kind) => this.agentSignIn(ok, kind),
|
|
5884
|
+
agentProblem: (driver) => this.agentProblem(driver),
|
|
4390
5885
|
grants: this.grants,
|
|
5886
|
+
reviewImageUploader: this.api,
|
|
4391
5887
|
// What the person already allows in their own Claude Code for a repository.
|
|
4392
5888
|
inherited: opts.config.inheritClaudeCodePermissions ? new ClaudeCodeRules({
|
|
4393
5889
|
exclude: [opts.config.reposDir, opts.config.worktreesDir]
|
|
@@ -4401,12 +5897,17 @@ var RunnerDaemon = class {
|
|
|
4401
5897
|
exitReason = "stopped";
|
|
4402
5898
|
agentInfo = null;
|
|
4403
5899
|
/**
|
|
4404
|
-
*
|
|
4405
|
-
* is signed in (an expired sign-in it
|
|
4406
|
-
* later turn finishes.
|
|
5900
|
+
* The agents (`AgentDriver.kind`) a turn could not sign in. Claude Code's `claude auth
|
|
5901
|
+
* status` (or `codex login status`) may still say it is signed in (an expired sign-in it
|
|
5902
|
+
* cannot refresh), so this outranks the probe until a later turn finishes.
|
|
4407
5903
|
*/
|
|
4408
|
-
signInFailed =
|
|
4409
|
-
|
|
5904
|
+
signInFailed = /* @__PURE__ */ new Set();
|
|
5905
|
+
/** Each agent's binary and features, by `AgentDriver.kind`, trusted for the probe's TTL. */
|
|
5906
|
+
agentInstalls = /* @__PURE__ */ new Map();
|
|
5907
|
+
/** The agent the heartbeat's `claude*` fields report on: the default kind's. */
|
|
5908
|
+
driver = agentDriver();
|
|
5909
|
+
/** The optional agents (Codex, Cursor), each reported in its own heartbeat fields. */
|
|
5910
|
+
optional = OPTIONAL_AGENTS;
|
|
4410
5911
|
inFlight = /* @__PURE__ */ new Set();
|
|
4411
5912
|
/** The tail of each session's command queue (see `inSessionOrder`); never rejects. */
|
|
4412
5913
|
sessionQueues = /* @__PURE__ */ new Map();
|
|
@@ -4459,44 +5960,108 @@ var RunnerDaemon = class {
|
|
|
4459
5960
|
);
|
|
4460
5961
|
this.stop();
|
|
4461
5962
|
}
|
|
4462
|
-
async
|
|
5963
|
+
async resolveAgent(driver) {
|
|
4463
5964
|
const ttl = this.opts.agentProbeTtlMs ?? 5 * 6e4;
|
|
4464
|
-
|
|
4465
|
-
|
|
4466
|
-
|
|
4467
|
-
|
|
4468
|
-
|
|
4469
|
-
|
|
4470
|
-
|
|
4471
|
-
|
|
4472
|
-
|
|
5965
|
+
const cached = this.agentInstalls.get(driver.kind);
|
|
5966
|
+
if (cached && Date.now() - cached.at < ttl) return cached;
|
|
5967
|
+
const bin = await driver.resolveBinary();
|
|
5968
|
+
if (!bin) throw new Error(driver.notInstalledMessage());
|
|
5969
|
+
const install = { bin, features: await driver.readFeatures(bin), at: Date.now() };
|
|
5970
|
+
this.agentInstalls.set(driver.kind, install);
|
|
5971
|
+
return install;
|
|
5972
|
+
}
|
|
5973
|
+
/** Claude Code, for planning requests (answered by Claude Code only; see `completion.ts`). */
|
|
5974
|
+
async resolveClaude() {
|
|
5975
|
+
const { bin, features } = await this.resolveAgent(claudeCodeDriver);
|
|
5976
|
+
return { bin, features };
|
|
4473
5977
|
}
|
|
4474
5978
|
async agent() {
|
|
4475
5979
|
const ttl = this.opts.agentProbeTtlMs ?? 5 * 6e4;
|
|
4476
5980
|
if (!this.agentInfo || Date.now() - this.agentInfo.at > ttl) {
|
|
4477
|
-
const
|
|
5981
|
+
const [claude, ...others] = await Promise.all([
|
|
5982
|
+
this.driver.probe(),
|
|
5983
|
+
...this.optional.map((a) => a.driver.probe())
|
|
5984
|
+
]);
|
|
5985
|
+
let info2 = {
|
|
5986
|
+
claudeVersion: claude.claudeVersion,
|
|
5987
|
+
claudeReady: claude.claudeReady,
|
|
5988
|
+
claudeProblem: claude.claudeProblem ?? null
|
|
5989
|
+
};
|
|
5990
|
+
this.optional.forEach((a, i) => {
|
|
5991
|
+
info2 = { ...withAgentFields(info2, a, readAgentFields(others[i], a)), [a.runs]: true };
|
|
5992
|
+
});
|
|
4478
5993
|
if (info2.claudeProblem && info2.claudeProblem !== this.agentInfo?.info.claudeProblem) {
|
|
4479
5994
|
this.opts.logger.warn(info2.claudeProblem);
|
|
4480
5995
|
}
|
|
5996
|
+
for (const a of this.optional) {
|
|
5997
|
+
const now = readAgentFields(info2, a);
|
|
5998
|
+
const before = this.agentInfo ? readAgentFields(this.agentInfo.info, a) : null;
|
|
5999
|
+
if (now.version && now.problem && now.problem !== before?.problem) {
|
|
6000
|
+
this.opts.logger.warn(now.problem);
|
|
6001
|
+
}
|
|
6002
|
+
}
|
|
4481
6003
|
this.agentInfo = { info: info2, at: Date.now() };
|
|
4482
6004
|
}
|
|
4483
|
-
|
|
4484
|
-
if (
|
|
4485
|
-
|
|
4486
|
-
|
|
4487
|
-
|
|
4488
|
-
|
|
4489
|
-
|
|
6005
|
+
let { info } = this.agentInfo;
|
|
6006
|
+
if (this.signInFailed.has(this.driver.kind) && info.claudeVersion && info.claudeReady !== false) {
|
|
6007
|
+
info = {
|
|
6008
|
+
...info,
|
|
6009
|
+
claudeReady: false,
|
|
6010
|
+
claudeProblem: `A run could not sign in to Claude. ${this.driver.signInFix()}`
|
|
6011
|
+
};
|
|
6012
|
+
}
|
|
6013
|
+
for (const a of this.optional) {
|
|
6014
|
+
const now = readAgentFields(info, a);
|
|
6015
|
+
if (this.signInFailed.has(a.driver.kind) && now.version && now.ready !== false) {
|
|
6016
|
+
info = withAgentFields(info, a, {
|
|
6017
|
+
...now,
|
|
6018
|
+
ready: false,
|
|
6019
|
+
problem: `A run could not sign in to ${a.driver.displayName}. ${a.driver.signInFix()}`
|
|
6020
|
+
});
|
|
6021
|
+
}
|
|
6022
|
+
}
|
|
6023
|
+
return info;
|
|
4490
6024
|
}
|
|
4491
|
-
|
|
4492
|
-
|
|
4493
|
-
|
|
6025
|
+
/**
|
|
6026
|
+
* Why a session of this agent would not run now (see `SessionManagerOptions.agentProblem`).
|
|
6027
|
+
* Asked of the agent itself, not of the heartbeat's cached or overridden view: a person who
|
|
6028
|
+
* just installed it or signed in is not refused for a probe taken before, nor for a turn
|
|
6029
|
+
* that failed to sign in earlier (a new turn that fails says so in its own error).
|
|
6030
|
+
*/
|
|
6031
|
+
async agentProblem(driver) {
|
|
6032
|
+
const agent = this.optional.find((a) => a.driver.kind === driver.kind);
|
|
6033
|
+
if (!agent) return null;
|
|
6034
|
+
const fresh = readAgentFields(await agent.driver.probe(), agent);
|
|
6035
|
+
if (this.agentInfo) this.agentInfo.info = withAgentFields(this.agentInfo.info, agent, fresh);
|
|
6036
|
+
if (fresh.ready === true) this.signInFailed.delete(agent.driver.kind);
|
|
6037
|
+
if (fresh.ready !== false) return null;
|
|
6038
|
+
return fresh.problem || `${agent.driver.displayName} is not ready. ${agent.driver.signInFix()}`;
|
|
6039
|
+
}
|
|
6040
|
+
agentSignIn(ok, kind = this.driver.kind) {
|
|
6041
|
+
const cached = this.agentInfo?.info;
|
|
6042
|
+
const agent = this.optional.find((a) => a.driver.kind === kind);
|
|
6043
|
+
if (ok && cached) {
|
|
6044
|
+
if (kind === this.driver.kind && cached.claudeReady === false && cached.claudeVersion) {
|
|
6045
|
+
this.agentInfo.info = { ...cached, claudeReady: true, claudeProblem: null };
|
|
6046
|
+
} else if (agent) {
|
|
6047
|
+
const now = readAgentFields(cached, agent);
|
|
6048
|
+
if (now.ready === false && now.version) {
|
|
6049
|
+
this.agentInfo.info = withAgentFields(cached, agent, {
|
|
6050
|
+
...now,
|
|
6051
|
+
ready: true,
|
|
6052
|
+
problem: null
|
|
6053
|
+
});
|
|
6054
|
+
}
|
|
6055
|
+
}
|
|
4494
6056
|
}
|
|
4495
|
-
if (ok === !this.signInFailed) return;
|
|
4496
|
-
|
|
4497
|
-
|
|
4498
|
-
|
|
6057
|
+
if (ok === !this.signInFailed.has(kind)) return;
|
|
6058
|
+
if (ok) {
|
|
6059
|
+
this.signInFailed.delete(kind);
|
|
6060
|
+
return;
|
|
4499
6061
|
}
|
|
6062
|
+
this.signInFailed.add(kind);
|
|
6063
|
+
const driver = agent?.driver ?? this.driver;
|
|
6064
|
+
this.opts.logger.warn(`${driver.displayName} could not sign in. ${driver.signInFix()}`);
|
|
4500
6065
|
}
|
|
4501
6066
|
/**
|
|
4502
6067
|
* The runner's one heartbeat, for all of its sessions (each session's state rides in it).
|
|
@@ -4524,6 +6089,8 @@ var RunnerDaemon = class {
|
|
|
4524
6089
|
relaysPermissionRequests: true,
|
|
4525
6090
|
// And reports denied tool calls, takes grants on them, and keeps saved rules.
|
|
4526
6091
|
grantsToolPermissions: true,
|
|
6092
|
+
// And attaches a design proposal's rendered screens to its task (`reviewImages`).
|
|
6093
|
+
uploadsReviewImages: true,
|
|
4527
6094
|
// And keeps a continued non-code run's deliverable whole (`resume.deliverable`).
|
|
4528
6095
|
receivesDeliverable: true
|
|
4529
6096
|
},
|
|
@@ -4634,7 +6201,7 @@ var RunnerDaemon = class {
|
|
|
4634
6201
|
if (this.droppedSessionIds.has(id)) return;
|
|
4635
6202
|
this.droppedSessionIds.add(id);
|
|
4636
6203
|
this.opts.logger.warn(
|
|
4637
|
-
`session ${id}: not a Discovery Tree session id, so it is left out of the heartbeat (its state is in ${
|
|
6204
|
+
`session ${id}: not a Discovery Tree session id, so it is left out of the heartbeat (its state is in ${join12(this.opts.config.stateDir, "sessions", id)})`
|
|
4638
6205
|
);
|
|
4639
6206
|
});
|
|
4640
6207
|
}
|
|
@@ -4740,8 +6307,8 @@ var RunnerDaemon = class {
|
|
|
4740
6307
|
error: result.error
|
|
4741
6308
|
});
|
|
4742
6309
|
}
|
|
4743
|
-
if (result.signInFailed) this.
|
|
4744
|
-
else if (result.ok) this.
|
|
6310
|
+
if (result.signInFailed) this.agentSignIn(false);
|
|
6311
|
+
else if (result.ok) this.agentSignIn(true);
|
|
4745
6312
|
for (let attempt = 0; attempt < 5; attempt++) {
|
|
4746
6313
|
try {
|
|
4747
6314
|
await this.api.postCompletion(req.id, result);
|
|
@@ -4780,6 +6347,37 @@ var RunnerDaemon = class {
|
|
|
4780
6347
|
});
|
|
4781
6348
|
}
|
|
4782
6349
|
};
|
|
6350
|
+
var OPTIONAL_AGENTS = [
|
|
6351
|
+
{
|
|
6352
|
+
driver: codexDriver,
|
|
6353
|
+
version: "codexVersion",
|
|
6354
|
+
ready: "codexReady",
|
|
6355
|
+
problem: "codexProblem",
|
|
6356
|
+
runs: "runsCodex"
|
|
6357
|
+
},
|
|
6358
|
+
{
|
|
6359
|
+
driver: cursorDriver,
|
|
6360
|
+
version: "cursorVersion",
|
|
6361
|
+
ready: "cursorReady",
|
|
6362
|
+
problem: "cursorProblem",
|
|
6363
|
+
runs: "runsCursor"
|
|
6364
|
+
}
|
|
6365
|
+
];
|
|
6366
|
+
function readAgentFields(info, agent) {
|
|
6367
|
+
return {
|
|
6368
|
+
version: info[agent.version] ?? null,
|
|
6369
|
+
ready: info[agent.ready] ?? null,
|
|
6370
|
+
problem: info[agent.problem] ?? null
|
|
6371
|
+
};
|
|
6372
|
+
}
|
|
6373
|
+
function withAgentFields(info, agent, fields) {
|
|
6374
|
+
return {
|
|
6375
|
+
...info,
|
|
6376
|
+
[agent.version]: fields.version,
|
|
6377
|
+
[agent.ready]: fields.ready,
|
|
6378
|
+
[agent.problem]: fields.problem
|
|
6379
|
+
};
|
|
6380
|
+
}
|
|
4783
6381
|
|
|
4784
6382
|
// src/doctor.ts
|
|
4785
6383
|
async function runDoctor(env = process.env) {
|
|
@@ -4814,39 +6412,7 @@ async function runDoctor(env = process.env) {
|
|
|
4814
6412
|
detail: "not installed (no `gh` on PATH): pull requests cannot be opened as you; see https://cli.github.com"
|
|
4815
6413
|
});
|
|
4816
6414
|
}
|
|
4817
|
-
const
|
|
4818
|
-
if (!bin) {
|
|
4819
|
-
checks.push({
|
|
4820
|
-
name: "Claude Code",
|
|
4821
|
-
level: "fail",
|
|
4822
|
-
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)"
|
|
4823
|
-
});
|
|
4824
|
-
} else {
|
|
4825
|
-
const version = await claudeVersion(bin);
|
|
4826
|
-
checks.push({
|
|
4827
|
-
name: "Claude Code",
|
|
4828
|
-
level: version ? "ok" : "fail",
|
|
4829
|
-
detail: version ? `${version} (${bin})` : `${bin} --version failed`
|
|
4830
|
-
});
|
|
4831
|
-
if (version) {
|
|
4832
|
-
const auth = await claudeAuthStatus(bin);
|
|
4833
|
-
checks.push(
|
|
4834
|
-
auth.loggedIn === true ? {
|
|
4835
|
-
name: "Claude sign-in",
|
|
4836
|
-
level: "ok",
|
|
4837
|
-
detail: `signed in${auth.authMethod ? ` (${auth.authMethod})` : ""}`
|
|
4838
|
-
} : auth.loggedIn === false ? {
|
|
4839
|
-
name: "Claude sign-in",
|
|
4840
|
-
level: "fail",
|
|
4841
|
-
detail: "not signed in: run `claude` and sign in with your Claude account"
|
|
4842
|
-
} : {
|
|
4843
|
-
name: "Claude sign-in",
|
|
4844
|
-
level: "warn",
|
|
4845
|
-
detail: "could not tell (this Claude Code has no `claude auth status`); update Claude Code"
|
|
4846
|
-
}
|
|
4847
|
-
);
|
|
4848
|
-
}
|
|
4849
|
-
}
|
|
6415
|
+
for (const kind of agentDriverKinds()) checks.push(...await agentDriver(kind).doctor(env));
|
|
4850
6416
|
if (env.ANTHROPIC_API_KEY) {
|
|
4851
6417
|
checks.push({
|
|
4852
6418
|
name: "ANTHROPIC_API_KEY",
|
|
@@ -4863,9 +6429,9 @@ function formatChecks(checks) {
|
|
|
4863
6429
|
|
|
4864
6430
|
// src/lock.ts
|
|
4865
6431
|
import { mkdir as mkdir7, open, readFile as readFile5, rm as rm7 } from "node:fs/promises";
|
|
4866
|
-
import { join as
|
|
6432
|
+
import { join as join13 } from "node:path";
|
|
4867
6433
|
function lockFile(stateDir) {
|
|
4868
|
-
return
|
|
6434
|
+
return join13(stateDir, "daemon.pid");
|
|
4869
6435
|
}
|
|
4870
6436
|
function pidAlive(pid) {
|
|
4871
6437
|
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
@@ -4903,8 +6469,8 @@ async function acquireDaemonLock(stateDir, pid = process.pid) {
|
|
|
4903
6469
|
lock: {
|
|
4904
6470
|
file,
|
|
4905
6471
|
async release() {
|
|
4906
|
-
const
|
|
4907
|
-
if (Number.parseInt(
|
|
6472
|
+
const current2 = await readFile5(file, "utf8").catch(() => "");
|
|
6473
|
+
if (Number.parseInt(current2.trim(), 10) === pid) await rm7(file, { force: true });
|
|
4908
6474
|
}
|
|
4909
6475
|
}
|
|
4910
6476
|
};
|
|
@@ -4921,7 +6487,7 @@ async function acquireDaemonLock(stateDir, pid = process.pid) {
|
|
|
4921
6487
|
}
|
|
4922
6488
|
|
|
4923
6489
|
// src/pairing.ts
|
|
4924
|
-
import { spawn as
|
|
6490
|
+
import { spawn as spawn5 } from "node:child_process";
|
|
4925
6491
|
async function pair(api, opts) {
|
|
4926
6492
|
const start2 = await api.startPairing({ name: opts.name, platform: RUNNER_PLATFORM });
|
|
4927
6493
|
opts.ui.showCode(start2.userCode, start2.verificationUrl, start2.expiresInSeconds);
|
|
@@ -4985,7 +6551,7 @@ function openUrl(url) {
|
|
|
4985
6551
|
if (!/^https?:\/\//i.test(url)) return;
|
|
4986
6552
|
const [cmd, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", url]] : ["xdg-open", [url]];
|
|
4987
6553
|
try {
|
|
4988
|
-
const child =
|
|
6554
|
+
const child = spawn5(cmd, args, { stdio: "ignore", detached: true, windowsHide: true });
|
|
4989
6555
|
child.on("error", () => void 0);
|
|
4990
6556
|
child.unref();
|
|
4991
6557
|
} catch {
|
|
@@ -5061,7 +6627,7 @@ async function main(argv) {
|
|
|
5061
6627
|
case "status":
|
|
5062
6628
|
return status();
|
|
5063
6629
|
case "doctor":
|
|
5064
|
-
return
|
|
6630
|
+
return doctor4();
|
|
5065
6631
|
case "logout":
|
|
5066
6632
|
return logout();
|
|
5067
6633
|
default:
|
|
@@ -5106,7 +6672,7 @@ async function login(server, name, openBrowser, yes) {
|
|
|
5106
6672
|
isTTY: process.stdin.isTTY === true,
|
|
5107
6673
|
print: (line) => console.log(line),
|
|
5108
6674
|
async ask(question) {
|
|
5109
|
-
const rl =
|
|
6675
|
+
const rl = createInterface3({ input: process.stdin, output: process.stdout });
|
|
5110
6676
|
try {
|
|
5111
6677
|
return await rl.question(question);
|
|
5112
6678
|
} finally {
|
|
@@ -5149,12 +6715,33 @@ async function start(opts) {
|
|
|
5149
6715
|
"ANTHROPIC_API_KEY is set: Claude Code will bill that API key, not your Claude subscription. Unset it unless that is what you want."
|
|
5150
6716
|
);
|
|
5151
6717
|
}
|
|
6718
|
+
const codexKey = codexKeyVariable(process.env);
|
|
6719
|
+
if (codexKey) {
|
|
6720
|
+
logger.warn(
|
|
6721
|
+
`${codexKey} is set: Codex runs may bill that API key, not your ChatGPT plan. Unset it unless that is what you want.`
|
|
6722
|
+
);
|
|
6723
|
+
}
|
|
6724
|
+
if (config.codexSandbox === "danger-full-access") {
|
|
6725
|
+
logger.warn(
|
|
6726
|
+
'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.'
|
|
6727
|
+
);
|
|
6728
|
+
}
|
|
6729
|
+
if (cursorKeyVariable(process.env)) {
|
|
6730
|
+
logger.warn(
|
|
6731
|
+
"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."
|
|
6732
|
+
);
|
|
6733
|
+
}
|
|
6734
|
+
if (config.cursorForce) {
|
|
6735
|
+
logger.warn(
|
|
6736
|
+
'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.'
|
|
6737
|
+
);
|
|
6738
|
+
}
|
|
5152
6739
|
if (config.permissionMode === "bypassPermissions") {
|
|
5153
6740
|
logger.warn(
|
|
5154
6741
|
"!!! permissionMode is bypassPermissions: Claude Code will run ANY command and edit ANY file on this computer without asking. !!!"
|
|
5155
6742
|
);
|
|
5156
6743
|
logger.warn(
|
|
5157
|
-
'!!! Only use this on a disposable machine or container. Remove "permissionMode" from the config to go back to
|
|
6744
|
+
'!!! Only use this on a disposable machine or container. Remove "permissionMode" from the config to go back to the default (auto). !!!'
|
|
5158
6745
|
);
|
|
5159
6746
|
}
|
|
5160
6747
|
const locked = await acquireDaemonLock(config.stateDir);
|
|
@@ -5164,6 +6751,15 @@ async function start(opts) {
|
|
|
5164
6751
|
);
|
|
5165
6752
|
return 1;
|
|
5166
6753
|
}
|
|
6754
|
+
if (process.platform === "win32") {
|
|
6755
|
+
void startJobHelper().then((ok) => {
|
|
6756
|
+
if (!ok) {
|
|
6757
|
+
logger.warn(
|
|
6758
|
+
"Could not set up Windows job objects (PowerShell unavailable?); processes a run leaves behind are found by parent process id instead."
|
|
6759
|
+
);
|
|
6760
|
+
}
|
|
6761
|
+
});
|
|
6762
|
+
}
|
|
5167
6763
|
const daemon = new RunnerDaemon({ config, logger });
|
|
5168
6764
|
let signals = 0;
|
|
5169
6765
|
const onSignal = (sig) => {
|
|
@@ -5218,7 +6814,7 @@ async function status() {
|
|
|
5218
6814
|
}
|
|
5219
6815
|
console.log("Daemon: not running");
|
|
5220
6816
|
try {
|
|
5221
|
-
const agent = await
|
|
6817
|
+
const agent = await agentDriver().probe();
|
|
5222
6818
|
const res = await api.heartbeat({
|
|
5223
6819
|
protocolVersion: RUNNER_PROTOCOL_VERSION,
|
|
5224
6820
|
runnerVersion: RUNNER_VERSION,
|
|
@@ -5248,7 +6844,7 @@ async function status() {
|
|
|
5248
6844
|
return 1;
|
|
5249
6845
|
}
|
|
5250
6846
|
}
|
|
5251
|
-
async function
|
|
6847
|
+
async function doctor4() {
|
|
5252
6848
|
const checks = await runDoctor();
|
|
5253
6849
|
console.log(formatChecks(checks));
|
|
5254
6850
|
const failed = checks.some((c) => c.level === "fail");
|