@speculoai/baton 0.4.0 → 0.5.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.
@@ -6,6 +6,15 @@ const AUTH = ["not logged in", "please log in", "authentication required", "code
6
6
  export const codex = {
7
7
  id: "codex",
8
8
  readonlyEnforcement: "os-sandbox",
9
+ // Verified 2026-11-21/22: AGENTS.md (+ override). Project .codex/config.toml MCP/hooks need trust.
10
+ rules: {
11
+ files: ["AGENTS.md", "AGENTS.override.md"],
12
+ rulesyncTarget: "codexcli",
13
+ gates: {
14
+ mcp: "Project .codex/config.toml (where rulesync writes Codex MCP) loads only for trusted project paths; a baton worktree is a separate absolute path and does not inherit the main repo's trust_level.",
15
+ hooks: "Project hooks require persisted hook trust; codex exec has --dangerously-bypass-hook-trust (Baton does not pass it).",
16
+ },
17
+ },
9
18
  resolve(env) {
10
19
  return which(["codex"], env);
11
20
  },
@@ -13,7 +22,7 @@ export const codex = {
13
22
  const lastMessagePath = path.join(os.tmpdir(), `baton-codex-${process.pid}-${Date.now()}.txt`);
14
23
  const effortArgs = reasoningEffort ? ["-c", `model_reasoning_effort="${reasoningEffort}"`] : [];
15
24
  const readonly = mode === "readonly";
16
- // `exec resume` 不接受 --cd/--color/--sandbox。write 首轮用 --approve-for-me(workspace-write,勿再加 --sandbox)。
25
+ // `exec resume` does not accept --cd/--color/--sandbox. The first write turn uses --approve-for-me (workspace-write; do not add --sandbox).
17
26
  if (sessionId) {
18
27
  return {
19
28
  command: bin,
@@ -74,7 +83,7 @@ export const codex = {
74
83
  const event = (data) => [{ ts: new Date().toISOString(), turn: 0, ...data }];
75
84
  if (obj.type === "turn.failed" && typeof obj.error?.message === "string")
76
85
  return event({ type: "error", text: obj.error.message });
77
- // 生命周期事件:session id 由 sessionIdFrom 取,轮次起止由 supervisor 记录,这里不重复出事件。
86
+ // Lifecycle events: the session id comes from sessionIdFrom and turn start/end are recorded by the supervisor, so no events are emitted here.
78
87
  if (["thread.started", "turn.started", "turn.completed"].includes(obj.type))
79
88
  return [];
80
89
  const item = obj.item;
@@ -19,9 +19,9 @@ export function resolveCursorModelArg(model, effort) {
19
19
  const e = effort || null;
20
20
  if (id && e) {
21
21
  if (id.includes("["))
22
- throw new Error("模型已含参数括号,不要再传 --effort。");
22
+ throw new Error("Model already has a parameter bracket; do not pass --effort.");
23
23
  if (EMBEDDED_EFFORT.test(id))
24
- throw new Error(`模型 ${id} 已含档位,不要再传 --effort。`);
24
+ throw new Error(`Model ${id} already includes an effort level; do not pass --effort.`);
25
25
  return `${id}[effort=${e}]`;
26
26
  }
27
27
  if (id)
@@ -33,8 +33,16 @@ export function resolveCursorModelArg(model, effort) {
33
33
  export const cursor = {
34
34
  id: "cursor",
35
35
  readonlyEnforcement: "agent-enforced",
36
+ // Verified 2026-11-21: AGENTS.md, CLAUDE.md, .cursor/rules/*.mdc, .cursorrules. --approve-mcps defaults false.
37
+ rules: {
38
+ files: ["AGENTS.md", "CLAUDE.md", ".cursor/rules", ".cursorrules"],
39
+ rulesyncTarget: "cursor",
40
+ gates: {
41
+ mcp: "Project MCP servers need --approve-mcps; Baton only passes --trust, so project MCP may not load.",
42
+ },
43
+ },
36
44
  resolve(env) {
37
- // cursor-agent 名字不会撞上 IDE 的 `cursor`,也比 PATH 里别的 `agent` 先命中。
45
+ // The cursor-agent name does not collide with the IDE's `cursor` and is matched before any other `agent` on PATH.
38
46
  return which(["cursor-agent", "agent"], env);
39
47
  },
40
48
  build({ bin, cwd, prompt, sessionId, reasoningEffort, model, mode }) {
@@ -60,7 +68,7 @@ export const cursor = {
60
68
  const obj = parse(line);
61
69
  if (!obj || typeof obj !== "object" || typeof obj.type !== "string")
62
70
  return null;
63
- // init 由 sessionIdFrom 处理;user 是 prompt 回显;thinking 是逐字增量,只会刷屏。
71
+ // init is handled by sessionIdFrom; user is the prompt echo; thinking is a per-character increment that would only flood the output.
64
72
  if (["system", "user", "thinking"].includes(obj.type))
65
73
  return [];
66
74
  if (obj.type === "assistant") {
@@ -85,8 +93,8 @@ export const cursor = {
85
93
  return null;
86
94
  }
87
95
  if (obj.type === "result") {
88
- // 最终文本已经以 assistant 消息出过一次,这里只报错误。
89
- return obj.is_error ? event({ type: "error", text: redact(String(obj.result ?? "cursor 返回错误")) }) : [];
96
+ // The final text was already emitted once as an assistant message; only report errors here.
97
+ return obj.is_error ? event({ type: "error", text: redact(String(obj.result ?? "cursor returned an error")) }) : [];
90
98
  }
91
99
  return null;
92
100
  },
package/dist/cli.js CHANGED
@@ -10,7 +10,7 @@ async function main() {
10
10
  let result;
11
11
  if (command === "_supervise") {
12
12
  if (args.length !== 1)
13
- throw new Error("缺少 task_id。");
13
+ throw new Error("task_id is missing.");
14
14
  await (await import("./supervisor.js")).supervise(args[0]);
15
15
  return;
16
16
  }
@@ -31,26 +31,31 @@ async function main() {
31
31
  "idle-timeout": { type: "string" }, "max-duration": { type: "string" },
32
32
  scope: { type: "string", multiple: true }, "scope-on-violation": { type: "string" },
33
33
  mode: { type: "string" }, "allow-weak": { type: "boolean" },
34
+ isolate: { type: "boolean" }, "allow-dirty": { type: "boolean" },
35
+ rules: { type: "string" },
34
36
  } });
35
37
  if (positionals.length)
36
- throw new Error("start 不接受位置参数。");
38
+ throw new Error("start takes no positional arguments.");
37
39
  result = await start({ target: values.target || "", prompt: values.prompt ?? fs.readFileSync(0, "utf8"), cwd: values.cwd, files: values.file,
38
40
  reasoningEffort: values.effort, model: values.model,
39
41
  idleTimeout: values["idle-timeout"] === undefined ? undefined : Number(values["idle-timeout"]), maxDuration: values["max-duration"] === undefined ? undefined : Number(values["max-duration"]),
40
42
  scope: values.scope, scopeOnViolation: values["scope-on-violation"],
41
- mode: values.mode, allowWeak: values["allow-weak"], });
43
+ mode: values.mode, allowWeak: values["allow-weak"],
44
+ isolate: values.isolate, allowDirty: values["allow-dirty"],
45
+ rules: values.rules,
46
+ });
42
47
  if (result.status !== "running")
43
48
  process.exitCode = 1;
44
49
  }
45
50
  else if (command === "status") {
46
51
  if (args.length !== 1)
47
- throw new Error("status 需要一个 task_id。");
52
+ throw new Error("status requires one task_id.");
48
53
  result = status(args[0]);
49
54
  }
50
55
  else if (command === "reply") {
51
56
  const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { prompt: { type: "string" }, as: { type: "string" } } });
52
57
  if (positionals.length !== 1)
53
- throw new Error("reply 需要一个 task_id。");
58
+ throw new Error("reply requires one task_id.");
54
59
  result = await reply(positionals[0], values.prompt ?? fs.readFileSync(0, "utf8"), (values.as ?? "host"));
55
60
  if (result.status !== "running")
56
61
  process.exitCode = 1;
@@ -61,31 +66,31 @@ async function main() {
61
66
  options: { for: { type: "string" }, "until-done": { type: "boolean" } },
62
67
  });
63
68
  if (values["until-done"] && values.for !== undefined)
64
- throw new Error("--until-done 与 --for 不能同时使用。");
69
+ throw new Error("--until-done and --for cannot be used together.");
65
70
  result = await wait(positionals, values["until-done"] ? Infinity : values.for === undefined ? 50 : Number(values.for));
66
71
  }
67
72
  else if (command === "tail") {
68
73
  const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { follow: { type: "boolean", short: "f" }, raw: { type: "boolean" } } });
69
74
  if (positionals.length !== 1)
70
- throw new Error("tail 需要一个 task_id。");
75
+ throw new Error("tail requires one task_id.");
71
76
  await (await import("./tail.js")).tail(positionals[0], { follow: values.follow, raw: values.raw });
72
77
  return;
73
78
  }
74
79
  else if (command === "ls") {
75
80
  const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { all: { type: "boolean" } } });
76
81
  if (positionals.length)
77
- throw new Error("ls 不接受位置参数。");
82
+ throw new Error("ls takes no positional arguments.");
78
83
  result = { tasks: ls(values.all) };
79
84
  }
