SLOPSHOPPER

plain-view

A quiet transcript: tool rows step aside and the agent's plan shows as a card above the prompt, with the current step, progress bars and a summary when the…

panebandspinnerrowsguardcommand
★ 11v0.1.9MITupdated 2026-10-17ice-lfernandes/claude-code-mods/plain-view
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · plain-view
│ ┃ plain-view ✕ › fix the failing auth test and add an audit log call │ ┃ ✻ plain-view · settings │ ┃ Applies to every session. Saved in /config ⏺ Read(src/auth.ts) │ ┃ → plain-view. ⎿ Read 6 lines │ ┃ ⏺ Update(src/auth.ts) │ ┃ ▸ Transcript · Card · General ⎿ Added 2 lines, removed 1 line │ ┃ ⏺ Bash(bun test) │ ┃ On ⎿ 3 pass, 1 fail │ ┃ ○ yes Hides tool rows; the plan shows │ ┃ above the prompt. ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ ● no The usual transcript. The other │ ┃ apply once it is on. ✻ Worked for 42s · done 4:20 PM │ ┃ │ ┃ The agent's words › /plain-view │ ┃ ● final Hides what the agent writes bef │ ┃ tools. The final answer stays. │ ┃ ○ none Hides all the agent's words. On │ ┃ stays. │ ┃ ○ card Hides the words. The answer's f │ ┃ sentence goes to the card. │ ┃ ○ all Shows all the agent's words. │ ┃ │ ┃ Ask for a task list │ ┃ ● yes One line in the system prompt a │ ┃ task list. Costs a few tokens p │ ┃ ○ no The card reads only the list th ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · plain-view
✻ plain-view · settings Applies to every session. Saved in /config → plain-view. ▸ Transcript · Card · General On ○ yes Hides tool rows; the plan shows in a card above prompt. ● no The usual transcript. The other options apply o on. The agent's words ● final Hides what the agent writes before calling tool final answer stays. (default) ○ none Hides all the agent's words. Only the card stay ○ card Hides the words. The answer's first sentence go card. ○ all Shows all the agent's words. Ask for a task list ● yes One line in the system prompt asks for a task l a few tokens per request. ○ no The card reads only the list the model keeps on /plain-view on · off · demo · help [ defaults ] [ close ]
README

plain-view

A quiet transcript. The tool rows step aside, and the agent's plan shows as a card above the prompt: the current step, a bar for the request and one for each task, and a summary when the turn ends.

plain-view: the card while the agent works, when the turn ends, a request of several lines, waiting for an agent, and the palettes

Five short scenarios, each drawn by the mod itself (scripts/screenshots/plain-view-demos.sh):

A task list (mp4)

plain-view: a task list

No task tool: a checklist in the answer (mp4)

plain-view: no task tool: a checklist in the answer

Esc interrupts the turn (mp4)

plain-view: esc interrupts the turn

A background agent (mp4)

plain-view: a background agent

A request of several lines (mp4)

plain-view: a request of several lines

  • Off until you turn it on: /plain-view on, the enabled option in /config, or the switch in launchpad's panel (◆ pad). The hint line under the prompt ends in plain view while it is on.
  • Tool rows: a call that worked draws nothing, its result neither, and a folded run of reads and searches neither. A failed or interrupted call draws in full, as Claude Code draws it; in a folded run, the run unfolds and only that call shows. The permission dialog, the agent's questions (AskUserQuestion), its plan (ExitPlanMode) and its helpers (Agent) are never touched.
  • The agent's words (agentText), while the mod is on:
ValueWhat the transcript keeps
final (A, default)The final answer. A message the agent writes before calling tools (a checklist, Checking:) steps aside once that step ends, so it can show for a moment; a message the mod knows nothing about (an earlier session) stays
none (B)No message of the agent: your requests and the card
card (C)No message; the end card carries the answer's first sentence (Answer: …) until the next request
all (D)Every message, as Claude Code draws it

A hidden message stays in the session: ctrl+o shows it, and all or /plain-view off draw it again. Failures, permission dialogs and the agent's questions show in every value.

The agent's thinking is not one of its messages: Claude Code draws it with no hook a mod can reach, so no value hides it. To hide it, set "showThinkingSummaries": false in ~/.claude/settings.json; that hides it everywhere, ctrl+o included, until you set it back.

  • The card, above the prompt:
  • the request's first line, and the time since it was sent. A request of several lines adds +5 lines and a show request button that unfolds it on the card until the next request; the request option shows the lines joined, from the first line of prose (auto), or up to 10 of them (all). A pasted code block shows as one line, ⟨code · 4 lines⟩;
  • Step 2 of 4 with a bar for the whole request and its percentage;
  • one row per task of the agent's list (TaskCreate/TaskUpdate or TodoWrite) with its own bar: Done, ~40% on the current step and what it is doing (reading weather.ts, a shell command's own description, using the artifact-design skill), Next, Up next. A list longer than 6 shows the 5 tasks around the current one, with a count of the rest;
  • with no task tool, the last checklist the agent writes in its answer (1. [ ] Read the API, - [x] Build the page) is the list, read as soon as the text before the step's first tool call is whole, so that call counts toward the step the checklist opens. A shorter checklist that names some of its tasks (the two steps it just finished) ticks them off and keeps the rest; one that shares no task is a new plan. A checklist the answer quotes (in a code block, fenced or indented, or a > quote) is not read as the plan. A checklist left open does not carry into the next request: it comes back, with the calls it counted, only when an answer there writes one of its tasks again, and is gone when that request ends without it. A task tool's list stays until every task is done;
  • before the agent writes a list: Understand your request and Plan the steps; with no list at all, the tool in flight;
  • the agents (subagents) the main turn starts, in one row: ◇ 1 agent running · code-review · 3m 12s (the latest one's name, the time since the oldest running one started), then ◇ 1 agent finished · code-review once they end. Only the count, the name and the time: tokens and cost are agent-watch's. With agent-watch installed, the row ends in /watch, which opens its pane. An agent that another agent starts does not count, nor a workflow's.
  • Waiting for an agent: when the main turn ends with an agent still running in the background and no task list, the card stays: ◐ Waiting for 1 agent with a moving bar, and the agents row. With a task list, the plan card shows its end and keeps the agents row. The shine runs until the last agent ends.
  • Ask for a list (askForTasks, on by default): the agent does not always keep a task list; in a live test it wrote its plan as a checklist in its answer. While the mod is on, one line in the system prompt asks it to keep one with TodoWrite or TaskCreate for work of more than two steps, or, when the session has neither tool, to write a Markdown checklist (- [ ] step) in its reply and, each time a step finishes and before the next step's first tool call, write - [x] <that step> (one line is enough) or the whole checklist again, a line the agent should keep even under a terse output style. That costs a few tokens per request, and the model may not always follow it: when a text list has not moved for far longer than its steps usually take, the card says so (see A list that stops moving) and the mod adds a short reminder to the next tool results. Turn it off in /config; the card then reads the list the agent keeps on its own, or its checklist.
  • A list that stops moving: a checklist read from the agent's text moves only when the agent writes it again. When the current step has made more than three times the calls of the finished steps (12 before any is done), the card stops guessing: the step's row reads list not updated for 14 calls instead of ~95%, list not updated sits next to the figure, and the request's bar counts only the finished steps. One line, - [x] Build the page, is enough to tick a task of an open text list and bring the card back; a lone line that names no task of the list is ignored. The steps that went stale stay out of the average. A task tool's list is never called stale: it is the agent's own marking. With askForTasks on, the mod also adds one reminder (plain-view: your checklist has not changed for 13 tool calls. ...) to the result of the call that crosses the limit, then every ten calls, three times at most per step. The model reads it; you do not see it, and the tool's result is unchanged.
  • The estimate: the current step's percentage compares its tool calls with the average of the steps already done (4 calls before any), and stops at 95% until the task is marked done. It is a guess, hence the ~. The request's bar counts done steps plus that estimate.
  • When the turn ends: the card turns green, ✓ All done, took 1m 47s, 100%, and a line with the files changed and read (changed 2 files · read 3 files). Changed counts edits made with shell commands too, read from the command without running it (sed -i, perl -pi, tee, > file); what a script or python -c writes is not counted. On Esc it turns grey, ■ Interrupted, with the step it left. A turn with no task list that called tools or agents ends in a small card: ✓ Done, the request, took 7m 34s, and a line with the files and the agents (changed 6 files · read 3 files · 1 agent); grey on Esc (■ Interrupted, stopped at 52s) or on an error. Under agentText: card it carries the answer too. A plain conversation (no tool, no agent) leaves no card. The next request starts a fresh card, keeps the agents still running and drops the finished ones; the engine's [-] folds it.
/plain-view                   the settings pane (also /plain-view config)
/plain-view on | off          show or hide the card and the tool rows
/plain-view demo              a sample plan in the card for 12 seconds, even when off
/plain-view palette           the 8 bar palettes with a sample, and a button to switch
/plain-view palette aurora    switch to one by name
/plain-view help              list the commands, with a button for each

Settings pane

/plain-view opens a pane, a tab like those of /limits and /watch, with the eight options in three tabs: Transcript (enabled, agentText, askForTasks), Card (request, palette with a sample of each, animation, and a preview of the card) and General (language, icons). Each value is a button with a line on what it does; a press saves it as /config would and the pane says ✓ Saved. An option your organization sets (managed settings) shows its value and why it does not change. defaults asks first, then puts the others back to their defaults. In launchpad's panel, the plain-view button opens this pane.

Bar colors

The bars and the request's title are a gradient of the palette option's colors. While the agent works a bright cell runs along each bar; the percentages take the color of the bar's end. Each palette has a dark and a light set: the light one when your theme's name says light, the dark one otherwise. To change it, run /plain-view palette and press use, run /plain-view palette <name>, or set palette in /config.

PaletteWorkingDone
claude (default)terracotta → amber → creamolive green
cleanorange → pink → violetgreen
sunsetyellow → orange → redgreen
aurorateal → blue → violetteal
oceancyan → blue → indigosea green
neonhot pink → purple → cyanneon green
forestdeep green → leaf → limegreen
calmgrey → text, no strong colorgreen

On the terminal each bar is a grid of colored cells. A terminal without truecolor rounds the colors to its 256, so the gradient shows in bands. On the desktop app the bars are plain, in the theme's colors. animation: off keeps the bars still, in the theme's colors, with no gradient.

Settings

Set them in /config, or under pluginConfigs in settings.json.

OptionDefaultWhat it does
enabledfalseHide the tool rows that worked and show the card
requestlineHow much of a request of several lines the card's title shows: line (the first line and +5 lines), joined (all lines in one, cut at the card's width), auto (the first line of prose; list items such as 1. yes go into the count), all (up to 10 lines under the title, then +N lines). The card's show request button unfolds the request, 10 lines at most
paletteclaudeThe bar colors: claude, clean, sunset, aurora, ocean, neon, forest, calm
animationtrueThe shine on the bars and the gradient. Off: still bars in theme colors
agentTextfinalWhat stays of the agent's messages: final (the final answer), none, card (the answer's first sentence in the end card), all
askForTaskstrueOne line in the system prompt asks the model to keep a task list for work of more than two steps (TodoWrite or TaskCreate), or a checklist in its reply when the session has neither tool. Off: no change to the prompt
languageautoauto, pt-BR or en. auto follows the system's LANG: Portuguese for pt_*, English otherwise
iconsautoemoji draws the steps as ✅ 🟠 ⚪, symbol as ✓ ● ○. auto uses symbol in a JetBrains IDE's terminal and emoji elsewhere

Install

/plugin install plain-view --marketplace ice-lfernandes/claude-code-mods

Or for one session: claude --plugin-dir ./plain-view

What it reaches

ModNetworkRuns processesFilesCalls a modelSends data anywhere
plain-viewNoNoNoNoNo

