project-brain 0.46.0 → 0.48.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -1
- package/package.json +6 -6
- package/templates/claude-tui/activity-pane/hooks/feat-agents.tsx +5 -4
- package/templates/claude-tui/activity-pane/hooks/feat-context.tsx +2 -2
- package/templates/claude-tui/activity-pane/hooks/feat-running.tsx +14 -8
- package/templates/claude-tui/activity-pane/hooks/register.tsx +215 -26
- package/templates/claude-tui/activity-pane/types/index.d.ts +9 -0
- package/templates/claude-tui/file-preview/.claude-plugin/plugin.json +7 -0
- package/templates/claude-tui/file-preview/hooks/core.ts +573 -0
- package/templates/claude-tui/file-preview/hooks/hooks.json +1 -0
- package/templates/claude-tui/file-preview/hooks/register.tsx +369 -0
- package/templates/claude-tui/file-preview/types/index.d.ts +17 -0
- package/templates/nvim/lua/plugins/project-brain-theme.lua +19 -0
- package/templates/nvim/lua/project-brain/highlights.lua +186 -0
- package/templates/skills/brain-design-review/SKILL.md +1 -1
- package/templates/skills/brain-qa-only/SKILL.md +1 -1
- package/templates/skills/brain-ux-review/SKILL.md +65 -0
- package/templates/skills/brain-ux-review/references/delegation.md +39 -0
- package/templates/skills/brain-ux-review/references/protocol.md +103 -0
- package/templates/skills/brain-ux-review/references/report.md +63 -0
- package/templates/skills/brain-worktree/SKILL.md +8 -1
package/README.md
CHANGED
|
@@ -196,6 +196,7 @@ These five are thin wrappers over the CLI. **project-brain does not install them
|
|
|
196
196
|
| `/brain-okf` | *(none — host skill)* | Write an OKF concept: the reasoning behind code, anchored to a verified symbol and checkable by `okf audit` |
|
|
197
197
|
| `/brain-design-review` | *(none — host skill)* | Audit a rendered UI like a designer (ten categories, AI-slop check), score it, then fix findings one commit each and re-verify |
|
|
198
198
|
| `/brain-qa-only` | *(none — host skill)* | Explore a browser, API, CLI or worker surface and report reproducible bugs with evidence; never edits product code |
|
|
199
|
+
| `/brain-ux-review` | *(none — host skill)* | Walk 3-5 real user tasks across a whole app, one feature or one screen; diagnose information architecture, interaction, layout and accessibility with labelled evidence; redesign the flows and write a validation plan (audit, redesign or implement mode) |
|
|
199
200
|
| `/brain-commit` | *(none — host skill)* | Write a commit message in the convention the repository's own log already shows |
|
|
200
201
|
| `/brain-record` | *(none — host skill)* | Record the flow a branch touches as video evidence for a PR or ticket |
|
|
201
202
|
| `/brain-worktree` | *(none — host skill)* | Give an isolated worktree its own index (seeded from the main checkout) and its own leased port |
|
|
@@ -371,8 +372,17 @@ The "Claude TUI" checklist sets up Claude Code's terminal. Every unit changes fi
|
|
|
371
372
|
|---|---|---|
|
|
372
373
|
| `tui:activity-pane` | Writes the `project-brain-activity` mod into a local marketplace at `~/.project-brain/claude-plugins/`, registers it in `~/.claude/settings.json` (`extraKnownMarketplaces["project-brain"]`, `enabledPlugins["project-brain-activity@project-brain"]`) and, on first install, sets `tui` to `"fullscreen"`, remembering the value it replaced; a renderer you pick later is kept on updates | Deletes both entries and the files it wrote, and puts your previous `tui` value back unless you changed it since |
|
|
373
374
|
| `tui:readable-replies` | Adds a marked block to `~/.claude/CLAUDE.md`: result first, full sentences, evidence at the end, no narration between tool calls | Deletes the block; the rest of the file stays as it was |
|
|
375
|
+
| `tui:terminal-theme` | Adds a marked block at the end of your Ghostty config (Supacode merges the same file): the active theme's colours, background opacity 0.88 and blur 20, and `background-opacity-cells` so tabs, pills and diff rows are as translucent as the rest. Off by default | Deletes only the block; the rest of the file stays as it was |
|
|
376
|
+
| `tui:claude-theme` | Writes a Claude Code custom theme to `~/.claude/themes/project-brain-<theme>.json` and sets `theme` to it, so the chat, the prompt and the `/diff` view use the same palette as the terminal and the activity pane. Off by default | Deletes the file and puts your previous `theme` back |
|
|
377
|
+
| `nvim:theme` | Writes three files into your Neovim config (`lua/project-brain/palette.lua`, `lua/project-brain/highlights.lua`, `lua/plugins/project-brain-theme.lua`): the active theme's palette on tokyonight, with Dracula's syntax roles and diffs that read as green added, red removed and a stronger tint on changed words. Needs LazyVim. Off by default | Deletes those files; a file of yours at one of those paths is never touched |
|
|
378
|
+
| `terminal:bat-theme` | Writes `themes/project-brain-<theme>.tmTheme` into bat's config directory and a marked `--theme` block at the end of its config, then rebuilds bat's cache. Same syntax colours as the Neovim theme; bat's git gutter markers stay its fixed ANSI green/red/yellow. Needs bat. Off by default | Deletes both and rebuilds the cache; a theme file of yours at that path is never touched. An exported `BAT_THEME` still wins over the config (setup warns when it is set) |
|
|
379
|
+
| `terminal:fzf-theme` | Adds a marked block at the end of `~/.zshrc` (`~/.bashrc` under bash) that appends the theme's `--color` to `FZF_DEFAULT_OPTS`, so your own options stay: current row on a soft raised line, purple focus, orange prompt, pink pointer. Needs fzf. Off by default | Deletes only the block |
|
|
380
|
+
| `terminal:lazygit-theme` | Writes `~/.lazygit.yml`, which lazygit merges over its config in every repository under your home: purple frame on the focused panel, orange while you filter, the current row on a quiet bar that keeps red and green readable. Your `config.yml` is never touched, and a theme you already set there is left alone. Off by default | Deletes the file |
|
|
381
|
+
| `terminal:tmux-theme` | Adds a marked block at the end of your tmux config: a transparent status bar, the session and current window as purple pills, readable pane borders with the focused one purple. It also sets `status-left` and the window-status formats, which overrides your own versions of those options while the block is there. A running tmux is not reloaded (`tmux source-file <file>`). Off by default | Deletes only the block |
|
|
382
|
+
| `terminal:starship-theme` | Adds two marked blocks to `starship.toml`: `palette` at the top and the theme's palette table at the end, so starship's red, green, yellow, cyan, purple and pink become the theme's and your styles can name roles such as `path`, `muted`, `progress` or `git_dirty`. It writes no module tables, so your own module styles have to name those keys to use them. A `palette` of your own is never touched. Needs starship; not tested against a real starship. Off by default | Deletes only the two blocks |
|
|
374
383
|
| `tui:skill-listing` | Writes the `project-brain-skill-listing` mod into the same local marketplace and registers it (`enabledPlugins["project-brain-skill-listing@project-brain"]`); asks for your general-use skills and saves them to `~/.project-brain/skills.json`; writes `~/.project-brain/skill-usage.json`. Unchecked even on a first run: it trades skill descriptions for tokens, which is yours to decide | Deletes its plugin entry, its files and `skill-usage.json`; the marketplace entry goes only with the last mod in it. `skills.json` stays, since the suggest hook reads it too |
|
|
375
384
|
| `tui:context-gate` | Writes the `project-brain-context-gate` mod into the same local marketplace and registers it (`enabledPlugins["project-brain-context-gate@project-brain"]`). Unchecked even on a first run: it leaves context out of what the model reads, which is yours to decide | Deletes its plugin entry and its files; the marketplace entry goes only with the last mod in it |
|
|
385
|
+
| `tui:file-preview` | Writes the `project-brain-file-preview` mod into the same local marketplace and registers it (`enabledPlugins["project-brain-file-preview@project-brain"]`). Under each Read, Edit and Write row, and under a reply that names project files (any path with a slash, or a bare `name.ext` in a code span), it draws the path and an `open` control (fullscreen renderer: they take clicks there). With the activity pane also installed, the controls show only on the tool rows the pane leaves visible; reply rows are not affected. A click on the path previews a text file: the mod reads it once (through `perl`, refusing a symlink, a FIFO, a file with more than one hard link, or one that moved), checks every byte it will show, and hands those bytes to the Neovim whose working directory is this project, which shows them in a floating window without opening the file (focus, cursor and your buffers untouched; it closes on your next cursor move there). With no such Neovim, a copy of those bytes opens read-only in a background Supacode tab, else they show as plain lines in a pane; at most the first 192 KiB. An image or video opens with `open`. `open` sends a text file to that Neovim (`tab drop` at the line), else to a new Supacode tab running your editor. Only regular files inside the session's directory, its project root and `PB_PREVIEW_ROOTS` (symlinks resolved first; a root that is your home folder or `/` is never used). Refused by name, for the file or any folder above it inside the project: `.env*`, keys and certificates (`*.pem`, `*.key`, `id_rsa*` and the other `id_*` keys, `*.p12`, `*.pfx`, `*.asc`, `*.ppk`, `*.keystore`, `*.jks`, `*.kdbx`), `credentials*`, `secrets.*`, `*.token`, `.vault-token`, `*.tfvars`, `terraform.tfstate*`, `.dev.vars`, `.npmrc`, `.netrc`, `.pypirc`, `.pgpass`, `.htpasswd`, `.git-credentials`, `kubeconfig*`, `.mcp.json`, `.claude.json`, `service-account*.json`, shell histories, everything under `.ssh`, `.gnupg`, `.aws` and `.kube`, and `.docker/config.json`, `.git/config`, `.claude/settings*.json`, `.config/gh/hosts.yml`. Refused by content: private keys (PEM, OpenSSH, PGP, PuTTY), AWS key ids, GitHub, OpenAI/Anthropic, Slack and Google keys, JWTs, and `password`/`secret`/`token`/`api_key` assignments with a long value; the toast says which kind, never the text. Both lists are best effort. Settings: `PB_EDITOR` (then `VISUAL`, `EDITOR`, else `nvim`; read as argv, no shell), `PB_NVIM_SERVER` (the Neovim socket to use first, then `$NVIM`), `PB_PREVIEW_ROOTS` (extra allowed roots, colon separated), `PB_PREVIEW_IMAGES=1` (draw images and a video's frame in the pane; untested on Supacode). Cmd+click is not the mod's: Claude Code hands a mod no modifier keys, so `open` is a control of its own. Off by default | Deletes its plugin entry and its files; the marketplace entry goes only with the last mod in it |
|
|
376
386
|
|
|
377
387
|
The activity pane is a side pane named "Actividad" with tabs for todos, commands and uncommitted changes; each changed file expands to its diff against HEAD, with line numbers, and Enter on a file name opens it in one reused nvim split (Supacode, tmux, or a Terminal window) with its diff. When subagents run, a selector shows each one with its own summary, commands and diff; the header and footer stay fixed while the body scrolls. It docks on the right only in the fullscreen renderer (`/tui fullscreen`), which is why the unit switches it on. `/activity` reopens the pane after you close it, and ctrl+o still expands tool rows in the chat. The cost it shows is Claude Code's own estimate for the session, not a bill. If another marketplace is already registered under the name `project-brain`, setup reports the unit as foreign and leaves it alone; other plugins' settings are never touched. Mods need Claude Code 2.1.287 or later, and do not load when `disableAllHooks` is set.
|
|
378
388
|
|
|
@@ -496,7 +506,7 @@ The bridge is [`mcp-proxy`](https://github.com/sparfenyuk/mcp-proxy), installed
|
|
|
496
506
|
|
|
497
507
|
The command moves across **verbatim**, so whatever flags you already answered for — `--autoConnect` included — carry over. The one thing setup adds is the default: a command that chose no browser (no `--autoConnect`, `--browserUrl`, `--wsEndpoint`, `--isolated` or `--userDataDir`) is shared with `--headless --userDataDir=~/.project-brain/chrome-profile`, so every session drives one shared headless browser that the server launches itself on a dedicated, persistent profile: no CDP toggle, no approval modal, and logins that survive restarts. Setup creates that directory (mode 0700) and, while it holds no Chrome profile yet, points you to `project-brain browser login`. That command opens your real Chrome, headed, on the profile with no remote-debugging or automation flags (Google refuses sign-in in automated browsers), and waits until you close it. Chrome allows one process per profile, so if the shared server (or any Chrome) holds the profile it stops and tells you to stop that first; it never kills anything. Restart the shared server afterwards so it reuses the saved login. For a separate session on the same URL (own cookies and storage), the agent passes `isolatedContext` to `new_page` inside that browser instead of starting another one. Removing the unit restores each entry from a record written at install rather than reconstructing a command.
|
|
498
508
|
|
|
499
|
-
An existing
|
|
509
|
+
An existing service this unit installed that still runs `--autoConnect` is the old default, not a choice you made, so the next `project-brain update` (or `setup`) moves it to the headless profile and reloads it: with `--autoConnect` every sub-agent's pages land in your own Chrome (one run left about ten pages, one at 3 GB, and the MCP stopped answering). Ticking "chrome-devtools autoConnect" is what records the choice; from then on setup keeps the flag, and unticking it (or `project-brain setup --without=config:chrome-autoconnect`) takes it away and reloads the service. To restart it by hand, the command is the one setup prints at install (`launchctl kickstart -k gui/$(id -u)/dev.projectbrain.chrome-devtools-shared` on macOS, `systemctl --user restart dev.projectbrain.chrome-devtools-shared` on Linux). Only the service this unit installed is rewritten; a bridge you set up yourself is never touched.
|
|
500
510
|
|
|
501
511
|
The `hooks:browser-route` unit (on by default, Claude Code only, opt out by unticking it) adds a `PreToolUse` hook on the `mcp__chrome-devtools__*` tools. The first time a session calls one, it adds one line saying: share the headless browser on its dedicated profile (sign in once with `project-brain browser login`), use `isolatedContext` for a separate session on the same URL, and use your real Chrome only when you ask. It prints nothing otherwise and never blocks the call.
|
|
502
512
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "project-brain",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.48.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Local-first MCP server that gives AI tools semantic memory of your codebase.",
|
|
6
6
|
"author": "jcsoftdev",
|
|
@@ -49,11 +49,11 @@
|
|
|
49
49
|
"zod": "^4.4.3"
|
|
50
50
|
},
|
|
51
51
|
"optionalDependencies": {
|
|
52
|
-
"project-brain-darwin-arm64": "0.
|
|
53
|
-
"project-brain-linux-x64": "0.
|
|
54
|
-
"project-brain-linux-arm64": "0.
|
|
55
|
-
"project-brain-windows-x64": "0.
|
|
56
|
-
"project-brain-windows-arm64": "0.
|
|
52
|
+
"project-brain-darwin-arm64": "0.48.0",
|
|
53
|
+
"project-brain-linux-x64": "0.48.0",
|
|
54
|
+
"project-brain-linux-arm64": "0.48.0",
|
|
55
|
+
"project-brain-windows-x64": "0.48.0",
|
|
56
|
+
"project-brain-windows-arm64": "0.48.0"
|
|
57
57
|
},
|
|
58
58
|
"devDependencies": {
|
|
59
59
|
"@types/bun": "latest",
|
|
@@ -24,7 +24,7 @@ export type AgentsCell = Omit<Cell, 'action'> & { action?: Action | AgentsAction
|
|
|
24
24
|
|
|
25
25
|
export type AgentsPart = { expanded: boolean; reports: Record<string, string> }
|
|
26
26
|
|
|
27
|
-
export type GroupedInput = { records: AgentRecord[]; scope: string; expanded: boolean; width: number }
|
|
27
|
+
export type GroupedInput = { records: AgentRecord[]; scope: string; expanded: boolean; width: number; modelOf?: (id: string) => string }
|
|
28
28
|
|
|
29
29
|
export type Verdict = { token: string; tone: Tone }
|
|
30
30
|
|
|
@@ -34,12 +34,13 @@ const newestFirst = (a: AgentRecord, b: AgentRecord): number => b.startedAt - a.
|
|
|
34
34
|
|
|
35
35
|
const widthOf = (cell: AgentsCell): number => cell.spans.reduce((sum, one) => sum + [...one.text].length, 0)
|
|
36
36
|
|
|
37
|
-
const chipOf = (key: string, label: string, isOn: boolean, action: Action, look?: Look): AgentsCell => ({
|
|
37
|
+
const chipOf = (key: string, label: string, isOn: boolean, action: Action, look?: Look, model = ''): AgentsCell => ({
|
|
38
38
|
key,
|
|
39
39
|
label,
|
|
40
40
|
action,
|
|
41
41
|
spans: [
|
|
42
42
|
span(` ${label} `, { inverse: isOn, bold: isOn }),
|
|
43
|
+
...(model ? [span(`${model} `, { inverse: isOn, dim: !isOn })] : []),
|
|
43
44
|
...(look ? [span(`${look.icon} `, { color: look.color, inverse: isOn })] : []),
|
|
44
45
|
span(' '),
|
|
45
46
|
],
|
|
@@ -95,14 +96,14 @@ const windowed = (pinned: AgentsCell[], chips: AgentsCell[], selected: number, i
|
|
|
95
96
|
* The agent chips grouped: "Principal" and the ended agents' toggle stay pinned; running agents follow,
|
|
96
97
|
* newest first; ended agents show after them only when expanded. The selected agent is always shown.
|
|
97
98
|
*/
|
|
98
|
-
export const agentChipsGrouped = ({ records, scope, expanded, width }: GroupedInput): AgentsCell[] => {
|
|
99
|
+
export const agentChipsGrouped = ({ records, scope, expanded, width, modelOf }: GroupedInput): AgentsCell[] => {
|
|
99
100
|
const live = records.filter(one => !isEnded(one)).sort(newestFirst)
|
|
100
101
|
const ended = records.filter(isEnded).sort(newestFirst)
|
|
101
102
|
const shownEnded = expanded ? ended : ended.filter(one => one.id === scope)
|
|
102
103
|
const visible = [...live, ...shownEnded]
|
|
103
104
|
const principal = chipOf(`agents-chip-${MAIN}`, 'Principal', scope === MAIN, { kind: 'agent', id: MAIN })
|
|
104
105
|
const pinned = ended.length > 0 ? [principal, toggleOf(ended, expanded)] : [principal]
|
|
105
|
-
const chips = visible.map(one => chipOf(`agents-chip-${one.id}`, shortName(one), scope === one.id, { kind: 'agent', id: one.id }, AGENT_LOOK[one.state]))
|
|
106
|
+
const chips = visible.map(one => chipOf(`agents-chip-${one.id}`, shortName(one), scope === one.id, { kind: 'agent', id: one.id }, AGENT_LOOK[one.state], modelOf?.(one.id) ?? ''))
|
|
106
107
|
return windowed(pinned, chips, visible.findIndex(one => one.id === scope), visible.map(one => one.id), Math.max(1, width))
|
|
107
108
|
}
|
|
108
109
|
|
|
@@ -3,7 +3,7 @@ import { atom, read, update } from 'claude-code'
|
|
|
3
3
|
import type { ContextCategory, Register, SessionCompactResult, SessionContextBreakdown, SessionContextUsage } from 'claude-code'
|
|
4
4
|
|
|
5
5
|
import type { Api, Row, Span, Tone } from './register'
|
|
6
|
-
import { clean, compact, contextPercentOf, fit, span } from './register'
|
|
6
|
+
import { againstCompaction, clean, compact, contextPercentOf, fit, span } from './register'
|
|
7
7
|
|
|
8
8
|
/** One breakdown row the pane keeps: deferred schemas sit outside the window and are dropped. */
|
|
9
9
|
export type ContextRowKind = 'used' | 'free' | 'buffer'
|
|
@@ -113,7 +113,7 @@ export const compactionLabel = (record: CompactionRecord, now: number): string =
|
|
|
113
113
|
|
|
114
114
|
/** The live fill against the session's measured window; the breakdown's own figure only before a response came back. */
|
|
115
115
|
export const livePercent = (part: Pick<ContextPart, 'usage' | 'breakdown'>): number | undefined => {
|
|
116
|
-
const measured = contextPercentOf(part.usage)
|
|
116
|
+
const measured = contextPercentOf(againstCompaction(part.usage, part.breakdown.window))
|
|
117
117
|
if (measured !== undefined) return measured
|
|
118
118
|
const { total, window } = part.breakdown
|
|
119
119
|
return window > 0 && total > 0 ? (total / window) * 100 : undefined
|
|
@@ -3,7 +3,8 @@ import { atom, read, update } from 'claude-code'
|
|
|
3
3
|
import type { Register } from 'claude-code'
|
|
4
4
|
|
|
5
5
|
import type { Api, Row, Span, Tone } from './register'
|
|
6
|
-
import { ICONS, clean, fit, shortName, span } from './register'
|
|
6
|
+
import { ICONS, agentUsage, clean, fit, shortName, span, usageRight } from './register'
|
|
7
|
+
import type { AgentUsage } from '../types'
|
|
7
8
|
import { notify } from './feat-notify'
|
|
8
9
|
|
|
9
10
|
export type RunningKind = 'bash' | 'monitor' | 'agent' | 'workflow'
|
|
@@ -31,7 +32,8 @@ export type RunningTask = {
|
|
|
31
32
|
isInferred?: boolean
|
|
32
33
|
}
|
|
33
34
|
|
|
34
|
-
|
|
35
|
+
/** `usage` is keyed by agent id: a background agent's task id is the agent id its model requests report. */
|
|
36
|
+
export type RunningPart = { tasks: RunningTask[]; now: number; usage?: Record<string, AgentUsage> }
|
|
35
37
|
|
|
36
38
|
/** What a background-launching tool call reported. */
|
|
37
39
|
export type Launch = Pick<RunningTask, 'id' | 'kind' | 'label'> & Partial<Pick<RunningTask, 'outputFile' | 'deadline'>>
|
|
@@ -288,15 +290,18 @@ export const rowsRunning = (part: RunningPart, ctx: { width: number; accent: str
|
|
|
288
290
|
cells: [{ spans: [span(fit(title, width), { bold: true, color: live > 0 ? ctx.accent : undefined })], action: { kind: 'toggle', key: SECTION_KEY }, label: 'En curso', key: `btn-${SECTION_KEY}` }],
|
|
289
291
|
}]
|
|
290
292
|
if (!open) return rows
|
|
293
|
+
const usageOf = (task: RunningTask, base: string): string => (task.kind === 'agent' ? usageRight(part.usage?.[task.id], base, width) : '')
|
|
294
|
+
const withUsage = (spent: string, right: Span[]): Span[] => (spent === '' ? right : [span(spent, { dim: true }), ...right])
|
|
291
295
|
for (const task of shown) {
|
|
292
296
|
const who = task.agentLabel !== undefined ? `${clean(task.agentLabel)} · ` : ''
|
|
293
297
|
const label = clean(task.label)
|
|
294
298
|
if (task.status === 'running') {
|
|
295
299
|
const right = elapsed(part.now - task.startedAt)
|
|
300
|
+
const spent = usageOf(task, right)
|
|
296
301
|
rows.push({
|
|
297
302
|
key: `running-${task.id}`,
|
|
298
|
-
cells: [{ spans: [span(` ${ICONS.running} `, { color: 'warning' }), span(`${kindIcon(task.kind)} ${fit(label, width - right.length - 8)}`)] }],
|
|
299
|
-
right: [span(right, { color: 'warning' })],
|
|
303
|
+
cells: [{ spans: [span(` ${ICONS.running} `, { color: 'warning' }), span(`${kindIcon(task.kind)} ${fit(label, width - spent.length - right.length - 8)}`)] }],
|
|
304
|
+
right: withUsage(spent, [span(right, { color: 'warning' })]),
|
|
300
305
|
})
|
|
301
306
|
const detail = `${who}${clean(task.lastLine ?? '')}`
|
|
302
307
|
if (detail !== '') rows.push({ key: `running-${task.id}-line`, cells: [{ spans: [span(fit(` └ ${detail}`, width), { dim: true })] }] })
|
|
@@ -306,10 +311,11 @@ export const rowsRunning = (part: RunningPart, ctx: { width: number; accent: str
|
|
|
306
311
|
const verdict = verdictOfTask(task)
|
|
307
312
|
const took = elapsed((task.endedAt ?? part.now) - task.startedAt)
|
|
308
313
|
const rightText = verdict ? `${verdict} ${took}` : took
|
|
314
|
+
const spent = usageOf(task, rightText)
|
|
309
315
|
rows.push({
|
|
310
316
|
key: `running-${task.id}`,
|
|
311
|
-
cells: [{ spans: [span(` ${look.icon} `, { color: look.color }), span(`${kindIcon(task.kind)} ${fit(`${who}${label}`, width - rightText.length - 8)}`, { dim: true })] }],
|
|
312
|
-
right: verdict ? [span(verdict, { color: verdict === 'PASS' ? 'success' : 'error' }), span(` ${took}`, { dim: true })] : [span(took, { dim: true })],
|
|
317
|
+
cells: [{ spans: [span(` ${look.icon} `, { color: look.color }), span(`${kindIcon(task.kind)} ${fit(`${who}${label}`, width - spent.length - rightText.length - 8)}`, { dim: true })] }],
|
|
318
|
+
right: withUsage(spent, verdict ? [span(verdict, { color: verdict === 'PASS' ? 'success' : 'error' }), span(` ${took}`, { dim: true })] : [span(took, { dim: true })]),
|
|
313
319
|
})
|
|
314
320
|
}
|
|
315
321
|
return rows
|
|
@@ -346,8 +352,8 @@ export const notifyLineOf = (task: RunningTask): string => {
|
|
|
346
352
|
// ---------------------------------------------------------------- engine
|
|
347
353
|
|
|
348
354
|
export async function readRunning($: Api): Promise<RunningPart> {
|
|
349
|
-
const [tasks, now] = await Promise.all([read($, tasksAtom), $.clock.now(), read($, tickAtom)])
|
|
350
|
-
return { tasks, now }
|
|
355
|
+
const [tasks, now, , usage] = await Promise.all([read($, tasksAtom), $.clock.now(), read($, tickAtom), read($, agentUsage)])
|
|
356
|
+
return { tasks, now, usage }
|
|
351
357
|
}
|
|
352
358
|
|
|
353
359
|
function announce($: Api, ended: RunningTask[]): void {
|
|
@@ -25,6 +25,7 @@ import { notifyCommand, notifyTurnComplete } from './feat-notify'
|
|
|
25
25
|
import type {
|
|
26
26
|
AgentRecord,
|
|
27
27
|
AgentState,
|
|
28
|
+
AgentUsage,
|
|
28
29
|
BranchCommit,
|
|
29
30
|
BranchView,
|
|
30
31
|
CallStatus,
|
|
@@ -33,6 +34,7 @@ import type {
|
|
|
33
34
|
CommitRecord,
|
|
34
35
|
ContextUsage,
|
|
35
36
|
StepContext,
|
|
37
|
+
SessionIdentityLine,
|
|
36
38
|
Decision,
|
|
37
39
|
DiffPatch,
|
|
38
40
|
DiffRow,
|
|
@@ -48,7 +50,8 @@ import type {
|
|
|
48
50
|
} from '../types'
|
|
49
51
|
|
|
50
52
|
const PANE = 'activity'
|
|
51
|
-
|
|
53
|
+
/** `transparent` keeps the engine from filling the dock with its sidebar grey, so the terminal's opacity and blur show through the pane. */
|
|
54
|
+
export const PANE_ARGS = { id: PANE, title: 'Actividad', columns: 1000, backgroundColor: 'transparent' } as const
|
|
52
55
|
export const MAIN = 'main'
|
|
53
56
|
const KEEP = 300
|
|
54
57
|
const OUTPUT_LINES = 40
|
|
@@ -131,6 +134,7 @@ const openFiles = atom({ plugin: 'project-brain-activity', key: 'openFiles' } as
|
|
|
131
134
|
const diffs = atom({ plugin: 'project-brain-activity', key: 'diffs' } as const, {} as Record<string, DiffPatch>, { shape: 'diffs-2' })
|
|
132
135
|
const costUsd = atom({ plugin: 'project-brain-activity', key: 'costUsd' } as const, 0, { shape: 'cost-1' })
|
|
133
136
|
const stepContext = atom({ plugin: 'project-brain-activity', key: 'stepContext' } as const, {} as Record<string, StepContext>, { shape: 'step-context-1' })
|
|
137
|
+
export const agentUsage = atom({ plugin: 'project-brain-activity', key: 'agentUsage' } as const, {} as Record<string, AgentUsage>, { shape: 'agent-usage-1' })
|
|
134
138
|
const contextUsage = atom({ plugin: 'project-brain-activity', key: 'context' } as const, { window: 0 } as ContextUsage, { shape: 'context-2' })
|
|
135
139
|
const agents = atom({ plugin: 'project-brain-activity', key: 'agents' } as const, [] as AgentRecord[], { shape: 'agents-1' })
|
|
136
140
|
const pickedAgent = atom({ plugin: 'project-brain-activity', key: 'pickedAgent' } as const, '', { shape: 'picked-1' })
|
|
@@ -142,27 +146,49 @@ const branch = atom({ plugin: 'project-brain-activity', key: 'branch' } as const
|
|
|
142
146
|
const autoOpen = atom({ plugin: 'project-brain-activity', key: 'autoOpen' } as const, true, { shape: 'auto-open-1' })
|
|
143
147
|
const editor = atom({ plugin: 'project-brain-activity', key: 'editor' } as const, { dir: '', tab: '' } as EditorState, { shape: 'editor-1' })
|
|
144
148
|
const accentColor = atom({ plugin: 'project-brain-activity', key: 'accent' } as const, 'claude' as string, { shape: 'accent-1' })
|
|
149
|
+
const mainModel = atom({ plugin: 'project-brain-activity', key: 'mainModel' } as const, '' as string, { shape: 'main-model-1' })
|
|
150
|
+
const identity = atom({ plugin: 'project-brain-activity', key: 'identity' } as const, { account: '', sessionId: '', folder: '' } as SessionIdentityLine, { shape: 'identity-1' })
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* The Dracula palette, as published at draculatheme.com/contribute. Roles follow how Dracula paints code:
|
|
154
|
+
* pink = keywords and titles, cyan = types and names, green = functions and success, orange = parameters and warnings,
|
|
155
|
+
* yellow = literals (strings), purple = commands and links, comment = everything secondary, red = errors.
|
|
156
|
+
*/
|
|
157
|
+
const DRACULA = {
|
|
158
|
+
background: '#17141d', currentLine: '#44475a', foreground: '#f8f8f2', comment: '#6272a4',
|
|
159
|
+
cyan: '#8be9fd', green: '#50fa7b', orange: '#ffb86c', pink: '#ff79c6', purple: '#bd93f9', red: '#ff5555', yellow: '#f1fa8c',
|
|
160
|
+
} as const
|
|
145
161
|
|
|
146
162
|
/** Claude Code's session colours (/color) as their Dracula counterparts; 'default' and unknown names keep the claude tone. */
|
|
147
163
|
const SESSION_COLORS: Record<string, string> = {
|
|
148
|
-
red:
|
|
149
|
-
purple:
|
|
164
|
+
red: DRACULA.red, blue: DRACULA.comment, green: DRACULA.green, yellow: DRACULA.yellow,
|
|
165
|
+
purple: DRACULA.purple, orange: DRACULA.orange, pink: DRACULA.pink, cyan: DRACULA.cyan,
|
|
150
166
|
}
|
|
151
167
|
|
|
152
|
-
/** The pane's palette (Dracula): each tone the rows name, painted as
|
|
168
|
+
/** The pane's palette (Dracula): each tone the rows name, painted as its Dracula colour. */
|
|
153
169
|
export const PALETTE: Record<Tone, string> = {
|
|
154
|
-
success:
|
|
155
|
-
claude:
|
|
170
|
+
success: DRACULA.green, error: DRACULA.red, warning: DRACULA.orange, subtle: DRACULA.comment, permission: DRACULA.purple,
|
|
171
|
+
claude: DRACULA.pink, suggestion: DRACULA.cyan, literal: DRACULA.yellow, diffAdded: DRACULA.green, diffRemoved: DRACULA.red,
|
|
156
172
|
}
|
|
157
|
-
const COMMENT =
|
|
158
|
-
/** The
|
|
159
|
-
export const PANE_BG =
|
|
173
|
+
const COMMENT = DRACULA.comment
|
|
174
|
+
/** The editor's background and foreground in Dracula. The background is never painted (the terminal's opacity and blur only show through cells with no background of their own); it is what dim colours fade towards and the text on a pill. */
|
|
175
|
+
export const PANE_BG = DRACULA.background
|
|
176
|
+
export const PANE_FG = DRACULA.foreground
|
|
160
177
|
|
|
161
|
-
/**
|
|
162
|
-
export const
|
|
163
|
-
|
|
164
|
-
const
|
|
165
|
-
|
|
178
|
+
/** `hex` moved `share` of the way towards `into`: how a dim span keeps its hue on the pane's own background instead of leaving the dimming to the terminal. */
|
|
179
|
+
export const blend = (hex: string, into: string, share: number): string => {
|
|
180
|
+
const parts = (value: string): number[] | undefined => (/^#[0-9a-f]{6}$/i.test(value) ? [1, 3, 5].map(at => Number.parseInt(value.slice(at, at + 2), 16)) : undefined)
|
|
181
|
+
const from = parts(hex)
|
|
182
|
+
const to = parts(into)
|
|
183
|
+
if (!from || !to) return hex
|
|
184
|
+
return `#${from.map((channel, at) => Math.round(channel + ((to[at] ?? channel) - channel) * share).toString(16).padStart(2, '0')).join('')}`
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** A span's colours as the surface draws them: palette tones become hex; an uncoloured span is the foreground, a bold one pink, a dim one the comment grey; a dim coloured span fades into the pane. An inverse span is a pill: its colour as the fill, the pane's background as the text. */
|
|
188
|
+
export const paint = (one: Pick<Span, 'color' | 'dim' | 'bold' | 'inverse'>): { color: string; backgroundColor?: string } => {
|
|
189
|
+
const base = one.color === undefined ? (one.dim ? COMMENT : one.bold ? DRACULA.pink : PANE_FG) : (PALETTE as Record<string, string>)[one.color] ?? one.color
|
|
190
|
+
const shown = one.dim && one.color !== undefined ? blend(base, PANE_BG, 0.5) : base
|
|
191
|
+
return one.inverse ? { color: PANE_BG, backgroundColor: shown } : { color: shown }
|
|
166
192
|
}
|
|
167
193
|
|
|
168
194
|
/** The last `"agentColor":"<name>"` grep match in the transcript, as a colour the pane can paint. */
|
|
@@ -196,6 +222,30 @@ const refreshAccent = async ($: Api): Promise<void> => {
|
|
|
196
222
|
if (next !== (await read($, accentColor))) await update($, accentColor, () => next)
|
|
197
223
|
}
|
|
198
224
|
|
|
225
|
+
/** Who this session runs as: the login's email, else `API · <host>` from ANTHROPIC_BASE_URL, else nothing. */
|
|
226
|
+
export const accountOf = (config: string, baseUrl: string): string => {
|
|
227
|
+
try {
|
|
228
|
+
const email = (JSON.parse(config) as { oauthAccount?: { emailAddress?: unknown } }).oauthAccount?.emailAddress
|
|
229
|
+
if (typeof email === 'string' && email !== '') return email
|
|
230
|
+
} catch {}
|
|
231
|
+
if (baseUrl === '') return ''
|
|
232
|
+
try { return `API · ${new URL(baseUrl).host}` } catch { return 'API' }
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** `~/x/y` for a folder under HOME, the path otherwise. */
|
|
236
|
+
export const folderOf = (root: string, home: string): string => (home !== '' && (root === home || root.startsWith(`${home}/`)) ? `~${root.slice(home.length)}` : root)
|
|
237
|
+
|
|
238
|
+
const env = async ($: Api, name: string): Promise<string> =>
|
|
239
|
+
$.process.run(['/usr/bin/printenv', name]).then(out => out.stdout.trim()).catch(() => '')
|
|
240
|
+
|
|
241
|
+
/** Reads the account, session id and folder once per session; the global config lives in CLAUDE_CONFIG_DIR, else in HOME. */
|
|
242
|
+
const refreshIdentity = async ($: Api): Promise<void> => {
|
|
243
|
+
const [sessionId, root, home, configDir, baseUrl] = await Promise.all([$.session.id(), $.session.root(), env($, 'HOME'), env($, 'CLAUDE_CONFIG_DIR'), env($, 'ANTHROPIC_BASE_URL')])
|
|
244
|
+
const configPath = configDir !== '' ? `${configDir}/.claude.json` : `${home}/.claude.json`
|
|
245
|
+
const config = home === '' && configDir === '' ? '' : await $.fs.read(configPath).catch(() => '')
|
|
246
|
+
await update($, identity, () => ({ account: accountOf(config, baseUrl), sessionId, folder: folderOf(root, home) }))
|
|
247
|
+
}
|
|
248
|
+
|
|
199
249
|
const sessionStart = atom({ plugin: 'project-brain-activity', key: 'sessionStart' } as const, 0, { shape: 'session-start-1' })
|
|
200
250
|
const commitCalls = atom({ plugin: 'project-brain-activity', key: 'commitCalls' } as const, [] as CommitCall[], { shape: 'commit-calls-1' })
|
|
201
251
|
const history = atom({ plugin: 'project-brain-activity', key: 'history' } as const, { state: 'idle', rows: [], more: 0, loadedAt: 0 } as HistoryView, { shape: 'history-1' })
|
|
@@ -244,7 +294,16 @@ const lastLines = (raw: string | undefined, count: number): string =>
|
|
|
244
294
|
|
|
245
295
|
export const dollars = (usd: number): string => `~$${usd < 10 ? usd.toFixed(2) : usd.toFixed(1)}`
|
|
246
296
|
|
|
247
|
-
|
|
297
|
+
/** A duration as people read it: `4.2 s` under a minute, `3 min 05 s` under an hour, `2 h 21 min` beyond. */
|
|
298
|
+
export const seconds = (ms: number | undefined): string => {
|
|
299
|
+
if (ms === undefined) return ''
|
|
300
|
+
const total = Math.max(0, ms) / 1000
|
|
301
|
+
if (total < 60) return `${total.toFixed(1)} s`
|
|
302
|
+
const whole = Math.round(total)
|
|
303
|
+
if (whole < 3600) return `${Math.floor(whole / 60)} min ${String(whole % 60).padStart(2, '0')} s`
|
|
304
|
+
const minutes = Math.round(whole / 60)
|
|
305
|
+
return `${Math.floor(minutes / 60)} h ${String(minutes % 60).padStart(2, '0')} min`
|
|
306
|
+
}
|
|
248
307
|
|
|
249
308
|
export const fit = (value: string, width: number): string => {
|
|
250
309
|
const room = Math.max(1, width)
|
|
@@ -269,6 +328,13 @@ export const compact = (count: number): string => {
|
|
|
269
328
|
return `${trimmed(count / 1_000_000)}M`
|
|
270
329
|
}
|
|
271
330
|
|
|
331
|
+
/**
|
|
332
|
+
* The main loop's fill against the window that triggers compaction, when the breakdown measured it:
|
|
333
|
+
* on a 1M model that compacts near 367k, 28 % of 1M is really 70 % of the room left before compacting.
|
|
334
|
+
*/
|
|
335
|
+
export const againstCompaction = (usage: ContextUsage, compactionWindow: number): ContextUsage =>
|
|
336
|
+
usage.tokens === undefined || compactionWindow <= 0 || compactionWindow >= usage.window ? usage : { tokens: usage.tokens, window: compactionWindow }
|
|
337
|
+
|
|
272
338
|
export const contextPercentOf = (usage: ContextUsage): number | undefined =>
|
|
273
339
|
usage.tokens === undefined || usage.window <= 0 ? undefined : (usage.percent ?? (usage.tokens / usage.window) * 100)
|
|
274
340
|
|
|
@@ -283,8 +349,8 @@ export const contextLabel = (usage: ContextUsage): string => {
|
|
|
283
349
|
* The context of the selected loop: the session's own figures for the main loop; for a subagent, its last
|
|
284
350
|
* model request (input + cache written + cache read) over the main window when it runs the same model.
|
|
285
351
|
*/
|
|
286
|
-
export const scopedContext = (snap: Pick<Snapshot, 'context' | 'steps'
|
|
287
|
-
if (scope === MAIN) return snap.context
|
|
352
|
+
export const scopedContext = (snap: Pick<Snapshot, 'context' | 'steps'> & { contextPart?: Pick<ContextPart, 'breakdown'> }, scope: string): ContextUsage => {
|
|
353
|
+
if (scope === MAIN) return againstCompaction(snap.context, snap.contextPart?.breakdown.window ?? 0)
|
|
288
354
|
const own = snap.steps[scope]
|
|
289
355
|
if (own === undefined) return { window: snap.context.window }
|
|
290
356
|
const sameModel = snap.steps[MAIN] !== undefined && snap.steps[MAIN].model === own.model
|
|
@@ -987,6 +1053,113 @@ export const defaultAgent = (records: AgentRecord[], picked: string): string =>
|
|
|
987
1053
|
return running[0]?.id ?? MAIN
|
|
988
1054
|
}
|
|
989
1055
|
|
|
1056
|
+
/** A model id as people say it: `claude-opus-5-5[1m]` → `opus 5.5`; anything else, trimmed. */
|
|
1057
|
+
export const modelLabel = (id: string): string => {
|
|
1058
|
+
const bare = id.trim().toLowerCase().replace(/\[[^\]]*\]$/, '').replace(/^claude-/, '').replace(/-\d{8}$/, '')
|
|
1059
|
+
const named = /^([a-z]+)-(\d+)(?:-(\d+))?$/.exec(bare)
|
|
1060
|
+
return named ? `${named[1]} ${named[2]}${named[3] ? `.${named[3]}` : ''}` : bare
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
// ---------------------------------------------------------------- pricing
|
|
1064
|
+
|
|
1065
|
+
/** USD per million tokens. Cache writes at the 5-minute rate, the one Claude Code uses. */
|
|
1066
|
+
export type Rates = { input: number; cacheWrite: number; cacheRead: number; output: number }
|
|
1067
|
+
|
|
1068
|
+
/** One model request's usage as the engine reports it; the cache fields may be null or absent. */
|
|
1069
|
+
export type StepUsage = {
|
|
1070
|
+
input_tokens?: number | null
|
|
1071
|
+
output_tokens?: number | null
|
|
1072
|
+
cache_creation_input_tokens?: number | null
|
|
1073
|
+
cache_read_input_tokens?: number | null
|
|
1074
|
+
}
|
|
1075
|
+
|
|
1076
|
+
const rates = (input: number, cacheWrite: number, cacheRead: number, output: number): Rates => ({ input, cacheWrite, cacheRead, output })
|
|
1077
|
+
|
|
1078
|
+
/** Public list prices as of 2026-11-17, from https://platform.claude.com/docs/en/about-claude/pricing, keyed by `modelLabel`. */
|
|
1079
|
+
const PRICES: Record<string, Rates> = {
|
|
1080
|
+
'fable 5.2': rates(8, 10, 0.2, 40),
|
|
1081
|
+
'fable 5.1': rates(10, 12.5, 0.25, 50),
|
|
1082
|
+
'fable 5': rates(10, 12.5, 1, 50),
|
|
1083
|
+
'opus 5.5': rates(4, 5, 0.2, 20),
|
|
1084
|
+
'opus 5': rates(5, 6.25, 0.5, 25),
|
|
1085
|
+
'opus 4.8': rates(5, 6.25, 0.5, 25),
|
|
1086
|
+
'opus 4.7': rates(5, 6.25, 0.5, 25),
|
|
1087
|
+
'opus 4.6': rates(5, 6.25, 0.5, 25),
|
|
1088
|
+
'opus 4.5': rates(5, 6.25, 0.5, 25),
|
|
1089
|
+
'opus 4.1': rates(15, 18.75, 1.5, 75),
|
|
1090
|
+
'opus 4': rates(15, 18.75, 1.5, 75),
|
|
1091
|
+
'sonnet 5.5': rates(2, 2.5, 0.1, 10),
|
|
1092
|
+
'sonnet 5': rates(2, 2.5, 0.2, 10),
|
|
1093
|
+
'sonnet 4.6': rates(3, 3.75, 0.3, 15),
|
|
1094
|
+
'sonnet 4.5': rates(3, 3.75, 0.3, 15),
|
|
1095
|
+
'sonnet 4': rates(3, 3.75, 0.3, 15),
|
|
1096
|
+
'haiku 4.5': rates(1, 1.25, 0.1, 5),
|
|
1097
|
+
}
|
|
1098
|
+
|
|
1099
|
+
/** Haiku 5.5 is priced by the size of each request's prompt: input, cache writes and cache reads together. */
|
|
1100
|
+
const HAIKU_5_5 = { label: 'haiku 5.5', promptLimit: 100_000, small: rates(0.1, 0.125, 0.01, 0.5), large: rates(0.5, 0.625, 0.05, 2.5) }
|
|
1101
|
+
|
|
1102
|
+
const tokenCount = (value: number | null | undefined): number => (typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0)
|
|
1103
|
+
|
|
1104
|
+
/** The rates for a model id and a request's prompt size; null for any model the price list does not name. */
|
|
1105
|
+
export const priceOf = (modelId: string, promptTokens = 0): Rates | null => {
|
|
1106
|
+
const label = modelLabel(modelId)
|
|
1107
|
+
if (label === HAIKU_5_5.label) return promptTokens > HAIKU_5_5.promptLimit ? HAIKU_5_5.large : HAIKU_5_5.small
|
|
1108
|
+
return PRICES[label] ?? null
|
|
1109
|
+
}
|
|
1110
|
+
|
|
1111
|
+
/** The estimated USD one model request cost; null when its model has no known price. */
|
|
1112
|
+
export const costOf = (usage: StepUsage, modelId: string): number | null => {
|
|
1113
|
+
const input = tokenCount(usage.input_tokens)
|
|
1114
|
+
const cacheWrite = tokenCount(usage.cache_creation_input_tokens)
|
|
1115
|
+
const cacheRead = tokenCount(usage.cache_read_input_tokens)
|
|
1116
|
+
const price = priceOf(modelId, input + cacheWrite + cacheRead)
|
|
1117
|
+
if (price === null) return null
|
|
1118
|
+
const perToken = price.input * input + price.cacheWrite * cacheWrite + price.cacheRead * cacheRead + price.output * tokenCount(usage.output_tokens)
|
|
1119
|
+
return perToken / 1_000_000
|
|
1120
|
+
}
|
|
1121
|
+
|
|
1122
|
+
/** Adds one model request to its loop's running total; a request without usage leaves the totals as they were. */
|
|
1123
|
+
export const addUsage = (all: Record<string, AgentUsage>, agentId: string, usage: StepUsage | undefined, modelId: string): Record<string, AgentUsage> => {
|
|
1124
|
+
if (!usage) return all
|
|
1125
|
+
const before = all[agentId] ?? { input: 0, output: 0, cacheWrite: 0, cacheRead: 0, usd: 0 }
|
|
1126
|
+
const step = costOf(usage, modelId)
|
|
1127
|
+
return {
|
|
1128
|
+
...all,
|
|
1129
|
+
[agentId]: {
|
|
1130
|
+
input: before.input + tokenCount(usage.input_tokens),
|
|
1131
|
+
output: before.output + tokenCount(usage.output_tokens),
|
|
1132
|
+
cacheWrite: before.cacheWrite + tokenCount(usage.cache_creation_input_tokens),
|
|
1133
|
+
cacheRead: before.cacheRead + tokenCount(usage.cache_read_input_tokens),
|
|
1134
|
+
usd: before.usd === null || step === null ? null : before.usd + step,
|
|
1135
|
+
},
|
|
1136
|
+
}
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
export const totalTokens = (usage: AgentUsage): number => usage.input + usage.cacheWrite + usage.cacheRead + usage.output
|
|
1140
|
+
|
|
1141
|
+
/** `~$1.84` from ten cents up, `~$0.045` below, `<$0.001` for dust. */
|
|
1142
|
+
export const estimatedUsd = (usd: number): string => {
|
|
1143
|
+
if (usd < 0.001) return '<$0.001'
|
|
1144
|
+
return `~$${usd < 0.1 ? usd.toFixed(3) : usd.toFixed(2)}`
|
|
1145
|
+
}
|
|
1146
|
+
|
|
1147
|
+
const USAGE_GAP = ' '
|
|
1148
|
+
const LABEL_ROOM = 12
|
|
1149
|
+
|
|
1150
|
+
/**
|
|
1151
|
+
* The usage text that goes before a row's right-hand `base` (its duration) in `width` columns, gap included:
|
|
1152
|
+
* `412k tok · ~$1.84 `, then without the price, then nothing, as the room for a readable label runs out.
|
|
1153
|
+
*/
|
|
1154
|
+
export const usageRight = (usage: AgentUsage | undefined, base: string, width: number): string => {
|
|
1155
|
+
if (usage === undefined) return ''
|
|
1156
|
+
const total = totalTokens(usage)
|
|
1157
|
+
if (total <= 0) return ''
|
|
1158
|
+
const tokens = `${compact(total)} tok`
|
|
1159
|
+
const choices = usage.usd === null ? [tokens] : [`${tokens} · ${estimatedUsd(usage.usd)}`, tokens]
|
|
1160
|
+
return choices.map(text => `${text}${USAGE_GAP}`).find(text => text.length + base.length + LABEL_ROOM + 8 <= width) ?? ''
|
|
1161
|
+
}
|
|
1162
|
+
|
|
990
1163
|
export const mergeAgent = (list: AgentRecord[], record: AgentRecord): AgentRecord[] => {
|
|
991
1164
|
const known = list.find(one => one.id === record.id)
|
|
992
1165
|
const merged = known ? { ...known, ...record, startedAt: known.startedAt, description: record.description || known.description } : record
|
|
@@ -1047,7 +1220,7 @@ export const windowStart = (state: PaneScroll, total: number, room: number): num
|
|
|
1047
1220
|
|
|
1048
1221
|
// ---------------------------------------------------------------- pane model
|
|
1049
1222
|
|
|
1050
|
-
export type Tone = 'success' | 'error' | 'warning' | 'subtle' | 'permission' | 'claude' | 'suggestion' | 'diffAdded' | 'diffRemoved'
|
|
1223
|
+
export type Tone = 'success' | 'error' | 'warning' | 'subtle' | 'permission' | 'claude' | 'suggestion' | 'literal' | 'diffAdded' | 'diffRemoved'
|
|
1051
1224
|
export type Span = { text: string; color?: Tone | (string & {}); dim?: boolean; bold?: boolean; inverse?: boolean }
|
|
1052
1225
|
export type Action =
|
|
1053
1226
|
| { kind: 'toggle'; key: string }
|
|
@@ -1069,6 +1242,8 @@ export type Snapshot = {
|
|
|
1069
1242
|
usd: number
|
|
1070
1243
|
context: ContextUsage
|
|
1071
1244
|
steps: Record<string, StepContext>
|
|
1245
|
+
mainModel: string
|
|
1246
|
+
who: SessionIdentityLine
|
|
1072
1247
|
accent: string
|
|
1073
1248
|
opened: string[]
|
|
1074
1249
|
patches: Record<string, DiffPatch>
|
|
@@ -1182,6 +1357,9 @@ export const buildPane = (snap: Snapshot, width: number): PaneModel => {
|
|
|
1182
1357
|
const { list, flipped, opened, patches, records } = snap
|
|
1183
1358
|
const accent = snap.accent
|
|
1184
1359
|
const scope = defaultAgent(records, snap.picked)
|
|
1360
|
+
const modelOf = (id: string): string =>
|
|
1361
|
+
modelLabel(snap.steps[id]?.model ?? (id === MAIN ? snap.mainModel : records.find(one => one.id === id)?.model) ?? '')
|
|
1362
|
+
const mainLabel = modelOf(MAIN)
|
|
1185
1363
|
const current: Tab = snap.tabByAgent[scope] ?? 'summary'
|
|
1186
1364
|
const cambios = cambiosScopeOf(snap, scope)
|
|
1187
1365
|
const agent = records.find(one => one.id === scope)
|
|
@@ -1480,8 +1658,8 @@ export const buildPane = (snap: Snapshot, width: number): PaneModel => {
|
|
|
1480
1658
|
]),
|
|
1481
1659
|
),
|
|
1482
1660
|
...section(`history-${scope}`, `${ICONS.log} ${scope === MAIN ? 'Historial de comandos' : 'Historial de este agente'} · ${commands.length}`, false, historyRows),
|
|
1483
|
-
...section(`context-${scope}`, `${ICONS.brain}
|
|
1484
|
-
|
|
1661
|
+
...section(`context-${scope}`, `${ICONS.brain} Archivos consultados · ${readFiles.length}`, false, () => [
|
|
1662
|
+
...(readFiles.length === 0 ? [line('ctx-none', ' Ninguno todavía.', { dim: true })] : []),
|
|
1485
1663
|
...readFiles.slice(0, 30).map(path => line(`ctx-${path}`, ` ${fileIcon(path)} ${path}`)),
|
|
1486
1664
|
]),
|
|
1487
1665
|
]
|
|
@@ -1514,17 +1692,19 @@ export const buildPane = (snap: Snapshot, width: number): PaneModel => {
|
|
|
1514
1692
|
spans: [span(` ${label}${look ? ' ' : ' '}`, { inverse: isOn, bold: isOn }), ...(look ? [span(`${look.icon} `, { color: look.color, inverse: isOn })] : []), span(' ')],
|
|
1515
1693
|
})
|
|
1516
1694
|
|
|
1517
|
-
const header: Row[] = [{ key: 'title', cells: [{ spans: [span('ACTIVIDAD', { bold: true })] }], right: [status ? [status] : [], headerRunning(snap.running), headerBlocked(snap.blocked, snap.running.now)].filter(one => one.length > 0).flatMap((one, index) => (index === 0 ? one : [span(' '), ...one])) }]
|
|
1695
|
+
const header: Row[] = [{ key: 'title', cells: [{ spans: [snap.who.account !== '' ? span(fit(snap.who.account, Math.max(8, width - 24)), { color: 'literal', bold: true }) : span('ACTIVIDAD', { bold: true })] }], right: [status ? [status] : [], headerRunning(snap.running), headerBlocked(snap.blocked, snap.running.now)].filter(one => one.length > 0).flatMap((one, index) => (index === 0 ? one : [span(' '), ...one])) }]
|
|
1696
|
+
const facts = [mainLabel, snap.who.sessionId.slice(0, 8), snap.who.folder].filter(one => one !== '')
|
|
1697
|
+
if (facts.length > 0) header.push(line('session-facts', facts.join(' · '), { dim: true }))
|
|
1518
1698
|
if (records.length > 0) {
|
|
1519
1699
|
header.push({
|
|
1520
1700
|
key: 'agents',
|
|
1521
|
-
cells: agentChipsGrouped({ records, scope, expanded: snap.agentsPart.expanded, width }),
|
|
1701
|
+
cells: agentChipsGrouped({ records, scope, expanded: snap.agentsPart.expanded, width, modelOf }),
|
|
1522
1702
|
})
|
|
1523
1703
|
}
|
|
1524
1704
|
if (agent) {
|
|
1525
1705
|
const look = AGENT_LOOK[agent.state]
|
|
1526
1706
|
header.push(
|
|
1527
|
-
{ key: 'agent-head', cells: [{ spans: [span(`${ICONS.agent} ${shortName(agent)}`, { color: accent, bold: true }), span(` · ${agent.id.slice(0, 4)} · `, { dim: true }), span(look.label, { color: look.color })] }] },
|
|
1707
|
+
{ key: 'agent-head', cells: [{ spans: [span(`${ICONS.agent} ${shortName(agent)}`, { color: accent, bold: true }), span(` · ${agent.id.slice(0, 4)} · `, { dim: true }), span(look.label, { color: look.color }), ...(modelOf(agent.id) ? [span(` · ${modelOf(agent.id)}`, { dim: true })] : [])] }] },
|
|
1528
1708
|
line('agent-task', agent.description, { dim: true }),
|
|
1529
1709
|
...rowsAgentReport(agent, snap.agentsPart.reports[agent.id], width),
|
|
1530
1710
|
)
|
|
@@ -1633,7 +1813,8 @@ const readSnapshot = async ($: Api): Promise<Snapshot> => {
|
|
|
1633
1813
|
read($, history), read($, historyFiles), read($, accentColor),
|
|
1634
1814
|
readAgents($), readCi($), readContext($), readProgress($), readRunning($), readBlocked($), readSavings($),
|
|
1635
1815
|
])
|
|
1636
|
-
|
|
1816
|
+
const [model, who] = await Promise.all([read($, mainModel), read($, identity)])
|
|
1817
|
+
return { mainModel: model, who, accent, list, tabByAgent, flipped, files, usd, context, steps, opened, patches, records, picked, isWorking, commitList, scopeByAgent, branchView, view, historyView, historyFiles: historyFilesBySha, agentsPart, ci, contextPart, progress, running, blocked, savings }
|
|
1637
1818
|
}
|
|
1638
1819
|
|
|
1639
1820
|
/** Fills in the line counts and files of up to ten commits that have none yet. */
|
|
@@ -1705,6 +1886,12 @@ async function mainSessionStart($: Api, e: Parameters<Hook<'session.start'>>[1],
|
|
|
1705
1886
|
await update($, sessionStart, () => sessionStartOf(stored, now, list, known))
|
|
1706
1887
|
scheduleRescan($ as Api)
|
|
1707
1888
|
void refreshAccent($ as Api).catch(() => undefined)
|
|
1889
|
+
void $.session.model().then(model => update($, mainModel, () => model)).catch(() => undefined)
|
|
1890
|
+
void refreshIdentity($ as Api).catch(() => undefined)
|
|
1891
|
+
if (!autoOpenSent && (await read($, autoOpen))) {
|
|
1892
|
+
autoOpenSent = true
|
|
1893
|
+
void $.ui.open(PANE_ARGS).then(opened => (opened?.isPlaced === false ? undefined : paneOpened($ as Api))).catch(() => undefined)
|
|
1894
|
+
}
|
|
1708
1895
|
return next(e)
|
|
1709
1896
|
}
|
|
1710
1897
|
|
|
@@ -1896,6 +2083,7 @@ export const register: Register = on => {
|
|
|
1896
2083
|
if (used) {
|
|
1897
2084
|
const tokens = used.input_tokens + used.cache_creation_input_tokens + used.cache_read_input_tokens
|
|
1898
2085
|
await update($, stepContext, all => ({ ...all, [e.agentId ?? MAIN]: { tokens, model: used.model } })).catch(() => undefined)
|
|
2086
|
+
await update($, agentUsage, all => addUsage(all, e.agentId ?? MAIN, used, used.model ?? '')).catch(() => undefined)
|
|
1899
2087
|
}
|
|
1900
2088
|
return result
|
|
1901
2089
|
})
|
|
@@ -1912,6 +2100,7 @@ export const register: Register = on => {
|
|
|
1912
2100
|
state: 'running',
|
|
1913
2101
|
startedAt: await $.clock.now(),
|
|
1914
2102
|
}
|
|
2103
|
+
if (spawned.model) record.model = spawned.model
|
|
1915
2104
|
await update($, agents, list => mergeAgent(list, record))
|
|
1916
2105
|
}
|
|
1917
2106
|
return spawned
|
|
@@ -2091,7 +2280,7 @@ export const register: Register = on => {
|
|
|
2091
2280
|
|
|
2092
2281
|
const spansOf = (spans: Span[]) =>
|
|
2093
2282
|
spans.map(one => (
|
|
2094
|
-
<Text {...paint(one)}
|
|
2283
|
+
<Text {...paint(one)} bold={one.bold}>{one.text}</Text>
|
|
2095
2284
|
))
|
|
2096
2285
|
const cellOf = (rowKey: string, cell: Cell, index: number) => {
|
|
2097
2286
|
const action = cell.action
|
|
@@ -2120,7 +2309,7 @@ export const register: Register = on => {
|
|
|
2120
2309
|
)
|
|
2121
2310
|
}
|
|
2122
2311
|
|
|
2123
|
-
return <Box flexDirection="column" width={width} height={Math.max(1, e.props.scroll.bodyRows)}
|
|
2312
|
+
return <Box flexDirection="column" width={width} height={Math.max(1, e.props.scroll.bodyRows)}>{frame.rows.map(row => rowOf(clampRow(row, width)))}</Box>
|
|
2124
2313
|
})
|
|
2125
2314
|
on('session.start', async ($, e, next) => {
|
|
2126
2315
|
const once = onceNext(next as never)
|