@speculoai/baton 0.6.0 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -109,6 +109,7 @@ If no target is named, the task goes to `codex`, or to `claude` when you are alr
109
109
  |---|---|
110
110
  | `baton start` | Starts a job. Options include `--effort`, `--mode readonly`, `--scope <glob>`, `--rules check\|pointer\|off`, and `--cwd <worktree>`. |
111
111
  | `baton wait` / `status` | Waits for the job to stop, or takes one look at it. |
112
+ | `baton result` | Prints the worker's full final answer, without the transcript. |
112
113
  | `baton tail [-f]` | Shows the live event stream as readable text. |
113
114
  | `baton reply` | Continues the same conversation when the worker asks a question or you want a follow-up. |
114
115
  | `baton cancel` / `ls` / `prune` | Stops a job, lists jobs, or deletes old ones. |
package/README.zh-CN.md CHANGED
@@ -109,6 +109,7 @@ baton tail -f <task_id>
109
109
  |---|---|
110
110
  | `baton start` | 启动任务。可选参数包括 `--effort`、`--mode readonly`、`--scope <glob>`、`--rules check\|pointer\|off`、`--cwd <worktree>`。 |
111
111
  | `baton wait` / `status` | 等任务停下,或者看一眼当前状态。 |
112
+ | `baton result` | 只打印 worker 的完整最终回答,不含过程记录。 |
112
113
  | `baton tail [-f]` | 以可读文本显示实时事件流。 |
113
114
  | `baton reply` | 执行者提问、或者你想追加要求时,在同一个会话里接着说。 |
114
115
  | `baton cancel` / `ls` / `prune` | 停止任务、列出任务、清理旧任务。 |
@@ -18,9 +18,14 @@ export const codex = {
18
18
  resolve(env) {
19
19
  return which(["codex"], env);
20
20
  },
21
- build({ bin, cwd, prompt, sessionId, reasoningEffort, mode }) {
21
+ build({ bin, cwd, prompt, sessionId, reasoningEffort, model, mode }) {
22
22
  const lastMessagePath = path.join(os.tmpdir(), `baton-codex-${process.pid}-${Date.now()}.txt`);
23
- const effortArgs = reasoningEffort ? ["-c", `model_reasoning_effort="${reasoningEffort}"`] : [];
23
+ // `-m` is accepted by both `exec` and `exec resume` (codex-cli 0.171.0).
24
+ const modelArg = model?.trim() || undefined;
25
+ const optionArgs = [
26
+ ...(modelArg ? ["-m", modelArg] : []),
27
+ ...(reasoningEffort ? ["-c", `model_reasoning_effort="${reasoningEffort}"`] : []),
28
+ ];
24
29
  const readonly = mode === "readonly";
25
30
  // `exec resume` does not accept --cd/--color/--sandbox. The first write turn uses --approve-for-me (workspace-write; do not add --sandbox).
26
31
  if (sessionId) {
@@ -33,12 +38,13 @@ export const codex = {
33
38
  "--skip-git-repo-check",
34
39
  "--output-last-message",
35
40
  lastMessagePath,
36
- ...effortArgs,
41
+ ...optionArgs,
37
42
  sessionId,
38
43
  "-",
39
44
  ],
40
45
  stdin: prompt,
41
46
  lastMessagePath,
47
+ modelArg,
42
48
  };
43
49
  }
44
50
  return {
@@ -54,11 +60,12 @@ export const codex = {
54
60
  cwd,
55
61
  "--output-last-message",
56
62
  lastMessagePath,
57
- ...effortArgs,
63
+ ...optionArgs,
58
64
  "-",
59
65
  ],
60
66
  stdin: prompt,
61
67
  lastMessagePath,
68
+ modelArg,
62
69
  };
63
70
  },
64
71
  sessionIdFrom(line) {
@@ -1,7 +1,6 @@
1
1
  import { redact } from "../redact.js";
2
2
  import { authHit, which } from "./common.js";
3
3
  const AUTH = ["not authenticated", "please log in", "agent login"];
4
- const EMBEDDED_EFFORT = /-(low|medium|high|xhigh|ultra|max)(-fast)?$/i;
5
4
  function event(data) {
6
5
  return [{ ts: new Date().toISOString(), turn: 0, ...data }];
7
6
  }
@@ -13,22 +12,16 @@ function parse(line) {
13
12
  return null;
14
13
  }
15
14
  }
16
- /** Build the Cursor `--model` value. Never emits two competing model args. */
15
+ /**
16
+ * Build the Cursor `--model` value.
17
+ * Verified 2026-11-23 (cursor-agent 2026.11.22): any `<id>[effort=…]` form is rejected ("Cannot use this model");
18
+ * the tier lives in the model id itself (e.g. gpt-5.3-codex-high), so `--effort` cannot be mapped.
19
+ */
17
20
  export function resolveCursorModelArg(model, effort) {
21
+ if (effort)
22
+ throw new Error("cursor does not support --effort; pick a model id that embeds the tier (see `cursor-agent --list-models`), e.g. --model gpt-5.3-codex-high.");
18
23
  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;
24
+ return id || null;
32
25
  }
33
26
  export const cursor = {
34
27
  id: "cursor",
package/dist/cli.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import fs from "node:fs";
3
3
  import { parseArgs } from "node:util";
4
- import { agents, start, status, cancel, wait, reply, ls, prune } from "./tasks.js";
4
+ import { agents, start, status, cancel, wait, reply, ls, prune, result as turnResult } from "./tasks.js";
5
5
  import { addWorktree, listWorktrees, removeWorktree } from "./worktree.js";
6
6
  import { redact } from "./redact.js";
7
7
  import { detectedHosts, runInstall } from "./install.js";
@@ -77,6 +77,14 @@ async function main() {
77
77
  throw new Error("--until-done and --for cannot be used together.");
78
78
  result = await wait(positionals, values["until-done"] ? Infinity : values.for === undefined ? 50 : Number(values.for));
79
79
  }
80
+ else if (command === "result") {
81
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { turn: { type: "string" } } });
82
+ if (positionals.length !== 1)
83
+ throw new Error("result requires one task_id.");
84
+ // Plain text, like tail: the point is to read the answer without JSON escaping or the full transcript.
85
+ process.stdout.write(`${turnResult(positionals[0], values.turn === undefined ? undefined : Number(values.turn)).final_message}\n`);
86
+ return;
87
+ }
80
88
  else if (command === "tail") {
81
89
  const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { follow: { type: "boolean", short: "f" }, raw: { type: "boolean" } } });