It reads the agent's task list and the files it touches from the tool.call event, the request from turn.start, and the agent's answer at the end of each step from turn.step, for a checklist. It counts the agents the main turn starts from agent.spawn (their name and start time) and their end from turn.complete; while one runs it asks $.agent.list() at most every 2 seconds for an end it missed, and $.command.list() whether agent-watch's /watch is there. Its agent.spawn hook only observes: the spawn goes on whatever happens after it. That hook passes every response through unchanged. With askForTasks on (the default), its prompt.compose hook adds one line to the system prompt while the mod is on. Under agentText it hides the agent's messages from the drawing only; the session keeps them. Its tool.call hook only observes: if it fails, the call goes on, and nothing after the call can make it run twice. Its one addition is the reminder above, handed to the model with the result of a call that worked (never with a refusal or an error), only with askForTasks on. The only thing it writes is its own options through $.config.set, when you run on, off or palette, or press a value or defaults in the settings pane (defaults asks first, in the engine's own question dialog). It keeps its values in the session's plugin state and nothing across sessions.

While the agent works, or one of its agents runs, the card redraws 10 times a second for the shine. animation: off stops that.

Source 9 files
hooks/register.tsx 722 lines
1// plain-view: a quiet transcript.
2//
3//   rows   ToolUse, ToolResult and ToolGroup draw nothing while the mod is on. A failed or
4//          interrupted call draws in full, and the agent's questions, its plan and its helpers
5//          (NEVER_HIDDEN) are never touched, nor the permission dialog or any message.
6//   card   AbovePrompt: the request's title, `Passo 2 de 4` with a bar, one row per task with its
7//          own bar and `Feito · ~40% · Próximo · Depois`. Before a task list, `Entender o pedido`
8//          and `Planejar os passos`; with no list at all, the tool in flight. When the turn ends
9//          the card turns green (`✓ Tudo pronto`, `levou 1m 47s`, the files changed and read), or
10//          grey on Esc; the next request starts a fresh one. The engine's `[-]` folds it.
11//   agents the agents (subagents) the main loop spawns, in one row of the card: `◇ 1 agente
12//          rodando · code-review · 3m 12s`, with agent-watch's `/watch` when it is installed.
13//          With the main turn over and no task list, the card waits for them (`Esperando 1
14//          agente`). A turn with no list that called tools or agents ends in a small card
15//          (`✓ Pronto`, the time, the files and the agents); a plain conversation leaves none.
16//   plan   from the agent's TaskCreate, TaskUpdate and TodoWrite calls, else from a checklist it
17//          writes in its answer (`1. [ ] Ler a API`). An open checklist sleeps at the next request
18//          and wakes only if an answer writes one of its tasks again. The `askForTasks` option
19//          asks the model, in the system prompt, to keep a task list with those tools, or a
20//          checklist in its reply when the session has none.
21//   title  the request's first line, and `+5 linhas` when it has more; the `request` option shows
22//          them joined, from the first line that reads as a sentence, or all of them. The card's
23//          `ver pedido` button unfolds the whole request until the next one.
24//   words  `agentText`: final (the default) hides the text of each step that went on to call
25//          tools, so the final answer stays; none hides every message; card hides them all and
26//          puts the answer's first sentence in the end card; all keeps every word.
27//   bars   a gradient of the `palette` option's colors, and a shine that runs while the agent
28//          works (`animation`); see palettes.ts and the design guide's "Exception: gradients".
29//   pane   /plain-view alone, or /plain-view config: a pane (a tab like /limits and /watch) with
30//          the eight options in three tabs, Transcript, Card and General. Each value is a button
31//          that saves it as /config would ($.config.set); the engine reloads the mod with it, and
32//          the pane opens again if the reload closed it. A locked option (managed settings) shows
33//          its value and why it does not change; `defaults` asks first, then resets them all.
34//   /plain-view config | on | off | demo | palette [name] | help
35//
36// The task list comes from the agent's TaskCreate, TaskUpdate and TodoWrite calls, the agents from
37// agent.spawn, their turn.complete and $.agent.list(). Reads nothing from disk, runs no process,
38// calls no model; the only writes are its own options, through $.config.set, when the person asks
39// for them.
40
41import { atom, read, update } from 'claude-code'
42import type { Elements, EngineInterface, Register, Timer } from 'claude-code'
43
44import type { Agent, AgentText, Flash, Item, Turn } from '../types'
45import { drawCard, rasterCells, barCells } from './card'
46import { PALETTES, paletteOf, stopsOf } from './palettes'
47import type { Palette } from './palettes'
48import {
49  agentTextOf,
50  applyTask,
51  cardOf,
52  countCall,
53  currentOf,
54  demoOf,
55  endTurn,
56  finishAgent,
57  isNudgeDue,
58  keepAgents,
59  LIST_MS,
60  MID_KEPT,
61  NEVER_HIDDEN,
62  normalize,
63  reconcileAgents,
64  requestModeOf,
65  runningOf,
66  showsBlock,
67  spawnAgent,
68  startTurn,
69  TASK_TOOLS,
70  titleOf,
71  touch,
72  wake,
73} from './plan'
74import type { RequestMode } from './plan'
75import type { Setting, SettingKey, SettingValue } from './settings'
76import { awayFromDefaults, SETTINGS, settingsOf, tabOf, TABS } from './settings'
77import type { IconStyle, Lang, Verb } from './ui'
78import { langOf, linesOf, styleOf, verbRow } from './ui'
79import { COMMAND, MODE, WATCH, WORDS } from './words'
80
81const turn = atom({ plugin: 'plain-view', key: 'turn' } as const, null as Turn | null)
82const items = atom({ plugin: 'plain-view', key: 'items' } as const, [] as Item[])
83const dormant = atom({ plugin: 'plain-view', key: 'dormant' } as const, [] as Item[])
84const unfolded = atom({ plugin: 'plain-view', key: 'unfolded' } as const, false)
85const tick = atom({ plugin: 'plain-view', key: 'tick' } as const, 0)
86const mids = atom({ plugin: 'plain-view', key: 'mids' } as const, [] as string[])
87const agents = atom({ plugin: 'plain-view', key: 'agents' } as const, [] as Agent[])
88const tab = atom({ plugin: 'plain-view', key: 'tab' } as const, 0)
89const flash = atom({ plugin: 'plain-view', key: 'flash' } as const, null as Flash | null)
90const reopenAt = atom({ plugin: 'plain-view', key: 'reopenAt' } as const, 0)
91const resetting = atom({ plugin: 'plain-view', key: 'resetting' } as const, false)
92
93/** The settings pane. */
94const PANE = 'plain-view-settings'
95/** How soon after a change from the pane a reload opens the pane again. */
96const REOPEN_MS = 10_000
97
98/** How often the shine moves while the agent works. */
99const TICK_MS = 100
100/** How long each step of the demo lasts. */
101const DEMO_STEP_MS = 3000
102
103// Set by register from the options, and by session.start from the system and the theme row.
104let lang: Lang = 'en'
105let style: IconStyle = 'emoji'
106let isOn = false
107let palette: Palette = paletteOf(undefined)
108let animate = true
109let askForTasks = true
110let agentText: AgentText = 'final'
111let requestMode: RequestMode = 'line'
112let theme: unknown = 'dark'
113// The timers of this load; a reload starts them again from session.start.
114let ticker: Timer | null = null
115let demoTimer: Timer | null = null
116// When the ticker last asked $.agent.list(), and whether agent-watch's /watch is there to offer.
117let listedAt = 0
118let hasWatch = false
119// The options this load got: what the pane shows for a row /config does not list.
120let loaded: Readonly<Record<string, unknown>> = {}
121
122const quietly = (p: Promise<unknown>) => void p.catch(() => undefined)
123
124/**
125 * The ticker: it moves the shine while the agent works (`animation`), and while the main loop's
126 * agents run it also asks $.agent.list() every LIST_MS, for an end their turn.complete missed.
127 * With animation off it runs only for the agents, at LIST_MS.
128 */
129const startTicking = ($: EngineInterface, forAgents = false) => {
130  if (ticker || (!animate && !forAgents)) return
131  ticker = $.clock.every(animate ? TICK_MS : LIST_MS, () => quietly(onTick($)))
132}
133const stopTicking = () => {
134  ticker?.cancel()
135  ticker = null
136}
137
138const onTick = async ($: EngineInterface) => {
139  if (animate) await update($, tick, n => n + 1)
140  const now = await $.clock.now()
141  if (now - listedAt < LIST_MS) return
142  listedAt = now
143  await reconcile($, now)
144}
145
146/** Folds $.agent.list() into the running agents, then stops the ticker when nothing is left to show moving. */
147const reconcile = async ($: EngineInterface, now: number) => {
148  if (runningOf(await read($, agents)).length > 0) {
149    const listed = await $.agent.list().catch(() => null)
150    if (listed) await update($, agents, list => reconcileAgents(list, listed, now))
151  }
152  await settle($)
153}
154
155/** Stops the ticker once the main turn is over and no agent of it runs. */
156const settle = async ($: EngineInterface) => {
157  const t = await read($, turn)
158  if (t?.isDemo && t.end === undefined) return
159  if ((!t || t.end !== undefined) && runningOf(await read($, agents)).length === 0) stopTicking()
160}
161
162/** Whether agent-watch's /watch is among the commands the person can run. */
163const watchOf = async ($: EngineInterface) =>
164  (await $.command.list().catch(() => [])).some(c => c.name === WATCH && c.plugin === 'agent-watch')
165
166/** Changes one of the mod's options as /config would; the engine reloads the mod with it. */
167const setOption = async ($: EngineInterface, key: string, value: unknown): Promise<string | null> => {
168  const result = await $.config.set({ key: `plain-view.${key}`, value } as never)
169  return result && 'deny' in result && result.deny !== undefined ? String(result.deny) : null
170}
171
172/** The eight options as /config holds them now. */
173const settingsNow = async ($: EngineInterface) => settingsOf(await $.config.list().catch(() => []), loaded)
174
175const openPane = ($: EngineInterface) =>
176  $.ui.open({ id: PANE, title: WORDS[lang].pane.title, focus: true, closeOnEscape: true }).catch(() => null)
177
178/**
179 * A value pressed in the pane. The reload a change causes may cut this hook short, so the
180 * `Salvo` line and the time to open the pane again are written first; a refusal, which reloads
181 * nothing, replaces the line.
182 */
183const choose = async ($: EngineInterface, key: SettingKey, value: SettingValue) => {
184  await update($, flash, (): Flash => ({ kind: 'saved', key, value }))
185  const now = await $.clock.now()
186  await update($, reopenAt, () => now)
187  const deny = await setOption($, key, value).catch((err: unknown) => String(err instanceof Error ? err.message : err))
188  if (deny) {
189    await update($, reopenAt, () => 0)
190    await update($, flash, (): Flash => ({ kind: 'denied', why: deny }))
191  }
192}
193
194/**
195 * Puts every option that is not locked back to its default, one $.config.set each. Each change
196 * reloads the mod; `resetting` lets the next load's session.start go on with what is left.
197 */
198const resetOptions = async ($: EngineInterface) => {
199  const wasResetting = await read($, resetting)
200  const left = awayFromDefaults(await settingsNow($))
201  if (left.length === 0) {
202    await update($, resetting, () => false)
203    await update($, flash, (): Flash => ({ kind: wasResetting ? 'reset' : 'resetNone' }))
204    return
205  }
206  await update($, resetting, () => true)
207  await update($, flash, (): Flash => ({ kind: 'reset' }))
208  for (const key of left) {
209    const now = await $.clock.now()
210    await update($, reopenAt, () => now)
211    const deny = await setOption($, key, SETTINGS[key].initial).catch((err: unknown) => String(err instanceof Error ? err.message : err))
212    if (deny) {
213      await update($, resetting, () => false)
214      await update($, flash, (): Flash => ({ kind: 'denied', why: deny }))
215      return
216    }
217  }
218  await update($, resetting, () => false)
219}
220
221/** `defaults`: asks first, since it may change all eight at once. */
222const askReset = async ($: EngineInterface) => {
223  const p = WORDS[lang].pane
224  if (awayFromDefaults(await settingsNow($)).length === 0) {
225    await update($, flash, (): Flash => ({ kind: 'resetNone' }))
226    return
227  }
228  const answer = await $.ui.ask(p.ask, { options: [p.askYes, p.askNo], header: 'plain-view' }).catch(() => null)
229  if (answer === p.askYes) await resetOptions($)
230}
231
232const runDemo = async ($: EngineInterface): Promise<string> => {
233  const w = WORDS[lang]
234  const now = await $.clock.now()
235  const t = await read($, turn)
236  if (t && t.end === undefined && !t.isDemo) return w.demoBusy
237  demoTimer?.cancel()
238  const show = async (step: number) => {
239    const demo = demoOf(step, now, lang)
240    await update($, items, () => demo.items)
241    if (step < demo.items.length) {
242      await update($, turn, () => demo.turn)
243      demoTimer = $.clock.after(DEMO_STEP_MS, () => quietly(show(step + 1)))
244    } else {
245      await update($, turn, () => endTurn(demo.turn, 'answer', now + DEMO_STEP_MS * step))
246      stopTicking()
247    }
248  }
249  await show(0)
250  startTicking($)
251  return w.demoStarted
252}
253
254/** The palette list as text, for a surface that does not draw the command's own row. */
255const paletteText = () => {
256  const w = WORDS[lang]
257  return [`**${w.palette}** · ${w.paletteNow(palette.id)}`, ...PALETTES.map(p => `- \`${p.id}\` ${p.hint[lang]}`), w.paletteAlso].join('\n')
258}
259
260/** /plain-view and its arguments. */
261const runCommand = async ($: EngineInterface, args: string): Promise<{ text?: string }> => {
262  const w = WORDS[lang]
263  const [verb = '', name = ''] = args.trim().toLowerCase().split(/\s+/)
264  switch (verb) {
265    case 'on':
266    case 'off': {
267      const want = verb === 'on'
268      if (want === isOn) return { text: want ? w.alreadyOn : w.alreadyOff }
269      const deny = await setOption($, 'enabled', want)
270      return { text: deny ? w.denied(deny) : want ? w.on : w.off }
271    }
272    case 'demo':
273      return { text: await runDemo($) }
274    case '':
275    case 'config':
276    case 'configuration':
277    case 'settings': {
278      await update($, flash, () => null)
279      const opened = await openPane($)
280      return opened?.isPlaced ? {} : { text: w.help }
281    }
282    case 'palette': {
283      if (!name) return { text: paletteText() }
284      const p = PALETTES.find(x => x.id === name)
285      if (!p) return { text: w.paletteUnknown(name, PALETTES.map(x => x.id).join(', ')) }
286      const deny = await setOption($, 'palette', p.id)
287      return { text: deny ? w.denied(deny) : w.paletteSet(p.id) }
288    }
289    default:
290      return { text: w.help }
291  }
292}
293
294const VERBS: readonly Verb[] = [{ verb: 'config' }, { verb: 'on' }, { verb: 'off' }, { verb: 'demo' }, { verb: 'palette' }]
295/** The pane's own footer: the verbs that do something the tabs do not. */
296const PANE_VERBS: readonly Verb[] = [{ verb: 'on' }, { verb: 'off' }, { verb: 'demo' }, { verb: 'help' }]
297
298const pressVerb = async ($: EngineInterface, v: Verb) => {
299  const { text } = await runCommand($, v.verb)
300  for (const line of linesOf(text)) $.ui.log(line)
301}
302
303/** A checklist in the agent's text becomes the plan, or wakes the one the last request left open. */
304const readChecklist = async ($: EngineInterface, text: string) => {
305  if (!text.trim()) return
306  try {
307    // The list is changed from its current value: the step's tools may have counted calls on it
308    // since the step began.
309    const sleeping = await read($, dormant)
310    let left = sleeping
311    await update($, items, list => {
312      const woke = wake(list, sleeping, text)
313      left = woke.dormant
314      return woke.items
315    })
316    if (left !== sleeping) await update($, dormant, () => left)
317  } catch {
318    // An observer: the step goes on.
319  }
320}
321
322/** True when a row of this tool, in this state, steps aside. */
323const hides = (tool: string, isErrored: boolean, isInterrupted: boolean) => isOn && !isErrored && !isInterrupted && !NEVER_HIDDEN.includes(tool)
324
325export const register: Register = (on, options) => {
326  lang = langOf(options.language)
327  style = styleOf(options.icons)
328  isOn = options.enabled === true
329  palette = paletteOf(options.palette)
330  animate = options.animation !== false
331  askForTasks = options.askForTasks !== false
332  agentText = agentTextOf(options.agentText)
333  requestMode = requestModeOf(options.request)
334  loaded = options
335
336  on('session.start', async ($, e, next) => {
337    const result = await next(e)
338    lang = langOf(options.language, await $.env.get('LANG').catch(() => undefined))
339    style = styleOf(options.icons, await $.env.get('TERMINAL_EMULATOR').catch(() => undefined))
340    await $.command.register({
341      name: COMMAND,
342      description: WORDS[lang].description,
343      argumentHint: '[config|on|off|demo|palette [name]|help]',
344      immediate: true,
345    })
346    const rows = await $.config.list().catch(() => [])
347    theme = rows.find(r => r.key === 'theme')?.value ?? theme
348    // A reload in the middle of a turn: the shine goes on. A demo cut by the reload ends here,
349    // since its timer is gone.
350    const t = await read($, turn)
351    if (t?.isDemo && t.end === undefined) {
352      await update($, turn, () => null)
353      await update($, items, () => [])
354    } else if (isOn && t && t.end === undefined) startTicking($)
355    // Agents that ran across the reload: settle the ones that ended meanwhile, and keep watching.
356    if (runningOf(await read($, agents)).length > 0) {
357      hasWatch = await watchOf($)
358      const listed = await $.agent.list().catch(() => null)
359      const now = await $.clock.now()
360      if (listed) await update($, agents, list => reconcileAgents(list, listed, now))
361      if (isOn && runningOf(await read($, agents)).length > 0) startTicking($, true)
362    }
363    // A reload a change from the pane caused: open the pane again (a no-op when it stayed open),
364    // and go on with a reset that the reload cut short.
365    const pressedAt = await read($, reopenAt)
366    if (pressedAt > 0) {
367      await update($, reopenAt, () => 0)
368      if ((await $.clock.now()) - pressedAt < REOPEN_MS) quietly(openPane($))
369    }
370    if (await read($, resetting)) quietly(resetOptions($))
371    return result
372  })
373
374  on('config.set', { key: 'theme' }, async ($, e, next) => {
375    const result = await next(e)
376    if (!('deny' in result && result.deny !== undefined)) theme = e.value
377    return result
378  }).catch(($, e, next) => next(e)) // an observer: fail open
379
380  on('turn.start', async ($, e, next) => {
381    const result = await next(e)
382    demoTimer?.cancel()
383    const now = await $.clock.now()
384    const fresh = startTurn(await read($, turn), await read($, items), e.text, now, lang)
385    await update($, items, () => fresh.items)
386    await update($, dormant, () => fresh.dormant).catch(() => undefined)
387    await update($, turn, () => fresh.turn)
388    // A new request opens folded; a notification or a continuation keeps it as it was.
389    if (titleOf(e.text)) await update($, unfolded, () => false).catch(() => undefined)
390    // A new request keeps the agents still running; a notification keeps the finished ones too.
391    await update($, agents, list => keepAgents(list, e.text))
392    if (isOn) startTicking($, runningOf(await read($, agents)).length > 0)
393    return result
394  })
395
396  // An agent the main loop spawns joins the card's agents row; one spawned by another agent does
397  // not, nor a workflow's (no $.agent.list() row settles it).
398  on('agent.spawn', async ($, e, next) => {
399    const result = await next(e)
400    const id = result.agentId
401    if (result.deny !== undefined || !id || e.parentAgentId || e.workflow) return result
402    // After next(e) nothing throws, so the spawn never runs twice.
403    try {
404      const now = await $.clock.now()
405      await update($, agents, list => spawnAgent(list, id, e.description || e.subagentType, now))
406      hasWatch = await watchOf($)
407      if (isOn) startTicking($, true)
408    } catch {
409      // An observer: the spawn goes on.
410    }
411    return result
412  })
413
414  // The agent's answer at the end of each step: a checklist in it becomes the plan, or wakes the
415  // one the last request left open.
416  // A checklist is read as soon as the text before the step's first tool call is whole, so the
417  // calls that follow count toward the step it opens; the whole answer is read again at the end.
418  on('turn.step', async function* ($, e, next) {
419    if (e.agentId) return yield* next(e)
420    const stream = next(e)
421    // A stream the engine closes early rejects its result; nothing here waits on it then.
422    stream.result.catch(() => undefined)
423    const texts: string[] = []
424    let isRead = false
425    for await (const chunk of stream) {
426      if (chunk.kind === 'text') texts[chunk.index] = (texts[chunk.index] ?? '') + chunk.text
427      else if (chunk.kind === 'tool' && !isRead) {
428        isRead = true
429        await readChecklist($, texts.join('\n'))
430      }
431      yield chunk
432    }
433    const result = await stream.result
434    if (result.answer) {
435      await readChecklist($, result.answer)
436      // A step that went on to call tools: its text is mid-turn, which `final` hides.
437      const text = normalize(result.answer)
438      if (result.toolUses.length > 0 && text) await update($, mids, list => [...list, text].slice(-MID_KEPT)).catch(() => undefined)
439    }
440    return result
441  })
442
443  // With askForTasks, one line in the system prompt asks for a task list, or for a checklist in
444  // the reply when the session has no task tool.
445  on('prompt.compose', async ($, e, next) => {
446    const result = await next(e)
447    if (!isOn || !askForTasks) return result
448    const text = e.tools.some(t => t === 'TodoWrite' || t === 'TaskCreate') ? WORDS.en.askForTasks : WORDS.en.askForChecklist
449    return { sections: [...result.sections, { id: 'plain-view:tasks', text, scope: 'session' as const }] }
450  })
451
452  on('tool.call', async ($, e, next) => {
453    if (e.agentId) return next(e)
454    const input = e as unknown as Readonly<Record<string, unknown>>
455    if (TASK_TOOLS.includes(e.tool)) {
456      const result = await next(e)
457      // TaskUpdate reports a refused change in its result ({ success: false }).
458      const refused = (result.result as { success?: unknown } | undefined)?.success === false
459      if (result.deny === undefined && !('isError' in result && result.isError) && !refused) {
460        await update($, items, list => applyTask(list, e.tool, input, result.result)).catch(() => undefined)
461        await update($, dormant, () => []).catch(() => undefined)
462      }
463      return result
464    }
465    const t = await read($, turn)
466    if (!t || t.end !== undefined || t.isDemo) return next(e)
467    await update($, turn, v => (v ? touch(v, e.tool, input, lang, null) : v))
468    await update($, items, countCall)
469    // With askForTasks, a text list that stopped moving: the model is reminded after this call's
470    // result, once it is known to have worked (the reminder rides on a result, never on a refusal).
471    const list = await read($, items)
472    const at = currentOf(list)
473    const nudge = isOn && askForTasks && isNudgeDue(list, at) ? WORDS.en.nudge(list[at]!.calls) : null
474    const result = await next(e)
475    const ok = result.deny === undefined && !('isError' in result && result.isError)
476    await update($, turn, v => (v ? touch(v, e.tool, input, lang, ok) : v)).catch(() => undefined)
477    if (nudge && ok && 'result' in result) return { ...result, context: [...(result.context ?? []), nudge] }
478    return result
479    // An observer: fail open. After next(e) nothing throws, so the call never runs twice.
480  }).catch(($, e, next) => next(e))
481
482  // The main turn ends the card's turn; an agent's run ends that agent. The ticker stops once both
483  // are over.
484  on('turn.complete', async ($, e, next) => {
485    const result = await next(e)
486    const now = await $.clock.now()
487    const id = e.agentId
488    if (id) await update($, agents, list => finishAgent(list, id, now))
489    else await update($, turn, v => (v && v.end === undefined && !v.isDemo ? endTurn(v, e.reason, now, e.answer) : v))
490    await settle($)
491    return result
492  })
493
494  on('command.run', { command: COMMAND }, ($, e) => runCommand($, e.args)).catch(() => ({ text: WORDS[lang].failed }))
495
496  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
497    if (e.props.hasSurvey) return next(e)
498    const t = await read($, turn)
499    if (!isOn && !t?.isDemo) return next(e)
500    // A demo's card shows no agents.
501    const team = t?.isDemo ? [] : await read($, agents)
502    const view = { mode: requestMode, isOpen: await read($, unfolded) }
503    const card = cardOf(t, await read($, items), await $.clock.now(), lang, agentText === 'card', team, view)
504    if (!card) return next(e)
505    const n = await read($, tick)
506    const isWorking = (t !== null && t.end === undefined) || runningOf(team).length > 0
507    // Rasters only on the terminal; another surface's table draws one as an empty box.
508    const all = $.ui.resolve(e)
509    const ui = { Box: all.Box, Text: all.Text, Button: all.Button, Raster: e.surface === 'terminal' ? (all as Elements['terminal']).Raster : undefined }
510    const mine = drawCard(ui, card, {
511      stops: animate ? stopsOf(palette, theme) : null,
512      tick: animate && isWorking ? n : null,
513      columns: e.props.bodyColumns || e.viewport?.columns || 80,
514      icons: style,
515      answerLabel: WORDS[lang].answer,
516      ...(hasWatch ? { onWatch: () => quietly($.command.run({ command: WATCH, args: '' })) } : {}),
517      request: { more: WORDS[lang].moreLines, show: WORDS[lang].showRequest, fold: WORDS[lang].foldRequest },
518      onRequest: () => quietly(update($, unfolded, v => !v)),
519    })
520    const { Box } = $.ui.resolve(e)
521    const theirs = await next(e)
522    return theirs ? (
523      <Box flexDirection="column">
524        {mine}
525        {theirs}
526      </Box>
527    ) : (
528      mine
529    )
530  })
531
532  // The agent's words, as `agentText` says. Under `final` a block hides once its step is known to
533  // have gone on to call tools (the read subscribes the block to that list).
534  on('ui.render', { component: 'AssistantMessage' }, async ($, e, next) => {
535    if (!isOn || agentText === 'all') return next(e)
536    if (showsBlock(agentText, e.props.text, agentText === 'final' ? await read($, mids) : [])) return next(e)
537    const { Box } = $.ui.resolve(e)
538    return <Box />
539  })
540
541  // The rows step aside; a failure, an interrupt and the never-hidden tools draw as the engine does.
542  on('ui.render', { component: 'ToolUse' }, ($, e, next) => {
543    if (!hides(e.props.tool, e.props.isErrored, e.props.isInterrupted)) return next(e)
544    const { Box } = $.ui.resolve(e)
545    return <Box />
546  })
547
548  on('ui.render', { component: 'ToolResult' }, ($, e, next) => {
549    if (!hides(e.props.tool, e.props.isErrored, false)) return next(e)
550    const { Box } = $.ui.resolve(e)
551    return <Box />
552  })
553
554  // A group folds its calls into one count line, which would hide a failure: a group with a failed
555  // or interrupted call unfolds, and its rows go through the ToolUse hook above, one by one.
556  on('ui.render', { component: 'ToolGroup' }, ($, e, next) => {
557    if (isOn && e.props.calls.some(c => c.isErrored || c.isInterrupted)) return next({ ...e, props: { ...e.props, isExpanded: true } })
558    if (!e.props.calls.every(c => hides(c.tool, c.isErrored, c.isInterrupted))) return next(e)
559    const { Box } = $.ui.resolve(e)
560    return <Box />
561  })
562
563  // The hint line under the prompt says the mode is on (the footer's mode labels do not show
564  // while none of the engine's modes is on).
565  on('ui.render', { component: 'PromptHint' }, ($, e, next) =>
566    isOn ? next({ ...e, props: { ...e.props, tail: e.props.tail ? `${e.props.tail} · ${MODE}` : MODE } }) : next(e),
567  )
568
569  // The command's own rows: the palettes with a sample and a button, and the help's verbs.
570  on('ui.render', { component: 'CommandOutput' }, async ($, e, next) => {
571    if (e.props.command !== COMMAND || e.props.isErrored) return next(e)
572    const [verb = '', name = ''] = e.props.args.trim().toLowerCase().split(/\s+/)
573    const ui = $.ui.resolve(e)
574    const { Box, Text, Button } = ui
575    const w = WORDS[lang]
576    if (verb === 'palette' && !name) {
577      const Raster = e.surface === 'terminal' ? (ui as Elements['terminal']).Raster : undefined
578      const isDark = !/light/i.test(String(theme ?? ''))
579      return (
580        <Box flexDirection="column">
581          <Text>
582            <Text bold>{w.palette}</Text>
583            <Text dimColor>{` · ${w.paletteNow(palette.id)}`}</Text>
584          </Text>
585          {PALETTES.map(p => {
586            const s = isDark ? p.dark : p.light
587            const inUse = p.id === palette.id
588            return (
589              <Box key={`palette:${p.id}`} flexDirection="row" gap={1}>
590                <Text bold={inUse} color={inUse ? 'claude' : undefined}>{p.id.padEnd(8)}</Text>
591                {Raster ? <Raster key={`work:${p.id}`} columns={10} rows={1} cells={rasterCells(barCells(10, 1, 'work', s, null))} /> : null}
592                {Raster ? <Raster key={`ok:${p.id}`} columns={3} rows={1} cells={rasterCells(barCells(3, 1, 'ok', s, null))} /> : null}
593                {inUse ? (
594                  <Text color="success">{w.inUse}</Text>
595                ) : (
596                  <Button key={`use:${p.id}`} label={w.use} onPress={() => quietly(runCommand($, `palette ${p.id}`).then(r => $.ui.toast(r.text ?? '')))} />
597                )}
598                <Text dimColor>{p.hint[lang]}</Text>
599              </Box>
600            )
601          })}
602          <Text dimColor>{w.paletteAlso}</Text>
603        </Box>
604      )
605    }
606    if (verb === 'help' || (verb === '' && e.props.text)) {
607      const theirs = await next(e)
608      return (
609        <Box flexDirection="column">
610          {theirs}
611          {verbRow({ Box, Text, Button }, COMMAND, VERBS, v => quietly(pressVerb($, v)))}
612        </Box>
613      )
614    }
615    return next(e)
616  })
617
618  // The settings pane: three tabs, a button per value, what each does, and a preview of the card.
619  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
620    const all = $.ui.resolve(e)
621    const { Box, Text, Button } = all
622    const Raster = e.surface === 'terminal' ? (all as Elements['terminal']).Raster : undefined
623    const w = WORDS[lang]
624    const p = w.pane
625    const s = await settingsNow($)
626    const shown = tabOf(await read($, tab))
627    const said = await read($, flash)
628    const columns = Math.max(30, (e.props.bodyColumns || e.viewport?.columns || 80) - 2)
629    const isDark = !/light/i.test(String(theme ?? ''))
630    const nameOf = (v: SettingValue) => (v === true ? p.yes : v === false ? p.no : String(v))
631    const whatOf = (key: SettingKey, v: SettingValue) =>
632      key === 'palette' ? (PALETTES.find(x => x.id === v)?.hint[lang] ?? '') : (p.values[key][String(v)] ?? '')
633
634    const option = (key: SettingKey, cur: Setting) => (
635      <Box key={`opt:${key}`} flexDirection="column">
636        <Text bold>{p.labels[key]}</Text>
637        {SETTINGS[key].values.map(v => {
638          const isCur = v === cur.value
639          const label = `${isCur ? '●' : '○'} ${nameOf(v)}`
640          const pal = key === 'palette' ? PALETTES.find(x => x.id === v) : undefined
641          return (
642            <Box key={`val:${key}:${String(v)}`} flexDirection="row">
643              <Box width={12}>
644                {isCur || cur.isLocked ? (
645                  <Text bold={isCur} color={cur.isLocked ? 'inactive' : 'claude'}>{label}</Text>
646                ) : (
647                  <Button key={`set:${key}:${String(v)}`} plain label={label} onPress={() => quietly(choose($, key, v))} />
648                )}
649              </Box>
650              {pal && Raster ? <Raster key={`swatch:${pal.id}`} columns={6} rows={1} cells={rasterCells(barCells(6, 1, 'work', isDark ? pal.dark : pal.light, null))} /> : null}
651              {pal && Raster ? <Text> </Text> : null}
652              <Text dimColor={!cur.isLocked} color={cur.isLocked ? 'inactive' : undefined}>{whatOf(key, v)}</Text>
653            </Box>
654          )
655        })}
656        {cur.isLocked && <Text color="inactive">{p.locked}</Text>}
657        {cur.isLocked && <Text dimColor>{p.lockedWhy}</Text>}
658      </Box>
659    )
660
661    // The card tab's preview: the demo's second step, in the palette and animation the pane shows.
662    const now = await $.clock.now()
663    const preview = () => {
664      const demo = demoOf(1, now - 12_000, lang)
665      const sample = cardOf(demo.turn, demo.items, now, lang)
666      if (!sample) return null
667      const stops = s.animation.value === true ? stopsOf(paletteOf(s.palette.value), theme) : null
668      return (
669        <Box key="preview" flexDirection="column">
670          <Text bold>{p.preview}</Text>
671          {drawCard({ Box, Text, Raster }, sample, { stops, tick: null, columns, icons: style })}
672        </Box>
673      )
674    }
675
676    const line =
677      said === null ? null : said.kind === 'saved' ? (
678        <Text color="success">{p.saved(p.labels[said.key as SettingKey] ?? said.key, nameOf(said.value))}</Text>
679      ) : said.kind === 'denied' ? (
680        <Text color="warning">{p.denied(said.why)}</Text>
681      ) : said.kind === 'reset' ? (
682        <Text color="success">{p.reset}</Text>
683      ) : (
684        <Text dimColor>{p.resetNone}</Text>
685      )
686
687    return (
688      <Box flexDirection="column" paddingX={1} gap={1}>
689        <Box flexDirection="column">
690          <Text color="claude" bold>{p.heading}</Text>
691          <Text dimColor>{p.hint}</Text>
692          {line}
693        </Box>
694
695        <Box flexDirection="row" flexWrap="wrap">
696          {p.tabs.map((name, i) => (
697            <Box key={`tabs:${i}`} flexDirection="row">
698              {i > 0 && <Text dimColor> · </Text>}
699              {i === shown ? (
700                <Text color="claude" bold>{`▸ ${name}`}</Text>
701              ) : (
702                <Button key={`tab:${i}`} plain label={name} onPress={() => quietly(update($, tab, () => i).then(() => update($, flash, () => null)))} />
703              )}
704            </Box>
705          ))}
706        </Box>
707
708        {TABS[shown]!.map(key => option(key, s[key]))}
709        {shown === 1 && preview()}
710
711        <Box flexDirection="column" alignItems="flex-start">
712          {verbRow({ Box, Text, Button }, COMMAND, PANE_VERBS, v => quietly(pressVerb($, v)))}
713          <Box flexDirection="row" gap={1}>
714            <Button key="reset" label={p.defaults} onPress={() => quietly(askReset($))} />
715            <Button key="close" role="dismiss" label={p.close} onPress={() => quietly($.ui.close({ id: PANE }))} />
716          </Box>
717        </Box>
718      </Box>
719    )
720  })
721}
722
hooks/card.tsx 312 lines
1// The plan card's drawing, with no `$`: register.tsx resolves the elements and hands them in.
2//
3// Bars are one Raster each on the terminal, a gradient of the palette's colors cell by cell, with
4// a bright cell running along the filled part while the agent works (`tick`). With no palette
5// (animation off) or on another surface they are plain text in the theme's own keys.
6
7import type { Elements } from 'claude-code'
8
9import type { AgentsRow, Card, RequestView, Row } from './plan'
10import type { Stops } from './palettes'
11import { hex, mix, titleColor } from './palettes'
12import type { IconStyle } from './ui'
13import { clip, glyph } from './ui'
14
15const FULL = 0x2588 // █
16const EMPTY = 0x2591 // ░
17const DEFAULT = 0x01000000
18
19/** How a bar paints: the working gradient, the done one, a stopped bar, or a comet over the track. */
20export type BarMode = 'work' | 'ok' | 'off' | 'comet'
21
22/** One cell of a bar: its character and its color. */
23export type Cell = { ch: number; fg: number }
24
25/** The cells of a bar of `n`, `frac` full; `tick` moves the shine (work) or the comet. */
26export const barCells = (n: number, frac: number, mode: BarMode, s: Stops, tick: number | null): Cell[] => {
27  if (mode === 'comet') {
28    const head = (tick ?? 0) % (n + 4)
29    return Array.from({ length: n }, (_, i) => {
30      const d = head - i
31      return d >= 0 && d < 4 ? { ch: FULL, fg: mix(s.g2, s.g1, d / 4) } : { ch: EMPTY, fg: s.track }
32    })
33  }
34  const f = Math.max(0, Math.min(n, Math.round(n * frac)))
35  const shineAt = tick === null || mode !== 'work' || f === 0 ? -9 : tick % (f + 8)
36  return Array.from({ length: n }, (_, i) => {
37    if (i >= f) return { ch: EMPTY, fg: s.track }
38    if (mode === 'off') return { ch: FULL, fg: s.off }
39    const x = f > 1 ? i / (f - 1) : 0
40    const base = mode === 'ok' ? mix(s.k1, s.k2, x) : mix(s.g1, s.g2, x)
41    const d = Math.abs(shineAt - i)
42    return { ch: FULL, fg: d === 0 ? mix(base, 0xffffff, 0.55) : d === 1 ? mix(base, 0xffffff, 0.25) : base }
43  })
44}
45
46const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
47
48/** Standard padded base64 of bytes. */
49export const base64 = (bytes: Uint8Array) => {
50  let out = ''
51  for (let i = 0; i < bytes.length; i += 3) {
52    const a = bytes[i]!
53    const b = bytes[i + 1]
54    const c = bytes[i + 2]
55    out += B64[a >> 2]! + B64[((a & 3) << 4) | ((b ?? 0) >> 4)]!
56    out += b === undefined ? '=' : B64[((b & 15) << 2) | ((c ?? 0) >> 6)]!
57    out += c === undefined ? '=' : B64[c & 63]!
58  }
59  return out
60}
61
62/** A Raster's `cells`: little-endian u32 triplets, code point, foreground, background (the terminal's). */
63export const rasterCells = (cells: readonly Cell[]) => {
64  const words = new Uint32Array(cells.length * 3)
65  cells.forEach((c, i) => {
66    words[i * 3] = c.ch
67    words[i * 3 + 1] = c.fg
68    words[i * 3 + 2] = DEFAULT
69  })
70  return base64(new Uint8Array(words.buffer))
71}
72
73/** The columns the card's parts take in a body of `inner` columns. */
74export const layoutOf = (inner: number) => {
75  const label = 14
76  const item = inner >= 100 ? 18 : inner >= 70 ? 10 : 6
77  const text = inner >= 100 ? 46 : Math.max(12, Math.min(30, inner - item - 30))
78  const bar = Math.max(6, inner - label - 6)
79  return { label, item, text, bar }
80}
81
82const ICONS = {
83  done: { emoji: '✅', symbol: '✓' },
84  now: { emoji: '🟠', symbol: '●' },
85  wait: { emoji: '⚪', symbol: '○' },
86  halted: { emoji: '⏹️', symbol: '■' },
87}
88
89type Ui = Pick<Elements[keyof Elements], 'Box' | 'Text'> & { Raster?: Elements['terminal']['Raster']; Button?: Elements[keyof Elements]['Button'] }
90
91export type DrawOptions = {
92  /** The palette's colors; null draws in theme keys with no gradient. */
93  stops: Stops | null
94  /** Moves the shine; null keeps the bars still. */
95  tick: number | null
96  /** The box the card draws into. */
97  columns: number
98  icons: IconStyle
99  /** `Resposta: ` before the answer's first sentence. */
100  answerLabel?: string
101  /** Opens agent-watch's pane: the agents row shows `/watch` only when this is given. */
102  onWatch?: () => void
103  /** A request of several lines: `+5 linhas`, and the button that unfolds it (shown only with `onRequest`). */
104  request?: { more: (n: number) => string; show: string; fold: string }
105  onRequest?: () => void
106}
107
108/** The fewest columns the request's title keeps before its count and button step aside. */
109const MIN_TITLE = 12
110
111/** The plan card: a bordered box above the prompt, as the approved prototype draws it. */
112export function drawCard(ui: Ui, card: Card, o: DrawOptions) {
113  const { Box, Text, Raster, Button } = ui
114  const inner = Math.max(30, o.columns - 4)
115  const L = layoutOf(inner)
116  const gradient = o.stops !== null && Raster !== undefined
117
118  const bar = (key: string, n: number, frac: number, mode: BarMode) => {
119    if (gradient) return <Raster key={key} columns={n} rows={1} cells={rasterCells(barCells(n, frac, mode, o.stops!, o.tick))} />
120    if (mode === 'comet') return <Text key={key} color="claude">{'░'.repeat(n)}</Text>
121    const f = Math.max(0, Math.min(n, Math.round(n * frac)))
122    return (
123      <Text key={key}>
124        <Text color={mode === 'ok' ? 'success' : mode === 'off' ? 'inactive' : 'claude'}>{'█'.repeat(f)}</Text>
125        <Text dimColor>{'░'.repeat(n - f)}</Text>
126      </Text>
127    )
128  }
129
130  // The figures take the color of the bar's filled end.
131  const tone = (state: string) =>
132    o.stops ? hex(state === 'done' ? o.stops.k2 : state === 'stopped' ? o.stops.off : o.stops.g2) : state === 'done' ? 'success' : state === 'stopped' ? 'inactive' : 'claude'
133
134  const title = (text: string, room: number, pal: 'work' | 'ok' | 'off') => {
135    const shown = clip(text, Math.max(8, room))
136    if (!o.stops || pal === 'off') return <Text bold dimColor={pal === 'off'} color={pal === 'off' ? undefined : pal === 'ok' ? 'success' : 'claude'}>{shown}</Text>
137    const s = o.stops
138    const last = Math.max(1, shown.length - 1)
139    return (
140      <Text bold>
141        {[...shown].map((ch, i) => (
142          <Text key={`t${i}`} color={hex(pal === 'ok' ? mix(s.k1, s.k2, i / last) : titleColor(s, i / last))}>{ch}</Text>
143        ))}
144      </Text>
145    )
146  }
147
148  // One row for the main loop's agents: `◇ 1 agente rodando · code-review · 3m 12s   /watch`.
149  const agentsLine = (a: AgentsRow) => {
150    const onWatch = o.onWatch
151    const watch = onWatch !== undefined && Button !== undefined
152    const room = inner - a.text.length - (a.time ? a.time.length + 3 : 0) - (watch ? 9 : 0) - 6
153    return (
154      <Box key="agents" flexDirection="row">
155        <Text>
156          <Text color={a.isRunning ? 'claude' : 'success'}>◇ </Text>
157          <Text bold={a.isRunning}>{a.text}</Text>
158          <Text dimColor>{` · ${clip(a.label, Math.max(8, room))}${a.time ? ` · ${a.time}` : ''}`}</Text>
159        </Text>
160        {watch ? <Text>   </Text> : null}
161        {onWatch && Button ? <Button key="watch" plain dimColor label="/watch" onPress={() => onWatch()} /> : null}
162      </Box>
163    )
164  }
165
166  // A request of several lines: `+5 linhas` after the title, the button that unfolds the request
167  // (only when something is left out), and its lines under the title.
168  const request: RequestView | undefined = card.request
169  const words = o.request
170  const titled = (text: string, room: number, pal: 'work' | 'ok' | 'off', badge?: { text: string; state: 'done' | 'stopped' }) => {
171    const label = (request?.isOpen ? words?.fold : words?.show) ?? ''
172    const onRequest = o.onRequest
173    // A narrow card keeps the title: the button goes first, then the count.
174    let more = request && request.more > 0 && words ? `  ${words.more(request.more)}` : ''
175    let hasButton =
176      request !== undefined && words !== undefined && onRequest !== undefined && Button !== undefined && (request.canOpen || (request.isJoined && text.length > room - more.length))
177    if (hasButton && room - more.length - label.length - 6 < MIN_TITLE) hasButton = false
178    if (room - more.length < MIN_TITLE) more = ''
179    return (
180      <Box flexDirection="row">
181        <Text>
182          {badge ? <Text bold inverse color={badge.state === 'done' ? 'success' : 'inactive'}>{` ${badge.text} `}</Text> : <Text color="claude">✦</Text>}
183          <Text> </Text>
184          {title(text, room - more.length - (hasButton ? label.length + 6 : 0), pal)}
185          {more ? <Text dimColor>{more}</Text> : null}
186        </Text>
187        {hasButton ? <Text>  </Text> : null}
188        {hasButton && onRequest ? <Button key="request" plain dimColor label={label} onPress={() => onRequest()} /> : null}
189      </Box>
190    )
191  }
192  const requestRows = () => request?.rest.map((line, i) => <Text key={`request${i}`} dimColor={line.startsWith('⟨')}>{`  ${clip(line, inner - 2)}`}</Text>)
193
194  const titleRow = (text: string, time: string) => (
195    <Box flexDirection="column">
196      <Box flexDirection="row" justifyContent="space-between">
197        {titled(text, inner - 10, 'work')}
198        <Text dimColor>{time}</Text>
199      </Box>
200      {requestRows()}
201    </Box>
202  )
203
204  if (card.kind === 'phrase') {
205    return (
206      <Box key="plain-view" flexDirection="column" borderStyle="round" borderColor="claude" paddingX={1}>
207        {titleRow(card.title, card.time)}
208        <Box flexDirection="row" gap={2}>
209          <Text>
210            <Text color="claude">{`${glyph(o.icons, ICONS.now)} `}</Text>
211            <Text bold>{clip(card.doing, Math.max(10, inner - L.item - 6))}</Text>
212          </Text>
213          {bar('doing', L.item, 0, 'comet')}
214        </Box>
215        {card.agents !== undefined && agentsLine(card.agents)}
216      </Box>
217    )
218  }
219
220  if (card.kind === 'waiting') {
221    return (
222      <Box key="plain-view" flexDirection="column" borderStyle="round" borderColor="claude" paddingX={1}>
223        {titleRow(card.title, card.time)}
224        <Box flexDirection="row" gap={2}>
225          <Text>
226            <Text color="claude">◐ </Text>
227            <Text bold>{card.text}</Text>
228          </Text>
229          {bar('waiting', L.item, 0, 'comet')}
230        </Box>
231        {agentsLine(card.agents)}
232      </Box>
233    )
234  }
235
236  // A badge, then the title in the end's colors.
237  const badged = (badge: string, state: 'done' | 'stopped', text: string) =>
238    titled(text, inner - badge.length - 18, state === 'done' ? 'ok' : 'off', { text: badge, state })
239
240  const answerLine = (answer: string | undefined) =>
241    answer !== undefined && (
242      <Text>
243        <Text dimColor>{`  ${o.answerLabel ?? ''}`}</Text>
244        <Text>{answer}</Text>
245      </Text>
246    )
247
248  if (card.kind === 'summary') {
249    return (
250      <Box key="plain-view" flexDirection="column" borderStyle="round" borderColor={card.state === 'done' ? 'success' : 'inactive'} paddingX={1}>
251        <Box flexDirection="row" justifyContent="space-between">
252          {badged(card.badge, card.state, card.title)}
253          <Text dimColor>{card.time}</Text>
254        </Box>
255        {requestRows()}
256        {card.detail !== undefined && <Text dimColor>{`  ${card.detail}`}</Text>}
257        {answerLine(card.answer)}
258      </Box>
259    )
260  }
261
262  const pal = card.state === 'done' ? 'ok' : card.state === 'stopped' ? 'off' : 'work'
263  const border = card.state === 'done' ? 'success' : card.state === 'stopped' ? 'inactive' : 'claude'
264  const head = card.badge && card.state !== 'work' ? badged(card.badge, card.state, card.title) : titled(card.title, inner - 12, pal)
265
266  const row = (r: Row, i: number) => {
267    const icon = r.kind === 'done' ? ICONS.done : r.kind === 'now' ? ICONS.now : r.kind === 'halted' ? ICONS.halted : ICONS.wait
268    const iconColor = r.kind === 'done' ? 'success' : r.kind === 'now' ? 'claude' : undefined
269    const mode: BarMode = r.kind === 'done' ? 'ok' : r.kind === 'now' ? 'work' : 'off'
270    const isNow = r.kind === 'now'
271    return (
272      <Box key={`row${i}`} flexDirection="row">
273        <Text color={iconColor} dimColor={iconColor === undefined}>{`${glyph(o.icons, icon)} `}</Text>
274        <Text bold={isNow} dimColor={r.kind !== 'done' && !isNow}>{clip(r.text, L.text).padEnd(L.text)}</Text>
275        <Text> </Text>
276        {bar(`bar${i}`, L.item, r.frac, mode)}
277        <Text>  </Text>
278        <Text>
279          <Text bold={isNow} color={isNow ? tone('work') : undefined} dimColor={r.kind === 'next' || r.kind === 'later' || r.kind === 'halted'}>{r.status}</Text>
280          {isNow && r.doing ? <Text dimColor>{` · ${clip(r.doing, inner >= 100 ? 40 : 16)}`}</Text> : null}
281        </Text>
282      </Box>
283    )
284  }
285
286  return (
287    <Box key="plain-view" flexDirection="column" borderStyle="round" borderColor={border} paddingX={1}>
288      <Box flexDirection="row" justifyContent="space-between">
289        {head}
290        <Text dimColor>{card.time}</Text>
291      </Box>
292      {requestRows()}
293      <Box flexDirection="row" justifyContent="space-between">
294        <Box flexDirection="row">
295          <Text dimColor>{clip(card.label, L.label).padEnd(L.label)}</Text>
296          {bar('total', L.bar, card.frac, pal === 'off' ? 'off' : pal)}
297        </Box>
298        <Text>
299          <Text bold color={tone(card.state)}>{card.pct}</Text>
300          {card.notice !== undefined ? <Text color="warning">{` · ${card.notice}`}</Text> : null}
301        </Text>
302      </Box>
303      {card.before !== undefined && <Text dimColor>{`  ${card.before}`}</Text>}
304      {card.rows.map(row)}
305      {card.after !== undefined && <Text dimColor>{`  ${card.after}`}</Text>}
306      {card.files !== undefined && <Text dimColor>{`  ${card.files}`}</Text>}
307      {answerLine(card.answer)}
308      {card.agents !== undefined && agentsLine(card.agents)}
309    </Box>
310  )
311}
312
hooks/palettes.ts 73 lines
1// The bar colors: the one place hex colors live (design guide, "Exception: gradients").
2// Each palette has a dark and a light set: g1 → g2 → g3 while the agent works (the bars run
3// g1 → g2, the title all three), k1 → k2 once the turn is done, `off` for a stopped bar, and
4// `track` for a bar's empty cells.
5
6export type PaletteId = 'claude' | 'clean' | 'sunset' | 'aurora' | 'ocean' | 'neon' | 'forest' | 'calm'
7
8export type Stops = { g1: number; g2: number; g3: number; k1: number; k2: number; off: number; track: number }
9
10export type Palette = {
11  id: PaletteId
12  /** What the colors are, in a few words, for /plain-view palette. */
13  hint: { 'pt-BR': string; en: string }
14  dark: Stops
15  light: Stops
16}
17
18const DARK_OFF = 0x5c5c68
19const DARK_TRACK = 0x5a5a6a
20const LIGHT_OFF = 0xa0a0aa
21const LIGHT_TRACK = 0xbdbdc6
22
23const set = (g1: number, g2: number, g3: number, k1: number, k2: number, isDark: boolean): Stops => ({
24  g1, g2, g3, k1, k2,
25  off: isDark ? DARK_OFF : LIGHT_OFF,
26  track: isDark ? DARK_TRACK : LIGHT_TRACK,
27})
28
29export const PALETTES: readonly Palette[] = [
30  { id: 'claude', hint: { 'pt-BR': 'terracota → âmbar → creme (marca)', en: 'terracotta → amber → cream (brand)' },
31    dark: set(0xd97757, 0xeaa25f, 0xf3d39b, 0x5fa86a, 0xb5dc8f, true), light: set(0xb4532f, 0xc97a22, 0xa8863a, 0x2e7d32, 0x5e9e3a, false) },
32  { id: 'clean', hint: { 'pt-BR': 'laranja → rosa → violeta (vídeo)', en: 'orange → pink → violet (video)' },
33    dark: set(0xf0915a, 0xe8577e, 0x9a7cf0, 0x3f9a54, 0x8fe0a6, true), light: set(0xc8622f, 0xc33a63, 0x6b4fd1, 0x2e7d32, 0x4caf68, false) },
34  { id: 'sunset', hint: { 'pt-BR': 'amarelo → laranja → vermelho', en: 'yellow → orange → red' },
35    dark: set(0xffd166, 0xf78c4b, 0xe0475b, 0x4caf7d, 0xa7e3a0, true), light: set(0xb7860b, 0xd1601f, 0xc0283f, 0x2e7d32, 0x4f9a45, false) },
36  { id: 'aurora', hint: { 'pt-BR': 'verde-água → azul → violeta', en: 'teal → blue → violet' },
37    dark: set(0x3dd6b5, 0x4aa8ff, 0x9a7cf0, 0x3dd6b5, 0xb6f2c9, true), light: set(0x0f8f78, 0x1f6feb, 0x6b4fd1, 0x0f8f78, 0x3a9d5d, false) },
38  { id: 'ocean', hint: { 'pt-BR': 'ciano → azul → anil', en: 'cyan → blue → indigo' },
39    dark: set(0x5ee7df, 0x3a8dde, 0x5b5bd6, 0x3fb6a8, 0x9be8c8, true), light: set(0x0e8f88, 0x1d5fb8, 0x3c3cb0, 0x0e7c6f, 0x2f9a6a, false) },
40  { id: 'neon', hint: { 'pt-BR': 'rosa-choque → roxo → ciano', en: 'hot pink → purple → cyan' },
41    dark: set(0xff4ecd, 0xa45cff, 0x3ee0ff, 0x39ff9f, 0xc6ffde, true), light: set(0xc4198f, 0x7a2fd6, 0x0a8fb0, 0x0f9a5a, 0x3cb57b, false) },
42  { id: 'forest', hint: { 'pt-BR': 'verde-escuro → folha → limão', en: 'deep green → leaf → lime' },
43    dark: set(0x2f9e6e, 0x8bd17c, 0xe5e27a, 0x2f9e6e, 0xc9f0a8, true), light: set(0x1d7a52, 0x4f9a3a, 0x8f8a12, 0x1d7a52, 0x4f9a3a, false) },
44  { id: 'calm', hint: { 'pt-BR': 'cinza → texto; verde só no fim', en: 'grey → text; green only at the end' },
45    dark: set(0x5c5c68, 0x8a8a98, 0xd4d4d8, 0x5f8f6a, 0x98c379, true), light: set(0xa0a0aa, 0x6b6b76, 0x1f1f24, 0x4f7d58, 0x2e7d32, false) },
46]
47
48export const DEFAULT_PALETTE: PaletteId = 'claude'
49
50/** The palette an option names, else the default. */
51export const paletteOf = (option: unknown): Palette =>
52  PALETTES.find(p => p.id === String(option ?? '').trim().toLowerCase()) ?? PALETTES.find(p => p.id === DEFAULT_PALETTE)!
53
54/** The palette's set for the person's theme: light when the theme's name says light, dark otherwise. */
55export const stopsOf = (p: Palette, theme: unknown): Stops => (/light/i.test(String(theme ?? '')) ? p.light : p.dark)
56
57/** A color `t` of the way from `a` to `b` (0..1), channel by channel. */
58export const mix = (a: number, b: number, t: number): number => {
59  const k = Math.max(0, Math.min(1, t))
60  const ch = (shift: number) => {
61    const x = (a >> shift) & 0xff
62    const y = (b >> shift) & 0xff
63    return Math.round(x + (y - x) * k) << shift
64  }
65  return ch(16) | ch(8) | ch(0)
66}
67
68/** `#rrggbb`, what a Text's color takes. */
69export const hex = (c: number) => `#${c.toString(16).padStart(6, '0')}`
70
71/** The title's color at `x` (0..1) of its length: g1 → g2 → g3. */
72export const titleColor = (s: Stops, x: number) => (x < 0.5 ? mix(s.g1, s.g2, x * 2) : mix(s.g2, s.g3, (x - 0.5) * 2))
73
hooks/plan.ts 730 lines
1// The plan card's logic, with no `$`: the agent's task list from its tool calls, the estimate of
2// the current step, what the turn touched, the agents the main loop spawned, and the card as
3// plain data that card.tsx draws.
4
5import type { Agent, AgentText, End, Item, RequestLine, Turn } from '../types'
6import { phraseOf } from './phrases'
7import type { Lang } from './ui'
8import { clip, elapsed } from './ui'
9import { WORDS } from './words'
10
11/** Tools whose rows plain-view never hides: the agent's questions, its plan and its helpers. */
12export const NEVER_HIDDEN: readonly string[] = ['AskUserQuestion', 'ExitPlanMode', 'EnterPlanMode', 'Agent', 'Task']
13
14/** The tools that write the agent's task list. */
15export const TASK_TOOLS: readonly string[] = ['TaskCreate', 'TaskUpdate', 'TodoWrite']
16
17const CHANGES = ['Edit', 'MultiEdit', 'Write', 'NotebookEdit']
18
19/** Tool calls a step is guessed to take before any step has finished. */
20export const DEFAULT_CALLS = 4
21
22/** The highest estimate a step shows before its task is marked done. */
23export const MAX_ESTIMATE = 0.95
24
25/** Seconds the first step (understanding the request) is guessed to take. */
26export const FIRST_STEP_SECONDS = 10
27
28/** A plan of more than this many tasks shows a window of WINDOW around the current one. */
29export const WINDOW = 5
30
31type Input = Readonly<Record<string, unknown>>
32const str = (v: unknown) => (typeof v === 'string' ? v.trim() : '')
33const isStatus = (s: unknown): s is Item['status'] => s === 'pending' || s === 'in_progress' || s === 'completed'
34
35/** A harness notification's opening tag, such as `<task-notification>`: an XML-like tag. */
36const NOTICE = /^<([a-zA-Z][\w-]*)[\s>]/
37
38const firstLine = (text: string) => text.split('\n').map(l => l.trim()).find(l => l !== '') ?? ''
39
40/**
41 * The turn's text without the harness notifications it starts with: each one up to its closing
42 * tag, or its line when it has none. A request sent with a notification follows them.
43 */
44const requestOf = (text: string) => {
45  let rest = text.trimStart()
46  for (let m = NOTICE.exec(rest); m; m = NOTICE.exec(rest)) {
47    const close = rest.indexOf(`</${m[1]}>`)
48    const end = rest.indexOf('\n')
49    rest = (close >= 0 ? rest.slice(close + m[1]!.length + 3) : end >= 0 ? rest.slice(end + 1) : '').trimStart()
50  }
51  return rest
52}
53
54/** Whether a turn's text is only a harness notification (a background agent finished), with no request. */
55const isNotice = (text: string) => NOTICE.test(text.trimStart()) && requestOf(text) === ''
56
57/** The request's first line, for the card's title; none when the turn holds only a notification. */
58export const titleOf = (text: string) => firstLine(requestOf(text))
59
60/**
61 * The request's lines for the card: the turn's text past its notifications, each non-blank line
62 * trimmed, and a fenced code block as one line that counts its lines (`{ code: 4 }`). Fences
63 * open and close as in checklistOf (fenceOf, closes).
64 */
65export const requestLinesOf = (text: string): RequestLine[] => {
66  const lines: RequestLine[] = []
67  let fence: Fence | null = null
68  let code = 0
69  for (const raw of requestOf(text).split('\n')) {
70    if (fence) {
71      if (closes(raw, fence)) {
72        lines.push({ code })
73        fence = null
74      } else code++
75      continue
76    }
77    const opened = indentOf(raw) <= 3 ? fenceOf(raw, false) : null
78    if (opened) {
79      fence = opened
80      code = 0
81      continue
82    }
83    const line = raw.trim().replace(/\s+/g, ' ')
84    if (line) lines.push(line)
85  }
86  // A fence left open still counts what it held.
87  if (fence) lines.push({ code })
88  return lines
89}
90
91/**
92 * A new turn: a fresh card, and the task list kept only while some task is still open. A new
93 * request puts an open checklist read from the text to sleep (`dormant`): not drawn, it counts
94 * no call, and wakes only when an answer writes one of its tasks again (wake).
95 */
96export const startTurn = (prev: Turn | null, items: Item[], text: string, now: number, lang: Lang): { turn: Turn; items: Item[]; dormant: Item[] } => {
97  // A notification, or a continuation with no text, keeps the last request's title and lines.
98  const isRequest = titleOf(text) !== ''
99  const title = titleOf(text) || prev?.title || (isNotice(text) ? WORDS[lang].agentDone : WORDS[lang].untitled)
100  const lines = isRequest ? requestLinesOf(text) : (prev?.lines ?? [])
101  // A demo's sample list never carries into a real request.
102  const open = !prev?.isDemo && items.some(i => i.status !== 'completed')
103  // A notification or a continuation goes on with the request before it: its checklist stays awake.
104  const isAsleep = open && isRequest && items.some(i => i.fromText)
105  return {
106    turn: { title, startedAt: now, calls: 0, changed: [], read: [], ...(lines.length > 1 || lines.some(l => typeof l !== 'string') ? { lines } : {}) },
107    items: open && !isAsleep ? items : [],
108    dormant: isAsleep ? items : [],
109  }
110}
111
112/** How often, at most, the ticker asks $.agent.list() about an agent whose end it may have missed. */
113export const LIST_MS = 2000
114
115/** An agent $.agent.list() no longer names this long after it started counts as ended. */
116export const GONE_MS = 10_000
117
118/** The statuses $.agent.list() gives an agent that ended. */
119const ENDED: readonly string[] = ['completed', 'failed', 'killed']
120
121/** The agents a turn starts with: a request keeps the running ones, a notification keeps them all. */
122export const keepAgents = (list: readonly Agent[], text: string): Agent[] =>
123  isNotice(text) ? [...list] : list.filter(a => a.endedAt === undefined)
124
125/** One more agent of the main loop, as agent.spawn answered it. */
126export const spawnAgent = (list: readonly Agent[], id: string, label: string, now: number): Agent[] =>
127  list.some(a => a.id === id) ? [...list] : [...list, { id, label, startedAt: now }]
128
129/** The agent's run ended (its turn.complete). */
130export const finishAgent = (list: readonly Agent[], id: string, now: number): Agent[] =>
131  list.map(a => (a.id === id && a.endedAt === undefined ? { ...a, endedAt: now } : a))
132
133/**
134 * The agents after a look at $.agent.list(): one it lists as completed, failed or killed ended,
135 * and so did one it no longer names GONE_MS after it started (its task dropped).
136 */
137export const reconcileAgents = (list: readonly Agent[], listed: readonly { id: string; status: string }[], now: number): Agent[] =>
138  list.map(a => {
139    if (a.endedAt !== undefined) return a
140    const l = listed.find(x => x.id === a.id)
141    const isOver = l ? ENDED.includes(l.status) : now - a.startedAt >= GONE_MS
142    return isOver ? { ...a, endedAt: now } : a
143  })
144
145/** The agents still running. */
146export const runningOf = (list: readonly Agent[]) => list.filter(a => a.endedAt === undefined)
147
148/** The card's agents row: how many run (or finished), the latest one's label, and the time since the oldest running one started. */
149export type AgentsRow = { isRunning: boolean; text: string; label: string; time?: string }
150
151/** The agents row, or none when no agent ran this request. Never tokens or cost: those are agent-watch's. */
152export const agentsRowOf = (list: readonly Agent[], now: number, lang: Lang): AgentsRow | undefined => {
153  if (list.length === 0) return undefined
154  const w = WORDS[lang]
155  const running = runningOf(list)
156  if (running.length > 0) {
157    const latest = running.reduce((a, b) => (b.startedAt >= a.startedAt ? b : a))
158    const oldest = Math.min(...running.map(a => a.startedAt))
159    return { isRunning: true, text: w.agentsRunning(running.length), label: latest.label, time: elapsed(now - oldest) }
160  }
161  const latest = list.reduce((a, b) => ((b.endedAt ?? 0) >= (a.endedAt ?? 0) ? b : a))
162  return { isRunning: false, text: w.agentsFinished(list.length), label: latest.label }
163}
164
165/** The index of the task being worked on: the first in progress, else the first pending; -1 when all are done. */
166export const currentOf = (items: readonly Item[]) => {
167  const busy = items.findIndex(i => i.status === 'in_progress')
168  return busy >= 0 ? busy : items.findIndex(i => i.status === 'pending')
169}
170
171/** A new list that keeps the tool calls the old one counted, matched by subject, else by place. */
172const keepCalls = (old: readonly Item[], next: Item[]): Item[] =>
173  next.map((it, i) => {
174    const kept = old.find(o => o.subject === it.subject) ?? old[i]
175    return kept ? { ...it, calls: kept.calls } : it
176  })
177
178const CHECK = /^\s*(?:\d+[.)]|[-*+])\s+\[([ xX~>\-])\]\s+(.+?)\s*$/
179
180/** A list item of any kind, checklist or not. */
181const LIST = /^\s*(?:\d+[.)]|[-*+])\s/
182
183/** A code fence's line: three or more backticks or tildes, then an info string or nothing. */
184const FENCE = /^[ \t]*(`{3,}|~{3,})(.*)$/
185
186/** A blockquote's line. */
187const QUOTE = /^ {0,3}>/
188
189/** A line's indent in columns, a tab reaching the next multiple of 4. */
190const indentOf = (line: string) => {
191  let col = 0
192  for (const c of line) {
193    if (c === ' ') col++
194    else if (c === '\t') col += 4 - (col % 4)
195    else break
196  }
197  return col
198}
199
200/** An open code fence: its mark, its length, and whether it sits in a list (any indent closes it then). */
201type Fence = { char: string; size: number; isNested: boolean }
202
203/** The fence a line opens, or none: a backtick fence's info string holds no backtick. */
204const fenceOf = (line: string, isNested: boolean): Fence | null => {
205  const m = FENCE.exec(line)
206  if (!m || (m[1]![0] === '`' && m[2]!.includes('`'))) return null
207  return { char: m[1]![0]!, size: m[1]!.length, isNested }
208}
209
210/** Whether a line closes the fence: the same mark, at least as long, and only spaces after it. */
211const closes = (line: string, fence: Fence) => {
212  const m = FENCE.exec(line)
213  const isPlaced = fence.isNested || indentOf(line) <= 3
214  return !!m && isPlaced && m[1]![0] === fence.char && m[1]!.length >= fence.size && m[2]!.trim() === ''
215}
216
217/**
218 * A checklist the agent wrote in its answer (`1. [ ] Ler a API`, `- [x] Montar o painel`), as a
219 * task list: `[x]` done, `[~]` `[>]` `[-]` in progress, `[ ]` pending. Null under `min` items.
220 * A checklist the answer quotes is not the plan: one in a fenced code block (an unclosed fence
221 * runs to the end), a blockquote, or an indented code block.
222 */
223export const checklistOf = (text: string, min = 2): Item[] | null => {
224  // The last run of checklist lines: blank lines may sit inside it, other text ends it.
225  let items: Item[] = []
226  let isOpen = false
227  let fence: Fence | null = null
228  // Inside a list, an indented line belongs to the list (a nested checklist); outside one, 4
229  // columns of indent make an indented code block. A line at column 0 that is no item ends the list.
230  let isInList = false
231  for (const line of text.split('\n')) {
232    if (fence) {
233      if (closes(line, fence)) fence = null
234      continue
235    }
236    if (line.trim() === '') continue
237    const indent = indentOf(line)
238    const isNested = isInList && indent > 0
239    const opened = indent <= 3 || isNested ? fenceOf(line, isNested) : null
240    const isQuoted = !opened && (QUOTE.test(line) || (indent >= 4 && !isNested))
241    if (opened || isQuoted) {
242      fence = opened
243      isOpen = false
244      isInList = isNested
245      continue
246    }
247    isInList = isNested || LIST.test(line)
248    const m = CHECK.exec(line)
249    if (!m) {
250      isOpen = false
251      continue
252    }
253    if (!isOpen) items = []
254    isOpen = true
255    const subject = m[2]!.replace(/[*_`]/g, '').trim()
256    if (!subject) continue
257    const mark = m[1]!.toLowerCase()
258    items.push({ subject, status: mark === 'x' ? 'completed' : mark === ' ' ? 'pending' : 'in_progress', calls: 0, fromText: true })
259  }
260  return items.length >= min ? items : null
261}
262
263/** Whether two task subjects name the same task: equal once markdown, spaces and case are gone. */
264const sameTask = (a: string, b: string) => normalize(a).toLowerCase() === normalize(b).toLowerCase()
265
266/**
267 * The list after an answer of the agent, unless a task tool keeps the list. A checklist shorter
268 * than the list that names some of its tasks ticks them off and keeps the rest (the agent listed
269 * what it just did); a checklist as long or longer, or one that shares no task, is the list now.
270 * Once a text list is open, one line is enough to tick its task (`- [x] Ler a API`), but only a
271 * line that names a task of the list: a lone line never replaces the list.
272 */
273export const applyAnswer = (items: Item[], answer: string): Item[] => {
274  if (items.some(i => !i.fromText)) return items
275  const list = checklistOf(answer, items.length > 0 ? 1 : 2)
276  if (!list) return items
277  const isPart = list.length < items.length && list.some(n => items.some(o => sameTask(o.subject, n.subject)))
278  if (list.length === 1 && !isPart) return items
279  if (!isPart) return keepCalls(items, list)
280  return items.map(o => {
281    const n = list.find(x => sameTask(x.subject, o.subject))
282    return n ? { ...o, status: n.status } : o
283  })
284}
285
286/**
287 * The list after an answer, with the checklist the last request left asleep: a checklist that
288 * shares a task with it, while the turn has no list, wakes it (applyAnswer against it, so its
289 * calls and ticks carry); any other checklist is the list, and the sleeping one is dropped.
290 */
291export const wake = (items: Item[], dormant: Item[], answer: string): { items: Item[]; dormant: Item[] } => {
292  const list = checklistOf(answer)
293  if (!list || dormant.length === 0) return { items: applyAnswer(items, answer), dormant }
294  const isSame = items.length === 0 && list.some(n => dormant.some(o => sameTask(o.subject, n.subject)))
295  return { items: applyAnswer(isSame ? dormant : items, answer), dormant: [] }
296}
297
298/** The task list after a task tool's call: TaskCreate adds (with the id its result gave), TaskUpdate changes, TodoWrite replaces. */
299export const applyTask = (from: Item[], tool: string, input: Input, result?: unknown): Item[] => {
300  // A task tool takes over from a checklist read in the text.
301  const items = from.some(i => i.fromText) ? [] : from
302  if (tool === 'TaskCreate') {
303    const task = (result as { task?: { id?: unknown } } | undefined)?.task
304    const subject = str(input.subject)
305    if (!subject) return items
306    const item: Item = { subject, status: 'pending', calls: 0 }
307    if (typeof task?.id === 'string') item.id = task.id
308    return [...items, item]
309  }
310  if (tool === 'TaskUpdate') {
311    const id = str(input.taskId)
312    const at = items.findIndex(i => i.id === id)
313    if (at < 0) return from
314    if (input.status === 'deleted') return items.filter((_, i) => i !== at)
315    const was = items[at]!
316    const next: Item = { ...was }
317    if (isStatus(input.status)) next.status = input.status
318    if (str(input.subject)) next.subject = str(input.subject)
319    return items.map((it, i) => (i === at ? next : it))
320  }
321  if (tool === 'TodoWrite') {
322    const todos = Array.isArray(input.todos) ? input.todos : []
323    const list = todos
324      .filter((t): t is Record<string, unknown> => typeof t === 'object' && t !== null && str((t as Record<string, unknown>).content) !== '')
325      .map((t): Item => ({ subject: str(t.content), status: isStatus(t.status) ? t.status : 'pending', calls: 0 }))
326    return keepCalls(items, list)
327  }
328  return from
329}
330
331/** One more tool call for the task being worked on. */
332export const countCall = (items: Item[]): Item[] => {
333  const at = currentOf(items)
334  return at < 0 ? items : items.map((it, i) => (i === at ? { ...it, calls: it.calls + 1 } : it))
335}
336
337/**
338 * What a call is doing, for the card: phraseOf's words, but a Bash call by its own description
339 * (the model's words, in its language), a skill by name, and any other tool as `usando X`.
340 */
341export const doingOf = (tool: string, input: Input, lang: Lang): string => {
342  const w = WORDS[lang]
343  if (tool === 'Bash' && str(input.description)) return clip(str(input.description), 50)
344  if (tool === 'Skill' && str(input.skill)) return w.usingSkill(clip(str(input.skill), 30))
345  if (KNOWN.includes(tool)) return phraseOf(tool, input, lang)
346  return w.using(clip(tool.startsWith('mcp__') ? (tool.split('__').pop() ?? tool) : tool, 30))
347}
348
349const KNOWN = ['Bash', 'Read', 'Write', 'Edit', 'MultiEdit', 'Grep', 'Glob', 'WebFetch', 'WebSearch', 'Agent']
350
351/** A shell word with its quotes gone; `''` stays an empty word. */
352const unquote = (w: string) => (/^(["']).*\1$/s.test(w) ? w.slice(1, -1) : w)
353
354/** The command's lines without the bodies of its heredocs (`<<EOF` ... `EOF`): those are data, not commands. */
355const withoutHeredocs = (command: string) => {
356  const kept: string[] = []
357  let until: string | undefined
358  for (const line of command.split('\n')) {
359    if (until !== undefined) {
360      if (line.trim() === until) until = undefined
361      continue
362    }
363    kept.push(line)
364    until = /(?<!<)<<-?(?!<)\s*["']?(\w+)["']?/.exec(line)?.[1]
365  }
366  return kept.join('\n')
367}
368
369/** A path the command names for sure: not a device, a variable, a glob or a substitution. */
370const isPath = (w: string) => w !== '' && !w.startsWith('-') && !w.startsWith('/dev/') && !/[$`*?{}()<>|;&]/.test(w)
371
372/** The files one simple command writes in place: `sed -i`, `perl -i` / `-pi`, `tee`. */
373const inPlace = (words: string[]): string[] => {
374  while (words[0] === 'sudo' || words[0] === 'command' || /^\w+=/.test(words[0] ?? '')) words = words.slice(1)
375  const name = (words[0] ?? '').split('/').pop()
376  const args = words.slice(1)
377  if (name === 'tee') return args.filter(isPath)
378  if (name !== 'sed' && name !== 'gsed' && name !== 'perl') return []
379  const flag = name === 'perl' ? /^-[a-zA-Z]*i/ : /^(?:-[a-zA-Z]*i|--in-place)/
380  if (!args.some(a => flag.test(a))) return []
381  // The script comes with -e (or -f), else it is the first word that is not an option.
382  const takesNext = (a: string) => (name === 'perl' ? /^-[a-zA-Z]*[eE]$/.test(a) : a === '-e' || a === '-f' || a === '--expression' || a === '--file')
383  const plain: string[] = []
384  let hasScript = false
385  for (let i = 0; i < args.length; i++) {
386    const a = args[i]!
387    if (takesNext(a)) {
388      hasScript = true
389      i++
390    } else if (name !== 'perl' && a === '-i' && args[i + 1] === '') i++ // BSD sed: -i '' (no backup)
391    else if (!a.startsWith('-')) plain.push(a)
392  }
393  return (hasScript ? plain : plain.slice(1)).filter(isPath)
394}
395
396/**
397 * The files a shell command writes, read from its text without running it: in-place edits
398 * (`sed -i`, `perl -pi`, `tee`) and output redirects (`> file`, `>> file`). Not `python -c` or a
399 * script: what those write cannot be read from the command.
400 */
401export const shellWrites = (command: string): string[] => {
402  // Quoted strings step aside first, so a `;`, `|` or `>` inside one splits or redirects nothing.
403  const quoted: string[] = []
404  const masked = withoutHeredocs(command).replace(/"[^"]*"|'[^']*'/g, q => `\0${quoted.push(q) - 1}\0`)
405  const word = (w: string) => unquote(w.replace(/\0(\d+)\0/g, (_, i: string) => quoted[Number(i)]!))
406  const files: string[] = []
407  for (const part of masked.split(/&&|\|\||[;|\n]/)) {
408    files.push(...inPlace((part.match(/\S+/g) ?? []).map(word)))
409    // Redirects of the output: `> f`, `>> f`, `1> f`, `&> f`; not `2> f` or `>&2`.
410    for (const m of part.matchAll(/(?:^|[^\d&<>])(?:1|&)?>>?(?!&)\s*([^\s;&|<>]+)/g)) {
411      const target = word(m[1]!)
412      if (isPath(target)) files.push(target)
413    }
414  }
415  return [...new Set(files)]
416}
417
418/** The list with one more file, unless it names it already, as a full or a relative path. */
419const withFile = (list: readonly string[], file: string) =>
420  list.some(f => f === file || f.endsWith(`/${file}`) || file.endsWith(`/${f}`)) ? [...list] : [...list, file]
421
422/** The turn after a tool call on the main loop: what it is doing, and the files it changed or read. */
423export const touch = (turn: Turn, tool: string, input: Input, lang: Lang, ok: boolean | null): Turn => {
424  const file = str(input.file_path) || str(input.notebook_path)
425  const next: Turn = { ...turn }
426  if (ok === null) {
427    next.calls = turn.calls + 1
428    next.doing = doingOf(tool, input, lang)
429    return next
430  }
431  if (!ok) return next
432  if (tool === 'Bash') next.changed = shellWrites(str(input.command)).reduce(withFile, turn.changed)
433  if (file && CHANGES.includes(tool)) next.changed = withFile(turn.changed, file)
434  if (file && tool === 'Read') next.read = withFile(turn.read, file)
435  return next
436}
437
438/** The turn once it ended, with its answer's first sentence when it gave one. */
439export const endTurn = (turn: Turn, reason: string, now: number, answer = ''): Turn => {
440  const end: End = reason === 'answer' ? 'answer' : reason === 'aborted' ? 'aborted' : 'error'
441  const { doing: _, ...rest } = turn
442  const first = firstSentence(answer)
443  return { ...rest, endedAt: now, end, ...(first ? { answer: first } : {}) }
444}
445
446/** The `agentText` option; `final` when it names none. */
447export const agentTextOf = (option: unknown): AgentText =>
448  option === 'none' || option === 'card' || option === 'all' ? option : 'final'
449
450/** Text with its markdown marks and runs of space gone, to compare a block with an answer. */
451export const normalize = (text: string) => text.replace(/[*_`#>]/g, '').replace(/\s+/g, ' ').trim()
452
453/** The first sentence of an answer, plain, up to 100 characters. */
454export const firstSentence = (answer: string) => {
455  const line = answer.split('\n').map(l => l.trim()).find(l => l !== '') ?? ''
456  const flat = normalize(line.replace(/^(?:\d+[.)]|[-*+])\s+/, ''))
457  // A sentence of at least 12 characters: `1.` or `e.g.` does not end one.
458  const m = /^(.{11,}?[.!?])(\s|$)/.exec(flat)
459  return clip(m ? m[1]! : flat, 100)
460}
461
462/** Mid-turn texts kept to hide their blocks under `final`: the last 200. Older ones show again. */
463export const MID_KEPT = 200
464
465/**
466 * Whether an assistant block shows. Under `final`, a block hides only when its text is known to
467 * be mid-turn (the text of a step that went on to call tools); anything else shows, so a final
468 * answer, an old turn or a resumed session is never hidden by mistake.
469 */
470export const showsBlock = (mode: AgentText, text: string, mids: ReadonlySet<string> | readonly string[]) => {
471  if (mode === 'all') return true
472  if (mode !== 'final') return false
473  const block = normalize(text)
474  if (block === '') return true
475  const list = [...mids]
476  return !(list.includes(block) || list.some(m => m.includes(block)))
477}
478
479/**
480 * The current step's estimate, 0 to MAX_ESTIMATE: its tool calls against the average of the
481 * finished steps (DEFAULT_CALLS before any). It is a guess, so the card shows it with `~`.
482 */
483export const estimate = (items: readonly Item[], at: number): number => {
484  const item = items[at]
485  if (!item) return 0
486  return Math.min(MAX_ESTIMATE, item.calls / Math.max(1, averageCalls(items)))
487}
488
489/** A text list is stale when its step has made this many times the average of the finished steps. */
490export const STALE_FACTOR = 3
491
492/** Calls between two reminders to the model, and the most it gets for one step. */
493export const NUDGE_EVERY = 10
494export const NUDGE_MAX = 3
495
496/**
497 * The average tool calls of the finished steps (DEFAULT_CALLS before any). A step that went
498 * stale stays out of it: its calls were not progress, and would make the next step look slow.
499 */
500const averageCalls = (items: readonly Item[]): number => {
501  const finished = items.filter(i => i.status === 'completed' && i.calls > 0 && i.calls <= STALE_FACTOR * DEFAULT_CALLS)
502  return finished.length ? finished.reduce((n, i) => n + i.calls, 0) / finished.length : DEFAULT_CALLS
503}
504
505/** The calls a step may make before its list counts as stale. */
506export const staleAfter = (items: readonly Item[]): number => Math.ceil(STALE_FACTOR * averageCalls(items))
507
508/**
509 * Whether the list of the current step has gone stale: it came from the agent's text, and the
510 * step has made far more calls than the finished ones, so the agent most likely stopped writing
511 * the checklist. A task tool's list is the agent's own marking, so it is never called stale.
512 */
513export const isStale = (items: readonly Item[], at: number): boolean => {
514  const item = items[at]
515  return item?.fromText === true && item.calls > staleAfter(items)
516}
517
518/**
519 * Whether the call that just made the step's count what it is should carry a reminder: the call
520 * that crosses the limit, then every NUDGE_EVERY calls, NUDGE_MAX times at most per step.
521 */
522export const isNudgeDue = (items: readonly Item[], at: number): boolean => {
523  if (!isStale(items, at)) return false
524  const past = items[at]!.calls - staleAfter(items) - 1
525  return past % NUDGE_EVERY === 0 && past / NUDGE_EVERY < NUDGE_MAX
526}
527
528/** What a task row shows: done, the one now, the next one, later ones, or the one a stop left. */
529export type RowKind = 'done' | 'now' | 'next' | 'later' | 'halted'
530
531export type Row = { kind: RowKind; text: string; frac: number; status: string; doing?: string }
532
533/** The card as data. `state`: working, done (the turn answered) or stopped (interrupted or an error). */
534export type Card =
535  | {
536      kind: 'plan'
537      state: 'work' | 'done' | 'stopped'
538      title: string
539      badge?: string
540      time: string
541      label: string
542      frac: number
543      pct: string
544      /** `lista parada`, next to the figure: the text list stopped moving, so the bar counts only finished steps. */
545      notice?: string
546      rows: Row[]
547      /** `✓ mais 3 feitos` above a long plan's window, `○ mais 2 depois` below it. */
548      before?: string
549      after?: string
550      files?: string
551      /** The answer's first sentence, under `agentText: card`. */
552      answer?: string
553      agents?: AgentsRow
554      request?: RequestView
555    }
556  | { kind: 'phrase'; title: string; time: string; doing: string; agents?: AgentsRow; request?: RequestView }
557  /** The main turn ended with no task list and an agent still runs: `Esperando 1 agente`. */
558  | { kind: 'waiting'; title: string; time: string; text: string; agents: AgentsRow; request?: RequestView }
559  /** A turn with no task list that called tools or agents ended: a small card with badge, time and files. */
560  | { kind: 'summary'; state: 'done' | 'stopped'; title: string; badge: string; time: string; detail?: string; answer?: string; request?: RequestView }
561
562/** The `request` option: how much of a request of several lines the card's title shows. */
563export type RequestMode = 'line' | 'joined' | 'auto' | 'all'
564
565/** The `request` option; `line` when it names none. */
566export const requestModeOf = (option: unknown): RequestMode => (option === 'joined' || option === 'auto' || option === 'all' ? option : 'line')
567
568/** The most request lines the card draws under its title (`all`, or unfolded); the rest is `+N linhas`. */
569export const REQUEST_ROWS = 10
570
571/**
572 * The request's lines under the card's title: the rows shown, the lines left out, whether it is
573 * unfolded, whether the button would show more (`joined` asks the card: only when the line is cut).
574 */
575export type RequestView = { rest: string[]; more: number; isOpen: boolean; isJoined: boolean; canOpen: boolean }
576
577/** A line as the card draws it: a code block as `⟨código · 4 linhas⟩`. */
578const lineText = (line: RequestLine, lang: Lang) => (typeof line === 'string' ? line : WORDS[lang].codeLines(line.code))
579
580const LIST_MARK = /^(?:\d+[.)]|[-*+])\s+/
581
582/** A line of three words or more; `isProse` asks for one that is not a list item either (`1. sim`). */
583const isSentence = (line: RequestLine, isProse: boolean) =>
584  typeof line === 'string' && !(isProse && LIST_MARK.test(line)) && line.replace(LIST_MARK, '').split(' ').length >= 3
585
586/**
587 * The card's title and the request's lines under it, as `request` says: `line` the first line and
588 * a count of the rest; `auto` the first line of prose (a list item only when there is none) and a count; `joined` all of
589 * them in one line; `all` every line. Unfolded (the card's button), every line. Under the title,
590 * REQUEST_ROWS lines at most.
591 */
592export const requestViewOf = (turn: Turn, mode: RequestMode, isOpen: boolean, lang: Lang): { title: string; request?: RequestView } => {
593  const lines = (turn.lines ?? []).map(l => lineText(l, lang))
594  if (lines.length === 0) return { title: turn.title }
595  if (lines.length === 1) return { title: lines[0]! }
596  if (isOpen || mode === 'all') {
597    const rest = lines.slice(1, 1 + REQUEST_ROWS)
598    return { title: lines[0]!, request: { rest, more: lines.length - 1 - rest.length, isOpen, isJoined: false, canOpen: isOpen } }
599  }
600  if (mode === 'joined') return { title: lines.join(' · '), request: { rest: [], more: 0, isOpen, isJoined: true, canOpen: false } }
601  // auto: the first line of prose, else the first list item that reads as a sentence, else the first line.
602  const all = turn.lines ?? []
603  const prose = all.findIndex(l => isSentence(l, true))
604  const at = mode === 'auto' ? Math.max(0, prose >= 0 ? prose : all.findIndex(l => isSentence(l, false))) : 0
605  return { title: lines[at]!, request: { rest: [], more: lines.length - 1, isOpen, isJoined: false, canOpen: true } }
606}
607
608/** The rows a long plan shows: WINDOW of them around the current one. */
609export const windowAround = (total: number, at: number): { start: number; end: number } => {
610  if (total <= WINDOW + 1) return { start: 0, end: total }
611  const start = Math.max(0, Math.min(total - WINDOW, at - 1))
612  return { start, end: start + WINDOW }
613}
614
615/**
616 * The card for a turn, or null when there is none to show: no turn, or a turn with no list that
617 * ended with no tool call and no agent (a plain conversation). `agents` are the main loop's.
618 */
619export const cardOf = (
620  turn: Turn | null,
621  items: readonly Item[],
622  now: number,
623  lang: Lang,
624  withAnswer = false,
625  agents: readonly Agent[] = [],
626  view: { mode: RequestMode; isOpen: boolean } = { mode: 'line', isOpen: false },
627): Card | null => {
628  if (!turn) return null
629  const w = WORDS[lang]
630  const head = requestViewOf(turn, view.mode, view.isOpen, lang)
631  const req = head.request ? { request: head.request } : {}
632  const span = elapsed((turn.endedAt ?? now) - turn.startedAt)
633  const isOver = turn.end !== undefined
634  const team = agentsRowOf(agents, now, lang)
635
636  // No task list yet: the two first steps until the agent calls a tool, then the tool's phrase.
637  if (items.length === 0) {
638    if (isOver) {
639      // The main turn ended with an agent running: the card waits for it.
640      const running = runningOf(agents).length
641      if (running > 0 && team) return { kind: 'waiting', title: head.title, time: elapsed(now - turn.startedAt), text: w.waiting(running), agents: team, ...req }
642      if (turn.calls === 0 && agents.length === 0) return null
643      const isDone = turn.end === 'answer'
644      const touched = turn.changed.length + turn.read.length > 0 ? w.files(turn.changed.length, turn.read.length) : ''
645      const detail = [touched, agents.length > 0 ? w.agents(agents.length) : ''].filter(x => x !== '').join(' · ')
646      return {
647        kind: 'summary',
648        state: isDone ? 'done' : 'stopped',
649        title: head.title,
650        badge: isDone ? w.ready : turn.end === 'aborted' ? w.interrupted : w.stopped,
651        time: isDone ? w.took(span) : w.stoppedAt(span),
652        ...(detail ? { detail } : {}),
653        ...(withAnswer && isDone && turn.answer ? { answer: turn.answer } : {}),
654        ...req,
655      }
656    }
657    if (turn.calls > 0) return { kind: 'phrase', title: head.title, time: span, doing: capital(turn.doing ?? ''), ...(team ? { agents: team } : {}), ...req }
658    const est = Math.min(0.9, (now - turn.startedAt) / 1000 / FIRST_STEP_SECONDS)
659    const rows: Row[] = [
660      { kind: 'now', text: w.first[0], frac: est, status: `~${Math.round(est * 100)}%` },
661      { kind: 'next', text: w.first[1], frac: 0, status: w.next },
662    ]
663    return { kind: 'plan', state: 'work', title: head.title, time: span, label: w.step(1, 2), frac: est / 2, pct: pct(est / 2), rows, ...(team ? { agents: team } : {}), ...req }
664  }
665
666  const total = items.length
667  const completed = items.filter(i => i.status === 'completed').length
668  const at = currentOf(items)
669  const state = turn.end === undefined ? 'work' : turn.end === 'answer' ? 'done' : 'stopped'
670  const est = state === 'work' && at >= 0 ? estimate(items, at) : 0
671  // A text list that stopped moving: the step's guess is gone (its calls were not progress).
672  const stale = state === 'work' && at >= 0 && isStale(items, at)
673  const frac = (completed + (stale ? 0 : est)) / total
674  const { start, end } = windowAround(total, at < 0 ? total - 1 : at)
675
676  const rows: Row[] = items.slice(start, end).map((it, j) => {
677    const i = start + j
678    if (it.status === 'completed') return { kind: 'done', text: it.subject, frac: 1, status: w.done }
679    if (i === at) {
680      if (state === 'stopped') return { kind: 'halted', text: it.subject, frac: Math.max(0.05, estimate(items, i)), status: w.halted }
681      // The turn answered with this task open: it waits, nothing stopped it.
682      if (state === 'done') return { kind: 'later', text: it.subject, frac: 0, status: w.leftOpen }
683      if (stale) return { kind: 'now', text: it.subject, frac: 0, status: w.staleFor(it.calls), doing: turn.doing }
684      return { kind: 'now', text: it.subject, frac: est, status: `~${Math.round(est * 100)}%`, doing: turn.doing }
685    }
686    return { kind: i === at + 1 ? 'next' : 'later', text: it.subject, frac: 0, status: i === at + 1 ? w.next : w.later }
687  })
688  // The rows outside the window, named by what they are: all done, or a count above or below.
689  const outside = (list: readonly Item[], done: (n: number) => string, other: (n: number) => string) =>
690    list.length === 0 ? undefined : list.every(i => i.status === 'completed') ? done(list.length) : other(list.length)
691  const before = outside(items.slice(0, start), w.moreDone, w.moreBefore)
692  const after = outside(items.slice(end), w.moreDone, w.moreAfter)
693
694  const badge = state === 'done' ? (completed === total ? w.allDone : w.turnDone) : state === 'stopped' ? (turn.end === 'aborted' ? w.interrupted : w.stopped) : undefined
695  const touched = turn.changed.length + turn.read.length > 0 ? w.files(turn.changed.length, turn.read.length) : undefined
696  return {
697    kind: 'plan',
698    state,
699    title: head.title,
700    ...(badge ? { badge } : {}),
701    time: state === 'done' ? w.took(span) : state === 'stopped' ? w.stoppedAt(span) : span,
702    label: state === 'done' && completed === total ? w.steps(total, total) : w.step(Math.min(total, (at < 0 ? total - 1 : at) + 1), total),
703    frac,
704    pct: pct(frac),
705    ...(stale ? { notice: w.stale } : {}),
706    rows,
707    ...(before ? { before } : {}),
708    ...(after ? { after } : {}),
709    ...(isOver && touched ? { files: touched } : {}),
710    ...(withAnswer && state === 'done' && turn.answer ? { answer: turn.answer } : {}),
711    ...(team ? { agents: team } : {}),
712    ...req,
713  }
714}
715
716const pct = (f: number) => `${Math.round(f * 100)}%`
717const capital = (s: string) => (s ? s[0]!.toUpperCase() + s.slice(1) : s)
718
719/** The sample turn /plain-view demo shows: step `step` of the four, `now` the time it shows. */
720export const demoOf = (step: number, startedAt: number, lang: Lang): { turn: Turn; items: Item[] } => {
721  const w = WORDS[lang]
722  const items: Item[] = w.demoTasks.map((subject, i) => ({
723    subject,
724    status: i < step ? 'completed' : i === step ? 'in_progress' : 'pending',
725    calls: i < step ? DEFAULT_CALLS : i === step ? 2 : 0,
726  }))
727  const turn: Turn = { title: w.demoTitle, startedAt, calls: step * DEFAULT_CALLS + 2, doing: w.demoDoing, changed: [], read: [], isDemo: true }
728  return { turn, items }
729}
730
hooks/settings.ts 59 lines
1// The settings pane's model, with no `$`: the eight options, the pane's three tabs, each option's
2// values and default (as plugin.json declares them), and what the /config rows say about each.
3
4import { PALETTES } from './palettes'
5
6export type SettingKey = 'enabled' | 'agentText' | 'askForTasks' | 'request' | 'palette' | 'animation' | 'language' | 'icons'
7export type SettingValue = boolean | string
8
9/** The pane's tabs, in order: Transcript, Card, General. */
10export const TABS: readonly (readonly SettingKey[])[] = [
11  ['enabled', 'agentText', 'askForTasks'],
12  ['request', 'palette', 'animation'],
13  ['language', 'icons'],
14]
15
16/** Every option, as plugin.json declares it: its values in order, and its default. */
17export const SETTINGS: Readonly<Record<SettingKey, { values: readonly SettingValue[]; initial: SettingValue }>> = {
18  enabled: { values: [true, false], initial: false },
19  agentText: { values: ['final', 'none', 'card', 'all'], initial: 'final' },
20  askForTasks: { values: [true, false], initial: true },
21  request: { values: ['line', 'joined', 'auto', 'all'], initial: 'line' },
22  palette: { values: PALETTES.map(p => p.id), initial: 'claude' },
23  animation: { values: [true, false], initial: true },
24  language: { values: ['auto', 'pt-BR', 'en'], initial: 'auto' },
25  icons: { values: ['auto', 'emoji', 'symbol'], initial: 'auto' },
26}
27
28export const KEYS = Object.keys(SETTINGS) as SettingKey[]
29
30/** The /config row of an option: `plain-view.palette`. */
31export const rowKey = (key: SettingKey) => `plain-view.${key}`
32
33/** An option's value and whether a trusted source (managed settings) owns it. */
34export type Setting = { value: SettingValue; isLocked: boolean }
35
36type Row = { key: string; value: unknown; isLocked?: boolean }
37
38/** A value the option takes, else its default. */
39const fit = (key: SettingKey, value: unknown): SettingValue => (SETTINGS[key].values.includes(value as SettingValue) ? (value as SettingValue) : SETTINGS[key].initial)
40
41/**
42 * Each option as the pane shows it: its /config row when listed, else the options this load got,
43 * else its default. A value the option does not take reads as the default.
44 */
45export const settingsOf = (rows: readonly Row[], options: Readonly<Record<string, unknown>>): Record<SettingKey, Setting> =>
46  Object.fromEntries(
47    KEYS.map(key => {
48      const row = rows.find(r => r.key === rowKey(key))
49      return [key, { value: fit(key, row ? row.value : options[key]), isLocked: row?.isLocked === true }]
50    }),
51  ) as Record<SettingKey, Setting>
52
53/** The options `defaults` would change: away from their default and not locked. */
54export const awayFromDefaults = (s: Readonly<Record<SettingKey, Setting>>): SettingKey[] =>
55  KEYS.filter(key => !s[key].isLocked && s[key].value !== SETTINGS[key].initial)
56
57/** The tab shown, kept inside the three. */
58export const tabOf = (n: number) => Math.max(0, Math.min(TABS.length - 1, Math.trunc(n) || 0))
59
hooks/ui.tsx 114 lines
1// Shared UI helpers, after launchpad's patterns. The same file in every mod that has one: a mod
2// installs alone and cannot import another's code, so scripts/check-shared.sh keeps the copies
3// equal. Change one, copy it to the others.
4//
5// Nothing here takes `$`: the engine follows `$` only into functions of the file that uses it,
6// never across an import. A call on `$` stays in register.tsx; this file gives it its arguments.
7//
8//   language and icons  the `language` and `icons` options, else the system's LANG and terminal.
9//   prompt              the arguments of $.prompt.fill: a text with its first `[blank]` marked.
10//   lists               the window of a long list a pane shows, for ui.scroll.
11//   verbs               a row of a command's arguments, one press each.
12//   numbers             tokens, elapsed time, clipped text and short model names.
13
14import type { Elements, PromptFillArgs } from 'claude-code'
15
16export type Lang = 'pt-BR' | 'en'
17export type IconStyle = 'emoji' | 'symbol'
18
19/** The language: the `language` option when it names one, else Portuguese for a pt LANG, else English. */
20export const langOf = (option: unknown, systemLang?: string | null): Lang =>
21  option === 'en' || option === 'pt-BR' ? option : /^pt([_.@-]|$)/i.test(systemLang ?? '') ? 'pt-BR' : 'en'
22
23/**
24 * The icon style: the `icons` option when it names one; on `auto` (or none), symbols in a
25 * JetBrains IDE's terminal (TERMINAL_EMULATOR=JetBrains-JediTerm), which gives many emoji one
26 * column where Claude Code counts two, and emoji everywhere else.
27 */
28export const styleOf = (option: unknown, terminal?: string | null): IconStyle =>
29  option === 'emoji' || option === 'symbol' ? option : /^JetBrains/i.test(terminal ?? '') ? 'symbol' : 'emoji'
30
31/** An icon in the style: its emoji, or the one-cell symbol that stands in for it. */
32export const glyph = (style: IconStyle, icon: { emoji: string; symbol: string }) => icon[style]
33
34const BLANK = /\[[^\]\n]+\]/
35
36/** The first `[blank]` in a text, as offsets, so the prompt can mark what to replace. */
37export const blankIn = (text: string): { start: number; end: number } | null => {
38  const m = BLANK.exec(text)
39  return m ? { start: m.index, end: m.index + m[0].length } : null
40}
41
42/** What `$.prompt.fill` takes to put a text in the prompt, its `[blank]` marked to replace. */
43export const fillArgs = (text: string): PromptFillArgs => {
44  const blank = blankIn(text)
45  return blank ? { text, decorations: [{ ...blank, bold: true, underline: true }] } : { text }
46}
47
48/** The rows of a list of `total` a pane shows from `offset`, kept inside the list. */
49export const windowOf = (total: number, offset: number, rows: number): { start: number; end: number } => {
50  const size = Math.max(1, rows)
51  const start = Math.max(0, Math.min(offset, total - size))
52  return { start, end: Math.min(total, start + size) }
53}
54
55/**
56 * One of a command's arguments in a verb row. `fill` is the text the prompt waits with, for a
57 * verb that takes an argument or undoes something: a stray click then loses nothing. A verb with
58 * no `fill` runs, and its answer goes to the transcript a line at a time (`linesOf`).
59 */
60export type Verb = { verb: string; label?: string; fill?: string }
61
62/** A command's answer as the lines `$.ui.log` writes, one row each; blank lines dropped. */
63export const linesOf = (text: string | undefined) => (text ?? '').split('\n').filter(line => line.trim() !== '')
64
65/** `/command verb · verb · verb`, each verb a plain button; `lead` goes dim before the command. */
66export function verbRow(
67  ui: Pick<Elements[keyof Elements], 'Box' | 'Text' | 'Button'>,
68  command: string,
69  verbs: readonly Verb[],
70  onPress: (v: Verb) => void,
71  lead = '',
72) {
73  const { Box, Text, Button } = ui
74  return (
75    <Box flexDirection="row" flexWrap="wrap">
76      {lead !== '' && <Text dimColor>{`${lead} · `}</Text>}
77      <Text dimColor>{`/${command} `}</Text>
78      {verbs.map((v, i) => (
79        <Box key={`verbrow:${v.verb}`} flexDirection="row">
80          {i > 0 && <Text dimColor> · </Text>}
81          <Button key={`verb:${v.verb}`} plain dimColor label={v.label ?? v.verb} onPress={() => onPress(v)} />
82        </Box>
83      ))}
84    </Box>
85  )
86}
87
88/** 950, 1.2k, 46k, 1.2M. */
89export const tokens = (n: number) => {
90  if (n < 1000) return String(n)
91  if (n < 1_000_000) return `${(n / 1000).toFixed(n < 10_000 ? 1 : 0)}k`
92  return `${(n / 1_000_000).toFixed(1)}M`
93}
94
95/** 42s, 6m 05s, 1h 02m. */
96export const elapsed = (ms: number) => {
97  const s = Math.max(0, Math.round(ms / 1000))
98  if (s < 60) return `${s}s`
99  const m = Math.floor(s / 60)
100  if (m < 60) return `${m}m ${String(s % 60).padStart(2, '0')}s`
101  return `${Math.floor(m / 60)}h ${String(m % 60).padStart(2, '0')}m`
102}
103
104/** The text cut to `n` characters, an ellipsis last when it was longer. */
105export const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n - 1)}…` : s)
106
107/** claude-haiku-4-5-20251001 -> haiku 4.5 */
108export const shortModel = (m?: string) => {
109  if (!m) return ''
110  const hit = /(opus|sonnet|haiku|fable)[-\s]?(\d+(?:[-.]\d+)?)?/i.exec(m)
111  if (!hit) return m.length > 14 ? `${m.slice(0, 13)}…` : m
112  return `${hit[1]!.toLowerCase()}${hit[2] ? ` ${hit[2].replace('-', '.')}` : ''}`
113}
114
hooks/words.ts 352 lines
1// What plain-view says, in Portuguese and English. The language comes from the `language`
2// option, else the system's LANG (ui.tsx's langOf).
3
4import type { SettingKey } from './settings'
5import type { Lang } from './ui'
6
7export const COMMAND = 'plain-view'
8
9/** The label the prompt footer shows while the mod is on. */
10export const MODE = 'plain view'
11
12/** agent-watch's command: the agents row offers it when agent-watch is installed. */
13export const WATCH = 'watch'
14
15type Words = {
16  description: string
17  /** The two steps the card shows before the agent writes a task list. */
18  first: [string, string]
19  untitled: string
20  /** The title of a turn a notification started (a background agent finished) with no turn before. */
21  agentDone: string
22  step: (n: number, of: number) => string
23  steps: (done: number, of: number) => string
24  allDone: string
25  turnDone: string
26  interrupted: string
27  stopped: string
28  took: (span: string) => string
29  stoppedAt: (span: string) => string
30  /** A task's status beside its bar. */
31  done: string
32  leftOpen: string
33  moreBefore: (n: number) => string
34  next: string
35  later: string
36  halted: string
37  moreDone: (n: number) => string
38  moreAfter: (n: number) => string
39  /** A request's lines the title leaves out, `+5 linhas`; a pasted code block, `⟨código · 4 linhas⟩`. */
40  moreLines: (n: number) => string
41  codeLines: (n: number) => string
42  /** The card's button that unfolds the whole request, and folds it back. */
43  showRequest: string
44  foldRequest: string
45  /** What the turn touched: `mudei 2 arquivos · li 3 arquivos`. */
46  files: (changed: number, read: number) => string
47  /** The badge of the small card a turn with no task list leaves. */
48  ready: string
49  /** The agents row: `2 agentes rodando`, `1 agente terminou`. */
50  agentsRunning: (n: number) => string
51  agentsFinished: (n: number) => string
52  /** The waiting card, once the main turn ended with an agent running. */
53  waiting: (n: number) => string
54  /** How many agents ran, on the small end card: `1 agente`. */
55  agents: (n: number) => string
56  on: string
57  off: string
58  alreadyOn: string
59  alreadyOff: string
60  denied: (why: string) => string
61  demoStarted: string
62  demoBusy: string
63  demoTitle: string
64  demoTasks: string[]
65  demoDoing: string
66  palette: string
67  paletteNow: (id: string) => string
68  paletteSet: (id: string) => string
69  paletteUnknown: (name: string, names: string) => string
70  paletteAlso: string
71  use: string
72  answer: string
73  using: (tool: string) => string
74  usingSkill: (skill: string) => string
75  /** The system prompt line the askForTasks option adds when the session has a task tool. */
76  askForTasks: string
77  /** The line it adds when the session has none: a checklist in the reply, which the card reads. */
78  askForChecklist: string
79  /** The card's notice when a text list stopped moving, and the row's status with the calls it has made. */
80  stale: string
81  staleFor: (calls: number) => string
82  /** The reminder the model reads after a tool result once its checklist is stale; English in both languages. */
83  nudge: (calls: number) => string
84  failed: string
85  inUse: string
86  help: string
87  /** The settings pane, /plain-view or /plain-view config. */
88  pane: PaneWords
89}
90
91type PaneWords = {
92  /** The pane's tab label. */
93  title: string
94  heading: string
95  hint: string
96  tabs: [string, string, string]
97  labels: Record<SettingKey, string>
98  yes: string
99  no: string
100  /** What each value does, by option and value (`true` / `false` for the yes-or-no ones). */
101  values: Record<Exclude<SettingKey, 'palette'>, Record<string, string>>
102  preview: string
103  saved: (label: string, value: string) => string
104  denied: (why: string) => string
105  locked: string
106  lockedWhy: string
107  defaults: string
108  close: string
109  ask: string
110  askYes: string
111  askNo: string
112  reset: string
113  resetNone: string
114}
115
116// The model reads English best; the same line in both languages.
117const ASK_FOR_TASKS =
118  'When a request takes more than two steps, keep its plan as a task list with the TodoWrite or TaskCreate tool, and mark each task in progress and completed as you go. The person follows your progress from that list, not from the tool calls.'
119const ASK_FOR_CHECKLIST =
120  "When a request takes more than two steps, write its plan as a Markdown checklist (`- [ ] step`) in your reply before you start. Each time a step finishes, before the next step's first tool call, write `- [x] <that step>` (one line is enough) or the whole checklist again. These checklist lines are exempt from any brevity or terse-output rule. The person follows your progress from them."
121const NUDGE = (calls: number) =>
122  `plain-view: your checklist has not changed for ${calls} tool calls. If a step is done, write \`- [x] <step>\` for it (one line is enough), or the whole checklist again.`
123
124const plural = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`
125
126export const WORDS: Record<Lang, Words> = {
127  'pt-BR': {
128    description: 'Transcript sem ruído: o plano do agente num cartão acima do prompt',
129    first: ['Entender o pedido', 'Planejar os passos'],
130    untitled: 'Pedido sem texto',
131    agentDone: 'Um agente terminou',
132    step: (n, of) => `Passo ${n} de ${of}`,
133    steps: (done, of) => `${done} de ${of} passos`,
134    allDone: '✓ Tudo pronto',
135    turnDone: '✓ Turno pronto',
136    interrupted: '■ Interrompido',
137    stopped: '■ Parou com erro',
138    took: span => `levou ${span}`,
139    stoppedAt: span => `parou em ${span}`,
140    done: 'Feito',
141    leftOpen: 'Ficou aberto',
142    moreBefore: n => `○ mais ${n} antes`,
143    next: 'Próximo',
144    later: 'Depois',
145    halted: 'Parado',
146    moreDone: n => `✓ mais ${n} ${n === 1 ? 'feito' : 'feitos'}`,
147    moreAfter: n => `○ mais ${n} depois`,
148    moreLines: n => `+${plural(n, 'linha', 'linhas')}`,
149    codeLines: n => `⟨código · ${plural(n, 'linha', 'linhas')}⟩`,
150    showRequest: 'ver pedido',
151    foldRequest: 'recolher',
152    files: (changed, read) =>
153      changed > 0 ? `mudei ${plural(changed, 'arquivo', 'arquivos')} · li ${plural(read, 'arquivo', 'arquivos')}` : `li ${plural(read, 'arquivo', 'arquivos')}`,
154    ready: '✓ Pronto',
155    agentsRunning: n => `${plural(n, 'agente', 'agentes')} rodando`,
156    agentsFinished: n => `${plural(n, 'agente', 'agentes')} ${n === 1 ? 'terminou' : 'terminaram'}`,
157    waiting: n => `Esperando ${plural(n, 'agente', 'agentes')}`,
158    agents: n => plural(n, 'agente', 'agentes'),
159    on: 'plain-view ligado · /plain-view off desliga',
160    off: 'plain-view desligado · /plain-view on liga',
161    alreadyOn: 'plain-view já está ligado.',
162    alreadyOff: 'plain-view já está desligado.',
163    denied: why => `Não deu para mudar a opção: ${why}`,
164    demoStarted: 'Demo no cartão acima do prompt por 12 s. Nada roda de verdade.',
165    demoBusy: 'O agente está trabalhando. Rode a demo quando o pedido terminar.',
166    demoTitle: 'Demo: monte um painel do tempo',
167    demoTasks: ['Escolher o estilo da página', 'Ver como pegar o tempo ao vivo', 'Montar o painel', 'Publicar o link'],
168    demoDoing: 'demo',
169    palette: 'Paleta das barras',
170    paletteNow: id => `agora: ${id}`,
171    paletteSet: id => `Paleta ${id} · salva em /config`,
172    paletteUnknown: (name, names) => `Não conheço a paleta "${name}". As paletas: ${names}.`,
173    paletteAlso: 'Também: /plain-view palette aurora, ou /config → plain-view → palette.',
174    use: 'usar',
175    answer: 'Resposta: ',
176    using: tool => `usando ${tool}`,
177    usingSkill: skill => `usando a skill ${skill}`,
178    askForTasks: ASK_FOR_TASKS,
179    askForChecklist: ASK_FOR_CHECKLIST,
180    stale: 'lista parada',
181    staleFor: n => `lista parada há ${n} calls`,
182    nudge: NUDGE,
183    failed: 'Algo falhou no plain-view. O transcript segue como estava.',
184    inUse: 'em uso',
185    help: [
186      '**plain-view** · transcript sem ruído',
187      '- `/plain-view` ou `config` abre o painel de configuração',
188      '- `on` esconde as linhas de tool; o plano aparece num cartão acima do prompt',
189      '- `off` volta o transcript de sempre',
190      '- `demo` mostra o cartão com um plano de exemplo',
191      '- `palette` mostra as 8 paletas e troca a cor das barras',
192      '- `help` esta ajuda',
193      'Falha de tool, permissão e perguntas sempre aparecem inteiras.',
194      'Opções no painel ou em /config → plain-view: agentText, askForTasks, request, palette, animation, language, icons.',
195      'agentText: final esconde o que o agente escreve antes de chamar tools e deixa a resposta final (padrão); none, nada; card, a resposta no cartão; all, tudo.',
196      'Paleta padrão: claude. /plain-view palette mostra as 8.',
197    ].join('\n'),
198    pane: {
199      title: 'plain-view',
200      heading: '✻ plain-view · configuração',
201      hint: 'Vale para todas as sessões. Fica salvo em /config → plain-view.',
202      tabs: ['Transcript', 'Cartão', 'Geral'],
203      labels: { enabled: 'Ligado', agentText: 'Fala do agente', askForTasks: 'Pedir lista de tarefas', request: 'Pedido no cartão', palette: 'Cores das barras', animation: 'Animação', language: 'Idioma', icons: 'Ícones' },
204      yes: 'sim',
205      no: 'não',
206      values: {
207        enabled: { true: 'Esconde as linhas de tools; o plano fica no cartão acima do prompt.', false: 'Transcript de sempre. As outras opções valem quando ligar.' },
208        agentText: {
209          final: 'Esconde o que o agente escreve antes de chamar tools. A resposta final fica. (padrão)',
210          none: 'Esconde toda a fala do agente. Fica só o cartão.',
211          card: 'Esconde a fala. A primeira frase da resposta vai para o cartão.',
212          all: 'Mostra toda a fala do agente.',
213        },
214        askForTasks: { true: 'Uma linha no system prompt pede uma lista de tarefas. Custa poucos tokens por pedido.', false: 'O cartão lê só a lista que o modelo fizer por conta própria.' },
215        request: {
216          line: 'A primeira linha do pedido e quantas faltam (+5 linhas). (padrão)',
217          joined: 'Todas as linhas numa só, separadas por ·, cortadas na largura do cartão.',
218          auto: 'A primeira linha de texto corrido. Itens de lista (1. sim) entram na contagem.',
219          all: 'Até 10 linhas do pedido embaixo do título; o resto vira +N linhas.',
220        },
221        animation: { true: 'Um brilho corre nas barras enquanto o agente trabalha.', false: 'Barras paradas, nas cores do tema.' },
222        language: { auto: 'Segue o LANG do sistema.', 'pt-BR': 'Português do Brasil.', en: 'Inglês.' },
223        icons: { auto: 'symbol no terminal do JetBrains, emoji nos outros.', emoji: 'Passos como ✅ 🟠 ⚪.', symbol: 'Passos como ✓ ● ○, para terminais que desenham emoji torto.' },
224      },
225      preview: 'Prévia',
226      saved: (label, value) => `✓ Salvo · ${label}: ${value}`,
227      denied: why => `Não salvou: ${why}`,
228      locked: '🔒 definido pela organização',
229      lockedWhy: 'Vem das configurações gerenciadas. Não muda aqui nem no /config.',
230      defaults: 'padrões',
231      close: 'fechar',
232      ask: 'Voltar as opções do plain-view ao padrão?',
233      askYes: 'voltar',
234      askNo: 'agora não',
235      reset: '✓ Opções no padrão',
236      resetNone: 'As opções já estão no padrão.',
237    },
238  },
239  en: {
240    description: 'A quiet transcript: the agent’s plan in a card above the prompt',
241    first: ['Understand your request', 'Plan the steps'],
242    untitled: 'Request with no text',
243    agentDone: 'An agent finished',
244    step: (n, of) => `Step ${n} of ${of}`,
245    steps: (done, of) => `${done} of ${of} steps`,
246    allDone: '✓ All done',
247    turnDone: '✓ Turn done',
248    interrupted: '■ Interrupted',
249    stopped: '■ Stopped on an error',
250    took: span => `took ${span}`,
251    stoppedAt: span => `stopped at ${span}`,
252    done: 'Done',
253    leftOpen: 'Left open',
254    moreBefore: n => `○ ${n} more before`,
255    next: 'Next',
256    later: 'Up next',
257    halted: 'Stopped',
258    moreDone: n => `✓ ${n} more done`,
259    moreAfter: n => `○ ${n} more after`,
260    moreLines: n => `+${plural(n, 'line', 'lines')}`,
261    codeLines: n => `⟨code · ${plural(n, 'line', 'lines')}⟩`,
262    showRequest: 'show request',
263    foldRequest: 'fold',
264    files: (changed, read) =>
265      changed > 0 ? `changed ${plural(changed, 'file', 'files')} · read ${plural(read, 'file', 'files')}` : `read ${plural(read, 'file', 'files')}`,
266    ready: '✓ Done',
267    agentsRunning: n => `${plural(n, 'agent', 'agents')} running`,
268    agentsFinished: n => `${plural(n, 'agent', 'agents')} finished`,
269    waiting: n => `Waiting for ${plural(n, 'agent', 'agents')}`,
270    agents: n => plural(n, 'agent', 'agents'),
271    on: 'plain-view on · /plain-view off turns it off',
272    off: 'plain-view off · /plain-view on turns it on',
273    alreadyOn: 'plain-view is already on.',
274    alreadyOff: 'plain-view is already off.',
275    denied: why => `Could not change the option: ${why}`,
276    demoStarted: 'Demo in the card above the prompt for 12 s. Nothing really runs.',
277    demoBusy: 'The agent is working. Run the demo once the request ends.',
278    demoTitle: 'Demo: build a weather dashboard',
279    demoTasks: ['Pick the page style', 'Check how to get live weather', 'Build the dashboard', 'Publish the link'],
280    demoDoing: 'demo',
281    palette: 'Bar palette',
282    paletteNow: id => `now: ${id}`,
283    paletteSet: id => `Palette ${id} · saved in /config`,
284    paletteUnknown: (name, names) => `No palette named "${name}". The palettes: ${names}.`,
285    paletteAlso: 'Also: /plain-view palette aurora, or /config → plain-view → palette.',
286    use: 'use',
287    answer: 'Answer: ',
288    using: tool => `using ${tool}`,
289    usingSkill: skill => `using the ${skill} skill`,
290    askForTasks: ASK_FOR_TASKS,
291    askForChecklist: ASK_FOR_CHECKLIST,
292    stale: 'list not updated',
293    staleFor: n => `list not updated for ${n} calls`,
294    nudge: NUDGE,
295    failed: 'Something failed in plain-view. The transcript stays as it was.',
296    inUse: 'in use',
297    help: [
298      '**plain-view** · a quiet transcript',
299      '- `/plain-view` or `config` opens the settings pane',
300      '- `on` hides tool rows; the plan shows in a card above the prompt',
301      '- `off` back to the usual transcript',
302      '- `demo` shows the card with a sample plan',
303      '- `palette` shows the 8 palettes and changes the bar colors',
304      '- `help` this help',
305      'Tool failures, permissions and questions always show in full.',
306      'Options in the pane or in /config → plain-view: agentText, askForTasks, request, palette, animation, language, icons.',
307      'agentText: final hides what the agent writes before calling tools and keeps the final answer (default); none, nothing; card, the answer in the card; all, everything.',
308      'Default palette: claude. /plain-view palette shows all 8.',
309    ].join('\n'),
310    pane: {
311      title: 'plain-view',
312      heading: '✻ plain-view · settings',
313      hint: 'Applies to every session. Saved in /config → plain-view.',
314      tabs: ['Transcript', 'Card', 'General'],
315      labels: { enabled: 'On', agentText: "The agent's words", askForTasks: 'Ask for a task list', request: 'Request on the card', palette: 'Bar colors', animation: 'Animation', language: 'Language', icons: 'Icons' },
316      yes: 'yes',
317      no: 'no',
318      values: {
319        enabled: { true: 'Hides tool rows; the plan shows in a card above the prompt.', false: 'The usual transcript. The other options apply once it is on.' },
320        agentText: {
321          final: 'Hides what the agent writes before calling tools. The final answer stays. (default)',
322          none: "Hides all the agent's words. Only the card stays.",
323          card: "Hides the words. The answer's first sentence goes to the card.",
324          all: "Shows all the agent's words.",
325        },
326        askForTasks: { true: 'One line in the system prompt asks for a task list. Costs a few tokens per request.', false: 'The card reads only the list the model keeps on its own.' },
327        request: {
328          line: "The request's first line and how many are left (+5 lines). (default)",
329          joined: "All lines in one, joined by ·, cut at the card's width.",
330          auto: 'The first line of prose. List items (1. yes) go into the count.',
331          all: 'Up to 10 lines of the request under the title; the rest shows as +N lines.',
332        },
333        animation: { true: 'A shine runs along the bars while the agent works.', false: "Still bars, in the theme's colors." },
334        language: { auto: "Follows the system's LANG.", 'pt-BR': 'Brazilian Portuguese.', en: 'English.' },
335        icons: { auto: 'symbol in a JetBrains terminal, emoji elsewhere.', emoji: 'Steps as ✅ 🟠 ⚪.', symbol: 'Steps as ✓ ● ○, for terminals that draw emoji at odd widths.' },
336      },
337      preview: 'Preview',
338      saved: (label, value) => `✓ Saved · ${label}: ${value}`,
339      denied: why => `Not saved: ${why}`,
340      locked: '🔒 set by your organization',
341      lockedWhy: 'Comes from managed settings. It does not change here or in /config.',
342      defaults: 'defaults',
343      close: 'close',
344      ask: "Put plain-view's options back to their defaults?",
345      askYes: 'reset',
346      askNo: 'not now',
347      reset: '✓ Options back to defaults',
348      resetNone: 'The options are already at their defaults.',
349    },
350  },
351}
352
hooks/phrases.ts 87 lines
1// A tool call in a few words, in Portuguese and English: `lendo routes.ts`, `buscando "fatura"`.
2// The same file in every mod that names tool calls: scripts/check-shared.sh keeps the copies
3// equal, so it imports from nothing but ui.tsx, which is shared too. Phrases start in lower case;
4// a mod that shows one alone capitalizes it.
5
6import type { Lang } from './ui'
7import { clip } from './ui'
8
9type Phrases = {
10  running: (what: string) => string
11  reading: (file: string) => string
12  writing: (file: string) => string
13  editing: (file: string) => string
14  searching: (pattern: string) => string
15  finding: (pattern: string) => string
16  web: string
17  delegating: (what: string) => string
18  calling: (tool: string) => string
19  /** Stand-ins for an argument the call left out. */
20  aCommand: string
21  aFile: string
22  aTask: string
23}
24
25export const PHRASES: Record<Lang, Phrases> = {
26  'pt-BR': {
27    running: what => `rodando ${what}`,
28    reading: file => `lendo ${file}`,
29    writing: file => `escrevendo ${file}`,
30    editing: file => `editando ${file}`,
31    searching: pattern => `buscando "${pattern}"`,
32    finding: pattern => `procurando ${pattern}`,
33    web: 'na web',
34    delegating: what => `delegando "${what}"`,
35    calling: tool => `chamando ${tool}`,
36    aCommand: 'um comando',
37    aFile: 'um arquivo',
38    aTask: 'uma tarefa',
39  },
40  en: {
41    running: what => `running ${what}`,
42    reading: file => `reading ${file}`,
43    writing: file => `writing ${file}`,
44    editing: file => `editing ${file}`,
45    searching: pattern => `searching "${pattern}"`,
46    finding: pattern => `finding ${pattern}`,
47    web: 'on the web',
48    delegating: what => `delegating "${what}"`,
49    calling: tool => `calling ${tool}`,
50    aCommand: 'a command',
51    aFile: 'a file',
52    aTask: 'a task',
53  },
54}
55
56/** The last part of a path, `/` or `\` separated. */
57const base = (p: unknown) => (typeof p === 'string' ? (p.split(/[/\\]/).filter(Boolean).pop() ?? '') : '')
58
59/** A tool call in a few words: the tool's verb and its main argument. */
60export const phraseOf = (tool: string, input: Readonly<Record<string, unknown>>, lang: Lang = 'en'): string => {
61  const w = PHRASES[lang]
62  const s = (k: string) => (typeof input[k] === 'string' ? (input[k] as string).trim() : '')
63  const file = () => base(input.file_path) || w.aFile
64  switch (tool) {
65    case 'Bash':
66      return w.running(clip(s('description') || s('command').split('\n')[0]!.trim() || w.aCommand, 50))
67    case 'Read':
68      return w.reading(file())
69    case 'Write':
70      return w.writing(file())
71    case 'Edit':
72    case 'MultiEdit':
73      return w.editing(file())
74    case 'Grep':
75      return w.searching(clip(s('pattern'), 30))
76    case 'Glob':
77      return w.finding(clip(s('pattern'), 30))
78    case 'WebFetch':
79    case 'WebSearch':
80      return w.web
81    case 'Agent':
82      return w.delegating(clip(s('description') || w.aTask, 30))
83    default:
84      return w.calling(clip(tool.startsWith('mcp__') ? (tool.split('__').pop() ?? tool) : tool, 30))
85  }
86}
87
types/index.d.ts 88 lines
1/** One task of the agent's list, from TaskCreate/TaskUpdate or TodoWrite. */
2export type Item = {
3  /** TaskCreate's id; absent for a TodoWrite entry. */
4  id?: string
5  subject: string
6  status: 'pending' | 'in_progress' | 'completed'
7  /** Tool calls made while this task was the current one: what the step's estimate reads. */
8  calls: number
9  /** Read from a checklist in the agent's answer, not from a task tool. */
10  fromText?: boolean
11}
12
13/** How a turn ended: the model answered, the person interrupted, or an error stopped it. */
14export type End = 'answer' | 'aborted' | 'error'
15
16/** The request the card follows, from its turn.start to the next one. Times are epoch milliseconds. */
17export type Turn = {
18  /** The request's first line, or the last title when a turn starts with no text. */
19  title: string
20  startedAt: number
21  endedAt?: number
22  end?: End
23  /** Tool calls on the main loop this turn, task tools left out. */
24  calls: number
25  /** The tool call in flight, in a few words. */
26  doing?: string
27  /** Files an Edit, Write or NotebookEdit changed, and files a Read read. */
28  changed: string[]
29  read: string[]
30  /** A sample turn from /plain-view demo. */
31  isDemo?: boolean
32  /** The answer's first sentence, for the end card under `agentText: card`. */
33  answer?: string
34  /** The request's lines, when it has more than one; the card's `request` option reads them. */
35  lines?: RequestLine[]
36}
37
38/** A line of the request: its text, or a fenced code block as the number of lines it held. */
39export type RequestLine = string | { code: number }
40
41/** An agent (subagent) the main loop spawned, from its agent.spawn to its turn.complete. Epoch ms. */
42export type Agent = {
43  /** agent.spawn's agentId, as $.agent.list() names it. */
44  id: string
45  /** The Agent call's description, else its agent type. */
46  label: string
47  startedAt: number
48  /** Set when it ended: its turn.complete, or $.agent.list() says completed, failed or killed. */
49  endedAt?: number
50}
51
52/** The settings pane's line under its hint: a change saved or refused, or the reset. */
53export type Flash =
54  | { kind: 'saved'; key: string; value: boolean | string }
55  | { kind: 'denied'; why: string }
56  | { kind: 'reset' }
57  | { kind: 'resetNone' }
58
59/** What stays of the agent's words in the transcript while the mod is on. */
60export type AgentText = 'final' | 'none' | 'card' | 'all'
61
62declare module 'claude-code' {
63  interface PluginState {
64    'plain-view': {
65      turn: Turn | null
66      /** The agent's task list; a task tool's outlives a turn until every task is done. */
67      items: Item[]
68      /** An open checklist from the text the last request left: not drawn, counts no call, wakes when an answer writes one of its tasks. */
69      dormant: Item[]
70      /** The card shows the whole request (its `ver pedido` button); the next request folds it again. */
71      unfolded: boolean
72      /** Moves while the agent works, so the bars' shine redraws. */
73      tick: number
74      /** Texts of steps that went on to call tools, normalized: the blocks `agentText: final` hides. */
75      mids: string[]
76      /** The agents the main loop spawned: running ones, and the ones that ended during this request. */
77      agents: Agent[]
78      /** The settings pane's tab: 0 Transcript, 1 Card, 2 General. */
79      tab: number
80      flash: Flash | null
81      /** When the pane last changed an option (epoch ms), so the reload after it opens the pane again; 0 when none. */
82      reopenAt: number
83      /** A reset from the pane under way: the next load goes on with the options left. */
84      resetting: boolean
85    }
86  }
87}
88