dsh-baton-mcp 0.5.8 → 0.6.0-next.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 +29 -3
- package/README.zh-CN.md +29 -3
- package/host/package.json +2 -2
- package/package.json +1 -1
- package/server.json +2 -2
- package/src/cli.mjs +5 -2
- package/src/core.mjs +104 -9
- package/src/evidence.mjs +101 -0
- package/src/folder.mjs +70 -0
- package/src/mcp.mjs +357 -0
- package/src/server.mjs +196 -260
package/README.md
CHANGED
|
@@ -69,6 +69,29 @@ That is all. If Harness says it could not register, run `npx -y dsh-baton-mcp se
|
|
|
69
69
|
- **Codex** waits inside `dsh_wait`, up to 270 s per call, just under its 300 s tool timeout. An unfinished wait returns only the state, so Codex calls again without summarising. Codex gets no `wait_command`: its terminal cannot wake it, so it would poll.
|
|
70
70
|
- Codex asks you to approve MCP tool calls: approve the `dsh-baton` tools. For unattended `codex exec` runs, add `--approve-for-me`.
|
|
71
71
|
|
|
72
|
+
**How a hand-over is checked** (from 0.6.0): the client sends the task with `checks`, the project's own test commands such as `npm test`. dsh-baton notes the folder's files before the run, and when the run ends it lists the files created, changed and deleted and runs the checks itself; this `evidence` comes from dsh-baton, not from the DeepSeek reply. The message also asks Harness to have a read-only sub-agent check the work against every requirement and end with a table (requirement, met, file:line). The client accepts from the evidence and that table, sends anything not met back in one message, and reads code only for rows not met. A new session starts in the folder the conversation works in unless `cwd` names another one.
|
|
73
|
+
|
|
74
|
+
## Token usage
|
|
75
|
+
|
|
76
|
+
Measured on 2026-10-25/26 with plain-language requests (what a user would type, plus "hand it to DeepSeek Harness"), the same model in both arms, three runs per cell, and every run checked by the same hidden acceptance test. Cost per task at list price; DeepSeek at its peak price, the most conservative case:
|
|
77
|
+
|
|
78
|
+
| Task | Claude Code alone | Claude Code → 0.6.0 | Codex alone | Codex → 0.6.0 |
|
|
79
|
+
|---|---|---|---|---|
|
|
80
|
+
| Medium: CLI, modules, tests | $1.07 | $0.37 client, $0.55 with DeepSeek | $0.17 | $0.09 client, $0.29 with DeepSeek |
|
|
81
|
+
| Large: web app, API, tests | $2.13 | $0.41 client, $0.70 with DeepSeek | $0.41 | $0.10 client, $0.41 with DeepSeek |
|
|
82
|
+
|
|
83
|
+
- **Claude Code** spends 65–81% less, and still about half or less once DeepSeek is added.
|
|
84
|
+
- **Codex** (gpt-6.1-sol, high) spends half to three quarters less of its own model, so a ChatGPT Plus 5-hour window lasts more than twice as long: 0.8% instead of 1.9% per medium task, 1.0% instead of 4.3% per large one. Sol is cheap, so with DeepSeek added a medium task costs more in total than doing it in Codex, and a large one about the same; the saving is in the subscription quota. With a pricier model the total drops too.
|
|
85
|
+
- All 12 runs of 0.6.0 passed the acceptance test the first time.
|
|
86
|
+
|
|
87
|
+
The [full report](./docs/benchmarks/token-usage-2026-10.md) has the method, every run, the earlier builds that were compared, raw data and scripts.
|
|
88
|
+
|
|
89
|
+
<p align="center">
|
|
90
|
+
<img src="./docs/benchmarks/token-usage-2026-10/charts/natural-total-claude-release.svg" width="100%" alt="Claude Code cost per task: alone vs handed over, with and without the DeepSeek share">
|
|
91
|
+
<img src="./docs/benchmarks/token-usage-2026-10/charts/natural-total-codex-release.svg" width="100%" alt="Codex cost per task: alone vs handed over, with and without the DeepSeek share">
|
|
92
|
+
<img src="./docs/benchmarks/token-usage-2026-10/charts/natural-codex-quota-release.svg" width="100%" alt="Codex Plus 5-hour window used per task">
|
|
93
|
+
</p>
|
|
94
|
+
|
|
72
95
|
## Tools
|
|
73
96
|
|
|
74
97
|
<p align="center">
|
|
@@ -88,16 +111,17 @@ That is all. If Harness says it could not register, run `npx -y dsh-baton-mcp se
|
|
|
88
111
|
| `dsh_create_workspace` | Register a folder as a workspace (creates the folder if missing); returns the existing one if already registered |
|
|
89
112
|
| `dsh_list_sessions` | Sessions newest first, with title, folder and running state; filter by folder or text. Archived sessions are left out |
|
|
90
113
|
| `dsh_read_session` | Recent prompts and replies of one session (with tool names); `archived: true` for an archived session |
|
|
91
|
-
| `dsh_send` | Send a message: `session_id` continues that session; `cwd` or `workspace_id
|
|
114
|
+
| `dsh_send` | Send a message: `session_id` continues that session; otherwise a new one starts in `cwd` or `workspace_id`, or, with neither, in the folder the conversation works in (a `cwd` that is not a workspace yet is registered first; a `cwd` outside the conversation's folder is allowed and noted in `folder_note`). `checks`: test commands dsh-baton runs itself when the run ends (see How a hand-over is checked). Returns a `run_id` at once. In Harness the message is marked "Sent by Claude / ChatGPT from another chat". An archived session is refused: unarchive it in Harness, or start a new session. To a busy session, `mode` `followup` queues the message after the current turn and `steer` adds it to the running turn; left out, it does what Harness's own setting says (Settings → sending while busy: queue or steer), and `followup` when that cannot be read. `mode_source` says which applied |
|
|
92
115
|
| `dsh_status` | Run progress: state, recent text and tool calls, final reply; `waiting_on` when the turn is over but sub-agents or jobs still run; `human_interjections` when someone typed in the Harness UI mid-run; state `interrupted` for a run cut short by a Harness restart |
|
|
93
|
-
| `dsh_wait` | Wait for the run to end (or until it stops to ask a person, see `dsh_answer`): up to 270 s per call for Codex, 50 s for other clients. Still going: returns `timed_out` with just the state; call it again. Clients that can wait in the background use `dsh_send`'s `wait_command` instead. `dsh_status` is a one-off look, not a way to wait |
|
|
94
|
-
| `dsh_answer` | Answer the questions a run stopped to ask (Harness's ask_user_question): per question, an option number or label, free text, or skip; one at a time or all at once. `dsh_wait` and `wait_command` return as soon as a run asks, with the questions (`needs_input`, `question
|
|
116
|
+
| `dsh_wait` | Wait for the run to end; a finished run carries `evidence` (files changed, check results) when the message was sent with `checks` (or until it stops to ask a person, see `dsh_answer`): up to 270 s per call for Codex, 50 s for other clients. Still going: returns `timed_out` with just the state; call it again. Clients that can wait in the background use `dsh_send`'s `wait_command` instead. `dsh_status` is a one-off look, not a way to wait |
|
|
117
|
+
| `dsh_answer` | Answer the questions a run stopped to ask (Harness's ask_user_question): per question, an option number or label, free text, or skip; one at a time or all at once. `dsh_wait` and `wait_command` return as soon as a run asks, with the questions (`needs_input`, `question`; the option Harness's model would pick is in `harness_suggested`, apart from the labels). The assistant answers by its own judgment only when you told it to decide, and then passes `reason` and tells you what it chose and why; otherwise it brings you the questions, starting with its own recommendation and reason. You can also answer in the Harness window: whoever answers first wins |
|
|
95
118
|
| `dsh_session_activity` | What a session is doing now: running turn, sub-agents (any depth), background jobs; `archived: true` for an archived session |
|
|
96
119
|
| `dsh_update_queued` | Change a message still waiting in the queue of a busy session, by its `run_id`: `edit` its text, `remove` it, or `steer` it into the running turn now. Once it has reached the conversation it can no longer be changed |
|
|
97
120
|
| `dsh_cancel` | Stop everything a session is doing, by `run_id` or `session_id`: turn, sub-agents, jobs. Harness also drops the messages waiting in its queue; their runs end as `cancelled` |
|
|
98
121
|
| `dsh_rename_session` | Rename a session |
|
|
99
122
|
| `dsh_rename_workspace` | Rename a workspace (sidebar title only; the folder is not moved) |
|
|
100
123
|
| `dsh_list_runs` | Recent runs, optionally of one session |
|
|
124
|
+
| `dsh_call` | Calls any `dsh_*` tool by name: the less used tools (create and rename workspace, rename session, session activity, update queued, list runs) are not in the tool list from 0.6.0 on, to keep every request short, and are reached this way; also for a conversation whose tool list predates an update. An unknown name lists the tools |
|
|
101
125
|
|
|
102
126
|
</details>
|
|
103
127
|
|
|
@@ -142,6 +166,8 @@ When the plugin is unreachable, the MCP server falls back to Harness's `dsh head
|
|
|
142
166
|
|
|
143
167
|
**What the plugin does when switched on.** It copies the MCP server to `~/.dsh-baton/app`, a folder that stays put, and writes the MCP entry into `~/.claude.json` and `~/.codex/config.toml` directly, keeping a `*.bak-dsh-baton` backup of each. It starts the server with your own Node.js ≥ 22.15 when it finds one on `PATH`; without one, with Harness's own runtime (the Harness app in Node mode, `ELECTRON_RUN_AS_NODE=1`), so nothing else has to be installed. Either way it works with only the desktop apps installed, when `claude` / `codex` are not on your `PATH`. It runs again on each Harness start: an entry that is already right, or a working one that starts another copy of dsh-baton, is left alone. In Harness, the source switches to the npm registry ("Official npm registry", 「npm 官方源」) by itself once you type the package name, and no restart is needed. To turn the registration off, set `DSH_BATON_AUTO_REGISTER=0` for Harness.
|
|
144
168
|
|
|
169
|
+
**Updates need no restart.** When a newer version lands in `~/.dsh-baton/app` (a plugin update, `setup`, or a copy by hand), conversations already open in Claude Code and Codex use it from their next `dsh_*` call: the server checks the folder before each call, starts the new version, and says once in that call's result that it was updated. A `dsh_wait` that is already running finishes on the old version first. If the new version cannot start, the old one keeps working and the result says why. A tool added in the new version shows up in Claude Code at once (the server tells the client its tool list changed); Codex keeps the tool list a conversation started with, so it does not show a new tool until the next conversation; from 0.5.9 on it can still use one at once through `dsh_call`, which the update note points to, and the tools it already has run the new code right away. This works from the version after 0.5.8 on; a server started from 0.5.8 or earlier needs one last restart (or `/mcp` reconnect) to pick it up.
|
|
170
|
+
|
|
145
171
|
**`npx -y dsh-baton-mcp setup`** does the same registration from a terminal: for a plugin that could not register, or when you come from an MCP directory. With the plugin already registered it changes nothing, then points you to the plugin if it is missing.
|
|
146
172
|
|
|
147
173
|
**Updating.** Harness has an update button only for its official plugins, so: Plugins → dsh-baton-host → **Uninstall**, then **Add plugin** → `dsh-baton-host`. For a while after a release, Harness installs the previous version instead (pnpm's `minimumReleaseAge` holds back versions published very recently, and the install dialog says so); to get the new one at once, type the version: `dsh-baton-host@0.5.0`. Switched on again, the plugin brings the MCP server to the same version; new conversations use it. If the two are ever out of step, the first tool call that notices it says so.
|
package/README.zh-CN.md
CHANGED
|
@@ -69,6 +69,29 @@ Codex 和 Claude 轮流往同一个 Harness 对话发消息,每条都标明是
|
|
|
69
69
|
- **Codex** 在 `dsh_wait` 里等待,每次最多 270 秒,刚好低于它 300 秒的工具超时。没做完时只返回状态,Codex 会直接再调用,不会去总结进度。Codex 不会收到 `wait_command`:它的终端无法在命令结束时唤醒它,只能轮询。
|
|
70
70
|
- Codex 调用 MCP 工具时会请你批准,批准 `dsh-baton` 的工具即可;无人值守的 `codex exec` 加上 `--approve-for-me`。
|
|
71
71
|
|
|
72
|
+
**转交之后怎么验收**(0.6.0 起):客户端发任务时附上 `checks`,也就是项目自己的测试命令,比如 `npm test`。dsh-baton 在运行前记下文件夹里的文件,运行结束后自己列出新建、修改、删除了哪些文件,并自己跑一遍这些命令;这份 `evidence`(证据)来自 dsh-baton,不是 DeepSeek 的自述。消息末尾还会请 Harness 派一个只读子智能体,对照每条需求复查,最后附一张表(需求、是否满足、依据在哪个文件第几行)。客户端凭证据和这张表验收,没满足的一次性发回去修,只对没满足的行看代码。新开对话默认建在当前对话所在的文件夹,除非用 `cwd` 指定别的文件夹。
|
|
73
|
+
|
|
74
|
+
## Token 用量实测
|
|
75
|
+
|
|
76
|
+
2026-10-25/26 实测:用户用大白话提需求(末尾加一句「交给 DeepSeek Harness 去做」),两边用同一个模型,每格跑 3 次,每次都用同一套隐藏的验收脚本检查。下表是每个任务的平均花费,按标价计;DeepSeek 按高峰价,是最保守的算法:
|
|
77
|
+
|
|
78
|
+
| 任务 | Claude Code 自己做 | Claude Code → 0.6.0 | Codex 自己做 | Codex → 0.6.0 |
|
|
79
|
+
|---|---|---|---|---|
|
|
80
|
+
| 中号:命令行工具、分模块、测试 | $1.07 | 主 Agent $0.37,含 DeepSeek $0.55 | $0.17 | 主 Agent $0.09,含 DeepSeek $0.29 |
|
|
81
|
+
| 大号:网页应用、接口、测试 | $2.13 | 主 Agent $0.41,含 DeepSeek $0.70 | $0.41 | 主 Agent $0.10,含 DeepSeek $0.41 |
|
|
82
|
+
|
|
83
|
+
- **Claude Code** 自己的花费少 65–81%,加上 DeepSeek 后总价也只有自己做的一半左右甚至更少。
|
|
84
|
+
- **Codex**(gpt-6.1-sol,high)自己模型的花费少一半到四分之三,ChatGPT Plus 的 5 小时额度能多撑一倍以上:中号任务从 1.9% 降到 0.8%,大号从 4.3% 降到 1.0%。Sol 本身很便宜,加上 DeepSeek 后,中号的总价比 Codex 自己做还贵,大号基本持平;省下的是订阅额度。主模型越贵,总价也越省。
|
|
85
|
+
- 0.6.0 的 12 次运行全部一次通过验收。
|
|
86
|
+
|
|
87
|
+
[完整报告](./docs/benchmarks/token-usage-2026-10.md)里有方法、每一次运行、对比过的其他版本、原始数据和脚本。
|
|
88
|
+
|
|
89
|
+
<p align="center">
|
|
90
|
+
<img src="./docs/benchmarks/token-usage-2026-10/charts/natural-total-claude-release.zh.svg" width="100%" alt="Claude Code 每个任务的花费:自己做与转交,含与不含 DeepSeek">
|
|
91
|
+
<img src="./docs/benchmarks/token-usage-2026-10/charts/natural-total-codex-release.zh.svg" width="100%" alt="Codex 每个任务的花费:自己做与转交,含与不含 DeepSeek">
|
|
92
|
+
<img src="./docs/benchmarks/token-usage-2026-10/charts/natural-codex-quota-release.zh.svg" width="100%" alt="Codex Plus 每个任务占用的 5 小时额度">
|
|
93
|
+
</p>
|
|
94
|
+
|
|
72
95
|
## 工具
|
|
73
96
|
|
|
74
97
|
<p align="center">
|
|
@@ -88,16 +111,17 @@ Codex 和 Claude 轮流往同一个 Harness 对话发消息,每条都标明是
|
|
|
88
111
|
| `dsh_create_workspace` | 把一个文件夹登记为工作区(文件夹不存在会先创建);已登记的直接返回原来那个 |
|
|
89
112
|
| `dsh_list_sessions` | 列出对话(最新在前),带标题、目录、是否在跑;可按目录或关键字过滤。已归档的对话不会列出 |
|
|
90
113
|
| `dsh_read_session` | 读某个对话最近的消息和回复(含用到的工具名);已归档的对话会带 `archived: true` |
|
|
91
|
-
| `dsh_send` | 发消息。带 `session_id`
|
|
114
|
+
| `dsh_send` | 发消息。带 `session_id` 续接那个对话;否则新开对话,建在 `cwd` 或 `workspace_id` 指定的位置,都不带时建在当前对话所在的文件夹(`cwd` 还不是工作区时会先登记;指定的 `cwd` 在当前对话文件夹之外也可以,结果里的 `folder_note` 会提醒)。`checks`:运行结束后 dsh-baton 自己跑的测试命令(见「转交之后怎么验收」)。立即返回 `run_id`。Harness 里这条消息会标注「由 Claude / ChatGPT 从另一个聊天发送」。已归档的对话会被拒绝:先在 Harness 里取消归档,或新开对话。对话正忙时,`mode` 为 `followup` 会排在当前回合之后,`steer` 会插进正在跑的回合;不传时跟随 Harness 自己的设置(设置 → 繁忙时的发送行为:排队发送或插话发送),读不到设置时按 `followup`。返回里的 `mode_source` 说明用的是哪种 |
|
|
92
115
|
| `dsh_status` | 查看运行进度:状态、最近的文字和工具调用、最终回复;回合结束但子智能体/后台任务还在跑时给出 `waiting_on`;中途有人在 Harness 界面里发消息时给出 `human_interjections`;被 Harness 重启打断的任务状态为 `interrupted` |
|
|
93
|
-
| `dsh_wait` |
|
|
94
|
-
| `dsh_answer` | 回答运行中途提出的问题(Harness 的 ask_user_question):每道题可以填选项编号或选项文字、自由填写,或者跳过;可以逐题回答,也可以一次答完。运行一提问,`dsh_wait` 和 `wait_command` 就会立刻返回,并带上题目(`needs_input`、`question
|
|
116
|
+
| `dsh_wait` | 等运行结束;发消息时带了 `checks` 的,结束后会附上 `evidence`(改了哪些文件、测试结果)(或者等到它停下来问人,见 `dsh_answer`):Codex 每次最多等 270 秒,其他客户端 50 秒。没做完会带 `timed_out`,只返回状态,再调用一次即可。能在后台等待的客户端改用 `dsh_send` 返回的 `wait_command`。`dsh_status` 只用来看一眼,不用来等待 |
|
|
117
|
+
| `dsh_answer` | 回答运行中途提出的问题(Harness 的 ask_user_question):每道题可以填选项编号或选项文字、自由填写,或者跳过;可以逐题回答,也可以一次答完。运行一提问,`dsh_wait` 和 `wait_command` 就会立刻返回,并带上题目(`needs_input`、`question`;Harness 那边模型推荐的选项单独放在 `harness_suggested` 里,不再写在选项文字中)。只有你说过让它自己决定时,助手才会按自己的判断回答,这时它会带上 `reason`,并告诉你选了什么、为什么;否则它会把题目转给你,开头先写它自己的建议和理由。你也可以直接在 Harness 窗口里回答,谁先答就算谁的 |
|
|
95
118
|
| `dsh_session_activity` | 对话此刻在做什么:正在跑的回合、子智能体(任意层级)、后台任务;已归档的对话会带 `archived: true` |
|
|
96
119
|
| `dsh_update_queued` | 按 `run_id` 修改还在忙碌对话队列里等待的消息:`edit` 改文字,`remove` 撤回,`steer` 立刻插进正在跑的回合。消息一旦进入对话就改不了了 |
|
|
97
120
|
| `dsh_cancel` | 按 `run_id` 或 `session_id` 停掉整个对话的工作:当前回合、子智能体、后台任务。Harness 会同时清掉队列里等待的消息,这些运行记为 `cancelled` |
|
|
98
121
|
| `dsh_rename_session` | 给对话改名 |
|
|
99
122
|
| `dsh_rename_workspace` | 给工作区改名(只改侧边栏标题,不动文件夹) |
|
|
100
123
|
| `dsh_list_runs` | 列出最近的运行,可按会话筛选 |
|
|
124
|
+
| `dsh_call` | 按名字调用任意 `dsh_*` 工具:0.6.0 起,不常用的工具(新建和重命名工作区、重命名对话、对话动态、修改排队消息、运行列表)不再出现在工具列表里,好让每次请求更短,改由这里调用;对话的工具列表还是更新前的旧版时也用它。名字不存在时会列出所有可用工具 |
|
|
101
125
|
|
|
102
126
|
</details>
|
|
103
127
|
|
|
@@ -144,6 +168,8 @@ dsh-baton rename-workspace ~/code/new-app 新名字
|
|
|
144
168
|
|
|
145
169
|
**插件启用时做了什么。**它把 MCP 服务器复制到 `~/.dsh-baton/app` 这个固定的文件夹,再直接把 MCP 注册写进 `~/.claude.json` 和 `~/.codex/config.toml`,各留一份 `*.bak-dsh-baton` 备份。电脑上有 Node.js ≥ 22.15(在 `PATH` 里能找到)就用它启动服务器;没有的话,就用 Harness 自带的运行环境(Harness 应用本身以 Node 模式运行,`ELECTRON_RUN_AS_NODE=1`),不用另外安装任何东西。两种情况下,只装了桌面应用、`claude` / `codex` 不在 `PATH` 里也能用。每次 Harness 启动都会再检查一遍:已经正确的注册、或者指向另一份可用 dsh-baton 的注册,都不会改动。在 Harness 里输入包名后,安装源会自动切到「npm 官方源」(英文界面是 "Official npm registry"),不用另外选择,也不用重启。不想让插件自动注册,给 Harness 设置 `DSH_BATON_AUTO_REGISTER=0`。
|
|
146
170
|
|
|
171
|
+
**更新不用重启。**新版本装进 `~/.dsh-baton/app` 后(插件更新、`setup` 或手动复制),Claude Code 和 Codex 里已经开着的对话,下一次调用 `dsh_*` 工具时就会用上:服务器每次调用前检查这个文件夹,启动新版本,并在这次调用的结果里提示一次已经更新。正在进行的 `dsh_wait` 会先在旧版本里跑完。新版本启动失败时,旧版本继续工作,结果里会说明原因。新版本新增的工具,Claude Code 里马上就能用(服务器会通知客户端工具列表变了);Codex 一直用对话开始时的工具列表,新工具要到下一个新对话才会显示;从 0.5.9 起,旧对话里也能通过 `dsh_call` 马上用上新功能(更新提示里会写明),已有的工具也会立刻用上新代码。这个功能从 0.5.8 之后的版本开始有效;由 0.5.8 或更早版本启动的服务器,还需要最后重启一次(或在 `/mcp` 里重新连接)。
|
|
172
|
+
|
|
147
173
|
**`npx -y dsh-baton-mcp setup`** 在终端里做同样的注册:用于插件没能注册的情况,或者从 MCP 目录过来的用户。插件已经注册过时它什么都不改;插件没装的话,它会提示去添加。
|
|
148
174
|
|
|
149
175
|
**更新。**Harness 只给官方插件提供"更新"按钮,所以要:插件 → dsh-baton-host → **卸载**,再**添加插件** → `dsh-baton-host`。新版本刚发布的一段时间里,Harness 会装上一个版本(pnpm 的 `minimumReleaseAge` 会暂缓刚发布的版本,安装弹窗里会说明);想马上用新版,输入带版本号的名字:`dsh-baton-host@0.5.0`。重新启用后,插件会把 MCP 服务器也更新到同一版本,新开的对话就会用上。万一两边版本对不上,第一次发现不一致的工具调用会提示。
|
package/host/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-baton-host",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0-next.0",
|
|
4
4
|
"description": "DeepSeek Harness plugin for dsh-baton: adding it is the whole install. Switched on, it registers the dsh-baton MCP server for Claude Code and Codex, then takes the baton over a local, owner-only control socket, runs it in a specific session through the host's own session controller, and hands the result back when the turn is done.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "lib/index.js",
|
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
"LICENSE"
|
|
21
21
|
],
|
|
22
22
|
"dependencies": {
|
|
23
|
-
"dsh-baton-mcp": "0.
|
|
23
|
+
"dsh-baton-mcp": "0.6.0-next.0"
|
|
24
24
|
},
|
|
25
25
|
"license": "MIT",
|
|
26
26
|
"dsh": {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-baton-mcp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0-next.0",
|
|
4
4
|
"mcpName": "io.github.JialaoLiu/dsh-baton",
|
|
5
5
|
"description": "Pass the baton from Claude Code, Codex or any MCP client to a local DeepSeek Harness: an MCP server that hands off tasks, continues a specific session, shows the run live in Harness and hands the result back when it is done.",
|
|
6
6
|
"type": "module",
|
package/server.json
CHANGED
|
@@ -7,12 +7,12 @@
|
|
|
7
7
|
"url": "https://github.com/JialaoLiu/dsh-baton",
|
|
8
8
|
"source": "github"
|
|
9
9
|
},
|
|
10
|
-
"version": "0.
|
|
10
|
+
"version": "0.6.0-next.0",
|
|
11
11
|
"packages": [
|
|
12
12
|
{
|
|
13
13
|
"registryType": "npm",
|
|
14
14
|
"identifier": "dsh-baton-mcp",
|
|
15
|
-
"version": "0.
|
|
15
|
+
"version": "0.6.0-next.0",
|
|
16
16
|
"transport": {
|
|
17
17
|
"type": "stdio"
|
|
18
18
|
}
|
package/src/cli.mjs
CHANGED
|
@@ -64,8 +64,11 @@ async function main() {
|
|
|
64
64
|
return print(await core.api.status({ run_id: rest[0] }))
|
|
65
65
|
case 'wait': {
|
|
66
66
|
const st = await core.api.wait({ run_id: rest[0], timeout_s: Number(flags.timeout) || 24 * 3600 })
|
|
67
|
-
print({
|
|
68
|
-
...(st.
|
|
67
|
+
print({
|
|
68
|
+
...(st.decided_for_user ? { hint: 'Required in your reply: you chose an answer for the user during this run, so start your reply by telling the user, in their language, what you chose and why (decided_for_user: answers and reason), then give the result. Passing on only final_text is not enough. ' + core.ENDED_HINT, decided_for_user: st.decided_for_user } : {}),
|
|
69
|
+
run_id: st.run_id, state: st.state, session_id: st.session_id, timed_out: !!st.timed_out, error: st.error, final_text: st.final_text,
|
|
70
|
+
...(st.state === 'completed' && !st.decided_for_user ? { hint: core.ENDED_HINT } : {}),
|
|
71
|
+
...(st.needs_input ? { needs_input: st.needs_input, question: st.question, ...(st.question ? { relay: core.relayText(st.question) } : {}), hint: st.question ? 'The run asks the user something. If the user allowed you to decide, choose by your own judgment and answer with dsh_answer (or dsh-baton answer), passing reason, and tell the user what you chose and why. Otherwise show the user relay, written in the user\'s language, with its first line filled in with your own pick and a reason from your own judgment of the question and the task (harness_suggested is only the asker\'s pick, never a reason by itself), and ask the user first. Then wait again.' : 'The run waits for a person in the Harness UI. Tell the user, then wait again.' } : {}) })
|
|
69
72
|
process.exitCode = st.state === 'completed' ? 0 : st.needs_input ? 3 : 1
|
|
70
73
|
return
|
|
71
74
|
}
|
package/src/core.mjs
CHANGED
|
@@ -9,6 +9,7 @@ import net from 'node:net'
|
|
|
9
9
|
import { spawn, execFileSync } from 'node:child_process'
|
|
10
10
|
import { fileURLToPath } from 'node:url'
|
|
11
11
|
import { setting, batonHome, socketEndpoint, hostEndpoints } from '../host/lib/socket.js'
|
|
12
|
+
import * as evidence from './evidence.mjs'
|
|
12
13
|
|
|
13
14
|
const HERE = path.dirname(fileURLToPath(import.meta.url))
|
|
14
15
|
export const ROOT = path.resolve(HERE, '..')
|
|
@@ -526,6 +527,89 @@ async function useHost() {
|
|
|
526
527
|
return up
|
|
527
528
|
}
|
|
528
529
|
|
|
530
|
+
// Said with a finished run's reply: review from the evidence dsh-baton produced, read code only
|
|
531
|
+
// where it points, and send every fix back in one message.
|
|
532
|
+
export const REVIEW_REQUEST = '\n\n---\nWhen the work is done, start a read-only sub-agent to check it against every requirement above, then end your final reply with its table: requirement | met (yes / no / unclear) | evidence (file:line or test name). Fix anything marked no before replying.'
|
|
533
|
+
|
|
534
|
+
export const ENDED_HINT = 'evidence is produced by dsh-baton (files changed, checks it ran), not by the Harness reply: trust it over final_text. If a check failed, a requirement has no check, or a file the task needs is missing from evidence.changes, send all fixes back in one message to the same session, quoting the failing output; do not reproduce failures or write test scripts yourself. If every check passed and final_text ends with a review table whose rows are all met, accept it without reading code; read code only for rows marked no or unclear.'
|
|
535
|
+
|
|
536
|
+
// The asking model marks its favourite option in the label ("(Recommended)", "(推荐)").
|
|
537
|
+
// Clients relaying the question tended to repeat that mark as their own advice, so the
|
|
538
|
+
// label is cleaned and the mark moves to harness_suggested: what the asker suggests, kept
|
|
539
|
+
// apart from the recommendation the client has to form itself. Harness still matches a
|
|
540
|
+
// cleaned label when it is chosen by label.
|
|
541
|
+
const MARK = /\s*(?:\((?:recommended|推荐)\)|((?:recommended|推荐)))\s*/gi
|
|
542
|
+
const cleanLabel = (label) => String(label).replace(MARK, ' ').trim()
|
|
543
|
+
export function shapeQuestion(question) {
|
|
544
|
+
if (!Array.isArray(question?.questions)) return question
|
|
545
|
+
return {
|
|
546
|
+
...question,
|
|
547
|
+
questions: question.questions.map((q) => {
|
|
548
|
+
let suggested = null
|
|
549
|
+
const options = (q.options ?? []).map(({ recommended, ...o }) => {
|
|
550
|
+
const label = cleanLabel(o.label)
|
|
551
|
+
if (!suggested && (recommended || label !== o.label)) suggested = { number: o.number, label }
|
|
552
|
+
return { ...o, label }
|
|
553
|
+
})
|
|
554
|
+
return { ...q, options, ...(suggested ? { harness_suggested: suggested } : {}) }
|
|
555
|
+
}),
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
// The question laid out for the user, ready to show: the first line is left for the
|
|
559
|
+
// client's own recommendation, the asker's pick comes last and only as information.
|
|
560
|
+
// Weaker models fill in a template more reliably than they follow a paragraph of rules.
|
|
561
|
+
export function relayText(question) {
|
|
562
|
+
if (!Array.isArray(question?.questions)) return undefined
|
|
563
|
+
const blocks = question.questions.map((q, i) => {
|
|
564
|
+
const head = `${question.questions.length > 1 ? `${i + 1}. ` : ''}${q.question}${q.multi_select ? ' (several can be chosen)' : ''}`
|
|
565
|
+
const options = (q.options ?? []).map((o) => ` ${o.number}. ${o.label}${o.description ? ` - ${o.description}` : ''}`)
|
|
566
|
+
const asker = q.harness_suggested ? [` (The model in Harness that asked would pick: ${q.harness_suggested.label})`] : []
|
|
567
|
+
return [head, ...options, ...asker].join('\n')
|
|
568
|
+
})
|
|
569
|
+
return ['My recommendation: <your pick>, because <your own reason>', '', ...blocks].join('\n')
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
// When the client chose for the user (dsh_answer with reason), the choice and reason are
|
|
573
|
+
// kept until the run ends: the final wait result carries them, so the client tells the
|
|
574
|
+
// user then, instead of only passing on the reply. A file, because the client may wait
|
|
575
|
+
// from another process (wait_command).
|
|
576
|
+
const reasonsFile = () => path.join(config.batonHome, 'answer-reasons.json')
|
|
577
|
+
const readReasons = () => { try { return JSON.parse(fs.readFileSync(reasonsFile(), 'utf8')) } catch { return {} } }
|
|
578
|
+
function rememberReason(runId, answers, reason) {
|
|
579
|
+
try {
|
|
580
|
+
const all = readReasons()
|
|
581
|
+
all[runId] = { answers: (answers ?? []).map((a) => ({ id: a.id, selected: (a.selected ?? []).map(cleanLabel), ...(a.custom ? { text: a.custom } : {}) })), reason, at: Date.now() }
|
|
582
|
+
const kept = Object.entries(all).sort((x, y) => y[1].at - x[1].at).slice(0, 50)
|
|
583
|
+
ensurePrivateDir(config.batonHome)
|
|
584
|
+
fs.writeFileSync(reasonsFile(), JSON.stringify(Object.fromEntries(kept)), { mode: 0o600 })
|
|
585
|
+
} catch { /* the reason is a courtesy; answering never fails over it */ }
|
|
586
|
+
}
|
|
587
|
+
const ENDED = new Set(['completed', 'failed', 'cancelled', 'interrupted'])
|
|
588
|
+
const shaped = (st) => {
|
|
589
|
+
if (!st || typeof st !== 'object') return st
|
|
590
|
+
let out = st.question ? { ...st, question: shapeQuestion(st.question) } : st
|
|
591
|
+
const decided = ENDED.has(st.state) && st.run_id ? readReasons()[st.run_id] : null
|
|
592
|
+
if (decided) out = { ...out, decided_for_user: { answers: decided.answers, reason: decided.reason } }
|
|
593
|
+
return Array.isArray(st.answers) ? { ...out, answers: st.answers.map((a) => (Array.isArray(a?.selected) ? { ...a, selected: a.selected.map(cleanLabel) } : a)) } : out
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
// The folder a run works in: given with dsh_send, or that of its workspace or session.
|
|
597
|
+
async function runFolder(a, st) {
|
|
598
|
+
if (a.cwd) return path.resolve(a.cwd.replace(/^~(?=$|[\\/])/, os.homedir()))
|
|
599
|
+
if (st?.cwd) return st.cwd
|
|
600
|
+
try {
|
|
601
|
+
if (a.workspace_id) return (await api.workspaces()).find((w) => w.id === a.workspace_id)?.path
|
|
602
|
+
const sid = a.session_id ?? st?.session_id
|
|
603
|
+
if (sid) return (await api.list_sessions({ query: sid, limit: 5 })).find((x) => x.session_id === sid)?.cwd
|
|
604
|
+
} catch { /* no folder, no evidence */ }
|
|
605
|
+
return undefined
|
|
606
|
+
}
|
|
607
|
+
const withEvidence = (st) => {
|
|
608
|
+
if (!st || !ENDED.has(st.state) || !st.run_id) return st
|
|
609
|
+
const ev = evidence.collect(config.batonHome, st.run_id)
|
|
610
|
+
return ev ? { ...st, evidence: ev } : st
|
|
611
|
+
}
|
|
612
|
+
|
|
529
613
|
const tag = (backend, value) => (Array.isArray(value) ? value.map((v) => ({ ...v, backend })) : { ...value, backend })
|
|
530
614
|
|
|
531
615
|
export const api = {
|
|
@@ -543,16 +627,22 @@ export const api = {
|
|
|
543
627
|
async read_session(a) {
|
|
544
628
|
return (await useHost()) ? tag('host', await hostCall('read_session', a)) : tag('headless', readSession(a))
|
|
545
629
|
},
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
630
|
+
// checks stay here: dsh-baton runs them itself when the run ends (see evidence.mjs).
|
|
631
|
+
// A hand-over (a message with checks) also asks Harness to have a read-only sub-agent
|
|
632
|
+
// review the work against the spec and end with a table, so the client can decide from
|
|
633
|
+
// that table and the evidence instead of reading the code itself.
|
|
634
|
+
async send({ checks, ...a }) {
|
|
635
|
+
if (Array.isArray(checks) && checks.length && typeof a.message === 'string') a = { ...a, message: `${a.message}${REVIEW_REQUEST}` }
|
|
636
|
+
const st = (await useHost()) ? tag('host', await hostCall('send', a)) : tag('headless', await waitForSessionId(startRun(a)))
|
|
637
|
+
evidence.prepare(config.batonHome, { run_id: st.run_id, cwd: await runFolder(a, st), checks })
|
|
638
|
+
return st
|
|
549
639
|
},
|
|
550
640
|
async status({ run_id, tail = 20 }) {
|
|
551
|
-
return isHostRun(run_id) ? tag('host', await hostCall('status', { run_id, tail })) : tag('headless', runStatus(run_id, { tail }))
|
|
641
|
+
return withEvidence(shaped(isHostRun(run_id) ? tag('host', await hostCall('status', { run_id, tail })) : tag('headless', runStatus(run_id, { tail }))))
|
|
552
642
|
},
|
|
553
643
|
async wait({ run_id, timeout_s = 300 }) {
|
|
554
|
-
if (isHostRun(run_id)) return tag('host', await hostCall('wait', { run_id, timeout_s }, { timeoutMs: (timeout_s + 15) * 1000 }))
|
|
555
|
-
return tag('headless', await waitRun(run_id, { timeout_s }))
|
|
644
|
+
if (isHostRun(run_id)) return withEvidence(shaped(tag('host', await hostCall('wait', { run_id, timeout_s }, { timeoutMs: (timeout_s + 15) * 1000 }))))
|
|
645
|
+
return withEvidence(tag('headless', await waitRun(run_id, { timeout_s })))
|
|
556
646
|
},
|
|
557
647
|
async cancel({ run_id, session_id }) {
|
|
558
648
|
if (run_id && !isHostRun(run_id)) return tag('headless', cancelRun(run_id))
|
|
@@ -579,10 +669,15 @@ export const api = {
|
|
|
579
669
|
throw new Error(`The Harness plugin dsh-baton-host ${hostVersion ?? ''} is too old to change queued messages; this MCP server is ${VERSION}. Update the plugin in Harness: Plugins → dsh-baton-host → Uninstall, then Add plugin → dsh-baton-host@${VERSION}.`.replace(' ', ' '))
|
|
580
670
|
}
|
|
581
671
|
},
|
|
582
|
-
|
|
672
|
+
// reason (why the client chose, when the user let it decide) stays here: it is for the
|
|
673
|
+
// user, not for Harness.
|
|
674
|
+
async answer({ reason, ...a }) {
|
|
583
675
|
if (!(await useHost())) throw new Error('Answering a question needs the dsh-baton-host plugin running inside DeepSeek Harness.')
|
|
584
676
|
try {
|
|
585
|
-
|
|
677
|
+
const result = shaped(await hostCall('answer', a))
|
|
678
|
+
if (!(typeof reason === 'string' && reason.trim())) return result
|
|
679
|
+
if (result.submitted) rememberReason(a.run_id, result.answers, reason.trim())
|
|
680
|
+
return { ...result, reason: reason.trim() }
|
|
586
681
|
} catch (error) {
|
|
587
682
|
if (!/Unknown method: answer/.test(error?.message)) throw error
|
|
588
683
|
throw new Error(`The Harness plugin dsh-baton-host ${hostVersion ?? ''} is too old to answer questions; this MCP server is ${VERSION}. Answer in the Harness window, or update the plugin: Plugins → dsh-baton-host → Uninstall, then Add plugin → dsh-baton-host@${VERSION}.`.replace(' ', ' '))
|
|
@@ -591,6 +686,6 @@ export const api = {
|
|
|
591
686
|
async list_runs({ limit = 10, session_id } = {}) {
|
|
592
687
|
// An older plugin ignores session_id, so the host's runs are filtered here too.
|
|
593
688
|
const host = (await hostAvailable()) ? tag('host', await hostCall('list_runs', { limit: session_id ? 100 : limit, session_id })).filter((r) => !session_id || r.session_id === session_id) : []
|
|
594
|
-
return [...host, ...tag('headless', listRuns({ limit, session_id }))].sort((x, y) => String(y.started_at).localeCompare(String(x.started_at))).slice(0, limit)
|
|
689
|
+
return [...host, ...tag('headless', listRuns({ limit, session_id }))].sort((x, y) => String(y.started_at).localeCompare(String(x.started_at))).slice(0, limit).map(shaped)
|
|
595
690
|
},
|
|
596
691
|
}
|
package/src/evidence.mjs
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// Evidence for a finished run that does not come from the Harness model: which files the run
|
|
2
|
+
// created, changed or deleted (a snapshot of the folder taken at dsh_send, compared when the
|
|
3
|
+
// run ends), and the result of check commands the client gave with dsh_send, run here by
|
|
4
|
+
// dsh-baton in that folder. The Harness reply can say "all tests pass"; this says whether
|
|
5
|
+
// they do. Kept in a file per run, because the client may wait from another process.
|
|
6
|
+
import fs from 'node:fs'
|
|
7
|
+
import path from 'node:path'
|
|
8
|
+
import crypto from 'node:crypto'
|
|
9
|
+
import { spawnSync } from 'node:child_process'
|
|
10
|
+
|
|
11
|
+
const SKIP = new Set(['node_modules', '.git', '.hg', '.svn', 'dist', 'build', '.next', '.cache', 'coverage', '__pycache__', '.venv', 'venv', 'target'])
|
|
12
|
+
const MAX_FILES = 3000
|
|
13
|
+
const MAX_TEXT = 512 * 1024
|
|
14
|
+
const CHECK_TIMEOUT_MS = 120_000
|
|
15
|
+
const CHECKS_TOTAL_MS = 180_000
|
|
16
|
+
const TAIL_LINES = 15
|
|
17
|
+
|
|
18
|
+
const fileOf = (home, runId) => path.join(home, 'evidence', `${String(runId).replace(/[^\w.-]/g, '_')}.json`)
|
|
19
|
+
|
|
20
|
+
// path -> { hash, lines } for the files under dir (bounded; big or binary files keep only a hash).
|
|
21
|
+
function snapshot(dir) {
|
|
22
|
+
const files = {}
|
|
23
|
+
let count = 0, truncated = false
|
|
24
|
+
const walk = (d) => {
|
|
25
|
+
let entries = []
|
|
26
|
+
try { entries = fs.readdirSync(d, { withFileTypes: true }) } catch { return }
|
|
27
|
+
for (const e of entries) {
|
|
28
|
+
if (count >= MAX_FILES) { truncated = true; return }
|
|
29
|
+
const p = path.join(d, e.name)
|
|
30
|
+
if (e.isDirectory()) { if (!SKIP.has(e.name)) walk(p); continue }
|
|
31
|
+
if (!e.isFile()) continue
|
|
32
|
+
count++
|
|
33
|
+
try {
|
|
34
|
+
const buf = fs.readFileSync(p)
|
|
35
|
+
const text = buf.length <= MAX_TEXT && !buf.includes(0)
|
|
36
|
+
files[path.relative(dir, p).split(path.sep).join('/')] = {
|
|
37
|
+
hash: crypto.createHash('sha1').update(buf).digest('hex'),
|
|
38
|
+
lines: text ? (buf.length ? buf.toString('utf8').split('\n').length - (buf.at(-1) === 10 ? 1 : 0) : 0) : null,
|
|
39
|
+
}
|
|
40
|
+
} catch { /* unreadable: left out */ }
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
walk(dir)
|
|
44
|
+
return { files, truncated }
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function prepare(home, { run_id, cwd, checks }) {
|
|
48
|
+
if (!run_id || !cwd || !fs.existsSync(cwd)) return
|
|
49
|
+
try {
|
|
50
|
+
fs.mkdirSync(path.join(home, 'evidence'), { recursive: true, mode: 0o700 })
|
|
51
|
+
const list = Array.isArray(checks) ? checks.filter((c) => typeof c === 'string' && c.trim()).slice(0, 10) : []
|
|
52
|
+
fs.writeFileSync(fileOf(home, run_id), JSON.stringify({ cwd, checks: list, before: snapshot(cwd), at: Date.now() }), { mode: 0o600 })
|
|
53
|
+
// Keep the folder small: the 50 newest runs.
|
|
54
|
+
const dir = path.join(home, 'evidence')
|
|
55
|
+
const old = fs.readdirSync(dir).map((n) => ({ n, t: fs.statSync(path.join(dir, n)).mtimeMs })).sort((a, b) => b.t - a.t).slice(50)
|
|
56
|
+
for (const { n } of old) fs.rmSync(path.join(dir, n), { force: true })
|
|
57
|
+
} catch { /* evidence is extra; sending never fails over it */ }
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function runCheck(command, cwd, timeout) {
|
|
61
|
+
const t0 = Date.now()
|
|
62
|
+
const r = spawnSync(command, { cwd, shell: true, encoding: 'utf8', timeout, maxBuffer: 16 * 1024 * 1024, env: { ...process.env, CI: '1' } })
|
|
63
|
+
const out = `${r.stdout ?? ''}${r.stderr ? `\n${r.stderr}` : ''}`.trimEnd().split('\n')
|
|
64
|
+
return {
|
|
65
|
+
command,
|
|
66
|
+
exit_code: r.status,
|
|
67
|
+
passed: r.status === 0,
|
|
68
|
+
...(r.error?.code === 'ETIMEDOUT' || r.signal ? { timed_out: true } : {}),
|
|
69
|
+
seconds: Math.round((Date.now() - t0) / 100) / 10,
|
|
70
|
+
output_tail: out.slice(-TAIL_LINES).join('\n'),
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// The evidence for a run that ended, computed once and then read back.
|
|
75
|
+
export function collect(home, runId) {
|
|
76
|
+
const file = fileOf(home, runId)
|
|
77
|
+
let rec
|
|
78
|
+
try { rec = JSON.parse(fs.readFileSync(file, 'utf8')) } catch { return null }
|
|
79
|
+
if (rec.result) return rec.result
|
|
80
|
+
const after = snapshot(rec.cwd)
|
|
81
|
+
const before = rec.before.files
|
|
82
|
+
const created = [], modified = [], deleted = []
|
|
83
|
+
for (const [p, f] of Object.entries(after.files)) {
|
|
84
|
+
if (!before[p]) created.push({ path: p, lines: f.lines })
|
|
85
|
+
else if (before[p].hash !== f.hash) modified.push({ path: p, lines_before: before[p].lines, lines_after: f.lines })
|
|
86
|
+
}
|
|
87
|
+
for (const p of Object.keys(before)) if (!after.files[p]) deleted.push(p)
|
|
88
|
+
const checks = []
|
|
89
|
+
const deadline = Date.now() + CHECKS_TOTAL_MS
|
|
90
|
+
for (const c of rec.checks) {
|
|
91
|
+
const left = deadline - Date.now()
|
|
92
|
+
checks.push(left > 1000 ? runCheck(c, rec.cwd, Math.min(CHECK_TIMEOUT_MS, left)) : { command: c, skipped: 'out of time' })
|
|
93
|
+
}
|
|
94
|
+
const result = {
|
|
95
|
+
source: 'dsh-baton, not the Harness model',
|
|
96
|
+
changes: { created, modified, deleted, ...(after.truncated || rec.before.truncated ? { truncated: true } : {}) },
|
|
97
|
+
...(checks.length ? { checks, all_checks_passed: checks.every((c) => c.passed) } : {}),
|
|
98
|
+
}
|
|
99
|
+
try { fs.writeFileSync(file, JSON.stringify({ ...rec, before: undefined, result }), { mode: 0o600 }) } catch { /* recomputed next time */ }
|
|
100
|
+
return result
|
|
101
|
+
}
|
package/src/folder.mjs
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// The folder the client's conversation works in, so a new Harness session starts next to it
|
|
2
|
+
// instead of in a folder the model guessed (an old workspace from dsh_list_workspaces, or
|
|
3
|
+
// ~/.codex). Codex sends its thread id with every tool call; that thread's rollout file starts
|
|
4
|
+
// with a session_meta line that records the thread's cwd. The MCP server's own folder is not
|
|
5
|
+
// enough there: the Codex app starts it in one folder for all of its projects. Other clients
|
|
6
|
+
// (Claude Code) start the server in the project folder.
|
|
7
|
+
import fs from 'node:fs'
|
|
8
|
+
import os from 'node:os'
|
|
9
|
+
import path from 'node:path'
|
|
10
|
+
|
|
11
|
+
const codexHome = () => process.env.CODEX_HOME || path.join(os.homedir(), '.codex')
|
|
12
|
+
const DAYS_SEARCHED = 120
|
|
13
|
+
const found = new Map()
|
|
14
|
+
|
|
15
|
+
const newestFirst = (dir) => { try { return fs.readdirSync(dir).filter((n) => /^\d+$/.test(n)).sort().reverse() } catch { return [] } }
|
|
16
|
+
|
|
17
|
+
// sessions/<yyyy>/<mm>/<dd>/rollout-<time>-<thread id>.jsonl, newest days first.
|
|
18
|
+
function codexThreadCwd(threadId) {
|
|
19
|
+
if (!/^[\w-]+$/.test(threadId ?? '')) return undefined
|
|
20
|
+
if (found.has(threadId)) return found.get(threadId)
|
|
21
|
+
const root = path.join(codexHome(), 'sessions')
|
|
22
|
+
let days = 0
|
|
23
|
+
for (const y of newestFirst(root)) for (const m of newestFirst(path.join(root, y))) for (const d of newestFirst(path.join(root, y, m))) {
|
|
24
|
+
if (++days > DAYS_SEARCHED) return undefined
|
|
25
|
+
const dir = path.join(root, y, m, d)
|
|
26
|
+
const file = fs.readdirSync(dir).find((n) => n.endsWith(`-${threadId}.jsonl`))
|
|
27
|
+
if (!file) continue
|
|
28
|
+
try {
|
|
29
|
+
const fd = fs.openSync(path.join(dir, file), 'r')
|
|
30
|
+
const buf = Buffer.alloc(64 * 1024)
|
|
31
|
+
const n = fs.readSync(fd, buf, 0, buf.length, 0)
|
|
32
|
+
fs.closeSync(fd)
|
|
33
|
+
const cwd = JSON.parse(buf.subarray(0, n).toString('utf8').split('\n')[0]).payload?.cwd
|
|
34
|
+
if (typeof cwd === 'string' && cwd) { found.set(threadId, cwd); return cwd }
|
|
35
|
+
} catch { /* unreadable: fall back */ }
|
|
36
|
+
return undefined
|
|
37
|
+
}
|
|
38
|
+
return undefined
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// The server's own folder counts only when it looks like a project: not the home folder,
|
|
42
|
+
// not the file-system root and not a client's own settings folder.
|
|
43
|
+
function serverCwd() {
|
|
44
|
+
const cwd = process.cwd()
|
|
45
|
+
const home = os.homedir()
|
|
46
|
+
const real = (p) => { try { return fs.realpathSync(p) } catch { return p } }
|
|
47
|
+
const inside = (dir) => { const r = path.relative(real(dir), real(cwd)); return r === '' || (!r.startsWith('..') && !path.isAbsolute(r)) }
|
|
48
|
+
if (cwd === home || cwd === path.parse(cwd).root) return undefined
|
|
49
|
+
if (inside(codexHome()) || inside(path.join(home, '.claude'))) return undefined
|
|
50
|
+
return cwd
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function conversationFolder(meta, isCodex) {
|
|
54
|
+
if (isCodex) {
|
|
55
|
+
const threadId = meta?.['x-codex-turn-metadata']?.thread_id ?? meta?.threadId
|
|
56
|
+
const cwd = codexThreadCwd(threadId)
|
|
57
|
+
if (cwd) return cwd
|
|
58
|
+
}
|
|
59
|
+
return serverCwd()
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const norm = (p) => {
|
|
63
|
+
const r = path.resolve(p.replace(/^~(?=$|[\\/])/, os.homedir()))
|
|
64
|
+
return process.platform === 'win32' || process.platform === 'darwin' ? r.toLowerCase() : r
|
|
65
|
+
}
|
|
66
|
+
// True when folder is the conversation's folder or inside it.
|
|
67
|
+
export function within(folder, conversation) {
|
|
68
|
+
const r = path.relative(norm(conversation), norm(folder))
|
|
69
|
+
return r === '' || (!r.startsWith('..') && !path.isAbsolute(r))
|
|
70
|
+
}
|