SLOPSHOPPER

raven

A live preview pane beside the transcript: the session's diff with review comments, and rendered plans and docs as Claude writes them.

panebandrowsguardcommandtoast
★ 3v0.4.0Apache-2.0updated 2026-10-22arunkumar9t2/raven/plugins/raven
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · raven
│ ┃ Diff ✕ › fix the failing auth╭────────────────────────────────────────────╮ │ ┃ 󰊢 1 file ▁ · source: HEAD ▾ ↑ ↓ ▣ c │ raven │ │ ┃ ▣ client module ../surface/strip.tsx ⏺ Read(src/auth.ts) │ Close the built-in diff panel (✕) once so │ │ ┃ ──────────────────────────────────────────── ⎿ Read 6 lines │ Raven can dock beside the transcript │ │ ┃ ─────────── ⏺ Update(src/auth.ts) ╰────────────────────────────────────────────╯ │ ┃ 󰈔 src/auth.ts ?? src/auth.test.ts M ▣ clien ⎿ Added 2 lines, removed 1 line │ ┃ ⏺ Bash(bun test) │ ┃ ▌ No textual changes ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /raven │ ◆ Raven diff shown │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Diff
󰊢 1 file ▁ · source: HEAD ▾ ↑ ↓ ▣ client module ../ ▣ client module ../surface/strip.tsx ─────────────────────────────────────────────────────── 󰈔 src/auth.ts ?? src/auth.test.ts M ▣ client module ../surf ▌ No textual changes
Command output
◆ Raven diff shown
README

Raven

A diff pane that sits next to Claude Code. Watch Claude's edits land, leave a note on the line you mean, and Claude reads it on its next turn.

Claude Code on the left, Raven on the right: a note on a hunk, Claude fixes the line, the note is marked addressed

Claude finishes a turn with "I've updated the retry logic across the codebase", and you scroll up to find out where. Then you describe the line you want changed in English ("the second change, the one with the hours, no, the other one"). Raven is a side panel for that moment.

What you get

<img src="docs/media/raven-grid.webp" alt="Raven's panes: the live diff, notes Claude has addressed, a rendered plan with a note, and the file tree with changes marked" width="640">

  • A live diff. Every changed file in one scrolling view, with syntax highlighting, updated as Claude edits files and runs commands. The file Claude is working on right now is highlighted. In a wide pane the diff shows side by side, with the changed words highlighted.
  • Notes Claude reads. Comment on a file, a hunk or a single line. Your notes go to Claude with your next prompt, or right away with send. After Claude replies, Raven marks the notes it addressed with ✓.
  • Stage and revert a single hunk with a click.
  • Compare against your last commit, the start of the session, the branch point, or one turn's edits.
  • Plans and docs, rendered. Plans and specs show up formatted as Claude writes them, and Claude can show you any Markdown file on request. You can leave notes on their sections too. When Claude wants your sign-off on a doc, it asks: approve, or comment first. Leave your notes in the pane, reply, and they go along with it.
  • Files and Tasks. Your repository tree with changed files marked, and Claude's task list with its progress.
  • Reminders above the prompt. Pending notes and updated plans show there while the pane is closed.