80
85
  else if (command === "prune") {
81
86
  const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { older: { type: "string" } } });
82
87
  if (positionals.length || values.older === undefined)
83
- throw new Error("prune 需要 --older 天数。");
88
+ throw new Error("prune requires --older days.");
84
89
  result = { deleted: prune(Number(values.older)) };
85
90
  }
86
91
  else if (command === "cancel") {
87
92
  if (args.length !== 1)
88
- throw new Error("cancel 需要一个 task_id。");
93
+ throw new Error("cancel requires one task_id.");
89
94
  result = await cancel(args[0]);
90
95
  }
91
96
  else if (command === "worktree") {
@@ -97,21 +102,21 @@ async function main() {
97
102
  options: { name: { type: "string" }, branch: { type: "string" }, base: { type: "string" } },
98
103
  });
99
104
  if (positionals.length)
100
- throw new Error("worktree add 不接受位置参数。");
105
+ throw new Error("worktree add takes no positional arguments.");
101
106
  result = addWorktree(process.cwd(), { name: values.name, branch: values.branch, base: values.base });
102
107
  }
103
108
  else if (action === "ls") {
104
109
  if (rest.length)
105
- throw new Error("worktree ls 不接受额外参数。");
110
+ throw new Error("worktree ls takes no extra arguments.");
106
111
  result = { worktrees: listWorktrees(process.cwd()) };
107
112
  }
