@speculoai/baton 0.8.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 CHANGED
@@ -27,7 +27,7 @@ You're working in Claude Code. Codex is installed on the same laptop, logged in,
27
27
 
28
28
  **Any agent as host, any agent as worker.** No API keys, no server, no cloud. Every agent uses its own login and subscription.
29
29
 
30
- Workers: `codex` (Codex CLI) · `claude` (Claude Code) · `cursor` (Cursor Agent CLI) · `agy` (Antigravity).
30
+ Workers: `codex` (Codex CLI) · `claude` (Claude Code) · `cursor` (Cursor Agent CLI) · `agy` (Antigravity) · `kimi` (Kimi Code CLI).
31
31
 
32
32
  ## Before / After
33
33
 
@@ -70,7 +70,7 @@ Check which workers Baton can see:
70
70
  baton agents
71
71
  ```
72
72
 
73
- Update everything later with `npx @speculoai/baton@latest update`. Flags (`--only`, `--force`, `--dry-run`), per-host manual installs, and MCP config for Claude Desktop, Windsurf, and Zed are covered in the [reference](docs/reference.md#installation).
73
+ `npm i -g @speculoai/baton` upgrades the CLI only. Use `baton update` or `npx @speculoai/baton@latest update` to update both the CLI and the recorded host plugins. Restart open agent sessions afterward to load the updated skills and MCP. An install with `--dry-run` lists update steps that may run. Flags (`--only`, `--force`, `--dry-run`), per-host manual installs, and MCP config for Claude Desktop, Windsurf, and Zed are covered in the [reference](docs/reference.md#installation).
74
74
 
75
75
  ## Use it
76
76
 
@@ -116,7 +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
+ | `baton report [id]` | Prints a redacted diagnostic report and prefilled GitHub issue link (`--body` fills in what happened, `--label` sets labels, default `bug`; `--submit` uses `gh` or opens a browser). |
120
120
  | `baton mcp` | Runs the same operations as an MCP server for hosts that can't run shell commands. |
121
121
 
122
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
@@ -27,7 +27,7 @@
27
27
 
28
28
  **任何 Agent 都能当主控,任何 Agent 都能当执行者。** 不需要 API Key,不需要服务器,不上云。每个 Agent 都用它自己的登录和订阅额度。
29
29
 
30
- 可派工的执行者:`codex`(Codex CLI)· `claude`(Claude Code)· `cursor`(Cursor Agent CLI)· `agy`(Antigravity)。
30
+ 可派工的执行者:`codex`(Codex CLI)· `claude`(Claude Code)· `cursor`(Cursor Agent CLI)· `agy`(Antigravity)· `kimi`(Kimi Code CLI)。
31
31
 
32
32
  ## 前后对比
33
33
 
@@ -70,7 +70,7 @@ npx @speculoai/baton install
70
70
  baton agents
71
71
  ```
72
72
 
