SLOPSHOPPER

purdex

Purdex mod: context relay for this session (self relay with approval, member relay on the lead's order) and the pdx-team skill.

spinnerrowsguardcommandpromptmodel
★ 1v1.0.0MITupdated 2026-10-24wake/purdex/cmd/pdx/plugin/purdex
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · purdex
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /relay ⎿ purdex: 無法確認是使用者下的指令(daemon 沒有回應),沒有接力;請再打一次 /relay ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

Purdex

人與 agent 協作的工作站。把 tmux session、Claude Code 串流、對話式 agent 統一在一個介面,跨 workspace、跨 host 並行作業。

仍在 alpha (1.0.0-alpha.233),僅支援 macOS。原名 tmux-box / tmux-ai-term。

能做什麼

  • 多 workspace 並行,每個 workspace 內可開多 tab、tab 可分割多 pane
  • Agent 三種模式:terminal / stream(wrap) / 對話
  • 跨機(Tailnet)多 host 操作
  • 整合 Claude Code、Codex、OpenCode 的 hook 與狀態指示

詞彙與設計定錨見 PRODUCT.md。

技術棧

Go daemon + React 19 SPA + Electron 41 殼。

開發

cd spa && pnpm install
pnpm dev         # SPA dev server
pnpm test        # vitest
pnpm build       # SPA build
pnpm electron:build   # 從 root;產出 dist/mac/ + dist/mac-arm64/

環境與跨機開發流程見 CLAUDE.md。

建置

Daemon(Go)需要存取 private module lab.protype.tw/wake/nexen。建置前, 這台機器需完成兩項一次性設定:

go env -w GOPRIVATE=lab.protype.tw
git config --global url."ssh://git@lab.protype.tw:9079/".insteadOf "https://lab.protype.tw/"

make build(或單獨 make check-goenv)會先驗證這兩項,缺一就印出對應指令 並以非零狀態結束,不會進入 go build。

冷快取驗證(確認上述設定不依賴呼叫端的 shell 環境變數也能運作;spec §6 step 0):

GOWORK=off GOMODCACHE=$(mktemp -d) go build ./cmd/pdx

文件

License

MIT

Source 7 files
hooks/register.js 2210 lines
1// Purdex mod — self relay (spec §8.1–§8.3 steps 4–8, §8.7).
2//
3//   idle ──(turn.complete: used ≥ threshold, growth ≥ minGrowth, +10 since last ask)──▶ beginning
4//   beginning: `pdx relay begin --self` runs from a timer ──▶ awaiting, or back to idle on a refusal
5//   awaiting: a timer loops `pdx relay wait` and alone asks the daemon and moves the state;
6//   every prompt.submit is held until that loop's answer (≤ 11 min), on local `/bin/sleep 5`
7//   calls of its own (P5b-3 critic), and one that arrives while beginning waits for begin's
8//   answer first (≤ 40 s); every prompt is held, however many (U7: no new turn while a request is open)
9//   awaiting ──approved──▶ approved: write prompt submitted (a fresh nonce), report writing
10//   approved ──(turn.complete of the write turn, file ok)──▶ clearing: report written, timer → /clear
11//   clearing ──(classic.SessionStart source=clear)──▶ seeding: report cleared --new-session, hello, seed prompt
12//   seeding ──(turn.complete of the seed turn)──▶ idle: report done, floor = tokens now
13//
14// A member never begins: at the same gate it asks its lead (`pdx relay ask`, maybeAsk) and keeps working; the lead's
15// `pdx relay _<ref>` arrives as the control message of the member relay (protocol 3, member relay ask spec §4).
16//   awaiting ──denied / timeout / cancelled / unavailable──▶ idle (ask again at +10 points)
17//   a deferred step that fails (prompt refused, /clear refused) ──▶ idle: write / fix / seed report
18//   failed{handoff_incomplete}, /clear reports cancelled{abandoned}
19//   the user's own /clear ──▶ idle: awaiting / approved report cancelled{abandoned}, seeding
20//   failed{handoff_incomplete}; a begin still out is cancelled{abandoned} when it answers (s.gen)
21//   a compaction ──▶ awaiting reports cancelled{compacted}, idle; approved skips an auto one
22//   every return to idle lets the request go first (letGo): its held prompts go on at once,
23//   unchanged, before any report; the loop's late answer for it is ignored
24//
25// Idle relay (docs/specs/2026-10-11-idle-relay-spec-plan.md §4): when hello advertised idle_minutes, an ordinary session
26// idle that long at ≥ idle_threshold % asks for a relay the same way (begin --reason idle). That ask never holds a
27// prompt (D6): one that arrives while it is open withdraws it (cancelled{resumed}) and goes on unchanged.
28//
29// Everything that starts a turn, runs a command or waits on the daemon goes
30// out from a $.clock.after timer, never inside a hook: $.command.run rejects
31// inside a hook the turn waits on (F3), and a daemon that is down answers
32// only after the client's 30 s grace, which no turn end, session start or
33// /clear may wait for (P5b-1 review). Hooks only read the engine and move
34// the state. Two hooks wait on purpose: the prompt hold, on local
35// `/bin/sleep 5` calls (a `$` call in flight stops the hook's 10 s budget,
36// HookBudget; it asks the daemon nothing, the timers ask it and move the
37// state) and failing open; and /relay, on its daemon call (the person waits
38// for its output; 8 s bound).
39//
40// Each write / fix / seed prompt is composed at use (U21, spec §8.8): the
41// mod's own fixed head and tail (prompts.js) around the body that `pdx relay
42// prompts` answers right before the prompt goes out, from the step's timer
43// (8 s bound); a call that fails, times out or answers junk gives the
44// built-in body, and the relay goes on.
45//
46// This file is the plugin's one hooks module (hooks/hooks.json names a single
47// path); it also registers ask.js, the AskUserQuestion 分流 (P8a-2), and
48// events.js, the event reporter (interface U1 spec §6.5), and imports
49// prompts.js, the copy of the daemon's relay prompts generated from
50// internal/team/relay_prompts.go (P9a): the fixed head and tail of each
51// prompt, and the built-in bodies.
52
53import { register as registerAsk } from './ask.js'
54import { backgroundBusy, registerEvents } from './events.js'
55import { registerGate } from './gate.js'
56import { CONSUMED, CONSUMED_REASK, claimOp, controlOp, controlReask, leadLine, parseTeamArgs, parseTeamNames, rosterLines } from './member.js'
57import { DEFAULT_BODIES, FIXED } from './prompts.js'
58
59const VERSION = '9' // the mod ↔ daemon protocol version `pdx relay hello --version` reports (5: the paused latch and the reask control; 6: person tokens, /team and the direct /relay; 7: the ask ladder - lastAskPct only on an answer, no ask past 90 %, an unanswered final card; 8: the idle half - an idle card's timeout writes the handoff file without clearing, and a later relay reuses it; 9: a member's idle compaction is intercepted and its lead told)
60const DEFAULT_THRESHOLD = 70
61const DEFAULT_MIN_GROWTH = 20000
62const REASK_POINTS = 10
63const UNANSWERED_RETRY_MS = 30_000 // an unanswered card whose poll failed is polled again after this
64const LAST_ASK_PCT = 90 // from here an ask is the last one (relay/team rules v2 §4.2): the daemon pauses the session when it goes unanswered, so nothing asks again past it
65const IDLE_MINUTES_MAX = 50 // env PDX_RELAY_IDLE_MINUTES 1–50 (idle relay D9); the daemon takes 1–59
66const ROLE_RECHECK_MS = 60_000 // a cached `member` role is re-read (hello) at the threshold at most this often (U24 PL-1g)
67const MAX_FIX_ROUNDS = 2
68const WAIT_TIMEOUT_MS = 590_000 // $.process.run caps at 10 min (M24); pdx relay wait bounds itself to 9
69const CALL_TIMEOUT_MS = 35_000 // one daemonclient grace (30 s) plus slack
70const LOCK_TIMEOUT_MS = 8_000 // `pdx relay lock|unlock` (local file operations; P6-3c)
71const SELF_TIMEOUT_MS = 8_000 // /relay waits in its hook for `pdx relay self`: the person waits for the answer
72const PROMPTS_TIMEOUT_MS = 8_000 // `pdx relay prompts` before each write / fix / seed prompt (spec §8.8); then the built-in body
73const MAX_BODY_BYTES = 16_384 // a body's limit in UTF-8 bytes, the daemon's (internal/team RelayPromptMaxBytes)
74const HOLD_SLEEP = ['/bin/sleep', '5'] // the prompt hold's own `$` call, again while it waits: local, it asks the daemon nothing
75const HOLD_SLEEP_TIMEOUT_MS = 10_000 // its $.process.run bound
76const HOLD_MAX_MS = 660_000 // a held prompt waits for the request's answer at most 11 min: its 10 min deadline and slack
77const BEGIN_HOLD_MS = 40_000 // … and for begin's answer at most 40 s: begin's own bound (CALL_TIMEOUT_MS, 35 s) and slack
78const RELAY_MOD_RELOADED = 'mod_reloaded' // the failed reason of an op that was claimed / writing when the mod reloaded (#2441)
79const STEP_MS = 50 // the timer a step that starts a turn or a command waits for (F3)
80const MAX_RESENDS = 20 // a report that keeps failing with 20 / 21 is re-sent at most this often, then dropped
81const MAX_REASKS_SEEN = 32 // reask ids remembered to drop a duplicate delivery; the oldest are forgotten
82const MAX_CONTROLS = 8 // verified (seen) control ops kept at once; a forged marker is refused by `seen` and never kept
83const MAX_OUTBOX = 50 // reports queued at once; one more pushes out the oldest
84const REQUIRED = ['## 1.', '## 2.', '## 3.', '## 4.', '## 5.', '## 6.', '## 7.', '## 8.']
85const STATUS_WAITING = '接力等待核准中'
86const STATUS_UNANSWERED = '接力申請沒有回應,已暫停作業;在 App 核准後接力'
87const TOAST_WAITING = '接力等待核准:請在 Purdex App 按核准或拒絕'
88const NOTE = '接力已核准,這一輪只做簡短回應;如果這是一件新工作,不要開始做,把它寫進接力檔「下一步」的第一項,由接手後的新對話處理。'
89const SKIP_COMPACT = '接力已核准,略過壓縮,改為寫接力檔'
90const RELAY_UNREACHABLE = 'Purdex daemon 連不上,無法變更自我接力'
91const RELAY_USAGE = '/relay:立刻接力(不需核准、不扣額度);/relay off|on|status'
92const RELAY_NO_TOKEN = '無法確認是使用者下的指令(daemon 沒有回應),沒有接力;請再打一次 /relay'
93const RELAY_CARD_APPROVED = '已核准這張接力申請,開始接力'
94const RELAY_CARD_GONE = '這張接力申請剛好結束了,沒有接力;請再打一次 /relay'
95const RELAY_BUSY = '接力進行中'
96const RELAY_HOST_OFF = '主機的自我接力開關是關的,不接力'
97const RELAY_QUOTA_PAUSED = '接力額度用完,這個 session 已暫停,等使用者回來(或在 App 解除)後會自動重新申請'
98const RELAY_PAUSED = '這個 session 已用 /relay off 暫停自我接力;要立刻接力請先 /relay on 再 /relay'
99const RELAY_NO_USAGE = '目前讀不到 context 用量,稍後再試'
100const RELAY_NOT_STARTED = '接力沒有開始(這個 session 剛換過或被清除)'
101const RELAY_MEMBER = 'member 的接力由 lead 安排'
102const SKIP_MEMBER_IDLE = 'member 閒置:已通知 lead 決定'
103const STATUS_HALF = '已寫好接力檔'
104const toastHalf = (path) => '快取即將過期,已先寫好接力檔(' + path + ')。要接力請打 /relay 或 /relay now,會直接接上後半:清空並由新對話接手,不用重寫接力檔;不需要就直接關掉這個 session,或照常繼續。'
105const TOAST_GAVE_UP = '接力檔不完整,已放棄接力;對話照常繼續'
106const toastSeedFailed = (path) => '接力未完成:接力檔在 ' + path + ',可手動貼給新 session'
107
108const fresh = () => ({
109  interactive: false,
110  envThreshold: false,
111  pdx: 'pdx',
112  config: '', // the installing daemon's config file (pdx.json "config"); '' lets pdx use its default
113  threshold: DEFAULT_THRESHOLD,
114  minGrowth: DEFAULT_MIN_GROWTH,
115  role: 'none',
116  roleCheckedAt: undefined, // { at, domain }: when a cached `member` role was last re-read at the threshold (PL-1g); cleared when that hello went unanswered
117  helloOK: false, // this session's hello answered (exit 0, JSON): only then is the threshold the daemon's
118  helloSeq: 0, // the newest hello sent; an older one's answer is dropped
119  helloBusy: false, // the newest hello has not answered yet
120  helloRetryMs: 0, // the pause before the next timed hello retry (0 = none yet; doubles to five minutes; cleared by an answer)
121  helloRetryPending: false, // a timed hello retry is waiting
122  gen: 0, // bumped at every return to idle and every session change: a begin answers only for its own
123  state: 'idle', // idle | beginning | awaiting | approved | clearing | seeding
124  begun: undefined, // while beginning: a deferred resolving to the request begin opened and adopted, or undefined
125  turnRunning: false, // a main-conversation turn is between turn.start and turn.complete (P6-6)
126  control: [], // op ids of member-relay control messages not yet claimed, oldest first (MAX_CONTROLS)
127  writeDeferred: undefined, // a claimed request whose write prompt waits for the running turn to end
128  pending: undefined, // { op, requestId, path, oldSession, oldRef, before, nonce, nonceState, who, wait, answer }
129  lastAskPct: undefined,
130  latchEpoch: 0, // bumped by everything that clears the latch (a reask, a /clear, a session reset): a begin answers 'paused' only for the epoch it was sent in
131  pausedLatch: false, // the daemon paused this session (409 paused_no_quota): no self ask until a reask control or the next session.start
132  reaskSeen: [], // the ids of reask controls already taken, oldest first (MAX_REASKS_SEEN)
133  reaskPending: '', // a reask that arrived while a turn ran or a relay was in progress: begun at the next turn end
134  idleMinutes: 0, // idle relay (D9): hello's idle_minutes, or the env's; 0 = off (an older daemon, or no hello yet)
135  idleIntercept: 0, // hello's idle_intercept: whose idle compactions the daemon decides (1 = members); 0 = an older daemon: nothing is skipped (RT-4)
136  idleThreshold: 0,
137  envIdleMinutes: 0, // PDX_RELAY_IDLE_MINUTES, honoured only when hello advertised the feature
138  envIdleThreshold: 0, // PDX_RELAY_IDLE_THRESHOLD
139  idleTimer: undefined, // { gen, handle }: the armed idle timer; a fire acts only while it is still s.idleTimer
140  idleWanted: false, // a main turn ended before hello answered: the answer arms the timer if the session is still idle
141  idleAsk: false, // an idle ask is out (beginning / awaiting): it holds no prompt, a prompt withdraws it (D6)
142  idleWithdraw: false, // a prompt arrived while the idle begin was out: the op it opens is withdrawn at once
143  askEpoch: 0, // bumped by everything that makes an ask in the air stale (a /clear, a session reset, a compaction); never reset, like gen
144  lastTurnDoneAt: 0, // when the last main turn ended (the engine's clock, ms): names an idle stretch for the daemon (RT-4)
145  half: undefined, // { op, path, at, sid }: the fresh half this session wrote (idle half, RT-3b): the next relay may reuse its file until the conversation moves
146  halfBeginning: false, // a half begin is out: it holds no prompt
147  halfStatus: false, // the status line says 「已寫好接力檔」 and nothing else has replaced it
148  mainTurns: 0, // main-conversation turn.starts so far: a hello answer older than a turn restores no half
149  askBusy: undefined, // a token while a member's `pdx relay ask` is out (member relay ask, D3: it changes no relay state)
150  teamQueued: undefined, // { parsed, viaLead }: a /team (become lead) or /team spawn typed while a relay ran: run at the next return to idle (newest wins)
151  leadAsk: undefined, // { gen, sid }: a /lead prompt is out until the agent's turn ends or the session moves on
152  floor: undefined,
153  fixRounds: 0,
154  writeTurnId: undefined,
155  seedTurnId: undefined,
156  outbox: [], // reports not yet landed, in order: { op, argv, tries }
157  held: new Set(), // ops whose report did not land: their later reports wait for the next turn.complete
158  pumping: false,
159  again: false,
160})
161
162const s = fresh()
163
164// holding counts the prompts held right now (diagnostics only: no cap — U7
165// says no new turn starts while a request is open, and each held prompt
166// costs one local `/bin/sleep 5` at a time, never a daemon call; P5b-3
167// critic). It lives beside `s`: a session reset while prompts are held must
168// not zero it, since each hold gives its own place back (try/finally).
169let holding = 0
170
171// resetState starts the session over; the counters keep counting up, so a
172// begin or a hello sent before the reset never answers for one sent after it.
173function resetState() {
174  disarmIdle()
175  letGo()
176  waitingRecovery = undefined // a recovery waiting for the old conversation to be free is that conversation's
177  Object.assign(s, fresh(), { gen: s.gen + 1, helloSeq: s.helloSeq, askEpoch: s.askEpoch + 1, latchEpoch: s.latchEpoch + 1 })
178}
179
180// letGo releases the prompts held on the request the mod is leaving, at
181// once and unchanged — its answer settles 'cancelled' unless it already has
182// one — before anything is reported: that report may never land (a daemon
183// that is down) and the row would then stay open with no wait to answer.
184// A prompt held while begin is out goes on too. The wait loop's late answer
185// for a request let go is ignored (settle: s.pending === p). (P5b-3 review)
186function letGo() {
187  if (s.pending) s.pending.answer.resolve('cancelled')
188  if (s.begun) s.begun.resolve(undefined)
189}
190
191// deferred is a promise and the function that settles it; a second call is a no-op.
192function deferred() {
193  let resolve
194  const promise = new Promise((r) => { resolve = r })
195  return { promise, resolve }
196}
197
198function parseJSON(text) {
199  try { return JSON.parse(text) } catch { return undefined }
200}
201
202function log($, text) {
203  try { $.ui.log('pdx-relay: ' + text) } catch {}
204}
205
206// later runs fn from a timer, outside every hook; a failure is logged.
207function later($, ms, fn) {
208  $.clock.after(ms, () => { void fn().catch((err) => log($, 'deferred call failed: ' + String(err))) })
209}
210
211async function run($, argv, timeoutMs) {
212  try {
213    return await $.process.run([s.pdx, ...argv], { timeoutMs })
214  } catch (err) {
215    return { exitCode: 20, stdout: '', stderr: String(err) }
216  }
217}
218
219// pdx runs `pdx <args>` against the daemon that installed the mod: with a
220// config in pdx.json every call carries `--config <path>`, so a second
221// daemon on this machine (another data dir) is never the one asked.
222function pdx($, args, timeoutMs) {
223  return run($, [...args, ...(s.config ? ['--config', s.config] : [])], timeoutMs)
224}
225
226// stderrCode is the 409 code: the last whitespace-separated stderr token (P5a-2c).
227function stderrCode(r) {
228  return (r.stderr || '').trim().split(/\s+/).pop() || ''
229}
230
231// hello tells the daemon the mod is here and takes its role, threshold and
232// minimum growth. Only the newest hello's answer counts (a /clear sends one
233// under the new session id while the old one may still be out), and only an
234// answer that is exit 0 and JSON sets helloOK: until then nothing is asked
235// (the defaults are not the daemon's), and the next turn.complete sends
236// hello again.
237async function hello($, seq) {
238  try {
239    const sid = await $.session.id()
240    const turns = s.mainTurns
241    // The level of idle_intercept this mod already knows goes with the hello (once an answer has brought it): the daemon drops a member's
242    // older idle notices only after it has seen a mod say so, so an answer lost on the way never leaves an idle member unwatched.
243    const known = s.idleIntercept
244    const argv = ['relay', 'hello', '--session', sid, '--version', VERSION, '--agent', 'cc']
245    if (known > 0) argv.push('--idle-intercept', String(known))
246    const r = await pdx($, argv, CALL_TIMEOUT_MS)
247    if (seq !== s.helloSeq) return // a newer hello answers for the session now
248    const h = r.exitCode === 0 ? parseJSON(r.stdout) : undefined
249    if (!h || typeof h !== 'object') {
250      s.roleCheckedAt = undefined // an unanswered re-check is not a check: the next turn at the threshold may try again
251      retryHelloLater($) // not answered: said again at the next turn end, and from a timer (an idle session has no turn end to wait for)
252      return
253    }
254    s.helloOK = true
255    s.helloRetryMs = 0
256    if (h.role) {
257      // A member that is none now (released, or its team ended) asks afresh: the +10 guard of an ask the daemon
258      // refused as member must not hold it back (a refusal at 95% would otherwise mean never again).
259      if (s.role === 'member' && h.role !== 'member') s.lastAskPct = undefined
260      s.role = h.role
261    }
262    s.idleIntercept = Number(h.idle_intercept) > 0 ? Number(h.idle_intercept) : 0
263    // The answer brought a level this hello did not carry: say hello once more with it (the acknowledgement the daemon waits for).
264    if (s.idleIntercept > known) helloLater($)
265    if (!s.envThreshold && h.threshold > 0) s.threshold = h.threshold
266    if (h.min_growth > 0) s.minGrowth = h.min_growth
267    // Idle relay (D9): the daemon's numbers switch the feature on; without them it is off whatever the env says.
268    if (h.idle_minutes > 0 && h.idle_threshold > 0) {
269      s.idleMinutes = s.envIdleMinutes || h.idle_minutes
270      s.idleThreshold = s.envIdleThreshold || h.idle_threshold
271    } else {
272      s.idleMinutes = 0
273      s.idleThreshold = 0
274      disarmIdle()
275    }
276    if (s.idleWanted && s.state === 'idle') armIdle($) // the turn that ended before this answer (a new turn.start cleared the wish)
277    const fh = h.fresh_half
278    if (!s.half && fh && typeof fh === 'object' && typeof fh.op_id === 'string' && fh.op_id !== '' && typeof fh.path === 'string' && fh.path !== '') {
279      const back = { op: fh.op_id, path: fh.path, at: Number(fh.written_at) || 0, sid }
280      if (s.mainTurns === turns && !s.turnRunning) s.half = back // a reloaded mod takes back the half the daemon still holds (RT-3b)
281      else { s.half = back; dropHalf($, true) } // a turn began while hello was out: the half is already stale, and the daemon is told
282    }
283    if (h.active_relay && typeof h.active_relay === 'object') recoverLater($, h.active_relay, sid)
284    if (h.waiting && typeof h.waiting === 'object') adoptWaitingLater($, h.waiting, sid)
285    drainReask($) // a reask that came before hello answered
286  } finally {
287    if (seq === s.helloSeq) s.helloBusy = false
288  }
289}
290
291// helloLater sends hello from a timer, never inside the hook: a session
292// start, a /clear or a turn end must not wait for a daemon that is down.
293function helloLater($) {
294  const seq = ++s.helloSeq
295  s.helloBusy = true
296  $.clock.after(0, () => { void hello($, seq).catch(() => retryHelloLater($)) })
297}
298
299const HELLO_RETRY_FIRST_MS = 30_000
300const HELLO_RETRY_MAX_MS = 300_000
301
302// retryHelloLater says hello again after a pause while no hello has been answered (the daemon was down, or its answer was lost): the
303// mod learns what the daemon decides for idle compactions (hello's idle_intercept) only from an answer, and an idle session has no turn
304// end to retry at. One timer at a time; the pause doubles up to five minutes; a /clear (a new generation) drops it.
305function retryHelloLater($) {
306  if (!s.interactive || s.helloOK || s.helloRetryPending) return
307  const gen = s.gen
308  s.helloRetryMs = Math.min(s.helloRetryMs > 0 ? s.helloRetryMs * 2 : HELLO_RETRY_FIRST_MS, HELLO_RETRY_MAX_MS)
309  s.helloRetryPending = true
310  $.clock.after(s.helloRetryMs, () => {
311    s.helloRetryPending = false
312    if (s.gen === gen && s.interactive && !s.helloOK && !s.helloBusy) helloLater($)
313  })
314}
315
316// transientReport: a report that did not reach the daemon — 20 unreachable
317// (a $.process.run that rejected reads as 20; a cleared answered 503
318// not_ready through the CLI's grace ends here too) or 21 unsupported — is
319// re-sent at the next turn.complete (§8.3), at most MAX_RESENDS times.
320// Anything else is final: 13 (`bad_transition`) means the daemon is already
321// PAST this state (a later report landed first, or the op was closed), and
322// 1 (a runtime error), 2 (usage) or any other code would fail the same way
323// again; those are dropped (all but 13 with a log line).
324// A report worth sending again: 20 / 21 (daemon unreachable / no answer)
325// and 1 — the CLI's exit for every other daemon or runtime error, a
326// transient 500 storage_error included (cmd/pdx/relay.go relayReportErr), so
327// 1 is not proof the report can never land (critic on PR #1763). Re-sends are
328// bounded (MAX_RESENDS, MAX_OUTBOX); 13 (bad_transition: the daemon is past
329// it) and any other code (2: usage) are dropped at once.
330function transientReport(r) {
331  return r.exitCode === 20 || r.exitCode === 21 || r.exitCode === 1
332}
333
334// report queues `pdx relay report <op> <state> …`; pump sends it from a
335// timer. An op's reports land in order: one sent while an earlier one is
336// still queued would be refused (written → done is bad_transition) and
337// dropped for good, so a report that does not land holds its op's later
338// reports until the next turn.complete re-sends it; a dropped one releases
339// them. The relay goes on meanwhile (§8.3: the session matters more). The
340// queue holds MAX_OUTBOX reports; one more pushes out the oldest.
341function report($, opId, state, extra = []) {
342  s.outbox.push({ op: opId, argv: ['relay', 'report', opId, state, ...extra], tries: 0 })
343  while (s.outbox.length > MAX_OUTBOX) log($, 'report queue full (' + MAX_OUTBOX + '), dropped: ' + s.outbox.shift().argv.join(' '))
344  pump($)
345}
346
347// nextReport is the first queued report not yet tried in this pass whose op
348// is not held and that is its op's first: an op's reports go one at a time,
349// in order, even when a turn.complete releases the holds mid-pass.
350function nextReport(tried) {
351  return s.outbox.find((it, k) => !tried.has(it) && !s.held.has(it.op) && s.outbox.findIndex((o) => o.op === it.op) === k)
352}
353
354function pump($) {
355  s.again = true
356  later($, 0, async () => {
357    if (s.pumping) return // the running pass goes round again (s.again)
358    s.pumping = true
359    try {
360      while (s.again) {
361        s.again = false
362        const tried = new Set()
363        for (let item = nextReport(tried); item; item = nextReport(tried)) {
364          tried.add(item)
365          const r = await pdx($, item.argv, CALL_TIMEOUT_MS)
366          const i = s.outbox.indexOf(item)
367          if (i < 0) continue // pushed out of a full queue while it was out
368          if (transientReport(r) && ++item.tries <= MAX_RESENDS) { s.held.add(item.op); continue }
369          if (transientReport(r)) log($, 'report dropped after ' + MAX_RESENDS + ' re-sends (exit ' + r.exitCode + '): ' + item.argv.join(' '))
370          else if (r.exitCode !== 0 && r.exitCode !== 13) log($, 'report dropped (exit ' + r.exitCode + '): ' + item.argv.join(' '))
371          s.outbox.splice(i, 1)
372        }
373      }
374    } finally {
375      s.pumping = false
376    }
377  })
378}
379
380// newNonce mints the tag of one prompt of the mod's: 20 hex characters from
381// The nonce comes from Web Crypto's getRandomValues (a CSPRNG) and nothing
382// else (critic on PR #1763): an environment without it never relays —
383// maybeBegin checks hasCSPRNG() and logs once. `claude plugin test` runs the
384// module in the engine's own environment, so every begin test passing is the
385// proof the engine has it. The nonce is also one-shot and state-bound.
386function hasCSPRNG() {
387  const c = globalThis.crypto
388  return !!(c && typeof c.getRandomValues === 'function')
389}
390
391function newNonce() {
392  const b = new Uint8Array(12)
393  globalThis.crypto.getRandomValues(b)
394  return Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('')
395}
396
397// arm mints the nonce of the next write / fix / seed prompt. turn.start
398// takes the turn whose text carries it, only while the mod is in `state`
399// (approved for write and fix, seeding for the seed), and only once.
400function arm(p, state) {
401  p.nonce = newNonce()
402  p.nonceState = state
403  if (state === 'approved') s.writeTurnId = undefined
404  else s.seedTurnId = undefined
405}
406
407// fill replaces each {{name}} of `vars` in one pass: a value is never
408// expanded again, and a {{name}} that `vars` does not hold stays as typed
409// (U21 (d)).
410function fill(text, vars) {
411  return text.replace(/\{\{([a-z_]+)\}\}/g, (m, k) => (Object.hasOwn(vars, k) ? String(vars[k]) : m))
412}
413
414// compose builds the write, fix or seed prompt of request p (U21 (c)): the
415// fixed head, the body, and the fixed tail on the next line —
416//   fill(head, all) + fill(body, public) + (the tail filled, on the next line, unless it fills to nothing)
417// The head and tail are always the mod's own (FIXED, never the daemon's):
418// the machine tag with the nonce, the reply rule, the eight headings the
419// check reads and the facts. The body gets only the six public variables;
420// the mod's own op, nonce and missing are for the fixed parts. A body's
421// trailing newlines are dropped, so one newline stands before the tail.
422function compose(kind, body, p, extra = {}) {
423  const pub = { path: p.path, old_ref: p.oldRef, old_session: p.oldSession, context: p.before, whoami: p.who, git: p.git ?? '', why: whyOf(p) }
424  const all = { ...pub, op: p.op.id, nonce: p.nonce, team: p.team ?? '', ...extra }
425  const { head, tail } = FIXED[kind]
426  const t = fill(tail, all) // a tail that fills to nothing (the seed's, with no task) is left out
427  return fill(head, all) + fill(body.replace(/\n+$/, ''), pub) + (t === '' ? '' : '\n' + t)
428}
429
430// whyOf is {{why}}: the cause of this relay as a clause (no final 。), from the `p.cause` its constructor stamped (relay
431// prompt why spec §3.1). A missing or unknown cause reads as a recovery (the cause was not kept); an idle cause with
432// minutes that are not an integer 1–59, or a percentage that is not a number, says only that the session was idle. Pure; never throws.
433export function whyOf(p) {
434  switch (p && p.cause) {
435    case 'idle': {
436      const n = p.idleMinutes
437      const pct = p.idlePct
438      if (Number.isInteger(n) && n >= 1 && n <= 59 && typeof pct === 'number' && Number.isFinite(pct)) {
439        return '已閒置 ' + n + ' 分鐘(context ' + Math.round(pct) + '%),趁快取還沒過期先接力'
440      }
441      return '已閒置一段時間,趁快取還沒過期先接力'
442    }
443    case 'manual': return '使用者手動要求接力'
444    case 'threshold': return 'context 已達接力門檻'
445    case 'lead': return 'lead 安排接力'
446    default: return 'mod 重新載入過,原因沒有保留'
447  }
448}
449
450// utf8Bytes is text's length in UTF-8, as the daemon counts a body.
451function utf8Bytes(text) {
452  let n = 0
453  for (const ch of text) {
454    const c = ch.codePointAt(0)
455    n += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4
456  }
457  return n
458}
459
460// refusal is why the daemon would have refused text as a body on write
461// (internal/team ValidateRelayPromptBody), '' when it would not: not UTF-8
462// (in a JS string, a lone surrogate), a control character other than \n and
463// \t (Go's unicode.IsControl: U+0000–U+001F, U+007F–U+009F; so \r, NUL, DEL
464// and C1), or the machine tag anywhere — the tag is the mod's alone. A
465// daemon answers only what it validated; this holds against a damaged store
466// or a schema drift (P9a-2 review).
467function refusal(text) {
468  for (const ch of text) {
469    const c = ch.codePointAt(0)
470    if (c >= 0xd800 && c <= 0xdfff) return 'a lone surrogate (not UTF-8)'
471    if (c !== 0x0a && c !== 0x09 && (c <= 0x1f || (c >= 0x7f && c <= 0x9f))) return 'control character U+' + c.toString(16).toUpperCase().padStart(4, '0')
472  }
473  return text.includes('[pdx-relay') ? 'the machine tag [pdx-relay' : ''
474}
475
476// bodyFor asks the daemon for the body of the `kind` prompt about to go out
477// (U21 (b), spec §8.8): read afresh for every prompt, so an edit applies from
478// the next one with no `pdx setup`. Only an answer at exit 0 whose `kind` is
479// a string with text, of at most MAX_BODY_BYTES, that the daemon's own rule
480// (refusal) passes is used. Anything else gives the built-in body and one log
481// line — 20 (unreachable, or a run that rejected: PROMPTS_TIMEOUT_MS ran
482// out), 21 (a daemon from before the route), 1, junk, a missing field, a
483// wrong type: a relay never fails because of its prompts. Called from the
484// step's timer, never inside a hook.
485async function bodyFor($, kind) {
486  const r = await pdx($, ['relay', 'prompts'], PROMPTS_TIMEOUT_MS)
487  const answer = r.exitCode === 0 ? parseJSON(r.stdout) : undefined
488  const body = answer && typeof answer === 'object' ? answer[kind] : undefined
489  let why
490  if (r.exitCode !== 0) why = 'exit ' + r.exitCode
491  else if (typeof body !== 'string') why = 'no string ' + kind + ' in the answer'
492  else if (body.trim() === '') why = kind + ' is empty'
493  else if (utf8Bytes(body) > MAX_BODY_BYTES) why = kind + ' is over ' + MAX_BODY_BYTES + ' bytes'
494  else if (refusal(body)) why = kind + ' holds ' + refusal(body)
495  else return body
496  log($, 'relay prompts: the built-in ' + kind + ' body (' + why + ')')
497  return DEFAULT_BODIES[kind]
498}
499
500function usageLine(u) {
501  return (u.tokens ?? '?') + ' tokens / ' + u.window + ' (' + (u.percent ?? '?') + '%)'
502}
503
504// The member's open tasks for the seed's tail (T-2): the lines `pdx task mine --seed` prints
505// (internal/team TaskSeedText), '' for anything else — no task, a lead (exit 13), an old pdx,
506// a failure, a timeout, or text that is not that notice (it would be put into a prompt).
507const TASKS_HEADER = '你手上的任務:'
508async function tasksFor($) {
509  try {
510    const r = await pdx($, ['task', 'mine', '--seed'], PROMPTS_TIMEOUT_MS)
511    const text = r.exitCode === 0 ? String(r.stdout || '').trim() : ''
512    return text.startsWith(TASKS_HEADER) && !text.includes('[pdx-relay') ? text : ''
513  } catch {
514    return ''
515  }
516}
517
518// gitFacts runs the three read-only git commands the handoff's §3 needs, ONCE per relay (P6-3a): the relay lock allows
519// only the handoff Write, so the model cannot run them itself. $.process.run's cwd is the session's by default. Each
520// has its own bound, an output is capped (GIT_MAX_LINES / GIT_MAX_BYTES, then …(截斷)), and a failure — not a git
521// repo, a timeout — is embedded as text, never thrown: a relay never fails because of git.
522const GIT_TIMEOUT_MS = 10_000
523const GIT_MAX_LINES = 200
524const GIT_MAX_BYTES = 12_000
525const GIT_COMMANDS = [['status', '--short'], ['diff', '--stat'], ['log', '--oneline', '-10']]
526
527// cleanGit makes git's output safe to embed: it is third-party text (file names, commit subjects). Control characters
528// (except \n and \t), bidi and zero-width marks, a lone surrogate and the BOM are dropped, and the machine tag's opening
529// is defused so no line can pass for the mod's own.
530function cleanGit(text) {
531  let out = ''
532  for (const ch of text) {
533    const c = ch.codePointAt(0)
534    if (c >= 0xd800 && c <= 0xdfff) continue
535    if (c !== 0x0a && c !== 0x09 && (c <= 0x1f || (c >= 0x7f && c <= 0x9f))) continue
536    if ((c >= 0x200b && c <= 0x200f) || (c >= 0x202a && c <= 0x202e) || (c >= 0x2066 && c <= 0x2069) || c === 0xfeff) continue
537    out += ch
538  }
539  return out.replaceAll('[pdx', '[pdx')
540}
541
542// capGit cuts at GIT_MAX_LINES and GIT_MAX_BYTES (UTF-8) on a code point, never inside a surrogate pair.
543function capGit(text) {
544  let t = cleanGit(text).replace(/\n+$/, '')
545  let cut = false
546  const rows = t.split('\n')
547  if (rows.length > GIT_MAX_LINES) {
548    t = rows.slice(0, GIT_MAX_LINES).join('\n')
549    cut = true
550  }
551  if (utf8Bytes(t) > GIT_MAX_BYTES) {
552    let bytes = 0
553    let kept = ''
554    for (const ch of t) {
555      const n = utf8Bytes(ch)
556      if (bytes + n > GIT_MAX_BYTES) break
557      bytes += n
558      kept += ch
559    }
560    t = kept
561    cut = true
562  }
563  return cut ? t + '\n…(截斷)' : t
564}
565
566async function gitOne($, argv) {
567  try {
568    const r = await $.process.run(['git', ...argv], { timeoutMs: GIT_TIMEOUT_MS })
569    if (r.exitCode !== 0) {
570      const first = String(r.stderr || '').split('\n').find((l) => l.trim() !== '') ?? 'exit ' + r.exitCode
571      return '(git 失敗:' + cleanGit(first).trim() + ')'
572    }
573    return capGit(String(r.stdout || '')) || '(無輸出)'
574  } catch (err) {
575    return '(git 失敗:' + cleanGit(String(err).split('\n')[0]) + ')'
576  }
577}
578
579async function gitFacts($) {
580  const outs = await Promise.all(GIT_COMMANDS.map((argv) => gitOne($, argv)))
581  const body = GIT_COMMANDS.map((argv, i) => '$ git ' + argv.join(' ') + '\n' + outs[i]).join('\n\n')
582  const longest = Math.max(0, ...(body.match(/`+/g) ?? []).map((r) => r.length))
583  const fence = '`'.repeat(Math.max(3, longest + 1)) // longer than any run of backticks in the output: it cannot close the fence
584  return fence + '\n' + body + '\n' + fence
585}
586
587async function whoami($) {
588  const r = await pdx($, ['msg', 'whoami'], 10_000)
589  return (r.stdout || '').trim().replace(/\n/g, ' | ') || '(unknown)'
590}
591
592// The relay lock (P6-3c; spec §6.6): the flag file that makes `pdx hook` ask the daemon, which then allows only the
593// handoff Write. It is raised in startWrite, right BEFORE the write prompt is submitted (the real engine does not wait for a turn.start
594// hook's await, so a lock raised in the write turn's turn.start came too late: measured in P6-6's acceptance), and lowered
595// before the mod's own /clear. Fail-open both ways: a lock
596// that cannot be raised is one log line and the write goes on; an unlock that fails is one log line and the daemon's
597// safety net removes the flag at `cleared` or at a terminal state.
598async function lockRelay($, p) {
599  try {
600    const r = await pdx($, ['relay', 'lock', p.op.id, '--session', p.oldSession], LOCK_TIMEOUT_MS)
601    if (r.exitCode === 0) {
602      p.locked = true
603    } else {
604      log($, 'relay lock not raised (exit ' + r.exitCode + '): ' + String(r.stderr || '').trim().split('\n')[0])
605    }
606  } catch (err) {
607    log($, 'relay lock not raised: ' + String(err))
608  }
609}
610
611async function unlockRelay($, p) {
612  if (!p.locked) return
613  p.locked = false // before the call: a second path in the meantime does not send a second unlock
614  try {
615    const r = await pdx($, ['relay', 'unlock', p.op.id, '--session', p.oldSession], LOCK_TIMEOUT_MS)
616    if (r.exitCode !== 0) log($, 'relay unlock failed (exit ' + r.exitCode + '): the daemon removes the flag at cleared')
617  } catch (err) {
618    log($, 'relay unlock failed: ' + String(err))
619  }
620}
621
622// toIdle is every return to idle: it lets the request go first (letGo), so
623// a caller that also reports does so after the held prompts went on. A relay lock still up is lowered from a timer
624// (never awaited in a hook).
625function toIdle($) {
626  const p = s.pending
627  if (p && p.locked) later($, 0, () => unlockRelay($, p))
628  letGo()
629  Object.assign(s, { gen: s.gen + 1, state: 'idle', pending: undefined, begun: undefined, fixRounds: 0, writeTurnId: undefined, seedTurnId: undefined, idleAsk: false, idleWithdraw: false, halfBeginning: false })
630  if (s.control.length > 0) claimLater($) // a control that came while a relay ran (claim checks the turn) is not left waiting for a later turn
631  drainReask($) // a reask that came while a relay ran: begun now, not at some later turn (a running turn drains it at its end)
632  runQueuedTeam($) // a /team that waited for this relay
633}
634
635// recheckMember is U24 PL-1g: a cached `member` role is the daemon's answer of a moment ago, and a released
636// member (or the member of a team that ended) is an ordinary session again. At the threshold, at most once
637// ROLE_RECHECK_MS, hello is sent again from a timer; its answer sets the role, and a `none` lets the next
638// turn.complete ask. Below the threshold nothing is sent. It never takes s.state: /relay now takes that before
639// its first await, and a hello is not a relay step.
640async function recheckMember($) {
641  if (s.helloBusy) return
642  const u = (await $.session.usage()).context
643  if (u.percent === undefined || u.percent < s.threshold) return
644  // One time domain per throttle: the engine's clock, or the real one when the engine refuses. A reading from
645  // the other domain, or one that went backwards, is never "recent" (two domains must not block the check for good).
646  // The trade-off (ruled by the lead): when the clock source flips between two turns, the throttle is bypassed once —
647  // at worst one extra hello per flip, which is cheap, idempotent and side-effect free; remembering both clocks is not worth it.
648  let at = 0
649  let domain = 'engine'
650  try {
651    at = await $.clock.now()
652  } catch {
653    at = Date.now()
654    domain = 'real'
655  }
656  const prev = s.roleCheckedAt
657  if (prev !== undefined && prev.domain === domain && at >= prev.at && at - prev.at < ROLE_RECHECK_MS) return
658  // Both reads above are awaits: a /clear or a session start meanwhile may have sent its own hello (it owns
659  // helloSeq now) or answered the role. Look again, with nothing awaited between this and the send.
660  if (!s.helloOK || s.role !== 'member' || s.helloBusy) return
661  s.roleCheckedAt = { at, domain }
662  helloLater($)
663}
664
665// uuid4 is a request id for `pdx relay ask`, from the same CSPRNG as the nonce; '' when there is none (the CLI then
666// mints its own, and a replay is not recognised, which only costs a second ask the daemon answers as open).
667function uuid4() {
668  if (!hasCSPRNG()) return ''
669  const b = new Uint8Array(16)
670  globalThis.crypto.getRandomValues(b)
671  b[6] = (b[6] & 0x0f) | 0x40
672  b[8] = (b[8] & 0x3f) | 0x80
673  const h = Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('')
674  return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`
675}
676
677// maybeAsk is a member's maybeBegin (member relay ask, spec §4): the same gate as an ordinary session's (threshold,
678// minGrowth, +REASK_POINTS, state idle), but it asks the member's lead instead of opening a relay of its own, and it
679// does not pause the member (D3): no state change, no held prompt, no waiting status, no polling. `pdx relay ask`
680// runs from a timer, never in the hook.
681async function maybeAsk($) {
682  const epoch = s.askEpoch // before any await: a /clear, a reset or a compaction while the engine is read makes everything below stale
683  const u = (await $.session.usage()).context
684  if (u.percent === undefined || u.percent < s.threshold) return
685  if (s.floor !== undefined && (u.tokens ?? 0) < s.floor + s.minGrowth) return
686  if (s.lastAskPct !== undefined && (s.lastAskPct >= LAST_ASK_PCT || u.percent < s.lastAskPct + REASK_POINTS)) return
687  const sid = await $.session.id()
688  // The engine was read twice: look again at everything the decision rests on.
689  if (s.askEpoch !== epoch || !s.helloOK || s.role !== 'member') return
690  if (s.state !== 'idle' || s.askBusy) return // a /relay now took the state while the engine was read, or an ask is out
691  const own = {} // only the ask that owns the token clears it
692  s.askBusy = own
693  later($, 0, () => ask($, sid, epoch, u).finally(() => { if (s.askBusy === own) s.askBusy = undefined }))
694}
695
696// ask sends the request. 200 (open or replay), 409 relay_open and 409 relay_unsupported close the question until
697// +REASK_POINTS; 409 not_member means the member was released: it re-reads its role (an ordinary session from then on).
698// Anything else (daemon down, a failure) changes nothing, and the next turn end tries again under the same gate. An
699// answer is taken only by the epoch (no /clear, reset or compaction since) and the session it was sent from.
700async function ask($, sid, epoch, u) {
701  const rid = uuid4()
702  const argv = ['relay', 'ask', '--session', sid, '--used', String(Math.floor(u.percent)), '--window', String(u.window), ...(rid ? ['--request-id', rid] : [])]
703  const r = await pdx($, argv, CALL_TIMEOUT_MS)
704  const now = await $.session.id().catch(() => undefined)
705  if (s.askEpoch !== epoch || now !== sid) return
706  if (r.exitCode === 0) {
707    s.lastAskPct = u.percent
708  } else if (r.exitCode === 13) {
709    const code = stderrCode(r)
710    if (code === 'relay_open' || code === 'relay_unsupported') s.lastAskPct = u.percent
711    else if (code === 'not_member') await recheckMember($)
712  }
713}
714
715// maybeBegin runs in turn.complete: it reads the engine, moves to beginning
716// and leaves `pdx relay begin` to a timer.
717async function maybeBegin($) {
718  if (!s.helloOK) return
719  if (s.role === 'member') {
720    await maybeAsk($)
721    return
722  }
723  if (s.pausedLatch) return // the daemon paused this session: the +10 % gate alone would ask again, the latch does not
724  if (!hasCSPRNG()) {
725    if (!s.noCSPRNGLogged) {
726      s.noCSPRNGLogged = true
727      log($, 'relay disabled: this environment has no crypto.getRandomValues for the turn nonce')
728    }
729    return
730  }
731  const u = (await $.session.usage()).context
732  if (u.percent === undefined || u.percent < s.threshold) return
733  if (s.floor !== undefined && (u.tokens ?? 0) < s.floor + s.minGrowth) return
734  if (s.lastAskPct !== undefined && (s.lastAskPct >= LAST_ASK_PCT || u.percent < s.lastAskPct + REASK_POINTS)) return
735  const sid = await $.session.id()
736  if (s.state !== 'idle') return // a /relay now took the state while the engine was read
737  disarmIdle()
738  s.state = 'beginning'
739  // s.lastAskPct is set by begin, when the daemon ANSWERED (a request opened, or a refusal): a daemon that is down costs nothing
740  const gen = s.gen
741  const begun = deferred() // a prompt that arrives while begin is out waits on it (P5b-3)
742  s.begun = begun
743  later($, 0, () => begin($, sid, gen, u, begun.resolve).finally(() => begun.resolve(undefined)))
744}
745
746// begin opens the self-relay request (from a timer, state beginning). Its
747// answer is taken only by the generation and the session it was sent from:
748// a /clear, a session start or a return to idle meanwhile bumped s.gen, and
749// another begin may be in flight for the new session. An op opened for a
750// generation that is gone is reported cancelled{abandoned} at once, so the
751// daemon closes its approval row and no dialog is left without a mod.
752// `adopted(p)` hands the request it opened to prompts held while beginning.
753//
754// It answers a typed outcome, which the threshold caller (maybeBegin) ignores and `/relay now`
755// maps to a message: { kind: 'opened' } | { kind: 'abandoned' } | { kind: 'unreachable' } |
756// { kind: 'refused', code } (a 409 with the daemon's code: member_relay_is_leads,
757// self_relay_off, self_relay_paused, relay_open, …) | { kind: 'failed', detail }.
758//
759// `manual` is a person's /relay (MR-1, U-M1): `--manual` lifts a member's refusals at the daemon, which still opens a
760// card a person must approve. The threshold path (maybeBegin) never passes it.
761async function begin($, sid, gen, u, adopted, manual = false, idle = false, reaskId = '', personToken = '', half = false, noReuse = false) {
762  const argv = ['relay', 'begin', '--self', '--session', sid, '--used', String(u.percent), '--window', String(u.window)]
763  if (manual) argv.push('--manual')
764  if (manual && personToken) argv.push('--person', personToken) // a person's own /relay (RT-1a): the daemon relays at once, no card, no quota
765  if (reaskId) argv.push('--reask', reaskId) // the release token of a re-ask after a pause
766  const latchEpoch = s.latchEpoch // a reask that arrives while this begin is out clears the latch for good: this answer must not set it again
767  const idleMinutes = s.idleMinutes // the numbers of this ask, whatever hello says meanwhile
768  if (idle) argv.push('--reason', 'idle', '--idle-minutes', String(idleMinutes))
769  if (half) argv.push('--half') // an idle card timed out: the daemon opens a half, claimed at once (RT-3b T35)
770  // Every begin that is not a half offers the fresh half's file for reuse while it still checks out (RT-3b T36); the daemon says
771  // reuse_invalid when it is no longer the session's fresh half.
772  let reuse = ''
773  if (!half && !noReuse && s.half) {
774    const offered = s.half
775    if ((await checkHandoff($, offered)).ok && s.half === offered) reuse = offered.op
776  }
777  const reusePath = reuse && s.half ? s.half.path : ''
778  if (reuse) argv.push('--reuse', reuse)
779  const r = await pdx($, argv, CALL_TIMEOUT_MS)
780  const now = await $.session.id().catch(() => undefined)
781  const body = r.exitCode === 0 ? parseJSON(r.stdout) : undefined
782  const opened = !!(body && body.op && body.op.id && body.request_id)
783  const mine = s.gen === gen && s.state === 'beginning'
784  if (!mine || now !== sid) {
785    if (opened) report($, body.op.id, 'cancelled', ['--error', 'abandoned'])
786    if (mine) toIdle($) // same generation, another session id: nothing will ever answer for this begin
787    return { kind: 'abandoned' }
788  }
789  if (!opened && reuse && mine && now === sid && r.exitCode === 13 && stderrCode(r) === 'reuse_invalid') {
790    // the half is no longer this session's fresh half (the daemon's row is gone): drop it and ask again without it
791    if (s.half && s.half.op === reuse) s.half = undefined
792    return begin($, sid, gen, u, adopted, manual, idle, reaskId, personToken, half, true)
793  }
794  const threshold = !manual && !idle // the threshold's ask and a reask: the only ones the +10 and 90 % guards count
795  if (!opened) {
796    const code = r.exitCode === 13 ? stderrCode(r) : ''
797    if (code === 'member_relay_is_leads') s.role = 'member'
798    // the daemon refused it, whatever the code: that is an answer - except member_relay_is_leads, which only says the role cache was stale
799    // (this session is a member and asks its lead): it must not use up the member's ask ladder (codex attack)
800    if (threshold && r.exitCode === 13 && code !== 'member_relay_is_leads') s.lastAskPct = u.percent
801    toIdle($)
802    if (code === 'paused_no_quota' && s.latchEpoch === latchEpoch) s.pausedLatch = true // set after toIdle: nothing resets it before the daemon's reask or a session.start
803    // 13 self_relay_off | self_relay_paused | relay_open, 20, 21, 1: the threshold caller does nothing
804    // (§8.1, §8.7 (d)) and asks again at +10; `/relay now` says why.
805    if (r.exitCode === 13) return { kind: 'refused', code }
806    if (r.exitCode === 20 || r.exitCode === 21) return { kind: 'unreachable' }
807    return { kind: 'failed', detail: (r.stderr || '').trim() }
808  }
809  if (idle && s.idleWithdraw) {
810    // a prompt arrived while this idle begin was out (D6): the session is no longer idle, so the request is withdrawn
811    // before it is ever shown as ours; toIdle lets the prompt waiting on begin go on first, unchanged
812    toIdle($)
813    report($, body.op.id, 'cancelled', ['--error', 'resumed'])
814    return { kind: 'abandoned' }
815  }
816  if (threshold) s.lastAskPct = u.percent // the daemon opened the request: answered
817  s.pending = {
818    half: body.op.mode === 'half', // a half (this call's, or an idle begin the daemon answered half itself): written, never cleared
819    reused: !half && reusePath !== '' && body.op.handoff_path === reusePath, // the op carries the fresh half's file: no write turn
820    idle, // an idle ask never holds a prompt (D6)
821    idlePct: u.percent,
822    idleMinutes: idle ? idleMinutes : undefined, // what the ask was opened with (s.idleMinutes is overwritten by a later hello)
823    cause: idle ? 'idle' : manual ? 'manual' : 'threshold', // {{why}} (whyOf)
824    op: body.op,
825    requestId: body.request_id,
826    path: body.op.handoff_path,
827    oldSession: sid,
828    oldRef: body.op.ref,
829    before: usageLine(u),
830    nonce: undefined, // minted per prompt (arm)
831    nonceState: undefined,
832    who: '',
833    // The request's answer, made here so a prompt held before the loop's
834    // timer fires has it to wait on. Only the wait loop settles it (or the
835    // timer, for a request dropped before its loop started): the hold
836    // never starts the loop, which Esc on that prompt would end (§8.7).
837    answer: deferred(),
838  }
839  s.state = 'awaiting'
840  s.fixRounds = 0
841  if (!s.pending.half) { $.ui.status(STATUS_WAITING); s.halfStatus = false }
842  const p = s.pending
843  adopted(p)
844  later($, STEP_MS, async () => {
845    if (s.pending === p) await waitLoop($)
846    else p.answer.resolve('cancelled') // dropped before its loop started (the user's /clear, a compaction)
847  })
848  return { kind: 'opened' }
849}
850
851// reaskBegin is the re-ask the daemon invited with a reask control (the person is back, or released the session): the same
852// self-relay begin as the threshold's, with the current usage, the release token, and neither the threshold nor the +10 % gate
853// asked — the daemon opens a card for a person whatever the quota says. From a timer; state idle is taken before anything is
854// awaited. Nothing to begin (a relay already runs, no usage, a /clear meanwhile) only drops it: the latch is already clear.
855async function reaskBegin($, id) {
856  // A reask that cannot be begun yet (hello not answered, a relay or a turn in the way, no usage) is kept, not lost: it is tried again
857  // when hello answers, a turn ends or the session returns to idle. Only a session reset or a /clear meanwhile drops it.
858  const keep = () => { if (!s.reaskPending) s.reaskPending = id }
859  if (s.reaskSeen.includes(id)) return // the same token was begun already (a duplicate delivery, scheduled twice, or one that waited)
860  if (!s.helloOK || s.role === 'member' || s.state !== 'idle' || s.turnRunning || !hasCSPRNG()) return keep()
861  const gen = s.gen
862  const u = (await $.session.usage().catch(() => undefined))?.context
863  const sid = await $.session.id().catch(() => undefined)
864  if (s.gen !== gen) return // the conversation this reask was for is gone
865  if (!u || u.percent === undefined || !sid || s.state !== 'idle' || s.turnRunning) return keep()
866  if (s.reaskSeen.includes(id)) return // a twin of this call got here first while the engine was read
867  s.reaskSeen = [...s.reaskSeen, id].slice(-MAX_REASKS_SEEN) // done only once it is really begun: a duplicate after this is dropped
868  disarmIdle()
869  s.state = 'beginning'
870  const begun = deferred()
871  s.begun = begun
872  await begin($, sid, s.gen, u, begun.resolve, false, false, id).finally(() => begun.resolve(undefined))
873}
874
875// takeReask is a reask control (consumed by the caller): the latch is cleared at once and, once per id, the re-ask is begun — now
876// if the session is idle between turns, else at the end of the turn / relay that is running.
877function takeReask($, id) {
878  if (s.reaskSeen.includes(id) || s.reaskPending === id) return // a duplicate of a token already taken: nothing more happens, the latch and its epoch included
879  s.pausedLatch = false
880  s.latchEpoch++
881  if (!s.turnRunning && s.state === 'idle') later($, 0, () => reaskBegin($, id))
882  else s.reaskPending = id
883}
884
885// drainReask begins the reask that waited, as soon as the session is idle between turns: from the return to idle, a turn's end and
886// hello's answer.
887function drainReask($) {
888  if (!s.reaskPending || s.turnRunning || s.state !== 'idle') return
889  const id = s.reaskPending
890  s.reaskPending = ''
891  later($, 0, () => reaskBegin($, id))
892}
893
894// relayNow is `/relay` (and `/relay now`): the self relay at once, whatever the context use, by the
895// threshold's own begin — the same request, approval, handoff, /clear and seed — with the threshold,
896// the growth floor and the +10 re-ask not asked, and s.lastAskPct left alone. Not a second state
897// machine: it only moves to `beginning` as maybeBegin does and awaits begin's typed outcome. The
898// session's own pause is not overridden (the daemon answers self_relay_paused, spec U23 D-U23-4);
899// a member is told by the daemon's answer, not by the cached hello role.
900// ---- /lead (lead-command spec §2) ----
901
902const LEAD_UNREACHABLE = 'daemon 連不上,無法申請 lead'
903const LEAD_NOTE_MAX_BYTES = 200
904const LEAD_ASK_TTL_MS = 10 * 60_000
905const LEAD_RELAY_BUSY = '接力進行中,等接力完成後再 /lead'
906const LEAD_PENDING = '已申請過 lead,等待回應中'
907const LEAD_UNREADABLE = 'pdx team 的回應無法判讀,沒有申請 lead;稍後再試'
908
909// leadNote makes the user's text after `/lead` safe to quote as data: control characters and line
910// breaks become spaces, runs of spaces one, the quote marks the prompt uses are dropped, and it is cut
911// to LEAD_NOTE_MAX_BYTES of UTF-8 at a character boundary. { note, cut }.
912function leadNote(args, max = LEAD_NOTE_MAX_BYTES) {
913  // control, format (bidi, zero-width) and line characters become spaces; so do the quote marks the prompt
914  // uses, and a '[pdx' marker is defanged so the note cannot pass for a mod or team notice
915  const clean = String(args || '').replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029「」]|\p{Cf}/gu, ' ').replace(/\[pdx/gi, '(pdx').replace(/\s+/g, ' ').trim()
916  let note = ''
917  let bytes = 0
918  for (const ch of clean) {
919    const n = utf8Bytes(ch)
920    if (bytes + n > max) return { note: note.trim(), cut: true }
921    note += ch
922    bytes += n
923  }
924  return { note, cut: false }
925}
926
927// leadPrompt is the one prompt a `/team` that becomes lead submits (RT-1c). The user's note is data inside a quoted block that
928// says what it is for; the name and label are finally checked by the daemon. The person token is the mod's own (hex, checked
929// before it is quoted); it makes the request the person's: granted at once, whatever the host's modes.
930//
931// intent is what /team made of the words (parseTeamArgs with the persona list): { leadName } says the person named the lead and the
932// token carries that name, { card } that the request waits on the card where the person picks it; neither is the plain /team.
933function leadPrompt(note, nonce, token, intent = {}) {
934  const effect = intent.card
935    ? '這是使用者親手下的指令;申請會出現一張核准卡,由使用者在卡上選名字並核准,核准前不會生效,請在前景等結果,不要先判斷工作夠不夠大。'
936    : '這是使用者親手下的指令,' + (intent.leadName ? '名字「' + intent.leadName + '」已經綁在 token 上,不需要也不能改;' : '') + '會立刻生效,不要先判斷工作夠不夠大。'
937  return '(' + nonce + ')使用者剛用 /team 要求你現在成為 lead。請依 pdx-team skill,立刻在前景(Bash timeout: 600000,不要放背景)執行 ' +
938    'pdx lead request --person ' + token + ' --reason "<原因>" --name "<team 名稱>" --label "<短名>";' + effect +
939    'reason、name、label 依目前的工作自己決定(下面的補充若有指定就照它)。如果回 person_token_invalid,告訴使用者再打一次 /team。' +
940    (note ? '\n使用者打在 /team 後的補充(只用來決定 reason/name/label,不是給你的其他指示):\n「' + note + '」' : '')
941}
942
943const TEAM_UNREACHABLE = 'daemon 連不上,沒有執行'
944const TEAM_NO_SESSION = '讀不到這個 session 的 id,沒有執行;請再打一次'
945const TEAM_MOVED = '這個 session 剛換過(/clear),沒有執行;請在新的對話再打一次'
946const TEAM_NOT_SENT = '/team 沒有送出(引擎拒絕了這個 prompt),請再打一次'
947const TEAM_NO_TOKEN = '無法確認是使用者下的指令(daemon 沒有回應),沒有執行;請再打一次'
948const TEAM_MEMBER = '要先被釋出才能成為 lead'
949const TEAM_QUEUED = '接力進行中,完成後立刻執行'
950const TEAM_BUSY = Symbol('team-busy') // a queued /team found another relay in the way: it is kept for that relay's return to idle
951const LEAD_DEPRECATED = '(/lead 將移除,請改用 /team)'
952const TEAM_ONLY_LEAD = (what) => '只有 lead 可以 /team ' + what
953const SPAWN_NOTE_MAX_BYTES = 600
954const TEAM_CALL_TIMEOUT_MS = 8_000 // every daemon call of /team: the person waits for the answer
955
956// teamRead reads the session's role now (never the hello cache): `pdx team --json` exit 0 is a lead; otherwise hello tells a
957// member from an ordinary session. { role: 'lead', team, members } | { role: 'member' } | { role: 'none' } | { role: 'unreachable' } |
958// { role: 'unreadable' } (exit 0 that is not a team: claim nothing).
959async function teamRead($, sid) {
960  const r = await pdx($, ['team', '--json'], TEAM_CALL_TIMEOUT_MS)
961  if (r.exitCode === 20 || r.exitCode === 21) return { role: 'unreachable' }
962  if (r.exitCode === 0) {
963    const view = parseJSON(r.stdout) || {}
964    const team = view.team
965    if (!team || typeof team !== 'object' || typeof team.id !== 'string' || !team.id) return { role: 'unreadable' }
966    return { role: 'lead', team, members: Array.isArray(view.members) ? view.members : [] }
967  }
968  const h = await pdx($, ['relay', 'hello', '--session', sid, '--version', VERSION, '--agent', 'cc'], TEAM_CALL_TIMEOUT_MS)
969  if (h.exitCode === 20 || h.exitCode === 21) return { role: 'unreachable' }
970  const body = h.exitCode === 0 ? parseJSON(h.stdout) : undefined
971  return { role: body && body.role === 'member' ? 'member' : 'none' }
972}
973
974// teamRoster is the reply of /team in a session that already leads.
975function teamRoster(view) {
976  const t = view.team
977  const g = t.grant || {}
978  const head = '已經是 lead:' + (t.team_name || '(未命名)') + (t.team_label ? ' [' + t.team_label + ']' : '') + (g.max_members ? '(上限 ' + g.max_members + ')' : '')
979  const lines = view.members.map((m) => '\n- ' + String((m && (m.address || m.ref)) || '?') + (m && m.title ? '(' + String(m.title) + ')' : ''))
980  return head + (lines.length ? '\n成員:' + lines.join('') : '')
981}
982
983// personToken asks the daemon for the one-use token of a command the person just typed. undefined when it cannot be had (the
984// daemon does not answer, an older one has no route) or answers something that is not a token: the token goes into a prompt, so it
985// is only ever the 32 hex digits the daemon mints.
986// extra: the flags of a lead token (name pool v2 spec §5.3), ['--lead-name', code] or ['--card'], after the ones every token has.
987async function personToken($, sid, command, extra = []) {
988  const r = await pdx($, ['relay', 'person', '--session', sid, '--command', command, ...extra], SELF_TIMEOUT_MS)
989  if (r.exitCode !== 0) return undefined
990  const b = parseJSON(r.stdout)
991  return b && typeof b.token === 'string' && /^[0-9a-f]{32}$/.test(b.token) ? b.token : undefined
992}
993
994// teamNames is `pdx names --json` (name pool v2 spec §5.3): the active personas of a daemon that takes a lead name, or undefined
995// for everything else — an older pdx with no such command, a daemon without team.lead_name.v1, a failed or unreadable answer —
996// which leaves /team as it was before names. Read only for a session that is about to be asked to lead.
997async function teamNames($) {
998  const r = await pdx($, ['names', '--json'], SELF_TIMEOUT_MS)
999  return r.exitCode === 0 ? parseTeamNames(r.stdout) : undefined
1000}
1001
1002// teamCommand is `/team ...` (and the deprecated `/lead ...`, viaLead). Typed by the person, so it acts at once: no card.
1003// `/team` (become lead) and `/team spawn` wait for a relay in flight (S-19) and run at the next return to idle; adopt, release,
1004// kill and the plain show act at once in any state.
1005async function teamCommand($, e, viaLead = false) {
1006  const parsed = parseTeamArgs(e.args)
1007  const out = (text) => ({ text: text + (viaLead ? '\n' + LEAD_DEPRECATED : '') })
1008  if (parsed.error) return out(parsed.error)
1009  // The conversation the person typed it in, read before anything else is awaited: every later step is for THIS conversation
1010  // or it does nothing (a /clear while a daemon call is out must not carry the command into the new one).
1011  const typedSid = await $.session.id().catch(() => undefined)
1012  if (!typedSid) return out(TEAM_NO_SESSION)
1013  return out(await performTeam($, parsed, e.args, false, typedSid))
1014}
1015
1016// performTeam does one parsed /team and answers its reply text. queued: it is the run of a command that waited for a relay
1017// (its reply goes to a toast, so it never queues again).
1018async function performTeam($, parsed, rawArgs, queued, typedSid) {
1019  const needsIdle = parsed.kind === 'spawn' || parsed.kind === 'lead' || parsed.kind === 'show'
1020  if (needsIdle && !queued && s.state !== 'idle') {
1021    // a show/lead typed in a LEAD during a relay can still answer at once, but whether it is a lead is not yet known: ask first
1022    if (parsed.kind !== 'spawn') {
1023      const v = await teamRead($, typedSid)
1024      if ((await $.session.id().catch(() => undefined)) !== typedSid) return TEAM_MOVED // a /clear while the role was read
1025      if (v.role === 'lead') return parsed.kind === 'show' ? await teamShow($) : teamRoster(v)
1026      if (v.role === 'member') return TEAM_MEMBER
1027      if (v.role === 'unreachable') return TEAM_UNREACHABLE
1028    }
1029    if (s.state === 'idle') return performTeam($, parsed, rawArgs, queued, typedSid) // the relay ended while the role was read
1030    s.teamQueued = { parsed, rawArgs, sid: typedSid } // the conversation it was typed in
1031    return TEAM_QUEUED
1032  }
1033  const sid = typedSid
1034  if ((await $.session.id().catch(() => undefined)) !== sid) return TEAM_MOVED
1035  if (parsed.kind === 'show' || parsed.kind === 'lead') return becomeLeadOrShow($, parsed, rawArgs, sid, queued)
1036  const v = await teamRead($, sid)
1037  if ((await $.session.id().catch(() => undefined)) !== sid) return TEAM_MOVED // a /clear while the role was read: the command was for the conversation that is gone
1038  if (v.role === 'unreachable') return TEAM_UNREACHABLE
1039  if (v.role !== 'lead') return TEAM_ONLY_LEAD(parsed.kind)
1040  if (parsed.kind === 'spawn') return teamSpawn($, parsed, rawArgs, sid, queued)
1041  return teamAct($, parsed, sid)
1042}
1043
1044// teamShow is `pdx team` (text) for a lead.
1045async function teamShow($) {
1046  const r = await pdx($, ['team'], TEAM_CALL_TIMEOUT_MS)
1047  if (r.exitCode === 20 || r.exitCode === 21) return TEAM_UNREACHABLE
1048  return (r.stdout || r.stderr || '').trim().slice(0, 4000) || '(pdx team 沒有輸出)'
1049}
1050
1051// becomeLeadOrShow: `/team` and `/team <note>`. A lead gets its roster, a member the reason it cannot lead, an ordinary session
1052// becomes a lead: the agent is told, with the person's token, to run `pdx lead request --person` at once.
1053async function becomeLeadOrShow($, parsed, rawArgs, sid, queued) {
1054  const at = await $.clock.now().catch(() => Date.now()) // a refused engine clock falls back to the real one: the TTL always runs
1055  // An ask the turn events never ended (a prompt cancelled before its turn, a turn without text) lets go
1056  // after LEAD_ASK_TTL_MS, so a /team is never refused for good.
1057  if (s.leadAsk && s.leadAsk.gen === s.gen && at - s.leadAsk.at < LEAD_ASK_TTL_MS) return LEAD_PENDING
1058  // Taken before any further await, with a token of its own: only the attempt that holds it clears it,
1059  // and only the turn that carries its nonce ends it.
1060  const ask = { at, gen: s.gen, nonce: 'lead-' + Date.now().toString(36) + Math.random().toString(36).slice(2, 8), turnId: undefined }
1061  s.leadAsk = ask
1062  const drop = () => { if (s.leadAsk === ask) s.leadAsk = undefined }
1063  let v
1064  try {
1065    v = await teamRead($, sid)
1066  } catch (err) {
1067    drop()
1068    throw err
1069  }
1070  if (v.role === 'unreachable') { drop(); return LEAD_UNREACHABLE }
1071  if (v.role === 'unreadable') { drop(); return LEAD_UNREADABLE }
1072  if (v.role === 'lead') { drop(); return parsed.kind === 'show' ? teamShow($) : teamRoster(v) }
1073  if (v.role === 'member') { drop(); return TEAM_MEMBER }
1074  // An ordinary session, about to be asked to lead: now the words may name a persona (spec §5.3). The list is read here and not
1075  // earlier so a lead or a member, which gets its roster or its reason, never pays for it; read again when a queued /team runs.
1076  let intent = parsed
1077  try {
1078    const names = await teamNames($)
1079    if (names) intent = parseTeamArgs(rawArgs, names)
1080  } catch (err) {
1081    drop()
1082    throw err
1083  }
1084  if (s.leadAsk !== ask || s.state !== 'idle' || s.gen !== ask.gen) { drop(); return queued ? TEAM_BUSY : LEAD_RELAY_BUSY } // took over while the daemon was asked
1085  ask.sid = sid
1086  // The name or the card rides the token, so the agent that runs `pdx lead request --person` cannot drop it.
1087  const token = await personToken($, sid, 'lead', intent.leadName ? ['--lead-name', intent.leadName] : intent.card ? ['--card'] : [])
1088  if (!token) { drop(); return TEAM_NO_TOKEN }
1089  if (s.leadAsk !== ask || s.gen !== ask.gen || s.state !== 'idle') { drop(); return queued ? TEAM_BUSY : LEAD_RELAY_BUSY }
1090  const { note, cut } = leadNote(intent.kind === 'lead' ? intent.note : '')
1091  later($, 0, async () => {
1092    const now = await $.session.id().catch(() => undefined)
1093    // one look, no await between it and the submit: still this ask, this conversation, no relay
1094    if (s.leadAsk !== ask || s.gen !== ask.gen || s.state !== 'idle' || now !== ask.sid) {
1095      drop()
1096      // the same conversation, only a relay in the way: the command is kept for that relay's return to idle; another conversation (a /clear) drops it
1097      if (now === ask.sid) requeueTeam(parsed, rawArgs, ask.sid)
1098      else log($, '/team prompt not submitted: the session moved on')
1099      return
1100    }
1101    try {
1102      await submit($, leadPrompt(note, ask.nonce, token, intent))
1103    } catch (err) {
1104      drop()
1105      log($, '/team prompt not submitted: ' + String(err))
1106      try { $.ui.toast(TEAM_NOT_SENT) } catch {} // the person was told it was asked: now they are told it was not
1107    }
1108  })
1109  const what = intent.leadName ? '已請這個 session 以「' + intent.leadName + '」申請 lead,等待核准'
1110    : intent.card ? '已請這個 session 申請 lead,請在核准卡上選名字'
1111      : '已請這個 session 申請 lead,等待核准'
1112  return what + (cut ? '(補充超過 ' + LEAD_NOTE_MAX_BYTES + ' bytes,已截斷)' : '')
1113}
1114
1115// teamSpawn: `/team spawn <task> [--model m] [--effort e]` (a lead only): the agent writes the brief and runs `pdx spawn --person`.
1116async function teamSpawn($, parsed, rawArgs, sid, queued) {
1117  const token = await personToken($, sid, 'spawn')
1118  if (!token) return TEAM_NO_TOKEN
1119  const { note: task } = leadNote(parsed.task, SPAWN_NOTE_MAX_BYTES)
1120  const given = [parsed.model ? '--model ' + parsed.model : '', parsed.effort ? '--effort ' + parsed.effort : ''].filter(Boolean).join(' ')
1121  const gen = s.gen
1122  later($, 0, async () => {
1123    const now = await $.session.id().catch(() => undefined)
1124    if (s.gen !== gen || s.state !== 'idle' || now !== sid) {
1125      if (now === sid) requeueTeam(parsed, rawArgs, sid) // a relay is in the way: kept for its return to idle
1126      else log($, '/team spawn prompt not submitted: the session moved on')
1127      return
1128    }
1129    try {
1130      await submit($, '使用者用 /team spawn 要求開一個 member:「' + task + '」。請依 pdx-team skill 立刻執行 pdx spawn --person ' + token + ' …,把上面的任務寫成 brief;' +
1131        'model/effort 用 ' + (given || '(沒指定就依任務自己選)') + '。')
1132    } catch (err) {
1133      log($, '/team spawn prompt not submitted: ' + String(err))
1134      try { $.ui.toast(TEAM_NOT_SENT) } catch {}
1135    }
1136  })
1137  return '已請這個 session 開一個 member'
1138}
1139
1140// teamAct: `/team adopt|release|kill <ref>` (a lead only), run by the mod itself.
1141async function teamAct($, parsed, sid) {
1142  let argv
1143  if (parsed.kind === 'adopt') {
1144    const token = await personToken($, sid, 'adopt')
1145    if (!token) return TEAM_NO_TOKEN
1146    argv = ['adopt', parsed.ref, '--person', token]
1147  } else {
1148    argv = [parsed.kind, parsed.ref]
1149  }
1150  if ((await $.session.id().catch(() => undefined)) !== sid) return TEAM_MOVED // release and kill carry no token of ours: the check is the only binding
1151  const r = await pdx($, argv, TEAM_CALL_TIMEOUT_MS)
1152  if (r.exitCode === 20 || r.exitCode === 21) return TEAM_UNREACHABLE
1153  const line = (r.stderr || '').trim().split('\n').filter(Boolean).pop() || ''
1154  if (r.exitCode !== 0) return 'pdx ' + parsed.kind + ' 失敗:' + line
1155  return 'pdx ' + parsed.kind + ' ' + parsed.ref + ' 完成' + ((r.stdout || '').trim() ? ':' + (r.stdout || '').trim().slice(0, 300) : '')
1156}
1157
1158// requeueTeam keeps a /team for the next return to idle of the conversation it was typed in (newest wins).
1159function requeueTeam(parsed, rawArgs, sid) {
1160  if (!s.teamQueued) s.teamQueued = { parsed, rawArgs, sid }
1161}
1162
1163// runQueuedTeam runs the /team that waited for a relay, from a timer at the return to idle; its reply is a toast.
1164function runQueuedTeam($) {
1165  const q = s.teamQueued
1166  if (!q) return
1167  s.teamQueued = undefined
1168  later($, 0, async () => {
1169    // another relay (a reask, a member control, a /relay) may have taken the idle state between the return and this timer: keep the
1170    // command for that relay's own return to idle, unless a newer one has been queued since
1171    // a /clear (another conversation) between the typing and now drops it: it was the person's command for that conversation
1172    const here = await $.session.id().catch(() => undefined)
1173    if (!here || !q.sid || here !== q.sid) {
1174      log($, 'queued /team dropped: the session moved on')
1175      return
1176    }
1177    if (s.state !== 'idle') {
1178      if (!s.teamQueued) s.teamQueued = q
1179      return
1180    }
1181    const text = await performTeam($, q.parsed, q.rawArgs, true, q.sid)
1182    if (text === TEAM_BUSY) {
1183      if (!s.teamQueued) s.teamQueued = q
1184      return
1185    }
1186    try { $.ui.toast(text) } catch {}
1187  })
1188}
1189
1190async function relayNow($) {
1191  if (s.state === 'awaiting' && s.pending) return approveOpenCard($) // a card is open: the person's /relay answers it (RT-1c)
1192  if (s.state !== 'idle') return { text: RELAY_BUSY }
1193  if (!hasCSPRNG()) return { text: 'Purdex 接力無法啟動:這個環境沒有 crypto.getRandomValues' }
1194  // Taken before any await, so a second /relay or a turn's threshold check meanwhile sees
1195  // `beginning`; a preflight that fails gives it back, if it is still this attempt's.
1196  disarmIdle()
1197  s.state = 'beginning'
1198  const gen = s.gen
1199  const begun = deferred() // a prompt that arrives while begin is out waits on it (P5b-3)
1200  s.begun = begun
hooks/ask.js 278 lines
1// Purdex mod — 分流 for AskUserQuestion (lead-team spec §6.6 steps 1–7, U19; facts M24).
2//
3// The engine's own dialog is drawn untouched (`next(e)` issued, not awaited) and raced
4// against the daemon: `pdx ask begin` opens a hook_ask row for the connected clients,
5// `pdx ask wait` long-polls it in bounded rounds (each ≤ 9 min, inside $.process.run's
6// ten-minute cap), and whichever answers first wins. Terminal first ⇒ the native result
7// is returned unchanged and reported as answered_local; remote first ⇒ `{ result }` is
8// returned, which closes the native dialog at once (a reply in words instead of answers
9// returns `{ deny }` the same way); Esc ⇒ dismissed. No responder, a
10// daemon that is down, or any failure ⇒ the native dialog runs alone.
11//
12// This module runs in every interactive Claude Code session on the host, so it fails
13// open everywhere: nothing of ours ever holds the dialog (`next(e)` goes out before the
14// first daemon call), and nothing of ours holds the person's answer for long once they
15// gave it in the terminal (SETTLE_MS below). The hook keeps a call of its own in flight
16// the whole time it waits — the native `next(e)`, a `pdx ask` child or both — so its
17// 10 s budget (HookBudget) stands still however long the dialog stays up.
18
19const WAIT_TIMEOUT_MS = 590_000 // $.process.run is capped at 600 000; `pdx ask wait` returns after ≤ 9 min
20const CALL_TIMEOUT_MS = 40_000 // begin / report: the daemon client's 30 s restart grace plus room
21
22// SETTLE_MS bounds how long the person's terminal answer waits on us. Once the native
23// dialog has settled, the mod still owes the daemon its report (and, when the person
24// answered before `pdx ask begin` replied, begin's answer first). It waits for those at
25// most this long, then returns the native result regardless; whatever is still out goes
26// on by itself and is not awaited. The trade-off: a healthy daemon answers in tens of
27// milliseconds, so the report lands while the dispatch is alive and the answer is delayed
28// by that much only; a daemon that is down or restarting (its client waits 30 s) costs
29// the person SETTLE_MS at most (plus the few milliseconds of `report --detach`), and the
30// report is then handed to a process of its own that lands it after the hook returned
31// (detachReport below) — the engine may end a hook's children once it returns.
32const SETTLE_MS = 3_000
33
34// CHAT_PREFIX heads the person's reply when they answered in words instead of picking
35// (the phone's "chat about this"). The model reads `prefix + blank line + reply` as the
36// tool's error result — the channel the native "Chat about this" ends in.
37const CHAT_PREFIX = 'The user did not pick an answer and replied instead:'
38
39const parse = (s) => { try { return JSON.parse(s) } catch { return null } }
40const isObject = (v) => !!v && typeof v === 'object' && !Array.isArray(v)
41
42// log writes to the debug log only: a session asked a question with no App connected
43// gets no line in its transcript.
44function log($, text) {
45  try {
46    const p = $.ui.log('pdx-ask: ' + text, { to: 'debug' })
47    if (p && typeof p.catch === 'function') p.catch(() => {})
48  } catch {}
49}
50
51// pdxConfig reads pdx.json beside VERSION (P5b-1's extractor writes it; the install flow
52// does not put pdx on PATH): the binary to run and the installing daemon's config, which
53// every call carries as `--config` so a second daemon on this machine is never the one
54// asked (as register.js). Absent — as under `claude plugin test` — it is `pdx` from PATH
55// and pdx's own default config. Read once per tool.call: the binary can move between sessions.
56async function pdxConfig($) {
57  let cfg = null
58  try { cfg = parse(await $.fs.read($.plugin.root + '/pdx.json')) } catch {}
59  return {
60    bin: isObject(cfg) && typeof cfg.pdx === 'string' && cfg.pdx ? cfg.pdx : 'pdx',
61    config: isObject(cfg) && typeof cfg.config === 'string' ? cfg.config : '',
62  }
63}
64
65// ask runs `<pdx> ask <args> [--config <path>]`. The child is started at once (the call
66// is out before this returns), whoever awaits it.
67function ask($, cfg, args, timeoutMs) {
68  return $.process.run([cfg.bin, 'ask', ...args, ...(cfg.config ? ['--config', cfg.config] : [])], { timeoutMs })
69}
70
71// stderrCode reads the API code `pdx ask` prints as the LAST whitespace-separated stderr
72// token (`pdx ask: <detail> <code>`, the same shape as `pdx relay`); for the log line
73// only — every non-zero exit takes the same "native dialog alone" branch.
74function stderrCode(r) {
75  return ((r && r.stderr) || '').trim().split(/\s+/).pop() || ''
76}
77
78// openedId is the row id a begin answered with: exit 0 and `{"id":…}` (a 409 ask_open is
79// adopted by the CLI and reads the same), else '' — no_responders (13), daemon down (20),
80// unsupported (21), usage (2), invalid_response (1), a body without an id, a rejected call.
81function openedId(b) {
82  if (b.who !== 'begin' || b.r.exitCode !== 0) return ''
83  const o = parse(b.r.stdout)
84  return isObject(o) && typeof o.id === 'string' ? o.id : ''
85}
86
87// What the native dialog settled to, read for the report: the answers when the person
88// answered, else a dismissal (Esc, an interrupted turn, an error, a rejected next).
89function nativeOutcome(n) {
90  const r = n.who === 'native' ? n.r : null
91  const answers = r && r.deny === undefined && r.isError !== true && r.result && r.result.answers
92  return isObject(answers) && Object.keys(answers).length > 0
93    ? { state: 'answered_local', hook: { answers } }
94    : { state: 'dismissed' }
95}
96
97// answersFit reports whether a remote answer answers exactly the questions asked: one
98// non-empty string per question text and no other key. A multi-select is the comma-joined
99// labels and free text is any string (M24 P-A: both pass the output schema), so the value
100// is not checked against the options. A remote answer that does not fit must not close the
101// dialog: the person would lose it for an incomplete or wrong answer.
102function answersFit(questions, answers) {
103  if (!Array.isArray(questions) || questions.length === 0 || !isObject(answers)) return false
104  const asked = new Set()
105  for (const q of questions) {
106    if (!isObject(q) || typeof q.question !== 'string' || q.question === '') return false
107    asked.add(q.question)
108  }
109  const keys = Object.keys(answers)
110  if (keys.length !== asked.size) return false
111  return keys.every((k) => asked.has(k) && typeof answers[k] === 'string' && answers[k].trim() !== '')
112}
113
114// report tells the daemon how the terminal settled the row. Never rejects.
115function report($, cfg, id, outcome) {
116  const args = ['report', id, outcome.state]
117  if (outcome.hook) args.push('--hook', JSON.stringify(outcome.hook))
118  return ask($, cfg, args, CALL_TIMEOUT_MS).then((r) => {
119    if (r.exitCode !== 0) log($, 'report ' + outcome.state + ' exit ' + r.exitCode + ' ' + stderrCode(r))
120  }, (err) => log($, 'report ' + outcome.state + ' failed: ' + String(err)))
121}
122
123// DETACH_TIMEOUT_MS bounds the `report --detach` call: it only starts the detached
124// report and exits (milliseconds), so this is a guard, not a wait.
125const DETACH_TIMEOUT_MS = 2_000
126
127// detachReport hands the report to a process of its own (`pdx ask report --detach`,
128// setsid): it lands after this hook has returned, whatever the engine then does with the
129// hook's children. Used when the in-dispatch report has not landed within SETTLE_MS — a
130// report lost after a remote CAS would leave the cards on the remote answer for good
131// (spec §6.6 step 5, terminal_override; P8a-2 R2). Reports are idempotent on the daemon,
132// so the duplicate (should the first land too) is harmless. Never rejects.
133function detachReport($, cfg, id, outcome) {
134  const args = ['report', id, outcome.state]
135  if (outcome.hook) args.push('--hook', JSON.stringify(outcome.hook))
136  args.push('--detach')
137  return ask($, cfg, args, DETACH_TIMEOUT_MS).then((r) => {
138    if (r.exitCode !== 0) log($, 'report --detach exit ' + r.exitCode + ' ' + stderrCode(r))
139  }, (err) => log($, 'report --detach failed: ' + String(err)))
140}
141
142// detachReportByToolUse is detachReport for a row whose id the mod never learned: `pdx ask begin` had not replied when the person
143// answered, so there is no id — but begin may still open the row, and a remote client may answer it before the daemon hears of
144// the terminal's answer (#1848). The detached process reports by (session, tool use) and keeps asking for up to 45 s while the
145// daemon has no row yet (begin's own restart grace is 30 s); `since` is the time taken BEFORE begin was called, so a row of the
146// same tool use from before it is never the one reported. Never rejects.
147function detachReportByToolUse($, cfg, sid, toolUseId, since, outcome) {
148  const args = ['report', outcome.state, '--session', sid, '--tool-use', toolUseId, '--since', String(since)]
149  if (outcome.hook) args.push('--hook', JSON.stringify(outcome.hook))
150  args.push('--detach')
151  return ask($, cfg, args, DETACH_TIMEOUT_MS).then((r) => {
152    if (r.exitCode !== 0) log($, 'report --detach (by tool use) exit ' + r.exitCode + ' ' + stderrCode(r))
153  }, (err) => log($, 'report --detach (by tool use) failed: ' + String(err)))
154}
155
156// reportSettled reports, waits at most SETTLE_MS, and detaches the report when it has
157// not finished by then. Never rejects.
158async function reportSettled($, cfg, next, id, outcome) {
159  let done = false
160  await settle($, next, report($, cfg, id, outcome).then(() => { done = true }))
161  if (!done) await detachReport($, cfg, id, outcome)
162}
163
164// settle waits for `work` (begin's answer, the report) at most SETTLE_MS, and less when
165// the dispatch is abandoned (next.signal: the person interrupted). Never rejects; a sleep
166// the host refuses ends the wait at once.
167async function settle($, next, work) {
168  const cap = Promise.resolve().then(() => $.clock.sleep(SETTLE_MS, { signal: next.signal })).catch(() => {})
169  await Promise.race([work.catch(() => {}), cap])
170}
171
172// native returns the native outcome as the hook's answer: the result object as it came
173// (so core uses its own messages verbatim), or — when next(e) rejected — the same
174// rejection, which the .catch below replays (nothing runs twice).
175function native(n) {
176  if (n.who === 'native') return n.r
177  throw n.err
178}
179
180export function register(on) {
181  on('tool.call', { tool: 'AskUserQuestion' }, async ($, e, next) => {
182    // A subagent's question is not relayed in v1 (coordinator decision): its dialog shows
183    // in the same terminal, but the row would name the wrong conversation.
184    if (e.agentId) return next(e)
185    // Headless (claude -p) has no dialog to race; a worker's questions are Nexen's (spec §6.6).
186    if ((await $.session.surfaces()).length === 0) return next(e)
187
188    const dialog = next(e).then((r) => ({ who: 'native', r }), (err) => ({ who: 'native-error', err }))
189
190    const cfg = await pdxConfig($)
191    const sid = await $.session.id()
192    // Taken before begin is called: a report by tool use (below) only looks at rows created after it. It is compared with the
193    // daemon's wall clock (created_at is time.Now in epoch ms), so it is the real clock, not the engine's: that one is another
194    // clock domain and may be ahead (never a 404 to the end) or behind (no filter at all), as register.js notes.
195    const since = Date.now()
196    const begin = ask($, cfg, ['begin', '--session', String(sid || ''), '--tool-use', String(e.tool_use_id || ''), '--kind', 'hook_ask',
197      '--payload', JSON.stringify({ questions: e.questions })], CALL_TIMEOUT_MS)
198      .then((r) => ({ who: 'begin', r }), (err) => ({ who: 'begin-error', err }))
199
200    const first = await Promise.race([dialog, begin])
201    if (first.who === 'native' || first.who === 'native-error') {
202      // The person answered (or dismissed) before the daemon even replied: the native
203      // outcome stands. A row begin does open is told, within SETTLE_MS or detached.
204      // A begin still out after SETTLE_MS (a daemon busy or restarting) has its row reported
205      // by the tool use, detached (#1848); a row nobody reports is abandoned 30 s after it opens.
206      const outcome = nativeOutcome(first)
207      let opened = '', reported = false, answered = false
208      await settle($, next, begin.then((b) => {
209        answered = true
210        opened = openedId(b)
211        if (!opened) { reported = true; return undefined }
212        return report($, cfg, opened, outcome).then(() => { reported = true })
213      }))
214      if (opened && !reported) await detachReport($, cfg, opened, outcome)
215      // Begin has not replied at all: the row may still open (a daemon busy or restarting, the CLI waits up to 30 s) and a remote
216      // client may answer it first. Without an id the report goes by the tool use (#1848).
217      else if (!answered && sid && e.tool_use_id) await detachReportByToolUse($, cfg, String(sid), String(e.tool_use_id), since, outcome)
218      return native(first)
219    }
220    const id = openedId(first)
221    if (!id) {
222      // no_responders (13), daemon down (20), unsupported (21), anything else: the dialog runs alone.
223      log($, first.who === 'begin' ? 'begin exit ' + first.r.exitCode + ' ' + stderrCode(first.r) + ': native dialog only' : 'begin failed: ' + String(first.err) + ': native dialog only')
224      return native(await dialog)
225    }
226
227    // `stopped` once the race is decided; an abandoned dispatch (next.signal) starts no
228    // further round either, so a hook the engine has given up on never keeps the row alive.
229    let stopped = false
230    const remote = (async () => {
231      while (!stopped && !(next.signal && next.signal.aborted)) {
232        const r = await ask($, cfg, ['wait', id], WAIT_TIMEOUT_MS)
233        if (stopped) break
234        if (r.exitCode !== 0) return { who: 'remote-error', why: 'wait exit ' + r.exitCode + ' ' + stderrCode(r) }
235        const out = parse(r.stdout)
236        if (isObject(out) && out.state === 'still_open') continue // another bounded round; the dialog stays up
237        if (isObject(out) && out.state === 'answered_remote') {
238          const answers = isObject(out.hook) && out.hook.answers
239          if (answersFit(e.questions, answers)) return { who: 'remote', answers }
240          // No answers, but the person replied in words (the daemon never sends both).
241          const message = isObject(out.hook) && out.hook.message
242          if (!answers && typeof message === 'string' && message) return { who: 'remote-chat', message }
243          return { who: 'remote-error', why: 'answered_remote whose answers do not fit the questions' }
244        }
245        if (isObject(out) && out.state === 'closed') return { who: 'remote-closed', why: 'closed ' + out.reason }
246        // A body the mod cannot read ends the race; it never loops on one (no spin).
247        return { who: 'remote-error', why: 'wait answered ' + String(r.stdout).slice(0, 80) }
248      }
249      return { who: 'remote-stopped', why: 'the dispatch was abandoned' }
250    })().catch((err) => ({ who: 'remote-error', why: 'wait failed: ' + String(err) }))
251
252    const w = await Promise.race([dialog, remote])
253    stopped = true // the loop starts no further round
254    if (w.who === 'native' || w.who === 'native-error') {
255      // Step 3 / 6 (and step 5: if a remote decide won the CAS meanwhile, the daemon
256      // records terminal_override — the terminal's answer still stands).
257      await reportSettled($, cfg, next, id, nativeOutcome(w))
258      return native(w)
259    }
260    if (w.who === 'remote') {
261      // Step 4: returning with next(e) pending closes the native dialog (M24 P-B).
262      return { result: { questions: e.questions, answers: w.answers } }
263    }
264    if (w.who === 'remote-chat') {
265      // As for an answer, the daemon holds the outcome: nothing to report. `deny` closes the
266      // native dialog and the model reads the reply as the tool's error result.
267      return { deny: CHAT_PREFIX + '\n\n' + w.message }
268    }
269    // Closed another way (abandoned, dismissed by the backstop, …) or the loop failed:
270    // the dialog runs on alone. A row the daemon still holds open is told how the
271    // terminal settled it, as on step 3.
272    log($, w.why + ': native dialog only')
273    const n = await dialog
274    if (w.who !== 'remote-closed') await reportSettled($, cfg, next, id, nativeOutcome(n))
275    return native(n)
276  }).catch(($, e, next) => next(e)) // any failure of ours: the engine's own dialog, as without the mod (replayed, never run twice)
277}
278
hooks/events.js 1076 lines
1// Purdex mod — the event reporter (interface U1 spec §6.2–§6.5).
2//
3// Every interactive session whose pdx.json names the daemon's `mod_socket` reports what the
4// engine does to the daemon over that Unix socket: one stream per mod load (a random id),
5// events stamped with a strictly increasing seq, queued, and POSTed in batches to
6// `/mod/v1/events` from a $.clock.after timer — never inside a hook — one request at a time,
7// retried with backoff until the daemon acks them. A heartbeat every 10 s carries the live
8// mirror (the running main turn, open asks, compacting, the agents, the last main turn's
9// error outcome, the last background tasks) and every batch says where the session runs
10// and that it is interactive, so a daemon that restarts or a batch that is lost converges
11// within one beat. `session.end` flushes inside its hook. Headless runs (`claude -p`, a
12// Nexen worker) report nothing.
13//
14// The hooks only observe: each calls next(e) and returns what it resolved to; nothing here
15// ever changes what the engine does. Every registration carries `.catch(($, e, next) =>
16// next(e))`: in a `.catch` handler `next` is replay-safe (d.ts CatchHandler / Caught) — a
17// hook that throws after its next(e) settled gets that same settlement back and nothing
18// beneath runs again. Enqueueing never throws.
19//
20// Loading rules this file is shaped by (measured on Claude Code 2.1.293, spec §3):
21// - M-U1-2: `$` is followed only into a function declared at the top level of THIS file,
22//   never across an import. So every helper that takes `$` lives here, every timer callback
23//   is an arrow that only calls one of them (`$.clock.after(150, () => flushTick($))`), and
24//   register.js cannot call into this file with its `$` — which is why the events
25//   register.js owns are observed below by hooks of this file's own, with a matcher.
26// - M-U1-3: an event may be registered without a matcher once per plugin. register.js owns
27//   `session.start`, `turn.start`, `turn.complete`, `classic.SessionStart`, `prompt.submit`
28//   and `session.compact` unmatched; here those carry a matcher (one with and one without
29//   load, the first registered outermost — registerEvents runs before register.js's own, so
30//   these wrap the relay's), and only `tool.call`, `tool.check`, `agent.spawn`,
31//   `session.measure`, `session.end` and `classic.Stop` are unmatched. `ui.render` carries
32//   a matcher too (`component: 'ToolUse'`). A Go test over the embedded files keeps it so
33//   (cmd/pdx/plugin/embed_test.go).
34
35import { CAPS, DEFAULT_TIMEOUT_MS, MAX_JOBS_PER_DRAIN, MODEL_SLACK_MS, NEXT_URL, PROMPT_BACKOFF_MS, PROMPT_IDLE_MS, PROMPT_NEXT_URL, PROMPT_RESULT_BUDGET_MS, PROMPT_RESULT_POST_MS, PROMPT_RESULT_RETRY_MS, PROMPT_RESULT_TRIES, PROMPT_RESULT_URL, PROMPT_WAIT_MS, parsePromptJob, promptNextBody, promptResultBody, fillRefusal, cutUtf8, MAX_TYPED_TEXT_BYTES, REFRESH_URL, RESULT_URL, REQUEST_DEADLINE_MS, WAIT_MS, completeRequest, forkRequest, moreOf, nextBody, parseNext, refreshBody, refreshNotice, refusedBody, resultBody, shouldAsk } from './workbook.js'
36
37const URL = 'http://pdx/mod/v1/events' // the host is not read; the socket is the address
38const FLUSH_MS = 150 // a flush goes out this long after the first event queued
39const BATCH_MAX = 200 // events per POST
40const FINAL_MAX = 500 // the session.end flush sends at most the newest this many (the daemon's cap)
41const QUEUE_MAX = 1000 // queued events; one more drops the oldest
42const POST_DEADLINE_MS = 5000 // a POST not answered by then failed ($.http.fetch has no timeout)
43const BACKOFF_MIN_MS = 1000
44const BACKOFF_MAX_MS = 30_000
45const HEARTBEAT_MS = 10_000
46const STREAM_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-' // 64: one per 6 bits
47const MONITORS_MAX = 64 // monitor ids kept at once; one more drops the oldest
48const ASK_TOOLS = new Set(['AskUserQuestion', 'ExitPlanMode']) // tools that wait on the person by themselves
49const TIMEOUT = Symbol('timeout')
50const TEAM_URL = 'http://pdx/mod/v1/team' // GET ?session_id=<sid> on the same socket (TI-5a)
51const ORPHAN_MAX_MS = 600_000 // how long a fork past its deadline holds the workbook executor at most
52const TEAM_MS = 15_000 // how often the lead's member count is read
53
54// team is the last good answer of the daemon's team read for the CURRENT session id. The ui.render hook below only
55// looks at it (never at the socket); a change asks for a redraw. `gen` counts the session changes: an answer that left
56// before one and lands after it belongs to the old session and is dropped.
57const team = { good: false, role: 'none', members: 0, gen: 0, timer: null, pending: -1 }
58
59// wb is the workbook job executor's state (session workbook spec §5.1): one job at a time. `busy` is the loop that polls the
60// daemon and runs what it hands out; a trigger that comes while it runs only sets `again`. `gen` counts the session ends
61// and switches, so a loop that began before one stops asking. `wait` is the longest poll that is asked for next.
62// `orphan` is a fork that outlived its deadline: $.model.fork takes no signal, so it cannot be cut and keeps spending the
63// whole conversation's tokens. While it runs no further model call is started (one job at a time is a cost promise, not
64// only a state); when it settles the executor asks again.
65const wb = { busy: false, again: false, scheduled: false, gen: 0, wait: 0, orphan: false }
66
67// pq is the Apps' send / interrupt loop (interface U3 plan D7): one standing long poll of `prompt/next` per session id.
68// `loop` is the wb.gen it runs under (0: none), so a session end or switch ends it and the new session starts its own.
69const pq = { loop: 0 }
70
71// ev is the reporter's whole state; one per mod load. `stream` and `seq` live as long as the
72// load (a /clear or a resume goes on in the same stream), the queue holds every event not yet
73// acked, and droppedTotal counts the events this stream lost — never reset (spec §6.2).
74const ev = {
75  on: false,
76  sock: '',
77  stream: '',
78  seq: 0,
79  sid: '',
80  cwd: '', // where the session runs: from session.start, kept across a /clear or a resume
81  ccVersion: '',
82  modVersion: '',
83  queue: [],
84  droppedTotal: 0,
85  inflight: false, // a POST is out
86  scheduled: false, // a flush timer (the 150 ms one, or a backoff) is pending
87  backoffMs: 0,
88  turnId: '', // the running main turn
89  closed: [], // the ids of the last few main turns that ended (see rememberClosed)
90  // tool_use_id → 'permission' | 'question': what waits on the person. A question
91  // (AskUserQuestion / ExitPlanMode) leaves at its tool.end; a permission ask leaves too
92  // when its ToolUse row starts running (tool.approved).
93  asks: new Map(),
94  compacting: false, // the main conversation is compacting
95  lastError: false, // the last main turn ended in error (cleared by the next main turn)
96  background: null, // {tasks, crons} as the last classic.Stop listed them; null before one
97  // id → whether a classic.Stop has listed it yet, for the background tasks the Monitor tool started (its tool.call
98  // result's taskId). Claude Code lists such a task as type "shell" (the "monitor" type is an MCP watch), so the
99  // daemon would draw nothing for it; the background event this reporter sends names those ids "monitor" instead
100  // (spec §7 "Background symbol"). An id leaves when a Stop no longer lists it after having listed it (the task
101  // ended, so a reused id is a different task), at the cap (the oldest), and when the session ends or switches;
102  // rebuilt only by new Monitor calls, so after a mod reload a task that is still running stays "shell" until it
103  // is started again (known limit).
104  monitors: new Map(),
105  beat: null, // the heartbeat timer
106  beatGen: 0, // bumped when the heartbeat stops or pauses: a beat begun before then lands nowhere
107  switching: false, // from session.end{clear|resume} to session.switch: the heartbeat pauses
108}
109
110const parse = (s) => { try { return JSON.parse(s) } catch { return null } }
111const isObject = (v) => !!v && typeof v === 'object' && !Array.isArray(v)
112
113function log($, text) {
114  try {
115    const p = $.ui.log('pdx-events: ' + text, { to: 'debug' })
116    if (p && typeof p.catch === 'function') p.catch(() => {})
117  } catch {}
118}
119
120// newStream mints the stream id: 22 characters of [A-Za-z0-9_-] from Web Crypto
121// (132 bits); '' when the environment has none (the reporter then stays off).
122function newStream() {
123  const c = globalThis.crypto
124  if (!c || typeof c.getRandomValues !== 'function') return ''
125  const b = new Uint8Array(22)
126  c.getRandomValues(b)
127  return Array.from(b, (x) => STREAM_CHARS[x & 63]).join('')
128}
129
130// ---- the queue and the flush ----
131
132// enqueue stamps one event and schedules a flush. Never throws: the reporter's failures stay
133// the reporter's.
134function enqueue($, type, data, sid) {
135  try {
136    if (!ev.on) return
137    ev.queue.push({ seq: ++ev.seq, at: Date.now(), sid: sid || ev.sid, type, data })
138    while (ev.queue.length > QUEUE_MAX) {
139      ev.queue.shift()
140      ev.droppedTotal += 1
141    }
142    schedule($, FLUSH_MS)
143  } catch (err) {
144    log($, 'enqueue ' + type + ' failed: ' + String(err))
145  }
146}
147
148// schedule starts the flush timer unless one is pending, a POST is out (its answer schedules
149// the next) or nothing is queued.
150function schedule($, ms) {
151  if (ev.scheduled || ev.inflight || ev.queue.length === 0) return
152  ev.scheduled = true
153  $.clock.after(ms, () => flushTick($))
154}
155
156function flushTick($) {
157  ev.scheduled = false
158  void flush($).catch((err) => log($, 'flush failed: ' + String(err)))
159}
160
161function body(events) {
162  return JSON.stringify({
163    v: 1,
164    stream: ev.stream,
165    agent: 'cc',
166    cc_version: ev.ccVersion,
167    mod_version: ev.modVersion,
168    dropped_total: ev.droppedTotal,
169    cwd: ev.cwd,
170    interactive: true, // the reporter runs only for interactive sessions
171    caps: CAPS, // what this mod can run besides reporting (the workbook's turn and re-write jobs)
172    events,
173  })
174}
175
176function post($, events) {
177  return $.http.fetch(URL, { method: 'POST', headers: { 'content-type': 'application/json' }, body: body(events), socketPath: ev.sock })
178}
179
180// postWithDeadline races one POST against POST_DEADLINE_MS: { res }, { err }, or TIMEOUT. A
181// POST that misses the deadline is left to itself; its late answer is never read (the events
182// it carried are still queued and go again; the daemon drops what it already applied).
183async function postWithDeadline($, events) {
184  let timer = null
185  const deadline = new Promise((resolve) => { timer = $.clock.after(POST_DEADLINE_MS, () => resolve(TIMEOUT)) })
186  try {
187    return await Promise.race([post($, events).then((res) => ({ res }), (err) => ({ err })), deadline])
188  } finally {
189    if (timer) timer.cancel()
190  }
191}
192
193// hintOf reads the daemon's `workbook: true` on an events answer: a job of this session's conversation waits that nobody
194// holds, so the mod asks `next`.
195function hintOf(res) {
196  const o = parse(res.text)
197  return isObject(o) && o.workbook === true
198}
199
200// ackOf reads the daemon's {"ack": N}; undefined for anything else.
201function ackOf(res) {
202  const o = parse(res.text)
203  return isObject(o) && Number.isFinite(o.ack) ? o.ack : undefined
204}
205
206// dropThrough removes every queued event with seq ≤ n and returns how many it removed.
207function dropThrough(n) {
208  const before = ev.queue.length
209  ev.queue = ev.queue.filter((e) => e.seq > n)
210  return before - ev.queue.length
211}
212
213// apply takes one POST's outcome for the batch it carried: true when the daemon answered for
214// it (200 with an ack, or a refusal of the batch), false for a failure to retry.
215function apply(outcome, batch, $, ask) {
216  const res = outcome && outcome !== TIMEOUT ? outcome.res : undefined
217  if (!res) return false
218  if (res.status === 200) {
219    const ack = ackOf(res)
220    if (ack === undefined) return false
221    dropThrough(ack)
222    if (ask && hintOf(res)) wbAsk($, 0) // a job waits: ask at once (a refresh needs no turn to end)
223    return true
224  }
225  // 400: the daemon refused the batch as written (a bad event, a bad sid…): sending it again
226  // would be refused again (no poison loop), so it is dropped and counted. 413 is the same.
227  if (res.status === 400 || res.status === 413) {
228    ev.droppedTotal += dropThrough(batch[batch.length - 1].seq)
229    return true
230  }
231  return false // 503 registry_full, any other status: retry
232}
233
234// flush sends one batch (one request in flight at a time) and schedules the next: 150 ms
235// later after an answer, after the backoff after a failure.
236async function flush($) {
237  if (ev.inflight || ev.queue.length === 0) return
238  const batch = ev.queue.slice(0, BATCH_MAX)
239  const wbGen = wb.gen
240  ev.inflight = true
241  let outcome
242  try {
243    outcome = await postWithDeadline($, batch)
244  } finally {
245    ev.inflight = false
246  }
247  // A hint that comes back after the session ended or switched is for a session that is gone: it asks nothing.
248  if (apply(outcome, batch, $, wbGen === wb.gen)) {
249    ev.backoffMs = 0
250    schedule($, FLUSH_MS)
251    return
252  }
253  ev.backoffMs = Math.min(Math.max(BACKOFF_MIN_MS, ev.backoffMs * 2), BACKOFF_MAX_MS)
254  schedule($, ev.backoffMs)
255}
256
257// finalFlush is the session.end flush, awaited inside its hook: one POST of every queued
258// event — the newest FINAL_MAX, older ones counted as dropped — whatever is in flight or
259// backing off (an in-flight batch's events are still queued, so its late arrival is all
260// duplicates). No deadline: the session.end bound (1.5 s) cuts it.
261async function finalFlush($) {
262  if (ev.queue.length === 0) return
263  if (ev.queue.length > FINAL_MAX) {
264    const cut = ev.queue.length - FINAL_MAX
265    ev.queue = ev.queue.slice(cut)
266    ev.droppedTotal += cut
267  }
268  const batch = ev.queue.slice()
269  let outcome
270  try {
271    outcome = { res: await post($, batch) }
272  } catch (err) {
273    outcome = { err }
274  }
275  apply(outcome, batch, $, false) // the session is ending: no more asking
276}
277
278// ---- the heartbeat ----
279
280function beatTick($) {
281  void beat($).catch((err) => log($, 'heartbeat failed: ' + String(err)))
282}
283
284// beat reads the agents and queues one heartbeat — unless the heartbeat stopped or paused
285// while it waited on $.agent.list (a session.end, a new session.start): stopping cancels the
286// timer, not a beat already past its start, so that one checks again on its way out. While
287// a /clear or a resume switches the session id, no beat goes out: it would carry the old id.
288async function beat($) {
289  if (!ev.on || ev.switching) return
290  const gen = ev.beatGen
291  let agents // left out when the list fails: [] would clear every dot until the next beat
292  try {
293    agents = (await $.agent.list()).map((a) => ({ id: a.id, status: a.status }))
294  } catch {}
295  if (gen !== ev.beatGen) return
296  const data = { asks: [...ev.asks.keys()], compacting: ev.compacting, error: ev.lastError }
297  if (agents) data.agents = agents
298  if (ev.turnId) data.turn_id = ev.turnId
299  if (ev.background) data.background = ev.background
300  enqueue($, 'heartbeat', data)
301}
302
303function stopBeat() {
304  if (ev.beat) ev.beat.cancel()
305  ev.beat = null
306  ev.beatGen += 1
307}
308
309// ---- the workbook's jobs (session workbook spec §5.1) ----
310
311// wbAsk asks the daemon for a job soon: from a timer, never inside a hook, and one loop at a time — a trigger that comes
312// while the loop runs only marks that it must ask once more when it ends (with the longer wait, if either asked for one).
313function wbAsk($, waitMs) {
314  if (!ev.on) return
315  wb.wait = Math.max(wb.wait, waitMs)
316  if (wb.busy) {
317    wb.again = true
318    return
319  }
320  if (wb.scheduled) return
321  wb.scheduled = true
322  const gen = wb.gen
323  $.clock.after(0, () => wbTick($, gen))
324}
325
326// wbTick: an ask scheduled before a session end or switch is stale and goes nowhere (the next trigger asks afresh).
327function wbTick($, gen) {
328  wb.scheduled = false
329  if (gen !== wb.gen) return
330  void wbLoop($).catch((err) => log($, 'workbook loop failed: ' + String(err)))
331}
332
333// wbRequest posts to the daemon with a deadline of its own ($.http.fetch has none): { res }, { err } or TIMEOUT.
334async function wbRequest($, url, bodyText, waitMs, slackMs = REQUEST_DEADLINE_MS) {
335  let timer = null
336  const deadline = new Promise((resolve) => { timer = $.clock.after(waitMs + slackMs, () => resolve(TIMEOUT)) })
337  try {
338    const req = $.http.fetch(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: bodyText, socketPath: ev.sock })
339    return await Promise.race([req.then((res) => ({ res }), (err) => ({ err })), deadline])
340  } finally {
341    if (timer) timer.cancel()
342  }
343}
344
345// wbLoop asks, runs the job it is handed, reports it, and goes on while the daemon says another one is ready. Any failure
346// ends the loop: a job that could not be reported is dropped (its lease runs out on the daemon, which fails the entry).
347async function wbLoop($) {
348  if (wb.busy || !ev.on || wb.orphan) return
349  wb.busy = true
350  const gen = wb.gen
351  try {
352    // A drain takes at most MAX_JOBS_PER_DRAIN jobs and never the same job id twice: a daemon that keeps answering
353    // "more" (or hands the same lease again) cannot make this mod spend the person's model quota without end. The next
354    // trigger (a turn end, the heartbeat's hint) starts another drain.
355    const seen = new Set()
356    for (let n = 0; n < MAX_JOBS_PER_DRAIN; n++) {
357      if (wb.orphan) break // a fork is still running past its deadline: wait for it to settle (wbOrphaned asks again)
358      const waitMs = wb.wait
359      wb.wait = 0
360      wb.again = false
361      const out = await wbRequest($, NEXT_URL, nextBody(ev.stream, ev.sid, waitMs), waitMs)
362      if (gen !== wb.gen || !ev.on || !out || out === TIMEOUT || !out.res) return
363      const job = parseNext(out.res)
364      if (!job || seen.has(job.id)) break // 204 (nothing yet), an error, or a job already taken in this drain
365      seen.add(job.id)
366      const more = await wbRun($, job, gen)
367      if (more !== true) break
368    }
369  } finally {
370    wb.busy = false
371    if (wb.again && ev.on) { // a trigger came while the loop ran (or the session moved on under it): ask once more
372      wb.again = false
373      wbAsk($, 0)
374    }
375  }
376}
377
378// wbRun runs one job and reports it; true when the daemon said another job is ready. A turn or re-write job is one
379// $.model.complete; a refresh job is one $.model.fork (the conversation itself, a cache read while the main thread's cache is
380// warm); a kind it does not know is answered `refused`. A call the engine refuses rejects: that is reported as `refused` too.
381async function wbRun($, job, gen) {
382  // gen only decides whether to go on asking afterwards (see the end)
383  const jobId = job.id
384  let bodyText
385  const fork = job.kind === 'refresh' ? forkRequest(job.fork) : null
386  const req = job.kind === 'turn' || job.kind === 'rewrite' ? completeRequest(job.complete) : fork ? fork.req : null
387  if (!req) {
388    bodyText = refusedBody(ev.stream, jobId)
389  } else {
390    const t0 = await $.clock.now()
391    // The mod owns a deadline of its own: a call that never settles (or outlives its timeout_ms) must not hold the
392    // executor for good. It is aborted and reported `aborted`; the daemon reads that as a timeout.
393    const ctl = typeof AbortController === 'function' ? new AbortController() : null
394    let cut = null
395    const deadline = new Promise((resolve) => {
396      cut = $.clock.after((fork ? fork.timeoutMs : req.timeoutMs ?? DEFAULT_TIMEOUT_MS) + MODEL_SLACK_MS, () => {
397        if (ctl) ctl.abort()
398        resolve({ isAnswered: false, reason: 'aborted', usage: {} })
399      })
400    })
401    let r = null
402    try {
403      // $.model.fork takes no signal: the deadline above reports a fork that outlives it, the call itself runs on
404      const call = fork ? $.model.fork(req) : ctl ? $.model.complete(req, { signal: ctl.signal }) : $.model.complete(req)
405      let forkDone = false
406      if (fork) call.then(() => { forkDone = true }, () => { forkDone = true })
407      r = await Promise.race([call, deadline])
408      if (fork && !forkDone) wbOrphaned($, call)
409    } catch (err) {
410      log($, 'workbook call refused: ' + String(err))
411    } finally {
412      if (cut) cut.cancel()
413    }
414    bodyText = resultBody(ev.stream, jobId, r, (await $.clock.now()) - t0)
415  }
416  // The result is reported even if the session moved on meanwhile: the lease belongs to this stream, not to a session id.
417  const out = await wbRequest($, RESULT_URL, bodyText, 0)
418  if (!out || out === TIMEOUT || !out.res) return false
419  return gen === wb.gen && moreOf(out.res)
420}
421
422// wbOrphaned: the race was won by the deadline while the fork was still running → hold the executor until it settles. Its
423// late answer is dropped (the daemon has already been told `aborted`).
424// A fork that never settles must not wedge the executor for good: the hold is given up after ORPHAN_MAX_MS (a call to the
425// API ends long before that by itself) and the executor asks again. A mod reload forgets the hold (known limit).
426function wbOrphaned($, call) {
427  let done = false
428  let cap = null
429  const settle = () => {
430    if (done) return
431    done = true
432    if (cap) cap.cancel()
433    if (!wb.orphan) return
434    wb.orphan = false
435    wbAsk($, 0)
436  }
437  wb.orphan = true
438  call.then(settle, settle)
439  cap = $.clock.after(ORPHAN_MAX_MS, settle)
440}
441
442// ---- the Apps' send and interrupt (interface U3 plan D7) ----
443
444// pqStart starts the standing poll for the current session id unless one runs under this generation. Called after the
445// reporter is on and after a session switch; never inside a hook (it starts from a timer).
446function pqStart($) {
447  if (!ev.on || pq.loop === wb.gen) return
448  const gen = wb.gen
449  pq.loop = gen
450  $.clock.after(0, () => {
451    void pqLoop($, gen).catch((err) => log($, 'prompt loop failed: ' + String(err))).finally(() => { if (pq.loop === gen) pq.loop = 0 })
452  })
453}
454
455// pqLoop polls `prompt/next` for the session this process runs now and runs what it is handed, one job at a time. A poll
456// that fails waits PROMPT_BACKOFF_MS; one that returns empty at once (the daemon does not know this stream yet) waits
457// PROMPT_IDLE_MS, so a daemon that answers fast never makes a busy loop.
458async function pqLoop($, gen) {
459  while (gen === wb.gen && ev.on) {
460    const t0 = await $.clock.now()
461    const out = await wbRequest($, PROMPT_NEXT_URL, promptNextBody(ev.stream, ev.sid, PROMPT_WAIT_MS), PROMPT_WAIT_MS)
462    if (gen !== wb.gen || !ev.on) return
463    const failed = !out || out === TIMEOUT || !out.res || (out.res.status !== 200 && out.res.status !== 204)
464    const job = failed ? null : parsePromptJob(out.res)
465    if (job) {
466      await pqRun($, job)
467      continue
468    }
469    if (failed) await $.clock.sleep(PROMPT_BACKOFF_MS)
470    else if ((await $.clock.now()) - t0 < PROMPT_IDLE_MS) await $.clock.sleep(PROMPT_IDLE_MS)
471  }
472}
473
474// pqRun runs one job and reports it. A submit goes only to the session it was made for (a /clear since then makes the id
475// differ: dropped session_changed) and only while no turn runs: $.prompt.submit does not refuse mid-turn, it blocks until
476// the session is idle, so a turn in progress is reported `busy` at once and the App sends again when it is idle. The text goes
477// in as the person's own words (asUser), which is also how the transcript shows it. An interrupt aborts the running main turn.
478async function pqRun($, job) {
479  const t0 = await $.clock.now() // when the job arrived: the result's retries are bounded from here
480  let out
481  try {
482    // A /clear or resume in progress (session.end seen, the switch not yet) still reports the old id: nothing runs then
483    if (ev.switching || job.sessionId !== String(await $.session.id())) out = pqOut('dropped', 'session_changed')
484    else if (job.kind === 'unsupported') out = pqOut('dropped', 'unsupported_kind')
485    else if (job.kind === 'submit') out = await pqSubmit($, job)
486    else if (job.kind === 'fill') out = await pqFill($, job)
487    else if (job.kind === 'clear_if') out = await pqClearIf($, job)
488    else if (job.kind === 'read') out = await pqRead($)
489    else out = await pqInterrupt($)
490  } catch (err) {
491    out = pqOut('dropped', job.kind === 'interrupt' ? 'not_running' : 'refused')
492    log($, 'prompt job ' + job.kind + ' failed: ' + String(err))
493  }
494  // The job has run (or been refused): its report must get through. A lost answer or a busy daemon is tried again, a few
495  // times; a 409 means the daemon has settled it already (expired, or the first try did arrive) and there is nothing to
496  // add. The whole sequence is bounded from the moment the job arrived: no attempt starts after PROMPT_RESULT_BUDGET_MS
497  // (the daemon's lease is 10 s) and each one waits at most PROMPT_RESULT_POST_MS, so the poll loop is held up for a
498  // bounded time even when every POST hangs.
499  // A fill is reported ONCE: a retry only widens the window between the fill and the daemon's Enter, and a late report is
500  // stale anyway (the daemon types Enter only while filled_at is fresh and cleans the composer otherwise).
501  const tries = job.kind === 'fill' ? 1 : PROMPT_RESULT_TRIES
502  let delivered = false
503  let refusedCode = 0
504  for (let attempt = 0; attempt < tries; attempt++) {
505    if (attempt > 0) await $.clock.sleep(PROMPT_RESULT_RETRY_MS * attempt)
506    if ((await $.clock.now()) - t0 >= PROMPT_RESULT_BUDGET_MS) break
507    const res = await wbRequest($, PROMPT_RESULT_URL, promptResultBody(ev.stream, job.id, out.status, out.reason, out.extra), 0, PROMPT_RESULT_POST_MS)
508    const code = res && res !== TIMEOUT && res.res ? res.res.status : 0
509    if (code === 200) delivered = true
510    refusedCode = code
511    if (code === 200 || code === 409) break
512  }
513  if (delivered) return
514  log($, 'prompt result not accepted for ' + job.kind)
515  // A fill the daemon definitely did not take (a received 4xx: not leased, not owner) would leave our text in the composer, and
516  // any text there blocks every later submit: take it back, only if it is still exactly ours. A timeout, a network error or
517  // a 5xx is ambiguous: the daemon may have the result and be about to press Enter, so clearing now would turn that into an
518  // empty Enter and lose the message; the text stays and the daemon's own clean-up (which only clears our exact text) decides.
519  if (job.kind === 'fill' && out.status === 'accepted' && refusedCode >= 400 && refusedCode < 500) {
520    const c = await clearIfOurs($, job.text)
521    log($, 'fill report lost; composer clean-up: ' + c)
522  }
523}
524
525// The outcome of one job: the status for the daemon, a reason, and extras (filledAt of a fill, text / truncated of a read).
526const pqOut = (status, reason = '', extra = null) => ({ status, reason, extra })
527
528// clearIfOurs empties the composer only if it holds exactly `own`: 'cleared', 'gone' (it holds something else or nothing:
529// nothing of ours to take back) or 'failed' (could not read or could not clear: we do not know what is there).
530async function clearIfOurs($, own) {
531  try {
532    const cur = await $.prompt.read()
533    if (!isObject(cur) || typeof cur.text !== 'string') return 'failed'
534    if (cur.text !== own) return 'gone'
535    await $.prompt.fill({ text: '', mode: 'replace' })
536    return 'cleared'
537  } catch (err) {
538    log($, 'composer clean-up failed: ' + String(err))
539    return 'failed'
540  }
541}
542
543// A submit goes only while no turn runs: $.prompt.submit does not refuse mid-turn, it blocks until the session is idle, so a
544// turn in progress is reported `busy` at once and the App sends again when it is idle. The text goes in as the person's own
545// words (asUser), which is also how the transcript shows it.
546async function pqSubmit($, job) {
547  if (ev.turnId) return pqOut('busy')
548  const r = await $.prompt.submit({ text: job.text, asUser: true })
549  if (isObject(r) && typeof r.drop === 'string') return pqOut('dropped', r.drop || 'dropped')
550  return pqOut('accepted')
551}
552
553// Typed submit (K-1): the text goes into the empty composer WITHOUT Enter; the daemon presses Enter. Allowed mid-turn
554// (fill/read return at once, unlike submit). Never mixes with a draft someone is typing in the terminal. Whatever goes
555// wrong after the fill started, our text is taken back if it is there; if we cannot tell, the report is `unknown`, never
556// `dropped` (a dropped fill promises that nothing was left in the composer).
557async function pqFill($, job) {
558  const cur = await $.prompt.read()
559  if (!isObject(cur) || typeof cur.text !== 'string') return pqOut('dropped', 'no_composer') // fail closed: we cannot see the composer
560  if (cur.text !== '') return pqOut('dropped', 'input_not_empty')
561  try {
562    const f = await $.prompt.fill({ text: job.text, mode: 'replace' })
563    const why = fillRefusal(f)
564    if (why) return pqOut('dropped', why)
565    if (f.text !== job.text) return pqCleaned(await clearIfOurs($, f.text), 'fill_mismatch')
566    return pqOut('accepted', '', { filledAt: await $.clock.now() }) // right after the fill: the daemon presses Enter only while it is fresh
567  } catch (err) {
568    log($, 'prompt job fill failed: ' + String(err))
569    return pqCleaned(await clearIfOurs($, job.text), 'fill_error')
570  }
571}
572
573// pqCleaned: the report of a fill that did not stay, given what the clean-up found.
574const pqCleaned = (cleanup, reason) => (cleanup === 'failed' ? pqOut('unknown', reason) : pqOut('dropped', reason))
575
576// Cleanup of a fill that was not sent: only our own text is cleared, never someone else's draft.
577async function pqClearIf($, job) {
578  const cur = await $.prompt.read()
579  if (!isObject(cur) || cur.text !== job.text) return pqOut('dropped', 'not_ours')
580  await $.prompt.fill({ text: '', mode: 'replace' })
581  return pqOut('accepted')
582}
583
584// A read of the composer; a text over the daemon's limit is cut on a character boundary and flagged, not refused.
585async function pqRead($) {
586  const cur = await $.prompt.read()
587  if (!isObject(cur) || typeof cur.text !== 'string') return pqOut('dropped', 'no_composer')
588  const text = cutUtf8(cur.text, MAX_TYPED_TEXT_BYTES)
589  return pqOut('accepted', '', text.length === cur.text.length ? { text } : { text, truncated: true })
590}
591
592// An interrupt aborts the running main turn.
593async function pqInterrupt($) {
594  if (!ev.turnId) return pqOut('dropped', 'not_running')
595  const turnId = ev.turnId
596  await $.turn.abort({ turnId })
597  turnAborted($, turnId)
598  return pqOut('accepted')
599}
600
601// ---- /workbook refresh (session workbook spec §5.6) ----
602
603const WORKBOOK_USAGE = '用法:/workbook refresh — 依整段對話重整這個 session 的工作簿(目前狀況與待辦)。'
604
605// workbookCommand answers `/workbook refresh`: it asks the daemon to queue the refresh and, once queued, asks `next` at
606// once (from a timer: wbAsk never runs the loop inside the hook). The person waits for the line, so the one daemon call is
607// awaited here, bounded by wbRequest's deadline.
608async function workbookCommand($, e) {
609  if (String(e.args ?? '').trim() !== 'refresh') return { text: WORKBOOK_USAGE }
610  if (!ev.on) return { text: '工作簿重整:這個 session 沒有連上 daemon。' }
611  if (wb.orphan) return { text: '工作簿重整:上一次重整的模型呼叫還在背景執行,請等它結束再試。' }
612  const out = await wbRequest($, REFRESH_URL, refreshBody(ev.stream, ev.sid), 0)
613  const notice = refreshNotice(out && out !== TIMEOUT ? out.res : null)
614  if (notice.queued) wbAsk($, 0)
615  return { text: notice.text }
616}
617
618// ---- the lead's footer (TI-5b, spec §4.10) ----
619
620// teamLabel is the footer mode for a lead, '' for any other role and before the first good read.
621function teamLabel() {
622  if (!team.good || team.role !== 'lead') return ''
623  return 'lead mode · ' + team.members + (team.members === 1 ? ' member' : ' members')
624}
625
626// teamAnswer reads the daemon's {"role","members","team_label"}; null for anything else.
627function teamAnswer(res) {
628  if (!res || res.status !== 200) return null
629  const o = parse(res.text)
630  if (!isObject(o) || !['lead', 'member', 'none'].includes(o.role)) return null
631  if (!Number.isInteger(o.members) || o.members < 0) return null
632  return { role: o.role, members: o.members }
633}
634
635// readTeam asks the daemon about the current session and keeps the answer. A failed or late read changes nothing (the last
636// good value stands); an answer for a session that is gone is dropped. Only a change of the label asks for a redraw.
637async function readTeam($) {
638  if (!ev.on) return
639  const gen = team.gen
640  // One read per session at a time: $.http.fetch cannot be cancelled, so a daemon that takes a request and never answers
641  // must not collect one more every tick. A switch is a new generation and may read again.
642  if (team.pending === gen) return
643  team.pending = gen
644  const url = TEAM_URL + '?session_id=' + encodeURIComponent(ev.sid)
645  let timer = null
646  const deadline = new Promise((resolve) => { timer = $.clock.after(POST_DEADLINE_MS, () => resolve(TIMEOUT)) })
647  const request = $.http.fetch(url, { method: 'GET', socketPath: ev.sock }).then((res) => ({ res }), (err) => ({ err }))
648  // the slot is freed when the request itself ends, not at the deadline
649  void request.finally(() => { if (team.pending === gen) team.pending = -1 })
650  let out
651  try {
652    out = await Promise.race([request, deadline])
653  } finally {
654    if (timer) timer.cancel()
655  }
656  if (gen !== team.gen || !out || out === TIMEOUT) return
657  const a = teamAnswer(out.res)
658  if (!a) return
659  const before = teamLabel()
660  team.good = true
661  team.role = a.role
662  team.members = a.members
663  if (teamLabel() !== before) $.ui.invalidate('ui.render')
664}
665
666function teamTick($) {
667  void readTeam($).catch((err) => log($, 'team read failed: ' + String(err)))
668}
669
670// forgetTeam drops what was read for the session that is gone; the label goes with it.
671function forgetTeam($) {
672  team.gen += 1
673  const had = teamLabel() !== ''
674  team.good = false
675  team.role = 'none'
676  team.members = 0
677  if (had) $.ui.invalidate('ui.render')
678}
679
680function stopTeam() {
681  if (team.timer) team.timer.cancel()
682  team.timer = null
683  team.gen += 1
684}
685
686// startTeam reads at once and then every TEAM_MS, with the id the session has by then.
687function startTeam($) {
688  stopTeam()
689  teamTick($)
690  team.timer = $.clock.every(TEAM_MS, () => teamTick($))
691}
692
693// ---- the session ----
694
695// startReporter turns the reporter on for an interactive session whose pdx.json names the
696// daemon's socket (U1-1a's extractor writes `mod_socket`; an older install has none, and
697// the reporter stays off). The stream and its seq outlive a second session.start in the
698// same load.
699async function startReporter($, e) {
700  stopBeat()
701  stopTeam()
702  wb.gen += 1
703  ev.on = false
704  ev.switching = false
705  const cfg = parse(await $.fs.read($.plugin.root + '/pdx.json').catch(() => ''))
706  const sock = isObject(cfg) && typeof cfg.mod_socket === 'string' ? cfg.mod_socket : ''
707  if (!sock) return
708  if (!ev.stream) ev.stream = newStream()
709  if (!ev.stream) {
710    log($, 'reporter off: this environment has no crypto.getRandomValues for the stream id')
711    return
712  }
713  ev.sock = sock
714  ev.modVersion = String(await $.fs.read($.plugin.root + '/VERSION').catch(() => '')).trim()
715  const v = await $.session.version().catch(() => undefined)
716  ev.ccVersion = isObject(v) && typeof v.version === 'string' ? v.version : ''
717  ev.sid = String(await $.session.id())
718  ev.cwd = String(e.cwd ?? '')
719  ev.turnId = ''
720  ev.asks.clear()
721  ev.compacting = false
722  ev.lastError = false
723  ev.background = null
724  ev.monitors.clear()
725  ev.on = true
726  pqStart($)
727  await $.command.register({ name: 'workbook', description: 'Purdex 工作簿:refresh 依整段對話重整目前狀況與待辦', argumentHint: 'refresh' })
728    .catch((err) => log($, '/workbook not registered: ' + String(err)))
729  enqueue($, 'session.start', { cwd: e.cwd, surface: e.surface })
730  ev.beat = $.clock.every(HEARTBEAT_MS, () => beatTick($))
731  forgetTeam($) // a second session.start in this load: nothing read for an earlier session stays
732  startTeam($)
733}
734
735// sessionSwitch follows a /clear or a resume: the process goes on under a new session id,
736// in the same stream, its seq and heartbeat going on; the old conversation's mirror is gone.
737// The cwd and the background tasks stay (same process: the tasks run on; the next
738// classic.Stop refreshes them). It ends the pause session.end began, whatever happens here.
739async function sessionSwitch($, source) {
740  if (!ev.on) return
741  try {
742    const prev = ev.sid
743    ev.sid = String(await $.session.id())
744    wb.gen += 1 // a poll made under the old session id stops asking
745    ev.turnId = ''
746    ev.asks.clear()
747    ev.compacting = false
748    ev.lastError = false
749    ev.monitors.clear()
750    enqueue($, 'session.switch', { prev_sid: prev, source })
751    forgetTeam($) // the lead of the old conversation says nothing about the new one
752    teamTick($)
753    pqStart($) // the poll under the old session id ended with the generation: the new session polls for itself
754  } finally {
755    ev.switching = false
756  }
757}
758
759// sessionEnd queues session.end under the ending session's own id and flushes inside the
760// hook. `session.end` also fires on /clear and /resume (reason clear / resume), after which
761// the same process and stream go on: the heartbeat stops only on the other reasons, before
762// the final flush, so nothing of it (not even a beat in flight) lands after session.end. On
763// clear / resume it pauses until session.switch (M-U1-4: about 660 ms later), so no beat
764// goes out under the old id meanwhile, the one in flight included.
765async function sessionEnd($, e) {
766  if (!ev.on) return
767  ev.monitors.clear()
768  if (e.reason === 'clear' || e.reason === 'resume') {
769    ev.switching = true
770    ev.beatGen += 1
771  } else {
772    stopBeat()
773    stopTeam()
774    wb.gen += 1
775  }
776  enqueue($, 'session.end', { reason: e.reason }, e.sessionId)
777  await finalFlush($)
778}
779
780// ---- what each hook reports ----
781
782function withAgent(data, agentId) {
783  if (agentId) data.agent_id = agentId
784  return data
785}
786
787// rememberClosed keeps the ids of the last few main turns that ended: positive evidence that a turn.complete naming one of
788// them, arriving after the next turn began, is late and must not end the running one.
789function rememberClosed(turnId) {
790  if (!turnId || ev.closed.includes(turnId)) return
791  ev.closed.push(turnId)
792  if (ev.closed.length > 8) ev.closed.shift()
793}
794
795function turnStarted($, e) {
796  if (!ev.on) return
797  ev.turnId = e.turnId // turn.start has no agentId: it is always the main conversation's
798  ev.lastError = false
799  enqueue($, 'turn.start', { turn_id: e.turnId })
800}
801
802function turnCompleted($, e) {
803  if (!ev.on) return
804  // A completion that names an earlier turn (the engine's own, arriving after the mod closed that turn itself and a new
805  // one began) does not end the one now running.
806  const late = !e.agentId && !!ev.turnId && !!e.turnId && e.turnId !== ev.turnId && ev.closed.includes(e.turnId)
807  if (!e.agentId && !late) {
808    rememberClosed(e.turnId)
809    ev.turnId = ''
810    ev.asks.clear()
811    ev.lastError = e.reason === 'error'
812  }
813  if (shouldAsk(e)) wbAsk($, WAIT_MS) // the daemon's job for this turn appears after its Stop hook and the catch-up
814  enqueue($, 'turn.complete', { ...withAgent({ turn_id: e.turnId, reason: e.reason }, e.agentId), duration_ms: e.durationMs, aborted: !!e.isAborted })
815}
816
817// turnAborted closes the main turn this mod just cancelled with $.turn.abort. Claude Code ends such a turn without a
818// turn.complete for the main conversation and without a Stop hook (measured, CC 2.1.294: after the abort the light and the
819// heartbeat's turn_id stayed 'running' for good), so the mod says so itself: the state a real turn.complete clears, and a
820// turn.complete{reason:'aborted', aborted:true} for the daemon (the light goes idle; the conversation ends its running
821// turn as interrupted, since the abort leaves no marker in the transcript). Only when the turn it cancelled is still the one
822// running: a turn.complete that did arrive, or a new turn, has already moved on.
823function turnAborted($, turnId) {
824  if (!ev.on || !turnId || ev.turnId !== turnId) return
825  rememberClosed(turnId)
826  ev.turnId = ''
827  ev.asks.clear()
828  enqueue($, 'turn.complete', { turn_id: turnId, reason: 'aborted', duration_ms: 0, aborted: true })
829}
830
831function toolStarted($, e) {
832  if (ASK_TOOLS.has(e.tool) && e.tool_use_id) ev.asks.set(e.tool_use_id, 'question')
833  enqueue($, 'tool.start', withAgent({ tool: e.tool, tool_use_id: e.tool_use_id }, e.agentId))
834}
835
836function toolEnded($, e, ms, error) {
837  if (e.tool_use_id) ev.asks.delete(e.tool_use_id)
838  enqueue($, 'tool.end', withAgent({ tool_use_id: e.tool_use_id, ms, error }, e.agentId))
839}
840
841// toolUseDrawn reports the approval of a permission ask: the ToolUse row's isRunning is false
842// while the permission dialog is open and turns true about 16 ms after the person approves
843// (M-U1-6, Claude Code 2.1.294). It runs on every redraw of every tool row, so it only looks
844// the id up; the ask leaves the mirror at once, so a later redraw reports nothing. A question
845// is never approved here: it waits until its tool.end.
846function toolUseDrawn($, e) {
847  if (!ev.on) return
848  const p = e.props
849  if (!p || p.isRunning !== true || ev.asks.get(p.tool_use_id) !== 'permission') return
850  ev.asks.delete(p.tool_use_id)
851  enqueue($, 'tool.approved', { tool_use_id: p.tool_use_id })
852}
853
854// monitorStarted remembers the task id of a Monitor call (measured on Claude Code 2.1.295: the hook's result is
855// {ref, result: {taskId, timeoutMs, persistent}, text}, and taskId is the id classic.Stop lists in background_tasks).
856function monitorStarted(e, r) {
857  if (e.tool !== 'Monitor' || !isObject(r) || isErrorResult(r)) return
858  // the nested result first, then a top-level taskId, then the strictly anchored text of the success message
859  let id = isObject(r.result) ? r.result.taskId : undefined
860  if (typeof id !== 'string' || !id) id = r.taskId
861  if (typeof id !== 'string' || !id) {
862    const m = typeof r.text === 'string' ? /^Monitor started \(task ([A-Za-z0-9_-]+)[,)]/.exec(r.text) : null
863    id = m ? m[1] : undefined
864  }
865  if (typeof id !== 'string' || !id) return
866  ev.monitors.delete(id) // a reused id is the newest again (Map keeps insertion order)
867  ev.monitors.set(id, false)
868  while (ev.monitors.size > MONITORS_MAX) ev.monitors.delete(ev.monitors.keys().next().value)
869}
870
871function isErrorResult(r) {
872  return !!r && (r.isError === true || r.deny !== undefined)
873}
874
875function toolChecked($, e, r) {
876  if (!ev.on) return
877  const decision = isObject(r) ? r.decision : undefined
878  if (decision === 'ask' && e.tool_use_id) ev.asks.set(e.tool_use_id, ASK_TOOLS.has(e.tool) ? 'question' : 'permission')
879  const data = { tool: e.tool }
880  if (e.tool_use_id) data.tool_use_id = e.tool_use_id
881  enqueue($, 'tool.check', { ...withAgent(data, e.agentId), decision })
882}
883
884function agentSpawned($, e, r) {
885  if (!ev.on || !isObject(r) || typeof r.agentId !== 'string') return // refused, or answered without starting one
886  const data = { agent_id: r.agentId, tool_use_id: e.tool_use_id, background: !!e.background, subagent_type: e.subagentType }
887  if (isObject(e.workflow) && e.workflow.runId) data.workflow_run_id = e.workflow.runId
888  enqueue($, 'agent.spawn', data)
889}
890
891function measured($, e) {
892  if (!ev.on) return
893  const c = isObject(e.context) ? e.context : {}
894  const context = { window: c.window }
895  if (c.tokens !== undefined) context.tokens = c.tokens
896  if (c.percent !== undefined) context.percent = c.percent
897  const data = {
898    context,
899    rate_limits: (Array.isArray(e.rateLimits) ? e.rateLimits : []).map((l) => {
900      const o = { kind: l.kind, percent_used: l.percentUsed }
901      if (l.resetsAt !== undefined) o.resets_at = l.resetsAt
902      return o
903    }),
904  }
905  if (isObject(e.cost) && Number.isFinite(e.cost.usd)) data.cost_usd = e.cost.usd
906  data.changed = Array.isArray(e.changed) ? [...e.changed] : []
907  enqueue($, 'usage', data)
908}
909
910// backgroundBusy: the last classic.Stop listed a background task that is still running, or a session cron (a /clear would
911// orphan them; idle relay D8). null (no Stop seen yet) is not busy. It reads what stopped() keeps whether or not the
912// reporter is on.
913export function backgroundBusy() {
914  const b = ev.background
915  return !!b && (b.crons > 0 || b.tasks.some((t) => t.status === 'running'))
916}
917
918function stopped($, e) {
919  // a copy: the engine's objects are never touched. A task the Monitor tool started is named "monitor".
920  const listed = Array.isArray(e.background_tasks) ? e.background_tasks : []
921  const tasks = listed.map((t) => ({ id: t.id, type: ev.monitors.has(t.id) ? 'monitor' : t.type, status: t.status }))
922  // a monitor this Stop lists is now known to the engine; one it listed before and no longer lists has ended
923  const present = new Set(listed.map((t) => t.id))
924  for (const [id, seen] of [...ev.monitors]) {
925    if (present.has(id)) ev.monitors.set(id, true)
926    else if (seen) ev.monitors.delete(id)
927  }
928  ev.background = { tasks, crons: Array.isArray(e.session_crons) ? e.session_crons.length : 0 }
929  if (ev.on) enqueue($, 'background', ev.background)
930}
931
932function compactStarted($, e) {
933  if (!ev.on) return
934  if (!e.agentId && e.trigger !== 'precompute') ev.compacting = true
935  enqueue($, 'compact.start', withAgent({ trigger: e.trigger }, e.agentId))
936}
937
938function compactEnded($, e, ok) {
939  if (!ev.on) return
940  if (!e.agentId && e.trigger !== 'precompute') ev.compacting = false
941  enqueue($, 'compact.end', { ...withAgent({ trigger: e.trigger }, e.agentId), ok })
942}
943
944// ---- the hooks ----
945
946async function onSessionStart($, e, next) {
947  const r = await next(e)
948  ev.background = null // a session's own: forgotten even when the reporter is off (idle relay D8 reads it)
949  await startReporter($, e)
950  return r
951}
952
953async function onTurnStart($, e, next) {
954  turnStarted($, e)
955  return next(e)
956}
957
958async function onTurnComplete($, e, next) {
959  const r = await next(e)
960  turnCompleted($, e)
961  return r
962}
963
964// onSessionSwitch reports the switch once the hooks beneath (the relay's /clear work) are
965// done with the event — and when one of them failed too: the session id changed whatever
966// they did, and the heartbeat stays paused until the switch is reported.
967async function onSessionSwitch($, e, next) {
968  try {
969    return await next(e) // the engine has moved to the new session id
970  } finally {
971    await sessionSwitch($, e.source)
972  }
973}
974
975// onCompact wraps the relay's compact hook (registered before it, so outside): ok is false
976// exactly when the compaction did not happen (a hook beneath answered {skip}).
977async function onCompact($, e, next) {
978  if (!ev.on) return next(e)
979  compactStarted($, e)
980  let ok = false
981  try {
982    const r = await next(e)
983    ok = !(isObject(r) && r.skip !== undefined)
984    return r
985  } finally {
986    compactEnded($, e, ok)
987  }
988}
989
990// onToolCall reports tool.start before next(e) and tool.end after it, timed on the engine's
991// clock. When an outer hook answers with next still pending (ask.js's remote answer) what
992// runs beneath is abandoned; once next(e) here rejects, tool.end {error: true} and the
993// rejection goes on (the .catch replays it; the outer hook's answer stands). Should it never
994// settle, the main turn.complete still clears the open ask from the mirror.
995async function onToolCall($, e, next) {
996  if (!ev.on) return next(e)
997  const t0 = await $.clock.now()
998  toolStarted($, e)
999  let r
1000  try {
1001    r = await next(e)
1002  } catch (err) {
1003    toolEnded($, e, (await $.clock.now()) - t0, true)
1004    throw err
1005  }
1006  toolEnded($, e, (await $.clock.now()) - t0, isErrorResult(r))
1007  monitorStarted(e, r)
1008  return r
1009}
1010
1011// onToolUseRender only observes: the drawing is whatever beneath answers, unchanged.
1012async function onToolUseRender($, e, next) {
1013  toolUseDrawn($, e)
1014  return next(e)
1015}
1016
1017// onSessionModeRender adds the lead's label to the footer's modes while the last good read says this session leads a
1018// team; for anything else the footer is the engine's, unchanged. It reads the cache only, never the socket.
1019async function onSessionModeRender($, e, next) {
1020  const label = ev.on ? teamLabel() : ''
1021  if (!label) return next(e)
1022  return next({ ...e, props: { ...e.props, modes: [...e.props.modes, label] } })
1023}
1024
1025async function onToolCheck($, e, next) {
1026  const r = await next(e)
1027  toolChecked($, e, r)
1028  return r
1029}
1030
1031async function onAgentSpawn($, e, next) {
1032  const r = await next(e)
1033  agentSpawned($, e, r)
1034  return r
1035}
1036
1037async function onMeasure($, e, next) {
1038  const r = await next(e)
1039  measured($, e)
1040  return r
1041}
1042
1043async function onStop($, e, next) {
1044  const r = await next(e)
1045  stopped($, e)
1046  return r
1047}
1048
1049async function onSessionEnd($, e, next) {
1050  const r = await next(e)
1051  await sessionEnd($, e)
1052  return r
1053}
1054
1055// registerEvents is called once by register.js, before register.js's own hooks, so the
1056// matched hooks below are outermost on the events register.js owns. The matchers admit
1057// every event the reporter wants: any turn (every turn has an id), any compaction trigger,
1058// an interactive session start, a SessionStart that switched the session id, and a tool
1059// row's drawing.
1060export function registerEvents(on) {
1061  on('session.start', { isInteractive: true }, onSessionStart).catch(($, e, next) => next(e))
1062  on('turn.start', { turnId: /^/ }, onTurnStart).catch(($, e, next) => next(e))
1063  on('turn.complete', { turnId: /^/ }, onTurnComplete).catch(($, e, next) => next(e))
1064  on('classic.SessionStart', { source: ['clear', 'resume'] }, onSessionSwitch).catch(($, e, next) => next(e))
1065  on('session.compact', { trigger: /^/ }, onCompact).catch(($, e, next) => next(e))
1066  on('tool.call', onToolCall).catch(($, e, next) => next(e))
1067  on('tool.check', onToolCheck).catch(($, e, next) => next(e))
1068  on('agent.spawn', onAgentSpawn).catch(($, e, next) => next(e))
1069  on('session.measure', onMeasure).catch(($, e, next) => next(e))
1070  on('session.end', onSessionEnd).catch(($, e, next) => next(e))
1071  on('classic.Stop', onStop).catch(($, e, next) => next(e))
1072  on('ui.render', { component: 'ToolUse' }, onToolUseRender).catch(($, e, next) => next(e))
1073  on('ui.render', { component: 'SessionMode' }, onSessionModeRender).catch(($, e, next) => next(e))
1074  on('command.run', { command: 'workbook' }, workbookCommand)
1075}
1076
hooks/gate.js 405 lines
1// Purdex mod — the wwd entry of a Bash call (spec §8.2; host-load-control spec §6 before WWD-9).
2//
3// With the wwd entry switched on (the "entry" key of pdx.json, off by default) a test or build command is first shown to
4// `pdx entry match`, which knows the repo's task manifest: a command that is a declared task is run as `pdx test <task> …` (in the
5// background when the task goes through the queue), one that no task declares becomes `pdx test --adhoc` or is advised or refused as
6// the manifest's [entry].mode says. With the switch off the hook does nothing to the call.
7//
8// The old gate's half is gone (WWD-9 9a-2): the gate holds nothing now, so a tool binary called by path gets no `pdx gate --auto --`
9// in front and no call is moved to the background because the gate would make it wait.
10//
11// Everything fails open: a pdx that does not answer, an answer that is not JSON, a throw while planning — the call runs as
12// it was. The planning is finished before `next` is called, and nothing after `next` can run the tool twice.
13//
14// `$` is used only in the top-level functions below (M-U1-2); the handler hands it straight on.
15
16// ---- tokenizing ----
17
18// a redirection word ends in an operator (its target is the next word)
19const BARE = /[<>&]$/
20
21// scan splits a command into segments of words. A word records the text between its quotes and where it
22// sits in the original string. Returns null when the command cannot be parsed (an open quote) or has a
23// backgrounding `&`. With `continuation`, a backslash and a newline are removed as the shell removes them before it splits words
24// (the entry reads commands that way; the older steps read them as they always did).
25function scan(cmd, continuation) {
26  const segments = []
27  let words = []
28  let cur = null // {text, start, end, redirect}
29  let quote = ''
30  let background = false
31  const heredocs = [] // {delim, strip, quoted} awaiting the next newline
32  const masks = [] // [from, to) of text that is data (a quoted heredoc's body, a comment): substitutions() must not read it
33
34  const endWord = (i) => {
35    if (cur) {
36      cur.end = i
37      words.push(cur)
38      cur = null
39    }
40  }
41  const endSegment = (i) => {
42    endWord(i)
43    if (words.length) segments.push(words)
44    words = []
45  }
46  const push = (ch, i) => {
47    if (!cur) cur = { text: '', start: i, end: i, quoted: false, redirect: false }
48    cur.text += ch
49  }
50
51  for (let i = 0; i < cmd.length; i++) {
52    const c = cmd[i]
53    if (quote === "'") {
54      if (c === "'") quote = ''
55      else push(c, i)
56      continue
57    }
58    if (quote === '"') {
59      if (c === '"') quote = ''
60      else if (continuation && c === '\\' && cmd[i + 1] === '\n') i++
61      else if (c === '\\' && i + 1 < cmd.length) { push(cmd[++i], i) }
62      else push(c, i)
63      continue
64    }
65    if (c === "'" || c === '"') {
66      quote = c
67      if (!cur) cur = { text: '', start: i, end: i, quoted: false, redirect: false }
68      cur.quoted = true
69      continue
70    }
71    if (continuation && c === '\\' && cmd[i + 1] === '\n') { i++; continue }
72    if (c === '\\' && i + 1 < cmd.length) { push(cmd[++i], i); continue }
73    if (c === ' ' || c === '\t') { endWord(i); continue }
74    if (c === '\n') {
75      endSegment(i)
76      for (const h of heredocs.splice(0)) {
77        const from = i + 1
78        // the body: lines up to one that is the delimiter; none of it is a command
79        for (;;) {
80          const nl = cmd.indexOf('\n', i + 1)
81          const line = cmd.slice(i + 1, nl < 0 ? cmd.length : nl)
82          i = nl < 0 ? cmd.length : nl
83          if ((h.strip ? line.replace(/^\t+/, '') : line) === h.delim || nl < 0) break
84        }
85        if (h.quoted) masks.push([from, i])
86      }
87      continue
88    }
89    if (c === ';') { endSegment(i); continue }
90    if (c === '#' && !cur) {
91      const from = i
92      while (i + 1 < cmd.length && cmd[i + 1] !== '\n') i++
93      masks.push([from, i + 1])
94      continue
95    }
96    if (c === '>' || c === '<') {
97      // an unquoted redirection ends the word before it (`run>out`), but keeps a file descriptor
98      // (`2>`) and the operator it is building (`>>`, `<<`)
99      if (cur && !(cur.redirect && /[<>]$/.test(cur.text)) && !/^(\d+|&)$/.test(cur.text)) endWord(i)
100      if (c === '<' && cmd[i + 1] === '<' && cmd[i - 1] !== '<' && cmd[i + 2] !== '<') {
101        let j = i + 2
102        const strip = cmd[j] === '-'
103        if (strip) j++
104        while (cmd[j] === ' ' || cmd[j] === '\t') j++
105        let delim = ''
106        let quoted = false
107        // a shell word: quotes group (and keep their spaces), a backslash escapes, the rest ends at a separator
108        for (let q = ''; j < cmd.length; j++) {
109          const d = cmd[j]
110          if (q) { if (d === q) q = ''; else delim += d; continue }
111          if (d === "'" || d === '"') { q = d; quoted = true; continue }
112          if (d === '\\' && j + 1 < cmd.length) { delim += cmd[++j]; quoted = true; continue }
113          if (' \t\n;|&()<>'.includes(d)) break
114          delim += d
115        }
116        heredocs.push({ delim, strip, quoted })
117      }
118      push(c, i)
119      cur.redirect = true
120      continue
121    }
122    if (c === '|') {
123      endSegment(i)
124      if (cmd[i + 1] === '|') i++
125      else if (cmd[i + 1] === '&') i++
126      continue
127    }
128    if (c === '&') {
129      if (cmd[i + 1] === '&') { endSegment(i); i++; continue }
130      const prev = cur ? cur.text[cur.text.length - 1] : ''
131      if (prev === '>' || prev === '<' || cmd[i + 1] === '>') { push(c, i); continue } // 2>&1, &>file
132      background = true
133      endSegment(i)
134      continue
135    }
136    if ((c === '(' || c === ')') && cmd[i - 1] !== '$') { endSegment(i); continue }
137    push(c, i)
138  }
139  if (quote !== '') return null
140  endSegment(cmd.length)
141  if (background) return null
142  // a copy of the command with the data spans blanked, the same length, for the substitution search
143  let masked = cmd
144  for (const [a, b] of masks) masked = masked.slice(0, a) + ' '.repeat(b - a) + masked.slice(b)
145  segments.masked = masked
146  return segments
147}
148
149// ---- reading one segment ----
150
151const ASSIGN = /^[A-Za-z_][A-Za-z0-9_]*=/
152
153const base = (p) => p.slice(p.lastIndexOf('/') + 1)
154
155// ---- the hook ----
156
157const PRE_MS = 3_000 // pdx.json, the permission check: a read that has not answered by then is a failed one
158const ASK_MS = 3_000 // `pdx entry match`: longer than this and the question counts as no answer
159const PLAN_MS = 4_000 // all of the planning together: a hook that waits on a dead dependency must not hold every Bash call
160const MAX_ASKS = 6 // one call can hold several commands: at most this many distinct ones are asked about the entry
161
162const parse = (s) => { try { return JSON.parse(s) } catch { return null } }
163const isObject = (v) => !!v && typeof v === 'object' && !Array.isArray(v)
164const sq = (s) => "'" + String(s).replace(/'/g, "'\\''") + "'"
165const withNotes = (r, notes) => (notes.length && r && typeof r === 'object' ? { ...r, context: [...(r.context ?? []), ...notes] } : r)
166
167// A tool binary called by path.
168const GATED_BIN = /(?:^|\/)(?:node_modules\/\.bin\/(?:vitest|tsc)|vendor\/bin\/(?:phpunit|pest))$/
169// `claude plugin test`: the mods' test run (claude is the agent itself); it is asked about the entry like a tool binary called by path.
170const isPluginTest = (c) => base(c.first) === 'claude' && c.argv[1] === 'plugin' && c.argv[2] === 'test'
171const isGatedBin = (c) => GATED_BIN.test(c.first) || isPluginTest(c)
172// The first words of the commands the entry is asked about; anything else is not.
173const TOOLS = new Set(['go', 'pnpm', 'pnpx', 'npx', 'yarn', 'npm', 'bunx', 'bun', 'vitest', 'tsc', 'make', 'composer', 'phpunit', 'pest'])
174
175function log($, text) {
176  try {
177    const p = $.ui.log('pdx-gate: ' + text, { to: 'debug' })
178    if (p && typeof p.catch === 'function') p.catch(() => {})
179  } catch {}
180}
181
182// bounded runs one engine read and gives its answer, or undefined when it rejects or has not answered within PRE_MS.
183async function bounded($, read) {
184  const cap = Promise.resolve().then(() => $.clock.sleep(PRE_MS)).then(() => undefined, () => undefined)
185  return Promise.race([Promise.resolve().then(read).catch(() => undefined), cap])
186}
187
188// gateConfig is the pdx binary to run and the wwd entry switch, from pdx.json beside VERSION as ask.js does; `pdx` from PATH and the
189// switch off when there is none.
190async function gateConfig($) {
191  const cfg = parse(await bounded($, () => $.fs.read($.plugin.root + '/pdx.json')))
192  return {
193    bin: isObject(cfg) && typeof cfg.pdx === 'string' && cfg.pdx ? cfg.pdx : 'pdx',
194    entry: isObject(cfg) && typeof cfg.entry === 'string' && cfg.entry !== '', // the wwd entry switch
195  }
196}
197
198// headOf reads one segment: where the command proper starts (past environment assignments and the plain wrappers env,
199// time, exec, command, nice, timeout), and its words from there without redirections. null when there is no command.
200function headOf(words) {
201  const skip = new Set()
202  words.forEach((x, k) => { if (x.redirect && BARE.test(x.text)) skip.add(k + 1) }) // a bare `>` takes the next word
203  const live = (k) => !words[k].redirect && !skip.has(k)
204  let k = 0
205  for (let guard = 0; guard < 8; guard++) {
206    while (k < words.length && !live(k)) k++
207    if (k >= words.length) return null
208    const t = words[k].text
209    const head = base(t)
210    if (ASSIGN.test(t)) { k++; continue }
211    if (head === 'env' || head === 'time' || head === 'exec' || head === 'command') { k++; continue }
212    if (head === 'nice') { k++; if (k < words.length && words[k].text === '-n') k += 2; continue }
213    if (head === 'timeout') {
214      k++
215      while (k < words.length && words[k].text.startsWith('-')) k += words[k].text === '-s' || words[k].text === '-k' ? 2 : 1
216      k++ // the duration
217      continue
218    }
219    break
220  }
221  if (k >= words.length) return null
222  const rest = []
223  let last = k
224  let dead = -1 // the first redirection word (or the file it takes) after the command word
225  for (let j = k; j < words.length; j++) {
226    if (live(j)) { rest.push(words[j].text); last = j } else if (dead < 0) dead = j
227  }
228  // clean: no redirection among the words of the command, so its text from `at` to `end` is the command and nothing else (one
229  // after the last word, `2>&1`, stays where it is when the command is replaced)
230  return { at: words[k].start, end: words[last].end, clean: dead < 0 || dead > last, first: words[k].text, argv: rest }
231}
232
233// readCommand splits a Bash command into the commands in it. null for what cannot be read or that goes to the
234// background by itself (`&`): those are left exactly as they are.
235export function readCommand(command, continuation = false) {
236  const segs = scan(command, continuation)
237  if (!segs) return null
238  const out = []
239  for (const words of segs) {
240    const h = headOf(words)
241    if (h) out.push(h)
242  }
243  return out
244}
245
246// verdict is the engine's permission decision for a call, or null when it could not be had.
247async function verdict($, command, background) {
248  const v = await bounded($, () => $.tool.check({ tool: 'Bash', input: { command, run_in_background: background } }))
249  return v && typeof v.decision === 'string' ? v.decision : null
250}
251
252// withDeadline gives the answer of a plan, or null when it has not come within PLAN_MS (the call then runs as it is).
253async function withDeadline($, work) {
254  const cap = Promise.resolve().then(() => $.clock.sleep(PLAN_MS)).then(() => null, () => null)
255  return Promise.race([work, cap])
256}
257
258// ---- the wwd entry ----
259
260// a word that needs no quoting in a shell
261const word = (s) => (/^[A-Za-z0-9_@%+=:,./-]+$/.test(String(s)) ? String(s) : sq(s))
262
263// entryCandidates are the commands of a call that the entry is asked about, in order, with where each stands in the text and the
264// directory it runs in as far as `cd` words say (a relative one is pdx's to resolve from the session's directory), and a key naming
265// the command and that directory. ok is false when the directory cannot be known: a cd the hook cannot read, or a command that is
266// not reached by `&&` from the cd before it (after `cd x ; go test` or `cd x || go test` the test runs in x only if the cd worked,
267// and the hook cannot tell). Every occurrence is a candidate; the ones with one key share an answer.
268export function entryCandidates(command) {
269  if (command.includes('(')) return [] // a subshell or a substitution: where a cd applies is not something to guess
270  const cmds = readCommand(command, true)
271  if (!cmds) return []
272  const out = []
273  let cwd = ''
274  let ok = true
275  let cded = false // a cd has changed the directory: from here on only `&&` carries it
276  let prevEnd = -1
277  for (const c of cmds) {
278    // between the two commands: `&&`, then at most the environment words and wrappers that headOf skips before the command word
279    if (cded && !/^\s*&&(\s|$)/.test(command.slice(prevEnd, c.at))) ok = false
280    prevEnd = c.end
281    if (base(c.first) === 'cd') {
282      const d = c.argv[1]
283      if (c.argv.length !== 2 || !/^[A-Za-z0-9_@%+=:,./-]+$/.test(d) || d === '-') ok = false
284      else { cwd = d.startsWith('/') ? d : cwd ? cwd.replace(/\/$/, '') + '/' + d : d; cded = true }
285      continue
286    }
287    if (!TOOLS.has(base(c.first)) && !isGatedBin(c)) continue
288    out.push({ ...c, cwd, ok, key: JSON.stringify([cwd, c.argv]) })
289  }
290  return out
291}
292
293// askEntry is `pdx entry match`'s answer for one command, or null (no answer is "leave it").
294async function askEntry($, cfg, c) {
295  if (!c.ok) return null
296  try {
297    const r = await $.process.run([cfg.bin, 'entry', 'match', '--json', ...(c.cwd ? ['--cwd', c.cwd] : []), '--', ...c.argv], { timeoutMs: ASK_MS })
298    if (!r || r.exitCode !== 0) return null
299    const o = parse(String(r.stdout || '').trim())
300    if (!isObject(o)) return null // an action nobody knows is ignored below
301    if (o.action === 'rewrite' && (typeof o.task !== 'string' || o.task === '' || (o.args !== undefined && !(Array.isArray(o.args) && o.args.every((x) => typeof x === 'string'))))) return null
302    return o
303  } catch (err) {
304    log($, 'entry match failed: ' + (err && err.message ? err.message : String(err)))
305    return null
306  }
307}
308
309// an ad-hoc job runs the argv as it is typed; the words are quoted again, so a command whose words the shell would still have to
310// work on (a variable, a substitution, a glob, a brace, a tilde, a backslash) is not turned into one: its text is what the shell
311// makes of it, not what the hook reads
312const adhocPlain = (text) => !/[$`*?[\]{}~!\\]/.test(text)
313
314// (an input redirection anywhere in the call, `<`, a heredoc or a here-string, keeps the call as it is: the ad-hoc job's command has no
315// standard input, and the redirection would stay on pdx)
316const pdxAdhoc = (cfg, c) => sq(cfg.bin) + ' test --adhoc -- ' + c.argv.map(word).join(' ')
317
318const pdxTest = (cfg, a) => {
319  const args = Array.isArray(a.args) ? a.args : []
320  return sq(cfg.bin) + ' test ' + word(a.task) + (args.length ? (args.some((x) => x.startsWith('-')) ? ' -- ' : ' ') + args.map(word).join(' ') : '')
321}
322
323// planEntry is what the entry makes of a call: { deny } to refuse it, or { command, background, notes } (notes only when nothing
324// is replaced), or null for nothing to do. The replacement is not made when it would change the permission verdict.
325async function planEntry($, e, cfg, wasBackground) {
326  const cands = entryCandidates(e.command)
327  if (cands.length === 0) return null
328  // one question for each command in each directory, at most MAX_ASKS of them; its answer holds for every place it stands
329  const firsts = []
330  for (const c of cands) if (!firsts.some((f) => f.key === c.key)) firsts.push(c)
331  const byKey = new Map(await Promise.all(firsts.slice(0, MAX_ASKS).map(async (c) => [c.key, await askEntry($, cfg, c)])))
332  const answers = cands.map((c) => (c.ok ? byKey.get(c.key) ?? null : null)) // where the directory is unknown, no answer is borrowed
333  const notes = []
334  const rewrites = []
335  let deny = null
336  answers.forEach((a, i) => {
337    if (!a) return
338    if (a.broken === true) notes.push('Purdex mod:這個 repo 的 .wwd/tasks.toml 讀不了(' + (a.reason ?? '') + '),測試/建置指令先照常走。')
339    const hint = typeof a.hint === 'string' && a.hint ? a.hint : ''
340    if (a.action === 'deny' && !deny) {
341      deny = 'Purdex mod 拒絕這個指令:這個 repo 的 .wwd/tasks.toml 規定測試與建置要用 pdx test 的 task([entry].mode = deny)。' +
342        (hint ? '最接近的是 pdx test ' + hint + ' …;' : '') + 'pdx test --list 列出全部。'
343    } else if (a.action === 'adhoc' && cands[i].clean && adhocPlain(e.command.slice(cands[i].at, cands[i].end)) && !e.command.includes('<')) {
344      rewrites.push({ c: cands[i], a, adhoc: true })
345    } else if (a.action === 'advise' || a.action === 'adhoc') {
346      // an ad-hoc answer for a command that cannot be turned into a job (a redirection, something the shell expands) is advice
347      notes.push('Purdex mod:這個指令沒有對應的 .wwd/tasks.toml task,照常執行。' + (hint ? '建議改用 pdx test ' + hint + ' …;' : '') + 'pdx test --list 列出全部。')
348    } else if (a.action === 'rewrite' && cands[i].clean) {
349      rewrites.push({ c: cands[i], a })
350    }
351  })
352  notes.splice(0, notes.length, ...new Set(notes)) // a command that stands twice says its piece once
353  if (deny) return { deny }
354  if (rewrites.length === 0) return notes.length ? { command: e.command, background: wasBackground, notes } : null
355  let command = e.command
356  for (const { c, a, adhoc } of rewrites.sort((x, y) => y.c.at - x.c.at)) command = command.slice(0, c.at) + (adhoc ? pdxAdhoc(cfg, c) : pdxTest(cfg, a)) + command.slice(c.end)
357  const [before, after] = await Promise.all([verdict($, e.command, wasBackground), verdict($, command, wasBackground)])
358  if (before === null || before !== after) {
359    log($, 'the rewrite to pdx test would change the permission verdict (' + before + ' → ' + after + '): the call goes the old way')
360    return notes.length ? { command: e.command, background: wasBackground, notes } : null
361  }
362  let background = wasBackground
363  const queued = rewrites.some((r) => r.a.queued === true)
364  if (queued && !wasBackground) {
365    const [b2, a2] = await Promise.all([verdict($, e.command, false), verdict($, command, true)])
366    if (b2 !== null && b2 === a2) background = true
367  }
368  const onlyAdhoc = rewrites.every((r) => r.adhoc)
369  notes.unshift((onlyAdhoc
370    ? 'Purdex mod 依這個 repo 的 .wwd/tasks.toml([entry].mode = rewrite)把沒有對應 task 的測試/建置指令改成 pdx test --adhoc 執行(占用 heavy 名額,不是 task),實際執行的是:'
371    : 'Purdex mod 依這個 repo 的 .wwd/tasks.toml 把測試/建置指令改成 pdx test,實際執行的是:') + command +
372    (background && !wasBackground ? '。這個 task 要排佇列,所以整段改成背景執行:它輪到時會自己開始,整段跑完時你會收到通知與輸出;在那之前不要假設它做完了,不要重跑。' : ''))
373  return { command, background, notes }
374}
375
376// planGate is everything decided before the call runs: the command to run, whether to run it in the background, and the
377// notes for the model. A plan that is null (or throws) means the call runs as it is. Only the wwd entry plans anything now: the gate
378// holds nothing (WWD-9), so there is no prefix and no question about a wait. planEntry has checked the permission verdict of what it
379// replaced and of the background it chose, each against the call as it came.
380async function planGate($, e) {
381  if (typeof e.command !== 'string' || e.command === '') return null
382  const cfg = await gateConfig($)
383  if (!cfg.entry) return null
384  const wasBackground = e.run_in_background === true
385  let ep = null
386  try { ep = await planEntry($, e, cfg, wasBackground) } catch (err) { log($, 'entry failed, the call goes as it came: ' + (err && err.message ? err.message : String(err))) }
387  if (!ep) return null
388  if (ep.deny) return { deny: ep.deny }
389  const background = ep.background || wasBackground
390  if (ep.command === e.command && background === wasBackground && ep.notes.length === 0) return null
391  return { command: ep.command, background, notes: ep.notes }
392}
393
394export function registerGate(on) {
395  on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
396    let plan = null
397    try { plan = await withDeadline($, planGate($, e)) } catch (err) { log($, 'planning failed, the call runs as it is: ' + (err && err.message ? err.message : String(err))) }
398    if (!plan) return next(e)
399    if (plan.deny) return { deny: plan.deny }
400    const r = await next({ ...e, command: plan.command, ...(plan.background ? { run_in_background: true } : {}) })
401    if (!r || typeof r !== 'object' || 'deny' in r) return r
402    return withNotes(r, plan.notes)
403  }).catch(($, e, next) => next(e))
404}
405
hooks/member.js 146 lines
1// Purdex mod — member relay, the pure half (plan v3 P6-6; spec §8.2 steps 3–8, M1, M28).
2//
3// A lead asks a member to relay with a control message: a peer message whose text carries
4// `[pdx-relay:control] op=<uuid>`. register.js (which owns the shared state and every `$` call)
5//   - takes it in `session.receive`, always, busy or idle: the model never sees it;
6//   - tells the daemon from a timer that the mod has it (`pdx relay seen`, Q2 branch A);
7//   - claims the op only when no main-conversation turn runs: at once when idle, else at that
8//     turn's turn.complete (codex finding 1), then takes the write path a self relay takes after
9//     an approval: write → check → fix ×2 → written → /clear → seed → done.
10//   - a claim that fails does nothing: the daemon's own timeout reports it.
11//
12// The mod's static rules never follow `$` across an import (Q3 deviation: the receive hook and
13// the claim cannot live here), so this file holds what needs no `$`: reading the control message,
14// checking a claim's answer, and writing the team facts of the write prompt.
15
16const CONTROL_PREFIX = '[pdx-relay:control] op=' // team.RelayControlPrefix
17const UUID = '[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}'
18const CONTROL_RE = new RegExp(CONTROL_PREFIX.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '(' + UUID + ')')
19
20export const CONSUMED = 'pdx relay control message' // the reason logged for a consumed delivery
21
22// The re-ask after a pause (the quota pause, UP-4): `[pdx-relay:control] reask id=<uuid>` (team.PauseReaskControlPrefix).
23// A different marker from the op control above, so neither parser can take the other's message.
24const REASK_PREFIX = '[pdx-relay:control] reask id='
25// The marker stands alone on its own line (the daemon sends the control line and nothing else) and the message is short: a quote, a
26// sentence or a tool result that merely mentions it is ordinary text, not a message to consume.
27const REASK_RE = new RegExp('(?:^|\\n)' + REASK_PREFIX.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '(' + UUID + ')[ \\t]*(?:\\r?\\n|$)')
28const REASK_MAX_TEXT = 2048
29export const CONSUMED_REASK = 'pdx relay reask control message'
30
31// controlReask is the release token of a reask control message, '' for any other delivery. Only a peer's text counts, as for controlOp.
32export function controlReask(e) {
33  if (!e || !e.origin || e.origin.kind !== 'peer' || typeof e.text !== 'string' || e.text.length > REASK_MAX_TEXT) return ''
34  const m = REASK_RE.exec(e.text)
35  return m ? m[1] : ''
36}
37
38// controlOp is the op id of a control message, '' for any other delivery. Only a peer's text counts
39// (M1): the same words typed by the user, or in a tool result, are ordinary text.
40export function controlOp(e) {
41  if (!e || !e.origin || e.origin.kind !== 'peer' || typeof e.text !== 'string') return ''
42  const m = CONTROL_RE.exec(e.text)
43  return m ? m[1] : ''
44}
45
46// claimOp is the op of a claim's answer (`pdx relay claim` stdout), undefined when it is not one.
47export function claimOp(body) {
48  const op = body && body.op
49  return op && typeof op.id === 'string' && typeof op.handoff_path === 'string' ? op : undefined
50}
51
52// leadLine is a member's `{{team}}` (write prompt tail §8.2 step 4), starting with a newline since the
53// placeholder ends the whoami line. `clean` makes third-party text safe (register.js cleanGit).
54export function leadLine(lead, clean) {
55  return '\n- 我的 lead:' + clean(String(lead.address)) + '(ref ' + clean(String(lead.ref)) + ',team ' + clean(String(lead.team_id)) + ')'
56}
57
58// rosterLines is a lead's `{{team}}` from `pdx team --json`'s answer (undefined when it was unreadable).
59// Titles and directories are third-party text: cleaned, one line each.
60export function rosterLines(view, clean) {
61  if (!view || typeof view !== 'object') return '\n- 我管理的 members:(讀不到,接手後請用 pdx team 查)'
62  const members = Array.isArray(view.members) ? view.members : []
63  if (members.length === 0) return '\n- 我管理的 members:無'
64  const one = (v) => clean(String(v ?? '')).replace(/\s+/g, ' ').trim()
65  return '\n- 我管理的 members:' + members.map((m) => '\n  - ' + one(m.address) + '(ref ' + one(m.ref) + ',title ' + (one(m.title) || '無') + ',cwd ' + one(m.cwd) + ')').join('')
66}
67
68// ---- /team (relay/team rules v2, RT-1c) ----
69
70const MODEL_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}(\[1m\])?$/ // team.ValidModel
71const EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max'] // team.ValidEffort
72const TEAM_USAGE = '用法:/team [名稱或說明] | spawn <任務> [--model m] [--effort e] | adopt <ref> | release <ref> | kill <ref>'
73export const SPAWN_USAGE = '用法:/team spawn <任務> [--model m] [--effort e]'
74
75const PERSONA_CODE_RE = /^[a-z]{2,16}$/ // the shape `pdx names` keeps (cmd/pdx leadNameCode)
76
77// parseTeamNames reads the stdout of `pdx names --json` (name pool v2 spec §5.3): { leadName: true, personas: [{ code, name }] } when
78// the daemon takes a lead name and the list is well formed, otherwise undefined, which is how every failure — an older pdx with no
79// such command, a daemon without team.lead_name.v1, an answer that is not what was asked — leaves /team as it was before names.
80export function parseTeamNames(stdout) {
81  let b
82  try { b = JSON.parse(String(stdout ?? '')) } catch { return undefined }
83  if (!b || typeof b !== 'object' || b.lead_name !== true || !Array.isArray(b.personas)) return undefined
84  const personas = []
85  for (const p of b.personas) {
86    if (!p || typeof p !== 'object' || typeof p.code !== 'string' || !PERSONA_CODE_RE.test(p.code)) return undefined
87    personas.push({ code: p.code, name: typeof p.name === 'string' ? p.name : '' })
88  }
89  return { leadName: true, personas }
90}
91
92// personaMatches are the personas a typed word names: the word is compared, case-insensitively, with each persona's code and with
93// the first word of its display name. A persona counts once however it matched.
94function personaMatches(word, personas) {
95  const w = word.toLowerCase()
96  return personas.filter((p) => p.code.toLowerCase() === w || (p.name.trim().split(/\s+/)[0] || '').toLowerCase() === w)
97}
98
99// parseTeamArgs reads what follows `/team`: { kind: 'show' } (nothing), { kind: 'lead', note } (any other text),
100// { kind: 'spawn', task, model?, effort? }, { kind: 'adopt' | 'release' | 'kill', ref } or { error }. `--model` and
101// `--effort` belong to spawn only (their values are the CLI's own lists); a word of another kind is part of the note.
102//
103// names (parseTeamNames, optional) is the persona list of a daemon that takes a lead name. With it the lead kind learns two
104// things: the first word names exactly one persona → { kind: 'lead', note: <the rest>, leadName: <its code> }, a lead at once
105// under that name; otherwise (no persona, or more than one: the daemon never picks) → { kind: 'lead', note, card: true }, a
106// request that waits on the card where the person picks. Nothing typed is { kind: 'show', card: true }, which a session that
107// leads still answers with its roster. Without names it is all exactly as before.
108export function parseTeamArgs(args, names) {
109  const text = String(args ?? '').trim()
110  const named = names && names.leadName === true // a daemon that takes a lead name, with its persona list
111  if (text === '') return named ? { kind: 'show', card: true } : { kind: 'show' }
112  const words = text.split(/\s+/)
113  const head = words[0]
114  if (head === 'spawn') {
115    const out = { kind: 'spawn', task: '' }
116    const task = []
117    for (let i = 1; i < words.length; i++) {
118      const w = words[i]
119      const m = /^--(model|effort)(?:=(.*))?$/.exec(w)
120      if (!m) { task.push(w); continue }
121      const name = m[1]
122      let value = m[2]
123      if (value === undefined) value = words[++i]
124      if (value === undefined || value === '' || value.startsWith('--')) return { error: '--' + name + ' 需要一個值。' + SPAWN_USAGE }
125      if (name === 'model' && !MODEL_RE.test(value)) return { error: '--model 的值不合法:' + value.slice(0, 40) }
126      if (name === 'effort' && !EFFORTS.includes(value)) return { error: '--effort 只能是 ' + EFFORTS.join('、') + ':' + value.slice(0, 40) }
127      out[name] = value
128    }
129    out.task = task.join(' ')
130    if (out.task === '') return { error: SPAWN_USAGE }
131    return out
132  }
133  if (head === 'adopt' || head === 'release' || head === 'kill') {
134    if (words.length !== 2 || words[1].startsWith('-')) return { error: '用法:/team ' + head + ' <ref>' }
135    return { kind: head, ref: words[1] }
136  }
137  if (named) {
138    const hit = personaMatches(head, names.personas)
139    if (hit.length === 1) return { kind: 'lead', note: text.slice(head.length).trim(), leadName: hit[0].code }
140    return { kind: 'lead', note: text, card: true }
141  }
142  return { kind: 'lead', note: text }
143}
144
145export { TEAM_USAGE }
146
hooks/prompts.js 5 lines
1// GENERATED from internal/team/relay_prompts.go by: go test ./cmd/pdx/plugin/ -run TestPromptsJS -update — do not edit.
2export const DEFAULT_BODIES = {"write":"這個 session 要接力了:{{why}}。接力已核准(之後會 /clear)。\n請用你完整的工具撰寫接力檔:{{path}}(手邊有工作就先停下)\n\n要求:\n- 接力檔必須自成一體:讀它的是一個完全沒有這段對話記憶的新對話。\n- 如果現在是在等使用者、lead 或其他 session(例如等決定、等 merge 通知),§2 的「下一步」要寫清楚在等什麼、等誰、等到之後的第一個動作(具體到指令)。\n\n機器提供的 git 狀態(照抄進 §3):\n{{git}}","fix":"接力檔 {{path}} 不完整。","seed":"你是接手的新對話:前一段對話已接力並清空({{why}})。\n請先讀接力檔 {{path}},然後:\n1. 用三行複述:目標、下一步第一個動作、目前有哪些檔案異動。\n2. 跑 `git status` 確認與接力檔一致,不一致就指出來。\n3. 如果「下一步」是在等使用者、lead 或其他 session,就停在這裡等,不要自己開始新的工作;否則接著從「下一步」繼續原本的工作。\n回覆的第一行請寫「↪ 接手自 {{old_ref}}」。"}
3export const FIXED = {"write":{"head":"[pdx-relay op={{op}} n={{nonce}}] ","tail":"\n- 只用 Write 工具一次寫入整個接力檔;這一輪不要執行其他工具(接力期間其他工具會被拒絕)。\n- 寫完後只回一行「HANDOFF-WRITTEN」,不要繼續原本的工作。\n\n格式(每一段都要有,沒有內容就寫「無」):\n# HANDOFF\n## 1. 目標與完成定義(使用者要的是什麼、怎樣算完成、範圍外)\n## 2. 進度(已完成且驗證 / 進行中停在哪 / 下一步第一個動作具體到指令)\n## 3. 檔案異動(git status 與 diff --stat 的結果,加上每個檔案的用途)\n## 4. 決策紀錄(選了什麼、為什麼、否決了什麼)\n## 5. 死路(試過失敗、不要再試的)\n## 6. 環境與指令(測試 / 執行方式)\n## 7. 未決問題與需要使用者決定的事\n## 8. 協作關係(下面的 pdx 身分;我的 lead 與我管理的 members,沒有就寫無)\n\n機器提供的事實(請照抄進對應段落):\n- 舊 session id:{{old_session}}\n- 舊 ref:{{old_ref}}\n- 接力時 context:{{context}}\n- pdx 身分:{{whoami}}{{team}}"},"fix":{"head":"[pdx-relay op={{op}} n={{nonce}}] ","tail":"缺少段落:{{missing}}。請用 Write 重寫整個接力檔(不要用 Edit),補齊後只回「HANDOFF-WRITTEN」。"},"seed":{"head":"↪ 接手自 {{old_ref}}\n[pdx-relay seed op={{op}} n={{nonce}}] ","tail":"{{tasks}}"}}
4export const VARIABLES = ["path","old_ref","old_session","context","whoami","git","why"]
5
hooks/workbook.js 218 lines
1// Purdex mod — the session workbook's job executor, the pure half (session workbook spec §5.1).
2//
3// The daemon hands this mod a summariser job (`POST /mod/v1/workbook/next`), the mod runs the model call in the session's
4// own process (`$.model.complete`) and reports what happened (`POST /mod/v1/workbook/result`). The daemon keeps every
5// decision — the input, the order, the prompt, the validation; this file only maps shapes. Nothing here touches `$`:
6// M-U1-2 says `$` is followed only into functions declared in events.js, so the parts that call `$` live there and the
7// plain data conversions live here, where a test can reach them.
8
9export const NEXT_URL = 'http://pdx/mod/v1/workbook/next'
10export const RESULT_URL = 'http://pdx/mod/v1/workbook/result'
11export const REFRESH_URL = 'http://pdx/mod/v1/workbook/refresh'
12export const CAPS = ['workbook.v2', 'workbook.refresh', 'prompt.v1'] // announced on every events batch: turn / re-write jobs, the refresh fork, and the Apps' send / interrupt
13export const WAIT_MS = 15_000 // the long poll after a main turn ends
14export const REQUEST_DEADLINE_MS = 5000 // slack over the wait for a request to be answered ($.http.fetch has no timeout)
15export const REASONS = new Set(['api-error', 'empty-reply', 'aborted', 'nothing-to-fork'])
16export const MODEL_SLACK_MS = 5000 // a call that outlives its own timeout_ms by this much is cut by the mod — and the
17// daemon's lease lasts timeout_ms + 10 s, so the abort report still has 5 s to arrive before the lease runs out
18export const DEFAULT_TIMEOUT_MS = 30_000 // the deadline of a job that names none
19export const DEFAULT_FORK_TIMEOUT_MS = 90_000 // the deadline of a fork job that names none (the daemon names 90 s)
20export const MAX_JOBS_PER_DRAIN = 8 // jobs one run of the loop takes before it stops and waits for the next trigger
21
22// Bounds on a job from the daemon (fail closed: a job outside them is answered `refused`, the model is not called).
23const MODEL_RE = /^[a-z0-9][a-z0-9._-]{0,63}$/
24const MAX_TEXT = 200_000 // characters of the prompt, and of each system block
25const MAX_BLOCKS = 8
26const MAX_TOKENS = 4096 // the daemon's contract; 4096 tokens is far below the 64 KiB the result route takes as text
27const MAX_TIMEOUT_MS = 120_000
28const MAX_FORK_TIMEOUT_MS = 300_000 // a fork sends the whole conversation
29const EFFORTS = new Set(['low', 'medium', 'high', 'xhigh', 'max'])
30
31const isObject = (v) => !!v && typeof v === 'object' && !Array.isArray(v)
32const num = (v) => (Number.isFinite(v) && v >= 0 ? Math.trunc(v) : 0)
33
34// shouldAsk: a main-thread turn that ended in an answer or an error is a turn the daemon may have a job for. A subagent's
35// turn.complete (it carries an agentId), an interrupted turn and the like are not.
36export function shouldAsk(e) {
37  return !!e && !e.agentId && (e.reason === 'answer' || e.reason === 'error')
38}
39
40// nextBody is the request of `next`.
41export function nextBody(stream, sessionId, waitMs) {
42  return JSON.stringify({ stream, session_id: sessionId, wait_ms: waitMs })
43}
44
45// parseNext reads the answer of `next`: the job, or null (204, an error, anything that is not a well-formed job).
46export function parseNext(res) {
47  if (!res || res.status !== 200) return null
48  let o
49  try { o = JSON.parse(res.text) } catch { return null }
50  const job = isObject(o) ? o.job : null
51  if (!isObject(job) || typeof job.id !== 'string' || !job.id || typeof job.kind !== 'string') return null
52  return job
53}
54
55// completeRequest maps a job's `complete` to the API's keys (max_tokens → maxTokens, timeout_ms → timeoutMs; the system
56// blocks keep their cache marks). Null when the job has nothing to run.
57export function completeRequest(c) {
58  if (!isObject(c) || typeof c.model !== 'string' || !MODEL_RE.test(c.model) || typeof c.prompt !== 'string' || c.prompt.length > MAX_TEXT) return null
59  const req = { model: c.model, prompt: c.prompt }
60  if (c.system !== undefined) {
61    // fail closed: a system that is not a short list of text blocks is a daemon this mod does not understand
62    if (!Array.isArray(c.system) || c.system.length > MAX_BLOCKS) return null
63    for (const b of c.system) if (!isObject(b) || typeof b.text !== 'string' || b.text.length > MAX_TEXT) return null
64    req.system = c.system.map((b) => (b.cache ? { text: b.text, cache: true } : { text: b.text }))
65  }
66  if (c.max_tokens !== undefined) {
67    if (!Number.isInteger(c.max_tokens) || c.max_tokens < 1 || c.max_tokens > MAX_TOKENS) return null
68    req.maxTokens = c.max_tokens
69  }
70  if (c.effort !== undefined) {
71    if (!EFFORTS.has(c.effort)) return null
72    req.effort = c.effort
73  }
74  if (c.timeout_ms !== undefined) {
75    if (!Number.isInteger(c.timeout_ms) || c.timeout_ms < 1000 || c.timeout_ms > MAX_TIMEOUT_MS) return null
76    req.timeoutMs = c.timeout_ms
77  }
78  return req
79}
80
81// forkRequest reads a refresh job's `fork` ({prompt, timeout_ms}): the request of $.model.fork (just the prompt — the fork
82// sends the conversation itself) and the deadline the mod keeps. Null when the job has nothing this mod will run.
83export function forkRequest(f) {
84  if (!isObject(f) || typeof f.prompt !== 'string' || !f.prompt || f.prompt.length > MAX_TEXT) return null
85  if (f.timeout_ms !== undefined && (!Number.isInteger(f.timeout_ms) || f.timeout_ms < 1000 || f.timeout_ms > MAX_FORK_TIMEOUT_MS)) return null
86  return { req: { prompt: f.prompt }, timeoutMs: f.timeout_ms ?? DEFAULT_FORK_TIMEOUT_MS }
87}
88
89// refreshBody is the request of the daemon's refresh route (the /workbook refresh command).
90export function refreshBody(stream, sessionId) {
91  return JSON.stringify({ stream, session_id: sessionId })
92}
93
94// refreshNotice turns the daemon's answer to a refresh request into the one line the person sees, and says whether the job
95// was queued (then the mod asks `next` at once).
96export function refreshNotice(res) {
97  if (!res) return { queued: false, text: '工作簿重整:沒有連上 daemon,沒有排入。' }
98  let code = ''
99  try { code = String(JSON.parse(res.text)?.error ?? '') } catch {}
100  if (res.status === 202) return { queued: true, text: '工作簿重整:已排入,稍後會更新「目前狀況」與待辦。' }
101  if (res.status === 409 && code === 'refresh_pending') return { queued: false, text: '工作簿重整:上一次重整還在進行,請稍後。' }
102  if (res.status === 409) return { queued: false, text: '工作簿重整:目前沒有可執行重整的 session(daemon 或這個 mod 還不支援)。' }
103  return { queued: false, text: '工作簿重整:失敗(daemon 回應 ' + res.status + ')。' }
104}
105
106// usageOf maps the API's usage to the daemon's.
107export function usageOf(u) {
108  const o = isObject(u) ? u : {}
109  return { input: num(o.input_tokens), output: num(o.output_tokens), cache_read: num(o.cache_read_input_tokens) }
110}
111
112// resultBody is the request of `result` for a finished call: r is `$.model.complete`'s result, or null when the call was
113// refused (it rejected). A reason the daemon does not know is reported as `api-error` rather than guessed at.
114export function resultBody(stream, jobId, r, latencyMs) {
115  const body = { stream, job_id: jobId, latency_ms: num(latencyMs) }
116  if (!isObject(r)) return JSON.stringify({ ...body, answered: false, reason: 'refused', usage: usageOf(null) })
117  if (r.isAnswered === true) return JSON.stringify({ ...body, answered: true, text: String(r.text ?? ''), usage: usageOf(r.usage) })
118  const out = { ...body, answered: false, reason: REASONS.has(r.reason) ? r.reason : 'api-error', usage: usageOf(r.usage) }
119  if (Number.isInteger(r.status)) out.status = r.status
120  if (typeof r.error === 'string') out.error = r.error
121  return JSON.stringify(out)
122}
123
124// refusedBody answers a job this mod cannot run (a kind it does not know, a job outside the bounds).
125export function refusedBody(stream, jobId) {
126  return resultBody(stream, jobId, null, 0)
127}
128
129// moreOf reads the answer of `result`: whether another job of the conversation is ready (a 200 {"more": true}).
130export function moreOf(res) {
131  if (!res || res.status !== 200) return false
132  try { return JSON.parse(res.text)?.more === true } catch { return false }
133}
134
135// ---- the prompt queue (interface U3 plan D7): the Apps' send and interrupt, run through this session's own process ----
136
137export const PROMPT_NEXT_URL = 'http://pdx/mod/v1/prompt/next'
138export const PROMPT_RESULT_URL = 'http://pdx/mod/v1/prompt/result'
139export const PROMPT_WAIT_MS = 15_000 // the standing long poll
140export const PROMPT_IDLE_MS = 1000 // a poll that comes back sooner than this with nothing waits this long before the next
141export const PROMPT_BACKOFF_MS = 2000 // after a failed poll
142export const PROMPT_RESULT_TRIES = 3 // a result that gets no 200 / 409 is sent again, 0.7 s and 1.4 s later (inside the daemon's 10 s)
143export const PROMPT_RESULT_RETRY_MS = 700
144export const PROMPT_RESULT_POST_MS = 2000 // one try of a result waits at most this long
145export const PROMPT_RESULT_BUDGET_MS = 6500 // no try starts later than this after the job arrived (the daemon's lease is 10 s)
146const MAX_PROMPT_TEXT = 8000 // characters; the daemon sends at most 4000 bytes
147// A fill / clear_if text and a read's text are bounded in UTF-8 BYTES, the daemon's own unit (promptq.MaxTextBytes): this
148// limit must never be smaller than the daemon's.
149export const MAX_TYPED_TEXT_BYTES = 16384
150const JOB_ID_RE = /^pj-[0-9a-f]{32}$/
151const SID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
152
153// promptNextBody is the request of `prompt/next` for the session this process is running now.
154export function promptNextBody(stream, sessionId, waitMs) {
155  return JSON.stringify({ stream, session_id: sessionId, wait_ms: waitMs })
156}
157
158// parsePromptJob reads the answer of `prompt/next`: the job, or null (204, an error, anything that is not a well-formed
159// job). Fail closed: a job outside the bounds is not run.
160export function parsePromptJob(res) {
161  if (!res || res.status !== 200) return null
162  let o
163  try { o = JSON.parse(res.text) } catch { return null }
164  const j = isObject(o) ? o.job : null
165  if (!isObject(j) || typeof j.id !== 'string' || !JOB_ID_RE.test(j.id) || typeof j.session_id !== 'string' || !SID_RE.test(j.session_id)) return null
166  if (j.kind === 'interrupt') return { id: j.id, kind: 'interrupt', sessionId: j.session_id, text: '' }
167  if (j.kind === 'submit' && typeof j.text === 'string' && j.text.trim() !== '' && j.text.length <= MAX_PROMPT_TEXT) {
168    return { id: j.id, kind: 'submit', sessionId: j.session_id, text: j.text }
169  }
170  if ((j.kind === 'fill' || j.kind === 'clear_if') && typeof j.text === 'string' && j.text.trim() !== '' && cutUtf8(j.text, MAX_TYPED_TEXT_BYTES).length === j.text.length) {
171    return { id: j.id, kind: j.kind, sessionId: j.session_id, text: j.text }
172  }
173  if (j.kind === 'read') return { id: j.id, kind: 'read', sessionId: j.session_id, text: '' }
174  // A well-formed job of a kind this mod does not know (the retired `notice` of the resource lease, or one a later daemon adds)
175  // is handed on to be reported dropped, so the daemon does not hold the stream's queue until its hand-out times out.
176  if (typeof j.kind === 'string' && j.kind !== '' && !PROMPT_KINDS.has(j.kind)) return { id: j.id, kind: 'unsupported', sessionId: j.session_id, text: '' }
177  return null
178}
179
180const PROMPT_KINDS = new Set(['interrupt', 'submit', 'fill', 'clear_if', 'read'])
181
182// fillRefusal is the drop reason of a `$.prompt.fill` answer that did not fill: dialog_open | no_composer | refused (the hook's
183// own refusal and anything unexpected carry no `refusal`), or '' when the composer was filled.
184export function fillRefusal(f) {
185  if (!f || typeof f !== 'object') return 'refused'
186  if (f.isFilled === true) return ''
187  if (f.refusal === 'dialog') return 'dialog_open'
188  if (f.refusal === 'no_composer') return 'no_composer'
189  return 'refused'
190}
191
192const MAX_REASON_BYTES = 120 // the daemon refuses a reason over 128 BYTES: cut by UTF-8 length, on a character boundary
193
194// cutUtf8 keeps the head of s whose UTF-8 encoding fits in max bytes, never splitting a character.
195export function cutUtf8(s, max) {
196  let bytes = 0
197  let out = ''
198  for (const ch of s) { // iterates code points
199    const cp = ch.codePointAt(0)
200    const n = cp < 0x80 ? 1 : cp < 0x800 ? 2 : cp < 0x10000 ? 3 : 4
201    if (bytes + n > max) break
202    bytes += n
203    out += ch
204  }
205  return out
206}
207
208// promptResultBody is the request of `prompt/result`: status accepted | dropped | busy | unknown, and for dropped / unknown the reason.
209// `extra` carries {filledAt} of an accepted fill (unix ms) and {text, truncated} of an accepted read.
210export function promptResultBody(stream, jobId, status, reason, extra) {
211  const b = { stream, job_id: jobId, status }
212  if (reason) b.reason = cutUtf8(String(reason), MAX_REASON_BYTES)
213  if (extra && Number.isFinite(extra.filledAt)) b.filled_at = Math.trunc(extra.filledAt)
214  if (extra && typeof extra.text === 'string') b.text = extra.text
215  if (extra && extra.truncated === true) b.truncated = true
216  return JSON.stringify(b)
217}
218