SLOPSHOPPER

colony

Side pane showing agents as pixel creatures

paneguardcommandtoaststatusprompt
v0.3.0MITupdated 2026-10-10openrory/colony-mod
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · colony
│ ┃ Colony ✕ › fix the failing auth test and add an audit log call │ ┃ │ ┃ ⏺ Read(src/auth.ts) │ ┃ ⎿ Read 6 lines │ ┃ ⏺ Update(src/auth.ts) │ ┃ ⎿ Added 2 lines, removed 1 line │ ┃ ⏺ Bash(bun test) │ ┃ ⎿ 3 pass, 1 fail │ ┃ ▄ ▄▄▄▄▄▄▀▄▄ │ ┃ ▀▄▄▀███▀▀▄▀▀ ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ ██████ │ ┃ █▀▀▀██ ✻ Worked for 42s · done 4:20 PM │ ┃ █ ██ │ ┃ › /colony │ ┃ main ⎿ colony: Colony pane shown. │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Colony
▄ ▄▄▄▄▄▄▀▄▄ ▀▄▄▀███▀▀▄▀▀ ██████ █▀▀▀██ █ ██ main
README

colony

A Claude Code mod that shows a side pane with every agent and subagent in your session as a small pixel creature. At a glance you can see who is sleeping, who is working, who needs your answer, who has finished, and who is waiting for an outside event, and you can watch agents hand work to each other.

What you see

StateLookMeaning
Idlehead down, floating zthe agent is asleep / has nothing to do
In progresseyes open, movingthe agent is working
Pendingarms up, blinking !the agent needs you: a question, or an approve/reject
Completedarms in a V, tickthe agent finished
Failed / cancelledfallen figure / boxed dotthe agent ended with an error or was stopped
Listeningantenna pulsing, [source] tagthe agent is waiting for an outside event (see limits)
Unknownoutline with ?the mod cannot tell what the agent is doing
  • Size follows the model. A Haiku agent is the smallest figure; Sonnet, Opus and Fable (rarely used) draw progressively bigger. A figure whose model is not known yet is the smallest size.
  • A darker fill shows context. The body fills from the feet up in a darker shade of its state colour as the agent's context window fills. The fill is an estimate: the engine does not report a subagent's context window while it runs, so the mod estimates it from the agent's transcript and assumes a 200k window (1M for a [1m] model and for the 5.5 models).
  • Hover for details. Point at a figure to see a card with its full title, state, model, tokens used and context estimate. The label under the figure is cut to fit; the card is not. Cost per agent is not shown, because the engine only reports cost for the whole session.
  • Working agents wander. Agents that are working drift slowly side to side, sleeping and finished ones stay put, and agents that are talking walk toward each other.
  • Subagents appear under the agent that started them, with a connector. Reusable agents (named agents and teammates) rest as a sleeping figure when they finish instead of being removed. Agents no orchestrator here started (a teammate in its own pane, for example) have no connector.
  • Eyes show on awake figures; a sleeping figure's eyes are shut, drawn as two dashes, and a failed figure's are crossed.
  • Agents that are talking (a subagent starting or returning a result, a message between agents, a parent waiting on a subagent) move closer together and exchange a stream of 0s and 1s. They drift apart when it ends.
  • Many agents: older finished agents collapse into a +N done row. Agents that need you are never hidden.
  • States are told apart by shape and pose, not only colour, and there is a reduced-motion option.

The mod only watches. It never changes your tools, prompts, permissions or output.

Install

Type this at the prompt of a Claude Code terminal session:

/plugin install colony --marketplace openrory/colony-mod

Then:

  1. Answer y to Add marketplace? (github:openrory/colony-mod).
  2. Choose a scope. User keeps the mod active in every later session.
  3. Set the options when asked (or accept the defaults).

You should see Installed colony. Plugin is now active. and it is active right away, with no restart.

The install command is typed in a terminal session. The desktop app's Code tab answers that the command is not available there, but a mod installed from a terminal at user scope also draws in the desktop app.

Try it without installing

git clone https://github.com/openrory/colony-mod.git
claude --plugin-dir ./colony-mod

Use

  • The pane opens by itself the first time a subagent appears or an agent needs your answer.
  • /colony shows or hides the pane. If you close it yourself it stays closed until you run /colony again.
  • When Claude Code cannot seat the pane (a narrow terminal, roughly under 144 columns), the mod does not draw it. It then shows a summary on the status line, such as colony: 2 working, 1 needs you, and a toast when something needs you. Widen the terminal, or run /colony, to see the pane.

Options

OptionDefaultWhat it does
Reduced motionoffstatic frames only; no animation timer
Retention seconds30how long finished agents stay in the pane before they are removed
Share with my other sessionsoffshares this session's agents with your other sessions and shows theirs, with full detail for sessions that share and a limited figure for the rest. Set it in every session. See Sharing across sessions below
Sharing folder (optional)emptywhere this session shares its agents. Leave empty for the default, <your Claude folder>/colony, which is used while the sharing switch is on. Set the same folder in every session if you override it
Claude session files folder (optional)emptywhere Claude Code keeps its session files. Leave empty for the default, <your Claude folder>/sessions, which is used while the sharing switch is on. Setting a folder here also turns on the limited view, even with the switch off

Sessions that share are shown in full. Other running sessions appear as one limited figure each (their busy or idle state, name and folder on hover), with no agent detail. A session that has quit can linger until its file is 6 hours old, because nothing in the file says whether it is still alive. The session files format is not documented by Claude Code, so this may stop working after an update.

Sharing across sessions

It is off by default. To use it, switch on Share with my other sessions in each session you want to take part. That is the whole setup: no folder needs setting. Then, in any of those sessions, the pane shows:

  • every other session that also has the switch on, in full: each appears as a group beneath your own, with its agents, their states and the same 0s-and-1s exchanges. A group is marked needs you when one of its agents is waiting for your answer, and it dims with stale when its session stops updating.
  • every other running session that does not share (or does not have the mod), as one limited figure with no agent detail.

Where the folders are. Your Claude folder is $CLAUDE_CONFIG_DIR when that variable is set, and otherwise ~/.claude. With the switch on, sessions share their agents in <your Claude folder>/colony, and the limited view reads Claude Code's own session files from <your Claude folder>/sessions. The two optional folder options replace those defaults: set one only to use another folder, and set the same path in every session that should see it. Setting an option also turns on its part, even with the switch off, so settings made with earlier versions keep working.

Switch the option off again to stop sharing; the session then stops sharing and stops reading the others.

Claude Code's session files. Turning the switch on also reads the sessions folder above, which holds Claude Code's own session files, to draw the limited figures. Those files are only read on this machine, by the same user. Their format is not a public interface and may change in a later Claude Code release, which would stop those figures from showing until the mod is updated.

What is shared. Each session writes one small file, <folder>/<session-id>.json, every time something changes and about every 5 seconds as a heartbeat. It contains only:

  • the session's name and working folder, and a version number and last-updated time
  • for each agent: a short label (at most 40 characters), its state, its parent agent, its model, its token totals and what it is listening for
  • which agents are currently exchanging information

It never contains your prompts, messages, tool inputs or outputs, or file contents. Only sessions that use the same sharing folder read these files, and nothing leaves your machine.

Cleaning up. When a session ends or sharing is turned off, its file is overwritten with a marker that holds no name, folder or agent information. The mods API cannot delete files, so these tiny marker files stay in the folder; they are ignored after a minute and are safe to delete by hand at any time.

Update and uninstall

Use the plugin manager of your Claude Code build (/plugin) to update colony from the colony-mod marketplace or to uninstall it. To remove the marketplace as well, remove colony-mod from the marketplaces list in the same menu.

Troubleshooting

MessageCause
Marketplace file not found at …the repository you named has no .claude-plugin/marketplace.json; check <owner>/<repo>
Plugin "colony" not found in marketplace …the name after /plugin install does not match the plugin name in the marketplace file
nothing appearsthe terminal may be narrower than the pane needs; widen it or run /colony

Known limits

  • Listening is only what the mod can see. The mods API cannot list triggers configured before the session. An agent shows as listening after it starts a Monitor or RemoteTrigger, and an inbound event (for example from GitHub) labels its source. A scheduled wake-up is the agent's own timer and does not count.
  • Which subagent is asking? If the engine does not say which subagent raised a permission request, the mod attributes it to the most recently active agent.
  • Failed vs. completed subagents depend on the engine's agent list being up to date when a subagent stops.
  • Sharing needs the mod in every session, with the switch on in each (and the same Sharing folder, if you override it). Updates reach other panes about a second late. It covers one user on one machine only.
  • Default folders follow the environment. CLAUDE_CONFIG_DIR or HOME is read when the session starts. A session whose environment differs (for example a different CLAUDE_CONFIG_DIR) does not see the others unless it uses the same folders, set explicitly.
  • The limited view reads Claude Code's session files once the switch is on, and their format is not public. A format change stops those figures from showing; it does not affect sharing between sessions that have the mod.
  • Very crowded panes: if even the headers of many sessions do not fit, a group that needs you folds to its header (the needs you marker stays) before any group is dropped.
  • The mods API is early access and may change between Claude Code releases.

Development

claude plugin validate .
claude plugin test .
claude --plugin-dir .

Design documents live in specs/001-agent-colony-pane/.

