SLOPSHOPPER

bus-band

Band above the Claude Code prompt with this session's pending Agent Team OS messages and the state of the sibling sessions (Onda)

bandcommandtoastprocesstimer
v2.6.0MITupdated 2026-10-25mariomosca/agent-team-os/mods/bus-band
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · bus-band
› 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 › /bus-band ⎿ bus-band: Banda del bus nascosta. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

bus-band

A Claude Code mod (Claude Code 2.1.287+) that draws a band above the prompt with what this session has to do on the Agent Team OS bus, the delegations it waits for, and the sibling sessions that need Mario.

Da fare (BR24-F6.8)

Da fare · 2                                                                 [-]
1: ✉ delega nuova   BR24-F6.7  Squadra nella banda solo con le eccezioni  da alita/work-hub  2 min
2: ◐ ci lavori      BR24-F6.6  Banda: in coda o ci lavora                  da alita/work-hub  8 min

On the model of the delegations below: one aligned line per message waiting for this session.

  • State for this session, computed by the centralino (stato_msg and riga on each pending message of the vista, centralino/palla.py, CENTRALINO.md §18), in glyph and word, never colour alone: ↩ risposta ricevuta (the delegator answered your question), ✉ delega nuova (not read yet), ≡ comunicazione da leggere, ◐ ci lavori (read), ? domanda in attesa (your question has no answer yet). Rows in this order, urgent/high first with the priority in a word (· urgente, · alta), then the oldest.
  • Plan code and title like the delegations (Orbit's step title, else the first sentence of the summary), the sender, the age.
  • A return on a delegation of this session is not here: it is in "Deleghe aperte" (✉ esito da leggere, ? domanda per te).
  • 1-9 or a click on a row puts /read <msg> in the prompt box, a click on the code /orbit <plan>; the digits go on in "Deleghe aperte", so a key is never taken twice. At most 5 rows, then +N, /inbox per la lista.
  • Scoping: agent from AGENT_MAP.json by cwd (longest rule), slug = workspace basename, the shared box plus this session's; messages whose context.project_path belongs to another workspace are counted apart (+N di altri workspace).
  • A toast when a new urgent/high message arrives. Polls every 20 s and at the end of every turn. /bus-band toggles the band.
  • Read-only on messages: it never moves, archives or writes a message (the only thing it ever writes is the Onda request file below). /read, /inbox and the MCP tools stay the way to act on them.
  • UI text is in Italian (the agents' working language). Honours AB_HOME like the shell lib (default ~/.agent-team-os).

Fonte: il centralino (BR24-F4.3)

From BR24 the band reads the bus from its centralino (agent-team-os/centralino, contract docs/CENTRALINO.md): one read-only op, vista, on $AB_HOME/centralino.sock (or AB_CENTRALINO_SOCK), once per round for all three sections. Liveness of the Squadra rows, pending messages and waits come from there, records in the bus file format, so the same parsers read them. The mod engine cannot speak line-JSON on a socket ($.http speaks HTTP), so the request goes through nc -U ($.process.run, 2 s timeout).

If the socket is missing or does not answer, the round reads today's files as before, and a dim line at the bottom of the band says so (Bus letto dai file: ...). The line only appears in a band that is already drawn: a missing centralino alone never raises it.

Agent from cwd now uses the longest matching rule on a folder boundary, the centralino's rule, instead of the first one.

Deleghe aperte (v3, BR24-F6.4)

Deleghe aperte · 2                                                         [-]
──────────────────────────────────────────────────────────────────────────────
1: ● tocca a Mario    ON24-F3   Hairline nella schermata vuota   kai/onda-electron  10 h
2: ○ Kai non aperto   AM18-F15  Analisi notturna del 24/10       kai/alita-mobile    3 min
──────────────────────────────────────────────────────────────────────────────
✉ 1 esito da leggere   ? 1 domanda per te        1-2 o clic: apri · clic sul codice: piano in Orbit

On the model of the Orbit pane: a title, rules, one aligned line per delegation, counts and keys at the bottom.

  • Source: the waits of this session in the centralino's vista, each with who holds the ball computed by the centralino (stato_palla and riga, centralino/palla.py, CENTRALINO.md §18): the band only draws it, the same state Orbit's office reads. Open ones, plus expired ones for a day. A centralino without stato_palla gives · stato non noto.
  • One line per delegation, always: newlines and runs of spaces become one space, the title is cut with … at the band's width (bodyColumns). The executor column goes when the band is under 80 columns.
  • Who holds the ball, in a word and a glyph, never colour alone:
  • ? domanda per te: the executor asked something and nobody answered;
  • ✉ esito da leggere: a return is in the box with no outcome;
  • ! scaduta: the deadline passed;
  • ● tocca a Mario: the last return was handled with riarma and in Orbit the linked step is Mario's, or Mario has an open step in the same phase;
  • ⧗ in coda: Kai occupato: the executor's session is alive and working, but has not read the delegation yet (no bus_read, no return, no wake delivered to it, BR24-F6.6): it is on something else;
  • ◐ Kai ci lavora, ◌ Kai fermo: the executor's session is alive, working (and has the delegation) or not;
  • ✓ Kai ha consegnato: the last return was re-armed, the executor is not working and Orbit names no step of Mario's: the executor is done for now, the ball is outside it;
  • ○ Kai non aperto: no live session of the executor; ○ Kai non aperto qui · vivo in onda-electron (+1, +2 for more) when the agent is alive in other folders on the same machine. Rows in this order, then by age.
  • Plan code and title from the centralino's row: the code from the intent or the summary (ON24-F3, BR24-F6.4, wh17-f8.3b, any case), the title from the step (or phase) in Orbit, first clause only; without Orbit (the mini, no code) the first sentence of the summary.
  • Keys and clicks: ctrl+x tab gives the band the keys; 1-9 or a click on a row puts /read <msg> in the prompt box (the open question, the first unread return, else the delegation); a click on the code puts /orbit <plan>. A draft already in the box is never overwritten: a toast says what to type. The engine's [-] (ctrl+x ctrl+a) collapses the band.
  • A wake held back by a cap (tetto_task, tetto_coppia, tetto_orario) is said in words at the end of the title. A toast once when a wait expires.

Squadra: only what needs Mario (BR24-F6.7)

The band says what Mario has to do now; the whole team is in Orbit's office. Nothing for him:

Squadra: 4 vive · niente per te

Something for him, one aligned line per session:

Squadra: 4 vive · 3 per te
✎ testo fermo nella casella  leo/pm-os          da 12 min  [Vai al pannello]
⚑ aspetta un permesso        vera/growth        da 3 min   fuori dal mosaico [Rimetti nel mosaico]
⊘ senza canale di sveglia    kai/onda-electron  da 2 h
  • Exceptions, in this order and then the longest waiting: ✎ testo fermo nella casella (text in the prompt box with no Enter), ⚑ aspetta un permesso, ? aspetta una risposta (Onda's states, from the vista's copy of onda/sessions.json), ⊘ senza canale di sveglia (alive for the centralino but with no Onda pane and no tmux: a wake cannot reach it). Glyph and word, never colour alone. At most 4 rows, then +N.
  • Live count from the centralino's sessioni (it sees the sessions outside Onda too), else Onda's list. The current session is never listed nor counted (same cwd, or same agent and slug).
  • The section is absent with no other live session, or if Onda's file is missing, unreadable, of an unknown version, or its ondaPid is not alive (kill -0).
  • The pane button stays on the exception rows that have an Onda workspace: Vai al pannello, or Rimetti nel mosaico when the workspace is out of the mosaic.
  • Toast once per episode when a sibling session becomes stuck (not for sessions already stuck when this one starts: they are in the band).
  • /bus-band hides/shows the whole band; /bus-band squadra only the team section.
  • Delegated sessions: with SESSIONE_DELEGATA=1 in the session's environment (a session another agent opened through Onda for a task) the team section is never drawn and raises no toasts. The messages for that session stay.

The button

Shown only when this session runs inside Onda (ONDA_SOCKET set). What the mod engine allows: $.fs reads and writes, $.process.run runs a command by argv, $.http.fetch can use a Unix socket but speaks HTTP, while Onda's socket is JSON-RPC, so the mod cannot call window.mountWorkspace directly. The button therefore writes $AB_HOME/onda/requests/req-<ts>-<rand>.json ({"action":"mount","workspaceId":"…"}): temp file, then mv through $.process.run ($.fs has no rename), so Onda never reads half a file. Onda consumes and deletes it. If Onda is not watching the folder, the request just sits there.

Install

The mod is its own plugin, separate from the main agent-team-os plugin, so a manual install (hooks registered in settings.json) never gets its hooks registered twice.

With install.sh (manual install): the installer copies it to ~/.claude/mods/bus-band/. Load it in every session by adding the folder to CLAUDE_CODE_PLUGIN_DIRS in the env block of ~/.claude/settings.json:

{ "env": { "CLAUDE_CODE_PLUGIN_DIRS": "~/.claude/mods/bus-band" } }

One session only: claude --plugin-dir /path/to/agent-team-os/mods/bus-band.

Security

Mods are not sandboxed: they run with Claude Code's own access. This one reads ~/.agent-team-os/ (AB_HOME) and ONDA_SOCKET, makes no network call, and runs only nc -U on the centralino socket (read-only vista), kill -0 <pid> (is Onda alive), mkdir -p and mv inside onda/requests/ (the button). It writes only there, and the prompt box when a row is opened. Check with claude plugin validate mods/bus-band, which lists every engine call and env variable the module touches.

Develop

claude plugin validate mods/bus-band   # manifest, hooks, calls, state contract
claude plugin test mods/bus-band       # hooks/bus.test.ts, hooks/team.test.ts, hooks/waits.test.ts and hooks/register.test.tsx (band with and without SESSIONE_DELEGATA): cwd→agent, slug, scoping, sort, sessions.json parse, team order, self exclusion

The pure bus logic lives in hooks/bus.ts (mirrors scripts/agent-team-os-lib.sh); hooks/register.tsx holds the hooks and the drawing; hooks/team.ts is the pure team logic. Known gap: the shell lib also matches the realpath of the cwd; the mod matches the cwd Claude Code reports, which is already resolved in practice.

Source 6 files
hooks/register.tsx 547 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { BusMessage, BusSnapshot, TeamSnapshot, WaitRow, WaitsSnapshot } from '../types'
5import {
6  PRIORITY_LABEL,
7  agentForCwd,
8  isPressing,
9  parseMessage,
10  slugForCwd,
11  sortMessages,
12  todoHeadline,
13  todoRows,
14  workspaceMatch,
15} from './bus'
16import {
17  exceptionRows,
18  isSelf,
19  orderTeam,
20  parseSessions,
21  requestBody,
22  requestName,
23  stuckKeys,
24  teamHeadline,
25  toastText,
26} from './team'
27import { orderRows, orderWaits, parseWait, toDelegationRow, waitsFooter, waitsHeadline } from './waits'
28import type { Wait } from './waits'
29import { fallbackText, inboxOf, liveCountOf, noChannelOf, parseVista, sessionsOf, vistaRequest, waitsOf } from './vista'
30import type { Vista } from './vista'
31
32const snapshot = atom({ plugin: 'bus-band', key: 'snapshot' } as const, null)
33const isHidden = atom({ plugin: 'bus-band', key: 'isHidden' } as const, false)
34
35const team = atom({ plugin: 'bus-band', key: 'team' } as const, null)
36const isTeamHidden = atom({ plugin: 'bus-band', key: 'isTeamHidden' } as const, false)
37
38const waits = atom({ plugin: 'bus-band', key: 'waits' } as const, null)
39
40// BR24-F4.3: why this round read the files instead of the centralino (null when it read the centralino).
41const fallback = atom({ plugin: 'bus-band', key: 'fallback' } as const, null)
42
43const POLL_MS = 20_000
44const VISTA_TIMEOUT_MS = 2_000
45const TODO_SHOWN = 5
46const TEAM_SHOWN = 4
47const WAITS_SHOWN = 5
48
49const busRoot = async ($: EngineInterface) => {
50  const busHome = await $.env.get('AB_HOME')
51  const home = await $.env.get('HOME')
52  if (busHome === undefined && home === undefined) return null
53
54  return busHome ?? `${home}/.agent-team-os`
55}
56
57// The bus centralino's vista (BR24-F4.3), one call per round for the three sections.
58// Null with the reason when the daemon is not there or does not answer: the round
59// reads today's files instead and the band says so.
60type Source = { vista: Vista } | { vista: null; why: string }
61
62const loadVista = async ($: EngineInterface): Promise<Source> => {
63  const root = await busRoot($)
64  if (root === null) return { vista: null, why: 'nessuna cartella del bus' }
65  const sock = (await $.env.get('AB_CENTRALINO_SOCK')) ?? `${root}/centralino.sock`
66  if (!(await $.fs.exists(sock))) return { vista: null, why: 'il centralino del bus non è attivo' }
67  const id = `r-band-${Math.random().toString(36).slice(2, 8)}`
68  const out = await $.process
69    .run(['nc', '-U', sock], { stdin: vistaRequest(id), timeoutMs: VISTA_TIMEOUT_MS })
70    .catch(() => null)
71  if (out === null || out.exitCode !== 0) return { vista: null, why: 'il centralino del bus non risponde' }
72  const parsed = parseVista(out.stdout)
73
74  return 'vista' in parsed ? { vista: parsed.vista } : { vista: null, why: parsed.error }
75}
76
77// The team as Onda sees it. Null (section absent) when the file is missing,
78// unusable, or written by an Onda that is no longer alive, and in a session another
79// agent opened for a delegated task (SESSIONE_DELEGATA=1): there it is only noise.
80const scanTeam = async ($: EngineInterface, vista: Vista | null): Promise<TeamSnapshot | null> => {
81  if ((await $.env.get('SESSIONE_DELEGATA')) === '1') return null
82  const root = await busRoot($)
83  if (root === null) return null
84
85  // The centralino already checked that Onda runs and the file is fresh.
86  let parsed = vista !== null ? sessionsOf(vista) : null
87  if (vista === null) {
88    const file = `${root}/onda/sessions.json`
89    if (!(await $.fs.exists(file))) return null
90    parsed = parseSessions(await $.fs.read(file))
91    if (parsed === null) return null
92    const alive = await $.process.run(['kill', '-0', String(parsed.ondaPid)])
93    if (alive.exitCode !== 0) return null
94  }
95  if (parsed === null) return null
96
97  const cwd = await $.session.cwd()
98  const map = JSON.parse(await $.fs.read(`${root}/AGENT_MAP.json`))
99  const agent = agentForCwd(map.rules ?? [], cwd) ?? ''
100  const slug = slugForCwd(cwd)
101  const canMount = (await $.env.get('ONDA_SOCKET')) !== undefined
102  const now = Date.now()
103  const others = orderTeam(parsed.sessions, s => isSelf(s, cwd, agent, slug))
104  // BR24-F6.7: the live count and the sessions without a channel come from the
105  // centralino (it sees the sessions outside Onda too); without it, Onda's list.
106  const live = Math.max(vista !== null ? liveCountOf(vista, agent, slug) : 0, others.length)
107  if (live === 0 && others.length === 0) return null
108  const rows = exceptionRows(others, vista !== null ? noChannelOf(vista, agent, slug) : [], now, canMount)
109
110  return {
111    headline: teamHeadline(live, rows.length),
112    rows: rows.slice(0, TEAM_SHOWN),
113    hidden: Math.max(0, rows.length - TEAM_SHOWN),
114    sessions: others,
115  }
116}
117
118// The results this session waits for (bus v2.6). Null when there are none.
119const scanWaits = async ($: EngineInterface, vista: Vista | null): Promise<WaitsSnapshot | null> => {
120  const root = await busRoot($)
121  if (root === null) return null
122  const cwd = await $.session.cwd()
123  const map = JSON.parse(await $.fs.read(`${root}/AGENT_MAP.json`))
124  const agent = agentForCwd(map.rules ?? [], cwd)
125  if (agent === undefined) return null
126
127  const texts: string[] = []
128  if (vista !== null) {
129    texts.push(...waitsOf(vista, agent, slugForCwd(cwd)))
130  } else {
131    const dir = `${root}/waits/${agent}/@${slugForCwd(cwd)}`
132    if (!(await $.fs.exists(dir))) return null
133    for (const entry of await $.fs.list(dir)) {
134      if (entry.kind !== 'file' || !/^[^.].*\.json$/.test(entry.name)) continue
135      texts.push(await $.fs.read(`${dir}/${entry.name}`))
136    }
137  }
138  const found: Wait[] = []
139  for (const text of texts) {
140    const w = parseWait(text)
141    if (w !== null) found.push(w)
142  }
143  const now = Date.now()
144  const ordered = orderWaits(found, now)
145  if (ordered.length === 0) return null
146
147  const rows = orderRows(ordered.map(w => toDelegationRow(w, now)))
148
149  return {
150    headline: waitsHeadline(ordered),
151    rows: rows.slice(0, WAITS_SHOWN),
152    hidden: Math.max(0, rows.length - WAITS_SHOWN),
153    footer: waitsFooter(rows),
154    expired: ordered.filter(w => w.state === 'expired').map(w => w.taskId),
155  }
156}
157
158// A row opens in the prompt box, for the person to send: `/read <msg>` or
159// `/orbit <plan>`. A draft already there is never overwritten.
160const openInPrompt = async ($: EngineInterface, text: string) => {
161  const box = await $.prompt.read().catch(() => null)
162  if (box !== null && box.text.trim() !== '') {
163    $.ui.toast(`La casella ha già del testo: ${text}`)
164
165    return
166  }
167  await $.prompt.fill({ text, mode: 'replace' }).catch(() => $.ui.toast(text))
168}
169
170// The mod cannot open Onda's socket (JSON-RPC; $.http speaks HTTP), so the
171// request is a file Onda consumes. Temp name first, then mv: Onda never sees half a file.
172const requestMount = async ($: EngineInterface, workspaceId: string) => {
173  const root = await busRoot($)
174  if (root === null) return
175  const dir = `${root}/onda/requests`
176  const rand = Math.random().toString(36).slice(2, 8)
177  const tmp = `${dir}/.tmp-${rand}.json`
178
179  await $.process.run(['mkdir', '-p', dir])
180  await $.fs.write(tmp, requestBody(workspaceId))
181  await $.process.run(['mv', tmp, `${dir}/${requestName(Date.now(), rand)}`])
182  $.ui.toast('Richiesta inviata a Onda')
183}
184
185const scan = async ($: EngineInterface, vista: Vista | null): Promise<BusSnapshot | null> => {
186  // Same bus home as the shell lib: AB_HOME, else ~/.agent-team-os.
187  const busHome = await $.env.get('AB_HOME')
188  const home = await $.env.get('HOME')
189  if (busHome === undefined && home === undefined) return null
190  const root = busHome ?? `${home}/.agent-team-os`
191  const cwd = await $.session.cwd()
192
193  const map = JSON.parse(await $.fs.read(`${root}/AGENT_MAP.json`))
194  const agent = agentForCwd(map.rules ?? [], cwd)
195  if (agent === undefined) return null
196  const slug = slugForCwd(cwd)
197
198  // Shared root (messages to the bare agent name) plus this session's own dir.
199  const found: [string, string][] = []
200  if (vista !== null) {
201    found.push(...inboxOf(vista, agent, slug))
202  } else {
203    for (const dir of [`${root}/inboxes/${agent}`, `${root}/inboxes/${agent}/@${slug}`]) {
204      if (!(await $.fs.exists(dir))) continue
205      for (const entry of await $.fs.list(dir)) {
206        if (entry.kind !== 'file' || !/^msg-.*\.json$/.test(entry.name)) continue
207        found.push([await $.fs.read(`${dir}/${entry.name}`), entry.name])
208      }
209    }
210  }
211  const messages: BusMessage[] = []
212  let elsewhere = 0
213  for (const [text, name] of found) {
214    const parsed = parseMessage(text, name)
215    if (parsed === null) continue
216    if (workspaceMatch(parsed.projectPath, cwd) === 'elsewhere') {
217      elsewhere += 1
218    } else {
219      messages.push(parsed.message)
220    }
221  }
222
223  const sorted = sortMessages(messages)
224
225  return { agent, slug, messages: sorted, rows: todoRows(sorted, Date.now()), elsewhere }
226}
227
228// Ids already seen, so only a message that arrives later raises a toast.
229let seen: Set<string> | null = null
230
231// Stuck episodes already announced (session:state), so a toast fires once per episode.
232let seenStuck: Set<string> | null = null
233
234// Expired waits already announced, so the deadline toasts once.
235let seenExpired: Set<string> | null = null
236
237async function refreshWaits($: EngineInterface, vista: Vista | null) {
238  const next = await scanWaits($, vista).catch(() => null)
239  const expired = next?.expired ?? []
240  const fresh = seenExpired === null ? [] : expired.filter(id => !seenExpired!.has(id))
241  seenExpired = new Set(expired)
242
243  await update($, waits, () => next)
244  if (fresh.length > 0) $.ui.toast(`Bus: nessun esito entro la scadenza per ${fresh.join(', ')}`)
245}
246
247async function refreshTeam($: EngineInterface, vista: Vista | null) {
248  const next = await scanTeam($, vista).catch(() => null)
249  const keys = stuckKeys(next?.sessions ?? [])
250  const fresh = seenStuck === null ? [] : [...keys].filter(([, episode]) => !seenStuck!.has(episode))
251  seenStuck = new Set(keys.values())
252
253  await update($, team, () => next)
254  const s = next?.sessions.find(x => fresh.some(([id]) => id === x.sessionId))
255  if (s !== undefined) $.ui.toast(toastText(s))
256}
257
258async function refresh($: EngineInterface) {
259  const source = await loadVista($).catch(() => ({ vista: null, why: 'il centralino del bus non risponde' }))
260  await update($, fallback, () => (source.vista === null ? fallbackText(source.why) : null))
261  await refreshTeam($, source.vista)
262  await refreshWaits($, source.vista)
263  const next = await scan($, source.vista)
264  const ids = new Set(next?.messages.map(m => m.id) ?? [])
265  const fresh = seen === null ? [] : (next?.messages ?? []).filter(m => !seen!.has(m.id))
266  seen = ids
267
268  await update($, snapshot, () => next)
269  if (fresh.length > 0) await update($, isHidden, () => false)
270
271  const m = fresh.find(isPressing)
272  if (m !== undefined) {
273    $.ui.toast(`Bus: ${PRIORITY_LABEL[m.priority]} da ${m.from} (${m.intent})`)
274  }
275}
276
277export const register: Register = on => {
278  on('session.start', async ($, e, next) => {
279    await $.command.register({
280      name: 'bus-band',
281      description: 'Mostra o nasconde la banda del bus; "squadra" solo la sezione squadra',
282      argumentHint: '[squadra]',
283    })
284    await refresh($).catch(() => {})
285    $.clock.every(POLL_MS, () => refresh($).catch(() => {}))
286
287    return next(e)
288  })
289
290  on('turn.complete', async ($, e, next) => {
291    await refresh($).catch(() => {})
292
293    return next(e)
294  })
295
296  on('command.run', { command: 'bus-band' }, async ($, e) => {
297    if (e.args.trim() === 'squadra') {
298      const teamHidden = await read($, isTeamHidden)
299      await update($, isTeamHidden, () => !teamHidden)
300
301      return { text: teamHidden ? 'Sezione squadra visibile.' : 'Sezione squadra nascosta.' }
302    }
303
304    const hidden = await read($, isHidden)
305    await update($, isHidden, () => !hidden)
306    await refresh($).catch(() => {})
307
308    return { text: hidden ? 'Banda del bus visibile.' : 'Banda del bus nascosta.' }
309  })
310
311  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
312    const snap = await read($, snapshot)
313    const squadra = await read($, team)
314    const showTeam = squadra !== null && !(await read($, isTeamHidden))
315    const showMessages = snap !== null && snap.rows.length > 0
316    const attese = await read($, waits)
317    const showWaits = attese !== null
318    const isQuiet =
319      e.props.hasSurvey || (!showMessages && !showTeam && !showWaits) || (await read($, isHidden))
320
321    if (isQuiet) return next(e)
322
323    const { Box, Button, Text } = $.ui.resolve(e)
324    // Only inside a band already drawn: a missing centralino alone never raises it.
325    const viaFile = await read($, fallback)
326
327    return (
328      <Box flexDirection="column">
329        {showMessages ? todoBlock($, snap, e.props.bodyColumns, Box, Button, Text) : null}
330        {showWaits
331          ? waitsBlock($, attese, e.props.bodyColumns, showMessages ? Math.min(TODO_SHOWN, snap.rows.length) : 0, Box, Button, Text)
332          : null}
333        {showTeam ? teamBlock($, squadra, Box, Button, Text) : null}
334        {viaFile !== null ? <Text dimColor>{viaFile}</Text> : null}
335      </Box>
336    )
337  })
338}
339
340type Els = ReturnType<EngineInterface['ui']['resolve']>
341
342// BR24-F6.8, like the delegations: what this session has to do, one aligned line
343// per message (state in glyph and word, plan code, title, sender, age). A digit or a
344// click puts `/read <msg>` in the prompt; a click on the code puts `/orbit <plan>`.
345// The digits go on in "Deleghe aperte" below, so a key is never taken twice.
346const todoBlock = (
347  $: EngineInterface,
348  snap: BusSnapshot,
349  columns: number | undefined,
350  Box: Els['Box'],
351  Button: Els['Button'],
352  Text: Els['Text'],
353) => {
354  const width = Math.max(40, columns ?? 100)
355  const rows = snap.rows.slice(0, TODO_SHOWN)
356  const rest = snap.rows.length - rows.length
357  const labelW = Math.max(...rows.map(r => cells(r.label)))
358  const stateW = labelW + 4
359  const codeW = Math.max(0, ...rows.map(r => cells(r.code ?? '')))
360  const sinceW = Math.max(...rows.map(r => cells(r.since)))
361  const fromW = width >= 80 ? Math.min(24, Math.max(...rows.map(r => cells(r.from)))) : 0
362  const gaps = 2 + (codeW > 0 ? 2 : 0) + (fromW > 0 ? 2 : 0) + 1
363  const titleW = Math.max(8, width - stateW - codeW - fromW - sinceW - gaps)
364
365  return (
366    <Box flexDirection="column">
367      <Text bold>{todoHeadline(snap.rows, snap.elsewhere)}</Text>
368      {rows.map((r, i) => {
369        const open = () => void openInPrompt($, r.read)
370        const tone = TODO_COLOR[r.state]
371
372        return (
373          <Box key={r.key}>
374            <Button key={`read-${r.key}`} plain {...(i < 9 ? { hotkey: String(i + 1) } : {})} onPress={open}>
375              <Text bold={r.pressing || r.state === 'nuova' || r.state === 'risposta'} {...(tone !== undefined ? { color: tone } : { dimColor: true })}>
376                {r.glyph} {pad(r.label, labelW)}{'  '}
377              </Text>
378            </Button>
379            {codeW > 0 ? (
380              r.plan !== null ? (
381                <Button key={`plan-${r.key}`} plain onPress={() => void openInPrompt($, `/orbit ${r.plan}`)}>
382                  {pad(r.code ?? '', codeW)}
383                </Button>
384              ) : (
385                <Text>{' '.repeat(codeW)}</Text>
386              )
387            ) : null}
388            <Button key={`title-${r.key}`} plain onPress={open}>
389              {codeW > 0 ? '  ' : ''}
390              {pad(r.title, titleW)}
391              {fromW > 0 ? <Text dimColor>{`  ${pad(r.from, fromW)}`}</Text> : null}
392              <Text dimColor>{` ${r.since.padStart(sinceW)}`}</Text>
393            </Button>
394          </Box>
395        )
396      })}
397      {rest > 0 ? <Text dimColor>{`  +${rest}, /inbox per la lista`}</Text> : null}
398    </Box>
399  )
400}
401
402// Cells a string takes: one per code point (the band draws no wide glyphs).
403const cells = (text: string) => Array.from(text).length
404
405// `text` cut to `width` cells, `…` last when cut.
406const fit = (text: string, width: number) => {
407  if (width <= 0) return ''
408  const chars = Array.from(text)
409
410  return chars.length <= width ? text : `${chars.slice(0, width - 1).join('')}…`
411}
412
413const pad = (text: string, width: number) => {
414  const cut = fit(text, width)
415
416  return cut + ' '.repeat(Math.max(0, width - cells(cut)))
417}
418
419const TODO_COLOR: Partial<Record<string, string>> = {
420  nuova: 'warning',
421  risposta: 'warning',
422  lavori: 'success',
423}
424
425const STATE_COLOR: Partial<Record<WaitRow['state'], string>> = {
426  domanda: 'warning',
427  esito: 'warning',
428  scaduta: 'error',
429  mario: 'claude',
430  lavora: 'success',
431}
432
433// BR24-F6.4, on the model of the Orbit pane: a title, rules, one aligned line per
434// delegation (state in words and glyph, plan code, title, executor, age), counts
435// and keys at the bottom. A digit or a click on a row puts `/read <msg>` in the
436// prompt; a click on the code puts `/orbit <plan>`.
437const waitsBlock = (
438  $: EngineInterface,
439  attese: WaitsSnapshot,
440  columns: number | undefined,
441  first: number,
442  Box: Els['Box'],
443  Button: Els['Button'],
444  Text: Els['Text'],
445) => {
446  const width = Math.max(40, columns ?? 100)
447  const rows = attese.rows
448  const labelW = Math.max(...rows.map(r => cells(r.label)))
449  // Glyph, space, label, two spaces.
450  const stateW = labelW + 4
451  const codeW = Math.max(0, ...rows.map(r => cells(r.code ?? '')))
452  const sinceW = Math.max(...rows.map(r => cells(r.since)))
453  // The executor column goes first when the band is narrow.
454  const whoW = width >= 80 ? Math.min(24, Math.max(...rows.map(r => cells(r.who)))) : 0
455  const gaps = 2 + (codeW > 0 ? 2 : 0) + (whoW > 0 ? 2 : 0) + 1
456  const titleW = Math.max(8, width - stateW - codeW - whoW - sinceW - gaps)
457  const rule = <Text color="subtle">{'─'.repeat(width)}</Text>
458  const keys = Math.max(0, Math.min(9, first + rows.length) - first)
459  const hint = `${keys > 1 ? `${first + 1}-${first + keys}` : keys === 1 ? `${first + 1}` : ''}${keys > 0 ? ' o ' : ''}clic: apri · clic sul codice: piano in Orbit`
460
461  return (
462    <Box flexDirection="column">
463      <Text bold>{attese.headline}</Text>
464      {rule}
465      {rows.map((r, i) => {
466        const open = () => (r.read !== null ? void openInPrompt($, r.read) : undefined)
467        const tone = STATE_COLOR[r.state]
468
469        return (
470          <Box key={r.key}>
471            <Button key={`read-${r.key}`} plain {...(first + i < 9 ? { hotkey: String(first + i + 1) } : {})} onPress={open}>
472              <Text bold={r.alert || r.state === 'mario'} {...(tone !== undefined ? { color: tone } : { dimColor: true })}>
473                {r.glyph} {pad(r.label, labelW)}{'  '}
474              </Text>
475            </Button>
476            {codeW > 0 ? (
477              r.plan !== null ? (
478                <Button key={`plan-${r.key}`} plain onPress={() => void openInPrompt($, `/orbit ${r.plan}`)}>
479                  {pad(r.code ?? '', codeW)}
480                </Button>
481              ) : (
482                <Text>{' '.repeat(codeW)}</Text>
483              )
484            ) : null}
485            <Button key={`title-${r.key}`} plain onPress={open}>
486              {codeW > 0 ? '  ' : ''}
487              {pad(r.note === null ? r.title : `${r.title} (${r.note})`, titleW)}
488              {whoW > 0 ? <Text dimColor>{`  ${pad(r.who, whoW)}`}</Text> : null}
489              <Text dimColor>{` ${r.since.padStart(sinceW)}`}</Text>
490            </Button>
491          </Box>
492        )
493      })}
494      {attese.hidden > 0 ? <Text dimColor>{`  +${attese.hidden}, bus_inbox per la lista`}</Text> : null}
495      {rule}
496      <Box justifyContent="space-between">
497        <Text bold>{attese.footer}</Text>
498        <Text dimColor>{fit(hint, Math.max(0, width - cells(attese.footer) - 2))}</Text>
499      </Box>
500    </Box>
501  )
502}
503
504// BR24-F6.7: only what needs Mario. One line when nothing does; otherwise one
505// aligned line per session, glyph and word first (never colour alone), the pane
506// button on the right.
507const teamBlock = (
508  $: EngineInterface,
509  squadra: TeamSnapshot,
510  Box: Els['Box'],
511  Button: Els['Button'],
512  Text: Els['Text'],
513) => {
514  const labelW = Math.max(0, ...squadra.rows.map(r => cells(r.label)))
515  const nameW = Math.max(0, ...squadra.rows.map(r => cells(r.name)))
516  const sinceW = Math.max(0, ...squadra.rows.map(r => cells(r.since)))
517
518  return (
519    <Box flexDirection="column">
520      <Text bold>{squadra.headline}</Text>
521      {squadra.rows.map(r => (
522        <Box key={r.key}>
523          <Text bold color="warning" wrap="truncate-end">
524            {r.glyph} {pad(r.label, labelW)}
525          </Text>
526          <Text wrap="truncate-end">
527            {'  '}
528            {pad(r.name, nameW)}
529          </Text>
530          <Text dimColor>
531            {`  ${r.since === '' ? '' : `da ${r.since}`.padEnd(sinceW + 3)}`}
532            {r.unmounted ? '  fuori dal mosaico' : ''}{' '}
533          </Text>
534          {r.canMount && r.workspaceId !== null ? (
535            <Button
536              key={`mount-${r.key}`}
537              label={r.unmounted ? 'Rimetti nel mosaico' : 'Vai al pannello'}
538              onPress={() => requestMount($, r.workspaceId!)}
539            />
540          ) : null}
541        </Box>
542      ))}
543      {squadra.hidden > 0 ? <Text dimColor>  +{squadra.hidden}</Text> : null}
544    </Box>
545  )
546}
547
hooks/bus.ts 140 lines
1import type { BusMessage, Priority, TodoRow } from '../types'
2
3// Pure logic of the Agent Team OS bus, mirrored from
4// ~/.claude/scripts/agent-team-os-lib.sh (v1.4): agent from cwd, session slug,
5// workspace scoping. No `$` here, so the tests run it as is.
6
7export type AgentRule = { pattern: string; match?: string; agent: string }
8
9const PRIORITIES: readonly Priority[] = ['urgent', 'high', 'normal', 'low']
10
11// The longest matching pattern wins, on a folder boundary (/a/work-hub does not
12// match /a/work-hub-x): the centralino's rule (BR24, docs/CENTRALINO.md §2).
13export const agentForCwd = (rules: readonly AgentRule[], cwd: string) => {
14  const c = cwd.replace(/\/+$/, '')
15  let best: AgentRule | undefined
16  let bestLen = -1
17  for (const rule of rules) {
18    const p = rule.pattern.replace(/\/+$/, '')
19    if (c !== p && !c.startsWith(`${p}/`)) continue
20    if (p.length > bestLen) {
21      best = rule
22      bestLen = p.length
23    }
24  }
25
26  return best?.agent
27}
28
29export const slugForCwd = (cwd: string) => {
30  const base = cwd.replace(/\/+$/, '').split('/').pop() || 'root'
31
32  return base.toLowerCase().replace(/[^a-z0-9._-]/g, '-')
33}
34
35export const workspaceMatch = (projectPath: string, cwd: string) => {
36  if (projectPath === '') return 'global'
37  const p = projectPath.replace(/\/+$/, '')
38  const c = cwd.replace(/\/+$/, '')
39  const isHere = p === c || c.startsWith(`${p}/`) || p.startsWith(`${c}/`)
40
41  return isHere ? 'here' : 'elsewhere'
42}
43
44export type Parsed = { message: BusMessage; projectPath: string }
45
46export const parseMessage = (text: string, fallbackId: string): Parsed | null => {
47  try {
48    const raw = JSON.parse(text)
49    const priority = PRIORITIES.includes(raw.priority) ? raw.priority : 'normal'
50
51    return {
52      message: {
53        id: String(raw.id ?? fallbackId),
54        from: String(raw.from ?? '?'),
55        intent: String(raw.intent ?? raw.type ?? ''),
56        priority,
57        type: String(raw.type ?? ''),
58        ts: String(raw.ts ?? ''),
59        state: typeof raw.stato_msg === 'string' ? raw.stato_msg : null,
60        row: typeof raw.riga === 'object' && raw.riga !== null ? raw.riga : null,
61      },
62      projectPath: typeof raw.context?.project_path === 'string' ? raw.context.project_path : '',
63    }
64  } catch {
65    return null
66  }
67}
68
69// Most pressing first, newest first within a priority.
70export const sortMessages = (messages: readonly BusMessage[]) =>
71  [...messages].sort(
72    (a, b) =>
73      PRIORITIES.indexOf(a.priority) - PRIORITIES.indexOf(b.priority) ||
74      b.ts.localeCompare(a.ts),
75  )
76
77export const isPressing = (m: BusMessage) => m.priority === 'urgent' || m.priority === 'high'
78
79// Text labels, never colour alone: the person reading this is colour-blind.
80export const PRIORITY_LABEL: Record<Priority, string> = {
81  urgent: 'URGENTE',
82  high: 'ALTA',
83  normal: 'normale',
84  low: 'bassa',
85}
86
87// ---- BR24-F6.8: "Da fare", what this session has to do, one row per message ----
88// The centralino says the state of each message for this session (centralino/palla.py,
89// `stato_msg` and `riga`); here only the drawing data. A return on a delegation of this
90// session (`ritorno`) is not here: it is in "Deleghe aperte".
91
92export const isTodo = (m: BusMessage) => m.state !== 'ritorno'
93
94const age = (iso: string, now: number) => {
95  const t = Date.parse(iso)
96  const min = Number.isNaN(t) ? 0 : Math.max(0, Math.floor((now - t) / 60_000))
97
98  return min < 1 ? 'meno di 1 min' : min < 120 ? `${min} min` : `${Math.floor(min / 60)} h`
99}
100
101const text = (v: unknown) => (typeof v === 'string' && v !== '' ? v.replace(/\s+/g, ' ').trim() : null)
102
103export const toTodoRow = (m: BusMessage, now: number): TodoRow => {
104  const r = m.row ?? {}
105  const word = text(r.parola) ?? (m.type === '' ? 'messaggio' : m.type)
106  // Priority only when it matters, in a word.
107  const priority = m.priority === 'urgent' ? 'urgente' : m.priority === 'high' ? 'alta' : null
108
109  return {
110    key: m.id,
111    state: m.state ?? 'ignoto',
112    glyph: text(r.glifo) ?? '·',
113    label: priority === null ? word : `${word} · ${priority}`,
114    code: text(r.codice),
115    plan: text(r.piano),
116    title: text(r.titolo) ?? m.intent,
117    from: `da ${text(r.mittente) ?? m.from}`,
118    since: age(m.ts, now),
119    read: text(r.leggi) ?? `/read ${m.id}`,
120    pressing: isPressing(m),
121  }
122}
123
124const order = (m: BusMessage) => (typeof m.row?.ordine === 'number' ? m.row.ordine : 99)
125
126// Urgent and high first, then by state (what sets this session going first), then the oldest.
127export const todoRows = (messages: readonly BusMessage[], now: number) =>
128  messages
129    .filter(isTodo)
130    .map(m => ({ m, r: toTodoRow(m, now) }))
131    .sort(
132      (a, b) =>
133        Number(b.r.pressing) - Number(a.r.pressing) || order(a.m) - order(b.m) || a.m.ts.localeCompare(b.m.ts),
134    )
135    .map(x => x.r)
136
137export const todoHeadline = (rows: readonly TodoRow[], elsewhere: number) =>
138  `Da fare · ${rows.length}${elsewhere > 0 ? ` (+${elsewhere} di altri workspace)` : ''}`
139
140
hooks/team.ts 191 lines
1import type { TeamRow, TeamSession, TeamState } from '../types'
2
3// Pure logic of the "Squadra" section: parse $AB_HOME/onda/sessions.json
4// (schema/CONTRACT.md, "Onda → mod"), order it, say it in words. No `$` here.
5
6const STATES: readonly TeamState[] = [
7  'working',
8  'idle',
9  'waiting_permission',
10  'waiting_answer',
11  'pending_input',
12  'exited',
13]
14
15export const isStuck = (state: TeamState) =>
16  state === 'pending_input' || state === 'waiting_permission' || state === 'waiting_answer'
17
18export type SessionsFile = { ondaPid: number; sessions: TeamSession[] }
19
20const str = (v: unknown) => (typeof v === 'string' ? v : null)
21
22// The entries of sessions.json (or of the centralino's vista, which carries them as they are).
23export const parseSessionList = (list: readonly unknown[]): TeamSession[] => {
24  const sessions: TeamSession[] = []
25  for (const x of list) {
26    const s = (typeof x === 'object' && x !== null ? x : {}) as Record<string, unknown>
27    const sessionId = str(s.sessionId)
28    const workspaceId = str(s.workspaceId)
29    const slug = str(s.slug)
30    const cwd = str(s.cwd)
31    if (sessionId === null || workspaceId === null || slug === null || cwd === null) continue
32
33    sessions.push({
34      sessionId,
35      workspaceId,
36      agent: str(s.agent),
37      slug,
38      cwd,
39      // An unknown state is read as idle (contract §13).
40      state: STATES.includes(s.state as TeamState) ? (s.state as TeamState) : 'idle',
41      stateSince: str(s.stateSince) ?? '',
42      lastTool: str(s.lastTool),
43      mounted: s.mounted === true,
44      host: str(s.host) ?? 'laptop',
45    })
46  }
47
48  return sessions
49}
50
51// Null when the file is not usable: not JSON, unknown major version, no pid.
52export const parseSessions = (text: string): SessionsFile | null => {
53  try {
54    const raw = JSON.parse(text)
55    if (raw.v !== 1 || !Number.isInteger(raw.ondaPid) || !Array.isArray(raw.sessions)) return null
56
57    return { ondaPid: raw.ondaPid, sessions: parseSessionList(raw.sessions) }
58  } catch {
59    return null
60  }
61}
62
63const trim = (p: string) => p.replace(/\/+$/, '')
64
65export const isSelf = (s: TeamSession, cwd: string, agent: string, slug: string) =>
66  trim(s.cwd) === trim(cwd) || (s.agent === agent && s.slug === slug)
67
68export const minutesSince = (iso: string, now: number) => {
69  const t = Date.parse(iso)
70
71  return Number.isNaN(t) ? 0 : Math.max(0, Math.floor((now - t) / 60_000))
72}
73
74// Stuck and waiting first (longest first), then the rest by how long they have
75// been in their state. Exited sessions are not part of the team.
76export const orderTeam = (sessions: readonly TeamSession[], self: (s: TeamSession) => boolean) =>
77  sessions
78    .filter(s => s.state !== 'exited' && !self(s))
79    .sort(
80      (a, b) =>
81        Number(isStuck(b.state)) - Number(isStuck(a.state)) ||
82        (Date.parse(a.stateSince) || 0) - (Date.parse(b.stateSince) || 0),
83    )
84
85const duration = (min: number) => (min < 1 ? 'meno di 1 min' : min < 120 ? `${min} min` : `${Math.floor(min / 60)} h`)
86
87// The state in words, never colour alone (toasts and the old wording).
88export const describe = (s: TeamSession, now: number) => {
89  const min = minutesSince(s.stateSince, now)
90
91  switch (s.state) {
92    case 'pending_input':
93      return `TESTO FERMO da ${duration(min)}`
94    case 'waiting_permission':
95      return `aspetta un permesso da ${duration(min)}`
96    case 'waiting_answer':
97      return `aspetta una risposta da ${duration(min)}`
98    case 'working':
99      return s.lastTool === null ? 'lavora' : `lavora (${s.lastTool})`
100    default:
101      return 'in attesa'
102  }
103}
104
105// ---- BR24-F6.7: only the sessions that need Mario ----
106// The band says what Mario has to do now; Orbit's office gives the whole team.
107
108export type Exception = TeamRow['kind']
109
110// Glyph and word per exception, in the order they are shown: never colour alone.
111const EXCEPTION: Record<Exception, { glyph: string; label: string }> = {
112  testo: { glyph: '✎', label: 'testo fermo nella casella' },
113  permesso: { glyph: '⚑', label: 'aspetta un permesso' },
114  domanda: { glyph: '?', label: 'aspetta una risposta' },
115  canale: { glyph: '⊘', label: 'senza canale di sveglia' },
116}
117const ORDER: readonly Exception[] = ['testo', 'permesso', 'domanda', 'canale']
118
119const exceptionOf = (state: TeamState): Exception | null =>
120  state === 'pending_input' ? 'testo' : state === 'waiting_permission' ? 'permesso' : state === 'waiting_answer' ? 'domanda' : null
121
122// A bus session the centralino sees alive without a channel to wake it (not in Onda, no tmux).
123export type NoChannel = { agent: string; slug: string; since: string }
124
125export const exceptionRows = (
126  onda: readonly TeamSession[],
127  noChannel: readonly NoChannel[],
128  now: number,
129  canMount: boolean,
130): TeamRow[] => {
131  const rows: { row: TeamRow; min: number }[] = []
132  for (const s of onda) {
133    const kind = exceptionOf(s.state)
134    if (kind === null) continue
135    const min = minutesSince(s.stateSince, now)
136    rows.push({ min, row: {
137      key: s.sessionId,
138      kind,
139      ...EXCEPTION[kind],
140      name: `${s.agent ?? '?'}/${s.slug}`,
141      since: duration(min),
142      stuck: true,
143      unmounted: !s.mounted,
144      workspaceId: s.workspaceId,
145      canMount,
146    } })
147  }
148  for (const s of noChannel) {
149    const min = s.since === '' ? 0 : minutesSince(s.since, now)
150    rows.push({ min, row: {
151      key: `canale:${s.agent}/${s.slug}`,
152      kind: 'canale',
153      ...EXCEPTION.canale,
154      name: `${s.agent}/${s.slug}`,
155      since: s.since === '' ? '' : duration(min),
156      stuck: true,
157      unmounted: false,
158      workspaceId: null,
159      canMount: false,
160    } })
161  }
162
163  // By kind, then the one waiting longest.
164  return rows
165    .sort((a, b) => ORDER.indexOf(a.row.kind) - ORDER.indexOf(b.row.kind) || b.min - a.min)
166    .map(r => r.row)
167}
168
169export const teamHeadline = (live: number, exceptions: number) => {
170  const vive = live === 1 ? '1 viva' : `${live} vive`
171
172  return `Squadra: ${vive} · ${exceptions === 0 ? 'niente per te' : `${exceptions} per te`}`
173}
174
175// Episode key: a session toasts once per (session, state) until it leaves it.
176export const stuckKeys = (sessions: readonly TeamSession[]) =>
177  new Map(sessions.filter(s => isStuck(s.state)).map(s => [s.sessionId, `${s.sessionId}:${s.state}`]))
178
179export const toastText = (s: TeamSession) => {
180  const who = `${s.agent ?? '?'}/${s.slug}`
181
182  return s.state === 'pending_input'
183    ? `Squadra: ${who}, testo fermo senza Invio`
184    : `Squadra: ${who} aspetta ${s.state === 'waiting_answer' ? 'una risposta' : 'un permesso'}`
185}
186
187// requests/ — mod → Onda. The temp name must not start with "req-".
188export const requestName = (ts: number, rand: string) => `req-${ts}-${rand}.json`
189export const requestBody = (workspaceId: string) =>
190  JSON.stringify({ action: 'mount', workspaceId })
191
hooks/waits.ts 153 lines
1import type { WaitRow } from '../types'
2
3// Pure logic of the "Deleghe aperte" section: the waits of this session from the
4// centralino's vista, each with who holds the ball computed there. No `$` here.
5
6export type Wait = {
7  taskId: string
8  description: string
9  delegatedTo: string | null
10  createdAt: string
11  state: string
12  expiredAt: string | null
13  // BR24-F6.4: the delegation message and the session that executes it.
14  msgId: string | null
15  executor: string | null
16  // BR24-F6.7: who holds the ball and the row, as the centralino's vista computed them.
17  ball: string | null
18  row: Record<string, unknown> | null
19}
20
21const str = (v: unknown) => (typeof v === 'string' && v !== '' ? v : null)
22
23// A wait the band shows: still expected, or expired in the last day.
24const SHOWN_STATES = new Set(['expected', 'expired'])
25const EXPIRED_SHOWN_MS = 24 * 60 * 60_000
26
27export const parseWait = (text: string): Wait | null => {
28  try {
29    const raw = JSON.parse(text)
30    const taskId = str(raw.task_id)
31    const state = str(raw.state)
32    if (taskId === null || state === null || !SHOWN_STATES.has(state)) return null
33
34    return {
35      taskId,
36      description: str(raw.description) ?? '',
37      delegatedTo: str(raw.delegated_to),
38      createdAt: str(raw.created_at) ?? '',
39      state,
40      expiredAt: str(raw.expired_at),
41      msgId: str(raw.delegation?.msg_id),
42      executor: str(raw.executor_session) ?? str(raw.delegated_to),
43      ball: str(raw.stato_palla),
44      row: typeof raw.riga === 'object' && raw.riga !== null ? raw.riga : null,
45    }
46  } catch {
47    return null
48  }
49}
50
51const minutes = (iso: string, now: number) => {
52  const t = Date.parse(iso)
53
54  return Number.isNaN(t) ? 0 : Math.max(0, Math.floor((now - t) / 60_000))
55}
56
57const age = (min: number) =>
58  min < 1 ? 'meno di 1 min' : min < 120 ? `${min} min` : `${Math.floor(min / 60)} h`
59
60export const visible = (w: Wait, now: number) =>
61  w.state === 'expected' || (w.expiredAt !== null && now - Date.parse(w.expiredAt) < EXPIRED_SHOWN_MS)
62
63// Expired first, then the oldest wait.
64export const orderWaits = (waits: readonly Wait[], now: number) =>
65  waits
66    .filter(w => visible(w, now))
67    .sort(
68      (a, b) =>
69        Number(b.state === 'expired') - Number(a.state === 'expired') ||
70        a.createdAt.localeCompare(b.createdAt),
71    )
72
73// ---- BR24-F6.4/F6.7: one row per delegation, with who holds the ball ----
74// The centralino computes the state and the row in its vista (centralino/palla.py,
75// `stato_palla` and `riga` on each wait): the band and Orbit's office draw the same
76// thing. Here only the drawing data, read as it comes.
77
78export type BallState = WaitRow['state']
79
80const BALL_STATES: readonly BallState[] = [
81  'domanda',
82  'esito',
83  'scaduta',
84  'mario',
85  'consegnato',
86  'fermo',
87  'chiusa',
88  'coda',
89  'lavora',
90]
91
92// One line, whatever the summary held: newlines and runs of spaces become one space.
93export const oneLine = (s: string) => s.replace(/\s+/g, ' ').trim()
94
95export const shownSince = (iso: string, now: number) => age(minutes(iso, now))
96
97const asBall = (v: unknown): BallState | null =>
98  typeof v === 'string' && (BALL_STATES as readonly string[]).includes(v) ? (v as BallState) : null
99
100// What a row needs to be drawn; register.tsx lays it out in columns. Without the
101// centralino's row (an older centralino, the files) the row says it does not know.
102export const toDelegationRow = (w: Wait, now: number): WaitRow => {
103  const r = w.row ?? {}
104  const state = asBall(w.ball) ?? 'ignoto'
105  const text = (v: unknown) => (typeof v === 'string' && v !== '' ? v : null)
106
107  return {
108    key: w.taskId,
109    state,
110    glyph: text(r.glifo) ?? '·',
111    label: text(r.parola) ?? 'stato non noto',
112    code: text(r.codice),
113    plan: text(r.piano),
114    title: oneLine(text(r.titolo) ?? w.description) || w.taskId,
115    who: text(r.esecutore) ?? w.executor ?? w.delegatedTo ?? '?',
116    since: shownSince(w.createdAt, now),
117    read: text(r.leggi) ?? (w.msgId === null ? null : `/read ${w.msgId}`),
118    alert: r.allerta === true,
119    note: text(r.nota),
120  }
121}
122
123// Rows that ask something of this session (or of Mario) come first; the unknown last.
124const rank = (s: WaitRow['state']) => {
125  const i = (BALL_STATES as readonly string[]).indexOf(s)
126
127  return i < 0 ? BALL_STATES.length : i
128}
129
130export const orderRows = (rows: readonly WaitRow[]) => [...rows].sort((a, b) => rank(a.state) - rank(b.state))
131
132export const waitsHeadline = (waits: readonly Wait[]) => {
133  const open = waits.filter(w => w.state === 'expected').length
134  const expired = waits.length - open
135  const tail = expired === 0 ? '' : expired === 1 ? ', 1 scaduta' : `, ${expired} scadute`
136
137  return `Deleghe aperte · ${open}${tail}`
138}
139
140// The footer's counts, only those not zero: what waits for this session.
141export const waitsFooter = (rows: readonly WaitRow[]) => {
142  const n = (s: BallState) => rows.filter(r => r.state === s).length
143  const parts: string[] = []
144  const esiti = n('esito')
145  const domande = n('domanda')
146  const mario = n('mario')
147  if (esiti > 0) parts.push(`✉ ${esiti} ${esiti === 1 ? 'esito' : 'esiti'} da leggere`)
148  if (domande > 0) parts.push(`? ${domande} ${domande === 1 ? 'domanda' : 'domande'} per te`)
149  if (mario > 0) parts.push(`● ${mario} ${mario === 1 ? 'tocca' : 'toccano'} a Mario`)
150
151  return parts.join('   ')
152}
153
hooks/vista.ts 114 lines
1import type { NoChannel, SessionsFile } from './team'
2import { parseSessionList } from './team'
3
4// Pure logic of the bus centralino's `vista` (BR24-F4.3): one read-only op on
5// $AB_HOME/centralino.sock that gives this band its three sections, records in
6// the bus file format so the parsers of bus.ts and waits.ts read them as they
7// are. The mod engine cannot speak line-JSON on a socket ($.http speaks HTTP),
8// so register.tsx sends the request through `nc -U`. No `$` here.
9
10export type VistaMessage = {
11  agent: string
12  slug: string | null
13  letto: boolean
14  raw: unknown
15  stato_msg?: unknown
16  riga?: unknown
17}
18// BR24-F6.7: stato_palla and riga, who holds the ball and the row to draw (centralino/palla.py).
19export type VistaWait = { agent: string; slug: string | null; raw: unknown; stato_palla?: unknown; riga?: unknown }
20// A bus session as the centralino sees it (only the fields the band reads).
21export type VistaSession = {
22  agent?: unknown
23  slug?: unknown
24  host?: unknown
25  viva?: unknown
26  ferma?: unknown
27  onda_state?: unknown
28  canale?: unknown
29  started_at?: unknown
30}
31
32export type Vista = {
33  onda?: { valido?: boolean; writtenAt?: string | null; sessioni?: unknown[] }
34  messaggi?: VistaMessage[]
35  attese?: VistaWait[]
36  sessioni?: VistaSession[]
37}
38
39// Every pending message, however old (the band lists them all, like the inbox);
40// no read ones; waits: open ones plus those of the last day.
41export const VISTA_ARGS = { pending_s: 365 * 86400, letti_s: 0, attese_s: 86400 }
42
43export const vistaRequest = (id: string) =>
44  `${JSON.stringify({ v: 1, id, op: 'vista', args: VISTA_ARGS })}\n`
45
46// The vista, or why there is none (the band says it in words).
47export const parseVista = (stdout: string): { vista: Vista } | { error: string } => {
48  const line = stdout.split('\n').find(l => l.trim() !== '')
49  if (line === undefined) return { error: 'il centralino non ha risposto' }
50  try {
51    const resp = JSON.parse(line)
52    if (resp?.ok === true && typeof resp.result === 'object' && resp.result !== null) {
53      return { vista: resp.result as Vista }
54    }
55    const msg = typeof resp?.error?.message === 'string' ? resp.error.message : 'errore sconosciuto'
56
57    return { error: `il centralino ha risposto con un errore (${msg})` }
58  } catch {
59    return { error: 'risposta del centralino illeggibile' }
60  }
61}
62
63// Pending messages of this session: the shared root (slug null) and its own @slug,
64// as [text, file name] for parseMessage.
65export const inboxOf = (v: Vista, agent: string, slug: string): [string, string][] =>
66  (v.messaggi ?? [])
67    .filter(m => m.agent === agent && !m.letto && (m.slug === null || m.slug === slug))
68    .map(m => {
69      const id = (m.raw as { id?: unknown } | null)?.id
70      // BR24-F6.8: the state for this session and the row, beside the record.
71      const raw =
72        'stato_msg' in m && typeof m.raw === 'object' && m.raw !== null
73          ? { ...m.raw, stato_msg: m.stato_msg, riga: m.riga }
74          : m.raw
75
76      return [JSON.stringify(raw), typeof id === 'string' ? `${id}.json` : 'msg-.json']
77    })
78
79// The waits of this session, as texts for parseWait, with who holds the ball.
80export const waitsOf = (v: Vista, agent: string, slug: string): string[] =>
81  (v.attese ?? [])
82    .filter(w => w.agent === agent && w.slug === slug)
83    .map(w =>
84      JSON.stringify(
85        'stato_palla' in w && typeof w.raw === 'object' && w.raw !== null
86          ? { ...w.raw, stato_palla: w.stato_palla, riga: w.riga }
87          : w.raw,
88      ),
89    )
90
91// Onda's sessions as the centralino sees them; null when it says sessions.json
92// is not valid (stale, or Onda not running): the section is absent, as with the file.
93export const sessionsOf = (v: Vista): SessionsFile | null =>
94  v.onda?.valido === true && Array.isArray(v.onda.sessioni)
95    ? { ondaPid: 0, sessions: parseSessionList(v.onda.sessioni) }
96    : null
97
98export const fallbackText = (why: string) => `Bus letto dai file: ${why}.`
99
100// BR24-F6.7: the other live bus sessions of this machine (not this one), and those of
101// them the centralino cannot wake (alive, no Onda pane, no tmux).
102const others = (v: Vista, agent: string, slug: string) =>
103  (v.sessioni ?? []).filter(
104    s => s.viva === true && typeof s.agent === 'string' && typeof s.slug === 'string' && !(s.agent === agent && s.slug === slug),
105  )
106
107export const liveCountOf = (v: Vista, agent: string, slug: string) => others(v, agent, slug).length
108
109export const noChannelOf = (v: Vista, agent: string, slug: string): NoChannel[] =>
110  others(v, agent, slug)
111    .filter(s => s.canale === 'nessuno')
112    .map(s => ({ agent: s.agent as string, slug: s.slug as string, since: typeof s.started_at === 'string' ? s.started_at : '' }))
113
114
types/index.d.ts 117 lines
1export type Priority = 'urgent' | 'high' | 'normal' | 'low'
2
3export type BusMessage = {
4  id: string
5  from: string
6  intent: string
7  priority: Priority
8  type: string
9  ts: string
10  // BR24-F6.8: the state for this session and the row, as the centralino's vista computed them.
11  state: string | null
12  row: Record<string, unknown> | null
13}
14
15// One message to do (BR24-F6.8), drawn like a delegation row.
16export type TodoRow = {
17  key: string
18  state: string
19  glyph: string
20  label: string
21  code: string | null
22  plan: string | null
23  title: string
24  from: string
25  since: string
26  read: string
27  pressing: boolean
28}
29
30export type BusSnapshot = {
31  agent: string
32  slug: string
33  messages: BusMessage[]
34  rows: TodoRow[]
35  elsewhere: number
36}
37
38export type TeamState =
39  | 'working'
40  | 'idle'
41  | 'waiting_permission'
42  | 'waiting_answer'
43  | 'pending_input'
44  | 'exited'
45
46export type TeamSession = {
47  sessionId: string
48  workspaceId: string
49  agent: string | null
50  slug: string
51  cwd: string
52  state: TeamState
53  stateSince: string
54  lastTool: string | null
55  mounted: boolean
56  host: string
57}
58
59// BR24-F6.7: one session that needs Mario, in word and glyph.
60export type TeamRow = {
61  key: string
62  kind: 'testo' | 'permesso' | 'domanda' | 'canale'
63  glyph: string
64  label: string
65  name: string
66  since: string
67  stuck: boolean
68  unmounted: boolean
69  workspaceId: string | null
70  canMount: boolean
71}
72
73export type TeamSnapshot = {
74  headline: string
75  rows: TeamRow[]
76  hidden: number
77  sessions: TeamSession[]
78}
79
80// One delegation this session waits for (BR24-F6.4): who holds the ball, in words
81// and glyph, the plan code, a one-line title, the executor, and what a click opens.
82export type WaitRow = {
83  key: string
84  state: 'domanda' | 'esito' | 'scaduta' | 'mario' | 'consegnato' | 'fermo' | 'chiusa' | 'coda' | 'lavora' | 'ignoto'
85  glyph: string
86  label: string
87  code: string | null
88  plan: string | null
89  title: string
90  who: string
91  since: string
92  read: string | null
93  alert: boolean
94  note: string | null
95}
96
97export type WaitsSnapshot = {
98  headline: string
99  rows: WaitRow[]
100  hidden: number
101  footer: string
102  expired: string[]
103}
104
105declare module 'claude-code' {
106  interface PluginState {
107    'bus-band': {
108      snapshot: BusSnapshot | null
109      isHidden: boolean
110      team: TeamSnapshot | null
111      isTeamHidden: boolean
112      waits: WaitsSnapshot | null
113      fallback: string | null
114    }
115  }
116}
117