@discovery-tree/runner 0.1.5 → 0.1.7
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 +22 -2
- package/dist/cli.js +1051 -774
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -5,6 +5,19 @@ import { hostname } from "node:os";
|
|
|
5
5
|
import { createInterface as createInterface2 } from "node:readline/promises";
|
|
6
6
|
import { parseArgs } from "node:util";
|
|
7
7
|
|
|
8
|
+
// ../contracts/src/agent-config.ts
|
|
9
|
+
var KEYED_AGENT_PROVIDER_TYPES = [
|
|
10
|
+
"cursor_cloud",
|
|
11
|
+
"openai",
|
|
12
|
+
"anthropic",
|
|
13
|
+
"webhook"
|
|
14
|
+
];
|
|
15
|
+
var WORKSPACE_ONLY_KEY_PROVIDERS = ["voyage"];
|
|
16
|
+
var WORKSPACE_KEY_PROVIDER_TYPES = [
|
|
17
|
+
...KEYED_AGENT_PROVIDER_TYPES,
|
|
18
|
+
...WORKSPACE_ONLY_KEY_PROVIDERS
|
|
19
|
+
];
|
|
20
|
+
|
|
8
21
|
// ../contracts/src/ui-evidence.ts
|
|
9
22
|
var UI_EVIDENCE_EXPECTATION = [
|
|
10
23
|
"Visual evidence (required for user-visible changes): if your change alters anything a person sees or interacts with \u2014 a component, layout, styling, copy, empty state, or navigation \u2014 capture a screenshot of the change and embed it in the pull request description using markdown image syntax. Attach one image per state you changed, including before/after when the change modifies existing UI, and both themes when the product has light and dark.",
|
|
@@ -24,6 +37,10 @@ var DEFAULT_AGENT_SYSTEM_PROMPT = [
|
|
|
24
37
|
// ../contracts/src/agent-runs.ts
|
|
25
38
|
var AGENT_RUN_MAX_WALL_MS = 6 * 60 * 60 * 1e3;
|
|
26
39
|
var AGENT_RUN_ABANDONED_GRACE_MS = 30 * 60 * 1e3;
|
|
40
|
+
var AGENT_RUN_AUTO_RECOVER_MAX_MS = 5 * 6e4;
|
|
41
|
+
|
|
42
|
+
// ../contracts/src/agent-work.ts
|
|
43
|
+
var AGENT_WORK_IDLE_AFTER_MS = 24 * 60 * 60 * 1e3;
|
|
27
44
|
|
|
28
45
|
// ../contracts/src/agent-runner.ts
|
|
29
46
|
var RUNNER_PROTOCOL_VERSION = 1;
|
|
@@ -33,7 +50,7 @@ var RUNNER_EVENT_TEXT_MAX_LENGTH = 64e3;
|
|
|
33
50
|
var RUNNER_EVENTS_MAX_BODY_BYTES = 8 * 1024 * 1024;
|
|
34
51
|
|
|
35
52
|
// src/version.ts
|
|
36
|
-
var RUNNER_VERSION = true ? "0.1.
|
|
53
|
+
var RUNNER_VERSION = true ? "0.1.7" : "0.0.0-dev";
|
|
37
54
|
var RUNNER_PLATFORM = `${process.platform}-${process.arch}`;
|
|
38
55
|
|
|
39
56
|
// src/api.ts
|
|
@@ -143,6 +160,14 @@ var RunnerApi = class {
|
|
|
143
160
|
}
|
|
144
161
|
};
|
|
145
162
|
|
|
163
|
+
// src/claude.ts
|
|
164
|
+
import { join as join4 } from "node:path";
|
|
165
|
+
|
|
166
|
+
// src/evidence.ts
|
|
167
|
+
import { mkdir as mkdir2, mkdtemp, readdir, readFile, rename, rm as rm2, stat as stat2, writeFile } from "node:fs/promises";
|
|
168
|
+
import { tmpdir } from "node:os";
|
|
169
|
+
import { isAbsolute as isAbsolute2, join as join3 } from "node:path";
|
|
170
|
+
|
|
146
171
|
// src/exec.ts
|
|
147
172
|
import { spawn } from "node:child_process";
|
|
148
173
|
import { access, constants } from "node:fs/promises";
|
|
@@ -198,190 +223,691 @@ async function isExecutable(file) {
|
|
|
198
223
|
}
|
|
199
224
|
}
|
|
200
225
|
|
|
201
|
-
// src/
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
226
|
+
// src/git.ts
|
|
227
|
+
import { mkdir, rm, stat } from "node:fs/promises";
|
|
228
|
+
import { dirname, join as join2 } from "node:path";
|
|
229
|
+
|
|
230
|
+
// src/log.ts
|
|
231
|
+
function createLogger(opts = {}) {
|
|
232
|
+
const write = opts.write ?? ((line) => process.stdout.write(line + "\n"));
|
|
233
|
+
const emit = (level, msg, fields) => {
|
|
234
|
+
if (level === "debug" && !opts.verbose) return;
|
|
235
|
+
const safe = fields ? redactFields(fields) : void 0;
|
|
236
|
+
if (opts.json) {
|
|
237
|
+
write(JSON.stringify({ time: (/* @__PURE__ */ new Date()).toISOString(), level, msg, ...safe }));
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
const time = (/* @__PURE__ */ new Date()).toISOString().slice(11, 19);
|
|
241
|
+
const tag = level === "info" ? "" : ` ${level.toUpperCase()}`;
|
|
242
|
+
const extra = safe ? " " + Object.entries(safe).filter(([, v]) => v !== void 0 && v !== null && v !== "").map(([k, v]) => `${k}=${typeof v === "string" ? v : JSON.stringify(v)}`).join(" ") : "";
|
|
243
|
+
write(`${time}${tag} ${msg}${extra.trimEnd() === "" ? "" : extra}`);
|
|
244
|
+
};
|
|
245
|
+
return {
|
|
246
|
+
debug: (m, f) => emit("debug", m, f),
|
|
247
|
+
info: (m, f) => emit("info", m, f),
|
|
248
|
+
warn: (m, f) => emit("warn", m, f),
|
|
249
|
+
error: (m, f) => emit("error", m, f)
|
|
250
|
+
};
|
|
215
251
|
}
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
return {
|
|
222
|
-
loggedIn: parsed.loggedIn,
|
|
223
|
-
authMethod: typeof parsed.authMethod === "string" ? parsed.authMethod : null
|
|
224
|
-
};
|
|
225
|
-
} catch {
|
|
226
|
-
return { loggedIn: null, authMethod: null };
|
|
227
|
-
}
|
|
252
|
+
var SECRET_KEY = /token|secret|password|authorization/i;
|
|
253
|
+
function redactFields(fields) {
|
|
254
|
+
const out = {};
|
|
255
|
+
for (const [k, v] of Object.entries(fields)) out[k] = SECRET_KEY.test(k) ? "[redacted]" : v;
|
|
256
|
+
return out;
|
|
228
257
|
}
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
const res = await exec(bin, ["--help"], { timeoutMs: 15e3 });
|
|
232
|
-
return {
|
|
233
|
-
permissionPrompts: res.stdout.includes("--permission-prompts"),
|
|
234
|
-
settingSources: res.stdout.includes("--setting-sources")
|
|
235
|
-
};
|
|
236
|
-
} catch {
|
|
237
|
-
return { permissionPrompts: false, settingSources: false };
|
|
238
|
-
}
|
|
258
|
+
function scrubSecrets(text) {
|
|
259
|
+
return text.replace(/(https?:\/\/)[^/\s@]+@/gi, "$1***@").replace(/\bdtr_[A-Za-z0-9_-]+/g, "dtr_***").replace(/\b(gh[pousr]_[A-Za-z0-9]{10,})/g, "***");
|
|
239
260
|
}
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
}
|
|
249
|
-
const version = await claudeVersion(bin);
|
|
250
|
-
if (!version) {
|
|
251
|
-
return {
|
|
252
|
-
claudeVersion: null,
|
|
253
|
-
claudeReady: false,
|
|
254
|
-
claudeProblem: "`claude --version` failed; reinstall or update Claude Code."
|
|
255
|
-
};
|
|
256
|
-
}
|
|
257
|
-
const auth = await claudeAuthStatus(bin);
|
|
258
|
-
if (auth.loggedIn === false) {
|
|
259
|
-
return {
|
|
260
|
-
claudeVersion: version,
|
|
261
|
-
claudeReady: false,
|
|
262
|
-
claudeProblem: "Claude Code is not signed in. Run `claude` once on this computer and sign in."
|
|
263
|
-
};
|
|
261
|
+
|
|
262
|
+
// src/git.ts
|
|
263
|
+
var GitError = class extends Error {
|
|
264
|
+
constructor(args, result) {
|
|
265
|
+
super(gitErrorMessage(args, result));
|
|
266
|
+
this.args = args;
|
|
267
|
+
this.result = result;
|
|
268
|
+
this.name = "GitError";
|
|
264
269
|
}
|
|
265
|
-
|
|
270
|
+
};
|
|
271
|
+
function gitErrorMessage(args, result) {
|
|
272
|
+
const detail = (result.stderr || result.stdout).trim().split("\n").filter(Boolean).slice(-3).join(" ");
|
|
273
|
+
return scrubSecrets(`git ${args[0]} failed${detail ? `: ${detail}` : ""}`).slice(0, 500);
|
|
266
274
|
}
|
|
267
|
-
var
|
|
268
|
-
|
|
269
|
-
|
|
275
|
+
var gitEnv = () => ({
|
|
276
|
+
...process.env,
|
|
277
|
+
GIT_TERMINAL_PROMPT: "0",
|
|
278
|
+
GCM_INTERACTIVE: "never",
|
|
279
|
+
GIT_ASKPASS: process.env.GIT_ASKPASS ?? ""
|
|
280
|
+
});
|
|
281
|
+
async function git(cwd, args, timeoutMs = 10 * 6e4) {
|
|
282
|
+
const res = await exec("git", args, { cwd, env: gitEnv(), timeoutMs });
|
|
283
|
+
if (res.code !== 0) throw new GitError(args, res);
|
|
284
|
+
return res.stdout.trim();
|
|
270
285
|
}
|
|
271
|
-
function
|
|
272
|
-
|
|
286
|
+
async function gitOk(cwd, args) {
|
|
287
|
+
const res = await exec("git", args, { cwd, env: gitEnv(), timeoutMs: 6e4 });
|
|
288
|
+
return res.code === 0;
|
|
273
289
|
}
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
290
|
+
var REPOSITORY_HOST = "github.com";
|
|
291
|
+
function parseRepoUrl(url) {
|
|
292
|
+
try {
|
|
293
|
+
const u = new URL(url);
|
|
294
|
+
if (u.protocol !== "https:" || u.hostname.toLowerCase() !== REPOSITORY_HOST) return null;
|
|
295
|
+
if (u.port || u.username || u.password || u.search || u.hash) return null;
|
|
296
|
+
const parts = u.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/, "").split("/");
|
|
297
|
+
if (parts.length !== 2 || !parts[0] || !parts[1]) return null;
|
|
298
|
+
if (!/^[\w.-]+$/.test(parts[0]) || !/^[\w.-]+$/.test(parts[1])) return null;
|
|
299
|
+
if (parts.some((p) => p === "." || p === "..")) return null;
|
|
300
|
+
return { host: REPOSITORY_HOST, owner: parts[0], repo: parts[1] };
|
|
301
|
+
} catch {
|
|
302
|
+
return null;
|
|
277
303
|
}
|
|
278
|
-
return 'On the runner\u2019s computer, run `claude`, type `/login` and sign in again, and check that `claude -p "say ok"` answers.';
|
|
279
|
-
}
|
|
280
|
-
var MODEL_NAME = /^[A-Za-z0-9][\w.:@/[\]-]{0,199}$/;
|
|
281
|
-
function isValidModelName(model) {
|
|
282
|
-
return MODEL_NAME.test(model);
|
|
283
304
|
}
|
|
284
|
-
function
|
|
285
|
-
|
|
286
|
-
throw new Error(
|
|
287
|
-
`The model "${model.slice(0, 80)}" is not a valid Claude Code model name; the runner refused to start it.`
|
|
288
|
-
);
|
|
289
|
-
}
|
|
305
|
+
function repositoryUrlError(url) {
|
|
306
|
+
return `Repository URL ${scrubSecrets(url).slice(0, 200)} is not a https://github.com/<owner>/<repo> URL; this runner only works on GitHub repositories.`;
|
|
290
307
|
}
|
|
291
|
-
function
|
|
292
|
-
|
|
293
|
-
"-p",
|
|
294
|
-
"--input-format",
|
|
295
|
-
"stream-json",
|
|
296
|
-
"--output-format",
|
|
297
|
-
"stream-json",
|
|
298
|
-
"--verbose",
|
|
299
|
-
"--include-partial-messages"
|
|
300
|
-
];
|
|
301
|
-
if (launch.permissionMode === "bypassPermissions") {
|
|
302
|
-
args.push("--dangerously-skip-permissions");
|
|
303
|
-
} else {
|
|
304
|
-
args.push("--permission-mode", launch.permissionMode);
|
|
305
|
-
}
|
|
306
|
-
if (launch.features.permissionPrompts) args.push("--permission-prompts", "none");
|
|
307
|
-
if (launch.features.settingSources && !launch.loadProjectSettings) {
|
|
308
|
-
args.push("--setting-sources", "user");
|
|
309
|
-
}
|
|
310
|
-
if (launch.model) {
|
|
311
|
-
assertValidModel(launch.model);
|
|
312
|
-
args.push(`--model=${launch.model}`);
|
|
313
|
-
}
|
|
314
|
-
if (launch.resume) args.push("--resume", launch.resume);
|
|
315
|
-
if (launch.appendSystemPrompt) args.push("--append-system-prompt", launch.appendSystemPrompt);
|
|
316
|
-
if (launch.disallowedTools?.length) args.push("--disallowedTools", ...launch.disallowedTools);
|
|
317
|
-
if (launch.allowedTools.length) args.push("--allowedTools", ...launch.allowedTools);
|
|
318
|
-
return args;
|
|
308
|
+
function cloneUrl(ref, protocol) {
|
|
309
|
+
return protocol === "ssh" ? `git@${ref.host}:${ref.owner}/${ref.repo}.git` : `https://${ref.host}/${ref.owner}/${ref.repo}.git`;
|
|
319
310
|
}
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
"Your working directory is a scratch directory created for this task; it is not a git repository."
|
|
325
|
-
].join(" ");
|
|
311
|
+
var UNSAFE_REF = /[\s~^:?*[\\\x00-\x1f]|\.\.|@\{|\/\/|\.lock$|\/$/;
|
|
312
|
+
function assertSafeRef(name, what) {
|
|
313
|
+
if (!name || name.startsWith("-") || UNSAFE_REF.test(name)) {
|
|
314
|
+
throw new Error(`${what} "${name}" is not a valid branch name.`);
|
|
326
315
|
}
|
|
327
|
-
return [
|
|
328
|
-
"You are running a Discovery Tree task through the person\u2019s local Discovery Tree runner.",
|
|
329
|
-
`Your working directory is a git worktree managed by the runner, on branch \`${input.workBranch}\``,
|
|
330
|
-
input.baseRef ? `(created from \`${input.baseRef}\`).` : ".",
|
|
331
|
-
"Commit your work to this branch as you go, with clear, descriptive commit messages.",
|
|
332
|
-
"Do not push, do not switch, create or delete branches, and do not rewrite commits that may",
|
|
333
|
-
"already be pushed: the runner commits anything left over and pushes this branch for you",
|
|
334
|
-
"at the end of every turn.",
|
|
335
|
-
"Do not open a pull request either: Discovery Tree opens it from this branch when a turn",
|
|
336
|
-
"ends, with that turn\u2019s final message as its description, and later turns add to it.",
|
|
337
|
-
"Before then (your first turn) there is none; say so rather than trying to open one.",
|
|
338
|
-
`To read it, use \`gh pr view ${input.workBranch}\` (\`--comments\` for the conversation),`,
|
|
339
|
-
"`gh pr diff`, `gh pr checks`, and `gh run view` for a check run\u2019s logs. Only `gh` commands",
|
|
340
|
-
"that read are allowed; ones that change GitHub (comment, edit, merge, `gh api`) are denied.",
|
|
341
|
-
"For screenshots of a user-visible change, save the images (PNG, JPEG, GIF or WebP) in",
|
|
342
|
-
"`.dt-evidence/` at the root of this worktree, named for what they show",
|
|
343
|
-
"(`settings-dark.png`), for example with `npx playwright screenshot <url> .dt-evidence/<name>.png`.",
|
|
344
|
-
"Do not commit them, upload them or link them yourself: at the end of the turn the runner",
|
|
345
|
-
"publishes them on a branch of their own and adds them, linked, under your final message,",
|
|
346
|
-
"so they appear in the pull request description. The folder is ignored by git."
|
|
347
|
-
].join(" ");
|
|
348
|
-
}
|
|
349
|
-
|
|
350
|
-
// src/config.ts
|
|
351
|
-
import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
352
|
-
import { homedir } from "node:os";
|
|
353
|
-
import { dirname, join as join2 } from "node:path";
|
|
354
|
-
|
|
355
|
-
// src/invocation.ts
|
|
356
|
-
var RUNNER_PACKAGE = "@discovery-tree/runner";
|
|
357
|
-
function launchedByNpx(env = process.env, argv1 = process.argv[1]) {
|
|
358
|
-
if (env.npm_command === "exec") return true;
|
|
359
|
-
return /[\\/](_npx|dlx)[\\/]/.test(argv1 ?? "");
|
|
360
316
|
}
|
|
361
|
-
|
|
362
|
-
|
|
317
|
+
var repoLocks = /* @__PURE__ */ new Map();
|
|
318
|
+
function withRepoLock(dir, fn) {
|
|
319
|
+
const prev = repoLocks.get(dir) ?? Promise.resolve();
|
|
320
|
+
const next = prev.catch(() => void 0).then(fn);
|
|
321
|
+
repoLocks.set(dir, next);
|
|
322
|
+
const release = () => {
|
|
323
|
+
if (repoLocks.get(dir) === next) repoLocks.delete(dir);
|
|
324
|
+
};
|
|
325
|
+
next.then(release, release);
|
|
326
|
+
return next;
|
|
363
327
|
}
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
const local = env.LOCALAPPDATA || join2(home, "AppData", "Local");
|
|
371
|
-
return {
|
|
372
|
-
configFile: join2(roaming, "discovery-tree", "runner.json"),
|
|
373
|
-
dataDir: join2(local, "discovery-tree", "runner"),
|
|
374
|
-
stateDir: join2(local, "discovery-tree", "runner", "state")
|
|
375
|
-
};
|
|
328
|
+
async function exists(p) {
|
|
329
|
+
try {
|
|
330
|
+
await stat(p);
|
|
331
|
+
return true;
|
|
332
|
+
} catch {
|
|
333
|
+
return false;
|
|
376
334
|
}
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
const
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
335
|
+
}
|
|
336
|
+
async function prepareWorktree(input) {
|
|
337
|
+
const ref = parseRepoUrl(input.url);
|
|
338
|
+
if (!ref) throw new Error(repositoryUrlError(input.url));
|
|
339
|
+
assertSafeRef(input.workBranch, "Work branch");
|
|
340
|
+
if (input.baseRef) assertSafeRef(input.baseRef, "Base branch");
|
|
341
|
+
const repoDir = join2(input.reposDir, ref.owner, ref.repo);
|
|
342
|
+
const worktree = join2(input.worktreesDir, input.worktreeKey || input.sessionId);
|
|
343
|
+
return withRepoLock(repoDir, async () => {
|
|
344
|
+
if (!await exists(join2(repoDir, ".git"))) {
|
|
345
|
+
await mkdir(dirname(repoDir), { recursive: true });
|
|
346
|
+
await rm(repoDir, { recursive: true, force: true });
|
|
347
|
+
await git(dirname(repoDir), [
|
|
348
|
+
"clone",
|
|
349
|
+
"--no-checkout",
|
|
350
|
+
cloneUrl(ref, input.protocol),
|
|
351
|
+
repoDir
|
|
352
|
+
]);
|
|
353
|
+
} else {
|
|
354
|
+
const wanted = cloneUrl(ref, input.protocol);
|
|
355
|
+
const current = await exec("git", ["config", "--get", "remote.origin.url"], {
|
|
356
|
+
cwd: repoDir,
|
|
357
|
+
env: gitEnv()
|
|
358
|
+
});
|
|
359
|
+
if (current.stdout.trim() !== wanted) {
|
|
360
|
+
await git(repoDir, ["remote", "set-url", "origin", wanted]);
|
|
361
|
+
}
|
|
362
|
+
await git(repoDir, ["fetch", "--prune", "origin"]);
|
|
363
|
+
}
|
|
364
|
+
const baseRef = input.baseRef ?? await defaultBranch(repoDir);
|
|
365
|
+
let start2 = `origin/${baseRef}`;
|
|
366
|
+
if (!await gitOk(repoDir, ["rev-parse", "--verify", "--quiet", `${start2}^{commit}`])) {
|
|
367
|
+
if (!await gitOk(repoDir, ["rev-parse", "--verify", "--quiet", `${baseRef}^{commit}`])) {
|
|
368
|
+
throw new Error(`Base branch ${baseRef} was not found on origin.`);
|
|
369
|
+
}
|
|
370
|
+
start2 = baseRef;
|
|
371
|
+
}
|
|
372
|
+
let baseSha = await git(repoDir, ["rev-parse", `${start2}^{commit}`]);
|
|
373
|
+
let checkout = start2;
|
|
374
|
+
let continuedFrom;
|
|
375
|
+
let setAside;
|
|
376
|
+
const remoteWork = `refs/remotes/origin/${input.workBranch}`;
|
|
377
|
+
if (input.continueBranch && await exists(worktree) && await exec("git", ["rev-parse", "--abbrev-ref", "HEAD"], {
|
|
378
|
+
cwd: worktree,
|
|
379
|
+
env: gitEnv(),
|
|
380
|
+
timeoutMs: 6e4
|
|
381
|
+
}).then((r) => r.code === 0 && r.stdout.trim() === input.workBranch) && // Only when it already has everything pushed to the work branch since: one that fell
|
|
382
|
+
// behind (the run went on elsewhere) would have the agent work on stale code.
|
|
383
|
+
(!await gitOk(repoDir, ["rev-parse", "--verify", "--quiet", `${remoteWork}^{commit}`]) || await exec("git", ["merge-base", "--is-ancestor", remoteWork, "HEAD"], {
|
|
384
|
+
cwd: worktree,
|
|
385
|
+
env: gitEnv(),
|
|
386
|
+
timeoutMs: 6e4
|
|
387
|
+
}).then((r) => r.code === 0))) {
|
|
388
|
+
const forkPoint = await exec("git", ["merge-base", "HEAD", start2], {
|
|
389
|
+
cwd: worktree,
|
|
390
|
+
env: gitEnv(),
|
|
391
|
+
timeoutMs: 6e4
|
|
392
|
+
});
|
|
393
|
+
if (forkPoint.code === 0 && forkPoint.stdout.trim()) baseSha = forkPoint.stdout.trim();
|
|
394
|
+
return { repoDir, worktree, baseRef, baseSha, continuedFrom: "worktree" };
|
|
395
|
+
}
|
|
396
|
+
if (input.continueBranch) {
|
|
397
|
+
const remote = `refs/remotes/origin/${input.workBranch}`;
|
|
398
|
+
const local = `refs/heads/${input.workBranch}`;
|
|
399
|
+
const hasRemote = await gitOk(repoDir, [
|
|
400
|
+
"rev-parse",
|
|
401
|
+
"--verify",
|
|
402
|
+
"--quiet",
|
|
403
|
+
`${remote}^{commit}`
|
|
404
|
+
]);
|
|
405
|
+
const hasLocal = await gitOk(repoDir, [
|
|
406
|
+
"rev-parse",
|
|
407
|
+
"--verify",
|
|
408
|
+
"--quiet",
|
|
409
|
+
`${local}^{commit}`
|
|
410
|
+
]);
|
|
411
|
+
const localAhead = hasLocal && (!hasRemote || await gitOk(repoDir, ["merge-base", "--is-ancestor", remote, local]));
|
|
412
|
+
if (localAhead) {
|
|
413
|
+
checkout = local;
|
|
414
|
+
continuedFrom = "local";
|
|
415
|
+
} else if (hasRemote) {
|
|
416
|
+
checkout = remote;
|
|
417
|
+
continuedFrom = "remote";
|
|
418
|
+
} else {
|
|
419
|
+
continuedFrom = "base";
|
|
420
|
+
}
|
|
421
|
+
if (continuedFrom !== "base") {
|
|
422
|
+
const forkPoint = await exec("git", ["merge-base", checkout, start2], {
|
|
423
|
+
cwd: repoDir,
|
|
424
|
+
env: gitEnv(),
|
|
425
|
+
timeoutMs: 6e4
|
|
426
|
+
});
|
|
427
|
+
if (forkPoint.code === 0 && forkPoint.stdout.trim()) baseSha = forkPoint.stdout.trim();
|
|
428
|
+
checkout = await git(repoDir, ["rev-parse", `${checkout}^{commit}`]);
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
if (input.continueBranch && await exists(worktree)) {
|
|
432
|
+
const dirty = await exec("git", ["status", "--porcelain"], {
|
|
433
|
+
cwd: worktree,
|
|
434
|
+
env: gitEnv(),
|
|
435
|
+
timeoutMs: 6e4
|
|
436
|
+
});
|
|
437
|
+
if (dirty.code === 0 && dirty.stdout.trim()) {
|
|
438
|
+
const aside = `${worktree}.kept-${Date.now()}`;
|
|
439
|
+
if (await gitOk(repoDir, ["worktree", "move", worktree, aside])) setAside = aside;
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
if (await exists(worktree)) {
|
|
443
|
+
await gitOk(repoDir, ["worktree", "remove", "--force", worktree]);
|
|
444
|
+
await rm(worktree, { recursive: true, force: true });
|
|
445
|
+
}
|
|
446
|
+
await gitOk(repoDir, ["worktree", "prune"]);
|
|
447
|
+
await mkdir(input.worktreesDir, { recursive: true });
|
|
448
|
+
await git(repoDir, [
|
|
449
|
+
"worktree",
|
|
450
|
+
"add",
|
|
451
|
+
"--no-track",
|
|
452
|
+
"-B",
|
|
453
|
+
input.workBranch,
|
|
454
|
+
worktree,
|
|
455
|
+
checkout
|
|
456
|
+
]);
|
|
457
|
+
return {
|
|
458
|
+
repoDir,
|
|
459
|
+
worktree,
|
|
460
|
+
baseRef,
|
|
461
|
+
baseSha,
|
|
462
|
+
...continuedFrom ? { continuedFrom } : {},
|
|
463
|
+
...setAside ? { setAside } : {}
|
|
464
|
+
};
|
|
465
|
+
});
|
|
466
|
+
}
|
|
467
|
+
async function defaultBranch(repoDir) {
|
|
468
|
+
const read = async () => {
|
|
469
|
+
const res = await exec("git", ["symbolic-ref", "--short", "refs/remotes/origin/HEAD"], {
|
|
470
|
+
cwd: repoDir,
|
|
471
|
+
env: gitEnv()
|
|
472
|
+
});
|
|
473
|
+
return res.code === 0 ? res.stdout.trim().replace(/^origin\//, "") : null;
|
|
474
|
+
};
|
|
475
|
+
const known = await read();
|
|
476
|
+
if (known) return known;
|
|
477
|
+
await gitOk(repoDir, ["remote", "set-head", "origin", "--auto"]);
|
|
478
|
+
return await read() ?? "main";
|
|
479
|
+
}
|
|
480
|
+
async function commitAndPush(input) {
|
|
481
|
+
const { worktree } = input;
|
|
482
|
+
const exclude = input.exclude ?? [];
|
|
483
|
+
const excluded = (line) => {
|
|
484
|
+
const path = line.slice(3).replace(/^"|"$/g, "");
|
|
485
|
+
return exclude.some((p) => path === p || path.startsWith(`${p}/`));
|
|
486
|
+
};
|
|
487
|
+
let committed = false;
|
|
488
|
+
try {
|
|
489
|
+
const status2 = await git(worktree, ["status", "--porcelain"]);
|
|
490
|
+
const dirty = status2.split("\n").some((line) => line && !excluded(line));
|
|
491
|
+
if (dirty) {
|
|
492
|
+
await git(worktree, ["add", "-A"]);
|
|
493
|
+
if (exclude.length) await git(worktree, ["reset", "-q", "--", ...exclude]);
|
|
494
|
+
}
|
|
495
|
+
const staged = dirty && !await gitOk(worktree, ["diff", "--cached", "--quiet"]);
|
|
496
|
+
if (staged) {
|
|
497
|
+
const identity2 = await gitOk(worktree, ["config", "user.email"]) ? [] : [
|
|
498
|
+
"-c",
|
|
499
|
+
"user.name=Discovery Tree runner",
|
|
500
|
+
"-c",
|
|
501
|
+
"user.email=dt-runner@users.noreply.local"
|
|
502
|
+
];
|
|
503
|
+
await git(worktree, [...identity2, "commit", "--no-verify", "-q", "-m", input.message]);
|
|
504
|
+
committed = true;
|
|
505
|
+
}
|
|
506
|
+
} catch (err) {
|
|
507
|
+
return {
|
|
508
|
+
committed,
|
|
509
|
+
pushed: false,
|
|
510
|
+
error: errorText(err, "Committing the work failed"),
|
|
511
|
+
failedAt: "commit"
|
|
512
|
+
};
|
|
513
|
+
}
|
|
514
|
+
try {
|
|
515
|
+
const ahead = Number(await git(worktree, ["rev-list", "--count", `${input.baseSha}..HEAD`]));
|
|
516
|
+
if (!ahead) return { committed, pushed: false, error: null };
|
|
517
|
+
await git(worktree, ["push", "--quiet", "-u", "origin", `HEAD:refs/heads/${input.workBranch}`]);
|
|
518
|
+
return { committed, pushed: true, error: null };
|
|
519
|
+
} catch (err) {
|
|
520
|
+
return {
|
|
521
|
+
committed,
|
|
522
|
+
pushed: false,
|
|
523
|
+
error: errorText(err, "Pushing the work branch failed"),
|
|
524
|
+
failedAt: "push"
|
|
525
|
+
};
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
async function removeWorktree(repoDir, worktree) {
|
|
529
|
+
if (repoDir && await exists(repoDir)) {
|
|
530
|
+
await gitOk(repoDir, ["worktree", "remove", "--force", worktree]);
|
|
531
|
+
}
|
|
532
|
+
await rm(worktree, { recursive: true, force: true });
|
|
533
|
+
if (repoDir && await exists(repoDir)) await gitOk(repoDir, ["worktree", "prune"]);
|
|
534
|
+
}
|
|
535
|
+
function errorText(err, prefix) {
|
|
536
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
537
|
+
return scrubSecrets(`${prefix}: ${msg}`).slice(0, 600);
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
// src/evidence.ts
|
|
541
|
+
var EVIDENCE_DIR = ".dt-evidence";
|
|
542
|
+
var PUBLISHED_DIR = "published";
|
|
543
|
+
var IMAGE_EXTENSIONS = /* @__PURE__ */ new Set(["png", "jpg", "jpeg", "gif", "webp"]);
|
|
544
|
+
var MAX_EVIDENCE_IMAGES = 12;
|
|
545
|
+
var MAX_EVIDENCE_BYTES = 8 * 1024 * 1024;
|
|
546
|
+
function evidenceBranch(workBranch) {
|
|
547
|
+
return `dt-evidence/${workBranch.replace(/%/g, "%25").replace(/\//g, "%2F")}`;
|
|
548
|
+
}
|
|
549
|
+
async function ensureEvidenceDir(worktree) {
|
|
550
|
+
await mkdir2(join3(worktree, EVIDENCE_DIR), { recursive: true });
|
|
551
|
+
const rel = await git(worktree, ["rev-parse", "--git-path", "info/exclude"]);
|
|
552
|
+
const file = isAbsolute2(rel) ? rel : join3(worktree, rel);
|
|
553
|
+
const line = `/${EVIDENCE_DIR}/`;
|
|
554
|
+
let current = "";
|
|
555
|
+
try {
|
|
556
|
+
current = await readFile(file, "utf8");
|
|
557
|
+
} catch {
|
|
558
|
+
}
|
|
559
|
+
if (current.split("\n").some((l) => l.trim() === line)) return;
|
|
560
|
+
await mkdir2(join3(file, ".."), { recursive: true });
|
|
561
|
+
const sep = current && !current.endsWith("\n") ? "\n" : "";
|
|
562
|
+
await writeFile(
|
|
563
|
+
file,
|
|
564
|
+
`${current}${sep}# Screenshots dt-runner publishes on their own branch
|
|
565
|
+
${line}
|
|
566
|
+
`
|
|
567
|
+
);
|
|
568
|
+
}
|
|
569
|
+
async function publishEvidence(input) {
|
|
570
|
+
const dir = join3(input.worktree, EVIDENCE_DIR);
|
|
571
|
+
let found;
|
|
572
|
+
try {
|
|
573
|
+
found = await waitingImages(dir);
|
|
574
|
+
} catch (err) {
|
|
575
|
+
const why = err instanceof Error ? err.message : String(err);
|
|
576
|
+
return { images: [], skipped: [], error: `Reading the screenshots failed: ${why}` };
|
|
577
|
+
}
|
|
578
|
+
const skipped = found.filter((f) => f.size > MAX_EVIDENCE_BYTES).map((f) => f.name);
|
|
579
|
+
const fitting = found.filter((f) => f.size <= MAX_EVIDENCE_BYTES);
|
|
580
|
+
skipped.push(...fitting.slice(MAX_EVIDENCE_IMAGES).map((f) => f.name));
|
|
581
|
+
const files = fitting.slice(0, MAX_EVIDENCE_IMAGES);
|
|
582
|
+
if (!files.length) return { images: [], skipped, error: null };
|
|
583
|
+
const branch = evidenceBranch(input.workBranch);
|
|
584
|
+
let scratch = null;
|
|
585
|
+
try {
|
|
586
|
+
assertSafeRef(branch, "Evidence branch");
|
|
587
|
+
scratch = await mkdtemp(join3(tmpdir(), "dt-evidence-"));
|
|
588
|
+
const index = join3(scratch, "index");
|
|
589
|
+
const ref = `refs/heads/${branch}`;
|
|
590
|
+
const build = async () => {
|
|
591
|
+
await gitOk2(input.repoDir, ["fetch", "--quiet", "origin", `+${ref}:${ref}`]);
|
|
592
|
+
const parent = await revParse(input.repoDir, ref);
|
|
593
|
+
const run = (args) => gitWithIndex(input.repoDir, index, args);
|
|
594
|
+
await run(parent ? ["read-tree", parent] : ["read-tree", "--empty"]);
|
|
595
|
+
for (const f of files) {
|
|
596
|
+
const blob = await git(input.repoDir, ["hash-object", "-w", "--", join3(dir, f.name)]);
|
|
597
|
+
await run(["update-index", "--add", "--cacheinfo", `100644,${blob},${f.path}`]);
|
|
598
|
+
}
|
|
599
|
+
const tree = await run(["write-tree"]);
|
|
600
|
+
const parentTree = parent ? await git(input.repoDir, ["rev-parse", `${parent}^{tree}`]) : null;
|
|
601
|
+
if (parent && tree === parentTree) return parent;
|
|
602
|
+
const made = await git(input.repoDir, [
|
|
603
|
+
...await identity(input.repoDir),
|
|
604
|
+
"commit-tree",
|
|
605
|
+
tree,
|
|
606
|
+
...parent ? ["-p", parent] : [],
|
|
607
|
+
"-m",
|
|
608
|
+
`Screenshots for ${input.workBranch}
|
|
609
|
+
|
|
610
|
+
Published by dt-runner for the pull request's review; not part of the change.`
|
|
611
|
+
]);
|
|
612
|
+
await git(input.repoDir, ["update-ref", ref, made]);
|
|
613
|
+
return made;
|
|
614
|
+
};
|
|
615
|
+
let commit = await build();
|
|
616
|
+
try {
|
|
617
|
+
await git(input.repoDir, ["push", "--quiet", "origin", `${commit}:${ref}`]);
|
|
618
|
+
} catch {
|
|
619
|
+
commit = await build();
|
|
620
|
+
await git(input.repoDir, ["push", "--quiet", "origin", `${commit}:${ref}`]);
|
|
621
|
+
}
|
|
622
|
+
await mkdir2(join3(dir, PUBLISHED_DIR), { recursive: true });
|
|
623
|
+
for (const f of files) {
|
|
624
|
+
await rename(join3(dir, f.name), join3(dir, PUBLISHED_DIR, f.name)).catch(() => void 0);
|
|
625
|
+
}
|
|
626
|
+
return {
|
|
627
|
+
images: files.map((f) => ({
|
|
628
|
+
path: f.path,
|
|
629
|
+
caption: captionFor(f.name),
|
|
630
|
+
url: rawFileUrl(input.repo, commit, f.path)
|
|
631
|
+
})),
|
|
632
|
+
skipped,
|
|
633
|
+
error: null
|
|
634
|
+
};
|
|
635
|
+
} catch (err) {
|
|
636
|
+
const why = err instanceof GitError || err instanceof Error ? err.message : String(err);
|
|
637
|
+
return { images: [], skipped, error: `Publishing the screenshots failed: ${why}` };
|
|
638
|
+
} finally {
|
|
639
|
+
if (scratch) await rm2(scratch, { recursive: true, force: true }).catch(() => void 0);
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
function evidenceMarkdown(result) {
|
|
643
|
+
if (!result.images.length) return "";
|
|
644
|
+
return ["## Screenshots", "", ...result.images.map((i) => ``)].join(
|
|
645
|
+
"\n"
|
|
646
|
+
);
|
|
647
|
+
}
|
|
648
|
+
function rawFileUrl(repo, commit, path) {
|
|
649
|
+
const segments = path.split("/").map(encodeURIComponent).join("/");
|
|
650
|
+
return `https://${repo.host}/${repo.owner}/${repo.repo}/raw/${commit}/${segments}`;
|
|
651
|
+
}
|
|
652
|
+
async function waitingImages(dir) {
|
|
653
|
+
let entries;
|
|
654
|
+
try {
|
|
655
|
+
entries = await readdir(dir, { withFileTypes: true });
|
|
656
|
+
} catch {
|
|
657
|
+
return [];
|
|
658
|
+
}
|
|
659
|
+
const out = [];
|
|
660
|
+
for (const e of entries) {
|
|
661
|
+
if (!e.isFile()) continue;
|
|
662
|
+
const ext = e.name.split(".").pop()?.toLowerCase() ?? "";
|
|
663
|
+
if (!e.name.includes(".") || !IMAGE_EXTENSIONS.has(ext)) continue;
|
|
664
|
+
const { size } = await stat2(join3(dir, e.name));
|
|
665
|
+
out.push({ name: e.name, path: safeName(e.name), size });
|
|
666
|
+
}
|
|
667
|
+
out.sort((a, b) => a.name.localeCompare(b.name));
|
|
668
|
+
const taken = /* @__PURE__ */ new Set();
|
|
669
|
+
for (const f of out) {
|
|
670
|
+
let path = f.path;
|
|
671
|
+
for (let n = 2; taken.has(path.toLowerCase()); n++) {
|
|
672
|
+
path = f.path.replace(/(\.[^.]+)?$/, (ext) => `-${n}${ext}`);
|
|
673
|
+
}
|
|
674
|
+
taken.add(path.toLowerCase());
|
|
675
|
+
f.path = path;
|
|
676
|
+
}
|
|
677
|
+
return out;
|
|
678
|
+
}
|
|
679
|
+
function safeName(name) {
|
|
680
|
+
const cleaned = name.replace(/[^\w.-]+/g, "-").replace(/^[.-]+/, "");
|
|
681
|
+
return cleaned || "screenshot.png";
|
|
682
|
+
}
|
|
683
|
+
function captionFor(name) {
|
|
684
|
+
return name.replace(/\.[^.]+$/, "").replace(/[-_]+/g, " ").replace(/[[\]]/g, "").trim();
|
|
685
|
+
}
|
|
686
|
+
async function gitOk2(cwd, args) {
|
|
687
|
+
const res = await exec("git", args, { cwd, env: gitEnv(), timeoutMs: 5 * 6e4 });
|
|
688
|
+
return res.code === 0;
|
|
689
|
+
}
|
|
690
|
+
async function revParse(cwd, ref) {
|
|
691
|
+
const res = await exec("git", ["rev-parse", "--verify", "-q", `${ref}^{commit}`], {
|
|
692
|
+
cwd,
|
|
693
|
+
env: gitEnv(),
|
|
694
|
+
timeoutMs: 6e4
|
|
695
|
+
});
|
|
696
|
+
return res.code === 0 ? res.stdout.trim() : null;
|
|
697
|
+
}
|
|
698
|
+
async function gitWithIndex(cwd, index, args) {
|
|
699
|
+
const res = await exec("git", args, {
|
|
700
|
+
cwd,
|
|
701
|
+
env: { ...gitEnv(), GIT_INDEX_FILE: index },
|
|
702
|
+
timeoutMs: 6e4
|
|
703
|
+
});
|
|
704
|
+
if (res.code !== 0) throw new GitError(args, res);
|
|
705
|
+
return res.stdout.trim();
|
|
706
|
+
}
|
|
707
|
+
async function identity(cwd) {
|
|
708
|
+
const res = await exec("git", ["config", "user.email"], {
|
|
709
|
+
cwd,
|
|
710
|
+
env: gitEnv(),
|
|
711
|
+
timeoutMs: 6e4
|
|
712
|
+
});
|
|
713
|
+
return res.code === 0 && res.stdout.trim() ? [] : ["-c", "user.name=Discovery Tree runner", "-c", "user.email=dt-runner@users.noreply.local"];
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
// src/claude.ts
|
|
717
|
+
async function findClaude(env = process.env) {
|
|
718
|
+
const override = env.DT_RUNNER_CLAUDE_BIN?.trim();
|
|
719
|
+
if (override) return which(override, env);
|
|
720
|
+
return which("claude", env);
|
|
721
|
+
}
|
|
722
|
+
async function claudeVersion(bin) {
|
|
723
|
+
try {
|
|
724
|
+
const res = await exec(bin, ["--version"], { timeoutMs: 15e3 });
|
|
725
|
+
if (res.code !== 0) return null;
|
|
726
|
+
return res.stdout.trim().split("\n")[0] || null;
|
|
727
|
+
} catch {
|
|
728
|
+
return null;
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
async function claudeAuthStatus(bin) {
|
|
732
|
+
try {
|
|
733
|
+
const res = await exec(bin, ["auth", "status", "--json"], { timeoutMs: 2e4 });
|
|
734
|
+
const parsed = JSON.parse(res.stdout);
|
|
735
|
+
if (typeof parsed.loggedIn !== "boolean") return { loggedIn: null, authMethod: null };
|
|
736
|
+
return {
|
|
737
|
+
loggedIn: parsed.loggedIn,
|
|
738
|
+
authMethod: typeof parsed.authMethod === "string" ? parsed.authMethod : null
|
|
739
|
+
};
|
|
740
|
+
} catch {
|
|
741
|
+
return { loggedIn: null, authMethod: null };
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
async function claudeFeatures(bin) {
|
|
745
|
+
try {
|
|
746
|
+
const res = await exec(bin, ["--help"], { timeoutMs: 15e3 });
|
|
747
|
+
return {
|
|
748
|
+
permissionPrompts: res.stdout.includes("--permission-prompts"),
|
|
749
|
+
settingSources: res.stdout.includes("--setting-sources")
|
|
750
|
+
};
|
|
751
|
+
} catch {
|
|
752
|
+
return { permissionPrompts: false, settingSources: false };
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
async function probeAgent(env = process.env) {
|
|
756
|
+
const bin = await findClaude(env);
|
|
757
|
+
if (!bin) {
|
|
758
|
+
return {
|
|
759
|
+
claudeVersion: null,
|
|
760
|
+
claudeReady: false,
|
|
761
|
+
claudeProblem: "Claude Code is not installed on this computer (no `claude` on PATH)."
|
|
762
|
+
};
|
|
763
|
+
}
|
|
764
|
+
const version = await claudeVersion(bin);
|
|
765
|
+
if (!version) {
|
|
766
|
+
return {
|
|
767
|
+
claudeVersion: null,
|
|
768
|
+
claudeReady: false,
|
|
769
|
+
claudeProblem: "`claude --version` failed; reinstall or update Claude Code."
|
|
770
|
+
};
|
|
771
|
+
}
|
|
772
|
+
const auth = await claudeAuthStatus(bin);
|
|
773
|
+
if (auth.loggedIn === false) {
|
|
774
|
+
return {
|
|
775
|
+
claudeVersion: version,
|
|
776
|
+
claudeReady: false,
|
|
777
|
+
claudeProblem: "Claude Code is not signed in. Run `claude` once on this computer and sign in."
|
|
778
|
+
};
|
|
779
|
+
}
|
|
780
|
+
return { claudeVersion: version, claudeReady: auth.loggedIn, claudeProblem: null };
|
|
781
|
+
}
|
|
782
|
+
var SIGN_IN_FAILURE = /failed to authenticate|oauth (session|token)\b[^.]*\bexpired|invalid (x-)?api[ -]key|authentication_error|please run \/login/i;
|
|
783
|
+
function looksLikeSignInFailure(text) {
|
|
784
|
+
return !!text && SIGN_IN_FAILURE.test(text);
|
|
785
|
+
}
|
|
786
|
+
function turnFailedToSignIn(turn) {
|
|
787
|
+
return (turn.subtype ?? "success") === "success" && looksLikeSignInFailure(turn.text);
|
|
788
|
+
}
|
|
789
|
+
function signInFix(env = process.env) {
|
|
790
|
+
if (env.ANTHROPIC_API_KEY) {
|
|
791
|
+
return "`ANTHROPIC_API_KEY` is set where the runner runs, so Claude Code signs in with that key instead of your Claude subscription. Unset it (or replace it with a working key) and restart the runner.";
|
|
792
|
+
}
|
|
793
|
+
return 'On the runner\u2019s computer, run `claude`, type `/login` and sign in again, and check that `claude -p "say ok"` answers.';
|
|
794
|
+
}
|
|
795
|
+
var MODEL_NAME = /^[A-Za-z0-9][\w.:@/[\]-]{0,199}$/;
|
|
796
|
+
function isValidModelName(model) {
|
|
797
|
+
return MODEL_NAME.test(model);
|
|
798
|
+
}
|
|
799
|
+
function assertValidModel(model) {
|
|
800
|
+
if (model && !isValidModelName(model)) {
|
|
801
|
+
throw new Error(
|
|
802
|
+
`The model "${model.slice(0, 80)}" is not a valid Claude Code model name; the runner refused to start it.`
|
|
803
|
+
);
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
function claudeArgs(launch) {
|
|
807
|
+
const args = [
|
|
808
|
+
"-p",
|
|
809
|
+
"--input-format",
|
|
810
|
+
"stream-json",
|
|
811
|
+
"--output-format",
|
|
812
|
+
"stream-json",
|
|
813
|
+
"--verbose",
|
|
814
|
+
"--include-partial-messages"
|
|
815
|
+
];
|
|
816
|
+
if (launch.permissionMode === "bypassPermissions") {
|
|
817
|
+
args.push("--dangerously-skip-permissions");
|
|
818
|
+
} else {
|
|
819
|
+
args.push("--permission-mode", launch.permissionMode);
|
|
820
|
+
}
|
|
821
|
+
if (launch.features.permissionPrompts) args.push("--permission-prompts", "none");
|
|
822
|
+
if (launch.features.settingSources && !launch.loadProjectSettings) {
|
|
823
|
+
args.push("--setting-sources", "user");
|
|
824
|
+
}
|
|
825
|
+
if (launch.model) {
|
|
826
|
+
assertValidModel(launch.model);
|
|
827
|
+
args.push(`--model=${launch.model}`);
|
|
828
|
+
}
|
|
829
|
+
if (launch.resume) args.push("--resume", launch.resume);
|
|
830
|
+
if (launch.appendSystemPrompt) args.push("--append-system-prompt", launch.appendSystemPrompt);
|
|
831
|
+
if (launch.disallowedTools?.length) args.push("--disallowedTools", ...launch.disallowedTools);
|
|
832
|
+
if (launch.allowedTools.length) args.push("--allowedTools", ...launch.allowedTools);
|
|
833
|
+
return args;
|
|
834
|
+
}
|
|
835
|
+
function runnerSystemPrompt(input) {
|
|
836
|
+
if (!input.workBranch) {
|
|
837
|
+
return [
|
|
838
|
+
"You are running a Discovery Tree task through the person\u2019s local Discovery Tree runner.",
|
|
839
|
+
"Your working directory is a scratch directory created for this task; it is not a git repository."
|
|
840
|
+
].join(" ");
|
|
841
|
+
}
|
|
842
|
+
const evidence = join4(input.cwd, EVIDENCE_DIR);
|
|
843
|
+
return [
|
|
844
|
+
"You are running a Discovery Tree task through the person\u2019s local Discovery Tree runner.",
|
|
845
|
+
`Your working directory is a git worktree managed by the runner, on branch \`${input.workBranch}\``,
|
|
846
|
+
input.baseRef ? `(created from \`${input.baseRef}\`).` : ".",
|
|
847
|
+
"Commit your work to this branch as you go, with clear, descriptive commit messages.",
|
|
848
|
+
"Do not push, do not switch, create or delete branches, and do not rewrite commits that may",
|
|
849
|
+
"already be pushed: the runner commits anything left over and pushes this branch for you",
|
|
850
|
+
"at the end of every turn.",
|
|
851
|
+
"Do not open a pull request either: Discovery Tree opens it from this branch when a turn",
|
|
852
|
+
"ends, with that turn\u2019s final message as its description, and later turns add to it.",
|
|
853
|
+
"Before then (your first turn) there is none; say so rather than trying to open one.",
|
|
854
|
+
`To read it, use \`gh pr view ${input.workBranch}\` (\`--comments\` for the conversation),`,
|
|
855
|
+
"`gh pr diff`, `gh pr checks`, and `gh run view` for a check run\u2019s logs. Only `gh` commands",
|
|
856
|
+
"that read are allowed; ones that change GitHub (comment, edit, merge, `gh api`) are denied.",
|
|
857
|
+
"For screenshots of a user-visible change, save the images (PNG, JPEG, GIF or WebP) in",
|
|
858
|
+
`\`${evidence}/\` (the root of this worktree, also after a \`cd\`), named for what they show`,
|
|
859
|
+
`(\`settings-dark.png\`), for example with \`npx playwright screenshot <url> "${evidence}/<name>.png"\`.`,
|
|
860
|
+
"Do not commit them, upload them or link them yourself: at the end of the turn the runner",
|
|
861
|
+
"publishes them on a branch of their own and adds them, linked, under your final message,",
|
|
862
|
+
"so they appear in the pull request description. The folder is ignored by git.",
|
|
863
|
+
"To run a dev server, start it with the Bash tool\u2019s background option (not `&` or",
|
|
864
|
+
"`nohup`), read its output file for the port it is listening on, check it with one command",
|
|
865
|
+
"such as `node -e \"fetch('http://localhost:<port>/', { signal: AbortSignal.timeout(60000) })",
|
|
866
|
+
'.then(r => console.log(r.status), e => console.log(e.cause?.code ?? e.message))"`',
|
|
867
|
+
"(the first request may wait while the page compiles; `curl` is denied; no loops), and stop",
|
|
868
|
+
"it with TaskStop before you finish.",
|
|
869
|
+
"Other runs may share this computer:",
|
|
870
|
+
"if the port is taken, start yours on another port; never stop a process you did not start.",
|
|
871
|
+
"Do not start databases, containers or other services yourself, directly or through a",
|
|
872
|
+
"package script, unless the task asks you to; if one the server needs is not running, say so."
|
|
873
|
+
].join(" ");
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
// src/config.ts
|
|
877
|
+
import { chmod, mkdir as mkdir3, readFile as readFile2, rm as rm3, writeFile as writeFile2 } from "node:fs/promises";
|
|
878
|
+
import { homedir } from "node:os";
|
|
879
|
+
import { dirname as dirname2, join as join5 } from "node:path";
|
|
880
|
+
|
|
881
|
+
// src/invocation.ts
|
|
882
|
+
var RUNNER_PACKAGE = "@discovery-tree/runner";
|
|
883
|
+
function launchedByNpx(env = process.env, argv1 = process.argv[1]) {
|
|
884
|
+
if (env.npm_command === "exec") return true;
|
|
885
|
+
return /[\\/](_npx|dlx)[\\/]/.test(argv1 ?? "");
|
|
886
|
+
}
|
|
887
|
+
function runnerCommand(subcommand, viaNpx = launchedByNpx()) {
|
|
888
|
+
return viaNpx ? `npx ${RUNNER_PACKAGE}@latest ${subcommand}` : `dt-runner ${subcommand}`;
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
// src/config.ts
|
|
892
|
+
function runnerPaths(env = process.env) {
|
|
893
|
+
const home = homedir();
|
|
894
|
+
if (process.platform === "win32") {
|
|
895
|
+
const roaming = env.APPDATA || join5(home, "AppData", "Roaming");
|
|
896
|
+
const local = env.LOCALAPPDATA || join5(home, "AppData", "Local");
|
|
897
|
+
return {
|
|
898
|
+
configFile: join5(roaming, "discovery-tree", "runner.json"),
|
|
899
|
+
dataDir: join5(local, "discovery-tree", "runner"),
|
|
900
|
+
stateDir: join5(local, "discovery-tree", "runner", "state")
|
|
901
|
+
};
|
|
902
|
+
}
|
|
903
|
+
const config = env.XDG_CONFIG_HOME || join5(home, ".config");
|
|
904
|
+
const data = env.XDG_DATA_HOME || join5(home, ".local", "share");
|
|
905
|
+
const state = env.XDG_STATE_HOME || join5(home, ".local", "state");
|
|
906
|
+
return {
|
|
907
|
+
configFile: join5(config, "discovery-tree", "runner.json"),
|
|
908
|
+
dataDir: join5(data, "discovery-tree", "runner"),
|
|
909
|
+
stateDir: join5(state, "discovery-tree", "runner")
|
|
910
|
+
};
|
|
385
911
|
}
|
|
386
912
|
var PERMISSION_MODES = [
|
|
387
913
|
"acceptEdits",
|
|
@@ -403,6 +929,9 @@ var DEFAULT_ALLOWED_TOOLS = [
|
|
|
403
929
|
"NotebookEdit",
|
|
404
930
|
"TodoWrite",
|
|
405
931
|
"Task",
|
|
932
|
+
// Stops a command started with the Bash tool's background option (a dev server); its
|
|
933
|
+
// output is a file the agent reads with Read.
|
|
934
|
+
"TaskStop",
|
|
406
935
|
"Bash(git status *)",
|
|
407
936
|
"Bash(git diff *)",
|
|
408
937
|
"Bash(git log *)",
|
|
@@ -453,7 +982,13 @@ var DEFAULT_ALLOWED_TOOLS = [
|
|
|
453
982
|
"Bash(sort *)",
|
|
454
983
|
"Bash(uniq *)",
|
|
455
984
|
"Bash(which *)",
|
|
456
|
-
"Bash(true)"
|
|
985
|
+
"Bash(true)",
|
|
986
|
+
// Starting a dev server and checking it: `cd web && npm run dev`, waiting for it, seeing
|
|
987
|
+
// what holds a port. Not `kill`: on the person's own computer the process on a busy port
|
|
988
|
+
// may be theirs (the agent stops its own servers with TaskStop and uses another port).
|
|
989
|
+
"Bash(cd *)",
|
|
990
|
+
"Bash(sleep *)",
|
|
991
|
+
"Bash(lsof *)"
|
|
457
992
|
];
|
|
458
993
|
var PROTECTED_PATHS = [
|
|
459
994
|
"~/.ssh/**",
|
|
@@ -490,442 +1025,128 @@ var PROTECTED_FROM_EDIT = [
|
|
|
490
1025
|
];
|
|
491
1026
|
var DEFAULT_DISALLOWED_TOOLS = [
|
|
492
1027
|
...PROTECTED_PATHS.map((p) => `Read(${p})`),
|
|
493
|
-
...[...PROTECTED_PATHS, ...PROTECTED_FROM_EDIT].map((p) => `Edit(${p})`)
|
|
494
|
-
];
|
|
495
|
-
function configDirRules(configFile, platform = process.platform) {
|
|
496
|
-
if (platform === "win32") return [];
|
|
497
|
-
const dir =
|
|
498
|
-
if (!dir.startsWith("/")) return [];
|
|
499
|
-
return [`Read(/${dir}/**)`, `Edit(/${dir}/**)`];
|
|
500
|
-
}
|
|
501
|
-
var DEFAULT_SERVER_URL = "https://discovery-tree-backend.onrender.com";
|
|
502
|
-
var DEFAULT_MAX_SESSIONS = 2;
|
|
503
|
-
var DEFAULT_IDLE_TIMEOUT_MINUTES = 15;
|
|
504
|
-
async function readConfigFile(file) {
|
|
505
|
-
let raw;
|
|
506
|
-
try {
|
|
507
|
-
raw = await readFile(file, "utf8");
|
|
508
|
-
} catch (err) {
|
|
509
|
-
if (err.code === "ENOENT") return null;
|
|
510
|
-
throw err;
|
|
511
|
-
}
|
|
512
|
-
try {
|
|
513
|
-
return JSON.parse(raw);
|
|
514
|
-
} catch {
|
|
515
|
-
throw new Error(
|
|
516
|
-
`${file} is not valid JSON; fix it or run \`${runnerCommand("logout")}\` to start over.`
|
|
517
|
-
);
|
|
518
|
-
}
|
|
519
|
-
}
|
|
520
|
-
async function writeConfigFile(file, config) {
|
|
521
|
-
await mkdir(dirname(file), { recursive: true, mode: 448 });
|
|
522
|
-
await writeFile(file, JSON.stringify(config, null, 2) + "\n", { mode: 384 });
|
|
523
|
-
await chmod(file, 384).catch(() => void 0);
|
|
524
|
-
}
|
|
525
|
-
async function deleteConfigFile(file) {
|
|
526
|
-
try {
|
|
527
|
-
await rm(file);
|
|
528
|
-
return true;
|
|
529
|
-
} catch (err) {
|
|
530
|
-
if (err.code === "ENOENT") return false;
|
|
531
|
-
throw err;
|
|
532
|
-
}
|
|
533
|
-
}
|
|
534
|
-
function normalizeServerUrl(url) {
|
|
535
|
-
const trimmed = url.trim().replace(/\/+$/, "");
|
|
536
|
-
return trimmed.replace(/\/api(\/health)?$/, "");
|
|
537
|
-
}
|
|
538
|
-
var MAX_SESSIONS_LIMIT = 64;
|
|
539
|
-
function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPaths(env)) {
|
|
540
|
-
const mode = file?.permissionMode ?? "acceptEdits";
|
|
541
|
-
if (!PERMISSION_MODES.includes(mode)) {
|
|
542
|
-
throw new Error(
|
|
543
|
-
`permissionMode "${mode}" in ${paths.configFile} is not one of ${PERMISSION_MODES.join(", ")}.`
|
|
544
|
-
);
|
|
545
|
-
}
|
|
546
|
-
const maxSessions = overrides.maxSessions ?? file?.maxSessions ?? DEFAULT_MAX_SESSIONS;
|
|
547
|
-
if (!Number.isInteger(maxSessions) || maxSessions < 1 || maxSessions > MAX_SESSIONS_LIMIT) {
|
|
548
|
-
throw new Error(
|
|
549
|
-
`maxSessions must be a whole number from 1 to ${MAX_SESSIONS_LIMIT} (got ${maxSessions}).`
|
|
550
|
-
);
|
|
551
|
-
}
|
|
552
|
-
const allowed = [
|
|
553
|
-
...file?.allowedTools ?? DEFAULT_ALLOWED_TOOLS,
|
|
554
|
-
...file?.extraAllowedTools ?? []
|
|
555
|
-
];
|
|
556
|
-
const disallowed = [
|
|
557
|
-
...file?.disallowedTools ?? [
|
|
558
|
-
...DEFAULT_DISALLOWED_TOOLS,
|
|
559
|
-
...configDirRules(paths.configFile)
|
|
560
|
-
],
|
|
561
|
-
...file?.extraDisallowedTools ?? []
|
|
562
|
-
];
|
|
563
|
-
return {
|
|
564
|
-
server: normalizeServerUrl(env.DT_SERVER_URL || file?.server || DEFAULT_SERVER_URL),
|
|
565
|
-
runnerId: file?.runnerId ?? null,
|
|
566
|
-
token: env.DT_RUNNER_TOKEN || file?.token || null,
|
|
567
|
-
name: file?.name ?? null,
|
|
568
|
-
maxSessions,
|
|
569
|
-
reposDir: overrides.reposDir ?? file?.reposDir ?? join2(paths.dataDir, "repos"),
|
|
570
|
-
worktreesDir: file?.worktreesDir ?? join2(paths.dataDir, "worktrees"),
|
|
571
|
-
permissionMode: mode,
|
|
572
|
-
allowedTools: [...new Set(allowed)],
|
|
573
|
-
disallowedTools: [...new Set(disallowed)],
|
|
574
|
-
loadProjectSettings: file?.loadProjectSettings === true,
|
|
575
|
-
gitProtocol: file?.gitProtocol === "ssh" ? "ssh" : "https",
|
|
576
|
-
idleTimeoutMs: (file?.idleTimeoutMinutes ?? DEFAULT_IDLE_TIMEOUT_MINUTES) * 6e4,
|
|
577
|
-
stateDir: paths.stateDir,
|
|
578
|
-
configFile: paths.configFile
|
|
579
|
-
};
|
|
580
|
-
}
|
|
581
|
-
|
|
582
|
-
// src/backoff.ts
|
|
583
|
-
function backoffDelay(attempt, baseMs = 1e3, maxMs = 6e4) {
|
|
584
|
-
const ceiling = Math.min(maxMs, baseMs * 2 ** Math.min(attempt, 20));
|
|
585
|
-
return Math.round(ceiling / 2 + Math.random() * ceiling / 2);
|
|
586
|
-
}
|
|
587
|
-
function sleep(ms, signal) {
|
|
588
|
-
return new Promise((resolve) => {
|
|
589
|
-
if (signal?.aborted) return resolve();
|
|
590
|
-
const timer = setTimeout(done, ms);
|
|
591
|
-
function done() {
|
|
592
|
-
clearTimeout(timer);
|
|
593
|
-
signal?.removeEventListener("abort", done);
|
|
594
|
-
resolve();
|
|
595
|
-
}
|
|
596
|
-
signal?.addEventListener("abort", done, { once: true });
|
|
597
|
-
});
|
|
598
|
-
}
|
|
599
|
-
|
|
600
|
-
// src/session-manager.ts
|
|
601
|
-
import { mkdir as mkdir6, rm as rm5 } from "node:fs/promises";
|
|
602
|
-
|
|
603
|
-
// src/git.ts
|
|
604
|
-
import { mkdir as mkdir2, rm as rm2, stat } from "node:fs/promises";
|
|
605
|
-
import { dirname as dirname2, join as join3 } from "node:path";
|
|
606
|
-
|
|
607
|
-
// src/log.ts
|
|
608
|
-
function createLogger(opts = {}) {
|
|
609
|
-
const write = opts.write ?? ((line) => process.stdout.write(line + "\n"));
|
|
610
|
-
const emit = (level, msg, fields) => {
|
|
611
|
-
if (level === "debug" && !opts.verbose) return;
|
|
612
|
-
const safe = fields ? redactFields(fields) : void 0;
|
|
613
|
-
if (opts.json) {
|
|
614
|
-
write(JSON.stringify({ time: (/* @__PURE__ */ new Date()).toISOString(), level, msg, ...safe }));
|
|
615
|
-
return;
|
|
616
|
-
}
|
|
617
|
-
const time = (/* @__PURE__ */ new Date()).toISOString().slice(11, 19);
|
|
618
|
-
const tag = level === "info" ? "" : ` ${level.toUpperCase()}`;
|
|
619
|
-
const extra = safe ? " " + Object.entries(safe).filter(([, v]) => v !== void 0 && v !== null && v !== "").map(([k, v]) => `${k}=${typeof v === "string" ? v : JSON.stringify(v)}`).join(" ") : "";
|
|
620
|
-
write(`${time}${tag} ${msg}${extra.trimEnd() === "" ? "" : extra}`);
|
|
621
|
-
};
|
|
622
|
-
return {
|
|
623
|
-
debug: (m, f) => emit("debug", m, f),
|
|
624
|
-
info: (m, f) => emit("info", m, f),
|
|
625
|
-
warn: (m, f) => emit("warn", m, f),
|
|
626
|
-
error: (m, f) => emit("error", m, f)
|
|
627
|
-
};
|
|
628
|
-
}
|
|
629
|
-
var SECRET_KEY = /token|secret|password|authorization/i;
|
|
630
|
-
function redactFields(fields) {
|
|
631
|
-
const out = {};
|
|
632
|
-
for (const [k, v] of Object.entries(fields)) out[k] = SECRET_KEY.test(k) ? "[redacted]" : v;
|
|
633
|
-
return out;
|
|
634
|
-
}
|
|
635
|
-
function scrubSecrets(text) {
|
|
636
|
-
return text.replace(/(https?:\/\/)[^/\s@]+@/gi, "$1***@").replace(/\bdtr_[A-Za-z0-9_-]+/g, "dtr_***").replace(/\b(gh[pousr]_[A-Za-z0-9]{10,})/g, "***");
|
|
637
|
-
}
|
|
638
|
-
|
|
639
|
-
// src/git.ts
|
|
640
|
-
var GitError = class extends Error {
|
|
641
|
-
constructor(args, result) {
|
|
642
|
-
super(gitErrorMessage(args, result));
|
|
643
|
-
this.args = args;
|
|
644
|
-
this.result = result;
|
|
645
|
-
this.name = "GitError";
|
|
646
|
-
}
|
|
647
|
-
};
|
|
648
|
-
function gitErrorMessage(args, result) {
|
|
649
|
-
const detail = (result.stderr || result.stdout).trim().split("\n").filter(Boolean).slice(-3).join(" ");
|
|
650
|
-
return scrubSecrets(`git ${args[0]} failed${detail ? `: ${detail}` : ""}`).slice(0, 500);
|
|
651
|
-
}
|
|
652
|
-
var gitEnv = () => ({
|
|
653
|
-
...process.env,
|
|
654
|
-
GIT_TERMINAL_PROMPT: "0",
|
|
655
|
-
GCM_INTERACTIVE: "never",
|
|
656
|
-
GIT_ASKPASS: process.env.GIT_ASKPASS ?? ""
|
|
657
|
-
});
|
|
658
|
-
async function git(cwd, args, timeoutMs = 10 * 6e4) {
|
|
659
|
-
const res = await exec("git", args, { cwd, env: gitEnv(), timeoutMs });
|
|
660
|
-
if (res.code !== 0) throw new GitError(args, res);
|
|
661
|
-
return res.stdout.trim();
|
|
662
|
-
}
|
|
663
|
-
async function gitOk(cwd, args) {
|
|
664
|
-
const res = await exec("git", args, { cwd, env: gitEnv(), timeoutMs: 6e4 });
|
|
665
|
-
return res.code === 0;
|
|
1028
|
+
...[...PROTECTED_PATHS, ...PROTECTED_FROM_EDIT].map((p) => `Edit(${p})`)
|
|
1029
|
+
];
|
|
1030
|
+
function configDirRules(configFile, platform = process.platform) {
|
|
1031
|
+
if (platform === "win32") return [];
|
|
1032
|
+
const dir = dirname2(configFile);
|
|
1033
|
+
if (!dir.startsWith("/")) return [];
|
|
1034
|
+
return [`Read(/${dir}/**)`, `Edit(/${dir}/**)`];
|
|
666
1035
|
}
|
|
667
|
-
var
|
|
668
|
-
|
|
1036
|
+
var DEFAULT_SERVER_URL = "https://discovery-tree-backend.onrender.com";
|
|
1037
|
+
var DEFAULT_MAX_SESSIONS = 2;
|
|
1038
|
+
var DEFAULT_IDLE_TIMEOUT_MINUTES = 15;
|
|
1039
|
+
async function readConfigFile(file) {
|
|
1040
|
+
let raw;
|
|
669
1041
|
try {
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
if (
|
|
673
|
-
|
|
674
|
-
if (parts.length !== 2 || !parts[0] || !parts[1]) return null;
|
|
675
|
-
if (!/^[\w.-]+$/.test(parts[0]) || !/^[\w.-]+$/.test(parts[1])) return null;
|
|
676
|
-
if (parts.some((p) => p === "." || p === "..")) return null;
|
|
677
|
-
return { host: REPOSITORY_HOST, owner: parts[0], repo: parts[1] };
|
|
678
|
-
} catch {
|
|
679
|
-
return null;
|
|
1042
|
+
raw = await readFile2(file, "utf8");
|
|
1043
|
+
} catch (err) {
|
|
1044
|
+
if (err.code === "ENOENT") return null;
|
|
1045
|
+
throw err;
|
|
680
1046
|
}
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
}
|
|
688
|
-
var UNSAFE_REF = /[\s~^:?*[\\\x00-\x1f]|\.\.|@\{|\/\/|\.lock$|\/$/;
|
|
689
|
-
function assertSafeRef(name, what) {
|
|
690
|
-
if (!name || name.startsWith("-") || UNSAFE_REF.test(name)) {
|
|
691
|
-
throw new Error(`${what} "${name}" is not a valid branch name.`);
|
|
1047
|
+
try {
|
|
1048
|
+
return JSON.parse(raw);
|
|
1049
|
+
} catch {
|
|
1050
|
+
throw new Error(
|
|
1051
|
+
`${file} is not valid JSON; fix it or run \`${runnerCommand("logout")}\` to start over.`
|
|
1052
|
+
);
|
|
692
1053
|
}
|
|
693
1054
|
}
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
repoLocks.set(dir, next);
|
|
699
|
-
const release = () => {
|
|
700
|
-
if (repoLocks.get(dir) === next) repoLocks.delete(dir);
|
|
701
|
-
};
|
|
702
|
-
next.then(release, release);
|
|
703
|
-
return next;
|
|
1055
|
+
async function writeConfigFile(file, config) {
|
|
1056
|
+
await mkdir3(dirname2(file), { recursive: true, mode: 448 });
|
|
1057
|
+
await writeFile2(file, JSON.stringify(config, null, 2) + "\n", { mode: 384 });
|
|
1058
|
+
await chmod(file, 384).catch(() => void 0);
|
|
704
1059
|
}
|
|
705
|
-
async function
|
|
1060
|
+
async function deleteConfigFile(file) {
|
|
706
1061
|
try {
|
|
707
|
-
await
|
|
1062
|
+
await rm3(file);
|
|
708
1063
|
return true;
|
|
709
|
-
} catch {
|
|
710
|
-
return false;
|
|
1064
|
+
} catch (err) {
|
|
1065
|
+
if (err.code === "ENOENT") return false;
|
|
1066
|
+
throw err;
|
|
711
1067
|
}
|
|
712
1068
|
}
|
|
713
|
-
|
|
714
|
-
const
|
|
715
|
-
|
|
716
|
-
assertSafeRef(input.workBranch, "Work branch");
|
|
717
|
-
if (input.baseRef) assertSafeRef(input.baseRef, "Base branch");
|
|
718
|
-
const repoDir = join3(input.reposDir, ref.owner, ref.repo);
|
|
719
|
-
const worktree = join3(input.worktreesDir, input.worktreeKey || input.sessionId);
|
|
720
|
-
return withRepoLock(repoDir, async () => {
|
|
721
|
-
if (!await exists(join3(repoDir, ".git"))) {
|
|
722
|
-
await mkdir2(dirname2(repoDir), { recursive: true });
|
|
723
|
-
await rm2(repoDir, { recursive: true, force: true });
|
|
724
|
-
await git(dirname2(repoDir), [
|
|
725
|
-
"clone",
|
|
726
|
-
"--no-checkout",
|
|
727
|
-
cloneUrl(ref, input.protocol),
|
|
728
|
-
repoDir
|
|
729
|
-
]);
|
|
730
|
-
} else {
|
|
731
|
-
const wanted = cloneUrl(ref, input.protocol);
|
|
732
|
-
const current = await exec("git", ["config", "--get", "remote.origin.url"], {
|
|
733
|
-
cwd: repoDir,
|
|
734
|
-
env: gitEnv()
|
|
735
|
-
});
|
|
736
|
-
if (current.stdout.trim() !== wanted) {
|
|
737
|
-
await git(repoDir, ["remote", "set-url", "origin", wanted]);
|
|
738
|
-
}
|
|
739
|
-
await git(repoDir, ["fetch", "--prune", "origin"]);
|
|
740
|
-
}
|
|
741
|
-
const baseRef = input.baseRef ?? await defaultBranch(repoDir);
|
|
742
|
-
let start2 = `origin/${baseRef}`;
|
|
743
|
-
if (!await gitOk(repoDir, ["rev-parse", "--verify", "--quiet", `${start2}^{commit}`])) {
|
|
744
|
-
if (!await gitOk(repoDir, ["rev-parse", "--verify", "--quiet", `${baseRef}^{commit}`])) {
|
|
745
|
-
throw new Error(`Base branch ${baseRef} was not found on origin.`);
|
|
746
|
-
}
|
|
747
|
-
start2 = baseRef;
|
|
748
|
-
}
|
|
749
|
-
let baseSha = await git(repoDir, ["rev-parse", `${start2}^{commit}`]);
|
|
750
|
-
let checkout = start2;
|
|
751
|
-
let continuedFrom;
|
|
752
|
-
let setAside;
|
|
753
|
-
const remoteWork = `refs/remotes/origin/${input.workBranch}`;
|
|
754
|
-
if (input.continueBranch && await exists(worktree) && await exec("git", ["rev-parse", "--abbrev-ref", "HEAD"], {
|
|
755
|
-
cwd: worktree,
|
|
756
|
-
env: gitEnv(),
|
|
757
|
-
timeoutMs: 6e4
|
|
758
|
-
}).then((r) => r.code === 0 && r.stdout.trim() === input.workBranch) && // Only when it already has everything pushed to the work branch since: one that fell
|
|
759
|
-
// behind (the run went on elsewhere) would have the agent work on stale code.
|
|
760
|
-
(!await gitOk(repoDir, ["rev-parse", "--verify", "--quiet", `${remoteWork}^{commit}`]) || await exec("git", ["merge-base", "--is-ancestor", remoteWork, "HEAD"], {
|
|
761
|
-
cwd: worktree,
|
|
762
|
-
env: gitEnv(),
|
|
763
|
-
timeoutMs: 6e4
|
|
764
|
-
}).then((r) => r.code === 0))) {
|
|
765
|
-
const forkPoint = await exec("git", ["merge-base", "HEAD", start2], {
|
|
766
|
-
cwd: worktree,
|
|
767
|
-
env: gitEnv(),
|
|
768
|
-
timeoutMs: 6e4
|
|
769
|
-
});
|
|
770
|
-
if (forkPoint.code === 0 && forkPoint.stdout.trim()) baseSha = forkPoint.stdout.trim();
|
|
771
|
-
return { repoDir, worktree, baseRef, baseSha, continuedFrom: "worktree" };
|
|
772
|
-
}
|
|
773
|
-
if (input.continueBranch) {
|
|
774
|
-
const remote = `refs/remotes/origin/${input.workBranch}`;
|
|
775
|
-
const local = `refs/heads/${input.workBranch}`;
|
|
776
|
-
const hasRemote = await gitOk(repoDir, [
|
|
777
|
-
"rev-parse",
|
|
778
|
-
"--verify",
|
|
779
|
-
"--quiet",
|
|
780
|
-
`${remote}^{commit}`
|
|
781
|
-
]);
|
|
782
|
-
const hasLocal = await gitOk(repoDir, [
|
|
783
|
-
"rev-parse",
|
|
784
|
-
"--verify",
|
|
785
|
-
"--quiet",
|
|
786
|
-
`${local}^{commit}`
|
|
787
|
-
]);
|
|
788
|
-
const localAhead = hasLocal && (!hasRemote || await gitOk(repoDir, ["merge-base", "--is-ancestor", remote, local]));
|
|
789
|
-
if (localAhead) {
|
|
790
|
-
checkout = local;
|
|
791
|
-
continuedFrom = "local";
|
|
792
|
-
} else if (hasRemote) {
|
|
793
|
-
checkout = remote;
|
|
794
|
-
continuedFrom = "remote";
|
|
795
|
-
} else {
|
|
796
|
-
continuedFrom = "base";
|
|
797
|
-
}
|
|
798
|
-
if (continuedFrom !== "base") {
|
|
799
|
-
const forkPoint = await exec("git", ["merge-base", checkout, start2], {
|
|
800
|
-
cwd: repoDir,
|
|
801
|
-
env: gitEnv(),
|
|
802
|
-
timeoutMs: 6e4
|
|
803
|
-
});
|
|
804
|
-
if (forkPoint.code === 0 && forkPoint.stdout.trim()) baseSha = forkPoint.stdout.trim();
|
|
805
|
-
checkout = await git(repoDir, ["rev-parse", `${checkout}^{commit}`]);
|
|
806
|
-
}
|
|
807
|
-
}
|
|
808
|
-
if (input.continueBranch && await exists(worktree)) {
|
|
809
|
-
const dirty = await exec("git", ["status", "--porcelain"], {
|
|
810
|
-
cwd: worktree,
|
|
811
|
-
env: gitEnv(),
|
|
812
|
-
timeoutMs: 6e4
|
|
813
|
-
});
|
|
814
|
-
if (dirty.code === 0 && dirty.stdout.trim()) {
|
|
815
|
-
const aside = `${worktree}.kept-${Date.now()}`;
|
|
816
|
-
if (await gitOk(repoDir, ["worktree", "move", worktree, aside])) setAside = aside;
|
|
817
|
-
}
|
|
818
|
-
}
|
|
819
|
-
if (await exists(worktree)) {
|
|
820
|
-
await gitOk(repoDir, ["worktree", "remove", "--force", worktree]);
|
|
821
|
-
await rm2(worktree, { recursive: true, force: true });
|
|
822
|
-
}
|
|
823
|
-
await gitOk(repoDir, ["worktree", "prune"]);
|
|
824
|
-
await mkdir2(input.worktreesDir, { recursive: true });
|
|
825
|
-
await git(repoDir, [
|
|
826
|
-
"worktree",
|
|
827
|
-
"add",
|
|
828
|
-
"--no-track",
|
|
829
|
-
"-B",
|
|
830
|
-
input.workBranch,
|
|
831
|
-
worktree,
|
|
832
|
-
checkout
|
|
833
|
-
]);
|
|
834
|
-
return {
|
|
835
|
-
repoDir,
|
|
836
|
-
worktree,
|
|
837
|
-
baseRef,
|
|
838
|
-
baseSha,
|
|
839
|
-
...continuedFrom ? { continuedFrom } : {},
|
|
840
|
-
...setAside ? { setAside } : {}
|
|
841
|
-
};
|
|
842
|
-
});
|
|
843
|
-
}
|
|
844
|
-
async function defaultBranch(repoDir) {
|
|
845
|
-
const read = async () => {
|
|
846
|
-
const res = await exec("git", ["symbolic-ref", "--short", "refs/remotes/origin/HEAD"], {
|
|
847
|
-
cwd: repoDir,
|
|
848
|
-
env: gitEnv()
|
|
849
|
-
});
|
|
850
|
-
return res.code === 0 ? res.stdout.trim().replace(/^origin\//, "") : null;
|
|
851
|
-
};
|
|
852
|
-
const known = await read();
|
|
853
|
-
if (known) return known;
|
|
854
|
-
await gitOk(repoDir, ["remote", "set-head", "origin", "--auto"]);
|
|
855
|
-
return await read() ?? "main";
|
|
1069
|
+
function normalizeServerUrl(url) {
|
|
1070
|
+
const trimmed = url.trim().replace(/\/+$/, "");
|
|
1071
|
+
return trimmed.replace(/\/api(\/health)?$/, "");
|
|
856
1072
|
}
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
const
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
let committed = false;
|
|
865
|
-
try {
|
|
866
|
-
const status2 = await git(worktree, ["status", "--porcelain"]);
|
|
867
|
-
const dirty = status2.split("\n").some((line) => line && !excluded(line));
|
|
868
|
-
if (dirty) {
|
|
869
|
-
await git(worktree, ["add", "-A"]);
|
|
870
|
-
if (exclude.length) await git(worktree, ["reset", "-q", "--", ...exclude]);
|
|
871
|
-
}
|
|
872
|
-
const staged = dirty && !await gitOk(worktree, ["diff", "--cached", "--quiet"]);
|
|
873
|
-
if (staged) {
|
|
874
|
-
const identity2 = await gitOk(worktree, ["config", "user.email"]) ? [] : [
|
|
875
|
-
"-c",
|
|
876
|
-
"user.name=Discovery Tree runner",
|
|
877
|
-
"-c",
|
|
878
|
-
"user.email=dt-runner@users.noreply.local"
|
|
879
|
-
];
|
|
880
|
-
await git(worktree, [...identity2, "commit", "--no-verify", "-q", "-m", input.message]);
|
|
881
|
-
committed = true;
|
|
882
|
-
}
|
|
883
|
-
} catch (err) {
|
|
884
|
-
return {
|
|
885
|
-
committed,
|
|
886
|
-
pushed: false,
|
|
887
|
-
error: errorText(err, "Committing the work failed"),
|
|
888
|
-
failedAt: "commit"
|
|
889
|
-
};
|
|
1073
|
+
var MAX_SESSIONS_LIMIT = 64;
|
|
1074
|
+
function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPaths(env)) {
|
|
1075
|
+
const mode = file?.permissionMode ?? "acceptEdits";
|
|
1076
|
+
if (!PERMISSION_MODES.includes(mode)) {
|
|
1077
|
+
throw new Error(
|
|
1078
|
+
`permissionMode "${mode}" in ${paths.configFile} is not one of ${PERMISSION_MODES.join(", ")}.`
|
|
1079
|
+
);
|
|
890
1080
|
}
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
} catch (err) {
|
|
897
|
-
return {
|
|
898
|
-
committed,
|
|
899
|
-
pushed: false,
|
|
900
|
-
error: errorText(err, "Pushing the work branch failed"),
|
|
901
|
-
failedAt: "push"
|
|
902
|
-
};
|
|
1081
|
+
const maxSessions = overrides.maxSessions ?? file?.maxSessions ?? DEFAULT_MAX_SESSIONS;
|
|
1082
|
+
if (!Number.isInteger(maxSessions) || maxSessions < 1 || maxSessions > MAX_SESSIONS_LIMIT) {
|
|
1083
|
+
throw new Error(
|
|
1084
|
+
`maxSessions must be a whole number from 1 to ${MAX_SESSIONS_LIMIT} (got ${maxSessions}).`
|
|
1085
|
+
);
|
|
903
1086
|
}
|
|
1087
|
+
const allowed = [
|
|
1088
|
+
...file?.allowedTools ?? DEFAULT_ALLOWED_TOOLS,
|
|
1089
|
+
...file?.extraAllowedTools ?? []
|
|
1090
|
+
];
|
|
1091
|
+
const disallowed = [
|
|
1092
|
+
...file?.disallowedTools ?? [
|
|
1093
|
+
...DEFAULT_DISALLOWED_TOOLS,
|
|
1094
|
+
...configDirRules(paths.configFile)
|
|
1095
|
+
],
|
|
1096
|
+
...file?.extraDisallowedTools ?? []
|
|
1097
|
+
];
|
|
1098
|
+
return {
|
|
1099
|
+
server: normalizeServerUrl(env.DT_SERVER_URL || file?.server || DEFAULT_SERVER_URL),
|
|
1100
|
+
runnerId: file?.runnerId ?? null,
|
|
1101
|
+
token: env.DT_RUNNER_TOKEN || file?.token || null,
|
|
1102
|
+
name: file?.name ?? null,
|
|
1103
|
+
maxSessions,
|
|
1104
|
+
reposDir: overrides.reposDir ?? file?.reposDir ?? join5(paths.dataDir, "repos"),
|
|
1105
|
+
worktreesDir: file?.worktreesDir ?? join5(paths.dataDir, "worktrees"),
|
|
1106
|
+
permissionMode: mode,
|
|
1107
|
+
allowedTools: [...new Set(allowed)],
|
|
1108
|
+
disallowedTools: [...new Set(disallowed)],
|
|
1109
|
+
loadProjectSettings: file?.loadProjectSettings === true,
|
|
1110
|
+
gitProtocol: file?.gitProtocol === "ssh" ? "ssh" : "https",
|
|
1111
|
+
idleTimeoutMs: (file?.idleTimeoutMinutes ?? DEFAULT_IDLE_TIMEOUT_MINUTES) * 6e4,
|
|
1112
|
+
stateDir: paths.stateDir,
|
|
1113
|
+
configFile: paths.configFile
|
|
1114
|
+
};
|
|
904
1115
|
}
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
if (repoDir && await exists(repoDir)) await gitOk(repoDir, ["worktree", "prune"]);
|
|
1116
|
+
|
|
1117
|
+
// src/backoff.ts
|
|
1118
|
+
function backoffDelay(attempt, baseMs = 1e3, maxMs = 6e4) {
|
|
1119
|
+
const ceiling = Math.min(maxMs, baseMs * 2 ** Math.min(attempt, 20));
|
|
1120
|
+
return Math.round(ceiling / 2 + Math.random() * ceiling / 2);
|
|
911
1121
|
}
|
|
912
|
-
function
|
|
913
|
-
|
|
914
|
-
|
|
1122
|
+
function sleep(ms, signal) {
|
|
1123
|
+
return new Promise((resolve) => {
|
|
1124
|
+
if (signal?.aborted) return resolve();
|
|
1125
|
+
const timer = setTimeout(done, ms);
|
|
1126
|
+
function done() {
|
|
1127
|
+
clearTimeout(timer);
|
|
1128
|
+
signal?.removeEventListener("abort", done);
|
|
1129
|
+
resolve();
|
|
1130
|
+
}
|
|
1131
|
+
signal?.addEventListener("abort", done, { once: true });
|
|
1132
|
+
});
|
|
915
1133
|
}
|
|
916
1134
|
|
|
1135
|
+
// src/session-manager.ts
|
|
1136
|
+
import { mkdir as mkdir6, rm as rm5 } from "node:fs/promises";
|
|
1137
|
+
|
|
917
1138
|
// src/fsutil.ts
|
|
918
|
-
import { mkdir as
|
|
1139
|
+
import { mkdir as mkdir4, readFile as readFile3, rename as rename2, writeFile as writeFile3 } from "node:fs/promises";
|
|
919
1140
|
import { dirname as dirname3 } from "node:path";
|
|
920
1141
|
async function writeJsonAtomic(file, value) {
|
|
921
|
-
await
|
|
1142
|
+
await mkdir4(dirname3(file), { recursive: true });
|
|
922
1143
|
const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
923
|
-
await
|
|
924
|
-
await
|
|
1144
|
+
await writeFile3(tmp, JSON.stringify(value), { mode: 384 });
|
|
1145
|
+
await rename2(tmp, file);
|
|
925
1146
|
}
|
|
926
1147
|
async function readJson(file) {
|
|
927
1148
|
try {
|
|
928
|
-
return JSON.parse(await
|
|
1149
|
+
return JSON.parse(await readFile3(file, "utf8"));
|
|
929
1150
|
} catch (err) {
|
|
930
1151
|
if (err.code === "ENOENT") return null;
|
|
931
1152
|
if (err instanceof SyntaxError) return null;
|
|
@@ -1164,214 +1385,186 @@ function takeBatch(pending) {
|
|
|
1164
1385
|
}
|
|
1165
1386
|
|
|
1166
1387
|
// src/session.ts
|
|
1167
|
-
import { spawn as
|
|
1388
|
+
import { spawn as spawn3 } from "node:child_process";
|
|
1168
1389
|
import { basename, dirname as dirname4 } from "node:path";
|
|
1169
1390
|
import { createInterface } from "node:readline";
|
|
1170
1391
|
|
|
1171
|
-
// src/
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
var PUBLISHED_DIR = "published";
|
|
1177
|
-
var IMAGE_EXTENSIONS = /* @__PURE__ */ new Set(["png", "jpg", "jpeg", "gif", "webp"]);
|
|
1178
|
-
var MAX_EVIDENCE_IMAGES = 12;
|
|
1179
|
-
var MAX_EVIDENCE_BYTES = 8 * 1024 * 1024;
|
|
1180
|
-
function evidenceBranch(workBranch) {
|
|
1181
|
-
return `dt-evidence/${workBranch.replace(/%/g, "%25").replace(/\//g, "%2F")}`;
|
|
1182
|
-
}
|
|
1183
|
-
async function ensureEvidenceDir(worktree) {
|
|
1184
|
-
await mkdir4(join4(worktree, EVIDENCE_DIR), { recursive: true });
|
|
1185
|
-
const rel = await git(worktree, ["rev-parse", "--git-path", "info/exclude"]);
|
|
1186
|
-
const file = isAbsolute2(rel) ? rel : join4(worktree, rel);
|
|
1187
|
-
const line = `/${EVIDENCE_DIR}/`;
|
|
1188
|
-
let current = "";
|
|
1189
|
-
try {
|
|
1190
|
-
current = await readFile3(file, "utf8");
|
|
1191
|
-
} catch {
|
|
1192
|
-
}
|
|
1193
|
-
if (current.split("\n").some((l) => l.trim() === line)) return;
|
|
1194
|
-
await mkdir4(join4(file, ".."), { recursive: true });
|
|
1195
|
-
const sep = current && !current.endsWith("\n") ? "\n" : "";
|
|
1196
|
-
await writeFile3(
|
|
1197
|
-
file,
|
|
1198
|
-
`${current}${sep}# Screenshots dt-runner publishes on their own branch
|
|
1199
|
-
${line}
|
|
1200
|
-
`
|
|
1201
|
-
);
|
|
1202
|
-
}
|
|
1203
|
-
async function publishEvidence(input) {
|
|
1204
|
-
const dir = join4(input.worktree, EVIDENCE_DIR);
|
|
1205
|
-
let found;
|
|
1392
|
+
// src/pull-request.ts
|
|
1393
|
+
var PULL_REQUEST_BODY_MAX_CHARS = 6e4;
|
|
1394
|
+
var GH_TIMEOUT_MS = 6e4;
|
|
1395
|
+
var PR_URL_RE = /https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/pull\/\d+/;
|
|
1396
|
+
async function openPullRequest(input, exec2 = exec) {
|
|
1206
1397
|
try {
|
|
1207
|
-
|
|
1398
|
+
const listed = await exec2(
|
|
1399
|
+
"gh",
|
|
1400
|
+
[
|
|
1401
|
+
"pr",
|
|
1402
|
+
"list",
|
|
1403
|
+
"--repo",
|
|
1404
|
+
input.repo,
|
|
1405
|
+
"--head",
|
|
1406
|
+
input.head,
|
|
1407
|
+
"--state",
|
|
1408
|
+
"open",
|
|
1409
|
+
"--json",
|
|
1410
|
+
"url",
|
|
1411
|
+
"--limit",
|
|
1412
|
+
"1"
|
|
1413
|
+
],
|
|
1414
|
+
{ timeoutMs: GH_TIMEOUT_MS }
|
|
1415
|
+
);
|
|
1416
|
+
if (listed.code !== 0) return { status: "failed", error: ghError("pr list", listed) };
|
|
1417
|
+
const existing = PR_URL_RE.exec(listed.stdout)?.[0];
|
|
1418
|
+
if (existing) {
|
|
1419
|
+
const appendError = input.appendIfExisting ? await appendToDescription(existing, input.appendIfExisting, exec2) : null;
|
|
1420
|
+
return { status: "existing", url: existing, ...appendError ? { appendError } : {} };
|
|
1421
|
+
}
|
|
1422
|
+
const created = await exec2(
|
|
1423
|
+
"gh",
|
|
1424
|
+
[
|
|
1425
|
+
"pr",
|
|
1426
|
+
"create",
|
|
1427
|
+
"--repo",
|
|
1428
|
+
input.repo,
|
|
1429
|
+
"--head",
|
|
1430
|
+
input.head,
|
|
1431
|
+
...input.base ? ["--base", input.base] : [],
|
|
1432
|
+
"--title",
|
|
1433
|
+
input.title,
|
|
1434
|
+
"--body-file",
|
|
1435
|
+
"-"
|
|
1436
|
+
],
|
|
1437
|
+
{ timeoutMs: GH_TIMEOUT_MS, input: input.body.slice(0, PULL_REQUEST_BODY_MAX_CHARS) }
|
|
1438
|
+
);
|
|
1439
|
+
const url = PR_URL_RE.exec(created.stdout)?.[0];
|
|
1440
|
+
if (created.code === 0 && url) return { status: "opened", url };
|
|
1441
|
+
if (/no commits between/i.test(created.stderr)) return { status: "no_changes" };
|
|
1442
|
+
return { status: "failed", error: ghError("pr create", created) };
|
|
1208
1443
|
} catch (err) {
|
|
1209
|
-
const
|
|
1210
|
-
return { images: [], skipped: [], error: `Reading the screenshots failed: ${why}` };
|
|
1211
|
-
}
|
|
1212
|
-
const skipped = found.filter((f) => f.size > MAX_EVIDENCE_BYTES).map((f) => f.name);
|
|
1213
|
-
const fitting = found.filter((f) => f.size <= MAX_EVIDENCE_BYTES);
|
|
1214
|
-
skipped.push(...fitting.slice(MAX_EVIDENCE_IMAGES).map((f) => f.name));
|
|
1215
|
-
const files = fitting.slice(0, MAX_EVIDENCE_IMAGES);
|
|
1216
|
-
if (!files.length) return { images: [], skipped, error: null };
|
|
1217
|
-
const branch = evidenceBranch(input.workBranch);
|
|
1218
|
-
let scratch = null;
|
|
1219
|
-
try {
|
|
1220
|
-
assertSafeRef(branch, "Evidence branch");
|
|
1221
|
-
scratch = await mkdtemp(join4(tmpdir(), "dt-evidence-"));
|
|
1222
|
-
const index = join4(scratch, "index");
|
|
1223
|
-
const ref = `refs/heads/${branch}`;
|
|
1224
|
-
const build = async () => {
|
|
1225
|
-
await gitOk2(input.repoDir, ["fetch", "--quiet", "origin", `+${ref}:${ref}`]);
|
|
1226
|
-
const parent = await revParse(input.repoDir, ref);
|
|
1227
|
-
const run = (args) => gitWithIndex(input.repoDir, index, args);
|
|
1228
|
-
await run(parent ? ["read-tree", parent] : ["read-tree", "--empty"]);
|
|
1229
|
-
for (const f of files) {
|
|
1230
|
-
const blob = await git(input.repoDir, ["hash-object", "-w", "--", join4(dir, f.name)]);
|
|
1231
|
-
await run(["update-index", "--add", "--cacheinfo", `100644,${blob},${f.path}`]);
|
|
1232
|
-
}
|
|
1233
|
-
const tree = await run(["write-tree"]);
|
|
1234
|
-
const parentTree = parent ? await git(input.repoDir, ["rev-parse", `${parent}^{tree}`]) : null;
|
|
1235
|
-
if (parent && tree === parentTree) return parent;
|
|
1236
|
-
const made = await git(input.repoDir, [
|
|
1237
|
-
...await identity(input.repoDir),
|
|
1238
|
-
"commit-tree",
|
|
1239
|
-
tree,
|
|
1240
|
-
...parent ? ["-p", parent] : [],
|
|
1241
|
-
"-m",
|
|
1242
|
-
`Screenshots for ${input.workBranch}
|
|
1243
|
-
|
|
1244
|
-
Published by dt-runner for the pull request's review; not part of the change.`
|
|
1245
|
-
]);
|
|
1246
|
-
await git(input.repoDir, ["update-ref", ref, made]);
|
|
1247
|
-
return made;
|
|
1248
|
-
};
|
|
1249
|
-
let commit = await build();
|
|
1250
|
-
try {
|
|
1251
|
-
await git(input.repoDir, ["push", "--quiet", "origin", `${commit}:${ref}`]);
|
|
1252
|
-
} catch {
|
|
1253
|
-
commit = await build();
|
|
1254
|
-
await git(input.repoDir, ["push", "--quiet", "origin", `${commit}:${ref}`]);
|
|
1255
|
-
}
|
|
1256
|
-
await mkdir4(join4(dir, PUBLISHED_DIR), { recursive: true });
|
|
1257
|
-
for (const f of files) {
|
|
1258
|
-
await rename2(join4(dir, f.name), join4(dir, PUBLISHED_DIR, f.name)).catch(() => void 0);
|
|
1259
|
-
}
|
|
1444
|
+
const missing = err?.code === "ENOENT";
|
|
1260
1445
|
return {
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
caption: captionFor(f.name),
|
|
1264
|
-
url: rawFileUrl(input.repo, commit, f.path)
|
|
1265
|
-
})),
|
|
1266
|
-
skipped,
|
|
1267
|
-
error: null
|
|
1446
|
+
status: "failed",
|
|
1447
|
+
error: missing ? "the GitHub CLI (`gh`) is not installed on this computer; see https://cli.github.com" : scrubSecrets(err instanceof Error ? err.message : String(err)).slice(0, 300)
|
|
1268
1448
|
};
|
|
1269
|
-
} catch (err) {
|
|
1270
|
-
const why = err instanceof GitError || err instanceof Error ? err.message : String(err);
|
|
1271
|
-
return { images: [], skipped, error: `Publishing the screenshots failed: ${why}` };
|
|
1272
|
-
} finally {
|
|
1273
|
-
if (scratch) await rm3(scratch, { recursive: true, force: true }).catch(() => void 0);
|
|
1274
1449
|
}
|
|
1275
1450
|
}
|
|
1276
|
-
function
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1451
|
+
async function appendToDescription(url, addition, exec2) {
|
|
1452
|
+
const images = [...addition.matchAll(/\]\((https?:\/\/[^)\s]+)\)/g)].map((m) => m[1]);
|
|
1453
|
+
if (!images.length) return null;
|
|
1454
|
+
const viewed = await exec2("gh", ["pr", "view", url, "--json", "body", "--jq", ".body"], {
|
|
1455
|
+
timeoutMs: GH_TIMEOUT_MS
|
|
1456
|
+
});
|
|
1457
|
+
if (viewed.code !== 0) return ghError("pr view", viewed);
|
|
1458
|
+
const body = viewed.stdout.replace(/\n$/, "");
|
|
1459
|
+
if (images.every((u) => body.includes(u))) return null;
|
|
1460
|
+
const text = addition.replace(/^## Screenshots$/m, "## Screenshots from a later turn");
|
|
1461
|
+
const next = body ? `${body.trimEnd()}
|
|
1462
|
+
|
|
1463
|
+
${text}` : text;
|
|
1464
|
+
if (next.length > PULL_REQUEST_BODY_MAX_CHARS)
|
|
1465
|
+
return "the description is too long to add them to";
|
|
1466
|
+
const edited = await exec2("gh", ["pr", "edit", url, "--body-file", "-"], {
|
|
1467
|
+
timeoutMs: GH_TIMEOUT_MS,
|
|
1468
|
+
input: next
|
|
1469
|
+
});
|
|
1470
|
+
return edited.code === 0 ? null : ghError("pr edit", edited);
|
|
1281
1471
|
}
|
|
1282
|
-
function
|
|
1283
|
-
const
|
|
1284
|
-
|
|
1472
|
+
function ghError(command, res) {
|
|
1473
|
+
const detail = (res.stderr || res.stdout).trim().split("\n").slice(-3).join(" ");
|
|
1474
|
+
if (/gh auth login|not logged in|authentication/i.test(detail)) {
|
|
1475
|
+
return "the GitHub CLI is not signed in; run `gh auth login` on this computer";
|
|
1476
|
+
}
|
|
1477
|
+
return scrubSecrets(`gh ${command} failed${detail ? `: ${detail}` : ""}`).slice(0, 300);
|
|
1285
1478
|
}
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1479
|
+
|
|
1480
|
+
// src/process-tree.ts
|
|
1481
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
1482
|
+
var OWN_PROCESS_GROUP = process.platform !== "win32";
|
|
1483
|
+
var liveGroups = /* @__PURE__ */ new Set();
|
|
1484
|
+
var exitHookInstalled = false;
|
|
1485
|
+
function trackGroup(child) {
|
|
1486
|
+
if (!OWN_PROCESS_GROUP || !child.pid) return;
|
|
1487
|
+
liveGroups.add(child.pid);
|
|
1488
|
+
if (!exitHookInstalled) {
|
|
1489
|
+
exitHookInstalled = true;
|
|
1490
|
+
process.once("exit", () => {
|
|
1491
|
+
for (const pgid of liveGroups) signalGroup(pgid, "SIGKILL");
|
|
1492
|
+
});
|
|
1292
1493
|
}
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
if (!
|
|
1298
|
-
|
|
1299
|
-
out.push({ name: e.name, path: safeName(e.name), size });
|
|
1494
|
+
}
|
|
1495
|
+
function signalTree(child, signal) {
|
|
1496
|
+
if (!child.pid) return;
|
|
1497
|
+
if (OWN_PROCESS_GROUP) {
|
|
1498
|
+
if (!signalGroup(child.pid, signal)) child.kill(signal);
|
|
1499
|
+
return;
|
|
1300
1500
|
}
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1501
|
+
if (signal === "SIGKILL") {
|
|
1502
|
+
const tk = spawn2("taskkill", ["/pid", String(child.pid), "/T", "/F"], {
|
|
1503
|
+
stdio: "ignore",
|
|
1504
|
+
windowsHide: true
|
|
1505
|
+
});
|
|
1506
|
+
let fellBack = false;
|
|
1507
|
+
const fallBack = () => {
|
|
1508
|
+
if (fellBack) return;
|
|
1509
|
+
fellBack = true;
|
|
1510
|
+
child.kill(signal);
|
|
1511
|
+
};
|
|
1512
|
+
tk.on("error", fallBack);
|
|
1513
|
+
tk.on("exit", (code) => {
|
|
1514
|
+
if (code !== 0) fallBack();
|
|
1515
|
+
});
|
|
1516
|
+
return;
|
|
1310
1517
|
}
|
|
1311
|
-
|
|
1312
|
-
}
|
|
1313
|
-
function safeName(name) {
|
|
1314
|
-
const cleaned = name.replace(/[^\w.-]+/g, "-").replace(/^[.-]+/, "");
|
|
1315
|
-
return cleaned || "screenshot.png";
|
|
1316
|
-
}
|
|
1317
|
-
function captionFor(name) {
|
|
1318
|
-
return name.replace(/\.[^.]+$/, "").replace(/[-_]+/g, " ").replace(/[[\]]/g, "").trim();
|
|
1319
|
-
}
|
|
1320
|
-
async function gitOk2(cwd, args) {
|
|
1321
|
-
const res = await exec("git", args, { cwd, env: gitEnv(), timeoutMs: 5 * 6e4 });
|
|
1322
|
-
return res.code === 0;
|
|
1323
|
-
}
|
|
1324
|
-
async function revParse(cwd, ref) {
|
|
1325
|
-
const res = await exec("git", ["rev-parse", "--verify", "-q", `${ref}^{commit}`], {
|
|
1326
|
-
cwd,
|
|
1327
|
-
env: gitEnv(),
|
|
1328
|
-
timeoutMs: 6e4
|
|
1329
|
-
});
|
|
1330
|
-
return res.code === 0 ? res.stdout.trim() : null;
|
|
1518
|
+
child.kill(signal);
|
|
1331
1519
|
}
|
|
1332
|
-
async function
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1520
|
+
async function reapGroup(pgid, graceMs = 2e3) {
|
|
1521
|
+
if (!OWN_PROCESS_GROUP || !pgid) return;
|
|
1522
|
+
try {
|
|
1523
|
+
if (!signalGroup(pgid, "SIGTERM")) return;
|
|
1524
|
+
const deadline = Date.now() + graceMs;
|
|
1525
|
+
while (Date.now() < deadline) {
|
|
1526
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
1527
|
+
if (!signalGroup(pgid, 0)) return;
|
|
1528
|
+
}
|
|
1529
|
+
signalGroup(pgid, "SIGKILL");
|
|
1530
|
+
} finally {
|
|
1531
|
+
liveGroups.delete(pgid);
|
|
1532
|
+
}
|
|
1340
1533
|
}
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1534
|
+
function signalGroup(pgid, signal) {
|
|
1535
|
+
try {
|
|
1536
|
+
process.kill(-pgid, signal);
|
|
1537
|
+
return true;
|
|
1538
|
+
} catch {
|
|
1539
|
+
return false;
|
|
1540
|
+
}
|
|
1348
1541
|
}
|
|
1349
1542
|
|
|
1350
1543
|
// src/session-store.ts
|
|
1351
1544
|
import { mkdir as mkdir5, readdir as readdir2, rm as rm4 } from "node:fs/promises";
|
|
1352
|
-
import { join as
|
|
1545
|
+
import { join as join6 } from "node:path";
|
|
1353
1546
|
var HANDLED_COMMAND_IDS_KEPT = 100;
|
|
1354
1547
|
var SessionStore = class {
|
|
1355
1548
|
constructor(stateDir) {
|
|
1356
1549
|
this.stateDir = stateDir;
|
|
1357
1550
|
}
|
|
1358
1551
|
dir(sessionId) {
|
|
1359
|
-
return
|
|
1552
|
+
return join6(this.stateDir, "sessions", sessionId);
|
|
1360
1553
|
}
|
|
1361
1554
|
outboxFile(sessionId) {
|
|
1362
|
-
return
|
|
1555
|
+
return join6(this.dir(sessionId), "outbox.json");
|
|
1363
1556
|
}
|
|
1364
1557
|
async save(record) {
|
|
1365
1558
|
record.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1366
|
-
await writeJsonAtomic(
|
|
1559
|
+
await writeJsonAtomic(join6(this.dir(record.sessionId), "session.json"), record);
|
|
1367
1560
|
}
|
|
1368
1561
|
async list() {
|
|
1369
|
-
const root =
|
|
1562
|
+
const root = join6(this.stateDir, "sessions");
|
|
1370
1563
|
await mkdir5(root, { recursive: true });
|
|
1371
1564
|
const out = [];
|
|
1372
1565
|
for (const entry of await readdir2(root, { withFileTypes: true })) {
|
|
1373
1566
|
if (!entry.isDirectory()) continue;
|
|
1374
|
-
const rec = await readJson(
|
|
1567
|
+
const rec = await readJson(join6(root, entry.name, "session.json"));
|
|
1375
1568
|
if (rec?.sessionId === entry.name) out.push(rec);
|
|
1376
1569
|
}
|
|
1377
1570
|
return out;
|
|
@@ -1381,7 +1574,7 @@ var SessionStore = class {
|
|
|
1381
1574
|
}
|
|
1382
1575
|
/** Scratch working directory for a session without a repository. */
|
|
1383
1576
|
scratchDir(sessionId) {
|
|
1384
|
-
return
|
|
1577
|
+
return join6(this.stateDir, "scratch", sessionId);
|
|
1385
1578
|
}
|
|
1386
1579
|
};
|
|
1387
1580
|
function assertSafeSessionId(id) {
|
|
@@ -1629,6 +1822,10 @@ var AgentSession = class {
|
|
|
1629
1822
|
*/
|
|
1630
1823
|
resumeRetry = null;
|
|
1631
1824
|
exitWaiters = [];
|
|
1825
|
+
/** Settles once the current process has exited and what it left in its group is gone. */
|
|
1826
|
+
groupReaped = Promise.resolve();
|
|
1827
|
+
/** How long what is left in the group gets after SIGTERM: a stop's grace, or the default. */
|
|
1828
|
+
reapGraceMs;
|
|
1632
1829
|
lastActivity = Date.now();
|
|
1633
1830
|
get sessionId() {
|
|
1634
1831
|
return this.record.sessionId;
|
|
@@ -1701,11 +1898,17 @@ var AgentSession = class {
|
|
|
1701
1898
|
}, this.deps.interruptGraceMs ?? 5e3);
|
|
1702
1899
|
return true;
|
|
1703
1900
|
}
|
|
1704
|
-
/**
|
|
1901
|
+
/**
|
|
1902
|
+
* Ends the process (closing stdin first, so Claude Code saves its session and exits), and
|
|
1903
|
+
* with it everything it started: the background commands still in its process group are
|
|
1904
|
+
* ended once it has exited, and SIGTERM and SIGKILL go to the whole group.
|
|
1905
|
+
*/
|
|
1705
1906
|
async stop(reason, graceMs = 5e3) {
|
|
1706
1907
|
const child = this.child;
|
|
1707
1908
|
if (!child) return;
|
|
1909
|
+
const reaped = this.groupReaped;
|
|
1708
1910
|
this.stopping = reason;
|
|
1911
|
+
this.reapGraceMs = graceMs;
|
|
1709
1912
|
const exited = new Promise((resolve) => this.exitWaiters.push(resolve));
|
|
1710
1913
|
child.stdin.end();
|
|
1711
1914
|
const timedOut = await Promise.race([
|
|
@@ -1713,11 +1916,12 @@ var AgentSession = class {
|
|
|
1713
1916
|
delay(graceMs).then(() => true)
|
|
1714
1917
|
]);
|
|
1715
1918
|
if (timedOut && this.child === child) {
|
|
1716
|
-
child
|
|
1919
|
+
signalTree(child, "SIGTERM");
|
|
1717
1920
|
const again = await Promise.race([exited.then(() => false), delay(graceMs).then(() => true)]);
|
|
1718
|
-
if (again && this.child === child) child
|
|
1921
|
+
if (again && this.child === child) signalTree(child, "SIGKILL");
|
|
1719
1922
|
await Promise.race([exited, delay(graceMs)]);
|
|
1720
1923
|
}
|
|
1924
|
+
if (child.exitCode !== null || child.signalCode !== null) await reaped;
|
|
1721
1925
|
await this.lineChain;
|
|
1722
1926
|
}
|
|
1723
1927
|
/** Waits until every stdout line seen so far (and any turn end it caused) is handled. */
|
|
@@ -1783,18 +1987,25 @@ ${text}`;
|
|
|
1783
1987
|
resume: this.record.claudeSessionId,
|
|
1784
1988
|
appendSystemPrompt: runnerSystemPrompt({
|
|
1785
1989
|
workBranch: this.record.workBranch,
|
|
1786
|
-
baseRef: this.record.baseRef
|
|
1990
|
+
baseRef: this.record.baseRef,
|
|
1991
|
+
cwd: this.record.cwd
|
|
1787
1992
|
}),
|
|
1788
1993
|
features
|
|
1789
1994
|
});
|
|
1790
|
-
const child =
|
|
1995
|
+
const child = spawn3(bin, args, {
|
|
1791
1996
|
cwd: this.record.cwd,
|
|
1792
1997
|
env: process.env,
|
|
1793
1998
|
stdio: ["pipe", "pipe", "pipe"],
|
|
1794
|
-
windowsHide: true
|
|
1999
|
+
windowsHide: true,
|
|
2000
|
+
// A process group of its own, so what it starts can be ended with it. It also means
|
|
2001
|
+
// the terminal's Ctrl+C no longer reaches it: the runner's shutdown stops it.
|
|
2002
|
+
detached: OWN_PROCESS_GROUP
|
|
1795
2003
|
});
|
|
1796
2004
|
await new Promise((resolve, reject) => {
|
|
1797
|
-
child.once("spawn", () =>
|
|
2005
|
+
child.once("spawn", () => {
|
|
2006
|
+
trackGroup(child);
|
|
2007
|
+
resolve();
|
|
2008
|
+
});
|
|
1798
2009
|
child.once(
|
|
1799
2010
|
"error",
|
|
1800
2011
|
(err) => reject(new Error(`Could not start Claude Code (${bin}): ${err.message}`))
|
|
@@ -1802,6 +2013,7 @@ ${text}`;
|
|
|
1802
2013
|
});
|
|
1803
2014
|
this.child = child;
|
|
1804
2015
|
this.stopping = null;
|
|
2016
|
+
this.reapGraceMs = void 0;
|
|
1805
2017
|
this.stderrTail = "";
|
|
1806
2018
|
this.sawResultSinceSpawn = false;
|
|
1807
2019
|
this.spawnedWithResume = !!this.record.claudeSessionId;
|
|
@@ -1810,6 +2022,9 @@ ${text}`;
|
|
|
1810
2022
|
`session ${this.sessionId}: Claude Code started${this.record.claudeSessionId ? " (resumed)" : ""}`,
|
|
1811
2023
|
{ pid: child.pid }
|
|
1812
2024
|
);
|
|
2025
|
+
this.groupReaped = new Promise(
|
|
2026
|
+
(resolve) => child.once("exit", () => void reapGroup(child.pid, this.reapGraceMs).then(resolve))
|
|
2027
|
+
);
|
|
1813
2028
|
child.stdin.on("error", () => void 0);
|
|
1814
2029
|
child.stderr.setEncoding("utf8").on("data", (d) => {
|
|
1815
2030
|
this.stderrTail = (this.stderrTail + d).slice(-4e3);
|
|
@@ -1913,15 +2128,20 @@ ${text}`;
|
|
|
1913
2128
|
});
|
|
1914
2129
|
return "";
|
|
1915
2130
|
});
|
|
2131
|
+
const failed = turnFailed || push.failed;
|
|
2132
|
+
const text = withScreenshots(
|
|
2133
|
+
interrupted ? turn.isError ? null : turn.text : turn.text,
|
|
2134
|
+
screenshots
|
|
2135
|
+
);
|
|
2136
|
+
const prUrl = push.branch ? await this.openPullRequest(text, screenshots) : null;
|
|
1916
2137
|
this.record.turnActive = false;
|
|
1917
2138
|
await this.deps.store.save(this.record);
|
|
1918
|
-
const failed = turnFailed || push.failed;
|
|
1919
|
-
const text = interrupted ? turn.isError ? null : turn.text : turn.text;
|
|
1920
2139
|
this.emit({
|
|
1921
2140
|
type: "result",
|
|
1922
2141
|
status: failed ? "failed" : "idle",
|
|
1923
|
-
text
|
|
2142
|
+
text,
|
|
1924
2143
|
branch: push.branch,
|
|
2144
|
+
...prUrl ? { prUrl } : {},
|
|
1925
2145
|
// The turn's work is only on this computer (committing or pushing it failed): a
|
|
1926
2146
|
// continuation of the run must come back to this runner to find it.
|
|
1927
2147
|
...push.failed ? { unpushedWork: true } : {},
|
|
@@ -1935,6 +2155,55 @@ ${text}`;
|
|
|
1935
2155
|
{ pushed: push.branch ?? void 0 }
|
|
1936
2156
|
);
|
|
1937
2157
|
}
|
|
2158
|
+
/**
|
|
2159
|
+
* When the runner opens this session's pull request (the GitHub App cannot), opens it from
|
|
2160
|
+
* the work branch with the person's `gh`, or finds the one already open; its URL, or null.
|
|
2161
|
+
* A failure is said in the conversation, and the server then shows the branch instead.
|
|
2162
|
+
*/
|
|
2163
|
+
async openPullRequest(text, screenshots) {
|
|
2164
|
+
const { pullRequest, workBranch, repository, baseRef } = this.record;
|
|
2165
|
+
const repo = parseRepoUrl(repository ?? "");
|
|
2166
|
+
if (!pullRequest || !workBranch || !repo) return null;
|
|
2167
|
+
const body = [
|
|
2168
|
+
text?.trim() || "Work by the Claude Code (local) agent.",
|
|
2169
|
+
"",
|
|
2170
|
+
"---",
|
|
2171
|
+
pullRequest.footer
|
|
2172
|
+
].join("\n");
|
|
2173
|
+
const outcome = await (this.deps.openPullRequest ?? openPullRequest)({
|
|
2174
|
+
repo: `${repo.owner}/${repo.repo}`,
|
|
2175
|
+
head: workBranch,
|
|
2176
|
+
base: baseRef,
|
|
2177
|
+
title: pullRequest.title,
|
|
2178
|
+
body,
|
|
2179
|
+
// A pull request already open keeps its description; this turn's screenshots join it.
|
|
2180
|
+
appendIfExisting: screenshots || null
|
|
2181
|
+
});
|
|
2182
|
+
if (outcome.status === "opened" || outcome.status === "existing") {
|
|
2183
|
+
if (outcome.appendError) {
|
|
2184
|
+
this.emit({
|
|
2185
|
+
type: "error",
|
|
2186
|
+
message: `This turn's screenshots were not added to the pull request description: ${outcome.appendError}.`,
|
|
2187
|
+
retryable: false
|
|
2188
|
+
});
|
|
2189
|
+
}
|
|
2190
|
+
if (outcome.status === "opened") {
|
|
2191
|
+
this.deps.logger.info(`session ${this.sessionId}: opened ${outcome.url}`);
|
|
2192
|
+
}
|
|
2193
|
+
return outcome.url;
|
|
2194
|
+
}
|
|
2195
|
+
if (outcome.status === "failed") {
|
|
2196
|
+
this.deps.logger.warn(
|
|
2197
|
+
`session ${this.sessionId}: could not open the pull request: ${outcome.error}`
|
|
2198
|
+
);
|
|
2199
|
+
this.emit({
|
|
2200
|
+
type: "error",
|
|
2201
|
+
message: `The runner could not open the pull request for ${workBranch}: ${outcome.error}.`,
|
|
2202
|
+
retryable: false
|
|
2203
|
+
});
|
|
2204
|
+
}
|
|
2205
|
+
return null;
|
|
2206
|
+
}
|
|
1938
2207
|
/** The screenshot folder exists and is kept out of git before the agent can use it. */
|
|
1939
2208
|
async prepareEvidenceDir() {
|
|
1940
2209
|
if (!this.record.workBranch || !this.record.repoDir) return;
|
|
@@ -2287,6 +2556,7 @@ var SessionManager = class {
|
|
|
2287
2556
|
repoDir: wt.repoDir,
|
|
2288
2557
|
repository: cmd.repository.url,
|
|
2289
2558
|
workBranch: cmd.repository.workBranch,
|
|
2559
|
+
...cmd.pullRequest ? { pullRequest: cmd.pullRequest } : {},
|
|
2290
2560
|
baseRef: wt.baseRef,
|
|
2291
2561
|
baseSha: wt.baseSha,
|
|
2292
2562
|
// A reused kept worktree still holds the uncommitted changes it was kept for: keep
|
|
@@ -2478,7 +2748,8 @@ var SessionManager = class {
|
|
|
2478
2748
|
disallowedTools: this.opts.config.disallowedTools ?? [],
|
|
2479
2749
|
loadProjectSettings: this.opts.config.loadProjectSettings ?? false,
|
|
2480
2750
|
interruptGraceMs: this.opts.interruptGraceMs,
|
|
2481
|
-
onClaudeSignIn: this.opts.onClaudeSignIn
|
|
2751
|
+
onClaudeSignIn: this.opts.onClaudeSignIn,
|
|
2752
|
+
openPullRequest: this.opts.openPullRequest
|
|
2482
2753
|
});
|
|
2483
2754
|
}
|
|
2484
2755
|
};
|
|
@@ -2613,8 +2884,13 @@ var RunnerDaemon = class {
|
|
|
2613
2884
|
protocolVersion: RUNNER_PROTOCOL_VERSION,
|
|
2614
2885
|
runnerVersion: RUNNER_VERSION,
|
|
2615
2886
|
platform: RUNNER_PLATFORM,
|
|
2616
|
-
// This runner continues closed sessions (`start_session` with `resume`)
|
|
2617
|
-
|
|
2887
|
+
// This runner continues closed sessions (`start_session` with `resume`), and opens
|
|
2888
|
+
// pull requests itself when asked (`start_session` with `pullRequest`).
|
|
2889
|
+
agent: {
|
|
2890
|
+
...await this.agent(),
|
|
2891
|
+
resumesClosedSessions: true,
|
|
2892
|
+
opensPullRequests: true
|
|
2893
|
+
},
|
|
2618
2894
|
activeSessionIds: this.manager.activeSessionIds(),
|
|
2619
2895
|
maxConcurrentSessions: this.opts.config.maxSessions
|
|
2620
2896
|
});
|
|
@@ -2766,13 +3042,13 @@ async function runDoctor(env = process.env) {
|
|
|
2766
3042
|
checks.push({
|
|
2767
3043
|
name: "GitHub CLI",
|
|
2768
3044
|
level: res.code === 0 ? "ok" : "warn",
|
|
2769
|
-
detail: res.code === 0 ? "signed in:
|
|
3045
|
+
detail: res.code === 0 ? "signed in: pull requests can be opened as you, and the agent can read them" : "not signed in: run `gh auth login` so pull requests can be opened as you"
|
|
2770
3046
|
});
|
|
2771
3047
|
} catch {
|
|
2772
3048
|
checks.push({
|
|
2773
3049
|
name: "GitHub CLI",
|
|
2774
3050
|
level: "warn",
|
|
2775
|
-
detail: "not installed (no `gh` on PATH):
|
|
3051
|
+
detail: "not installed (no `gh` on PATH): pull requests cannot be opened as you; see https://cli.github.com"
|
|
2776
3052
|
});
|
|
2777
3053
|
}
|
|
2778
3054
|
const bin = await findClaude(env);
|
|
@@ -2824,9 +3100,9 @@ function formatChecks(checks) {
|
|
|
2824
3100
|
|
|
2825
3101
|
// src/lock.ts
|
|
2826
3102
|
import { mkdir as mkdir7, open, readFile as readFile4, rm as rm6 } from "node:fs/promises";
|
|
2827
|
-
import { join as
|
|
3103
|
+
import { join as join7 } from "node:path";
|
|
2828
3104
|
function lockFile(stateDir) {
|
|
2829
|
-
return
|
|
3105
|
+
return join7(stateDir, "daemon.pid");
|
|
2830
3106
|
}
|
|
2831
3107
|
function pidAlive(pid) {
|
|
2832
3108
|
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
@@ -2882,7 +3158,7 @@ async function acquireDaemonLock(stateDir, pid = process.pid) {
|
|
|
2882
3158
|
}
|
|
2883
3159
|
|
|
2884
3160
|
// src/pairing.ts
|
|
2885
|
-
import { spawn as
|
|
3161
|
+
import { spawn as spawn4 } from "node:child_process";
|
|
2886
3162
|
async function pair(api, opts) {
|
|
2887
3163
|
const start2 = await api.startPairing({ name: opts.name, platform: RUNNER_PLATFORM });
|
|
2888
3164
|
opts.ui.showCode(start2.userCode, start2.verificationUrl, start2.expiresInSeconds);
|
|
@@ -2946,7 +3222,7 @@ function openUrl(url) {
|
|
|
2946
3222
|
if (!/^https?:\/\//i.test(url)) return;
|
|
2947
3223
|
const [cmd, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", url]] : ["xdg-open", [url]];
|
|
2948
3224
|
try {
|
|
2949
|
-
const child =
|
|
3225
|
+
const child = spawn4(cmd, args, { stdio: "ignore", detached: true, windowsHide: true });
|
|
2950
3226
|
child.on("error", () => void 0);
|
|
2951
3227
|
child.unref();
|
|
2952
3228
|
} catch {
|
|
@@ -3140,6 +3416,7 @@ async function start(opts) {
|
|
|
3140
3416
|
};
|
|
3141
3417
|
process.on("SIGINT", onSignal);
|
|
3142
3418
|
process.on("SIGTERM", onSignal);
|
|
3419
|
+
process.on("SIGHUP", onSignal);
|
|
3143
3420
|
let exit;
|
|
3144
3421
|
try {
|
|
3145
3422
|
exit = await daemon.run();
|