Anime-themed subagents: a strategist orchestrator plus backend, frontend, architecture, research, QA and docs crew, each with its own model, tools and voice…

<a href="https://img.shields.io/badge/version-0.8.0-9E62CA"><img src="https://img.shields.io/badge/version-0.8.0-9E62CA" alt="version 0.8.0"></a> <a href="https://img.shields.io/badge/Claude%20Code-plugin-9E62CA"><img src="https://img.shields.io/badge/Claude%20Code-plugin-9E62CA" alt="Claude Code plugin"></a> <a href="https://img.shields.io/badge/license-MIT-9E62CA"><img src="https://img.shields.io/badge/license-MIT-9E62CA" alt="license MIT"></a>
An anime crew for Claude Code: a strategist, seven specialists, and a terminal that shows their personality.
/plugin marketplace add shreym95/dojo
/plugin install dojo@dojo
Launch the strategist with claude --agent dojo:strategist or pin it in settings.json with "agent": "dojo:strategist". Use crew to show the on-duty persona; pass crew shikamaru or crew lelouch to pin one. Override with DOJO_STRATEGIST=shikamaru|lelouch or set DOJO_DEBUG=1 to log hook input to ${TMPDIR:-/tmp}/dojo-hook-debug.log.
<img src="docs/assets/crew.svg" alt="The dojo crew" width="100%">
| Agent | Character | Role | Model | Effort |
|---|---|---|---|---|
dojo:strategist | Shikamaru or Lelouch | Orchestrator / integrator (main thread) | claude-opus-5-5 | medium |
dojo:senku | Senku | Backend builder | claude-haiku-5-5 | medium |
dojo:sanji | Sanji | Frontend builder | claude-haiku-5-5 | medium |
dojo:kurisu | Kurisu | Solutions architect | claude-sonnet-5-5 | medium |
dojo:jiraiya | Jiraiya | Web researcher | claude-haiku-5-5 | medium |
dojo:light | Light | Quick fact-finder | claude-haiku-5-5 | low |
dojo:levi | Levi | QA inspector (read-only) | claude-haiku-5-5 | medium |
dojo:robin | Robin | Documentation writer | claude-haiku-5-5 | low |
dojo:light, replies NOT FOUND if the answer is not at hand.dojo:jiraiya, cited findings with confidence per claim.dojo:kurisu, replies NEEDS INTEL: <exact question> for research beyond targeted lookups.dojo:senku (behaviour and data) or dojo:sanji (presentation and interaction), reply BLOCKED: <question> instead of guessing.dojo:levi, read-only.dojo:robin, from existing code or decisions already made.Senku owns behaviour and data; Sanji owns presentation and interaction. The seam is a data contract.
<img src="docs/assets/terminal.svg" alt="dojo in the terminal" width="100%">
banners toggle (off by default); ASCII banners on deploy/return/fall./dojo): the crew, who is on duty and running, per-crew session stats, rank./dojo-recap): crew deployed, runs, time, tokens, last quote, who fell, final context and cost, rank, strategist sign-off./dojo-gallery): preview each character's banner, colors, animation frames, spinner verbs, signature lines, speech bubble.Co-Authored-By: Claude).model from any dojo:* agent spawn so the agent's own frontmatter model always wins.| Command | What it does | |||||
|---|---|---|---|---|---|---|
| `/dojo-duty [shikamaru\ | lelouch]` | Show or switch the strategist persona on duty. | ||||
| `/dojo-voice [subtle\ | medium\ | full\ | default\ | reset\ | off]` | Show or set the dojo voice level for this session. |
/dojo | Open the roster pane (requires rosterPane toggle on). | |||||
/dojo-recap | Open the mission report (requires rosterPane toggle on). | |||||
/dojo-gallery | Browse each character's banner, colors, spinner verbs, signature lines. |
| Key | Default | What it does |
|---|---|---|
spinners | true | Replace the spinner word with the on-duty strategist's (or crew member's) themed verbs. |
turnFlair | true | Past-tense themed word on the line that closes a turn (Outmaneuvered, Checkmated). |
band | true | Show one animated row per running dojo subagent above the prompt. |
usageLine | true | Show one row above the prompt with the session's context fill (Chakra) and the cost, plus the busiest rate-limit window (Stamina) once it passes 25%. |
toasts | true | Short in-character toast when a dojo subagent is deployed, returns or falls, and when the crew rank goes up. |
neutralMainTheme | true | When no strategist persona is detected, still theme the main spinner with a neutral strategist pool. |
commitGate | true | Force the configured commit trailer into git texts and deny git commit commands whose inline message breaks the commit rules (Conventional Commits subject, no body, exact trailer). Applies in every session. |
commitTrailer | Co-Authored-By: Claude | The exact Co-Authored-By line commits must carry. Empty keeps Claude Code's own text and skips the trailer check. |
roleGuard | true | In a dojo session, cap the main thread's inline edits and web lookups per turn and point it at dojo:senku, dojo:sanji, dojo:jiraiya or dojo:light. |
architectGuard | true | Keep dojo:kurisu's file writes out of the main working tree: Edit, Write and NotebookEdit are allowed only in the scratchpad, the system temp dir or an isolated worktree. Bash is not checked. |
inlineEditFiles | 2 | Distinct files the main thread may edit itself in one turn before it must delegate. |
inlineEditLines | 6 | Largest Edit (lines in new_string) the main thread may make itself. |
inlineLookups | 3 | WebSearch and WebFetch calls the main thread may make itself in one turn before it must delegate. |
archivist | true | In a dojo session, tell the compaction summary to keep the on-duty line, the voice level, running dojo agents with their tasks, and the user's decisions. |
transcriptTheme | true | Frame messages, tool calls and subagent results in the on-duty character's colors: persona frames on messages, tool badges, crew cards and speech bubbles. |
banners | false | Show full ASCII-banner crew cards in the transcript instead of one-line deploy/return lines. |
promptChrome | true | Tag the session mode line under the prompt with the on-duty strategist's emoji and name, in its color. |
rosterPane | true | Show the /dojo roster panel: the crew, who is on duty and who is running. |
sounds | true | Play a sound cue when a dojo subagent is deployed, returns or falls (macOS only). |
paletteMode | auto | Colors of the dojo chrome and transcript. auto follows the Claude Code theme (light when its name contains "light"); dark and light force one. Light-theme colors meet ≥4.5:1 on white; dark colors are lifted to ≥4.5:1 on black. |
rank | true | Keep a rank that grows with every dojo crew member that returns, across sessions. Shown in /dojo and /dojo-recap, with a toast on rank-up. Ladder: Shikamaru/neutral (Genin / Chūnin / Jōnin / Kage), Lelouch (Pawn / Knight / Rook / King); thresholds 0 / 25 / 100 / 300 points. |
Edit roster.mjs (characters, models, tools), personas/*.md (voice sheets), roles/*.md (duties) or shared/house-rules.md, then:
npm run build # regenerate agents/*.md
npm run check # fail if agents/ has drifted (used in CI)
npm test
agents/*.md is generated; do not edit by hand.
Visuals and art: edit mods/theme.ts for character emoji and colors; mods/visuals/transcript-art.ts for banners and speech bubbles; mods/visuals/chrome-art.ts for spinners, turn-end words, toasts, and band rows.
Validate, test and try the plugin locally:
claude plugin validate . # check the hook structure
claude plugin test . # run the mod suite
claude --plugin-dir . # try the plugin locally without installing
Persona sheets live in personas/; roles in roles/; character art in mods/visuals/.
afplay).model to dojo agents; the model guard enforces each agent's own frontmatter model.MIT
mods/register.tsx 36 lines1import type { Register } from 'claude-code'
2
3import { installArchitectGuard } from './features/architect-guard'
4import { installArchivist } from './features/archivist'
5import { installCommands } from './features/commands'
6import { installCommitGate } from './features/commit-gate'
7import { installModelGuard } from './features/model-guard'
8import { installRoleGuard } from './features/role-guard'
9import { installPersona } from './lib/persona'
10import { installRecorders } from './state/recorders'
11import { installChrome } from './visuals/chrome'
12import { installTranscript } from './visuals/transcript'
13
14// What `claude plugin validate` enforces on this module graph, and so on every installer:
15// - an event has at most one hook without a matcher (today: session.append, prompt.submit, agent.spawn in the
16// model guard, tool.call in the state recorders); every further hook on it needs a matcher: on(event, matcher, hook),
17// and several hooks may share one matcher (each runs)
18// - `$` is passed only to functions declared in the same file, never across an import
19// - an atom is read and updated only through a const of the file that uses it (the {plugin, key} pair is the shared name)
20// - events are spelled literally: on('<event>', ...)
21export const register: Register = (on, options) => {
22 installPersona(on, options)
23 installModelGuard(on, options)
24 installCommitGate(on, options)
25 installRoleGuard(on, options)
26 installArchitectGuard(on, options)
27 installArchivist(on, options)
28 installCommands(on, options)
29 installChrome(on, options)
30 installTranscript(on, options)
31 // Registered after the visuals on purpose: the first hook registered is the outermost, and a hook acts on what `next(e)`
32 // returned, so the recorders (innermost) have written their state by the time the visuals' hooks read it (the deploy toast
33 // reads the run count that the agent.spawn recorder has just bumped).
34 installRecorders(on, options)
35}
36mods/features/architect-guard.ts 79 lines1import type { EngineInterface as Engine } from 'claude-code'
2
3import { isOn } from '../lib/options'
4import type { Installer } from '../lib/options'
5import { toastLine } from '../lib/toast'
6import { isExemptPath } from './role-guard'
7
8const ARCHITECT = 'dojo:kurisu'
9const WRITE_TOOLS = ['Edit', 'Write', 'NotebookEdit'] as const
10
11// Where Claude Code puts the worktree of an Agent call with `isolation: "worktree"`: <project>/.claude/worktrees/<name>.
12const WORKTREE = /\/\.claude\/worktrees\/[^/]+\//
13
14/** The target of a file-writing tool call, or null when the call names none. */
15export function writeTarget(tool: string, args: Record<string, unknown>): string | null {
16 const file = tool === 'NotebookEdit' ? args.notebook_path : args.file_path
17 return typeof file === 'string' && file !== '' ? file : null
18}
19
20/** Collapse `.`, `..` and repeated slashes, so `/tmp/../home/x` is not taken for a temp path. Relative paths keep their `..`. */
21export function normalizePath(path: string): string {
22 const absolute = path.startsWith('/')
23 const out: string[] = []
24 for (const part of path.split('/')) {
25 if (part === '' || part === '.') continue
26 if (part === '..') {
27 if (out.length > 0 && out[out.length - 1] !== '..') out.pop()
28 else if (!absolute) out.push('..')
29 } else out.push(part)
30 }
31 return (absolute ? '/' : '') + out.join('/')
32}
33
34/** True when the architect may write here: scratch space (system temp dirs, `$TMPDIR`, any `/scratchpad/`) or an isolated worktree. */
35export function isArchitectPath(path: string, tmpDirs: readonly string[] = []): boolean {
36 const p = normalizePath(path)
37 return isExemptPath(p, tmpDirs) || WORKTREE.test(p)
38}
39
40export function architectDenyReason(path: string): string {
41 return `Writes to the main working tree are not the architect's job (${path}). Put POCs in the scratchpad or system temp dir, or run in an isolated worktree; implementation goes to dojo:senku or dojo:sanji via the strategist.`
42}
43
44async function tmpDirs($: Engine): Promise<string[]> {
45 try {
46 const dir = await $.env.get('TMPDIR')
47 return typeof dir === 'string' && dir !== '' ? [dir] : []
48 } catch {
49 return []
50 }
51}
52
53async function isArchitect($: Engine, agentId: string): Promise<boolean> {
54 return (await $.agent.list()).some(a => a.id === agentId && a.type === ARCHITECT)
55}
56
57export const installArchitectGuard: Installer = (on, options) => {
58 // Architect guard: dojo:kurisu may write only to scratch space or an isolated worktree, never the main working tree.
59 // Bash is not parsed: a shell redirect or `sed -i` is not caught here.
60 on('tool.call', { tool: WRITE_TOOLS }, async ($, e, next) => {
61 try {
62 if (e.agentId !== undefined && isOn(options, 'architectGuard') && (await isArchitect($, e.agentId))) {
63 const file = writeTarget(String(e.tool), e as unknown as Record<string, unknown>)
64 if (file !== null && !isArchitectPath(file, await tmpDirs($))) {
65 try {
66 $.ui.toast(toastLine('architect'))
67 } catch {
68 // a toast is never worth failing a hook
69 }
70 return { deny: architectDenyReason(file) }
71 }
72 }
73 } catch {
74 // fail open: the call goes through
75 }
76 return next(e)
77 })
78}
79mods/features/archivist.ts 71 lines1import { atom, read } from 'claude-code'
2
3import { isOn } from '../lib/options'
4import type { Installer } from '../lib/options'
5import { isDojoType, strategistKey, strategistName } from '../lib/persona'
6import { toastLine } from '../lib/toast'
7import { voiceKey } from '../lib/voice'
8import type { VoiceLevel } from '../voice.generated'
9
10// The module scan reads an atom only from a const of the file that uses it; the {plugin, key} pair is the shared name.
11const strategist = atom({ plugin: 'dojo', key: 'strategist' } as const, null)
12const voice = atom({ plugin: 'dojo', key: 'voice' } as const, null)
13
14const TERMINAL = new Set(['completed', 'failed', 'killed'])
15
16export type RunningAgent = { id: string; type: string; description: string }
17
18/** The directive appended to the compaction instructions. */
19export function compactDirective(input: { strategist: string | null; voice: VoiceLevel | null; agents: readonly RunningAgent[] }): string {
20 const name = strategistName(input.strategist)
21 const lines = ['When summarizing, preserve verbatim:']
22 lines.push(
23 name === null
24 ? '- the context line "dojo: on duty: <Name>" naming the strategist persona on duty, exactly as it appeared'
25 : `- the context line "dojo: on duty: ${name}" (the strategist persona on duty)`,
26 )
27 lines.push(
28 input.voice === null
29 ? '- the active voice level: the roster default (no override is set)'
30 : `- the active voice level override: "dojo: voice level: ${input.voice}"`,
31 )
32 lines.push(
33 input.agents.length === 0
34 ? '- every running dojo agent with its task (none are running now)'
35 : `- every running dojo agent with its task:\n${input.agents.map(a => ` - ${a.type} (${a.id}): ${a.description}`).join('\n')}`,
36 )
37 lines.push('- every decision the user made, with the question it answered')
38 return lines.join('\n')
39}
40
41export const installArchivist: Installer = (on, options) => {
42 // The compaction summary keeps what a dojo session cannot afford to lose.
43 on('session.compact', async ($, e, next) => {
44 let out = e
45 try {
46 if (isOn(options, 'archivist') && e.agentId === undefined) {
47 const key = (await read($, strategist)) ?? strategistKey(await $.env.get('DOJO_STRATEGIST'))
48 if (key !== null) {
49 const agents = (await $.agent.list())
50 .filter(a => isDojoType(a.type) && !TERMINAL.has(a.status))
51 .map(a => ({ id: a.id, type: a.type, description: a.description }))
52 const level = voiceKey(await read($, voice))
53 const directive = compactDirective({ strategist: key, voice: level, agents })
54 const instructions = e.instructions === undefined || e.instructions.trim() === '' ? directive : `${e.instructions}\n\n${directive}`
55 out = { ...e, instructions }
56 if (e.trigger !== 'precompute') {
57 try {
58 $.ui.toast(toastLine('compact'))
59 } catch {
60 // a toast is never worth failing a hook
61 }
62 }
63 }
64 }
65 } catch {
66 out = e
67 }
68 return next(out)
69 })
70}
71mods/features/commands.ts 89 lines1import { atom, read, update } from 'claude-code'
2
3import type { Installer } from '../lib/options'
4import { isDojoType, strategistKey, strategistName } from '../lib/persona'
5import { VOICE_CLEAR_WORDS, VOICE_LEVELS, voiceContext, voiceKey, voiceOverrideBlock } from '../lib/voice'
6import { STRATEGISTS } from '../theme'
7
8// The module scan reads an atom only from a const of the file that uses it; the {plugin, key} pair is the shared name.
9const strategist = atom({ plugin: 'dojo', key: 'strategist' } as const, null)
10const chosen = atom({ plugin: 'dojo', key: 'chosen' } as const, null)
11const voice = atom({ plugin: 'dojo', key: 'voice' } as const, null)
12
13const COMMANDS = [
14 { name: 'dojo-duty', description: 'Show or switch the strategist persona on duty', argumentHint: '[shikamaru|lelouch]' },
15 { name: 'dojo-voice', description: 'Show or set the dojo voice level for this session', argumentHint: '[subtle|medium|full|default]' },
16] as const
17
18const argsOf = (args: unknown) => (typeof args === 'string' ? args : '')
19
20export const installCommands: Installer = on => {
21 // Voice override: dojo crew spawned while /dojo-voice is set carry that level's rules.
22 on('agent.spawn', { subagentType: /^dojo:/ }, async ($, e, next) => {
23 let out = e
24 try {
25 const level = voiceKey(await read($, voice))
26 if (level !== null && isDojoType(e.subagentType) && e.subagentType !== 'dojo:strategist') {
27 out = { ...e, prompt: `${e.prompt}\n\n${voiceOverrideBlock(level)}` }
28 }
29 } catch {
30 out = e
31 }
32 return next(out)
33 })
34
35 // Slash commands can only be registered once the session binds.
36 on('session.start', async ($, e, next) => {
37 for (const spec of COMMANDS) {
38 try {
39 await $.command.register(spec)
40 } catch {
41 // a name taken or refused: the others still register
42 }
43 }
44 return next(e)
45 })
46
47 on('command.run', { command: 'dojo-duty' }, async ($, e, next) => {
48 try {
49 const arg = argsOf(e.args).trim()
50 const current = (await read($, strategist)) ?? strategistKey(await $.env.get('DOJO_STRATEGIST'))
51 if (arg === '') {
52 const name = strategistName(current)
53 return { text: name === null ? `No strategist on duty. Valid names: ${Object.keys(STRATEGISTS).join(', ')}.` : `On duty: ${name}` }
54 }
55 const key = strategistKey(arg)
56 if (key === null) return { text: `Unknown strategist "${arg}". Valid names: ${Object.keys(STRATEGISTS).join(', ')}.` }
57 // the choice is the persona on duty now, and the one every later automatic on-duty line must yield to
58 await update($, strategist, () => key)
59 await update($, chosen, () => key)
60 const name = strategistName(key) as string
61 return { text: `On duty: ${name}`, context: [`dojo: on duty: ${name}`] }
62 } catch {
63 return next(e)
64 }
65 })
66
67 on('command.run', { command: 'dojo-voice' }, async ($, e, next) => {
68 try {
69 const arg = argsOf(e.args).trim().toLowerCase()
70 if (arg === '') {
71 const level = voiceKey(await read($, voice))
72 return { text: `Voice level override: ${level ?? 'none (roster default)'}` }
73 }
74 if (VOICE_CLEAR_WORDS.includes(arg)) {
75 await update($, voice, () => null)
76 return { text: 'Voice level override cleared (roster default).', context: ['dojo: voice level: default'] }
77 }
78 const level = voiceKey(arg)
79 if (level === null) {
80 return { text: `Unknown voice level "${arg}". Valid levels: ${VOICE_LEVELS.join(', ')}, or default to clear.` }
81 }
82 await update($, voice, () => level)
83 return { text: `Voice level override: ${level} (the strategist and dojo agents spawned from now on).`, context: [voiceContext(level)] }
84 } catch {
85 return next(e)
86 }
87 })
88}
89mods/features/commit-gate.ts 199 lines1import { isOn } from '../lib/options'
2import type { Installer, Options } from '../lib/options'
3import { base, head, parseShell } from '../lib/shell'
4import type { Word } from '../lib/shell'
5import { toastLine } from '../lib/toast'
6
7export const DEFAULT_TRAILER = 'Co-Authored-By: Claude'
8
9export type CommitCall = { messages: string[]; trailers: string[] }
10
11const GIT_VALUE_OPTIONS = new Set(['-C', '-c', '--git-dir', '--work-tree', '--namespace', '--exec-path', '--super-prefix'])
12const UNSUPPORTED_LONG = new Set(['--file', '--reuse-message', '--reedit-message', '--fixup', '--squash', '--template'])
13const SKIP_VALUE_LONG = new Set(['--author', '--date', '--cleanup', '--pathspec-from-file'])
14
15/**
16 * Every `git commit` in `command` that carries its message inline (-m / --message, repeated or not).
17 * Commits whose message cannot be read statically (-F, -C, --fixup, editor, expansions) are left out.
18 */
19export function extractCommits(command: string): CommitCall[] {
20 const calls: CommitCall[] = []
21 for (const cmd of parseShell(command)) {
22 const h = head(cmd)
23 if (base(h[0]?.text) !== 'git') continue
24 let k = 1
25 while (h[k] !== undefined && h[k]?.text.startsWith('-')) k += GIT_VALUE_OPTIONS.has(h[k]?.text ?? '') ? 2 : 1
26 if (h[k]?.text !== 'commit') continue
27
28 const args = h.slice(k + 1)
29 const messages: string[] = []
30 const trailers: string[] = []
31 let unreadable = false
32 let a = 0
33 const value = (): string | undefined => {
34 const w = args[++a]
35 if (w === undefined) {
36 unreadable = true
37 return undefined
38 }
39 if (w.dynamic) unreadable = true
40 return w.text
41 }
42 for (; a < args.length; a++) {
43 const w = args[a] as Word
44 if (w.text === '--') break
45 if (w.dynamic) unreadable = true
46 if (w.text.startsWith('--')) {
47 const eq = w.text.indexOf('=')
48 const name = eq < 0 ? w.text : w.text.slice(0, eq)
49 const inline = eq < 0 ? undefined : w.text.slice(eq + 1)
50 if (name === '--message') {
51 const v = inline ?? value()
52 if (v !== undefined) messages.push(v)
53 } else if (name === '--trailer') {
54 const v = inline ?? value()
55 if (v !== undefined) trailers.push(v)
56 } else if (UNSUPPORTED_LONG.has(name)) {
57 unreadable = true
58 } else if (SKIP_VALUE_LONG.has(name) && inline === undefined) {
59 a++
60 }
61 } else if (w.text.startsWith('-') && w.text.length > 1) {
62 for (let p = 1; p < w.text.length; p++) {
63 const ch = w.text[p] as string
64 if (ch === 'm') {
65 const rest = w.text.slice(p + 1)
66 const v = rest === '' ? value() : rest
67 if (v !== undefined) messages.push(v)
68 break
69 }
70 if ('FCct'.includes(ch)) {
71 unreadable = true
72 break
73 }
74 if (ch === 'S' || ch === 'u') break
75 }
76 }
77 }
78 if (!unreadable && messages.length > 0) calls.push({ messages, trailers })
79 }
80 return calls
81}
82
83export const COMMIT_TYPES = ['feat', 'fix', 'docs', 'style', 'refactor', 'perf', 'test', 'build', 'ci', 'chore', 'revert'] as const
84const SUBJECT = new RegExp(`^(${COMMIT_TYPES.join('|')})(\\([^()\\r\\n]+\\))?!?: \\S`)
85const SUBJECT_MAX = 72
86const TRAILER_LINE = /^[A-Za-z][A-Za-z0-9-]*\s*:\s*\S/
87const GENERATED_WITH = /generated with \[?claude code/i
88
89function clip(text: string, max = 60): string {
90 const chars = [...text]
91 return chars.length <= max ? text : chars.slice(0, max - 1).join('') + '…'
92}
93
94/** Rule violations of one commit message, empty when it is clean. `trailer` '' skips the trailer check. */
95export function checkCommitMessage(call: CommitCall, trailer: string): string[] {
96 const full = [...call.messages, ...(call.trailers.length > 0 ? [call.trailers.join('\n')] : [])]
97 .join('\n\n')
98 .replace(/\r\n?/g, '\n')
99 const lines = full.split('\n')
100 while (lines.length > 0 && (lines[0] ?? '').trim() === '') lines.shift()
101 const subject = (lines.shift() ?? '').trim()
102 const out: string[] = []
103
104 if (!SUBJECT.test(subject)) {
105 out.push(
106 `the subject is not Conventional Commits (type(scope)!: subject; types: ${COMMIT_TYPES.join(', ')}): "${clip(subject)}"`,
107 )
108 }
109 const length = [...subject].length
110 if (length > SUBJECT_MAX) out.push(`the subject is ${length} characters; the limit is ${SUBJECT_MAX}`)
111
112 let body: string | undefined
113 for (const raw of lines) {
114 const line = raw.trim()
115 if (line === '' || GENERATED_WITH.test(line) || TRAILER_LINE.test(line)) continue
116 body ??= line
117 }
118 if (body !== undefined) {
119 out.push(`the message has a body ("${clip(body)}"); keep only the subject line and trailer lines`)
120 }
121
122 if (trailer !== '') {
123 for (const raw of lines) {
124 const line = raw.trim()
125 if (/^co-authored-by\s*:/i.test(line) && /claude/i.test(line) && line !== trailer) {
126 out.push(`the Co-Authored-By line "${clip(line, 80)}" must be exactly "${trailer}"`)
127 }
128 }
129 }
130 if (lines.some(l => /^claude-session\s*:/i.test(l.trim()))) out.push('a "Claude-Session:" line is not allowed')
131 if (GENERATED_WITH.test(full)) out.push('"Generated with Claude Code" text is not allowed')
132 return out
133}
134
135/** All violations over every inline `git commit` in `command` (empty: nothing to object to). */
136export function checkCommitCommand(command: string, trailer: string): string[] {
137 const out: string[] = []
138 for (const call of extractCommits(command)) {
139 for (const v of checkCommitMessage(call, trailer)) if (!out.includes(v)) out.push(v)
140 }
141 return out
142}
143
144/** The deny text the model reads: each violation, then the corrected form. */
145export function commitDenyReason(violations: readonly string[], trailer: string): string {
146 const fix =
147 trailer === ''
148 ? 'Retry git commit with a single Conventional Commits subject line (at most 72 characters), no body, and no Claude-Session or "Generated with Claude Code" lines.'
149 : `Retry git commit with a single Conventional Commits subject line (at most 72 characters), no body, and, if you add a trailer, exactly this line:\n${trailer}`
150 return ['Commit message rejected by the dojo commit gate:', ...violations.map(v => `- ${v}`), fix].join('\n')
151}
152
153function trailerOf(options: Options): string {
154 const v = options.commitTrailer
155 return typeof v === 'string' ? v.trim() : DEFAULT_TRAILER
156}
157
158function commandOf(input: unknown): string | null {
159 const c = typeof input === 'object' && input !== null ? (input as { command?: unknown }).command : undefined
160 return typeof c === 'string' ? c : null
161}
162
163export const installCommitGate: Installer = (on, options) => {
164 // The model reads the configured trailer wherever core would have written its own.
165 on('attribution.text', { kind: 'commit' }, async ($, e, next) => {
166 try {
167 const trailer = trailerOf(options)
168 if (isOn(options, 'commitGate') && trailer !== '') return { text: trailer }
169 } catch {
170 // fall through to core's text
171 }
172 return next(e)
173 })
174
175 // Core answers first; a deny is never weakened.
176 on('tool.check', { tool: 'Bash' }, async ($, e, next) => {
177 const core = await next(e)
178 try {
179 if (core.decision === 'deny') return core
180 const command = commandOf(e.input)
181 if (command === null || !isOn(options, 'commitGate')) return core
182
183 const trailer = trailerOf(options)
184 const violations = checkCommitCommand(command, trailer)
185 if (violations.length > 0) {
186 try {
187 $.ui.toast(toastLine('commit'))
188 } catch {
189 // a toast is never worth failing a hook
190 }
191 return { decision: 'deny' as const, reason: commitDenyReason(violations, trailer) }
192 }
193 } catch {
194 // fail open: core's verdict stands
195 }
196 return core
197 })
198}
199mods/features/model-guard.ts 12 lines1import { isDojoType } from '../lib/persona'
2import type { Installer } from '../lib/options'
3
4// A caller's "always pass model: sonnet" must not override a dojo agent's own frontmatter model;
5// undefined lets the agent decide. Ships regardless of every toggle.
6export const installModelGuard: Installer = on => {
7 on('agent.spawn', async ($, e, next) => {
8 if (!isDojoType(e.subagentType)) return next(e)
9 return next(e.model === undefined ? e : { ...e, model: undefined })
10 })
11}
12mods/features/role-guard.ts 189 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface as Engine } from 'claude-code'
3
4import { isOn } from '../lib/options'
5import type { Installer, Options } from '../lib/options'
6import { strategistKey } from '../lib/persona'
7import { toastLine } from '../lib/toast'
8import type { DojoBudget } from '../state'
9
10// The module scan reads an atom only from a const of the file that uses it; the {plugin, key} pair is the shared name.
11const strategist = atom({ plugin: 'dojo', key: 'strategist' } as const, null)
12const turn = atom({ plugin: 'dojo', key: 'turn' } as const, 0)
13const budget = atom({ plugin: 'dojo', key: 'budget' } as const, { files: [], lookups: 0 } as DojoBudget)
14// The prompt number the budget belongs to: a new prompt is a new turn, and its first metered call starts a fresh budget.
15const budgetTurn = atom({ plugin: 'dojo', key: 'budgetTurn' } as const, 0)
16
17export type Budget = DojoBudget
18export const EMPTY_BUDGET: Budget = { files: [], lookups: 0 }
19
20const METERED_TOOLS = ['Edit', 'Write', 'NotebookEdit', 'WebSearch', 'WebFetch'] as const
21
22export type RoleLimits = { files: number; lines: number; lookups: number }
23
24const FRONTEND = /\.(tsx|jsx|vue|svelte|css|scss|sass|less|html)$/i
25const TEMP_ROOTS = ['/tmp/', '/var/tmp/', '/private/tmp/', '/var/folders/', '/private/var/folders/']
26
27/** `dojo:sanji` for UI files, `dojo:senku` for everything else. */
28export function delegateFor(path: string): 'dojo:sanji' | 'dojo:senku' {
29 return FRONTEND.test(path) ? 'dojo:sanji' : 'dojo:senku'
30}
31
32/** Scratch space is not the project: system temp dirs (and `tmpDirs`) and any `/scratchpad/`. */
33export function isExemptPath(path: string, tmpDirs: readonly string[] = []): boolean {
34 if (path.includes('/scratchpad/')) return true
35 const roots = [...TEMP_ROOTS, ...tmpDirs.filter(d => d !== '').map(d => (d.endsWith('/') ? d : `${d}/`))]
36 return roots.some(r => path.startsWith(r))
37}
38
39export function countLines(text: string): number {
40 if (text === '') return 0
41 const n = text.split('\n').length
42 return text.endsWith('\n') ? n - 1 : n
43}
44
45export type RoleCall =
46 | { kind: 'edit'; file: string; lines: number | null }
47 | { kind: 'lookup' }
48
49/** What the main thread's tool call spends, or null for a call the role guard does not meter. */
50export function roleCall(tool: string, args: Record<string, unknown>): RoleCall | null {
51 if (tool === 'WebSearch' || tool === 'WebFetch') return { kind: 'lookup' }
52 if (tool === 'Edit' || tool === 'Write' || tool === 'NotebookEdit') {
53 const file = tool === 'NotebookEdit' ? args.notebook_path : args.file_path
54 if (typeof file !== 'string' || file === '') return null
55 const lines = tool === 'Edit' && typeof args.new_string === 'string' ? countLines(args.new_string) : null
56 return { kind: 'edit', file, lines }
57 }
58 return null
59}
60
61export type Charge = {
62 budget: Budget
63 /** True when this call newly spent budget (a file not yet edited this turn, or a lookup). */
64 added: boolean
65 denied: null | { reason: string; toast: 'backend' | 'frontend' | 'lookups' }
66}
67
68/** Pure: spend one call from the turn's budget, or say why it is over. */
69export function charge(b: Budget, call: RoleCall, limits: RoleLimits, tmpDirs: readonly string[] = []): Charge {
70 if (call.kind === 'lookup') {
71 if (b.lookups >= limits.lookups) {
72 return {
73 budget: b,
74 added: false,
75 denied: {
76 reason: `Inline lookup budget reached: ${b.lookups} WebSearch/WebFetch calls already made this turn (limit ${limits.lookups}). Delegate multi-source research to dojo:jiraiya, or a single-fact lookup to dojo:light, with a delegation brief.`,
77 toast: 'lookups',
78 },
79 }
80 }
81 return { budget: { ...b, lookups: b.lookups + 1 }, added: true, denied: null }
82 }
83 if (isExemptPath(call.file, tmpDirs)) return { budget: b, added: false, denied: null }
84 const agent = delegateFor(call.file)
85 const toast = agent === 'dojo:sanji' ? 'frontend' : 'backend'
86 if (call.lines !== null && call.lines > limits.lines) {
87 return {
88 budget: b,
89 added: false,
90 denied: {
91 reason: `This Edit writes ${call.lines} lines (inline limit ${limits.lines}). Delegate it to ${agent} with a delegation brief instead of editing ${call.file} yourself.`,
92 toast,
93 },
94 }
95 }
96 if (b.files.includes(call.file)) return { budget: b, added: false, denied: null }
97 if (b.files.length >= limits.files) {
98 return {
99 budget: b,
100 added: false,
101 denied: {
102 reason: `Inline edit budget reached: ${b.files.length} distinct files already edited this turn (limit ${limits.files}). Delegate the change to ${agent} with a delegation brief instead of editing ${call.file} yourself.`,
103 toast,
104 },
105 }
106 }
107 return { budget: { ...b, files: [...b.files, call.file] }, added: true, denied: null }
108}
109
110/** Pure: give back what a charge spent, for a call that core then refused. */
111export function refund(b: Budget, call: RoleCall): Budget {
112 if (call.kind === 'lookup') return { ...b, lookups: Math.max(0, b.lookups - 1) }
113 return { ...b, files: b.files.filter(f => f !== call.file) }
114}
115
116function count(options: Options, name: string, fallback: number): number {
117 const v = options[name]
118 return typeof v === 'number' && Number.isFinite(v) && v >= 0 ? Math.floor(v) : fallback
119}
120
121function limitsOf(options: Options): RoleLimits {
122 return {
123 files: count(options, 'inlineEditFiles', 2),
124 lines: count(options, 'inlineEditLines', 6),
125 lookups: count(options, 'inlineLookups', 3),
126 }
127}
128
129async function tmpDirs($: Engine): Promise<string[]> {
130 try {
131 const dir = await $.env.get('TMPDIR')
132 return typeof dir === 'string' && dir !== '' ? [dir] : []
133 } catch {
134 return []
135 }
136}
137
138async function newTurnBudget($: Engine) {
139 const n = (await read($, turn)) ?? 0
140 if ((await read($, budgetTurn)) === n) return
141 await update($, budget, () => EMPTY_BUDGET)
142 await update($, budgetTurn, () => n)
143}
144
145export const installRoleGuard: Installer = (on, options) => {
146 // Role guard on the main thread: caps inline edits and web lookups per turn in a dojo session.
147 on('tool.call', { tool: METERED_TOOLS }, async ($, e, next) => {
148 let spent: RoleCall | null = null
149 try {
150 if (e.agentId === undefined && isOn(options, 'roleGuard') && ((await read($, strategist)) ?? strategistKey(await $.env.get('DOJO_STRATEGIST'))) !== null) {
151 const call = roleCall(String(e.tool), e as unknown as Record<string, unknown>)
152 if (call !== null) {
153 await newTurnBudget($)
154 const limits = limitsOf(options)
155 const tmp = call.kind === 'edit' ? await tmpDirs($) : []
156 let result = charge(EMPTY_BUDGET, call, limits, tmp)
157 await update($, budget, b => {
158 result = charge(b, call, limits, tmp)
159 return result.budget
160 })
161 if (result.denied !== null) {
162 try {
163 $.ui.toast(toastLine(result.denied.toast))
164 } catch {
165 // a toast is never worth failing a hook
166 }
167 return { deny: result.denied.reason }
168 }
169 if (result.added) spent = call
170 }
171 }
172 } catch {
173 // fail open: the call goes through unmetered
174 }
175
176 const ran = await next(e)
177
178 try {
179 if (ran.deny !== undefined && spent !== null) {
180 const call = spent
181 await update($, budget, b => refund(b, call))
182 }
183 } catch {
184 // bookkeeping only
185 }
186 return ran
187 })
188}
189mods/lib/persona.ts 117 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface as Engine } from 'claude-code'
3
4import type { Installer } from './options'
5import { CREW, STRATEGISTS } from '../theme'
6
7// The one copy of strategist detection. Every feature that needs to know who is on duty reads it here.
8
9export const DOJO_PREFIX = 'dojo:'
10const ON_DUTY = /dojo: on duty: ([A-Za-z]+)/g
11
12/** The strategist persona key (`shikamaru`, `lelouch`) read off the session, or null. */
13export const strategist = atom({ plugin: 'dojo', key: 'strategist' } as const, null)
14/** The persona a /dojo-duty command picked; it outranks every automatic on-duty line after it. */
15export const chosen = atom({ plugin: 'dojo', key: 'chosen' } as const, null)
16/** Prompts submitted so far; rotates the verb pools and bounds the transcript scan. */
17export const turn = atom({ plugin: 'dojo', key: 'turn' } as const, 0)
18
19const TALK_DOORS = new Set(['prompt', 'response', 'tool-result'])
20// The transcript fallback only looks during the first prompts: later it would cost a read per prompt.
21const SCAN_PROMPTS = 3
22
23const has = (table: Record<string, unknown>, key: string) => Object.prototype.hasOwnProperty.call(table, key)
24
25/** `dojo:levi` -> `levi`; anything that is not a dojo crew type -> null (the strategist is no crew). */
26export function crewKey(type: string): string | null {
27 if (!type.startsWith(DOJO_PREFIX)) return null
28 const key = type.slice(DOJO_PREFIX.length)
29 return has(CREW, key) ? key : null
30}
31
32export function isDojoType(type: string): boolean {
33 return type.startsWith(DOJO_PREFIX)
34}
35
36/** Persona key from the context line `dojo: on duty: <Name>` (the last one in the text), or null. */
37export function parseOnDuty(text: string): string | null {
38 let found: string | null = null
39 for (const m of text.matchAll(ON_DUTY)) {
40 const name = m[1]?.toLowerCase()
41 if (name !== undefined && has(STRATEGISTS, name)) found = name
42 }
43 return found
44}
45
46export function strategistKey(raw: string | undefined | null): string | null {
47 const key = (raw ?? '').trim().toLowerCase()
48 return has(STRATEGISTS, key) ? key : null
49}
50
51export function strategistName(key: string | null): string | null {
52 return key === null ? null : (STRATEGISTS[key]?.name ?? null)
53}
54
55/** Every known `dojo: on duty: <Name>` line in `text` renamed to the persona `key`. */
56export function reassertOnDuty(text: string, key: string): string {
57 const name = STRATEGISTS[key]?.name
58 if (name === undefined) return text
59 return text.replace(ON_DUTY, (line, found: string) => (has(STRATEGISTS, found.toLowerCase()) ? `dojo: on duty: ${name}` : line))
60}
61
62async function scanForPersona($: Engine) {
63 if ((await read($, strategist)) !== null || (await read($, turn)) > SCAN_PROMPTS) return
64 try {
65 const messages = await $.session.messages()
66 if ('deny' in messages) return
67 for (const m of [...messages].reverse()) {
68 const found = m.role === 'user' ? parseOnDuty(m.text) : null
69 if (found !== null) {
70 await update($, strategist, () => found)
71 return
72 }
73 }
74 } catch {
75 // no transcript to read: the env var or no dojo session stands
76 }
77}
78
79export const installPersona: Installer = on => {
80 // The dojo SessionStart hook (and /dojo-duty) inject `dojo: on duty: <Name>` as context. The most recent
81 // line wins, so every appended row updates the persona, except that a /dojo-duty choice outranks the hook:
82 // SessionStart fires again on resume and compact and would announce the original persona over the switch,
83 // so such a line is rewritten to the chosen persona before the model reads it.
84 on('session.append', async ($, e, next) => {
85 let out = e
86 try {
87 if (e.agentId === undefined && !TALK_DOORS.has(e.door)) {
88 const picked = (await read($, chosen)) ?? null
89 const content = e.message.content.map(block => {
90 if (block.type !== 'text' || typeof block.text !== 'string') return block
91 const text = picked === null ? block.text : reassertOnDuty(block.text, picked)
92 return text === block.text ? block : { ...block, text }
93 })
94 for (const block of content) {
95 const found = block.type === 'text' && typeof block.text === 'string' ? parseOnDuty(block.text) : null
96 if (found !== null) await update($, strategist, () => found)
97 }
98 if (content.some((block, i) => block !== e.message.content[i])) out = { ...e, message: { ...e.message, content } }
99 }
100 } catch {
101 out = e
102 }
103 return next(out)
104 })
105
106 // A new prompt is a new turn.
107 on('prompt.submit', async ($, e, next) => {
108 try {
109 await update($, turn, n => n + 1)
110 await scanForPersona($)
111 } catch {
112 // bookkeeping only
113 }
114 return next(e)
115 })
116}
117mods/state/recorders.tsx 248 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface as Engine } from 'claude-code'
3
4import { isOn } from '../lib/options'
5import type { Installer, Options } from '../lib/options'
6import { crewKey } from '../lib/persona'
7import { summarizeTool } from '../lib/text'
8import { CREW, resolveMode } from '../theme'
9import type { PaletteMode } from '../theme'
10import type { DojoBand, DojoCrewStats, DojoRank, DojoRosterEntry, DojoRun, DojoUsage } from '../state'
11import { RANK_STORE_KEY } from '../visuals/chrome-art'
12import { addStats, agentTokens, parseSays, snapshotUsage, stepTokens } from '../visuals/chrome-lib'
13import type { AgentTokens } from '../visuals/chrome-lib'
14import { remember } from '../visuals/transcript-lib'
15
16// The state installer: every hook here records, derives or persists data and draws nothing. The visual modules (chrome,
17// transcript) read what lands here through atoms of their own.
18//
19// The module scan reads an atom only from a const of the file that uses it; the {plugin, key} pair is the shared name.
20const band = atom({ plugin: 'dojo', key: 'band' } as const, { frame: 0, rows: [] } as DojoBand)
21const tools = atom({ plugin: 'dojo', key: 'tools' } as const, {} as Record<string, string>)
22const roster = atom({ plugin: 'dojo', key: 'roster' } as const, {} as Record<string, DojoRosterEntry>)
23const runs = atom({ plugin: 'dojo', key: 'runs' } as const, {} as Record<string, DojoRun>)
24const usage = atom({ plugin: 'dojo', key: 'usage' } as const, null as DojoUsage | null)
25const stats = atom({ plugin: 'dojo', key: 'stats' } as const, {} as Record<string, DojoCrewStats>)
26const rank = atom({ plugin: 'dojo', key: 'rank' } as const, null as DojoRank | null)
27const paletteMode = atom({ plugin: 'dojo', key: 'paletteMode' } as const, 'dark' as PaletteMode)
28/** tool_use_id of a call a subagent made -> its crew key, or `-` for any other subagent. The main thread has no entry. */
29const callers = atom({ plugin: 'dojo', key: 'callers' } as const, {} as Record<string, string>)
30/** tool_use_id of an Agent call -> the crew key it spawns, or `-` for any other agent type. */
31const spawns = atom({ plugin: 'dojo', key: 'spawns' } as const, {} as Record<string, string>)
32
33/** A run no step has counted yet. */
34export const NO_TOKENS = { latestInput: 0, cumOutput: 0 }
35
36/** A run the steps never counted takes the usage its turn reports; one they did count keeps its own figures. */
37function settleTokens(cur: AgentTokens, usage: unknown): AgentTokens {
38 return agentTokens(cur) > 0 ? cur : stepTokens(cur, usage)
39}
40
41/** The palette for the engine theme and the `paletteMode` setting; `changed` is a row being written right now. */
42async function syncMode($: Engine, options: Options, changed?: { key: string; value: unknown }) {
43 let theme: unknown
44 let setting: unknown = options.paletteMode
45 try {
46 const rows = await $.config.list()
47 theme = rows.find(r => r.key === 'theme')?.value
48 const mine = rows.find(r => r.key === 'dojo.paletteMode')
49 if (mine !== undefined) setting = mine.value
50 } catch {
51 // no config rows to read: the option and the dark default stand
52 }
53 if (changed !== undefined) {
54 if (changed.key === 'theme') theme = changed.value
55 else setting = changed.value
56 }
57 const next = resolveMode(setting, theme)
58 await update($, paletteMode, () => next)
59}
60
61export const pointsOf = (stored: unknown): number => {
62 const p = typeof stored === 'object' && stored !== null ? (stored as { points?: unknown }).points : undefined
63 return typeof p === 'number' && Number.isFinite(p) && p > 0 ? Math.floor(p) : 0
64}
65
66/** The rank points: held in state once loaded from the plugin store. Writes state, so never call it while drawing. */
67async function loadRank($: Engine): Promise<DojoRank> {
68 const held = await read($, rank)
69 if (held !== null) return held
70 let first: DojoRank
71 try {
72 first = { points: pointsOf(await $.store.get(RANK_STORE_KEY)), saved: true }
73 } catch {
74 // no store: the points live in this session only, and say so
75 first = { points: 0, saved: false }
76 }
77 return (await update($, rank, r => r ?? first)) ?? first
78}
79
80export const installRecorders: Installer = (on, options) => {
81 // Roster, stats, start time and band row for a dojo subagent that started.
82 on('agent.spawn', { subagentType: /^dojo:(?!strategist$)/ }, async ($, e, next) => {
83 const ran = await next(e)
84 const key = crewKey(e.subagentType)
85 if (ran.deny === undefined && ran.agentId !== undefined && key !== null) {
86 try {
87 if (isOn(options, 'rosterPane') || isOn(options, 'toasts')) {
88 await update($, roster, r => ({
89 ...r,
90 [key]: { status: 'running' as const, count: (r[key]?.count ?? 0) + 1, task: e.description },
91 }))
92 }
93 if (isOn(options, 'rosterPane')) await update($, stats, s => addStats(s, key, { runs: 1 }))
94 if (isOn(options, 'band')) {
95 const id = ran.agentId
96 try {
97 const startedAt = await $.clock.now()
98 await update($, runs, r => ({ ...r, [id]: { startedAt, ...NO_TOKENS } }))
99 } catch {
100 // no start time: the row shows no elapsed figure until the tick notes one
101 }
102 await update($, band, b => ({
103 ...b,
104 rows: [...b.rows.filter(r => r.id !== id), { id, key, description: e.description }],
105 }))
106 }
107 } catch {
108 // bookkeeping only: the subagent has started either way
109 }
110 }
111 return ran
112 })
113
114 // What a crew member said last: the `Says:` line of its report.
115 on('turn.complete', { reason: 'answer' }, async ($, e, next) => {
116 const ran = await next(e)
117 if (e.agentId !== undefined && isOn(options, 'band')) {
118 try {
119 const id = e.agentId
120 await update($, runs, r => {
121 const cur = r[id]
122 const settled = cur === undefined ? undefined : settleTokens(cur, e.usage)
123 return cur === undefined || settled === cur ? r : { ...r, [id]: { ...cur, ...settled } }
124 })
125 } catch {
126 // the token figure is a garnish
127 }
128 }
129 if (e.agentId !== undefined && (isOn(options, 'rosterPane') || isOn(options, 'toasts'))) {
130 try {
131 const says = parseSays(e.answer)
132 const id = e.agentId
133 const agent = (await $.agent.list()).find(a => a.id === id)
134 const key = agent === undefined ? null : crewKey(agent.type)
135 if (key !== null && CREW[key] !== undefined && isOn(options, 'rosterPane')) {
136 const ms = Number.isFinite(e.durationMs) && e.durationMs > 0 ? e.durationMs : 0
137 const tokens = agentTokens(settleTokens((await read($, runs))[id] ?? NO_TOKENS, e.usage))
138 if (ms > 0 || tokens > 0 || says !== undefined) await update($, stats, s => addStats(s, key, { ms, tokens, ...(says === undefined ? {} : { says }) }))
139 }
140 if (says !== undefined && key !== null) {
141 await update($, roster, r => ({
142 ...r,
143 [key]: { status: 'running' as const, count: 1, task: '', ...r[key], says },
144 }))
145 }
146 } catch {
147 // the line is a garnish
148 }
149 }
150 return ran
151 })
152
153 // Latest tool call per subagent, for the band's tool column.
154 on('tool.call', async ($, e, next) => {
155 if (e.agentId !== undefined && isOn(options, 'band')) {
156 const id = e.agentId
157 const line = summarizeTool(String(e.tool), e as unknown as Record<string, unknown>)
158 await update($, tools, t => ({ ...t, [id]: line }))
159 }
160 return next(e)
161 })
162
163 // Remember which subagent made each tool call, so a row can be marked by the crew member behind it.
164 on('tool.call', { agentId: /./ }, async ($, e, next) => {
165 if (isOn(options, 'transcriptTheme')) {
166 try {
167 const id = String(e.tool_use_id)
168 const loop = String(e.agentId)
169 const found = (await $.agent.list()).find(a => a.id === loop)
170 const key = found === undefined ? null : crewKey(found.type)
171 await update($, callers, table => remember(table, id, key ?? '-'))
172 } catch {
173 // bookkeeping only
174 }
175 }
176 return next(e)
177 })
178
179 // Remember which agent type each Agent call spawns, so its result can be drawn as that character's return.
180 on('tool.call', { tool: 'Agent' }, async ($, e, next) => {
181 if (isOn(options, 'transcriptTheme')) {
182 try {
183 const type = (e as unknown as { subagent_type?: unknown }).subagent_type
184 const key = typeof type === 'string' ? crewKey(type) : null
185 await update($, spawns, table => remember(table, String(e.tool_use_id), key ?? '-'))
186 } catch {
187 // bookkeeping only
188 }
189 }
190 return next(e)
191 })
192
193 // What a crew member has spent so far: each model request replaces the run's latest input and adds its output (Claude Code's own per-agent figure). The main loop passes.
194 on('turn.step', async function* ($, e, next) {
195 const out = yield* next(e)
196 if (e.agentId !== undefined && isOn(options, 'band')) {
197 try {
198 const id = e.agentId
199 await update($, runs, r => {
200 const cur = r[id]
201 return cur === undefined ? r : { ...r, [id]: { ...cur, ...stepTokens(cur, out.usage) } }
202 })
203 } catch {
204 // the token figure is a garnish
205 }
206 }
207 return out
208 })
209
210 // The latest session figures for the usage line; the engine pushes them, the chrome band hook draws them.
211 on('session.measure', async ($, e, next) => {
212 const ran = await next(e)
213 if (isOn(options, 'usageLine')) {
214 try {
215 const figures = snapshotUsage(e)
216 await update($, usage, () => figures)
217 } catch {
218 // the usage line is a garnish
219 }
220 }
221 return ran
222 })
223
224 // The palette and the rank points, set once an interactive session binds.
225 on('session.start', { isInteractive: true }, async ($, e, next) => {
226 try {
227 await syncMode($, options)
228 if (isOn(options, 'rank')) await loadRank($)
229 } catch {
230 // the dark palette and a rank loaded on first use stand
231 }
232 return next(e)
233 })
234
235 // The palette follows the engine theme (and the setting): re-resolved when either is written.
236 on('config.set', { key: ['theme', 'dojo.paletteMode'] }, async ($, e, next) => {
237 const ran = await next(e)
238 if (ran.deny === undefined) {
239 try {
240 await syncMode($, options, { key: e.key, value: e.value })
241 } catch {
242 // the palette stays as it was
243 }
244 }
245 return ran
246 })
247}
248mods/visuals/chrome.tsx 646 lines1import { atom, read, update } from 'claude-code'
2import type { ElementConstructor, EngineInterface as Engine, RenderElement, TextProps } from 'claude-code'
3
4import { isOn } from '../lib/options'
5import type { Installer, Options } from '../lib/options'
6import { crewKey, strategistKey } from '../lib/persona'
7import { CREW, NEUTRAL, STRATEGISTS, WORDS } from '../theme'
8import type { PaletteMode, Theme, Words } from '../theme'
9import type { DojoBand, DojoCrewRow, DojoCrewStats, DojoRank, DojoRosterEntry, DojoRun, DojoUsage } from '../state'
10import { NO_TOKENS, pointsOf } from '../state/recorders'
11import { CUE_GAP_MS, GALLERY_ORDER, RANK_STORE_KEY, SOUNDS, TOAST_MS } from './chrome-art'
12import type { Cue } from './chrome-art'
13import {
14 addStats,
15 agentTokens,
16 deployToast,
17 fallToast,
18 framesOf,
19 galleryLines,
20 galleryText,
21 planBand,
22 planModes,
23 planUsage,
24 rankOf,
25 rankUpText,
26 recapLines,
27 recapText,
28 returnToast,
29 rosterLines,
30 rosterText,
31 snapshotUsage,
32 turnWord,
33 verbAt,
34} from './chrome-lib'
35import type { Line, Seg } from './chrome-lib'
36
37export { bandLine } from './chrome-lib'
38export type { RowInput } from './chrome-lib'
39
40// The module scan reads an atom only from a const of the file that uses it; the {plugin, key} pair is the shared name.
41const strategist = atom({ plugin: 'dojo', key: 'strategist' } as const, null)
42const turn = atom({ plugin: 'dojo', key: 'turn' } as const, 0)
43const voice = atom({ plugin: 'dojo', key: 'voice' } as const, null)
44const band = atom({ plugin: 'dojo', key: 'band' } as const, { frame: 0, rows: [] } as DojoBand)
45const tools = atom({ plugin: 'dojo', key: 'tools' } as const, {} as Record<string, string>)
46const roster = atom({ plugin: 'dojo', key: 'roster' } as const, {} as Record<string, DojoRosterEntry>)
47const runs = atom({ plugin: 'dojo', key: 'runs' } as const, {} as Record<string, DojoRun>)
48const pulse = atom({ plugin: 'dojo', key: 'pulse' } as const, 0)
49const cueAt = atom({ plugin: 'dojo', key: 'cueAt' } as const, null as number | null)
50const usage = atom({ plugin: 'dojo', key: 'usage' } as const, null as DojoUsage | null)
51const stats = atom({ plugin: 'dojo', key: 'stats' } as const, {} as Record<string, DojoCrewStats>)
52const rank = atom({ plugin: 'dojo', key: 'rank' } as const, null as DojoRank | null)
53const gallery = atom({ plugin: 'dojo', key: 'gallery' } as const, 0)
54// written by the state recorders (session start, theme or setting change), read here and by the transcript module
55const paletteMode = atom({ plugin: 'dojo', key: 'paletteMode' } as const, 'dark' as PaletteMode)
56
57const TICK_MS = 250
58const PULSE_MS = 400
59// the spinner walks on to its next verb every this many pulses
60const VERB_EVERY = 12
61// pulses with no spinner drawn before the pulse timer stops itself
62const PULSE_IDLE = 3
63const PANE_ID = 'dojo-roster'
64const RECAP_ID = 'dojo-recap'
65const GALLERY_ID = 'dojo-gallery'
66const COMMANDS = [
67 { name: 'dojo', description: 'Open the dojo roster: strategist on duty, crew, models and status' },
68 { name: 'dojo-recap', description: 'Open the mission report: who was deployed, what fell, final context and cost, rank' },
69 { name: 'dojo-gallery', description: 'Browse the dojo characters: banner, colors, spinner words and lines' },
70] as const
71const TERMINAL = new Set(['completed', 'failed', 'killed'])
72
73// Module variables die with a hot reload; everything a drawing reads lives in $.state.
74const seen = new Map<string, string>()
75let timer: { cancel: () => void } | undefined
76let pulseTimer: { cancel: () => void } | undefined
77let spinnerDraws = 0
78
79const wordsOf = (key: string): Words => WORDS[key] as Words
80
81/** The strategist's theme and words for `key`; the neutral ones when `neutral` is on and no persona is known. */
82export function strategistTheme(key: string | null, neutral: boolean): (Theme & Words) | null {
83 const theme = key !== null ? STRATEGISTS[key] : neutral ? NEUTRAL : undefined
84 return theme === undefined ? null : { ...theme, ...wordsOf(theme.key) }
85}
86
87/** The persona on duty (`shikamaru`, `lelouch`): what a command or the transcript said, else DOJO_STRATEGIST. */
88async function personaKey($: Engine): Promise<string | null> {
89 const known = await read($, strategist)
90 if (known !== null) return known
91 try {
92 return strategistKey(await $.env.get('DOJO_STRATEGIST'))
93 } catch {
94 return null
95 }
96}
97
98async function mainTheme($: Engine, options: Options) {
99 return strategistTheme(await personaKey($), isOn(options, 'neutralMainTheme'))
100}
101
102const textProps = (s: Seg) => ({
103 ...(s.color === undefined ? {} : { color: s.color }),
104 ...(s.bold === true ? { bold: true } : {}),
105 ...(s.dim === true ? { dimColor: true } : {}),
106 ...(s.italic === true ? { italic: true } : {}),
107})
108
109/** One planned line as a Text: flat when it has one segment, nested colored runs otherwise. Always cut at the row's end. */
110function drawLine(Text: ElementConstructor<TextProps>, line: Line, key: string): RenderElement {
111 const only = line.length === 1 ? line[0] : undefined
112 if (only !== undefined) {
113 return (
114 <Text key={key} wrap="truncate-end" {...textProps(only)}>
115 {only.text}
116 </Text>
117 )
118 }
119 return (
120 <Text key={key} wrap="truncate-end">
121 {line.map((s, i) => (
122 <Text key={`${key}-${i}`} {...textProps(s)}>
123 {s.text}
124 </Text>
125 ))}
126 </Text>
127 )
128}
129
130/**
131 * Plays a cue unless one played within the gap. The stamp is claimed inside `update`, which retries on a version
132 * miss, so parallel callers (each in an environment of its own) cannot both pass the gate.
133 */
134async function cue($: Engine, options: Options, kind: Cue): Promise<void> {
135 if (!isOn(options, 'sounds')) return
136 try {
137 const now = await $.clock.now()
138 let isClaimed = false
139 await update($, cueAt, last => {
140 isClaimed = !(last !== null && now >= last && now - last < CUE_GAP_MS)
141 return isClaimed ? now : last
142 })
143 if (isClaimed) $.audio.play({ asset: SOUNDS[kind] }).catch(() => {})
144 } catch {
145 // no clock or no player: the cue is a garnish
146 }
147}
148
149/** Keeps the spinner animating while one is on screen, and stops once none has been drawn for a few pulses. */
150function startPulse($: Engine) {
151 if (pulseTimer !== undefined) return
152 let lastDraws = -1
153 let idle = 0
154 pulseTimer = $.clock.every(PULSE_MS, () => {
155 if (spinnerDraws === lastDraws) {
156 idle += 1
157 if (idle >= PULSE_IDLE) {
158 pulseTimer?.cancel()
159 pulseTimer = undefined
160 return
161 }
162 } else {
163 idle = 0
164 lastDraws = spinnerDraws
165 }
166 update($, pulse, p => p + 1).catch(() => {})
167 })
168}
169
170type Group = { running: number; last?: 'returned' | 'fell'; task: string }
171
172/** The roster after folding in what the agent list says now; the same object when nothing changed. */
173function foldRoster(prev: Record<string, DojoRosterEntry>, groups: ReadonlyMap<string, Group>): Record<string, DojoRosterEntry> {
174 let out = prev
175 for (const [key, g] of groups) {
176 const status = g.running > 0 ? 'running' : g.last
177 if (status === undefined) continue
178 const before = prev[key]
179 if (before !== undefined && before.status === status && (status !== 'running' || before.task === g.task)) continue
180 out = {
181 ...out,
182 [key]: {
183 status,
184 count: before?.count ?? 1,
185 task: g.running > 0 ? g.task : (before?.task ?? ''),
186 ...(before?.says === undefined ? {} : { says: before.says }),
187 },
188 }
189 }
190 return out
191}
192
193/** Keeps a start time and a token count for each running crew id: new ids start now, ended ones go. */
194async function trackRuns($: Engine, ids: readonly string[]) {
195 const held = await read($, runs)
196 const live = new Set(ids)
197 const isStale = Object.keys(held).some(id => !live.has(id))
198 const isFresh = ids.some(id => held[id] === undefined)
199 if (!isStale && !isFresh) return
200 const now = await $.clock.now()
201 await update($, runs, r => {
202 const next: Record<string, DojoRun> = {}
203 for (const id of ids) next[id] = r[id] ?? { startedAt: now, ...NO_TOKENS }
204 return next
205 })
206}
207
208async function tick($: Engine, options: Options) {
209 const crew = (await $.agent.list()).filter(a => crewKey(a.type) !== null)
210 const rows: DojoCrewRow[] = []
211 const groups = new Map<string, Group>()
212 const finished: { key: string; ok: boolean }[] = []
213 for (const a of crew) {
214 const key = crewKey(a.type)
215 if (key === null || CREW[key] === undefined) continue
216 const before = seen.get(a.id)
217 seen.set(a.id, a.status)
218 const g = groups.get(key) ?? { running: 0, task: '' }
219 groups.set(key, g)
220 if (TERMINAL.has(a.status)) {
221 g.last = a.status === 'completed' ? 'returned' : 'fell'
222 if (before !== undefined && !TERMINAL.has(before)) finished.push({ key, ok: a.status === 'completed' })
223 } else {
224 g.running += 1
225 g.task = a.description
226 rows.push({ id: a.id, key, description: a.description })
227 }
228 }
229
230 const keepRoster = isOn(options, 'rosterPane') || isOn(options, 'toasts')
231 let table: Record<string, DojoRosterEntry> = {}
232 if (keepRoster) {
233 const now = await read($, roster)
234 table = foldRoster(now, groups) === now ? now : await update($, roster, r => foldRoster(r, groups))
235 }
236
237 if (finished.length > 0 && isOn(options, 'rosterPane')) {
238 try {
239 await update($, stats, s => finished.reduce((t, f) => addStats(t, f.key, f.ok ? { returned: 1 } : { fell: 1 }), s))
240 } catch {
241 // the figures are a garnish
242 }
243 }
244 const promoted = await awardRank($, options, finished.filter(f => f.ok).length)
245
246 // one toast per agent that ended; the return that earned a new rank speaks as the rank-up instead
247 if (isOn(options, 'toasts')) {
248 let wins = 0
249 for (const f of finished) {
250 if (f.ok) wins += 1
251 if (f.ok && promoted !== undefined && wins === promoted.win) {
252 $.ui.toast(promoted.text, { timeoutMs: TOAST_MS.rankUp })
253 continue
254 }
255 const nth = table[f.key]?.count ?? 1
256 if (f.ok) $.ui.toast(returnToast(f.key, nth, table[f.key]?.says), { timeoutMs: TOAST_MS.return })
257 else $.ui.toast(fallToast(f.key, nth), { timeoutMs: TOAST_MS.fall })
258 }
259 }
260 if (finished.length > 0) await cue($, options, finished.some(f => !f.ok) ? 'fall' : 'return')
261
262 if (rows.length === 0) {
263 timer?.cancel()
264 timer = undefined
265 }
266 if (!isOn(options, 'band')) return
267 await trackRuns($, rows.map(r => r.id))
268 await update($, band, b =>
269 rows.length === 0 && b.rows.length === 0 ? b : { frame: rows.length === 0 ? 0 : b.frame + 1, rows },
270 )
271}
272
273/** The rank points: held in state once loaded from the plugin store. Writes state, so never call it while drawing. */
274async function loadRank($: Engine): Promise<DojoRank> {
275 const held = await read($, rank)
276 if (held !== null) return held
277 let first: DojoRank
278 try {
279 first = { points: pointsOf(await $.store.get(RANK_STORE_KEY)), saved: true }
280 } catch {
281 // no store: the points live in this session only, and say so
282 first = { points: 0, saved: false }
283 }
284 return (await update($, rank, r => r ?? first)) ?? first
285}
286
287/** The rank points for a drawing: state when loaded, else read from the store without writing state. */
288async function peekRank($: Engine, options: Options): Promise<DojoRank | undefined> {
289 if (!isOn(options, 'rank')) return undefined
290 const held = await read($, rank)
291 if (held !== null) return held
292 try {
293 return { points: pointsOf(await $.store.get(RANK_STORE_KEY)), saved: true }
294 } catch {
295 return { points: 0, saved: false }
296 }
297}
298
299/**
300 * Adds `wins` returned crew to the points and saves them. When that reaches a new rung it answers with the rung's
301 * toast text in the strategist's voice and `win`, which of the returns (1-based) crossed the line.
302 */
303async function awardRank($: Engine, options: Options, wins: number): Promise<{ win: number; text: string } | undefined> {
304 if (wins <= 0 || !isOn(options, 'rank')) return undefined
305 try {
306 const before = await loadRank($)
307 const grown = (r: DojoRank | null): DojoRank => {
308 const cur = r ?? before
309 return { points: cur.points + wins, saved: cur.saved }
310 }
311 const after = (await update($, rank, grown)) ?? grown(null)
312 if (after.saved) {
313 try {
314 await $.store.set(RANK_STORE_KEY, { points: after.points })
315 } catch {
316 await update($, rank, r => (r === null ? r : { ...r, saved: false }))
317 }
318 }
319 if (isOn(options, 'toasts')) {
320 const persona = await personaKey($)
321 const now = rankOf(after.points, persona)
322 if (now.index > rankOf(after.points - wins, persona).index) {
323 let win = wins
324 while (win > 1 && rankOf(after.points - wins + win - 1, persona).index === now.index) win -= 1
325 return { win, text: rankUpText(now, persona) }
326 }
327 }
328 } catch {
329 // the rank is a garnish
330 }
331 return undefined
332}
333
334function ensureTick($: Engine, options: Options) {
335 const wanted = ['band', 'toasts', 'sounds', 'rosterPane', 'rank'].some(name => isOn(options, name))
336 if (timer !== undefined || !wanted) return
337 timer = $.clock.every(TICK_MS, () => {
338 tick($, options).catch(() => {})
339 })
340}
341
342/** What the roster pane (and its text fallback) is drawn from. */
343async function rosterInput($: Engine, options: Options, columns: number) {
344 const points = await peekRank($, options)
345 return {
346 persona: await personaKey($),
347 voice: await read($, voice),
348 entries: await read($, roster),
349 frame: (await read($, band)).frame,
350 columns,
351 mode: await read($, paletteMode),
352 stats: await read($, stats),
353 ...(points === undefined ? {} : { rank: points }),
354 }
355}
356
357/** What the mission report is drawn from; the usage atom, or the session's own figures before the first measure. */
358async function recapInput($: Engine, options: Options, columns: number) {
359 let figures = await read($, usage)
360 if (figures === null) {
361 try {
362 figures = snapshotUsage(await $.session.usage())
363 } catch {
364 figures = null
365 }
366 }
367 const points = await peekRank($, options)
368 return {
369 persona: await personaKey($),
370 stats: await read($, stats),
371 usage: figures,
372 columns,
373 mode: await read($, paletteMode),
374 ...(points === undefined ? {} : { rank: points }),
375 }
376}
377
378/** Opens a pane for a command; a pane that cannot be placed answers with `text` instead. */
379async function openPane($: Engine, spec: { id: string; title: string; rows: number }, text: () => Promise<string>) {
380 const opened = await $.ui.open({ ...spec, focus: true, closeOnEscape: true })
381 return opened.isPlaced ? {} : { text: await text() }
382}
383
384export const installChrome: Installer = (on, options) => {
385 // Deploy toast and sound for a dojo subagent that started, and a tick to watch it. The state recorders have written the roster by now.
386 on('agent.spawn', { subagentType: /^dojo:(?!strategist$)/ }, async ($, e, next) => {
387 const ran = await next(e)
388 const key = crewKey(e.subagentType)
389 if (ran.deny === undefined && ran.agentId !== undefined && key !== null) {
390 try {
391 seen.set(ran.agentId, 'running')
392 const c = CREW[key]
393 let nth = 1
394 if (isOn(options, 'rosterPane') || isOn(options, 'toasts')) nth = (await read($, roster))[key]?.count ?? 1
395 if (c !== undefined && isOn(options, 'toasts')) $.ui.toast(deployToast(key, nth), { timeoutMs: TOAST_MS.deploy })
396 await cue($, options, 'deploy')
397 ensureTick($, options)
398 } catch {
399 // chrome only: the subagent has started either way
400 }
401 }
402 return ran
403 })
404
405 // A subagent at work keeps the tick running; the tool it called is recorded by the state recorders.
406 on('tool.call', { agentId: /./ }, async ($, e, next) => {
407 if (e.agentId !== undefined && isOn(options, 'band')) ensureTick($, options)
408 return next(e)
409 })
410
411 on('ui.render', { component: 'Spinner' }, async ($, e, next) => {
412 // a message (compacting, rewinding) is the engine's own state line: leave it alone
413 if (!isOn(options, 'spinners') || e.props.message !== null) return next(e)
414 let props = e.props
415 try {
416 const n = (await read($, turn)) ?? 0
417 const beat = (await read($, pulse)) ?? 0
418 spinnerDraws += 1
419 try {
420 startPulse($)
421 } catch {
422 // no clock to animate with: the first verb stands still
423 }
424 const step = Math.floor(beat / VERB_EVERY)
425 const agent = (await $.agent.list()).find(a => a.id === e.requestId)
426 const key = agent === undefined ? null : crewKey(agent.type)
427 const crew = key === null ? undefined : CREW[key]
428 let word: string | undefined
429 let owner: string | undefined
430 if (key !== null && crew !== undefined) {
431 owner = key
432 word = `${crew.emoji} ${verbAt(key, n, e.requestId, step)}`
433 } else if (agent === undefined) {
434 const theme = await mainTheme($, options)
435 if (theme !== null) {
436 owner = theme.key
437 word = `${theme.emoji} ${verbAt(theme.key, n, '', step)}`
438 }
439 }
440 if (word !== undefined && owner !== undefined) {
441 const frames = framesOf(owner)
442 // the animated glyph rides after the ellipsis; the terminal is the surface that documents a suffix rewrite
443 props =
444 e.surface === 'terminal'
445 ? { ...e.props, word, suffix: `${e.props.suffix} ${frames[beat % frames.length] ?? ''}`.trimEnd() }
446 : { ...e.props, word }
447 }
448 } catch {
449 props = e.props
450 }
451 return next({ ...e, props } as typeof e)
452 })
453
454 on('ui.render', { component: 'TurnDuration' }, async ($, e, next) => {
455 if (!isOn(options, 'turnFlair')) return next(e)
456 let word: string | undefined
457 try {
458 const theme = await mainTheme($, options)
459 if (theme?.done !== undefined) {
460 const n = (await read($, turn)) ?? 0
461 word = turnWord(theme.key, theme.done, e.props.durationMs, n)
462 }
463 } catch {
464 word = undefined
465 }
466 return word === undefined ? next(e) : next({ ...e, props: { ...e.props, word } })
467 })
468
469 // The crew band rows first, so they sit under the engine's own agent line, then one usage row last (when on and known; the state recorders keep its figures), just above the prompt.
470 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
471 const wantBand = isOn(options, 'band')
472 const wantUsage = isOn(options, 'usageLine')
473 if ((!wantBand && !wantUsage) || e.props.hasSurvey) return next(e)
474 let tree: RenderElement | undefined
475 try {
476 const persona = await personaKey($)
477 const mode = await read($, paletteMode)
478 const columns = e.props.bodyColumns
479 const bandState = wantBand ? await read($, band) : undefined
480 const crewOut = bandState !== undefined && bandState.rows.length > 0
481 // with a single row to spare the crew band keeps it
482 let usageRow: Line | undefined
483 if (wantUsage && !(crewOut && e.props.maxRows < 2)) {
484 try {
485 usageRow = planUsage({ persona, usage: (await read($, usage)) ?? snapshotUsage(await $.session.usage()), columns, mode })
486 } catch {
487 usageRow = undefined
488 }
489 }
490 let lines: Line[] = []
491 if (bandState !== undefined && crewOut) {
492 const latest = await read($, tools)
493 const held = await read($, runs)
494 let now: number | undefined
495 try {
496 now = await $.clock.now()
497 } catch {
498 now = undefined
499 }
500 lines = [
501 ...planBand({
502 persona,
503 rows: bandState.rows.map(r => {
504 const run = held[r.id]
505 return {
506 key: r.key,
507 description: r.description,
508 tool: latest[r.id],
509 ...(run === undefined || now === undefined ? {} : { elapsedMs: Math.max(0, now - run.startedAt) }),
510 ...(run === undefined || agentTokens(run) <= 0 ? {} : { tokens: agentTokens(run) }),
511 }
512 }),
513 frame: bandState.frame,
514 columns,
515 maxRows: e.props.maxRows - (usageRow === undefined ? 0 : 1),
516 mode,
517 }),
518 ]
519 }
520 if (usageRow !== undefined) lines = [...lines, usageRow]
521 if (lines.length > 0) {
522 const { Box, Text } = $.ui.resolve(e)
523 tree = <Box flexDirection="column">{lines.map((l, i) => drawLine(Text, l, `band-${i}`))}</Box>
524 }
525 } catch {
526 tree = undefined
527 }
528 return tree ?? next(e)
529 })
530
531 // The footer keeps the modes' names, dim, and ends on the strategist's small tag in its color.
532 on('ui.render', { component: 'SessionMode' }, async ($, e, next) => {
533 if (!isOn(options, 'promptChrome')) return next(e)
534 let tree: RenderElement | undefined
535 try {
536 const line = planModes(await personaKey($), e.props.modes, await read($, paletteMode))
537 if (line !== undefined) tree = drawLine($.ui.resolve(e).Text, line, 'modes')
538 } catch {
539 tree = undefined
540 }
541 return tree ?? next(e)
542 })
543
544 // /dojo, /dojo-recap and /dojo-gallery open panes. Commands can only be registered once an interactive session binds.
545 on('session.start', { isInteractive: true }, async ($, e, next) => {
546 if (isOn(options, 'rosterPane')) {
547 for (const spec of COMMANDS) {
548 try {
549 await $.command.register(spec)
550 } catch {
551 // a name taken or refused: the other commands still stand
552 }
553 }
554 }
555 return next(e)
556 })
557
558 on('command.run', { command: 'dojo' }, async ($, e, next) => {
559 if (!isOn(options, 'rosterPane')) return next(e)
560 try {
561 return await openPane($, { id: PANE_ID, title: 'Dojo roster', rows: 22 }, async () =>
562 rosterText(await rosterInput($, options, e.presentation.columns)),
563 )
564 } catch {
565 return next(e)
566 }
567 })
568
569 on('command.run', { command: 'dojo-recap' }, async ($, e, next) => {
570 if (!isOn(options, 'rosterPane')) return next(e)
571 try {
572 return await openPane($, { id: RECAP_ID, title: 'Mission report', rows: 18 }, async () =>
573 recapText(await recapInput($, options, e.presentation.columns)),
574 )
575 } catch {
576 return next(e)
577 }
578 })
579
580 on('command.run', { command: 'dojo-gallery' }, async ($, e, next) => {
581 if (!isOn(options, 'rosterPane')) return next(e)
582 try {
583 return await openPane($, { id: GALLERY_ID, title: 'Dojo gallery', rows: 26 }, async () =>
584 galleryText({ index: await read($, gallery), columns: e.presentation.columns, mode: await read($, paletteMode) }),
585 )
586 } catch {
587 return next(e)
588 }
589 })
590
591 // One hook for the three dojo panes: the roster, the mission report and the gallery.
592 on('ui.render', { component: 'Pane', requestId: /^dojo-(roster|recap|gallery)$/ }, async ($, e, next) => {
593 if (!isOn(options, 'rosterPane')) return next(e)
594 let tree: RenderElement | undefined
595 try {
596 const columns = e.props.bodyColumns
597 const mode = await read($, paletteMode)
598 const isGallery = e.requestId === GALLERY_ID
599 const lines =
600 e.requestId === RECAP_ID
601 ? recapLines(await recapInput($, options, columns))
602 : isGallery
603 ? galleryLines({ index: await read($, gallery), columns, mode })
604 : rosterLines(await rosterInput($, options, columns))
605 const id = e.requestId
606 const { Box, Text, Button } = $.ui.resolve(e)
607 const closePane = () => {
608 $.ui.close({ id }).catch(() => {})
609 }
610 const close = <Button key="close" label="close" hotkey="q" onPress={closePane} />
611 const step = (by: number) => {
612 update($, gallery, n => (((n + by) % GALLERY_ORDER.length) + GALLERY_ORDER.length) % GALLERY_ORDER.length).catch(() => {})
613 }
614 const note = (text: string) => (
615 <Text dimColor wrap="truncate-end">
616 {text}
617 </Text>
618 )
619 // the gallery page is taller than the pane: its keys sit on top, the arrows scroll the rest
620 tree = isGallery ? (
621 <Box flexDirection="column">
622 {lines.slice(0, 1).map((l, i) => drawLine(Text, l, `pane-${i}`))}
623 <Box gap={1}>
624 <Button key="prev" label="< prev (p)" hotkey="p" onPress={() => step(-1)} />
625 <Button key="next" label="next (n)" hotkey="n" onPress={() => step(1)} />
626 <Button key="close" label="close (q)" hotkey="q" onPress={closePane} />
627 {note('↑↓ scroll')}
628 </Box>
629 {lines.slice(1).map((l, i) => drawLine(Text, l, `pane-${i + 1}`))}
630 </Box>
631 ) : (
632 <Box flexDirection="column">
633 {lines.map((l, i) => drawLine(Text, l, `pane-${i}`))}
634 <Box marginTop={1} gap={1}>
635 {close}
636 {note('esc closes')}
637 </Box>
638 </Box>
639 )
640 } catch {
641 tree = undefined
642 }
643 return tree ?? next(e)
644 })
645}
646mods/visuals/transcript.tsx 490 lines1import { atom, read } from 'claude-code'
2import type { BoxProps, EngineInterface as Engine, ElementConstructor, RenderNode, TextProps } from 'claude-code'
3
4import { isOn } from '../lib/options'
5import type { Installer, Options } from '../lib/options'
6import { crewKey, strategistKey } from '../lib/persona'
7import { CREW, FELL_EMOJI, NEUTRAL, STRATEGISTS } from '../theme'
8import type { PaletteMode, Theme } from '../theme'
9import { BUBBLES, COMMAND_TITLES, DEPLOY_LINES, FALLEN_LINES, MOTIFS, RETURN_LINES } from './transcript-art'
10import {
11 FALLEN_STATUSES,
12 WIDE,
13 agentFacts,
14 bannerRows,
15 cells,
16 columnsOf,
17 crewOfInput,
18 descriptionOf,
19 dojoCommand,
20 duration,
21 dutyNameOf,
22 extractSays,
23 fitLine,
24 line,
25 modeOf,
26 paint,
27 statsLine,
28 tinyMark,
29} from './transcript-lib'
30
31// Transcript makeover (userConfig `transcriptTheme`; `banners` brings back the full crew cards with ASCII art).
32// By default a crew moment is one line: who, what, a signature quote. Decoration only: every hook asks the engine for its own drawing first and wraps it. Whatever happens here,
33// the engine's drawing is what comes back.
34
35// The module scan reads an atom only from a const of the file that uses it; the {plugin, key} pair is the shared name.
36const strategist = atom({ plugin: 'dojo', key: 'strategist' } as const, null)
37/** tool_use_id of a call a subagent made -> its crew key, or `-` for any other subagent. The main thread has no entry. The state recorders write it. */
38const callers = atom({ plugin: 'dojo', key: 'callers' } as const, {} as Record<string, string>)
39/** tool_use_id of an Agent call -> the crew key it spawns, or `-` for any other agent type. The state recorders write it. */
40const spawns = atom({ plugin: 'dojo', key: 'spawns' } as const, {} as Record<string, string>)
41/** The palette in force; the state recorders write it. Dark until it says otherwise. */
42const paletteMode = atom({ plugin: 'dojo', key: 'paletteMode' } as const, 'dark' as PaletteMode)
43
44type UI = { Box: ElementConstructor<BoxProps>; Text: ElementConstructor<TextProps> }
45type CardState = 'deployed' | 'returned' | 'fell' | 'recalled' | 'background'
46
47const motifOf = (key: string) => MOTIFS[key] ?? (MOTIFS.strategist as (typeof MOTIFS)[string])
48
49/** `t` with its colors resolved for the palette in force. Every color this module draws comes from here. */
50async function painted($: Engine, t: Theme): Promise<Theme> {
51 return paint(t, modeOf(await read($, paletteMode)))
52}
53
54async function mainTheme($: Engine, options: Options): Promise<Theme | null> {
55 const key = (await read($, strategist)) ?? strategistKey(await $.env.get('DOJO_STRATEGIST'))
56 const t = key !== null ? (STRATEGISTS[key] ?? null) : isOn(options, 'neutralMainTheme') ? NEUTRAL : null
57 return t === null ? null : painted($, t)
58}
59
60/** Which crew member made tool call `id`: their theme, or null for the main thread and for a subagent that is no dojo crew. */
61async function callerTheme($: Engine, id: string): Promise<Theme | null> {
62 const lane = (await read($, callers))[id]
63 const t = lane === undefined || lane === '-' ? null : (CREW[lane] ?? null)
64 return t === null ? null : painted($, t)
65}
66
67/** A one-cell-wide stripe in `color`, as tall as what stands beside it. */
68function stripe({ Box }: UI, color: string) {
69 return <Box width={1} flexShrink={0} marginRight={1} backgroundColor={color} />
70}
71
72/** `inner` beside a stripe. */
73function striped(ui: UI, color: string, inner: RenderNode) {
74 const { Box } = ui
75 return (
76 <Box flexDirection="row">
77 {stripe(ui, color)}
78 <Box flexDirection="column" flexGrow={1} flexShrink={1}>
79 {inner}
80 </Box>
81 </Box>
82 )
83}
84
85/** `inner` after the emoji of the crew members behind it, on the same row. */
86function prefixed(ui: UI, who: readonly Theme[], inner: RenderNode) {
87 const { Box, Text } = ui
88 const first = who[0]
89 if (first === undefined) return <Box>{inner}</Box>
90 return (
91 <Box flexDirection="row">
92 <Box flexShrink={0} marginRight={1}>
93 <Text color={who.length === 1 ? first.color : undefined} wrap="truncate-end">
94 {who.map(t => t.emoji).join(' ')}
95 </Text>
96 </Box>
97 <Box flexDirection="column" flexGrow={1} flexShrink={1}>
98 {inner}
99 </Box>
100 </Box>
101 )
102}
103
104/** A one-word mark above an errored crew result; the error text itself is the engine's. Longer marks are dropped. */
105function errorMark({ Text }: UI, who: Theme, mark: string) {
106 return (
107 <Text wrap="truncate-end">
108 <Text color={who.color}>{who.emoji}</Text>
109 <Text color="error">{' ✗'}</Text>
110 <Text dimColor>{` ${mark}`}</Text>
111 </Text>
112 )
113}
114
115type Moment = {
116 theme: Theme
117 /** Draws the fallen skull instead of the character's emoji. */
118 fell?: boolean
119 glyph: string
120 glyphColor?: string
121 /** Dim text right after the glyph: a duration, `fell`. */
122 detail?: string
123 task?: string
124 quote?: string
125 cols: number
126}
127
128/** A crew moment as one line: emoji and name in the character's color, glyph, dim detail, task, then the quote dim and italic. */
129function momentLine({ Text }: UI, m: Moment) {
130 const t = m.theme
131 const head = `${m.fell === true ? FELL_EMOJI : t.emoji} ${t.name}`
132 const detail = m.detail ?? ''
133 const fixed = cells(head) + 1 + cells(m.glyph) + (detail === '' ? 0 : 1 + cells(detail))
134 const fit = fitLine({ fixed, lead: ' ', task: m.task ?? '', quote: m.quote ?? '', cols: m.cols })
135 return (
136 <Text wrap="truncate-end">
137 <Text color={t.color} bold>
138 {head}
139 </Text>
140 <Text color={m.glyphColor}>{` ${m.glyph}`}</Text>
141 {detail === '' ? null : <Text dimColor>{` ${detail}`}</Text>}
142 {fit.task === '' ? null : <Text>{` ${fit.task}`}</Text>}
143 {fit.quote === '' ? null : (
144 <Text color={t.accent} italic dimColor>
145 {` “${fit.quote}”`}
146 </Text>
147 )}
148 </Text>
149 )
150}
151
152type Card = {
153 theme: Theme
154 state: CardState
155 description: string
156 cols: number
157 banners: boolean
158 salt: string
159 stats?: string
160}
161
162const STATE_LABEL: Record<CardState, string> = {
163 deployed: '▸ deployed',
164 returned: '✓ returned',
165 fell: '✗ fell',
166 recalled: '↩ recalled',
167 background: '… running in background',
168}
169
170function cardLine(c: Card): string {
171 const pool = c.state === 'deployed' ? DEPLOY_LINES : c.state === 'returned' ? RETURN_LINES : c.state === 'fell' ? FALLEN_LINES : undefined
172 return line(pool?.[c.theme.key], c.salt)
173}
174
175/** A crew member's card: banner, header, task, signature. One compact line when the width is short. */
176function crewCard(ui: UI, c: Card) {
177 const { Box, Text } = ui
178 const t = c.theme
179 const fell = c.state === 'fell'
180 const emoji = fell ? FELL_EMOJI : t.emoji
181 const label = STATE_LABEL[c.state]
182 if (c.cols < WIDE) {
183 const task = c.description === '' ? '' : ` · ${c.description}`
184 return (
185 <Text color={t.color} bold={!fell} dimColor={fell} wrap="truncate-end">
186 {`${emoji} ${t.name} · ${label}${task}`}
187 </Text>
188 )
189 }
190 const width = Math.min(c.cols - 2, 46)
191 const art = c.banners ? bannerRows(t.key, width - 4) : []
192 const said = cardLine(c)
193 return (
194 <Box flexDirection="column" borderStyle="round" borderColor={fell ? 'error' : t.color} borderDimColor={fell} paddingX={1} width={width}>
195 {art.map((row, i) => (
196 <Text key={`art-${i}`} color={t.color} dimColor={fell} wrap="truncate-end">
197 {row}
198 </Text>
199 ))}
200 <Text wrap="truncate-end">
201 <Text color={t.color} bold>
202 {`${emoji} ${t.name}`}
203 </Text>
204 <Text dimColor>{` · ${t.role} · `}</Text>
205 <Text color={fell ? 'error' : t.color}>{label}</Text>
206 </Text>
207 {c.description === '' ? null : <Text wrap="wrap">{`task ${c.description}`}</Text>}
208 {c.stats === undefined || c.stats === '' ? null : (
209 <Text dimColor wrap="truncate-end">
210 {c.stats}
211 </Text>
212 )}
213 {said === '' ? null : (
214 <Text color={t.color} italic dimColor={fell} wrap="wrap">
215 {`“${said}”`}
216 </Text>
217 )}
218 </Box>
219 )
220}
221
222/** The `Says:` line as a speech bubble in the character's colour. */
223function bubble(ui: UI, t: Theme, says: string, cols: number) {
224 const { Box, Text } = ui
225 if (cols < WIDE) {
226 return (
227 <Text color={t.color} italic wrap="wrap">
228 {`${t.emoji} “${says}”`}
229 </Text>
230 )
231 }
232 const shape = BUBBLES[t.key] ?? { borderStyle: 'round', tail: '<' }
233 const prefix = `${t.emoji} ${shape.tail}`
234 const avail = cols - cells(prefix) - 2
235 const width = Math.max(10, Math.min(avail, cells(says) + 4))
236 return (
237 <Box flexDirection="row" alignItems="center">
238 <Box flexShrink={0}>
239 <Text color={t.color}>{prefix}</Text>
240 </Box>
241 <Box borderStyle={shape.borderStyle} borderColor={t.color} paddingX={1} width={width}>
242 <Text color={t.color} italic wrap="wrap">
243 {says}
244 </Text>
245 </Box>
246 </Box>
247 )
248}
249
250export const installTranscript: Installer = (on, options) => {
251 const themed = () => isOn(options, 'transcriptTheme')
252 // Full crew cards with ASCII banners are opt-in: only an explicit true turns them on.
253 const cardsOn = () => options.banners === true
254
255 // The strategist's reply keeps only its thin colored stripe.
256 on('ui.render', { component: 'AssistantMessage' }, async ($, e, next) => {
257 const base = await next(e)
258 if (!themed()) return base
259 try {
260 const t = await mainTheme($, options)
261 if (t === null) return base
262 return striped($.ui.resolve(e), t.color, base)
263 } catch {
264 return base
265 }
266 })
267
268 on('ui.render', { component: 'ToolUse' }, async ($, e, next) => {
269 const base = await next(e)
270 if (!themed()) return base
271 try {
272 const ui = $.ui.resolve(e)
273 const { Box } = ui
274 const cols = columnsOf(e.viewport)
275 const p = e.props
276 const who = await callerTheme($, p.tool_use_id)
277 const row = who === null ? base : prefixed(ui, [who], base)
278 const spawned = p.tool === 'Agent' ? crewOfInput(p.input) : null
279 const crewBase = spawned === null ? undefined : CREW[spawned]
280 if (crewBase === undefined) return row
281 const crew = await painted($, crewBase)
282 const description = descriptionOf(p.input)
283 let top: RenderNode
284 if (cardsOn()) {
285 const state: CardState = p.isErrored ? 'fell' : p.isInterrupted ? 'recalled' : 'deployed'
286 top = crewCard(ui, { theme: crew, state, description, cols, banners: true, salt: p.tool_use_id })
287 } else if (p.isErrored) {
288 top = momentLine(ui, {
289 theme: crew,
290 fell: true,
291 glyph: '✗',
292 glyphColor: 'error',
293 detail: 'fell',
294 quote: line(FALLEN_LINES[crew.key], p.tool_use_id),
295 cols,
296 })
297 } else if (p.isInterrupted) {
298 top = momentLine(ui, { theme: crew, glyph: '↩', detail: 'recalled', task: description, cols })
299 } else {
300 top = momentLine(ui, { theme: crew, glyph: '▸', task: description, quote: line(DEPLOY_LINES[crew.key], p.tool_use_id), cols })
301 }
302 return (
303 <Box flexDirection="column">
304 {top}
305 {row}
306 </Box>
307 )
308 } catch {
309 return base
310 }
311 })
312
313 on('ui.render', { component: 'ToolResult' }, async ($, e, next) => {
314 const base = await next(e)
315 if (!themed()) return base
316 try {
317 const ui = $.ui.resolve(e)
318 const { Box } = ui
319 const cols = columnsOf(e.viewport)
320 const p = e.props
321 if (p.tool === 'Agent') {
322 const facts = agentFacts(p.output)
323 const lane = (await read($, spawns))[p.tool_use_id]
324 let key = lane !== undefined && lane !== '-' ? lane : null
325 if (lane === undefined && facts.agentType !== null) key = crewKey(facts.agentType)
326 const crewBase = key === null ? undefined : CREW[key]
327 if (crewBase !== undefined) {
328 const crew = await painted($, crewBase)
329 let fell = p.isErrored || (facts.status !== null && FALLEN_STATUSES.has(facts.status))
330 if (!fell && facts.agentId !== null) {
331 try {
332 const found = (await $.agent.list()).find(a => a.id === facts.agentId)
333 fell = found !== undefined && FALLEN_STATUSES.has(found.status)
334 } catch {
335 // the roster is a second opinion only: the result itself decides
336 }
337 }
338 const background = !fell && facts.status === 'async_launched'
339 if (cardsOn()) {
340 const state: CardState = fell ? 'fell' : background ? 'background' : 'returned'
341 const says = fell || background ? null : extractSays(facts.text)
342 const card = crewCard(ui, {
343 theme: crew,
344 state,
345 description: '',
346 cols,
347 banners: true,
348 salt: p.tool_use_id,
349 stats: statsLine(facts),
350 })
351 return (
352 <Box flexDirection="column">
353 {card}
354 {says === null ? null : bubble(ui, crew, says, cols)}
355 {base}
356 </Box>
357 )
358 }
359 // a background launch is no return: the spawn line already said it
360 if (background) return base
361 const moment = fell
362 ? momentLine(ui, {
363 theme: crew,
364 fell: true,
365 glyph: '✗',
366 glyphColor: 'error',
367 detail: 'fell',
368 quote: line(FALLEN_LINES[crew.key], p.tool_use_id),
369 cols,
370 })
371 : momentLine(ui, {
372 theme: crew,
373 glyph: '✓',
374 glyphColor: 'success',
375 ...(facts.durationMs === null ? {} : { detail: duration(facts.durationMs) }),
376 quote: extractSays(facts.text) ?? line(RETURN_LINES[crew.key], p.tool_use_id),
377 cols,
378 })
379 return (
380 <Box flexDirection="column">
381 {moment}
382 {base}
383 </Box>
384 )
385 }
386 }
387 if (!p.isErrored) return base
388 const who = await callerTheme($, p.tool_use_id)
389 const mark = who === null ? null : tinyMark(who.key)
390 if (who === null || mark === null) return base
391 return (
392 <Box flexDirection="column">
393 {errorMark(ui, who, mark)}
394 {base}
395 </Box>
396 )
397 } catch {
398 return base
399 }
400 })
401
402 on('ui.render', { component: 'ToolGroup' }, async ($, e, next) => {
403 const base = await next(e)
404 if (!themed()) return base
405 try {
406 const ui = $.ui.resolve(e)
407 const lanes = await read($, callers)
408 const who: Theme[] = []
409 for (const call of e.props.calls) {
410 const lane = call.tool_use_id === undefined ? undefined : lanes[call.tool_use_id]
411 const known = lane === undefined || lane === '-' ? null : (CREW[lane] ?? null)
412 if (known === null || who.some(w => w.key === known.key)) continue
413 who.push(await painted($, known))
414 }
415 if (who.length === 0) return base
416 return prefixed(ui, who, base)
417 } catch {
418 return base
419 }
420 })
421
422 on('ui.render', { component: 'ToolProgress' }, async ($, e, next) => {
423 const base = await next(e)
424 if (!themed()) return base
425 try {
426 const ui = $.ui.resolve(e)
427 const who = await callerTheme($, e.props.tool_use_id)
428 if (who === null) return base
429 return prefixed(ui, [who], base)
430 } catch {
431 return base
432 }
433 })
434
435 on('ui.render', { component: 'CommandOutput' }, async ($, e, next) => {
436 const base = await next(e)
437 if (!themed()) return base
438 try {
439 const command = dojoCommand(e.props.command)
440 if (command === null || e.props.isErrored) return base
441 let t = await mainTheme($, options)
442 let art: string | null = null
443 if (command === 'dojo-duty') {
444 const named = dutyNameOf(e.props.text, Object.keys(STRATEGISTS))
445 if (named !== null) {
446 const picked = STRATEGISTS[named]
447 t = picked === undefined ? t : await painted($, picked)
448 art = named
449 }
450 }
451 if (t === null) return base
452 const { Box, Text } = $.ui.resolve(e)
453 const cols = columnsOf(e.viewport)
454 if (!cardsOn()) {
455 return (
456 <Box flexDirection="column">
457 <Text wrap="truncate-end">
458 <Text color={t.color} bold>
459 {`${t.emoji} ${t.name}`}
460 </Text>
461 <Text dimColor>{` · ${COMMAND_TITLES[command]}`}</Text>
462 </Text>
463 {base}
464 </Box>
465 )
466 }
467 const m = motifOf(t.key)
468 const rows = art !== null && cols >= WIDE ? bannerRows(art, cols - 4) : []
469 return (
470 <Box flexDirection="column" borderStyle="round" borderColor={t.color} paddingX={1}>
471 {rows.map((row, i) => (
472 <Text key={`art-${i}`} color={t.color} wrap="truncate-end">
473 {row}
474 </Text>
475 ))}
476 <Text wrap="truncate-end">
477 <Text color={t.color} bold>
478 {`${t.emoji} ${m.glyph} ${t.name}`}
479 </Text>
480 <Text color={t.accent}>{` · ${COMMAND_TITLES[command]}`}</Text>
481 </Text>
482 {base}
483 </Box>
484 )
485 } catch {
486 return base
487 }
488 })
489}
490mods/lib/options.ts 10 lines1import type { On, PluginOptions } from 'claude-code'
2
3export type Options = PluginOptions
4
5/** A feature installer: registers its hooks on `on`, reading its toggles from `options`. */
6export type Installer = (on: On, options: Options) => void
7
8/** Every feature is a `userConfig` toggle: on unless explicitly false. */
9export const isOn = (options: Options, name: string): boolean => options[name] !== false
10