@accodev/hairline 0.47.0 → 0.47.2
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/LICENSE +21 -21
- package/README.md +69 -69
- package/package.json +29 -29
- package/pi/anim.ts +138 -138
- package/pi/index.ts +598 -598
- package/pi/line.ts +504 -504
package/pi/line.ts
CHANGED
|
@@ -1,504 +1,504 @@
|
|
|
1
|
-
import { truncateToWidth, visibleWidth } from '@earendil-works/pi-tui'
|
|
2
|
-
import { scanCells, SECONDS_WIDTH } from './anim.ts'
|
|
3
|
-
|
|
4
|
-
// The footer as text. Pi hands every line to the terminal as is, so the colors are SGR codes for
|
|
5
|
-
// the 16 palette slots: each person's terminal scheme picks the shades, as in Claude Code.
|
|
6
|
-
|
|
7
|
-
// Fixed widths, so a changing figure never moves the ones after it on the line.
|
|
8
|
-
// The terminal's columns give the readout 12 cells, as in Claude Code.
|
|
9
|
-
export const READOUT_WIDTH = 12
|
|
10
|
-
export const TPS_WIDTH = READOUT_WIDTH - ' t/s'.length
|
|
11
|
-
const TPS_MAX = 9999
|
|
12
|
-
// The widest count human() prints: 999.99M, 112.46B. At 6 cells, 112.46M wrapped the row.
|
|
13
|
-
export const COUNT_WIDTH = 7
|
|
14
|
-
// The padded token row: 4 counts, each a space and its unit, joined by 3 " / ".
|
|
15
|
-
export const TOKEN_SPLIT_WIDTH = 4 * COUNT_WIDTH + ' in out read write'.length + 3 * ' / '.length
|
|
16
|
-
// The graph fills the activity row to the token split's width: the phase glyph and its space, the
|
|
17
|
-
// readout, a space, the graph.
|
|
18
|
-
export const GRAPH_CELLS = TOKEN_SPLIT_WIDTH - 2 - READOUT_WIDTH - 1
|
|
19
|
-
// The first column: the repository over the context, cut with an ellipsis past this width.
|
|
20
|
-
export const WORKSPACE_WIDTH = 52
|
|
21
|
-
const COLUMN_GAP = 3
|
|
22
|
-
const LIMITS_GAP = 6
|
|
23
|
-
const WARN_FROM = 60
|
|
24
|
-
const BAD_FROM = 85
|
|
25
|
-
const BURN_MIN_HOURS = 0.1
|
|
26
|
-
export const HOUR_MS = 3_600_000
|
|
27
|
-
// Nerd Font glyphs are private-use code points that any other font draws as a box.
|
|
28
|
-
// U+21BB, Claude Code's first reset arrow, is missing from common terminal fonts.
|
|
29
|
-
export const NERD_GLYPHS = { reset: '\uf017', worktree: '\uf07b', branch: '\ue725' } as const // nf-fa-clock_o, nf-fa-folder, nf-dev-git_branch
|
|
30
|
-
const IDLE_GLYPH = '\u25cb' // a white circle, which every terminal font draws
|
|
31
|
-
export const PHASE_WORDS = { idle: 'idle', sending: 'sending', tool: 'running' } as const
|
|
32
|
-
// The readout, its gap and the graph: a running tool's name and argument fill them all.
|
|
33
|
-
export const TOOL_WIDTH = READOUT_WIDTH + 1 + GRAPH_CELLS
|
|
34
|
-
const SPINNER = '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'
|
|
35
|
-
const SPINNER_MS = 80
|
|
36
|
-
export const RATE_LIMIT_WINDOWS = [
|
|
37
|
-
{ kind: 'five_hour', label: '5h' },
|
|
38
|
-
{ kind: 'seven_day', label: '7d' },
|
|
39
|
-
] as const
|
|
40
|
-
|
|
41
|
-
const C = {
|
|
42
|
-
ok: 2, warn: 3, bad: 1, folder: 4, branch: 5, track: 8, marker: 15,
|
|
43
|
-
ramp: [10, 2, 11, 3, 1, 9],
|
|
44
|
-
} as const
|
|
45
|
-
// Pi's thinking levels; "minimal" and "off" have no color of their own and draw dim.
|
|
46
|
-
const EFFORT_COLORS: Record<string, number> = { low: 4, medium: 5, high: 13, xhigh: 1, max: 9 }
|
|
47
|
-
|
|
48
|
-
export type Phase = 'sending' | 'receiving' | 'tool' | 'idle'
|
|
49
|
-
export type Tool = { name: string; arg: string }
|
|
50
|
-
export type Limit = { kind: string; percentUsed: number; resetsAt?: string }
|
|
51
|
-
export type LimitStart = Record<string, { pct: number; at: number; resetsAt?: string }>
|
|
52
|
-
// The month's extra usage, in the currency the account is billed in.
|
|
53
|
-
export type Extra = { used: number; limit: number; currency: string; pct: number }
|
|
54
|
-
export type Stats = { input: number; write: number; read: number; output: number; costUsd: number | null }
|
|
55
|
-
export type Style = { color?: number; dim?: boolean; bold?: boolean; underline?: boolean; inverse?: boolean }
|
|
56
|
-
|
|
57
|
-
export type View = {
|
|
58
|
-
folder: string // the repository's name: in a worktree, the main checkout's folder
|
|
59
|
-
worktree: string | null
|
|
60
|
-
branch: string | null
|
|
61
|
-
model: string
|
|
62
|
-
effort: string | null
|
|
63
|
-
sessionId: string
|
|
64
|
-
context: { tokens: number | null; contextWindow: number; percent: number | null } | null
|
|
65
|
-
compactAt: number | null // percent of the window where auto-compaction starts
|
|
66
|
-
stats: Stats
|
|
67
|
-
turns: number
|
|
68
|
-
activeMs: number
|
|
69
|
-
costStart: number | null
|
|
70
|
-
limits: Limit[]
|
|
71
|
-
limitStart: LimitStart
|
|
72
|
-
extra: Extra | null
|
|
73
|
-
phase: Phase
|
|
74
|
-
tools: Tool[]
|
|
75
|
-
readout: string // the readout as the animation shows it, READOUT_WIDTH or TOOL_WIDTH cells
|
|
76
|
-
graph: string // the graph, GRAPH_CELLS cells
|
|
77
|
-
sweepMs: number // the time into the sending scan
|
|
78
|
-
isLit: boolean // the graph draws at full strength while a reply streams or a request waits
|
|
79
|
-
hasNerdFont: boolean
|
|
80
|
-
open: 'ledger' | 'model' | 'effort' | null
|
|
81
|
-
hover: string | null // the action of the part under the mouse pointer
|
|
82
|
-
models: { label: string; isCurrent: boolean }[] // the models the picker offers
|
|
83
|
-
efforts: string[] // the thinking levels the model supports
|
|
84
|
-
lastTurn: { tokens: number; ms: number; usd: number | null } | null
|
|
85
|
-
lastRequestAt: number | null
|
|
86
|
-
cacheTtlMinutes: number
|
|
87
|
-
money: (usd: number) => string
|
|
88
|
-
statuses: string[]
|
|
89
|
-
now: number
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
export function paint(text: string, s: Style = {}): string {
|
|
93
|
-
const codes: number[] = []
|
|
94
|
-
if (s.bold) codes.push(1)
|
|
95
|
-
if (s.dim) codes.push(2)
|
|
96
|
-
if (s.underline) codes.push(4)
|
|
97
|
-
if (s.inverse) codes.push(7)
|
|
98
|
-
if (s.color !== undefined) codes.push(s.color < 8 ? 30 + s.color : 90 + s.color - 8)
|
|
99
|
-
return codes.length && text ? `\x1b[${codes.join(';')}m${text}\x1b[0m` : text
|
|
100
|
-
}
|
|
101
|
-
const dim = (text: string) => paint(text, { dim: true })
|
|
102
|
-
const SEP = dim(' · ')
|
|
103
|
-
|
|
104
|
-
export const counted = (s: Stats) => s.input + s.write + s.read + s.output
|
|
105
|
-
|
|
106
|
-
function severity(pct: number): number {
|
|
107
|
-
return pct >= BAD_FROM ? C.bad : pct >= WARN_FROM ? C.warn : C.ok
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
// Red at the compaction point, which is where the context runs out in practice.
|
|
111
|
-
function rampColor(pct: number, compactAt: number | null): number {
|
|
112
|
-
const share = pct / (compactAt ?? 100)
|
|
113
|
-
return C.ramp[Math.max(0, Math.min(C.ramp.length - 1, Math.floor(share * C.ramp.length)))]!
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
// Largest first. Each cut is where the unit below would round up to 1000: 999,500 prints 1000k
|
|
117
|
-
// with whole thousands, 999.995M prints 1000.00M with 2 decimals.
|
|
118
|
-
const BIG_UNITS = [
|
|
119
|
-
['Q', 1e15, 999_995e9],
|
|
120
|
-
['T', 1e12, 999_995e6],
|
|
121
|
-
['B', 1e9, 999_995e3],
|
|
122
|
-
['M', 1e6, 999_500],
|
|
123
|
-
] as const
|
|
124
|
-
|
|
125
|
-
export function human(n: number): string {
|
|
126
|
-
for (const [suffix, size, cut] of BIG_UNITS) {
|
|
127
|
-
if (n >= cut) return `${(n / size).toFixed(2).replace(/\.?0+$/, '')}${suffix}`
|
|
128
|
-
}
|
|
129
|
-
if (n >= 1_000) return `${Math.round(n / 1_000)}k`
|
|
130
|
-
return String(n)
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
const DURATION_UNITS = [
|
|
134
|
-
['days', 86_400_000, 'd'],
|
|
135
|
-
['hours', 3_600_000, 'h'],
|
|
136
|
-
['minutes', 60_000, 'm'],
|
|
137
|
-
['seconds', 1_000, 's'],
|
|
138
|
-
] as const
|
|
139
|
-
type DurationFormatter = { format(d: Partial<Record<string, number>>): string }
|
|
140
|
-
// Node 22 has no Intl.DurationFormat; its narrow English output is the fallback's.
|
|
141
|
-
const DurationFormat = (Intl as unknown as { DurationFormat?: new (l?: string, o?: object) => DurationFormatter }).DurationFormat
|
|
142
|
-
const durationFormat: DurationFormatter = DurationFormat
|
|
143
|
-
? new DurationFormat(undefined, { style: 'narrow' })
|
|
144
|
-
: { format: d => DURATION_UNITS.filter(([unit]) => d[unit]).map(([unit, , short]) => `${d[unit]}${short}`).join(' ') || '0s' }
|
|
145
|
-
|
|
146
|
-
// 2 units, as humanize-duration and pretty-ms default to, so every time on the line has one form.
|
|
147
|
-
export function duration(ms: number): string {
|
|
148
|
-
const largest = DURATION_UNITS.findIndex(([, size]) => ms >= size)
|
|
149
|
-
const first = largest === -1 ? DURATION_UNITS.length - 1 : largest // under 1 second shows "0s"
|
|
150
|
-
const shown = DURATION_UNITS.slice(first, first + 2)
|
|
151
|
-
const step = shown[shown.length - 1]![1]
|
|
152
|
-
let left = Math.round(Math.max(0, ms) / step) * step
|
|
153
|
-
const parts: Partial<Record<string, number>> = {}
|
|
154
|
-
for (const [unit, size] of shown) {
|
|
155
|
-
parts[unit] = Math.floor(left / size)
|
|
156
|
-
left -= parts[unit]! * size
|
|
157
|
-
}
|
|
158
|
-
return durationFormat.format(parts)
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
export function modelLabel(id: string): string {
|
|
162
|
-
const [family, ...version] = id.replace(/^claude-/, '').replace(/\[.*\]$/, '').replace(/-\d{8}$/, '').split('-')
|
|
163
|
-
return version.length ? `${family} ${version.join('.')}` : family ?? id
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
export function basename(path: string): string {
|
|
167
|
-
return path.replace(/[\\/]+$/, '').split(/[\\/]/).pop() || path
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
// The argument that says most about a call. Pi's built-in tools and Claude Code's share these keys.
|
|
171
|
-
const ARG_KEYS = ['description', 'command', 'file_path', 'path', 'notebook_path', 'pattern', 'url', 'query', 'subagent_type', 'agent'] as const
|
|
172
|
-
const PATH_KEYS = new Set(['file_path', 'path', 'notebook_path'])
|
|
173
|
-
|
|
174
|
-
export function toolArg(input: unknown): string {
|
|
175
|
-
const args = (input && typeof input === 'object' ? input : {}) as Record<string, unknown>
|
|
176
|
-
const key = ARG_KEYS.find(k => typeof args[k] === 'string' && args[k])
|
|
177
|
-
if (!key) return ''
|
|
178
|
-
const value = args[key] as string
|
|
179
|
-
return PATH_KEYS.has(key) ? basename(value) : key === 'url' ? value.replace(/^https?:\/\/(www\.)?/, '') : value
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
export function toolName(name: string): string {
|
|
183
|
-
return name.startsWith('mcp__') ? name.split('__').pop()! : name
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
// Exactly `width` cells. One call: its name and argument. Parallel calls: their count, then each
|
|
187
|
-
// call's name and argument, so every tool the turn runs shows, not the first alone.
|
|
188
|
-
export function toolReadout(tools: Tool[], width: number): { text: string; bright: number } {
|
|
189
|
-
const first = tools[0]
|
|
190
|
-
if (!first) return { text: PHASE_WORDS.tool.padStart(width), bright: 0 }
|
|
191
|
-
const head = tools.length < 2 ? '' : `${tools.length} tools `
|
|
192
|
-
const full = (head + tools.map(t => `${t.name} ${t.arg}`.trim()).join(' · ')).replace(/\s+/g, ' ')
|
|
193
|
-
const text = full.length > width ? `${full.slice(0, width - 1)}…` : full.padEnd(width)
|
|
194
|
-
return { text, bright: Math.min(head ? head.length - 1 : first.name.length, width) }
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
// The readout's target text for a phase, before the animation scrambles it.
|
|
198
|
-
export function readoutTarget(phase: Phase, tps: number, tools: Tool[]): { text: string; bright: number } {
|
|
199
|
-
if (phase === 'receiving') return { text: `${String(Math.min(TPS_MAX, tps)).padStart(TPS_WIDTH)} t/s`, bright: TPS_WIDTH }
|
|
200
|
-
if (phase === 'tool') return toolReadout(tools, TOOL_WIDTH)
|
|
201
|
-
// Sending: the readout takes the graph's first SECONDS_WIDTH cells for the time after "waiting...".
|
|
202
|
-
if (phase === 'sending') return { text: ' '.repeat(READOUT_WIDTH + SECONDS_WIDTH), bright: 0 }
|
|
203
|
-
return { text: PHASE_WORDS[phase].padStart(READOUT_WIDTH), bright: 0 }
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
function phaseGlyph(v: View): string {
|
|
208
|
-
switch (v.phase) {
|
|
209
|
-
case 'sending': return paint('↑ ', { color: C.folder })
|
|
210
|
-
case 'receiving': return paint('↓ ', { color: C.ok })
|
|
211
|
-
case 'tool': return paint(`${SPINNER[Math.floor(v.now / SPINNER_MS) % SPINNER.length]} `, { color: C.warn })
|
|
212
|
-
case 'idle': return dim(`${IDLE_GLYPH} `)
|
|
213
|
-
}
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
function percent(value: number): string {
|
|
217
|
-
return paint(`${Math.round(value)}%`, { color: severity(value) })
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
// claude.ai's usage endpoint gives amounts in the currency's minor units: 972 with 2 decimal
|
|
222
|
-
// places is 9.72. Its shape is undocumented, so anything unexpected reads as no extra usage.
|
|
223
|
-
// The endpoint reports the account's 5h and 7d use, other sessions' included. A response header
|
|
224
|
-
// reports it too, but only when this session sends a request.
|
|
225
|
-
export function readUsageLimits(text: string): Limit[] {
|
|
226
|
-
const body = JSON.parse(text) as Record<string, { utilization?: number | null; resets_at?: string | null } | null | undefined>
|
|
227
|
-
return RATE_LIMIT_WINDOWS.flatMap(({ kind }) => {
|
|
228
|
-
const w = body[kind]
|
|
229
|
-
if (typeof w?.utilization !== 'number') return []
|
|
230
|
-
return [{ kind, percentUsed: Math.round(w.utilization * 10) / 10, ...(w.resets_at ? { resetsAt: w.resets_at } : {}) }]
|
|
231
|
-
})
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
export function readExtraBody(text: string): Extra | null {
|
|
235
|
-
const x = (JSON.parse(text) as { extra_usage?: { is_enabled?: boolean; monthly_limit?: number | null; used_credits?: number | null; utilization?: number | null; currency?: string | null; decimal_places?: number | null } | null }).extra_usage
|
|
236
|
-
if (!x?.is_enabled || typeof x.monthly_limit !== 'number' || typeof x.used_credits !== 'number' || x.monthly_limit <= 0) return null
|
|
237
|
-
const scale = 10 ** (x.decimal_places ?? 2)
|
|
238
|
-
const used = x.used_credits / scale
|
|
239
|
-
const limit = x.monthly_limit / scale
|
|
240
|
-
return { used, limit, currency: x.currency || 'USD', pct: x.utilization ?? (used / limit) * 100 }
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
// 9.72 keeps its cents, a whole 100 drops them.
|
|
244
|
-
export function amount(value: number, currency: string): string {
|
|
245
|
-
const digits = Number.isInteger(value) ? 0 : 2
|
|
246
|
-
return new Intl.NumberFormat(undefined, { style: 'currency', currency, minimumFractionDigits: digits, maximumFractionDigits: 2 }).format(value)
|
|
247
|
-
}
|
|
248
|
-
|
|
249
|
-
// Extra usage is billed only after the 5h or 7d window is full, so the spend shows only then.
|
|
250
|
-
function extraSpend(v: View): string {
|
|
251
|
-
const x = v.extra
|
|
252
|
-
const isCapped = RATE_LIMIT_WINDOWS.some(({ kind }) => (v.limits.find(l => l.kind === kind)?.percentUsed ?? 0) >= 100)
|
|
253
|
-
return x && isCapped ?`${SEP}${dim('extra ')}${paint(amount(x.used, x.currency), { color: severity(x.pct) })}${dim(`/${amount(x.limit, x.currency)}`)}` : ''
|
|
254
|
-
}
|
|
255
|
-
|
|
256
|
-
export type Hit = { row: number; from: number; to: number; action: string }
|
|
257
|
-
|
|
258
|
-
// The part under the pointer is underlined, so it reads as a control before the click.
|
|
259
|
-
function hoverable(text: string, action: string | undefined, v: View): string {
|
|
260
|
-
return action && action === v.hover ? `\x1b[4m${text}\x1b[0m` : text
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
// A linked worktree's git folder is <main checkout>/.git/worktrees/<id>, so the main checkout names
|
|
264
|
-
// the repository. A submodule's is .git/modules/<name>, and it stays a repository of its own.
|
|
265
|
-
export function worktreeOf(gitDir: string, top: string): { name: string; worktree: string | null } {
|
|
266
|
-
const base = (p: string) => p.replace(/[\\/]+$/, '').split(/[\\/]/).pop() ?? p
|
|
267
|
-
const main = gitDir.match(/^(.*)[\\/]\.git[\\/]worktrees[\\/][^\\/]+[\\/]?$/)?.[1]
|
|
268
|
-
return main ? { name: base(main), worktree: base(top) } : { name: base(top), worktree: null }
|
|
269
|
-
}
|
|
270
|
-
|
|
271
|
-
// Exactly `width` cells: cut with an ellipsis, or padded.
|
|
272
|
-
function fit(text: string, width: number): string {
|
|
273
|
-
const cut = truncateToWidth(text, width, '…')
|
|
274
|
-
return cut + ' '.repeat(Math.max(0, width - visibleWidth(cut)))
|
|
275
|
-
}
|
|
276
|
-
|
|
277
|
-
// The worktree and the branch cut to fit the column with the repository, the parentheses, the
|
|
278
|
-
// separator and the glyphs. The longer name loses a cell first, so both stay readable.
|
|
279
|
-
export function cutWorkspace(folder: string, worktree: string | null, branch: string | null, hasGlyphs: boolean, width: number): { worktree: string; branch: string } {
|
|
280
|
-
const glyph = hasGlyphs ? 2 : 0
|
|
281
|
-
const fixed = folder.length + (worktree || branch ? 3 : 0) + (worktree && branch ? 3 : 0) + (worktree ? glyph : 0) + (branch ? glyph : 0)
|
|
282
|
-
const room = Math.max(0, width - fixed)
|
|
283
|
-
let w = worktree?.length ?? 0
|
|
284
|
-
let b = branch?.length ?? 0
|
|
285
|
-
while (w + b > room) {
|
|
286
|
-
if (w >= b && w > 1) w--
|
|
287
|
-
else if (b > 1) b--
|
|
288
|
-
else break
|
|
289
|
-
}
|
|
290
|
-
const cut = (name: string | null, n: number) => (!name ? '' : name.length <= n ? name : `${name.slice(0, Math.max(0, n - 1))}…`)
|
|
291
|
-
return { worktree: cut(worktree, w), branch: cut(branch, b) }
|
|
292
|
-
}
|
|
293
|
-
|
|
294
|
-
// The repository, then the worktree and the branch in parentheses: two rows leave them room.
|
|
295
|
-
function workspace(v: View, width: number): string {
|
|
296
|
-
if (!v.folder) return ''
|
|
297
|
-
const glyph = (g: string) => (v.hasNerdFont ? `${g} ` : '')
|
|
298
|
-
const cut = cutWorkspace(v.folder, v.worktree, v.branch, v.hasNerdFont, width)
|
|
299
|
-
const parts = [
|
|
300
|
-
v.worktree ? dim(glyph(NERD_GLYPHS.worktree) + cut.worktree) : '',
|
|
301
|
-
v.branch ? paint(glyph(NERD_GLYPHS.branch) + cut.branch, { color: C.branch }) : '',
|
|
302
|
-
].filter(Boolean)
|
|
303
|
-
return paint(v.folder, { color: C.folder }) + (parts.length ? `${dim(' (')}${parts.join(dim(' · '))}${dim(')')}` : '')
|
|
304
|
-
}
|
|
305
|
-
|
|
306
|
-
function contextCell(v: View): string {
|
|
307
|
-
const pct = v.context?.percent ?? null
|
|
308
|
-
const size = v.context?.tokens == null ? '---/---' : `${human(v.context.tokens)}/${human(v.context.contextWindow)}`
|
|
309
|
-
return [
|
|
310
|
-
pct === null ? dim('--%') : paint(`${Math.round(pct)}%`, { color: rampColor(pct, v.compactAt) }),
|
|
311
|
-
dim(` ${size}`),
|
|
312
|
-
v.compactAt === null ? '' : dim(` · compacts at ${Math.round(v.compactAt)}%`),
|
|
313
|
-
].join('')
|
|
314
|
-
}
|
|
315
|
-
|
|
316
|
-
// Idle, the readout stays empty: a dim glyph, a word and a flat graph only said so.
|
|
317
|
-
function activityRow(v: View): string {
|
|
318
|
-
if (v.phase === 'idle') return ''
|
|
319
|
-
if (v.phase === 'sending') {
|
|
320
|
-
// The word is dim and the time is at full strength: the time is what changes.
|
|
321
|
-
const [before, head, after] = scanCells(v.sweepMs, GRAPH_CELLS - SECONDS_WIDTH)
|
|
322
|
-
const scan = `${dim('─'.repeat(before))}${paint('━'.repeat(head), { color: C.folder })}${dim('─'.repeat(after))}`
|
|
323
|
-
return `${phaseGlyph(v)}${dim(v.readout.slice(0, -SECONDS_WIDTH))}${v.readout.slice(-SECONDS_WIDTH)} ${scan}`
|
|
324
|
-
}
|
|
325
|
-
const bright = v.phase === 'receiving' ? TPS_WIDTH : v.phase === 'tool' ? toolReadout(v.tools, TOOL_WIDTH).bright : 0
|
|
326
|
-
const readout = `${v.readout.slice(0, bright)}${dim(v.readout.slice(bright))}`
|
|
327
|
-
// A running tool's name fills the graph's cells too.
|
|
328
|
-
const dots = v.phase === 'tool' ? '' : ` ${paint(v.graph, { color: C.folder, dim: !v.isLit })}`
|
|
329
|
-
return `${phaseGlyph(v)}${readout}${dots}`
|
|
330
|
-
}
|
|
331
|
-
|
|
332
|
-
// Each kind costs a different price, so the line splits them as Pi's own footer does. Each count
|
|
333
|
-
// is padded to the widest human() gives, so a count that grows a digit moves none after it.
|
|
334
|
-
function tokenSplitRow(v: View): string {
|
|
335
|
-
if (counted(v.stats) === 0) return dim('--- tok')
|
|
336
|
-
const inverse = v.open === 'ledger'
|
|
337
|
-
return hoverable(paint([
|
|
338
|
-
[v.stats.input, 'in'], [v.stats.output, 'out'], [v.stats.read, 'read'], [v.stats.write, 'write'],
|
|
339
|
-
// One muted gray: the token split is a tally to glance at, the activity above it is live.
|
|
340
|
-
].map(([n, unit]) => `${human(n as number).padStart(COUNT_WIDTH)} ${unit}`).join(' / '), { inverse, dim: true }), 'ledger', v)
|
|
341
|
-
}
|
|
342
|
-
|
|
343
|
-
function limitCell(v: View, kind: string, label: string): string {
|
|
344
|
-
const w = v.limits.find(l => l.kind === kind)
|
|
345
|
-
if (!w) return ''
|
|
346
|
-
const reset = w.resetsAt ? dim(` ${v.hasNerdFont ? `${NERD_GLYPHS.reset} ` : ''}${duration(Date.parse(w.resetsAt) - v.now)}`) : ''
|
|
347
|
-
return `${dim(`${label} `)}${percent(w.percentUsed)}${reset}`
|
|
348
|
-
}
|
|
349
|
-
|
|
350
|
-
// The model and the thinking level on the first row, the session ID on the second, each part with
|
|
351
|
-
// the action a click on it runs.
|
|
352
|
-
function modelParts(v: View): { text: string; action?: string }[][] {
|
|
353
|
-
const top: { text: string; action?: string }[] = []
|
|
354
|
-
if (v.model) {
|
|
355
|
-
top.push({ text: paint(modelLabel(v.model), { inverse: v.open === 'model' }), action: v.models.length > 1 ? 'model' : undefined })
|
|
356
|
-
if (v.effort) {
|
|
357
|
-
const style: Style = EFFORT_COLORS[v.effort] === undefined ? { dim: true } : { color: EFFORT_COLORS[v.effort] }
|
|
358
|
-
top.push({ text: ' ' }, { text: paint(v.effort, { ...style, inverse: v.open === 'effort' }), action: v.efforts.length > 1 ? 'effort' : undefined })
|
|
359
|
-
}
|
|
360
|
-
}
|
|
361
|
-
// Dim only: slot 8 with dim on top vanished on dark terminal schemes.
|
|
362
|
-
const bottom = v.sessionId ? [{ text: dim(v.sessionId.slice(0, 8)), action: 'id' }] : []
|
|
363
|
-
return [top, bottom].map(parts => parts.map(p => ({ ...p, text: hoverable(p.text, p.action, v) })))
|
|
364
|
-
}
|
|
365
|
-
|
|
366
|
-
// The context bar across the whole footer: one cell per column is the finest step it can take.
|
|
367
|
-
function contextBar(pct: number | null, compactAt: number | null, cells: number): string {
|
|
368
|
-
const filled = pct === null ? 0 : Math.round((Math.min(pct, 100) / 100) * cells)
|
|
369
|
-
// In the last cell the marker would only repeat the rule's own end, so it hides there.
|
|
370
|
-
const marker = compactAt === null ? -1 : Math.floor((compactAt / 100) * cells)
|
|
371
|
-
let out = ''
|
|
372
|
-
for (let i = 0; i < cells; i++) {
|
|
373
|
-
const color = rampColor(((i + 0.5) / cells) * 100, compactAt)
|
|
374
|
-
// The track is dim text: slot 8 vanishes on translucent and dark backgrounds.
|
|
375
|
-
if (i === marker && i < cells - 1) out += paint('┃', i < filled ? { color } : { color: C.marker })
|
|
376
|
-
else out += i < filled ? paint('━', { color }) : dim('─')
|
|
377
|
-
}
|
|
378
|
-
return out
|
|
379
|
-
}
|
|
380
|
-
|
|
381
|
-
// Two rows of four columns, as in Claude Code: the workspace over the context, the activity over the
|
|
382
|
-
// tokens, 5h over 7d, the model over the session ID. The first two columns have fixed widths, so
|
|
383
|
-
// nothing moves as figures change; the limits and the model sit right. Then the rule.
|
|
384
|
-
function mainRows(v: View, width: number, hits: Hit[]): string[] {
|
|
385
|
-
const limits = [limitCell(v, 'five_hour', '5h'), limitCell(v, 'seven_day', '7d') + extraSpend(v)]
|
|
386
|
-
const limitsWidth = Math.max(...limits.map(visibleWidth))
|
|
387
|
-
const right = modelParts(v)
|
|
388
|
-
const rightTexts = right.map(parts => parts.map(p => p.text).join(''))
|
|
389
|
-
const rightWidth = Math.max(...rightTexts.map(visibleWidth))
|
|
390
|
-
const rest = COLUMN_GAP + TOKEN_SPLIT_WIDTH + 2 + limitsWidth + (limitsWidth ? LIMITS_GAP : 0) + rightWidth
|
|
391
|
-
// A narrow footer cuts the place first, as Claude Code's first column shrinks first.
|
|
392
|
-
const workspaceWidth = Math.max(12, Math.min(WORKSPACE_WIDTH, width - rest))
|
|
393
|
-
const left = [workspace(v, workspaceWidth), contextCell(v)].map(t => fit(t, workspaceWidth))
|
|
394
|
-
const middle = [activityRow(v), tokenSplitRow(v)].map(t => fit(t, TOKEN_SPLIT_WIDTH))
|
|
395
|
-
const leftWidth = workspaceWidth + COLUMN_GAP + TOKEN_SPLIT_WIDTH
|
|
396
|
-
const free = Math.max(2, width - leftWidth - limitsWidth - (limitsWidth ? LIMITS_GAP : 0) - rightWidth)
|
|
397
|
-
if (counted(v.stats) > 0) hits.push({ row: 1, from: workspaceWidth + COLUMN_GAP, to: workspaceWidth + COLUMN_GAP + visibleWidth(tokenSplitRow(v)), action: 'ledger' })
|
|
398
|
-
const rows = [0, 1].map(r => {
|
|
399
|
-
const rightPad = rightWidth - visibleWidth(rightTexts[r]!)
|
|
400
|
-
let at = leftWidth + free + limitsWidth + (limitsWidth ? LIMITS_GAP : 0) + rightPad
|
|
401
|
-
for (const p of right[r]!) {
|
|
402
|
-
const w = visibleWidth(p.text)
|
|
403
|
-
if (p.action && at + w <= width) hits.push({ row: r, from: at, to: at + w, action: p.action })
|
|
404
|
-
at += w
|
|
405
|
-
}
|
|
406
|
-
return truncateToWidth([
|
|
407
|
-
left[r], ' '.repeat(COLUMN_GAP), middle[r], ' '.repeat(free),
|
|
408
|
-
limitsWidth ? fit(limits[r]!, limitsWidth) + ' '.repeat(LIMITS_GAP) : '',
|
|
409
|
-
' '.repeat(rightPad), rightTexts[r],
|
|
410
|
-
].join(''), width, '')
|
|
411
|
-
})
|
|
412
|
-
return [...rows, contextBar(v.context?.percent ?? null, v.compactAt, width)]
|
|
413
|
-
}
|
|
414
|
-
|
|
415
|
-
// A picker's options, right-aligned under the line as Claude Code shows them, wrapped to the width.
|
|
416
|
-
function pickerRows(label: string, options: { text: string; action: string }[], width: number, firstRow: number, hits: Hit[], v: View): string[] {
|
|
417
|
-
const rows: { parts: { text: string; action?: string }[]; width: number }[] = []
|
|
418
|
-
let current = { parts: [{ text: dim(`${label} `) }] as { text: string; action?: string }[], width: label.length + 1 }
|
|
419
|
-
for (const o of options) {
|
|
420
|
-
const w = visibleWidth(o.text) + 1
|
|
421
|
-
if (current.width + w > width && current.parts.length > 1) {
|
|
422
|
-
rows.push(current)
|
|
423
|
-
current = { parts: [], width: 0 }
|
|
424
|
-
}
|
|
425
|
-
current.parts.push({ text: ' ' }, { ...o, text: hoverable(o.text, o.action, v) })
|
|
426
|
-
current.width += w
|
|
427
|
-
}
|
|
428
|
-
rows.push(current)
|
|
429
|
-
return rows.map((r, i) => {
|
|
430
|
-
let at = Math.max(0, width - r.width)
|
|
431
|
-
for (const p of r.parts) {
|
|
432
|
-
const w = visibleWidth(p.text)
|
|
433
|
-
if (p.action) hits.push({ row: firstRow + i, from: at, to: at + w, action: p.action })
|
|
434
|
-
at += w
|
|
435
|
-
}
|
|
436
|
-
return `${' '.repeat(Math.max(0, width - r.width))}${r.parts.map(p => p.text).join('')}`
|
|
437
|
-
})
|
|
438
|
-
}
|
|
439
|
-
|
|
440
|
-
function row(label: string, body: string): string {
|
|
441
|
-
return ` ${dim(label.padEnd(8))}${body}`
|
|
442
|
-
}
|
|
443
|
-
const fig = (value: string, unit?: string) => `${value}${unit ? dim(` ${unit}`) : ''}`
|
|
444
|
-
|
|
445
|
-
function ledger(v: View): string[] {
|
|
446
|
-
const { stats } = v
|
|
447
|
-
const hours = v.activeMs / HOUR_MS
|
|
448
|
-
const trackedUsd = stats.costUsd !== null && v.costStart !== null ? stats.costUsd - v.costStart : null
|
|
449
|
-
const hit = stats.read / Math.max(1, stats.read + stats.write + stats.input)
|
|
450
|
-
const cacheLeft = v.lastRequestAt === null ? null : v.cacheTtlMinutes * 60_000 - (v.now - v.lastRequestAt)
|
|
451
|
-
const cost = stats.costUsd === null ? dim('not reported') : [
|
|
452
|
-
fig(v.money(stats.costUsd)),
|
|
453
|
-
trackedUsd !== null && hours >= BURN_MIN_HOURS ? `${SEP}${fig(v.money(trackedUsd / hours), 'per active hour')}` : '',
|
|
454
|
-
v.lastTurn?.usd != null ? `${SEP}${dim('last turn ')}${fig(v.money(v.lastTurn.usd))}` : '',
|
|
455
|
-
].join('')
|
|
456
|
-
const tokens = [
|
|
457
|
-
fig(human(stats.input), 'in'), fig(human(stats.write), 'cache write'), fig(human(stats.read), 'cache read'),
|
|
458
|
-
fig(human(stats.output), 'out'), fig(`${Math.round(hit * 100)}%`, 'cache hit'),
|
|
459
|
-
...(cacheLeft === null ? [] : [cacheLeft > 0 ? dim(`cache warm ${duration(cacheLeft)}`) : paint('cache cold', { color: C.warn })]),
|
|
460
|
-
].join(SEP)
|
|
461
|
-
const turns = [
|
|
462
|
-
fig(String(v.turns), 'turns'),
|
|
463
|
-
...(v.activeMs > 0 ? [fig(duration(v.activeMs), 'active')] : []),
|
|
464
|
-
...(v.lastTurn ? [`${dim('last turn ')}${fig(human(v.lastTurn.tokens), `tok in ${duration(v.lastTurn.ms)}`)}`] : []),
|
|
465
|
-
].join(SEP)
|
|
466
|
-
const burns = RATE_LIMIT_WINDOWS.flatMap(({ kind, label }) => {
|
|
467
|
-
const w = v.limits.find(l => l.kind === kind)
|
|
468
|
-
if (!w) return []
|
|
469
|
-
const start = v.limitStart[kind]
|
|
470
|
-
const spanHours = start ? (v.now - start.at) / HOUR_MS : 0
|
|
471
|
-
const perHour = start && spanHours >= BURN_MIN_HOURS ? (w.percentUsed - start.pct) / spanHours : 0
|
|
472
|
-
const fullInMs = perHour > 0 ? ((100 - w.percentUsed) / perHour) * HOUR_MS : null
|
|
473
|
-
const resetsInMs = w.resetsAt ? Date.parse(w.resetsAt) - v.now : null
|
|
474
|
-
// Only a limit that fills before its reset needs a word.
|
|
475
|
-
const trend = perHour > 0
|
|
476
|
-
? `${dim(` +${perHour.toFixed(1)}%/h`)}${fullInMs === null || resetsInMs === null || fullInMs < resetsInMs ? paint(`, full in ${duration(fullInMs ?? 0)}`, { color: C.warn }) : ''}`
|
|
477
|
-
: dim(spanHours < BURN_MIN_HOURS ? ' measuring' : ' steady')
|
|
478
|
-
return [`${dim(`${label} `)}${percent(w.percentUsed)}${trend}`]
|
|
479
|
-
}).join(SEP)
|
|
480
|
-
return [row('cost', cost), row('tokens', tokens), row('turns', turns), ...(burns ? [row('limits', burns)] : [])]
|
|
481
|
-
}
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
// The lines, and where each clickable part sits: Pi routes mouse events to the footer in fullscreen mode.
|
|
485
|
-
export function drawFooter(v: View, width: number): { lines: string[]; hits: Hit[] } {
|
|
486
|
-
const hits: Hit[] = []
|
|
487
|
-
const lines = mainRows(v, width, hits)
|
|
488
|
-
if (v.open === 'model') {
|
|
489
|
-
lines.push(...pickerRows('model', v.models.map((m, i) => ({
|
|
490
|
-
text: paint(m.label, m.isCurrent ? { bold: true, underline: true } : { dim: true }),
|
|
491
|
-
action: `model:${i}`,
|
|
492
|
-
})), width, lines.length, hits, v))
|
|
493
|
-
}
|
|
494
|
-
if (v.open === 'effort') {
|
|
495
|
-
lines.push(...pickerRows('thinking', v.efforts.map(level => ({
|
|
496
|
-
text: paint(level, { ...(EFFORT_COLORS[level] === undefined ? { dim: true } : { color: EFFORT_COLORS[level] }), bold: level === v.effort, underline: level === v.effort }),
|
|
497
|
-
action: `effort:${level}`,
|
|
498
|
-
})), width, lines.length, hits, v))
|
|
499
|
-
}
|
|
500
|
-
if (v.open === 'ledger' && counted(v.stats) > 0) lines.push(...ledger(v))
|
|
501
|
-
// Other extensions' setStatus texts, which Pi's own footer would show.
|
|
502
|
-
if (v.statuses.length) lines.push(v.statuses.join(dim(' ')))
|
|
503
|
-
return { lines: lines.map(line => truncateToWidth(line, width, '')), hits }
|
|
504
|
-
}
|
|
1
|
+
import { truncateToWidth, visibleWidth } from '@earendil-works/pi-tui'
|
|
2
|
+
import { scanCells, SECONDS_WIDTH } from './anim.ts'
|
|
3
|
+
|
|
4
|
+
// The footer as text. Pi hands every line to the terminal as is, so the colors are SGR codes for
|
|
5
|
+
// the 16 palette slots: each person's terminal scheme picks the shades, as in Claude Code.
|
|
6
|
+
|
|
7
|
+
// Fixed widths, so a changing figure never moves the ones after it on the line.
|
|
8
|
+
// The terminal's columns give the readout 12 cells, as in Claude Code.
|
|
9
|
+
export const READOUT_WIDTH = 12
|
|
10
|
+
export const TPS_WIDTH = READOUT_WIDTH - ' t/s'.length
|
|
11
|
+
const TPS_MAX = 9999
|
|
12
|
+
// The widest count human() prints: 999.99M, 112.46B. At 6 cells, 112.46M wrapped the row.
|
|
13
|
+
export const COUNT_WIDTH = 7
|
|
14
|
+
// The padded token row: 4 counts, each a space and its unit, joined by 3 " / ".
|
|
15
|
+
export const TOKEN_SPLIT_WIDTH = 4 * COUNT_WIDTH + ' in out read write'.length + 3 * ' / '.length
|
|
16
|
+
// The graph fills the activity row to the token split's width: the phase glyph and its space, the
|
|
17
|
+
// readout, a space, the graph.
|
|
18
|
+
export const GRAPH_CELLS = TOKEN_SPLIT_WIDTH - 2 - READOUT_WIDTH - 1
|
|
19
|
+
// The first column: the repository over the context, cut with an ellipsis past this width.
|
|
20
|
+
export const WORKSPACE_WIDTH = 52
|
|
21
|
+
const COLUMN_GAP = 3
|
|
22
|
+
const LIMITS_GAP = 6
|
|
23
|
+
const WARN_FROM = 60
|
|
24
|
+
const BAD_FROM = 85
|
|
25
|
+
const BURN_MIN_HOURS = 0.1
|
|
26
|
+
export const HOUR_MS = 3_600_000
|
|
27
|
+
// Nerd Font glyphs are private-use code points that any other font draws as a box.
|
|
28
|
+
// U+21BB, Claude Code's first reset arrow, is missing from common terminal fonts.
|
|
29
|
+
export const NERD_GLYPHS = { reset: '\uf017', worktree: '\uf07b', branch: '\ue725' } as const // nf-fa-clock_o, nf-fa-folder, nf-dev-git_branch
|
|
30
|
+
const IDLE_GLYPH = '\u25cb' // a white circle, which every terminal font draws
|
|
31
|
+
export const PHASE_WORDS = { idle: 'idle', sending: 'sending', tool: 'running' } as const
|
|
32
|
+
// The readout, its gap and the graph: a running tool's name and argument fill them all.
|
|
33
|
+
export const TOOL_WIDTH = READOUT_WIDTH + 1 + GRAPH_CELLS
|
|
34
|
+
const SPINNER = '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'
|
|
35
|
+
const SPINNER_MS = 80
|
|
36
|
+
export const RATE_LIMIT_WINDOWS = [
|
|
37
|
+
{ kind: 'five_hour', label: '5h' },
|
|
38
|
+
{ kind: 'seven_day', label: '7d' },
|
|
39
|
+
] as const
|
|
40
|
+
|
|
41
|
+
const C = {
|
|
42
|
+
ok: 2, warn: 3, bad: 1, folder: 4, branch: 5, track: 8, marker: 15,
|
|
43
|
+
ramp: [10, 2, 11, 3, 1, 9],
|
|
44
|
+
} as const
|
|
45
|
+
// Pi's thinking levels; "minimal" and "off" have no color of their own and draw dim.
|
|
46
|
+
const EFFORT_COLORS: Record<string, number> = { low: 4, medium: 5, high: 13, xhigh: 1, max: 9 }
|
|
47
|
+
|
|
48
|
+
export type Phase = 'sending' | 'receiving' | 'tool' | 'idle'
|
|
49
|
+
export type Tool = { name: string; arg: string }
|
|
50
|
+
export type Limit = { kind: string; percentUsed: number; resetsAt?: string }
|
|
51
|
+
export type LimitStart = Record<string, { pct: number; at: number; resetsAt?: string }>
|
|
52
|
+
// The month's extra usage, in the currency the account is billed in.
|
|
53
|
+
export type Extra = { used: number; limit: number; currency: string; pct: number }
|
|
54
|
+
export type Stats = { input: number; write: number; read: number; output: number; costUsd: number | null }
|
|
55
|
+
export type Style = { color?: number; dim?: boolean; bold?: boolean; underline?: boolean; inverse?: boolean }
|
|
56
|
+
|
|
57
|
+
export type View = {
|
|
58
|
+
folder: string // the repository's name: in a worktree, the main checkout's folder
|
|
59
|
+
worktree: string | null
|
|
60
|
+
branch: string | null
|
|
61
|
+
model: string
|
|
62
|
+
effort: string | null
|
|
63
|
+
sessionId: string
|
|
64
|
+
context: { tokens: number | null; contextWindow: number; percent: number | null } | null
|
|
65
|
+
compactAt: number | null // percent of the window where auto-compaction starts
|
|
66
|
+
stats: Stats
|
|
67
|
+
turns: number
|
|
68
|
+
activeMs: number
|
|
69
|
+
costStart: number | null
|
|
70
|
+
limits: Limit[]
|
|
71
|
+
limitStart: LimitStart
|
|
72
|
+
extra: Extra | null
|
|
73
|
+
phase: Phase
|
|
74
|
+
tools: Tool[]
|
|
75
|
+
readout: string // the readout as the animation shows it, READOUT_WIDTH or TOOL_WIDTH cells
|
|
76
|
+
graph: string // the graph, GRAPH_CELLS cells
|
|
77
|
+
sweepMs: number // the time into the sending scan
|
|
78
|
+
isLit: boolean // the graph draws at full strength while a reply streams or a request waits
|
|
79
|
+
hasNerdFont: boolean
|
|
80
|
+
open: 'ledger' | 'model' | 'effort' | null
|
|
81
|
+
hover: string | null // the action of the part under the mouse pointer
|
|
82
|
+
models: { label: string; isCurrent: boolean }[] // the models the picker offers
|
|
83
|
+
efforts: string[] // the thinking levels the model supports
|
|
84
|
+
lastTurn: { tokens: number; ms: number; usd: number | null } | null
|
|
85
|
+
lastRequestAt: number | null
|
|
86
|
+
cacheTtlMinutes: number
|
|
87
|
+
money: (usd: number) => string
|
|
88
|
+
statuses: string[]
|
|
89
|
+
now: number
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function paint(text: string, s: Style = {}): string {
|
|
93
|
+
const codes: number[] = []
|
|
94
|
+
if (s.bold) codes.push(1)
|
|
95
|
+
if (s.dim) codes.push(2)
|
|
96
|
+
if (s.underline) codes.push(4)
|
|
97
|
+
if (s.inverse) codes.push(7)
|
|
98
|
+
if (s.color !== undefined) codes.push(s.color < 8 ? 30 + s.color : 90 + s.color - 8)
|
|
99
|
+
return codes.length && text ? `\x1b[${codes.join(';')}m${text}\x1b[0m` : text
|
|
100
|
+
}
|
|
101
|
+
const dim = (text: string) => paint(text, { dim: true })
|
|
102
|
+
const SEP = dim(' · ')
|
|
103
|
+
|
|
104
|
+
export const counted = (s: Stats) => s.input + s.write + s.read + s.output
|
|
105
|
+
|
|
106
|
+
function severity(pct: number): number {
|
|
107
|
+
return pct >= BAD_FROM ? C.bad : pct >= WARN_FROM ? C.warn : C.ok
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// Red at the compaction point, which is where the context runs out in practice.
|
|
111
|
+
function rampColor(pct: number, compactAt: number | null): number {
|
|
112
|
+
const share = pct / (compactAt ?? 100)
|
|
113
|
+
return C.ramp[Math.max(0, Math.min(C.ramp.length - 1, Math.floor(share * C.ramp.length)))]!
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// Largest first. Each cut is where the unit below would round up to 1000: 999,500 prints 1000k
|
|
117
|
+
// with whole thousands, 999.995M prints 1000.00M with 2 decimals.
|
|
118
|
+
const BIG_UNITS = [
|
|
119
|
+
['Q', 1e15, 999_995e9],
|
|
120
|
+
['T', 1e12, 999_995e6],
|
|
121
|
+
['B', 1e9, 999_995e3],
|
|
122
|
+
['M', 1e6, 999_500],
|
|
123
|
+
] as const
|
|
124
|
+
|
|
125
|
+
export function human(n: number): string {
|
|
126
|
+
for (const [suffix, size, cut] of BIG_UNITS) {
|
|
127
|
+
if (n >= cut) return `${(n / size).toFixed(2).replace(/\.?0+$/, '')}${suffix}`
|
|
128
|
+
}
|
|
129
|
+
if (n >= 1_000) return `${Math.round(n / 1_000)}k`
|
|
130
|
+
return String(n)
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const DURATION_UNITS = [
|
|
134
|
+
['days', 86_400_000, 'd'],
|
|
135
|
+
['hours', 3_600_000, 'h'],
|
|
136
|
+
['minutes', 60_000, 'm'],
|
|
137
|
+
['seconds', 1_000, 's'],
|
|
138
|
+
] as const
|
|
139
|
+
type DurationFormatter = { format(d: Partial<Record<string, number>>): string }
|
|
140
|
+
// Node 22 has no Intl.DurationFormat; its narrow English output is the fallback's.
|
|
141
|
+
const DurationFormat = (Intl as unknown as { DurationFormat?: new (l?: string, o?: object) => DurationFormatter }).DurationFormat
|
|
142
|
+
const durationFormat: DurationFormatter = DurationFormat
|
|
143
|
+
? new DurationFormat(undefined, { style: 'narrow' })
|
|
144
|
+
: { format: d => DURATION_UNITS.filter(([unit]) => d[unit]).map(([unit, , short]) => `${d[unit]}${short}`).join(' ') || '0s' }
|
|
145
|
+
|
|
146
|
+
// 2 units, as humanize-duration and pretty-ms default to, so every time on the line has one form.
|
|
147
|
+
export function duration(ms: number): string {
|
|
148
|
+
const largest = DURATION_UNITS.findIndex(([, size]) => ms >= size)
|
|
149
|
+
const first = largest === -1 ? DURATION_UNITS.length - 1 : largest // under 1 second shows "0s"
|
|
150
|
+
const shown = DURATION_UNITS.slice(first, first + 2)
|
|
151
|
+
const step = shown[shown.length - 1]![1]
|
|
152
|
+
let left = Math.round(Math.max(0, ms) / step) * step
|
|
153
|
+
const parts: Partial<Record<string, number>> = {}
|
|
154
|
+
for (const [unit, size] of shown) {
|
|
155
|
+
parts[unit] = Math.floor(left / size)
|
|
156
|
+
left -= parts[unit]! * size
|
|
157
|
+
}
|
|
158
|
+
return durationFormat.format(parts)
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export function modelLabel(id: string): string {
|
|
162
|
+
const [family, ...version] = id.replace(/^claude-/, '').replace(/\[.*\]$/, '').replace(/-\d{8}$/, '').split('-')
|
|
163
|
+
return version.length ? `${family} ${version.join('.')}` : family ?? id
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export function basename(path: string): string {
|
|
167
|
+
return path.replace(/[\\/]+$/, '').split(/[\\/]/).pop() || path
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// The argument that says most about a call. Pi's built-in tools and Claude Code's share these keys.
|
|
171
|
+
const ARG_KEYS = ['description', 'command', 'file_path', 'path', 'notebook_path', 'pattern', 'url', 'query', 'subagent_type', 'agent'] as const
|
|
172
|
+
const PATH_KEYS = new Set(['file_path', 'path', 'notebook_path'])
|
|
173
|
+
|
|
174
|
+
export function toolArg(input: unknown): string {
|
|
175
|
+
const args = (input && typeof input === 'object' ? input : {}) as Record<string, unknown>
|
|
176
|
+
const key = ARG_KEYS.find(k => typeof args[k] === 'string' && args[k])
|
|
177
|
+
if (!key) return ''
|
|
178
|
+
const value = args[key] as string
|
|
179
|
+
return PATH_KEYS.has(key) ? basename(value) : key === 'url' ? value.replace(/^https?:\/\/(www\.)?/, '') : value
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export function toolName(name: string): string {
|
|
183
|
+
return name.startsWith('mcp__') ? name.split('__').pop()! : name
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// Exactly `width` cells. One call: its name and argument. Parallel calls: their count, then each
|
|
187
|
+
// call's name and argument, so every tool the turn runs shows, not the first alone.
|
|
188
|
+
export function toolReadout(tools: Tool[], width: number): { text: string; bright: number } {
|
|
189
|
+
const first = tools[0]
|
|
190
|
+
if (!first) return { text: PHASE_WORDS.tool.padStart(width), bright: 0 }
|
|
191
|
+
const head = tools.length < 2 ? '' : `${tools.length} tools `
|
|
192
|
+
const full = (head + tools.map(t => `${t.name} ${t.arg}`.trim()).join(' · ')).replace(/\s+/g, ' ')
|
|
193
|
+
const text = full.length > width ? `${full.slice(0, width - 1)}…` : full.padEnd(width)
|
|
194
|
+
return { text, bright: Math.min(head ? head.length - 1 : first.name.length, width) }
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// The readout's target text for a phase, before the animation scrambles it.
|
|
198
|
+
export function readoutTarget(phase: Phase, tps: number, tools: Tool[]): { text: string; bright: number } {
|
|
199
|
+
if (phase === 'receiving') return { text: `${String(Math.min(TPS_MAX, tps)).padStart(TPS_WIDTH)} t/s`, bright: TPS_WIDTH }
|
|
200
|
+
if (phase === 'tool') return toolReadout(tools, TOOL_WIDTH)
|
|
201
|
+
// Sending: the readout takes the graph's first SECONDS_WIDTH cells for the time after "waiting...".
|
|
202
|
+
if (phase === 'sending') return { text: ' '.repeat(READOUT_WIDTH + SECONDS_WIDTH), bright: 0 }
|
|
203
|
+
return { text: PHASE_WORDS[phase].padStart(READOUT_WIDTH), bright: 0 }
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
function phaseGlyph(v: View): string {
|
|
208
|
+
switch (v.phase) {
|
|
209
|
+
case 'sending': return paint('↑ ', { color: C.folder })
|
|
210
|
+
case 'receiving': return paint('↓ ', { color: C.ok })
|
|
211
|
+
case 'tool': return paint(`${SPINNER[Math.floor(v.now / SPINNER_MS) % SPINNER.length]} `, { color: C.warn })
|
|
212
|
+
case 'idle': return dim(`${IDLE_GLYPH} `)
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function percent(value: number): string {
|
|
217
|
+
return paint(`${Math.round(value)}%`, { color: severity(value) })
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
// claude.ai's usage endpoint gives amounts in the currency's minor units: 972 with 2 decimal
|
|
222
|
+
// places is 9.72. Its shape is undocumented, so anything unexpected reads as no extra usage.
|
|
223
|
+
// The endpoint reports the account's 5h and 7d use, other sessions' included. A response header
|
|
224
|
+
// reports it too, but only when this session sends a request.
|
|
225
|
+
export function readUsageLimits(text: string): Limit[] {
|
|
226
|
+
const body = JSON.parse(text) as Record<string, { utilization?: number | null; resets_at?: string | null } | null | undefined>
|
|
227
|
+
return RATE_LIMIT_WINDOWS.flatMap(({ kind }) => {
|
|
228
|
+
const w = body[kind]
|
|
229
|
+
if (typeof w?.utilization !== 'number') return []
|
|
230
|
+
return [{ kind, percentUsed: Math.round(w.utilization * 10) / 10, ...(w.resets_at ? { resetsAt: w.resets_at } : {}) }]
|
|
231
|
+
})
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
export function readExtraBody(text: string): Extra | null {
|
|
235
|
+
const x = (JSON.parse(text) as { extra_usage?: { is_enabled?: boolean; monthly_limit?: number | null; used_credits?: number | null; utilization?: number | null; currency?: string | null; decimal_places?: number | null } | null }).extra_usage
|
|
236
|
+
if (!x?.is_enabled || typeof x.monthly_limit !== 'number' || typeof x.used_credits !== 'number' || x.monthly_limit <= 0) return null
|
|
237
|
+
const scale = 10 ** (x.decimal_places ?? 2)
|
|
238
|
+
const used = x.used_credits / scale
|
|
239
|
+
const limit = x.monthly_limit / scale
|
|
240
|
+
return { used, limit, currency: x.currency || 'USD', pct: x.utilization ?? (used / limit) * 100 }
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
// 9.72 keeps its cents, a whole 100 drops them.
|
|
244
|
+
export function amount(value: number, currency: string): string {
|
|
245
|
+
const digits = Number.isInteger(value) ? 0 : 2
|
|
246
|
+
return new Intl.NumberFormat(undefined, { style: 'currency', currency, minimumFractionDigits: digits, maximumFractionDigits: 2 }).format(value)
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// Extra usage is billed only after the 5h or 7d window is full, so the spend shows only then.
|
|
250
|
+
function extraSpend(v: View): string {
|
|
251
|
+
const x = v.extra
|
|
252
|
+
const isCapped = RATE_LIMIT_WINDOWS.some(({ kind }) => (v.limits.find(l => l.kind === kind)?.percentUsed ?? 0) >= 100)
|
|
253
|
+
return x && isCapped ?`${SEP}${dim('extra ')}${paint(amount(x.used, x.currency), { color: severity(x.pct) })}${dim(`/${amount(x.limit, x.currency)}`)}` : ''
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
export type Hit = { row: number; from: number; to: number; action: string }
|
|
257
|
+
|
|
258
|
+
// The part under the pointer is underlined, so it reads as a control before the click.
|
|
259
|
+
function hoverable(text: string, action: string | undefined, v: View): string {
|
|
260
|
+
return action && action === v.hover ? `\x1b[4m${text}\x1b[0m` : text
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// A linked worktree's git folder is <main checkout>/.git/worktrees/<id>, so the main checkout names
|
|
264
|
+
// the repository. A submodule's is .git/modules/<name>, and it stays a repository of its own.
|
|
265
|
+
export function worktreeOf(gitDir: string, top: string): { name: string; worktree: string | null } {
|
|
266
|
+
const base = (p: string) => p.replace(/[\\/]+$/, '').split(/[\\/]/).pop() ?? p
|
|
267
|
+
const main = gitDir.match(/^(.*)[\\/]\.git[\\/]worktrees[\\/][^\\/]+[\\/]?$/)?.[1]
|
|
268
|
+
return main ? { name: base(main), worktree: base(top) } : { name: base(top), worktree: null }
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// Exactly `width` cells: cut with an ellipsis, or padded.
|
|
272
|
+
function fit(text: string, width: number): string {
|
|
273
|
+
const cut = truncateToWidth(text, width, '…')
|
|
274
|
+
return cut + ' '.repeat(Math.max(0, width - visibleWidth(cut)))
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
// The worktree and the branch cut to fit the column with the repository, the parentheses, the
|
|
278
|
+
// separator and the glyphs. The longer name loses a cell first, so both stay readable.
|
|
279
|
+
export function cutWorkspace(folder: string, worktree: string | null, branch: string | null, hasGlyphs: boolean, width: number): { worktree: string; branch: string } {
|
|
280
|
+
const glyph = hasGlyphs ? 2 : 0
|
|
281
|
+
const fixed = folder.length + (worktree || branch ? 3 : 0) + (worktree && branch ? 3 : 0) + (worktree ? glyph : 0) + (branch ? glyph : 0)
|
|
282
|
+
const room = Math.max(0, width - fixed)
|
|
283
|
+
let w = worktree?.length ?? 0
|
|
284
|
+
let b = branch?.length ?? 0
|
|
285
|
+
while (w + b > room) {
|
|
286
|
+
if (w >= b && w > 1) w--
|
|
287
|
+
else if (b > 1) b--
|
|
288
|
+
else break
|
|
289
|
+
}
|
|
290
|
+
const cut = (name: string | null, n: number) => (!name ? '' : name.length <= n ? name : `${name.slice(0, Math.max(0, n - 1))}…`)
|
|
291
|
+
return { worktree: cut(worktree, w), branch: cut(branch, b) }
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
// The repository, then the worktree and the branch in parentheses: two rows leave them room.
|
|
295
|
+
function workspace(v: View, width: number): string {
|
|
296
|
+
if (!v.folder) return ''
|
|
297
|
+
const glyph = (g: string) => (v.hasNerdFont ? `${g} ` : '')
|
|
298
|
+
const cut = cutWorkspace(v.folder, v.worktree, v.branch, v.hasNerdFont, width)
|
|
299
|
+
const parts = [
|
|
300
|
+
v.worktree ? dim(glyph(NERD_GLYPHS.worktree) + cut.worktree) : '',
|
|
301
|
+
v.branch ? paint(glyph(NERD_GLYPHS.branch) + cut.branch, { color: C.branch }) : '',
|
|
302
|
+
].filter(Boolean)
|
|
303
|
+
return paint(v.folder, { color: C.folder }) + (parts.length ? `${dim(' (')}${parts.join(dim(' · '))}${dim(')')}` : '')
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
function contextCell(v: View): string {
|
|
307
|
+
const pct = v.context?.percent ?? null
|
|
308
|
+
const size = v.context?.tokens == null ? '---/---' : `${human(v.context.tokens)}/${human(v.context.contextWindow)}`
|
|
309
|
+
return [
|
|
310
|
+
pct === null ? dim('--%') : paint(`${Math.round(pct)}%`, { color: rampColor(pct, v.compactAt) }),
|
|
311
|
+
dim(` ${size}`),
|
|
312
|
+
v.compactAt === null ? '' : dim(` · compacts at ${Math.round(v.compactAt)}%`),
|
|
313
|
+
].join('')
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
// Idle, the readout stays empty: a dim glyph, a word and a flat graph only said so.
|
|
317
|
+
function activityRow(v: View): string {
|
|
318
|
+
if (v.phase === 'idle') return ''
|
|
319
|
+
if (v.phase === 'sending') {
|
|
320
|
+
// The word is dim and the time is at full strength: the time is what changes.
|
|
321
|
+
const [before, head, after] = scanCells(v.sweepMs, GRAPH_CELLS - SECONDS_WIDTH)
|
|
322
|
+
const scan = `${dim('─'.repeat(before))}${paint('━'.repeat(head), { color: C.folder })}${dim('─'.repeat(after))}`
|
|
323
|
+
return `${phaseGlyph(v)}${dim(v.readout.slice(0, -SECONDS_WIDTH))}${v.readout.slice(-SECONDS_WIDTH)} ${scan}`
|
|
324
|
+
}
|
|
325
|
+
const bright = v.phase === 'receiving' ? TPS_WIDTH : v.phase === 'tool' ? toolReadout(v.tools, TOOL_WIDTH).bright : 0
|
|
326
|
+
const readout = `${v.readout.slice(0, bright)}${dim(v.readout.slice(bright))}`
|
|
327
|
+
// A running tool's name fills the graph's cells too.
|
|
328
|
+
const dots = v.phase === 'tool' ? '' : ` ${paint(v.graph, { color: C.folder, dim: !v.isLit })}`
|
|
329
|
+
return `${phaseGlyph(v)}${readout}${dots}`
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// Each kind costs a different price, so the line splits them as Pi's own footer does. Each count
|
|
333
|
+
// is padded to the widest human() gives, so a count that grows a digit moves none after it.
|
|
334
|
+
function tokenSplitRow(v: View): string {
|
|
335
|
+
if (counted(v.stats) === 0) return dim('--- tok')
|
|
336
|
+
const inverse = v.open === 'ledger'
|
|
337
|
+
return hoverable(paint([
|
|
338
|
+
[v.stats.input, 'in'], [v.stats.output, 'out'], [v.stats.read, 'read'], [v.stats.write, 'write'],
|
|
339
|
+
// One muted gray: the token split is a tally to glance at, the activity above it is live.
|
|
340
|
+
].map(([n, unit]) => `${human(n as number).padStart(COUNT_WIDTH)} ${unit}`).join(' / '), { inverse, dim: true }), 'ledger', v)
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
function limitCell(v: View, kind: string, label: string): string {
|
|
344
|
+
const w = v.limits.find(l => l.kind === kind)
|
|
345
|
+
if (!w) return ''
|
|
346
|
+
const reset = w.resetsAt ? dim(` ${v.hasNerdFont ? `${NERD_GLYPHS.reset} ` : ''}${duration(Date.parse(w.resetsAt) - v.now)}`) : ''
|
|
347
|
+
return `${dim(`${label} `)}${percent(w.percentUsed)}${reset}`
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// The model and the thinking level on the first row, the session ID on the second, each part with
|
|
351
|
+
// the action a click on it runs.
|
|
352
|
+
function modelParts(v: View): { text: string; action?: string }[][] {
|
|
353
|
+
const top: { text: string; action?: string }[] = []
|
|
354
|
+
if (v.model) {
|
|
355
|
+
top.push({ text: paint(modelLabel(v.model), { inverse: v.open === 'model' }), action: v.models.length > 1 ? 'model' : undefined })
|
|
356
|
+
if (v.effort) {
|
|
357
|
+
const style: Style = EFFORT_COLORS[v.effort] === undefined ? { dim: true } : { color: EFFORT_COLORS[v.effort] }
|
|
358
|
+
top.push({ text: ' ' }, { text: paint(v.effort, { ...style, inverse: v.open === 'effort' }), action: v.efforts.length > 1 ? 'effort' : undefined })
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
// Dim only: slot 8 with dim on top vanished on dark terminal schemes.
|
|
362
|
+
const bottom = v.sessionId ? [{ text: dim(v.sessionId.slice(0, 8)), action: 'id' }] : []
|
|
363
|
+
return [top, bottom].map(parts => parts.map(p => ({ ...p, text: hoverable(p.text, p.action, v) })))
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
// The context bar across the whole footer: one cell per column is the finest step it can take.
|
|
367
|
+
function contextBar(pct: number | null, compactAt: number | null, cells: number): string {
|
|
368
|
+
const filled = pct === null ? 0 : Math.round((Math.min(pct, 100) / 100) * cells)
|
|
369
|
+
// In the last cell the marker would only repeat the rule's own end, so it hides there.
|
|
370
|
+
const marker = compactAt === null ? -1 : Math.floor((compactAt / 100) * cells)
|
|
371
|
+
let out = ''
|
|
372
|
+
for (let i = 0; i < cells; i++) {
|
|
373
|
+
const color = rampColor(((i + 0.5) / cells) * 100, compactAt)
|
|
374
|
+
// The track is dim text: slot 8 vanishes on translucent and dark backgrounds.
|
|
375
|
+
if (i === marker && i < cells - 1) out += paint('┃', i < filled ? { color } : { color: C.marker })
|
|
376
|
+
else out += i < filled ? paint('━', { color }) : dim('─')
|
|
377
|
+
}
|
|
378
|
+
return out
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
// Two rows of four columns, as in Claude Code: the workspace over the context, the activity over the
|
|
382
|
+
// tokens, 5h over 7d, the model over the session ID. The first two columns have fixed widths, so
|
|
383
|
+
// nothing moves as figures change; the limits and the model sit right. Then the rule.
|
|
384
|
+
function mainRows(v: View, width: number, hits: Hit[]): string[] {
|
|
385
|
+
const limits = [limitCell(v, 'five_hour', '5h'), limitCell(v, 'seven_day', '7d') + extraSpend(v)]
|
|
386
|
+
const limitsWidth = Math.max(...limits.map(visibleWidth))
|
|
387
|
+
const right = modelParts(v)
|
|
388
|
+
const rightTexts = right.map(parts => parts.map(p => p.text).join(''))
|
|
389
|
+
const rightWidth = Math.max(...rightTexts.map(visibleWidth))
|
|
390
|
+
const rest = COLUMN_GAP + TOKEN_SPLIT_WIDTH + 2 + limitsWidth + (limitsWidth ? LIMITS_GAP : 0) + rightWidth
|
|
391
|
+
// A narrow footer cuts the place first, as Claude Code's first column shrinks first.
|
|
392
|
+
const workspaceWidth = Math.max(12, Math.min(WORKSPACE_WIDTH, width - rest))
|
|
393
|
+
const left = [workspace(v, workspaceWidth), contextCell(v)].map(t => fit(t, workspaceWidth))
|
|
394
|
+
const middle = [activityRow(v), tokenSplitRow(v)].map(t => fit(t, TOKEN_SPLIT_WIDTH))
|
|
395
|
+
const leftWidth = workspaceWidth + COLUMN_GAP + TOKEN_SPLIT_WIDTH
|
|
396
|
+
const free = Math.max(2, width - leftWidth - limitsWidth - (limitsWidth ? LIMITS_GAP : 0) - rightWidth)
|
|
397
|
+
if (counted(v.stats) > 0) hits.push({ row: 1, from: workspaceWidth + COLUMN_GAP, to: workspaceWidth + COLUMN_GAP + visibleWidth(tokenSplitRow(v)), action: 'ledger' })
|
|
398
|
+
const rows = [0, 1].map(r => {
|
|
399
|
+
const rightPad = rightWidth - visibleWidth(rightTexts[r]!)
|
|
400
|
+
let at = leftWidth + free + limitsWidth + (limitsWidth ? LIMITS_GAP : 0) + rightPad
|
|
401
|
+
for (const p of right[r]!) {
|
|
402
|
+
const w = visibleWidth(p.text)
|
|
403
|
+
if (p.action && at + w <= width) hits.push({ row: r, from: at, to: at + w, action: p.action })
|
|
404
|
+
at += w
|
|
405
|
+
}
|
|
406
|
+
return truncateToWidth([
|
|
407
|
+
left[r], ' '.repeat(COLUMN_GAP), middle[r], ' '.repeat(free),
|
|
408
|
+
limitsWidth ? fit(limits[r]!, limitsWidth) + ' '.repeat(LIMITS_GAP) : '',
|
|
409
|
+
' '.repeat(rightPad), rightTexts[r],
|
|
410
|
+
].join(''), width, '')
|
|
411
|
+
})
|
|
412
|
+
return [...rows, contextBar(v.context?.percent ?? null, v.compactAt, width)]
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
// A picker's options, right-aligned under the line as Claude Code shows them, wrapped to the width.
|
|
416
|
+
function pickerRows(label: string, options: { text: string; action: string }[], width: number, firstRow: number, hits: Hit[], v: View): string[] {
|
|
417
|
+
const rows: { parts: { text: string; action?: string }[]; width: number }[] = []
|
|
418
|
+
let current = { parts: [{ text: dim(`${label} `) }] as { text: string; action?: string }[], width: label.length + 1 }
|
|
419
|
+
for (const o of options) {
|
|
420
|
+
const w = visibleWidth(o.text) + 1
|
|
421
|
+
if (current.width + w > width && current.parts.length > 1) {
|
|
422
|
+
rows.push(current)
|
|
423
|
+
current = { parts: [], width: 0 }
|
|
424
|
+
}
|
|
425
|
+
current.parts.push({ text: ' ' }, { ...o, text: hoverable(o.text, o.action, v) })
|
|
426
|
+
current.width += w
|
|
427
|
+
}
|
|
428
|
+
rows.push(current)
|
|
429
|
+
return rows.map((r, i) => {
|
|
430
|
+
let at = Math.max(0, width - r.width)
|
|
431
|
+
for (const p of r.parts) {
|
|
432
|
+
const w = visibleWidth(p.text)
|
|
433
|
+
if (p.action) hits.push({ row: firstRow + i, from: at, to: at + w, action: p.action })
|
|
434
|
+
at += w
|
|
435
|
+
}
|
|
436
|
+
return `${' '.repeat(Math.max(0, width - r.width))}${r.parts.map(p => p.text).join('')}`
|
|
437
|
+
})
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
function row(label: string, body: string): string {
|
|
441
|
+
return ` ${dim(label.padEnd(8))}${body}`
|
|
442
|
+
}
|
|
443
|
+
const fig = (value: string, unit?: string) => `${value}${unit ? dim(` ${unit}`) : ''}`
|
|
444
|
+
|
|
445
|
+
function ledger(v: View): string[] {
|
|
446
|
+
const { stats } = v
|
|
447
|
+
const hours = v.activeMs / HOUR_MS
|
|
448
|
+
const trackedUsd = stats.costUsd !== null && v.costStart !== null ? stats.costUsd - v.costStart : null
|
|
449
|
+
const hit = stats.read / Math.max(1, stats.read + stats.write + stats.input)
|
|
450
|
+
const cacheLeft = v.lastRequestAt === null ? null : v.cacheTtlMinutes * 60_000 - (v.now - v.lastRequestAt)
|
|
451
|
+
const cost = stats.costUsd === null ? dim('not reported') : [
|
|
452
|
+
fig(v.money(stats.costUsd)),
|
|
453
|
+
trackedUsd !== null && hours >= BURN_MIN_HOURS ? `${SEP}${fig(v.money(trackedUsd / hours), 'per active hour')}` : '',
|
|
454
|
+
v.lastTurn?.usd != null ? `${SEP}${dim('last turn ')}${fig(v.money(v.lastTurn.usd))}` : '',
|
|
455
|
+
].join('')
|
|
456
|
+
const tokens = [
|
|
457
|
+
fig(human(stats.input), 'in'), fig(human(stats.write), 'cache write'), fig(human(stats.read), 'cache read'),
|
|
458
|
+
fig(human(stats.output), 'out'), fig(`${Math.round(hit * 100)}%`, 'cache hit'),
|
|
459
|
+
...(cacheLeft === null ? [] : [cacheLeft > 0 ? dim(`cache warm ${duration(cacheLeft)}`) : paint('cache cold', { color: C.warn })]),
|
|
460
|
+
].join(SEP)
|
|
461
|
+
const turns = [
|
|
462
|
+
fig(String(v.turns), 'turns'),
|
|
463
|
+
...(v.activeMs > 0 ? [fig(duration(v.activeMs), 'active')] : []),
|
|
464
|
+
...(v.lastTurn ? [`${dim('last turn ')}${fig(human(v.lastTurn.tokens), `tok in ${duration(v.lastTurn.ms)}`)}`] : []),
|
|
465
|
+
].join(SEP)
|
|
466
|
+
const burns = RATE_LIMIT_WINDOWS.flatMap(({ kind, label }) => {
|
|
467
|
+
const w = v.limits.find(l => l.kind === kind)
|
|
468
|
+
if (!w) return []
|
|
469
|
+
const start = v.limitStart[kind]
|
|
470
|
+
const spanHours = start ? (v.now - start.at) / HOUR_MS : 0
|
|
471
|
+
const perHour = start && spanHours >= BURN_MIN_HOURS ? (w.percentUsed - start.pct) / spanHours : 0
|
|
472
|
+
const fullInMs = perHour > 0 ? ((100 - w.percentUsed) / perHour) * HOUR_MS : null
|
|
473
|
+
const resetsInMs = w.resetsAt ? Date.parse(w.resetsAt) - v.now : null
|
|
474
|
+
// Only a limit that fills before its reset needs a word.
|
|
475
|
+
const trend = perHour > 0
|
|
476
|
+
? `${dim(` +${perHour.toFixed(1)}%/h`)}${fullInMs === null || resetsInMs === null || fullInMs < resetsInMs ? paint(`, full in ${duration(fullInMs ?? 0)}`, { color: C.warn }) : ''}`
|
|
477
|
+
: dim(spanHours < BURN_MIN_HOURS ? ' measuring' : ' steady')
|
|
478
|
+
return [`${dim(`${label} `)}${percent(w.percentUsed)}${trend}`]
|
|
479
|
+
}).join(SEP)
|
|
480
|
+
return [row('cost', cost), row('tokens', tokens), row('turns', turns), ...(burns ? [row('limits', burns)] : [])]
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
// The lines, and where each clickable part sits: Pi routes mouse events to the footer in fullscreen mode.
|
|
485
|
+
export function drawFooter(v: View, width: number): { lines: string[]; hits: Hit[] } {
|
|
486
|
+
const hits: Hit[] = []
|
|
487
|
+
const lines = mainRows(v, width, hits)
|
|
488
|
+
if (v.open === 'model') {
|
|
489
|
+
lines.push(...pickerRows('model', v.models.map((m, i) => ({
|
|
490
|
+
text: paint(m.label, m.isCurrent ? { bold: true, underline: true } : { dim: true }),
|
|
491
|
+
action: `model:${i}`,
|
|
492
|
+
})), width, lines.length, hits, v))
|
|
493
|
+
}
|
|
494
|
+
if (v.open === 'effort') {
|
|
495
|
+
lines.push(...pickerRows('thinking', v.efforts.map(level => ({
|
|
496
|
+
text: paint(level, { ...(EFFORT_COLORS[level] === undefined ? { dim: true } : { color: EFFORT_COLORS[level] }), bold: level === v.effort, underline: level === v.effort }),
|
|
497
|
+
action: `effort:${level}`,
|
|
498
|
+
})), width, lines.length, hits, v))
|
|
499
|
+
}
|
|
500
|
+
if (v.open === 'ledger' && counted(v.stats) > 0) lines.push(...ledger(v))
|
|
501
|
+
// Other extensions' setStatus texts, which Pi's own footer would show.
|
|
502
|
+
if (v.statuses.length) lines.push(v.statuses.join(dim(' ')))
|
|
503
|
+
return { lines: lines.map(line => truncateToWidth(line, width, '')), hits }
|
|
504
|
+
}
|