@speculoai/baton 0.0.0-stage → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +459 -2
- package/README.zh-CN.md +460 -0
- package/dist/adapters/agy.js +62 -0
- package/dist/adapters/claude.js +79 -0
- package/dist/adapters/codex.js +105 -0
- package/dist/adapters/common.js +25 -0
- package/dist/adapters/cursor.js +96 -0
- package/dist/adapters/index.js +6 -0
- package/dist/cli.js +162 -0
- package/dist/contract.js +42 -0
- package/dist/git.js +201 -0
- package/dist/install.js +231 -0
- package/dist/mcp.js +90 -0
- package/dist/process.js +23 -0
- package/dist/redact.js +9 -0
- package/dist/scope.js +108 -0
- package/dist/store.js +105 -0
- package/dist/supervisor.js +293 -0
- package/dist/tail.js +64 -0
- package/dist/tasks.js +305 -0
- package/dist/types.js +1 -0
- package/dist/worktree.js +260 -0
- package/package.json +34 -4
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { redact } from "../redact.js";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { authHit, which } from "./common.js";
|
|
5
|
+
const AUTH = ["not logged in", "please log in", "authentication required", "codex login"];
|
|
6
|
+
export const codex = {
|
|
7
|
+
id: "codex",
|
|
8
|
+
readonlyEnforcement: "os-sandbox",
|
|
9
|
+
resolve(env) {
|
|
10
|
+
return which(["codex"], env);
|
|
11
|
+
},
|
|
12
|
+
build({ bin, cwd, prompt, sessionId, reasoningEffort, mode }) {
|
|
13
|
+
const lastMessagePath = path.join(os.tmpdir(), `baton-codex-${process.pid}-${Date.now()}.txt`);
|
|
14
|
+
const effortArgs = reasoningEffort ? ["-c", `model_reasoning_effort="${reasoningEffort}"`] : [];
|
|
15
|
+
const readonly = mode === "readonly";
|
|
16
|
+
// `exec resume` 不接受 --cd/--color/--sandbox。write 首轮用 --approve-for-me(workspace-write,勿再加 --sandbox)。
|
|
17
|
+
if (sessionId) {
|
|
18
|
+
return {
|
|
19
|
+
command: bin,
|
|
20
|
+
args: [
|
|
21
|
+
"exec",
|
|
22
|
+
"resume",
|
|
23
|
+
"--json",
|
|
24
|
+
"--skip-git-repo-check",
|
|
25
|
+
"--output-last-message",
|
|
26
|
+
lastMessagePath,
|
|
27
|
+
...effortArgs,
|
|
28
|
+
sessionId,
|
|
29
|
+
"-",
|
|
30
|
+
],
|
|
31
|
+
stdin: prompt,
|
|
32
|
+
lastMessagePath,
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
return {
|
|
36
|
+
command: bin,
|
|
37
|
+
args: [
|
|
38
|
+
"exec",
|
|
39
|
+
"--json",
|
|
40
|
+
"--color",
|
|
41
|
+
"never",
|
|
42
|
+
...(readonly ? ["--sandbox", "read-only"] : ["--approve-for-me"]),
|
|
43
|
+
"--skip-git-repo-check",
|
|
44
|
+
"--cd",
|
|
45
|
+
cwd,
|
|
46
|
+
"--output-last-message",
|
|
47
|
+
lastMessagePath,
|
|
48
|
+
...effortArgs,
|
|
49
|
+
"-",
|
|
50
|
+
],
|
|
51
|
+
stdin: prompt,
|
|
52
|
+
lastMessagePath,
|
|
53
|
+
};
|
|
54
|
+
},
|
|
55
|
+
sessionIdFrom(line) {
|
|
56
|
+
try {
|
|
57
|
+
const obj = JSON.parse(line);
|
|
58
|
+
return obj?.type === "thread.started" && typeof obj.thread_id === "string" ? obj.thread_id : null;
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
},
|
|
64
|
+
parseLine(line) {
|
|
65
|
+
let obj;
|
|
66
|
+
try {
|
|
67
|
+
obj = JSON.parse(line);
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
if (!obj || typeof obj !== "object")
|
|
73
|
+
return null;
|
|
74
|
+
const event = (data) => [{ ts: new Date().toISOString(), turn: 0, ...data }];
|
|
75
|
+
if (obj.type === "turn.failed" && typeof obj.error?.message === "string")
|
|
76
|
+
return event({ type: "error", text: obj.error.message });
|
|
77
|
+
// 生命周期事件:session id 由 sessionIdFrom 取,轮次起止由 supervisor 记录,这里不重复出事件。
|
|
78
|
+
if (["thread.started", "turn.started", "turn.completed"].includes(obj.type))
|
|
79
|
+
return [];
|
|
80
|
+
const item = obj.item;
|
|
81
|
+
if (obj.type === "item.completed" && item?.type === "error" && typeof item.message === "string") {
|
|
82
|
+
return event({ type: "error", text: redact(item.message) });
|
|
83
|
+
}
|
|
84
|
+
if (!item || !["item.started", "item.completed"].includes(obj.type))
|
|
85
|
+
return null;
|
|
86
|
+
const completed = obj.type === "item.completed";
|
|
87
|
+
if (item.type === "agent_message" && typeof item.text === "string")
|
|
88
|
+
return completed ? event({ type: "message", text: item.text }) : [];
|
|
89
|
+
if (item.type === "command_execution" && typeof item.command === "string") {
|
|
90
|
+
return event(completed
|
|
91
|
+
? { type: "tool_result", name: "command_execution", ok: item.exit_code === 0, detail: redact(String(item.aggregated_output || item.command)).slice(0, 200) }
|
|
92
|
+
: { type: "tool_call", name: "command_execution", detail: redact(item.command).slice(0, 200) });
|
|
93
|
+
}
|
|
94
|
+
if (item.type === "file_change" && Array.isArray(item.changes)) {
|
|
95
|
+
const detail = redact(JSON.stringify(item.changes)).slice(0, 200);
|
|
96
|
+
return event(completed
|
|
97
|
+
? { type: "tool_result", name: "file_change", ok: item.status === "completed", detail }
|
|
98
|
+
: { type: "tool_call", name: "file_change", detail });
|
|
99
|
+
}
|
|
100
|
+
return null;
|
|
101
|
+
},
|
|
102
|
+
isAuthFailure(text) {
|
|
103
|
+
return authHit(text, AUTH);
|
|
104
|
+
},
|
|
105
|
+
};
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
export function which(names, env = process.env) {
|
|
4
|
+
const dirs = (env.PATH || "").split(path.delimiter).filter(Boolean);
|
|
5
|
+
for (const name of names) {
|
|
6
|
+
for (const dir of dirs) {
|
|
7
|
+
const full = path.join(dir, name);
|
|
8
|
+
try {
|
|
9
|
+
const stat = fs.statSync(full);
|
|
10
|
+
if (!stat.isFile())
|
|
11
|
+
continue;
|
|
12
|
+
fs.accessSync(full, fs.constants.X_OK);
|
|
13
|
+
return full;
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
// Try the next PATH entry.
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
return null;
|
|
21
|
+
}
|
|
22
|
+
export function authHit(text, phrases) {
|
|
23
|
+
const hay = String(text || "").toLowerCase();
|
|
24
|
+
return phrases.some((phrase) => hay.includes(phrase));
|
|
25
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
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("模型已含参数括号,不要再传 --effort。");
|
|
23
|
+
if (EMBEDDED_EFFORT.test(id))
|
|
24
|
+
throw new Error(`模型 ${id} 已含档位,不要再传 --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
|
+
resolve(env) {
|
|
37
|
+
// cursor-agent 名字不会撞上 IDE 的 `cursor`,也比 PATH 里别的 `agent` 先命中。
|
|
38
|
+
return which(["cursor-agent", "agent"], env);
|
|
39
|
+
},
|
|
40
|
+
build({ bin, cwd, prompt, sessionId, reasoningEffort, model, mode }) {
|
|
41
|
+
const args = ["--print"];
|
|
42
|
+
if (mode === "readonly")
|
|
43
|
+
args.push("--mode", "ask");
|
|
44
|
+
else
|
|
45
|
+
args.push("--force");
|
|
46
|
+
args.push("--trust", "--output-format", "stream-json", "--workspace", cwd);
|
|
47
|
+
const modelArg = resolveCursorModelArg(model, reasoningEffort);
|
|
48
|
+
if (modelArg)
|
|
49
|
+
args.push("--model", modelArg);
|
|
50
|
+
if (sessionId)
|
|
51
|
+
args.push("--resume", sessionId);
|
|
52
|
+
args.push(prompt);
|
|
53
|
+
return { command: bin, args, stdin: null, modelArg: modelArg ?? undefined };
|
|
54
|
+
},
|
|
55
|
+
sessionIdFrom(line) {
|
|
56
|
+
const obj = parse(line);
|
|
57
|
+
return obj?.type === "system" && obj.subtype === "init" && typeof obj.session_id === "string" ? obj.session_id : null;
|
|
58
|
+
},
|
|
59
|
+
parseLine(line) {
|
|
60
|
+
const obj = parse(line);
|
|
61
|
+
if (!obj || typeof obj !== "object" || typeof obj.type !== "string")
|
|
62
|
+
return null;
|
|
63
|
+
// init 由 sessionIdFrom 处理;user 是 prompt 回显;thinking 是逐字增量,只会刷屏。
|
|
64
|
+
if (["system", "user", "thinking"].includes(obj.type))
|
|
65
|
+
return [];
|
|
66
|
+
if (obj.type === "assistant") {
|
|
67
|
+
const text = (obj.message?.content ?? [])
|
|
68
|
+
.filter((part) => part?.type === "text" && typeof part.text === "string")
|
|
69
|
+
.map((part) => part.text)
|
|
70
|
+
.join("");
|
|
71
|
+
return text ? event({ type: "message", text }) : [];
|
|
72
|
+
}
|
|
73
|
+
if (obj.type === "tool_call" && obj.tool_call && typeof obj.tool_call === "object") {
|
|
74
|
+
const key = Object.keys(obj.tool_call)[0];
|
|
75
|
+
if (!key)
|
|
76
|
+
return null;
|
|
77
|
+
const call = obj.tool_call[key] ?? {};
|
|
78
|
+
const name = key.replace(/ToolCall$/, "");
|
|
79
|
+
const args = call.args ?? {};
|
|
80
|
+
const detail = redact(String(args.command ?? args.path ?? JSON.stringify(args))).slice(0, 200);
|
|
81
|
+
if (obj.subtype === "started")
|
|
82
|
+
return event({ type: "tool_call", name, detail });
|
|
83
|
+
if (obj.subtype === "completed")
|
|
84
|
+
return event({ type: "tool_result", name, ok: Boolean(call.result?.success), detail });
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
if (obj.type === "result") {
|
|
88
|
+
// 最终文本已经以 assistant 消息出过一次,这里只报错误。
|
|
89
|
+
return obj.is_error ? event({ type: "error", text: redact(String(obj.result ?? "cursor 返回错误")) }) : [];
|
|
90
|
+
}
|
|
91
|
+
return null;
|
|
92
|
+
},
|
|
93
|
+
isAuthFailure(text) {
|
|
94
|
+
return authHit(text, AUTH);
|
|
95
|
+
},
|
|
96
|
+
};
|
|
@@ -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,162 @@
|
|
|
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。");
|
|
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
|
+
} });
|
|
35
|
+
if (positionals.length)
|
|
36
|
+
throw new Error("start 不接受位置参数。");
|
|
37
|
+
result = await start({ target: values.target || "", prompt: values.prompt ?? fs.readFileSync(0, "utf8"), cwd: values.cwd, files: values.file,
|
|
38
|
+
reasoningEffort: values.effort, model: values.model,
|
|
39
|
+
idleTimeout: values["idle-timeout"] === undefined ? undefined : Number(values["idle-timeout"]), maxDuration: values["max-duration"] === undefined ? undefined : Number(values["max-duration"]),
|
|
40
|
+
scope: values.scope, scopeOnViolation: values["scope-on-violation"],
|
|
41
|
+
mode: values.mode, allowWeak: values["allow-weak"], });
|
|
42
|
+
if (result.status !== "running")
|
|
43
|
+
process.exitCode = 1;
|
|
44
|
+
}
|
|
45
|
+
else if (command === "status") {
|
|
46
|
+
if (args.length !== 1)
|
|
47
|
+
throw new Error("status 需要一个 task_id。");
|
|
48
|
+
result = status(args[0]);
|
|
49
|
+
}
|
|
50
|
+
else if (command === "reply") {
|
|
51
|
+
const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { prompt: { type: "string" }, as: { type: "string" } } });
|
|
52
|
+
if (positionals.length !== 1)
|
|
53
|
+
throw new Error("reply 需要一个 task_id。");
|
|
54
|
+
result = await reply(positionals[0], values.prompt ?? fs.readFileSync(0, "utf8"), (values.as ?? "host"));
|
|
55
|
+
if (result.status !== "running")
|
|
56
|
+
process.exitCode = 1;
|
|
57
|
+
}
|
|
58
|
+
else if (command === "wait") {
|
|
59
|
+
const { values, positionals } = parseArgs({
|
|
60
|
+
args, allowPositionals: true,
|
|
61
|
+
options: { for: { type: "string" }, "until-done": { type: "boolean" } },
|
|
62
|
+
});
|
|
63
|
+
if (values["until-done"] && values.for !== undefined)
|
|
64
|
+
throw new Error("--until-done 与 --for 不能同时使用。");
|
|
65
|
+
result = await wait(positionals, values["until-done"] ? Infinity : values.for === undefined ? 50 : Number(values.for));
|
|
66
|
+
}
|
|
67
|
+
else if (command === "tail") {
|
|
68
|
+
const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { follow: { type: "boolean", short: "f" }, raw: { type: "boolean" } } });
|
|
69
|
+
if (positionals.length !== 1)
|
|
70
|
+
throw new Error("tail 需要一个 task_id。");
|
|
71
|
+
await (await import("./tail.js")).tail(positionals[0], { follow: values.follow, raw: values.raw });
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
else if (command === "ls") {
|
|
75
|
+
const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { all: { type: "boolean" } } });
|
|
76
|
+
if (positionals.length)
|
|
77
|
+
throw new Error("ls 不接受位置参数。");
|
|
78
|
+
result = { tasks: ls(values.all) };
|
|
79
|
+
}
|
|
80
|
+
else if (command === "prune") {
|
|
81
|
+
const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { older: { type: "string" } } });
|
|
82
|
+
if (positionals.length || values.older === undefined)
|
|
83
|
+
throw new Error("prune 需要 --older 天数。");
|
|
84
|
+
result = { deleted: prune(Number(values.older)) };
|
|
85
|
+
}
|
|
86
|
+
else if (command === "cancel") {
|
|
87
|
+
if (args.length !== 1)
|
|
88
|
+
throw new Error("cancel 需要一个 task_id。");
|
|
89
|
+
result = await cancel(args[0]);
|
|
90
|
+
}
|
|
91
|
+
else if (command === "worktree") {
|
|
92
|
+
const [action, ...rest] = args;
|
|
93
|
+
if (action === "add") {
|
|
94
|
+
const { values, positionals } = parseArgs({
|
|
95
|
+
args: rest,
|
|
96
|
+
allowPositionals: true,
|
|
97
|
+
options: { name: { type: "string" }, branch: { type: "string" }, base: { type: "string" } },
|
|
98
|
+
});
|
|
99
|
+
if (positionals.length)
|
|
100
|
+
throw new Error("worktree add 不接受位置参数。");
|
|
101
|
+
result = addWorktree(process.cwd(), { name: values.name, branch: values.branch, base: values.base });
|
|
102
|
+
}
|
|
103
|
+
else if (action === "ls") {
|
|
104
|
+
if (rest.length)
|
|
105
|
+
throw new Error("worktree ls 不接受额外参数。");
|
|
106
|
+
result = { worktrees: listWorktrees(process.cwd()) };
|
|
107
|
+
}
|
|
108
|
+
else if (action === "rm") {
|
|
109
|
+
if (rest.length !== 1)
|
|
110
|
+
throw new Error("worktree rm 需要一个 name 或 path。");
|
|
111
|
+
result = removeWorktree(process.cwd(), rest[0]);
|
|
112
|
+
}
|
|
113
|
+
else {
|
|
114
|
+
throw new Error("用法:baton worktree add|ls|rm");
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
else if (command === "install" || command === "update" || command === "uninstall") {
|
|
118
|
+
const { values, positionals } = parseArgs({
|
|
119
|
+
args, allowPositionals: true,
|
|
120
|
+
options: {
|
|
121
|
+
only: { type: "string", multiple: true }, force: { type: "boolean" },
|
|
122
|
+
"dry-run": { type: "boolean" }, "skip-global": { type: "boolean" },
|
|
123
|
+
},
|
|
124
|
+
});
|
|
125
|
+
if (positionals.length)
|
|
126
|
+
throw new Error(`${command} 不接受位置参数。`);
|
|
127
|
+
if (command !== "install" && values.force)
|
|
128
|
+
throw new Error(`${command} 不接受 --force。`);
|
|
129
|
+
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();
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
else
|
|
153
|
+
throw new Error("用法:baton version | agents | start | status | cancel | wait | tail | reply | ls | prune | worktree | install | update | uninstall | mcp");
|
|
154
|
+
process.stdout.write(`${JSON.stringify(result)}\n`);
|
|
155
|
+
}
|
|
156
|
+
try {
|
|
157
|
+
await main();
|
|
158
|
+
}
|
|
159
|
+
catch (error) {
|
|
160
|
+
process.stdout.write(`${JSON.stringify({ status: "failed", summary: redact(error.message) })}\n`);
|
|
161
|
+
process.exitCode = 1;
|
|
162
|
+
}
|
package/dist/contract.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
export const OUTPUT_CONTRACT = [
|
|
2
|
+
"完成前用下面两种结尾之一。标记必须各占一行。",
|
|
3
|
+
"需要用户做选择时停下来,不要猜,也不要继续后面的步骤:",
|
|
4
|
+
"BATON_DECISION",
|
|
5
|
+
"question: <一个问题>",
|
|
6
|
+
"options: <选项A> | <选项B>",
|
|
7
|
+
"BATON_END",
|
|
8
|
+
"",
|
|
9
|
+
"做完时:",
|
|
10
|
+
"BATON_RESULT",
|
|
11
|
+
"summary: <做了什么>",
|
|
12
|
+
"BATON_END",
|
|
13
|
+
"",
|
|
14
|
+
"不要再调用其他 Agent。",
|
|
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,201 @@
|
|
|
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
|
+
export function gitSnapshot(cwd) {
|
|
44
|
+
const result = spawnSync("git", ["status", "--porcelain", "-uall"], {
|
|
45
|
+
cwd,
|
|
46
|
+
encoding: "utf8",
|
|
47
|
+
timeout: 5000,
|
|
48
|
+
});
|
|
49
|
+
if (result.error || result.status !== 0)
|
|
50
|
+
return null;
|
|
51
|
+
// Porcelain paths are relative to the repo root, even when cwd is a subdirectory.
|
|
52
|
+
const root = gitRepoRoot(cwd) ?? cwd;
|
|
53
|
+
const porcelain = new Map();
|
|
54
|
+
const digests = new Map();
|
|
55
|
+
for (const line of result.stdout.split("\n")) {
|
|
56
|
+
if (line.length < 4)
|
|
57
|
+
continue;
|
|
58
|
+
const body = line.slice(3);
|
|
59
|
+
const filePath = body.includes(" -> ") ? body.split(" -> ").pop() : body;
|
|
60
|
+
porcelain.set(filePath, line);
|
|
61
|
+
const digest = digestFile(root, filePath);
|
|
62
|
+
if (digest)
|
|
63
|
+
digests.set(filePath, digest);
|
|
64
|
+
}
|
|
65
|
+
return { head: revParseHead(cwd), porcelain, digests };
|
|
66
|
+
}
|
|
67
|
+
export function snapshotToBaseline(snapshot) {
|
|
68
|
+
if (!snapshot.head)
|
|
69
|
+
throw new Error("scope baseline 需要有效 HEAD。");
|
|
70
|
+
return {
|
|
71
|
+
head: snapshot.head,
|
|
72
|
+
porcelain: Object.fromEntries(snapshot.porcelain),
|
|
73
|
+
digests: Object.fromEntries(snapshot.digests),
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
export function baselineToSnapshot(baseline) {
|
|
77
|
+
return {
|
|
78
|
+
head: baseline.head,
|
|
79
|
+
porcelain: new Map(Object.entries(baseline.porcelain)),
|
|
80
|
+
digests: new Map(Object.entries(baseline.digests)),
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
function workingTreeChanged(before, after) {
|
|
84
|
+
const paths = [];
|
|
85
|
+
for (const key of new Set([...before.porcelain.keys(), ...after.porcelain.keys()])) {
|
|
86
|
+
const lineChanged = before.porcelain.get(key) !== after.porcelain.get(key);
|
|
87
|
+
const digestChanged = before.digests.get(key) !== after.digests.get(key)
|
|
88
|
+
&& (before.digests.has(key) || after.digests.has(key));
|
|
89
|
+
if (lineChanged || digestChanged)
|
|
90
|
+
paths.push(key);
|
|
91
|
+
}
|
|
92
|
+
return paths;
|
|
93
|
+
}
|
|
94
|
+
/** Committed path names between two HEADs; renames contribute both sides. Throws if git diff fails while HEADs differ. */
|
|
95
|
+
export function committedNames(cwd, fromHead, toHead) {
|
|
96
|
+
if (!fromHead || !toHead || fromHead === toHead)
|
|
97
|
+
return [];
|
|
98
|
+
const result = spawnSync("git", ["diff", "--name-status", "-M", `${fromHead}..${toHead}`], { cwd, encoding: "utf8", timeout: 10_000 });
|
|
99
|
+
if (result.error || result.status !== 0) {
|
|
100
|
+
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}`}`);
|
|
102
|
+
}
|
|
103
|
+
const paths = new Set();
|
|
104
|
+
for (const line of (result.stdout || "").split("\n")) {
|
|
105
|
+
if (!line.trim())
|
|
106
|
+
continue;
|
|
107
|
+
const parts = line.split("\t");
|
|
108
|
+
const status = parts[0] ?? "";
|
|
109
|
+
if (status.startsWith("R") || status.startsWith("C")) {
|
|
110
|
+
if (parts[1])
|
|
111
|
+
paths.add(parts[1]);
|
|
112
|
+
if (parts[2])
|
|
113
|
+
paths.add(parts[2]);
|
|
114
|
+
}
|
|
115
|
+
else if (parts[1]) {
|
|
116
|
+
paths.add(parts[1]);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return [...paths];
|
|
120
|
+
}
|
|
121
|
+
/** Task-level net change: commits since baseline HEAD ∪ working-tree digest/porcelain diff. */
|
|
122
|
+
export function pathsSinceBaseline(cwd, baseline, current) {
|
|
123
|
+
const set = new Set();
|
|
124
|
+
if (baseline.head && current.head) {
|
|
125
|
+
for (const p of committedNames(cwd, baseline.head, current.head))
|
|
126
|
+
set.add(p);
|
|
127
|
+
}
|
|
128
|
+
for (const p of workingTreeChanged(baseline, current))
|
|
129
|
+
set.add(p);
|
|
130
|
+
return [...set];
|
|
131
|
+
}
|
|
132
|
+
function untrackedInsertions(cwd, filePath) {
|
|
133
|
+
try {
|
|
134
|
+
const text = fs.readFileSync(path.join(cwd, filePath), "utf8");
|
|
135
|
+
if (!text)
|
|
136
|
+
return 0;
|
|
137
|
+
const lines = text.split("\n");
|
|
138
|
+
return text.endsWith("\n") ? Math.max(lines.length - 1, 0) : lines.length;
|
|
139
|
+
}
|
|
140
|
+
catch {
|
|
141
|
+
return 0;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
export function gitChanges(cwd, beforeRaw, afterRaw) {
|
|
145
|
+
const before = normalizeSnapshot(beforeRaw);
|
|
146
|
+
const after = normalizeSnapshot(afterRaw);
|
|
147
|
+
if (!before || !after)
|
|
148
|
+
return undefined;
|
|
149
|
+
const paths = workingTreeChanged(before, after);
|
|
150
|
+
if (paths.length === 0) {
|
|
151
|
+
return { files_changed: 0, insertions: 0, deletions: 0, diff_stat: "" };
|
|
152
|
+
}
|
|
153
|
+
const root = gitRepoRoot(cwd) ?? cwd;
|
|
154
|
+
const untracked = [];
|
|
155
|
+
const tracked = [];
|
|
156
|
+
for (const filePath of paths) {
|
|
157
|
+
const afterLine = after.porcelain.get(filePath);
|
|
158
|
+
const beforeLine = before.porcelain.get(filePath);
|
|
159
|
+
if (afterLine?.startsWith("??") || (!afterLine && beforeLine?.startsWith("??"))) {
|
|
160
|
+
untracked.push(filePath);
|
|
161
|
+
}
|
|
162
|
+
else {
|
|
163
|
+
tracked.push(filePath);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
let diffStat = "";
|
|
167
|
+
let insertions = 0;
|
|
168
|
+
let deletions = 0;
|
|
169
|
+
if (tracked.length) {
|
|
170
|
+
// shortcut: 超过 50 个路径就不再逐个点名,升级时改成 --raw 再过滤。
|
|
171
|
+
const result = spawnSync("git", ["diff", "--stat", "--", ...tracked.slice(0, 50)], {
|
|
172
|
+
cwd: root,
|
|
173
|
+
encoding: "utf8",
|
|
174
|
+
timeout: 5000,
|
|
175
|
+
});
|
|
176
|
+
diffStat = (result.stdout || "").trim();
|
|
177
|
+
insertions = Number(diffStat.match(/(\d+) insertion/)?.[1] || 0);
|
|
178
|
+
deletions = Number(diffStat.match(/(\d+) deletion/)?.[1] || 0);
|
|
179
|
+
}
|
|
180
|
+
if (untracked.length) {
|
|
181
|
+
const extras = [];
|
|
182
|
+
for (const filePath of untracked) {
|
|
183
|
+
if (after.porcelain.has(filePath)) {
|
|
184
|
+
const added = untrackedInsertions(root, filePath);
|
|
185
|
+
insertions += added;
|
|
186
|
+
extras.push(`${filePath} | untracked +${added}`);
|
|
187
|
+
}
|
|
188
|
+
else {
|
|
189
|
+
extras.push(`${filePath} | untracked deleted`);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
const extra = extras.join("\n");
|
|
193
|
+
diffStat = diffStat ? `${diffStat}\n${extra}` : extra;
|
|
194
|
+
}
|
|
195
|
+
return {
|
|
196
|
+
files_changed: paths.length,
|
|
197
|
+
insertions,
|
|
198
|
+
deletions,
|
|
199
|
+
diff_stat: diffStat,
|
|
200
|
+
};
|
|
201
|
+
}
|