Requirements

  • Claude Code 2.1.287 or later
  • A terminal at least 110 columns wide
  • Bun installed (Claude uses it to run Raven's command-line helper)
  • A Nerd Font Mono variant as your terminal font, for the icons (optional; without one, icons show as blank boxes)
  • Under tmux, CLAUDE_CODE_NO_FLICKER=1 set in your environment

Install

In Claude Code:

/plugin marketplace add arunkumar9t2/raven
/plugin install raven@raven

Then run /reload-plugins, or restart Claude Code.

Use

<img src="docs/media/raven-hero.webp" alt="Claude Code on the left and the Raven diff pane on the right, with a note marked addressed" width="640">

Type /raven to open the diff. Raven also opens on its own when Claude makes its first edit, writes a plan, or starts a task list (see Settings to turn that off).

CommandDoes
/raven or /raven diffopens the diff
/raven docopens the rendered plan or doc
/raven filesopens your repository tree
/raven tasksopens Claude's task list
/raven sendsends your pending notes to Claude now
/raven offcloses every Raven pane and stops Raven opening any by itself
/raven onreopens the panes /raven off closed (the diff if there were none)

Run a pane's command again to close it.

To leave a note, click note on a file or a hunk, pick a line if you want one, type, and press Enter. To send notes without waiting for your next prompt, click send.

You can also ask Claude to show you things, like "show me the plan in raven". To let Claude do that without asking for permission each time, add Bash(raven:*) to the allowed tools in your settings.

Settings

Open /config and look for Raven:

SettingDefaultWhat it does
autoOpenonLets Raven open panes by itself: the diff on Claude's first edit, a plan as Claude writes it, the task list when Claude starts one. Turn it off and panes open only when you (or Claude, when you ask) open them.
autoOpenColumns144Raven only opens by itself when the terminal is at least this many columns wide.
watchedPathsemptyExtra folders, comma-separated, whose Markdown files open rendered as Claude writes them. Plan folders are watched already.
keyboardControlsoffDraws plain buttons you can reach with Tab, so every control works from the keyboard.
cardStylebarHow files, doc sections, the note box and tables are framed: bar (a coloured bar down the left), none (no marks, a rule under titles), sharp or rounded (a closed frame; tables become full grids).
splitColumns160The diff shows side by side when the pane is at least this many columns wide. The split / unified chip in the diff header overrides it, and Raven remembers the choice per repository.
paneBackgroundemptyA colour painted behind every Raven pane so it matches your terminal, for example #101315. Takes #rgb, #rrggbb, rgb(r, g, b) or a theme colour name, which Claude Code resolves. Empty keeps Claude Code's own pane colour.

Settings are read when a session starts, so a change applies to the next session.

Raven cannot read your terminal's background, so set paneBackground to the same colour, the background in your terminal's theme or config.

Troubleshooting

  • The pane doesn't appear. Widen the terminal to at least 110 columns; the pane draws as soon as it fits. Under tmux, set CLAUDE_CODE_NO_FLICKER=1.
  • Claude Code's own diff panel covers Raven. Close it once with its ✕; Claude Code remembers.
  • Raven keeps opening by itself. Turn off autoOpen in /config.
  • Icons look like boxes. Switch your terminal to a Nerd Font.
  • Icons touch or overlap the text after them. Your terminal draws the icons wider than a cell. Set the terminal font itself to a patched Nerd Font Mono (for example IosevkaTerm Nerd Font Mono or JetBrainsMono Nerd Font Mono). A separate symbols font as a fallback is not enough in terminals such as Alacritty, which draw a fallback glyph at its own width.

Contributing

Raven is a Claude Code plugin written in TypeScript. To work on it:

bun install
bun run setup:local    # load this checkout in every local Claude Code session (--remove to undo)
bun run check          # typecheck, lint, tests and plugin validation

claude --plugin-dir ./plugins/raven loads it for a single session instead. The design lives in spec/, and CLAUDE.md covers the layout and workflow.

License

Apache License 2.0. See LICENSE.

Source 78 files
hooks/register.ts 370 lines
1import type { On, PluginOptions, RenderSurface } from 'claude-code'
2import { isCheckpointing } from './core/checkpointing'
3import { commandGlyphOf } from './core/command-glyph'
4import { DIRECTIVE_OPS, withoutDirectives } from './core/directive'
5import type { Host } from './core/host'
6import { isRecord } from './core/is-record'
7import { createRaven, type Raven } from './core/raven'
8import { settingsOf } from './core/settings'
9import type { ToolEvent } from './core/triggers'
10import { capabilitiesOf, type Kit, type Ui } from './core/view'
11import {
12  COMMAND,
13  COMMAND_DESCRIPTION,
14  NAME,
15  PANE_IDS,
16  PANE_SUBCOMMANDS,
17  TOOL_NAME,
18  toolNameOf,
19} from './names'
20import { styleOf } from './ui/style'
21import { commandOutputRow } from './views/band'
22
23// The plugin's own name is only known once `$` binds, so the tool's full name cannot be a static
24// string here; this matches any plugin's `show` tool as `tool.call`'s matcher must be static.
25const TOOL_MATCH = new RegExp(`^mcp__.+__${TOOL_NAME}$`)
26
27const TOOL_DESCRIPTION =
28  'Show something to the user in the Raven preview pane beside the transcript, where they can ' +
29  'comment on it. Use it whenever you produce something the user should read or decide on rather ' +
30  'than scroll past: a plan, spec, design, report or any doc you wrote (`show`), a summary or ' +
31  "checklist you compose (`note`), one file's changes (`diff`), or a pane by name (`open`). Some " +
32  'docs open by themselves, and the result of the edit that wrote them says so; no such note means ' +
33  'it was not shown, so show it. `comments` fetches pending comments on demand.'
34
35/** The context block every conversation carries: that the pane exists, and what it is for. */
36const CONTEXT_TEXT =
37  'Raven docks a preview pane beside the transcript: the live diff, and rendered plans and docs. ' +
38  'The user can comment on diff hunks and doc sections there. Use the Raven show tool to put ' +
39  'something in front of them.'
40
41/** The line Raven's entry in the MCP server instructions reads instead of the engine's stock one. */
42const INSTRUCTIONS_TEXT =
43  "Raven's show tool puts a plan, doc, note or diff in the preview pane beside the transcript, " +
44  'and reads the review comments the user leaves there.'
45
46/** The engine's stock line for a plugin's registered tools, which says nothing about them. */
47const stockInstructionsOf = (plugin: string) =>
48  `Tools registered by the ${plugin} plugin through $.tool.register.`
49
50/** The question tool whose answer, given to the main loop, carries the person's pending review. */
51const ASK_TOOL = 'AskUserQuestion'
52
53const TOOL_INPUT_SCHEMA = {
54  type: 'object',
55  properties: {
56    op: {
57      enum: [...DIRECTIVE_OPS],
58      description:
59        "'show' renders a file at `path`; 'note' renders the markdown you compose; 'diff' opens " +
60        "the diff, optionally at `path`; 'comments' reads the user's pending review comments; " +
61        "'open' switches the pane to `pane` (leaving it showing if it already is).",
62    },
63    path: {
64      type: 'string',
65      description: 'A file path, relative to the session cwd unless absolute.',
66    },
67    pane: {
68      enum: [...PANE_SUBCOMMANDS],
69      description: 'The pane to show, for `op: "open"`.',
70    },
71    markdown: { type: 'string', description: 'Markdown to render, for `op: "note"`.' },
72    title: {
73      type: 'string',
74      description: 'A title for the pane, for `op: "show"` or `op: "note"`.',
75    },
76  },
77  required: ['op'],
78}
79
80/**
81 * Raven's hooks: binds the engine once at `session.start`, then forwards commands, tool calls,
82 * prompts and pane drawing to the controller in `core/raven`.
83 */
84export function register(on: On, options: PluginOptions) {
85  const settings = settingsOf(options)
86  const style = styleOf(settings.cardStyle)
87  let raven: Raven | null = null
88
89  /**
90   * Notes the viewport off any `ui.render` event and builds its `Kit` around `resolve` (always
91   * `() => $.ui.resolve(e)` at the call site: the sandbox forbids passing `$` itself), whose `ui`
92   * resolves lazily so a handler whose guard declines to draw (a hidden pane, a band a survey
93   * suppresses) never pays for `$.ui.resolve`. `capabilities` is computed once here, off
94   * `surface`, not off which elements `resolve()` happens to hand back. See `core/view.ts`.
95   */
96  function kitOf(
97    viewport: { columns?: number } | undefined,
98    resolve: () => unknown,
99    columns: number,
100    rows: number,
101    surface: RenderSurface,
102    requestId: string,
103  ): Kit {
104    raven?.noteViewport(viewport?.columns)
105    let cached: Ui | undefined
106    return {
107      get ui() {
108        if (cached === undefined) cached = resolve() as unknown as Ui
109        return cached
110      },
111      columns,
112      rows,
113      capabilities: capabilitiesOf(surface, settings.keyboardControls),
114      style,
115      press: (id, onPress) => raven?.registerPress(requestId, id, onPress),
116    }
117  }
118
119  on('session.start', async ($, e, next) => {
120    const bound: Host = {
121      run: (argv, stdin) => $.process.run(argv, stdin === undefined ? undefined : { stdin }),
122      readFile: async path => {
123        const text = await $.fs.read(path)
124        return typeof text === 'string' ? text : ''
125      },
126      after: (ms, fn) => $.clock.after(ms, fn),
127      redraw: () => $.ui.invalidate('ui.render'),
128      openPane: async pane => (await $.ui.open(pane)).isPlaced,
129      closePane: id => $.ui.close({ id }),
130      shownPaneIds: async () =>
131        new Set((await $.ui.panes()).filter(pane => pane.isShown).map(pane => pane.id)),
132      panes: () => $.ui.panes(),
133      focus: async (paneId, key) => {
134        await $.ui.focus({ requestId: paneId, key })
135      },
136      storeGet: key => $.store.get(key),
137      storeSet: (key, value) => $.store.set(key, value),
138      submitPrompt: async text => {
139        await $.prompt.submit({ text })
140      },
141      cwd: () => $.session.cwd(),
142      fork: async prompt => {
143        const result = await $.model.fork({ prompt })
144        return result.isAnswered ? result.text : null
145      },
146      status: text => $.ui.status(text),
147      fillPrompt: async text => {
148        const result = await $.prompt.fill({ text, mode: 'replace' })
149        return { isFilled: result.isFilled, refusal: result.refusal }
150      },
151      toast: text => $.ui.toast(text),
152      messages: () => $.session.messages(),
153      debug: text => $.ui.log(text, { to: 'debug' }),
154      readGlobalConfig: async () => {
155        const home = await $.env.get('HOME')
156        if (home === undefined) return null
157        try {
158          const text = await $.fs.read(`${home}/.claude.json`)
159          return JSON.parse(typeof text === 'string' ? text : '')
160        } catch {
161          return null
162        }
163      },
164      isCheckpointing: async () =>
165        isCheckpointing(
166          await $.settings.read(),
167          await $.env.get('CLAUDE_CODE_DISABLE_FILE_CHECKPOINTING'),
168        ),
169    }
170
171    const created = createRaven(bound, settings, () => Date.now())
172    await $.command.register({
173      name: COMMAND,
174      description: COMMAND_DESCRIPTION,
175      argumentHint: created.argumentHint,
176    })
177    await $.tool.register({
178      name: TOOL_NAME,
179      description: TOOL_DESCRIPTION,
180      inputSchema: TOOL_INPUT_SCHEMA,
181    })
182    raven = created
183
184    return next(e)
185  })
186
187  on('command.run', { command: COMMAND }, async ($, e, next) => {
188    if (!raven) return next(e)
189    const result = await raven.command(e.args)
190    return { text: result.text }
191  })
192
193  on('ui.render', { component: 'Pane' }, async ($, e, next) => {
194    const kit = kitOf(
195      e.viewport,
196      () => $.ui.resolve(e),
197      e.props.bodyColumns,
198      e.props.scroll.bodyRows,
199      e.surface,
200      e.requestId,
201    )
202    if (!raven || !PANE_IDS.includes(e.requestId)) return next(e)
203    const drawn = raven.render(e.requestId, kit)
204    return drawn ?? next(e)
205  })
206
207  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
208    const kit = kitOf(
209      e.viewport,
210      () => $.ui.resolve(e),
211      e.props.bodyColumns,
212      e.props.maxRows,
213      e.surface,
214      e.requestId,
215    )
216    if (!raven) return next(e)
217    const drawn = await raven.band(kit, e.props.hasSurvey, e.requestId)
218    return drawn ?? next(e)
219  })
220
221  on(
222    'ui.render',
223    { component: 'CommandOutput', props: { command: COMMAND } },
224    async ($, e, next) => {
225      const kit = kitOf(e.viewport, () => $.ui.resolve(e), 0, 0, e.surface, e.requestId)
226      if (!raven) return next(e)
227      return commandOutputRow(kit, {
228        text: e.props.text,
229        isErrored: e.props.isErrored,
230        glyph: commandGlyphOf(raven.resultKindOf(e.props.text)),
231      })
232    },
233  )
234
235  // A `Client` pill's press (`surface/strip.tsx` posts `{ press: id }`) from a pane or the band. `data` came from code, so
236  // it is validated; a stale or unknown id is ignored. Answers `{}` either way: nothing to hand back.
237  on('ui.message', ($, e, next) => {
238    const data = e.data
239    if (raven && isRecord(data) && typeof data.press === 'string') {
240      raven.press(e.requestId, data.press)
241      return {}
242    }
243    return next(e)
244  })
245
246  on('ui.scroll', { requestId: PANE_IDS }, ($, e, next) => {
247    if (!raven || e.origin.kind !== 'person' || !raven.scroll(e.requestId, e.by)) return next(e)
248    $.ui.invalidate('ui.render')
249    return {}
250  })
251
252  // A fork of its own answer raises no turn.complete the types promise, but the flag inside
253  // `turnCompleted` guards it either way; `next(e)` runs first so this never slows the turn. Every
254  // main-loop turn end reaches it, not just `reason: 'answer'`, so the live feed resets even on an
255  // interrupted or errored turn; `turnCompleted` itself only forks to resolve sent comments when
256  // the turn actually answered.
257  on('turn.complete', ($, e, next) => {
258    const result = next(e)
259    if (raven && e.agentId === undefined) void raven.turnCompleted(e)
260    return result
261  })
262
263  on('ui.close', { id: PANE_IDS }, async ($, e, next) => {
264    const result = await next(e)
265    if (result.deny === undefined) raven?.paneClosed(e.id)
266    return result
267  })
268
269  // The tool's schema and description sit in the prompt's tool list instead of behind ToolSearch,
270  // so the model knows the pane is there without first going looking for it.
271  on('tool.describe', { tool: TOOL_MATCH }, async ($, e, next) => {
272    const result = await next(e)
273    return e.tool === toolNameOf($.plugin.name) ? { ...result, isDeferred: false } : result
274  })
275
276  on('prompt.context', async ($, e, next) => {
277    const result = await next(e)
278    return { ...result, blocks: [...result.blocks, { name: NAME, text: CONTEXT_TEXT }] }
279  })
280
281  // The engine lists each plugin with registered tools under `## <plugin>` and a stock line; only
282  // Raven's own line is rewritten, and an attachment without it passes through untouched.
283  on('prompt.attachment', { type: 'mcp_instructions_delta' }, async ($, e, next) => {
284    const result = await next(e)
285    const stock = stockInstructionsOf($.plugin.name)
286    return result.text?.includes(stock)
287      ? { ...result, text: result.text.replace(stock, INSTRUCTIONS_TEXT) }
288      : result
289  })
290
291  // Registered before the catch-all below: answering here without calling `next` keeps that hook
292  // from also reacting to this call (a call no hook answers fails, so this one must answer).
293  on('tool.call', { tool: TOOL_MATCH }, async ($, e, next) => {
294    if (e.tool !== toolNameOf($.plugin.name) || !raven) return next(e)
295    try {
296      const text = await raven.runTool(e)
297      return { result: text, text }
298    } catch (error) {
299      return { deny: error instanceof Error ? error.message : String(error) }
300    }
301  })
302
303  on('tool.call', async ($, e, next) => {
304    const result = await next(e)
305    if (!raven) return result
306
307    const isLanded = result.deny === undefined && result.isError !== true
308    const output = isLanded && isRecord(result.result) ? result.result : {}
309    const event: ToolEvent = {
310      tool: e.tool,
311      input: isRecord(e) ? e : {},
312      isLanded,
313      agentId: e.agentId,
314      stdout: typeof output.stdout === 'string' ? output.stdout : undefined,
315      result: isLanded ? result.result : undefined,
316    }
317
318    const outcome = await raven.afterTool(event)
319    const notes = [...outcome.notes]
320    // An answer the person gave the main loop's question carries their pending review, as a prompt
321    // they type does, so notes left before the question appeared are not held back. (The question's
322    // dialog holds the keyboard, so no note can be typed while it is open.)
323    if (isLanded && e.tool === ASK_TOOL && e.agentId === undefined) {
324      const review = await raven.takeAnswerContext()
325      if (review !== undefined) notes.push(review)
326    }
327    if (result.deny !== undefined) return result
328    const withNotes =
329      notes.length > 0 ? { ...result, context: [...(result.context ?? []), ...notes] } : result
330    const ack = outcome.text
331    if (ack === undefined || !isLanded || !isRecord(result.result)) return withNotes
332    // The model reads Bash's result from its `stdout`, so the ack replaces the CLI's lines there;
333    // anything else the command printed stays.
334    const rest = withoutDirectives(event.stdout ?? '')
335    const text = rest === '' ? ack : `${rest}\n${ack}`
336    return { ...withNotes, result: { ...result.result, stdout: text }, text }
337  })
338
339  // Plan mode's notes name the plan file wherever plans are kept; observed, never rewritten.
340  on(
341    'prompt.attachment',
342    { type: ['plan_mode', 'plan_mode_exit', 'plan_mode_reentry'] },
343    async ($, e, next) => {
344      const result = await next(e)
345      if (raven && e.agentId === undefined && e.detail) {
346        await raven.planNoted({ type: e.type, ...e.detail })
347      }
348      return result
349    },
350  )
351
352  // Only a prompt the person sent (typed, or through Remote Control) carries the review. The
353  // toast only fires once the prompt actually went through: a dropped prompt restores the
354  // comments it carried instead (R5).
355  on('prompt.submit', async ($, e, next) => {
356    const isPersons = e.origin.kind === 'composer' || e.origin.kind === 'bridge'
357    const carried = isPersons ? await raven?.takePromptContext() : undefined
358    if (!carried) return next(e)
359    try {
360      const result = await next({ ...e, context: [...(e.context ?? []), carried.text] })
361      if (result.drop === undefined) raven?.noteCarried(carried.count)
362      else raven?.restoreCarried(carried.ids)
363      return result
364    } catch (error) {
365      raven?.restoreCarried(carried.ids)
366      throw error
367    }
368  })
369}
370
hooks/core/checkpointing.ts 22 lines
1import type { Settings } from 'claude-code'
2import { isRecord } from './is-record'
3
4/**
5 * Whether the session checkpoints Claude's edits, read as the built-in diff panel reads it: the
6 * setting on unless set false, the variable unset or falsy.
7 */
8export const isCheckpointing = (settings: Settings, disabling: string | undefined): boolean =>
9  settings.fileCheckpointingEnabled !== false &&
10  !['1', 'true', 'yes', 'on'].includes((disabling ?? '').trim().toLowerCase())
11
12/** Whether `~/.claude.json` leaves the built-in diff sidebar open; undefined when unreadable. */
13export const diffSidebarOpenOf = (globalConfig: unknown): boolean | undefined => {
14  if (!isRecord(globalConfig)) return undefined
15  const value = globalConfig.diffSidebarOpen
16  return typeof value === 'boolean' ? value : undefined
17}
18
19/** Whether the built-in diff panel is set to cover Raven's dock: open (or unknown) and checkpointing. */
20export const coversRavenDock = (globalConfig: unknown, isCheckpointingOn: boolean): boolean =>
21  diffSidebarOpenOf(globalConfig) !== false && isCheckpointingOn
22
hooks/core/command-glyph.ts 24 lines
1/** The text `/raven` answers when the terminal is too narrow to dock the pane. */
2export const NARROW_TEXT = 'Widen the terminal to dock the Raven pane'
3
4/**
5 * What a `/raven` command run resolved to. `info` is the fallback for a `CommandOutput` row whose
6 * text no `command()` call in this session produced (a replayed transcript, a reloaded module).
7 */
8export type CommandKind = 'shown' | 'hidden' | 'narrow' | 'error' | 'info'
9
10export type CommandResult = { kind: CommandKind; text: string }
11
12const GLYPHS: Record<CommandKind, string> = {
13  shown: '◆',
14  hidden: '◇',
15  narrow: '!',
16  error: '!',
17  info: '◆',
18}
19
20/** Which glyph leads a `/raven` command's output row, by its result's kind. */
21export function commandGlyphOf(kind: CommandKind): string {
22  return GLYPHS[kind]
23}
24
hooks/core/directive.ts 57 lines
1import { DIRECTIVE_PREFIX, FALLBACK_PREFIX, PANE_SUBCOMMANDS, type PaneSubcommand } from '../names'
2import { isRecord } from './is-record'
3
4export const DIRECTIVE_OPS = ['show', 'note', 'diff', 'comments', 'open'] as const
5type DirectiveOp = (typeof DIRECTIVE_OPS)[number]
6
7/** What the CLI asks of the pane; see spec/agentic.md. */
8export type Directive =
9  | { op: 'show'; path: string; title?: string }
10  | { op: 'note'; markdown: string; title?: string }
11  | { op: 'diff'; path?: string }
12  | { op: 'comments' }
13  | { op: 'open'; pane: PaneSubcommand }
14
15const optionalString = (value: unknown) => value === undefined || typeof value === 'string'
16
17/** Parses one directive's payload (a CLI's printed JSON, or the `show` tool's input) or null. */
18export function directiveOf(value: unknown): Directive | null {
19  if (!isRecord(value)) return null
20  const { op, path, title, markdown, pane } = value
21  if (!optionalString(title) || !optionalString(path)) return null
22  if (!DIRECTIVE_OPS.includes(op as DirectiveOp)) return null
23
24  switch (op as DirectiveOp) {
25    case 'show':
26      return typeof path === 'string' ? (value as Directive) : null
27    case 'note':
28      return typeof markdown === 'string' ? (value as Directive) : null
29    case 'open':
30      return PANE_SUBCOMMANDS.includes(pane as PaneSubcommand) ? (value as Directive) : null
31    case 'diff':
32    case 'comments':
33      return value as Directive
34  }
35}
36
37/** The directives in a command's stdout, in order; malformed and unknown lines are skipped. */
38export function directivesIn(stdout: string): Directive[] {
39  return stdout.split('\n').flatMap(line => {
40    if (!line.startsWith(DIRECTIVE_PREFIX)) return []
41    try {
42      const directive = directiveOf(JSON.parse(line.slice(DIRECTIVE_PREFIX.length)))
43      return directive ? [directive] : []
44    } catch {
45      return []
46    }
47  })
48}
49
50/** A command's output with the CLI's directive and fallback lines removed, keeping everything else. */
51export const withoutDirectives = (output: string) =>
52  output
53    .split('\n')
54    .filter(line => !line.startsWith(DIRECTIVE_PREFIX) && !line.startsWith(FALLBACK_PREFIX))
55    .join('\n')
56    .trim()
57
hooks/core/host.ts 59 lines
1import type { PaneOpenArgs, SessionMessage, Timer } from 'claude-code'
2
3export type RunResult = {
4  exitCode: number
5  stdout: string
6  stderr: string
7  /** Set when the engine cut `stdout` at its 4 MiB cap; absent from fakes that never cut it. */
8  isStdoutTruncated?: boolean
9}
10
11/**
12 * The slice of the engine Raven uses, bound once from `$` at `session.start`. Controllers and
13 * views take a Host rather than `$`, so they can be driven by a fake in unit tests.
14 */
15export type Host = {
16  run: (argv: readonly string[], stdin?: string) => Promise<RunResult>
17  readFile: (path: string) => Promise<string>
18  after: (ms: number, fn: () => void) => Timer
19  redraw: () => void
20  /** Resolves false when the engine left the pane waiting undrawn (too narrow to dock). */
21  openPane: (pane: PaneOpenArgs) => Promise<boolean>
22  closePane: (id: string) => Promise<void>
23  /** Every pane id the surface currently shows, off one call, for a check over several ids. */
24  shownPaneIds: () => Promise<ReadonlySet<string>>
25  /** Every pane the surface holds, shown or behind another tab. */
26  panes: () => Promise<readonly { id: string; isShown: boolean }[]>
27  /** Moves keyboard focus to the element drawn under `key` in pane `paneId`. */
28  focus: (paneId: string, key: string) => Promise<void>
29  storeGet: (key: string) => Promise<unknown>
30  storeSet: (key: string, value: unknown) => Promise<void>
31  submitPrompt: (text: string) => Promise<void>
32  /** The session's working directory, absolute; relative tool paths resolve against it. */
33  cwd: () => Promise<string>
34  /** Forks the main thread's last turn with `prompt`; the reply's text, or null when unanswered. */
35  fork: (prompt: string) => Promise<string | null>
36  /** Pins `text` as Raven's status line under the prompt; `undefined` clears it. */
37  status: (text: string | undefined) => void
38  /** Replaces the prompt box's draft with `text`; false when no box could take it. */
39  fillPrompt: (text: string) => Promise<{ isFilled: boolean; refusal?: 'no_composer' | 'dialog' }>
40  /** A transient toast over the transcript, for an error the pane has no room to show inline. */
41  toast: (text: string) => void
42  /** The main conversation's transcript so far. */
43  messages: () => Promise<readonly SessionMessage[]>
44  /** Writes `text` to the debug log only, for a failure a person never needs to see. */
45  debug: (text: string) => void
46  /** The parsed contents of `~/.claude.json` (settings never carries it); null when unreadable. */
47  readGlobalConfig: () => Promise<unknown>
48  /** Whether the session checkpoints Claude's edits, the built-in diff panel's own gate. */
49  isCheckpointing: () => Promise<boolean>
50}
51
52/** A `.catch` handler that logs the failure to the debug log and answers `fallback`. */
53export const loggedAs =
54  <T>(host: Pick<Host, 'debug'>, what: string, fallback: T) =>
55  (error: unknown): T => {
56    host.debug(`raven: ${what} failed: ${String(error)}`)
57    return fallback
58  }
59
hooks/core/is-record.ts 4 lines
1/** Narrows untrusted data (store values, JSON, tool results) to an object whose fields can be read. */
2export const isRecord = (value: unknown): value is Record<string, unknown> =>
3  typeof value === 'object' && value !== null
4
hooks/core/raven.ts 651 lines
1import type { RenderElement, Timer, TurnCompleteInput } from 'claude-code'
2import { existingPathsOf } from '../git/load'
3import { DIFF_PANEL_WARNING } from '../names'
4import { addressedIdsOf, type Comment, reviewTextOf } from '../review/comments'
5import { resolvePromptOf } from '../review/resolve'
6import { createReview } from '../review/review'
7import { paneFill } from '../ui/pane-fill'
8import { createDiffView } from '../views/diff-view'
9import { createDocView, type Doc } from '../views/doc-view'
10import { createTasksView } from '../views/tasks-view'
11import { createTreeView } from '../views/tree-view'
12import { shouldAutoOpen } from './auto-open'
13import { createBandState } from './band-state'
14import { coversRavenDock } from './checkpointing'
15import { type CommandKind, type CommandResult, NARROW_TEXT } from './command-glyph'
16import { type Directive, directiveOf } from './directive'
17import { countOf } from './format'
18import { type Host, loggedAs } from './host'
19import { createPower } from './power'
20import { createPresses } from './presses'
21import type { RavenSettings } from './settings'
22import {
23  type Action,
24  actionsOf,
25  type PlanNote,
26  planActionsOf,
27  type ToolEvent,
28  triggersOf,
29} from './triggers'
30import type { Kit, View } from './view'
31
32/**
33 * What a finished tool call means for the model: `text` replaces a shell call's directive lines,
34 * `notes` are read after the result (the user never sees them).
35 */
36export type ToolOutcome = { text?: string; notes: readonly string[] }
37
38/** The engine-facing surface of Raven; `register` forwards engine events here and nothing else. */
39export type Raven = {
40  /** The `/raven` argument hint: each view's subcommand, then `send`, `on` and `off`. */
41  argumentHint: string
42  command: (args: string) => Promise<CommandResult>
43  /**
44   * Reacts to a finished tool call: replacement result text for a directive, and notes telling the
45   * main loop what Raven opened by itself. Never rejects: a failure goes to the debug log.
46   */
47  afterTool: (event: ToolEvent) => Promise<ToolOutcome>
48  /**
49   * Learns the plan file plan mode named, so its edits render live; opens it on exit/re-entry.
50   * Never rejects: a failure goes to the debug log.
51   */
52  planNoted: (note: PlanNote) => Promise<void>
53  /** Runs the `show` tool's input as a directive; throws on input `directiveOf` rejects. */
54  runTool: (input: unknown) => Promise<string>
55  /**
56   * Hidden context the next prompt carries: the live pending comments, which it marks sent (a
57   * stale pending comment among them moves to 'open' instead, never riding). `undefined` when
58   * there is nothing live to carry. `ids` is the taken batch, for `restoreCarried` if the prompt
59   * this primes is later dropped.
60   */
61  takePromptContext: () => Promise<
62    { text: string; count: number; ids: readonly string[] } | undefined
63  >
64  /** The prompt `takePromptContext` primed went through: toasts how many comments it carried. */
65  noteCarried: (count: number) => void
66  /**
67   * The main loop's AskUserQuestion was answered: takes the live pending review for the answer's
68   * hidden context, and toasts it. Never rejects: a failure is logged, and the review stays pending.
69   */
70  takeAnswerContext: () => Promise<string | undefined>
71  /** The prompt `takePromptContext` primed was dropped: undoes it, restoring `ids` to pending. */
72  restoreCarried: (ids: readonly string[]) => void
73  /**
74   * Reacts to a finished main-loop turn: always resets the live feed (clears this turn's edited
75   * marks and resumes following); only an answered turn also forks once to learn which sent
76   * comments it addressed.
77   */
78  turnCompleted: (turn: TurnCompleteInput) => Promise<void>
79  render: (paneId: string, kit: Kit) => RenderElement | null
80  /**
81   * Runs the handler a `Client` pill's `{ press: id }` post names, in the pane `paneId` drew it in;
82   * false when the id is not (or no longer) drawn there.
83   */
84  press: (paneId: string, id: string) => boolean
85  /** Registers the handler for a pill `id` drawn in `paneId`'s current render (`Kit.press`). */
86  registerPress: (paneId: string, id: string, onPress: () => void) => void
87  /** Moves a pane's own scroll by `by` rows; true when its view handled the move. */
88  scroll: (paneId: string, by: number) => boolean
89  paneClosed: (paneId: string) => void
90  /** Records the terminal's width off any `ui.render` Raven sees, for the auto-open gate. */
91  noteViewport: (columns: number | undefined) => void
92  /**
93   * The `AbovePrompt` band: null while a survey holds it, `maxRows` is too small, nothing is
94   * pending, or a Raven pane is already visible (not just open behind another tab).
95   */
96  band: (kit: Kit, hasSurvey: boolean, requestId: string) => Promise<RenderElement | null>
97  /** The kind a past `command()` call resolved `text` to; `'info'` when no call produced it. */
98  resultKindOf: (text: string) => CommandKind
99}
100
101const REFRESH_DEBOUNCE_MS = 300
102
103/** Told to the main loop when the first edit opened the diff by itself. */
104export const DIFF_NOTE =
105  "Raven: the session's diff is now live in the Raven pane beside the transcript."
106
107/** Told to the main loop when a doc it wrote opened by itself. */
108export const docNoteOf = (path: string) =>
109  `Raven: ${path} is shown rendered in the Raven pane beside the transcript, and the user can ` +
110  'comment on its sections there. If it is something they should approve, say so in one line and ask with ' +
111  'AskUserQuestion ("Looks good, proceed" / "I\'ll comment in the pane"); on the second, end your ' +
112  'turn asking them to leave notes and reply, and the notes arrive with their reply.'
113
114/**
115 * Told to the main loop when plan mode's own plan opened by itself: plan mode approves through its
116 * own exit, so this names no question to ask.
117 */
118export const planNoteOf = (path: string) =>
119  `Raven: the plan ${path} is shown rendered in the Raven pane beside the transcript; the user ` +
120  'can comment on its sections there, and their notes arrive with their next reply.'
121
122/**
123 * `focus`: the pane takes the keyboard. `isAuto`: Raven opens it unasked, so the auto-open gate is
124 * asked again right before the open.
125 */
126type ShowOptions = { focus?: true; isAuto?: true }
127
128/** What one action did: `text` answers a directive, `note` tells the model about an unasked open. */
129type ActionOutcome = { text?: string; note?: string }
130
131const toastOfCarried = (count: number, carrier: string) =>
132  `Raven: ${countOf(count, 'review comment')} sent with ${carrier}`
133const SEND = 'send'
134const ON = 'on'
135const OFF = 'off'
136
137const REFUSAL_TEXTS: Record<'no_composer' | 'dialog', string> = {
138  no_composer: 'no prompt box in this session',
139  dialog: 'a dialog has the keyboard',
140}
141
142export function createRaven(host: Host, settings: RavenSettings, now: () => number): Raven {
143  const review = createReview(host, now)
144  const diff = createDiffView(
145    host,
146    review,
147    {
148      send: () => void sendReview(),
149      editAndSend: () => void editAndSend(),
150      focus: key => void focusIn(diff, key),
151    },
152    now,
153    { splitColumns: settings.splitColumns },
154  )
155  const doc = createDocView(host, review, { focus: key => void focusIn(doc, key) }, now)
156  const tree = createTreeView(host, { open: path => void showDoc({ kind: 'file', path }) })
157  const tasksView = createTasksView(host)
158  const views: readonly View[] = [diff, doc, tree, tasksView]
159
160  const open = new Set<string>()
161  const power = createPower()
162  let refreshTimer: Timer | null = null
163  let hasAutoOpened = false
164  // Every file the Doc view has shown, and whether the main loop has been told so (by a note, or by
165  // its own `show` call's result). A watched doc opens by itself only the first time, so later edits
166  // reload it in place instead of pulling it in front of a pane the person switched to; a doc a
167  // subagent's edit opened stays 'shown' until the main loop's first edit of it names it.
168  const docs = new Map<string, 'shown' | 'told'>()
169  let hasOpenedTasks = false
170  let hasWarnedDiffPanel = false
171  // Guards the fork below from re-entering itself and caps it at one per sent batch.
172  let isResolving = false
173  const planPaths = new Set<string>()
174  const triggers = triggersOf(settings)
175  // The kind the most recent `command()` call resolved each reply text to, for a `CommandOutput`
176  // row the engine asks Raven to redraw without re-running the command.
177  const resultKindByText = new Map<string, CommandKind>()
178  const presses = createPresses()
179
180  const bandState = createBandState(host, review, {
181    openDiff: async () => {
182      await showDiff()
183    },
184    openDoc: async () => {
185      await show(doc)
186    },
187    sendReview,
188  })
189
190  // Kicked off at session start rather than waiting for the first `AbovePrompt` render or prompt
191  // submit to need it: by the time either happens, the common case already has it loaded.
192  // `ensureReviewLoaded` is idempotent, so the `await` each still does is then a no-op; this
193  // only spares the *first* one from paying for the git read itself.
194  void bandState.ensureReviewLoaded()
195
196  /**
197   * Once per module instance: warns when the built-in diff panel will cover Raven's dock. Never
198   * throws, so a failed check never blocks the command or edit that triggered it.
199   */
200  async function warnDiffPanelOnce(): Promise<void> {
201    if (hasWarnedDiffPanel) return
202    hasWarnedDiffPanel = true
203    try {
204      const [globalConfig, checkpointing] = await Promise.all([
205        host.readGlobalConfig(),
206        host.isCheckpointing(),
207      ])
208      if (coversRavenDock(globalConfig, checkpointing)) host.toast(DIFF_PANEL_WARNING)
209    } catch (error) {
210      host.debug(`raven: diff panel check failed: ${String(error)}`)
211    }
212  }
213
214  const takeReviewText = () => reviewTextOf(review.take())
215
216  /**
217   * A pending comment is live when it has a `section` (a doc comment, always live); `known` (the
218   * diff's `knownPaths` at call time) is null (no live git list to check against: a turn source,
219   * or nothing loaded yet); its path is among those known paths (which include a renamed file's
220   * `oldPath`); or `existing` says the file is still there: checked only for comments `known`
221   * doesn't already cover (R32: it's the diff moving past a file, not the file being gone, that
222   * stops meaning "stale"). `existing` null (the check never ran, or failed) never counts against
223   * a comment: fail open, same as `known` null. Only a comment whose file is truly gone moves to
224   * 'open' by `review.take`, rather than riding the prompt silently.
225   */
226  const isLiveComment =
227    (known: ReadonlySet<string> | null, existing: ReadonlySet<string> | null) =>
228    (comment: Comment) =>
229      comment.section !== undefined ||
230      known === null ||
231      known.has(comment.path) ||
232      existing === null ||
233      existing.has(comment.path)
234
235  /** Forks once to ask which sent comments the finished turn addressed, then marks them. */
236  async function resolveSent(): Promise<void> {
237    const sent = review.sent()
238    if (sent.length === 0 || isResolving) return
239    isResolving = true
240    // Captured before the fork: a newer batch sent while this fork is in flight must not be
241    // touched by the reply this one gets back.
242    const batchIds = sent.map(comment => comment.id)
243    try {
244      const reply = await host.fork(resolvePromptOf(sent))
245      // No bracketed array in the reply means it was unparseable, not "nothing addressed"; leave
246      // the comments sent rather than bouncing every one of them to 'open'.
247      if (reply !== null && /\[[\s\S]*\]/.test(reply)) {
248        review.resolveBatch(batchIds, addressedIdsOf(reply, batchIds))
249        host.redraw()
250      }
251    } catch (error) {
252      host.debug(`raven: resolving sent comments failed: ${String(error)}`)
253    } finally {
254      isResolving = false
255    }
256  }
257
258  function cancelRefresh() {
259    refreshTimer?.cancel()
260    refreshTimer = null
261  }
262
263  /** Submits the pending review as a visible prompt, so the person sees what Claude was asked. */
264  async function sendReview(): Promise<boolean> {
265    const text = takeReviewText()
266    if (text !== undefined) await host.submitPrompt(text)
267    return text !== undefined
268  }
269
270  const refusalTextOf = (refusal: 'no_composer' | 'dialog' | undefined) =>
271    (refusal && REFUSAL_TEXTS[refusal]) ?? 'the fill was refused'
272
273  /** Fills the prompt box with the pending review so the person can edit it before sending. */
274  async function editAndSend(): Promise<void> {
275    const taken = review.take()
276    const text = reviewTextOf(taken)
277    if (text === undefined) return
278    const filled = await host.fillPrompt(text)
279    if (!filled.isFilled) {
280      review.restore(taken.map(comment => comment.id))
281      host.toast(`Raven: could not fill the prompt (${refusalTextOf(filled.refusal)})`)
282    }
283  }
284
285  /**
286   * Shows a view's pane, bringing it forward when it is a tab behind another; false when the
287   * terminal is too narrow to dock it.
288   */
289  const isPaneShown = async (id: string) => (await host.shownPaneIds()).has(id)
290
291  async function show(view: View, { focus, isAuto }: ShowOptions = {}): Promise<boolean> {
292    // Asked again after the caller's awaits: a `/raven off` meanwhile must not be undone by it.
293    if (isAuto && !mayAutoOpen()) return false
294    const wasOff = power.isOff()
295    if (open.has(view.pane.id)) {
296      if (!focus && (await isPaneShown(view.pane.id))) return true
297      // Reopening an open id only retitles it; a fresh open brings a background tab forward.
298      if (!focus) await host.closePane(view.pane.id)
299    }
300    // Marked before the open: the engine draws the pane while `openPane` is in flight.
301    open.add(view.pane.id)
302    const isPlaced = await host.openPane({ ...view.pane, holdToasts: true, focus })
303    // A `/raven off` that ran while this open was in flight wins: it already closed every pane.
304    if (isPlaced && (wasOff || !power.isOff())) {
305      // Off means no pane is open, so whoever placed this one turned Raven back on.
306      power.noteOpened()
307      return true
308    }
309    // A pane left waiting would seat itself on a later resize; withdraw it instead.
310    await hide(view)
311    return false
312  }
313
314  async function hide(view: View) {
315    await host.closePane(view.pane.id)
316    open.delete(view.pane.id)
317    host.redraw()
318  }
319
320  /** The keyboard is the person's: an element can take it only once its pane asked for focus. */
321  async function focusIn(view: View, key: string) {
322    if (await show(view, { focus: true })) {
323      await host
324        .focus(view.pane.id, key)
325        .catch(error => host.debug(`raven: focus failed: ${String(error)}`))
326    }
327  }
328
329  function scheduleRefresh() {
330    cancelRefresh()
331    refreshTimer = host.after(REFRESH_DEBOUNCE_MS, () => {
332      refreshTimer = null
333      if (open.has(diff.pane.id)) void diff.refresh()
334      if (open.has(tree.pane.id)) void tree.refresh()
335    })
336  }
337
338  async function showDiff({ path, isAuto }: { path?: string; isAuto?: true } = {}) {
339    cancelRefresh()
340    await diff.refresh()
341    if (open.has(tree.pane.id)) void tree.refresh()
342    if (path) diff.reveal(path)
343    return show(diff, { isAuto })
344  }
345
346  /** Loads `shown` into the Doc view and tells the band, without opening the pane. */
347  async function loadDoc(shown: Doc) {
348    await doc.show(shown)
349    bandState.noteDocShown(
350      shown.kind === 'file' ? shown.path : undefined,
351      await isPaneShown(doc.pane.id),
352    )
353  }
354
355  async function showDoc(shown: Doc, { isAuto }: { isAuto?: true } = {}) {
356    await loadDoc(shown)
357    const isShown = await show(doc, { isAuto })
358    // A show the terminal was too narrow for is not counted, so the next edit tries again.
359    if (isShown && shown.kind === 'file' && !docs.has(shown.path)) docs.set(shown.path, 'shown')
360    return isShown
361  }
362
363  async function showTree() {
364    await tree.refresh({ force: true })
365    return show(tree)
366  }
367
368  const shownText = (isShown: boolean, what: string) =>
369    isShown
370      ? `Shown in the Raven pane: ${what}.`
371      : `Raven could not dock its pane (the terminal is too narrow): ${what} was not shown.`
372
373  /** Shows `view` the way its slash command does, minus the toggle: always leaves it visible. */
374  const showView = (view: View) =>
375    view === diff ? showDiff() : view === tree ? showTree() : show(view)
376
377  function viewOf(subcommand: string): View {
378    const view = views.find(each => each.subcommand === subcommand)
379    if (!view) throw new Error(`Raven has no pane "${subcommand}"`)
380    return view
381  }
382
383  async function runDirective(directive: Directive): Promise<string> {
384    switch (directive.op) {
385      case 'show': {
386        const isShown = await showDoc({
387          kind: 'file',
388          path: directive.path,
389          title: directive.title,
390        })
391        if (isShown) docs.set(directive.path, 'told')
392        return shownText(isShown, directive.path)
393      }
394      case 'note':
395        return shownText(
396          await showDoc({ kind: 'note', markdown: directive.markdown, title: directive.title }),
397          directive.title ?? 'the note',
398        )
399      case 'diff':
400        return shownText(await showDiff({ path: directive.path }), 'the diff')
401      case 'open':
402        return shownText(await showView(viewOf(directive.pane)), `the ${directive.pane} pane`)
403      case 'comments':
404        return takeReviewText() ?? 'The user has no pending review comments.'
405    }
406  }
407
408  /** A relative `path` is the tool's own, resolved against the session's cwd, not the CLI's shell. */
409  async function resolveDirective(directive: Directive): Promise<Directive> {
410    if (directive.op !== 'show' && directive.op !== 'diff') return directive
411    const { path } = directive
412    if (path === undefined || path.startsWith('/')) return directive
413    return { ...directive, path: `${await host.cwd()}/${path}` }
414  }
415
416  /** Raven may open a pane unasked, setting and width permitting, whether or not it is off. */
417  const wouldAutoOpen = () => shouldAutoOpen(settings, bandState.viewportColumns())
418  /** Every pane Raven opens unasked goes through this one gate. */
419  const mayAutoOpen = () => !power.isOff() && wouldAutoOpen()
420
421  /** `isMainLoop`: the action came from the main loop's own tool call, whose result a note can ride. */
422  async function runAction(action: Action, isMainLoop: boolean): Promise<ActionOutcome> {
423    switch (action.kind) {
424      case 'refresh-diff':
425        if (action.path !== undefined) diff.noteEdited(action.path)
426        if (open.has(diff.pane.id) || open.has(tree.pane.id)) scheduleRefresh()
427        return {}
428      case 'main-loop-edit':
429        void warnDiffPanelOnce()
430        if (!hasAutoOpened) {
431          hasAutoOpened = true
432          if (mayAutoOpen() && (await showDiff({ isAuto: true }))) return { note: DIFF_NOTE }
433        }
434        return {}
435      case 'show-doc': {
436        const { path } = action
437        if ((!docs.has(path) || action.force) && wouldAutoOpen()) {
438          // Off, the doc still loads, so the band flags it unseen.
439          if (power.isOff()) await loadDoc({ kind: 'file', path })
440          else await showDoc({ kind: 'file', path }, { isAuto: true })
441        }
442        if (!isMainLoop || docs.get(path) !== 'shown') return {}
443        docs.set(path, 'told')
444        return { note: planPaths.has(path) ? planNoteOf(path) : docNoteOf(path) }
445      }
446      case 'reload-doc':
447        await doc.reload(action.path)
448        bandState.noteDocReloaded(action.path, await isPaneShown(doc.pane.id))
449        return {}
450      case 'directive':
451        return { text: await runDirective(action.directive) }
452      case 'tasks': {
453        const changed = tasksView.apply(action.tool, action.input, action.result)
454        if (changed && !hasOpenedTasks && tasksView.hasTasks()) {
455          hasOpenedTasks = true
456          if (open.size === 0 && mayAutoOpen()) await show(tasksView, { isAuto: true })
457        }
458        return {}
459      }
460    }
461  }
462
463  /** Records `kind` against `text` for a later `resultKindOf`, and returns the pair as-is. */
464  const resultOf = (kind: CommandKind, text: string): CommandResult => {
465    resultKindByText.set(text, kind)
466    return { kind, text }
467  }
468
469  async function toggle(view: View): Promise<CommandResult> {
470    const name = `Raven ${view.pane.title.toLowerCase()}`
471    if (open.has(view.pane.id) && (await isPaneShown(view.pane.id))) {
472      await hide(view)
473      return resultOf('hidden', `${name} hidden`)
474    }
475    const isShown = await showView(view)
476    return isShown ? resultOf('shown', `${name} shown`) : resultOf('narrow', NARROW_TEXT)
477  }
478
479  const sortFrontLast = (closed: readonly View[], front: string | undefined) => [
480    ...closed.filter(view => view.pane.id !== front),
481    ...closed.filter(view => view.pane.id === front),
482  ]
483
484  /**
485   * Closes every open pane and remembers them for `turnOn`; auto-opens stay muted meanwhile. A pane
486   * the engine still holds counts as open even when `open` lost it (a reloaded module starts empty).
487   */
488  async function turnOff(): Promise<CommandResult> {
489    if (power.isOff()) return resultOf('hidden', 'Raven is already off')
490    const held = await host.panes()
491    const closing = views.filter(
492      view => open.has(view.pane.id) || held.some(pane => pane.id === view.pane.id),
493    )
494    const ids = closing.map(view => view.pane.id)
495    const front = held.find(pane => pane.isShown && ids.includes(pane.id))?.id
496    power.turnOff({ ids, front })
497    for (const view of closing) await hide(view)
498    return resultOf('hidden', 'Raven off: panes closed until /raven on')
499  }
500
501  /** Reopens what `turnOff` closed, front last (else the diff); `show` ends off on the first placed. */
502  async function turnOn(): Promise<CommandResult> {
503    const { ids, front } = power.snapshot() ?? { ids: [] }
504    const closed = views.filter(view => ids.includes(view.pane.id))
505    const order = closed.length === 0 ? [diff] : sortFrontLast(closed, front)
506    let isPlaced = false
507    for (const view of order) if (await showView(view)) isPlaced = true
508    return isPlaced ? resultOf('shown', 'Raven on') : resultOf('narrow', NARROW_TEXT)
509  }
510
511  const argumentHint = `[${[...views.map(view => view.subcommand), SEND, ON, OFF].join('|')}]`
512
513  /** Never rejects: a thrown failure becomes an `'error'` result like usage help does. */
514  async function command(args: string): Promise<CommandResult> {
515    try {
516      await warnDiffPanelOnce()
517      const word = args.trim() || diff.subcommand
518      const view = views.find(each => each.subcommand === word)
519      if (view) return toggle(view)
520      if (word === SEND) {
521        return (await sendReview())
522          ? resultOf('shown', 'Review sent')
523          : resultOf('hidden', 'No review comments to send')
524      }
525      if (word === OFF) return turnOff()
526      if (word === ON) return turnOn()
527      return resultOf('error', `Usage: /raven ${argumentHint}`)
528    } catch (error) {
529      return resultOf('error', `Raven failed: ${String(error)}`)
530    }
531  }
532
533  async function takePromptContext() {
534    // A prompt can carry comments before any pane has ever loaded the review (the band's own
535    // load path, reused here so both see the same `hasLoadedReview` guard).
536    await bandState.ensureReviewLoaded()
537    const known = diff.knownPaths()
538    const toplevel = diff.toplevel()
539    let existing: ReadonlySet<string> | null = null
540    if (known !== null && toplevel !== null) {
541      // Only the comments `known` doesn't already resolve need the existence check:
542      // `existingPathsOf` batches all of them together (chunked, never one call per comment),
543      // and this is skipped entirely when `known` is null (everything is already live) or
544      // there is nothing left to check.
545      const candidates = review
546        .pending()
547        .filter(comment => comment.section === undefined && !known.has(comment.path))
548      if (candidates.length > 0) {
549        const paths = [...new Set(candidates.map(comment => comment.path))]
550        existing = await existingPathsOf(host.run, toplevel, paths).catch(
551          loggedAs(host, 'checking comment file existence', null),
552        )
553      }
554    }
555    const taken = review.take(isLiveComment(known, existing))
556    const text = reviewTextOf(taken)
557    if (text === undefined) return undefined
558    return { text, count: taken.length, ids: taken.map(comment => comment.id) }
559  }
560
561  return {
562    argumentHint,
563    command,
564    afterTool: async event => {
565      const texts: string[] = []
566      const notes: string[] = []
567      try {
568        for (const action of actionsOf(event, triggers, planPaths)) {
569          // A subagent's result is not where the main loop would read a note.
570          const { text, note } = await runAction(action, event.agentId === undefined)
571          if (text !== undefined) texts.push(text)
572          if (note !== undefined) notes.push(note)
573        }
574      } catch (error) {
575        host.debug(`raven: afterTool failed: ${String(error)}`)
576      }
577      return { text: texts.length > 0 ? texts.join('\n') : undefined, notes }
578    },
579    planNoted: async note => {
580      planPaths.add(note.planFilePath)
581      try {
582        // No tool result carries these opens, so no note is made for them.
583        for (const action of planActionsOf(note)) await runAction(action, false)
584      } catch (error) {
585        host.debug(`raven: planNoted failed: ${String(error)}`)
586      }
587    },
588    runTool: async input => {
589      const directive = directiveOf(input)
590      if (!directive)
591        throw new Error(`Invalid input for the Raven show tool: ${JSON.stringify(input)}`)
592      return runDirective(await resolveDirective(directive))
593    },
594    takePromptContext,
595    noteCarried: count => {
596      host.toast(toastOfCarried(count, 'this prompt'))
597    },
598    takeAnswerContext: async () => {
599      try {
600        const carried = await takePromptContext()
601        if (carried) host.toast(toastOfCarried(carried.count, 'your answer'))
602        return carried?.text
603      } catch (error) {
604        host.debug(`raven: carrying the review on an answer failed: ${String(error)}`)
605        return undefined
606      }
607    },
608    restoreCarried: ids => {
609      if (ids.length > 0) review.restore(ids)
610    },
611    turnCompleted: async turn => {
612      diff.turnEnded()
613      if (turn.reason === 'answer') await resolveSent()
614    },
615    // A throwing handler is logged, never rejected into the `ui.message` hook (which would fail the post).
616    press: (paneId, id) => {
617      try {
618        return presses.dispatch(paneId, id)
619      } catch (error) {
620        host.debug(`raven: press handler "${id}" threw: ${String(error)}`)
621        return true
622      }
623    },
624    registerPress: (paneId, id, onPress) => presses.add(paneId, id, onPress),
625    render: (paneId, kit) => {
626      const view = views.find(each => each.pane.id === paneId)
627      if (!view) return null
628      // A reloaded module inherits open panes it never opened: drawing one proves it is open, and
629      // its model starts empty until a refresh.
630      if (!open.has(paneId)) {
631        open.add(paneId)
632        void view.refresh?.().catch(error => host.debug(`raven: refresh failed: ${String(error)}`))
633      }
634      if (view === doc) bandState.noteDocRendered()
635      presses.begin(paneId)
636      return paneFill(kit, settings.paneBackground, view.render(kit))
637    },
638    scroll: (paneId, by) => views.find(view => view.pane.id === paneId)?.scroll?.(by) ?? false,
639    paneClosed: paneId => {
640      open.delete(paneId)
641      host.redraw()
642    },
643    noteViewport: columns => bandState.noteViewport(columns),
644    // `begin` runs right before the band's synchronous registrations, after the band's awaits: a
645    // render that draws nothing, or a newer one landing meanwhile, never wipes handlers it still needs.
646    band: (kit, hasSurvey, requestId) =>
647      bandState.band(kit, hasSurvey, () => presses.begin(requestId)),
648    resultKindOf: text => resultKindByText.get(text) ?? 'info',
649  }
650}
651
hooks/core/settings.ts 97 lines
1import type { PluginOptions } from 'claude-code'
2import { type CardStyle, isCardStyle } from '../ui/style'
3
4/** Raven's parsed `userConfig`, defaults filled in for any field a wrong type left unusable. */
5export type RavenSettings = {
6  /** Extra path fragments (trimmed, non-empty) whose `.md` files open in the Doc view. */
7  watchedPaths: readonly string[]
8  /** Lets Raven open panes nobody asked for; `shouldAutoOpen` is the one gate. */
9  autoOpen: boolean
10  /** Skips those opens below this terminal width, in columns. */
11  autoOpenColumns: number
12  /** Draws plain Tab-reachable Buttons instead of interactive pills on every surface (R42). */
13  keyboardControls: boolean
14  /** How files, doc sections, the compose box and tables are framed (`ui/style.ts`). */
15  cardStyle: CardStyle
16  /** Pane width, in columns, at which the diff goes side-by-side unless the header chip forced a mode. */
17  splitColumns: number
18  /** A colour painted behind every pane so it matches the terminal; `''` leaves the engine's own. */
19  paneBackground: string
20}
21
22export const DEFAULT_SETTINGS: RavenSettings = {
23  watchedPaths: [],
24  autoOpen: true,
25  autoOpenColumns: 144,
26  keyboardControls: false,
27  cardStyle: 'bar',
28  splitColumns: 160,
29  paneBackground: '',
30}
31
32const watchedPathsOf = (value: unknown): readonly string[] => {
33  if (typeof value !== 'string') return DEFAULT_SETTINGS.watchedPaths
34  const fragments = value
35    .split(',')
36    .map(fragment => fragment.trim())
37    .filter(fragment => fragment !== '')
38  return fragments.length > 0 ? fragments : DEFAULT_SETTINGS.watchedPaths
39}
40
41const autoOpenOf = (value: unknown): boolean =>
42  typeof value === 'boolean' ? value : DEFAULT_SETTINGS.autoOpen
43
44const autoOpenColumnsOf = (value: unknown): number =>
45  typeof value === 'number' && Number.isFinite(value) && value > 0
46    ? value
47    : DEFAULT_SETTINGS.autoOpenColumns
48
49/** Trimmed like `paneBackground`: a stray space around the value in a settings file is not a typo. */
50const cardStyleOf = (value: unknown): CardStyle => {
51  const text = typeof value === 'string' ? value.trim() : value
52  return isCardStyle(text) ? text : DEFAULT_SETTINGS.cardStyle
53}
54
55const splitColumnsOf = (value: unknown): number =>
56  typeof value === 'number' && Number.isFinite(value) && value > 0
57    ? value
58    : DEFAULT_SETTINGS.splitColumns
59
60const HEX_COLOR = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i
61const RGB_COLOR = /^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/
62const THEME_KEY = /^[A-Za-z][A-Za-z0-9_]*$/
63
64const isColor = (text: string): boolean => {
65  if (HEX_COLOR.test(text) || THEME_KEY.test(text)) return true
66  const rgb = RGB_COLOR.exec(text)
67  return rgb?.slice(1).every(part => Number(part) <= 255) ?? false
68}
69
70/**
71 * A hex, `rgb(r, g, b)` or theme-key colour, trimmed; anything else is `''` (the engine's own).
72 * Any identifier passes as a theme key on purpose: the engine's theme keys are open-ended (and
73 * `COLORS` lists only the ones Raven draws with), so an unknown key like `banana` is the engine's to
74 * resolve, not Raven's to second-guess.
75 */
76const paneBackgroundOf = (value: unknown): string => {
77  if (typeof value !== 'string') return DEFAULT_SETTINGS.paneBackground
78  const text = value.trim()
79  return isColor(text) ? text : DEFAULT_SETTINGS.paneBackground
80}
81
82/** Parses `register`'s `options` defensively: a field of the wrong type falls back to its default. */
83export function settingsOf(options: PluginOptions): RavenSettings {
84  return {
85    watchedPaths: watchedPathsOf(options.watchedPaths),
86    autoOpen: autoOpenOf(options.autoOpen),
87    autoOpenColumns: autoOpenColumnsOf(options.autoOpenColumns),
88    keyboardControls:
89      typeof options.keyboardControls === 'boolean'
90        ? options.keyboardControls
91        : DEFAULT_SETTINGS.keyboardControls,
92    cardStyle: cardStyleOf(options.cardStyle),
93    splitColumns: splitColumnsOf(options.splitColumns),
94    paneBackground: paneBackgroundOf(options.paneBackground),
95  }
96}
97
hooks/core/triggers.ts 148 lines
1import { TASK_TOOLS } from '../review/tasks'
2import { type Directive, directivesIn } from './directive'
3import type { RavenSettings } from './settings'
4
5/** A finished tool call, as the triggers read it. */
6export type ToolEvent = {
7  tool: string
8  input: Readonly<Record<string, unknown>>
9  /** The call ran and was neither refused nor an error. */
10  isLanded: boolean
11  /** Set when a subagent made the call. */
12  agentId?: string
13  stdout?: string
14  /** The tool result's structured `result`, when the call landed. */
15  result?: unknown
16}
17
18export type Action =
19  /** `path` is the edit that caused it; a shell refresh carries no path. */
20  | { kind: 'refresh-diff'; path?: string }
21  /** The main loop's edit landed: the controller opens the diff on the first of these. */
22  | { kind: 'main-loop-edit' }
23  /**
24   * A doc to open unasked: once per path, unless `force` (leaving or re-entering plan mode, a moment
25   * the person chose) shows it again.
26   */
27  | { kind: 'show-doc'; path: string; force?: true }
28  | { kind: 'reload-doc'; path: string }
29  | { kind: 'directive'; directive: Directive }
30  | { kind: 'tasks'; tool: string; input: Readonly<Record<string, unknown>>; result?: unknown }
31
32/** A pure reading of one finished call, given the plan files plan mode has named so far. */
33export type Trigger = (event: ToolEvent, planPaths: ReadonlySet<string>) => readonly Action[]
34
35const EDIT_TOOLS = ['Edit', 'Write', 'NotebookEdit', 'MultiEdit']
36const SHELL_TOOLS = ['Bash', 'PowerShell']
37
38/**
39 * Markdown written under these paths opens in the doc view as it is written. Plan mode's own plan
40 * file is not guessed here: its path arrives on plan mode's notes (`PlanNote`).
41 */
42const WATCHED_DOC_PATTERNS = [
43  /\/docs\/superpowers\/(plans|specs)\/[^/]+\.md$/,
44  /\/\.superpowers\/.+\.md$/,
45]
46
47/** `fragment` split into its non-empty `/`-separated segments. */
48const segmentsOf = (value: string) => value.split('/').filter(segment => segment !== '')
49
50/**
51 * True when `fragment`'s segments occur contiguously among `path`'s, so a single-segment fragment
52 * like `docs` never matches a longer segment like `docsystem`, while a multi-segment fragment like
53 * `notes/drafts` still matches across the two segments it names.
54 */
55const containsFragment = (path: string, fragment: string): boolean => {
56  const needle = segmentsOf(fragment)
57  if (needle.length === 0) return false
58  const haystack = path.split('/')
59  for (let start = 0; start + needle.length <= haystack.length; start++) {
60    if (needle.every((segment, i) => haystack[start + i] === segment)) return true
61  }
62  return false
63}
64
65const isWatchedDocPath = (
66  path: string,
67  watchedPaths: readonly string[],
68  planPaths: ReadonlySet<string>,
69) =>
70  planPaths.has(path) ||
71  (path.endsWith('.md') &&
72    (WATCHED_DOC_PATTERNS.some(pattern => pattern.test(path)) ||
73      watchedPaths.some(fragment => containsFragment(path, fragment))))
74
75/** The file a landed edit wrote, or null for any other call. */
76const editedPathOf = (event: ToolEvent) => {
77  if (!event.isLanded || !EDIT_TOOLS.includes(event.tool)) return null
78  const path = event.input.file_path ?? event.input.notebook_path
79  return typeof path === 'string' ? path : null
80}
81
82const onEdit: Trigger = event => {
83  const path = editedPathOf(event)
84  if (path === null) return []
85  const actions: Action[] = [
86    { kind: 'refresh-diff', path },
87    { kind: 'reload-doc', path },
88  ]
89  if (event.agentId === undefined) actions.push({ kind: 'main-loop-edit' })
90  return actions
91}
92
93// A failed or interrupted command may still have written files, so any shell call refreshes.
94const onShell: Trigger = event =>
95  SHELL_TOOLS.includes(event.tool) ? [{ kind: 'refresh-diff' }] : []
96
97const onWatchedDocOf =
98  (watchedPaths: readonly string[]): Trigger =>
99  (event, planPaths) => {
100    const path = editedPathOf(event)
101    return path !== null && isWatchedDocPath(path, watchedPaths, planPaths)
102      ? [{ kind: 'show-doc', path }]
103      : []
104  }
105
106const onDirective: Trigger = event =>
107  SHELL_TOOLS.includes(event.tool) && event.stdout
108    ? directivesIn(event.stdout).map(directive => ({ kind: 'directive', directive }))
109    : []
110
111const onTasks: Trigger = event =>
112  event.isLanded && TASK_TOOLS.includes(event.tool)
113    ? [{ kind: 'tasks', tool: event.tool, input: event.input, result: event.result }]
114    : []
115
116/** Every trigger, built once per session from its settings; only `onWatchedDoc` reads them. */
117export const triggersOf = (settings: RavenSettings): readonly Trigger[] => [
118  onEdit,
119  onShell,
120  onWatchedDocOf(settings.watchedPaths),
121  onDirective,
122  onTasks,
123]
124
125export const actionsOf = (
126  event: ToolEvent,
127  triggers: readonly Trigger[],
128  planPaths: ReadonlySet<string> = new Set(),
129) => triggers.flatMap(trigger => trigger(event, planPaths))
130
131/**
132 * One of plan mode's notes to the main loop, off `prompt.attachment`: `plan_mode` rides every
133 * request while planning, `plan_mode_exit` and `plan_mode_reentry` mark leaving and re-entering it.
134 * Each names the plan file wherever the session keeps plans.
135 */
136export type PlanNote = {
137  type: 'plan_mode' | 'plan_mode_exit' | 'plan_mode_reentry'
138  planFilePath: string
139  /** Whether the engine found the plan file; a re-entry note is only made when it did. */
140  hasPlan?: boolean
141}
142
143/** Leaving or re-entering plan mode opens the plan, when there is one to read. */
144export const planActionsOf = (note: PlanNote): readonly Action[] =>
145  note.type !== 'plan_mode' && note.hasPlan !== false
146    ? [{ kind: 'show-doc', path: note.planFilePath, force: true }]
147    : []
148
hooks/core/view.ts 106 lines
1import type { Elements, RenderElement, RenderSurface } from 'claude-code'
2import type { PaneSubcommand } from '../names'
3import type { Style } from '../ui/style'
4
5/**
6 * The elements a view draws with; Raven draws on the terminal surface, mobile among them. The
7 * engine always completes every surface's table to a constructor for every element name, even one
8 * that surface doesn't carry (it just draws a fragment there); so `Image`, `Input` and `Select`
9 * are typed as present here too, never `| undefined`: presence can never tell a real control from
10 * a completed fragment. A view never checks for one; it reads `kit.capabilities` instead, which
11 * `capabilitiesOf` derives from the surface name, the one source of truth for what each surface
12 * actually carries.
13 */
14export type Ui = Pick<
15  Elements['terminal'],
16  'Box' | 'Text' | 'Button' | 'Code' | 'Markdown' | 'Image' | 'Input' | 'Select' | 'Client'
17>
18
19/** What a surface's element table lets a view draw: typed text, a picker, an inline image. */
20export type Capabilities = {
21  canType: boolean
22  canPick: boolean
23  canShowImage: boolean
24  /** Whether the surface draws a `Client` (a surface module with pointer hover); see `ui/strip.tsx`. */
25  canClient: boolean
26}
27
28/**
29 * The fixed, per-surface element table (`Elements` in `claude-code`): every surface carries
30 * `Input` and `Select` but `mobile`; only `terminal` carries `Image`.
31 */
32const CAPABILITIES_BY_SURFACE: Record<RenderSurface, Capabilities> = {
33  terminal: { canType: true, canPick: true, canShowImage: true, canClient: true },
34  desktop: { canType: true, canPick: true, canShowImage: false, canClient: true },
35  vscode: { canType: true, canPick: true, canShowImage: false, canClient: false },
36  mobile: { canType: false, canPick: false, canShowImage: false, canClient: false },
37}
38
39/** A surface not among the table's known rows draws no typed, picking or imaging controls. */
40const NO_CAPABILITIES: Capabilities = {
41  canType: false,
42  canPick: false,
43  canShowImage: false,
44  canClient: false,
45}
46
47/**
48 * A surface's capabilities, read off the fixed table above, never off element presence. An
49 * unknown future surface (one the table hasn't been taught yet) degrades to `NO_CAPABILITIES`
50 * rather than throwing, so a view still renders, just without controls the surface may not
51 * actually support.
52 */
53export function capabilitiesOf(surface: RenderSurface, keyboardControls = false): Capabilities {
54  const capabilities = CAPABILITIES_BY_SURFACE[surface] ?? NO_CAPABILITIES
55  // R42: with `keyboardControls` every surface draws the plain-Button fallback, which is in the Tab ring.
56  return keyboardControls ? { ...capabilities, canClient: false } : capabilities
57}
58
59/** `terminal`'s row, every capability on, so a caller outside a real render can skip the surface. */
60export const FULL_CAPABILITIES: Capabilities = CAPABILITIES_BY_SURFACE.terminal
61
62/** The engine refuses a `Markdown`, `Code` or `Text` element whose text is longer than this. */
63export const ELEMENT_TEXT_LIMIT = 10_000
64
65/**
66 * What a view's render is handed: the elements, the pane body's width and rows in cells, and the
67 * capabilities its surface carries: computed once in `register.ts`'s `kitOf`, so a view never
68 * calls `capabilitiesOf` or checks an element's presence itself.
69 */
70export type Kit = {
71  ui: Ui
72  columns: number
73  rows: number
74  capabilities: Capabilities
75  /** The border style (`cardStyle` setting), resolved once in `register.ts`; every pane frames through it. */
76  style: Style
77  /**
78   * Registers the handler a pill's `{ press: id }` post runs, for the pane this render draws; the
79   * controller clears the pane's registrations before each of its renders (`core/presses.ts`).
80   */
81  press: (id: string, onPress: () => void) => void
82}
83
84/**
85 * What a kit function that draws off `kit.ui` alone needs: the `hooks/ui/` kit's own
86 * components take this rather than the full `Kit`, so a caller holding only `{ ui, columns }`
87 * (the `AbovePrompt` band) can still reach them without a cast.
88 */
89export type UiKit = Pick<Kit, 'ui'>
90
91/**
92 * One engine pane Raven draws. The engine shows one pane at a time and tabs the rest, so each
93 * view is a tab.
94 */
95export type View = {
96  readonly pane: { readonly id: string; readonly title: string }
97  /** The `/raven <subcommand>` that toggles it; one of `PANE_SUBCOMMANDS`, so the CLI, the tool
98   * and the views share one list. */
99  readonly subcommand: PaneSubcommand
100  /** Rereads the world; the controller runs it before the first drawing of a fresh module. */
101  refresh?: () => Promise<void>
102  render: (kit: Kit) => RenderElement
103  /** Moves the view's own scroll by `by` rows (negative up); true when it handled the move. */
104  scroll?: (by: number) => boolean
105}
106
hooks/names.ts 47 lines
1/**
2 * Every name derived from the product's working title, so a rename is one edit here; the CLI
3 * imports these at build time.
4 */
5export const NAME = 'raven'
6
7export const COMMAND = NAME
8export const COMMAND_DESCRIPTION =
9  'Toggle the Raven preview pane (diff, docs, review), or turn it off and on'
10
11export const DIFF_PANE = { id: NAME, title: 'Diff' } as const
12export const DOC_PANE = { id: `${NAME}-doc`, title: 'Doc' } as const
13export const TREE_PANE = { id: `${NAME}-files`, title: 'Files' } as const
14export const TASKS_PANE = { id: `${NAME}-tasks`, title: 'Tasks' } as const
15/** The `/raven <subcommand>` word of each pane, which `raven open <pane>` and the tool share. */
16export const PANE_SUBCOMMANDS = ['diff', 'doc', 'files', 'tasks'] as const
17export type PaneSubcommand = (typeof PANE_SUBCOMMANDS)[number]
18export const PANE_IDS: readonly string[] = [DIFF_PANE.id, DOC_PANE.id, TREE_PANE.id, TASKS_PANE.id]
19
20/** The short name `$.tool.register` takes; the model calls it as `mcp__<plugin>__show`. */
21export const TOOL_NAME = 'show'
22
23/**
24 * The tool's full name, as the model sees it. A plugin loaded from a directory may carry a name
25 * other than `raven`, so this reads `$.plugin.name` at runtime rather than assuming one.
26 */
27export const toolNameOf = (pluginName: string) => `mcp__${pluginName}__${TOOL_NAME}`
28
29/** The start of the line the CLI prints after a directive, for a reader with no mod to consume it. */
30export const FALLBACK_PREFIX = 'Raven pane is not active;'
31
32/** The prefix of a directive line the CLI prints; the JSON payload follows it. */
33export const DIRECTIVE_PREFIX = `::${NAME}::`
34
35/** The store key of one repository's pending review comments. */
36export const commentsStoreKeyOf = (repository: string) => `comments:${repository}`
37
38/** The store key of one repository's diff base choice (HEAD, session start, or branch point). */
39export const sourceStoreKeyOf = (repository: string) => `source:${repository}`
40
41/** The store key of one repository's forced diff layout (`split` or `unified`; absent means by width). */
42export const splitStoreKeyOf = (repository: string) => `split:${repository}`
43
44/** Warns that the built-in diff panel, left open, will cover Raven's dock. */
45export const DIFF_PANEL_WARNING =
46  'Close the built-in diff panel (✕) once so Raven can dock beside the transcript'
47
hooks/ui/style.ts 81 lines
1/**
2 * The border style, as data: one `Style` per `cardStyle` setting, read by every pane through
3 * `kit.style` so no view carries a box glyph of its own. Pure, no imports: it loads in the mod
4 * sandbox and under bun alike.
5 */
6
7export type CardStyle = 'bar' | 'none' | 'sharp' | 'rounded'
8
9export const CARD_STYLES: readonly CardStyle[] = ['bar', 'none', 'sharp', 'rounded']
10
11export const isCardStyle = (value: unknown): value is CardStyle =>
12  typeof value === 'string' && (CARD_STYLES as readonly string[]).includes(value)
13
14/** The six glyphs of a closed frame: four corners, the horizontal and the vertical. */
15export type Frame = { tl: string; tr: string; bl: string; br: string; h: string; v: string }
16
17export const SHARP_FRAME: Frame = { tl: '┌', tr: '┐', bl: '└', br: '┘', h: '─', v: '│' }
18export const ROUNDED_FRAME: Frame = { tl: '╭', tr: '╮', bl: '╰', br: '╯', h: '─', v: '│' }
19
20/** A note's bar, the same in every style: drawn in the note's state colour. */
21export const NOTE_BAR = '┃'
22
23export type Style = {
24  cardStyle: CardStyle
25  /** The left mark drawn per body row of a group (file card, doc section); `bar` only. */
26  group: string | null
27  /** The closed frame around a group; `sharp` and `rounded` only. */
28  frame: Frame | null
29  /** A dim `─` rule row under a title; `none` only. */
30  titleRule: boolean
31  /** The compose box's frame: always closed, rounded only under `rounded`. */
32  compose: Frame
33  /** `rule`: header and one rule, no verticals. `grid`: the full boxed grid. */
34  table: 'rule' | 'grid'
35  /** The outer corners of a `grid` table. */
36  tableCorners: 'sharp' | 'rounded'
37}
38
39const STYLES: Record<CardStyle, Style> = {
40  bar: {
41    cardStyle: 'bar',
42    group: '▌',
43    frame: null,
44    titleRule: false,
45    compose: SHARP_FRAME,
46    table: 'rule',
47    tableCorners: 'sharp',
48  },
49  none: {
50    cardStyle: 'none',
51    group: null,
52    frame: null,
53    titleRule: true,
54    compose: SHARP_FRAME,
55    table: 'rule',
56    tableCorners: 'sharp',
57  },
58  sharp: {
59    cardStyle: 'sharp',
60    group: null,
61    frame: SHARP_FRAME,
62    titleRule: false,
63    compose: SHARP_FRAME,
64    table: 'grid',
65    tableCorners: 'sharp',
66  },
67  rounded: {
68    cardStyle: 'rounded',
69    group: null,
70    frame: ROUNDED_FRAME,
71    titleRule: false,
72    compose: ROUNDED_FRAME,
73    table: 'grid',
74    tableCorners: 'rounded',
75  },
76}
77
78export function styleOf(cardStyle: CardStyle): Style {
79  return STYLES[cardStyle]
80}
81