@speculoai/baton 0.7.0 → 0.8.1
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 +4 -3
- package/README.zh-CN.md +4 -3
- package/dist/adapters/agy.js +3 -2
- package/dist/adapters/claude.js +2 -2
- package/dist/adapters/common.js +39 -11
- package/dist/adapters/cursor.js +2 -2
- package/dist/adapters/index.js +2 -1
- package/dist/adapters/kimi.js +84 -0
- package/dist/cli.js +65 -38
- package/dist/install-ui.js +3 -0
- package/dist/install.js +87 -28
- package/dist/mcp.js +4 -3
- package/dist/process.js +18 -0
- package/dist/report.js +194 -0
- package/dist/rules.js +8 -10
- 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 +35 -18
- package/dist/usage.js +212 -0
- package/dist/worktree.js +71 -27
- package/package.json +6 -2
package/dist/install.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
|
-
import
|
|
1
|
+
import spawn from "cross-spawn";
|
|
2
2
|
import fs from "node:fs";
|
|
3
3
|
import path from "node:path";
|
|
4
|
+
import { isDeepStrictEqual } from "node:util";
|
|
4
5
|
import { which } from "./adapters/common.js";
|
|
6
|
+
import { killGroup } from "./process.js";
|
|
5
7
|
import { batonHome } from "./store.js";
|
|
6
8
|
export const REPO = "https://github.com/SpeculoAI/baton";
|
|
7
9
|
const PLUGIN_ID = "baton@speculoai";
|
|
@@ -30,6 +32,7 @@ export const HOSTS = [
|
|
|
30
32
|
id: "codex",
|
|
31
33
|
label: "Codex CLI",
|
|
32
34
|
bins: ["codex"],
|
|
35
|
+
refreshOnInstall: true,
|
|
33
36
|
migrate: [
|
|
34
37
|
{ args: ["plugin", "remove", OLD_ID], soft: true },
|
|
35
38
|
{ args: ["plugin", "marketplace", "remove", OLD_MARKET], soft: true },
|
|
@@ -74,15 +77,22 @@ export const HOSTS = [
|
|
|
74
77
|
export function detectedHosts(env = process.env) {
|
|
75
78
|
return HOSTS.filter((host) => which(host.bins, env)).map((host) => ({ id: host.id, label: host.label }));
|
|
76
79
|
}
|
|
77
|
-
|
|
80
|
+
function hostFor(id) {
|
|
78
81
|
const host = HOSTS.find((item) => item.id === id);
|
|
79
82
|
if (!host)
|
|
80
83
|
throw new Error(`Unknown agent: ${id}`);
|
|
84
|
+
return host;
|
|
85
|
+
}
|
|
86
|
+
export function commandsFor(id, action, opts = {}) {
|
|
87
|
+
const host = hostFor(id);
|
|
81
88
|
if (action !== "install")
|
|
82
89
|
return host[action];
|
|
83
90
|
const forced = opts.force ? host.uninstall.map((step) => ({ ...step, soft: true })) : [];
|
|
84
91
|
return [...(host.migrate ?? []), ...forced, ...host.install];
|
|
85
92
|
}
|
|
93
|
+
function installUpdateSteps(host) {
|
|
94
|
+
return isDeepStrictEqual(host.install, host.update) ? [] : host.update;
|
|
95
|
+
}
|
|
86
96
|
export function planInstall(input) {
|
|
87
97
|
const env = input.env ?? process.env;
|
|
88
98
|
const known = new Set(HOSTS.map((host) => host.id));
|
|
@@ -97,9 +107,7 @@ export function planInstall(input) {
|
|
|
97
107
|
const hosts = [];
|
|
98
108
|
const missing = [];
|
|
99
109
|
for (const id of ids) {
|
|
100
|
-
const host =
|
|
101
|
-
if (!host)
|
|
102
|
-
throw new Error(`Unknown agent: ${id}`);
|
|
110
|
+
const host = hostFor(id);
|
|
103
111
|
const bin = which(host.bins, env);
|
|
104
112
|
if (!bin) {
|
|
105
113
|
if (input.only?.length)
|
|
@@ -107,10 +115,13 @@ export function planInstall(input) {
|
|
|
107
115
|
missing.push(id);
|
|
108
116
|
continue;
|
|
109
117
|
}
|
|
118
|
+
const steps = commandsFor(id, input.action, { force: input.force });
|
|
119
|
+
if (input.action === "install")
|
|
120
|
+
steps.push(...installUpdateSteps(host));
|
|
110
121
|
hosts.push({
|
|
111
122
|
id,
|
|
112
123
|
bin,
|
|
113
|
-
commands:
|
|
124
|
+
commands: steps.map((step) => step.args),
|
|
114
125
|
...(host.note && input.action === "install" ? { note: host.note } : {}),
|
|
115
126
|
});
|
|
116
127
|
}
|
|
@@ -118,7 +129,7 @@ export function planInstall(input) {
|
|
|
118
129
|
return { hosts, missing };
|
|
119
130
|
const version = JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
|
|
120
131
|
const spec = input.action === "update" ? "@speculoai/baton@latest" : `@speculoai/baton@${version}`;
|
|
121
|
-
return { hosts, missing, global: { command: [
|
|
132
|
+
return { hosts, missing, global: { command: ["npm", "install", "-g", spec] } };
|
|
122
133
|
}
|
|
123
134
|
export function readInstalled(home = batonHome()) {
|
|
124
135
|
try {
|
|
@@ -133,14 +144,30 @@ export function writeInstalled(ids, home = batonHome()) {
|
|
|
133
144
|
fs.mkdirSync(home, { recursive: true });
|
|
134
145
|
fs.writeFileSync(path.join(home, "installed.json"), `${JSON.stringify({ hosts: [...new Set(ids)] })}\n`);
|
|
135
146
|
}
|
|
136
|
-
|
|
147
|
+
// A host command stuck on a prompt nobody can see (Gemini's "install via git clone instead? [Y/n]") must not hang install.
|
|
148
|
+
export const HOST_STEP_TIMEOUT_MS = 120_000;
|
|
149
|
+
function defaultSpawn(command, args, env, quiet = false, timeoutMs) {
|
|
137
150
|
return new Promise((resolve) => {
|
|
138
|
-
|
|
151
|
+
// Host steps run in their own process group (POSIX) so a timeout kills the whole tree; stdin is closed because
|
|
152
|
+
// their output is hidden behind the spinner. shortcut: Ctrl+C on baton does not reach a detached host step.
|
|
153
|
+
const child = timeoutMs
|
|
154
|
+
? spawn(command, args, { env, detached: process.platform !== "win32", windowsHide: true, stdio: ["ignore", "pipe", "pipe"] })
|
|
155
|
+
: spawn(command, args, { env, stdio: ["inherit", "pipe", "pipe"] });
|
|
139
156
|
let stdout = "";
|
|
140
157
|
let stderr = "";
|
|
141
158
|
let settled = false;
|
|
159
|
+
const timer = timeoutMs
|
|
160
|
+
? setTimeout(() => {
|
|
161
|
+
try {
|
|
162
|
+
killGroup(child.pid ?? null);
|
|
163
|
+
}
|
|
164
|
+
catch { /* already gone */ }
|
|
165
|
+
finish({ status: 1, stdout, stderr: `${stderr}\ntimed out after ${timeoutMs / 1000}s: ${command} ${args.join(" ")}` });
|
|
166
|
+
}, timeoutMs)
|
|
167
|
+
: undefined;
|
|
142
168
|
const finish = (result) => { if (!settled) {
|
|
143
169
|
settled = true;
|
|
170
|
+
clearTimeout(timer);
|
|
144
171
|
resolve(result);
|
|
145
172
|
} };
|
|
146
173
|
// Soft migrate steps and TTY spinners must not live-tee: expected "Failed to uninstall old id"
|
|
@@ -169,14 +196,22 @@ export async function runInstall(input) {
|
|
|
169
196
|
return { exitCode: 0, result: { action: input.action, hosts: [] } };
|
|
170
197
|
only = picked;
|
|
171
198
|
}
|
|
172
|
-
const
|
|
199
|
+
const recorded = readInstalled(home);
|
|
200
|
+
const planned = planInstall({ action: input.action, only, force: input.force, skipGlobal: input.skipGlobal, env, recorded });
|
|
201
|
+
const resultBase = {
|
|
202
|
+
action: input.action,
|
|
203
|
+
...(planned.missing.length ? { missing: planned.missing } : {}),
|
|
204
|
+
...(input.action === "update" && !only?.length && !recorded.length
|
|
205
|
+
? { warnings: ["no recorded hosts; run `baton install` to install the plugin into agent CLIs"] }
|
|
206
|
+
: {}),
|
|
207
|
+
};
|
|
173
208
|
if (input.dryRun) {
|
|
174
209
|
return {
|
|
175
210
|
exitCode: 0,
|
|
176
|
-
result: {
|
|
211
|
+
result: { ...resultBase, dry_run: true, ...(planned.global ? { global: planned.global } : {}), hosts: planned.hosts },
|
|
177
212
|
};
|
|
178
213
|
}
|
|
179
|
-
const run = (command, args, quiet) => input.spawn ? input.spawn(command, args) : defaultSpawn(command, args, env, quiet);
|
|
214
|
+
const run = (command, args, quiet, timeoutMs) => input.spawn ? input.spawn(command, args) : defaultSpawn(command, args, env, quiet, timeoutMs);
|
|
180
215
|
const report = input.onProgress;
|
|
181
216
|
let global;
|
|
182
217
|
if (planned.global) {
|
|
@@ -186,41 +221,65 @@ export async function runInstall(input) {
|
|
|
186
221
|
report?.({ type: "global", phase: "done", ok: global.ok, ...(global.error ? { error: global.error } : {}) });
|
|
187
222
|
}
|
|
188
223
|
const hosts = [];
|
|
224
|
+
const installed = [];
|
|
189
225
|
for (const host of planned.hosts) {
|
|
190
226
|
report?.({ type: "host", phase: "start", id: host.id });
|
|
191
227
|
let error;
|
|
192
|
-
let
|
|
228
|
+
let alreadyInstalled = false;
|
|
229
|
+
const runStep = (step) => run(host.bin, step.args, Boolean(input.quiet || step.soft), input.stepTimeoutMs ?? HOST_STEP_TIMEOUT_MS);
|
|
193
230
|
for (const step of commandsFor(host.id, input.action, { force: input.force })) {
|
|
194
231
|
// Soft steps (old-id migrate) often print "Failed to uninstall…" — hide that when overall install is fine.
|
|
195
|
-
const ran = await
|
|
196
|
-
if (
|
|
232
|
+
const ran = await runStep(step);
|
|
233
|
+
if (step.soft)
|
|
197
234
|
continue;
|
|
198
|
-
if (/already installed/i.test(`${ran.stdout || ""}\n${ran.stderr || ""}`)) {
|
|
199
|
-
|
|
235
|
+
if ((input.action === "install" || ran.status !== 0) && /already installed/i.test(`${ran.stdout || ""}\n${ran.stderr || ""}`)) {
|
|
236
|
+
alreadyInstalled = true;
|
|
200
237
|
continue;
|
|
201
238
|
}
|
|
239
|
+
if (ran.status === 0)
|
|
240
|
+
continue;
|
|
202
241
|
error = failText(ran);
|
|
203
242
|
break;
|
|
204
243
|
}
|
|
205
|
-
|
|
244
|
+
let note = alreadyInstalled ? "already installed, skipped" : host.note;
|
|
245
|
+
if (input.action === "install" && !error) {
|
|
246
|
+
installed.push(host.id);
|
|
247
|
+
const target = hostFor(host.id);
|
|
248
|
+
if (alreadyInstalled || target.refreshOnInstall) {
|
|
249
|
+
const steps = installUpdateSteps(target);
|
|
250
|
+
for (const step of steps) {
|
|
251
|
+
const ran = await runStep(step);
|
|
252
|
+
if (ran.status === 0 || step.soft)
|
|
253
|
+
continue;
|
|
254
|
+
error = failText(ran);
|
|
255
|
+
break;
|
|
256
|
+
}
|
|
257
|
+
if (steps.length && alreadyInstalled)
|
|
258
|
+
note = error ? undefined : "already installed, updated";
|
|
259
|
+
}
|
|
260
|
+
}
|
|
206
261
|
const row = { id: host.id, ok: !error, ...(note ? { note } : {}), ...(error ? { error } : {}) };
|
|
207
262
|
hosts.push(row);
|
|
208
263
|
report?.({ type: "host", phase: "done", id: host.id, ok: row.ok, ...(note ? { note } : {}), ...(error ? { error } : {}) });
|
|
209
264
|
}
|
|
210
265
|
if (input.action !== "update") {
|
|
211
|
-
const
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
266
|
+
const current = new Set(readInstalled(home));
|
|
267
|
+
if (input.action === "install") {
|
|
268
|
+
for (const id of installed)
|
|
269
|
+
current.add(id);
|
|
270
|
+
}
|
|
271
|
+
else {
|
|
272
|
+
for (const host of hosts)
|
|
273
|
+
if (host.ok)
|
|
274
|
+
current.delete(host.id);
|
|
219
275
|
}
|
|
220
|
-
writeInstalled([...
|
|
276
|
+
writeInstalled([...current], home);
|
|
221
277
|
}
|
|
278
|
+
const note = input.action !== "uninstall" && hosts.some((host) => host.ok)
|
|
279
|
+
? "Restart open agent sessions to load the updated skills and MCP."
|
|
280
|
+
: undefined;
|
|
222
281
|
return {
|
|
223
282
|
exitCode: hosts.some((host) => !host.ok) ? 1 : 0,
|
|
224
|
-
result: {
|
|
283
|
+
result: { ...resultBase, ...(global ? { global } : {}), hosts, ...(note ? { note } : {}) },
|
|
225
284
|
};
|
|
226
285
|
}
|
package/dist/mcp.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
1
2
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2
3
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
3
4
|
import { z } from "zod";
|
|
@@ -17,16 +18,16 @@ async function respond(run) {
|
|
|
17
18
|
return { content: [{ type: "text", text: JSON.stringify(value) }] };
|
|
18
19
|
}
|
|
19
20
|
export function createServer() {
|
|
20
|
-
const server = new McpServer({ name: "baton", version: "
|
|
21
|
+
const server = new McpServer({ name: "baton", version: JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf8")).version });
|
|
21
22
|
server.registerTool("list_agents", { description: "List local CLIs available for delegation and whether each is installed." }, () => respond(() => ({ agents: agents() })));
|
|
22
23
|
server.registerTool("delegate_task", {
|
|
23
24
|
description: "Delegate a bounded task to another local AI CLI. Returns task_id immediately (status=running); the task runs in a separate process and survives exit of this MCP process or the host session. Then use task_wait for a bounded wait.",
|
|
24
25
|
inputSchema: {
|
|
25
|
-
target_agent: z.enum(["codex", "claude", "cursor", "agy"]),
|
|
26
|
+
target_agent: z.enum(["codex", "claude", "cursor", "agy", "kimi"]),
|
|
26
27
|
prompt: z.string(),
|
|
27
28
|
files: z.array(z.string()).optional(),
|
|
28
29
|
reasoning_effort: z.enum(["low", "medium", "high", "ultra"]).optional(),
|
|
29
|
-
model: z.string().optional().describe("Per-task model (cursor, codex and
|
|
30
|
+
model: z.string().optional().describe("Per-task model (cursor, codex, claude and kimi; stored in meta and carried over by reply)."),
|
|
30
31
|
idle_timeout_seconds: z.number().optional().describe("Stop after this long with no output at all; default 600."),
|
|
31
32
|
max_duration_seconds: z.number().optional().describe("Maximum total duration per turn; default unlimited."),
|
|
32
33
|
cwd: z.string().optional(),
|
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,194 @@
|
|
|
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, labels, body, shortBody) {
|
|
98
|
+
const make = (b) => `${ISSUE_NEW_URL}?${new URLSearchParams({ title, labels: labels.join(","), body: b }).toString()}`;
|
|
99
|
+
const full = make(body);
|
|
100
|
+
return full.length <= MAX_URL_LEN ? full : make(shortBody);
|
|
101
|
+
}
|
|
102
|
+
export function buildReport(taskId, opts = {}) {
|
|
103
|
+
const meta = taskId ? readMeta(taskId) : null;
|
|
104
|
+
if (taskId && !meta)
|
|
105
|
+
throw new Error("No such task.");
|
|
106
|
+
const detected = agents().map((a) => `- ${a.id}: ${a.installed ? (a.version ? clip(sanitize(a.version), 80) : "installed") : "not installed"}`);
|
|
107
|
+
const envSection = [
|
|
108
|
+
"### Environment",
|
|
109
|
+
`- baton: ${readVersion()}`,
|
|
110
|
+
`- node: ${process.version}`,
|
|
111
|
+
`- os: ${process.platform} ${process.arch} (${os.release()})`,
|
|
112
|
+
"- agents:",
|
|
113
|
+
...detected.map((line) => ` ${line}`),
|
|
114
|
+
];
|
|
115
|
+
const taskSection = [];
|
|
116
|
+
if (meta) {
|
|
117
|
+
const fields = [
|
|
118
|
+
["target", meta.target],
|
|
119
|
+
["status", meta.status],
|
|
120
|
+
["turn", meta.turn],
|
|
121
|
+
["mode", meta.mode],
|
|
122
|
+
["enforcement", meta.enforcement],
|
|
123
|
+
["isolated", Boolean(meta.worktree)],
|
|
124
|
+
["stop_reason", meta.stop_reason],
|
|
125
|
+
["idle_timeout_s", meta.idle_timeout_s],
|
|
126
|
+
["max_duration_s", meta.max_duration_s ?? undefined],
|
|
127
|
+
["scope_on_violation", meta.scope_on_violation],
|
|
128
|
+
["rules_mode", meta.rules?.mode],
|
|
129
|
+
["rulesync_status", meta.rules?.rulesync?.status],
|
|
130
|
+
["check", meta.check ? `${meta.check.status} (exit=${meta.check.exit_code ?? "null"}, ${meta.check.duration_ms}ms)` : undefined],
|
|
131
|
+
["summary", safeSummary(meta)],
|
|
132
|
+
];
|
|
133
|
+
taskSection.push("", "### Task (redacted)", ...fields.filter(([, value]) => value !== undefined).map(([key, value]) => `- ${key}: ${value}`));
|
|
134
|
+
const timeline = readEventSkeleton(meta.task_id, meta.cwd);
|
|
135
|
+
if (timeline.length) {
|
|
136
|
+
taskSection.push("", "### Event timeline", "```text", ...timeline, "```");
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
const header = [
|
|
140
|
+
"> Review before posting: remove any project-specific terms if present.",
|
|
141
|
+
"",
|
|
142
|
+
"### What happened",
|
|
143
|
+
opts.body?.trim() ? sanitize(opts.body.trim(), meta?.cwd) : "<!-- Describe what you expected vs. what happened -->",
|
|
144
|
+
"",
|
|
145
|
+
];
|
|
146
|
+
const markdown = [...header, ...envSection, ...taskSection].join("\n");
|
|
147
|
+
const title = opts.title?.trim() || (meta ? `bug(${meta.target}): ${meta.status}` : "bug: <describe issue>");
|
|
148
|
+
const given = (opts.labels ?? []).map((l) => l.trim()).filter(Boolean);
|
|
149
|
+
const labels = given.length ? given : ["bug"];
|
|
150
|
+
const shortBody = [
|
|
151
|
+
...header,
|
|
152
|
+
...envSection,
|
|
153
|
+
"",
|
|
154
|
+
"<!-- Full task timeline omitted for URL length; paste the output of `baton report` here -->",
|
|
155
|
+
].join("\n");
|
|
156
|
+
const issueUrl = makeIssueUrl(title, labels, markdown, shortBody);
|
|
157
|
+
return { title, labels, markdown, issueUrl };
|
|
158
|
+
}
|
|
159
|
+
function defaultOpenBrowser(url) {
|
|
160
|
+
try {
|
|
161
|
+
// Windows: rundll32 avoids cmd.exe, which would split the URL on `&`.
|
|
162
|
+
const [cmd, args] = process.platform === "darwin"
|
|
163
|
+
? ["open", [url]]
|
|
164
|
+
: process.platform === "win32"
|
|
165
|
+
? ["rundll32", ["url.dll,FileProtocolHandler", url]]
|
|
166
|
+
: ["xdg-open", [url]];
|
|
167
|
+
const child = spawn(cmd, args, { detached: true, stdio: "ignore", windowsHide: true });
|
|
168
|
+
child.unref();
|
|
169
|
+
return true;
|
|
170
|
+
}
|
|
171
|
+
catch {
|
|
172
|
+
return false;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
export function submitReport(report, deps = {}) {
|
|
176
|
+
const runSync = deps.spawnSync ?? spawn.sync;
|
|
177
|
+
const openBrowser = deps.openBrowser ?? defaultOpenBrowser;
|
|
178
|
+
const auth = runSync("gh", ["auth", "status"], { stdio: "ignore", windowsHide: true });
|
|
179
|
+
if (auth.status === 0) {
|
|
180
|
+
const ghOpts = { input: report.markdown, encoding: "utf8", windowsHide: true };
|
|
181
|
+
const args = (labels) => ["issue", "create", "-R", REPO, "--title", report.title, ...labels.flatMap((l) => ["--label", l]), "--body-file", "-"];
|
|
182
|
+
let created = runSync("gh", args(report.labels), ghOpts);
|
|
183
|
+
// External users without triage/label rights may fail on --label; retry once without it.
|
|
184
|
+
if (created.status !== 0 && report.labels.length && /label|permission/i.test(created.stderr ?? "")) {
|
|
185
|
+
created = runSync("gh", args([]), ghOpts);
|
|
186
|
+
}
|
|
187
|
+
const url = (created.stdout ?? "").trim();
|
|
188
|
+
if (created.status === 0 && url)
|
|
189
|
+
return { method: "gh", url, submitted: true };
|
|
190
|
+
}
|
|
191
|
+
if (openBrowser(report.issueUrl))
|
|
192
|
+
return { method: "browser", url: report.issueUrl, submitted: false };
|
|
193
|
+
return { method: "url", url: report.issueUrl, submitted: false };
|
|
194
|
+
}
|
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"];
|
|
@@ -17,6 +18,7 @@ export const RULE_ENTRIES = [
|
|
|
17
18
|
".agents/GEMINI.md",
|
|
18
19
|
".agents/rules",
|
|
19
20
|
".agent/rules",
|
|
21
|
+
".kimi-code/AGENTS.md",
|
|
20
22
|
".cursor/rules",
|
|
21
23
|
".cursorrules",
|
|
22
24
|
];
|
|
@@ -72,9 +74,10 @@ export function discoverRules(cwd) {
|
|
|
72
74
|
}
|
|
73
75
|
return [...found].sort();
|
|
74
76
|
}
|
|
77
|
+
// discoverRules only walks upward, so a found path is some "../" segments plus the entry itself.
|
|
78
|
+
// Comparing the tail alone would let ".agents/AGENTS.md" pass for a CLI that only reads "AGENTS.md".
|
|
75
79
|
function basenameMatch(foundRel, entry) {
|
|
76
|
-
|
|
77
|
-
return n === entry || n.endsWith(`/${entry}`);
|
|
80
|
+
return toPosix(foundRel).replace(/^(\.\.\/)+/, "") === entry;
|
|
78
81
|
}
|
|
79
82
|
function levelHasAny(found, foundRel, names) {
|
|
80
83
|
const dir = path.posix.dirname(toPosix(foundRel));
|
|
@@ -233,14 +236,9 @@ function expandFeatures(value) {
|
|
|
233
236
|
/** Locate rulesync: project node_modules → main repo node_modules → PATH. Never uses npx. */
|
|
234
237
|
export function resolveRulesync(repoRoot, mainRepoRoot, env = process.env) {
|
|
235
238
|
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);
|
|
239
|
+
const local = which(["rulesync"], { PATH: path.join(root, "node_modules", ".bin") });
|
|
240
|
+
if (local)
|
|
239
241
|
return local;
|
|
240
|
-
}
|
|
241
|
-
catch {
|
|
242
|
-
// try next
|
|
243
|
-
}
|
|
244
242
|
}
|
|
245
243
|
return which(["rulesync"], env);
|
|
246
244
|
}
|
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 });
|