Agent-team swarm: message log, roster, /swarm pane, lead wake modes, and the swarm protocol skill

A Claude Code mod plus a skill for leading a self-organising agent team: teammates message each other directly with SendMessage, and the lead sets the goal and is woken only when it is needed.
Status: experimental. Needs CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1 and Claude Code ≥ 2.1.287; built and tested against 2.1.302. Mod events and methods change between releases.
This section is written for AI agents: orchestrators looking for a way to lead a Claude Code agent team. Humans: skip to For humans.
What it does for you as the lead. When you orchestrate an agent team, every message a teammate sends you, every idle notice and every protocol message ([PROPOSE], [CLAIM], [HANDOFF], [REVIEW]) costs you a full turn over your whole context. This mod sits inside Claude Code and keeps that traffic out of your context budget: coordination happens between teammates, and you hear only @lead mentions, [ASK], [BLOCK], [DONE], untyped text, idle notices with a failure reason and real alarms. It runs in Claude Code's own hooks, with no extra runtime, server or queue. It also:
#412 · 17:04:12), so a duplicate [CLAIM] is settled by the lower stamp, and answers each build or research claim: the slice is the claimant's, or who holds it;merge-lock works as a lock and code is merged one slice at a time;[WAIT] <path>) or at a time ([WAIT] until <ISO time>), so nobody polls;stop_swarm, that stops every live teammate or the ones you name;.swarm/log.jsonl and the team to .swarm/roster.json, which you can read.Install and check (shell; then start a new session):
claude plugin install agent-swarm --marketplace rahimi/claude-code-swarm
claude plugin list # agent-swarm is listed and enabled
export CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1
In the session, /swarm status answers with one line (swarm: yes/no, quiet: on, the log path). Without installing: git clone https://github.com/rahimi/claude-code-swarm and start claude --plugin-dir ./claude-code-swarm.
When to use it. A team of 3–7 teammates under CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1 working on research, review, exploration or a creative build, or code cut into slices that each get their own git worktree and merge through merge-lock. For a single fix list, one builder with independent reviewers did better (see What we measured).
Measured benefit. In a 7-agent release review (2026-10-14) the lead was woken once while 61 messages to it were held. In an 18-agent review (2026-10-17) slices worked twice went from 6 and 8 of 21 to 0 once claimants waited for the mod's answer; the lead was woken 1.7 times per agent. Six teammates building 12 slices of this mod (2026-10-18) merged 15 times through merge-lock with 0 overlaps. Details: What we measured.
What you can do yourself as the lead.
.swarm/roster.json (agents, code names, claims, deliverables, waits) and .swarm/log.jsonl (one JSON line per message or event, with from, to, summary, type; stamp on teammate-to-teammate messages).Deliverable: <path> line per artefact in each spawn prompt; the mod tells you when one has no builder.stop_swarm (mcp__agent-swarm__stop_swarm, input { names?: string[] }) when the work is done. It answers one line: who stopped, who failed and why.claude -p "/swarm status" from a shell for the one-line state where no pane draws.The instructions for the lead are the skill swarm-protocol (agent-swarm:swarm-protocol, skills/swarm-protocol/SKILL.md): the brief, self-chosen code names, [TYPE] subject messages, claims, reviewer veto, [LOCK], [WAIT], code merged one slice at a time through merge-lock, announced cuts, and a fresh agent for the final synthesis. Load it before you spawn the team, e.g. Use the swarm-protocol skill. Goal: … Budget: 4 agents, 30 min. Kill criterion: … Done when: ….
Search terms. Claude Code agent teams, CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS, multi-agent orchestration, swarm, team lead, SendMessage, TaskStop, claims, lead wakes, Claude Code mod, plugin.
Every behaviour of the mod, exactly: REFERENCE.md. Changes per version: CHANGELOG.md.
<!-- film --> https://github.com/user-attachments/assets/6c096b84-152b-4982-863a-38c02b2a3531
/swarm opens a pane with two looks. Look A (the default, key 1) is the working view: one card per teammate with its state, time in it, current action and tool-call count, the file it last touched, and a bar of its tool calls and messages over time; the claim cards; the lead's wakes, delivered and held; the message list, refused spawns among them. Look B (key 2) shows the team as a star map around the lead, each message flying as a comet, for watching and demos. Both draw in any 24-bit colour terminal and add pictures where the terminal draws them (/swarm level auto|basic|rich).
◉ S W A R M LIVE · t1–t2 T+6:12 01:21:40 ● live
A G E N T S 2 · 1 running C L A I M S
▌Atlas t1 ↑3 ↓4 opus ╭ src/parser.ts ─────────── BUILDING ╮
▌● RUNNING 0:42 ✎ src/parser.ts │ build Atlas │
▌▁▃█▂▁▁▁▅▂▁▁▁▁▃ │ review ◦Sage │
▌Sage t2 ↑2 ↓3 sonnet ╰────────────────────────────────────╯
▌● IDLE 2:03 ◦ README.md
▌▁▂▁▁▄▁▁▁▁▁▁▁▁▁
LEAD ▲ 2 woken ▽ 5 held back
M E S S A G E S
01:21:40 Atlas → Sage HANDOFF src/parser.ts
01:17:02 Sage → Atlas CLAIM review src/parser.ts
A teammate that joins slides in (look A) or fades in (look B), one that leaves greys out, and the header says + joined Kite or − left t2 for 10 s. In the live pane, pressing a live agent's name shows the last lines of its transcript and a field to message it: type, Enter sends. The text list shows a subagent that a teammate spawned under that teammate.
/swarm replay .swarm/log.jsonl plays a finished run back in the pane. While a swarm runs, the status line reads ◇ swarm 3 live · 1 done; when it ends, a toast gives its totals (swarm stood down: 4 agents · 52 messages · 12m · lead woken 3 (0.8/agent), held 18).
One session: CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1 claude --plugin-dir <path to this directory>.
Permanently (Claude Code 2.1.287+), from your terminal:
claude plugin install agent-swarm --marketplace rahimi/claude-code-swarm
or inside Claude Code:
/plugin marketplace add rahimi/claude-code-swarm
/plugin install agent-swarm@claude-code-swarm
Look B's rich sky uses a python with numpy for smooth motion: the python the skyPython setting names (in /config); with it empty, python3 from PATH, else uv run --no-project --with numpy python when uv is on PATH. Without one look B draws its basic sky and says why (/swarm status too). Nothing else needs Python.
Add .swarm/ to the project's .gitignore.
/swarm open the pane
/swarm wake all|mentions|digest|off
/swarm quiet on|off lead filter, default on
/swarm stall <minutes> 0 turns the watchdog off
/swarm claim <minutes> claim watchdog delay, 0 turns it off
/swarm level auto|basic|rich pane level, default auto
/swarm deliverable <path> adds a deliverable the claim watchdog checks for a builder
/swarm status one line of text (works where nothing draws, e.g. claude -p)
/swarm stop all|<name> stops every live teammate, or one (team or code name), with TaskStop
/swarm say <agent> <text> sends a live agent (team or code name) `swarm: the user says: <text>`
/swarm replay <log.jsonl> [--look A|B] [--level basic|rich] [--speed N] [--from <ISO>] [--to <ISO>]
/swarm replay stop
/swarmctl is a second name for the same command, for sessions where another plugin also registers /swarm.
If another plugin already uses /swarm, this one still loads and answers on /swarmctl; /swarmctl status and the /swarmctl help say /swarm is taken by <plugin>; use /swarmctl. In an interactive session it asks you once, a second after start (or after the lead's turn ends): keep both (stored, never asked again), see the command that removes the other plugin, or ask again next session. It never uninstalls anything. Two plugins with the same name cannot both load.
Wake mode, the lead filter, stall and claim minutes and the pane level persist in the plugin's store across sessions. replay plays a recorded .swarm/log.jsonl in the pane at --speed (default 30×, a quiet stretch at most 1.5 s), one run per team (teammates that messaged each other, from 30 s before their first peer message to their last line before 30 min without one, so a later team reusing their names is its own run); without --from/--to it plays the most recent run; its reply lists the runs with their --from/--to, ▶ on the one playing. Each agent of the run shows from its JOIN line, else its first log line, sent or received, so a teammate spawned late appears when it does. A replay sends nothing. A finished replay holds its last frame for 3 s, marked replay finished, then the pane shows the live view. When a live team spawns a teammate or sends a peer message during a replay, the header says live swarm running and a [ live ] button (0) stops the replay and shows it. Start a swarm by asking the lead to use the swarm-protocol skill, e.g. Use the swarm-protocol skill. Goal: … Budget: 4 agents, 30 min. Kill criterion: … Done when: ….
One project, a handful of runs: treat these as data points.
is yours, 0 of 21 were, and the lead was woken 1.7 times per agent.merge-lock, 0 overlapping, tests green after every merge (265 to 280), no slice built twice, and reviews that caught real defects. Given only a goal and no slice list, a second team of six (2026-10-19) cut the work into 4 slices within about a minute of their hellos and merged 6 times in 29 minutes.mentionsThe team mailbox already delivers every message addressed to the lead (and idle notifications) as a new lead turn. Waking the lead again for those would double each one, so no mode ever wakes for a message to or from the lead. The modes govern only teammate-to-teammate traffic, which the lead otherwise never sees:
| Mode | Wakes the lead |
|---|---|
mentions (default) | for peer messages containing @lead, @orchestrator, @main or @team-lead, coalesced over 3 s |
all | for every peer message, coalesced over 10 s so a burst is one wake |
digest | at most once per 60 s, with a list of the new peer messages |
off | never (the watchdog still runs unless /swarm stall 0) |
Why not all: every wake is a full lead turn over the lead's whole context. With 4 chatty teammates, all turns a peer conversation into N extra lead turns, which multiplies cost and pulls the lead back into relaying, the opposite of a self-organising swarm. mentions keeps the lead out until a teammate asks for it; digest is the middle ground for watching.
A wake is never submitted while the lead is mid-turn: it waits in the queue and goes out 250 ms after the lead's turn completes. Per the 2.1.299 types, $.prompt.submit from a plugin "runs once idle" and resolves when its turn starts, so the mod never awaits it inside a hook (a session.receive hook awaiting its own submit hangs) and sends one wake at a time.
Claude Code's own TeammateIdle and TaskCompleted hooks keep a teammate working, or a task open, at the moment it would stop; use them for hard gates such as "tests pass before you stop". The mod covers what they cannot: waking an idle teammate later, and the lead's load.
REFERENCE.md describes every part exactly: logging and order stamps, roster and teams, claims and watchdogs, lead wakes, the pane and stopping and the protocol skill.
– or open tasks: unknown.From this directory:
claude plugin validate --strict .
claude plugin test
python3 -B -m unittest discover -s tests -p 'test_*.py' # the sky renderer's motion (needs numpy)
To typecheck: tsconfig.json extends .claude-plugin/types/tsconfig.json, which is not in the repo. Claude Code writes .claude-plugin/types/ each time it loads a mod from a folder you own (as the header of the written types says), so run claude --plugin-dir . once, then npx tsc --noEmit.
hooks/core.ts holds every rule as plain functions (log, dedupe, roster, wake policy, stall, pane text); hooks/replay.ts the teams, runs and the scene the looks draw; hooks/look-a.ts and hooks/look-b.ts the two looks; hooks/pane.ts the pane's stage, live and replay; hooks/register.ts wires them to events; hooks/looks.ts, hooks/grid.ts and hooks/pixels.ts are the shared drawing helpers (palettes, the cell grid, the pixel canvas); hooks/pane-draw.ts cuts a frame into Rasters and Images; hooks/sidecar.ts runs hooks/sky.py, the look B sky renderer. tests/core.test.ts pins the rules, tests/register.test.ts drives the hooks through the test kit with a mock clock, tests/replay.test.ts covers the looks and the replay, tests/pane.test.ts the pane, tests/sky.test.ts the renderer from the mod's side, and tests/test_sky.py the renderer's motion.
hooks/register.ts 1494 lines1import type { AgentSpawnInput, ElementConstructor, EngineInterface, InputProps, On, PluginOptions } from 'claude-code'
2
3import {
4 MEMORY_CAP,
5 ClaimBoard,
6 commandHolder,
7 DEFAULT_CLAIM_MIN,
8 DEFAULT_STALL_MIN,
9 ENDED,
10 IDLE_ENDED_H,
11 LEAD,
12 MOD,
13 NUDGE_COOLDOWN_MIN,
14 MessageLog,
15 REPORTS,
16 Roster,
17 WAKE_MODES,
18 WakePolicy,
19 actionOf,
20 ago,
21 bandText,
22 bareName,
23 claimAlerts,
24 claimOf,
25 claimOfLine,
26 claimWakeText,
27 deliverablesOf,
28 fileOf,
29 firstLine,
30 hydrateClaims,
31 hydrateLog,
32 idleNotice,
33 isLeadAddress,
34 isHeldFromLead,
35 mentionsTarget,
36 targetMatches,
37 isStalled,
38 jsonl,
39 messageText,
40 namesText,
41 nudgeText,
42 openTaskCount,
43 paneRows,
44 parseLog,
45 parseTasks,
46 workflowRunOf,
47 isWaitDue,
48 waitPathOf,
49 waitTimeText,
50 waitUntilOf,
51 waitWakeText,
52 reviewOf,
53 sameTarget,
54 shortModel,
55 stallText,
56 stampLine,
57 timeOfDay,
58 typeOf,
59 writtenPath,
60} from './core'
61import type { AgentRow, Claim, ClaimRef, LogEntry, RosterEntry, UnclaimedWorker, Via, Wait, WakeMode } from './core'
62import { PANE, COMPOSE_KEY, buttonsOf, isReplaying, setStopAll, liveActivity, ownSky, paneClosed, skyStatus, liveEvent, liveFilter, liveView, renderLive, renderReplay, replayCommand, setLevel, showView } from './pane'
63import { setSkyPython } from './sidecar'
64import { STOP_ALL_KEY, stopControls, viewControls } from './pane-draw'
65import type { LevelSetting, LiveSource } from './pane'
66import { LiveScene, isTeammateName, runTitle } from './replay'
67import type { ModelFamily, Team } from './replay'
68
69const TICK_MS = 2_000
70const LIST_EVERY_TICKS = 2
71const TASKS_EVERY_TICKS = 15
72const FLUSH_MS = 1_000
73const STALE_TURN_MS = 60 * 60_000
74const MAX_TASK_FILES = 200
75const WAIT_EVERY_TICKS = 5
76/** A read of a file the teammate read this recently shows live but writes no FILE line. */
77const READ_LOG_MS = 5 * 60_000
78/** How long after a swarm's teammate ended its idle notices still count as the swarm's for the lead filter. */
79const STOPPED_GRACE_MS = 60_000
80/** How long after a teammate's message reached the lead its idle notice is held as a duplicate of that message. */
81const REPORT_GRACE_MS = 60_000
82/** The least time between two ACT lines of one teammate; a call in between is shown when that time is up. */
83const ACT_EVERY_MS = 2_000
84/** How long the stand-down toast stays; the default 4 s ends before a lead back from its stop_swarm turn looks. */
85const STAND_DOWN_TOAST_MS = 20_000
86/** How long a writer is not warned again about the same claimed file. */
87const OVERWRITE_WARN_MS = 2 * 60_000
88const LEVELS: readonly LevelSetting[] = ['auto', 'basic', 'rich']
89/** The tool the lead calls to stop the swarm: `stop_swarm` as the model sees it, `mcp__<plugin>__stop_swarm`. */
90const STOP_TOOL = 'stop_swarm'
91/** The full name `$.tool.register` gave the stop tool, `mcp__<plugin>__stop_swarm`. */
92let stopToolId = 'mcp__agent-swarm__' + STOP_TOOL
93const STOP_THEM = 'Stop them'
94/** The store key of one session's wake mode, before its session name; the plugin's store is shared by every session. */
95const WAKE_KEY = 'wakeMode@'
96/** The command's names: `/swarm`, and `/swarmctl` for sessions where another mod also registers `/swarm`. */
97const COMMANDS = ['swarm', 'swarmctl'] as const
98
99const roster = new Roster()
100const log = new MessageLog()
101const policy = new WakePolicy()
102const board = new ClaimBoard()
103board.isLive = name => !roster.hasTeammate(name) || roster.isLiveTeammate(name)
104roster.isHeld = name => waits.has(name) || board.openClaims(name).length > 0
105
106let cwd: string | null = null
107let session = ''
108let isHydrated = false
109let unwritten: LogEntry[] = []
110let isFlushScheduled = false
111let isRosterDirty = false
112let ticks = 0
113let lastActivityAt = 0
114/** When this load's session started. */
115let loadedAt = 0
116let stallMin = DEFAULT_STALL_MIN
117/** Whether the lead filter holds idle notices and protocol traffic back from the lead. */
118let quiet = true
119/** When the current team was last seen to be a swarm. */
120let swarmSeenAt = -Infinity
121/** When each sender's latest message other than an idle notice reached the lead. */
122const reachedLeadAt = new Map<string, number>()
123/** The team whose end last cleared the claims board, as `@<first peer message>/<latest spawn of its names>`. */
124let clearedTeam: string | undefined
125/** The status line last pinned, undefined while none is. */
126let shownStatus: string | undefined
127/** The swarm being watched for its stand-down: its names, start, last peer message, and the lead's wakes and held deliveries when it began. */
128let standing: { key: string; names: string[]; from: number; lastPeerAt: number; wakes: number; held: number } | undefined
129/** The key of the last swarm whose stand-down was toasted, so a teammate of it restarted later does not toast it again; cleared when a teammate is spawned. */
130let stoodDown: string | undefined
131let hasStallFired = false
132/** The open claims the stall watchdog has nudged, as `<holder> <claim key> <when it was sent>`; a re-sent claim is a new one. */
133const nudged = new Set<string>()
134/** When the stall watchdog last nudged each teammate, by bare team name. */
135const nudgedAt = new Map<string, number>()
136let openTasks: number | null = null
137let claimMin = DEFAULT_CLAIM_MIN
138let sawDoneOrHandoff = false
139/** When each teammate last sent a `[DONE]`, to anyone, by bare team name. */
140const doneAt = new Map<string, number>()
141/** When each teammate last sent a `[CLAIM]`, by bare team name. */
142const claimAt = new Map<string, number>()
143const firedClaimAlerts = new Set<string>()
144/** When the claim board was last cleared because its team ended; logged claims before it are not replayed. */
145let claimsSince = -Infinity
146/** Each teammate's latest `[WAIT]`, a path or a time, by bare team name. */
147const waits = new Map<string, Wait>()
148const openTurns = new Map<string, number>()
149/** The plugin holding `/swarm` when this plugin's registration of it was refused. */
150let swarmTakenBy: string | undefined
151/** Whether the user is still to be asked this session how to live with the other `/swarm`. */
152let isConflictAskDue = false
153const KEEP_BOTH = "Keep both: I'll use /swarmctl"
154const SHOW_REMOVE = 'Show me how to remove the other plugin'
155const ASK_AGAIN = 'Ask me again next session'
156const sendsBy = new Map<string, number>()
157/** The texts of this plugin's own sends still in flight, with how many of each. */
158const modSending = new Map<string, number>()
159const scene = new LiveScene()
160/** The file each teammate last showed, by bare team name. */
161const lastFile = new Map<string, string>()
162/** When each teammate's read of a file was last logged, by `<name> <shown>`. */
163const readLoggedAt = new Map<string, number>()
164/** The order stamp of the session's latest teammate-to-teammate send. */
165let lastStamp = 0
166/** Later claimants already told a target is taken, as `<name> <claim key>`. */
167const askedTaken = new Set<string>()
168/** Claimants already told a build or research slice is theirs, as `<name> <role> <target>`. */
169const ackedClaims = new Set<string>()
170/** Releases already applied or answered, as `<name> <claim key>`: a copy of the same release to another teammate is not answered. */
171const releasedBy = new Set<string>()
172/** The teammates whose leaving is logged (or had ended before this load), by agent id. */
173const leftLogged = new Set<string>()
174/** Each teammate's tool calls, by bare team name: how many, when its last ACT line went out, and the one waiting to. */
175const acts = new Map<string, { calls: number; at: number; pending?: LogEntry }>()
176/** The transcript tail shown for the agent the live pane is filtered to, by agent id: when it was read and its lines. */
177const transcripts = new Map<string, { at: number; lines: string[] }>()
178/** Transcripts being read now, by agent id. */
179const readingTranscript = new Set<string>()
180/** How many transcript lines the live pane shows under the stage. */
181const TRANSCRIPT_LINES = 6
182/** How long a shown transcript stands before it is read again. */
183const TRANSCRIPT_MS = 2_000
184/** When each writer was last warned about each claimed file, by `<writer> <path>`. */
185const warnedWrite = new Map<string, number>()
186
187/** Whether a name can be a teammate's: a teammate the roster knows, or a name it knows no agent by. */
188function isMate(name: string): boolean {
189 return roster.hasTeammate(name) || ![...roster.agents.values()].some(a => bareName(a.name) === name)
190}
191
192/** What the team rules read from the roster: each agent's name, teammate flag, status and spawn. */
193function rosterVersion(): string {
194 let out = ''
195 for (const a of roster.agents.values()) out += a.name + (a.isTeammate ? '+' : '-') + a.status + (a.spawnedAt ?? '') + ';'
196 return out
197}
198
199/** Whether every teammate going by `name` had ended at `at`; false when none goes by it or one is live. */
200function wasStoppedAt(name: string, at: number): boolean {
201 const mates = [...roster.agents.values()].filter(a => a.isTeammate && bareName(a.name) === name)
202 return mates.length > 0 && mates.every(a => ENDED.includes(a.status) && (a.statusAt ?? -Infinity) <= at)
203}
204
205/**
206 * Whether a teammate joins a team on a peer line it receives at `at`: not when it had stopped by then, nor when it was
207 * dormant: started over `IDLE_ENDED_H` hours before and without a message of its own in those hours.
208 */
209function canJoinByReceiving(name: string, at: number): boolean {
210 if (wasStoppedAt(name, at)) return false
211 const started = roster.startedAt(name)
212 const window = IDLE_ENDED_H * 3_600_000
213 return started === undefined || at - started <= window || (roster.lastMessageAt.get(name) ?? -Infinity) >= at - window
214}
215
216/** Whether a teammate going by `name` had started and not yet ended at `at`. */
217function wasLiveAt(name: string, at: number): boolean {
218 return [...roster.agents.values()].some(a => a.isTeammate && bareName(a.name) === name && (a.spawnedAt ?? a.firstSeenAt ?? -Infinity) <= at
219 && (!ENDED.includes(a.status) || (a.statusAt ?? Infinity) > at))
220}
221
222/**
223 * The current team: the latest whose teammates messaged each other (see `teamsOf`), joined by every teammate spawned after
224 * it formed while one of its teammates was live, in spawn order, though it only writes to the lead.
225 */
226function currentTeam(): Team | undefined {
227 const team = scene.team(isMate, rosterVersion(), canJoinByReceiving)
228 if (team === undefined) return undefined
229 const joiners = [...roster.agents.values()]
230 .filter(a => a.isTeammate && a.spawnedAt !== undefined && a.spawnedAt > team.firstAt && !team.names.includes(bareName(a.name))
231 && team.names.some(n => wasLiveAt(n, a.spawnedAt!)))
232 .sort((a, b) => a.spawnedAt! - b.spawnedAt!)
233 .map(a => bareName(a.name))
234 return joiners.length === 0 ? team : { ...team, names: [...team.names, ...new Set(joiners)] }
235}
236
237/** Whether the current team is a swarm: its teammates have messaged each other and one of them has not ended. */
238function isSwarm(): boolean {
239 return currentTeam()?.names.some(n => roster.isLiveTeammate(n)) === true
240}
241
242/** The latest status of the teammate going by `name` (bare team name), or undefined. */
243function statusOf(name: string): string | undefined {
244 return [...roster.agents.values()].filter(a => a.isTeammate && bareName(a.name) === name).pop()?.status
245}
246
247/** Whether the teammate going by `name` sent a `[DONE]` since its latest spawn and no `[CLAIM]` after it. */
248function sentDone(name: string): boolean {
249 const spawnedAt = [...roster.agents.values()].filter(a => a.isTeammate && bareName(a.name) === name).pop()?.spawnedAt ?? -Infinity
250 const at = doneAt.get(name)
251 return at !== undefined && at >= spawnedAt && !((claimAt.get(name) ?? -Infinity) >= at)
252}
253
254/**
255 * The status line while the current team is a swarm: `◇ swarm 3 live · 1 done`, live counting its teammates that have not
256 * ended, done those that sent a `[DONE]` and no `[CLAIM]` after it (live or not), with `· 1 failed` when any failed.
257 */
258function swarmStatus(): string | undefined {
259 if (!isSwarm()) return undefined
260 let live = 0
261 let done = 0
262 let failed = 0
263 for (const n of teamNames()) {
264 if (roster.isLiveTeammate(n)) live++
265 else if (statusOf(n) === 'failed') failed++
266 if (sentDone(n)) done++
267 }
268 return `◇ swarm ${live} live · ${done} done${failed > 0 ? ` · ${failed} failed` : ''}`
269}
270
271/** Pins the swarm's status line, or clears it, when it changed. */
272function showStatus($: EngineInterface) {
273 const text = swarmStatus()
274 if (text === shownStatus) return
275 shownStatus = text
276 $.ui.status(text)
277}
278
279/**
280 * When a team started: the first spawn of its teammates, each the latest of its name spawned by the team's last activity
281 * (a name an earlier swarm used counts from its new spawn, also one spawned after the first peer message), and never later
282 * than that first peer message.
283 */
284function teamStart(team: Team): number {
285 const until = lastActivityOf(team.names, team.lastPeerAt)
286 const starts = team.names.map(n => {
287 const at = [...roster.agents.values()].filter(a => a.isTeammate && bareName(a.name) === n).map(a => a.spawnedAt ?? a.firstSeenAt).filter((t): t is number => t !== undefined && t <= until)
288 return at.length > 0 ? Math.max(...at) : team.firstAt
289 })
290 return Math.min(team.firstAt, ...starts)
291}
292
293/**
294 * Follows the current swarm and, once its last teammate has ended, toasts its totals once:
295 * `swarm stood down: 4 agents · 52 messages · 12m · lead woken 3 (0.8/agent), held 18`; the mod's own messages are not counted.
296 * Its time runs from the team's start (see `teamStart`) to its last activity, the span the ENDED header shows as `ran`.
297 */
298function watchStandDown($: EngineInterface) {
299 const team = currentTeam()
300 if (isSwarm() && team !== undefined) {
301 const key = '@' + team.firstAt
302 if (key === stoodDown) return
303 if (standing?.key !== key) standing = { key, names: team.names, from: teamStart(team), lastPeerAt: team.lastPeerAt, wakes: policy.wakes, held: policy.held }
304 standing.names = team.names
305 standing.lastPeerAt = team.lastPeerAt
306 return
307 }
308 const s = standing
309 if (s === undefined || s.names.some(n => roster.isLiveTeammate(n))) return
310 standing = undefined
311 stoodDown = s.key
312 const messages = log.entries.filter(e => e.ts >= s.from && e.from !== MOD && (s.names.includes(e.from) || s.names.includes(e.to))).length
313 const wakes = policy.wakes - s.wakes
314 $.ui.toast(`swarm stood down: ${s.names.length} agents · ${messages} messages · ${ago(lastActivityOf(s.names, s.lastPeerAt) - s.from)} · lead woken ${wakes} (${(wakes / s.names.length).toFixed(1)}/agent), held ${policy.held - s.held}`, { timeoutMs: STAND_DOWN_TOAST_MS })
315}
316
317/**
318 * The team the pane shows: the current team, unless every one of its teammates has ended and a live teammate outside it is
319 * running, pending or waiting, or started after its last peer message; then none, so the live teammates show as a new team.
320 */
321function shownTeam(): Team | undefined {
322 const team = currentTeam()
323 if (team === undefined || !isTeamOver()) return team
324 const isNew = (a: RosterEntry) => a.isTeammate && !team.names.includes(bareName(a.name)) && !roster.isShownEnded(a)
325 && (a.status === 'running' || a.status === 'pending' || a.status === 'waiting' || (roster.startedAt(a.name) ?? -Infinity) > team.lastPeerAt)
326 return [...roster.agents.values()].some(isNew) ? undefined : team
327}
328
329/** The current team's names: the shown team's, else the teammates that have not ended. */
330function teamNames(): string[] {
331 const team = shownTeam()
332 if (team !== undefined) return team.names
333 const names = [...roster.agents.values()].filter(a => a.isTeammate && !roster.isShownEnded(a)).map(a => bareName(a.name))
334 return [...new Set(names)]
335}
336
337/** The model family of the live agent going by `name`. */
338function modelOf(name: string): ModelFamily | undefined {
339 const family = shortModel(roster.liveEntry(name)?.model).split(' ')[0]
340 return family === 'opus' || family === 'sonnet' || family === 'haiku' || family === 'fable' ? family : undefined
341}
342
343/** Whether the current team (the latest whose teammates messaged each other) exists and every one of its teammates has ended. */
344function isTeamOver(): boolean {
345 const team = currentTeam()
346 return team !== undefined && team.names.every(n => roster.hasTeammate(n) && !roster.isLiveTeammate(n))
347}
348
349/** The current team's last activity: its last peer message, or a later message or idle notice from one of its teammates. */
350function lastActivityOf(names: readonly string[], lastPeerAt: number): number {
351 return Math.max(lastPeerAt, ...names.map(n => Math.max(roster.lastMessageAt.get(n) ?? -Infinity, roster.idle.get(n)?.lastAt ?? -Infinity)))
352}
353
354/**
355 * What the live pane draws: the shown team from its start (see `teamStart`), else the live teammates from their start; a
356 * team whose teammates have all ended with its clock held at its last activity.
357 */
358function liveSource(): LiveSource {
359 const team = shownTeam()
360 const names = teamNames()
361 const starts = names.map(n => roster.startedAt(n)).filter((t): t is number => t !== undefined)
362 const from = team !== undefined ? teamStart(team) : starts.length > 0 ? Math.min(...starts) : loadedAt
363 const ended = team !== undefined && isTeamOver() ? { endedAt: lastActivityOf(team.names, team.lastPeerAt) } : {}
364 return { scene: scene.scene(names, from, modelOf, stallMin * 60_000), title: names.length > 0 ? runTitle(names) : 'no team yet', from, ...ended }
365}
366
367function logPath(): string | null {
368 return cwd === null ? null : cwd + '/.swarm/log.jsonl'
369}
370
371function rosterPath(): string | null {
372 return cwd === null ? null : cwd + '/.swarm/roster.json'
373}
374
375/** A receiver's bare team name; a code name no agent goes by as its team name is read as the teammate that took it. */
376function addressOf(to: string): string {
377 const name = bareName(to) || to
378 return [...roster.agents.values()].some(a => bareName(a.name) === name) ? name : roster.resolve(name)
379}
380
381/** Records one message, queues it for the file and the wake policy, and asks for a redraw. */
382async function note($: EngineInterface, m: { from: string; to: string; text: string; via: Via; fromId?: string; toId?: string; stamp?: number }) {
383 const ts = await $.clock.now()
384 if (roster.announce(m.from, m.text, m.via)) {
385 markRosterDirty($)
386 const other = roster.clashWith(m.from)
387 if (other !== undefined && m.fromId !== undefined && m.via !== 'receive') void tellClash($, bareName(m.from), m.fromId, other)
388 }
389 roster.noteMessage(m.from, ts)
390 const claim = claimOf(m.text)
391 const waitPath = waitPathOf(m.text)
392 const until = waitUntilOf(m.text)
393 if ((waitPath !== undefined || until !== undefined) && m.via !== 'receive' && !isLeadAddress(m.from)) {
394 const name = bareName(m.from)
395 const since = Math.max(roster.idle.get(name)?.lastAt ?? -Infinity, roster.liveEntry(name)?.spawnedAt ?? -Infinity)
396 const prior = waits.get(name)
397 const wokenFor = prior?.path === waitPath && prior?.until === until ? prior?.wokenFor : undefined
398 waits.set(name, { ...(waitPath === undefined ? { until, since: 0 } : { path: waitPath, since: since > -Infinity ? since : ts }), ...(wokenFor === undefined ? {} : { wokenFor }) })
399 markRosterDirty($)
400 }
401 const entry = log.record({ ...m, from: bareName(m.from) || m.from, to: addressOf(m.to), ts })
402 if (!entry) return
403 noteClaims($, m, claim, ts)
404 if (session) entry.session = session
405 if (m.stamp !== undefined) entry.stamp = m.stamp
406 if (claim !== undefined && !isLeadAddress(m.from) && bareName(m.from) !== MOD) entry.claim = claim
407 if ((entry.type === 'DONE' || entry.type === 'HANDOFF') && !isLeadAddress(entry.from)) sawDoneOrHandoff = true
408 if (entry.type === 'DONE') doneAt.set(entry.from, entry.ts)
409 if (claim !== undefined) claimAt.set(entry.from, entry.ts)
410 lastActivityAt = ts
411 hasStallFired = false
412 unwritten.push(entry)
413 scene.push(entry)
414 policy.offer(entry, m.text)
415 scheduleFlush($)
416 $.ui.invalidate('ui.render')
417 void liveEvent($)
418 if (entry.from !== entry.to && [entry.from, entry.to].every(n => isTeammateName(n) && isMate(n))) liveActivity($)
419}
420
421/**
422 * Applies a logged message's claim, release, verdict and report to the claims board, as the looks apply its log line; a
423 * delivery of a send already logged applies nothing, so a broadcast `[CLAIM]` taken late never undoes a release. A release
424 * also forgets that its sender was told those slices were its, so claiming one again is answered again; a release hands its
425 * slices on (see `handOver`), a report never does. A release naming a slice others hold and its sender does not is answered once: it
426 * released nothing.
427 * A report or review claim that ends its sender's wait on a slice it was told is taken (see `ClaimBoard.isActive`) is answered.
428 */
429function noteClaims($: EngineInterface, m: { from: string; text: string; via: Via; fromId?: string; stamp?: number }, claim: ClaimRef | undefined, ts: number) {
430 if (isLeadAddress(m.from) || bareName(m.from) === MOD) return
431 const name = bareName(m.from)
432 const waiting = board.openClaims(name).filter(c => askedTaken.has(name + ' ' + c.key))
433 if (claim !== undefined) {
434 if (board.claim(m.from, claim, m.via !== 'receive', { stamp: m.stamp, at: ts })) markRosterDirty($)
435 releasedBy.delete(name + ' ' + claim.role + ' ' + board.canonical(claim).target)
436 if (m.via !== 'receive' && m.fromId !== undefined) void tellTaken($, m.from, m.fromId, claim)
437 }
438 const released = board.releasing(m.from, m.text)
439 if (released.length > 0) {
440 for (const k of [...ackedClaims]) {
441 if (released.some(c => k.startsWith(`${name} ${c.role} `) && sameTarget(k.slice(name.length + c.role.length + 2), c.target))) ackedClaims.delete(k)
442 }
443 for (const c of released) releasedBy.add(name + ' ' + c.key)
444 handOver($, released)
445 markRosterDirty($)
446 } else if (m.via !== 'receive' && m.fromId !== undefined) {
447 for (const c of board.heldByOthers(m.from, m.text)) {
448 if (releasedBy.has(name + ' ' + c.key)) continue
449 releasedBy.add(name + ' ' + c.key)
450 const holder = c.by.find(n => board.isActive(c, n) && board.heldBefore(n, c) === undefined) ?? c.by[0]!
451 void sendTo($, m.fromId, name, `[ASK] you hold no ${c.key}: ${opened(holder)}) does. Your release released nothing.`)
452 }
453 }
454 const verdict = reviewOf(m.text)
455 if (verdict !== undefined && board.review(m.from, verdict)) markRosterDirty($)
456 const type = typeOf(m.text)
457 if (type !== undefined && REPORTS.includes(type) && board.report(m.from, type, m.via !== 'receive', m.text)) markRosterDirty($)
458 for (const c of waiting) {
459 if (released.includes(c) || (claim !== undefined && claim.role !== 'review') || board.openClaims(name).some(o => o.key === c.key) || m.via === 'receive' || m.fromId === undefined) continue
460 askedTaken.delete(name + ' ' + c.key)
461 void sendTo($, m.fromId, name, `[ASK] you no longer wait for ${c.key}: a report ends a wait. Claim it again to wait.`)
462 }
463}
464
465/**
466 * Tells the claimant who now holds each `released` build or research slice first that it is theirs, once; who was told that
467 * slice was taken is forgotten, so a later claim on it is answered again.
468 */
469function handOver($: EngineInterface, released: readonly Claim[]) {
470 for (const c of released) {
471 if (c.role !== 'build' && c.role !== 'research') continue
472 const next = board.handOff(c)
473 const entry = next === undefined ? undefined : roster.liveEntry(next)
474 if (next === undefined || entry === undefined || ackedClaims.has(next + ' ' + c.key)) continue
475 ackedClaims.add(next + ' ' + c.key)
476 for (const k of [...askedTaken]) if (k.endsWith(' ' + c.key)) askedTaken.delete(k)
477 void sendTo($, entry.id, next, `${c.key} is yours.`)
478 }
479}
480
481/** Counts an idle notification and writes it to the log file as `type: "IDLE"`; it is no message and wakes nobody. */
482async function noteIdle($: EngineInterface, from: string, to: string, reason: string | undefined, text: string) {
483 const ts = await $.clock.now()
484 const name = bareName(from) || from
485 roster.noteIdle(name, reason, ts)
486 const entry: LogEntry = { ts, from: name, to: bareName(to) || to, summary: firstLine(text), length: text.length, type: 'IDLE', via: 'receive' }
487 if (reason !== undefined) entry.idleReason = reason
488 if (session) entry.session = session
489 unwritten.push(entry)
490 scene.push(entry)
491 markRosterDirty($)
492 void liveEvent($)
493}
494
495/**
496 * Shows a teammate's file tool call on its card when the file changes, and logs it as one `type: "FILE"` line: an edit or
497 * write always, a read only when the teammate has not read that file in the last `READ_LOG_MS`.
498 */
499async function noteFile($: EngineInterface, agentId: string, shown: string) {
500 const a = roster.agents.get(agentId)
501 if (a === undefined || !a.isTeammate) return
502 const name = bareName(a.name)
503 if (lastFile.get(name) === shown) return
504 lastFile.set(name, shown)
505 const ts = await $.clock.now()
506 const entry: LogEntry = { ts, from: name, to: '', summary: shown, length: 0, type: 'FILE', via: 'tool' }
507 if (session) entry.session = session
508 scene.push(entry)
509 const key = name + ' ' + shown
510 if (!shown.startsWith('◦') || ts - (readLoggedAt.get(key) ?? -Infinity) >= READ_LOG_MS) {
511 if (shown.startsWith('◦')) readLoggedAt.set(key, ts)
512 unwritten.push(entry)
513 scheduleFlush($)
514 }
515 $.ui.invalidate('ui.render')
516}
517
518/**
519 * Counts a teammate's tool call and shows it on its card as an ACT line (logged too), at most one per `ACT_EVERY_MS`; a call
520 * inside that time waits for its end, the latest one winning.
521 */
522async function noteAction($: EngineInterface, agentId: string, action: string) {
523 const a = roster.agents.get(agentId)
524 if (a === undefined || !a.isTeammate) return
525 const name = bareName(a.name)
526 const ts = await $.clock.now()
527 const s = acts.get(name) ?? { calls: 0, at: -Infinity }
528 acts.set(name, s)
529 s.calls++
530 const entry: LogEntry = { ts, from: name, to: '', summary: action, length: 0, type: 'ACT', via: 'tool', calls: s.calls }
531 if (session) entry.session = session
532 if (ts - s.at >= ACT_EVERY_MS) return sendAction($, s, entry)
533 if (s.pending === undefined) {
534 $.clock.after(s.at + ACT_EVERY_MS - ts, () => {
535 const next = s.pending
536 s.pending = undefined
537 if (next !== undefined) sendAction($, s, next)
538 })
539 }
540 s.pending = entry
541}
542
543/**
544 * Logs a refused spawn as one `type: "REFUSED"` line from its spawner (the lead, or the teammate whose loop spawned it) to
545 * the agent's name or description, the reason's first line as its summary; look A's message list shows it.
546 */
547async function noteRefusal($: EngineInterface, e: AgentSpawnInput, deny: string) {
548 const parent = e.parentAgentId === undefined ? undefined : roster.agents.get(e.parentAgentId)
549 if (e.parentAgentId !== undefined && parent?.isTeammate !== true) return
550 const entry: LogEntry = { ts: await $.clock.now(), from: parent === undefined ? LEAD : bareName(parent.name), to: e.name || e.description, summary: firstLine(deny), length: deny.length, type: 'REFUSED', via: 'tool' }
551 if (session) entry.session = session
552 scene.push(entry)
553 unwritten.push(entry)
554 scheduleFlush($)
555 $.ui.invalidate('ui.render')
556}
557
558/** Logs a teammate joining or leaving as one `type: "JOIN"` or `"LEFT"` line; the looks show it, it is no message. */
559async function noteMove($: EngineInterface, name: string, type: 'JOIN' | 'LEFT', summary: string) {
560 const entry: LogEntry = { ts: await $.clock.now(), from: name, to: '', summary, length: 0, type, via: 'tool' }
561 if (session) entry.session = session
562 scene.push(entry)
563 unwritten.push(entry)
564 scheduleFlush($)
565 $.ui.invalidate('ui.render')
566 void liveEvent($)
567}
568
569/** Logs a LEFT line for each teammate that has ended (completed, failed or killed) since its last check. */
570async function noteLeaves($: EngineInterface) {
571 for (const a of roster.agents.values()) {
572 if (!a.isTeammate || !ENDED.includes(a.status) || leftLogged.has(a.id)) continue
573 leftLogged.add(a.id)
574 await noteMove($, bareName(a.name), 'LEFT', a.status)
575 }
576}
577
578function sendAction($: EngineInterface, s: { at: number }, entry: LogEntry) {
579 s.at = entry.ts
580 scene.push(entry)
581 unwritten.push(entry)
582 scheduleFlush($)
583 $.ui.invalidate('ui.render')
584}
585
586function scheduleFlush($: EngineInterface) {
587 if (isFlushScheduled) return
588 isFlushScheduled = true
589 $.clock.after(FLUSH_MS, () => {
590 isFlushScheduled = false
591 void flush($)
592 })
593}
594
595/** Appends unwritten entries to the JSONL file and rewrites roster.json when it changed. */
596async function flush($: EngineInterface) {
597 const path = logPath()
598 if (path !== null && unwritten.length > 0) {
599 const batch = unwritten
600 unwritten = []
601 try {
602 const r = await $.process.run(
603 ['/bin/sh', '-c', 'mkdir -p "$(dirname "$1")" && cat >> "$1"', 'swarm-log', path],
604 { stdin: jsonl(batch), timeoutMs: 10_000 },
605 )
606 if (r.exitCode !== 0) $.ui.log('log append failed: ' + r.stderr.trim())
607 } catch (err) {
608 $.ui.log('log append failed: ' + String(err))
609 }
610 }
611 const rpath = rosterPath()
612 if (rpath !== null && isRosterDirty) {
613 isRosterDirty = false
614 try {
615 const json = { ...roster.toJSON(await $.clock.now(), session || undefined), stamp: lastStamp, askedTaken: [...askedTaken], ackedClaims: [...ackedClaims], deliverables: board.deliverables, claims: board.all(), unclaimedTasks: board.unclaimedTasks, firedAlerts: [...firedClaimAlerts], ...(claimsSince > -Infinity ? { claimsSince } : {}), workflows: Object.fromEntries(roster.workflowNames), waits: Object.fromEntries(waits) }
616 await $.fs.write(rpath, JSON.stringify(json, null, 2) + '\n')
617 } catch (err) {
618 $.ui.log('roster write failed: ' + String(err))
619 }
620 }
621}
622
623/** Reads the log file's tail and roster.json once per load, so the pane shows what came before a reload. */
624async function hydrate($: EngineInterface) {
625 if (isHydrated) return
626 isHydrated = true
627 const rpath = rosterPath()
628 const lpath = logPath()
629 try {
630 if (rpath !== null && (await $.fs.exists(rpath))) {
631 const json = JSON.parse(await $.fs.read(rpath)) as { session?: unknown; stamp?: unknown; askedTaken?: unknown; ackedClaims?: unknown; firedAlerts?: unknown; claimsSince?: unknown; workflows?: unknown; waits?: unknown }
632 roster.hydrate(json, session, await $.clock.now())
633 for (const a of roster.agents.values()) if (a.isTeammate && ENDED.includes(a.status)) leftLogged.add(a.id)
634 if (json.session === session && json.workflows && typeof json.workflows === 'object') {
635 for (const [id, name] of Object.entries(json.workflows)) if (typeof name === 'string') roster.workflowNames.set(id, name)
636 }
637 if (json.session === session) {
638 if (typeof json.stamp === 'number') lastStamp = Math.max(lastStamp, json.stamp)
639 if (Array.isArray(json.askedTaken)) for (const k of json.askedTaken) if (typeof k === 'string') askedTaken.add(k)
640 if (Array.isArray(json.ackedClaims)) for (const k of json.ackedClaims) if (typeof k === 'string') ackedClaims.add(k)
641 board.restore(json)
642 if (typeof json.claimsSince === 'number') claimsSince = json.claimsSince
643 if (Array.isArray(json.firedAlerts)) for (const k of json.firedAlerts) if (typeof k === 'string') firedClaimAlerts.add(k)
644 if (json.waits && typeof json.waits === 'object') {
645 for (const [n, w] of Object.entries(json.waits as Record<string, Partial<Wait>>)) if ((typeof w?.path === 'string' || typeof w?.until === 'number') && typeof w.since === 'number') waits.set(n, w as Wait)
646 }
647 }
648 }
649 } catch (err) {
650 $.ui.log('roster read failed: ' + String(err))
651 }
652 try {
653 if (lpath !== null && (await $.fs.exists(lpath))) {
654 const r = await $.process.run(['tail', '-n', String(MEMORY_CAP), lpath], { timeoutMs: 10_000 })
655 if (r.exitCode === 0) {
656 const lines = parseLog(r.stdout)
657 hydrateLog(log, roster, lines, session)
658 hydrateClaims(board, lines, session, claimsSince)
659 for (const e of lines) if (e.session === session) {
660 scene.push(e)
661 if (e.type === 'DONE') doneAt.set(e.from, e.ts)
662 if (claimOfLine(e) !== undefined) claimAt.set(e.from, e.ts)
663 if (typeof e.stamp === 'number') lastStamp = Math.max(lastStamp, e.stamp)
664 }
665 }
666 }
667 } catch (err) {
668 $.ui.log('log read failed: ' + String(err))
669 }
670 $.ui.invalidate('ui.render')
671}
672
673function markRosterDirty($: EngineInterface) {
674 isRosterDirty = true
675 scheduleFlush($)
676 $.ui.invalidate('ui.render')
677}
678
679/** Sets the wake mode and stores it twice: as this session's, which a reload restores, and as `wakeMode`, which a new session starts with. */
680async function setWakeMode($: EngineInterface, mode: WakeMode) {
681 policy.setMode(mode, await $.clock.now())
682 await $.store.set('wakeMode', mode)
683 await $.store.set(WAKE_KEY + session, mode)
684}
685
686/** Drops the queued messages of a current team whose teammates have all ended, then submits a queued wake when the policy says it is due and the lead is idle. */
687async function tryWake($: EngineInterface) {
688 const now = await $.clock.now()
689 const team = currentTeam()
690 if (team !== undefined && isTeamOver()) policy.pending = policy.pending.filter(e => !team.names.includes(e.from))
691 const text = policy.due(now, roster.leadBusy)
692 if (text === null) return
693 submitWake($, text, now)
694}
695
696/** Starts a framed plugin prompt without awaiting it: it resolves only once the lead's turn starts. Counted as a wake at `now`, in the band and in the looks. */
697function submitWake($: EngineInterface, text: string, now: number) {
698 policy.inFlight = true
699 policy.wakes++
700 scene.wake(now)
701 $.prompt.submit({ text }).then(
702 () => {
703 policy.inFlight = false
704 },
705 (err: unknown) => {
706 policy.inFlight = false
707 $.ui.log('wake not submitted: ' + String(err))
708 },
709 )
710}
711
712async function pollAgents($: EngineInterface) {
713 try {
714 const rows = await $.agent.list()
715 const mapped: AgentRow[] = rows.map(r => ({
716 id: r.id,
717 name: r.name,
718 type: r.type,
719 status: r.status,
720 teammateId: r.teammateId,
721 description: r.description,
722 parentId: r.parentId,
723 }))
724 if (roster.merge(mapped, await $.clock.now())) markRosterDirty($)
725 await noteLeaves($)
726 } catch (err) {
727 $.ui.log('agent list failed: ' + String(err))
728 }
729}
730
731/** Counts open tasks in this session's team task list; null when it cannot be read. */
732async function refreshTasks($: EngineInterface) {
733 try {
734 const configDir = (await $.env.get('CLAUDE_CONFIG_DIR')) ?? ((await $.env.get('HOME')) ?? '') + '/.claude'
735 const id = await $.session.id()
736 const dir = configDir + '/tasks/session-' + id.slice(0, 8)
737 if (!(await $.fs.exists(dir))) {
738 openTasks = null
739 return
740 }
741 const files = (await $.fs.list(dir)).filter(f => f.kind === 'file' && f.name.endsWith('.json')).slice(0, MAX_TASK_FILES)
742 const texts: string[] = []
743 for (const f of files) texts.push(await $.fs.read(dir + '/' + f.name))
744 openTasks = openTaskCount(texts)
745 board.setTasks(parseTasks(texts), owner => {
746 const name = roster.resolve(owner)
747 return roster.isLiveTeammate(name) ? name : undefined
748 })
749 } catch {
750 openTasks = null
751 }
752}
753
754/** The periodic pass: agent status, tasks, stale turns, wakes, the stall watchdog and the clock in the band. */
755async function tick($: EngineInterface) {
756 ticks++
757 const now = await $.clock.now()
758 if (isSwarm()) swarmSeenAt = now
759 if (ticks % LIST_EVERY_TICKS === 0) await pollAgents($)
760 showStatus($)
761 watchStandDown($)
762 if (ticks % TASKS_EVERY_TICKS === 1) await refreshTasks($)
763 for (const [id, at] of openTurns) if (now - at > STALE_TURN_MS) openTurns.delete(id)
764 roster.leadBusy = openTurns.size > 0
765 if (roster.activeCount() > 0) {
766 lastActivityAt = now
767 hasStallFired = false
768 }
769 await tryWake($)
770 const openClaims = [...board.claimants()].filter(n => roster.isLiveTeammate(n)).reduce((sum, n) => sum + board.openClaims(n).length, 0)
771 const stalled = isSwarm() && isStalled({
772 now,
773 lastActivityAt,
774 stallMs: stallMin * 60_000,
775 activeAgents: roster.activeCount(),
776 liveAgents: roster.liveCount(),
777 openTasks,
778 openClaims,
779 leadBusy: roster.leadBusy || policy.inFlight,
780 alreadyFired: hasStallFired || stallMin <= 0,
781 })
782 if (stalled) {
783 hasStallFired = true
784 const nudges = await nudgeClaimHolders($)
785 if (nudges.delivered > 0) lastActivityAt = now
786 if (nudges.delivered > 0 || nudges.coolingDown > 0) hasStallFired = false
787 else submitWake($, stallText(stallMin, openTasks, openClaims), now)
788 }
789 expireEndedTeam($, now)
790 checkClaims($, now)
791 checkWorkDone($, now)
792 if (ticks % WAIT_EVERY_TICKS === 0) await checkWaits($)
793 if (roster.agents.size > 0 || log.total > 0) $.ui.invalidate('ui.render')
794}
795
796/** The band's line: counts, wake mode, then the current team's announced code names. */
797function bandLine(now: number): string {
798 const names = namesText(roster, teamNames())
799 const dup = board.duplicates().map(c => c.target || c.role)
800 const missing = sawDoneOrHandoff || board.deliverables.length > 0 ? board.missingBuilders() : []
801 const warn = [...(missing.length ? ['no builder: ' + missing.join(', ')] : []), ...(dup.length ? ['dup claim: ' + dup.join(', ')] : [])]
802 return `${bandText(roster, log, now)} · wake: ${policy.mode} · wakes ${policy.wakes} · held ${policy.held}${warn.length ? ' · ⚠ ' + warn.join(' · ') : ''}${names ? ' · ' + names : ''}`
803}
804
805/**
806 * Teammates that are running or have sent a message, hold no claim, sent no `[CLAIM]` since their spawn (one released
807 * since counts as claimed), and have not ended, each with when it started.
808 */
809function unclaimedWorkers(): UnclaimedWorker[] {
810 const claimants = board.claimants()
811 const out: UnclaimedWorker[] = []
812 for (const a of roster.agents.values()) {
813 if (!a.isTeammate || ENDED.includes(a.status)) continue
814 const name = bareName(a.name)
815 const working = a.status === 'running' || (log.sent.get(name) ?? 0) > 0
816 const claimedAt = claimAt.get(name)
817 const hasClaimed = claimants.has(name) || (claimedAt !== undefined && claimedAt >= (a.spawnedAt ?? -Infinity))
818 if (working && !hasClaimed) out.push({ label: roster.label(a.name), startedAt: roster.startedAt(a.name) })
819 }
820 return out
821}
822
823/**
824 * Once every teammate has ended, or once every teammate of the current team has (once per team), clears the claims,
825 * verdicts, deliverables, nudges, waits and fired alerts.
826 */
827function expireEndedTeam($: EngineInterface, now: number) {
828 const team = currentTeam()
829 const key = team === undefined ? undefined : `@${team.firstAt}/${Math.max(...[...roster.agents.values()].filter(a => a.isTeammate && team.names.includes(bareName(a.name))).map(a => a.spawnedAt ?? 0))}`
830 const teamOver = key !== undefined && key !== clearedTeam && isTeamOver()
831 if (teamOver) clearedTeam = key
832 if (!board.hasMessageClaims() || !(roster.isTeamEnded() || teamOver)) return
833 board.clear()
834 askedTaken.clear()
835 ackedClaims.clear()
836 releasedBy.clear()
837 firedClaimAlerts.clear()
838 nudged.clear()
839 nudgedAt.clear()
840 waits.clear()
841 sawDoneOrHandoff = false
842 claimsSince = now
843 markRosterDirty($)
844}
845
846/** Wakes the lead once per claim condition, once the team is a swarm; conditions that hold together go out as one wake. */
847function checkClaims($: EngineInterface, now: number) {
848 if (!isSwarm()) return
849 const alerts = claimAlerts({
850 now,
851 claimMs: claimMin * 60_000,
852 sawDoneOrHandoff,
853 missingBuilders: board.missingBuilders(),
854 unclaimedWorkers: unclaimedWorkers(),
855 }).filter(a => !firedClaimAlerts.has(a.key))
856 if (alerts.length === 0 || roster.leadBusy || policy.inFlight) return
857 for (const a of alerts) firedClaimAlerts.add(a.key)
858 markRosterDirty($)
859 submitWake($, claimWakeText(alerts, board.deliverables.length > 0), now)
860}
861
862/** Whether the `[DONE]` line `e` names `target`, or names none of its sender's build and research claims while one of them is on `target`. */
863function doneNames(e: LogEntry, target: string): boolean {
864 const subject = e.summary.replace(/^\s*\[DONE\]\s*/i, '')
865 if (mentionsTarget(subject, target)) return true
866 const mine = board.all().filter(c => c.by.includes(e.from) && (c.role === 'build' || c.role === 'research'))
867 return !mine.some(c => mentionsTarget(subject, c.target)) && mine.some(c => targetMatches(c.target, target))
868}
869
870/**
871 * Wakes the lead once the swarm's work is done: a `[DONE]` from the team names every deliverable (with none declared, every
872 * build and research claim), no claim but a review claim is open, no teammate's latest report or review verdict is a `[BLOCK]`, and every live
873 * teammate of the current team is idle (an idle notice after its last message). Once per last message (`firedAlerts` in roster.json), so a new claim or message re-arms it.
874 */
875function checkWorkDone($: EngineInterface, now: number) {
876 const team = currentTeam()
877 const key = 'work-done@' + log.lastAt
878 if (team === undefined || !isSwarm() || firedClaimAlerts.has(key) || roster.leadBusy || policy.inFlight) return
879 if (team.names.some(n => roster.isLiveTeammate(n) && (roster.idleSince(n) === undefined || board.openClaims(n).some(c => c.role !== 'review')))) return
880 if ([...board.reports.values()].some(r => r.type === 'BLOCK') || [...board.reviews.values()].some(s => [...s.values()].includes('block'))) return
881 const dones = log.entries.filter(e => e.type === 'DONE' && e.ts >= claimsSince && team.names.includes(e.from))
882 const targets = board.deliverables.length > 0 ? board.deliverables : board.all().filter(c => c.role === 'build' || c.role === 'research').map(c => c.target)
883 if (targets.length === 0 || !targets.every(t => dones.some(e => doneNames(e, t)))) return
884 firedClaimAlerts.add(key)
885 markRosterDirty($)
886 submitWake($, `swarm: ${board.deliverables.length > 0 ? 'all deliverables' : 'every build and research claim'} done, no open claims or blocks, every teammate idle; start the final review (protocol §3, phase 6) unless it ran, else stop_swarm when you agree.`, now)
887}
888
889/**
890 * Sends each idle teammate whose `[WAIT]` file changed after it registered the wait `[ASK] <path> changed: …`, once per
891 * change, and one whose `[WAIT] until` time came `[ASK] <time> reached: …`.
892 */
893async function checkWaits($: EngineInterface) {
894 for (const [name, w] of waits) {
895 const a = roster.liveEntry(name)
896 if (a === undefined || !a.isTeammate) continue
897 const path = w.path
898 const changedAt = path === undefined ? (w.until !== undefined && (await $.clock.now()) >= w.until ? w.until : undefined) : await $.fs.stat(path).then(st => st.mtimeMs, () => undefined)
899 if (!isWaitDue(w, roster.idleSince(name), changedAt)) continue
900 w.wokenFor = changedAt
901 markRosterDirty($)
902 await sendTo($, a.id, name, path === undefined ? waitTimeText(w.until!) : waitWakeText(path, await $.fs.read(path).catch(() => '')))
903 }
904}
905
906/**
907 * Sends each live teammate that holds an open claim not yet nudged one `swarm: [ASK] quiet …`, unless it was nudged in the last
908 * `NUDGE_COOLDOWN_MIN`; returns how many were delivered and how many such teammates wait out their cooldown.
909 */
910async function nudgeClaimHolders($: EngineInterface): Promise<{ delivered: number; coolingDown: number }> {
911 let delivered = 0
912 let coolingDown = 0
913 const now = await $.clock.now()
914 for (const name of board.claimants()) {
915 const a = roster.liveEntry(name)
916 if (a === undefined || !a.isTeammate) continue
917 const ids = new Map(board.openClaims(name).map(c => [`${name} ${c.key} ${board.sentAt(c.key, name)}`, c]))
918 for (const id of ids.keys()) if (nudged.has(id)) ids.delete(id)
919 if (ids.size === 0) continue
920 if (now - (nudgedAt.get(name) ?? -Infinity) < NUDGE_COOLDOWN_MIN * 60_000) {
921 coolingDown++
922 continue
923 }
924 if (!(await sendTo($, a.id, name, nudgeText(stallMin, [...ids.values()], board.reports, n => roster.label(n))))) continue
925 for (const id of ids.keys()) nudged.add(id)
926 nudgedAt.set(name, now)
927 delivered++
928 }
929 return { delivered, coolingDown }
930}
931
932/** What starts each of this plugin's own messages to a teammate, so its recipient does not read it as the lead's. */
933const MOD_PREFIX = MOD + ': '
934
935/**
936 * Sends one message from this plugin to an agent, `swarm: ` before it, and logs it as from `swarm`; returns whether it
937 * was delivered. A failure is logged, never thrown.
938 */
939async function sendTo($: EngineInterface, agentId: string, name: string, body: string): Promise<boolean> {
940 const text = MOD_PREFIX + body
941 modSending.set(text, (modSending.get(text) ?? 0) + 1)
942 try {
943 const r = await $.session.send({ to: { agentId }, text }).finally(() => {
944 const n = (modSending.get(text) ?? 1) - 1
945 if (n > 0) modSending.set(text, n)
946 else modSending.delete(text)
947 })
948 const entry = log.record({ ts: await $.clock.now(), from: MOD, to: name, text, via: 'send' })
949 if (entry !== undefined) {
950 if (session) entry.session = session
951 unwritten.push(entry)
952 scene.push(entry)
953 scheduleFlush($)
954 }
955 if (!r.isDelivered) $.ui.log(`message to ${name} not delivered: ${r.reason}`)
956 return r.isDelivered
957 } catch (err) {
958 $.ui.log(`message to ${name} failed: ` + String(err))
959 return false
960 }
961}
962
963/** What `/swarm say` and the pane's compose field send: `text` to the live agent `who` names; the answer in one line. */
964async function sayTo($: EngineInterface, who: string, text: string): Promise<string> {
965 const name = roster.resolve(who)
966 const a = roster.liveEntry(name)
967 if (a === undefined) return `no live agent goes by ${who}`
968 return (await sendTo($, a.id, name, 'the user says: ' + text)) ? `sent to ${roster.label(name)}` : `not delivered to ${roster.label(name)}`
969}
970
971/** One transcript message as pane lines: `› ` and the user's first line, `‹ ` and the agent's, `· <tool>` per tool call. */
972function transcriptLines(m: { role: string; text: string; toolUses: readonly { tool: string }[] }): string[] {
973 const first = m.text.trim().split('\n')[0] ?? ''
974 return [...(first === '' ? [] : [(m.role === 'user' ? '› ' : '‹ ') + first]), ...m.toolUses.map(t => '· ' + t.tool)]
975}
976
977/** Reads an agent's transcript into `transcripts`, its last `TRANSCRIPT_LINES` lines, and redraws when they changed. */
978async function readTranscript($: EngineInterface, agentId: string) {
979 if (readingTranscript.has(agentId)) return
980 readingTranscript.add(agentId)
981 try {
982 let lines: string[]
983 try {
984 const found = await $.session.messages({ agentId })
985 lines = 'deny' in found ? ['transcript not readable: ' + found.deny] : found.flatMap(transcriptLines).slice(-TRANSCRIPT_LINES)
986 } catch (err) {
987 lines = ['transcript not readable: ' + String(err)]
988 }
989 const prior = transcripts.get(agentId)
990 transcripts.set(agentId, { at: await $.clock.now(), lines })
991 if (prior?.lines.join('\n') !== lines.join('\n')) $.ui.invalidate('ui.render')
992 } finally {
993 readingTranscript.delete(agentId)
994 }
995}
996
997/** A teammate as `<code name> (<team name>`, or `<team name> (<team name>` without a code name, for the mod's asks. */
998function opened(name: string): string {
999 return `${roster.codeNames.get(name) ?? name} (${name}`
1000}
1001
1002/** Tells a teammate whose new code name another teammate already uses to send a hello with another one. */
1003async function tellClash($: EngineInterface, name: string, agentId: string, other: string) {
1004 await sendTo($, agentId, name, `[ASK] code name ${roster.codeNames.get(name)} is already used by ${opened(other)}). Send a first-line \`[PROPOSE] hello <other name>\` to every teammate to take another.`)
1005}
1006
1007/**
1008 * Answers a build or research claim once: the first claimant hears the slice is its, once however it spells the target; a later claimant who already holds
1009 * it and up to 3 unclaimed slices; nothing is refused.
1010 */
1011async function tellTaken($: EngineInterface, by: string, agentId: string, claim: ClaimRef) {
1012 const name = bareName(by)
1013 const held = board.heldBefore(name, claim)
1014 if (held === undefined) {
1015 const key = name + ' ' + claim.role + ' ' + board.canonical(claim).target
1016 if (claim.role === 'review' || ackedClaims.has(key)) return
1017 ackedClaims.add(key)
1018 markRosterDirty($)
1019 await sendTo($, agentId, name, `${claim.role} ${claim.target} is yours.`)
1020 return
1021 }
1022 if (askedTaken.has(name + ' ' + held.key)) return
1023 askedTaken.add(name + ' ' + held.key)
1024 markRosterDirty($)
1025 const since = held.at === undefined ? '' : ', since ' + timeOfDay(held.at)
1026 const stamp = held.stamp === undefined ? '' : `, #${held.stamp}`
1027 const free = board.unclaimed().slice(0, 3)
1028 await sendTo($, agentId, name, `[ASK] ${claim.target} is already claimed by ${opened(held.holder)}${since}${stamp}). Talk to them, split it, or pick another slice${free.length > 0 ? ': ' + free.join(', ') : ''}.\nIf you wait instead, the mod tells you when it passes to you.`)
1029}
1030
1031/**
1032 * After a teammate wrote a file other live teammates hold a build claim on and it does not: tells the writer and, as a
1033 * copy, the first holder, at most once per writer and file per `OVERWRITE_WARN_MS`. The write itself is never refused.
1034 */
1035async function warnOverwrite($: EngineInterface, agentId: string, path: string) {
1036 const a = roster.agents.get(agentId)
1037 if (a === undefined || !a.isTeammate) return
1038 const writer = bareName(a.name)
1039 const claims = board.all().filter(c => c.role === 'build' && sameTarget(c.target, path))
1040 if (claims.some(c => c.by.includes(writer))) return
1041 const holder = claims.flatMap(c => c.by).find(h => roster.isLiveTeammate(h))
1042 if (holder === undefined) return
1043 const now = await $.clock.now()
1044 const key = writer + ' ' + path
1045 if (now - (warnedWrite.get(key) ?? -Infinity) < OVERWRITE_WARN_MS) return
1046 warnedWrite.set(key, now)
1047 await sendTo($, agentId, writer, `[ASK] you wrote ${path}, claimed by ${opened(holder)}). Settle it with them.`)
1048 const owner = roster.liveEntry(holder)
1049 if (owner !== undefined) await sendTo($, owner.id, holder, `[ASK] ${opened(writer)}) wrote ${path}, which you claimed. Settle it with them.`)
1050}
1051
1052/** Records the deliverables a brief names and redraws when one is new. */
1053function noteDeliverables($: EngineInterface, list: readonly string[]) {
1054 if (board.addDeliverables(list)) markRosterDirty($)
1055}
1056
1057/** Asks once, while the lead is not mid-turn, how to live with the plugin holding `/swarm`; `Keep both` is stored, a dismissed or `-p` ask stores nothing. */
1058async function askConflict($: EngineInterface) {
1059 if (!isConflictAskDue || roster.leadBusy || swarmTakenBy === undefined) return
1060 isConflictAskDue = false
1061 const answer = await $.ui.ask(`Another plugin (${swarmTakenBy}) already uses /swarm. How do you want to use this one?`, [KEEP_BOTH, SHOW_REMOVE, ASK_AGAIN]).catch(() => undefined)
1062 if (answer === KEEP_BOTH) await $.store.set('swarmConflict', 'keep')
1063 if (answer !== SHOW_REMOVE) return
1064 const enabled = (await $.settings.read().catch(() => ({}))) as { enabledPlugins?: Record<string, unknown> }
1065 const id = Object.keys(enabled.enabledPlugins ?? {}).find(k => k.startsWith(swarmTakenBy + '@'))
1066 $.ui.toast(`To remove ${swarmTakenBy}: ${id === undefined ? '/plugin, then uninstall it there' : '/plugin uninstall ' + id}, and restart Claude Code afterwards.`, { timeoutMs: 20_000 })
1067}
1068
1069/** This session's live teammates: agents spawned as teammates that have not ended; never a subagent, never a workflow's agent. */
1070function liveTeammates(): RosterEntry[] {
1071 return [...roster.agents.values()].filter(a => a.isTeammate && a.workflowRunId === undefined && !ENDED.includes(a.status))
1072}
1073
1074/**
1075 * Stops live teammates with TaskStop, through the permission check like any tool call: every live teammate, or those
1076 * `names` gives (team or code names). Never a subagent that is not a teammate. Each stopped one is marked killed at once,
1077 * so the team shows as ended. Returns one line per name, `stopped` or `failed` with the reason.
1078 */
1079async function stopTeammates($: EngineInterface, names?: readonly string[]): Promise<{ stopped: string[]; failed: { name: string; reason: string }[] }> {
1080 const live = liveTeammates()
1081 const out = { stopped: [] as string[], failed: [] as { name: string; reason: string }[] }
1082 const targets: RosterEntry[] = []
1083 for (const n of names ?? live.map(a => a.name)) {
1084 const name = roster.resolve(n)
1085 const a = live.find(x => bareName(x.name) === name)
1086 if (a === undefined) out.failed.push({ name: n, reason: roster.hasTeammate(name) ? 'already ended' : 'no teammate of this session goes by that name' })
1087 else if (!targets.includes(a)) targets.push(a)
1088 }
1089 for (const a of targets) {
1090 try {
1091 const r = (await $.tool.call({ tool: 'TaskStop', task_id: a.name } as never)) as { deny?: string; isError?: boolean; text?: string }
1092 if (r.deny !== undefined) out.failed.push({ name: a.name, reason: r.deny })
1093 else if (r.isError === true) out.failed.push({ name: a.name, reason: r.text ?? 'TaskStop failed' })
1094 else {
1095 out.stopped.push(a.name)
1096 roster.agents.set(a.id, { ...a, status: 'killed', statusAt: await $.clock.now() })
1097 }
1098 } catch (err) {
1099 out.failed.push({ name: a.name, reason: String(err) })
1100 }
1101 }
1102 if (out.stopped.length > 0) markRosterDirty($)
1103 await noteLeaves($)
1104 return out
1105}
1106
1107/** A stop's outcome in one line: `stopped h01, h02 · failed h03 (denied)`, or that no live teammate was there. */
1108function stopText(r: { stopped: string[]; failed: { name: string; reason: string }[] }): string {
1109 const parts = [...(r.stopped.length > 0 ? [`stopped ${r.stopped.map(n => roster.label(n)).join(', ')}`] : []), ...(r.failed.length > 0 ? [`failed ${r.failed.map(f => `${f.name} (${f.reason})`).join(', ')}`] : [])]
1110 return parts.length > 0 ? 'swarm: ' + parts.join(' · ') : 'swarm: no live teammate to stop'
1111}
1112
1113/** The pane's `[ stop all ]`: asks once, then stops every live teammate and toasts the outcome. */
1114async function confirmStopAll($: EngineInterface) {
1115 const live = liveTeammates()
1116 if (live.length === 0) return $.ui.toast('swarm: no live teammate to stop')
1117 const answer = await $.ui.ask(`Stop all ${live.length} live teammate${live.length === 1 ? '' : 's'} (${live.map(a => roster.label(a.name)).join(', ')})?`, [STOP_THEM, 'Cancel']).catch(() => undefined)
1118 if (answer !== STOP_THEM) return
1119 $.ui.toast(stopText(await stopTeammates($)))
1120 $.ui.invalidate('ui.render')
1121}
1122
1123function statusText(now: number): string {
1124 const tasks = openTasks === null ? 'unknown' : String(openTasks)
1125 return `${swarmTakenBy === undefined ? '' : `/swarm is taken by ${swarmTakenBy}; use /swarmctl · `}${bandLine(now)} · swarm: ${isSwarm() ? 'yes' : 'no'} · sky renderer: ${skyStatus()} · quiet: ${quiet ? 'on' : 'off'} · stall: ${stallMin} min · claim watch: ${claimMin} min · open tasks: ${tasks} · log: ${logPath() ?? '(no cwd)'}`
1126}
1127
1128export function register(on: On, options: PluginOptions) {
1129 setSkyPython(typeof options.skyPython === 'string' ? options.skyPython : '')
1130 on('session.start', async ($, e, next) => {
1131 try {
1132 cwd = await $.session.cwd()
1133 session = 'session-' + (await $.session.id()).slice(0, 8)
1134 await hydrate($)
1135 const now = await $.clock.now()
1136 lastActivityAt = now
1137 loadedAt = now
1138 const savedMode = (await $.store.get(WAKE_KEY + session)) ?? (await $.store.get('wakeMode'))
1139 if (typeof savedMode === 'string' && (WAKE_MODES as readonly string[]).includes(savedMode)) policy.setMode(savedMode as WakeMode, now)
1140 else policy.setMode('mentions', now)
1141 const savedStall = await $.store.get('stallMin')
1142 if (typeof savedStall === 'number' && savedStall >= 0) stallMin = savedStall
1143 const savedQuiet = await $.store.get('quiet')
1144 if (typeof savedQuiet === 'boolean') quiet = savedQuiet
1145 const savedClaim = await $.store.get('claimMin')
1146 if (typeof savedClaim === 'number' && savedClaim >= 0) claimMin = savedClaim
1147 const savedLevel = await $.store.get('level')
1148 if (typeof savedLevel === 'string' && (LEVELS as readonly string[]).includes(savedLevel)) setLevel(savedLevel as LevelSetting)
1149 $.clock.every(TICK_MS, () => {
1150 void tick($)
1151 })
1152 ownSky($)
1153 setStopAll(() => confirmStopAll($))
1154 await $.tool.register({
1155 name: STOP_TOOL,
1156 description: 'Stops the swarm: every live teammate of this session (agents spawned as teammates; never other subagents), or only the teammates `names` lists (team or code names), each with TaskStop. Call it once when the swarm\'s work is done (every [DONE] in, no open [BLOCK]) and before you spawn a new swarm. Returns which teammates stopped and which failed, with the reason.',
1157 inputSchema: { type: 'object', properties: { names: { type: 'array', items: { type: 'string' }, description: 'Teammates to stop; leave out to stop every live teammate.' } } },
1158 isDeferred: false,
1159 }).then(r => {
1160 stopToolId = r.tool
1161 }, (err: unknown) => $.ui.log('swarm: stop_swarm not registered: ' + String(err)))
1162 for (const name of COMMANDS) {
1163 await $.command.register({
1164 name,
1165 description: (swarmTakenBy === undefined ? '' : `/swarm is taken by ${swarmTakenBy}; use /swarmctl. `) + 'Swarm: open the pane, or set wake all|mentions|digest|off, quiet on|off, stall <min>, claim <min>, level auto|basic|rich, deliverable <path>, status; stop all|<name> stops teammates; say <agent> <text> messages an agent; replay <log.jsonl> plays a recorded run',
1166 argumentHint: '[wake all|mentions|digest|off | quiet on|off | stall <min> | claim <min> | level auto|basic|rich | deliverable <path> | status | stop all|<name> | say <agent> <text> | replay <log.jsonl> [--speed N] [--look A|B] [--level basic|rich] [--from <ISO>] [--to <ISO>] | replay stop]',
1167 immediate: true,
1168 }).catch((err: unknown) => {
1169 if (name === 'swarm') swarmTakenBy = commandHolder(err instanceof Error ? err.message : String(err))
1170 $.ui.log(`swarm: /${name} not registered: ${String(err)}`)
1171 })
1172 }
1173 isConflictAskDue = swarmTakenBy !== undefined && e.isInteractive && (await $.store.get('swarmConflict')) !== 'keep'
1174 if (isConflictAskDue) $.clock.after(1_000, () => void askConflict($).catch(() => undefined))
1175 } catch (err) {
1176 $.ui.log('swarm start: ' + String(err))
1177 }
1178 return next(e)
1179 })
1180
1181 on('tool.call', { tool: /^mcp__.+__stop_swarm$/ }, async ($, e, next) => {
1182 if (e.tool !== stopToolId) return next(e)
1183 if (e.agentId !== undefined) return { result: "stop_swarm is the lead's: ask the lead to stop the swarm" } as never
1184 try {
1185 const names = (e as unknown as { names?: unknown }).names
1186 const list = Array.isArray(names) ? names.filter((n): n is string => typeof n === 'string' && n.trim() !== '') : []
1187 return { result: stopText(await stopTeammates($, list.length > 0 ? list : undefined)) } as never
1188 } catch (err) {
1189 $.ui.log('swarm stop_swarm: ' + String(err))
1190 return { result: 'swarm: stop_swarm failed; stop each teammate by name with TaskStop' } as never
1191 }
1192 })
1193
1194 on('tool.call', { tool: 'SendMessage' }, async ($, e, next) => {
1195 const key = e.agentId ?? 'main'
1196 const before = sendsBy.get(key) ?? 0
1197 const result = await next(e)
1198 try {
1199 const refused = typeof result === 'object' && result !== null && 'deny' in result && result.deny !== undefined
1200 const input = e as unknown as { to?: unknown; message?: unknown }hooks/core.ts 1766 lines1// Pure swarm state: message log, roster, wake policy and the text the pane
2// and band draw. No mods API here, so every rule is unit-testable.
3
4export type WakeMode = 'all' | 'mentions' | 'digest' | 'off'
5export const WAKE_MODES: readonly WakeMode[] = ['all', 'mentions', 'digest', 'off']
6
7export const LEAD = 'team-lead'
8/** The `from` of the messages this plugin sends and logs. */
9export const MOD = 'swarm'
10/** Whether a logged sender is this plugin: its name, and also the names older logs use. */
11export const isModName = (name: string): boolean => name === MOD || name === 'swarm-console'
12/** Message types that report on a claim. */
13export const REPORTS: readonly string[] = ['DONE', 'REVIEW', 'BLOCK']
14export const COALESCE_MS = { all: 10_000, mentions: 3_000 } as const
15export const DIGEST_MS = 60_000
16/** How many recent sends a delivery is checked against: a delivery reaches a busy receiver only at its next turn or tool round. */
17const SEND_MEMORY = 200
18export const MEMORY_CAP = 500
19export const DEFAULT_STALL_MIN = 5
20/** The plugin a refused command registration names as holding the command (`… the plugin <name> registered it already`), else the refusal's text. */
21export function commandHolder(refusal: string): string {
22 return /the plugin (\S+) registered it/.exec(refusal)?.[1] ?? refusal.replace(/^\w*Error: /, '')
23}
24export const DEFAULT_CLAIM_MIN = 3
25/** Minutes before the stall watchdog nudges the same teammate again. */
26export const NUDGE_COOLDOWN_MIN = 10
27/** Minutes without a message from its holder after which a claim shows as stale. */
28const CLAIM_TTL_MIN = 10
29const LABEL_MAX = 28
30const EARLIER = '── earlier ──'
31export const OTHER_AGENTS = '── other agents ──'
32const STALE_MS = 10 * 60_000
33/** How many rows the text list shows under `other agents` and under `earlier`, the newest; the rest as `… N more`. */
34export const OTHERS_SHOWN = 5
35/** Hours a teammate stays idle before the pane and the band show it as ended (see `Roster.isDormant`). */
36export const IDLE_ENDED_H = 6
37/** The statuses of an agent that has ended. */
38export const ENDED: readonly string[] = ['completed', 'failed', 'killed']
39
40const LEAD_ALIASES = new Set(['team-lead', 'main', 'lead', 'orchestrator'])
41const MENTION = /(^|[^\w@])@(lead|orchestrator|main|team-lead)\b/i
42const TYPE_TAG = /^\s*(?:swarm:\s*)?\[(PROPOSE|CLAIM|LOCK|WAIT|ASK|REVIEW|BLOCK|HANDOFF|DONE|RELEASE|WITHDRAW)\]/i
43/** The order stamp line the mod puts before a teammate-to-teammate message (`#412 · 17:04:12`), after any envelope tag. */
44const STAMP_LINE = /^(\s*(?:<[^>]*>\s*)?)#\d+ · \d\d:\d\d:\d\d[^\S\n]*\n/
45const HELLO = /^(?:<[^>]*>\s*)?\[PROPOSE\]\s+hello\s+([A-Za-z][\w-]{0,23})\b/i
46const NAME = '[\\"\'`“]?([A-Za-z][\\w-]{0,23})\\b'
47const CAP_NAME = '([A-Z][\\w-]{0,23})\\b'
48const SELF = "\\bI(?:'m)?\\b(?:\\s*\\([^)]*\\))?"
49const RENAMES: readonly RegExp[] = [
50 new RegExp(SELF + '\\s+(?:am\\s+|have\\s+)?(?:now\\s+)?renam(?:e|ed|ing)\\s+(?:myself\\s+)?(?:to\\s+|as\\s+)?' + NAME, 'i'),
51 new RegExp('^renamed\\s+(?:to\\s+)?' + NAME, 'i'),
52 new RegExp('\\(renamed(?:\\s+to)?\\s+' + NAME + '\\s*\\)', 'i'),
53 new RegExp('\\([Nn]ow\\s+' + CAP_NAME + '\\s*\\)'),
54 new RegExp('\\bcall\\s+me\\s+' + NAME, 'i'),
55 new RegExp('\\bnow\\s+(?:called|named|known\\s+as|going\\s+by)\\s+' + NAME, 'i'),
56 new RegExp("\\bI(?:'m|\\s+am)\\s+(?![\\w-]*ing\\b)" + NAME + '\\s+from\\s+now\\s+on', 'i'),
57 new RegExp(SELF + '\\s+(?:am\\s+)?now\\s+' + CAP_NAME),
58 new RegExp(SELF + '\\s+am\\s+' + CAP_NAME),
59 new RegExp("\\bI'm\\s+" + CAP_NAME),
60]
61const NOT_NAMES = new Set(['to', 'as', 'me', 'myself', 'the', 'a', 'an', 'now', 'not', 'ok', 'okay', 'done', 'ready', 'busy', 'free', 'here', 'back',
62 'also', 'still', 'idle', 'available', 'blocked', 'waiting', 'working', 'on', 'in', 'at', 'with', 'sure', 'going', 'it', 'this', 'that'])
63const MODEL_FAMILIES = ['opus', 'sonnet', 'haiku', 'fable']
64
65export type Via = 'send' | 'receive' | 'tool'
66
67export type LogEntry = {
68 ts: number
69 from: string
70 to: string
71 summary: string
72 length: number
73 type?: string
74 via: Via
75 /** The order stamp the mod gave a teammate-to-teammate send. */
76 stamp?: number
77 /** On an ACT line: how many tool calls the teammate had made by then. */
78 calls?: number
79 idleReason?: string
80 /** The claim the whole message made (see `claimOf`), also when it was not on the first line. */
81 claim?: ClaimRef
82 session?: string
83 fromId?: string
84 toId?: string
85}
86
87export type RosterEntry = {
88 id: string
89 name: string
90 model?: string
91 type?: string
92 status: string
93 isTeammate: boolean
94 teammateId?: string
95 description?: string
96 /** When `agent.spawn` returned it. */
97 spawnedAt?: number
98 /** When its status last changed. */
99 statusAt?: number
100 /** When `$.agent.list()` first reported it, for an agent whose spawn this load did not see. */
101 firstSeenAt?: number
102 /** Whether `$.agent.list()` has reported it; one it then stops reporting has ended. */
103 isListed?: boolean
104 /** The Workflow run that started it (`wf_…`), for a workflow script's agent. */
105 workflowRunId?: string
106 /** The agent whose loop spawned it (`parentAgentId`); absent when the main loop did. */
107 parentId?: string
108}
109
110/** Whether an agent was started by a workflow script: `agent.spawn`'s `workflow`, or the type the engine gives such agents. */
111function isWorkflowAgent(a: RosterEntry): boolean {
112 return a.workflowRunId !== undefined || a.type === 'workflow-subagent'
113}
114
115export type AgentRow = {
116 id: string
117 name?: string
118 type: string
119 status: string
120 teammateId?: string
121 description: string
122 parentId?: string
123}
124
125/** The address without its `@team` suffix, lower-cased. */
126export function bareName(address: string): string {
127 return (address.split('@')[0] ?? '').trim().toLowerCase()
128}
129
130export function isLeadAddress(address: string): boolean {
131 return LEAD_ALIASES.has(bareName(address))
132}
133
134/** Whether a message sent to `address` reaches the lead: `team-lead`, or `main`; `lead` and `orchestrator` name it only in a mention. */
135export function isLeadRecipient(address: string): boolean {
136 const name = bareName(address)
137 return name === LEAD || name === 'main'
138}
139
140/** A message without the order stamp line the mod put before it. */
141export function unstamped(text: string): string {
142 return text.replace(STAMP_LINE, '$1')
143}
144
145/** `HH:MM:SS` in the local time zone: the one clock of the pane, the text list and the stamps. */
146export function timeOfDay(ts: number): string {
147 return new Date(ts - new Date(ts).getTimezoneOffset() * 60_000).toISOString().slice(11, 19)
148}
149
150/** The stamp line put before a teammate-to-teammate message: its order `n` in the session and the local time it was sent. */
151export function stampLine(n: number, ts: number): string {
152 return `#${n} · ${timeOfDay(ts)}`
153}
154
155export function firstLine(text: string, max = 160): string {
156 const line = unstamped(text).split('\n').find(l => l.trim() !== '') ?? ''
157 const trimmed = line.trim()
158 return trimmed.length > max ? trimmed.slice(0, max - 1) + '…' : trimmed
159}
160
161export function typeOf(text: string): string | undefined {
162 const m = TYPE_TAG.exec(unstamped(text))
163 return m?.[1]?.toUpperCase()
164}
165
166export type IdleNotice = { from?: string; idleReason?: string }
167
168/** The idle notification a delivery carries (a JSON body with `type: "idle_notification"`), or undefined. */
169export function idleNotice(text: string): IdleNotice | undefined {
170 if (!text.includes('idle_notification')) return undefined
171 const start = text.indexOf('{')
172 const end = text.lastIndexOf('}')
173 if (start < 0 || end <= start) return undefined
174 try {
175 const o = JSON.parse(text.slice(start, end + 1)) as Record<string, unknown>
176 if (o.type !== 'idle_notification') return undefined
177 const notice: IdleNotice = {}
178 if (typeof o.from === 'string') notice.from = o.from
179 if (typeof o.idleReason === 'string') notice.idleReason = o.idleReason
180 return notice
181 } catch {
182 return undefined
183 }
184}
185
186/** The code name a teammate announces on the first line as `[PROPOSE] hello <Name>`. */
187export function helloName(text: string): string | undefined {
188 return HELLO.exec(firstLine(text))?.[1]
189}
190
191/**
192 * The new code name a sender gives itself anywhere in a message: `I (t3) rename to kite`, `renamed Kite` at a line's start
193 * (after its type tag), `(renamed kite)`, `(now Kite)`, `call me Kite`, `now called Kite`, `I am now Kite`, `I am Kite`, `I'm Kite`.
194 * `(now Kite)` and the last three need a capitalised name. A name may be quoted, and `I'm kite from now on` renames to a name that does not end in `ing`.
195 */
196export function renameName(text: string): string | undefined {
197 for (const raw of text.split('\n')) {
198 const line = raw.replace(/^\s*(?:<[^>]*>\s*)?(?:\[[A-Za-z]+\]\s*)?/, '').trim()
199 for (const re of RENAMES) {
200 const name = re.exec(line)?.[1]
201 if (name !== undefined && !NOT_NAMES.has(name.toLowerCase())) return name
202 }
203 }
204 return undefined
205}
206
207/** A model id as family plus version: `claude-opus-5-5[1m]` → `opus 5.5`, `claude-3-5-sonnet-20241022` → `sonnet 3.5`; `–` when unknown. */
208export function shortModel(id: string | undefined): string {
209 if (id === undefined || id.trim() === '') return '–'
210 const parts = id.trim().toLowerCase().replace(/\[[^\]]*\]$/, '').replace(/^(?:[\w.]+\.)?anthropic\./, '').replace(/^claude-/, '').replace(/-v\d+(?::\d+)?$/, '').split('-')
211 const family = parts.find(p => MODEL_FAMILIES.includes(p)) ?? parts.find(p => /^[a-z]+$/.test(p))
212 const version = parts.filter(p => /^\d{1,2}$/.test(p)).join('.')
213 if (family === undefined) return id.trim()
214 return version === '' ? family : `${family} ${version}`
215}
216
217/**
218 * The run id and workflow name a Workflow tool call started, from its result (`runId`, `workflowName`, at any depth up to
219 * three) or its input (`name`, else the script file's name before `-wf_`); undefined without a run id.
220 */
221export function workflowRunOf(input: unknown, result: unknown): { runId: string; name: string } | undefined {
222 const find = (o: unknown, key: string, depth = 0): string | undefined => {
223 if (depth > 3 || o === null || typeof o !== 'object') return undefined
224 const v = (o as Record<string, unknown>)[key]
225 if (typeof v === 'string' && v !== '') return v
226 for (const child of Object.values(o as Record<string, unknown>)) {
227 const found = find(child, key, depth + 1)
228 if (found !== undefined) return found
229 }
230 return undefined
231 }
232 const text = typeof result === 'string' ? result : JSON.stringify(result ?? null)
233 const runId = find(result, 'runId') ?? /\bRun ID:\s*(wf_[\w-]+)/.exec(text)?.[1] ?? /"runId"\s*:\s*"(wf_[\w-]+)"/.exec(text)?.[1]
234 if (runId === undefined) return undefined
235 const i = (input ?? {}) as { name?: unknown; scriptPath?: unknown }
236 const script = typeof i.scriptPath === 'string' ? /([\w.-]+?)-wf_[\w-]+\.js$/.exec(i.scriptPath)?.[1] : undefined
237 const name = find(result, 'workflowName') ?? (typeof i.name === 'string' && i.name !== '' ? i.name : undefined) ?? script ?? runId
238 return { runId, name }
239}
240
241export function mentionsLead(text: string): boolean {
242 return MENTION.test(text)
243}
244
245/** Text of a SendMessage `message` argument, which may be a structured protocol object. */
246export function messageText(message: unknown): string {
247 if (typeof message === 'string') return message
248 if (message && typeof message === 'object' && 'type' in message) {
249 return '[' + String((message as { type: unknown }).type) + ']'
250 }
251 return ''
252}
253
254export class Roster {
255 readonly agents = new Map<string, RosterEntry>()
256 /** Code names by the agent's bare team name. */
257 readonly codeNames = new Map<string, string>()
258 /** Idle notifications by the agent's bare team name, with the last reason given. */
259 readonly idle = new Map<string, { count: number; lastReason?: string; lastAt?: number }>()
260 /** When each agent, by bare team name, was first seen sending a message. */
261 readonly firstMessageAt = new Map<string, number>()
262 /** When each agent, by bare team name, last sent a message. */
263 readonly lastMessageAt = new Map<string, number>()
264 /** Workflow names by run id, from the Workflow tool's calls. */
265 readonly workflowNames = new Map<string, string>()
266 /** Agents from a previous session's roster.json, shown under `earlier`. */
267 earlier: RosterEntry[] = []
268 /** Whether the lead is in a turn. */
269 leadBusy = false
270 /** The time of the latest `merge` or `hydrate` that gave one, against which an idle teammate's age is read. */
271 private seenAt = -Infinity
272 /** Whether a teammate (bare team name) holds a registered wait or an open claim; such a teammate is never dormant. */
273 isHeld: (name: string) => boolean = () => false
274
275 /**
276 * Whether a teammate is dormant: reported `idle`, holding no wait or open claim, and without a status change, message or
277 * idle notice for over `IDLE_ENDED_H` hours at `now`. Display only: the pane and the band show it as ended; the team,
278 * claims, waits and watchdogs still count it live.
279 */
280 isDormant(a: RosterEntry, now = this.seenAt): boolean {
281 if (!a.isTeammate || a.status !== 'idle' || a.statusAt === undefined) return false
282 const name = bareName(a.name)
283 const lastSeen = Math.max(a.statusAt, this.lastMessageAt.get(name) ?? -Infinity, this.idle.get(name)?.lastAt ?? -Infinity)
284 return now - lastSeen > IDLE_ENDED_H * 3_600_000 && !this.isHeld(name)
285 }
286
287 /** Whether the pane and the band show an agent as ended: completed, failed or killed, or dormant. */
288 isShownEnded(a: RosterEntry, now = this.seenAt): boolean {
289 return ENDED.includes(a.status) || this.isDormant(a, now)
290 }
291
292 /** Counts one idle notification from `sender`, received at `ts`. */
293 noteIdle(sender: string, reason?: string, ts?: number) {
294 const name = bareName(sender)
295 const prior = this.idle.get(name)
296 const lastAt = ts === undefined ? prior?.lastAt : Math.max(ts, prior?.lastAt ?? ts)
297 this.idle.set(name, { count: (prior?.count ?? 0) + 1, lastReason: reason ?? prior?.lastReason, lastAt })
298 }
299
300 /** Records that `sender` sent a message at `ts`; keeps the earliest and the latest. */
301 noteMessage(sender: string, ts: number) {
302 const name = bareName(sender)
303 if (name === '') return
304 const prior = this.firstMessageAt.get(name)
305 if (prior === undefined || ts < prior) this.firstMessageAt.set(name, ts)
306 if (ts > (this.lastMessageAt.get(name) ?? -Infinity)) this.lastMessageAt.set(name, ts)
307 }
308
309 /** The latest agent going by `name` (bare team name) that has not ended, or undefined. */
310 liveEntry(name: string): RosterEntry | undefined {
311 const n = bareName(name)
312 return [...this.agents.values()].filter(a => bareName(a.name) === n && !ENDED.includes(a.status)).pop()
313 }
314
315 /** When `name` went idle: its last idle notice, while it has sent nothing since and its live agent is not running; else undefined. */
316 idleSince(name: string): number | undefined {
317 const n = bareName(name)
318 const at = this.idle.get(n)?.lastAt
319 if (at === undefined || (this.lastMessageAt.get(n) ?? -Infinity) > at) return undefined
320 const entry = this.liveEntry(n)
321 return entry === undefined || entry.status === 'running' ? undefined : at
322 }
323
324 /**
325 * Stores the code name `sender` gives itself, with its casing as written: a first-line `[PROPOSE] hello <Name>` or a rename
326 * (see `renameName`). A received message sets a name only while the sender has none, since deliveries can arrive after a
327 * later rename. Returns whether it changed. The lead has none.
328 */
329 announce(sender: string, text: string, via: Via = 'send'): boolean {
330 const name = bareName(sender)
331 if (name === '' || isLeadAddress(name) || name === 'peer') return false
332 const code = helloName(text) ?? renameName(text)
333 if (code === undefined) return false
334 if (via === 'receive' && this.codeNames.has(name)) return false
335 if (this.codeNames.get(name) === code) return false
336 this.codeNames.set(name, code)
337 return true
338 }
339
340 /** The bare team name of another current agent that uses `name`'s code name (any case), or undefined. */
341 clashWith(name: string): string | undefined {
342 const n = bareName(name)
343 const code = this.codeNames.get(n)?.toLowerCase()
344 if (code === undefined) return undefined
345 return [...this.agents.values()].filter(a => !this.isShownEnded(a)).map(a => bareName(a.name)).find(o => o !== n && this.codeNames.get(o)?.toLowerCase() === code)
346 }
347
348 /** Bare team names of current agents whose code name another current agent also uses, case-insensitively. */
349 duplicateCodes(): Set<string> {
350 const byCode = new Map<string, string[]>()
351 for (const a of this.agents.values()) {
352 if (this.isShownEnded(a)) continue
353 const name = bareName(a.name)
354 const code = this.codeNames.get(name)?.toLowerCase()
355 if (code === undefined) continue
356 const names = byCode.get(code) ?? []
357 if (!names.includes(name)) names.push(name)
358 byCode.set(code, names)
359 }
360 const out = new Set<string>()
361 for (const names of byCode.values()) if (names.length > 1) for (const n of names) out.add(n)
362 return out
363 }
364
365 /** The team of the most recently added teammate (the part after `@` of its teammate id), or undefined without teammates. */
366 currentTeam(): string | undefined {
367 let team: string | undefined
368 for (const a of this.agents.values()) if (a.isTeammate) team = a.teammateId?.split('@')[1] ?? ''
369 return team
370 }
371
372 /**
373 * Whether an agent belongs under `other agents`: outside the current team while a team exists, shown as ended (see `isShownEnded`),
374 * or pending for more than `STALE_MS`.
375 */
376 isOther(a: RosterEntry, now: number): boolean {
377 const team = this.currentTeam()
378 if (team !== undefined && (!a.isTeammate || (a.teammateId?.split('@')[1] ?? '') !== team)) return true
379 if (this.isShownEnded(a, now)) return true
380 return a.status === 'pending' && a.statusAt !== undefined && now - a.statusAt > STALE_MS
381 }
382
383 /** When an agent started: its spawn, else its first message, else when the agent list first reported it; undefined when none was seen. */
384 startedAt(name: string): number | undefined {
385 const n = bareName(name)
386 const entry = [...this.agents.values()].find(a => bareName(a.name) === n)
387 return entry?.spawnedAt ?? this.firstMessageAt.get(n) ?? entry?.firstSeenAt
388 }
389
390 /**
391 * `Atlas (t1)` once t1 announced Atlas; for an agent without a name of its own
392 * (named by its id prefix) its spawn description, also when addressed by its full id; else the name itself.
393 */
394 label(name: string): string {
395 const code = this.codeNames.get(bareName(name))
396 if (code !== undefined) return code.toLowerCase() === bareName(name) ? `${name} (no code name)` : `${code} (${name})`
397 const entry = [...this.agents.values(), ...this.earlier].find(a => a.name === name || a.id === name)
398 if (entry !== undefined && entry.name === entry.id.slice(0, 8) && entry.description) return clip(entry.description.trim(), LABEL_MAX)
399 return name
400 }
401
402 /**
403 * Restores a roster.json: this session's agents rejoin the roster, a previous session's go to `earlier`. A restored agent
404 * of this session that has not ended counts as listed, so the next `merge` that does not report it marks it completed.
405 */
406 hydrate(json: unknown, session: string, now?: number) {
407 if (now !== undefined) this.seenAt = Math.max(this.seenAt, now)
408 if (!json || typeof json !== 'object') return
409 const j = json as { session?: unknown; agents?: unknown }
410 if (!Array.isArray(j.agents)) return
411 const isCurrent = j.session === session
412 for (const raw of j.agents) {
413 if (!raw || typeof raw !== 'object' || typeof (raw as RosterEntry).id !== 'string') continue
414 const a = raw as RosterEntry & { codeName?: unknown; idleNotices?: unknown; lastIdleReason?: unknown; lastIdleAt?: unknown }
415 const entry: RosterEntry = {
416 id: a.id,
417 name: typeof a.name === 'string' ? a.name : a.id.slice(0, 8),
418 model: typeof a.model === 'string' ? a.model : undefined,
419 type: typeof a.type === 'string' ? a.type : undefined,
420 status: isCurrent && typeof a.status === 'string' ? a.status : 'earlier',
421 isTeammate: a.isTeammate === true,
422 teammateId: typeof a.teammateId === 'string' ? a.teammateId : undefined,
423 description: typeof a.description === 'string' ? a.description : undefined,
424 spawnedAt: typeof a.spawnedAt === 'number' ? a.spawnedAt : undefined,
425 statusAt: isCurrent && typeof a.statusAt === 'number' ? a.statusAt : undefined,
426 workflowRunId: typeof a.workflowRunId === 'string' ? a.workflowRunId : undefined,
427 }
428 if (isCurrent && now !== undefined && isWorkflowAgent(entry) && !ENDED.includes(entry.status) && (entry.statusAt === undefined || now - entry.statusAt > STALE_MS)) {
429 entry.status = 'completed'
430 entry.statusAt = now
431 }
432 if (isCurrent && !isWorkflowAgent(entry) && !ENDED.includes(entry.status)) entry.isListed = true
433 if (typeof a.codeName === 'string' && !this.codeNames.has(bareName(entry.name))) this.codeNames.set(bareName(entry.name), a.codeName)
434 if (isCurrent) {
435 if (!this.agents.has(entry.id)) this.agents.set(entry.id, entry)
436 if (typeof a.idleNotices === 'number') {
437 this.idle.set(bareName(entry.name), {
438 count: a.idleNotices,
439 lastReason: typeof a.lastIdleReason === 'string' ? a.lastIdleReason : undefined,
440 lastAt: typeof a.lastIdleAt === 'number' ? a.lastIdleAt : undefined,
441 })
442 }
443 } else if (!this.earlier.some(e => e.id === entry.id)) {
444 this.earlier.push(entry)
445 }
446 }
447 }
448
449 /**
450 * The bare team name an agent goes by, given its team name or its code name. A code name several agents took goes to the
451 * one that has not ended, else to the latest started.
452 */
453 resolve(nameOrCode: string): string {
454 const n = bareName(nameOrCode)
455 const holders = [...this.codeNames].filter(([, code]) => code.toLowerCase() === n).map(([name]) => name)
456 if (holders.length === 0) return n
457 const live = holders.filter(h => this.liveEntry(h) !== undefined && [...this.agents.values()].some(a => bareName(a.name) === h))
458 const pool = live.length > 0 ? live : holders
459 return pool.reduce((best, h) => ((this.startedAt(h) ?? -Infinity) >= (this.startedAt(best) ?? -Infinity) ? h : best))
460 }
461
462 /** Records an `agent.spawn` once `next` answered with the started agent. */
463 spawned(input: { name?: string; model?: string; subagentType?: string; isTeammate?: boolean; description?: string; workflow?: { runId?: string }; parentAgentId?: string },
464 result: { agentId?: string; model?: string; teammateId?: string }, now?: number): RosterEntry | undefined {
465 if (!result.agentId) return undefined
466 const prior = this.agents.get(result.agentId)
467 const entry: RosterEntry = {
468 id: result.agentId,
469 name: input.name ?? prior?.name ?? result.agentId.slice(0, 8),
470 model: result.model ?? input.model ?? prior?.model,
471 type: input.subagentType ?? prior?.type,
472 status: prior?.status ?? 'pending',
473 isTeammate: input.isTeammate === true,
474 teammateId: result.teammateId ?? prior?.teammateId,
475 description: input.description ?? prior?.description,
476 spawnedAt: prior?.spawnedAt ?? now,
477 statusAt: prior?.statusAt ?? now,
478 workflowRunId: input.workflow?.runId || prior?.workflowRunId,
479 parentId: input.parentAgentId ?? prior?.parentId,
480 }
481 this.agents.set(entry.id, entry)
482 return entry
483 }
484
485 /** Merges `$.agent.list()` rows seen at `now`; returns whether anything changed. */
486 merge(rows: readonly AgentRow[], now?: number): boolean {
487 if (now !== undefined) this.seenAt = Math.max(this.seenAt, now)
488 let changed = false
489 const seen = new Set(rows.map(r => r.id))
490 for (const a of this.agents.values()) {
491 if (a.isListed === true && !seen.has(a.id) && !ENDED.includes(a.status)) {
492 this.agents.set(a.id, { ...a, status: 'completed', statusAt: now })
493 changed = true
494 }
495 }
496 for (const row of rows) {
497 const prior = this.agents.get(row.id)
498 const next: RosterEntry = {
499 ...prior,
500 isListed: true,
501 id: row.id,
502 name: row.name ?? prior?.name ?? row.id.slice(0, 8),
503 model: prior?.model,
504 type: prior?.type ?? row.type,
505 status: row.status,
506 isTeammate: prior?.isTeammate ?? (row.teammateId !== undefined || row.type === 'teammate'),
507 teammateId: row.teammateId ?? prior?.teammateId,
508 description: prior?.description ?? row.description,
509 parentId: prior?.parentId ?? row.parentId,
510 spawnedAt: prior?.spawnedAt,
511 firstSeenAt: prior === undefined ? now : prior.firstSeenAt,
512 statusAt: prior !== undefined && prior.status === row.status ? prior.statusAt : now,
513 }
514 if (!prior || JSON.stringify(prior) !== JSON.stringify(next)) changed = true
515 this.agents.set(row.id, next)
516 }
517 return changed
518 }
519
520 /** Marks a workflow agent whose turn completed as completed; returns whether it changed. */
521 settle(agentId: string, now?: number): boolean {
522 const a = this.agents.get(agentId)
523 if (a === undefined || !isWorkflowAgent(a) || ENDED.includes(a.status)) return false
524 this.agents.set(agentId, { ...a, status: 'completed', statusAt: now })
525 return true
526 }
527
528 nameOf(agentId: string | undefined): string {
529 if (agentId === undefined) return LEAD
530 return this.agents.get(agentId)?.name ?? agentId.slice(0, 8)
531 }
532
533 /** Agents whose loop is doing or about to do work. */
534 activeCount(): number {
535 let n = 0
536 for (const a of this.agents.values()) if (a.status === 'running' || a.status === 'pending' || a.status === 'waiting') n++
537 return n
538 }
539
540 /** Whether teammates were spawned and every one has ended. */
541 isTeamEnded(): boolean {
542 const mates = [...this.agents.values()].filter(a => a.isTeammate)
543 return mates.length > 0 && mates.every(a => ENDED.includes(a.status))
544 }
545
546 /** Whether a teammate ever went by `name` (bare team name). */
547 hasTeammate(name: string): boolean {
548 const n = bareName(name)
549 return [...this.agents.values()].some(a => a.isTeammate && bareName(a.name) === n)
550 }
551
552 /** Whether a teammate that goes by `name` (bare team name) ended at `since` or later and none by that name is live. */
553 hasStoppedSince(name: string, since: number): boolean {
554 const n = bareName(name)
555 const mates = [...this.agents.values()].filter(a => a.isTeammate && bareName(a.name) === n)
556 return mates.length > 0 && mates.every(a => ENDED.includes(a.status)) && mates.some(a => (a.statusAt ?? -Infinity) >= since)
557 }
558
559 /** Whether a teammate that goes by `name` (bare team name) has not ended. */
560 isLiveTeammate(name: string): boolean {
561 const n = bareName(name)
562 return [...this.agents.values()].some(a => a.isTeammate && bareName(a.name) === n && !ENDED.includes(a.status))
563 }
564
565 /** Agents not ended (completed, failed, killed). */
566 liveCount(): number {
567 let n = 0
568 for (const a of this.agents.values()) if (!ENDED.includes(a.status)) n++
569 return n
570 }
571
572 toJSON(now: number, session?: string) {
573 return {
574 updatedAt: new Date(now).toISOString(),
575 ...(session === undefined ? {} : { session }),
576 lead: { name: LEAD, status: this.leadBusy ? 'running' : 'idle' },
577 agents: [...this.agents.values()].map(a => {
578 const codeName = this.codeNames.get(bareName(a.name))
579 const idle = this.idle.get(bareName(a.name))
580 return {
581 ...a,
582 ...(codeName === undefined ? {} : { codeName, label: this.label(a.name) }),
583 ...(idle === undefined ? {} : { idleNotices: idle.count, lastIdleReason: idle.lastReason, lastIdleAt: idle.lastAt }),
584 }
585 }),
586 }
587 }
588}
589
590export class MessageLog {
591 readonly entries: LogEntry[] = []
592 /** Messages from a previous session's log file, newest last. */
593 earlier: LogEntry[] = []
594 total = 0
595 lastAt: number | null = null
596 readonly sent = new Map<string, number>()
597 readonly received = new Map<string, number>()
598 private recentSends: { from: string; to: string; text: string }[] = []
599 /** The texts of this plugin's own sends not yet delivered, by bare recipient name, at most `SEND_MEMORY` each. */
600 private readonly modUndelivered = new Map<string, string[]>()
601
602 /** Records one message; returns the entry, or undefined when it is the delivery of a recorded send. */
603 record(m: { ts: number; from: string; to: string; text: string; via: Via; fromId?: string; toId?: string }): LogEntry | undefined {
604 if (m.via === 'receive' && (this.isModDelivery(m.to, m.text) || this.isEchoOfSend(m.from, m.to, m.text))) return undefined
605 if (m.via !== 'receive' && isModName(m.from) && m.text.trim() !== '') {
606 const pending = this.modUndelivered.get(bareName(m.to)) ?? []
607 pending.push(m.text.trim())
608 if (pending.length > SEND_MEMORY) pending.splice(0, pending.length - SEND_MEMORY)
609 this.modUndelivered.set(bareName(m.to), pending)
610 }
611 if (m.via !== 'receive') {
612 this.recentSends.push({ from: m.from, to: m.to, text: m.text })
613 if (this.recentSends.length > SEND_MEMORY) this.recentSends.splice(0, this.recentSends.length - SEND_MEMORY)
614 }
615 const entry: LogEntry = {
616 ts: m.ts,
617 from: m.from,
618 to: m.to,
619 summary: firstLine(m.text),
620 length: m.text.length,
621 via: m.via,
622 }
623 const type = typeOf(m.text)
624 if (type) entry.type = type
625 if (m.fromId) entry.fromId = m.fromId
626 if (m.toId) entry.toId = m.toId
627 this.entries.push(entry)
628 if (this.entries.length > MEMORY_CAP) this.entries.splice(0, this.entries.length - MEMORY_CAP)
629 this.total++
630 this.lastAt = m.ts
631 this.sent.set(m.from, (this.sent.get(m.from) ?? 0) + 1)
632 this.received.set(m.to, (this.received.get(m.to) ?? 0) + 1)
633 return entry
634 }
635
636 /** Restores a logged line of this session as if it had just been recorded, without dedupe. */
637 restore(e: LogEntry) {
638 this.entries.push(e)
639 if (this.entries.length > MEMORY_CAP) this.entries.splice(0, this.entries.length - MEMORY_CAP)
640 this.total++
641 this.lastAt = this.lastAt === null ? e.ts : Math.max(this.lastAt, e.ts)
642 this.sent.set(e.from, (this.sent.get(e.from) ?? 0) + 1)
643 this.received.set(e.to, (this.received.get(e.to) ?? 0) + 1)
644 }
645
646 /** Whether a delivery to `to` carries the text of one of this plugin's own sends to it not yet delivered; that send then counts as delivered. */
647 private isModDelivery(to: string, text: string): boolean {
648 const pending = this.modUndelivered.get(bareName(to))
649 const t = text.trim()
650 const i = t === '' || pending === undefined ? -1 : pending.findIndex(st => t.includes(st) || st.includes(t))
651 if (i < 0) return false
652 pending!.splice(i, 1)
653 return true
654 }
655
656 /** Whether a delivery carries a recorded send's text, from the same sender or to the same recipient. */
657 private isEchoOfSend(from: string, to: string, text: string): boolean {
658 const t = text.trim()
659 if (t === '') return false
660 return this.recentSends.some(s => {
661 const st = s.text.trim()
662 if (st === '') return false
663 const sameEnd = bareName(s.from) === bareName(from) || bareName(s.to) === bareName(to) || from === 'peer' || from === 'coordinator'
664 return sameEnd && (t.includes(st) || st.includes(t))
665 })
666 }
667
668 last(n: number): LogEntry[] {
669 return this.entries.slice(-n)
670 }
671}
672
673/** Whether a logged line is an idle notification. */
674export function isIdleLine(e: LogEntry): boolean {
675 return e.type === 'IDLE'
676}
677
678/** Whether a logged line records a tool call (`FILE`, `ACT`, a refused spawn `REFUSED`) or a teammate joining or leaving (`JOIN`, `LEFT`), not a message. */
679export function isToolLine(e: LogEntry): boolean {
680 return e.type === 'FILE' || e.type === 'ACT' || e.type === 'REFUSED' || e.type === 'JOIN' || e.type === 'LEFT'
681}
682
683const WRITE_TOOLS = ['Edit', 'Write', 'MultiEdit', 'NotebookEdit']
684
685/**
686 * What a FILE line shows for a file tool call: `✎ <path>` for Edit, Write, MultiEdit and NotebookEdit, `◦ <path>` for Read,
687 * relative to `cwd` when inside it, else its last two segments after `…/`; undefined for any other call.
688 */
689export function fileOf(tool: string, input: unknown, cwd: string | null): string | undefined {
690 const mark = tool === 'Read' ? '◦' : WRITE_TOOLS.includes(tool) ? '✎' : undefined
691 const path = pathOf(input)
692 if (mark === undefined || path === undefined) return undefined
693 return `${mark} ${shownPath(path, cwd)}`
694}
695
696/** A path as a card shows it: relative to `cwd` when inside it, else its last two segments after `…/`. */
697function shownPath(path: string, cwd: string | null): string {
698 if (cwd !== null && path.startsWith(cwd + '/')) return path.slice(cwd.length + 1)
699 const parts = path.split('/').filter(Boolean)
700 return `${parts.length > 2 ? '…/' : ''}${parts.slice(-2).join('/')}`
701}
702
703/** One line of a tool call's input, at most `max` characters. */
704function brief(value: unknown, max = 48): string {
705 const line = (typeof value === 'string' ? value : '').split('\n')[0]!.replace(/\s+/g, ' ').trim()
706 return line.length > max ? line.slice(0, max - 1) + '…' : line
707}
708
709/**
710 * A tool call in plain words for a card: `Reading README.md`, `Editing hooks/core.ts`, `Running npm test`,
711 * `Searching 'claimOf'`, `Messaging t2`; `Using <tool>` for a tool it has no words for.
712 */
713export function actionOf(tool: string, input: unknown, cwd: string | null): string {
714 const i = (input ?? {}) as Record<string, unknown>
715 const path = pathOf(input)
716 const file = path === undefined ? '' : shownPath(path, cwd)
717 switch (tool) {
718 case 'Read': return `Reading ${file}`
719 case 'Write': return `Writing ${file}`
720 case 'Edit':
721 case 'MultiEdit':
722 case 'NotebookEdit': return `Editing ${file}`
723 case 'Bash': return `Running ${brief(i.command)}`
724 case 'Grep': return `Searching '${brief(i.pattern, 32)}'`
725 case 'Glob': return `Finding ${brief(i.pattern, 32)}`
726 case 'SendMessage': return `Messaging ${brief(i.to, 24)}`
727 case 'WebFetch': return `Fetching ${/^\w+:\/\/([^/]+)/.exec(brief(i.url, 200))?.[1] ?? 'a page'}`
728 case 'WebSearch': return `Searching the web for '${brief(i.query, 32)}'`
729 case 'Agent':
730 case 'Task': return 'Starting an agent'
731 default: return /^Task/.test(tool) ? 'Updating tasks' : `Using ${tool}`
732 }
733}
734
735/** The file a tool call names (`file_path`, else `notebook_path`), or undefined. */
736function pathOf(input: unknown): string | undefined {
737 const i = (input ?? {}) as { file_path?: unknown; notebook_path?: unknown }
738 const path = typeof i.file_path === 'string' ? i.file_path : typeof i.notebook_path === 'string' ? i.notebook_path : undefined
739 return path === '' ? undefined : path
740}
741
742/** The file an Edit, Write, MultiEdit or NotebookEdit call writes, or undefined for any other call. */
743export function writtenPath(tool: string, input: unknown): string | undefined {
744 return WRITE_TOOLS.includes(tool) ? pathOf(input) : undefined
745}
746
747/** Log lines from JSONL text; lines that are not entries are skipped. */
748export function parseLog(text: string): LogEntry[] {
749 const out: LogEntry[] = []
750 for (const line of text.split('\n')) {
751 if (line.trim() === '') continue
752 try {
753 const e = JSON.parse(line) as LogEntry
754 if (typeof e.ts === 'number' && typeof e.from === 'string' && typeof e.to === 'string' && typeof e.summary === 'string') out.push(e)
755 } catch {
756 continue
757 }
758 }
759 return out
760}
761
762/**
763 * Restores the log file's tail: this session's lines count as messages, a previous session's go to `earlier`. This session's
764 * idle lines give each agent's wait count (the larger of roster.json's count and the lines') and the time of its last wait.
765 */
766export function hydrateLog(log: MessageLog, roster: Roster, lines: readonly LogEntry[], session: string) {
767 const waits = new Roster()
768 for (const e of lines) {
769 if (isToolLine(e)) continue
770 if (e.session === session) {
771 if (isIdleLine(e)) waits.noteIdle(e.from, e.idleReason, e.ts)
772 else {
773 log.restore(e)
774 roster.noteMessage(e.from, e.ts)
775 }
776 } else if (!isIdleLine(e)) {
777 log.earlier.push(e)
778 }
779 }
780 for (const [name, w] of waits.idle) {
781 const prior = roster.idle.get(name)
782 roster.idle.set(name, { count: Math.max(prior?.count ?? 0, w.count), lastReason: w.lastReason ?? prior?.lastReason, lastAt: Math.max(prior?.lastAt ?? 0, w.lastAt ?? 0) || undefined })
783 }
784 if (log.earlier.length > MEMORY_CAP) log.earlier = log.earlier.slice(-MEMORY_CAP)
785}
786
787export function jsonl(entries: readonly LogEntry[]): string {
788 return entries.map(e => JSON.stringify(e)).join('\n') + (entries.length ? '\n' : '')
789}
790
791export function ago(ms: number): string {
792 const s = Math.max(0, Math.floor(ms / 1000))
793 if (s < 60) return s + 's'
794 const m = Math.floor(s / 60)
795 if (m < 60) return m + 'm'
796 return Math.floor(m / 60) + 'h' + String(m % 60).padStart(2, '0')
797}
798
799/**
800 * Decides when the lead is woken. Messages addressed to the lead are already
801 * delivered to it by the team mailbox, so they never cause a wake here.
802 */
803export class WakePolicy {
804 mode: WakeMode = 'mentions'
805 pending: LogEntry[] = []
806 firstPendingAt: number | null = null
807 lastDigestAt = 0
808 inFlight = false
809 /** Deliveries that reached the lead plus the mod's own wakes. */
810 wakes = 0
811 /** Deliveries the lead filter kept from the lead. */
812 held = 0
813
814 /** Considers one logged message; returns whether it was queued for a wake. */
815 offer(entry: LogEntry, text: string): boolean {
816 if (this.mode === 'off') return false
817 if (entry.from === LEAD || isLeadAddress(entry.from)) return false
818 if (isLeadAddress(entry.to)) return false
819 if (this.mode === 'mentions' && !mentionsLead(text)) return false
820 if (this.pending.length === 0) this.firstPendingAt = entry.ts
821 this.pending.push(entry)
822 return true
823 }
824
825 setMode(mode: WakeMode, now: number) {
826 this.mode = mode
827 this.pending = []
828 this.firstPendingAt = null
829 this.lastDigestAt = now
830 }
831
832 /** The wake text to submit now, or null; clears the queue when it returns text. */
833 due(now: number, leadBusy: boolean): string | null {
834 if (this.mode === 'off' || leadBusy || this.inFlight) return null
835 if (this.mode === 'digest') {
836 if (now - this.lastDigestAt < DIGEST_MS) return null
837 this.lastDigestAt = now
838 if (this.pending.length === 0) return null
839 } else {
840 if (this.pending.length === 0 || this.firstPendingAt === null) return null
841 if (now - this.firstPendingAt < COALESCE_MS[this.mode]) return null
842 }
843 const text = wakeText(this.mode, this.pending)
844 this.pending = []
845 this.firstPendingAt = null
846 return text
847 }
848}
849
850const HELD_TYPES = ['PROPOSE', 'CLAIM', 'HANDOFF', 'REVIEW']
851
852/**
853 * Whether the lead filter keeps a teammate's delivery from the lead: an idle notice whose reason is `available` or absent;
854 * else a `[PROPOSE]`, `[CLAIM]`, `[HANDOFF]` or `[REVIEW]` that neither mentions `@lead` nor has a line starting `[ASK]` or `[BLOCK]`.
855 */
856export function isHeldFromLead(text: string, idle: IdleNotice | undefined): boolean {
857 if (idle !== undefined) return idle.idleReason === undefined || idle.idleReason === 'available'
858 if (mentionsLead(text) || /^\s*(?:<[^>]*>\s*)?\[(?:ASK|BLOCK)\]/im.test(text)) return false
859 const type = typeOf(text.replace(/^\s*<[^>]*>/, ''))
860 return type !== undefined && HELD_TYPES.includes(type)
861}
862
863function wakeText(mode: WakeMode, entries: readonly LogEntry[]): string {
864 const shown = entries.slice(-12)
865 const lines = shown.map(e => `- ${e.from} → ${e.to}: ${e.summary}`)
866 const more = entries.length > shown.length ? [`- … ${entries.length - shown.length} earlier`] : []
867 const head = mode === 'mentions'
868 ? `swarm: ${entries.length} message(s) between teammates mention you:`
869 : `swarm (${mode}): ${entries.length} new message(s) between teammates:`
870 return [head, ...more, ...lines,
871 'Act only if a decision, a tie, a blocker or a budget call needs you; teammates coordinate the rest. Full log: .swarm/log.jsonl.'].join('\n')
872}
873
874/** The stall watchdog's nudge to a teammate holding open claims: what it holds and who has reported. */
875export function nudgeText(minutes: number, claims: readonly Claim[], reports: ReadonlyMap<string, { type: string }>, label: (name: string) => string): string {
876 const reported = [...reports].map(([name, r]) => `${label(name)} ${r.type}`)
877 const who = reported.length > 0 ? 'reported: ' + reported.join(', ') : 'nobody has reported'
878 return `[ASK] quiet ${minutes} min: you hold ${claims.map(c => c.key).join(', ')}; ${who}. Continue, or send [DONE]/[BLOCK].`
879}
880
881export function stallText(minutes: number, openTasks: number | null, openClaims = 0): string {
882 const tasks = openTasks === null ? 'task list unreadable' : `${openTasks} task(s) still open`
883 const claims = openClaims > 0 ? `, ${openClaims} claim(s) open` : ''
884 return `swarm stalled: no message for ${minutes} min, no agent running, ${tasks}${claims}. Check .swarm/roster.json and the task list; reassign, unblock or end the swarm.`
885}
886
887export type StallInput = {
888 now: number
889 lastActivityAt: number
890 stallMs: number
891 activeAgents: number
892 liveAgents: number
893 openTasks: number | null
894 /** Open message claims of live teammates: a `[CLAIM]` its holder has not released or reported on since (see `ClaimBoard.report`). */
895 openClaims: number
896 leadBusy: boolean
897 alreadyFired: boolean
898}
899
900/** Whether the stall watchdog should act now: quiet, nobody running, and work remains (an open claim, or open tasks). */
901export function isStalled(s: StallInput): boolean {
902 if (s.alreadyFired || s.leadBusy || s.activeAgents > 0) return false
903 if (s.now - s.lastActivityAt < s.stallMs) return false
904 if (s.openClaims > 0) return true
905 if (s.openTasks !== null) return s.openTasks > 0
906 return s.liveAgents > 0
907}
908
909/** Counts open tasks in task files; a file whose status is not readable counts as open. */
910export function openTaskCount(files: readonly string[]): number {
911 let open = 0
912 for (const text of files) {
913 try {
914 const task = JSON.parse(text) as { status?: unknown }
915 if (task.status !== 'completed' && task.status !== 'deleted') open++
916 } catch {
917 open++
918 }
919 }
920 return open
921}
922
923function pad(s: string, n: number): string {
924 if (s.length > n) return s.slice(0, Math.max(0, n - 1)) + '…'
925 return s.padEnd(n)
926}
927
928function clip(s: string, n: number): string {
929 return s.length > n ? s.slice(0, Math.max(0, n - 1)) + '…' : s
930}
931
932/** The band's counts: agents of the current team that have not ended, messages, time since the last one. */
933export function bandText(roster: Roster, log: MessageLog, now: number): string {
934 const n = [...roster.agents.values()].filter(a => !roster.isOther(a, now)).length
935 const last = log.lastAt === null ? '—' : ago(now - log.lastAt)
936 const earlier = log.earlier.length ? ` (${log.earlier.length} earlier)` : ''
937 return `swarm: ${n} agent${n === 1 ? '' : 's'} · ${log.total} msg${log.total === 1 ? '' : 's'}${earlier} · last ${last}`
938}
939
940/** The announced code names of `names` (bare team names) as `Atlas (t1), Sage (t2)`, or '' before any announcement. */
941export function namesText(roster: Roster, names: readonly string[]): string {
942 return names.filter(n => roster.codeNames.has(bareName(n))).map(n => roster.label(n)).join(', ')
943}
944
945/**
946 * One line per workflow run for its agents: `✓ workflow dev-team · 16 agents` once all ended, else with the running and
947 * pending counts. A run whose name the mod never saw shows its run id, or nothing.
948 */
949function workflowGroups(roster: Roster, agents: readonly RosterEntry[], now: number): { text: string; isOther: boolean }[] {
950 const runs = new Map<string, RosterEntry[]>()
951 for (const a of agents) {
952 if (!isWorkflowAgent(a)) continue
953 const key = a.workflowRunId ?? ''
954 runs.set(key, [...(runs.get(key) ?? []), a])
955 }
956 return [...runs].map(([runId, list]) => {
957 const name = roster.workflowNames.get(runId) ?? runId
958 const isDone = list.every(a => ENDED.includes(a.status))
959 const failed = list.filter(a => a.status === 'failed' || a.status === 'killed').length
960 const running = list.filter(a => a.status === 'running').length
961 const pending = list.filter(a => !ENDED.includes(a.status) && a.status !== 'running').length
962 const head = `${isDone ? (failed ? '✗' : '✓') : '●'} workflow${name ? ' ' + name : ''} · ${list.length} agent${list.length === 1 ? '' : 's'}`
963 const tail = isDone ? (failed ? ` · ${failed} failed` : '') : ` · ${running} running · ${pending} pending`
964 return { text: head + tail, isOther: isDone || list.every(a => roster.isOther(a, now)) }
965 })
966}
967
968const STATUS_MARK: Record<string, string> = {
969 running: '●', pending: '◌', waiting: '◐', idle: '○', stalled: '!', completed: '✓', failed: '✗', killed: '✗',
970}
971
972export type PaneRow = { text: string; dim?: boolean; bold?: boolean }
973
974/**
975 * The pane's rows: the header bold; roster rows of active agents, then agents outside the current team or settled for
976 * `STALE_MS` dimmed under `── other agents ──` and a previous session's agents under `── earlier ──`, each block its newest
977 * `OTHERS_SHOWN` after a `… N more` line; messages newest first, a previous session's dimmed under `── earlier ──` at the bottom.
978 */
979export function paneRows(roster: Roster, log: MessageLog, policy: WakePolicy, now: number, cols: number, maxMessages: number, board?: ClaimBoard, stallMs = DEFAULT_STALL_MIN * 60_000): PaneRow[] {
980 const w = Math.max(20, cols)
981 const out: string[] = []
982 const dim = new Set<number>()
983 out.push(clip(`${bandText(roster, log, now)} · wake: ${policy.mode}${policy.pending.length ? ` (${policy.pending.length} queued)` : ''} · wakes ${policy.wakes} · held ${policy.held}`, w))
984 out.push('')
985 out.push(clip('ROSTER name · model · status · sent/recv · waits', w))
986 const nameW = Math.min(LABEL_MAX, Math.max(8, Math.floor(w * 0.3)))
987 const models = [...roster.agents.values(), ...roster.earlier].map(a => shortModel(a.model))
988 const modelW = w >= 48 ? Math.max(1, ...models.map(m => m.length)) : 0
989 const statusW = 10
990 const dups = roster.duplicateCodes()
991 const nameCell = (name: string, isCurrent = true) => {
992 const mark = isCurrent && dups.has(bareName(name)) ? ' ⚠ dup' : ''
993 return pad(clip(roster.label(name), nameW - mark.length) + mark, nameW)
994 }
995 const row = (name: string, model: string, status: string) => {
996 const idle = roster.idle.get(bareName(name))
997 const reason = idle?.lastReason !== undefined && idle.lastReason !== 'available' ? ` (${idle.lastReason})` : ''
998 const age = idle?.lastAt !== undefined ? ` · ${ago(now - idle.lastAt)} ago` : ''
999 const counts = `${log.sent.get(name) ?? 0}/${log.received.get(name) ?? 0}${idle ? ` · waits ${idle.count}${reason}${age}` : ''}`
1000 const mark = STATUS_MARK[status] ?? '?'
1001 return clip(`${mark} ${nameCell(name)} ${modelW ? model.padEnd(modelW) + ' ' : ''}${pad(status, statusW)} ${counts}`, w)
1002 }
1003 out.push(row(LEAD, '', roster.leadBusy ? 'running' : 'idle'))
1004 const all = [...roster.agents.values()]
1005 const agents = all.filter(a => !isWorkflowAgent(a))
1006 const others = agents.filter(a => roster.isOther(a, now))
1007 const groups = workflowGroups(roster, all, now)
1008 const hasStalled = (name: string) => {
1009 const since = roster.idleSince(name)
1010 return stallMs > 0 && since !== undefined && now - since > stallMs && (board?.openClaims(name).length ?? 0) > 0
1011 }
1012 const shown = agents.filter(a => !others.includes(a))
1013 const nested = others.filter(c => c.parentId !== undefined && !roster.isShownEnded(c, now) && shown.some(a => a.id === c.parentId))
1014 for (const a of shown) {
1015 out.push(row(a.name, shortModel(a.model), hasStalled(a.name) ? 'stalled' : a.status))
1016 for (const c of nested) if (c.parentId === a.id) out.push(clip(' └ ' + row(c.name, shortModel(c.model), c.status), w))
1017 }
1018 for (const g of groups) if (!g.isOther) out.push(clip(g.text, w))
1019 const newest = (lines: readonly string[]) => {
1020 const more = lines.length - OTHERS_SHOWN
1021 for (const l of more > 0 ? [` … ${more} more`, ...lines.slice(-OTHERS_SHOWN)] : lines) {
1022 dim.add(out.length)
1023 out.push(l)
1024 }
1025 }
1026 const otherLines = [...groups.filter(g => g.isOther).map(g => clip(g.text, w)), ...others.filter(a => !nested.includes(a)).map(a => row(a.name, shortModel(a.model), a.status))]
1027 if (otherLines.length > 0) {
1028 out.push(OTHER_AGENTS)
1029 newest(otherLines)
1030 }
1031 if (roster.earlier.length > 0) {
1032 out.push(EARLIER)
1033 newest(roster.earlier.map(a => clip(` ${nameCell(a.name, false)} ${modelW ? shortModel(a.model).padEnd(modelW) + ' ' : ''}`.trimEnd(), w)))
1034 }
1035 if (board !== undefined) {
1036 out.push('')
1037 out.push('CLAIMS')
1038 const isStale = (n: string) => now - (roster.lastMessageAt.get(bareName(n)) ?? now) > CLAIM_TTL_MIN * 60_000
1039 const lines = claimLines(board, n => roster.label(n) + (isStale(n) ? ' stale' : ''))
1040 if (lines.length === 0) out.push('(none yet)')
1041 for (const l of lines) out.push(clip(l, w))
1042 }
1043 out.push('')
1044 const current = log.last(maxMessages)
1045 const earlier = log.earlier.slice(log.earlier.length - Math.max(0, maxMessages - current.length))
1046 out.push(clip(`MESSAGES last ${current.length} of ${log.total}${log.earlier.length ? ` · ${log.earlier.length} earlier` : ''}`, w))
1047 const line = (e: LogEntry) => clip(`${timeOfDay(e.ts)} ${roster.label(e.from)} → ${roster.label(e.to)}: ${e.summary}`, w)
1048 if (current.length === 0 && earlier.length === 0) out.push('(none yet)')
1049 for (const e of [...current].reverse()) out.push(line(e))
1050 if (earlier.length > 0) {
1051 out.push(EARLIER)
1052 for (const e of [...earlier].reverse()) {
1053 dim.add(out.length)
1054 out.push(line(e))
1055 }
1056 }
1057 return out.map((text, i) => ({ text, ...(i === 0 ? { bold: true } : {}), ...(dim.has(i) ? { dim: true } : {}) }))
1058}
1059
1060const CLAIM_TAG = /^(?:<[^>]*>\s*)?\[CLAIM\]\s*(.*)$/i
1061const ROLE_WORDS: Record<string, string> = {
1062 build: 'build', builder: 'build', builds: 'build', building: 'build',
1063 review: 'review', reviewer: 'review', reviews: 'review',
1064 research: 'research', researcher: 'research', researches: 'research',
1065}
1066const DELIVERABLE_LINE = /^[\s*_>-]*deliverables?[*_]*\s*:[*_]*\s*(.+)$/gim
1067
1068export type ClaimRef = { role: string; target: string }
1069export type Claim = ClaimRef & { key: string; by: string[] }
1070export type TaskRow = { subject: string; owner?: string; status: string }
1071
1072/** Whether a word names a file or a path: it holds a `/` or ends in a file extension. */
1073function isPathLike(word: string): boolean {
1074 return word.includes('/') || /\.[a-z][a-z0-9]{0,7}$/.test(word)
1075}
1076
1077/**
1078 * Role and target of a claim subject: `build var/gaps.md` → { role: 'build', target: 'var/gaps.md' }. A target that starts
1079 * with a path or file name is that path alone: `research docs/05-x.md (h14). output: …` → `docs/05-x.md`.
1080 */
1081function parseClaimSubject(subject: string): ClaimRef {
1082 const words = subject.trim().replace(/\s+/g, ' ').split(' ')
1083 const head = (words[0] ?? '').toLowerCase().replace(/[:,]$/, '')
1084 const role = ROLE_WORDS[head]
1085 const rest = (role === undefined ? words : words.slice(1)).join(' ')
1086 const target = rest.toLowerCase().replace(/^(of|the|for)\s+/, '').replace(/[`"'„“”]/g, '').replace(/[.,;:!]+$/, '').trim()
1087 const path = /^[^\s,;()]+/.exec(target)?.[0]?.replace(/[.:!]+$/, '')
1088 return { role: role ?? 'other', target: path !== undefined && isPathLike(path) ? path : target }
1089}
1090
1091/**
1092 * Whether a claim subject is a sentence fragment, not a target. Judged on its target token, the first word after the role
1093 * word, or the inside of a quoted or bracketed start: a fragment when that is empty, holds a `"`, says `please`, or holds a
1094 * space outside quotes (`"group A"` and `` `group A` `` name one slice of several words).
1095 */
1096function isFragment(subject: string): boolean {
1097 const rest = subject.trim().replace(/^(\S+)\s*/, (w, head: string) => (ROLE_WORDS[head.toLowerCase().replace(/[:,]$/, '')] === undefined ? w : ''))
1098 const wrapped = /^(?:"([^"]*)"|`([^`]*)`|\(([^)]*)\))/.exec(rest)
1099 const token = wrapped === null ? (rest.split(/\s/)[0] ?? '') : (wrapped[1] ?? wrapped[2] ?? wrapped[3] ?? '').trim()
1100 const isQuoted = wrapped !== null && wrapped[3] === undefined
1101 return token === '' || token.includes('"') || (/\s/.test(token) && !isQuoted) || /please/i.test(token)
1102}
1103
1104/**
1105 * The rest of the line after the first `[CLAIM]` that is a claim's own tag: any one not inside quotes or backticks and not
1106 * right after a possessive (`v18's [CLAIM] …`) or after my, your, his, her, their, its, the, a, own, confirm, quote(d),
1107 * send, sends or sent, which quote or report another claim.
1108 */
1109function claimSubjectOf(text: string): string | undefined {
1110 for (const line of unstamped(text).split('\n')) {
1111 for (const m of line.matchAll(/\[CLAIM\]/gi)) {
1112 const before = line.slice(0, m.index)
1113 if (((before.match(/["`“”]/g)?.length ?? 0) % 2) === 1) continue
1114 if (/(?:['’]s|\b(?:my|your|his|her|their|its|the|a|own|confirm|quote|quoted|send|sends|sent))\s*$/i.test(before)) continue
1115 return line.slice(m.index + m[0].length).trim()
1116 }
1117 }
1118 return undefined
1119}
1120
1121/**
1122 * The target token of a claim subject after its role word, lower-cased: the first word, or the inside of a quoted or
1123 * bracketed start, after a leading `of`, `the` or `for`; cut at a `,`, `;`, `(` or `|` and without quotes, a leading `*` or trailing `.:!)*`.
1124 * `research core-aa (u1, sonnet)` → `core-aa`, `build #155 (hydration fix)` → `#155`, `build (docs/x.md)` → `docs/x.md`.
1125 */
1126function claimTarget(rest: string): string {
1127 const r = rest.trim().replace(/^(?:of|the|for)\s+/i, '')
1128 const wrapped = /^(?:"([^"]*)"|`([^`]*)`|\(([^)]*)\))/.exec(r)
1129 const token = wrapped === null ? (r.split(/\s/)[0] ?? '') : (wrapped[1] ?? wrapped[2] ?? wrapped[3] ?? '').trim()
1130 return (token.toLowerCase().replace(/[`"'„“”]/g, '').replace(/^\*+/, '').split(/[,;(|]/)[0] ?? '').replace(/[.:!)*]+$/, '')
1131}
1132
1133/**
1134 * The claim a message makes: `[CLAIM] <role> <target>` on its first line, else after the first `[CLAIM]` anywhere in it
1135 * (`Slice wanted: [CLAIM] build #158 (…)` inside a hello); the target is its target token (see `claimTarget`), never the
1136 * words after it. None when the subject is a fragment or its first word is no role (`build`, `review`, `research`), none
1137 * for a first line `[CLAIM] <target> is withdrawn|is released …`, which releases it, and none for a first line that reports
1138 * who holds it (`[CLAIM] <target> is already taken: …`, `… claimed by w2`; see `isClaimReport`).
1139 */
1140export function claimOf(text: string): ClaimRef | undefined {
1141 if (isClaimReport(firstLine(text, 400))) return undefined
1142 const subject = CLAIM_TAG.exec(firstLine(text, 400))?.[1] ?? claimSubjectOf(text)
1143 if (subject === undefined || isFragment(subject)) return undefined
1144 const words = subject.trim().split(/\s+/)
1145 const role = ROLE_WORDS[(words[0] ?? '').toLowerCase().replace(/[:,]$/, '')]
1146 if (role === undefined) return undefined
1147 const target = claimTarget(subject.trim().slice((words[0] ?? '').length))
1148 return target === '' ? undefined : { role, target }
1149}
1150
1151const RELEASE_TAG = /^(?:<[^>]*>\s*)?\[(?:RELEASE|WITHDRAW)\]\s*(.+)$/i
1152const RELEASED = String.raw`(?!(?:the|my|a|an|it|this|that)\b)((?:(?:build|review|research)\s+)?[^\s,;:()]+)`
1153const RELEASE_SAID = new RegExp(String.raw`^(?:<[^>]*>\s*)?(?:\[[A-Za-z]+\]\s*)?(?:[\w-]+:\s*)?(?:I\s+(?:release|withdraw|drop\s+my\s+claim\s+on)\s+${RELEASED}|I\s+drop\s+my\s+${RELEASED}\s+claim\b|Yield(?:ing)?\s+${RELEASED}\s+to\s)`, 'i')
1154const CLAIM_RELEASED = new RegExp(String.raw`^(?:<[^>]*>\s*)?\[CLAIM\]\s*${RELEASED}\s+is\s+(?:withdrawn|released)\b`, 'i')
1155const CLAIM_REPORTED = new RegExp(String.raw`^(?:<[^>]*>\s*)?\[CLAIM\]\s*${RELEASED}\s+(?:is\s+(?:already\s+)?(?:taken|held)\b|is\s+already\s+claimed\b|(?:is\s+)?(?:already\s+)?(?:claimed|held|taken)\s+by\b)`, 'i')
1156
1157/**
1158 * Whether a first line is `[CLAIM] <target> is withdrawn|released …`, or reports a holder: `[CLAIM] <target> is (already)
1159 * taken|held`, `is already claimed`, or `(is) claimed|held|taken by …`. No claim.
1160 */
1161function isClaimReport(line: string): boolean {
1162 return CLAIM_RELEASED.test(line) || CLAIM_REPORTED.test(line)
1163}
1164const RELEASED_TO = new RegExp(String.raw`^(?:the\s+)?${RELEASED}\s+claim\s+is\s+released\s+to\s`, 'i')
1165
1166/**
1167 * What a message gives up, or undefined: the target after a first-line `[RELEASE] <target>` or `[WITHDRAW] <target>`; the
1168 * one word (after an optional role word) of a first clause, after an optional `<name>:`, `I release|withdraw|drop my claim
1169 * on <target>`, `I drop my <target> claim` or `Yielding <target> to …`; or of a first-line sentence `The <target> claim is
1170 * released to …`; or of a first line `[CLAIM] <target> is withdrawn|is released …`, which is no claim. A word that is `the`, `my`, `a`, `an`, `it`, `this` or `that` names no target. Nothing else is a release.
1171 */
1172export function releaseOf(text: string): string | undefined {
1173 const line = firstLine(text, 400)
1174 const said = RELEASE_SAID.exec(line.split(/\.\s|;|\s[—–-]\s/)[0] ?? '')
1175 const target = RELEASE_TAG.exec(line)?.[1] ?? CLAIM_RELEASED.exec(line)?.[1] ?? said?.slice(1).find(g => g !== undefined) ?? line.split(/\.\s|;\s*/).map(s => RELEASED_TO.exec(s.trim())?.[1]).find(g => g !== undefined)
1176 return target === undefined || target.trim() === '' ? undefined : target.trim()
1177}
1178
1179/**
1180 * Whether a text names a claim target: its first word, that word's file name, the file name without its extension, or the
1181 * file name's leading number (`03` for `docs/03-accounts.md`), each as a whole word.
1182 */
1183export function mentionsTarget(text: string, target: string): boolean {
1184 const t = text.toLowerCase()
1185 const head = (target.toLowerCase().split(/[\s(,;]/)[0] ?? '').replace(/[.:!]+$/, '')
1186 const base = baseName(head)
1187 const words = [head, base, base.replace(/\.[a-z][a-z0-9]{0,7}$/, ''), /^(\d+)-/.exec(base)?.[1] ?? ''].filter(w => w.length >= 2)
1188 const esc = (w: string) => w.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
1189 return words.some(w => new RegExp(`(^|[^\\w-])${esc(w)}($|[^\\w-])`).test(t))
1190}
1191
1192/** The `Deliverable: <path>` lines of a brief; several split on `,` or `;`. */
1193export function deliverablesOf(text: string): string[] {
1194 const out: string[] = []
1195 for (const m of text.matchAll(DELIVERABLE_LINE)) {
1196 for (const part of (m[1] ?? '').split(/[;,]/)) {
1197 const d = part.replace(/[`*_]/g, '').trim()
1198 if (d !== '' && !out.includes(d)) out.push(d)
1199 }
1200 }hooks/pane.ts 564 lines1// The pane's stage at run time: the live team and `/swarm replay`, drawn by look A or B in bands of Rasters and Images;
2// cells move frame by frame while an event lands, Images are sent only when what they draw changed.
3
4import type { EngineInterface, RenderElement, RenderInputOf } from 'claude-code'
5
6import { parseLog } from './core'
7import { css } from './grid'
8import { newSidecar, pauseSidecar, quitSidecar, startSidecar, updateSidecar } from './sidecar'
9import type { LogEntry } from './core'
10import { FLASH_MS, PULSE_MS } from './looks'
11import type { Frame, View } from './looks'
12import { IMAGE_MIN_MS, ImageShelf, LOOK_FNS, STOP_ALL_KEY, agentControls, bandsOf, controlRows, controlsOf, shapeOf, stopControls, viewControls } from './pane-draw'
13import type { Control } from './pane-draw'
14import { Scene, modelsOf, parseReplayArgs, resolveCodes, runTitle, schedule, splitRuns, windowOf } from './replay'
15import type { Look, Level, ReplayArgs, Run } from './replay'
16
17export const PANE = 'swarm'
18/** The key of the live pane's field that messages the agent it is filtered to. */
19export const COMPOSE_KEY = 'compose'
20/** Real ms between animation frames while a message travels or a change glows. */
21const FRAME_MS = 80
22/** How long after the latest event the animation keeps running. */
23const ANIMATE_MS = Math.max(PULSE_MS, FLASH_MS * 1.5)
24/** A 1×1 picture the pane draws once to learn whether the terminal shows pictures. */
25const PROBE_SOURCE = { rgba: 'AAAA/w==', width: 1, height: 1 }
26
27export type LevelSetting = Level | 'auto'
28
29/** The person's level choice; `auto` is rich where the terminal draws pictures. */
30let levelSetting: LevelSetting = 'auto'
31/** Whether a probe Image drew as a picture (true) or the terminal draws none (false); undefined until a blit tells. */
32let imagesDrawn: boolean | undefined
33/** Probe blits refused for another reason (no image id free, not yet mounted); the pane stops asking after `PROBE_TRIES`. */
34let probeRefusals = 0
35const PROBE_TRIES = 3
36
37export function setLevel(level: LevelSetting) {
38 levelSetting = level
39}
40
41/** The level a stage draws at: an explicit one, else the setting, `auto` resolved by the probe. */
42function levelOf(explicit?: Level): Level {
43 const l = explicit ?? levelSetting
44 return l === 'auto' ? (imagesDrawn === true ? 'rich' : 'basic') : l
45}
46
47/** What a stage draws now, at a size and a real time. */
48type FrameOf = (cols: number, rows: number, realNow: number) => Frame
49
50type Stage = {
51 look: Look
52 filter?: string
53 anim?: { cancel: () => void }
54 /** The next paint while an image still fades after the motion ended. */
55 settle?: { cancel: () => void }
56 /** The real ms the last frame's images still change, and its cells still move, by themselves. */
57 fadeMs: number
58 motionMs: number
59 lastEventReal: number
60 /** The stage size the pane last drew, and the bands' shape then. */
61 size?: { cols: number; rows: number }
62 shape?: string
63 /** The source each Image shows, sent at most once a second. */
64 images: ImageShelf
65}
66
67function newStage(look: Look): Stage {
68 return { look, lastEventReal: 0, images: new ImageShelf(), fadeMs: 0, motionMs: 0 }
69}
70
71type Replay = Stage & {
72 level?: Level
73 speed: number
74 run: Run
75 lines: LogEntry[]
76 realAt: number[]
77 scene: Scene
78 /** The next line to play. */
79 next: number
80 /** The real time playback would have started at, paused time left out. */
81 startReal: number
82 pausedAt?: number
83 /** When each played run time was played, in real ms. */
84 played: Map<number, number>
85 timer?: { cancel: () => void }
86 /** Whether it played its last line; it then hands the pane back to the live view after `REPLAY_HOLD_MS`. */
87 isFinished: boolean
88 /** Whether live team activity came while it played: the pane offers `[ live ]`. */
89 isLiveWaiting: boolean
90}
91
92/** How long a finished replay holds its end frame before the pane shows the live view again. */
93export const REPLAY_HOLD_MS = 3_000
94
95/** What the live stage draws: the current team's scene, its title and when it started. */
96/** What the live pane draws; `endedAt`, once every teammate of the team has ended: its last activity, where the clock holds. */
97export type LiveSource = { scene: Scene; title: string; from: number; endedAt?: number }
98
99export type LiveView = Look | 'list'
100
101let replay: Replay | undefined
102const live: Stage & { view: LiveView; source?: () => LiveSource } = { ...newStage('A'), view: 'A' }
103
104export function isReplaying(): boolean {
105 return replay !== undefined
106}
107
108/** The agent the live pane is filtered to, or undefined. */
109export function liveFilter(): string | undefined {
110 return live.filter
111}
112
113/** Which live view the pane shows: look A (the default), look B, or the text list. */
114export function liveView(): LiveView {
115 return live.view
116}
117
118function stopReplay() {
119 replay?.timer?.cancel()
120 replay?.anim?.cancel()
121 replay?.settle?.cancel()
122 replay = undefined
123}
124
125function replayFrame(r: Replay): FrameOf {
126 return (cols, rows, realNow) => {
127 const last = r.lines[r.next - 1]
128 const view: View = {
129 cols,
130 rows,
131 level: lookLevel(r.look, levelOf(r.level)),
132 now: last?.ts ?? r.run.from,
133 runFrom: r.run.from,
134 runTo: r.run.to,
135 title: runTitle(r.run.names),
136 speed: r.speed,
137 isPaused: r.pausedAt !== undefined,
138 age: ts => {
139 const at = r.played.get(ts)
140 return at === undefined ? Infinity : realNow - at
141 },
142 ...(r.filter === undefined ? {} : { filter: r.filter }),
143 ...(r.isFinished || r.isLiveWaiting ? { note: [...(r.isFinished ? ['replay finished'] : []), ...(r.isLiveWaiting ? ['live swarm running'] : [])].join(' · ') } : {}),
144 }
145 return LOOK_FNS[r.look](r.scene, view)
146 }
147}
148
149function liveFrame(src: LiveSource): FrameOf {
150 return (cols, rows, realNow) => {
151 const now = src.endedAt ?? realNow
152 const view: View = {
153 cols,
154 rows,
155 level: lookLevel(live.look, levelOf()),
156 now,
157 runFrom: src.from,
158 runTo: Math.max(now, src.from + 1),
159 title: src.title,
160 isPaused: false,
161 ...(src.endedAt === undefined ? {} : { isEnded: true }),
162 age: ts => realNow - ts,
163 ...(live.filter === undefined ? {} : { filter: live.filter }),
164 }
165 return LOOK_FNS[live.look](src.scene, view)
166 }
167}
168
169/** The stage on screen now and how to draw it, or undefined when the pane shows no stage. */
170function current(): { stage: Stage; frame: FrameOf } | undefined {
171 if (replay !== undefined) return { stage: replay, frame: replayFrame(replay) }
172 if (live.view !== 'list' && live.source !== undefined) return { stage: live, frame: liveFrame(live.source()) }
173 return undefined
174}
175
176/** Plays every line that is due, schedules the next one, and animates when anything played; the last line draws the pane in full. */
177async function step($: EngineInterface) {
178 const r = replay
179 if (r === undefined || r.pausedAt !== undefined) return
180 r.timer = undefined
181 const now = await $.clock.now()
182 const elapsed = now - r.startReal
183 let played = false
184 while (r.next < r.lines.length && r.realAt[r.next]! <= elapsed) {
185 const e = r.lines[r.next]!
186 r.scene.apply(e)
187 r.played.set(e.ts, now)
188 r.next++
189 played = true
190 }
191 if (played) {
192 r.lastEventReal = now
193 animate($, r)
194 }
195 if (r.next < r.lines.length) {
196 r.timer = $.clock.after(Math.max(1, r.realAt[r.next]! - elapsed), () => {
197 void step($)
198 })
199 } else if (played) {
200 r.isFinished = true
201 $.ui.invalidate('ui.render')
202 $.ui.toast('swarm: replay finished')
203 r.timer = $.clock.after(REPLAY_HOLD_MS, () => {
204 if (replay !== r) return
205 stopReplay()
206 $.ui.invalidate('ui.render')
207 })
208 }
209}
210
211/** Live team activity (a teammate spawned, a peer message) while a replay shows: the pane offers `[ live ]` (key 0). */
212export function liveActivity($: EngineInterface) {
213 if (replay === undefined || replay.isLiveWaiting) return
214 replay.isLiveWaiting = true
215 $.ui.invalidate('ui.render')
216}
217
218/** A live event landed: the live stage animates while it moves on screen. */
219export async function liveEvent($: EngineInterface) {
220 if (replay !== undefined || live.size === undefined || live.view === 'list') return
221 live.lastEventReal = await $.clock.now()
222 animate($, live)
223}
224
225/** Runs frames while the latest event still moves on screen (a frame's `motionMs`), then stops; never a frame without an event. */
226function animate($: EngineInterface, s: Stage) {
227 if (s.anim !== undefined) return
228 void paint($)
229 s.anim = $.clock.every(FRAME_MS, () => {
230 void (async () => {
231 const now = await $.clock.now()
232 if (now - s.lastEventReal > ANIMATE_MS && s.motionMs <= 0) {
233 s.anim?.cancel()
234 s.anim = undefined
235 }
236 if (current()?.stage === s) await paint($)
237 if (s.anim === undefined) settle($, s)
238 })()
239 })
240}
241
242/** After the motion, paints once a second while the stage's images still fade, then stops. */
243function settle($: EngineInterface, s: Stage) {
244 s.settle?.cancel()
245 s.settle = undefined
246 if (s.fadeMs <= 0) return
247 s.settle = $.clock.after(IMAGE_MIN_MS, () => {
248 s.settle = undefined
249 if (s.anim !== undefined || current()?.stage !== s) return
250 void paint($).then(() => settle($, s))
251 })
252}
253
254/**
255 * Repaints the mounted stage: every Raster by blit, an Image only when its sig changed; a change of shape (an agent
256 * appeared, a resize) draws the pane again instead.
257 */
258async function paint($: EngineInterface) {
259 try {
260 await paintNow($)
261 } catch (err) {
262 $.ui.log('swarm paint: ' + String(err))
263 }
264}
265
266async function paintNow($: EngineInterface) {
267 const cur = current()
268 const size = cur?.stage.size
269 if (cur === undefined || size === undefined) return
270 const s = cur.stage
271 const now = await $.clock.now()
272 const frame = cur.frame(size.cols, size.rows, now)
273 s.fadeMs = frame.fadeMs ?? 0
274 s.motionMs = frame.motionMs ?? 0
275 await feedSky($, frame, now)
276 const bands = bandsOf(frame)
277 if (shapeOf(bands) !== s.shape) {
278 $.ui.invalidate('ui.render')
279 return
280 }
281 for (const b of bands) {
282 for (const p of b.pieces) {
283 if (p.kind === 'raster') {
284 await $.ui.blit({ requestId: PANE, key: p.key, cells: frame.grid.cells(p.x, b.y, p.cols, b.rows), columns: p.cols, rows: b.rows })
285 } else if (p.layer.stream === undefined) {
286 const { source, isNew } = s.images.take(p.layer, now)
287 if (isNew && (await $.ui.blit({ requestId: PANE, key: p.layer.key, source })).deny !== undefined) s.images.forget(p.layer.key)
288 }
289 }
290 }
291}
292
293/** The look B sky renderer process, while a stage draws look B rich. */
294const sky = newSidecar(PANE, 'sky')
295let skyDir: string | undefined
296/**
297 * Starts the renderer through the session's `$`, on its clock: a child spawned through a render's or a paint's `$` is
298 * killed when that dispatch is abandoned (a render superseded, its budget spent). Set at `session.start`.
299 */
300let startSky: ((dir: string) => void) | undefined
301
302/** Makes the session's `$` the owner of the sky renderer. */
303export function ownSky($: EngineInterface) {
304 startSky = dir => {
305 $.clock.after(0, () => startSidecar($, sky, dir))
306 }
307}
308
309/**
310 * Keeps the sky renderer in step with a frame: started and handed the scene while the frame has a streamed sky, stopped
311 * when it has none.
312 */
313async function feedSky($: EngineInterface, frame: Frame, now: number) {
314 const layer = frame.images.find(im => im.stream !== undefined)
315 if (layer === undefined) return pauseSidecar($, sky)
316 if (sky.state === 'failed') return
317 if (sky.state === 'off') {
318 if (startSky === undefined) return
319 skyDir ??= `${(await $.env.get('TMPDIR')) ?? '/tmp'}`.replace(/\/+$/, '') + `/swarm-${(await $.session.id()).slice(0, 8)}`
320 sky.state = 'starting'
321 sky.dir = skyDir
322 startSky(skyDir)
323 return
324 }
325 await updateSidecar($, sky, now, layer.stream!)
326}
327
328/** The level look `look` draws at: basic for look B once the sky renderer failed. */
329function lookLevel(look: Look, level: Level): Level {
330 return look === 'B' && sky.state === 'failed' ? 'basic' : level
331}
332
333/** What the sky Image shows until the renderer's first frame: one pixel of the sky's dark ground. */
334const SKY_WAIT = { rgba: 'BwYO/w==', width: 1, height: 1 }
335
336/** The sky renderer's state for `/swarm status`. */
337export function skyStatus(): string {
338 const ms = [...sky.renderMs].sort((a, b) => a - b)
339 if (sky.state === 'failed') return 'failed (' + sky.failure + '), look B draws the basic sky'
340 const notes = [...(sky.crash === undefined ? [] : ['crashed once: ' + sky.crash]), ...(ms.length > 0 ? [`${ms[ms.length >> 1]!.toFixed(1)} ms a frame`] : [])]
341 return sky.state + (notes.length > 0 ? ` (${notes.join('; ')})` : '')
342}
343
344/**
345 * Blits the probe Image once it is mounted: taken, the terminal draws pictures; refused because the terminal draws no
346 * placeholder images, it does not. Any other refusal counts toward `PROBE_TRIES`.
347 */
348async function probe($: EngineInterface) {
349 if (imagesDrawn !== undefined || probeRefusals >= PROBE_TRIES) return
350 const res = await $.ui.blit({ requestId: PANE, key: 'probe', source: PROBE_SOURCE }).catch(() => ({ deny: 'no blit' }))
351 if (res.deny === undefined) imagesDrawn = true
352 else if (/no placeholder images/i.test(res.deny)) imagesDrawn = false
353 else if (++probeRefusals < PROBE_TRIES) return
354 $.ui.invalidate('ui.render')
355}
356
357/** The run to play: the window the flags give, else the most recent run. */
358function pickRun(lines: readonly LogEntry[], runs: readonly Run[], args: ReplayArgs): Run | undefined {
359 if (args.from !== undefined || args.to !== undefined) {
360 const from = args.from ?? -Infinity
361 const to = args.to ?? Infinity
362 const inside = windowOf(lines, from, to)
363 if (inside.length === 0) return undefined
364 const names = [...new Set(splitRuns(inside).flatMap(r => r.names))]
365 return { from: inside[0]!.ts, to: inside[inside.length - 1]!.ts, count: inside.length, names }
366 }
367 return [...runs].sort((a, b) => b.from - a.from)[0]
368}
369
370/** `/swarm replay …`: starts or stops a replay; the text lists the runs the log holds. */
371export async function replayCommand($: EngineInterface, rest: string): Promise<{ text: string }> {
372 const parsed = parseReplayArgs(rest)
373 if ('error' in parsed) return { text: parsed.error }
374 if ('stop' in parsed) {
375 const was = replay !== undefined
376 stopReplay()
377 $.ui.invalidate('ui.render')
378 return { text: was ? 'replay stopped; the pane shows the live swarm' : 'no replay running' }
379 }
380 const args = parsed.args
381 const path = args.path.startsWith('/') ? args.path : (await $.session.cwd()) + '/' + args.path
382 let text: string
383 try {
384 text = await $.fs.read(path)
385 } catch (err) {
386 return { text: `cannot read ${path}: ${String(err)}` }
387 }
388 const lines = resolveCodes(parseLog(text))
389 const runs = splitRuns(lines)
390 const run = pickRun(lines, runs, args)
391 if (run === undefined) return { text: `no run in ${path}${args.from !== undefined || args.to !== undefined ? ' between those times' : ''}` }
392 let rosterJson: unknown = null
393 const rosterPath = path.replace(/[^/]*$/, 'roster.json')
394 try {
395 if (await $.fs.exists(rosterPath)) rosterJson = JSON.parse(await $.fs.read(rosterPath))
396 } catch {
397 rosterJson = null
398 }
399 stopReplay()
400 const win = windowOf(lines, run.from, run.to)
401 const scene = new Scene(modelsOf(rosterJson))
402 scene.seed(run.names, run.from, false)
403 replay = {
404 ...newStage(args.look),
405 ...(args.level === undefined ? {} : { level: args.level }),
406 speed: args.speed,
407 run,
408 lines: win,
409 realAt: schedule(win, args.speed),
410 scene,
411 next: 0,
412 startReal: await $.clock.now(),
413 played: new Map(),
414 isFinished: false,
415 isLiveWaiting: false,
416 }
417 await $.ui.open({ id: PANE, title: 'swarm replay', focus: true })
418 $.ui.invalidate('ui.render')
419 void step($)
420 const list = runs.map(r => ` ${r === run ? '▶' : ' '} ${runTitle(r.names).padEnd(12)} --from ${new Date(r.from).toISOString()} --to ${new Date(r.to).toISOString()} (${r.count} lines)`)
421 return { text: [`replaying ${runTitle(run.names)} at ${args.speed}× · look ${args.look} ${levelOf(args.level)}; stop with /swarm replay stop`, 'runs in this log:', ...list].join('\n') }
422}
423
424/**
425 * The stage's tree: the control row first, so a body the host cuts short never hides it, then the bands of Rasters and
426 * Images sized to the rows the control row (as wrapped) and the caller's rows leave, the caller's rows, and the claim paths when rich.
427 */
428async function renderStage($: EngineInterface, e: RenderInputOf<'Pane', 'terminal'>, s: Stage, level: Level, frameOf: FrameOf, controls: Control[], extra: RenderElement[]): Promise<RenderElement> {
429 const { Box, Text, Raster, Image, Link } = $.ui.resolve(e)
430 const cols = Math.max(20, e.props.bodyColumns)
431 const skyNote = s.look === 'B' && level === 'rich' && sky.state === 'failed' ? [Text({ dimColor: true, wrap: 'truncate-end', children: [`basic sky: the sky renderer failed (${sky.failure})`] })] : []
432 const frameRows = Math.max(3, Math.min(60, e.props.scroll.bodyRows - (level === 'rich' ? 1 : 0) - controlRows(controls, cols) - skyNote.length - extra.length))
433 const now = await $.clock.now()
434 const frame = frameOf(cols, frameRows, now)
435 s.motionMs = frame.motionMs ?? 0
436 await feedSky($, frame, now)
437 const bands = bandsOf(frame)
438 s.size = { cols, rows: frameRows }
439 s.shape = shapeOf(bands)
440 const stage = bands.map(b =>
441 Box({
442 key: 'band-' + b.y,
443 flexDirection: 'row',
444 height: b.rows,
445 children: b.pieces.map(p => {
446 if (p.kind === 'raster') return Raster({ key: p.key, columns: p.cols, rows: b.rows, cells: frame.grid.cells(p.x, b.y, p.cols, b.rows) })
447 const source = p.layer.stream !== undefined ? (sky.source ?? SKY_WAIT) : s.images.take(p.layer, now).source
448 const image = Image({ key: p.layer.key, columns: p.layer.cols, rows: p.layer.rows, source, alt: p.layer.alt })
449 if (p.layer.ground === undefined) return image
450 return Box({ key: p.layer.key + '-ground', width: p.layer.cols, height: p.layer.rows, backgroundColor: css(p.layer.ground), children: [image] })
451 }),
452 }),
453 )
454 const buttons = buttonsOf($, e, controls, key => press($, key))
455 if (levelSetting === 'auto' && imagesDrawn === undefined && probeRefusals < PROBE_TRIES) {
456 buttons.push(Image({ key: 'probe', columns: 1, rows: 1, source: PROBE_SOURCE, alt: ' ' }))
457 $.clock.after(50, () => {
458 void probe($)
459 })
460 }
461 const rows: RenderElement[] = [Box({ key: 'controls', flexDirection: 'row', flexWrap: 'wrap', columnGap: 2, children: buttons }), ...stage, ...skyNote, ...extra]
462 if (level === 'rich' && frame.links.length > 0) {
463 rows.push(Text({ dimColor: true, children: ['open: ', ...frame.links.flatMap((l, i) => [...(i > 0 ? [' '] : []), Link({ href: l.href, label: l.label })])] }))
464 }
465 return Box({ flexDirection: 'column', children: rows })
466}
467
468/** The controls as Buttons; the hidden ones last, in a Box drawn `display: none`, so only their hotkeys act. */
469export function buttonsOf($: EngineInterface, e: RenderInputOf<'Pane', 'terminal'>, controls: readonly Control[], onPress: (key: string) => Promise<void> | void): RenderElement[] {
470 const { Box, Text, Button } = $.ui.resolve(e)
471 const button = (c: Control) =>
472 Button({
473 key: c.key,
474 ...(c.hotkey === undefined ? {} : { hotkey: c.hotkey }),
475 ...(c.plain === true ? { plain: true as const } : {}),
476 ...(c.dim === true ? { dimColor: true } : {}),
477 onPress: async () => onPress(c.key),
478 children: [Text({ ...(c.color === undefined ? {} : { color: c.color }), children: [c.label] })],
479 })
480 const hidden = controls.filter(c => c.hidden === true)
481 return [...controls.filter(c => c.hidden !== true).map(button), ...(hidden.length > 0 ? [Box({ key: 'views', display: 'none', children: hidden.map(button) })] : [])]
482}
483
484/** The replay pane, or undefined while no replay runs. */
485export async function renderReplay($: EngineInterface, e: RenderInputOf<'Pane', 'terminal'>): Promise<RenderElement | undefined> {
486 const r = replay
487 if (r === undefined) return undefined
488 return renderStage($, e, r, levelOf(r.level), replayFrame(r), controlsOf(r.scene, r.filter, r.look, r.pausedAt !== undefined, r.isLiveWaiting), [])
489}
490
491/** The live pane in look A or B: the agents, the view buttons and `[ stop all ]` while a teammate is live, the stage, then the caller's rows. */
492export async function renderLive($: EngineInterface, e: RenderInputOf<'Pane', 'terminal'>, source: () => LiveSource, extra: RenderElement[], hasLive = false): Promise<RenderElement> {
493 live.source = source
494 const src = source()
495 const controls: Control[] = [...agentControls(src.scene, live.filter, live.look), ...viewControls(live.view, true), ...stopControls(hasLive)]
496 return renderStage($, e, live, levelOf(), liveFrame(src), controls, extra)
497}
498
499/** The pane closed: the replay stops, nothing animates or paints, and the sky renderer quits; the next open starts them again. */
500export async function paneClosed($: EngineInterface) {
501 stopReplay()
502 live.anim?.cancel()
503 live.anim = undefined
504 live.settle?.cancel()
505 live.settle = undefined
506 live.size = undefined
507 await quitSidecar($, sky)
508}
509
510/** What the live pane's `[ stop all ]` does: set by the mod at session start. */
511let stopAll: (() => Promise<void>) | undefined
512
513export function setStopAll(fn: () => Promise<void>) {
514 stopAll = fn
515}
516
517/** Shows a view: a look in the replay while one plays, else a look or the text list live. */
518export function showView($: EngineInterface, view: LiveView) {
519 if (replay !== undefined && view !== 'list') replay.look = view
520 else {
521 live.view = view
522 if (view !== 'list') live.look = view
523 }
524 if (view !== 'B') void pauseSidecar($, sky)
525 $.ui.invalidate('ui.render')
526}
527
528/** A control-row press: an agent toggles the filter; a view button switches the view; nudge, pause and stop act on the replay. */
529async function press($: EngineInterface, key: string) {
530 const r = replay
531 const s: Stage = r ?? live
532 if (key.startsWith('agent-')) {
533 const name = key.slice('agent-'.length)
534 s.filter = s.filter === name ? undefined : name
535 $.ui.invalidate('ui.render')
536 if (r === undefined && s.filter !== undefined) void $.ui.focus({ requestId: PANE, key: COMPOSE_KEY }).catch(() => undefined)
537 } else if (key.startsWith('view-')) showView($, key.slice('view-'.length) as LiveView)
538 else if (key === STOP_ALL_KEY && r === undefined) await stopAll?.()
539 else if (r === undefined) return
540 else if (key === 'live') {
541 stopReplay()
542 $.ui.invalidate('ui.render')
543 }
544 else if (key === 'nudge') {
545 const target = r.filter === undefined ? 'the claim holders' : r.scene.label(r.filter)
546 $.ui.toast(`replay: a nudge would go to ${target}; a replay sends nothing`)
547 } else if (key === 'pause') {
548 const now = await $.clock.now()
549 if (r.pausedAt === undefined) {
550 r.pausedAt = now
551 r.timer?.cancel()
552 r.timer = undefined
553 } else {
554 r.startReal += now - r.pausedAt
555 r.pausedAt = undefined
556 void step($)
557 }
558 $.ui.invalidate('ui.render')
559 } else if (key === 'stop') {
560 stopReplay()
561 $.ui.invalidate('ui.render')
562 }
563}
564hooks/sidecar.ts 218 lines1// The look B sky renderer process: hooks/sky.py paints the star map and writes each frame to a file the terminal reads
2// itself; the pane shows a frame by blitting its `{ file }` source, so no pixel crosses the engine and the mod draws no
3// picture of its own. The mod hands it the scene in DIR/scene.json. Any failure falls back for good.
4
5import type { EngineInterface, ImageSource } from 'claude-code'
6
7import type { SkyLine, SkyScene } from './looks'
8
9export type SidecarState = 'off' | 'starting' | 'running' | 'failed'
10
11/** Real ms before a frame the host held back (the sky Image not drawn now, the terminal busy) is offered again. */
12const RETRY_MS = 500
13
14/** The refusals that mean the terminal will never show a `{ file }` frame: no pictures at all, or no files read. */
15const CANNOT_SHOW = /draws no placeholder images|cannot read files on this machine/
16
17/** The commands that run the renderer, tried in turn until one starts with numpy: python3 from PATH, then uv with numpy. */
18const PYTHONS: readonly (readonly string[])[] = [['python3', '-I'], ['uv', 'run', '--no-project', '--with', 'numpy', 'python', '-I']]
19let pythons = PYTHONS
20
21/** The `skyPython` setting: a python path to run the renderer with instead of PYTHONS; empty, PYTHONS. */
22export function setSkyPython(path: string) {
23 pythons = path === '' ? PYTHONS : [[path, '-I']]
24}
25
26/** The renderer's state; the functions below act on it. */
27export type SkySidecar = {
28 requestId: string
29 key: string
30 state: SidecarState
31 /** Why it failed, once it did. */
32 failure: string | undefined
33 /** The latest frame as an Image source, once one came. */
34 source: ImageSource | undefined
35 /** The renderer's ms per frame, the last 100. */
36 renderMs: number[]
37 /** The newest frame not yet taken by the host. */
38 pending: ImageSource | undefined
39 retryTimer: { cancel: () => void } | undefined
40 /** How often it crashed this session, and the last crash: its exit and the end of its stderr. */
41 crashes: number
42 crash: string | undefined
43 /** Whether the running renderer said it ends on its own (`bye`), and the end of its stderr. */
44 isLeaving: boolean
45 stderr: string
46 dir: string
47 stream: AsyncGenerator<unknown, unknown> | undefined
48 /** The index in `pythons` of the command that runs the renderer, and why each one before it did not. */
49 python: number
50 tried: string[]
51 seq: number
52 sent: string
53}
54
55export function newSidecar(requestId: string, key: string): SkySidecar {
56 return { requestId, key, state: 'off', failure: undefined, source: undefined, renderMs: [], crashes: 0, crash: undefined, isLeaving: false, stderr: '', pending: undefined, retryTimer: undefined, dir: '', stream: undefined, python: 0, tried: [], seq: 0, sent: '' }
57}
58
59/** Starts the renderer in `dir` while it is asked for (`starting`) and not yet spawned; its frames are blitted as they come. */
60export function startSidecar($: EngineInterface, sc: SkySidecar, dir: string) {
61 if (sc.state !== 'starting' || sc.stream !== undefined) return
62 sc.dir = dir
63 sc.sent = ''
64 sc.isLeaving = false
65 sc.stderr = ''
66 const stream = $.process.spawn({ argv: [...pythons[sc.python]!, `${$.plugin.root}/hooks/sky.py`, dir] })
67 sc.stream = stream
68 void readSidecar($, sc, stream)
69}
70
71/**
72 * Reads the renderer's lines until it ends. An end it announced (`bye`: told to quit, idle) or one we caused leaves it off,
73 * to start again when wanted; any other end is a crash: the first leaves it off with the crash noted, a second fails it.
74 */
75async function readSidecar($: EngineInterface, sc: SkySidecar, stream: AsyncGenerator<{ stream: string; text: string }, unknown>) {
76 let buf = ''
77 let end: { code?: number | null; signal?: string | null } | undefined
78 try {
79 for (let r = await stream.next(); ; r = await stream.next()) {
80 if (r.done === true) {
81 end = r.value as typeof end
82 break
83 }
84 if (sc.stream !== stream) break
85 if (r.value.stream === 'stderr') {
86 sc.stderr = (sc.stderr + r.value.text).slice(-400)
87 continue
88 }
89 buf += r.value.text
90 let nl: number
91 while ((nl = buf.indexOf('\n')) >= 0) {
92 const line = buf.slice(0, nl).trim()
93 buf = buf.slice(nl + 1)
94 await sidecarLine($, sc, line)
95 }
96 }
97 } catch (err) {
98 if (sc.stream !== stream) return
99 if (sc.state === 'starting') nextPython($, sc, String(err))
100 else failSidecar($, sc, 'renderer did not start: ' + String(err))
101 return
102 }
103 if (sc.stream !== stream) return
104 sc.stream = undefined
105 sc.source = undefined
106 sc.sent = ''
107 if (sc.isLeaving) {
108 sc.state = 'off'
109 return
110 }
111 const last = sc.stderr.trim().split('\n').pop() ?? ''
112 const crash = `exit ${end?.code ?? end?.signal ?? '?'}${last === '' ? '' : ': ' + last}`
113 if (++sc.crashes > 1) failSidecar($, sc, 'renderer crashed: ' + crash)
114 else {
115 sc.crash = crash
116 sc.state = 'off'
117 $.ui.log('swarm sky renderer crashed, starts again when wanted: ' + crash)
118 }
119}
120
121async function sidecarLine($: EngineInterface, sc: SkySidecar, line: string) {
122 const [kind, ...rest] = line.split(' ')
123 if (kind === 'ready') sc.state = 'running'
124 else if (kind === 'bye') sc.isLeaving = true
125 else if (kind === 'fail' && rest.join(' ') === 'numpy missing') nextPython($, sc, 'numpy missing')
126 else if (kind === 'fail') failSidecar($, sc, rest.join(' '))
127 else if (kind === 'frame' && sc.state !== 'failed') {
128 const [file, gen, ms, w, h] = rest
129 sc.renderMs.push(Number(ms))
130 if (sc.renderMs.length > 100) sc.renderMs.shift()
131 sc.pending = { file: file!, format: 'rgb' as const, width: Number(w), height: Number(h), generation: Number(gen) }
132 await flushSidecar($, sc)
133 }
134}
135
136/**
137 * Blits the newest frame to the sky Image. A refusal that says the terminal cannot show it fails the renderer; any other
138 * (the Image not drawn now, the terminal busy) keeps the newest frame and offers it again in `RETRY_MS` and after each
139 * draw of the pane, for as long as it takes.
140 */
141async function flushSidecar($: EngineInterface, sc: SkySidecar) {
142 const source = sc.pending
143 if (source === undefined || sc.state === 'failed' || sc.state === 'off') return
144 const res = await $.ui.blit({ requestId: sc.requestId, key: sc.key, source }).catch((err: unknown) => ({ deny: String(err) }))
145 if (res.deny === undefined) {
146 if (sc.pending === source) sc.pending = undefined
147 sc.source = source
148 } else if (CANNOT_SHOW.test(res.deny)) failSidecar($, sc, 'frame refused: ' + res.deny)
149 else if (sc.retryTimer === undefined) {
150 sc.retryTimer = $.clock.after(RETRY_MS, () => {
151 sc.retryTimer = undefined
152 void flushSidecar($, sc)
153 })
154 }
155}
156
157/** Hands the renderer the scene when it changed, each lit edge and comet with its start in the mod's clock at `now`. */
158export async function updateSidecar($: EngineInterface, sc: SkySidecar, now: number, sky: SkyScene) {
159 if (sc.state === 'off' || sc.state === 'failed') return
160 const timed = ({ age, ...rest }: SkyLine) => ({ ...rest, start: Math.round(now - age) })
161 const scene = {
162 ...sky,
163 edges: sky.edges.map(({ age, ...e }) => (age === undefined ? e : { ...e, start: Math.round(now - age) })),
164 lit: sky.lit.map(timed),
165 comets: sky.comets.map(timed),
166 }
167 const sent = JSON.stringify(scene)
168 if (sent === sc.sent) return
169 sc.sent = sent
170 await $.fs.write(sc.dir + '/scene.json', JSON.stringify({ seq: ++sc.seq, now, ...scene }))
171}
172
173/** Ends the renderer cleanly, as when its pane closes: it reads `quit`, removes its files and exits; it starts again when wanted. */
174export async function quitSidecar($: EngineInterface, sc: SkySidecar) {
175 if (sc.state === 'off' || sc.state === 'failed') return
176 await endSidecar($, sc)
177 sc.state = 'off'
178}
179
180/** Pauses the renderer while look B rich is not drawn: it draws nothing until the next scene. */
181export async function pauseSidecar($: EngineInterface, sc: SkySidecar) {
182 if (sc.state === 'off' || sc.state === 'failed' || sc.sent === 'pause') return
183 sc.sent = 'pause'
184 sc.pending = undefined
185 await $.fs.write(sc.dir + '/scene.json', JSON.stringify({ seq: ++sc.seq, pause: true }))
186}
187
188/** Starts the renderer with the next command in `pythons`, the current one having failed for `why`; past the last, fails it. */
189function nextPython($: EngineInterface, sc: SkySidecar, why: string) {
190 sc.tried.push(`${pythons[sc.python]![0]}: ${why}`)
191 if (sc.python >= pythons.length - 1) return failSidecar($, sc, 'no python with numpy: ' + sc.tried.join('; '))
192 sc.python++
193 void sc.stream?.return(undefined)
194 sc.stream = undefined
195 startSidecar($, sc, sc.dir)
196}
197
198function failSidecar($: EngineInterface, sc: SkySidecar, why: string) {
199 if (sc.state === 'failed') return
200 sc.failure = why
201 void endSidecar($, sc)
202 sc.state = 'failed'
203 $.ui.log('swarm sky renderer: ' + why)
204 $.ui.invalidate('ui.render')
205}
206
207async function endSidecar($: EngineInterface, sc: SkySidecar) {
208 const stream = sc.stream
209 sc.stream = undefined
210 sc.source = undefined
211 sc.sent = ''
212 sc.pending = undefined
213 sc.retryTimer?.cancel()
214 sc.retryTimer = undefined
215 await $.fs.write(sc.dir + '/scene.json', JSON.stringify({ seq: ++sc.seq, quit: true })).catch(() => undefined)
216 void stream?.return(undefined)
217}
218hooks/pane-draw.ts 142 lines1// The pane's drawing without the mods API: the look per letter, the control rows, the frame cut into bands of Rasters and
2// Images, and each Image's source kept by its signature.
3
4import { lookA } from './look-a'
5import { lookB } from './look-b'
6import { agentColor, width } from './looks'
7import type { Frame, ImageLayer, LookFn } from './looks'
8import { FLIGHT } from './look-a'
9import { NEBULA } from './look-b'
10import type { Look, Scene } from './replay'
11import { css } from './grid'
12import type { ImageSource } from 'claude-code'
13
14export const LOOK_FNS: Record<Look, LookFn> = { A: lookA, B: lookB }
15const PALETTES = { A: FLIGHT, B: NEBULA }
16
17/** One button of the control row: an agent to filter by, or an action; a `hidden` one is only its hotkey. */
18export type Control = { key: string; label: string; color?: string; dim?: boolean; plain?: boolean; hotkey?: string; hidden?: boolean }
19
20/** One button per agent, in its colour, `⚠` after a code name another agent also took; pressed, it filters to that agent's threads. */
21export function agentControls(scene: Scene, filter: string | undefined, look: Look): Control[] {
22 const p = PALETTES[look]
23 return scene.order().map(a => ({
24 key: 'agent-' + a.name,
25 label: (a.code ?? a.name) + (scene.isDuplicateCode(a.name) ? ' ⚠' : ''),
26 color: css(agentColor(p, a)),
27 dim: filter !== undefined && filter !== a.name,
28 plain: true,
29 }))
30}
31
32/** The view controls: live, a `[ list ]` button (`l`), drawn bright while shown; looks A and B as hidden keys `1` and `2`. */
33export function viewControls(shown: Look | 'list', withList: boolean): Control[] {
34 return [
35 ...(withList ? [{ key: 'view-list', label: 'list', hotkey: 'l', dim: shown !== 'list' }] : []),
36 { key: 'view-A', label: 'A', hotkey: '1', hidden: true },
37 { key: 'view-B', label: 'B', hotkey: '2', hidden: true },
38 ]
39}
40
41/** The key of the live pane's `[ stop all ]` button. */
42export const STOP_ALL_KEY = 'stop-all'
43
44/** The live pane's `[ stop all ]` (`x`), while any teammate is live: it asks, then stops every live teammate. */
45export function stopControls(hasLive: boolean): Control[] {
46 return hasLive ? [{ key: STOP_ALL_KEY, label: 'stop all', hotkey: 'x' }] : []
47}
48
49/** The replay's control row: `[ live ]` while a live swarm waits, each agent, the views, then nudge, pause and stop. */
50export function controlsOf(scene: Scene, filter: string | undefined, look: Look, isPaused = false, liveWaiting = false): Control[] {
51 return [
52 ...(liveWaiting ? [{ key: 'live', label: 'live', hotkey: '0' }] : []),
53 ...agentControls(scene, filter, look),
54 ...viewControls(look, false),
55 { key: 'nudge', label: 'nudge', hotkey: 'n' },
56 { key: 'pause', label: isPaused ? 'play' : 'pause', hotkey: 'p' },
57 { key: 'stop', label: 'stop', hotkey: 's' },
58 ]
59}
60
61/** How many rows the control row takes at `cols` columns once it wraps: a plain button is its label, another `[ label ]`, two columns apart. */
62export function controlRows(controls: readonly Control[], cols: number): number {
63 let rows = 1
64 let x = 0
65 for (const c of controls) {
66 if (c.hidden === true) continue
67 const w = width(c.label) + (c.plain === true ? 0 : 4)
68 if (x > 0 && x + 2 + w > cols) {
69 rows++
70 x = w
71 } else x += (x > 0 ? 2 : 0) + w
72 }
73 return rows
74}
75
76/** A horizontal band of the stage: rows [y, y + rows), cut at its images' columns into raster and image pieces. */
77export type Band = { y: number; rows: number; pieces: ({ kind: 'raster'; key: string; x: number; cols: number } | { kind: 'image'; layer: ImageLayer })[] }
78
79/**
80 * The frame as bands top to bottom: rows no image covers form raster-only bands; images sharing rows form one band, the
81 * cells beside them rasters of their own. Images in one band must share their rows; one that does not is dropped.
82 */
83export function bandsOf(frame: Frame): Band[] {
84 const { grid, images } = frame
85 const groups = new Map<number, ImageLayer[]>()
86 for (const im of images) {
87 if (im.y < 0 || im.y + im.rows > grid.rows || im.x < 0 || im.x + im.cols > grid.cols) continue
88 const list = groups.get(im.y) ?? []
89 if (list.length > 0 && list[0]!.rows !== im.rows) continue
90 list.push(im)
91 groups.set(im.y, list)
92 }
93 const starts = [...groups.keys()].sort((a, b) => a - b)
94 const out: Band[] = []
95 let y = 0
96 for (const s of starts) {
97 if (s < y) continue
98 const layers = groups.get(s)!.sort((a, b) => a.x - b.x).filter((im, i, arr) => i === 0 || im.x >= arr[i - 1]!.x + arr[i - 1]!.cols)
99 if (s > y) out.push({ y, rows: s - y, pieces: [{ kind: 'raster', key: `r${y}`, x: 0, cols: grid.cols }] })
100 const rows = layers[0]!.rows
101 const pieces: Band['pieces'] = []
102 let x = 0
103 for (const im of layers) {
104 if (im.x > x) pieces.push({ kind: 'raster', key: `r${s}x${x}`, x, cols: im.x - x })
105 pieces.push({ kind: 'image', layer: im })
106 x = im.x + im.cols
107 }
108 if (x < grid.cols) pieces.push({ kind: 'raster', key: `r${s}x${x}`, x, cols: grid.cols - x })
109 out.push({ y: s, rows, pieces })
110 y = s + rows
111 }
112 if (y < grid.rows) out.push({ y, rows: grid.rows - y, pieces: [{ kind: 'raster', key: `r${y}`, x: 0, cols: grid.cols }] })
113 return out
114}
115
116/** A string that changes when the bands' shape does: same shape, the pane repaints by blit; another, it draws again. */
117export function shapeOf(bands: readonly Band[]): string {
118 return bands.map(b => `${b.y}+${b.rows}:` + b.pieces.map(p => (p.kind === 'raster' ? `${p.key}/${p.cols}` : `${p.layer.key}@${p.layer.x}/${p.layer.cols}`)).join(',')).join(';')
119}
120
121/** The least real time between two sources of one Image: a change sooner waits, and changes in between merge into it. */
122export const IMAGE_MIN_MS = 1_000
123
124/** The source each Image key shows, its sig and when it was made; a new one waits `IMAGE_MIN_MS` after the kept one. */
125export class ImageShelf {
126 private readonly held = new Map<string, { sig: string; source: ImageSource; at: number }>()
127
128 /** The source to show for the layer at real time `now`, and whether it is a new one to send. */
129 take(layer: ImageLayer, now: number): { source: ImageSource; isNew: boolean } {
130 const kept = this.held.get(layer.key)
131 if (kept !== undefined && (kept.sig === layer.sig || now - kept.at < IMAGE_MIN_MS)) return { source: kept.source, isNew: false }
132 const source = layer.draw().source()
133 this.held.set(layer.key, { sig: layer.sig, source, at: now })
134 return { source, isNew: true }
135 }
136
137 /** Drops a key's source, so the next `take` makes and sends it again. */
138 forget(key: string) {
139 this.held.delete(key)
140 }
141}
142hooks/replay.ts 632 lines1// Replay of a recorded run: the command's arguments, the runs a log holds, the playback schedule, and the Scene a pane look draws.
2
3import {
4 ClaimBoard,
5 DEFAULT_STALL_MIN,
6 IDLE_ENDED_H,
7 isModName,
8 bareName,
9 claimOfLine,
10 clauseOf,
11 helloName,
12 isHeldFromLead,
13 isIdleLine,
14 isToolLine,
15 isLeadAddress,
16 isLeadRecipient,
17 mentionsTarget,
18 renameName,
19 reviewOf,
20 shortModel,
21 sliceOf,
22 typeOf,
23 REPORTS,
24} from './core'
25import type { LogEntry, ReviewState } from './core'
26
27export type Look = 'A' | 'B'
28export type Level = 'basic' | 'rich'
29const LOOKS: readonly Look[] = ['A', 'B']
30const DEFAULT_SPEED = 30
31/** The longest real pause between two replayed events: a quiet stretch of the run plays in at most this long. */
32const MAX_GAP_MS = 1_500
33/** Two teams founded this close together are one spawn burst: a peer line between them makes them one. */
34export const BURST_MS = 15_000
35/** A team silent between its own members this long starts over when its names talk again. */
36const REUSE_GAP_MS = 30 * 60_000
37
38/** `level` absent: the pane picks rich where the terminal draws images, else basic. */
39export type ReplayArgs = { path: string; speed: number; look: Look; level?: Level; from?: number; to?: number }
40
41/** The arguments after `replay`: `stop`, or a log path and its flags; an error text for anything it cannot read. */
42export function parseReplayArgs(rest: string): { stop: true } | { args: ReplayArgs } | { error: string } {
43 const words = rest.trim().split(/\s+/).filter(Boolean)
44 if (words[0] === 'stop') return { stop: true }
45 const out: ReplayArgs = { path: '', speed: DEFAULT_SPEED, look: 'A' }
46 for (let i = 0; i < words.length; i++) {
47 const w = words[i]!
48 const value = words[i + 1]
49 if (w.startsWith('--') && value === undefined) return { error: `${w} needs a value` }
50 if (w === '--speed') {
51 const n = Number(value)
52 if (!Number.isFinite(n) || n <= 0) return { error: '--speed takes a number above 0' }
53 out.speed = n
54 i++
55 } else if (w === '--look') {
56 const l = value!.toUpperCase()
57 if (!(LOOKS as readonly string[]).includes(l)) return { error: '--look takes A or B' }
58 out.look = l as Look
59 i++
60 } else if (w === '--level') {
61 if (value !== 'basic' && value !== 'rich') return { error: '--level takes basic or rich' }
62 out.level = value
63 i++
64 } else if (w === '--from' || w === '--to') {
65 const t = Date.parse(value!)
66 if (!Number.isFinite(t)) return { error: `${w} takes an ISO time, e.g. 2026-10-12T19:47:00Z` }
67 out[w === '--from' ? 'from' : 'to'] = t
68 i++
69 } else if (w.startsWith('--')) return { error: 'unknown flag ' + w }
70 else if (out.path === '') out.path = w
71 else return { error: 'one log path only' }
72 }
73 if (out.path === '') return { error: 'usage: /swarm replay <log.jsonl> [--speed N] [--look A|B] [--level basic|rich] [--from <ISO>] [--to <ISO>] | replay stop' }
74 return { args: out }
75}
76
77/** Whether an address is a teammate's: not the lead, this plugin, or an unnamed peer. */
78export function isTeammateName(name: string): boolean {
79 return name !== '' && !isLeadAddress(name) && !isModName(name) && name !== 'peer' && name !== 'coordinator'
80}
81
82/**
83 * The code names a log's senders gave themselves (`[PROPOSE] hello <Name>` or a rename), read line by line; a line sent to
84 * a code name instead of a team name (`h15 → jaspis`) is read as sent to the teammate that took it, so no phantom agent
85 * goes by a code name. A name some line was sent from stays itself.
86 */
87export class CodeBook {
88 private readonly owners = new Map<string, string>()
89 private readonly senders = new Set<string>()
90
91 /** The line with its receiver resolved; learns the sender's code name from it. */
92 read(e: LogEntry): LogEntry {
93 const from = bareName(e.from)
94 if (from !== '' && !isIdleLine(e)) this.senders.add(from)
95 if (!isIdleLine(e) && !isToolLine(e) && e.via !== 'receive' && isTeammateName(from)) {
96 const code = helloName(e.summary) ?? renameName(e.summary)
97 if (code !== undefined && code.toLowerCase() !== from) this.owners.set(code.toLowerCase(), from)
98 }
99 const to = bareName(e.to)
100 const owner = this.owners.get(to)
101 return owner === undefined || this.senders.has(to) ? e : { ...e, to: owner }
102 }
103}
104
105/** A log's lines with code-name receivers resolved (see `CodeBook`), in time order. */
106export function resolveCodes(lines: readonly LogEntry[]): LogEntry[] {
107 const book = new CodeBook()
108 return [...lines].sort((a, b) => a.ts - b.ts).map(e => book.read(e))
109}
110
111export type Run = { from: number; to: number; count: number; names: string[] }
112
113/** How long before a run's first teammate line the replay starts: the lead's own lines before it are its brief, not the run. */
114export const LEAD_IN_MS = 30_000
115
116/** A team: the teammates that message each other, from its first peer message to its last. */
117export type Team = { names: string[]; firstAt: number; lastPeerAt: number }
118
119/**
120 * The teams a log holds, from teammate-to-teammate lines in time order. A peer line belongs to the team either end talked
121 * in within `REUSE_GAP_MS`; a line between two names with no such team founds a new one. The sender joins on that line
122 * unless it is still talking in another team; the receiver too, unless it is asleep: its last message, to anyone, came
123 * more than `IDLE_ENDED_H` hours before, or `canJoin` (the roster's view: stopped, or dormant) says no. An asleep receiver
124 * joins only by sending a peer line itself, and a line from a teamless sender to an asleep one founds no team. A line between
125 * two teams founded within `BURST_MS` of each other merges them. A team's names come in the order each first sent a peer
126 * line, as the looks place them. Agents that only write to the lead are in no team.
127 */
128export function teamsOf(lines: readonly LogEntry[], isMate: (name: string) => boolean = isTeammateName, canJoin: (name: string, at: number) => boolean = () => true): Team[] {
129 const out: Team[] = []
130 const seen = new Map<string, { team: Team; at: number }>()
131 const firstSent = new Map<Team, Map<string, number>>()
132 const lastSent = new Map<string, number>()
133 for (const e of [...lines].sort((a, b) => a.ts - b.ts)) {
134 if (isIdleLine(e) || isToolLine(e)) continue
135 const from = bareName(e.from)
136 const to = bareName(e.to)
137 const sentBefore = lastSent.get(to)
138 lastSent.set(from, e.ts)
139 if (from === to || !isTeammateName(from) || !isTeammateName(to) || !isMate(from) || !isMate(to)) continue
140 const isAwake = (sentBefore === undefined || e.ts - sentBefore <= IDLE_ENDED_H * 3_600_000) && canJoin(to, e.ts)
141 const teamOf = (n: string) => {
142 const last = seen.get(n)
143 return last !== undefined && e.ts - last.at <= REUSE_GAP_MS ? last.team : undefined
144 }
145 let team = teamOf(from) ?? teamOf(to)
146 const other = teamOf(to)
147 if (team !== undefined && other !== undefined && other !== team && Math.abs(other.firstAt - team.firstAt) <= BURST_MS) {
148 for (const n of other.names) if (!team.names.includes(n)) team.names.push(n)
149 team.firstAt = Math.min(team.firstAt, other.firstAt)
150 for (const [n, last] of seen) if (last.team === other) seen.set(n, { team, at: last.at })
151 out.splice(out.indexOf(other), 1)
152 const mine = firstSent.get(team) ?? new Map<string, number>()
153 for (const [n, at] of firstSent.get(other) ?? []) mine.set(n, Math.min(at, mine.get(n) ?? Infinity))
154 firstSent.set(team, mine)
155 }
156 if (team === undefined) {
157 if (!isAwake) continue
158 team = { names: [from, to], firstAt: e.ts, lastPeerAt: e.ts }
159 out.push(team)
160 } else {
161 team.lastPeerAt = e.ts
162 for (const n of isAwake ? [from, to] : [from]) if (!team.names.includes(n) && teamOf(n) === undefined) team.names.push(n)
163 }
164 for (const n of [from, to]) if (team.names.includes(n)) seen.set(n, { team, at: e.ts })
165 if (!firstSent.has(team)) firstSent.set(team, new Map())
166 if (!firstSent.get(team)!.has(from)) firstSent.get(team)!.set(from, e.ts)
167 }
168 for (const t of out) {
169 const sent = firstSent.get(t) ?? new Map<string, number>()
170 t.names.sort((a, b) => (sent.get(a) ?? Infinity) - (sent.get(b) ?? Infinity))
171 }
172 return out
173}
174
175/**
176 * The runs a log holds, one per team: from `LEAD_IN_MS` before its first peer message to the last line from or to one of
177 * its members before a later team that shares a name starts, or before the first gap of over `REUSE_GAP_MS` between them.
178 */
179export function splitRuns(lines: readonly LogEntry[]): Run[] {
180 const sorted = resolveCodes(lines)
181 const teams = teamsOf(sorted)
182 return teams.map((t, i) => {
183 const next = teams.slice(i + 1).find(n => n.names.some(x => t.names.includes(x)))
184 const end = next?.firstAt ?? Infinity
185 const from = t.firstAt - LEAD_IN_MS
186 let to = t.lastPeerAt
187 for (const e of sorted) {
188 if (e.ts < t.firstAt || e.ts >= end || !(t.names.includes(bareName(e.from)) || t.names.includes(bareName(e.to)))) continue
189 if (e.ts - to > REUSE_GAP_MS) break
190 to = Math.max(to, e.ts)
191 }
192 return { from, to, count: sorted.filter(e => e.ts >= from && e.ts <= to).length, names: t.names }
193 })
194}
195
196/** The lines inside a window, in time order. */
197export function windowOf(lines: readonly LogEntry[], from: number, to: number): LogEntry[] {
198 return lines.filter(e => e.ts >= from && e.ts <= to).sort((a, b) => a.ts - b.ts)
199}
200
201/** When each line plays, in real milliseconds from the start: the recorded gap over `speed`, at most `maxGapMs`. */
202export function schedule(lines: readonly LogEntry[], speed: number, maxGapMs = MAX_GAP_MS): number[] {
203 const out: number[] = []
204 let at = 0
205 for (let i = 0; i < lines.length; i++) {
206 if (i > 0) at += Math.min((lines[i]!.ts - lines[i - 1]!.ts) / speed, maxGapMs)
207 out.push(at)
208 }
209 return out
210}
211
212export type ModelFamily = 'opus' | 'sonnet' | 'haiku' | 'fable'
213
214/**
215 * The model family per teammate name from a roster.json, for a run starting at `at`: the latest entry of that name spawned
216 * by then (with a minute's grace), else its only entry; undefined when the roster does not say.
217 */
218export function modelsOf(rosterJson: unknown): (name: string, at: number) => ModelFamily | undefined {
219 const agents = (rosterJson as { agents?: unknown } | null)?.agents
220 const rows = Array.isArray(agents) ? (agents as { name?: unknown; model?: unknown; spawnedAt?: unknown }[]) : []
221 return (name, at) => {
222 const mine = rows.filter(r => typeof r.name === 'string' && bareName(r.name) === name && typeof r.model === 'string')
223 const before = mine.filter(r => typeof r.spawnedAt === 'number' && r.spawnedAt <= at + 60_000).sort((a, b) => (b.spawnedAt as number) - (a.spawnedAt as number))
224 const pick = before[0] ?? (mine.length === 1 ? mine[0] : undefined)
225 const family = pick === undefined ? undefined : shortModel(pick.model as string).split(' ')[0]
226 return family === 'opus' || family === 'sonnet' || family === 'haiku' || family === 'fable' ? family : undefined
227 }
228}
229
230export type LaneState = 'running' | 'idle' | 'waiting'
231export type AgentState = LaneState | 'stalled' | 'quiet' | 'ended'
232export type Segment = { state: LaneState; from: number; holdsClaim: boolean }
233
234export type SceneAgent = {
235 name: string
236 code?: string
237 model?: ModelFamily
238 /** Its place in first-seen order: the index of its colour. */
239 index: number
240 sent: number
241 received: number
242 /** When it sent each message. */
243 sends: number[]
244 /** When it made each tool call, as the ACT lines' running count gives them (one entry per call). */
245 callTimes: number[]
246 segments: Segment[]
247 /** The file it last edited, wrote or read, as the log's FILE line gives it: `✎ hooks/core.ts`. */
248 file?: string
249 /** Its last tool call in plain words, as the log's ACT line gives it: `Running npm test`. */
250 action?: string
251 /** How many tool calls it had made by its latest ACT line. */
252 calls?: number
253 /** When it joined: its JOIN line, else when it entered the scene. */
254 joinedAt: number
255 /** When it left, as its LEFT line gives it. */
256 leftAt?: number
257}
258
259export type MessageKind = 'send' | 'receive' | 'idle' | 'refused'
260
261export type SceneMessage = {
262 ts: number
263 from: string
264 to: string
265 type?: string
266 summary: string
267 kind: MessageKind
268 /** For a delivery to the lead: whether the lead filter holds it back. */
269 held?: boolean
270}
271
272export type CardStatus = 'unclaimed' | 'open' | 'building' | 'done' | 'approved' | 'blocked'
273export type Card = {
274 slice: string
275 builders: string[]
276 reviewers: { name: string; state?: ReviewState }[]
277 others: string[]
278 status: CardStatus
279 isDuplicate: boolean
280 /** The last claim, verdict or report on it. */
281 at: number
282 /** A path it names, for a link. */
283 path?: string
284}
285
286/** What a look draws at one moment of a replay: built line by line from the log, never from live state. */
287export class Scene {
288 readonly agents = new Map<string, SceneAgent>()
289 readonly messages: SceneMessage[] = []
290 readonly edges = new Map<string, number>()
291 readonly wakes: { ts: number; held: boolean }[] = []
292 readonly board = new ClaimBoard()
293 private readonly cardAt = new Map<string, number>()
294 private readonly paths = new Map<string, string>()
295 /** When each slice was last reported done, and last claimed. */
296 private readonly doneAt = new Map<string, number>()
297 private readonly claimedAt = new Map<string, number>()
298 /** The seeded team; once set, no other name becomes an agent and lines between non-members are left out. */
299 private members: Set<string> | undefined
300 startedAt: number | undefined
301 now = 0
302
303 constructor(
304 private readonly models: (name: string, at: number) => ModelFamily | undefined = () => undefined,
305 readonly stallMs = DEFAULT_STALL_MIN * 60_000,
306 ) {}
307
308 get delivered(): number {
309 return this.wakes.filter(w => !w.held).length
310 }
311
312 get held(): number {
313 return this.wakes.filter(w => w.held).length
314 }
315
316 /** The teammates in first-seen order. */
317 order(): SceneAgent[] {
318 return [...this.agents.values()].sort((a, b) => a.index - b.index)
319 }
320
321 /** Sets the run's teammates; when `upFront`, adds them at once in this order, so the layout holds still while they start, else each at its first line. */
322 seed(names: readonly string[], at: number, upFront = true) {
323 this.startedAt ??= at
324 this.members = new Set(names)
325 if (upFront) for (const n of names) this.agent(n, at, true)
326 }
327
328 /** The agent of a name; a teammate not yet seen is added when `create` (it sent a line), else undefined. */
329 private agent(name: string, ts: number, create: boolean): SceneAgent | undefined {
330 if (!isTeammateName(name) || (this.members !== undefined && !this.members.has(name))) return undefined
331 let a = this.agents.get(name)
332 if (a === undefined) {
333 if (!create) return undefined
334 a = { name, index: this.agents.size, sent: 0, received: 0, sends: [], callTimes: [], segments: [], joinedAt: ts }
335 const model = this.models(name, this.startedAt ?? ts)
336 if (model !== undefined) a.model = model
337 this.agents.set(name, a)
338 }
339 return a
340 }
341
342 private enter(a: SceneAgent, state: LaneState, ts: number) {
343 const last = a.segments[a.segments.length - 1]
344 if (last?.state === state) return
345 a.segments.push({ state, from: ts, holdsClaim: this.board.openClaims(a.name).length > 0 })
346 }
347
348 /** Counts a wake the mod itself gave the lead at `ts` (a wake mode or a watchdog), in time order; it reached the lead. */
349 noteWake(ts: number) {
350 const i = this.wakes.findIndex(w => w.ts > ts)
351 this.wakes.splice(i < 0 ? this.wakes.length : i, 0, { ts, held: false })
352 }
353
354 /** Whether a line repeats the previous one of the same sender and text within 3 s (a tool call and its send). */
355 private isRepeat(e: LogEntry, from: string, to: string): boolean {
356 for (let i = this.messages.length - 1; i >= 0; i--) {
357 const m = this.messages[i]!
358 if (e.ts - m.ts > 3_000) return false
359 if (m.kind === 'send' && m.from === from && m.to === to && m.summary === e.summary) return true
360 }
361 return false
362 }
363
364 /** Applies one log line. */
365 apply(e: LogEntry) {
366 this.startedAt ??= e.ts
367 this.now = Math.max(this.now, e.ts)
368 const from = bareName(e.from) || e.from
369 const to = bareName(e.to) || e.to
370 if (e.type === 'REFUSED') {
371 if (isLeadAddress(from) || this.agent(from, e.ts, true) !== undefined) this.messages.push({ ts: e.ts, from, to, type: 'REFUSED', summary: e.summary, kind: 'refused' })
372 return
373 }
374 if (this.members !== undefined && !this.members.has(from) && !this.members.has(to)) return
375 if (e.type === 'JOIN' || e.type === 'LEFT') {
376 const a = this.agent(from, e.ts, true)
377 if (a !== undefined && e.type === 'JOIN') {
378 a.joinedAt = e.ts
379 delete a.leftAt
380 } else if (a !== undefined) a.leftAt = e.ts
381 return
382 }
383 if (e.type === 'FILE') {
384 const a = this.agent(from, e.ts, true)
385 if (a !== undefined) {
386 a.file = e.summary
387 this.enter(a, 'running', e.ts)
388 }
389 return
390 }
391 if (e.type === 'ACT') {
392 const a = this.agent(from, e.ts, true)
393 if (a !== undefined) {
394 a.action = e.summary
395 const calls = e.calls ?? (a.calls ?? 0) + 1
396 for (let i = a.calls === undefined ? 1 : Math.max(1, calls - a.calls); i > 0; i--) a.callTimes.push(e.ts)
397 a.calls = calls
398 this.enter(a, 'running', e.ts)
399 }
400 return
401 }
402 if (isIdleLine(e)) {
403 const a = this.agent(from, e.ts, true)
404 if (a !== undefined) this.enter(a, 'idle', e.ts)
405 if (isLeadAddress(to)) this.wakes.push({ ts: e.ts, held: isHeldFromLead('', { idleReason: e.idleReason }) })
406 this.messages.push({ ts: e.ts, from, to, type: 'IDLE', summary: e.idleReason ?? 'idle', kind: 'idle' })
407 return
408 }
409 const isSend = e.via !== 'receive'
410 if (isSend && this.isRepeat(e, from, to)) return
411 const sender = this.agent(from, e.ts, isSend)
412 const receiver = this.agent(to, e.ts, this.members !== undefined)
413 const type = e.type ?? typeOf(e.summary)
414 const m: SceneMessage = { ts: e.ts, from, to, summary: e.summary, kind: isSend ? 'send' : 'receive' }
415 if (type !== undefined) m.type = type
416 if (isLeadRecipient(to) && sender !== undefined) {
417 m.held = isHeldFromLead(e.summary, undefined)
418 if (isSend || !this.messages.some(x => x.kind === 'send' && x.from === from && isLeadRecipient(x.to) && x.summary === e.summary)) this.wakes.push({ ts: e.ts, held: m.held })
419 }
420 this.messages.push(m)
421 if (sender !== undefined) {
422 const code = helloName(e.summary) ?? renameName(e.summary)
423 if (code !== undefined && isSend) sender.code = code
424 this.claims(sender.name, e, isSend)
425 }
426 if (isSend) {
427 if (sender !== undefined) {
428 sender.sent++
429 sender.sends.push(e.ts)
430 this.enter(sender, type === 'WAIT' ? 'waiting' : 'running', e.ts)
431 }
432 if (receiver !== undefined) receiver.received++
433 if ((sender !== undefined || isLeadAddress(from)) && (receiver !== undefined || isLeadRecipient(to))) {
434 const key = (isLeadAddress(from) ? 'team-lead' : from) + '>' + (isLeadAddress(to) ? 'team-lead' : to)
435 this.edges.set(key, (this.edges.get(key) ?? 0) + 1)
436 }
437 }
438 }
439
440 private claims(by: string, e: LogEntry, isSend: boolean) {
441 const ref = claimOfLine(e)
442 const touch = (target: string) => {
443 const slice = sliceOf(target, this.board.deliverables)
444 this.cardAt.set(slice, e.ts)
445 const path = /(?:^|\s)((?:\/|~\/|[\w.-]+\/)[\w./-]*\w|[\w-]+\.(?:md|ts|tsx|json|py|sql))\b/.exec(e.summary.replace(/^.*?\[CLAIM\]\s*\S+\s*/i, ''))?.[1]
446 if (path !== undefined && !this.paths.has(slice)) this.paths.set(slice, path)
447 }
448 if (ref !== undefined) {
449 const path = ref.role === 'build' ? /(?:^|\s)(\/\S+\/[^\s/]+\.\w+)/.exec(ref.target)?.[1] : undefined
450 if (path !== undefined) this.board.addDeliverables([path])
451 if (this.board.claim(by, ref, isSend) || isSend) {
452 touch(ref.target)
453 this.claimedAt.set(sliceOf(ref.target, this.board.deliverables), e.ts)
454 }
455 }
456 this.board.release(by, e.summary)
457 const verdict = reviewOf(e.summary)
458 if (verdict !== undefined && this.board.review(by, verdict)) this.cardAt.set(verdict.slice, e.ts)
459 const type = typeOf(e.summary)
460 if (type !== undefined && REPORTS.includes(type) && this.board.report(by, type, isSend, e.summary) && type === 'DONE') {
461 const mine = this.board.all().filter(c => c.by.includes(by) && (c.role === 'build' || c.role === 'research'))
462 const named = mine.filter(c => mentionsTarget(e.summary.replace(/^\s*\[DONE\]\s*/i, ''), c.target))
463 for (const c of named.length > 0 ? named : mine) {
464 const slice = sliceOf(c.target, this.board.deliverables)
465 this.doneAt.set(slice, e.ts)
466 this.cardAt.set(slice, e.ts)
467 }
468 }
469 }
470
471 /** An agent's state at `t`: `ended` once it left, else its segment then, `stalled` once idle past the stall time while it held a claim, `quiet` before its first line. */
472 stateAt(name: string, t = this.now): AgentState {
473 const a = this.agents.get(name)
474 if (a?.leftAt !== undefined && a.leftAt <= t) return 'ended'
475 const seg = a === undefined ? undefined : [...a.segments].reverse().find(s => s.from <= t)
476 if (seg === undefined) return 'quiet'
477 if (seg.state === 'idle' && seg.holdsClaim && t - seg.from >= this.stallMs) return 'stalled'
478 return seg.state
479 }
480
481 /** How long, in ms, an agent has been in its state at `t`. */
482 stateFor(name: string, t = this.now): number {
483 const a = this.agents.get(name)
484 if (a?.leftAt !== undefined && a.leftAt <= t) return t - a.leftAt
485 const seg = a === undefined ? undefined : [...a.segments].reverse().find(s => s.from <= t)
486 return seg === undefined ? 0 : t - seg.from
487 }
488
489 /** Whether another agent of the run took the same code name, in any case. */
490 isDuplicateCode(name: string): boolean {
491 const code = this.agents.get(name)?.code?.toLowerCase()
492 return code !== undefined && [...this.agents.values()].some(a => a.name !== name && a.code?.toLowerCase() === code)
493 }
494
495 /** An agent's code name, with its team name when another agent of the run took the same one; the name itself for anyone else. */
496 label(name: string): string {
497 const code = this.agents.get(name)?.code
498 if (code === undefined) return name
499 const clash = [...this.agents.values()].some(a => a.name !== name && a.code?.toLowerCase() === code.toLowerCase())
500 return clash ? `${code}·${name}` : code
501 }
502
503 /** The claims board: one card per slice, newest activity first. */
504 cards(): Card[] {
505 const slices = new Map<string, Card>()
506 const at = (slice: string): Card => {
507 let c = slices.get(slice)
508 if (c === undefined) {
509 c = { slice, builders: [], reviewers: [], others: [], status: 'open', isDuplicate: false, at: this.cardAt.get(slice) ?? 0 }
510 const path = this.paths.get(slice)
511 if (path !== undefined) c.path = path
512 slices.set(slice, c)
513 }
514 return c
515 }
516 const holding = new Map<Card, Set<string>>()
517 for (const cl of this.board.all()) {
518 const card = at(sliceOf(cl.target, this.board.deliverables))
519 const list = cl.role === 'build' ? card.builders : cl.role === 'review' ? undefined : card.others
520 for (const b of cl.by) {
521 if (list !== undefined && !list.includes(b)) list.push(b)
522 if (cl.role === 'build' || cl.role === 'research') {
523 const held = holding.get(card) ?? new Set<string>()
524 holding.set(card, held)
525 if (this.board.isActive(cl, b)) held.add(cl.role + ' ' + b)
526 }
527 if (cl.role === 'review' && !card.reviewers.some(r => r.name === b)) card.reviewers.push({ name: b })
528 }
529 }
530 for (const [slice, states] of this.board.reviews) {
531 const card = at(slice)
532 for (const [by, state] of states) {
533 const r = card.reviewers.find(x => x.name === by)
534 if (r !== undefined) r.state = state
535 else if (!card.builders.includes(by)) card.reviewers.push({ name: by, state })
536 }
537 }
538 for (const card of slices.values()) {
539 const held = [...(holding.get(card) ?? [])]
540 card.isDuplicate = held.filter(h => h.startsWith('build ')).length > 1 || held.filter(h => h.startsWith('research ')).length > 1
541 const states = card.reviewers.map(r => r.state)
542 if (states.includes('block')) card.status = 'blocked'
543 else if (states.includes('approve')) card.status = 'approved'
544 else if (this.doneAt.has(card.slice) && this.doneAt.get(card.slice)! >= (this.claimedAt.get(card.slice) ?? -Infinity)) card.status = 'done'
545 else if (card.builders.length > 0) card.status = 'building'
546 else if (card.reviewers.length === 0 && card.others.length === 0) card.status = 'unclaimed'
547 }
548 return [...slices.values()].sort((a, b) => b.at - a.at)
549 }
550}
551
552/** How many of this session's lines the live scene keeps. */
553const LIVE_LINES = 5_000
554
555/**
556 * The live pane's scene, from this session's lines: built again when its team changes, else fed the lines since. Teams
557 * are worked out from the messages alone, kept apart from the FILE lines so a flood of those never pushes a team out.
558 */
559export class LiveScene {
560 private readonly lines: LogEntry[] = []
561 private readonly talk: LogEntry[] = []
562 /** When the mod itself woke the lead. */
563 private readonly modWakes: number[] = []
564 private built: { key: string; scene: Scene; applied: number; woken: number } | undefined
565 private teams: { key: string; team: Team | undefined } | undefined
566 private readonly codes = new CodeBook()
567
568 /** Adds a line, its code-name receiver resolved (see `CodeBook`). */
569 push(line: LogEntry) {
570 const e = this.codes.read(line)
571 if (!isToolLine(e) && !isIdleLine(e)) {
572 this.talk.push(e)
573 if (this.talk.length > LIVE_LINES) this.talk.splice(0, this.talk.length - LIVE_LINES)
574 }
575 this.lines.push(e)
576 if (this.lines.length > LIVE_LINES) {
577 this.lines.splice(0, this.lines.length - LIVE_LINES)
578 this.built = undefined
579 }
580 }
581
582 /** Records that the mod woke the lead at `ts`; the scene counts it with the lead's other wakes. */
583 wake(ts: number) {
584 this.modWakes.push(ts)
585 if (this.modWakes.length > LIVE_LINES) {
586 this.modWakes.splice(0, this.modWakes.length - LIVE_LINES)
587 this.built = undefined
588 }
589 }
590
591 /** The current team: the latest whose members messaged each other (see `teamsOf`); worked out again when a line or `version` changed. */
592 team(isMate: (name: string) => boolean, version = '', canJoin?: (name: string, at: number) => boolean): Team | undefined {
593 const key = `${this.talk.length}:${this.talk.at(-1)?.ts}:${version}`
594 if (this.teams?.key !== key) this.teams = { key, team: teamsOf(this.talk, isMate, canJoin).at(-1) }
595 return this.teams.team
596 }
597
598 /** The scene of `names` from `from`, with the lines since applied. */
599 scene(names: readonly string[], from: number, models: (name: string, at: number) => ModelFamily | undefined, stallMs: number): Scene {
600 const key = `${names.join(',')}@${from}/${stallMs}`
601 if (this.built?.key !== key) {
602 const scene = new Scene(models, stallMs)
603 scene.seed(names, from)
604 this.built = { key, scene, applied: 0, woken: 0 }
605 }
606 const b = this.built
607 for (; b.applied < this.lines.length; b.applied++) {
608 const e = this.lines[b.applied]!
609 if (e.ts >= from) b.scene.apply(e)
610 }
611 for (; b.woken < this.modWakes.length; b.woken++) if (this.modWakes[b.woken]! >= from) b.scene.noteWake(this.modWakes[b.woken]!)
612 return b.scene
613 }
614}
615
616/** A short title for a run: its teammates as a range when they share a stem (`r1–r4`, `h01–h18` with the digits as named), else listed. */
617export function runTitle(names: readonly string[]): string {
618 const m = names.map(n => /^([a-z-]*?)(\d+)$/.exec(n))
619 const stem = m[0]?.[1]
620 if (names.length > 1 && m.every(x => x !== null && x[1] === stem)) {
621 const nums = m.map(x => x![2]!).sort((a, b) => Number(a) - Number(b))
622 return `${stem}${nums[0]}–${stem}${nums[nums.length - 1]}`
623 }
624 return names.join(' ')
625}
626
627/** The clause a card shows for its slice: the first clause, at most `max` characters. */
628export function cardTitle(slice: string, max: number): string {
629 const s = clauseOf(slice).replace(/^\/.*\//, '')
630 return s.length > max ? s.slice(0, Math.max(1, max - 1)) + '…' : s
631}
632hooks/grid.ts 158 lines1// A cell grid for the terminal's Raster: glyph, foreground and background per cell, with text, braille dots and half-block pixels.
2
3/** The terminal's own colour in a Raster cell. */
4const DEFAULT = 0x01000000
5
6/** `#rrggbb` as `0xRRGGBB`. */
7export function hex(s: string): number {
8 return parseInt(s.replace('#', ''), 16) & 0xffffff
9}
10
11/** The colour `t` of the way from `a` to `b`, per channel; `t` is clamped to 0..1. */
12export function mix(a: number, b: number, t: number): number {
13 const k = Math.max(0, Math.min(1, t))
14 const ch = (s: number) => Math.round(((a >> s) & 255) * (1 - k) + ((b >> s) & 255) * k)
15 return (ch(16) << 16) | (ch(8) << 8) | ch(0)
16}
17
18/** `0xRRGGBB` as `#rrggbb`. */
19export function css(c: number): string {
20 return '#' + (c & 0xffffff).toString(16).padStart(6, '0')
21}
22
23const BRAILLE_BIT = [
24 [0x01, 0x08],
25 [0x02, 0x10],
26 [0x04, 0x20],
27 [0x40, 0x80],
28]
29
30export class Grid {
31 readonly cols: number
32 readonly rows: number
33 readonly ch: Uint32Array
34 readonly fg: Uint32Array
35 readonly bg: Uint32Array
36 /** The braille dots set per cell (bits as U+2800 counts them); a cell with dots draws as braille. */
37 private readonly dots: Uint8Array
38
39 constructor(cols: number, rows: number, bg = DEFAULT) {
40 this.cols = Math.max(1, Math.floor(cols))
41 this.rows = Math.max(1, Math.floor(rows))
42 const n = this.cols * this.rows
43 this.ch = new Uint32Array(n).fill(32)
44 this.fg = new Uint32Array(n).fill(DEFAULT)
45 this.bg = new Uint32Array(n).fill(bg)
46 this.dots = new Uint8Array(n)
47 }
48
49 private at(x: number, y: number): number {
50 if (x < 0 || y < 0 || x >= this.cols || y >= this.rows) return -1
51 return y * this.cols + x
52 }
53
54 /** Sets one cell; an undefined colour keeps the cell's. */
55 put(x: number, y: number, ch: string | number, fg?: number, bg?: number) {
56 const i = this.at(Math.floor(x), Math.floor(y))
57 if (i < 0) return
58 const cp = typeof ch === 'number' ? ch : (ch.codePointAt(0) ?? 32)
59 this.ch[i] = cp > 0xffff || cp < 32 ? 0x3f : cp
60 this.dots[i] = 0
61 if (fg !== undefined) this.fg[i] = fg
62 if (bg !== undefined) this.bg[i] = bg
63 }
64
65 fill(x: number, y: number, w: number, h: number, ch: string, fg?: number, bg?: number) {
66 for (let r = y; r < y + h; r++) for (let c = x; c < x + w; c++) this.put(c, r, ch, fg, bg)
67 }
68
69 /** Paints the background of a rectangle, keeping glyphs. */
70 shade(x: number, y: number, w: number, h: number, bg: number) {
71 for (let r = y; r < y + h; r++) for (let c = x; c < x + w; c++) {
72 const i = this.at(c, r)
73 if (i >= 0) this.bg[i] = bg
74 }
75 }
76
77 /** Writes text from `x`, cut to `max` cells with `…`; returns the column after it. */
78 text(x: number, y: number, s: string, fg?: number, bg?: number, max = Infinity): number {
79 const chars = [...s].filter(c => (c.codePointAt(0) ?? 0) <= 0xffff)
80 const room = Math.min(max, this.cols - x)
81 if (room <= 0) return x
82 const shown = chars.length > room ? [...chars.slice(0, Math.max(0, room - 1)), '…'] : chars
83 shown.forEach((c, k) => this.put(x + k, y, c, fg, bg))
84 return x + shown.length
85 }
86
87 /** Writes text so that it ends at column `right` (exclusive). */
88 textRight(right: number, y: number, s: string, fg?: number, bg?: number): number {
89 const x = Math.max(0, right - [...s].length)
90 this.text(x, y, s, fg, bg, right - x)
91 return x
92 }
93
94 /** Sets one braille dot at sub-cell position (2 per column, 4 per row); its colour wins the cell's foreground. */
95 dot(dx: number, dy: number, fg: number) {
96 const x = Math.floor(dx)
97 const y = Math.floor(dy)
98 if (x < 0 || y < 0) return
99 const i = this.at(x >> 1, y >> 2)
100 if (i < 0) return
101 this.dots[i]! |= BRAILLE_BIT[y & 3]![x & 1]!
102 this.ch[i] = 0x2800 + this.dots[i]!
103 this.fg[i] = fg
104 }
105
106 /** A braille line between two dot positions. */
107 line(x0: number, y0: number, x1: number, y1: number, fg: number | ((t: number) => number), from = 0, to = 1) {
108 const n = Math.max(1, Math.ceil(Math.max(Math.abs(x1 - x0), Math.abs(y1 - y0))))
109 for (let k = Math.floor(n * from); k <= Math.ceil(n * to); k++) {
110 const t = k / n
111 if (t < from || t > to) continue
112 this.dot(x0 + (x1 - x0) * t, y0 + (y1 - y0) * t, typeof fg === 'number' ? fg : fg(t))
113 }
114 }
115
116 /** The glyphs of one row, trailing spaces kept. */
117 rowText(y: number): string {
118 let s = ''
119 for (let x = 0; x < this.cols; x++) s += String.fromCharCode(this.ch[y * this.cols + x]!)
120 return s
121 }
122
123 /** The cells of a rectangle as a Raster's `cells`: base64 of u32 triplets, little-endian. */
124 cells(x = 0, y = 0, w = this.cols, h = this.rows): string {
125 const words = new Uint32Array(w * h * 3)
126 let k = 0
127 for (let r = y; r < y + h; r++) for (let c = x; c < x + w; c++) {
128 const i = this.at(c, r)
129 words[k++] = i < 0 ? 32 : this.ch[i]!
130 words[k++] = i < 0 ? DEFAULT : this.fg[i]!
131 words[k++] = i < 0 ? DEFAULT : this.bg[i]!
132 }
133 return base64(new Uint8Array(words.buffer))
134 }
135}
136
137const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
138
139/** Standard padded base64 of bytes. */
140export function base64(bytes: Uint8Array): string {
141 const parts: string[] = []
142 const CHUNK = 3 * 4096
143 for (let start = 0; start < bytes.length; start += CHUNK) {
144 const end = Math.min(bytes.length, start + CHUNK)
145 const codes: number[] = []
146 for (let i = start; i < end; i += 3) {
147 const a = bytes[i]!
148 const b = i + 1 < end ? bytes[i + 1]! : 0
149 const c = i + 2 < end ? bytes[i + 2]! : 0
150 codes.push(B64.charCodeAt(a >> 2), B64.charCodeAt(((a & 3) << 4) | (b >> 4)))
151 codes.push(i + 1 < end ? B64.charCodeAt(((b & 15) << 2) | (c >> 6)) : 61)
152 codes.push(i + 2 < end ? B64.charCodeAt(c & 63) : 61)
153 }
154 parts.push(String.fromCharCode(...codes))
155 }
156 return parts.join('')
157}
158hooks/looks.ts 263 lines1// What every pane look shares: the view it draws, the frame it returns, palettes, badges and small drawing helpers.
2
3import { Grid, hex, mix } from './grid'
4
5import type { Canvas } from './pixels'
6import type { AgentState, Card, CardStatus, Level, ModelFamily, Scene, SceneAgent, SceneMessage } from './replay'
7
8/** An agent's state in the view: `ended` for every agent once the team has ended, else its state at the view's time. */
9export function stateIn(scene: Scene, name: string, v: View): AgentState {
10 return v.isEnded === true ? 'ended' : scene.stateAt(name, v.now)
11}
12
13/** How long a message travels sender → receiver on screen, in real ms. */
14export const PULSE_MS = 700
15/** How long a state change or a card change glows, in real ms. */
16export const FLASH_MS = 900
17
18export type View = {
19 cols: number
20 rows: number
21 level: Level
22 /** The run's time now: the replayed time, or the clock live. */
23 now: number
24 runFrom: number
25 /** The run's end; live, the time now. */
26 runTo: number
27 title: string
28 /** The replay speed; absent live. */
29 speed?: number
30 /** Live, once every teammate of the team has ended: `now` and `runTo` hold at its last activity. */
31 isEnded?: boolean
32 isPaused: boolean
33 /** Real ms since the event of run time `ts` reached the pane; Infinity for one it never played. */
34 age: (ts: number) => number
35 /** The agent whose threads the person picked; the rest draw dim. */
36 filter?: string
37 /** A short dim note for the header: `replay finished`, `live swarm running`. */
38 note?: string
39}
40
41type XY = [number, number]
42type RGB = [number, number, number]
43
44/** A message on the sky, in the picture's pixels: from `a` bent toward `q` to `b`, `stop` of the way; `age`, real ms since it was sent. */
45export type SkyLine = { a: XY; q: XY; b: XY; stop: number; rgb: RGB; age: number; held?: boolean; lead?: boolean }
46
47/**
48 * Everything the sky renderer paints, in the picture's pixels: the backdrop's colours, the membrane, edges with their
49 * weights, leader lines, the lead's rays and beads, the lit edges and comets, the agents; `u` and `nu` scale strokes and
50 * marks.
51 */
52export type SkyScene = {
53 w: number
54 h: number
55 u: number
56 nu: number
57 centre: XY
58 membrane: number
59 ground: RGB
60 haze: RGB
61 star: RGB
62 membraneRgb: RGB
63 accent: RGB
64 dim: RGB
65 rule: RGB
66 stalled: RGB
67 /** `age`, while the first message between the two is still on its way: the edge grows behind it. */
68 edges: { a: XY; q: XY; b: XY; w: number; rgb: RGB; lit: number; age?: number }[]
69 leaders: { pts: XY[]; rgb: RGB; lit: number }[]
70 rays: number
71 /** The lead's delivered wakes once the rays are capped, drawn as a number in the ring; 0 below the cap. */
72 count: number
73 beads: number
74 lit: SkyLine[]
75 comets: SkyLine[]
76 nodes: { x: number; y: number; rgb: RGB; state: string; lit: number }[]
77 litMs: number
78 flightMs: number
79 landMs: number
80}
81
82/**
83 * A picture over a box of cells: `sig` names everything it draws from, so a pane sends it again only when `sig` changes,
84 * at most once per `IMAGE_MIN_MS`. `draw` makes the pixels, sent raw within `IMAGE_BUDGET`.
85 */
86export type ImageLayer = {
87 key: string
88 x: number
89 y: number
90 cols: number
91 rows: number
92 sig: string
93 draw: () => Canvas
94 /** The colour of the cells under the picture, where a terminal that fits it inside its box leaves them bare. */
95 ground?: number
96 /** Set where a renderer process may paint this picture instead: the scene it paints. */
97 stream?: SkyScene
98 alt: string
99}
100
101/**
102 * A drawn frame; `fadeMs`, the real ms its images still change by themselves (a lit edge fading), and `motionMs`, the
103 * real ms its cells still move by themselves (a comet flying), when they do.
104 */
105export type Frame = { grid: Grid; images: ImageLayer[]; links: { label: string; href: string }[]; fadeMs?: number; motionMs?: number }
106export type LookFn = (scene: Scene, view: View) => Frame
107
108export type Palette = {
109 name: string
110 bg: number
111 panel: number
112 rule: number
113 text: number
114 dim: number
115 accent: number
116 agents: readonly number[]
117 state: Record<AgentState, number>
118 status: Record<CardStatus, number>
119 model: Record<ModelFamily, number>
120}
121
122export function palette(p: {
123 name: string
124 bg: string
125 panel: string
126 rule: string
127 text: string
128 dim: string
129 accent: string
130 agents: readonly string[]
131 state: Record<AgentState, string>
132 status: Record<CardStatus, string>
133 model: Record<ModelFamily, string>
134}): Palette {
135 const map = <K extends string>(r: Record<K, string>) => Object.fromEntries(Object.entries(r).map(([k, v]) => [k, hex(v as string)])) as Record<K, number>
136 return { ...p, bg: hex(p.bg), panel: hex(p.panel), rule: hex(p.rule), text: hex(p.text), dim: hex(p.dim), accent: hex(p.accent), agents: p.agents.map(hex), state: map(p.state), status: map(p.status), model: map(p.model) }
137}
138
139export const MODEL_GLYPH: Record<ModelFamily, string> = { opus: '◆', sonnet: '●', haiku: '▲', fable: '✦' }
140export const STATUS_WORD: Record<CardStatus, string> = { unclaimed: 'UNCLAIMED', open: 'OPEN', building: 'BUILDING', done: 'DONE', approved: 'APPROVED', blocked: 'BLOCKED' }
141
142export function agentColor(p: Palette, a: SceneAgent | undefined): number {
143 return a === undefined ? p.text : p.agents[a.index % p.agents.length]!
144}
145
146/** A colour for an address: the agent's, the accent for the lead, the dim text for anything else. */
147export function nameColor(p: Palette, scene: Scene, name: string): number {
148 const a = scene.agents.get(name)
149 if (a !== undefined) return agentColor(p, a)
150 return name === 'team-lead' || name === 'main' || name === 'lead' ? p.text : p.dim
151}
152
153/** Whether a message is one of the filtered agent's threads; every message is without a filter. */
154export function touches(filter: string | undefined, from: string, to: string): boolean {
155 return filter === undefined || from === filter || to === filter
156}
157
158/** `mm:ss` (or `h:mm:ss`) of a duration. */
159export function clock(ms: number): string {
160 const s = Math.max(0, Math.floor(ms / 1000))
161 const h = Math.floor(s / 3600)
162 const m = Math.floor((s % 3600) / 60)
163 const ss = String(s % 60).padStart(2, '0')
164 return h > 0 ? `${h}:${String(m).padStart(2, '0')}:${ss}` : `${m}:${ss}`
165}
166
167/** The most base64 characters an Image source may carry (about 75 KB of RGBA pixels), so a redraw never stalls the console. */
168export const IMAGE_BUDGET = 100_000
169
170/** The least real time between two sky sources. */
171export const SKY_MIN_MS = 2_000
172/** Pixels per terminal cell, across and down: the types give a mod no cell size, so the common one. */
173export const CELL_PX = { w: 10, h: 20 }
174
175/** Pixels per cell column for an image of `cols` × `rows` cells (a cell twice as tall as wide) inside the budget, at most `max`. */
176export function pixelScale(cols: number, rows: number, max = 8): number {
177 const pixels = Math.floor((IMAGE_BUDGET * 3) / 4 / 4)
178 return Math.min(max, Math.floor(Math.sqrt(pixels / Math.max(1, cols * rows * 2)) * 100) / 100)
179}
180
181const STEPS = [1, 2, 5, 10, 15, 30, 60, 120, 300, 600, 900, 1800, 3600, 7200].map(s => s * 1000)
182
183/** A round slot length so `slots` of them cover `span` ms: the slots hold still while a live run grows. */
184export function slotMs(span: number, slots: number): number {
185 const want = span / Math.max(1, slots)
186 return STEPS.find(s => s >= want) ?? Math.ceil(want / 3_600_000) * 3_600_000
187}
188
189/** The messages the look tells as events: sends and the mod's own, newest last. */
190export function sends(scene: Scene): SceneMessage[] {
191 return scene.messages.filter(m => m.kind === 'send')
192}
193
194/** Spells a word with a space between letters, for titles. */
195export function spaced(s: string): string {
196 return [...s].join(' ')
197}
198
199/** A brightness bump for an event `age` real ms old: full at once, gone after `ms`. */
200export function fade(age: number, ms = FLASH_MS): number {
201 return age < 0 || age >= ms ? 0 : (1 - age / ms) ** 2
202}
203
204/** A left agent's light once its fade-out ends. */
205const LEFT_LIT = 0.35
206/** How long, in real ms, the header names an agent that joined or left. */
207export const MOVE_NOTE_MS = 10_000
208
209/** An agent's light, 0 → 1: rising over `FLASH_MS` after it joined; once it left, falling over `FLASH_MS` to `LEFT_LIT`. */
210export function presence(a: SceneAgent, v: View): number {
211 if (a.leftAt !== undefined && a.leftAt <= v.now) return LEFT_LIT + (1 - LEFT_LIT) * fade(v.age(a.leftAt))
212 return 1 - fade(v.age(a.joinedAt))
213}
214
215/** The header's note on the agents that joined or left in the last `MOVE_NOTE_MS`: `+ joined Kite · − left w2`. */
216export function movesNote(scene: Scene, v: View): string | undefined {
217 const isRecent = (t: number | undefined) => t !== undefined && t <= v.now && v.age(t) >= 0 && v.age(t) < MOVE_NOTE_MS
218 const hasLeft = (a: SceneAgent) => a.leftAt !== undefined && a.leftAt <= v.now
219 const joined = scene.order().filter(a => isRecent(a.joinedAt) && !hasLeft(a)).map(a => scene.label(a.name))
220 const left = scene.order().filter(a => isRecent(a.leftAt)).map(a => scene.label(a.name))
221 const parts = [...(joined.length > 0 ? [`+ joined ${joined.join(', ')}`] : []), ...(left.length > 0 ? [`− left ${left.join(', ')}`] : [])]
222 return parts.length > 0 ? parts.join(' · ') : undefined
223}
224
225/** The messages in flight now, each with how far it has travelled (0 → 1). */
226export function inFlight(scene: Scene, view: View): { m: SceneMessage; t: number }[] {
227 const out: { m: SceneMessage; t: number }[] = []
228 for (let i = scene.messages.length - 1; i >= 0; i--) {
229 const m = scene.messages[i]!
230 const age = view.age(m.ts)
231 if (age >= PULSE_MS) break
232 if (m.kind === 'send' && age >= 0) out.push({ m, t: age / PULSE_MS })
233 }
234 return out.reverse()
235}
236
237/** The display width of a string in cells, counting each BMP code point as one. */
238export function width(s: string): number {
239 return [...s].length
240}
241
242/** Counts per slot of `slot` ms from `from`, `slots` of them. */
243export function histogram(times: readonly number[], from: number, slot: number, slots: number): number[] {
244 const out = new Array<number>(Math.max(1, slots)).fill(0)
245 for (const t of times) {
246 const i = Math.floor((t - from) / slot)
247 if (i >= 0 && i < out.length) out[i]!++
248 }
249 return out
250}
251
252/** The absolute paths the claim cards name, as `file://` links, newest first. */
253export function cardLinks(cards: readonly Card[], max = 4): { label: string; href: string }[] {
254 const out: { label: string; href: string }[] = []
255 for (const c of cards) {
256 if (c.path === undefined || !c.path.startsWith('/') || out.some(l => l.href === 'file://' + c.path)) continue
257 out.push({ label: c.path.split('/').pop() ?? c.path, href: 'file://' + c.path })
258 }
259 return out.slice(0, max)
260}
261
262export { Grid, mix }
263hooks/look-a.ts 425 lines1// Look A, "mission control": agent cards with a state-coloured activity bar on one time axis, the claims board, lead wakes and the message list.
2
3import { ago, clauseOf, timeOfDay } from './core'
4import { Canvas } from './pixels'
5import { cardTitle } from './replay'
6import type { AgentState, Card, Scene, SceneAgent } from './replay'
7import {
8 FLASH_MS,
9 Grid,
10 PULSE_MS,
11 STATUS_WORD,
12 agentColor,
13 clock,
14 fade,
15 cardLinks,
16 histogram,
17 inFlight,
18 mix,
19 movesNote,
20 nameColor,
21 palette,
22 pixelScale,
23 slotMs,
24 spaced,
25 stateIn,
26 touches,
27 width,
28} from './looks'
29import type { Frame, ImageLayer, View } from './looks'
30
31export const FLIGHT = palette({
32 name: 'Flight',
33 bg: '#0A0E14',
34 panel: '#121A24',
35 rule: '#1E2A38',
36 text: '#CAD5E2',
37 dim: '#5E6E80',
38 accent: '#FFB547',
39 agents: ['#4FD6FF', '#FF7AB6', '#3DDC97', '#B18CFF', '#F4E04D', '#FF8F5A', '#7AA2FF', '#9BE564'],
40 state: { running: '#3DDC97', idle: '#5E6E80', waiting: '#4FD6FF', stalled: '#FF5C6C', quiet: '#2A3646', ended: '#5E6E80' },
41 status: { unclaimed: '#5E6E80', open: '#7AA2FF', building: '#FFB547', done: '#4FD6FF', approved: '#3DDC97', blocked: '#FF5C6C' },
42 model: { opus: '#D9A6FF', sonnet: '#7FC8FF', haiku: '#9BE5A0', fable: '#FFD27A' },
43})
44
45const TYPE_COLOR: Record<string, string> = {
46 PROPOSE: '#7AA2FF',
47 CLAIM: '#FFB547',
48 REVIEW: '#B18CFF',
49 DONE: '#3DDC97',
50 BLOCK: '#FF5C6C',
51 REFUSED: '#FF5C6C',
52 HANDOFF: '#4FD6FF',
53 ASK: '#FF7AB6',
54 WAIT: '#4FD6FF',
55 LOCK: '#FFB547',
56}
57
58const P = FLIGHT
59
60function typeColor(type: string | undefined): number {
61 const c = type === undefined ? undefined : TYPE_COLOR[type]
62 return c === undefined ? P.text : parseInt(c.slice(1), 16)
63}
64
65/** The header bar: title, the note and who joined or left, run, replay clock and speed. */
66function header(g: Grid, scene: Scene, v: View, narrow: boolean) {
67 g.fill(0, 0, g.cols, 1, ' ', P.text, P.panel)
68 const speed = v.isEnded === true ? '■ ended' : v.speed === undefined ? '● live' : (v.isPaused ? '❚❚ ' : '▶ ') + v.speed + '×'
69 let r = g.textRight(g.cols - 1, 0, speed, P.accent)
70 r = g.textRight(r - 2, 0, timeOfDay(v.now), P.text)
71 if (!narrow) r = g.textRight(r - 2, 0, 'T+' + clock(v.now - v.runFrom) + ' / ' + clock(v.runTo - v.runFrom), P.dim)
72 let x = g.text(1, 0, '◉', P.accent)
73 x = g.text(x + 1, 0, narrow ? 'SWARM' : spaced('SWARM'), P.text)
74 const title = v.isEnded === true ? `ENDED · ${v.title} · ran ${ago(v.runTo - v.runFrom)}` : (v.speed === undefined ? 'LIVE · ' : 'REPLAY · ') + v.title
75 x = g.text(x + 2, 0, narrow ? v.title : title, P.dim, undefined, r - x - 4)
76 const note = [v.note, movesNote(scene, v)].filter(n => n !== undefined).join(' · ')
77 if (note !== '') g.text(x + 2, 0, note, P.dim, undefined, r - x - 4)
78}
79
80/** The shared time axis of the agent bars: `slots` slots of `slot` ms from the run's start, and the busiest slot's count. */
81type Axis = { from: number; slot: number; slots: number; peak: number }
82
83function axisOf(scene: Scene, v: View, slots: number): Axis {
84 const slot = slotMs(Math.max(1, v.runTo - v.runFrom), slots)
85 const peak = Math.max(1, ...scene.order().flatMap(a => histogram([...a.sends, ...a.callTimes], v.runFrom, slot, slots)))
86 return { from: v.runFrom, slot, slots, peak }
87}
88
89/** One slot of an agent's bar: its tool calls and sends then (`count` is both) and its state at the slot's end (or now); undefined after now. */
90type Slot = { count: number; sends: number; calls: number; state: AgentState } | undefined
91
92function slotsOf(scene: Scene, a: SceneAgent, v: View, ax: Axis): Slot[] {
93 const sends = histogram(a.sends, ax.from, ax.slot, ax.slots)
94 const calls = histogram(a.callTimes, ax.from, ax.slot, ax.slots)
95 return sends.map((n, i) => {
96 const start = ax.from + i * ax.slot
97 if (start > v.now) return undefined
98 return { count: n + calls[i]!, sends: n, calls: calls[i]!, state: scene.stateAt(a.name, Math.min(v.now, start + ax.slot - 1)) }
99 })
100}
101
102/** A slot's colour, lifted toward white when it holds a message and tool calls were counted: the message shows as a brighter tick. */
103function brightIf(s: NonNullable<Slot>, color: number): number {
104 return s.sends > 0 && s.calls > 0 ? mix(color, 0xffffff, 0.5) : color
105}
106
107/** What a bar shows, as a string: each slot's state, count and message mark, the axis peak, and whether the agent is dimmed. */
108function barSig(slots: readonly Slot[], ax: Axis, isDim: boolean): string {
109 return slots.map(s => (s === undefined ? '-' : s.state[0]! + s.count + (s.sends > 0 && s.calls > 0 ? '+' : ''))).join(',') + '/' + ax.peak + (isDim ? 'd' : '')
110}
111
112/** The file line of a card: the mark and the path's end, cut from the left to `w` cells. */
113function fileText(file: string, w: number): string {
114 const chars = [...file]
115 if (chars.length <= w) return file
116 return chars[0] + ' …' + chars.slice(chars.length - Math.max(1, w - 3)).join('')
117}
118
119/**
120 * One agent card: full name (`⚠ dup` when another agent took its code name in any case), tool calls, message counts and model; state, time in it and its last action (dim unless
121 * running), else its file; its bar on the shared axis.
122 */
123function agentCard(g: Grid, scene: Scene, v: View, a: SceneAgent, x0: number, y: number, w0: number, ax: Axis, images: ImageLayer[]) {
124 const slide = Math.round(fade(v.age(a.joinedAt), FLASH_MS) * w0)
125 const x = x0 + slide
126 const w = w0 - slide
127 const color = agentColor(P, a)
128 const isDim = (v.filter !== undefined && v.filter !== a.name) || (a.leftAt !== undefined && a.leftAt <= v.now)
129 const state = stateIn(scene, a.name, v)
130 const seg = a.segments[a.segments.length - 1]
131 const flash = seg === undefined ? 0 : fade(v.age(seg.from), FLASH_MS)
132 const pulse = inFlight(scene, v).find(p => p.m.from === a.name || p.m.to === a.name)
133 const ink = (c: number) => (isDim ? mix(c, P.bg, 0.65) : c)
134 const panel = mix(P.panel, color, 0.06 + 0.22 * flash)
135 g.shade(x, y, w, 3, panel)
136 const barGlow = pulse === undefined ? 0 : pulse.m.from === a.name ? 1 - pulse.t : pulse.t
137 for (let r = 0; r < 3; r++) g.put(x, y + r, '▌', ink(mix(color, 0xffffff, 0.5 * barGlow)), panel)
138 let right = x + w - 1
139 if (a.model !== undefined) {
140 const chip = ' ' + a.model + ' '
141 right = g.textRight(right, y, chip, ink(P.bg), ink(P.model[a.model])) - 1
142 }
143 right = g.textRight(right, y, `↑${a.sent} ↓${a.received}`, ink(P.dim)) - 1
144 if (a.calls !== undefined) right = g.textRight(right - 1, y, `${a.calls}×`, ink(P.dim)) - 1
145 let cx = g.text(x + 2, y, a.code ?? a.name, ink(color), undefined, right - x - 2)
146 if (a.code !== undefined && a.code !== a.name) cx = g.text(cx + 1, y, a.name, ink(P.dim), undefined, right - cx - 1)
147 if (scene.isDuplicateCode(a.name)) g.text(cx + 1, y, '⚠ dup', ink(P.status.blocked), undefined, right - cx - 1)
148 let sx = g.text(x + 2, y + 1, '●', ink(mix(P.state[state], 0xffffff, 0.6 * flash)))
149 sx = g.text(sx + 1, y + 1, state.toUpperCase(), ink(P.state[state]))
150 sx = g.text(sx + 1, y + 1, clock(scene.stateFor(a.name, v.now)), ink(P.dim))
151 if (a.action !== undefined) g.text(sx + 2, y + 1, a.action, ink(state === 'running' ? P.text : P.dim), undefined, x + w - sx - 3)
152 else if (a.file !== undefined) g.text(sx + 2, y + 1, fileText(a.file, x + w - sx - 3), ink(P.text))
153 const slots = slotsOf(scene, a, v, ax)
154 if (v.level === 'rich' && slide === 0) {
155 const sig = barSig(slots, ax, isDim)
156 const still = mix(P.panel, color, 0.06)
157 images.push({ key: 'bar-' + a.name, x: x + 2, y: y + 2, cols: ax.slots, rows: 1, sig: sig + '/' + still, draw: () => richBar(slots, ax, ink, still), alt: ' ' })
158 return
159 }
160 slots.forEach((s, i) => {
161 const cx = x + 2 + i
162 if (cx >= x + w) return
163 if (s === undefined) g.put(cx, y + 2, '·', mix(P.panel, P.dim, 0.35))
164 else if (s.state === 'quiet') return
165 else {
166 const n = s.count === 0 ? 1 : Math.max(2, Math.round((s.count / ax.peak) * 8))
167 g.put(cx, y + 2, String.fromCharCode(0x2580 + n), ink(brightIf(s, P.state[s.state])))
168 }
169 })
170}
171
172const LINE_BAR = 16
173
174/** The bar of an agent line at rich: `LINE_BAR` cells at the line's end, fewer on a narrow line, none under 6. */
175function lineBarWidth(v: View, w: number): number {
176 const cells = Math.min(LINE_BAR, w - 26)
177 return v.level === 'rich' && cells >= 6 ? cells : 0
178}
179
180/**
181 * One agent on one line: its colour bar, state dot, name (`⚠` on a duplicate code name), state and time in it, then its last action
182 * (cut first, left out under 8 cells); at rich its bar on the lines' shared axis `ax` at the line's end.
183 */
184function agentLine(g: Grid, scene: Scene, v: View, a: SceneAgent, x: number, y: number, w: number, ax: Axis | undefined, images: ImageLayer[]) {
185 const color = agentColor(P, a)
186 const isDim = (v.filter !== undefined && v.filter !== a.name) || (a.leftAt !== undefined && a.leftAt <= v.now)
187 const ink = (c: number) => (isDim ? mix(c, P.bg, 0.65) : c)
188 const state = stateIn(scene, a.name, v)
189 const end = x + w - (ax === undefined ? 0 : ax.slots + 1)
190 g.put(x, y, '▌', ink(color))
191 let cx = g.text(x + 1, y, '●', ink(P.state[state]))
192 cx = g.text(cx + 1, y, (a.code ?? a.name) + (scene.isDuplicateCode(a.name) ? ' ⚠' : ''), ink(color), undefined, end - cx - 1)
193 if (a.code !== undefined && a.code !== a.name) cx = g.text(cx + 1, y, a.name, ink(P.dim), undefined, end - cx - 1)
194 cx = g.text(cx + 1, y, state.toUpperCase(), ink(P.state[state]), undefined, end - cx - 1)
195 cx = g.text(cx + 1, y, clock(scene.stateFor(a.name, v.now)), ink(P.dim), undefined, end - cx - 1)
196 if (a.action !== undefined && end - cx - 2 >= 8) g.text(cx + 2, y, a.action, ink(state === 'running' ? P.text : P.dim), undefined, end - cx - 2)
197 if (ax === undefined) return
198 const slots = slotsOf(scene, a, v, ax)
199 const sig = barSig(slots, ax, isDim)
200 images.push({ key: 'bar-' + a.name, x: x + w - ax.slots, y, cols: ax.slots, rows: 1, sig: sig + '/' + P.bg, draw: () => richBar(slots, ax, ink, P.bg), alt: ' ' })
201}
202
203/**
204 * The agents in `rows` rows from `y`: a 3-row card each (a blank row between when there is room), else one line each, else
205 * one line each in two columns, the last cell `+N more` when even those do not fit; the lines' bars share one short axis.
206 * Returns the row after the list.
207 */
208function agentList(g: Grid, scene: Scene, v: View, agents: readonly SceneAgent[], x: number, y: number, w: number, rows: number, ax: Axis, images: ImageLayer[]): number {
209 if (3 * agents.length <= rows) {
210 const gap = 4 * agents.length <= rows ? 1 : 0
211 for (const a of agents) {
212 agentCard(g, scene, v, a, x, y, w, ax, images)
213 y += 3 + gap
214 }
215 return y
216 }
217 const cols = agents.length <= rows ? 1 : 2
218 const cw = Math.floor((w - (cols - 1)) / cols)
219 const slots = rows * cols
220 const shown = agents.length <= slots ? agents : agents.slice(0, slots - 1)
221 const perCol = Math.ceil(Math.min(agents.length, slots) / cols)
222 const barW = lineBarWidth(v, cw)
223 const lax = barW === 0 ? undefined : axisOf(scene, v, barW)
224 shown.forEach((a, i) => agentLine(g, scene, v, a, x + Math.floor(i / perCol) * (cw + 1), y + (i % perCol), cw, lax, images))
225 if (shown.length < agents.length) g.text(x + (cols - 1) * (cw + 1) + 1, y + perCol - 1, `+${agents.length - shown.length} more`, P.dim)
226 return y + perCol + 1
227}
228
229/** An agent's bar as pixels: one rounded column per slot, its height the tool calls and sends, its colour the state; a thin line while quiet. */
230function richBar(slots: readonly Slot[], ax: Axis, ink: (c: number) => number, bg: number): Canvas {
231 const k = pixelScale(ax.slots, 1, 4)
232 const h = 2 * k
233 const c = new Canvas(ax.slots * k, h, bg)
234 slots.forEach((s, i) => {
235 if (s === undefined || s.state === 'quiet') return
236 const color = ink(brightIf(s, P.state[s.state]))
237 const top = s.count === 0 ? h - 1.2 : h - 1 - Math.max(2, (s.count / ax.peak) * (h - 2))
238 c.rect(i * k + 0.5, top, Math.max(1, k - 1), h - top, color, 0.9)
239 })
240 return c
241}
242
243/** The lead's wakes: delivered vs held back, then a strip of the latest ones in order. */
244function leadBlock(g: Grid, scene: Scene, v: View, x: number, y: number, w: number, images: ImageLayer[]) {
245 g.shade(x, y, w, 2, P.panel)
246 g.put(x, y, '▌', P.text, P.panel)
247 g.put(x, y + 1, '▌', P.text, P.panel)
248 let cx = g.text(x + 2, y, 'LEAD', P.text)
249 cx = g.text(cx + 2, y, '▲ ' + scene.delivered + ' woken', P.accent)
250 g.text(cx + 2, y, '▽ ' + scene.held + ' held back', P.dim)
251 const sw = w - 3
252 const last = scene.wakes.slice(-sw)
253 if (v.level === 'rich') {
254 const sig = last.map(wk => (wk.held ? 'h' : 'd')).join('')
255 images.push({ key: 'wakes', x: x + 2, y: y + 1, cols: sw, rows: 1, sig, draw: () => richWakes(last, sw), alt: `lead wakes ${scene.delivered} delivered, ${scene.held} held` })
256 return
257 }
258 last.forEach((wk, i) => {
259 const glow = fade(v.age(wk.ts))
260 g.put(x + 2 + i, y + 1, wk.held ? '·' : '▮', wk.held ? mix(P.dim, 0xffffff, glow) : mix(P.accent, 0xffffff, glow))
261 })
262}
263
264/** The wake strip as pixels: one per cell, delivered wakes as tall amber ticks, held ones as low dim dots. */
265function richWakes(last: readonly { held: boolean }[], cols: number): Canvas {
266 const k = pixelScale(cols, 1, 4)
267 const h = 2 * k
268 const c = new Canvas(cols * k, h, P.panel)
269 last.forEach((wk, i) => {
270 const x = i * k + k / 2
271 if (wk.held) c.disc(x, h - k / 2, Math.max(0.6, k / 6), P.dim)
272 else c.line(x, k / 3, x, h - k / 3, Math.max(0.5, k / 8), P.accent)
273 })
274 return c
275}
276
277/** One claim card: a rounded box in its status colour, the builders, the reviewers and their verdicts. */
278function claimCard(g: Grid, scene: Scene, v: View, card: Card, x: number, y: number, w: number) {
279 const sc = P.status[card.status]
280 const glow = fade(v.age(card.at), FLASH_MS * 1.5)
281 const isDim = v.filter !== undefined && ![...card.builders, ...card.reviewers.map(r => r.name), ...card.others].includes(v.filter)
282 const ink = (c: number) => (isDim ? mix(c, P.bg, 0.65) : c)
283 const edge = ink(mix(mix(sc, P.bg, 0.35), 0xffffff, 0.5 * glow))
284 g.shade(x, y, w, 4, mix(P.bg, sc, 0.05 + 0.15 * glow))
285 g.put(x, y, '╭', edge)
286 g.put(x + w - 1, y, '╮', edge)
287 g.put(x, y + 3, '╰', edge)
288 g.put(x + w - 1, y + 3, '╯', edge)
289 for (let i = 1; i < w - 1; i++) {
290 g.put(x + i, y, '─', edge)
291 g.put(x + i, y + 3, '─', edge)
292 }
293 for (let r = 1; r < 3; r++) {
294 g.put(x, y + r, '│', edge)
295 g.put(x + w - 1, y + r, '│', edge)
296 }
297 const word = STATUS_WORD[card.status]
298 g.text(x + 2, y, ' ' + cardTitle(card.slice, w - width(word) - 8) + ' ', ink(P.text))
299 g.textRight(x + w - 2, y, ' ' + word + ' ', ink(sc))
300 let cx = x + 2
301 if (card.builders.length > 0) {
302 cx = g.text(cx, y + 1, 'build', ink(P.dim))
303 for (const b of card.builders) cx = g.text(cx + 1, y + 1, scene.label(b), ink(nameColor(P, scene, b)), undefined, x + w - 2 - cx - 1)
304 } else if (card.others.length > 0) {
305 cx = g.text(cx, y + 1, 'research', ink(P.dim))
306 for (const b of card.others) cx = g.text(cx + 1, y + 1, scene.label(b), ink(nameColor(P, scene, b)), undefined, x + w - 2 - cx - 1)
307 } else g.text(cx, y + 1, 'no builder', ink(P.dim))
308 if (card.isDuplicate) g.text(cx + 1, y + 1, '⚠ duplicate', ink(P.status.blocked), undefined, x + w - 2 - cx - 1)
309 cx = x + 2
310 if (card.reviewers.length > 0) {
311 cx = g.text(cx, y + 2, 'review', ink(P.dim))
312 for (const r of card.reviewers) {
313 const mark = r.state === 'approve' ? '✓' : r.state === 'block' ? '✗' : '◦'
314 cx = g.text(cx + 1, y + 2, mark, ink(r.state === 'approve' ? P.status.approved : r.state === 'block' ? P.status.blocked : P.dim), undefined, x + w - 2 - cx - 1)
315 cx = g.text(cx, y + 2, scene.label(r.name), ink(nameColor(P, scene, r.name)), undefined, x + w - 2 - cx)
316 }
317 }
318}
319
320/** One claim on one line, for a board too long for its boxes: a mark in its status colour, the slice (its file name for a path), its claimants (cut first), `⚠` on a double claim, its status. */
321function claimLine(g: Grid, scene: Scene, v: View, card: Card, x: number, y: number, w: number) {
322 const sc = P.status[card.status]
323 const isDim = v.filter !== undefined && ![...card.builders, ...card.reviewers.map(r => r.name), ...card.others].includes(v.filter)
324 const ink = (c: number) => (isDim ? mix(c, P.bg, 0.65) : c)
325 const word = STATUS_WORD[card.status]
326 let right = g.textRight(x + w - 1, y, word, ink(sc)) - 1
327 if (card.isDuplicate) right = g.textRight(right, y, '⚠', ink(P.status.blocked)) - 1
328 let cx = g.text(x, y, '■', ink(sc))
329 cx = g.text(cx + 1, y, cardTitle(clauseOf(card.slice).replace(/^.*\//, ''), Math.max(4, Math.floor((right - cx) * 0.6))), ink(P.text), undefined, right - cx - 1)
330 for (const n of [...card.builders, ...card.others]) cx = g.text(cx + 1, y, scene.label(n), ink(nameColor(P, scene, n)), undefined, right - cx - 1)
331}
332
333/** The message list: newest first, the one in flight lit, names in full; refused spawns among them. */
334function ticker(g: Grid, scene: Scene, v: View, x: number, y: number, w: number, rows: number) {
335 g.text(x, y, spaced('MESSAGES'), P.dim)
336 const all = scene.messages.filter(m => (m.kind === 'send' || m.kind === 'refused') && touches(v.filter, m.from, m.to))
337 g.textRight(x + w, y, `${all.filter(m => m.kind === 'send').length} msgs${v.filter ? ' · ' + scene.label(v.filter) : ''}`, P.dim)
338 const shown = all.slice(-(rows - 1)).reverse()
339 const nameW = Math.max(4, ...shown.flatMap(m => [width(scene.label(m.from)), width(scene.label(m.to))]))
340 shown.forEach((m, i) => {
341 const r = y + 1 + i
342 const t = v.age(m.ts) / PULSE_MS
343 const lit = t >= 0 && t < 1 ? 1 - t : 0
344 if (lit > 0) g.shade(x - 1, r, w + 2, 1, mix(P.bg, mix(P.panel, P.accent, 0.25), lit))
345 let cx = x
346 if (w >= 60) cx = g.text(cx, r, timeOfDay(m.ts), mix(P.dim, P.text, lit)) + 2
347 cx = g.text(cx, r, scene.label(m.from).padEnd(nameW), nameColor(P, scene, m.from))
348 cx = g.text(cx + 1, r, '→', lit > 0 ? P.accent : P.dim)
349 cx = g.text(cx + 2, r, scene.label(m.to).padEnd(nameW), nameColor(P, scene, m.to))
350 const type = m.type ?? ''
351 cx = g.text(cx + 1, r, type.padEnd(8).slice(0, 8), typeColor(m.type))
352 g.text(cx, r, m.summary.replace(/^\s*\[[A-Z]+\]\s*/, ''), mix(P.dim, P.text, 0.55 + 0.45 * lit), undefined, x + w - cx)
353 })
354}
355
356/** The first of `needs` (rows, in the order the forms are tried) that fits in `max` rows, else `max`. */
357function firstFit(needs: readonly number[], max: number): number {
358 return needs.find(n => n <= max) ?? max
359}
360
361/** Look A at the view's size. */
362export function lookA(scene: Scene, v: View): Frame {
363 const g = new Grid(v.cols, v.rows, P.bg)
364 const images: ImageLayer[] = []
365 const narrow = v.cols < 72
366 header(g, scene, v, narrow)
367 const agents = scene.order()
368 const cards = v.isEnded === true ? [] : scene.cards()
369 if (narrow) {
370 const w = g.cols - 2
371 const ax = axisOf(scene, v, w - 3)
372 let y = agentList(g, scene, v, agents, 1, 2, w, Math.max(1, g.rows - 9), ax, images)
373 leadBlock(g, scene, v, 1, y, w, images)
374 y += 3
375 const fit = Math.max(0, Math.min(3, g.rows - 4 - y))
376 const shown = cards.length <= fit ? cards : cards.slice(0, Math.max(0, fit - 1))
377 for (const c of shown) {
378 g.text(1, y, '■', P.status[c.status])
379 const cx = g.text(3, y, cardTitle(c.slice, Math.floor(w / 2)), P.text)
380 g.text(cx + 1, y, c.builders.map(b => scene.label(b)).join(' ') || STATUS_WORD[c.status].toLowerCase(), P.dim, undefined, w - cx)
381 y++
382 }
383 if (shown.length < cards.length && fit > 0) g.text(1, y++, `+${cards.length - shown.length} more`, P.dim)
384 ticker(g, scene, v, 1, y + 1, w, g.rows - y - 1)
385 return { grid: g, images, links: cardLinks(cards) }
386 }
387 const leftW = Math.max(34, Math.min(46, Math.floor(v.cols * 0.42)))
388 const rightX = leftW + 3
389 const rightW = v.cols - rightX - 1
390 g.text(1, 2, spaced('AGENTS'), P.dim)
391 const word = v.isEnded === true ? 'ended' : 'running'
392 g.textRight(leftW + 1, 2, `${agents.length} · ${agents.filter(a => stateIn(scene, a.name, v) === word).length} ${word}`, P.dim)
393 g.text(rightX, 2, spaced('CLAIMS'), P.dim)
394 const cardCols = rightW >= 54 ? 2 : 1
395 const cardW = Math.floor((rightW - (cardCols - 1)) / cardCols)
396 const maxBottom = v.rows - 3 - 1
397 const agentRows = firstFit([3 * agents.length, agents.length, Math.ceil(agents.length / 2)], maxBottom - 6)
398 const claimLines = Math.min(Math.ceil(cards.length / cardCols), maxBottom - 3)
399 const tickerRows = Math.max(3, Math.min(Math.max(5, Math.min(12, Math.floor(v.rows * 0.3))), v.rows - 1 - Math.max(agentRows + 6, claimLines + 3)))
400 const bodyMax = v.rows - tickerRows - 1
401 const ax = axisOf(scene, v, leftW - 3)
402 const y = agentList(g, scene, v, agents, 1, 3, leftW, Math.max(1, bodyMax - 3 - 3), ax, images)
403 leadBlock(g, scene, v, 1, Math.min(y, bodyMax - 2), leftW, images)
404 const claimRows = bodyMax - 3
405 let claimEnd = 4
406 if (Math.ceil(cards.length / cardCols) * 4 <= claimRows) {
407 cards.forEach((c, i) => claimCard(g, scene, v, c, rightX + (i % cardCols) * (cardW + 1), 3 + Math.floor(i / cardCols) * 4, cardW))
408 claimEnd = 3 + Math.ceil(cards.length / cardCols) * 4
409 } else {
410 const slots = claimRows * cardCols
411 const shown = cards.length <= slots ? cards : cards.slice(0, slots - 1)
412 const perCol = Math.ceil(Math.min(cards.length, slots) / cardCols)
413 shown.forEach((c, i) => claimLine(g, scene, v, c, rightX + Math.floor(i / perCol) * (cardW + 1), 3 + (i % perCol), cardW))
414 if (shown.length < cards.length) g.text(rightX + (cardCols - 1) * (cardW + 1), 3 + perCol - 1, `+${cards.length - shown.length} more`, P.dim)
415 claimEnd = 3 + perCol
416 }
417 if (cards.length === 0) g.text(rightX, 3, v.isEnded === true ? 'claims cleared: the team ended' : 'no claims yet', P.dim)
418 // The rule sits right under the taller column; the message list takes the rows left.
419 const bodyBottom = Math.min(bodyMax, Math.max(y + 2, claimEnd))
420 for (let x = 1; x < v.cols - 1; x++) g.put(x, bodyBottom, '─', P.rule)
421 ticker(g, scene, v, 1, bodyBottom + 1, v.cols - 2, v.rows - bodyBottom - 1)
422 return { grid: g, images, links: cardLinks(cards) }
423}
424
425hooks/look-b.ts 675 lines1// Look B, "constellation": the team as a star map around the lead, messages as comets along its edges.
2
3import { ago, timeOfDay } from './core'
4
5import { Canvas } from './pixels'
6import { cardTitle } from './replay'
7import type { AgentState, Scene, SceneAgent, SceneMessage } from './replay'
8import {
9 FLASH_MS,
10 Grid,
11 MODEL_GLYPH,
12 agentColor,
13 cardLinks,
14 fade,
15 mix,
16 movesNote,
17 nameColor,
18 palette,
19 presence,
20 SKY_MIN_MS,
21 CELL_PX,
22 sends,
23 spaced,
24 stateIn,
25 touches,
26 width,
27} from './looks'
28import type { Frame, ImageLayer, SkyScene, View } from './looks'
29
30export const NEBULA = palette({
31 name: 'Nebula',
32 bg: '#07060E',
33 panel: '#0E0C1F',
34 rule: '#2A2547',
35 text: '#EDE9FF',
36 dim: '#6E6890',
37 accent: '#FFE6A8',
38 agents: ['#FF6FA3', '#FFC65C', '#5FE3E0', '#9D8CFF', '#7CF5A0', '#FF9D5C', '#5CA8FF', '#F2F07A'],
39 state: { running: '#EDE9FF', idle: '#6E6890', waiting: '#5FE3E0', stalled: '#FF4F6D', quiet: '#2A2547', ended: '#6E6890' },
40 status: { unclaimed: '#6E6890', open: '#9D8CFF', building: '#FFC65C', done: '#5FE3E0', approved: '#7CF5A0', blocked: '#FF4F6D' },
41 model: { opus: '#C9B8FF', sonnet: '#8FD3FF', haiku: '#A8F0C0', fable: '#FFE6A8' },
42})
43
44const P = NEBULA
45const LEAD = 'team-lead'
46const MEMBRANE = 0x5a51a0
47const STATE_GLYPH: Record<AgentState, string> = { running: '◉', idle: '○', waiting: '◌', stalled: '⊗', quiet: '·', ended: '○' }
48
49type Node = { name: string; x: number; y: number; side: 'left' | 'right'; labelRow: number }
50
51/**
52 * Where each agent sits: evenly round an ellipse about the centre, turned a little off the axes so no two line up; in cell
53 * units. An agent left of the centre has its label in the left margin, the rest in the right.
54 */
55function layout(agents: readonly SceneAgent[], cx: number, cy: number, rx: number, ry: number): Node[] {
56 const n = agents.length
57 const start = -Math.PI / 2 - Math.PI / Math.max(1, n) + 0.3
58 return agents.map((a, k) => {
59 const ang = start + (k * 2 * Math.PI) / Math.max(1, n)
60 const x = cx + Math.cos(ang) * rx
61 return { name: a.name, x, y: cy + Math.sin(ang) * ry, side: x < cx ? 'left' : 'right', labelRow: 0 }
62 })
63}
64
65/** Spreads the label rows of one side so no two sit closer than `gap`, keeping them in order and inside [top, bottom]. */
66function spreadLabels(nodes: Node[], top: number, bottom: number, gap: number) {
67 for (const side of ['left', 'right'] as const) {
68 const list = nodes.filter(n => n.side === side).sort((a, b) => a.y - b.y)
69 let next = top
70 for (const n of list) {
71 n.labelRow = Math.max(next, Math.round(n.y))
72 next = n.labelRow + gap
73 }
74 let last = bottom
75 for (const n of [...list].reverse()) {
76 n.labelRow = Math.min(n.labelRow, last)
77 last = n.labelRow - gap
78 }
79 }
80}
81
82/** A smooth in-out easing of 0 → 1. */
83function ease(t: number): number {
84 return t < 0.5 ? 2 * t * t : 1 - (-2 * t + 2) ** 2 / 2
85}
86
87/** A deterministic pseudo-random 0..1 for a position: the star field never flickers between frames. */
88function hash(x: number, y: number): number {
89 let h = (x * 374761393 + y * 668265263) ^ 0x5bd1e995
90 h = Math.imul(h ^ (h >>> 13), 1274126177)
91 return ((h ^ (h >>> 16)) >>> 0) / 4294967296
92}
93
94type Geometry = { gx: number; gy: number; gw: number; gh: number; cx: number; cy: number; membrane: number; nodes: Node[] }
95
96function geometry(scene: Scene, v: View, wide: boolean): Geometry {
97 const margin = wide ? Math.min(18, Math.floor(v.cols * 0.2)) : 0
98 const legend = wide ? 0 : Math.ceil(scene.agents.size / 2)
99 const gx = margin
100 const gy = 1
101 const gw = v.cols - 2 * margin
102 const gh = Math.max(6, v.rows - 5 - legend)
103 const cx = Math.floor(gx + gw / 2) + 0.5
104 const cy = Math.floor(gy + gh / 2) + 0.5
105 const rx = Math.max(4, gw / 2 - 4)
106 const ry = Math.max(2, gh / 2 - 1.2)
107 const nodes = layout(scene.order(), cx, cy, rx, ry).map(n => ({ ...n, x: Math.floor(n.x) + 0.5, y: Math.floor(n.y) + 0.5 }))
108 spreadLabels(nodes, gy, gy + gh - 2, 2)
109 return { gx, gy, gw, gh, cx, cy, membrane: Math.max(2.5, Math.min(rx, ry * 2) * 0.24), nodes }
110}
111
112function pos(geo: Geometry, name: string): { x: number; y: number } | undefined {
113 if (name === LEAD || name === 'main' || name === 'lead') return { x: geo.cx, y: geo.cy }
114 return geo.nodes.find(n => n.name === name)
115}
116
117/** The weight of each edge, both directions together, as 0..1 of the busiest. */
118function edgeWeights(scene: Scene): Map<string, { a: string; b: string; w: number }> {
119 const out = new Map<string, { a: string; b: string; w: number }>()
120 for (const [key, n] of scene.edges) {
121 const [a, b] = key.split('>') as [string, string]
122 const k = a < b ? a + '|' + b : b + '|' + a
123 const e = out.get(k) ?? { a, b, w: 0 }
124 e.w += n
125 out.set(k, e)
126 }
127 const peak = Math.max(1, ...[...out.values()].map(e => e.w))
128 for (const e of out.values()) e.w /= peak
129 return out
130}
131
132/** Where a message travels: sender to receiver, stopping at the membrane (`stop` < 1) for one the lead filter holds back. */
133function pathOf(geo: Geometry, from: string, to: string, held: boolean | undefined) {
134 const a = pos(geo, from)
135 const b = pos(geo, to)
136 if (a === undefined || b === undefined) return undefined
137 if (held !== true) return { a, b, stop: 1 }
138 const len = Math.hypot((b.x - a.x) * 2, (b.y - a.y) * 4)
139 return { a, b, stop: Math.max(0.1, 1 - (geo.membrane * 2) / Math.max(1, len)) }
140}
141
142/** Colour channels are rounded to this step before a basic-sky cell is written, so a frame stays under the Raster's 1024 colour pairs. */
143const QUANT = 8
144/** The most labelled flights at once on the basic sky. */
145export const WORDS_MAX = 6
146/** How long a held comet's splash on the membrane and a delivered comet's flare at its receiver last, in real ms. */
147const SPLASH_MS = 400
148const FLARE_MS = 300
149/** The pixels of a comet's trail on the basic sky: a few cells, one pixel thick. */
150const TRAIL = 6
151
152function quant(c: number): number {
153 const q = (s: number) => Math.min(255, Math.round(((c >> s) & 255) / QUANT) * QUANT)
154 return (q(16) << 16) | (q(8) << 8) | q(0)
155}
156
157function luma(c: number): number {
158 return 0.3 * ((c >> 16) & 255) + 0.59 * ((c >> 8) & 255) + 0.11 * (c & 255)
159}
160
161/** A point of the quadratic curve a → b bent toward `c` by `bend`. */
162function curveAt(a: { x: number; y: number }, b: { x: number; y: number }, c: { x: number; y: number }, t: number, bend = 0.18): { x: number; y: number } {
163 const mx = (a.x + b.x) / 2
164 const my = (a.y + b.y) / 2
165 const qx = mx + (c.x - mx) * bend
166 const qy = my + (c.y - my) * bend
167 return { x: (1 - t) * (1 - t) * a.x + 2 * (1 - t) * t * qx + t * t * b.x, y: (1 - t) * (1 - t) * a.y + 2 * (1 - t) * t * qy + t * t * b.y }
168}
169
170/** The fraction of a flight (0 → 1) at which its eased head reaches `stop`. */
171function arrivalT(stop: number): number {
172 let lo = 0
173 let hi = 1
174 for (let i = 0; i < 24; i++) {
175 const mid = (lo + hi) / 2
176 if (ease(mid) < stop) lo = mid
177 else hi = mid
178 }
179 return hi
180}
181
182/** The word a message flies as: its type, else the bracketed tag of its summary, else `msg`. */
183function wordOf(m: SceneMessage): string {
184 return (m.type ?? /^\s*\[([A-Z]+)\]/.exec(m.summary)?.[1] ?? 'msg').toLowerCase()
185}
186
187/**
188 * Look B's basic sky: the sky as a bitmap of half cells, `▀` with a 24-bit colour above and below, glow from
189 * the colour of an area; braille only for curved edges and the membrane. Each message flies as a comet with its type
190 * riding quietly behind the head, a burst (one sender, one word) bundled as `claim ×5`, at most `WORDS_MAX` words at
191 * once. Its edge lights up behind it, a pair's first edge growing with its first comet. A comet the lead filter holds
192 * stops at the membrane with a splash; one that lands flares its receiver. Returns how long, in real ms, the cells still
193 * move by themselves.
194 */
195function drawBasicSky(g: Grid, scene: Scene, v: View, geo: Geometry, wide: boolean): number {
196 const W = geo.gw
197 const H = geo.gh * 2
198 const pt = (p: { x: number; y: number }) => ({ x: p.x - geo.gx, y: (p.y - geo.gy) * 2 })
199 const centre = pt({ x: geo.cx, y: geo.cy })
200 const c = new Canvas(W, H, P.bg)
201 const hs = Math.max(0.65, Math.min(1, geo.gw / 64))
202
203 type Fly = { m: SceneMessage; age: number; a: { x: number; y: number }; b: { x: number; y: number }; stop: number; color: number }
204 const flying: Fly[] = []
205 let motion = 0
206 for (let i = scene.messages.length - 1; i >= 0; i--) {
207 const m = scene.messages[i]!
208 const age = v.age(m.ts)
209 if (age >= FLIGHT_MS + ARRIVAL_MS) break
210 if (m.kind !== 'send' || age < 0) continue
211 const path = pathOf(geo, m.from, m.to, m.held)
212 if (path === undefined) continue
213 motion = Math.max(motion, FLIGHT_MS + ARRIVAL_MS - age)
214 flying.push({ m, age, a: path.a, b: path.b, stop: path.stop, color: nameColor(P, scene, m.from) })
215 }
216 flying.reverse()
217 const word = new Map<SceneMessage, string>()
218 const bursts: { from: string; w: string; ts: number; n: number; lead: SceneMessage }[] = []
219 for (const f of flying) {
220 const w = wordOf(f.m)
221 const b = bursts.find(x => x.from === f.m.from && x.w === w && f.m.ts - x.ts < BURST_MS)
222 if (b === undefined) bursts.push({ from: f.m.from, w, ts: f.m.ts, n: 1, lead: f.m })
223 else {
224 b.n++
225 if (f.m.to === LEAD || f.m.to === 'main') b.lead = f.m
226 }
227 }
228 for (const b of bursts.sort((x, y) => y.ts - x.ts).slice(0, WORDS_MAX)) word.set(b.lead, b.w + (b.n > 1 ? ' ×' + b.n : ''))
229
230 const flare = new Map<string, number>()
231 type Head = { x: number; y: number; dir: number; word: string; color: number }
232 const heads: Head[] = []
233 const rests: { x: number; y: number; word: string; color: number; k: number }[] = []
234 for (const f of flying) {
235 const A = pt(f.a)
236 const B = pt(f.b)
237 const t = Math.min(1, f.age / FLIGHT_MS)
238 const tLand = arrivalT(f.stop)
239 const head = Math.min(f.stop, ease(t))
240 const landedFor = f.age - tLand * FLIGHT_MS
241 if (landedFor < 0) {
242 const p = curveAt(A, B, centre, head)
243 // One pixel of head with a faint halo under a cell; a one-pixel trail of at most TRAIL pixels, fading fast.
244 const length = Math.max(1, Math.hypot(B.x - A.x, B.y - A.y))
245 for (let k = TRAIL; k >= 1; k--) {
246 const tt = head - k / length
247 if (tt < 0.02) continue
248 const q = curveAt(A, B, centre, tt)
249 c.blend(Math.floor(q.x), Math.floor(q.y), f.color, 0.75 * (1 - k / (TRAIL + 1)) ** 2)
250 }
251 c.glow(p.x, p.y, 0.6, f.color, 0.35)
252 c.blend(Math.floor(p.x), Math.floor(p.y), mix(f.color, 0xffffff, 0.7), 1)
253 heads.push({ x: p.x, y: p.y, dir: Math.sign(B.x - A.x) || 1, word: word.get(f.m) ?? '', color: f.color })
254 } else if (f.m.held === true) {
255 if (landedFor < SPLASH_MS) {
256 const k = 1 - landedFor / SPLASH_MS
257 const p = curveAt(A, B, centre, f.stop)
258 c.glow(p.x, p.y, 0.6 + 0.6 * (1 - k), mix(MEMBRANE, 0xffffff, 0.5 * k), 0.9 * k)
259 }
260 } else {
261 if (landedFor < FLARE_MS) flare.set(f.m.to === 'main' ? LEAD : f.m.to, Math.max(flare.get(f.m.to) ?? 0, 1 - landedFor / FLARE_MS))
262 const w = word.get(f.m)
263 if (!wide && w !== undefined && landedFor < ARRIVAL_MS) rests.push({ x: B.x, y: B.y, word: w, color: f.color, k: 1 - landedFor / ARRIVAL_MS })
264 }
265 }
266
267 const sun = flare.get(LEAD) ?? 0
268 // At rest the lead is one calm pixel with a faint halo under a cell; a delivered wake flares it, within two cells, for FLARE_MS.
269 c.glow(centre.x, centre.y, 0.6 + 1.0 * sun, P.accent, 0.25 + 0.65 * sun)
270 if (sun > 0) c.blend(Math.floor(centre.x), Math.floor(centre.y), mix(P.accent, 0xffffff, 0.5), sun)
271 const halos: { n: Node; state: AgentState; color: number; lit: number; bump: number }[] = []
272 for (const n of geo.nodes) {
273 const a = scene.agents.get(n.name)!
274 const state = stateIn(scene, a.name, v)
275 const color = state === 'stalled' ? P.state.stalled : agentColor(P, a)
276 const lit = (v.filter !== undefined && v.filter !== n.name ? 0.3 : 1) * presence(a, v)
277 const seg = a.segments[a.segments.length - 1]
278 const bump = Math.max(seg === undefined ? 0 : fade(v.age(seg.from), FLASH_MS), flare.get(n.name) ?? 0)
279 halos.push({ n, state, color, lit, bump })
280 if (state === 'quiet') continue
281 const p = pt(n)
282 const r = state === 'running' ? 1.15 : state === 'stalled' ? 1.25 : state === 'waiting' ? 0.85 : 0.65
283 const a0 = state === 'idle' || state === 'ended' ? 0.2 : state === 'waiting' ? 0.35 : 0.5
284 c.glow(p.x, p.y, (r + 0.4 * bump) * hs, color, (a0 + 0.3 * bump) * lit)
285 if (state === 'running' || bump > 0) c.blend(Math.floor(p.x), Math.floor(p.y), mix(color, 0xffffff, 0.5 + 0.5 * bump), lit)
286 }
287
288 const rgb = c.rgb()
289 const at = (x: number, y: number) => {
290 const i = (y * W + x) * 3
291 return quant((rgb[i]! << 16) | (rgb[i + 1]! << 8) | rgb[i + 2]!)
292 }
293 const bright = new Uint8Array(W * geo.gh)
294 for (let y = 0; y < geo.gh; y++) for (let x = 0; x < W; x++) {
295 const top = at(x, 2 * y)
296 const bot = at(x, 2 * y + 1)
297 if (top === bot) g.put(geo.gx + x, geo.gy + y, ' ', top, top)
298 else g.put(geo.gx + x, geo.gy + y, '▀', top, bot)
299 if (Math.max(luma(top), luma(bot)) > 60) bright[y * W + x] = 1
300 }
301 const cellBg = (x: number, y: number) => g.bg[y * g.cols + x]!
302 const isBright = (x: number, y: number) => x < geo.gx || y < geo.gy || x >= geo.gx + W || y >= geo.gy + geo.gh || bright[(y - geo.gy) * W + (x - geo.gx)] === 1
303 const dot = (dx: number, dy: number, color: number, k: number) => {
304 const x = Math.floor(dx) >> 1
305 const y = Math.floor(dy) >> 2
306 if (!isBright(x, y)) g.dot(dx, dy, quant(mix(cellBg(x, y), color, k)))
307 }
308
309 for (let y = geo.gy; y < geo.gy + geo.gh; y++) for (let x = geo.gx; x < geo.gx + geo.gw; x++) {
310 const r = hash(x, y)
311 if (r < 0.03) dot(x * 2 + ((r * 100) % 2), y * 4 + ((r * 1000) % 4), P.text, 0.2 + r * 10)
312 }
313 const rm = geo.membrane * 2
314 const ring = Math.max(12, Math.ceil(rm * 6))
315 for (let k = 0; k < ring; k++) {
316 if (Math.floor(k / 3) % 2 === 1) continue
317 const a = (k / ring) * Math.PI * 2
318 dot(geo.cx * 2 + Math.cos(a) * rm, geo.cy * 4 + Math.sin(a) * rm, mix(MEMBRANE, P.text, 0.25), 1)
319 }
320
321 // Edges as braille curves; a pair's edge whose first comet still flies shows only as far as that comet got.
322 const norm = (n: string) => (n === 'main' || n === 'lead' ? LEAD : n)
323 const pairOf = (x: string, y: string) => [norm(x), norm(y)].sort().join('|')
324 const first = new Map<string, SceneMessage>()
325 for (const m of scene.messages) if (m.kind === 'send' && !first.has(pairOf(m.from, m.to))) first.set(pairOf(m.from, m.to), m)
326 const sweep = (pa: { x: number; y: number }, pb: { x: number; y: number }, from: number, to: number, color: (t: number) => number, k: number) => {
327 const steps = Math.ceil(Math.hypot((pb.x - pa.x) * 2, (pb.y - pa.y) * 4)) + 4
328 for (let i = 0; i <= steps; i++) {
329 const t = i / steps
330 if (t < Math.max(0.06, from) || t > Math.min(0.94, to)) continue
331 const p = curveAt(pa, pb, { x: geo.cx, y: geo.cy }, t)
332 dot(p.x * 2, p.y * 4, color(t), k)
333 }
334 }
335 for (const e of edgeWeights(scene).values()) {
336 const m = first.get(pairOf(e.a, e.b))
337 const age = m === undefined ? Infinity : v.age(m.ts)
338 const young = age >= 0 && age < FLIGHT_MS
339 const [from, to] = young && norm(m!.from) !== e.a ? [e.b, e.a] : [e.a, e.b]
340 const pa = pos(geo, from)
341 const pb = pos(geo, to)
342 if (pa === undefined || pb === undefined) continue
343 const ca = nameColor(P, scene, from)
344 const cb = nameColor(P, scene, to)
345 const lit = touches(v.filter, e.a, e.b) ? 1 : 0.25
346 sweep(pa, pb, 0, young ? ease(age / FLIGHT_MS) : 1, t => mix(ca, cb, t), (0.4 + 0.6 * e.w) * lit)
347 }
348 // The edge behind a comet in flight lights up in the sender's colour, from the sender to the head.
349 for (const f of flying) {
350 const t = f.age / FLIGHT_MS
351 if (t >= 1) continue
352 sweep(f.a, f.b, 0, Math.min(f.stop, ease(t)), () => mix(f.color, 0xffffff, 0.25), 0.95)
353 }
354
355 if (geo.gx > 0) {
356 for (const n of geo.nodes) {
357 const color = agentColor(P, scene.agents.get(n.name))
358 const ink = v.filter !== undefined && v.filter !== n.name ? mix(color, P.bg, 0.6) : color
359 const edge = n.side === 'left' ? geo.gx * 2 : (geo.gx + geo.gw) * 2 - 1
360 const knee = n.side === 'left' ? n.x * 2 - 6 : n.x * 2 + 8
361 g.line(edge, n.labelRow * 4 + 2, knee, n.labelRow * 4 + 2, quant(mix(P.bg, ink, 0.3)))
362 g.line(knee, n.labelRow * 4 + 2, n.x * 2 + (n.side === 'left' ? -2 : 2), n.y * 4, quant(mix(P.bg, ink, 0.3)))
363 }
364 }
365
366 const sx = Math.floor(geo.cx)
367 const sy = Math.floor(geo.cy)
368 g.put(sx, sy, '◉', quant(mix(P.accent, 0xffffff, sun)), cellBg(sx, sy))
369 leadWakes(g, scene, v, sx, sy)
370 for (const h of halos) {
371 const x = Math.floor(h.n.x)
372 const y = Math.floor(h.n.y)
373 const fg = h.state === 'quiet' ? P.rule : mix(mix(h.color, 0xffffff, h.state === 'running' ? 0.6 : 0.2), 0xffffff, 0.5 * h.bump)
374 g.put(x, y, STATE_GLYPH[h.state], quant(h.state === 'quiet' ? P.rule : mix(P.bg, fg, h.lit)), cellBg(x, y))
375 }
376
377 // Words: quiet, behind the head; with no label margins, a landed word rests under its receiver. A word is written whole
378 // where every cell it needs is in the box and holds only sky, with a sky cell (or the box edge) on each side, else not at all.
379 const fits = (x0: number, y: number, text: string) => {
380 if (y < geo.gy || y >= geo.gy + geo.gh || x0 < geo.gx || x0 + width(text) > geo.gx + geo.gw) return false
381 for (let x = Math.max(geo.gx, x0 - 1); x < Math.min(geo.gx + geo.gw, x0 + width(text) + 1); x++) {
382 const ch = g.ch[y * g.cols + x]!
383 if (!(ch === 0x2580 || ch === 32 || (ch >= 0x2800 && ch <= 0x28ff))) return false
384 }
385 return true
386 }
387 const write = (x0: number, y: number, text: string, fg: (x: number) => number) => {
388 if (!fits(x0, y, text)) return
389 for (let i = 0; i < width(text); i++) g.put(x0 + i, y, text[i]!, quant(fg(x0 + i)), cellBg(x0 + i, y))
390 }
391 for (const h of heads) {
392 if (h.word === '') continue
393 const hx = Math.floor(h.x) + geo.gx
394 const hy = Math.floor(h.y / 2) + geo.gy
395 const x0 = Math.max(geo.gx, Math.min(geo.gx + geo.gw - width(h.word), h.dir > 0 ? hx - 1 - width(h.word) : hx + 2))
396 write(x0, hy, h.word, x => mix(cellBg(x, hy), mix(h.color, P.text, 0.4), 0.55))
397 }
398 for (const r of rests) {
399 const hx = Math.floor(r.x) + geo.gx
400 const y = Math.floor(r.y / 2) + geo.gy + 1
401 write(Math.max(geo.gx, hx - (width(r.word) >> 1)), y, r.word, x => mix(cellBg(x, y), mix(r.color, P.text, 0.4), 0.6 * r.k))
402 }
403 return motion
404}
405
406/** The wakes beside the lead: `▲ n` delivered on its left, `▽ n` held on its right, each lit as one lands, and `LEAD` below. */
407function leadWakes(g: Grid, scene: Scene, v: View, sx: number, sy: number) {
408 const last = (held: boolean) => scene.wakes.filter(w => w.held === held).at(-1)
409 const lit = (held: boolean) => {
410 const w = last(held)
411 return w === undefined ? 0 : fade(v.age(w.ts), 1200)
412 }
413 g.textRight(sx, sy, ' ▲ ' + scene.delivered + ' ', mix(P.accent, 0xffffff, lit(false)))
414 g.text(sx + 1, sy, ' ▽ ' + scene.held + ' ', mix(P.dim, P.text, lit(true)))
415 g.text(sx - 1, sy + 1, 'LEAD', P.accent)
416}
417
418/** How long a message lights its edge on the rich sky, in real ms: three sky redraws, a step dimmer each. */
419export const LIT_MS = 3 * SKY_MIN_MS
420
421type Lit = { from: string; to: string; held?: boolean; level: number; age: number }
422
423/** The edges messages light now, by `from>to`: level 3 for one sent in the last sky interval, 2 and 1 for older; at most the newest per edge. */
424function litEdges(scene: Scene, v: View): { lit: Map<string, Lit>; fadeMs: number } {
425 const lit = new Map<string, Lit>()
426 let fadeMs = 0
427 for (let i = scene.messages.length - 1; i >= 0; i--) {
428 const m = scene.messages[i]!
429 const age = v.age(m.ts)
430 if (age >= LIT_MS) break
431 if (m.kind !== 'send' || age < 0) continue
432 fadeMs = Math.max(fadeMs, LIT_MS - age)
433 const key = m.from + '>' + m.to
434 const level = 3 - Math.floor(age / SKY_MIN_MS)
435 if ((lit.get(key)?.level ?? 0) < level) lit.set(key, { from: m.from, to: m.to, ...(m.held === undefined ? {} : { held: m.held }), level, age })
436 }
437 return { lit, fadeMs }
438}
439
440/** How long a comet takes from sender to receiver, in real ms. */
441export const FLIGHT_MS = 1_000
442/** How long a burst of messages animates the sky at most, in real ms: the flight and a short landing. */
443export const BURST_MS = 1_200
444type Flight = { t: number; comets: SceneMessage[] }
445
446/**
447 * The burst in flight now: messages played within `BURST_MS` of the burst's first, which started less than `BURST_MS`
448 * ago; all its comets fly together, `t` of the way (0 → 1 over `FLIGHT_MS`). Undefined when none flies.
449 */
450function flightOf(scene: Scene, v: View): Flight | undefined {
451 const recent: { m: SceneMessage; age: number }[] = []
452 for (let i = scene.messages.length - 1; i >= 0; i--) {
453 const m = scene.messages[i]!
454 const age = v.age(m.ts)
455 if (age >= 5 * BURST_MS) break
456 if (m.kind === 'send' && age >= 0) recent.push({ m, age })
457 }
458 let start: number | undefined
459 let comets: SceneMessage[] = []
460 for (const r of recent.reverse()) {
461 if (start === undefined || start - r.age >= BURST_MS) {
462 start = r.age
463 comets = []
464 }
465 comets.push(r.m)
466 }
467 if (start === undefined || start >= BURST_MS) return undefined
468 return { t: Math.min(1, start / FLIGHT_MS), comets }
469}
470
471/** The most pixels a sky is drawn with: a pane larger than about 1100 × 900 pixels gets a scaled-down sky. */
472const SKY_MAX_PX = 1_000_000
473
474/** The most rays the lead's delivered wakes draw; from this many on, their count shows in the ring too. */
475export const RAYS_MAX = 24
476
477const rgbOf = (c: number): [number, number, number] => [(c >> 16) & 255, (c >> 8) & 255, c & 255]
478
479/**
480 * The sky as a scene for the renderer process, at a cell's pixel size scaled to at most `SKY_MAX_PX` pixels: the edges,
481 * leader lines, rays, beads, agents and lit edges, and the burst in flight as comets that set off together.
482 */
483function skyScene(scene: Scene, v: View, geo: Geometry, lit: Map<string, Lit>, flight: Flight | undefined): SkyScene {
484 const scale = Math.min(1, Math.sqrt(SKY_MAX_PX / (geo.gw * CELL_PX.w * geo.gh * CELL_PX.h)))
485 const kx = CELL_PX.w * scale
486 const ky = CELL_PX.h * scale
487 const u = Math.max(0.4, kx / 6)
488 const W = Math.max(1, Math.floor(geo.gw * kx))
489 const H = Math.max(1, Math.floor(geo.gh * ky))
490 const node = (p: { x: number; y: number }): [number, number] => [(Math.floor(p.x) + 0.5 - geo.gx) * kx, (Math.floor(p.y) + 0.5 - geo.gy) * ky]
491 const centre = node({ x: geo.cx, y: geo.cy })
492 const bend = (a: [number, number], b: [number, number]): [number, number] => {
493 const mx = (a[0] + b[0]) / 2
494 const my = (a[1] + b[1]) / 2
495 return [mx + (centre[0] - mx) * 0.18, my + (centre[1] - my) * 0.18]
496 }
497 const line = (from: string, to: string, held: boolean | undefined, age: number) => {
498 const path = pathOf(geo, from, to, held)
499 if (path === undefined) return []
500 const a = node(path.a)
501 const b = node(path.b)
502 const toLead = to === LEAD || to === 'main' || to === 'lead'
503 return [{ a, q: bend(a, b), b, stop: path.stop, rgb: rgbOf(nameColor(P, scene, from)), age, ...(toLead ? { lead: true, held: held === true } : {}) }]
504 }
505 const norm = (n: string) => (n === 'main' || n === 'lead' ? LEAD : n)
506 const pairOf = (x: string, y: string) => [norm(x), norm(y)].sort().join('|')
507 const first = new Map<string, SceneMessage>()
508 for (const m of scene.messages) if (m.kind === 'send' && !first.has(pairOf(m.from, m.to))) first.set(pairOf(m.from, m.to), m)
509 const edges = [...edgeWeights(scene).values()].flatMap(e => {
510 const m = first.get(pairOf(e.a, e.b))
511 const age = m === undefined ? Infinity : v.age(m.ts)
512 const young = age >= 0 && age < FLIGHT_MS
513 const [from, to] = young && norm(m!.from) !== e.a ? [e.b, e.a] : [e.a, e.b]
514 const pa = pos(geo, from)
515 const pb = pos(geo, to)
516 if (pa === undefined || pb === undefined) return []
517 const a = node(pa)
518 const b = node(pb)
519 return [{ a, q: bend(a, b), b, w: Math.ceil(e.w * 4) / 4, rgb: rgbOf(mix(nameColor(P, scene, e.a), nameColor(P, scene, e.b), 0.5)), lit: touches(v.filter, e.a, e.b) ? 1 : 0.2, ...(young ? { age } : {}) }]
520 })
521 const dimmed = (name: string) => (v.filter !== undefined && v.filter !== name ? 0.3 : 1) * presence(scene.agents.get(name)!, v)
522 const leaders = geo.gx === 0 ? [] : geo.nodes.map(n => {
523 const p = node(n)
524 const ey = (n.labelRow + 0.5 - geo.gy) * ky
525 const kn = n.side === 'left' ? p[0] - 2 * kx : p[0] + 2 * kx
526 return { pts: [[n.side === 'left' ? 0 : W, ey], [kn, ey], p] as [number, number][], rgb: rgbOf(agentColor(P, scene.agents.get(n.name))), lit: dimmed(n.name) }
527 })
528 const nodes = geo.nodes.map(n => {
529 const state = stateIn(scene, n.name, v)
530 const [x, y] = node(n)
531 return { x, y, rgb: rgbOf(state === 'stalled' ? P.state.stalled : agentColor(P, scene.agents.get(n.name))), state, lit: dimmed(n.name) }
532 })
533 return {
534 w: W,
535 h: H,
536 u,
537 nu: Math.max(0.75, u),
538 centre,
539 membrane: geo.membrane * kx,
540 ground: rgbOf(P.bg),
541 haze: rgbOf(0x120f2e),
542 star: rgbOf(P.text),
543 membraneRgb: rgbOf(MEMBRANE),
544 accent: rgbOf(P.accent),
545 dim: rgbOf(P.dim),
546 rule: rgbOf(P.rule),
547 stalled: rgbOf(P.state.stalled),
548 edges,
549 leaders,
550 rays: Math.min(scene.delivered, RAYS_MAX),
551 count: scene.delivered >= RAYS_MAX ? scene.delivered : 0,
552 beads: Math.min(scene.held, RAYS_MAX),
553 lit: [...lit.values()].flatMap(l => line(l.from, l.to, l.held, l.age)),
554 comets: (flight?.comets ?? []).flatMap(m => line(m.from, m.to, m.held, flight!.t * FLIGHT_MS)),
555 nodes,
556 litMs: LIT_MS,
557 flightMs: FLIGHT_MS,
558 landMs: BURST_MS,
559 }
560}
561
562/** How long a landed message's type shows under its receiver's name, in real ms. */
563export const ARRIVAL_MS = 1_500
564
565/** The types of the messages that landed at `name` in the last `ARRIVAL_MS`, a burst bundled: `claim ×3 · handoff`. */
566function arrivals(scene: Scene, v: View, name: string): string {
567 const counts = new Map<string, number>()
568 for (let i = scene.messages.length - 1; i >= 0; i--) {
569 const m = scene.messages[i]!
570 const age = v.age(m.ts)
571 if (age >= 5 * BURST_MS + ARRIVAL_MS) break
572 if (m.kind !== 'send' || m.to !== name || age < FLIGHT_MS || age >= FLIGHT_MS + ARRIVAL_MS) continue
573 const type = (m.type ?? 'message').toLowerCase()
574 counts.set(type, (counts.get(type) ?? 0) + 1)
575 }
576 return [...counts].reverse().map(([t, n]) => (n > 1 ? `${t} ×${n}` : t)).join(' · ')
577}
578
579/** Look B at the view's size. */
580export function lookB(scene: Scene, v: View): Frame {
581 const g = new Grid(v.cols, v.rows, P.bg)
582 const images: ImageLayer[] = []
583 const wide = v.cols >= 72
584 const geo = geometry(scene, v, wide)
585 g.text(1, 0, '◎', P.accent)
586 const badge = v.isEnded === true ? `■ ended · ran ${ago(v.runTo - v.runFrom)}` : v.speed === undefined ? '● live' : (v.isPaused ? '❚❚ ' : '▶ ') + v.speed + '×'
587 const r = g.textRight(v.cols - 1, 0, badge, P.dim)
588 const rt = g.textRight(r - 2, 0, timeOfDay(v.now), P.text)
589 const tx = g.text(3, 0, spaced(v.title), P.text, undefined, Math.min(v.cols - 30, rt - 5))
590 const note = [v.note, movesNote(scene, v)].filter(n => n !== undefined).join(' · ')
591 if (note !== '') g.text(tx + 2, 0, note, P.dim, undefined, rt - tx - 4)
592 let fadeMs = 0
593 const flight = v.level === 'rich' ? flightOf(scene, v) : undefined
594 const lit = v.level === 'rich' ? litEdges(scene, v) : undefined
595 const stream = lit === undefined ? undefined : skyScene(scene, v, geo, lit.lit, flight)
596 if (lit !== undefined) {
597 fadeMs = lit.fadeMs
598 images.push({
599 key: 'sky',
600 x: geo.gx,
601 y: geo.gy,
602 cols: geo.gw,
603 rows: geo.gh,
604 sig: '',
605 draw: () => new Canvas(1, 1, P.bg),
606 ground: P.bg,
607 stream,
608 alt: `star map of ${scene.agents.size} agents around the lead`,
609 })
610 } else fadeMs = drawBasicSky(g, scene, v, geo, wide)
611 if (wide) {
612 for (const n of geo.nodes) {
613 const a = scene.agents.get(n.name)!
614 const state = stateIn(scene, a.name, v)
615 const isDim = v.filter !== undefined && v.filter !== n.name
616 const ink = (c: number) => (isDim ? mix(c, P.bg, 0.6) : c)
617 const name = (a.model === undefined ? '' : MODEL_GLYPH[a.model] + ' ') + (a.code ?? a.name)
618 const landed = arrivals(scene, v, n.name)
619 const sub = landed !== '' ? landed : `${a.code === undefined ? '' : a.name + ' · '}${state === 'quiet' ? 'not started' : state}`
620 const w = geo.gx - 2
621 const subInk = ink(landed !== '' ? P.accent : state === 'stalled' ? P.state.stalled : P.dim)
622 if (n.side === 'left') {
623 g.textRight(geo.gx - 1, n.labelRow, name.slice(0, w), ink(agentColor(P, a)))
624 g.textRight(geo.gx - 1, n.labelRow + 1, sub.slice(0, w), subInk)
625 } else {
626 g.text(geo.gx + geo.gw + 1, n.labelRow, name, ink(agentColor(P, a)), undefined, w)
627 g.text(geo.gx + geo.gw + 1, n.labelRow + 1, sub, subInk, undefined, w)
628 }
629 }
630 }
631 let y = geo.gy + geo.gh
632 if (!wide) {
633 const half = Math.floor(v.cols / 2)
634 scene.order().forEach((a, i) => {
635 const x = 1 + (i % 2) * half
636 const row = y + Math.floor(i / 2)
637 const state = stateIn(scene, a.name, v)
638 const cx = g.text(x, row, STATE_GLYPH[state], state === 'stalled' ? P.state.stalled : agentColor(P, a))
639 g.text(cx + 1, row, (a.model ? MODEL_GLYPH[a.model] + ' ' : '') + scene.label(a.name), agentColor(P, a), undefined, half - 3)
640 })
641 y += Math.ceil(scene.agents.size / 2)
642 }
643 const last = sends(scene).filter(m => touches(v.filter, m.from, m.to)).at(-1)
644 if (last !== undefined) {
645 const lit = fade(v.age(last.ts), 1200)
646 const parts: [string, number][] = [
647 [scene.label(last.from), nameColor(P, scene, last.from)],
648 [' → ', P.dim],
649 [scene.label(last.to), nameColor(P, scene, last.to)],
650 [' ' + (last.type ?? '') + ' ', mix(P.accent, 0xffffff, lit)],
651 [last.summary.replace(/^\s*\[[A-Z]+\]\s*/, ''), mix(P.dim, P.text, 0.5 + 0.5 * lit)],
652 ]
653 const total = parts.reduce((n, [s]) => n + width(s), 0)
654 let x = Math.max(1, Math.floor((v.cols - total) / 2))
655 for (const [s, c] of parts) x = g.text(x, y + 1, s, c, undefined, v.cols - 1 - x)
656 }
657 let x = 1
658 const cards = v.isEnded === true ? [] : scene.cards()
659 const titles = cards.slice(0, 6).map(c => cardTitle(c.slice, 22) + (c.isDuplicate ? ' ⚠' : ''))
660 const ends: number[] = []
661 for (const t of titles) ends.push((ends.at(-1) ?? 1) + width(t) + 5)
662 const fits = (n: number) => n === 0 || (ends[n - 1]! <= v.cols && (n === cards.length || ends[n - 1]! + width(`+${cards.length - n} more`) <= v.cols - 1))
663 let n = titles.length
664 while (!fits(n)) n--
665 cards.slice(0, n).forEach((card, i) => {
666 x = g.text(x, y + 2, '■', P.status[card.status])
667 x = g.text(x + 1, y + 2, titles[i]!, mix(P.text, P.bg, 0.15)) + 3
668 })
669 if (n < cards.length) g.text(x, y + 2, `+${cards.length - n} more`, P.dim, undefined, v.cols - 1 - x)
670 let wx = g.text(1, y + 3, 'lead', P.dim)
671 wx = g.text(wx + 2, y + 3, '▲ ' + scene.delivered + ' woken', P.accent)
672 g.text(wx + 2, y + 3, '▽ ' + scene.held + ' held at the membrane', P.dim)
673 return { grid: g, images, links: cardLinks(cards), ...(fadeMs > 0 ? { fadeMs } : {}), ...(v.level === 'basic' && fadeMs > 0 ? { motionMs: fadeMs } : {}) }
674}
675hooks/pixels.ts 180 lines1// An RGBA pixel canvas for Image layers: anti-aliased lines, curves, discs and rings, additive glows.
2
3import { base64 } from './grid'
4
5export class Canvas {
6 readonly w: number
7 readonly h: number
8 /** Linear-ish working buffer, 0..255 per channel, RGB; alpha is 255 everywhere. */
9 private readonly px: Float32Array
10
11 constructor(w: number, h: number, bg: number) {
12 this.w = Math.max(1, Math.floor(w))
13 this.h = Math.max(1, Math.floor(h))
14 this.px = new Float32Array(this.w * this.h * 3)
15 this.rect(0, 0, this.w, this.h, bg, 1)
16 }
17
18 /** A copy of this canvas. */
19 clone(): Canvas {
20 const c = new Canvas(this.w, this.h, 0)
21 c.px.set(this.px)
22 return c
23 }
24
25 /** Mixes a colour into one pixel at `a` (0..1) over what is there. */
26 blend(x: number, y: number, c: number, a: number) {
27 if (a <= 0 || x < 0 || y < 0 || x >= this.w || y >= this.h) return
28 const i = (y * this.w + x) * 3
29 const k = Math.min(1, a)
30 this.px[i] = this.px[i]! * (1 - k) + ((c >> 16) & 255) * k
31 this.px[i + 1] = this.px[i + 1]! * (1 - k) + ((c >> 8) & 255) * k
32 this.px[i + 2] = this.px[i + 2]! * (1 - k) + (c & 255) * k
33 }
34
35 /** Adds a colour to one pixel at `a`, clamped at white: light on light gets brighter. */
36 add(x: number, y: number, c: number, a: number) {
37 if (a <= 0 || x < 0 || y < 0 || x >= this.w || y >= this.h) return
38 const i = (y * this.w + x) * 3
39 this.px[i] = Math.min(255, this.px[i]! + ((c >> 16) & 255) * a)
40 this.px[i + 1] = Math.min(255, this.px[i + 1]! + ((c >> 8) & 255) * a)
41 this.px[i + 2] = Math.min(255, this.px[i + 2]! + (c & 255) * a)
42 }
43
44 rect(x: number, y: number, w: number, h: number, c: number, a = 1) {
45 const x0 = Math.max(0, Math.floor(x))
46 const y0 = Math.max(0, Math.floor(y))
47 const x1 = Math.min(this.w, Math.ceil(x + w))
48 const y1 = Math.min(this.h, Math.ceil(y + h))
49 for (let py = y0; py < y1; py++) {
50 const cy = Math.min(py + 1, y + h) - Math.max(py, y)
51 for (let px = x0; px < x1; px++) {
52 const cx = Math.min(px + 1, x + w) - Math.max(px, x)
53 this.blend(px, py, c, a * cx * cy)
54 }
55 }
56 }
57
58 /** A line of half-width `r` (pixels), anti-aliased by distance to the segment. */
59 line(x0: number, y0: number, x1: number, y1: number, r: number, c: number, a = 1, additive = false) {
60 const minX = Math.max(0, Math.floor(Math.min(x0, x1) - r - 1))
61 const maxX = Math.min(this.w - 1, Math.ceil(Math.max(x0, x1) + r + 1))
62 const minY = Math.max(0, Math.floor(Math.min(y0, y1) - r - 1))
63 const maxY = Math.min(this.h - 1, Math.ceil(Math.max(y0, y1) + r + 1))
64 const dx = x1 - x0
65 const dy = y1 - y0
66 const len2 = dx * dx + dy * dy || 1
67 for (let py = minY; py <= maxY; py++) for (let px = minX; px <= maxX; px++) {
68 const qx = px + 0.5
69 const qy = py + 0.5
70 const t = Math.max(0, Math.min(1, ((qx - x0) * dx + (qy - y0) * dy) / len2))
71 const d = Math.hypot(qx - (x0 + dx * t), qy - (y0 + dy * t))
72 const cover = Math.max(0, Math.min(1, r + 0.5 - d))
73 if (cover > 0) additive ? this.add(px, py, c, a * cover) : this.blend(px, py, c, a * cover)
74 }
75 }
76
77 /** A quadratic curve from (x0,y0) to (x2,y2) bent toward (x1,y1), drawn from `from` to `to` of its length. */
78 curve(x0: number, y0: number, x1: number, y1: number, x2: number, y2: number, r: number, c: number, a = 1, from = 0, to = 1, additive = false) {
79 const steps = Math.max(4, Math.ceil(Math.hypot(x2 - x0, y2 - y0) / 6))
80 const pts: number[] = []
81 for (let k = 0; k <= steps; k++) {
82 const t = from + ((to - from) * k) / steps
83 pts.push((1 - t) * (1 - t) * x0 + 2 * (1 - t) * t * x1 + t * t * x2, (1 - t) * (1 - t) * y0 + 2 * (1 - t) * t * y1 + t * t * y2)
84 }
85 this.stroke(pts, r, c, a, additive)
86 }
87
88 /** A polyline of half-width `r` through `pts` (x, y pairs), each pixel covered once however many segments touch it. */
89 stroke(pts: readonly number[], r: number, c: number, a = 1, additive = false) {
90 if (pts.length < 4) return
91 let minX = Infinity
92 let minY = Infinity
93 let maxX = -Infinity
94 let maxY = -Infinity
95 for (let i = 0; i < pts.length; i += 2) {
96 minX = Math.min(minX, pts[i]!)
97 maxX = Math.max(maxX, pts[i]!)
98 minY = Math.min(minY, pts[i + 1]!)
99 maxY = Math.max(maxY, pts[i + 1]!)
100 }
101 const x0 = Math.max(0, Math.floor(minX - r - 1))
102 const y0 = Math.max(0, Math.floor(minY - r - 1))
103 const x1 = Math.min(this.w - 1, Math.ceil(maxX + r + 1))
104 const y1 = Math.min(this.h - 1, Math.ceil(maxY + r + 1))
105 if (x1 < x0 || y1 < y0) return
106 const mw = x1 - x0 + 1
107 const mask = new Float32Array(mw * (y1 - y0 + 1))
108 for (let i = 0; i + 3 < pts.length; i += 2) {
109 const ax = pts[i]!
110 const ay = pts[i + 1]!
111 const dx = pts[i + 2]! - ax
112 const dy = pts[i + 3]! - ay
113 const len2 = dx * dx + dy * dy || 1
114 const sx0 = Math.max(x0, Math.floor(Math.min(ax, ax + dx) - r - 1))
115 const sx1 = Math.min(x1, Math.ceil(Math.max(ax, ax + dx) + r + 1))
116 const sy0 = Math.max(y0, Math.floor(Math.min(ay, ay + dy) - r - 1))
117 const sy1 = Math.min(y1, Math.ceil(Math.max(ay, ay + dy) + r + 1))
118 for (let py = sy0; py <= sy1; py++) for (let px = sx0; px <= sx1; px++) {
119 const qx = px + 0.5
120 const qy = py + 0.5
121 const t = Math.max(0, Math.min(1, ((qx - ax) * dx + (qy - ay) * dy) / len2))
122 const cover = Math.max(0, Math.min(1, r + 0.5 - Math.hypot(qx - (ax + dx * t), qy - (ay + dy * t))))
123 const k = (py - y0) * mw + (px - x0)
124 if (cover > mask[k]!) mask[k] = cover
125 }
126 }
127 for (let py = y0; py <= y1; py++) for (let px = x0; px <= x1; px++) {
128 const cover = mask[(py - y0) * mw + (px - x0)]!
129 if (cover > 0) additive ? this.add(px, py, c, a * cover) : this.blend(px, py, c, a * cover)
130 }
131 }
132
133 disc(cx: number, cy: number, r: number, c: number, a = 1) {
134 for (let py = Math.floor(cy - r - 1); py <= Math.ceil(cy + r + 1); py++) for (let px = Math.floor(cx - r - 1); px <= Math.ceil(cx + r + 1); px++) {
135 const d = Math.hypot(px + 0.5 - cx, py + 0.5 - cy)
136 this.blend(px, py, c, a * Math.max(0, Math.min(1, r + 0.5 - d)))
137 }
138 }
139
140 /** A ring of half-width `w` at radius `r`. */
141 circle(cx: number, cy: number, r: number, w: number, c: number, a = 1) {
142 for (let py = Math.floor(cy - r - w - 1); py <= Math.ceil(cy + r + w + 1); py++) for (let px = Math.floor(cx - r - w - 1); px <= Math.ceil(cx + r + w + 1); px++) {
143 const d = Math.abs(Math.hypot(px + 0.5 - cx, py + 0.5 - cy) - r)
144 this.blend(px, py, c, a * Math.max(0, Math.min(1, w + 0.5 - d)))
145 }
146 }
147
148 /** A soft additive halo: intensity falls off as a gaussian of radius `r`. */
149 glow(cx: number, cy: number, r: number, c: number, a = 1) {
150 const reach = r * 2.2
151 for (let py = Math.floor(cy - reach); py <= Math.ceil(cy + reach); py++) for (let px = Math.floor(cx - reach); px <= Math.ceil(cx + reach); px++) {
152 const d2 = (px + 0.5 - cx) ** 2 + (py + 0.5 - cy) ** 2
153 this.add(px, py, c, a * Math.exp(-d2 / (r * r)))
154 }
155 }
156
157 /** The pixels as an Image's `{ rgba, width, height }` source. */
158 source(): { rgba: string; width: number; height: number } {
159 return { rgba: base64(this.rgba()), width: this.w, height: this.h }
160 }
161
162 /** The pixels as RGB, 3 bytes each, rows top down. */
163 rgb(): Uint8Array {
164 const out = new Uint8Array(this.w * this.h * 3)
165 for (let i = 0; i < this.px.length; i++) out[i] = this.px[i]!
166 return out
167 }
168
169 rgba(): Uint8Array {
170 const out = new Uint8Array(this.w * this.h * 4)
171 for (let i = 0, j = 0; i < this.px.length; i += 3, j += 4) {
172 out[j] = this.px[i]!
173 out[j + 1] = this.px[i + 1]!
174 out[j + 2] = this.px[i + 2]!
175 out[j + 3] = 255
176 }
177 return out
178 }
179}
180