Glitch pets: pick one of six pixel critters; it sits at the end of the HUD row, shows moods and says a word now and then; leads the crew pane when Claude…

Glitch is a kit of Claude Code mods, published from this folder as a marketplace named glitch. It puts one band above the prompt that shows the session at a glance, makes spending and prompt-cache expiry visible before they cost money, and themes everything from one place. A Glitch bug never breaks the session, and Glitch refuses nothing unless you ask it to: the one refusal is the opt-in subagent block at a budget cap.
| Plugin | What it does |
|---|---|
glitch-core | Shared themes and the /glitch command. |
glitch-hud | The band above the prompt: turn, speed, cost and budget, cache countdown with keep-warm, context, git. Depends on glitch-core. |
glitch-pets | A pixel pet at the end of the HUD row, with moods, short remarks and a daily streak. Depends on glitch-core and glitch-hud. |
One line above the prompt. In the terminal it is text with theme colors and icons:
| Part | Example | Source |
|---|---|---|
| turn | #12 | count of main-session turns |
| speed | ⚡ 84 tok/s | output tokens divided by streaming time of the last main response (ignores answers under 20 tokens or 0.5 s) |
| cost | $ 0.42 reply · 3.10 session · 21.40 today | the last reply, this session, and today across every session on this machine; pick them with costShows. Colored by budget level |
| cache | ⧗ 47:12 ↻ | countdown to prompt-cache expiry (cacheTtlMinutes, 60 by default); … while a turn runs |
| context | ▓▓▓▓░░ 63% | context window used; amber from 65%, red from 85% |
| git | main ±4 ↑1 | branch, changed files, ahead/behind; hidden outside a repo |
Desktop, VS Code and mobile. These apps draw the band with vector icons, a real context bar and worded values (Turn 12, $0.42 reply · $3.10 session · $21.40 today, 47:12 left, 63% context). The desktop already shows the branch above the band, so git is left out there unless you change Parts in the settings or run /glitch hud parts …. tok/s is left out on the desktop too: turn it on with the Show tok/s setting or /glitch hud speed on.
The three costs. A reply is everything Claude does to answer one message: every model call, tool use and subagent until it stops. It is left out while it equals the session figure (the first reply). Session is the figure /cost shows. Today adds up every session that ran glitch-hud on this computer since local midnight, in any project; it is not your account's spend on other machines or on claude.ai. With a cap set, the figure shows it: $3.10 of $5.00 session.
Width. As the window narrows, parts drop in the order git, speed, turn; then the cost figures lose their words and the context bar becomes just the percent. The row never wraps.
Hiding. The × at the end of the band hides it for the session; /glitch hud toggles it again. The band is not drawn before the first turn or while a survey shows. Other mods' bands render beneath it.
Set a cap per session (budgetSession), per local day (budgetDaily), or both. 0 turns a cap off.
notify = windows also a Windows notification.The 90% and 100% toasts appear in the session whatever notify says; notify = windows adds the Windows notification at 100%; notify also picks how the cache warnings reach you (an in-app toast by default, a Windows notification with windows, none with off).
Each level fires once per cap per session; raising a cap re-arms the higher levels. The daily ledger sums every session's spend for the local date: each session keeps its own entry per day under its session id, so sessions running side by side, a reload, a /clear or a resume never double count; entries older than 7 days are pruned. Caps changed in /config apply when the plugin reloads, except a session cap you already set with /glitch budget.
With budgetBlocksAgents on, new subagents are refused once either cap is reached. At the session cap the refusal asks Claude to have you raise it with /glitch budget +N; at the daily cap it asks you to run /glitch budget off for this session or raise budgetDaily in /config (+N moves the session cap only). The main conversation is never blocked, and if the check itself fails the call is allowed.
Costs are Claude Code's own estimate at API prices, not a bill; on a subscription they are not charged.
Claude Code's prompt cache lives for a fixed time after the last request: 1 hour on most plans, 5 minutes on others. Set cacheTtlMinutes to match (60 by default; set 5 if your account's cache lasts 5 minutes). The cache part counts down to that deadline from each answer and pauses (…) while a turn runs; a turn interrupted before any request leaves it as it was, and /clear drops it.
Left empty, cacheWarnMinutes fits the lifetime: marks at 10 and 5 minutes left for 1 hour, at 2 and 1 for 5 minutes. Marks you type at or above the lifetime can never fire: they are ignored and named once at session start. The countdown turns the warning color at a third of the lifetime left (20 minutes of an hour, 1:40 of 5 minutes) and the alert color at a sixth (10 minutes, 0:50).
<project> — Glitch: "Prompt cache expires in N min".notify = toast) a warning is an in-app toast in the session that raised it, so background sessions never reach the OS notification centre. Set notify = windows to opt in to OS notifications: a native Windows toast is tried first; if that fails (or the OS is not Windows) Claude Code's own notification channel is used, then an in-app toast. off turns off the cache warnings (the budget toasts above still show).↻ on the cache part, or /glitch warm, sends a tool-less fork of the session's last request with a one-line question after it. The request is served from the prompt cache, which refreshes it, and nothing is added to the transcript. It is refused while a turn runs. The reply reports how many tokens were read from cache, and the countdown resets to the full lifetime (60:00, or 05:00).autoWarmMaxIdle minutes; never twice in a row without a prompt from you in between.Pick a pet and it sits at the end of the HUD row on the desktop app. While Claude works, your pet types on a little laptop; between turns it does its signature move. It reacts to the session through moods, says a short word now and then as a toast, and keeps a daily streak. Click the pet and it hops for a moment, then goes back to what it was doing. It is not drawn in the terminal; there, remarks arrive as toasts.
| Pet | Kind | Temperament | Signature move (idle) |
|---|---|---|---|
| Screenhead | screen bot | Earnest, literal and a little robotic; reports facts, proud of tidy output. | Types; code scrolls on its screen face. |
| Byte blob | blob | Bubbly and easily startled; squeaks with joy, wobbles when worried. | Bounces: squash, stretch and a glitch slice. |
| Pixel | cat | Dry and unimpressed, secretly proud; says little, means it. | Swishes its tail and sheds pixels. |
| Dot | ladybug | Tidy, gentle and encouraging; notices the small things. | Flutters her wings on a daisy. |
| Fork | octopus | The organised multitasker; a born lead who loves a plan. | Taps four keys with four arms. |
| Bud | dog | Eager and loyal; cheers for everything and wants to go again. | Wags, pants and flops an ear. |
Moods: idle, working, happy, tired, sleepy, worried, oops, cheering, leading, reviewing, crying. It cries when the budget cap is reached, when a daily streak of two or more days is broken, and after three failures in a row.
/glitch-pets <name | off> switches to a pet and remembers it, or empties the slot; /glitch-pets alone lists the pets. /glitch pet [name | off] works the same way.
| Setting | Default | Meaning |
|---|---|---|
pet | bud | your pet: screenhead, blob, pixel, dot, fork, bud or off; /glitch pet <name> overrides it |
voice | true | one-line remarks as toasts |
voiceEveryMinutes | 3 | at most one remark per this many minutes |
tiredMinutes | 10 | a turn this long makes the pet tired |
sleepyMinutes | 10 | this long without a prompt makes the pet sleepy |
/plugin install glitch-pets@glitch
When Claude splits work across a crew of agents, the crew pane (glitch-crew) shows them live. Your pet leads: its line says what it is doing (waiting on a member, looking into a failure, checking the work), and its mood follows the crew. Each crew member is a small copy of your pet acting out its role, in the crew look you picked.
Crew · 3 running · 1 done · 1 failed · ≈$0.31 · 74k tok · 0:37
Bud · sniffing out builder-1
● Researcher Research date formats Haiku 5.5 low 9k ≈$0.04 0:37 ██████░░ 6/8
● Designer Design the date picker Opus 5.5 high 31k ≈$0.13 0:37 ██░░░░░░ 2/8
● Builder ↑ Sonnet · medium · Build th… Sonnet 5.5 high 4k ≈$0.02 0:05 █░░░░░░░ 1/8
✗ 2 finished · 1 completed · 1 failed [ Show ]
builder-1, researcher-2, …), or failing that from the words in its task, then the opening of its instructions; a task put as a question ("how refrigerators cool") or an Explore agent is a researcher. With the default look (busy-hands) each mini acts its role out beside itself, at its model's tempo; with hats it wears its role's hat.↑ stepped up from Haiku · low; on the terminal ↑ Haiku · low).Researcher) with its task cut short beside it, and below that what it is doing right now, from its latest tool call (Searching the web: “…”, Editing cpu-notes.md, Running: npm test). Once it has finished, the chip stands alone and the line below shows its whole task. Its model, cost and tokens are small rounded badges, and each member has a little room above and below. The terminal shows the role and the task on the member's line. A member of no clear role goes by its name. When Claude's description only repeats the role or the name, the task comes from the first sentence of the member's instructions.Expected steps: N line in its instructions; without one, a default for its tier: light 6, medium 12, heavy 20, the reviewer 10). It starts at 0/12, not a bare 0, and the total goes up if the member runs past it. The Running header's bar and its 6/20 are the whole crew's steps done out of those planned: blue while the crew works, full and green once the last member finishes.✓ 3 finished · 3 completed · 0 failed [ Show ]); Show lists them, Hide folds them again. On the desktop, Running and Finished are accordion groups that start open; press a header's words (● RUNNING 3 ▾, FINISHED 2 ▾; RUN 3 ▾ in a very narrow pane) to fold it to that line. The colored bar beside Running is the crew's steps done out of those planned; beside Finished, the share completed and failed. Finished keeps its tally of tasks, completed and failed. The choice lasts for the current crew./glitch crew (or /glitch-pets crew) opens or closes the pane. With crewPane: auto it opens by itself when the first crew member starts./glitch crew debug (or /glitch-pets crew debug) prints the crew rows beside the engine's own agent list (ids and statuses), the pane's last presses and what came of them, and the view each surface drew under, for checking the pane live./glitch crew theme [id] (or /glitch-pets crew theme [id]) lists the crew looks, or picks one and keeps it: busy-hands (default: each crew member acts its role out beside itself, and the model sets how much each beat makes and the tempo) or hats.The crew skill is the workflow Claude follows when work splits into 2 or more parts:
A standing system-prompt rule asks for this. If 2 or more crew members (named builder-1, researcher-2 and so on) finish with no reviewer, Claude gets a one-time reminder on its next turn to run the review.
| Setting | Default | Meaning |
|---|---|---|
crewPane | auto | auto opens the pane when a crew starts; manual waits for /glitch crew |
crewReview | true | the crew rule in the system prompt, and the reminder when a review was skipped |
crewTiers | empty | JSON: each crew tier's model and effort, and the reviewer's (see below); empty uses the default table |
crewTheme | busy-hands | how crew members look in the pane: busy-hands or hats; /glitch crew theme <id> overrides it |
crew skill guides it: Claude writes the plan, gives each task a role and a tier, and names each crew member <role>-<n>.subagent_type: glitch-pets:crew-<tier>:| Tier | Agent type | Model | Effort |
|---|---|---|---|
| light | glitch-pets:crew-light | Haiku 5.5 (claude-haiku-5-5) | low |
| medium | glitch-pets:crew-medium | Sonnet 5.5 (claude-sonnet-5-5) | medium |
| heavy | glitch-pets:crew-heavy | Opus 5.5 (claude-opus-5-5) | high |
The type's model wins: if the Agent call passes a different model, the plugin sets it back to the type's when the crew member starts, and it sets an effort the Agent call passes to the type's. The one thing that beats the type is a setup that forces one model on every subagent. A crew member can't start agents of its own.
crewTiers to a JSON object. Each tier you leave out keeps its default, for example: { "light": { "model": "claude-sonnet-5-5", "effort": "low" }, "heavy": { "effort": "medium" } }
model is an alias (haiku, sonnet, opus) or a full model id. A tier's effort is low, medium or high. A bad value keeps that field's default, and a toast at session start says what was wrong.
Haiku low → Haiku high → Sonnet medium → Sonnet high → Opus high → Opus xhigh → Opus max
A task gets at most 2 step-ups. The step-up types (crew-light-high, crew-medium-high, crew-heavy-xhigh, crew-heavy-max) are registered next to the tiers. xhigh and max are only ever steps, never a tier's own effort. With your own crewTiers, the steps follow the same rule: the tier's model at high effort (if it isn't already high), then the next tier, and after the heavy tier each higher effort.
general-purpose, your .claude/agents/*.md) picks its model as Claude Code always does: the Agent call's model, then the type's model, then your default subagent model, then the session's model. A fork always runs on its parent's model. The plugin leaves those alone and doesn't step them up.The reviewer checks the crew's work. It doesn't do the work again. Redoing every task would roughly double the cost and the time of the crew.
glitch-pets:crew-reviewer, on Sonnet 5.5 (claude-sonnet-5-5) at low effort. It has a limit of 18 turns and is told to stop checking by turn 14, so it always has room to send its findings. It can run commands (for the checks) but can't edit files or start agents of its own. Claude starts it as reviewer-1. If Claude starts an agent named reviewer-<n> on another type anyway, the plugin moves it onto glitch-pets:crew-reviewer, with the reviewer's model and effort. Only the name counts: other agents that review something (an Explore agent reading docs, another plugin's reviewer) keep their own type.reviewer entry to crewTiers. For example, to use Haiku at medium effort: { "reviewer": { "model": "claude-haiku-5-5", "effort": "medium" } }
The reviewer's effort is low, medium or high. A field you leave out or get wrong keeps its default. The reviewer never steps up.
Six built-in themes: glitch (default, electric cyan and magenta), neon, mono, sunset, matrix, paper. /glitch theme lists them, /glitch theme neon switches and remembers the choice across sessions, /glitch theme default clears it.
Resolution order: the last /glitch theme <name>, then the theme setting, then glitch. The custom setting, a JSON object of tokens, is merged over the result:
{ "accent": "#ff6ad5", "bar": "█░" }
Color tokens are accent, good, warn, alert, muted, info (as #rrggbb); bar is the full and empty characters of the context bar; icons is emoji, symbols or ascii. An unknown theme name falls back to glitch; malformed custom JSON is ignored and the chosen theme is kept. Either problem toasts at session start.
/glitch is owned by glitch-core. The HUD subcommands are answered by glitch-hud directly, the pet subcommand by glitch-pets, and the same subcommands also work as /glitch-hud ….
| Command | Owner | Does | |||
|---|---|---|---|---|---|
/glitch | core | help card: theme and the subcommands each plugin answers | |||
| `/glitch theme [name\ | default]` | core | list themes, or switch and persist | ||
| `/glitch-pets [name\ | off]` | pets | list pets, switch and persist, or turn the pet off | ||
| `/glitch pet [name\ | off]` | pets | the same, through the core command | ||
/glitch crew | pets | open or close the crew pane (also /glitch-pets crew) | |||
/glitch hud | hud | show or hide the band | |||
/glitch hud parts <list> | hud | parts and order for this session, as a comma list, e.g. cost,cache,context or cost, cache | |||
/glitch hud cost <list> | hud | cost figures and order for this session, e.g. session,today | |||
| `/glitch hud speed on\ | off\ | auto` | hud | show or hide tok/s, kept for later sessions; auto follows the setting | |
| `/glitch budget [+N \ | N \ | off \ | on]` | hud | show, raise, set, disable or re-enable this session's caps |
/glitch warm | hud | keep-warm ping now | |||
/glitch demo cache <min> | hud | preview the cache part and warnings at N minutes left; demo warnings say "(demo)", never auto-warm, and the real countdown comes back when the demo runs out or at the next answer | |||
/glitch demo budget <pct> | hud | preview the budget levels at N percent |
An unknown subcommand shows the help card. /glitch budget +N and N change this session's cap only; off disables both caps for this session.
Set them in /config, or in ~/.claude/settings.json under pluginConfigs. Invalid values fall back to the default and toast once.
glitch-core
| Setting | Default | Meaning |
|---|---|---|
theme | glitch | default theme: glitch, neon, mono, sunset, matrix, paper |
custom | empty | JSON object of theme tokens laid over the theme |
glitch-hud
| Setting | Default | Meaning |
|---|---|---|
parts | turn,speed,cost,cache,context,git | which parts show, in order |
showSpeed | auto | tok/s: auto shows it in the terminal only (and on the desktop when Parts was changed), on or off everywhere |
costShows | reply,session,today | which cost figures show, in order |
budgetSession | 0 | USD cap per session; 0 is off |
budgetDaily | 0 | USD cap per local day, across sessions; 0 is off |
budgetBlocksAgents | false | refuse new subagents at a cap |
cacheTtlMinutes | 60 | prompt cache lifetime: 60 (most plans) or 5 |
cacheWarnMinutes | empty | minutes-left marks that notify; empty fits the lifetime (10,5 for 1 hour, 2,1 for 5 minutes); marks at or above the lifetime are ignored |
notify | toast | toast (inside the Claude Code session that raised it), windows (native Windows notification) or off (no cache or cap notifications; budget toasts still show) |
autoWarm | false | keep the cache warm by itself at the last warning mark |
autoWarmMaxIdle | 120 | minutes without a prompt from you after which autoWarm stops |
/plugin install glitch-hud --marketplace <owner>/<repo>
Answer y to add the marketplace, then pick a scope. This also installs glitch-core.
From a local folder:
claude plugin marketplace add C:\path\to\this\folder
/plugin install glitch-hud@glitch
To add the pets: /plugin install glitch-pets@glitch.
Or load the plugin folders directly with CLAUDE_CODE_PLUGIN_DIRS, separated by ; on Windows. In cmd:
set CLAUDE_CODE_PLUGIN_DIRS=C:\path\to\this\folder\plugins\glitch-core;C:\path\to\this\folder\plugins\glitch-hud
In PowerShell:
`
hooks/register.tsx 981 lines1import { atom, read, update } from 'claude-code'
2import type { AgentInfo, EngineInterface, Register } from 'claude-code'
3
4import type { MoodState, PetsView } from '../types'
5import { personaProblems } from './behavior/contract'
6import { INITIAL_CREW, crewSummaryOf, elapsedOf, helpersRunning, memberName, onAgentRunEnd, onAgentTurnEnd, onAgentWake, onMainTurnEnd, onMainTurnStart, onSpawn, onStatuses, onStep, onStepUsage, onTool, onToolStart, reviewerRunning, shares, stepsOf } from './behavior/crew'
7import type { CrewState, CrewSummary } from './behavior/crew'
8import { CREW_RULE, GATE_TEXT, needsReview } from './behavior/gate'
9import { leadStatus } from './behavior/lead-status'
10import { isCapReached } from './behavior/moods'
11import type { BudgetLike } from './behavior/moods'
12import { createPlayer, frameIndex } from './behavior/player'
13import { activityOf } from './behavior/activity'
14import { isHopping, nextSparkIn, withSparkle } from './behavior/sparkle'
15import { STORE_STREAK, advance, asStreak } from './behavior/streak'
16import { AGENT_PREFIX, REVIEWER_TYPE, agentSpecs, claimStepUp, isReviewerName, isReviewerSpawn, isReviewerType, ladderOf, reviewerSpec, rungOfType, stepUpNote, stepUpsFor } from './behavior/tiers'
17import type { CrewTiers, Rung, StepUp } from './behavior/tiers'
18import type { MoodArt, MoodId, Persona, PetId, Sprite, VoiceMoment } from './behavior/types'
19import { PET_IDS } from './behavior/types'
20import { INITIAL_VOICE, pickLine } from './behavior/voice'
21import type { VoiceState } from './behavior/voice'
22import { PETS_USAGE, ROUTED_PETS, STORE_PET, parsePetArg, petArgsOf, petList } from './commands'
23import { parsePetsConfig } from './config'
24import type { PetsConfig } from './config'
25import { DESKTOP_CELL, LEAD_POKE, MINI_PIXEL, crewTree } from './pane'
26import type { CrewGroup, CrewMember, CrewView } from './pane'
27import { PERSONAS } from './personas/index'
28import { onCrewChange, onPoke, onToolResult, onTurnEnd, onTurnStartStreak, tickOnce } from './tick'
29import { INITIAL_REACTIONS } from './behavior/reactions'
30// Crew themes (#41): the setting and /glitch crew theme. The pane draws minis with crewMini(view.crewTheme, ...).
31import { STORE_CREW_THEME, crewDebugText, crewThemeArgOf, isCrewDebug, parseThemeArg, themeList } from './commands'
32import type { CrewDebugState } from './commands'
33import { CREW_THEMES, DEFAULT_CREW_THEME, crewMini, crewThemeIds } from './crew-themes/index'
34
35const INITIAL_MOOD: MoodState = { mood: 'idle', since: 0, turnSince: null, lastPromptAt: 0, oopsUntil: 0, happyUntil: 0, cheerUntil: 0, cryUntil: 0, failStreak: 0, pokedUntil: 0, pokeSeen: 0, reactions: INITIAL_REACTIONS }
36
37export const sprite = atom({ plugin: 'glitch-pets', key: 'sprite' } as const, null as Sprite | null)
38export const mood = atom({ plugin: 'glitch-pets', key: 'mood' } as const, INITIAL_MOOD)
39export const view = atom({ plugin: 'glitch-pets', key: 'view' } as const, { petId: 'bud' } as PetsView)
40export const crew = atom({ plugin: 'glitch-pets', key: 'crew' } as const, INITIAL_CREW as CrewState)
41/** Which crew pane groups are open, keyed `<crew start>:<group>` (the terminal's fold under its own key). */
42export const crewOpen = atom({ plugin: 'glitch-pets', key: 'crewOpen' } as const, {} as Record<string, boolean>)
43/** What glitch-hud's crew pill shows; null while no crew is open or recent. */
44export const crewSummary = atom({ plugin: 'glitch-pets', key: 'crewSummary' } as const, null as CrewSummary | null)
45/** The crew pane's frame clock: touched (from the 100 ms tick) when a mini (running, or hopping after its finish) next changes, so the pane redraws then. */
46export const paneFrame = atom({ plugin: 'glitch-pets', key: 'paneFrame' } as const, 0)
47
48const PANE = 'glitch-crew'
49/** The lead draws at 3× (48 × 39), clearly larger than the crew's 2× minis. */
50const LEAD_PIXEL = 3
51/**
52 * The room the pane asks for, by where it will show: a narrow dock (about 300 px) and
53 * room inline for the lead and about three members on the rich surfaces; a dock wide
54 * enough for the aligned rows and a few lines inline on the terminal.
55 */
56const PANE_SIZE = { rich: { columns: 56, rows: 24 }, terminal: { columns: 90, rows: 10 } } as const
57type PaneSize = { columns: number; rows: number }
58/** A fullscreen terminal's dock leaves the transcript about half its columns, within these. */
59const DOCK_COLUMNS = { min: 40, max: 90 } as const
60/** glitch-hud's crew pill in its band: a press on it opens or closes the pane. */
61const HUD_PILL = 'glitch-crew'
62/** Helpers' statuses are asked every this many ticks (1 s). */
63const STATUS_TICKS = 10
64
65export const TICK_MS = 100
66const LONG_TURN_MS = 120_000
67const SPEAKS_ON_ENTRY: Partial<Record<MoodId, VoiceMoment>> = { worried: 'worried', sleepy: 'sleepy', oops: 'oops', cheering: 'cheering', crying: 'crying' }
68
69// Pets that break the contract are left out (named once at start).
70// Composed personas hold the laptop keys 4/6/7 by design; the raw-file reserved-key check lives in personas/index.ts (composeSafely) and personas.test.
71const usable = Object.fromEntries(Object.entries(PERSONAS).filter(([, p]) => p && personaProblems(p, { composed: true }).length === 0)) as Partial<Record<PetId, Persona>>
72const broken = (Object.keys(PERSONAS) as PetId[]).filter(id => !usable[id])
73const available = PET_IDS.filter(id => usable[id])
74const personaFor = (id: PetId | 'off'): Persona | null => (id === 'off' ? null : (usable[id] ?? usable.screenhead ?? null))
75
76// Per-load state, set in `register`.
77let config: PetsConfig = parsePetsConfig({}).config
78let player = createPlayer()
79let voice: VoiceState = INITIAL_VOICE
80let lastSource: string | null = null
81let ticking = false
82let ticks = 0
83/** The reviewer finished while the main turn ran: crewDone waits for the turn's end (no remark mid-turn). */
84let crewDonePending = false
85/** Reviewer rows whose finish has had its crewDone moment (said, or held for the turn's end). */
86let crewDoneSaidFor = new Set<string>()
87/** The crew pane is open (drawn since its open, not closed since): only then does the frame clock run. */
88let paneShown = false
89/** Per surface: when the pane's drawing next changes (clock ms), from its last draw. */
90const frameDue = new Map<string, number>()
91/** The crew's cost as of a crew state: a frame-only redraw reads no usage. */
92let costCache: { sig: string; crewKey: string; cost: number; at: number } | null = null
93/** How long a read of the crew's cost stands (the pill's 1 s cadence). */
94const COST_FRESH_MS = 1000
95/** The crew's 2+ helpers finished with no reviewer: the next prompt carries the reminder. */
96let reviewMissed = false
97/** A prompt is carrying the reminder now: claimed before awaiting, so two prompts at once cannot both. */
98let reminderInFlight = false
99/** The pane's frame clock on a rich surface: at most one frame-driven redraw this often (≤ 4 a second). */
100const FRAME_FLOOR_MS = 250
101/** What `/glitch crew debug` shows: the engine's last list, the last presses, the view each surface drew under. */
102const freshDebug = (): CrewDebugState => ({ list: null, listError: null, presses: [], views: {}, draws: {} })
103let debug: CrewDebugState = freshDebug()
104function recordPress(p: CrewDebugState['presses'][number]) {
105 debug.presses = [p, ...debug.presses].slice(0, 10)
106}
107
108// $.state.get needs a literal plugin and key, so these three cannot be merged.
109async function hudStats($: EngineInterface): Promise<unknown> {
110 try {
111 return (await $.state.get({ plugin: 'glitch-hud', key: 'stats' } as const)).value
112 } catch {
113 return null
114 }
115}
116
117async function hudBudget($: EngineInterface): Promise<unknown> {
118 try {
119 return (await $.state.get({ plugin: 'glitch-hud', key: 'budget' } as const)).value
120 } catch {
121 return null
122 }
123}
124
125async function hudCache($: EngineInterface): Promise<unknown> {
126 try {
127 return (await $.state.get({ plugin: 'glitch-hud', key: 'cache' } as const)).value
128 } catch {
129 return null
130 }
131}
132
133async function hudPoke($: EngineInterface): Promise<unknown> {
134 try {
135 return (await $.state.get({ plugin: 'glitch-hud', key: 'poke' } as const)).value
136 } catch {
137 return null
138 }
139}
140
141// Helpers' statuses from the engine's list. While a row runs, each refresh touches the
142// crew so the pane's clocks move.
143async function refreshCrew($: EngineInterface) {
144 // Nothing runs: no status can change, so no call.
145 if (!(await read($, crew)).rows.some(r => r.status === 'running')) return
146 let list: AgentInfo[] | null = null
147 try {
148 list = await $.agent.list()
149 } catch (err) {
150 debug.listError = err instanceof Error ? err.message : String(err)
151 }
152 const now = await $.clock.now()
153 if (!list) return
154 debug.list = { at: now, entries: list.map(a => ({ id: a.id, status: a.status, description: a.description, ...(a.name ? { name: a.name } : {}) })) }
155 debug.listError = null
156 const got = list
157 if (!(await changeCrew($, now, c => onStatuses(c, got, now)))) {
158 if ((await read($, crew)).rows.some(r => r.status === 'running')) await update($, crew, c => ({ ...c, tickAt: now }))
159 }
160}
161
162/**
163 * One change to the crew's statuses, from whichever source (the list, a helper's own turn end or
164 * wake): the rows, the step-ups, the lead's reaction, the HUD summary at once, and the crewDone
165 * remark once the reviewer finishes and nothing else runs. False when no status changed.
166 */
167async function changeCrew($: EngineInterface, now: number, fn: (c: CrewState) => CrewState): Promise<boolean> {
168 const before = await read($, crew)
169 const sameStatuses = (c: CrewState) => c.rows.length === before.rows.length && c.rows.every((r, i) => r.status === before.rows[i]?.status)
170 if (sameStatuses(fn(before))) return false
171 await update($, crew, fn)
172 const c = await read($, crew)
173 queueStepUps(before.rows, c.rows)
174 // The lead reacts: a member done is a brief joy (its own mini hops in the pane), one failed a worry (behavior/reactions.ts).
175 await update($, mood, m => onCrewChange(m, before, c, now))
176 // The HUD pill follows the pane now, not at the next 1 s tick.
177 await publishSummary($, true).catch(() => undefined)
178 // A reviewer's first finish only: one woken by a message and ending again is not remarked twice.
179 const finishedNow = before.rows.filter(r => r.role === 'reviewer' && r.status === 'running' && c.rows.find(x => x.id === r.id)?.status !== 'running').map(r => r.id)
180 const firstFinish = finishedNow.filter(id => !crewDoneSaidFor.has(id))
181 for (const id of finishedNow) crewDoneSaidFor.add(id)
182 if (crewDoneSaidFor.size > 256) crewDoneSaidFor = new Set(finishedNow)
183 if (!firstFinish.length || helpersRunning(c) > 0 || reviewerRunning(c)) return true
184 if ((await read($, mood)).turnSince !== null) crewDonePending = true
185 else await say($, 'crewDone')
186 return true
187}
188
189// `/glitch crew debug`: the rows against a fresh read of the engine's list, the last presses and views.
190async function answerCrewDebug($: EngineInterface): Promise<string> {
191 const now = await $.clock.now()
192 const c = await read($, crew)
193 let freshList: NonNullable<CrewDebugState['list']>['entries'] | null = null
194 let listError = debug.listError
195 try {
196 freshList = (await $.agent.list()).map(a => ({ id: a.id, status: a.status, description: a.description, ...(a.name ? { name: a.name } : {}) }))
197 } catch (err) {
198 listError = err instanceof Error ? err.message : String(err)
199 }
200 const surfaces = await surfacesOf($)
201 const panes = (await panesOf($)).map(p => p.id)
202 return crewDebugText({ now, crew: c, list: debug.list, listError, freshList, presses: debug.presses, views: debug.views, draws: debug.draws, surfaces, panes })
203}
204
205// Calls an older engine may lack are asked inside try (a missing one throws before any `.catch`):
206// an empty answer stands in for it.
207async function panesOf($: EngineInterface): Promise<readonly { id: string }[]> {
208 try {
209 return await $.ui.panes()
210 } catch {
211 return []
212 }
213}
214async function surfacesOf($: EngineInterface): Promise<readonly string[]> {
215 try {
216 return await $.session.surfaces()
217 } catch {
218 return []
219 }
220}
221async function usdOf($: EngineInterface): Promise<number | null> {
222 try {
223 return (await $.session.usage())?.cost?.usd ?? null
224 } catch {
225 return null
226 }
227}
228// With no surface named (auto-open), a session the desktop or a phone draws gets the
229// narrow dock; a terminal-only one the wide dock.
230async function sessionSize($: EngineInterface): Promise<PaneSize> {
231 const surfaces = await surfacesOf($)
232 return surfaces.some(s => s !== 'terminal') ? PANE_SIZE.rich : PANE_SIZE.terminal
233}
234
235async function toggleCrew($: EngineInterface, size: PaneSize): Promise<string> {
236 const isOpen = (await panesOf($)).some(x => x.id === PANE)
237 if (isOpen) {
238 paneClosed()
239 await $.ui.close({ id: PANE })
240 return 'Crew pane closed.'
241 }
242 await $.ui.open({ id: PANE, title: 'Crew', columns: size.columns, rows: size.rows })
243 return 'Crew pane opened.'
244}
245
246function paneClosed() {
247 paneShown = false
248 frameDue.clear()
249}
250
251/**
252 * A command typed at the terminal (the composer, or any fullscreen one) gets the
253 * terminal's dock, even in a session the desktop draws too; a fullscreen dock leaves
254 * the transcript about half the columns. Any other command sizes as the session.
255 */
256async function commandSize($: EngineInterface, e: { origin?: { kind: string }; presentation?: { isFullscreen?: boolean; columns?: number } }): Promise<PaneSize> {
257 const fullscreen = e.presentation?.isFullscreen === true
258 if (e.origin?.kind === 'composer') {
259 const surfaces = await surfacesOf($)
260 const atTerminal = fullscreen || surfaces.includes('terminal')
261 const cols = e.presentation?.columns
262 if (atTerminal) return fullscreen && typeof cols === 'number' && cols > 0 ? { columns: Math.max(DOCK_COLUMNS.min, Math.min(DOCK_COLUMNS.max, Math.floor(cols / 2))), rows: PANE_SIZE.terminal.rows } : PANE_SIZE.terminal
263 }
264 return await sessionSize($)
265}
266
267// The crew's share of the session cost: one source for the pane and the HUD pill.
268async function crewCostOf($: EngineInterface, c: CrewState): Promise<number> {
269 const usdNow = (await usdOf($)) ?? c.costAtStart
270 return Math.max(0, usdNow - c.costAtStart)
271}
272
273// The figures glitch-hud's crew pill shows, written only when they change. No crew, no reads.
274// `keepCost`: a status change publishes its counts at once, with the cost last read for this same
275// crew (its start and starting cost) and no usage read; with no read of this crew yet (a fresh
276// crew) it is read now, as the pane reads it. The next 1 s tick reads it again for both.
277async function publishSummary($: EngineInterface, keepCost = false) {
278 const c = await read($, crew)
279 const before = await read($, crewSummary)
280 if (c.rows.length === 0 && before === null) return
281 const now = await $.clock.now()
282 let cost = 0
283 if (c.rows.length && keepCost && costCache && costCache.crewKey === crewKeyOf(c)) cost = costCache.cost
284 else if (c.rows.length) cost = await sharedCost($, c, now)
285 const next = crewSummaryOf(c, cost, now)
286 if (JSON.stringify(before) !== JSON.stringify(next)) await update($, crewSummary, () => next)
287}
288
289/**
290 * A finished member's mini while it hops: its crew theme's frame drawn from the pet's happy loop
291 * (the theme's own size, hat or hands kept), so it neither jumps nor loses its look.
292 */
293function happyMini(p: Persona, theme: string, row: CrewState['rows'][number], elapsedMs: number, now: number): Sprite {
294 const happy = p.moods.happy
295 const frame = happy.frames[frameIndex(happy, elapsedMs)] ?? p.moods.idle.frames[0] ?? []
296 const asHappy: Persona = { ...p, moods: { ...p.moods, idle: { frames: [frame], fps: happy.fps } } }
297 const s = crewMini(theme, { persona: asHappy, role: row.role, model: row.model, effort: row.effort, status: row.status, elapsedMs: (row.endedAt ?? now) - row.startedAt }, MINI_PIXEL)
298 return { source: s.source, alt: `${p.name} the ${p.kind}, happy`, width: s.width, height: s.height }
299}
300
301/** Ms until a mood loop shows its next frame. */
302const nextFrameIn = (art: MoodArt, elapsedMs: number): number => {
303 const period = 1000 / art.fps
304 return Math.max(1, Math.ceil(period - (Math.max(0, elapsedMs) % period)))
305}
306
307/**
308 * The crew's cost, one value for the pane and the HUD pill: read again when the crew changed or
309 * the last read is a second old, so a frame-only redraw reads no usage.
310 */
311async function sharedCost($: EngineInterface, c: CrewState, now: number): Promise<number> {
312 const sig = costSigOf(c)
313 if (costCache && costCache.sig === sig && now - costCache.at < COST_FRESH_MS) return costCache.cost
314 const cost = await crewCostOf($, c)
315 costCache = { sig, crewKey: crewKeyOf(c), cost, at: now }
316 return cost
317}
318/** Which crew a cost was read for (its start and its starting cost). */
319const crewKeyOf = (c: CrewState) => JSON.stringify([c.startedAt, c.costAtStart])
320/** The crew state a cost read stands for. */
321const costSigOf = (c: CrewState) => JSON.stringify([c.startedAt, c.costAtStart, c.rows.map(r => [r.id, r.status, r.tokens, r.weight])])
322
323const openKey = (c: CrewState, group: CrewGroup, isTerminal: boolean) => `${c.startedAt ?? 0}:${group}${isTerminal && group === 'finished' ? ':terminal' : ''}`
324// Desktop groups start open; the terminal's finished members start folded.
325const isOpenIn = (o: Record<string, boolean>, c: CrewState, group: CrewGroup, isTerminal: boolean) =>
326 o[openKey(c, group, isTerminal)] ?? !(isTerminal && group === 'finished')
327
328async function say($: EngineInterface, moment: VoiceMoment) {
329 const p = personaFor((await read($, view)).petId)
330 if (!p) return
331 const m = await read($, mood)
332 const picked = pickLine(p, moment, voice, { now: await $.clock.now(), isTurnRunning: m.turnSince !== null, enabled: config.voice, everyMs: config.voiceEveryMs, random: Math.random })
333 if (!picked) return
334 voice = picked.state
335 $.ui.toast(picked.text, { timeoutMs: 6000 })
336}
337
338async function tick($: EngineInterface) {
339 const now = await $.clock.now()
340 // The crew pane needs the statuses with the pet off too.
341 ticks += 1
342 if (ticks % STATUS_TICKS === 0) {
343 await refreshCrew($)
344 await publishSummary($)
345 }
346 // The pane's frame clock: while it is open and a mini (or the lead's flourish) is due to change.
347 if (paneShown && frameDue.size > 0 && now >= Math.min(...frameDue.values())) {
348 frameDue.clear()
349 await update($, paneFrame, () => now)
350 }
351 const p = personaFor((await read($, view)).petId)
352 if (!p) {
353 if (lastSource !== null) {
354 lastSource = null
355 await update($, sprite, () => null)
356 }
357 return
358 }
359 const stats = (await hudStats($)) as { total?: number } | null
360 const b = (await hudBudget($)) as BudgetLike | null
361 const c = (await hudCache($)) as { secondsLeft?: number | null } | null
362 // A click on the pet (glitch-hud draws it and records the press) starts a hop.
363 const pressed = (await hudPoke($)) as { at?: unknown } | null
364 if (typeof pressed?.at === 'number' && pressed.at > (await read($, mood)).pokeSeen) {
365 await update($, mood, x => onPoke(x, pressed.at as number, now))
366 }
367 const team = await read($, crew)
368 const m = await read($, mood)
369 const r = tickOnce({
370 now, persona: p, player, state: m, lastSource, total: stats?.total ?? 0, budget: b, cacheSecondsLeft: c?.secondsLeft ?? null,
371 helpersRunning: helpersRunning(team), reviewerRunning: reviewerRunning(team), tiredMs: config.tiredMs, sleepyMs: config.sleepyMs, crew: team,
372 })
373 if (r.moodChanged) {
374 await update($, mood, x => ({ ...x, mood: r.mood, since: r.since }))
375 // Crew news has no remark here: a member's failure is not the budget's worry.
376 const moment = r.fromCrew ? undefined : SPEAKS_ON_ENTRY[r.mood]
377 if (moment) await say($, moment)
378 }
379 if (r.sprite) {
380 lastSource = r.sprite.source
381 await update($, sprite, () => r.sprite)
382 }
383}
384
385const firstWord = (args: string): string => (args.trim().split(/\s+/)[0] ?? '').toLowerCase()
386
387// `arg` is the pet argument (see petArgsOf): empty lists the pets.
388async function answerPets($: EngineInterface, arg: string): Promise<string> {
389 const word = arg.trim().split(/\s+/)[0]
390 const parsed = parsePetArg(word)
391 if (parsed.kind === 'show') return petList((await read($, view)).petId, available)
392 if (parsed.kind === 'unknown') return `Unknown pet "${parsed.name}". ${petList((await read($, view)).petId, available)}`
393 const petId: PetId | 'off' = parsed.kind === 'off' ? 'off' : parsed.id
394 await $.store.set(STORE_PET, petId).catch(() => undefined)
395 await update($, view, v => ({ ...v, petId }))
396 const p = personaFor(petId)
397 return p ? `Pet: ${p.name} the ${p.kind}.` : 'Pet off.'
398}
399
400// ── Crew tiers (#43): typed crew members, their model enforced, step-up on failure ──
401// The step-up goes to Claude as a one-time note beside the next prompt (the crew
402// review reminder's channel): Claude retries under the next rung's type, so the
403// retry's answer reaches it as its own helper's task notification.
404
405let crewTiers: CrewTiers = parsePetsConfig({}).config.crewTiers
406let ladder: Rung[] = ladderOf(crewTiers)
407/** Failed crew members whose note has not reached the model yet. */
408let stepUpsQueued: StepUp[] = []
409/** Notes sent this main turn: the retry spawn they ask for claims one, linking its row. */
410let stepUpsSent: StepUp[] = []
411/** Notes riding a prompt now (between its submit and its answer): they hold the review too. */
412let stepUpsInFlight: StepUp[] = []
413/** Notes a main turn ended without acting on: still claimable by name, no longer holding the review. */
414let stepUpsStale: StepUp[] = []
415/** Rows already stepped up from (queued, sent or claimed): a resumed row failing again is not stepped twice. */
416let steppedFrom = new Set<string>()
417
418function queueStepUps(before: CrewState['rows'], after: CrewState['rows']) {
419 for (const u of stepUpsFor(before, after, ladder)) {
420 if (steppedFrom.has(u.fromId)) continue
421 steppedFrom.add(u.fromId)
422 stepUpsQueued.push(u)
423 }
424}
425
426/** Failed rows whose retry is still to come: the review reminder waits for them. */
427const heldForStepUp = (): string[] => [...stepUpsQueued, ...stepUpsInFlight, ...stepUpsSent].map(u => u.fromId)
428
429/** A main turn ended: a note Claude read and did not act on stops holding the review (a same-name retry still links). */
430function dropUnclaimedStepUps() {
431 stepUpsStale = [...stepUpsStale, ...stepUpsSent]
432 stepUpsSent = []
433}
434
435/** A main turn that a step-up note rides is the crew's: it is busy, so its end does not close the crew before the review check. */
436const busyForStepUps = (c: CrewState): CrewState => (stepUpsSent.length || stepUpsInFlight.length ? { ...c, turnBusy: true } : c)
437
438type StepList = 'queued' | 'sent' | 'stale'
439const stepList = (l: StepList): StepUp[] => (l === 'queued' ? stepUpsQueued : l === 'sent' ? stepUpsSent : stepUpsStale)
440function setStepList(l: StepList, v: StepUp[]) {
441 if (l === 'queued') stepUpsQueued = v
442 else if (l === 'sent') stepUpsSent = v
443 else stepUpsStale = v
444}
445
446/**
447 * The retry a call or spawn is (read only; tool.call and agent.spawn decide alike): a
448 * pending step-up by name (queued, sent, then stale), else a sent note by type; and
449 * the rung it runs on: the step-up's target when the asked crew type is at or below
450 * the failed rung, else the asked one.
451 */
452function findRetry(type: string, name: string | undefined): { list: StepList; index: number; claimed: StepUp; target: Rung } | null {
453 const asked = rungOfType(ladder, type)
454 if (!asked) return null
455 let found: { list: StepList; index: number } | null = null
456 for (const l of ['queued', 'sent', 'stale'] as const) {
457 const i = name ? stepList(l).findIndex(u => u.name === name) : -1
458 if (i >= 0) {
459 found = { list: l, index: i }
460 break
461 }
462 }
463 if (!found) {
464 const { claimed } = claimStepUp(stepUpsSent, type, name)
465 if (claimed) found = { list: 'sent', index: stepUpsSent.indexOf(claimed) }
466 }
467 if (!found) return null
468 const claimed = stepList(found.list)[found.index] as StepUp
469 const at = (t: string) => ladder.findIndex(r => r.type === t)
470 const target = at(asked.type) <= at(claimed.from) ? (ladder[at(claimed.to)] ?? asked) : asked
471 return { ...found, claimed, target }
472}
473
474type CrewStep = { rung?: string; stepUps?: number; steppedUpFrom?: NonNullable<CrewState['rows'][number]['steppedUpFrom']> }
475
476/**
477 * Before a spawn: a retry of a member with a step-up pending (by name; else a sent
478 * note by type) runs at least one rung up — a crew type at or below the failed rung is
479 * rewritten to the step-up's target — and counts toward the cap. A crew type's model wins.
480 * `restore` puts the claim back when the spawn is refused.
481 */
482function crewSpawnOf<E extends { subagentType: string; model?: string; fork: boolean; workflow?: unknown; name?: string }>(e: E, c: CrewState | null, own: boolean): { e: E; step: CrewStep; restore: () => void } {
483 const none = { e: crewModelOf(e), step: {}, restore: () => undefined }
484 if (!own) return none
485 if (c?.closed) {
486 stepUpsQueued = []
487 stepUpsSent = []
488 stepUpsStale = []
489 steppedFrom = new Set()
490 }
491 const started = !((e as { resume?: unknown }).resume || e.fork || e.workflow)
492 // The crew's reviewer (#45), by its reviewer-<n> name, runs as the lean crew-reviewer whatever type it was asked on.
493 if (started && isReviewerSpawn(e)) {
494 const forced = isReviewerType(e.subagentType) ? e : { ...e, subagentType: `${AGENT_PREFIX}${REVIEWER_TYPE}` }
495 return { e: crewModelOf(forced), step: { rung: REVIEWER_TYPE }, restore: () => undefined }
496 }
497 const asked = started ? rungOfType(ladder, e.subagentType) : null
498 if (!asked) return none
499 const retry = findRetry(e.subagentType, e.name)
500 if (!retry) {
501 // Past the cap (or retried without a note): the name's earlier tries still count.
502 const before = Math.max(0, ...(c?.rows ?? []).filter(r => r.rung && e.name && r.name === e.name).map(r => r.stepUps ?? 0))
503 return { e: crewModelOf(e), step: { rung: asked.type, ...(before ? { stepUps: before } : {}) }, restore: () => undefined }
504 }
505 const { claimed, target } = retry
506 setStepList(retry.list, stepList(retry.list).filter((_, k) => k !== retry.index))
507 const restore = () => setStepList(retry.list, [...stepList(retry.list), claimed])
508 const at = (t: string) => ladder.findIndex(r => r.type === t)
509 const from = ladder[at(claimed.from)]
510 const forced = target.type === asked.type ? e : { ...e, subagentType: `${AGENT_PREFIX}${target.type}` }
511 return {
512 e: crewModelOf(forced),
513 step: { rung: target.type, stepUps: claimed.stepUps, steppedUpFrom: { id: claimed.fromId, rung: claimed.from, model: from?.model ?? '', effort: from?.effort ?? '' } },
514 restore,
515 }
516}
517
518/** A spawn on a crew type (or the reviewer's) runs on the type's model: a different `model` is set back to it. */
519function crewModelOf<E extends { subagentType: string; model?: string; fork: boolean; workflow?: unknown }>(e: E): E {
520 const fresh = !((e as { resume?: unknown }).resume || e.fork || e.workflow)
521 const pinned = !fresh ? null : isReviewerType(e.subagentType) ? crewTiers.reviewer : rungOfType(ladder, e.subagentType)
522 return !pinned || e.model === undefined || e.model === pinned.model ? e : { ...e, model: pinned.model }
523}
524
525/** One agent type per rung (glitch-pets:crew-light, crew-light-high, …) and the lean reviewer: effort can only come from a type. */
526async function registerCrewTypes($: EngineInterface) {
527 const failed: string[] = []
528 for (const spec of [...agentSpecs(ladder), reviewerSpec(crewTiers)]) {
529 try {
530 await $.agent.register(spec)
531 } catch {
532 failed.push(spec.name)
533 }
534 }
535 if (failed.length) $.ui.toast(`Glitch pets: could not register crew agent types: ${failed.join(', ')}`, { timeoutMs: 8000 })
536}
537
538/**
539 * The step-up notes ride the next prompt that reaches the model (a person's, or a
540 * helper's task notification), once: the prompt with them, and a `next` that counts
541 * them sent only if they entered (a hook beneath may rewrite the context).
542 */
543function withStepUps<E extends { origin: { kind: string }; context?: readonly string[] }, N extends (x: E) => Promise<unknown>>(e: E, next: N): { e: E; next: N } {
544 if (stepUpsQueued.length === 0 || e.origin.kind === 'plugin' || (e as { command?: unknown }).command) return { e, next }
545 const ups = stepUpsQueued
546 stepUpsQueued = []
547 stepUpsInFlight = [...stepUpsInFlight, ...ups]
548 const notes = ups.map(u => stepUpNote(u, ladder))
549 const wrapped = (async (x: E) => {
550 let r: { context?: readonly string[]; drop?: unknown }
551 try {
552 r = (await next(x)) as typeof r
553 } catch (err) {
554 stepUpsQueued = [...ups, ...stepUpsQueued]
555 throw err
556 } finally {
557 stepUpsInFlight = stepUpsInFlight.filter(u => !ups.includes(u))
558 }
559 const entered = 'context' in r && r.context !== undefined ? notes.every(n => r.context?.includes(n)) : r.drop === undefined
560 if (entered) stepUpsSent = [...stepUpsSent, ...ups]
561 else stepUpsQueued = [...ups, ...stepUpsQueued]
562 return r
563 }) as unknown as N
564 return { e: { ...e, context: [...(e.context ?? []), ...notes] }, next: wrapped }
565}
566// ── end crew tiers (module part) ──
567
568// ── Crew themes (#41) ─────────────────────────────────────────────────────────────────────
569// The active theme lives in `view.crewTheme`: the saved choice, else the crewTheme setting.
570const themeOrConfig = (saved: unknown): string => (typeof saved === 'string' && Object.hasOwn(CREW_THEMES, saved) ? saved : config.crewTheme)
571
572async function restoreCrewTheme($: EngineInterface) {
573 const crewTheme = themeOrConfig(await $.store.get(STORE_CREW_THEME).catch(() => undefined))
574 await update($, view, v => ({ ...v, crewTheme }))
575}
576
577// `arg` is the theme argument (see crewThemeArgOf): empty lists the themes.
578async function answerCrewTheme($: EngineInterface, arg: string): Promise<string> {
579 const ids = crewThemeIds()
580 const list = async () => themeList(themeOrConfig((await read($, view)).crewTheme), ids.map(id => ({ id, name: CREW_THEMES[id]?.name ?? id })))
581 const parsed = parseThemeArg(arg, ids)
582 if (parsed.kind === 'show') return list()
583 if (parsed.kind === 'unknown') return `Unknown crew theme "${parsed.name}". ${await list()}`
584 await $.store.set(STORE_CREW_THEME, parsed.id).catch(() => undefined)
585 await update($, view, v => ({ ...v, crewTheme: parsed.id }))
586 return `Crew theme: ${CREW_THEMES[parsed.id]?.name ?? parsed.id}.`
587}
588// ── end crew themes ───────────────────────────────────────────────────────────────────────
589
590export const register: Register = (on, options) => {
591 const parsed = parsePetsConfig(options as Record<string, unknown>)
592 const problems = parsed.problems
593 config = parsed.config
594 player = createPlayer()
595 voice = INITIAL_VOICE
596 lastSource = null
597 ticking = false
598 ticks = 0
599 crewDonePending = false
600 crewDoneSaidFor = new Set()
601 reviewMissed = false
602 reminderInFlight = false
603 paneShown = false
604 frameDue.clear()
605 costCache = null
606 debug = freshDebug()
607
608 on('session.start', async ($, e, next) => {
609 const started = await next(e)
610 try {
611 await $.command.register({ name: 'glitch-pets', description: PETS_USAGE })
612 } catch {
613 $.ui.toast('Glitch pets: could not register /glitch-pets', { timeoutMs: 8000 })
614 }
615 await registerCrewTypes($)
616 if (problems.length) $.ui.toast(`Glitch pets: ${problems.join('; ')}`, { timeoutMs: 8000 })
617 if (broken.length) $.ui.toast(`Glitch pets: left out (art problems): ${broken.join(', ')}`, { timeoutMs: 8000 })
618 const saved = await $.store.get(STORE_PET).catch(() => undefined)
619 const petId = saved === 'off' || (PET_IDS as readonly unknown[]).includes(saved) ? (saved as PetId | 'off') : config.pet
620 const now = await $.clock.now()
621 await update($, view, v => ({ ...v, petId }))
622 await restoreCrewTheme($).catch(() => undefined) // crew themes (#41)
623 await update($, mood, m => ({ ...m, since: now, lastPromptAt: m.lastPromptAt || now }))
624 if (!ticking) {
625 ticking = true
626 $.clock.every(TICK_MS, async () => {
627 try {
628 await tick($)
629 } catch {
630 // The next tick draws again.
631 }
632 })
633 }
634 return started
635 })
636
637 on('prompt.submit', async ($, raw, rawNext) => {
638 const { e, next } = withStepUps(raw, rawNext)
639 if (e.origin.kind !== 'plugin') {
640 try {
641 const now = await $.clock.now()
642 await update($, mood, m => ({ ...m, lastPromptAt: now }))
643 } catch {
644 // The pet just misses this one.
645 }
646 }
647 // The missed-review reminder rides the next prompt that reaches the model (not a
648 // plugin's own, not a slash command's), as context the person never sees.
649 if (!reviewMissed || reminderInFlight || !config.crewReview || e.origin.kind === 'plugin' || (e as { command?: unknown }).command) return next(e)
650 // Stale by now (a reviewer joined, the turn was aborted, a new crew): dropped.
651 const now = await read($, crew).catch(() => null)
652 if (!now || !needsReview(now, { enabled: true, stopHookActive: false, capReached: false, held: heldForStepUp() })) {
653 reviewMissed = false
654 return next(e)
655 }
656 if (reminderInFlight) return next(e)
657 reminderInFlight = true
658 let r: Awaited<ReturnType<typeof next>>
659 try {
660 r = await next({ ...e, context: [...(e.context ?? []), GATE_TEXT] })
661 } finally {
662 reminderInFlight = false
663 }
664 // Sent only if it entered: a hook beneath may have rewritten the context.
665 const entered = 'context' in r && r.context !== undefined ? r.context.includes(GATE_TEXT) : r.drop === undefined
666 if (entered) {
667 reviewMissed = false
668 await update($, crew, c => ({ ...c, gateFired: true })).catch(() => undefined)
669 }
670 return r
671 })
672
673 on('turn.start', async ($, e, next) => {
674 if ((e as { agentId?: string }).agentId === undefined) {
675 try {
676 await update($, crew, c => busyForStepUps(onMainTurnStart(c)))
677 const now = await $.clock.now()
678 await update($, mood, m => ({ ...m, turnSince: now }))
679 const r = advance(asStreak(await $.store.get(STORE_STREAK).catch(() => null)), now)
680 if (r.changed) await $.store.set(STORE_STREAK, r.streak).catch(() => undefined)
681 await update($, mood, m => onTurnStartStreak(m, r, now))
682 } catch {
683 // The pet just misses this one.
684 }
685 } else {
686 // A helper's own turn starting: a message woke a finished one, so its row runs again.
687 const agentId = (e as { agentId?: string }).agentId as string
688 try {
689 const now = await $.clock.now()
690 const woke = await changeCrew($, now, c => onAgentWake(c, agentId, now))
691 // At work again: a retry note queued for its failure is no longer wanted.
692 if (woke) stepUpsQueued = stepUpsQueued.filter(u => u.fromId !== agentId)
693 } catch {
694 // The list's poll still sees it.
695 }
696 }
697 return next(e)
698 })
699
700 on('turn.complete', async ($, e, next) => {
701 try {
702 return await next(e)
703 } finally {
704 if (e.agentId === undefined) {
705 // Statuses first, while the turn still counts as running: a reviewer that just
706 // finished holds crewDone for the remark below, which then wins over happy.
707 await refreshCrew($).catch(() => undefined)
708 try {
709 const now = await $.clock.now()
710 await update($, mood, m => onTurnEnd(m, e.reason, now))
711 if (crewDonePending) {
712 crewDonePending = false
713 await say($, 'crewDone')
714 } else if (e.reason === 'answer' && e.durationMs >= LONG_TURN_MS) await say($, 'happy')
715 } catch {
716 // Leave the mood as it was.
717 }
718 // Each main turn's end: is the crew's work unreviewed (the reminder goes out
719 // with the next prompt), then a quiet turn closes the crew.
720 try {
721 // Every main turn's end, before the hud reads: unclaimed notes stop holding the review.
722 dropUnclaimedStepUps()
723 // An interrupted turn is the person's call: no reminder for this crew.
724 if (e.isAborted) await update($, crew, c => ({ ...c, gateFired: true }))
725 else if (config.crewReview) {
726 const stats = (await hudStats($)) as { total?: number } | null
727 const capReached = isCapReached((await hudBudget($)) as BudgetLike | null, stats?.total ?? 0)
728 if (needsReview(await read($, crew), { enabled: true, stopHookActive: false, capReached, held: heldForStepUp() })) reviewMissed = true
729 }
730 await update($, crew, onMainTurnEnd)
731 } catch {
732 // No reminder this time.
733 }
734 } else {
735 const agentId = e.agentId
736 try {
737 const now = await $.clock.now()
738 await update($, crew, c => onAgentTurnEnd(c, agentId, e.usage, now))
739 // The list's word first (it names a failure or a stop exactly); then, one run of a helper's
740 // loop being one turn, a row the list still shows running ends by the turn's reason.
741 await refreshCrew($)
742 await changeCrew($, now, c => onAgentRunEnd(c, agentId, e.reason, now))
743 } catch {
744 // The tick asks for the statuses again.
745 }
746 }
747 }
748 })
749
750 on('tool.call', async ($, e, next) => {
751 const agentId = e.agentId
752 // A helper's row says what it is doing while the call runs: written before the call (a quick
753 // write, and none when the words are the same), so the pane shows it for the call's whole run.
754 if (agentId !== undefined) await update($, crew, c => onToolStart(c, agentId, activityOf(e as never))).catch(() => undefined)
755 const ran = await next(e)
756 if (agentId === undefined) {
757 const now = await $.clock.now().catch(() => 0)
758 await update($, mood, m => onToolResult(m, e, ran, now)).catch(() => undefined)
759 } else {
760 await update($, crew, c => onTool(c, agentId)).catch(() => undefined)
761 }
762 return ran
763 })
764
765 // The standing rule, sent after the cache boundary so it never disturbs the shared prompt.
766 on('prompt.compose', async ($, e, next) => {
767 const composed = await next(e)
768 if (!config.crewReview) return composed
769 return { sections: [...composed.sections, { id: 'glitch-pets:crew', text: CREW_RULE, scope: 'session' as const }] }
770 })
771
772 // A helper joins the open crew, or starts a fresh one; a fresh crew opens the pane (auto).
773 on('agent.spawn', async ($, e, next) => {
774 const pre = crewSpawnOf(e, await read($, crew).catch(() => null), e.parentAgentId === undefined && e.workflow === undefined && next.origin.plugin === 'engine')
775 const r = await next(pre.e)
776 if (r.deny !== undefined || !r.agentId) pre.restore()
777 if (r.deny !== undefined || !r.agentId) return r
778 // Only the main loop's own helpers: not a helper's sub-spawn, a workflow's agent or another plugin's.
779 if (e.parentAgentId !== undefined || e.workflow !== undefined || next.origin.plugin !== 'engine') return r
780 const agentId = r.agentId
781 try {
782 const now = await $.clock.now()
783 const costNow = (await usdOf($)) ?? 0
784 // Decided inside the update, so two spawns at once cannot both start a crew.
785 let fresh = false
786 await update($, crew, c => {
787 fresh = c.closed
788 return onSpawn(c, { agentId, ...(e.name ? { name: e.name } : {}), description: e.description, prompt: e.prompt, type: e.subagentType, model: r.model, now, costNow, ...pre.step })
789 })
790 if (fresh && config.crewPane === 'auto' && !(await panesOf($)).some(x => x.id === PANE)) {
791 const size = await sessionSize($)
792 await $.ui.open({ id: PANE, title: 'Crew', columns: size.columns, rows: size.rows }).catch(() => undefined)
793 }
794 } catch {
795 // The pane misses this helper.
796 }
797 return r
798 })
799
800 // A helper's model and effort, as each of its requests names them.
801 on('turn.step', async function* ($, e, next) {
802 const agentId = e.agentId
803 if (agentId !== undefined) {
804 // An engine before 2.1.302 sends a helper no turn.start: a step of an ended row is its wake
805 // (a no-op for a running one, so the turn.start wake on newer engines stays the only one).
806 try {
807 const now = await $.clock.now()
808 const woke = await changeCrew($, now, c => onAgentWake(c, agentId, now))
809 if (woke) stepUpsQueued = stepUpsQueued.filter(u => u.fromId !== agentId)
810 } catch {
811 // The list's poll still sees it.
812 }
813 const effort = e.effort === undefined ? null : String(e.effort)
814 await update($, crew, c => onStep(c, agentId, e.model, effort)).catch(() => undefined)
815 }
816 const r = yield* next(e)
817 const usage = r?.usage
818 if (agentId !== undefined && usage) await update($, crew, c => onStepUsage(c, agentId, usage)).catch(() => undefined)
819 return r
820 })
821
822 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e, next) => {
823 try {
824 const ui = $.ui.resolve(e)
825 const { Box, Button, Text } = ui
826 // Read so a touch of the frame clock redraws the pane.
827 await read($, paneFrame)
828 paneShown = true
829 const c = await read($, crew)
830 if (c.rows.length === 0) {
831 frameDue.delete(e.surface)
832 return <Text dimColor>No crew yet. Crew members appear here when Claude splits work.</Text>
833 }
834 const now = await $.clock.now()
835 const pv = await read($, view)
836 const p = personaFor(pv.petId)
837 const m = await read($, mood)
838 // One cost with the HUD pill (sharedCost); read the summary so a new figure redraws the pane.
839 await read($, crewSummary)
840 const crewCost = await sharedCost($, c, now)
841 const cost = shares(c.rows, crewCost)
842 const isTerminal = e.surface === 'terminal'
843 const o = await read($, crewOpen)
844 const theme = pv.crewTheme ?? config.crewTheme
845 // When the drawing next changes: a running mini's next beat, a hopping one's next frame or sparkle.
846 const due: number[] = []
847 const rows: CrewMember[] = c.rows.map(row => {
848 let mini = p && !isTerminal ? crewMini(theme, { persona: p, role: row.role, model: row.model, effort: row.effort, status: row.status, elapsedMs: (row.endedAt ?? now) - row.startedAt }, MINI_PIXEL) : null
849 if (row.status === 'running' && mini?.nextChangeMs !== undefined) due.push(now + mini.nextChangeMs)
850 // A member that just finished hops with a sparkle on its own mini (each its own, at once).
851 if (p && mini && isHopping(row, now)) {
852 const since = now - (row.endedAt as number)
853 mini = withSparkle(happyMini(p, theme, row, since, now), p.palette, since, p.hatAnchor)
854 const spark = nextSparkIn(since)
855 due.push(now + Math.min(nextFrameIn(p.moods.happy, since), spark ?? Infinity))
856 }
857 return { row, mini, cost: cost[row.id] ?? 0, steps: stepsOf(row) }
858 })
859 const themeColumns = (CREW_THEMES[theme] ?? CREW_THEMES[DEFAULT_CREW_THEME])?.size.columns ?? 16
860 // An engine that sends no bodyColumns: the size the pane asked for.
861 const bodyColumns = typeof e.props.bodyColumns === 'number' && e.props.bodyColumns > 0 ? e.props.bodyColumns : isTerminal ? PANE_SIZE.terminal.columns : PANE_SIZE.rich.columns
862 const v: CrewView = {
863 lead: { name: p?.name ?? 'Lead', status: leadStatus(p, c, m.reactions, now), sprite: p ? player.sprite(p, m.mood, now - m.since, LEAD_PIXEL) : null },
864 rows,
865 header: { cost: crewCost, tokens: c.rows.reduce((t, r) => t + r.tokens, 0), elapsedMs: elapsedOf(c, now) },
866 isTerminal,
867 now,
868 bodyColumns,
869 open: { running: isOpenIn(o, c, 'running', isTerminal), finished: isOpenIn(o, c, 'finished', isTerminal) },
870 miniColumns: p ? Math.ceil((themeColumns * MINI_PIXEL) / DESKTOP_CELL.width) : 0,
871 }
872 // The lead's flourish (pleased) after a finish, and its hop (happy) after a click, are its mood:
873 // its next frame redraws the pane too.
874 if (p && !isTerminal && (m.mood === 'pleased' || m.mood === 'happy')) due.push(now + nextFrameIn(p.moods[m.mood], now - m.since))
875 // Floored on a rich surface: at most FRAME_FLOOR_MS apart, so a press never races a redraw every
876 // tick (the minis and the hops are computed from the time, so coarser steps stay right).
877 if (due.length) frameDue.set(e.surface, Math.max(Math.min(...due), isTerminal ? 0 : now + FRAME_FLOOR_MS))
878 else frameDue.delete(e.surface)
879 // For /glitch crew debug: the view this surface draws under, and when it drew.
880 const surface = e.surface
881 const viewing = (e.props as { view?: { agentId?: string } }).view?.agentId ?? null
882 debug.views[surface] = viewing
883 debug.draws[surface] = [...(debug.draws[surface] ?? []).filter(t => now - t <= 10_000), now].slice(-200)
884 // A group's open state is kept per crew: a new crew starts from the defaults. A press is never silent:
885 // it is recorded for /glitch crew debug, and a failure is said in a toast.
886 const toggle = async (group: CrewGroup) => {
887 const element = isTerminal ? 'crew-finished' : `crew-acc:${group}`
888 try {
889 const now2 = await read($, crew)
890 const key = openKey(now2, group, isTerminal)
891 const prefix = `${now2.startedAt ?? 0}:`
892 let opened = false
893 await update($, crewOpen, x => {
894 opened = !isOpenIn(x, now2, group, isTerminal)
895 return { ...Object.fromEntries(Object.entries(x).filter(([kk]) => kk.startsWith(prefix))), [key]: opened }
896 })
897 recordPress({ at: await $.clock.now(), surface, element, result: opened ? 'opened' : 'folded' })
898 } catch (err) {
899 const why = err instanceof Error ? err.message : String(err)
900 recordPress({ at: await $.clock.now().catch(() => now), surface, element, result: `failed: ${why}` })
901 $.ui.toast(`Glitch pets: could not fold or open ${group === 'running' ? 'Running' : 'Finished'} (${why})`, { timeoutMs: 6000 })
902 }
903 }
904 return crewTree(v, { Box, Text, Button, Svg: 'Svg' in ui ? ui.Svg : null, Client: 'Client' in ui ? ui.Client : null } as never, { toggle })
905 } catch {
906 return next(e)
907 }
908 })
909
910 // A click on the pane's lead (its blank press target posts it): the same hop as a click on the HUD's pet.
911 on('ui.message', async ($, e, next) => {
912 if (e.element !== LEAD_POKE.key) return next(e)
913 try {
914 const now = await $.clock.now()
915 recordPress({ at: now, surface: e.surface, element: LEAD_POKE.key, result: 'poked' })
916 await update($, mood, x => onPoke(x, now, now))
917 } catch {
918 // No hop this time.
919 }
920 return {}
921 })
922
923 // The pane closed (the person's close mark, our own close, an unload): the frame clock stops.
924 on('ui.close', async ($, e, next) => {
925 if (e.id === PANE) paneClosed()
926 return next(e)
927 })
928
929 // A press on glitch-hud's crew pill (it draws the pill from crewSummary): the pane
930 // opens or closes here, behind the person's press.
931 on('ui.press', { plugin: 'glitch-hud', element: HUD_PILL }, async ($, e, next) => {
932 const r = await next(e)
933 try {
934 const said = await toggleCrew($, e.surface === 'terminal' ? PANE_SIZE.terminal : PANE_SIZE.rich)
935 recordPress({ at: await $.clock.now(), surface: e.surface, element: `glitch-hud:${HUD_PILL}`, result: said })
936 } catch (err) {
937 const why = err instanceof Error ? err.message : String(err)
938 recordPress({ at: await $.clock.now().catch(() => Date.now()), surface: e.surface, element: `glitch-hud:${HUD_PILL}`, result: `failed: ${why}` })
939 $.ui.toast(`Glitch pets: could not open or close the crew pane (${why}). Try /glitch crew.`, { timeoutMs: 8000 })
940 }
941 return r
942 })
943
944 on('command.run', { command: 'glitch-pets' }, async ($, e) => {
945 const themeArg = crewThemeArgOf(e.args) // crew themes (#41)
946 if (themeArg !== null) return { text: await answerCrewTheme($, themeArg) }
947 if (isCrewDebug(e.args)) return { text: await answerCrewDebug($) }
948 return { text: firstWord(e.args) === 'crew' ? await toggleCrew($, await commandSize($, e)) : await answerPets($, petArgsOf('glitch-pets', e.args)) }
949 })
950 on('command.run', { command: 'glitch' }, async ($, e, next) => {
951 const word = firstWord(e.args)
952 if (!ROUTED_PETS.includes(word)) return next(e)
953 const themeArg = crewThemeArgOf(e.args) // crew themes (#41)
954 if (themeArg !== null) return { text: await answerCrewTheme($, themeArg) }
955 if (isCrewDebug(e.args)) return { text: await answerCrewDebug($) }
956 return { text: word === 'crew' ? await toggleCrew($, await commandSize($, e)) : await answerPets($, petArgsOf('glitch', e.args)) }
957 })
958
959 // ── Crew tiers (#43): hooks ──
960 crewTiers = config.crewTiers
961 ladder = ladderOf(crewTiers)
962 stepUpsQueued = []
963 stepUpsSent = []
964 stepUpsInFlight = []
965 stepUpsStale = []
966 steppedFrom = new Set()
967
968 // A crew type's effort wins: an Agent call's own `effort` for a crew type is set to
969 // the type's (session.start registers the types, agent.spawn pins their model, prompt.submit
970 // carries the step-up notes: one hook per event, so those are lines in the hooks above).
971 on('tool.call', { tool: 'Agent' }, async ($, e, next) => {
972 const a = e as typeof e & { subagent_type?: string; effort?: string; name?: string }
973 // The reviewer (its type, or a reviewer-<n> name agent.spawn moves onto it) runs at the reviewer's effort.
974 const reviewer = a.effort !== undefined && (isReviewerName(a.name) || (!!a.subagent_type && isReviewerType(a.subagent_type)))
975 const asked = a.effort !== undefined && a.subagent_type && !reviewer ? rungOfType(ladder, a.subagent_type) : null
976 const rung = reviewer ? crewTiers.reviewer : asked ? (findRetry(a.subagent_type as string, a.name)?.target ?? asked) : null
977 return next(!rung || a.effort === rung.effort ? e : ({ ...a, effort: rung.effort } as typeof e))
978 })
979 // ── end crew tiers (hooks) ──
980}
981hooks/behavior/contract.ts 49 lines1// The rules every persona file must keep. The persona tests run it on each pet,
2// and register.tsx skips a pet that breaks it.
3import type { Frame, Persona } from './types'
4import { GRID, LAPTOP_KEYS, LEAD_SITUATIONS, MOOD_IDS, PET_KEY, VOICE_MOMENTS } from './types'
5
6const HEX = /^#[0-9a-f]{6}$/i
7
8/** `composed`: the persona already went through withLaptop, so it holds the laptop's keys by design. */
9export function personaProblems(p: Persona, opts: { composed?: boolean } = {}): string[] {
10 const out: string[] = []
11 for (const [key, color] of Object.entries(p.palette)) {
12 if (key === '.' || key.length !== 1) out.push(`palette key "${key}" must be one char other than "."`)
13 else if (LAPTOP_KEYS.includes(key)) {
14 if (!opts.composed) out.push(`palette key "${key}" is reserved for the laptop`)
15 } else if (!PET_KEY.test(key)) out.push(`palette key "${key}" is reserved for crew themes (a pet's keys are letters)`)
16 if (!HEX.test(color)) out.push(`palette "${key}" must be #rrggbb, got ${color}`)
17 }
18 const frameProblems = (label: string, frame: Frame) => {
19 if (frame.length !== GRID.height) out.push(`${label} has ${frame.length} rows, not ${GRID.height}`)
20 frame.forEach((row, y) => {
21 if (row.length !== GRID.width) out.push(`${label} row ${y} is ${row.length} wide, not ${GRID.width}`)
22 for (const ch of row) if (ch !== '.' && !(ch in p.palette)) out.push(`${label} row ${y} uses "${ch}", not in the palette`)
23 })
24 }
25 for (const mood of MOOD_IDS) {
26 const art = p.moods[mood]
27 if (!art) {
28 out.push(`mood ${mood} is missing`)
29 continue
30 }
31 if (!(art.fps > 0)) out.push(`${mood} fps must be above 0`)
32 if (art.frames.length === 0) out.push(`${mood} has no frames`)
33 art.frames.forEach((frame, f) => frameProblems(`${mood} frame ${f}`, frame))
34 }
35 for (const [situation, text] of Object.entries(p.leadStatus ?? {})) {
36 if (!(LEAD_SITUATIONS as readonly string[]).includes(situation)) out.push(`leadStatus "${situation}" is not a lead situation`)
37 const ok = (t: unknown) => typeof t === 'string' && !!t.trim()
38 if (!(ok(text) || (Array.isArray(text) && text.length === 2 && text.every(ok)))) out.push(`leadStatus ${situation} must be some text, or a pair for one and for more`)
39 }
40 for (const moment of VOICE_MOMENTS) {
41 const lines = p.voice[moment]
42 if (!lines || lines.length < 3 || lines.length > 5) out.push(`voice ${moment} needs 3 to 5 lines`)
43 }
44 if (!(p.laptopPaw in p.palette)) out.push(`laptopPaw "${p.laptopPaw}" is not in the palette`)
45 const { x, y } = p.hatAnchor
46 if (!(x >= 0 && x < GRID.width && y >= 0 && y < GRID.height)) out.push('hatAnchor must be inside the 16 × 13 grid')
47 return out
48}
49hooks/behavior/crew.ts 308 lines1// The crew: helpers started together, as rows for the pane. Pure.
2// A crew spans main turns (background helpers finish in later turns, the reviewer
3// is spawned after them): it stays open until a quiet main turn ends, one where no
4// helper ran at its start, none was spawned and none runs at its end.
5import { REVIEWER_TYPE } from './tiers'
6import type { Role, Tier } from './types'
7
8export type UsageLike = { input_tokens: number; output_tokens: number; cache_creation_input_tokens: number; cache_read_input_tokens: number }
9
10export type CrewRow = {
11 id: string
12 name?: string
13 /** Spawned under a crew name (`<role>-<n>`): only these count for the review reminder. */
14 named: boolean
15 description: string
16 /** What the pane shows as the task when the description only repeats the role or the name: the prompt's first sentence. */
17 task?: string
18 role: Role
19 tier: Tier
20 model: string | null
21 effort: string | null
22 tokens: number
23 /** Price-shaped token weight (tokenWeight), for sharing the crew's cost. */
24 weight: number
25 /** Tokens and weight its steps reported in its current turn, so the turn's own sum counts them once. */
26 turnTokens: number
27 turnWeight: number
28 tools: number
29 /** The steps the lead planned for it (its prompt's "Expected steps: N"); absent: its tier's default. */
30 planned?: number
31 /** What it is doing now: its latest tool call in words ("Reading pane.tsx"). */
32 doing?: string
33 startedAt: number
34 /** When a resume set it running again: the list grace counts from here, not from the first start. */
35 resumedAt?: number
36 endedAt: number | null
37 status: 'running' | 'done' | 'failed'
38 /** Failed because it was stopped (killed), not by its own error: no step-up. */
39 killed?: true
40 /** The crew agent type it runs as (`crew-light`, `crew-light-high`, …), when it is one. */
41 rung?: string
42 /** How many step-ups led to this row (0 or absent for a first try). */
43 stepUps?: number
44 /** The failed row this one retries, and the rung it failed on (for "stepped up from Haiku · low"). */
45 steppedUpFrom?: { id: string; rung: string; model: string; effort: string }
46}
47
48export type CrewState = {
49 /** No crew is open: the next spawn starts a fresh one. True before any crew. */
50 closed: boolean
51 /** The main turn running now had a helper running at its start, or spawned one. */
52 turnBusy: boolean
53 startedAt: number | null
54 /** Clock ms of the last refresh while a row runs, so the pane's clocks move. */
55 tickAt: number
56 costAtStart: number
57 rows: CrewRow[]
58 /** The missed-review reminder already went out for this crew. */
59 gateFired: boolean
60}
61
62export const INITIAL_CREW: CrewState = { closed: true, turnBusy: false, startedAt: null, tickAt: 0, costAtStart: 0, rows: [], gateFired: false }
63
64const ROLE_NAME = /^(builder|researcher|designer|tester|reviewer)-\d+$/i
65// Stems take any word form (reviews, reviewer, researching, tests, builds…). The reviewer rule stays first.
66const ROLE_WORDS: [Role, RegExp][] = [
67 ['reviewer', /\b(review\w*|audit\w*|check the whole)\b/i],
68 ['researcher', /\b(research\w*|find\w*|investigat\w*|explor\w*|look(s|ed|ing)? up|survey\w*|explain\w*|summar\w*|describ\w*|answer\w*|analy[sz]\w*|compar\w*)\b/i],
69 ['tester', /\b(test\w*|verif\w*|validat\w*|qa)\b/i],
70 ['designer', /\b(design\w*|draw\w*|drew|mock(s|ed|ing)? ?ups?|styl\w*|layouts?)\b/i],
71 ['builder', /\b(build\w*|built|implement\w*|writ\w*|wrote|creat\w*|fix\w*|add(s|ed|ing)?|cod(e|es|ed|ing)|refactor\w*)\b/i],
72]
73
74/** A task put as a question ("how a CPU works", "Why X?"): finding out, so a researcher. */
75const QUESTION = /(^|[:\s])(how|why|what|when|where|which|who)\b|\?\s*$/i
76/** How much of a prompt the role words are read in: its opening says the task. */
77const PROMPT_HEAD = 400
78
79/**
80 * A member's role: its crew name (`builder-1`), else the role words in its description, then in
81 * its prompt's opening, then a question-shaped task or the Explore type (a researcher); else other.
82 */
83export function roleOf(name: string | undefined, description: string, prompt = '', type = ''): Role {
84 const m = name ? ROLE_NAME.exec(name) : null
85 if (m) return (m[1] as string).toLowerCase() as Role
86 for (const text of [description, prompt.slice(0, PROMPT_HEAD)]) for (const [role, re] of ROLE_WORDS) if (re.test(text)) return role
87 if (QUESTION.test(description) || /^explore$/i.test(type)) return 'researcher'
88 return 'other'
89}
90
91const ROLE_WORD = /^(builder|researcher|designer|tester|reviewer)$/
92const squash = (t: string): string => t.toLowerCase().replace(/[^a-z0-9]/g, '')
93
94/** True when a description says no more than the role or the name ("researcher" for researcher-1). */
95export function repeatsName(description: string, name: string | undefined, role: Role): boolean {
96 const d = squash(description)
97 if (!d || d === role || ROLE_WORD.test(d)) return true
98 return !!name && (d === squash(name) || d === squash(name.replace(/-\d+$/, '')))
99}
100
101/** `text` in about `n` characters: cut at a word in its second half when there is one, with an ellipsis. */
102export function shortOf(text: string, n: number): string {
103 const t = text.trim().replace(/\s+/g, ' ')
104 if (t.length <= n) return t
105 const cut = t.slice(0, n)
106 const space = cut.lastIndexOf(' ')
107 return `${(space >= n / 2 ? cut.slice(0, space) : cut.slice(0, n - 1)).trimEnd()}…`
108}
109
110/** A sentence's end: `.`, `!` or `?` and a space, never the dot of "e.g." or "i.e.". */
111const SENTENCE_END = /(?<=[.!?])(?<!\b(?:e\.g|i\.e)\.)\s+/i
112
113/**
114 * A prompt as a task line: its first sentence that says the task, about 80 characters at most. A
115 * "You are…" opener and one that only repeats the name or a role word are skipped (kept if nothing else).
116 */
117export function taskOfPrompt(prompt: string, name?: string): string {
118 const sentences = prompt.split('\n').map(l => l.trim()).filter(l => l.length > 0).flatMap(l => l.split(SENTENCE_END)).map(t => t.trim()).filter(Boolean)
119 const says = (t: string) => !/^you are\b/i.test(t) && !repeatsName(t, name, 'other')
120 return shortOf(sentences.find(says) ?? sentences[0] ?? '', 80)
121}
122
123/** A member's name, shown once: its crew name, else its role word, else a short form of its task. */
124export const memberName = (r: Pick<CrewRow, 'name' | 'role' | 'description' | 'task'>): string =>
125 r.name ?? (r.role !== 'other' ? r.role : shortOf(memberTask(r), 24))
126
127/** A member's task line: its description, or the prompt's first sentence when the description only repeats the role or name. */
128export const memberTask = (r: Pick<CrewRow, 'description' | 'task'>): string => r.task || r.description
129
130export function tierOf(model: string | null, effort: string | null): Tier {
131 const mdl = (model ?? '').toLowerCase()
132 const eff = (effort ?? '').toLowerCase()
133 if (mdl.includes('haiku') || eff === 'low') return 'light'
134 if (mdl.includes('opus') && ['high', 'xhigh', 'max'].includes(eff)) return 'heavy'
135 return 'medium'
136}
137
138export const tokenWeight = (u: UsageLike): number =>
139 u.input_tokens + 5 * u.output_tokens + 1.25 * u.cache_creation_input_tokens + 0.1 * u.cache_read_input_tokens
140
141const mapRow = (s: CrewState, id: string, fn: (r: CrewRow) => CrewRow): CrewState => ({ ...s, rows: s.rows.map(r => (r.id === id ? fn(r) : r)) })
142
143const anyRunning = (s: CrewState): boolean => s.rows.some(r => r.status === 'running')
144
145/** A main turn starts: it is busy when a helper of the crew is still running. */
146export const onMainTurnStart = (s: CrewState): CrewState => ({ ...s, turnBusy: anyRunning(s) })
147
148/** A main turn ends: a quiet one (not busy, nothing running) closes the crew. */
149export const onMainTurnEnd = (s: CrewState): CrewState => ({ ...s, closed: s.closed || (!s.turnBusy && !anyRunning(s)), turnBusy: false })
150
151const usageTokens = (u: UsageLike): number => u.input_tokens + u.output_tokens + u.cache_creation_input_tokens + u.cache_read_input_tokens
152
153/** A spawn: a new row, or, for an agent already in the crew (a resume), its row running again with its counts kept. */
154export function onSpawn(s: CrewState, a: { agentId: string; name?: string; description: string; prompt?: string; type?: string; model: string | null; now: number; costNow: number; rung?: string; stepUps?: number; steppedUpFrom?: CrewRow['steppedUpFrom'] }): CrewState {
155 if (s.rows.some(r => r.id === a.agentId)) {
156 return { ...mapRow(s, a.agentId, ({ doing: _d, ...r }) => ({ ...r, status: 'running', resumedAt: a.now, endedAt: null, turnTokens: 0, turnWeight: 0 })), closed: false, turnBusy: true }
157 }
158 const base: CrewState = s.closed ? { ...INITIAL_CREW, closed: false, startedAt: a.now, tickAt: a.now, costAtStart: a.costNow } : s
159 // A row on the lean reviewer's type is the reviewer, whatever its name or description.
160 const role: Role = a.rung === REVIEWER_TYPE ? 'reviewer' : roleOf(a.name, a.description, a.prompt, a.type)
161 const task = repeatsName(a.description, a.name, role) && a.prompt ? taskOfPrompt(a.prompt, a.name) : ''
162 const planned = a.prompt ? plannedOf(a.prompt) : null
163 const row: CrewRow = {
164 id: a.agentId, ...(a.name ? { name: a.name } : {}), named: !!a.name && ROLE_NAME.test(a.name), description: a.description,
165 ...(task ? { task } : {}),
166 ...(planned ? { planned } : {}),
167 role,
168 tier: tierOf(a.model, null), model: a.model, effort: null, tokens: 0, weight: 0, turnTokens: 0, turnWeight: 0, tools: 0, startedAt: a.now, endedAt: null, status: 'running',
169 ...(a.rung ? { rung: a.rung } : {}), ...(a.stepUps ? { stepUps: a.stepUps } : {}), ...(a.steppedUpFrom ? { steppedUpFrom: a.steppedUpFrom } : {}),
170 }
171 return { ...base, turnBusy: true, rows: [...base.rows.filter(r => r.id !== a.agentId), row] }
172}
173
174export const onStep = (s: CrewState, agentId: string, model: string, effort: string | null): CrewState =>
175 mapRow(s, agentId, r => ({ ...r, model, effort, tier: tierOf(model, effort) }))
176
177/** A tool call starts: the row says what it is doing. */
178export const onToolStart = (s: CrewState, agentId: string, doing: string): CrewState =>
179 s.rows.some(r => r.id === agentId && r.doing !== doing) ? mapRow(s, agentId, r => ({ ...r, doing })) : s
180
181/** A tool call ended: one more step. */
182export const onTool = (s: CrewState, agentId: string): CrewState => mapRow(s, agentId, r => ({ ...r, tools: r.tools + 1 }))
183
184/** One step's usage (per request), counted as it comes so a running row shows its tokens. */
185export const onStepUsage = (s: CrewState, agentId: string, u: UsageLike): CrewState =>
186 mapRow(s, agentId, r => {
187 const t = usageTokens(u)
188 const w = tokenWeight(u)
189 return { ...r, tokens: r.tokens + t, weight: r.weight + w, turnTokens: r.turnTokens + t, turnWeight: r.turnWeight + w }
190 })
191
192/** The agent's turn ends: its usage (the sum of the turn's requests) adds only what its steps did not report. */
193export const onAgentTurnEnd = (s: CrewState, agentId: string, u: UsageLike | undefined, now: number): CrewState =>
194 mapRow(s, agentId, r => ({
195 ...r,
196 tokens: r.tokens + (u ? Math.max(0, usageTokens(u) - r.turnTokens) : 0),
197 weight: r.weight + (u ? Math.max(0, tokenWeight(u) - r.turnWeight) : 0),
198 turnTokens: 0,
199 turnWeight: 0,
200 endedAt: r.status === 'running' ? r.endedAt : r.endedAt ?? now,
201 }))
202
203/**
204 * A helper's run ended (its own `turn.complete`: one run of a subagent's loop is one turn):
205 * its row ends at once by the turn's reason, without waiting for the list to catch up.
206 * An answer is done; an API error or a refusal failed; an interrupt stopped (killed).
207 */
208export const onAgentRunEnd = (s: CrewState, agentId: string, reason: string, now: number): CrewState =>
209 mapRow(s, agentId, r => {
210 if (r.status !== 'running') return r
211 if (reason === 'answer') return { ...r, status: 'done', endedAt: now }
212 if (reason === 'aborted') return { ...r, status: 'failed', killed: true, endedAt: now }
213 return { ...r, status: 'failed', endedAt: now }
214 })
215
216/** A message woke a finished helper (its own `turn.start`): its row runs again, its counts kept. */
217export function onAgentWake(s: CrewState, agentId: string, now: number): CrewState {
218 const row = s.rows.find(r => r.id === agentId)
219 if (!row || row.status === 'running') return s
220 const { killed: _k, doing: _d, ...rest } = row
221 return { ...mapRow(s, agentId, () => ({ ...rest, status: 'running', resumedAt: now, endedAt: null, turnTokens: 0, turnWeight: 0 })), closed: false }
222}
223
224/** A row missing from the agent list this long after its spawn has ended (the list drops a finished task soon). */
225export const LIST_GRACE_MS = 3000
226
227/** Rows from a successful `agent.list` (never call it with a failed call's empty stand-in). */
228export function onStatuses(s: CrewState, list: readonly { id: string; status: string }[], now: number): CrewState {
229 const by = new Map(list.map(a => [a.id, a.status]))
230 return {
231 ...s,
232 rows: s.rows.map(r => {
233 if (r.status !== 'running') return r
234 const st = by.get(r.id)
235 // A teammate waiting for a message has done its part.
236 if (st === 'completed' || st === 'idle') return { ...r, status: 'done', endedAt: now }
237 if (st === undefined && now - (r.resumedAt ?? r.startedAt) >= LIST_GRACE_MS) return { ...r, status: 'done', endedAt: now }
238 if (st === 'failed') return { ...r, status: 'failed', endedAt: now }
239 if (st === 'killed') return { ...r, status: 'failed', killed: true, endedAt: now }
240 return r
241 }),
242 }
243}
244
245export function shares(rows: readonly CrewRow[], crewCost: number): Record<string, number> {
246 const total = rows.reduce((t, r) => t + r.weight, 0)
247 const round = (n: number) => Math.round(n * 1e6) / 1e6
248 return Object.fromEntries(rows.map(r => [r.id, round(total > 0 ? (crewCost * r.weight) / total : crewCost / Math.max(1, rows.length))]))
249}
250
251/** The crew's elapsed time: up to now while a row runs, else up to the last row's end. */
252export function elapsedOf(s: CrewState, now: number): number {
253 if (s.startedAt === null) return 0
254 const end = anyRunning(s) ? now : Math.max(s.startedAt, ...s.rows.map(r => r.endedAt ?? s.startedAt as number))
255 return Math.max(0, end - s.startedAt)
256}
257
258export const helpersRunning = (s: CrewState): number => s.rows.filter(r => r.status === 'running' && r.role !== 'reviewer').length
259export const reviewerRunning = (s: CrewState): boolean => s.rows.some(r => r.status === 'running' && r.role === 'reviewer')
260
261/** A member's planned steps when its prompt names none: by tier, the reviewer its own. */
262export const DEFAULT_STEPS: Record<Tier | 'reviewer', number> = { light: 6, medium: 12, heavy: 20, reviewer: 10 }
263
264/** The lead's estimate in a prompt: a line "Expected steps: N" (1 to 999). */
265const PLANNED = /\bexpected steps:\s*(\d{1,3})\b/i
266export function plannedOf(prompt: string): number | null {
267 const n = Number(PLANNED.exec(prompt)?.[1] ?? 0)
268 return n > 0 ? n : null
269}
270
271const plannedFor = (r: CrewRow): number => r.planned ?? DEFAULT_STEPS[r.role === 'reviewer' ? 'reviewer' : r.tier]
272
273/**
274 * A running row's steps (tool calls) against its plan; past the plan the total stays one
275 * above the count, so a running pill never reads full. Null once it has ended.
276 */
277export function stepsOf(row: CrewRow): { n: number; of: number } | null {
278 if (row.status !== 'running') return null
279 return { n: row.tools, of: Math.max(plannedFor(row), row.tools + 1) }
280}
281
282/** The whole crew's steps: each running row against its plan, each ended row as its own count (all done). */
283export function crewSteps(rows: readonly CrewRow[]): { n: number; of: number } {
284 let n = 0
285 let of = 0
286 for (const r of rows) {
287 const st = stepsOf(r)
288 n += st ? st.n : r.tools
289 of += st ? st.of : r.tools
290 }
291 return { n, of }
292}
293
294/** What glitch-hud's crew pill shows (state key `glitch-pets.crewSummary`). */
295export type CrewSummary = { running: number; done: number; failed: number; cost: number; elapsedMs: number }
296
297/** A closed crew keeps its pill this long after its last member ended. */
298export const RECENT_MS = 120_000
299
300/** The pill's figures while a crew is open, or closed less than RECENT_MS ago; else null. */
301export function crewSummaryOf(s: CrewState, cost: number, now: number): CrewSummary | null {
302 if (s.rows.length === 0) return null
303 const lastEnd = Math.max(0, ...s.rows.map(r => r.endedAt ?? now))
304 if (s.closed && !anyRunning(s) && now - lastEnd >= RECENT_MS) return null
305 const count = (st: CrewRow['status']) => s.rows.filter(r => r.status === st).length
306 return { running: count('running'), done: count('done'), failed: count('failed'), cost: Math.round(Math.max(0, cost) * 1e4) / 1e4, elapsedMs: elapsedOf(s, now) }
307}
308hooks/behavior/gate.ts 19 lines1// The crew rule's backstop: multi-part work left unreviewed gets a reminder with the next prompt. Pure.
2import type { CrewState } from './crew'
3
4export const GATE_TEXT =
5 'Glitch crew: 2 or more helpers have finished and no reviewer has checked the whole result. Before going on, start reviewer-1 with subagent_type glitch-pets:crew-reviewer and no model or effort; give it the plan, each helper\'s report and the changed paths, and tell it to verify, not redo: check the deliverables and the diff, run the existing checks, spot-check a few items, never recompute the work. Send each finding back to the helper that did that part; a second review checks only what changed (at most 2 rounds); then report what is still open.'
6
7export const CREW_RULE =
8 'Glitch crew rule: whenever you split work across 2 or more helper agents, first write a short plan (each task with a role, a tier and its expected number of tool calls), end every helper prompt with a line "Expected steps: N", name helpers <role>-<n> (builder, researcher, designer, tester), start each with subagent_type glitch-pets:crew-<tier> (crew-light, crew-medium or crew-heavy) and no model or effort, and after they finish start one reviewer, reviewer-1, with subagent_type glitch-pets:crew-reviewer and no model or effort: give it the plan, each report and the changed paths, and tell it to verify, not redo (check the deliverables and the diff, run the existing checks, spot-check a few items, never recompute the work). Send findings back to the helper responsible; a second review checks only what changed, at most 2 rounds; report anything still open plainly.'
9
10export function needsReview(s: CrewState, o: { enabled: boolean; stopHookActive: boolean; capReached: boolean; held?: readonly string[] }): boolean {
11 if (!o.enabled || o.stopHookActive || o.capReached || s.gateFired || s.closed) return false
12 if (s.rows.some(r => r.role === 'reviewer')) return false
13 // Only crew-named helpers (<role>-<n>, as the crew rule asks) count: an ad-hoc fan-out is not a crew.
14 const helpers = s.rows.filter(r => r.role !== 'reviewer' && r.named)
15 // A failed helper whose step-up retry is still to come (held) is not finished yet.
16 const finished = helpers.filter(r => r.status !== 'running' && !o.held?.includes(r.id))
17 return helpers.length >= 2 && finished.length === helpers.length
18}
19hooks/behavior/lead-status.ts 64 lines1// What the lead row says: one short clause about what the lead is doing. Pure.
2// The situations follow the lead's mood order (moods.ts), so the words and the picture agree:
3// a fresh failure, a fresh finish, the reviewer at work, looking into a failure, then the crew at work or back.
4import type { CrewRow, CrewState } from './crew'
5import type { Reactions } from './reactions'
6import { crewName, isInvestigating, reactionAt } from './reactions'
7import type { LeadSituation, LeadWording, Persona } from './types'
8
9/** The wording any pet uses unless its persona has its own. */
10export const NEUTRAL_STATUS: Readonly<Record<LeadSituation, LeadWording>> = {
11 worry: '{who} hit a snag',
12 joy: ['{who} is done', '{who} are done'],
13 reviewing: 'checking the work',
14 investigating: 'looking into {who}',
15 many: 'keeping an eye on the crew ({n} at work)',
16 one: 'waiting on {who}',
17 allDone: 'job done, the whole crew is back',
18 someFailed: ['{d} done, {f} needs a look', '{d} done, {f} need a look'],
19}
20
21export type LeadSituationNow = { situation: LeadSituation; who: string; n: number; d: number; f: number } | null
22
23/** One name, two joined with "and", more as a count. */
24export const whoOf = (names: readonly string[]): string =>
25 names.length <= 1 ? (names[0] ?? 'the crew') : names.length === 2 ? `${names[0]} and ${names[1]}` : `${names.length} of the crew`
26
27const isHelper = (r: CrewRow) => r.role !== 'reviewer'
28
29/** Which situation the lead is in at `now`, with what fills the wording; null with no crew at all. */
30export function leadSituation(crew: CrewState, reactions: Reactions | undefined, now: number): LeadSituationNow {
31 const running = crew.rows.filter(r => r.status === 'running')
32 const helpers = running.filter(isHelper)
33 const d = crew.rows.filter(r => r.status === 'done').length
34 const f = crew.rows.filter(r => r.status === 'failed').length
35 const at = (situation: LeadSituation, who = '', n = helpers.length) => ({ situation, who, n, d, f })
36 const r = reactionAt(reactions, now)
37 if (r?.kind === 'worry') return at('worry', whoOf(r.who), r.who.length)
38 if (r?.kind === 'joy') return at('joy', whoOf(r.who), r.who.length)
39 if (running.some(x => !isHelper(x))) return at('reviewing')
40 if (isInvestigating(reactions, crew, now)) return at('investigating', reactions?.failWho ?? 'the crew')
41 if (helpers.length >= 2) return at('many')
42 if (helpers.length === 1) return at('one', crewName(helpers[0]!))
43 if (crew.rows.length === 0) return null
44 return f === 0 ? at('allDone', '', crew.rows.length) : at('someFailed', '', crew.rows.length)
45}
46
47/** The wording for one situation with its blanks filled, in number: a pair picks by the situation's count. */
48export function statusText(persona: Pick<Persona, 'leadStatus'> | null, situation: LeadSituation, s: { who: string; n: number; d: number; f: number }): string {
49 const w = persona?.leadStatus?.[situation] ?? NEUTRAL_STATUS[situation]
50 const count = situation === 'someFailed' ? s.f : s.n
51 const t = typeof w === 'string' ? w : w[count === 1 ? 0 : 1]
52 return t.replaceAll('{who}', s.who).replaceAll('{n}', String(s.n)).replaceAll('{d}', String(s.d)).replaceAll('{f}', String(s.f))
53}
54
55/** The lead row's status clause ("waiting on builder-1"), in the pet's own voice where it has one. */
56export function leadStatus(persona: Pick<Persona, 'leadStatus'> | null, crew: CrewState, reactions: Reactions | undefined, now: number): string {
57 const s = leadSituation(crew, reactions, now)
58 return s ? statusText(persona, s.situation, s) : 'ready for a crew'
59}
60
61/** The whole lead row: "Fork · waiting on builder-1". */
62export const leadLine = (persona: Pick<Persona, 'leadStatus' | 'name'>, crew: CrewState, reactions: Reactions | undefined, now: number): string =>
63 `${persona.name} · ${leadStatus(persona, crew, reactions, now)}`
64hooks/behavior/moods.ts 75 lines1// Plain inputs → the one mood to show. Pure: timed moods are "until" timestamps.
2import type { MoodId } from './types'
3
4export const OOPS_MS = 4000
5export const HAPPY_MS = 5000
6export const CHEER_MS = 6000
7export const CRY_MS = 6000
8/** The hop a click on the pet plays. */
9export const POKE_MS = 2000
10/** Failures in a row (main loop) that make the pet cry. */
11export const CRY_FAILS = 3
12export const WORRY_CACHE_S = 60
13const WORRY_BUDGET = 0.9
14
15/** The fields of glitch-hud's Budget this plugin reads. */
16export type BudgetLike = { sessionCap: number; dailyCap: number; isOff: boolean; dailySpent: number; demoPercent: number | null }
17
18export type MoodInputs = {
19 now: number
20 turnSince: number | null
21 lastPromptAt: number
22 oopsUntil: number
23 happyUntil: number
24 cheerUntil: number
25 cryUntil: number
26 pokedUntil: number
27 capReached: boolean
28 /** Spend as a fraction of the nearest cap (budgetFraction), null with no caps. */
29 budget: number | null
30 /** glitch-hud's countdown; null before the first answer. */
31 cacheSecondsLeft: number | null
32 helpersRunning: number
33 reviewerRunning: boolean
34 tiredMs: number
35 sleepyMs: number
36 /** A crew member just finished: `pleased` until then (reactionMoodInputs). */
37 crewJoyUntil?: number
38 /** A crew member just failed: `worried` until then. */
39 crewWorryUntil?: number
40 /** After a failure, `investigating` until then while helpers still run. */
41 investigateUntil?: number
42}
43
44export function budgetFraction(b: BudgetLike | null, sessionTotal: number): number | null {
45 if (!b) return null
46 if (b.demoPercent !== null) return b.demoPercent / 100
47 if (b.isOff) return null
48 const parts = [b.sessionCap > 0 ? sessionTotal / b.sessionCap : null, b.dailyCap > 0 ? b.dailySpent / b.dailyCap : null].filter((x): x is number => x !== null)
49 return parts.length ? Math.round(Math.max(...parts) * 1000) / 1000 : null
50}
51
52export const isCapReached = (b: BudgetLike | null, sessionTotal: number): boolean =>
53 !!b && !b.isOff && ((b.sessionCap > 0 && sessionTotal >= b.sessionCap) || (b.dailyCap > 0 && b.dailySpent >= b.dailyCap))
54
55export function moodOf(i: MoodInputs): MoodId {
56 const running = i.turnSince !== null
57 // A click always answers at once, whatever the pet was doing; it goes back after.
58 if (i.pokedUntil > i.now) return 'happy'
59 if (i.cryUntil > i.now || i.capReached) return 'crying'
60 if (i.oopsUntil > i.now) return 'oops'
61 if ((i.budget !== null && i.budget >= WORRY_BUDGET) || (i.cacheSecondsLeft !== null && i.cacheSecondsLeft > 0 && i.cacheSecondsLeft < WORRY_CACHE_S)) return 'worried'
62 if (i.cheerUntil > i.now) return 'cheering'
63 // Crew news (behavior/reactions.ts) ranks under the session's own trouble and over the steady crew moods.
64 if ((i.crewWorryUntil ?? 0) > i.now) return 'worried'
65 if ((i.crewJoyUntil ?? 0) > i.now) return 'pleased'
66 if (i.reviewerRunning) return 'reviewing'
67 if (i.helpersRunning > 0 && (i.investigateUntil ?? 0) > i.now) return 'investigating'
68 if (i.helpersRunning > 0) return 'leading'
69 if (i.happyUntil > i.now) return 'happy'
70 if (running && i.now - (i.turnSince as number) >= i.tiredMs) return 'tired'
71 if (running) return 'working'
72 if (i.now - i.lastPromptAt >= i.sleepyMs || i.cacheSecondsLeft === 0) return 'sleepy'
73 return 'idle'
74}
75hooks/behavior/player.ts 48 lines1// Frames to images. Pure, and gallery-safe: only type imports, so Node can load it.
2import type { Frame, MoodArt, MoodId, Persona, Sprite } from './types'
3
4/** CSS px per sprite pixel in the band: a 16 × 13 pet draws 24 × 20, about the HUD row's height. */
5export const PIXEL = 1.5
6const W = 16
7
8export const frameIndex = (art: MoodArt, elapsedMs: number): number =>
9 Math.floor((Math.max(0, elapsedMs) * art.fps) / 1000) % art.frames.length
10
11/** One frame as an SVG document: one rect per run of a color within a row. As wide as its rows (16 for a pet; a crew mini may be wider). */
12export function frameSvg(palette: Readonly<Record<string, string>>, frame: Frame, pixel: number): string {
13 let rects = ''
14 frame.forEach((row, y) => {
15 let x = 0
16 while (x < row.length) {
17 const ch = row[x] as string
18 let end = x + 1
19 while (end < row.length && row[end] === ch) end++
20 const color = palette[ch]
21 if (ch !== '.' && color) rects += `<rect x="${x}" y="${y}" width="${end - x}" height="1" fill="${color}"/>`
22 x = end
23 }
24 })
25 const h = frame.length
26 const w = frame[0]?.length ?? W
27 return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${w} ${h}" width="${Math.round(w * pixel)}" height="${Math.round(h * pixel)}" shape-rendering="crispEdges">${rects}</svg>`
28}
29
30/** Builds each (pet, mood, frame, size) image once; a tick only picks which. */
31export function createPlayer(): { sprite(p: Persona, mood: MoodId, elapsedMs: number, pixel?: number): Sprite } {
32 const cache = new Map<string, Sprite>()
33 return {
34 sprite(p, mood, elapsedMs, pixel = PIXEL) {
35 const art = p.moods[mood]
36 const i = frameIndex(art, elapsedMs)
37 const key = `${p.id}|${mood}|${i}|${pixel}`
38 let s = cache.get(key)
39 if (!s) {
40 const frame = art.frames[i] as Frame
41 s = { source: frameSvg(p.palette, frame, pixel), alt: `${p.name} the ${p.kind}, ${mood}`, width: Math.round(W * pixel), height: Math.round(frame.length * pixel) }
42 cache.set(key, s)
43 }
44 return s
45 },
46 }
47}
48hooks/behavior/activity.ts 56 lines1// What a crew member is doing, in words, from the tool call it is making. Pure.
2import { shortOf } from './crew'
3
4type Call = { tool: string } & Record<string, unknown>
5
6const str = (v: unknown): string => (typeof v === 'string' ? v.trim().replace(/\s+/g, ' ') : '')
7/** A path's last part: "pane.tsx" for "C:\\x\\hooks\\pane.tsx". */
8const base = (p: string): string => p.split(/[\\/]/).filter(Boolean).pop() ?? p
9const quoted = (t: string): string => `“${shortOf(t, 48)}”`
10const hostOf = (url: string): string => {
11 try {
12 return new URL(url).host || url
13 } catch {
14 return url
15 }
16}
17
18/** "Reading pane.tsx", "Searching the web: “…”", "Running: npm test"; a tool it does not know by its name. */
19export function activityOf(call: Call): string {
20 const t = call.tool
21 const path = str(call.file_path) || str(call.notebook_path) || str(call.path)
22 switch (t) {
23 case 'Read':
24 return path ? `Reading ${base(path)}` : 'Reading a file'
25 case 'Edit':
26 case 'MultiEdit':
27 case 'NotebookEdit':
28 return path ? `Editing ${base(path)}` : 'Editing a file'
29 case 'Write':
30 return path ? `Writing ${base(path)}` : 'Writing a file'
31 case 'Grep':
32 return str(call.pattern) ? `Searching the code: ${quoted(str(call.pattern))}` : 'Searching the code'
33 case 'Glob':
34 return str(call.pattern) ? `Finding files: ${shortOf(str(call.pattern), 48)}` : 'Finding files'
35 case 'Bash':
36 case 'PowerShell': {
37 const said = str(call.description) || str(call.command)
38 return said ? `Running: ${shortOf(said, 60)}` : 'Running a command'
39 }
40 case 'WebSearch':
41 return str(call.query) ? `Searching the web: ${quoted(str(call.query))}` : 'Searching the web'
42 case 'WebFetch':
43 return str(call.url) ? `Reading ${hostOf(str(call.url))}` : 'Reading a web page'
44 case 'Agent':
45 case 'Task':
46 return 'Starting a helper'
47 case 'TodoWrite':
48 return 'Updating its to-do list'
49 case 'Skill':
50 return str(call.skill) ? `Using the ${str(call.skill)} skill` : 'Using a skill'
51 }
52 const mcp = /^mcp__(.+?)__(.+)$/.exec(t)
53 if (mcp) return `Using ${mcp[1]}: ${(mcp[2] as string).replace(/_/g, ' ')}`
54 return `Using ${t}`
55}
56hooks/behavior/sparkle.ts 61 lines1// A crew member's finish (desktop): its own mini does a short happy hop with a small sparkle
2// by its head, for HOP_MS. Each member that finishes gets its own, so several finishing
3// together each hop at once. Pure: the sparkle is laid into the mini's own image (same box,
4// same size), so nothing around it moves.
5import { GRID } from './types'
6import type { Frame, Sprite } from './types'
7
8/** How long a finished member hops (from its row's end). */
9export const HOP_MS = 1500
10/** The sparkle changes this often: the pane's frame clock floor, so each step is drawn. */
11export const SPARK_STEP_MS = 250
12
13/** The sparkle as it twinkles: small, large, then the burst. Palette keys every pet has (Y, C). */
14export const SPARKS: readonly Frame[] = [
15 ['.Y.', 'YCY', '.Y.'],
16 ['..Y..', '..Y..', 'YYCYY', '..Y..', '..Y..'],
17 ['Y...Y', '.....', '..Y..', '.....', 'Y...Y'],
18]
19
20/** Where the sparkle centers, in sprite pixels: by the pet's head, at the right of its 16 columns. */
21const SPARK_AT = { x: 14, y: 2 } as const
22const FALLBACK = { Y: '#f5c542', C: '#fff6c8' } as const
23
24/** True while a row that finished `endedAt` (clock ms) is still hopping at `now`. */
25export const isHopping = (r: { status: string; endedAt: number | null }, now: number): boolean =>
26 r.status === 'done' && r.endedAt !== null && now >= r.endedAt && now - r.endedAt < HOP_MS
27
28/** Ms until the hop's sparkle next changes, `t` ms into the hop (null once it is over). */
29export const nextSparkIn = (t: number): number | null => (t >= HOP_MS ? null : Math.min(HOP_MS - t, SPARK_STEP_MS - (Math.max(0, t) % SPARK_STEP_MS)))
30
31/**
32 * The mini with the sparkle `t` ms into the hop laid over it, in its own viewBox (sprite pixels),
33 * as an inert `data-part="sparkle"` group. Same width and height as the mini. It stays inside the
34 * viewBox (a hats mini is 16 wide); rows a theme adds on top (a hat over `hatAnchor`) are kept clear.
35 */
36export function withSparkle(mini: Sprite, palette: Readonly<Record<string, string>>, t: number, hatAnchor?: { x: number; y: number }): Sprite {
37 const spark = SPARKS[Math.floor(Math.max(0, t) / SPARK_STEP_MS) % SPARKS.length] as Frame
38 const h = spark.length
39 const w = spark[0]?.length ?? 0
40 const view = /viewBox="0 0 ([\d.]+) ([\d.]+)"/.exec(mini.source)
41 const vw = view ? Number(view[1]) : GRID.width
42 const vh = view ? Number(view[2]) : GRID.height
43 // Rows above the pet's own 13: a hat's, its brim just above the head (the anchor).
44 const added = Math.max(0, vh - GRID.height)
45 const below = added > 0 ? added + (hatAnchor?.y ?? 0) : 0
46 const x0 = Math.max(0, Math.min(SPARK_AT.x - Math.floor(w / 2), vw - w))
47 const y0 = Math.max(0, below, Math.min(added + SPARK_AT.y - Math.floor(h / 2), vh - h))
48 let rects = ''
49 spark.forEach((row, y) => {
50 for (let x = 0; x < row.length; x++) {
51 const ch = row[x] as 'Y' | 'C' | '.'
52 if (ch === '.') continue
53 const color = palette[ch] ?? FALLBACK[ch]
54 rects += `<rect x="${x0 + x}" y="${y0 + y}" width="1" height="1" fill="${color}"/>`
55 }
56 })
57 const at = mini.source.lastIndexOf('</svg>')
58 if (at < 0) return mini
59 return { ...mini, source: `${mini.source.slice(0, at)}<g data-part="sparkle">${rects}</g>${mini.source.slice(at)}` }
60}
61hooks/behavior/streak.ts 39 lines1// The daily streak: consecutive local days with at least one turn. Pure; the
2// caller keeps it in $.store under STORE_STREAK.
3export type Streak = { lastDay: string; count: number; cheered: number }
4
5export const STORE_STREAK = 'streak'
6
7const pad = (n: number) => String(n).padStart(2, '0')
8export const dayKey = (ms: number): string => {
9 const d = new Date(ms)
10 return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
11}
12
13const yesterdayOf = (ms: number): string => {
14 const d = new Date(ms)
15 d.setDate(d.getDate() - 1)
16 return dayKey(d.getTime())
17}
18
19const FIRST = [3, 7, 14, 30, 50, 100]
20export const isMilestone = (n: number): boolean => FIRST.includes(n) || (n > 100 && n % 100 === 0)
21
22export function advance(s: Streak | null, nowMs: number): { streak: Streak; cheer: boolean; changed: boolean; broken: boolean } {
23 const today = dayKey(nowMs)
24 if (s && s.lastDay === today) return { streak: s, cheer: false, changed: false, broken: false }
25 const continues = !!s && s.lastDay === yesterdayOf(nowMs)
26 const count = continues ? (s as Streak).count + 1 : 1
27 const broken = !!s && !continues && s.count > 1
28 const cheer = isMilestone(count) && (s?.cheered ?? 0) !== count
29 return { streak: { lastDay: today, count, cheered: cheer ? count : (s?.cheered ?? 0) }, cheer, changed: true, broken }
30}
31
32export function asStreak(v: unknown): Streak | null {
33 if (!v || typeof v !== 'object') return null
34 const o = v as Record<string, unknown>
35 return typeof o.lastDay === 'string' && typeof o.count === 'number' && typeof o.cheered === 'number'
36 ? { lastDay: o.lastDay, count: o.count, cheered: o.cheered }
37 : null
38}
39hooks/behavior/tiers.ts 214 lines1// Crew tiers: the model and effort each tier runs at, the step-up ladder a failed
2// crew member climbs, and the agent types that pin them. Pure.
3import type { CrewRow } from './crew'
4import type { Tier } from './types'
5
6export type Effort = 'low' | 'medium' | 'high' | 'xhigh' | 'max'
7export type TierSpec = { model: string; effort: Effort }
8/** Each tier's model and effort, and the lean reviewer's (not a rung: it never steps up). */
9export type CrewTiers = Record<Tier | 'reviewer', TierSpec>
10/** One step of the ladder: an agent type (`crew-<tier>` or `crew-<tier>-<effort>`) and what it runs at. */
11export type Rung = { type: string; tier: Tier; model: string; effort: Effort }
12/** A failed crew member's retry one rung up. `stepUps` counts the retry itself. */
13export type StepUp = { fromId: string; name: string; from: string; to: string; stepUps: number }
14
15export const TIERS: readonly Tier[] = ['light', 'medium', 'heavy']
16export const EFFORTS: readonly Effort[] = ['low', 'medium', 'high', 'xhigh', 'max']
17/** A tier's own effort: xhigh and max are only step-up rungs. */
18const TIER_EFFORTS: readonly Effort[] = ['low', 'medium', 'high']
19export const AGENT_PREFIX = 'glitch-pets:'
20export const MAX_STEP_UPS = 2
21
22export const DEFAULT_TIERS: CrewTiers = {
23 light: { model: 'claude-haiku-5-5', effort: 'low' },
24 medium: { model: 'claude-sonnet-5-5', effort: 'medium' },
25 heavy: { model: 'claude-opus-5-5', effort: 'high' },
26 reviewer: { model: 'claude-sonnet-5-5', effort: 'low' },
27}
28/** The `crewTiers` entries: the tiers and the reviewer. */
29const ENTRIES = [...TIERS, 'reviewer'] as const
30
31const MODEL = /^[A-Za-z0-9][\w.:[\]-]*$/
32const isObject = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v)
33
34/** The `crewTiers` setting: a JSON object (or the object itself), tier → { model, effort }; each bad field keeps its default. */
35export function parseCrewTiers(raw: unknown): { tiers: CrewTiers; problems: string[] } {
36 const problems: string[] = []
37 let o: unknown = raw
38 if (raw === undefined || raw === null || (typeof raw === 'string' && raw.trim() === '')) return { tiers: DEFAULT_TIERS, problems }
39 if (typeof raw === 'string') {
40 try {
41 o = JSON.parse(raw)
42 } catch {
43 return { tiers: DEFAULT_TIERS, problems: ['crewTiers is not valid JSON'] }
44 }
45 }
46 if (!isObject(o)) return { tiers: DEFAULT_TIERS, problems: ['crewTiers must be a JSON object of tiers (light, medium, heavy, reviewer)'] }
47 for (const k of Object.keys(o)) if (!(ENTRIES as readonly string[]).includes(k)) problems.push(`crewTiers: unknown tier ${k}`)
48 const tiers = { ...DEFAULT_TIERS }
49 for (const t of ENTRIES) {
50 const v = o[t]
51 if (v === undefined) continue
52 if (!isObject(v)) {
53 problems.push(`crewTiers.${t} must be an object with model and effort`)
54 continue
55 }
56 let { model, effort } = DEFAULT_TIERS[t]
57 if (v.model !== undefined) {
58 if (typeof v.model === 'string' && MODEL.test(v.model)) model = v.model
59 else problems.push(`crewTiers.${t}.model must be a model alias or id`)
60 }
61 if (v.effort !== undefined) {
62 if ((TIER_EFFORTS as readonly unknown[]).includes(v.effort)) effort = v.effort as Effort
63 else problems.push(`crewTiers.${t}.effort must be low, medium or high${t === 'reviewer' ? '' : ' (xhigh and max are only step-up rungs)'}`)
64 }
65 tiers[t] = { model, effort }
66 }
67 return { tiers, problems }
68}
69
70const rank = (e: Effort): number => EFFORTS.indexOf(e)
71
72/**
73 * The step-up ladder: each tier's own rung, then (effort first) the same model at
74 * high, then the next tier. Past the heavy tier: its model at each higher effort.
75 */
76export function ladderOf(tiers: CrewTiers): Rung[] {
77 const rungs: Rung[] = []
78 TIERS.forEach((tier, i) => {
79 const { model, effort } = tiers[tier]
80 rungs.push({ type: `crew-${tier}`, tier, model, effort })
81 const above = i < TIERS.length - 1 ? (rank(effort) < rank('high') ? ['high' as const] : []) : EFFORTS.slice(rank(effort) + 1)
82 for (const e of above) rungs.push({ type: `crew-${tier}-${e}`, tier, model, effort: e })
83 })
84 return rungs
85}
86
87const shortType = (type: string): string => (type.startsWith(AGENT_PREFIX) ? type.slice(AGENT_PREFIX.length) : type.includes(':') ? '' : type)
88
89/** The rung an agent type is (`glitch-pets:crew-light` or `crew-light`), or null for any other type. */
90export const rungOfType = (ladder: readonly Rung[], type: string): Rung | null => ladder.find(r => r.type === shortType(type)) ?? null
91
92/** One rung up from `current`, skipping rungs that run the same model at the same effort; null at the top or off the ladder. */
93export function nextRung(ladder: readonly Rung[], current: Rung | string): Rung | null {
94 const at = ladder.findIndex(r => r.type === (typeof current === 'string' ? shortType(current) : current.type))
95 if (at < 0) return null
96 const cur = ladder[at] as Rung
97 return ladder.slice(at + 1).find(r => r.model !== cur.model || r.effort !== cur.effort) ?? null
98}
99
100const FAMILY = /(haiku|sonnet|opus|fable)/i
101
102/** `Haiku · low`: the model family (or the model as set) and the effort. */
103export function rungLabel(r: Pick<Rung, 'model' | 'effort'>): string {
104 const m = FAMILY.exec(r.model)
105 const fam = m ? (m[1] as string).charAt(0).toUpperCase() + (m[1] as string).slice(1).toLowerCase() : r.model
106 return `${fam} · ${r.effort}`
107}
108
109const WHEN: Record<Tier, string> = {
110 light: 'small, mechanical tasks: a lookup, a rename, a one-file edit, running a known check',
111 medium: 'normal work: a feature across a few files, a focused research question, a test pass',
112 heavy: 'hard reasoning: a tricky design, debugging across a system',
113}
114
115export const CREW_MEMBER_PROMPT = [
116 'You are a member of a Glitch crew: a helper agent the lead (the main Claude session) started for one task.',
117 'Do exactly that task with the tools you have, within the files or sources it names and the constraints it states.',
118 'Do not start helper agents of your own and never start a crew; if the task is too big for you, say so in your report.',
119 'When you are done, reply with a short report: what you did, where (paths), and anything you are unsure of or could not do.',
120 'If you could not finish, say so plainly. Never say something is done, fixed or verified unless you checked it.',
121].join('\n')
122
123/** One agent type per rung, as `$.agent.register` takes it. */
124export function agentSpecs(ladder: readonly Rung[]): { name: string; description: string; prompt: string; model: string; effort: Effort; disallowedTools: string[] }[] {
125 return ladder.map(r => ({
126 name: r.type,
127 description: r.type === `crew-${r.tier}`
128 ? `Glitch crew member, ${r.tier} tier (${rungLabel(r)}): for ${WHEN[r.tier]}. Use it for a crew helper whose plan row says tier ${r.tier}; pass no model or effort.`
129 : `Glitch crew step-up rung (${rungLabel(r)}): only to retry a failed crew member when a Glitch crew note names this type.`,
130 prompt: CREW_MEMBER_PROMPT,
131 model: r.model,
132 effort: r.effort,
133 disallowedTools: ['Agent'],
134 }))
135}
136
137// ── The lean reviewer (#45): verification, not regeneration ──
138
139export const REVIEWER_TYPE = 'crew-reviewer'
140/** The reviewer's turn cap (`AgentSpec.maxTurns`, "the most turns the agent takes before it stops"): room to read, run the checks, spot-check a few items and still reply. */
141export const REVIEWER_MAX_TURNS = 18
142/** The turn by which the reviewer stops investigating, so the cap never swallows its findings. */
143const REVIEWER_WRAP_UP = REVIEWER_MAX_TURNS - 4
144
145const REVIEWER_NAME = /^reviewer-\d+$/i
146/** `reviewer-<n>`, the crew rule's name for the reviewer. */
147export const isReviewerName = (name: string | undefined): boolean => !!name && REVIEWER_NAME.test(name)
148/** The lean reviewer's type, full (`glitch-pets:crew-reviewer`) or short. */
149export const isReviewerType = (type: string): boolean => shortType(type) === REVIEWER_TYPE
150
151/**
152 * A spawn that runs as the lean crew-reviewer: on that type, or named `reviewer-<n>`
153 * (on any type). By name only: a description never moves an agent onto it.
154 */
155export const isReviewerSpawn = (e: { subagentType: string; name?: string }): boolean => isReviewerType(e.subagentType) || isReviewerName(e.name)
156
157export const CREW_REVIEWER_PROMPT = [
158 'You are the reviewer of a Glitch crew: a verifier, not a second crew. The lead (the main Claude session) gives you the plan, each crew member\'s report and the paths of what changed.',
159 'Verify the work; do not do it again:',
160 '1. Read the plan and the reports. Check that every task in the plan has a deliverable and that each report matches the plan and the user\'s request.',
161 '2. Look at the changed files and outputs (git diff or git status when there is a repository). Read what changed, not the whole project.',
162 '3. Run the project\'s existing tests, linters and checks, if there are any, once. Do not write new ones.',
163 '4. Spot-check at most 3 items against the plan, picking the riskiest: check a value against its stated source or a quick sanity bound, never a full re-derivation.',
164 'Never redo or recompute the work from scratch, and never rewrite a crew member\'s script or answer to compare. Go deeper on one item only when a concrete check fails (a test fails, a file is missing, a value contradicts its source), and only on that item.',
165 'Do not change any file; do not start agents. On a second review, check only what changed since the first one and whether each earlier finding is fixed.',
166 'Reply in under 200 words: a list of findings, each with where it is (path or item), which task it belongs to and what is wrong, or exactly "no findings". Say which checks you ran. Never say something is verified unless you checked it.',
167 `You have about ${REVIEWER_MAX_TURNS} turns; stop investigating by turn ${REVIEWER_WRAP_UP} and send your reply. Always end with the findings list or "no findings", even when you could not finish every check (say which ones you skipped).`,
168].join('\n')
169
170/** The lean reviewer's agent type, as `$.agent.register` takes it: the `reviewer` entry's model and effort, a turn cap, no agents of its own and no file edits. */
171export function reviewerSpec(tiers: CrewTiers): { name: string; description: string; prompt: string; model: string; effort: Effort; maxTurns: number; disallowedTools: string[] } {
172 const { model, effort } = tiers.reviewer
173 return {
174 name: REVIEWER_TYPE,
175 description: `Glitch crew reviewer (${rungLabel({ model, effort })}): a quick verifier of a finished crew's result. Use it for reviewer-1 once every crew member has finished: pass the plan, each report and the changed paths, and no model or effort. It verifies (checks, existing tests, spot-checks); it does not redo the work.`,
176 prompt: CREW_REVIEWER_PROMPT,
177 model,
178 effort,
179 maxTurns: REVIEWER_MAX_TURNS,
180 // Bash stays, to run the project's checks.
181 disallowedTools: ['Agent', 'Edit', 'Write', 'NotebookEdit'],
182 }
183}
184
185/** Rows that just went from running to failed on a crew rung, each with its next rung (none past the top or the cap; a kill is the person's call). */
186export function stepUpsFor(before: readonly CrewRow[], after: readonly CrewRow[], ladder: readonly Rung[]): StepUp[] {
187 const ups: StepUp[] = []
188 for (const r of after) {
189 const was = before.find(b => b.id === r.id)
190 if (r.status !== 'failed' || r.killed || !r.rung || was?.status !== 'running') continue
191 const done = r.stepUps ?? 0
192 if (done >= MAX_STEP_UPS) continue
193 const next = nextRung(ladder, r.rung)
194 if (!next) continue
195 ups.push({ fromId: r.id, name: r.name ?? r.description, from: r.rung, to: next.type, stepUps: done + 1 })
196 }
197 return ups
198}
199
200/** What Claude reads beside the next prompt: retry the failed member one rung up. */
201export function stepUpNote(u: StepUp, ladder: readonly Rung[]): string {
202 const from = ladder.find(r => r.type === u.from)
203 return `Glitch crew: ${u.name} failed on ${from ? rungLabel(from) : u.from} (${AGENT_PREFIX}${u.from}); retry it with subagent type ${AGENT_PREFIX}${u.to}: the same prompt, the name ${u.name}, and no model or effort.`
204}
205
206/** The step-up a retry spawn answers: same type and name first, else the oldest of that type. */
207export function claimStepUp(sent: readonly StepUp[], type: string, name: string | undefined): { claimed: StepUp | null; rest: StepUp[] } {
208 const t = shortType(type)
209 const i = sent.findIndex(u => u.to === t && u.name === name)
210 const j = i >= 0 ? i : sent.findIndex(u => u.to === t)
211 if (j < 0) return { claimed: null, rest: [...sent] }
212 return { claimed: sent[j] as StepUp, rest: sent.filter((_, k) => k !== j) }
213}
214hooks/behavior/types.ts 58 lines1// The shapes every persona and every behavior module agree on. No imports: the
2// gallery script loads this file directly.
3
4export const PET_IDS = ['screenhead', 'blob', 'pixel', 'dot', 'fork', 'bud'] as const
5export type PetId = (typeof PET_IDS)[number]
6
7export const MOOD_IDS = ['idle', 'working', 'happy', 'tired', 'sleepy', 'worried', 'oops', 'cheering', 'leading', 'reviewing', 'crying', 'investigating', 'pleased'] as const
8export type MoodId = (typeof MOOD_IDS)[number]
9
10export const VOICE_MOMENTS = ['happy', 'worried', 'oops', 'cheering', 'sleepy', 'crying', 'crewDone'] as const
11export type VoiceMoment = (typeof VOICE_MOMENTS)[number]
12
13/** A persona's own palette keys are letters; every digit and punctuation char is left to overlay art. */
14export const PET_KEY = /^[A-Za-z]$/
15/** The laptop's keys (behavior/laptop.ts). Every other digit and punctuation char is free for crew themes. */
16export const LAPTOP_KEYS: readonly string[] = ['4', '6', '7']
17
18/** The sprite grid: 16 columns × 13 rows. */
19export const GRID = { width: 16, height: 13 } as const
20
21/** One frame: 13 strings of 16 chars; '.' is empty, any other char a palette key. */
22export type Frame = readonly string[]
23
24export type MoodArt = { frames: readonly Frame[]; fps: number }
25
26/** What the lead row can say, in the order the lead's mood picks them (first match wins). */
27export const LEAD_SITUATIONS = ['worry', 'joy', 'reviewing', 'investigating', 'many', 'one', 'allDone', 'someFailed'] as const
28export type LeadSituation = (typeof LEAD_SITUATIONS)[number]
29/** One wording for any number, or a pair: for one, then for more than one (the count is who's for joy and worry, {f} for someFailed, {n} otherwise). */
30export type LeadWording = string | readonly [one: string, many: string]
31
32export type Persona = {
33 id: PetId
34 /** Shown in toasts and the crew pane: "Bud". */
35 name: string
36 /** For alt text: "dog". */
37 kind: string
38 /** One line, for the gallery and the README. */
39 temperament: string
40 /** Palette key → #rrggbb. Keys are letters (PET_KEY): digits and punctuation are reserved for overlay art (LAPTOP_KEYS, crew themes). */
41 palette: Readonly<Record<string, string>>
42 moods: Readonly<Record<MoodId, MoodArt>>
43 /** Top-center of the head, where a crew hat's brim sits (x 0–15, y 0–12). */
44 hatAnchor: { x: number; y: number }
45 /** Palette key of the pet's paw or body color; the laptop's typing paws use it. */
46 laptopPaw: string
47 /** 3–5 lines per moment, in this pet's own voice. */
48 voice: Readonly<Record<VoiceMoment, readonly string[]>>
49 /** The lead row's wording in this pet's voice; `{n}`, `{who}`, `{d}`, `{f}` are filled in. Missing ones use the neutral wording. */
50 leadStatus?: Readonly<Partial<Record<LeadSituation, LeadWording>>>
51}
52
53/** What glitch-hud draws: one frame as an image. */
54export type Sprite = { source: string; alt: string; width: number; height: number }
55
56export type Role = 'builder' | 'researcher' | 'designer' | 'tester' | 'reviewer' | 'other'
57export type Tier = 'light' | 'medium' | 'heavy'
58