Side pane listing the agents at work, plus a live browser map of their flow, files touched and crucial files, with a history of past sessions

A growing collection of mods for Claude Code.
| Mod | What it does |
|---|---|
| agent-squad | Side pane listing the agents at work: nickname, icon, role, status and current activity. /squadra flusso (or a click on an agent) opens a live map in the browser: call graph, timeline, files touched and crucial files. /squadra storico lists past sessions and the files each one changed. A 💬 button on sessions, files and calls puts a question about them in the prompt of the session that did the work (/squadra collega registers the squadra:// link once). Windows only for now |
| token-bar | Bar above the prompt showing account usage (5h and 7-day limits), context, cost, model, effort and login expiry (🔑, read from .credentials.json; absent on macOS, where credentials live in the Keychain). Bars shrink with the terminal width and drop to bare percentages below 90 columns |
The in-app labels are in Italian.
Inside Claude Code:
/plugin marketplace add Lerma4/claude-code-mods
/plugin install agent-squad@claude-code-mods
/plugin install token-bar@claude-code-mods
Then restart Claude Code.
/plugin marketplace update claude-code-mods
Or enable auto-update for this marketplace from the /plugin menu.
The pane works as soon as the plugin is installed. The browser pages and the 💬 buttons need Windows (for now).
/squadra opens it again./squadra flusso, the 🗺 Flusso button in the pane, or a click on an agent's name. It opens in your default browser and updates live./squadra storico, or the 📚 Storico link in the flow page./squadra collega.claude --resume) or pick another open session.squadra link: allow it (tick "always allow" to skip the question next time).| Command | What it does |
|---|---|
/squadra | Opens the pane |
/squadra flusso [name] | Flow map of the session, or of one agent and its subagents |
/squadra storico | Past sessions, the files each one changed, search by file, project or request |
/squadra collega | Registers the squadra:// link for your Windows user (no admin rights) |
/squadra scollega | Removes it |
/squadra pulisci | Clears finished agents from the pane |
/squadra tombola [name] | New random nicknames |
Settings (/plugin → agent-squad → configure): keepSessions, how many recent sessions keep their full flow map (default 20). Older ones keep only the list of files they changed.
What it writes on your machine
%USERPROFILE%\.claude\agent-flow\: the pages, one folder per recent session, the history data. Delete it any time; it is rebuilt./squadra collega only: the key HKCU\Software\Classes\squadra, which runs agent-flow\chiedi.ps1 on a squadra:// link. That script takes only a known session id from the link and puts text in that session's prompt box; /squadra scollega removes the key.Troubleshooting
/squadra collega, then reload the page.hooks/register.tsx 337 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { SquadAgent, SquadStatus } from '../types'
5import { flowAgent, flowCall, flowPrompt, flowStart, flowStatus, link, openFlow, openHistory, unlink } from './flow'
6
7const PANE = 'agent-squad'
8const TITLE = 'La Squadra'
9const MAX = 20
10const MAIN = 'main'
11const agents = atom({ plugin: 'agent-squad', key: 'agents' } as const, [])
12// Ticks once a second while someone is at work, so the running clocks redraw.
13const now = atom({ plugin: 'agent-squad', key: 'now' } as const, 0)
14
15const NAMES = [
16 'Gigi Grep', 'Rita Regex', 'Beppe Bash', 'Tina Token', 'Nando Null',
17 'Pina Pipeline', 'Ugo Undefined', 'Franca Fork', 'Mimmo Merge', 'Lella Lambda',
18 'Tonino Timeout', 'Carla Cache', 'Sandro Stacktrace', 'Wanda Wildcard',
19 'Peppino Ping', 'Ornella Overflow', 'Dario Deploy', 'Silvia Socket',
20 'Rocco Rollback', 'Gina Git',
21]
22
23// A random name not already on screen; repeats only when every name is taken.
24export const pickName = (taken: string[], rand = Math.random): string => {
25 const free = NAMES.filter(n => !taken.includes(n))
26 const pool = free.length ? free : NAMES
27 return pool[Math.floor(rand() * pool.length)]
28}
29
30const ROLES: Record<string, { logo: string; title: string; role: string }> = {
31 main: { logo: '👑', title: 'Coordinatore', role: 'Parla con te e smista il lavoro' },
32 Explore: { logo: '🔍', title: 'Segugio', role: 'Fruga nel codice e trova file e simboli' },
33 Plan: { logo: '🧭', title: 'Architetto', role: "Disegna il piano d'attacco" },
34 'general-purpose': { logo: '🔧', title: 'Tuttofare', role: 'Ricerche e lavori in più passi' },
35 'claude-code-guide': { logo: '📖', title: 'Bibliotecario', role: 'Conosce a memoria la documentazione' },
36 fork: { logo: '🧬', title: 'Clone', role: 'Una copia del capo con lo stesso contesto' },
37 'statusline-setup': { logo: '🎨', title: 'Decoratore', role: 'Sistema la status line' },
38 teammate: { logo: '🤝', title: 'Compagno di squadra', role: 'Lavora in parallelo nel team' },
39 claude: { logo: '🧠', title: 'Jolly', role: 'Agente generico, fa un po\' di tutto' },
40}
41
42// Generic agents: the job, not the type, says what they do.
43const GENERIC = new Set(['general-purpose', 'claude', 'fork'])
44
45// Role guessed from keywords in a custom agent's name or in the task description (English or Italian).
46// First match wins, so the more specific roles come first.
47const KINDS: [RegExp, { logo: string; title: string; role: string }][] = [
48 [/secur|sicurezz|\bauth|login|permess|pentest|vuln/, { logo: '🛡️', title: 'Guardiano', role: 'Permessi, login e vulnerabilità' }],
49 [/debug|\bbug|diagnos|\bfix|corregg|errore/, { logo: '🐛', title: 'Acchiappabug', role: 'Riproduce e risolve i bug' }],
50 [/review|revision|rivedi|audit|critic/, { logo: '🧐', title: 'Revisore', role: 'Rilegge il codice e scova i difetti' }],
51 [/\btest(s|ing)?\b|collaud|\bqa\b|tdd|e2e|regression/, { logo: '🧪', title: 'Collaudatore', role: 'Scrive test e caccia regressioni' }],
52 [/\b(db|sql)\b|database|schema|migra|prisma|tabell|query/, { logo: '🗄️', title: 'Archivista', role: 'Tabelle, query e migrazioni' }],
53 [/devops|deploy|docker|k8s|kube|\bci\b|infra|release|rilasc|pipeline/, { logo: '🚀', title: 'Sistemista', role: 'Build, deploy e infrastruttura' }],
54 [/perf|prestazion|optimi|ottimizz|velocizz|cache/, { logo: '⚡', title: 'Ottimizzatore', role: 'Rende tutto più veloce' }],
55 [/integra|webhook|\bsync|connector/, { logo: '🔌', title: 'Integratore', role: 'Collega sistemi esterni e API di terzi' }],
56 [/\bdat[ai]\b|analy|anali|report|etl|export|import|estrazion/, { logo: '📊', title: 'Analista', role: 'Dati, report ed export' }],
57 [/asset|image|immagin|icon/, { logo: '🖼️', title: 'Grafico', role: 'Prepara immagini e asset' }],
58 [/design|\bux\b|style|stile|theme|\btema|grafic/, { logo: '💅', title: 'Designer', role: 'Cura UX e aspetto grafico' }],
59 [/front|\bui\b|react|angular|\bvue|svelte|css|component|interfacc|schermat|pagin|maschera|\bform\b/, { logo: '🖥️', title: 'Frontendista', role: 'Schermate, form e componenti' }],
60 [/\bback|\bapi\b|server|service|servizi|endpoint/, { logo: '⚙️', title: 'Backendista', role: 'API e logica di business' }],
61 [/i18n|transl|tradu|locali/, { logo: '🌍', title: 'Traduttore', role: 'Testi e traduzioni' }],
62 [/\bdoc|writer|readme|changelog/, { logo: '📝', title: 'Scrivano', role: 'Documentazione e README' }],
63 [/refactor|rifattor|simplif|semplific|clean|pulizi/, { logo: '🧹', title: 'Spazzino', role: 'Refactoring e pulizia' }],
64 [/architect|architett|\bplan|\bpiano/, { logo: '🧭', title: 'Architetto', role: "Disegna il piano d'attacco" }],
65 [/explor|esplor|search|research|find|\bcerca|\btrova/, { logo: '🔍', title: 'Segugio', role: 'Fruga nel codice e trova file e simboli' }],
66]
67
68const pretty = (s: string) => s.replace(/[-_]+/g, ' ').replace(/\b\w/g, c => c.toUpperCase())
69const guess = (text: string) => KINDS.find(([re]) => re.test(text.toLowerCase()))?.[1]
70
71export const roleOf = (type: string, description = '') => {
72 if (ROLES[type] && !GENERIC.has(type)) return ROLES[type]
73 // Plugin agents are named 'plugin:agent'; the plugin name only says where it came from.
74 const [plugin, agent] = type.includes(':') ? type.split(/:(.*)/) : ['', type]
75 const kind = (!GENERIC.has(type) && guess(agent)) || guess(description)
76 if (kind) return kind
77 if (ROLES[type]) return ROLES[type]
78 return plugin
79 ? { logo: '🧩', title: pretty(agent), role: `Dal plugin ${plugin}` }
80 : { logo: '🤖', title: 'Agente', role: type }
81}
82
83const STATUS: Record<SquadStatus, { icon: string; label: string; color: string }> = {
84 running: { icon: '●', label: 'al lavoro', color: 'claude' },
85 idle: { icon: '○', label: 'in attesa', color: 'subtle' },
86 completed: { icon: '✔', label: 'finito', color: 'success' },
87 failed: { icon: '✖', label: 'errore', color: 'error' },
88 killed: { icon: '■', label: 'fermato', color: 'inactive' },
89}
90
91// The tool argument that best says what a call is doing, first match wins.
92const HINTS = ['description', 'command', 'file_path', 'pattern', 'url', 'query', 'path', 'prompt']
93
94export const describe = (e: { tool: string }): string => {
95 const args = e as unknown as Record<string, unknown>
96 const hint = HINTS.map(k => args[k]).find((v): v is string => typeof v === 'string' && v.trim() !== '')
97 return hint ? `${e.tool}: ${hint.replace(/\s+/g, ' ').trim()}` : e.tool
98}
99
100// 'claude-haiku-4-5-20251001' -> 'haiku 4.5'; an alias ('haiku') stays as it is.
101export const shortModel = (model: string): string =>
102 model
103 .replace(/^claude-/, '')
104 .replace(/\[.*\]$/, '')
105 .replace(/-\d{8}$/, '')
106 .replace(/-(\d+)-(\d+)$/, ' $1.$2')
107 .replace(/-(\d+)$/, ' $1')
108
109// 42_000 -> '42s', 125_000 -> '2m 05s', 3_720_000 -> '1h 02m'.
110export const elapsed = (ms: number): string => {
111 const s = Math.max(0, Math.floor(ms / 1000))
112 const pad = (n: number) => String(n).padStart(2, '0')
113 if (s < 60) return `${s}s`
114 if (s < 3600) return `${Math.floor(s / 60)}m ${pad(s % 60)}s`
115 return `${Math.floor(s / 3600)}h ${pad(Math.floor(s / 60) % 60)}m`
116}
117
118// Starts the clock of a row that was not already running.
119const start = async ($: EngineInterface, id: string, patch: Partial<SquadAgent>) => {
120 const t = await $.clock.now()
121 await touch($, id, a => ({ ...patch, status: 'running', since: a.status === 'running' && a.since ? a.since : t }))
122}
123
124const fresh = (id: string, list: SquadAgent[]): SquadAgent =>
125 id === MAIN
126 ? { id, name: 'Il Capo', type: 'main', description: '', status: 'idle', activity: '' }
127 : {
128 id,
129 name: pickName(list.map(a => a.name)),
130 type: 'agent',
131 description: '',
132 status: 'running',
133 activity: '',
134 }
135
136// Patch the row with this id, adding it first when it is new; trims the oldest finished rows.
137const touch = ($: EngineInterface, id: string, patch: (a: SquadAgent) => Partial<SquadAgent>) =>
138 update($, agents, list => {
139 const known = list.some(a => a.id === id)
140 const all = known ? list : [...list, fresh(id, list)]
141 const out = all.map(a => (a.id === id ? { ...a, ...patch(a) } : a))
142 while (out.length > MAX) {
143 const old = out.findIndex(a => a.id !== MAIN && a.status !== 'running')
144 if (old < 0) break
145 out.splice(old, 1)
146 }
147 return out
148 })
149
150const ended = (a: SquadAgent, reason: string): Partial<SquadAgent> => {
151 if (a.id === MAIN || a.type === 'teammate') return { status: 'idle', activity: 'Aspetta istruzioni' }
152 if (reason === 'answer') return { status: 'completed', activity: 'Missione compiuta' }
153 if (reason === 'aborted') return { status: 'killed', activity: 'Interrotto' }
154 return { status: 'failed', activity: 'Qualcosa è andato storto' }
155}
156
157// New random names for every agent but the boss, or only for the one called `who`.
158export const reroll = (list: SquadAgent[], who = '', rand = Math.random): SquadAgent[] => {
159 const out = list.map(a => ({ ...a }))
160 for (const a of out) {
161 if (a.id !== MAIN && (!who || a.name.toLowerCase() === who.toLowerCase())) a.name = pickName(out.map(b => b.name), rand)
162 }
163 return out
164}
165
166const order = (a: SquadAgent) => (a.id === MAIN ? 0 : a.status === 'running' ? 1 : a.status === 'idle' ? 2 : 3)
167
168export const register: Register = (on, options) => {
169 // How many past sessions keep their full flow; the rest keep only their history row.
170 const keep = Math.max(1, Math.round(Number(options.keepSessions) || 20))
171
172 on('session.start', async ($, e, next) => {
173 await $.command.register({ name: 'squadra', description: 'Mostra il pannello con gli agenti al lavoro', argumentHint: '[flusso [nome] | storico | collega | scollega | pulisci | tombola [nome]]' })
174 void $.ui.open({ id: PANE, title: TITLE, columns: 46 })
175 await flowStart($, keep)
176 $.clock.every(1000, async () => {
177 if ((await read($, agents)).some(a => a.status === 'running')) {
178 const t = await $.clock.now()
179 await update($, now, () => t)
180 }
181 })
182 return next(e)
183 })
184
185 on('command.run', { command: 'squadra' }, async ($, e) => {
186 const [sub = '', ...rest] = e.args.trim().split(/\s+/)
187 if (sub === 'tombola') {
188 const who = rest.join(' ')
189 const target = (await read($, agents)).find(a => a.id !== MAIN && a.name.toLowerCase() === who.toLowerCase())
190 if (who && !target) return { text: `Nessun agente si chiama ${who} (il capo non partecipa alla tombola).` }
191 const out = await update($, agents, l => reroll(l, who))
192 if (!target) return { text: 'Tombola! Nuovi nomi estratti per tutta la squadra, capo escluso.' }
193 return { text: `Ambo! ${target.name} ora si chiama ${out.find(a => a.id === target.id)?.name}.` }
194 }
195 if (sub === 'flusso') {
196 const who = rest.join(' ')
197 const target = who ? (await read($, agents)).find(a => a.name.toLowerCase() === who.toLowerCase()) : undefined
198 if (who && !target) return { text: `Nessun agente si chiama ${who}.` }
199 const missed = await openFlow($, target?.id)
200 if (missed) return { text: `Non riesco ad aprire il browser, apri a mano: ${missed}` }
201 return { text: target ? `Flusso di ${target.name} aperto nel browser.` : 'Flusso della sessione aperto nel browser.' }
202 }
203 if (sub === 'storico') {
204 const missed = await openHistory($)
205 return { text: missed ? `Non riesco ad aprire il browser, apri a mano: ${missed}` : 'Storico delle sessioni aperto nel browser.' }
206 }
207 if (sub === 'collega') {
208 const failed = await link($)
209 return { text: failed ? `Collegamento non riuscito: ${failed}` : 'Collegato: i pulsanti 💬 delle pagine ora scrivono la domanda nel prompt della sessione giusta. /squadra scollega per toglierlo.' }
210 }
211 if (sub === 'scollega') {
212 const failed = await unlink($)
213 return { text: failed ? `Scollegamento non riuscito: ${failed}` : 'Scollegato: i pulsanti 💬 ora copiano solo la domanda negli appunti.' }
214 }
215 if (sub === 'pulisci') {
216 await update($, agents, list => list.filter(a => a.id === MAIN || a.status === 'running'))
217 return { text: 'Squadra ripulita: restano solo gli agenti al lavoro.' }
218 }
219 await $.ui.open({ id: PANE, title: TITLE, columns: 46 })
220 return { text: 'Pannello della squadra aperto.' }
221 })
222
223 on('agent.spawn', async ($, e, next) => {
224 const started = await next(e)
225 if (started.agentId) {
226 await flowAgent($, {
227 id: started.agentId,
228 parent: e.parentAgentId ?? MAIN,
229 call: e.tool_use_id,
230 type: e.subagentType,
231 description: e.description,
232 model: started.model,
233 })
234 await start($, started.agentId, {
235 type: e.subagentType,
236 description: e.description,
237 model: started.model,
238 activity: 'Si scalda i muscoli…',
239 })
240 }
241 return started
242 })
243
244 on('tool.call', async ($, e, next) => {
245 const id = e.agentId ?? MAIN
246 const list = await read($, agents)
247 if (id !== MAIN && !list.some(a => a.id === id)) {
248 // Not spawned while we watched (a reload, a teammate): adopt it only if the engine lists it.
249 const info = (await $.agent.list()).find(a => a.id === id)
250 if (!info) return next(e)
251 await touch($, id, () => ({ type: info.type, description: info.description }))
252 }
253 await start($, id, { activity: describe(e) })
254 const finish = await flowCall($, e as unknown as Record<string, unknown>)
255 const ran = await next(e)
256 await finish(ran)
257 return ran
258 })
259
260 on('prompt.submit', async ($, e, next) => {
261 if (!e.isMeta && !e.command) await flowPrompt($, e.text)
262 return next(e)
263 })
264
265 // Every model request names the model it goes to: the live truth for the main loop and each subagent.
266 on('turn.step', async function* ($, e, next) {
267 const id = e.agentId ?? MAIN
268 const row = (await read($, agents)).find(a => a.id === id)
269 const effort = e.effort === undefined ? undefined : String(e.effort)
270 if ((row || id === MAIN) && (row?.model !== e.model || row?.effort !== effort)) {
271 await touch($, id, () => ({ model: e.model, effort }))
272 }
273 return yield* next(e)
274 })
275
276 on('turn.start', async ($, e, next) => {
277 await start($, MAIN, { activity: 'Ci sta pensando…' })
278 await flowStatus($, MAIN, 'running', false)
279 return next(e)
280 })
281
282 on('turn.complete', async ($, e, next) => {
283 const id = e.agentId ?? MAIN
284 const list = await read($, agents)
285 if (id === MAIN || list.some(a => a.id === id)) {
286 const t = await $.clock.now()
287 await touch($, id, a => ({ ...ended(a, e.reason), since: undefined, lastMs: e.durationMs || (a.since ? t - a.since : a.lastMs) }))
288 }
289 await flowStatus($, id, id === MAIN ? 'idle' : e.reason === 'answer' ? 'completed' : e.reason === 'aborted' ? 'killed' : 'failed', true)
290 return next(e)
291 })
292
293 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
294 const { Box, Text, Button } = $.ui.resolve(e)
295 const list = [...(await read($, agents))].sort((a, b) => order(a) - order(b))
296 const busy = list.filter(a => a.status === 'running').length
297 await read($, now) // subscribes the pane to the ticks
298 const t = await $.clock.now()
299 // Running: how long so far. Otherwise: how long the last task took.
300 const timer = (a: SquadAgent) =>
301 a.status === 'running' ? (a.since ? ` · ${elapsed(t - a.since)}` : '') : a.lastMs !== undefined ? ` · ${elapsed(a.lastMs)}` : ''
302
303 return (
304 <Box flexDirection="column">
305 <Box justifyContent="space-between" flexWrap="wrap" columnGap={1}>
306 <Text bold color="claude">⚡ La Squadra</Text>
307 <Button key="flow" plain dimColor onPress={() => void openFlow($)}>🗺 Flusso</Button>
308 </Box>
309 <Text dimColor wrap="wrap">{busy} al lavoro · {list.length - busy} a riposo · clic su un nome per il suo flusso</Text>
310 {list.length === 0 && <Text dimColor>Nessun agente in campo.</Text>}
311 {list.map(a => {
312 const r = roleOf(a.type, a.description)
313 const s = STATUS[a.status]
314 return (
315 <Box flexDirection="column" marginTop={1}>
316 {/* Wraps instead of truncating: in a narrow pane the status drops below the name. */}
317 <Box flexWrap="wrap" justifyContent="space-between" columnGap={1}>
318 <Box flexWrap="wrap" flexShrink={1}>
319 {/* A click opens this agent's flow in the browser. */}
320 <Button key={`flow:${a.id}`} plain onPress={() => void openFlow($, a.id)}>
321 <Text bold wrap="wrap">{r.logo} {a.name}</Text>
322 </Button>
323 {a.model && <Text color="suggestion" wrap="wrap"> · {shortModel(a.model)}</Text>}
324 {a.effort && <Text color="warning" wrap="wrap"> · {a.effort}</Text>}
325 </Box>
326 <Text color={s.color} wrap="wrap">{s.icon} {s.label}{timer(a)}</Text>
327 </Box>
328 <Text dimColor italic wrap="wrap">{r.title} · {a.description || r.role}</Text>
329 <Text color={a.status === 'running' ? 'text' : 'subtle'} wrap="wrap">↳ {a.activity || '—'}</Text>
330 </Box>
331 )
332 })}
333 </Box>
334 )
335 })
336}
337hooks/flow.ts 345 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface } from 'claude-code'
3
4import type { FileStat, Flow, FlowAgent, FlowBeat, FlowEvent, FlowKind, FlowSummary, FlowTouch } from '../types'
5
6// The flow view: every tool call, spawn and prompt, dumped to data.js beside a static page
7// (viewer/index.html) that re-reads it every second in the browser.
8
9const MAIN = 'main'
10const MAX_EVENTS = 3000
11// File touches are small and kept apart, so the file list outlives the oldest calls.
12const MAX_TOUCHES = 20000
13const CLIP = 1500
14// The history lives in $.store (4 MiB in all): a few KB per session.
15const HISTORY = 'storico'
16const MAX_HISTORY = 1500
17const MAX_HISTORY_FILES = 50
18const HISTORY_EVERY_MS = 30_000
19// Every open session writes a heartbeat; the pages offer only the live ones as targets for a question.
20const BEAT_EVERY_MS = 5_000
21const ALIVE_MS = 15_000
22const BEAT_GONE_MS = 3_600_000
23const flow = atom({ plugin: 'agent-squad', key: 'flow' } as const, { agents: [], events: [], prompts: [], touches: [] } as Flow)
24
25const VERIFY = /\b(test|tests|pytest|vitest|jest|tsc|lint|eslint|build|mvn|gradle|cargo|go test|dotnet|npm run|pnpm|yarn|make)\b/i
26const SEARCH = new Set(['Grep', 'Glob', 'LS', 'WebSearch', 'WebFetch', 'ToolSearch', 'LSP'])
27
28export const kindOf = (tool: string, command = ''): FlowKind => {
29 if (tool === 'Read' || tool === 'NotebookRead') return 'read'
30 if (SEARCH.has(tool)) return 'search'
31 if (tool === 'Edit' || tool === 'MultiEdit' || tool === 'NotebookEdit') return 'edit'
32 if (tool === 'Write') return 'write'
33 if (tool === 'Bash' || tool === 'PowerShell') return VERIFY.test(command) ? 'verify' : 'shell'
34 if (tool === 'Agent' || tool === 'Task') return 'agent'
35 return 'other'
36}
37
38// Same file, same key: forward slashes, relative to the session directory when under it.
39export const relPath = (path: string, cwd: string): string => {
40 const p = path.replace(/\\/g, '/')
41 const c = cwd.replace(/\\/g, '/').replace(/\/$/, '')
42 return p.toLowerCase().startsWith(c.toLowerCase() + '/') ? p.slice(c.length + 1) : p
43}
44
45const HINTS = ['description', 'command', 'file_path', 'notebook_path', 'pattern', 'url', 'query', 'path', 'prompt']
46const clip = (s: unknown, n = CLIP) => (typeof s === 'string' ? (s.length > n ? s.slice(0, n) + '…' : s) : undefined)
47
48export const toEvent = (e: Record<string, unknown>, cwd: string, n: number, t: number): FlowEvent => {
49 const tool = String(e.tool)
50 const kind = kindOf(tool, typeof e.command === 'string' ? e.command : '')
51 const hint = HINTS.map(k => e[k]).find((v): v is string => typeof v === 'string' && v.trim() !== '') ?? ''
52 const raw = (e.file_path ?? e.notebook_path) as string | undefined
53 const file = raw && ['read', 'edit', 'write'].includes(kind) ? relPath(raw, cwd) : undefined
54 const ev: FlowEvent = { n, t, agent: (e.agentId as string) ?? MAIN, tool, kind, hint: clip(hint.replace(/\s+/g, ' ').trim(), 200)!, file }
55 if (kind === 'agent') ev.call = e.tool_use_id as string
56 if (tool === 'Edit') Object.assign(ev, { old: clip(e.old_string), new: clip(e.new_string) })
57 if (tool === 'Write') ev.new = clip(e.content)
58 if (kind === 'verify' || kind === 'shell') ev.old = clip(e.command)
59 return ev
60}
61
62// Attention per file and why it matters. ponytail: heuristic weights, tune them by eye.
63export const fileStats = (events: readonly FlowTouch[]): FileStat[] => {
64 const by = new Map<string, FileStat>()
65 const get = (path: string) => by.get(path) ?? by.set(path, { path, reads: 0, edits: 0, writes: 0, agents: [], score: 0, why: [] }).get(path)!
66 const lastFail = new Map<string, number>()
67 const recentReads = new Map<string, string[]>()
68 for (const ev of events) {
69 if (ev.kind === 'verify') {
70 if (ev.ok === false) lastFail.set(ev.agent, ev.n)
71 else lastFail.delete(ev.agent)
72 }
73 if (!ev.file) continue
74 const f = get(ev.file)
75 if (!f.agents.includes(ev.agent)) f.agents.push(ev.agent)
76 if (ev.kind === 'read') {
77 f.reads++
78 const r = (recentReads.get(ev.agent) ?? []).filter(p => p !== ev.file).slice(-4)
79 recentReads.set(ev.agent, [...r, ev.file])
80 continue
81 }
82 if (ev.kind === 'edit') f.edits++
83 else f.writes++
84 // The files read just before a change are the context the change came from.
85 for (const p of recentReads.get(ev.agent) ?? []) {
86 if (p === ev.file) continue
87 const ctx = get(p)
88 ctx.score += 2
89 if (!ctx.why.includes('contesto di una modifica')) ctx.why.push('contesto di una modifica')
90 }
91 recentReads.set(ev.agent, [])
92 if (lastFail.has(ev.agent)) {
93 f.score += 3
94 if (!f.why.includes('corretto dopo un test fallito')) f.why.push('corretto dopo un test fallito')
95 }
96 }
97 for (const f of by.values()) {
98 f.score += 5 * (f.edits + f.writes) + f.reads + 2 * (f.agents.length - 1)
99 if (f.writes && !f.edits) f.why.unshift('creato')
100 else if (f.edits) f.why.unshift(`modificato ${f.edits}×`)
101 if (f.reads > 2) f.why.push(`riletto ${f.reads}×`)
102 if (f.agents.length > 1) f.why.push(`${f.agents.length} agenti`)
103 }
104 return [...by.values()].sort((a, b) => b.score - a.score)
105}
106
107// Pure: the history row of one session, modified files only, the most crucial first.
108export const summarize = (id: string, project: string, f: Flow, updated: number): FlowSummary => ({
109 id,
110 project,
111 start: f.agents.find(a => a.id === MAIN)?.start ?? updated,
112 updated,
113 agents: f.agents.filter(a => a.id !== MAIN).length,
114 calls: f.events.at(-1)?.n ?? 0,
115 prompt: f.prompts[0]?.text.slice(0, 120),
116 files: fileStats(f.touches)
117 .filter(s => s.edits + s.writes > 0)
118 .slice(0, MAX_HISTORY_FILES)
119 .map(s => ({ path: s.path, edits: s.edits, writes: s.writes, score: s.score })),
120})
121
122// Pure: the session folders to delete, all but the `keep` most recent (the current one always kept).
123export const toPrune = (dirs: readonly string[], history: readonly FlowSummary[], current: string, keep: number): string[] => {
124 const when = new Map(history.map(h => [h.id, h.updated]))
125 return dirs
126 .filter(d => d !== current)
127 .sort((a, b) => (when.get(b) ?? 0) - (when.get(a) ?? 0))
128 .slice(Math.max(0, keep - 1))
129}
130
131// Pure: the sessions whose heartbeat is recent, the newest first.
132export const alive = (beats: readonly FlowBeat[], now: number): FlowBeat[] =>
133 beats.filter(b => now - b.t < ALIVE_MS).sort((a, b) => b.t - a.t)
134
135// Module state: a reload starts these over, the flow itself lives in $.state.
136let root = ''
137let out = ''
138let sessionId = ''
139let dirty = true
140let seq = 0
141let savedAt = 0
142let beatAt = 0
143let asking = false
144// Whether squadra:// is registered: without it the pages only copy the question and say how to link.
145let linked = false
146const PROTOCOL = 'HKCU\\Software\\Classes\\squadra'
147
148function patch($: EngineInterface, id: string, p: (a: FlowAgent) => Partial<FlowAgent>) {
149 return update($, flow, f => ({ ...f, agents: f.agents.map(a => (a.id === id ? { ...a, ...p(a) } : a)) }))
150}
151
152async function history($: EngineInterface): Promise<FlowSummary[]> {
153 return ((await $.store.get(HISTORY)) as FlowSummary[] | undefined) ?? []
154}
155
156// Folders under sessioni/ that still hold a full flow.
157async function detailed($: EngineInterface): Promise<string[]> {
158 if (!(await $.fs.exists(`${root}/sessioni`))) return []
159 return (await $.fs.list(`${root}/sessioni`)).filter(e => e.kind === 'dir' && /^[\w-]+$/.test(e.name)).map(e => e.name)
160}
161
162// Writes this session's row into the history and the history page's data.
163async function saveHistory($: EngineInterface, f: Flow, now: number) {
164 savedAt = now
165 const row = summarize(sessionId, await $.session.root(), f, now)
166 const rows = [row, ...(await history($)).filter(h => h.id !== sessionId)].slice(0, MAX_HISTORY)
167 await $.store.set(HISTORY, rows)
168 const detail = await detailed($)
169 await $.fs.write(`${root}/storico.js`, `window.__STORICO(${JSON.stringify(rows.map(r => ({ ...r, detail: detail.includes(r.id) })))})`)
170}
171
172// Rewrites data.js when something changed, and the history row at most every 30 s.
173async function dump($: EngineInterface, force = false) {
174 if (!out || (!dirty && !force)) return
175 dirty = false
176 const f = await read($, flow)
177 const now = await $.clock.now()
178 const data = { ...f, id: sessionId, project: await $.session.root(), touches: undefined, files: fileStats(f.touches), cwd: await $.session.cwd(), updated: now }
179 await $.fs.write(`${out}/data.js`, `window.__FLOW(${JSON.stringify(data)})`)
180 if (force || now - savedAt > HISTORY_EVERY_MS) await saveHistory($, f, now)
181}
182
183const win = (path: string) => path.replace(/\//g, '\\')
184
185// Tells the other sessions (and the pages) this one is open, and writes the list of open ones.
186async function beat($: EngineInterface) {
187 const now = await $.clock.now()
188 if (now - beatAt < BEAT_EVERY_MS) return
189 beatAt = now
190 const f = await read($, flow)
191 const me: FlowBeat = { id: sessionId, project: await $.session.root(), prompt: f.prompts.at(-1)?.text.slice(0, 120), t: now }
192 await $.fs.write(`${root}/vive/${sessionId}.json`, JSON.stringify(me))
193 const beats: FlowBeat[] = []
194 for (const e of await $.fs.list(`${root}/vive`)) {
195 if (e.kind !== 'file') continue
196 try {
197 const b = JSON.parse(await $.fs.read(`${root}/vive/${e.name}`)) as FlowBeat
198 if (now - b.t > BEAT_GONE_MS) await $.process.run(['cmd', '/c', 'del', '/q', win(`${root}/vive/${e.name}`)])
199 else beats.push(b)
200 } catch {
201 // A beat caught half written: the next round reads it.
202 }
203 }
204 await $.fs.write(`${root}/vive.js`, `window.__VIVE(${JSON.stringify(alive(beats, now))}, ${linked})`)
205}
206
207// Questions sent from the pages (squadra:// links, see viewer/chiedi.ps1) land in this session's
208// inbox; each goes into the prompt box once the session is idle. Never submitted: the person sends it.
209async function inbox($: EngineInterface) {
210 const dir = `${out}/chiedi`
211 if (asking || !(await $.fs.exists(dir))) return
212 const names = (await $.fs.list(dir)).filter(e => e.kind === 'file').map(e => e.name).sort()
213 if (!names.length || (await read($, flow)).agents.find(a => a.id === MAIN)?.status === 'running') return
214 asking = true
215 try {
216 for (const name of names) {
217 // Keeps the trailing space of 'Domanda: ', so typing goes straight on.
218 const text = (await $.fs.read(`${dir}/${name}`)).replace(/^\s+/, '')
219 const draft = (await $.prompt.read()).text
220 if (text.trim() && !(await $.prompt.fill(draft.trim() ? { text: `\n${text}`, mode: 'append' } : { text })).isFilled) return
221 await $.process.run(['cmd', '/c', 'del', '/q', win(`${dir}/${name}`)])
222 if (text.trim()) $.ui.toast('💬 Domanda dal browser pronta nel prompt')
223 }
224 } finally {
225 asking = false
226 }
227}
228
229async function tick($: EngineInterface) {
230 await dump($)
231 await beat($)
232 await inbox($)
233}
234
235// Registers squadra:// for this Windows user (HKCU, no admin) to run viewer/chiedi.ps1.
236export async function link($: EngineInterface): Promise<string> {
237 const key = PROTOCOL
238 const command = `powershell.exe -NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -File "${win(`${root}/chiedi.ps1`)}" "%1"`
239 for (const args of [[key, '/ve', '/d', 'URL:Squadra'], [key, '/v', 'URL Protocol', '/d', ''], [`${key}\\shell\\open\\command`, '/ve', '/d', command]]) {
240 const ran = await $.process.run(['reg', 'add', ...args, '/f'])
241 if (ran.exitCode !== 0) return ran.stderr.trim() || ran.stdout.trim() || 'reg add non riuscito'
242 }
243 linked = true
244 beatAt = 0
245 return ''
246}
247
248export async function unlink($: EngineInterface): Promise<string> {
249 const ran = await $.process.run(['reg', 'delete', PROTOCOL, '/f'])
250 if (ran.exitCode !== 0) return ran.stderr.trim() || 'reg delete non riuscito'
251 linked = false
252 beatAt = 0
253 return ''
254}
255
256async function launch($: EngineInterface, page: string): Promise<string> {
257 const path = win(page)
258 const ran = await $.process.run(['cmd', '/c', 'start', '', path])
259 return ran.exitCode === 0 ? '' : path
260}
261
262// Opens the page in the default browser, on the whole session or on one agent and its subagents.
263export async function openFlow($: EngineInterface, agentId?: string): Promise<string> {
264 dirty = true
265 await dump($, true)
266 // `start` drops a #fragment on a file path, so a one-line page carries it instead.
267 if (!agentId) return launch($, `${out}/index.html`)
268 await $.fs.write(`${out}/agente.html`, `<script>location.replace('index.html#agent=' + ${JSON.stringify(encodeURIComponent(agentId))})</script>`)
269 return launch($, `${out}/agente.html`)
270}
271
272// Opens the list of past sessions.
273export async function openHistory($: EngineInterface): Promise<string> {
274 await dump($, true)
275 return launch($, `${root}/index.html`)
276}
277
278// Called from the squad's own hooks: the engine takes one unfiltered hook per event per plugin.
279
280export async function flowStart($: EngineInterface, keep: number) {
281 // ponytail: Windows only (%USERPROFILE%, `start`); add open/xdg-open when someone runs it elsewhere.
282 const home = (await $.process.run(['cmd', '/c', 'echo %USERPROFILE%'])).stdout.trim().replace(/\\/g, '/')
283 root = `${home}/.claude/agent-flow`
284 sessionId = await $.session.id()
285 out = `${root}/sessioni/${sessionId}`
286 await $.fs.write(`${out}/index.html`, await $.fs.read(`${$.plugin.root}/viewer/index.html`))
287 await $.fs.write(`${root}/index.html`, await $.fs.read(`${$.plugin.root}/viewer/storico.html`))
288 linked = (await $.process.run(['reg', 'query', `${PROTOCOL}\\shell\\open\\command`])).exitCode === 0
289 for (const name of ['chiedi.js', 'chiedi.ps1']) await $.fs.write(`${root}/${name}`, await $.fs.read(`${$.plugin.root}/viewer/${name}`))
290 for (const old of toPrune(await detailed($), await history($), sessionId, keep)) {
291 await $.process.run(['cmd', '/c', 'rmdir', '/s', '/q', win(`${root}/sessioni/${old}`)])
292 }
293 // A flow kept from 0.5.0, before touches existed.
294 if (!(await read($, flow)).touches) {
295 await update($, flow, x => ({ ...x, touches: x.events.filter(e => e.file || e.kind === 'verify').map(e => ({ n: e.n, agent: e.agent, kind: e.kind, file: e.file, ok: e.ok })) }))
296 }
297 const f = await read($, flow)
298 seq = f.events.at(-1)?.n ?? 0
299 if (!f.agents.some(a => a.id === MAIN)) {
300 const t = await $.clock.now()
301 await update($, flow, x => ({ ...x, agents: [{ id: MAIN, type: 'main', description: 'Sessione principale', start: t, status: 'idle' as const }, ...x.agents] }))
302 }
303 $.clock.every(1000, () => tick($))
304}
305
306export async function flowPrompt($: EngineInterface, text: string) {
307 const t = await $.clock.now()
308 await update($, flow, f => ({ ...f, prompts: [...f.prompts, { t, text: text.slice(0, 300) }] }))
309 dirty = true
310}
311
312export async function flowAgent($: EngineInterface, a: Omit<FlowAgent, 'start' | 'status'>) {
313 const t = await $.clock.now()
314 await update($, flow, f => ({ ...f, agents: [...f.agents.filter(x => x.id !== a.id), { ...a, start: t, status: 'running' as const }] }))
315 dirty = true
316}
317
318export async function flowStatus($: EngineInterface, id: string, status: FlowAgent['status'], isEnd: boolean) {
319 const t = await $.clock.now()
320 await patch($, id, () => (isEnd ? { status, end: t } : { status }))
321 dirty = true
322}
323
324// Records the call before it runs; the returned function records how it ended.
325export async function flowCall($: EngineInterface, e: Record<string, unknown>) {
326 const t = await $.clock.now()
327 const ev = toEvent(e, await $.session.cwd(), ++seq, t)
328 const touch: FlowTouch | undefined = ev.file || ev.kind === 'verify' ? { n: ev.n, agent: ev.agent, kind: ev.kind, file: ev.file } : undefined
329 await update($, flow, f => ({
330 ...f,
331 events: [...f.events, ev].slice(-MAX_EVENTS),
332 touches: touch ? [...f.touches, touch].slice(-MAX_TOUCHES) : f.touches,
333 }))
334 dirty = true
335 return async (ran: { deny?: string; isError?: boolean; text?: string }) => {
336 const done = { ms: (await $.clock.now()) - t, ok: ran.deny === undefined && !ran.isError, out: clip(ran.deny ?? ran.text, 800) }
337 await update($, flow, f => ({
338 ...f,
339 events: f.events.map(x => (x.n === ev.n ? { ...x, ...done } : x)),
340 touches: touch ? f.touches.map(x => (x.n === ev.n ? { ...x, ok: done.ok } : x)) : f.touches,
341 }))
342 dirty = true
343 }
344}
345types/index.d.ts 87 lines1export type SquadStatus = 'running' | 'idle' | 'completed' | 'failed' | 'killed'
2
3export type SquadAgent = {
4 id: string
5 name: string
6 type: string
7 description: string
8 status: SquadStatus
9 activity: string
10 model?: string
11 effort?: string
12 // When the current task started (ms since epoch), set while running.
13 since?: number
14 // How long the last finished task took, in ms.
15 lastMs?: number
16}
17
18export type FlowKind = 'read' | 'search' | 'edit' | 'write' | 'verify' | 'shell' | 'agent' | 'other'
19
20// One tool call as the flow view shows it.
21export type FlowEvent = {
22 n: number
23 t: number
24 ms?: number
25 agent: string
26 tool: string
27 kind: FlowKind
28 hint: string
29 file?: string
30 ok?: boolean
31 // tool_use_id of an Agent call: links it to the subagent it spawned.
32 call?: string
33 old?: string
34 new?: string
35 out?: string
36}
37
38export type FlowAgent = {
39 id: string
40 parent?: string
41 call?: string
42 type: string
43 description: string
44 model?: string
45 start: number
46 end?: number
47 status: SquadStatus
48}
49
50export type FlowPrompt = { t: number; text: string }
51
52// What file scores need from a call, kept longer than the calls themselves.
53export type FlowTouch = Pick<FlowEvent, 'n' | 'agent' | 'kind' | 'file' | 'ok'>
54
55export type Flow = { agents: FlowAgent[]; events: FlowEvent[]; prompts: FlowPrompt[]; touches: FlowTouch[] }
56
57// One past session in the history: small on purpose, it is kept for good.
58export type FlowSummary = {
59 id: string
60 project: string
61 start: number
62 updated: number
63 agents: number
64 calls: number
65 prompt?: string
66 files: { path: string; edits: number; writes: number; score: number }[]
67}
68
69// An open session's heartbeat: what the pages show when asking where a question goes.
70export type FlowBeat = { id: string; project: string; prompt?: string; t: number }
71
72export type FileStat = {
73 path: string
74 reads: number
75 edits: number
76 writes: number
77 agents: string[]
78 score: number
79 why: string[]
80}
81
82declare module 'claude-code' {
83 interface PluginState {
84 'agent-squad': { agents: SquadAgent[]; now: number; flow: Flow }
85 }
86}
87