Tells a running Fleet which jobs you have open, and what each one holds: its slot, branch, pull request and subagents. Ships a fleet of subagents any…

<img src="packages/brand/covers/armada-social-preview.png" alt="Armada — delegate without watching. You handle the decisions without babysitting." width="100%">
<a href="#status"><img src="https://img.shields.io/badge/status-pre--alpha-EE8450" alt="Status: pre-alpha"></a> <a href="LICENSE"><img src="https://img.shields.io/badge/license-Apache--2.0-4A9EDB" alt="License: Apache 2.0"></a> <img src="https://img.shields.io/badge/rust-1.90-4FB8D9" alt="Rust 1.90"> <img src="https://img.shields.io/badge/platform-macOS-8C97A6" alt="Platform: macOS">
On an Apple Silicon Mac, one line in Terminal:
curl -fsSL https://github.com/Mele-Labs/armada/releases/latest/download/install.sh | sh
| What it does | Puts Armada.app in /Applications, starts Fleet from the armada inside it under launchd, and opens the app. Run it again to move onto the newest release |
| What it needs | macOS on Apple Silicon and Apple's Command Line Tools. It opens their installer when they are missing and asks you to run it again. No Rust, no Node |
| When it refuses | When Fleet here runs from a checkout you build: scripts/restart updates that one |
Every merge to main that passes ci is a release, tagged v0.<minor>.<commits on main>. docs/practices/ci.md, Releases, says how one is made.
Armada is pre-alpha, and part of it runs. There is one binary, armada:
armada serve [<path>] | The daemon. Binds a loopback port, publishes a runtime file, serves the API and hosts Jobs until it is signalled |
armada check <name> | Runs one Check the repository's armada.yml declares, and first any Command its requires names, exactly as the merge line does |
armada run <name> | Runs one Command it declares. The merge line runs Checks; it does not run Commands |
armada covers | Reads changed paths on stdin and prints each Check they make run, by the same when: reading the merge line uses. Needs nothing running |
armada clean [--all] [--force] | Destructive. Gives this repository's worktrees and branches back, keeping any branch whose work is not merged, and naming each worktree slot still held. --force deletes unmerged branches too, and gives back a slot where it is clean and landed. docs/practices/running-locally.md, Clearing up |
armada worktree lease <branch> | Leases a warm worktree from the repository's pool, waiting while every slot is held; release gives it back once clean and landed, --status lists who holds each. docs/practices/running-locally.md, Leasing a worktree |
What holds today, and how each is known:
| Claim | Evidence |
|---|---|
| A Job runs end to end — slot, agent, Checks, commit, push, pull request | Several have |
| The machinery is proved | The acceptance test, hermetic — no process, no repository, no network |
| The merge is proved | A real agent fixed a real defect here, and the commit is in the history |
Installing it is how to start, and Running it locally is how to build it from source. Watch the milestones for what is next.
You can run several coding agents at once today. What you cannot do is stop watching them.
Armada is a macOS application that dispatches coding agents against git repositories and checks their work before it lands. An agent does not decide its work is ready: Fleet reads progress from what it observes, and the repository's own Checks run against the result before a branch merges. Saying "done" in prose does nothing.
It exists because delegating work to something that reports on itself means reading everything anyway, which costs more than doing the work yourself.
Three rules it is built around:
This is not a sandbox. An agent can still run a shell, because a tool allowlist is a permission list and not a toolset. What bounds a Job is the slot it writes in and its permission gate; real confinement means containers, and that is a different system. docs/scope.md carries the reasoning.
Two processes that ship as a pair and version together.
| Fleet | Rust daemon | Owns Jobs, hosts and supervises agents, runs checks, writes the record. Runs detached — quitting the app does not kill work in flight |
| Bridge | Electron app | The only way in. Holds one connection to Fleet and never talks to an agent directly |
They meet at exactly one seam: a versioned protocol over HTTP and a WebSocket. Every other boundary in the system is a function call or a file.
armada/
├── crates/ the Rust workspace — Fleet, the domain, the adapters
├── apps/desktop/ Bridge
├── packages/ shared: design tokens, icons, and what surfaces both read
├── xtask/ the build gate
└── docs/ contracts, practices, spikes, and what v1 taught
ARCHITECTURE.md is the map — the process topology, the crate graph, and the rules that hold everywhere, with diagrams.
You need macOS and four toolchains that do not come with it.
| Tool | Version | Where it comes from |
|---|---|---|
| Command Line Tools | the one matching your macOS | xcode-select --install, and Software Update after a macOS upgrade |
| Rust | 1.90 or later | rustup |
| Node | 24 — the version in .nvmrc | nvm, then nvm use |
| pnpm | the version in package.json | corepack enable, bundled with Node |
Command Line Tools behind your macOS fail at the link, not the compile. clang picks the newest SDK on the machine and hands it to whichever linker is installed, so a linker older than that SDK cannot read it and every Rust build ends in ld: tapi error: malformed file naming libSystem.tbd. It reads as a broken checkout and is a toolchain a version behind. softwareupdate --list names the one to install.
pnpm comes from corepack, which ships with Node, at the version package.json pins. You do not install it yourself. A Node that does not match .nvmrc refuses the install rather than warning about it: engineStrict is on.
cargo install writes to ~/.cargo/bin, and something has to put that on your PATH. rustup does, through the ~/.cargo/env it writes and your shell sources. A Rust from Homebrew writes no such file, so pnpm dev installs armada, calls it on the next line, and reports command not found.
git clone https://github.com/NickMele/armada.git
cd armada
nvm use # Node 24, per .nvmrc
corepack enable # puts pnpm on your PATH
pnpm install
cargo xtask verify-foundations # read what each line names, not the exit code
One more, once per machine: armada run browsers, before the component tests — see Tests.
A gate that reports red is not a broken checkout. A rule whose subject does not exist yet fails and names it, so the gate goes red whenever a milestone lands its registry rows ahead of the code satisfying them. The tests pass either way.
Armada checks itself with a task rather than a CI config, so the same command runs on a laptop and in CI. It has no dependencies and needs nothing built.
| Command | Checks |
|---|---|
cargo xtask verify-foundations | Every foundation rule. Red is a legitimate state |
cargo xtask verify-tokens | Design token outputs match the CSS they are generated from |
cargo xtask verify-docs | Open questions are collected, and every citation resolves |
cargo xtask verify-roadmap | Capabilities and their issues agree. Needs gh and a network, so not part of the gate |
Some of what the gate refuses:
armada check test # not `cargo test`
armada check acceptance # the milestone's own claim
pnpm bridge-test # the TypeScript half
pnpm bridge-test needs a browser. It runs the pure modules under packages/screens in node, then mounts every story in packages/components in headless Chromium — a story that throws is a failure, and a story with a play function has its assertions run against what it drew.
pnpm install does not fetch that browser. armada run browsers does, once per machine. Without it the second suite fails naming an executable that is not there, which is a missing browser and not a failing component.
Watch one while you work on it, from packages/components or packages/screens: pnpm exec vitest.
pnpm dev
That is the whole loop: it stops the running Fleet, reinstalls armada from the working tree, starts Fleet, waits for it to publish, and starts Bridge in the foreground. Ctrl-C stops both, which is a convenience of the script and not how Armada behaves in earnest.
Or by hand, which is only the same two halves in the right order:
cargo install --path crates/armada --debug # armada, on your PATH
armada serve . # runs until Ctrl-C
pnpm --filter @armada/desktop dev # in another terminal
Fleet first, always. Fleet binds a port and publishes a runtime file, and Bridge reads that file to find where to connect.
docs/practices/running-locally.md is the rest — what a healthy start prints, what Fleet refuses before it binds a port, how the two halves handle a protocol mismatch, and what armada clean will and will not delete.
Work is tracked as GitHub issues, grouped two ways.
Not yet — see CONTRIBUTING.md. Issues and questions are welcome; there is nothing to review.
Security: SECURITY.md. Armada brokers credentials and runs commands a repository declares, so the interesting constraints are listed there.
This repository is the second attempt. There was a v1 that worked well enough to be used and badly enough to be replaced, and it was deleted rather than refactored.
What it taught is written down in docs/v1-learnings/ — including the things that went wrong, which is most of it. Its history is on the v1-archive branch and the v1-final tag; a bare file path in a document means git show v1-final:<path>.
hooks/register.ts 1502 lines1// Tells a running Fleet which sessions this machine has open and what each holds.
2// `docs/concepts/session.md`.
3//
4// **A session is reported as it happens and never read back**, with one
5// exception: a message a person sent it from Bridge, which Fleet holds until
6// this mod asks (`submitHeld`). Two things are told to the model: its own session id, so
7// `show_window` can name it, and the lines a stop is sent back with. Four hooks change what a session does: an `open` of a page, a whole read of a large file
8// (turned away once with its outline, `reading.ts`), an `AskUserQuestion` Bridge answers first, and a stop on a reply that names what the owner owes outside
9// `waiting_for`, sent back once (`sendBack`); every other answers with what `next` returned and lets its report go unawaited, so
10// Fleet being down costs the session nothing (`fleet.ts`). **No message text and no prompt leaves, apart from the first
11// line of the first prompt as a title, the first line of what a turn ended on as the reply Fleet shows, the first line of a shell command, the text of each item on the task list the agent wrote, a question put to Bridge, and each line a reply named as owed that the session left out of
12// `waiting_for` after it was sent back.** A message is reported as who it went to
13// or came from, and how many. A file a session wrote or read is reported as its path from the session's directory,
14// and never its content. What fills the context window is reported as names, paths and counts, never contents.
15// The Loadout is reported the same way: each skill, subagent, MCP server and tool, memory file, output style,
16// Armada's rules and this mod's own `armadaSession` block by name and where it came from, and each skill, MCP
17// tool, loaded tool and subagent the agent used by name, never a body, an input or a prompt (`loadoutOf`).
18//
19// The helpers are top-level because the engine follows `$` only into a function
20// declared at the top of a file, and refuses the module otherwise.
21
22import type { Engine, Register } from 'claude-code'
23
24import {
25 answersIn,
26 artifactOf,
27 usedFact,
28 customTitleIn,
29 ghAct,
30 ghIssueCreate,
31 issuesIn,
32 mayMoveBranch,
33 micros,
34 breakdownOf,
35 commitIn,
36 madeTask,
37 planOf,
38 spentUntil,
39 pagesOpenedIn,
40 pullRequestsIn,
41 pushIn,
42 senderOf,
43 titleOf,
44 todoTasks,
45 updatedTask,
46 storedTasks,
47 taskListDir,
48 saidOf,
49 withoutMarkup,
50 effortOf,
51 modeOf,
52 modelName,
53 MOD_VERSION,
54 agentItemsIn,
55 backgroundEndOf,
56 backgroundOf,
57 isCovered,
58 needsSaidIn,
59 sentBackReason,
60 waitingItemsOf,
61 withReplyNeeds,
62 promptDetail,
63 transcriptPath,
64 agentUseOrigin,
65 loadoutOf,
66 searchedOf,
67 skillUseOrigin,
68 styleOrigin,
69 toolOrigin,
70 waitedOf,
71} from './facts'
72import type { Equipment, LoadoutItem, LoadoutUse, RateLimit, WaitingItem } from './facts'
73import type { Asked, Door, Fact, Report, Task } from './fleet'
74import { turnedAway, wholeRead, WHOLE_READ_MOST } from './reading'
75
76const HARNESS = 'claude_code'
77const MEASURE_EVERY_MS = 10_000
78const RUNTIME_FILE = 'Library/Application Support/Armada/fleet.json'
79const WAIT_MS = 1500
80// What a subagent's start waits for the Logbook: past it, the subagent starts with its prompt as it was.
81const LOGBOOK_WAIT_MS = 800
82// The tick that starts an ask when none is open, so also how soon one is retried after it failed.
83const ASK_EVERY_MS = 2000
84// How long Fleet may hold an ask, and how long the mod waits on one before it asks again.
85const HELD_WAIT_MS = 25_000
86const HELD_FETCH_MS = 35_000
87const SILENT_MS = 30_000
88const DOCS_ACTS = ['create', 'batch', 'update']
89
90type Dollar = Door & Pick<Engine, 'command' | 'process' | 'prompt' | 'session'>
91
92type Known = {
93 cwd: string
94 title?: string
95 branch?: string
96 prs: Map<string, Record<string, string>>
97 messages: Map<string, number>
98 artifacts: Map<string, Record<string, string>>
99 /** The tasks the agent started in the background, by task id, with the detail last told (`status` once ended). */
100 background: Map<string, Record<string, string>>
101 /** The agent's task list as its tools last left it, in order. */
102 tasks: Task[]
103 /** Whether the harness's own list was read for this process, which is done once. */
104 tasksRead: boolean
105 /** The list as Fleet last heard it, so a seed that changes nothing Fleet holds tells nothing. */
106 tasksTold: string
107 tuned?: Tuning
108 // The terminal's permission prompts open now, oldest first. Fleet is told of the first.
109 prompts: Prompt[]
110 /** What the session's last `waiting_for` call set, and whether this mod load saw one. */
111 waiting: WaitingItem[]
112 sawWaiting: boolean
113 turn: Turn
114 loadout: Loadout
115}
116
117/** What the Loadout is made from, the list Fleet last heard, and when the turn its uses go under began. */
118type Loadout = { equipment: Equipment; told?: LoadoutItem[]; turnAt: string }
119
120/**
121 * What this turn did about the owner. `sentBack` holds the lines the Stop hook sent the session back
122 * with; a turn is sent back once, then what is still missing is put in the list for it.
123 */
124type Turn = { setWaiting: boolean; asked: boolean; sentBack?: string[]; reported: boolean }
125
126const freshTurn = (): Turn => ({ setWaiting: false, asked: false, reported: false })
127
128type Prompt = { tool: string; detail: string }
129
130type Tuning = Extract<Fact, { kind: 'tuned' }>
131
132type Reading = { tokens?: number; window?: number; usd?: number; limits: RateLimit[]; changed: string[] }
133
134const known = new Map<string, Known>()
135let measuredAt = Number.NEGATIVE_INFINITY
136/** The newest reading the throttle held back, told when its ten seconds are up. */
137let measureHeld: Reading | undefined
138/** Files a whole read was turned away from in this load: the second asks for it on purpose. */
139const turnedAwayFrom = new Set<string>()
140
141function told(id: string, fact: Fact): Report {
142 return { harness: HARNESS, session_id: id, fact }
143}
144
145function everything(): Report[] {
146 return [...known].flatMap(([id, one]) => [
147 told(id, { kind: 'started', cwd: one.cwd, title: one.title, origin: 'terminal', mod_version: MOD_VERSION }),
148 ...(one.tuned === undefined ? [] : [told(id, one.tuned)]),
149 ...(one.branch === undefined
150 ? []
151 : [told(id, { kind: 'attached', attachment: { kind: 'branch', target: one.branch } })]),
152 ...[...one.prs].map(([number, detail]) =>
153 told(id, { kind: 'attached', attachment: { kind: 'pr', target: number, detail } }),
154 ),
155 ...[...one.artifacts].map(([target, detail]) =>
156 told(id, { kind: 'attached', attachment: { kind: 'artifact', target, detail } }),
157 ),
158 ...[...one.background].flatMap(([target, detail]) => [
159 told(id, { kind: 'attached', attachment: { kind: 'background', target, detail } }),
160 ...(detail.status === undefined ? [] : [told(id, { kind: 'settled', attachment: { kind: 'background', target }, state: 'spent' as const })]),
161 ]),
162 ...(one.tasks.length === 0 ? [] : [told(id, { kind: 'tasks', tasks: one.tasks })]),
163 ...one.prompts.slice(0, 1).map(open => told(id, promptFact(open))),
164 ...(one.loadout.told === undefined ? [] : [told(id, { kind: 'equipped', loadout: { items: one.loadout.told } })]),
165 ])
166}
167
168// What was dropped while Fleet was out of reach is not replayed, so what the
169// sessions hold is told again from `everything` when it answers.
170let queue: Promise<void> = Promise.resolve()
171let silentUntil = 0
172let wasOut = false
173
174
175async function portOf($: Door): Promise<number | undefined> {
176 const home = await $.env.get('HOME')
177 if (!home) return undefined
178 const file = JSON.parse(await $.fs.read(`${home}/${RUNTIME_FILE}`)) as { port?: unknown }
179 const port = file.port
180 if (typeof port !== 'number' || !Number.isInteger(port) || port < 1 || port > 65535) {
181 return undefined
182 }
183 return port
184}
185
186// **Slow is not down.** A connection that fails is Fleet out of reach, and a request still unanswered
187// after `WAIT_MS` is only Fleet busy: the report is left to land and the next goes behind it.
188async function post($: Door, report: Report): Promise<boolean> {
189 const port = await portOf($)
190 if (port === undefined) return false
191 const sent = $.http.fetch(`http://127.0.0.1:${port}/sessions/report`, {
192 method: 'POST',
193 headers: { 'content-type': 'application/json' },
194 body: JSON.stringify(report),
195 })
196 // Handled here too, so a refusal that arrives after the wait is not left unhandled.
197 sent.catch(() => undefined)
198 await Promise.race([sent, $.clock.sleep(WAIT_MS)])
199 return true
200}
201
202async function deliver($: Door, report: Report): Promise<void> {
203 const now = await $.clock.now()
204 if (now < silentUntil) return
205 try {
206 const reports = wasOut ? [...everything(), report] : [report]
207 for (const one of reports) {
208 if (!(await post($, one))) throw new Error('out of reach')
209 }
210 wasOut = false
211 } catch {
212 silentUntil = now + SILENT_MS
213 wasOut = true
214 }
215}
216
217// What a person sent this session from Bridge. Each is submitted as the person's
218// own prompt, which starts a turn when the session is idle and waits for it when
219// it is not (spike 27). One at a time, so they keep their order.
220let submitting: Promise<void> = Promise.resolve()
221
222// **One ask is held open at a time**, and Fleet answers it the moment something is held, so a
223// message arrives when it is sent and not at the next tick. It is its own path: the reports'
224// silence does not gate it, and its failures are met here (the tick asks again).
225let holding = false
226
227async function submitHeld($: Dollar): Promise<void> {
228 if (holding) return
229 holding = true
230 try {
231 while (await askHeld($)) continue
232 } finally {
233 holding = false
234 }
235}
236
237/** One held ask. True to ask again at once; false where the tick should try later. */
238async function askHeld($: Dollar): Promise<boolean> {
239 const port = await portOf($)
240 if (port === undefined) return false
241 const id = await $.session.id()
242 const began = await $.clock.now()
243 const asked = await Promise.race([
244 $.http.fetch(`http://127.0.0.1:${port}/sessions/held`, {
245 method: 'POST',
246 headers: { 'content-type': 'application/json' },
247 body: JSON.stringify({ session_id: id, wait_ms: HELD_WAIT_MS }),
248 }),
249 $.clock.sleep(HELD_FETCH_MS).then(() => undefined),
250 ])
251 if (asked === undefined || !asked.ok) return false
252 const held = JSON.parse(asked.text) as { messages?: unknown; commands?: unknown; end?: unknown }
253 // A command is run as typed: the engine refuses a slash command submitted as text.
254 const commands = Array.isArray(held.commands) ? held.commands : []
255 for (const one of commands as { command?: unknown; args?: unknown }[]) {
256 if (typeof one.command !== 'string' || typeof one.args !== 'string') continue
257 const { command, args } = one
258 submitting = submitting
259 .then(() => $.command.run({ command, args }))
260 .then(() => tuned($, id, {}))
261 .catch(() => undefined)
262 }
263 const messages = Array.isArray(held.messages) ? held.messages : []
264 for (const text of messages) {
265 if (typeof text !== 'string') continue
266 submitting = submitting
267 .then(() => $.prompt.submit({ text, asUser: true }))
268 .then(() => undefined)
269 .catch(() => undefined)
270 }
271 // End session pressed in Bridge: `/exit`, as the person would type it, behind the messages above.
272 // It waits for the session to be idle, so a message submitted just before has its turn first.
273 const end = held.end === true
274 if (end) {
275 submitting = submitting
276 .then(() => $.command.run({ command: 'exit' }))
277 .then(() => undefined)
278 .catch(() => undefined)
279 }
280 // A Fleet that answers at once with nothing (one from before the wait, or a session it has not
281 // heard of yet) is asked no faster than the tick used to.
282 const took = (await $.clock.now()) - began
283 if (commands.length === 0 && messages.length === 0 && !end && took < ASK_EVERY_MS) {
284 await $.clock.sleep(ASK_EVERY_MS - took)
285 }
286 return true
287}
288
289/** Queue a report, in order. Never throws and never waits. */
290function send($: Door, report: Report): void {
291 queue = queue.then(() => deliver($, report)).catch(() => undefined)
292}
293
294/** Wait, within a short bound, for what is queued. */
295async function flush($: Door): Promise<void> {
296 await Promise.race([queue, $.clock.sleep(WAIT_MS * 2)])
297}
298
299// A fact that was still being worked out when its session ended is dropped, so
300// `ended` is the last thing Fleet hears of a session.
301function say($: Door, id: string, fact: Fact): void {
302 if (fact.kind !== 'started' && fact.kind !== 'ended' && !known.has(id)) return
303 send($, told(id, fact))
304}
305
306function settle($: Door, id: string, kind: string, target: string, state: 'spent' | 'given_back') {
307 say($, id, { kind: 'settled', attachment: { kind, target }, state })
308}
309
310async function branchOf($: Dollar, cwd: string): Promise<string | undefined> {
311 const ran = await $.process.run(['git', 'rev-parse', '--abbrev-ref', 'HEAD'], {
312 cwd,
313 timeoutMs: 3000,
314 })
315 const name = ran.stdout.trim()
316 return ran.exitCode === 0 && name !== '' && name !== 'HEAD' ? name : undefined
317}
318
319/**
320 * The pull request on the branch checked out in `cwd`, or the one `ref` names. `created` marks one this
321 * session opened, which Fleet credits wherever the session stood.
322 */
323async function pullRequestOn($: Dollar, id: string, one: Known, cwd: string, ref?: string, created = false): Promise<void> {
324 const ran = await $.process.run(['gh', 'pr', 'view', ...(ref === undefined ? [] : [ref]), '--json', 'number,url,state,title,headRefName,isDraft'], {
325 cwd,
326 timeoutMs: 10_000,
327 })
328 if (ran.exitCode !== 0) return
329 const view = JSON.parse(ran.stdout) as {
330 number?: number
331 url?: string
332 state?: string
333 title?: string
334 headRefName?: string
335 isDraft?: boolean
336 }
337 if (typeof view.number !== 'number') return
338 const number = String(view.number)
339 // The ledger names a pull request by its title, so a row told without one draws as a bare number.
340 const detail: Record<string, string> = {
341 url: view.url ?? '',
342 address: view.url ?? '',
343 state: view.isDraft === true && view.state === 'OPEN' ? 'draft' : (view.state ?? '').toLowerCase(),
344 ...(view.title === undefined ? {} : { title: view.title }),
345 ...(view.headRefName === undefined ? {} : { branch: view.headRefName }),
346 ...(created ? { created: 'true' } : {}),
347 }
348 one.prs.set(number, detail)
349 say($, id, { kind: 'attached', attachment: { kind: 'pr', target: number, detail } })
350 if (view.state === 'MERGED') settle($, id, 'pr', number, 'spent')
351 if (view.state === 'CLOSED') settle($, id, 'pr', number, 'given_back')
352}
353
354/**
355 * Where the branch is now, and the pull request on it. **Read from where the session is now**, not
356 * from the directory last reported: a session that left a slot, or a slot another session leased
357 * since, would otherwise be credited with the branch checked out there. Fleet checks it too.
358 */
359async function look($: Dollar, id: string): Promise<void> {
360 try {
361 const one = known.get(id)
362 if (one === undefined) return
363 const cwd = await $.session.cwd()
364 const branch = await branchOf($, cwd)
365 if (branch === one.branch) return
366 if (one.branch !== undefined && branch === undefined) {
367 settle($, id, 'branch', one.branch, 'given_back')
368 }
369 one.branch = branch
370 if (branch === undefined) return
371 say($, id, { kind: 'attached', attachment: { kind: 'branch', target: branch } })
372 await pullRequestOn($, id, one, cwd).catch(() => undefined)
373 } catch {
374 // A directory with no repository, or no `git`: nothing to report.
375 }
376}
377
378const SHOWN_INSTEAD =
379 "Shown in Bridge's window instead. Use the armada show_window tool to show the owner a page; never `open` it."
380
381async function showPages($: Dollar, urls: string[]): Promise<void> {
382 try {
383 const port = await portOf($)
384 if (port === undefined) return
385 const session_id = await $.session.id()
386 for (const url of urls) {
387 await Promise.race([
388 $.http.fetch(`http://127.0.0.1:${port}/sessions/window`, {
389 method: 'POST',
390 headers: { 'content-type': 'application/json' },
391 body: JSON.stringify({ url, session_id }),
392 }),
393 $.clock.sleep(WAIT_MS),
394 ])
395 }
396 } catch {
397 // Fleet out of reach: the line is still not run.
398 }
399}
400
401/** What is put to Bridge: a question's input, or a call the terminal is asking permission for and its tool. */
402type Asking = { input: unknown; tool?: string }
403
404/** How long Fleet holds one poll, and how long the mod waits on a request before it asks again. */
405const POLL_FETCH_MS = 35_000
406const POLL_RETRY_MS = 3000
407
408async function postAsk($: Door, port: number, body: unknown, bound: number): Promise<Asked | undefined> {
409 const sent = await Promise.race([
410 $.http.fetch(`http://127.0.0.1:${port}/sessions/ask/terminal`, {
411 method: 'POST',
412 headers: { 'content-type': 'application/json' },
413 body: JSON.stringify(body),
414 }),
415 $.clock.sleep(bound).then(() => undefined),
416 ])
417 return sent?.ok === true ? (JSON.parse(sent.text) as Asked) : undefined
418}
419
420/**
421 * The terminal's question, put to Bridge. **Posted once, then polled for**: Fleet keeps the question
422 * and any answer from Bridge, so a request that times out, a dropped connection or a Fleet that
423 * restarts costs one poll and never the question. Resolves with the answer, or nothing where Fleet
424 * says the card is gone. A Fleet that is out of reach is waited out quietly; the terminal's own
425 * prompt is all there is meanwhile. `over` ends the loop once the terminal's prompt has. `first` is
426 * Fleet's answer to the post the hook made before the prompt opened, where it came in time.
427 */
428async function putToBridge($: Door, id: string, asking: Asking, over: { done: boolean }, first?: Asked): Promise<Asked | undefined> {
429 try {
430 if (first !== undefined && first.outcome !== 'asked') return undefined
431 let call = first?.outcome === 'asked' ? first.call : undefined
432 while (call === undefined && !over.done) {
433 const port = await portOf($).catch(() => undefined)
434 const put = port === undefined ? undefined : await postAsk($, port, { kind: 'asks', session_id: id, ...asking }, POLL_FETCH_MS).catch(() => undefined)
435 if (put?.outcome === 'asked') call = put.call
436 else if (put?.outcome === 'refused') return put
437 else if (put !== undefined) return undefined
438 else await $.clock.sleep(POLL_RETRY_MS)
439 }
440 while (call !== undefined && !over.done) {
441 const port = await portOf($).catch(() => undefined)
442 const polled = port === undefined ? undefined : await postAsk($, port, { kind: 'wait', session_id: id, call }, POLL_FETCH_MS).catch(() => undefined)
443 if (polled === undefined) await $.clock.sleep(POLL_RETRY_MS)
444 else if (polled.outcome !== 'waiting') return polled
445 }
446 return undefined
447 } catch {
448 return undefined
449 }
450}
451
452/**
453 * The question's first post, bounded short: it runs before the terminal's prompt opens, so a question
454 * Fleet refuses (a walk is open) never opens one. A Fleet slow or out of reach answers nothing here,
455 * and `putToBridge` posts again.
456 */
457async function firstPut($: Door, id: string, asking: Asking): Promise<Asked | undefined> {
458 try {
459 const port = await portOf($).catch(() => undefined)
460 if (port === undefined) return undefined
461 return await postAsk($, port, { kind: 'asks', session_id: id, ...asking }, WAIT_MS)
462 } catch {
463 return undefined
464 }
465}
466
467/** The terminal's own prompt ended first, so Bridge's card closes. */
468async function settledInTerminal($: Door, id: string, answered: boolean): Promise<void> {
469 try {
470 const port = await portOf($)
471 if (port === undefined) return
472 await Promise.race([
473 $.http.fetch(`http://127.0.0.1:${port}/sessions/ask/terminal`, {
474 method: 'POST',
475 headers: { 'content-type': 'application/json' },
476 body: JSON.stringify({ kind: 'settled', session_id: id, answered }),
477 }),
478 $.clock.sleep(WAIT_MS),
479 ])
480 } catch {
481 // Fleet out of reach: its card closes when its hold runs out.
482 }
483}
484
485/** `ask_in_window`, for a question about the page the walk shows; any other question waits. */
486const ASK_IN_WINDOW = "To ask the owner about something on a page you showed him, call ask_in_window with the question, its options, the page's url and a CSS selector for the place, passing session_id, then end your turn.";
487
488/** `show_sketch`, for any diagram, so the owner is never handed ASCII art. */
489const SHOW_SKETCH = "To show the owner a diagram, a flow, an architecture or a layout, call show_sketch with a title and a scene, passing session_id; never draw ASCII art.";
490
491/** `show_file`, to put a file in the owner's side panel to read or edit. */
492const SHOW_FILE = "To put a file in front of the owner to read or edit, call show_file with its path, passing session_id; it opens in Bridge's side panel.";
493
494function idNote(id: string): string {
495 return `Your Armada job id is ${id}. Pass it as session_id to the armada show_window tool. To show the owner a web page (a walk, a mock, a dev server), call show_window; to offer several takes of one change, pass variations, a list of {name, url}. To walk him through a page step by step, pass steps, a list of {say, plus one verb: press, look, hover, later, paste, type with into, key with on, select with in, or drag with by} aimed at {role, name}: Bridge rings each target and acts on it when he presses Next. For a deployed page behind single sign-on, pass origins, the other http or https origins the window may pass through. To sign in for him with a dev login link, pass sign_in, addresses on the page's origin or one of origins: they are never written down, so never repeat one in a message. Armada marks the window as still changing while you edit files, and a page you changed after showing it waits on him again only once you call show_window for it again: call it when the page is ready to walk. Never run \`open\`. Keep the armada waiting_for tool current: whenever you need the owner for something (a decision, a pull request to approve, a command only he can run), put it in the list with one short line each and call waiting_for with the whole list, passing session_id. Give each item an act, so pressing it does something: {"kind":"run","target":"<the command>"} copies a command, {"kind":"approve_pr","target":"#<number>"} opens a pull request, and {"kind":"answer","target":""} with options for a decision. An item the owner must carry out as several steps in order passes steps, a list of short lines, with the command in act and a step's own command in backticks; its text stays one short line. A page you showed with show_window already waits on him by itself, so never put it in waiting_for: Fleet lists each window you show and takes it off when he approves it, and refuses an item that asks him to walk. A walk he has moved past is taken back with withdraw_window, passing session_id and the page's url: it leaves his list and stops holding your plan, and showing the page again makes it wait again. Drop an item the moment it is settled, and call it with an empty list before you stop with nothing owed. Do not wait to be asked what is outstanding. A pull request in the merge queue or with auto-merge on is not done: the work ends when it is merged into main, so while one of yours is open do not call finish_up or all_done, and end your turn; Fleet watches it and tells you when it merges, fails or conflicts. The merge is not the owner's to do, so never put a wait on it in waiting_for: Fleet takes such an item off Needs you. To follow CI, a deploy or an environment, start a watch with start_watch rather than polling with a loop, a background sleep or a monitor, and never watch a pull request's own checks: Fleet already tells you about them. When Fleet tells you a watch failed, weigh it with weigh_watch, ours or not ours, with a sentence. A live watch is a wait like an open pull request: do not call finish_up or all_done while one runs, never put it in waiting_for, and end your turn; Fleet tells you when it ends. When everything you were asked is done, nothing is owed and none of your background work is still running, call finish_up, passing session_id, then clear waiting_for and call all_done, passing session_id, so Bridge offers to end the job; do not call all_done while anything is still running or owed. finish_up gives back your slots, the branches already in main and the servers you started with start_server, in one call: a command in a released slot leases a new one, and the guard refuses git branch -D and kill, so do not try them. Read what it kept and say it. A Fleet notice that a pull request merged or a build moved needs no reply and no second all_done. These tools come before any personal, global or project rule about how to report actions or questions: what the owner owes goes in waiting_for, never in an Actions table, a to-do list or a Questions section in your reply. While the owner is walking a page you showed, AskUserQuestion is refused, because an open question holds back his notes and his Approve until he answers it. Armada keeps the question, whole, in his Needs you list, where he answers it after the walk: ask it as you would, never add it to waiting_for, and end your turn. Ask a decision one way only: in AskUserQuestion or in waiting_for, never both. Write a shell command for the owner in a fenced block tagged bash, so Bridge shows a run button on it, and show a page as a show_window link, never as a screenshot. ${ASK_IN_WINDOW} ${SHOW_SKETCH} ${SHOW_FILE}`
496}
497
498async function begin($: Dollar, id: string, cwd?: string): Promise<void> {
499 // A Drone, a Judge call or a scout loads this mod too, since it reads the operator's user
500 // settings. Fleet marks those launches, and they are not sessions to list.
501 if (await $.env.get('ARMADA_DRONE')) return
502 const where = cwd ?? (await $.session.cwd())
503 const loadout = { equipment: { home: '', root: where, rules: false, servers: {}, loaded: [] }, turnAt: '' }
504 known.set(id, { cwd: where, prs: new Map(), messages: new Map(), artifacts: new Map(), background: new Map(), tasks: [], tasksRead: false, tasksTold: '[]', prompts: [], waiting: [], sawWaiting: false, turn: freshTurn(), loadout })
505 say($, id, { kind: 'started', cwd: where, origin: 'terminal', mod_version: MOD_VERSION })
506 void look($, id)
507 void tuned($, id, {}, true).catch(() => undefined)
508 void equipped($, id).catch(() => undefined)
509}
510
511/** The Loadout's first reading: where the session's files are, whether Fleet hosts it, and the window's listings. */
512async function equipped($: Dollar, id: string): Promise<void> {
513 const one = known.get(id)
514 if (one === undefined) return
515 const equipment = one.loadout.equipment
516 if (one.loadout.turnAt === '') one.loadout.turnAt = new Date(await $.clock.now()).toISOString()
517 equipment.home = (await $.env.get('HOME')) ?? ''
518 equipment.root = await $.session.root().catch(() => equipment.root)
519 equipment.rules = Boolean(await $.env.get('ARMADA_SESSION'))
520 await equip($, id, true)
521}
522
523/** The Loadout, told when it moved; `read` takes the window's listings afresh first. */
524async function equip($: Dollar, id: string, read = false): Promise<void> {
525 const one = known.get(id)
526 if (one === undefined) return
527 if (read) one.loadout.equipment.breakdown = (await breakdownNow($)) ?? one.loadout.equipment.breakdown
528 const items = loadoutOf(one.loadout.equipment)
529 if (JSON.stringify(items) === JSON.stringify(one.loadout.told)) return
530 one.loadout.told = items
531 say($, id, { kind: 'equipped', loadout: { items } })
532}
533
534/** One skill, MCP tool, loaded tool or subagent the agent used, under the turn it was used in. */
535async function equipmentUsed($: Dollar, use: Omit<LoadoutUse, 'turn_started_at'> | undefined): Promise<void> {
536 if (use === undefined) return
537 const [id, one] = await current($)
538 say($, id, { kind: 'used', use: { turn_started_at: one.loadout.turnAt, ...use } })
539}
540
541/** What a hook learned of the servers and the loaded tools, folded in and told if it moved anything. */
542async function reequipped($: Dollar, servers: Equipment['servers'], loaded: string[] = []): Promise<void> {
543 const [id, one] = await current($)
544 const equipment = one.loadout.equipment
545 equipment.servers = { ...equipment.servers, ...servers }
546 equipment.loaded = [...new Set([...equipment.loaded, ...loaded])]
547 await equip($, id)
548}
549
550/**
551 * The output style a system prompt was composed with. A teammate's or an analysis prompt is not the
552 * session's own; the default style is no item.
553 */
554async function styled($: Dollar, name: string | undefined): Promise<void> {
555 const one = known.get(await $.session.id())
556 if (one === undefined || one.loadout.equipment.style?.name === name) return
557 const equipment = one.loadout.equipment
558 if (name === undefined) {
559 equipment.style = undefined
560 } else {
561 const inRepository = await $.fs.exists(`${equipment.root}/.claude/output-styles/${name}.md`).catch(() => false)
562 equipment.style = { name, ...styleOrigin(name, inRepository) }
563 }
564 await equip($, await $.session.id())
565}
566
567/** A use with its source, or nothing where Armada has no source to give it. */
568function sourced(use: Omit<LoadoutUse, 'turn_started_at' | 'source' | 'from'>, origin: Pick<LoadoutUse, 'source' | 'from'> | undefined) {
569 return origin === undefined ? undefined : { ...use, ...origin }
570}
571
572/**
573 * What the terminal runs on, told when it changed: the model, and the effort and permission mode a
574 * hook input carries. The commands it lists go once, with the first. **The mode is only read**: the
575 * mods API cannot switch a live session's (spike 27).
576 */
577async function tuned(
578 $: Dollar,
579 id: string,
580 seen: { mode?: string; effort?: unknown },
581 withCommands = false,
582): Promise<void> {
583 const one = known.get(id)
584 if (one === undefined) return
585 const mode = modeOf(seen.mode)
586 const effort = effortOf(seen.effort)
587 const next: Tuning = {
588 kind: 'tuned',
589 model: modelName(await $.session.model()),
590 ...(effort === undefined ? {} : { effort }),
591 ...(mode === undefined ? {} : { mode }),
592 }
593 if (withCommands) {
594 next.commands = (await $.command.list()).map(c => ({ name: c.name, says: c.description }))
595 next.mod_version = MOD_VERSION
596 }
597 const before = one.tuned
598 const same =
599 before !== undefined &&
600 before.model === next.model &&
601 before.effort === (next.effort ?? before.effort) &&
602 before.mode === (next.mode ?? before.mode)
603 if (same && !withCommands) return
604 one.tuned = { ...before, ...next, commands: undefined, mod_version: undefined }
605 say($, id, next)
606}
607
608async function seen($: Dollar, mode: string | undefined, effort: unknown): Promise<void> {
609 try {
610 const [id] = await current($)
611 await tuned($, id, { mode, effort })
612 } catch {
613 // What the terminal runs on is a nicety: nothing here is worth a session's turn.
614 }
615}
616
617/** The session's id, starting it first where it began without a `session.start`. */
618async function current($: Dollar): Promise<[string, Known]> {
619 const id = await $.session.id()
620 if (!known.has(id)) await begin($, id)
621 const one = known.get(id)
622 if (one === undefined) throw new Error('unreported session')
623 return [id, one]
624}
625
626async function afterBash($: Dollar, command: string, text: string): Promise<void> {
627 const [id, one] = await current($)
628 const act = ghAct(command)
629 if (act?.act === 'create') {
630 // What `gh pr create` printed is this session's own, whichever slot the command ran in.
631 for (const pr of pullRequestsIn(text)) {
632 const detail = { url: pr.url, created: 'true' }
633 one.prs.set(pr.number, detail)
634 say($, id, { kind: 'attached', attachment: { kind: 'pr', target: pr.number, detail } })
635 await pullRequestOn($, id, one, await $.session.cwd(), pr.url, true).catch(() => undefined)
636 }
637 }
638 // What `gh issue create` printed is an issue the session filed. Fleet keeps it only where it is in
639 // the session's own repository, and reads its title and state from the forge.
640 if (ghIssueCreate(command)) {
641 for (const issue of issuesIn(text)) {
642 say($, id, { kind: 'attached', attachment: { kind: 'issue', target: issue.number, detail: { address: issue.url } } })
643 }
644 }
645 if (act?.act === 'merge' || act?.act === 'close') {
646 const target = act.number ?? (one.prs.size === 1 ? [...one.prs.keys()][0] : undefined)
647 if (target !== undefined) {
648 settle($, id, 'pr', target, act.act === 'merge' ? 'spent' : 'given_back')
649 }
650 }
651 // Read from what the commands printed, so a commit with nothing staged and a push with nothing to
652 // send are not told. Fleet enters them on the timeline, where the build record reads its road.
653 const committed = commitIn(command, text)
654 if (committed !== undefined) say($, id, { kind: 'committed', ...committed })
655 const pushed = pushIn(command, text)
656 if (pushed !== undefined) say($, id, { kind: 'pushed', ...pushed })
657 if (mayMoveBranch(command) || act?.act === 'create') {
658 const cwd = await $.session.cwd()
659 if (cwd !== one.cwd) {
660 one.cwd = cwd
661 say($, id, { kind: 'moved', cwd })
662 }
663 await look($, id)
664 }
665}
666
667/**
668 * The agent's task list, whole, after one of its task tools ran. A subagent's `TaskCreate` and `TaskUpdate`
669 * write the same list (measured on claude 2.1.300), so they are heard too, each task marked with who made it.
670 * A subagent's `TodoWrite` is a list of its own and would replace this one: not heard. A list that did not
671 * change is not told again.
672 *
673 * **A process that began after the list was made does not hold it** (a session resumed after Fleet restarted,
674 * or moved into a slot), so the first of these tools reads the harness's own list from disk (`stored`) and
675 * the call's change goes on top of it. Without that, a `TaskUpdate` named a task nothing here had made and
676 * was never told. The `TaskCreate` hears `by` from the call; a task made before this process has none.
677 */
678async function planned($: Dollar, next: (list: Task[]) => Task[] | undefined, seed = true): Promise<void> {
679 const [id, one] = await current($)
680 if (seed && !one.tasksRead) {
681 const kept = await stored($, id).catch(() => undefined)
682 if (kept !== undefined && !one.tasksRead) {
683 one.tasksRead = true
684 if (one.tasks.length === 0) one.tasks = kept
685 }
686 }
687 const tasks = next(one.tasks) ?? one.tasks
688 one.tasks = tasks
689 const now = JSON.stringify(tasks)
690 if (now === one.tasksTold) return
691 one.tasksTold = now
692 say($, id, { kind: 'tasks', tasks })
693}
694
695/** The harness's own list for this session, or nothing where it has none yet or cannot be read. */
696async function stored($: Dollar, id: string): Promise<Task[] | undefined> {
697 const home = await $.env.get('HOME')
698 if (!home) return undefined
699 const dir = taskListDir(home, (await $.env.get('CLAUDE_CODE_TASK_LIST_ID')) || id)
700 const entries = await $.fs.list(dir)
701 const files = await Promise.all(
702 entries
703 .filter(one => one.kind === 'file' && one.name.endsWith('.json') && !one.name.startsWith('.'))
704 .map(one => $.fs.read(`${dir}/${one.name}`).then(text => (typeof text === 'string' ? text : ''), () => '')),
705 )
706 return storedTasks(files)
707}
708
709async function spawned(
710 $: Dollar,
711 target: string,
712 type: string,
713 description: string,
714 call?: string,
715): Promise<void> {
716 const [id] = await current($)
717 // The call that started it: Fleet keys a hosted subagent's touches by it, the Field matches them to this row by it.
718 const detail = { type, description: description.slice(0, 80), ...(call === undefined || call === target ? {} : { call }) }
719 say($, id, { kind: 'attached', attachment: { kind: 'subagent', target, detail } })
720}
721
722/**
723 * A shell command run in the background, or a Monitor, as the call's own result names it. **Told on the
724 * call and settled on the engine's notice**, and never on what the agent says of it.
725 */
726async function backgrounded(
727 $: Dollar,
728 tool: string,
729 input: Record<string, unknown>,
730 text: string,
731): Promise<void> {
732 const task = backgroundOf(tool, input, text)
733 if (task === undefined) return
734 const [id, one] = await current($)
735 one.background.set(task.target, task.detail)
736 say($, id, { kind: 'attached', attachment: { kind: 'background', target: task.target, detail: task.detail } })
737}
738
739/**
740 * A background task ended: by the engine's notice (`completed`, `failed`, or `killed` for one stopped), or
741 * by a `TaskStop` the agent called. Only a task this load saw start is settled, and once.
742 */
743async function backgroundEnded($: Dollar, target: string, word: string, exit?: string, output?: string): Promise<void> {
744 const [id, one] = await current($)
745 const held = one.background.get(target)
746 if (held === undefined || held.status !== undefined) return
747 const status = word === 'completed' ? 'completed' : word === 'killed' || word === 'stopped' ? 'killed' : 'failed'
748 const detail = { ...held, status, ...(exit === undefined || status === 'killed' ? {} : { exit }), ...(output === undefined ? {} : { output }) }
749 one.background.set(target, detail)
750 say($, id, { kind: 'attached', attachment: { kind: 'background', target, detail } })
751 settle($, id, 'background', target, 'spent')
752}
753
754/**
755 * A page published, a document written or a Claude Docs document made: an artifact on the ledger.
756 * Only what a person would open. A code edit is not told.
757 */
758async function made(
759 $: Dollar,
760 tool: string,
761 input: Record<string, unknown>,
762 text: string,
763 created: boolean,
764): Promise<void> {
765 const artifact = artifactOf(tool, input, text, created)
766 if (artifact === undefined) return
767 const [id, one] = await current($)
768 const detail: Record<string, string> = { form: artifact.form }
769 if (artifact.title !== undefined) detail.title = artifact.title
770 if (artifact.form === 'image' && one.artifacts.has(artifact.target)) return
771 one.artifacts.set(artifact.target, detail)
772 say($, id, { kind: 'attached', attachment: { kind: 'artifact', target: artifact.target, detail } })
773}
774
775async function used(
776 $: Dollar,
777 act: 'touched' | 'read' | 'ran',
778 input: Record<string, unknown>,
779 by?: { how?: 'write' | 'edit'; agent?: string },
780): Promise<void> {
781 const [id, one] = await current($)
782 const fact = usedFact(act, one.cwd, input, by)
783 if (fact !== undefined) say($, id, fact)
784}
785
786async function messaged($: Dollar, direction: 'sent' | 'received', who: string): Promise<void> {
787 const [id, one] = await current($)
788 const target = `${direction === 'sent' ? 'to' : 'from'}:${who}`
789 const count = (one.messages.get(target) ?? 0) + 1
790 one.messages.set(target, count)
791 const detail = { direction, count: String(count) }
792 say($, id, { kind: 'attached', attachment: { kind: 'message', target, detail } })
793}
794
795async function measured(
796 $: Dollar,
797 tokens?: number,
798 window?: number,
799 usd?: number,
800 limits: RateLimit[] = [],
801 changed: string[] = [],
802): Promise<void> {
803 const at = await $.clock.now()
804 const held = at - measuredAt < MEASURE_EVERY_MS
805 // A window that moved is the one reading nothing else reports, so it is not left behind by the throttle.
806 if (held && !changed.includes('rateLimits')) {
807 hold($, measuredAt + MEASURE_EVERY_MS - at, { tokens, window, usd, limits, changed })
808 return
809 }
810 measuredAt = at
811 measureHeld = undefined
812 const [id, one] = await current($)
813 const usage = { context_tokens: tokens, context_window: window, cost_micros: micros(usd) }
814 const plan = planOf(limits)
815 const fact: Extract<Fact, { kind: 'measured' }> = { kind: 'measured', usage }
816 if (plan.length > 0) fact.plan = plan
817 // `summary` estimates locally; `full` would call the token-count API for every tool and file.
818 const found = !held && changed.includes('context') ? await breakdownNow($) : undefined
819 if (found !== undefined) fact.context_breakdown = breakdownOf(found)
820 say($, id, fact)
821 if (found !== undefined) {
822 one.loadout.equipment.breakdown = found
823 await equip($, id)
824 }
825}
826
827/**
828 * Keeps a reading the throttle held back, over any older one, and tells it when the window is up,
829 * so the last reading of a burst is not left behind until something else is measured.
830 */
831function hold($: Dollar, wait: number, reading: Reading): void {
832 const older = measureHeld
833 measureHeld = {
834 tokens: reading.tokens ?? older?.tokens,
835 window: reading.window ?? older?.window,
836 usd: reading.usd ?? older?.usd,
837 limits: reading.limits.length > 0 ? reading.limits : (older?.limits ?? []),
838 changed: [...new Set([...(older?.changed ?? []), ...reading.changed])],
839 }
840 if (older !== undefined) return
841 void $.clock
842 .sleep(wait)
843 .then(() => {
844 const one = measureHeld
845 if (one === undefined) return
846 measureHeld = undefined
847 return measured($, one.tokens, one.window, one.usd, one.limits, one.changed)
848 })
849 .catch(() => undefined)
850}
851
852/** What one main-thread model request was answered over: uncached, cache-written and cache-read. */
853function stepTokens(usage: { input_tokens: number; cache_creation_input_tokens: number; cache_read_input_tokens: number }): number {
854 return usage.input_tokens + usage.cache_creation_input_tokens + usage.cache_read_input_tokens
855}
856
857async function breakdownNow($: Dollar) {
858 try {
859 return (await $.session.usage({ breakdown: 'summary' })).context.breakdown
860 } catch {
861 return undefined
862 }
863}
864
865/**
866 * A turn ended on the plan's limit. Fleet is told when the window that is full opens again, and
867 * wakes the session with `Continue` then; no window at or near full leaves nothing to wake it at.
868 */
869async function limited($: Dollar): Promise<void> {
870 const [id] = await current($)
871 const resets = spentUntil((await $.session.usage()).rateLimits)
872 if (resets !== undefined) say($, id, { kind: 'limited', resets_at: resets })
873}
874
875async function titled($: Dollar, prompt: string): Promise<void> {
876 const [id, one] = await current($)
877 const title = one.title === undefined ? titleOf(prompt) : undefined
878 if (title === undefined) return
879 one.title = title
880 say($, id, { kind: 'titled', title })
881}
882
883/**
884 * A turn began, so Fleet has the session working and the reply the turn before left is over. **Fleet
885 * reads this from the prompt going in and never from the model.** A slash command is not a turn:
886 * most of them end without one, so they would leave the session working with nothing to end it.
887 */
888async function turnBegan($: Dollar, prompt: string): Promise<void> {
889 if (withoutMarkup(prompt).trim().startsWith('/')) return
890 const [id, one] = await current($)
891 one.prompts = []
892 one.loadout.turnAt = new Date(await $.clock.now()).toISOString()
893 say($, id, { kind: 'turn_started' })
894}
895
896/** A turn ended: Fleet has the close of what it ended on, to read for an ask and show as the reply, with no call from the model. */
897function turnEnd(answer: string): Fact {
898 const said = saidOf(answer)
899 return said === undefined ? { kind: 'turn_completed' } : { kind: 'turn_completed', said }
900}
901
902/**
903 * A `/rename` in the terminal. **The name is what was typed**; a bare `/rename` has Claude Code
904 * make one up, which is read from the transcript it writes the entry to. It replaces any title
905 * and is told as `named`, so the first prompt's line never takes it back.
906 */
907async function renamed($: Dollar, typed: string): Promise<void> {
908 const [id, one] = await current($)
909 let title: string | undefined = typed.replace(/\s+/g, ' ').trim() || undefined
910 if (title === undefined) {
911 try {
912 const home = await $.env.get('HOME')
913 const cwd = await $.session.cwd()
914 title = home ? customTitleIn(await $.fs.read(transcriptPath(home, cwd, id))) : undefined
915 } catch {
916 // A transcript too large to read, or not there: the name is not known.
917 }
918 }
919 if (title === undefined) return
920 one.title = title
921 say($, id, { kind: 'titled', title, named: true })
922}
923
924function promptFact(open: Prompt): Fact {
925 return open.detail === '' ? { kind: 'permission_asked', tool: open.tool } : { kind: 'permission_asked', tool: open.tool, detail: open.detail }
926}
927
928/**
929 * The harness opened its own permission prompt, so the session waits on a person at the terminal.
930 * **The harness says so**, through its `PermissionRequest` hook; the agent is never asked. Fleet is
931 * told of the oldest open, which is the one the terminal shows.
932 */
933async function promptOpened($: Dollar, tool: string, input: unknown): Promise<void> {
934 const [id, one] = await current($)
935 const open = { tool, detail: promptDetail((input ?? {}) as Record<string, unknown>) }
936 one.prompts.push(open)
937 if (one.prompts.length === 1) say($, id, promptFact(open))
938}
939
940/**
941 * A tool call ended, so the prompt it raised is closed: it was answered and ran, or was refused. The
942 * next one open, if any, is told in its place.
943 */
944async function promptSettled($: Dollar, tool: string, input: Record<string, unknown>): Promise<void> {
945 const id = await $.session.id()
946 const one = known.get(id)
947 if (one === undefined || one.prompts.length === 0) return
948 const detail = promptDetail(input)
949 const at = one.prompts.findIndex(open => open.tool === tool && open.detail === detail)
950 if (at < 0) return
951 one.prompts.splice(at, 1)
952 if (at !== 0) return
953 say($, id, { kind: 'permission_settled' })
954 const next = one.prompts[0]
955 if (next !== undefined) say($, id, promptFact(next))
956}
957
958/** A tool call under way whose terminal prompt Bridge may answer first. */
959type Underway = { answer: (asked: Asked) => void; over: { done: boolean }; put: boolean }
960
961// The calls under way by `callKey`, oldest first, and the ones Bridge allowed, which `tool.check` lets
962// run again without the terminal's prompt.
963const underway = new Map<string, Underway[]>()
964const allowedInBridge = new Set<string>()
965
966function callKey(tool: string, input: Record<string, unknown>): string {
967 return `${tool}\n${promptDetail(input)}`
968}
969
970/**
971 * The terminal's prompt, put to Bridge as well: the call that raised it takes Bridge's answer where it
972 * comes first. Fleet keeps it until a person answers or the call ends.
973 */
974async function promptPut($: Dollar, tool: string, input: unknown): Promise<void> {
975 const id = await $.session.id()
976 if (!known.has(id)) return
977 const call = underway.get(callKey(tool, (input ?? {}) as Record<string, unknown>))?.find(one => !one.put)
978 if (call === undefined) return
979 call.put = true
980 const asked = await putToBridge($, id, { tool, input }, call.over)
981 if (asked?.outcome === 'answered' || asked?.outcome === 'refused') call.answer(asked)
982}
983
984/**
985 * A turn is stopping on a reply that names what the owner owes and a `waiting_for` list that does not
986 * hold it. The first stop is blocked with the lines found; the second, or one another hook already sent
987 * back (`stopActive`), is let through and the lines go in the list marked as read from the reply, so
988 * the session can never loop on it.
989 */
990async function sendBack($: Dollar, answer: string, stopActive: boolean): Promise<string | undefined> {
991 if (await $.env.get('ARMADA_DRONE')) return undefined
992 const [id, one] = await current($)
993 const turn = one.turn
994 if (turn.reported) return undefined
995 const found = needsSaidIn(answer)
996 if (turn.sentBack === undefined && !stopActive) {
997 if (found.length === 0 || turn.asked || isCovered(found, one.waiting)) return undefined
998 turn.sentBack = found
999 turn.setWaiting = false
1000 return sentBackReason(found, id)
1001 }
1002 turn.reported = true
1003 const needs = [...new Set([...(turn.sentBack ?? []), ...found])]
1004 const complied = turn.sentBack !== undefined && turn.setWaiting && one.waiting.length > 0
1005 if (needs.length === 0 || turn.asked || complied || isCovered(needs, one.waiting)) return undefined
1006 void putInWaiting($, id, one, needs).catch(() => undefined)
1007 return undefined
1008}
1009
1010/**
1011 * The session's list with the reply's lines added, set through the route the `waiting_for` tool posts to.
1012 * **The post replaces the list, so it starts from the one Fleet holds**; where that cannot be read, from
1013 * the mod's own copy only if this load saw the agent set it, and otherwise nothing is posted.
1014 */
1015async function putInWaiting($: Door, id: string, one: Known, needs: string[]): Promise<void> {
1016 const port = await portOf($)
1017 if (port === undefined) return
1018 const read = await Promise.race([
1019 $.http.fetch(`http://127.0.0.1:${port}/sessions/one?session_id=${encodeURIComponent(id)}`),
1020 $.clock.sleep(WAIT_MS).then(() => undefined),
1021 ]).catch(() => undefined)
1022 const held = read?.ok === true ? agentItemsIn(read.text) : undefined
1023 const base = held ?? (one.sawWaiting ? one.waiting : undefined)
1024 if (base === undefined) return
1025 const items = withReplyNeeds(base, needs)
1026 if (items.length === base.length) return
1027 const sent = await Promise.race([
1028 $.http.fetch(`http://127.0.0.1:${port}/sessions/waiting`, {
1029 method: 'POST',
1030 headers: { 'content-type': 'application/json' },
1031 body: JSON.stringify({ session_id: id, items }),
1032 }),
1033 $.clock.sleep(WAIT_MS).then(() => undefined),
1034 ])
1035 if (sent?.ok === true) one.waiting = items
1036}
1037
1038/**
1039 * The Logbook lines for a subagent about to start, from Fleet: the habits and the entries whose paths match
1040 * the ones its prompt names. **Quiet**: a Fleet that is out, slow, older or refuses gives an empty string.
1041 */
1042async function logbookFor($: Dollar, prompt: string): Promise<string> {
1043 try {
1044 const port = await portOf($)
1045 if (port === undefined) return ''
1046 const id = await $.session.id()
1047 const asked = await Promise.race([
1048 $.http.fetch(`http://127.0.0.1:${port}/logbook/subagent`, {
1049 method: 'POST',
1050 headers: { 'content-type': 'application/json' },
1051 body: JSON.stringify({ session_id: id, prompt }),
1052 }),
1053 $.clock.sleep(LOGBOOK_WAIT_MS).then(() => undefined),
1054 ])
1055 if (asked === undefined || !asked.ok) return ''
1056 const text = (JSON.parse(asked.text) as { text?: unknown }).text
1057 return typeof text === 'string' ? text.trim() : ''
1058 } catch {
1059 return ''
1060 }
1061}
1062
1063async function ended($: Dollar, id: string, reason: string): Promise<void> {
1064 if (!known.has(id)) await begin($, id)
1065 say($, id, { kind: 'ended', reason })
1066 known.delete(id)
1067 await flush($)
1068}
1069
1070export const register: Register = on => {
1071 on('session.start', async ($, e, next) => {
1072 const started = await next(e)
1073 if (await $.env.get('ARMADA_DRONE')) return started
1074 $.clock.every(ASK_EVERY_MS, () => submitHeld($).catch(() => undefined))
1075 void $.session
1076 .id()
1077 .then(id => begin($, id, e.cwd))
1078 .catch(() => undefined)
1079 return started
1080 })
1081
1082 // `show_window` places a terminal session by the id it names, which the model cannot learn otherwise.
1083 on('prompt.context', async ($, e, next) => {
1084 const out = await next(e)
1085 if (await $.env.get('ARMADA_DRONE')) return out
1086 const id = await $.session.id()
1087 return { ...out, blocks: [...out.blocks, { name: 'armadaSession', text: idNote(id) }] }
1088 })
1089
1090 // Again at every start (startup, resume, clear, compact), so the id is never out of view.
1091 on('classic.SessionStart', async ($, e, next) => {
1092 const out = await next(e)
1093 if (await $.env.get('ARMADA_DRONE')) return out
1094 const id = await $.session.id()
1095 return { ...out, additionalContext: [...(out.additionalContext ?? []), idNote(id)] }
1096 })
1097
1098 on('prompt.submit', async ($, e, next) => {
1099 const out = await next(e)
1100 const one = known.get(await $.session.id())
1101 if (one !== undefined) one.turn = freshTurn()
1102 void titled($, e.text).catch(() => undefined)
1103 void turnBegan($, e.text).catch(() => undefined)
1104 // Whatever the origin: the notice can arrive inside a system-reminder, and only a task this load saw start is settled.
1105 const ended = backgroundEndOf(e.text)
1106 if (ended !== undefined) void backgroundEnded($, ended.target, ended.status, ended.exit, ended.output).catch(() => undefined)
1107 return out
1108 })
1109
1110 on('command.run', { command: 'rename' }, async ($, e, next) => {
1111 const out = await next(e)
1112 void renamed($, e.args).catch(() => undefined)
1113 return out
1114 })
1115
1116 // A page is shown in Bridge's window and lands on the ledger; `open` would go to the owner's browser.
1117 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
1118 const pages = pagesOpenedIn(e.command)
1119 if (pages.length > 0 && !(await $.env.get('ARMADA_DRONE'))) {
1120 await showPages($, pages)
1121 return { deny: SHOWN_INSTEAD }
1122 }
1123 const ran = await next(e)
1124 if (ran.deny === undefined) void used($, 'ran', e as Record<string, unknown>).catch(() => undefined)
1125 if (ran.deny === undefined && ran.isError !== true) {
1126 void afterBash($, e.command, ran.text ?? '').catch(() => undefined)
1127 void backgrounded($, 'Bash', e as Record<string, unknown>, ran.text ?? '').catch(() => undefined)
1128 }
1129 return ran
1130 })
1131
1132 // A whole read of a large file is turned away once, with its outline, so the agent reads a range.
1133 on('tool.call', { tool: 'Read' }, async ($, e, next) => {
1134 if (!wholeRead(e) || turnedAwayFrom.has(e.file_path)) return next(e)
1135 const file = await $.fs.stat(e.file_path).catch(() => undefined)
1136 if (file?.kind !== 'file' || file.size <= WHOLE_READ_MOST) return next(e)
1137 const text = await $.fs.read(e.file_path).catch(() => undefined)
1138 if (typeof text !== 'string') return next(e)
1139 turnedAwayFrom.add(e.file_path)
1140 const root = await $.session.root().catch(() => undefined)
1141 const graph = root !== undefined && (await $.fs.exists(`${root}/.gitnexus`).catch(() => false))
1142 return { deny: turnedAway(e.file_path, file.size, text, graph) }
1143 })
1144
1145 // A Monitor watch is a background task as a command run in the background is.
1146 on('tool.call', { tool: 'Monitor' }, async ($, e, next) => {
1147 const ran = await next(e)
1148 if (ran.deny === undefined && ran.isError !== true) {
1149 void backgrounded($, 'Monitor', e as Record<string, unknown>, ran.text ?? '').catch(() => undefined)
1150 }
1151 return ran
1152 })
1153
1154 // Stopped by the agent: the notice that follows says so too, and settles nothing twice.
1155 on('tool.call', { tool: 'TaskStop' }, async ($, e, next) => {
1156 const ran = await next(e)
1157 const target = (e as { task_id?: string; shell_id?: string }).task_id ?? (e as { shell_id?: string }).shell_id
1158 if (ran.deny === undefined && ran.isError !== true && target !== undefined) {
1159 void backgroundEnded($, target, 'killed').catch(() => undefined)
1160 }
1161 return ran
1162 })
1163
1164 // A question asked in the terminal is also put to Bridge, and the first answer wins; Fleet refusing it
1165 // (the owner is walking a page) stops it before the terminal's prompt opens. The terminal's
1166 // prompt opens beneath (`next`) while Fleet holds the question; returning before `next` does aborts
1167 // the prompt, so an answer from Bridge is the tool's own result and the terminal never keeps it.
1168 on('tool.call', { tool: 'AskUserQuestion' }, async ($, e, next) => {
1169 if (await $.env.get('ARMADA_DRONE')) return next(e)
1170 const id = await $.session.id()
1171 const put = await firstPut($, id, { input: { questions: e.questions } })
1172 if (put?.outcome === 'refused') return { deny: put.message }
1173 const asking = known.get(id)
1174 if (asking !== undefined) asking.turn.asked = true
1175 const over = { done: false }
1176 const terminal = next(e).then(ran => ({ ran }))
1177 const bridge = putToBridge($, id, { input: { questions: e.questions } }, over, put).then(asked =>
1178 asked?.outcome === 'answered' || asked?.outcome === 'refused'
1179 ? { asked }
1180 : new Promise<never>(() => undefined),
1181 )
1182 try {
1183 const first = await Promise.race([terminal, bridge])
1184 if ('asked' in first) {
1185 if (first.asked.outcome === 'refused') return { deny: first.asked.message }
1186 return { result: { questions: e.questions, answers: answersIn(first.asked.updated_input) } }
1187 }
1188 void settledInTerminal($, id, first.ran.deny === undefined && first.ran.isError !== true)
1189 return first.ran
1190 } catch (error) {
1191 void settledInTerminal($, id, false)
1192 throw error
1193 } finally {
1194 over.done = true
1195 }
1196 })
1197
1198 // The plan, from the tools the agent already calls to write it: nothing is asked of the model. The task
1199 // tools came in two generations, a whole list in `TodoWrite` and one task at a time in `TaskCreate` and `TaskUpdate`.
1200 // Only the session's own `TodoWrite` is heard, but a subagent's task calls share the session's list.hooks/facts.ts 983 lines1// What a session's own words and tool results say about what it holds. Pure, so
2// each reading is a test and not a session.
3
4import type { SessionContextBreakdown } from 'claude-code'
5
6import type { Fact, Task } from './fleet'
7
8const TITLE_MOST = 80
9const SAID_MOST = 1500
10const COMMAND_MOST = 300
11
12/**
13 * The version this mod reports to Fleet, so Bridge can mark a session whose mod is older than the
14 * repository's. **Bump it with `version` in `.claude-plugin/plugin.json`**: the mod cannot read that
15 * file while it runs, and a Fleet test (`terminal_session.rs`) holds the two equal.
16 */
17export const MOD_VERSION = '0.3.43'
18
19/** What fills the context window, trimmed for Fleet (`ContextBreakdown`, `crates/ipc/src/context_breakdown.rs`). */
20export type ContextBreakdown = {
21 categories: { name: string; tokens: number; kind: 'used' | 'free' | 'buffer' | 'deferred' }[]
22 memory_files: { path: string; tokens: number }[]
23 mcp_tools: { name: string; server: string; tokens: number }[]
24 total_tokens: number
25 max_tokens: number
26 autocompact_threshold?: number
27}
28
29const MOST_MCP_TOOLS = 10
30
31/**
32 * The breakdown as Fleet keeps it. **Names, paths and counts only**: the grid, the skill and agent
33 * listings and every other field are left behind, and the MCP tools are the ten that weigh most.
34 */
35export function breakdownOf(breakdown: SessionContextBreakdown): ContextBreakdown {
36 const trimmed: ContextBreakdown = {
37 categories: breakdown.categories.map(one => ({ name: one.name, tokens: one.tokens, kind: one.kind })),
38 memory_files: breakdown.memoryFiles.map(one => ({ path: one.path, tokens: one.tokens })),
39 mcp_tools: [...breakdown.mcpTools]
40 .sort((a, b) => b.tokens - a.tokens)
41 .slice(0, MOST_MCP_TOOLS)
42 .map(one => ({ name: one.name, server: one.serverName, tokens: one.tokens })),
43 total_tokens: breakdown.totalTokens,
44 max_tokens: breakdown.maxTokens,
45 }
46 if (breakdown.autoCompactThreshold !== undefined) trimmed.autocompact_threshold = breakdown.autoCompactThreshold
47 return trimmed
48}
49
50/** A plan window as the engine reports it (`SessionRateLimit`). */
51export type RateLimit = { kind: string; percentUsed: number; resetsAt?: string }
52
53/** A plan window as Fleet takes it: whole percent, and the reset as an ISO instant Fleet can read. */
54export type PlanWindow = { kind: string; percent_used: number; resets_at?: string }
55
56function isoOf(text: string | undefined): string | undefined {
57 if (text === undefined) return undefined
58 const at = new Date(text)
59 return Number.isNaN(at.getTime()) ? undefined : at.toISOString()
60}
61
62/** The windows in Fleet's spelling. Empty off a subscription, and a window with no usable reset keeps its percent. */
63export function planOf(limits: RateLimit[]): PlanWindow[] {
64 return limits.map(one => {
65 const resets = isoOf(one.resetsAt)
66 return { kind: one.kind, percent_used: Math.round(one.percentUsed), ...(resets === undefined ? {} : { resets_at: resets }) }
67 })
68}
69
70/** Near enough to full that a turn failing on the limit was this window's doing. */
71const NEARLY_FULL = 99
72
73/**
74 * When the limit a turn just hit opens again: the latest reset among the windows at or near full, so
75 * a weekly window spent beside a five-hour one is waited out. Nothing where no full window says when.
76 */
77export function spentUntil(limits: RateLimit[]): string | undefined {
78 const resets = limits
79 .filter(one => one.percentUsed >= NEARLY_FULL)
80 .map(one => isoOf(one.resetsAt))
81 .filter((one): one is string => one !== undefined)
82 .sort()
83 return resets.at(-1)
84}
85
86/** The `answers` map a question's answered input carries, keyed by question text. */
87export function answersIn(input: unknown): Record<string, string> {
88 const answers = (input as { answers?: unknown } | null)?.answers
89 if (typeof answers !== 'object' || answers === null) return {}
90 return Object.fromEntries(Object.entries(answers).filter(([, said]) => typeof said === 'string')) as Record<string, string>
91}
92
93/**
94 * The web pages a shell line opens in the owner's browser: `open`, `xdg-open` or
95 * `python -m webbrowser` with an `http(s)` address. Fleet reads hosted sessions' lines the same way
96 * (`pages_opened`, `crates/fleet/src/helm/deciding.rs`).
97 */
98export function pagesOpenedIn(command: string): string[] {
99 const pages: string[] = []
100 for (const segment of command.replace(/&&|\|\|/g, ';').split(/[;|\n]/)) {
101 const words = segment
102 .split(/\s+/)
103 .filter(word => word !== '')
104 .map(word => word.replace(/^['"]+|['"]+$/g, ''))
105 const first = words[0] ?? ''
106 const opens =
107 first === 'open' ||
108 first === 'xdg-open' ||
109 (first.startsWith('python') && words.some((word, i) => word === '-m' && words[i + 1] === 'webbrowser'))
110 if (opens) pages.push(...words.filter(word => /^https?:\/\//.test(word)))
111 }
112 return pages
113}
114
115// A harness wraps what it adds to a prompt in hyphenated tags. A command's and a reminder's
116// contents are the harness's words, so the whole block goes; any other wrapper, such as
117// `<agent-message from="…">`, only loses its tag and the words inside are the person's.
118const MACHINE_BLOCK = /<((?:local-)?command-[\w-]+|system-reminder)(?:\s[^>]*)?>[\s\S]*?(?:<\/\1>|$)/g
119const WRAPPER_TAG = /<\/?[a-z]+(?:-[\w]+)+(?:\s[^>]*)?>/gi
120
121/** What is left of a prompt once the harness's own markup is taken off. */
122export function withoutMarkup(prompt: string): string {
123 return prompt.replace(MACHINE_BLOCK, '').replace(WRAPPER_TAG, '')
124}
125
126/** The first line of real text in a prompt as a title, or nothing for a command or a blank. */
127export function titleOf(prompt: string): string | undefined {
128 const line = withoutMarkup(prompt)
129 .split('\n')
130 .map(one => one.trim())
131 .find(one => one !== '')
132 if (line === undefined || line.startsWith('/')) return undefined
133 const flat = line.replace(/\s+/g, ' ')
134 return flat.length > TITLE_MOST ? `${flat.slice(0, TITLE_MOST - 1)}…` : flat
135}
136
137/**
138 * The close of what a turn ended on, which Fleet reads for an ask and shows the first line of as the reply:
139 * the last 1,500 characters from the start of a line, as Fleet keeps them for a hosted Session (`tail` in
140 * `crates/fleet/src/session_host/standing.rs`, which this mirrors). Nothing for a turn that said nothing.
141 */
142export function saidOf(answer: string): string | undefined {
143 const said = answer.trim()
144 if (said === '') return undefined
145 const chars = Array.from(said)
146 if (chars.length <= SAID_MOST) return said
147 const kept = chars.slice(chars.length - SAID_MOST).join('')
148 const cut = kept.indexOf('\n')
149 if (cut >= 0) {
150 const rest = kept.slice(cut + 1)
151 if (rest.trim() !== '') return rest.trimStart()
152 }
153 return kept
154}
155
156/** The name a `/rename` gave, from a transcript: its last `custom-title` entry. */
157export function customTitleIn(transcript: string): string | undefined {
158 let found: string | undefined
159 for (const line of transcript.split('\n')) {
160 if (!line.includes('customTitle')) continue
161 try {
162 const entry = JSON.parse(line) as { type?: unknown; customTitle?: unknown }
163 if (entry.type === 'custom-title' && typeof entry.customTitle === 'string') {
164 found = entry.customTitle.trim() || found
165 }
166 } catch {
167 // A line cut short at the end of a file being written.
168 }
169 }
170 return found === undefined ? undefined : found.replace(/\s+/g, ' ')
171}
172
173/** Where Claude Code keeps a session's transcript, under the directory it ran in. */
174export function transcriptPath(home: string, cwd: string, id: string): string {
175 return `${home}/.claude/projects/${cwd.replace(/[^a-zA-Z0-9]/g, '-')}/${id}.jsonl`
176}
177
178/** Whether a Bash command may have moved the branch or the directory. */
179export function mayMoveBranch(command: string): boolean {
180 return /\bgit\b[^|;&]*\b(checkout|switch|branch|commit|merge|rebase|pull|worktree|reset|cherry-pick|clone)\b/.test(
181 command,
182 )
183}
184
185export type PullRequest = { number: string; url: string }
186
187/** Pull requests a result names by their address. */
188export function pullRequestsIn(text: string): PullRequest[] {
189 const found = new Map<string, PullRequest>()
190 for (const hit of text.matchAll(/https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/pull\/(\d+)/g)) {
191 found.set(hit[1], { number: hit[1], url: hit[0] })
192 }
193 return [...found.values()]
194}
195
196/** Issues a result names by their address, as `pullRequestsIn` reads pull requests. */
197export function issuesIn(text: string): PullRequest[] {
198 const found = new Map<string, PullRequest>()
199 for (const hit of text.matchAll(/https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/issues\/(\d+)/g)) {
200 found.set(hit[1], { number: hit[1], url: hit[0] })
201 }
202 return [...found.values()]
203}
204
205/** A Bash command that files an issue with `gh`, which prints the new issue's address. */
206export function ghIssueCreate(command: string): boolean {
207 return /\bgh\s+issue\s+create\b/.test(command)
208}
209
210export type GhAct = { act: 'create' | 'merge' | 'close'; number?: string }
211
212/** A `gh pr` command that makes, lands or closes a pull request. */
213export function ghAct(command: string): GhAct | undefined {
214 const hit = /\bgh\s+pr\s+(create|merge|close)\b([^|;&]*)/.exec(command)
215 if (hit === null) return undefined
216 // `--auto` asks the forge to merge later, or puts it in the merge queue: nothing has merged
217 // yet, and Fleet's pull reading settles it when it does (#2027 read as merged, 8 Oct 2026).
218 if (hit[1] === 'merge' && /(?:^|\s)--auto(?:\s|$)/.test(hit[2])) return undefined
219 const number = /(?:^|\s)#?(\d+)(?:\s|$)/.exec(hit[2])?.[1]
220 return { act: hit[1] as GhAct['act'], number }
221}
222
223/** Whom a delivery came from, as far as the delivery says: never a session id. */
224export function senderOf(origin: { kind: string; teammate?: string }): string {
225 return origin.teammate ?? origin.kind
226}
227
228export function micros(usd: number | undefined): number | undefined {
229 return usd === undefined ? undefined : Math.round(usd * 1_000_000)
230}
231
232export type Artifact = {
233 /** A published page, a file written outside the code, a picture looked at, or a Claude Docs document. */
234 form: 'page' | 'file' | 'image' | 'doc'
235 /** The address a page or doc opens at, or the file's path. */
236 target: string
237 title?: string
238}
239
240// Written, and not code: documents, pictures and prose, never configuration. A page's own source (`.html`) is left
241// out because the page appears once it is published, as a page.
242const DOCUMENT = /\.(md|mdx|txt|pdf|png|jpe?g|gif|webp|svg|csv|docx?|xlsx?|pptx?)$/i
243// Where a session keeps what it only needs on the way: its own settings and scratch space.
244const SCRATCH = /(^|\/)(node_modules|\.git|\.claude|\.armada|target|dist|build)\/|^\/(private\/)?(tmp|var\/folders)\//
245
246/** Whether a file a session wrote is something a person would want to open, and not code. */
247export function isDocument(path: string): boolean {
248 return DOCUMENT.test(path) && !SCRATCH.test(path)
249}
250
251// A picture a session looked at. Scratch is kept: a screenshot is usually read from `/tmp`.
252const PICTURE = /\.(png|jpe?g|gif|webp)$/i
253
254const CLAUDE_ADDRESS = /https:\/\/claude\.ai\/[^\s)"'<>\]]*artifact[^\s)"'<>\]]*/
255const DOCS = /^mcp__claude_ai_Claude_Docs__(create|batch|update)$/
256
257const nameOf = (path: string) => path.slice(path.lastIndexOf('/') + 1).replace(/\.[^.]+$/, '')
258
259/**
260 * What a tool call made, or looked at, that a person would open. **A code edit is never one**: only a page
261 * published, a new document written, and a Claude Docs document created or edited.
262 * `created` is whether a Write made a file that was not there.
263 */
264export function artifactOf(
265 tool: string,
266 input: Record<string, unknown>,
267 text: string,
268 created: boolean,
269): Artifact | undefined {
270 if (tool === 'Artifact') {
271 if (input.asset === true || (input.action !== undefined && input.action !== 'publish')) return undefined
272 const target = typeof input.url === 'string' ? input.url : CLAUDE_ADDRESS.exec(text)?.[0]
273 if (target === undefined) return undefined
274 const title =
275 typeof input.title === 'string' ? input.title : typeof input.file_path === 'string' ? nameOf(input.file_path) : undefined
276 return { form: 'page', target, title }
277 }
278 if (tool === 'Write') {
279 const path = input.file_path
280 if (!created || typeof path !== 'string' || !isDocument(path)) return undefined
281 return { form: 'file', target: path, title: path.slice(path.lastIndexOf('/') + 1) }
282 }
283 if (tool === 'Read') {
284 const path = input.file_path
285 if (typeof path !== 'string' || !PICTURE.test(path)) return undefined
286 return { form: 'image', target: path, title: path.slice(path.lastIndexOf('/') + 1) }
287 }
288 if (DOCS.test(tool)) {
289 const container = input.container as { id?: unknown; create?: { name?: unknown } } | undefined
290 const id = typeof container?.id === 'string' ? container.id : undefined
291 const target = CLAUDE_ADDRESS.exec(text)?.[0] ?? (id === undefined ? undefined : `https://claude.ai/artifact/${id}`)
292 if (target === undefined) return undefined
293 const name = container?.create?.name
294 return { form: 'doc', target, title: typeof name === 'string' ? name : undefined }
295 }
296 return undefined
297}
298
299/** A task the agent started in the background: a shell command run with `run_in_background`, or a Monitor watch. */
300export type Background = { target: string; detail: Record<string, string> }
301
302const SHELL_TASK = /running in background with ID:\s*([\w-]+)/
303// **No Monitor result has been recorded.** This pattern is tolerant on purpose ("ID: x" or "task x", an id of five or
304// more characters) and wants a real sample to tighten it. The shell's is verbatim (`background.fixture.ts`).
305const MONITOR_TASK = /(?:\bID:?|\btask)\s+([A-Za-z0-9][\w-]{4,})/
306// The sentence ends the path with a full stop, which is not part of it.
307const OUTPUT_FILE = /Output is being written to:\s*(\S+?)\.?(?:\s|$)/
308
309/**
310 * A background task, from the call that started it and the id its result gave back. **No id in the result, no
311 * task**: a call that was refused or answered in some other words is not reported. `task` is the call's own
312 * description; `output` is the file the engine writes the task's output to, when the result names it.
313 */
314export function backgroundOf(tool: string, input: Record<string, unknown>, text: string): Background | undefined {
315 const said = (value: unknown) => (typeof value === 'string' ? (value.trim().split('\n')[0] ?? '').slice(0, COMMAND_MOST) : '')
316 const output = OUTPUT_FILE.exec(text)?.[1]
317 const where = output === undefined ? {} : { output }
318 if (tool === 'Bash') {
319 const target = SHELL_TASK.exec(text)?.[1]
320 if (input.run_in_background !== true || target === undefined) return undefined
321 const command = said(input.command)
322 return { target, detail: { form: 'command', task: said(input.description) || command, command, ...where } }
323 }
324 if (tool === 'Monitor') {
325 const target = MONITOR_TASK.exec(text)?.[1]
326 if (target === undefined) return undefined
327 const watched = said(input.command) || said((input.ws as { url?: unknown } | undefined)?.url)
328 return { target, detail: { form: 'monitor', task: said(input.description) || watched, command: watched, ...where } }
329 }
330 return undefined
331}
332
333/** How a background task ended, off the notification the engine queues for the session: the task's id, its word, and the exit code when the summary gives one. */
334export type BackgroundEnd = { target: string; status: string; exit?: string; output?: string }
335
336export function backgroundEndOf(text: string): BackgroundEnd | undefined {
337 const field = (name: string) => new RegExp(`<${name}>\\s*([\\s\\S]*?)\\s*</${name}>`).exec(text)?.[1]
338 const target = field('task-id')
339 const status = field('status')
340 if (target === undefined || status === undefined) return undefined
341 const exit = /exit code\s+(-?\d+)/i.exec(field('summary') ?? '')?.[1]
342 // The notice names the file the engine wrote the output to, which is better than any parsing of the launch.
343 const output = field('output-file')
344 return { target, status, ...(exit === undefined ? {} : { exit }), ...(output === undefined ? {} : { output }) }
345}
346
347/**
348 * The file a write tool changed, named from the session's directory, for Fleet's check of who else
349 * writes it. **A path and nothing else**: never the content, and nothing outside the directory.
350 * `cwd` is where the session stands; an absolute path under it is made relative, and a path that
351 * climbs out of it, or lies elsewhere, is not told.
352 */
353export function touchedOf(cwd: string, input: Record<string, unknown>): string | undefined {
354 const named = input.file_path ?? input.notebook_path
355 if (typeof named !== 'string' || named === '') return undefined
356 const root = cwd.replace(/\/+$/, '')
357 const relative = named.startsWith('/') ? (named.startsWith(`${root}/`) ? named.slice(root.length + 1) : undefined) : named
358 if (relative === undefined || relative === '' || relative.split('/').includes('..')) return undefined
359 return relative.replace(/^\.\//, '')
360}
361
362/**
363 * What a tool call did that Fleet's timeline counts: a file it wrote or read, as a path from the
364 * session's directory, or a shell command, as its first line. **Never content.** Fleet cuts a command
365 * further and hides what looks like a secret in it (`crates/fleet/src/timeline/tools.rs`).
366 */
367export function usedFact(
368 act: 'touched' | 'read' | 'ran',
369 cwd: string,
370 input: Record<string, unknown>,
371 by?: { how?: 'write' | 'edit'; agent?: string },
372): Fact | undefined {
373 if (act === 'ran') {
374 const line = typeof input.command === 'string' ? (input.command.trim().split('\n')[0] ?? '') : ''
375 return line === '' ? undefined : { kind: 'ran', command: line.slice(0, COMMAND_MOST) }
376 }
377 const path = touchedOf(cwd, input)
378 if (path === undefined) return undefined
379 if (act === 'read') return { kind: 'read', path }
380 // Which subagent wrote it, by the id its `subagent` attachment carries, and whether it made the file.
381 return {
382 kind: 'touched',
383 paths: [path],
384 ...(by?.how === undefined ? {} : { act: by.how }),
385 ...(by?.agent === undefined ? {} : { by: by.agent }),
386 }
387}
388
389/**
390 * What a permission prompt asks about, as the call names it: a shell command's first line, a file's
391 * path, an address, or nothing for a tool with none of these. One line and cut, never content. The
392 * same reading of the prompt's input and of the tool call's, so the call settles the prompt it raised.
393 */
394export function promptDetail(input: Record<string, unknown>): string {
395 const named = [input.command, input.file_path, input.notebook_path, input.path, input.url].find(
396 one => typeof one === 'string' && one.trim() !== '',
397 )
398 if (typeof named !== 'string') return ''
399 return (named.trim().split('\n')[0] ?? '').slice(0, COMMAND_MOST)
400}
401
402const MODELS = ['haiku', 'sonnet', 'opus']
403
404/** A model by the short name the person picks it by, and by its own id where it has no short one. */
405export function modelName(id: string): string {
406 return MODELS.find(one => id.includes(one)) ?? id
407}
408
409export type Mode = 'ask' | 'auto' | 'accept_edits' | 'plan'
410
411/** The terminal's permission mode in Armada's words, or nothing for one Armada has no word for. */
412export function modeOf(mode: string | undefined): Mode | undefined {
413 switch (mode) {
414 case 'default':
415 return 'ask'
416 case 'auto':
417 return 'auto'
418 case 'acceptEdits':
419 return 'accept_edits'
420 case 'plan':
421 return 'plan'
422 default:
423 return undefined
424 }
425}
426
427/** An effort level, whether the hook input carries the word or an object around it. */
428export function effortOf(effort: unknown): string | undefined {
429 if (typeof effort === 'string') return effort
430 const level = (effort as { level?: unknown } | null | undefined)?.level
431 return typeof level === 'string' ? level : undefined
432}
433
434const TASK_MOST = 200
435
436function textOf(value: unknown): string | undefined {
437 if (typeof value !== 'string') return undefined
438 const text = value.replace(/\s+/g, ' ').trim()
439 return text === '' ? undefined : text.slice(0, TASK_MOST)
440}
441
442function statusOf(value: unknown): Task['status'] | undefined {
443 return value === 'pending' || value === 'in_progress' || value === 'completed' ? value : undefined
444}
445
446/**
447 * The list a `TodoWrite` wrote, whole: its items in order, each with its place as the id. An input
448 * with no list is nothing to tell, and an empty one is a list cleared.
449 */
450export function todoTasks(input: Record<string, unknown>): Task[] | undefined {
451 if (!Array.isArray(input.todos)) return undefined
452 const tasks: Task[] = []
453 for (const one of input.todos as Record<string, unknown>[]) {
454 const text = textOf(one?.content ?? one?.subject)
455 if (text === undefined) continue
456 tasks.push({ id: String(tasks.length + 1), text, status: statusOf(one.status) ?? 'pending' })
457 }
458 return tasks
459}
460
461/** The id the task tool gave a task it made, from its result: `{ task: { id } }`, or `Task #3 created`. */
462function madeId(result: unknown, text: string): string | undefined {
463 const task = (result as { task?: { id?: unknown } } | null | undefined)?.task
464 if (typeof task?.id === 'string' || typeof task?.id === 'number') return String(task.id)
465 return /\bTask #?(\w+)/.exec(text)?.[1]
466}
467
468/** The list after a `TaskCreate`, or nothing where the call named no task. `by` is the subagent that made it. */
469export function madeTask(
470 list: Task[],
471 input: Record<string, unknown>,
472 result: unknown,
473 text: string,
474 by?: string,
475): Task[] | undefined {
476 const named = textOf(input.subject ?? input.content ?? input.title)
477 if (named === undefined) return undefined
478 const id = madeId(result, text) ?? String(list.length + 1)
479 return [...list.filter(one => one.id !== id), { id, text: named, status: 'pending', ...(by === undefined ? {} : { by }) }]
480}
481
482/**
483 * Where Claude Code keeps a task list: `~/.claude/tasks/<list>/<n>.json`, one file a task. The list is the
484 * session's id unless `CLAUDE_CODE_TASK_LIST_ID` names it, and the harness cleans the name the same way.
485 */
486export function taskListDir(home: string, list: string): string {
487 return `${home}/.claude/tasks/${list.replace(/[^a-zA-Z0-9_-]/g, '-')}`
488}
489
490/**
491 * The harness's own list, from its task files. It is what the agent's tools left, whichever process made
492 * them, so a process that began after the list was written (a resumed session) starts from it. A file
493 * that is not a task, or not whole yet, is left out. In order of id.
494 */
495export function storedTasks(files: string[]): Task[] {
496 const tasks: Task[] = []
497 for (const file of files) {
498 let one: Record<string, unknown>
499 try {
500 one = JSON.parse(file) as Record<string, unknown>
501 } catch {
502 continue
503 }
504 const id = typeof one?.id === 'string' || typeof one?.id === 'number' ? String(one.id) : undefined
505 const text = textOf(one.subject)
506 if (id === undefined || text === undefined) continue
507 tasks.push({ id, text, status: statusOf(one.status) ?? 'pending' })
508 }
509 return tasks.sort((a, b) => Number(a.id) - Number(b.id) || a.id.localeCompare(b.id))
510}
511
512/**
513 * The list after a `TaskUpdate`. A task that is in neither the list nor the harness's store is not
514 * invented: nothing to tell.
515 */
516export function updatedTask(list: Task[], input: Record<string, unknown>): Task[] | undefined {
517 const id = input.taskId ?? input.task_id ?? input.id
518 const key = typeof id === 'string' || typeof id === 'number' ? String(id) : undefined
519 const was = list.find(one => one.id === key)
520 if (key === undefined || was === undefined) return undefined
521 if (input.status === 'deleted') return list.filter(one => one.id !== key)
522 // Whoever updates it, the task stays its maker's.
523 const next: Task = {
524 ...was,
525 text: textOf(input.subject ?? input.content ?? input.title) ?? was.text,
526 status: statusOf(input.status) ?? was.status,
527 }
528 if (next.text === was.text && next.status === was.status) return undefined
529 return list.map(one => (one.id === key ? next : one))
530}
531
532/**
533 * A successful `git commit`, read from its output (`[branch 1a2b3c4] subject`) and not from the command alone: a
534 * commit with nothing staged prints no such line. `branch` is absent on a detached head.
535 */
536export function commitIn(command: string, output: string): { branch?: string } | undefined {
537 if (!/\bgit\b[^|;&\n]*\bcommit\b/.test(command)) return undefined
538 const made = /^\[(\S+)(?: [^\]]*)? [0-9a-f]{7,40}\]/m.exec(output)
539 if (made === null) return undefined
540 return made[1] === 'detached' ? {} : { branch: made[1] }
541}
542
543/**
544 * The branch a successful `git push` updated, from the ref line it printed: `abc..def main -> main`,
545 * `* [new branch] topic -> topic`, a forced `+ abc...def`. A push with nothing to send, one that was
546 * rejected and a `--dry-run` print no such line or are not one, and tell nothing.
547 */
548export function pushIn(command: string, output: string): { branch?: string } | undefined {
549 if (!/\bgit\b[^|;&\n]*\bpush\b/.test(command) || /--dry-run|(?:^|\s)-n(?:\s|$)/.test(command)) return undefined
550 const sent = /^\s*(?:[0-9a-f]{7,40}\.\.\.?[0-9a-f]{7,40}|\*\s+\[new (?:branch|tag)\]|\+\s+[0-9a-f]{7,40}\.\.\.[0-9a-f]{7,40})\s+\S+\s+->\s+(\S+)/m.exec(output)
551 return sent === null ? undefined : { branch: sent[1] }
552}
553
554/** One item of a session's `waiting_for` list, as the agent stated it (`WaitingInput`, `crates/ipc/src/sessions.rs`). */
555export type WaitingItem = { id: string; text: string; act?: unknown; options?: unknown; steps?: unknown }
556
557const NEED_MOST = 200
558const NEEDS_MOST = 10
559const FENCE = /^\s*(```|~~~)/
560const HEADING = /^\s{0,3}#{1,6}\s+(.*?)\s*#*\s*$/
561const BOLD_LINE = /^\s*\*\*([^*]+?)\*\*:?\s*$/
562const DIVIDER = /^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$/
563const LIST_ITEM = /^\s*(?:[-*+]|\d+[.)])\s+(.*)$/
564const OWNER_HEAD = /^(owner|owned by)$/
565// Read as an owner column only under an Actions heading, where the table is the owner's list of acts.
566const WHO_HEAD = /^(who|assignee|assigned to)$/
567const STATUS_HEAD = /^(status|state)$/
568const ACT_HEAD = /^(action|what|item|task|step|next step|to ?do|ask|need)s?$/
569const INDEX_HEAD = /^(#|no\.?|n)?$/
570// What owns a row that asks nothing of a person. `me`, `we` and `us` are the agent writing; a
571// kebab-case owner is a subagent type (`rust-engineer`).
572const NOT_A_PERSON = /\b(agent|agents|subagents?|claude|assistant|ai|bot|ci|fleet|drone|judge|helm|armada|bridge|github|automation|system|explore|plan|reviewer|engineer|me|we|us)\b|\w-\w|^(-|—|–|n\/a|none|tbd)?$/
573const DONE = /^(✅|✔|✓|☑)|\b(done|completed?|merged|closed|resolved|shipped|landed|finished)\b/
574const NOT_DONE = /\b(not|pending|blocked|waiting|open|todo|to do)\b|❌|⏳/
575const NO_QUESTIONS = /^(none|nothing|no (open )?questions?)\b/
576// The marker is upper case, or bold: a lower-case `question:` is prose.
577const QUESTION_LINE = /^\s*(?:[-*+]\s+)?QUESTION:\s*(.+)$/
578const BOLD_QUESTION = /^\s*(?:[-*+]\s+)?\*\*question:\*\*\s*(.+)$/i
579
580function plain(text: string): string {
581 return text.replace(/[*_`~]/g, '').replace(/\[([^\]]*)\]\([^)]*\)/g, '$1').replace(/\s+/g, ' ').trim()
582}
583
584function needLine(text: string): string {
585 const flat = plain(text)
586 return flat.length > NEED_MOST ? `${flat.slice(0, NEED_MOST - 1)}…` : flat
587}
588
589function cellsOf(row: string): string[] {
590 const inner = row.trim().replace(/^\|/, '').replace(/\|$/, '')
591 return inner.split(/(?<!\\)\|/).map(cell => cell.replace(/\\\|/g, '|').trim())
592}
593
594function isPerson(owner: string): boolean {
595 return plain(owner)
596 .toLowerCase()
597 .split(/\s*(?:\/|,|&|\+|\band\b)\s*/)
598 .some(part => part !== '' && !NOT_A_PERSON.test(part))
599}
600
601function isDone(status: string): boolean {
602 const said = plain(status).toLowerCase()
603 return DONE.test(said) && !NOT_DONE.test(said)
604}
605
606/** The rows of one table a person owns and has not done, each as the act it names. */
607function tableNeeds(rows: string[], underActions: boolean): string[] {
608 const head = cellsOf(rows[0] ?? '').map(cell => plain(cell).toLowerCase())
609 const owner = head.findIndex(cell => OWNER_HEAD.test(cell) || (underActions && WHO_HEAD.test(cell)))
610 if (owner < 0) return []
611 const status = head.findIndex(cell => STATUS_HEAD.test(cell))
612 const named = head.findIndex(cell => ACT_HEAD.test(cell))
613 const found: string[] = []
614 for (const row of rows.slice(2)) {
615 const cells = cellsOf(row)
616 if (cells.every(cell => cell === '') || /^\s*~~/.test(cells.join(''))) continue
617 if (!isPerson(cells[owner] ?? '')) continue
618 if (status >= 0 && isDone(cells[status] ?? '')) continue
619 const act =
620 named >= 0
621 ? cells[named]
622 : cells.find((cell, at) => at !== owner && at !== status && !INDEX_HEAD.test(head[at] ?? '') && plain(cell) !== '')
623 if (act !== undefined && plain(act) !== '') found.push(needLine(act))
624 }
625 return found
626}
627
628/**
629 * What a reply says the person owes, one line each: a row a person owns in a table with an Owner
630 * column (an Actions table may name it Who), that is not marked done; an item under a Questions
631 * heading; a `QUESTION:` line. **Conservative**, as a line found sends the session back for a turn:
632 * a fenced block is never read, and a table with no owner column names nobody.
633 */
634export function needsSaidIn(answer: string): string[] {
635 const lines = answer.split('\n')
636 const found: string[] = []
637 let fenced = false
638 let section = ''
639 for (let at = 0; at < lines.length; at += 1) {
640 const line = lines[at] ?? ''
641 if (FENCE.test(line)) {
642 fenced = !fenced
643 continue
644 }
645 if (fenced) continue
646 const heading = HEADING.exec(line) ?? BOLD_LINE.exec(line)
647 if (heading !== null) {
648 section = plain(heading[1] ?? '').replace(/:$/, '').toLowerCase()
649 continue
650 }
651 const asked = QUESTION_LINE.exec(line) ?? BOLD_QUESTION.exec(line)
652 if (asked !== null) {
653 found.push(needLine(asked[1] ?? ''))
654 continue
655 }
656 if (line.trim().startsWith('|') && DIVIDER.test(lines[at + 1] ?? '')) {
657 const rows: string[] = []
658 while ((lines[at] ?? '').trim().startsWith('|')) rows.push(lines[at++] ?? '')
659 at -= 1
660 found.push(...tableNeeds(rows, /\bactions?\b/.test(section)))
661 continue
662 }
663 if (/^(open )?questions?\b/.test(section)) {
664 const item = LIST_ITEM.exec(line)
665 const text = item?.[1] ?? (line.trim().endsWith('?') ? line : undefined)
666 if (text !== undefined && !NO_QUESTIONS.test(plain(text).toLowerCase())) found.push(needLine(text))
667 }
668 }
669 return [...new Set(found)].slice(0, NEEDS_MOST)
670}
671
672/** The list a `waiting_for` call set, from the tool's input (`{ body: { session_id, waiting_for } }`). */
673export function waitingItemsOf(input: Record<string, unknown>): WaitingItem[] | undefined {
674 let body: unknown = input.body ?? input
675 if (typeof body === 'string') {
676 try {
677 body = JSON.parse(body)
678 } catch {
679 return undefined
680 }
681 }
682 const list = (body as { waiting_for?: unknown; items?: unknown } | null)?.waiting_for ?? (body as { items?: unknown } | null)?.items
683 if (!Array.isArray(list)) return undefined
684 return list.filter(
685 (item): item is WaitingItem => typeof item?.id === 'string' && typeof item?.text === 'string',
686 )
687}
688
689function keyWords(text: string): Set<string> {
690 return new Set(
691 plain(text)
692 .toLowerCase()
693 .split(/[^a-z0-9#]+/)
694 .filter(word => word.length >= 4 || /\d/.test(word)),
695 )
696}
697
698/**
699 * Whether the list holds each line: an item shares two of its words, or all where it has fewer. Loose
700 * on purpose, as an item is the line said shorter and a miss costs the session a turn.
701 */
702export function isCovered(needs: string[], items: WaitingItem[]): boolean {
703 const held = items.map(item => keyWords(item.text))
704 return needs.every(need => {
705 const words = [...keyWords(need)]
706 const enough = Math.min(2, words.length)
707 return enough === 0 || held.some(item => words.filter(word => item.has(word)).length >= enough)
708 })
709}
710
711/** What sends a session back to put what its reply named in `waiting_for`. Read by the agent. */
712export function sentBackReason(needs: string[], sessionId: string): string {
713 return [
714 'Your reply names what the owner owes, and the armada waiting_for list does not hold it:',
715 ...needs.map(need => `- ${need}`),
716 `Put each in waiting_for with its own id, one short line and an act, passing session_id ${sessionId}, then end the turn. Do not repeat them as a table.`,
717 ].join('\n')
718}
719
720const FROM_REPLY = 'From the reply: '
721
722/** The list with what the reply named and the agent left out, each marked as read from the reply. */
723export function withReplyNeeds(items: WaitingItem[], needs: string[]): WaitingItem[] {
724 const missing = needs.filter(need => !isCovered([need], items))
725 return [...items, ...missing.map((need, at) => ({ id: `reply:${at + 1}`, text: `${FROM_REPLY}${need}` }))]
726}
727
728/**
729 * The agent's own items in the list Fleet holds, from `GET /sessions/one` (`SessionThread`). Items Fleet
730 * raised itself (a walk, a question card, a permission) are left out: Fleet keeps those apart and would
731 * read them posted back as the agent's. Nothing where the answer is not a session.
732 */
733export function agentItemsIn(thread: string): WaitingItem[] | undefined {
734 let read: unknown
735 try {
736 read = JSON.parse(thread)
737 } catch {
738 return undefined
739 }
740 const list = (read as { session?: { waiting_for?: unknown } } | null)?.session?.waiting_for
741 if (!Array.isArray(list)) return undefined
742 return list
743 .filter(item => item?.source === 'agent' && typeof item.id === 'string' && typeof item.text === 'string')
744 .map(({ id, text, act, options, steps }) => ({
745 id,
746 text,
747 ...(act === undefined ? {} : { act }),
748 ...(options === undefined ? {} : { options }),
749 ...(steps === undefined ? {} : { steps }),
750 }))
751}
752
753// The Loadout: what a session's agent knows, was told and used, each with where it came from.
754// `crates/ipc/src/sessions.rs`. **Names, sources and counts only**, never a body or a text.
755
756/** Where an item came from. `kit` is the person's harness home, `~/.claude`; `managed` an organisation's settings. */
757export type LoadoutSource = 'kit' | 'armada' | 'repository' | 'plugin' | 'mcp' | 'built_in' | 'managed'
758
759export type LoadoutKind = 'skill' | 'subagent' | 'mcp_server' | 'tool' | 'memory_file' | 'output_style' | 'rules' | 'injection'
760
761export type LoadoutItem = {
762 kind: LoadoutKind
763 name: string
764 source: LoadoutSource
765 from?: string
766 state?: 'connected' | 'failed' | 'pending' | 'deferred' | 'loaded'
767 tokens?: number
768}
769
770export type LoadoutUse = {
771 turn_started_at: string
772 kind: 'skill' | 'tool' | 'subagent'
773 name: string
774 source: LoadoutSource
775 from?: string
776 model?: string
777 by?: string
778}
779
780type Origin = { source: LoadoutSource; from?: string }
781
782export type ServerState = 'connected' | 'failed' | 'pending'
783
784/** This mod's own plugin name, so what it ships reads as Armada's and not as any plugin's. */
785const ARMADA_PLUGIN = 'armada'
786/** The harness's own output styles; `default` is no style at all and is not an item. */
787const BUILT_IN_STYLES = ['Explanatory', 'Learning']
788/** The name Armada's own rules go by, as Kit lists them (`crates/fleet/src/kit.rs`). */
789export const ARMADA_RULES = 'Armada session rules'
790/** The block `prompt.context` adds with the session id (`idNote`). */
791export const ARMADA_INJECTION = 'armadaSession'
792
793function pluginOrigin(plugin: string | undefined): Origin | undefined {
794 if (plugin === undefined || plugin === '') return undefined
795 return plugin === ARMADA_PLUGIN ? { source: 'armada' } : { source: 'plugin', from: plugin }
796}
797
798/** A plugin's skill, agent or style is spelled `<plugin>:<name>`. */
799function prefixOf(name: string): string | undefined {
800 const at = name.indexOf(':')
801 return at > 0 ? name.slice(0, at) : undefined
802}
803
804/** A skill's source by the engine's word for it (`SkillSource`); nothing for one Armada has no word for. */
805export function skillOrigin(source: string, name: string, plugin?: string): Origin | undefined {
806 if (source === 'userSettings' || source === 'syncedSkills') return { source: 'kit' }
807 if (source === 'projectSettings') return { source: 'repository' }
808 if (source === 'policySettings') return { source: 'managed' }
809 if (source === 'plugin') return pluginOrigin(plugin ?? prefixOf(name))
810 if (source === 'built-in' || source === 'bundled') return { source: 'built_in' }
811 if (source === 'mcp') {
812 const server = prefixOf(name)
813 return server === undefined ? undefined : { source: 'mcp', from: server }
814 }
815 return undefined
816}
817
818/** A subagent's source by the engine's word for where it was defined (`ContextAgent.source`). */
819export function agentOrigin(source: string, type: string): Origin | undefined {
820 if (source === 'userSettings') return { source: 'kit' }
821 if (source === 'projectSettings' || source === 'localSettings') return { source: 'repository' }
822 if (source === 'policySettings' || source === 'flagSettings') return { source: 'managed' }
823 if (source === 'plugin') return pluginOrigin(prefixOf(type))
824 if (source === 'built-in') return { source: 'built_in' }
825 return undefined
826}
827
828/**
829 * A memory file's source and the name it goes by: under `~/.claude` the person's, under the session's
830 * root the repository's, relative to it. Elsewhere the engine's label decides.
831 */
832export function memoryItem(path: string, type: string, home: string, root: string): { name: string; source: LoadoutSource } | undefined {
833 const kit = `${home.replace(/\/$/, '')}/.claude/`
834 const repository = `${root.replace(/\/$/, '')}/`
835 if (path.startsWith(kit)) return { name: `~/.claude/${path.slice(kit.length)}`, source: 'kit' }
836 if (path.startsWith(repository)) return { name: path.slice(repository.length), source: 'repository' }
837 if (type === 'Project' || type === 'Local') return { name: path, source: 'repository' }
838 if (type === 'User' || type === 'AutoMem') return { name: path, source: 'kit' }
839 if (type === 'Managed') return { name: path, source: 'managed' }
840 return undefined
841}
842
843/**
844 * An MCP server's name and source. A plugin's server is listed as `plugin:<plugin>:<server>` and is
845 * that plugin's; any other is its own.
846 */
847export function serverItem(listed: string): { name: string; source: LoadoutSource; from: string } {
848 const parts = /^plugin:([^:]+):(.+)$/.exec(listed)
849 if (parts === null) return { name: listed, source: 'mcp', from: listed }
850 const [, plugin = '', name = ''] = parts
851 return { name, source: plugin === ARMADA_PLUGIN ? 'armada' : 'plugin', from: plugin }
852}
853
854/** The server an `mcp__<server>__<tool>` name names, as the tool name spells it. */
855export function serverOfTool(tool: string): string | undefined {
856 const parts = /^mcp__(.+?)__.+$/.exec(tool)
857 return parts?.[1]
858}
859
860/** A tool's source: an MCP tool's server as `/mcp` lists it where the breakdown says, else the harness's. */
861export function toolOrigin(tool: string, mcpTools: readonly { name: string; serverName: string }[] = []): Origin {
862 const server = mcpTools.find(one => one.name === tool)?.serverName ?? serverOfTool(tool)
863 return server === undefined ? { source: 'built_in' } : { source: 'mcp', from: server }
864}
865
866/**
867 * The output style's source. A plugin's is `<plugin>:<name>`; Armada's own is `Armada`; a style
868 * found in the repository's `.claude/output-styles` is the repository's, and any other the person's.
869 */
870export function styleOrigin(name: string, inRepository: boolean): Origin {
871 if (name === 'Armada') return { source: 'armada' }
872 const plugin = pluginOrigin(prefixOf(name))
873 if (plugin !== undefined) return plugin
874 if (BUILT_IN_STYLES.includes(name)) return { source: 'built_in' }
875 return { source: inRepository ? 'repository' : 'kit' }
876}
877
878/** What the mod holds of a session to make its Loadout from. */
879export type Equipment = {
880 breakdown?: SessionContextBreakdown
881 home: string
882 root: string
883 /** The output style in force and its source; absent for the default. */
884 style?: { name: string } & Origin
885 /** Whether Fleet hosts the session, so Armada's session rules ride on its prompt (`ARMADA_SESSION`). */
886 rules: boolean
887 /** What `ToolSearch` and `WaitForMcpServers` last said of each server. */
888 servers: Record<string, ServerState>
889 /** The tools a `ToolSearch` loaded. */
890 loaded: string[]
891}
892
893/**
894 * The whole Loadout, in a fixed order so two readings that hold the same compare equal. An item the
895 * engine gives no source Armada has a word for is left out rather than guessed.
896 */
897export function loadoutOf(equipment: Equipment): LoadoutItem[] {
898 const { breakdown, home, root } = equipment
899 const items: LoadoutItem[] = []
900 const tokens = (count: number) => (Number.isFinite(count) && count > 0 ? { tokens: count } : {})
901 for (const skill of breakdown?.skills?.skillFrontmatter ?? []) {
902 const origin = skillOrigin(skill.source, skill.name, skill.pluginName)
903 if (origin !== undefined) items.push({ kind: 'skill', name: skill.name, ...origin, ...tokens(skill.tokens) })
904 }
905 for (const agent of breakdown?.agents ?? []) {
906 const origin = agentOrigin(agent.source, agent.agentType)
907 if (origin !== undefined) items.push({ kind: 'subagent', name: agent.agentType, ...origin, ...tokens(agent.tokens) })
908 }
909 const mcpTools = breakdown?.mcpTools ?? []
910 const servers = new Map<string, ServerState>(Object.entries(equipment.servers))
911 // A server whose tools the window lists is connected, whatever was said of it before.
912 for (const tool of mcpTools) servers.set(tool.serverName, 'connected')
913 for (const [name, state] of [...servers].sort(([a], [b]) => a.localeCompare(b))) {
914 items.push({ kind: 'mcp_server', ...serverItem(name), state })
915 }
916 const loaded = new Set(equipment.loaded)
917 for (const tool of mcpTools) {
918 const state = tool.isLoaded || loaded.has(tool.name) ? 'loaded' : 'deferred'
919 items.push({ kind: 'tool', name: tool.name, source: 'mcp', from: tool.serverName, state, ...tokens(tool.tokens) })
920 }
921 for (const name of [...loaded].sort()) {
922 if (mcpTools.some(tool => tool.name === name)) continue
923 items.push({ kind: 'tool', name, ...toolOrigin(name), state: 'loaded' })
924 }
925 for (const file of breakdown?.memoryFiles ?? []) {
926 const named = memoryItem(file.path, file.type, home, root)
927 if (named !== undefined) items.push({ kind: 'memory_file', ...named, ...tokens(file.tokens) })
928 }
929 if (equipment.style !== undefined) {
930 const { name, ...origin } = equipment.style
931 items.push({ kind: 'output_style', name, ...origin })
932 }
933 if (equipment.rules) items.push({ kind: 'rules', name: ARMADA_RULES, source: 'armada' })
934 items.push({ kind: 'injection', name: ARMADA_INJECTION, source: 'armada' })
935 return items
936}
937
938/** What a `ToolSearch` result says: the tools it loaded, and the servers not yet or never connected. */
939export function searchedOf(result: unknown): { matches: string[]; servers: Record<string, ServerState> } {
940 const read = (result ?? {}) as { matches?: unknown; pending_mcp_servers?: unknown; failed_mcp_servers?: unknown }
941 const names = (list: unknown) => (Array.isArray(list) ? list.filter((one): one is string => typeof one === 'string') : [])
942 const servers: Record<string, ServerState> = {}
943 for (const name of names(read.pending_mcp_servers)) servers[name] = 'pending'
944 if (Array.isArray(read.failed_mcp_servers)) {
945 for (const one of read.failed_mcp_servers) if (typeof one?.name === 'string') servers[one.name] = 'failed'
946 }
947 return { matches: names(read.matches), servers }
948}
949
950/** What a `WaitForMcpServers` result says of each server. One that needs signing in to gives no tools, so it is `failed`. */
951export function waitedOf(result: unknown): Record<string, ServerState> {
952 const read = (result ?? {}) as Record<string, unknown>
953 const servers: Record<string, ServerState> = {}
954 const mark = (key: string, state: ServerState) => {
955 const list = read[key]
956 if (Array.isArray(list)) for (const name of list) if (typeof name === 'string') servers[name] = state
957 }
958 mark('stillPending', 'pending')
959 mark('connected', 'connected')
960 mark('failed', 'failed')
961 mark('needsAuth', 'failed')
962 return servers
963}
964
965/** A skill the agent called, sourced from the listing the window carries, else by its plugin prefix. */
966export function skillUseOrigin(name: string, breakdown?: SessionContextBreakdown): Origin | undefined {
967 const bare = name.replace(/^\//, '')
968 const listed = breakdown?.skills?.skillFrontmatter.find(one => one.name === bare)
969 if (listed !== undefined) return skillOrigin(listed.source, listed.name, listed.pluginName)
970 return pluginOrigin(prefixOf(bare))
971}
972
973/**
974 * A subagent dispatched, sourced from the agent listing the window carries. The listing leaves the
975 * harness's own out, so one it does not name that the engine provides is built in.
976 */
977export function agentUseOrigin(type: string, provider: string, breakdown?: SessionContextBreakdown): Origin | undefined {
978 const listed = breakdown?.agents.find(one => one.agentType === type)
979 if (listed !== undefined) return agentOrigin(listed.source, listed.agentType)
980 if (provider !== 'engine') return pluginOrigin(provider)
981 return prefixOf(type) === undefined ? { source: 'built_in' } : pluginOrigin(prefixOf(type))
982}
983hooks/fleet.ts 75 lines1// What Fleet's intake takes: `crates/ipc/src/sessions.rs`, `SessionReport`. Only
2// shapes here; the code that sends them is in `register.ts`, since the engine
3// follows `$` into one file only.
4
5import type { Engine } from 'claude-code'
6
7import type { ContextBreakdown, LoadoutItem, LoadoutUse, PlanWindow } from './facts'
8
9export type Door = Pick<Engine, 'clock' | 'env' | 'fs' | 'http'>
10
11export type Report = {
12 harness: string
13 session_id: string
14 fact: Fact
15}
16
17/** What Fleet answers a terminal question with (`TerminalAsked`, `crates/ipc/src/hosted_sessions.rs`). */
18export type Asked =
19 | { outcome: 'asked'; call: string }
20 | { outcome: 'waiting' }
21 | { outcome: 'answered'; updated_input: unknown }
22 | { outcome: 'refused'; message: string }
23 | { outcome: 'gone' }
24
25export type Usage = {
26 context_tokens?: number
27 context_window?: number
28 cost_micros?: number
29}
30
31/** One task of the agent's list. `id` is its task tool's, or its place in a `TodoWrite` list. */
32/** `by` is the subagent that made the task, absent for the session's own. */
33export type Task = { id: string; text: string; status: 'pending' | 'in_progress' | 'completed'; by?: string }
34
35export type Fact =
36 | { kind: 'started'; cwd: string; title?: string; origin: 'terminal'; mod_version?: string }
37 | { kind: 'titled'; title: string; named?: boolean }
38 | { kind: 'moved'; cwd: string }
39 | {
40 kind: 'attached'
41 attachment: { kind: string; target: string; detail?: Record<string, string> }
42 }
43 | {
44 kind: 'settled'
45 attachment: { kind: string; target: string }
46 state: 'spent' | 'given_back'
47 }
48 | { kind: 'measured'; usage: Usage; plan?: PlanWindow[]; context_breakdown?: ContextBreakdown }
49 | {
50 kind: 'tuned'
51 model?: string
52 effort?: string
53 mode?: 'ask' | 'auto' | 'accept_edits' | 'plan'
54 commands?: { name: string; says: string }[]
55 mod_version?: string
56 }
57 | { kind: 'turn_started' }
58 | { kind: 'turn_completed'; said?: string }
59 | { kind: 'limited'; resets_at: string }
60 | { kind: 'signed_out' }
61 | { kind: 'touched'; paths: string[]; act?: 'write' | 'edit'; by?: string }
62 | { kind: 'read'; path: string }
63 | { kind: 'ran'; command: string }
64 | { kind: 'wrote' }
65 | { kind: 'tasks'; tasks: Task[] }
66 | { kind: 'plan_left' }
67 | { kind: 'committed'; branch?: string }
68 | { kind: 'pushed'; branch?: string }
69 | { kind: 'permission_asked'; tool: string; detail?: string }
70 | { kind: 'permission_settled' }
71 | { kind: 'ended'; reason: string }
72 // The Loadout: the whole list, replacing the last, and one use in the turn it began in.
73 | { kind: 'equipped'; loadout: { items: LoadoutItem[] } }
74 | { kind: 'used'; use: LoadoutUse }
75hooks/reading.ts 55 lines1// A whole-file read of a large file stays in the context for every turn after it. The guard
2// turns the first one away with the file's outline, so the agent reads the range it needs.
3// Pure, so each reading is a test and not a session.
4
5/** Past this many bytes (about 10k tokens), a Read with no range is turned away once. */
6export const WHOLE_READ_MOST = 40 * 1024
7
8/** The engine reads these as pages or images, not lines: the guard leaves them alone. */
9const NOT_LINES = /\.(pdf|ipynb|png|jpe?g|gif|webp|bmp|ico|icns)$/i
10
11const OUTLINE_MOST = 60
12const LINE_MOST = 100
13
14/** What a Read asked for, as far as the guard reads it. */
15export type ReadAsked = { file_path: string; offset?: number; limit?: number; pages?: string; allow_large?: boolean }
16
17/** Whether the guard looks at this Read at all: a whole read of a file read as lines. */
18export function wholeRead(e: ReadAsked): boolean {
19 return e.offset === undefined && e.limit === undefined && e.pages === undefined && e.allow_large !== true && !NOT_LINES.test(e.file_path)
20}
21
22/**
23 * The lines that say where things are: a markdown heading, or a top-level declaration in
24 * Rust, TypeScript or Python. Numbered from 1, as Read's `offset` counts.
25 */
26export function outlineOf(path: string, text: string): string[] {
27 const markdown = /\.mdx?$/i.test(path)
28 const marks = markdown
29 ? /^#{1,4} /
30 : /^(pub(\([a-z]+\))? )?(async )?(fn|struct|enum|trait|impl|mod|type|const|static|class|def|function|interface|export) /
31 const found: string[] = []
32 let fenced = false
33 text.split('\n').forEach((line, at) => {
34 if (markdown && line.startsWith('```')) fenced = !fenced
35 if (!fenced && marks.test(line)) found.push(`${at + 1}: ${line.length > LINE_MOST ? `${line.slice(0, LINE_MOST)}…` : line}`)
36 })
37 return found
38}
39
40/** What the agent is told in place of the file. */
41export function turnedAway(path: string, size: number, text: string, graph = false): string {
42 const lines = text.split('\n').length
43 const outline = outlineOf(path, text)
44 const shown = outline.slice(0, OUTLINE_MOST)
45 const more = outline.length > shown.length ? `\n… ${outline.length - shown.length} more; Grep the file for the rest.` : ''
46 const where = shown.length > 0 ? `\n\nWhere things are (line: text):\n${shown.join('\n')}${more}` : ''
47 return (
48 `Not read: ${path} is ${Math.round(size / 1024)} KB, ${lines} lines, about ${Math.round(size / 4000)}k tokens, ` +
49 `and a whole read stays in the context for every turn after this one. ` +
50 `${graph && !/\.mdx?$/i.test(path) ? 'Ask the code graph (gitnexus query or context) what you are looking for, ' : ''}` +
51 `Grep it, or Read again with offset and limit for the part you need. ` +
52 `Reading it whole again goes through.${where}`
53 )
54}
55