82
90
  if (positionals.length !== 1)
@@ -289,7 +297,7 @@ async function main() {
289
297
  return;
290
298
  }
291
299
  else
292
- throw new Error("Usage: baton version | agents | start | status | cancel | wait | tail | reply | ls | prune | worktree | rules | install | update | uninstall | mcp");
300
+ throw new Error("Usage: baton version | agents | start | status | cancel | wait | result | tail | reply | ls | prune | worktree | rules | install | update | uninstall | mcp");
293
301
  process.stdout.write(`${JSON.stringify(result)}\n`);
294
302
  }
295
303
  try {
package/dist/mcp.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
2
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
3
  import { z } from "zod";
4
- import { agents, cancel, ls, reply, start, status, wait } from "./tasks.js";
4
+ import { agents, cancel, ls, reply, result, start, status, wait } from "./tasks.js";
5
5
  import { redact } from "./redact.js";
6
6
  const MAX_WAIT_SECONDS = 55;
7
7
  const PROGRESS_MS = 15_000;
@@ -26,7 +26,7 @@ export function createServer() {
26
26
  prompt: z.string(),
27
27
  files: z.array(z.string()).optional(),
28
28
  reasoning_effort: z.enum(["low", "medium", "high", "ultra"]).optional(),
29
- model: z.string().optional().describe("Per-task model (cursor only for now; stored in meta and carried over by reply)."),
29
+ model: z.string().optional().describe("Per-task model (cursor and codex; stored in meta and carried over by reply)."),
30
30
  idle_timeout_seconds: z.number().optional().describe("Stop after this long with no output at all; default 600."),
31
31
  max_duration_seconds: z.number().optional().describe("Maximum total duration per turn; default unlimited."),
32
32
  cwd: z.string().optional(),
@@ -76,6 +76,10 @@ export function createServer() {
76
76
  clearInterval(timer);
77
77
  }
78
78
  }));
