SLOPSHOPPER

glitchdeck

A mod that docks a live pane beside your conversation: what Claude is doing right now, every agent, workflow and background task it started as a process you…

panerowsguardcommandtoastprompt
v0.2.1MITupdated 2026-10-210hte/glitchdeck
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · glitchdeck
│ ┃ glitchdeck ✕ › fix the failing auth test and add an audit log call │ ┃ fold-main ╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱ │ ┃ ⏺ Read(src/auth.ts) │ ┃ ✓ last turn 42s · 9 tools · 1 error ⎿ Read 6 lines │ ┃ ✓ Bash cat .env ⏺ Update(src/auth.ts) │ ┃ ✓ Bash rm -rf build && git push --force o ⎿ Added 2 lines, removed 1 line │ ┃ ✓ Bash git status --porcelain ⏺ Bash(bun test) │ ┃ ✗ Bash bun test ⎿ 3 pass, 1 fail │ ┃ ✓ Write src/cache.ts │ ┃ ✓ Write src/audit.ts ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ ✓ Edit src/auth.ts │ ┃ ✓ Grep refresh\( ✻ Worked for 42s · done 4:20 PM │ ┃ ✓ Read src/auth.ts │ ┃ › /glitchdeck │ ┃ files 1 read · 3 edited · 0 created · 1 de │ ┃ │ ┃ fold-history ╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱ │ ┃ │ ┃ hist-1 --:-- hist-1~fill │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · glitchdeck
fold-main ╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱ opus 5.5 ✓ last turn 42s · 9 tools · 1 error ✓ Bash cat .env 0.0s ✓ Bash rm -rf build && git push --force origin… 0.0s ✓ Bash git status --porcelain 0.0s ✗ Bash bun test 0.0s ✓ Write src/cache.ts 0.0s ✓ Write src/audit.ts 0.0s ✓ Edit src/auth.ts 0.0s ✓ Grep refresh\( 0.0s ✓ Read src/auth.ts 0.0s files 1 read · 3 edited · 0 created · 1 deleted fold-history ╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱╱ 1 hist-1 --:-- hist-1~fill hist-1~copy
README
 ██████╗ ██╗     ██╗████████╗ ██████╗██╗  ██╗██████╗ ███████╗ ██████╗██╗  ██╗
██╔════╝ ██║     ██║╚══██╔══╝██╔════╝██║  ██║██╔══██╗██╔════╝██╔════╝██║ ██╔╝
██║  ███╗██║     ██║   ██║   ██║     ███████║██║  ██║█████╗  ██║     █████╔╝
██║   ██║██║     ██║   ██║   ██║     ██╔══██║██║  ██║██╔══╝  ██║     ██╔═██╗
╚██████╔╝███████╗██║   ██║   ╚██████╗██║  ██║██████╔╝███████╗╚██████╗██║  ██╗
 ╚═════╝ ╚══════╝╚═╝   ╚═╝    ╚═════╝╚═╝  ╚═╝╚═════╝ ╚══════╝ ╚═════╝╚═╝  ╚═╝

Claude Code 2.1.303+ mod version license: MIT

A Claude Code mod that docks a live pane beside your conversation. It shows what Claude is doing right now, every agent, workflow and background task it started as a process you can open, how fast it is writing, and every prompt you sent, one click away from its place in the transcript.

<img src="https://github.com/user-attachments/assets/638a90ef-8f42-4280-bf7d-435054fca8f1" width="521" alt="The glitchdeck pane: a test runs in the main loop while the throughput graph scrolls; a background job fails and its row turns red; an Explore agent is opened to show its live tool calls, then closed.">

No panels, no fills. Everything finished fades to gray, and only what is alive carries the one ice-blue accent, with a bar beside it that breathes. Failures keep a red bar.

What it shows

main follows the main loop live: thinking, writing, preparing or running a tool (and which one, on what), with a ticking turn clock. A question put to you, or a plan to approve, holds its bar still and says waiting. Above it, the last minute of output speed, every agent's included, measured while responses stream; it scrolls while the turn or any agent runs, and freezes, gray, once nothing does. Under it: the turn's finished tool calls, newest first, with their durations, the todo list's progress, and how many files the main loop read, edited, created and deleted over the session (an agent's own calls are in its timeline; Claude's own files, such as its scratchpad, plans and memory, are left out). When the turn ends it keeps a one-line receipt.

processes lists what the session started, each row opening with its kind:

KindComes fromEnds when
agentthe Agent tool, foreground or backgroundits turn completes, its notification arrives, or the agent list says so
workflowthe Workflow tool; a few of its agents nest under it while it runsits task notification, TaskStop, or the next stop that no longer lists it
shella Bash or PowerShell command run in the background, by the session or an agentits task notification with the exit code, its agent's final answer when the command ends with it, TaskStop, Claude checking on it with GetTask, or the next stop that no longer lists it
monitorthe Monitor toolits task notification, TaskStop, or the next stop that no longer lists it

Live work comes first, with its last tool call under it. Finished work drops to one gray line; failed work keeps a red bar and says why (exit 1, killed). A row glitches for a moment when its state changes. Open one to swap the list for that process's live timeline: an agent's tool calls, tokens and last words, or a workflow's agents.

prompts numbers your prompts, the ones typed while Claude works included. Click one and the transcript scrolls back to it.

Before anything has run, main is its header with the model's name, and the files line at zero; processes and prompts appear once they have something to show.

Install

Built on Claude Code 2.1.303 and last tested on 2.1.306 (mods are early access; the API moves between releases).

glitchdeck needs the fullscreen layout. Turn it on in ~/.claude/settings.json:

{ "tui": "fullscreen" }

Without it, the pane sits above the prompt instead of beside the transcript, and jumping to a prompt does not work.

Then, at the prompt of a terminal session:

/plugin install glitchdeck --marketplace 0hte/glitchdeck

Answer y to add the marketplace, then pick a scope.

Use

ActionHow
Open or close the pane/glitchdeck (also /glitchdeck open, /glitchdeck close)
Fold or open a sectionclick its name: ▾ is open, ▸ is folded to its header, which keeps its status on the right
Open a processclick any line of it
Back to the listclick ‹ name at the top of the timeline
Every process, one line eachclick +N more; ▴ / ▾ page it, ‹ fewer returns
Page through promptsclick ▴ / ▾
Jump to a promptclick its row
Put a prompt back in the boxclick ↩ beside its time; it lands at the cursor, so a draft already typed survives
Copy a promptclick ⧉ beside its time; it copies the prompt as you sent it
Stop a processclick [stop] on its row, then answer the permission prompt
Stop the turnclick [stop] beside the turn clock

Every control also takes the keyboard: focus the pane with ctrl+x tab, move with tab, press with enter.

When you open the pane yourself, it opens at any terminal width. When it opens on its own at session start, it waits until the terminal is 144 columns wide, or 110 if you opened it yourself before and haven't closed it since. Closing it keeps it closed across reloads of the mod until you open it again.

Options

One option, set in /config or under pluginConfigs in your settings: openOnStart (default true) opens the pane when a session starts.

Limits

  • No event reports when you answer a permission prompt, so a call held at one keeps breathing as if it ran. Only a question or a plan put to you shows waiting: its whole run is the wait.
  • Only work with a task id of its own can be stopped: background commands, monitors, workflows and background agents. A foreground agent ends with the turn, so the turn's own control is what stops it.
  • Jumping to a prompt works in the terminal's fullscreen layout, from the main conversation. The desktop app does not let a plugin scroll the transcript.
  • A resumed session rebuilds its history from the transcript file. Past 4 MiB, which a plugin cannot read, it falls back to the session's newest 4096 messages: those carry no times (rows show --:--) and jump by matching the prompt's text. When neither can be read, a toast says so.
  • Under a Team or Enterprise organization, or on a machine with managed settings (unless the organization's managed prependPlugins leaves it out), Claude Code's built-in security plugin keeps plugins you install away from the settings-hook events and from what is folded into a running turn, and says so in the transcript. There, a resumed session's history comes from its messages (after an in-session /resume, at your next prompt), and a background command, monitor or workflow whose notification arrives while Claude is working is never seen ending: it stays live until Claude checks on it with GetTask (commands only), or the session is cleared or resumed.
  • Workflow agents are not in Claude Code's agent list, so their timelines start when glitchdeck sees them and are not read back after a reload.
  • No tool reports a deletion, so a file counts as deleted when one of the main loop's shell commands names it to rm, unlink, git rm, del or Remove-Item. A folder or a glob counts as one, and a file deleted some other way, by a script for instance, is not counted.
  • The colors are tuned for dark terminals.
  • While a response streams, its speed is estimated from what it streams; the true token count corrects it when the response ends, and output it never streamed, such as hidden thinking, is spread over the time it took. Outside the terminal the graph is drawn in braille and moves only when the pane redraws.

Privacy

Prompts, commands, targets, tasks and agents' words go through a credential filter, and escape codes and control characters are stripped, before anything is kept or drawn; files are kept only as a hash of their path, so each is counted once. The filter mostly protects your screen: any plugin can read another's state, and can hook the same events glitchdeck does.

Develop

.claude-plugin/types/ is written by Claude Code each time it loads the mod and is gitignored, so on a fresh clone run claude --plugin-dir . once before tsc.

claude --plugin-dir .          # load from this folder; saving a file reloads it
claude plugin validate .       # what the engine sees and would refuse
claude plugin test .           # tests/ against the engine's test kit
npx -p typescript tsc -p .     # types

License

MIT

Source 23 files
hooks/register.tsx 822 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, RenderSurface, Timer, TurnStepChunk, UiPressArgument } from 'claude-code'
3
4import type { ActivityKind, FileMarks, Fx, HistoryEntry, Main, Proc, SectionKey, Timeline, Todos, ToolState, View } from '../types'
5import { effectsOf } from './core/effects'
6import type { Effect } from './core/effects'
7import { closeColumn, credit, flowCols, newFlow, newStream, settle } from './core/flow'
8import type { Stream } from './core/flow'
9import { fmtClock } from './core/fmt'
10import { FRAME_MS, GLITCH_MS } from './core/glitch'
11import { allText, attachUuid, keepRow, originalOf, promptText, promptsFromMessages, promptsFromTranscript, pushPrompt, rowKey, textKey } from './core/history'
12import { columnMs } from './core/graph'
13import { GRAPH_ROWS, layout } from './core/layout'
14import {
15  DEFAULT_MAIN,
16  DEFAULT_TODOS,
17  endTool,
18  endTurn,
19  kindOfChunk,
20  runningCalls,
21  setActivity,
22  startTool,
23  startTurn,
24  targetOf,
25  todoCreated,
26  todoUpdated,
27} from './core/main'
28import { internalRoots, markFile } from './core/files'
29import type { Place } from './core/files'
30import {
31  addProc,
32  applyList,
33  applyStep,
34  callsFromMessages,
35  childrenOf,
36  detailItems,
37  endCall,
38  endChildren,
39  endLive,
40  endMissing,
41  endingOf,
42  isLive,
43  itemHeight,
44  newProc,
45  setState,
46  shortType,
47  shownKids,
48  startCall,
49  topLevel,
50  turnEnding,
51  withBackfill,
52} from './core/procs'
53
54import { BREATH, BREATH_MS, C } from './palette'
55import { GRAPH_KEY, GRAPH_MIN_W, graphCells, graphCols, graphView } from './views/graph'
56import { COPY_SUFFIX, FILL_SUFFIX, HIST_PREFIX, histNumOf, historySection } from './views/history'
57import { mainSection, nowRows } from './views/main'
58import { PROC_PREFIX, STOP_SUFFIX, canStop, detailSection, itemsSection, listSection, maxProcOffset, procIdOf, secondLine } from './views/procs'
59import type { Bar, Clock, Fold } from './views/section'
60
61const PANE = 'glitchdeck'
62const COLUMNS = 60
63const POLL_MS = 3000
64
65const DEFAULT_VIEW: View = { histOffset: 0, agent: '', allProcs: false, procOffset: 0, isClosed: false }
66
67// Each value keeps its own shape tag: bump only the one whose shape changed, and only it reads as absent.
68const history = atom({ plugin: 'glitchdeck', key: 'history' } as const, [] as readonly HistoryEntry[], { shape: 'v6' })
69const view = atom({ plugin: 'glitchdeck', key: 'view' } as const, DEFAULT_VIEW, { shape: 'v6' })
70const main = atom({ plugin: 'glitchdeck', key: 'main' } as const, DEFAULT_MAIN as Main, { shape: 'm10' })
71const todos = atom({ plugin: 'glitchdeck', key: 'todos' } as const, DEFAULT_TODOS as Todos, { shape: 'v6' })
72const files = atom({ plugin: 'glitchdeck', key: 'files' } as const, {} as FileMarks, { shape: 'f8' })
73const procs = atom({ plugin: 'glitchdeck', key: 'procs' } as const, [] as readonly Proc[], { shape: 'p7' })
74const fx = atom({ plugin: 'glitchdeck', key: 'fx' } as const, { frame: 0 } as Fx, { shape: 'v6' })
75// A family: one value per process, written alone when that process calls a tool.
76const timeline = { plugin: 'glitchdeck', key: 'timeline' } as const
77
78const openPane = ($: EngineInterface) => $.ui.open({ id: PANE, title: 'glitchdeck', columns: COLUMNS })
79
80const clamp = (n: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, n))
81
82// `update` always writes and redraws its readers; these skip it when the reducer changes nothing.
83// One per atom: the engine's scan needs each state call to name its atom directly.
84async function patchMain($: EngineInterface, change: (m: Main) => Main) {
85  const m = await read($, main)
86  if (change(m) !== m) await update($, main, change)
87}
88async function patchHistory($: EngineInterface, change: (h: readonly HistoryEntry[]) => readonly HistoryEntry[]) {
89  const h = await read($, history)
90  if (change(h) !== h) await update($, history, change)
91}
92async function patchFiles($: EngineInterface, change: (f: FileMarks) => FileMarks) {
93  const f = await read($, files)
94  if (change(f) !== f) await update($, files, change)
95}
96async function patchView($: EngineInterface, change: (v: View) => View) {
97  const v = await read($, view)
98  if (change(v) !== v) await update($, view, change)
99}
100/** Resolves whether a process changed state, so the caller can start the glitch, and which ones the cap let go. */
101async function patchProcs($: EngineInterface, change: (p: readonly Proc[]) => readonly Proc[]) {
102  const before = await read($, procs)
103  if (change(before) === before) return { isChanged: false, gone: [] as string[] }
104  const after = await update($, procs, change)
105  const kept = new Set(after.map(p => p.id))
106  return {
107    isChanged: after.some(p => before.find(b => b.id === p.id)?.changedAt !== p.changedAt),
108    gone: before.filter(b => !kept.has(b.id)).map(b => b.id),
109  }
110}
111
112async function isProc($: EngineInterface, id: string) {
113  return (await read($, procs)).some(p => p.id === id)
114}
115
116// Timers die with the module on a reload; session.start, which fires again, restarts what is needed.
117// Where relative and internal paths are judged from; learned at session start, which a reload fires again.
118let place: Place = { cwd: '', home: '', roots: [] }
119let fxTimer: Timer | undefined
120let fxBeat = 0
121let glitchUntil = 0
122let pollTimer: Timer | undefined
123let pollBeat = 0
124let graphTimer: Timer | undefined
125let graphEvery = 0
126let graphBeat = 0
127// The graph's columns at the pane's last render, kept while it is away: they share the minute between them.
128let graphWidth = graphCols(COLUMNS)
129// Whether the pane last drew the graph as a Raster, which the timer scrolls between redraws.
130let isGraphDrawn = false
131// Messages to read at the next prompt: a /resume that only session.end saw, or a start before they loaded.
132let pendingSeed: 'resume' | 'start' | undefined
133// What every response of the session streamed, a column per tick, and the responses streaming now.
134let flow = newFlow()
135const streams = new Set<Stream>()
136// False only while the pane's last render had no flow to draw: the first column then redraws it, once.
137let isFlowDrawn = true
138
139/** A refused period ends an interval without a word: one that has not beaten lately is started again. */
140const isStale = (beat: number, now: number, ms: number) => now - beat > ms * 3
141
142const stopFx = () => {
143  fxTimer?.cancel()
144  fxTimer = undefined
145}
146const stopPoll = () => {
147  pollTimer?.cancel()
148  pollTimer = undefined
149}
150const stopGraph = () => {
151  graphTimer?.cancel()
152  graphTimer = undefined
153}
154
155/** Redraws the rows every frame while a state change is still glitching, then stops. */
156async function kickFx($: EngineInterface) {
157  const now = await $.clock.now()
158  glitchUntil = now + GLITCH_MS
159  if (fxTimer && !isStale(fxBeat, now, FRAME_MS)) return
160  stopFx()
161  fxBeat = now
162  fxTimer = $.clock.every(FRAME_MS, () => void fxFrame($).catch(stopFx))
163}
164
165async function fxFrame($: EngineInterface) {
166  const now = await $.clock.now()
167  fxBeat = now
168  if (now > glitchUntil) stopFx()
169  await update($, fx, f => ({ frame: f.frame + 1 }))
170}
171
172async function changeProcs($: EngineInterface, change: (p: readonly Proc[]) => readonly Proc[]) {
173  const { isChanged, gone } = await patchProcs($, change)
174  // State has no delete: a process the cap let go keeps an empty timeline.
175  for (const id of gone) await $.state.set({ ...timeline, id }, { calls: [], total: 0 })
176  if (isChanged) await kickFx($)
177}
178
179/** Agents end without a notification when they run in the foreground: the list says so. */
180async function pollAgents($: EngineInterface) {
181  const [list, agents, now] = await Promise.all([read($, procs), $.agent.list(), $.clock.now()])
182  pollBeat = now
183  await changeProcs($, ps => applyList(ps, agents, now))
184  if (!list.some(p => p.kind === 'agent' && isLive(p)) && !agents.some(a => a.status === 'running')) stopPoll()
185}
186
187function ensurePoll($: EngineInterface, now: number) {
188  if (pollTimer && !isStale(pollBeat, now, POLL_MS)) return
189  stopPoll()
190  pollBeat = now
191  pollTimer = $.clock.every(POLL_MS, () => void pollAgents($).catch(stopPoll))
192}
193
194/** Agents stream tokens; shells and monitors do not. */
195const isStreamer = (p: Proc) => isLive(p) && p.kind !== 'shell' && p.kind !== 'monitor'
196
197/** Whether anything can still stream: the graph keeps scrolling while it can, and freezes gray after. */
198const isFlowing = (m: Main, ps: readonly Proc[]) => m.isRunning || streams.size > 0 || ps.some(isStreamer)
199
200/** While anything runs, the graph closes a column per tick, drawn or not, so it always shows the last minute. */
201async function startGraph($: EngineInterface) {
202  const every = columnMs(graphWidth)
203  const now = await $.clock.now()
204  if (graphTimer && graphEvery === every && !isStale(graphBeat, now, every)) return
205  stopGraph()
206  graphEvery = every
207  graphBeat = now
208  graphTimer = $.clock.every(every, () => void tickGraph($).catch(() => undefined))
209}
210
211async function tickGraph($: EngineInterface) {
212  for (const s of streams) credit(flow, s)
213  closeColumn(flow, graphEvery)
214  const [m, ps, now] = await Promise.all([read($, main), read($, procs), $.clock.now()])
215  graphBeat = now
216  const isLiveNow = isFlowing(m, ps)
217  if (isGraphDrawn) await $.ui.blit({ requestId: PANE, key: GRAPH_KEY, cells: graphCells(C, { flow, isLive: isLiveNow }, graphWidth) })
218  else if (!isFlowDrawn && flow.cols.length > 0) {
219    isFlowDrawn = true
220    await patchMain($, x => ({ ...x, flow: flowCols(flow) }))
221  }
222  if (!isLiveNow) {
223    stopGraph()
224    // Kept for a reload, which starts the module, and so the flow, over.
225    await patchMain($, x => ({ ...x, flow: flowCols(flow) }))
226  } else if (columnMs(graphWidth) !== graphEvery) await startGraph($)
227}
228
229/** A response starts streaming: its text counts toward the graph from its first piece. */
230const openStream = ($: EngineInterface) => {
231  const s = newStream(flow)
232  streams.add(s)
233  void startGraph($).catch(() => undefined)
234  return s
235}
236
237const countChunk = (s: Stream, c: TurnStepChunk) => {
238  if (c.kind === 'text' || c.kind === 'thinking') s.chars += c.text.length
239  else if (c.kind === 'input') s.chars += c.json.length
240}
241
242async function applyEffect($: EngineInterface, x: Effect, now: number) {
243  if (x.kind === 'file') await patchFiles($, f => markFile(f, x.key, x.mark))
244  else if (x.kind === 'proc') await changeProcs($, ps => addProc(ps, x.proc))
245  else if (x.kind === 'end') await changeProcs($, ps => endLive(ps, x.id, x.state, x.why, now))
246  else if (x.kind === 'todos') await update($, todos, () => x.todos)
247  else if (x.kind === 'todo-created') await update($, todos, t => todoCreated(t, x))
248  else await update($, todos, t => todoUpdated(t, x))
249}
250
251/** Everything this session showed, but the model's name and whether the person closed the pane. */
252async function resetSession($: EngineInterface) {
253  stopGraph()
254  flow = newFlow()
255  streams.clear()
256  await update($, history, () => [])
257  await update($, view, v => ({ ...DEFAULT_VIEW, isClosed: v.isClosed, collapsed: v.collapsed }))
258  await update($, main, m => ({ ...DEFAULT_MAIN, model: m.model }))
259  await update($, todos, () => DEFAULT_TODOS)
260  await update($, files, () => ({}))
261  for (const p of await read($, procs)) await $.state.set({ ...timeline, id: p.id }, { calls: [], total: 0 })
262  await update($, procs, () => [])
263}
264
265/**
266 * The history from the session's messages, for when classic.SessionStart never ran: they carry no ids
267 * or times, so a history written meanwhile stays. Resolves true when there were no messages yet.
268 */
269async function seedHistory($: EngineInterface, isQuiet: boolean) {
270  const rows = await $.session.messages().catch(() => null)
271  if (!Array.isArray(rows)) {
272    if (!isQuiet) $.ui.toast("glitchdeck couldn't read this session's earlier prompts")
273    return false
274  }
275  if (rows.length > 0) await update($, history, h => (h.length === 0 ? promptsFromMessages(rows) : h))
276  return rows.length === 0
277}
278
279export const register: Register = (on, options) => {
280  // Transcript row ids as drawn, by rowKey. Rebuilt as rows redraw after a reload.
281  const drawn = new Map<string, string>()
282  // The same rows by their text, for prompts read back without an id.
283  const drawnByText = new Map<string, string>()
284  // Agents whose conversation was read back since this load, so a press reads it once.
285  const backfilled = new Set<string>()
286
287  on('session.start', async ($, e, next) => {
288    const started = await next(e)
289    await $.command.register({
290      name: 'glitchdeck',
291      description: 'Toggle the glitchdeck pane: what Claude is doing, the processes it started and your prompts',
292      argumentHint: '[open|close]',
293      immediate: true,
294    })
295    const [model, m, now] = await Promise.all([$.session.model().catch(() => ''), read($, main), $.clock.now()])
296    const [CLAUDE_CONFIG_DIR, HOME, USERPROFILE, TMPDIR, TEMP, TMP, cwd] = await Promise.all([
297      $.env.get('CLAUDE_CONFIG_DIR').catch(() => undefined),
298      $.env.get('HOME').catch(() => undefined),
299      $.env.get('USERPROFILE').catch(() => undefined),
300      $.env.get('TMPDIR').catch(() => undefined),
301      $.env.get('TEMP').catch(() => undefined),
302      $.env.get('TMP').catch(() => undefined),
303      $.session.cwd().catch(() => ''),
304    ])
305    place = { cwd, home: HOME || USERPROFILE || '', roots: internalRoots({ CLAUDE_CONFIG_DIR, HOME, USERPROFILE, TMPDIR, TEMP, TMP }) }
306    if (model) await patchMain($, x => (x.model === model ? x : { ...x, model }))
307    if (flow.cols.length === 0) flow = newFlow(m.flow)
308    if (m.isRunning) await startGraph($)
309    // Picks up agents already running when the mod (re)loads.
310    await pollAgents($).catch(() => undefined)
311    if ((await read($, procs)).some(isLive)) ensurePoll($, now)
312    // A reload keeps the history it had; an empty one is a fresh, resumed or forked session's.
313    if ((await read($, history)).length === 0 && (await seedHistory($, true))) pendingSeed = 'start'
314    const isOpen = (await $.ui.panes()).some(p => p.id === PANE)
315    if (options.openOnStart !== false && !isOpen && !(await read($, view)).isClosed) void openPane($).catch(() => undefined)
316    return started
317  })
318
319  on('ui.close', async ($, e, next) => {
320    const closed = await next(e)
321    if (e.id === PANE) {
322      // Nothing is drawn while the pane is away: the glitch waits for it; the graph keeps counting.
323      stopFx()
324      isGraphDrawn = false
325      isFlowDrawn = true
326      if (e.origin.kind === 'person') await patchView($, v => (v.isClosed ? v : { ...v, isClosed: true }))
327    }
328    return closed
329  }).catch(($, e, next) => next(e))
330
331  on('session.end', async ($, e, next) => {
332    pendingSeed = e.reason === 'resume' ? 'resume' : undefined
333    if (e.reason === 'clear' || e.reason === 'resume') {
334      await resetSession($)
335      drawn.clear()
336      drawnByText.clear()
337      backfilled.clear()
338    }
339    return next(e)
340  })
341
342  // A resumed or forked session loads its rows without appending them, so its prompts come from the file.
343  on('classic.SessionStart', async ($, e, next) => {
344    const done = await next(e)
345    if (e.source === 'resume' || e.source === 'fork') {
346      pendingSeed = undefined
347      await resetSession($)
348      drawn.clear()
349      drawnByText.clear()
350      backfilled.clear()
351      // The file has ids and times; past 4 MiB it cannot be read, and the session's newest messages stand in.
352      const text = await $.fs.read(e.transcript_path).catch(() => null)
353      const rows = typeof text === 'string' ? null : await $.session.messages().catch(() => null)
354      const seeded = typeof text === 'string' ? promptsFromTranscript(text) : Array.isArray(rows) ? promptsFromMessages(rows) : null
355      if (seeded) await update($, history, () => seeded)
356      else $.ui.toast("glitchdeck couldn't read this session's earlier prompts")
357    }
358    return done
359  }).catch(($, e, next) => next(e))
360
361  // At a stop the engine lists the background work still in flight; whatever ran here and is gone
362  // from that list has ended, even if its notification reached no hook.
363  on('classic.Stop', async ($, e, next) => {
364    const done = await next(e)
365    const listed = e.background_tasks
366    // An absent list says nothing about what still runs.
367    if (listed) {
368      const inFlight = new Set(listed.map(t => t.id))
369      const now = await $.clock.now()
370      await changeProcs($, ps => endMissing(ps, inFlight, now))
371    }
372    return done
373  }).catch(($, e, next) => next(e))
374
375  on('command.run', { command: 'glitchdeck' }, async ($, e) => {
376    const verb = e.args.trim().split(/\s+/)[0] ?? ''
377    const mine = (await $.ui.panes()).find(p => p.id === PANE)
378    if (verb === 'close' || (verb !== 'open' && mine?.isShown)) {
379      await $.ui.close({ id: PANE })
380      stopFx()
381      isGraphDrawn = false
382      isFlowDrawn = true
383      await patchView($, v => (v.isClosed ? v : { ...v, isClosed: true }))
384      return {}
385    }
386    await patchView($, v => (v.isClosed ? { ...v, isClosed: false } : v))
387    if ((await read($, main)).isRunning) await startGraph($)
388    const opened = await openPane($)
389    return opened.isPlaced ? {} : { text: `glitchdeck is waiting for room: ${opened.reason}` }
390  })
391
392  // ---------------------------------------------------------------- loops
393
394  on('turn.start', async ($, e, next) => {
395    const now = await $.clock.now()
396    await update($, main, m => startTurn(m, now, e.turnId))
397    await startGraph($)
398    return next(e)
399  })
400
401  on('turn.step', async function* ($, e, next) {
402    const agentId = e.agentId
403    const stream = openStream($)
404    try {
405      const s = next(e)
406      if (agentId) {
407        for await (const c of s) {
408          yield c
409          countChunk(stream, c)
410        }
411        const result = await s.result
412        settle(flow, stream, result.usage?.output_tokens)
413        const now = await $.clock.now()
414        await changeProcs($, ps => applyStep(ps, agentId, { usage: result.usage, answer: result.answer, now }))
415        return result
416      }
417      const model = e.model
418      await patchMain($, m => (m.model === model ? m : { ...m, model }))
419      let shown: ActivityKind | undefined
420      for await (const c of s) {
421        yield c
422        // The bookkeeping follows each piece, so no piece waits on it: characters are only counted, and
423        // the clock is read on a change of kind, not per token chunk.
424        countChunk(stream, c)
425        const kind = kindOfChunk(c.kind)
426        if (kind !== undefined && kind !== shown) {
427          shown = kind
428          const now = await $.clock.now()
429          const tool = c.kind === 'tool' ? c.name : ''
430          await patchMain($, m => setActivity(m, { kind, tool, target: '' }, now))
431        }
432      }
433      const result = await s.result
434      settle(flow, stream, result.usage?.output_tokens)
435      return result
436    } finally {
437      streams.delete(stream)
438    }
439  })
440
441  on('tool.call', async ($, e, next) => {
442    // A call this mod raised itself is the person pressing a control, not work of the turn's.
443    if (next.origin.plugin === $.plugin.name) return next(e)
444    const id = e.tool_use_id
445    const tool = String(e.tool)
446    const agentId = e.agentId
447    // The call runs while its row is written: nothing waits on the bookkeeping.
448    const running = next(e)
449    running.catch(() => undefined)
450    const target = targetOf(tool, e)
451    const [startedAt, isTracked] = await Promise.all([$.clock.now(), agentId === undefined ? false : isProc($, agentId)])
452    const row = { id, tool, target, startedAt }
453    if (agentId === undefined) await update($, main, m => startTool(m, row))
454    else if (isTracked) await update($, { ...timeline, id: agentId }, t => startCall(t, row))
455    const settle = async (state: ToolState) => {
456      const now = await $.clock.now()
457      if (agentId === undefined) await update($, main, m => endTool(m, id, state, now))
458      else if (isTracked) await update($, { ...timeline, id: agentId }, t => endCall(t, id, state, now))
459      return now
460    }
461    let ran: Awaited<typeof running>
462    try {
463      ran = await running
464    } catch (err) {
465      await settle('err')
466      throw err
467    }
468    const state: ToolState = ran.deny !== undefined ? 'deny' : ran.isError ? 'err' : 'ok'
469    const now = await settle(state)
470    if (state !== 'ok') return ran
471    for (const x of effectsOf({ tool, input: e, result: ran.result, agentId, now, place })) await applyEffect($, x, now)
472    return ran
473  }).catch(($, e, next) => next(e))
474
475
476  on('agent.spawn', async ($, e, next) => {
477    const started = await next(e)
478    if (started.deny !== undefined || !started.agentId) return started
479    const now = await $.clock.now()
480    const runId = e.workflow?.runId ?? ''
481    const agent = newProc({
482      id: started.agentId,
483      kind: runId ? 'wfagent' : 'agent',
484      type: shortType(e.subagentType),
485      task: e.description,
486      now,
487      parent: runId || e.parentAgentId || '',
488      isBackground: e.background,
489    })
490    await changeProcs($, ps => {
491      // A workflow's agents can start before its Workflow call has answered: hold a place for the run.
492      // No task id until the Workflow call answers, so nothing offers to stop the run before then.
493      const withRun =
494        runId && !ps.some(p => p.id === runId) ? addProc(ps, newProc({ id: runId, taskId: '', kind: 'workflow', type: 'workflow', task: '', now })) : ps
495      return addProc(withRun, agent)
496    })
497    if (!runId) ensurePoll($, now)
498    return started
499  }).catch(($, e, next) => next(e))
500
501  on('turn.complete', async ($, e, next) => {
502    const done = await next(e)
503    const now = await $.clock.now()
504    const agentId = e.agentId
505    if (agentId === undefined) {
506      const t = { durationMs: e.durationMs, reason: e.reason }
507      await update($, main, m => endTurn(m, now, t))
508    } else {
509      const end = turnEnding(e.reason)
510      await changeProcs($, ps => endChildren(setState(ps, agentId, end.state, end.why, now), agentId, now))
511    }
512    return done
513  })
514
515  // ---------------------------------------------------------------- rows: prompts and notifications
516
517  on('session.append', async ($, e, next) => {
518    const stored = await next(e)
519    const kind = e.origin.kind
520    const words = allText(e.message.content)
521    if (e.agentId === undefined && e.door === 'prompt' && (kind === 'composer' || kind === 'bridge')) {
522      const text = promptText(e.message.content)
523      const at = await $.clock.now()
524      await patchHistory($, list => {
525        const named = attachUuid(list, text, e.uuid, true)
526        return named !== list ? named : pushPrompt(list, { uuid: e.uuid, text, at })
527      })
528      await patchView($, v => (v.histOffset === 0 ? v : { ...v, histOffset: 0 }))
529    } else if (e.agentId === undefined && e.door === 'attachment' && e.message.name === 'queued_command' && !words.includes('<task-notification>')) {
530      // A prompt typed mid-turn reaches the model inside the engine's framing of it.
531      await patchHistory($, list => attachUuid(list, words, e.uuid, false))
532    }
533    if (e.door === 'prompt' || e.door === 'attachment' || e.door === 'delivery') {
534      // A notification is its own prompt row when the session is idle, and an attachment folded into
535      // the running turn (origin `engine`) otherwise; it reaches a subagent's loop when that agent started the task.
536      const ending = endingOf(words)
537      if (ending) {
538        const now = await $.clock.now()
539        await changeProcs($, ps => setState(ps, ending.taskId, ending.state, ending.why, now))
540      }
541    }
542    return stored
543  }).catch(($, e, next) => next(e))
544
545  // A prompt typed at idle is kept from its row, which session.append sees before this resolves; one
546  // typed over a running turn reaches the model inside that turn, so it is taken here. Slash commands do not count.
547  on('prompt.submit', async ($, e, next) => {
548    if (pendingSeed) {
549      const isQuiet = pendingSeed === 'start'
550      pendingSeed = undefined
551      await seedHistory($, isQuiet)
552    }
553    const entered = await next(e)
554    const kind = e.origin.kind
555    const text = entered.drop === undefined ? entered.text : ''
556    if (e.turnId !== undefined && (kind === 'composer' || kind === 'bridge') && text.trim() !== '' && !text.trim().startsWith('/')) {
557      const at = await $.clock.now()
558      await patchHistory($, list => pushPrompt(list, { uuid: '', text, at }))
559      await patchView($, v => (v.histOffset === 0 ? v : { ...v, histOffset: 0 }))
560    }
561    return entered
562  }).catch(($, e, next) => next(e))
563
564  on('ui.render', { component: 'UserMessage' }, ($, e, next) => {
565    const kind = e.props.origin.kind
566    if (kind === 'composer' || kind === 'bridge') {
567      keepRow(drawn, e.requestId)
568      const key = textKey(e.props.text)
569      if (!drawnByText.has(key)) drawnByText.set(key, e.requestId)
570    }
571    return next(e)
572  })
573
574  // The transcript scrolls only while answering the person's own press, so the jump runs here,
575  // inside the press dispatch, not in the Button's onPress closure. Opening an agent reads its
576  // conversation back once, for the calls it made before the mod loaded.
577  on('ui.press', { plugin: 'glitchdeck' }, async ($, e, next) => {
578    // The controls act from their own closures; a press on the row itself is the one that jumps or opens.
579    if (e.element.startsWith(HIST_PREFIX) && !e.element.endsWith(FILL_SUFFIX) && !e.element.endsWith(COPY_SUFFIX)) {
580      const entry = (await read($, history)).find(p => p.n === histNumOf(e.element))
581      if (entry) await jumpTo($, entry, drawn, drawnByText)
582    } else if (e.element.startsWith(PROC_PREFIX) && !e.element.endsWith(STOP_SUFFIX)) {
583      const id = procIdOf(e.element)
584      const p = (await read($, procs)).find(x => x.id === id)
585      if (p?.kind === 'agent' && !backfilled.has(id)) {
586        backfilled.add(id)
587        const rows = await $.session.messages({ agentId: id }).catch(() => null)
588        if (Array.isArray(rows)) {
589          const back = callsFromMessages(rows, isLive(p), targetOf)
590          if (back.length > 0) await update($, { ...timeline, id }, t => withBackfill(t, back))
591        }
592      }
593    }
594    return next(e)
595  })
596
597  // ---------------------------------------------------------------- drawing
598
599  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
600    const els = $.ui.resolve(e)
601    const [m, t, f, hist, v, ps, , now] = await Promise.all([
602      read($, main),
603      read($, todos),
604      read($, files),
605      read($, history),
606      read($, view),
607      read($, procs),
608      // Read so a glitch frame redraws the pane; the frame itself is computed from the clock.
609      read($, fx),
610      $.clock.now(),
611    ])
612    const Client = 'Client' in els ? els.Client : undefined
613    // Other surfaces list a Raster but draw it as nothing, so they get the braille graph.
614    const Raster = e.surface === 'terminal' && 'Raster' in els ? els.Raster : undefined
615    const clock: Clock = (key, since, endAt, color) =>
616      since <= 0 ? (
617        <els.Text color={color}>—</els.Text>
618      ) : Client ? (
619        <Client key={key} module="./clients/elapsed.tsx" props={{ since, now, endAt, color }} />
620      ) : (
621        <els.Text color={color}>{fmtClock((endAt ?? now) - since)}</els.Text>
622      )
623    const bar: Bar = (key, tone, rows = 1) => {
624      if (tone === 'live' && Client) return <Client key={key} module="./clients/breathe.tsx" props={{ colors: BREATH, glyph: '▎', rows, ms: BREATH_MS, now }} />
625      return (
626        <els.Box flexDirection="column" flexShrink={0}>
627          {Array.from({ length: rows }, () =>
628            tone === 'none' ? <els.Text> </els.Text> : <els.Text color={tone === 'err' ? C.err : C.accent}>▎</els.Text>,
629          )}
630        </els.Box>
631      )
632    }
633
634    // The body's own width: never wider, or the pane would draw past its frame.
635    const W = Math.max(1, e.props.bodyColumns)
636    const opened = v.agent ? ps.find(p => p.id === v.agent) : undefined
637    const top = topLevel(ps)
638
639    // Reading a timeline while drawing subscribes the pane to it: only the opened process's, its live
640    // agents', and those of the live processes the short list can show are read.
641    const folded = v.collapsed ?? {}
642    // A folded section draws no process, so none of their calls needs to redraw the pane.
643    const wanted = new Set<string>()
644    if (opened && !folded.procs) {
645      wanted.add(opened.id)
646      for (const k of childrenOf(ps, opened.id)) if (isLive(k)) wanted.add(k.id)
647    } else if (!v.allProcs && !folded.procs)
648      for (const p of top.filter(isLive)) {
649        wanted.add(p.id)
650        if (p.kind === 'workflow') for (const k of shownKids(ps, p.id).shown) if (isLive(k)) wanted.add(k.id)
651      }
652    const read2 = await Promise.all([...wanted].map(async id => [id, await read($, { ...timeline, id })] as const))
653    const calls = new Map<string, Timeline>()
654    for (const [id, tl] of read2) if (tl) calls.set(id, tl)
655    const own = opened ? calls.get(opened.id) : undefined
656
657    const L = layout({
658      rows: e.props.scroll.bodyRows,
659      main: {
660        now: nowRows(m),
661        past: m.tools.length - runningCalls(m).length,
662        hasTodo: t.items.length > 0,
663        hasActive: t.active !== '',
664        hasGraph: flow.cols.length > 0 && W >= GRAPH_MIN_W,
665      },
666      procs:
667        ps.length === 0
668          ? null
669          : {
670              items: top.map(p => (v.allProcs ? 1 : itemHeight(p, ps, secondLine(p, calls.get(p.id)) !== ''))),
671              detail: opened ? detailItems(opened, ps, own?.calls ?? []) : null,
672              isList: v.allProcs,
673            },
674      history: hist.length,
675      collapsed: folded,
676    })
677
678    const raster = Raster ? (cols: number, cells: string) => <Raster key={GRAPH_KEY} columns={cols} rows={GRAPH_ROWS} cells={cells} /> : undefined
679    if (W >= GRAPH_MIN_W) graphWidth = graphCols(W)
680    isGraphDrawn = L.showGraph && raster !== undefined
681    isFlowDrawn = flow.cols.length > 0
682    const graph = L.showGraph ? graphView(els, C, W, { g: { flow, isLive: isFlowing(m, ps) }, raster }) : null
683
684    const maxHist = Math.max(0, hist.length - L.histRows)
685    const offset = Math.min(v.histOffset, maxHist)
686    const page = (delta: number) => () =>
687      void patchView($, x => {
688        const o = clamp(x.histOffset + delta, 0, maxHist)
689        return o === x.histOffset ? x : { ...x, histOffset: o }
690      })
691    const maxProcs = maxProcOffset(ps, L.listRows)
692    const pageProcs = (delta: number) => () =>
693      void patchView($, x => {
694        const o = clamp(x.procOffset + delta, 0, maxProcs)
695        return o === x.procOffset ? x : { ...x, procOffset: o }
696      })
697    const openProc = (id: string) => () => void update($, view, x => ({ ...x, agent: x.agent === id ? '' : id }))
698    const back = () => void update($, view, x => ({ ...x, agent: '' }))
699    const toggleAll = () => void update($, view, x => ({ ...x, allProcs: !x.allProcs, procOffset: 0 }))
700    // These three reach the engine and may put a dialog up: none of them holds the press dispatch.
701    const stopProcess = (id: string) => () => void stopProc($, id).catch(() => undefined)
702    const fillPrompt = (n: number) => () => void fillFrom($, n).catch(() => undefined)
703    const copyPrompt = (n: number) => (e: UiPressArgument) => void copyFrom($, n, e.surface).catch(() => undefined)
704    const abort = () => void abortTurn($, m.turnId).catch(() => undefined)
705    const fold = (key: SectionKey): Fold => ({
706      isCollapsed: folded[key] === true,
707      onToggle: () => void update($, view, x => ({ ...x, collapsed: { ...x.collapsed, [key]: !x.collapsed?.[key] } })),
708    })
709    const shared = { list: ps, calls, now, clock, bar, onOpen: openProc, onAll: toggleAll, onStop: stopProcess, fold: fold('procs') }
710
711    return (
712      <els.Box flexDirection="column" width={W}>
713        {mainSection(els, C, W, {
714          m,
715          todos: t,
716          files: f,
717          clock,
718          bar,
719          now,
720          graph,
721          pastRows: L.pastRows,
722          showTodo: L.showTodo,
723          showFiles: L.showFiles,
724          onAbort: abort,
725          fold: fold('main'),
726        })}
727        {L.procMode === 'detail' && opened
728          ? detailSection(els, C, W, { ...shared, proc: opened, own, rows: L.detailRows, onBack: back })
729          : L.procMode === 'list'
730            ? listSection(els, C, W, { ...shared, rows: L.listRows, offset: Math.min(v.procOffset, maxProcs), onPage: pageProcs })
731            : L.procMode === 'items'
732              ? itemsSection(els, C, W, { ...shared, items: L.procItems })
733              : null}
734        {hist.length > 0
735          ? historySection(els, C, W, { list: hist, offset, rows: L.histRows, onNewer: page(-L.histRows), onOlder: page(L.histRows), onFill: fillPrompt, onCopy: copyPrompt, fold: fold('history') })
736          : null}
737      </els.Box>
738    )
739  })
740}
741
742/** The engine asks the person first, as it does for the model's own call. */
743async function stopProc($: EngineInterface, id: string) {
744  const p = (await read($, procs)).find(x => x.id === id)
745  if (!p || !canStop(p)) return
746  let why = ''
747  try {
748    // The permission path reads `consent` as the person's own words: nothing the model wrote goes in it.
749    const ran = await $.tool.call({ tool: 'TaskStop', task_id: p.taskId, consent: `The user pressed stop on ${p.kind} ${p.taskId} in the glitchdeck pane` })
750    why = ran.deny !== undefined ? ran.deny || 'refused' : ran.isError ? 'it would not stop' : ''
751  } catch (err) {
752    why = (err instanceof Error && err.message) || 'the call failed'
753  }
754  if (why) {
755    $.ui.toast(`can't stop ${p.type}: ${why}`)
756    return
757  }
758  const now = await $.clock.now()
759  await changeProcs($, list => setState(list, p.id, 'Z', 'killed', now))
760}
761
762/** Ends the turn the control was drawn for: once another has started, the engine refuses the stale id. */
763async function abortTurn($: EngineInterface, turnId: string) {
764  if (!turnId) return
765  try {
766    await $.turn.abort({ turnId })
767  } catch (err) {
768    $.ui.toast(`can't stop this turn: ${err instanceof Error ? err.message : 'it is already over'}`)
769  }
770}
771
772/** The list keeps a filtered, cut copy: this is the prompt as it was sent, or null once a toast has said why not. */
773async function sentText($: EngineInterface, n: number, verb: string) {
774  const entry = (await read($, history)).find(p => p.n === n)
775  if (!entry) return null
776  const text = originalOf(await $.session.messages().catch(() => []), entry)
777  if (text === null) $.ui.toast(`can't ${verb} prompt ${n}: its full text is no longer in the session`)
778  return text
779}
780
781const COPY_REFUSED = { 'no-surface': 'nothing here has a clipboard', 'no-clipboard': 'the clipboard took nothing', refused: 'a plugin refused it' }
782
783async function copyFrom($: EngineInterface, n: number, surface: RenderSurface) {
784  const text = await sentText($, n, 'copy')
785  if (text === null) return
786  try {
787    const copied = await $.ui.copy({ text, surface })
788    $.ui.toast(copied.isCopied ? `copied prompt ${n}` : `can't copy prompt ${n}: ${COPY_REFUSED[copied.reason]}`)
789  } catch (err) {
790    $.ui.toast(`can't copy prompt ${n}: ${(err instanceof Error && err.message) || 'the copy failed'}`)
791  }
792}
793
794/** Puts a prompt back in the box at the cursor, so a draft already typed there survives it. */
795async function fillFrom($: EngineInterface, n: number) {
796  const text = await sentText($, n, 'reuse')
797  if (text === null) return
798  try {
799    const filled = await $.prompt.fill({ text, mode: 'insert' })
800    if (filled.isFilled) return
801    // An absent cause is a hook's own refusal, which says nothing about whether a box is drawn.
802    const why = filled.refusal === 'dialog' ? 'a dialog has the keys' : filled.refusal === 'no_composer' ? 'there is no prompt box here' : 'the box would not take it'
803    $.ui.toast(`can't reuse prompt ${n}: ${why}`)
804  } catch (err) {
805    $.ui.toast(`can't reuse prompt ${n}: ${err instanceof Error ? err.message : 'the box refused it'}`)
806  }
807}
808
809async function jumpTo($: EngineInterface, entry: HistoryEntry, drawn: Map<string, string>, drawnByText: Map<string, string>) {
810  const byId = entry.uuid ? [drawn.get(rowKey(entry.uuid)), entry.uuid] : []
811  const targets = [...new Set([...byId, drawnByText.get(entry.text)].filter((t): t is string => t !== undefined && t !== ''))]
812  let why = 'not drawn yet'
813  for (const requestId of targets) {
814    const moved = await $.ui
815      .scroll({ to: { requestId }, block: 'start' })
816      .catch((err: unknown) => ({ deny: err instanceof Error ? err.message : 'scroll failed' }))
817    if (moved.deny === undefined) return
818    why = moved.deny
819  }
820  $.ui.toast(`can't jump to prompt ${entry.n}: ${why}`)
821}
822
hooks/core/effects.ts 86 lines
1import type { Proc, ProcState, Todos } from '../../types'
2import { CREATED, DELETED, EDITED, EDIT_TOOLS, READ, READ_TOOLS, deletedPaths, isInternal, keyOf, normalPath } from './files'
3import type { Place } from './files'
4import { todosFromWrite } from './main'
5import { newProc } from './procs'
6
7export type Effect =
8  | { kind: 'file'; key: string; mark: number }
9  | { kind: 'proc'; proc: Proc }
10  | { kind: 'end'; id: string; state: ProcState; why: string }
11  | { kind: 'todos'; todos: Todos }
12  | { kind: 'todo-created'; id: string; subject: string }
13  | { kind: 'todo-updated'; taskId: string; status: string; subject: string; activeForm: string }
14
15const obj = (v: unknown): Record<string, unknown> => (typeof v === 'object' && v !== null ? (v as Record<string, unknown>) : {})
16const str = (v: unknown) => (typeof v === 'string' ? v : '')
17const basename = (p: string) => p.split(/[\\/]/).pop()?.replace(/\.[^.]+$/, '') ?? ''
18
19/** Whether a file call made the file: Write says so, and an Edit that had no original file did. */
20const isCreation = (tool: string, result: Record<string, unknown>) =>
21  (tool === 'Write' && result.type === 'create') || (tool === 'Edit' && result.originalFile === null)
22
23/**
24 * What a call that went through means for the pane, read from its input and result: a file read,
25 * edited, created or deleted, a background process started or stopped, the todo list changed. Files
26 * and todos count for the main loop only, Claude's own files never; an agent's calls are in its timeline.
27 */
28export const effectsOf = (c: { tool: string; input: unknown; result: unknown; agentId?: string; now: number; place: Place }): Effect[] => {
29  const { tool, now, place } = c
30  const input = obj(c.input)
31  const result = obj(c.result)
32  const isMain = c.agentId === undefined
33  const parent = c.agentId ?? ''
34  const out: Effect[] = []
35  const touch = (raw: string, mark: number) => {
36    const normal = normalPath(raw, place)
37    if (!isInternal(normal, place.roots)) out.push({ kind: 'file', key: keyOf(normal), mark })
38  }
39
40  const file = str(input.file_path) || str(input.notebook_path)
41  if (isMain && file && READ_TOOLS.has(tool)) touch(file, READ)
42  if (isMain && file && EDIT_TOOLS.has(tool)) touch(file, isCreation(tool, result) ? CREATED : EDITED)
43  // A command sent to the background has not run yet when its call answers.
44  if (isMain && (tool === 'Bash' || tool === 'PowerShell') && !str(result.backgroundTaskId))
45    for (const p of deletedPaths(str(input.command), tool === 'PowerShell')) touch(p, DELETED)
46
47  if ((tool === 'Bash' || tool === 'PowerShell') && str(result.backgroundTaskId)) {
48    const type = tool === 'Bash' ? 'bash' : 'pwsh'
49    const endsWithParent = result.backgroundEndsWithFinalResponse === true
50    out.push({ kind: 'proc', proc: newProc({ id: str(result.backgroundTaskId), kind: 'shell', type, task: str(input.command), now, parent, endsWithParent }) })
51  }
52  if (tool === 'Monitor' && str(result.taskId)) {
53    const task = str(input.description) || str(input.command)
54    out.push({ kind: 'proc', proc: newProc({ id: str(result.taskId), kind: 'monitor', type: 'monitor', task, now, parent }) })
55  }
56  if (tool === 'Workflow' && str(result.taskId)) {
57    // The tool ignores the call's description and title: a run is named by its script.
58    const name = str(result.workflowName) || str(input.name) || basename(str(input.scriptPath)) || 'workflow'
59    const id = str(result.runId) || str(result.taskId)
60    out.push({ kind: 'proc', proc: newProc({ id, taskId: str(result.taskId), kind: 'workflow', type: 'workflow', task: name, now, parent }) })
61  }
62  if (tool === 'TaskStop') {
63    const id = str(input.task_id) || str(input.shell_id)
64    if (id) out.push({ kind: 'end', id, state: 'Z', why: 'killed' })
65  }
66  // Only the model's own GetTask calls reach a hook: the engine splices its deliveries into the messages.
67  if (tool === 'GetTask' && str(input.taskId)) {
68    const id = str(input.taskId)
69    const status = str(result.status)
70    const code = /Exited with code (\d+)/.exec(str(result.statusMessage))?.[1]
71    const failed = code !== undefined && code !== '0' ? `exit ${code}` : obj(result.result).isError === true ? 'failed' : ''
72    if (status === 'cancelled') out.push({ kind: 'end', id, state: 'Z', why: 'killed' })
73    else if (status === 'failed') out.push({ kind: 'end', id, state: 'Z', why: 'failed' })
74    else if (status === 'completed') out.push({ kind: 'end', id, state: failed ? 'Z' : 'X', why: failed })
75  }
76
77  if (isMain && tool === 'TodoWrite') out.push({ kind: 'todos', todos: todosFromWrite(input.todos) })
78  if (isMain && tool === 'TaskCreate') {
79    const task = obj(result.task)
80    if (str(task.id)) out.push({ kind: 'todo-created', id: str(task.id), subject: str(task.subject) || str(input.subject) })
81  }
82  if (isMain && tool === 'TaskUpdate' && str(input.taskId))
83    out.push({ kind: 'todo-updated', taskId: str(input.taskId), status: str(input.status), subject: str(input.subject), activeForm: str(input.activeForm) })
84  return out
85}
86
hooks/core/flow.ts 96 lines
1import type { FlowCols } from '../../types'
2
3/** Columns kept: a Raster is at most 512 columns wide, so no graph draws more. */
4export const FLOW_CAP = 512
5
6/** Characters per token before any response has ended to learn from. */
7const CPT_START = 3.6
8/** The fewest characters a token is taken to cover, so streamed text never explains more tokens than this allows. */
9const CPT_MIN = 1.5
10const CPT_MAX = 8
11
12/** Below this the eased rate counts as nothing, so a pause ends flat instead of on a sliver. */
13const FLOOR_TPS = 0.5
14
15/**
16 * Output tokens per graph column, every response of the session counted as it streams. `cols` are the
17 * closed columns, oldest first, each lasting its `ms`; `pending` fills the open one, number `seq`.
18 */
19export type Flow = FlowCols & { seq: number; pending: number; cpt: number }
20
21/** One response as it streams: the characters of its text, thinking and tool input, how many are credited, and to which columns. */
22export type Stream = { chars: number; counted: number; startSeq: number; credits: Map<number, number> }
23
24export const newFlow = ({ cols, ms }: FlowCols = { cols: [], ms: [] }): Flow => {
25  const n = Math.min(cols.length, ms.length, FLOW_CAP)
26  return { cols: cols.slice(cols.length - n), ms: ms.slice(ms.length - n), seq: n, pending: 0, cpt: CPT_START }
27}
28
29export const flowCols = (f: Flow): FlowCols => ({ cols: f.cols.slice(), ms: f.ms.slice() })
30
31export const newStream = (f: Flow): Stream => ({ chars: 0, counted: 0, startSeq: f.seq, credits: new Map() })
32
33const add = (f: Flow, seq: number, tokens: number) => {
34  if (seq === f.seq) f.pending = Math.max(0, f.pending + tokens)
35  else {
36    const i = f.cols.length - (f.seq - seq)
37    if (i >= 0) f.cols[i] = Math.max(0, (f.cols[i] ?? 0) + tokens)
38  }
39}
40
41/** Moves a stream's characters since the last call into the open column, as estimated tokens. */
42export const credit = (f: Flow, s: Stream) => {
43  const tokens = (s.chars - s.counted) / f.cpt
44  if (tokens <= 0) return
45  s.counted = s.chars
46  f.pending += tokens
47  s.credits.set(f.seq, (s.credits.get(f.seq) ?? 0) + tokens)
48}
49
50export const closeColumn = (f: Flow, ms: number) => {
51  f.cols.push(f.pending)
52  f.ms.push(ms)
53  f.pending = 0
54  f.seq += 1
55  if (f.cols.length > FLOW_CAP) {
56    f.cols.splice(0, f.cols.length - FLOW_CAP)
57    f.ms.splice(0, f.ms.length - FLOW_CAP)
58  }
59}
60
61/**
62 * A response ended with its true count. What its streamed characters were credited is scaled to the share
63 * they can explain, column by column, and the characters-per-token guess learns when they explain it all.
64 * The rest, output the engine never streamed such as hidden thinking, spreads evenly over the columns the
65 * response lasted.
66 */
67export const settle = (f: Flow, s: Stream, outputTokens: number | undefined) => {
68  credit(f, s)
69  if (!outputTokens || outputTokens <= 0) return
70  const estimated = [...s.credits.values()].reduce((a, b) => a + b, 0)
71  const shown = estimated > 0 ? Math.min(outputTokens, s.chars / CPT_MIN) : 0
72  if (shown > 0) {
73    for (const [seq, tokens] of s.credits) add(f, seq, tokens * (shown / estimated - 1))
74    if (shown === outputTokens) f.cpt = Math.min(CPT_MAX, Math.max(CPT_MIN, f.cpt * 0.8 + (s.chars / outputTokens) * 0.2))
75  }
76  const rest = outputTokens - shown
77  if (rest <= 0) return
78  const first = Math.max(s.startSeq, f.seq - f.cols.length)
79  const span = f.seq - first + 1
80  for (let q = first; q <= f.seq; q++) add(f, q, rest / span)
81}
82
83/**
84 * Tokens per second for the last `n` columns, each over its own length, oldest first, eased so a pause
85 * slopes down over a few columns instead of dropping out; null where the flow has no column yet.
86 */
87export const flowRates = (f: FlowCols, n: number): (number | null)[] => {
88  let eased = 0
89  const rates = f.cols.map((t, i) => {
90    eased = eased * 0.65 + ((t * 1000) / Math.max(1, f.ms[i] ?? 1)) * 0.35
91    return eased < FLOOR_TPS ? 0 : eased
92  })
93  const shown = rates.slice(-n)
94  return [...Array.from({ length: Math.max(0, n - shown.length) }, () => null), ...shown]
95}
96
hooks/core/fmt.ts 32 lines
1import { shorten } from './text'
2
3/** `0.4s`, `12s`, `3:07`, `1h05`. */
4export const fmtMs = (ms: number) => {
5  if (ms < 10_000) return `${(Math.max(0, ms) / 1000).toFixed(1)}s`
6  const s = Math.floor(ms / 1000)
7  if (s < 60) return `${s}s`
8  const m = Math.floor(s / 60)
9  return m < 60 ? `${m}:${String(s % 60).padStart(2, '0')}` : `${Math.floor(m / 60)}h${String(m % 60).padStart(2, '0')}`
10}
11
12/** A running clock as the elapsed client draws it: `0:42`, `12:05`, `1h05`. */
13export const fmtClock = (ms: number) => {
14  const s = Math.max(0, Math.floor(ms / 1000))
15  const m = Math.floor(s / 60)
16  return m < 60 ? `${m}:${String(s % 60).padStart(2, '0')}` : `${Math.floor(m / 60)}h${String(m % 60).padStart(2, '0')}`
17}
18
19/** Wall-clock `HH:MM` of an epoch time, in the environment's zone. */
20export const fmtWall = (ms: number) => (ms > 0 ? new Date(ms).toTimeString().slice(0, 5) : '--:--')
21
22export const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? '' : 's'}`
23
24/** `claude-opus-5-5[1m]` → `Opus 5.5`. */
25export const prettyModel = (id: string) => {
26  if (!id) return 'Claude'
27  const cap = (f: string) => f.charAt(0).toUpperCase() + f.slice(1)
28  const m = /claude-([a-z]+)-(\d+)(?:-(\d{1,2}))?(?:-\d{8})?(?!\d)/i.exec(id)
29  if (m?.[1] && m[2]) return `${cap(m[1].toLowerCase())} ${m[2]}${m[3] ? `.${m[3]}` : ''}`
30  return shorten(id, 18)
31}
32
hooks/core/glitch.ts 31 lines
1import { cellWidth, hash } from './text'
2
3/** How long a row glitches after it changes state, and how often the effect redraws. */
4export const GLITCH_MS = 1500
5export const FRAME_MS = 120
6
7const NOISE = ['▓', '▒', '░', '/', '\\', '|', '_', '#']
8
9export const isGlitching = (changedAt: number, now: number) => changedAt > 0 && now - changedAt < GLITCH_MS
10
11/**
12 * The text a few cells corrupted, seeded by `seed` and the frame so a test sees the same thing twice;
13 * the corruption thins out over the effect and the text comes back whole when it ends. Same width always.
14 */
15export const glitchText = (text: string, seed: string, changedAt: number, now: number) => {
16  if (!isGlitching(changedAt, now)) return text
17  const cps = [...text]
18  if (cps.length === 0) return text
19  const frame = Math.floor((now - changedAt) / FRAME_MS)
20  const left = 1 - (now - changedAt) / GLITCH_MS
21  const hits = Math.max(1, Math.round(Math.min(3, cps.length / 3) * left))
22  const h = hash(`${seed}:${frame}`)
23  for (let i = 0; i < hits; i++) {
24    const at = (h >>> (i * 5)) % cps.length
25    // Only one-cell glyphs are swapped, so the row keeps its width.
26    const ch = cps[at] ?? ' '
27    if (ch !== ' ' && cellWidth(ch.codePointAt(0) ?? 0) === 1) cps[at] = NOISE[(h >>> (i * 3 + 1)) % NOISE.length] ?? '▒'
28  }
29  return cps.join('')
30}
31
hooks/core/history.ts 144 lines
1import type { HistoryEntry } from '../../types'
2import { oneLine, redact } from './text'
3
4export const HISTORY_CAP = 1000
5export const PROMPT_CHARS = 160
6
7// When the transcript splits one message over several rows it replaces the uuid's
8// last group with the row index, so rows are matched on the first four groups.
9const UUID_HEAD = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-/i
10
11export const rowKey = (id: string) => (UUID_HEAD.test(id) ? id.slice(0, 24) : id)
12
13/** Remembers the id a transcript row was drawn under, preferring the message's first row. */
14export const keepRow = (drawn: Map<string, string>, requestId: string) => {
15  const key = rowKey(requestId)
16  const had = drawn.get(key)
17  if (had === undefined || (requestId.length === 36 && had.length !== 36)) drawn.set(key, requestId)
18}
19
20type Block = { type?: unknown; text?: unknown }
21
22/** The typed words of a prompt row: its first text block (hooks' context follows as further blocks). */
23export const promptText = (content: unknown): string => {
24  if (typeof content === 'string') return content
25  if (!Array.isArray(content)) return ''
26  const blocks = content as Block[]
27  const first = blocks.find(b => b.type === 'text' && typeof b.text === 'string' && b.text.trim() !== '')
28  if (first) return first.text as string
29  return blocks.some(b => b.type === 'image') ? '[image]' : ''
30}
31
32/** Every text block of a row, for finding a prompt inside the engine's framing of it. */
33export const allText = (content: unknown): string => {
34  if (typeof content === 'string') return content
35  if (!Array.isArray(content)) return ''
36  return (content as Block[])
37    .filter(b => b.type === 'text' && typeof b.text === 'string')
38    .map(b => b.text as string)
39    .join(' ')
40}
41
42/**
43 * The same list back when nothing is added, so the caller can skip the write. A prompt is taken
44 * when it is submitted, with no id yet; `attachUuid` gives it the row's id once the row is kept.
45 */
46export const pushPrompt = (
47  list: readonly HistoryEntry[],
48  p: { uuid: string; text: string; at: number },
49): readonly HistoryEntry[] => {
50  const text = oneLine(redact(p.text))
51  if (text === '' || (p.uuid !== '' && list.some(x => x.uuid === p.uuid))) return list
52  const n = (list.at(-1)?.n ?? 0) + 1
53  return [...list, { n, uuid: p.uuid, text: [...text].slice(0, PROMPT_CHARS).join(''), at: p.at }].slice(-HISTORY_CAP)
54}
55
56/** How a prompt is matched to its drawn row when it was read back without an id. */
57export const textKey = (text: string) => [...oneLine(redact(text))].slice(0, PROMPT_CHARS).join('')
58
59// How the engine hands the model a prompt typed mid-turn, often in the row of the next tool result.
60const MID_TURN = /The user sent (?:a new )?message while you were working:\s*([\s\S]*?)(?:\n\nThis is how Claude Code surfaces|\s*<\/system-reminder>)/g
61
62const midTurn = (text: string) => [...text.matchAll(MID_TURN)].map(m => m[1] ?? '')
63
64/** The prompts a row carries: the row itself as typed, or each one typed mid-turn inside its framing. */
65const sentIn = (r: MessageRow) => [...((r.toolResults?.length ?? 0) === 0 ? [r.text] : []), ...midTurn(r.text)]
66
67/** A kept prompt's full text, from the session's rows; null unless exactly one distinct text matches its cut copy. */
68export const originalOf = (rows: readonly MessageRow[], entry: HistoryEntry): string | null => {
69  const found = new Set(rows.filter(r => r.role === 'user').flatMap(sentIn).filter(t => textKey(t) === entry.text))
70  return found.size === 1 ? ([...found][0] ?? null) : null
71}
72
73/**
74 * Gives the newest prompt still waiting for an id the id of the row that carries it: the row as
75 * typed (`exact`), or, for one typed mid-turn, the engine's framing of it, which contains its text.
76 */
77export const attachUuid = (list: readonly HistoryEntry[], text: string, uuid: string, exact: boolean): readonly HistoryEntry[] => {
78  if (list.some(x => x.uuid === uuid)) return list
79  const key = exact ? textKey(text) : oneLine(redact(text))
80  for (let i = list.length - 1; i >= 0; i--) {
81    const x = list[i]
82    if (x && x.uuid === '' && x.text !== '' && (exact ? x.text === key : key.includes(x.text))) return list.map((y, j) => (j === i ? { ...y, uuid } : y))
83  }
84  return list
85}
86
87// What the engine writes as the user: its tags, an interruption, a compaction's summary.
88const ENGINE_TEXT =
89  /^\s*(?:<(?:task-notification|command-name|command-message|local-command-|system-reminder|bash-|user-memory-input)|\[Request interrupted by user|This session is being continued from a previous conversation|Caveat: The messages below were generated)/
90
91type MessageRow = { role: string; text: string; toolResults?: readonly unknown[] }
92
93/**
94 * The fallback for a transcript too large to read: the session's own messages carry no id or
95 * origin, so typed prompts are told apart by shape, and their rows are found by text when drawn.
96 */
97export const promptsFromMessages = (rows: readonly MessageRow[]): readonly HistoryEntry[] => {
98  let list: readonly HistoryEntry[] = []
99  for (const r of rows) {
100    if (r.role !== 'user') continue
101    const typed = (r.toolResults?.length ?? 0) === 0 && !ENGINE_TEXT.test(r.text) ? [r.text] : []
102    for (const text of [...typed, ...midTurn(r.text)]) {
103      if (!text.trim()) continue
104      const n = (list.at(-1)?.n ?? 0) + 1
105      list = [...list, { n, uuid: '', text: textKey(text), at: 0 }].slice(-HISTORY_CAP)
106    }
107  }
108  return list
109}
110
111type TranscriptRow = {
112  type?: unknown
113  uuid?: unknown
114  isSidechain?: unknown
115  isMeta?: unknown
116  origin?: { kind?: unknown }
117  timestamp?: unknown
118  message?: { content?: unknown }
119  attachment?: { type?: unknown; prompt?: unknown; origin?: { kind?: unknown } }
120}
121
122/** The typed prompts of a transcript file, for a resumed session: loads are not appends. */
123export const promptsFromTranscript = (jsonl: string): readonly HistoryEntry[] => {
124  let list: readonly HistoryEntry[] = []
125  for (const raw of jsonl.split('\n')) {
126    if (!raw.includes('"human"')) continue
127    let row: TranscriptRow
128    try {
129      row = JSON.parse(raw) as TranscriptRow
130    } catch {
131      continue
132    }
133    if (row.isSidechain === true || typeof row.uuid !== 'string') continue
134    // A prompt typed mid-turn is saved as the attachment that delivered it, never as a user row.
135    const queued = row.type === 'attachment' && row.attachment?.type === 'queued_command' && row.attachment.origin?.kind === 'human'
136    if (!queued && (row.type !== 'user' || row.isMeta === true || row.origin?.kind !== 'human')) continue
137    const text = promptText(queued ? row.attachment?.prompt : row.message?.content)
138    if (queued && text.trim().startsWith('/')) continue
139    const at = typeof row.timestamp === 'string' ? Date.parse(row.timestamp) : 0
140    list = pushPrompt(list, { uuid: row.uuid, text, at: Number.isNaN(at) ? 0 : at })
141  }
142  return list
143}
144
hooks/core/graph.ts 80 lines
1import { rgb } from './color'
2
3/** A Raster cell's color that leaves the terminal's own. */
4const DEFAULT = 0x01000000
5/** `▁` is one eighth of a cell; `█` the whole of it. */
6const LOWER_EIGHTH = 0x2581
7const FULL = 0x2588
8
9/** The span of time the graph shows, right edge now: its columns share it, one per tick. */
10export const WINDOW_MS = 60_000
11
12/** How long one column stands for, and so how often the graph scrolls by exactly one. */
13export const columnMs = (cols: number) => Math.round(WINDOW_MS / Math.max(1, cols))
14
15/**
16 * Columns as a filled area in eighths of a cell, scaled to the largest: any value above zero shows at
17 * least one eighth, an empty column stays the terminal's own. `color(fromTop, age)` paints a cell:
18 * `fromTop` 0 at the top row, `age` 0 at the newest column.
19 */
20export const areaCells = (values: readonly (number | null)[], rows: number, color: (fromTop: number, age: number) => string) => {
21  const cols = values.length
22  const out = new Uint32Array(cols * rows * 3)
23  const max = Math.max(1e-9, ...values.map(v => v ?? 0))
24  const eighths = rows * 8
25  for (let c = 0; c < cols; c++) {
26    const v = values[c] ?? 0
27    const h = v > 0 ? Math.max(1, Math.round((v / max) * eighths)) : 0
28    const age = 1 - c / Math.max(1, cols - 1)
29    for (let r = 0; r < rows; r++) {
30      const fill = Math.max(0, Math.min(8, h - (rows - 1 - r) * 8))
31      const i = (r * cols + c) * 3
32      if (fill === 0) out.set([0x20, DEFAULT, DEFAULT], i)
33      else out.set([fill === 8 ? FULL : LOWER_EIGHTH + fill - 1, rgb(color(r / Math.max(1, rows - 1), age)), DEFAULT], i)
34    }
35  }
36  return out
37}
38
39const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
40
41/** A Raster's `cells`: padded base64 of little-endian u32 triplets. */
42export const encodeCells = (cells: Uint32Array) => {
43  const bytes = new Uint8Array(cells.length * 4)
44  const view = new DataView(bytes.buffer)
45  cells.forEach((v, i) => view.setUint32(i * 4, v, true))
46  let s = ''
47  for (let i = 0; i < bytes.length; i += 3) {
48    const n = ((bytes[i] ?? 0) << 16) | ((bytes[i + 1] ?? 0) << 8) | (bytes[i + 2] ?? 0)
49    s += B64.charAt((n >> 18) & 63) + B64.charAt((n >> 12) & 63)
50    s += i + 1 < bytes.length ? B64.charAt((n >> 6) & 63) : '='
51    s += i + 2 < bytes.length ? B64.charAt(n & 63) : '='
52  }
53  return s
54}
55
56// Braille dots filled bottom-up, left column then right: levels 0-4 per column.
57const LEFT = [0, 0x40, 0x44, 0x46, 0x47]
58const RIGHT = [0, 0x80, 0xa0, 0xb0, 0xb8]
59
60/** The same area in braille, two values per cell, top row first: for surfaces without a Raster. */
61export const brailleRows = (values: readonly (number | null)[], rows: number) => {
62  const cols = Math.floor(values.length / 2)
63  const max = Math.max(1e-9, ...values.map(v => v ?? 0))
64  const level = (i: number) => {
65    const v = values[i] ?? 0
66    return v > 0 ? Math.max(1, Math.round((v / max) * rows * 4)) : 0
67  }
68  const out: string[] = []
69  for (let r = rows - 1; r >= 0; r--) {
70    let s = ''
71    for (let c = 0; c < cols; c++) {
72      const l = Math.max(0, Math.min(4, level(2 * c) - r * 4))
73      const rr = Math.max(0, Math.min(4, level(2 * c + 1) - r * 4))
74      s += String.fromCharCode(0x2800 + (LEFT[l] ?? 0) + (RIGHT[rr] ?? 0))
75    }
76    out.push(s)
77  }
78  return out
79}
80
hooks/core/layout.ts 121 lines
1// Every row count the pane draws is decided here, so the sections always add up to the room the pane
2// has. These constants describe the shapes the views draw; a test holds a drawn pane to `height`.
3
4import type { Collapsed } from '../../types'
5
6/** A section's header and the blank row under it. */
7export const HEAD = 2
8/** The blank row between sections. */
9export const GAP = 1
10/** The throughput graph's rows. */
11export const GRAPH_ROWS = 3
12/** The throughput graph and the blank row under it. */
13export const GRAPH_H = GRAPH_ROWS + 1
14/** The opened process without its body: task, numbers, a blank, two rows of its last words. A body adds a blank above it. */
15export const DETAIL_BASE = 5
16
17const MAX_PAST_ROWS = 12
18const MAX_ITEMS = 12
19const MAX_LIST_ROWS = 40
20const MAX_DETAIL_ROWS = 15
21const MAX_HIST_ROWS = 12
22
23export type LayoutInput = {
24  rows: number
25  /** `now`: rows of what runs right now, or the last turn's receipt; `past`: finished calls of the turn. */
26  main: { now: number; past: number; hasTodo: boolean; hasActive: boolean; hasGraph: boolean }
27  /** Each top-level process's height, in drawing order; the opened one's body rows; whether all are listed. */
28  procs: { items: readonly number[]; detail: number | null; isList: boolean } | null
29  history: number
30  /** Sections folded to their header: each takes that one row and gives the rest of its room away. */
31  collapsed?: Collapsed
32}
33
34export type Layout = {
35  pastRows: number
36  showGraph: boolean
37  showTodo: boolean
38  showFiles: boolean
39  procMode: 'none' | 'items' | 'list' | 'detail'
40  /** Top-level processes the short list shows. */
41  procItems: number
42  listRows: number
43  detailRows: number
44  histRows: number
45  /** What the pane takes with these counts; more than `rows` only when even the minimums don't fit. */
46  height: number
47}
48
49const sum = (xs: readonly number[]) => xs.reduce((a, b) => a + b, 0)
50
51/**
52 * Minimums first (what runs now, two processes, two prompts), then the room left goes to what reads
53 * best, in order: todo and files, a few finished calls, the graph, more history, the opened process,
54 * more processes, more calls, then everything else up to its cap.
55 */
56export const layout = (input: LayoutInput): Layout => {
57  const { main, procs, history } = input
58  const folded = input.collapsed ?? {}
59  const items = procs?.items ?? []
60  const l: Layout = {
61    pastRows: 0,
62    showGraph: false,
63    showTodo: false,
64    showFiles: false,
65    procMode: procs === null ? 'none' : procs.detail !== null ? 'detail' : procs.isList ? 'list' : 'items',
66    procItems: 0,
67    listRows: 0,
68    detailRows: procs?.detail != null ? Math.min(procs.detail, 1) : 0,
69    histRows: Math.min(history, 1),
70    height: 0,
71  }
72  // With no room for anything under it, main is its header alone.
73  const mainH = () => {
74    if (folded.main) return 1
75    // A blank parts the extras from the rows above them, when there are any.
76    const extras = l.showTodo || l.showFiles ? Number(main.now + l.pastRows > 0) + (l.showTodo ? 1 + Number(main.hasActive) : 0) + Number(l.showFiles) : 0
77    const body = main.now + l.pastRows + (l.showGraph ? GRAPH_H : 0) + extras
78    return body === 0 ? 1 : HEAD + body
79  }
80  const procsH = () => {
81    if (l.procMode === 'none') return 0
82    if (folded.procs) return GAP + 1
83    if (l.procMode === 'detail') return GAP + HEAD + DETAIL_BASE + (l.detailRows > 0 ? 1 + l.detailRows : 0)
84    // The full list ends on its way back; the short one on `+N more` when it hides some.
85    if (l.procMode === 'list') return GAP + HEAD + l.listRows + 1
86    return GAP + HEAD + sum(items.slice(0, l.procItems)) + (l.procItems < items.length ? 1 : 0)
87  }
88  const histH = () => (history === 0 ? 0 : folded.history ? GAP + 1 : GAP + HEAD + l.histRows)
89  const used = () => mainH() + procsH() + histH()
90  const fits = (change: () => void) => {
91    const before = { ...l }
92    change()
93    if (used() > input.rows) Object.assign(l, before)
94  }
95  const grow = (key: 'pastRows' | 'procItems' | 'listRows' | 'detailRows' | 'histRows', upTo: number) => {
96    for (let i = l[key]; i < upTo; i++) fits(() => (l[key] += 1))
97  }
98
99  if (l.procMode === 'items') grow('procItems', Math.min(items.length, 2))
100  if (l.procMode === 'list') grow('listRows', Math.min(items.length, 3))
101  grow('detailRows', Math.min(procs?.detail ?? 0, 3))
102  grow('histRows', Math.min(history, 2))
103  if (main.hasTodo) fits(() => (l.showTodo = true))
104  fits(() => (l.showFiles = true))
105  grow('pastRows', Math.min(main.past, 3))
106  if (main.hasGraph) fits(() => (l.showGraph = true))
107  grow('histRows', Math.min(history, 5))
108  grow('detailRows', Math.min(procs?.detail ?? 0, MAX_DETAIL_ROWS))
109  if (l.procMode === 'items') grow('procItems', Math.min(items.length, MAX_ITEMS))
110  if (l.procMode === 'list') grow('listRows', Math.min(items.length, MAX_LIST_ROWS))
111  grow('pastRows', Math.min(main.past, 6))
112  grow('pastRows', Math.min(main.past, MAX_PAST_ROWS))
113  grow('histRows', Math.min(history, MAX_HIST_ROWS))
114  // A folded section's counts cost nothing above, so they grew freely: nothing of them is drawn.
115  if (folded.main) Object.assign(l, { pastRows: 0, showGraph: false, showTodo: false, showFiles: false })
116  if (folded.procs) Object.assign(l, { procItems: 0, listRows: 0, detailRows: 0 })
117  if (folded.history) l.histRows = 0
118  l.height = used()
119  return l
120}
121
hooks/core/main.ts 149 lines
1import type { Activity, ActivityKind, LastTurn, Main, Todo, Todos, ToolRow, ToolState } from '../../types'
2import { oneLine, redact, shorten } from './text'
3
4export const TOOLS_CAP = 50
5export const TODOS_CAP = 60
6
7export const IDLE: Activity = { kind: 'idle', tool: '', target: '', since: 0 }
8
9export const DEFAULT_MAIN: Main = {
10  model: '',
11  isRunning: false,
12  turnStartedAt: 0,
13  activity: IDLE,
14  tools: [],
15  flow: { cols: [], ms: [] },
16  lastTurn: null,
17  turnId: '',
18}
19
20export const DEFAULT_TODOS: Todos = { items: [], active: '', activeId: '' }
21
22// ---------------------------------------------------------------- activity
23
24export const startTurn = (m: Main, now: number, turnId = ''): Main => ({
25  ...m,
26  isRunning: true,
27  turnStartedAt: now,
28  turnId,
29  tools: [],
30  activity: { ...IDLE, kind: 'requesting', since: now },
31})
32
33export const endTurn = (m: Main, now: number, t: { durationMs: number; reason: string }): Main => {
34  const lastTurn: LastTurn = {
35    durationMs: t.durationMs,
36    tools: m.tools.length,
37    errors: m.tools.filter(r => r.state === 'err').length,
38    reason: t.reason,
39    endedAt: now,
40  }
41  return { ...m, isRunning: false, turnId: '', activity: { ...IDLE, since: now }, lastTurn }
42}
43
44// Their run is the question itself. A permission prompt is not marked: nothing reports its answer before the call ends.
45export const ALWAYS_WAITS = new Set(['AskUserQuestion', 'ExitPlanMode'])
46
47/** A step's chunk kind as the activity it shows; undefined keeps the current one. */
48export const kindOfChunk = (kind: string): ActivityKind | undefined =>
49  kind === 'thinking' ? 'thinking' : kind === 'text' ? 'responding' : kind === 'tool' ? 'tool-input' : undefined
50
51export const setActivity = (m: Main, a: Omit<Activity, 'since'>, now: number): Main =>
52  m.activity.kind === a.kind && m.activity.tool === a.tool && m.activity.target === a.target
53    ? m
54    : { ...m, activity: { ...a, since: now } }
55
56// ---------------------------------------------------------------- tools
57
58const isObject = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null
59
60/** A path as its last two segments. */
61export const shortPath = (p: string) => oneLine(p).split(/[\\/]/).filter(Boolean).slice(-2).join('/')
62
63/** What a call is about, in one redacted line: its command, path, pattern, url or description. */
64export const targetOf = (tool: string, input: unknown): string => {
65  const i = isObject(input) ? input : {}
66  const str = (k: string) => (typeof i[k] === 'string' ? (i[k] as string) : '')
67  const path = str('file_path') || str('notebook_path') || str('path')
68  const raw =
69    tool === 'Bash' || tool === 'PowerShell'
70      ? str('command')
71      : tool === 'Grep' || tool === 'Glob'
72        ? str('pattern')
73        : tool === 'WebFetch'
74          ? str('url')
75          : tool === 'WebSearch' || tool === 'ToolSearch'
76            ? str('query')
77            : path
78              ? shortPath(path)
79              : str('description') || str('subject') || str('prompt') || str('skill') || str('query')
80  return shorten(redact(oneLine(raw)), 120)
81}
82
83/** The calls MAIN draws above the finished ones: those still running, while the turn is. */
84export const runningCalls = (m: Main) => (m.isRunning ? m.tools.filter(r => r.state === 'run') : [])
85
86export const startTool = (m: Main, row: Omit<ToolRow, 'state' | 'ms'>): Main => {
87  const tool = shorten(row.tool, 40)
88  return {
89    ...m,
90    tools: [...m.tools, { ...row, tool, state: 'run' as const, ms: null }].slice(-TOOLS_CAP),
91    activity: { kind: 'tool-use', tool, target: row.target, since: row.startedAt },
92  }
93}
94
95/** Calls run in parallel: the header follows the newest call still running, then waits for the model. */
96export const endTool = (m: Main, id: string, state: ToolState, now: number): Main => {
97  const tools = m.tools.map(r => (r.id === id ? { ...r, state, ms: now - r.startedAt } : r))
98  if (m.activity.kind !== 'tool-use') return { ...m, tools }
99  const running = tools.filter(r => r.state === 'run').at(-1)
100  const activity = running
101    ? { kind: 'tool-use' as const, tool: running.tool, target: running.target, since: running.startedAt }
102    : { ...IDLE, kind: 'requesting' as const, since: now }
103  return { ...m, tools, activity }
104}
105
106// ---------------------------------------------------------------- todos
107
108type TodoInput = { content?: unknown; status?: unknown; activeForm?: unknown }
109
110const asStatus = (s: unknown): Todo['status'] =>
111  s === 'in_progress' || s === 'completed' ? s : 'pending'
112
113/** TodoWrite replaces the whole list. */
114export const todosFromWrite = (todos: unknown): Todos => {
115  const list = Array.isArray(todos) ? (todos as TodoInput[]) : []
116  const items = list.slice(0, TODOS_CAP).map((t, i) => ({
117    id: String(i),
118    text: shorten(redact(String(t.content ?? '')), 120),
119    status: asStatus(t.status),
120  }))
121  const at = list.findIndex(t => t.status === 'in_progress')
122  const current = list[at]
123  const words = (v: unknown) => (typeof v === 'string' ? v : '')
124  return {
125    items,
126    active: current ? shorten(redact(words(current.activeForm) || words(current.content)), 120) : '',
127    activeId: current ? String(at) : '',
128  }
129}
130
131export const todoCreated = (t: Todos, task: { id: string; subject: string }): Todos =>
132  t.items.some(x => x.id === task.id)
133    ? t
134    : { ...t, items: [...t.items, { id: task.id, text: shorten(redact(task.subject), 120), status: 'pending' as const }].slice(-TODOS_CAP) }
135
136export const todoUpdated = (t: Todos, u: { taskId: string; status?: string; subject?: string; activeForm?: string }): Todos => {
137  if (u.status === 'deleted')
138    return t.activeId === u.taskId ? { items: t.items.filter(x => x.id !== u.taskId), active: '', activeId: '' } : { ...t, items: t.items.filter(x => x.id !== u.taskId) }
139  const items = t.items.map(x =>
140    x.id === u.taskId
141      ? { ...x, status: u.status ? asStatus(u.status) : x.status, text: u.subject ? shorten(redact(u.subject), 120) : x.text }
142      : x,
143  )
144  const item = items.find(x => x.id === u.taskId)
145  if (u.status === 'in_progress') return { items, active: shorten(redact(u.activeForm || item?.text || ''), 120), activeId: u.taskId }
146  if (u.status === 'completed' && t.activeId === u.taskId) return { items, active: '', activeId: '' }
147  return { ...t, items }
148}
149
hooks/core/files.ts 95 lines
1import type { FileMarks } from '../../types'
2import { hash, oneLine } from './text'
3
4export const READ = 1
5export const EDITED = 2
6export const CREATED = 4
7export const DELETED = 8
8
9// Distinct files are counted by remembering each; past this many, new ones are no longer counted.
10export const FILES_CAP = 5000
11
12export const READ_TOOLS = new Set(['Read'])
13export const EDIT_TOOLS = new Set(['Edit', 'Write', 'NotebookEdit', 'MultiEdit'])
14
15/** Where the files a session's tools act on are found: its working directory, and Claude's own folders. */
16export type Place = { cwd: string; home: string; roots: readonly string[] }
17
18const isAbsolute = (p: string) => p.startsWith('/') || /^[a-zA-Z]:\//.test(p)
19
20/** A path made absolute and plain: forward slashes, no `.` or `..`, and one case on Windows, whose paths ignore it. */
21export const normalPath = (raw: string, place: Pick<Place, 'cwd' | 'home'>) => {
22  let p = oneLine(raw).replace(/\\/g, '/')
23  if (p === '~' || p.startsWith('~/')) p = place.home.replace(/\\/g, '/') + p.slice(1)
24  if (!isAbsolute(p)) p = `${place.cwd.replace(/\\/g, '/')}/${p}`
25  const parts: string[] = []
26  for (const s of p.split('/')) {
27    if (s === '..') parts.pop()
28    else if (s !== '.' && (s !== '' || parts.length === 0)) parts.push(s)
29  }
30  const out = parts.join('/')
31  return /^[a-zA-Z]:\//.test(out) ? out.toLowerCase() : out
32}
33
34/** Claude's own folders: its config directory, and the temporary one that holds scratchpads and task output. */
35export const internalRoots = (env: Record<string, string | undefined>) => {
36  const home = env.HOME || env.USERPROFILE || ''
37  const temp = env.TMPDIR || env.TEMP || env.TMP || ''
38  const place = { cwd: '/', home }
39  return [env.CLAUDE_CONFIG_DIR || (home && `${home}/.claude`), temp && `${temp}/claude`, '/tmp/claude']
40    .filter((r): r is string => !!r)
41    .map(r => normalPath(r, place))
42}
43
44export const isInternal = (normal: string, roots: readonly string[]) => roots.some(r => normal === r || normal.startsWith(`${r}/`))
45
46/** A file's key: a hash of its whole path, so each is counted once and no path is kept. */
47export const keyOf = (normal: string) => hash(normal).toString(36)
48
49export const markFile = (marks: FileMarks, key: string, mark: number): FileMarks => {
50  const had = marks[key] ?? 0
51  if ((had & mark) === mark || (had === 0 && Object.keys(marks).length >= FILES_CAP)) return marks
52  return { ...marks, [key]: had | mark }
53}
54
55/** A file the session created is counted as created, not edited, whatever was done to it after. */
56export const countFiles = (marks: FileMarks) => {
57  const c = { read: 0, edited: 0, created: 0, deleted: 0 }
58  for (const m of Object.values(marks)) {
59    if (m & READ) c.read++
60    if (m & CREATED) c.created++
61    else if (m & EDITED) c.edited++
62    if (m & DELETED) c.deleted++
63  }
64  return c
65}
66
67const BASH_DELETE = new Set(['rm', 'unlink'])
68const PWSH_DELETE = new Set(['remove-item', 'rm', 'del', 'erase', 'ri'])
69// PowerShell parameters whose value is a pattern, not a path.
70const PWSH_VALUED = /^-(filter|include|exclude)$/i
71
72const words = (segment: string) => [...segment.matchAll(/"([^"]*)"|'([^']*)'|(\S+)/g)].map(m => m[1] ?? m[2] ?? m[3] ?? '')
73
74/**
75 * The paths a shell command names for deletion, read from its words: no tool reports a deletion.
76 * A glob or a folder counts as one path; a `git rm --cached` deletes nothing on disk.
77 */
78export const deletedPaths = (command: string, isPowerShell: boolean): string[] => {
79  const out: string[] = []
80  for (const segment of command.split(/&&|\|\||[;|\n]/)) {
81    let w = words(segment.trim())
82    while (w[0] !== undefined && (w[0] === 'sudo' || /^\w+=/.test(w[0]))) w = w.slice(1)
83    const head = (w[0] ?? '').toLowerCase()
84    const isGitRm = head === 'git' && w[1] === 'rm'
85    if (isGitRm ? w.includes('--cached') : !(isPowerShell ? PWSH_DELETE : BASH_DELETE).has(head)) continue
86    const args = w.slice(isGitRm ? 2 : 1)
87    for (let i = 0; i < args.length; i++) {
88      const a = args[i] ?? ''
89      if (isPowerShell && PWSH_VALUED.test(a)) i++
90      else if (a !== '' && !a.startsWith('-') && !/[<>&]/.test(a)) out.push(a)
91    }
92  }
93  return out
94}
95
hooks/core/procs.ts 258 lines
1import type { Proc, ProcKind, ProcState, Timeline, ToolRow, ToolState } from '../../types'
2import { oneLine, redact, shorten } from './text'
3
4export const PROCS_CAP = 80
5export const CALLS_CAP = 40
6export const TEXT_CAP = 300
7/** A live workflow's agents the short list shows under it; the rest fold into one line. */
8export const KIDS_SHOWN = 3
9
10export const isLive = (p: Proc) => p.state === 'R' || p.state === 'S'
11
12/** `voltagent-qa-sec:code-reviewer` → `code-reviewer`. */
13export const shortType = (t: string) => t.split(':').pop() || t
14
15export const newProc = (p: {
16  id: string
17  kind: ProcKind
18  type: string
19  task: string
20  now: number
21  taskId?: string
22  parent?: string
23  endsWithParent?: boolean
24  isBackground?: boolean
25}): Proc => ({
26  id: p.id,
27  taskId: p.taskId ?? p.id,
28  isBackground: p.isBackground,
29  kind: p.kind,
30  parent: p.parent ?? '',
31  type: shorten(p.type, 40),
32  task: shorten(redact(oneLine(p.task)), 160),
33  state: 'R',
34  why: '',
35  startedAt: p.now,
36  endedAt: null,
37  changedAt: p.now,
38  tokOut: 0,
39  ctx: 0,
40  steps: 0,
41  lastText: '',
42  endsWithParent: p.endsWithParent ?? false,
43})
44
45/** Adds or refreshes a process; past the cap the oldest finished ones go first, then the oldest live ones. */
46export const addProc = (list: readonly Proc[], p: Proc): readonly Proc[] => {
47  const had = list.find(x => x.id === p.id)
48  const merged = had ? list.map(x => (x.id === p.id ? { ...p, startedAt: x.startedAt } : x)) : [...list, p]
49  const over = merged.length - PROCS_CAP
50  if (over <= 0) return merged
51  const oldest = merged
52    .filter(x => x.id !== p.id)
53    .sort((a, b) => Number(isLive(a)) - Number(isLive(b)) || (a.endedAt ?? a.startedAt) - (b.endedAt ?? b.startedAt))
54  const gone = new Set(oldest.slice(0, over).map(x => x.id))
55  return merged.filter(x => !gone.has(x.id))
56}
57
58const edit = (list: readonly Proc[], id: string, change: (p: Proc) => Proc): readonly Proc[] => {
59  const p = list.find(x => x.id === id || x.taskId === id)
60  if (!p) return list
61  const next = change(p)
62  return next === p ? list : list.map(x => (x === p ? next : x))
63}
64
65export const setState = (list: readonly Proc[], id: string, state: ProcState, why: string, now: number): readonly Proc[] =>
66  edit(list, id, p =>
67    p.state === state && p.why === why
68      ? p
69      : { ...p, state, why, changedAt: now, endedAt: state === 'X' || state === 'Z' ? (p.endedAt ?? now) : null },
70  )
71
72/** Ends a process that still runs; one that has ended keeps the reason it ended with. */
73export const endLive = (list: readonly Proc[], id: string, state: ProcState, why: string, now: number): readonly Proc[] => {
74  const p = list.find(x => x.id === id || x.taskId === id)
75  return p && isLive(p) ? setState(list, id, state, why, now) : list
76}
77
78type StepUsage = { input_tokens: number; output_tokens: number; cache_read_input_tokens: number; cache_creation_input_tokens: number }
79
80/** One model request of an agent: its tokens, its words, and it is running again. */
81export const applyStep = (
82  list: readonly Proc[],
83  id: string,
84  s: { usage: StepUsage | null; answer: string; now: number },
85): readonly Proc[] =>
86  edit(list, id, p => ({
87    ...p,
88    state: 'R',
89    why: '',
90    endedAt: null,
91    changedAt: p.state === 'R' ? p.changedAt : s.now,
92    steps: p.steps + 1,
93    tokOut: p.tokOut + (s.usage?.output_tokens ?? 0),
94    ctx: s.usage ? s.usage.input_tokens + s.usage.cache_read_input_tokens + s.usage.cache_creation_input_tokens : p.ctx,
95    lastText: s.answer.trim() ? shorten(redact(oneLine(s.answer)), TEXT_CAP) : p.lastText,
96  }))
97
98/** The background commands an agent's final answer ends: no notification follows them. */
99export const endChildren = (list: readonly Proc[], parent: string, now: number): readonly Proc[] =>
100  list.filter(p => p.parent === parent && p.endsWithParent && isLive(p)).reduce((acc, p) => setState(acc, p.id, 'X', '', now), list)
101
102// ---------------------------------------------------------------- timelines
103
104/** Calls made in all; a value kept before the count existed has only its calls. */
105export const totalOf = (t: Timeline | undefined) => t?.total ?? t?.calls.length ?? 0
106
107export const startCall = (t: Timeline | undefined, row: Omit<ToolRow, 'state' | 'ms'>): Timeline => ({
108  calls: [...(t?.calls ?? []), { ...row, tool: shorten(row.tool, 40), state: 'run' as const, ms: null }].slice(-CALLS_CAP),
109  total: totalOf(t) + 1,
110})
111
112export const endCall = (t: Timeline | undefined, callId: string, state: ToolState, now: number): Timeline => ({
113  calls: (t?.calls ?? []).map(c => (c.id === callId ? { ...c, state, ms: now - c.startedAt } : c)),
114  total: totalOf(t),
115})
116
117type Summary = { toolUses: readonly { tool_use_id: string; tool: string; input: unknown }[]; toolResults?: readonly { tool_use_id: string; isError: boolean }[] }
118
119/**
120 * Calls read back from an agent's conversation, for one that ran before the mod loaded: each one
121 * settled by its result, still running while the agent is, cut off when it ended without one.
122 */
123export const callsFromMessages = (rows: readonly Summary[], isAgentLive: boolean, targetOf: (tool: string, input: unknown) => string): ToolRow[] => {
124  const results = new Map<string, boolean>()
125  for (const r of rows) for (const x of r.toolResults ?? []) results.set(x.tool_use_id, x.isError)
126  return rows
127    .flatMap(r => r.toolUses)
128    .map(u => {
129      const isError = results.get(u.tool_use_id)
130      const state: ToolState = isError === undefined ? (isAgentLive ? 'run' : 'err') : isError ? 'err' : 'ok'
131      return { id: u.tool_use_id, tool: shorten(u.tool, 40), target: targetOf(u.tool, u.input), state, startedAt: 0, ms: null }
132    })
133}
134
135/** The calls read back, under the ones seen live (which know their times), and the count of both. */
136export const withBackfill = (t: Timeline | undefined, back: readonly ToolRow[]): Timeline => {
137  const seen = t?.calls ?? []
138  const seenIds = new Set(seen.map(c => c.id))
139  const backIds = new Set(back.map(c => c.id))
140  const total = back.length + seen.filter(c => !backIds.has(c.id)).length
141  return { calls: [...back.filter(c => !seenIds.has(c.id)), ...seen].slice(-CALLS_CAP), total: Math.max(total, totalOf(t)) }
142}
143
144// ---------------------------------------------------------------- endings
145
146export type Ending = { taskId: string; state: ProcState; why: string }
147
148const tag = (text: string, name: string) => new RegExp(`<${name}>([\\s\\S]*?)</${name}>`).exec(text)?.[1]?.trim()
149
150/**
151 * A background task's notification, as the transcript holds it:
152 * `<task-id>…</task-id> … <status>completed|failed|killed</status> <summary>… (exit code N)</summary>`.
153 * A Monitor's output lines arrive the same way with no status: those end nothing.
154 */
155export const endingOf = (text: string): Ending | null => {
156  if (!text.includes('<task-notification>')) return null
157  const taskId = tag(text, 'task-id')
158  const status = tag(text, 'status')
159  if (!taskId || !status) return null
160  const code = /exit code (\d+)/.exec(tag(text, 'summary') ?? '')?.[1]
161  if (status === 'completed') return code && code !== '0' ? { taskId, state: 'Z', why: `exit ${code}` } : { taskId, state: 'X', why: '' }
162  if (status === 'killed' || status === 'stopped') return { taskId, state: 'Z', why: 'killed' }
163  if (status === 'failed') return { taskId, state: 'Z', why: code ? `exit ${code}` : 'failed' }
164  return null
165}
166
167/** `$.agent.list()`'s status as a process state; undefined leaves the process as it is. */
168export const stateOfStatus = (status: string): ProcState | undefined =>
169  status === 'running'
170    ? 'R'
171    : status === 'pending' || status === 'waiting' || status === 'idle'
172      ? 'S'
173      : status === 'completed'
174        ? 'X'
175        : status === 'failed' || status === 'killed'
176          ? 'Z'
177          : undefined
178
179type Listed = { id: string; status: string; type: string; description: string; parentId?: string }
180
181/**
182 * `$.agent.list()` folded in: an agent not seen yet is added while it runs, a known one follows its
183 * status. The list is read before it is applied, so it never brings back an agent that ended meanwhile;
184 * one that works again says so with its next step.
185 */
186export const applyList = (list: readonly Proc[], agents: readonly Listed[], now: number): readonly Proc[] => {
187  let acc = list
188  for (const a of agents) {
189    const state = stateOfStatus(a.status)
190    if (!state) continue
191    const known = acc.find(p => p.id === a.id)
192    if (known) {
193      const isRevival = !isLive(known) && (state === 'R' || state === 'S')
194      if (known.kind === 'agent' && known.state !== state && !isRevival) acc = setState(acc, a.id, state, state === 'Z' ? a.status : known.why, now)
195    } else if (state === 'R' || state === 'S')
196      acc = addProc(acc, { ...newProc({ id: a.id, kind: 'agent', type: shortType(a.type), task: a.description, now, parent: a.parentId }), state })
197  }
198  return acc
199}
200
201/**
202 * At a turn's stop the engine lists the background work still in flight, its agents' commands
203 * included: live work missing there has ended, even when its notification reached no hook. A nested
204 * agent is left alone, since a foreground one is never listed; a workflow's agents end with their run.
205 */
206export const endMissing = (list: readonly Proc[], inFlight: ReadonlySet<string>, now: number): readonly Proc[] => {
207  const isListed = (p: Proc) => p.kind === 'shell' || p.kind === 'monitor' || p.kind === 'workflow' || (p.kind === 'agent' && p.parent === '')
208  const gone = list.filter(p => isLive(p) && isListed(p) && !inFlight.has(p.id) && !inFlight.has(p.taskId))
209  return gone.reduce((acc, p) => setState(acc, p.id, 'X', '', now), list)
210}
211
212export const turnEnding = (reason: string): { state: ProcState; why: string } =>
213  reason === 'answer' ? { state: 'X', why: '' } : reason === 'aborted' ? { state: 'Z', why: 'stopped' } : { state: 'Z', why: reason }
214
215// ---------------------------------------------------------------- display
216
217/** Live ones by start (so rows don't move), then the newest endings. */
218const ordered = (list: readonly Proc[]): Proc[] => {
219  const live = list.filter(isLive).sort((a, b) => a.startedAt - b.startedAt)
220  const done = list.filter(p => !isLive(p)).sort((a, b) => (b.endedAt ?? 0) - (a.endedAt ?? 0))
221  return [...live, ...done]
222}
223
224/** Top-level processes in drawing order; a workflow's agents stay inside their workflow. */
225export const topLevel = (list: readonly Proc[]): Proc[] => ordered(list.filter(p => p.kind !== 'wfagent'))
226
227export const childrenOf = (list: readonly Proc[], id: string) => ordered(list.filter(p => p.parent === id))
228
229/** The agents a live workflow shows under it in the short list, and how many fold into `+N more`. */
230export const shownKids = (list: readonly Proc[], id: string) => {
231  const kids = childrenOf(list, id)
232  return { shown: kids.slice(0, KIDS_SHOWN), hidden: Math.max(0, kids.length - KIDS_SHOWN) }
233}
234
235/** Rows a top-level process takes: a live agent adds a line when it has something to say, a live workflow its agents. */
236export const itemHeight = (p: Proc, list: readonly Proc[], hasSecondLine: boolean) => {
237  if (!isLive(p)) return 1
238  if (p.kind === 'workflow') {
239    const k = shownKids(list, p.id)
240    return 1 + k.shown.length + (k.hidden > 0 ? 1 : 0)
241  }
242  return p.kind === 'agent' && hasSecondLine ? 2 : 1
243}
244
245/** How many rows the opened process's body has: its calls, or a workflow's agents. */
246export const detailItems = (p: Proc, list: readonly Proc[], calls: readonly ToolRow[]) =>
247  p.kind === 'workflow' ? childrenOf(list, p.id).length : calls.length
248
249/** `840`, `8.1k`, `31k`, `1.2M`. */
250export const kTokens = (n: number) =>
251  n >= 1_000_000
252    ? `${(n / 1_000_000).toFixed(1)}M`
253    : n >= 10_000
254      ? `${Math.round(n / 1000)}k`
255      : n >= 1000
256        ? `${(n / 1000).toFixed(1).replace(/\.0$/, '')}k`
257        : String(n)
258
hooks/palette.ts 30 lines
1import { mix } from './core/color'
2
3/** Neutrals for everything finished, one ice accent for what is alive, red for what failed. */
4export const C = {
5  hi: '#ECEAF4',
6  body: '#C6C3D3',
7  muted: '#9C99AD',
8  dim: '#7C798E',
9  faint: '#34333F',
10  accent: '#5CE1FF',
11  err: '#FF5C7A',
12  // The terminal's own background cannot be read: this sits just above the usual dark ones.
13  hover: '#2E2D3A',
14}
15
16export type Palette = typeof C
17
18const BREATH_STEPS = 16
19export const BREATH_MS = 150
20
21/** One breath of the live bar, full accent down toward the rule color and back. */
22export const BREATH = Array.from({ length: BREATH_STEPS }, (_, i) => mix(C.accent, C.faint, 0.3 * (1 - Math.cos((i / BREATH_STEPS) * 2 * Math.PI))))
23
24/**
25 * A graph pixel: brightest on the top edge and at the newest column, never past the rule color, so the
26 * oldest pixels never read as a dark patch on a lighter background. Gray once nothing runs.
27 */
28export const graphColor = (isLive: boolean) => (fromTop: number, age: number) =>
29  mix(isLive ? C.accent : C.dim, C.faint, Math.min(0.85, 0.08 + fromTop * 0.6 + 0.45 * age ** 1.5))
30