SLOPSHOPPER

luff-crew-monitor

Live crew panel inside Claude: every subagent with model, effort, steps, context, estimated cost and time, plus a job bar above the prompt and your 5-hour and…

panebandguardcommandtoastprompt
v1.6.9MITupdated 2026-10-12tanwar-harsh/luff-crew-monitor
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · luff-crew-monitor
│ ┃ Crew ✕ › fix the failing auth test and add an audit log call │ ┃ Cost ≈$0.00 · Tokens 0 · Time 0:00 │ ┃ ⏺ Read(src/auth.ts) │ ┃ ▾ Plan limits Collapse Open in browser ⎿ Read 6 lines │ ┃ 5-hour session ▰▰▰▰▰▱▱▱▱▱▱▱▱▱▱▱ 31% 0 · ≈… ⏺ Update(src/auth.ts) │ ┃ Weekly no plan data 0 · ≈$0.00 ⎿ Added 2 lines, removed 1 line │ ┃ No subagents yet. Give Claude a job big ⏺ Bash(bun test) │ ┃ enough to split across a few helpers. ⎿ 3 pass, 1 fail │ ┃ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /agents-info │ ⎿ luff-crew-monitor: Luff Crew panel opened. │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Crew
Cost ≈$0.00 · Tokens 0 · Time 0:00 ▾ Plan limits Collapse Open in browser 5-hour session ▰▰▰▰▰▱▱▱▱▱▱▱▱▱▱▱ 31% 0 · ≈$0.00 Weekly no plan data 0 · ≈$0.00 No subagents yet. Give Claude a job big enough to split across a few helpers.
README

Luff Crew Monitor

See what every helper Claude is doing, and what it costs, live.

A Claude Code mod: it draws inside Claude itself (the desktop app, VS Code and the terminal). When Claude splits work across subagents, Luff Crew gives you a live panel of the whole crew: who's running, who's finished, what's still planned, and for each one the model, effort, step progress, context fill, estimated cost and time. A job bar sits above the prompt, and your 5-hour and weekly plan limits are always one glance away.

<img src="docs/panel-light.png" alt="The Luff Crew panel and job bar in light theme" width="48%"> <img src="docs/panel-dark.png" alt="The Luff Crew panel and job bar in dark theme" width="48%"> <img src="docs/panel-terminal.png" alt="The Luff Crew panel in the terminal, each subagent drawn as a half-block pixel mascot" width="48%">

  • Job bar on every prompt: while Claude works on anything, the bar above the prompt shows what you asked, one segment per model request, tool calls (and the one running now), elapsed time and estimated cost, then Done or Stopped. When Claude splits the work across subagents it becomes the job bar: title, phase, accepted tasks out of planned (one segment per task), percent done and crew size. Your 5-hour and weekly limits sit at its right edge as colored rings.
  • Agents panel: Running, Finished and Planned sections with cost, token and time totals. Each subagent is its own pixel crew member, with a body color, hat, eyes, mouth and extra of its own, kept from planned to done; what it holds shows its effort level: mop, oar, spyglass, lantern or ship's wheel. The terminal draws the same crew in colored half blocks, three lines tall.
  • Worker steps: subagents report their own steps (2/5 · running tests), as often as the stepReports option asks (see Configure). A subagent that doesn't report shows its context fill in grey instead.
  • Works with any subagent: built-in, custom or plugin agents, foreground or background, retries counted as rounds.
  • Plan limits: your 5-hour session and weekly usage, with % used and when each resets, above the agents. Under each meter, the tokens, estimated cost and requests counted from your local transcripts for that window.
  • /agents-info opens or closes the panel. It also opens on its own when a job with a plan starts, or when the first subagent of a session starts.
  • Optional browser view: /agents-web opens the same crew in your browser on localhost, for when you want it on a second screen. It never opens by itself.
  • Private by design: everything stays on your machine. No telemetry; the browser view listens on localhost only and only while you have it on.

Install

In a terminal, run:

/plugin install luff-crew-monitor --marketplace tanwar-harsh/luff-crew-monitor

Answer y to add the marketplace and pick the user scope. From then on it runs in every session: terminal, desktop app and VS Code. (The desktop app's Code tab can't run /plugin, but a mod installed from a terminal loads there too.)

Or, from your shell:

claude plugin marketplace add tanwar-harsh/luff-crew-monitor
claude plugin install luff-crew-monitor@luff-crew

Requires Claude Code 2.1.295 or newer. Run claude update; the desktop app updates itself.

Update

Already installed? Pull the latest version, then restart Claude (or run /reload-plugins):

claude plugin update luff-crew-monitor@luff-crew

Without the mod: MCP server and browser dashboard

For other MCP clients, the same tracker also ships as a standalone MCP server with a browser dashboard on localhost:

npm install -g https://codeload.github.com/tanwar-harsh/luff-crew-monitor/tar.gz/refs/heads/main
luff-crew-monitor setup

Don't use both in Claude Code: the mod already provides the same tools.

Use

  1. Send Claude anything. The bar above the prompt follows the turn: steps, tool calls, time and estimated cost.
  2. Give it a job big enough to split across a few subagents and the bar becomes the job bar. Type /agents-info to open the panel.

Browser view (optional)

Inside Claude is the default and needs nothing. If you'd also like the crew in a browser tab:

<img src="docs/browser-light.png" alt="The Luff Crew browser view in light theme: a finished job and its five crew members" width="48%"> <img src="docs/browser-dark.png" alt="The Luff Crew browser view in dark theme" width="48%">

CommandWhat it does
/agents-webStarts the browser view for this session on localhost (port 7420, or the next free one) and opens it. Run it again to reopen the tab.
/agents-web stopStops it. It also stops when the session ends.

The panel's Open in browser button does the same. The browser view needs Node.js 18.17 or newer on your machine; it's the package's own dashboard (dist/luff-crew.mjs) following this session's transcript.

You don't need to prompt anything special. The mod adds a short note to Claude's system prompt so it reports progress and asks its subagents for steps. If you want the job bar to be precise, say "plan it as tasks for subagents" in your request.

Plan limits

The panel at the top tracks the two Claude.ai plan windows: the 5-hour session and the weekly limit.

  • % used and reset time come straight from Claude Code (the same figures as its status line), after your first reply in a session. The meters turn amber past 70% and red past 90%.
  • On the job bar the same two windows sit at the right edge, beside the crew count, as small rings in the same colors. The terminal shows them as colored text (◔ 5h 38%).
  • Tokens, estimated cost and requests for each window are counted from every model request the mod sees, across your sessions and their subagents.

Plan percentages exist only for Claude.ai subscriptions (Pro, Max, Team, Enterprise). With an API key, Bedrock or Vertex the meters stay empty and the local totals cover the last 5 hours and 7 days.

Tools

The mod gives Claude two tools. The note it adds to the system prompt tells Claude when to call them.

ToolWho calls itWhat it does
mcp__luff-crew-monitor__progressOrchestratorReports the job: title, tasks[] (title, agent, model, effort, after), phase (plan, design, delegate, review, close), done, total, finished. Omitted fields keep their value. A new title starts a new job.
mcp__luff-crew-monitor__stepSubagentReports its own steps: done, total, note.

Planned tasks match runs by title, so each task's title should equal the Agent tool description it's delegated with.

Configure

Two options, set with /plugin configure luff-crew-monitor@luff-crew or in ~/.claude/settings.json:

  • language: auto (the default) follows Claude Code's language setting, then your locale. en and ru are available.
  • stepReports: how often subagents report their own steps. Each report is one more model request in the subagent, so this is the mod's main cost.
  • light (the default): twice per subagent, at the start and about halfway.
  • full: after every step, for the most detailed rows.
  • off: never; the step tool is not even registered. Rows still show running/done, model, context, tokens, cost and time, only not "2/4 · reading files".

Step reports only feed the panel. The main agent learns what a subagent did from the subagent's own answer either way.

{ "pluginConfigs": { "luff-crew-monitor@luff-crew": { "options": { "language": "en", "stepReports": "off" } } } }

How it works

The mod is a hooks module (hooks/register.tsx) that Claude Code loads into every session:

  • agent.spawn, turn.step and turn.complete give it each subagent's start, model, effort, token usage and end. Cost comes from token counts and the price table in src/pricing.ts.
  • session.measure gives the 5-hour and weekly plan windows.
  • tool.call answers progress and step. A subagent's call carries its loop's id, which is how its steps land on the right row.
  • turn.start, turn.step and turn.complete on the main loop drive the per-prompt bar.
  • A Pane and an AbovePrompt render hook draw the panel and the bar. Words are the app's own themed text. Mascots, bars and limit rings are small SVGs (desktop, VS Code); the terminal draws mascots in colored half blocks and bars as text. Each crew member's look comes from src/crew.ts, which the browser view shares, so a subagent looks the same everywhere.
  • /agents-web runs node dist/luff-crew.mjs dashboard --session <id> as a child of the session ($.process.spawn); the child ends with the session or on /agents-web stop.

Inside Claude it needs no server, no browser and no network.

Good to know

  • Costs are estimates. They're computed from token counts and public list prices (including cache reads, and 5-minute vs 1-hour cache writes), not taken from your bill. Subscription plans aren't billed per token at all.
  • Plan limits appear after Claude's first reply in a session. They're Claude.ai plans only.
  • Where it draws: the desktop app's Code tab, the VS Code extension and the terminal. In the terminal's main screen the panel opens inline. In the fullscreen layout it docks as a sidebar.

Standalone CLI and MCP server

The package also ships a CLI that reads Claude Code's transcripts directly. It's for other MCP clients, or a browser view outside Claude.

luff-crew-monitor                 MCP server over stdio
luff-crew-monitor setup           Register it with `claude mcp add`  [--statusline] [--scope user|project|local] [--force] [--dry-run]
luff-crew-monitor dashboard       Browser dashboard following the latest session (or one: --session <id>)  [--project <dir>] [--session <id>] [--port <n>] [--no-open]
luff-crew-monitor status          Print the crew once as text
luff-crew-monitor statusline      Status line command  [--wrap "<existing command>"] [--no-color]
luff-crew-monitor doctor          Check the installation
luff-crew-monitor uninstall       Undo setup

Its settings live in ~/.luff-crew/config.json, or in LUFF_CREW_PORT, LUFF_CREW_LANG, LUFF_CREW_AUTO_OPEN, LUFF_CREW_STALL_MINUTES and LUFF_CREW_STEP_REPORTS. stepReports (off, light or full, default light) works as the mod's option of the same name: how often subagents are asked to report their steps, and with off the step tool isn't offered. autoOpen is off by default: the MCP server opens the browser only when its open_dashboard tool is called. Set it to true to have the dashboard open by itself when a job with a plan starts.

Development