79
+ server.registerTool("task_result", {
80
+ description: "Get the agent's full final message of a finished turn (default: the latest), without the tool-call transcript. task_status/task_wait only carry the one-line summary.",
81
+ inputSchema: { task_id: z.string(), turn: z.number().int().optional() },
82
+ }, (args) => respond(() => result(args.task_id, args.turn)));
79
83
  server.registerTool("task_reply", {
80
84
  description: "After a task stops at needs_input, success, scope_violation or readonly_violation, start the next turn in the same session. as=human means a human said it; default host. Returns busy while running.",
81
85
  inputSchema: { task_id: z.string(), prompt: z.string(), as: z.enum(["host", "human"]).optional() },
package/dist/process.js CHANGED
@@ -17,7 +17,9 @@ export function killGroup(pid) {
17
17
  process.kill(-pid, "SIGKILL");
18
18
  }
19
19
  catch (error) {
20
- if (error.code !== "ESRCH")
20
+ // macOS returns EPERM for a group whose members have all exited but are not reaped yet (zombies); nothing is left to kill.
21
+ const code = error.code;
22
+ if (code !== "ESRCH" && code !== "EPERM")
21
23
  throw error;
22
24
  }
23
25
  }
package/dist/store.js CHANGED
@@ -42,6 +42,25 @@ export function readMeta(id) {
42
42
  return null;
43
43
  }
44
44
  }
45
+ export function hasTurnEnded(id, turn) {
46
+ let text;
47
+ try {
48
+ text = fs.readFileSync(path.join(taskDir(id), "events.jsonl"), "utf8");
49
+ }
50
+ catch (error) {
51
+ if (error.code === "ENOENT")
52
+ return false;
53
+ throw error;
54
+ }
55
+ for (const line of text.split("\n")) {
56
+ if (!line)
57
+ continue;
58
+ const event = JSON.parse(line);
59
+ if (event.type === "turn_ended" && event.turn === turn)
60
+ return true;
61
+ }
62
+ return false;
63
+ }
45
64
  export function appendEvent(id, event) {
46
65
  const safe = Object.fromEntries(Object.entries(event).map(([key, value]) => [key, typeof value === "string" ? redact(value) : value]));
47
66
  fs.appendFileSync(path.join(ensureTask(id), "events.jsonl"), `${JSON.stringify(safe)}\n`, { mode: 0o600 });
@@ -7,7 +7,7 @@ import { buildPrompt, interpret } from "./contract.js";
7
7
  import { baselineToSnapshot, gitChanges, gitRepoRoot, gitSnapshot, pathsSinceBaseline } from "./git.js";
8
8
  import { applyScopePolicy, findScopeViolations, isDirUnderCwd, relativizeToTaskCwd } from "./scope.js";
9
9
  import { resolveRulesync, rulesGitRoot, rulesyncCheck } from "./rules.js";
10
- import { appendEvent, readMeta, writeMeta, readTurn, writeTurn, taskDir, lockTask } from "./store.js";
10
+ import { appendEvent, hasTurnEnded, readMeta, writeMeta, readTurn, writeTurn, taskDir, lockTask } from "./store.js";
11
11
  import { redact } from "./redact.js";
12
12
  import { killGroup } from "./process.js";
13
13
  const QUOTA_PHRASES = ["usage limit", "quota exceeded", "rate limit"];
@@ -58,6 +58,12 @@ function failureSummary(stdout, stderr) {
58
58
  return (withoutHtml(stderr) || withoutHtml(stdout)).slice(-8192);
59
59
  }
60
60
  export async function supervise(id) {
61
+ // Test hook: simulate a slow ("<ms>") or crashing ("exit") supervisor start.
62
+ const hook = process.env.BATON_TEST_SUPERVISE_START;
63
+ if (hook === "exit")
64
+ process.exit(1);
65
+ if (hook)
66
+ await new Promise((resolve) => setTimeout(resolve, Number(hook)));
61
67
  const release = lockTask(id);
62
68
  if (!release)
63
69
  return;
@@ -69,9 +75,18 @@ export async function supervise(id) {
69
75
  let childPid = null;
70
76
  let stopped = null;
71
77
  const stop = (reason) => {
72
- if (!stopped)
78
+ if (!stopped) {
73
79
  stopped = reason;
74
- killGroup(childPid);
80
+ meta.stop_reason = reason;
81
+ meta.updated_at = new Date().toISOString();
82
+ writeMeta(meta);
83
+ }
84
+ try {
85
+ killGroup(childPid);
86
+ }
87
+ catch { /* 决定已落盘;杀进程失败留待孤儿收尾 */ }
88
+ if (process.env.BATON_CRASH_AFTER_STOP_PERSIST === "1")
89
+ process.exit(1);
75
90
  };
76
91
  const cancel = () => stop("cancelled");
77
92
  process.on("SIGTERM", cancel);
@@ -312,9 +327,15 @@ export async function supervise(id) {
312
327
  }
313
328
  }
314
329
  }
330
+ delete meta.stop_reason;
315
331
  turn.status = final;
316
332
  turn.summary = meta.summary;
333
+ if (message.trim())
334
+ turn.final_message = redact(message.trim());
317
335
  writeTurn(id, turn);
318
- emit({ type: "turn_ended", status: final, exit_code: code });
336
+ if (hasTurnEnded(id, meta.turn))
337
+ save();
338
+ else
339
+ emit({ type: "turn_ended", status: final, exit_code: code });
319
340
  process.off("SIGTERM", cancel);
320
341
  }
