@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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 SpeculoAI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,172 @@
1
- # Temporary Holding Version
1
+ <h1 align="center">Baton</h1>
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ <p align="center">
4
+ <strong>Pass the task to the agent next door.</strong>
5
+ </p>
6
+
7
+ <p align="center">
8
+ <a href="https://github.com/SpeculoAI/baton/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/SpeculoAI/baton/ci.yml?branch=main&style=flat-square&label=CI" alt="CI"></a>
9
+ <a href="https://www.npmjs.com/package/@speculoai/baton"><img src="https://img.shields.io/npm/v/@speculoai/baton?style=flat-square&color=111111&label=npm" alt="npm"></a>
10
+ <img src="https://img.shields.io/node/v/@speculoai/baton?style=flat-square&color=111111" alt="Node version">
11
+ <img src="https://img.shields.io/badge/hosts-Claude%20Code%20%C2%B7%20Codex%20%C2%B7%20Cursor%20%C2%B7%20Antigravity%20%C2%B7%20Gemini-111111?style=flat-square" alt="Hosts">
12
+ <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-111111?style=flat-square" alt="MIT license"></a>
13
+ </p>
14
+
15
+ <p align="center">
16
+ <a href="#before--after">Before/After</a> •
17
+ <a href="#install">Install</a> •
18
+ <a href="#use-it">Use it</a> •
19
+ <a href="#how-it-works">How it works</a> •
20
+ <a href="docs/reference.md">Full reference</a> •
21
+ <a href="README.zh-CN.md">Chinese</a>
22
+ </p>
23
+
24
+ ---
25
+
26
+ You're working in Claude Code. Codex is installed on the same laptop, logged in, already paid for, and sitting idle. Baton lets the agent you're talking to hand a bounded coding task to that other agent, keep an eye on it, answer its questions, and bring the result back.
27
+
28
+ **Any agent as host, any agent as worker.** No API keys, no server, no cloud. Every agent uses its own login and subscription.
29
+
30
+ Workers: `codex` (Codex CLI) · `claude` (Claude Code) · `cursor` (Cursor Agent CLI) · `agy` (Antigravity).
31
+
32
+ ## Before / After
33
+
34
+ <table>
35
+ <tr>
36
+ <td width="50%">
37
+
38
+ ### Without Baton
39
+
40
+ 1. Open a second terminal and start `codex`.
41
+ 2. Copy the task in, plus the context it needs.
42
+ 3. Keep switching windows to check on it.
43
+ 4. It asks "A or B?" and waits for you, possibly for hours.
44
+ 5. Copy the result back into the first session and explain what changed.
45
+
46
+ </td>
47
+ <td width="50%">
48
+
49
+ ### With Baton
50
+
51
+ > **You:** rescue this refactor to Codex.
52
+
53
+ The host starts the job, checks on it in short steps, passes Codex's "A or B?" to you, and then reports what Codex did and which files it changed. You never leave the session.
54
+
55
+ </td>
56
+ </tr>
57
+ </table>
58
+
59
+ ## Install
60
+
61
+ ```bash
62
+ npx @speculoai/baton install
63
+ ```
64
+
65
+ It finds the agent CLIs on your machine, asks which ones should get the plugin, and installs the global `baton` command. Requires Node ≥ 20.17 and at least one supported agent CLI that is already logged in.
66
+
67
+ Check which workers Baton can see:
68
+
69
+ ```bash
70
+ baton agents
71
+ ```
72
+
73
+ Update everything later with `npx @speculoai/baton@latest update`. Flags (`--only`, `--force`, `--dry-run`), per-host manual installs, and MCP config for Claude Desktop, Windsurf, and Zed are covered in the [reference](docs/reference.md#installation).
74
+
75
+ ## Use it
76
+
77
+ Just ask in plain language:
78
+
79
+ ```text
80
+ rescue this failing test to codex
81
+ have claude review the diff, read-only
82
+ split the migration into three jobs and run them on codex and cursor
83
+ ```
84
+
85
+ Behind the scenes, the host runs ordinary shell commands:
86
+
87
+ ```bash
88
+ baton start --target codex --prompt "Fix the failing test in src/parser.ts" # returns a task_id at once
89
+ baton wait <task_id> --for 50 # repeats until the job stops
90
+ ```
91
+
92
+ Want to see what the worker is doing? Run this in any terminal:
93
+
94
+ ```bash
95
+ baton tail -f <task_id>
96
+ ```
97
+
98
+ If no target is named, the task goes to `codex`, or to `claude` when you are already in Codex. Baton never delegates to the agent you are already using.
99
+
100
+ ## What you get
101
+
102
+ | Skill | What it does |
103
+ |---|---|
104
+ | `baton-rescue` | Hands off one job, waits in short steps, passes the worker's questions to you, and reports the result. |
105
+ | `baton-orchestrate` | Runs several jobs with dependencies between them, reviews each one, retries, switches workers when one fails, and writes a summary. |
106
+ | `/baton:setup` | Puts the `baton` command on PATH if a marketplace install skipped it. |
107
+
108
+ | Command | What it does |
109
+ |---|---|
110
+ | `baton start` | Starts a job. Options include `--effort`, `--mode readonly`, `--scope <glob>`, `--rules check\|pointer\|off`, and `--cwd <worktree>`. |
111
+ | `baton wait` / `status` | Waits for the job to stop, or takes one look at it. |
112
+ | `baton tail [-f]` | Shows the live event stream as readable text. |
113
+ | `baton reply` | Continues the same conversation when the worker asks a question or you want a follow-up. |
114
+ | `baton cancel` / `ls` / `prune` | Stops a job, lists jobs, or deletes old ones. |
115
+ | `baton worktree add/ls/rm` | Gives a job its own git worktree so it doesn't touch your checkout. |
116
+ | `baton mcp` | Runs the same operations as an MCP server for hosts that can't run shell commands. |
117
+
118
+ Every command prints exactly one JSON object, so the host agent can read it reliably. See the [full flag list and statuses](docs/reference.md#command-line).
119
+
120
+ ## How it works
121
+
122
+ ```
123
+ Host agent ──shell──> baton start ──spawns a detached supervisor──> worker CLI (codex / claude / ...)
124
+ │ │ returns task_id at once │ streamed output → uniform events
125
+ │ ▼ │
126
+ │ ~/.baton/tasks/<id>/ <──────── single writer ───────┘
127
+ │ ▲
128
+ └──shell/MCP──> baton wait / status / tail / reply / cancel
129
+ ```
130
+
131
+ - **Jobs outlive the host.** Each job runs under its own supervisor, so closing the session or the terminal, or restarting MCP, doesn't stop it. You can still read the result afterwards.
132
+ - **No total time limit.** A job is stopped only after 10 minutes with no output at all, so slow models can think for hours.
133
+ - **One event format.** Messages, tool calls, and errors from every CLI are converted to the same events, and `status` tells you whether the worker is working, quietly thinking, or dead.
134
+ - **Questions don't strand the job.** When the worker needs a decision, the job pauses at `needs_input`. `baton reply` resumes the same session and records who answered.
135
+ - **Guardrails, not a sandbox.** `--mode readonly` uses each CLI's own read-only mode and flags the job if files change anyway. `--scope` checks git changes against path patterns after each turn. Workers can't call Baton again, and credentials are redacted from the event log.
136
+
137
+ ## FAQ
138
+
139
+ **Do I need API keys?**
140
+ No. Baton runs the CLIs you already have, with their existing logins.
141
+
142
+ **What happens if I close my host session mid-job?**
143
+ The job keeps running. Open a new session and run `baton ls` or `baton status <id>`.
144
+
145
+ **Is `--scope` a security boundary?**
146
+ No. It catches mistakes in files git can see. For real isolation, put the job in a `baton worktree`.
147
+
148
+ **Will the worker follow my project rules / environment?**
149
+ `baton status` reports `rules.unseen` (rule files the target does not load natively) and, if you use [rulesync](https://github.com/dyoshikawa/rulesync), whether generated configs are in sync. Pass `--rules pointer` to tell the worker to read unread rule files first. Prefer a shared `AGENTS.md` (and rulesync for MCP/skills/hooks across CLIs).
150
+
151
+ **Can Gemini CLI be a worker?**
152
+ Not yet. Gemini CLI works as a host.
153
+
154
+ **Where is the state?**
155
+ In `~/.baton/tasks/<id>/` (change it with `BATON_HOME`): `meta.json`, `events.jsonl`, one file per turn, and the raw logs. Nothing is deleted automatically.
156
+
157
+ ## Development
158
+
159
+ ```bash
160
+ npm install
161
+ npm test # typecheck + node --test, using fake CLIs; no model quota spent
162
+ ```
163
+
164
+ Changes land through pull requests only; see [CONTRIBUTING](.github/CONTRIBUTING.md) for the branch, PR, CI, and release workflow. Design notes are in [docs/architecture.md](docs/architecture.md) and [docs/hosts.md](docs/hosts.md). Upgrading from 0.3.x or earlier? See [the upgrade notes](docs/reference.md#upgrading-from-03x).
165
+
166
+ ## License
167
+
168
+ [MIT](LICENSE)
169
+
170
+ ---
171
+
172
+ <sub>Formerly **Agent-Plugin-Agent (APA)**. Old install strings no longer work; use `baton@speculoai`.</sub>
@@ -0,0 +1,172 @@
1
+ <h1 align="center">Baton</h1>
2
+
3
+ <p align="center">
4
+ <strong>把活儿递给隔壁的 Agent。</strong>
5
+ </p>
6
+
7
+ <p align="center">
8
+ <a href="https://github.com/SpeculoAI/baton/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/SpeculoAI/baton/ci.yml?branch=main&style=flat-square&label=CI" alt="CI"></a>
9
+ <a href="https://www.npmjs.com/package/@speculoai/baton"><img src="https://img.shields.io/npm/v/@speculoai/baton?style=flat-square&color=111111&label=npm" alt="npm"></a>
10
+ <img src="https://img.shields.io/node/v/@speculoai/baton?style=flat-square&color=111111" alt="Node 版本">
11
+ <img src="https://img.shields.io/badge/hosts-Claude%20Code%20%C2%B7%20Codex%20%C2%B7%20Cursor%20%C2%B7%20Antigravity%20%C2%B7%20Gemini-111111?style=flat-square" alt="支持的宿主">
12
+ <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-111111?style=flat-square" alt="MIT 许可证"></a>
13
+ </p>
14
+
15
+ <p align="center">
16
+ <a href="#前后对比">前后对比</a> •
17
+ <a href="#安装">安装</a> •
18
+ <a href="#怎么用">怎么用</a> •
19
+ <a href="#工作原理">工作原理</a> •
20
+ <a href="docs/reference.zh-CN.md">完整手册</a> •
21
+ <a href="README.md">English</a>
22
+ </p>
23
+
24
+ ---
25
+
26
+ 你正在 Claude Code 里干活。同一台电脑上还装着 Codex,已经登录、已经付了费,却闲着。Baton 让你正在对话的这个 Agent 把一块有边界的代码任务交给那个 Agent:盯着它跑、替你转达它的问题,最后把结果带回来。
27
+
28
+ **任何 Agent 都能当主控,任何 Agent 都能当执行者。** 不需要 API Key,不需要服务器,不上云。每个 Agent 都用它自己的登录和订阅额度。
29
+
30
+ 可派工的执行者:`codex`(Codex CLI)· `claude`(Claude Code)· `cursor`(Cursor Agent CLI)· `agy`(Antigravity)。
31
+
32
+ ## 前后对比
33
+
34
+ <table>
35
+ <tr>
36
+ <td width="50%">
37
+
38
+ ### 没有 Baton
39
+
40
+ 1. 另开一个终端,启动 `codex`。
41
+ 2. 把任务和它需要的上下文复制进去。
42
+ 3. 来回切窗口看它跑到哪了。
43
+ 4. 它问一句“选 A 还是 B?”,然后就一直等着你,可能一等几个小时。
44
+ 5. 再把结果复制回第一个会话,解释它改了什么。
45
+
46
+ </td>
47
+ <td width="50%">
48
+
49
+ ### 有了 Baton
50
+
51
+ > **你:** 把这次重构交给 Codex。
52
+
53
+ 主控 Agent 启动任务,分小段检查进度,把 Codex 的“A 还是 B?”转给你,最后告诉你 Codex 做了什么、改了哪些文件。你全程不用离开当前会话。
54
+
55
+ </td>
56
+ </tr>
57
+ </table>
58
+
59
+ ## 安装
60
+
61
+ ```bash
62
+ npx @speculoai/baton install
63
+ ```
64
+
65
+ 它会找出本机装了哪些 Agent CLI,问你要给哪些装插件,并安装全局 `baton` 命令。需要 Node ≥ 20.17,以及至少一个已登录的受支持 Agent CLI。
66
+
67
+ 看看 Baton 能找到哪些执行者:
68
+
69
+ ```bash
70
+ baton agents
71
+ ```
72
+
73
+ 以后用 `npx @speculoai/baton@latest update` 一键更新。安装参数(`--only`、`--force`、`--dry-run`)、各宿主的手动安装方式,以及 Claude Desktop、Windsurf、Zed 的 MCP 配置,见[完整手册](docs/reference.zh-CN.md#安装指南-installation)。
74
+
75
+ ## 怎么用
76
+
77
+ 直接用大白话说:
78
+
79
+ ```text
80
+ 把这个失败的测试交给 codex 修
81
+ 让 claude 只读地审一下这次 diff
82
+ 把迁移拆成三个任务,分给 codex 和 cursor 跑
83
+ ```
84
+
85
+ 主控 Agent 在背后执行的只是普通 shell 命令:
86
+
87
+ ```bash
88
+ baton start --target codex --prompt "修复 src/parser.ts 里失败的测试" # 立刻返回 task_id
89
+ baton wait <task_id> --for 50 # 反复调用,直到任务停下
90
+ ```
91
+
92
+ 想看执行者在干什么,在任意终端里运行:
93
+
94
+ ```bash
95
+ baton tail -f <task_id>
96
+ ```
97
+
98
+ 没指定目标时默认交给 `codex`;如果你本来就在 Codex 里,就交给 `claude`。Baton 永远不会把任务派给你当前正在用的那个 Agent。
99
+
100
+ ## 你会得到什么
101
+
102
+ | 技能 | 作用 |
103
+ |---|---|
104
+ | `baton-rescue` | 派出一个任务,分小段等待,把执行者的问题转给你,最后汇报结果。 |
105
+ | `baton-orchestrate` | 调度多个有依赖关系的任务:逐个审查、返工,某个执行者失败时换一家,最后写汇总。 |
106
+ | `/baton:setup` | 如果通过插件市场安装时没装上 `baton` 命令,用它补上。 |
107
+
108
+ | 命令 | 作用 |
109
+ |---|---|
110
+ | `baton start` | 启动任务。可选参数包括 `--effort`、`--mode readonly`、`--scope <glob>`、`--rules check\|pointer\|off`、`--cwd <worktree>`。 |
111
+ | `baton wait` / `status` | 等任务停下,或者看一眼当前状态。 |
112
+ | `baton tail [-f]` | 以可读文本显示实时事件流。 |
113
+ | `baton reply` | 执行者提问、或者你想追加要求时,在同一个会话里接着说。 |
114
+ | `baton cancel` / `ls` / `prune` | 停止任务、列出任务、清理旧任务。 |
115
+ | `baton worktree add/ls/rm` | 给任务单独开一个 git worktree,不碰你的工作目录。 |
116
+ | `baton mcp` | 以 MCP 服务器的形式提供同样的操作,给不能跑 shell 的宿主用。 |
117
+
118
+ 每个命令都只输出一个 JSON 对象,主控 Agent 读起来不会出错。全部参数和状态见[完整手册](docs/reference.zh-CN.md#命令行)。
119
+
120
+ ## 工作原理
121
+
122
+ ```
123
+ 主控 Agent ──shell──> baton start ──拉起独立的守护进程──> 执行者 CLI(codex / claude / ...)
124
+ │ │ 立刻返回 task_id │ 流式输出 → 统一事件
125
+ │ ▼ │
126
+ │ ~/.baton/tasks/<id>/ <────── 唯一写者 ───┘
127
+ │ ▲
128
+ └──shell/MCP──> baton wait / status / tail / reply / cancel
129
+ ```
130
+
131
+ - **任务不依附主控。** 每个任务都由自己的守护进程看管。关掉会话、关掉终端或重启 MCP,任务都照常跑,之后仍能读到结果。
132
+ - **没有总时长上限。** 只有连续 10 分钟没有任何输出才会停,慢模型想几个小时也没问题。
133
+ - **统一的事件格式。** 各家 CLI 的消息、工具调用和错误都转换成同一种事件;`status` 会告诉你执行者是在干活、在安静思考,还是已经死了。
134
+ - **提问不会把任务卡死。** 执行者需要你拍板时,任务停在 `needs_input`;`baton reply` 会在原会话里继续,并记下是谁回答的。
135
+ - **是护栏,不是沙箱。** `--mode readonly` 使用各家 CLI 自带的只读模式,如果文件还是被改了就标记出来;`--scope` 在每轮结束后用路径规则检查 git 改动。执行者不能再调用 Baton,事件日志里的凭据会被脱敏。
136
+
137
+ ## 常见问题
138
+
139
+ **需要 API Key 吗?**
140
+ 不需要。Baton 调用的是你已经装好的 CLI,用它们现有的登录。
141
+
142
+ **任务跑到一半我把主控会话关了怎么办?**
143
+ 任务会继续跑。开个新会话,运行 `baton ls` 或 `baton status <id>`。
144
+
145
+ **`--scope` 算安全边界吗?**
146
+ 不算。它只能拦住 git 看得见的文件里的误改。要真正隔离,请把任务放进 `baton worktree`。
147
+
148
+ **执行者会遵守我的项目规则 / 环境吗?**
149
+ `baton status` 会报告 `rules.unseen`(目标原生不会加载的规则文件);若你用了 [rulesync](https://github.com/dyoshikawa/rulesync),还会报告生成配置是否同步。需要时加 `--rules pointer`,让执行者先去读那些文件。更稳妥的做法是维护共享的 `AGENTS.md`,并用 rulesync 把 MCP/skills/hooks 同步到各家 CLI。
150
+
151
+ **Gemini CLI 能当执行者吗?**
152
+ 暂时不能,但可以当主控。
153
+
154
+ **状态存在哪?**
155
+ 在 `~/.baton/tasks/<id>/` 下(可用 `BATON_HOME` 修改):`meta.json`、`events.jsonl`、每轮一个文件,以及原始日志。不会被自动删除。
156
+
157
+ ## 开发
158
+
159
+ ```bash
160
+ npm install
161
+ npm test # 类型检查 + node --test,用假 CLI 跑,不消耗模型额度
162
+ ```
163
+
164
+ 所有改动都必须通过 PR 合并,分支、PR、CI 和发布流程见 [CONTRIBUTING](.github/CONTRIBUTING.md)。设计文档见 [docs/architecture.md](docs/architecture.md) 和 [docs/hosts.md](docs/hosts.md)。从 0.3.x 或更早版本升级,请看[升级说明](docs/reference.zh-CN.md#从-03x-升级)。
165
+
166
+ ## 许可证
167
+
168
+ [MIT](LICENSE)
169
+
170
+ ---
171
+
172
+ <sub>曾用名 **Agent-Plugin-Agent (APA)**。旧的安装字符串已失效,请使用 `baton@speculoai`。</sub>
@@ -0,0 +1,67 @@
1
+ import { redact } from "../redact.js";
2
+ import { authHit, which } from "./common.js";
3
+ const AUTH = ["not logged in", "please log in", "authentication required"];
4
+ function event(data) {
5
+ return [{ ts: new Date().toISOString(), turn: 0, ...data }];
6
+ }
7
+ function parse(line) {
8
+ try {
9
+ return JSON.parse(line);
10
+ }
11
+ catch {
12
+ return null;
13
+ }
14
+ }
15
+ export const agy = {
16
+ id: "agy",
17
+ readonlyEnforcement: "agent-enforced",
18
+ // Verified 2026-11-21: AGENTS.md / GEMINI.md / .agents/rules (and legacy .agent/rules). No load gates surveyed.
19
+ rules: {
20
+ files: ["AGENTS.md", "GEMINI.md", ".agents/AGENTS.md", ".agents/GEMINI.md", ".agents/rules", ".agent/rules"],
21
+ rulesyncTarget: "antigravity-cli",
22
+ },
23
+ resolve(env) {
24
+ return which(["agy"], env);
25
+ },
26
+ build({ bin, prompt, sessionId, reasoningEffort, mode }) {
27
+ const args = ["--print", prompt, "--mode", mode === "readonly" ? "plan" : "accept-edits", "--output-format", "stream-json"];
28
+ if (reasoningEffort)
29
+ args.push("--effort", reasoningEffort === "ultra" ? "max" : reasoningEffort);
30
+ if (sessionId)
31
+ args.push("--conversation", sessionId);
32
+ return { command: bin, args, stdin: null };
33
+ },
34
+ sessionIdFrom(line) {
35
+ const obj = parse(line);
36
+ return obj?.event === "init" && typeof obj.conversation_id === "string" ? obj.conversation_id : null;
37
+ },
38
+ parseLine(line) {
39
+ const obj = parse(line);
40
+ if (!obj || typeof obj !== "object" || typeof obj.event !== "string")
41
+ return null;
42
+ if (obj.event === "init")
43
+ return [];
44
+ if (obj.event === "step_update") {
45
+ const step = obj.step_update ?? {};
46
+ // agent_response text_delta events are per-character increments; the full reply appears once in result.response,
47
+ // otherwise marker parsing would only see the last increment.
48
+ if (step.step_type !== "tool")
49
+ return [];
50
+ const name = String(step.tool_name ?? step.tool_info?.name ?? "tool");
51
+ const detail = redact(JSON.stringify(step.tool_info?.parameters ?? {})).slice(0, 200);
52
+ if (step.state === "ACTIVE")
53
+ return event({ type: "tool_call", name, detail });
54
+ return event({ type: "tool_result", name, ok: step.state === "DONE", detail });
55
+ }
56
+ if (obj.event === "result") {
57
+ const result = obj.result ?? {};
58
+ if (result.status !== "SUCCESS")
59
+ return event({ type: "error", text: redact(String(result.response || result.status || "agy returned an error")) });
60
+ return typeof result.response === "string" && result.response ? event({ type: "message", text: result.response }) : [];
61
+ }
62
+ return null;
63
+ },
64
+ isAuthFailure(text) {
65
+ return authHit(text, AUTH);
66
+ },
67
+ };
@@ -0,0 +1,86 @@
1
+ import { redact } from "../redact.js";
2
+ import { authHit, which } from "./common.js";
3
+ const AUTH = ["not logged in", "please run /login", "invalid api key"];
4
+ function stamp(data) {
5
+ return { ts: new Date().toISOString(), turn: 0, ...data };
6
+ }
7
+ function parse(line) {
8
+ try {
9
+ return JSON.parse(line);
10
+ }
11
+ catch {
12
+ return null;
13
+ }
14
+ }
15
+ function contentText(content) {
16
+ if (typeof content === "string")
17
+ return content;
18
+ if (!Array.isArray(content))
19
+ return "";
20
+ return content.map((part) => (typeof part?.text === "string" ? part.text : "")).join("");
21
+ }
22
+ export const claude = {
23
+ id: "claude",
24
+ readonlyEnforcement: "agent-enforced",
25
+ // Verified 2026-11-21/22: CLAUDE.md hierarchy; AGENTS.md only when none of those three exist.
26
+ // Baton uses -p, which loads project .mcp.json without an approval prompt (no mcp gate).
27
+ rules: {
28
+ files: ["CLAUDE.md", ".claude/CLAUDE.md", "CLAUDE.local.md"],
29
+ conditional: [{ file: "AGENTS.md", unless: ["CLAUDE.md", ".claude/CLAUDE.md", "CLAUDE.local.md"] }],
30
+ rulesyncTarget: "claudecode",
31
+ },
32
+ resolve(env) {
33
+ return which(["claude"], env);
34
+ },
35
+ build({ bin, prompt, sessionId, reasoningEffort, mode }) {
36
+ // stream-json requires --verbose with -p.
37
+ const permission = mode === "readonly" ? "plan" : "acceptEdits";
38
+ const args = ["-p", "--output-format", "stream-json", "--verbose", "--permission-mode", permission, "--permission-prompts", "none"];
39
+ if (reasoningEffort)
40
+ args.push("--effort", reasoningEffort === "ultra" ? "max" : reasoningEffort);
41
+ if (sessionId)
42
+ args.push("--resume", sessionId);
43
+ args.push(prompt);
44
+ return { command: bin, args, stdin: null };
45
+ },
46
+ sessionIdFrom(line) {
47
+ const obj = parse(line);
48
+ return obj?.type === "system" && obj.subtype === "init" && typeof obj.session_id === "string" ? obj.session_id : null;
49
+ },
50
+ parseLine(line) {
51
+ const obj = parse(line);
52
+ if (!obj || typeof obj !== "object" || typeof obj.type !== "string")
53
+ return null;
54
+ // system: init is handled by sessionIdFrom; hook_* carries host hook output and stays out of the event stream.
55
+ if (obj.type === "system" || obj.type === "rate_limit_event")
56
+ return [];
57
+ const parts = Array.isArray(obj.message?.content) ? obj.message.content : [];
58
+ if (obj.type === "assistant") {
59
+ const events = [];
60
+ const text = parts.filter((p) => p?.type === "text" && typeof p.text === "string").map((p) => p.text).join("");
61
+ for (const p of parts) {
62
+ if (p?.type !== "tool_use")
63
+ continue;
64
+ const input = p.input ?? {};
65
+ const detail = redact(String(input.command ?? input.file_path ?? input.path ?? JSON.stringify(input))).slice(0, 200);
66
+ events.push(stamp({ type: "tool_call", name: String(p.name ?? "tool"), detail }));
67
+ }
68
+ if (text)
69
+ events.push(stamp({ type: "message", text }));
70
+ return events;
71
+ }
72
+ if (obj.type === "user") {
73
+ return parts
74
+ .filter((p) => p?.type === "tool_result")
75
+ .map((p) => stamp({ type: "tool_result", name: "tool", ok: p.is_error !== true, detail: redact(contentText(p.content)).slice(0, 200) }));
76
+ }
77
+ if (obj.type === "result") {
78
+ // The final text was already emitted once as an assistant message; only report errors here.
79
+ return obj.is_error ? [stamp({ type: "error", text: redact(String(obj.result ?? obj.subtype ?? "claude returned an error")) })] : [];
80
+ }
81
+ return null;
82
+ },
83
+ isAuthFailure(text) {
84
+ return authHit(text, AUTH);
85
+ },
86
+ };
@@ -0,0 +1,114 @@
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
+ // Verified 2026-11-21/22: AGENTS.md (+ override). Project .codex/config.toml MCP/hooks need trust.
10
+ rules: {
11
+ files: ["AGENTS.md", "AGENTS.override.md"],
12
+ rulesyncTarget: "codexcli",
13
+ gates: {
14
+ mcp: "Project .codex/config.toml (where rulesync writes Codex MCP) loads only for trusted project paths; a baton worktree is a separate absolute path and does not inherit the main repo's trust_level.",
15
+ hooks: "Project hooks require persisted hook trust; codex exec has --dangerously-bypass-hook-trust (Baton does not pass it).",
16
+ },
17
+ },
18
+ resolve(env) {
19
+ return which(["codex"], env);
20
+ },
21
+ build({ bin, cwd, prompt, sessionId, reasoningEffort, mode }) {
22
+ const lastMessagePath = path.join(os.tmpdir(), `baton-codex-${process.pid}-${Date.now()}.txt`);
23
+ const effortArgs = reasoningEffort ? ["-c", `model_reasoning_effort="${reasoningEffort}"`] : [];
24
+ const readonly = mode === "readonly";
25
+ // `exec resume` does not accept --cd/--color/--sandbox. The first write turn uses --approve-for-me (workspace-write; do not add --sandbox).
26
+ if (sessionId) {
27
+ return {
28
+ command: bin,
29
+ args: [
30
+ "exec",
31
+ "resume",
32
+ "--json",
33
+ "--skip-git-repo-check",
34
+ "--output-last-message",
35
+ lastMessagePath,
36
+ ...effortArgs,
37
+ sessionId,
38
+ "-",
39
+ ],
40
+ stdin: prompt,
41
+ lastMessagePath,
42
+ };
43
+ }
44
+ return {
45
+ command: bin,
46
+ args: [
47
+ "exec",
48
+ "--json",
49
+ "--color",
50
+ "never",
51
+ ...(readonly ? ["--sandbox", "read-only"] : ["--approve-for-me"]),
52
+ "--skip-git-repo-check",
53
+ "--cd",
54
+ cwd,
55
+ "--output-last-message",
56
+ lastMessagePath,
57
+ ...effortArgs,
58
+ "-",
59
+ ],
60
+ stdin: prompt,
61
+ lastMessagePath,
62
+ };
63
+ },
64
+ sessionIdFrom(line) {
65
+ try {
66
+ const obj = JSON.parse(line);
67
+ return obj?.type === "thread.started" && typeof obj.thread_id === "string" ? obj.thread_id : null;
68
+ }
69
+ catch {
70
+ return null;
71
+ }
72
+ },
73
+ parseLine(line) {
74
+ let obj;
75
+ try {
76
+ obj = JSON.parse(line);
77
+ }
78
+ catch {
79
+ return null;
80
+ }
81
+ if (!obj || typeof obj !== "object")
82
+ return null;
83
+ const event = (data) => [{ ts: new Date().toISOString(), turn: 0, ...data }];
84
+ if (obj.type === "turn.failed" && typeof obj.error?.message === "string")
85
+ return event({ type: "error", text: obj.error.message });
86
+ // Lifecycle events: the session id comes from sessionIdFrom and turn start/end are recorded by the supervisor, so no events are emitted here.
87
+ if (["thread.started", "turn.started", "turn.completed"].includes(obj.type))
88
+ return [];
89
+ const item = obj.item;
90
+ if (obj.type === "item.completed" && item?.type === "error" && typeof item.message === "string") {
91
+ return event({ type: "error", text: redact(item.message) });
92
+ }
93
+ if (!item || !["item.started", "item.completed"].includes(obj.type))
94
+ return null;
95
+ const completed = obj.type === "item.completed";
96
+ if (item.type === "agent_message" && typeof item.text === "string")
97
+ return completed ? event({ type: "message", text: item.text }) : [];
98
+ if (item.type === "command_execution" && typeof item.command === "string") {
99
+ return event(completed
100
+ ? { type: "tool_result", name: "command_execution", ok: item.exit_code === 0, detail: redact(String(item.aggregated_output || item.command)).slice(0, 200) }
101
+ : { type: "tool_call", name: "command_execution", detail: redact(item.command).slice(0, 200) });
102
+ }
103
+ if (item.type === "file_change" && Array.isArray(item.changes)) {
104
+ const detail = redact(JSON.stringify(item.changes)).slice(0, 200);
105
+ return event(completed
106
+ ? { type: "tool_result", name: "file_change", ok: item.status === "completed", detail }
107
+ : { type: "tool_call", name: "file_change", detail });
108
+ }
109
+ return null;
110
+ },
111
+ isAuthFailure(text) {
112
+ return authHit(text, AUTH);
113
+ },
114
+ };
@@ -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
+ }