@speculoai/baton 0.6.1 → 0.7.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 +2 -0
- package/README.zh-CN.md +2 -0
- package/dist/adapters/claude.js +6 -2
- package/dist/adapters/codex.js +11 -4
- package/dist/adapters/cursor.js +8 -15
- package/dist/cli.js +26 -4
- package/dist/mcp.js +17 -3
- package/dist/process.js +3 -1
- package/dist/supervisor.js +76 -0
- package/dist/tail.js +2 -0
- package/dist/tasks.js +86 -10
- package/dist/worktree.js +97 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -109,6 +109,8 @@ If no target is named, the task goes to `codex`, or to `claude` when you are alr
|
|
|
109
109
|
|---|---|
|
|
110
110
|
| `baton start` | Starts a job. Options include `--effort`, `--mode readonly`, `--scope <glob>`, `--rules check\|pointer\|off`, and `--cwd <worktree>`. |
|
|
111
111
|
| `baton wait` / `status` | Waits for the job to stop, or takes one look at it. |
|
|
112
|
+
| `baton result` | Prints the worker's full final answer, without the transcript. |
|
|
113
|
+
| `baton diff` / `apply` | Shows what an `--isolate` job changed, then brings it back as one local commit on your current branch (never pushes). |
|
|
112
114
|
| `baton tail [-f]` | Shows the live event stream as readable text. |
|
|
113
115
|
| `baton reply` | Continues the same conversation when the worker asks a question or you want a follow-up. |
|
|
114
116
|
| `baton cancel` / `ls` / `prune` | Stops a job, lists jobs, or deletes old ones. |
|
package/README.zh-CN.md
CHANGED
|
@@ -109,6 +109,8 @@ baton tail -f <task_id>
|
|
|
109
109
|
|---|---|
|
|
110
110
|
| `baton start` | 启动任务。可选参数包括 `--effort`、`--mode readonly`、`--scope <glob>`、`--rules check\|pointer\|off`、`--cwd <worktree>`。 |
|
|
111
111
|
| `baton wait` / `status` | 等任务停下,或者看一眼当前状态。 |
|
|
112
|
+
| `baton result` | 只打印 worker 的完整最终回答,不含过程记录。 |
|
|
113
|
+
| `baton diff` / `apply` | 查看 `--isolate` 任务改了什么,再把改动作为一个本地 commit 收回到当前分支(不 push)。 |
|
|
112
114
|
| `baton tail [-f]` | 以可读文本显示实时事件流。 |
|
|
113
115
|
| `baton reply` | 执行者提问、或者你想追加要求时,在同一个会话里接着说。 |
|
|
114
116
|
| `baton cancel` / `ls` / `prune` | 停止任务、列出任务、清理旧任务。 |
|
package/dist/adapters/claude.js
CHANGED
|
@@ -32,16 +32,20 @@ export const claude = {
|
|
|
32
32
|
resolve(env) {
|
|
33
33
|
return which(["claude"], env);
|
|
34
34
|
},
|
|
35
|
-
build({ bin, prompt, sessionId, reasoningEffort, mode }) {
|
|
35
|
+
build({ bin, prompt, sessionId, reasoningEffort, model, mode }) {
|
|
36
36
|
// stream-json requires --verbose with -p.
|
|
37
37
|
const permission = mode === "readonly" ? "plan" : "acceptEdits";
|
|
38
38
|
const args = ["-p", "--output-format", "stream-json", "--verbose", "--permission-mode", permission, "--permission-prompts", "none"];
|
|
39
39
|
if (reasoningEffort)
|
|
40
40
|
args.push("--effort", reasoningEffort === "ultra" ? "max" : reasoningEffort);
|
|
41
|
+
// Verified 2026-11-24 (Claude Code 2.1.332): --resume without --model falls back to the default model, so pass it every turn.
|
|
42
|
+
const modelArg = model?.trim() || undefined;
|
|
43
|
+
if (modelArg)
|
|
44
|
+
args.push("--model", modelArg);
|
|
41
45
|
if (sessionId)
|
|
42
46
|
args.push("--resume", sessionId);
|
|
43
47
|
args.push(prompt);
|
|
44
|
-
return { command: bin, args, stdin: null };
|
|
48
|
+
return { command: bin, args, stdin: null, modelArg };
|
|
45
49
|
},
|
|
46
50
|
sessionIdFrom(line) {
|
|
47
51
|
const obj = parse(line);
|
package/dist/adapters/codex.js
CHANGED
|
@@ -18,9 +18,14 @@ export const codex = {
|
|
|
18
18
|
resolve(env) {
|
|
19
19
|
return which(["codex"], env);
|
|
20
20
|
},
|
|
21
|
-
build({ bin, cwd, prompt, sessionId, reasoningEffort, mode }) {
|
|
21
|
+
build({ bin, cwd, prompt, sessionId, reasoningEffort, model, mode }) {
|
|
22
22
|
const lastMessagePath = path.join(os.tmpdir(), `baton-codex-${process.pid}-${Date.now()}.txt`);
|
|
23
|
-
|
|
23
|
+
// `-m` is accepted by both `exec` and `exec resume` (codex-cli 0.171.0).
|
|
24
|
+
const modelArg = model?.trim() || undefined;
|
|
25
|
+
const optionArgs = [
|
|
26
|
+
...(modelArg ? ["-m", modelArg] : []),
|
|
27
|
+
...(reasoningEffort ? ["-c", `model_reasoning_effort="${reasoningEffort}"`] : []),
|
|
28
|
+
];
|
|
24
29
|
const readonly = mode === "readonly";
|
|
25
30
|
// `exec resume` does not accept --cd/--color/--sandbox. The first write turn uses --approve-for-me (workspace-write; do not add --sandbox).
|
|
26
31
|
if (sessionId) {
|
|
@@ -33,12 +38,13 @@ export const codex = {
|
|
|
33
38
|
"--skip-git-repo-check",
|
|
34
39
|
"--output-last-message",
|
|
35
40
|
lastMessagePath,
|
|
36
|
-
...
|
|
41
|
+
...optionArgs,
|
|
37
42
|
sessionId,
|
|
38
43
|
"-",
|
|
39
44
|
],
|
|
40
45
|
stdin: prompt,
|
|
41
46
|
lastMessagePath,
|
|
47
|
+
modelArg,
|
|
42
48
|
};
|
|
43
49
|
}
|
|
44
50
|
return {
|
|
@@ -54,11 +60,12 @@ export const codex = {
|
|
|
54
60
|
cwd,
|
|
55
61
|
"--output-last-message",
|
|
56
62
|
lastMessagePath,
|
|
57
|
-
...
|
|
63
|
+
...optionArgs,
|
|
58
64
|
"-",
|
|
59
65
|
],
|
|
60
66
|
stdin: prompt,
|
|
61
67
|
lastMessagePath,
|
|
68
|
+
modelArg,
|
|
62
69
|
};
|
|
63
70
|
},
|
|
64
71
|
sessionIdFrom(line) {
|
package/dist/adapters/cursor.js
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { redact } from "../redact.js";
|
|
2
2
|
import { authHit, which } from "./common.js";
|
|
3
3
|
const AUTH = ["not authenticated", "please log in", "agent login"];
|
|
4
|
-
const EMBEDDED_EFFORT = /-(low|medium|high|xhigh|ultra|max)(-fast)?$/i;
|
|
5
4
|
function event(data) {
|
|
6
5
|
return [{ ts: new Date().toISOString(), turn: 0, ...data }];
|
|
7
6
|
}
|
|
@@ -13,22 +12,16 @@ function parse(line) {
|
|
|
13
12
|
return null;
|
|
14
13
|
}
|
|
15
14
|
}
|
|
16
|
-
/**
|
|
15
|
+
/**
|
|
16
|
+
* Build the Cursor `--model` value.
|
|
17
|
+
* Verified 2026-11-23 (cursor-agent 2026.11.22): any `<id>[effort=…]` form is rejected ("Cannot use this model");
|
|
18
|
+
* the tier lives in the model id itself (e.g. gpt-5.3-codex-high), so `--effort` cannot be mapped.
|
|
19
|
+
*/
|
|
17
20
|
export function resolveCursorModelArg(model, effort) {
|
|
21
|
+
if (effort)
|
|
22
|
+
throw new Error("cursor does not support --effort; pick a model id that embeds the tier (see `cursor-agent --list-models`), e.g. --model gpt-5.3-codex-high.");
|
|
18
23
|
const id = typeof model === "string" ? model.trim() : "";
|
|
19
|
-
|
|
20
|
-
if (id && e) {
|
|
21
|
-
if (id.includes("["))
|
|
22
|
-
throw new Error("Model already has a parameter bracket; do not pass --effort.");
|
|
23
|
-
if (EMBEDDED_EFFORT.test(id))
|
|
24
|
-
throw new Error(`Model ${id} already includes an effort level; do not pass --effort.`);
|
|
25
|
-
return `${id}[effort=${e}]`;
|
|
26
|
-
}
|
|
27
|
-
if (id)
|
|
28
|
-
return id;
|
|
29
|
-
if (e)
|
|
30
|
-
return `auto[effort=${e}]`;
|
|
31
|
-
return null;
|
|
24
|
+
return id || null;
|
|
32
25
|
}
|
|
33
26
|
export const cursor = {
|
|
34
27
|
id: "cursor",
|
package/dist/cli.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import fs from "node:fs";
|
|
3
3
|
import { parseArgs } from "node:util";
|
|
4
|
-
import { agents, start, status, cancel, wait, reply, ls, prune } from "./tasks.js";
|
|
4
|
+
import { agents, start, status, cancel, wait, reply, ls, prune, diff, apply, result as turnResult } from "./tasks.js";
|
|
5
5
|
import { addWorktree, listWorktrees, removeWorktree } from "./worktree.js";
|
|
6
6
|
import { redact } from "./redact.js";
|
|
7
7
|
import { detectedHosts, runInstall } from "./install.js";
|
|
@@ -40,7 +40,7 @@ async function main() {
|
|
|
40
40
|
scope: { type: "string", multiple: true }, "scope-on-violation": { type: "string" },
|
|
41
41
|
mode: { type: "string" }, "allow-weak": { type: "boolean" },
|
|
42
42
|
isolate: { type: "boolean" }, "allow-dirty": { type: "boolean" },
|
|
43
|
-
rules: { type: "string" },
|
|
43
|
+
rules: { type: "string" }, check: { type: "string" },
|
|
44
44
|
} });
|
|
45
45
|
if (positionals.length)
|
|
46
46
|
throw new Error("start takes no positional arguments.");
|
|
@@ -51,7 +51,7 @@ async function main() {
|
|
|
51
51
|
mode: values.mode, allowWeak: values["allow-weak"],
|
|
52
52
|
isolate: values.isolate, allowDirty: values["allow-dirty"],
|
|
53
53
|
rules: values.rules,
|
|
54
|
-
|
|
54
|
+
check: values.check, });
|
|
55
55
|
if (result.status !== "running")
|
|
56
56
|
process.exitCode = 1;
|
|
57
57
|
}
|
|
@@ -77,6 +77,22 @@ async function main() {
|
|
|
77
77
|
throw new Error("--until-done and --for cannot be used together.");
|
|
78
78
|
result = await wait(positionals, values["until-done"] ? Infinity : values.for === undefined ? 50 : Number(values.for));
|
|
79
79
|
}
|
|
80
|
+
else if (command === "result") {
|
|
81
|
+
const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { turn: { type: "string" } } });
|
|
82
|
+
if (positionals.length !== 1)
|
|
83
|
+
throw new Error("result requires one task_id.");
|
|
84
|
+
// Plain text, like tail: the point is to read the answer without JSON escaping or the full transcript.
|
|
85
|
+
process.stdout.write(`${turnResult(positionals[0], values.turn === undefined ? undefined : Number(values.turn)).final_message}\n`);
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
else if (command === "diff") {
|
|
89
|
+
const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { stat: { type: "boolean" } } });
|
|
90
|
+
if (positionals.length !== 1)
|
|
91
|
+
throw new Error("diff requires one task_id.");
|
|
92
|
+
// Plain text, like result: a patch is read, not parsed.
|
|
93
|
+
process.stdout.write(diff(positionals[0], { stat: values.stat }));
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
80
96
|
else if (command === "tail") {
|
|
81
97
|
const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { follow: { type: "boolean", short: "f" }, raw: { type: "boolean" } } });
|
|
82
98
|
if (positionals.length !== 1)
|
|
@@ -96,6 +112,12 @@ async function main() {
|
|
|
96
112
|
throw new Error("prune requires --older days.");
|
|
97
113
|
result = { deleted: prune(Number(values.older)) };
|
|
98
114
|
}
|
|
115
|
+
else if (command === "apply") {
|
|
116
|
+
const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { remove: { type: "boolean" } } });
|
|
117
|
+
if (positionals.length !== 1)
|
|
118
|
+
throw new Error("apply requires one task_id.");
|
|
119
|
+
result = apply(positionals[0], { remove: values.remove });
|
|
120
|
+
}
|
|
99
121
|
else if (command === "cancel") {
|
|
100
122
|
if (args.length !== 1)
|
|
101
123
|
throw new Error("cancel requires one task_id.");
|
|
@@ -289,7 +311,7 @@ async function main() {
|
|
|
289
311
|
return;
|
|
290
312
|
}
|
|
291
313
|
else
|
|
292
|
-
throw new Error("Usage: baton version | agents | start | status | cancel | wait | tail | reply | ls | prune | worktree | rules | install | update | uninstall | mcp");
|
|
314
|
+
throw new Error("Usage: baton version | agents | start | status | cancel | wait | result | diff | apply | tail | reply | ls | prune | worktree | rules | install | update | uninstall | mcp");
|
|
293
315
|
process.stdout.write(`${JSON.stringify(result)}\n`);
|
|
294
316
|
}
|
|
295
317
|
try {
|
package/dist/mcp.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2
2
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
3
3
|
import { z } from "zod";
|
|
4
|
-
import { agents, cancel, ls, reply, start, status, wait } from "./tasks.js";
|
|
4
|
+
import { agents, apply, cancel, diff, ls, reply, result, start, status, wait } from "./tasks.js";
|
|
5
5
|
import { redact } from "./redact.js";
|
|
6
6
|
const MAX_WAIT_SECONDS = 55;
|
|
7
7
|
const PROGRESS_MS = 15_000;
|
|
@@ -26,7 +26,7 @@ export function createServer() {
|
|
|
26
26
|
prompt: z.string(),
|
|
27
27
|
files: z.array(z.string()).optional(),
|
|
28
28
|
reasoning_effort: z.enum(["low", "medium", "high", "ultra"]).optional(),
|
|
29
|
-
model: z.string().optional().describe("Per-task model (cursor
|
|
29
|
+
model: z.string().optional().describe("Per-task model (cursor, codex and claude; stored in meta and carried over by reply)."),
|
|
30
30
|
idle_timeout_seconds: z.number().optional().describe("Stop after this long with no output at all; default 600."),
|
|
31
31
|
max_duration_seconds: z.number().optional().describe("Maximum total duration per turn; default unlimited."),
|
|
32
32
|
cwd: z.string().optional(),
|
|
@@ -37,6 +37,7 @@ export function createServer() {
|
|
|
37
37
|
isolate: z.boolean().optional().describe("Create a git worktree and run the write job there (default false)."),
|
|
38
38
|
allow_dirty: z.boolean().optional().describe("Allow in-place write on a dirty working tree (default false)."),
|
|
39
39
|
rules: z.enum(["check", "pointer", "off"]).optional().describe("Project rules discovery; default check. pointer injects unread rule paths into the first-turn prompt."),
|
|
40
|
+
check: z.string().optional().describe("Shell command Baton runs in the task cwd after each successful turn; a non-zero exit ends the turn as check_failed."),
|
|
40
41
|
},
|
|
41
42
|
}, (args) => respond(() => start({
|
|
42
43
|
target: args.target_agent, prompt: args.prompt, files: args.files, cwd: args.cwd,
|
|
@@ -46,6 +47,7 @@ export function createServer() {
|
|
|
46
47
|
mode: args.mode, allowWeak: args.allow_weak,
|
|
47
48
|
isolate: args.isolate, allowDirty: args.allow_dirty,
|
|
48
49
|
rules: args.rules,
|
|
50
|
+
check: args.check,
|
|
49
51
|
})));
|
|
50
52
|
server.registerTool("task_status", {
|
|
51
53
|
description: "Get a task's current status. While running, includes liveness (active/quiet/orphaned) and quiet_for_s.",
|
|
@@ -76,8 +78,20 @@ export function createServer() {
|
|
|
76
78
|
clearInterval(timer);
|
|
77
79
|
}
|
|
78
80
|
}));
|
|
81
|
+
server.registerTool("task_result", {
|
|
82
|
+
description: "Get the agent's full final message of a finished turn (default: the latest), without the tool-call transcript. task_status/task_wait only carry the one-line summary.",
|
|
83
|
+
inputSchema: { task_id: z.string(), turn: z.number().int().optional() },
|
|
84
|
+
}, (args) => respond(() => result(args.task_id, args.turn)));
|
|
85
|
+
server.registerTool("task_diff", {
|
|
86
|
+
description: "Net change of an --isolate task since its worktree was created (worker commits, edits and new files; Baton's own worktree files excluded). stat=true returns a diffstat instead of the patch.",
|
|
87
|
+
inputSchema: { task_id: z.string(), stat: z.boolean().optional() },
|
|
88
|
+
}, (args) => respond(() => ({ task_id: args.task_id, diff: diff(args.task_id, { stat: args.stat }) })));
|
|
89
|
+
server.registerTool("task_apply", {
|
|
90
|
+
description: "Bring an --isolate task's net change onto the source repo's current branch as one local commit (three-way cherry-pick; never pushes). Refuses, changing nothing, on staged changes, overlapping dirty or untracked files, an operation in progress, or a conflict. remove=true then deletes the worktree and branch. Only with the user's consent.",
|
|
91
|
+
inputSchema: { task_id: z.string(), remove: z.boolean().optional() },
|
|
92
|
+
}, (args) => respond(() => apply(args.task_id, { remove: args.remove })));
|
|
79
93
|
server.registerTool("task_reply", {
|
|
80
|
-
description: "After a task stops at needs_input, success, scope_violation or
|
|
94
|
+
description: "After a task stops at needs_input, success, scope_violation, readonly_violation or check_failed, start the next turn in the same session. as=human means a human said it; default host. Returns busy while running.",
|
|
81
95
|
inputSchema: { task_id: z.string(), prompt: z.string(), as: z.enum(["host", "human"]).optional() },
|
|
82
96
|
}, (args) => respond(() => reply(args.task_id, args.prompt, (args.as ?? "host"))));
|
|
83
97
|
server.registerTool("task_cancel", {
|
package/dist/process.js
CHANGED
|
@@ -17,7 +17,9 @@ export function killGroup(pid) {
|
|
|
17
17
|
process.kill(-pid, "SIGKILL");
|
|
18
18
|
}
|
|
19
19
|
catch (error) {
|
|
20
|
-
|
|
20
|
+
// macOS returns EPERM for a group whose members have all exited but are not reaped yet (zombies); nothing is left to kill.
|
|
21
|
+
const code = error.code;
|
|
22
|
+
if (code !== "ESRCH" && code !== "EPERM")
|
|
21
23
|
throw error;
|
|
22
24
|
}
|
|
23
25
|
}
|
package/dist/supervisor.js
CHANGED
|
@@ -10,6 +10,7 @@ import { resolveRulesync, rulesGitRoot, rulesyncCheck } from "./rules.js";
|
|
|
10
10
|
import { appendEvent, hasTurnEnded, readMeta, writeMeta, readTurn, writeTurn, taskDir, 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 || "")
|
|
@@ -58,6 +59,12 @@ function failureSummary(stdout, stderr) {
|
|
|
58
59
|
return (withoutHtml(stderr) || withoutHtml(stdout)).slice(-8192);
|
|
59
60
|
}
|
|
60
61
|
export async function supervise(id) {
|
|
62
|
+
// Test hook: simulate a slow ("<ms>") or crashing ("exit") supervisor start.
|
|
63
|
+
const hook = process.env.BATON_TEST_SUPERVISE_START;
|
|
64
|
+
if (hook === "exit")
|
|
65
|
+
process.exit(1);
|
|
66
|
+
if (hook)
|
|
67
|
+
await new Promise((resolve) => setTimeout(resolve, Number(hook)));
|
|
61
68
|
const release = lockTask(id);
|
|
62
69
|
if (!release)
|
|
63
70
|
return;
|
|
@@ -104,6 +111,55 @@ export async function supervise(id) {
|
|
|
104
111
|
};
|
|
105
112
|
emit({ type: "turn_started", author: turn.author, prompt_preview: redact(turn.prompt).slice(0, 200) });
|
|
106
113
|
const heartbeat = setInterval(() => { meta.heartbeat_at = new Date().toISOString(); save(); }, 10_000);
|
|
114
|
+
// Run the --check command in its own process group. Cancel reaches it through childPid; the idle limit only kills the check.
|
|
115
|
+
const runCheck = async (command) => {
|
|
116
|
+
const startedCheck = Date.now();
|
|
117
|
+
const file = path.join(taskDir(id), "raw", `${meta.turn}.check.log`);
|
|
118
|
+
fs.writeFileSync(file, "", { mode: 0o600 });
|
|
119
|
+
let output = "";
|
|
120
|
+
let lastOutput = startedCheck;
|
|
121
|
+
let idle = false;
|
|
122
|
+
let code = null;
|
|
123
|
+
// The worker's heartbeat has already stopped; without this a check longer than 30s looks orphaned and gets killed.
|
|
124
|
+
const beat = setInterval(() => { meta.heartbeat_at = new Date().toISOString(); save(); }, 10_000);
|
|
125
|
+
let idleTimer;
|
|
126
|
+
try {
|
|
127
|
+
const child = spawn("/bin/sh", ["-c", command], { cwd: meta.cwd, env: { ...process.env, BATON_DELEGATION: "1" }, detached: true, stdio: ["ignore", "pipe", "pipe"] });
|
|
128
|
+
childPid = child.pid ?? null;
|
|
129
|
+
meta.child_pid = childPid;
|
|
130
|
+
save();
|
|
131
|
+
if (stopped)
|
|
132
|
+
killGroup(childPid);
|
|
133
|
+
const onData = (chunk) => {
|
|
134
|
+
lastOutput = Date.now();
|
|
135
|
+
fs.appendFileSync(file, chunk);
|
|
136
|
+
output = (output + chunk.toString()).slice(-200_000);
|
|
137
|
+
};
|
|
138
|
+
child.stdout.on("data", onData);
|
|
139
|
+
child.stderr.on("data", onData);
|
|
140
|
+
idleTimer = setInterval(() => {
|
|
141
|
+
if (Date.now() - lastOutput < meta.idle_timeout_s * 1000)
|
|
142
|
+
return;
|
|
143
|
+
idle = true;
|
|
144
|
+
try {
|
|
145
|
+
killGroup(childPid);
|
|
146
|
+
}
|
|
147
|
+
catch { /* already gone */ }
|
|
148
|
+
}, 50);
|
|
149
|
+
code = await new Promise((resolve) => {
|
|
150
|
+
child.once("error", (error) => { output += `\n${error.message}`; resolve(null); });
|
|
151
|
+
child.once("close", resolve);
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
finally {
|
|
155
|
+
clearInterval(beat);
|
|
156
|
+
clearInterval(idleTimer);
|
|
157
|
+
}
|
|
158
|
+
const result = { command, exit_code: code, duration_ms: Date.now() - startedCheck, output_tail: redact(output).slice(-CHECK_TAIL) };
|
|
159
|
+
if (!stopped)
|
|
160
|
+
result.status = idle ? "timed_out" : code === 0 ? "passed" : "failed";
|
|
161
|
+
return result;
|
|
162
|
+
};
|
|
107
163
|
// rulesync --check before the idle timer so its duration does not count against the worker.
|
|
108
164
|
if (meta.turn === 1 && meta.rules?.rulesync?.status === "pending") {
|
|
109
165
|
const repoRoot = rulesGitRoot(meta.cwd) ?? meta.cwd;
|
|
@@ -321,9 +377,29 @@ export async function supervise(id) {
|
|
|
321
377
|
}
|
|
322
378
|
}
|
|
323
379
|
}
|
|
380
|
+
if (final === "success" && meta.check_command && !stopped) {
|
|
381
|
+
// Keep waiters blocked: the turn is not decided until the check ends.
|
|
382
|
+
meta.status = "running";
|
|
383
|
+
emit({ type: "check_started", command: redact(meta.check_command).slice(0, 200) });
|
|
384
|
+
const check = await runCheck(meta.check_command);
|
|
385
|
+
emit({ type: "check_ended", status: check.status ?? "cancelled", exit_code: check.exit_code });
|
|
386
|
+
turn.check = check;
|
|
387
|
+
meta.check = check;
|
|
388
|
+
if (stopped === "cancelled") {
|
|
389
|
+
final = "cancelled";
|
|
390
|
+
meta.summary = "Cancelled.";
|
|
391
|
+
}
|
|
392
|
+
else if (check.status !== "passed") {
|
|
393
|
+
final = "check_failed";
|
|
394
|
+
meta.summary = `check_failed: ${check.status === "timed_out" ? "timed out" : `exit ${check.exit_code}`}\n${check.output_tail}`.slice(0, 8192);
|
|
395
|
+
}
|
|
396
|
+
meta.status = final;
|
|
397
|
+
}
|
|
324
398
|
delete meta.stop_reason;
|
|
325
399
|
turn.status = final;
|
|
326
400
|
turn.summary = meta.summary;
|
|
401
|
+
if (message.trim())
|
|
402
|
+
turn.final_message = redact(message.trim());
|
|
327
403
|
writeTurn(id, turn);
|
|
328
404
|
if (hasTurnEnded(id, meta.turn))
|
|
329
405
|
save();
|
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
|
@@ -12,7 +12,7 @@ import { isAlive, killGroup } from "./process.js";
|
|
|
12
12
|
import { dirtyPaths, gitRepoRoot, gitSnapshot, snapshotToBaseline } from "./git.js";
|
|
13
13
|
import { normalizeScopeInput, scopePromptPrefix } from "./scope.js";
|
|
14
14
|
import { buildRulesyncReport, discoverRules, hasRulesyncSource, readRulesyncConfig, resolveRulesync, rulesGitRoot, rulesPointer, unseenRules, } from "./rules.js";
|
|
15
|
-
import { addWorktree, assertNotNestedWorktree, batonWorktreeExemptPaths, resolveRepoRoot } from "./worktree.js";
|
|
15
|
+
import { addWorktree, applyTree, assertNotNestedWorktree, batonWorktreeExemptPaths, diffTrees, forkPoint, headSha, netTree, removeTaskWorktree, resolveRepoRoot } from "./worktree.js";
|
|
16
16
|
const DIRTY_PATHS_CAP = 50;
|
|
17
17
|
/** Validate --isolate / --allow-dirty against mode. Throws on invalid combos. */
|
|
18
18
|
export function resolveWriteSafety(mode, isolate, allowDirty) {
|
|
@@ -44,19 +44,28 @@ function positive(value, name) {
|
|
|
44
44
|
throw new Error(`${name} must be a positive number.`);
|
|
45
45
|
return value;
|
|
46
46
|
}
|
|
47
|
+
// Node boot + module load takes ~150ms idle but >1s on a busy machine; a slow start is not a failure.
|
|
48
|
+
// Stay under the 30s no-supervisor orphan window in orphaned().
|
|
49
|
+
const SUPERVISOR_READY_MS = 15_000;
|
|
47
50
|
async function launch(id) {
|
|
48
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 });
|
|
49
52
|
await once(child, "spawn");
|
|
53
|
+
let exited = false;
|
|
54
|
+
child.once("exit", () => { exited = true; });
|
|
50
55
|
child.unref();
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
56
|
+
// supervisor_pid is never cleared, so a supervisor that claimed the task and already finished still counts as ready.
|
|
57
|
+
const ready = () => readMeta(id)?.supervisor_pid === child.pid;
|
|
58
|
+
const deadline = Date.now() + SUPERVISOR_READY_MS;
|
|
59
|
+
while (!exited && Date.now() < deadline) {
|
|
60
|
+
if (ready())
|
|
54
61
|
return;
|
|
55
62
|
await sleep(10);
|
|
56
63
|
}
|
|
64
|
+
if (ready())
|
|
65
|
+
return;
|
|
57
66
|
child.kill("SIGKILL");
|
|
58
67
|
killGroup(readMeta(id)?.child_pid ?? null);
|
|
59
|
-
throw new Error("supervisor not ready.");
|
|
68
|
+
throw new Error(exited ? "supervisor exited before it was ready." : "supervisor not ready.");
|
|
60
69
|
}
|
|
61
70
|
export async function start(input) {
|
|
62
71
|
if (process.env.BATON_DELEGATION === "1")
|
|
@@ -71,9 +80,9 @@ export async function start(input) {
|
|
|
71
80
|
if (input.reasoningEffort && !["low", "medium", "high", "ultra"].includes(input.reasoningEffort))
|
|
72
81
|
throw new Error("Unknown effort.");
|
|
73
82
|
const model = input.model?.trim() || undefined;
|
|
74
|
-
if (model && adapter.id !== "cursor")
|
|
75
|
-
throw new Error(`${adapter.id} does not support --model yet (cursor only).`);
|
|
76
|
-
let model_argv;
|
|
83
|
+
if (model && adapter.id !== "cursor" && adapter.id !== "codex" && adapter.id !== "claude")
|
|
84
|
+
throw new Error(`${adapter.id} does not support --model yet (cursor, codex and claude only).`);
|
|
85
|
+
let model_argv = adapter.id === "codex" || adapter.id === "claude" ? model : undefined;
|
|
77
86
|
if (adapter.id === "cursor") {
|
|
78
87
|
const resolved = resolveCursorModelArg(model, input.reasoningEffort ?? null);
|
|
79
88
|
if (resolved)
|
|
@@ -141,6 +150,7 @@ export async function start(input) {
|
|
|
141
150
|
branch: added.branch,
|
|
142
151
|
source_cwd,
|
|
143
152
|
gitignore_updated: added.gitignore_updated,
|
|
153
|
+
base_sha: headSha(added.path),
|
|
144
154
|
};
|
|
145
155
|
}
|
|
146
156
|
let scope_baseline;
|
|
@@ -191,6 +201,7 @@ export async function start(input) {
|
|
|
191
201
|
scope_baseline,
|
|
192
202
|
rules,
|
|
193
203
|
...(input.allowDirty ? { allow_dirty: true } : {}),
|
|
204
|
+
...(input.check?.trim() ? { check_command: input.check.trim() } : {}),
|
|
194
205
|
...(worktree ? { worktree } : {}),
|
|
195
206
|
};
|
|
196
207
|
writeMeta(meta);
|
|
@@ -246,7 +257,9 @@ export function status(id) {
|
|
|
246
257
|
process.kill(meta.supervisor_pid, "SIGKILL");
|
|
247
258
|
}
|
|
248
259
|
catch (error) {
|
|
249
|
-
|
|
260
|
+
// EPERM: the pid now belongs to another user's process (reuse); it is not our writer, so recovery goes on.
|
|
261
|
+
const code = error.code;
|
|
262
|
+
if (code !== "ESRCH" && code !== "EPERM")
|
|
250
263
|
throw error;
|
|
251
264
|
}
|
|
252
265
|
}
|
|
@@ -300,6 +313,68 @@ export async function cancel(id) {
|
|
|
300
313
|
}
|
|
301
314
|
throw new Error("Cancellation not yet confirmed; retry status.");
|
|
302
315
|
}
|
|
316
|
+
/** The agent's full last message of a finished turn (default: the latest turn). */
|
|
317
|
+
export function result(id, turnNo) {
|
|
318
|
+
const meta = status(id);
|
|
319
|
+
const n = turnNo ?? meta.turn;
|
|
320
|
+
if (!Number.isInteger(n) || n < 1 || n > meta.turn)
|
|
321
|
+
throw new Error(`turn must be an integer from 1 to ${meta.turn}.`);
|
|
322
|
+
const turn = readTurn(id, n);
|
|
323
|
+
if (turn.status === "running")
|
|
324
|
+
throw new Error(`Turn ${n} is still running; wait for it first.`);
|
|
325
|
+
if (!turn.final_message)
|
|
326
|
+
throw new Error(`Turn ${n} has no recorded final message (older baton, or the agent sent none); use baton tail.`);
|
|
327
|
+
return { task_id: id, turn: n, status: turn.status, final_message: turn.final_message };
|
|
328
|
+
}
|
|
329
|
+
function isolatedWorktree(meta) {
|
|
330
|
+
if (!meta.worktree)
|
|
331
|
+
throw new Error(`Task ${meta.task_id} was not started with --isolate.`);
|
|
332
|
+
return meta.worktree;
|
|
333
|
+
}
|
|
334
|
+
/** Fork point and net tree of an --isolate task; the temp index lives in the task dir, never in the worktree. */
|
|
335
|
+
function netChange(meta) {
|
|
336
|
+
const worktree = isolatedWorktree(meta);
|
|
337
|
+
if (!fs.existsSync(worktree.path))
|
|
338
|
+
throw new Error(`Worktree ${worktree.path} no longer exists (applied with --remove, or removed by hand).`);
|
|
339
|
+
const base = forkPoint(resolveRepoRoot(worktree.source_cwd), worktree.branch, worktree.base_sha);
|
|
340
|
+
const tree = netTree(worktree.path, path.join(taskDir(meta.task_id), `net.${randomUUID()}.index`));
|
|
341
|
+
return { worktree, base, tree };
|
|
342
|
+
}
|
|
343
|
+
export function diff(id, options = {}) {
|
|
344
|
+
const { worktree, base, tree } = netChange(status(id));
|
|
345
|
+
return diffTrees(worktree.path, base, tree, options.stat);
|
|
346
|
+
}
|
|
347
|
+
/** One squash commit of the task's net change, cherry-picked onto the source repo's current branch. Never pushes. */
|
|
348
|
+
export function apply(id, options = {}) {
|
|
349
|
+
const running = new Error("Task is running; wait for it to finish.");
|
|
350
|
+
if (status(id).status === "running")
|
|
351
|
+
throw running;
|
|
352
|
+
const release = lockTask(id);
|
|
353
|
+
if (!release)
|
|
354
|
+
throw running;
|
|
355
|
+
try {
|
|
356
|
+
const meta = readMeta(id);
|
|
357
|
+
if (meta.status === "running")
|
|
358
|
+
throw running;
|
|
359
|
+
const { worktree, base, tree } = netChange(meta);
|
|
360
|
+
const repo = resolveRepoRoot(worktree.source_cwd);
|
|
361
|
+
const subject = redact(meta.summary?.split("\n")[0]?.trim() || `apply task ${id.slice(0, 8)}`).slice(0, 72);
|
|
362
|
+
const message = `baton(${meta.target}): ${subject}\n\nBaton-Task: ${id}\nBaton-Target: ${meta.target}\n`;
|
|
363
|
+
const applied = applyTree(repo, base, tree, message);
|
|
364
|
+
const result = applied
|
|
365
|
+
? { task_id: id, status: "applied", repo, commit: applied.commit, files: applied.files, removed: false }
|
|
366
|
+
: { task_id: id, status: "nothing_to_apply", repo, removed: false };
|
|
367
|
+
if (options.remove) {
|
|
368
|
+
result.removed = removeTaskWorktree(repo, worktree.path, worktree.branch);
|
|
369
|
+
if (!result.removed)
|
|
370
|
+
result.warning = `Applied, but could not fully remove ${worktree.path} or branch ${worktree.branch}.`;
|
|
371
|
+
}
|
|
372
|
+
return result;
|
|
373
|
+
}
|
|
374
|
+
finally {
|
|
375
|
+
release();
|
|
376
|
+
}
|
|
377
|
+
}
|
|
303
378
|
export async function wait(ids, seconds = 50) {
|
|
304
379
|
if (!ids.length)
|
|
305
380
|
throw new Error("task_ids is missing.");
|
|
@@ -337,7 +412,7 @@ export async function reply(id, prompt, author = "host") {
|
|
|
337
412
|
const meta = readMeta(id);
|
|
338
413
|
if (meta.status === "running")
|
|
339
414
|
return busy;
|
|
340
|
-
if (!["success", "needs_input", "scope_violation", "readonly_violation"].includes(meta.status))
|
|
415
|
+
if (!["success", "needs_input", "scope_violation", "readonly_violation", "check_failed"].includes(meta.status))
|
|
341
416
|
throw new Error(`Cannot continue a task in status ${meta.status}.`);
|
|
342
417
|
if (!meta.session_id)
|
|
343
418
|
throw new Error("No session_id; cannot resume the session.");
|
|
@@ -348,6 +423,7 @@ export async function reply(id, prompt, author = "host") {
|
|
|
348
423
|
delete next.summary;
|
|
349
424
|
delete next.warning;
|
|
350
425
|
delete next.scope_violations;
|
|
426
|
+
delete next.check;
|
|
351
427
|
writeTurn(id, { turn: next.turn, author, prompt, status: "running" });
|
|
352
428
|
writeMeta(next);
|
|
353
429
|
}
|
package/dist/worktree.js
CHANGED
|
@@ -5,10 +5,105 @@ import { spawnSync } from "node:child_process";
|
|
|
5
5
|
import { hasRulesyncSource, resolveRulesync, RULE_ENTRIES } from "./rules.js";
|
|
6
6
|
import { redact } from "./redact.js";
|
|
7
7
|
const META_NAME = ".baton-worktree.json";
|
|
8
|
-
function git(cwd, args) {
|
|
9
|
-
const ran = spawnSync("git", args, {
|
|
8
|
+
function git(cwd, args, options = {}) {
|
|
9
|
+
const ran = spawnSync("git", args, {
|
|
10
|
+
cwd, encoding: "utf8", input: options.input, maxBuffer: 256 * 1024 * 1024,
|
|
11
|
+
env: options.env ? { ...process.env, ...options.env } : process.env,
|
|
12
|
+
});
|
|
10
13
|
return { status: ran.status ?? 1, stdout: ran.stdout || "", stderr: ran.stderr || "" };
|
|
11
14
|
}
|
|
15
|
+
function mustGit(cwd, args, options = {}) {
|
|
16
|
+
const ran = git(cwd, args, options);
|
|
17
|
+
if (ran.status !== 0)
|
|
18
|
+
throw new Error(`git ${args[0]} failed: ${(ran.stderr || ran.stdout).trim()}`);
|
|
19
|
+
return ran.stdout;
|
|
20
|
+
}
|
|
21
|
+
export function headSha(cwd) {
|
|
22
|
+
return mustGit(cwd, ["rev-parse", "HEAD"]).trim();
|
|
23
|
+
}
|
|
24
|
+
/** Commit the task worktree forked from: the recorded sha, or (older tasks) the merge-base with the source HEAD. */
|
|
25
|
+
export function forkPoint(sourceRepo, branch, recorded) {
|
|
26
|
+
if (recorded)
|
|
27
|
+
return recorded;
|
|
28
|
+
const ran = git(sourceRepo, ["merge-base", branch, "HEAD"]);
|
|
29
|
+
if (ran.status !== 0 || !ran.stdout.trim())
|
|
30
|
+
throw new Error(`Cannot find where ${branch} forked from; no base_sha recorded and merge-base failed.`);
|
|
31
|
+
return ran.stdout.trim();
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* The worktree's net state as a tree object: HEAD plus every non-ignored working-tree change,
|
|
35
|
+
* minus Baton's own files (.baton-worktree.json, copy / symlink entries). Built in a throwaway
|
|
36
|
+
* index so the worktree's own index, branch and files stay untouched.
|
|
37
|
+
*/
|
|
38
|
+
export function netTree(worktreePath, indexFile) {
|
|
39
|
+
const env = { GIT_INDEX_FILE: indexFile };
|
|
40
|
+
try {
|
|
41
|
+
mustGit(worktreePath, ["read-tree", "HEAD"], { env });
|
|
42
|
+
const exclude = [...batonWorktreeExemptPaths(worktreePath)].map((entry) => `:(exclude,glob)${entry}`);
|
|
43
|
+
mustGit(worktreePath, ["add", "-A", "--", ".", ...exclude], { env });
|
|
44
|
+
return mustGit(worktreePath, ["write-tree"], { env }).trim();
|
|
45
|
+
}
|
|
46
|
+
finally {
|
|
47
|
+
fs.rmSync(indexFile, { force: true });
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
export function diffTrees(cwd, base, tree, stat = false) {
|
|
51
|
+
return mustGit(cwd, ["diff", stat ? "--stat" : "--binary", base, tree]);
|
|
52
|
+
}
|
|
53
|
+
/** Paths touched between two trees; --no-renames so a rename lists both its old and new path. */
|
|
54
|
+
export function changedPaths(cwd, base, tree) {
|
|
55
|
+
return mustGit(cwd, ["diff", "--name-only", "--no-renames", "-z", base, tree]).split("\0").filter(Boolean);
|
|
56
|
+
}
|
|
57
|
+
const IN_PROGRESS = ["MERGE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD", "rebase-merge", "rebase-apply"];
|
|
58
|
+
/** Why bringing `files` into `repo` is unsafe right now, or null. Checked before anything is written. */
|
|
59
|
+
function applyBlocker(repo, files) {
|
|
60
|
+
for (const name of IN_PROGRESS) {
|
|
61
|
+
if (fs.existsSync(path.resolve(repo, mustGit(repo, ["rev-parse", "--git-path", name]).trim()))) {
|
|
62
|
+
return `${repo} is in the middle of a merge, rebase, cherry-pick or revert (${name}); finish or abort it first.`;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
if (git(repo, ["diff", "--cached", "--quiet"]).status !== 0)
|
|
66
|
+
return `Staged changes in ${repo}; commit or unstage them first.`;
|
|
67
|
+
// porcelain v1 -z: "XY path\0", and a rename / copy adds its source path as the next field.
|
|
68
|
+
const fields = mustGit(repo, ["status", "--porcelain=v1", "-z", "--untracked-files=all"]).split("\0");
|
|
69
|
+
const dirty = new Set();
|
|
70
|
+
for (let i = 0; i < fields.length; i++) {
|
|
71
|
+
const entry = fields[i];
|
|
72
|
+
if (entry.length < 4)
|
|
73
|
+
continue;
|
|
74
|
+
dirty.add(entry.slice(3));
|
|
75
|
+
if (entry[0] === "R" || entry[0] === "C")
|
|
76
|
+
dirty.add(fields[++i]);
|
|
77
|
+
}
|
|
78
|
+
const overlap = files.filter((file) => dirty.has(file));
|
|
79
|
+
return overlap.length ? `Uncommitted or untracked files in ${repo} overlap the task's changes: ${overlap.join(", ")}. Commit, stash or move them first.` : null;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Bring `tree` (forked at `base`) onto the current branch of `repo` as one commit: commit-tree, then cherry-pick
|
|
83
|
+
* for a three-way merge. Any refusal or conflict leaves HEAD, index and working tree as they were.
|
|
84
|
+
*/
|
|
85
|
+
export function applyTree(repo, base, tree, message) {
|
|
86
|
+
const files = changedPaths(repo, base, tree);
|
|
87
|
+
if (!files.length)
|
|
88
|
+
return null;
|
|
89
|
+
const blocker = applyBlocker(repo, files);
|
|
90
|
+
if (blocker)
|
|
91
|
+
throw new Error(blocker);
|
|
92
|
+
const squash = mustGit(repo, ["commit-tree", tree, "-p", base, "-F", "-"], { input: message }).trim();
|
|
93
|
+
const picked = git(repo, ["cherry-pick", squash]);
|
|
94
|
+
if (picked.status !== 0) {
|
|
95
|
+
const conflicts = git(repo, ["diff", "--name-only", "--diff-filter=U", "-z"]).stdout.split("\0").filter(Boolean);
|
|
96
|
+
git(repo, ["cherry-pick", "--abort"]);
|
|
97
|
+
const detail = (picked.stderr || picked.stdout).trim();
|
|
98
|
+
throw new Error(`cherry-pick failed and was aborted; ${repo} is unchanged.${conflicts.length ? ` Conflicts: ${conflicts.join(", ")}.` : ""} ${detail}`.trim());
|
|
99
|
+
}
|
|
100
|
+
return { commit: headSha(repo), files };
|
|
101
|
+
}
|
|
102
|
+
/** Delete a task's worktree and branch regardless of their state; true when both are gone. */
|
|
103
|
+
export function removeTaskWorktree(repo, worktreePath, branch) {
|
|
104
|
+
cleanupWorktree(repo, worktreePath, branch);
|
|
105
|
+
return !fs.existsSync(worktreePath) && git(repo, ["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`]).status !== 0;
|
|
106
|
+
}
|
|
12
107
|
function strings(value) {
|
|
13
108
|
return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
|
|
14
109
|
}
|
package/package.json
CHANGED