See the messages your teammates, named subagents, and other Claude Code sessions send you, grouped by peer with unread counts: a pane, a band above the prompt…

<img src="https://img.shields.io/badge/Claude_Code-2.1.288%2B-D97757" alt="Claude Code 2.1.288+"> <img src="https://img.shields.io/badge/type-mod-555555" alt="mod"> <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-555555" alt="License: MIT"></a> <img src="https://img.shields.io/badge/version-1.3.1-555555" alt="Version: 1.3.1">
The band above the prompt and the status line under it: 5 unread from scout, tester, and helper.
When your session works with other agents, their messages arrive in the transcript one at a time, between your own turns. It is hard to see who wrote what, what you have not read yet, and what each of your sends reported. Users report teammate text that looked like their own turns (#40166, #28627) and ask for a message inbox (#100724). High Command groups these messages by peer, says how far Claude Code vouches for each sender, and shows the reported result of each plain-text send.
/highcommand.high-command: 5 unread (retained), is the mod's own line, so another mod's band cannot hide it. It clears at zero. Both count the main inbox. The agentLanesInBand option adds the unread messages of agent lanes.suspicious mark, the time of the latest message, the peer's last known state, and the start of that message. Open a peer to read its thread, newest first: its messages to you and Claude's sends to it, each send with its reported result. Messages that were unread when you opened the thread, and messages that arrive while it is open, stay marked new until you go back to the roster.verified sender: a teammate whose message the team harness wrote under that name.local sender: another session or agent whose message Claude Code delivered. Claude Code does not report the sender's host, so a remote session's message can have this label too.unverified sender: everything else, such as a message that a mod in the sender's session wrote outside a verified team mailbox, or a delivery that Claude Code could not place. Teammates in their own split panes (tmux or iTerm2) write through a file that Claude Code cannot check, so their messages always get this label.The message text can lower a label but never raise one: a message that names a different teammate than the one that sent it is unverified sender. A peer's row and /highcommand show the weakest label among its unread messages, so a newer message cannot hide a warning.
suspicious in its thread, and on its peer's row while it is unread. The list covers some wordings that tell an agent to ignore its earlier instructions, to change the permission mode, to run a download in a shell, or to read a credential file, and long base64 blocks. The check ignores these invisible characters: Unicode format characters (category Cf, such as a zero-width space or a soft hyphen), the combining grapheme joiner U+034F, and the variation selectors U+FE00 to U+FE0F and U+E0100 to U+E01EF. It tests the text once with each of them read as a space and once with each removed, and marks the message when either test matches. Other invisible characters, look-alike letters from another alphabet, and one wording with these characters both inside a word and between two words can still avoid the mark. Other wording with the same aim gets no mark, so a message without the mark can still try to steer an agent. The mark is for you alone: it hides no text and changes nothing that Claude reads.The roster: one row per peer, warning marks first in the last message.
The researcher thread, newest first, with Back, the state, and the sender label at the top.
flowchart LR
IN["Message to your session<br>session.receive"] --> CC["Other mods and Claude Code<br>handle it as usual"]
SUB["Named subagent's message<br>to your session<br>prompt.submit"] --> CC
OUT["Plain-text SendMessage<br>by Claude<br>session.send"] --> CC
CC -->|"queued text or reported result"| MEM[("Session memory: peer, sender label,<br>suspicious mark, send result")]
LIST["ListAgents results and<br>the local agent list"] -->|"states"| MEM
MEM --> BAND["Band and status line"]
MEM --> PANE["Pane: roster and threads"]
MEM --> CMD["/highcommand summary"]
session.receive. Claude Code submits it as a prompt from a peer, so High Command reads it in prompt.submit, both while the session is idle and during a turn. Task notifications, scheduled prompts, and your own Remote Control prompts are not recorded. A message that another mod consumes, or that you decline in an approval dialog, never reaches Claude, so High Command does not record it.Works with Claude Code 2.1.288 and later. Tested with Claude Code 2.1.296.
Agent teams are optional. Turn them on with CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1.
Inside Claude Code:
/plugin marketplace add dot-agi/high-command
/plugin install high-command@high-command
From a shell:
claude plugin marketplace add dot-agi/high-command
claude plugin install high-command@high-command
For one session from a clone:
claude --plugin-dir ./high-command
Install from a shell with Claude Code 2.1.292 or later. The second part turns on auto-update. It runs only when the install succeeds and the marketplace entry exists:
claude plugin install high-command --marketplace dot-agi/high-command --scope user --json \
&& f="${CLAUDE_CONFIG_DIR:-$HOME/.claude}/settings.json" \
&& jq -e --arg name high-command '.extraKnownMarketplaces[$name].source' "$f" > /dev/null \
&& tmp=$(mktemp "$f.XXXXXX") \
&& { jq --arg name high-command '.extraKnownMarketplaces[$name].autoUpdate = true' "$f" > "$tmp" && mv "$tmp" "$f" || { rm -f "$tmp"; false; }; }
Claude Code 2.1.288 to 2.1.291 has no --marketplace option. Add the marketplace first, then run the auto-update part above, from f= on:
claude plugin marketplace add dot-agi/high-command --scope user --json \
&& claude plugin install high-command@high-command --scope user --json
Auto-update runs only in interactive sessions. A headless job updates at its start, before the session that uses the mod:
claude plugin update high-command@high-command --json
/reload-plugins.install again does not update. Use update.CLAUDE_CODE_PLUGIN_PREFER_HTTPS=1 in the environment of every claude command and session.settings.json with a new file with mode 600. If settings.json is a symbolic link, edit its target instead.| Command | What it does |
|---|---|
/highcommand | Prints the summary: one row per peer with its unread count, the time of its latest message, its state, and the kind of its latest message. Runs at once, even during a turn. |
/highcommand open | Opens the pane on the first page of the main inbox roster. In claude -p, it explains that no pane can draw. |
| Key | Where | Action |
|---|---|---|
| Ctrl+X, then Tab | Anywhere | Move the keyboard to the band or the pane. This is Claude Code's own focus chord. |
| Tab | Band or pane | Move to the next button |
| Enter | Band or pane | Press the button that has focus |
o | Band | Open the pane |
r | Band or pane roster | Mark every message read |
h | Band | Hide the band until a newer message arrives |
1-9 | Pane roster | Open the thread of that peer |
p, n | Pane roster | Previous or next page of peers |
m | Pane roster | Show the main inbox |
b | Pane thread, identity, or agent lane | Back up one level |
i | Pane thread | Show the peer's full name |
r | Pane thread | Mark that peer read, only while Mark read shows |
p, n | Pane thread | Newer or older page |
p, n | Pane identity | Previous or next part of the name |
| Esc | Band or pane | Give the keyboard back to the prompt |
In the terminal, the pane shows each letter and digit key before its button's label, as in r: Read all. The agent buttons, the agent pages, Agent status, and Show send details have no key: press Tab to reach them, or click them. When the pane's location line has room, it ends with the dim hint ctrl+x tab or click for keys · esc to prompt.
When the band's row has room, it ends with the dim hint ctrl+x tab to choose. Press Ctrl+X, then Tab, to give the band the keyboard. Then Tab moves between its buttons, Enter presses one, and Esc gives the keyboard back to the prompt.
Release Ctrl before you press Tab, because many terminals read Ctrl+Tab as next tab. In Emacs terminals, Ctrl+X goes to Emacs: click the band, run /highcommand open, or rebind abovePrompt:focus with /keybindings.
Letter and digit keys work only while the band or the pane has the keyboard. Open in the band opens the pane but leaves the keyboard on the band, and focus passes each band button before it reaches the pane. Press Ctrl+X, then Tab, until the pane border shows focus, or click the pane, before you press a digit. Each letter and digit key also has a button you can click. The full guide is docs/usage.md.
Set options in /config, or under pluginConfigs["high-command@high-command"].options in ~/.claude/settings.json. For a --plugin-dir load, the key is high-command@inline.
| Option | Default | Effect |
|---|---|---|
agentLanesInBand | false | Adds the unread count of all agent lanes to the band and the status line, as in high-command: 3 unread (retained) · 2 unread in agent lanes. Read all in the band then also marks every agent lane read. Hide then also ends when a newer message arrives in an agent lane. Open still shows the main inbox. |
A change takes effect at once: Claude Code reloads the mod with the new values. The reload keeps the current inbox, but it drops the inboxes that the mod kept for /resume (see Reloads in Known limits).
Claude Code and other mods also show peer messages. Each row says what the tool does and what High Command adds.
| Tool or feature | What it does | What High Command adds |
|---|---|---|
Built-in Message from rows in the transcript (cross-session messaging) | One dim preview line per message with the sender name. Ctrl+O expands it. | Messages grouped by peer, unread counts, sender labels, and the reported result of each plain-text send. |
Built-in /list-agents (/peers) (cross-session messaging) | Lists subagents, teammates, and local and remote sessions, with offline status. | The messages of each peer. When Claude runs ListAgents, the reported state shows on that peer's roster row. |
| Built-in agent panel (agent teams) | Lists teammates and subagents. Enter opens one teammate's transcript. | One inbox across teammates, named subagents, and other sessions. |
| session-orchestra | A read-only mod with session cards (working or idle state, model, effort, context bar), subagent cards, and a message list with a full-message view and a copy button. It reads transcripts and runs in a terminal. | Unread counts, sender labels, suspicious marks, and the reported result of each plain-text send. High Command reads no files, and its pane also draws in the desktop app, the VS Code panel, and the mobile app. |
| claude-crosstalk | A mod with a per-peer inbox for cross-session messages, unread counts, a status line, and a reply field that sends through SendMessage. It keeps history across restarts and --resume, rebuilt from the session journal. | Teammates and named subagents in the same inbox, sender labels, suspicious marks, and the reported result of each plain-text send. High Command sends nothing and keeps no history past the Claude Code process. |
/clear. /branch keeps the parent conversation's inbox, except with managed settings or a Team or Enterprise sign-in. /resume brings an inbox back only for one of the last 10 conversations that ended in this process since the mod last loaded. Any other /resume starts empty (see Branches and resumes below).shutdown_request, and sends by other mods or by agents that a mod started.suspicious mark covers a short list of wordings, and other wordings get no mark.The list below holds the limits you can hit in daily use. docs/usage.md has every limit, also the rare ones: size caps, unusual names and frames, changes by other mods, and display gaps.
/highcommand lists the counts apart from the main inbox. By default, the band, the status line, and Hide cover the main inbox only, so an unread message in an agent lane does not show there. The agentLanesInBand option adds the unread count of all agent lanes to the band and the status line. A message between your main conversation and a local agent can show twice, once in the main inbox and once in that agent's lane. The lane copy of a message from your main conversation never counts as unread. High Command does not see messages between teammates that run in their own split panes./highcommand, names its source. A roster snapshot status comes from Claude Code's local agent list. High Command reads that list when you open the pane or run /highcommand, when an agent starts, and when an agent ends a turn. Between reads, the status can be old. When two reads overlap, the older one can bring back an agent that the newer one removed. Open the pane or run /highcommand again after agent activity settles. A lifecycle observation says how an agent's last turn ended, such as turn answered or turn error. When the list does not hold an agent that ended a turn, an open pane shows that observation as the agent's status until the next read of the list. It describes a finished turn, so it does not prove that the agent still runs. A teammate in its own split pane can keep its last status after it crashes. /highcommand lists up to 100 local agents. The pane pages through all of them, up to 10 at a time.offline, stays on that peer's row. When the result holds only the printed listing, that name gets the state of the last such row that has one.shutdown_request, shutdown_response, or plan_approval_response object does not reach it. Neither its attempt nor its result appears in the main inbox, an agent lane, or /highcommand. Check the transcript for these sends./branch keeps the inbox as it stood at the branch point: the messages of the main inbox and of each agent lane, the peers and their reply addresses, the read marks, and Hide. New messages go on top. A message you had not read stays unread, with its sender label and any suspicious mark, so the band and the status line count it again. The pane says when you branched and how many messages came from the parent conversation, and /highcommand says the same. That count covers the main inbox and the agent lanes. A branch of a branch also keeps the messages of each conversation before it, and /highcommand counts those conversations. /resume of a conversation that ended in the same process brings back its inbox as it was when it ended. The process keeps the inboxes of the 10 conversations that ended last, so a resume of an older one starts empty. /resume never keeps the inbox of the conversation you leave. A /resume of any other conversation, such as one from an earlier process in the /resume list, starts empty, with no agent lanes, as after /clear. The open thread and the roster page start over, in the main inbox and in each agent lane, and so does the lane you picked. With managed settings or a Team or Enterprise sign-in, /branch starts empty instead (see Managed settings and Team or Enterprise sign-ins below)./resume. A /resume after the reload then starts empty, also for a conversation that ended in this process. Claude Code reloads the mod when you change one of its options, and when it loads new code of the mod, as at /reload-plugins after an update. /branch still keeps the inbox after a reload. With managed settings or a Team or Enterprise sign-in, a reload that no slash command and no /config change causes, before High Command takes a /resume and writes its copy, drops the inbox that it would bring back (see Managed settings and Team or Enterprise sign-ins below)./clear starts an empty inbox. High Command keeps the inboxes in the memory of the Claude Code process only, never on disk. So claude --resume in a new process, --fork-session, and a /fork copy, which runs in a process of its own, start empty, even when the conversation that Claude reads holds earlier messages. A conversation that you move to the background, with /background, /bg, or the left arrow (←) on an empty prompt, starts empty too: Claude Code continues it in a new process, as after claude --resume. The pane and `/highcommanhooks/register.tsx 1227 lines1import { atom, read } from 'claude-code'
2import type { AgentInfo, CommandRunResult, EngineInterface, Register, SessionReceiveOrigin, SessionSendResult, Timer, TraceEntry } from 'claude-code'
3
4import type { HighCommandAgent, HighCommandCapture, HighCommandEntry, HighCommandLane, HighCommandPeer, HighCommandThread, HighCommandView } from '../types'
5import { agentSenderOf, isAgentMessage, parseDelivery, spawnerOf, UNNAMED, type NewEntry, type PeerReport } from './envelope'
6import {
7 appendEntries,
8 coreEvidence,
9 applyReports,
10 fitLanes,
11 hideLanes,
12 keepsThread,
13 lanesSeen,
14 lanesUnread,
15 markOf,
16 markRead,
17 newestInboundSeq,
18 newestSeq,
19 newestUnreadableSeq,
20 outboundEntry,
21 recipientOf,
22 rosterOf,
23 threadOf,
24 unreadTotal,
25 type RosterRow,
26} from './inbox'
27import { LIMITS } from './limits'
28import { parseListing, parseStructuredListing } from './listing'
29import { summaryText } from './summary'
30import { count, sanitize, peerKey, peerKeys, peerLabels, unreadText } from './text'
31import { bandTree, compactBandTree, fitsBounds, laneIdsOf, laneIdsShown, paneTree, rosterPageOf, type BandActions, type PaneActions } from './views'
32
33const DESCRIPTION = 'High Command: messages from teammates and other sessions (/highcommand open shows the pane)'
34const PANE = { id: 'high-command', title: 'High Command', focus: true } as const
35const USAGE = 'Usage: /highcommand shows the inbox summary. /highcommand open opens the High Command pane.'
36const NO_PANES =
37 'command.run: this session draws no panes (claude -p or an SDK host). Use /highcommand for the summary.'
38
39/** The origin kinds whose deliveries can hold messages from peers; `unclassified` counts only with a frame. */
40const MESSAGE_ORIGINS: ReadonlySet<string> = new Set(['peer', 'coordinator', 'peer-send-message', 'unclassified'])
41
42const VIEW = { plugin: 'high-command', key: 'view' } as const
43const LANE_VIEW = { plugin: 'high-command', key: 'laneView' } as const
44
45/** The values of 1.2.2, read once after an update (adoptOld). */
46const OLD_ENTRIES = { plugin: 'high-command', key: 'entries' } as const
47const OLD_PEERS = { plugin: 'high-command', key: 'peers' } as const
48const OLD_READ_THROUGH = { plugin: 'high-command', key: 'readThrough' } as const
49const OLD_OPEN_THREAD = { plugin: 'high-command', key: 'openThread' } as const
50const OLD_HIDDEN_THROUGH = { plugin: 'high-command', key: 'hiddenThrough' } as const
51const OLD_INBOUND_THROUGH = { plugin: 'high-command', key: 'inboundThrough' } as const
52const OLD_LANES = { plugin: 'high-command', key: 'lanes' } as const
53const OLD_HIDDEN_LANES = { plugin: 'high-command', key: 'hiddenLanes' } as const
54const OLD_CAPTURE = { plugin: 'high-command', key: 'capture' } as const
55const OLD_SELECTED_LANE = { plugin: 'high-command', key: 'selectedLane' } as const
56const OLD_LANE_PAGE = { plugin: 'high-command', key: 'lanePage' } as const
57const OLD_AGENT_STATUS = { plugin: 'high-command', key: 'agentStatus' } as const
58const OLD_ROSTER_PAGE = { plugin: 'high-command', key: 'rosterPage' } as const
59const OLD_AGENTS = { plugin: 'high-command', key: 'agents' } as const
60
61/**
62 * The mirror of the current inbox in `$.state`. The pane and the band read it, so Claude Code draws them again after
63 * each mirror write, but they draw the inbox in module memory: a late mirror write cannot show another conversation.
64 */
65const view = atom(VIEW, {
66 session: '', epoch: 0, revision: 0, entries: [], peers: {}, readThrough: {}, hiddenThrough: 0, inboundThrough: 0, capture: null,
67 openThread: null, rosterPage: 0, selectedLane: null, lanePage: 0, agentStatus: false, agents: {},
68})
69
70/**
71 * One conversation's inbox. Module memory holds it, and it survives /branch, /resume, and /clear, so the reset of
72 * `$.state` at a switch cannot race it. Each hook and press changes it at once, without an await in between (edit).
73 */
74type Inbox = {
75 /** A new number for each new inbox, a branch copy included: a press from a drawing of another inbox marks nothing. */
76 epoch: number
77 entries: HighCommandEntry[]
78 peers: Record<string, HighCommandPeer>
79 readThrough: Record<string, number>
80 hiddenThrough: number
81 inboundThrough: number
82 lanes: Record<string, HighCommandLane>
83 hiddenLanes: Record<string, number>
84 capture: HighCommandCapture | null
85 openThread: HighCommandThread | null
86 rosterPage: number
87 selectedLane: string | null
88 lanePage: number
89 agentStatus: boolean
90}
91
92/** Inboxes made since this module loaded. */
93let epochs = 0
94
95function emptyInbox(): Inbox {
96 epochs += 1
97 return {
98 epoch: epochs, entries: [], peers: {}, readThrough: {}, hiddenThrough: 0, inboundThrough: 0, lanes: {}, hiddenLanes: {},
99 capture: null, openThread: null, rosterPage: 0, selectedLane: null, lanePage: 0, agentStatus: false,
100 }
101}
102
103/**
104 * The inbox of each conversation this process saw, by session id, the one used last at the end: a branch copies its
105 * parent's, and a resume takes its own back. It keeps the current one and LIMITS.snapshots others.
106 */
107const inboxes = new Map<string, Inbox>()
108/** The session whose inbox the hooks change and the pane and the band draw; '' when Claude Code did not say. */
109let current: string | undefined
110/** The session that ended last at a switch, until the next conversation starts: the parent of a branch. */
111let lastEnded: string | undefined
112/**
113 * The switch that session.end noted, until classic.SessionStart or settle takes it: its reason and the session that
114 * ended. With managed settings or a Team or Enterprise sign-in, Claude Code passes no classic event to installed mods,
115 * so only settle sees the switch.
116 */
117let pending: { reason: 'clear' | 'resume'; ended: string } | undefined
118/** The session that settle moved to since the last session.end: a classic.SessionStart for it changes no inbox. */
119let settled: string | undefined
120/** The local agents of the process: every conversation shows them. */
121let agents: Record<string, HighCommandAgent> = {}
122/** Counts the changes of module data: the mirror and the status line write only after one. */
123let changes = 0
124
125/** Changes `inbox` at once and counts the change. */
126function edit(inbox: Inbox, change: Partial<Inbox>): void {
127 Object.assign(inbox, change)
128 changes += 1
129}
130
131/** Files `inbox` under `id` as the one used last, and drops the inboxes used least recently past the bound. */
132function keep(id: string, inbox: Inbox): Inbox {
133 inboxes.delete(id)
134 inboxes.set(id, inbox)
135 for (const old of inboxes.keys()) if (inboxes.size > LIMITS.snapshots + 1 && old !== id) inboxes.delete(old)
136 changes += 1
137 return inbox
138}
139
140/** The inbox of the session `id`, a new empty one when the process holds none. */
141function inboxOf(id: string): Inbox {
142 return inboxes.get(id) ?? keep(id, emptyInbox())
143}
144
145/** The current conversation's inbox. */
146function inboxNow(): Inbox {
147 return inboxOf(current ?? '')
148}
149
150/**
151 * The inbox a press acts on: the one its drawing showed, while that conversation is still the current one and its
152 * inbox the same; else undefined, and the press does nothing.
153 */
154function pressed(drawn: Drawn): Inbox | undefined {
155 const inbox = current === drawn.session ? inboxes.get(drawn.session) : undefined
156 return inbox?.epoch === drawn.epoch ? inbox : undefined
157}
158
159/** What a drawing showed: its conversation and inbox, and the newest seq it drew, also per agent lane. */
160type Drawn = { session: string; epoch: number; through: number; lanes: ReadonlyMap<string, number> }
161
162function drawnOf(inbox: Inbox, list: readonly HighCommandEntry[]): Drawn {
163 const lanes = new Map(Object.entries(inbox.lanes).map(([id, lane]) => [id, newestSeq(lane.entries)]))
164 return { session: current ?? '', epoch: inbox.epoch, through: newestSeq(list), lanes }
165}
166
167/** The entries of `list` that a drawing through seq `through` showed: a mark never covers a message drawn later. */
168function seenOf(list: readonly HighCommandEntry[], through: number): HighCommandEntry[] {
169 return list.filter(entry => entry.seq <= through)
170}
171
172function emptyLane(): HighCommandLane {
173 return { entries: [], peers: {}, readThrough: {}, openThread: null }
174}
175
176function laneOf(inbox: Inbox, id: string): HighCommandLane {
177 return Object.hasOwn(inbox.lanes, id) ? inbox.lanes[id]! : emptyLane()
178}
179
180/** Characters that the copy of the lanes adds around them: its session id, its epoch, and its keys. */
181const LANE_VIEW_FRAME = 256
182
183/** Characters of the copy of `lanes` and `hiddenLanes` as one saved value. */
184function savedSize(lanes: Readonly<Record<string, HighCommandLane>>, hiddenLanes: Readonly<Record<string, number>>): number {
185 return JSON.stringify(lanes).length + JSON.stringify(hiddenLanes).length + LANE_VIEW_FRAME
186}
187
188/**
189 * Lanes and their Hide marks cut to the space of one saved value, for lanes that no change built, as those of 1.2.2:
190 * fitLanes first, then the Hide marks go, so that the band counts those lanes again, and then the lanes whose newest
191 * message is oldest. `isCut` says whether a Hide mark or a lane went; `dropped` counts the lanes.
192 */
193function fitSaved(lanes: Readonly<Record<string, HighCommandLane>>, hiddenLanes: Readonly<Record<string, number>>): { lanes: Record<string, HighCommandLane>; hiddenLanes: Record<string, number>; isCut: boolean; dropped: number } {
194 const fitted = fitLanes(lanes)
195 if (savedSize(fitted, hiddenLanes) <= LIMITS.savedChars) return { lanes: fitted, hiddenLanes: { ...hiddenLanes }, isCut: false, dropped: 0 }
196 const kept = new Map(Object.entries(fitted))
197 let size = savedSize(fitted, {})
198 let dropped = 0
199 const oldestFirst = [...kept].sort(([, a], [, b]) => (a.entries.at(-1)?.at ?? 0) - (b.entries.at(-1)?.at ?? 0))
200 for (const [id, lane] of oldestFirst) {
201 if (size <= LIMITS.savedChars) break
202 kept.delete(id)
203 size -= JSON.stringify(id).length + JSON.stringify(lane).length + 2
204 dropped += 1
205 }
206 return { lanes: Object.fromEntries(kept), hiddenLanes: {}, isCut: true, dropped }
207}
208
209/**
210 * Sets the agent lanes and their Hide marks of `inbox`, unless their copy would pass the space of one saved value.
211 * fitLanes drops old lane messages, but each lane keeps its newest message, so very many lanes can still pass it: the
212 * change then throws before memory changes, and the hook or the press says so.
213 */
214function setLanes(inbox: Inbox, lanes: Record<string, HighCommandLane>, hiddenLanes = inbox.hiddenLanes): void {
215 const size = JSON.stringify(lanes).length + JSON.stringify(hiddenLanes).length + LANE_VIEW_FRAME
216 if (size > LIMITS.savedChars) {
217 throw new Error(`the agent lanes would pass the ${count(LIMITS.savedChars, 'character')} that Claude Code saves in one value, so the change is not kept`)
218 }
219 edit(inbox, { lanes, hiddenLanes })
220}
221
222/** Changes one agent lane; fitLanes keeps all lanes within the space of one saved value where it can (setLanes). */
223function changeLane(inbox: Inbox, id: string, change: (lane: HighCommandLane) => HighCommandLane): void {
224 const next = new Map(Object.entries(inbox.lanes))
225 next.set(id, change(next.get(id) ?? emptyLane()))
226 setLanes(inbox, fitLanes(Object.fromEntries(next), id))
227}
228
229/** Changes every agent lane at once; `change` gets each lane and its id. */
230function changeLanes(inbox: Inbox, change: (lane: HighCommandLane, id: string) => HighCommandLane): void {
231 setLanes(inbox, fitLanes(Object.fromEntries(Object.entries(inbox.lanes).map(([id, lane]) => [id, change(lane, id)]))))
232}
233
234function changeThread(inbox: Inbox, id: string | undefined, change: (thread: HighCommandThread | null) => HighCommandThread | null): void {
235 if (id === undefined) edit(inbox, { openThread: change(inbox.openThread) })
236 else changeLane(inbox, id, lane => ({ ...lane, openThread: change(lane.openThread) }))
237}
238
239function ensureCapture(inbox: Inbox, at: number): void {
240 if (inbox.capture === null) edit(inbox, { capture: { at, reset: false } })
241}
242
243/** The open threads, roster pages, lane picked, and lane page of `inbox` start over, as after a reset of `$.state`. */
244function startOver(inbox: Inbox): Inbox {
245 const lanes = Object.fromEntries(Object.entries(inbox.lanes).map(([id, { openThread: _thread, rosterPage: _page, ...lane }]) => [id, { ...lane, openThread: null }]))
246 edit(inbox, { lanes, openThread: null, rosterPage: 0, selectedLane: null, lanePage: 0, agentStatus: false })
247 return inbox
248}
249
250/** A branch of `parent`: a copy of its inbox under a new epoch, where the views start over (startOver). */
251function branchOf(parent: Inbox): Inbox {
252 epochs += 1
253 return startOver({ ...parent, epoch: epochs })
254}
255
256/** Reads status without treating a repeated split-pane roster word as liveness evidence. */
257async function refreshAgents($: EngineInterface, event: string): Promise<void> {
258 try {
259 const at = await $.clock.now()
260 const list = await $.agent.list()
261 const next = new Map(Object.entries(agents).filter(([, value]) => value.at > at))
262 for (const agent of list) if (!next.has(agent.id)) next.set(agent.id, {
263 id: agent.id, name: agent.name === undefined ? undefined : peerKey(agent.name),
264 status: agent.status, at, source: 'roster snapshot',
265 lastEvent: Object.hasOwn(agents, agent.id) ? agents[agent.id]?.lastEvent : undefined,
266 })
267 agents = Object.fromEntries(next)
268 changes += 1
269 } catch (error) {
270 diagnose($, `high-command: ${event}: could not refresh local agents: ${causeOf(error)}`)
271 }
272}
273
274/** Transcript diagnostics already written since this module loaded. */
275const logged = new Set<string>()
276
277function causeOf(error: unknown): string {
278 return error instanceof Error ? error.message : String(error)
279}
280
281/** Writes a diagnostic to the transcript once per module load; a repeat goes to the debug log alone. */
282function diagnose($: EngineInterface, line: string): void {
283 if (logged.has(line)) {
284 $.ui.log(line.replace(/^high-command: /, ''), { to: 'debug' })
285 return
286 }
287 logged.add(line)
288 $.ui.log(line.replace(/^high-command: /, ''))
289}
290
291/** Whether this module took the inbox back from `$.state`, or found no copy there: only then may it write the mirror. */
292let isAdopted = false
293/** The take-back under way or done; undefined until the first hook, and again after one that could not read the copy. */
294let ready: Promise<boolean> | undefined
295
296/**
297 * Takes the inbox back once per module load (adopt), before any write. Resolves false while the copy in `$.state`
298 * cannot be read: the hook then records nothing and writes nothing, and the next hook tries again. So memory that is
299 * empty after a reload never writes over the copy that the module before it left.
300 */
301function ensureReady($: EngineInterface, event: string): Promise<boolean> {
302 if (ready === undefined) {
303 const adopting = adopt($, event)
304 ready = adopting
305 void adopting.then(isDone => {
306 if (!isDone && ready === adopting) ready = undefined
307 })
308 }
309 return ready
310}
311
312/**
313 * Takes back the inbox that `$.state` mirrors when this module has none for the current session, as after a reload of
314 * the mod, which empties module memory, keeps `$.state`, and runs session.start again. A mirror of another session
315 * stays out, and one that names no session counts as this session's. Resolves whether it could read the copy.
316 */
317async function adopt($: EngineInterface, event: string): Promise<boolean> {
318 if (current === undefined) {
319 // Without the id, no copy can be told apart from another session's: take nothing back, and try again later.
320 try {
321 current = await $.session.id()
322 } catch (error) {
323 diagnose($, `high-command: ${event}: could not read the session id: ${causeOf(error)}`)
324 return false
325 }
326 }
327 const id = current
328 if (inboxes.has(id)) {
329 isAdopted = true
330 return true
331 }
332 const inbox = emptyInbox()
333 try {
334 const main = (await $.state.get(VIEW)).value
335 const laneView = (await $.state.get(LANE_VIEW)).value
336 const isOwn = (session: string | undefined) => session === undefined || session === id
337 if (main !== undefined && isOwn(main.session)) {
338 edit(inbox, {
339 entries: main.entries ?? [], peers: main.peers ?? {}, readThrough: main.readThrough ?? {},
340 hiddenThrough: main.hiddenThrough ?? 0, inboundThrough: main.inboundThrough ?? 0, capture: main.capture ?? null,
341 openThread: main.openThread ?? null, rosterPage: main.rosterPage ?? 0, selectedLane: main.selectedLane ?? null,
342 lanePage: main.lanePage ?? 0, agentStatus: main.agentStatus ?? false,
343 })
344 agents = main.agents ?? {}
345 }
346 if (laneView !== undefined && isOwn(laneView.session)) edit(inbox, { lanes: laneView.lanes ?? {}, hiddenLanes: laneView.hiddenLanes ?? {} })
347 // Until both copies have landed, the values of 1.2.2 still hold what a missing copy would have held.
348 if (main === undefined || laneView === undefined) await adoptOld($, inbox, event, main === undefined, laneView === undefined)
349 } catch (error) {
350 diagnose($, `high-command: ${event}: could not take back the inbox: ${causeOf(error)}`)
351 return false
352 }
353 keep(id, inbox)
354 isAdopted = true
355 return true
356}
357
358/**
359 * Takes over into `inbox` the values that 1.2.2 kept in `$.state` itself, after an update by /reload-plugins: the
360 * values belong to the current session, since Claude Code resets them at each switch. `isMain` and `isLanes` say which
361 * copy has not landed yet, and so which part to take: until a copy lands, each load takes its part from these values.
362 * The lanes take the space of one saved value at most (fitSaved), so that their copy can land.
363 */
364async function adoptOld($: EngineInterface, inbox: Inbox, event: string, isMain: boolean, isLanes: boolean): Promise<void> {
365 if (isMain) {
366 const main = {
367 entries: (await $.state.get(OLD_ENTRIES)).value, peers: (await $.state.get(OLD_PEERS)).value,
368 readThrough: (await $.state.get(OLD_READ_THROUGH)).value, openThread: (await $.state.get(OLD_OPEN_THREAD)).value,
369 hiddenThrough: (await $.state.get(OLD_HIDDEN_THROUGH)).value, inboundThrough: (await $.state.get(OLD_INBOUND_THROUGH)).value,
370 capture: (await $.state.get(OLD_CAPTURE)).value, selectedLane: (await $.state.get(OLD_SELECTED_LANE)).value,
371 lanePage: (await $.state.get(OLD_LANE_PAGE)).value, agentStatus: (await $.state.get(OLD_AGENT_STATUS)).value,
372 rosterPage: (await $.state.get(OLD_ROSTER_PAGE)).value, agents: (await $.state.get(OLD_AGENTS)).value,
373 }
374 if (Object.values(main).some(value => value !== undefined)) {
375 edit(inbox, {
376 entries: main.entries ?? [], peers: main.peers ?? {}, readThrough: main.readThrough ?? {}, openThread: main.openThread ?? null,
377 hiddenThrough: main.hiddenThrough ?? 0, inboundThrough: main.inboundThrough ?? 0, capture: main.capture ?? null,
378 selectedLane: main.selectedLane ?? null, lanePage: main.lanePage ?? 0, agentStatus: main.agentStatus ?? false, rosterPage: main.rosterPage ?? 0,
379 })
380 agents = main.agents ?? agents
381 }
382 }
383 if (isLanes) {
384 const lanes = (await $.state.get(OLD_LANES)).value
385 const hiddenLanes = (await $.state.get(OLD_HIDDEN_LANES)).value
386 if (lanes === undefined && hiddenLanes === undefined) return
387 const fitted = fitSaved(lanes ?? {}, hiddenLanes ?? {})
388 if (fitted.isCut) {
389 const dropped = fitted.dropped === 0 ? '' : ` and ${count(fitted.dropped, 'lane')} whose newest message was oldest`
390 diagnose($, `high-command: ${event}: the agent lanes of 1.2.2 pass the space of one saved value, so High Command dropped their Hide marks${dropped}`)
391 }
392 edit(inbox, { lanes: fitted.lanes, hiddenLanes: fitted.hiddenLanes })
393 }
394}
395
396/** The `changes` count that the mirror last wrote. */
397let mirrored = -1
398/** Mirror writes issued, and the newest one that answered. */
399let writes = 0
400let answered = 0
401/** The lane value the mirror wrote last; undefined once Claude Code resets `$.state` or a lane write may be stale. */
402let laneMirror: { session: string; epoch: number; lanes: Record<string, HighCommandLane>; hiddenLanes: Record<string, number> } | undefined
403
404/** The mirror writes under way (publish), until each lands or fails: the copy of a settled switch waits for them too (startCopy). */
405const publishing = new Set<Promise<void>>()
406
407/** Writes the mirror (writeMirror), and notes the write in `publishing` while it is under way. */
408function publish($: EngineInterface): Promise<void> {
409 const run = writeMirror($)
410 publishing.add(run)
411 const done = () => { publishing.delete(run) }
412 void run.then(done, done)
413 return run
414}
415
416/**
417 * Writes the current inbox to `$.state`, each value whole: the main view, and the lanes when they changed. Each write
418 * holds the data of the moment it leaves, so the last one wins with current data. A write that answers after a newer
419 * one may have landed last, so it writes the data again.
420 */
421async function writeMirror($: EngineInterface): Promise<void> {
422 if (!isAdopted || changes === mirrored) return
423 for (;;) {
424 mirrored = changes
425 const session = current ?? ''
426 const inbox = inboxNow()
427 writes += 1
428 const write = writes
429 const sent = laneMirror
430 // A failed lane write is reported once the main view is written, so it never keeps a main message from the copy.
431 let laneFailure: { error: unknown } | undefined
432 if (sent === undefined || sent.session !== session || sent.epoch !== inbox.epoch || sent.lanes !== inbox.lanes || sent.hiddenLanes !== inbox.hiddenLanes) {
433 const lanes = { session, epoch: inbox.epoch, lanes: inbox.lanes, hiddenLanes: inbox.hiddenLanes }
434 laneMirror = lanes
435 try {
436 await $.state.set(LANE_VIEW, lanes)
437 } catch (error) {
438 laneMirror = undefined
439 laneFailure = { error }
440 }
441 }
442 const main: HighCommandView = {
443 session, epoch: inbox.epoch, revision: write, entries: inbox.entries, peers: inbox.peers, readThrough: inbox.readThrough,
444 hiddenThrough: inbox.hiddenThrough, inboundThrough: inbox.inboundThrough, capture: inbox.capture, openThread: inbox.openThread,
445 rosterPage: inbox.rosterPage, selectedLane: inbox.selectedLane, lanePage: inbox.lanePage, agentStatus: inbox.agentStatus, agents,
446 }
447 await $.state.set(VIEW, main)
448 if (write > answered) {
449 answered = write
450 if (laneFailure !== undefined) throw laneFailure.error
451 return
452 }
453 laneMirror = undefined
454 }
455}
456
457/** Writes the mirror after a change; a failure is diagnosed under `event`. */
458async function mirror($: EngineInterface, event: string): Promise<void> {
459 try {
460 await publish($)
461 } catch (error) {
462 diagnose($, `high-command: ${event}: could not update the view: ${causeOf(error)}`)
463 }
464}
465
466/** The `changes` count that the status line last showed. */
467let pinned = -1
468
469/**
470 * Pins the unread count as this plugin's status line, which no other mod's band can hide, or clears the line at zero,
471 * once per change of module data. The count comes from module memory as the call leaves, so the newest call carries
472 * the newest count. `isForced` pins whatever the line shows: a reload may drop the line. `withLanes` (agentLanesInBand)
473 * adds the unread count of all agent lanes. A failure is diagnosed under `event`.
474 */
475function syncStatus($: EngineInterface, event: string, isForced = false, withLanes = false): void {
476 if (!isForced && changes === pinned) return
477 pinned = changes
478 try {
479 const inbox = inboxNow()
480 $.ui.status(unreadText(unreadTotal(rosterOf(inbox.entries, {}, inbox.readThrough)), withLanes ? lanesUnread(inbox.lanes) : 0) || undefined)
481 } catch (error) {
482 diagnose($, `high-command: ${event}: could not update the status line: ${causeOf(error)}`)
483 }
484}
485
486/**
487 * Takes the switch that session.end noted when no classic.SessionStart reports it, at the first hook after
488 * `$.session.id()` stops answering the session that ended. Until then the switch is still under way, and nothing
489 * changes. Then, once: a clear starts an empty inbox; a resume takes back the inbox that this process kept for the
490 * session, else starts an empty one. Here a branch cannot be told from a resume of another process's conversation, so
491 * it starts empty too, and shows nothing of another conversation. Without the guard, a branch never settles here:
492 * `$.session.id()` answers the parent until classic.SessionStart has run. `write` says when the copy of the inbox goes
493 * to `$.state` (CopyWrite, startCopy).
494 */
495async function settle($: EngineInterface, event: string, withLanes: boolean, write: CopyWrite = 'await'): Promise<void> {
496 const waiting = pending
497 if (waiting === undefined) return
498 let id: string
499 try {
500 id = await $.session.id()
501 } catch (error) {
502 diagnose($, `high-command: ${event}: could not read the session id: ${causeOf(error)}`)
503 return
504 }
505 if (pending !== waiting || id === waiting.ended) return
506 let now: number | undefined
507 try { now = await $.clock.now() } catch (error) { diagnose($, `high-command: ${event}: could not set capture window: ${causeOf(error)}`) }
508 // Another hook, classic.SessionStart, or a newer session.end took the switch meanwhile.
509 if (pending !== waiting) return
510 pending = undefined
511 settled = id
512 lastEnded = undefined
513 laneMirror = undefined
514 const known = waiting.reason === 'resume' ? inboxes.get(id) : undefined
515 current = id
516 const inbox = keep(id, known !== undefined ? startOver(known) : emptyInbox())
517 if (now !== undefined) {
518 if (known === undefined) edit(inbox, { capture: { at: now, reset: true } })
519 else ensureCapture(inbox, now)
520 }
521 syncStatus($, event, true, withLanes)
522 const copy = noteCopy()
523 if (write === 'timer') $.clock.after(0, () => { void startCopy($, copy, event) })
524 else if (write === 'start') void startCopy($, copy, event)
525 else await startCopy($, copy, event)
526}
527
528/**
529 * When a settle writes its copy of the inbox to `$.state` (startCopy): `await`, before the settle resolves; `timer`, in
530 * a timer at 0 ms, as a drawing may not write `$.state`; `start`, at once, while the caller waits for it (settleFirst).
531 */
532type CopyWrite = 'await' | 'timer' | 'start'
533
534/** The copy of the inbox that a settle writes to `$.state`: its write once begun (startCopy). */
535type SettleCopy = { written?: Promise<void> }
536
537/**
538 * The copy that the last settle writes, from the settle until that write has landed or failed (noteCopy). A slash
539 * command or a /config change waits for it (settleFirst), and writes it at once when a drawing left it to its timer.
540 */
541let settleCopy: SettleCopy | undefined
542
543/** Notes a new copy of a settle in `settleCopy`, not begun yet. */
544function noteCopy(): SettleCopy {
545 const copy: SettleCopy = {}
546 settleCopy = copy
547 return copy
548}
549
550/**
551 * Writes `copy` once, and resolves once that write has landed or failed: whoever starts it first writes it with its own
552 * `$`, the timer of a drawing or a hook, and each later call gets the same write. The write is a mirror write under
553 * `event`, then a wait for every mirror write under way (publishing): a write that another hook began after the settle
554 * holds its data, and may not have landed yet. Then the note goes.
555 */
556function startCopy($: EngineInterface, copy: SettleCopy, event: string): Promise<void> {
557 copy.written ??= (async () => {
558 await mirror($, event)
559 await Promise.allSettled([...publishing])
560 if (settleCopy === copy) settleCopy = undefined
561 })()
562 return copy.written
563}
564
565/** ensureReady, then settle a switch that no classic.SessionStart reported. Resolves what ensureReady resolves. */
566async function ensureCurrent($: EngineInterface, event: string, withLanes: boolean, write: CopyWrite = 'await'): Promise<boolean> {
567 if (!(await ensureReady($, event))) return false
568 if (pending !== undefined) await settle($, event, withLanes, write)
569 return true
570}
571
572/**
573 * Settles a pending switch before a slash command or a /config change goes on (settle), then waits until the copy of
574 * the inbox that a settle writes has landed (settleCopy), LIMITS.settleWaitMs at most. Either can reload the mod, as
575 * /reload-plugins and a change of an option do: the reload empties module memory, and Claude Code reset `$.state` at
576 * the switch, so the copy must be in `$.state` first. A copy that a drawing left to its timer is written here at once.
577 * With no switch pending and no copy under way, it calls nothing and waits for nothing.
578 */
579async function settleFirst($: EngineInterface, event: string, withLanes: boolean): Promise<void> {
580 if (pending !== undefined) await ensureCurrent($, event, withLanes, 'start')
581 const copy = settleCopy
582 if (copy === undefined) return
583 let passed = () => {}
584 const deadline = new Promise<void>(resolve => { passed = resolve })
585 const timer = $.clock.after(LIMITS.settleWaitMs, () => passed())
586 try {
587 await Promise.race([startCopy($, copy, event), deadline])
588 } finally {
589 timer.cancel()
590 }
591}
592
593/** The timers of the last switch that session.end noted (watch). */
594let watcher: Timer | undefined
595
596/**
597 * Settles the switch that session.end noted without waiting for another hook: on a surface with no band and with the
598 * pane closed, none may come before a reload of the mod, which would find `$.state` reset and the inbox gone. It reads
599 * `$.session.id()` (ensureCurrent) once at 0 ms, then every LIMITS.switchReadMs, one read at a time. It stops once the
600 * switch settled, by these timers, another hook, or classic.SessionStart, and after LIMITS.switchReads periods. A newer
601 * switch stops it.
602 */
603function watch($: EngineInterface, withLanes: boolean): void {
604 watcher?.cancel()
605 const waiting = pending
606 if (waiting === undefined) return
607 const timers: Timer[] = []
608 const stop = () => { for (const timer of timers) timer.cancel() }
609 let periods = 0
610 let isReading = false
611 const readId = () => {
612 if (pending !== waiting) {
613 stop()
614 return
615 }
616 if (isReading) return
617 isReading = true
618 void ensureCurrent($, 'session.end', withLanes).finally(() => {
619 isReading = false
620 if (pending !== waiting) stop()
621 })
622 }
623 timers.push($.clock.after(0, readId))
624 timers.push($.clock.every(LIMITS.switchReadMs, () => {
625 periods += 1
626 if (periods > LIMITS.switchReads) {
627 stop()
628 return
629 }
630 readId()
631 }))
632 watcher = { cancel: stop }
633}
634
635/** The entries of the main inbox or of a lane, and the roster built from them, as `/highcommand` and the pane read them. */
636function rosterIn(inbox: Inbox, laneId?: string): { list: HighCommandEntry[]; rows: RosterRow[] } {
637 if (laneId !== undefined) {
638 const lane = laneOf(inbox, laneId)
639 return { list: lane.entries, rows: rosterOf(lane.entries, lane.peers, lane.readThrough) }
640 }
641 return { list: inbox.entries, rows: rosterOf(inbox.entries, inbox.peers, inbox.readThrough) }
642}
643
644/**
645 * Appends fresh entries. The open thread closes when this append drops its peer from the window, so the pane shows
646 * the roster and stays there when that peer writes again; keepsThread keeps a thread opened after this append.
647 * `inboundThrough`, and a lane's own `inboundThrough`, keep the newest inbound seq after its entry leaves the window,
648 * so a Hide that it outdates stays ended.
649 */
650function append(inbox: Inbox, fresh: readonly NewEntry[], at: number, laneId?: string): void {
651 if (laneId !== undefined) {
652 changeLane(inbox, laneId, lane => {
653 const list = appendEntries(lane.entries, fresh, at)
654 return {
655 ...lane, entries: list, inboundThrough: Math.max(lane.inboundThrough ?? 0, newestUnreadableSeq(list)),
656 openThread: lane.openThread === null || keepsThread(lane.openThread, lane.entries, list) ? lane.openThread : null,
657 }
658 })
659 return
660 }
661 const before = inbox.entries
662 const list = appendEntries(before, fresh, at)
663 const open = inbox.openThread
664 edit(inbox, {
665 entries: list, inboundThrough: Math.max(inbox.inboundThrough, newestInboundSeq(list)),
666 openThread: open === null || keepsThread(open, before, list) ? open : null,
667 })
668}
669
670function saveReports(inbox: Inbox, reports: readonly PeerReport[], at: number, laneId?: string): void {
671 if (laneId === undefined) edit(inbox, { peers: applyReports(inbox.peers, reports, at) })
672 else changeLane(inbox, laneId, lane => ({ ...lane, peers: applyReports(lane.peers, reports, at) }))
673}
674
675/**
676 * Records the entries and peer states of one queued delivery in `inbox`, and says in the debug log when it names no
677 * sender. `event` is the hook that saw it: session.receive, or prompt.submit for a local agent's message. `sender`,
678 * when given, files all of the delivery under that name, whatever names its text claims.
679 */
680function recordDelivery($: EngineInterface, inbox: Inbox, event: string, text: string, origin: SessionReceiveOrigin, at: number, laneId?: string, sender?: string): void {
681 const parsed = parseDelivery(text, origin, sender)
682 if (parsed.incomplete) diagnose($, `high-command: ${event}: incomplete frame parsing; consult the transcript for original framing`)
683 if ([...parsed.entries, ...parsed.reports].some(item => item.peer === UNNAMED)) {
684 $.ui.log(`${event}: a ${origin.kind} delivery named no sender; it shows as "${UNNAMED}"`, { to: 'debug' })
685 }
686 if (parsed.entries.length === 0 && parsed.reports.length === 0) return
687 // In an agent lane, a coordinator delivery is the main conversation's own message to that agent: never unread.
688 const fresh = laneId !== undefined && origin.kind === 'coordinator' ? parsed.entries.map(entry => ({ ...entry, fromMain: true as const })) : parsed.entries
689 if (fresh.length > 0) append(inbox, fresh, at, laneId)
690 if (parsed.reports.length > 0) saveReports(inbox, parsed.reports, at, laneId)
691}
692
693/** The local agents for a subagent message's sender label; a failure keeps the label and goes to the debug log. */
694async function agentsForLabel($: EngineInterface): Promise<readonly AgentInfo[]> {
695 try {
696 return await $.agent.list()
697 } catch (error) {
698 $.ui.log(`prompt.submit: could not read local agents: ${causeOf(error)}; the message keeps the local sender label`, { to: 'debug' })
699 return []
700 }
701}
702
703/** Records the observed send attempt and its result in the inbox of `session`; an attempt to an agent with no name is left out. */
704async function recordSend($: EngineInterface, session: string, to: string, text: string, sent: SessionSendResult, trace: readonly TraceEntry<'session.send'>[], at: number, laneId?: string): Promise<void> {
705 const listed = await $.agent.list()
706 const inbox = inboxes.get(session)
707 if (inbox === undefined) return
708 const lane = laneId === undefined ? undefined : laneOf(inbox, laneId)
709 const peer = recipientOf(to, lane?.peers ?? inbox.peers, listed, lane?.entries ?? inbox.entries)
710 if (peer === undefined) return
711 append(inbox, [{ ...outboundEntry(peer, text, sent), core: coreEvidence(trace) }], at, laneId)
712}
713
714/** Records the peer states a ListAgents listing names in the inbox of `session`, or says in the debug log that no row gave one. */
715async function recordListing($: EngineInterface, session: string, { reports, rowCount }: ReturnType<typeof parseListing>, laneId?: string): Promise<void> {
716 reports.forEach(report => { report.source ??= 'formatted listing' })
717 if (reports.length > 0) {
718 const at = await $.clock.now()
719 const inbox = inboxes.get(session)
720 if (inbox !== undefined) saveReports(inbox, reports, at, laneId)
721 } else if (rowCount > 0) {
722 $.ui.log(
723 `tool.call ListAgents: no listing row gave a peer state (${count(rowCount, 'row')} read); peer states are unchanged`,
724 { to: 'debug' },
725 )
726 }
727}
728
729/** Opens the main inbox roster; answers why the pane is not drawn, or undefined when it is. */
730async function openPane($: EngineInterface): Promise<string | undefined> {
731 await refreshAgents($, 'ui.open')
732 try { ensureCapture(inboxNow(), await $.clock.now()) } catch (error) { diagnose($, `high-command: ui.open: could not set capture window: ${causeOf(error)}`) }
733 edit(inboxNow(), { selectedLane: '', rosterPage: 0, openThread: null })
734 await publish($)
735 const opened = await $.ui.open(PANE)
736 return opened.isPlaced ? undefined : `the pane waits to be drawn: ${opened.reason}`
737}
738
739/** `/highcommand open`: the pane, or the reason there is none. */
740async function openFromCommand($: EngineInterface): Promise<CommandRunResult> {
741 try {
742 if ((await $.session.surfaces()).length === 0) return { text: NO_PANES }
743 const problem = await openPane($)
744 return problem === undefined ? {} : { text: `command.run: ${problem}` }
745 } catch (error) {
746 return { text: `command.run: the pane did not open: ${causeOf(error)}` }
747 }
748}
749
750/**
751 * Runs a button's work; a failure becomes a toast that names the action. The press counts as the person's
752 * own input only while its onPress work runs, so each handler returns this promise: a `$.ui.open` after
753 * awaits is then asked, and the pane is placed at any width. A switch that no classic.SessionStart reported
754 * settles first, so a press on a drawing of the conversation that ended does nothing (pressed).
755 */
756function press($: EngineInterface, action: string, withLanes: boolean, work: () => Promise<unknown>): Promise<void> {
757 const run = pending === undefined ? work() : settle($, 'ui.press', withLanes).then(work)
758 return run.then(() => undefined, (error: unknown) => $.ui.toast(`ui.press: ${action}: ${causeOf(error)}`))
759}
760
761/**
762 * Marks `peer`, or every peer when none is given, read through its newest inbound entry that the drawing `drawn`
763 * showed, in the lane `laneId` or the main inbox of `inbox`.
764 */
765function markPeersRead(inbox: Inbox, drawn: Drawn, peer?: string, laneId?: string): void {
766 if (laneId !== undefined) changeLane(inbox, laneId, lane => ({ ...lane, readThrough: markRead(lane.readThrough, seenOf(lane.entries, drawn.through), peer) }))
767 else edit(inbox, { readThrough: markRead(inbox.readThrough, seenOf(inbox.entries, drawn.through), peer) })
768}
769
770/**
771 * What a press changes, for the status line: read marks (`marks`), agent lane content (`lane`), which can evict lane
772 * messages (fitLanes), or only the view (`view`).
773 */
774type PressKind = 'marks' | 'lane' | 'view'
775
776/**
777 * Refreshes the status line after a press of `kind`, then writes the mirror. Read marks count in the main inbox, and in
778 * an agent lane only when the line counts agent lanes (`withLanes`); a lane change counts only then too. A failed
779 * mirror write rejects, so the press shows it.
780 */
781async function afterPress($: EngineInterface, kind: PressKind, laneId: string | undefined, withLanes: boolean): Promise<void> {
782 const counts = kind === 'marks' ? laneId === undefined || withLanes : kind === 'lane' && laneId !== undefined && withLanes
783 if (counts) syncStatus($, 'ui.press', false, withLanes)
784 await publish($)
785}
786
787/**
788 * Moves the pane's focus ring onto the element `key` after a view change, so the person keeps their place. The keys
789 * are the person's to give: a site that does not hold them refuses, and the view change stands.
790 */
791async function focusOn($: EngineInterface, key: string | undefined): Promise<void> {
792 if (key === undefined) return
793 try {
794 await $.ui.focus({ requestId: PANE.id, key })
795 } catch {
796 // Refused: the person holds the keys elsewhere, or the element is gone. Nothing to report.
797 }
798}
799
800/**
801 * Shows the roster page that draws `peer`'s row and returns that row's key. The thread can move the row to another
802 * page: opening it marks the peer read, which sorts it behind the unread peers. Without the row (its messages left the
803 * window), the page stays and there is no key.
804 */
805function showPeerRow(inbox: Inbox, laneId: string | undefined, peer: string): string | undefined {
806 const { rows } = rosterIn(inbox, laneId)
807 const page = rosterPageOf(rows, peer)
808 if (page === undefined) return undefined
809 if (laneId === undefined) edit(inbox, { rosterPage: page })
810 else changeLane(inbox, laneId, lane => ({ ...lane, rosterPage: page }))
811 return peerKeys(rows.map(row => row.peer)).get(peer)
812}
813
814/** Whether the lane page shown draws the agent `id`'s lane Button. */
815function isLaneShown(inbox: Inbox, id: string): boolean {
816 const all = Object.values(agents)
817 return laneIdsShown(laneIdsOf(Object.keys(inbox.lanes), all), inbox.lanePage, all).includes(id)
818}
819
820/** Where the ring goes once the lane `id` ('' for the main inbox) shows: Back of its open thread, else `key`. */
821function laneFocus(inbox: Inbox, id: string, key: string): string {
822 const open = id === '' ? inbox.openThread : laneOf(inbox, id).openThread
823 return open === null ? key : 'pane:back'
824}
825
826/**
827 * The pane's buttons. Each acts on the inbox its drawing showed (`drawn`), and does nothing once another conversation
828 * or another inbox is current (pressed).
829 */
830function paneActions($: EngineInterface, withLanes: boolean, drawn: Drawn, laneId?: string): PaneActions {
831 /**
832 * Runs `change` on the drawn inbox, then refreshes the status line and writes the mirror (afterPress); nothing once
833 * the inbox changed. `change` answers the key that the focus ring moves to, if any.
834 */
835 const act = (action: string, kind: PressKind, change: (inbox: Inbox) => string | undefined | void) => press($, action, withLanes, async () => {
836 const inbox = pressed(drawn)
837 if (inbox === undefined) return
838 const key = change(inbox)
839 await afterPress($, kind, laneId, withLanes)
840 if (typeof key === 'string') await focusOn($, key)
841 })
842 return {
843 openThread: peer => act('open thread', 'marks', inbox => {
844 const marks = laneId === undefined ? inbox.readThrough : laneOf(inbox, laneId).readThrough
845 changeThread(inbox, laneId, () => ({ peer, since: markOf(marks, peer), from: drawn.through }))
846 markPeersRead(inbox, drawn, peer, laneId)
847 return 'pane:back'
848 }),
849 // Up one level, to the roster page that draws the peer that was open, with the ring on its row.
850 back: () => act('back', 'lane', inbox => {
851 const closed: { peer?: string } = {}
852 changeThread(inbox, laneId, open => {
853 closed.peer = open?.peer
854 return null
855 })
856 return closed.peer === undefined ? undefined : showPeerRow(inbox, laneId, closed.peer)
857 }),
858 markRead: peer => act('mark read', 'marks', inbox => markPeersRead(inbox, drawn, peer, laneId)),
859 readAll: () => act('read all', 'marks', inbox => markPeersRead(inbox, drawn, undefined, laneId)),
860 page: page => act('page', 'lane', inbox => changeThread(inbox, laneId, open => open === null ? null : { ...open, page })),
861 // Opening the Identity level puts the ring on its Back; closing it puts the ring back on Show identity.
862 identity: identityPage => act('identity', 'lane', inbox => {
863 const before: { wasOpen?: boolean } = {}
864 changeThread(inbox, laneId, open => {
865 before.wasOpen = open?.identityPage !== undefined
866 return open === null ? null : { ...open, identityPage }
867 })
868 if (identityPage === undefined) return 'pane:identity'
869 return before.wasOpen === false ? 'pane:back' : undefined
870 }),
871 reason: reasonSeq => act('send details', 'lane', inbox => changeThread(inbox, laneId, open => open === null ? null : { ...open, reasonSeq: open.reasonSeq === reasonSeq ? undefined : reasonSeq })),
872 lane: id => act('select lane', 'view', inbox => {
873 edit(inbox, { selectedLane: id })
874 return laneFocus(inbox, id, id === '' ? 'lane:main' : `lane:${id}`)
875 }),
876 // Up one level from an agent lane, to the main inbox, with the ring on the Button of the lane that was open.
877 leaveLane: () => act('back', 'view', inbox => {
878 edit(inbox, { selectedLane: '' })
879 return laneFocus(inbox, '', laneId !== undefined && isLaneShown(inbox, laneId) ? `lane:${laneId}` : 'lane:main')
880 }),
881 rosterPage: page => act('peer page', 'lane', inbox => {
882 if (laneId === undefined) edit(inbox, { rosterPage: page })
883 else changeLane(inbox, laneId, lane => ({ ...lane, rosterPage: page }))
884 }),
885 lanePage: page => act('agent page', 'view', inbox => edit(inbox, { lanePage: page })),
886 agentStatus: () => act('agent status', 'view', inbox => edit(inbox, { agentStatus: !inbox.agentStatus })),
887 }
888}
889
890/**
891 * The band's buttons; with agentLanesInBand (`withLanes`), Read all and Hide also cover agent lanes. Read all and Hide
892 * cover what the drawing `drawn` showed, and do nothing once another conversation or another inbox is current.
893 */
894function bandActions($: EngineInterface, withLanes: boolean, drawn: Drawn): BandActions {
895 return {
896 open: () =>
897 press($, 'the pane did not open', withLanes, async () => {
898 const problem = await openPane($)
899 if (problem !== undefined) $.ui.toast(`ui.press: ${problem}`)
900 }),
901 readAll: () =>
902 press($, 'read all', withLanes, async () => {
903 const inbox = pressed(drawn)
904 if (inbox === undefined) return
905 if (withLanes) changeLanes(inbox, (lane, id) => ({ ...lane, readThrough: markRead(lane.readThrough, seenOf(lane.entries, drawn.lanes.get(id) ?? 0)) }))
906 markPeersRead(inbox, drawn)
907 await afterPress($, 'marks', undefined, withLanes)
908 }),
909 hide: () =>
910 press($, 'hide', withLanes, async () => {
911 const inbox = pressed(drawn)
912 if (inbox === undefined) return
913 if (withLanes) setLanes(inbox, inbox.lanes, hideLanes(inbox.hiddenLanes, drawn.lanes))
914 edit(inbox, { hiddenThrough: Math.max(inbox.hiddenThrough, drawn.through) })
915 await publish($)
916 }),
917 }
918}
919
920export const register: Register = (on, options) => {
921 /** The `agentLanesInBand` option: the band and the status line add the unread count of all agent lanes. */
922 const withLanes = options.agentLanesInBand === true
923
924 on('session.start', async ($, e, next) => {
925 try {
926 await $.command.register({ name: 'highcommand', description: DESCRIPTION, argumentHint: '[open]', immediate: true })
927 } catch (error) {
928 diagnose($, `high-command: session.start: could not register /highcommand: ${causeOf(error)}`)
929 }
930 if (!(await ensureCurrent($, 'session.start', withLanes))) return next(e)
931 try { ensureCapture(inboxNow(), await $.clock.now()) } catch (error) { diagnose($, `high-command: session.start: could not set capture window: ${causeOf(error)}`) }
932 syncStatus($, 'session.start', true, withLanes)
933 await mirror($, 'session.start')
934 return next(e)
935 })
936
937 // At /clear, /resume, and /branch, Claude Code runs session.end, then resets $.state, then runs classic.SessionStart.
938 // The inbox stays in module memory, so the hook only remembers the session that ends: the parent of a branch. It
939 // also notes the switch for settle, in case no classic.SessionStart comes, and starts the timers that settle it once
940 // the id changed (watch). Any other reason is an exit with no switch after it, so the hook does nothing then.
941 on('session.end', async ($, e, next) => {
942 if (e.reason !== 'clear' && e.reason !== 'resume') return next(e)
943 pending = { reason: e.reason, ended: e.sessionId }
944 settled = undefined
945 await ensureReady($, 'session.end')
946 lastEnded = e.sessionId
947 laneMirror = undefined
948 watch($, withLanes)
949 return next(e)
950 })
951
952 // Any source sets the current session from `e.session_id`: at a branch, `$.session.id()` still answers the parent
953 // here. A branch copies its parent's inbox (the session that ended last), a resume takes its own inbox back when
954 // this process kept it, and a clear, or a resume or branch with nothing kept, starts a new empty inbox. Then the hook
955 // writes the mirror again, so the last mirror write after the switch holds the new conversation's inbox. When settle
956 // already moved to this conversation, the hook changes no inbox: settle gave the same one, and what was recorded
957 // since then stays.
958 on('classic.SessionStart', async ($, e, next) => {
959 const isSwitch = e.source === 'fork' || e.source === 'resume' || e.source === 'clear'
960 if (!(await ensureReady($, 'classic.SessionStart'))) {
961 if (!isSwitch) return next(e)
962 // The copy that could not be read is the inbox of the conversation that ended, so the next one may write its own.
963 ready = Promise.resolve(true)
964 isAdopted = true
965 }
966 const id = e.session_id
967 if (isSwitch) {
968 const isSettled = settled === id
969 pending = undefined
970 settled = undefined
971 if (isSettled) {
972 lastEnded = undefined
973 syncStatus($, 'classic.SessionStart', false, withLanes)
974 await mirror($, 'classic.SessionStart')
975 return next(e)
976 }
977 }
978 const parent = e.source === 'fork' && lastEnded !== undefined ? inboxes.get(lastEnded) : undefined
979 const known = e.source === 'resume' ? inboxes.get(id) : undefined
980 if (isSwitch) lastEnded = undefined
981 current = id
982 laneMirror = undefined
983 const inbox = keep(id, parent !== undefined ? branchOf(parent) : known !== undefined ? startOver(known) : isSwitch ? emptyInbox() : inboxOf(id))
984 // A branch counts what it copied, in the same moment: the parent can record more while the clock answers.
985 const copied = parent === undefined ? undefined : {
986 window: inbox.capture, messages: inbox.entries.length + Object.values(inbox.lanes).reduce((sum, lane) => sum + lane.entries.length, 0),
987 }
988 try {
989 const now = await $.clock.now()
990 if (copied !== undefined) {
991 const window = copied.window ?? { at: now, reset: true }
992 edit(inbox, { capture: { ...window, branch: { at: now, messages: copied.messages, depth: (window.branch?.depth ?? 0) + 1 } } })
993 } else if (isSwitch && known === undefined) edit(inbox, { capture: { at: inbox.capture?.at ?? now, reset: true } })
994 else ensureCapture(inbox, now)
995 } catch (error) {
996 diagnose($, `high-command: classic.SessionStart: could not set capture window: ${causeOf(error)}`)
997 }
998 syncStatus($, 'classic.SessionStart', parent !== undefined || known !== undefined, withLanes)
999 await mirror($, 'classic.SessionStart')
1000 return next(e)
1001 })
1002
1003 on('session.receive', async ($, e, next) => {
1004 if (!MESSAGE_ORIGINS.has(e.origin.kind)) return next(e)
1005 if (!(await ensureCurrent($, 'session.receive', withLanes))) return next(e)
1006 // The message belongs to the conversation that is current as it arrives, even when a switch comes before it records.
1007 const session = current ?? ''
1008 let at: number | undefined
1009 try { at = await $.clock.now(); ensureCapture(inboxOf(session), at) } catch (error) { diagnose($, `high-command: session.receive: could not observe delivery time: ${causeOf(error)}`) }
1010 const queued = await next(e)
1011 if (queued.consumed !== undefined) return queued
1012 const inbox = inboxes.get(session)
1013 try {
1014 if (at !== undefined && inbox !== undefined) recordDelivery($, inbox, 'session.receive', queued.text, e.origin, at, e.agentId)
1015 } catch (error) {
1016 diagnose($, `high-command: session.receive: could not record a delivery (${e.origin.kind}): ${causeOf(error)}`)
1017 }
1018 if (e.agentId === undefined || withLanes) syncStatus($, 'session.receive', false, withLanes)
1019 await mirror($, 'session.receive')
1020 return queued
1021 })
1022
1023 // In Claude Code 2.1.296 a named subagent's SendMessage to the main conversation skips session.receive:
1024 // Claude Code submits its <agent-message> as a peer prompt, while the session is idle or into a running
1025 // turn. A message from another session passed session.receive first, so only an agent message counts here.
1026 // A mod beneath can rewrite it without the frame; the text that entered is then filed under the one sender
1027 // that the frames named, or under `unnamed peer`, and a name that the rewritten text claims does not count.
1028 // The prompt's origin does not say whether a mod started the sender, so the local agent list can lower its label;
1029 // the list is read before the mods beneath run, while an agent that ends meanwhile is still listed.
1030 on('prompt.submit', { origin: { kind: 'peer' } }, async ($, e, next) => {
1031 if (!isAgentMessage(e.text)) return next(e)
1032 if (!(await ensureCurrent($, 'prompt.submit', withLanes))) return next(e)
1033 const session = current ?? ''
1034 let at: number | undefined
1035 try { at = await $.clock.now(); ensureCapture(inboxOf(session), at) } catch (error) { diagnose($, `high-command: prompt.submit: could not observe delivery time: ${causeOf(error)}`) }
1036 const named = agentSenderOf(e.text, e.origin)
1037 const listed = named === undefined ? undefined : agentsForLabel($)
1038 const entered = await next(e)
1039 if (entered.drop !== undefined) return entered
1040 try {
1041 if (at !== undefined) {
1042 let sender: string | undefined
1043 if (!isAgentMessage(entered.text)) {
1044 sender = named
1045 const filing = sender === undefined ? `its frames named no single sender, so it is filed under "${UNNAMED}"` : 'it is filed under the sender that the frame named'
1046 $.ui.log(`prompt.submit: a mod rewrote a subagent message without its <agent-message> frame; ${filing}`, { to: 'debug' })
1047 sender ??= UNNAMED
1048 }
1049 const plugin = named === undefined || listed === undefined ? undefined : spawnerOf(await listed, named)
1050 const origin = plugin === undefined ? e.origin : { kind: 'peer' as const, plugin }
1051 const inbox = inboxes.get(session)
1052 if (inbox !== undefined) recordDelivery($, inbox, 'prompt.submit', entered.text, origin, at, undefined, sender)
1053 }
1054 } catch (error) {
1055 diagnose($, `high-command: prompt.submit: could not record a delivery (${e.origin.kind}): ${causeOf(error)}`)
1056 }
1057 syncStatus($, 'prompt.submit', false, withLanes)
1058 await mirror($, 'prompt.submit')
1059 return entered
1060 })
1061
1062 on('session.send', async ($, e, next) => {
1063 if (e.origin.kind !== 'model') return next(e)
1064 if (!(await ensureCurrent($, 'session.send', withLanes))) return next(e)
1065 const session = current ?? ''
1066 let at: number | undefined
1067 try { at = await $.clock.now(); ensureCapture(inboxOf(session), at) } catch (error) { diagnose($, `high-command: session.send: could not observe send time: ${causeOf(error)}`) }
1068 const sent = await next(e)
1069 try {
1070 if (at !== undefined) {
1071 await recordSend($, session, e.to, e.text, sent, next.trace, at, e.agentId)
1072 }
1073 } catch (error) {
1074 diagnose($, `high-command: session.send: could not record a message to ${sanitize(e.to)}: ${causeOf(error)}`)
1075 }
1076 if (e.agentId === undefined || withLanes) syncStatus($, 'session.send', false, withLanes)
1077 await mirror($, 'session.send')
1078 return sent
1079 })
1080
1081 on('tool.call', { tool: 'ListAgents' }, async ($, e, next) => {
1082 if (!(await ensureCurrent($, 'tool.call ListAgents', withLanes))) return next(e)
1083 const session = current ?? ''
1084 const out = await next(e)
1085 const result: unknown = out.isError === true ? undefined : out.result
1086 const structured = parseStructuredListing(result)
1087 const listing = typeof result === 'object' && result !== null && 'listing' in result ? result.listing : undefined
1088 if (structured === undefined && typeof listing !== 'string') return out
1089 try {
1090 if (structured !== undefined) {
1091 await recordListing($, session, structured, e.agentId)
1092 } else if (typeof listing === 'string') await recordListing($, session, parseListing(listing), e.agentId)
1093 } catch (error) {
1094 diagnose($, `high-command: tool.call ListAgents: could not record peer states: ${causeOf(error)}`)
1095 }
1096 // Peer states make a lane longer, so fitLanes can evict lane messages.
1097 if (e.agentId !== undefined && withLanes) syncStatus($, 'tool.call ListAgents', false, true)
1098 await mirror($, 'tool.call ListAgents')
1099 return out
1100 })
1101
1102 on('agent.spawn', async ($, e, next) => {
1103 const result = await next(e)
1104 if (!(await ensureCurrent($, 'agent.spawn', withLanes))) return result
1105 await refreshAgents($, 'agent.spawn')
1106 await mirror($, 'agent.spawn')
1107 return result
1108 })
1109
1110 // A main turn records nothing, but the first one after a switch that no classic.SessionStart reported settles it.
1111 on('turn.complete', async ($, e, next) => {
1112 const result = await next(e)
1113 if (e.agentId === undefined && pending === undefined) return result
1114 if (await ensureCurrent($, 'turn.complete', withLanes) && e.agentId !== undefined) {
1115 await refreshAgents($, 'turn.complete')
1116 try {
1117 const at = await $.clock.now()
1118 const observed = new Map(Object.entries(agents))
1119 const agent = observed.get(e.agentId)
1120 const word = e.reason === 'answer' ? 'turn answered' : `turn ${e.reason}`
1121 if ((agent?.lastEvent?.at ?? -Infinity) <= at) observed.set(e.agentId, {
1122 ...agent, id: e.agentId, status: agent?.status ?? word, at: agent?.at ?? at,
1123 source: agent?.source ?? 'lifecycle observation', lastEvent: { word, at },
1124 })
1125 agents = Object.fromEntries(observed)
1126 changes += 1
1127 } catch (error) { diagnose($, `high-command: turn.complete: could not record lifecycle observation: ${causeOf(error)}`) }
1128 await mirror($, 'turn.complete')
1129 }
1130 return result
1131 })
1132
1133 // Every slash command, /highcommand included, settles a pending switch first and waits for the copy of the inbox
1134 // that a settle writes, also one that a drawing left to its timer, then runs as typed: a command can reload the mod,
1135 // as /reload-plugins does (settleFirst). With no switch pending and no copy under way, the hook calls nothing.
1136 on('command.run', async ($, e, next) => {
1137 await settleFirst($, 'command.run', withLanes)
1138 return next(e)
1139 })
1140
1141 // Every /config change does the same first: a change of an option reloads the mod (settleFirst). The change then
1142 // goes on as it came: the hook never refuses it and never changes its value.
1143 on('config.set', async ($, e, next) => {
1144 await settleFirst($, 'config.set', withLanes)
1145 return next(e)
1146 })
1147
1148 on('command.run', { command: 'highcommand' }, async ($, e) => {
1149 const argument = e.args.trim()
1150 if (!(await ensureCurrent($, 'command.run', withLanes))) return { text: 'command.run: could not take back the inbox from $.state' }
1151 if (argument === 'open') return openFromCommand($)
1152 if (argument !== '') return { text: USAGE }
1153 try {
1154 await refreshAgents($, 'command.run')
1155 const now = await $.clock.now()
1156 const inbox = inboxNow()
1157 ensureCapture(inbox, now)
1158 const { list, rows } = rosterIn(inbox)
1159 const text = summaryText(rows, list.length, now, { evicted: list.at(-1)?.evictedTotal, capture: inbox.capture, agents: Object.values(agents), lanes: inbox.lanes })
1160 await mirror($, 'command.run')
1161 return { text }
1162 } catch (error) {
1163 return { text: `command.run: could not build the summary: ${causeOf(error)}` }
1164 }
1165 })
1166
1167 on('ui.render', { component: 'Pane', requestId: 'high-command' }, async ($, e) => {
1168 const ui = $.ui.resolve(e)
1169 try {
1170 if (!(await ensureCurrent($, 'ui.render', withLanes, 'timer'))) throw new Error('could not take back the inbox from $.state')
1171 await read($, view)
1172 const inbox = inboxNow()
1173 const chosen = inbox.selectedLane
1174 const laneId = chosen === '' ? undefined : chosen ?? e.props.view.agentId
1175 const { list, rows } = rosterIn(inbox, laneId)
1176 const lane = laneId === undefined ? undefined : laneOf(inbox, laneId)
1177 const thread = threadOf(list, rows, lane === undefined ? inbox.openThread : lane.openThread)
1178 const drawn = drawnOf(inbox, list)
1179 const laneIds = Object.keys(inbox.lanes)
1180 const laneUnread = new Map(Object.entries(inbox.lanes).map(([id, known]) => [id, unreadTotal(rosterOf(known.entries, {}, known.readThrough))]))
1181 const now = await $.clock.now()
1182 return paneTree(ui, { rows, now, thread, laneId, rosterPage: lane === undefined ? inbox.rosterPage : lane.rosterPage, lanePage: inbox.lanePage,
1183 laneIds, agents: Object.values(agents), laneUnread, capture: inbox.capture, evicted: list.at(-1)?.evictedTotal ?? 0,
1184 columns: e.props.bodyColumns, statusOpen: inbox.agentStatus,
1185 }, paneActions($, withLanes, drawn, laneId))
1186 } catch (error) {
1187 const { Text } = ui
1188 return <Text color="red">{`high-command: ui.render (Pane): ${causeOf(error)}`}</Text>
1189 }
1190 })
1191
1192 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
1193 if (e.props.hasSurvey) return next(e)
1194 const below = await next(e)
1195 if (!(await ensureCurrent($, 'ui.render', withLanes, 'timer'))) return below
1196 await read($, view)
1197 const inbox = inboxNow()
1198 const list = inbox.entries
1199 // A Hide holds while the person had seen every inbound entry: those in the window and those recorded before.
1200 const isHidden = inbox.hiddenThrough >= Math.max(inbox.inboundThrough, newestInboundSeq(list))hooks/envelope.ts 263 lines1import type { AgentInfo, SessionReceiveOrigin } from 'claude-code'
2
3import type { HighCommandEntry, HighCommandTrust } from '../types'
4import { capBody, isSuspicious, peerKey, sanitize, summaryOf } from './text'
5
6/** An entry before the inbox numbers and stamps it. */
7export type NewEntry = Omit<HighCommandEntry, 'seq' | 'at'>
8
9/** What a frame or a listing row says about a peer. */
10export type PeerReport = { peer: string; state?: string; address?: string; source?: string }
11
12/** The peer a delivery that names no sender is filed under. */
13export const UNNAMED = 'unnamed peer'
14
15/** One frame of a delivery; `name` is the tag, absent for text kept from beside the frames. */
16type Frame = { name?: string; attributes: ReadonlyMap<string, string>; body: string }
17type Protocol = { type: string } & Record<string, unknown>
18
19const FRAMING = /^\s*Another Claude session sent a message:\s*/
20/** The start of the notice that the engine writes on a line of its own after a delivery's text. */
21const NOTICE = '\nThis came from another Claude session'
22/** Decodes the XML entities attribute values use; `&` last, so `&lt;` stays `<`. */
23function decode(value: string): string {
24 return value
25 .replaceAll('"', '"')
26 .replaceAll(''', "'")
27 .replaceAll('<', '<')
28 .replaceAll('>', '>')
29 .replaceAll('&', '&')
30}
31
32/** Tokenizes once from left to right; malformed names never trigger suffix searches. */
33function attributesOf(text: string): { attributes: Map<string, string>; malformed: boolean } {
34 const attributes = new Map<string, string>()
35 let at = 0
36 let malformed = false
37 while (at < text.length) {
38 if (/\s/.test(text[at]!)) { at++; continue }
39 const start = at
40 while (at < text.length && /[\w-]/.test(text[at]!)) at++
41 const name = text.slice(start, at)
42 if (name === '' || text[at] !== '=' || text[at + 1] !== '"') {
43 malformed = true
44 if (at === start) at++
45 continue
46 }
47 at += 2
48 const valueAt = at
49 while (at < text.length && text[at] !== '"') at++
50 if (at === text.length) { malformed = true; break }
51 const value = text.slice(valueAt, at++)
52 if (value.trim() !== '') attributes.set(name, decode(value))
53 }
54 return { attributes, malformed }
55}
56
57/** Finds a frame's closing tag, ignoring literals inside a JSON object's strings. */
58function closingOf(text: string, start: number, closing: string): number {
59 let at = start
60 while (at < text.length && /\s/.test(text[at]!)) at += 1
61 if (text[at] !== '{') return text.indexOf(closing, at)
62 let depth = 0
63 let quoted = false
64 let escaped = false
65 for (; at < text.length; at += 1) {
66 const char = text[at]
67 if (quoted) {
68 // A raw line feed or tab cannot occur in a JSON string; keep malformed text as a message.
69 if (char === '\n' || char === '\t') return text.indexOf(closing, at)
70 if (escaped) escaped = false
71 else if (char === '\\') escaped = true
72 else if (char === '"') quoted = false
73 } else if (text.startsWith(closing, at)) {
74 return at
75 } else if (char === '"') {
76 quoted = true
77 } else if (char === '{') {
78 depth += 1
79 } else if (char === '}') {
80 depth -= 1
81 if (depth === 0) return text.indexOf(closing, at + 1)
82 }
83 }
84 return -1
85}
86
87/**
88 * Finds complete frames in one forward pass, skipping closing-tag literals in JSON strings.
89 * A name with no closing tag left is not searched for again, keeping the scan linear.
90 */
91function framesOf(text: string): { frames: Frame[]; incomplete: boolean } {
92 const names = ['teammate-message', 'agent-message', 'cross-session-message']
93 const unclosed = new Set<string>()
94 const frames: Frame[] = []
95 let at = 0
96 let span = 0
97 let incomplete = false
98 const preserve = (end: number, tail = false): void => {
99 const raw = text.slice(span, end)
100 const body = (tail ? unframed(raw) : raw).trim()
101 if (body !== '') {
102 frames.push({ attributes: new Map(), body })
103 incomplete = true
104 }
105 }
106 while (at < text.length) {
107 const opening = text.indexOf('<', at)
108 if (opening < 0) break
109 at = opening + 1
110 const name = names.find(value => text.startsWith(value, at) && /[\s>]/.test(text[at + value.length] ?? ''))
111 if (name === undefined || unclosed.has(name)) continue
112 const attributesAt = at + name.length
113 at = attributesAt
114 while (at < text.length && text[at] !== '>' && text[at] !== '<') at++
115 if (text[at] !== '>') { incomplete = true; continue }
116 const start = at + 1
117 const closing = `</${name}>`
118 const end = closingOf(text, start, closing)
119 if (end === -1) { incomplete = true; unclosed.add(name); continue }
120 preserve(opening)
121 const parsed = attributesOf(text.slice(attributesAt, at))
122 incomplete ||= parsed.malformed
123 frames.push({ name, attributes: parsed.attributes, body: text.slice(start, end).trim() })
124 at = end + closing.length
125 span = at
126 }
127 if (frames.length > 0) preserve(text.length, true)
128 return { frames, incomplete }
129}
130
131/** The text of a delivery that holds no frame, cut before the engine's last notice; the peer wrote only the text before it. */
132function unframed(text: string): string {
133 const at = `\n${text}`.lastIndexOf(NOTICE)
134 return (at === -1 ? text : text.slice(0, at)).trim()
135}
136
137/** The JSON object a protocol body holds, or undefined for any other body. */
138function protocolOf(body: string): Protocol | undefined {
139 if (!body.startsWith('{')) return undefined
140 try {
141 // JSON text that starts with "{" parses to an object or throws.
142 const value = JSON.parse(body) as Record<string, unknown>
143 return typeof value.type === 'string' ? (value as Protocol) : undefined
144 } catch {
145 // A body that starts with "{" and is not JSON is a plain message.
146 return undefined
147 }
148}
149
150/** A sanitized string field with a non-space character, else undefined. */
151function textField(value: unknown): string | undefined {
152 const text = typeof value === 'string' ? sanitize(value) : ''
153 return text.trim() === '' ? undefined : text
154}
155
156/**
157 * The first claim that is a name after peerKey: the frame, the team origin's name (`stamped`), the protocol
158 * body; else the origin's default. Every other claim is text of this frame, so the work stays linear in the
159 * delivery.
160 */
161function senderOf(frame: Frame, protocol: Protocol | undefined, origin: SessionReceiveOrigin, stamped: string): string {
162 const from = protocol?.from
163 const claims = [
164 peerKey(frame.attributes.get('teammate_id') ?? ''),
165 peerKey(frame.attributes.get('from-name') ?? ''),
166 peerKey(frame.attributes.get('from') ?? ''),
167 stamped,
168 typeof from === 'string' ? peerKey(from) : '',
169 ]
170 return claims.find(name => name !== '') ?? (origin.kind === 'coordinator' ? 'coordinator' : UNNAMED)
171}
172
173/**
174 * The trust level of one sender name, from origin fields alone. A team mailbox entry is verified only
175 * when the harness checked it and the frame names that same member; another session's or agent's
176 * message that Claude Code delivered is local unless a plugin composed it; the rest is unverified.
177 */
178function trustOf(origin: SessionReceiveOrigin, peer: string, stamped: string): HighCommandTrust {
179 if ('teammate' in origin) return origin.isVerified && peer === stamped ? 'verified' : 'unverified'
180 const isPluginClaim = 'plugin' in origin && origin.plugin !== undefined
181 return isPluginClaim || origin.kind === 'unclassified' ? 'unverified' : 'local'
182}
183
184/** The state an idle notification reports. */
185function idleState(protocol: Protocol): string {
186 if (textField(protocol.failureReason) !== undefined || protocol.idleReason === 'failed') return 'failed'
187 return protocol.idleReason === 'interrupted' ? 'interrupted' : 'idle'
188}
189
190/**
191 * Whether a peer prompt is a local agent's SendMessage to the main conversation: it holds an
192 * `<agent-message>` frame and no frame of another kind. Claude Code 2.1.296 submits such a message as a
193 * prompt and skips session.receive; a message from another session passes session.receive first.
194 */
195export function isAgentMessage(text: string): boolean {
196 const { frames } = framesOf(sanitize(text).replace(FRAMING, ''))
197 const names = new Set(frames.flatMap(frame => (frame.name === undefined ? [] : [frame.name])))
198 return names.size === 1 && names.has('agent-message')
199}
200
201/**
202 * The one sender that the `<agent-message>` frames of a prompt name, or undefined when they name none or
203 * several. A mod beneath can rewrite such a prompt without its frame; the text that enters keeps this name.
204 */
205export function agentSenderOf(text: string, origin: SessionReceiveOrigin): string | undefined {
206 const { frames } = framesOf(sanitize(text).replace(FRAMING, ''))
207 const names = new Set(frames.flatMap(frame =>
208 frame.name === 'agent-message' ? [senderOf(frame, protocolOf(frame.body), origin, '')] : []))
209 const [name] = names
210 return names.size === 1 && name !== UNNAMED ? name : undefined
211}
212
213/**
214 * The mod that started the local agents whose id or name is `sender`, when a mod started every one of them;
215 * undefined when none is listed or the model or the person started one. Claude Code does not pass a mod on with a
216 * subagent's peer prompt, so this can only lower the label of a message from that sender.
217 */
218export function spawnerOf(agents: readonly AgentInfo[], sender: string): string | undefined {
219 const matches = agents.filter(agent => agent.id === sender || peerKey(agent.name ?? '') === sender)
220 return matches.length > 0 && matches.every(agent => agent.spawnedBy !== undefined) ? matches[0]!.spawnedBy : undefined
221}
222
223/**
224 * Splits one queued delivery into entries and peer reports. When `sender` is given, every frame and text of
225 * the delivery is filed under it, and the names that they claim are ignored.
226 */
227export function parseDelivery(text: string, origin: SessionReceiveOrigin, sender?: string): { entries: NewEntry[]; reports: PeerReport[]; incomplete?: boolean } {
228 const clean = sanitize(text).replace(FRAMING, '')
229 const { frames, incomplete } = framesOf(clean)
230 if (frames.length === 0 && origin.kind === 'unclassified') return { entries: [], reports: [], ...(incomplete ? { incomplete: true } : {}) }
231 const entries: NewEntry[] = []
232 const reports: PeerReport[] = []
233 // The origin's name is the same for every frame, so it is keyed once.
234 const stamped = 'teammate' in origin ? peerKey(origin.teammate) : ''
235 for (const frame of frames.length > 0 ? frames : [{ attributes: new Map<string, string>(), body: unframed(clean) }]) {
236 const protocol = protocolOf(frame.body)
237 const peer = sender ?? senderOf(frame, protocol, origin, stamped)
238 const trust = trustOf(origin, peer, stamped)
239 const add = (kind: NewEntry['kind'], preferred: string | undefined, body: string): void => {
240 const mark = isSuspicious(`${preferred ?? ''}\n${body}`) ? { isSuspicious: true as const } : {}
241 entries.push({ peer, direction: 'in', kind, summary: summaryOf(preferred, body), ...capBody(body), trust, ...mark })
242 }
243 const address = frame.attributes.has('from-name') ? frame.attributes.get('from') : undefined
244 if (address !== undefined) reports.push({ peer, address })
245 if (protocol === undefined) {
246 add('message', frame.attributes.get('summary'), frame.body)
247 } else if (protocol.type === 'idle_notification') {
248 const failure = textField(protocol.failureReason)
249 const result = textField(protocol.result)
250 reports.push({ peer, state: idleState(protocol) })
251 if (failure !== undefined) add('failure', undefined, result === undefined ? failure : `${failure}\n\n${result}`)
252 else if (result !== undefined) add('result', textField(protocol.summary), result)
253 } else if (protocol.type === 'teammate_terminated') {
254 reports.push({ peer, state: 'ended' })
255 } else if (protocol.type === 'shutdown_approved') {
256 reports.push({ peer, state: 'shut down' })
257 } else {
258 add('message', `[${sanitize(protocol.type)}]`, frame.body)
259 }
260 }
261 return { entries, reports, ...(incomplete ? { incomplete: true } : {}) }
262}
263hooks/inbox.ts 366 lines1import type { AgentInfo, SessionSendResult, TraceEntry } from 'claude-code'
2
3import type { HighCommandEntry, HighCommandLane, HighCommandPeer, HighCommandState, HighCommandThread, HighCommandTrust } from '../types'
4import type { NewEntry, PeerReport } from './envelope'
5import { LIMITS } from './limits'
6import { capBody, lineOf, peerKey, sanitize, summaryOf } from './text'
7
8type Peers = Record<string, HighCommandPeer>
9
10/** Per peer, the highest inbound seq marked read. */
11type ReadMarks = Record<string, number>
12
13/** The trust levels, the weakest first. */
14const LEVELS: readonly HighCommandTrust[] = ['unverified', 'local', 'verified']
15
16/** The six hexadecimal characters appended to a recipient name in ListAgents output. */
17const RECIPIENT_REF = / \[[0-9a-f]{6}\]$/i
18
19/**
20 * A peer with entries: its unread count, its newest entry, its last reported state, and the trust level and
21 * suspicious mark its row shows (no trust level when it only received sends).
22 */
23export type RosterRow = {
24 peer: string
25 unread: number
26 last: HighCommandEntry
27 state?: HighCommandState
28 trust?: HighCommandTrust
29 isSuspicious: boolean
30}
31
32/** The open thread as the pane draws it: the newest entries first, the count of older ones, and the count of new ones. */
33/** `moved`: the entries that moved to the next page because this one ended at its budget, up to LIMITS.threadEntries. */
34export type Thread = { row: RosterRow; since: number; shown: HighCommandEntry[]; hidden: number; fresh: number; page: number; pages: number; moved: number; identityPage?: number; reasonSeq?: number }
35
36/** The seq of the newest entry, or 0 for an empty list. The window never drops its newest entry. */
37export function newestSeq(list: readonly HighCommandEntry[]): number {
38 return list.at(-1)?.seq ?? 0
39}
40
41/** The seq of the newest inbound entry, or 0 without one. */
42export function newestInboundSeq(list: readonly HighCommandEntry[]): number {
43 return list.findLast(entry => entry.direction === 'in')?.seq ?? 0
44}
45
46/**
47 * Numbers and stamps fresh entries; keeps each peer's newest LIMITS.peerEntries entries and the newest
48 * LIMITS.entries in all, so a busy peer drops its own oldest entries first.
49 */
50export function appendEntries(list: readonly HighCommandEntry[], fresh: readonly NewEntry[], at: number): HighCommandEntry[] {
51 const newest = newestSeq(list)
52 const all = [...list, ...fresh.map((entry, index) => ({ ...entry, seq: newest + index + 1, at }))]
53 const held = new Map<string, number>()
54 const kept = all.reverse().filter(entry => {
55 const count = held.get(entry.peer) ?? 0
56 held.set(entry.peer, count + 1)
57 return count < LIMITS.peerEntries
58 })
59 const result = kept.slice(0, LIMITS.entries).reverse()
60 const last = result.at(-1)
61 if (last !== undefined) result[result.length - 1] = {
62 ...last, evictedTotal: (list.at(-1)?.evictedTotal ?? 0) + all.length - result.length,
63 }
64 return result
65}
66
67/**
68 * A record's own value under a peer name. Names come from senders, so `constructor` must not read
69 * Object.prototype; records are written through Map and Object.fromEntries, so `__proto__` is a plain key.
70 */
71function own<T>(record: Readonly<Record<string, T>>, peer: string): T | undefined {
72 return Object.hasOwn(record, peer) ? record[peer] : undefined
73}
74
75/** The peer's read mark: the highest inbound seq marked read, or 0 before any. */
76export function markOf(marks: Readonly<ReadMarks>, peer: string): number {
77 return own(marks, peer) ?? 0
78}
79
80/** String addresses can survive a hot reload; seenAt is their only saved timestamp. */
81function addressOf(peer: HighCommandPeer): HighCommandPeer['address'] {
82 return typeof peer.address === 'string' ? { value: peer.address, at: peer.seenAt } : peer.address
83}
84
85/**
86 * Applies peer reports and keeps the LIMITS.peers peers reported most recently. Deliveries can finish
87 * recording out of order, so a state or an address older than the stored one leaves it, and `seenAt` never
88 * moves back. Address observations retain their application order to break timestamp ties.
89 */
90export function applyReports(peers: Readonly<Peers>, reports: readonly PeerReport[], at: number): Peers {
91 const isCurrent = (stored: { at: number } | undefined): boolean => stored === undefined || stored.at <= at
92 const next = new Map(Object.entries(peers).map(([name, peer]) => [
93 name, typeof peer.address === 'string' ? { ...peer, address: addressOf(peer) } : peer,
94 ]))
95 let order = 0
96 for (const peer of next.values()) order = Math.max(order, peer.address?.order ?? 0)
97 for (const { peer, state, address, source } of reports) {
98 const known = next.get(peer)
99 next.set(peer, {
100 ...known,
101 seenAt: Math.max(known?.seenAt ?? at, at),
102 ...(state !== undefined && isCurrent(known?.state) ? { state: { word: state, at, source: source ?? 'peer notice' } } : {}),
103 ...(address !== undefined && isCurrent(known?.address) ? { address: { value: address, at, order: ++order } } : {}),
104 })
105 }
106 return keepPeers(next)
107}
108
109/** The LIMITS.peers peers reported most recently. */
110function keepPeers(peers: ReadonlyMap<string, HighCommandPeer>): Peers {
111 const all = [...peers]
112 return Object.fromEntries(all.length <= LIMITS.peers ? all : all.sort(([, a], [, b]) => b.seenAt - a.seenAt).slice(0, LIMITS.peers))
113}
114
115/**
116 * The key a send to a listed agent files under: its name, so the send joins that agent's messages to the main
117 * conversation, or its name and ID when the name is empty after peerKey, another listed agent has that name, or a
118 * peer of that name has an address (another session).
119 */
120function agentRecipient(agent: AgentInfo, agents: readonly AgentInfo[], peers: Readonly<Peers>): string {
121 if (agent.name === undefined) return ''
122 const name = peerKey(agent.name)
123 const isShared = name === '' || own(peers, name)?.address !== undefined ||
124 agents.some(other => other.id !== agent.id && peerKey(other.name ?? '') === name)
125 return isShared ? peerKey(`${agent.name} [${agent.id}]`) : name
126}
127
128/**
129 * The peer a send goes to: the peer whose newest address report matches `to`, else this session's agent whose
130 * id is `to` (agentRecipient), else the name `to` gives; undefined when that is no name.
131 * Equal address timestamps use observation order. Known names keep their brackets; an unknown recipient
132 * can carry one trailing listing reference.
133 */
134export function recipientOf(to: string, peers: Readonly<Peers>, agents: readonly AgentInfo[], entries: readonly HighCommandEntry[] = []): string | undefined {
135 let addressed: { name: string; at: number; order: number } | undefined
136 for (const [name, peer] of Object.entries(peers)) {
137 const address = addressOf(peer)
138 if (address?.value === to && (addressed === undefined || address.at > addressed.at ||
139 (address.at === addressed.at && (address.order ?? 0) > addressed.order))) {
140 addressed = { name, at: address.at, order: address.order ?? 0 }
141 }
142 }
143 if (addressed !== undefined) return addressed.name
144 const agent = agents.find(candidate => candidate.id === to)
145 let name = agent === undefined ? peerKey(to) : agentRecipient(agent, agents, peers)
146 const isKnown = Object.hasOwn(peers, name) || entries.some(entry => entry.peer === name) ||
147 agents.some(candidate => peerKey(candidate.name ?? '') === name)
148 if (agent === undefined && !isKnown) {
149 name = name.replace(RECIPIENT_REF, '')
150 }
151 return name === '' ? undefined : name
152}
153
154/** The observed send attempt, its reported outcome, and a bounded detailed refusal. */
155export function outboundEntry(peer: string, text: string, sent: SessionSendResult): NewEntry {
156 const body = sanitize(text)
157 return {
158 peer,
159 direction: 'out',
160 kind: 'message',
161 summary: summaryOf(undefined, body),
162 ...capBody(body),
163 ...(!sent.isDelivered ? { refusal: capBody(sanitize(sent.reason)) } : {}),
164 delivery: sent.isDelivered ? { isDelivered: true } : { isDelivered: false, reason: lineOf(sanitize(sent.reason)) },
165 }
166}
167
168/** An inbound entry newer than `mark`. Outbound entries and lane copies of the main conversation's sends are never new. */
169export function isNewer(entry: HighCommandEntry, mark: number): boolean {
170 return entry.direction === 'in' && entry.fromMain !== true && entry.seq > mark
171}
172
173/** The unread count of all rows. */
174export function unreadTotal(rows: readonly RosterRow[]): number {
175 return rows.reduce((sum, row) => sum + row.unread, 0)
176}
177
178/**
179 * One row per peer with entries: peers with unread entries first, then the newest activity first. While a peer
180 * has unread entries, its row shows the weakest trust level and any suspicious mark among them, so a newer
181 * message cannot hide a warning on one the person has not read; else it shows those of its newest inbound entry.
182 */
183export function rosterOf(entries: readonly HighCommandEntry[], peers: Readonly<Peers>, marks: Readonly<ReadMarks>): RosterRow[] {
184 const rows = new Map<string, RosterRow>()
185 for (const entry of entries) {
186 const row = rows.get(entry.peer) ?? { peer: entry.peer, unread: 0, last: entry, state: own(peers, entry.peer)?.state, isSuspicious: false }
187 if (entry.at > row.last.at || (entry.at === row.last.at && entry.seq > row.last.seq)) row.last = entry
188 if (entry.direction === 'in') {
189 const isUnread = isNewer(entry, markOf(marks, entry.peer))
190 // A peer's read entries come before its unread ones, so its first unread entry starts the fold. A lane copy of
191 // the main conversation's send is never unread and can follow unread entries; it leaves their fold alone.
192 if (isUnread || row.unread === 0) {
193 const isFolded = isUnread && row.unread > 0
194 row.trust = isFolded ? LEVELS.find(level => level === row.trust || level === entry.trust) : entry.trust
195 row.isSuspicious = (isFolded && row.isSuspicious) || entry.isSuspicious === true
196 }
197 if (isUnread) row.unread += 1
198 }
199 rows.set(entry.peer, row)
200 }
201 return [...rows.values()].sort((a, b) => Number(b.unread > 0) - Number(a.unread > 0) || b.last.at - a.last.at || b.last.seq - a.last.seq)
202}
203
204/** The unread count of all agent lanes. */
205export function lanesUnread(lanes: Readonly<Record<string, HighCommandLane>>): number {
206 return Object.values(lanes).reduce((sum, lane) => sum + unreadTotal(rosterOf(lane.entries, {}, lane.readThrough)), 0)
207}
208
209/** Per lane, the newest seq that a press of Hide saw, `seen`. A mark never moves back. */
210export function hideLanes(hidden: Readonly<Record<string, number>>, seen: ReadonlyMap<string, number>): Record<string, number> {
211 const next = new Map(Object.entries(hidden))
212 for (const [id, seq] of seen) next.set(id, Math.max(next.get(id) ?? 0, seq))
213 return Object.fromEntries(next)
214}
215
216/** The seq of the newest lane entry that can be unread (isNewer), or 0 without one. */
217export function newestUnreadableSeq(list: readonly HighCommandEntry[]): number {
218 return list.findLast(entry => isNewer(entry, 0))?.seq ?? 0
219}
220
221/**
222 * Whether a Hide saw every lane's newest entry that can be unread, also one that left its lane since: the lane's
223 * `inboundThrough` keeps its seq, so an eviction cannot bring back a Hide that the entry ended.
224 */
225export function lanesSeen(lanes: Readonly<Record<string, HighCommandLane>>, hidden: Readonly<Record<string, number>>): boolean {
226 return Object.entries(lanes).every(([id, lane]) => Math.max(lane.inboundThrough ?? 0, newestUnreadableSeq(lane.entries)) <= markOf(hidden, id))
227}
228
229/**
230 * Whether an append keeps the open thread: the person opened it after the append, or its peer
231 * has entries before and after it. So the thread on a peer the append drops closes, and so does a thread
232 * opened from an older view on a peer already gone, when that peer writes again.
233 */
234export function keepsThread(open: HighCommandThread, before: readonly HighCommandEntry[], after: readonly HighCommandEntry[]): boolean {
235 const has = (list: readonly HighCommandEntry[]): boolean => list.some(entry => entry.peer === open.peer)
236 return open.from >= newestSeq(after) || (has(before) && has(after))
237}
238
239/** The characters of `value` as JSON text: the measure that Claude Code holds a saved value to. */
240function jsonChars(value: unknown): number {
241 return JSON.stringify(value).length
242}
243
244/**
245 * The lane without its `drop` oldest entries, where `drop` is less than its entry count. Its newest entry stays and
246 * counts them as evicted, and the open thread closes as an append that dropped them would close it.
247 */
248function dropOldest(lane: HighCommandLane, drop: number): HighCommandLane {
249 if (drop <= 0) return lane
250 const kept = lane.entries.slice(drop)
251 const last = kept.at(-1)!
252 kept[kept.length - 1] = { ...last, evictedTotal: (last.evictedTotal ?? 0) + drop }
253 const open = lane.openThread
254 return { ...lane, entries: kept, openThread: open === null || keepsThread(open, lane.entries, kept) ? open : null }
255}
256
257/** Drops the lane's oldest entries while its entries pass LIMITS.laneChars; it keeps its newest entry. */
258function capLane(lane: HighCommandLane): HighCommandLane {
259 let size = jsonChars(lane.entries)
260 if (size <= LIMITS.laneChars) return lane
261 let drop = 0
262 while (size > LIMITS.laneChars && drop < lane.entries.length - 1) {
263 size -= jsonChars(lane.entries[drop]) + 1
264 drop += 1
265 }
266 const next = dropOldest(lane, drop)
267 // The evicted count on the newest entry adds a few characters.
268 return drop > 0 && jsonChars(next.entries) > LIMITS.laneChars ? capLane(next) : next
269}
270
271/**
272 * Fits the agent lanes in the space of one saved value. The lane `id`, the one that changed, first drops its own
273 * oldest entries past LIMITS.laneChars. Then, while all lanes pass LIMITS.lanesChars, the entries observed first
274 * drop from every lane. An entry drops only with the older entries of its lane, so it ranks by the latest observation
275 * among them. Each lane keeps its newest entry, so its seq numbers and read marks stay in step.
276 */
277export function fitLanes(lanes: Readonly<Record<string, HighCommandLane>>, id?: string): Record<string, HighCommandLane> {
278 const all = new Map(Object.entries(lanes))
279 const changed = id === undefined ? undefined : all.get(id)
280 if (changed !== undefined) all.set(id!, capLane(changed))
281 let over = jsonChars(Object.fromEntries(all)) - LIMITS.lanesChars
282 while (over > 0) {
283 const ranked: { lane: string; index: number; at: number; size: number }[] = []
284 for (const [name, lane] of all) {
285 let at = -Infinity
286 lane.entries.slice(0, -1).forEach((entry, index) => {
287 at = Math.max(at, entry.at)
288 ranked.push({ lane: name, index, at, size: jsonChars(entry) + 1 })
289 })
290 }
291 if (ranked.length === 0) break
292 ranked.sort((a, b) => a.at - b.at || a.index - b.index || (a.lane < b.lane ? -1 : a.lane > b.lane ? 1 : 0))
293 const drops = new Map<string, number>()
294 for (const { lane, index, size } of ranked) {
295 if (over <= 0) break
296 drops.set(lane, index + 1)
297 over -= size
298 }
299 for (const [name, drop] of drops) all.set(name, dropOldest(all.get(name)!, drop))
300 over = jsonChars(Object.fromEntries(all)) - LIMITS.lanesChars
301 }
302 return Object.fromEntries(all)
303}
304
305/** The thread of the open peer, or undefined when the pane draws the roster. */
306export function threadOf(entries: readonly HighCommandEntry[], rows: readonly RosterRow[], open: HighCommandThread | null): Thread | undefined {
307 const row = rows.find(candidate => candidate.peer === open?.peer)
308 if (open === null || row === undefined) return undefined
309 const all = entries.filter(entry => entry.peer === open.peer).sort((a, b) => b.at - a.at || b.seq - a.seq)
310 const groups: HighCommandEntry[][] = [[]]
311 let size = 0
312 for (const entry of all) {
313 // Each text the entry can draw, Send details open, serialized; 2,000 more for its lines, Buttons, and structure.
314 const cost = JSON.stringify([entry.body, entry.summary, entry.delivery?.isDelivered === false ? entry.delivery.reason : '', entry.refusal?.body, entry.core?.to, entry.core?.body, entry.core?.reason]).length + 2000
315 if (groups.at(-1)!.length >= LIMITS.threadEntries || size + cost > 60_000) {
316 groups.push([])
317 size = 0
318 }
319 groups.at(-1)!.push(entry)
320 size += cost
321 }
322 const pages = groups.length
323 const page = Math.max(0, Math.min(open.page ?? 0, pages - 1))
324 const shown = groups[page]!
325 const fresh = all.filter(entry => isNewer(entry, open.since)).length
326 const later = groups.slice(page + 1).reduce((sum, group) => sum + group.length, 0)
327 const moved = later > 0 ? Math.min(LIMITS.threadEntries - shown.length, later) : 0
328 return { row, since: open.since, shown, hidden: all.length - shown.length, fresh, page, pages, moved, identityPage: open.identityPage, reasonSeq: open.reasonSeq }
329}
330
331/**
332 * Marks `peer`, or every peer when none is given, read through its newest inbound entry in the window `entries`.
333 * A mark never moves back: `update` can apply an entries snapshot older than marks that another press already
334 * wrote. A mark below the window's oldest entry goes, so the marks of peers that left the window do not pile up:
335 * every entry of its peer, now or later, is newer, so it marked nothing. An older snapshot only drops less.
336 */
337export function markRead(marks: Readonly<ReadMarks>, entries: readonly HighCommandEntry[], peer?: string): ReadMarks {
338 const oldest = entries[0]?.seq ?? 0
339 const next = new Map(Object.entries(marks).filter(([, seq]) => seq >= oldest))
340 for (const entry of entries) {
341 if (entry.direction === 'in' && (peer === undefined || entry.peer === peer)) {
342 next.set(entry.peer, Math.max(next.get(entry.peer) ?? 0, entry.seq))
343 }
344 }
345 return Object.fromEntries(next)
346}
347
348/** The arrow and label for an inbound message or an observed send attempt. */
349export function labelOf(entry: HighCommandEntry): { arrow: '←' | '→'; word: string } {
350 if (entry.direction === 'out') return { arrow: '→', word: entry.delivery?.isDelivered === false ? 'send attempted (not delivered)' : 'send attempted' }
351 return { arrow: '←', word: entry.kind === 'result' ? 'finished' : entry.kind === 'failure' ? 'failed' : 'message' }
352}
353
354/** A settled core call proves only that call's queue outcome. */
355export function coreEvidence(trace: readonly TraceEntry<'session.send'>[]): HighCommandEntry['core'] {
356 const core = trace.find(item => item.plugin === 'engine' && item.tier === 'core' &&
357 (item.outcome === 'returned' || item.outcome === 'passed') && item.returned !== undefined)
358 if (core?.returned === undefined) return undefined
359 return {
360 to: sanitize(core.received.to).slice(0, LIMITS.bodyChars),
361 ...capBody(sanitize(core.received.text)),
362 isDelivered: core.returned.isDelivered,
363 ...(!core.returned.isDelivered ? { reason: lineOf(sanitize(core.returned.reason)) } : {}),
364 }
365}
366hooks/limits.ts 55 lines1/** Every bound of High Command, in one place. */
2export const LIMITS = {
3 /** Entries kept in all; the oldest drop first. */
4 entries: 200,
5 /** Entries kept for one peer; a busy peer drops its own oldest entries first. */
6 peerEntries: 50,
7 /** Characters of JSON text that one agent lane's entries keep; past it, that lane drops its own oldest entries first. */
8 laneChars: 500_000,
9 /**
10 * Characters of JSON text that all agent lanes keep together: their copy in `$.state` is one value, and Claude Code
11 * 2.1.296 refuses a value over 4,194,304 characters. Past it, the entries observed first drop; each lane keeps its newest.
12 */
13 lanesChars: 4_000_000,
14 /** Characters of JSON text in one saved value that Claude Code 2.1.296 accepts: a `$.state` value past it is refused. */
15 savedChars: 4_194_304,
16 /** Peers kept; the ones reported least recently drop first. */
17 peers: 100,
18 /**
19 * Conversations besides the current one whose inbox the process keeps in module memory, for a branch or a resume;
20 * the one used least recently drops first.
21 */
22 snapshots: 10,
23 /** Milliseconds between two reads of the session id after a switch, after the read at 0 ms, until the switch settles (watch). */
24 switchReadMs: 500,
25 /** Periods of switchReadMs after a switch in which the session id is read at most: 600 of 500 ms take 5 minutes. */
26 switchReads: 600,
27 /** Milliseconds that a slash command or a /config change waits at most for the copy that a settled switch writes (settleFirst). */
28 settleWaitMs: 2000,
29 /** Characters of a body kept; the transcript keeps the rest. */
30 bodyChars: 2000,
31 /** Characters of a summary line. */
32 summaryChars: 120,
33 /** Characters of a displayed peer label; identity keys keep the full normalized name. */
34 nameChars: 60,
35 /** Characters of a ListAgents state word. */
36 stateChars: 24,
37 /** Peer rows on one roster page. */
38 rosterRows: 50,
39 /** Agent lane Buttons on one lane page of the pane. */
40 laneButtons: 10,
41 /** Entries drawn in one thread. */
42 threadEntries: 20,
43 /**
44 * The engine's bounds on one drawing: characters of text, nodes (strings count), and depth. The engine
45 * refuses a drawing past any of them, so the band checks the drawing it wraps against them.
46 */
47 drawingText: 100_000,
48 drawingNodes: 20_000,
49 drawingDepth: 32,
50 /** Peers named in the band. */
51 bandPeers: 3,
52 /** Roster rows that get a digit hotkey. */
53 hotkeys: 9,
54} as const
55hooks/listing.ts 53 lines1import type { PeerReport } from './envelope'
2import { LIMITS } from './limits'
3import { peerKey, sanitize } from './text'
4
5/**
6 * The start of a listing row, ` name [ref]`, where the engine's `·` fields begin. The name runs to the last
7 * ` [ref]` that a `·` follows, so a session name that holds ` [ref] · ` stays whole and cannot place a field.
8 * The fields after it are split on `·`, not matched by a repeated group, so a hostile row cannot make the
9 * match backtrack across its fields.
10 */
11const HEAD = /^\s+(\S.*) \[[0-9a-z]+\](?=\s+·)/i
12/** A state word as the engine writes one: a letter, then letters, spaces, and hyphens. */
13const STATE_WORD = new RegExp(`^[a-z][a-z -]{0,${LIMITS.stateChars - 1}}$`, 'i')
14
15/** Peer states from a ListAgents listing, and how many lines looked like rows. */
16export function parseListing(listing: string): { reports: PeerReport[]; rowCount: number } {
17 const rows = sanitize(listing)
18 .split('\n')
19 .filter(line => /^\s+\S/.test(line))
20 const reports: PeerReport[] = []
21 for (const row of rows) {
22 const head = HEAD.exec(row)
23 if (head === null) continue
24 const peer = peerKey(head[1] ?? '')
25 // The text before the first `·` is the space after the ref; the fields keep their places, so an empty one stays empty.
26 const state = row.slice(head[0].length).split('·')[2]?.trim()
27 if (peer !== '' && state !== undefined && STATE_WORD.test(state)) reports.push({ peer, state })
28 }
29 return { reports, rowCount: rows.length }
30}
31
32/** Structured rows take precedence; duplicate names cannot establish one peer's state. */
33export function parseStructuredListing(result: unknown): { reports: PeerReport[]; rowCount: number } | undefined {
34 if (typeof result !== 'object' || result === null || !('sections' in result) || !Array.isArray(result.sections)) return undefined
35 const states = new Map<string, string | undefined>()
36 let rowCount = 0
37 for (const section of result.sections) {
38 if (typeof section !== 'object' || section === null || !Array.isArray(section.rows)) continue
39 for (const row of section.rows) {
40 rowCount++
41 if (typeof row !== 'object' || row === null || typeof row.name !== 'string') continue
42 const peer = peerKey(row.name)
43 if (peer === '') continue
44 const state = typeof row.status === 'string' ? sanitize(row.status).trim() : ''
45 states.set(peer, states.has(peer) || !STATE_WORD.test(state) ? undefined : state)
46 }
47 }
48 return {
49 reports: [...states].flatMap(([peer, state]) => state === undefined ? [] : [{ peer, state, source: 'structured listing' }]),
50 rowCount,
51 }
52}
53hooks/summary.ts 55 lines1import type { HighCommandAgent, HighCommandCapture, HighCommandLane } from '../types'
2import { labelOf, rosterOf, unreadTotal, type RosterRow } from './inbox'
3import { captureLabel, clockLabel, count, peerLabel, peerLabels, stateLabel, trustLabel } from './text'
4
5/** Names remain literal, including backticks and link-shaped text. */
6function literal(name: string): string {
7 const longest = Math.max(0, ...Array.from(name.matchAll(/`+/g), run => run[0].length))
8 const fence = '`'.repeat(longest + 1)
9 const pad = name.startsWith('`') || name.endsWith('`') ? ' ' : ''
10 return `${fence}${pad}${name}${pad}${fence}`
11}
12
13type SummaryContext = { evicted?: number; capture?: HighCommandCapture | null; agents?: readonly HighCommandAgent[]; lanes?: Record<string, HighCommandLane> }
14
15/** Counts cover retained messages only. Message bodies never enter command output. */
16export function summaryText(rows: readonly RosterRow[], entryCount: number, now: number, context: SummaryContext = {}): string {
17 const labels = peerLabels(rows.map(row => row.peer))
18 const useList = Array.from(labels.values()).some(name => {
19 let oddBackslashes = false
20 for (const char of name) {
21 if (char === '|' && oddBackslashes) return true
22 oddBackslashes = char === '\\' && !oddBackslashes
23 }
24 return false
25 })
26 const lines = rows.map(row => {
27 const label = trustLabel(row.trust)
28 const name = literal(labels.get(row.peer)!)
29 const peer = `${name}${label === undefined ? '' : ` (${label})`}`
30 const { arrow, word } = labelOf(row.last)
31 const fields = [String(row.unread), clockLabel(row.last.at, now), stateLabel(row.state, now) ?? '—', `${arrow} ${word}`]
32 if (useList) return `- ${peer}: ${fields[0]} new; last ${fields[1]}; state ${fields[2]}; latest ${fields[3]}`
33 const escaped = peer.replace(/\|/g, '\\|')
34 return `| ${escaped} | ${fields.join(' | ')} |`
35 })
36 const header = rows.length === 0 ? 'No messages from teammates or other sessions in this capture window.' :
37 `${unreadTotal(rows)} unread · ${count(rows.length, 'peer')} · ${count(entryCount, 'retained message')}`
38 const agents = context.agents ?? []
39 const lanes = Object.entries(context.lanes ?? {})
40 return [
41 ...(context.capture ? [captureLabel(context.capture, now)] : []),
42 header,
43 'Order: observation time; read marks and retention use recording sequence.',
44 ...((context.evicted ?? 0) > 0 ? [`History trimmed: ${count(context.evicted!, 'message')} permanently evicted; totals cover retained messages.`] : []),
45 ...(rows.length === 0 ? [] : ['', ...(useList ? [] : ['| Peer | New | Last | State | Latest |', '| --- | --- | --- | --- | --- |']), ...lines]),
46 ...(lanes.length === 0 ? [] : ['', 'Agent observations (separate counts; split-pane traffic unavailable):',
47 ...lanes.map(([id, lane]) => `- ${literal(peerLabel(id))}: ${unreadTotal(rosterOf(lane.entries, lane.peers, lane.readThrough))} unread; ${count(lane.entries.length, 'retained message')}; ${lane.entries.at(-1)?.evictedTotal ?? 0} permanently evicted`),
48 ]),
49 ...(agents.length === 0 ? [] : ['', 'Local agents (separate from peer names; split-pane liveness is unconfirmed):',
50 ...agents.slice(0, 100).map(agent => `- ${literal(peerLabel(agent.name ?? agent.id))} (${literal(peerLabel(agent.id))}): ${agent.status}; ${agent.source} at ${clockLabel(agent.at, now)}${agent.lastEvent ? `; lifecycle observation: ${agent.lastEvent.word} at ${clockLabel(agent.lastEvent.at, now)}` : ''}`),
51 ...(agents.length > 100 ? [`${agents.length - 100} more local agents; open the pane to page through them.`] : []),
52 ]),
53 ].join('\n')
54}
55hooks/text.ts 371 lines1import type { HighCommandCapture, HighCommandState, HighCommandTrust } from '../types'
2import { LIMITS } from './limits'
3
4const CONTROL = /[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g
5const FORMAT = /\p{Cf}/gu
6/**
7 * The invisible characters that the suspicious-text check reads past: format characters (category Cf), the
8 * combining grapheme joiner U+034F, and the variation selectors U+FE00 to U+FE0F and U+E0100 to U+E01EF.
9 */
10const INVISIBLE = /[\p{Cf}\u034F\uFE00-\uFE0F\u{E0100}-\u{E01EF}]/gu
11const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
12
13/**
14 * The suspicious-text list, in order: an instruction to ignore earlier instructions, to
15 * change the permission mode, to run a download in a shell (piped, or through `$(...)` or `<(...)`), or to
16 * read a credential file. Every repeat is bounded or over distinct words, so a match is linear in the text.
17 * `hasBase64Block` adds the last item of the list, a long base64 block.
18 */
19const SUSPICIOUS = [
20 /\b(?:ignore|disregard|forget)\s+(?:(?:all|any|the|your|of)\s+)*(?:(?:previous|prior|earlier|above)\s+(?:instructions?|prompts?|rules?)\b|(?:instructions?|prompts?|rules?)\s+above\b)/i,
21 /\b(?:bypassPermissions|dangerously-skip-permissions)\b|\b(?:change|switch|set)\b[^.\n]{0,30}\bpermission mode\b/i,
22 /\b(?:curl|wget)\b[^|\n]{0,200}\|\s*(?:sudo\s+)?(?:ba|z|da|k)?sh\b|\b(?:(?:ba|z|da|k)?sh|eval|source)\s+(?:-c\s+)?["']?(?:\$\(|<\()\s*(?:curl|wget)\b/i,
23 /\b(?:cat|read|print|send|upload|paste|share|copy|dump)\b[^\n]{0,60}(?:\.ssh\/|\bid_(?:rsa|ecdsa|ed25519)\b|\.aws\/credentials|\.netrc\b|\.git-credentials\b|\.env\b)/i,
24]
25/** Characters of one unbroken base64 run that make a long base64 block. */
26const BASE64_RUN = 200
27
28/** Removes control characters, keeping tab and line feed, so no terminal sequence reaches a drawing. */
29export function sanitize(text: string): string {
30 return text.replace(CONTROL, '')
31}
32
33/** Replaces each run of white space with one space and trims. */
34function oneLine(text: string): string {
35 return text.replace(/\s+/g, ' ').trim()
36}
37
38/** The first line that holds a non-space character, as one line; '' when there is none. */
39export function firstLine(text: string): string {
40 const line = text.split('\n').find(part => part.trim() !== '')
41 return line === undefined ? '' : oneLine(line)
42}
43
44/** Keeps at most `max` UTF-16 units of a longer text, never splitting a surrogate pair. */
45function cut(text: string, max: number): string {
46 if (text.length <= max) return text
47 const kept = text.slice(0, max)
48 const last = kept.charCodeAt(max - 1)
49 return last >= 0xd800 && last <= 0xdbff ? kept.slice(0, -1) : kept
50}
51
52/** The text when it has at most `max` characters, else its start and '…'. */
53function clip(text: string, max: number): string {
54 return text.length <= max ? text : `${cut(text, max - 1)}…`
55}
56
57/** The text as one line of at most LIMITS.summaryChars characters. */
58export function lineOf(text: string): string {
59 return clip(oneLine(text), LIMITS.summaryChars)
60}
61
62/** One summary line: the preferred text, else the first line of the body, else '(empty message)'. */
63export function summaryOf(preferred: string | undefined, body: string): string {
64 return lineOf(preferred ?? '') || lineOf(firstLine(body)) || '(empty message)'
65}
66
67/** The body as stored, and its length before the cut. */
68export function capBody(text: string): { body: string; fullChars: number } {
69 return { body: cut(text, LIMITS.bodyChars), fullChars: text.length }
70}
71
72function twoDigits(value: number): string {
73 return String(value).padStart(2, '0')
74}
75
76/** `HH:MM` in local time. */
77export function timeLabel(at: number): string {
78 const time = new Date(at)
79 return `${twoDigits(time.getHours())}:${twoDigits(time.getMinutes())}`
80}
81
82/** The local day, as in `Oct 4`. */
83export function dayLabel(at: number): string {
84 const time = new Date(at)
85 return `${MONTHS[time.getMonth()]} ${time.getDate()}`
86}
87
88/** Whether two times fall on one local day. */
89export function isSameDay(at: number, other: number): boolean {
90 const one = new Date(at)
91 const two = new Date(other)
92 return one.getFullYear() === two.getFullYear() && one.getMonth() === two.getMonth() && one.getDate() === two.getDate()
93}
94
95/** `HH:MM` on the local day of `now`, else `Mon D HH:MM`. */
96export function clockLabel(at: number, now: number): string {
97 return isSameDay(at, now) ? timeLabel(at) : `${dayLabel(at)} ${timeLabel(at)}`
98}
99
100/** A state with the clock time it was reported, as in `idle (12:04)`; undefined without a state. */
101export function stateLabel(state: HighCommandState | undefined, now: number): string | undefined {
102 return state === undefined ? undefined : `${state.word} (${clockLabel(state.at, now)}${state.source ? `; ${state.source}; last reported` : ''})`
103}
104
105/**
106 * A state as the roster shows it, as in `idle at 12:04`, whole: the roster row cuts it only when the row is full.
107 * Undefined without a state. The thread shows its source (threadState).
108 */
109export function rosterState(state: HighCommandState | undefined, now: number): string | undefined {
110 return state === undefined ? undefined : `${state.word} at ${clockLabel(state.at, now)}`
111}
112
113/** A state as a thread shows it, as in `State idle at 12:04 · peer notice · last reported`; the source only when known. */
114export function threadState(state: HighCommandState, now: number): string {
115 return `State ${state.word} at ${clockLabel(state.at, now)}${state.source ? ` · ${state.source} · last reported` : ''}`
116}
117
118/**
119 * Whether the text holds BASE64_RUN or more base64 characters in a row that mix upper case, lower case,
120 * and digits, as encoded data does; a run of one letter or of hex digits is not a block. One pass.
121 */
122function hasBase64Block(text: string): boolean {
123 let run = 0
124 let kinds = 0
125 for (let index = 0; index < text.length; index += 1) {
126 const code = text.charCodeAt(index)
127 const kind = code >= 65 && code <= 90 ? 1 : code >= 97 && code <= 122 ? 2 : code >= 48 && code <= 57 ? 4 : code === 43 || code === 47 ? 8 : 0
128 run = kind === 0 ? 0 : run + 1
129 kinds = kind === 0 ? 0 : kinds | kind
130 if (run >= BASE64_RUN && (kinds & 7) === 7) return true
131 }
132 return false
133}
134
135/**
136 * Whether the text matches the suspicious-text list; the mark it gives is for display only. The list is tested on
137 * two forms of the text: each INVISIBLE character read as a space, as between two words, and each one removed,
138 * as inside a word. A match in either form marks the text. A space matches every class that an INVISIBLE
139 * character matches in the list, so the first form keeps each match of the text as it came.
140 */
141export function isSuspicious(text: string): boolean {
142 return [text.replace(INVISIBLE, ' '), text.replace(INVISIBLE, '')].some(
143 form => SUSPICIOUS.some(pattern => pattern.test(form)) || hasBase64Block(form),
144 )
145}
146
147/**
148 * How the roster, the thread, and `/highcommand` name a trust level, as in `verified sender`; no label for a peer
149 * that only received sends.
150 */
151export function trustLabel(trust: HighCommandTrust | undefined): string | undefined {
152 return trust === undefined ? undefined : `${trust} sender`
153}
154
155/** A count and its noun: `1 peer`, `2 peers`. */
156export function count(n: number, noun: string): string {
157 return `${n} ${noun}${n === 1 ? '' : 's'}`
158}
159
160/**
161 * The unread counts that the band and the status line show, as in `3 unread (retained) · 2 unread in agent lanes`:
162 * the main inbox's count, and the agent lanes' count when it is above zero; '' when both are zero.
163 */
164export function unreadText(main: number, lanes = 0): string {
165 return [main > 0 ? `${main} unread (retained)` : undefined, lanes > 0 ? `${lanes} unread in agent lanes` : undefined]
166 .filter(part => part !== undefined).join(' · ')
167}
168
169/** The dim hint at the end of the band's row: the keys that give the band the keyboard. */
170export const BAND_KEY_HINT = 'ctrl+x tab to choose'
171
172/** The dim hint at the end of the pane's location row: how to give the pane the keys, and how to give them back. */
173export const PANE_KEY_HINT = 'ctrl+x tab or click for keys · esc to prompt'
174
175/**
176 * Code points a terminal can draw two cells wide, in broad ranges: Hangul, CJK, full-width forms, the emoji of the
177 * symbol blocks, and every code point past U+FFFF.
178 */
179const WIDE: readonly (readonly [number, number])[] = [
180 [0x1100, 0x115f], [0x231a, 0x2b55], [0x2e80, 0xa4cf], [0xa960, 0xa97f], [0xac00, 0xd7a3],
181 [0xf900, 0xfaff], [0xfe10, 0xfe6f], [0xff00, 0xff60], [0xffe0, 0xffe6], [0x10000, 0x10ffff],
182]
183
184/**
185 * The terminal cells one line of text takes, counted high: a code point in WIDE counts two, any other one, so a
186 * row that fits by this count fits on the screen.
187 */
188export function cellWidth(text: string): number {
189 let cells = 0
190 for (const char of text) {
191 const code = char.codePointAt(0)!
192 cells += WIDE.some(([first, last]) => code >= first && code <= last) ? 2 : 1
193 }
194 return cells
195}
196
197/**
198 * A full peer identity: one line without control or format characters
199 * (bidi controls, zero-width marks). Bracketed text belongs to the name.
200 */
201export function peerKey(name: string): string {
202 return oneLine(sanitize(name).replace(FORMAT, ''))
203}
204
205/** The 32-bit FNV-1a hash of a text's UTF-16 units, as 8 hexadecimal digits. */
206function fnv1a(text: string): string {
207 let hash = 2166136261
208 for (let index = 0; index < text.length; index++) hash = Math.imul(hash ^ text.charCodeAt(index), 16777619)
209 return (hash >>> 0).toString(16).padStart(8, '0')
210}
211
212/** A display label for a normalized peer identity, clipped without changing its state key. */
213export function peerLabel(peer: string): string {
214 return peer.length <= LIMITS.nameChars ? peer : `${clip(peer, LIMITS.nameChars - 11)} [${fnv1a(peer)}]`
215}
216
217/**
218 * The text's start and end around `…`, in at most `max` cells (cellWidth): the start takes the odd cell. Look-alike
219 * names mostly differ at their end, so this keeps both the shared start and the part that tells them apart.
220 */
221function clipMiddle(text: string, max: number): string {
222 const chars = [...text]
223 let head = ''
224 let headCells = 0
225 for (const char of chars) {
226 if (headCells + cellWidth(char) > Math.ceil((max - 1) / 2)) break
227 head += char
228 headCells += cellWidth(char)
229 }
230 let tail = ''
231 let tailCells = 0
232 for (const char of chars.reverse()) {
233 if (tailCells + cellWidth(char) > max - 1 - headCells) break
234 tail = char + tail
235 tailCells += cellWidth(char)
236 }
237 return `${head}…${tail}`
238}
239
240/** The text whole when it takes at most `max` cells (cellWidth), else its start and end around `…` (clipMiddle). */
241function cutCells(text: string, max: number): string {
242 return cellWidth(text) <= max ? text : clipMiddle(text, max)
243}
244
245/** Hexadecimal digits of the code that tells look-alike cut labels apart. */
246const CODE_DIGITS = 4
247
248/**
249 * A peer's label in `cells` cells, at one of two steps, each from the name alone. Step 0: the name, or its start and end
250 * when it is wider. Step 1: a shorter cut and the first CODE_DIGITS digits of the name's FNV-1a hash, as in
251 * `rele…west [3f9a]`.
252 */
253function cellLabel(peer: string, cells: number, step: number): string {
254 return step === 0 ? cutCells(peer, cells) : `${cutCells(peer, cells - CODE_DIGITS - 3)} [${fnv1a(peer).slice(0, CODE_DIGITS)}]`
255}
256
257/**
258 * Labels in `cells` cells, at least 12, for the fixed roster columns. A peer shows its step 0 label (cellLabel) while
259 * no other peer shows the same text, else its step 1 label, so a label passes to no other peer. A step 0 label that
260 * reads as another peer's step 1 label also moves, so a name cannot copy a coded label. Peers whose step 1 labels still
261 * match, which takes equal cuts and an equal code, are numbered in name order, apart from every other label.
262 */
263function cellLabels(peers: readonly string[], cells: number): Map<string, string> {
264 const steps = new Map(peers.map(peer => [peer, 0]))
265 const labelOf = (peer: string) => cellLabel(peer, cells, steps.get(peer)!)
266 for (let isMoved = true; isMoved;) {
267 isMoved = false
268 const counts = new Map<string, number>()
269 for (const peer of peers) counts.set(labelOf(peer), (counts.get(labelOf(peer)) ?? 0) + 1)
270 for (const peer of peers) {
271 if (steps.get(peer) === 0 && counts.get(labelOf(peer))! > 1) {
272 steps.set(peer, 1)
273 isMoved = true
274 }
275 }
276 }
277 const groups = new Map<string, string[]>()
278 for (const peer of [...peers].sort()) groups.set(labelOf(peer), [...(groups.get(labelOf(peer)) ?? []), peer])
279 const result = new Map<string, string>()
280 const reserved = new Set(groups.keys())
281 for (const [label, group] of groups) {
282 if (group.length === 1) {
283 result.set(group[0]!, label)
284 continue
285 }
286 let index = 0
287 for (const peer of group) {
288 let resolved: string
289 do {
290 index += 1
291 resolved = `${cutCells(peer, cells - 3 - String(index).length)} [${index}]`
292 } while (reserved.has(resolved))
293 reserved.add(resolved)
294 result.set(peer, resolved)
295 }
296 }
297 return new Map(peers.map(peer => [peer, result.get(peer)!]))
298}
299
300/**
301 * Resolves even hash collisions across the current retained roster. With `cells`, labels fit that many cells
302 * (cellLabels).
303 */
304export function peerLabels(peers: readonly string[], cells?: number): Map<string, string> {
305 if (cells !== undefined) return cellLabels([...new Set(peers)], cells)
306 const groups = new Map<string, string[]>()
307 for (const peer of new Set(peers)) {
308 const label = peerLabel(peer)
309 groups.set(label, [...(groups.get(label) ?? []), peer])
310 }
311 const result = new Map<string, string>()
312 const reserved = new Set(groups.keys())
313 for (const [label, group] of groups) {
314 group.sort()
315 let index = 0
316 for (const peer of group) {
317 let resolved = label
318 if (group.length > 1) {
319 do { resolved = `${clip(label, 50)} [${++index}]` } while (reserved.has(resolved))
320 reserved.add(resolved)
321 }
322 result.set(peer, resolved)
323 }
324 }
325 return result
326}
327
328/**
329 * Button keys for peer rows that stay with the peer when the roster order changes: `peer:` and the FNV-1a hash of the
330 * full identity, with `-2`, `-3`, ... for the later names, in name order, that share a hash.
331 */
332export function peerKeys(peers: readonly string[]): Map<string, string> {
333 const keys = new Map<string, string>()
334 const taken = new Map<string, number>()
335 for (const peer of [...new Set(peers)].sort()) {
336 const hash = fnv1a(peer)
337 const count = (taken.get(hash) ?? 0) + 1
338 taken.set(hash, count)
339 keys.set(peer, count === 1 ? `peer:${hash}` : `peer:${hash}-${count}`)
340 }
341 return keys
342}
343
344/** How a branch's capture window names the messages it took from the parent: `Branched 13:04 · 12 messages from the parent conversation`. */
345export function branchLabel(branch: { at: number; messages: number }, now: number): string {
346 return `Branched ${clockLabel(branch.at, now)} · ${count(branch.messages, 'message')} from the parent conversation`
347}
348
349/**
350 * The conversations a branch's capture window covers: its parent, and one earlier conversation for each /branch step
351 * before that, as in `this conversation, the one it branched from, and 1 earlier conversation`.
352 */
353function branchScope(depth: number): string {
354 return depth <= 1 ? 'this conversation and the one it branched from' : `this conversation, the one it branched from, and ${count(depth - 1, 'earlier conversation')}`
355}
356
357/** A conversation-local marker, preserved across module reloads; a branch's covers the conversations it branched from too. */
358export function captureLabel(capture: HighCommandCapture, now: number): string {
359 const scope = capture.branch === undefined ? 'current conversation only.' : `${branchScope(capture.branch.depth)}. ${branchLabel(capture.branch, now)}.`
360 return `Capture window: ${clockLabel(capture.at, now)} · ${scope} ${capture.reset ? 'Previous High Command history was not restored.' : 'Earlier history is not included.'}`
361}
362
363/** Fixed-width identity pages never separate the halves of a surrogate pair. */
364export function identityPart(peer: string, page: number): string {
365 const boundary = (at: number): number => {
366 const char = peer.charCodeAt(at)
367 return char >= 0xdc00 && char <= 0xdfff ? at - 1 : at
368 }
369 return peer.slice(boundary(page * 1000), boundary((page + 1) * 1000))
370}
371hooks/views.tsx 819 lines1import type { BoxProps, ButtonProps, ElementConstructor, RenderElement, TextProps } from 'claude-code'
2
3import type { HighCommandAgent, HighCommandCapture, HighCommandEntry } from '../types'
4import { isNewer, labelOf, unreadTotal, type RosterRow, type Thread } from './inbox'
5import { LIMITS } from './limits'
6import {
7 BAND_KEY_HINT,
8 PANE_KEY_HINT,
9 branchLabel,
10 cellWidth,
11 clockLabel,
12 count,
13 dayLabel,
14 firstLine,
15 identityPart,
16 isSameDay,
17 lineOf,
18 peerKeys,
19 peerLabel,
20 peerLabels,
21 rosterState,
22 threadState,
23 timeLabel,
24 trustLabel,
25 unreadText,
26} from './text'
27
28/** The elements High Command draws with; every surface's table has them. */
29type HighCommandElements = {
30 Box: ElementConstructor<BoxProps>
31 Text: ElementConstructor<TextProps>
32 Button: ElementConstructor<ButtonProps>
33}
34
35/** What the pane draws: a roster (the main inbox or an agent lane), a thread, or a peer's identity. */
36type PaneModel = {
37 rows: RosterRow[]; now: number; thread: Thread | undefined
38 evicted?: number; capture?: HighCommandCapture | null
39 rosterPage?: number; laneId?: string; laneIds?: string[]; lanePage?: number; agents?: HighCommandAgent[]
40 /** Each agent lane's unread count, by agent id. */
41 laneUnread?: ReadonlyMap<string, number>
42 /** The body's cells across (Pane.bodyColumns). Without it, roster rows take two lines and no key hint shows. */
43 columns?: number
44 /** Whether the Agent status block is open. */
45 statusOpen?: boolean
46}
47
48/**
49 * Each action returns its work, and each Button's onPress returns the action's promise: a press stays the
50 * person's own input only while that work runs.
51 */
52export type PaneActions = {
53 openThread: (peer: string) => Promise<void>
54 /** Back from a thread to the roster page that draws its peer. */
55 back: () => Promise<void>
56 markRead: (peer: string) => Promise<void>
57 readAll: () => Promise<void>
58 page: (page: number) => Promise<void>
59 /** Opens the Identity view at a part, or closes it (undefined). */
60 identity: (page: number | undefined) => Promise<void>
61 reason: (seq: number) => Promise<void>
62 /** Shows the main inbox ('') or an agent's lane. */
63 lane: (id: string) => Promise<void>
64 /** Back from an agent lane's roster to the main inbox. */
65 leaveLane: () => Promise<void>
66 lanePage: (page: number) => Promise<void>
67 rosterPage: (page: number) => Promise<void>
68 /** Opens or closes the Agent status block. */
69 agentStatus: () => Promise<void>
70}
71
72export type BandActions = { open: () => Promise<void>; readAll: () => Promise<void>; hide: () => Promise<void> }
73
74const ORDER_NOTE = 'Order: observation time. Counts cover retained messages.'
75const LANE_NOTE = 'Split-pane traffic is not shown. Sent and received messages are observed separately.'
76const LIVENESS_NOTE = 'Roster snapshots do not confirm liveness.'
77const SEND_NOTE = 'Sends show observed text; a reported result is not a receipt.'
78const CORE_NOTE = 'Core evidence covers only the latest traced call, never reading or every send.'
79const NOT_DELIVERED = '(not delivered)'
80
81/** Body cells from which the roster draws fixed columns; below it, each roster row takes two lines. */
82const COLUMNS_FROM = 90
83/**
84 * The fixed roster columns: gutter and peer, New, Time, Sender, and Last state at its least; Last message takes the
85 * rest. Last state widens to the longest state on the page while Last message keeps MESSAGE_CELLS.
86 */
87const CELLS = { peer: 19, fresh: 3, time: 6, sender: 10, state: 13 } as const
88/**
89 * Cells Last message keeps at least when Last state widens: both warning marks, which start it, and the cell that a
90 * cut at its end draws as `…`, so no cut reaches a mark.
91 */
92const MESSAGE_CELLS = cellWidth(`suspicious ${NOT_DELIVERED}`) + 1
93/** Cells the latest message keeps at least beside the marks on line 2 of a two-line row; with fewer, it takes line 3. */
94const PREVIEW_CELLS = 20
95/** Cells of a peer label in the fixed columns. */
96const LABEL_CELLS = 16
97/** The cells of `1: ` that a digit hotkey draws before a plain Button's label, and the gutter of rows without one. */
98const GUTTER = 3
99
100/** The defined parts, joined with ` · `. */
101function joined(parts: readonly (string | undefined)[]): string {
102 return parts.filter(part => part !== undefined).join(' · ')
103}
104
105/** The kept parts, each one or more inline nodes, with ` · ` between two. */
106function dotted(parts: readonly (readonly (RenderElement | string)[] | false | undefined)[]): (RenderElement | string)[] {
107 return parts.filter(part => part !== false && part !== undefined).flatMap((part, index) => (index === 0 ? [...part] : [' · ', ...part]))
108}
109
110/** The cells a plain Button with a hotkey draws: `h: label`. */
111function plainCells(label: string): number {
112 return GUTTER + cellWidth(label)
113}
114
115/** The cells a Button with chrome draws on the terminal: `[ label ]`. */
116function chromeCells(label: string): number {
117 return 4 + cellWidth(label)
118}
119
120/**
121 * The engine refuses a drawing past 100,000 characters serialized and draws its own in place of the pane, so a roster
122 * view keeps to about 90,000. Its peer rows take at most ROWS_BUDGET, the agents of its lane page at most LANES_BUDGET,
123 * and the rest of the view less than the 8,000 left. A thread page keeps its own budget (threadOf). A page ends before
124 * the row that would pass its budget and says how many rows moved to the next page.
125 */
126const ROWS_BUDGET = 70_000
127const LANES_BUDGET = 12_000
128const MOVED_NOTE = 'moved to the next page to keep the pane within its drawing limit.'
129
130/** Characters of a tree serialized as the band's bounds check counts them: each handler as 256. */
131function serialized(tree: unknown): number {
132 return JSON.stringify(tree, (_key, value: unknown) => typeof value === 'function' ? 'handler'.padEnd(256, '_') : value).length
133}
134
135/** A Box's or a Text's children as a drawing holds them: one flat list, without the booleans and empty values. */
136function flatChildren(node: unknown): unknown[] {
137 return Array.isArray(node) ? node.flatMap(flatChildren) : node === false || node === true || node === null || node === undefined ? [] : [node]
138}
139
140/**
141 * Elements as a drawing serializes them, each Button with a press handle of the longest number in place of its
142 * handler: the budgets measure rows with these, outside any render, and so in every place that pages.
143 */
144const MEASURE: HighCommandElements = {
145 Box: ({ children, ...props }) => ({ type: 'Box', props, children: flatChildren(children) }) as unknown as RenderElement,
146 Text: ({ children, ...props }) => ({ type: 'Text', props, children: flatChildren(children) }) as unknown as RenderElement,
147 Button: ({ onPress: _onPress, ...props }) => ({ type: 'Button', props, press: { plugin: 'high-command', handle: Number.MAX_SAFE_INTEGER } }) as unknown as RenderElement,
148}
149
150/** The first item of each page: at most `size` items, whose costs stay within `budget`; a page holds at least one. */
151function pageStarts(costs: readonly number[], size: number, budget: number): number[] {
152 const starts = [0]
153 let used = 0
154 costs.forEach((cost, index) => {
155 const start = starts.at(-1)!
156 if (index > start && (index - start >= size || used + cost > budget)) {
157 starts.push(index)
158 used = 0
159 }
160 used += cost
161 })
162 return starts
163}
164
165/**
166 * The page shown of `length` items cut at `starts`, when `page` was asked: within the pages there are, with the
167 * bounds of its items and how many of them moved on, up to `size`, because the page ended at its budget.
168 */
169function pageIn(starts: readonly number[], length: number, size: number, page: number | undefined): { page: number; pages: number; from: number; to: number; moved: number } {
170 const shown = Math.max(0, Math.min(page ?? 0, starts.length - 1))
171 const from = starts[shown]!
172 const to = starts[shown + 1] ?? length
173 return { page: shown, pages: starts.length, from, to, moved: to < length ? Math.min(size - (to - from), length - to) : 0 }
174}
175
176/** The dim note under a page that ended at its budget: how many `noun`s moved to the next page. */
177function movedLine(Text: HighCommandElements['Text'], moved: number, noun: string): RenderElement | false {
178 return moved > 0 && <Text dimColor wrap="wrap">{`${count(moved, noun)} ${MOVED_NOTE}`}</Text>
179}
180
181/**
182 * The first row of each roster page: at most LIMITS.rosterRows rows, within ROWS_BUDGET. A row costs the most it can
183 * draw in either layout, at any place on the page and at any time, so the pages stay the same at every width.
184 */
185function rosterStarts(rows: readonly RosterRow[]): number[] {
186 const peers = rows.map(row => row.peer)
187 const [narrow, wide, keys] = [peerLabels(peers), peerLabels(peers, LABEL_CELLS), peerKeys(peers)]
188 const open = async () => {}
189 const costs = rows.map(row => {
190 // A time of another day draws the longest clock labels; a row past the ninth draws its gutter Box.
191 const args = { row, index: LIMITS.hotkeys, key: keys.get(row.peer)!, now: 0, open }
192 return Math.max(
193 serialized(twoLineRow(MEASURE, { ...args, label: narrow.get(row.peer)! }, undefined)),
194 serialized(twoLineRow(MEASURE, { ...args, label: narrow.get(row.peer)! }, COLUMNS_FROM - 1)),
195 serialized(columnsRow(MEASURE, { ...args, label: wide.get(row.peer)! }, CELLS.state)),
196 )
197 })
198 return pageStarts(costs, LIMITS.rosterRows, ROWS_BUDGET)
199}
200
201/** The roster page shown when `page` was asked. */
202function rosterPageIn(rows: readonly RosterRow[], page: number | undefined) {
203 return pageIn(rosterStarts(rows), rows.length, LIMITS.rosterRows, page)
204}
205
206/** The roster page that draws `peer`'s row; undefined when the roster has no row for it. */
207export function rosterPageOf(rows: readonly RosterRow[], peer: string): number | undefined {
208 const index = rows.findIndex(row => row.peer === peer)
209 return index < 0 ? undefined : rosterStarts(rows).findLastIndex(start => start <= index)
210}
211
212/** Every agent the pane can show a lane for, in id order: each local agent and each agent with a lane. */
213export function laneIdsOf(laneIds: readonly string[], agents: readonly HighCommandAgent[]): string[] {
214 return [...new Set([...laneIds, ...agents.map(agent => agent.id)])].sort()
215}
216
217/**
218 * The lane page shown when `lanePage` was asked: at most LIMITS.laneButtons agents, within LANES_BUDGET. An agent costs
219 * its lane Button at its longest and its status line, so the pages stay the same whatever is open or unread.
220 */
221function lanePageIn(ids: readonly string[], lanePage: number | undefined, agents: readonly HighCommandAgent[]) {
222 const known = new Map(agents.map(agent => [agent.id, agent]))
223 const { Button, Text } = MEASURE
224 const costs = ids.map(id => {
225 const agent = known.get(id)
226 const label = `▸ ${peerLabel(nameOf(agent) ?? id)} (${peerLabel(id)}) · ${Number.MAX_SAFE_INTEGER} unread`
227 const status = agent === undefined ? '' : statusLine(agent, id, 0)
228 return serialized(<Button key={`lane:${id}`} label={label} variant="primary" onPress={async () => {}} />) + serialized(<Text wrap="wrap">{status}</Text>)
229 })
230 return pageIn(pageStarts(costs, LIMITS.laneButtons, LANES_BUDGET), ids.length, LIMITS.laneButtons, lanePage)
231}
232
233/** The ids on the lane page shown. */
234export function laneIdsShown(ids: readonly string[], lanePage: number | undefined, agents: readonly HighCommandAgent[] = []): string[] {
235 const { from, to } = lanePageIn(ids, lanePage, agents)
236 return ids.slice(from, to)
237}
238
239/**
240 * An agent's name, or undefined when it has none. A name of only spaces or invisible characters is stored as '' (peerKey),
241 * and counts as none, so the agent shows its id.
242 */
243function nameOf(agent: HighCommandAgent | undefined): string | undefined {
244 return agent?.name === undefined || agent.name === '' ? undefined : agent.name
245}
246
247/** An agent as its status line and a lane's location name it: `name (id)`, or the id when it has no name. */
248function agentName(agent: HighCommandAgent | undefined, id: string): string {
249 const name = nameOf(agent)
250 return name !== undefined && name !== id ? `${peerLabel(name)} (${peerLabel(id)})` : peerLabel(id)
251}
252
253/** The current place in a roster's location line: the main inbox or an agent's lane. */
254function laneTitle(model: PaneModel): string {
255 if (model.laneId === undefined) return 'Main inbox'
256 return `Agent observations: ${agentName(model.agents?.find(agent => agent.id === model.laneId), model.laneId)}`
257}
258
259/**
260 * Row 1 of every view: Back where there is a level above, a dim prefix that truncates from its start, the current place
261 * in bold, and the dim key hint when the row and the hint fit `columns`, the band's rule. While the place fits the row
262 * beside Back, it does not shrink, so the prefix takes the whole cut. A place wider than that may wrap, so it still
263 * shows whole.
264 */
265function locationRow(
266 { Box, Text, Button }: HighCommandElements,
267 prefix: string,
268 place: string,
269 columns: number | undefined,
270 back?: { onPress: () => Promise<void>; autoFocus: boolean },
271): RenderElement {
272 const backCells = back === undefined ? 0 : plainCells('Back') + 2
273 const cells = backCells + cellWidth(prefix) + 1 + cellWidth(place)
274 const hint = columns !== undefined && cells + 2 + cellWidth(PANE_KEY_HINT) <= columns
275 const isKept = columns !== undefined && backCells + 1 + cellWidth(place) <= columns
276 return (
277 <Box flexDirection="row" columnGap={2}>
278 {back !== undefined && <Button key="pane:back" label="Back" hotkey="b" plain {...(back.autoFocus ? { autoFocus: true as const } : {})} onPress={back.onPress} />}
279 <Box flexDirection="row" columnGap={1}>
280 <Text dimColor wrap="truncate-start">{prefix}</Text>
281 {isKept ? <Box flexShrink={0}><Text bold>{place}</Text></Box> : <Text bold>{place}</Text>}
282 </Box>
283 {hint && <Box flexGrow={1} justifyContent="flex-end"><Text dimColor wrap="truncate-end">{PANE_KEY_HINT}</Text></Box>}
284 </Box>
285 )
286}
287
288/**
289 * The dim context line: when capture began, this conversation only, the order; after a reset, that history is gone. A
290 * branch's line starts with the branch time and the messages it took from the parent conversation (branchLabel).
291 */
292function contextLine(Text: HighCommandElements['Text'], model: PaneModel): RenderElement | false {
293 const capture = model.capture
294 if (capture === undefined || capture === null) return false
295 const since = clockLabel(capture.at, model.now)
296 const scope = capture.branch === undefined ? `Since ${since} · this conversation only` : `${branchLabel(capture.branch, model.now)} · since ${since}`
297 return <Text dimColor wrap="wrap">{`${scope} · observation order${capture.reset ? ' · earlier history not restored' : ''}`}</Text>
298}
299
300/** The notice of messages dropped for good, at full strength: it says whether the list is complete. */
301function evictedLine(Text: HighCommandElements['Text'], model: PaneModel): RenderElement | false {
302 return (model.evicted ?? 0) > 0 && <Text>{`History trimmed: ${count(model.evicted!, 'message')} permanently evicted.`}</Text>
303}
304
305/** The verbatim order note, last and dim. */
306function footer({ Box, Text }: HighCommandElements): RenderElement {
307 return <Box marginTop={1}><Text dimColor wrap="wrap">{ORDER_NOTE}</Text></Box>
308}
309
310/** One pager row: the Button back, if any, the dim position, and the Button on, if any. */
311function pagerRow({ Box, Text }: HighCommandElements, before: RenderElement | false, position: string, after: RenderElement | false, marginTop = 0): RenderElement {
312 return (
313 <Box flexDirection="row" columnGap={2} {...(marginTop > 0 ? { marginTop } : {})}>
314 {before}
315 <Text dimColor wrap="truncate-end">{position}</Text>
316 {after}
317 </Box>
318 )
319}
320
321/** Whether the latest message is a send that was not delivered. */
322function isRefused(last: HighCommandEntry): boolean {
323 return labelOf(last).word.endsWith(NOT_DELIVERED)
324}
325
326/**
327 * The latest message of a roster row: the arrow, the kind, then the summary. With `hasMark`, a send that was not
328 * delivered starts with `(not delivered)`, in color `error`; without it, the row draws that mark with its others. On a
329 * read row only the summary is dim: the arrow, the kind and the marks keep their strength, and no dim parent holds a mark.
330 */
331function messageSpans(Text: HighCommandElements['Text'], last: HighCommandEntry, isRead: boolean, hasMark: boolean): (RenderElement | string)[] {
332 const { arrow, word } = labelOf(last)
333 const kind = isRefused(last) ? word.slice(0, -NOT_DELIVERED.length - 1) : word
334 return [
335 ...(hasMark && isRefused(last) ? [<Text color="error">{NOT_DELIVERED}</Text>, ' '] : []),
336 `${arrow} ${kind === 'message' ? '' : `${kind}: `}`,
337 styled(Text, last.summary, isRead ? { dimColor: true } : {}),
338 ]
339}
340
341/** A Text that holds `text`, styled; the plain string when it has no style. */
342function styled(Text: HighCommandElements['Text'], text: string, props: TextProps): RenderElement | string {
343 return Object.keys(props).length === 0 ? text : <Text {...props}>{text}</Text>
344}
345
346type RosterRowArgs = { row: RosterRow; index: number; label: string; key: string; now: number; open: () => Promise<void> }
347
348/** A peer's Button: its digit for the first nine rows of a page, plain so the digit shows. */
349function peerButton({ Button }: HighCommandElements, { index, label, key, open }: RosterRowArgs): RenderElement {
350 return <Button key={key} label={label} plain {...(index < LIMITS.hotkeys ? { hotkey: String(index + 1) } : {})} onPress={open} />
351}
352
353/**
354 * A roster row in two lines, below COLUMNS_FROM cells. Line 1: who, how many new, when, and the state, which a narrow
355 * pane cuts first. Line 2, under the name: the marks first (the sender label, `suspicious`, `(not delivered)`), in a
356 * Text of their own that wraps, so no width of `columns` cuts one; then the latest message, which alone is cut at its
357 * end. It shares line 2 while the marks leave it PREVIEW_CELLS, and takes a line of its own otherwise.
358 */
359function twoLineRow(ui: HighCommandElements, args: RosterRowArgs, columns: number | undefined): RenderElement {
360 const { Box, Text } = ui
361 const { row, index, now } = args
362 const isRead = row.unread === 0
363 const dim: TextProps = isRead ? { dimColor: true } : {}
364 const weight: TextProps = isRead ? {} : { bold: true }
365 const state = rosterState(row.state, now)
366 const trust = trustLabel(row.trust)
367 const button = peerButton(ui, args)
368 const marks = dotted([
369 // Every sender label is plain text: in tmux each teammate's pane makes every message `unverified sender`, and a
370 // color there would hide a real `suspicious`.
371 trust !== undefined && [trust],
372 row.isSuspicious && [<Text color="warning">suspicious</Text>],
373 isRefused(row.last) && [<Text color="error">{NOT_DELIVERED}</Text>],
374 ])
375 const markCells = cellWidth(joined([trust, row.isSuspicious ? 'suspicious' : undefined, isRefused(row.last) ? NOT_DELIVERED : undefined]))
376 const message = messageSpans(Text, row.last, isRead, false)
377 const isShared = columns !== undefined && GUTTER + markCells + cellWidth(' · ') + PREVIEW_CELLS <= columns
378 return (
379 <Box flexDirection="column">
380 <Box flexDirection="row" columnGap={1}>
381 {index < LIMITS.hotkeys ? button : <Box paddingLeft={GUTTER}>{button}</Box>}
382 <Text {...weight} wrap="truncate-end">
383 {dotted([
384 row.unread > 0 && [<Text bold>{`${row.unread} new`}</Text>],
385 [styled(Text, clockLabel(row.last.at, now), dim)],
386 state !== undefined && [styled(Text, state, dim)],
387 ])}
388 </Text>
389 </Box>
390 {marks.length === 0 ? (
391 <Box paddingLeft={GUTTER}><Text {...weight} wrap="truncate-end">{message}</Text></Box>
392 ) : isShared ? (
393 <Box flexDirection="row" paddingLeft={GUTTER}>
394 <Box flexShrink={0}><Text {...weight} wrap="wrap">{marks}</Text></Box>
395 <Text {...weight} wrap="truncate-end">{[' · ', ...message]}</Text>
396 </Box>
397 ) : [
398 <Box paddingLeft={GUTTER}><Text {...weight} wrap="wrap">{marks}</Text></Box>,
399 <Box paddingLeft={GUTTER}><Text {...weight} wrap="truncate-end">{message}</Text></Box>,
400 ]}
401 </Box>
402 )
403}
404
405/**
406 * The cells of Last state on a roster page: the longest state, at least CELLS.state, and at most what leaves Last
407 * message MESSAGE_CELLS of `columns`. A state wider than that is cut at its end, so only a full row cuts a state.
408 */
409function stateCells(states: readonly (string | undefined)[], columns: number): number {
410 const others = CELLS.peer + CELLS.fresh + CELLS.time + CELLS.sender + 5
411 const longest = Math.max(0, ...states.map(state => (state === undefined ? 0 : cellWidth(state))))
412 return Math.max(CELLS.state, Math.min(longest, columns - others - MESSAGE_CELLS))
413}
414
415/**
416 * The dim header row over the fixed roster columns; `state` is the cells of Last state. A Box can shrink by default,
417 * so each fixed cell sets `flexShrink={0}`: only Last message gives up room, as in each row (columnsRow).
418 */
419function columnsHeader({ Box, Text }: HighCommandElements, state: number): RenderElement {
420 return (
421 <Box flexDirection="row" columnGap={1}>
422 <Box width={CELLS.peer} flexShrink={0} paddingLeft={GUTTER}><Text dimColor>Peer</Text></Box>
423 <Box width={CELLS.fresh} flexShrink={0} justifyContent="flex-end"><Text dimColor>New</Text></Box>
424 <Box width={CELLS.time} flexShrink={0} justifyContent="flex-end"><Text dimColor>Time</Text></Box>
425 <Box width={CELLS.sender} flexShrink={0}><Text dimColor>Sender</Text></Box>
426 <Box width={state} flexShrink={0}><Text dimColor>Last state</Text></Box>
427 <Box flexGrow={1} flexShrink={1} minWidth={0}><Text dimColor>Last message</Text></Box>
428 </Box>
429 )
430}
431
432/**
433 * A roster row in fixed columns, from COLUMNS_FROM cells: the peer (its label cut to 16 cells), the unread count, the
434 * time (the date alone on another day), the sender level, the state in `stateWidth` cells (stateCells), and the latest
435 * message. Any `suspicious` and `(not delivered)` marks start it, within the MESSAGE_CELLS it always keeps. Each fixed
436 * cell, the gutter and peer cell too, keeps its width (`flexShrink={0}`); only Last message shrinks, and is cut there.
437 */
438function columnsRow(ui: HighCommandElements, args: RosterRowArgs, stateWidth: number): RenderElement {
439 const { Box, Text } = ui
440 const { row, index, now } = args
441 const isRead = row.unread === 0
442 const dim: TextProps = isRead ? { dimColor: true } : {}
443 const state = rosterState(row.state, now)
444 return (
445 <Box flexDirection="row" columnGap={1}>
446 <Box width={CELLS.peer} flexShrink={0} {...(index < LIMITS.hotkeys ? {} : { paddingLeft: GUTTER })}>{peerButton(ui, args)}</Box>
447 <Box width={CELLS.fresh} flexShrink={0} justifyContent="flex-end">{row.unread > 0 && <Text bold>{String(row.unread)}</Text>}</Box>
448 <Box width={CELLS.time} flexShrink={0} justifyContent="flex-end">
449 <Text {...dim}>{isSameDay(row.last.at, now) ? timeLabel(row.last.at) : dayLabel(row.last.at)}</Text>
450 </Box>
451 <Box width={CELLS.sender} flexShrink={0}>{row.trust !== undefined && <Text>{row.trust}</Text>}</Box>
452 <Box width={stateWidth} flexShrink={0}>{state !== undefined && <Text {...dim} wrap="truncate-end">{state}</Text>}</Box>
453 <Box flexGrow={1} flexShrink={1} minWidth={0}>
454 <Text {...(isRead ? {} : { bold: true })} wrap="truncate-end">
455 {row.isSuspicious && [<Text color="warning">suspicious</Text>, ' ']}
456 {messageSpans(Text, row.last, isRead, true)}
457 </Text>
458 </Box>
459 </Box>
460 )
461}
462
463/** Puts items of known cells on rows of at most `columns` cells, `gap` cells apart; a row holds at least one. */
464function packed<T>(items: readonly { cells: number; node: T }[], columns: number | undefined, gap: number): T[][] {
465 if (columns === undefined) return [items.map(item => item.node)]
466 const rows: T[][] = []
467 let used = 0
468 for (const { cells, node } of items) {
469 const last = rows.at(-1)
470 if (last !== undefined && used + gap + cells <= columns) {
471 last.push(node)
472 used += gap + cells
473 } else {
474 rows.push([node])
475 used = cells
476 }
477 }
478 return rows
479}
480
481/** An agent's status line behind Agent status: its status and source, with the time of each, at `now`. */
482function statusLine(agent: HighCommandAgent, id: string, now: number): string {
483 const at = (time: number) => clockLabel(time, now)
484 const last = agent.lastEvent === undefined ? '' : ` · lifecycle observation: ${agent.lastEvent.word} at ${at(agent.lastEvent.at)}`
485 return `${agentName(agent, id)}: ${agent.status} · ${agent.source} at ${at(agent.at)}${last}`
486}
487
488/**
489 * The agent lanes, in roster views only: one row of lane Buttons, packed to the width so no row needs a wrap, the
490 * current lane marked `▸` (and primary), the lane note, the statuses behind Agent status, the agents that moved to the
491 * next page when this one ended at LANES_BUDGET, and one pager row.
492 */
493function laneSection(ui: HighCommandElements, model: PaneModel, actions: PaneActions): RenderElement | false {
494 const { Box, Text, Button } = ui
495 const agents = new Map((model.agents ?? []).map(agent => [agent.id, agent]))
496 const ids = laneIdsOf(model.laneIds ?? [], model.agents ?? [])
497 if (ids.length === 0) return false
498 const { page, pages, from, to, moved } = lanePageIn(ids, model.lanePage, model.agents ?? [])
499 const shown = ids.slice(from, to)
500 // A label is the agent's name, or its id; ` (id)` only where two drawn Buttons would read the same.
501 const names = shown.map(id => peerLabel(nameOf(agents.get(id)) ?? id))
502 const label = (name: string, id: string) => (names.filter(other => other === name).length > 1 || name === 'Main inbox' ? `${name} (${peerLabel(id)})` : name)
503 const main = `${model.laneId === undefined ? '▸ ' : ''}Main inbox`
504 const status = model.statusOpen === true ? 'Hide agent status' : 'Agent status'
505 const buttons = [
506 { cells: plainCells(main), node: <Button key="lane:main" label={main} hotkey="m" plain onPress={() => actions.lane('')} /> },
507 ...shown.map((id, index) => {
508 const unread = model.laneUnread?.get(id) ?? 0
509 const isCurrent = model.laneId === id
510 const text = `${isCurrent ? '▸ ' : ''}${label(names[index]!, id)}${unread > 0 ? ` · ${unread} unread` : ''}`
511 return { cells: chromeCells(text), node: <Button key={`lane:${id}`} label={text} {...(isCurrent ? { variant: 'primary' as const } : {})} onPress={() => actions.lane(id)} /> }
512 }),
513 { cells: chromeCells(status), node: <Button key="lanes:status" label={status} onPress={actions.agentStatus} /> },
514 ]
515 return (
516 <Box flexDirection="column" marginTop={1}>
517 <Text bold>Agent lanes</Text>
518 {packed(buttons, model.columns, 1).map(row => <Box flexDirection="row" flexWrap="wrap" columnGap={1}>{row}</Box>)}
519 <Text dimColor wrap="wrap">{LANE_NOTE}</Text>
520 {model.statusOpen === true && (
521 <Box flexDirection="column" paddingLeft={2}>
522 <Text dimColor wrap="wrap">{LIVENESS_NOTE}</Text>
523 {shown.flatMap(id => {
524 const agent = agents.get(id)
525 return agent === undefined ? [] : [<Text wrap="wrap">{statusLine(agent, id, model.now)}</Text>]
526 })}
527 </Box>
528 )}
529 {movedLine(Text, moved, 'agent')}
530 {pages > 1 && (
531 <Box flexDirection="row" columnGap={1}>
532 {page > 0 && <Button key="lanes:previous" label="Previous agents" onPress={() => actions.lanePage(page - 1)} />}
533 {page + 1 < pages && <Button key="lanes:next" label="More agents" onPress={() => actions.lanePage(page + 1)} />}
534 <Text dimColor wrap="truncate-end">{`agents ${from + 1}-${to} of ${ids.length}`}</Text>
535 </Box>
536 )}
537 </Box>
538 )
539}
540
541/**
542 * The main inbox or an agent lane: location, counts, context, the peer rows, the peers that moved to the next page
543 * when this one ended at ROWS_BUDGET, their pager, the agent lanes, the order note.
544 */
545function rosterView(ui: HighCommandElements, model: PaneModel, actions: PaneActions): RenderElement {
546 const { Box, Text, Button } = ui
547 const peers = model.rows.map(row => row.peer)
548 const unread = unreadTotal(model.rows)
549 const { page, pages, from, to, moved } = rosterPageIn(model.rows, model.rosterPage)
550 const shown = model.rows.slice(from, to)
551 const isWide = model.columns !== undefined && model.columns >= COLUMNS_FROM
552 const stateWidth = isWide ? stateCells(shown.map(row => rosterState(row.state, model.now)), model.columns!) : CELLS.state
553 const labels = peerLabels(peers, isWide ? LABEL_CELLS : undefined)
554 const keys = peerKeys(peers)
555 const back = model.laneId === undefined ? undefined : { onPress: actions.leaveLane, autoFocus: false }
556 return (
557 <Box flexDirection="column">
558 {locationRow(ui, 'High Command ›', laneTitle(model), model.columns, back)}
559 <Box flexDirection="row" columnGap={2}>
560 <Text>{`${unread} unread (retained) · ${count(model.rows.length, 'peer')}`}</Text>
561 {unread > 0 && <Button key="pane:read-all" label="Read all" hotkey="r" plain onPress={actions.readAll} />}
562 </Box>
563 {contextLine(Text, model)}
564 {evictedLine(Text, model)}
565 {model.rows.length === 0 && <Text dimColor>No messages from teammates or other sessions in this capture window.</Text>}
566 {isWide && shown.length > 0 && columnsHeader(ui, stateWidth)}
567 {shown.map((row, index) => {
568 const args = { row, index, label: labels.get(row.peer)!, key: keys.get(row.peer)!, now: model.now, open: () => actions.openThread(row.peer) }
569 return isWide ? columnsRow(ui, args, stateWidth) : twoLineRow(ui, args, model.columns)
570 })}
571 {movedLine(Text, moved, 'peer')}
572 {pages > 1 && pagerRow(
573 ui,
574 page > 0 && <Button key="roster:previous" label="Previous peers" hotkey="p" plain onPress={() => actions.rosterPage(page - 1)} />,
575 `Peer page ${page + 1} of ${pages}`,
576 page + 1 < pages && <Button key="roster:next" label="More peers" hotkey="n" plain onPress={() => actions.rosterPage(page + 1)} />,
577 )}
578 {laneSection(ui, model, actions)}
579 {footer(ui)}
580 </Box>
581 )
582}
583
584type EntryArgs = { isFresh: boolean; isOpen: boolean; hasSendNote: boolean; hasDayLine: boolean }
585
586/**
587 * One thread entry: the send note above the first send of the page, a day line above the first entry of an earlier
588 * day, a header of fixed cells (new, time, arrow, kind) that never shrink and the trust marks, which alone shrink and
589 * wrap, the reported send result on a line of its own, the summary only when the sender wrote one that the body does
590 * not start with, the body, and Send details.
591 */
592function entryView(ui: HighCommandElements, entry: HighCommandEntry, args: EntryArgs, actions: PaneActions): RenderElement {
593 const { Box, Text, Button } = ui
594 const { isFresh, isOpen } = args
595 const weight: TextProps = isFresh ? { bold: true } : {}
596 const { arrow, word } = labelOf(entry)
597 const marks = dotted([
598 entry.trust !== undefined && [trustLabel(entry.trust)!],
599 entry.isSuspicious === true && [<Text color="warning">suspicious</Text>],
600 ])
601 const delivery = entry.delivery
602 return (
603 <Box flexDirection="column" marginTop={1}>
604 {args.hasSendNote && <Box paddingLeft={4}><Text dimColor wrap="wrap">{SEND_NOTE}</Text></Box>}
605 {args.hasDayLine && <Box paddingLeft={4}><Text dimColor>{dayLabel(entry.at)}</Text></Box>}
606 <Box flexDirection="row" columnGap={1}>
607 <Box width={3} flexShrink={0}>{isFresh && <Text bold>new</Text>}</Box>
608 <Box width={5} flexShrink={0}><Text {...weight}>{timeLabel(entry.at)}</Text></Box>
609 <Box width={1} flexShrink={0}><Text {...weight}>{arrow}</Text></Box>
610 <Box width={15} flexShrink={0}><Text {...weight}>{entry.direction === 'out' ? 'send attempted' : word}</Text></Box>
611 {marks.length > 0 && <Box flexShrink={1} minWidth={0}><Text wrap="wrap">{marks}</Text></Box>}
612 </Box>
613 {delivery !== undefined && (
614 <Box paddingLeft={10}>
615 <Text wrap="wrap" {...(delivery.isDelivered ? {} : { color: 'error' })}>
616 {delivery.isDelivered ? 'reported send result: queued' : `reported send result: not delivered: ${delivery.reason}`}
617 </Text>
618 </Box>
619 )}
620 {entry.summary !== lineOf(firstLine(entry.body)) && <Box paddingLeft={4}><Text {...weight} wrap="wrap">{entry.summary}</Text></Box>}
621 <Box paddingLeft={4}><Text wrap="wrap">{entry.body}</Text></Box>
622 {entry.fullChars > entry.body.length && (
623 <Box paddingLeft={4}><Text dimColor>{`(${count(entry.fullChars - entry.body.length, 'more character')} in the transcript.)`}</Text></Box>
624 )}
625 {(entry.refusal !== undefined || entry.core !== undefined) && (
626 <Box paddingLeft={4}>
627 <Button key={`reason:${entry.seq}`} label={isOpen ? 'Hide send details' : 'Show send details'} onPress={() => actions.reason(entry.seq)} />
628 </Box>
629 )}
630 {isOpen && entry.refusal !== undefined && (
631 <Box flexDirection="column" paddingLeft={4}>
632 <Text wrap="wrap">{entry.refusal.body}</Text>
633 {entry.refusal.fullChars > entry.refusal.body.length && (
634 <Text dimColor>{`Refusal truncated: ${entry.refusal.fullChars} characters originally; ${entry.refusal.body.length} retained.`}</Text>
635 )}
636 </Box>
637 )}
638 {isOpen && entry.core !== undefined && (
639 <Box flexDirection="column" paddingLeft={4}>
640 <Text dimColor wrap="wrap">{CORE_NOTE}</Text>
641 <Text>{`Latest traced core recipient (bounded): ${entry.core.to}`}</Text>
642 <Text>{`Core queue outcome: ${entry.core.isDelivered ? 'accepted, not read' : `refused: ${entry.core.reason}`}`}</Text>
643 <Text wrap="wrap">{entry.core.body}</Text>
644 {entry.core.fullChars > entry.core.body.length && <Text>{`Core text truncated: ${entry.core.fullChars} characters originally.`}</Text>}
645 </Box>
646 )}
647 </Box>
648 )
649}
650
651/**
652 * One peer's thread, newest entry first: location with Back, the state line, the facts line with Show identity and
653 * Mark read (on a row of their own when the line does not fit), the context line, the entries, one pager row, the order note.
654 */
655function threadView(ui: HighCommandElements, model: PaneModel, thread: Thread, actions: PaneActions, label: string): RenderElement {
656 const { Box, Text, Button } = ui
657 const { row, since, shown, hidden, fresh } = thread
658 const facts = dotted([
659 row.trust !== undefined && [`Sender ${row.trust}`],
660 [count(shown.length + hidden, 'retained message')],
661 fresh > 0 && [`${fresh} new`],
662 thread.pages > 1 && [`page ${thread.page + 1} of ${thread.pages}`],
663 ])
664 const factsText = joined([
665 row.trust === undefined ? undefined : `Sender ${row.trust}`,
666 count(shown.length + hidden, 'retained message'),
667 fresh > 0 ? `${fresh} new` : undefined,
668 thread.pages > 1 ? `page ${thread.page + 1} of ${thread.pages}` : undefined,
669 ])
670 const buttons = [
671 <Button key="pane:identity" label="Show identity" hotkey="i" plain onPress={() => actions.identity(0)} />,
672 row.unread > 0 && <Button key="pane:mark-read" label="Mark read" hotkey="r" plain onPress={() => actions.markRead(row.peer)} />,
673 ]
674 const buttonCells = 2 + plainCells('Show identity') + (row.unread > 0 ? 2 + plainCells('Mark read') : 0)
675 const fits = model.columns === undefined || cellWidth(factsText) + buttonCells <= model.columns
676 const firstSend = shown.find(entry => entry.direction === 'out')
677 return (
678 <Box flexDirection="column">
679 {locationRow(ui, `High Command › ${laneTitle(model)} ›`, label, model.columns, { onPress: actions.back, autoFocus: true })}
680 {row.state !== undefined && <Text dimColor wrap="wrap">{threadState(row.state, model.now)}</Text>}
681 {fits ? (
682 <Box flexDirection="row" flexWrap="wrap" columnGap={2}>
683 <Text wrap="wrap">{facts}</Text>
684 {buttons}
685 </Box>
686 ) : [
687 <Text wrap="wrap">{facts}</Text>,
688 <Box flexDirection="row" flexWrap="wrap" columnGap={2}>{buttons}</Box>,
689 ]}
690 {contextLine(Text, model)}
691 {evictedLine(Text, model)}
692 {shown.map((entry, index) => {
693 const previous = shown[index - 1]
694 return entryView(ui, entry, {
695 isFresh: isNewer(entry, since),
696 isOpen: thread.reasonSeq === entry.seq,
697 hasSendNote: entry === firstSend,
698 hasDayLine: !isSameDay(entry.at, model.now) && (previous === undefined || !isSameDay(previous.at, entry.at)),
699 }, actions)
700 })}
701 {movedLine(Text, thread.moved, 'message')}
702 {thread.pages > 1 && pagerRow(
703 ui,
704 thread.page > 0 && <Button key="pane:newer" label="Newer" hotkey="p" plain onPress={() => actions.page(thread.page - 1)} />,
705 `Page ${thread.page + 1} of ${thread.pages} · ${count(hidden, 'retained message')} on other pages`,
706 thread.page + 1 < thread.pages && <Button key="pane:older" label="Older" hotkey="n" plain onPress={() => actions.page(thread.page + 1)} />,
707 1,
708 )}
709 {footer(ui)}
710 </Box>
711 )
712}
713
714/** A peer's full identity, as a level of its own under its thread: one 1,000-character part at a time. */
715function identityView(ui: HighCommandElements, model: PaneModel, thread: Thread, actions: PaneActions, label: string): RenderElement {
716 const { Box, Text, Button } = ui
717 const peer = thread.row.peer
718 const part = thread.identityPage ?? 0
719 const parts = Math.ceil(peer.length / 1000)
720 return (
721 <Box flexDirection="column">
722 {locationRow(ui, `High Command › ${laneTitle(model)} ›`, `${label} › Identity`, model.columns, { onPress: () => actions.identity(undefined), autoFocus: true })}
723 <Text>{`Identity part ${part + 1} of ${parts} (${peer.length} characters):`}</Text>
724 <Text wrap="wrap">{identityPart(peer, part)}</Text>
725 {parts > 1 && (
726 <Box flexDirection="row" columnGap={2}>
727 {part > 0 && <Button key="identity:previous" label="Previous identity part" hotkey="p" plain onPress={() => actions.identity(part - 1)} />}
728 {part + 1 < parts && <Button key="identity:next" label="Next identity part" hotkey="n" plain onPress={() => actions.identity(part + 1)} />}
729 </Box>
730 )}
731 </Box>
732 )
733}
734
735/** Includes JSON structure, escaped strings, and space for serialized button handlers. */
736export function fitsBounds(tree: RenderElement): boolean {
737 const pending = [{ node: tree as unknown, depth: 1 }]
738 let nodes = 0
739 while (pending.length > 0) {
740 const { node, depth } = pending.pop()!
741 if (++nodes > LIMITS.drawingNodes || depth > LIMITS.drawingDepth) return false
742 if (typeof node !== 'object' || node === null) continue
743 const children: unknown = Reflect.get(node, 'children')
744 if (Array.isArray(children)) for (const child of children) pending.push({ node: child, depth: depth + 1 })
745 }
746 try {
747 return serialized(tree) <= LIMITS.drawingText
748 } catch {
749 return false
750 }
751}
752
753/** The pane's tree: a roster (the main inbox or an agent lane), one peer's thread, or that peer's identity. */
754export function paneTree(ui: HighCommandElements, model: PaneModel, actions: PaneActions): RenderElement {
755 const thread = model.thread
756 if (thread === undefined) return rosterView(ui, model, actions)
757 const label = peerLabels(model.rows.map(row => row.peer)).get(thread.row.peer)!
758 return thread.identityPage === undefined ? threadView(ui, model, thread, actions, label) : identityView(ui, model, thread, actions, label)
759}
760
761/** The terminal cells of a row of one text and Buttons drawn as `[ label ]`, with `gap` cells before each Button. */
762function rowCells(text: string, labels: readonly string[], gap: number): number {
763 return labels.reduce((cells, label) => cells + gap + cellWidth(label) + 4, cellWidth(text))
764}
765
766/**
767 * The dim key hint after the last Button of a row of `cells` cells, or false. It shows only when the row, a gap of
768 * one and the hint all fit the band's `columns`, so the row never wraps and keeps every Button; never without `columns`.
769 */
770function keyHint(Text: HighCommandElements['Text'], cells: number, columns: number | undefined): RenderElement | false {
771 return columns !== undefined && cells + 1 + cellWidth(BAND_KEY_HINT) <= columns && <Text dimColor wrap="truncate-end">{BAND_KEY_HINT}</Text>
772}
773
774/**
775 * The band row, one blank row below its top, above what other mods draw there. `waiting` holds only rows with unread
776 * entries; `laneUnread` is the unread count of all agent lanes, above zero only with agentLanesInBand on. `columns`,
777 * the band's width in cells, adds the key hint where the row has room for it.
778 */
779export function bandTree(
780 { Box, Text, Button }: HighCommandElements,
781 waiting: readonly RosterRow[],
782 actions: BandActions,
783 below: RenderElement,
784 labels: Map<string, string>,
785 laneUnread = 0,
786 columns?: number,
787): RenderElement {
788 const named = waiting.slice(0, LIMITS.bandPeers).map(row => `${labels.get(row.peer)} ${row.unread}`)
789 const more = waiting.length > LIMITS.bandPeers ? [`+${waiting.length - LIMITS.bandPeers} more`] : []
790 const peers = [...named, ...more]
791 const summary = `High Command · ${unreadText(unreadTotal(waiting), laneUnread)}${peers.length === 0 ? '' : ` — ${peers.join(' · ')}`}`
792 return (
793 <Box flexDirection="column">
794 <Box flexDirection="row" columnGap={1} marginTop={1}>
795 <Text wrap="truncate-end">{summary}</Text>
796 <Button key="band:open" label="Open" hotkey="o" onPress={actions.open} />
797 <Button key="band:read-all" label="Read all" hotkey="r" onPress={actions.readAll} />
798 <Button key="band:hide" label="Hide" hotkey="h" onPress={actions.hide} />
799 {keyHint(Text, rowCells(summary, ['Open', 'Read all', 'Hide'], 1), columns)}
800 </Box>
801 {below}
802 </Box>
803 )
804}
805
806/** Keeps only the counts and Open, below the same blank row, when the full band exceeds the shared budget; `columns` as in bandTree. */
807export function compactBandTree({ Box, Text, Button }: HighCommandElements, waiting: readonly RosterRow[], actions: BandActions, below: RenderElement, laneUnread = 0, columns?: number): RenderElement {
808 const summary = `High Command · ${unreadText(unreadTotal(waiting), laneUnread)}`
809 const hint = keyHint(Text, rowCells(summary, ['Open'], 0), columns)
810 return <Box flexDirection="column">
811 <Box flexDirection="row" marginTop={1}>
812 <Text>{summary}</Text>
813 <Button key="band:open" label="Open" hotkey="o" onPress={actions.open} />
814 {hint && <Box marginLeft={1}>{hint}</Box>}
815 </Box>
816 {below}
817 </Box>
818}
819types/index.d.ts 168 lines1/** A peer's last reported state. */
2export type HighCommandState = {
3 /** 'idle', 'interrupted', 'failed', 'ended', 'shut down', or a ListAgents state word. */
4 word: string
5 source?: string
6 /** $.clock.now() when the state was reported. */
7 at: number
8}
9
10/**
11 * How far Claude Code vouches for an inbound sender name: 'verified' for a team mailbox
12 * entry the harness wrote under that name, 'local' for another session's or agent's message that Claude
13 * Code delivered, 'unverified' for every other origin, a name only a plugin claims included.
14 */
15export type HighCommandTrust = 'verified' | 'local' | 'unverified'
16
17/** One receive observation ('in') or send attempt ('out') in its conversation lane. */
18export type HighCommandEntry = {
19 /** Lane-unique and increasing from 1: the recording order. */
20 seq: number
21 /** The full normalized peer identity: the thread this entry belongs to. */
22 peer: string
23 direction: 'in' | 'out'
24 /** 'result': a teammate's final answer. 'failure': a teammate's failure. */
25 kind: 'message' | 'result' | 'failure'
26 /** One line, at most LIMITS.summaryChars characters. */
27 summary: string
28 /** The sanitized body, cut at LIMITS.bodyChars characters. */
29 body: string
30 /** The length of the sanitized body before the cut. */
31 fullChars: number
32 /** $.clock.now() when High Command observed the event. */
33 at: number
34 /** Inbound entries only: the trust level of the sender name, set from origin fields alone. */
35 trust?: HighCommandTrust
36 /** Inbound entries only: the text matches the suspicious-text list; a display mark. */
37 isSuspicious?: true
38 /** Agent lane inbound entries only: the main conversation's own message to that agent, never unread. */
39 fromMain?: true
40 /** Cumulative retention loss, carried atomically by the newest recorded entry. */
41 evictedTotal?: number
42 /** The detailed refusal, bounded separately from its one-line preview. */
43 refusal?: { body: string; fullChars: number }
44 /** Evidence from the latest downstream call only, never a complete send history. */
45 core?: { to: string; body: string; fullChars: number; isDelivered: boolean; reason?: string }
46 /** Outbound entries only: the reported outcome, separate from core evidence. */
47 delivery?: { isDelivered: true } | { isDelivered: false; reason: string }
48}
49
50/** What High Command knows about a peer besides its messages. */
51export type HighCommandPeer = {
52 /** $.clock.now() of the last report about this peer; the peer cap keeps the newest. */
53 seenAt: number
54 state?: HighCommandState
55 /** The `from` address the newest cross-session frame named for this peer, and $.clock.now() when it was reported. */
56 address?: {
57 value: string
58 at: number
59 /** Address observation order for timestamp ties; absent in older saved state. */
60 order?: number
61 }
62}
63
64/** The thread the pane shows, with the peer's read mark from the moment it opened. */
65export type HighCommandThread = {
66 peer: string
67 page?: number
68 identityPage?: number
69 reasonSeq?: number
70 /** Inbound entries with a higher seq draw as new while the thread stays open. */
71 since: number
72 /** The newest seq when the person opened the thread: an append that it saw never closes it. */
73 from: number
74}
75
76export type HighCommandLane = {
77 rosterPage?: number
78 entries: HighCommandEntry[]
79 peers: Record<string, HighCommandPeer>
80 readThrough: Record<string, number>
81 openThread: HighCommandThread | null
82 /**
83 * The seq of the newest entry recorded that can be unread; it only grows and outlives the entry's eviction.
84 * Absent before the lane's first append.
85 */
86 inboundThrough?: number
87}
88
89export type HighCommandAgent = {
90 id: string
91 name?: string
92 status: string
93 at: number
94 source: 'roster snapshot' | 'lifecycle observation'
95 lastEvent?: { word: string; at: number }
96}
97
98/**
99 * The capture window: when it began, and whether it began after a reset that dropped earlier history. A branch keeps
100 * its parent's window, and `branch` says when it branched and how many kept messages it took from the parent. `depth`
101 * counts the /branch steps from the conversation where the window began: 1 for its branch, 2 for a branch of that.
102 */
103export type HighCommandCapture = { at: number; reset: boolean; branch?: { at: number; messages: number; depth: number } }
104
105/**
106 * The copy of one conversation's inbox that `$.state` holds: what a reload of the mod takes back. The hooks module keeps
107 * the inbox itself in memory, and the pane and the band draw from there. `session` and `epoch` name the inbox it copies.
108 */
109export type HighCommandView = {
110 session: string
111 /** The number of the inbox in the module that wrote it; a branch copy and a fresh inbox each take a new one. */
112 epoch: number
113 /** Grows with each write: Claude Code draws the pane and the band again when it changes. */
114 revision: number
115 entries: HighCommandEntry[]
116 peers: Record<string, HighCommandPeer>
117 readThrough: Record<string, number>
118 /** The newest seq that a press of Hide had seen; 0 before any press. It only grows. */
119 hiddenThrough: number
120 /** The seq of the newest inbound entry recorded; it only grows and outlives the entry's eviction. */
121 inboundThrough: number
122 capture: HighCommandCapture | null
123 openThread: HighCommandThread | null
124 rosterPage: number
125 selectedLane: string | null
126 lanePage: number
127 /** Whether the pane's Agent status block is open. */
128 agentStatus: boolean
129 /** The local agents of the process, which every conversation shows. */
130 agents: Record<string, HighCommandAgent>
131}
132
133/** The copy of one conversation's agent lanes, apart from HighCommandView: each saved value has a size limit. */
134export type HighCommandLaneView = {
135 session: string
136 epoch: number
137 lanes: Record<string, HighCommandLane>
138 /**
139 * Per agent lane, the newest seq that a press of Hide had seen while agentLanesInBand is on; a mark only grows.
140 */
141 hiddenLanes: Record<string, number>
142}
143
144declare module 'claude-code' {
145 interface PluginState {
146 'high-command': {
147 view: HighCommandView
148 laneView: HighCommandLaneView
149 // The values of 1.2.2, which kept the inbox in `$.state` itself. After an update, when neither copy above holds
150 // anything, the module reads them once to take the inbox over, and never writes them.
151 entries: HighCommandEntry[]
152 peers: Record<string, HighCommandPeer>
153 readThrough: Record<string, number>
154 openThread: HighCommandThread | null
155 hiddenThrough: number
156 inboundThrough: number
157 lanes: Record<string, HighCommandLane>
158 hiddenLanes: Record<string, number>
159 capture: HighCommandCapture | null
160 selectedLane: string | null
161 lanePage: number
162 agentStatus: boolean
163 rosterPage: number
164 agents: Record<string, HighCommandAgent>
165 }
166 }
167}
168