A chief of staff for Claude Code: /fleet start makes a session the chief, which plans, keeps a task board and delegates to one agent per repository.

A chief of staff for Claude Code, as a herdr plugin.
You talk to one Claude Code session, the chief. It plans the work, breaks it into tasks on a shared board, and starts one Claude Code agent per repository, each in a herdr tab of its own, to do them. fleet shows you the crew: a live graph of who is working, who is waiting on you and who told whom what, with the board beside it.
It is for work that crosses repositories — a backend change, the service that consumes it, the UI on top — where one agent per repo keeps each one's context small, and something has to keep track of what waits on what.

fleet board go or from you typing in its tab.fleet board, with a /board skill that teaches it. Nothing to install: every agent starts with the skill loaded.fleet board msg records a message on the board and puts it in front of the recipient, marked as coming from a peer. A Claude Code mod in each agent picks it up once the agent's turn has ended, whole; without mods (Claude Code before v2.1.287, or mods turned off) it is typed into the agent's pane instead.↵ or a click goes to an agent's tab.herdr status shows both.~/.local/bin/claude), or any claude named by FLEET_CLAUDE, which fleet starts its agents with.cargo) only on a machine without a prebuilt binary: macOS and Linux on arm64 and x86_64 have one.Outside herdr, start a fleet by running this in the workspace, the directory that holds your repositories:
fleet chief # a new chief, and a new run
fleet chief --resume # back into the last chief's conversation and its run
The terminal becomes the chief's Claude Code session: briefed, with the /board skill and fleet's mod, on the workspace's board. It refuses to start a second chief while the first is still running.
Or make a session you already have open the chief. In a Claude Code session with fleet's plugin loaded, in the workspace:
/fleet start
The session is put on the board as the chief of a new run, gets the board's tools and the fleet view, which opens beside the conversation, and receives the chief's brief as a turn. Claude Code keeps a plugin you install out of the system prompt, so the brief is part of the conversation; when the conversation is compacted, fleet puts the brief back at the head of what is kept. The plugin does nothing in a session until /fleet start.
In a workspace listed in ~/.claude-fleet/auto-open (see Quick start), the band above the prompt offers it as a button: Start fleet does what /fleet start does. Anywhere else, nothing shows until you type it.
fleet runs the agents the chief starts as Claude Code background sessions instead of herdr tabs. fleet spawn, fleet handoff, fleet board retire and resume work the same from any terminal: each agent is a claude --bg session in its repository, with the same brief, plugin and tools, and messages reach it through fleet's mod. claude agents lists the crew and says which one needs you; claude attach <id>, which fleet spawn prints, opens one to talk to.
The chief's own session draws the fleet, in place of the fleet tab:
/fleet opens a pane beside the conversation with the fleet view: the fleet tab in herdr, live and with its keys, drawn by fleet at the pane's size. Click into it, and ↑↓ ←→ move between agents, l switches to the log, n starts an agent, x retires one, r brings a crew back and q closes it; a click on a card selects it. ↵ on a background agent says how to open it (claude attach <id>), since there is no tab to switch to. A worker waiting for its go has a button beneath the view. In the Claude desktop app and on the phone the pane is drawn natively instead: the crew as a graph, a card for each agent with a button for its go and, past 80% context, one to hand it off, the open tasks and the latest messages.fleet · 3 agents · 1 working · 4 open · billing needs a go · accounts at 84%, with an Open fleet button while the pane is closed.fleet tui runs in a plain terminal too, for the graph.
Two things to know:
claude once in each repository an agent will work in and accept the prompt. When a spawn is refused, fleet names the repository to trust.FLEET_HOST=herdr or FLEET_HOST=background picks one instead of going by where fleet runs. The setup check's running in row says which it will use.
With FLEET_HOST=desktop, a chief in the Claude desktop app starts its agents as desktop sessions instead. Each one shows in the sidebar under the chief, where you open it and talk to it with a click. fleet cannot start a desktop session itself: the chief's model does, with the app's start_session tool, and the app allows that only on a turn your own message started. So the chief works this way:
fleet spawn <name> --repo <path> --task <key> --host desktop puts the agent on the board and prints what the chief passes to start_session.mcp__fleet__join tool. It reads its task, sends the chief its plan and waits for a go.fleet board go and fleet board msg record it and say what to send. The chief sends it with SendMessage to the worker's local_… id, and that starts the worker's turn./fleet:spawn <name>.fleet board retire takes the worker off the board. The chief then stops it with stop_session and archives it with archive_session.The app asks you to trust each repository once, before the first worker starts there. fleet must be installed as a Claude Code plugin, so that each worker loads its mod. After fleet board retire, the desktop app's Import also shows the conversations of background workers in the sidebar.
claude plugin marketplace add patrickkunzke/fleet
claude plugin install fleet@fleet
Then start Claude Code in your workspace as you always do, and make that session the chief:
/fleet start
The plugin does nothing in a session until then. The first /fleet start downloads fleet's binary for your machine into the plugin's folder, checked against the release's SHA256SUMS; a fleet already on your PATH is used if that fails. See Without herdr for what the chief and its agents do from there.
herdr plugin install patrickkunzke/fleet --ref release
release is the branch at the newest release whose prebuilt binaries are up. herdr shows what it is about to run, clones the repository and runs its build step, scripts/install.sh. That downloads the release's prebuilt binary for your machine and checks it against the release's SHA256SUMS; it builds with cargo build --release --locked instead when there is no binary for your machine, or when the checkout is not a release commit. FLEET_BUILD=source always builds. Then, in ~/.config/herdr/config.toml:
[session]
# herdr would resume agents itself, as plain `claude --resume <id>`: no role,
# and a chief with its editing tools back. fleet resumes its crew instead.
resume_agents_on_restore = false
[ui.toast]
# herdr shows no notifications by default; fleet's go through it.
delivery = "system" # or "herdr" for in-app toasts
[[keys.command]]
key = "prefix+f"
type = "plugin_action"
command = "fleet.open"
description = "fleet"
[[keys.command]]
key = "prefix+shift+f"
type = "plugin_action"
command = "fleet.new"
description = "new workspace in fleet mode"
To check the setup, run the fleet: check the setup action from herdr's action list (herdr plugin action invoke fleet.doctor), and read what it found with herdr plugin log list --plugin fleet. It checks herdr's server version, which claude fleet will start and whether it loads mods (v2.1.287 or newer, and disableAllHooks not set), and the two settings above, and says what to change.
/board skill, and fleet on your PATHNothing to install for either. Every agent fleet starts has the /board skill loaded (as fleet:board, through Claude Code's --plugin-dir, for that session only) and fleet first on its PATH. Your own Claude Code sessions are left as they were: the board is for the crew.
To run fleet from your own shell as well, put this on your PATH as ~/.local/bin/fleet:
#!/bin/sh
# fleet as herdr has it installed: herdr 0.9.4 and newer put every update
# in a directory of its own, so a link to one would go stale.
root=$(herdr plugin list --plugin fleet --json | sed -n 's/.*"plugin_root":"\([^"]*\)".*/\1/p')
exec "$root/target/release/fleet" "$@"
With herdr 0.9.4 or newer, and fleet installed at release:
herdr plugin update fleet
herdr plugin update follows the ref fleet was installed at. An install at a tag (--ref v0.16.0, which older fleet updates made) stays at that tag: run fleet update once to move it to release. On any herdr:
fleet update --check # the installed version and the newest release
fleet update # install the newest release
It installs again through herdr at release, so herdr shows what it is about to run, as on the first install, and herdr plugin update follows the branch from then on. herdr builds the new version beside the old one and switches to it only when the build passes: a failed update leaves the fleet you had. For a checkout linked with herdr plugin link, it pulls main and builds instead, and stops if the checkout is on another branch or has uncommitted changes; herdr plugin update leaves a linked checkout alone.
Without fleet on your PATH, the same thing by hand:
herdr plugin install patrickkunzke/fleet --ref release
After an update, a fleet view that is already open still runs the old version: press q in it, then prefix+f. Agents that are already running may keep the old fleet until they are next started: herdr 0.9.4 and newer leave the old version's directory in place, on their PATH, until its server stops. The doctor action says when a newer release is out.
~/Code/acme, say, with service/billing-service and ui/storefront somewhere below it.prefix+f. The fleet tab opens with the chief on its left.Every agent asks the chief before it starts changing code, and fleet holds it to that: its edits are refused until the chief gives its task a go with fleet board go, or you answer it in its own tab. The chief asks you about anything that is yours to decide. You can go to any agent's tab and talk to it directly; it is an ordinary Claude Code session.
prefix+shift+f opens a new workspace in fleet mode wherever the focused pane is. To have a directory's workspaces open in fleet mode by themselves, list it in ~/.claude-fleet/auto-open, one directory a line:
echo '~/Code/acme' >> ~/.claude-fleet/auto-open
It matches the workspace's own directory exactly, so a workspace opened in one repository inside it stays an ordinary one. Outside herdr, a Claude Code session started in a listed directory offers a Start fleet button above its prompt instead.
| Key | |
|---|---|
← → ↑ ↓ | move between agents |
↵, or a click | go to that agent's tab |
l | the log of every message and state change; l again for the graph |
n | start an agent in a repository of your choosing |
r | bring back an earlier run |
x | take an agent off the board (its tab is left alone) |
q | quit the view; the agents keep running |
No key needs a prefix: none of them belongs to an agent.
The graph is the crew as it is shaped: the chief's card over its agents', a line from it into each. A line is heavy where the most has gone along it and dashed where nothing has, amber while the agent at its end is working and teal while it waits for you. A message is drawn travelling along its line as it is sent. An agent stopped at a permission or question dialog shows as ! needs you.
The board lists the open tasks by epic, with who holds each and what it waits on, and the background processes the agents have running. In a narrow pane it goes under the graph.
The sidebar. On each agent's second line, where herdr would say claude, fleet writes what it is on — ENG-2553-2 · waits on ENG-2553-1, ENG-2553-2 · review — and on the chief's, the board at a glance: 3 open · 1 blocked · 1 in review.
The chief is briefed as a chief of staff for the workspace: plan, write the tasks down, delegate, and answer the agents. It starts with --disallowed-tools Edit Write NotebookEdit, because asking was not enough — given a ticket touching a single repository, it did the work itself. fleet's mod (see Messages) also refuses the chief's Bash commands that write files: redirects, sed -i, tee, cp, mv, rm, git commit and the like, outside /tmp. Not airtight, since a pattern cannot know every way a command writes, but it closes the paths of least resistance.
A worker does not change files until its task has a go-ahead. It reads its task, sends the chief its plan, and its Edit, Write and file-writing Bash calls are refused, with a reason that says to wait, until either the chief answers with
fleet board go ENG-2553-2 "go — keep the old column until billing is on it"
which records the go and sends the message in one step, or you type a prompt in the worker's own tab: talking to it there is your go. A worker cannot run fleet board go itself. Anything short of a go, such as a question or "hold off", is a fleet board msg and leaves it waiting. A task approved before anyone claims it is approved for whoever does. Like message delivery, this needs the mod: without it, the go-ahead is only asked for, as it was.
A worker waiting for its go is easy to spot. Its card in the graph reads ◇ needs a go once it is idle (● planning while it is still reading and writing its plan), the header counts it, its herdr sidebar label says ENG-2553-2 · needs a go, and herdr notifies you once when it stops to wait. In the worker's own tab, the line under its prompt says waiting for a go on ENG-2553-2. A task that is blocked, or waits on another, is waiting on that instead, and is not shown as needing a go.
The mod also reports what its session is doing each time it checks in. A working agent's card names the tool it is running (● Bash, an MCP tool by its own name without the server's), and the top right gives how full its context window is beside its uptime, 41m · 63%, with the uptime dropped when a long name leaves no room. From 80% the figure turns to the accent colour and herdr notifies you once: an agent that compacts keeps a summary of its brief rather than the brief, and a fresh agent may be the better one to finish its task. An agent without the mod shows only ● working.
It delegates with fleet spawn, which opens a tab in the repository, briefs the agent, and claims the task on the board in the same step, so it cannot be dispatched twice:
fleet spawn billing-svc --repo ~/Code/acme/service/billing-service --task ENG-2553-2
An agent nearly out of context is handed off rather than left to compact:
fleet handoff billing-svc --note "the flaky test is known; skip it"
A fresh session starts in the same repository under the same name, on the same task, briefed on the task, its messages on the board, the old session's last reply and the note, and told to look at the branch and git status before anything else. A go-ahead the task had stands. The old session is retired and its tab closed; an agent mid-turn is refused unless --now is given. The chief is told when a worker passes 80% context, with the command to run, and so are you, through herdr.
A retired session that is still running, because its tab was left open, changes nothing more: fleet's mod refuses its edits, and tells it once, when it is next idle, to stop.
When an agent is finished with, the chief retires it with fleet board retire billing-svc, which takes it off the board and closes its tab. A working agent's tab is left open, and --keep-tab leaves it either way. x in the fleet view only takes an agent off the board.
Each agent is briefed in two halves. Who it is goes into the system prompt, with --append-system-prompt, where it outranks whatever a hook injects later and survives compaction. What to do now is its first turn: the task, its body, what it waits on, and how to report.
One SQLite file per fleet, at ~/.claude-fleet/fleets/<name>/fleet.db, holding its epics, tasks and their dependencies, agents, runs, background processes, and every event. A fleet is one workspace directory, and its board is its own: agents are handed theirs in FLEET_DB, and a Claude Code session fleet did not start is refused (not part of a fleet) rather than written onto somebody else's.
fleet board epic ENG-2553 "shared settings flag"
fleet board add ENG-2553-1 ~/Code/acme/service/accounts-service "shared column" --epic ENG-2553
fleet board add ENG-2553-2 ~/Code/acme/service/billing-service "consume it" --epic ENG-2553 --dep ENG-2553-1
fleet board ready # only ENG-2553-1: the other one is waiting
fleet board start ENG-2553-1
fleet board done ENG-2553-1 # and says it unblocked ENG-2553-2
fleet board ls
fleet board log
fleet board --help lists the rest. FLEET_JSON=1 gives JSON from any read. fleet board sql takes a SELECT and refuses anything else: every write goes through a verb that records its event, and the log is only as good as that. From a shell, fleet fleets lists the fleets and --fleet <name> picks one.
$ fleet board msg accounts-svc chief "the column is in" --task ENG-2553-1
accounts-svc -> chief: the column is in
queued for chief: it arrives when chief is next idle
The message is written to the board first, then delivered, marked so the agent does not take a peer for the person at the keyboard: [fleet · accounts-svc · ENG-2553-1] the column is in.
Every agent fleet starts carries a small Claude Code mod beside the /board skill. It checks the board every few seconds, and once its session's turn has ended it takes what is waiting and submits it as a prompt of its own: the whole body, its line breaks kept, several messages in one prompt. While a turn runs, the line under the prompt says how many are waiting. Nothing is typed into a prompt the agent is busy at.
An agent whose mod is not checking in — Claude Code older than v2.1.287, mods turned off with disableAllHooks or --safe-mode, or a session that is not running — gets the old delivery instead: the message typed at its prompt through herdr, on one line, cut at 1500 characters, and held at a permission dialog rather than typed into it. Neither delivery ever costs the record: a message to an agent that has gone is still on the board.
A message an agent sends some other way and never logs does not appear in the graph. The board is the record, by design.
A reboot or a herdr restart takes the agents' processes, not their conversations. A run records which conversations belonged together: the chief and every agent it started, each with its session. Open fleet in a workspace with nothing running and a run to come back to, and it asks:
pick up where you left off
▌ 28m ago · the chief + 2 agents
▌ ENG-2155-fixes, ENG-2155-review, ENG-2155, staging-fix
▌ chief, eng-2155, eng-2155-review
start fresh — a new chief, nothing brought back
Choosing one starts each agent again with claude --resume, in its own repository and its own tab, with its role back in the system prompt and the chief's editing tools still withheld. An agent you took off with x stays off, and one whose conversation is gone from disk is named rather than resumed into an empty session.
~/.claude-fleet/auto-open | directories whose new workspaces open in fleet mode |
FLEET_CLAUDE | the claude to start, by path. Otherwise ~/.local/bin/claude, then whatever is on PATH |
FLEET_DB | the board a command uses. Set for every agent fleet starts |
FLEET_HOST | where agents run: herdr, background or desktop. Otherwise herdr inside it, background outside |
FLEET_JSON=1 | JSON from fleet board reads |
fleet keeps everything under ~/.claude-fleet: each fleet's board, and the briefs each agent was started with (briefs/), which are what it was told, and the Claude Code plugin that carries the /board skill (claude-plugin/). It reads Claude Code's session registry (~/.claude/sessions) to see who is alive, and sends nothing anywhere.
↵ or a click does nothing for an agent in another tab. herdr's serv
hooks/register.tsx 1124 lines1// fleet's mod: messages from the board, delivered by the session itself.
2//
3// Without it, `fleet board msg` types a message into the recipient's herdr
4// pane: one line, cut at 1500 characters, and typed whether or not the agent
5// is in the middle of a turn. With it, this session checks its mailbox on the
6// board every few seconds and, once it is idle, takes what is waiting and
7// submits it as a prompt of its own, whole.
8//
9// The check is also how the board knows the mod is here: a mailbox that
10// stops checking in goes quiet after fifteen seconds, and fleet goes back to
11// typing. So a session without the mod, or one whose mod has died, still
12// gets its messages.
13//
14// It also holds the go-ahead. A worker does not edit until its task has one:
15// `fleet board go` from the chief, or a prompt the person types in the
16// worker's own pane. The chief does not edit at all, Bash included. Both are
17// a guard against an agent drifting into work, not a sandbox: a determined
18// one can write a file in ways no pattern here knows. When the board cannot
19// be asked, the edit goes ahead, as it would without the mod.
20//
21// It gives the session the board as tools: `mcp__fleet__board_start`,
22// `..._msg`, `..._go` and the rest, each running the `fleet board` command of
23// the same name. A tool has a schema to fill in where a shell line has
24// quoting to get wrong, and nothing to mistake for a skill.
25//
26// And in the chief's session it draws the fleet. In herdr the fleet tab sits
27// beside the chief; outside herdr there is no tab, so `/fleet` opens a pane
28// with the crew, the open tasks and the latest messages, a band above the
29// prompt says who needs something, and toasts say what herdr would have
30// notified. It reads `fleet board snapshot` every few seconds; a worker's
31// session stops reading once the board says it is one.
32
33import { atom, read, update } from 'claude-code'
34import type { EngineInterface, Register } from 'claude-code'
35
36import type { GraphSpan, Snapshot } from '../types'
37
38import { HIGH, Seen, crewPane, fleetBand } from './crew'
39
40/** How often the mailbox is checked. Well inside the board's fifteen. */
41const EVERY = 3_000
42
43/** What `fleet board inbox` prints. */
44type Inbox = {
45 agent: string | null
46 text: string | null
47 waiting: number
48 /** The task this worker cannot change files for until it has a go. */
49 awaiting_go?: string | null
50}
51
52/** What `fleet board gate` prints. */
53type Gate = {
54 agent: string | null
55 role: string | null
56 tasks: string[]
57 approved: boolean
58}
59
60/** The tools that change files. */
61const EDITS = new Set(['Edit', 'Write', 'NotebookEdit', 'MultiEdit'])
62
63/** Where writing is fine even for an agent that may not edit. */
64const SCRATCH = String.raw`(?:/dev/|/tmp/|/private/tmp/|\$TMPDIR|"\$TMPDIR)`
65
66/** A command at the start of a pipeline, a list or a substitution. */
67const AT = String.raw`(?:^|[;&|(]\s*|\$\(\s*|\bxargs\s+)`
68
69/**
70 * Whether a shell command writes files outside scratch space, as far as a
71 * pattern can tell. Quoted text is blanked first, so a message that says
72 * "a -> b" is not a redirect.
73 */
74export function writes(command: string): boolean {
75 const bare = command.replace(/'[^']*'/g, "''").replace(/"(?:[^"\\]|\\.)*"/g, '""')
76 const rules = [
77 // > and >> into a file, not 2>&1 and not into /dev/null or /tmp
78 new RegExp(String.raw`(?<![0-9&])>>?\s*(?!&|\s*${SCRATCH})[^\s&|;)]`),
79 new RegExp(String.raw`[0-9]>>?\s*(?!&|\s*${SCRATCH})[^\s&|;)]`),
80 new RegExp(String.raw`${AT}(?:sed|gsed)\s+(?:[^|;&]*\s)?(?:-[a-zA-Z]*i|--in-place)`),
81 new RegExp(String.raw`${AT}perl\s+(?:-[a-zA-Z]*\s+)*-[a-zA-Z]*i`),
82 new RegExp(String.raw`${AT}tee\s+(?!(?:-a\s+)?${SCRATCH})`),
83 new RegExp(String.raw`${AT}(?:cp|mv|rm|touch|mkdir|rmdir|ln|install|truncate|patch|dd)\b(?![^;&|]*\s${SCRATCH}\S*\s*$)`),
84 new RegExp(String.raw`${AT}git\s+(?:-C\s+\S+\s+)?(?:apply|am|checkout|switch|restore|reset|stash|commit|merge|rebase|cherry-pick|revert|mv|rm|clean|pull)\b`),
85 ]
86 return rules.some(rule => rule.test(bare))
87}
88
89/** One of the board's commands, as a tool the model calls. */
90type BoardTool = {
91 name: string
92 description: string
93 properties: Record<string, unknown>
94 required: string[]
95 /** Only the chief plans, dispatches and gives the go. */
96 isChiefs?: true
97 /** The `fleet` command line, from the tool's input and who calls it. */
98 argv: (input: Record<string, unknown>, me: string) => string[]
99}
100
101const str = (description: string) => ({ type: 'string', description })
102const TASK = str('The task key, such as ENG-2553-1')
103
104/** `--flag value` when the value was given. */
105function opt(flag: string, value: unknown): string[] {
106 return typeof value === 'string' && value !== '' ? [flag, value] : []
107}
108
109const BOARD_TOOLS: BoardTool[] = [
110 {
111 name: 'board_ls',
112 description: 'Every task on the board, with its state, its agent and what it waits on.',
113 properties: { state: str('Only tasks in this state: queued, running, blocked, review, done, dropped'), epic: str('Only this epic'), repo: str('Only tasks whose repository path contains this') },
114 required: [],
115 argv: i => ['board', 'ls', ...opt('--state', i.state), ...opt('--epic', i.epic), ...opt('--repo', i.repo)],
116 },
117 {
118 name: 'board_show',
119 description: 'One task: its brief, and everything that happened to it.',
120 properties: { task: TASK },
121 required: ['task'],
122 argv: i => ['board', 'show', String(i.task)],
123 },
124 {
125 name: 'board_ready',
126 description: 'Queued tasks whose dependencies are all done: what can be dispatched now.',
127 properties: {},
128 required: [],
129 argv: () => ['board', 'ready'],
130 },
131 {
132 name: 'board_start',
133 description: 'Mark a task running: you have picked it up.',
134 properties: { task: TASK },
135 required: ['task'],
136 argv: i => ['board', 'start', String(i.task)],
137 },
138 {
139 name: 'board_block',
140 description: 'Mark a task blocked, with why. Tell the chief as well.',
141 properties: { task: TASK, reason: str('What it is waiting for') },
142 required: ['task', 'reason'],
143 argv: i => ['board', 'block', String(i.task), String(i.reason)],
144 },
145 {
146 name: 'board_unblock',
147 description: 'Carry on with a blocked task.',
148 properties: { task: TASK },
149 required: ['task'],
150 argv: i => ['board', 'unblock', String(i.task)],
151 },
152 {
153 name: 'board_review',
154 description: 'Open a task for review rather than finished.',
155 properties: { task: TASK, mr: str('The merge or pull request URL') },
156 required: ['task'],
157 argv: i => ['board', 'review', String(i.task), ...opt('--mr', i.mr)],
158 },
159 {
160 name: 'board_done',
161 description: 'Finish a task. Says which tasks that freed.',
162 properties: { task: TASK, mr: str('The merge or pull request URL') },
163 required: ['task'],
164 argv: i => ['board', 'done', String(i.task), ...opt('--mr', i.mr)],
165 },
166 {
167 name: 'board_msg',
168 description: 'Send another agent a message, recorded on the board and delivered to them. You are the sender.',
169 properties: { to: str('The agent, by its board name: chief, or a worker'), summary: str('One line'), body: str('The rest, if there is more'), task: TASK },
170 required: ['to', 'summary'],
171 argv: (i, me) => ['board', 'msg', me, String(i.to), String(i.summary), ...opt('--body', i.body), ...opt('--task', i.task)],
172 },
173 {
174 name: 'board_note',
175 description: 'Record something on the board that is not a message to anyone.',
176 properties: { summary: str('One line'), body: str('The rest'), task: TASK },
177 required: ['summary'],
178 argv: i => ['board', 'note', String(i.summary), ...opt('--body', i.body), ...opt('--task', i.task)],
179 },
180 {
181 name: 'board_add',
182 description: 'Queue a task for a repository.',
183 properties: {
184 task: TASK,
185 repo: str('The repository, as an absolute path'),
186 title: str('A short title'),
187 body: str('What a fresh agent in that repository needs in order to start'),
188 epic: str('The epic it belongs to'),
189 deps: { type: 'array', items: { type: 'string' }, description: 'Tasks it waits on' },
190 },
191 required: ['task', 'repo', 'title'],
192 isChiefs: true,
193 argv: i => [
194 'board', 'add', String(i.task), String(i.repo), String(i.title),
195 ...opt('--epic', i.epic), ...opt('--body', i.body),
196 ...(Array.isArray(i.deps) ? i.deps.flatMap(d => ['--dep', String(d)]) : []),
197 ],
198 },
199 {
200 name: 'board_dep',
201 description: 'Record that one task waits on another.',
202 properties: { task: TASK, depends_on: str('The task it waits on') },
203 required: ['task', 'depends_on'],
204 isChiefs: true,
205 argv: i => ['board', 'dep', String(i.task), String(i.depends_on)],
206 },
207 {
208 name: 'board_epic',
209 description: 'Create or retitle an epic.',
210 properties: { key: str('The epic key, such as ENG-2553'), title: str('Its title') },
211 required: ['key', 'title'],
212 isChiefs: true,
213 argv: i => ['board', 'epic', String(i.key), String(i.title)],
214 },
215 {
216 name: 'board_claim',
217 description: 'Assign a task to an agent.',
218 properties: { task: TASK, agent: str('The agent, by its board name') },
219 required: ['task', 'agent'],
220 isChiefs: true,
221 argv: i => ['board', 'claim', String(i.task), String(i.agent)],
222 },
223 {
224 name: 'board_go',
225 description: "Give a worker the go-ahead on its task, and tell it. Until a task has one, its worker cannot change files. Anything short of a go is board_msg.",
226 properties: { task: TASK, message: str('What to send with it; "go" when not given'), body: str('More, if there is more') },
227 required: ['task'],
228 isChiefs: true,
229 argv: i => ['board', 'go', String(i.task), ...(typeof i.message === 'string' && i.message ? [i.message] : []), ...opt('--body', i.body)],
230 },
231 {
232 name: 'board_drop',
233 description: 'Abandon a task.',
234 properties: { task: TASK, reason: str('Why') },
235 required: ['task'],
236 isChiefs: true,
237 argv: i => ['board', 'drop', String(i.task), ...(typeof i.reason === 'string' && i.reason ? [i.reason] : [])],
238 },
239 {
240 name: 'spawn',
241 description:
242 'Start an agent in a repository, briefed on its task, and claim the task for it. ' +
243 'With host "desktop" it only registers the agent and says what to pass to start_session.',
244 properties: {
245 name: str('What to call it, usually after the repository'),
246 repo: str('The repository, as an absolute path'),
247 task: TASK,
248 host: { type: 'string', enum: ['herdr', 'background', 'desktop'], description: 'Where it runs; FLEET_HOST by default' },
249 },
250 required: ['name', 'repo'],
251 isChiefs: true,
252 argv: i => ['spawn', String(i.name), '--repo', String(i.repo), ...opt('--task', i.task), ...opt('--host', i.host)],
253 },
254 {
255 name: 'handoff',
256 description: "Hand an agent's task to a fresh session of it, for one nearly out of context.",
257 properties: { agent: str('The agent'), note: str('Anything the new session should know that the board does not say'), now: { type: 'boolean', description: 'Close the old session even mid-turn' } },
258 required: ['agent'],
259 isChiefs: true,
260 argv: i => ['handoff', String(i.agent), ...opt('--note', i.note), ...(i.now === true ? ['--now'] : [])],
261 },
262 {
263 name: 'retire',
264 description: "Take an agent off the board once its work is done, and close its tab or background session.",
265 properties: { name: str('The agent') },
266 required: ['name'],
267 isChiefs: true,
268 argv: i => ['board', 'retire', String(i.name)],
269 },
270]
271
272/** What Claude Code calls a tool of this plugin's. */
273const TOOL_PREFIX = 'mcp__fleet__'
274
275/** Run a board tool as the agent `me`, and answer with what fleet said. */
276async function runBoardTool($: EngineInterface, tool: BoardTool, input: Record<string, unknown>, me: string) {
277 try {
278 // spawn and handoff wait for the new session to report.
279 const out = await $.process.run(['fleet', ...tool.argv(input, me)], { timeoutMs: 120_000 })
280 const said = (out.stdout + out.stderr).trim() || 'done'
281 return out.exitCode === 0 ? { result: said } : { isError: true as const, result: said }
282 } catch (err) {
283 return { isError: true as const, result: `fleet could not be run: ${String(err)}` }
284 }
285}
286
287/** Register the board's tools in this session. */
288async function registerTools($: EngineInterface) {
289 for (const t of BOARD_TOOLS) {
290 try {
291 await $.tool.register({ name: t.name, description: t.description, inputSchema: { type: 'object', properties: t.properties, required: t.required } })
292 } catch {
293 // A name already taken: the `fleet board` command still is.
294 }
295 }
296}
297
298/**
299 * Where the `fleet` to start with is, or why there is none. The one that
300 * matches this plugin first, so the mod and the board agree on what they
301 * say to each other: FLEET_BIN when set, for working on fleet itself; then
302 * the copy in this plugin's folder, fetched now if it is not there yet or
303 * is another version than the plugin's; and only then whatever fleet is on
304 * PATH, or the other version when there is none.
305 */
306async function findFleet($: EngineInterface): Promise<{ path: string } | { problem: string }> {
307 const given = await $.env.get('FLEET_BIN')
308 if (given) return { path: given }
309 const own = `${$.plugin.root}/bin/fleet`
310 const there = (await $.process.run(['test', '-x', own])).exitCode === 0
311 if (there) {
312 const wanted = await pluginVersion($)
313 if (!wanted || (await versionOf($, own)) === `fleet ${wanted}`) return { path: own }
314 }
315 const fetched = await $.process.run(['sh', `${$.plugin.root}/scripts/fetch-fleet.sh`], { timeoutMs: 120_000 })
316 if (fetched.exitCode === 0) return { path: own }
317 const onPath = await $.process.run(['sh', '-c', 'command -v fleet'])
318 if (onPath.exitCode === 0 && onPath.stdout.trim()) return { path: onPath.stdout.trim() }
319 if (there) return { path: own }
320 return { problem: (fetched.stderr || fetched.stdout).trim() || 'fleet could not be downloaded' }
321}
322
323/** The plugin's version, as its manifest names it: fleet's own, too. */
324async function pluginVersion($: EngineInterface): Promise<string | undefined> {
325 try {
326 const manifest = JSON.parse(await $.fs.read(`${$.plugin.root}/.claude-plugin/plugin.json`)) as { version?: unknown }
327 return typeof manifest.version === 'string' ? manifest.version : undefined
328 } catch {
329 return undefined
330 }
331}
332
333/** What `fleet --version` says, as `fleet 0.17.2`; undefined when it does not run. */
334async function versionOf($: EngineInterface, fleet: string): Promise<string | undefined> {
335 try {
336 const out = await $.process.run([fleet, '--version'], { timeoutMs: 10_000 })
337 return out.exitCode === 0 ? out.stdout.trim() : undefined
338 } catch {
339 return undefined
340 }
341}
342
343/** What `fleet chief --adopt` prints. */
344type Adopted = { board: string; run: number; bin: string | null; brief: string }
345
346/** What `fleet join` prints: the same, for a worker. */
347type Joined = Adopted
348
349/** The tool a desktop worker joins the board with: see `join`. */
350const JOIN = {
351 name: 'join',
352 description:
353 "Join a fleet's board as the agent a fleet brief names. Call it only when a fleet brief tells you to, " +
354 'with the board, run and name the brief gives.',
355 inputSchema: {
356 type: 'object',
357 properties: {
358 board: str("The board's path, from the brief"),
359 run: { type: 'number', description: 'The run, from the brief' },
360 name: str("This agent's name, from the brief"),
361 },
362 required: ['board', 'run', 'name'],
363 },
364} as const
365
366/**
367 * A plain `fleet board`, `fleet spawn` or `fleet handoff` command: what a
368 * fleet session runs without being asked. Anything that chains, pipes,
369 * redirects or substitutes is left to the usual prompt.
370 */
371const FLEET_COMMAND = /^\s*fleet\s+(?:board|spawn|handoff)\b[^;&|`$<>\n]*$/
372
373/** A worker reaching for the go-ahead it is waiting for. */
374const SELF_APPROVAL = /\bfleet\s+board\s+(?:go|gate)\b/
375
376/**
377 * Ask the board whether `session` may edit, and with `approve`, give its
378 * task the user's go first. Undefined when the board cannot be asked.
379 */
380async function gate($: EngineInterface, session: string, approve = false): Promise<Gate | undefined> {
381 const argv = ['fleet', 'board', 'gate', '--session', session]
382 if (approve) argv.push('--user-approves')
383 try {
384 const out = await $.process.run(argv, { timeoutMs: 10_000 })
385 return out.exitCode === 0 ? (JSON.parse(out.stdout) as Gate) : undefined
386 } catch {
387 return undefined
388 }
389}
390
391const PANE = 'fleet'
392
393const snapshot = atom({ plugin: 'fleet', key: 'snapshot' } as const, null)
394const brief = atom({ plugin: 'fleet', key: 'brief' } as const, null)
395const offer = atom({ plugin: 'fleet', key: 'offer' } as const, false)
396const paneOpen = atom({ plugin: 'fleet', key: 'paneOpen' } as const, false)
397const starting = atom({ plugin: 'fleet', key: 'starting' } as const, false)
398
399/** The board as `session` sees it; undefined when it cannot be read. */
400async function look($: EngineInterface, session: string): Promise<Snapshot | undefined> {
401 try {
402 const out = await $.process.run(['fleet', 'board', 'snapshot', '--session', session], { timeoutMs: 10_000 })
403 return out.exitCode === 0 ? (JSON.parse(out.stdout) as Snapshot) : undefined
404 } catch {
405 return undefined
406 }
407}
408
409/** A key as `fleet board view-send` names it, with its modifiers. */
410function keyWords(e: { key: string; ctrl: boolean; shift: boolean; meta: boolean }): string[] | undefined {
411 const name = e.key === ' ' ? 'space' : e.key
412 if (!name || /\s/.test(name)) return undefined
413 return ['key', name, ...(e.ctrl ? ['ctrl'] : []), ...(e.shift ? ['shift'] : []), ...(e.meta ? ['alt'] : [])]
414}
415
416/** Send the followed view one message: a key, a click or its size. */
417async function sendView($: EngineInterface, control: string, words: string[]) {
418 try {
419 await $.process.run(['fleet', 'board', 'view-send', '--control', control, ...words], { timeoutMs: 5_000 })
420 } catch {
421 // The view has ended: the next tick starts another.
422 }
423}
424
425/** Give a waiting agent its go, as the chief would with `fleet board go`. */
426async function give($: EngineInterface, task: string) {
427 try {
428 const out = await $.process.run(['fleet', 'board', 'go', task], { timeoutMs: 10_000 })
429 $.ui.toast(out.exitCode === 0 ? `${task}: go given` : `${task}: ${out.stderr.trim() || 'the go did not go through'}`)
430 } catch {
431 $.ui.toast(`${task}: fleet could not be run`)
432 }
433}
434
435/** One directory a line; `#` starts a comment, and `~` is the home directory. */
436export function rootsFrom(text: string, home: string): string[] {
437 return text
438 .split('\n')
439 .map(l => (l.split('#')[0] ?? '').trim())
440 .filter(l => l !== '')
441 .map(l => (l === '~' || l.startsWith('~/') ? home + l.slice(1) : l))
442}
443
444/**
445 * Whether `root` is listed in ~/.claude-fleet/auto-open, the workspaces
446 * herdr opens in fleet mode: there the band offers to start a fleet. The
447 * same directory however it is spelled, as fleet matches it: macOS's /tmp is
448 * /private/tmp.
449 */
450async function listed($: EngineInterface, root: string): Promise<boolean> {
451 const home = await $.env.get('HOME')
452 if (!home) return false
453 let text: string
454 try {
455 const read = await $.fs.read(`${home}/.claude-fleet/auto-open`)
456 if (typeof read !== 'string') return false
457 text = read
458 } catch {
459 return false
460 }
461 const dirs = rootsFrom(text, home)
462 if (dirs.length === 0) return false
463 if (dirs.includes(root)) return true
464 try {
465 const out = await $.process.run(
466 ['sh', '-c', 'for d; do (cd "$d" 2>/dev/null && pwd -P) || echo; done', 'sh', root, ...dirs],
467 { timeoutMs: 5_000 },
468 )
469 const [want, ...got] = out.stdout.split('\n')
470 return want !== undefined && want !== '' && got.includes(want)
471 } catch {
472 return false
473 }
474}
475
476/**
477 * Make `session` the chief of its workspace, as `/fleet start` does: put it
478 * on the board, give it the board's tools and fleet on its PATH, and submit
479 * the chief's brief. What went wrong, when it could not.
480 */
481async function adopt($: EngineInterface, session: string): Promise<{ root: string } | { problem: string }> {
482 const root = await $.session.root()
483 let adopted: Adopted
484 try {
485 const found = await findFleet($)
486 if ('problem' in found) return { problem: `${found.problem}\nInstall fleet another way (see its README), then run /fleet start again.` }
487 const out = await $.process.run([found.path, 'chief', '--adopt', session, '--root', root], { timeoutMs: 20_000 })
488 if (out.exitCode !== 0) return { problem: `fleet: ${(out.stderr || out.stdout).trim()}` }
489 adopted = JSON.parse(out.stdout) as Adopted
490 } catch (err) {
491 return { problem: `fleet could not be started: ${String(err)}` }
492 }
493 // What a session fleet starts is given on its command line: the board,
494 // the run, and fleet itself on PATH, for this session's processes and
495 // the agents it starts.
496 await $.env.set('FLEET_DB', adopted.board)
497 await $.env.set('FLEET_RUN', String(adopted.run))
498 if (adopted.bin) await $.env.set('PATH', `${adopted.bin}:${(await $.env.get('PATH')) ?? ''}`)
499 await registerTools($)
500 // The chief's brief, as a turn of its own: Claude Code keeps a mod
501 // installed by a user out of the system prompt. From a timer, since a
502 // command cannot wait on a turn while it holds this one.
503 $.clock.after(1, () => { void $.prompt.submit({ text: adopted.brief }) })
504 // Kept for compaction, which summarises a turn like any other.
505 await update($, brief, () => adopted.brief)
506 await update($, offer, () => false)
507 return { root }
508}
509
510/**
511 * Put `session` on the board as the desktop worker the chief started it
512 * as, as `/fleet start` does for the chief: the board and the run in its
513 * environment, fleet on its PATH, the board's tools. Its brief came as its
514 * first prompt, which compaction summarises: kept for that.
515 */
516async function join($: EngineInterface, session: string, input: Record<string, unknown>): Promise<Joined | { problem: string }> {
517 const name = typeof input.name === 'string' ? input.name : ''
518 const board = typeof input.board === 'string' ? input.board : ''
519 const run = typeof input.run === 'number' ? input.run : Number(input.run)
520 if (!name || !board || !Number.isInteger(run)) return { problem: 'fleet: join needs the board, the run and the name the brief gives' }
521 let joined: Joined
522 try {
523 const found = await findFleet($)
524 if ('problem' in found) return { problem: `fleet: ${found.problem}` }
525 const out = await $.process.run(
526 [found.path, 'join', name, '--session', session, '--run', String(run), '--db', board],
527 { timeoutMs: 20_000 },
528 )
529 if (out.exitCode !== 0) return { problem: `fleet: ${(out.stderr || out.stdout).trim()}` }
530 joined = JSON.parse(out.stdout) as Joined
531 } catch (err) {
532 return { problem: `fleet could not be run: ${String(err)}` }
533 }
534 await $.env.set('FLEET_DB', joined.board)
535 await $.env.set('FLEET_RUN', String(joined.run))
536 if (joined.bin) await $.env.set('PATH', `${joined.bin}:${(await $.env.get('PATH')) ?? ''}`)
537 await registerTools($)
538 await update($, brief, () => joined.brief)
539 return joined
540}
541
542/**
543 * Whether the fleet pane is up, as the engine has it: the desktop app's
544 * panel can be put away without the pane being closed, so `ui.close` alone
545 * does not say. Kept in `paneOpen`, which redraws the band when it changes.
546 */
547async function paneShown($: EngineInterface): Promise<boolean> {
548 try {
549 const up = (await $.ui.panes()).some(p => p.id === PANE && p.isShown && p.isPlaced)
550 if (up !== (await read($, paneOpen))) await update($, paneOpen, () => up)
551 return up
552 } catch {
553 return read($, paneOpen)
554 }
555}
556
557/** Open the fleet pane; whether it is drawn now. */
558async function openPane($: EngineInterface): Promise<boolean> {
559 const opened = await $.ui.open({ id: PANE, title: 'fleet' })
560 await update($, paneOpen, () => true)
561 return opened.isPlaced
562}
563
564/** Hand an agent nearly out of context to a fresh session of it. */
565async function handoff($: EngineInterface, agent: string) {
566 $.ui.toast(`${agent}: handing off to a fresh session…`)
567 try {
568 const out = await $.process.run(['fleet', 'handoff', agent], { timeoutMs: 120_000 })
569 $.ui.toast(out.exitCode === 0 ? `${agent}: handed off` : `${agent}: ${(out.stderr || out.stdout).trim() || 'the handoff did not go through'}`)
570 } catch {
571 $.ui.toast(`${agent}: fleet could not be run`)
572 }
573}
574
575/** What needs the user, for the band and its count. */
576/**
577 * Toast what is new since `seen`, and return what holds now. `seen` is
578 * undefined until the first read, which marks everything already there as
579 * seen: opening the chief must not replay yesterday's blockers.
580 */
581function notify($: EngineInterface, s: Snapshot, seen: Set<string> | undefined): Set<string> {
582 const now = new Set<string>()
583 const said: string[] = []
584 for (const e of s.events) {
585 if (!e.notice) continue
586 now.add(`event:${e.key}`)
587 if (seen && !seen.has(`event:${e.key}`)) said.push(`${e.notice.title} — ${e.notice.body}`)
588 }
589 for (const a of s.agents) {
590 const marks: [string, string][] = []
591 if (a.waiting_for) marks.push([`ask:${a.name}:${a.waiting_for}`, `fleet · ${a.name} is waiting at a ${a.waiting_for}`])
592 if (a.awaiting_go && a.presence === 'waiting') {
593 marks.push([`go:${a.name}:${a.awaiting_go}`, `fleet · ${a.name} needs a go on ${a.awaiting_go}`])
594 }
595 if (a.context !== null && a.context >= HIGH) {
596 marks.push([`full:${a.name}`, `fleet · ${a.name} is at ${a.context}% context: \`fleet handoff ${a.name}\``])
597 }
598 for (const [mark, text] of marks) {
599 now.add(mark)
600 if (seen && !seen.has(mark)) said.push(text)
601 }
602 }
603 for (const text of said) $.ui.toast(text)
604 // Only what still holds, so a later wait or climb is news again.
605 return now
606}
607
608export const register: Register = on => {
609 // The session's id, once it has started.
610 let session: string | undefined
611 // Whether it is part of a fleet: started by one (FLEET_DB is set), or made
612 // its chief with /fleet start. Until then the plugin does nothing at all.
613 let active = false
614
615 // The view's own: see the header.
616 // Set once the board says this session is a worker: it draws nothing.
617 let isWorker = false
618 let looking = false
619 // The fleet view behind the pane: `fleet board view --follow`, started
620 // when the pane first asks for a frame and stopped when it closes. Its
621 // newest frame, numbered, and the number the pane last got.
622 let view: { control: string; size: { w: number; h: number } } | undefined
623 let frame: GraphSpan[][] = []
624 let frameNumber = 0
625 let shownNumber = -1
626 // What has been toasted already: see notify.
627 let seen: Set<string> | undefined
628 // When the pane first saw each message, for the graph's dots in flight,
629 // and the redraw that takes the youngest away once it has landed.
630 const arrived = new Seen()
631 let landing: { at: number; cancel: () => void } | undefined
632
633 // A desktop worker, joined with `mcp__fleet__join`. Its messages come
634 // from the chief's model, through the app: its mod leaves them on the board.
635 let desktop = false
636 // The mod's work, started once: see session.start. A desktop worker's
637 // join starts it too, since nobody may have opened that session yet.
638 let boot: (() => Promise<void>) | undefined
639 let booted = false
640
641 // A turn is running. Messages wait on the board until it ends, rather than
642 // queueing up as prompts behind it.
643 let busy = false
644 // A prompt was submitted and its turn has not started yet. Taking more now
645 // would stack a second prompt behind the first.
646 let pending = false
647 // A check is still running. The timer does not wait for one to finish.
648 let checking = false
649 // The main loop's tools running now, newest last: what the fleet view
650 // shows the agent doing. Several run at once when Claude calls them in
651 // parallel.
652 const running: string[] = []
653
654 on('session.start', async ($, e, next) => {
655 // The mod's work starts once a person can be at the session: at once in
656 // the terminal, and once a surface attaches where the desktop app hosts
657 // the session through the SDK, which starts it with no surface and not
658 // interactive. A `claude -p` run never has one, and is left alone.
659 // How a desktop session the chief started joins its fleet: the app
660 // wraps the first prompt, so a slash command there never runs. At once,
661 // not at boot: the app starts that session with no surface, and it may
662 // have none until the user opens it.
663 try {
664 await $.tool.register(JOIN)
665 } catch {
666 // A name already taken: the session cannot join, and says so.
667 }
668
669 boot = async () => {
670 if (booted) return
671 booted = true
672 const id = await $.session.id()
673 session = id
674 // /fleet, in every session with the plugin: in one fleet started it
675 // shows the fleet, in any other `/fleet start` makes it the chief.
676 try {
677 await $.command.register({ name: 'fleet', description: 'Show the fleet, or `/fleet start` to make this session its chief', argumentHint: '[start]' })
678 } catch {
679 // A command of that name already: the band and toasts still work.
680 }
681 // A session fleet started has a board from the start. Any other waits
682 // for /fleet start, and the timers below do nothing until then.
683 active = Boolean(await $.env.get('FLEET_DB'))
684 // A workspace listed in auto-open: the band offers to start a fleet.
685 if (!active) {
686 const offered = await listed($, await $.session.root())
687 await update($, offer, () => offered)
688 }
689 // The board as tools. Which ones the chief alone may use is settled when
690 // they are called: a session is put on the board, and so has a role,
691 // only after it starts.
692 if (active) await registerTools($)
693
694 const check = async () => {
695 if (!active || checking) return
696 checking = true
697 try {
698 // A draft in the prompt box: the person is mid-sentence, and a
699 // message submitted now would go out with what they typed so far.
700 const drafting = (await $.prompt.read()).text.trim() !== ''
701 const take = !busy && !pending && !drafting && !desktop
702 const argv = ['fleet', 'board', 'inbox', '--session', id]
703 if (take) argv.push('--take')
704 const tool = running.at(-1)
705 if (tool) argv.push('--tool', tool)
706 try {
707 const { context } = await $.session.usage()
708 if (context.percent !== undefined) argv.push('--context', String(Math.round(context.percent)))
709 } catch {
710 // No reading yet, before the first answer: nothing to say.
711 }
712 const out = await $.process.run(argv, { timeoutMs: 10_000 })
713 if (out.exitCode !== 0) return
714 const inbox = JSON.parse(out.stdout) as Inbox
715 if (inbox.text) {
716 pending = true
717 // Not awaited: it resolves when the turn starts, and the mailbox
718 // has to keep checking in meanwhile or the board stops trusting it.
719 $.prompt.submit({ text: inbox.text }).then(
720 () => { pending = false },
721 () => { pending = false },
722 )
723 }
724 const parts: string[] = []
725 if (inbox.awaiting_go) parts.push(`waiting for a go on ${inbox.awaiting_go}`)
726 if (inbox.waiting > 0) {
727 const until = busy || pending ? 'this turn to end' : 'your draft to be sent'
728 parts.push(`${inbox.waiting} ${inbox.waiting === 1 ? 'message' : 'messages'} waiting for ${until}`)
729 }
730 $.ui.status(parts.length ? parts.join(' · ') : undefined)
731 } catch {
732 // fleet not on PATH, a board locked past the timeout, output that is
733 // not JSON: the next check tries again, and while none succeeds the
734 // board falls back to typing.
735 } finally {
736 checking = false
737 }
738 }
739
740 $.clock.every(EVERY, () => { void check() })
741 void check()
742
743 // The chief's view, in every fleet session, since which one is the chief
744 // is only known once the board has linked it.
745 const watch = $.clock.every(EVERY, async () => {
746 if (!active || isWorker || looking) return
747 looking = true
748 try {
749 const s = await look($, id)
750 if (!s) return
751 if (s.me?.role === 'worker') {
752 isWorker = true
753 watch.cancel()
754 return
755 }
756 // Not linked yet: a session is put on the board a few seconds after
757 // it starts.
758 if (s.me?.role !== 'chief') return
759 arrived.track(s.events, await $.clock.now())
760 await update($, snapshot, () => s)
761 await paneShown($)
762 seen = notify($, s, seen)
763
764 } finally {
765 looking = false
766 }
767 })
768 }
769
770 // A surface already attached: the desktop app's session, reloaded.
771 if (e.isInteractive || (await $.session.surfaces()).length > 0) {
772 await boot()
773 } else {
774 const wait = $.clock.every(1_000, async () => {
775 if (booted) {
776 wait.cancel()
777 return
778 }
779 if ((await $.session.surfaces()).length === 0) return
780 wait.cancel()
781 await boot?.()
782 })
783 }
784 return next(e)
785 })
786
787 // The person typing in this pane is the user's own go-ahead. Three things
788 // arrive the same way and are not: the brief fleet starts an agent with,
789 // given on the command line, which is always a new session's first prompt
790 // (a resumed one has turns already); a message fleet typed here because
791 // the mod was not checking in; and a slash command.
792 on('prompt.submit', async ($, e, next) => {
793 const typed = e.origin?.kind === 'composer' || e.origin?.kind === 'bridge'
794 const text = e.text.trimStart()
795 if (
796 active && session && typed && !text.startsWith('[fleet ·') && !text.startsWith('/') &&
797 (await $.session.turns()) > 0
798 ) {
799 await gate($, session, true)
800 }
801 return next(e)
802 })
803
804 on('tool.call', async ($, e, next) => {
805 // The main loop's tool, not a subagent's: those run under the main
806 // loop's Agent call, which is what the fleet view says it is doing.
807 const main = session !== undefined && e.agentId === undefined
808 if (main) running.push(e.tool)
809 try {
810 if (e.tool === TOOL_PREFIX + JOIN.name) {
811 if (active) return { isError: true as const, result: 'fleet: this session is part of a fleet already' }
812 const joined = await join($, session ?? (await $.session.id()), e as unknown as Record<string, unknown>)
813 if ('problem' in joined) return { isError: true as const, result: joined.problem }
814 desktop = true
815 // Its check-in, the board's tools and the rest, now that it has a board.
816 await boot?.()
817 active = true
818 return { result: `Joined the fleet's board (run ${joined.run}). The board's tools, mcp__fleet__board_*, are yours now. Carry on with your brief.` }
819 }
820 const boardTool = active && session && e.tool.startsWith(TOOL_PREFIX)
821 ? BOARD_TOOLS.find(t => TOOL_PREFIX + t.name === e.tool)
822 : undefined
823 if (boardTool && session) {
824 const g = await gate($, session)
825 if (!g?.agent) return { isError: true as const, result: 'fleet: this session is not on the board yet; try again in a moment' }
826 if (g.role === 'retired') return { deny: `fleet: this session of ${g.agent} was retired, and changes nothing more.` }
827 if (boardTool.isChiefs && g.role !== 'chief') {
828 return { deny: `fleet: ${boardTool.name} is the chief's. Ask the chief with board_msg.` }
829 }
830 return await runBoardTool($, boardTool, e as unknown as Record<string, unknown>, g.agent)
831 }
832 const edit = EDITS.has(e.tool)
833 const command = e.tool === 'Bash' && typeof e.command === 'string' ? e.command : undefined
834 if (!active || !session || (!edit && command === undefined)) return await next(e)
835 if (command !== undefined && !writes(command) && !SELF_APPROVAL.test(command)) return await next(e)
836
837 const g = await gate($, session)
838 if (!g?.agent) return await next(e)
839
840 // Retired, or handed off to a fresh session that carries on: what
841 // this one changes now, the other does not know about.
842 if (g.role === 'retired') {
843 return {
844 deny:
845 `fleet: this session of ${g.agent} was retired, and changes nothing more. ` +
846 'If its task was handed off, a fresh session is carrying on with it.',
847 }
848 }
849
850 if (g.role === 'chief') {
851 if (edit || (command !== undefined && writes(command))) {
852 return {
853 deny:
854 'fleet: the chief of staff does not change files, through Bash either. ' +
855 'Put the work on the board and give it to the agent for that repository.',
856 }
857 }
858 return await next(e)
859 }
860
861 if (command !== undefined && SELF_APPROVAL.test(command)) {
862 return { deny: `fleet: a go-ahead comes from the chief or the user, not from ${g.agent}.` }
863 }
864 if (g.approved) return await next(e)
865 const task = g.tasks.join(', ')
866 return {
867 deny:
868 `fleet: ${task} has no go-ahead yet, so ${g.agent} does not change files. ` +
869 `Send the chief your plan with \`fleet board msg ${g.agent} chief '...'\` and wait for its go, ` +
870 'or for the user to answer you here.',
871 }
872 } finally {
873 if (main) running.splice(running.lastIndexOf(e.tool), 1)
874 }
875 })
876
877 // A chief made with /fleet start has its brief as a turn, and compaction
878 // summarises turns: put the brief back at the head of what is kept. A
879 // chief fleet started has it in its system prompt, which compaction
880 // leaves alone, so it has nothing here to put back.
881 on('session.compact', async ($, e, next) => {
882 const compacted = await next(e)
883 const kept = await read($, brief)
884 if (!active || !kept || e.agentId !== undefined || !('messages' in compacted) || !compacted.messages) {
885 return compacted
886 }
887 const reminder = {
888 role: 'user' as const,
889 text: desktop
890 ? `[fleet] You are an agent of a fleet. Your brief, kept through compaction:\n\n${kept}`
891 : `[fleet] You are this workspace's chief of staff. Your brief, kept through compaction:\n\n${kept}`,
892 toolUses: [],
893 }
894 return { ...compacted, messages: [reminder, ...compacted.messages] }
895 })
896
897 // fleet's own tools and plain fleet commands need no prompt in a fleet
898 // session: an agent started by fleet has them allowed on its command
899 // line, and a session made the chief with /fleet start has this.
900 on('tool.check', ($, e, next) => {
901 if (!active) return next(e)
902 if (e.tool.startsWith(TOOL_PREFIX)) return { decision: 'allow' as const }
903 const command = (e.input as { command?: unknown } | null)?.command
904 if (e.tool === 'Bash' && typeof command === 'string' && FLEET_COMMAND.test(command)) {
905 return { decision: 'allow' as const }
906 }
907 return next(e)
908 })
909
910 on('turn.start', ($, e, next) => {
911 busy = true
912 pending = false
913 return next(e)
914 })
915
916 on('turn.complete', async ($, e, next) => {
917 const done = await next(e)
918 // A subagent's run ends with a turn.complete of its own, in the middle
919 // of the main loop's turn; only the main loop's says the session is idle.
920 if (e.agentId === undefined) busy = false
921 return done
922 })
923
924 on('command.run', { command: 'fleet' }, async ($, e) => {
925 if (e.args.trim() === 'start') {
926 if (active) return { text: 'This session is part of a fleet already. /fleet shows it.' }
927 if (!session) return { text: 'This session has not started yet.' }
928 const started = await adopt($, session)
929 if ('problem' in started) return { text: started.problem }
930 active = true
931 await openPane($)
932 return { text: `This session is the chief of ${started.root} now. Its brief follows; the fleet pane shows the crew.` }
933 }
934 if (!active) return { text: 'This session is not part of a fleet. `/fleet start` makes it the chief of this workspace.' }
935 if (isWorker) return { text: "The fleet is drawn in the chief's session." }
936 return (await openPane($)) ? {} : { text: 'Widen the terminal to see the fleet pane.' }
937 })
938
939 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
940 const s = await read($, snapshot)
941 // The desktop app and the phone draw the fleet natively, from the
942 // snapshot: see crew.tsx.
943 if (e.surface !== 'terminal') {
944 const el = $.ui.resolve(e)
945 if (!s) return <el.Text dimColor>Reading the board…</el.Text>
946 const now = await $.clock.now()
947 const at = arrived.track(s.events, now)
948 // The graph is remembered per workspace and surface; until it is
949 // pressed, it is on where there is room for it and off on a phone.
950 const key = `graph:${e.surface}:${await $.session.root()}`
951 const stored = await $.store.get(key).catch(() => undefined)
952 const showGraph = typeof stored === 'boolean' ? stored : e.surface !== 'mobile'
953 // Draw again once the youngest message in flight has landed.
954 const end = arrived.nextExpiry(now)
955 if (showGraph && end !== undefined && landing?.at !== end) {
956 landing?.cancel()
957 const timer = $.clock.after(end - now + 50, () => {
958 landing = undefined
959 $.ui.invalidate('ui.render')
960 })
961 landing = { at: end, cancel: () => timer.cancel() }
962 }
963 return crewPane(el, s, { go: task => void give($, task), handoff: agent => void handoff($, agent) }, {
964 columns: e.props.bodyColumns ?? 80,
965 showGraph,
966 toggleGraph: () => {
967 void (async () => {
968 await $.store.set(key, !showGraph).catch(() => undefined)
969 $.ui.invalidate('ui.render')
970 })()
971 },
972 seen: at,
973 now,
974 })
975 }
976 const { Box, Button, Client, Text } = $.ui.resolve(e)
977 if (!s) return <Text dimColor>Reading the board…</Text>
978 const waiting = s.agents.filter(a => a.awaiting_go && a.presence === 'waiting')
979 // The fleet tab, live: fleet draws it, the Client shows it and takes its
980 // keys. Beneath it, while a worker waits, the go the tab gives by keys.
981 // The rows the pane shows, not the terminal's: the prompt and the
982 // status take the bottom of the screen.
983 const shown = e.props.scroll?.bodyRows ?? (e.viewport?.rows ?? 30) - 8
984 const rows = Math.max(10, shown - (waiting.length > 0 ? 1 : 0))
985 return (
986 <Box flexDirection="column" width={Math.max(40, e.props.bodyColumns ?? 80)}>
987 <Client key="fleet-view" module="./view.tsx" props={{ lines: frame }} width="100%" height={rows} />
988 {waiting.length > 0 && (
989 <Box flexDirection="row" gap={1}>
990 <Text> Waiting for a go:</Text>
991 {waiting.map(a => (
992 <Button key={`go-${a.name}`} label={`go ${a.awaiting_go}`} onPress={() => give($, a.awaiting_go ?? '')} />
993 ))}
994 </Box>
995 )}
996 </Box>
997 )
998 })
999
1000 // What the pane's view posts: a tick asking for a newer frame, with its
1001 // size; a key; a click.
1002 on('ui.message', async ($, e, next) => {
1003 const data = e.data as { t?: string; w?: number; h?: number; key?: string; ctrl?: boolean; shift?: boolean; meta?: boolean; x?: number; y?: number }
1004 if (!active || !session) return next(e)
1005 if (data.t === 'tick' && typeof data.w === 'number' && typeof data.h === 'number' && data.w > 0 && data.h > 0) {
1006 const size = { w: data.w, h: data.h }
1007 if (!view) {
1008 const home = (await $.env.get('HOME')) ?? '/tmp'
1009 // Short: a socket's path has a hundred characters or so to fit in.
1010 const control = `${home}/.claude-fleet/views/${session.slice(0, 8)}.sock`
1011 const root = await $.session.root()
1012 view = { control, size }
1013 const argv = ['fleet', 'board', 'view', '--root', root, '--width', String(size.w), '--height', String(size.h), '--follow', '--control', control]
1014 void (async () => {
1015 let pending = ''
1016 try {
1017 for await (const piece of $.process.spawn({ argv })) {
1018 if (piece.stream !== 'stdout') continue
1019 pending += piece.text
1020 let end = pending.indexOf('\n')
1021 while (end >= 0) {
1022 const line = pending.slice(0, end)
1023 pending = pending.slice(end + 1)
1024 try {
1025 frame = (JSON.parse(line) as { lines: GraphSpan[][] }).lines
1026 frameNumber += 1
1027 } catch {
1028 // Not a frame: nothing to draw.
1029 }
1030 end = pending.indexOf('\n')
1031 }
1032 }
1033 // It ended by itself: the view was quit, as `q` quits the fleet
1034 // tab. The pane goes with it.
1035 view = undefined
1036 await $.ui.close({ id: PANE })
1037 } catch {
1038 // It could not start, or it died: the next tick starts another.
1039 } finally {
1040 view = undefined
1041 }
1042 })()
1043 } else if (view.size.w !== size.w || view.size.h !== size.h) {
1044 view.size = size
1045 await sendView($, view.control, ['resize', String(size.w), String(size.h)])
1046 }
1047 if (frameNumber !== shownNumber) {
1048 shownNumber = frameNumber
1049 return { props: { lines: frame } }
1050 }
1051 return {}
1052 }
1053 if (!view) return {}
1054 if (data.t === 'key' && typeof data.key === 'string') {
1055 const words = keyWords({ key: data.key, ctrl: data.ctrl === true, shift: data.shift === true, meta: data.meta === true })
1056 if (words) await sendView($, view.control, words)
1057 return {}
1058 }
1059 if (data.t === 'click' && typeof data.x === 'number' && typeof data.y === 'number') {
1060 await sendView($, view.control, ['click', String(data.x), String(data.y)])
1061 return {}
1062 }
1063 return next(e)
1064 })
1065
1066 // The pane closed: the view behind it has no one to draw for.
1067 on('ui.close', async ($, e, next) => {
1068 const closed = await next(e)
1069 if ((e as { id?: string }).id === PANE) await update($, paneOpen, () => false)
1070 if (view && (e as { id?: string }).id === PANE) {
1071 await sendView($, view.control, ['quit'])
1072 frame = []
1073 shownNumber = -1
1074 }
1075 return closed
1076 })
1077
1078 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
1079 if (isWorker || e.props.hasSurvey) return next(e)
1080 const { Box, Button, Text } = $.ui.resolve(e)
1081
1082 // A workspace listed in auto-open, not yet a fleet: one press starts it.
1083 if (!active) {
1084 if (!(await read($, offer))) return next(e)
1085 const busy = await read($, starting)
1086 // What /fleet start does, and the pane. It takes a few seconds, and
1087 // the first time a download too, so the band says it is under way.
1088 const start = async () => {
1089 if ((await read($, starting)) || active || !session) return
1090 await update($, starting, () => true)
1091 try {
1092 const started = await adopt($, session)
1093 if ('problem' in started) {
1094 $.ui.toast(started.problem)
1095 return
1096 }
1097 active = true
1098 await openPane($)
1099 } finally {
1100 await update($, starting, () => false)
1101 }
1102 }
1103 return (
1104 <Box flexDirection="row" columnGap={2} alignItems="center" paddingX={1} width={e.props.bodyColumns}>
1105 <Text bold>fleet</Text>
1106 {busy && <Text color="yellow">◌ Starting the fleet…</Text>}
1107 {busy && <Text dimColor>The first start downloads fleet too.</Text>}
1108 {!busy && <Box flexGrow={1}><Text dimColor>This workspace runs as a fleet.</Text></Box>}
1109 {!busy && <Button key="fleet-start" variant="primary" label="Start fleet" onPress={() => void start()} />}
1110 </Box>
1111 )
1112 }
1113
1114 const s = await read($, snapshot)
1115 if (!s || s.me?.role !== 'chief') return next(e)
1116 const crew = s.agents.filter(a => a.role === 'worker')
1117 const isOpen = await paneShown($)
1118 // Nothing to count and the pane is up: the band has nothing to add.
1119 if (crew.length === 0 && isOpen) return next(e)
1120 const act = { go: (task: string) => void give($, task), handoff: (agent: string) => void handoff($, agent) }
1121 return fleetBand({ Box, Button, Text }, s, act, { columns: e.props.bodyColumns, isOpen, open: () => void openPane($) })
1122 })
1123}
1124hooks/crew.tsx 567 lines1// The fleet on a surface that draws natively: the desktop app and the phone.
2// The terminal shows the fleet tab itself, drawn by fleet as text
3// (view.tsx); a desktop window would show that as a grid of characters that
4// wants the keyboard, and the phone draws no surface module at all. So here
5// the pane is built from the board's snapshot instead, out of the surface's
6// own elements, as a roster: what needs the user, the crew, the open tasks
7// by state and the latest messages, under an optional live graph. The band
8// above the prompt reads the same asks.
9
10import type { ElementTable } from 'claude-code'
11
12import type { SnapAgent, SnapEvent, SnapTask, Snapshot } from '../types'
13
14/** What a press in the pane does: the same as the chief's commands. */
15export type CrewActions = {
16 go: (task: string) => void
17 handoff: (agent: string) => void
18}
19
20/** From here an agent is close to compacting: the board's CONTEXT_HIGH. */
21export const HIGH = 80
22
23/** How many of the latest messages the pane lists. */
24const RECENT = 6
25
26/** A message this young is still in flight on the graph. */
27export const LIVE_MS = 60_000
28
29/** This many messages along one line within STEADY_MS is steady traffic. */
30const STEADY = 3
31const STEADY_MS = 180_000
32
33/** The tool as the fleet view names it: an MCP tool without its server. */
34export function toolName(tool: string): string {
35 return tool.startsWith('mcp__') ? tool.split('__').at(-1) ?? tool : tool
36}
37
38export type Tone = 'working' | 'needs' | 'idle' | 'gone'
39
40/** What an agent is doing, in the fleet view's words. */
41export function doing(a: SnapAgent): { text: string; tone: Tone } {
42 if (a.waiting_for) return { text: `! needs you · ${a.waiting_for}`, tone: 'needs' }
43 if (a.presence === 'working') return { text: `● ${a.tool ? toolName(a.tool) : 'working'}`, tone: 'working' }
44 if (a.presence === 'waiting' && a.awaiting_go) return { text: '◇ needs a go', tone: 'needs' }
45 if (a.presence === 'waiting') return { text: '○ idle', tone: 'idle' }
46 if (a.presence === 'unlinked') return { text: '○ starting', tone: 'idle' }
47 return { text: 'gone', tone: 'gone' }
48}
49
50/** The colours the band uses too, which read on light and dark alike. */
51export const TONE = { working: 'yellow', needs: 'yellow', idle: 'green', gone: 'gray' } as const
52
53/** An agent as one glyph in the band's row of dots. */
54export function dot(a: SnapAgent): string {
55 const d = doing(a)
56 if (d.tone === 'needs') return a.waiting_for ? '!' : '◆'
57 return d.tone === 'working' ? '●' : '○'
58}
59
60const STATE: Record<string, string> = {
61 running: 'yellow',
62 blocked: 'red',
63 review: 'cyan',
64 done: 'green',
65 queued: 'gray',
66 dropped: 'gray',
67}
68
69/** Something an agent waits on the user for, most urgent first. */
70export type Ask = {
71 agent: string
72 task: string | null
73 kind: 'prompt' | 'go' | 'full'
74 /** What it is, as a sentence after the agent's name. */
75 text: string
76}
77
78/** The newest message `agent` sent, which says what a go is for. */
79function said(s: Snapshot, agent: string): string | undefined {
80 return s.events.find(e => e.kind === 'message' && e.from === agent)?.summary
81}
82
83/**
84 * What the crew waits on the user for: an agent stopped at a prompt in its
85 * own session, then a plan waiting for a go, then an agent close to
86 * compacting.
87 */
88export function asks(s: Snapshot): Ask[] {
89 const crew = s.agents.filter(a => a.role === 'worker')
90 const out: Ask[] = []
91 for (const a of crew) {
92 if (a.waiting_for) out.push({ agent: a.name, task: a.task, kind: 'prompt', text: `is waiting at a ${a.waiting_for} in its session.` })
93 }
94 for (const a of crew) {
95 if (a.awaiting_go && a.presence === 'waiting') {
96 const what = said(s, a.name)
97 out.push({ agent: a.name, task: a.awaiting_go, kind: 'go', text: what ?? `needs a go on ${a.awaiting_go}.` })
98 }
99 }
100 for (const a of crew) {
101 if (a.context !== null && a.context >= HIGH) {
102 out.push({ agent: a.name, task: a.task, kind: 'full', text: `is at ${a.context}% context and will compact soon.` })
103 }
104 }
105 return out
106}
107
108/** The press that answers `ask`, if there is one: a prompt is answered in the agent's own session. */
109export function askButton(el: Pick<ElementTable<'mobile'>, 'Button'>, ask: Ask, act: CrewActions, long: boolean) {
110 const { Button } = el
111 if (ask.kind === 'go') {
112 return <Button key={`go-${ask.agent}`} variant="primary" label={`Go on ${ask.task}`} onPress={() => act.go(ask.task ?? '')} />
113 }
114 if (ask.kind === 'full') {
115 return <Button key={`handoff-${ask.agent}`} label={long ? 'Hand off to a fresh session' : 'Hand off'} onPress={() => act.handoff(ask.agent)} />
116 }
117 return null
118}
119
120/**
121 * The band above the chief's prompt: one quiet line while all is well, a dot
122 * per agent and the counts; only the most urgent ask gets a second line, as
123 * a sentence with its button. Both lines start their text in one column, the
124 * labels given one width, and the sentence keeps to its line: the pane has
125 * it whole.
126 */
127export function fleetBand(
128 el: Pick<ElementTable<'mobile'>, 'Box' | 'Text' | 'Button'>,
129 s: Snapshot,
130 act: CrewActions,
131 o: { columns: number; isOpen: boolean; open: () => void },
132) {
133 const { Box, Text, Button } = el
134 const crew = s.agents.filter(a => a.role === 'worker')
135 const want = asks(s)
136 const top = want[0]
137 const working = crew.filter(a => a.presence === 'working').length
138 const idle = crew.filter(a => a.presence === 'waiting' && doing(a).tone === 'idle').length
139 const ask = top ? `▲ ${clip(top.agent, 16)}` : ''
140 const label = Math.max('fleet'.length, ask.length)
141 return (
142 <Box flexDirection="column" rowGap={1} paddingX={1} width={o.columns}>
143 <Box flexDirection="row" columnGap={2} alignItems="center">
144 <Box minWidth={label} flexShrink={0}>
145 <Text bold>fleet</Text>
146 </Box>
147 <Box flexDirection="row" columnGap={2} flexGrow={1} flexShrink={1} minWidth={0}>
148 {crew.length === 0 ? (
149 <Text dimColor wrap="truncate-end">No agents yet. Tell the chief what you want done.</Text>
150 ) : (
151 <Text wrap="truncate-end">
152 {crew.map(a => <Text color={TONE[doing(a).tone]}>{dot(a)}</Text>)}
153 {' '}
154 {`${working} working`}
155 <Text dimColor> · </Text>
156 {`${idle} idle`}
157 <Text dimColor> · </Text>
158 {`${s.tasks.length} open`}
159 </Text>
160 )}
161 </Box>
162 <Box flexShrink={0}>
163 {o.isOpen ? <Text dimColor>/fleet</Text> : <Button key="fleet-open" label="Open fleet" onPress={() => o.open()} />}
164 </Box>
165 </Box>
166 {top && (
167 <Box flexDirection="row" columnGap={2} alignItems="center">
168 <Box minWidth={label} flexShrink={0}>
169 <Text color="yellow" bold>{ask}</Text>
170 </Box>
171 <Box flexGrow={1} flexShrink={1} minWidth={0}>
172 <Text wrap="truncate-end">{top.text}</Text>
173 </Box>
174 {want.length > 1 && (
175 <Box flexShrink={0}>
176 <Text dimColor>{`+${want.length - 1} more`}</Text>
177 </Box>
178 )}
179 <Box flexShrink={0}>{askButton({ Button }, top, act, false)}</Box>
180 </Box>
181 )}
182 </Box>
183 )
184}
185
186/** How to reach a background agent from a terminal: there is no tab here. */
187function attach(a: SnapAgent): string | undefined {
188 return a.target?.startsWith('bg:') ? `claude attach ${a.target.slice(3)}` : undefined
189}
190
191function esc(text: string): string {
192 return text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')
193}
194
195function clip(text: string, max: number): string {
196 return text.length > max ? `${text.slice(0, Math.max(1, max - 1))}…` : text
197}
198
199/**
200 * When the pane first saw each event, by key: the snapshot carries no times,
201 * so a message's age is how long ago it turned up. What was on the board at
202 * the first look is old news, never in flight.
203 */
204export class Seen {
205 private at = new Map<string, number>()
206 private started = false
207
208 track(events: SnapEvent[], now: number): Map<string, number> {
209 for (const e of events) {
210 if (!this.at.has(e.key)) this.at.set(e.key, this.started ? now : -Infinity)
211 }
212 this.started = true
213 // Keep only what the board still lists.
214 const listed = new Set(events.map(e => e.key))
215 for (const key of this.at.keys()) if (!listed.has(key)) this.at.delete(key)
216 return this.at
217 }
218
219 /** When the youngest message stops being in flight; undefined when none is. */
220 nextExpiry(now: number): number | undefined {
221 let soonest: number | undefined
222 for (const t of this.at.values()) {
223 const end = t + LIVE_MS
224 if (end > now && (soonest === undefined || end < soonest)) soonest = end
225 }
226 return soonest
227 }
228}
229
230// The graph's own colours: drawn as an image, it cannot read the theme, so it
231// sits on its own dark plate and reads the same on light and dark.
232const PLATE = '#2B2D42'
233const FILL: Record<Tone, string> = { working: '#E0A526', needs: '#E76F51', idle: '#2A9D8F', gone: '#8A8A8A' }
234const INK: Record<Tone, string> = { working: '#1F1A10', needs: '#FFFFFF', idle: '#FFFFFF', gone: '#FFFFFF' }
235
236const GRAPH_STYLE =
237 'text{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}' +
238 '.dot{fill:none;stroke-width:7;stroke-linecap:round;stroke-dasharray:0.01 200}' +
239 '.down{animation:fdown 2.4s linear infinite}' +
240 '.up{animation:fup 2.4s linear infinite}' +
241 '.march{fill:none;stroke-dasharray:7 7;animation:march .8s linear infinite}' +
242 '.pulse{transform-box:fill-box;transform-origin:center;animation:pulse 1.6s ease-out infinite}' +
243 '@keyframes fdown{from{stroke-dashoffset:0}to{stroke-dashoffset:-100}}' +
244 '@keyframes fup{from{stroke-dashoffset:-100}to{stroke-dashoffset:0}}' +
245 '@keyframes march{to{stroke-dashoffset:-14}}' +
246 '@keyframes pulse{from{opacity:.9;transform:scale(1)}to{opacity:0;transform:scale(1.5)}}' +
247 '@media (prefers-reduced-motion:reduce){.down,.up,.march,.pulse{animation:none}.dot{display:none}}'
248
249type Node = { a: SnapAgent; x: number; y: number }
250
251/**
252 * The crew as a live graph: the chief's card over a round node per agent,
253 * its ring the agent's context, pulsing while it needs the user. A line from
254 * the chief into each agent, heavier the more has gone along it, dashed and
255 * still where nothing has, with dashes moving along it while the traffic is
256 * steady; agents that talk to each other are joined by a curve under them.
257 * Each message from the last minute is a dot travelling from its sender to
258 * its receiver, drawn with CSS animation since the image runs no script.
259 */
260export function graph(s: Snapshot, seen: Map<string, number>, now: number): { source: string; height: number; alt: string } {
261 const W = 400
262 const PER_ROW = 5
263 const R = 20
264 const RING = 26
265 const CIRC = 2 * Math.PI * RING
266 const chief = s.agents.find(a => a.role === 'chief')
267 const crew = s.agents.filter(a => a.role === 'worker')
268 const cx = W / 2
269 const chiefTop = 30
270 const chiefBottom = chiefTop + 42
271 const parts: string[] = []
272
273 if (crew.length === 0) {
274 const height = 190
275 parts.push(
276 `<rect width="${W}" height="${height}" rx="12" fill="${PLATE}"/>`,
277 `<path d="M${cx} ${chiefBottom} L${cx} ${chiefBottom + 36}" fill="none" stroke="#6C6F93" stroke-width="1.5" stroke-dasharray="4 5"/>`,
278 ...[-74, 0, 74].map(dx => `<circle cx="${cx + dx}" cy="${chiefBottom + 58}" r="${R}" fill="none" stroke="#6C6F93" stroke-width="1.5" stroke-dasharray="4 4"/>`),
279 `<text x="${cx}" y="${height - 14}" font-size="11" fill="#D6D7E6" text-anchor="middle">agents join here when you approve a plan</text>`,
280 )
281 chiefCard()
282 return { source: wrap(height), height, alt: `The crew: ${chief ? `${chief.name}, the chief, and ` : ''}no agents yet` }
283 }
284
285 // Where each agent sits: rows of up to PER_ROW, centred.
286 const rows = Math.ceil(crew.length / PER_ROW)
287 const step = W / Math.min(PER_ROW, crew.length)
288 const rowH = 110
289 const nodes = new Map<string, Node>()
290 crew.forEach((a, i) => {
291 const row = Math.floor(i / PER_ROW)
292 const inRow = Math.min(PER_ROW, crew.length - row * PER_ROW)
293 const x = W / 2 + (i % PER_ROW - (inRow - 1) / 2) * step
294 nodes.set(a.name, { a, x, y: chiefBottom + 78 + row * rowH })
295 })
296
297 // Messages by the pair they went between, either way, with their ages.
298 const chiefName = chief?.name
299 const pair = (a: string, b: string) => (a < b ? `${a}\n${b}` : `${b}\n${a}`)
300 const total = new Map<string, number>()
301 const steady = new Map<string, number>()
302 const live: SnapEvent[] = []
303 for (const e of s.events) {
304 if (e.kind !== 'message' || !e.from || !e.to) continue
305 const known = (n: string) => n === chiefName || nodes.has(n)
306 if (!known(e.from) || !known(e.to) || e.from === e.to) continue
307 const k = pair(e.from, e.to)
308 total.set(k, (total.get(k) ?? 0) + 1)
309 const age = now - (seen.get(e.key) ?? -Infinity)
310 if (age <= STEADY_MS) steady.set(k, (steady.get(k) ?? 0) + 1)
311 if (age <= LIVE_MS) live.push(e)
312 }
313
314 // The lines: chief to agent, and a curve under the nodes between agents.
315 const lines = new Map<string, { d: string; from: string }>()
316 for (const n of nodes.values()) {
317 if (!chiefName) break
318 const mid = (chiefBottom + n.y - RING) / 2
319 lines.set(pair(chiefName, n.a.name), { d: `M${cx} ${chiefBottom} C${cx} ${mid}, ${n.x} ${mid}, ${n.x} ${n.y - RING}`, from: chiefName })
320 }
321 let dip = 0
322 for (const k of total.keys()) {
323 if (lines.has(k)) continue
324 const [p, q] = k.split('\n') as [string, string]
325 const a = nodes.get(p)
326 const b = nodes.get(q)
327 if (!a || !b) continue
328 const sag = 44 + Math.abs(a.x - b.x) / 8
329 dip = Math.max(dip, sag)
330 // From under each name, so the curve never crosses one.
331 const ay = a.y + RING + 26
332 const by = b.y + RING + 26
333 lines.set(k, { d: `M${a.x} ${ay} C${a.x} ${ay + sag}, ${b.x} ${by + sag}, ${b.x} ${by}`, from: p })
334 }
335
336 const height = Math.round(chiefBottom + 78 + (rows - 1) * rowH + RING + 30 + (dip > 0 ? dip * 0.75 + 4 : 0))
337 parts.push(`<rect width="${W}" height="${height}" rx="12" fill="${PLATE}"/>`)
338 const inFlight = live.length
339 parts.push(
340 `<text x="12" y="20" font-size="11" fill="#B9BBD0">${inFlight > 0 ? `live · ${inFlight} message${inFlight === 1 ? '' : 's'} in the last minute` : 'quiet · no messages in the last minute'}</text>`,
341 )
342
343 for (const [k, line] of lines) {
344 const n = total.get(k) ?? 0
345 const [p, q] = k.split('\n') as [string, string]
346 const toChief = p === chiefName || q === chiefName
347 const agent = nodes.get(p === chiefName ? q : p)?.a
348 const stroke = toChief && agent ? FILL[doing(agent).tone] : '#8A8DB0'
349 if (n === 0) {
350 parts.push(`<path d="${line.d}" fill="none" stroke="${stroke}" stroke-width="1.5" stroke-dasharray="5 5" opacity="0.8"/>`)
351 continue
352 }
353 const width = (1.5 + Math.min(3, n * 0.5)).toFixed(1)
354 const isSteady = (steady.get(k) ?? 0) >= STEADY
355 parts.push(`<path d="${line.d}" fill="none" stroke="${stroke}" stroke-width="${isSteady ? Math.max(4, Number(width)) : width}" opacity="${isSteady ? 0.55 : 0.9}"/>`)
356 if (isSteady) parts.push(`<path class="march" d="${line.d}" stroke="#F5D488" stroke-width="2"/>`)
357 }
358
359 // A dot for each message in flight, from its sender to its receiver; two
360 // along one line set off one after the other.
361 const along = new Map<string, number>()
362 for (const e of live) {
363 const k = pair(e.from ?? '', e.to ?? '')
364 const line = lines.get(k)
365 if (!line) continue
366 const i = along.get(k) ?? 0
367 along.set(k, i + 1)
368 const way = line.from === e.from ? 'down' : 'up'
369 const delay = i > 0 ? ` style="animation-delay:${(i * 0.8).toFixed(1)}s"` : ''
370 parts.push(`<path class="dot ${way}" pathLength="100" d="${line.d}" stroke="${way === 'down' ? '#FFE7A3' : '#FFFFFF'}"${delay}/>`)
371 }
372
373 for (const { a, x, y } of nodes.values()) {
374 const d = doing(a)
375 const full = a.context !== null && a.context >= HIGH
376 if (d.tone === 'needs') parts.push(`<circle class="pulse" cx="${x}" cy="${y}" r="${RING}" fill="none" stroke="${FILL.needs}" stroke-width="3"/>`)
377 parts.push(`<circle cx="${x}" cy="${y}" r="${RING}" fill="none" stroke="#4A4D68" stroke-width="4"/>`)
378 if (a.context !== null) {
379 const arc = ((CIRC * Math.min(100, Math.max(0, a.context))) / 100).toFixed(1)
380 parts.push(
381 `<circle cx="${x}" cy="${y}" r="${RING}" fill="none" stroke="${full ? FILL.needs : '#D6D7E6'}" stroke-width="4" stroke-dasharray="${arc} ${CIRC.toFixed(1)}" transform="rotate(-90 ${x} ${y})"/>`,
382 )
383 }
384 parts.push(`<circle cx="${x}" cy="${y}" r="${R}" fill="${FILL[d.tone]}"/>`)
385 const mark = d.tone === 'needs' ? '!' : a.context !== null ? `${a.context}%` : '–'
386 parts.push(
387 `<text x="${x}" y="${y + 5}" font-size="${mark === '!' ? 14 : 12}" font-weight="${mark === '!' ? 800 : 700}" fill="${INK[d.tone]}" text-anchor="middle">${mark}</text>`,
388 `<text x="${x}" y="${y + RING + 20}" font-size="12" font-weight="600" fill="#FFFFFF" text-anchor="middle">${esc(clip(a.name, Math.floor(step / 7.5)))}</text>`,
389 )
390 }
391 chiefCard()
392
393 const alt =
394 `The crew: ${chief ? `${chief.name}, the chief, ` : ''}and ${crew.length} ${crew.length === 1 ? 'agent' : 'agents'}: ` +
395 crew.map(a => `${a.name} ${doing(a).text}${a.context !== null ? ` at ${a.context}% context` : ''}`).join('; ') +
396 (inFlight > 0 ? `. In the last minute: ${live.map(e => `${e.from} to ${e.to}`).join(', ')}` : '. No messages in the last minute')
397 return { source: wrap(height), height, alt }
398
399 function chiefCard() {
400 if (!chief) return
401 const d = doing(chief)
402 const what = d.tone === 'working' ? d.text.replace(/^● /, '') : d.tone === 'idle' ? 'idle' : d.tone === 'needs' ? 'needs you' : 'gone'
403 parts.push(
404 `<rect x="${cx - 70}" y="${chiefTop}" width="140" height="42" rx="10" fill="#3D405B" stroke="#6C6F93"/>`,
405 `<text x="${cx}" y="${chiefTop + 18}" font-size="13" font-weight="600" fill="#FFFFFF" text-anchor="middle">◆ ${esc(clip(chief.name, 16))}</text>`,
406 `<text x="${cx}" y="${chiefTop + 34}" font-size="11" fill="#D6D7E6" text-anchor="middle">${esc(clip(what, 14))}${chief.context !== null ? ` · ${chief.context}%` : ''}</text>`,
407 )
408 }
409
410 function wrap(h: number): string {
411 return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${W} ${h}" width="${W}" height="${h}"><style>${GRAPH_STYLE}</style>${parts.join('')}</svg>`
412 }
413}
414
415/** An agent's context as a small bar, red once it is close to compacting. */
416function contextBar(context: number): string {
417 const w = Math.round((140 * Math.min(100, Math.max(0, context))) / 100)
418 const fill = context >= HIGH ? FILL.needs : '#9A9A9A'
419 return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 140 6" width="140" height="6"><rect width="140" height="6" rx="3" fill="#8A8A8A" opacity="0.35"/><rect width="${w}" height="6" rx="3" fill="${fill}"/></svg>`
420}
421
422/** The order the board lists open tasks in. */
423const TASK_ORDER = ['blocked', 'review', 'running', 'queued']
424
425/** Open tasks grouped by state, in the board's order; any other state after. */
426function grouped(tasks: SnapTask[]): [string, SnapTask[]][] {
427 const by = new Map<string, SnapTask[]>()
428 for (const t of tasks) by.set(t.state, [...(by.get(t.state) ?? []), t])
429 const states = [...TASK_ORDER.filter(st => by.has(st)), ...[...by.keys()].filter(st => !TASK_ORDER.includes(st))]
430 return states.map(st => [st, by.get(st) ?? []])
431}
432
433export type PaneOptions = {
434 columns: number
435 /** Whether the live graph is shown, and the press that flips it. */
436 showGraph: boolean
437 toggleGraph: () => void
438 /** When each event was first seen, and the time now, for the graph. */
439 seen: Map<string, number>
440 now: number
441}
442
443/** The pane, built from `s` with the elements of the surface it is drawn on. */
444export function crewPane(el: ElementTable<'mobile'>, s: Snapshot, act: CrewActions, o: PaneOptions) {
445 const { Box, Text, Button, Svg, Markdown } = el
446 const crew = s.agents.filter(a => a.role === 'worker')
447 const working = crew.filter(a => a.presence === 'working').length
448 const want = asks(s)
449 const needing = new Set(want.map(w => w.agent)).size
450 const messages = s.events.filter(e => e.kind === 'message')
451
452 return (
453 <Box flexDirection="column" gap={1} paddingX={1}>
454 <Box flexDirection="column">
455 <Box flexDirection="row" alignItems="center" columnGap={1}>
456 <Box flexGrow={1}>
457 <Markdown text="### Fleet" />
458 </Box>
459 <Button key="fleet-graph" variant={o.showGraph ? 'primary' : 'secondary'} label="Graph" onPress={() => o.toggleGraph()} />
460 </Box>
461 {crew.length === 0 && s.tasks.length === 0 ? (
462 <Text dimColor>no agents · no open tasks</Text>
463 ) : (
464 <Box flexDirection="row" columnGap={2} flexWrap="wrap" alignItems="center">
465 <Text dimColor>{`${crew.length} ${crew.length === 1 ? 'agent' : 'agents'}`}</Text>
466 {working > 0 ? <Text color="yellow">{`● ${working} working`}</Text> : <Text dimColor>0 working</Text>}
467 <Text dimColor>{`${s.tasks.length} open`}</Text>
468 {needing > 0 && <Text color="yellow" bold>{`▲ ${needing} need${needing === 1 ? 's' : ''} you`}</Text>}
469 </Box>
470 )}
471 </Box>
472
473 {o.showGraph && graphBlock()}
474
475 {crew.length === 0 && (
476 <Text>Tell the chief what you want done. It plans the work across your repositories. When you approve the plan, it starts one agent per repository.</Text>
477 )}
478
479 {want.length > 0 && (
480 <Box flexDirection="column" gap={1}>
481 <Text bold dimColor>NEEDS YOU</Text>
482 {want.map(w => (
483 <Box key={`ask-${w.kind}-${w.agent}`} flexDirection="column" borderStyle="round" borderColor="yellow" paddingX={1}>
484 <Text>
485 <Text bold>{w.agent}</Text>
486 {w.task ? <Text dimColor>{` · ${w.task}`}</Text> : null}
487 </Text>
488 <Text>{w.text}</Text>
489 {askButton(el, w, act, true)}
490 </Box>
491 ))}
492 </Box>
493 )}
494
495 {crew.length > 0 && (
496 <Box flexDirection="column" gap={1}>
497 <Text bold dimColor>CREW</Text>
498 {crew.map(a => {
499 const d = doing(a)
500 const full = a.context !== null && a.context >= HIGH
501 const how = attach(a)
502 return (
503 <Box key={`agent-${a.name}`} flexDirection="column">
504 <Box flexDirection="row" columnGap={1} flexWrap="wrap">
505 <Text color={TONE[d.tone]}>{dot(a)}</Text>
506 <Text bold>{a.name}</Text>
507 {a.task && <Text dimColor>{a.task}</Text>}
508 <Text color={TONE[d.tone]}>{d.text}</Text>
509 </Box>
510 {(a.context !== null || how) && (
511 <Box flexDirection="row" columnGap={1} alignItems="center" paddingLeft={2} flexWrap="wrap">
512 {a.context !== null && <Svg source={contextBar(a.context)} alt={`${a.context}% of its context used`} width={140} height={6} />}
513 {a.context !== null && <Text color={full ? 'yellow' : undefined} dimColor={!full} bold={full}>{`${a.context}% context`}</Text>}
514 {how && <Text dimColor>{how}</Text>}
515 </Box>
516 )}
517 </Box>
518 )
519 })}
520 </Box>
521 )}
522
523 {s.tasks.length > 0 && (
524 <Box flexDirection="column" gap={1}>
525 <Text bold dimColor>TASKS</Text>
526 {grouped(s.tasks).map(([state, tasks]) => (
527 <Box key={`state-${state}`} flexDirection="column">
528 <Text color={STATE[state] ?? 'gray'}>{`${state} · ${tasks.length}`}</Text>
529 {tasks.map(t => (
530 <Box key={`task-${t.key}`} flexDirection="row" columnGap={2} flexWrap="wrap" paddingLeft={2}>
531 <Text>{t.key}</Text>
532 <Text>{t.title}</Text>
533 {t.agent && <Text dimColor>{t.agent}</Text>}
534 {t.note && <Text dimColor italic>{t.note}</Text>}
535 </Box>
536 ))}
537 </Box>
538 ))}
539 </Box>
540 )}
541
542 {messages.length > 0 && (
543 <Box flexDirection="column">
544 <Text bold dimColor>LATEST</Text>
545 {messages.slice(0, RECENT).map(e => (
546 <Text key={`event-${e.key}`} wrap="truncate-end">
547 <Text dimColor>{`${e.from ?? '?'} → ${e.to ?? '?'} `}</Text>
548 {e.summary}
549 </Text>
550 ))}
551 </Box>
552 )}
553 </Box>
554 )
555
556 function graphBlock() {
557 const g = graph(s, o.seen, o.now)
558 const width = Math.min(560, Math.max(280, o.columns * 8))
559 return (
560 <Box flexDirection="column">
561 <Svg source={g.source} alt={g.alt} width={width} />
562 {crew.length > 0 && <Text dimColor>● message in flight · ⋯ steady traffic · - - quiet · ring = context</Text>}
563 </Box>
564 )
565 }
566}
567hooks/view.tsx 45 lines1// The fleet view in the chief's /fleet pane: the frames fleet draws, and the
2// keys and clicks that go back to it.
3//
4// A surface module: it runs where the pane is drawn, with no `$`. It draws
5// the newest frame its props carry, asks the hooks module for a newer one on
6// its frame clock, and posts every key pressed while it has the focus and
7// every click, with its own size, so the view behind it is drawn to fit.
8
9import type { ClientModule } from 'claude-code'
10
11import type { GraphSpan } from '../types'
12
13type Props = { lines: GraphSpan[][] }
14type State = { isStarted: true }
15
16/** How often to ask for a newer frame: the view's own animation rate. */
17const TICK_MS = 100
18
19const FleetView: ClientModule<Props, State> = (props, surface) => {
20 const { Box, Text } = surface.elements
21 if (surface.state === undefined) {
22 surface.every(TICK_MS, () => surface.post({ t: 'tick', w: surface.columns, h: surface.rows }))
23 surface.onKey(e => surface.post({ t: 'key', key: e.key, ctrl: e.ctrl === true, shift: e.shift === true, meta: e.meta === true }))
24 surface.onPointer(e => {
25 if (e.type === 'down' && e.button === 'left') surface.post({ t: 'click', x: e.x, y: e.y })
26 })
27 surface.setState({ isStarted: true })
28 }
29 const lines = props.lines ?? []
30 if (lines.length === 0) return <Text dimColor>Drawing the fleet…</Text>
31 return (
32 <Box flexDirection="column">
33 {lines.map((line, i) => (
34 <Text key={`l${i}`} wrap="truncate-end">
35 {line.length === 0 ? ' ' : line.map(span => (
36 <Text color={span.fg} bold={span.bold} dimColor={span.dim}>{span.t}</Text>
37 ))}
38 </Text>
39 ))}
40 </Box>
41 )
42}
43
44export default FleetView
45types/index.d.ts 61 lines1// What `fleet board snapshot` prints: the fleet as the chief's session draws it.
2
3export type SnapAgent = {
4 name: string
5 role: 'chief' | 'worker'
6 presence: 'working' | 'waiting' | 'gone' | 'unlinked'
7 waiting_for: string | null
8 tool: string | null
9 context: number | null
10 task: string | null
11 awaiting_go: string | null
12 target: string | null
13}
14
15export type SnapTask = {
16 key: string
17 title: string
18 state: string
19 agent: string | null
20 note: string | null
21}
22
23export type SnapEvent = {
24 key: string
25 kind: string
26 from: string | null
27 to: string | null
28 task: string | null
29 summary: string
30 notice: { title: string; body: string } | null
31}
32
33export type Snapshot = {
34 me: { name: string; role: string } | null
35 agents: SnapAgent[]
36 tasks: SnapTask[]
37 events: SnapEvent[]
38}
39
40/** One run of cells in one style, as `fleet board graph` draws them. */
41export type GraphSpan = { t: string; fg?: string; bold?: boolean; dim?: boolean }
42
43declare module 'claude-code' {
44 interface PluginState {
45 fleet: {
46 snapshot: Snapshot | null
47 /** The brief a session made the chief with /fleet start, or a desktop
48 * worker that joined, received as a turn, kept to put back after
49 * compaction. */
50 brief: string | null
51 /** The workspace is listed in ~/.claude-fleet/auto-open and this
52 * session is not part of a fleet yet: the band offers to start one. */
53 offer: boolean
54 /** The fleet pane is open, so the band need not offer to open it. */
55 paneOpen: boolean
56 /** The band's Start fleet was pressed and the fleet is still starting. */
57 starting: boolean
58 }
59 }
60}
61