108
113
  else if (action === "rm") {
109
114
  if (rest.length !== 1)
110
- throw new Error("worktree rm 需要一个 name 或 path。");
115
+ throw new Error("worktree rm requires one name or path.");
111
116
  result = removeWorktree(process.cwd(), rest[0]);
112
117
  }
113
118
  else {
114
- throw new Error("用法:baton worktree add|ls|rm");
119
+ throw new Error("Usage: baton worktree add|ls|rm");
115
120
  }
116
121
  }
117
122
  else if (command === "install" || command === "update" || command === "uninstall") {
@@ -123,34 +128,91 @@ async function main() {
123
128
  },
124
129
  });
125
130
  if (positionals.length)
126
- throw new Error(`${command} 不接受位置参数。`);
131
+ throw new Error(`${command} takes no positional arguments.`);
127
132
  if (command !== "install" && values.force)
128
- throw new Error(`${command} 不接受 --force。`);
133
+ throw new Error(`${command} does not accept --force.`);
129
134
  if (command === "uninstall" && values["skip-global"])
130
- throw new Error("uninstall 不接受 --skip-global。");
131
- const interactive = command === "install" && !values.only?.length && Boolean(process.stdin.isTTY);
132
- const readline = interactive ? await import("node:readline/promises") : null;
133
- const rl = readline?.createInterface({ input: process.stdin, output: process.stderr });
134
- try {
135
- const ran = await runInstall({
136
- action: command,
137
- only: values.only,
138
- force: values.force,
139
- skipGlobal: values["skip-global"],
140
- dryRun: Boolean(values["dry-run"]),
141
- tty: interactive,
142
- readLine: rl ? () => rl.question("") : undefined,
143
- });
144
- result = ran.result;
145
- if (ran.exitCode)
146
- process.exitCode = ran.exitCode;
147
- }
148
- finally {
149
- rl?.close();
135
+ throw new Error("uninstall does not accept --skip-global.");
136
+ const action = command;
137
+ const pretty = Boolean(process.stdin.isTTY);
138
+ const interactive = action === "install" && !values.only?.length && pretty;
139
+ const dryRun = Boolean(values["dry-run"]);
140
+ const ui = pretty ? await import("./install-ui.js") : null;
141
+ if (ui)
142
+ ui.beginAction(action);
143
+ let cancelled = false;
144
+ const spin = ui && !dryRun ? ui.createSpinner() : null;
145
+ let spinning = false;
146
+ const ran = await runInstall({
147
+ action,
148
+ only: values.only,
149
+ force: values.force,
150
+ skipGlobal: values["skip-global"],
151
+ dryRun,
152
+ selectHosts: interactive && ui
153
+ ? async (detected) => {
154
+ const picked = await ui.multiselectHosts(detected);
155
+ if (!picked) {
156
+ cancelled = true;
157
+ ui.cancelAction("Install cancelled.");
158
+ return null;
159
+ }
160
+ return picked;
161
+ }
162
+ : undefined,
163
+ onProgress: spin && ui
164
+ ? (event) => {
165
+ if (event.phase === "start") {
166
+ const msg = event.type === "global" ? "Installing global baton…" : `${action} ${event.id}…`;
167
+ if (!spinning) {
168
+ spin.start(msg);
169
+ spinning = true;
170
+ }
171
+ else
172
+ spin.message(msg);
173
+ return;
174
+ }
175
+ if (event.type === "global") {
176
+ if (event.ok)
177
+ ui.logSuccess("global baton");
178
+ else
179
+ ui.logError(`global: ${event.error ?? "failed"}`);
180
+ return;
181
+ }
182
+ if (event.ok)
183
+ ui.logSuccess(`${event.id}${event.note ? ` — ${event.note}` : ""}`);
184
+ else
185
+ ui.logError(`${event.id}: ${event.error ?? "failed"}`);
186
+ }
187
+ : undefined,
188
+ });
189
+ if (spinning)
190
+ spin.stop(ran.exitCode ? "Finished with errors" : "Done");
191
+ if (ui && !cancelled) {
192
+ if (dryRun) {
193
+ const lines = [];
194
+ if (ran.result.global && "command" in ran.result.global && ran.result.global.command) {
195
+ lines.push(`global: ${ran.result.global.command.join(" ")}`);
196
+ }
197
+ for (const host of ran.result.hosts) {
198
+ for (const args of host.commands ?? [])
199
+ lines.push(`${host.id}: ${args.join(" ")}`);
200
+ }
201
+ if (ran.result.missing?.length)
202
+ lines.push(`missing: ${ran.result.missing.join(", ")}`);
203
+ ui.notePlan("Dry run", lines);
204
+ }
205
+ else if (ran.result.missing?.length) {
206
+ ui.logInfo(`missing: ${ran.result.missing.join(", ")}`);
207
+ }
208
+ ui.endAction(ui.summarizeResult(ran.result));
150
209
  }
210
+ result = ran.result;
211
+ if (ran.exitCode)
212
+ process.exitCode = ran.exitCode;
151
213
  }
