claude-fleet's in-session extension: version gate + heartbeat on the window's tmux options (#1335), the task-progress band above the prompt (#1339) gone with…

English | 简体中文
Product blueprint: Fleet product direction and design principles (中文) guides future product decisions. The rest of this README describes the current implementation.
Share a team's AI subscriptions, and run the work in the cloud.
claude-fleet does two things: subscription sharing — a small team's Claude and ChatGPT/Codex subscriptions become one pool, metered and routed by headroom — and a cloud runtime — Claude Code and Codex CLI sessions run on managed machines, each task in its own session and git worktree, and keep running when you close your laptop. You reach them from a terminal (fleet), a phone or the web console.
A task is a hub record, T<n>, and it belongs to a person, not to a repository. You say what you want (⌘P's ⚡ line, the web console, or the task tool from another session); the hub writes the record first, then opens the session that does it. A task that names a repository works in a worktree of it and lands a pull request — GitHub only hosts the code and the PRs. Nothing claims, comments on or closes a GitHub issue, and a task with no repository (a page, a document, a conversation) needs no GitHub at all.
The core workflow uses the CLIs' subscription sign-in, with no separate model API key required. Claude subscription account pools and quota-aware routing assign new work by available 5-hour / 7-day headroom and resume tasks on another account when needed; Codex account homes are selected by native quota headroom. See the agent capability table.
Built from daily use on an always-on Mac mini. A local transcript audit found a historical peak of 25 Claude main sessions processing tasks in parallel, across 25 independent worktrees, on September 1, 2026. A separate interval held at least 15 concurrent task directories for 14.46 minutes. These count overlapping CLI processing turns, not simultaneous server-side token generation or a throughput multiplier. Evidence and counting method.
For people who use fleet rather than build it, the guides are in docs/public/en/ (members, admins, self-hosting).
/loop waits between iterations, green ✓ when a turn finishes, red ! + bell when it is blocked on your answer. The task list puts the session that needs you first, and ⌘P's panel lets you answer it without attaching.fleet): the session in view, the task list beside it, and the ⌘P panel to switch, dispatch, answer or open a shell — on your own computer, over SSH from a phone, or in the web console. Sessions on other machines are rows of the same list.ccquota) you can optionally pause remote starts near a limit. See subscription and quota management./fleet-history first, so it stays resumable), and an hourly janitor removes worktrees that are merged + clean + not attached to any live pane (and never anything else).conf/statusline.sh): wired as a measurement bus, not a visible line (issue #1452) — it prints nothing and stamps the context %, window size, model and effort level (plus the account's rate limits) onto the pane's tmux window, where the client's top line shows 剩余 62% · Opus 5.5 · high on its right and the auto-handoff nudge reads the %. Opt-in at install time by pointing settings.json's statusLine at the live-install path, so it improves through land → /fleet-sync-install; jq-gated (inert without it). Never auto-wired. The fleet mod feeds the same script from inside the session (statusline.sh --from mod, issue #1459), so once every Claude window carries the mod the key can go — bin/fleet-statusline.sh off removes it (and the blank bottom row Claude Code keeps for any statusLine), refusing while a window would be left blind.Public architecture blueprint · 中文版 · Text version
Claude Code hooks (PreToolUse/PostToolUse/Stop/Notification)
│ instant, semantic-blind
▼
@claude_state on the tmux window ──► spinner daemon (0.12s frames, single
▲ writer, change-detected) ──► list glyphs
│ native state (OSC 7501) + needs tally
the agent's own status report
collector daemon (60s) ──► cache files ──► task list / top line / ⌘P panel
git · ctx tokens · (read-only producers, render instantly)
usage proxy
hub (tokenledger) ──► task records T<n> · placement · subscription pool · console
Design rules that made it work:
@claude_state; it is not required for recorded schedules, explicit waits or native pending requests.tmux source-file per frame = one repaint); a single collector owns every cache file; producers are read-only.Deeper reference: docs/dev/TERMS.md defines every term (what the collector, the hub and a task record actually are), docs/dev/ARCHITECTURE.md covers the shared-vs-per-fleet split and how several logins' fleets share one machine, and docs/dev/STATE.md traces how each window's Claude state (working/done/needs/looping) is set, rendered, and corrected. docs/dev/EMIT.md covers the optional, off-by-default emitter that POSTs session lifecycle facts (session → task → PR) so an external ledger can join what a week of agent work cost to what it produced — including the exact list of what does, and does not, leave the machine.
The installer is Claude itself — docs/dev/INSTALL.md is the playbook:
git clone https://github.com/verkyyi/claude-fleet.git
cd claude-fleet
claude "install claude-fleet on this machine"
Claude will check dependencies, copy the scripts to ~/.claude/fleet/, write your fleet.conf (first repo, main checkout, base branch), append one source line to ~/.tmux.conf, merge five hook entries into ~/.claude/settings.json, install the daemons (launchd on macOS, the systemd/ user units on Linux), and verify each piece — asking before it touches anything.
Prefer manual? Every step is in docs/dev/INSTALL.md; the pieces are plain shell scripts with no hidden state.
Running it on an unattended machine (a Mac mini you reach over SSH)? Read docs/dev/HOST.md — the host setup that keeps the machine busy only with its sessions: turning off Spotlight, the unattended-Mac checklist (never sleep, no Siri, no iCloud sync, no GUI apps on the console) and how much a container VM may take. fleet-doctor's host section checks each item; fleet-host-tune.sh plans them all (--apply asks per item).
The fleet's slash commands, the base skills/ tree and the hook table also install as a Claude Code plugin, served by a marketplace in this same repo:
claude plugin marketplace add verkyyi/claude-fleet
claude plugin install fleet@claude-fleet --scope user --yes
That replaces the copy-and-merge passes above for those three, and /plugin update fleet keeps them current — so on a second machine, or a teammate's, nobody has to remember /fleet-sync-install for them. Plugin commands are namespaced (/fleet:fleet-history); the fleet detects which install path a machine has and seeds the form that resolves, so spawns work either way. Codex does not consume Claude plugin commands directly; /fleet-sync-install generates native Codex skills from commands/*.md under each known $CODEX_HOME/skills/<name>/SKILL.md, so the same command becomes $fleet-history there.
It does not replace the playbook: bin/, conf/, the tmux layer and the daemons are machine-level and stay at ~/.claude/fleet. A plugin's install path is version-scoped and moves on every update, so nothing with a stable absolute path — a launchd unit, a tmux bind, a hook command — can point into it.
tmux ≥ 3.2 · fzf ≥ 0.59 (the node's pickers use --no-input) · gh (authed — only to push, open and merge PRs on a GitHub repo; a repo at any other git address, and a task with no repo, need none) · python3 · Claude Code (the claude CLI; also used by the sleep digest). Soft: perl Time::HiRes (sharper list spinner).
Run bin/fleet-doctor.sh to check all of these at once. Its install lines also answer "is this machine's live install current?" — the ~/.claude/fleet half is a hand-run git pull per machine, so it goes stale in silence (see bin/fleet-install-version.sh) — and "is each login still following refs/tags/stable on its own, and if not, why?" (see bin/fleet-install-follow.sh). (No standalone jq for the core — the collector only uses gh --jq, which is built in; jq is a soft dep only for the optional conf/statusline.sh status line, which exits silently without it.)
fleet opens the thin client. ⌘P in iTerm2, or F12 / ⌃] p on a phone or another terminal, opens the panel: choose a session, start a task, open its shell, or quit fleet. Tab on a row shows its actions. The panel and top bar run on the home machine (fleet_view.py, fleet-topbar.py --node, conf/tmux-view.conf). Your computer runs one foreground Python loop and one connection; closing it leaves the sessions running. See the client guide for key customization, phone controls and the completed sidebar migration checklist.
A direct node attach keeps tmux's stock keys. One fleet per login holds every repo you work on; the panel includes your sessions on other machines too.
conf/tmux-attention.conf also carries an opinionated fleet baseline the UX assumes so a clean install behaves consistently: mouse on, truecolor (default-terminal + a Tc terminal-overrides so the theme's hex colors render), escape-time 10 (snappy ESC in the Claude TUI), history-limit 50000, allow-rename/automatic-rename off (the fleet navigates by explicit window names), and the Tokyo-Night status / pane / message theme. Every line is documented inline and easy to override — put your own settings in ~/.tmux.conf after the source-file line (later wins) or comment the baseline out. Truly personal bits (prefix remaps, personal binds) are intentionally left in your ~/.tmux.conf.
One file, ~/.claude/fleet/fleet.conf (see fleet.conf.example; every key with its default and help is in conf/fleet.conf.reference):
FLEET_REPO="you/your-repo" # the first hosted repo: its code + PRs
FLEET_MAIN="$HOME/projects/your-repo" # worktrees are created as its siblings
FLEET_BASE_BRANCH="main"
FLEET_PROTECTED_RE="^(master|main|develop|test)$"
FLEET_CTX_WINDOW=200000 # 1000000 if you run 1M-context models
FLEET_GLOBAL_MAX_SESSIONS=0 # optional hard cap on live sessions; 0 (default) = the machine's admission decides
FLEET_AGENT="claude" # or "codex" — see the capability matrix below
A fleet ≡ a tmux session on its own tmux server, and a login runs exactly one (issues #977/#979/#980). Every repo that login works on lives in that one fleet — add them with bin/fleet-repo.sh add — so moving between repos is the task list's grouped rows, never a switch between fleets. There is no fleet picker.
Several fleets on one machine means several logins. Each login has its own ~/.config/claude-fleet/, its own fleet and its own tmux socket, so a crash in one never touches another. They share one collector without clobbering each other (see docs/dev/ARCHITECTURE.md). A repo you want isolated from the rest goes to a second login. A login that ended up with two fleets folds one into the other with bin/fleet-repo.sh fold (below).
fleet # open the client — the one way in (on this machine, or through the hub)
bin/fleet-up.sh you/webapp # first repo: clone-or-reuse ~/projects/webapp, bring the fleet up
bin/fleet-repo.sh add you/infra ~/src/infra # another repo in the same fleet (explicit checkout dir)
bin/fleet-list.sh # ● live / ○ down · name · repo · checkout (+ ↳ each further repo)
bin/fleet-down.sh fleet # kill the fleet after you type its name; `fleet up --undo` brings it back
bin/fleet-down.sh fleet --yes --purge # from a script, and drop its conf/cache too; checkouts stay
On SSH login, shell/fleet-intro.sh prints a short, phone-width banner: this login's fleet and its repo count, the fleet line to get in, and any machine-local intro.d lines — and then opens the client: an interactive SSH login runs bin/fleet, the same client you run on your own computer, here reading this machine (its bar says 客户端在 <机器> 上运行) — never a direct attach to the node's own session (issue #1711). scp / rsync / ssh host cmd are never touched; ~/.hushfleet-attach keeps the banner only. See docs/dev/INSTALL.md step 7 for the one ~/.zshrc line, source ~/.claude/fleet/shell/fleet-login.zsh.
Several repos in one fleet. From inside the fleet, bin/dash-repo-add.sh (issue #1103) opens a popup that asks just owner/name (a GitHub URL is fine) and adds it — so on an iPad nothing leaves the screen: the checkout is ~/projects/<name> (reused if it already is that repo, cloned if missing, the clone's progress in the popup), the verdict stays up until you dismiss it, and the new repo's heading is in the task list's next frame — no restart. The shell form, bin/fleet-repo.sh add you/infra [<checkout>], is the same registration (clone-or-reuse, like fleet-up.sh) and the one that takes a different checkout dir; list shows what it hosts and remove drops one. The rest follows on its own, as it does for the first repo: a warning if Claude Code has not trusted the checkout, and the background daemons woken so the list picks the repo up within a tick; fleet-doctor.sh's repos row lists every hosted repo and whether it is healthy. All hosted repos are equal — there is no main repo. Once a fleet hosts two:
@repo), shown in the task list as a repo heading / short-tag badge;$HOME;issue-12 never touches repo B's.Folding a fleet into another. bin/fleet-repo.sh fold <old-fleet> --into <fleet> --dry-run shows what would move; drop --dry-run to do it. The old fleet's repo and its per-repo settings become an overlay of <fleet> (a setting that only a fleet conf can hold is warned about, not carried). Every idle or finished session exits cleanly and resumes in <fleet> with the same conversation and folder. Busy sessions are left where they are, or moved as each one finishes with --wait. Once the old fleet is empty, its server goes down and its conf is archived under ~/.config/claude-fleet/archive/. It is never deleted.
bin/multirepo-e2e-selftest.sh proves the whole path end to end. One crash of the fleet's tmux server takes every repo in it down — and a login runs exactly one fleet (issue #979): fleet-up <owner/repo> / fleet repo add <owner/repo> with a fleet already configured ADDS the repo to it, and a second fleet is refused. A repo you want isolated needs a second login. A brand-new fleet is named fleet; an existing one keeps its name.
fleet is your one way into a fleet (issue #1711, EPIC #1710): the client, on your own computer or after an ssh login (the old cf helper, shell/cw.zsh, is gone — issue #4902). bin/fleet-attach.sh — a direct attach to the node's own session — still works for a script or a person who types it, but is no longer advertised.
Each fleet keeps its durable state in one directory per fleet — ~/.config/claude-fleet/fleets/<session>/ (its conf overlay, restore map), so ls ~/.config/claude-fleet/fleets/ is the list of running fleets (issue #181). The conf overlays the global fleet.conf, which still works as a one-fleet default. One settings file per login (issue #979): bin/fleet-settings.sh merge folds the install's fleet.conf and the fleet's conf into ~/.config/claude-fleet/fleet.settings (the conf keeps only FLEET_REPO/FLEET_MAIN/FLEET_BASE_BRANCH; the old files stay as *.pre-merge). Read order is install fleet.conf < fleet.settings < the fleet conf, so an unmerged login loads exactly as before. The config panel writes only the two layers you can tell apart — this fleet (a global-only key goes to fleet.settings, any other to the fleet conf) and a hosted repo — and never the install's fleet.conf, which it reads as legacy (issue #1102). A fleet's resting window is home, a plain shell the task list draws beside; nothing spawns a Claude session for you, and there is no resident orchestrator. Run your own claude in whatever window you like, or open an orchestrator session (spawn agent:orchestrator) to talk a request through and dispatch it. Workers land their own PRs on green (#441). The base checkout stays edit-read-only for every pane (hooks/base-readonly-guard.py), so an operator's session can drive the fleet without ever committing to it. Upgrading from the old flat layout is automatic — /fleet-sync-install runs bin/fleet-migrate-layout.sh once (idempotent; readers dual-read both layouts).
The optional Fleet Hub gives authorized Agents one MCP endpoint for Fleets on several machines, including SSH-connected hosts. It supports scoped status queries, worker starts, messaging / graceful stop / resume of a worker by a durable identity that survives handoffs and account migrations, limited configuration updates and persistent operation tracking. Nodes use a fixed SSH control entry point; existing workers continue if the Hub disconnects. A launchd installer runs a persistent Hub on macOS, with private HTTPS grant tokens or an OAuth HTTP deployment. See Fleet Hub setup and authorization.
A session does not choose its subscription. With the credential proxy on, every session opens with a session credential from this login's proxy, and the pool — the hub's subscriptions — picks which one each request runs on; a full subscription is the pool's to change, so the session keeps running where it is. With no pool, a session runs on the login's own login, exactly as before. This applies to Claude Code and Codex alike.
fleet account add --provider claude --label work # sign a subscription in, hand it to the hub
~/.claude/fleet/bin/fleet-account.sh whoami # which subscription THIS session is on
sh ~/.claude/fleet/bin/fleet-doctor.sh # credproxy / credsep / modelcap rows
Each session's own 剩余 % is on its window (the client's top line). A cap on one model is not the subscription's wall: the state-reconcile tick switches a walled session to FLEET_MODEL_FALLBACK (default opus) in place with /model, falling back to restart + resume when the flip cannot be verified.
The remote-start quota gate is separate and off by default:
# In fleet.conf; choose the subscription the gate should judge.
FLEET_QUOTA_GATE=1
FLEET_QUOTA_CEILING=90
# FLEET_QUOTA_ACCOUNT="<subscription-uuid>" # or "all"; unset uses ccquota's default
It gates only the starts and resumes the hub sends. Missing ccquota, an unreachable hub or an unreadable limit leaves the gate open; it is not a hard spending cap. Details: docs/dev/MULTI-ACCOUNT.md.
/skills)Optional repo-shipped Claude Code slash commands that operate on the current fleet (its $FLEET_REPO only), installed either as the plugin (typed /fleet:fleet-history) or by appending commands/*.md into ~/.claude/commands/ (typed /fleet-history). The same files are generated as Codex skills under $CODEX_HOME/skills/ and invoked as $fleet-history, $fleet-context, and so on. Each declares an owner seat (worker / hub / either) and refuses from the wrong one. Live so far:
brief tool, a PR, pr_verdict → pr_merge, report) rides its SessionStart hook (bin/fleet-worker-start-hook.sh, issue #4898); the cleanup daemon reaps afterwards (see docs/dev/CLEANUP.md)./fleet-history (hub) — browse & resume closed sessions (landed + unlanded, workers and scratch-<N> sessions) from the history ledger, reconstructing a reaped worktree off the recorded SHA so claude --resume still works./fleet-handoff (either) — bridge long-running work across a context-window boundary: write a durable handoff, then /clear and pick it up clean./fleet-sync-install (either, any fleet) — after claude-fleet's own PRs land, re-applies them to the shared live inhooks/register.ts 33 lines1// claude-fleet's in-session extension (issue #1335, EPIC #1334).
2//
3// This file only ASSEMBLES: one `register<Feature>(on)` line per feature file.
4// lifecycle.ts owns session.start / session.end (the version gate, the
5// heartbeat, and every feature's start-up work); gate.ts says how a feature's
6// own hooks stand behind the gate. Rules every feature keeps (EPIC #1334):
7// tmux window options stay the one state store (tmux.ts); no network, no gh —
8// local files via $.fs, the outside world via `$.process.run` of tmux and the
9// fleet's own scripts; every hook has a `.catch` that hands the event on, so a
10// broken mod never holds up a session.
11//
12// Loaded by bin/fleet-claude.sh (`--plugin-dir`) when FLEET_MOD is on (the
13// default). FLEET_MOD=0, or a Claude Code outside SUPPORTED, and every session
14// runs exactly as it did before the mod existed.
15
16import type { Register } from 'claude-code'
17
18import { registerAccept } from './accept'
19import { registerCompose } from './compose'
20import { registerLifecycle } from './lifecycle'
21import { registerState } from './state'
22import { registerTools } from './tools'
23import { registerUsage } from './usage'
24
25export const register: Register = on => {
26 registerLifecycle(on)
27 registerUsage(on)
28 registerState(on)
29 registerCompose(on)
30 registerTools(on)
31 registerAccept(on)
32}
33hooks/accept.ts 258 lines1// Conditional idle acceptance for a Claude session (issue #4618; Codex: #4617).
2//
3// fleet_runtime.accept_if_idle posts ONE request to the pane's inbox
4// (inbox.ts, fixed slot `idle-accept.json`, a nonce like runtime.v1):
5//
6// {"accept":"idle.v1","nonce":…,"launch":…,"delivery_id":…,
7// "expected_turn":…,"text":…,"deadline":…}
8//
9// and only an `accepted` answer carrying the turn that started is a delivery.
10// What the engine gives (verified on 2.1.295, bin/fleet-idle-accept-claude-selftest.py):
11//
12// - `$.prompt.submit` is a turn of its own once the session is idle, never
13// folded into a running one. Called while a turn runs, the prompt.submit
14// hooks run when it is dequeued, right before it enters — the entry boundary.
15// - a `prompt.submit` hook that answers `{ drop }` keeps it out: no turn, never
16// re-queued, and the call resolves `{ drop }`.
17// - while one prompt's chain runs, a person's Enter waits behind it.
18// - a `$` call made from a module TIMER skips every hook of this plugin, so the
19// submit is made from an engine frame instead: the inbox poll (a timer) bumps
20// an atom, and the band's redraw (`ui.render` AbovePrompt, raised by the
21// engine) makes the call, which this plugin's prompt.submit hook then sees.
22//
23// So: precheck in-process (lifecycle.ts), queue the slot, and at the entry
24// boundary check again — this request's own prompt, the last finished turn is
25// still `expected_turn` with no turn running and no session boundary since, the
26// prompt box holds no draft, the deadline has not passed. Any miss ⇒ `{ drop }`
27// ⇒ rejected. Passed ⇒ the receipt rides as hidden context
28// (`fleet idle-accept receipt delivery_id=<id>`), readable again in the
29// transcript after a disconnect, and the turn that starts is the receipt's.
30// A prompt this module handed to the engine that matches no live slot (a late
31// one, after its deadline) is dropped. Every other prompt passes untouched —
32// the same `plugin:fleet` origin also stamps the prompt a markdown command or
33// skill expands into when the inbox runs it with `$.command.run` (a handoff's
34// `/fleet-handoff pickup`, issue #4865), so the origin alone never decides.
35//
36// `idle.v2` (task HHV0, the session gate — bin/fleet_session_gate.py): the same
37// slot and the same entry check, with no launch context (C8 retired it — a window
38// is its ID) and no turn the caller must name. The fence is the conversation it
39// was taken in: no main turn running at the precheck and at entry, no session.end
40// (a /clear, a /resume) in between, no draft, before the deadline. A person's turn
41// that ran and finished in between does not refuse it — the gate's words are a
42// turn of their own after it, first come first in. `expected_turn`, when given,
43// still pins the last finished turn.
44//
45// Stopped (the gate's 停止 is an Esc): the engine puts an interrupted prompt back
46// in the box (verified on 2.1.295) — for the gate's own words that would be a
47// "draft" nobody typed, refusing every later sentence. When a turn this module
48// entered ends aborted, a box holding exactly its words is emptied; anything else
49// in the box is the person's and stays (state.ts's turn.complete does it: one
50// turn.complete hook a plugin).
51
52import { atom, read } from 'claude-code'
53import type { On, PromptSubmitResult } from 'claude-code'
54
55import { isOpen } from './gate'
56import { runtimeGen, runtimeIdle, runtimeIdleNow, runtimeLastTurn, runtimeTurnNow } from './state'
57
58export const ACCEPT = 'idle.v1'
59/** What a pane's `@mod_accept` says since task HHV0: the session gate's road. */
60export const ACCEPT_V2 = 'idle.v2'
61/** A submitted slot still unanswered this long past its deadline is unknown. */
62export const ACCEPT_GRACE_S = 3
63/** The receipt line's prefix in the hidden context. */
64export const RECEIPT_PREFIX = 'fleet idle-accept receipt delivery_id='
65
66export type AcceptRequest = {
67 version: 1 | 2
68 nonce: string
69 delivery_id: string
70 expected_turn: string
71 text: string
72 deadline: number
73}
74
75export type AcceptOutcome = {
76 state: 'accepted' | 'rejected' | 'unknown'
77 reason: string
78 nonce: string
79 delivery_id: string
80 turn_id?: string
81 previous_turn_id?: string
82}
83
84type Slot = AcceptRequest & { phase: 'queued' | 'submitted' | 'entered'; receipt: string; gen: number; outcome?: AcceptOutcome }
85
86/** Bumped by lifecycle.ts when a slot is queued; the band's redraw reads it. */
87const acceptKick = atom({ plugin: 'fleet', key: 'acceptKick' } as const, 0)
88
89// One slot per pane: the inbox runs one request at a time.
90let slot: Slot | undefined
91// The turns this module entered, by id → their words (a few, newest last).
92const entered = new Map<string, string>()
93
94/** state.ts's turn.complete: the words of a turn this module entered (once), else undefined. */
95export function takeEntered(turnId: string): string | undefined {
96 const t = entered.get(turnId)
97 entered.delete(turnId)
98 return t
99}
100// Texts this module passed to `$.prompt.submit` whose call has not resolved yet:
101// the only prompts the entry hook may claim (and drop).
102const handed = new Map<string, number>()
103
104function hand(text: string, d: 1 | -1): void {
105 const n = (handed.get(text) ?? 0) + d
106 if (n > 0) handed.set(text, n)
107 else handed.delete(text)
108}
109
110const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
111
112/** A request's fields, or why it cannot run. `context` is FLEET_LAUNCH_CONTEXT. */
113export function parseAccept(request: Record<string, unknown>, context: string | undefined, now: number): AcceptRequest | { error: string } {
114 const version = request.accept === ACCEPT ? 1 : request.accept === ACCEPT_V2 ? 2 : 0
115 if (version === 0) return { error: 'unsupported accept' }
116 if (version === 1) {
117 let launch: Record<string, unknown> | undefined
118 try { launch = context ? JSON.parse(context) as Record<string, unknown> : undefined } catch { launch = undefined }
119 const expected = request.launch as Record<string, unknown> | undefined
120 if (!isOpen() || !launch || !expected || typeof expected !== 'object'
121 || Object.keys(launch).length !== Object.keys(expected).length
122 || !Object.keys(launch).every(k => launch?.[k] === expected[k])) return { error: 'launch_changed' }
123 } else if (!isOpen()) return { error: 'closed' }
124 const { nonce, delivery_id: id, text, deadline } = request
125 const turn = version === 2 && request.expected_turn === undefined ? '' : request.expected_turn
126 if (typeof nonce !== 'string' || !/^[a-f0-9]{32}$/.test(nonce)
127 || typeof id !== 'string' || !UUID.test(id)
128 || typeof turn !== 'string' || (turn === '' && version === 1) || turn.length > 200
129 || typeof text !== 'string' || text === '' || text.length > 65536
130 || typeof deadline !== 'number' || !Number.isFinite(deadline)) return { error: 'invalid_request' }
131 if (now >= deadline || deadline - now > 30) return { error: 'expired' }
132 return { version, nonce, delivery_id: id, expected_turn: turn, text, deadline }
133}
134
135function outcome(r: AcceptRequest, state: AcceptOutcome['state'], reason: string, turn?: string): AcceptOutcome {
136 return { state, reason, nonce: r.nonce, delivery_id: r.delivery_id,
137 ...(turn ? { turn_id: turn, previous_turn_id: r.expected_turn } : {}) }
138}
139
140function settle(s: Slot, o: AcceptOutcome): void {
141 if (s.outcome === undefined) s.outcome = o
142}
143
144/** The durable receipt beside the inbox, read again after a disconnect. */
145export function receiptPath(inbox: string, id: string): string {
146 return `${inbox}/idle-accept-${id}.receipt`
147}
148
149/** lifecycle.ts: refuse before anything is queued, or take the one slot. */
150export function beginAccept(r: AcceptRequest, inbox: string): AcceptOutcome | undefined {
151 if (slot !== undefined) return outcome(r, 'rejected', 'slot_busy')
152 if (!(r.version === 2 ? runtimeIdleNow(r.expected_turn) : runtimeIdle(r.expected_turn))) {
153 return outcome(r, 'rejected', 'precheck_not_idle')
154 }
155 // v2: the turn it follows is whichever finished last ('' before any) — the
156 // entered turn is told apart from it, and it is the receipt's previous_turn_id
157 const anchor = r.version === 2 ? runtimeLastTurn() : r.expected_turn
158 slot = { ...r, expected_turn: anchor, phase: 'queued', receipt: receiptPath(inbox, r.delivery_id), gen: runtimeGen() }
159 return undefined
160}
161
162/** lifecycle.ts, each wait step: the slot's answer once there is one (and the slot freed). */
163export function acceptOutcome(r: AcceptRequest, now: number): AcceptOutcome | undefined {
164 const s = slot
165 if (s === undefined || s.nonce !== r.nonce) return outcome(r, 'unknown', 'slot_lost')
166 let o = s.outcome
167 // Never submitted by the deadline: nothing was handed to the engine.
168 if (o === undefined && s.phase === 'queued' && now >= s.deadline) o = outcome(r, 'rejected', 'not_submitted')
169 // Handed over and unanswered: a late arrival is dropped (no live slot).
170 if (o === undefined && now >= s.deadline + ACCEPT_GRACE_S) o = outcome(r, 'unknown', 'entry_unanswered')
171 if (o !== undefined) slot = undefined
172 return o
173}
174
175/** session.end (lifecycle.ts): a queued slot never goes into the next conversation. */
176export function acceptSessionEnded(): void {
177 if (slot !== undefined && slot.phase === 'queued') settle(slot, outcome(slot, 'rejected', 'session_ended'))
178}
179
180/** Why this prompt may not enter now, or '' — synchronous, after every await. */
181export function entryRefusal(s: Slot, draft: string, now: number): string {
182 if (slot !== s) return 'slot_lost'
183 if (now >= s.deadline) return 'deadline_passed'
184 if (s.version === 2 && s.gen !== runtimeGen()) return 'session_changed'
185 if (!(s.version === 2 ? runtimeIdleNow() : runtimeIdle(s.expected_turn))) return 'not_idle_at_entry'
186 if (draft.trim() !== '') return 'draft_present'
187 return ''
188}
189
190/** This module's own submit: fleet's origin AND a text it handed over and is still waiting on. */
191function ours(e: { text: string; origin?: { kind: string; name?: string } }): boolean {
192 return e.origin?.kind === 'plugin' && e.origin.name === 'fleet' && handed.has(e.text)
193}
194
195export function registerAccept(on: On): void {
196 // The engine frame that makes the call (see the header): one redraw per kick.
197 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
198 await read($, acceptKick)
199 const s = slot
200 if (!isOpen() || s === undefined || s.phase !== 'queued') return next(e)
201 s.phase = 'submitted'
202 hand(s.text, 1)
203 // Once the entry hook passed it on, that hook alone names the outcome.
204 $.prompt.submit({ text: s.text, asUser: true }).then(
205 (r: PromptSubmitResult) => {
206 hand(s.text, -1)
207 if (r.drop !== undefined) settle(s, outcome(s, 'rejected', 'dropped'))
208 else if (s.phase !== 'entered') settle(s, outcome(s, 'unknown', 'entry_unreviewed'))
209 },
210 () => { hand(s.text, -1); if (s.phase !== 'entered') settle(s, outcome(s, 'unknown', 'submit_failed')) })
211 return next(e)
212 }).catch(($, e, next) => next(e))
213
214 on('prompt.submit', async ($, e, next) => {
215 if (!isOpen() || !ours(e)) return next(e)
216 const s = slot
217 if (s === undefined || s.phase !== 'submitted' || s.text !== e.text || s.outcome !== undefined) {
218 return { drop: 'fleet idle-accept: no live request' }
219 }
220 const draft = (await $.prompt.read()).text
221 const now = (await $.clock.now()) / 1000
222 const why = entryRefusal(s, draft, now)
223 if (why !== '') {
224 settle(s, outcome(s, 'rejected', why))
225 return { drop: `fleet idle-accept: ${why}` }
226 }
227 s.phase = 'entered'
228 const r = await next({ ...e, context: [...(e.context ?? []), RECEIPT_PREFIX + s.delivery_id] })
229 if (r.drop !== undefined) {
230 settle(s, outcome(s, 'rejected', 'dropped_beneath'))
231 return r
232 }
233 // state.ts's turn.start hook names the turn that began with this prompt.
234 let turn = runtimeTurnNow()
235 for (let i = 0; i < 40 && (turn === undefined || turn === s.expected_turn); i++) {
236 await $.clock.sleep(50)
237 turn = runtimeTurnNow()
238 }
239 const o = turn !== undefined && turn !== s.expected_turn
240 ? outcome(s, 'accepted', 'native_entry', turn)
241 : outcome(s, 'unknown', 'turn_unobserved')
242 if (o.state === 'accepted') {
243 if (o.turn_id) {
244 entered.set(o.turn_id, s.text)
245 if (entered.size > 8) entered.delete(entered.keys().next().value as string)
246 }
247 try {
248 await $.fs.write(s.receipt, `${JSON.stringify({ ...o, nonce: undefined, accepted_at: (await $.clock.now()) / 1000 })}\n`)
249 } catch {
250 // The hidden-context line in the transcript still names the delivery.
251 }
252 }
253 settle(s, o)
254 return r
255 }).catch(($, e, next) => (next.called ? next(e) : ours(e) ? { drop: 'fleet idle-accept: guard failed' } : next(e)))
256
257}
258hooks/compose.ts 29 lines1// The mod's sections of the system prompt — ONE `prompt.compose` hook (the
2// engine takes one unmatched hook per event per plugin). Each feature keeps its
3// own text and state; this hook only puts them after the engine's own:
4//
5// fleet:where where the person is (where.ts, #1716)
6//
7// The orchestrator's role section (#2582) left with the resident seat (#3118):
8// the mod adds no role to any session's prompt.
9//
10// Nothing to add (gate shut, no line yet) passes the engine's through.
11
12import type { On, PromptComposeSection } from 'claude-code'
13
14import { isOpen } from './gate'
15import { WHERE_SECTION, currentWhere, whereSection } from './where'
16
17export function registerCompose(on: On): void {
18 on('prompt.compose', async ($, e, next) => {
19 const r = await next(e)
20 if (!isOpen()) return r
21 const where = currentWhere()
22 const ours: PromptComposeSection[] = []
23 if (where !== undefined) ours.push(whereSection(where))
24 if (ours.length === 0) return r
25 const ids = new Set([WHERE_SECTION])
26 return { sections: [...r.sections.filter(s => !ids.has(s.id)), ...ours] }
27 }).catch(($, e, next) => next(e))
28}
29hooks/lifecycle.ts 333 lines1// The session's lifecycle: the version gate and the heartbeat (issue #1335).
2//
3// The engine takes ONE unmatched `session.start` (and `session.end`) hook per
4// plugin, and follows `$` only within the file it is spelled in — so start-up
5// work for every feature lives in THIS file's start hook, behind the gate.
6// A feature that needs to start something (a timer, a first write) adds it
7// to `onReady` below; its other hooks live in its own file and start with
8// `if (!isOpen()) return next(e)` (gate.ts).
9//
10// Gate: out of SUPPORTED (version.ts), nothing past the gate runs and the
11// window says `@mod_state off:version`; in range, `@mod_state on`.
12//
13// Heartbeat: while the session lives, its window carries `@mod_alive <epoch
14// seconds>`, rewritten every HEARTBEAT_MS. Bash reads it with `fleet_mod_alive
15// <win>` (bin/fleet-lib.sh): fresh within 45s = the mod is here, take the new
16// path; stale or missing = take today's path. The timer lives in the module,
17// not the session: a /clear ends the session (`session.end`, reason `clear`)
18// and fires no new `session.start`, but the module and its timers go on — so
19// the beat survives a handoff's /clear. A real exit unsets it at once.
20//
21// Inbox (issue #1337): the same module also polls the pane's command inbox every
22// INBOX_MS and runs what bash posted there with `$.command.run` (inbox.ts) — on a
23// module timer for the same reason: the pickup a handoff posts right after its
24// /clear must still be taken.
25//
26// Accept (issue #4618; idle.v2 task HHV0): an `idle.v1` / `idle.v2` request on the same inbox is accept.ts's —
27// the precheck and the wait run here, the submit and its entry check there.
28//
29// Where (issue #1716): the same module reads bin/fleet-client-where.sh at the
30// start and every WHERE_POLL_MS; where.ts puts the line in the context.
31//
32// The orchestrator's role section (#2582), its band strings and its queue count
33// (#2617) left with the resident seat (issue #3118): nothing here reads a role.
34//
35// Panels (issue #2835) — the decision sheet, the patrol, the batches — are gone
36// (issue #4339); this mod starts none.
37//
38// Tools (issue #2057): a session the launcher gave no fleet tool service (no
39// FLEET_MCP_SERVER=1 — launched before #1828) gets the mod's three fallback tools
40// at the start, from the service's own specs (tools.ts); a served session gets
41// none — status / spawn / await are the service's there.
42
43import { atom, update } from 'claude-code'
44import type { EngineInterface, On, Timer, ToolSpec } from 'claude-code'
45
46import type { FleetModStatus } from '../types'
47import { isOpen, openGate } from './gate'
48import { INBOX_MS, inboxDir, pollInbox, pollNativeCancel } from './inbox'
49import type { InboxIo } from './inbox'
50import { TMUX_TIMEOUT_MS, windowOptionsArgv } from './tmux'
51import { SPEC_TIMEOUT_MS, binDir, fallbackSpecs, specArgv } from './tools'
52import { MODEL_POLL_MS, STATUSLINE_TIMEOUT_MS, claimModelFeed, feedArgv, modelMoved, resetModelFeed } from './usage'
53import { MOD_VERSION, isSupported } from './version'
54import { WHERE_POLL_MS, WHERE_TIMEOUT_MS, takeWhere, whereArgv } from './where'
55import { noteSessionBoundary, runtimeQuery, runtimeIdleNow, runtimeGen, WRITE_TIMEOUT_MS } from './state'
56import { ACCEPT_V2, acceptOutcome, acceptSessionEnded, beginAccept, parseAccept } from './accept'
57import { cancelNative } from './native-cancel'
58
59export const HEARTBEAT_MS = 15_000
60
61/** Exits that end the process (a `clear` or `resume` keeps it beating). */
62const EXITS = new Set(['prompt_input_exit', 'logout', 'other'])
63
64const status = atom({ plugin: 'fleet', key: 'status' } as const, null as FleetModStatus | null)
65// accept.ts's own ref: bumping it redraws the band, whose hook submits the slot.
66const acceptKick = atom({ plugin: 'fleet', key: 'acceptKick' } as const, 0)
67
68// Module state: a reload is a fresh module, and session.start fires again.
69let timer: Timer | undefined
70let inboxTimer: Timer | undefined
71let modelTimer: Timer | undefined
72let whereTimer: Timer | undefined
73let whereBusy = false
74let inboxBusy = false
75let cancelBusy = false
76let pane: string | undefined
77let inbox: string | undefined
78
79async function setOptions($: EngineInterface, options: Record<string, string | null>): Promise<void> {
80 if (pane === undefined) return
81 const argv = windowOptionsArgv(pane, options)
82 if (argv !== null) await $.process.run(argv, { timeoutMs: TMUX_TIMEOUT_MS })
83}
84
85async function beat($: EngineInterface): Promise<void> {
86 try {
87 await setOptions($, { '@mod_alive': String(Math.floor((await $.clock.now()) / 1000)) })
88 } catch {
89 // A missed beat ages the option out; the bash side falls back on its own.
90 }
91}
92
93function inboxIo($: EngineInterface): InboxIo {
94 return {
95 list: async dir => (await $.fs.list(dir)).filter(f => f.kind === 'file').map(f => f.name),
96 read: path => $.fs.read(path),
97 write: (path, text) => $.fs.write(path, text),
98 claim: async (from, to) => {
99 const r = await $.process.run(['mv', from, to], { timeoutMs: TMUX_TIMEOUT_MS })
100 return r.exitCode === 0
101 },
102 run: async (command, args) => {
103 await $.command.run({ command, args })
104 },
105 cancel: async request => {
106 // No capability is advertised. Stop orchestration must still preserve
107 // the root long enough to use this bounded, opt-in durable-plan road.
108 if (!isOpen() || (await $.session.version()).version !== '2.1.295') {
109 return { ok: false, state: 'refused', reason: 'unsupported_native_version' }
110 }
111 return cancelNative({
112 now: async () => (await $.clock.now()) / 1000,
113 sleep: milliseconds => $.clock.sleep(milliseconds),
114 session: () => $.session.id(),
115 generation: runtimeGen,
116 verify: async (req, ids, expected) => {
117 const payload = { request: req, ids, expected,
118 session_id: await $.session.id(), project: await $.session.cwd() }
119 const remaining = req.deadline * 1000 - await $.clock.now()
120 if (remaining <= 0) throw new Error('cancel deadline expired')
121 const result = await $.process.run(['python3', `${$.plugin.root}/../../bin/fleet_native_cancel.py`], {
122 stdin: JSON.stringify(payload), timeoutMs: Math.max(1, Math.min(500, remaining)),
123 })
124 if (result.exitCode !== 0) throw new Error('durable ownership unavailable or changed')
125 return JSON.parse(result.stdout)
126 },
127 call: async input => await $.tool.call(input) as Record<string, unknown>,
128 }, request)
129 },
130 query: async request => {
131 if (request.query === 'park.v1') {
132 const now = (await $.clock.now()) / 1000
133 if (!isOpen() || typeof request.deadline !== 'number' || now >= request.deadline
134 || request.deadline - now > 5) return { ok: false, why: 'expired' }
135 if (!runtimeIdleNow()) return { ok: false, why: 'busy' }
136 if ((await $.prompt.read()).text !== '') return { ok: false, why: 'draft' }
137 return { ok: runtimeIdleNow(), why: runtimeIdleNow() ? '' : 'busy' }
138 }
139 const context = await $.env.get('FLEET_LAUNCH_CONTEXT')
140 const payload = runtimeQuery(request, context, (await $.clock.now()) / 1000)
141 const r = await $.process.run(['python3', `${$.plugin.root}/../../bin/fleet_runtime.py`, 'event'], {
142 stdin: JSON.stringify(payload), timeoutMs: WRITE_TIMEOUT_MS,
143 })
144 if (r.exitCode !== 0) throw new Error('native runtime observation refused')
145 },
146 // Conditional idle acceptance (accept.ts): refused at once, or the slot
147 // queued and the band's redraw kicked; waits for the entry boundary's answer.
148 accept: async request => {
149 const parsed = parseAccept(request, await $.env.get('FLEET_LAUNCH_CONTEXT'), (await $.clock.now()) / 1000)
150 if ('error' in parsed) throw new Error(parsed.error)
151 if (inbox === undefined) throw new Error('no inbox')
152 const refused = beginAccept(parsed, inbox)
153 if (refused !== undefined) return refused
154 await update($, acceptKick, n => n + 1)
155 for (;;) {
156 const o = acceptOutcome(parsed, (await $.clock.now()) / 1000)
157 if (o !== undefined) return o
158 await $.clock.sleep(50)
159 }
160 },
161 }
162}
163
164// The model poll (usage.ts explains it; the timer and `$` live here because the
165// engine follows `$` only within one file): when the live model is not the one
166// last fed, feed it alone through conf/statusline.sh, so a `/model` with no turn
167// yet still flips @model within MODEL_POLL_MS (fleet-model-switch's verify).
168async function pollModel($: EngineInterface): Promise<void> {
169 if (pane === undefined) return
170 let fields: string[] | null = null
171 try {
172 const id = await $.session.model()
173 if (!modelMoved(id)) return
174 fields = claimModelFeed(id, undefined)
175 if (fields === null) return
176 await $.process.run(feedArgv($.plugin.root, fields), { timeoutMs: STATUSLINE_TIMEOUT_MS })
177 } catch {
178 if (fields !== null) resetModelFeed() // the next tick or turn feeds it again
179 }
180}
181
182// Where the person is (where.ts): one read at a time, a failed one keeps the line.
183async function pollWhere($: EngineInterface): Promise<void> {
184 // A session outside tmux is no fleet session: there is no one to place.
185 if (whereBusy || pane === undefined) return
186 whereBusy = true
187 try {
188 const r = await $.process.run(whereArgv($.plugin.root), { timeoutMs: WHERE_TIMEOUT_MS })
189 takeWhere(r.exitCode, r.stdout)
190 } catch {
191 // The next tick reads it again.
192 } finally {
193 whereBusy = false
194 }
195}
196
197async function pollOnce($: EngineInterface): Promise<void> {
198 // One command at a time: a /compact can hold its run for a minute, and the
199 // next one waits its turn behind it rather than racing it.
200 if (inboxBusy || inbox === undefined) return
201 inboxBusy = true
202 try {
203 await pollInbox(inboxIo($), inbox)
204 } catch {
205 // A failed poll is retried on the next tick; the poster times out on its own.
206 } finally {
207 inboxBusy = false
208 }
209}
210
211async function pollCancelOnce($: EngineInterface): Promise<void> {
212 if (cancelBusy || inbox === undefined) return
213 cancelBusy = true
214 try {
215 await pollNativeCancel(inboxIo($), inbox)
216 } catch {
217 // A missing request is normal; failed receipt writes remain unconfirmed.
218 } finally {
219 cancelBusy = false
220 }
221}
222
223// The fallback tools (tools.ts explains them; the run is here because the engine
224// follows `$` only within one file): the specs from the service itself; a spec
225// read that fails registers nothing (an old session's list already carries them),
226// and one tool that will not register costs that tool only, never the session.
227async function registerFallbackTools($: EngineInterface): Promise<void> {
228 let specs: ToolSpec[]
229 try {
230 const r = await $.process.run(specArgv(binDir($.plugin.root)), { timeoutMs: SPEC_TIMEOUT_MS })
231 if (r.exitCode !== 0) return
232 specs = fallbackSpecs(r.stdout)
233 } catch {
234 return
235 }
236 for (const spec of specs) {
237 try {
238 await $.tool.register(spec)
239 } catch {
240 // Already listed (a reload), or refused: this tool only.
241 }
242 }
243}
244
245/** Start-up work of every feature, run once the gate is open. */
246async function onReady($: EngineInterface): Promise<void> {
247 // The fallback tools (tools.ts, issue #2057) — only for a fleet session the
248 // launcher did not give the tool service: FLEET_MCP_SERVER=1 says it did (issue
249 // #1807), and then the mod registers nothing (#1812). Without it, advertise
250 // status and spawn from the service's schemas. The tools.ts handler still
251 // answers cached await calls with the service's explicit retirement refusal.
252 if (pane !== undefined && (await $.env.get('FLEET_MCP_SERVER')) !== '1') await registerFallbackTools($)
253 await beat($)
254 timer?.cancel()
255 timer = $.clock.every(HEARTBEAT_MS, () => {
256 void beat($)
257 })
258 // The model on the bus from the first second, and a /model within ~2 s (#1459).
259 resetModelFeed()
260 await pollModel($)
261 modelTimer?.cancel()
262 modelTimer = $.clock.every(MODEL_POLL_MS, () => {
263 void pollModel($)
264 })
265 const home = (await $.env.get('HOME')) ?? ''
266 const conf = (await $.env.get('FLEET_CONF_DIR')) || `${home}/.config/claude-fleet`
267 const tmux = await $.env.get('TMUX')
268 // Where the person is, in the context from the first request (#1716).
269 await pollWhere($)
270 whereTimer?.cancel()
271 whereTimer = $.clock.every(WHERE_POLL_MS, () => {
272 void pollWhere($)
273 })
274 inbox = inboxDir(conf, tmux, pane)
275 inboxTimer?.cancel()
276 inboxTimer = inbox === undefined ? undefined : $.clock.every(INBOX_MS, () => {
277 void pollCancelOnce($)
278 void pollOnce($)
279 })
280}
281
282export function registerLifecycle(on: On): void {
283 on('session.start', async ($, e, next) => {
284 const { version } = await $.session.version()
285 const supported = isSupported(version)
286 const state = supported ? 'on' : 'off:version'
287 const id = await $.env.get('TMUX_PANE')
288 pane = id !== undefined && id !== '' ? id : undefined
289 await update($, status, () => ({ state, engine: version, mod: MOD_VERSION }))
290 await setOptions($, {
291 '@mod_state': state,
292 '@mod_ver': MOD_VERSION,
293 // the session gate (bin/fleet_session_gate.py) offers a Claude pane only
294 // what its mod answers: idle.v2 (idle.v1, still taken, needs a launch context)
295 '@mod_accept': supported ? ACCEPT_V2 : null,
296 // Out of range never beats: clear one a previous load left behind.
297 ...(supported ? {} : { '@mod_alive': null }),
298 })
299 if (supported) {
300 openGate()
301 await onReady($)
302 // not on a wake out of a park (task EQBE): the resumed screen stays the conversation's
303 if (e.isInteractive && (await $.env.get('FLEET_PARK_RESUME')) !== '1') {
304 $.ui.toast(`fleet 扩展已加载 · v${MOD_VERSION}`)
305 }
306 }
307 return next(e)
308 }).catch(($, e, next) => next(e))
309
310 on('session.end', async ($, e, next) => {
311 if (isOpen()) {
312 // A /clear or /resume: no earlier turn is the one a conditional prompt follows.
313 noteSessionBoundary()
314 acceptSessionEnded()
315 }
316 if (isOpen() && EXITS.has(e.reason)) {
317 timer?.cancel()
318 timer = undefined
319 inboxTimer?.cancel()
320 inboxTimer = undefined
321 modelTimer?.cancel()
322 modelTimer = undefined
323 whereTimer?.cancel()
324 whereTimer = undefined
325 await setOptions($, {
326 '@mod_alive': null,
327 '@mod_accept': null,
328 })
329 }
330 return next(e)
331 }).catch(($, e, next) => next(e))
332}
333hooks/state.ts 223 lines1// The session reports its own state (issue #1336, EPIC #1334 C2).
2//
3// Until now `@claude_state` came from settings hooks (PreToolUse / PostToolUse /
4// Stop / Notification) plus a screen classifier that read the pane with a model
5// call to tell `done` from "waiting on you" and "a Loop is pending". The engine
6// knows all three outright, so the mod says them as they happen:
7//
8// turn.start → working
9// turn.complete → done, or `looping` when @loop says a Loop is pending
10// tool.call AskUserQuestion → needs/ask while the question is open, working after
11// tool.call ScheduleWakeup | CronCreate | CronDelete → @loop, after the call
12//
13// Every write goes through the fleet's own writers, never a tmux call of ours:
14// bin/set-claude-state.sh (`--via mod`: the state write alone — the Stop hook keeps
15// the auto-handoff / compaction / parent-report side of a clean stop) and
16// bin/fleet_loop_mark.py's PostToolUse entry, fed the same payload the hook gets, so
17// whichever of the two writers arrives first, @loop reads the same. The settings
18// hooks are not removed: they still fire, and write the same values.
19//
20// (The screen classifier that stood down for a live mod retired with issue #2543.)
21// Subagent turns and calls (`agentId`) are not this pane's state and are passed straight on.
22
23import type { EngineInterface, On } from 'claude-code'
24
25import { takeEntered } from './accept'
26import { isOpen } from './gate'
27
28/** How long one fleet-script write may take before it is abandoned. */
29export const WRITE_TIMEOUT_MS = 10_000
30
31const LOOP_TOOLS = new Set(['ScheduleWakeup', 'CronCreate', 'CronDelete'])
32
33// Only accepted C3 executions publish observations. Old sessions keep their
34// display hooks; missing turn/native identity means unknown to the reader.
35let runtimeSequence = 0
36let runtimeTurn: string | undefined
37let runtimeObservation: { state: string; turn_id: string } | undefined
38// A session.end (a /clear, a /resume) since the last turn: that turn's id no
39// longer names the conversation a prompt would enter (accept.ts, #4618).
40let runtimeBoundary = false
41// Bumped by every session.end: an idle.v2 request (accept.ts, the session gate)
42// enters only into the conversation it was taken in.
43let runtimeGeneration = 0
44
45/** The last main turn finished as `expected` (idle), none runs, no session boundary since. */
46export function runtimeIdle(expected: string): boolean {
47 return runtimeTurn === undefined && !runtimeBoundary && runtimeObservation?.turn_id === expected
48 && runtimeObservation.state === 'idle'
49}
50
51/** idle.v2: no main turn runs now (and, when `expected` is given, the last one
52 * finished is that one — idle or interrupted alike: a stopped turn is idle too). */
53export function runtimeIdleNow(expected = ''): boolean {
54 return runtimeTurn === undefined && (expected === '' || runtimeObservation?.turn_id === expected)
55}
56
57/** The last main turn this module saw finish or start, '' before any. */
58export function runtimeLastTurn(): string {
59 return runtimeObservation?.turn_id ?? ''
60}
61
62/** The conversation generation: one more per session.end (a /clear, a /resume). */
63export function runtimeGen(): number {
64 return runtimeGeneration
65}
66
67/** The main turn running now, as turn.start named it. */
68export function runtimeTurnNow(): string | undefined {
69 return runtimeTurn
70}
71
72/** lifecycle.ts session.end: no earlier turn is the one a prompt would follow. */
73export function noteSessionBoundary(): void {
74 runtimeBoundary = true
75 runtimeGeneration++
76}
77
78/** An on-demand reply from this native module, never a renewed disk cache. */
79export function runtimeQuery(request: Record<string, unknown>, context: string | undefined, now: number): Record<string, unknown> {
80 const launch = context ? JSON.parse(context) as Record<string, unknown> : undefined
81 const expected = request.launch as Record<string, unknown> | undefined
82 if (!isOpen() || !launch || !expected || typeof expected !== 'object'
83 || Object.keys(launch).length !== Object.keys(expected).length
84 || !Object.keys(launch).every(k => launch[k] === expected[k]) || !runtimeObservation
85 || typeof request.nonce !== 'string' || !/^[a-f0-9]{32}$/.test(request.nonce)
86 || typeof request.deadline !== 'number' || now >= request.deadline || request.deadline - now > 5) {
87 throw new Error('runtime query unavailable or expired')
88 }
89 return { ...runtimeObservation, start: false, sequence: ++runtimeSequence,
90 observed_at: now, query_id: request.nonce }
91}
92
93async function runtimeEvent($: EngineInterface, state: string, turn: string | undefined, start = false): Promise<void> {
94 // Allocate at the native edge, before any await can reorder publishers.
95 const sequence = ++runtimeSequence
96 if (turn && (start || (runtimeObservation?.turn_id === turn
97 && !['idle', 'interrupted'].includes(runtimeObservation.state)))) runtimeObservation = { state, turn_id: turn }
98 try {
99 if (!turn || !(await $.env.get('FLEET_LAUNCH_CONTEXT'))) return
100 const bin = await fleetBin($)
101 if (bin === undefined) return
102 const payload = { state, turn_id: turn, start, sequence,
103 observed_at: (await $.clock.now()) / 1000 }
104 await $.process.run(['python3', `${bin}/fleet_runtime.py`, 'event'], {
105 stdin: JSON.stringify(payload), timeoutMs: WRITE_TIMEOUT_MS,
106 })
107 } catch {
108 // An absent/failed observation expires; it never authorizes an action.
109 }
110}
111
112/** The fleet's bin/ beside this plugin (<install>/mod/fleet → <install>/bin), or
113 * undefined outside tmux, where there is no window to write. */
114async function fleetBin($: EngineInterface): Promise<string | undefined> {
115 const pane = await $.env.get('TMUX_PANE')
116 if (pane === undefined || pane === '') return undefined
117 return `${$.plugin.root}/../../bin`
118}
119
120/** `set-claude-state.sh --via mod <verb>`; a failed write leaves the hooks' value.
121 * `stdin`: the hook payload's shape, for a verb that reads one (`ask`'s question). */
122async function setState($: EngineInterface, verb: 'working' | 'done' | 'ask', stdin = ''): Promise<void> {
123 try {
124 const bin = await fleetBin($)
125 if (bin === undefined) return
126 await $.process.run(['sh', `${bin}/set-claude-state.sh`, '--via', 'mod', verb], {
127 stdin,
128 timeoutMs: WRITE_TIMEOUT_MS,
129 })
130 } catch {
131 // The settings hooks still write the same state; nothing to undo.
132 }
133}
134
135/** Hand fleet_loop_mark.py the PostToolUse payload of a Loop tool call. */
136async function markLoop($: EngineInterface, payload: Record<string, unknown>): Promise<void> {
137 try {
138 const bin = await fleetBin($)
139 if (bin === undefined) return
140 await $.process.run(['python3', `${bin}/fleet_loop_mark.py`, 'hook'], {
141 stdin: JSON.stringify(payload),
142 timeoutMs: WRITE_TIMEOUT_MS,
143 })
144 } catch {
145 // The PostToolUse hook writes the same @loop.
146 }
147}
148
149/** The tool's own arguments: the call's input minus the envelope keys. */
150function toolInput(e: Record<string, unknown>): Record<string, unknown> {
151 const { tool: _t, tool_use_id: _id, agentId: _a, consent: _c, ...rest } = e
152 return rest
153}
154
155export function registerState(on: On): void {
156 on('turn.start', async ($, e, next) => {
157 if (isOpen()) {
158 if ((e as { agentId?: string }).agentId === undefined) {
159 runtimeTurn = e.turnId
160 runtimeBoundary = false
161 await runtimeEvent($, 'active', e.turnId, true)
162 }
163 await setState($, 'working')
164 }
165 return next(e)
166 }).catch(($, e, next) => next(e))
167
168 on('turn.complete', async ($, e, next) => {
169 const result = await next(e)
170 // set-claude-state.sh's done branch turns this into `looping` when @loop (or a
171 // loop ledger) says a Loop is pending — the one place that decides it.
172 if (isOpen() && e.agentId === undefined) {
173 await runtimeEvent($, e.isAborted || e.reason !== 'answer' ? 'interrupted' : 'idle', e.turnId)
174 if (runtimeTurn === e.turnId) runtimeTurn = undefined
175 await setState($, 'done')
176 // the session gate's own words, stopped (accept.ts): the engine puts them back
177 // in the box — not a draft; the person's own text in it is never touched
178 const gate = takeEntered(e.turnId)
179 if (gate !== undefined && (e.isAborted || e.reason !== 'answer')) {
180 try {
181 for (let i = 0; i < 20; i++) {
182 const box = (await $.prompt.read()).text
183 if (box.trim() === gate.trim()) { await $.prompt.fill({ text: '', mode: 'replace' }); break }
184 if (box.trim() !== '') break
185 await $.clock.sleep(50)
186 }
187 } catch {
188 // the box keeps it: the gate then reads it as typing until a person clears it
189 }
190 }
191 }
192 return result
193 }).catch(($, e, next) => next(e))
194
195 on('tool.call', { tool: 'AskUserQuestion' }, async ($, e, next) => {
196 if (!isOpen() || e.agentId !== undefined) return next(e)
197 const turn = runtimeTurn
198 await runtimeEvent($, 'ask', turn)
199 // The question's own words ride along (issue #1951): @claude_needs_detail.
200 await setState($, 'ask', JSON.stringify({ tool_name: 'AskUserQuestion', tool_input: toolInput(e) }))
201 try {
202 return await next(e)
203 } finally {
204 await runtimeEvent($, 'active', turn)
205 // Answered, declined or interrupted: the question is no longer open.
206 await setState($, 'working')
207 }
208 }).catch(($, e, next) => next(e))
209
210 on('tool.call', async ($, e, next) => {
211 if (!isOpen() || e.agentId !== undefined || !LOOP_TOOLS.has(e.tool)) return next(e)
212 const result = await next(e)
213 if (result.deny === undefined && !result.isError) {
214 await markLoop($, {
215 tool_name: e.tool,
216 tool_input: toolInput(e as unknown as Record<string, unknown>),
217 tool_response: result.result,
218 })
219 }
220 return result
221 }).catch(($, e, next) => next(e))
222}
223hooks/tools.ts 129 lines1// Fallback tools for sessions launched before the fleet MCP service.
2// New sessions advertise status and spawn only. The cached await name remains
3// handled for one version and forwards to the service's explicit RETIRED refusal.
4// The service owns schemas, identity checks and call handling.
5
6import type { On, ToolSpec } from 'claude-code'
7
8import { isOpen } from './gate'
9
10export const PLUGIN = 'fleet'
11// FLEET_MCP_SERVER=1 (set by bin/fleet-claude.sh, #1807) says the service is
12// mounted; lifecycle.ts reads it by its literal name, as the engine requires.
13// bin/fleet-oldcfg-replay.py reads the two below (issue #2075): FALLBACK is «the tools
14// this version registers», TOOL_RE «the names the tool.call hook answers». Rename
15// either and teach the replay the new spelling, or the release gate goes red.
16/** The service's tools the fallback carries, in registration order. */
17export const FALLBACK = ['status', 'spawn'] as const
18export type Fallback = (typeof FALLBACK)[number]
19
20/** Every tool this file serves, as the model calls it. */
21export const TOOL_RE = /^mcp__fleet__fleet_(status|spawn|await)$/
22
23// Timeouts stand a little past fleet-mcp.py's own (SPAWN_TIMEOUT_S 120, STATUS 30,
24// await = timeout + 25), so the service's «did not answer within» is what the model
25// reads, not a cut from here; `$.process.run` allows ten minutes at most.
26export const AWAIT_DEFAULT_S = 540
27const AWAIT_SLACK_S = 25
28const HEADROOM_S = 10
29export const SPEC_TIMEOUT_MS = 30_000
30export const STATUS_TIMEOUT_MS = (3 * 30 + HEADROOM_S) * 1000
31export const SPAWN_TIMEOUT_MS = (120 + HEADROOM_S) * 1000
32export const RUN_MAX_MS = 600_000
33
34/** The install's bin/, from the plugin root (<install>/mod/fleet). */
35export function binDir(root: string): string {
36 const base = root.replace(/\/+$/, '').replace(/\/\.claude-plugin$/, '')
37 return `${base}/../../bin`
38}
39
40function service(bin: string): string[] {
41 return ['python3', `${bin}/fleet-mcp.py`]
42}
43
44/** The argv that prints the currently advertised fallback specs. */
45export function specArgv(bin: string): string[] {
46 return [...service(bin), '--spec', ...FALLBACK]
47}
48
49/** The argv that makes one call — the arguments travel as one JSON word. */
50export function callArgv(bin: string, tool: string, args: Record<string, unknown>): string[] {
51 return [...service(bin), '--call', tool, JSON.stringify(args)]
52}
53
54/** True for a run of this file's (a test's recorder filters them, like where.ts's). */
55export function isToolsRun(argv: readonly string[]): boolean {
56 return argv[0] === 'python3' && (argv[1] ?? '').endsWith('/fleet-mcp.py')
57}
58
59/** How long a forwarded call may take, by tool (await: its own timeout + slack). */
60export function timeoutFor(tool: string, args: Record<string, unknown>): number {
61 if (tool === 'await') {
62 const t = typeof args.timeout === 'number' ? args.timeout : AWAIT_DEFAULT_S
63 return Math.min(RUN_MAX_MS, (t + AWAIT_SLACK_S + HEADROOM_S) * 1000)
64 }
65 return tool === 'spawn' ? SPAWN_TIMEOUT_MS : STATUS_TIMEOUT_MS
66}
67
68const NOTE =
69 '[fallback — this session was launched before the fleet tool service; the call is forwarded to ' +
70 'bin/fleet-mcp.py. A reopened session (/fleet-handoff, or claude --resume) has the service\'s own tools.] '
71
72/** The `--spec` output as the tools to register: `fleet_` + name, the note, the schema as is. */
73export function fallbackSpecs(stdout: string): ToolSpec[] {
74 const rows = JSON.parse(stdout) as unknown
75 if (!Array.isArray(rows)) throw new Error('--spec did not print a list')
76 return rows.map(row => {
77 const r = row as { name?: unknown; description?: unknown; inputSchema?: unknown }
78 if (typeof r.name !== 'string' || r.inputSchema === undefined) throw new Error('--spec row without name/schema')
79 return {
80 name: `fleet_${r.name}`,
81 description: NOTE + (typeof r.description === 'string' ? r.description : ''),
82 inputSchema: r.inputSchema,
83 } as ToolSpec
84 })
85}
86
87/** The one message when the forward itself cannot run (the issue's B). */
88export function unreachable(full: string, tool: string, detail: string): string {
89 if (tool === 'await') return `${full}: RETIRED: Parent await is disabled. View each Task directly. (${detail})`
90 const script = tool === 'spawn' ? 'dash-issue-session.sh <N> --repo <owner/name>'
91 : `fleet-mcp.py --call status '{}'`
92 return [
93 `${full}: 这个会话启动于 fleet 工具服务(bin/fleet-mcp.py)之前,mod 的兜底转调失败:${detail}。`,
94 '请 /fleet-handoff,或退出后用 `claude --resume` 重开 — 新会话挂上 fleet 工具服务(mcp__fleet__status / spawn)。',
95 `临时可以用 Bash 调 ~/.claude/fleet/bin/${script}。`,
96 ].join('\n')
97}
98
99const RESERVED = new Set(['tool', 'tool_use_id', 'agentId', 'consent'])
100
101function argsOf(e: Record<string, unknown>): Record<string, unknown> {
102 const out: Record<string, unknown> = {}
103 for (const [k, v] of Object.entries(e)) if (!RESERVED.has(k)) out[k] = v
104 return out
105}
106
107export function registerTools(on: On): void {
108 // Unconditional past the gate: a call arrives only where a tool is listed, and
109 // that list is the session's own — so answer it, served or not.
110 on('tool.call', { tool: TOOL_RE }, async ($, e, next) => {
111 const full = String(e.tool)
112 const m = TOOL_RE.exec(full)
113 if (!isOpen() || m === null) return next(e)
114 const tool = m[1] as Fallback | 'await'
115 const args = argsOf(e as unknown as Record<string, unknown>)
116 try {
117 const r = await $.process.run(callArgv(binDir($.plugin.root), tool, args), { timeoutMs: timeoutFor(tool, args) })
118 const text = r.stdout.replace(/\s+$/, '')
119 if (r.exitCode === 0) return { result: text }
120 if (r.exitCode === 1 && text !== '') return { deny: text } // the service refused or faulted, with its reason
121 const err = r.stderr.replace(/\s+$/, '')
122 return { result: unreachable(full, tool, `fleet-mcp.py --call exited ${r.exitCode}${err ? ` (${err})` : ''}`) }
123 } catch (err) {
124 // No python3, no bin/, a timeout: say what to do, never hang.
125 return { result: unreachable(full, tool, err instanceof Error ? err.message : String(err)) }
126 }
127 }).catch(($, e, next) => next(e))
128}
129hooks/usage.ts 180 lines1// Context, quota, model and effort, reported by the session itself (issue #1338,
2// EPIC #1334; model/effort + the bus feed, issue #1459).
3//
4// The engine pushes `session.measure` after every main-thread turn and when a
5// rate-limit window moves a whole point — rendered or not, watched or not. So a
6// background window nobody looks at still reports, where Claude Code's status
7// line (conf/statusline.sh) only runs when the status line redraws — and once a
8// login turns that status line OFF (`bin/fleet-statusline.sh off`, which gives the
9// pane its bottom row back) this is the ONLY reporter.
10//
11// One writer: everything here goes through conf/statusline.sh itself, run as
12//
13// bash <install>/conf/statusline.sh --from mod key=value …
14//
15// so the window options, their rounding and the @ctx_band thresholds are that
16// one file's whoever feeds it — Claude Code's JSON or this mod's argv. The
17// options it stamps for us:
18//
19// @ctx_pct @ctx_limit @ctx_band the context fill (integer %), window size and
20// the fleet's handoff band (fleet-context.sh, the
21// auto-handoff nudge, the pane header's colour)
22// @ctx_src mod this mod fed the bus at least once; the Claude
23// path never touches it, so a window keeps the
24// mark — fleet-statusline.sh counts them
25// @model @effort the model's display name and effort level (the
26// pane header; fleet-model-switch.sh verifies a
27// /model off @model, so it must flip without a
28// turn — hence the poll)
29// @rl5h @rl7d @rl_reset @rl_ts the account's 5h/7d % used and resets (issue
30// @rl_src mod #1267; a fresh `mod` stamp lets the quota watch
31// skip its ccquota fetch, bin/fleet-quotawatch.sh)
32//
33// Three sources, one target:
34// session.measure context + rate limits, when `changed` names either (here)
35// turn.step the model id and effort of each main-thread model request,
36// fed only when the pair changed — observe-and-pass, the
37// stream is never held for the write (here)
38// a 2 s poll `$.session.model()`, run by lifecycle.ts's onReady timer
39// (the engine follows `$` only within one file), so a /model
40// typed or posted lands on the bus within ~2 s and
41// fleet-model-switch's 15 s verify reads it. It feeds the
42// model alone — the script unsets @effort, and the next
43// turn.step restores the new model's.
44// The model dedup (`claimModelFeed`) is shared by the two model sources so a
45// pair is fed once. Rate limits are stamped only when BOTH windows have a
46// reading — the watch reads a half stamp as none; the script enforces that too.
47
48import type { EngineInterface, On, SessionMeasureInput, TurnStepInput } from 'claude-code'
49
50import { isOpen } from './gate'
51
52/** One bash + awk + tmux chain; well under the hook's budget. */
53export const STATUSLINE_TIMEOUT_MS = 10_000
54/** How often lifecycle.ts re-reads the live model while nothing else reports it. */
55export const MODEL_POLL_MS = 2_000
56
57/** <install>/conf/statusline.sh from the plugin root (<install>/mod/fleet). */
58export function statuslinePath(root: string): string {
59 const base = root.replace(/\/+$/, '').replace(/\/\.claude-plugin$/, '')
60 return `${base}/../../conf/statusline.sh`
61}
62
63/** The argv that feeds `fields` to the bus through the script. */
64export function feedArgv(root: string, fields: readonly string[]): string[] {
65 return ['bash', statuslinePath(root), '--from', 'mod', ...fields]
66}
67
68/**
69 * Claude Code's display name for a model id, as its status line spells it:
70 * `claude-opus-5-5` → `Opus 5.5`, `claude-haiku-4-5-20251001` → `Haiku 4.5`,
71 * `claude-sonnet-4-6[1m]` → `Sonnet 4.6 (1M context)`. An id outside that
72 * grammar (a Bedrock arn, an alias) is shown as it is — fleet-model-switch's
73 * match is a case-insensitive substring either way.
74 */
75export function displayName(id: string): string {
76 const raw = id.trim()
77 const m = /^claude-([a-z]+)-(\d+)-(\d+)(?:-\d{6,})?(\[1m\])?$/i.exec(raw)
78 if (m === null) return raw
79 const family = m[1]!.charAt(0).toUpperCase() + m[1]!.slice(1).toLowerCase()
80 return `${family} ${m[2]}.${m[3]}${m[4] ? ' (1M context)' : ''}`
81}
82
83/** ISO 8601 → epoch seconds as a string; `-` when absent or unreadable. */
84function epoch(iso: string | undefined): string {
85 const ms = iso === undefined ? NaN : Date.parse(iso)
86 return Number.isFinite(ms) ? String(Math.floor(ms / 1000)) : '-'
87}
88
89/** The key=value fields one measurement feeds the bus; empty when it carries nothing to say. */
90export function measureFields(e: Pick<SessionMeasureInput, 'context' | 'rateLimits'>): string[] {
91 const out: string[] = []
92 const { percent, window } = e.context
93 if (percent !== undefined && Number.isFinite(percent)) {
94 // Raw, to two decimals: the script rounds it (printf %.0f) as it rounds Claude's.
95 out.push(`ctx_pct=${percent.toFixed(2)}`)
96 if (Number.isFinite(window) && window > 0) out.push(`ctx_limit=${Math.floor(window)}`)
97 }
98 const five = e.rateLimits.find(r => r.kind === 'five_hour')
99 const seven = e.rateLimits.find(r => r.kind === 'seven_day')
100 if (five !== undefined && seven !== undefined && Number.isFinite(five.percentUsed) && Number.isFinite(seven.percentUsed)) {
101 out.push(`rl5h=${Math.max(0, Math.floor(five.percentUsed))}`)
102 out.push(`rl7d=${Math.max(0, Math.floor(seven.percentUsed))}`)
103 out.push(`rl_reset5=${epoch(five.resetsAt)}`)
104 out.push(`rl_reset7=${epoch(seven.resetsAt)}`)
105 }
106 return out
107}
108
109/** The key=value fields for a model (+ its effort; none ⇒ the script unsets @effort). */
110export function modelFields(id: string, effort: string | number | undefined): string[] {
111 const out = [`model=${displayName(id)}`]
112 if (effort !== undefined && effort !== '') out.push(`effort=${effort}`)
113 return out
114}
115
116// --- the model dedup, shared by turn.step (here) and the poll (lifecycle.ts) ---
117// Module state: a reload is a fresh module and session.start fires again.
118let fedModel: { id: string; effort: string } | undefined
119
120/** Forget what was fed (session.start, or a feed that failed — the next source retries). */
121export function resetModelFeed(): void {
122 fedModel = undefined
123}
124
125/** True when `id` is not the model last fed (the poll's question). */
126export function modelMoved(id: string): boolean {
127 return id !== '' && fedModel?.id !== id
128}
129
130/**
131 * Record (id, effort) as fed and return its fields — or null when that pair is
132 * what the bus already has, or `id` is empty.
133 */
134export function claimModelFeed(id: string, effort: string | number | undefined): string[] | null {
135 if (id === '') return null
136 const eff = effort === undefined ? '' : String(effort)
137 if (fedModel !== undefined && fedModel.id === id && fedModel.effort === eff) return null
138 fedModel = { id, effort: eff }
139 return modelFields(id, effort)
140}
141
142async function feed($: EngineInterface, fields: readonly string[]): Promise<void> {
143 if (fields.length === 0) return
144 const pane = await $.env.get('TMUX_PANE')
145 if (pane === undefined || pane === '') return
146 await $.process.run(feedArgv($.plugin.root, fields), { timeoutMs: STATUSLINE_TIMEOUT_MS })
147}
148
149async function feedStep($: EngineInterface, e: TurnStepInput): Promise<void> {
150 const fields = claimModelFeed(e.model, e.effort)
151 if (fields === null) return
152 try {
153 await feed($, fields)
154 } catch {
155 resetModelFeed()
156 }
157}
158
159export function registerUsage(on: On): void {
160 on('session.measure', async ($, e, next) => {
161 if (!isOpen()) return next(e)
162 if (e.changed.includes('context') || e.changed.includes('rateLimits')) {
163 try {
164 await feed($, measureFields(e))
165 } catch {
166 // A missed report leaves the last one standing; the next measurement writes.
167 }
168 }
169 return next(e)
170 }).catch(($, e, next) => next(e))
171
172 on('turn.step', async function* ($, e, next) {
173 // Observe and pass: the write runs beside the stream, never ahead of it.
174 if (isOpen() && e.agentId === undefined) void feedStep($, e)
175 return yield* next(e)
176 }).catch(async function* ($, e, next) {
177 return yield* next(e)
178 })
179}
180hooks/gate.ts 27 lines1// The one switch every fleet hook stands behind (EPIC #1334 rule 5).
2//
3// `register` runs before the engine can say its version, so a feature file
4// cannot simply skip registering. lifecycle.ts's session.start hook checks the
5// version and opens the gate when it is in range, so:
6//
7// - an ordinary hook starts with `if (!isOpen()) return next(e)` and passes
8// straight through to the engine while the gate is shut;
9// - work that needs the session up (a timer, a first write) goes in
10// lifecycle.ts's `onReady`, which runs only once the gate is open — the
11// engine takes one unmatched session.start hook per plugin.
12//
13// `$` is never handed across an import (the engine follows it only within one
14// file), so this file holds the flag and nothing else. A reload is a fresh
15// module: the gate starts shut and session.start fires again.
16
17let open = false
18
19export function isOpen(): boolean {
20 return open
21}
22
23/** lifecycle.ts only: the version check passed. */
24export function openGate(): void {
25 open = true
26}
27hooks/where.ts 72 lines1// Where the person is (issue #1716, EPIC #1710 C6): one line in the session's
2// context — 「操作者此刻在:MacBook · macOS · iTerm2 3.6 · 能:打开网页…」 — so a
3// session on any machine knows which device and terminal the person uses right
4// now, and what it can do for them there.
5//
6// The line comes from bin/fleet-client-where.sh, THE one reader (EPIC rule 7):
7// the hub's client lease, or with no hub the fleet-shell client attached here.
8// lifecycle.ts reads it at the start and every WHERE_POLL_MS — a read another
9// session of this login took under WHERE_SHARED_SECS ago is taken as is — (the timer and `$`
10// live there: the engine follows `$` only within one file); compose.ts's
11// `prompt.compose` hook adds it as the last `session` section, so a takeover (the phone
12// opening the client) reaches the model's next request within the poll. A read
13// that fails keeps the last line; no line yet adds nothing.
14
15import type { PromptComposeSection } from 'claude-code'
16
17export const WHERE_POLL_MS = 15_000
18/** The script asks the hub (≤5 s) and maybe tmux; well inside this. */
19export const WHERE_TIMEOUT_MS = 10_000
20export const WHERE_SECTION = 'fleet:where'
21/**
22 * Every session of a login polls; they share one read this young (issue #3544:
23 * ten idle sessions were ten hub requests and ten python starts every 15 s).
24 */
25export const WHERE_SHARED_SECS = 14
26
27let line: string | undefined
28
29/** <install>/bin/fleet-client-where.sh from the plugin root (<install>/mod/fleet). */
30export function whereArgv(root: string): string[] {
31 const base = root.replace(/\/+$/, '').replace(/\/\.claude-plugin$/, '')
32 return ['bash', `${base}/../../bin/fleet-client-where.sh`, '--max-age', String(WHERE_SHARED_SECS)]
33}
34
35/**
36 * Take one run of the script: exit 0 names a client, 3 says nobody is
37 * connected; anything else is no answer and keeps what we had. Returns true
38 * when the line changed.
39 */
40export function takeWhere(exitCode: number, stdout: string): boolean {
41 if (exitCode !== 0 && exitCode !== 3) return false
42 const next = stdout.split('\n')[0]?.trim() ?? ''
43 if (next === '' || next === line) return false
44 line = next
45 return true
46}
47
48export function currentWhere(): string | undefined {
49 return line
50}
51
52/** Tests: forget the line. */
53export function resetWhere(): void {
54 line = undefined
55}
56
57export function whereSection(text: string): PromptComposeSection {
58 return {
59 id: WHERE_SECTION,
60 scope: 'session',
61 text:
62 `# 操作者此刻在哪\n操作者此刻在:${text}\n` +
63 '(fleet 客户端租约;换设备接管后这一行会跟着变。要最新的或要字段,运行 ' +
64 '`~/.claude/fleet/bin/fleet-client-where.sh [--json]`;给操作者看网页/文件前按这里的「能:」选送达方式,不要自己猜终端或设备。)',
65 }
66}
67
68/** Tests: is this argv the where read (so a test counting its own runs can skip it)? */
69export function isWhereRun(argv: readonly string[]): boolean {
70 return argv[0] === 'bash' && (argv[1] ?? '').endsWith('/bin/fleet-client-where.sh')
71}
72hooks/inbox.ts 152 lines1// The pane's command inbox (issue #1337, EPIC #1334 C3).
2//
3// The fleet used to TYPE `/clear`, `/compact …`, `/model …` and the handoff
4// pickup into a pane (Escape, the text, a separate Enter, then poll the screen).
5// Now bash posts the command as a file (bin/fleet-lib.sh fleet_session_command)
6// and this mod runs it with `$.command.run`, which the engine queues until the
7// session is idle — never mid-turn, never glued onto a half-typed draft.
8//
9// <FLEET_CONF_DIR>/global/mod-inbox/<socket-label>/<pane-id>/
10// <seq>.json {"cmd":"/clear","args":"","from":"handoff-cycle"}
11// <seq>.taken our claim: an atomic `mv` of the .json — the poster cancels with
12// the same rename, so exactly one side ever wins
13// <seq>.done {"ok":true} | {"ok":false,"error":"…"}
14//
15// The poll runs on lifecycle.ts's timer, not on a session event: a /clear ends
16// the session and fires no new session.start, but the module and its timers go
17// on — so the pickup posted right after a handoff's /clear is still taken.
18// `$` is never handed across an import (gate.ts), so lifecycle.ts hands this
19// file an `InboxIo` built from its own `$` calls; everything here is plain logic.
20
21/** The poll interval (ms). */
22export const INBOX_MS = 1000
23
24/** One posted command. */
25export type InboxMessage = { cmd: string; args: string; from: string }
26
27/** The `$` calls one poll needs, bound by lifecycle.ts. */
28export type InboxIo = {
29 list: (dir: string) => Promise<string[]>
30 read: (path: string) => Promise<string>
31 write: (path: string, text: string) => Promise<void>
32 /** Atomic rename; false when the source is gone (the poster cancelled it). */
33 claim: (from: string, to: string) => Promise<boolean>
34 run: (command: string, args: string) => Promise<void>
35 /** Read-only native observation. This never enters command.run. */
36 query?: (request: Record<string, unknown>) => Promise<void | Record<string, unknown>>
37 /** Conditional idle acceptance (accept.ts, #4618): its outcome rides the .done. */
38 accept?: (request: Record<string, unknown>) => Promise<Record<string, unknown>>
39 /** Narrow, ownership-checked native cancellation; never a free-form tool call. */
40 cancel?: (request: Record<string, unknown>) => Promise<Record<string, unknown>>
41}
42
43/**
44 * The inbox directory for this pane, or undefined outside tmux. `tmux` is $TMUX
45 * (`<socket path>,<pid>,<session>`); the socket's basename is the fleet's label —
46 * a pane id is unique per server only, and every fleet runs its own (#159).
47 */
48export function inboxDir(confDir: string, tmux: string | undefined, pane: string | undefined): string | undefined {
49 if (!tmux || !pane || !/^%\d+$/.test(pane)) return undefined
50 const sock = tmux.split(',')[0]?.split('/').pop() ?? ''
51 if (sock === '') return undefined
52 return `${confDir.replace(/\/+$/, '')}/global/mod-inbox/${sock}/${pane.slice(1)}`
53}
54
55/** A posted file's message, or a reason it cannot run. */
56export function parseMessage(text: string): InboxMessage | { error: string } {
57 let v: unknown
58 try {
59 v = JSON.parse(text)
60 } catch {
61 return { error: 'not JSON' }
62 }
63 if (typeof v !== 'object' || v === null) return { error: 'not an object' }
64 const o = v as Record<string, unknown>
65 const cmd = typeof o.cmd === 'string' ? o.cmd.trim() : ''
66 if (!/^\/[^\s/][^\s]*$/.test(cmd)) return { error: 'cmd must be one /command' }
67 return {
68 cmd: cmd.slice(1),
69 args: typeof o.args === 'string' ? o.args : '',
70 from: typeof o.from === 'string' ? o.from : '?',
71 }
72}
73
74/** Pending seqs, oldest first (seqs start with the epoch second). */
75export function pending(names: readonly string[]): string[] {
76 return names
77 .filter(n => n.endsWith('.json') && !n.startsWith('.') && n !== 'native-cancel.json')
78 .map(n => n.slice(0, -'.json'.length))
79 .sort()
80}
81
82/** One fixed cancellation slot, independent of an idle-waiting command poll. */
83export async function pollNativeCancel(io: InboxIo, dir: string): Promise<void> {
84 const base = `${dir}/native-cancel`
85 if (!(await io.claim(`${base}.json`, `${base}.taken`))) return
86 let result: Record<string, unknown>
87 try {
88 const request: unknown = JSON.parse(await io.read(`${base}.taken`))
89 if (!io.cancel || typeof request !== 'object' || request === null || Array.isArray(request)) {
90 throw new Error('native cancellation unavailable')
91 }
92 result = await io.cancel(request as Record<string, unknown>)
93 } catch (error) {
94 result = { ok: false, state: 'refused', error: errorText(error) }
95 }
96 await io.write(`${base}.done`, `${JSON.stringify(result)}\n`)
97}
98
99function errorText(err: unknown): string {
100 const s = err instanceof Error ? err.message : String(err)
101 return s.replace(/\s+/g, ' ').slice(0, 300)
102}
103
104/**
105 * One poll: claim each pending command, run it, write its .done. Commands run
106 * one at a time, in post order; `$.command.run` itself waits for an idle session.
107 */
108export async function pollInbox(io: InboxIo, dir: string): Promise<number> {
109 let names: string[]
110 try {
111 names = await io.list(dir)
112 } catch {
113 return 0 // no inbox yet: nothing was ever posted to this pane
114 }
115 let ran = 0
116 for (const seq of pending(names)) {
117 const base = `${dir}/${seq}`
118 if (!(await io.claim(`${base}.json`, `${base}.taken`))) continue
119 let result: { ok: boolean; error?: string; [k: string]: unknown }
120 try {
121 const text = await io.read(`${base}.taken`)
122 let request: Record<string, unknown> | undefined
123 try { request = JSON.parse(text) } catch { /* Keep the command parser's error. */ }
124 if (request?.accept !== undefined) {
125 if (request.accept !== 'idle.v1' && request.accept !== 'idle.v2') throw new Error('unsupported accept')
126 if (!io.accept) throw new Error('idle accept unavailable')
127 result = { ok: true, ...(await io.accept(request)) }
128 } else if (request?.query !== undefined) {
129 if (request.query !== 'runtime.v1' && request.query !== 'park.v1') throw new Error('unsupported query')
130 if (!io.query) throw new Error('runtime query unavailable')
131 result = { ok: true, ...((await io.query(request)) ?? {}) }
132 } else {
133 const msg = parseMessage(text)
134 if ('error' in msg) result = { ok: false, error: msg.error }
135 else {
136 await io.run(msg.cmd, msg.args)
137 result = { ok: true }
138 }
139 }
140 } catch (err) {
141 result = { ok: false, error: errorText(err) }
142 }
143 try {
144 await io.write(`${base}.done`, `${JSON.stringify(result)}\n`)
145 } catch {
146 // The poster times out to "running" (exit 6) and never types it again.
147 }
148 ran++
149 }
150 return ran
151}
152hooks/tmux.ts 30 lines1// Window options through tmux — the fleet's one state store (EPIC #1334 rule 1).
2//
3// Run the argv this builds with `$.process.run(...)` at the call site (`$` is
4// never handed across an import). `$.process.run` inherits the session's
5// environment, so a bare `tmux` lands on THIS fleet's own server via $TMUX (one
6// fleet ≡ one socket, issue #159), and `-t $TMUX_PANE` pins the write to this
7// pane's window — an untargeted `set-option -w` would hit the session's CURRENT
8// window instead (issue #511). Read the pane with `$.env.get('TMUX_PANE')`;
9// unset or empty = outside tmux, write nothing.
10
11/**
12 * The argv that sets (string) or unsets (null) window options on `pane`'s
13 * window, all in ONE tmux call (`;`-chained); null when there is nothing to do.
14 */
15export function windowOptionsArgv(
16 pane: string,
17 options: Record<string, string | null>,
18): string[] | null {
19 const argv: string[] = ['tmux']
20 for (const [key, value] of Object.entries(options)) {
21 if (argv.length > 1) argv.push(';')
22 if (value === null) argv.push('set-option', '-w', '-u', '-t', pane, key)
23 else argv.push('set-option', '-w', '-t', pane, key, value)
24 }
25 return argv.length > 1 ? argv : null
26}
27
28/** How long one tmux write may take before the run is abandoned. */
29export const TMUX_TIMEOUT_MS = 5000
30hooks/version.ts 37 lines1// The Claude Code versions this mod is written against (EPIC #1334 rule 5).
2// The function-hook API is early access and moves between releases, so outside
3// this range the mod registers nothing and the session runs exactly as it does
4// with no mod at all: the window says `@mod_state off:version` and fleet-doctor's
5// `mod` row counts it. Widen BELOW after checking a new release.
6
7/** The mod's own version — keep equal to .claude-plugin/plugin.json. */
8export const MOD_VERSION = '0.7.0'
9
10/** Supported Claude Code releases: MIN inclusive, BELOW exclusive. */
11export const SUPPORTED = { min: '2.1.288', below: '2.2.0' } as const
12
13type Triple = [number, number, number]
14
15/** `2.1.288`, `2.1.288-dev`, `2.1.288-dev.20260920…` → [2, 1, 288]; else null. */
16export function parseVersion(text: string | undefined): Triple | null {
17 const m = /^(\d+)\.(\d+)\.(\d+)/.exec(text ?? '')
18 return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null
19}
20
21function cmp(a: Triple, b: Triple): number {
22 for (let i = 0; i < 3; i++) {
23 const d = (a[i] ?? 0) - (b[i] ?? 0)
24 if (d !== 0) return d
25 }
26 return 0
27}
28
29/** True when `version` (a release or dev spelling) lies in SUPPORTED. */
30export function isSupported(version: string | undefined): boolean {
31 const v = parseVersion(version)
32 const lo = parseVersion(SUPPORTED.min)
33 const hi = parseVersion(SUPPORTED.below)
34 if (v === null || lo === null || hi === null) return false
35 return cmp(v, lo) >= 0 && cmp(v, hi) < 0
36}
37