@speculoai/baton 0.7.0 → 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 +2 -1
- package/README.zh-CN.md +2 -1
- package/dist/adapters/agy.js +3 -2
- package/dist/adapters/claude.js +2 -2
- package/dist/adapters/common.js +23 -11
- package/dist/adapters/cursor.js +2 -2
- package/dist/cli.js +44 -34
- package/dist/install.js +2 -2
- 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 +14 -4
- package/dist/tasks.js +32 -15
- package/dist/usage.js +182 -0
- package/dist/worktree.js +37 -11
- package/package.json +6 -2
package/README.md
CHANGED
|
@@ -62,7 +62,7 @@ The host starts the job, checks on it in short steps, passes Codex's "A or B?" t
|
|
|
62
62
|
npx @speculoai/baton install
|
|
63
63
|
```
|
|
64
64
|
|
|
65
|
-
It finds the agent CLIs on your machine, asks which ones should get the plugin, and installs the global `baton` command. It then offers to set up [rulesync](https://github.com/dyoshikawa/rulesync) for the current project (optional; rerun any time with `baton rules init`).
|
|
65
|
+
It finds the agent CLIs on your machine, asks which ones should get the plugin, and installs the global `baton` command. It then offers to set up [rulesync](https://github.com/dyoshikawa/rulesync) for the current project (optional; rerun any time with `baton rules init`). Supports macOS, Linux, and native Windows 10/11 (PowerShell or cmd); requires Node ≥ 20.17 and at least one supported agent CLI that is already logged in. See [Windows notes](docs/reference.md#windows-notes) for platform differences.
|
|
66
66
|
|
|
67
67
|
Check which workers Baton can see:
|
|
68
68
|
|
|
@@ -116,6 +116,7 @@ If no target is named, the task goes to `codex`, or to `claude` when you are alr
|
|
|
116
116
|
| `baton cancel` / `ls` / `prune` | Stops a job, lists jobs, or deletes old ones. |
|
|
117
117
|
| `baton worktree add/ls/rm` | Gives a job its own git worktree so it doesn't touch your checkout. |
|
|
118
118
|
| `baton rules init` | Installs and initializes rulesync for the current project, previewing changes before writing. |
|
|
119
|
+
| `baton report [id]` | Prints a redacted diagnostic report and prefilled GitHub issue link (`--submit` uses `gh` or opens a browser). |
|
|
119
120
|
| `baton mcp` | Runs the same operations as an MCP server for hosts that can't run shell commands. |
|
|
120
121
|
|
|
121
122
|
Every command prints exactly one JSON object, so the host agent can read it reliably. See the [full flag list and statuses](docs/reference.md#command-line).
|
package/README.zh-CN.md
CHANGED
|
@@ -62,7 +62,7 @@
|
|
|
62
62
|
npx @speculoai/baton install
|
|
63
63
|
```
|
|
64
64
|
|
|
65
|
-
它会找出本机装了哪些 Agent CLI,问你要给哪些装插件,并安装全局 `baton` 命令。之后会推荐为当前项目配置 [rulesync](https://github.com/dyoshikawa/rulesync)(可选,以后可随时用 `baton rules init`
|
|
65
|
+
它会找出本机装了哪些 Agent CLI,问你要给哪些装插件,并安装全局 `baton` 命令。之后会推荐为当前项目配置 [rulesync](https://github.com/dyoshikawa/rulesync)(可选,以后可随时用 `baton rules init` 重跑)。支持 macOS、Linux 与原生 Windows 10/11(PowerShell 或 cmd);需要 Node ≥ 20.17,以及至少一个已登录的受支持 Agent CLI。Windows 差异与限制见[Windows 平台说明](docs/reference.zh-CN.md#windows-平台说明)。
|
|
66
66
|
|
|
67
67
|
看看 Baton 能找到哪些执行者:
|
|
68
68
|
|
|
@@ -116,6 +116,7 @@ baton tail -f <task_id>
|
|
|
116
116
|
| `baton cancel` / `ls` / `prune` | 停止任务、列出任务、清理旧任务。 |
|
|
117
117
|
| `baton worktree add/ls/rm` | 给任务单独开一个 git worktree,不碰你的工作目录。 |
|
|
118
118
|
| `baton rules init` | 为当前项目安装并初始化 rulesync,写入前先预览改动。 |
|
|
119
|
+
| `baton report [id]` | 生成脱敏诊断报告和预填 GitHub issue 链接(`--submit` 有 `gh` 直接提,否则在浏览器打开)。 |
|
|
119
120
|
| `baton mcp` | 以 MCP 服务器的形式提供同样的操作,给不能跑 shell 的宿主用。 |
|
|
120
121
|
|
|
121
122
|
每个命令都只输出一个 JSON 对象,主控 Agent 读起来不会出错。全部参数和状态见[完整手册](docs/reference.zh-CN.md#命令行)。
|
package/dist/adapters/agy.js
CHANGED
|
@@ -24,12 +24,13 @@ export const agy = {
|
|
|
24
24
|
return which(["agy"], env);
|
|
25
25
|
},
|
|
26
26
|
build({ bin, prompt, sessionId, reasoningEffort, mode }) {
|
|
27
|
-
|
|
27
|
+
// Verified 2026-11-25: agy has no plain-text stdin. `--print=` (empty) plus stream-json input reads one {"event":"user","message":{"content":…}} line per turn from stdin.
|
|
28
|
+
const args = ["--print=", "--mode", mode === "readonly" ? "plan" : "accept-edits", "--input-format", "stream-json", "--output-format", "stream-json"];
|
|
28
29
|
if (reasoningEffort)
|
|
29
30
|
args.push("--effort", reasoningEffort === "ultra" ? "max" : reasoningEffort);
|
|
30
31
|
if (sessionId)
|
|
31
32
|
args.push("--conversation", sessionId);
|
|
32
|
-
return { command: bin, args, stdin:
|
|
33
|
+
return { command: bin, args, stdin: `${JSON.stringify({ event: "user", message: { content: prompt } })}\n` };
|
|
33
34
|
},
|
|
34
35
|
sessionIdFrom(line) {
|
|
35
36
|
const obj = parse(line);
|
package/dist/adapters/claude.js
CHANGED
|
@@ -44,8 +44,8 @@ export const claude = {
|
|
|
44
44
|
args.push("--model", modelArg);
|
|
45
45
|
if (sessionId)
|
|
46
46
|
args.push("--resume", sessionId);
|
|
47
|
-
|
|
48
|
-
return { command: bin, args, stdin:
|
|
47
|
+
// The prompt goes through stdin: argv would pass through cmd.exe for a .cmd shim on Windows, which cuts it at the first newline.
|
|
48
|
+
return { command: bin, args, stdin: prompt, modelArg };
|
|
49
49
|
},
|
|
50
50
|
sessionIdFrom(line) {
|
|
51
51
|
const obj = parse(line);
|
package/dist/adapters/common.js
CHANGED
|
@@ -1,19 +1,31 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
2
|
import path from "node:path";
|
|
3
|
+
// Windows variable names are case-insensitive ("Path"), but a copied env object is not.
|
|
4
|
+
const envValue = (env, key) => process.platform === "win32" ? env[key] ?? env[Object.keys(env).find((name) => name.toUpperCase() === key) ?? key] : env[key];
|
|
5
|
+
// Windows: only the extensions cross-spawn can run. The extensionless npm shim next to a .cmd is a sh script and must not match.
|
|
6
|
+
function fileNames(name, env) {
|
|
7
|
+
if (process.platform !== "win32")
|
|
8
|
+
return [name];
|
|
9
|
+
const runnable = [".com", ".exe", ".bat", ".cmd"];
|
|
10
|
+
const exts = (envValue(env, "PATHEXT") || ".COM;.EXE;.BAT;.CMD").split(";").map((ext) => ext.toLowerCase());
|
|
11
|
+
return exts.filter((ext) => runnable.includes(ext)).map((ext) => name + ext);
|
|
12
|
+
}
|
|
3
13
|
export function which(names, env = process.env) {
|
|
4
|
-
const dirs = (env
|
|
14
|
+
const dirs = (envValue(env, "PATH") || "").split(path.delimiter).filter(Boolean);
|
|
5
15
|
for (const name of names) {
|
|
6
16
|
for (const dir of dirs) {
|
|
7
|
-
const
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
+
for (const file of fileNames(name, env)) {
|
|
18
|
+
const full = path.join(dir, file);
|
|
19
|
+
try {
|
|
20
|
+
const stat = fs.statSync(full);
|
|
21
|
+
if (!stat.isFile())
|
|
22
|
+
continue;
|
|
23
|
+
fs.accessSync(full, fs.constants.X_OK);
|
|
24
|
+
return full;
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
// Try the next PATH entry.
|
|
28
|
+
}
|
|
17
29
|
}
|
|
18
30
|
}
|
|
19
31
|
}
|
package/dist/adapters/cursor.js
CHANGED
|
@@ -50,8 +50,8 @@ export const cursor = {
|
|
|
50
50
|
args.push("--model", modelArg);
|
|
51
51
|
if (sessionId)
|
|
52
52
|
args.push("--resume", sessionId);
|
|
53
|
-
|
|
54
|
-
return { command: bin, args, stdin:
|
|
53
|
+
// Prompt on stdin, not argv (see claude.ts).
|
|
54
|
+
return { command: bin, args, stdin: prompt, modelArg: modelArg ?? undefined };
|
|
55
55
|
},
|
|
56
56
|
sessionIdFrom(line) {
|
|
57
57
|
const obj = parse(line);
|
package/dist/cli.js
CHANGED
|
@@ -6,6 +6,7 @@ import { addWorktree, listWorktrees, removeWorktree } from "./worktree.js";
|
|
|
6
6
|
import { redact } from "./redact.js";
|
|
7
7
|
import { detectedHosts, runInstall } from "./install.js";
|
|
8
8
|
import { mappedAgents, rulesInit } from "./rulesync-setup.js";
|
|
9
|
+
import { COMMANDS, commandList, isCommand, renderHelp, wantsHelp } from "./usage.js";
|
|
9
10
|
function installChoice(value, flag) {
|
|
10
11
|
if (value === undefined)
|
|
11
12
|
return undefined;
|
|
@@ -16,6 +17,21 @@ function installChoice(value, flag) {
|
|
|
16
17
|
async function main() {
|
|
17
18
|
const [command, ...args] = process.argv.slice(2);
|
|
18
19
|
let result;
|
|
20
|
+
if (command === undefined || command === "help" || command === "-h" || command === "--help") {
|
|
21
|
+
const name = command === "help" ? args[0] : undefined;
|
|
22
|
+
if (name === undefined)
|
|
23
|
+
process.stdout.write(renderHelp());
|
|
24
|
+
else if (isCommand(name))
|
|
25
|
+
process.stdout.write(renderHelp(name));
|
|
26
|
+
else
|
|
27
|
+
throw new Error(commandList);
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
// Before parsing, so `start --help` neither trips strict parsing nor waits on stdin.
|
|
31
|
+
if (isCommand(command) && wantsHelp(args)) {
|
|
32
|
+
process.stdout.write(renderHelp(command));
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
19
35
|
if (command === "_supervise") {
|
|
20
36
|
if (args.length !== 1)
|
|
21
37
|
throw new Error("task_id is missing.");
|
|
@@ -26,6 +42,20 @@ async function main() {
|
|
|
26
42
|
await (await import("./mcp.js")).startMcp();
|
|
27
43
|
return;
|
|
28
44
|
}
|
|
45
|
+
if (command === "report") {
|
|
46
|
+
const { values, positionals } = parseArgs({ args, allowPositionals: true, options: COMMANDS.report.options });
|
|
47
|
+
if (positionals.length > 1)
|
|
48
|
+
throw new Error("report takes at most one task_id.");
|
|
49
|
+
const { buildReport, submitReport } = await import("./report.js");
|
|
50
|
+
const report = buildReport(positionals[0], { title: values.title });
|
|
51
|
+
if (values.submit) {
|
|
52
|
+
result = submitReport(report);
|
|
53
|
+
process.stdout.write(`${JSON.stringify(result)}\n`);
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
process.stdout.write(`${report.markdown}\n\nOpen issue: ${report.issueUrl}\n`);
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
29
59
|
if (command === "version" || command === "--version") {
|
|
30
60
|
result = { version: JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf8")).version };
|
|
31
61
|
}
|
|
@@ -33,15 +63,7 @@ async function main() {
|
|
|
33
63
|
result = { agents: agents() };
|
|
34
64
|
}
|
|
35
65
|
else if (command === "start") {
|
|
36
|
-
const { values, positionals } = parseArgs({ args, allowPositionals: true, options:
|
|
37
|
-
target: { type: "string" }, prompt: { type: "string" }, cwd: { type: "string" },
|
|
38
|
-
file: { type: "string", multiple: true }, effort: { type: "string" }, model: { type: "string" },
|
|
39
|
-
"idle-timeout": { type: "string" }, "max-duration": { type: "string" },
|
|
40
|
-
scope: { type: "string", multiple: true }, "scope-on-violation": { type: "string" },
|
|
41
|
-
mode: { type: "string" }, "allow-weak": { type: "boolean" },
|
|
42
|
-
isolate: { type: "boolean" }, "allow-dirty": { type: "boolean" },
|
|
43
|
-
rules: { type: "string" }, check: { type: "string" },
|
|
44
|
-
} });
|
|
66
|
+
const { values, positionals } = parseArgs({ args, allowPositionals: true, options: COMMANDS.start.options });
|
|
45
67
|
if (positionals.length)
|
|
46
68
|
throw new Error("start takes no positional arguments.");
|
|
47
69
|
result = await start({ target: values.target || "", prompt: values.prompt ?? fs.readFileSync(0, "utf8"), cwd: values.cwd, files: values.file,
|
|
@@ -61,7 +83,7 @@ async function main() {
|
|
|
61
83
|
result = status(args[0]);
|
|
62
84
|
}
|
|
63
85
|
else if (command === "reply") {
|
|
64
|
-
const { values, positionals } = parseArgs({ args, allowPositionals: true, options:
|
|
86
|
+
const { values, positionals } = parseArgs({ args, allowPositionals: true, options: COMMANDS.reply.options });
|
|
65
87
|
if (positionals.length !== 1)
|
|
66
88
|
throw new Error("reply requires one task_id.");
|
|
67
89
|
result = await reply(positionals[0], values.prompt ?? fs.readFileSync(0, "utf8"), (values.as ?? "host"));
|
|
@@ -71,14 +93,14 @@ async function main() {
|
|
|
71
93
|
else if (command === "wait") {
|
|
72
94
|
const { values, positionals } = parseArgs({
|
|
73
95
|
args, allowPositionals: true,
|
|
74
|
-
options:
|
|
96
|
+
options: COMMANDS.wait.options,
|
|
75
97
|
});
|
|
76
98
|
if (values["until-done"] && values.for !== undefined)
|
|
77
99
|
throw new Error("--until-done and --for cannot be used together.");
|
|
78
100
|
result = await wait(positionals, values["until-done"] ? Infinity : values.for === undefined ? 50 : Number(values.for));
|
|
79
101
|
}
|
|
80
102
|
else if (command === "result") {
|
|
81
|
-
const { values, positionals } = parseArgs({ args, allowPositionals: true, options:
|
|
103
|
+
const { values, positionals } = parseArgs({ args, allowPositionals: true, options: COMMANDS.result.options });
|
|
82
104
|
if (positionals.length !== 1)
|
|
83
105
|
throw new Error("result requires one task_id.");
|
|
84
106
|
// Plain text, like tail: the point is to read the answer without JSON escaping or the full transcript.
|
|
@@ -86,7 +108,7 @@ async function main() {
|
|
|
86
108
|
return;
|
|
87
109
|
}
|
|
88
110
|
else if (command === "diff") {
|
|
89
|
-
const { values, positionals } = parseArgs({ args, allowPositionals: true, options:
|
|
111
|
+
const { values, positionals } = parseArgs({ args, allowPositionals: true, options: COMMANDS.diff.options });
|
|
90
112
|
if (positionals.length !== 1)
|
|
91
113
|
throw new Error("diff requires one task_id.");
|
|
92
114
|
// Plain text, like result: a patch is read, not parsed.
|
|
@@ -94,26 +116,26 @@ async function main() {
|
|
|
94
116
|
return;
|
|
95
117
|
}
|
|
96
118
|
else if (command === "tail") {
|
|
97
|
-
const { values, positionals } = parseArgs({ args, allowPositionals: true, options:
|
|
119
|
+
const { values, positionals } = parseArgs({ args, allowPositionals: true, options: COMMANDS.tail.options });
|
|
98
120
|
if (positionals.length !== 1)
|
|
99
121
|
throw new Error("tail requires one task_id.");
|
|
100
122
|
await (await import("./tail.js")).tail(positionals[0], { follow: values.follow, raw: values.raw });
|
|
101
123
|
return;
|
|
102
124
|
}
|
|
103
125
|
else if (command === "ls") {
|
|
104
|
-
const { values, positionals } = parseArgs({ args, allowPositionals: true, options:
|
|
126
|
+
const { values, positionals } = parseArgs({ args, allowPositionals: true, options: COMMANDS.ls.options });
|
|
105
127
|
if (positionals.length)
|
|
106
128
|
throw new Error("ls takes no positional arguments.");
|
|
107
129
|
result = { tasks: ls(values.all) };
|
|
108
130
|
}
|
|
109
131
|
else if (command === "prune") {
|
|
110
|
-
const { values, positionals } = parseArgs({ args, allowPositionals: true, options:
|
|
132
|
+
const { values, positionals } = parseArgs({ args, allowPositionals: true, options: COMMANDS.prune.options });
|
|
111
133
|
if (positionals.length || values.older === undefined)
|
|
112
134
|
throw new Error("prune requires --older days.");
|
|
113
135
|
result = { deleted: prune(Number(values.older)) };
|
|
114
136
|
}
|
|
115
137
|
else if (command === "apply") {
|
|
116
|
-
const { values, positionals } = parseArgs({ args, allowPositionals: true, options:
|
|
138
|
+
const { values, positionals } = parseArgs({ args, allowPositionals: true, options: COMMANDS.apply.options });
|
|
117
139
|
if (positionals.length !== 1)
|
|
118
140
|
throw new Error("apply requires one task_id.");
|
|
119
141
|
result = apply(positionals[0], { remove: values.remove });
|
|
@@ -129,7 +151,7 @@ async function main() {
|
|
|
129
151
|
const { values, positionals } = parseArgs({
|
|
130
152
|
args: rest,
|
|
131
153
|
allowPositionals: true,
|
|
132
|
-
options:
|
|
154
|
+
options: COMMANDS.worktree.options,
|
|
133
155
|
});
|
|
134
156
|
if (positionals.length)
|
|
135
157
|
throw new Error("worktree add takes no positional arguments.");
|
|
@@ -155,10 +177,7 @@ async function main() {
|
|
|
155
177
|
throw new Error("Usage: baton rules init");
|
|
156
178
|
const { values, positionals } = parseArgs({
|
|
157
179
|
args: rest, allowPositionals: true,
|
|
158
|
-
options:
|
|
159
|
-
install: { type: "string" }, source: { type: "string" }, template: { type: "boolean" },
|
|
160
|
-
targets: { type: "string", multiple: true }, yes: { type: "boolean" }, "dry-run": { type: "boolean" },
|
|
161
|
-
},
|
|
180
|
+
options: COMMANDS.rules.options,
|
|
162
181
|
});
|
|
163
182
|
if (positionals.length)
|
|
164
183
|
throw new Error("rules init takes no positional arguments.");
|
|
@@ -191,20 +210,11 @@ async function main() {
|
|
|
191
210
|
else if (command === "install" || command === "update" || command === "uninstall") {
|
|
192
211
|
const { values, positionals } = parseArgs({
|
|
193
212
|
args, allowPositionals: true,
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
"dry-run": { type: "boolean" }, "skip-global": { type: "boolean" },
|
|
197
|
-
rulesync: { type: "string" },
|
|
198
|
-
},
|
|
213
|
+
// Each command parses with its own table (update/uninstall reject install-only flags); typed as install's superset.
|
|
214
|
+
options: COMMANDS[command].options,
|
|
199
215
|
});
|
|
200
216
|
if (positionals.length)
|
|
201
217
|
throw new Error(`${command} takes no positional arguments.`);
|
|
202
|
-
if (command !== "install" && values.force)
|
|
203
|
-
throw new Error(`${command} does not accept --force.`);
|
|
204
|
-
if (command === "uninstall" && values["skip-global"])
|
|
205
|
-
throw new Error("uninstall does not accept --skip-global.");
|
|
206
|
-
if (command !== "install" && values.rulesync !== undefined)
|
|
207
|
-
throw new Error(`${command} does not accept --rulesync.`);
|
|
208
218
|
const rulesyncChoice = installChoice(values.rulesync, "--rulesync");
|
|
209
219
|
const action = command;
|
|
210
220
|
const pretty = Boolean(process.stdin.isTTY);
|
|
@@ -311,7 +321,7 @@ async function main() {
|
|
|
311
321
|
return;
|
|
312
322
|
}
|
|
313
323
|
else
|
|
314
|
-
throw new Error(
|
|
324
|
+
throw new Error(commandList);
|
|
315
325
|
process.stdout.write(`${JSON.stringify(result)}\n`);
|
|
316
326
|
}
|
|
317
327
|
try {
|
package/dist/install.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import
|
|
1
|
+
import spawn from "cross-spawn";
|
|
2
2
|
import fs from "node:fs";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { which } from "./adapters/common.js";
|
|
@@ -118,7 +118,7 @@ export function planInstall(input) {
|
|
|
118
118
|
return { hosts, missing };
|
|
119
119
|
const version = JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
|
|
120
120
|
const spec = input.action === "update" ? "@speculoai/baton@latest" : `@speculoai/baton@${version}`;
|
|
121
|
-
return { hosts, missing, global: { command: [
|
|
121
|
+
return { hosts, missing, global: { command: ["npm", "install", "-g", spec] } };
|
|
122
122
|
}
|
|
123
123
|
export function readInstalled(home = batonHome()) {
|
|
124
124
|
try {
|
package/dist/process.js
CHANGED
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { spawnSync } from "node:child_process";
|
|
3
|
+
// Absolute, because a sandboxed or trimmed PATH need not contain them.
|
|
4
|
+
const SYSTEM32 = path.join(process.env.SystemRoot ?? "C:\\Windows", "System32");
|
|
1
5
|
export function isAlive(pid) {
|
|
2
6
|
if (!pid || !Number.isSafeInteger(pid) || pid <= 1)
|
|
3
7
|
return false;
|
|
@@ -13,6 +17,20 @@ export function isAlive(pid) {
|
|
|
13
17
|
export function killGroup(pid) {
|
|
14
18
|
if (!pid || !Number.isSafeInteger(pid) || pid <= 1)
|
|
15
19
|
return;
|
|
20
|
+
if (process.platform === "win32") {
|
|
21
|
+
// shortcut: taskkill follows parent pids, so a grandchild whose parent already exited escapes; a Job Object would need a native addon.
|
|
22
|
+
const killed = spawnSync(path.join(SYSTEM32, "taskkill.exe"), ["/PID", String(pid), "/T", "/F"], { windowsHide: true, stdio: "ignore" });
|
|
23
|
+
// libuv ends a worker's direct child (a .cmd shim's cmd.exe) when the supervisor dies, but the shim's own children keep that dead pid
|
|
24
|
+
// as their parent, so taskkill finds nothing (or only a half-closed root). Kill whatever still names it as parent.
|
|
25
|
+
if (killed.status !== 0) {
|
|
26
|
+
const listed = spawnSync(path.join(SYSTEM32, "WindowsPowerShell", "v1.0", "powershell.exe"), ["-NoProfile", "-Command", `(Get-CimInstance Win32_Process -Filter 'ParentProcessId=${pid}').ProcessId`], { encoding: "utf8", windowsHide: true, timeout: 15_000 });
|
|
27
|
+
for (const child of (listed.stdout ?? "").split(/\s+/).map(Number)) {
|
|
28
|
+
if (Number.isSafeInteger(child) && child > 1)
|
|
29
|
+
spawnSync(path.join(SYSTEM32, "taskkill.exe"), ["/PID", String(child), "/T", "/F"], { windowsHide: true, stdio: "ignore" });
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
16
34
|
try {
|
|
17
35
|
process.kill(-pid, "SIGKILL");
|
|
18
36
|
}
|
package/dist/report.js
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import spawn from "cross-spawn";
|
|
5
|
+
import { redact } from "./redact.js";
|
|
6
|
+
import { readMeta, taskDir } from "./store.js";
|
|
7
|
+
import { agents } from "./tasks.js";
|
|
8
|
+
const REPO = "SpeculoAI/baton";
|
|
9
|
+
const ISSUE_NEW_URL = `https://github.com/${REPO}/issues/new`;
|
|
10
|
+
const MAX_URL_LEN = 3500;
|
|
11
|
+
const MAX_EVENTS = 30;
|
|
12
|
+
const MAX_TEXT = 200;
|
|
13
|
+
function replaceAllCase(text, needle, replacement) {
|
|
14
|
+
if (!needle)
|
|
15
|
+
return text;
|
|
16
|
+
if (process.platform !== "win32")
|
|
17
|
+
return text.split(needle).join(replacement);
|
|
18
|
+
const escaped = needle.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
19
|
+
return text.replace(new RegExp(escaped, "gi"), replacement);
|
|
20
|
+
}
|
|
21
|
+
/** Redact secrets and replace home/cwd paths so user-specific paths never leave the machine. */
|
|
22
|
+
export function sanitize(text, cwd) {
|
|
23
|
+
let out = redact(text);
|
|
24
|
+
const paths = [];
|
|
25
|
+
if (cwd) {
|
|
26
|
+
paths.push([cwd, "<cwd>"]);
|
|
27
|
+
try {
|
|
28
|
+
const real = fs.realpathSync.native(cwd);
|
|
29
|
+
if (real !== cwd)
|
|
30
|
+
paths.push([real, "<cwd>"]);
|
|
31
|
+
}
|
|
32
|
+
catch { }
|
|
33
|
+
}
|
|
34
|
+
const home = os.homedir();
|
|
35
|
+
if (home)
|
|
36
|
+
paths.push([home, "~"]);
|
|
37
|
+
// Longest first so a cwd under home becomes <cwd>, not ~/...
|
|
38
|
+
paths.sort((a, b) => b[0].length - a[0].length);
|
|
39
|
+
for (const [needle, repl] of paths)
|
|
40
|
+
out = replaceAllCase(out, needle, repl);
|
|
41
|
+
return out;
|
|
42
|
+
}
|
|
43
|
+
function clip(text, limit = MAX_TEXT) {
|
|
44
|
+
const single = text.replace(/\s+/g, " ").trim();
|
|
45
|
+
return single.length > limit ? `${single.slice(0, limit)}...` : single;
|
|
46
|
+
}
|
|
47
|
+
function readVersion() {
|
|
48
|
+
try {
|
|
49
|
+
return JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf8")).version ?? "unknown";
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
return "unknown";
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/** Keep only baton-generated diagnostic summaries; drop agent-authored business summaries from success/needs_input. */
|
|
56
|
+
function safeSummary(meta) {
|
|
57
|
+
if (!meta.summary || meta.status === "success" || meta.status === "needs_input")
|
|
58
|
+
return undefined;
|
|
59
|
+
const firstLine = meta.summary.split(/\r?\n/, 1)[0] ?? "";
|
|
60
|
+
return clip(sanitize(firstLine, meta.cwd));
|
|
61
|
+
}
|
|
62
|
+
function readEventSkeleton(id, cwd) {
|
|
63
|
+
let raw;
|
|
64
|
+
try {
|
|
65
|
+
raw = fs.readFileSync(path.join(taskDir(id), "events.jsonl"), "utf8");
|
|
66
|
+
}
|
|
67
|
+
catch (error) {
|
|
68
|
+
if (error.code === "ENOENT")
|
|
69
|
+
return [];
|
|
70
|
+
throw error;
|
|
71
|
+
}
|
|
72
|
+
const lines = [];
|
|
73
|
+
for (const line of raw.split("\n")) {
|
|
74
|
+
if (!line.trim())
|
|
75
|
+
continue;
|
|
76
|
+
let ev;
|
|
77
|
+
try {
|
|
78
|
+
ev = JSON.parse(line);
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
const parts = [ev.ts, `t${ev.turn}`, ev.type];
|
|
84
|
+
if (ev.type === "turn_ended") {
|
|
85
|
+
parts.push(`status=${ev.status}`, `exit=${ev.exit_code ?? "null"}`);
|
|
86
|
+
}
|
|
87
|
+
else if (ev.type === "check_ended") {
|
|
88
|
+
parts.push(`status=${ev.status}`, `exit=${ev.exit_code ?? "null"}`);
|
|
89
|
+
}
|
|
90
|
+
else if (ev.type === "error") {
|
|
91
|
+
parts.push(clip(sanitize(ev.text, cwd)));
|
|
92
|
+
}
|
|
93
|
+
lines.push(parts.join(" "));
|
|
94
|
+
}
|
|
95
|
+
return lines.slice(-MAX_EVENTS);
|
|
96
|
+
}
|
|
97
|
+
function makeIssueUrl(title, body, shortBody) {
|
|
98
|
+
const full = `${ISSUE_NEW_URL}?${new URLSearchParams({ title, body }).toString()}`;
|
|
99
|
+
if (full.length <= MAX_URL_LEN)
|
|
100
|
+
return full;
|
|
101
|
+
return `${ISSUE_NEW_URL}?${new URLSearchParams({ title, body: shortBody }).toString()}`;
|
|
102
|
+
}
|
|
103
|
+
export function buildReport(taskId, opts = {}) {
|
|
104
|
+
const meta = taskId ? readMeta(taskId) : null;
|
|
105
|
+
if (taskId && !meta)
|
|
106
|
+
throw new Error("No such task.");
|
|
107
|
+
const detected = agents().map((a) => `- ${a.id}: ${a.installed ? (a.version ? clip(sanitize(a.version), 80) : "installed") : "not installed"}`);
|
|
108
|
+
const envSection = [
|
|
109
|
+
"### Environment",
|
|
110
|
+
`- baton: ${readVersion()}`,
|
|
111
|
+
`- node: ${process.version}`,
|
|
112
|
+
`- os: ${process.platform} ${process.arch} (${os.release()})`,
|
|
113
|
+
"- agents:",
|
|
114
|
+
...detected.map((line) => ` ${line}`),
|
|
115
|
+
];
|
|
116
|
+
const taskSection = [];
|
|
117
|
+
if (meta) {
|
|
118
|
+
const fields = [
|
|
119
|
+
["target", meta.target],
|
|
120
|
+
["status", meta.status],
|
|
121
|
+
["turn", meta.turn],
|
|
122
|
+
["mode", meta.mode],
|
|
123
|
+
["enforcement", meta.enforcement],
|
|
124
|
+
["isolated", Boolean(meta.worktree)],
|
|
125
|
+
["stop_reason", meta.stop_reason],
|
|
126
|
+
["idle_timeout_s", meta.idle_timeout_s],
|
|
127
|
+
["max_duration_s", meta.max_duration_s ?? undefined],
|
|
128
|
+
["scope_on_violation", meta.scope_on_violation],
|
|
129
|
+
["rules_mode", meta.rules?.mode],
|
|
130
|
+
["rulesync_status", meta.rules?.rulesync?.status],
|
|
131
|
+
["check", meta.check ? `${meta.check.status} (exit=${meta.check.exit_code ?? "null"}, ${meta.check.duration_ms}ms)` : undefined],
|
|
132
|
+
["summary", safeSummary(meta)],
|
|
133
|
+
];
|
|
134
|
+
taskSection.push("", "### Task (redacted)", ...fields.filter(([, value]) => value !== undefined).map(([key, value]) => `- ${key}: ${value}`));
|
|
135
|
+
const timeline = readEventSkeleton(meta.task_id, meta.cwd);
|
|
136
|
+
if (timeline.length) {
|
|
137
|
+
taskSection.push("", "### Event timeline", "```text", ...timeline, "```");
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
const header = [
|
|
141
|
+
"> Review before posting: remove any project-specific terms if present.",
|
|
142
|
+
"",
|
|
143
|
+
"### What happened",
|
|
144
|
+
"<!-- Describe what you expected vs. what happened -->",
|
|
145
|
+
"",
|
|
146
|
+
];
|
|
147
|
+
const markdown = [...header, ...envSection, ...taskSection].join("\n");
|
|
148
|
+
const title = opts.title?.trim() || (meta ? `bug(${meta.target}): ${meta.status}` : "bug: <describe issue>");
|
|
149
|
+
const shortBody = [
|
|
150
|
+
...header,
|
|
151
|
+
...envSection,
|
|
152
|
+
"",
|
|
153
|
+
"<!-- Full task timeline omitted for URL length; paste the output of `baton report` here -->",
|
|
154
|
+
].join("\n");
|
|
155
|
+
const issueUrl = makeIssueUrl(title, markdown, shortBody);
|
|
156
|
+
return { title, markdown, issueUrl };
|
|
157
|
+
}
|
|
158
|
+
function defaultOpenBrowser(url) {
|
|
159
|
+
try {
|
|
160
|
+
// Windows: rundll32 avoids cmd.exe, which would split the URL on `&`.
|
|
161
|
+
const [cmd, args] = process.platform === "darwin"
|
|
162
|
+
? ["open", [url]]
|
|
163
|
+
: process.platform === "win32"
|
|
164
|
+
? ["rundll32", ["url.dll,FileProtocolHandler", url]]
|
|
165
|
+
: ["xdg-open", [url]];
|
|
166
|
+
const child = spawn(cmd, args, { detached: true, stdio: "ignore", windowsHide: true });
|
|
167
|
+
child.unref();
|
|
168
|
+
return true;
|
|
169
|
+
}
|
|
170
|
+
catch {
|
|
171
|
+
return false;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
export function submitReport(report, deps = {}) {
|
|
175
|
+
const runSync = deps.spawnSync ?? spawn.sync;
|
|
176
|
+
const openBrowser = deps.openBrowser ?? defaultOpenBrowser;
|
|
177
|
+
const auth = runSync("gh", ["auth", "status"], { stdio: "ignore", windowsHide: true });
|
|
178
|
+
if (auth.status === 0) {
|
|
179
|
+
const created = runSync("gh", ["issue", "create", "-R", REPO, "--title", report.title, "--body-file", "-"], {
|
|
180
|
+
input: report.markdown,
|
|
181
|
+
encoding: "utf8",
|
|
182
|
+
windowsHide: true,
|
|
183
|
+
});
|
|
184
|
+
const url = (created.stdout ?? "").trim();
|
|
185
|
+
if (created.status === 0 && url)
|
|
186
|
+
return { method: "gh", url, submitted: true };
|
|
187
|
+
}
|
|
188
|
+
if (openBrowser(report.issueUrl))
|
|
189
|
+
return { method: "browser", url: report.issueUrl, submitted: false };
|
|
190
|
+
return { method: "url", url: report.issueUrl, submitted: false };
|
|
191
|
+
}
|
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,13 +1,13 @@
|
|
|
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
13
|
const CHECK_TAIL = 4000;
|
|
@@ -58,6 +58,8 @@ function failureSummary(stdout, stderr) {
|
|
|
58
58
|
return reason.slice(-8192);
|
|
59
59
|
return (withoutHtml(stderr) || withoutHtml(stdout)).slice(-8192);
|
|
60
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";
|
|
61
63
|
export async function supervise(id) {
|
|
62
64
|
// Test hook: simulate a slow ("<ms>") or crashing ("exit") supervisor start.
|
|
63
65
|
const hook = process.env.BATON_TEST_SUPERVISE_START;
|
|
@@ -91,6 +93,13 @@ export async function supervise(id) {
|
|
|
91
93
|
};
|
|
92
94
|
const cancel = () => stop("cancelled");
|
|
93
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();
|
|
94
103
|
try {
|
|
95
104
|
meta.supervisor_pid = process.pid;
|
|
96
105
|
meta.heartbeat_at = new Date().toISOString();
|
|
@@ -124,7 +133,7 @@ export async function supervise(id) {
|
|
|
124
133
|
const beat = setInterval(() => { meta.heartbeat_at = new Date().toISOString(); save(); }, 10_000);
|
|
125
134
|
let idleTimer;
|
|
126
135
|
try {
|
|
127
|
-
const child = spawn(
|
|
136
|
+
const child = spawn(command, { shell: true, cwd: meta.cwd, env: { ...process.env, BATON_DELEGATION: "1" }, detached: DETACHED, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] });
|
|
128
137
|
childPid = child.pid ?? null;
|
|
129
138
|
meta.child_pid = childPid;
|
|
130
139
|
save();
|
|
@@ -223,7 +232,7 @@ export async function supervise(id) {
|
|
|
223
232
|
fs.writeFileSync(spec.lastMessagePath, "", { mode: 0o600, flag: "wx" });
|
|
224
233
|
lastMessageCreated = true;
|
|
225
234
|
}
|
|
226
|
-
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"] });
|
|
227
236
|
childPid = child.pid ?? null;
|
|
228
237
|
meta.child_pid = childPid;
|
|
229
238
|
if (stopped)
|
|
@@ -406,4 +415,5 @@ export async function supervise(id) {
|
|
|
406
415
|
else
|
|
407
416
|
emit({ type: "turn_ended", status: final, exit_code: code });
|
|
408
417
|
process.off("SIGTERM", cancel);
|
|
418
|
+
clearInterval(cancelWatch);
|
|
409
419
|
}
|
package/dist/tasks.js
CHANGED
|
@@ -2,10 +2,11 @@ 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";
|
|
@@ -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; });
|
|
@@ -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.");
|
|
@@ -264,7 +265,7 @@ export function status(id) {
|
|
|
264
265
|
}
|
|
265
266
|
}
|
|
266
267
|
killGroup(meta.child_pid);
|
|
267
|
-
const reason = meta.stop_reason;
|
|
268
|
+
const reason = meta.stop_reason ?? (fs.existsSync(cancelRequestPath(id, meta.turn)) ? "cancelled" : undefined);
|
|
268
269
|
const decided = reason === "idle" || reason === "max_duration" || reason === "cancelled";
|
|
269
270
|
meta.status = decided ? (reason === "cancelled" ? "cancelled" : "timed_out") : "failed";
|
|
270
271
|
meta.summary = decided ? (reason === "cancelled" ? "Cancelled." : `Timed out: ${reason}.`) : "supervisor exited unexpectedly";
|
|
@@ -289,17 +290,22 @@ export function status(id) {
|
|
|
289
290
|
release();
|
|
290
291
|
}
|
|
291
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;
|
|
292
295
|
export async function cancel(id) {
|
|
293
296
|
let meta = status(id);
|
|
294
297
|
if (meta.status !== "running")
|
|
295
298
|
return meta;
|
|
296
|
-
|
|
299
|
+
fs.writeFileSync(cancelRequestPath(id, meta.turn), "", { flag: "a", mode: 0o600 });
|
|
300
|
+
const start = Date.now();
|
|
297
301
|
let signalled = null;
|
|
298
|
-
|
|
302
|
+
let forced = false;
|
|
303
|
+
while (Date.now() - start < CANCEL_FORCE_MS + 2000) {
|
|
299
304
|
meta = status(id);
|
|
300
305
|
if (meta.status !== "running")
|
|
301
306
|
return meta;
|
|
302
|
-
|
|
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)) {
|
|
303
309
|
try {
|
|
304
310
|
process.kill(meta.supervisor_pid, "SIGTERM");
|
|
305
311
|
signalled = meta.supervisor_pid;
|
|
@@ -309,6 +315,16 @@ export async function cancel(id) {
|
|
|
309
315
|
throw error;
|
|
310
316
|
}
|
|
311
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
|
+
}
|
|
312
328
|
await sleep(20);
|
|
313
329
|
}
|
|
314
330
|
throw new Error("Cancellation not yet confirmed; retry status.");
|
|
@@ -365,9 +381,10 @@ export function apply(id, options = {}) {
|
|
|
365
381
|
? { task_id: id, status: "applied", repo, commit: applied.commit, files: applied.files, removed: false }
|
|
366
382
|
: { task_id: id, status: "nothing_to_apply", repo, removed: false };
|
|
367
383
|
if (options.remove) {
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
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}`;
|
|
371
388
|
}
|
|
372
389
|
return result;
|
|
373
390
|
}
|
|
@@ -436,7 +453,7 @@ export function ls(all = false, cwd = process.cwd()) {
|
|
|
436
453
|
const here = path.resolve(cwd);
|
|
437
454
|
let hereReal = here;
|
|
438
455
|
try {
|
|
439
|
-
hereReal = fs.realpathSync(here);
|
|
456
|
+
hereReal = fs.realpathSync.native(here);
|
|
440
457
|
}
|
|
441
458
|
catch { /* keep resolved */ }
|
|
442
459
|
return listTasks().filter((meta) => {
|
|
@@ -445,9 +462,9 @@ export function ls(all = false, cwd = process.cwd()) {
|
|
|
445
462
|
if (meta.cwd === here || meta.worktree?.source_cwd === here)
|
|
446
463
|
return true;
|
|
447
464
|
try {
|
|
448
|
-
if (fs.realpathSync(meta.cwd) === hereReal)
|
|
465
|
+
if (fs.realpathSync.native(meta.cwd) === hereReal)
|
|
449
466
|
return true;
|
|
450
|
-
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)
|
|
451
468
|
return true;
|
|
452
469
|
}
|
|
453
470
|
catch { /* missing path */ }
|
|
@@ -492,7 +509,7 @@ export function agents(env = process.env) {
|
|
|
492
509
|
const bin = adapter.resolve(env);
|
|
493
510
|
if (!bin)
|
|
494
511
|
return { id: adapter.id, installed: false, bin: null, version: null };
|
|
495
|
-
const ran =
|
|
512
|
+
const ran = crossSpawn.sync(bin, ["--version"], { encoding: "utf8", timeout: 5000, env });
|
|
496
513
|
const version = `${ran.stdout || ""}\n${ran.stderr || ""}`.trim().split("\n").filter(Boolean)[0] || null;
|
|
497
514
|
return { id: adapter.id, installed: true, bin, version };
|
|
498
515
|
});
|
package/dist/usage.js
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
const INSTALL_OPTIONS = {
|
|
2
|
+
only: { type: "string", multiple: true, arg: "agent", desc: "Only this agent: claude, codex, cursor, agy or gemini (repeatable)" },
|
|
3
|
+
force: { type: "boolean", desc: "Reinstall even when already installed" },
|
|
4
|
+
"dry-run": { type: "boolean", desc: "Print the commands without running them" },
|
|
5
|
+
"skip-global": { type: "boolean", desc: "Do not install or update the global baton command" },
|
|
6
|
+
rulesync: { type: "string", arg: "project|global|skip", desc: "Answer the rulesync install question up front" },
|
|
7
|
+
};
|
|
8
|
+
const UPDATE_OPTIONS = { only: INSTALL_OPTIONS.only, "dry-run": INSTALL_OPTIONS["dry-run"], "skip-global": INSTALL_OPTIONS["skip-global"] };
|
|
9
|
+
const UNINSTALL_OPTIONS = { only: INSTALL_OPTIONS.only, "dry-run": INSTALL_OPTIONS["dry-run"] };
|
|
10
|
+
export const COMMANDS = {
|
|
11
|
+
version: { usage: "baton version", summary: "Print the installed baton version." },
|
|
12
|
+
agents: { usage: "baton agents", summary: "List the local agent CLIs baton can delegate to and whether each is installed." },
|
|
13
|
+
start: {
|
|
14
|
+
usage: "baton start --target <agent> [--prompt <text> | stdin] [options]",
|
|
15
|
+
summary: "Start a job in the background and return its task_id.",
|
|
16
|
+
options: {
|
|
17
|
+
target: { type: "string", arg: "agent", desc: "Agent CLI to run: codex, claude, cursor or agy (required)" },
|
|
18
|
+
prompt: { type: "string", arg: "text", desc: "Task prompt; read from stdin when omitted" },
|
|
19
|
+
cwd: { type: "string", arg: "dir", desc: "Working directory for the job (default: current directory)" },
|
|
20
|
+
file: { type: "string", multiple: true, arg: "path", desc: "File the agent should focus on (repeatable)" },
|
|
21
|
+
effort: { type: "string", arg: "low|medium|high|ultra", desc: "Reasoning effort, mapped to the CLI's native flag (not cursor)" },
|
|
22
|
+
model: { type: "string", arg: "id", desc: "Model id for cursor, codex or claude; kept across reply" },
|
|
23
|
+
"idle-timeout": { type: "string", arg: "s", desc: "Stop after this many seconds with no output (default 600)" },
|
|
24
|
+
"max-duration": { type: "string", arg: "s", desc: "Maximum seconds per turn (default unlimited)" },
|
|
25
|
+
scope: { type: "string", multiple: true, arg: "glob", desc: "Paths allowed to change, checked after each turn (repeatable)" },
|
|
26
|
+
"scope-on-violation": { type: "string", arg: "warn|fail", desc: "What an out-of-scope change does (default warn)" },
|
|
27
|
+
mode: { type: "string", arg: "readonly|write", desc: "Permission mode (default write)" },
|
|
28
|
+
"allow-weak": { type: "boolean", desc: "Allow --mode readonly on a target that cannot enforce it" },
|
|
29
|
+
isolate: { type: "boolean", desc: "Run in a new git worktree; bring the work back with baton apply" },
|
|
30
|
+
"allow-dirty": { type: "boolean", desc: "Allow an in-place write job on a dirty working tree" },
|
|
31
|
+
rules: { type: "string", arg: "check|pointer|off", desc: "Project rule file discovery (default check)" },
|
|
32
|
+
check: { type: "string", arg: "cmd", desc: "Shell command run after each successful turn; non-zero ends it as check_failed" },
|
|
33
|
+
},
|
|
34
|
+
examples: [
|
|
35
|
+
"baton start --target codex --isolate --prompt \"fix the failing test in test/a.test.ts\"",
|
|
36
|
+
"baton start --target claude --mode readonly --scope \"src/**\" < task.md",
|
|
37
|
+
],
|
|
38
|
+
},
|
|
39
|
+
status: { usage: "baton status <task_id>", summary: "Print a job's current status; while running, includes liveness." },
|
|
40
|
+
cancel: { usage: "baton cancel <task_id>", summary: "Stop a running job and its whole process group." },
|
|
41
|
+
wait: {
|
|
42
|
+
usage: "baton wait <task_id>... [--for <s> | --until-done]",
|
|
43
|
+
summary: "Wait until any of the jobs leaves running, or until the time runs out.",
|
|
44
|
+
options: {
|
|
45
|
+
for: { type: "string", arg: "s", desc: "Seconds to wait (default 50)" },
|
|
46
|
+
"until-done": { type: "boolean", desc: "Block until a job leaves running" },
|
|
47
|
+
},
|
|
48
|
+
},
|
|
49
|
+
result: {
|
|
50
|
+
usage: "baton result <task_id> [--turn <n>]",
|
|
51
|
+
summary: "Print the agent's full final message of a finished turn as plain text.",
|
|
52
|
+
options: { turn: { type: "string", arg: "n", desc: "Turn number (default latest)" } },
|
|
53
|
+
},
|
|
54
|
+
diff: {
|
|
55
|
+
usage: "baton diff <task_id> [--stat]",
|
|
56
|
+
summary: "Print the net change of an --isolate job as a plain-text patch.",
|
|
57
|
+
options: { stat: { type: "boolean", desc: "Print a diffstat instead of the patch" } },
|
|
58
|
+
},
|
|
59
|
+
apply: {
|
|
60
|
+
usage: "baton apply <task_id> [--remove]",
|
|
61
|
+
summary: "Bring an --isolate job's net change onto the current branch as one local commit; never pushes.",
|
|
62
|
+
options: { remove: { type: "boolean", desc: "Delete the worktree and its branch after a successful apply" } },
|
|
63
|
+
},
|
|
64
|
+
tail: {
|
|
65
|
+
usage: "baton tail <task_id> [-f] [--raw]",
|
|
66
|
+
summary: "Print a job's events in readable form.",
|
|
67
|
+
options: {
|
|
68
|
+
follow: { type: "boolean", short: "f", desc: "Keep following until the job stops" },
|
|
69
|
+
raw: { type: "boolean", desc: "Print the raw events.jsonl lines" },
|
|
70
|
+
},
|
|
71
|
+
},
|
|
72
|
+
reply: {
|
|
73
|
+
usage: "baton reply <task_id> [--prompt <text> | stdin] [--as host|human]",
|
|
74
|
+
summary: "Start the next turn of a stopped job in the same session.",
|
|
75
|
+
options: {
|
|
76
|
+
prompt: { type: "string", arg: "text", desc: "Reply text; read from stdin when omitted" },
|
|
77
|
+
as: { type: "string", arg: "host|human", desc: "Who is speaking (default host)" },
|
|
78
|
+
},
|
|
79
|
+
},
|
|
80
|
+
ls: {
|
|
81
|
+
usage: "baton ls [--all]",
|
|
82
|
+
summary: "List jobs for the current directory, newest first.",
|
|
83
|
+
options: { all: { type: "boolean", desc: "List jobs from every directory" } },
|
|
84
|
+
},
|
|
85
|
+
prune: {
|
|
86
|
+
usage: "baton prune --older <days>",
|
|
87
|
+
summary: "Delete non-running task directories older than N days (worktrees are kept).",
|
|
88
|
+
options: { older: { type: "string", arg: "days", desc: "Age threshold in days (required)" } },
|
|
89
|
+
},
|
|
90
|
+
worktree: {
|
|
91
|
+
usage: "baton worktree add [options] | ls | rm <name-or-path>",
|
|
92
|
+
summary: "Manage baton worktrees under .worktrees/.",
|
|
93
|
+
options: {
|
|
94
|
+
name: { type: "string", arg: "id", desc: "Worktree name (add)" },
|
|
95
|
+
branch: { type: "string", arg: "name", desc: "Branch to create (add)" },
|
|
96
|
+
base: { type: "string", arg: "ref", desc: "Ref to start from (add; default HEAD)" },
|
|
97
|
+
},
|
|
98
|
+
notes: ["rm refuses dirty or unmerged trees; when clean it removes the tree and deletes the local branch."],
|
|
99
|
+
},
|
|
100
|
+
rules: {
|
|
101
|
+
usage: "baton rules init [options]",
|
|
102
|
+
summary: "Set up rulesync so your agents share one set of rules.",
|
|
103
|
+
options: {
|
|
104
|
+
install: { type: "string", arg: "project|global|skip", desc: "How to install rulesync when it is missing" },
|
|
105
|
+
source: { type: "string", arg: "agent", desc: "Import existing rules from claudecode, codexcli or cursor" },
|
|
106
|
+
template: { type: "boolean", desc: "Start from baton's template instead of importing" },
|
|
107
|
+
targets: { type: "string", multiple: true, arg: "agent[,agent]", desc: "Agents to generate for (default: detected hosts)" },
|
|
108
|
+
yes: { type: "boolean", desc: "Apply the generated changes without asking" },
|
|
109
|
+
"dry-run": { type: "boolean", desc: "Preview only" },
|
|
110
|
+
},
|
|
111
|
+
},
|
|
112
|
+
install: {
|
|
113
|
+
usage: "baton install [options]",
|
|
114
|
+
summary: "Install the global baton command and the plugin into your agent CLIs.",
|
|
115
|
+
options: INSTALL_OPTIONS,
|
|
116
|
+
},
|
|
117
|
+
update: {
|
|
118
|
+
usage: "baton update [--only <agent>]... [--dry-run] [--skip-global]",
|
|
119
|
+
summary: "Update the global baton command and the installed plugins.",
|
|
120
|
+
options: UPDATE_OPTIONS,
|
|
121
|
+
},
|
|
122
|
+
uninstall: {
|
|
123
|
+
usage: "baton uninstall [--only <agent>]... [--dry-run]",
|
|
124
|
+
summary: "Remove the baton plugin from your agent CLIs.",
|
|
125
|
+
options: UNINSTALL_OPTIONS,
|
|
126
|
+
},
|
|
127
|
+
mcp: { usage: "baton mcp", summary: "Start the MCP server on stdio." },
|
|
128
|
+
report: {
|
|
129
|
+
usage: "baton report [task_id] [--title <text>] [--submit]",
|
|
130
|
+
summary: "Generate a redacted diagnostic report and GitHub issue link (optionally submit).",
|
|
131
|
+
options: {
|
|
132
|
+
title: { type: "string", arg: "text", desc: "Issue title override" },
|
|
133
|
+
submit: { type: "boolean", desc: "Create the issue via gh if logged in, otherwise open the prefilled form in a browser" },
|
|
134
|
+
},
|
|
135
|
+
notes: ["Never includes prompts, raw logs, file names, or credentials; still review before posting."],
|
|
136
|
+
},
|
|
137
|
+
};
|
|
138
|
+
export function isCommand(name) {
|
|
139
|
+
return name !== undefined && Object.hasOwn(COMMANDS, name);
|
|
140
|
+
}
|
|
141
|
+
/** `-h` / `--help` anywhere before `--`. */
|
|
142
|
+
export function wantsHelp(args) {
|
|
143
|
+
const end = args.indexOf("--");
|
|
144
|
+
return (end < 0 ? args : args.slice(0, end)).some((arg) => arg === "-h" || arg === "--help");
|
|
145
|
+
}
|
|
146
|
+
export const commandList = `Usage: baton ${Object.keys(COMMANDS).join(" | ")}`;
|
|
147
|
+
function columns(rows) {
|
|
148
|
+
const width = Math.max(...rows.map(([left]) => left.length)) + 2;
|
|
149
|
+
return rows.map(([left, right]) => ` ${left.padEnd(width)}${right}`);
|
|
150
|
+
}
|
|
151
|
+
export function renderHelp(name) {
|
|
152
|
+
if (!name) {
|
|
153
|
+
return [
|
|
154
|
+
"Usage: baton <command> [options]",
|
|
155
|
+
"",
|
|
156
|
+
"Hand a bounded coding task to another local agent CLI, then continue the same session.",
|
|
157
|
+
"",
|
|
158
|
+
"Commands:",
|
|
159
|
+
...columns(Object.entries(COMMANDS).map(([cmd, def]) => [cmd, def.summary])),
|
|
160
|
+
"",
|
|
161
|
+
"Run `baton <command> --help` for a command's options.",
|
|
162
|
+
"",
|
|
163
|
+
].join("\n");
|
|
164
|
+
}
|
|
165
|
+
const cmd = COMMANDS[name];
|
|
166
|
+
const options = Object.entries(cmd.options ?? {}).map(([key, opt]) => [
|
|
167
|
+
`${opt.short ? `-${opt.short}, ` : ""}--${key}${opt.type === "string" ? ` <${opt.arg ?? "value"}>` : ""}`,
|
|
168
|
+
opt.desc,
|
|
169
|
+
]);
|
|
170
|
+
options.push(["-h, --help", "Show this help"]);
|
|
171
|
+
return [
|
|
172
|
+
`Usage: ${cmd.usage}`,
|
|
173
|
+
"",
|
|
174
|
+
cmd.summary,
|
|
175
|
+
"",
|
|
176
|
+
"Options:",
|
|
177
|
+
...columns(options),
|
|
178
|
+
...(cmd.notes?.length ? ["", ...cmd.notes] : []),
|
|
179
|
+
...(cmd.examples?.length ? ["", "Examples:", ...cmd.examples.map((line) => ` ${line}`)] : []),
|
|
180
|
+
"",
|
|
181
|
+
].join("\n");
|
|
182
|
+
}
|
package/dist/worktree.js
CHANGED
|
@@ -2,6 +2,7 @@ import fs from "node:fs";
|
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { randomBytes } from "node:crypto";
|
|
4
4
|
import { spawnSync } from "node:child_process";
|
|
5
|
+
import crossSpawn from "cross-spawn";
|
|
5
6
|
import { hasRulesyncSource, resolveRulesync, RULE_ENTRIES } from "./rules.js";
|
|
6
7
|
import { redact } from "./redact.js";
|
|
7
8
|
const META_NAME = ".baton-worktree.json";
|
|
@@ -100,9 +101,22 @@ export function applyTree(repo, base, tree, message) {
|
|
|
100
101
|
return { commit: headSha(repo), files };
|
|
101
102
|
}
|
|
102
103
|
/** Delete a task's worktree and branch regardless of their state; true when both are gone. */
|
|
104
|
+
/** Removes an --isolate worktree and its branch; null on success, otherwise what stayed behind and what git said. */
|
|
103
105
|
export function removeTaskWorktree(repo, worktreePath, branch) {
|
|
104
|
-
cleanupWorktree(repo, worktreePath, branch);
|
|
105
|
-
|
|
106
|
+
const problems = cleanupWorktree(repo, worktreePath, branch);
|
|
107
|
+
// Windows keeps a deleted directory visible ("delete pending", or git leaves it) until the last handle on it closes, e.g. a worker that is still exiting.
|
|
108
|
+
for (let wait = 0; process.platform === "win32" && wait < 20 && fs.existsSync(worktreePath); wait++) {
|
|
109
|
+
try {
|
|
110
|
+
fs.rmSync(worktreePath, { recursive: true, force: true });
|
|
111
|
+
}
|
|
112
|
+
catch { /* still held */ }
|
|
113
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 100);
|
|
114
|
+
}
|
|
115
|
+
if (fs.existsSync(worktreePath))
|
|
116
|
+
problems.push(`${worktreePath} still exists`);
|
|
117
|
+
if (git(repo, ["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`]).status === 0)
|
|
118
|
+
problems.push(`branch ${branch} still exists`);
|
|
119
|
+
return problems.length ? problems.join("; ") : null;
|
|
106
120
|
}
|
|
107
121
|
function strings(value) {
|
|
108
122
|
return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
|
|
@@ -164,8 +178,8 @@ export function assertNotNestedWorktree(cwd) {
|
|
|
164
178
|
if (dir.status !== 0 || common.status !== 0)
|
|
165
179
|
throw new Error("Current directory is not a git repository.");
|
|
166
180
|
// realpath: on macOS /var vs /private/var must not look like a linked worktree.
|
|
167
|
-
const gitDir = fs.realpathSync(path.resolve(cwd, dir.stdout.trim()));
|
|
168
|
-
const gitCommon = fs.realpathSync(path.resolve(cwd, common.stdout.trim()));
|
|
181
|
+
const gitDir = fs.realpathSync.native(path.resolve(cwd, dir.stdout.trim()));
|
|
182
|
+
const gitCommon = fs.realpathSync.native(path.resolve(cwd, common.stdout.trim()));
|
|
169
183
|
if (gitDir === gitCommon)
|
|
170
184
|
return;
|
|
171
185
|
const superproject = git(cwd, ["rev-parse", "--show-superproject-working-tree"]);
|
|
@@ -190,8 +204,8 @@ export function batonWorktreeExemptPaths(cwd) {
|
|
|
190
204
|
const common = git(cwd, ["rev-parse", "--git-common-dir"]);
|
|
191
205
|
if (dir.status !== 0 || common.status !== 0)
|
|
192
206
|
return new Set();
|
|
193
|
-
const gitDir = fs.realpathSync(path.resolve(cwd, dir.stdout.trim()));
|
|
194
|
-
const gitCommon = fs.realpathSync(path.resolve(cwd, common.stdout.trim()));
|
|
207
|
+
const gitDir = fs.realpathSync.native(path.resolve(cwd, dir.stdout.trim()));
|
|
208
|
+
const gitCommon = fs.realpathSync.native(path.resolve(cwd, common.stdout.trim()));
|
|
195
209
|
if (gitDir === gitCommon)
|
|
196
210
|
return new Set(); // main checkout
|
|
197
211
|
const top = git(cwd, ["rev-parse", "--show-toplevel"]);
|
|
@@ -297,7 +311,7 @@ function applyWorktreeRulesync(repo, worktreePath, cfg) {
|
|
|
297
311
|
if (!bin) {
|
|
298
312
|
return { rulesync: "skipped", detail: "rulesync not found in node_modules/.bin or PATH", missing, dirtied: [] };
|
|
299
313
|
}
|
|
300
|
-
const ran =
|
|
314
|
+
const ran = crossSpawn.sync(bin, ["generate"], {
|
|
301
315
|
cwd: worktreePath,
|
|
302
316
|
encoding: "utf8",
|
|
303
317
|
env: { ...process.env, BATON_DELEGATION: "1" },
|
|
@@ -365,7 +379,15 @@ function prepareWorktree(repo, worktreePath, cfg) {
|
|
|
365
379
|
continue;
|
|
366
380
|
if (fs.existsSync(dest))
|
|
367
381
|
fs.rmSync(dest, { recursive: true, force: true });
|
|
368
|
-
|
|
382
|
+
try {
|
|
383
|
+
// junction: Windows lets any user link a directory this way; file links need Developer Mode or admin.
|
|
384
|
+
fs.symlinkSync(src, dest, fs.statSync(src).isDirectory() ? "junction" : "file");
|
|
385
|
+
}
|
|
386
|
+
catch (error) {
|
|
387
|
+
if (error.code !== "EPERM")
|
|
388
|
+
throw error;
|
|
389
|
+
throw new Error(`cannot symlink ${name}: Windows needs Developer Mode or admin rights for file links; list it under "copy" in .baton.json instead.`);
|
|
390
|
+
}
|
|
369
391
|
}
|
|
370
392
|
}
|
|
371
393
|
for (const command of cfg.post_create) {
|
|
@@ -383,9 +405,13 @@ function prepareWorktree(repo, worktreePath, cfg) {
|
|
|
383
405
|
}
|
|
384
406
|
}
|
|
385
407
|
function cleanupWorktree(repo, worktreePath, branch) {
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
408
|
+
const errors = [];
|
|
409
|
+
for (const args of [["worktree", "remove", "--force", worktreePath], ["branch", "-D", branch], ["worktree", "prune"]]) {
|
|
410
|
+
const ran = git(repo, args);
|
|
411
|
+
if (ran.status !== 0)
|
|
412
|
+
errors.push(`git ${args.slice(0, 2).join(" ")}: ${(ran.stderr || ran.stdout).trim()}`);
|
|
413
|
+
}
|
|
414
|
+
return errors;
|
|
389
415
|
}
|
|
390
416
|
function resolveManagedPath(cwd, nameOrPath) {
|
|
391
417
|
const repo = resolveRepoRoot(cwd);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@speculoai/baton",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"description": "Hand a bounded coding task to another local agent CLI, then continue the same session when it needs a decision.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -23,7 +23,9 @@
|
|
|
23
23
|
},
|
|
24
24
|
"dependencies": {
|
|
25
25
|
"@clack/prompts": "^1.9.0",
|
|
26
|
-
"@modelcontextprotocol/sdk": "^1.20.2"
|
|
26
|
+
"@modelcontextprotocol/sdk": "^1.20.2",
|
|
27
|
+
"cross-spawn": "^7.0.6",
|
|
28
|
+
"picomatch": "^4.0.7"
|
|
27
29
|
},
|
|
28
30
|
"engines": {
|
|
29
31
|
"node": ">=20.17"
|
|
@@ -32,7 +34,9 @@
|
|
|
32
34
|
"access": "public"
|
|
33
35
|
},
|
|
34
36
|
"devDependencies": {
|
|
37
|
+
"@types/cross-spawn": "^6.0.6",
|
|
35
38
|
"@types/node": "^26.6.6",
|
|
39
|
+
"@types/picomatch": "^4.0.3",
|
|
36
40
|
"typescript": "^7.0.2"
|
|
37
41
|
}
|
|
38
42
|
}
|