@speculoai/baton 0.6.2 → 0.8.0
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 +3 -1
- package/README.zh-CN.md +3 -1
- package/dist/adapters/agy.js +3 -2
- package/dist/adapters/claude.js +7 -3
- package/dist/adapters/common.js +23 -11
- package/dist/adapters/cursor.js +2 -2
- package/dist/cli.js +58 -34
- package/dist/install.js +2 -2
- package/dist/mcp.js +13 -3
- package/dist/process.js +18 -0
- package/dist/report.js +191 -0
- package/dist/rules.js +4 -8
- package/dist/rulesync-setup.js +3 -3
- package/dist/scope.js +12 -3
- package/dist/store.js +20 -1
- package/dist/supervisor.js +81 -3
- package/dist/tail.js +2 -0
- package/dist/tasks.js +86 -17
- package/dist/usage.js +182 -0
- package/dist/worktree.js +132 -11
- package/package.json +6 -2
package/dist/rules.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
2
|
import path from "node:path";
|
|
3
|
-
import {
|
|
3
|
+
import { spawnSync } from "node:child_process";
|
|
4
|
+
import spawn from "cross-spawn";
|
|
4
5
|
import { which } from "./adapters/common.js";
|
|
5
6
|
import { redact } from "./redact.js";
|
|
6
7
|
const ALL_FEATURES = ["rules", "mcp", "subagents", "skills", "hooks", "permissions", "checks"];
|
|
@@ -233,14 +234,9 @@ function expandFeatures(value) {
|
|
|
233
234
|
/** Locate rulesync: project node_modules → main repo node_modules → PATH. Never uses npx. */
|
|
234
235
|
export function resolveRulesync(repoRoot, mainRepoRoot, env = process.env) {
|
|
235
236
|
for (const root of [repoRoot, mainRepoRoot].filter(Boolean)) {
|
|
236
|
-
const local = path.join(root, "node_modules", ".bin"
|
|
237
|
-
|
|
238
|
-
fs.accessSync(local, fs.constants.X_OK);
|
|
237
|
+
const local = which(["rulesync"], { PATH: path.join(root, "node_modules", ".bin") });
|
|
238
|
+
if (local)
|
|
239
239
|
return local;
|
|
240
|
-
}
|
|
241
|
-
catch {
|
|
242
|
-
// try next
|
|
243
|
-
}
|
|
244
240
|
}
|
|
245
241
|
return which(["rulesync"], env);
|
|
246
242
|
}
|
package/dist/rulesync-setup.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
2
|
import path from "node:path";
|
|
3
|
-
import {
|
|
3
|
+
import { spawnSync } from "node:child_process";
|
|
4
|
+
import spawn from "cross-spawn";
|
|
4
5
|
import { adapters } from "./adapters/index.js";
|
|
5
6
|
import { which } from "./adapters/common.js";
|
|
6
7
|
import { redact } from "./redact.js";
|
|
@@ -199,8 +200,7 @@ export async function rulesInit(input) {
|
|
|
199
200
|
if (choice === "project" && projectUnavailable) {
|
|
200
201
|
return { ...base, status: "failed", detail: `Cannot install rulesync into the project: ${projectUnavailable}` };
|
|
201
202
|
}
|
|
202
|
-
const
|
|
203
|
-
const command = choice === "project" ? [npm, "install", "-D", "rulesync"] : [npm, "install", "-g", "rulesync"];
|
|
203
|
+
const command = choice === "project" ? ["npm", "install", "-D", "rulesync"] : ["npm", "install", "-g", "rulesync"];
|
|
204
204
|
if (input.dryRun)
|
|
205
205
|
return { ...base, status: "planned", install: { choice, ok: false, command } };
|
|
206
206
|
prompt?.step?.(`Installing rulesync (${command.slice(1).join(" ")})…`);
|
package/dist/scope.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
2
|
import path from "node:path";
|
|
3
|
+
import picomatch from "picomatch";
|
|
3
4
|
const HAS_WILDCARD = /[*?[\]]/;
|
|
4
5
|
export function validateScopeGlob(glob) {
|
|
5
6
|
if (!glob || !glob.trim())
|
|
@@ -40,7 +41,8 @@ export function pathInScope(filePath, globs, opts = {}) {
|
|
|
40
41
|
if (!glob)
|
|
41
42
|
continue;
|
|
42
43
|
if (hasWildcard(glob)) {
|
|
43
|
-
|
|
44
|
+
// dot: `dir/**` must cover dotfiles like `.env.example` (#72); path.matchesGlob cannot opt in.
|
|
45
|
+
if (picomatch.isMatch(file, glob, { dot: true }))
|
|
44
46
|
return true;
|
|
45
47
|
continue;
|
|
46
48
|
}
|
|
@@ -64,8 +66,15 @@ export function findScopeViolations(paths, globs, opts = {}) {
|
|
|
64
66
|
}
|
|
65
67
|
/** Map repo-root-relative git paths into task-cwd-relative paths; cwd escapes → `../…`. */
|
|
66
68
|
export function relativizeToTaskCwd(repoRelativePaths, repoRoot, cwd) {
|
|
67
|
-
|
|
68
|
-
const
|
|
69
|
+
// git prints the long, real path; cwd may arrive as a Windows 8.3 short name (RUNNER~1) or a symlink.
|
|
70
|
+
const real = (dir) => { try {
|
|
71
|
+
return fs.realpathSync.native(dir);
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
return path.resolve(dir);
|
|
75
|
+
} };
|
|
76
|
+
const root = real(repoRoot);
|
|
77
|
+
const base = real(cwd);
|
|
69
78
|
return repoRelativePaths.map((rel) => {
|
|
70
79
|
const abs = path.resolve(root, rel);
|
|
71
80
|
return normalizeRel(path.relative(base, abs));
|
package/dist/store.js
CHANGED
|
@@ -7,6 +7,10 @@ import { isAlive } from "./process.js";
|
|
|
7
7
|
export function batonHome() {
|
|
8
8
|
return path.resolve(process.env.BATON_HOME || path.join(os.homedir(), ".baton"));
|
|
9
9
|
}
|
|
10
|
+
/** A cancel request is a file, not a signal: Windows cannot deliver one, and a file also survives a supervisor that has not started yet. One per turn, so a later reply is not hit by an old request. */
|
|
11
|
+
export function cancelRequestPath(id, turn) {
|
|
12
|
+
return path.join(taskDir(id), `cancel_requested.${turn}`);
|
|
13
|
+
}
|
|
10
14
|
export function taskDir(id) {
|
|
11
15
|
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id))
|
|
12
16
|
throw new Error("task_id must be a UUID.");
|
|
@@ -20,11 +24,26 @@ export function ensureTask(id) {
|
|
|
20
24
|
}
|
|
21
25
|
return dir;
|
|
22
26
|
}
|
|
27
|
+
// Windows refuses to replace a file another process has open (EPERM/EBUSY/EACCES), and `start` polls meta.json while the supervisor rewrites it.
|
|
28
|
+
// Readers hold it for microseconds, so a short bounded retry is enough. POSIX never needs it.
|
|
29
|
+
function renameReplacing(from, to) {
|
|
30
|
+
for (let attempt = 0;; attempt++) {
|
|
31
|
+
try {
|
|
32
|
+
return fs.renameSync(from, to);
|
|
33
|
+
}
|
|
34
|
+
catch (error) {
|
|
35
|
+
const code = error.code;
|
|
36
|
+
if (process.platform !== "win32" || (code !== "EPERM" && code !== "EBUSY" && code !== "EACCES") || attempt >= 20)
|
|
37
|
+
throw error;
|
|
38
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
23
42
|
function writeJson(file, value) {
|
|
24
43
|
const tmp = `${file}.${randomUUID()}.tmp`;
|
|
25
44
|
try {
|
|
26
45
|
fs.writeFileSync(tmp, JSON.stringify(value), { mode: 0o600, flag: "wx" });
|
|
27
|
-
|
|
46
|
+
renameReplacing(tmp, file);
|
|
28
47
|
}
|
|
29
48
|
finally {
|
|
30
49
|
fs.rmSync(tmp, { force: true });
|
package/dist/supervisor.js
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
2
|
import path from "node:path";
|
|
3
|
-
import
|
|
3
|
+
import spawn from "cross-spawn";
|
|
4
4
|
import { createInterface } from "node:readline";
|
|
5
5
|
import { getAdapter } from "./adapters/index.js";
|
|
6
6
|
import { buildPrompt, interpret } from "./contract.js";
|
|
7
7
|
import { baselineToSnapshot, gitChanges, gitRepoRoot, gitSnapshot, pathsSinceBaseline } from "./git.js";
|
|
8
8
|
import { applyScopePolicy, findScopeViolations, isDirUnderCwd, relativizeToTaskCwd } from "./scope.js";
|
|
9
9
|
import { resolveRulesync, rulesGitRoot, rulesyncCheck } from "./rules.js";
|
|
10
|
-
import { appendEvent, hasTurnEnded, readMeta, writeMeta, readTurn, writeTurn, taskDir, lockTask } from "./store.js";
|
|
10
|
+
import { appendEvent, hasTurnEnded, readMeta, writeMeta, readTurn, writeTurn, taskDir, cancelRequestPath, lockTask } from "./store.js";
|
|
11
11
|
import { redact } from "./redact.js";
|
|
12
12
|
import { killGroup } from "./process.js";
|
|
13
|
+
const CHECK_TAIL = 4000;
|
|
13
14
|
const QUOTA_PHRASES = ["usage limit", "quota exceeded", "rate limit"];
|
|
14
15
|
function withoutHtml(text) {
|
|
15
16
|
return String(text || "")
|
|
@@ -57,6 +58,8 @@ function failureSummary(stdout, stderr) {
|
|
|
57
58
|
return reason.slice(-8192);
|
|
58
59
|
return (withoutHtml(stderr) || withoutHtml(stdout)).slice(-8192);
|
|
59
60
|
}
|
|
61
|
+
// Only POSIX needs a process group (killGroup). On Windows a detached child under a .cmd shim never produces output, and taskkill /T finds the tree through parent pids anyway.
|
|
62
|
+
const DETACHED = process.platform !== "win32";
|
|
60
63
|
export async function supervise(id) {
|
|
61
64
|
// Test hook: simulate a slow ("<ms>") or crashing ("exit") supervisor start.
|
|
62
65
|
const hook = process.env.BATON_TEST_SUPERVISE_START;
|
|
@@ -90,6 +93,13 @@ export async function supervise(id) {
|
|
|
90
93
|
};
|
|
91
94
|
const cancel = () => stop("cancelled");
|
|
92
95
|
process.on("SIGTERM", cancel);
|
|
96
|
+
// The request file is the portable path (Windows has no signal to send); SIGTERM only makes POSIX react sooner.
|
|
97
|
+
const cancelFile = cancelRequestPath(id, meta.turn);
|
|
98
|
+
const cancelWatch = setInterval(() => { if (fs.existsSync(cancelFile)) {
|
|
99
|
+
clearInterval(cancelWatch);
|
|
100
|
+
cancel();
|
|
101
|
+
} }, 250);
|
|
102
|
+
cancelWatch.unref();
|
|
93
103
|
try {
|
|
94
104
|
meta.supervisor_pid = process.pid;
|
|
95
105
|
meta.heartbeat_at = new Date().toISOString();
|
|
@@ -110,6 +120,55 @@ export async function supervise(id) {
|
|
|
110
120
|
};
|
|
111
121
|
emit({ type: "turn_started", author: turn.author, prompt_preview: redact(turn.prompt).slice(0, 200) });
|
|
112
122
|
const heartbeat = setInterval(() => { meta.heartbeat_at = new Date().toISOString(); save(); }, 10_000);
|
|
123
|
+
// Run the --check command in its own process group. Cancel reaches it through childPid; the idle limit only kills the check.
|
|
124
|
+
const runCheck = async (command) => {
|
|
125
|
+
const startedCheck = Date.now();
|
|
126
|
+
const file = path.join(taskDir(id), "raw", `${meta.turn}.check.log`);
|
|
127
|
+
fs.writeFileSync(file, "", { mode: 0o600 });
|
|
128
|
+
let output = "";
|
|
129
|
+
let lastOutput = startedCheck;
|
|
130
|
+
let idle = false;
|
|
131
|
+
let code = null;
|
|
132
|
+
// The worker's heartbeat has already stopped; without this a check longer than 30s looks orphaned and gets killed.
|
|
133
|
+
const beat = setInterval(() => { meta.heartbeat_at = new Date().toISOString(); save(); }, 10_000);
|
|
134
|
+
let idleTimer;
|
|
135
|
+
try {
|
|
136
|
+
const child = spawn(command, { shell: true, cwd: meta.cwd, env: { ...process.env, BATON_DELEGATION: "1" }, detached: DETACHED, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] });
|
|
137
|
+
childPid = child.pid ?? null;
|
|
138
|
+
meta.child_pid = childPid;
|
|
139
|
+
save();
|
|
140
|
+
if (stopped)
|
|
141
|
+
killGroup(childPid);
|
|
142
|
+
const onData = (chunk) => {
|
|
143
|
+
lastOutput = Date.now();
|
|
144
|
+
fs.appendFileSync(file, chunk);
|
|
145
|
+
output = (output + chunk.toString()).slice(-200_000);
|
|
146
|
+
};
|
|
147
|
+
child.stdout.on("data", onData);
|
|
148
|
+
child.stderr.on("data", onData);
|
|
149
|
+
idleTimer = setInterval(() => {
|
|
150
|
+
if (Date.now() - lastOutput < meta.idle_timeout_s * 1000)
|
|
151
|
+
return;
|
|
152
|
+
idle = true;
|
|
153
|
+
try {
|
|
154
|
+
killGroup(childPid);
|
|
155
|
+
}
|
|
156
|
+
catch { /* already gone */ }
|
|
157
|
+
}, 50);
|
|
158
|
+
code = await new Promise((resolve) => {
|
|
159
|
+
child.once("error", (error) => { output += `\n${error.message}`; resolve(null); });
|
|
160
|
+
child.once("close", resolve);
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
finally {
|
|
164
|
+
clearInterval(beat);
|
|
165
|
+
clearInterval(idleTimer);
|
|
166
|
+
}
|
|
167
|
+
const result = { command, exit_code: code, duration_ms: Date.now() - startedCheck, output_tail: redact(output).slice(-CHECK_TAIL) };
|
|
168
|
+
if (!stopped)
|
|
169
|
+
result.status = idle ? "timed_out" : code === 0 ? "passed" : "failed";
|
|
170
|
+
return result;
|
|
171
|
+
};
|
|
113
172
|
// rulesync --check before the idle timer so its duration does not count against the worker.
|
|
114
173
|
if (meta.turn === 1 && meta.rules?.rulesync?.status === "pending") {
|
|
115
174
|
const repoRoot = rulesGitRoot(meta.cwd) ?? meta.cwd;
|
|
@@ -173,7 +232,7 @@ export async function supervise(id) {
|
|
|
173
232
|
fs.writeFileSync(spec.lastMessagePath, "", { mode: 0o600, flag: "wx" });
|
|
174
233
|
lastMessageCreated = true;
|
|
175
234
|
}
|
|
176
|
-
const child = spawn(spec.command, spec.args, { cwd: meta.cwd, env: { ...process.env, BATON_DELEGATION: "1" }, detached: true, stdio: [spec.stdin == null ? "ignore" : "pipe", "pipe", "pipe"] });
|
|
235
|
+
const child = spawn(spec.command, spec.args, { cwd: meta.cwd, env: { ...process.env, BATON_DELEGATION: "1" }, detached: DETACHED, windowsHide: true, stdio: [spec.stdin == null ? "ignore" : "pipe", "pipe", "pipe"] });
|
|
177
236
|
childPid = child.pid ?? null;
|
|
178
237
|
meta.child_pid = childPid;
|
|
179
238
|
if (stopped)
|
|
@@ -327,6 +386,24 @@ export async function supervise(id) {
|
|
|
327
386
|
}
|
|
328
387
|
}
|
|
329
388
|
}
|
|
389
|
+
if (final === "success" && meta.check_command && !stopped) {
|
|
390
|
+
// Keep waiters blocked: the turn is not decided until the check ends.
|
|
391
|
+
meta.status = "running";
|
|
392
|
+
emit({ type: "check_started", command: redact(meta.check_command).slice(0, 200) });
|
|
393
|
+
const check = await runCheck(meta.check_command);
|
|
394
|
+
emit({ type: "check_ended", status: check.status ?? "cancelled", exit_code: check.exit_code });
|
|
395
|
+
turn.check = check;
|
|
396
|
+
meta.check = check;
|
|
397
|
+
if (stopped === "cancelled") {
|
|
398
|
+
final = "cancelled";
|
|
399
|
+
meta.summary = "Cancelled.";
|
|
400
|
+
}
|
|
401
|
+
else if (check.status !== "passed") {
|
|
402
|
+
final = "check_failed";
|
|
403
|
+
meta.summary = `check_failed: ${check.status === "timed_out" ? "timed out" : `exit ${check.exit_code}`}\n${check.output_tail}`.slice(0, 8192);
|
|
404
|
+
}
|
|
405
|
+
meta.status = final;
|
|
406
|
+
}
|
|
330
407
|
delete meta.stop_reason;
|
|
331
408
|
turn.status = final;
|
|
332
409
|
turn.summary = meta.summary;
|
|
@@ -338,4 +415,5 @@ export async function supervise(id) {
|
|
|
338
415
|
else
|
|
339
416
|
emit({ type: "turn_ended", status: final, exit_code: code });
|
|
340
417
|
process.off("SIGTERM", cancel);
|
|
418
|
+
clearInterval(cancelWatch);
|
|
341
419
|
}
|
package/dist/tail.js
CHANGED
|
@@ -13,6 +13,8 @@ export function formatEvent(event) {
|
|
|
13
13
|
case "tool_result": return `${prefix} ${event.name} ${event.ok ? "ok" : "failed"}: ${event.detail}`;
|
|
14
14
|
case "error": return `${prefix} error: ${event.text}`;
|
|
15
15
|
case "raw": return `${prefix} ${event.stream}: ${event.line}`;
|
|
16
|
+
case "check_started": return `${prefix} check: ${event.command}`;
|
|
17
|
+
case "check_ended": return `${prefix} check ${event.status} (exit ${event.exit_code})`;
|
|
16
18
|
case "turn_ended": return `${prefix} ended: ${event.status} (exit ${event.exit_code})`;
|
|
17
19
|
}
|
|
18
20
|
}
|
package/dist/tasks.js
CHANGED
|
@@ -2,17 +2,18 @@ import fs from "node:fs";
|
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { randomUUID } from "node:crypto";
|
|
4
4
|
import { spawn, spawnSync } from "node:child_process";
|
|
5
|
+
import crossSpawn from "cross-spawn";
|
|
5
6
|
import { once } from "node:events";
|
|
6
7
|
import { adapters, getAdapter } from "./adapters/index.js";
|
|
7
8
|
import { resolveCursorModelArg } from "./adapters/cursor.js";
|
|
8
|
-
import { readMeta, writeMeta, writeTurn, readTurn, appendEvent, hasTurnEnded, taskDir, lockTask, listTasks } from "./store.js";
|
|
9
|
+
import { readMeta, writeMeta, writeTurn, readTurn, appendEvent, hasTurnEnded, taskDir, cancelRequestPath, lockTask, listTasks } from "./store.js";
|
|
9
10
|
import { setTimeout as sleep } from "node:timers/promises";
|
|
10
11
|
import { redact } from "./redact.js";
|
|
11
12
|
import { isAlive, killGroup } from "./process.js";
|
|
12
13
|
import { dirtyPaths, gitRepoRoot, gitSnapshot, snapshotToBaseline } from "./git.js";
|
|
13
14
|
import { normalizeScopeInput, scopePromptPrefix } from "./scope.js";
|
|
14
15
|
import { buildRulesyncReport, discoverRules, hasRulesyncSource, readRulesyncConfig, resolveRulesync, rulesGitRoot, rulesPointer, unseenRules, } from "./rules.js";
|
|
15
|
-
import { addWorktree, assertNotNestedWorktree, batonWorktreeExemptPaths, resolveRepoRoot } from "./worktree.js";
|
|
16
|
+
import { addWorktree, applyTree, assertNotNestedWorktree, batonWorktreeExemptPaths, diffTrees, forkPoint, headSha, netTree, removeTaskWorktree, resolveRepoRoot } from "./worktree.js";
|
|
16
17
|
const DIRTY_PATHS_CAP = 50;
|
|
17
18
|
/** Validate --isolate / --allow-dirty against mode. Throws on invalid combos. */
|
|
18
19
|
export function resolveWriteSafety(mode, isolate, allowDirty) {
|
|
@@ -48,7 +49,7 @@ function positive(value, name) {
|
|
|
48
49
|
// Stay under the 30s no-supervisor orphan window in orphaned().
|
|
49
50
|
const SUPERVISOR_READY_MS = 15_000;
|
|
50
51
|
async function launch(id) {
|
|
51
|
-
const child = spawn(process.execPath, [path.join(import.meta.dirname, `cli${path.extname(import.meta.filename)}`), "_supervise", id], { detached: true, stdio: "ignore", env: process.env });
|
|
52
|
+
const child = spawn(process.execPath, [path.join(import.meta.dirname, `cli${path.extname(import.meta.filename)}`), "_supervise", id], { detached: true, windowsHide: true, stdio: "ignore", env: process.env });
|
|
52
53
|
await once(child, "spawn");
|
|
53
54
|
let exited = false;
|
|
54
55
|
child.once("exit", () => { exited = true; });
|
|
@@ -80,9 +81,9 @@ export async function start(input) {
|
|
|
80
81
|
if (input.reasoningEffort && !["low", "medium", "high", "ultra"].includes(input.reasoningEffort))
|
|
81
82
|
throw new Error("Unknown effort.");
|
|
82
83
|
const model = input.model?.trim() || undefined;
|
|
83
|
-
if (model && adapter.id !== "cursor" && adapter.id !== "codex")
|
|
84
|
-
throw new Error(`${adapter.id} does not support --model yet (cursor and
|
|
85
|
-
let model_argv = adapter.id === "codex" ? model : undefined;
|
|
84
|
+
if (model && adapter.id !== "cursor" && adapter.id !== "codex" && adapter.id !== "claude")
|
|
85
|
+
throw new Error(`${adapter.id} does not support --model yet (cursor, codex and claude only).`);
|
|
86
|
+
let model_argv = adapter.id === "codex" || adapter.id === "claude" ? model : undefined;
|
|
86
87
|
if (adapter.id === "cursor") {
|
|
87
88
|
const resolved = resolveCursorModelArg(model, input.reasoningEffort ?? null);
|
|
88
89
|
if (resolved)
|
|
@@ -135,8 +136,8 @@ export async function start(input) {
|
|
|
135
136
|
const short = task_id.replace(/-/g, "").slice(0, 8);
|
|
136
137
|
const name = `task-${short}`;
|
|
137
138
|
const added = addWorktree(cwd, { name, branch: `baton/${name}`, base: "HEAD" });
|
|
138
|
-
const realCwd = fs.realpathSync(cwd);
|
|
139
|
-
const realRepo = fs.realpathSync(repo);
|
|
139
|
+
const realCwd = fs.realpathSync.native(cwd);
|
|
140
|
+
const realRepo = fs.realpathSync.native(repo);
|
|
140
141
|
const rel = path.relative(realRepo, realCwd);
|
|
141
142
|
if (rel.startsWith("..") || path.isAbsolute(rel)) {
|
|
142
143
|
throw new Error("--isolate cwd must be inside the repository.");
|
|
@@ -150,6 +151,7 @@ export async function start(input) {
|
|
|
150
151
|
branch: added.branch,
|
|
151
152
|
source_cwd,
|
|
152
153
|
gitignore_updated: added.gitignore_updated,
|
|
154
|
+
base_sha: headSha(added.path),
|
|
153
155
|
};
|
|
154
156
|
}
|
|
155
157
|
let scope_baseline;
|
|
@@ -200,6 +202,7 @@ export async function start(input) {
|
|
|
200
202
|
scope_baseline,
|
|
201
203
|
rules,
|
|
202
204
|
...(input.allowDirty ? { allow_dirty: true } : {}),
|
|
205
|
+
...(input.check?.trim() ? { check_command: input.check.trim() } : {}),
|
|
203
206
|
...(worktree ? { worktree } : {}),
|
|
204
207
|
};
|
|
205
208
|
writeMeta(meta);
|
|
@@ -262,7 +265,7 @@ export function status(id) {
|
|
|
262
265
|
}
|
|
263
266
|
}
|
|
264
267
|
killGroup(meta.child_pid);
|
|
265
|
-
const reason = meta.stop_reason;
|
|
268
|
+
const reason = meta.stop_reason ?? (fs.existsSync(cancelRequestPath(id, meta.turn)) ? "cancelled" : undefined);
|
|
266
269
|
const decided = reason === "idle" || reason === "max_duration" || reason === "cancelled";
|
|
267
270
|
meta.status = decided ? (reason === "cancelled" ? "cancelled" : "timed_out") : "failed";
|
|
268
271
|
meta.summary = decided ? (reason === "cancelled" ? "Cancelled." : `Timed out: ${reason}.`) : "supervisor exited unexpectedly";
|
|
@@ -287,17 +290,22 @@ export function status(id) {
|
|
|
287
290
|
release();
|
|
288
291
|
}
|
|
289
292
|
}
|
|
293
|
+
// The supervisor polls for the request every 250ms; past this it is treated as stuck and killed, and the orphan path records the cancel.
|
|
294
|
+
const CANCEL_FORCE_MS = 5000;
|
|
290
295
|
export async function cancel(id) {
|
|
291
296
|
let meta = status(id);
|
|
292
297
|
if (meta.status !== "running")
|
|
293
298
|
return meta;
|
|
294
|
-
|
|
299
|
+
fs.writeFileSync(cancelRequestPath(id, meta.turn), "", { flag: "a", mode: 0o600 });
|
|
300
|
+
const start = Date.now();
|
|
295
301
|
let signalled = null;
|
|
296
|
-
|
|
302
|
+
let forced = false;
|
|
303
|
+
while (Date.now() - start < CANCEL_FORCE_MS + 2000) {
|
|
297
304
|
meta = status(id);
|
|
298
305
|
if (meta.status !== "running")
|
|
299
306
|
return meta;
|
|
300
|
-
|
|
307
|
+
// POSIX also signals so the supervisor reacts at once; Windows has no signal that reaches its handler.
|
|
308
|
+
if (process.platform !== "win32" && meta.supervisor_pid !== signalled && isAlive(meta.supervisor_pid)) {
|
|
301
309
|
try {
|
|
302
310
|
process.kill(meta.supervisor_pid, "SIGTERM");
|
|
303
311
|
signalled = meta.supervisor_pid;
|
|
@@ -307,6 +315,16 @@ export async function cancel(id) {
|
|
|
307
315
|
throw error;
|
|
308
316
|
}
|
|
309
317
|
}
|
|
318
|
+
if (!forced && Date.now() - start > CANCEL_FORCE_MS && isAlive(meta.supervisor_pid)) {
|
|
319
|
+
forced = true;
|
|
320
|
+
try {
|
|
321
|
+
process.kill(meta.supervisor_pid, "SIGKILL");
|
|
322
|
+
}
|
|
323
|
+
catch (error) {
|
|
324
|
+
if (error.code !== "ESRCH")
|
|
325
|
+
throw error;
|
|
326
|
+
}
|
|
327
|
+
}
|
|
310
328
|
await sleep(20);
|
|
311
329
|
}
|
|
312
330
|
throw new Error("Cancellation not yet confirmed; retry status.");
|
|
@@ -324,6 +342,56 @@ export function result(id, turnNo) {
|
|
|
324
342
|
throw new Error(`Turn ${n} has no recorded final message (older baton, or the agent sent none); use baton tail.`);
|
|
325
343
|
return { task_id: id, turn: n, status: turn.status, final_message: turn.final_message };
|
|
326
344
|
}
|
|
345
|
+
function isolatedWorktree(meta) {
|
|
346
|
+
if (!meta.worktree)
|
|
347
|
+
throw new Error(`Task ${meta.task_id} was not started with --isolate.`);
|
|
348
|
+
return meta.worktree;
|
|
349
|
+
}
|
|
350
|
+
/** Fork point and net tree of an --isolate task; the temp index lives in the task dir, never in the worktree. */
|
|
351
|
+
function netChange(meta) {
|
|
352
|
+
const worktree = isolatedWorktree(meta);
|
|
353
|
+
if (!fs.existsSync(worktree.path))
|
|
354
|
+
throw new Error(`Worktree ${worktree.path} no longer exists (applied with --remove, or removed by hand).`);
|
|
355
|
+
const base = forkPoint(resolveRepoRoot(worktree.source_cwd), worktree.branch, worktree.base_sha);
|
|
356
|
+
const tree = netTree(worktree.path, path.join(taskDir(meta.task_id), `net.${randomUUID()}.index`));
|
|
357
|
+
return { worktree, base, tree };
|
|
358
|
+
}
|
|
359
|
+
export function diff(id, options = {}) {
|
|
360
|
+
const { worktree, base, tree } = netChange(status(id));
|
|
361
|
+
return diffTrees(worktree.path, base, tree, options.stat);
|
|
362
|
+
}
|
|
363
|
+
/** One squash commit of the task's net change, cherry-picked onto the source repo's current branch. Never pushes. */
|
|
364
|
+
export function apply(id, options = {}) {
|
|
365
|
+
const running = new Error("Task is running; wait for it to finish.");
|
|
366
|
+
if (status(id).status === "running")
|
|
367
|
+
throw running;
|
|
368
|
+
const release = lockTask(id);
|
|
369
|
+
if (!release)
|
|
370
|
+
throw running;
|
|
371
|
+
try {
|
|
372
|
+
const meta = readMeta(id);
|
|
373
|
+
if (meta.status === "running")
|
|
374
|
+
throw running;
|
|
375
|
+
const { worktree, base, tree } = netChange(meta);
|
|
376
|
+
const repo = resolveRepoRoot(worktree.source_cwd);
|
|
377
|
+
const subject = redact(meta.summary?.split("\n")[0]?.trim() || `apply task ${id.slice(0, 8)}`).slice(0, 72);
|
|
378
|
+
const message = `baton(${meta.target}): ${subject}\n\nBaton-Task: ${id}\nBaton-Target: ${meta.target}\n`;
|
|
379
|
+
const applied = applyTree(repo, base, tree, message);
|
|
380
|
+
const result = applied
|
|
381
|
+
? { task_id: id, status: "applied", repo, commit: applied.commit, files: applied.files, removed: false }
|
|
382
|
+
: { task_id: id, status: "nothing_to_apply", repo, removed: false };
|
|
383
|
+
if (options.remove) {
|
|
384
|
+
const problem = removeTaskWorktree(repo, worktree.path, worktree.branch);
|
|
385
|
+
result.removed = problem === null;
|
|
386
|
+
if (problem)
|
|
387
|
+
result.warning = `Applied, but could not fully remove ${worktree.path} or branch ${worktree.branch}: ${problem}`;
|
|
388
|
+
}
|
|
389
|
+
return result;
|
|
390
|
+
}
|
|
391
|
+
finally {
|
|
392
|
+
release();
|
|
393
|
+
}
|
|
394
|
+
}
|
|
327
395
|
export async function wait(ids, seconds = 50) {
|
|
328
396
|
if (!ids.length)
|
|
329
397
|
throw new Error("task_ids is missing.");
|
|
@@ -361,7 +429,7 @@ export async function reply(id, prompt, author = "host") {
|
|
|
361
429
|
const meta = readMeta(id);
|
|
362
430
|
if (meta.status === "running")
|
|
363
431
|
return busy;
|
|
364
|
-
if (!["success", "needs_input", "scope_violation", "readonly_violation"].includes(meta.status))
|
|
432
|
+
if (!["success", "needs_input", "scope_violation", "readonly_violation", "check_failed"].includes(meta.status))
|
|
365
433
|
throw new Error(`Cannot continue a task in status ${meta.status}.`);
|
|
366
434
|
if (!meta.session_id)
|
|
367
435
|
throw new Error("No session_id; cannot resume the session.");
|
|
@@ -372,6 +440,7 @@ export async function reply(id, prompt, author = "host") {
|
|
|
372
440
|
delete next.summary;
|
|
373
441
|
delete next.warning;
|
|
374
442
|
delete next.scope_violations;
|
|
443
|
+
delete next.check;
|
|
375
444
|
writeTurn(id, { turn: next.turn, author, prompt, status: "running" });
|
|
376
445
|
writeMeta(next);
|
|
377
446
|
}
|
|
@@ -384,7 +453,7 @@ export function ls(all = false, cwd = process.cwd()) {
|
|
|
384
453
|
const here = path.resolve(cwd);
|
|
385
454
|
let hereReal = here;
|
|
386
455
|
try {
|
|
387
|
-
hereReal = fs.realpathSync(here);
|
|
456
|
+
hereReal = fs.realpathSync.native(here);
|
|
388
457
|
}
|
|
389
458
|
catch { /* keep resolved */ }
|
|
390
459
|
return listTasks().filter((meta) => {
|
|
@@ -393,9 +462,9 @@ export function ls(all = false, cwd = process.cwd()) {
|
|
|
393
462
|
if (meta.cwd === here || meta.worktree?.source_cwd === here)
|
|
394
463
|
return true;
|
|
395
464
|
try {
|
|
396
|
-
if (fs.realpathSync(meta.cwd) === hereReal)
|
|
465
|
+
if (fs.realpathSync.native(meta.cwd) === hereReal)
|
|
397
466
|
return true;
|
|
398
|
-
if (meta.worktree?.source_cwd && fs.realpathSync(meta.worktree.source_cwd) === hereReal)
|
|
467
|
+
if (meta.worktree?.source_cwd && fs.realpathSync.native(meta.worktree.source_cwd) === hereReal)
|
|
399
468
|
return true;
|
|
400
469
|
}
|
|
401
470
|
catch { /* missing path */ }
|
|
@@ -440,7 +509,7 @@ export function agents(env = process.env) {
|
|
|
440
509
|
const bin = adapter.resolve(env);
|
|
441
510
|
if (!bin)
|
|
442
511
|
return { id: adapter.id, installed: false, bin: null, version: null };
|
|
443
|
-
const ran =
|
|
512
|
+
const ran = crossSpawn.sync(bin, ["--version"], { encoding: "utf8", timeout: 5000, env });
|
|
444
513
|
const version = `${ran.stdout || ""}\n${ran.stderr || ""}`.trim().split("\n").filter(Boolean)[0] || null;
|
|
445
514
|
return { id: adapter.id, installed: true, bin, version };
|
|
446
515
|
});
|