152
214
  else
153
- throw new Error("用法:baton version | agents | start | status | cancel | wait | tail | reply | ls | prune | worktree | install | update | uninstall | mcp");
215
+ throw new Error("Usage: baton version | agents | start | status | cancel | wait | tail | reply | ls | prune | worktree | install | update | uninstall | mcp");
154
216
  process.stdout.write(`${JSON.stringify(result)}\n`);
155
217
  }
156
218
  try {
package/dist/contract.js CHANGED
@@ -1,17 +1,17 @@
1
1
  export const OUTPUT_CONTRACT = [
2
- "完成前用下面两种结尾之一。标记必须各占一行。",
3
- "需要用户做选择时停下来,不要猜,也不要继续后面的步骤:",
2
+ "Before finishing, end with one of the two endings below. Each marker must be on its own line.",
3
+ "If the user must make a choice, stop; do not guess and do not continue with later steps:",
4
4
  "BATON_DECISION",
5
- "question: <一个问题>",
6
- "options: <选项A> | <选项B>",
5
+ "question: <one question>",
6
+ "options: <option A> | <option B>",
7
7
  "BATON_END",
8
8
  "",
9
- "做完时:",
9
+ "When done:",
10
10
  "BATON_RESULT",
11
- "summary: <做了什么>",
11
+ "summary: <what you did>",
12
12
  "BATON_END",
13
13
  "",
14
- "不要再调用其他 Agent。",
14
+ "Do not call other agents.",
15
15
  ].join("\n");
16
16
  export function buildPrompt(prompt, files) {
17
17
  const focus = files?.length
package/dist/git.js CHANGED
@@ -40,6 +40,25 @@ function normalizeSnapshot(snapshot) {
40
40
  return { head: null, porcelain: snapshot, digests: new Map() };
41
41
  return null;
42
42
  }
43
+ /** Paths from `git status --porcelain -uall` (repo-wide). Null outside a git repo. No content digests. */
44
+ export function dirtyPaths(cwd) {
45
+ const result = spawnSync("git", ["status", "--porcelain", "-uall"], {
46
+ cwd,
47
+ encoding: "utf8",
48
+ timeout: 5000,
49
+ });
50
+ if (result.error || result.status !== 0)
51
+ return null;
52
+ const paths = [];
53
+ for (const line of result.stdout.split("\n")) {
54
+ if (line.length < 4)
55
+ continue;
56
+ const body = line.slice(3);
57
+ const filePath = body.includes(" -> ") ? body.split(" -> ").pop() : body;
58
+ paths.push(filePath);
59
+ }
60
+ return paths.sort();
61
+ }
43
62
  export function gitSnapshot(cwd) {
44
63
  const result = spawnSync("git", ["status", "--porcelain", "-uall"], {
45
64
  cwd,
@@ -66,7 +85,7 @@ export function gitSnapshot(cwd) {
66
85
  }
67
86
  export function snapshotToBaseline(snapshot) {
68
87
  if (!snapshot.head)
69
- throw new Error("scope baseline 需要有效 HEAD。");
88
+ throw new Error("scope baseline requires a valid HEAD.");
70
89
  return {
71
90
  head: snapshot.head,
72
91
  porcelain: Object.fromEntries(snapshot.porcelain),
@@ -98,7 +117,7 @@ export function committedNames(cwd, fromHead, toHead) {
98
117
  const result = spawnSync("git", ["diff", "--name-status", "-M", `${fromHead}..${toHead}`], { cwd, encoding: "utf8", timeout: 10_000 });
99
118
  if (result.error || result.status !== 0) {
100
119
  const detail = (result.stderr || result.stdout || result.error?.message || "").trim();
101
- throw new Error(`git diff ${fromHead.slice(0, 7)}..${toHead.slice(0, 7)} 失败:${detail || `exit ${result.status}`}`);
120
+ throw new Error(`git diff ${fromHead.slice(0, 7)}..${toHead.slice(0, 7)} failed: ${detail || `exit ${result.status}`}`);
102
121
  }
103
122
  const paths = new Set();
104
123
  for (const line of (result.stdout || "").split("\n")) {
@@ -167,7 +186,7 @@ export function gitChanges(cwd, beforeRaw, afterRaw) {
167
186
  let insertions = 0;
168
187
  let deletions = 0;
169
188
  if (tracked.length) {
170
- // shortcut: 超过 50 个路径就不再逐个点名,升级时改成 --raw 再过滤。
189
+ // shortcut: stop naming paths individually beyond 50; upgrade by switching to --raw and filtering.
171
190
  const result = spawnSync("git", ["diff", "--stat", "--", ...tracked.slice(0, 50)], {
172
191
  cwd: root,
173
192
  encoding: "utf8",
@@ -0,0 +1,74 @@
1
+ import * as p from "@clack/prompts";
2
+ /** stderr for humans, with a sane width when `stderr.columns` is 0/missing (piped TTYs, `script`, etc.). */
3
+ function uiOutput() {
4
+ const stream = process.stderr;
5
+ const columns = Math.max(stream.columns || 0, process.stdout.columns || 0, Number(process.env.COLUMNS) || 0, 80);
6
+ if (stream.columns === columns)
7
+ return stream;
8
+ return new Proxy(stream, {
9
+ get(target, prop, receiver) {
10
+ if (prop === "columns")
11
+ return columns;
12
+ const value = Reflect.get(target, prop, receiver);
13
+ return typeof value === "function" ? value.bind(target) : value;
14
+ },
15
+ });
16
+ }
17
+ const out = uiOutput();
18
+ const opts = { output: out };
19
+ export function beginAction(action) {
20
+ p.intro(`baton ${action}`, opts);
21
+ }
22
+ export function endAction(message) {
23
+ p.outro(message, opts);
24
+ }
25
+ export function cancelAction(message = "Cancelled.") {
26
+ p.cancel(message, opts);
27
+ }
28
+ /** Returns selected host ids, or `null` if the user cancelled / selected none. */
29
+ export async function multiselectHosts(detected) {
30
+ const ids = detected.map((host) => host.id);
31
+ const selected = await p.multiselect({
32
+ message: "Install plugin for which agents?",
33
+ options: detected.map((host) => ({ value: host.id, label: `${host.label} (${host.id})` })),
34
+ initialValues: ids,
35
+ required: false,
36
+ ...opts,
37
+ });
38
+ if (p.isCancel(selected) || selected.length === 0)
39
+ return null;
40
+ return selected;
41
+ }
42
+ export function notePlan(title, lines) {
43
+ p.note(lines.join("\n") || "(nothing)", title, opts);
44
+ }
45
+ export function logSuccess(message) {
46
+ p.log.success(message, opts);
47
+ }
48
+ export function logError(message) {
49
+ p.log.error(message, opts);
50
+ }
51
+ export function logInfo(message) {
52
+ p.log.info(message, opts);
53
+ }
54
+ export function createSpinner() {
55
+ return p.spinner(opts);
56
+ }
57
+ export function summarizeResult(input) {
58
+ if (input.dry_run) {
59
+ const n = input.hosts.length + (input.global ? 1 : 0);
60
+ return `Dry run: ${n} step(s) planned.`;
61
+ }
62
+ const ok = input.hosts.filter((host) => host.ok).length;
63
+ const fail = input.hosts.filter((host) => host.ok === false).length;
64
+ const parts = [`${input.action} complete`];
65
+ if (input.hosts.length)
66
+ parts.push(`${ok} ok` + (fail ? `, ${fail} failed` : ""));
67
+ if (input.global?.ok === false)
68
+ parts.push("global failed");
69
+ else if (input.global?.ok)
70
+ parts.push("global ok");
71
+ if (input.missing?.length)
72
+ parts.push(`missing: ${input.missing.join(", ")}`);
73
+ return parts.join(" · ");
74
+ }
package/dist/install.js CHANGED
@@ -48,7 +48,7 @@ export const HOSTS = [
48
48
  id: "cursor",
49
49
  label: "Cursor Agent CLI",
50
50
  bins: ["agent", "cursor-agent"],
51
- note: "在 Cursor 对话里执行 /add-plugin baton",
51
+ note: "Run /add-plugin baton in a Cursor chat",
52
52
  migrate: [{ args: ["plugin", "marketplace", "remove", OLD_MARKET], soft: true }],
53
53
  install: [{ args: ["plugin", "marketplace", "add", REPO] }],
54
54
  update: [{ args: ["plugin", "marketplace", "update", "speculoai"] }],
@@ -71,28 +71,13 @@ export const HOSTS = [
71
71
  uninstall: [{ args: ["extensions", "uninstall", "baton"] }],
72
72
  },
73
73
  ];
74
- export function parseChoice(line, count) {
75
- const text = line.trim().toLowerCase();
76
- if (!text)
77
- return Array.from({ length: count }, (_, index) => index);
78
- if (text === "q")
79
- return [];
80
- const picked = [];
81
- for (const part of text.split(/[,\s]+/).filter(Boolean)) {
82
- if (!/^\d+$/.test(part))
83
- throw new Error(`无法识别的选择:${part}`);
84
- const number = Number(part);
85
- if (number < 1 || number > count)
86
- throw new Error(`选择越界:${part}`);
87
- if (!picked.includes(number - 1))
88
- picked.push(number - 1);
89
- }
90
- return picked;
74
+ export function detectedHosts(env = process.env) {
75
+ return HOSTS.filter((host) => which(host.bins, env)).map((host) => ({ id: host.id, label: host.label }));
91
76
  }
92
77
  export function commandsFor(id, action, opts = {}) {
93
78
  const host = HOSTS.find((item) => item.id === id);
94
79
  if (!host)
95
- throw new Error(`未知的 agent:${id}`);
80
+ throw new Error(`Unknown agent: ${id}`);
96
81
  if (action !== "install")
97
82
  return host[action];
98
83
  const forced = opts.force ? host.uninstall.map((step) => ({ ...step, soft: true })) : [];
@@ -103,7 +88,7 @@ export function planInstall(input) {
103
88
  const known = new Set(HOSTS.map((host) => host.id));
104
89
  for (const id of input.only ?? [])
105
90
  if (!known.has(id))
106
- throw new Error(`未知的 agent:${id}`);
91
+ throw new Error(`Unknown agent: ${id}`);
107
92
  const ids = input.only?.length
108
93
  ? input.only
109
94
  : input.action === "install"
@@ -114,11 +99,11 @@ export function planInstall(input) {
114
99
  for (const id of ids) {
115
100
  const host = HOSTS.find((item) => item.id === id);
116
101
  if (!host)
117
- throw new Error(`未知的 agent:${id}`);
102
+ throw new Error(`Unknown agent: ${id}`);
118
103
  const bin = which(host.bins, env);
119
104
  if (!bin) {
120
105
  if (input.only?.length)
121
- throw new Error(`未检测到 ${id}。`);
106
+ throw new Error(`${id} not detected.`);
122
107
  missing.push(id);
123
108
  continue;
124
109
  }
@@ -165,21 +150,20 @@ function defaultSpawn(command, args, env) {
165
150
  });
166
151
  }
167
152
  function failText(ran) {
168
- return `${ran.stderr || ran.stdout || ""}`.trim().slice(-500) || `退出码 ${ran.status}`;
153
+ return `${ran.stderr || ran.stdout || ""}`.trim().slice(-500) || `exit code ${ran.status}`;
169
154
  }
170
155
  export async function runInstall(input) {
171
156
  const env = input.env ?? process.env;
172
157
  const home = input.home ?? batonHome();
173
158
  let only = input.only;
174
- if (input.action === "install" && !only?.length && input.tty) {
175
- const detected = HOSTS.filter((host) => which(host.bins, env));
159
+ if (input.action === "install" && !only?.length && input.selectHosts) {
160
+ const detected = detectedHosts(env);
176
161
  if (!detected.length)
177
162
  return { exitCode: 0, result: { action: input.action, hosts: [] } };
178
- process.stderr.write(`${detected.map((host, index) => `[${index + 1}] ${host.id} ${host.label}`).join("\n")}\n回车全选,q 退出:`);
179
- const picked = parseChoice(await input.readLine(), detected.length);
180
- if (!picked.length)
163
+ const picked = await input.selectHosts(detected);
164
+ if (!picked?.length)
181
165
  return { exitCode: 0, result: { action: input.action, hosts: [] } };
182
- only = picked.map((index) => detected[index].id);
166
+ only = picked;
183
167
  }
184
168
  const planned = planInstall({ action: input.action, only, force: input.force, skipGlobal: input.skipGlobal, env, recorded: readInstalled(home) });
185
169
  if (input.dryRun) {
@@ -189,13 +173,17 @@ export async function runInstall(input) {
189
173
  };
190
174
  }
191
175
  const spawn = input.spawn ?? ((command, args) => defaultSpawn(command, args, env));
176
+ const report = input.onProgress;
192
177
  let global;
193
178
  if (planned.global) {
179
+ report?.({ type: "global", phase: "start" });
194
180
  const ran = await spawn(planned.global.command[0], planned.global.command.slice(1));
195
181
  global = ran.status === 0 ? { ok: true } : { ok: false, error: failText(ran) };
182
+ report?.({ type: "global", phase: "done", ok: global.ok, ...(global.error ? { error: global.error } : {}) });
196
183
  }
197
184
  const hosts = [];
198
185
  for (const host of planned.hosts) {
186
+ report?.({ type: "host", phase: "start", id: host.id });
199
187
  let error;
200
188
  let skipped = false;
201
189
  for (const step of commandsFor(host.id, input.action, { force: input.force })) {
@@ -209,8 +197,10 @@ export async function runInstall(input) {
209
197
  error = failText(ran);
210
198
  break;
211
199
  }
212
- const note = skipped ? "已安装,跳过" : host.note;
213
- hosts.push({ id: host.id, ok: !error, ...(note ? { note } : {}), ...(error ? { error } : {}) });
200
+ const note = skipped ? "already installed, skipped" : host.note;
201
+ const row = { id: host.id, ok: !error, ...(note ? { note } : {}), ...(error ? { error } : {}) };
202
+ hosts.push(row);
203
+ report?.({ type: "host", phase: "done", id: host.id, ok: row.ok, ...(note ? { note } : {}), ...(error ? { error } : {}) });
214
204
  }
215
205
  if (input.action !== "update") {
216
206
  const recorded = new Set(readInstalled(home));