package/dist/tasks.js CHANGED
@@ -5,7 +5,7 @@ import { spawn, spawnSync } from "node:child_process";
5
5
  import { once } from "node:events";
6
6
  import { adapters, getAdapter } from "./adapters/index.js";
7
7
  import { resolveCursorModelArg } from "./adapters/cursor.js";
8
- import { readMeta, writeMeta, writeTurn, readTurn, appendEvent, taskDir, lockTask, listTasks } from "./store.js";
8
+ import { readMeta, writeMeta, writeTurn, readTurn, appendEvent, hasTurnEnded, taskDir, lockTask, listTasks } from "./store.js";
9
9
  import { setTimeout as sleep } from "node:timers/promises";
10
10
  import { redact } from "./redact.js";
11
11
  import { isAlive, killGroup } from "./process.js";
@@ -44,19 +44,28 @@ function positive(value, name) {
44
44
  throw new Error(`${name} must be a positive number.`);
45
45
  return value;
46
46
  }
47
+ // Node boot + module load takes ~150ms idle but >1s on a busy machine; a slow start is not a failure.
48
+ // Stay under the 30s no-supervisor orphan window in orphaned().
49
+ const SUPERVISOR_READY_MS = 15_000;
47
50
  async function launch(id) {
48
51
  const child = spawn(process.execPath, [path.join(import.meta.dirname, `cli${path.extname(import.meta.filename)}`), "_supervise", id], { detached: true, stdio: "ignore", env: process.env });
49
52
  await once(child, "spawn");
53
+ let exited = false;
54
+ child.once("exit", () => { exited = true; });
50
55
  child.unref();
51
- const deadline = Date.now() + 750;
52
- while (Date.now() < deadline) {
53
- if (readMeta(id)?.supervisor_pid === child.pid)
56
+ // supervisor_pid is never cleared, so a supervisor that claimed the task and already finished still counts as ready.
57
+ const ready = () => readMeta(id)?.supervisor_pid === child.pid;
58
+ const deadline = Date.now() + SUPERVISOR_READY_MS;
59
+ while (!exited && Date.now() < deadline) {
60
+ if (ready())
54
61
  return;
55
62
  await sleep(10);
56
63
  }
64
+ if (ready())
65
+ return;
57
66
  child.kill("SIGKILL");
58
67
  killGroup(readMeta(id)?.child_pid ?? null);
59
- throw new Error("supervisor not ready.");
68
+ throw new Error(exited ? "supervisor exited before it was ready." : "supervisor not ready.");
60
69
  }
61
70
  export async function start(input) {
62
71
  if (process.env.BATON_DELEGATION === "1")
@@ -71,9 +80,9 @@ export async function start(input) {
71
80
  if (input.reasoningEffort && !["low", "medium", "high", "ultra"].includes(input.reasoningEffort))
72
81
  throw new Error("Unknown effort.");
73
82
  const model = input.model?.trim() || undefined;
74
- if (model && adapter.id !== "cursor")
75
- throw new Error(`${adapter.id} does not support --model yet (cursor only).`);
76
- let model_argv;
83
+ if (model && adapter.id !== "cursor" && adapter.id !== "codex")
84
+ throw new Error(`${adapter.id} does not support --model yet (cursor and codex only).`);
85
+ let model_argv = adapter.id === "codex" ? model : undefined;
77
86
  if (adapter.id === "cursor") {
78
87
  const resolved = resolveCursorModelArg(model, input.reasoningEffort ?? null);
79
88
  if (resolved)
@@ -246,24 +255,32 @@ export function status(id) {
246
255
  process.kill(meta.supervisor_pid, "SIGKILL");
247
256
  }
248
257
  catch (error) {
249
- if (error.code !== "ESRCH")
258
+ // EPERM: the pid now belongs to another user's process (reuse); it is not our writer, so recovery goes on.
259
+ const code = error.code;
260
+ if (code !== "ESRCH" && code !== "EPERM")
250
261
  throw error;
251
262
  }
252
263
  }
253
264
  killGroup(meta.child_pid);
254
- meta.status = "failed";
255
- meta.summary = "supervisor exited unexpectedly";
265
+ const reason = meta.stop_reason;
266
+ const decided = reason === "idle" || reason === "max_duration" || reason === "cancelled";
267
+ meta.status = decided ? (reason === "cancelled" ? "cancelled" : "timed_out") : "failed";
268
+ meta.summary = decided ? (reason === "cancelled" ? "Cancelled." : `Timed out: ${reason}.`) : "supervisor exited unexpectedly";
269
+ delete meta.stop_reason;
256
270
  meta.updated_at = new Date().toISOString();
257
271
  try {
258
272
  const turn = readTurn(id, meta.turn);
259
- writeTurn(id, { ...turn, status: "failed", summary: meta.summary });
273
+ writeTurn(id, { ...turn, status: meta.status, summary: meta.summary });
260
274
  }
261
275
  catch (error) {
262
276
  if (error.code !== "ENOENT")
263
277
  throw error;
264
278
  }
265
- appendEvent(id, { ts: meta.updated_at, turn: meta.turn, type: "turn_ended", status: "failed", exit_code: null });
279
+ if (!hasTurnEnded(id, meta.turn))
280
+ appendEvent(id, { ts: meta.updated_at, turn: meta.turn, type: "turn_ended", status: meta.status, exit_code: null });
266
281
  writeMeta(meta);
282
+ if (decided)
283
+ return finished(meta);
267
284
  return { ...meta, liveness: "orphaned", quiet_for_s: quiet };
268
285
  }
269
286
  finally {
@@ -294,6 +311,19 @@ export async function cancel(id) {
294
311
  }
295
312
  throw new Error("Cancellation not yet confirmed; retry status.");
296
313
  }
314
+ /** The agent's full last message of a finished turn (default: the latest turn). */
315
+ export function result(id, turnNo) {
316
+ const meta = status(id);
317
+ const n = turnNo ?? meta.turn;
318
+ if (!Number.isInteger(n) || n < 1 || n > meta.turn)
319
+ throw new Error(`turn must be an integer from 1 to ${meta.turn}.`);
320
+ const turn = readTurn(id, n);
321
+ if (turn.status === "running")
322
+ throw new Error(`Turn ${n} is still running; wait for it first.`);
323
+ if (!turn.final_message)
324
+ throw new Error(`Turn ${n} has no recorded final message (older baton, or the agent sent none); use baton tail.`);
325
+ return { task_id: id, turn: n, status: turn.status, final_message: turn.final_message };
326
+ }
297
327
  export async function wait(ids, seconds = 50) {
298
328
  if (!ids.length)
299
329
  throw new Error("task_ids is missing.");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@speculoai/baton",
3
- "version": "0.6.0",
3
+ "version": "0.6.2",
4
4
  "description": "Hand a bounded coding task to another local agent CLI, then continue the same session when it needs a decision.",
5
5
  "license": "MIT",
6
6
  "type": "module",