@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.
@@ -0,0 +1,231 @@
1
+ import { spawn } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { which } from "./adapters/common.js";
5
+ import { batonHome } from "./store.js";
6
+ export const REPO = "https://github.com/SpeculoAI/baton";
7
+ const PLUGIN_ID = "baton@speculoai";
8
+ const OLD_ID = "baton@agent-plugin-agent";
9
+ const OLD_MARKET = "agent-plugin-agent";
10
+ export const HOSTS = [
11
+ {
12
+ id: "claude",
13
+ label: "Claude Code",
14
+ bins: ["claude"],
15
+ migrate: [
16
+ { args: ["plugin", "uninstall", OLD_ID], soft: true },
17
+ { args: ["plugin", "marketplace", "remove", OLD_MARKET], soft: true },
18
+ ],
19
+ install: [
20
+ { args: ["plugin", "marketplace", "add", REPO], soft: true },
21
+ { args: ["plugin", "install", PLUGIN_ID] },
22
+ ],
23
+ update: [
24
+ { args: ["plugin", "marketplace", "update", "speculoai"] },
25
+ { args: ["plugin", "update", PLUGIN_ID] },
26
+ ],
27
+ uninstall: [{ args: ["plugin", "uninstall", PLUGIN_ID] }],
28
+ },
29
+ {
30
+ id: "codex",
31
+ label: "Codex CLI",
32
+ bins: ["codex"],
33
+ migrate: [
34
+ { args: ["plugin", "remove", OLD_ID], soft: true },
35
+ { args: ["plugin", "marketplace", "remove", OLD_MARKET], soft: true },
36
+ ],
37
+ install: [
38
+ { args: ["plugin", "marketplace", "add", REPO], soft: true },
39
+ { args: ["plugin", "add", PLUGIN_ID] },
40
+ ],
41
+ update: [
42
+ { args: ["plugin", "marketplace", "upgrade", "speculoai"] },
43
+ { args: ["plugin", "add", PLUGIN_ID] },
44
+ ],
45
+ uninstall: [{ args: ["plugin", "remove", PLUGIN_ID] }],
46
+ },
47
+ {
48
+ id: "cursor",
49
+ label: "Cursor Agent CLI",
50
+ bins: ["agent", "cursor-agent"],
51
+ note: "在 Cursor 对话里执行 /add-plugin baton",
52
+ migrate: [{ args: ["plugin", "marketplace", "remove", OLD_MARKET], soft: true }],
53
+ install: [{ args: ["plugin", "marketplace", "add", REPO] }],
54
+ update: [{ args: ["plugin", "marketplace", "update", "speculoai"] }],
55
+ uninstall: [{ args: ["plugin", "marketplace", "remove", "speculoai"] }],
56
+ },
57
+ {
58
+ id: "agy",
59
+ label: "Antigravity",
60
+ bins: ["agy"],
61
+ install: [{ args: ["plugin", "install", REPO] }],
62
+ update: [{ args: ["plugin", "install", REPO] }],
63
+ uninstall: [{ args: ["plugin", "uninstall", "baton"] }],
64
+ },
65
+ {
66
+ id: "gemini",
67
+ label: "Gemini CLI",
68
+ bins: ["gemini"],
69
+ install: [{ args: ["extensions", "install", REPO, "--consent"] }],
70
+ update: [{ args: ["extensions", "update", "baton"] }],
71
+ uninstall: [{ args: ["extensions", "uninstall", "baton"] }],
72
+ },
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;
91
+ }
92
+ export function commandsFor(id, action, opts = {}) {
93
+ const host = HOSTS.find((item) => item.id === id);
94
+ if (!host)
95
+ throw new Error(`未知的 agent:${id}`);
96
+ if (action !== "install")
97
+ return host[action];
98
+ const forced = opts.force ? host.uninstall.map((step) => ({ ...step, soft: true })) : [];
99
+ return [...(host.migrate ?? []), ...forced, ...host.install];
100
+ }
101
+ export function planInstall(input) {
102
+ const env = input.env ?? process.env;
103
+ const known = new Set(HOSTS.map((host) => host.id));
104
+ for (const id of input.only ?? [])
105
+ if (!known.has(id))
106
+ throw new Error(`未知的 agent:${id}`);
107
+ const ids = input.only?.length
108
+ ? input.only
109
+ : input.action === "install"
110
+ ? HOSTS.filter((host) => which(host.bins, env)).map((host) => host.id)
111
+ : input.recorded ?? readInstalled();
112
+ const hosts = [];
113
+ const missing = [];
114
+ for (const id of ids) {
115
+ const host = HOSTS.find((item) => item.id === id);
116
+ if (!host)
117
+ throw new Error(`未知的 agent:${id}`);
118
+ const bin = which(host.bins, env);
119
+ if (!bin) {
120
+ if (input.only?.length)
121
+ throw new Error(`未检测到 ${id}。`);
122
+ missing.push(id);
123
+ continue;
124
+ }
125
+ hosts.push({
126
+ id,
127
+ bin,
128
+ commands: commandsFor(id, input.action, { force: input.force }).map((step) => step.args),
129
+ ...(host.note && input.action === "install" ? { note: host.note } : {}),
130
+ });
131
+ }
132
+ if (input.action === "uninstall" || input.skipGlobal)
133
+ return { hosts, missing };
134
+ const version = JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
135
+ const spec = input.action === "update" ? "@speculoai/baton@latest" : `@speculoai/baton@${version}`;
136
+ return { hosts, missing, global: { command: [process.platform === "win32" ? "npm.cmd" : "npm", "install", "-g", spec] } };
137
+ }
138
+ export function readInstalled(home = batonHome()) {
139
+ try {
140
+ const data = JSON.parse(fs.readFileSync(path.join(home, "installed.json"), "utf8"));
141
+ return Array.isArray(data.hosts) ? data.hosts.filter((id) => typeof id === "string") : [];
142
+ }
143
+ catch {
144
+ return [];
145
+ }
146
+ }
147
+ export function writeInstalled(ids, home = batonHome()) {
148
+ fs.mkdirSync(home, { recursive: true });
149
+ fs.writeFileSync(path.join(home, "installed.json"), `${JSON.stringify({ hosts: [...new Set(ids)] })}\n`);
150
+ }
151
+ function defaultSpawn(command, args, env) {
152
+ return new Promise((resolve) => {
153
+ const child = spawn(command, args, { env, stdio: ["inherit", "pipe", "pipe"] });
154
+ let stdout = "";
155
+ let stderr = "";
156
+ let settled = false;
157
+ const finish = (result) => { if (!settled) {
158
+ settled = true;
159
+ resolve(result);
160
+ } };
161
+ child.stdout?.on("data", (chunk) => { stdout += chunk; process.stderr.write(chunk); });
162
+ child.stderr?.on("data", (chunk) => { stderr += chunk; process.stderr.write(chunk); });
163
+ child.on("error", (error) => finish({ status: 1, stderr: error.message }));
164
+ child.on("close", (status) => finish({ status, stdout, stderr }));
165
+ });
166
+ }
167
+ function failText(ran) {
168
+ return `${ran.stderr || ran.stdout || ""}`.trim().slice(-500) || `退出码 ${ran.status}`;
169
+ }
170
+ export async function runInstall(input) {
171
+ const env = input.env ?? process.env;
172
+ const home = input.home ?? batonHome();
173
+ let only = input.only;
174
+ if (input.action === "install" && !only?.length && input.tty) {
175
+ const detected = HOSTS.filter((host) => which(host.bins, env));
176
+ if (!detected.length)
177
+ 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)
181
+ return { exitCode: 0, result: { action: input.action, hosts: [] } };
182
+ only = picked.map((index) => detected[index].id);
183
+ }
184
+ const planned = planInstall({ action: input.action, only, force: input.force, skipGlobal: input.skipGlobal, env, recorded: readInstalled(home) });
185
+ if (input.dryRun) {
186
+ return {
187
+ exitCode: 0,
188
+ result: { action: input.action, dry_run: true, ...(planned.global ? { global: planned.global } : {}), hosts: planned.hosts, ...(planned.missing.length ? { missing: planned.missing } : {}) },
189
+ };
190
+ }
191
+ const spawn = input.spawn ?? ((command, args) => defaultSpawn(command, args, env));
192
+ let global;
193
+ if (planned.global) {
194
+ const ran = await spawn(planned.global.command[0], planned.global.command.slice(1));
195
+ global = ran.status === 0 ? { ok: true } : { ok: false, error: failText(ran) };
196
+ }
197
+ const hosts = [];
198
+ for (const host of planned.hosts) {
199
+ let error;
200
+ let skipped = false;
201
+ for (const step of commandsFor(host.id, input.action, { force: input.force })) {
202
+ const ran = await spawn(host.bin, step.args);
203
+ if (ran.status === 0 || step.soft)
204
+ continue;
205
+ if (/already installed/i.test(`${ran.stdout || ""}\n${ran.stderr || ""}`)) {
206
+ skipped = true;
207
+ continue;
208
+ }
209
+ error = failText(ran);
210
+ break;
211
+ }
212
+ const note = skipped ? "已安装,跳过" : host.note;
213
+ hosts.push({ id: host.id, ok: !error, ...(note ? { note } : {}), ...(error ? { error } : {}) });
214
+ }
215
+ if (input.action !== "update") {
216
+ const recorded = new Set(readInstalled(home));
217
+ for (const host of hosts) {
218
+ if (!host.ok)
219
+ continue;
220
+ if (input.action === "install")
221
+ recorded.add(host.id);
222
+ else
223
+ recorded.delete(host.id);
224
+ }
225
+ writeInstalled([...recorded], home);
226
+ }
227
+ return {
228
+ exitCode: hosts.some((host) => !host.ok) ? 1 : 0,
229
+ result: { action: input.action, ...(global ? { global } : {}), hosts, ...(planned.missing.length ? { missing: planned.missing } : {}) },
230
+ };
231
+ }
package/dist/mcp.js ADDED
@@ -0,0 +1,90 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
+ import { z } from "zod";
4
+ import { agents, cancel, ls, reply, start, status, wait } from "./tasks.js";
5
+ import { redact } from "./redact.js";
6
+ const MAX_WAIT_SECONDS = 55;
7
+ const PROGRESS_MS = 15_000;
8
+ // 每个工具只转调 tasks.ts;MCP 进程里不保存任何任务状态,重启后照样能读到任务。
9
+ async function respond(run) {
10
+ let value;
11
+ try {
12
+ value = await run();
13
+ }
14
+ catch (error) {
15
+ value = { status: "failed", summary: redact(error.message) };
16
+ }
17
+ return { content: [{ type: "text", text: JSON.stringify(value) }] };
18
+ }
19
+ export function createServer() {
20
+ const server = new McpServer({ name: "baton", version: "0.3.0" });
21
+ server.registerTool("list_agents", { description: "列出本机可派工的 CLI 及是否安装。" }, () => respond(() => ({ agents: agents() })));
22
+ server.registerTool("delegate_task", {
23
+ description: "把一个有边界的任务派给本机另一个 AI CLI。立即返回 task_id(status=running),任务在独立进程里跑,不受本 MCP 进程或宿主会话退出影响。之后用 task_wait 有界等待。",
24
+ inputSchema: {
25
+ target_agent: z.enum(["codex", "claude", "cursor", "agy"]),
26
+ prompt: z.string(),
27
+ files: z.array(z.string()).optional(),
28
+ reasoning_effort: z.enum(["low", "medium", "high", "ultra"]).optional(),
29
+ model: z.string().optional().describe("按任务指定模型(当前仅 cursor;写入 meta,reply 延续)。"),
30
+ idle_timeout_seconds: z.number().optional().describe("连续这么久没有任何输出就停掉,默认 600。"),
31
+ max_duration_seconds: z.number().optional().describe("单轮总时长上限,默认不限。"),
32
+ cwd: z.string().optional(),
33
+ scope: z.array(z.string()).optional().describe("允许修改的路径 glob,可多条;任务结束后对照净变更检查。"),
34
+ scope_on_violation: z.enum(["warn", "fail"]).optional().describe("越界策略,默认 warn。"),
35
+ mode: z.enum(["readonly", "write"]).optional().describe("权限模式,默认 write;readonly 映射到各 CLI 只读参数。"),
36
+ allow_weak: z.boolean().optional().describe("仅当目标无法强制只读时,显式放行 --mode readonly。"),
37
+ },
38
+ }, (args) => respond(() => start({
39
+ target: args.target_agent, prompt: args.prompt, files: args.files, cwd: args.cwd,
40
+ reasoningEffort: args.reasoning_effort, model: args.model,
41
+ idleTimeout: args.idle_timeout_seconds, maxDuration: args.max_duration_seconds,
42
+ scope: args.scope, scopeOnViolation: args.scope_on_violation,
43
+ mode: args.mode, allowWeak: args.allow_weak,
44
+ })));
45
+ server.registerTool("task_status", {
46
+ description: "看一单当前状态。running 时带 liveness(active/quiet/orphaned)和 quiet_for_s。",
47
+ inputSchema: { task_id: z.string() },
48
+ }, (args) => respond(() => status(args.task_id)));
49
+ server.registerTool("task_wait", {
50
+ description: `有界等待:任一任务离开 running 即返回该任务;到 wait_seconds(默认 50,上限 ${MAX_WAIT_SECONDS})仍在跑就返回 running,调用方再次调用即可。`,
51
+ inputSchema: { task_ids: z.array(z.string()).min(1), wait_seconds: z.number().optional() },
52
+ }, (args, extra) => respond(async () => {
53
+ const seconds = Math.min(Math.max(args.wait_seconds ?? 50, 0), MAX_WAIT_SECONDS);
54
+ const token = extra?._meta?.progressToken;
55
+ let step = 0;
56
+ const timer = token == null ? null : setInterval(() => {
57
+ step += 1;
58
+ const quiet = args.task_ids.map((id) => { try {
59
+ return `${id.slice(0, 8)} ${status(id).quiet_for_s ?? "?"}s 无输出`;
60
+ }
61
+ catch {
62
+ return id;
63
+ } }).join("; ");
64
+ extra.sendNotification({ method: "notifications/progress", params: { progressToken: token, progress: step, message: quiet } }).catch(() => { });
65
+ }, PROGRESS_MS);
66
+ try {
67
+ return await wait(args.task_ids, seconds);
68
+ }
69
+ finally {
70
+ if (timer)
71
+ clearInterval(timer);
72
+ }
73
+ }));
74
+ server.registerTool("task_reply", {
75
+ description: "任务停在 needs_input、success、scope_violation 或 readonly_violation 后,在同一会话开下一轮。as=human 表示这是人说的话,默认 host。running 时返回 busy。",
76
+ inputSchema: { task_id: z.string(), prompt: z.string(), as: z.enum(["host", "human"]).optional() },
77
+ }, (args) => respond(() => reply(args.task_id, args.prompt, (args.as ?? "host"))));
78
+ server.registerTool("task_cancel", {
79
+ description: "停掉一单还在跑的任务(杀整个进程组)。",
80
+ inputSchema: { task_id: z.string() },
81
+ }, (args) => respond(() => cancel(args.task_id)));
82
+ server.registerTool("task_list", {
83
+ description: "列出任务,按更新时间倒序。默认只列 cwd(或 BATON_CWD)下的任务,all=true 列全部。",
84
+ inputSchema: { all: z.boolean().optional(), cwd: z.string().optional() },
85
+ }, (args) => respond(() => ({ tasks: ls(args.all ?? false, args.cwd ?? process.env.BATON_CWD ?? process.cwd()) })));
86
+ return server;
87
+ }
88
+ export async function startMcp() {
89
+ await createServer().connect(new StdioServerTransport());
90
+ }
@@ -0,0 +1,23 @@
1
+ export function isAlive(pid) {
2
+ if (!pid || !Number.isSafeInteger(pid) || pid <= 1)
3
+ return false;
4
+ // shortcut: PID 复用可能误判,需要更严格身份校验时加入进程启动时间。
5
+ try {
6
+ process.kill(pid, 0);
7
+ return true;
8
+ }
9
+ catch (error) {
10
+ return error.code === "EPERM";
11
+ }
12
+ }
13
+ export function killGroup(pid) {
14
+ if (!pid || !Number.isSafeInteger(pid) || pid <= 1)
15
+ return;
16
+ try {
17
+ process.kill(-pid, "SIGKILL");
18
+ }
19
+ catch (error) {
20
+ if (error.code !== "ESRCH")
21
+ throw error;
22
+ }
23
+ }
package/dist/redact.js ADDED
@@ -0,0 +1,9 @@
1
+ export function redact(text) {
2
+ let safe = text;
3
+ for (const [key, value] of Object.entries(process.env)) {
4
+ if (/TOKEN|SECRET|PASSWORD|API_KEY|CREDENTIAL/i.test(key) && value && value.length >= 4)
5
+ safe = safe.split(value).join("[REDACTED]");
6
+ }
7
+ return safe.replace(/(Bearer\s+)[\w.\-]+/gi, "$1[REDACTED]")
8
+ .replace(/((?:api[_-]?key|token|secret|password)["']?\s*[=:]\s*["']?)[^\s"',;}]+/gi, "$1[REDACTED]");
9
+ }
package/dist/scope.js ADDED
@@ -0,0 +1,108 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ const HAS_WILDCARD = /[*?[\]]/;
4
+ export function validateScopeGlob(glob) {
5
+ if (!glob || !glob.trim())
6
+ throw new Error("scope 不能为空。");
7
+ if (glob.trimStart().startsWith("!"))
8
+ throw new Error("scope 不支持 ! 否定模式。");
9
+ }
10
+ /** Normalize CLI/MCP scope list; throws if policy set without scopes. */
11
+ export function normalizeScopeInput(scopes, policy) {
12
+ const cleaned = (scopes ?? []).map((s) => s.trim()).filter(Boolean);
13
+ if (policy && !cleaned.length)
14
+ throw new Error("未指定 --scope 时不能使用 --scope-on-violation。");
15
+ if (!cleaned.length)
16
+ return {};
17
+ for (const g of cleaned)
18
+ validateScopeGlob(g);
19
+ const scope_on_violation = policy ?? "warn";
20
+ if (scope_on_violation !== "warn" && scope_on_violation !== "fail") {
21
+ throw new Error("scope-on-violation 必须是 warn 或 fail。");
22
+ }
23
+ return { scope: cleaned, scope_on_violation };
24
+ }
25
+ export function scopePromptPrefix(scopes) {
26
+ return `[Baton scope] Only modify these paths (post-check enforced): ${scopes.join(", ")}\n\n`;
27
+ }
28
+ function normalizeRel(p) {
29
+ return p.replace(/\\/g, "/").replace(/^\.\//, "");
30
+ }
31
+ function hasWildcard(glob) {
32
+ return HAS_WILDCARD.test(glob);
33
+ }
34
+ export function pathInScope(filePath, globs, opts = {}) {
35
+ const file = normalizeRel(filePath);
36
+ if (file.startsWith("../") || file === "..")
37
+ return false;
38
+ for (const raw of globs) {
39
+ const glob = normalizeRel(raw);
40
+ if (!glob)
41
+ continue;
42
+ if (hasWildcard(glob)) {
43
+ if (path.matchesGlob(file, glob))
44
+ return true;
45
+ continue;
46
+ }
47
+ if (file === glob)
48
+ return true;
49
+ const isDir = opts.isDir?.(glob) ?? false;
50
+ if (isDir && (file === glob || file.startsWith(`${glob}/`)))
51
+ return true;
52
+ }
53
+ return false;
54
+ }
55
+ export function findScopeViolations(paths, globs, opts = {}) {
56
+ const out = [];
57
+ for (const p of paths) {
58
+ const file = normalizeRel(p);
59
+ if (file.startsWith("../") || file === ".." || !pathInScope(file, globs, opts)) {
60
+ out.push(file);
61
+ }
62
+ }
63
+ return out;
64
+ }
65
+ /** Map repo-root-relative git paths into task-cwd-relative paths; cwd escapes → `../…`. */
66
+ export function relativizeToTaskCwd(repoRelativePaths, repoRoot, cwd) {
67
+ const root = path.resolve(repoRoot);
68
+ const base = path.resolve(cwd);
69
+ return repoRelativePaths.map((rel) => {
70
+ const abs = path.resolve(root, rel);
71
+ return normalizeRel(path.relative(base, abs));
72
+ });
73
+ }
74
+ export function isDirUnderCwd(cwd, pattern) {
75
+ try {
76
+ return fs.statSync(path.resolve(cwd, pattern)).isDirectory();
77
+ }
78
+ catch {
79
+ return false;
80
+ }
81
+ }
82
+ /** Apply warn/fail after transport final status is known. */
83
+ export function applyScopePolicy(input) {
84
+ const violations = [...input.violations];
85
+ if (!violations.length) {
86
+ return {
87
+ status: input.final,
88
+ summary: input.summary,
89
+ warning: input.warning,
90
+ scope_violations: [],
91
+ };
92
+ }
93
+ const note = `scope_violation: ${violations.length} file(s)`;
94
+ const warning = input.warning ? `${input.warning}; ${note}` : note;
95
+ if (input.policy === "fail" && input.final === "success") {
96
+ const body = input.summary ?? "";
97
+ const summary = body.startsWith("scope_violation:")
98
+ ? body
99
+ : `scope_violation: 见 scope_violations${body ? `\n${body}` : ""}`;
100
+ return { status: "scope_violation", summary, warning, scope_violations: violations };
101
+ }
102
+ return {
103
+ status: input.final,
104
+ summary: input.summary,
105
+ warning,
106
+ scope_violations: violations,
107
+ };
108
+ }
package/dist/store.js ADDED
@@ -0,0 +1,105 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { randomUUID } from "node:crypto";
5
+ import { redact } from "./redact.js";
6
+ import { isAlive } from "./process.js";
7
+ export function batonHome() {
8
+ return path.resolve(process.env.BATON_HOME || path.join(os.homedir(), ".baton"));
9
+ }
10
+ export function taskDir(id) {
11
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id))
12
+ throw new Error("task_id 必须为 UUID。");
13
+ return path.join(batonHome(), "tasks", id);
14
+ }
15
+ export function ensureTask(id) {
16
+ const dir = taskDir(id);
17
+ for (const name of [batonHome(), path.dirname(dir), dir, path.join(dir, "turns"), path.join(dir, "raw")]) {
18
+ fs.mkdirSync(name, { recursive: true, mode: 0o700 });
19
+ fs.chmodSync(name, 0o700);
20
+ }
21
+ return dir;
22
+ }
23
+ function writeJson(file, value) {
24
+ const tmp = `${file}.${randomUUID()}.tmp`;
25
+ try {
26
+ fs.writeFileSync(tmp, JSON.stringify(value), { mode: 0o600, flag: "wx" });
27
+ fs.renameSync(tmp, file);
28
+ }
29
+ finally {
30
+ fs.rmSync(tmp, { force: true });
31
+ }
32
+ }
33
+ export function writeMeta(meta) {
34
+ writeJson(path.join(ensureTask(meta.task_id), "meta.json"), meta);
35
+ }
36
+ export function readMeta(id) {
37
+ const dir = taskDir(id);
38
+ try {
39
+ return JSON.parse(fs.readFileSync(path.join(dir, "meta.json"), "utf8"));
40
+ }
41
+ catch {
42
+ return null;
43
+ }
44
+ }
45
+ export function appendEvent(id, event) {
46
+ const safe = Object.fromEntries(Object.entries(event).map(([key, value]) => [key, typeof value === "string" ? redact(value) : value]));
47
+ fs.appendFileSync(path.join(ensureTask(id), "events.jsonl"), `${JSON.stringify(safe)}\n`, { mode: 0o600 });
48
+ }
49
+ export function writeTurn(id, turn) {
50
+ if (!Number.isSafeInteger(turn.turn) || turn.turn < 1)
51
+ throw new Error("轮次必须为正整数。");
52
+ writeJson(path.join(ensureTask(id), "turns", `${turn.turn}.json`), turn);
53
+ }
54
+ export function readTurn(id, turn) {
55
+ return JSON.parse(fs.readFileSync(path.join(taskDir(id), "turns", `${turn}.json`), "utf8"));
56
+ }
57
+ export function listTasks() {
58
+ let names;
59
+ try {
60
+ names = fs.readdirSync(path.join(batonHome(), "tasks"));
61
+ }
62
+ catch (error) {
63
+ if (error.code === "ENOENT")
64
+ return [];
65
+ throw error;
66
+ }
67
+ return names.filter((name) => /^[0-9a-f-]{36}$/i.test(name)).flatMap((name) => {
68
+ try {
69
+ return readMeta(name) ?? [];
70
+ }
71
+ catch {
72
+ return [];
73
+ }
74
+ });
75
+ }
76
+ export function lockTask(id) {
77
+ const file = path.join(taskDir(id), ".control.lock");
78
+ const temp = `${file}.${randomUUID()}.tmp`;
79
+ fs.writeFileSync(temp, String(process.pid), { mode: 0o600, flag: "wx" });
80
+ try {
81
+ for (let attempt = 0; attempt < 2; attempt++) {
82
+ try {
83
+ fs.linkSync(temp, file);
84
+ return () => fs.rmSync(file, { force: true });
85
+ }
86
+ catch (error) {
87
+ if (error.code !== "EEXIST")
88
+ throw error;
89
+ try {
90
+ if (isAlive(Number(fs.readFileSync(file, "utf8"))))
91
+ return null;
92
+ fs.rmSync(file, { force: true });
93
+ }
94
+ catch (readError) {
95
+ if (readError.code !== "ENOENT")
96
+ throw readError;
97
+ }
98
+ }
99
+ }
100
+ return null;
101
+ }
102
+ finally {
103
+ fs.rmSync(temp, { force: true });
104
+ }
105
+ }