npm install
npm run check
claude plugin test .
claude plugin validate .
  • npm run check runs the typecheck, the build and the Node tests (test/*.spec.ts).
  • claude plugin test . runs the mod's own tests (hooks/*.test.tsx) against the engine, on the terminal and desktop surfaces.
  • node scripts/mod-preview.ts light|dark renders the panel and job bar as HTML for the screenshots in docs/.
  • To work on the mod live, start Claude Code with claude --plugin-dir .. Edits reload when a turn ends.
  • The CLI bundle in dist/ is committed so installs need no build step. Run npm run build before committing source changes.

License

MIT © 2026 Harsh Tanwar

Source 9 files
hooks/register.tsx 1156 lines
1// Luff Crew as a Claude Code mod: a live crew panel and a job bar drawn inside
2// Claude itself (desktop app, VS Code, terminal), fed straight from engine events.
3
4import { atom, read, update } from 'claude-code'
5import type { EngineInterface, Register } from 'claude-code'
6
7import { applyProgress, cleanTasks, doneCount, startsNewFlow } from '../src/flow.ts'
8import { clip, fmtCost, fmtDuration, fmtTime, fmtTokens, normalize } from '../src/format.ts'
9import { STRINGS } from '../src/i18n.ts'
10import { contextWindowOf, costOf, modelLabel, tokensOf } from '../src/pricing.ts'
11import type { ProgressInput } from '../src/types.ts'
12import type { CrewFlow, CrewLimitWindow, CrewPanel, CrewRun, CrewTask, CrewTurn, CrewUsageBuckets } from '../types'
13import {
14  ACCENT,
15  BAD,
16  barSvg,
17  crewSlots,
18  ctxPercent,
19  MASCOT_H,
20  MASCOT_W,
21  mascotCells,
22  mascotSvg,
23  TERM_MASCOT_W,
24  OK,
25  progressOf,
26  runMeta,
27  runStats,
28  SEG_H,
29  segmentsSvg,
30  statusColor,
31  statusGlyph,
32  stepText,
33  STRIP_H,
34  STRIP_STEP,
35  stripSvg,
36  textBar,
37  meterColor,
38  limitPairs,
39  ringSvg,
40  RING,
41  typeColor,
42} from './draw.ts'
43
44const PLUGIN = 'luff-crew-monitor'
45const PANE = 'luff-crew'
46const TOOL_PROGRESS = `mcp__${PLUGIN}__progress`
47const TOOL_STEP = `mcp__${PLUGIN}__step`
48const HOUR = 3_600_000
49const FIVE_HOURS = 5 * HOUR
50const SEVEN_DAYS = 7 * 24 * HOUR
51
52const flowAtom = atom({ plugin: 'luff-crew-monitor', key: 'flow' } as const, null)
53const runsAtom = atom({ plugin: 'luff-crew-monitor', key: 'runs' } as const, [])
54const turnAtom = atom({ plugin: 'luff-crew-monitor', key: 'turn' } as const, null)
55const webAtom = atom({ plugin: 'luff-crew-monitor', key: 'web' } as const, null)
56const panelAtom = atom({ plugin: 'luff-crew-monitor', key: 'panel' } as const, {
57  isCompact: false,
58  isFinishedOpen: true,
59  isLimitsOpen: true,
60  hiddenAt: 0,
61  autoOpenedFor: [],
62})
63const nowAtom = atom({ plugin: 'luff-crew-monitor', key: 'now' } as const, 0)
64const limitsAtom = atom({ plugin: 'luff-crew-monitor', key: 'limits' } as const, { windows: [], measuredAt: 0 })
65const usageAtom = atom({ plugin: 'luff-crew-monitor', key: 'usage' } as const, {})
66const othersAtom = atom({ plugin: 'luff-crew-monitor', key: 'others' } as const, {})
67
68type Lang = 'en' | 'ru'
69let lang: Lang = 'en'
70const s = () => STRINGS[lang]
71
72// This session's own key in `$.store`, so concurrent sessions never overwrite each other.
73let storeKey = ''
74
75/** How often subagents report their own steps; each report is one more model request. */
76type StepReports = 'off' | 'light' | 'full'
77
78const stepReportsOf = (value: unknown): StepReports => (value === 'off' || value === 'full' ? value : 'light')
79
80const STEP_BRIEF: Record<StepReports, string> = {
81  off: 'Do not ask subagents to report steps; the panel follows them on its own.\n',
82  light: `In each subagent's prompt, ask it to call \`${TOOL_STEP}\` at most twice: right after reading its brief (done: 0, total: its plan in 3-8 steps) and once about halfway, loading it first with ToolSearch (\`select:${TOOL_STEP}\`) if it is deferred.\n`,
83  full: `In each subagent's prompt, ask it to call \`${TOOL_STEP}\` right after reading its brief (done: 0, total: its plan in 3-8 steps) and again as each step finishes, loading it first with ToolSearch (\`select:${TOOL_STEP}\`) if it is deferred.\n`,
84}
85
86const protocol = (steps: StepReports): string => `## Luff Crew (subagent progress)
87The user watches subagents on the Luff Crew panel. When you split a job across subagents (the Agent tool):
881. After presenting the plan, call \`${TOOL_PROGRESS}\` with a short title, the tasks (each title EXACTLY equal to the Agent \`description\` you will use) and phase "delegate".
892. The bar counts finished subagents by itself; call it again only to switch \`phase\` to "review" or to re-plan.
903. When everything is finished, call it once with \`finished: true\`.
91${STEP_BRIEF[steps]}Skip all of this for work you do yourself without subagents.`
92
93// ---------------------------------------------------------------------------
94// Helpers
95
96const isRussian = (v: unknown): boolean => typeof v === 'string' && /^(ru|russian|рус)/i.test(v.trim())
97
98async function detectLang($: EngineInterface, option: unknown): Promise<Lang> {
99  if (option === 'en' || option === 'ru') return option
100  try {
101    const settings = (await $.settings.read()) as { language?: unknown }
102    if (typeof settings.language === 'string' && settings.language.trim()) return isRussian(settings.language) ? 'ru' : 'en'
103  } catch {
104    // No settings: fall through to the locale.
105  }
106  const locale = (await $.env.get('LC_ALL')) || (await $.env.get('LANG'))
107  return isRussian(locale) ? 'ru' : 'en'
108}
109
110const failedWords = () => ({ error: s().error, killed: s().killed, stalled: s().stalled })
111
112/** Runs on screen: a new job hides runs that ended before it began. */
113const visible = (flow: CrewFlow | null, runs: CrewRun[]): CrewRun[] =>
114  flow ? runs.filter(r => r.status === 'running' || (r.endedAt ?? r.startedAt) >= flow.startedAt) : runs
115
116/** Planned tasks no run has picked up yet. */
117function pending(flow: CrewFlow | null, runs: CrewRun[]): Array<CrewTask & { n: number }> {
118  if (!flow || flow.finished) return []
119  const started = new Set(runs.map(r => normalize(r.description)))
120  return flow.tasks.map((t, i) => ({ ...t, n: i + 1 })).filter(t => !started.has(normalize(t.title)))
121}
122
123function totals(runs: CrewRun[], now: number) {
124  let cost = 0
125  let tokens = 0
126  let start = Infinity
127  let end = 0
128  for (const r of runs) {
129    cost += r.costUsd
130    tokens += r.tokens
131    start = Math.min(start, r.startedAt)
132    end = Math.max(end, r.endedAt ?? Math.max(now, r.startedAt))
133  }
134  return { cost, tokens, time: runs.length ? end - start : 0 }
135}
136
137function flowLabel(f: CrewFlow, running: number, done = f.done): string {
138  const phase = f.phase === 'plan' && running > 0 ? 'delegate' : f.phase
139  if (f.finished) return s().phase.close
140  if (phase === 'plan' || phase === 'design') return s().phase[phase]
141  const count = f.total ? `${done}/${f.total}` : `${running} ${s().busy}`
142  return `${phase === 'review' ? s().phase.review : s().phase.delegate} ${count}`
143}
144
145const flowRatio = (f: CrewFlow, done = f.done): number => (f.finished ? 1 : f.total ? done / f.total : 0)
146
147function segments(f: CrewFlow, runs: CrewRun[]): Array<'done' | 'running' | 'todo'> {
148  const total = f.finished ? Math.max(f.total, 1) : f.total
149  const byTitle = new Map(runs.map(r => [normalize(r.description), r.status]))
150  const inFlight = f.tasks.length ? f.tasks.filter(t => byTitle.get(normalize(t.title)) === 'running').length : runs.filter(r => r.status === 'running').length
151  const done = doneCount(f, runs)
152  return Array.from({ length: total }, (_, i) => (f.finished || i < done ? 'done' : i < done + inFlight ? 'running' : 'todo'))
153}
154
155function sumBuckets(sources: CrewUsageBuckets[], since: number) {
156  const out = { tokens: 0, costUsd: 0, requests: 0 }
157  const first = Math.floor(since / HOUR)
158  for (const b of sources)
159    for (const [hour, v] of Object.entries(b)) {
160      if (Number(hour) < first) continue
161      out.tokens += v.tokens
162      out.costUsd += v.costUsd
163      out.requests += v.requests
164    }
165  return out
166}
167
168/** Other sessions' buckets from `$.store`, dropping entries older than a week. */
169async function loadOthers($: EngineInterface): Promise<void> {
170  const cutoff = Math.floor(((await $.clock.now()) - SEVEN_DAYS - HOUR) / HOUR)
171  const merged: CrewUsageBuckets = {}
172  for (const key of await $.store.keys()) {
173    if (!key.startsWith('usage:') || key === storeKey) continue
174    const value = (await $.store.get(key)) as CrewUsageBuckets | undefined
175    let fresh = 0
176    for (const [hour, v] of Object.entries(value ?? {})) {
177      if (Number(hour) < cutoff) continue
178      fresh++
179      const m = (merged[hour] ??= { tokens: 0, costUsd: 0, requests: 0 })
180      m.tokens += v.tokens
181      m.costUsd += v.costUsd
182      m.requests += v.requests
183    }
184    if (!fresh) await $.store.delete(key)
185  }
186  await update($, othersAtom, () => merged)
187}
188
189function toWindows(rateLimits: ReadonlyArray<{ kind: string; percentUsed: number; resetsAt?: string }>): CrewLimitWindow[] {
190  return rateLimits.map(w => {
191    const resetsAt = w.resetsAt ? Date.parse(w.resetsAt) : NaN
192    return { kind: w.kind, percentUsed: w.percentUsed, resetsAt: Number.isFinite(resetsAt) ? resetsAt : 0 }
193  })
194}
195
196async function togglePane($: EngineInterface): Promise<boolean> {
197  if ((await $.ui.panes()).some(p => p.id === PANE)) {
198    await $.ui.close({ id: PANE })
199    return false
200  }
201  await update($, nowAtom, () => Date.now())
202  await $.ui.open({ id: PANE, title: s().appName })
203  return true
204}
205
206/** Opens the panel by itself once per job (and once for the session's first subagent). */
207async function autoOpen($: EngineInterface, key: string): Promise<void> {
208  const panel = await read($, panelAtom)
209  if (panel.autoOpenedFor.includes(key)) return
210  await update($, panelAtom, p => ({ ...p, autoOpenedFor: [...p.autoOpenedFor, key].slice(-20) }))
211  if (!(await $.ui.panes()).some(p => p.id === PANE)) void $.ui.open({ id: PANE, title: s().appName })
212}
213
214// ---------------------------------------------------------------------------
215// The main loop's turn: every prompt moves the bar, subagents or not.
216
217/** `mcp__server__ctx_execute` → `ctx_execute`; built-in names stay. */
218const shortTool = (name: string): string => name.split('__').pop() || name
219
220const newTurn = (turnId: string, prompt: string, at: number): CrewTurn => ({
221  turnId,
222  prompt: clip(prompt.replace(/\s+/g, ' ').trim(), 120),
223  status: 'running',
224  startedAt: at,
225  steps: 0,
226  tools: 0,
227  tokens: 0,
228  costUsd: 0,
229})
230
231function turnWord(t: CrewTurn): string {
232  return t.status === 'running' ? s().working : t.status === 'done' ? s().answered : s().stopped
233}
234
235function turnStats(t: CrewTurn, now: number): string {
236  const time = fmtTime((t.endedAt ?? Math.max(now, t.startedAt)) - t.startedAt)
237  const tool = t.status === 'running' && t.lastTool ? ` (${t.lastTool})` : ''
238  return `${t.steps} ${s().steps} · ${t.tools} ${s().tools}${tool} · ${time} · ≈${fmtCost(t.costUsd)}`
239}
240
241/** One segment per model request (the last 24), the one in flight striped. */
242function turnSegments(t: CrewTurn): Array<'done' | 'running'> {
243  if (t.status !== 'running') return Array.from({ length: Math.max(1, Math.min(24, t.steps)) }, () => 'done' as const)
244  return [...Array.from({ length: Math.min(23, t.steps) }, () => 'done' as const), 'running' as const]
245}
246
247/** A block sliding along the track while a turn runs; full once it ends. */
248function pulseBar(t: CrewTurn, now: number, width: number): string {
249  if (t.status !== 'running') return textBar(1, width)
250  const block = Math.min(3, width)
251  const pos = Math.floor((now - t.startedAt) / 1000) % (width - block + 1)
252  return '▱'.repeat(pos) + '▰'.repeat(block) + '▱'.repeat(width - block - pos)
253}
254
255// ---------------------------------------------------------------------------
256// The browser view: optional, started only by /agents-web or the panel's button.
257// It is the package's own CLI dashboard (dist/luff-crew.mjs), following this
258// session's transcript on localhost; it ends with the session or on request.
259
260let stopWeb: (() => void) | null = null
261
262async function findNode($: EngineInterface): Promise<string | null> {
263  const works = async (bin: string): Promise<boolean> => {
264    try {
265      return (await $.process.run([bin, '--version'], { timeoutMs: 5000 })).exitCode === 0
266    } catch {
267      return false
268    }
269  }
270  if (await works('node')) return 'node'
271  const nvm = await $.env.get('NVM_BIN')
272  if (nvm && (await works(`${nvm}/node`))) return `${nvm}/node`
273  // Apps started from the Dock lack the shell's PATH: ask the login shell.
274  try {
275    const shell = (await $.env.get('SHELL')) || '/bin/sh'
276    const { stdout } = await $.process.run([shell, '-ilc', 'command -v node'], { timeoutMs: 8000 })
277    const found = stdout
278      .split('\n')
279      .map(l => l.trim())
280      .reverse()
281      .find(l => l.startsWith('/') && l.endsWith('/node'))
282    if (found && (await works(found))) return found
283  } catch {
284    // No login shell: try the usual places.
285  }
286  for (const bin of ['/opt/homebrew/bin/node', '/usr/local/bin/node', '/usr/bin/node']) if (await works(bin)) return bin
287  return null
288}
289
290async function openUrl($: EngineInterface, url: string): Promise<void> {
291  for (const argv of [['open', url], ['xdg-open', url], ['cmd', '/c', 'start', '""', url]]) {
292    try {
293      if ((await $.process.run(argv, { timeoutMs: 5000 })).exitCode === 0) return
294    } catch {
295      // Not this platform's opener.
296    }
297  }
298}
299
300async function startWebView($: EngineInterface): Promise<string> {
301  const cur = await read($, webAtom)
302  if (cur?.status === 'running' && stopWeb) {
303    await openUrl($, cur.url)
304    return `${s().webAt}: ${cur.url}`
305  }
306  if (cur?.status === 'starting') return s().webStarting
307  await update($, webAtom, () => ({ status: 'starting' as const, url: '', startedAt: Date.now() }))
308
309  const node = await findNode($)
310  if (!node) {
311    await update($, webAtom, () => null)
312    return 'The browser view needs Node.js 18.17 or newer, and none was found on PATH. Install Node.js, then run /agents-web again.'
313  }
314  const [cwd, sessionId] = await Promise.all([$.session.cwd(), $.session.id()])
315  const argv = [node, `${$.plugin.root}/dist/luff-crew.mjs`, 'dashboard', '--project', cwd, ...(sessionId ? ['--session', sessionId] : [])]
316  const child = $.process.spawn({ argv, env: { LUFF_CREW_LANG: lang } })
317
318  let settle: (url: string | null) => void = () => {}
319  const found = new Promise<string | null>(resolve => (settle = resolve))
320  let isStopped = false
321  stopWeb = () => {
322    isStopped = true
323    void child.return(undefined as never).catch(() => {})
324  }
325  void (async () => {
326    let out = ''
327    let errors = ''
328    try {
329      for await (const { stream, text } of child) {
330        if (stream === 'stderr') errors = (errors + text).slice(-2000)
331        out = (out + text).slice(-4000)
332        const m = /dashboard:\s*(https?:\/\/\S+)/i.exec(out)
333        if (m) {
334          settle(m[1]!)
335          await update($, webAtom, () => ({ status: 'running' as const, url: m[1]!, startedAt: Date.now() }))
336          out = ''
337        }
338      }
339    } catch (err) {
340      errors ||= String(err)
341    }
342    settle(null)
343    stopWeb = null
344    await update($, webAtom, () => null).catch(() => {})
345    if (!isStopped && errors.trim()) $.ui.log(`luff-crew: the browser view stopped: ${clip(errors.trim(), 300)}`, { to: 'debug' })
346  })()
347
348  const url = await Promise.race([found, $.clock.sleep(15_000).then(() => null)])
349  if (url) return `${s().webAt}: ${url} (opened in your browser; /agents-web stop ends it)`
350  stopWeb?.()
351  return 'The browser view did not start. Run Claude Code with --debug for the reason, or start it by hand: luff-crew-monitor dashboard'
352}
353
354async function stopWebView($: EngineInterface): Promise<string> {
355  const wasRunning = !!stopWeb
356  stopWeb?.()
357  stopWeb = null
358  await update($, webAtom, () => null)
359  return wasRunning ? 'Browser view stopped.' : 'No browser view is running.'
360}
361
362// ---------------------------------------------------------------------------
363
364export const register: Register = (on, options) => {
365  const stepReports = stepReportsOf(options.stepReports)
366  on('session.start', async ($, e, next) => {
367    const started = await next(e)
368    lang = await detectLang($, options.language)
369    const at = await $.clock.now()
370    storeKey = `usage:${at.toString(36)}${Math.random().toString(36).slice(2, 6)}`
371
372    await $.tool.register({
373      name: 'progress',
374      isDeferred: false,
375      description:
376        'Report the progress of a multi-agent job to the Luff Crew panel and job bar. ' +
377        'Call it after presenting the plan (title, tasks, phase "delegate"), each time a task is accepted (done), ' +
378        'when switching phase or re-planning (tasks), and once at the end with finished: true. ' +
379        'Omitted fields keep their previous value; a new title starts a new job.',
380      inputSchema: {
381        type: 'object',
382        properties: {
383          title: { type: 'string', description: 'Short name of the overall job, a few words.' },
384          total: { type: 'integer', minimum: 0, description: 'Number of planned worker tasks; defaults to the number of tasks.' },
385          done: { type: 'integer', minimum: 0, description: 'Number of tasks accepted so far.' },
386          phase: { type: 'string', enum: ['plan', 'design', 'delegate', 'review', 'close'] },
387          finished: { type: 'boolean', description: 'True once the whole job is closed.' },
388          tasks: {
389            type: 'array',
390            description: 'The planned worker tasks in order, numbered from 1. Each title must equal the Agent tool `description` it will be delegated with.',
391            items: {
392              type: 'object',
393              properties: {
394                title: { type: 'string' },
395                agent: { type: 'string', description: 'Subagent type, e.g. general-purpose or Explore.' },
396                model: { type: 'string', description: 'Expected model, e.g. opus, sonnet, haiku.' },
397                effort: { type: 'string', enum: ['low', 'medium', 'high', 'xhigh', 'max'] },
398                after: { type: 'array', items: { type: 'integer' }, description: 'Numbers of the tasks this one waits for.' },
399              },
400              required: ['title'],
401            },
402          },
403        },
404      },
405    })
406    // With step reports off, subagents never call it: leave its schema out of every request.
407    if (stepReports !== 'off') {
408      await $.tool.register({
409        name: 'step',
410        isDeferred: false,
411        description:
412          'For subagents: report progress on your own task to the Luff Crew panel. Right after reading your brief, call it with ' +
413          '`total` (your plan in 3-8 steps) and `done: 0`; call it again only as often as your brief asks. Silent: it only moves your bar.',
414        inputSchema: {
415          type: 'object',
416          properties: {
417            done: { type: 'integer', minimum: 0, description: 'Steps finished so far.' },
418            total: { type: 'integer', minimum: 1, description: 'Steps planned; may change.' },
419            note: { type: 'string', description: 'The step in progress, a few words.' },
420          },
421          required: ['done'],
422        },
423      })
424    }
425    await $.command.register({
426      name: 'agents-info',
427      description: 'Show or hide the Luff Crew panel: subagents, plan limits, cost and time',
428      immediate: true,
429    })
430    await $.command.register({
431      name: 'agents-web',
432      description: 'Open the Luff Crew view in your browser (localhost); /agents-web stop ends it',
433      argumentHint: '[stop]',
434      immediate: true,
435    })
436
437    try {
438      const usage = await $.session.usage()
439      if (usage.rateLimits.length) await update($, limitsAtom, () => ({ windows: toWindows(usage.rateLimits), measuredAt: at }))
440    } catch {
441      // No reading yet: the first response brings one.
442    }
443    await loadOthers($).catch(() => {})
444
445    // Running clocks tick once a second; other sessions' usage refreshes each minute.
446    let ticks = 0
447    $.clock.every(1000, () => {
448      void (async () => {
449        ticks++
450        if (ticks % 60 === 0) await loadOthers($).catch(() => {})
451        const runs = await read($, runsAtom)
452        const turn = await read($, turnAtom)
453        if (runs.some(r => r.status === 'running') || turn?.status === 'running' || ticks % 30 === 0) await update($, nowAtom, () => Date.now())
454      })()
455    })
456    return started
457  })
458
459  // Teach the model the protocol, for the whole session.
460  on('prompt.compose', async ($, e, next) => {
461    const composed = await next(e)
462    return { sections: [...composed.sections, { id: 'luff-crew-protocol', text: protocol(stepReports), scope: 'session' as const }] }
463  })
464
465  on('command.run', { command: 'agents-info' }, async $ => {
466    const isOpen = await togglePane($)
467    return { text: isOpen ? 'Luff Crew panel opened.' : 'Luff Crew panel closed.' }
468  })
469
470  on('command.run', { command: 'agents-web' }, async ($, e) => {
471    const arg = e.args.trim().toLowerCase()
472    return { text: arg === 'stop' || arg === 'off' || arg === 'close' ? await stopWebView($) : await startWebView($) }
473  })
474
475  // Each prompt starts a turn of the main loop: the bar follows it from here.
476  on('turn.start', async ($, e, next) => {
477    try {
478      if (!(e as { agentId?: string }).agentId) {
479        const at = await $.clock.now()
480        await update($, turnAtom, () => newTurn(e.turnId, e.text, at))
481        await update($, nowAtom, () => at)
482      }
483    } catch {
484      // Bookkeeping never holds up a turn.
485    }
486    return next(e)
487  })
488
489  on('tool.call', { tool: TOOL_PROGRESS }, async ($, e) => {
490    const input = e as unknown as ProgressInput
491    const at = await $.clock.now()
492    const prev = await read($, flowAtom)
493    if (startsNewFlow(prev, input) && input.title?.trim()) {
494      // A new job starts with a clean list; agents still running stay.
495      await update($, runsAtom, list => list.filter(r => r.status === 'running'))
496    }
497    const tasks = cleanTasks(input.tasks)
498    const next = await update($, flowAtom, p => applyProgress(p, { ...input, ...(tasks ? { tasks } : {}) }, at) as CrewFlow)
499    await update($, panelAtom, p => ({ ...p, hiddenAt: 0 }))
500    const runs = await read($, runsAtom)
501    const running = runs.filter(r => r.status === 'running').length
502    if (next && input.tasks?.length) await autoOpen($, `job:${next.title}`)
503    return { result: `ok: ${next ? flowLabel(next, running, doneCount(next, runs)) : 'ok'}` }
504  }).catch(() => ({ result: 'ok' }))
505
506  // A worker's own steps: the call runs in the worker's loop, so `agentId` names it.
507  on('tool.call', { tool: TOOL_STEP }, async ($, e) => {
508    const input = e as unknown as { done?: number; total?: number; note?: string }
509    const agentId = e.agentId
510    if (!agentId) return { result: 'ignored: only subagents report steps' }
511    const int = (v: unknown): number | undefined => (typeof v === 'number' && Number.isFinite(v) ? Math.max(0, Math.round(v)) : undefined)
512    await update($, runsAtom, list =>
513      list.map(r => {
514        if (r.agentId !== agentId) return r
515        const total = int(input.total) ?? r.step?.total ?? 0
516        const done = int(input.done) ?? r.step?.done ?? 0
517        const note = typeof input.note === 'string' ? clip(input.note.trim(), 80) : ''
518        return { ...r, step: { total, done: total ? Math.min(total, done) : done, ...(note ? { note } : {}) } }
519      }),
520    )
521    return { result: 'ok' }
522  }).catch(() => ({ result: 'ok' }))
523
524  on('agent.spawn', async ($, e, next) => {
525    const started = await next(e)
526    if (started.deny !== undefined) return started
527    const at = await $.clock.now()
528    await update($, runsAtom, list => {
529      const round = 1 + list.filter(r => e.description && normalize(r.description) === normalize(e.description)).length
530      const run: CrewRun = {
531        id: started.agentId ?? e.tool_use_id,
532        type: e.subagentType,
533        description: e.description,
534        model: started.model,
535        status: 'running',
536        startedAt: at,
537        contextTokens: 0,
538        contextMax: contextWindowOf(started.model),
539        tokens: 0,
540        costUsd: 0,
541        requests: 0,
542        round,
543      }
544      if (started.agentId) run.agentId = started.agentId
545      return [...list.filter(r => r.id !== run.id), run].slice(-200)
546    })
547    await update($, nowAtom, () => at)
548    await autoOpen($, 'first-subagent')
549    return started
550  }).catch(($, e, next) => next(e)) // never block a launch over bookkeeping
551
552  // Every model request, main loop and subagents: usage for the limits panel,
553  // and a subagent's live model, effort, context, tokens and cost.
554  on('turn.step', async function* ($, e, next) {
555    const result = yield* next(e)
556    const at = await $.clock.now()
557    const usage = result.usage
558    const model = usage?.model || e.model
559    const tokens = usage ? tokensOf(usage) : 0
560    const cost = usage ? costOf(model, usage) : 0
561
562    // The main loop's turn: one more request, the tools it asked for.
563    if (!e.agentId) {
564      const last = result.toolUses.at(-1)?.name
565      await update($, turnAtom, t => {
566        const base = t && t.turnId === e.turnId ? t : newTurn(e.turnId, '', at)
567        return {
568          ...base,
569          status: 'running' as const,
570          steps: base.steps + 1,
571          tools: base.tools + result.toolUses.length,
572          ...(last ? { lastTool: shortTool(last) } : {}),
573          tokens: base.tokens + tokens,
574          costUsd: base.costUsd + cost,
575        }
576      })
577    }
578    if (!usage) return result
579
580    const hour = String(Math.floor(at / HOUR))
581    const own = await update($, usageAtom, b => {
582      const cur = b[hour] ?? { tokens: 0, costUsd: 0, requests: 0 }
583      const kept = Object.fromEntries(Object.entries(b).filter(([h]) => Number(h) >= Math.floor((at - SEVEN_DAYS) / HOUR)))
584      return { ...kept, [hour]: { tokens: cur.tokens + tokens, costUsd: cur.costUsd + cost, requests: cur.requests + 1 } }
585    })
586    if (storeKey) void $.store.set(storeKey, own).catch(() => {})
587
588    const agentId = e.agentId
589    if (agentId) {
590      await update($, runsAtom, list =>
591        list.map(r =>
592          r.agentId !== agentId
593            ? r
594            : {
595                ...r,
596                model,
597                ...(typeof e.effort === 'string' ? { effort: e.effort } : {}),
598                status: 'running' as const,
599                contextTokens: tokens,
600                contextMax: contextWindowOf(model),
601                tokens: r.tokens + tokens,
602                costUsd: r.costUsd + cost,
603                requests: r.requests + 1,
604              },
605        ),
606      )
607    }
608    return result
609  })
610
611  on('turn.complete', async ($, e, next) => {
612    const agentId = e.agentId
613    if (agentId) {
614      const at = await $.clock.now()
615      const reason = e.reason
616      await update($, runsAtom, list =>
617        list.map(r => {
618          if (r.agentId !== agentId) return r
619          const out: CrewRun = { ...r, status: reason === 'answer' ? 'done' : 'failed', endedAt: at }
620          if (reason === 'aborted') out.failure = 'killed'
621          else if (reason !== 'answer') out.failure = 'error'
622          else delete out.failure
623          // A run whose steps went unseen still gets the turn's own sum.
624          if (r.requests === 0 && e.usage) {
625            const model = e.usage.model || r.model
626            out.model = model
627            out.tokens = tokensOf(e.usage)
628            out.costUsd = costOf(model, e.usage)
629          }
630          return out
631        }),
632      )
633      await update($, nowAtom, () => at)
634    } else {
635      const at = await $.clock.now()
636      const reason = e.reason
637      await update($, turnAtom, t => {
638        if (!t || (t.turnId !== e.turnId && t.status !== 'running')) return t
639        const out: CrewTurn = { ...t, status: reason === 'answer' ? 'done' : 'failed', endedAt: at }
640        if (reason === 'aborted') out.failure = 'stopped'
641        else if (reason !== 'answer') out.failure = 'error'
642        else delete out.failure
643        delete out.lastTool
644        return out
645      })
646      await update($, nowAtom, () => at)
647    }
648    return next(e)
649  })
650
651  // Plan usage: the 5-hour and weekly windows, as the status line has them.
652  on('session.measure', async ($, e, next) => {
653    if (e.changed.includes('rateLimits')) {
654      const at = await $.clock.now()
655      await update($, limitsAtom, () => ({ windows: toWindows(e.rateLimits), measuredAt: at }))
656    }
657    return next(e)
658  })
659
660  // ---------------------------------------------------------------------------
661  // The panel
662
663  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
664    const ui = $.ui.resolve(e)
665    const { Box, Text, Button } = ui
666    const flow = await read($, flowAtom)
667    const all = await read($, runsAtom)
668    const panel: CrewPanel = await read($, panelAtom)
669    const limits = await read($, limitsAtom)
670    const own = await read($, usageAtom)
671    const others = await read($, othersAtom)
672    const turn = await read($, turnAtom)
673    const web = await read($, webAtom)
674    const now = Math.max(await read($, nowAtom), ...all.map(r => r.startedAt), turn?.startedAt ?? 0, 0)
675
676    const runs = visible(flow, all)
677    const running = runs.filter(r => r.status === 'running').reverse()
678    const finished = runs.filter(r => r.status !== 'running').reverse()
679    const planned = pending(flow, runs)
680    // Every crew member keeps one look: planned tasks by title, other runs by id.
681    const crewSlot = crewSlots(flow?.title ?? '', [...(flow?.tasks ?? []).map(t => normalize(t.title)), ...runs.map(r => normalize(r.description) || r.id)])
682    const slotOf = (title: string) => crewSlot(normalize(title))
683    const runSlot = (r: CrewRun) => crewSlot(normalize(r.description) || r.id)
684    const t = totals(runs, now)
685    const title = flow && !flow.finished ? flow.title : ''
686    const isEmpty = !runs.length && !planned.length
687    const words = { round: s().round, failed: failedWords() }
688
689    const five = limits.windows.find(w => w.kind === 'five_hour')
690    const week = limits.windows.find(w => w.kind === 'seven_day')
691    const limitRows = [
692      { label: s().fiveHour, window: five, span: s().lastHours, since: five?.resetsAt ? five.resetsAt - FIVE_HOURS : now - FIVE_HOURS },
693      { label: s().weekly, window: week, span: s().lastDays, since: week?.resetsAt ? week.resetsAt - SEVEN_DAYS : now - SEVEN_DAYS },
694    ].map(r => ({ ...r, local: sumBuckets([own, others], r.since) }))
695
696    const toggleCompact = (
697      <Button key="compact" plain label={panel.isCompact ? s().expand : s().collapse} onPress={() => update($, panelAtom, p => ({ ...p, isCompact: !p.isCompact }))} />
698    )
699    const toggleLimits = (
700      <Button
701        key="limits"
702        plain
703        label={`${panel.isLimitsOpen ? '▾' : '▸'} ${s().limits}`}
704        onPress={() => update($, panelAtom, p => ({ ...p, isLimitsOpen: !p.isLimitsOpen }))}
705      />
706    )
707    const turnHead = turn ? `${turn.status === 'running' ? s().thisPrompt : s().lastPrompt}: ${turnWord(turn)}` : ''
708    const turnLine = turn ? `${turn.prompt ? `“${clip(turn.prompt, 60)}” · ` : ''}${turnStats(turn, now)}` : ''
709    const webButton = (
710      <Button
711        key="web"
712        plain
713        label={web ? (web.status === 'running' ? s().stopWeb : s().webStarting) : s().openWeb}
714        onPress={async () => {
715          const cur = await read($, webAtom)
716          if (cur?.status === 'running') await stopWebView($)
717          else if (!cur) $.ui.toast(await startWebView($))
718        }}
719      />
720    )
721    const webLine = web?.status === 'running' ? `${s().webAt}: ${web.url}` : ''
722    const toggleFinished = (
723      <Button
724        key="finished"
725        plain
726        label={`${panel.isFinishedOpen ? '▾' : '▸'} ${s().finished} · ${finished.length}`}
727        onPress={() => update($, panelAtom, p => ({ ...p, isFinishedOpen: !p.isFinishedOpen }))}
728      />
729    )
730
731    if (e.surface !== 'terminal' && 'Svg' in ui) {
732      const { Svg } = ui
733      const W = Math.max(260, Math.min(900, (e.props.bodyColumns || 48) * 8 - 8))
734      const barW = Math.max(120, W - MASCOT_W - 34)
735      const icons = [
736        ...running.map(r => ({ slot: runSlot(r), effort: r.effort, running: true, dim: false })),
737        ...finished.map(r => ({ slot: runSlot(r), effort: r.effort, running: false, dim: false })),
738        ...planned.map(p => ({ slot: slotOf(p.title), effort: p.effort, running: false, dim: true })),
739      ]
740      // Words are engine Text (themed by the app); pictures are theme-neutral SVG.
741      const runRow = (r: CrewRun, prefix: string) => {
742        const color = typeColor(r.type)
743        const progress = progressOf(r)
744        const steps = stepText(r)
745        return (
746          <Box key={`${prefix}-${r.id}`} flexDirection="row" gap={1} alignItems="center">
747            <Svg key="m" source={mascotSvg(runSlot(r), r.effort, { running: r.status === 'running', dim: r.status === 'failed' })} alt={r.type} width={MASCOT_W} height={MASCOT_H} />
748            <Box key="body" flexDirection="column" flexGrow={1}>
749              <Text key="d" bold wrap="truncate-end">
750                <Text color={statusColor(r.status, color)}>{statusGlyph(r.status)}</Text> {r.description || r.type}
751              </Text>
752              <Text key="meta" wrap="truncate-end">
753                <Text color={color} bold>
754                  {r.type}
755                </Text>
756                <Text dimColor> · {runMeta(r, words)}</Text>
757              </Text>
758              <Text key="stats" dimColor wrap="truncate-end">
759                {steps ? `${steps}   ` : ''}
760                {runStats(r, now)}
761              </Text>
762              <Svg
763                key="bar"
764                source={barSvg(barW, progress ?? ctxPercent(r) / 100, progress === null ? '#8a8a8a' : r.status === 'failed' ? BAD : color, 4)}
765                alt={progress === null ? `context ${ctxPercent(r)}%` : `${Math.round(progress * 100)}%`}
766                width={barW}
767                height={4}
768              />
769            </Box>
770          </Box>
771        )
772      }
773      const limitRow = (row: (typeof limitRows)[number]) => {
774        const pct = row.window?.percentUsed
775        const reset = row.window?.resetsAt ? ` · ${s().resetsIn} ${fmtDuration(row.window.resetsAt - now)}` : ''
776        return (
777          <Box key={`limit-${row.label}`} flexDirection="column">
778            <Box key="head" flexDirection="row" justifyContent="space-between">
779              <Text key="l" bold>
780                {row.label}
781              </Text>
782              <Text key="r" dimColor>
783                {pct === undefined ? s().noPlan : `${Math.round(pct)}%${reset}`}
784              </Text>
785            </Box>
786            <Svg key="bar" source={barSvg(W, pct === undefined ? null : pct / 100, meterColor(pct ?? 0), 7)} alt={`${row.label} ${pct ?? 0}%`} width={W} height={7} />
787            <Text key="local" dimColor wrap="truncate-end">
788              {`${row.span}: ${fmtTokens(row.local.tokens)} ${s().tokensWord} · ≈${fmtCost(row.local.costUsd)} · ${row.local.requests} ${s().requests}`}
789            </Text>
790          </Box>
791        )
792      }
793      return (
794        <Box flexDirection="column" gap={1}>
795          {title ? (
796            <Text key="title" bold>
797              {title}
798            </Text>
799          ) : null}
800          <Text key="totals">
801            <Text dimColor>{s().cost} </Text>
802            <Text bold>≈{fmtCost(t.cost)}</Text>
803            <Text dimColor>{`   ${s().tokens} `}</Text>
804            <Text bold>{fmtTokens(t.tokens)}</Text>
805            <Text dimColor>{`   ${s().time} `}</Text>
806            <Text bold>{fmtTime(t.time)}</Text>
807          </Text>
808          {turn ? (
809            <Box key="turn" flexDirection="column">
810              <Text key="h" bold>
811                <Text color={statusColor(turn.status, ACCENT)}>{statusGlyph(turn.status)}</Text> {turnHead}
812              </Text>
813              <Text key="d" dimColor wrap="truncate-end">
814                {turnLine}
815              </Text>
816            </Box>
817          ) : null}
818          {toggleLimits}
819          {panel.isLimitsOpen ? limitRows.map(limitRow) : null}
820          {panel.isLimitsOpen && !limits.windows.length ? (
821            <Text key="limits-hint" dimColor>
822              {s().limitsHint}
823            </Text>
824          ) : null}
825          {toggleCompact}
826          {isEmpty ? (
827            <Text key="empty" dimColor>
828              {s().empty}
829            </Text>
830          ) : null}
831          {panel.isCompact && !isEmpty ? <Svg key="strip" source={stripSvg(W, icons)} alt={s().agentsCount(icons.length)} width={Math.min(W, icons.length * STRIP_STEP)} height={STRIP_H} /> : null}
832          {!panel.isCompact && running.length > 0 ? (
833            <Text key="h-running" dimColor>
834              {`${s().running} · ${running.length}`}
835            </Text>
836          ) : null}
837          {!panel.isCompact ? running.map(r => runRow(r, 'run')) : null}
838          {!panel.isCompact && finished.length > 0 ? toggleFinished : null}
839          {!panel.isCompact && panel.isFinishedOpen ? finished.map(r => runRow(r, 'fin')) : null}
840          {!panel.isCompact && planned.length > 0 ? (
841            <Text key="h-planned" dimColor>
842              {`${s().planned} · ${planned.length}`}
843            </Text>
844          ) : null}
845          {!panel.isCompact
846            ? planned.map(p => (
847                <Box key={`plan-${p.n}`} flexDirection="row" gap={1} alignItems="center">
848                  <Svg key="m" source={mascotSvg(slotOf(p.title), p.effort, { dim: true })} alt="planned" width={MASCOT_W} height={MASCOT_H} />
849                  <Box key="body" flexDirection="column" flexGrow={1}>
850                    <Text key="t" dimColor bold wrap="truncate-end">
851                      ◷ {p.n}. {p.title}
852                    </Text>
853                    <Text key="m" dimColor wrap="truncate-end">
854                      {[p.agent, p.model ? modelLabel(p.model) : '', p.effort, p.after.length ? `${s().after} ${p.after.join(', ')}` : ''].filter(Boolean).join(' · ') || ' '}
855                    </Text>
856                  </Box>
857                </Box>
858              ))
859            : null}
860          <Text key="estimate" dimColor>
861            {s().estimate}
862          </Text>
863          {webButton}
864          {webLine ? (
865            <Text key="web-url" dimColor wrap="truncate-end">
866              {webLine}
867            </Text>
868          ) : null}
869        </Box>
870      )
871    }
872
873    // Terminal: the same panel in text.
874    const cols = Math.max(30, e.props.bodyColumns || 60)
875    const barW = Math.max(8, Math.min(24, cols - 40))
876    // The half-block mascot at a row's left edge, dropped when the pane is too narrow.
877    const hasMascot = cols >= 40
878    const termMascot = (slot: number, effort: string | undefined, opts: { running?: boolean; dim?: boolean }) => (
879      <Box key="m" flexDirection="column" width={TERM_MASCOT_W} flexShrink={0}>
880        {mascotCells(slot, effort, opts.running ? Math.floor(now / 1000) : 0).map((cells, i) => (
881          <Text key={`l${i}`} dimColor={opts.dim}>
882            {cells.map((c, k) => (
883              <Text key={`c${k}`} color={c.fg} backgroundColor={c.bg}>
884                {c.ch}
885              </Text>
886            ))}
887          </Text>
888        ))}
889      </Box>
890    )
891    const row = (r: CrewRun) => {
892      const progress = progressOf(r)
893      const color = typeColor(r.type)
894      const steps = stepText(r)
895      const indent = hasMascot ? '' : '  '
896      return (
897        <Box key={`row-${r.id}`} flexDirection="row" gap={1} marginBottom={1}>
898          {hasMascot ? termMascot(runSlot(r), r.effort, { running: r.status === 'running', dim: r.status === 'failed' }) : null}
899          <Box key="body" flexDirection="column" flexGrow={1}>
900            <Text wrap="truncate-end">
901              <Text color={r.status === 'failed' ? 'red' : r.status === 'done' ? 'green' : color}>{r.status === 'running' ? '●' : r.status === 'done' ? '✓' : '✗'}</Text>{' '}
902              <Text bold>{r.description || r.type}</Text>
903            </Text>
904            <Text dimColor wrap="truncate-end">
905              {indent}
906              {r.type} · {runMeta(r, words)}
907            </Text>
908            <Text wrap="truncate-end">
909              {indent}
910              {progress === null ? <Text dimColor>{textBar(ctxPercent(r) / 100, barW)}</Text> : <Text color={color}>{textBar(progress, barW)}</Text>}
911              <Text dimColor>
912                {' '}
913                {steps ? steps + ' · ' : ''}
914                {runStats(r, now)}
915              </Text>
916            </Text>
917          </Box>
918        </Box>
919      )
920    }
921    const limitLine = (r: (typeof limitRows)[number]) => (
922      <Text key={`lim-${r.label}`} wrap="truncate-end">
923        {r.label.padEnd(15)}{' '}
924        {r.window ? (
925          <Text>
926            {textBar(r.window.percentUsed / 100, barW)} {Math.round(r.window.percentUsed)}%
927          </Text>
928        ) : (
929          <Text dimColor>{s().noPlan}</Text>
930        )}
931        <Text dimColor>
932          {'  '}
933          {fmtTokens(r.local.tokens)} · ≈{fmtCost(r.local.costUsd)}
934        </Text>
935      </Text>
936    )
937    return (
938      <Box flexDirection="column">
939        {title ? <Text bold>{title}</Text> : null}
940        <Text dimColor>
941          {s().cost} ≈{fmtCost(t.cost)} · {s().tokens} {fmtTokens(t.tokens)} · {s().time} {fmtTime(t.time)}
942        </Text>
943        {turn ? (
944          <Text wrap="truncate-end">
945            <Text color={turn.status === 'failed' ? 'red' : turn.status === 'done' ? 'green' : 'magenta'}>{statusGlyph(turn.status)}</Text> {turnHead}
946            <Text dimColor> · {turnLine}</Text>
947          </Text>
948        ) : null}
949        <Box flexDirection="row" gap={2} marginTop={1}>
950          {toggleLimits}
951          {toggleCompact}
952          {webButton}
953        </Box>
954        {webLine ? <Text dimColor wrap="truncate-end">{webLine}</Text> : null}
955        {panel.isLimitsOpen ? limitRows.map(limitLine) : null}
956        {isEmpty ? <Text dimColor>{s().empty}</Text> : null}
957        {panel.isCompact ? (
958          <Text wrap="truncate-end">
959            {[...running, ...finished].map(r => (r.status === 'running' ? '● ' : r.status === 'done' ? '✓ ' : '✗ ')).join('')}
960            <Text dimColor>{planned.map(() => '◷ ').join('')}</Text>
961          </Text>
962        ) : (
963          <Box flexDirection="column" marginTop={1}>
964            {running.length > 0 ? <Text dimColor>{`${s().running} · ${running.length}`}</Text> : null}
965            {running.map(row)}
966            {finished.length > 0 ? toggleFinished : null}
967            {panel.isFinishedOpen ? finished.map(row) : null}
968            {planned.length > 0 ? <Text dimColor>{`${s().planned} · ${planned.length}`}</Text> : null}
969            {planned.map(p =>
970              hasMascot ? (
971                <Box key={`plan-${p.n}`} flexDirection="row" gap={1} marginBottom={1}>
972                  {termMascot(slotOf(p.title), p.effort, { dim: true })}
973                  <Box key="body" flexDirection="column" flexGrow={1}>
974                    <Text key="t" dimColor bold wrap="truncate-end">
975                      ◷ {p.n}. {p.title}
976                    </Text>
977                    <Text key="m" dimColor wrap="truncate-end">
978                      {[p.agent, p.model ? modelLabel(p.model) : '', p.effort, p.after.length ? `${s().after} ${p.after.join(', ')}` : ''].filter(Boolean).join(' · ') || ' '}
979                    </Text>
980                  </Box>
981                </Box>
982              ) : (
983                <Text key={`plan-${p.n}`} dimColor wrap="truncate-end">
984                  ◷ {p.n}. {p.title}
985                  {p.after.length ? ` · ${s().after} ${p.after.join(', ')}` : ''}
986                </Text>
987              ),
988            )}
989          </Box>
990        )}
991      </Box>
992    )
993  })
994
995  // ---------------------------------------------------------------------------
996  // The job bar above the prompt
997
998  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
999    if (e.props.hasSurvey) return next(e)
1000    const flow = await read($, flowAtom)
1001    const all = await read($, runsAtom)
1002    const panel = await read($, panelAtom)
1003    const limits = await read($, limitsAtom)
1004    const runs = visible(flow, all)
1005    const running = runs.filter(r => r.status === 'running').length
1006    const turn = await read($, turnAtom)
1007    const shownTurn = turn && turn.startedAt > panel.hiddenAt ? turn : null
1008    // A finished job gives way to the next prompt.
1009    const isFlowOver = !!flow?.finished && !!shownTurn && shownTurn.startedAt > flow.updatedAt
1010    const shownFlow = flow && flow.updatedAt > panel.hiddenAt && !isFlowOver ? flow : null
1011
1012    const ui = $.ui.resolve(e)
1013    const { Box, Text, Button } = ui
1014    // Plan limits sit at the right edge, beside the crew count: a colored ring
1015    // per window on surfaces that draw pictures, a colored percent in the terminal.
1016    const pairs = limitPairs(limits.windows)
1017    const limitRings = (u: typeof ui) =>
1018      'Svg' in u
1019        ? pairs.map(([k, pct]) => (
1020            <Box key={`lim-${k}`} flexDirection="row" alignItems="center" gap={1}>
1021              <u.Svg source={ringSvg(pct)} alt={`${k} ${pct}% used`} width={RING} height={RING} />
1022              <Text dimColor>{`${k} ${pct}%`}</Text>
1023            </Box>
1024          ))
1025        : limitText()
1026    const termColor = (pct: number) => (pct >= 90 ? 'red' : pct >= 70 ? 'yellow' : 'blue')
1027    const limitText = () =>
1028      pairs.map(([k, pct]) => (
1029        <Text key={`lim-${k}`} dimColor={pct < 70} color={termColor(pct)}>{`◔ ${k} ${pct}%`}</Text>
1030      ))
1031    const dismissBar = (
1032      <Button key="hide" plain role="dismiss" label="✕" onPress={() => update($, panelAtom, p => ({ ...p, hiddenAt: Date.now() }))} />
1033    )
1034
1035    // No job and no subagent: the bar follows the prompt itself.
1036    if (!shownFlow && running === 0) {
1037      if (!shownTurn) return next(e)
1038      const now = Math.max(await read($, nowAtom), shownTurn.startedAt)
1039      const prompt = shownTurn.prompt || s().thisPrompt
1040      const word = turnWord(shownTurn)
1041      const stats = turnStats(shownTurn, now)
1042      const panelButton = <Button key="crew" plain label={runs.length ? `×${runs.length}` : s().appName} onPress={() => void togglePane($)} />
1043
1044      if (e.surface !== 'terminal' && 'Svg' in ui) {
1045        const { Svg } = ui
1046        const color = shownTurn.status === 'failed' ? BAD : shownTurn.status === 'done' ? OK : ACCENT
1047        const cols = e.props.bodyColumns || 100
1048        const reserved = Math.min(28, prompt.length) + word.length + stats.length + pairs.length * 10 + 22
1049        const barW = Math.max(60, Math.min(600, (cols - reserved) * 8))
1050        return (
1051          <Box flexDirection="row" alignItems="center" gap={1}>
1052            <Text key="title" bold wrap="truncate-end">
1053              <Text color={color}>{statusGlyph(shownTurn.status)}</Text> {clip(prompt, 28)}
1054            </Text>
1055            <Svg
1056              key="segs"
1057              source={segmentsSvg(barW, turnSegments(shownTurn), color, shownTurn.status === 'running')}
1058              alt={`${word}, ${stats}`}
1059              width={barW}
1060              height={SEG_H}
1061            />
1062            <Text key="label" bold color={color}>
1063              {word}
1064            </Text>
1065            <Text key="stats" dimColor wrap="truncate-end">
1066              {stats}
1067            </Text>
1068            <Box key="spacer" flexGrow={1} />
1069            {limitRings(ui)}
1070            {panelButton}
1071            {dismissBar}
1072          </Box>
1073        )
1074      }
1075
1076      const cols = e.props.bodyColumns || 80
1077      const promptW = Math.max(8, Math.min(28, Math.floor(cols / 4)))
1078      const width = Math.max(6, Math.min(16, cols - promptW - stats.length - 24))
1079      const color = shownTurn.status === 'failed' ? 'red' : shownTurn.status === 'done' ? 'green' : 'magenta'
1080      return (
1081        <Box flexDirection="row" gap={1}>
1082          <Text color={color}>{statusGlyph(shownTurn.status)}</Text>
1083          <Text bold wrap="truncate-end">
1084            {clip(prompt, promptW)}
1085          </Text>
1086          <Text color={color}>{pulseBar(shownTurn, now, width)}</Text>
1087          <Text bold>{word}</Text>
1088          <Text dimColor wrap="truncate-end">
1089            {stats}
1090          </Text>
1091          <Box flexGrow={1} />
1092          {limitText()}
1093          {panelButton}
1094          {dismissBar}
1095        </Box>
1096      )
1097    }
1098    const crew = runs.length + pending(shownFlow, runs).length
1099    const title = shownFlow?.title ?? s().appName
1100    const shownDone = shownFlow ? doneCount(shownFlow, runs) : 0
1101    const label = shownFlow ? flowLabel(shownFlow, running, shownDone) : `${running} ${s().busy}`
1102    const ratio = shownFlow ? flowRatio(shownFlow, shownDone) : 0
1103    const crewButton = <Button key="crew" plain label={`×${crew}`} onPress={() => void togglePane($)} />
1104
1105    if (e.surface !== 'terminal' && 'Svg' in ui) {
1106      const { Svg } = ui
1107      const color = shownFlow?.finished ? OK : ACCENT
1108      const cols = e.props.bodyColumns || 100
1109      const reserved = Math.min(28, title.length) + label.length + pairs.length * 10 + 22
1110      const barW = Math.max(60, Math.min(900, (cols - reserved) * 8))
1111      return (
1112        <Box flexDirection="row" alignItems="center" gap={1}>
1113          <Text key="title" bold wrap="truncate-end">
1114            <Text color={color}>●</Text> {clip(title, 28)}
1115          </Text>
1116          <Svg
1117            key="segs"
1118            source={segmentsSvg(barW, shownFlow ? segments(shownFlow, runs) : [], color, running > 0)}
1119            alt={`${label}, ${Math.round(ratio * 100)}%`}
1120            width={barW}
1121            height={SEG_H}
1122          />
1123          <Text key="label" bold color={color}>
1124            {label}
1125          </Text>
1126          <Text key="pct" dimColor>{`${Math.round(ratio * 100)}%`}</Text>
1127          <Box key="spacer" flexGrow={1} />
1128          {limitRings(ui)}
1129          {crewButton}
1130          {shownFlow ? dismissBar : null}
1131        </Box>
1132      )
1133    }
1134
1135    const cols = e.props.bodyColumns || 80
1136    const titleW = Math.max(8, Math.min(28, Math.floor(cols / 4)))
1137    const width = Math.max(6, Math.min(30, cols - titleW - 40))
1138    return (
1139      <Box flexDirection="row" gap={1}>
1140        <Text color={shownFlow?.finished ? 'green' : 'magenta'}>⛵</Text>
1141        <Text bold wrap="truncate-end">
1142          {clip(title, titleW)}
1143        </Text>
1144        <Text color={shownFlow?.finished ? 'green' : 'magenta'}>{textBar(ratio, width)}</Text>
1145        <Text bold>{label}</Text>
1146        <Text dimColor>{`${Math.round(ratio * 100)}%`}</Text>
1147        <Box flexGrow={1} />
1148        {limitText()}
1149        {crewButton}
1150        {shownFlow ? dismissBar : null}
1151      </Box>
1152    )
1153  })
1154
1155}
1156
src/flow.ts 122 lines
1import { normalize } from './format.ts'
2import { PHASES } from './types.ts'
3import type { AgentRun, Flow, FlowView, Phase, PlannedTask, PlannedView, ProgressInput } from './types.ts'
4
5const DEFAULT_TITLE = 'Crew job'
6const MAX_COUNT = 100
7
8const isPhase = (p: unknown): p is Phase => typeof p === 'string' && (PHASES as readonly string[]).includes(p)
9
10const toCount = (n: unknown): number | undefined =>
11  typeof n === 'number' && Number.isFinite(n) ? Math.min(MAX_COUNT, Math.max(0, Math.round(n))) : undefined
12
13/** Drops untitled tasks and nonsense dependency numbers. */
14export function cleanTasks(tasks: ProgressInput['tasks']): PlannedTask[] | undefined {
15  if (!Array.isArray(tasks)) return undefined
16  // `after` numbers refer to the caller's 1-based positions; remap them past any dropped untitled tasks.
17  const newIndex = new Map<number, number>()
18  const kept = tasks.filter((t, i) => {
19    const ok = typeof t?.title === 'string' && t.title.trim() !== ''
20    if (ok) newIndex.set(i + 1, newIndex.size + 1)
21    return ok
22  })
23  return kept.map((t, i) => {
24    const out: PlannedTask = {
25      title: (t.title ?? '').trim(),
26      after: [...new Set((t.after ?? []).filter(n => Number.isInteger(n) && newIndex.has(n) && newIndex.get(n) !== i + 1).map(n => newIndex.get(n)!))].sort((a, b) => a - b),
27    }
28    if (t.agent?.trim()) out.agent = t.agent.trim()
29    if (t.model?.trim()) out.model = t.model.trim()
30    if (t.effort?.trim()) out.effort = t.effort.trim().toLowerCase()
31    return out
32  })
33}
34
35/**
36 * True when a progress call opens a new job instead of updating the current one:
37 * nothing is running yet, the last job closed, or the title changed.
38 */
39export function startsNewFlow(prev: Flow | null, input: ProgressInput): boolean {
40  if (!prev) return true
41  if (prev.finished) return input.finished !== true
42  const title = input.title?.trim()
43  return title !== undefined && title !== '' && title !== prev.title
44}
45
46/** Applies one `progress` call. Omitted fields keep their previous values. */
47export function applyProgress(prev: Flow | null, input: ProgressInput, at: number): Flow {
48  const fresh = startsNewFlow(prev, input)
49  const base: Flow =
50    fresh || !prev
51      ? { title: DEFAULT_TITLE, total: 0, done: 0, phase: 'plan', finished: false, tasks: [], startedAt: at, updatedAt: at }
52      : prev
53  const tasks = cleanTasks(input.tasks) ?? base.tasks
54  const total = toCount(input.total) ?? (input.tasks ? tasks.length : base.total)
55  const doneRaw = toCount(input.done) ?? base.done
56  const done = input.finished ? Math.max(doneRaw, total) : total ? Math.min(total, doneRaw) : doneRaw
57  const phase: Phase = input.finished ? 'close' : isPhase(input.phase) ? input.phase : base.phase
58  return {
59    title: input.title?.trim() || base.title,
60    total,
61    done,
62    phase,
63    finished: input.finished === true,
64    tasks,
65    startedAt: base.startedAt,
66    updatedAt: at,
67  }
68}
69
70/** Runs that belong on screen: a new job hides runs that finished before it began. */
71export function visibleRuns(flow: Flow | null, runs: AgentRun[]): AgentRun[] {
72  if (!flow) return runs
73  return runs.filter(r => r.status === 'running' || (r.endedAt ?? r.lastActivityAt) >= flow.startedAt)
74}
75
76/** Planned tasks no run has picked up yet, matched by title. */
77export function pendingTasks(flow: Flow | null, runs: AgentRun[]): PlannedView[] {
78  if (!flow || flow.finished) return []
79  const started = new Set(runs.map(r => normalize(r.description)))
80  return flow.tasks.map((t, i) => ({ ...t, n: i + 1 })).filter(t => !started.has(normalize(t.title)))
81}
82
83type RunLike = Pick<AgentRun, 'description' | 'status'> & { endedAt?: number }
84
85/**
86 * Tasks finished so far: the larger of the orchestrator's reported `done` and what the runs show,
87 * so the bar moves as each subagent ends without waiting for a `progress` call.
88 * A planned task counts once it has runs and none is still going; without a plan, every run that ended in this job counts.
89 */
90export function doneCount(flow: Flow, runs: RunLike[]): number {
91  const seen = flow.tasks.length
92    ? flow.tasks.filter(t => {
93        const mine = runs.filter(r => normalize(r.description) === normalize(t.title))
94        return mine.some(r => r.status === 'done') && !mine.some(r => r.status === 'running')
95      }).length
96    : runs.filter(r => r.status === 'done' && (r.endedAt === undefined || r.endedAt >= flow.startedAt)).length
97  const done = Math.max(flow.done, seen)
98  return flow.total ? Math.min(flow.total, done) : done
99}
100
101export function viewFlow(source: Flow | null, runs: AgentRun[]): FlowView | null {
102  if (!source) return null
103  const flow = { ...source, done: doneCount(source, runs) }
104  const running = runs.filter(r => r.status === 'running').length
105  const ratio = flow.finished ? 1 : flow.total ? flow.done / flow.total : 0
106  const shownPhase: Phase = flow.phase === 'plan' && running > 0 ? 'delegate' : flow.phase
107
108  // One segment per planned task: accepted ones first, then those in flight.
109  const segments: FlowView['segments'] = []
110  const total = flow.finished ? Math.max(flow.total, 1) : flow.total
111  const byTitle = new Map(runs.map(r => [normalize(r.description), r]))
112  const inFlight = flow.tasks.length
113    ? flow.tasks.filter(t => byTitle.get(normalize(t.title))?.status === 'running').length
114    : running
115  for (let i = 0; i < total; i++) {
116    if (flow.finished || i < flow.done) segments.push('done')
117    else if (i < flow.done + inFlight) segments.push('running')
118    else segments.push('todo')
119  }
120  return { ...flow, ratio, running, shownPhase, segments }
121}
122
src/format.ts 45 lines
1export const fmtTokens = (n: number): string =>
2  n >= 999_500 ? `${(n / 1e6).toFixed(1)}M` : n >= 1e3 ? `${Math.round(n / 1e3)}k` : `${Math.max(0, Math.round(n))}`
3
4export const fmtCost = (usd: number): string =>
5  usd >= 100 ? `$${Math.round(usd)}` : usd >= 10 ? `$${usd.toFixed(1)}` : `$${usd.toFixed(2)}`
6
7/** `m:ss`, or `h:mm:ss` past an hour. */
8export function fmtTime(ms: number): string {
9  const s = Math.max(0, Math.round(ms / 1000))
10  const h = Math.floor(s / 3600)
11  const m = Math.floor((s % 3600) / 60)
12  const ss = String(s % 60).padStart(2, '0')
13  return h ? `${h}:${String(m).padStart(2, '0')}:${ss}` : `${m}:${ss}`
14}
15
16/** A coarse countdown: `3d 4h`, `1h 20m`, `12m`. */
17export function fmtDuration(ms: number): string {
18  const m = Math.max(0, Math.ceil(ms / 60_000))
19  const d = Math.floor(m / 1440)
20  const h = Math.floor((m % 1440) / 60)
21  if (d) return `${d}d ${h}h`
22  if (h) return `${h}h ${m % 60}m`
23  return `${m}m`
24}
25
26/** Lowercase, punctuation-free form used to match task titles against run descriptions. */
27export const normalize = (s: string): string =>
28  s
29    .toLowerCase()
30    .replace(/[^\p{L}\p{N}]+/gu, ' ')
31    .trim()
32
33export const clip = (s: string, max: number): string => {
34  if (s.length <= max) return s
35  const chars = Array.from(s)
36  return chars.length > max ? chars.slice(0, Math.max(1, max - 1)).join('') + '…' : s
37}
38
39/** A text bar such as `▰▰▰▱▱`. */
40export const textBar = (ratio: number, width: number, on = '▰', off = '▱'): string => {
41  const w = Math.max(0, Math.floor(Number.isFinite(width) ? width : 0))
42  const filled = Math.round(Math.max(0, Math.min(1, Number.isFinite(ratio) ? ratio : 0)) * w)
43  return on.repeat(filled) + off.repeat(Math.max(0, w - filled))
44}
45
src/i18n.ts 124 lines
1/** Languages the panel speaks. */
2export type Lang = 'en' | 'ru'
3import type { Phase } from './types.ts'
4
5export const STRINGS = {
6  en: {
7    appName: 'Crew',
8    cost: 'Cost',
9    tokens: 'Tokens',
10    time: 'Time',
11    collapse: 'Collapse',
12    expand: 'Expand',
13    running: 'Running',
14    finished: 'Finished',
15    planned: 'Planned',
16    empty: 'No subagents yet. Give Claude a job big enough to split across a few helpers.',
17    waiting: 'Waiting for a Claude Code session…',
18    round: 'round',
19    error: 'error',
20    killed: 'stopped',
21    stalled: 'stalled',
22    after: 'after',
23    background: 'background',
24    tokensWord: 'tokens',
25    agents: 'agents',
26    agentsCount: (n: number) => `${n} ${n === 1 ? 'agent' : 'agents'}`,
27    live: 'live',
28    reconnecting: 'reconnecting…',
29    dismiss: 'Hide bar',
30    theme: 'Theme',
31    estimate: 'Costs are estimates from token counts and list prices, not your bill.',
32    phase: { plan: 'Plan', design: 'Design', delegate: 'Tasks', review: 'Review', close: 'Done' } satisfies Record<Phase, string>,
33    busy: 'running',
34    limits: 'Plan limits',
35    fiveHour: '5-hour session',
36    weekly: 'Weekly',
37    resetsIn: 'resets in',
38    startsNext: 'resets with your next message',
39    updated: 'updated',
40    justNow: 'just now',
41    ago: 'ago',
42    requests: 'requests',
43    lastHours: 'last 5 hours',
44    lastDays: 'last 7 days',
45    noPlan: 'no plan data',
46    working: 'Working',
47    answered: 'Done',
48    stopped: 'Stopped',
49    steps: 'steps',
50    tools: 'tools',
51    lastPrompt: 'Last prompt',
52    thisPrompt: 'This prompt',
53    openWeb: 'Open in browser',
54    stopWeb: 'Stop browser view',
55    webStarting: 'Starting browser view…',
56    webAt: 'Browser view',
57    limitsHint:
58      'Plan percentages come from Claude Code\'s status line (Claude.ai plans only). Run `luff-crew-monitor setup --statusline` to record them. Token and cost totals are counted from your local transcripts.',
59  },
60  ru: {
61    appName: 'Команда',
62    cost: 'Стоимость',
63    tokens: 'Токены',
64    time: 'Время',
65    collapse: 'Свернуть',
66    expand: 'Развернуть',
67    running: 'Работают',
68    finished: 'Завершены',
69    planned: 'Запланированы',
70    empty: 'Субагентов пока нет. Дайте Claude задачу, которую стоит разделить между помощниками.',
71    waiting: 'Ждём сессию Claude Code…',
72    round: 'раунд',
73    error: 'ошибка',
74    killed: 'остановлен',
75    stalled: 'завис',
76    after: 'после',
77    background: 'в фоне',
78    tokensWord: 'токенов',
79    agents: 'агентов',
80    agentsCount: (n: number) => {
81      const m10 = n % 10
82      const m100 = n % 100
83      const word = m10 === 1 && m100 !== 11 ? 'агент' : m10 >= 2 && m10 <= 4 && (m100 < 12 || m100 > 14) ? 'агента' : 'агентов'
84      return `${n} ${word}`
85    },
86    live: 'онлайн',
87    reconnecting: 'переподключение…',
88    dismiss: 'Скрыть полосу',
89    theme: 'Тема',
90    estimate: 'Стоимость оценена по токенам и прайс-листу, это не счёт.',
91    phase: { plan: 'План', design: 'Дизайн', delegate: 'Задачи', review: 'Ревью', close: 'Готово' } satisfies Record<Phase, string>,
92    busy: 'в работе',
93    limits: 'Лимиты плана',
94    fiveHour: 'Сессия 5 часов',
95    weekly: 'Неделя',
96    resetsIn: 'сброс через',
97    startsNext: 'сброшен, начнётся со следующего сообщения',
98    updated: 'обновлено',
99    justNow: 'только что',
100    ago: 'назад',
101    requests: 'запросов',
102    lastHours: 'за 5 часов',
103    lastDays: 'за 7 дней',
104    noPlan: 'нет данных плана',
105    working: 'Работает',
106    answered: 'Готово',
107    stopped: 'Остановлено',
108    steps: 'шагов',
109    tools: 'инструментов',
110    lastPrompt: 'Последний запрос',
111    thisPrompt: 'Текущий запрос',
112    openWeb: 'Открыть в браузере',
113    stopWeb: 'Закрыть браузерный вид',
114    webStarting: 'Запускаем браузерный вид…',
115    webAt: 'Браузерный вид',
116    limitsHint:
117      'Проценты плана приходят из статус-строки Claude Code (только планы Claude.ai). Запустите `luff-crew-monitor setup --statusline`, чтобы их записывать. Токены и стоимость считаются по локальным транскриптам.',
118  },
119} as const
120
121export type Strings = (typeof STRINGS)[Lang]
122
123export const stringsFor = (lang: Lang): Strings => STRINGS[lang] ?? STRINGS.en
124
src/pricing.ts 128 lines
1/**
2 * Cost estimation. Transcripts record tokens, not money, so every dollar figure
3 * this tool shows is an estimate from the public list prices below.
4 * Source: https://docs.claude.com/en/docs/about-claude/pricing (USD per million tokens).
5 */
6
7export interface Usage {
8  input_tokens?: number
9  output_tokens?: number
10  cache_read_input_tokens?: number
11  cache_creation_input_tokens?: number
12  cache_creation?: {
13    ephemeral_5m_input_tokens?: number
14    ephemeral_1h_input_tokens?: number
15  }
16}
17
18/** [input, 5m cache write, 1h cache write, cache read, output] in USD per MTok. */
19export type PriceRow = readonly [number, number, number, number, number]
20
21interface PriceRule {
22  match: RegExp
23  price: PriceRow
24  /** Price used when the request's prompt exceeds `threshold` tokens. */
25  long?: { threshold: number; price: PriceRow }
26}
27
28// Most specific first: the first match wins.
29const RULES: PriceRule[] = [
30  { match: /(fable|mythos)-5-1/, price: [10, 12.5, 20, 0.25, 50] },
31  { match: /fable|mythos/, price: [10, 12.5, 20, 1, 50] },
32  { match: /opus-5-5/, price: [4, 5, 8, 0.2, 20] },
33  { match: /claude-3-opus|3-opus/, price: [15, 18.75, 30, 1.5, 75] },
34  { match: /opus-4-1|opus-4(?!-\d)|opus-4-2025/, price: [15, 18.75, 30, 1.5, 75] },
35  { match: /opus/, price: [5, 6.25, 10, 0.5, 25] },
36  { match: /sonnet-5-5/, price: [2, 2.5, 4, 0.1, 10] },
37  { match: /sonnet-5/, price: [2, 2.5, 4, 0.2, 10] },
38  { match: /sonnet/, price: [3, 3.75, 6, 0.3, 15] },
39  {
40    match: /haiku-5-5/,
41    price: [0.1, 0.125, 0.2, 0.01, 0.5],
42    long: { threshold: 100_000, price: [0.5, 0.625, 1, 0.05, 2.5] },
43  },
44  { match: /claude-3-haiku|3-haiku/, price: [0.25, 0.3, 0.5, 0.03, 1.25] },
45  { match: /haiku-3-5|3-5-haiku/, price: [0.8, 1, 1.6, 0.08, 4] },
46  { match: /haiku/, price: [1, 1.25, 2, 0.1, 5] },
47]
48
49/** Used for unknown model ids: mid-range, so an estimate is never wildly off. */
50export const FALLBACK_PRICE: PriceRow = [3, 3.75, 6, 0.3, 15]
51
52let overrides: Array<{ match: RegExp; price: PriceRow }> = []
53
54/** Lets `~/.luff-crew/config.json` add or replace prices, keyed by a substring of the model id. */
55export function setPriceOverrides(table: Record<string, number[]> | undefined): void {
56  overrides = Object.entries(table ?? {})
57    .filter(([key, row]) => key.trim() !== '' && Array.isArray(row) && row.length === 5 && row.every(n => typeof n === 'number' && Number.isFinite(n) && n >= 0))
58    .map(([key, row]) => ({ match: new RegExp(escapeRegExp(key.toLowerCase())), price: row as unknown as PriceRow }))
59}
60
61const escapeRegExp = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
62
63const promptTokens = (u: Usage): number =>
64  (u.input_tokens ?? 0) + (u.cache_read_input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0)
65
66export function priceOf(model: string, usage?: Usage): PriceRow {
67  const id = model.toLowerCase()
68  const custom = overrides.find(o => o.match.test(id))
69  if (custom) return custom.price
70  const rule = RULES.find(r => r.match.test(id))
71  if (!rule) return FALLBACK_PRICE
72  if (rule.long && usage && promptTokens(usage) > rule.long.threshold) return rule.long.price
73  return rule.price
74}
75
76/** Estimated USD for one model request. */
77export function costOf(model: string, u: Usage): number {
78  const [input, write5m, write1h, read, output] = priceOf(model, u)
79  const written = u.cache_creation_input_tokens ?? 0
80  // The split by TTL is recorded on newer transcripts; older ones bill all writes at the 5m rate.
81  const w1h = Math.min(written, u.cache_creation?.ephemeral_1h_input_tokens ?? 0)
82  const w5m = written - w1h
83  return (
84    ((u.input_tokens ?? 0) * input +
85      w5m * write5m +
86      w1h * write1h +
87      (u.cache_read_input_tokens ?? 0) * read +
88      (u.output_tokens ?? 0) * output) /
89    1e6
90  )
91}
92
93/** Every token a request was billed for. */
94export const tokensOf = (u: Usage): number => promptTokens(u) + (u.output_tokens ?? 0)
95
96let windowOverrides: Record<string, number> = {}
97
98export function setContextWindowOverrides(table: Record<string, number> | undefined): void {
99  windowOverrides = Object.fromEntries(
100    Object.entries(table ?? {}).filter(([k, n]) => k.trim() !== '' && typeof n === 'number' && Number.isFinite(n) && n > 0).map(([k, n]) => [k.toLowerCase(), n]),
101  )
102}
103
104/** Context window size used for the `ctx %` figure. */
105export function contextWindowOf(model: string): number {
106  const id = model.toLowerCase()
107  for (const [key, size] of Object.entries(windowOverrides)) if (id.includes(key)) return size
108  if (/\[1m\]/.test(id)) return 1_000_000
109  if (/haiku|claude-3/.test(id)) return 200_000
110  // Generation 5 and later ship with a 1M window; earlier ones default to 200k.
111  const gen = /(?:opus|sonnet|fable|mythos)-(\d+)/.exec(id)
112  if (gen && Number(gen[1]) < 5) return 200_000
113  return 1_000_000
114}
115
116/** `claude-opus-5-5` → `Opus 5.5`, `claude-sonnet-5` → `Sonnet 5`. */
117export function modelLabel(id: string): string {
118  if (!id) return '—'
119  const m = /(fable|mythos|opus|sonnet|haiku)-(\d+)(?:-(\d{1,2})(?!\d))?/i.exec(id)
120  if (!m) {
121    const bare = id.replace(/^claude-/, '').replace(/\[.*\]$/, '')
122    if (/^(fable|mythos|opus|sonnet|haiku)$/i.test(bare)) return bare.charAt(0).toUpperCase() + bare.slice(1).toLowerCase()
123    return bare || '—'
124  }
125  const [, family = '', major = '', minor] = m
126  return `${family.charAt(0).toUpperCase()}${family.slice(1).toLowerCase()} ${major}${minor ? '.' + minor : ''}`
127}
128
src/types.ts 158 lines
1/** Phases an orchestrator moves through while it runs a multi-agent job. */
2export const PHASES = ['plan', 'design', 'delegate', 'review', 'close'] as const
3export type Phase = (typeof PHASES)[number]
4
5export const EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max'] as const
6export type Effort = (typeof EFFORTS)[number]
7
8/** One worker task the orchestrator plans to hand to a subagent. */
9export interface PlannedTask {
10  /** Must equal the Agent tool `description` so runs can be matched to tasks. */
11  title: string
12  /** Subagent type it will run as, e.g. `Explore` or `general-purpose`. */
13  agent?: string
14  /** Model family or id it is expected to run on, e.g. `opus` or `claude-sonnet-5`. */
15  model?: string
16  effort?: string
17  /** 1-based numbers of the tasks this one waits for. */
18  after: number[]
19}
20
21/** What the `progress` tool accepts. Every field is optional: omitted fields keep their value. */
22export interface ProgressInput {
23  title?: string
24  total?: number
25  done?: number
26  phase?: Phase
27  finished?: boolean
28  tasks?: Array<{ title?: string; agent?: string; model?: string; effort?: string; after?: number[] }>
29}
30
31/** The orchestrator's job as reported through `progress`. */
32export interface Flow {
33  title: string
34  total: number
35  done: number
36  phase: Phase
37  finished: boolean
38  tasks: PlannedTask[]
39  /** Epoch ms of the call that started this flow. */
40  startedAt: number
41  /** Epoch ms of the latest progress call. */
42  updatedAt: number
43}
44
45export type RunStatus = 'running' | 'done' | 'failed'
46
47/** Self-reported progress from a worker through the `step` tool. */
48export interface StepReport {
49  done: number
50  total: number
51  note?: string
52}
53
54/** One subagent run, rebuilt from its transcript. */
55export interface AgentRun {
56  /** Claude Code's agent id (the `agent-<id>.jsonl` file name). */
57  id: string
58  /** The parent's Agent tool_use id, when known. */
59  toolUseId?: string
60  /** Subagent type: `general-purpose`, `Explore`, a custom agent name, ... */
61  type: string
62  description: string
63  model: string
64  effort?: string
65  status: RunStatus
66  /** Why a run is marked failed: `error`, `killed`, `stalled`. */
67  failure?: string
68  background: boolean
69  startedAt: number
70  endedAt?: number
71  lastActivityAt: number
72  /** Tokens in the latest request: what the context window holds right now. */
73  contextTokens: number
74  contextMax: number
75  /** All tokens billed across the run's requests. */
76  tokens: number
77  costUsd: number
78  /** Model requests made so far. */
79  requests: number
80  /** 1 for the first run of a description, 2 for a retry, ... */
81  round: number
82  step?: StepReport
83  /** Nesting level: 1 for a subagent of the main thread, 2 for its own subagents. */
84  depth: number
85  /** The run's crew mascot as an SVG group on a 26×22 grid; set for the browser view. */
86  mascot?: string
87}
88
89export interface Totals {
90  costUsd: number
91  tokens: number
92  /** Wall-clock span from the first run's start to the last run's end (or now). */
93  timeMs: number
94  running: number
95  done: number
96  failed: number
97}
98
99export interface PlannedView extends PlannedTask {
100  /** 1-based position in the plan. */
101  n: number
102  /** The task's crew mascot as an SVG group on a 26×22 grid; set for the browser view. */
103  mascot?: string
104}
105
106export interface FlowView extends Flow {
107  /** Accepted share of the plan, 0..1. */
108  ratio: number
109  /** Workers running right now. */
110  running: number
111  /** Phase shown to the user: `plan` turns into `delegate` once workers start. */
112  shownPhase: Phase
113  /** Per-task state, for the segmented bar. */
114  segments: Array<'done' | 'running' | 'todo'>
115}
116
117export interface SessionInfo {
118  id: string
119  projectDir: string
120  cwd?: string
121  transcript: string
122}
123
124/** One plan usage window (5-hour session or weekly) on the limits panel. */
125export interface LimitWindowView {
126  /** Share of the plan limit used, 0..100, as Claude Code reports it; null when it has not. */
127  usedPct: number | null
128  /** Epoch ms when the window resets; null when unknown. */
129  resetsAt: number | null
130  /** Epoch ms the local totals below are counted from. */
131  since: number
132  /** Tokens, estimated cost and model requests in local transcripts since `since`. */
133  tokens: number
134  costUsd: number
135  requests: number
136}
137
138export interface LimitsView {
139  fiveHour: LimitWindowView
140  sevenDay: LimitWindowView
141  /** Epoch ms Claude Code last reported plan limits through the status line; null when never. */
142  reportedAt: number | null
143}
144
145/** Everything a view (dashboard, statusline, tool reply) needs, at one instant. */
146export interface Snapshot {
147  version: string
148  now: number
149  lang: 'en' | 'ru'
150  session: SessionInfo | null
151  flow: FlowView | null
152  agents: AgentRun[]
153  planned: PlannedView[]
154  totals: Totals
155  /** Plan usage limits; only views that poll local usage fill it in. */
156  limits?: LimitsView
157}
158
hooks/draw.ts 370 lines
1// Pure drawing for the Luff Crew mod: SVG sources for the surfaces that draw
2// pictures (desktop, VS Code, mobile) and the bits of text the terminal uses.
3// No engine calls here, so everything is testable as plain functions.
4
5import { BROWN, GOLD, INK, LENS, lookOf, mascot, shade, WHITE, WOOD } from '../src/crew.ts'
6import type { Look } from '../src/crew.ts'
7import { clip, fmtCost, fmtTime, fmtTokens } from '../src/format.ts'
8import { modelLabel } from '../src/pricing.ts'
9import type { CrewLimitWindow, CrewRun } from '../types'
10
11export const ACCENT = '#5b6cf0'
12export const OK = '#2f9e66'
13export const BAD = '#d0453f'
14export const WARN = '#c98a12'
15
16// ---------------------------------------------------------------------------
17// Colors and the mascots: a round crew member per agent, each with its own
18// look, holding gear for its effort.
19
20const PALETTE = ['#E07A5F', '#3D9DD9', '#2BB3A0', '#9B7BE0', '#E0A83D', '#D96BA0', '#5FAF4F']
21const KNOWN: Record<string, number> = { 'general-purpose': 0, Explore: 2, Plan: 3 }
22
23export function typeColor(type: string): string {
24  const bare = type.replace(/^[^:]*:/, '')
25  const known = KNOWN[bare]
26  if (known !== undefined) return PALETTE[known] ?? ACCENT
27  let h = 0
28  for (const ch of bare) h = (h * 31 + ch.charCodeAt(0)) >>> 0
29  return PALETTE[h % PALETTE.length] ?? ACCENT
30}
31
32// The crew's looks live in src/crew.ts, shared with the browser view.
33export { crewSlots, EXTRA_STYLES, EYE_STYLES, HAT_STYLES, hashOf, lookOf, mascot, MOUTH_STYLES, shade } from '../src/crew.ts'
34export type { Look } from '../src/crew.ts'
35
36// Graphics only: the engine gives a render hook no theme, so every word is an
37// engine Text element (themed by the app) and these SVGs use colors that read
38// on light and dark alike: a translucent grey track, saturated fills.
39const TRACK = 'fill="#8a8a8a" fill-opacity=".22"'
40
41const STYLE = `<style>
42.m g{transform-box:fill-box}
43.m.run .la{animation:hop .5s steps(1) infinite}.m.run .lb{animation:hop .5s steps(1) infinite -.25s}
44.m.run .bd{animation:bob .5s steps(1) infinite -.125s}
45.m.e-low.run .la,.m.e-low.run .lb{animation-duration:.25s}
46.m.e-low.run .prop{transform-origin:50% 0;animation:swish .5s ease-in-out infinite}
47.m.e-medium.run .prop{transform-origin:50% 30%;animation:row 1s ease-in-out infinite}
48.m.e-high.run .prop{animation:scan 1s steps(1) infinite}
49.m.e-xhigh.run .flame{animation:flicker .25s steps(1) infinite}
50.m.e-max.run .prop{transform-origin:center;animation:spin 1s linear infinite}
51.stripe{animation:march 1s linear infinite}
52@keyframes hop{50%{transform:translateY(-1px)}}@keyframes bob{50%{transform:translateY(1px)}}
53@keyframes swish{50%{transform:rotate(14deg)}}@keyframes row{50%{transform:rotate(-22deg)}}
54@keyframes scan{33%{transform:translate(1px,-1px)}66%{transform:translate(0,-2px)}}
55@keyframes flicker{50%{opacity:.35}}@keyframes spin{to{transform:rotate(360deg)}}
56@keyframes march{to{transform:translateX(8px)}}
57@media (prefers-reduced-motion: reduce){.m.run *,.stripe{animation:none!important}}
58</style>`
59
60export const svg = (w: number, h: number, body: string): string =>
61  `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}">${STYLE}${body}</svg>`
62
63// ---------------------------------------------------------------------------
64// Row parts
65
66export const ctxPercent = (r: CrewRun): number => (r.contextMax ? Math.min(100, Math.round((r.contextTokens / r.contextMax) * 100)) : 0)
67export const elapsed = (r: CrewRun, now: number): number => (r.endedAt ?? Math.max(now, r.startedAt)) - r.startedAt
68
69/** The worker's own steps when it reports them; a finished run is full; else null (show context). */
70export function progressOf(r: CrewRun): number | null {
71  if (r.status === 'done') return 1
72  if (r.step?.total) return Math.min(1, r.step.done / r.step.total)
73  return null
74}
75
76export function runMeta(r: CrewRun, words: { round: string; failed: Record<string, string> }): string {
77  const parts = [r.effort ? `${modelLabel(r.model)} · ${r.effort}` : modelLabel(r.model)]
78  if (r.round > 1) parts.push(`${words.round} ${r.round}`)
79  if (r.status === 'failed') parts.push(words.failed[r.failure ?? 'error'] ?? words.failed.error ?? 'error')
80  return parts.join(' · ')
81}
82
83export const runStats = (r: CrewRun, now: number): string =>
84  `ctx ${ctxPercent(r)}% · ${fmtTokens(r.contextTokens)} · ≈${fmtCost(r.costUsd)} · ${fmtTime(elapsed(r, now))}`
85
86export const stepText = (r: CrewRun): string =>
87  r.step?.total ? `${r.step.done}/${r.step.total}${r.step.note ? ' · ' + r.step.note : ''}` : ''
88
89export const statusGlyph = (status: string): string => (status === 'running' ? '●' : status === 'done' ? '✓' : status === 'failed' ? '✗' : '◷')
90export const statusColor = (status: string, color: string): string => (status === 'done' ? OK : status === 'failed' ? BAD : status === 'running' ? color : '#8a8a8a')
91
92// The 26×22 sprite at a whole 2×, so every pixel stays crisp.
93export const MASCOT_W = 52
94export const MASCOT_H = 46
95
96/** One mascot on its own, for a row's left edge. */
97export const mascotSvg = (slot: number, effort: string | undefined, opts: { running?: boolean; dim?: boolean } = {}): string =>
98  svg(MASCOT_W, MASCOT_H, mascot(0, 2, 2, slot, effort, opts))
99
100export const BAR_H = 6
101
102/** A thin progress bar: `ratio` filled in `color`, or null to draw the track alone. */
103export function barSvg(W: number, ratio: number | null, color: string, h = BAR_H): string {
104  const fillW = ratio === null ? 0 : Math.round(W * Math.max(0, Math.min(1, ratio)))
105  return svg(W, h, `<rect x="0" y="0" width="${W}" height="${h}" rx="${h / 2}" ${TRACK}/>${fillW ? `<rect x="0" y="0" width="${fillW}" height="${h}" rx="${h / 2}" fill="${color}"/>` : ''}`)
106}
107
108/** Fill color of a usage meter: calm, then amber past 70%, red past 90%. */
109export const meterColor = (pct: number): string => (pct >= 90 ? BAD : pct >= 70 ? WARN : ACCENT)
110
111export const STRIP_H = 40
112export const STRIP_STEP = 50
113
114/** A row of small mascots for the compact view. */
115export function stripSvg(W: number, icons: Array<{ slot: number; effort?: string | undefined; running: boolean; dim: boolean }>): string {
116  const step = STRIP_STEP
117  const fit = Math.max(1, Math.floor(W / step))
118  return svg(
119    Math.min(W, Math.max(step, icons.slice(0, fit).length * step)),
120    STRIP_H,
121    icons
122      .slice(0, fit)
123      .map((ic, i) => mascot(i * step, 0, 1.8, ic.slot, ic.effort, { running: ic.running, dim: ic.dim }))
124      .join(''),
125  )
126}
127
128export const SEG_H = 12
129
130/** The job's segmented bar: one segment per planned task, the running ones striped. */
131export function segmentsSvg(W: number, segments: Array<'done' | 'running' | 'todo'>, color: string, isWorking: boolean): string {
132  const segs = segments.length ? segments : [isWorking ? 'running' : 'todo']
133  const gap = segs.length > 1 ? 3 : 0
134  const sw = (W - gap * (segs.length - 1)) / segs.length
135  const body = segs
136    .map((s, i) => {
137      const x = (i * (sw + gap)).toFixed(1)
138      const w = sw.toFixed(1)
139      if (s === 'done') return `<rect x="${x}" y="0" width="${w}" height="${SEG_H}" rx="3" fill="${color}"/>`
140      if (s === 'running') {
141        const stripes = Array.from({ length: Math.ceil(sw / 8) + 2 }, (_, k) => `<path d="M${Number(x) - 8 + k * 8} ${SEG_H}l7-${SEG_H}h3l-7 ${SEG_H}z" fill="${color}"/>`).join('')
142        return `<clipPath id="c${i}"><rect x="${x}" y="0" width="${w}" height="${SEG_H}" rx="3"/></clipPath><g clip-path="url(#c${i})"><rect x="${x}" y="0" width="${w}" height="${SEG_H}" fill="${color}" fill-opacity=".3"/><g class="stripe">${stripes}</g></g>`
143      }
144      return `<rect x="${x}" y="0" width="${w}" height="${SEG_H}" rx="3" ${TRACK}/>`
145    })
146    .join('')
147  return svg(Math.max(1, Math.round(W)), SEG_H, body)
148}
149
150// ---------------------------------------------------------------------------
151// The terminal mascot: the crew member redrawn for text, not shrunk from the
152// SVG one. It stands three lines tall (the height of a row's text) and seven
153// columns wide: six of body, one for what it holds. Each cell is a quadrant
154// block, 2×2 pixels in two colors, so the grid is 14×6 pixels, twice the
155// detail half blocks give. Pixels are drawn so no cell needs a third color:
156// round corners, eyes with a glint, a mouth, feet, a hat with its own shape.
157//
158//   pixel rows: 0 hat · 1 head top · 2-3 eyes · 4 chin and mouth · 5 feet
159//   cell columns: 0 and 5 the round sides · 1 and 4 the eyes · 2-3 the mouth
160//
161// While a member runs (`frame` > 0) it blinks, glances, lifts its feet in
162// turn, its hat's loose parts flutter, and what it holds moves.
163
164export type Cell = { ch: string; fg?: string | undefined; bg?: string | undefined }
165
166export const TERM_MASCOT_W = 7
167export const TERM_MASCOT_H = 3
168
169type Dot = (x: number, y: number, c: string | undefined) => void
170type Span = (x0: number, x1: number, y: number, c: string | undefined) => void
171
172const GREY = '#8A847C'
173const MOP = '#CFCFCB'
174const LIP = '#7A2230'
175const BLUSH = '#FF8FA3'
176
177// Dark hats vanish against a dark terminal: lift them toward white.
178const lift = (hex: string): string => {
179  const [r, g, b] = rgb(hex)
180  if (0.2126 * r + 0.7152 * g + 0.0722 * b > 90) return hex
181  return '#' + [r, g, b].map(v => Math.round(v + (255 - v) * 0.45).toString(16).padStart(2, '0')).join('')
182}
183const rgb = (hex: string): [number, number, number] => [1, 3, 5].map(i => parseInt(hex.slice(i, i + 2), 16)) as [number, number, number]
184
185// Hats sit on pixel rows 0-1. Over the head (cells 1-4) a cell's top pixels
186// share one color with the head below; beside it (cells 0 and 5) anything goes.
187const TERM_HATS: Record<Look['hat'], (p: Dot, s: Span, c: string, d: string, f: number) => void> = {
188  // Tied over the head top, its tail fluttering.
189  bandana: (p, s, c, _d, f) => { s(2, 9, 1, c); p(10, 1, c); p(f % 2 ? 11 : 10, 0, c) },
190  // White cap on a colored band, a ribbon behind.
191  sailor: (p, s, c, _d, f) => { s(2, 9, 0, WHITE); s(2, 9, 1, c); p(10, 1, c); p(f % 2 ? 11 : 10, f % 2 ? 1 : 0, c) },
192  // A wide brim with upturned corners.
193  tricorne: (p, s, c) => { s(0, 11, 0, c); p(0, 1, c); p(11, 1, c); s(4, 7, 0, GOLD) },
194  // A knit cap and a darker rim.
195  beanie: (_p, s, c, d) => { s(2, 9, 0, c); s(2, 9, 1, d) },
196  // A cap on a gold band wider than the head.
197  captain: (_p, s, c) => { s(2, 9, 0, c); s(0, 11, 1, GOLD) },
198  // A band over the top, cups over the round sides.
199  headphones: (p, s, c) => { s(2, 9, 0, GREY); p(1, 1, GREY); p(10, 1, GREY); p(1, 2, c); s(0, 1, 3, c); p(10, 2, c); s(10, 11, 3, c) },
200  // Two stalks at the sides that wiggle.
201  antennae: (p, _s, c, _d, f) => { p(f % 2 ? 0 : 1, 0, c); p(1, 1, c); p(f % 2 ? 11 : 10, 0, c); p(10, 1, c) },
202  // Hair standing up in four spikes.
203  spikes: (p, s, c) => { s(2, 9, 1, c); for (const x of [2, 4, 6, 8]) p(x, 0, c); p(1, 1, c); p(10, 1, c) },
204  // A bow on one side, its knot darker.
205  bow: (p, s, c, d) => { s(6, 7, 0, c); s(8, 9, 0, d); p(10, 0, c); p(10, 1, c); p(11, 0, c) },
206}
207
208// Eyes fill cells 1 and 4: pixels (2-3, 2-3) and (8-9, 2-3).
209type Eye = [string, string, string, string] // top-left, top-right, bottom-left, bottom-right
210const TERM_EYES: Record<Look['eyes'], (L: Look, f: number, side: 0 | 1) => Eye> = {
211  round: () => [WHITE, INK, INK, INK],
212  // Big whites whose pupils glance from side to side.
213  big: (_L, f) => (f % 4 < 2 ? [WHITE, INK, WHITE, INK] : [INK, WHITE, INK, WHITE]),
214  sleepy: L => [L.body, L.body, INK, INK],
215  patch: (_L, _f, side) => (side ? [WHITE, INK, INK, INK] : [INK, INK, INK, INK]),
216  glasses: () => [LENS, LENS, INK, INK],
217  // Brows slanting in.
218  fierce: (L, _f, side) => (side ? [INK, L.body, INK, INK] : [L.body, INK, INK, INK]),
219}
220
221// The mouth fills the top of cells 2-3 (pixels 4-7, row 4).
222const TERM_MOUTHS: Record<Look['mouth'], (p: Dot, s: Span, L: Look, f: number) => void> = {
223  smile: (_p, s, L) => s(4, 7, 4, shade(L.body, 0.5)),
224  flat: (_p, s) => s(4, 7, 4, INK),
225  // Talks while it works.
226  open: (_p, s, L, f) => s(4, 7, 4, f % 2 ? shade(L.body, 0.5) : LIP),
227  // A handlebar: its ends curl up beside the mouth.
228  mustache: (p, s) => { s(4, 7, 4, BROWN); p(4, 3, BROWN); p(7, 3, BROWN) },
229  beard: (_p, s) => s(2, 9, 4, BROWN),
230  grin: (_p, s) => s(4, 7, 4, WHITE),
231}
232
233const TERM_EXTRAS: Record<Look['extra'], (p: Dot, s: Span, L: Look, f: number) => void> = {
234  none: () => {},
235  // Cheeks under the eyes.
236  blush: (_p, s) => { s(2, 3, 4, BLUSH); s(8, 9, 4, BLUSH) },
237  // Round the chin, a tail that flutters.
238  scarf: (p, s, L, f) => { s(1, 10, 4, L.extraColor); p(f % 2 ? 11 : 10, 5, L.extraColor) },
239  belt: () => {},
240}
241
242// What it holds, in cell 6 (pixels 12-13).
243const TERM_GEAR: Record<string, (p: Dot, s: Span, f: number) => void> = {
244  // A mop that swishes.
245  low: (p, s, f) => { for (let y = 0; y <= 3; y++) p(12, y, WOOD); s(12, 13, 4, MOP); p(f % 2 ? 13 : 12, 5, MOP) },
246  // An oar that rows: the blade dips deep, then rises.
247  medium: (p, s, f) => { const blade = f % 2 ? 2 : 4; for (let y = 0; y < blade; y++) p(12, y, WOOD); for (let y = blade; y <= 5; y++) s(12, 13, y, '#8A6038') },
248  // A spyglass whose lens glints.
249  high: (p, s, f) => { s(12, 13, 2, GOLD); p(12, 3, GOLD); p(13, 3, f % 2 ? WHITE : '#9BD3F5') },
250  // A lantern whose flame flickers.
251  xhigh: (p, s, f) => { p(13, 0, GREY); s(12, 13, 1, GREY); p(12, 2, f % 2 ? '#FF8A3D' : '#FFD27A'); p(13, 2, f % 2 ? '#FFD27A' : '#FF8A3D'); p(12, 3, f % 2 ? '#FFD27A' : '#FF8A3D'); p(13, 3, f % 2 ? '#FF8A3D' : '#FFD27A'); s(12, 13, 4, GREY) },
252  // A ship's wheel that turns.
253  max: (p, _s, f) => { for (let y = 0; y <= 5; y++) for (const x of [12, 13]) p(x, y, (x + y + f) % 2 ? GOLD : WOOD) },
254}
255
256// Quadrant blocks by which of a cell's pixels take the foreground:
257// top-left 1, top-right 2, bottom-left 4, bottom-right 8.
258const QUAD = ' ▘▝▀▖▌▞▛▗▚▐▜▄▙▟█'
259
260const dist = (a: string, b: string): number => {
261  const [x, y] = [rgb(a), rgb(b)]
262  return (x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2 + (x[2] - y[2]) ** 2
263}
264
265/** One cell from its four pixels; a third color, if a design ever makes one, goes to the nearer of the two kept. */
266function quadCell(px: Array<string | undefined>): Cell {
267  const counts = new Map<string | undefined, number>()
268  for (const c of px) counts.set(c, (counts.get(c) ?? 0) + 1)
269  let kept = [...counts.keys()]
270  if (kept.length > 2) {
271    kept = kept.sort((a, b) => (counts.get(b) ?? 0) - (counts.get(a) ?? 0)).slice(0, 2)
272    px = px.map(c => (kept.includes(c) ? c : c && kept.filter(Boolean).sort((a, b) => dist(c, a!) - dist(c, b!))[0]))
273  }
274  if (kept.length === 1) return kept[0] ? { ch: '█', fg: kept[0] } : { ch: ' ' }
275  // The foreground is a color, never the terminal's own background.
276  const fg = kept[0] ?? kept[1]
277  const bg = fg === kept[0] ? kept[1] : kept[0]
278  const mask = px.reduce((m, c, i) => (c === fg ? m | (1 << i) : m), 0)
279  return { ch: QUAD[mask] ?? ' ', fg, bg }
280}
281
282/**
283 * A crew member as three lines of cells, runs of one style merged. `frame`
284 * counts seconds while it runs and stays 0 while it doesn't, so a resting
285 * member stands still.
286 */
287export function mascotCells(slot: number, effort: string | undefined, frame = 0): Cell[][] {
288  const L = lookOf(slot)
289  const B = L.body
290  const D = shade(B, 0.72)
291  const W = TERM_MASCOT_W * 2
292  const px: Array<Array<string | undefined>> = Array.from({ length: TERM_MASCOT_H * 2 }, () => Array<string | undefined>(W).fill(undefined))
293  const p: Dot = (x, y, c) => {
294    const row = px[y]
295    if (row && x >= 0 && x < W) row[x] = c
296  }
297  const s: Span = (x0, x1, y, c) => {
298    for (let x = x0; x <= x1; x++) p(x, y, c)
299  }
300  // A round body: narrow head top, widening to the cheeks, a chin.
301  s(2, 9, 1, B); s(1, 10, 2, B); s(0, 11, 3, B); s(1, 10, 4, B)
302  // Feet under the eye columns; while walking, one lifts at a time.
303  const lifted = frame ? frame % 3 : -1
304  if (lifted !== 1) s(2, 3, 5, D)
305  if (lifted !== 2) s(8, 9, 5, D)
306  TERM_EXTRAS[L.extra](p, s, L, frame)
307  TERM_MOUTHS[L.mouth](p, s, L, frame)
308  const blink = frame > 0 && (frame + slot) % 5 === 4
309  for (const [side, x] of [[0, 2], [1, 8]] as const) {
310    const [tl, tr, bl, br] = blink ? [B, B, INK, INK] : TERM_EYES[L.eyes](L, frame, side)
311    p(x, 2, tl); p(x + 1, 2, tr); p(x, 3, bl); p(x + 1, 3, br)
312  }
313  const hat = lift(L.hatColor)
314  TERM_HATS[L.hat](p, s, hat, shade(hat, 0.72), frame)
315  if (effort) TERM_GEAR[effort]?.(p, s, frame)
316  const lines: Cell[][] = []
317  for (let j = 0; j < px.length; j += 2) {
318    const cells: Cell[] = []
319    for (let x = 0; x < W; x += 2) {
320      const c = quadCell([px[j]?.[x], px[j]?.[x + 1], px[j + 1]?.[x], px[j + 1]?.[x + 1]])
321      const last = cells[cells.length - 1]
322      if (last && last.fg === c.fg && last.bg === c.bg) last.ch += c.ch
323      else cells.push(c)
324    }
325    lines.push(cells)
326  }
327  return lines
328}
329
330/** `▰▰▰▱▱` for the terminal. */
331export const textBar = (ratio: number, width: number): string => {
332  const filled = Math.round(Math.max(0, Math.min(1, ratio)) * width)
333  return '▰'.repeat(filled) + '▱'.repeat(Math.max(0, width - filled))
334}
335
336/** `5h 23% · wk 41%`, or '' with no reading yet. */
337export function limitsShort(windows: CrewLimitWindow[]): string {
338  const five = windows.find(w => w.kind === 'five_hour')
339  const week = windows.find(w => w.kind === 'seven_day')
340  return [five ? `5h ${Math.round(five.percentUsed)}%` : '', week ? `wk ${Math.round(week.percentUsed)}%` : ''].filter(Boolean).join(' · ')
341}
342
343export { clip }
344
345export const RING = 18
346
347/** A small circular meter for a usage window, colored by meterColor. */
348export function ringSvg(pct: number, size = RING): string {
349  const c = size / 2
350  const r = c - 2
351  const len = 2 * Math.PI * r
352  const fill = (Math.max(0, Math.min(100, pct)) / 100) * len
353  return svg(
354    size,
355    size,
356    `<circle cx="${c}" cy="${c}" r="${r}" fill="none" stroke="#8a8a8a" stroke-opacity=".3" stroke-width="3"/>` +
357      `<circle cx="${c}" cy="${c}" r="${r}" fill="none" stroke="${meterColor(pct)}" stroke-width="3" stroke-linecap="round" stroke-dasharray="${fill.toFixed(2)} ${len.toFixed(2)}" transform="rotate(-90 ${c} ${c})"/>`,
358  )
359}
360
361/** The 5-hour and weekly windows, in that order, as [label, percent]. */
362export function limitPairs(windows: CrewLimitWindow[]): Array<[string, number]> {
363  const out: Array<[string, number]> = []
364  const five = windows.find(w => w.kind === 'five_hour')
365  const week = windows.find(w => w.kind === 'seven_day')
366  if (five) out.push(['5h', Math.round(five.percentUsed)])
367  if (week) out.push(['wk', Math.round(week.percentUsed)])
368  return out
369}
370
src/crew.ts 186 lines
1// The crew's looks: each subagent's own body color, hat, eyes, mouth and extra,
2// and its pixel mascot as an SVG group. Shared by the mod (hooks/draw.ts) and
3// the browser view (dashboard), so a crew member looks the same everywhere.
4// Pure functions, no engine or Node calls.
5
6export const INK = '#22201d'
7export const WOOD = '#A87B4F'
8export const GOLD = '#E8B931'
9export const WHITE = '#F4F4F1'
10export const BROWN = '#6B4A2B'
11export const LENS = '#CFEFFF'
12
13// ---------------------------------------------------------------------------
14// Each crew member's own look. A slot is a member's place in the job; every
15// trait steps through its list at a stride coprime to the list's length, so
16// neighbouring slots differ in every trait and the first twelve never share a
17// body color.
18
19const BODY = ['#E07A5F', '#3D9DD9', '#6CBF4A', '#9B7BE0', '#F2C94C', '#2BB3A0', '#E86AA6', '#4C6EF5', '#F08C2E', '#3CCFCF', '#E5484D', '#B5895A']
20const HATS = ['#E5484D', '#2B3A67', '#F2C94C', '#2E2A27', '#7CD35B', '#9B7BE0', '#F08C2E', '#3D9DD9', '#E86AA6', '#1F2A4A']
21
22export const HAT_STYLES = ['bandana', 'sailor', 'tricorne', 'beanie', 'captain', 'headphones', 'antennae', 'spikes', 'bow'] as const
23export const EYE_STYLES = ['round', 'big', 'sleepy', 'patch', 'glasses', 'fierce'] as const
24export const MOUTH_STYLES = ['smile', 'flat', 'open', 'mustache', 'beard', 'grin'] as const
25export const EXTRA_STYLES = ['none', 'blush', 'scarf', 'belt'] as const
26
27export type Look = {
28  body: string
29  hat: (typeof HAT_STYLES)[number]
30  hatColor: string
31  eyes: (typeof EYE_STYLES)[number]
32  mouth: (typeof MOUTH_STYLES)[number]
33  extra: (typeof EXTRA_STYLES)[number]
34  extraColor: string
35}
36
37const pick = <T>(list: readonly T[], n: number): T => list[((n % list.length) + list.length) % list.length] as T
38
39export function lookOf(slot: number): Look {
40  const body = pick(BODY, slot)
41  const notBody = (c: string, n: number): string => (c === body ? pick(HATS, n + 1) : c)
42  return {
43    body,
44    hat: pick(HAT_STYLES, slot * 2 + 1),
45    hatColor: notBody(pick(HATS, slot * 7 + 3), slot * 7 + 3),
46    eyes: pick(EYE_STYLES, slot * 5 + 1),
47    mouth: pick(MOUTH_STYLES, slot + 3),
48    extra: pick(EXTRA_STYLES, slot * 3 + 1),
49    extraColor: notBody(pick(HATS, slot * 3), slot * 3),
50  }
51}
52
53export function hashOf(s: string): number {
54  let h = 0
55  for (const ch of s) h = (h * 31 + ch.charCodeAt(0)) >>> 0
56  return h
57}
58
59/**
60 * Slots for one job's crew: the planned task titles first, in plan order, then
61 * any other run, so a member keeps its look from planned to running to done.
62 * The job's title turns the wheel, so two jobs field different crews.
63 */
64export function crewSlots(job: string, keys: string[]): (key: string) => number {
65  const base = hashOf(job) % BODY.length
66  const index = new Map<string, number>()
67  for (const k of keys) if (!index.has(k)) index.set(k, index.size)
68  return key => base + (index.get(key) ?? hashOf(key))
69}
70
71/** `#rrggbb` scaled toward black (f < 1) or white (f > 1). */
72export function shade(hex: string, f: number): string {
73  return '#' + [1, 3, 5].map(i => Math.round(Math.min(255, parseInt(hex.slice(i, i + 2), 16) * f)).toString(16).padStart(2, '0')).join('')
74}
75
76type Put = (x: number, y: number, w: number, h: number, fill: string, group?: string) => void
77
78// What a member holds tells its effort; the animation classes move these.
79const GEAR: Record<string, (r: Put) => void> = {
80  // A mop that swishes.
81  low: r => {
82    r(21, 4, 1, 13, WOOD, 'prop'); r(19, 17, 5, 2, '#CFCFCB', 'prop')
83    r(19, 19, 1, 1, '#CFCFCB', 'prop'); r(21, 19, 1, 1, '#CFCFCB', 'prop'); r(23, 19, 1, 1, '#CFCFCB', 'prop')
84  },
85  // An oar that rows.
86  medium: r => {
87    r(21, 3, 1, 13, WOOD, 'prop'); r(20, 15, 3, 4, '#8A6038', 'prop')
88  },
89  // A spyglass that scans.
90  high: r => {
91    r(19, 11, 5, 2, '#C9A227', 'prop'); r(19, 11, 1, 2, '#8C6F12', 'prop'); r(23, 11, 1, 2, '#9BD3F5', 'prop')
92  },
93  // A lantern whose flame flickers.
94  xhigh: r => {
95    r(21, 7, 1, 2, INK); r(20, 9, 3, 1, INK); r(20, 10, 3, 4, GOLD); r(20, 14, 3, 1, INK)
96    r(21, 11, 1, 2, '#FF8A3D', 'flame')
97  },
98  // A ship's wheel that turns.
99  max: r => {
100    r(20, 11, 3, 1, WOOD, 'prop'); r(20, 17, 3, 1, WOOD, 'prop'); r(18, 13, 1, 3, WOOD, 'prop'); r(24, 13, 1, 3, WOOD, 'prop')
101    r(19, 12, 1, 1, WOOD, 'prop'); r(23, 12, 1, 1, WOOD, 'prop'); r(19, 16, 1, 1, WOOD, 'prop'); r(23, 16, 1, 1, WOOD, 'prop')
102    r(21, 10, 1, 9, '#8A6038', 'prop'); r(17, 14, 9, 1, '#8A6038', 'prop'); r(21, 14, 1, 1, GOLD, 'prop')
103  },
104}
105
106const EYES: Record<Look['eyes'], (r: Put, L: Look) => void> = {
107  round: r => {
108    for (const x of [8, 14]) { r(x, 12, 2, 2, INK); r(x, 12, 1, 1, '#fff') }
109  },
110  big: r => {
111    for (const x of [8, 14]) { r(x, 11, 2, 3, '#fff'); r(x + 1, 12, 1, 2, INK) }
112  },
113  sleepy: (r, L) => {
114    for (const x of [8, 14]) { r(x, 12, 2, 1, shade(L.body, 0.7)); r(x, 13, 2, 1, INK) }
115  },
116  patch: r => {
117    r(5, 10, 14, 1, INK); r(7, 11, 4, 3, INK); r(14, 12, 2, 2, INK); r(14, 12, 1, 1, '#fff')
118  },
119  glasses: r => {
120    for (const x of [7, 13]) { r(x, 11, 4, 4, INK); r(x + 1, 12, 2, 2, LENS); r(x + 2, 13, 1, 1, INK) }
121    r(11, 12, 2, 1, INK)
122  },
123  fierce: r => {
124    for (const x of [8, 14]) { r(x, 12, 2, 2, INK); r(x, 12, 1, 1, '#fff') }
125    r(7, 10, 1, 1, INK); r(8, 11, 2, 1, INK); r(16, 10, 1, 1, INK); r(14, 11, 2, 1, INK)
126  },
127}
128
129const MOUTHS: Record<Look['mouth'], (r: Put) => void> = {
130  smile: r => { r(10, 15, 1, 1, INK); r(11, 16, 2, 1, INK); r(13, 15, 1, 1, INK) },
131  flat: r => r(11, 15, 2, 1, INK),
132  open: r => { r(11, 15, 2, 2, '#7A2230'); r(11, 16, 2, 1, '#E5737F') },
133  mustache: r => { r(9, 15, 6, 1, BROWN); r(8, 16, 1, 1, BROWN); r(15, 16, 1, 1, BROWN) },
134  beard: r => { r(7, 15, 10, 1, BROWN); r(6, 16, 12, 1, BROWN); r(7, 17, 10, 1, BROWN); r(11, 15, 2, 1, '#7A2230') },
135  grin: r => { r(10, 15, 4, 2, INK); r(11, 15, 1, 1, '#fff'); r(12, 15, 1, 1, '#fff') },
136}
137
138const EXTRAS: Record<Look['extra'], (r: Put, L: Look) => void> = {
139  none: () => {},
140  blush: (r, L) => {
141    r(6, 15, 2, 1, 'rgba(255,120,140,.6)'); r(16, 15, 2, 1, 'rgba(255,120,140,.6)')
142    r(7, 14, 1, 1, shade(L.body, 0.7)); r(16, 14, 1, 1, shade(L.body, 0.7))
143  },
144  scarf: (r, L) => { r(6, 17, 12, 1, L.extraColor); r(15, 18, 2, 2, L.extraColor) },
145  belt: r => { r(6, 17, 12, 1, '#3A2A1E'); r(11, 17, 2, 1, GOLD) },
146}
147
148const HATS_DRAW: Record<Look['hat'], (r: Put, c: string, d: string) => void> = {
149  bandana: (r, c, d) => { r(6, 9, 12, 2, c); r(18, 9, 2, 1, c); r(19, 10, 2, 1, d); r(8, 9, 1, 1, '#fff'); r(12, 10, 1, 1, '#fff'); r(15, 9, 1, 1, '#fff') },
150  sailor: (r, c) => { r(7, 6, 10, 3, WHITE); r(7, 8, 10, 1, c); r(11, 5, 2, 1, c) },
151  tricorne: (r, c) => { r(7, 6, 10, 2, c); r(5, 8, 14, 1, INK); r(11, 6, 2, 1, GOLD) },
152  beanie: (r, c, d) => { r(7, 7, 10, 3, c); r(7, 9, 10, 1, d); r(11, 6, 2, 1, WHITE) },
153  captain: (r, c) => { r(6, 5, 12, 3, c); r(5, 8, 14, 1, INK); r(11, 6, 2, 1, GOLD) },
154  headphones: (r, c) => { r(7, 7, 10, 1, INK); r(6, 8, 1, 2, INK); r(17, 8, 1, 2, INK); r(4, 10, 3, 4, c); r(17, 10, 3, 4, c) },
155  antennae: (r, c) => { r(8, 6, 1, 3, INK); r(15, 6, 1, 3, INK); r(7, 4, 3, 2, c); r(14, 4, 3, 2, c) },
156  spikes: (r, c) => { r(7, 8, 10, 1, c); r(7, 7, 2, 1, c); r(10, 5, 2, 3, c); r(13, 6, 2, 2, c); r(16, 7, 1, 1, c) },
157  bow: (r, c, d) => { r(12, 6, 3, 3, c); r(16, 6, 3, 3, c); r(15, 7, 1, 1, d) },
158}
159
160/**
161 * One crew member as an SVG group on a 26×22 grid, placed at (x, y) and
162 * scaled. Periods of every motion divide one second, so the once-a-second
163 * redraw of a running row restarts them in step and nothing visibly jumps.
164 */
165export function mascot(x: number, y: number, scale: number, slot: number, effort: string | undefined, opts: { running?: boolean; dim?: boolean } = {}): string {
166  const groups: Record<string, string[]> = { bd: [], la: [], lb: [], prop: [], flame: [] }
167  const r: Put = (px, py, w, h, fill, g = 'bd') => {
168    ;(groups[g] ??= []).push(`<rect x="${px}" y="${py}" width="${w}" height="${h}" fill="${fill}"/>`)
169  }
170  const L = lookOf(slot)
171  const B = L.body
172  const D = shade(B, 0.72)
173  r(7, 9, 10, 1, B); r(6, 10, 12, 1, B); r(5, 11, 14, 6, B); r(6, 17, 12, 1, B)
174  r(3, 13, 2, 3, B); r(19, 13, 2, 3, B)
175  r(6, 18, 2, 3, D, 'la'); r(12, 18, 2, 3, D, 'la'); r(9, 18, 2, 3, D, 'lb'); r(15, 18, 2, 3, D, 'lb')
176  EXTRAS[L.extra](r, L)
177  EYES[L.eyes](r, L)
178  MOUTHS[L.mouth](r)
179  HATS_DRAW[L.hat](r, L.hatColor, shade(L.hatColor, 0.72))
180  const gear = effort ? GEAR[effort] : undefined
181  gear?.(r)
182  const g = (name: string): string => ((groups[name] ?? []).length ? `<g class="${name}">${(groups[name] ?? []).join('')}</g>` : '')
183  const cls = `m e-${gear ? effort : 'none'}${opts.running ? ' run' : ''}`
184  return `<g transform="translate(${x},${y}) scale(${scale})" opacity="${opts.dim ? 0.6 : 1}" shape-rendering="crispEdges"><g class="${cls}"><g class="bd">${(groups.bd ?? []).join('')}${g('prop')}${g('flame')}</g>${g('la')}${g('lb')}</g></g>`
185}
186
types/index.d.ts 117 lines
1// State contract of the Luff Crew mod: every value it keeps in `$.state`.
2
3export type CrewPhase = 'plan' | 'design' | 'delegate' | 'review' | 'close'
4
5export type CrewTask = {
6  title: string
7  agent?: string
8  model?: string
9  effort?: string
10  after: number[]
11}
12
13export type CrewFlow = {
14  title: string
15  total: number
16  done: number
17  phase: CrewPhase
18  finished: boolean
19  tasks: CrewTask[]
20  startedAt: number
21  updatedAt: number
22}
23
24export type CrewStep = { done: number; total: number; note?: string }
25
26export type CrewRun = {
27  /** The subagent's id, or the Agent call's id until the engine names one. */
28  id: string
29  agentId?: string
30  type: string
31  description: string
32  model: string
33  effort?: string
34  status: 'running' | 'done' | 'failed'
35  failure?: string
36  startedAt: number
37  endedAt?: number
38  contextTokens: number
39  contextMax: number
40  tokens: number
41  costUsd: number
42  requests: number
43  round: number
44  step?: CrewStep
45}
46
47export type CrewPanel = {
48  isCompact: boolean
49  isFinishedOpen: boolean
50  isLimitsOpen: boolean
51  /** The job bar was hidden at this time; a later progress call or prompt shows it again. */
52  hiddenAt: number
53  /** Job titles the pane already opened itself for. */
54  autoOpenedFor: string[]
55}
56
57export type CrewLimitWindow = {
58  /** `five_hour`, `seven_day`, or a gateway's `spend_limit`. */
59  kind: string
60  percentUsed: number
61  /** Epoch ms; 0 when unknown. */
62  resetsAt: number
63}
64
65export type CrewLimits = {
66  windows: CrewLimitWindow[]
67  /** Epoch ms of the last reading; 0 before the first. */
68  measuredAt: number
69}
70
71/** The main loop's current (or last) turn: one per prompt, subagents or not. */
72export type CrewTurn = {
73  turnId: string
74  /** The prompt that started it, clipped; "" for a continuation. */
75  prompt: string
76  status: 'running' | 'done' | 'failed'
77  /** `stopped` or `error` when it did not end with an answer. */
78  failure?: string
79  startedAt: number
80  endedAt?: number
81  /** Model requests so far. */
82  steps: number
83  /** Tool calls the model asked for so far. */
84  tools: number
85  lastTool?: string
86  tokens: number
87  costUsd: number
88}
89
90/** The optional browser dashboard, while one runs for this session. */
91export type CrewWeb = {
92  status: 'starting' | 'running'
93  url: string
94  startedAt: number
95}
96
97/** Tokens and estimated cost the mod saw, per hour bucket (epoch hour → totals). */
98export type CrewUsageBuckets = Record<string, { tokens: number; costUsd: number; requests: number }>
99
100declare module 'claude-code' {
101  interface PluginState {
102    'luff-crew-monitor': {
103      flow: CrewFlow | null
104      runs: CrewRun[]
105      turn: CrewTurn | null
106      web: CrewWeb | null
107      panel: CrewPanel
108      now: number
109      limits: CrewLimits
110      /** What this session counted, per hour. */
111      usage: CrewUsageBuckets
112      /** What other sessions counted, per hour, read from `$.store`. */
113      others: CrewUsageBuckets
114    }
115  }
116}
117