Source 16 files
hooks/register.tsx 525 lines
1import { atom, read, update } from 'claude-code'
2import type { Register, EngineInterface } from 'claude-code'
3
4import { initialColony, reduce, REACT_MS, type Peer, type Signal } from '../src/model'
5import { parsePeer } from '../src/peers'
6import { guarded } from '../src/observe'
7import { layout } from '../src/layout'
8import {
9  animates,
10  attentionOf,
11  CLOCK_MS,
12  contextFor,
13  DEFAULT_RETENTION_SECONDS,
14  nextRecentAgent,
15  pendingAgentsOf,
16  readOptions,
17  sessionsFolderFor,
18  sharedFolderFor,
19  shouldAutoOpen,
20  shouldToastPending,
21  shouldWrite,
22  statusFor,
23  summaryPath,
24} from '../src/runtime'
25import { buildSummary, endedSummary, parseSummary } from '../src/snapshot'
26import { mergeSessions, type FileRead } from '../src/sessions'
27import { reconcileFromList, toSignals, type ListedAgent } from '../src/signals'
28import { estimateContextTokens } from '../src/context'
29import { renderPane } from '../src/view'
30
31const PANE = 'colony'
32const PANE_TITLE = 'Colony'
33const HIDDEN_KEY = 'isHiddenByUser'
34const DEFAULT_RETENTION_MS = DEFAULT_RETENTION_SECONDS * 1000
35
36// One colony per session. Its retention is set from options at session.start.
37export const colonyAtom = atom(
38  { plugin: 'colony', key: 'colony' } as const,
39  initialColony(DEFAULT_RETENTION_MS),
40)
41
42// Module state for this load of the mod. Lost on reload, which is acceptable (see T018 notes).
43let reducedMotion = false
44let retentionMs = DEFAULT_RETENTION_MS
45let sessionTimer: { cancel: () => void } | null = null
46let shareTimer: { cancel: () => void } | null = null
47// The options as configured; the folders actually used (`sharedFolder`, `sessionsFolder`) are resolved at
48// session start, when the environment (CLAUDE_CONFIG_DIR, HOME) can be read. Until then both are off.
49let shareSessions = false
50let sharedFolderOption = ''
51let sessionsDirectoryOption = ''
52let sharedFolder = ''
53let sessionsFolder = ''
54let recentAgentId: string | null = null
55let clockTimer: { cancel: () => void } | null = null
56let firstAutoDone = false
57let lastStatus: string | undefined = undefined
58let lastPendingCount = 0
59
60type Dollar = EngineInterface
61
62// Fold one signal into the colony.
63export function dispatch($: Dollar, signal: Signal): Promise<unknown> {
64  return applySignals($, [signal])
65}
66
67async function applySignals($: Dollar, signals: Signal[]): Promise<void> {
68  if (signals.length === 0) return
69  await update($, colonyAtom, c => signals.reduce(reduce, c))
70  // Every state change is a chance to share (the throttle in shareState decides whether it is written now).
71  if (sharedFolder) await shareState($)
72}
73
74// The engine's agent list; an unreadable list reads as empty so the colony falls back to events.
75async function listAgents($: Dollar): Promise<ListedAgent[]> {
76  try {
77    return (await $.agent.list()) as ListedAgent[]
78  } catch {
79    return []
80  }
81}
82
83// Reconcile with the engine's list: its status wins over inferred state (contracts/event-mapping.md).
84async function reconcileAgents($: Dollar): Promise<void> {
85  const listed = await listAgents($)
86  await applySignals($, reconcileFromList(listed, await $.clock.now()))
87}
88
89// Run the clock only while something animates (never in reduced motion).
90async function syncClock($: Dollar): Promise<void> {
91  const colony = await read($, colonyAtom)
92  const wanted = animates(colony, reducedMotion)
93  if (wanted && !clockTimer) {
94    clockTimer = $.clock.every(CLOCK_MS, () => {
95      void tick($).catch(() => {})
96    })
97  } else if (!wanted && clockTimer) {
98    clockTimer.cancel()
99    clockTimer = null
100  }
101}
102
103async function tick($: Dollar): Promise<void> {
104  const at = await $.clock.now()
105  await applySignals($, [{ type: 'tick', at }])
106  await syncClock($)
107}
108
109async function paneState($: Dollar): Promise<{ paneOpen: boolean; placed: boolean }> {
110  const pane = (await $.ui.panes()).find(p => p.id === PANE)
111  return { paneOpen: pane !== undefined, placed: pane?.isPlaced ?? false }
112}
113
114// Keeps the status line and the pending toast in step with the colony (narrow-terminal fallback).
115async function refreshPane($: Dollar): Promise<void> {
116  const colony = await read($, colonyAtom)
117  const { paneOpen, placed } = await paneState($)
118  const status = statusFor(colony, paneOpen, placed)
119  if (status !== lastStatus) {
120    $.ui.status(status)
121    lastStatus = status
122  }
123  const pending = pendingAgentsOf(colony)
124  if (
125    shouldToastPending({ pendingCount: pending.length, previousPendingCount: lastPendingCount, paneOpen, placed })
126  ) {
127    $.ui.toast(`colony: ${pending[0]?.label ?? 'an agent'} needs you`)
128  }
129  lastPendingCount = pending.length
130}
131
132// Other sessions. Two sources, both read only while the pane is open: the shared folder (spec 002) and the
133// sessions folder (spec 003, the Claude session files). Both are resolved at session start (spec 005): one
134// switch turns on both defaults, and an override turns on its own part. Nothing is read from an empty folder
135// path; a file that cannot be read or parsed is skipped.
136const PEER_POLL_MS = 5000
137const SHARED_POLL_MS = 1000
138
139async function readPeers($: Dollar): Promise<Peer[]> {
140  if (!sessionsFolder) return []
141  const now = await $.clock.now()
142  const self = await Promise.resolve($.session.id()).catch(() => null)
143  const peers: Peer[] = []
144  for (const entry of await $.fs.list(sessionsFolder)) {
145    if (entry.kind !== 'file' || !entry.name.endsWith('.json')) continue
146    try {
147      const text = await $.fs.read(`${sessionsFolder.replace(/\/$/, '')}/${entry.name}`)
148      const peer = parsePeer(typeof text === 'string' ? text : '', self ?? null, now)
149      if (peer) peers.push(peer)
150    } catch {
151      // Unreadable or vanished between listing and reading: skip it.
152    }
153  }
154  return peers
155}
156
157// The spec 003 peer view, unchanged: with no shared folder, the peer folder's sessions are the figures.
158async function pollPeers($: Dollar): Promise<void> {
159  const peers = await readPeers($)
160  await applySignals($, [{ type: 'peers', peers, at: await $.clock.now() }])
161}
162
163// Summaries from the shared folder, each file read only when its modification time changed since the
164// last poll. A file that cannot be read or parsed leaves no summary; a missing folder leaves none at all.
165const sharedFiles = new Map<string, { mtimeMs: number; read: FileRead }>()
166
167async function readSharedFile($: Dollar, name: string): Promise<FileRead> {
168  const stem = name.slice(0, -'.json'.length)
169  try {
170    const text = await $.fs.read(`${sharedFolder.replace(/\/+$/, '')}/${name}`)
171    const summary = parseSummary(typeof text === 'string' ? text : '')
172    return { sessionId: summary?.sessionId ?? stem, summary }
173  } catch {
174    return { sessionId: stem, summary: null }
175  }
176}
177
178async function readShared($: Dollar): Promise<{ summaries: FileRead[]; mtimes: Record<string, number> }> {
179  const summaries: FileRead[] = []
180  const mtimes: Record<string, number> = {}
181  const entries = await $.fs.list(sharedFolder).catch(() => null)
182  if (!entries) return { summaries, mtimes }
183  const listed = new Set<string>()
184  for (const entry of entries) {
185    if (entry.kind !== 'file' || !entry.name.endsWith('.json')) continue
186    listed.add(entry.name)
187    let cached = sharedFiles.get(entry.name)
188    if (!cached || cached.mtimeMs !== entry.mtimeMs) {
189      cached = { mtimeMs: entry.mtimeMs, read: await readSharedFile($, entry.name) }
190      sharedFiles.set(entry.name, cached)
191    }
192    summaries.push(cached.read)
193    mtimes[cached.read.sessionId] = entry.mtimeMs
194  }
195  for (const name of sharedFiles.keys()) if (!listed.has(name)) sharedFiles.delete(name)
196  return { summaries, mtimes }
197}
198
199async function selfIdOf($: Dollar): Promise<string | null> {
200  try {
201    return await $.session.id()
202  } catch {
203    return null
204  }
205}
206
207// Shared summaries and the peer list merged into session groups; a session that shares is drawn as shared,
208// once. The peer figures are then groups too, so they are not also sent as agents.
209async function pollShared($: Dollar): Promise<void> {
210  const now = await $.clock.now()
211  const peers = sessionsFolder ? await readPeers($).catch((): Peer[] => []) : []
212  const { summaries, mtimes } = await readShared($)
213  const sessions = mergeSessions({ summaries, peers, selfId: await selfIdOf($), now, mtimes })
214  await applySignals($, [{ type: 'sessions', sessions, at: now }])
215}
216
217async function pollSessions($: Dollar): Promise<void> {
218  if (!(await paneState($)).paneOpen) return stopSessions()
219  try {
220    if (sharedFolder) await pollShared($)
221    else await pollPeers($)
222    await syncClock($)
223  } catch {
224    // The folder is missing or unreadable: no other sessions are shown.
225  }
226}
227
228function stopSessions(): void {
229  sessionTimer?.cancel()
230  sessionTimer = null
231}
232
233async function startSessions($: Dollar): Promise<void> {
234  if ((!sharedFolder && !sessionsFolder) || sessionTimer) return
235  sessionTimer = $.clock.every(sharedFolder ? SHARED_POLL_MS : PEER_POLL_MS, () => {
236    void pollSessions($).catch(() => {})
237  })
238  await pollSessions($)
239}
240
241// Own summary (spec 002). Written only while the shared folder is set. buildSummary is the only content;
242// the content is compared without its time, and shouldWrite decides when a change or a heartbeat goes out.
243const SHARE_TICK_MS = 250
244const LAST_FOLDER_KEY = 'lastSharedFolder'
245let lastWrittenKey: string | null = null
246let lastWriteAt = Number.NEGATIVE_INFINITY
247let lastHeartbeatAt = Number.NEGATIVE_INFINITY
248// Set when the session ends: the clock may still tick after it, and nothing may follow the ended marker.
249let sharingEnded = false
250
251// The session's id, folder and name. The API has no session name: the name is the folder's last
252// segment, or the first 8 characters of the id when the folder is empty.
253async function ownSession($: Dollar): Promise<{ id: string; name: string; folder: string }> {
254  const id = await $.session.id()
255  const folder = await $.session.cwd()
256  const last = folder.split('/').filter(Boolean).pop() ?? ''
257  return { id, name: last || id.slice(0, 8), folder }
258}
259
260async function shareState($: Dollar): Promise<void> {
261  if (!sharedFolder || sharingEnded) return
262  const now = await $.clock.now()
263  const colony = await read($, colonyAtom)
264  const session = await ownSession($)
265  const summary = buildSummary(colony, session, now)
266  const key = JSON.stringify({ ...summary, updatedAt: 0 })
267  const due = shouldWrite({
268    changed: key !== lastWrittenKey,
269    lastWriteAt,
270    now,
271    lastHeartbeatAt,
272  })
273  if (!due) return
274  // Stamped before the write, so a failing write is not retried on every tick.
275  lastWriteAt = now
276  lastHeartbeatAt = now
277  await $.fs.write(summaryPath(sharedFolder, session.id), JSON.stringify(summary))
278  lastWrittenKey = key
279}
280
281function startSharing($: Dollar): void {
282  if (!sharedFolder || shareTimer) return
283  // A trailing change is written by the next tick once the interval has passed; heartbeats ride the same tick.
284  shareTimer = $.clock.every(SHARE_TICK_MS, () => {
285    void shareState($).catch(() => {})
286  })
287}
288
289function stopSharing(): void {
290  shareTimer?.cancel()
291  shareTimer = null
292}
293
294// The ended marker for the session: no name, no folder, no agents.
295async function writeEnded($: Dollar, folder: string): Promise<void> {
296  const id = await $.session.id()
297  const now = await $.clock.now()
298  await $.fs.write(summaryPath(folder, id), JSON.stringify(endedSummary({ id }, now)))
299}
300
301// Sharing is off but this session shared before (the option was cleared and the mod reloaded): mark its
302// summary ended in the folder it last used, then forget that folder.
303async function endLeftoverShare($: Dollar): Promise<void> {
304  if (sharedFolder) return
305  const last = await $.store.get(LAST_FOLDER_KEY)
306  if (typeof last !== 'string' || last === '') return
307  await writeEnded($, last)
308  await $.store.delete(LAST_FOLDER_KEY)
309}
310
311async function showPane($: Dollar): Promise<void> {
312  await reconcileAgents($)
313  await $.ui.open({ id: PANE, title: PANE_TITLE })
314  await startSessions($)
315  await refreshPane($)
316}
317
318// Auto-open the first time a subagent appears or an agent needs the user (FR-001).
319async function autoOpen($: Dollar): Promise<void> {
320  if (firstAutoDone) return
321  const colony = await read($, colonyAtom)
322  const attention = attentionOf(colony)
323  // Nothing to show: no engine calls on the hot path (every tool call passes through here).
324  if (attention === 0) return
325  const { paneOpen } = await paneState($)
326  const hidden = Boolean(await $.store.get(HIDDEN_KEY))
327  if (!shouldAutoOpen({ attention, hidden, paneOpen, firstAutoDone })) return
328  firstAutoDone = true
329  await showPane($)
330}
331
332// Apply one event's signals, then settle the clock and the pane.
333async function fold($: Dollar, eventName: string, e: Record<string, unknown>): Promise<void> {
334  const colony = await read($, colonyAtom)
335  const at = await $.clock.now()
336  // A reaction flash is motion, so reduced motion skips it (the figure goes straight to in-progress).
337  const signals = toSignals(eventName, e, contextFor(colony, recentAgentId, at, reducedMotion ? 0 : REACT_MS))
338  recentAgentId = nextRecentAgent(recentAgentId, eventName, e)
339  await applySignals($, signals)
340  // Reduced motion never runs the clock, so retention expiry and easing ride on events instead.
341  if (reducedMotion) await applySignals($, [{ type: 'tick', at }])
342  await autoOpen($)
343  await syncClock($)
344  await refreshPane($)
345}
346
347// Observer hooks (FR-016): fold the event into the colony, then pass it on unchanged, even when
348// folding fails. Each hook runs its task through guarded() (src/observe.ts, the body of observe()).
349// The engine follows $ only into functions declared in this file, so $ stays inside these hooks.
350const foldEvent = (eventName: string, $: Dollar, e: unknown) =>
351  fold($, eventName, e as Record<string, unknown>)
352
353// The engine's list row for a subagent, if it has one yet.
354async function listedRow($: Dollar, id: unknown): Promise<ListedAgent | undefined> {
355  return (await listAgents($)).find(row => row.id === id)
356}
357
358// The effective folders, computed once per session start: the shared folder (<config dir>/colony) and the
359// sessions folder (<config dir>/sessions), each unless its override is set. A failed environment read counts
360// as unset, so the default path is never guessed.
361async function resolveFolders($: Dollar): Promise<{ shared: string; sessions: string }> {
362  const configDir = (await $.env.get('CLAUDE_CONFIG_DIR').catch(() => undefined)) ?? ''
363  const home = (await $.env.get('HOME').catch(() => undefined)) ?? ''
364  return {
365    shared: sharedFolderFor({ shareSessions, sharedFolder: sharedFolderOption, configDir, home }),
366    sessions: sessionsFolderFor({ shareSessions, sessionsDirectory: sessionsDirectoryOption, configDir, home }),
367  }
368}
369
370async function sessionStart($: Dollar, e: unknown): Promise<void> {
371  await $.command.register({
372    name: 'colony',
373    description: 'Show or hide the agent colony pane',
374  })
375  await update($, colonyAtom, c => ({ ...c, retentionMs }))
376  const folders = await resolveFolders($)
377  sharedFolder = folders.shared
378  sessionsFolder = folders.sessions
379  await endLeftoverShare($)
380  if (sharedFolder) {
381    sharingEnded = false
382    await $.store.set(LAST_FOLDER_KEY, sharedFolder)
383    startSharing($)
384  }
385  await fold($, 'session.start', e as Record<string, unknown>)
386  await reconcileAgents($)
387  // The pane opens on the first pending or first subagent (FR-001), or when the person runs /colony.
388}
389
390// The session ends: its summary is marked ended in the shared folder, or in the folder it last shared to
391// when sharing is off now (FR-003, spec edge case).
392async function sessionEnd($: Dollar): Promise<void> {
393  stopSharing()
394  sharingEnded = true
395  if (sharedFolder) await writeEnded($, sharedFolder)
396  else await endLeftoverShare($)
397}
398
399async function turnComplete($: Dollar, e: unknown): Promise<void> {
400  await foldEvent('turn.complete', $, e)
401  await reconcileAgents($)
402}
403
404// agent.spawn answers the new agent's id only after the spawn, so the id comes from the result.
405async function spawnSeen($: Dollar, e: unknown, out: unknown): Promise<void> {
406  const agentId = (out as { agentId?: unknown } | undefined)?.agentId
407  if (typeof agentId !== 'string') return
408  await fold($, 'agent.spawn', { ...(e as Record<string, unknown>), agentId })
409}
410
411// SubagentStart and SubagentStop carry no parent or status: the engine's list supplies them.
412async function subagentStart($: Dollar, e: unknown): Promise<void> {
413  const payload = e as Record<string, unknown>
414  const row = await listedRow($, payload.agent_id)
415  await fold($, 'classic.SubagentStart', {
416    ...payload,
417    parentId: row?.parentId,
418    description: row?.description ?? payload.description,
419  })
420}
421
422async function subagentStop($: Dollar, e: unknown): Promise<void> {
423  const payload = e as Record<string, unknown>
424  const row = await listedRow($, payload.agent_id)
425  await fold($, 'classic.SubagentStop', {
426    ...payload,
427    parentId: row?.parentId,
428    status: row?.status,
429  })
430}
431
432// Messages in an agent's transcript when its context was last estimated; throttles the estimate.
433const estimatedAt = new Map<string, number>()
434const ESTIMATE_EVERY = 4
435
436// A model request is about to go out. Count it for its agent, and now and then estimate that agent's
437// context from its transcript. Light on purpose: no pane or status work, this fires on every step.
438async function stepSeen($: Dollar, e: Record<string, unknown>): Promise<void> {
439  const at = await $.clock.now()
440  const colony = await read($, colonyAtom)
441  await applySignals($, toSignals('turn.step', e, contextFor(colony, recentAgentId, at)))
442  const id = typeof e.agentId === 'string' && e.agentId ? e.agentId : 'main'
443  const count = typeof e.messageCount === 'number' ? e.messageCount : 0
444  if (count - (estimatedAt.get(id) ?? -ESTIMATE_EVERY) < ESTIMATE_EVERY) return
445  estimatedAt.set(id, count)
446  try {
447    const args = id === 'main' ? { as: 'api' as const } : { agentId: id, as: 'api' as const }
448    const messages = await $.session.messages(args as never)
449    if (!Array.isArray(messages)) return
450    await applySignals($, [
451      { type: 'agent-meta', id, contextTokens: estimateContextTokens(messages), at },
452    ])
453  } catch {
454    // The transcript can be unreadable (a finished agent, another process): the estimate just waits.
455  }
456}
457
458async function uiClosed($: Dollar, e: unknown): Promise<void> {
459  // Closing the pane with the person's own mark or key counts as hiding it (FR-001).
460  const close = e as { id: string; origin: { kind: string } }
461  if (close.id === PANE) stopSessions()
462  if (close.id === PANE && close.origin.kind === 'person') await $.store.set(HIDDEN_KEY, true)
463}
464
465export const register: Register = (on, options) => {
466  const parsed = readOptions(options as Readonly<Record<string, unknown>>)
467  reducedMotion = parsed.reducedMotion
468  retentionMs = parsed.retentionMs
469  sessionsDirectoryOption = parsed.sessionsDirectory
470  shareSessions = parsed.shareSessions
471  sharedFolderOption = parsed.sharedFolder
472  sharedFolder = ''
473  sessionsFolder = ''
474
475  on('session.start', ($, e, next) => guarded(() => sessionStart($, e), () => next(e)))
476
477  on('command.run', { command: 'colony' }, async $ => {
478    const paneOpen = (await $.ui.panes()).some(p => p.id === PANE)
479    if (paneOpen) {
480      await $.store.set(HIDDEN_KEY, true)
481      await $.ui.close({ id: PANE })
482      return { text: 'Colony pane hidden.' }
483    }
484    await $.store.set(HIDDEN_KEY, false)
485    await showPane($)
486    return { text: 'Colony pane shown.' }
487  })
488
489  on('ui.close', ($, e, next) => guarded(() => uiClosed($, e), () => next(e)))
490  on('session.end', ($, e, next) => guarded(() => sessionEnd($), () => next(e)))
491
492  on('turn.start', ($, e, next) => guarded(() => foldEvent('turn.start', $, e), () => next(e)))
493  on('turn.complete', ($, e, next) => guarded(() => turnComplete($, e), () => next(e)))
494  // Streaming event: observe the request, then pass the stream through untouched.
495  on('turn.step', async function* ($, e, next) {
496    await guarded(() => stepSeen($, e as unknown as Record<string, unknown>), () => undefined)
497    return yield* next(e)
498  })
499  on('tool.call', ($, e, next) => guarded(() => foldEvent('tool.call', $, e), () => next(e)))
500  on('classic.PermissionRequest', ($, e, next) => guarded(() => foldEvent('classic.PermissionRequest', $, e), () => next(e)))
501  on('classic.Elicitation', ($, e, next) => guarded(() => foldEvent('classic.Elicitation', $, e), () => next(e)))
502  on('classic.ElicitationResult', ($, e, next) => guarded(() => foldEvent('classic.ElicitationResult', $, e), () => next(e)))
503  on('classic.Notification', ($, e, next) => guarded(() => foldEvent('classic.Notification', $, e), () => next(e)))
504  on('prompt.submit', ($, e, next) => guarded(() => foldEvent('prompt.submit', $, e), () => next(e)))
505
506  on('agent.spawn', async ($, e, next) => {
507    const out = await next(e)
508    await guarded(() => spawnSeen($, e, out), () => out)
509    return out
510  })
511  on('classic.SubagentStart', ($, e, next) => guarded(() => subagentStart($, e), () => next(e)))
512  on('classic.SubagentStop', ($, e, next) => guarded(() => subagentStop($, e), () => next(e)))
513  on('classic.TeammateIdle', ($, e, next) => guarded(() => foldEvent('classic.TeammateIdle', $, e), () => next(e)))
514  on('session.send', ($, e, next) => guarded(() => foldEvent('session.send', $, e), () => next(e)))
515  on('session.receive', ($, e, next) => guarded(() => foldEvent('session.receive', $, e), () => next(e)))
516
517  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
518    const { Box, Text } = $.ui.resolve(e)
519    const colony = await read($, colonyAtom)
520    const viewport = { rows: e.viewport?.rows ?? 24, columns: e.viewport?.columns ?? 80 }
521    const scene = layout(colony, viewport, reducedMotion ? 0 : colony.tick)
522    return renderPane(scene, { Box, Text })
523  })
524}
525
src/model.ts 541 lines
1import type { Agent, AgentState, Colony, Exchange, SessionGroup, Usage } from '../types'
2import { resolveState } from './priority'
3
4export const MAIN_ID = 'main'
5// Ids of figures that stand for another session (not an agent of this one) start with this.
6export const PEER_PREFIX = 'session:'
7// How long a spawn / message / result burst keeps its exchange alive (ms).
8export const BURST_MS = 1500
9// Silence after which a working agent with no list status becomes unknown (ms).
10export const SILENCE_MS = 60_000
11// How long main keeps its completed look before it returns to idle (ms).
12export const MAIN_DONE_MS = 5_000
13// Largest proximity shift (columns) an exchange pulls two figures together by (FR-008).
14export const MAX_SHIFT = 2
15// How long a listening figure shows its reaction after an inbound event (ms, FR-011).
16export const REACT_MS = 1000
17// Furthest a working figure drifts from its home cell (columns), and how fast (columns per tick).
18export const WANDER_MAX = 2
19export const WANDER_STEP = 0.25
20
21export type Peer = { id: string; label: string; state: AgentState; note: string }
22
23export type ExchangeReason = Exchange['reasons'][number]
24
25export type Signal =
26  | { type: 'agent-added'; id: string; label: string; parentId: string | null; at: number }
27  | { type: 'agent-state'; id: string; state: AgentState; listenSource?: string | null; at: number }
28  | {
29      type: 'agent-ended'
30      id: string
31      state: 'completed' | 'failed' | 'cancelled'
32      at: number
33    }
34  // An inbound event reaches a figure: a reaction flash, then in-progress (flashMs 0 skips the flash).
35  | { type: 'agent-react'; id: string; source: string; flashMs: number; at: number }
36  | {
37      type: 'exchange-open'
38      fromId: string
39      toId: string
40      reason: ExchangeReason
41      at: number
42    }
43  | {
44      type: 'exchange-close'
45      fromId: string
46      toId: string
47      reason: ExchangeReason
48      at: number
49    }
50  // Facts about an agent that arrive apart from its state: model, origin, context estimate.
51  | {
52      type: 'agent-meta'
53      id: string
54      at: number
55      model?: string
56      addressable?: boolean
57      independent?: boolean
58      spawnedBy?: string | null
59      contextTokens?: number
60    }
61  // A finished turn's token counts, added to the agent's total; its run of steps starts over.
62  | { type: 'agent-usage'; id: string; usage: Usage; at: number }
63  // One more model request in the agent's current run.
64  | { type: 'agent-step'; id: string; model?: string; at: number }
65  // The other sessions on this machine, as the pane last read them; replaces the figures for them.
66  | { type: 'peers'; peers: Peer[]; at: number }
67  // The other sessions as the shared folder and the peer list last showed them; replaces them all.
68  | { type: 'sessions'; sessions: Record<string, SessionGroup>; at: number }
69  | { type: 'tick'; at: number }
70  | {
71      type: 'reconcile'
72      at: number
73      listed: Array<{ id: string; label: string; parentId: string | null; state: AgentState }>
74    }
75
76export const TERMINAL_STATES: ReadonlyArray<AgentState> = ['completed', 'failed', 'cancelled']
77const WORKING_STATES: ReadonlyArray<AgentState> = ['in-progress', 'pending', 'listening']
78const BURST_REASONS: ReadonlyArray<ExchangeReason> = ['spawn', 'message', 'result']
79
80export function initialColony(retentionMs: number): Colony {
81  return { agents: {}, exchanges: {}, tick: 0, retentionMs, sessions: {} }
82}
83
84export function exchangeId(fromId: string, toId: string): string {
85  return `${fromId}>${toId}`
86}
87
88// An agent no list names (an engine fork such as compaction or memory, or a workflow's agent) is
89// known only by its id; the prefix tells it from a subagent.
90function unlistedLabel(id: string): string {
91  return `bg ${id}`
92}
93
94function newBackgroundAgent(id: string, at: number): Agent {
95  return { ...newAgent(id, unlistedLabel(id), null, at), background: true }
96}
97
98function newAgent(id: string, label: string, parentId: string | null, at: number): Agent {
99  return {
100    id,
101    label,
102    parentId,
103    state: 'idle',
104    listenSource: null,
105    reactUntil: null,
106    startedAt: at,
107    endedAt: null,
108    lastEventAt: at,
109    listed: false,
110    shift: 0,
111    model: null,
112    usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
113    steps: 0,
114    contextTokens: null,
115    wander: 0,
116    wanderTarget: 0,
117    addressable: false,
118    independent: false,
119    background: false,
120    spawnedBy: null,
121    note: null,
122  }
123}
124
125export function isPeer(agent: Pick<Agent, 'id'>): boolean {
126  return agent.id.startsWith(PEER_PREFIX)
127}
128
129function isFinishedSubagent(agent: Agent): boolean {
130  return agent.id !== MAIN_ID && TERMINAL_STATES.includes(agent.state)
131}
132
133function setAgents(colony: Colony, agents: Record<string, Agent>): Colony {
134  return { ...colony, agents }
135}
136
137// The state a figure is drawn in (FR-013): a reaction flash outranks the stored state, and a listening
138// registration shows only while the agent is otherwise at rest (FR-010: an idle agent); pending outranks both.
139const AT_REST: ReadonlyArray<AgentState> = ['idle', 'completed', 'unknown']
140export function shownStateOf(agent: Agent): AgentState {
141  if (agent.reactUntil !== null) return resolveState([agent.state, 'listening'])
142  if (agent.listenSource !== null && AT_REST.includes(agent.state)) return 'listening'
143  return agent.state
144}
145
146// Silent working agents become unknown (FR-018). Terminal and idle agents are not "working".
147// The main agent is never judged by silence (a long tool call is not unknown), and an agent the
148// engine's list named at the last reconcile is trusted to that status instead of silence.
149function markSilent(agents: Record<string, Agent>, at: number): Record<string, Agent> {
150  let out = agents
151  for (const agent of Object.values(agents)) {
152    if (agent.id === MAIN_ID || agent.listed || isPeer(agent)) continue
153    if (WORKING_STATES.includes(agent.state) && at - agent.lastEventAt >= SILENCE_MS) {
154      if (out === agents) out = { ...agents }
155      out[agent.id] = { ...agent, state: 'unknown' }
156    }
157  }
158  return out
159}
160
161// Burst reasons (spawn, message, result) last only while their burst animates.
162function pruneBursts(
163  reasons: ExchangeReason[],
164  burstUntil: number,
165  at: number,
166): ExchangeReason[] {
167  if (burstUntil > at) return reasons
168  return reasons.filter(r => !BURST_REASONS.includes(r))
169}
170
171function dropDanglingExchanges(
172  exchanges: Record<string, Exchange>,
173  agents: Record<string, Agent>,
174): Record<string, Exchange> {
175  const out: Record<string, Exchange> = {}
176  for (const [key, ex] of Object.entries(exchanges)) {
177    if (agents[ex.fromId] && agents[ex.toId]) out[key] = ex
178  }
179  return out
180}
181
182// Target proximity shift for one agent (0, 1 or 2 columns), from the exchanges it is in.
183// A live burst pulls it two columns, a plain wait one, nothing none.
184function targetShiftOf(agentId: string, exchanges: Record<string, Exchange>): number {
185  let target = 0
186  for (const ex of Object.values(exchanges)) {
187    if (ex.fromId !== agentId && ex.toId !== agentId) continue
188    if (ex.reasons.length === 0) continue
189    const bursting = ex.reasons.some(r => BURST_REASONS.includes(r))
190    target = Math.max(target, bursting ? MAX_SHIFT : 1)
191  }
192  return target
193}
194
195// Each figure moves one column toward its target per tick, so the pull eases in and back out.
196function easeShifts(agents: Record<string, Agent>, exchanges: Record<string, Exchange>): Record<string, Agent> {
197  let out = agents
198  for (const agent of Object.values(agents)) {
199    const target = targetShiftOf(agent.id, exchanges)
200    const shift = agent.shift < target ? agent.shift + 1 : agent.shift > target ? agent.shift - 1 : agent.shift
201    if (shift === agent.shift) continue
202    if (out === agents) out = { ...agents }
203    out[agent.id] = { ...agent, shift }
204  }
205  return out
206}
207
208// A small stable hash, so wandering is deterministic and the reducer stays pure.
209function hashOf(text: string, n: number): number {
210  let h = 2166136261 ^ n
211  for (let i = 0; i < text.length; i++) h = Math.imul(h ^ text.charCodeAt(i), 16777619)
212  return (h >>> 0) % 1000
213}
214
215const WANDERS: ReadonlyArray<AgentState> = ['in-progress', 'listening']
216
217// Working figures drift to a new spot every so often; resting ones, and any in an exchange, drift home.
218function wanderAgents(
219  agents: Record<string, Agent>,
220  exchanges: Record<string, Exchange>,
221  tick: number,
222): Record<string, Agent> {
223  let out = agents
224  for (const agent of Object.values(agents)) {
225    if (agent.id === MAIN_ID) continue
226    const talking = targetShiftOf(agent.id, exchanges) > 0
227    const roams = WANDERS.includes(shownStateOf(agent)) && !talking
228    let target = agent.wanderTarget
229    if (!roams) target = 0
230    else if ((tick + hashOf(agent.id, 0)) % 16 === 0) {
231      target = (hashOf(agent.id, tick) % (2 * WANDER_MAX + 1)) - WANDER_MAX
232    }
233    const gap = target - agent.wander
234    const wander = Math.abs(gap) <= WANDER_STEP ? target : agent.wander + Math.sign(gap) * WANDER_STEP
235    if (wander === agent.wander && target === agent.wanderTarget) continue
236    if (out === agents) out = { ...agents }
237    out[agent.id] = { ...agent, wander, wanderTarget: target }
238  }
239  return out
240}
241
242function isEasing(ex: Exchange, agents: Record<string, Agent>): boolean {
243  return (agents[ex.fromId]?.shift ?? 0) > 0 || (agents[ex.toId]?.shift ?? 0) > 0
244}
245
246export function reduce(colony: Colony, signal: Signal): Colony {
247  switch (signal.type) {
248    case 'agent-added': {
249      const existing = colony.agents[signal.id]
250      if (existing) {
251        // Idempotent: a repeat add refreshes the label only.
252        return setAgents(colony, {
253          ...colony.agents,
254          [signal.id]: {
255            ...existing,
256            label: signal.label,
257            parentId: signal.parentId ?? existing.parentId,
258            lastEventAt: signal.at,
259          },
260        })
261      }
262      return setAgents(colony, {
263        ...colony.agents,
264        [signal.id]: newAgent(signal.id, signal.label, signal.parentId, signal.at),
265      })
266    }
267
268    case 'agent-state': {
269      const known = colony.agents[signal.id]
270      // A finished subagent stays finished: a late event must not revive it (it would linger as a ghost).
271      if (known && isFinishedSubagent(known) && signal.state !== 'listening') return colony
272      const existing = known ?? newBackgroundAgent(signal.id, signal.at)
273      // A listening registration is an overlay: it sets the source and leaves the stored state alone.
274      if (signal.state === 'listening') {
275        const registered: Agent = {
276          ...existing,
277          listenSource: signal.listenSource ?? 'external',
278          lastEventAt: signal.at,
279        }
280        return setAgents(colony, { ...colony.agents, [signal.id]: registered })
281      }
282      const next: Agent = {
283        ...existing,
284        state: signal.state,
285        // Re-entering a live state clears the end marker; the retention timer restarts on the next end.
286        endedAt: TERMINAL_STATES.includes(signal.state) ? (existing.endedAt ?? signal.at) : null,
287        lastEventAt: signal.at,
288      }
289      return setAgents(colony, { ...colony.agents, [signal.id]: next })
290    }
291
292    case 'agent-react': {
293      const existing = colony.agents[signal.id]
294      // Pending outranks listening (FR-013): an agent waiting on the user does not react.
295      if (existing?.state === 'pending') return colony
296      if (existing && isFinishedSubagent(existing)) return colony
297      const agent = existing ?? newBackgroundAgent(signal.id, signal.at)
298      return setAgents(colony, {
299        ...colony.agents,
300        [signal.id]: {
301          ...agent,
302          listenSource: signal.source,
303          reactUntil: signal.at + signal.flashMs,
304          endedAt: null,
305          lastEventAt: signal.at,
306        },
307      })
308    }
309
310    case 'agent-ended': {
311      const existing =
312        colony.agents[signal.id] ?? newBackgroundAgent(signal.id, signal.at)
313      return setAgents(colony, {
314        ...colony.agents,
315        [signal.id]: {
316          ...existing,
317          // A reusable agent that finishes a task rests; it is not removed.
318          state: existing.addressable && signal.state === 'completed' ? 'idle' : signal.state,
319          listenSource: null,
320          reactUntil: null,
321          // A repeat stop keeps the first end time, so it cannot extend retention.
322          endedAt:
323            existing.addressable && signal.state === 'completed'
324              ? null
325              : isFinishedSubagent(existing)
326                ? (existing.endedAt ?? signal.at)
327                : signal.at,
328          lastEventAt: signal.at,
329        },
330      })
331    }
332
333    case 'agent-meta': {
334      const existing = colony.agents[signal.id]
335      if (!existing) return colony
336      return setAgents(colony, {
337        ...colony.agents,
338        [signal.id]: {
339          ...existing,
340          model: signal.model ?? existing.model,
341          addressable: signal.addressable ?? existing.addressable,
342          independent: signal.independent ?? existing.independent,
343          spawnedBy: signal.spawnedBy === undefined ? existing.spawnedBy : signal.spawnedBy,
344          contextTokens: signal.contextTokens ?? existing.contextTokens,
345        },
346      })
347    }
348
349    case 'agent-usage': {
350      const existing = colony.agents[signal.id]
351      if (!existing) return colony
352      const u = existing.usage
353      return setAgents(colony, {
354        ...colony.agents,
355        [signal.id]: {
356          ...existing,
357          usage: {
358            input: u.input + signal.usage.input,
359            output: u.output + signal.usage.output,
360            cacheRead: u.cacheRead + signal.usage.cacheRead,
361            cacheWrite: u.cacheWrite + signal.usage.cacheWrite,
362          },
363          // One step is the exact window (input side of the last response); more is an estimate the
364          // caller supplies through agent-meta, so only the single-step case is settled here.
365          contextTokens:
366            existing.steps <= 1
367              ? signal.usage.input + signal.usage.cacheRead + signal.usage.cacheWrite + signal.usage.output
368              : existing.contextTokens,
369          steps: 0,
370        },
371      })
372    }
373
374    case 'agent-step': {
375      const existing = colony.agents[signal.id]
376      if (!existing) return colony
377      return setAgents(colony, {
378        ...colony.agents,
379        [signal.id]: { ...existing, steps: existing.steps + 1, model: signal.model ?? existing.model },
380      })
381    }
382
383    case 'peers': {
384      const agents: Record<string, Agent> = {}
385      for (const [id, agent] of Object.entries(colony.agents)) if (!isPeer(agent)) agents[id] = agent
386      for (const peer of signal.peers) {
387        const existing = colony.agents[peer.id] ?? newAgent(peer.id, peer.label, null, signal.at)
388        agents[peer.id] = {
389          ...existing,
390          label: peer.label,
391          state: peer.state,
392          independent: true,
393          note: peer.note,
394          lastEventAt: signal.at,
395        }
396      }
397      return setAgents(colony, agents)
398    }
399
400    case 'sessions':
401      return { ...colony, sessions: signal.sessions }
402
403    case 'exchange-open': {
404      const id = exchangeId(signal.fromId, signal.toId)
405      const existing = colony.exchanges[id]
406      const reasons = new Set(existing?.reasons ?? [])
407      reasons.add(signal.reason)
408      const isBurst = BURST_REASONS.includes(signal.reason)
409      const burstUntil = isBurst
410        ? Math.max(existing?.burstUntil ?? 0, signal.at + BURST_MS)
411        : (existing?.burstUntil ?? 0)
412      // A message to a finished subagent resumes it (a reusable agent), unlike a stray late event.
413      const target = colony.agents[signal.toId]
414      const agents =
415        signal.reason === 'message' && target && isFinishedSubagent(target)
416          ? { ...colony.agents, [target.id]: { ...target, state: 'in-progress' as const, endedAt: null, lastEventAt: signal.at } }
417          : colony.agents
418      return {
419        ...colony,
420        agents,
421        exchanges: {
422          ...colony.exchanges,
423          [id]: {
424            id,
425            fromId: signal.fromId,
426            toId: signal.toId,
427            reasons: [...reasons],
428            burstUntil,
429          },
430        },
431      }
432    }
433
434    case 'exchange-close': {
435      const id = exchangeId(signal.fromId, signal.toId)
436      const existing = colony.exchanges[id]
437      if (!existing) return colony
438      const reasons = pruneBursts(
439        existing.reasons.filter(r => r !== signal.reason),
440        existing.burstUntil,
441        signal.at,
442      )
443      // Dropped only once no reason is left and both figures are back at rest (easing finishes first).
444      if (reasons.length === 0 && !isEasing(existing, colony.agents)) {
445        const { [id]: _removed, ...rest } = colony.exchanges
446        return { ...colony, exchanges: rest }
447      }
448      return {
449        ...colony,
450        exchanges: { ...colony.exchanges, [id]: { ...existing, reasons } },
451      }
452    }
453
454    case 'tick': {
455      // A reaction flash that has run its course ends the listening: the agent goes to in-progress.
456      let agents: Record<string, Agent> = colony.agents
457      for (const agent of Object.values(colony.agents)) {
458        if (agent.reactUntil === null || signal.at < agent.reactUntil) continue
459        if (agents === colony.agents) agents = { ...colony.agents }
460        agents[agent.id] = {
461          ...agent,
462          state: agent.state === 'pending' ? 'pending' : 'in-progress',
463          listenSource: null,
464          reactUntil: null,
465        }
466      }
467      agents = markSilent(agents, signal.at)
468      // Main's completed look fades back to idle after MAIN_DONE_MS (main is never removed).
469      const main = agents[MAIN_ID]
470      if (
471        main &&
472        main.state === 'completed' &&
473        main.endedAt !== null &&
474        signal.at - main.endedAt >= MAIN_DONE_MS
475      ) {
476        agents = { ...agents, [MAIN_ID]: { ...main, state: 'idle', endedAt: null } }
477      }
478      for (const agent of Object.values(agents)) {
479        // FR-015: every terminal subagent (completed, failed, cancelled) is removed; main never is.
480        const expired =
481          agent.id !== MAIN_ID &&
482          !isPeer(agent) &&
483          !agent.addressable &&
484          TERMINAL_STATES.includes(agent.state) &&
485          agent.endedAt !== null &&
486          signal.at - agent.endedAt >= colony.retentionMs
487        if (expired) {
488          if (agents === colony.agents) agents = { ...colony.agents }
489          delete agents[agent.id]
490        }
491      }
492      let exchanges: Record<string, Exchange> = {}
493      for (const [key, ex] of Object.entries(colony.exchanges)) {
494        const reasons = pruneBursts(ex.reasons, ex.burstUntil, signal.at)
495        exchanges[key] = reasons.length === ex.reasons.length ? ex : { ...ex, reasons }
496      }
497      exchanges = dropDanglingExchanges(exchanges, agents)
498      agents = easeShifts(agents, exchanges)
499      agents = wanderAgents(agents, exchanges, colony.tick)
500      // An exchange with no reason left is kept only while its figures are still easing back.
501      for (const [key, ex] of Object.entries(exchanges)) {
502        if (ex.reasons.length === 0 && !isEasing(ex, agents)) {
503          if (exchanges === colony.exchanges) exchanges = { ...colony.exchanges }
504          delete exchanges[key]
505        }
506      }
507      return { ...colony, agents, exchanges, tick: colony.tick + 1 }
508    }
509
510    case 'reconcile': {
511      // The engine's list status wins over inferred state (contracts/event-mapping.md).
512      const agents: Record<string, Agent> = { ...colony.agents }
513      const listedIds = new Set<string>()
514      for (const item of signal.listed) {
515        listedIds.add(item.id)
516        const existing = agents[item.id] ?? newAgent(item.id, item.label, item.parentId, signal.at)
517        const state = existing.addressable && item.state === 'completed' ? 'idle' : item.state
518        agents[item.id] = {
519          ...existing,
520          label: item.label,
521          parentId: item.parentId,
522          state,
523          listed: true,
524          background: false,
525          listenSource: existing.listenSource,
526          endedAt: TERMINAL_STATES.includes(state) ? (existing.endedAt ?? signal.at) : null,
527          lastEventAt: signal.at,
528        }
529      }
530      // Agents the list does not name are judged by silence alone.
531      const unlisted: Record<string, Agent> = {}
532      for (const [id, agent] of Object.entries(agents)) {
533        if (!listedIds.has(id)) unlisted[id] = { ...agent, listed: false }
534      }
535      const silent = markSilent(unlisted, signal.at)
536      for (const [id, agent] of Object.entries(silent)) agents[id] = agent
537      return setAgents(colony, agents)
538    }
539  }
540}
541
src/peers.ts 51 lines
1// Other Claude sessions on this machine, read from the folder of session files the person points the
2// mod at (option `sessionsDirectory`). Session-level only: another session's own subagents are not
3// visible from here. Pure parsing; hooks/register.tsx does the reading.
4import { PEER_PREFIX, type Peer } from './model'
5import type { AgentState } from '../types'
6
7// A session file older than this is taken as a session that has gone (nothing says it is alive).
8export const PEER_STALE_MS = 6 * 60 * 60 * 1000
9
10function ago(ms: number): string {
11  const minutes = Math.max(0, Math.round(ms / 60_000))
12  if (minutes < 1) return 'just now'
13  if (minutes < 90) return `${minutes}m ago`
14  return `${Math.round(minutes / 60)}h ago`
15}
16
17function stateOf(status: unknown): AgentState {
18  if (status === 'busy') return 'in-progress'
19  if (status === 'idle') return 'idle'
20  return 'unknown'
21}
22
23// One session file's text -> a peer, or null when it is not a usable record.
24export function parsePeer(text: string, selfId: string | null, now: number): Peer | null {
25  let raw: unknown
26  try {
27    raw = JSON.parse(text)
28  } catch {
29    return null
30  }
31  if (!raw || typeof raw !== 'object') return null
32  const r = raw as Record<string, unknown>
33  // The mod's own shared summaries (spec 002) carry a list of agents; they are never sessions, even when
34  // the sessions folder and the shared folder are the same (spec 004). Session files have no such list.
35  if (Array.isArray(r.agents)) return null
36  const sessionId = typeof r.sessionId === 'string' ? r.sessionId : ''
37  if (!sessionId || sessionId === selfId) return null
38  const updatedAt = typeof r.updatedAt === 'number' ? r.updatedAt : typeof r.startedAt === 'number' ? r.startedAt : 0
39  if (updatedAt === 0 || now - updatedAt > PEER_STALE_MS) return null
40  const cwd = typeof r.cwd === 'string' ? r.cwd : ''
41  const folder = cwd.split('/').filter(Boolean).pop() ?? ''
42  const name = typeof r.name === 'string' && r.name ? r.name : folder || sessionId.slice(0, 8)
43  const where = cwd ? ` in ${cwd}` : ''
44  return {
45    id: `${PEER_PREFIX}${sessionId}`,
46    label: name,
47    state: stateOf(r.status),
48    note: `another session${where}, updated ${ago(now - updatedAt)}`,
49  }
50}
51
src/observe.ts 26 lines
1// Observer wrapper (FR-016): the mod never changes what a hook passes on.
2// The task may update colony state; whatever it does, the hook returns passOn() unchanged.
3
4export type Passthrough<D, E, R> = (dollar: D, e: E, next: (e: E) => R | Promise<R>) => Promise<R>
5
6// Runs the observer task, swallowing any error, then answers with passOn() (normally next(e)).
7export async function guarded<R>(
8  task: () => unknown,
9  passOn: () => R | Promise<R>,
10  onError: (error: unknown) => void = () => {},
11): Promise<R> {
12  try {
13    await task()
14  } catch (error) {
15    onError(error)
16  }
17  return passOn()
18}
19
20export function observe<D, E, R>(
21  handler: (dollar: D, e: E) => unknown,
22  onError: (error: unknown) => void = () => {},
23): Passthrough<D, E, R> {
24  return (dollar, e, next) => guarded(() => handler(dollar, e), () => next(e), onError)
25}
26
src/layout.ts 602 lines
1// Colony + viewport + tick -> Scene (data-model.md). Pure: positions, labels, frames and streams.
2import type { Agent, AgentState, Colony, Exchange, SessionGroup } from '../types'
3import { exchangeId, isPeer, MAIN_ID, MAX_SHIFT, shownStateOf } from './model'
4import { frameOf } from './sprites'
5import { detailsOf, fillOf, pixelsOf, tierOf, type Tier } from './tiers'
6
7// The smallest figure: an 8-column sprite (4 text rows) with one label row beneath it. Bigger models
8// draw bigger (tiers.ts); these are the floor, and the viewport size below which only a summary fits.
9export const FIGURE_WIDTH = 8
10export const FIGURE_HEIGHT = 5
11// Columns between neighbouring cells in a row. Two figures pulled toward each other by MAX_SHIFT and
12// wandering toward each other by WANDER_MAX still keep columns between them (and layout() pushes
13// apart any that would touch).
14export const GAP = 8
15// Below each grid row: 2 stream lanes, then 1 connector row above the next row.
16const LANES = 2
17const CONNECTOR_ROWS = 3
18
19export type Viewport = { rows: number; columns: number }
20
21export type Figure = {
22  agentId: string
23  x: number
24  y: number
25  state: AgentState
26  // The frame to draw this tick: pixel rows of '#' and '.'.
27  grid: string[]
28  // Label, truncated with an ellipsis to the figure width.
29  label: string
30  isMain: boolean
31  // Size: the sprite's width in columns, and its height in rows with the label row.
32  width: number
33  height: number
34  tier: Tier | null
35  // How full its context window is (0..1), or null when unknown. Drawn as a darker fill from the feet.
36  fill: number | null
37  // A fork or workflow agent no list names: drawn muted so active agents stand out.
38  background: boolean
39  // The full, untruncated title, and the lines of its hover card.
40  title: string
41  details: string[]
42  // A figure of a stale session group: drawn dimmed and frozen (spec 002).
43  stale: boolean
44}
45
46// A run of text on a row of the pane, in one style (group headers, the `+N done` line of a group).
47export type Segment = { text: string; color?: string; dim?: boolean }
48export type Line = { row: number; segments: Segment[] }
49
50// One other session's group as the pane drew it: its header row, and whether its agents are shown.
51export type GroupView = {
52  sessionId: string
53  name: string
54  row: number
55  expanded: boolean
56  source: SessionGroup['source']
57  freshness: SessionGroup['freshness']
58  needsAttention: boolean
59  agents: number
60}
61
62// A 0/1 stream between two exchanging figures, on a lane row of its own (never overlapping another).
63export type Stream = {
64  fromId: string
65  toId: string
66  row: number
67  x: number
68  width: number
69}
70
71// One connector glyph, drawn in the gap above a child figure.
72export type Connector = { x: number; y: number }
73
74export type Scene = {
75  figures: Figure[]
76  streams: Stream[]
77  connectors: Connector[]
78  // Agents that did not fit the viewport.
79  hidden: number
80  // Completed agents folded into the `+N done` overflow line.
81  collapsed: number
82  // The row the overflow line sits on, or -1 when nothing collapsed.
83  overflowRow: number
84  // The tick the frames were chosen for; the view draws streams from it.
85  tick: number
86  // True when the colony has no agents at all.
87  empty: boolean
88  // True when the viewport is too small to draw figures; draw `summary` instead.
89  tooSmall: boolean
90  summary: string
91  // The viewport the scene was laid out for.
92  viewport: Viewport
93  // Header rows and `+N done` lines of the session groups (spec 002), drawn as text on their rows.
94  lines: Line[]
95  // The other sessions, in the order drawn (empty when none are shared or known).
96  groups: GroupView[]
97}
98
99export function truncate(text: string, width: number): string {
100  const chars = [...text]
101  if (chars.length <= width) return text
102  if (width <= 0) return ''
103  if (width === 1) return '…'
104  return chars.slice(0, width - 1).join('') + '…'
105}
106
107// A listening figure is labelled with its source tag instead of its name (FR-010): `[github]`.
108export function listenTagOf(source: string | null): string {
109  return truncate(`[${source ?? 'external'}]`, FIGURE_WIDTH)
110}
111
112// The figure's own copy of each agent: the state it is drawn in (FR-013), not the stored one.
113function shownAgents(agents: Record<string, Agent>): Record<string, Agent> {
114  const out: Record<string, Agent> = {}
115  for (const agent of Object.values(agents)) out[agent.id] = { ...agent, state: shownStateOf(agent) }
116  return out
117}
118
119function figureFor(agent: Agent, x: number, y: number, tick: number, px: number, isMain: boolean): Figure {
120  const reacting = agent.state === 'listening' && agent.reactUntil !== null
121  return {
122    agentId: agent.id,
123    x,
124    y,
125    state: agent.state,
126    grid: frameOf(agent.state, tick, reacting, px),
127    label:
128      agent.state === 'listening'
129        ? listenTagOf(agent.listenSource)
130        : truncate(agent.label, px),
131    isMain,
132    stale: false,
133    width: px,
134    height: px / 2 + 1,
135    tier: tierOf(agent.model),
136    fill: fillOf(agent),
137    background: agent.background,
138    title: agent.label,
139    details: detailsOf(agent, agent.state),
140  }
141}
142
143// One short line for the pane, the status line, or a tiny viewport.
144export function summaryOf(agents: Agent[]): string {
145  if (agents.length === 0) return 'colony: no agents'
146  // Other sessions are drawn but not counted: the summary speaks for this session.
147  const shown = agents.filter(a => !isPeer(a)).map(a => shownStateOf(a))
148  const working = shown.filter(s => s === 'in-progress').length
149  const needs = shown.filter(s => s === 'pending').length
150  const parts = [`${working} working`]
151  if (needs > 0) parts.push(`${needs} needs you`)
152  return `colony: ${parts.join(', ')}`
153}
154
155// Subagents in family order: each agent's children follow it, so a family shares a block of the grid.
156// Children whose parent is not in the colony join main's children.
157export function familyOrder(agents: Agent[], root: string = MAIN_ID): Agent[] {
158  const ids = new Set(agents.map(a => a.id))
159  const byParent = new Map<string, Agent[]>()
160  for (const agent of agents) {
161    if (agent.id === root) continue
162    const parent = agent.parentId && ids.has(agent.parentId) ? agent.parentId : root
163    const list = byParent.get(parent) ?? []
164    list.push(agent)
165    byParent.set(parent, list)
166  }
167  const byStart = (a: Agent, b: Agent) =>
168    (a.startedAt ?? 0) - (b.startedAt ?? 0) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)
169  const out: Agent[] = []
170  const visit = (parent: string, seen: Set<string>) => {
171    for (const child of (byParent.get(parent) ?? []).sort(byStart)) {
172      if (seen.has(child.id)) continue
173      seen.add(child.id)
174      out.push(child)
175      visit(child.id, seen)
176    }
177  }
178  const seen = new Set<string>()
179  visit(root, seen)
180  // Agents caught in a parent cycle (or their own parent) are unreachable from main: draw them last.
181  for (const agent of agents.slice().sort(byStart)) {
182    if (agent.id === root || out.includes(agent)) continue
183    out.push(agent)
184    seen.add(agent.id)
185  }
186  return out
187}
188
189// How many grid figures fit in `avail` rows of the viewport, for cells `maxH` rows tall.
190function capacityFor(cols: number, maxH: number, avail: number): number {
191  if (avail < maxH) return 0
192  return cols * (Math.floor((avail - maxH) / (maxH + CONNECTOR_ROWS)) + 1)
193}
194
195function gridColumns(columns: number, maxW: number): number {
196  return Math.max(1, Math.floor((columns + GAP) / (maxW + GAP)))
197}
198
199// Overflow: past capacity, the oldest completed figures fold into the `+N done` line. Pending and
200// running figures are never folded. Returns the figures to lay out and how many were folded.
201function fitOthers(
202  others: Agent[],
203  cols: number,
204  maxH: number,
205  avail: number,
206): { kept: Agent[]; collapsed: number; reserveLine: boolean } {
207  const full = capacityFor(cols, maxH, avail)
208  if (others.length <= full) return { kept: others, collapsed: 0, reserveLine: false }
209  const room = capacityFor(cols, maxH, avail - 1)
210  const excess = others.length - room
211  const completed = others
212    .filter(a => a.state === 'completed')
213    .sort((a, b) => (a.startedAt ?? 0) - (b.startedAt ?? 0) || (a.id < b.id ? -1 : 1))
214  const folded = new Set(completed.slice(0, Math.max(0, excess)).map(a => a.id))
215  const kept = others.filter(a => !folded.has(a.id))
216  if (folded.size === 0) return { kept, collapsed: 0, reserveLine: false }
217  return { kept, collapsed: folded.size, reserveLine: true }
218}
219
220// Exchanges that draw a stream: they carry a burst or a wait (an exchange only easing back draws none).
221function streamExchanges(exchanges: Record<string, Exchange>): Exchange[] {
222  return Object.keys(exchanges)
223    .sort()
224    .map(key => exchanges[key]!)
225    .filter(ex => ex.reasons.length > 0)
226}
227
228// The pull (in columns) a figure feels toward its partner: its shift, toward the partner's column.
229function shiftFor(
230  agent: Agent,
231  exchanges: Record<string, Exchange>,
232  base: Map<string, { x: number; y: number }>,
233): number {
234  const magnitude = Math.min(MAX_SHIFT, Math.max(0, agent.shift))
235  if (magnitude === 0) return 0
236  for (const ex of Object.values(exchanges)) {
237    const partner = ex.fromId === agent.id ? ex.toId : ex.toId === agent.id ? ex.fromId : null
238    if (partner === null) continue
239    const me = base.get(agent.id)
240    const other = base.get(partner)
241    if (!me || !other) continue
242    const dx = other.x - me.x
243    if (dx === 0) continue
244    return Math.sign(dx) * Math.min(magnitude, Math.abs(dx))
245  }
246  return 0
247}
248
249// The agents of one colony (this session's, or one other session's group) laid out in a viewport.
250// `root` is the agent drawn on top (main, or a group's own main agent).
251function layoutAgents(colony: Colony, viewport: Viewport, tick: number, root: string = MAIN_ID): Scene {
252  const byId = shownAgents(colony.agents)
253  const agents = Object.values(byId)
254  const summary = summaryOf(agents)
255  const none = {
256    figures: [],
257    streams: [],
258    connectors: [],
259    hidden: 0,
260    collapsed: 0,
261    overflowRow: -1,
262    tick,
263    viewport,
264    lines: [],
265    groups: [],
266  }
267  if (agents.length === 0) {
268    return { ...none, empty: true, tooSmall: false, summary }
269  }
270  if (viewport.columns < FIGURE_WIDTH || viewport.rows < FIGURE_HEIGHT) {
271    return { ...none, empty: false, tooSmall: true, summary }
272  }
273
274  // Each figure's size follows its model, shrunk to fit a small viewport (never below the base figure).
275  const fits = Math.max(FIGURE_WIDTH, 2 * Math.floor(Math.min(viewport.columns, 2 * (viewport.rows - 1)) / 2))
276  const pxOf = (agent: Agent) => Math.max(FIGURE_WIDTH, Math.min(pixelsOf(agent.model), fits))
277  // Grid cells fit the biggest of the other agents; main stands alone on the row above them.
278  const others = agents.filter(a => a.id !== root)
279  const maxW = Math.max(FIGURE_WIDTH, ...others.map(pxOf))
280  const maxH = maxW / 2 + 1
281  const rowStep = maxH + CONNECTOR_ROWS
282
283  const base = new Map<string, { x: number; y: number; rowTop: number; rowBottom: number }>()
284  const placed: Array<{ agent: Agent; x: number; y: number }> = []
285
286  // Main figure on top, centred.
287  const main = byId[root]
288  let top = 0
289  if (main) {
290    const px = pxOf(main)
291    const height = px / 2 + 1
292    const x = Math.floor((viewport.columns - px) / 2)
293    base.set(root, { x, y: 0, rowTop: 0, rowBottom: height })
294    placed.push({ agent: main, x, y: 0 })
295    top = height + CONNECTOR_ROWS
296  }
297
298  // Everyone else in family order in a grid beneath.
299  const cols = gridColumns(viewport.columns, maxW)
300  const { kept, collapsed, reserveLine } = fitOthers(familyOrder(agents, root), cols, maxH, viewport.rows - top)
301  const capacity = capacityFor(cols, maxH, viewport.rows - top - (reserveLine ? 1 : 0))
302  // Past capacity, drop from the end of family order but never a pending figure (the user must see it).
303  let overflow = Math.max(0, kept.length - capacity)
304  const dropped = new Set<string>()
305  for (let i = kept.length - 1; i >= 0 && overflow > 0; i--) {
306    if (kept[i]!.state === 'pending') continue
307    dropped.add(kept[i]!.id)
308    overflow--
309  }
310  // Only if pending figures alone exceed capacity are some of them cut.
311  const shown = kept.filter(a => !dropped.has(a.id)).slice(0, capacity)
312  const hidden = kept.length - shown.length
313  shown.forEach((agent, i) => {
314    const px = pxOf(agent)
315    const rowTop = top + Math.floor(i / cols) * rowStep
316    const x = (i % cols) * (maxW + GAP) + Math.floor((maxW - px) / 2)
317    const y = rowTop + (maxH - (px / 2 + 1))
318    base.set(agent.id, { x, y, rowTop, rowBottom: rowTop + maxH })
319    placed.push({ agent, x, y })
320  })
321
322  // Figures: the base position moved toward the exchange partner by the eased shift, then by the
323  // wander drift of a working figure.
324  const figures: Figure[] = placed.map(({ agent, x, y }) => {
325    const drift = agent.id === root ? 0 : Math.round(agent.wander)
326    const x2 = x + shiftFor(agent, colony.exchanges, base) + drift
327    return figureFor(agent, x2, y, tick, pxOf(agent), agent.id === root)
328  })
329
330  // Keep every row's figures apart (a drift or pull never makes two touch) and inside the pane.
331  const rows = new Map<number, Figure[]>()
332  for (const f of figures) {
333    const rowTop = base.get(f.agentId)!.rowTop
334    rows.set(rowTop, [...(rows.get(rowTop) ?? []), f])
335  }
336  for (const row of rows.values()) {
337    row.sort((a, b) => a.x - b.x)
338    let edge = 0
339    for (const f of row) {
340      f.x = Math.max(f.x, edge)
341      edge = f.x + f.width + 1
342    }
343    let limit = viewport.columns
344    for (let i = row.length - 1; i >= 0; i--) {
345      const f = row[i]!
346      f.x = Math.max(0, Math.min(f.x, limit - f.width))
347      limit = f.x - 1
348    }
349  }
350  const at = new Map(figures.map(f => [f.agentId, f]))
351
352  // Connectors: one glyph per child in the gap directly above it, clear of every figure. An agent no
353  // orchestrator here started (a teammate, an independent agent) has none.
354  const connectors: Connector[] = []
355  for (const figure of figures) {
356    const agent = byId[figure.agentId]!
357    if (figure.isMain || agent.independent || !agent.parentId || !at.has(agent.parentId)) continue
358    const cx = figure.x + Math.floor(figure.width / 2)
359    const rowTop = base.get(figure.agentId)!.rowTop
360    for (let y = Math.max(0, rowTop - CONNECTOR_ROWS); y < figure.y; y++) connectors.push({ x: cx, y })
361  }
362
363  // Streams: one per active exchange, on a lane row below the upper figure's row; lanes never overlap.
364  const lanes = new Map<number, Array<[number, number]>>()
365  const streams: Stream[] = []
366  for (const ex of streamExchanges(colony.exchanges)) {
367    const a = at.get(ex.fromId)
368    const b = at.get(ex.toId)
369    if (!a || !b) continue
370    const upper = a.y < b.y || (a.y === b.y && a.x <= b.x) ? a : b
371    const x0 = Math.min(a.x + Math.floor(a.width / 2), b.x + Math.floor(b.width / 2))
372    const x1 = Math.max(a.x + Math.floor(a.width / 2), b.x + Math.floor(b.width / 2))
373    const span: [number, number] = [x0, x1]
374    const below = base.get(upper.agentId)!.rowBottom
375    for (let lane = 0; lane < LANES; lane++) {
376      const row = below + lane
377      if (row >= viewport.rows) continue
378      const taken = lanes.get(row) ?? []
379      if (taken.some(([s, e]) => x0 <= e && s <= x1)) continue
380      taken.push(span)
381      lanes.set(row, taken)
382      streams.push({ fromId: ex.fromId, toId: ex.toId, row, x: x0, width: x1 - x0 + 1 })
383      break
384    }
385  }
386
387  return {
388    figures,
389    streams,
390    connectors,
391    hidden,
392    collapsed,
393    overflowRow: collapsed > 0 ? viewport.rows - 1 : -1,
394    tick,
395    empty: false,
396    tooSmall: false,
397    summary,
398    viewport,
399    lines: [],
400    groups: [],
401  }
402}
403
404// ---- Session groups (spec 002, contracts/pane-render.md) --------------------------------------
405
406// The text of a group's header row: name, folder dimmed, then the markers. A collapsed group names how
407// many agents it folds. Pure: the same words for live, stale and limited groups.
408export function headerOf(group: SessionGroup, expanded: boolean): Segment[] {
409  const out: Segment[] = [{ text: group.name }]
410  if (group.folder) out.push({ text: `  ${group.folder}`, dim: true })
411  if (group.needsAttention) out.push({ text: '  ! needs you', color: 'yellow' })
412  if (group.freshness === 'stale') out.push({ text: '  stale', dim: true })
413  if (group.source === 'peer') out.push({ text: '  limited', dim: true })
414  if (!expanded && group.agents.length > 0) out.push({ text: `  +${group.agents.length} agents`, dim: true })
415  return out
416}
417
418// What a block of drawn parts takes up: rows from its top to its lowest figure, lane, connector or line.
419type Parts = {
420  figures: Figure[]
421  streams: Stream[]
422  connectors: Connector[]
423  lines: Line[]
424  overflowRow?: number
425}
426
427function heightOf(parts: Parts): number {
428  let height = (parts.overflowRow ?? -1) + 1
429  for (const f of parts.figures) height = Math.max(height, f.y + f.height)
430  for (const s of parts.streams) height = Math.max(height, s.row + 1)
431  for (const c of parts.connectors) height = Math.max(height, c.y + 1)
432  for (const l of parts.lines) height = Math.max(height, l.row + 1)
433  return height
434}
435
436// One group's drawing, in its own rows (row 0 is the first row under its header).
437type Block = Parts & { hidden: number; height: number }
438
439type Plan = { group: SessionGroup; block: Block; expanded: boolean; dropped: boolean }
440
441// Other sessions in a stable order: by name, then by id.
442function orderedGroups(sessions: Record<string, SessionGroup>): SessionGroup[] {
443  return Object.values(sessions).sort(
444    (a, b) => a.name.localeCompare(b.name) || (a.sessionId < b.sessionId ? -1 : a.sessionId > b.sessionId ? 1 : 0),
445  )
446}
447
448// A group's agents as a colony of their own: the same drawing as a local session. Exchanges between
449// its agents pull the pair together like local ones do.
450function groupColony(group: SessionGroup): Colony {
451  const agents: Record<string, Agent> = {}
452  for (const a of group.agents) agents[a.id] = { ...a }
453  const exchanges: Record<string, Exchange> = {}
454  for (const e of group.exchanges) {
455    const from = agents[e.from]
456    const to = agents[e.to]
457    if (!from || !to) continue
458    const id = exchangeId(e.from, e.to)
459    exchanges[id] = { id, fromId: e.from, toId: e.to, reasons: ['message'], burstUntil: 0 }
460    from.shift = MAX_SHIFT
461    to.shift = MAX_SHIFT
462  }
463  return { agents, exchanges, tick: 0, retentionMs: 0, sessions: {} }
464}
465
466// The fallback figure of a session that does not share (spec 003): one unknown-style figure.
467function peerBlockOf(group: SessionGroup, columns: number): Block {
468  const px = FIGURE_WIDTH
469  const figure: Figure = {
470    agentId: group.sessionId,
471    x: Math.floor((columns - px) / 2),
472    y: 0,
473    state: 'unknown',
474    grid: frameOf('unknown', 0, false, px),
475    label: truncate(group.name, px),
476    isMain: false,
477    width: px,
478    height: px / 2 + 1,
479    tier: null,
480    fill: null,
481    background: false,
482    title: group.name,
483    details: ['limited: this session shares no agent detail'],
484    stale: false,
485  }
486  return { figures: [figure], streams: [], connectors: [], lines: [], hidden: 0, height: figure.height }
487}
488
489// A group's drawing in the viewport's width. A stale group is frozen on its first frame, dimmed, with no
490// streams: it does not animate.
491function blockOf(group: SessionGroup, viewport: Viewport, tick: number): Block {
492  if (group.agents.length === 0) {
493    if (group.source === 'peer') return peerBlockOf(group, viewport.columns)
494    return { figures: [], streams: [], connectors: [], lines: [], hidden: 0, height: 0 }
495  }
496  const frozen = group.freshness === 'stale'
497  const scene = layoutAgents(groupColony(group), viewport, frozen ? 0 : tick, `${group.sessionId}/${MAIN_ID}`)
498  const figures = scene.figures.map(f => ({ ...f, stale: frozen }))
499  const streams = frozen ? [] : scene.streams
500  const lines: Line[] = []
501  // Past the group's capacity, its oldest completed agents fold into a `+N done` line under them.
502  if (scene.collapsed > 0) {
503    const row = heightOf({ figures, streams, connectors: scene.connectors, lines })
504    lines.push({ row, segments: [{ text: `+${scene.collapsed} done`, dim: true }] })
505  }
506  const parts = { figures, streams, connectors: scene.connectors, lines }
507  return { ...parts, hidden: scene.hidden, height: heightOf(parts) }
508}
509
510// The whole pane: the local session first, then each other session as a group under it. When the
511// groups do not fit, fresh quiet groups fold to their header first, then stale ones; a group needing
512// attention and the local session never fold. Only if even the folded headers do not fit are the last
513// groups left out (counted in `hidden`).
514export function layout(colony: Colony, viewport: Viewport, tick: number): Scene {
515  const groups = orderedGroups(colony.sessions)
516  const tooSmall = viewport.columns < FIGURE_WIDTH || viewport.rows < FIGURE_HEIGHT
517  if (groups.length === 0 || tooSmall) return layoutAgents(colony, viewport, tick)
518
519  // The local session keeps the rows above the groups' headers.
520  const localRows = Math.max(FIGURE_HEIGHT, viewport.rows - groups.length)
521  const local = layoutAgents(colony, { ...viewport, rows: localRows }, tick)
522  const budget = viewport.rows - heightOf(local)
523
524  const plans: Plan[] = groups.map(group => ({ group, block: blockOf(group, viewport, tick), expanded: true, dropped: false }))
525  const cost = (p: Plan) => 1 + (p.expanded ? p.block.height : 0)
526  const used = () => plans.reduce((sum, p) => sum + (p.dropped ? 0 : cost(p)), 0)
527
528  const quiet = plans.filter(p => p.group.freshness === 'live' && !p.group.needsAttention).reverse()
529  const stale = plans.filter(p => p.group.freshness === 'stale' && !p.group.needsAttention).reverse()
530  const folded: Plan[] = []
531  for (const p of [...quiet, ...stale]) {
532    if (used() <= budget) break
533    p.expanded = false
534    folded.push(p)
535  }
536  // Fold only as deep as the space needs: the last folded groups reopen first, if they fit again.
537  for (const p of folded.reverse()) {
538    p.expanded = true
539    if (used() > budget) p.expanded = false
540  }
541  // Last resort, when even the folded headers do not fit: a group needing attention folds to its header
542  // (its marker stays), then the other groups are left out from the end, and attention groups last.
543  const others = plans.filter(p => !p.group.needsAttention).reverse()
544  const attention = plans.filter(p => p.group.needsAttention).reverse()
545  for (const p of attention) {
546    if (used() <= budget) break
547    p.expanded = false
548  }
549  for (const p of [...others, ...attention]) {
550    if (used() <= budget) break
551    p.dropped = true
552  }
553
554  const figures = [...local.figures]
555  const streams = [...local.streams]
556  const connectors = [...local.connectors]
557  const lines: Line[] = []
558  const views: GroupView[] = []
559  let hidden = local.hidden
560  let row = heightOf(local)
561  for (const p of plans) {
562    if (p.dropped) {
563      hidden += p.group.agents.length || 1
564      continue
565    }
566    const header = row
567    lines.push({ row: header, segments: headerOf(p.group, p.expanded) })
568    views.push({
569      sessionId: p.group.sessionId,
570      name: p.group.name,
571      row: header,
572      expanded: p.expanded,
573      source: p.group.source,
574      freshness: p.group.freshness,
575      needsAttention: p.group.needsAttention,
576      agents: p.group.agents.length,
577    })
578    if (p.expanded) {
579      const dy = header + 1
580      figures.push(...p.block.figures.map(f => ({ ...f, y: f.y + dy })))
581      streams.push(...p.block.streams.map(s => ({ ...s, row: s.row + dy })))
582      connectors.push(...p.block.connectors.map(c => ({ ...c, y: c.y + dy })))
583      lines.push(...p.block.lines.map(l => ({ ...l, row: l.row + dy })))
584      hidden += p.block.hidden
585    }
586    row = header + cost(p)
587  }
588
589  return {
590    ...local,
591    figures,
592    streams,
593    connectors,
594    lines,
595    groups: views,
596    hidden,
597    empty: false,
598    tooSmall: false,
599    viewport,
600  }
601}
602
src/runtime.ts 192 lines
1// Pure helpers behind hooks/register.tsx: option parsing, signal context, clock and pane decisions.
2// No engine imports, so each rule is unit-tested without the engine.
3import { activityOf, type SignalContext } from './signals'
4import { summaryOf } from './layout'
5import { isPeer, REACT_MS, shownStateOf, TERMINAL_STATES } from './model'
6import type { Agent, AgentState, Colony } from '../types'
7
8export const DEFAULT_RETENTION_SECONDS = 30
9export const CLOCK_MS = 250
10// Shared-summary writes: a change is written at most once per WRITE_MIN_MS; while any agent is active
11// a heartbeat is written every HEARTBEAT_MS so readers can tell a live session from a stale one.
12export const WRITE_MIN_MS = 1000
13export const HEARTBEAT_MS = 5000
14
15// States whose figures animate; while any is present (or an exchange is open) the clock runs.
16const ANIMATED: ReadonlyArray<AgentState> = ['in-progress', 'pending', 'completed', 'listening']
17
18export type ColonyOptions = {
19  reducedMotion: boolean
20  retentionMs: number
21  sessionsDirectory: string
22  // The "Share with my other sessions" switch (off by default, FR-002).
23  shareSessions: boolean
24  // The optional folder override. Empty means the default folder (see sharedFolderFor), or nothing when sharing is off.
25  sharedFolder: string
26}
27
28// userConfig values as the engine hands them to register(on, options). Anything unusable falls back.
29export function readOptions(options: Readonly<Record<string, unknown>> | undefined): ColonyOptions {
30  const raw = Number(options?.retentionSeconds)
31  const seconds =
32    options?.retentionSeconds !== undefined && Number.isFinite(raw) && raw >= 0
33      ? raw
34      : DEFAULT_RETENTION_SECONDS
35  return {
36    reducedMotion: options?.reducedMotion === true || options?.reducedMotion === 'true',
37    retentionMs: Math.round(seconds * 1000),
38    // Empty (the default) means the default folder (see sessionsFolderFor), read only while the switch is on.
39    sessionsDirectory: typeof options?.sessionsDirectory === 'string' ? options.sessionsDirectory.trim() : '',
40    shareSessions: options?.shareSessions === true || options?.shareSessions === 'true',
41    sharedFolder: typeof options?.sharedFolder === 'string' ? options.sharedFolder.trim() : '',
42  }
43}
44
45export type SharedFolderInput = {
46  shareSessions: boolean
47  sharedFolder: string
48  // The CLAUDE_CONFIG_DIR and HOME values read at session start ('' when unset).
49  configDir: string
50  home: string
51}
52
53// The folder this session shares to and reads from (spec 002). '' means sharing is off: nothing is written
54// or read. Sharing is on when the switch is on or a folder is set. A set folder wins; otherwise the folder is
55// <config dir>/colony, where the config dir is CLAUDE_CONFIG_DIR or else <home>/.claude.
56export function sharedFolderFor(input: SharedFolderInput): string {
57  const override = input.sharedFolder.trim()
58  if (override !== '') return stripTrailingSlashes(override) || override
59  if (!input.shareSessions) return ''
60  const configDir = stripTrailingSlashes(input.configDir.trim())
61  const home = stripTrailingSlashes(input.home.trim())
62  const base = configDir || (home ? `${home}/.claude` : '')
63  return base ? `${base}/colony` : ''
64}
65
66// The folder the limited view of other sessions is read from (spec 003, spec 005). A set override wins, even
67// with the switch off (FR-003). Otherwise the switch decides: on gives <config dir>/sessions, where the config
68// dir is CLAUDE_CONFIG_DIR or else <home>/.claude; off gives '' (nothing is read, FR-005).
69export function sessionsFolderFor(input: SessionsFolderInput): string {
70  const override = input.sessionsDirectory.trim()
71  if (override !== '') return stripTrailingSlashes(override) || override
72  if (!input.shareSessions) return ''
73  const configDir = stripTrailingSlashes(input.configDir.trim())
74  const home = stripTrailingSlashes(input.home.trim())
75  const base = configDir || (home ? `${home}/.claude` : '')
76  return base ? `${base}/sessions` : ''
77}
78
79export type SessionsFolderInput = {
80  shareSessions: boolean
81  sessionsDirectory: string
82  // The CLAUDE_CONFIG_DIR and HOME values read at session start ('' when unset).
83  configDir: string
84  home: string
85}
86
87function stripTrailingSlashes(path: string): string {
88  return path.replace(/\/+$/, '')
89}
90
91export function pendingIdsOf(colony: Colony): string[] {
92  return Object.values(colony.agents)
93    .filter(a => a.state === 'pending')
94    .map(a => a.id)
95}
96
97// The clock runs only while a figure animates or an exchange is open, and never in reduced motion.
98export function animates(colony: Colony, reducedMotion: boolean): boolean {
99  if (reducedMotion) return false
100  if (Object.keys(colony.exchanges).length > 0) return true
101  // A figure still drifting (or easing home after it stopped working) keeps the clock running too.
102  return Object.values(colony.agents).some(
103    (a: Agent) => ANIMATED.includes(shownStateOf(a)) || a.wander !== a.wanderTarget || a.wanderTarget !== 0,
104  )
105}
106
107// The most recently active agent, kept across events (see activityOf); unchanged by other events.
108export function nextRecentAgent(previous: string | null, eventName: string, e: Record<string, unknown>): string | null {
109  return activityOf(eventName, e) ?? previous
110}
111
112export function contextFor(
113  colony: Colony,
114  recentAgentId: string | null,
115  at: number,
116  reactFlashMs: number = REACT_MS,
117): SignalContext {
118  const agents = Object.values(colony.agents).map(a => ({ id: a.id, label: a.label }))
119  return { at, recentAgentId, pendingIds: pendingIdsOf(colony), agents, reactFlashMs }
120}
121
122// The agents of other sessions that share and are live (a stale or limited session is not counted).
123export function sharedAgentsOf(colony: Colony): Agent[] {
124  return Object.values(colony.sessions)
125    .filter(g => g.source === 'shared' && g.freshness === 'live')
126    .flatMap(g => g.agents)
127}
128
129// Pending agents of this session and of live sharing sessions (FR-009); limited peer figures never count.
130export function pendingAgentsOf(colony: Colony): Agent[] {
131  return [...Object.values(colony.agents), ...sharedAgentsOf(colony)].filter(a => a.state === 'pending')
132}
133
134// The status line text, or undefined when the pane is placed (or not open at all).
135export function statusFor(colony: Colony, paneOpen: boolean, placed: boolean): string | undefined {
136  if (!paneOpen || placed) return undefined
137  return summaryOf([...Object.values(colony.agents), ...sharedAgentsOf(colony)])
138}
139
140// Whether any of this session's own agents is doing something a reader should see as live: a heartbeat
141// is written while this holds (spec 002, shouldWrite).
142export function anyActiveOf(colony: Colony): boolean {
143  return Object.values(colony.agents).some(
144    a => !isPeer(a) && a.state !== 'idle' && !TERMINAL_STATES.includes(a.state),
145  )
146}
147
148// The file a session's summary goes to in the shared folder: one `<sessionId>.json` per session.
149export function summaryPath(folder: string, sessionId: string): string {
150  return `${stripTrailingSlashes(folder)}/${sessionId}.json`
151}
152
153// What justifies opening the pane: pending agents plus subagents (main alone never does).
154export function attentionOf(colony: Colony): number {
155  const pending = pendingIdsOf(colony).length
156  const subagents = Object.values(colony.agents).filter(a => a.id !== 'main' && !isPeer(a)).length
157  return pending + subagents
158}
159
160// Auto-open the first time an agent needs the user or a subagent appears, unless the user hid the pane (FR-001).
161export function shouldAutoOpen(input: {
162  attention: number
163  hidden: boolean
164  paneOpen: boolean
165  firstAutoDone: boolean
166}): boolean {
167  return input.attention > 0 && !input.hidden && !input.paneOpen && !input.firstAutoDone
168}
169
170// Toast when a new pending appears while the open pane is not placed (narrow terminal).
171export function shouldToastPending(input: {
172  pendingCount: number
173  previousPendingCount: number
174  paneOpen: boolean
175  placed: boolean
176}): boolean {
177  return input.paneOpen && !input.placed && input.pendingCount > input.previousPendingCount
178}
179
180// Whether to write the own shared summary now. `changed` means a change is still unwritten: the caller
181// keeps it set until a write happens, so the trailing change is written once the interval has passed.
182export function shouldWrite(input: {
183  changed: boolean
184  lastWriteAt: number
185  now: number
186  lastHeartbeatAt: number
187}): boolean {
188  if (input.changed && input.now - input.lastWriteAt >= WRITE_MIN_MS) return true
189  // A live session heartbeats whether or not an agent is busy: an idle session must not look stale.
190  return input.now - input.lastHeartbeatAt >= HEARTBEAT_MS
191}
192
src/snapshot.ts 155 lines
1// The summary a session shares with other sessions (contracts/shared-summary.md). Pure: the writer
2// builds only from an explicit allow-list, and the reader validates what it finds. No engine imports.
3import { isPeer, MAIN_ID, TERMINAL_STATES } from './model'
4import type { Agent, AgentState, Colony, SharedAgent, SharedSummary } from '../types'
5
6export const SUMMARY_VERSION = 1
7export const MAX_AGENTS = 100
8// Labels are cut to this length when written; a reader accepts up to LABEL_READ_MAX and cuts to LABEL_MAX.
9export const LABEL_MAX = 40
10export const LABEL_READ_MAX = 200
11
12const STATES: ReadonlyArray<AgentState> = [
13  'idle',
14  'in-progress',
15  'pending',
16  'listening',
17  'completed',
18  'failed',
19  'cancelled',
20  'unknown',
21]
22
23export type SessionInfo = { id: string; name: string; folder: string }
24
25function isRecord(value: unknown): value is Record<string, unknown> {
26  return typeof value === 'object' && value !== null && !Array.isArray(value)
27}
28
29function tokensOf(agent: Agent): { in: number; out: number } | null {
30  const { input, output } = agent.usage
31  if (input === 0 && output === 0) return null
32  return { in: input, out: output }
33}
34
35// Over the limit, the writer drops the oldest finished subagents first, then the oldest of the rest.
36// The main agent is never dropped.
37function withinLimit(agents: Agent[]): Agent[] {
38  let excess = agents.length - MAX_AGENTS
39  if (excess <= 0) return agents
40  const dropped = new Set<string>()
41  const finished = agents
42    .filter(a => a.id !== MAIN_ID && TERMINAL_STATES.includes(a.state))
43    .sort((a, b) => (a.endedAt ?? 0) - (b.endedAt ?? 0))
44  for (const a of finished.slice(0, excess)) dropped.add(a.id)
45  excess -= dropped.size
46  if (excess > 0) {
47    const rest = agents
48      .filter(a => a.id !== MAIN_ID && !dropped.has(a.id))
49      .sort((a, b) => a.lastEventAt - b.lastEventAt)
50    for (const a of rest.slice(0, excess)) dropped.add(a.id)
51  }
52  return agents.filter(a => !dropped.has(a.id))
53}
54
55// Builds this session's summary. Each agent is copied field by field from the allow-list; nothing
56// else on an agent, the colony or an exchange is ever copied. Other sessions' figures are not shared.
57export function buildSummary(colony: Colony, session: SessionInfo, now: number): SharedSummary {
58  const own = withinLimit(Object.values(colony.agents).filter(a => !isPeer(a)))
59  const ids = new Set(own.map(a => a.id))
60  const agents: SharedAgent[] = own.map(a => ({
61    id: a.id,
62    label: a.label.slice(0, LABEL_MAX),
63    parentId: a.parentId,
64    state: a.state,
65    listenSource: a.listenSource,
66    model: a.model,
67    tokens: tokensOf(a),
68  }))
69  const exchanges = Object.values(colony.exchanges)
70    .filter(x => ids.has(x.fromId) && ids.has(x.toId))
71    .map(x => ({ from: x.fromId, to: x.toId }))
72  return {
73    version: 1,
74    sessionId: session.id,
75    name: session.name,
76    folder: session.folder,
77    updatedAt: now,
78    ended: false,
79    agents,
80    exchanges,
81  }
82}
83
84// The marker written when a session ends or sharing is switched off: no name, no folder, no agents.
85export function endedSummary(session: { id: string }, now: number): SharedSummary {
86  return { version: 1, sessionId: session.id, updatedAt: now, ended: true, agents: [] }
87}
88
89function readAgent(item: unknown): SharedAgent | null {
90  if (!isRecord(item)) return null
91  const { id, label } = item
92  if (typeof id !== 'string' || id === '') return null
93  if (typeof label !== 'string' || label.length > LABEL_READ_MAX) return null
94  const state = STATES.includes(item.state as AgentState) ? (item.state as AgentState) : 'unknown'
95  const tokens = isRecord(item.tokens) && typeof item.tokens.in === 'number' && typeof item.tokens.out === 'number'
96    ? { in: item.tokens.in, out: item.tokens.out }
97    : null
98  return {
99    id,
100    label: label.slice(0, LABEL_MAX),
101    parentId: typeof item.parentId === 'string' ? item.parentId : null,
102    state,
103    listenSource: typeof item.listenSource === 'string' ? item.listenSource : null,
104    model: typeof item.model === 'string' ? item.model : null,
105    tokens,
106  }
107}
108
109function readExchanges(raw: unknown): Array<{ from: string; to: string }> {
110  if (!Array.isArray(raw)) return []
111  const out: Array<{ from: string; to: string }> = []
112  for (const item of raw) {
113    if (isRecord(item) && typeof item.from === 'string' && typeof item.to === 'string') {
114      out.push({ from: item.from, to: item.to })
115    }
116  }
117  return out
118}
119
120// One session's file text -> a summary, or null when it must be ignored (FR-008). Fields outside
121// the contract are dropped because the result is built afresh.
122export function parseSummary(text: string): SharedSummary | null {
123  let raw: unknown
124  try {
125    raw = JSON.parse(text)
126  } catch {
127    return null
128  }
129  if (!isRecord(raw) || raw.version !== SUMMARY_VERSION) return null
130  const { sessionId, updatedAt } = raw
131  if (typeof sessionId !== 'string' || sessionId === '') return null
132  if (typeof updatedAt !== 'number' || !Number.isFinite(updatedAt)) return null
133  const list = raw.agents
134  if (!Array.isArray(list) || list.length > MAX_AGENTS) return null
135  const agents: SharedAgent[] = []
136  const seen = new Set<string>()
137  for (const item of list) {
138    const agent = readAgent(item)
139    if (!agent || seen.has(agent.id)) return null
140    seen.add(agent.id)
141    agents.push(agent)
142  }
143  const summary: SharedSummary = {
144    version: 1,
145    sessionId,
146    updatedAt,
147    ended: raw.ended === true,
148    agents,
149    exchanges: readExchanges(raw.exchanges),
150  }
151  if (typeof raw.name === 'string') summary.name = raw.name
152  if (typeof raw.folder === 'string') summary.folder = raw.folder
153  return summary
154}
155
src/sessions.ts 140 lines
1// Merges the shared summaries other sessions wrote and the peer fallback into session groups for the
2// pane (spec 002, data-model.md). Pure: hooks/register.tsx reads the folder and passes the results in.
3import { PEER_PREFIX, type Peer } from './model'
4import type { Agent, SessionGroup, SharedAgent, SharedSummary } from '../types'
5
6// Live below STALE_MS since the newer of updatedAt and the file's modification time; stale up to REMOVE_MS.
7export const STALE_MS = 10_000
8export const REMOVE_MS = 60_000
9// A summary older than this is ignored outright (in practice the removal rule already drops it sooner).
10export const IGNORE_AGE_MS = 24 * 60 * 60 * 1000
11
12// One file in the shared folder, as the reader read it. `summary` is null when it could not be used.
13export type FileRead = { sessionId: string; summary: SharedSummary | null }
14
15export type MergeInput = {
16  summaries: FileRead[]
17  peers: Peer[]
18  selfId: string | null
19  now: number
20  // Modification time (ms) of each shared file, by session id.
21  mtimes: Record<string, number>
22}
23
24function lastSegment(folder: string): string {
25  return folder.split('/').filter(Boolean).pop() ?? ''
26}
27
28// A shared agent as a full pane agent. Ids are namespaced by session so they cannot clash with local ids.
29function agentOf(sessionId: string, a: SharedAgent, updatedAt: number): Agent {
30  const ns = (id: string) => `${sessionId}/${id}`
31  return {
32    id: ns(a.id),
33    label: a.label,
34    parentId: a.parentId === null ? null : ns(a.parentId),
35    state: a.state,
36    listenSource: a.listenSource,
37    reactUntil: null,
38    startedAt: null,
39    endedAt: null,
40    lastEventAt: updatedAt,
41    listed: false,
42    shift: 0,
43    model: a.model,
44    usage: { input: a.tokens?.in ?? 0, output: a.tokens?.out ?? 0, cacheRead: 0, cacheWrite: 0 },
45    steps: 0,
46    contextTokens: null,
47    wander: 0,
48    wanderTarget: 0,
49    addressable: false,
50    independent: false,
51    background: false,
52    spawnedBy: null,
53    note: null,
54  }
55}
56
57// A group from a usable summary, or null when the summary says the session has ended or it is too old.
58function sharedGroup(sessionId: string, summary: SharedSummary, mtime: number, now: number): SessionGroup | null {
59  if (summary.ended) return null
60  const age = now - Math.max(summary.updatedAt, mtime)
61  if (age >= REMOVE_MS || age >= IGNORE_AGE_MS) return null
62  const folder = summary.folder ?? ''
63  const agents = summary.agents.map(a => agentOf(sessionId, a, summary.updatedAt))
64  return {
65    sessionId,
66    name: summary.name || lastSegment(folder) || sessionId.slice(0, 8),
67    folder,
68    updatedAt: summary.updatedAt,
69    source: 'shared',
70    freshness: age < STALE_MS ? 'live' : 'stale',
71    agents,
72    exchanges: (summary.exchanges ?? []).map(e => ({ from: `${sessionId}/${e.from}`, to: `${sessionId}/${e.to}` })),
73    needsAttention: agents.some(a => a.state === 'pending'),
74  }
75}
76
77// Two groups with the same name are told apart by their folder's last segment, then by a short id.
78function distinctNames(groups: SessionGroup[]): void {
79  const byName = new Map<string, SessionGroup[]>()
80  for (const g of groups) byName.set(g.name, [...(byName.get(g.name) ?? []), g])
81  for (const clash of byName.values()) {
82    if (clash.length < 2) continue
83    const counts = new Map<string, number>()
84    for (const g of clash) {
85      const seg = lastSegment(g.folder)
86      counts.set(seg, (counts.get(seg) ?? 0) + 1)
87    }
88    for (const g of clash) {
89      const seg = lastSegment(g.folder)
90      g.name = seg && counts.get(seg) === 1 ? seg : g.sessionId.slice(0, 8)
91    }
92  }
93}
94
95export function mergeSessions(input: MergeInput): Record<string, SessionGroup> {
96  const { summaries, peers, selfId, now, mtimes } = input
97  const peerBySession = new Map<string, Peer>()
98  for (const p of peers) {
99    if (p.id.startsWith(PEER_PREFIX)) peerBySession.set(p.id.slice(PEER_PREFIX.length), p)
100  }
101  // The limited figure for a session that does not share (spec 003 fallback).
102  const fallback = (sessionId: string): SessionGroup | null => {
103    const p = peerBySession.get(sessionId)
104    if (!p || sessionId === selfId) return null
105    return {
106      sessionId,
107      name: p.label,
108      folder: '',
109      updatedAt: now,
110      source: 'peer',
111      freshness: 'live',
112      agents: [],
113      exchanges: [],
114      needsAttention: false,
115    }
116  }
117
118  const groups: SessionGroup[] = []
119  const handled = new Set<string>()
120  for (const { sessionId, summary } of summaries) {
121    if (sessionId === selfId || handled.has(sessionId)) continue
122    handled.add(sessionId)
123    // A usable shared summary wins; an ended, stale, unreadable or missing one falls back to the peer entry.
124    const group = summary ? sharedGroup(sessionId, summary, mtimes[sessionId] ?? 0, now) : null
125    const chosen = group ?? fallback(sessionId)
126    if (chosen) groups.push(chosen)
127  }
128  for (const sessionId of peerBySession.keys()) {
129    if (handled.has(sessionId)) continue
130    handled.add(sessionId)
131    const chosen = fallback(sessionId)
132    if (chosen) groups.push(chosen)
133  }
134
135  distinctNames(groups)
136  const out: Record<string, SessionGroup> = {}
137  for (const g of groups) out[g.sessionId] = g
138  return out
139}
140
src/signals.ts 292 lines
1// Engine event -> colony signals (contracts/event-mapping.md). Pure: no engine imports.
2// Hooks in hooks/register.tsx enrich an event with what only the engine's agent list knows
3// (a parent id, a description, an end status) before calling toSignals.
4import { MAIN_ID, REACT_MS, TERMINAL_STATES, type Signal } from './model'
5import type { AgentState, Usage } from '../types'
6
7// What attribution needs beyond the event itself.
8export type SignalContext = {
9  at: number
10  // The most recently active agent (see activityOf), or null before any activity.
11  recentAgentId: string | null
12  // Agents currently pending, i.e. waiting on the user.
13  pendingIds: string[]
14  // Known agents, so a recipient or teammate name can be resolved by id or label.
15  agents: Array<{ id: string; label: string }>
16  // Length of a reaction flash (ms); 0 under reduced motion. Defaults to REACT_MS.
17  reactFlashMs?: number
18}
19
20// Tools that register an external trigger (R5). ScheduleWakeup and CronCreate are the agent's own
21// timers and are deliberately absent.
22const LISTENING_TOOLS: Readonly<Record<string, string>> = {
23  Monitor: 'watch',
24  RemoteTrigger: 'webhook',
25}
26
27type EventInput = Record<string, unknown>
28
29// Notification types that mean the agent is waiting on the user (research R3).
30const PROMPT_NOTIFICATIONS: ReadonlyArray<string> = ['permission_prompt', 'idle_prompt']
31
32// One row of `$.agent.list()` as the mod reads it (AgentInfo, reduced to what the pane needs).
33export type ListedAgent = {
34  id: string
35  description?: string
36  type?: string
37  parentId?: string
38  status: string
39  name?: string
40  teammateId?: string
41  spawnedBy?: string
42}
43
44// The token counts of a turn.complete `usage` (ModelUsage), or null when it carries none.
45export function usageOf(value: unknown): Usage | null {
46  if (!value || typeof value !== 'object') return null
47  const u = value as Record<string, unknown>
48  const n = (k: string) => (typeof u[k] === 'number' && Number.isFinite(u[k]) ? (u[k] as number) : 0)
49  return {
50    input: n('input_tokens'),
51    output: n('output_tokens'),
52    cacheRead: n('cache_read_input_tokens'),
53    cacheWrite: n('cache_creation_input_tokens'),
54  }
55}
56
57function text(value: unknown): string {
58  return typeof value === 'string' ? value : ''
59}
60
61// The agent a hook fired from: `agentId` on engine events, `agent_id` on classic hooks; null = main.
62export function agentOf(e: EventInput): string | null {
63  const id = e.agentId ?? e.agent_id
64  return typeof id === 'string' && id.length > 0 ? id : null
65}
66
67// The agent an event shows as active, for recentAgentId tracking. Null when the event is not activity.
68export function activityOf(eventName: string, e: EventInput): string | null {
69  if (eventName === 'tool.call') return agentOf(e) ?? MAIN_ID
70  if (eventName === 'turn.start') return MAIN_ID
71  return null
72}
73
74// Pending attribution: the event's own agent, else the most recently active agent, else main.
75function pendingOwner(e: EventInput, ctx: SignalContext): string {
76  return agentOf(e) ?? ctx.recentAgentId ?? MAIN_ID
77}
78
79function clearPending(ctx: SignalContext): Signal[] {
80  return ctx.pendingIds.map(id => ({
81    type: 'agent-state' as const,
82    id,
83    state: 'in-progress' as const,
84    at: ctx.at,
85  }))
86}
87
88// The ending state of a subagent from its engine status (AgentStatus). The SubagentStop hook itself
89// carries no outcome, so a status the list gives decides, and anything else reads as completed.
90export function endStateOf(status: string | undefined): 'completed' | 'failed' | 'cancelled' {
91  if (status === 'failed') return 'failed'
92  if (status === 'killed' || status === 'cancelled') return 'cancelled'
93  return 'completed'
94}
95
96// The pane state an engine AgentStatus shows as (contracts/event-mapping.md, R2).
97export function listStateOf(status: string): AgentState {
98  switch (status) {
99    case 'running':
100    case 'waiting':
101      return 'in-progress'
102    case 'completed':
103      return 'completed'
104    case 'failed':
105      return 'failed'
106    case 'killed':
107      return 'cancelled'
108    default:
109      // pending (not started) and idle (between turns)
110      return 'idle'
111  }
112}
113
114// Resolve a recipient or teammate name against known agents: an id, or a label that names exactly one.
115export function resolveAgent(to: unknown, agents: SignalContext['agents']): string | null {
116  const key =
117    typeof to === 'string'
118      ? to
119      : to && typeof to === 'object' && typeof (to as { agentId?: unknown }).agentId === 'string'
120        ? (to as { agentId: string }).agentId
121        : ''
122  if (!key) return null
123  if (agents.some(a => a.id === key)) return key
124  const named = agents.filter(a => a.label === key)
125  return named.length === 1 ? named[0]!.id : null
126}
127
128// A new subagent: it is added under its parent, and the parent opens a spawn burst and a wait.
129function spawnSignals(parentId: string, childId: string, label: string, at: number): Signal[] {
130  return [
131    { type: 'agent-added', id: childId, label, parentId, at },
132    { type: 'exchange-open', fromId: parentId, toId: childId, reason: 'spawn', at },
133    { type: 'exchange-open', fromId: parentId, toId: childId, reason: 'waiting', at },
134  ]
135}
136
137export function toSignals(eventName: string, e: EventInput, ctx: SignalContext): Signal[] {
138  switch (eventName) {
139    case 'session.start':
140      return [{ type: 'agent-added', id: MAIN_ID, label: 'main', parentId: null, at: ctx.at }]
141
142    case 'turn.start':
143      return [{ type: 'agent-state', id: MAIN_ID, state: 'in-progress', at: ctx.at }]
144
145    // A turn that ran in a subagent's loop (it carries that agent's id) is that agent's usage only;
146    // the main agent completes when its own turn does.
147    case 'turn.complete': {
148      const id = agentOf(e)
149      const usage = usageOf(e.usage)
150      const model = text((e.usage as { model?: unknown } | undefined)?.model)
151      const out: Signal[] = []
152      if (id === null) out.push({ type: 'agent-state', id: MAIN_ID, state: 'completed', at: ctx.at })
153      if (usage) {
154        out.push({ type: 'agent-usage', id: id ?? MAIN_ID, usage, at: ctx.at })
155        if (model) out.push({ type: 'agent-meta', id: id ?? MAIN_ID, model, at: ctx.at })
156      }
157      return out
158    }
159
160    // A model request is about to go out: the model it names, and one more step in the run.
161    case 'turn.step':
162      return [{ type: 'agent-step', id: agentOf(e) ?? MAIN_ID, model: text(e.model) || undefined, at: ctx.at }]
163
164    case 'tool.call': {
165      // A tool call is the agent working; it also resolves that agent's pending state.
166      const id = agentOf(e) ?? MAIN_ID
167      const working: Signal = { type: 'agent-state', id, state: 'in-progress', at: ctx.at }
168      const source = typeof e.tool === 'string' ? LISTENING_TOOLS[e.tool] : undefined
169      if (source === undefined) return [working]
170      // A watch or webhook registration: the agent now listens for that trigger (FR-010).
171      return [working, { type: 'agent-state', id, state: 'listening', listenSource: source, at: ctx.at }]
172    }
173
174    // An inbound delivery with an event: the target reacts under the event's source (FR-011).
175    case 'session.receive': {
176      if (!e.event || typeof e.event !== 'object') return []
177      const event = e.event as { source?: unknown }
178      const source = typeof event.source === 'string' && event.source.length > 0 ? event.source : 'external'
179      return [
180        {
181          type: 'agent-react',
182          id: agentOf(e) ?? MAIN_ID,
183          source,
184          flashMs: ctx.reactFlashMs ?? REACT_MS,
185          at: ctx.at,
186        },
187      ]
188    }
189
190    case 'classic.PermissionRequest':
191    case 'classic.Elicitation':
192      return [{ type: 'agent-state', id: pendingOwner(e, ctx), state: 'pending', at: ctx.at }]
193
194    case 'classic.Notification': {
195      const kind = typeof e.notification_type === 'string' ? e.notification_type : ''
196      if (!PROMPT_NOTIFICATIONS.includes(kind)) return []
197      return [{ type: 'agent-state', id: pendingOwner(e, ctx), state: 'pending', at: ctx.at }]
198    }
199
200    case 'classic.ElicitationResult':
201    case 'prompt.submit':
202      return clearPending(ctx)
203
204    // Spawn: the engine answers the new agent's id only after the spawn, so the hook passes it in.
205    case 'agent.spawn': {
206      const childId = text(e.agentId)
207      if (!childId) return []
208      const parent = text(e.parentAgentId) || MAIN_ID
209      const label = text(e.description) || text(e.subagentType) || childId
210      const model = text(e.model) || text(e.parentModel)
211      return [
212        ...spawnSignals(parent, childId, label, ctx.at),
213        { type: 'agent-meta', id: childId, model: model || undefined, addressable: e.isTeammate === true, at: ctx.at },
214      ]
215    }
216
217    case 'classic.SubagentStart': {
218      const childId = text(e.agent_id)
219      if (!childId) return []
220      const parent = text(e.parentId) || MAIN_ID
221      const label = text(e.description) || text(e.agent_type) || childId
222      return [
223        ...spawnSignals(parent, childId, label, ctx.at),
224        ...(text(e.model) ? [{ type: 'agent-meta' as const, id: childId, model: text(e.model), at: ctx.at }] : []),
225      ]
226    }
227
228    // Stop: the wait ends, the agent ends by its status, and its result burst returns to the parent.
229    case 'classic.SubagentStop': {
230      const childId = text(e.agent_id)
231      if (!childId) return []
232      const parent = text(e.parentId) || MAIN_ID
233      return [
234        { type: 'exchange-close', fromId: parent, toId: childId, reason: 'waiting', at: ctx.at },
235        { type: 'agent-ended', id: childId, state: endStateOf(text(e.status)), at: ctx.at },
236        { type: 'exchange-open', fromId: parent, toId: childId, reason: 'result', at: ctx.at },
237      ]
238    }
239
240    case 'session.send': {
241      const sender = agentOf(e) ?? MAIN_ID
242      const recipient = resolveAgent(e.to, ctx.agents)
243      if (!recipient || recipient === sender) return []
244      return [{ type: 'exchange-open', fromId: sender, toId: recipient, reason: 'message', at: ctx.at }]
245    }
246
247    case 'classic.TeammateIdle': {
248      const id = agentOf(e) ?? resolveAgent(e.teammate_name, ctx.agents)
249      if (!id) return []
250      return [{ type: 'agent-state', id, state: 'idle', at: ctx.at }]
251    }
252
253    default:
254      return []
255  }
256}
257
258// The engine's agent list as a reconcile: list status wins (contracts/event-mapping.md). Children of
259// an agent that has ended lose their waiting exchange, since their SubagentStop may never arrive.
260export function reconcileFromList(listed: ListedAgent[], at: number): Signal[] {
261  const items = listed.map(info => ({
262    id: info.id,
263    label: info.description || info.type || info.id,
264    parentId: info.parentId || MAIN_ID,
265    state: listStateOf(info.status),
266  }))
267  // What the list knows about an agent's origin: a name or teammate address makes it reusable, and a
268  // teammate or an agent a plugin started has no orchestrator among the agents drawn here.
269  const metas: Signal[] = listed.flatMap(info => {
270    const addressable = Boolean(info.name || info.teammateId)
271    const independent = Boolean(info.teammateId)
272    if (!addressable && !info.spawnedBy) return []
273    return [
274      {
275        type: 'agent-meta' as const,
276        id: info.id,
277        addressable: addressable || undefined,
278        independent: independent || undefined,
279        spawnedBy: info.spawnedBy ?? undefined,
280        at,
281      },
282    ]
283  })
284  const closes: Signal[] = []
285  for (const item of items) {
286    if (TERMINAL_STATES.includes(item.state)) {
287      closes.push({ type: 'exchange-close', fromId: item.parentId, toId: item.id, reason: 'waiting', at })
288    }
289  }
290  return [{ type: 'reconcile', at, listed: items }, ...metas, ...closes]
291}
292
src/context.ts 13 lines
1// A rough count of the tokens in a conversation, from its text. The engine does not report a
2// subagent's context window while it runs, so the pane estimates it (about 3.5 characters a token).
3const CHARS_PER_TOKEN = 3.5
4
5export function estimateContextTokens(messages: ReadonlyArray<{ content?: unknown }>): number {
6  let chars = 0
7  for (const message of messages) {
8    const content = message.content
9    chars += typeof content === 'string' ? content.length : JSON.stringify(content ?? '').length
10  }
11  return Math.round(chars / CHARS_PER_TOKEN)
12}
13
src/view.tsx 221 lines
1// Scene -> element tree (contracts/pane-render.md). JSX compiles to the engine's global `h`;
2// this module neither declares nor imports it. Box and Text come from $.ui.resolve(e).
3//
4// Two layers: the background (connectors, streams, the `+N done` line) is rows of text, and every
5// figure sits on top as an absolutely positioned box so it can carry a hover. The hover card is its
6// own box at the top level, in the figure's hover group, so no later figure can paint over it.
7import type { Figure, Scene } from './layout'
8import { stream } from './particles'
9import { BACKGROUND_COLOUR, BACKGROUND_COLOUR_DARK, renderCells, STATE_COLOUR, STATE_COLOUR_DARK } from './sprites'
10import { wrap } from './tiers'
11
12// An element constructor from the engine's element table. Typed loosely: the engine checks its props.
13// eslint-disable-next-line @typescript-eslint/no-explicit-any
14type Tag = (props: any) => any
15export type Tags = { Box: Tag; Text: Tag }
16
17// One screen cell: a character plus the style it is drawn in.
18type Cell = { ch: string; color?: string; dim?: boolean }
19
20const BLANK: Cell = { ch: ' ' }
21
22// The eye colour: bright against both the body colour and its darker fill.
23export const EYE_COLOUR = 'white'
24// The grey a stale session group is drawn in (dimmed, spec 002).
25export const STALE_COLOUR = '#5a5a5a'
26
27// Paint the background layer onto a cell grid: connectors, then streams, then the overflow line.
28export function paint(scene: Scene): Cell[][] {
29  const { columns, rows } = scene.viewport
30  const width = Math.max(
31    0,
32    ...scene.streams.map(s => s.x + s.width),
33    ...scene.connectors.map(c => c.x + 1),
34    ...scene.figures.map(f => f.x + f.width),
35    ...scene.lines.map(l => l.segments.reduce((n, s) => n + [...s.text].length, 0)),
36  )
37  const height = Math.max(
38    0,
39    ...scene.figures.map(f => f.y + f.height),
40    ...scene.streams.map(s => s.row + 1),
41    ...scene.connectors.map(c => c.y + 1),
42    ...scene.lines.map(l => l.row + 1),
43    scene.overflowRow + 1,
44  )
45  const grid: Cell[][] = Array.from({ length: Math.min(height, rows) }, () =>
46    Array.from({ length: Math.min(width, columns) }, () => BLANK),
47  )
48
49  for (const c of scene.connectors) if (grid[c.y]?.[c.x]) grid[c.y]![c.x] = { ch: '│', dim: true }
50
51  for (const s of scene.streams) {
52    const glyphs = [...stream(s.width, scene.tick)]
53    glyphs.forEach((ch, i) => {
54      if (grid[s.row]?.[s.x + i]) grid[s.row]![s.x + i] = { ch, color: 'cyan' }
55    })
56  }
57
58  // Group headers and their `+N done` lines (spec 002): text in its own style, clipped to the pane.
59  for (const line of scene.lines) {
60    let x = 0
61    for (const segment of line.segments) {
62      for (const ch of segment.text) {
63        if (grid[line.row]?.[x]) grid[line.row]![x] = { ch, color: segment.color, dim: segment.dim }
64        x++
65      }
66    }
67  }
68
69  if (scene.overflowRow >= 0 && grid[scene.overflowRow]) {
70    const line = `+${scene.collapsed} done`
71    ;[...line].forEach((ch, i) => {
72      if (grid[scene.overflowRow]![i]) grid[scene.overflowRow]![i] = { ch, dim: true }
73    })
74  }
75  return grid
76}
77
78// Consecutive cells with the same style become one Text element.
79function runsOf(cells: Cell[]): Cell[][] {
80  const runs: Cell[][] = []
81  for (const cell of cells) {
82    const last = runs[runs.length - 1]
83    if (last && last[0]!.color === cell.color && last[0]!.dim === cell.dim) last.push(cell)
84    else runs.push([cell])
85  }
86  return runs
87}
88
89// A text run of one figure row: same foreground and background colour.
90type Run = { text: string; color?: string; background?: string }
91
92// The rows of a figure's sprite as coloured runs. The fraction of the context window in use fills the
93// body from the feet up in the darker shade of the state colour; eyes stay bright.
94export function spriteRuns(figure: Figure): Run[][] {
95  const cells = renderCells(figure.grid)
96  // A stale group's figures are dimmed to one grey, whatever their state (spec 002).
97  const body = figure.stale ? STALE_COLOUR : figure.background ? BACKGROUND_COLOUR : STATE_COLOUR[figure.state]
98  const dark = figure.stale
99    ? STALE_COLOUR
100    : figure.background
101      ? BACKGROUND_COLOUR_DARK
102      : (STATE_COLOUR_DARK[figure.state] ?? body)
103  const filledRows =
104    figure.fill === null ? 0 : figure.fill <= 0 ? 0 : Math.max(1, Math.round(figure.fill * cells.length))
105  return cells.map((row, r) => {
106    const ink = r >= cells.length - filledRows ? dark : body
107    const colourOf = (kind: 'ink' | 'eye' | null) => (kind === 'eye' ? EYE_COLOUR : kind === 'ink' ? ink : undefined)
108    const runs: Run[] = []
109    for (const cell of row) {
110      const color = colourOf(cell.fg)
111      const background = colourOf(cell.bg)
112      const last = runs[runs.length - 1]
113      if (last && last.color === color && last.background === background) last.text += cell.ch
114      else runs.push({ text: cell.ch, color, background })
115    }
116    return runs
117  })
118}
119
120const CARD_MAX_WIDTH = 44
121const CARD_MIN_WIDTH = 16
122
123// The hover card's lines and size: the full title wrapped, then the details.
124export function cardOf(figure: Figure, columns: number): { title: string[]; details: string[]; width: number; height: number } {
125  const inner = Math.max(8, Math.min(CARD_MAX_WIDTH, columns) - 4)
126  const title = wrap(figure.title, inner)
127  const details = figure.details.flatMap(line => wrap(line, inner))
128  const longest = Math.max(...title.map(l => [...l].length), ...details.map(l => [...l].length))
129  const width = Math.min(columns, Math.max(CARD_MIN_WIDTH, longest + 4))
130  return { title, details, width, height: title.length + details.length + 2 }
131}
132
133export function renderPane(scene: Scene, { Box, Text }: Tags) {
134  if (scene.empty) {
135    return (
136      <Box flexDirection="column">
137        <Text dimColor>No agents yet.</Text>
138      </Box>
139    )
140  }
141  if (scene.tooSmall) {
142    return (
143      <Box flexDirection="column">
144        <Text>{scene.summary}</Text>
145      </Box>
146    )
147  }
148
149  const { columns, rows } = scene.viewport
150  const grid = paint(scene)
151  const height = Math.max(grid.length, ...scene.figures.map(f => f.y + f.height))
152
153  return (
154    <Box flexDirection="column" width={columns} height={Math.min(rows, Math.max(height, 1))}>
155      {grid.map(cells => {
156        if (cells.length === 0) return <Text> </Text>
157        return (
158          <Box flexDirection="row">
159            {runsOf(cells).map(run => (
160              <Text color={run[0]!.color} dimColor={run[0]!.dim}>
161                {run.map(c => c.ch).join('')}
162              </Text>
163            ))}
164          </Box>
165        )
166      })}
167      {scene.figures.map((figure, i) => (
168        <Box
169          key={`f${i}`}
170          position="absolute"
171          left={figure.x}
172          top={figure.y}
173          width={figure.width}
174          height={figure.height}
175          flexDirection="column"
176          hover={{ scope: `fig${i}` }}
177        >
178          {spriteRuns(figure).map(runs => (
179            <Box flexDirection="row">
180              {runs.map(run => (
181                <Text color={run.color} backgroundColor={run.background}>
182                  {run.text}
183                </Text>
184              ))}
185            </Box>
186          ))}
187          <Text dimColor={figure.stale}>{figure.label.padEnd(figure.width)}</Text>
188        </Box>
189      ))}
190      {scene.figures.map((figure, i) => {
191        const card = cardOf(figure, columns)
192        const left = Math.max(0, Math.min(figure.x, columns - card.width))
193        // Below the figure when it fits, else above it.
194        const below = figure.y + figure.height
195        const top = below + card.height <= rows ? below : Math.max(0, figure.y - card.height)
196        return (
197          <Box
198            position="absolute"
199            left={left}
200            top={top}
201            width={card.width}
202            display="none"
203            hover={{ display: 'flex', scope: `fig${i}` }}
204            flexDirection="column"
205            borderStyle="round"
206            paddingX={1}
207          >
208            {card.title.map(line => (
209              <Text bold>{line}</Text>
210            ))}
211            {card.details.map(line => (
212              <Text dimColor>{line}</Text>
213            ))}
214          </Box>
215        )
216      })}
217      {scene.hidden > 0 && <Text dimColor>+{scene.hidden} not shown</Text>}
218    </Box>
219  )
220}
221
src/priority.ts 27 lines
1import type { AgentState } from '../types'
2
3// Highest precedence first (FR-013). failed and cancelled share a rank.
4const RANK: Record<AgentState, number> = {
5  pending: 7,
6  listening: 6,
7  'in-progress': 5,
8  failed: 4,
9  cancelled: 4,
10  completed: 3,
11  idle: 2,
12  unknown: 1,
13}
14
15export function resolveState(candidates: AgentState[]): AgentState {
16  let best: AgentState = 'unknown'
17  let bestRank = 0
18  for (const candidate of candidates) {
19    const rank = RANK[candidate]
20    if (rank > bestRank) {
21      best = candidate
22      bestRank = rank
23    }
24  }
25  return best
26}
27