dsh-baton-mcp 0.6.15 → 0.6.17

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
@@ -26,7 +26,7 @@
26
26
 
27
27
  Hand coding tasks from Claude Code, Codex or Antigravity to DeepSeek Harness on your machine: the task runs live in the Harness window, the main agent hears back once when it ends, and it gets back the files that changed, the project's own test results and a requirement-by-requirement checklist.
28
28
 
29
- - **Watch it and step in:** the task runs live in the Harness window and you can type into it at any time. Every message is labelled "Sent by Claude / ChatGPT / Antigravity from another chat". When Harness stops to ask a question, the main agent answers it if you told it to decide, or brings it to you with its own recommendation.
29
+ - **Watch it and step in:** the task runs live in the Harness window and you can type into it at any time. Every message is labelled "Sent by Claude / ChatGPT / Antigravity from another chat". When Harness stops to ask a question, the main agent brings it to you.
30
30
  - **Less of the 5-hour window:** a long Codex job takes 16% of a ChatGPT Plus 5-hour window instead of 86% (GPT-6 Astra, the kanban task). The rest of the numbers are under [Token usage](#token-usage).
31
31
  - **Nothing to watch or poll:** the main agent waits without polling and gets the result when the run ends. With several runs going at once, each one comes back within a second of finishing.
32
32
 
@@ -47,7 +47,7 @@ dsh-baton is an MCP server plus a small Harness plugin. The main agent hands the
47
47
  | You can step in mid-run | **Yes, in Harness, or the main agent steers it in** | Yes | Usually not |
48
48
  | Each message says who sent it | **Yes, sent by ChatGPT / Claude** | One side only | Not needed |
49
49
  | Changed files and test results come back | **dsh-baton lists the files and runs your tests itself** | No hand-over step | The sub-agent's own summary |
50
- | Questions reach you | **Yes, with the main agent's recommendation** | It asks you directly | Usually not |
50
+ | Questions reach you | **Yes, through the main agent** | It asks you directly | Usually not |
51
51
 
52
52
  <p align="center"><picture><source media="(prefers-color-scheme: dark)" srcset="./assets/readme/en/divider-dark.svg"><img src="./assets/readme/en/divider.svg" width="100%" alt=""></picture></p>
53
53
 
@@ -197,9 +197,9 @@ Working alone, Astra rated its own work 23/23; the independent check found 17/23
197
197
 
198
198
  **Approvals:** a task sent through dsh-baton was already handed over by Claude Code, Codex or Antigravity, so an approval Harness asks for during a hand-over run is allowed at once, and the reply lists each one (`approvals_allowed`). A call Harness's Auto review mode turned down is never allowed this way; it waits for you in Harness, and so does every approval when the settings file cannot be read. On the plugin page, **Hand-over approvals** → **Leave them to me in Harness** makes every approval wait for you; the reply then says the run needs you in Harness.
199
199
 
200
- **Git worktrees:** when the session moves to a new Git worktree (Harness's Git worktree plugin), the evidence lists that worktree's branch, commits and changed files under `worktrees`, and the checks run there. Merging the branch is up to you.
200
+ **Questions:** when Harness asks you something during a hand-over, the question comes back to the main agent, which asks you its own way (its question card, or a message) and sends your answer to Harness. You can also answer in the Harness window.
201
201
 
202
- **Answering Harness's questions:** the main agent answers the way the task needs, rather than picking the least bad option. See `dsh_answer` under [Tools](#tools).
202
+ **Git worktrees:** when the session moves to a new Git worktree (Harness's Git worktree plugin), the evidence lists that worktree's branch, commits and changed files under `worktrees`, and the checks run there. Merging the branch is up to you.
203
203
 
204
204
  **Several runs at once.** When a task is split across sessions, the main agent sends them all and waits for them together; whichever ends first comes back first, so it can review it and send a fix while the rest still run.
205
205
 
@@ -250,10 +250,10 @@ The server's MCP instructions are a single sentence; how to hand over, wait and
250
250
  | `dsh_list_sessions` | Sessions newest first, with title, folder, running state and `model` (what its next request uses); filter by folder or text. Archived sessions are left out |
251
251
  | `dsh_list_models` | The models Harness can run (provider, id, name, reasoning efforts) and its default model |
252
252
  | `dsh_read_session` | Recent prompts and replies of one session (with tool names); `archived: true` for an archived session |
253
- | `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`). A `cwd` inside the conversation's folder joins that folder's workspace instead of getting one of its own: the session opens in the conversation's folder and the message names the subfolder (`work_folder`), where `checks` run. Folders a client makes per conversation share one workspace each: Codex chats without a project (Codex chats), Claude scratch folders (Claude scratch), Codex worktrees (Codex worktrees) and a project's Claude worktrees (Claude worktrees). A folder that is a workspace already, or a Git worktree, keeps its own. `checks`: test commands dsh-baton runs itself when the run ends (see [How a hand-over is checked](#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. `model` only when the user names one ("DeepSeek-V4 Pro", "v4-pro"; `reasoning_effort` likewise): it is matched against Harness's own model list, ignoring case, spaces, hyphens and a leading DeepSeek, so a model Harness adds later (V4.1 Pro) works as soon as Harness lists it; a name that matches nothing or several fails the send, before anything is created, with the list (`provider/model` picks one). It is set on that session before the message goes in, and Harness's default model is put back as it was (Harness saves a session's pick as the default too). Left out, a continued session keeps its own model and a new one uses the hand-over default from the plugin page, else Harness's default. The reply says which in `model` and `model_source` (`requested`, `handover_default`, `default` or `session`), and `model_note` says when a hand-over default was skipped or Harness's default changed since the last new hand-over. `team` (Harness 0.2.2-rc.2 or later): `true` turns Agent Teams on for the session before the message goes in, `false` turns them off; refused, with nothing sent, on an older Harness or on a sub-agent's session |
253
+ | `dsh_send` | Send a message: `session_id` continues that session. Without it, a task for a folder where this conversation already has an idle session continues that session, so Harness keeps the earlier context (`continued_session` says so; `new_session` `true` starts a fresh one); a busy session is never reused, so parts sent in parallel get a session each. 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`). A `cwd` inside the conversation's folder joins that folder's workspace instead of getting one of its own: the session opens in the conversation's folder and the message names the subfolder (`work_folder`), where `checks` run. Folders a client makes per conversation share one workspace each: Codex chats without a project (Codex chats), Claude scratch folders (Claude scratch), Codex worktrees (Codex worktrees) and a project's Claude worktrees (Claude worktrees). A folder that is a workspace already, or a Git worktree, keeps its own. `checks`: test commands dsh-baton runs itself when the run ends (see [How a hand-over is checked](#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. `model` only when the user names one ("DeepSeek-V4 Pro", "v4-pro"; `reasoning_effort` likewise): it is matched against Harness's own model list, ignoring case, spaces, hyphens and a leading DeepSeek, so a model Harness adds later (V4.1 Pro) works as soon as Harness lists it; a name that matches nothing or several fails the send, before anything is created, with the list (`provider/model` picks one). It is set on that session before the message goes in, and Harness's default model is put back as it was (Harness saves a session's pick as the default too). Left out, a continued session keeps its own model and a new one uses the hand-over default from the plugin page, else Harness's default. The reply says which in `model` and `model_source` (`requested`, `handover_default`, `default` or `session`), and `model_note` says when a hand-over default was skipped or Harness's default changed since the last new hand-over. `team` (Harness 0.2.2-rc.2 or later): `true` turns Agent Teams on for the session before the message goes in, `false` turns them off; refused, with nothing sent, on an older Harness or on a sub-agent's session |
254
254
  | `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; `model` the run was sent with. With `session_id` instead of `run_id`: what the session is doing, its Harness goal and its last turn's reply |
255
- | `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 3540 s per call for Codex (its tool timeout for dsh-baton less 60 s; 270 s when that is not set), 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. A run in a session with a Harness goal is waited for until the goal stops (`until` `turn` and `every_minutes` for progress reports). With `session_id` instead of `run_id` it follows the session's Harness goal without sending anything (`until`, `cursor`, `every_minutes`; see How each client waits). With `run_ids` it waits for several runs and returns as soon as any ends or asks (`ended`, `still_running`) |
256
- | `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; on a single choice, free text replaces the option. `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`) and a layout for passing them on (`relay`, `question_tool`). When you let the main agent decide, it takes an option only if it fits as written, and otherwise answers in its own words; before it picks an option for you, the first call is held back and it writes the answer you would want without the options, sending the option only if the two agree. Otherwise it brings you the questions with its recommendation first, which may be an answer outside the options; pick that and only the answer itself is sent. You can also answer in the Harness window: whoever answers first wins |
255
+ | `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 3540 s per call for Codex (its tool timeout for dsh-baton less 60 s; 270 s when that is not set), 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; for a run a background `wait_command` already waits for, `dsh_wait` returns at once (`waiting_in_background`) rather than waiting a second time. `dsh_status` is a one-off look, not a way to wait. A run in a session with a Harness goal is waited for until the goal stops (`until` `turn` and `every_minutes` for progress reports). With `session_id` instead of `run_id` it follows the session's Harness goal without sending anything (`until`, `cursor`, `every_minutes`; see How each client waits). With `run_ids` it waits for several runs and returns as soon as any ends or asks (`ended`, `still_running`) |
256
+ | `dsh_answer` | Send your answer to the questions a run stopped to ask (Harness's ask_user_question): per question, an option number or label, free text, or skip; on a single choice, free text replaces the option. `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`); the main agent asks you and sends your answer. You can also answer in the Harness window: whoever answers first wins |
257
257
  | `dsh_session_activity` | Codex: through `dsh_call`. What a session is doing now: running turn, sub-agents (any depth), background jobs; `archived: true` for an archived session |
258
258
  | `dsh_update_queued` | Codex: through `dsh_call`. 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 |
259
259
  | `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` |
@@ -339,7 +339,7 @@ Version history is on [GitHub Releases](https://github.com/JialaoLiu/dsh-baton/r
339
339
 
340
340
  **`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.
341
341
 
342
- **Updating.** On Harness 0.2.2 and later: Plugins → dsh-baton-host → **Update to x.y.z** (更新到) under Version; if it still says up to date, press **Check again** (重新检查) first. Harness 0.2.1 has no update button for this plugin: **Uninstall**, then **Add plugin** → `dsh-baton-host`. For about a day 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@x.y.z`. A pre-release must always be added by its exact version, such as `dsh-baton-host@0.6.0-next.0`: Harness resolves `@next` to a broken placeholder. Plain `dsh-baton-host` gets the latest release. 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, naming the older side and the newer side's exact version to install.
342
+ **Updating.** On Harness 0.2.1-rc.5 and later: Plugins → dsh-baton-host → **Update to x.y.z** (更新到) under Version; if it still says up to date, press **Check again** (重新检查) first. On older 0.2.1 builds without that button: **Uninstall**, then **Add plugin** → `dsh-baton-host`. For about a day 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@x.y.z`. A pre-release must always be added by its exact version, such as `dsh-baton-host@0.6.0-next.0`: Harness resolves `@next` to a broken placeholder. Plain `dsh-baton-host` gets the latest release. 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, naming the older side and the newer side's exact version to install.
343
343
 
344
344
  **Removing.** Harness → Plugins → dsh-baton-host → **Uninstall**, then `npx -y dsh-baton-mcp setup --remove`. The plugin cannot tell an uninstall from Harness quitting, so it leaves the MCP entries to that command, which also deletes `~/.dsh-baton/app`; run records stay in `~/.dsh-baton` until you delete it.
345
345
 
package/README.zh-CN.md CHANGED
@@ -26,7 +26,7 @@
26
26
 
27
27
  把 Claude Code、Codex 或 Antigravity 的编码任务交给本机的 DeepSeek Harness:任务在 Harness 界面里实时跑,跑完主 Agent 收到一次结果,带回改了哪些文件、项目自己的测试结果,以及逐条需求对照表。
28
28
 
29
- - **看得见、能插话**:任务在 Harness 界面里实时跑,你随时能插话;每条消息都标着“由 Claude / ChatGPT / Antigravity 从另一个聊天发送”。Harness 中途提问时,你让主 Agent 自己决定的,它直接回答;否则它带着自己的建议把问题转给你。
29
+ - **看得见、能插话**:任务在 Harness 界面里实时跑,你随时能插话;每条消息都标着“由 Claude / ChatGPT / Antigravity 从另一个聊天发送”。Harness 中途提问时,主 Agent 把问题转给你。
30
30
  - **省额度**:Codex 长任务占 ChatGPT Plus 5 小时额度,从 86% 降到 16%(GPT-6 Astra,看板案例)。其他数字在 [Token 用量实测](#token-用量实测)。
31
31
  - **不用盯**:主 Agent 等着结果、不轮询,做完就交回;几个任务同时跑时,每个做完 1 秒内就拿到。
32
32
 
@@ -47,7 +47,7 @@ dsh-baton 是一个 MCP 服务器加一个 Harness 小插件。主 Agent 用一
47
47
  | 能中途插话 | **能,在 Harness 里直接说,或由主 Agent 插队** | 能 | 通常不能 |
48
48
  | 消息标明是谁发的 | **每条都标着由 ChatGPT / Claude 发送** | 只有一方 | 不需要 |
49
49
  | 做完带回改动文件和测试结果 | **dsh-baton 自己列出改动文件、跑项目测试** | 没有交接这一步 | 子代理自己写的总结 |
50
- | 提问能转给你 | **能,主 Agent 带着建议转给你** | 直接问你 | 通常不能 |
50
+ | 提问能转给你 | **能,经主 Agent 转给你** | 直接问你 | 通常不能 |
51
51
 
52
52
  <p align="center"><picture><source media="(prefers-color-scheme: dark)" srcset="./assets/readme/zh/divider-dark.svg"><img src="./assets/readme/zh/divider.svg" width="100%" alt=""></picture></p>
53
53
 
@@ -81,7 +81,7 @@ dsh-baton 是一个 MCP 服务器加一个 Harness 小插件。主 Agent 用一
81
81
 
82
82
  就这些。要转交任务,在需求最后加一句“交给 DeepSeek Harness 去做”。更新、卸载、Windows,以及插件没能注册时怎么手动注册,在[后面](#安装细节)。
83
83
 
84
- **刚发版就安装?** 新版本发布后大约一天内,Harness 会装上一个版本,安装弹窗里会说明。打开插件详情页点 **更新到 x.y.z**,或者添加插件时带上版本号,比如 `dsh-baton-host@x.y.z`。
84
+ **刚发版就安装?** 新版本发布后大约一天内,Harness 装的是上一个版本,安装弹窗里会说明。打开插件详情页点 **更新到 x.y.z**,或者添加插件时带上版本号,比如 `dsh-baton-host@x.y.z`。
85
85
 
86
86
  <p align="center"><picture><source media="(prefers-color-scheme: dark)" srcset="./assets/readme/zh/divider-dark.svg"><img src="./assets/readme/zh/divider.svg" width="100%" alt=""></picture></p>
87
87
 
@@ -197,9 +197,9 @@ Codex 占 ChatGPT Plus 5 小时额度的比例,以及主 Agent 自己的花费
197
197
 
198
198
  **审批**:经 dsh-baton 转交的任务已经由 Claude Code、Codex 或 Antigravity 交代过,所以转交过程中 Harness 弹出的审批会直接放行,回复里会逐条列出放行了什么(`approvals_allowed`)。Harness「自动审查」模式拒掉的调用不会这样放行,仍在 Harness 里等你处理;设置文件读不了时,所有审批也都等你处理。插件页的**转交会话里的审批**选**交给我在 Harness 里处理**后,所有审批都等你点,回复会说这个转交在等你。
199
199
 
200
- **Git 工作树**:会话切到新的 Git 工作树时(Harness 的「Git 工作树」插件),证据里的 `worktrees` 会列出这个工作树的分支、提交和改动文件,检查也在那里跑。要不要合并分支由你决定。
200
+ **提问**:转交过程中 Harness 向你提问时,问题会回到主 Agent,由它用自己的方式问你(它自己的问题卡片或一条消息),再把你的回答发给 Harness。你也可以直接在 Harness 窗口里回答。
201
201
 
202
- **回答 Harness 的提问**:主 Agent 按任务真正需要的答案来回答,不会在几个都不合适的选项里挑一个凑合。细节见[完整工具说明](#工具)里的 `dsh_answer`。
202
+ **Git 工作树**:会话切到新的 Git 工作树时(Harness 的「Git 工作树」插件),证据里的 `worktrees` 会列出这个工作树的分支、提交和改动文件,检查也在那里跑。要不要合并分支由你决定。
203
203
 
204
204
  **同时等多个任务**。一个任务拆给几个会话做时,主 Agent 全部发出去再一起等;哪个先做完就先拿到哪个,马上检查、发返修,其他的接着跑。
205
205
 
@@ -250,10 +250,10 @@ Codex 占 ChatGPT Plus 5 小时额度的比例,以及主 Agent 自己的花费
250
250
  | `dsh_list_sessions` | 列出对话(最新在前),带标题、目录、是否在跑和 `model`(下一次请求用的模型);可按目录或关键字过滤。已归档的对话不会列出 |
251
251
  | `dsh_list_models` | 列出 Harness 能用的模型(provider、id、名称、推理强度)和它的默认模型 |
252
252
  | `dsh_read_session` | 读某个对话最近的消息和回复(含用到的工具名);已归档的对话会带 `archived: true` |
253
- | `dsh_send` | 发消息。带 `session_id` 续接那个对话;否则新开对话,建在 `cwd` 或 `workspace_id` 指定的位置,都不带时建在当前对话所在的文件夹(`cwd` 还不是工作区时会先登记;指定的 `cwd` 在当前对话文件夹之外也可以,结果里的 `folder_note` 会提醒)。`cwd` 在当前对话文件夹里面时,不再单独建工作区,而是进当前对话文件夹的工作区:对话开在那个文件夹,消息里写明要在哪个子文件夹工作(`work_folder`),`checks` 也在子文件夹里跑。客户端给每个对话单独建的文件夹各自共用一个工作区:Codex 没选项目的对话(Codex chats)、Claude 的 scratch 文件夹(Claude scratch)、Codex 的 worktree(Codex worktrees)、同一项目的 Claude worktree(Claude worktrees)。本来就是工作区的文件夹,或者 Git worktree,仍用它自己的工作区。`checks`:运行结束后 dsh-baton 自己跑的测试命令(见[转交之后怎么验收](#转交之后怎么验收))。立即返回 `run_id`。Harness 里这条消息会标注「由 Claude / ChatGPT 从另一个聊天发送」。已归档的对话会被拒绝:先在 Harness 里取消归档,或新开对话。对话正忙时,`mode` 为 `followup` 会排在当前回合之后,`steer` 会插进正在跑的回合;不传时跟随 Harness 自己的设置(设置 → 繁忙时的发送行为:排队发送或插话发送),读不到设置时按 `followup`。返回里的 `mode_source` 说明用的是哪种。`model` 只在用户点名模型时传(如“DeepSeek-V4 Pro”“v4-pro”;`reasoning_effort` 同理):按 Harness 自己的模型列表匹配,不分大小写,忽略空格、连字符和开头的 DeepSeek,所以 Harness 以后上线的模型(如 V4.1 Pro)一出现在列表里就能用;匹配不到或匹配到多个时,发送直接失败、什么都不创建,并列出可用模型(用 `provider/model` 指定其一)。模型在消息发出前设到该对话上,Harness 的默认模型会恢复原样(Harness 会把对话里选的模型同时存成默认)。不传时,续接的对话沿用它自己的模型,新对话用插件页的转交默认模型,没设就用 Harness 默认模型。返回值的 `model` 和 `model_source`(`requested`、`handover_default`、`default` 或 `session`)写明用的是哪个;转交默认模型用不上,或 Harness 的默认模型和上一次新开转交时不一样时,`model_note` 会说明。`team`(需要 Harness 0.2.2-rc.2 及以上):`true` 在消息发出前为该对话打开智能体团队协作,`false` 关闭;Harness 版本太旧或传的是子智能体的对话时,直接拒绝、什么都不发 |
253
+ | `dsh_send` | 发消息。带 `session_id` 续接那个对话。不带时,如果当前对话在这个文件夹里已经有一个空闲的对话,就续接它,Harness 保留之前的上下文(结果里的 `continued_session` 会说明;`new_session` 为 `true` 时新开一个);正忙的对话不会被续接,所以并行发出的几部分仍各开一个对话。其余情况新开对话,建在 `cwd` 或 `workspace_id` 指定的位置,都不带时建在当前对话所在的文件夹(`cwd` 还不是工作区时会先登记;指定的 `cwd` 在当前对话文件夹之外也可以,结果里的 `folder_note` 会提醒)。`cwd` 在当前对话文件夹里面时,不再单独建工作区,而是进当前对话文件夹的工作区:对话开在那个文件夹,消息里写明要在哪个子文件夹工作(`work_folder`),`checks` 也在子文件夹里跑。客户端给每个对话单独建的文件夹各自共用一个工作区:Codex 没选项目的对话(Codex chats)、Claude 的 scratch 文件夹(Claude scratch)、Codex 的 worktree(Codex worktrees)、同一项目的 Claude worktree(Claude worktrees)。本来就是工作区的文件夹,或者 Git worktree,仍用它自己的工作区。`checks`:运行结束后 dsh-baton 自己跑的测试命令(见[转交之后怎么验收](#转交之后怎么验收))。立即返回 `run_id`。Harness 里这条消息会标注「由 Claude / ChatGPT 从另一个聊天发送」。已归档的对话会被拒绝:先在 Harness 里取消归档,或新开对话。对话正忙时,`mode` 为 `followup` 会排在当前回合之后,`steer` 会插进正在跑的回合;不传时跟随 Harness 自己的设置(设置 → 繁忙时的发送行为:排队发送或插话发送),读不到设置时按 `followup`。返回里的 `mode_source` 说明用的是哪种。`model` 只在用户点名模型时传(如“DeepSeek-V4 Pro”“v4-pro”;`reasoning_effort` 同理):按 Harness 自己的模型列表匹配,不分大小写,忽略空格、连字符和开头的 DeepSeek,所以 Harness 以后上线的模型(如 V4.1 Pro)一出现在列表里就能用;匹配不到或匹配到多个时,发送直接失败、什么都不创建,并列出可用模型(用 `provider/model` 指定其一)。模型在消息发出前设到该对话上,Harness 的默认模型会恢复原样(Harness 会把对话里选的模型同时存成默认)。不传时,续接的对话沿用它自己的模型,新对话用插件页的转交默认模型,没设就用 Harness 默认模型。返回值的 `model` 和 `model_source`(`requested`、`handover_default`、`default` 或 `session`)写明用的是哪个;转交默认模型用不上,或 Harness 的默认模型和上一次新开转交时不一样时,`model_note` 会说明。`team`(需要 Harness 0.2.2-rc.2 及以上):`true` 在消息发出前为该对话打开智能体团队协作,`false` 关闭;Harness 版本太旧或传的是子智能体的对话时,直接拒绝、什么都不发 |
254
254
  | `dsh_status` | 查看运行进度:状态、最近的文字和工具调用、最终回复;回合结束但子智能体/后台任务还在跑时给出 `waiting_on`;中途有人在 Harness 界面里发消息时给出 `human_interjections`;被 Harness 重启打断的任务状态为 `interrupted`;以及这次运行发送时用的 `model`。用 `session_id` 代替 `run_id` 时:会话正在做什么、它的 Harness 目标,以及上一回合的回复 |
255
- | `dsh_wait` | 等运行结束;发消息时带了 `checks` 的,结束后会附上 `evidence`(改了哪些文件、测试结果)(或者等到它停下来问人,见 `dsh_answer`):Codex 每次最多等 3540 秒(它对 dsh-baton 的工具超时减 60 秒;没设时 270 秒),其他客户端 50 秒。没做完会带 `timed_out`,只返回状态,再调用一次即可。能在后台等待的客户端改用 `dsh_send` 返回的 `wait_command`。`dsh_status` 只用来看一眼,不用来等待。发到带 Harness 目标的会话的任务会一直等到目标停下(要汇报进度时用 `until` 为 `turn` 和 `every_minutes`)。用 `session_id` 代替 `run_id` 时,不发任何消息,跟进这个会话的 Harness 目标(`until`、`cursor`、`every_minutes`;见“各客户端怎么等待”)。用 `run_ids` 时同时等多个任务,任何一个做完或提问就返回(`ended`、`still_running`) |
256
- | `dsh_answer` | 回答运行中途提出的问题(Harness 的 ask_user_question):每道题可以填选项编号或选项文字、自由填写,或者跳过;单选题填了文字就以文字为准。运行一提问,`dsh_wait` 和 `wait_command` 就立刻返回,带上题目(`needs_input`、`question`;Harness 模型推荐的选项在 `harness_suggested`)和转给你时用的排版(`relay`、`question_tool`)。你让主 Agent 自己决定时,选项照原文正好合适它才选,否则用自己的话回答;要替你选某个选项时,第一次调用不会发出,它得先不看选项写出你想要的答案,两者一致才发。没让它决定时,它把题目转给你,开头先写它的建议,建议可以不在选项里;你选了这条建议,就只发这条答案。你也可以直接在 Harness 窗口里回答,谁先答就算谁的 |
255
+ | `dsh_wait` | 等运行结束;发消息时带了 `checks` 的,结束后会附上 `evidence`(改了哪些文件、测试结果)(或者等到它停下来问人,见 `dsh_answer`):Codex 每次最多等 3540 秒(它对 dsh-baton 的工具超时减 60 秒;没设时 270 秒),其他客户端 50 秒。没做完会带 `timed_out`,只返回状态,再调用一次即可。能在后台等待的客户端改用 `dsh_send` 返回的 `wait_command`;某个任务已经有后台 `wait_command` 在等时,`dsh_wait` 会立即返回(`waiting_in_background`),不再重复等待。`dsh_status` 只用来看一眼,不用来等待。发到带 Harness 目标的会话的任务会一直等到目标停下(要汇报进度时用 `until` 为 `turn` 和 `every_minutes`)。用 `session_id` 代替 `run_id` 时,不发任何消息,跟进这个会话的 Harness 目标(`until`、`cursor`、`every_minutes`;见“各客户端怎么等待”)。用 `run_ids` 时同时等多个任务,任何一个做完或提问就返回(`ended`、`still_running`) |
256
+ | `dsh_answer` | 把你对运行中途提问的回答发回去(Harness 的 ask_user_question):每道题可以填选项编号或选项文字、自由填写,或者跳过;单选题填了文字就以文字为准。运行一提问,`dsh_wait` 和 `wait_command` 就立刻返回,带上题目(`needs_input`、`question`;Harness 模型推荐的选项在 `harness_suggested`),由主 Agent 问你并把你的回答发回去。你也可以直接在 Harness 窗口里回答,谁先答就算谁的 |
257
257
  | `dsh_session_activity` | Codex 里经 `dsh_call` 调用。对话此刻在做什么:正在跑的回合、子智能体(任意层级)、后台任务;已归档的对话会带 `archived: true` |
258
258
  | `dsh_update_queued` | Codex 里经 `dsh_call` 调用。按 `run_id` 修改还在忙碌对话队列里等待的消息:`edit` 改文字,`remove` 撤回,`steer` 立刻插进正在跑的回合。消息一旦进入对话就改不了了 |
259
259
  | `dsh_cancel` | 按 `run_id` 或 `session_id` 停掉整个对话的工作:当前回合、子智能体、后台任务。Harness 会同时清掉队列里等待的消息,这些运行记为 `cancelled` |
@@ -339,7 +339,7 @@ Harness 插件连不上时:
339
339
 
340
340
  **`npx -y dsh-baton-mcp setup`** 在终端里做同样的注册:用于插件没能注册的情况,或者从 MCP 目录过来的用户。插件已经注册过时它什么都不改;插件没装的话,它会提示去添加。
341
341
 
342
- **更新**。Harness 0.2.2 及以上:插件 → dsh-baton-host → 版本一栏里的 **更新到 x.y.z**;如果还显示已是最新版本,先点 **重新检查**。Harness 0.2.1 没有这个插件的更新按钮:**卸载**,再**添加插件** → `dsh-baton-host`。新版本发布后大约一天内,Harness 会装上一个版本(pnpm 的 `minimumReleaseAge` 会暂缓刚发布的版本,安装弹窗里会说明);想马上用新版,输入带版本号的名字:`dsh-baton-host@x.y.z`。预发布版必须写确切版本号添加,比如 `dsh-baton-host@0.6.0-next.0`:Harness 会把 `@next` 解析成一个坏掉的占位包。只输入 `dsh-baton-host` 装的是最新正式版。重新启用后,插件会把 MCP 服务器也更新到同一版本,新开的对话就会用上。万一两边版本对不上,第一次发现不一致的工具调用会提示,并写明哪一边旧、另一边的确切版本号。
342
+ **更新**。Harness 0.2.1-rc.5 及以上:插件 → dsh-baton-host → 版本一栏里的 **更新到 x.y.z**;如果还显示已是最新版本,先点 **重新检查**。更早的 0.2.1 没有这个按钮的话:**卸载**,再**添加插件** → `dsh-baton-host`。新版本发布后大约一天内,Harness 装的是上一个版本(pnpm 的 `minimumReleaseAge` 会暂缓刚发布的版本,安装弹窗里会说明);想马上用新版,输入带版本号的名字:`dsh-baton-host@x.y.z`。预发布版必须写确切版本号添加,比如 `dsh-baton-host@0.6.0-next.0`:Harness 会把 `@next` 解析成一个坏掉的占位包。只输入 `dsh-baton-host` 装的是最新正式版。重新启用后,插件会把 MCP 服务器也更新到同一版本,新开的对话就会用上。万一两边版本对不上,第一次发现不一致的工具调用会提示,并写明哪一边旧、另一边的确切版本号。
343
343
 
344
344
  **卸载**。Harness → 插件 → dsh-baton-host → **卸载**,再运行 `npx -y dsh-baton-mcp setup --remove`。插件分不清"被卸载"和"Harness 退出",所以 MCP 注册交给这条命令删,它也会删掉 `~/.dsh-baton/app`;运行记录留在 `~/.dsh-baton`,不需要的话自己删掉。
345
345
 
package/host/lib/index.js CHANGED
@@ -19,11 +19,15 @@ export const inject = ['sessionController', 'workspaceRegistry']
19
19
 
20
20
  const VERSION = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version
21
21
  const MAX_EVENTS = 200
22
+ const admitWaitMs = () => Number(process.env.DSH_BATON_ADMIT_WAIT_MS) || 10_000
22
23
  const MAX_RUNS = 100
23
24
  const QUIET_CONFIRM_MS = 2000
24
25
  const CANCEL_ATTEMPTS = 3
25
26
  const CANCEL_SETTLE_MS = 6000
26
27
  const ACTIVITY_MAX_ERRORS = 10
28
+ // A run taken up after a plugin reload whose message Harness had not admitted yet.
29
+ const TAKE_UP_RETRY_MS = 3000
30
+ const takeUpAdmitMs = () => Number(process.env.DSH_BATON_TAKE_UP_ADMIT_MS) || 5 * 60_000
27
31
  const MAX_REQUEST_BYTES = 4 * 1024 * 1024
28
32
  const MAX_WAIT_S = 24 * 3600
29
33
  const MAX_HUMAN_INPUTS = 10
@@ -333,8 +337,10 @@ export function apply(ctx) {
333
337
  if (again.size) store.timer = setTimeout(guard('persist runs', flushRuns), PERSIST_DELAY_MS)
334
338
  }
335
339
 
336
- // Load earlier records. A run that was active when Harness went away cannot
337
- // finish any more (Harness ends the turn on restart), so it is marked interrupted.
340
+ // Load earlier records. A run that was active when the plugin went away is taken up again
341
+ // when its session is still at work: the plugin was reloaded (switched off and on, or
342
+ // updated) while Harness kept running. Otherwise it cannot finish any more (Harness ends the
343
+ // turn on restart), so it is marked interrupted.
338
344
  function enableStore() {
339
345
  fs.mkdirSync(store.dir, { recursive: true, mode: 0o700 })
340
346
  if (!IS_WIN) fs.chmodSync(store.dir, 0o700)
@@ -350,15 +356,53 @@ export function apply(ctx) {
350
356
  loaded.sort((a, b) => String(a.startedAt).localeCompare(String(b.startedAt)))
351
357
  for (const old of loaded.splice(0, Math.max(0, loaded.length - MAX_RUNS))) fs.rmSync(path.join(store.dir, `${old.id}.json`), { force: true })
352
358
  store.enabled = true
359
+ const resumable = []
353
360
  for (const run of loaded) {
354
361
  if (runs.has(run.id)) continue
355
362
  run.events ??= []
356
363
  runs.set(run.id, run)
357
- if (isActive(run)) {
358
- Object.assign(run, { state: 'interrupted', endedAt: new Date().toISOString(), error: 'Harness restarted while this run was active; its turn was stopped.' })
359
- persist(run)
364
+ if (isActive(run)) resumable.push(run)
365
+ }
366
+ for (const run of resumable) guard('take up runs', takeUp)(run)
367
+ }
368
+ async function takeUp(run, tries = 0) {
369
+ const items = run.sessionId ? await sessionActivity(run.sessionId).catch(() => null) : []
370
+ if (!isActive(run)) return
371
+ // A message that reached the conversation while no plugin listened: the run is in it.
372
+ if (!run.sawPrompt && run.sessionId) {
373
+ const log = await sessionLog(run.sessionId).catch(() => null)
374
+ // Ended meanwhile (a late refusal of the prompt, a cancel): left as it is.
375
+ if (!isActive(run)) return
376
+ if (Array.isArray(log?.events) && log.events.some((e) => e.type === 'user/message' && e.data?.source?.rpcId === run.requestId)) {
377
+ Object.assign(run, { sawPrompt: true, state: 'running', admitted: true })
360
378
  }
361
379
  }
380
+ // Unknown is not idle (Harness may not answer yet right after the reload): look again a few
381
+ // times. A message Harness had not taken in yet may still arrive: a cold start took 2 min 35 s
382
+ // to admit one (Mac, 2026-11-18), so that is looked for up to takeUpAdmitMs().
383
+ const notYetIn = !run.admitted && !run.sawPrompt
384
+ const again = items === null ? tries < ACTIVITY_MAX_ERRORS : notYetIn && !items?.length && (tries + 1) * TAKE_UP_RETRY_MS < takeUpAdmitMs()
385
+ if (again) {
386
+ setTimeout(guard('take up runs', () => takeUp(run, tries + 1)), TAKE_UP_RETRY_MS)
387
+ return
388
+ }
389
+ if (Array.isArray(items) && items.length) {
390
+ // Its turn may have ended while no plugin listened: with no turn left, only background
391
+ // work (sub-agents, jobs), the run ends once that is done, as after a seen turn end.
392
+ if (run.sawPrompt && !items.some((g) => g.kind === 'turn')) run.idleSeen = true
393
+ // A question asked through the plugin that went away cannot be answered from here any more
394
+ // (its request belonged to the old plugin): the wait says to answer it in the Harness window.
395
+ if (run.question && !questions.has(run.sessionId)) {
396
+ delete run.question
397
+ if (run.state === 'waiting') run.waitNoticed = false
398
+ }
399
+ pushEvent(run, { type: 'plugin_reloaded' })
400
+ persist(run)
401
+ scheduleQuietCheck(run.sessionId, 1000)
402
+ return
403
+ }
404
+ // settle, so a wait that began since the reload wakes now.
405
+ settle(run, 'interrupted', { error: notYetIn ? 'The plugin reloaded before Harness took the message in, and it never arrived; send it again if it is still wanted.' : 'Harness restarted while this run was active; its turn was stopped.' })
362
406
  }
363
407
 
364
408
  // Per-session turn state: whether the current turn has produced assistant
@@ -745,11 +789,11 @@ export function apply(ctx) {
745
789
  const run = run_id ? getRun(run_id) : null
746
790
  const entry = questions.get(run?.sessionId ?? session_id)
747
791
  if (run && (!isActive(run) || !entry || run.question?.question_id !== entry.id)) {
748
- if (run.state === 'waiting') throw new Error(`Run ${run.id} is waiting for something in the Harness UI (an approval, for example) that cannot be answered from here; tell the user.`)
792
+ if (run.state === 'waiting') throw new Error(`Run ${run.id} is waiting for something in the Harness UI (an approval, or a question left open when the plugin reloaded) that cannot be answered from here; tell the user to answer it in the Harness window.`)
749
793
  throw new Error(`Run ${run.id} is ${run.state} and has no open question to answer.`)
750
794
  }
751
795
  if (!entry) {
752
- if (waitingSessions.has(session_id)) throw new Error(`Session ${session_id} is waiting for something in the Harness UI (an approval, for example) that cannot be answered from here; tell the user.`)
796
+ if (waitingSessions.has(session_id)) throw new Error(`Session ${session_id} is waiting for something in the Harness UI (an approval, or a question left open when the plugin reloaded) that cannot be answered from here; tell the user to answer it in the Harness window.`)
753
797
  throw new Error(`Session ${session_id} has no open question to answer.`)
754
798
  }
755
799
  const shown = run ? publicRun(run, 0) : { session_id }
@@ -761,7 +805,13 @@ export function apply(ctx) {
761
805
  const options = q.options ?? []
762
806
  const chosen = (a.choose ?? []).map((c) => {
763
807
  const byNumber = typeof c === 'number' || /^\d+$/.test(String(c)) ? options[Number(c) - 1] : undefined
764
- const option = byNumber ?? options.find((o) => o.label === c) ?? options.find((o) => o.label.toLowerCase().replace(RECOMMENDED, '').trim() === String(c).toLowerCase().replace(RECOMMENDED, '').trim())
808
+ // Labels compared on letters and digits, the asker's mark left out: "Markdown(.md,推荐)" and "Markdown (.md)" are one option.
809
+ const bareLabel = (v) => String(v).toLowerCase().replace(/\(recommended\)|recommended|推荐/g, '').replace(/[^\p{L}\p{N}]+/gu, '')
810
+ const option = byNumber ?? options.find((o) => o.label === c) ?? options.find((o) => o.label.toLowerCase().replace(RECOMMENDED, '').trim() === String(c).toLowerCase().replace(RECOMMENDED, '').trim()) ?? (bareLabel(c) ? options.find((o) => bareLabel(o.label) === bareLabel(c)) : undefined) ?? (() => {
811
+ // The label's head: "md" for "md (Markdown)", when only one option starts that way.
812
+ const heads = bareLabel(c) ? options.filter((o) => bareLabel(String(o.label).split(/[((]/)[0]) === bareLabel(c)) : []
813
+ return heads.length === 1 ? heads[0] : undefined
814
+ })()
765
815
  if (!option) throw new Error(`Question ${q.id} has no option ${JSON.stringify(c)}; options: ${options.map((o, i) => `${i + 1}. ${o.label}`).join('; ')}`)
766
816
  return option.label
767
817
  })
@@ -864,25 +914,46 @@ export function apply(ctx) {
864
914
  // A session's whole event log and its folder. Harness up to 0.2.1 has sessionController.inspect;
865
915
  // 0.2.2 replaced it with paged history (events): the newest page first, beforeSeq walks back,
866
916
  // throughSeq pins every page to the same cut. The folder then comes from the session list.
917
+ // A log read before (the last few sessions) is kept, so a later read walks back only to the
918
+ // last event it has instead of reading the whole log again (a follow reads it each round). A
919
+ // log that no longer holds that event, or has fewer events, is read whole.
920
+ const logCache = new Map()
867
921
  async function sessionLog(sessionId) {
868
922
  if (typeof controller.inspect === 'function') return controller.inspect(sessionId, signal())
869
923
  if (typeof controller.events !== 'function') throw new Error('This DeepSeek Harness version cannot read a session log.')
924
+ const events = await pagedLog(sessionId, logCache.get(sessionId))
925
+ const { items } = await controller.list({}, signal())
926
+ return { meta: { cwd: items.find((it) => it.sessionId === sessionId)?.cwd ?? null }, events }
927
+ }
928
+ async function pagedLog(sessionId, known) {
870
929
  const address = { kind: 'session', sessionId }
871
930
  const pages = []
872
931
  let throughSeq
873
932
  let beforeSeq
933
+ let joined = false
874
934
  for (;;) {
875
935
  const page = await controller.events({ address, maxMessages: 500, ...(throughSeq === undefined ? {} : { throughSeq }), ...(beforeSeq === undefined ? {} : { beforeSeq }) }, signal())
876
936
  throughSeq ??= page.cursor
877
937
  const events = (page.records ?? []).filter((r) => r?.type === 'event' && r.event).map((r) => r.event)
878
938
  pages.unshift(events)
939
+ if (known && events.length && events[0].seq <= known.lastSeq) { joined = true; break }
879
940
  if (!page.hasMore || !events.length || events[0].seq === beforeSeq) break
880
941
  beforeSeq = events[0].seq
881
942
  }
882
943
  const seen = new Set()
883
- const events = pages.flat().filter((e) => (seen.has(e.seq) ? false : (seen.add(e.seq), true)))
884
- const { items } = await controller.list({}, signal())
885
- return { meta: { cwd: items.find((it) => it.sessionId === sessionId)?.cwd ?? null }, events }
944
+ let events = pages.flat().filter((e) => (seen.has(e.seq) ? false : (seen.add(e.seq), true)))
945
+ if (joined) {
946
+ if (!events.some((e) => e.seq === known.lastSeq)) return pagedLog(sessionId, null)
947
+ events = [...known.events, ...events.filter((e) => e.seq > known.lastSeq)]
948
+ }
949
+ const lastSeq = events.at(-1)?.seq
950
+ logCache.delete(sessionId)
951
+ // Read-only for callers; a very long log is not kept (memory).
952
+ if (Number.isFinite(lastSeq) && events.length <= 50_000 && events.every((e, i) => i === 0 || e.seq > events[i - 1].seq)) {
953
+ logCache.set(sessionId, { events, lastSeq })
954
+ if (logCache.size > 8) logCache.delete(logCache.keys().next().value)
955
+ }
956
+ return events
886
957
  }
887
958
 
888
959
  async function readSession({ session_id, last = 10 }) {
@@ -1665,14 +1736,25 @@ export function apply(ctx) {
1665
1736
  ...(chosen.model ? { model: chosen.model } : {}),
1666
1737
  }
1667
1738
  remember(run)
1668
- try {
1669
- await controller.prompt({ sessionId, requestId: run.requestId, content: [{ type: 'text', text: message }], mode }, signal())
1670
- run.admitted = true // in Harness's queue (or conversation) now
1671
- if (drift) rememberDefault(drift.now)
1672
- } catch (error) {
1673
- settle(run, 'failed', { error: String(error?.message ?? error) })
1674
- }
1739
+ // Harness answers the prompt once it has taken the message in; on a cold start (the first
1740
+ // session after a restart) that took 2 min 35 s, and the client sat in dsh_send all along
1741
+ // (Mac, 2026-11-18). So the reply waits at most admitWaitMs() (10 s); Harness's answer still settles
1742
+ // the run when it comes (a refusal fails it, and dsh_wait says so).
1743
+ const admitted = controller.prompt({ sessionId, requestId: run.requestId, content: [{ type: 'text', text: message }], mode }, signal())
1744
+ .then(() => {
1745
+ run.admitted = true // in Harness's queue (or conversation) now
1746
+ if (drift) rememberDefault(drift.now)
1747
+ return true
1748
+ }, (error) => {
1749
+ settle(run, 'failed', { error: String(error?.message ?? error) })
1750
+ return true
1751
+ })
1752
+ let timer
1753
+ const answered = await Promise.race([admitted, new Promise((r) => { timer = setTimeout(() => r(false), admitWaitMs()) })])
1754
+ clearTimeout(timer)
1755
+ if (!answered) pushEvent(run, { type: 'admission_pending' })
1675
1756
  return {
1757
+ ...(answered ? {} : { admission_pending: true }),
1676
1758
  ...publicRun(run),
1677
1759
  mode,
1678
1760
  mode_source: modeSource,
package/host/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-baton-host",
3
- "version": "0.6.15",
3
+ "version": "0.6.17",
4
4
  "description": "Hand coding tasks from Claude Code, Codex or Antigravity to DeepSeek Harness: they run live in the Harness window and come back with the changed files and test results. 让 Claude Code、Codex 和 Antigravity 把编码任务交给 DeepSeek Harness:在 Harness 窗口里实时跑,做完带着改动文件和测试结果交回。",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -24,7 +24,7 @@
24
24
  "docs"
25
25
  ],
26
26
  "dependencies": {
27
- "dsh-baton-mcp": "0.6.15"
27
+ "dsh-baton-mcp": "0.6.17"
28
28
  },
29
29
  "license": "MIT",
30
30
  "dsh": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-baton-mcp",
3
- "version": "0.6.15",
3
+ "version": "0.6.17",
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.6.15",
10
+ "version": "0.6.17",
11
11
  "packages": [
12
12
  {
13
13
  "registryType": "npm",
14
14
  "identifier": "dsh-baton-mcp",
15
- "version": "0.6.15",
15
+ "version": "0.6.17",
16
16
  "transport": {
17
17
  "type": "stdio"
18
18
  }
package/src/cli.mjs CHANGED
@@ -5,6 +5,7 @@ import path from 'node:path'
5
5
  import * as core from './core.mjs'
6
6
  import { setup, stableNodePath } from './setup.mjs'
7
7
  import { runHook, parseHookInput } from './codex-hook.mjs'
8
+ import { markWaiting } from './waiters.mjs'
8
9
 
9
10
  const USAGE = `Usage: dsh-baton <command> [args]
10
11
 
@@ -88,6 +89,8 @@ async function main() {
88
89
  case 'status':
89
90
  return print(await core.api.status(rest[0]?.startsWith('session') || flags.session ? { session_id: flags.session ?? rest[0] } : { run_id: rest[0] }))
90
91
  case 'wait': {
92
+ // So that dsh_wait in the same client knows this run is waited for already.
93
+ markWaiting(rest[0])
91
94
  const total_s = Number(flags.timeout) || 24 * 3600
92
95
  const waitStarted = Date.now()
93
96
  const st = await core.api.wait({ run_id: rest[0], timeout_s: total_s })
@@ -103,17 +106,17 @@ async function main() {
103
106
  ? self(`wait ${rest[0]} --until ${f.until} --cursor ${f.cursor}${f.until === 'turn' ? ` --every ${every_s}s` : ''}`)
104
107
  : undefined
105
108
  print({ ...f, ...(again ? { follow_command: again, hint: `${f.hint} To go on following, run follow_command in the background (not dsh_wait).` } : {}) })
106
- process.exitCode = f.state === 'needs_input' ? 3 : 0
109
+ // 0 even when a person is needed: the output says so, and Claude Code showed exit 3 as a
110
+ // red "failed" background command (Windows, 2026-11-18).
111
+ process.exitCode = 0
107
112
  return
108
113
  }
109
114
  if (st.needs_input && st.question) {
110
115
  const { run_id, state, session_id, needs_input, question } = st
111
116
  print(core.asking({ run_id, state, session_id, needs_input, question }, core.askHint(question.count ?? question.questions?.length ?? 1, 'dsh_answer (or dsh-baton answer)', 'wait again')))
112
- process.exitCode = 3
113
117
  return
114
118
  }
115
119
  print({
116
- ...(st.decided_for_user ? { hint: `${core.DECIDED_HINT} ${core.endedHint(st)}`, decided_for_user: st.decided_for_user } : {}),
117
120
  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,
118
121
  // A goal goes on after this run: the hint says so and how to follow it.
119
122
  ...(st.goal ? { goal: st.goal, ...(st.goal.phase === 'active' ? { follow_command: self(`follow ${st.session_id}`) } : {}) } : {}),
@@ -121,7 +124,7 @@ async function main() {
121
124
  ...(st.evidence ? { evidence: st.evidence } : {}),
122
125
  // Approvals this plugin allowed during the run (the plugin page's default): the client says what was let through.
123
126
  ...(st.approvals_allowed?.length ? { approvals_allowed: st.approvals_allowed } : {}),
124
- ...(st.state === 'completed' && !st.decided_for_user ? { hint: core.endedHint(st) } : {}),
127
+ ...(st.state === 'completed' ? { hint: core.endedHint(st) } : {}),
125
128
  // Stopped by the user, cancelled, or cut off by a Harness restart: say so, or the client
126
129
  // takes it for a failure in the work and sends it again.
127
130
  ...(st.harness_down ? { harness_down: true, hint: core.harnessDownHint('run this same wait command again') } : {}),
@@ -147,7 +150,12 @@ async function main() {
147
150
  case 'queued':
148
151
  return print(await core.api.update_queued({ run_id: rest[0], action: rest[1], ...(rest[1] === 'edit' ? { message: rest.slice(2).join(' ') } : {}) }))
149
152
  case 'answer':
150
- return print(await core.api.answer({ run_id: rest[0], answers: JSON.parse(rest.slice(1).join(' ')) }))
153
+ {
154
+ // The answers, or { answers } as dsh_answer takes them.
155
+ if (!rest[0] || /^[[{]/.test(rest[0])) throw new Error(`Usage: dsh-baton answer <run_id> '<answers JSON>'`)
156
+ const given = JSON.parse(rest.slice(1).join(' '))
157
+ return print(await core.api.answer({ ...(Array.isArray(given) ? { answers: given } : given), run_id: rest[0] }))
158
+ }
151
159
  case 'rename':
152
160
  return print(await core.api.rename_session({ session_id: rest[0], title: rest.slice(1).join(' ') }))
153
161
  case 'rename-workspace':
package/src/core.mjs CHANGED
@@ -594,19 +594,17 @@ export function goalHint(goal, sid) {
594
594
  // A run in a session whose Harness goal goes on: its wait goes on with the goal.
595
595
  // Also one that stopped after the run began: the rounds after the run's are its work too.
596
596
  export const goalGoesOn = (st) => st?.state === 'completed' && !!st.session_id && !!st.goal && ((st.goal.phase === 'active' && st.goal.activation !== 'disarmed') || !!st.goal.ended_since_run)
597
- // The run's wait followed on through its goal (f, from followResult): the follow's result, with
598
- // any answer chosen for the user during the run, and, once the goal stopped, the run's checks
599
- // run again then (budget_ms; without the time, the ones from the end of the run's own round).
597
+ // The run's wait followed on through its goal (f, from followResult): the follow's result, and,
598
+ // once the goal stopped, the run's checks run again then (budget_ms; without the time, the ones
599
+ // from the end of the run's own round).
600
600
  export function throughGoal(run, f, { budget_ms = 180_000 } = {}) {
601
- const chose = run.decided_for_user ? 'You chose an answer for the user during this run (decided_for_user): start your reply by telling the user what you chose and why. ' : ''
602
601
  const final = f.state === 'goal_ended' && run.evidence?.checks?.length
603
602
  const again = final && budget_ms >= 5000 ? evidence.recheck(config.batonHome, run.run_id, budget_ms) : null
604
603
  return {
605
604
  ...f, run_id: run.run_id,
606
605
  ...(final ? (again ? { checks: again, all_checks_passed: again.every((c) => c.passed) } : { checks: run.evidence.checks, checks_from: 'the end of the run\'s own round (no time left to run them again)' }) : {}),
607
- ...(run.decided_for_user ? { decided_for_user: run.decided_for_user } : {}),
608
606
  // Going on through the run keeps the run's checks for the goal's end.
609
- ...(f.hint ? { hint: chose + f.hint.replaceAll(AGAIN, AGAIN.replace('session_id', 'run_id')) } : {}),
607
+ ...(f.hint ? { hint: f.hint.replaceAll(AGAIN, AGAIN.replace('session_id', 'run_id')) } : {}),
610
608
  }
611
609
  }
612
610
 
@@ -620,8 +618,8 @@ export function followResult(st) {
620
618
  case 'following': return { ...st, hint: `No report is due yet: ${AGAIN}, with no progress note in between. ${QUIET}` }
621
619
  case 'goal_ended': return { ...st, hint: `The goal stopped (${st.ended_because}${st.goal?.blocked_reason ? `: ${st.goal.blocked_reason.message}` : ''}), so following is over. ${report}${st.ended_because === 'blocked' || st.ended_because === 'paused' ? ' It needs the user before it goes on: say so.' : ''}` }
622
620
  case 'needs_input': return st.question
623
- ? asking(st, askHint(st.question.count ?? st.question.questions?.length ?? 1, `dsh_answer and session_id ${st.session_id} (no run_id)`, AGAIN))
624
- : { ...st, hint: `Harness waits for something only a person can do in its window (an approval, for example). Tell the user, then ${AGAIN}.` }
621
+ ? asking(st, askHint(countOf(st.question), `dsh_answer and session_id ${st.session_id} (no run_id)`, AGAIN))
622
+ : { ...st, hint: `Harness waits for something only a person can do in its window: an approval, or a question left open when the plugin reloaded (it is answered in the Harness window, not with dsh_answer). Tell the user, then ${AGAIN}.` }
625
623
  case 'needs_resume': return { ...st, hint: 'The goal is still active, but Harness will not go on with it by itself (for example after a Harness restart). Tell the user to press Continue in Harness, and stop following until they have.' }
626
624
  case 'goal_stalled': return { ...st, hint: 'The goal is active, yet no new round has started for 5 minutes: Harness may have stopped going on with it (for example after a restart). Tell the user; they can press Continue in Harness. Stop following until they have.' }
627
625
  case 'no_goal': return { ...st, hint: 'This session has no Harness goal, so there is nothing to follow. To get a reply from it, send a message with dsh_send and wait for that run.' }
@@ -634,27 +632,22 @@ export const QUOTA_HINT = 'The run stopped because the DeepSeek account has no b
634
632
  const outOfBalance = (st) => st.state === 'failed' && (['ACCOUNT_QUOTA', 'QUOTA'].includes(st.turn_end?.error?.code) || st.turn_end?.error?.status === 402 || /insufficient balance/i.test(st.error ?? ''))
635
633
 
636
634
  // What to do when a run stops to ask a person (dsh_wait, wait_command and the instructions say it).
637
- // The options are the asking model's guesses, not the limit of the answer: every question also
638
- // takes free text (on a single-choice question it replaces the option, Harness's own rule).
639
- // The user wants the client to decide as the owner of the task, not pick the least bad option.
635
+ // The question goes back to the client, which asks the user its own way and submits their
636
+ // answer. dsh-baton no longer steers how the client asks or lets it answer for the user: hints,
637
+ // a plugin-page setting, laid-out calls and forms were each followed by some clients and
638
+ // permission modes and refused or ignored by others (Codex app, Claude Code auto mode;
639
+ // 2026-11-08 to 11-19).
640
640
  export const OWN_WORDS = 'On a single choice, text replaces the option.'
641
- export const ASKED = `If the user told you to decide such questions yourself, decide as the task's owner: an option only if it fits as is, else your own words. ${OWN_WORDS} Call dsh_answer with a one-sentence reason, then tell the user what you answered and why. Otherwise relay the questions, starting with your advice on its own line: "My recommendation: <an option, or your own answer>, because <reason>", from your own judgment, even outside the options (harness_suggested is only the asker's pick, never a reason). List the options (the user may also answer in words) and submit their decision with dsh_answer. Never answer on the user's behalf without that permission.`
642
- export const DECIDED_HINT = 'Required in your reply: you answered for the user during this run, so start your reply by telling the user, in their language, what you answered (an option or your own words) and why (decided_for_user: answers and reason), then give the result. Passing on only final_text is not enough.'
643
- // What to do when a run asks the user, in one short hint that goes first in the result.
644
- // Codex relays through its own question tool (request_user_input: a title and plain option
645
- // strings); the message before that call is folded away in the Codex app, so a recommendation
646
- // written only there is lost (Mac, 2026-11-08), and longer hints did not change that. The
647
- // result therefore carries question_tool, the call laid out with the recommendation as its first
648
- // option, as relay is the message laid out with it as its first line: clients copy a layout
649
- // more reliably than they follow rules.
650
- export const askHint = (n, answerWith, then) => `Harness asks the user ${n} question(s). If the user let you decide such questions, answer as the task's owner: an option only if it fits as is, else your own words (text; ${OWN_WORDS.toLowerCase().replace(/\.$/, '')}). An option that needs a note, a fix or an explanation to work for this task does not fit: write the answer it should have been instead. Answer with ${answerWith} and a one-sentence reason, then tell the user what you answered and why. Otherwise ask the user, your own recommendation first: fill the first line of relay (in a message) or the first option of question_tool (in a question tool such as request_user_input) with the answer that best fits this task, checked against its file names and requirements (an option, or your own answer when none fits), and why. Never "your choice", nor the asker's pick (harness_suggested) unchecked. If they pick your recommendation, submit the answer alone, without "Recommended" or the reason. Submit their answer with ${answerWith}, then ${then}.`
641
+ export const ASKED = 'Ask the user (your own question tool, or a message), your recommendation first if you have one, and submit their answer.'
642
+ export const askHint = (n, answerWith, then) => `Harness asks the user ${n} question(s). Ask the user (your own question tool, or a message), your recommendation first if you have one, and submit their answer with ${answerWith}: an option, or their own words (text; ${OWN_WORDS.toLowerCase().replace(/\.$/, '')}). Then ${then}.`
643
+ const countOf = (q) => q?.count ?? q?.questions?.length ?? 1
651
644
  const NEEDS_INPUT_HINT = (st) => st.question
652
- ? askHint(st.question.count ?? st.question.questions?.length ?? 1, 'dsh_answer', 'wait for the run again')
653
- : 'The run waits for something only a person can do in the Harness UI (an approval, for example). Tell the user, then wait for the run again.'
654
- // The hint first, then the question laid out two ways, then the rest of the status.
645
+ ? askHint(countOf(st.question), 'dsh_answer', 'wait for the run again')
646
+ : 'The run waits for something only a person can do in the Harness UI: an approval, or a question left open when the plugin reloaded (it is answered in the Harness window, not with dsh_answer). Tell the user, then wait for the run again.'
647
+ // The hint first, then the rest of the status.
655
648
  export function asking(st, hint) {
656
- const { hint: _old, relay: _r, question_tool: _q, ...rest } = st
657
- return { hint, ...(st.question ? { relay: relayText(st.question), question_tool: questionTool(st.question) } : {}), ...rest }
649
+ const { hint: _old, ...rest } = st
650
+ return { hint, ...rest }
658
651
  }
659
652
 
660
653
  // A run the user stopped in the Harness UI: its turn ended aborted, by the user. With the usual
@@ -669,16 +662,12 @@ export const USER_STOPPED_HINT = 'The user stopped this run in Harness (stopped_
669
662
  export const INTERRUPTED_HINT = 'Harness restarted or quit while this run was going, and its turn was stopped (interrupted). It is not a failure in the work: do not send it again or continue it on your own. Tell the user Harness was restarted and what evidence shows the run got done, then ask whether to run it again or continue in the same session.'
670
663
  export const CANCELLED_HINT = 'This run was cancelled before it finished: with dsh_cancel, or in Harness, where the user stopped the session or removed the queued message. If you did not cancel it yourself, the user did: do not send it again. Tell the user it was cancelled and ask what to do next.'
671
664
  // The hint for a run that did not end by its own work, or null for one that did.
672
- // A run that answered a question for the user before it stopped keeps the sentence telling the
673
- // client to say so.
674
665
  export function stopHint(st) {
675
- const told = (hint) => (st?.decided_for_user ? `${DECIDED_STOPPED} ${hint}` : hint)
676
- if (stoppedByUser(st)) return { stopped_by_user: true, hint: told(USER_STOPPED_HINT) }
677
- if (st?.state === 'interrupted') return { hint: told(INTERRUPTED_HINT) }
678
- if (st?.state === 'cancelled') return { hint: told(CANCELLED_HINT) }
666
+ if (stoppedByUser(st)) return { stopped_by_user: true, hint: USER_STOPPED_HINT }
667
+ if (st?.state === 'interrupted') return { hint: INTERRUPTED_HINT }
668
+ if (st?.state === 'cancelled') return { hint: CANCELLED_HINT }
679
669
  return null
680
670
  }
681
- const DECIDED_STOPPED = 'You answered a question for the user during this run: tell the user, in their language, what you answered and why (decided_for_user: answers and reason).'
682
671
 
683
672
  // The result of a run that ended, kept short: the client already knows what it sent, and a
684
673
  // completed run's event log is only the work behind final_text (dsh_status still has it).
@@ -688,10 +677,7 @@ function ended({ recent_events, message_preview, backend, ...st }) {
688
677
  if (outOfBalance(st)) return { ...out, hint: QUOTA_HINT }
689
678
  const stop = stopHint(st)
690
679
  if (stop) return { ...out, ...stop }
691
- // decided_for_user first, so a client that skims to final_text still meets it.
692
- return st.decided_for_user
693
- ? { hint: `${DECIDED_HINT} ${endedHint(st)}`, decided_for_user: st.decided_for_user, ...out }
694
- : { ...out, hint: endedHint(st) }
680
+ return { ...out, hint: endedHint(st) }
695
681
  }
696
682
 
697
683
 
@@ -704,7 +690,9 @@ export const waitResult = (st) => (st.needs_input ? asking(st, NEEDS_INPUT_HINT(
704
690
  // apart from the recommendation the client has to form itself. Harness still matches a
705
691
  // cleaned label when it is chosen by label.
706
692
  const MARK = /\s*(?:\((?:recommended|推荐)\)|((?:recommended|推荐)))\s*/gi
707
- const cleanLabel = (label) => String(label).replace(MARK, ' ').trim()
693
+ // The mark inside other brackets too: "Markdown(.md,推荐)" (Windows, 2026-11-18).
694
+ const INNER_MARK = /\s*[,,、;;]\s*(?:recommended|推荐)\s*(?=[))])|(?<=[((])\s*(?:recommended|推荐)\s*[,,、;;]\s*/gi
695
+ const cleanLabel = (label) => String(label).replace(MARK, ' ').replace(INNER_MARK, '').trim()
708
696
  export function shapeQuestion(question) {
709
697
  if (!Array.isArray(question?.questions)) return question
710
698
  return {
@@ -720,72 +708,10 @@ export function shapeQuestion(question) {
720
708
  }),
721
709
  }
722
710
  }
723
- // The question laid out for the user, ready to show: the first line is left for the
724
- // client's own recommendation, the asker's pick comes last and only as information.
725
- // Weaker models fill in a template more reliably than they follow a paragraph of rules.
726
- export function relayText(question) {
727
- if (!Array.isArray(question?.questions)) return undefined
728
- const blocks = question.questions.map((q, i) => {
729
- const head = `${question.questions.length > 1 ? `${i + 1}. ` : ''}${q.question}${q.multi_select ? ' (several can be chosen)' : ''}`
730
- const options = (q.options ?? []).map((o) => ` ${o.number}. ${o.label}${o.description ? ` - ${o.description}` : ''}`)
731
- const asker = q.harness_suggested ? [` (The model in Harness that asked would pick: ${q.harness_suggested.label})`] : []
732
- return [head, ...options, ...asker].join('\n')
733
- })
734
- return [RECOMMEND_LINE, '', ...blocks, '', 'You can also answer in your own words.'].join('\n')
735
- }
736
- const RECOMMEND_LINE = 'My recommendation: <an option, or your own answer>, because <your own reason>'
737
- // The same questions as a question tool takes them (a title, plain option strings), the first
738
- // option left for the client's recommendation; the user can still type their own answer there.
739
- export function questionTool(question) {
740
- if (!Array.isArray(question?.questions)) return undefined
741
- return question.questions.map((q) => ({
742
- title: `${q.question}${q.multi_select ? ' (several can be chosen)' : ''}`,
743
- options: ['Recommended: <an option, or your own answer>, because <your own reason>', ...(q.options ?? []).map((o) => o.label)],
744
- }))
745
- }
746
-
747
- // When the client chose for the user (dsh_answer with reason), the choice and reason are
748
- // kept until the run ends: the final wait result carries them, so the client tells the
749
- // user then, instead of only passing on the reply. A file, because the client may wait
750
- // from another process (wait_command).
751
- const reasonsFile = () => path.join(config.batonHome, 'answer-reasons.json')
752
- const readReasons = () => { try { return JSON.parse(fs.readFileSync(reasonsFile(), 'utf8')) } catch { return {} } }
753
- // A client deciding for the user picked the least bad option and patched it with a note
754
- // (".doc, but keep it plain text"; "XV:00, with a line saying it means 3 pm"), however the hint
755
- // put it (Codex, Mac, 2026-11-09). So an option chosen for the user is not sent at once: the
756
- // first call asks for a second look, and the same answers sent again go through. Own words
757
- // (text) go through at once, as do answers the user gave (no reason).
758
- export const OPTION_CHECK_HINT = 'Not sent yet, because you chose an option for the user. First, without looking at the options, write down the answer this user would want for this task, as if Harness had asked with no options at all. Send the option (dsh_answer again with the same answers) only if it says the same as that answer. If it does not, answer with text: your answer. An option you can argue for, or make work with a note or an explanation, is not the answer this user would want.'
759
- const checked = new Map()
760
- // questionId: the question being answered, so a check left over from an earlier question
761
- // (answered another way, or in the Harness window) never lets a later one through.
762
- export function optionCheck(a, reason, questionId = null) {
763
- if (!(typeof reason === 'string' && reason.trim())) return null
764
- const picks = (a.answers ?? []).filter((x) => x.choose?.length && !(typeof x.text === 'string' && x.text.trim()))
765
- if (!picks.length) return null
766
- const key = JSON.stringify([a.run_id ?? a.session_id, questionId, picks.map((x) => [x.id ?? null, x.choose.map(String)])])
767
- for (const [k, at] of checked) if (Date.now() - at > 30 * 60_000) checked.delete(k)
768
- // Once looked at, the same answers go through each time: a send that then fails (the user
769
- // answered in the window meanwhile) is retried and shows its real error.
770
- if (checked.has(key)) return null
771
- checked.set(key, Date.now())
772
- return { submitted: false, check: picks.map((x) => ({ ...(x.id ? { id: x.id } : {}), choose: x.choose })), hint: OPTION_CHECK_HINT }
773
- }
774
- function rememberReason(runId, answers, reason) {
775
- try {
776
- const all = readReasons()
777
- all[runId] = { answers: (answers ?? []).map((a) => ({ id: a.id, selected: (a.selected ?? []).map(cleanLabel), ...(a.custom ? { text: a.custom } : {}) })), reason, at: Date.now() }
778
- const kept = Object.entries(all).sort((x, y) => y[1].at - x[1].at).slice(0, 50)
779
- ensurePrivateDir(config.batonHome)
780
- fs.writeFileSync(reasonsFile(), JSON.stringify(Object.fromEntries(kept)), { mode: 0o600 })
781
- } catch { /* the reason is a courtesy; answering never fails over it */ }
782
- }
783
711
  const ENDED = new Set(['completed', 'failed', 'cancelled', 'interrupted'])
784
712
  const shaped = (st) => {
785
713
  if (!st || typeof st !== 'object') return st
786
- let out = st.question ? { ...st, question: shapeQuestion(st.question) } : st
787
- const decided = ENDED.has(st.state) && st.run_id ? readReasons()[st.run_id] : null
788
- if (decided) out = { ...out, decided_for_user: { answers: decided.answers, reason: decided.reason } }
714
+ const out = st.question ? { ...st, question: shapeQuestion(st.question) } : st
789
715
  return Array.isArray(st.answers) ? { ...out, answers: st.answers.map((a) => (Array.isArray(a?.selected) ? { ...a, selected: a.selected.map(cleanLabel) } : a)) } : out
790
716
  }
791
717
 
@@ -994,22 +920,12 @@ export const api = {
994
920
  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(' ', ' '))
995
921
  }
996
922
  },
997
- // reason (why the client chose, when the user let it decide) stays here: it is for the
998
- // user, not for Harness.
999
- async answer({ reason, ...a }) {
923
+ // reason and recommend (dsh_answer arguments of 0.6.16 drafts and older clients' memories)
924
+ // are dropped: nothing in them goes to Harness.
925
+ async answer({ reason: _reason, recommend: _recommend, ...a }) {
1000
926
  if (!(await useHost())) throw new Error('Answering a question needs the dsh-baton-host plugin running inside DeepSeek Harness.')
1001
- let questionId = null
1002
- if (typeof reason === 'string' && reason.trim()) {
1003
- const st = await hostCall('status', a.run_id ? { run_id: a.run_id } : { session_id: a.session_id }).catch(() => null)
1004
- questionId = st?.question?.question_id ?? null
1005
- }
1006
- const check = optionCheck(a, reason, questionId)
1007
- if (check) return check
1008
927
  try {
1009
- const result = shaped(await hostCall('answer', a))
1010
- if (!(typeof reason === 'string' && reason.trim())) return result
1011
- if (result.submitted && a.run_id) rememberReason(a.run_id, result.answers, reason.trim())
1012
- return { ...result, reason: reason.trim() }
928
+ return shaped(await hostCall('answer', a))
1013
929
  } catch (error) {
1014
930
  if (!/Unknown method: answer/.test(error?.message)) throw error
1015
931
  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(' ', ' '))
package/src/evidence.mjs CHANGED
@@ -62,7 +62,8 @@ function listWorktrees(dir) {
62
62
  if (out == null) return null
63
63
  return out.split('\n').filter((l) => l.startsWith('worktree ')).map((l) => realPath(l.slice('worktree '.length).trim()))
64
64
  }
65
- const realPath = (p) => { try { return fs.realpathSync(p) } catch { return path.resolve(p) } }
65
+ // The native call, as git reports paths: on Windows it also expands 8.3 short names (RUNNER~1).
66
+ const realPath = (p) => { try { return fs.realpathSync.native(p) } catch { return path.resolve(p) } }
66
67
 
67
68
  // What a worktree changed against the commit the folder was on at dsh_send: committed and
68
69
  // uncommitted alike, from git rather than a copy of the whole checkout. With no such commit,
package/src/folder.mjs CHANGED
@@ -47,7 +47,7 @@ function codexThreadCwd(threadId) {
47
47
  function serverCwd() {
48
48
  const cwd = process.cwd()
49
49
  const home = os.homedir()
50
- const real = (p) => { try { return fs.realpathSync(p) } catch { return p } }
50
+ const real = (p) => { try { return fs.realpathSync.native(p) } catch { return p } }
51
51
  const inside = (dir) => { const r = path.relative(real(dir), real(cwd)); return r === '' || (!r.startsWith('..') && !path.isAbsolute(r)) }
52
52
  if (norm(real(cwd)) === norm(real(home)) || cwd === path.parse(cwd).root) return undefined
53
53
  if (inside(codexHome()) || inside(path.join(home, '.claude'))) return undefined
@@ -129,6 +129,8 @@ const norm = (p) => {
129
129
  const r = path.resolve(p.replace(/^~(?=$|[\\/])/, os.homedir()))
130
130
  return process.platform === 'win32' || process.platform === 'darwin' ? r.toLowerCase() : r
131
131
  }
132
+ // A folder as compared with another one (case-insensitive where the file system is).
133
+ export const folderId = (p) => norm(p)
132
134
  // True when folder is the conversation's folder or inside it.
133
135
  export function within(folder, conversation) {
134
136
  const r = path.relative(norm(conversation), norm(folder))
package/src/mcp.mjs CHANGED
@@ -6,8 +6,9 @@ import path from 'node:path'
6
6
  import * as core from './core.mjs'
7
7
  import { stableNodePath } from './setup.mjs'
8
8
  import { codexConfigPath, readCodexToolTimeout, codexTimeoutNoteFile, codexWaitSeconds, codexConfigReadAt, codexProcessStartedAtAsync } from './register.mjs'
9
- import { conversationFolder, within } from './folder.mjs'
9
+ import { conversationFolder, within, folderId } from './folder.mjs'
10
10
  import { threadOf, delivered } from './codex-hook.mjs'
11
+ import { waitingInBackground } from './waiters.mjs'
11
12
 
12
13
  const SERVER = { name: 'dsh-baton', version: core.VERSION }
13
14
  const PROTOCOLS = ['2025-06-18', '2025-03-26', '2024-11-05']
@@ -117,6 +118,40 @@ const FOLLOW_COMMAND_HINT = ' Your client wakes you when a background command ex
117
118
  // wait returned (measured 2026-11-08: a result read 3 minutes late, its rework sent late).
118
119
  const PARALLEL_HINT = 'If you are sending several parts in parallel, send them all first, then wait for them together: one dsh_wait with run_ids set to all their run_ids, never one run after another.'
119
120
 
121
+ // Sessions this conversation sent to, so that a new task for the same folder continues the
122
+ // session it used there before, when that one is idle, rather than starting a session per task
123
+ // (2026-11-19: three tasks in one project, one after another, went to three new sessions).
124
+ // Kept per conversation: Codex and Antigravity run one server for several conversations and
125
+ // send the conversation's id with each call; Claude Code runs one server per conversation.
126
+ // Kept in memory only: after a server restart (an update) the next task starts one more session.
127
+ const AG_META = 'antigravity.google/'
128
+ const conversationKey = (meta) => threadOf(meta) ?? meta?.[`${AG_META}root_conversation_id`] ?? meta?.[`${AG_META}conversation_id`] ?? 'this'
129
+ const usedSessions = new Map()
130
+ const folderKey = (a) => (a.workspace_id ? `workspace:${a.workspace_id}` : a.cwd ? `folder:${folderId(a.cwd)}` : null)
131
+ function rememberSession(meta, sessionId, folder) {
132
+ if (!sessionId) return
133
+ const key = conversationKey(meta)
134
+ if (!usedSessions.has(key)) usedSessions.set(key, new Map())
135
+ const mine = usedSessions.get(key)
136
+ const known = mine.get(sessionId)
137
+ if (folder || known) mine.set(sessionId, { folder: folder ?? known.folder, at: Date.now() })
138
+ }
139
+ // The session this conversation last used for folder, if it is idle now: no turn, no run of
140
+ // ours, no question, no goal going on, not archived. A busy one is never taken, so parts sent
141
+ // in parallel still get a session each.
142
+ async function idleSessionFor(meta, folder) {
143
+ const mine = usedSessions.get(conversationKey(meta))
144
+ if (!mine || !folder) return null
145
+ const candidates = [...mine].filter(([, v]) => v.folder === folder).sort((x, y) => y[1].at - x[1].at)
146
+ for (const [sid] of candidates) {
147
+ const st = await core.api.status({ session_id: sid }).catch(() => null)
148
+ if (!st || st.archived) { mine.delete(sid); continue }
149
+ if (st.busy || st.turn_running || st.bridge_runs?.length || st.needs_input || st.goal?.phase === 'active') continue
150
+ return sid
151
+ }
152
+ return null
153
+ }
154
+
120
155
  // Wait in short chunks, reporting progress between them (clients that support it can
121
156
  // show it or reset their timer). An unfinished wait returns only the state, not the run's
122
157
  // recent events, so the client has nothing to summarise and simply waits again.
@@ -142,7 +177,7 @@ async function waitInChunks({ run_id }, progress, signal, meta) {
142
177
  run_id, state: st.state, timed_out: true,
143
178
  ...(st.waiting_on ? { waiting_on: st.waiting_on } : {}),
144
179
  hint: st.state === 'waiting'
145
- ? 'The run is still waiting for a person (see dsh_status for its question). Answer it with dsh_answer if you may, or tell the user; then call dsh_wait again.'
180
+ ? 'The run is still waiting for a person (see dsh_status for its question). Ask the user and submit their answer with dsh_answer; then call dsh_wait again.'
146
181
  : `Still ${st.state}. Call dsh_wait again with the same run_id, with no progress check or progress note in between (work the user asked you to do meanwhile is fine).`,
147
182
  }
148
183
  }
@@ -150,6 +185,22 @@ async function waitInChunks({ run_id }, progress, signal, meta) {
150
185
  }
151
186
  }
152
187
 
188
+ // Runs a background wait_command of this machine already waits for (waiters.mjs): dsh_wait says
189
+ // so at once instead of waiting a second time in the foreground. Only for clients that wait in
190
+ // the background, and only while none of the runs has ended or asks (then the ordinary wait
191
+ // returns it at once).
192
+ const BACKGROUND_WAIT_HINT = (n) => `A background wait_command already waits for ${n > 1 ? 'these runs' : 'this run'} and wakes you when ${n > 1 ? 'each' : 'it'} ends or stops to ask the user something, so dsh_wait did not wait. Do not call dsh_wait for ${n > 1 ? 'them' : 'it'}: go on with other work, or end your turn if there is none.`
193
+ const STOPPED = new Set(['completed', 'failed', 'cancelled', 'interrupted', 'waiting'])
194
+ async function waitedInBackground(ids) {
195
+ if (!backgroundWaits() || !ids.length || !ids.every((id) => waitingInBackground(id))) return null
196
+ const states = await Promise.all(ids.map((id) => core.api.status({ run_id: id, tail: 1 }).catch(() => null)))
197
+ if (states.some((st) => !st || STOPPED.has(st.state) || st.needs_input)) return null
198
+ const hint = BACKGROUND_WAIT_HINT(ids.length)
199
+ return ids.length === 1
200
+ ? { run_id: ids[0], state: states[0].state, waiting_in_background: true, hint }
201
+ : { run_ids: ids, still_running: states.map((st, i) => ({ run_id: ids[i], state: st.state, session_id: st.session_id })), waiting_in_background: true, hint }
202
+ }
203
+
153
204
  // Several runs (dsh_wait run_ids): returns as soon as any of them ends or stops to ask a person,
154
205
  // with every one that has by then and the ones still running. Each round asks about all of them
155
206
  // together for a short chunk, so an ending is seen within MULTI_CHUNK_S. Every answer is kept:
@@ -298,8 +349,8 @@ const TOOLS = [
298
349
  {
299
350
  name: 'dsh_send',
300
351
  annotations: annotations('Send message', hints(false, false, false)),
301
- description: 'Hand a task to DeepSeek Harness, or continue a session: returns at once with a run_id and a hint saying how to wait for the reply; follow it. Call it directly, no need to list anything first. A new session starts in the folder this conversation works in, or in cwd or workspace_id (a new cwd is registered first); session_id continues that session. message arrives verbatim as a user message, and Harness does not see this conversation: make it self-contained, in the user\'s language, the full, explicit spec, asking for tests that cover each requirement. Keep a leading /goal (it sets a Harness goal) and the user\'s goal text as written. For a large task, write a concrete spec (goal, modules and the files each owns, level of detail, acceptance criteria) rather than passing the user\'s words on, and send independent parts to separate sessions in parallel, each owning its own files; wait for them together (dsh_wait run_ids), review each as it returns and send its fixes at once. With checks, a short request for a sub-agent review table is appended. To a busy session, mode followup queues the message and steer adds it to the running turn; left out, the Harness setting decides.',
302
- inputSchema: { type: 'object', required: ['message'], properties: { message: str('The task or reply to send'), session_id: str('Existing session to continue'), cwd: str('Workspace folder for a new session; leave out to use the folder this conversation works in'), workspace_id: str('Harness workspace for a new session (from dsh_list_workspaces)'), mode: { type: 'string', enum: ['followup', 'steer'], description: "followup queues after the current turn; steer injects into a running turn. Omit to follow Harness's busy-send setting" }, model: str('Only when the user names a model for this run (e.g. "DeepSeek-V4 Pro"); else the session keeps its own; a new one takes the plugin page\'s default. Matched ignoring case, spaces, hyphens and a leading DeepSeek; no match or several fails the send with the list (provider/model picks one). Sets this session only'), team: { type: 'boolean', description: 'Only when the user asks for Agent Teams: true turns them on for this session, false off' }, reasoning_effort: str('Only when the user names a reasoning effort, e.g. high; one of the efforts dsh_list_models shows for the model'), checks: { type: 'array', items: { type: 'string' }, description: 'The project\'s own test commands, e.g. npm test, or python -m pytest (a bare pytest is often not on PATH, on Windows especially); never check scripts you write yourself. dsh-baton runs them in the folder when the run ends and returns exit codes and the last output lines as evidence.' } } },
352
+ description: 'Hand a task to DeepSeek Harness, or continue a session: returns at once with a run_id and a hint saying how to wait for the reply; follow it. Call it directly, no need to list anything first. A new session starts in the folder this conversation works in, or in cwd or workspace_id (a new cwd is registered first); session_id continues that session. Without session_id, a task for a folder where this conversation already has an idle Harness session continues that session, so it keeps the earlier context (continued_session in the result says so; new_session: true starts a fresh one); a busy session is never reused, so parts sent in parallel still get a session each. message arrives verbatim as a user message, and Harness does not see this conversation: make it self-contained, in the user\'s language, the full, explicit spec, asking for tests that cover each requirement. Keep a leading /goal (it sets a Harness goal) and the user\'s goal text as written. For a large task, write a concrete spec (goal, modules and the files each owns, level of detail, acceptance criteria) rather than passing the user\'s words on, and send independent parts to separate sessions in parallel, each owning its own files; wait for them together (dsh_wait run_ids), review each as it returns and send its fixes at once. With checks, a short request for a sub-agent review table is appended. To a busy session, mode followup queues the message and steer adds it to the running turn; left out, the Harness setting decides.',
353
+ inputSchema: { type: 'object', required: ['message'], properties: { message: str('The task or reply to send'), session_id: str('Existing session to continue'), new_session: { type: 'boolean', description: 'Start a new session even though this conversation has an idle session in that folder: only for an unrelated task, or one that must not see the earlier work' }, cwd: str('Workspace folder for a new session; leave out to use the folder this conversation works in'), workspace_id: str('Harness workspace for a new session (from dsh_list_workspaces)'), mode: { type: 'string', enum: ['followup', 'steer'], description: "followup queues after the current turn; steer injects into a running turn. Omit to follow Harness's busy-send setting" }, model: str('Only when the user names a model for this run (e.g. "DeepSeek-V4 Pro"); else the session keeps its own; a new one takes the plugin page\'s default. Matched ignoring case, spaces, hyphens and a leading DeepSeek; no match or several fails the send with the list (provider/model picks one). Sets this session only'), team: { type: 'boolean', description: 'Only when the user asks for Agent Teams: true turns them on for this session, false off' }, reasoning_effort: str('Only when the user names a reasoning effort, e.g. high; one of the efforts dsh_list_models shows for the model'), checks: { type: 'array', items: { type: 'string' }, description: 'The project\'s own test commands, e.g. npm test, or python -m pytest (a bare pytest is often not on PATH, on Windows especially); never check scripts you write yourself. dsh-baton runs them in the folder when the run ends and returns exit codes and the last output lines as evidence.' } } },
303
354
  run: async (a, { meta } = {}) => {
304
355
  // A new session goes to this conversation's folder unless the call names another one;
305
356
  // a different folder is allowed but said back, so a wrong guess does not go unnoticed.
@@ -318,12 +369,19 @@ const TOOLS = [
318
369
  ? { folder_note: `This conversation works in ${here}; the new session was started in ${a.cwd} as asked. If that was not intended, cancel it and send again without cwd.` }
319
370
  : filled ? { cwd: here } : {}
320
371
  // The conversation's folder goes along, so a hand-over to a folder inside it joins its workspace.
321
- const args = { ...a, ...(filled ? { cwd: here } : {}), ...(here && !a.workspace_id ? { conversation_folder: here } : {}) }
322
- const sent = await core.api.send({ ...args, sender: core.senderOf(core.setting('SENDER') || clientName) })
372
+ const { new_session: fresh, ...given } = a
373
+ const args = { ...given, ...(filled ? { cwd: here } : {}), ...(here && !a.workspace_id ? { conversation_folder: here } : {}) }
374
+ // A new task for a folder this conversation already has an idle session in continues it.
375
+ const folderOf = a.session_id ? null : folderKey(args)
376
+ const reused = a.session_id || fresh ? null : await idleSessionFor(meta, folderOf)
377
+ const { cwd: _cwd, workspace_id: _ws, conversation_folder: _cf, ...rest } = args
378
+ const sent = await core.api.send({ ...(reused ? { ...rest, session_id: reused } : args), sender: core.senderOf(core.setting('SENDER') || clientName) })
379
+ rememberSession(meta, sent.session_id, folderOf)
323
380
  // Only when it waits behind a turn (queued_behind; a plugin before 0.6.14 says only
324
381
  // other_active_runs): every run starts out queued until Harness takes its prompt.
325
382
  const behind = a.session_id && sent.state === 'queued' && sent.mode === 'followup' && (sent.queued_behind || sent.other_active_runs?.length)
326
- const st = { ...sent, ...folder, ...(behind ? { queue_hint: QUEUE_HINT() } : {}) }
383
+ const continued = reused ? { continued_session: reused, session_note: `Continued session ${reused}, which this conversation used for this folder before and which is idle now, so Harness keeps that context. For an unrelated task that must not see the earlier work, send with new_session: true.` } : {}
384
+ const st = { ...sent, ...(reused ? {} : folder), ...continued, ...(behind ? { queue_hint: QUEUE_HINT() } : {}) }
327
385
  // Codex has no wake-on-exit for shell commands: offered wait_command, it runs it in a
328
386
  // terminal and polls that, so it gets dsh_wait only.
329
387
  if (isCodex()) {
@@ -346,7 +404,7 @@ const TOOLS = [
346
404
  return {
347
405
  ...st,
348
406
  wait_command: waitCommand(st.run_id),
349
- hint: `Run started. If you can run a shell command in the background and are woken when it exits (Claude Code: Bash with run_in_background), run wait_command that way: it ends when the run ends, or stops to ask the user something, and prints the reply or the questions, with no polling (several runs: one background wait_command each, so whichever ends first wakes you). Otherwise call dsh_wait with this run_id (several runs: one dsh_wait with run_ids). ${GOAL_WAIT_HINT('--until turn --every 10m on wait_command')}`,
407
+ hint: `Run started. If you can run a shell command in the background and are woken when it exits (Claude Code: Bash with run_in_background), run wait_command that way: it ends when the run ends, or stops to ask the user something, and prints the reply or the questions, with no polling (several runs: one background wait_command each, so whichever ends first wakes you). Then do not also call dsh_wait for it: go on with other work, or end your turn if there is none. Otherwise call dsh_wait with this run_id (several runs: one dsh_wait with run_ids). ${GOAL_WAIT_HINT('--until turn --every 10m on wait_command')}`,
350
408
  }
351
409
  },
352
410
  },
@@ -363,7 +421,7 @@ const TOOLS = [
363
421
  {
364
422
  name: 'dsh_wait',
365
423
  annotations: annotations('Wait for run'),
366
- description: () => `Wait for a run sent with dsh_send to end and return its state and final reply.${backgroundWaits() ? ' Prefer the background wait_command from dsh_send if your client wakes you when a background command exits: it costs no turns.' : ''} It also returns at once when the run stops to ask a person: needs_input answer (reply with dsh_answer) or harness-ui (an approval in the Harness window). Each call waits up to ${waitSeconds()} s${isCodex() && waitSeconds() > 270 ? ' (270 s in a conversation that was already open when dsh-baton set Codex\'s tool timeout)' : ''}; if it returns timed_out: true, call dsh_wait again with the same run_id, without a progress note. Parallel runs: all ids in run_ids, never one by one; returns once any ends or asks (ended; the rest in still_running); then wait again with the rest plus your fixes. A run in a session with a Harness goal is followed on until the goal stops, with every round since the run began. With session_id instead of run_id it follows that session's Harness goal (see until) without sending anything; it also returns when Harness needs a person or will not go on by itself. Pass back the cursor each result gives.${isCodex() ? ` ${NO_POLL} ${codeModeYield()}` : ''}`,
424
+ description: () => `Wait for a run sent with dsh_send to end and return its state and final reply.${backgroundWaits() ? ' Prefer the background wait_command from dsh_send if your client wakes you when a background command exits: it costs no turns. For a run a background wait_command already waits for, dsh_wait returns at once without waiting: do not call it for that run.' : ''} It also returns at once when the run stops to ask a person: needs_input answer (reply with dsh_answer) or harness-ui (an approval in the Harness window). Each call waits up to ${waitSeconds()} s${isCodex() && waitSeconds() > 270 ? ' (270 s in a conversation that was already open when dsh-baton set Codex\'s tool timeout)' : ''}; if it returns timed_out: true, call dsh_wait again with the same run_id, without a progress note. Parallel runs: all ids in run_ids, never one by one; returns once any ends or asks (ended; the rest in still_running); then wait again with the rest plus your fixes. A run in a session with a Harness goal is followed on until the goal stops, with every round since the run began. With session_id instead of run_id it follows that session's Harness goal (see until) without sending anything; it also returns when Harness needs a person or will not go on by itself. Pass back the cursor each result gives.${isCodex() ? ` ${NO_POLL} ${codeModeYield()}` : ''}`,
367
425
  inputSchema: {
368
426
  type: 'object', properties: {
369
427
  run_id: str('Run id from dsh_send'),
@@ -376,6 +434,8 @@ const TOOLS = [
376
434
  },
377
435
  run: async (a, { progress, signal, meta }) => {
378
436
  const ids = [...new Set([...(Array.isArray(a.run_ids) ? a.run_ids : []), ...(a.run_id ? [a.run_id] : [])].filter((id) => typeof id === 'string' && id))]
437
+ const background = await waitedInBackground(ids)
438
+ if (background) return background
379
439
  if (ids.length > 1) {
380
440
  const r = await waitAnyInChunks(ids, progress, signal, meta)
381
441
  return r.cancelled || r.timed_out ? r : anyResult(r)
@@ -411,7 +471,7 @@ const TOOLS = [
411
471
  {
412
472
  name: 'dsh_answer',
413
473
  annotations: annotations('Answer question', hints(false, false, false)),
414
- description: `Answer the questions a waiting run asked (needs_input in dsh_wait or dsh_status). ${core.ASKED} Per question: choose (option numbers or labels), text (your own answer, complete on its own), or skip. It reaches Harness once every question has an answer (submitted: true; remaining lists the rest); then wait again. If the user already answered in Harness, it says there is no open question.`,
474
+ description: `Submit the user's answer to the questions a waiting run asked (needs_input in dsh_wait or dsh_status). ${core.ASKED} Per question: choose (option numbers or labels), text (an answer in words), or skip. It reaches Harness once every question has an answer (submitted: true; remaining lists the rest); then wait again. If the user already answered in Harness, it says there is no open question.`,
415
475
  inputSchema: {
416
476
  type: 'object', required: ['answers'], properties: {
417
477
  run_id: str('Run id that is waiting (needs_input: answer)'),
@@ -421,25 +481,17 @@ const TOOLS = [
421
481
  type: 'object', properties: {
422
482
  id: str('Question id from question.questions[].id; may be left out when there is one question'),
423
483
  choose: { type: 'array', items: { type: ['integer', 'string'] }, description: 'Option numbers (1 = first) or labels; one for a single-choice question' },
424
- text: str('Your own answer in words'),
484
+ text: str('An answer in words'),
425
485
  skip: { type: 'boolean', description: 'Skip this question' },
426
486
  },
427
487
  },
428
488
  },
429
- reason: str('Required when the user let you decide: one sentence on why you chose this, from your own judgment of the question and the task; it is returned for you to tell the user and not sent to Harness'),
430
489
  },
431
490
  },
432
491
  run: async (a) => {
433
492
  const st = await core.api.answer(a)
434
- // The second look at an option chosen for the user: nothing was sent, its hint says what next.
435
- if (st.check) return st
436
- if (!a.run_id) return { ...st, hint: `${st.reason ? 'Tell the user what you chose and this reason. ' : ''}Then call dsh_wait again as before (the same run_id or session_id), with the same until and the last cursor.` }
437
- return {
438
- ...st,
439
- hint: st.reason
440
- ? 'Tell the user what you chose and this reason. Then wait for the run again.'
441
- : 'If you chose on the user\'s behalf, tell them what you chose and why, from your own judgment of the task (that the asker suggested it is not a reason); next time pass reason. Then wait for the run again.',
442
- }
493
+ if (st.submitted === false && st.hint) return st
494
+ return { ...st, hint: a.run_id ? 'Then wait for the run again.' : 'Then call dsh_wait again as before (the same run_id or session_id), with the same until and the last cursor.' }
443
495
  },
444
496
  },
445
497
  {
package/src/register.mjs CHANGED
@@ -452,7 +452,7 @@ export function clients(env = process.env, home = os.homedir()) {
452
452
  // survives upgrades (Homebrew's /opt/homebrew/bin/node, not the versioned Cellar path
453
453
  // that process.execPath resolves to); otherwise the running binary itself.
454
454
  export function stableNodePath(env = process.env, execPath = process.execPath) {
455
- const real = (p) => { try { return fs.realpathSync(p) } catch { return null } }
455
+ const real = (p) => { try { return fs.realpathSync.native(p) } catch { return null } }
456
456
  const target = real(execPath)
457
457
  const names = process.platform === 'win32' ? ['node.exe'] : ['node']
458
458
  for (const dir of (env.PATH ?? env.Path ?? '').split(path.delimiter).filter(Boolean)) {
@@ -483,7 +483,7 @@ export function findNode({ env = process.env, platform = process.platform, exclu
483
483
  } else {
484
484
  dirs.push('/opt/homebrew/bin', '/usr/local/bin', '/usr/bin')
485
485
  }
486
- const real = (x) => { try { return fs.realpathSync(x) } catch { return x } }
486
+ const real = (x) => { try { return fs.realpathSync.native(x) } catch { return x } }
487
487
  const fold = (s) => (platform === 'win32' ? s.toLowerCase() : s)
488
488
  const skip = exclude.filter(Boolean).map((x) => fold(real(x)))
489
489
  const seen = new Set()
package/src/server.mjs CHANGED
@@ -141,7 +141,10 @@ async function reloadIfInstalled() {
141
141
  current = next
142
142
  currentStamp = now
143
143
  currentVersion = init?.serverInfo?.version ?? null
144
- note = `dsh-baton was updated from ${before} to ${currentVersion} without a restart; this call already used ${currentVersion}.` +
144
+ // The same version with changed files (a reinstall, or files copied by hand) says so plainly.
145
+ note = (before && before === currentVersion
146
+ ? `dsh-baton ${currentVersion} was reloaded with changed files without a restart; this call already used them.`
147
+ : `dsh-baton was updated from ${before} to ${currentVersion} without a restart; this call already used ${currentVersion}.`) +
145
148
  (added.length ? ` New in this version: ${added.join(', ')}. If this conversation does not show them, call them through dsh_call {name, arguments}.` : '')
146
149
  if (lastTools !== null && JSON.stringify(tools) !== lastTools) {
147
150
  lastTools = JSON.stringify(tools)
@@ -0,0 +1,44 @@
1
+ // Background waits: a wait_command the client runs in the background leaves a file named
2
+ // <run_id>.<pid> in ~/.dsh-baton/waiting while it waits. dsh_wait reads them, so a client
3
+ // that already waits in the background for a run is told so at once instead of waiting a
4
+ // second time in the foreground (Claude Code did that on 2026-11-19, a minute a call, while
5
+ // its background waits were still running).
6
+ import fs from 'node:fs'
7
+ import path from 'node:path'
8
+ import { batonHome } from '../host/lib/socket.js'
9
+
10
+ const dir = (home = batonHome()) => path.join(home, 'waiting')
11
+ const safe = (id) => /^[\w.-]+$/.test(id ?? '')
12
+
13
+ const alive = (pid) => {
14
+ try { process.kill(pid, 0); return true } catch (e) { return e.code === 'EPERM' }
15
+ }
16
+
17
+ // Marks this process as waiting for runId until it exits. Returns the function that clears it.
18
+ export function markWaiting(runId, { pid = process.pid, home } = {}) {
19
+ if (!safe(runId)) return () => {}
20
+ const file = path.join(dir(home), `${runId}.${pid}`)
21
+ try {
22
+ fs.mkdirSync(dir(home), { recursive: true })
23
+ fs.writeFileSync(file, String(Date.now()))
24
+ } catch { return () => {} }
25
+ const clear = () => { try { fs.unlinkSync(file) } catch { /* gone already */ } }
26
+ process.once('exit', clear)
27
+ return clear
28
+ }
29
+
30
+ // Whether a live process waits for runId in the background. Files left by a process that is
31
+ // gone (killed without its exit handler) are removed on the way.
32
+ export function waitingInBackground(runId, { home } = {}) {
33
+ if (!safe(runId)) return false
34
+ let names
35
+ try { names = fs.readdirSync(dir(home)) } catch { return false }
36
+ let found = false
37
+ for (const name of names) {
38
+ if (!name.startsWith(`${runId}.`)) continue
39
+ const pid = Number(name.slice(runId.length + 1))
40
+ if (pid > 0 && alive(pid)) { found = true; continue }
41
+ try { fs.unlinkSync(path.join(dir(home), name)) } catch { /* removed meanwhile */ }
42
+ }
43
+ return found
44
+ }