@speculoai/baton 0.0.0-stage → 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.
@@ -0,0 +1,104 @@
1
+ import { redact } from "../redact.js";
2
+ import { authHit, which } from "./common.js";
3
+ const AUTH = ["not authenticated", "please log in", "agent login"];
4
+ const EMBEDDED_EFFORT = /-(low|medium|high|xhigh|ultra|max)(-fast)?$/i;
5
+ function event(data) {
6
+ return [{ ts: new Date().toISOString(), turn: 0, ...data }];
7
+ }
8
+ function parse(line) {
9
+ try {
10
+ return JSON.parse(line);
11
+ }
12
+ catch {
13
+ return null;
14
+ }
15
+ }
16
+ /** Build the Cursor `--model` value. Never emits two competing model args. */
17
+ export function resolveCursorModelArg(model, effort) {
18
+ const id = typeof model === "string" ? model.trim() : "";
19
+ const e = effort || null;
20
+ if (id && e) {
21
+ if (id.includes("["))
22
+ throw new Error("Model already has a parameter bracket; do not pass --effort.");
23
+ if (EMBEDDED_EFFORT.test(id))
24
+ throw new Error(`Model ${id} already includes an effort level; do not pass --effort.`);
25
+ return `${id}[effort=${e}]`;
26
+ }
27
+ if (id)
28
+ return id;
29
+ if (e)
30
+ return `auto[effort=${e}]`;
31
+ return null;
32
+ }
33
+ export const cursor = {
34
+ id: "cursor",
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
+ },
44
+ resolve(env) {
45
+ // The cursor-agent name does not collide with the IDE's `cursor` and is matched before any other `agent` on PATH.
46
+ return which(["cursor-agent", "agent"], env);
47
+ },
48
+ build({ bin, cwd, prompt, sessionId, reasoningEffort, model, mode }) {
49
+ const args = ["--print"];
50
+ if (mode === "readonly")
51
+ args.push("--mode", "ask");
52
+ else
53
+ args.push("--force");
54
+ args.push("--trust", "--output-format", "stream-json", "--workspace", cwd);
55
+ const modelArg = resolveCursorModelArg(model, reasoningEffort);
56
+ if (modelArg)
57
+ args.push("--model", modelArg);
58
+ if (sessionId)
59
+ args.push("--resume", sessionId);
60
+ args.push(prompt);
61
+ return { command: bin, args, stdin: null, modelArg: modelArg ?? undefined };
62
+ },
63
+ sessionIdFrom(line) {
64
+ const obj = parse(line);
65
+ return obj?.type === "system" && obj.subtype === "init" && typeof obj.session_id === "string" ? obj.session_id : null;
66
+ },
67
+ parseLine(line) {
68
+ const obj = parse(line);
69
+ if (!obj || typeof obj !== "object" || typeof obj.type !== "string")
70
+ return null;
71
+ // init is handled by sessionIdFrom; user is the prompt echo; thinking is a per-character increment that would only flood the output.
72
+ if (["system", "user", "thinking"].includes(obj.type))
73
+ return [];
74
+ if (obj.type === "assistant") {
75
+ const text = (obj.message?.content ?? [])
76
+ .filter((part) => part?.type === "text" && typeof part.text === "string")
77
+ .map((part) => part.text)
78
+ .join("");
79
+ return text ? event({ type: "message", text }) : [];
80
+ }
81
+ if (obj.type === "tool_call" && obj.tool_call && typeof obj.tool_call === "object") {
82
+ const key = Object.keys(obj.tool_call)[0];
83
+ if (!key)
84
+ return null;
85
+ const call = obj.tool_call[key] ?? {};
86
+ const name = key.replace(/ToolCall$/, "");
87
+ const args = call.args ?? {};
88
+ const detail = redact(String(args.command ?? args.path ?? JSON.stringify(args))).slice(0, 200);
89
+ if (obj.subtype === "started")
90
+ return event({ type: "tool_call", name, detail });
91
+ if (obj.subtype === "completed")
92
+ return event({ type: "tool_result", name, ok: Boolean(call.result?.success), detail });
93
+ return null;
94
+ }
95
+ if (obj.type === "result") {
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")) }) : [];
98
+ }
99
+ return null;
100
+ },
101
+ isAuthFailure(text) {
102
+ return authHit(text, AUTH);
103
+ },
104
+ };
@@ -0,0 +1,6 @@
1
+ import { agy } from "./agy.js";
2
+ import { claude } from "./claude.js";
3
+ import { codex } from "./codex.js";
4
+ import { cursor } from "./cursor.js";
5
+ export const adapters = { codex, claude, cursor, agy };
6
+ export function getAdapter(id) { return Object.hasOwn(adapters, id) ? adapters[id] : null; }
package/dist/cli.js ADDED
@@ -0,0 +1,224 @@
1
+ #!/usr/bin/env node
2
+ import fs from "node:fs";
3
+ import { parseArgs } from "node:util";
4
+ import { agents, start, status, cancel, wait, reply, ls, prune } from "./tasks.js";
5
+ import { addWorktree, listWorktrees, removeWorktree } from "./worktree.js";
6
+ import { redact } from "./redact.js";
7
+ import { runInstall } from "./install.js";
8
+ async function main() {
9
+ const [command, ...args] = process.argv.slice(2);
10
+ let result;
11
+ if (command === "_supervise") {
12
+ if (args.length !== 1)
13
+ throw new Error("task_id is missing.");
14
+ await (await import("./supervisor.js")).supervise(args[0]);
15
+ return;
16
+ }
17
+ if (command === "mcp") {
18
+ await (await import("./mcp.js")).startMcp();
19
+ return;
20
+ }
21
+ if (command === "version" || command === "--version") {
22
+ result = { version: JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf8")).version };
23
+ }
24
+ else if (command === "agents") {
25
+ result = { agents: agents() };
26
+ }
27
+ else if (command === "start") {
28
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: {
29
+ target: { type: "string" }, prompt: { type: "string" }, cwd: { type: "string" },
30
+ file: { type: "string", multiple: true }, effort: { type: "string" }, model: { type: "string" },
31
+ "idle-timeout": { type: "string" }, "max-duration": { type: "string" },
32
+ scope: { type: "string", multiple: true }, "scope-on-violation": { type: "string" },
33
+ mode: { type: "string" }, "allow-weak": { type: "boolean" },
34
+ isolate: { type: "boolean" }, "allow-dirty": { type: "boolean" },
35
+ rules: { type: "string" },
36
+ } });
37
+ if (positionals.length)
38
+ throw new Error("start takes no positional arguments.");
39
+ result = await start({ target: values.target || "", prompt: values.prompt ?? fs.readFileSync(0, "utf8"), cwd: values.cwd, files: values.file,
40
+ reasoningEffort: values.effort, model: values.model,
41
+ idleTimeout: values["idle-timeout"] === undefined ? undefined : Number(values["idle-timeout"]), maxDuration: values["max-duration"] === undefined ? undefined : Number(values["max-duration"]),
42
+ scope: values.scope, scopeOnViolation: values["scope-on-violation"],
43
+ mode: values.mode, allowWeak: values["allow-weak"],
44
+ isolate: values.isolate, allowDirty: values["allow-dirty"],
45
+ rules: values.rules,
46
+ });
47
+ if (result.status !== "running")
48
+ process.exitCode = 1;
49
+ }
50
+ else if (command === "status") {
51
+ if (args.length !== 1)
52
+ throw new Error("status requires one task_id.");
53
+ result = status(args[0]);
54
+ }
55
+ else if (command === "reply") {
56
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { prompt: { type: "string" }, as: { type: "string" } } });
57
+ if (positionals.length !== 1)
58
+ throw new Error("reply requires one task_id.");
59
+ result = await reply(positionals[0], values.prompt ?? fs.readFileSync(0, "utf8"), (values.as ?? "host"));
60
+ if (result.status !== "running")
61
+ process.exitCode = 1;
62
+ }
63
+ else if (command === "wait") {
64
+ const { values, positionals } = parseArgs({
65
+ args, allowPositionals: true,
66
+ options: { for: { type: "string" }, "until-done": { type: "boolean" } },
67
+ });
68
+ if (values["until-done"] && values.for !== undefined)
69
+ throw new Error("--until-done and --for cannot be used together.");
70
+ result = await wait(positionals, values["until-done"] ? Infinity : values.for === undefined ? 50 : Number(values.for));
71
+ }
72
+ else if (command === "tail") {
73
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { follow: { type: "boolean", short: "f" }, raw: { type: "boolean" } } });
74
+ if (positionals.length !== 1)
75
+ throw new Error("tail requires one task_id.");
76
+ await (await import("./tail.js")).tail(positionals[0], { follow: values.follow, raw: values.raw });
77
+ return;
78
+ }
79
+ else if (command === "ls") {
80
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { all: { type: "boolean" } } });
81
+ if (positionals.length)
82
+ throw new Error("ls takes no positional arguments.");
83
+ result = { tasks: ls(values.all) };
84
+ }
85
+ else if (command === "prune") {
86
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { older: { type: "string" } } });
87
+ if (positionals.length || values.older === undefined)
88
+ throw new Error("prune requires --older days.");
89
+ result = { deleted: prune(Number(values.older)) };
90
+ }
91
+ else if (command === "cancel") {
92
+ if (args.length !== 1)
93
+ throw new Error("cancel requires one task_id.");
94
+ result = await cancel(args[0]);
95
+ }
96
+ else if (command === "worktree") {
97
+ const [action, ...rest] = args;
98
+ if (action === "add") {
99
+ const { values, positionals } = parseArgs({
100
+ args: rest,
101
+ allowPositionals: true,
102
+ options: { name: { type: "string" }, branch: { type: "string" }, base: { type: "string" } },
103
+ });
104
+ if (positionals.length)
105
+ throw new Error("worktree add takes no positional arguments.");
106
+ result = addWorktree(process.cwd(), { name: values.name, branch: values.branch, base: values.base });
107
+ }
108
+ else if (action === "ls") {
109
+ if (rest.length)
110
+ throw new Error("worktree ls takes no extra arguments.");
111
+ result = { worktrees: listWorktrees(process.cwd()) };
112
+ }
113
+ else if (action === "rm") {
114
+ if (rest.length !== 1)
115
+ throw new Error("worktree rm requires one name or path.");
116
+ result = removeWorktree(process.cwd(), rest[0]);
117
+ }
118
+ else {
119
+ throw new Error("Usage: baton worktree add|ls|rm");
120
+ }
121
+ }
122
+ else if (command === "install" || command === "update" || command === "uninstall") {
123
+ const { values, positionals } = parseArgs({
124
+ args, allowPositionals: true,
125
+ options: {
126
+ only: { type: "string", multiple: true }, force: { type: "boolean" },
127
+ "dry-run": { type: "boolean" }, "skip-global": { type: "boolean" },
128
+ },
129
+ });
130
+ if (positionals.length)
131
+ throw new Error(`${command} takes no positional arguments.`);
132
+ if (command !== "install" && values.force)
133
+ throw new Error(`${command} does not accept --force.`);
134
+ if (command === "uninstall" && values["skip-global"])
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));
209
+ }
210
+ result = ran.result;
211
+ if (ran.exitCode)
212
+ process.exitCode = ran.exitCode;
213
+ }
214
+ else
215
+ throw new Error("Usage: baton version | agents | start | status | cancel | wait | tail | reply | ls | prune | worktree | install | update | uninstall | mcp");
216
+ process.stdout.write(`${JSON.stringify(result)}\n`);
217
+ }
218
+ try {
219
+ await main();
220
+ }
221
+ catch (error) {
222
+ process.stdout.write(`${JSON.stringify({ status: "failed", summary: redact(error.message) })}\n`);
223
+ process.exitCode = 1;
224
+ }
@@ -0,0 +1,42 @@
1
+ export const OUTPUT_CONTRACT = [
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
+ "BATON_DECISION",
5
+ "question: <one question>",
6
+ "options: <option A> | <option B>",
7
+ "BATON_END",
8
+ "",
9
+ "When done:",
10
+ "BATON_RESULT",
11
+ "summary: <what you did>",
12
+ "BATON_END",
13
+ "",
14
+ "Do not call other agents.",
15
+ ].join("\n");
16
+ export function buildPrompt(prompt, files) {
17
+ const focus = files?.length
18
+ ? `Focus on these files:\n${files.map((file) => `- ${file}`).join("\n")}\n\n`
19
+ : "";
20
+ return `${focus}${String(prompt).trim()}\n\n${OUTPUT_CONTRACT}`;
21
+ }
22
+ export function interpret(text) {
23
+ if (!text)
24
+ return null;
25
+ const re = /(?:APA|BATON)_(DECISION|RESULT)\r?\n([\s\S]*?)\r?\n(?:APA|BATON)_END/g;
26
+ let last = null;
27
+ for (const match of text.matchAll(re))
28
+ last = match;
29
+ if (!last)
30
+ return null;
31
+ const body = last[2];
32
+ if (last[1] === "DECISION") {
33
+ const question = body.match(/^question:\s*(.*)$/m)?.[1]?.trim() || "";
34
+ const options = (body.match(/^options:\s*(.*)$/m)?.[1] || "")
35
+ .split("|")
36
+ .map((item) => item.trim())
37
+ .filter(Boolean);
38
+ return { kind: "decision", question, options };
39
+ }
40
+ const summary = body.replace(/^summary:\s*/m, "").trim();
41
+ return { kind: "result", summary };
42
+ }
package/dist/git.js ADDED
@@ -0,0 +1,220 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { spawnSync } from "node:child_process";
5
+ function digestFile(cwd, filePath) {
6
+ try {
7
+ const full = path.join(cwd, filePath);
8
+ const data = fs.readFileSync(full);
9
+ return crypto.createHash("sha256").update(data).digest("hex");
10
+ }
11
+ catch {
12
+ return null;
13
+ }
14
+ }
15
+ function revParseHead(cwd) {
16
+ const result = spawnSync("git", ["rev-parse", "HEAD"], { cwd, encoding: "utf8", timeout: 5000 });
17
+ if (result.error || result.status !== 0)
18
+ return null;
19
+ const head = (result.stdout || "").trim();
20
+ return head || null;
21
+ }
22
+ export function gitRepoRoot(cwd) {
23
+ const result = spawnSync("git", ["rev-parse", "--show-toplevel"], { cwd, encoding: "utf8", timeout: 5000 });
24
+ if (result.error || result.status !== 0)
25
+ return null;
26
+ const root = (result.stdout || "").trim();
27
+ return root || null;
28
+ }
29
+ function normalizeSnapshot(snapshot) {
30
+ if (!snapshot)
31
+ return null;
32
+ if (!(snapshot instanceof Map) && snapshot.porcelain instanceof Map) {
33
+ return {
34
+ head: snapshot.head ?? null,
35
+ porcelain: snapshot.porcelain,
36
+ digests: snapshot.digests ?? new Map(),
37
+ };
38
+ }
39
+ if (snapshot instanceof Map)
40
+ return { head: null, porcelain: snapshot, digests: new Map() };
41
+ return null;
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
+ }
62
+ export function gitSnapshot(cwd) {
63
+ const result = spawnSync("git", ["status", "--porcelain", "-uall"], {
64
+ cwd,
65
+ encoding: "utf8",
66
+ timeout: 5000,
67
+ });
68
+ if (result.error || result.status !== 0)
69
+ return null;
70
+ // Porcelain paths are relative to the repo root, even when cwd is a subdirectory.
71
+ const root = gitRepoRoot(cwd) ?? cwd;
72
+ const porcelain = new Map();
73
+ const digests = new Map();
74
+ for (const line of result.stdout.split("\n")) {
75
+ if (line.length < 4)
76
+ continue;
77
+ const body = line.slice(3);
78
+ const filePath = body.includes(" -> ") ? body.split(" -> ").pop() : body;
79
+ porcelain.set(filePath, line);
80
+ const digest = digestFile(root, filePath);
81
+ if (digest)
82
+ digests.set(filePath, digest);
83
+ }
84
+ return { head: revParseHead(cwd), porcelain, digests };
85
+ }
86
+ export function snapshotToBaseline(snapshot) {
87
+ if (!snapshot.head)
88
+ throw new Error("scope baseline requires a valid HEAD.");
89
+ return {
90
+ head: snapshot.head,
91
+ porcelain: Object.fromEntries(snapshot.porcelain),
92
+ digests: Object.fromEntries(snapshot.digests),
93
+ };
94
+ }
95
+ export function baselineToSnapshot(baseline) {
96
+ return {
97
+ head: baseline.head,
98
+ porcelain: new Map(Object.entries(baseline.porcelain)),
99
+ digests: new Map(Object.entries(baseline.digests)),
100
+ };
101
+ }
102
+ function workingTreeChanged(before, after) {
103
+ const paths = [];
104
+ for (const key of new Set([...before.porcelain.keys(), ...after.porcelain.keys()])) {
105
+ const lineChanged = before.porcelain.get(key) !== after.porcelain.get(key);
106
+ const digestChanged = before.digests.get(key) !== after.digests.get(key)
107
+ && (before.digests.has(key) || after.digests.has(key));
108
+ if (lineChanged || digestChanged)
109
+ paths.push(key);
110
+ }
111
+ return paths;
112
+ }
113
+ /** Committed path names between two HEADs; renames contribute both sides. Throws if git diff fails while HEADs differ. */
114
+ export function committedNames(cwd, fromHead, toHead) {
115
+ if (!fromHead || !toHead || fromHead === toHead)
116
+ return [];
117
+ const result = spawnSync("git", ["diff", "--name-status", "-M", `${fromHead}..${toHead}`], { cwd, encoding: "utf8", timeout: 10_000 });
118
+ if (result.error || result.status !== 0) {
119
+ const detail = (result.stderr || result.stdout || result.error?.message || "").trim();
120
+ throw new Error(`git diff ${fromHead.slice(0, 7)}..${toHead.slice(0, 7)} failed: ${detail || `exit ${result.status}`}`);
121
+ }
122
+ const paths = new Set();
123
+ for (const line of (result.stdout || "").split("\n")) {
124
+ if (!line.trim())
125
+ continue;
126
+ const parts = line.split("\t");
127
+ const status = parts[0] ?? "";
128
+ if (status.startsWith("R") || status.startsWith("C")) {
129
+ if (parts[1])
130
+ paths.add(parts[1]);
131
+ if (parts[2])
132
+ paths.add(parts[2]);
133
+ }
134
+ else if (parts[1]) {
135
+ paths.add(parts[1]);
136
+ }
137
+ }
138
+ return [...paths];
139
+ }
140
+ /** Task-level net change: commits since baseline HEAD ∪ working-tree digest/porcelain diff. */
141
+ export function pathsSinceBaseline(cwd, baseline, current) {
142
+ const set = new Set();
143
+ if (baseline.head && current.head) {
144
+ for (const p of committedNames(cwd, baseline.head, current.head))
145
+ set.add(p);
146
+ }
147
+ for (const p of workingTreeChanged(baseline, current))
148
+ set.add(p);
149
+ return [...set];
150
+ }
151
+ function untrackedInsertions(cwd, filePath) {
152
+ try {
153
+ const text = fs.readFileSync(path.join(cwd, filePath), "utf8");
154
+ if (!text)
155
+ return 0;
156
+ const lines = text.split("\n");
157
+ return text.endsWith("\n") ? Math.max(lines.length - 1, 0) : lines.length;
158
+ }
159
+ catch {
160
+ return 0;
161
+ }
162
+ }
163
+ export function gitChanges(cwd, beforeRaw, afterRaw) {
164
+ const before = normalizeSnapshot(beforeRaw);
165
+ const after = normalizeSnapshot(afterRaw);
166
+ if (!before || !after)
167
+ return undefined;
168
+ const paths = workingTreeChanged(before, after);
169
+ if (paths.length === 0) {
170
+ return { files_changed: 0, insertions: 0, deletions: 0, diff_stat: "" };
171
+ }
172
+ const root = gitRepoRoot(cwd) ?? cwd;
173
+ const untracked = [];
174
+ const tracked = [];
175
+ for (const filePath of paths) {
176
+ const afterLine = after.porcelain.get(filePath);
177
+ const beforeLine = before.porcelain.get(filePath);
178
+ if (afterLine?.startsWith("??") || (!afterLine && beforeLine?.startsWith("??"))) {
179
+ untracked.push(filePath);
180
+ }
181
+ else {
182
+ tracked.push(filePath);
183
+ }
184
+ }
185
+ let diffStat = "";
186
+ let insertions = 0;
187
+ let deletions = 0;
188
+ if (tracked.length) {
189
+ // shortcut: stop naming paths individually beyond 50; upgrade by switching to --raw and filtering.
190
+ const result = spawnSync("git", ["diff", "--stat", "--", ...tracked.slice(0, 50)], {
191
+ cwd: root,
192
+ encoding: "utf8",
193
+ timeout: 5000,
194
+ });
195
+ diffStat = (result.stdout || "").trim();
196
+ insertions = Number(diffStat.match(/(\d+) insertion/)?.[1] || 0);
197
+ deletions = Number(diffStat.match(/(\d+) deletion/)?.[1] || 0);
198
+ }
199
+ if (untracked.length) {
200
+ const extras = [];
201
+ for (const filePath of untracked) {
202
+ if (after.porcelain.has(filePath)) {
203
+ const added = untrackedInsertions(root, filePath);
204
+ insertions += added;
205
+ extras.push(`${filePath} | untracked +${added}`);
206
+ }
207
+ else {
208
+ extras.push(`${filePath} | untracked deleted`);
209
+ }
210
+ }
211
+ const extra = extras.join("\n");
212
+ diffStat = diffStat ? `${diffStat}\n${extra}` : extra;
213
+ }
214
+ return {
215
+ files_changed: paths.length,
216
+ insertions,
217
+ deletions,
218
+ diff_stat: diffStat,
219
+ };
220
+ }
@@ -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
+ }