SLOPSHOPPER

dispatch-relay

dispatch-board 的搭檔:worker session 把回報寫進結果檔後以一行結束,由 mod 在 turn 結束時把新增內容與最終回覆轉送給指揮站;背景工作進行中的回覆暫存、延後併送(mission 檔寫了 station 才啟用;需 Claude Code ≥ 2.1.296)

guardpromptprocesstimer
A shopper browsing a rack in a slop shop
README

dispatch-relay

dispatch-board 的搭檔,裝在 worker 那一側。多個 session 分工時,worker 做完通常要自己 SendMessage 把回報全文送給指揮站,然後再結束 turn——同一份回報生成兩次,SendMessage 之後還要多跑一次收尾 request。

裝了 dispatch-relay 之後,worker 只要把回報寫進結果檔、以一行結束 turn;mod 在 turn 結束時讀結果檔,把新增或變更的內容連同最終回覆原文送給指揮站。

↪ dispatch-relay:結果檔全文+最終回覆(1834 字)已送達指揮站 shop-lead

安裝

/plugin install dispatch-relay --marketplace Hangghost/learning-hacker-claude-mod

裝在 worker 那一側(通常跟 dispatch-board 一起裝)。

用法

  1. 照 dispatch-board 的方式寫 mission 檔(~/.claude/missions/*.json),在 mission 層加上 station:指揮站 session 的名稱。
  2. 指揮站與 worker 都必須用 --name 開:claude --bg --name shop-lead、claude --bg --name shop-api。名字要和 claude agents 列出的一樣(不分大小寫);沒命名的 session 對不到節點,指揮站沒命名則送不到。
  3. worker 把回報寫進結果檔(預設專案根目錄的 .mission-result.md),以一行結束 turn。

開始前要注意:

  • 新目錄要先接受信任:在一個從沒開過 Claude Code 的目錄第一次 claude --bg 之前,先在該目錄跑一次 claude、接受信任提示。否則 CLI 會回 Workspace not trusted…,session 開不起來。
  • 用 --worktree <名> 開的 worker:它的專案根目錄是 <repo>/.claude/worktrees/<名>,result_file 相對的是這個容器根目錄,不是 repo 根。
{
  "mission_id": "shop-redesign",
  "station": "shop-lead",
  "nodes": [
    { "id": "api", "session": "shop-api", "done": "…", "result_file": "reports/api.md" },
    { "id": "web", "session": "shop-web", "done": "…" }
  ]
}
欄位必填說明
station否指揮站 session 的名稱。沒寫就不啟用:只用 dispatch-board 的 mission 不受影響
nodes[].result_file否結果檔,相對於 worker 的專案根目錄(--worktree 開的 worker 是 <repo>/.claude/worktrees/<名>);預設 .mission-result.md。不能是絕對路徑,不能含 ..

其餘欄位(mission_id、nodes[].id、nodes[].session、done…)與 dispatch-board 相同,見 dispatch-board 的 README。

怎麼判定「我是哪個節點」

  1. $.session.id() 取得本 session 的 id。
  2. claude agents --json 找出這個 id 的名稱。
  3. 在 mission 目錄找 nodes[].session 等於這個名稱(不分大小寫)的節點。

恰好一個節點、且該 mission 有 station,才啟用。查無、多個節點都指到自己、mission 沒有 station、station 就是自己、名冊不可用,一律不啟用並在日誌(claude --debug)寫一行原因。未啟用時零行為:不改 system prompt、不放行任何送件、不送任何訊息。

mission 目錄裡沒有任何 mission 寫了 station 時,mod 連名冊都不讀——沒在用它的 session 不付這個成本。

啟動時還沒對到的話,每個新 prompt 會再試一次。啟用後,每次要送件前都重新判定一次:mission 檔搬到 done/、改派、或 session 改名就停用;指揮站重開換了 session id 也跟得上(每次送件前用名冊把 station 名稱解析成 session id)。

行為

  • 只送有變更的內容:結果檔與上次送出的不同才送;新內容以舊內容開頭時只送追加段,否則送全文。記錄遺失時當成沒送過、送全文(寧可重複,不要漏送)。
  • 最終回覆:worker 本 turn 沒有自己 SendMessage 時,最終回覆附帶送出,不設長度門檻(一行的「要不要 push?」也要送到)。worker 已自送時不附最終回覆,但結果檔變更照送。背景工作進行中的「等待中」回覆例外:先暫存、延後併入下一則(見下節)。
  • 只在正常答覆結束的 turn 送:中斷、錯誤、subagent 的 turn 不送,下一次正常 turn 補送。
  • 注入一段說明到 worker 的 system prompt:回報寫進結果檔後以一行結束、不要為同一份回報再 SendMessage。需要問指揮站時照常 SendMessage,或寫在最終回覆;背景工作進行中要立即回應時用 SendMessage(自送不延後,見下節)。
  • 訊息格式(指揮站若要解析,以此為準):
  [dispatch-relay] mission=<mission_id> node=<node_id> parts=<part>[,<part>…] chars=<本文總字數>

  --- <part> ---
  <該部分原文>

part 是 result-full、result-append、held-reply、final-reply 之一,本文依這個順序排列(時間先後);chars 是各部分原文長度加總。held-reply 是先前因背景工作進行中而暫存、延後送出的最終回覆(見下節)。

背景工作進行中的回覆會暫存

worker 常見的收尾是「起一個背景測試、說一句『等待中』、結束 turn」,背景工作完成時 Claude Code 再喚醒它。若每個「等待中」都立刻送出,指揮站每則都被喚醒一次。所以 turn 結束時帳上仍有未通知的背景工作,這則最終回覆不單獨送出,改為暫存,等下一則一起送。

  • 什麼算背景工作:背景 Bash(有 backgroundTaskId)、Monitor、背景 Agent/Task、ScheduleWakeup、CronCreate;只記主迴圈(不含 subagent 內)發起的。收到對應的完成通知(背景 Bash、Monitor 帶 <status> 的那一則、背景 Agent 的回傳、排程的觸發)就銷帳;Monitor 的中途事件通知不算結束。
  • 暫存的條件(全部成立):正常答覆結束的主迴圈 turn、最終回覆非空、本 turn 結果檔沒有變更、worker 本 turn 沒有自己 SendMessage、帳上有未通知的背景工作。有結果檔變更、worker 自送、或沒有背景工作時,照原規則立即送出,單行提問也一樣。
  • 暫存只延後、不丟棄,以 held-reply 併入送出,任一成立即送:
  • 下一個正常答覆結束的 turn(通常就是背景工作完成後那一則)——不論該 turn 自己有沒有東西要送、worker 是否自送。
  • 從第一則暫存起算 10 分鐘(固定常數;連續暫存的回覆以空行串接,不重設時限)。
  • session 結束(盡力而為;時間上限很短)。
  • 時限到時:計時器回呼裡只叫醒 worker——排入一個「只回覆 ok」的 prompt,由那個 turn 結束時的 turn.complete 送出暫存。不在回呼裡直接送件:auto mode 下回呼內的送件不經 tool.check,會被擋下。叫醒 turn 一定送出(即使帳上仍有背景工作),它自己的「ok」不附帶。時限到時 worker 正在 turn 中就不叫醒,該 turn 結束時直接送出;為防狀態誤判,每 60 秒重確認一次,連續 5 次仍在 turn 中就直接叫醒。
  • 畫面一行會說這則被暫存了:↪ dispatch-relay:背景工作進行中,這則回覆已暫存,於下一則回報或最久 10 分鐘內轉送指揮站。
  • 暫存內容存在 $.store,重新載入 plugin 不會丟,計時器依原起算時間重排。暫存寫不進去時改為立即送出(寧可多喚醒一次,不漏送)。
  • 帳是 mod 自己的記錄,不是 Claude Code 的內部狀態:漏登(未知的背景工具)只會變成立即送出;漏銷(完成通知沒對上)只會讓之後的等待中回覆被延後,每則仍受時限約束。兩種錯誤都不會漏送。

送不到的時候

  • 名冊上找不到 station、同名多筆(不猜是哪一個)、或送件失敗:mod 先把內容記為已處理,再排一個 prompt 請 worker 自己 SendMessage。prompt 裡給的收件位址依序是:mission 檔的 station 名稱(SendMessage 直接收名稱)、上次成功送達時的位址,最後才是最近一則來訊的 from 位址——而且僅限該則來自指揮站。worker 可能收過其他 session 的訊息,「回覆最近一則」會把回報送給第三方。
  • 同一份內容只降級一次:降級那個 turn 裡再失敗,只在畫面與日誌說明,不再排 prompt,避免 worker 與 mod 互相觸發。
  • 連請 worker 自送的 prompt 都排不進去時,把「已處理」回滾,下一次正常 turn 結束時重送;畫面會照實說哪些東西不會重送。結果檔以外的部分(暫存的 held-reply、最終回覆)沒有比對狀態可回滾,排入失敗就不重送。

完成與否仍以 mission 檔的完成條件為準:轉送的訊息只是門鈴。

安全邊界

dispatch-relay 會把檔案內容送到另一個 session。 送什麼、送給誰、何時不送:

  • 送什麼:只有本 session 對到的節點的結果檔,以及 worker 的最終回覆。結果檔路徑必須在 worker 的專案根目錄底下:mission 檔裡的絕對路徑、~、.. 一律拒絕;讀檔前解析符號連結,指到根目錄外的不讀也不送。超過 256 KB 不送。
  • 送給誰:mission 檔的 station 名稱,在 claude agents --json 名冊上恰好一筆對到的 session。查無或多筆都不送(改請 worker 自己決定)。station 是自己時不啟用。
  • 何時不送:沒有啟用時(見上);mission 沒有 station 時;turn 不是正常答覆結束時。
  • mission 檔從哪裡讀:與 dispatch-board 相同的規則——只讀使用者層級目錄,否則 clone 一個陌生 repo 就能讓 mod 把你的檔案送給別人。
  • 預設 ~/.claude/missions/。可在 /plugin 的設定改 missions_dir,但只認使用者層級設定裡的值($.settings.read({ source: 'user' }) 讀到的,通常是 ~/.claude/settings.json);專案設定給的值不採用。
  • 自訂目錄只要設一次:dispatch-relay 沒有自己的 missions_dir 時,沿用 dispatch-board 的 missions_dir。優先序是 dispatch-relay 自己的 → dispatch-board 的 → 預設;dispatch-board 的值同樣只認使用者層級設定。沒裝 dispatch-board 時不受影響。
  • 目錄解析符號連結後必須在家目錄底下、不在本 session 的專案目錄內、不在任何 git 工作樹內。個別 mission 檔經符號連結指到目錄外的不讀。
  • 放行送件:auto mode 下,plugin 的送件會被權限分類器擋下,所以 mod 在 tool.check 只放行自己發出的 SendMessage;其他來源(包括 worker 自己的 SendMessage)一律交給原本的流程,不攔截、不改寫、不放行。
  • 不寫任何檔案(狀態存在 plugin 自己的 $.store)、不執行 mission 檔的完成條件、不連網、不呼叫模型。

安裝前看看它會做什麼

claude plugin validate ./plugins/dispatch-relay

結果(v0.2.0):

hooks: session.start, prompt.submit, prompt.compose, turn.start, tool.call,
       tool.call{tool=SendMessage}, session.send, tool.check{tool=SendMessage},
       turn.complete, session.end
calls: $.clock.after, $.clock.now, $.env.get, $.fs.exists, $.fs.list, $.fs.read, $.fs.stat,
       $.process.run, $.prompt.submit, $.session.cwd, $.session.id, $.session.root,
       $.session.send, $.settings.read, $.store.delete, $.store.get, $.store.set, $.ui.log
env reads: HOME
env writes: nothing
  • $.process.run:只跑 claude agents --json
  • $.session.send:唯一的送件點,送給名冊解析出的指揮站;只在 turn.complete 與 session.end 裡呼叫,計時器回呼不送件
  • $.prompt.submit:只在兩處排入——送不到時請 worker 自己 SendMessage,與暫存時限到時叫醒 worker
  • $.clock.after、$.clock.now:只用在暫存的時限(10 分鐘)與重確認
  • tool.call(不限工具):只觀察、原樣放行,用來記哪些背景工作還沒通知;不改寫工具的輸入或結果
  • $.fs.*:只讀 mission 目錄、檢查安全邊界、讀結果檔;沒有寫檔

限制

  • 需要 Claude Code v2.1.296 以上(turn.complete、$.session.send、tool.check 的 next.origin.plugin、$.store、$.prompt.submit、$.clock.after、session.end)。0.1.0 的下限是 v2.1.289;0.2.0 新用到的 $.clock.after 與 session.end 只在 v2.1.296 驗證過,更早的版本沒有逐版查。
  • worker 必須有名字(--name)並出現在 claude agents 名冊上;沒命名的前景 session 對不到節點。
  • 經 marketplace 安裝會在每個 session 載入。沒有 mission 寫 station 時它只讀 mission 目錄,不做別的事。
  • 放行送件時無法驗證收件者:plugin 以 session id 送件時,tool.check 看到的收件者是引擎解析後的位址,對不回 session id,所以只驗證寄件 mod 是 dispatch-relay(這是固定的退化,不是異常,所以只在除錯日誌寫一次,不出現在對話畫面)。
  • TaskStop 成功時銷帳(0.2.1):worker 用 TaskStop 停掉背景 Bash、Monitor 或背景 Agent,且結果成功時,mod 會把帳上同 id 的那一筆銷掉(停掉的 Bash 與 Monitor 沒有完成通知,帳要靠這條銷)。TaskStop 失敗(id 不存在或已結束)、結果缺 task_id、或 id 對不上帳時不動帳,不會猜測式清帳;subagent 內的 TaskStop 不算。帳沒銷到時的最壞情形不變:之後的「等待中」回覆被延後到時限才送出(最久 10 分鐘,加重確認最多 5 分鐘),不會漏送;要立即回應時 worker 用 SendMessage。
  • 排程刪除或停止後銷帳(0.2.2):CronDelete 成功時,以輸入的排程 id 銷掉 CronCreate 登的那一筆;ScheduleWakeup 以 stop: true 成功時,銷掉帳上的喚醒。ScheduleWakeup 的 stop 結果也帶 scheduledFor(Claude Code 2.1.301 實測為 0),0.2.1 以前會把它誤登成一筆新的待觸發喚醒,現在 stop 本身不登帳。新的 ScheduleWakeup 取代前一個待觸發的喚醒(同一 session 只會有一個),帳上同步只留新的。失敗、id 對不上帳、或在 subagent 內的呼叫不動帳。帳沒銷到時的最壞情形不變:之後的「等待中」回覆最久延後到時限。
  • 名冊查無指揮站型失敗的辨識(0.2.2):送件失敗原因含引擎的 no live session on this machine has id 時,畫面與日誌附一句說明——名冊以 session id 查不到指揮站,指揮站程序可能仍存活(名冊該列缺 pid 即此型,Claude Code 2.1.296 上指揮站以 bg job 執行時出現)。只改文字,降級規則不變,mod 不自行改送其他位址。
  • 暫存的回覆最久晚 10 分鐘到達指揮站。叫醒每次多一個 request(輸出幾個 token,讀的是 prompt cache;叫醒間隔若超過帳號的 cache TTL,會變成整份 context 的重新建立,這部分沒量過)。
  • 叫醒文字與背景工作的完成通知幾乎同時到時,叫醒旗標只認「下一個主迴圈 turn」,不比對文字:極少數情形下通知先開了 turn,那個 turn 的最終回覆(進度性質)會被當成叫醒 turn 而不附帶;暫存內容仍會送出。
  • session 被強制終止或崩潰時,暫存可能沒送出(內容仍在 worker 的 transcript 裡);session.end 時還沒解析過指揮站 id 的話暫存保留在 $.store,不送也不清。
  • 不隱藏 worker 畫面上的最終回覆、不代寫結果檔。

開發

claude --plugin-dir ./plugins/dispatch-relay   # 單次載入
claude plugin test ./plugins/dispatch-relay     # 跑測試

English

dispatch-relay is the worker-side companion to dispatch-board. Instead of a worker writing its report and then sending the whole thing again with SendMessage, the worker writes the report to a result file (default .mission-result.md in its project root) and ends the turn with one line; at the end of each turn the mod sends what changed in that file, plus the worker's final reply, to the commanding session.

It is opt-in per mission: add "station": "<commander session name>" to a dispatch-board mission file. A session activates only if claude agents --json maps its own session id ($.session.id()) to a name that exactly one node's session matches (case-insensitive) in a mission that has a station. The station name is resolved to a session id from the roster before every send; no match or duplicate names means no send — the worker is asked to send it itself instead (once per content; no loops). Sessions with no stationed mission do nothing, not even read the roster.

Security: the mod sends file contents to another session. It sends only the matched node's result file (relative to the project root, no absolute paths or .., symlinks resolved and kept inside the root, 256 KB cap) and the final reply, only to the one roster session named by station. Mission files are read under the same rules as dispatch-board: a user-level directory under your home, outside the session's project and any git work tree; a custom missions_dir is honoured only from user-level settings (what $.settings.read({ source: 'user' }) returns, normally ~/.claude/settings.json), and when dispatch-relay has none of its own it reuses dispatch-board's (from the same source). Both sessions must be started with --name; run claude once in a new directory to accept the trust prompt before the first claude --bg there; for a --worktree <name> worker, result_file is relative to <repo>/.claude/worktrees/<name>. When forwarding fails, the worker is pointed at the station name first, and at the latest from address only if that message came from the station. In tool.check it allows only its own SendMessage; everything else passes through untouched. It writes no files and runs no completion checks.

Held replies (0.2.0): a worker that starts a background job and ends its turn with a "waiting…" line would otherwise wake the commander once per such turn. When a turn ends while background work is still un-notified (background Bash, Monitor, background Agent, ScheduleWakeup, CronCreate, started by the main loop; settled by the matching completion notification), the final reply is held in the plugin's $.store instead of sent, provided the result file did not change and the worker did not SendMessage itself that turn. Held text is never dropped: it goes out as a held-reply part (order: result file → held-reply → final-reply) on the next normally-answered turn, after a fixed 10-minute limit counted from the first held reply, or at session.end (best effort). At the limit the timer callback only wakes the worker with a "reply ok" prompt and that turn's turn.complete does the send, because a send from inside a timer callback is refused under auto mode; the wake turn's own "ok" is not forwarded. The screen shows a line when a reply is held. A worker that needs the commander right away should use SendMessage itself, which is never delayed. TaskStop (0.2.1): a successful TaskStop from the main loop settles the matching background-job entry by task id (a stopped Bash or Monitor produces no completion notification, so this is the only way it gets settled). A failed TaskStop (unknown or already finished id), a result without task_id, or an id not on the ledger changes nothing and never clears the ledger by guesswork; a TaskStop inside a subagent is ignored. If an entry is somehow left unsettled, later "waiting" replies are still delayed only up to the 10-minute limit (never lost). Schedule settling (0.2.2): a successful CronDelete settles the ledger entry that CronCreate registered (matched by the cron id from the call input), and a successful ScheduleWakeup with stop: true settles the pending wakeup. A stop result also carries scheduledFor (0 on Claude Code 2.1.301), which earlier versions registered as a new pending wakeup; stop is now never registered. A new ScheduleWakeup replaces the previous pending wakeup on the ledger. Failed calls, ids not on the ledger and calls inside a subagent change nothing. Roster-miss hint (0.2.2): when forwarding fails with the engine's no live session on this machine has id, the screen and log line add a note that the roster could not find the station by session id (the station process may still be alive; seen on Claude Code 2.1.296 when the roster row lacks a pid). Text only, the degrade rules are unchanged. Requires Claude Code v2.1.296+.

Source 3 files
hooks/register.ts 633 lines
1// dispatch-relay:worker session 的回報由 mod 在 turn 結束時轉送給指揮站。
2//
3// 作用面(全部):
4//   - prompt.compose 尾端加一段說明(只在啟用時)。
5//   - turn.complete 讀結果檔(預設 `<session 根目錄>/.mission-result.md`),內容有變更才轉送;
6//     worker 本 turn 沒自送時附帶最終回覆。
7//   - tool.check 只放行「本 mod 自己發出」的送件;worker 自己的 SendMessage 原樣通過。
8//   - session.send 只觀察本 mod 自己的送件,記下送達時引擎使用的位址(供降級 prompt 引用),原樣放行。
9//   - 送件失敗時請 worker 自己 SendMessage(先記為已處理,同一內容至多降級一次;降級排不進去則回滾,下次 turn 重送)。
10//   - 仍有未通知的背景工作時最終回覆暫存($.store),於下一則、時限或 session 結束時以 held-reply 送出。
11//     時限到時 $.clock.after 回呼只叫醒 worker($.prompt.submit),由叫醒 turn 的 turn.complete 送出:
12//     auto 下回呼內的 $.session.send 不經 tool.check、送不出去。
13// 不做:不寫任何檔案(日誌走 ui.log、狀態走 store)、不寫結果檔、不執行 mission 檔的完成條件。
14//
15// 啟用判定:`$.session.id()` → `claude agents --json` 反查本 session 的名稱 → mission 目錄裡恰好一個節點的
16// `session` 是這個名稱,且該 mission 有 `station` 欄位(opt-in)。mission 目錄的安全邊界與 dispatch-board 相同。
17
18import type { Register } from 'claude-code'
19
20import {
21  DEFAULT_DIR,
22  HOLD_LIMIT_MS,
23  HOLD_RECHECK_MAX,
24  HOLD_RECHECK_MS,
25  MAX_FILE_BYTES,
26  PLUGIN,
27  ROSTER_TIMEOUT_MS,
28  SECTION_ID,
29  WAKE_TEXT,
30  bgEntryOf,
31  bgRegister,
32  bgSettle,
33  bgSettleCron,
34  bgSettleStopped,
35  bgSettleWake,
36  buildMessage,
37  classifySendFailure,
38  degradeFailedLine,
39  degradePrompt,
40  degradedLine,
41  deletedCronIdOf,
42  deliveredLine,
43  dirRefusal,
44  expandDir,
45  failedAgainLine,
46  failureHint,
47  findIdentity,
48  gitProbePaths,
49  heldLine,
50  inactiveLog,
51  injectionText,
52  isMissionFileName,
53  isUnder,
54  mergeHeld,
55  ownName,
56  parseHeld,
57  parseMission,
58  parseRoster,
59  pickDir,
60  resolveStation,
61  resultChanged,
62  sendCheckVerdict,
63  shouldHold,
64  stoppedTaskIdOf,
65  truncate,
66  trySubmit,
67  wakeStoppedOf,
68} from './logic'
69import type { BgEntry, Built, Held, Identity, RelayMission, Resolution, Roster } from './logic'
70
71// ── 模組狀態(熱重載即重來;持久狀態只放 $.store)─────────────────────────────
72let dirSetting = DEFAULT_DIR
73let identity: Identity | null = null // 啟用後的節點身份;每個答覆 turn 結束時重新判定
74let lastStationId = '' // 最近一次解析到的指揮站 session id:tool.check 比對用
75let lastDelivered = '' // 最近一次成功送達時引擎實際使用的收件位址(uds:…),降級 prompt 引用;綁行程,不進 $.store
76let lastDeliveredStation = '' // 取得 lastDelivered 的那次送件,送往的指揮站 id;與目前 id 不同時不引用該位址
77// forward() 送件期間的指揮站 id,供 session.send 觀察 hook 與位址一起記下。
78// 前提:forward() 不並行——它只在主迴圈的 turn.complete 與 session.end 被呼叫,同一 session 的主迴圈 turn 不重疊。
79// 新增呼叫點前要重新檢查。
80let sendingTo = ''
81let selfSent = false // 本 turn worker 是否自己呼叫過 SendMessage(turn.start 重置)
82let pendingDegrade = false // 本 mod 剛排入一個降級 prompt,等它的 turn.start
83let inDegradedTurn = false // 目前這個 turn 是本 mod 排入的降級 turn
84let lastInactiveLog = '' // 未啟用的原因只在改變時出聲,避免每個 prompt 重複同一行
85let laxRecipientLogged = false
86// 背景工作帳與暫存/叫醒狀態(只在記憶體;暫存內容本身在 $.store)
87let ledger: BgEntry[] = [] // 本 session 主迴圈已發起、尚未收到完成通知的背景工作
88let inTurn = false // turn.start 設起、主迴圈 turn.complete 設落
89let wakeTurn = false // 時限叫醒:在計時器回呼內設定(回呼內排入的 prompt 不觸發 prompt.submit hook),下一個主迴圈 turn.complete 消費
90let flushNext = false // 下一次 turn.complete 必須送出暫存(時限到時 worker 在 turn 中,或叫醒沒成功)
91let holdTimer: { cancel: () => void } | null = null
92let recheckCount = 0 // 時限到時連續判為「在 turn 中」的次數,叫醒後歸零
93let timerEverArmed = false // 這個模組實例是否排過計時器:熱重載後為 false,resumeTimer 才會依 store 重排
94
95function log($: any, text: string, options?: { to: 'debug' }): void {
96  try {
97    $.ui.log(text, options)
98  } catch {}
99}
100
101function logInactive($: any, text: string): void {
102  if (text === lastInactiveLog) return
103  lastInactiveLog = text
104  log($, text)
105}
106
107// ── mission 目錄(安全邊界與 dispatch-board 相同)────────────────────────────
108
109async function realPathOf($: any, path: string): Promise<string | undefined> {
110  const st = await $.fs.stat(path, { resolve: true }).catch(() => undefined)
111  return st?.realPath
112}
113
114type Located = { kind: 'ok'; realDir: string } | { kind: 'missing' } | { kind: 'refused'; error: string }
115
116/** 找出 mission 目錄並檢查安全邊界。任何一步不確定都拒讀,不退而求其次。 */
117async function locate($: any): Promise<Located> {
118  const home = await $.env.get('HOME')
119  if (!home || !home.startsWith('/')) return { kind: 'refused', error: '讀不到家目錄(HOME 未設定),不讀任何 mission 檔' }
120  // 只讀使用者層級設定:本 mod 自訂值的來源檢查,以及沿用 dispatch-board 的 missions_dir。
121  const userSettings = await $.settings.read({ source: 'user' }).catch(() => ({}))
122  const picked = pickDir(dirSetting, userSettings ?? {})
123  if (!picked.ok) return { kind: 'refused', error: picked.error }
124  const expanded = expandDir(picked.dir, home)
125  if (!expanded.ok) return { kind: 'refused', error: expanded.error }
126  const realHome = await realPathOf($, home)
127  if (!realHome) return { kind: 'refused', error: `家目錄 ${home} 解析不了,不讀任何 mission 檔` }
128  const dirStat = await $.fs.stat(expanded.path, { resolve: true }).catch(() => undefined)
129  if (!dirStat) return { kind: 'missing' }
130  if (dirStat.kind !== 'dir' || !dirStat.realPath) return { kind: 'refused', error: `${expanded.path} 不是目錄` }
131  const realDir: string = dirStat.realPath
132  const projectDirs: string[] = []
133  for (const p of [await $.session.root(), await $.session.cwd()]) projectDirs.push((await realPathOf($, p)) ?? p)
134  const gitHits: string[] = []
135  for (const p of gitProbePaths(realDir, realHome)) if (await $.fs.exists(p)) gitHits.push(p)
136  const refused = dirRefusal({ realHome, realDir, projectDirs, gitHits })
137  if (refused) return { kind: 'refused', error: refused }
138  return { kind: 'ok', realDir }
139}
140
141/** 讀目錄第一層的 *.json;經符號連結指到目錄外、太大、格式錯、mission_id 重複的檔一律略過(dispatch-board 會列出原因)。 */
142async function loadMissions($: any, realDir: string): Promise<RelayMission[]> {
143  const out: RelayMission[] = []
144  const entries = await $.fs.list(realDir)
145  const names = entries
146    .filter((e: any) => e.kind !== 'dir' && isMissionFileName(e.name))
147    .map((e: any) => String(e.name))
148    .sort()
149  const ids = new Set<string>()
150  for (const name of names) {
151    const st = await $.fs.stat(`${realDir}/${name}`, { resolve: true }).catch(() => undefined)
152    if (!st?.realPath || !isUnder(st.realPath, realDir) || st.kind !== 'file' || st.size > MAX_FILE_BYTES) continue
153    let text: string
154    try {
155      text = await $.fs.read(st.realPath)
156    } catch {
157      continue
158    }
159    const parsed = parseMission(text, name)
160    if (!parsed.ok || ids.has(parsed.value.missionId)) continue
161    ids.add(parsed.value.missionId)
162    out.push(parsed.value)
163  }
164  return out
165}
166
167async function fetchRoster($: any): Promise<Roster> {
168  try {
169    const r = await $.process.run(['claude', 'agents', '--json'], { timeoutMs: ROSTER_TIMEOUT_MS })
170    return parseRoster(r.exitCode, r.stdout, r.stderr)
171  } catch (err) {
172    return { available: false, note: `claude agents --json 跑不起來:${truncate(String(err), 80)}` }
173  }
174}
175
176/**
177 * 身份判定;never throw。沒有任何 mission 選用 relay(沒有 `station`)時不讀名冊、不啟動任何程式:
178 * 本 mod 經 marketplace 安裝會在每個 session 載入,沒用到它的 session 不該付這個成本。
179 * `full`:已啟用的 worker 重新判定時一律讀名冊,停用訊息才能分辨「節點還在但 mission 拿掉了 station」與「沒有節點」。
180 */
181async function resolve($: any, full = false): Promise<{ res: Resolution; roster: Roster | null }> {
182  try {
183    const where = await locate($)
184    if (where.kind === 'refused') return { res: { kind: 'unavailable', reason: where.error }, roster: null }
185    if (where.kind === 'missing') return { res: { kind: 'no-missions' }, roster: null }
186    const missions = await loadMissions($, where.realDir)
187    if (missions.length === 0) return { res: { kind: 'no-missions' }, roster: null }
188    if (!full && !missions.some(m => m.station)) return { res: { kind: 'no-relay' }, roster: null }
189    let sessionId = ''
190    try {
191      sessionId = String((await $.session.id()) ?? '')
192    } catch {}
193    if (!sessionId) return { res: { kind: 'unavailable', reason: '取不到本 session 的 id' }, roster: null }
194    const roster = await fetchRoster($)
195    if (!roster.available) return { res: { kind: 'unavailable', reason: `名冊不可用(${roster.note})` }, roster }
196    const name = ownName(roster.entries, sessionId)
197    if (!name) return { res: { kind: 'unavailable', reason: '名冊上找不到本 session 的名稱(用 --name 命名的 session 才能對到節點)' }, roster }
198    return { res: findIdentity(missions, name), roster }
199  } catch (err) {
200    return { res: { kind: 'unavailable', reason: `判定身份時出錯:${truncate(String(err), 120)}` }, roster: null }
201  }
202}
203
204/** 名冊上解析得到指揮站就記下它的 session id(session.end 沒有時間再讀名冊時沿用);解析不到不動。 */
205function noteStation(roster: Roster | null, station: string): void {
206  if (!roster) return
207  const to = resolveStation(roster, station)
208  if (to.ok) lastStationId = to.sessionId
209}
210
211/** 啟用嘗試:尚未啟用時才查。 */
212async function tryActivate($: any): Promise<void> {
213  if (identity !== null) return
214  const { res, roster } = await resolve($)
215  if (res.kind === 'match') {
216    identity = res.identity
217    noteStation(roster, identity.station)
218    lastInactiveLog = ''
219    log($, `已啟用:mission ${identity.missionId} 節點 ${identity.nodeId},回報轉送給 ${identity.station}`)
220    return
221  }
222  logInactive($, inactiveLog(res))
223}
224
225// ── 轉送與降級 ──────────────────────────────────────────────────────────────
226
227/**
228 * 唯一的送件點:把訊息送給指揮站。`target` 是名冊加名稱(每次送件前解析成 session id,不猜),或直接給 session id
229 * (session.end 的時間上限很短,沿用最近一次解析到的 id,不再讀名冊)。
230 * 只在 turn.complete 與 session.end 內呼叫;計時器回呼 SHALL NOT 呼叫(auto 下回呼內的送出不經 tool.check,會被拒)。
231 */
232async function forward(
233  $: any,
234  built: Built,
235  target: { roster: Roster | null; station: string } | { sessionId: string },
236): Promise<{ ok: boolean; reason: string }> {
237  let sessionId: string
238  if ('sessionId' in target) {
239    if (!target.sessionId) return { ok: false, reason: '沒有指揮站 session id' }
240    sessionId = target.sessionId
241  } else {
242    const to = resolveStation(target.roster ?? { available: false, note: '沒有名冊' }, target.station)
243    if (!to.ok) return { ok: false, reason: to.reason }
244    sessionId = to.sessionId
245  }
246  lastStationId = sessionId
247  sendingTo = sessionId
248  try {
249    const sent: any = await $.session.send({ to: { sessionId }, text: built.text })
250    return sent && sent.isDelivered ? { ok: true, reason: '' } : { ok: false, reason: String(sent?.reason ?? '未送達') }
251  } catch (err) {
252    return { ok: false, reason: String(err) }
253  } finally {
254    sendingTo = ''
255  }
256}
257
258/** 本 mod 唯一會排入 prompt 的點(降級與時限叫醒共用)。回傳 `null`=進入了,否則為失敗原因。 */
259async function queuePrompt($: any, text: string): Promise<string | null> {
260  return await trySubmit(() => $.prompt.submit({ text }))
261}
262
263/**
264 * 降級點:排一個 turn 請 worker 自己 SendMessage。呼叫端 SHALL 已先把內容記為已處理。
265 * 排入呼叫拋例外,或 resolve 為 `{ drop }`,皆為失敗——後者若當成功,內容會停在「已處理」卻沒有人送。
266 */
267async function degrade($: any, id: Identity, built: Built, reason: string): Promise<{ ok: boolean; reason: string }> {
268  pendingDegrade = true
269  // 上次成功送達的位址只在「送往的正是目前這個指揮站 id」時才給:id 改變代表指揮站重開,舊位址綁的是舊行程。
270  const usable = lastDelivered && lastDeliveredStation === lastStationId ? lastDelivered : ''
271  const text = degradePrompt(built, reason, id.resultFile, { station: id.station, lastDelivered: usable })
272  const failure = await queuePrompt($, text)
273  if (failure === null) return { ok: true, reason: '' }
274  pendingDegrade = false
275  log($, `降級 prompt 排入失敗:${truncate(failure, 120)}`)
276  return { ok: false, reason: failure }
277}
278
279/** 讀結果檔;不存在回 null。解析符號連結後不在 session 根目錄底下的一律不讀——它的內容會被送出去。 */
280async function readResult($: any, root: string, file: string): Promise<string | null> {
281  try {
282    const realRoot = (await realPathOf($, root)) ?? root
283    const st = await $.fs.stat(`${root}/${file}`, { resolve: true }).catch(() => undefined)
284    if (!st) return null
285    if (!st.realPath || !isUnder(st.realPath, realRoot)) {
286      log($, `結果檔 ${file} 解析後不在 session 根目錄底下,不讀也不送`)
287      return null
288    }
289    if (st.kind !== 'file') return null
290    if (st.size > MAX_FILE_BYTES) {
291      log($, `結果檔 ${file} 超過 ${MAX_FILE_BYTES / 1024} KB,不送`)
292      return null
293    }
294    return String(await $.fs.read(st.realPath))
295  } catch {
296    return null
297  }
298}
299
300function sentKey(root: string, file: string): string {
301  return `relay:sent:${root}/${file}`
302}
303
304async function readSent($: any, key: string): Promise<string | undefined> {
305  try {
306    const v = await $.store.get(key)
307    return typeof v === 'string' ? v : undefined
308  } catch {
309    return undefined
310  }
311}
312
313async function markSent($: any, key: string, content: string): Promise<void> {
314  try {
315    await $.store.set(key, content)
316  } catch (err) {
317    log($, `無法記錄已處理的結果檔內容(下次會重送):${truncate(String(err), 120)}`)
318  }
319}
320
321/**
322 * 降級排入失敗時把「已處理」恢復為轉送前的值;轉送前沒有值就刪鍵(缺失視為從未處理,下次送全文)。
323 * 回傳是否恢復成功:失敗時內容仍停在已處理、不會重送,畫面須照實說。
324 */
325async function restoreSent($: any, key: string, prev: string | undefined): Promise<boolean> {
326  try {
327    if (prev === undefined) await $.store.delete(key)
328    else await $.store.set(key, prev)
329    return true
330  } catch (err) {
331    log($, `無法回滾已處理狀態(這份內容不會自動重送):${truncate(String(err), 120)}`)
332    return false
333  }
334}
335
336// ── 暫存的等待中回覆與時限叫醒 ──────────────────────────────────────────────
337
338function heldKey(root: string): string {
339  return `relay:held:${root}`
340}
341
342async function readHeld($: any, root: string): Promise<Held | null> {
343  try {
344    return parseHeld(await $.store.get(heldKey(root)))
345  } catch {
346    return null
347  }
348}
349
350/** 暫存寫不進 store 時回 false:呼叫端改為立即送出(暫存只是延後,寫不進就別延後,漏送不能)。 */
351async function writeHeld($: any, root: string, held: Held): Promise<boolean> {
352  try {
353    await $.store.set(heldKey(root), held)
354    return true
355  } catch (err) {
356    log($, `無法暫存等待中的回覆(改為立即送出):${truncate(String(err), 120)}`)
357    return false
358  }
359}
360
361async function clearHeld($: any, root: string): Promise<void> {
362  try {
363    await $.store.delete(heldKey(root))
364  } catch (err) {
365    log($, `無法清除暫存的等待中回覆(之後可能重複送出):${truncate(String(err), 120)}`)
366  }
367}
368
369async function nowMs($: any): Promise<number> {
370  try {
371    return Number(await $.clock.now())
372  } catch {
373    return Date.now()
374  }
375}
376
377function disarm(): void {
378  try {
379    holdTimer?.cancel()
380  } catch {}
381  holdTimer = null
382}
383
384/** 排一個 ms 毫秒後的計時器(取代既有的)。回呼只叫醒,不送件:auto 下回呼內的送出不經 tool.check。 */
385function arm($: any, root: string, ms: number): void {
386  disarm()
387  timerEverArmed = true
388  try {
389    holdTimer = $.clock.after(Math.max(0, ms), () => {
390      holdTimer = null
391      void onHoldExpiry($, root).catch(() => {})
392    })
393  } catch (err) {
394    holdTimer = null
395    log($, `無法排入暫存時限的計時器(暫存留待下一個答覆 turn 或 session 結束送出):${truncate(String(err), 120)}`)
396  }
397}
398
399/**
400 * 熱重載會取消計時器:下一個 hook 呼叫時依 `$.store` 記錄的起算時間重排。
401 * 只在這個模組實例從未排過計時器時做:已排過並觸發的(叫醒、重確認)不得因下一個 turn.start 再叫醒一次,否則叫醒迴圈。
402 */
403async function resumeTimer($: any): Promise<void> {
404  if (identity === null || holdTimer !== null || timerEverArmed) return
405  let root = ''
406  try {
407    root = await $.session.root()
408  } catch {
409    return
410  }
411  const held = await readHeld($, root)
412  if (held !== null) arm($, root, held.since + HOLD_LIMIT_MS - (await nowMs($)))
413}
414
415/**
416 * 暫存時限到。worker 閒置:以 `$.prompt.submit` 叫醒,旗標在這裡設(回呼內排入的 prompt 不觸發 prompt.submit hook),
417 * 由叫醒 turn 的 turn.complete 送出。worker 在 turn 中:不叫醒,旗標讓該 turn 的 turn.complete 無條件送出;
418 * `inTurn` 可能被 subagent 的 turn.start 誤設,所以定期重確認,連續 HOLD_RECHECK_MAX 次仍在 turn 中就直接叫醒。
419 */
420async function onHoldExpiry($: any, root: string): Promise<void> {
421  if (identity === null || (await readHeld($, root)) === null) return
422  if (inTurn && recheckCount < HOLD_RECHECK_MAX) {
423    recheckCount += 1
424    flushNext = true
425    arm($, root, HOLD_RECHECK_MS)
426    return
427  }
428  recheckCount = 0
429  wakeTurn = true
430  const failure = await queuePrompt($, WAKE_TEXT)
431  if (failure !== null) {
432    wakeTurn = false
433    flushNext = true
434    log($, `暫存時限到了但叫醒 prompt 排入失敗(${truncate(failure, 120)}):暫存留待下一個答覆 turn 或 session 結束時送出`)
435  }
436}
437
438/** session.end(時間上限很短,best-effort):送出暫存的等待中回覆,沿用最近一次的指揮站 id。 */
439async function flushOnEnd($: any): Promise<void> {
440  disarm()
441  if (identity === null) return
442  let root = ''
443  try {
444    root = await $.session.root()
445  } catch {
446    return
447  }
448  const held = await readHeld($, root)
449  if (held === null) return
450  if (!lastStationId) {
451    // 沒有可用的位址:暫存留在 store(session 日後 resume 時由下一個答覆 turn 帶出),不清空
452    log($, 'session 結束時暫存的等待中回覆未能送出:還沒解析過指揮站的 session id(暫存保留,resume 後下一則回報帶出)')
453    return
454  }
455  await clearHeld($, root)
456  const sent = await forward($, buildMessage(identity, undefined, null, '', true, held.text), { sessionId: lastStationId })
457  if (!sent.ok) log($, `session 結束時暫存的等待中回覆未能送出(不會重送):${truncate(sent.reason, 120)}${failureHint(classifySendFailure(sent.reason))}`)
458}
459
460export const register: Register = (on, options) => {
461  const configured = (options as Record<string, unknown> | undefined)?.missions_dir
462  dirSetting = typeof configured === 'string' && configured.trim() ? configured : DEFAULT_DIR
463
464  on('session.start', async ($, e, next) => {
465    await tryActivate($)
466    await resumeTimer($)
467    return next(e)
468  })
469
470  // 啟動時 mission 檔可能還沒寫好、session 可能還沒命名:每個新 prompt 在尚未啟用時重試。
471  // 本 mod 自己排入的 prompt(降級、叫醒)不觸發重試(能降級代表已啟用),也不是背景工作的通知。
472  on('prompt.submit', async ($, e, next) => {
473    const own = (e as any).origin?.kind === 'plugin' && (e as any).origin?.name === PLUGIN
474    if (identity === null && !own) await tryActivate($)
475    // 只觀察:銷帳
476    if (identity !== null && !own) ledger = bgSettle(ledger, (e as any).origin?.kind, String((e as any).text ?? ''))
477    return next(e)
478  })
479
480  on('prompt.compose', async ($, e, next) => {
481    const r = await next(e)
482    if (identity === null) return r
483    return { ...r, sections: [...r.sections, { id: SECTION_ID, text: injectionText(identity), scope: 'session' as const }] }
484  })
485
486  on('turn.start', async ($, e, next) => {
487    // 與 turn.complete 同一道門:subagent 的事件不動主迴圈的 turn 狀態(防禦:subagent 的 turn.start 若誤設 inTurn,主迴圈已閒置時暫存會被當成「在 turn 中」而多重確認)
488    if ((e as any).agentId !== undefined) return next(e)
489    selfSent = false
490    inTurn = true
491    inDegradedTurn = pendingDegrade
492    pendingDegrade = false
493    await resumeTimer($)
494    return next(e)
495  })
496
497  // 只觀察、原樣放行:登帳與 TaskStop/CronDelete/ScheduleWakeup stop 銷帳。結果在 next(e) 之後才看得到 task id;只處理主迴圈(agentId 為 undefined)的呼叫。
498  // 三者都是成功才銷(`isError` 在結果上,不在 `result` 內);停掉的背景 Bash/Monitor、刪掉或停止的排程都沒有後續通知。
499  on('tool.call', async ($, e, next) => {
500    const r = await next(e)
501    if (identity !== null && (e as any).agentId === undefined) {
502      const tool = String((e as any).tool)
503      const entry = bgEntryOf(tool, e as any, (r as any)?.result)
504      if (entry !== null) ledger = bgRegister(ledger, entry)
505      const stopped = stoppedTaskIdOf(tool, (r as any)?.result, (r as any)?.isError)
506      if (stopped !== null) ledger = bgSettleStopped(ledger, stopped)
507      const cronId = deletedCronIdOf(tool, e as any, (r as any)?.isError)
508      if (cronId !== null) ledger = bgSettleCron(ledger, cronId)
509      if (wakeStoppedOf(tool, (r as any)?.result, (r as any)?.isError)) ledger = bgSettleWake(ledger)
510    }
511    return r
512  })
513
514  // 只觀察、原樣放行:記下 worker 本 turn 是否自己送過件。
515  on('tool.call', { tool: 'SendMessage' }, async ($, e, next) => {
516    if (identity !== null && (e as any).agentId === undefined) selfSent = true
517    return next(e)
518  })
519
520  // 只觀察本 mod 自己的送件、原樣放行:送達時記下引擎實際使用的收件位址,供降級 prompt 引用。
521  // origin 形狀是 { kind: 'plugin', name }(與 tool.check 的 next.origin.plugin 不同)。
522  on('session.send', async ($, e, next) => {
523    const origin = (e as any).origin
524    if (!(origin?.kind === 'plugin' && origin?.name === PLUGIN)) return next(e)
525    const r: any = await next(e)
526    if (r?.isDelivered && typeof (e as any).to === 'string' && (e as any).to) {
527      lastDelivered = (e as any).to
528      lastDeliveredStation = sendingTo
529    }
530    return r
531  })
532
533  // 只放行本 mod 自己的送件(auto mode 的分類器會拒絕 plugin 的送件)。其他來源一律交給下一個 hook。
534  on('tool.check', { tool: 'SendMessage' }, async ($, e, next) => {
535    const origin = (next as any).origin
536    const { verdict, lax } = sendCheckVerdict(identity !== null, origin?.plugin, (e as any).input, lastStationId)
537    if (verdict === 'pass') return next(e)
538    if (lax && !laxRecipientLogged) {
539      laxRecipientLogged = true
540      // 這是已知且固定的退化(README「限制」有寫),不是異常:只進除錯日誌,不佔對話畫面
541      log($, '放行送件時無法驗證收件者(事件的收件者是引擎解析後的位址,不是 session id):只驗證寄件 mod 為 dispatch-relay', { to: 'debug' })
542    }
543    return { decision: 'allow' as const, reason: 'dispatch-relay 轉送回報給指揮站' }
544  })
545
546  on('turn.complete', async ($, e, next) => {
547    const r = await next(e)
548    if (e.agentId !== undefined) return r
549    inTurn = false
550    const wasDegraded = inDegradedTurn
551    inDegradedTurn = false
552    const wasWake = wakeTurn
553    wakeTurn = false
554    if (identity === null) return r
555    if (e.reason !== 'answer') {
556      // 叫醒 turn 沒有以答覆結束:不再叫醒(避免迴圈),留給下一個答覆 turn 無條件送出
557      if (wasWake) flushNext = true
558      return r
559    }
560
561    // 每次送件前重新判定:mission 檔被搬走或改派、session 改名時停用;指揮站重開換 id 也跟得上。
562    const { res, roster } = await resolve($, true)
563    if (res.kind !== 'match') {
564      disarm()
565      identity = null
566      logInactive($, `停用(${inactiveLog(res)})`)
567      return r
568    }
569    const id = res.identity
570    identity = id
571    noteStation(roster, id.station)
572
573    let root = ''
574    try {
575      root = await $.session.root()
576    } catch {
577      return r
578    }
579    // 叫醒 turn 與「必須送出」旗標:無條件送出暫存,不再進入暫存
580    const mustFlush = wasWake || flushNext
581    flushNext = false
582    const key = sentKey(root, id.resultFile)
583    const content = await readResult($, root, id.resultFile)
584    const prev = await readSent($, key)
585    const held = await readHeld($, root)
586    // 叫醒 turn 自己的最終回覆是對叫醒文字的應答(「ok」),不是 worker 的回報
587    const answer = wasWake ? '' : e.answer
588    if (shouldHold({ answer, resultChanged: resultChanged(prev, content), selfSent, pending: ledger.length, mustFlush })) {
589      const merged = mergeHeld(held, answer, await nowMs($))
590      if (await writeHeld($, root, merged)) {
591        if (holdTimer === null) arm($, root, merged.since + HOLD_LIMIT_MS - (await nowMs($)))
592        return { ...r, text: heldLine() }
593      }
594    }
595    // 先清空暫存再送,避免同一內容同時經降級與下一次暫存送出兩次
596    if (held !== null) {
597      disarm()
598      await clearHeld($, root)
599    }
600    const built = buildMessage(id, prev, content, answer, selfSent, held?.text ?? '')
601    if (built.parts.length === 0) return r
602
603    const sent = await forward($, built, { roster, station: id.station })
604    if (sent.ok) {
605      if (built.nextSent !== null) await markSent($, key, built.nextSent)
606      return { ...r, text: deliveredLine(built, id.station) }
607    }
608    // 失敗:先把內容記為已處理,才排降級 turn——順序顛倒時,worker 在補記之前就自送並結束 turn 會被重送。
609    const hint = failureHint(classifySendFailure(sent.reason))
610    if (hint) log($, `轉送失敗:${truncate(sent.reason, 160)}${hint}`)
611    if (built.nextSent !== null) await markSent($, key, built.nextSent)
612    if (wasDegraded) {
613      log($, `降級 turn 內轉送再度失敗:${truncate(sent.reason, 120)}${hint}`)
614      return { ...r, text: failedAgainLine(sent.reason) }
615    }
616    const queued = await degrade($, id, built, sent.reason)
617    if (queued.ok) return { ...r, text: degradedLine(sent.reason) }
618    // 降級沒排進去:沒有人會送出這份內容。回滾為轉送前的狀態,讓下一個以答覆結束的 turn 重送(偏向重複而非漏送);
619    // 不自行排任何 prompt,所以不構成迴圈。
620    const result = built.nextSent === null ? 'none' : (await restoreSent($, key, prev)) ? 'resend' : 'lost'
621    const finalReply = built.parts.includes('final-reply')
622    const heldReply = built.parts.includes('held-reply')
623    return { ...r, text: degradeFailedLine(sent.reason, queued.reason, { result, finalReply, heldReply }) }
624  })
625
626  on('session.end', async ($, e, next) => {
627    try {
628      await flushOnEnd($)
629    } catch {}
630    return next(e)
631  })
632}
633
hooks/logic.ts 661 lines
1// dispatch-relay 純函式:mission 檔解析、目錄安全邊界、名冊解析、身份判定、訊息組裝、降級與注入文字。
2// 不碰 $,供 register.ts 與測試共用。
3// 結果檔判定一律比對內容,不看任何工具呼叫的種類或時機(結果檔可能經 Write、Edit、`cat >>` 或 `mv` 寫入)。
4// 目錄安全邊界與名冊解析和 dispatch-board 同一套規則,刻意複製而不跨 plugin import:兩個 mod 必須能各自安裝。
5
6import type { Identity, Part, Resolution } from '../types'
7
8export type { Identity, Part, Resolution }
9
10export const PLUGIN = 'dispatch-relay'
11export const DEFAULT_DIR = '~/.claude/missions'
12export const DEFAULT_RESULT_FILE = '.mission-result.md'
13export const ROSTER_TIMEOUT_MS = 10000
14export const MAX_FILE_BYTES = 256 * 1024
15export const MAX_NODES = 50
16export const SECTION_ID = 'dispatch-relay:relay'
17/** 暫存時限(從第一則暫存起算,固定常數)。 */
18export const HOLD_LIMIT_MS = 10 * 60 * 1000
19/** 時限到時 worker 仍在 turn 中:每隔這麼久再確認一次是否已閒置。 */
20export const HOLD_RECHECK_MS = 60 * 1000
21/**
22 * 重確認的次數上限:連續這麼多次仍判為「在 turn 中」就當作狀態被誤設而直接叫醒。
23 * `inTurn` 只在主迴圈 turn.complete 落下;subagent 的 turn.start 若誤設了它而主迴圈已閒置,沒有上限的話會永遠重確認。
24 * 叫醒 prompt 在 worker 真的還在 turn 中時只會排在該 turn 之後,所以誤叫醒無害。
25 */
26export const HOLD_RECHECK_MAX = 5
27const HOLD_MINUTES = Math.round(HOLD_LIMIT_MS / 60000)
28/** 叫醒文字自帶完整指示:模型看到的會被包成「The <plugin> plugin sent a message: … Address the message above.」。 */
29export const WAKE_TEXT = 'dispatch-relay:暫存的回報已到時限,會在本 turn 結束時轉送給指揮站。只回覆 ok,不要做其他事。'
30
31export function truncate(s: string, max: number): string {
32  const one = s.replace(/\s+/g, ' ').trim()
33  return one.length <= max ? one : `${one.slice(0, max - 1)}…`
34}
35
36// ── 目錄與安全邊界(與 dispatch-board 相同)──────────────────────────────────
37// relay 會把 mission 檔指定的結果檔內容送給另一個 session,所以 mission 檔只從使用者層級的目錄讀:
38// 家目錄底下、不在任何 git 工作樹內、也不在本 session 的專案目錄內。
39
40/** 設定值 → 絕對路徑;只收 `~`、`~/…` 或絕對路徑。 */
41export function expandDir(raw: string, home: string): { ok: true; path: string } | { ok: false; error: string } {
42  const text = raw.trim()
43  if (!text) return { ok: false, error: 'missions_dir 是空的' }
44  if (text.includes('\0')) return { ok: false, error: 'missions_dir 含不合法字元' }
45  if (text === '~') return { ok: true, path: home }
46  if (text.startsWith('~/')) return { ok: true, path: `${home}/${text.slice(2)}` }
47  if (text.startsWith('/')) return { ok: true, path: text }
48  return { ok: false, error: `missions_dir 須為 ~/… 或絕對路徑(收到 ${truncate(text, 60)})` }
49}
50
51export function isUnder(child: string, parent: string): boolean {
52  const p = parent.replace(/\/+$/, '')
53  return child.startsWith(`${p}/`)
54}
55
56export function isSameOrUnder(child: string, parent: string): boolean {
57  return child === parent.replace(/\/+$/, '') || isUnder(child, parent)
58}
59
60/** realDir 往上到(不含)realHome 的每一層:檢查 `.git` 用。 */
61export function gitProbePaths(realDir: string, realHome: string): string[] {
62  const out: string[] = []
63  let p = realDir.replace(/\/+$/, '')
64  while (isUnder(p, realHome)) {
65    out.push(`${p}/.git`)
66    p = p.slice(0, p.lastIndexOf('/'))
67  }
68  return out
69}
70
71export type DirFacts = {
72  realHome: string
73  realDir: string
74  /** 本 session 的專案根與工作目錄(已解析) */
75  projectDirs: readonly string[]
76  /** gitProbePaths 裡存在的那些 */
77  gitHits: readonly string[]
78}
79
80/** 安全邊界判定;回 null=可讀,否則回拒絕原因。 */
81export function dirRefusal(f: DirFacts): string | null {
82  if (!isUnder(f.realDir, f.realHome)) return `mission 目錄 ${f.realDir} 不在家目錄底下,拒讀`
83  for (const p of f.projectDirs) {
84    if (isSameOrUnder(f.realDir, p)) return `mission 目錄 ${f.realDir} 在本 session 的專案目錄內,拒讀`
85  }
86  if (f.gitHits.length) return `mission 目錄 ${f.realDir} 在 git 工作樹內(${f.gitHits[0]}),拒讀`
87  return null
88}
89
90/**
91 * 自訂的 missions_dir 必須來自使用者層級設定(`$.settings.read({ source: 'user' })`,通常是 ~/.claude/settings.json)。
92 * 專案的 .claude/settings.json 也能寫 pluginConfigs;不檢查來源的話,clone 一個陌生 repo
93 * 就能把目錄指到別處、讓 relay 讀對方寫的 mission 檔。預設值不需要來源。
94 */
95export function configRefusal(configured: string, userSettings: Readonly<Record<string, unknown>>): string | null {
96  if (configured.trim() === DEFAULT_DIR) return null
97  if (userDirOption(userSettings, PLUGIN) === configured) return null
98  return 'missions_dir 只接受使用者層級設定(通常是 ~/.claude/settings.json);其他來源的值不採用'
99}
100
101export const BOARD_PLUGIN = 'dispatch-board'
102
103/** 使用者層級設定裡某個 plugin(`<name>` 或 `<name>@<marketplace>`)的 missions_dir;沒設回 undefined。 */
104export function userDirOption(userSettings: Readonly<Record<string, unknown>>, plugin: string): string | undefined {
105  const configs = userSettings.pluginConfigs
106  if (!configs || typeof configs !== 'object') return undefined
107  for (const [key, entry] of Object.entries(configs as Record<string, unknown>)) {
108    if (key !== plugin && !key.startsWith(`${plugin}@`)) continue
109    const v = (entry as { options?: Record<string, unknown> } | null)?.options?.missions_dir
110    if (typeof v === 'string' && v.trim()) return v
111  }
112  return undefined
113}
114
115/**
116 * 要用的 mission 目錄設定。優先序:本 mod 自己的 missions_dir → dispatch-board 的 missions_dir → 預設。
117 * 兩者都只認使用者層級設定:`configured` 是引擎給本 mod 的值(可能來自專案設定,所以非預設值要過 configRefusal);
118 * dispatch-board 的值直接從 `userSettings`(只讀使用者層級設定)取,專案設定裡的 board 鍵看不到、不採用。
119 * 自訂目錄因此只要在 dispatch-board 設一次;沒裝 dispatch-board(設定裡沒有它的鍵)時行為不變。
120 */
121export function pickDir(
122  configured: string,
123  userSettings: Readonly<Record<string, unknown>>,
124): { ok: true; dir: string } | { ok: false; error: string } {
125  if (configured.trim() !== DEFAULT_DIR) {
126    const refused = configRefusal(configured, userSettings)
127    return refused ? { ok: false, error: refused } : { ok: true, dir: configured }
128  }
129  if (userDirOption(userSettings, PLUGIN) !== undefined) return { ok: true, dir: DEFAULT_DIR }
130  return { ok: true, dir: userDirOption(userSettings, BOARD_PLUGIN) ?? DEFAULT_DIR }
131}
132
133/** mission 檔候選:目錄第一層的 `*.json`(子目錄不讀,`done/` 可放收斂完的檔) */
134export function isMissionFileName(name: string): boolean {
135  return name.endsWith('.json') && !name.startsWith('.') && name.length > '.json'.length
136}
137
138// ── mission 檔(relay 只讀它用得到的欄位)─────────────────────────────────────
139
140export type RelayNode = { id: string; session: string; resultFile: string }
141export type RelayMission = { missionId: string; station: string; nodes: RelayNode[] }
142
143const ID_RE = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,79}$/
144
145function optString(v: unknown, field: string, max: number): string {
146  if (v === undefined || v === null) return ''
147  if (typeof v !== 'string') throw new Error(`${field} 必須是字串`)
148  if (v.length > max) throw new Error(`${field} 超過 ${max} 字`)
149  return v.trim()
150}
151
152/**
153 * 結果檔的相對路徑:拒絕絕對路徑、`~`、反斜線與任何 `.`/`..` 段——relay 會把它的內容送出去,
154 * 路徑只能落在 session 根目錄底下。實際讀檔前另以解析後的路徑再確認一次(防符號連結)。
155 */
156export function checkResultFile(raw: string): { ok: true; path: string } | { ok: false; error: string } {
157  const text = raw.trim()
158  if (!text) return { ok: true, path: DEFAULT_RESULT_FILE }
159  if (text.includes('\0') || text.includes('\\')) return { ok: false, error: 'result_file 含不合法字元' }
160  if (text.startsWith('/') || text.startsWith('~')) return { ok: false, error: 'result_file 必須是相對於 session 根目錄的路徑' }
161  const segs = text.split('/')
162  if (segs.some(s => s === '' || s === '.' || s === '..')) return { ok: false, error: 'result_file 不能含空段、. 或 ..' }
163  return { ok: true, path: text }
164}
165
166/** mission 檔文字 → relay 用得到的欄位或原因。mission_id 省略時取檔名(去掉 .json)。 */
167export function parseMission(text: string, fileName: string): { ok: true; value: RelayMission } | { ok: false; reason: string } {
168  let raw: unknown
169  try {
170    raw = JSON.parse(text)
171  } catch {
172    return { ok: false, reason: '不是合法 JSON' }
173  }
174  if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return { ok: false, reason: '最外層必須是 JSON 物件' }
175  const r = raw as Record<string, unknown>
176  try {
177    const missionId = optString(r.mission_id, 'mission_id', 80) || fileName.replace(/\.json$/, '')
178    if (!ID_RE.test(missionId)) throw new Error(`mission_id「${truncate(missionId, 40)}」只能用英數、_ . -`)
179    const station = optString(r.station, 'station', 200)
180    if (!Array.isArray(r.nodes) || r.nodes.length === 0) throw new Error('nodes 必須是非空陣列')
181    if (r.nodes.length > MAX_NODES) throw new Error(`nodes 超過 ${MAX_NODES} 個`)
182    const nodes: RelayNode[] = []
183    const ids = new Set<string>()
184    r.nodes.forEach((n: unknown, i: number) => {
185      if (n === null || typeof n !== 'object' || Array.isArray(n)) throw new Error(`nodes[${i}] 必須是物件`)
186      const o = n as Record<string, unknown>
187      const id = optString(o.id, `nodes[${i}].id`, 80)
188      if (!ID_RE.test(id)) throw new Error(`nodes[${i}].id 缺少或含不合法字元(只能用英數、_ . -)`)
189      if (ids.has(id)) throw new Error(`節點 id「${id}」重複`)
190      ids.add(id)
191      const file = checkResultFile(optString(o.result_file, `${id}.result_file`, 200))
192      if (!file.ok) throw new Error(`${id}.${file.error}`)
193      nodes.push({ id, session: optString(o.session, `${id}.session`, 200), resultFile: file.path })
194    })
195    return { ok: true, value: { missionId, station, nodes } }
196  } catch (err) {
197    return { ok: false, reason: err instanceof Error ? err.message : String(err) }
198  }
199}
200
201// ── session 名冊 ────────────────────────────────────────────────────────────
202
203export type RosterEntry = { name: string; sessionId: string }
204export type Roster = { available: true; entries: RosterEntry[] } | { available: false; note: string }
205
206/** `claude agents --json` 的結果 → 名冊。任何非預期都算不可用,不當成「名冊是空的」。 */
207export function parseRoster(exitCode: number, stdout: string, stderr: string): Roster {
208  if (exitCode !== 0) {
209    const line = stderr.trim().split('\n').pop() ?? ''
210    return { available: false, note: `claude agents --json exit ${exitCode}${line ? `:${truncate(line, 80)}` : ''}` }
211  }
212  let raw: unknown
213  try {
214    raw = JSON.parse(stdout)
215  } catch {
216    return { available: false, note: 'claude agents --json 輸出不是 JSON' }
217  }
218  if (!Array.isArray(raw)) return { available: false, note: 'claude agents --json 輸出不是陣列' }
219  const entries: RosterEntry[] = []
220  for (const e of raw) {
221    if (!e || typeof e !== 'object') continue
222    const o = e as Record<string, unknown>
223    entries.push({
224      name: typeof o.name === 'string' ? o.name : '',
225      sessionId: typeof o.sessionId === 'string' ? o.sessionId : '',
226    })
227  }
228  return { available: true, entries }
229}
230
231export function normalizeName(name: string): string {
232  return name.trim().toLowerCase()
233}
234
235/** 名冊上本 session 的名稱;查無或沒名稱回 ''。 */
236export function ownName(roster: RosterEntry[], sessionId: string): string {
237  for (const e of roster) if (e.sessionId === sessionId && e.name.trim()) return e.name.trim()
238  return ''
239}
240
241/** 指揮站名稱 → session id。查無、同名多筆都不猜。 */
242export function resolveStation(
243  roster: Roster,
244  station: string,
245): { ok: true; sessionId: string } | { ok: false; reason: string } {
246  if (!roster.available) return { ok: false, reason: `名冊不可用(${roster.note})` }
247  const key = normalizeName(station)
248  const ids = [...new Set(roster.entries.filter(e => normalizeName(e.name) === key && e.sessionId).map(e => e.sessionId))]
249  if (ids.length === 0) return { ok: false, reason: `名冊上沒有名為 ${station} 的 session` }
250  if (ids.length > 1) return { ok: false, reason: `名冊上有 ${ids.length} 個名為 ${station} 的 session,不猜` }
251  return { ok: true, sessionId: ids[0] as string }
252}
253
254// ── 身份判定 ────────────────────────────────────────────────────────────────
255
256/**
257 * 本 session 的名稱 → 它在 mission 目錄裡負責的節點。名稱比對不分大小寫。
258 * 恰好一個節點才算數:零個是「不是 worker」、多個是「不知道是哪一個」,都不啟用——錯認身份會把
259 * 別人的結果檔送出去。對到的 mission 沒有 `station`=沒有選用 relay,同樣不啟用。
260 */
261export function findIdentity(missions: readonly RelayMission[], name: string): Resolution {
262  if (!name) return { kind: 'none', name }
263  const key = normalizeName(name)
264  const hits: { m: RelayMission; n: RelayNode }[] = []
265  for (const m of missions) for (const n of m.nodes) if (n.session && normalizeName(n.session) === key) hits.push({ m, n })
266  if (hits.length === 0) return { kind: 'none', name }
267  if (hits.length > 1) return { kind: 'ambiguous', candidates: hits.map(h => `${h.m.missionId}/${h.n.id}`) }
268  const { m, n } = hits[0] as { m: RelayMission; n: RelayNode }
269  if (!m.station) return { kind: 'no-station', missionId: m.missionId, nodeId: n.id }
270  if (normalizeName(m.station) === key) return { kind: 'self-station', missionId: m.missionId, nodeId: n.id }
271  return { kind: 'match', identity: { missionId: m.missionId, nodeId: n.id, station: m.station, resultFile: n.resultFile } }
272}
273
274/** 未啟用時的日誌一行。 */
275export function inactiveLog(r: Exclude<Resolution, { kind: 'match' }>): string {
276  switch (r.kind) {
277    case 'unavailable':
278      return `未啟用:${r.reason}`
279    case 'no-missions':
280      return '未啟用:mission 目錄不存在或沒有可讀的 mission 檔'
281    case 'no-relay':
282      return '未啟用:mission 目錄裡沒有任何 mission 寫 station(沒有選用 dispatch-relay)'
283    case 'none':
284      return `未啟用:mission 目錄裡沒有指派給本 session${r.name ? `(${r.name})` : ''}的節點`
285    case 'ambiguous':
286      return `未啟用:多重匹配,候選 ${r.candidates.join('、')},不任選其一`
287    case 'no-station':
288      return `未啟用:找到指派給本 session 的節點 ${r.missionId}/${r.nodeId},但該 mission 沒有 station 欄位(沒有選用 dispatch-relay),照原本方式回報`
289    case 'self-station':
290      return `未啟用:mission ${r.missionId} 的 station 就是本 session,不轉送給自己`
291  }
292}
293
294// ── 訊息組裝 ────────────────────────────────────────────────────────────────
295
296export type Built = {
297  /** 空陣列=沒有東西要送。 */
298  parts: Part[]
299  /** 含固定首行的完整訊息;parts 為空時為 ''。 */
300  text: string
301  /** 本文總字數(各部分原文長度加總,不含首行與段落標題)。 */
302  chars: number
303  /** 送出(或交給 worker 自送)後要記為「已處理」的結果檔內容;沒有結果檔部分時為 null。 */
304  nextSent: string | null
305}
306
307/** 結果檔相對上次已處理的內容是否有變更(缺席、空白、相同都不算)。 */
308export function resultChanged(prev: string | undefined, content: string | null): boolean {
309  return content !== null && content !== (prev ?? '') && content.trim() !== ''
310}
311
312/**
313 * 組出本 turn 要轉送的訊息。
314 *
315 * - 結果檔:`content` 非 null、非空白、且與 `prev` 不同才轉送;以 `prev` 為前綴且 `prev` 非空時只送追加段,
316 *   否則送全文。`prev` 缺失(狀態被清空)視為從未處理 → 全文:偏向重複而非漏送。
317 * - 暫存的等待中回覆(`held`,非空才算):排在結果檔之後、最終回覆之前,**不受 `selfSent` 影響**——
318 *   暫存只延後、不丟棄,worker 自送的 turn 一樣把它帶出。
319 * - 最終回覆:非空、且 worker 本 turn 沒自送時附帶為 `final-reply`,**不設長度或行數門檻**——
320 *   worker 結束 turn 只有回報與提問兩種原因,兩者都要送達;以「超過一行」為門檻會吞掉單行提問。
321 * - 自送時不附最終回覆,但結果檔變更仍轉送(結果檔是回報正本,自送的可能只是提問)。
322 */
323export function buildMessage(
324  ids: { missionId: string; nodeId: string },
325  prev: string | undefined,
326  content: string | null,
327  answer: string,
328  selfSent: boolean,
329  held = '',
330): Built {
331  const before = prev ?? ''
332  const sections: { part: Part; body: string }[] = []
333  let nextSent: string | null = null
334  if (content !== null && resultChanged(prev, content)) {
335    if (before !== '' && content.startsWith(before)) {
336      sections.push({ part: 'result-append', body: content.slice(before.length) })
337    } else {
338      sections.push({ part: 'result-full', body: content })
339    }
340    nextSent = content
341  }
342  if (held.trim() !== '') sections.push({ part: 'held-reply', body: held.trim() })
343  if (!selfSent && answer.trim() !== '') sections.push({ part: 'final-reply', body: answer.trim() })
344  if (sections.length === 0) return { parts: [], text: '', chars: 0, nextSent: null }
345  const chars = sections.reduce((n, s) => n + s.body.length, 0)
346  const head = `[dispatch-relay] mission=${ids.missionId} node=${ids.nodeId} parts=${sections.map(s => s.part).join(',')} chars=${chars}`
347  const text = [head, ...sections.map(s => `--- ${s.part} ---\n${s.body}`)].join('\n\n')
348  return { parts: sections.map(s => s.part), text, chars, nextSent }
349}
350
351// ── 畫面一行、降級 prompt、注入段 ───────────────────────────────────────────
352
353const PART_LABEL: Record<Part, string> = {
354  'result-full': '結果檔全文',
355  'result-append': '結果檔追加段',
356  'held-reply': '暫存的等待中回覆',
357  'final-reply': '最終回覆',
358}
359
360export function partsLabel(parts: readonly Part[]): string {
361  return parts.map(p => PART_LABEL[p]).join('+')
362}
363
364export function deliveredLine(built: Built, station: string): string {
365  return `↪ dispatch-relay:${partsLabel(built.parts)}(${built.chars} 字)已送達指揮站 ${station}`
366}
367
368/** 最終回覆被暫存時畫面的一行(不是靜默:worker 與使用者都看得到它被延後了)。 */
369export function heldLine(): string {
370  return `↪ dispatch-relay:背景工作進行中,這則回覆已暫存,於下一則回報或最久 ${HOLD_MINUTES} 分鐘內轉送指揮站`
371}
372
373export function degradedLine(reason: string): string {
374  return `⚠ dispatch-relay:轉送失敗(${truncate(reason, 80)})${failureHint(classifySendFailure(reason))},已請 worker 自行 SendMessage`
375}
376
377/**
378 * `$.prompt.submit` 正常 resolve 時的結果 → 排入失敗的原因;**進入了回 `null`**。
379 * `{ drop }` 是「沒進入 session、也沒拋例外」的那一型:漏掉它,內容會停在已處理卻沒有人送。
380 * 有 `drop` 鍵就算失敗,不看它的型別。以 `null` 而非空字串表示成功:空字串是合法的失敗原因。
381 */
382export function submitFailure(result: unknown): string | null {
383  if (result === null || typeof result !== 'object' || !('drop' in result)) return null
384  const drop = (result as { drop?: unknown }).drop
385  return `被擋下:${typeof drop === 'string' && drop ? drop : '(未附原因)'}`
386}
387
388/**
389 * 執行一次排入並把結局歸成失敗原因;**進入了回 `null`**。拋例外(含同步拋出)與 resolve 為 `{ drop }` 皆為失敗。
390 * 排入呼叫由參數傳入,讓例外路徑可測(測試引擎的 prompt.submit 做不出「拋例外」)。
391 */
392export async function trySubmit(submit: () => Promise<unknown>): Promise<string | null> {
393  try {
394    return submitFailure(await submit())
395  } catch (err) {
396    return String(err) || '排入時拋出例外(無訊息)'
397  }
398}
399
400/**
401 * 送件失敗且降級 prompt 也沒排進去:沒有人會送出這份內容,畫面不得暗示有人接手。
402 *
403 * - `result`:`resend`=已回滾為未處理、下一個以答覆結束的 turn 會重送;`lost`=回滾本身失敗,不會重送;
404 *   `none`=本次沒有結果檔部分。
405 * - `finalReply`:本次是否附帶最終回覆。最終回覆沒有比對狀態可回滾,排入失敗即不會重送,SHALL 明說。
406 * - `heldReply`:本次是否帶出暫存的等待中回覆。暫存在送件前已清空,同樣不會重送。
407 */
408export function degradeFailedLine(
409  sendReason: string,
410  submitReason: string,
411  outcome: { result: 'resend' | 'lost' | 'none'; finalReply: boolean; heldReply?: boolean },
412): string {
413  const parts: string[] = []
414  if (outcome.result === 'resend') parts.push('結果檔內容維持未送出,下次 turn 結束時重送')
415  if (outcome.result === 'lost') parts.push('結果檔內容無法回滾為未處理,不會重送')
416  if (outcome.heldReply) parts.push('暫存的等待中回覆不會重送')
417  if (outcome.finalReply) parts.push('本則最終回覆不會重送')
418  if (outcome.result !== 'resend' || outcome.finalReply || outcome.heldReply) parts.push('請指揮站以完成條件判定進度')
419  return `⚠ dispatch-relay:轉送失敗(${truncate(sendReason, 80)})${failureHint(classifySendFailure(sendReason))},也無法請 worker 自行送出(${truncate(submitReason, 80)});${parts.join(';')}`
420}
421
422export function failedAgainLine(reason: string): string {
423  return `⚠ dispatch-relay:降級 turn 內轉送再度失敗(${truncate(reason, 80)})${failureHint(classifySendFailure(reason))},不再請 worker 自送;請指揮站以完成條件判定進度`
424}
425
426/** 降級 prompt 可引用的收件位址。`lastDelivered`:最近一次成功送達時引擎實際使用的位址。 */
427export type DegradeAddress = { station: string; lastDelivered?: string }
428
429/**
430 * 降級 prompt:載明失敗原因;要求 worker 自己 SendMessage 全文;不要求落成另一個檔案;告訴 worker 送去哪裡。
431 * 位址依可靠度排序:mission 檔的 station 名稱 → 上次成功送達時的位址 → 最近一則來訊的 `from` 位址(僅當來自指揮站)。
432 * from 放最後:worker 可能收過其他 session 的訊息,「最近一則」不一定是指揮站,回錯人會把回報送給第三方。
433 * 各位址候選各占一行,model 不必從連成一串的句子裡切出位址。
434 */
435export function degradePrompt(built: Built, reason: string, resultFile: string, addr: DegradeAddress): string {
436  const what: string[] = []
437  if (built.parts.some(p => p === 'result-full' || p === 'result-append')) {
438    what.push(`${resultFile} 的內容(${built.parts.includes('result-append') ? '本次新增的部分' : '全文'})`)
439  }
440  if (built.parts.includes('held-reply')) what.push('先前暫存的等待中回覆')
441  if (built.parts.includes('final-reply')) what.push('你剛才那則最終回覆')
442  const lines = [
443    `dispatch-relay 沒能把回報轉送給指揮站(${reason})。`,
444    `請改用 SendMessage,把${what.join('與')}原文放進訊息本體送給指揮站。`,
445    `收件者:${addr.station}(mission 檔記錄的指揮站名稱,SendMessage 的 to 直接填這個名稱)。`,
446  ]
447  if (addr.lastDelivered) {
448    lines.push(`名稱送不到時,改用上次成功送達指揮站時使用的位址 ${addr.lastDelivered}(指揮站若已重開可能失效)。`)
449  }
450  lines.push(
451    `以上都送不到時,才回覆最近一則送給你的訊息的 from 位址——僅當該則來自指揮站 ${addr.station};來自其他 session 的訊息不算,不要回給它。`,
452  )
453  lines.push('不要為此另外寫檔。')
454  return lines.join('\n')
455}
456
457/** `prompt.compose` 注入段。刻意只說「寫進結果檔、以一行結束、不要另外 SendMessage」,不提降級細節。 */
458export function injectionText(id: Identity): string {
459  return [
460    `本 session 是 mission ${id.missionId} 節點 ${id.nodeId} 的 worker,掛了 dispatch-relay(回報轉送)。`,
461    `每個 turn 結束時,dispatch-relay 會把專案根目錄 ${id.resultFile} 新增或變更的內容、以及你的最終回覆,原文送給指揮站 ${id.station}。`,
462    `因此:回報寫進 ${id.resultFile} 後直接以一行結束本 turn;不要為同一份回報另外呼叫 SendMessage,也不要為回報再讀取或驗證結果檔。`,
463    '需要問指揮站、被擋住或需要它決策時,照常用 SendMessage,或把問題寫在最終回覆,同樣會送達。',
464    `背景工作進行中需要指揮站立即回應時,用 SendMessage:那時結束 turn 的最終回覆會被暫存,等下一則回報或最久 ${HOLD_MINUTES} 分鐘才送出,自送不受延後。`,
465    '節點是否完成仍以 mission 檔的完成條件為準。',
466  ].join('')
467}
468
469// ── tool.check 的收件者判斷 ─────────────────────────────────────────────────
470
471const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
472
473/**
474 * `SendMessage` 的 `tool.check` 輸入裡的收件者 vs 指揮站 id。
475 * plugin 以 `{ sessionId }` 送件時,事件的收件者通常是引擎解析後的位址(`uds:…`),無從對回 session id:
476 * 此時是 `unverifiable`,退回只驗證寄件 mod。收件者明確是另一個 session id 時是 `mismatch`。
477 */
478export function classifyRecipient(input: unknown, station: string): 'match' | 'mismatch' | 'unverifiable' {
479  const to = input && typeof input === 'object' ? (input as any).to ?? (input as any).recipient : undefined
480  if (typeof to !== 'string' || to === '') return 'unverifiable'
481  if (station && to === station) return 'match'
482  return UUID_RE.test(to) ? 'mismatch' : 'unverifiable'
483}
484
485/**
486 * `tool.check { tool: 'SendMessage' }` 的判定:只放行「由本 mod 發出、且收件者不是別的 session」的送件。
487 * 其餘一律 `pass`(交給下一個 hook/引擎原本的流程)——worker 自己的 SendMessage 不被攔截、改寫或拒絕。
488 * `lax` 為真代表收件者無法驗證、只驗證了寄件 mod,呼叫端 SHALL 出聲。
489 */
490export function sendCheckVerdict(
491  active: boolean,
492  originPlugin: string | undefined,
493  input: unknown,
494  station: string,
495): { verdict: 'allow' | 'pass'; lax: boolean } {
496  if (!active || originPlugin !== PLUGIN) return { verdict: 'pass', lax: false }
497  const recipient = classifyRecipient(input, station)
498  if (recipient === 'mismatch') return { verdict: 'pass', lax: false }
499  return { verdict: 'allow', lax: recipient === 'unverifiable' }
500}
501
502// ── 暫存的等待中回覆與背景工作帳 ────────────────────────────────────────────
503
504/** 存在 `$.store` 的暫存:原文(連續暫存以空行串接)與第一則暫存的時間(毫秒,時限由此起算)。 */
505export type Held = { text: string; since: number }
506
507export function parseHeld(v: unknown): Held | null {
508  if (v === null || typeof v !== 'object') return null
509  const { text, since } = v as { text?: unknown; since?: unknown }
510  return typeof text === 'string' && text.trim() !== '' && typeof since === 'number' ? { text, since } : null
511}
512
513/** 併入一則新的暫存:起算時間沿用第一則,連續暫存不重設時限。 */
514export function mergeHeld(held: Held | null, answer: string, now: number): Held {
515  const body = answer.trim()
516  return held ? { text: `${held.text}\n\n${body}`, since: held.since } : { text: body, since: now }
517}
518
519/**
520 * 本 turn 的最終回覆是否暫存。`pending`=帳上未通知的背景工作數;`mustFlush`=叫醒 turn 或「必須送出」旗標。
521 * 叫醒 turn 必須無條件送出:它若再進入暫存,每個時限就叫醒一次、永遠送不出去。
522 */
523export function shouldHold(i: { answer: string; resultChanged: boolean; selfSent: boolean; pending: number; mustFlush: boolean }): boolean {
524  return !i.mustFlush && i.pending > 0 && !i.selfSent && !i.resultChanged && i.answer.trim() !== ''
525}
526
527/**
528 * 帳上一筆:背景工作以 id 對回通知;排程以 prompt 原文對回觸發(觸發 prompt 不帶 id)。
529 * 排程的識別放在 `sched`、不放 `id`:`id` 的有無是背景工作類/排程類的判定(bgSettle 的同類銷帳依此分)。
530 */
531export type BgEntry = { id?: string; text?: string; sched?: { cronId?: string; wake?: true } }
532
533const nonEmpty = (v: unknown): v is string => typeof v === 'string' && v !== ''
534
535/**
536 * `tool.call` 結果 → 要登的帳;沒有(失敗、前景、會隨最終回覆終止)回 null。
537 * 工具參數在事件頂層(Bash 事件的 keys 為 command、description、tool、tool_use_id,沒有 `input`);
538 * 同時容忍 `input` 內層形狀,讀不到 prompt 時退為空字串(對不上 scheduled-trigger 只會走「銷最舊的排程」)。
539 * `ScheduleWakeup` 的 `stop: true` 結果也帶 `scheduledFor`(Claude Code 2.1.301 實測為 0),以 `stopped` 排除:它是銷帳,不是登帳。
540 * TaskStop、CronDelete、ScheduleWakeup stop 不在這裡登帳;它們的銷帳見 `stoppedTaskIdOf`/`deletedCronIdOf`/`wakeStoppedOf`。
541 */
542export function bgEntryOf(tool: string, event: { prompt?: unknown; input?: { prompt?: unknown } }, result: unknown): BgEntry | null {
543  const prompt = event?.prompt ?? event?.input?.prompt
544  const r: any = result !== null && typeof result === 'object' ? result : {}
545  switch (tool) {
546    case 'Bash':
547      return nonEmpty(r.backgroundTaskId) && !r.backgroundEndsWithFinalResponse ? { id: r.backgroundTaskId } : null
548    case 'Monitor':
549      return nonEmpty(r.taskId) ? { id: r.taskId } : null
550    case 'Agent':
551    case 'Task':
552      return r.isAsync === true && nonEmpty(r.agentId) ? { id: r.agentId } : null
553    case 'ScheduleWakeup':
554      return r.scheduledFor !== undefined && r.stopped !== true ? { text: String(prompt ?? ''), sched: { wake: true } } : null
555    case 'CronCreate':
556      return nonEmpty(r.id) ? { text: String(prompt ?? ''), sched: { cronId: r.id } } : null
557    default:
558      return null
559  }
560}
561
562/** 登一筆帳(不就地修改)。新的喚醒取代既有的待觸發喚醒(同一 session 只會有一個),所以先移除舊的喚醒類。 */
563export function bgRegister(entries: readonly BgEntry[], entry: BgEntry): BgEntry[] {
564  const kept = entry.sched?.wake ? entries.filter(en => !en.sched?.wake) : entries
565  return [...kept, entry]
566}
567
568/**
569 * 一則 prompt → 銷帳後的帳(不就地修改)。錯誤只能造成「立即送出」或「有上界的延後」,所以對不上的一律偏向不動帳:
570 * Monitor 的事件通知(只帶 `<event>`)不是結束;帶 task id 卻對不上帳(漏登)不銷最舊一筆,否則會誤銷不相干的工作。
571 */
572export function bgSettle(entries: readonly BgEntry[], originKind: string | undefined, text: string): BgEntry[] {
573  const without = (i: number) => entries.filter((_, j) => j !== i)
574  // 對不上時只銷「同類」最舊一筆:通知對的是背景工作(id 類)、觸發對的是排程(text 類),跨類銷帳會誤銷不相干的工作
575  const oldestOf = (isKind: (en: BgEntry) => boolean) => {
576    const i = entries.findIndex(isKind)
577    return i >= 0 ? without(i) : [...entries]
578  }
579  if (originKind === 'task-notification') {
580    const id = /<task-id>\s*([^<\s]+)\s*<\/task-id>/.exec(text)?.[1]
581    if (id === undefined) return oldestOf(en => en.id !== undefined)
582    if (!/<status>/.test(text)) return [...entries]
583    const i = entries.findIndex(en => en.id === id)
584    return i >= 0 ? without(i) : [...entries]
585  }
586  if (originKind === 'peer') {
587    const from = /<agent-message from="([^"]+)"/.exec(text)?.[1]
588    const i = from === undefined ? -1 : entries.findIndex(en => en.id === from)
589    return i >= 0 ? without(i) : [...entries]
590  }
591  if (originKind === 'scheduled-trigger') {
592    const i = entries.findIndex(en => en.text !== undefined && en.text === text)
593    return i >= 0 ? without(i) : oldestOf(en => en.text !== undefined)
594  }
595  return [...entries]
596}
597
598/**
599 * `TaskStop` 的 `tool.call` 結果 → 引擎確認停掉的 task id;不是成功的 TaskStop 回 null。
600 * 成功時 `result` 為 `{ message, task_id, task_type, command }`;失敗(id 不存在、已結束)時 `result` 是字串 `"Error: …"`,
601 * 且 `isError` 在「結果」上(和 `result` 同層),不在 `result` 裡。
602 * 被停掉的背景 Bash 與 Monitor 沒有完成通知,只能靠這條銷帳;背景 Agent 之後仍有 `killed` 通知,先銷無害(對不上帳不動帳)。
603 */
604export function stoppedTaskIdOf(tool: string, result: unknown, isError: unknown): string | null {
605  if (tool !== 'TaskStop' || isError) return null
606  const id = result !== null && typeof result === 'object' ? (result as any).task_id : undefined
607  return nonEmpty(id) ? id : null
608}
609
610/** 銷掉帳上 id 相符的那一筆(不就地修改);對不上不動帳,不以「最舊」之類的猜測銷帳。 */
611export function bgSettleStopped(entries: readonly BgEntry[], id: string): BgEntry[] {
612  const i = entries.findIndex(en => en.id === id)
613  return i >= 0 ? entries.filter((_, j) => j !== i) : [...entries]
614}
615
616/**
617 * `CronDelete` 的 `tool.call` → 被刪掉的排程 id;失敗或取不到回 null(不猜)。輸入 `id` 在事件頂層,
618 * 成功結果為 `{ id }`、沒有 `isError`;失敗時 `isError` 為真、結果為字串 `"Error: No scheduled job with id '…'"`。
619 * id 取輸入,同時容忍 `input` 內層形狀。
620 */
621export function deletedCronIdOf(tool: string, event: { id?: unknown; input?: { id?: unknown } }, isError: unknown): string | null {
622  if (tool !== 'CronDelete' || isError) return null
623  const id = event?.id ?? event?.input?.id
624  return nonEmpty(id) ? id : null
625}
626
627/** 銷掉排程 id 相符的那一筆(不就地修改);對不上不動帳,不動背景工作類。 */
628export function bgSettleCron(entries: readonly BgEntry[], cronId: string): BgEntry[] {
629  const i = entries.findIndex(en => en.sched?.cronId === cronId)
630  return i >= 0 ? entries.filter((_, j) => j !== i) : [...entries]
631}
632
633/** `ScheduleWakeup` 以 `stop: true` 成功結束?結果為 `{ …, stopped: true, cancelledWakeups: N }`。 */
634export function wakeStoppedOf(tool: string, result: unknown, isError: unknown): boolean {
635  if (tool !== 'ScheduleWakeup' || isError) return false
636  return result !== null && typeof result === 'object' && (result as any).stopped === true
637}
638
639/** 銷掉全部喚醒類(停止後不會再有喚醒觸發);不動 CronCreate 登的排程與背景工作類。 */
640export function bgSettleWake(entries: readonly BgEntry[]): BgEntry[] {
641  return entries.filter(en => !en.sched?.wake)
642}
643
644// ── 轉送失敗的分類 ──────────────────────────────────────────────────────────
645
646/** Claude Code 2.1.296 的引擎原文。字串改版時分類退回 `other`,即沒有這段說明時的行為。 */
647const ROSTER_MISSING_RE = /no live session on this machine has id/
648
649export type SendFailureKind = 'roster-missing' | 'other'
650
651export function classifySendFailure(reason: string): SendFailureKind {
652  return ROSTER_MISSING_RE.test(reason) ? 'roster-missing' : 'other'
653}
654
655/** 「名冊查無指揮站」型附在畫面與日誌的說明;其他型為空字串。 */
656export function failureHint(kind: SendFailureKind): string {
657  return kind === 'roster-missing'
658    ? '(名冊以 session id 查不到指揮站,指揮站程序可能仍存活——名冊該列缺 pid 時即為此型;降級時請 worker 改用指揮站名稱或其來訊的 from 位址自送)'
659    : ''
660}
661
types/index.d.ts 30 lines
1// dispatch-relay 的型別契約:身份判定的結果與轉送訊息的 part 值域。
2// 本 mod 不使用 `$.state`(日誌走 `$.ui.log`、持久狀態走 `$.store`),故無 PluginState。
3
4/** 轉送訊息首行 `parts=` 的值域。改動屬 BREAKING(指揮站端若要解析訊息,以此為接縫)。 */
5export type Part = 'result-full' | 'result-append' | 'held-reply' | 'final-reply'
6
7/** 已啟用 session 的節點身份。`station` 是 mission 檔寫的名稱;session id 每次送件前由名冊解析,不快取。 */
8export type Identity = { missionId: string; nodeId: string; station: string; resultFile: string }
9
10/**
11 * 身份判定的結果。
12 * - match:恰好一個節點的 `session` 是本 session 的名稱,且該 mission 有 `station`
13 * - no-missions:mission 目錄不存在或沒有可讀的 mission 檔
14 * - no-relay:沒有任何 mission 寫 station(不讀名冊就能確定不啟用)
15 * - none:有選用 relay 的 mission,但沒有節點指派給本 session(`name` 是本 session 的名稱)
16 * - ambiguous:多個節點都指派給本 session
17 * - no-station:唯一匹配,但 mission 沒有 `station`(沒有選用 relay)
18 * - self-station:唯一匹配,但 `station` 就是本 session
19 * - unavailable:mission 目錄被拒讀、名冊不可用、取不到 session id 等
20 */
21export type Resolution =
22  | { kind: 'match'; identity: Identity }
23  | { kind: 'no-missions' }
24  | { kind: 'no-relay' }
25  | { kind: 'none'; name: string }
26  | { kind: 'ambiguous'; candidates: string[] }
27  | { kind: 'no-station'; missionId: string; nodeId: string }
28  | { kind: 'self-station'; missionId: string; nodeId: string }
29  | { kind: 'unavailable'; reason: string }
30