73
- 以后用 `npx @speculoai/baton@latest update` 一键更新。安装参数(`--only`、`--force`、`--dry-run`)、各宿主的手动安装方式,以及 Claude Desktop、Windsurf、Zed 的 MCP 配置,见[完整手册](docs/reference.zh-CN.md#安装指南-installation)。
73
+ `npm i -g @speculoai/baton` 只升级 CLI。用 `baton update` 或 `npx @speculoai/baton@latest update` 同时更新 CLI 和已记录的宿主插件。升级后重开已打开的 agent 会话,加载新版 skills 和 MCP。安装时加 `--dry-run` 会列出可能执行的更新步骤。安装参数(`--only`、`--force`、`--dry-run`)、各宿主的手动安装方式,以及 Claude Desktop、Windsurf、Zed 的 MCP 配置,见[完整手册](docs/reference.zh-CN.md#安装指南-installation)。
74
74
 
75
75
  ## 怎么用
76
76
 
@@ -35,3 +35,19 @@ export function authHit(text, phrases) {
35
35
  const hay = String(text || "").toLowerCase();
36
36
  return phrases.some((phrase) => hay.includes(phrase));
37
37
  }
38
+ // cmd.exe cuts a .cmd/.bat argument at the first newline and has no safe escaping for these.
39
+ const CMD_UNSAFE = /[\r\n&|<>^%!"()]/;
40
+ const WIN_CMDLINE_MAX = 32767;
41
+ /** For CLIs that take the prompt in argv: refuse what Windows would truncate or reinterpret, instead of running a damaged prompt. */
42
+ export function assertArgvSafe(bin, args, platform = process.platform, hint) {
43
+ if (platform !== "win32")
44
+ return;
45
+ const base = path.win32.basename(bin);
46
+ if (/\.(cmd|bat)$/i.test(base) && args.some((arg) => CMD_UNSAFE.test(arg))) {
47
+ throw new Error(`${base} is a .cmd/.bat shim: Windows runs it through cmd.exe, which cuts a multi-line prompt at the first newline and cannot safely pass & | < > ^ % ! " ( ).${hint ? ` ${hint}` : ""}`);
48
+ }
49
+ // shortcut: counts each argument plus quotes and a space, ignoring escape growth; exact enough to fail before CreateProcess does.
50
+ const length = [bin, ...args].reduce((sum, arg) => sum + arg.length + 3, 0);
51
+ if (length > WIN_CMDLINE_MAX)
52
+ throw new Error(`The command line is ${length} characters; Windows allows at most ${WIN_CMDLINE_MAX}.`);
53
+ }
@@ -2,5 +2,6 @@ import { agy } from "./agy.js";
2
2
  import { claude } from "./claude.js";
3
3
  import { codex } from "./codex.js";
4
4
  import { cursor } from "./cursor.js";
5
- export const adapters = { codex, claude, cursor, agy };
5
+ import { kimi } from "./kimi.js";
6
+ export const adapters = { codex, claude, cursor, agy, kimi };
6
7
  export function getAdapter(id) { return Object.hasOwn(adapters, id) ? adapters[id] : null; }
@@ -0,0 +1,84 @@
1
+ import { redact } from "../redact.js";
2
+ import { assertArgvSafe, authHit, which } from "./common.js";
3
+ // Verified 2026-11-26 (kimi 2.8.0): stderr when no account or model is set up.
4
+ const AUTH = ["no model configured", "use /login"];
5
+ // Verified 2026-11-26 (kimi 2.8.0): the Bash tool result has no status field, only this trailer on failure.
6
+ const FAILED = /Command failed with exit code: \d+\.\s*$/;
7
+ function stamp(data) {
8
+ return { ts: new Date().toISOString(), turn: 0, ...data };
9
+ }
10
+ function parse(line) {
11
+ try {
12
+ return JSON.parse(line);
13
+ }
14
+ catch {
15
+ return null;
16
+ }
17
+ }
18
+ function toolDetail(raw) {
19
+ const text = typeof raw === "string" ? raw : JSON.stringify(raw ?? {});
20
+ const input = parse(text);
21
+ return redact(String(input?.command ?? input?.path ?? input?.file_path ?? text)).slice(0, 200);
22
+ }
23
+ export const kimi = {
24
+ id: "kimi",
25
+ // No readonlyEnforcement: -p always runs with auto permission and cannot take --plan (verified 2026-11-26, kimi 2.8.0).
26
+ // `--agent explore` is read-only but its sessions fail to resume ("tool \"Agent\" is not declared"), so reply would break.
27
+ // Verified 2026-11-26: AGENTS.md and .kimi-code/AGENTS.md at every level from the git root to cwd; CLAUDE.md is not read.
28
+ rules: {
29
+ files: ["AGENTS.md", ".kimi-code/AGENTS.md"],
30
+ rulesyncTarget: "kimi-code",
31
+ gates: {
32
+ mcp: "Project .kimi-code/mcp.json loads under kimi -p only in a trusted workspace (or with KIMI_CODE_TRUST_WORKSPACE=1); Baton sets neither.",
33
+ hooks: "rulesync writes kimi-code hooks only with --global; project hooks are not generated.",
34
+ },
35
+ },
36
+ resolve(env) {
37
+ return which(["kimi"], env);
38
+ },
39
+ build({ bin, prompt, sessionId, reasoningEffort, model }) {
40
+ // Verified 2026-11-26 (kimi 2.8.0): -p has no stdin form (`-p -` is taken literally), so the prompt goes in argv.
41
+ const args = ["-p", prompt, "--output-format", "stream-json"];
42
+ // Verified 2026-11-26: -m is honoured on -S resume, so pass it every turn.
43
+ const modelArg = model?.trim() || undefined;
44
+ if (modelArg)
45
+ args.push("-m", modelArg);
46
+ if (sessionId)
47
+ args.push("-S", sessionId);
48
+ assertArgvSafe(bin, args, process.platform, "Install the native kimi.exe with the official install.ps1 instead of the npm package.");
49
+ const spec = { command: bin, args, stdin: null };
50
+ if (modelArg)
51
+ spec.modelArg = modelArg;
52
+ // kimi has no thinking-effort flag (only config.toml [thinking] effort).
53
+ if (reasoningEffort)
54
+ spec.warning = `kimi has no command-line thinking effort; --effort ${reasoningEffort} was ignored.`;
55
+ return spec;
56
+ },
57
+ sessionIdFrom(line) {
58
+ const obj = parse(line);
59
+ return obj?.role === "meta" && obj.type === "session.resume_hint" && typeof obj.session_id === "string" ? obj.session_id : null;
60
+ },
61
+ parseLine(line) {
62
+ const obj = parse(line);
63
+ if (!obj || typeof obj !== "object" || typeof obj.role !== "string")
64
+ return null;
65
+ // system.version and session.resume_hint (handled by sessionIdFrom) stay out of the event stream.
66
+ if (obj.role === "meta")
67
+ return [];
68
+ if (obj.role === "assistant") {
69
+ const calls = Array.isArray(obj.tool_calls) ? obj.tool_calls : [];
70
+ const events = calls.map((call) => stamp({ type: "tool_call", name: String(call?.function?.name ?? "tool"), detail: toolDetail(call?.function?.arguments) }));
71
+ if (typeof obj.content === "string" && obj.content)
72
+ events.push(stamp({ type: "message", text: obj.content }));
73
+ return events;
74
+ }
75
+ if (obj.role === "tool") {
76
+ const content = typeof obj.content === "string" ? obj.content : JSON.stringify(obj.content ?? "");
77
+ return [stamp({ type: "tool_result", name: "tool", ok: !FAILED.test(content), detail: redact(content).slice(0, 200) })];
78
+ }
79
+ return null;
80
+ },
81
+ isAuthFailure(text) {
82
+ return authHit(text, AUTH);
83
+ },
84
+ };
package/dist/cli.js CHANGED
@@ -6,7 +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
+ import { COMMANDS, commandList, hasSubcommand, isCommand, renderHelp, wantsHelp } from "./usage.js";
10
10
  function installChoice(value, flag) {
11
11
  if (value === undefined)
12
12
  return undefined;
@@ -19,17 +19,24 @@ async function main() {
19
19
  let result;
20
20
  if (command === undefined || command === "help" || command === "-h" || command === "--help") {
21
21
  const name = command === "help" ? args[0] : undefined;
22
+ const sub = command === "help" ? args[1] : undefined;
22
23
  if (name === undefined)
23
24
  process.stdout.write(renderHelp());
24
- else if (isCommand(name))
25
- process.stdout.write(renderHelp(name));
25
+ else if (isCommand(name)) {
26
+ if (sub === undefined)
27
+ process.stdout.write(renderHelp(name));
28
+ else if (hasSubcommand(name, sub))
29
+ process.stdout.write(renderHelp(name, sub));
30
+ else
31
+ throw new Error(`Usage: ${COMMANDS[name].usage}`);
32
+ }
26
33
  else
27
34
  throw new Error(commandList);
28
35
  return;
29
36
  }
30
37
  // Before parsing, so `start --help` neither trips strict parsing nor waits on stdin.
31
38
  if (isCommand(command) && wantsHelp(args)) {
32
- process.stdout.write(renderHelp(command));
39
+ process.stdout.write(renderHelp(command, hasSubcommand(command, args[0]) ? args[0] : undefined));
33
40
  return;
34
41
  }
35
42
  if (command === "_supervise") {
@@ -47,7 +54,7 @@ async function main() {
47
54
  if (positionals.length > 1)
48
55
  throw new Error("report takes at most one task_id.");
49
56
  const { buildReport, submitReport } = await import("./report.js");
50
- const report = buildReport(positionals[0], { title: values.title });
57
+ const report = buildReport(positionals[0], { title: values.title, body: values.body, labels: values.label });
51
58
  if (values.submit) {
52
59
  result = submitReport(report);
53
60
  process.stdout.write(`${JSON.stringify(result)}\n`);
@@ -151,21 +158,27 @@ async function main() {
151
158
  const { values, positionals } = parseArgs({
152
159
  args: rest,
153
160
  allowPositionals: true,
154
- options: COMMANDS.worktree.options,
161
+ options: COMMANDS.worktree.subcommands.add.options,
155
162
  });
156
163
  if (positionals.length)
157
164
  throw new Error("worktree add takes no positional arguments.");
158
165
  result = addWorktree(process.cwd(), { name: values.name, branch: values.branch, base: values.base });
159
166
  }
160
167
  else if (action === "ls") {
161
- if (rest.length)
162
- throw new Error("worktree ls takes no extra arguments.");
168
+ const { positionals } = parseArgs({ args: rest, allowPositionals: true, options: {} });
169
+ if (positionals.length)
170
+ throw new Error("worktree ls takes no positional arguments.");
163
171
  result = { worktrees: listWorktrees(process.cwd()) };
164
172
  }
165
173
  else if (action === "rm") {
166
- if (rest.length !== 1)
174
+ const { values, positionals } = parseArgs({
175
+ args: rest,
176
+ allowPositionals: true,
177
+ options: COMMANDS.worktree.subcommands.rm.options,
178
+ });
179
+ if (positionals.length !== 1)
167
180
  throw new Error("worktree rm requires one name or path.");
168
- result = removeWorktree(process.cwd(), rest[0]);
181
+ result = removeWorktree(process.cwd(), positionals[0], { force: values.force });
169
182
  }
170
183
  else {
171
184
  throw new Error("Usage: baton worktree add|ls|rm");
@@ -310,6 +323,10 @@ async function main() {
310
323
  else if (ran.result.missing?.length) {
311
324
  ui.logInfo(`missing: ${ran.result.missing.join(", ")}`);
312
325
  }
326
+ for (const warning of ran.result.warnings ?? [])
327
+ ui.logWarning(warning);
328
+ if (ran.result.note)
329
+ ui.logInfo(ran.result.note);
313
330
  ui.endAction(ui.summarizeResult(ran.result));
314
331
  }
315
332
  result = rulesync ? { ...ran.result, rulesync } : ran.result;
@@ -54,6 +54,9 @@ export function logError(message) {
54
54
  export function logInfo(message) {
55
55
  p.log.info(message, opts);
56
56
  }
57
+ export function logWarning(message) {
58
+ p.log.warn(message, opts);
59
+ }
57
60
  export function createSpinner() {
58
61
  return p.spinner(opts);
59
62
  }
package/dist/install.js CHANGED
@@ -1,7 +1,9 @@
1
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
- export function commandsFor(id, action, opts = {}) {
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 = HOSTS.find((item) => item.id === id);
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: commandsFor(id, input.action, { force: input.force }).map((step) => step.args),
124
+ commands: steps.map((step) => step.args),
114
125
  ...(host.note && input.action === "install" ? { note: host.note } : {}),
115
126
  });
116
127
  }
@@ -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
- function defaultSpawn(command, args, env, quiet = false) {
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
- const child = spawn(command, args, { env, stdio: ["inherit", "pipe", "pipe"] });
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 planned = planInstall({ action: input.action, only, force: input.force, skipGlobal: input.skipGlobal, env, recorded: readInstalled(home) });
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: { action: input.action, dry_run: true, ...(planned.global ? { global: planned.global } : {}), hosts: planned.hosts, ...(planned.missing.length ? { missing: planned.missing } : {}) },
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 skipped = false;
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 run(host.bin, step.args, Boolean(input.quiet) || Boolean(step.soft));
196
- if (ran.status === 0 || step.soft)
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
- skipped = true;
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
- const note = skipped ? "already installed, skipped" : host.note;
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 recorded = new Set(readInstalled(home));
212
- for (const host of hosts) {
213
- if (!host.ok)
214
- continue;
215
- if (input.action === "install")
216
- recorded.add(host.id);
217
- else
218
- recorded.delete(host.id);
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([...recorded], home);
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: { action: input.action, ...(global ? { global } : {}), hosts, ...(planned.missing.length ? { missing: planned.missing } : {}) },
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: "0.3.0" });
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 claude; stored in meta and carried over by reply)."),
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/report.js CHANGED
@@ -94,11 +94,10 @@ function readEventSkeleton(id, cwd) {
94
94
  }
95
95
  return lines.slice(-MAX_EVENTS);
96
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()}`;
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);
102
101
  }
103
102
  export function buildReport(taskId, opts = {}) {
104
103
  const meta = taskId ? readMeta(taskId) : null;
@@ -141,19 +140,21 @@ export function buildReport(taskId, opts = {}) {
141
140
  "> Review before posting: remove any project-specific terms if present.",
142
141
  "",
143
142
  "### What happened",
144
- "<!-- Describe what you expected vs. what happened -->",
143
+ opts.body?.trim() ? sanitize(opts.body.trim(), meta?.cwd) : "<!-- Describe what you expected vs. what happened -->",
145
144
  "",
146
145
  ];
147
146
  const markdown = [...header, ...envSection, ...taskSection].join("\n");
148
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"];
149
150
  const shortBody = [
150
151
  ...header,
151
152
  ...envSection,
152
153
  "",
153
154
  "<!-- Full task timeline omitted for URL length; paste the output of `baton report` here -->",
154
155
  ].join("\n");
155
- const issueUrl = makeIssueUrl(title, markdown, shortBody);
156
- return { title, markdown, issueUrl };
156
+ const issueUrl = makeIssueUrl(title, labels, markdown, shortBody);
157
+ return { title, labels, markdown, issueUrl };
157
158
  }
158
159
  function defaultOpenBrowser(url) {
159
160
  try {
@@ -176,11 +177,13 @@ export function submitReport(report, deps = {}) {
176
177
  const openBrowser = deps.openBrowser ?? defaultOpenBrowser;
177
178
  const auth = runSync("gh", ["auth", "status"], { stdio: "ignore", windowsHide: true });
178
179
  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
- });
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
+ }
184
187
  const url = (created.stdout ?? "").trim();
185
188
  if (created.status === 0 && url)
186
189
  return { method: "gh", url, submitted: true };
package/dist/rules.js CHANGED
@@ -18,6 +18,7 @@ export const RULE_ENTRIES = [
18
18
  ".agents/GEMINI.md",
19
19
  ".agents/rules",
20
20
  ".agent/rules",
21
+ ".kimi-code/AGENTS.md",
21
22
  ".cursor/rules",
22
23
  ".cursorrules",
23
24
  ];
@@ -73,9 +74,10 @@ export function discoverRules(cwd) {
73
74
  }
74
75
  return [...found].sort();
75
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".
76
79
  function basenameMatch(foundRel, entry) {
77
- const n = toPosix(foundRel);
78
- return n === entry || n.endsWith(`/${entry}`);
80
+ return toPosix(foundRel).replace(/^(\.\.\/)+/, "") === entry;
79
81
  }
80
82
  function levelHasAny(found, foundRel, names) {
81
83
  const dir = path.posix.dirname(toPosix(foundRel));
package/dist/tasks.js CHANGED
@@ -81,9 +81,9 @@ export async function start(input) {
81
81
  if (input.reasoningEffort && !["low", "medium", "high", "ultra"].includes(input.reasoningEffort))
82
82
  throw new Error("Unknown effort.");
83
83
  const model = input.model?.trim() || undefined;
84
- if (model && adapter.id !== "cursor" && adapter.id !== "codex" && adapter.id !== "claude")
85
- throw new Error(`${adapter.id} does not support --model yet (cursor, codex and claude only).`);
86
- let model_argv = adapter.id === "codex" || adapter.id === "claude" ? model : undefined;
84
+ if (model && adapter.id !== "cursor" && adapter.id !== "codex" && adapter.id !== "claude" && adapter.id !== "kimi")
85
+ throw new Error(`${adapter.id} does not support --model yet (cursor, codex, claude and kimi only).`);
86
+ let model_argv = adapter.id === "codex" || adapter.id === "claude" || adapter.id === "kimi" ? model : undefined;
87
87
  if (adapter.id === "cursor") {
88
88
  const resolved = resolveCursorModelArg(model, input.reasoningEffort ?? null);
89
89
  if (resolved)
package/dist/usage.js CHANGED
@@ -14,12 +14,12 @@ export const COMMANDS = {
14
14
  usage: "baton start --target <agent> [--prompt <text> | stdin] [options]",
15
15
  summary: "Start a job in the background and return its task_id.",
16
16
  options: {
17
- target: { type: "string", arg: "agent", desc: "Agent CLI to run: codex, claude, cursor or agy (required)" },
17
+ target: { type: "string", arg: "agent", desc: "Agent CLI to run: codex, claude, cursor, agy or kimi (required)" },
18
18
  prompt: { type: "string", arg: "text", desc: "Task prompt; read from stdin when omitted" },
19
19
  cwd: { type: "string", arg: "dir", desc: "Working directory for the job (default: current directory)" },
20
20
  file: { type: "string", multiple: true, arg: "path", desc: "File the agent should focus on (repeatable)" },
21
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" },
22
+ model: { type: "string", arg: "id", desc: "Model id for cursor, codex, claude or kimi; kept across reply" },
23
23
  "idle-timeout": { type: "string", arg: "s", desc: "Stop after this many seconds with no output (default 600)" },
24
24
  "max-duration": { type: "string", arg: "s", desc: "Maximum seconds per turn (default unlimited)" },
25
25
  scope: { type: "string", multiple: true, arg: "glob", desc: "Paths allowed to change, checked after each turn (repeatable)" },
@@ -88,14 +88,34 @@ export const COMMANDS = {
88
88
  options: { older: { type: "string", arg: "days", desc: "Age threshold in days (required)" } },
89
89
  },
90
90
  worktree: {
91
- usage: "baton worktree add [options] | ls | rm <name-or-path>",
91
+ usage: "baton worktree add | ls | rm",
92
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)" },
93
+ subcommands: {
94
+ add: {
95
+ usage: "baton worktree add [--name <id>] [--branch <name>] [--base <ref>]",
96
+ summary: "Create a baton-managed worktree and local branch.",
97
+ options: {
98
+ name: { type: "string", arg: "id", desc: "Worktree name (default random hex)" },
99
+ branch: { type: "string", arg: "name", desc: "Branch to create (default baton/<name>)" },
100
+ base: { type: "string", arg: "ref", desc: "Ref to start from (default .baton.json base, main, master, or HEAD)" },
101
+ },
102
+ },
103
+ ls: {
104
+ usage: "baton worktree ls",
105
+ summary: "List baton-managed worktrees.",
106
+ },
107
+ rm: {
108
+ usage: "baton worktree rm <name-or-path> [-f | --force]",
109
+ summary: "Remove a baton-managed worktree and delete its local branch.",
110
+ options: {
111
+ force: { type: "boolean", short: "f", desc: "Remove even when dirty or unmerged (git branch -D)" },
112
+ },
113
+ notes: [
114
+ "Accepts a worktree name under .worktrees/ or its path; only baton-managed trees can be removed.",
115
+ "Without --force, refuses dirty trees or branches with commits unmerged into base; when clean, removes the tree and deletes the associated local branch (e.g. baton/*).",
116
+ ],
117
+ },
97
118
  },
98
- notes: ["rm refuses dirty or unmerged trees; when clean it removes the tree and deletes the local branch."],
99
119
  },
100
120
  rules: {
101
121
  usage: "baton rules init [options]",
@@ -126,10 +146,12 @@ export const COMMANDS = {
126
146
  },
127
147
  mcp: { usage: "baton mcp", summary: "Start the MCP server on stdio." },
128
148
  report: {
129
- usage: "baton report [task_id] [--title <text>] [--submit]",
149
+ usage: "baton report [task_id] [--title <text>] [--body <text>] [--label <name>]... [--submit]",
130
150
  summary: "Generate a redacted diagnostic report and GitHub issue link (optionally submit).",
131
151
  options: {
132
152
  title: { type: "string", arg: "text", desc: "Issue title override" },
153
+ body: { type: "string", arg: "text", desc: "What happened: expected vs. actual, repro (redacted like the rest)" },
154
+ label: { type: "string", multiple: true, arg: "name", desc: "Existing repo label to apply (repeatable; default: bug)" },
133
155
  submit: { type: "boolean", desc: "Create the issue via gh if logged in, otherwise open the prefilled form in a browser" },
134
156
  },
135
157
  notes: ["Never includes prompts, raw logs, file names, or credentials; still review before posting."],
@@ -138,6 +160,10 @@ export const COMMANDS = {
138
160
  export function isCommand(name) {
139
161
  return name !== undefined && Object.hasOwn(COMMANDS, name);
140
162
  }
163
+ export function hasSubcommand(name, sub) {
164
+ const subs = COMMANDS[name].subcommands;
165
+ return sub !== undefined && subs !== undefined && Object.hasOwn(subs, sub);
166
+ }
141
167
  /** `-h` / `--help` anywhere before `--`. */
142
168
  export function wantsHelp(args) {
143
169
  const end = args.indexOf("--");
@@ -148,7 +174,7 @@ function columns(rows) {
148
174
  const width = Math.max(...rows.map(([left]) => left.length)) + 2;
149
175
  return rows.map(([left, right]) => ` ${left.padEnd(width)}${right}`);
150
176
  }
151
- export function renderHelp(name) {
177
+ export function renderHelp(name, sub) {
152
178
  if (!name) {
153
179
  return [
154
180
  "Usage: baton <command> [options]",
@@ -162,21 +188,25 @@ export function renderHelp(name) {
162
188
  "",
163
189
  ].join("\n");
164
190
  }
165
- const cmd = COMMANDS[name];
191
+ const top = COMMANDS[name];
192
+ const cmd = sub && top.subcommands && Object.hasOwn(top.subcommands, sub) ? top.subcommands[sub] : top;
166
193
  const options = Object.entries(cmd.options ?? {}).map(([key, opt]) => [
167
194
  `${opt.short ? `-${opt.short}, ` : ""}--${key}${opt.type === "string" ? ` <${opt.arg ?? "value"}>` : ""}`,
168
195
  opt.desc,
169
196
  ]);
170
197
  options.push(["-h, --help", "Show this help"]);
198
+ const subs = cmd.subcommands ? Object.entries(cmd.subcommands) : [];
171
199
  return [
172
200
  `Usage: ${cmd.usage}`,
173
201
  "",
174
202
  cmd.summary,
203
+ ...(subs.length ? ["", "Subcommands:", ...columns(subs.map(([k, v]) => [k, v.summary]))] : []),
175
204
  "",
176
205
  "Options:",
177
206
  ...columns(options),
178
207
  ...(cmd.notes?.length ? ["", ...cmd.notes] : []),
179
208
  ...(cmd.examples?.length ? ["", "Examples:", ...cmd.examples.map((line) => ` ${line}`)] : []),
209
+ ...(subs.length ? ["", `Run \`baton ${name} <subcommand> --help\` for a subcommand's options.`] : []),
180
210
  "",
181
211
  ].join("\n");
182
212
  }
package/dist/worktree.js CHANGED
@@ -162,11 +162,13 @@ export function ensureIgnored(repo, worktreeRoot) {
162
162
  if (rel.startsWith("..") || path.isAbsolute(rel)) {
163
163
  throw new Error("worktree root must be inside the repository.");
164
164
  }
165
- const check = git(repo, ["check-ignore", "-q", rel]);
165
+ const normalized = rel.replace(/\\/g, "/");
166
+ // Trailing slash tells git check-ignore this is a directory even before mkdirSync creates it.
167
+ const entry = normalized.endsWith("/") ? normalized : `${normalized}/`;
168
+ const check = git(repo, ["check-ignore", "-q", entry]);
166
169
  if (check.status === 0)
167
170
  return false;
168
171
  const ignorePath = path.join(repo, ".gitignore");
169
- const entry = rel.endsWith("/") ? rel : `${rel}/`;
170
172
  const existing = fs.existsSync(ignorePath) ? fs.readFileSync(ignorePath, "utf8") : "";
171
173
  const prefix = existing && !existing.endsWith("\n") ? "\n" : "";
172
174
  fs.writeFileSync(ignorePath, `${existing}${prefix}${entry}\n`);
@@ -434,9 +436,20 @@ function resolveManagedPath(cwd, nameOrPath) {
434
436
  return { repo, root, worktreePath, meta };
435
437
  }
436
438
  function isDirty(worktreePath) {
437
- // Ignore untracked (copy/.baton-worktree.json); only block on tracked edits.
438
- const status = git(worktreePath, ["status", "--porcelain", "--untracked-files=no"]);
439
- return status.status === 0 && status.stdout.trim().length > 0;
439
+ const status = git(worktreePath, ["status", "--porcelain=v1", "-z", "--untracked-files=normal"]);
440
+ if (status.status !== 0)
441
+ return true;
442
+ const exempt = [...batonWorktreeExemptPaths(worktreePath)];
443
+ for (const entry of status.stdout.split("\0")) {
444
+ if (entry.length < 4)
445
+ continue;
446
+ if (entry.slice(0, 2) !== "??")
447
+ return true;
448
+ const top = entry.slice(3).replace(/\/$/, "").split("/")[0];
449
+ if (!exempt.some((pattern) => matchBasename(top, pattern)))
450
+ return true;
451
+ }
452
+ return false;
440
453
  }
441
454
  function hasUnmergedCommits(repo, branch, base) {
442
455
  const ran = git(repo, ["rev-list", "--count", `${base}..${branch}`]);
@@ -444,23 +457,28 @@ function hasUnmergedCommits(repo, branch, base) {
444
457
  return true;
445
458
  return Number(ran.stdout.trim()) > 0;
446
459
  }
447
- export function removeWorktree(cwd, nameOrPath) {
460
+ export function removeWorktree(cwd, nameOrPath, options = {}) {
448
461
  const { repo, worktreePath, meta } = resolveManagedPath(cwd, nameOrPath);
449
- if (isDirty(worktreePath)) {
450
- throw new Error(`worktree has uncommitted changes; refusing to remove: ${worktreePath}`);
451
- }
452
- if (hasUnmergedCommits(repo, meta.branch, meta.base)) {
453
- throw new Error(`Branch ${meta.branch} has commits not merged into ${meta.base}; refusing to remove.`);
462
+ if (!options.force) {
463
+ if (isDirty(worktreePath)) {
464
+ throw new Error(`worktree has uncommitted changes; refusing to remove: ${worktreePath} (pass --force to remove anyway).`);
465
+ }
466
+ if (hasUnmergedCommits(repo, meta.branch, meta.base)) {
467
+ throw new Error(`Branch ${meta.branch} has commits not merged into ${meta.base}; refusing to remove (pass --force to remove anyway).`);
468
+ }
454
469
  }
455
- // ponytail: --force after our tracked-dirty + unmerged checks; untracked copy/meta are expected
470
+ // ponytail: --force after our dirty + unmerged checks (or user --force); untracked copy/meta are expected
456
471
  const removed = git(repo, ["worktree", "remove", "--force", worktreePath]);
457
472
  if (removed.status !== 0) {
458
473
  throw new Error(`git worktree remove failed: ${(removed.stderr || removed.stdout).trim()}`);
459
474
  }
460
- const deleted = git(repo, ["branch", "-d", meta.branch]);
461
- if (deleted.status !== 0) {
462
- throw new Error(`Failed to delete branch: ${(deleted.stderr || deleted.stdout).trim()}`);
463
- }
464
475
  git(repo, ["worktree", "prune"]);
476
+ const branchExists = git(repo, ["rev-parse", "--verify", "--quiet", `refs/heads/${meta.branch}`]).status === 0;
477
+ if (branchExists || !options.force) {
478
+ const deleted = git(repo, ["branch", options.force ? "-D" : "-d", meta.branch]);
479
+ if (deleted.status !== 0) {
480
+ throw new Error(`Failed to delete branch: ${(deleted.stderr || deleted.stdout).trim()}`);
481
+ }
482
+ }
465
483
  return { status: "ok", path: worktreePath, branch: meta.branch, name: meta.name };
466
484
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@speculoai/baton",
3
- "version": "0.8.0",
3
+ "version": "0.8.1",
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",