A pane that shows the main session and its subagents, with an animated pixel character for each agent

hooks/register.tsx 12 lines1import type { Register } from 'claude-code'
2
3import { registerCollect } from './collect.ts'
4import { settingsFromOptions } from './core/avatar/settings.ts'
5import { motionMode } from './core/character.ts'
6import { registerPane } from './view/pane.tsx'
7
8export const register: Register = (on, options) => {
9 registerCollect(on, settingsFromOptions(options))
10 registerPane(on, motionMode(options.motion))
11}
12hooks/collect.ts 295 lines1// Event collection: the only layer that hooks engine events. It turns each
2// event into a domain event and applies it to the state through the core.
3
4import type {
5 AgentInfo,
6 EngineInterface,
7 HookStream,
8 On,
9 SessionUsage,
10 Timer,
11 TurnStepChunk,
12 TurnStepInput,
13 TurnStepResult,
14 TurnUsage,
15} from 'claude-code'
16import { atom, update } from 'claude-code'
17
18import { refreshPacks, runPackCommand, settingChanged } from './commands.ts'
19import type { AgentEvent } from './core/agents.ts'
20import { initialAgents, reduceAgents } from './core/agents.ts'
21import type { AvatarSettings } from './core/avatar/settings.ts'
22import { initialSettings } from './core/avatar/settings.ts'
23import type { SessionEvent } from './core/session.ts'
24import { cacheTtlMs, initialSession, reduceSession } from './core/session.ts'
25import { initialUsage, reduceUsage } from './core/usage/usage.ts'
26import type { StepFinished, UsageEvent } from './core/usage/usage.ts'
27import { isSupportedEngine, MIN_ENGINE_VERSION } from './core/version.ts'
28import { PANE_ID, SESSION_SHAPE } from './state.ts'
29
30const session = atom({ plugin: 'crabarium', key: 'session' } as const, initialSession, { shape: SESSION_SHAPE })
31const agents = atom({ plugin: 'crabarium', key: 'agents' } as const, initialAgents)
32const usageBoard = atom({ plugin: 'crabarium', key: 'usage' } as const, initialUsage)
33const settings = atom({ plugin: 'crabarium', key: 'settings' } as const, initialSettings)
34
35const POLL_MS = 1000
36
37// A hot reload drops this module and its timers; session.start runs again
38// then and restarts the poll for a pane that is still open.
39let poll: Timer | null = null
40
41export function usageEvent(usage: SessionUsage, turns: number | null, at: number): SessionEvent {
42 return {
43 kind: 'usage-read',
44 contextPercent: usage.context.percent ?? null,
45 costUsd: usage.cost?.usd ?? null,
46 startedAt: usage.startedAt,
47 rateLimits: usage.rateLimits.map(({ kind, percentUsed }) => ({ kind, percentUsed })),
48 turns,
49 at,
50 }
51}
52
53export function stepEvent(e: Pick<TurnStepInput, 'agentId' | 'effort'>, u: TurnUsage): StepFinished {
54 return {
55 kind: 'step-finished',
56 agentId: e.agentId ?? null,
57 model: u.model,
58 effort: e.effort === undefined ? null : String(e.effort),
59 tokens: {
60 input: u.input_tokens,
61 output: u.output_tokens,
62 cacheRead: u.cache_read_input_tokens,
63 cacheWrite: u.cache_creation_input_tokens,
64 },
65 }
66}
67
68export function listedEvent(list: readonly AgentInfo[], at: number): AgentEvent {
69 return { kind: 'agents-listed', statuses: list.map(({ id, status }) => ({ id, status })), at }
70}
71
72async function dispatch($: EngineInterface, event: SessionEvent): Promise<void> {
73 await update($, session, s => reduceSession(s, event))
74}
75
76async function dispatchUsage($: EngineInterface, event: UsageEvent): Promise<void> {
77 await update($, usageBoard, s => reduceUsage(s, event))
78}
79
80// Runs a write of the mod's own state from a hook on engine work. A failure,
81// in the write or in making its event, is logged and does not fail the work.
82async function observe($: EngineInterface, what: string, write: () => Promise<void>): Promise<void> {
83 await Promise.resolve()
84 .then(write)
85 .catch((error: unknown) => {
86 $.ui.log(`crabarium: ${what} was not recorded: ${error instanceof Error ? error.message : String(error)}`)
87 })
88}
89
90async function dispatchAgent($: EngineInterface, event: AgentEvent): Promise<void> {
91 await update($, agents, s => reduceAgents(s, event))
92}
93
94/** The prompt origins that are the user's own: typed, through Remote Control, or from the SDK host. */
95const USER_ORIGINS: ReadonlySet<string> = new Set(['composer', 'bridge', 'sdk'])
96
97async function recordUsage($: EngineInterface, e: TurnStepInput, result: TurnStepResult): Promise<void> {
98 // A step that got no response has no usage to count.
99 if (result.usage === null) return
100 const usage = result.usage
101 await observe($, 'the usage of a step', () => dispatchUsage($, stepEvent(e, usage)))
102}
103
104// Passes a step's stream on unchanged. `done` gets the result and the time of
105// the first content chunk (`null` when none came).
106async function* timed(
107 $: EngineInterface,
108 stream: HookStream<TurnStepChunk, TurnStepResult>,
109 done: (result: TurnStepResult, firstAt: number | null) => Promise<void>,
110): AsyncGenerator<TurnStepChunk, TurnStepResult> {
111 let firstAt: number | null = null
112 for await (const chunk of stream) {
113 if (firstAt === null && chunk.kind !== 'engine') firstAt = await $.clock.now().catch(() => null)
114 yield chunk
115 }
116 const result = await stream.result
117 await done(result, firstAt)
118 return result
119}
120
121// One read of everything the pane polls: the usage, the agent list, the time.
122async function refresh($: EngineInterface): Promise<void> {
123 // The turn count is a detail: if the engine does not answer it, the rest still updates.
124 const turns = $.session.turns().catch(() => null)
125 const [usage, list, at] = await Promise.all([$.session.usage(), $.agent.list(), $.clock.now()])
126 await dispatch($, usageEvent(usage, await turns, at))
127 await dispatchAgent($, listedEvent(list, at))
128}
129
130// The API has no file watch, so the mod checks the user packs' file times
131// while the pane is open. A failed check waits for the next one.
132const PACK_POLL_MS = 3000
133let packPoll: Timer | null = null
134
135function startPoll($: EngineInterface): void {
136 poll ??= $.clock.every(POLL_MS, () => void refresh($))
137 packPoll ??= $.clock.every(PACK_POLL_MS, () => void refreshPacks($).catch(() => undefined))
138}
139
140function stopPoll(): void {
141 poll?.cancel()
142 poll = null
143 packPoll?.cancel()
144 packPoll = null
145}
146
147async function isPaneOpen($: EngineInterface): Promise<boolean> {
148 return (await $.ui.panes()).some(pane => pane.id === PANE_ID)
149}
150
151async function openPane($: EngineInterface): Promise<string> {
152 await refresh($)
153 const opened = await $.ui.open({ id: PANE_ID, title: 'crabarium' })
154 startPoll($)
155 return opened.isPlaced ? 'crabarium pane opened.' : `crabarium pane waits: ${opened.reason}`
156}
157
158/** `options` are the plugin's `userConfig` values as the module loaded with them. */
159export function registerCollect(on: On, options: AvatarSettings): void {
160 on('session.start', async ($, e, next) => {
161 const { version } = await $.session.version()
162 if (!isSupportedEngine(version)) {
163 $.ui.log(`crabarium needs Claude Code ${MIN_ENGINE_VERSION} or later (this is ${version}); it stays off.`)
164 return next(e)
165 }
166 // The engine loads the module again with new options, so they are current here.
167 await update($, settings, () => options)
168 await $.command.register({
169 name: 'crabarium',
170 description: 'Show or hide the crabarium pane; `pack` lists, selects, checks and previews character packs',
171 argumentHint: '[pack [<name> | reload | check [<name>] | preview [<name>]]]',
172 })
173 await refreshPacks($).catch(() => undefined)
174 if (await isPaneOpen($)) {
175 await refresh($)
176 startPoll($)
177 }
178 return next(e)
179 })
180
181 on('command.run', { command: 'crabarium' }, async ($, e) => {
182 const [word, ...rest] = e.args
183 .trim()
184 .split(/\s+/)
185 .filter(w => w !== '')
186 if (word === 'pack')
187 return { text: await runPackCommand($, rest, { openPane: async () => void ((await isPaneOpen($)) || (await openPane($))) }) }
188 if (word !== undefined) return { text: `Unknown argument ${JSON.stringify(word)}. Usage: /crabarium [pack ...]` }
189 if (await isPaneOpen($)) {
190 await $.ui.close({ id: PANE_ID })
191 return { text: 'crabarium pane closed.' }
192 }
193 return { text: await openPane($) }
194 })
195
196 // The user changed a crabarium row in /config. An observer: if it fails, the change goes on.
197 on('config.set', async ($, e, next) => {
198 const result = await next(e)
199 // The provider names the row's plugin; a caller that leaves it out names no plugin.
200 if (result.deny === undefined && (e.provider as typeof e.provider | undefined)?.plugin === $.plugin.name) {
201 await settingChanged($, e.key, result.value)
202 }
203 return result
204 }).catch((_$, e, next) => next(e))
205
206 // An observer: if it fails, the close goes on.
207 on('ui.close', { id: PANE_ID }, (_$, e, next) => {
208 stopPoll()
209 return next(e)
210 }).catch((_$, e, next) => next(e))
211
212 // The model request is the engine's work, not the mod's: a failed write of
213 // the mod's own state only logs, and never fails the request.
214 on('turn.step', async function* ($, e, next) {
215 // A step with an agentId belongs to a subagent, not the main session.
216 if (e.agentId !== undefined) return yield* timed($, next(e), result => recordUsage($, e, result))
217 await observe($, 'the model of a step', () => dispatch($, { kind: 'model-used', model: e.model }))
218 const sentAt = await $.clock.now()
219 return yield* timed($, next(e), async (result, firstAt) => {
220 await recordUsage($, e, result)
221 if (result.usage === null) return
222 const usage = result.usage
223 await observe($, 'the timing of a step', async () => {
224 const end = await $.clock.now()
225 await dispatch($, {
226 kind: 'step-timed',
227 // The output time starts at the first chunk: the wait before it, and
228 // any retry before a chunk came, is not output.
229 step: firstAt === null ? null : { outputTokens: usage.output_tokens, ms: end - firstAt },
230 model: e.model,
231 sentAt,
232 cacheUsed: usage.cache_read_input_tokens + usage.cache_creation_input_tokens > 0,
233 })
234 })
235 })
236 })
237
238 // Observers: if one fails, the prompt or the switch goes on. The turn cost
239 // counts from a prompt that the user sent, as the engine's turn count does;
240 // a notification or a schedule that wakes the loop does not start a turn.
241 on('prompt.submit', async ($, e, next) => {
242 if (USER_ORIGINS.has(e.origin.kind)) {
243 await observe($, 'the cost at a prompt', async () =>
244 dispatch($, { kind: 'prompt-sent', costUsd: (await $.session.usage()).cost?.usd ?? null }),
245 )
246 }
247 return next(e)
248 }).catch((_$, e, next) => next(e))
249
250 // The engine tells the cache TTL only here. The mod does not guess it at other times.
251 on('classic.PostModelSwitch', async ($, e, next) => {
252 await observe($, 'the model switch', () =>
253 dispatch($, { kind: 'model-switched', model: e.to_model, cacheTtlMs: cacheTtlMs(e.cache_ttl) }),
254 )
255 return next(e)
256 }).catch((_$, e, next) => next(e))
257
258 // A /clear or a resume ends the conversation without a new session.start;
259 // the token sums start again, as the engine's cost and time do.
260 on('session.end', async ($, e, next) => {
261 if (e.reason === 'clear' || e.reason === 'resume') {
262 await dispatchUsage($, { kind: 'usage-reset' })
263 await dispatch($, { kind: 'conversation-replaced' })
264 }
265 return next(e)
266 }).catch((_$, e, next) => next(e))
267
268 // Observers: if one fails, the spawn or the turn end goes on; `next(e)` in
269 // the fallback gives back what the first `next` call settled to.
270 on('agent.spawn', async ($, e, next) => {
271 const result = await next(e)
272 // A denied spawn starts nothing, and a remote workflow agent has no local loop.
273 if (result.deny !== undefined || result.agentId === undefined) return result
274 await dispatchAgent($, {
275 kind: 'agent-spawned',
276 id: result.agentId,
277 description: e.description,
278 type: e.subagentType,
279 model: result.model,
280 parentId: e.parentAgentId ?? null,
281 isTeammate: e.isTeammate === true,
282 at: await $.clock.now(),
283 })
284 return result
285 }).catch((_$, e, next) => next(e))
286
287 on('turn.complete', async ($, e, next) => {
288 const result = await next(e)
289 if (e.agentId !== undefined) {
290 await dispatchAgent($, { kind: 'agent-turn-ended', id: e.agentId, reason: e.reason, at: await $.clock.now() })
291 }
292 return result
293 }).catch((_$, e, next) => next(e))
294}
295hooks/core/avatar/settings.ts 18 lines1// The `userConfig` values that the pane draws with, as the state holds them.
2import type { AvatarSettings } from '../../../types'
3import { avatarMode } from './select.ts'
4
5export type { AvatarSettings }
6
7/** The pack that a new install shows, and the one that the pane falls back to. */
8export const DEFAULT_PACK = 'minimal'
9
10export const initialSettings: AvatarSettings = { pack: DEFAULT_PACK, avatarMode: 'keywords', avatarRules: '' }
11
12/** The settings from the plugin options; a missing or wrong value takes its default. */
13export function settingsFromOptions(options: Readonly<Record<string, unknown>>): AvatarSettings {
14 const pack = typeof options.pack === 'string' && options.pack.trim() !== '' ? options.pack.trim() : DEFAULT_PACK
15 const rules = typeof options.avatarRules === 'string' ? options.avatarRules : ''
16 return { pack, avatarMode: avatarMode(options.avatarMode), avatarRules: rules }
17}
18hooks/core/character.ts 324 lines1// What each character shows at a time: its state from the agent status, and
2// the frame of each motion. Pure: the time comes in as an argument.
3import type { AgentRow } from './agents.ts'
4import { isEnded } from './agents.ts'
5import { own } from './own.ts'
6import { coversAny, isUnder, partOf } from './pack/pack.ts'
7import type { CharacterState, Frame, Motion, Move, Pack, PartFrame, PartSelection, Pose, Role } from './pack/pack.ts'
8import type { Rule, Weighted } from './pack/rules.ts'
9import { motionNamed, styleOf } from './pack/style.ts'
10import type { Style } from './pack/style.ts'
11
12/** How long a new character is `entering` before it is `working`. */
13export const ENTER_MS = 1500
14
15/** `full` animates; `reduced` shows one still pose for each state; `off` shows the still character. */
16export type MotionMode = 'full' | 'reduced' | 'off'
17
18const MOTION_MODES: readonly unknown[] = ['full', 'reduced', 'off'] satisfies MotionMode[]
19
20function isMotionMode(option: unknown): option is MotionMode {
21 return MOTION_MODES.includes(option)
22}
23
24/** The `motion` option. The engine gives only the manifest's values, so another value is a bug; it falls back to `full`. */
25export function motionMode(option: unknown): MotionMode {
26 return isMotionMode(option) ? option : 'full'
27}
28
29const STATE_OF_STATUS = {
30 pending: 'working',
31 running: 'working',
32 waiting: 'idle',
33 idle: 'idle',
34 completed: 'finished',
35 failed: 'failed',
36 killed: 'failed',
37} as const satisfies Record<AgentRow['status'], CharacterState>
38
39/**
40 * The state, and the time its motion starts from. A live agent's motion runs
41 * from the spawn, so it does not jump when `entering` turns into `working`. An
42 * ended agent's runs from the end, which a later correction of how it ended
43 * (failed to killed) does not move. Nothing gives `leaving` yet: rows do not
44 * leave the pane.
45 */
46export function characterState(row: AgentRow, now: number): { state: CharacterState; since: number } {
47 if (!isEnded(row.status) && now - row.startedAt < ENTER_MS) return { state: 'entering', since: row.startedAt }
48 const state = STATE_OF_STATUS[row.status]
49 if (state === 'working') return { state, since: row.startedAt }
50 if (row.endedAt !== null) return { state, since: row.endedAt }
51 // `$.state` outlives a hot reload, so a row from a build before `statusAt` has none.
52 return { state, since: Number.isFinite(row.statusAt) ? row.statusAt : row.startedAt }
53}
54
55// The tick at which each frame ends, made once for each motion: a frame count has no limit.
56const endsOf = new WeakMap<Motion<{ repeat?: number }>, readonly number[]>()
57
58function frameEnds(motion: Motion<{ repeat?: number }>): readonly number[] {
59 let ends = endsOf.get(motion)
60 if (ends === undefined) {
61 const list: number[] = []
62 for (const frame of motion.frames) list.push((list.at(-1) ?? 0) + (frame.repeat ?? 1))
63 ends = list
64 endsOf.set(motion, ends)
65 }
66 return ends
67}
68
69// The index of the first value above `tick`, by binary search over sorted values.
70function firstAbove(values: readonly number[], tick: number): number {
71 let [low, high] = [0, values.length - 1]
72 while (low < high) {
73 const mid = (low + high) >> 1
74 if (values[mid]! > tick) high = mid
75 else low = mid + 1
76 }
77 return low
78}
79
80/** A frame index, and the elapsed time of the next frame change; `null` when no later time changes it. */
81export type FrameAt = { index: number; nextAt: number | null }
82
83/**
84 * The frame of a motion `elapsedMs` after it started. A frame holds for its
85 * `repeat` ticks. A loop wraps; a one-shot motion holds its last frame.
86 */
87export function frameAt(motion: Motion<{ repeat?: number }>, elapsedMs: number, mode: MotionMode = 'full'): FrameAt {
88 const last = motion.frames.length - 1
89 // Reduced motion keeps the pose that tells the state: the end of a one-shot motion, the start of a loop.
90 if (mode === 'reduced') return { index: motion.loop ? 0 : last, nextAt: null }
91 const ends = frameEnds(motion)
92 const total = ends.at(-1) ?? 1
93 const step = Math.floor((Math.max(0, elapsedMs) * motion.fps) / 1000)
94 if (!motion.loop && step >= total - (motion.frames[last]?.repeat ?? 1)) return { index: last, nextAt: null }
95 const cycle = motion.loop ? Math.floor(step / total) * total : 0
96 const index = firstAbove(ends, step - cycle)
97 // The first whole millisecond of the tick at which the next frame starts; a loop of one frame never changes.
98 const nextTick = cycle + ends[index]!
99 return { index, nextAt: motion.loop && last === 0 ? null : Math.ceil((nextTick * 1000) / motion.fps) }
100}
101
102/** What decides how an agent looks: its pack, the pack's rules, the agent's role, and the parts that it wears. */
103export type Look = { pack: Pack; rules: readonly Rule[]; role: Role | null; parts: PartSelection }
104
105/**
106 * What a character shows at `now`. `key` names the pose, so equal keys draw
107 * equal pixels for one look; `nextAt` is the time of its next frame change,
108 * or `null` when no later time changes the pose.
109 */
110export type CharacterPose = { key: string; pose: Pose; nextAt: number | null }
111
112// What the locks of a style keep a frame from: a swap of a locked channel, a
113// covering variant over a locked node, and a hide of a locked node or of a node
114// that a locked node is on.
115function lockGuard(pack: Pack, style: Style, parts: PartSelection) {
116 const locks = [...style.locks]
117 return {
118 swap: (channel: string, value: string) => !style.locks.has(channel) && !coversAny(pack, channel, value, style.locks, parts),
119 hide: (target: string) => !locks.some(locked => locked === target || isUnder(pack, locked, target, parts)),
120 }
121}
122
123/** The frame on the base pose: the frame's swaps and hides apply, except where a lock keeps them from it. */
124export function onPose(pack: Pack, style: Style, frame: Frame | undefined, parts: PartSelection): Frame {
125 const guard = lockGuard(pack, style, parts)
126 const swap: Record<string, string> = { ...style.pose }
127 for (const [channel, value] of Object.entries(frame?.swap ?? {})) if (guard.swap(channel, value)) swap[channel] = value
128 const hide = frame?.hide?.filter(guard.hide)
129 return { ...frame, swap, ...(hide === undefined ? {} : { hide }) }
130}
131
132const sameRecord = (a: Readonly<Record<string, unknown>>, b: Readonly<Record<string, unknown>>) =>
133 Object.keys(a).length === Object.keys(b).length && Object.entries(a).every(([k, v]) => Object.hasOwn(b, k) && b[k] === v)
134
135// Whether two styles draw the same in a mode: the same loop on the same base pose, and in full motion the same tricks.
136function sameStyle(a: Style, b: Style, mode: MotionMode): boolean {
137 const same = a.play === b.play && sameRecord(a.pose, b.pose) && a.locks.size === b.locks.size && [...a.locks].every(l => b.locks.has(l))
138 if (!same || mode !== 'full') return same
139 return sameRecord(a.tricks, b.tricks) && a.trickEvery?.[0] === b.trickEvery?.[0] && a.trickEvery?.[1] === b.trickEvery?.[1]
140}
141
142/** The distinct swaps and hides of a motion: what a lock can keep it from. */
143type Touches = { swaps: readonly (readonly [channel: string, value: string])[]; hides: readonly string[] }
144
145// Made once for each motion, so the cost of a lock check does not grow with the frame count.
146const touchesOf = new WeakMap<Motion, Touches>()
147
148function touches(motion: Motion): Touches {
149 let found = touchesOf.get(motion)
150 if (found === undefined) {
151 const swaps = new Map<string, readonly [string, string]>()
152 const hides = new Set<string>()
153 for (const frame of motion.frames) {
154 for (const [channel, value] of Object.entries(frame.swap ?? {})) swaps.set(`${channel}\0${value}`, [channel, value])
155 for (const target of frame.hide ?? []) hides.add(target)
156 }
157 found = { swaps: [...swaps.values()], hides: [...hides] }
158 touchesOf.set(motion, found)
159 }
160 return found
161}
162
163// FNV-1a, then the murmur3 finalizer, so each bit of the result depends on each input character.
164function hash(text: string): number {
165 let h = 0x811c9dc5
166 for (let i = 0; i < text.length; i += 1) h = Math.imul(h ^ text.charCodeAt(i), 0x01000193)
167 h = Math.imul(h ^ (h >>> 16), 0x85ebca6b)
168 h = Math.imul(h ^ (h >>> 13), 0xc2b2ae35)
169 return (h ^ (h >>> 16)) >>> 0
170}
171
172export type Choice = { name: string; motion: Motion; weight: number }
173
174/** The motions of a weighted list that can play on the style: each exists, and no lock keeps it from a frame. */
175export function usable(pack: Pack, style: Style, weights: Weighted, parts: PartSelection): Choice[] {
176 const guard = lockGuard(pack, style, parts)
177 return Object.entries(weights).flatMap(([name, weight]) => {
178 const motion = motionNamed(pack, name)
179 if (motion === null) return []
180 const { swaps, hides } = touches(motion)
181 return swaps.every(([channel, value]) => guard.swap(channel, value)) && hides.every(guard.hide) ? [{ name, motion, weight }] : []
182 })
183}
184
185// A choice by weight; the same seed gives the same choice.
186function pick(pool: readonly Choice[], seed: string): Choice | null {
187 const total = pool.reduce((sum, choice) => sum + choice.weight, 0)
188 if (total === 0) return null
189 let rest = hash(seed) % total
190 for (const choice of pool) {
191 if (rest < choice.weight) return choice
192 rest -= choice.weight
193 }
194 return null
195}
196
197/** How long a motion plays once through, in whole milliseconds. */
198function lengthMs(motion: Motion<{ repeat?: number }>): number {
199 return Math.ceil(((frameEnds(motion).at(-1) ?? 1) * 1000) / motion.fps)
200}
201
202/** A track 1 motion: a `once` motion of an event, or a trick. */
203type Shot = { name: string; motion: Motion; startsAt: number }
204
205/**
206 * The track 1 motion at `now`, or `null`, and the times at which track 1 can
207 * change. `begun` is when the state began. An event that the state starts
208 * (`finished`, `failed`) plays its `once` motion from then. After it, trick k
209 * starts at `base + min + phase + floor(k * mid) + jitter(k)`: `mid` is the
210 * middle of the two `trick-every` times, the jitter is from 0 to half their
211 * difference, and the phase (from 0 to `mid`) is the agent's own. So two
212 * tricks are from `min` to `max` apart, the first is from `min` to
213 * `min + max` after the base, two agents do not trick in step, and the trick
214 * at a time is known with no history.
215 */
216function trackOne(
217 look: Look,
218 row: AgentRow,
219 style: Style,
220 state: CharacterState,
221 begun: number,
222 now: number,
223): { shot: Shot | null; changes: number[] } {
224 const { pack, parts } = look
225 let base = begun
226 const event = state === 'finished' || state === 'failed' ? style.once[state] : undefined
227 if (event !== undefined) {
228 const chosen = pick(usable(pack, style, event, parts), `${row.id}:${state}`)
229 if (chosen !== null) {
230 base = begun + lengthMs(chosen.motion)
231 if (now < base) return { shot: { name: chosen.name, motion: chosen.motion, startsAt: begun }, changes: [base] }
232 }
233 }
234 if (style.trickEvery === null) return { shot: null, changes: [] }
235 const pool = usable(pack, style, style.tricks, parts)
236 if (pool.length === 0) return { shot: null, changes: [] }
237 const [min, max] = style.trickEvery
238 const mid = (min + max) / 2
239 const first = base + min + (hash(`${row.id}:${base}`) % Math.floor(mid))
240 const jitter = Math.floor((max - min) / 2) + 1
241 const startOf = (k: number) => first + Math.floor(k * mid) + (hash(`${row.id}:${base}:${k}`) % jitter)
242 // An estimate, then one step: a jitter is less than one `mid`.
243 let k = Math.max(-1, Math.floor((now - first) / mid))
244 if (startOf(k + 1) <= now) k += 1
245 else if (k >= 0 && startOf(k) > now) k -= 1
246 const changes = [startOf(k + 1)]
247 if (k < 0) return { shot: null, changes }
248 const startsAt = startOf(k)
249 const chosen = pick(pool, `${row.id}:${base}:${k}:trick`)
250 if (chosen === null || now >= startsAt + lengthMs(chosen.motion)) return { shot: null, changes }
251 changes.push(startsAt + lengthMs(chosen.motion))
252 return { shot: { name: chosen.name, motion: chosen.motion, startsAt }, changes }
253}
254
255// Track 1 over track 0, per channel: its swaps and palette win, offsets add, and hides join.
256function layered(below: Frame | undefined, above: Frame | undefined): Frame | undefined {
257 if (below === undefined || above === undefined) return above ?? below
258 const offset: Record<string, Move> = { ...below.offset }
259 for (const [node, [dx, dy]] of Object.entries(above.offset ?? {})) {
260 const [x, y] = own(offset, node) ?? [0, 0]
261 offset[node] = [x + dx, y + dy]
262 }
263 const hide = [...new Set([...(below.hide ?? []), ...(above.hide ?? [])])]
264 return {
265 offset,
266 swap: { ...below.swap, ...above.swap },
267 hide,
268 palette: { ...below.palette, ...above.palette },
269 }
270}
271
272export function characterPose(look: Look, row: AgentRow, now: number, mode: MotionMode): CharacterPose {
273 const { pack, rules, role, parts } = look
274 const { state, since } = characterState(row, now)
275 const style = styleOf(pack, rules, { role, state, parts })
276 // The role and the state choose the style; the rest of the look is the caller's key.
277 const keys = [`${role ?? '-'}:${state}`]
278 const changes: number[] = []
279 // The entrance ends at a fixed time. Only a different next style changes the pose then.
280 if (state === 'entering') {
281 const end = row.startedAt + ENTER_MS
282 const next = styleOf(pack, rules, { role, state: characterState(row, end).state, parts })
283 if (!sameStyle(style, next, mode)) changes.push(end)
284 }
285 if (mode === 'off') return { key: keys[0]!, pose: { body: onPose(pack, style, undefined, parts) }, nextAt: changes[0] ?? null }
286 const pose: { body?: Pose['body']; parts?: Record<string, PartFrame> } = {}
287
288 const body = style.play === null ? null : motionNamed(pack, style.play)
289 let frame: Frame | undefined
290 if (body !== null) {
291 const { index, nextAt } = frameAt(body, now - since, mode)
292 frame = body.frames[index]
293 keys.push(String(index))
294 if (nextAt !== null) changes.push(since + nextAt)
295 }
296 // Track 1 plays only in full motion: a trick does not tell the state.
297 if (mode === 'full') {
298 // Track 0 of working runs from the spawn, but working begins after the entrance, or when the agent runs again.
299 const statusAt = Number.isFinite(row.statusAt) ? row.statusAt : row.startedAt
300 const begun = state === 'working' ? Math.max(row.startedAt + ENTER_MS, statusAt) : since
301 const one = trackOne(look, row, style, state, begun, now)
302 changes.push(...one.changes)
303 if (one.shot !== null) {
304 const { index, nextAt } = frameAt(one.shot.motion, now - one.shot.startsAt)
305 frame = layered(frame, one.shot.motion.frames[index])
306 keys.push(`1:${one.shot.name}:${index}`)
307 if (nextAt !== null) changes.push(one.shot.startsAt + nextAt)
308 }
309 }
310 pose.body = onPose(pack, style, frame, parts)
311 // A part motion is the part's own: it runs from the spawn, whatever the state.
312 for (const [slot, name] of Object.entries(parts)) {
313 const motion = partOf(pack, slot, name)?.motion
314 if (motion === undefined) continue
315 const { index, nextAt } = frameAt(motion, now - row.startedAt, mode)
316 const partFrame = motion.frames[index]!
317 // A locked slot keeps its value: the part's own motion moves it, but does not swap it.
318 pose.parts = { ...pose.parts, [slot]: style.locks.has(slot) ? { ...partFrame, swap: undefined } : partFrame }
319 keys.push(`${slot}:${index}`)
320 if (nextAt !== null) changes.push(row.startedAt + nextAt)
321 }
322 return { key: keys.join('|'), pose, nextAt: changes.length > 0 ? Math.min(...changes) : null }
323}
324hooks/view/pane.tsx 265 lines1// View: draws the pane from the state. It reads; it never writes.
2import { atom, read } from 'claude-code'
3import type { Elements, On, ThemeKey } from 'claude-code'
4
5import { initialAgents } from '../core/agents.ts'
6import type { AgentStatus } from '../core/agents.ts'
7import { parseRules, selectOutfit } from '../core/avatar/select.ts'
8import { initialSettings } from '../core/avatar/settings.ts'
9import type { MotionMode } from '../core/character.ts'
10import { activePack, packEntries } from '../core/pack/registry.ts'
11import { initialSession } from '../core/session.ts'
12import { initialUsage } from '../core/usage/usage.ts'
13import { builtinPacks } from '../packs.generated.ts'
14import { NO_PACK_FILES } from '../packs.ts'
15import { PANE_ID, SESSION_SHAPE } from '../state.ts'
16import { fallbackPack } from './avatar.ts'
17import { avatarKey, framePlan, framesDrawn, stopFrames } from './frames.ts'
18import type { DrawnCharacter } from './frames.ts'
19import { paneLayout } from './layout.ts'
20import type { AgentLine, Folded, Limit, Stat } from './layout.ts'
21import { previewModel } from './preview.ts'
22
23const session = atom({ plugin: 'crabarium', key: 'session' } as const, initialSession, { shape: SESSION_SHAPE })
24const agents = atom({ plugin: 'crabarium', key: 'agents' } as const, initialAgents)
25const usage = atom({ plugin: 'crabarium', key: 'usage' } as const, initialUsage)
26const settings = atom({ plugin: 'crabarium', key: 'settings' } as const, initialSettings)
27const packFiles = atom({ plugin: 'crabarium', key: 'packFiles' } as const, NO_PACK_FILES)
28const preview = atom({ plugin: 'crabarium', key: 'preview' } as const, null)
29
30/** The mark and the theme color of each status. Pending, idle and waiting are all quiet. */
31const STATUS_MARK: Readonly<Record<AgentStatus, { mark: string; color: ThemeKey }>> = {
32 pending: { mark: '○', color: 'inactive' },
33 running: { mark: '●', color: 'claude' },
34 waiting: { mark: '◐', color: 'inactive' },
35 idle: { mark: '○', color: 'inactive' },
36 completed: { mark: '✓', color: 'success' },
37 failed: { mark: '✗', color: 'error' },
38 killed: { mark: '⊘', color: 'warning' },
39}
40
41const FOLDED_STATUSES = ['completed', 'failed', 'killed'] as const satisfies readonly (keyof Folded & AgentStatus)[]
42
43/** The cards and the one-column gaps between them fill the body. */
44function cardWidth(columns: number, count: number): number {
45 return Math.floor((columns - (count - 1)) / count)
46}
47
48// A narrow line cuts from the end, so the three values come first and the details after them.
49function statsLine(stats: readonly Stat[]): string {
50 return [...stats.map(s => `${s.label} ${s.value ?? '—'}`), ...stats.flatMap(s => (s.detail === undefined ? [] : [s.detail]))].join(' · ')
51}
52
53function limitsLine(limits: readonly Limit[]): string {
54 return `limits ${limits.map(l => `${l.name} ${l.used}`).join(' · ')}`
55}
56
57/** The two elements that every surface has, which the row helpers draw with. */
58type Ui = Pick<Elements['terminal'], 'Box' | 'Text'>
59
60function status({ Text }: Ui, l: AgentLine) {
61 const { mark, color } = STATUS_MARK[l.status]
62 return <Text color={color}>{` ${mark} ${l.status}`}</Text>
63}
64
65// A tree guide two lines high: the connector, then the line that goes on down (or space).
66function guide({ Box, Text }: Ui, first: string, rest: string) {
67 return (
68 <Box flexDirection="column" width={2} flexShrink={0}>
69 <Text dimColor>{first}</Text>
70 <Text dimColor>{rest}</Text>
71 </Box>
72 )
73}
74
75function folded({ Box, Text }: Ui, f: Folded) {
76 return (
77 <Box>
78 <Text dimColor>└ </Text>
79 {FOLDED_STATUSES.filter(st => f[st] > 0).map((st, i) => (
80 <Text key={st} color={STATUS_MARK[st].color}>{`${i > 0 ? ' ' : ''}${STATUS_MARK[st].mark} ${f[st]}`}</Text>
81 ))}
82 <Text dimColor>{` ${f.agents} ended ${f.agents === 1 ? 'subagent' : 'subagents'}`}</Text>
83 </Box>
84 )
85}
86
87export function registerPane(on: On, mode: MotionMode): void {
88 on('ui.render', { component: 'Pane', requestId: PANE_ID }, async ($, e) => {
89 const ui = $.ui.resolve(e)
90 const { Box, Text } = ui
91 // The terminal draws the characters with half blocks; other surfaces get them with the Svg renderer.
92 const raster = e.surface === 'terminal' ? $.ui.resolve(e).Raster : undefined
93 const columns = e.props.bodyColumns
94 const [s, board, u, now, config, files, shownPreview] = await Promise.all([
95 read($, session),
96 read($, agents),
97 read($, usage),
98 $.clock.now(),
99 read($, settings),
100 read($, packFiles),
101 read($, preview),
102 ])
103 const layout = paneLayout(board, s, u, now, columns, raster !== undefined)
104 const entries = packEntries(builtinPacks, files)
105 const active = activePack(entries, config.pack, fallbackPack())
106 const choice = { mode: config.avatarMode, rules: parseRules(config.avatarRules).rules }
107 const rows = new Map(board.rows.map(r => [r.id, r]))
108 const agentCharacters = layout.characters.flatMap(({ id, size }): DrawnCharacter[] => {
109 const row = rows.get(id)
110 if (row === undefined) return []
111 const { role, parts } = selectOutfit(active.pack, { id, type: row.type, description: row.description }, choice)
112 return [{ id, size, row, look: { pack: active.pack, rules: active.rules, role, parts } }]
113 })
114 const shown = previewModel(entries, shownPreview, now, layout.steps.character ? 'full' : null)
115 // A preview hides the agents, so their Rasters are not mounted: a blit to one would stop the loop.
116 const characters = shown === null ? agentCharacters : shown.characters
117 // The current frames, so that a redraw continues each motion and does not start it again.
118 const plan = raster === undefined ? null : framePlan(characters, now, mode)
119 if (plan !== null) framesDrawn($, mode, characters, plan, now)
120
121 const character = (id: string) => {
122 const image = plan?.images.get(id)
123 if (raster === undefined || image === undefined) return null
124 // A Raster paints all its columns even where the layout gives it fewer. So
125 // its column has a fixed width and does not shrink; the text gives way.
126 return (
127 <Box width={image.columns} flexShrink={0} marginRight={1}>
128 {h(raster, { key: avatarKey(id), ...image })}
129 </Box>
130 )
131 }
132
133 // Line 1: the description and the status. Line 2: the detail, indented when no character shows.
134 const text = (l: AgentLine) => (
135 <Box flexDirection="column" flexGrow={1} flexShrink={1}>
136 <Box>
137 <Box flexGrow={1} flexShrink={1}>
138 <Text wrap="truncate-end">{l.description}</Text>
139 </Box>
140 {status(ui, l)}
141 </Box>
142 <Text dimColor wrap="truncate-end">
143 {l.character === null ? ` ${l.detail}` : l.detail}
144 </Text>
145 </Box>
146 )
147
148 // A group heading: the title, a count, and a rule to the edge.
149 const heading = (title: string, count: string) => (
150 <Box>
151 <Text weight="semibold">{title}</Text>
152 <Text dimColor>{count}</Text>
153 <Text dimColor wrap="truncate">
154 {'─'.repeat(Math.max(0, columns - title.length - count.length))}
155 </Text>
156 </Box>
157 )
158
159 const { header, steps } = layout
160 // The limits card shows only when there are limits; the cards share the width.
161 const width = cardWidth(columns, header.stats.length + (header.limits.length > 0 ? 1 : 0))
162 return (
163 <Box flexDirection="column">
164 <Box>
165 <Text weight="semibold">Main session</Text>
166 <Text dimColor wrap="truncate-end">{` ${[header.model, `context ${header.context}`, ...header.live].join(' · ')}`}</Text>
167 </Box>
168 {steps.cards ? (
169 <Box gap={1}>
170 {header.stats.map(stat => (
171 <Box key={stat.label} borderStyle="round" borderDimColor flexDirection="column" width={width} paddingX={1}>
172 <Text dimColor wrap="truncate-end">
173 {stat.label}
174 </Text>
175 {stat.value === null ? (
176 <Text dimColor>—</Text>
177 ) : (
178 <Text weight="semibold" wrap="truncate-end">
179 {stat.value}
180 </Text>
181 )}
182 <Text dimColor wrap="truncate-end">
183 {stat.detail ?? ''}
184 </Text>
185 </Box>
186 ))}
187 {header.limits.length > 0 && (
188 // One line for each window, so a name never parts from its percent.
189 <Box key="limits" borderStyle="round" borderDimColor flexDirection="column" width={width} paddingX={1}>
190 <Text dimColor>limits</Text>
191 {header.limits.map(l => (
192 <Text key={l.name} wrap="truncate-end">
193 <Text dimColor>{`${l.name} `}</Text>
194 <Text weight="semibold">{l.used}</Text>
195 </Text>
196 ))}
197 </Box>
198 )}
199 </Box>
200 ) : (
201 <Box flexDirection="column">
202 <Text wrap="truncate-end">{statsLine(header.stats)}</Text>
203 {header.limits.length > 0 && <Text wrap="truncate-end">{limitsLine(header.limits)}</Text>}
204 </Box>
205 )}
206 {active.problem !== null && (
207 <Text color="warning" wrap="truncate-end">
208 {`${active.problem}; the pane shows ${active.name}`}
209 </Text>
210 )}
211 {shown !== null ? (
212 // A preview takes the place of the agents until it ends.
213 <Box flexDirection="column" marginTop={1}>
214 {heading(shown.title, ' ')}
215 {shown.problem !== null && (
216 <Text color="warning" wrap="truncate-end">
217 {shown.problem}
218 </Text>
219 )}
220 {shown.lines.map(l => (
221 <Box key={l.id} alignItems="center">
222 {character(l.id)}
223 {text(l)}
224 </Box>
225 ))}
226 </Box>
227 ) : null}
228 {(shown === null ? layout.groups : []).map(group => {
229 return (
230 <Box key={group.title} flexDirection="column" marginTop={1}>
231 {heading(group.title, ` ${group.agents} `)}
232 {group.trees.map((tree, i) => (
233 <Box key={tree.root.id} flexDirection="column" marginTop={i > 0 && !steps.character ? 1 : 0}>
234 <Box alignItems="center">
235 {character(tree.root.id)}
236 {text(tree.root)}
237 </Box>
238 {tree.children.map((child, j) => {
239 const isLast = j === tree.children.length - 1 && tree.folded === null
240 return (
241 <Box key={child.id}>
242 {guide(ui, isLast ? '└ ' : '├ ', isLast ? ' ' : '│ ')}
243 {character(child.id)}
244 {text(child)}
245 </Box>
246 )
247 })}
248 {tree.folded !== null && folded(ui, tree.folded)}
249 </Box>
250 ))}
251 </Box>
252 )
253 })}
254 {shown === null && layout.earlier > 0 && <Text dimColor>{`+ ${layout.earlier} earlier`}</Text>}
255 </Box>
256 )
257 })
258
259 // An observer: if it fails, the close goes on.
260 on('ui.close', { id: PANE_ID }, (_$, e, next) => {
261 stopFrames()
262 return next(e)
263 }).catch((_$, e, next) => next(e))
264}
265hooks/commands.ts 148 lines1// `/crabarium pack ...`: list, select, reload, check and preview packs. The
2// text of each answer is pure and tested; the rest reads and writes state.
3import { atom, read, update } from 'claude-code'
4import type { EngineInterface } from 'claude-code'
5
6import { parseRules } from './core/avatar/select.ts'
7import type { RuleError } from './core/avatar/select.ts'
8import { initialSettings } from './core/avatar/settings.ts'
9import type { AvatarSettings } from './core/avatar/settings.ts'
10import { packEntries, RESERVED } from './core/pack/registry.ts'
11import type { PackEntry, PackFiles } from './core/pack/registry.ts'
12import { builtinPacks } from './packs.generated.ts'
13import { NO_PACK_FILES, samePackFiles, scanPacks } from './packs.ts'
14import { PREVIEW_MS } from './view/preview.ts'
15
16const settings = atom({ plugin: 'crabarium', key: 'settings' } as const, initialSettings)
17const packFiles = atom({ plugin: 'crabarium', key: 'packFiles' } as const, NO_PACK_FILES)
18const preview = atom({ plugin: 'crabarium', key: 'preview' } as const, null)
19
20/** Reads the user packs again, and writes the state only when a file changed. */
21export async function refreshPacks($: EngineInterface): Promise<PackFiles> {
22 const old = await read($, packFiles)
23 const next = await scanPacks($, old)
24 if (!samePackFiles(old, next)) await update($, packFiles, () => next)
25 return next
26}
27
28function errorCount(entry: PackEntry): number {
29 return entry.result.ok ? 0 : entry.result.errors.length
30}
31
32function plural(n: number, word: string): string {
33 return `${n} ${word}${n === 1 ? '' : 's'}`
34}
35
36/** The answer of `/crabarium pack`: each pack, which one is active, and where user packs go. */
37export function packListText(entries: readonly PackEntry[], active: string, dir: string | null, ruleErrors: readonly RuleError[]): string {
38 const lines = entries.map(e => {
39 const mark = e.name === active ? '●' : ' '
40 const state = e.result.ok ? '' : ` · not valid (${plural(errorCount(e), 'error')}): /crabarium pack check ${e.name}`
41 return `${mark} ${e.name} (${e.source})${state}`
42 })
43 if (!entries.some(e => e.name === active)) lines.push(` ${active} is selected, but it is not installed`)
44 lines.push(dir === null ? 'User packs: no home directory found.' : `User packs: ${dir}/<name>/pack.json`)
45 if (ruleErrors.length > 0) lines.push(`avatarRules: ${plural(ruleErrors.length, 'rule')} cannot be read: /crabarium pack check`)
46 return lines.join('\n')
47}
48
49/** The answer of `/crabarium pack check <name>`: each error by field, or a summary of a valid pack. */
50export function checkText(entry: PackEntry | undefined, name: string, ruleErrors: readonly RuleError[]): string {
51 const lines: string[] = []
52 if (entry === undefined) {
53 lines.push(`No pack ${JSON.stringify(name)}.`)
54 } else if (!entry.result.ok) {
55 lines.push(`${entry.name} (${entry.source}) is not valid:`)
56 for (const error of entry.result.errors) lines.push(` ${error.path}: ${error.message}`)
57 } else {
58 const { pack } = entry.result
59 const parts = Object.values(pack.parts ?? {}).reduce((n, named) => n + Object.keys(named).length, 0)
60 const roles = Object.keys(pack.roles ?? {})
61 lines.push(
62 `${entry.name} (${entry.source}) is valid: ${plural(Object.keys(pack.groups).length, 'group')}, ${plural(parts, 'part')}, ` +
63 `${plural(Object.keys(pack.motions ?? {}).length, 'motion')}, roles: ${roles.length === 0 ? 'none' : roles.join(', ')}.`,
64 )
65 }
66 for (const error of ruleErrors) lines.push(`avatarRules: ${JSON.stringify(error.rule)} ${error.message}`)
67 return lines.join('\n')
68}
69
70// The `/config` key of a field of this plugin's `userConfig`: `<plugin>.<field>`,
71// where the plugin part can carry a suffix (`@inline` for a --plugin-dir mod).
72async function configKey($: EngineInterface, field: string): Promise<string | undefined> {
73 const rows = await $.config.list()
74 return rows.find(r => r.provider.plugin === $.plugin.name && r.key.endsWith(`.${field}`))?.key
75}
76
77/** What a pack command needs from its caller: opening the pane, for a preview. */
78export type PackCommandContext = { openPane: () => Promise<void> }
79
80async function select($: EngineInterface, name: string): Promise<string> {
81 const entries = packEntries(builtinPacks, await refreshPacks($))
82 const entry = entries.find(e => e.name === name)
83 if (entry === undefined) return `No pack ${JSON.stringify(name)}. Packs: ${entries.map(e => e.name).join(', ')}.`
84 if (!entry.result.ok) return `${name} is not valid, so it stays unselected: /crabarium pack check ${name}`
85 const key = await configKey($, 'pack')
86 if (key === undefined) return 'crabarium cannot find its pack setting in /config.'
87 const result = await $.config.set({ key, value: name })
88 if (result.deny !== undefined) return `The pack setting did not change: ${result.deny}`
89 // The plugin's own `config.set` hook does not see its own change.
90 await update($, settings, s => ({ ...s, pack: name }))
91 return `crabarium pack: ${name}`
92}
93
94/** Runs `/crabarium pack <args>` and gives the text to show. */
95export async function runPackCommand($: EngineInterface, args: readonly string[], context: PackCommandContext): Promise<string> {
96 const [sub, name, ...extra] = args
97 const config = await read($, settings)
98 const { errors } = parseRules(config.avatarRules)
99 if (extra.length > 0 || (sub !== undefined && !RESERVED.includes(sub) && name !== undefined)) {
100 return 'Usage: /crabarium pack [<name> | reload | check [<name>] | preview [<name>]]'
101 }
102 switch (sub) {
103 case undefined:
104 case 'reload': {
105 const files = await refreshPacks($)
106 return packListText(packEntries(builtinPacks, files), config.pack, files.dir, errors)
107 }
108 case 'check': {
109 const target = name ?? config.pack
110 const entries = packEntries(builtinPacks, await refreshPacks($))
111 return checkText(
112 entries.find(e => e.name === target),
113 target,
114 errors,
115 )
116 }
117 case 'preview': {
118 if (name === undefined) {
119 await update($, preview, () => null)
120 return 'The preview ended.'
121 }
122 const entry = packEntries(builtinPacks, await refreshPacks($)).find(e => e.name === name)
123 if (entry === undefined) return `No pack ${JSON.stringify(name)}.`
124 if (!entry.result.ok) return `${name} is not valid: /crabarium pack check ${name}`
125 const now = await $.clock.now()
126 await update($, preview, () => ({ pack: name, startedAt: now, until: now + PREVIEW_MS }))
127 await context.openPane()
128 return `Preview of ${name} for ${PREVIEW_MS / 1000} s. /crabarium pack preview ends it.`
129 }
130 default:
131 return select($, sub)
132 }
133}
134
135/** Updates a setting when the user changes this plugin's row in `/config`. */
136export async function settingChanged($: EngineInterface, key: string, value: unknown): Promise<void> {
137 const field = key.slice(key.lastIndexOf('.') + 1)
138 const change: Partial<AvatarSettings> | null =
139 field === 'pack' && typeof value === 'string'
140 ? { pack: value.trim() === '' ? initialSettings.pack : value.trim() }
141 : field === 'avatarMode' && (value === 'off' || value === 'keywords')
142 ? { avatarMode: value }
143 : field === 'avatarRules' && typeof value === 'string'
144 ? { avatarRules: value }
145 : null
146 if (change !== null) await update($, settings, s => ({ ...s, ...change }))
147}
148hooks/core/agents.ts 94 lines1// The subagents as the pane shows them. Pure: no engine calls; times come in
2// with the events.
3import type { AgentBoard, AgentRow, AgentStatus } from '../../types'
4
5export type { AgentBoard, AgentRow, AgentStatus }
6
7/** How a turn ended, as `turn.complete` gives it. */
8export type TurnEndReason = 'answer' | 'aborted' | 'refusal' | 'error'
9
10export type AgentEvent =
11 | {
12 kind: 'agent-spawned'
13 id: string
14 description: string
15 type: string
16 model: string
17 parentId: string | null
18 isTeammate: boolean
19 at: number
20 }
21 | { kind: 'agents-listed'; statuses: ReadonlyArray<{ id: string; status: AgentStatus }>; at: number }
22 | { kind: 'agent-turn-ended'; id: string; reason: TurnEndReason; at: number }
23
24export const initialAgents: AgentBoard = { now: null, rows: [] }
25
26const ENDED: ReadonlySet<AgentStatus> = new Set(['completed', 'failed', 'killed'])
27
28export function isEnded(status: AgentStatus): boolean {
29 return ENDED.has(status)
30}
31
32const STATUS_OF_TURN_END: Readonly<Record<TurnEndReason, AgentStatus>> = {
33 answer: 'completed',
34 aborted: 'killed',
35 refusal: 'failed',
36 error: 'failed',
37}
38
39// An ended agent starts again only through a new spawn (a resume). The list
40// can still say `running` for a moment after the turn end, so a list status
41// does not reopen an ended row; it can only correct how the row ended.
42function withStatus(row: AgentRow, status: AgentStatus, at: number): AgentRow {
43 if (row.status === status) return row
44 if (isEnded(row.status)) return isEnded(status) ? { ...row, status, statusAt: at } : row
45 return { ...row, status, statusAt: at, endedAt: isEnded(status) ? at : null }
46}
47
48function mapRows(rows: readonly AgentRow[], fn: (row: AgentRow) => AgentRow): readonly AgentRow[] {
49 const next = rows.map(fn)
50 return next.every((row, i) => row === rows[i]) ? rows : next
51}
52
53export function reduceAgents(state: AgentBoard, event: AgentEvent): AgentBoard {
54 switch (event.kind) {
55 case 'agent-spawned': {
56 const { kind: _kind, at, ...fields } = event
57 const row: AgentRow = { ...fields, status: 'running', statusAt: at, startedAt: at, endedAt: null }
58 const rest = state.rows.filter(r => r.id !== event.id)
59 return { now: at, rows: [...rest, row] }
60 }
61 case 'agents-listed': {
62 const byId = new Map(event.statuses.map(s => [s.id, s.status]))
63 const rows = mapRows(state.rows, row => {
64 const status = byId.get(row.id)
65 return status === undefined ? row : withStatus(row, status, event.at)
66 })
67 // `now` only moves durations; with no live row it changes nothing shown.
68 if (rows === state.rows && !rows.some(r => !isEnded(r.status))) return state
69 return { now: event.at, rows }
70 }
71 case 'agent-turn-ended': {
72 const rows = mapRows(state.rows, row =>
73 row.id === event.id && !row.isTeammate ? withStatus(row, STATUS_OF_TURN_END[event.reason], event.at) : row,
74 )
75 return rows === state.rows ? state : { now: event.at, rows }
76 }
77 }
78}
79
80/**
81 * Milliseconds the agent has run, or `null` before the first read of the time.
82 *
83 * A live row can show a different value than a `subagentStatusLine` row for the
84 * same agent. The status line computes its time from the engine's task
85 * `startTime`, and it refreshes on its own interval (some seconds). The mod API
86 * does not give `startTime`, so `startedAt` is the time the spawn hook ends, and
87 * the pane moves `now` each second. So the status line can show a smaller value
88 * until its next refresh. A finished row agrees with the engine's duration to the second.
89 */
90export function durationMs(row: AgentRow, now: number | null): number | null {
91 const end = row.endedAt ?? now
92 return end === null ? null : Math.max(0, end - row.startedAt)
93}
94hooks/core/session.ts 122 lines1// The main session as the pane shows it. Pure: no engine calls, no clock.
2import type { CacheUse, MainSession, PromptCache, RateLimit, TimedStep } from '../../types'
3
4export type { CacheUse, MainSession, PromptCache, RateLimit, TimedStep }
5
6export type SessionEvent =
7 | { kind: 'model-used'; model: string }
8 | {
9 kind: 'usage-read'
10 contextPercent: number | null
11 costUsd: number | null
12 startedAt: number
13 rateLimits: readonly RateLimit[]
14 /** `null` when the engine did not answer. */
15 turns: number | null
16 at: number
17 }
18 /** The user sent a prompt, at this session cost. */
19 | { kind: 'prompt-sent'; costUsd: number | null }
20 /**
21 * A main-session request answered. `model` is the model that the request
22 * named; `sentAt` is when the engine sent it; `cacheUsed` says that it read
23 * or wrote the prompt cache. `step` is `null` when no output came.
24 */
25 | { kind: 'step-timed'; step: TimedStep | null; model: string; sentAt: number; cacheUsed: boolean }
26 /** The model changed. The new model has no cache yet. `cacheTtlMs` is `null` for a TTL the mod does not know. */
27 | { kind: 'model-switched'; model: string; cacheTtlMs: number | null }
28 /** A `/clear` started a new conversation, or a resume put an old one in its place. */
29 | { kind: 'conversation-replaced' }
30
31export const initialSession: MainSession = {
32 model: null,
33 contextPercent: null,
34 costUsd: null,
35 startedAt: null,
36 readAt: null,
37 rateLimits: [],
38 turns: null,
39 turnBaseCost: null,
40 lastStep: null,
41 cache: { ttlMs: null, model: null, use: { kind: 'unknown' } },
42}
43
44const CACHE_TTL_MS: Readonly<Record<string, number>> = { '5m': 5 * 60_000, '1h': 60 * 60_000 }
45
46/** The TTL that the engine names, in milliseconds; `null` for a name that the mod does not know. */
47export function cacheTtlMs(name: string): number | null {
48 return CACHE_TTL_MS[name] ?? null
49}
50
51// A request refreshes the cache entry when the API reads the prompt, before
52// the first output token. So the countdown counts from the send: it can end
53// early, but never late.
54function cacheAfterStep(cache: PromptCache, model: string, sentAt: number, cacheUsed: boolean): PromptCache {
55 // A request to another model (a fallback, or one that a hook sent elsewhere) uses another cache.
56 if (!cacheUsed || (cache.model !== null && cache.model !== model)) return cache
57 return { ...cache, use: { kind: 'used', at: sentAt } }
58}
59
60export function reduceSession(state: MainSession, event: SessionEvent): MainSession {
61 switch (event.kind) {
62 case 'model-used':
63 return state.model === event.model ? state : { ...state, model: event.model }
64 case 'usage-read': {
65 const { kind: _kind, at, ...usage } = event
66 return { ...state, ...usage, readAt: at }
67 }
68 case 'prompt-sent':
69 // The cost comes from the same read as the base, so the turn cost never mixes an old cost with a new base.
70 return { ...state, costUsd: event.costUsd, turnBaseCost: event.costUsd }
71 case 'step-timed':
72 return {
73 ...state,
74 lastStep: event.step ?? state.lastStep,
75 cache: cacheAfterStep(state.cache, event.model, event.sentAt, event.cacheUsed),
76 }
77 case 'model-switched':
78 return { ...state, cache: { ttlMs: event.cacheTtlMs, model: event.model, use: { kind: 'cold' } } }
79 case 'conversation-replaced':
80 // The TTL is the session's setting, so it stays. Whether the cache is
81 // still warm is not known: a resume can come back within the TTL, and
82 // a /clear keeps the system prompt. The next request tells.
83 return {
84 ...state,
85 costUsd: null,
86 turnBaseCost: null,
87 lastStep: null,
88 cache: { ...state.cache, use: { kind: 'unknown' } },
89 }
90 }
91}
92
93/** The cost since the user's last prompt, subagents included; `null` when it is not known. */
94export function turnCost(s: MainSession): number | null {
95 if (s.costUsd === null || s.turnBaseCost === null) return null
96 const cost = s.costUsd - s.turnBaseCost
97 // Below the base, the cost started again under the mod (a /clear it did not see).
98 return cost < 0 ? null : cost
99}
100
101/** The output tokens per second of the last request; `null` before it, or when it took no time. */
102export function tokensPerSecond(step: TimedStep | null): number | null {
103 return step === null || step.ms <= 0 ? null : step.outputTokens / (step.ms / 1000)
104}
105
106/**
107 * The time until the prompt cache expires: 0 when it is cold, `null` when it
108 * is not known. The mod does not guess: a wrong countdown would be worse than
109 * none.
110 */
111export function cacheLeftMs(cache: PromptCache, now: number): number | null {
112 if (cache.ttlMs === null) return null
113 switch (cache.use.kind) {
114 case 'unknown':
115 return null
116 case 'cold':
117 return 0
118 case 'used':
119 return Math.max(0, cache.use.at + cache.ttlMs - now)
120 }
121}
122hooks/core/usage/usage.ts 81 lines1// The usage of each agent loop, summed over its model requests. Pure: the
2// request figures come in with the events.
3//
4// The counts are the API's own, request by request; only the sums are the
5// mod's. Two limits: a hook beneath the mod that sends a request again shows
6// the mod only the last answer, and a resumed session starts the sums at zero
7// while the engine's cost keeps the earlier part. There is no cost per agent:
8// see the note in ./models.ts.
9import type { AgentUsage, LastRequest, TokenSums, UsageBoard } from '../../../types'
10import { contextWindowOf, promptTokens } from './models.ts'
11
12export type { AgentUsage, LastRequest, TokenSums, UsageBoard }
13
14/** One model request that answered: whose loop, which model, how hard, and what it used. */
15export type StepFinished = {
16 kind: 'step-finished'
17 /** `null` for the main session. */
18 agentId: string | null
19 /** The model that answered, by the id the API reports. */
20 model: string
21 effort: string | null
22 tokens: TokenSums
23}
24
25/** A conversation ended (`/clear`, or a resume took its place): the sums start again. */
26export type UsageReset = { kind: 'usage-reset' }
27
28export type UsageEvent = StepFinished | UsageReset
29
30export const initialUsage: UsageBoard = { main: null, agents: {} }
31
32const NO_TOKENS: TokenSums = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }
33
34function add(a: TokenSums, b: TokenSums): TokenSums {
35 return {
36 input: a.input + b.input,
37 output: a.output + b.output,
38 cacheRead: a.cacheRead + b.cacheRead,
39 cacheWrite: a.cacheWrite + b.cacheWrite,
40 }
41}
42
43// A resume of an agent keeps its key, so its sums go on: they describe the
44// agent's whole life, while its row's duration starts again.
45export function reduceUsage(state: UsageBoard, event: UsageEvent): UsageBoard {
46 if (event.kind === 'usage-reset') return initialUsage
47 if (event.agentId === null) return { ...state, main: add(state.main ?? NO_TOKENS, event.tokens) }
48 const last: LastRequest = { promptTokens: promptTokens(event.tokens), model: event.model, effort: event.effort }
49 const before = state.agents[event.agentId]?.tokens ?? NO_TOKENS
50 const agent: AgentUsage = { tokens: add(before, event.tokens), last }
51 return { ...state, agents: { ...state.agents, [event.agentId]: agent } }
52}
53
54/**
55 * The tokens that the requests added: the uncached input, the cache writes,
56 * and the output. Cache reads are left out: each request reads the whole
57 * cached context again, so in a long session they would be most of a sum that
58 * says little about the work. `cacheHitRate` tells how much they were.
59 */
60export function newTokens(t: TokenSums): number {
61 return t.input + t.cacheWrite + t.output
62}
63
64/** The share of all input that the prompt cache served, 0 to 100; `null` before any input. */
65export function cacheHitRate(t: TokenSums): number | null {
66 const input = t.input + t.cacheRead + t.cacheWrite
67 return input === 0 ? null : (t.cacheRead / input) * 100
68}
69
70/** The sums of the main session and every agent together; `null` before the first request. */
71export function sessionSums(board: UsageBoard): TokenSums | null {
72 const sums = [...(board.main === null ? [] : [board.main]), ...Object.values(board.agents).map(a => a.tokens)]
73 return sums.length === 0 ? null : sums.reduce(add, NO_TOKENS)
74}
75
76/** The last prompt over its model's context window, 0 to 100; `null` when the window is unknown. */
77export function contextPercent(last: LastRequest): number | null {
78 const window = contextWindowOf(last.model)
79 return window === null ? null : (last.promptTokens / window) * 100
80}
81hooks/core/version.ts 22 lines1// Function hooks are an early-access API: the mod runs only on engine
2// versions it was tested against.
3export const MIN_ENGINE_VERSION = '2.1.300'
4
5type Triple = readonly [number, number, number]
6
7function parse(version: string): Triple | null {
8 const match = /^(\d+)\.(\d+)\.(\d+)/.exec(version)
9 if (!match) return null
10 return [Number(match[1]), Number(match[2]), Number(match[3])]
11}
12
13// A development build of a release (`2.1.300-dev`) counts as that release.
14// A version that does not parse is not supported.
15export function isSupportedEngine(version: string, minimum: string = MIN_ENGINE_VERSION): boolean {
16 const have = parse(version)
17 const need = parse(minimum)
18 if (!have || !need) return false
19 const order = have[0] - need[0] || have[1] - need[1] || have[2] - need[2]
20 return order >= 0
21}
22hooks/state.ts 12 lines1// The engine's state scan reads each `$.state` reference in the file that
2// uses it, so each user declares its atom itself; types/index.d.ts holds them
3// to one contract.
4export const PANE_ID = 'crabarium'
5
6/**
7 * The shape tag of the session value. A hot reload keeps `$.state`, so a
8 * change to `MainSession` takes a new tag: the new code then reads the old
9 * value as absent and starts from the initial one.
10 */
11export const SESSION_SHAPE = 'session-2'
12hooks/core/avatar/select.ts 223 lines1// Avatar selection: which outfit an agent wears. Pure: the pack, the agent
2// and the settings come in as arguments.
3//
4// The sources give a role or outfits, and the pack gives the parts. A role is
5// a closed set, so the same keyword and type tables work for each pack, and a
6// classifier (a later source) answers one choice over the roles. The sources
7// go in priority order and the first valid result wins; no source mixes
8// scores with another.
9import { own } from '../own.ts'
10import { partOf } from '../pack/pack.ts'
11import type { Outfit, Pack, PartSelection, Role } from '../pack/pack.ts'
12import { ROLES } from '../pack/schema.ts'
13
14/** `off` turns off the automatic sources (keywords, type defaults). User rules still apply. */
15export type AvatarMode = 'off' | 'keywords'
16
17const AVATAR_MODES: readonly unknown[] = ['off', 'keywords'] satisfies AvatarMode[]
18
19function isAvatarMode(option: unknown): option is AvatarMode {
20 return AVATAR_MODES.includes(option)
21}
22
23/** The `avatarMode` option. The engine gives only the manifest's values, so another value is a bug; it falls back to `keywords`. */
24export function avatarMode(option: unknown): AvatarMode {
25 return isAvatarMode(option) ? option : 'keywords'
26}
27
28/** What the selector reads of an agent. */
29export type AgentInfo = { id: string; type: string; description: string }
30
31/** What a rule gives: a role, which the pack dresses, or outfits by part name. */
32export type Target = { kind: 'role'; role: Role } | { kind: 'outfits'; outfits: readonly Outfit[] }
33
34export type Rule = { pattern: string; target: Target }
35
36export type RuleError = { rule: string; message: string }
37
38/** Where a choice came from. */
39export type Source = 'rule' | 'keywords' | 'type' | 'default'
40
41export type Choice = { source: Source; role: Role | null; parts: PartSelection }
42
43const PART_NAME = /^[a-zA-Z][a-zA-Z0-9-]{0,31}$/
44
45export function isRole(text: string): text is Role {
46 return (ROLES as readonly string[]).includes(text)
47}
48
49function parseOutfit(text: string): Outfit | string {
50 const outfit = text.trim()
51 const [body = '', weightText, ...rest] = outfit.split('*')
52 if (rest.length > 0) return `${JSON.stringify(outfit)} has more than one "*"`
53 // Digits only: Number() would also take 1e2, 0x10 and 1.0.
54 const weight = weightText === undefined ? 1 : /^\s*\d{1,3}\s*$/.test(weightText) ? Number(weightText) : Number.NaN
55 if (!(weight >= 1 && weight <= 100)) return `the weight in ${JSON.stringify(outfit)} is not a whole number from 1 to 100`
56 const parts: Record<string, string> = {}
57 for (const token of body.split(/\s+/).filter(t => t !== '')) {
58 const [slot = '', part = '', ...more] = token.split(':')
59 if (more.length > 0 || !PART_NAME.test(slot) || !PART_NAME.test(part)) return `${JSON.stringify(token)} is not slot:part`
60 if (Object.hasOwn(parts, slot)) return `${JSON.stringify(outfit)} names the slot ${JSON.stringify(slot)} twice`
61 parts[slot] = part
62 }
63 if (Object.keys(parts).length === 0) return `${JSON.stringify(outfit)} names no part`
64 return { parts, weight }
65}
66
67/**
68 * Parses the `avatarRules` option: `pattern = target; pattern = target`. A
69 * target is a role, or outfits `slot:part slot:part*weight | ...`. A rule
70 * that does not parse is left out, with an error that names it.
71 */
72export function parseRules(text: string): { rules: readonly Rule[]; errors: readonly RuleError[] } {
73 const rules: Rule[] = []
74 const errors: RuleError[] = []
75 for (const raw of text.split(';')) {
76 const rule = raw.trim()
77 if (rule === '') continue
78 const at = rule.indexOf('=')
79 const pattern = at < 0 ? '' : rule.slice(0, at).trim().toLowerCase()
80 const target = at < 0 ? '' : rule.slice(at + 1).trim()
81 if (at < 0 || pattern === '' || /\s/.test(pattern) || target === '') {
82 errors.push({ rule, message: 'is not "pattern = target"' })
83 continue
84 }
85 if (isRole(target)) {
86 rules.push({ pattern, target: { kind: 'role', role: target } })
87 continue
88 }
89 const parsed = target.split('|').map(parseOutfit)
90 const bad = parsed.find(o => typeof o === 'string')
91 if (bad !== undefined) {
92 errors.push({ rule, message: `${bad}, and ${JSON.stringify(target)} is not a role (${ROLES.join(', ')})` })
93 continue
94 }
95 const outfits = parsed.filter((o): o is Outfit => typeof o !== 'string')
96 rules.push({ pattern, target: { kind: 'outfits', outfits } })
97 }
98 return { rules, errors }
99}
100
101/** The words of a description, lower case. A hyphenated word stays one word: a rule pattern can name it. */
102function wordsOf(description: string): readonly string[] {
103 return description
104 .toLowerCase()
105 .split(/[^a-z0-9-]+/)
106 .filter(w => w !== '')
107}
108
109/**
110 * The stem of a word, so that a keyword matches its common forms: review,
111 * reviews, reviewing, reviewer; write, writing; plan, planner, planning. It
112 * cuts one ending (when three letters stay), then a doubled last consonant,
113 * then a last "e".
114 */
115export function stem(word: string): string {
116 let w = word.toLowerCase()
117 const ending = ['ings', 'ing', 'ers', 'er', 'ed', 'es', 's'].find(e => w.endsWith(e) && w.length - e.length >= 3)
118 if (ending !== undefined) w = w.slice(0, -ending.length)
119 if (/([b-df-hj-np-tv-z])\1$/.test(w)) w = w.slice(0, -1)
120 return w.endsWith('e') && w.length > 3 ? w.slice(0, -1) : w
121}
122
123// The verbs that tell a role. The first one in a description gives the role,
124// as the verb leads a task ("Review the loop").
125const KEYWORDS: Readonly<Record<Role, readonly string[]>> = {
126 explorer: ['explore', 'find', 'search', 'locate', 'read', 'list', 'grep', 'scan', 'map', 'trace'],
127 reviewer: ['review', 'audit', 'critique', 'inspect'],
128 builder: ['write', 'implement', 'build', 'fix', 'refactor', 'add', 'create', 'update', 'change', 'port', 'migrate'],
129 tester: ['test', 'verify', 'check', 'validate', 'reproduce', 'measure'],
130 planner: ['plan', 'design', 'outline', 'decide', 'draft'],
131 researcher: ['research', 'fetch', 'docs', 'documentation', 'web', 'summarize', 'compare'],
132}
133
134const ROLE_OF_STEM: ReadonlyMap<string, Role> = new Map(ROLES.flatMap(role => KEYWORDS[role].map(k => [stem(k), role] as const)))
135
136/** The role of the first keyword in `words`. A hyphenated word counts as its parts: code-review has review. */
137function keywordRole(words: readonly string[]): Role | null {
138 for (const word of words.flatMap(w => w.split('-'))) {
139 const role = ROLE_OF_STEM.get(stem(word))
140 if (role !== undefined) return role
141 }
142 return null
143}
144
145// The agent types of Claude Code and of common plugins by their whole name.
146const TYPE_ROLES: Readonly<Record<string, Role>> = {
147 explore: 'explorer',
148 coder: 'builder',
149 oracle: 'tester',
150 architect: 'planner',
151 plan: 'planner',
152 fetcher: 'researcher',
153 'web-fetch': 'researcher',
154}
155
156/** The role of a type: by its whole name, else by the keywords among its words (linus-reviewer, docs-fetcher). */
157function typeRole(type: string): Role | null {
158 const name = type.toLowerCase()
159 return own(TYPE_ROLES, name) ?? keywordRole(name.split(/[^a-z0-9]+/).filter(w => w !== ''))
160}
161
162/** FNV-1a: a small, stable hash, so the same agent picks the same outfit at each draw. */
163function hash(text: string): number {
164 let h = 0x811c9dc5
165 for (let i = 0; i < text.length; i += 1) h = Math.imul(h ^ text.charCodeAt(i), 0x01000193) >>> 0
166 return h
167}
168
169/**
170 * One of the outfits whose parts the pack has, by weight, seeded by `seed`;
171 * `null` when none fits. An outfit fills its slots, and the pack defaults
172 * fill the others.
173 */
174export function pickOutfit(pack: Pack, outfits: readonly Outfit[], seed: string): PartSelection | null {
175 const fits = outfits.filter(o => Object.entries(o.parts).every(([slot, name]) => partOf(pack, slot, name) !== undefined))
176 const total = fits.reduce((sum, o) => sum + (o.weight ?? 1), 0)
177 if (total === 0) return null
178 let left = hash(seed) % total
179 for (const outfit of fits) {
180 left -= outfit.weight ?? 1
181 if (left < 0) return { ...pack.defaults?.parts, ...outfit.parts }
182 }
183 return null
184}
185
186function dress(pack: Pack, role: Role | null, seed: string): PartSelection | null {
187 const outfits = role === null ? undefined : pack.roles?.[role]
188 return outfits === undefined ? null : pickOutfit(pack, outfits, seed)
189}
190
191function matches(rule: Rule, agent: AgentInfo, words: readonly string[]): boolean {
192 return agent.type.toLowerCase() === rule.pattern || words.includes(rule.pattern)
193}
194
195export type Settings = { mode: AvatarMode; rules: readonly Rule[] }
196
197/**
198 * The outfit of an agent. The sources in order: the first user rule that
199 * matches; then, when the mode is `keywords`, the description keywords and
200 * the agent type; then the pack's default parts. A source whose result the
201 * pack cannot dress gives nothing, and the next source runs.
202 */
203export function selectOutfit(pack: Pack, agent: AgentInfo, settings: Settings): Choice {
204 const words = wordsOf(agent.description)
205 const rule = settings.rules.find(r => matches(r, agent, words))
206 if (rule !== undefined) {
207 const { target } = rule
208 const role = target.kind === 'role' ? target.role : null
209 const parts = target.kind === 'role' ? dress(pack, role, agent.id) : pickOutfit(pack, target.outfits, agent.id)
210 if (parts !== null) return { source: 'rule', role, parts }
211 }
212 if (settings.mode === 'keywords') {
213 for (const [source, role] of [
214 ['keywords', keywordRole(words)],
215 ['type', typeRole(agent.type)],
216 ] as const) {
217 const parts = dress(pack, role, agent.id)
218 if (parts !== null) return { source, role, parts }
219 }
220 }
221 return { source: 'default', role: null, parts: pack.defaults?.parts ?? {} }
222}
223