@accodev/hairline 0.0.0-stage → 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 -0
- package/README.md +68 -2
- package/package.json +27 -4
- package/pi/anim.ts +138 -0
- package/pi/index.ts +598 -0
- package/pi/line.ts +504 -0
package/pi/index.ts
ADDED
|
@@ -0,0 +1,598 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process'
|
|
2
|
+
import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
3
|
+
import { join } from 'node:path'
|
|
4
|
+
import { getSupportedThinkingLevels, type AssistantMessage, type Model } from '@earendil-works/pi-ai'
|
|
5
|
+
import { copyToClipboard, getAgentDir, type ExtensionAPI, type ExtensionContext } from '@earendil-works/pi-coding-agent'
|
|
6
|
+
import { isScrambling, newReadout, newGraph, waitingText, setReadoutKind, readoutFrame, graphText, tickReadout, tickGraph } from './anim.ts'
|
|
7
|
+
import { basename, counted, drawFooter, type Extra, type Hit, HOUR_MS, modelLabel, type Limit, type LimitStart, type Phase, readExtraBody, readUsageLimits, readoutTarget, GRAPH_CELLS, type Stats, toolArg, toolName, type Tool, type View, worktreeOf } from './line.ts'
|
|
8
|
+
|
|
9
|
+
const RATE_WINDOW_MS = 1_000
|
|
10
|
+
const RATE_MIN_WINDOW_MS = 100 // the first chunks' rate, over at least this, so one chunk draws no spike
|
|
11
|
+
const RATIO_MIN_TOKENS = 20 // shorter responses give a noisy characters-per-token ratio
|
|
12
|
+
const RATIO_MIN = 2
|
|
13
|
+
const RATIO_MAX = 6
|
|
14
|
+
const REDRAWS_MAX = 30
|
|
15
|
+
const FRAMES_MAX = 60
|
|
16
|
+
const REFRESH_MS = 5_000
|
|
17
|
+
const DEFAULT_RESERVE_TOKENS = 16_384 // Pi's compaction.reserveTokens default
|
|
18
|
+
const CURRENCIES = ['USD', 'CAD', 'AUD', 'EUR', 'JPY', 'CNY'] as const
|
|
19
|
+
const READOUT_EASE_MS = 400 // a figure redrawn faster than this flickers past reading
|
|
20
|
+
const RATES_URL = 'https://api.frankfurter.dev/v1/latest?base=USD&symbols=' // European Central Bank rates, no key
|
|
21
|
+
const NERD_FONT_NAME = /nerd ?font|(^|[\s_-])NFM?([\s_.-]|$)/i // CaskaydiaCove Nerd Font, MapleMono-NF-Regular.ttf
|
|
22
|
+
// Anthropic sends the subscription limits as response headers; other providers send none.
|
|
23
|
+
const LIMIT_HEADERS = [
|
|
24
|
+
{ kind: 'five_hour', prefix: 'anthropic-ratelimit-unified-5h' },
|
|
25
|
+
{ kind: 'seven_day', prefix: 'anthropic-ratelimit-unified-7d' },
|
|
26
|
+
] as const
|
|
27
|
+
// A window reset restarts the fill rate. Reset times jitter by seconds, so only 1 minute counts.
|
|
28
|
+
const WINDOW_MOVED_MS = 60_000
|
|
29
|
+
// claude.ai's own usage endpoint, undocumented: it alone reports the extra usage spend.
|
|
30
|
+
const USAGE_URL = 'https://api.anthropic.com/api/oauth/usage'
|
|
31
|
+
const EXTRA_REFRESH_MS = 60_000
|
|
32
|
+
const IDLE_REFRESH_MS = 60_000
|
|
33
|
+
const EXTRA_RETRY_MS = 600_000
|
|
34
|
+
|
|
35
|
+
type Settings = { currency: string; usdRate: number; cacheTtlMinutes: number; refreshPerSecond: number; frameRate: number }
|
|
36
|
+
|
|
37
|
+
function readSettings(raw: unknown): Settings {
|
|
38
|
+
const o = (raw && typeof raw === 'object' ? raw : {}) as Record<string, unknown>
|
|
39
|
+
const code = String(o.currency || 'EUR').trim().toUpperCase().replace(/^RMB$/, 'CNY')
|
|
40
|
+
const rate = Number(o.usdRate)
|
|
41
|
+
const ttl = Number(o.cacheTtlMinutes)
|
|
42
|
+
const refresh = Number(o.speedRefreshPerSecond)
|
|
43
|
+
const frames = Number(o.animationFps)
|
|
44
|
+
return {
|
|
45
|
+
currency: (CURRENCIES as readonly string[]).includes(code) ? code : 'EUR',
|
|
46
|
+
usdRate: rate > 0 ? rate : 0.9,
|
|
47
|
+
cacheTtlMinutes: ttl > 0 ? ttl : 60,
|
|
48
|
+
refreshPerSecond: refresh > 0 ? Math.min(REDRAWS_MAX, Math.max(1, refresh)) : REDRAWS_MAX,
|
|
49
|
+
frameRate: frames > 0 ? Math.min(FRAMES_MAX, Math.max(1, frames)) : 30,
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// One file for every Pi session: the font answer, the account's last limits, and per session the
|
|
54
|
+
// figures no session entry records. Newest session first, as the Claude Code mod keeps them.
|
|
55
|
+
type Saved = { sessionId: string; turns: number; activeMs: number; costStart: number | null; limitStart: LimitStart }
|
|
56
|
+
type Store = { nerdFont?: boolean; limits?: Limit[]; sessions?: Saved[] }
|
|
57
|
+
const SAVED_MAX = 20
|
|
58
|
+
const storePath = () => join(getAgentDir(), 'hairline.json')
|
|
59
|
+
|
|
60
|
+
function readStore(): Store {
|
|
61
|
+
try {
|
|
62
|
+
return JSON.parse(readFileSync(storePath(), 'utf8')) as Store
|
|
63
|
+
} catch {
|
|
64
|
+
return {}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function writeStore(change: (s: Store) => void): void {
|
|
69
|
+
try {
|
|
70
|
+
const s = readStore()
|
|
71
|
+
change(s)
|
|
72
|
+
writeFileSync(storePath(), JSON.stringify(s))
|
|
73
|
+
} catch {}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// The terminal font is out of reach, so an installed Nerd Font stands in for one in use. fc-list
|
|
77
|
+
// covers Linux and Homebrew macOS; the font folders cover Windows and plain macOS.
|
|
78
|
+
async function findNerdFont(): Promise<boolean> {
|
|
79
|
+
if (process.platform !== 'win32') {
|
|
80
|
+
const out = await new Promise<string | null>(resolve =>
|
|
81
|
+
execFile('fc-list', [':', 'family'], { timeout: 3_000 }, (err, stdout) => resolve(err ? null : stdout)))
|
|
82
|
+
if (out !== null) return NERD_FONT_NAME.test(out)
|
|
83
|
+
}
|
|
84
|
+
const { WINDIR, LOCALAPPDATA, HOME } = process.env
|
|
85
|
+
const dirs = [WINDIR && `${WINDIR}/Fonts`, LOCALAPPDATA && `${LOCALAPPDATA}/Microsoft/Windows/Fonts`, HOME && `${HOME}/Library/Fonts`, '/Library/Fonts']
|
|
86
|
+
return dirs.some(dir => {
|
|
87
|
+
try {
|
|
88
|
+
return !!dir && readdirSync(dir).some(name => NERD_FONT_NAME.test(name))
|
|
89
|
+
} catch {
|
|
90
|
+
return false
|
|
91
|
+
}
|
|
92
|
+
})
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// The working copy's top folder, which a worktree's .git file also marks. That file names the
|
|
96
|
+
// worktree's git folder, which sits in the main checkout.
|
|
97
|
+
function findRepo(cwd: string): { name: string; worktree: string | null } {
|
|
98
|
+
const parts = cwd.replace(/[\\/]+$/, '').split(/[\\/]/)
|
|
99
|
+
for (let n = parts.length; n > 0; n--) {
|
|
100
|
+
const top = parts.slice(0, n).join('/')
|
|
101
|
+
if (!existsSync(`${top}/.git`)) continue
|
|
102
|
+
try {
|
|
103
|
+
const dir = readFileSync(`${top}/.git`, 'utf8').match(/^gitdir:\s*(.+)$/m)?.[1]?.trim()
|
|
104
|
+
if (dir) return worktreeOf(/^([a-z]:)?[\\/]/i.test(dir) ? dir : `${top}/${dir}`, top)
|
|
105
|
+
} catch {} // a folder: the main checkout
|
|
106
|
+
return { name: basename(top), worktree: null }
|
|
107
|
+
}
|
|
108
|
+
return { name: basename(cwd), worktree: null }
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function readLimits(headers: Record<string, string>): Limit[] {
|
|
112
|
+
return LIMIT_HEADERS.flatMap(({ kind, prefix }) => {
|
|
113
|
+
const used = Number(headers[`${prefix}-utilization`])
|
|
114
|
+
const reset = Number(headers[`${prefix}-reset`])
|
|
115
|
+
if (!headers[`${prefix}-utilization`] || !Number.isFinite(used)) return []
|
|
116
|
+
return [{ kind, percentUsed: used * 100, resetsAt: reset > 0 ? new Date(reset * 1000).toISOString() : undefined }]
|
|
117
|
+
})
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function sumUsage(ctx: ExtensionContext): Stats {
|
|
121
|
+
const s: Stats = { input: 0, write: 0, read: 0, output: 0, costUsd: null }
|
|
122
|
+
// Every branch: tokens spent on a branch left behind were still spent.
|
|
123
|
+
for (const e of ctx.sessionManager.getEntries()) {
|
|
124
|
+
if (e.type !== 'message' || e.message.role !== 'assistant') continue
|
|
125
|
+
const u = (e.message as AssistantMessage).usage
|
|
126
|
+
if (!u) continue
|
|
127
|
+
s.input += u.input
|
|
128
|
+
s.write += u.cacheWrite
|
|
129
|
+
s.read += u.cacheRead
|
|
130
|
+
s.output += u.output
|
|
131
|
+
if (u.cost?.total) s.costUsd = (s.costUsd ?? 0) + u.cost.total
|
|
132
|
+
}
|
|
133
|
+
return s
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export default function hairline(pi: ExtensionAPI) {
|
|
137
|
+
let settings = readSettings(undefined)
|
|
138
|
+
let requestRender: (() => void) | null = null
|
|
139
|
+
let timer: ReturnType<typeof setInterval> | null = null
|
|
140
|
+
let refresh: ReturnType<typeof setInterval> | null = null
|
|
141
|
+
|
|
142
|
+
let repo: { name: string; worktree: string | null } = { name: '', worktree: null }
|
|
143
|
+
let model = ''
|
|
144
|
+
let sessionId = ''
|
|
145
|
+
let stats: Stats = { input: 0, write: 0, read: 0, output: 0, costUsd: null }
|
|
146
|
+
let saved: Saved = { sessionId: '', turns: 0, activeMs: 0, costStart: null, limitStart: {} }
|
|
147
|
+
let limits: Limit[] = []
|
|
148
|
+
let context: View['context'] = null
|
|
149
|
+
let compactAt: number | null = null
|
|
150
|
+
let phase: Phase = 'idle'
|
|
151
|
+
let tools: Tool[] = []
|
|
152
|
+
let sentAt = 0
|
|
153
|
+
let tps = 0
|
|
154
|
+
let readoutTps = 0 // the figure the readout shows, eased every READOUT_EASE_MS
|
|
155
|
+
let lastReadout = 0
|
|
156
|
+
let isStreaming = false
|
|
157
|
+
let charsPerToken = 4 // the usual English ratio, until the first response measures it
|
|
158
|
+
let hasNerdFont = false
|
|
159
|
+
type Open = View['open']
|
|
160
|
+
let open: Open = null
|
|
161
|
+
let ui: ExtensionContext | null = null // for notify and the model list, from the last session_start
|
|
162
|
+
let hits: Hit[] = []
|
|
163
|
+
let hover: string | null = null
|
|
164
|
+
let footerTop: number | null = null // the footer's first screen row, learned from its mouse events
|
|
165
|
+
let footerRows = 0
|
|
166
|
+
let currentModel: Model<any> | undefined // the session's model, which model_select replaces
|
|
167
|
+
let lastRequestAt: number | null = null
|
|
168
|
+
let lastTurn: { tokens: number; ms: number; usd: number | null } | null = null
|
|
169
|
+
let run: { at: number; tokens: number; usd: number | null } | null = null
|
|
170
|
+
let exchange: { currency: string; rate: number; fetchedOn: string } | null = null
|
|
171
|
+
let exchangeTriedAt = 0
|
|
172
|
+
let extra: Extra | null = null
|
|
173
|
+
let extraNextAt = 0
|
|
174
|
+
let idleReadAt = 0
|
|
175
|
+
const readout = newReadout()
|
|
176
|
+
const graph = newGraph(GRAPH_CELLS)
|
|
177
|
+
let stream = { firstAt: 0, lastSample: 0, recent: [] as { at: number; chars: number }[], chars: 0 }
|
|
178
|
+
|
|
179
|
+
const redraw = () => requestRender?.()
|
|
180
|
+
|
|
181
|
+
function save(): void {
|
|
182
|
+
writeStore(s => {
|
|
183
|
+
s.sessions = [saved, ...(s.sessions ?? []).filter(x => x.sessionId !== saved.sessionId)].slice(0, SAVED_MAX)
|
|
184
|
+
})
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function trackLimits(next: Limit[]): void {
|
|
188
|
+
let changed = false
|
|
189
|
+
for (const l of next) {
|
|
190
|
+
const start = saved.limitStart[l.kind]
|
|
191
|
+
const isNewWindow = !!start && (
|
|
192
|
+
l.percentUsed < start.pct ||
|
|
193
|
+
(!!l.resetsAt && !!start.resetsAt && Date.parse(l.resetsAt) - Date.parse(start.resetsAt) > WINDOW_MOVED_MS)
|
|
194
|
+
)
|
|
195
|
+
if (!start || isNewWindow) {
|
|
196
|
+
saved.limitStart[l.kind] = { pct: l.percentUsed, at: Date.now(), resetsAt: l.resetsAt }
|
|
197
|
+
changed = true
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
if (changed) save()
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// The tilde marks an amount at the usdRate setting, which is only an estimate of the rate.
|
|
204
|
+
function money(usd: number): string {
|
|
205
|
+
const rate = settings.currency === 'USD' ? 1 : exchange?.currency === settings.currency ? exchange.rate : null
|
|
206
|
+
const amount = new Intl.NumberFormat(undefined, { style: 'currency', currency: settings.currency, maximumFractionDigits: 2 }).format(usd * (rate ?? settings.usdRate))
|
|
207
|
+
return rate === null ? `~${amount}` : amount
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
async function readExchange(): Promise<void> {
|
|
211
|
+
const today = new Date().toISOString().slice(0, 10)
|
|
212
|
+
if (settings.currency === 'USD' || (exchange?.currency === settings.currency && exchange.fetchedOn === today)) return
|
|
213
|
+
if (Date.now() - exchangeTriedAt < HOUR_MS) return // a failed fetch waits an hour
|
|
214
|
+
exchangeTriedAt = Date.now()
|
|
215
|
+
try {
|
|
216
|
+
const res = await fetch(RATES_URL + settings.currency, { signal: AbortSignal.timeout(10_000) })
|
|
217
|
+
const rate = ((await res.json()) as { rates?: Record<string, number> }).rates?.[settings.currency]
|
|
218
|
+
if (!res.ok || !rate || rate <= 0) return
|
|
219
|
+
exchange = { currency: settings.currency, rate, fetchedOn: today }
|
|
220
|
+
exchangeTriedAt = 0
|
|
221
|
+
redraw()
|
|
222
|
+
} catch {}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// The store holds the last limits any session saw, so all of them show the same.
|
|
226
|
+
function setLimits(fresh: Limit[]): void {
|
|
227
|
+
if (!fresh.length) return
|
|
228
|
+
const next = [...limits.filter(l => !fresh.some(f => f.kind === l.kind)), ...fresh]
|
|
229
|
+
if (JSON.stringify(next) === JSON.stringify(limits)) return
|
|
230
|
+
limits = next
|
|
231
|
+
trackLimits(fresh)
|
|
232
|
+
writeStore(s => { s.limits = next })
|
|
233
|
+
redraw()
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// Other sessions move the account's limits, and a settings edit changes hairline's own, with no
|
|
237
|
+
// event here. Pi reads its settings file again on each call.
|
|
238
|
+
function readIdle(): void {
|
|
239
|
+
if (phase !== 'idle' || Date.now() - idleReadAt < IDLE_REFRESH_MS) return
|
|
240
|
+
idleReadAt = Date.now()
|
|
241
|
+
settings = readSettings((pi.getSettings() as Record<string, unknown>).hairline)
|
|
242
|
+
const stored = (readStore().limits ?? []).filter(l => !l.resetsAt || Date.parse(l.resetsAt) > Date.now())
|
|
243
|
+
if (JSON.stringify(stored) !== JSON.stringify(limits)) limits = stored
|
|
244
|
+
void readExchange()
|
|
245
|
+
redraw()
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// Only a Claude subscription login (an sk-ant-oat token) has extra usage; an API key has none.
|
|
249
|
+
async function readExtra(): Promise<void> {
|
|
250
|
+
if (!ui || Date.now() < extraNextAt) return
|
|
251
|
+
extraNextAt = Date.now() + EXTRA_RETRY_MS
|
|
252
|
+
try {
|
|
253
|
+
const key = await ui.modelRegistry.getApiKeyForProvider('anthropic')
|
|
254
|
+
if (!key?.includes('sk-ant-oat')) return
|
|
255
|
+
const res = await fetch(USAGE_URL, { headers: { authorization: `Bearer ${key}`, 'anthropic-beta': 'oauth-2025-04-20' }, signal: AbortSignal.timeout(10_000) })
|
|
256
|
+
if (!res.ok) return
|
|
257
|
+
const text = await res.text()
|
|
258
|
+
const next = readExtraBody(text)
|
|
259
|
+
extraNextAt = Date.now() + EXTRA_REFRESH_MS
|
|
260
|
+
setLimits(readUsageLimits(text))
|
|
261
|
+
if (JSON.stringify(next) === JSON.stringify(extra)) return
|
|
262
|
+
extra = next
|
|
263
|
+
redraw()
|
|
264
|
+
} catch {}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
async function readNerdFont(isFresh = false): Promise<boolean> {
|
|
268
|
+
const cached = isFresh ? undefined : readStore().nerdFont
|
|
269
|
+
const found = typeof cached === 'boolean' ? cached : await findNerdFont()
|
|
270
|
+
if (found !== cached) writeStore(s => { s.nerdFont = found })
|
|
271
|
+
if (found !== hasNerdFont) {
|
|
272
|
+
hasNerdFont = found
|
|
273
|
+
redraw()
|
|
274
|
+
}
|
|
275
|
+
return found
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function readContext(c: ExtensionContext): void {
|
|
279
|
+
context = c.getContextUsage() ?? null
|
|
280
|
+
const compaction = (pi.getSettings() as { compaction?: { enabled?: boolean; reserveTokens?: number; modelOverrides?: Record<string, { reserveTokens?: number }> } }).compaction
|
|
281
|
+
const window = context?.contextWindow ?? c.model?.contextWindow ?? 0
|
|
282
|
+
const reserve = (c.model && compaction?.modelOverrides?.[`${c.model.provider}/${c.model.id}`]?.reserveTokens) ?? compaction?.reserveTokens ?? DEFAULT_RESERVE_TOKENS
|
|
283
|
+
compactAt = compaction?.enabled !== false && window > reserve ? ((window - reserve) / window) * 100 : null
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
function setPhase(next: Phase): void {
|
|
287
|
+
phase = next
|
|
288
|
+
setReadoutKind(readout, next, readoutTarget(next, readoutTps, tools).text)
|
|
289
|
+
startTimer()
|
|
290
|
+
redraw()
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
const isAnimating = () => phase !== 'idle' || isScrambling(readout) || !graph.isSettled
|
|
294
|
+
|
|
295
|
+
// One timer drives the spinner, the scramble, the sending time and the graph, and stops
|
|
296
|
+
// when all four are still.
|
|
297
|
+
function startTimer(): void {
|
|
298
|
+
if (timer || !requestRender) return
|
|
299
|
+
const frameMs = Math.round(1000 / settings.frameRate)
|
|
300
|
+
timer = setInterval(() => {
|
|
301
|
+
tickReadout(readout, readoutTarget(phase, readoutTps, tools).text.length)
|
|
302
|
+
tickGraph(graph, frameMs, isStreaming ? tps : 0, phase === 'sending')
|
|
303
|
+
redraw()
|
|
304
|
+
if (!isAnimating() && timer) {
|
|
305
|
+
clearInterval(timer)
|
|
306
|
+
timer = null
|
|
307
|
+
}
|
|
308
|
+
}, frameMs)
|
|
309
|
+
timer.unref?.()
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
function stopTimers(): void {
|
|
313
|
+
if (timer) clearInterval(timer)
|
|
314
|
+
if (refresh) clearInterval(refresh)
|
|
315
|
+
timer = refresh = null
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
function install(c: ExtensionContext): void {
|
|
319
|
+
c.ui.setFooter((tui, _theme, footerData) => {
|
|
320
|
+
requestRender = () => tui.requestRender()
|
|
321
|
+
const unsubscribe = footerData.onBranchChange(() => tui.requestRender())
|
|
322
|
+
// Pi sends pointer moves only to the component under the pointer, so the footer never hears
|
|
323
|
+
// that the pointer left it. The raw SGR reports tell, without consuming them.
|
|
324
|
+
const watchPointer = (data: string) => {
|
|
325
|
+
const m = /\x1b\[<(\d+);(\d+);(\d+)M/.exec(data)
|
|
326
|
+
if (m && hover && footerTop !== null && (Number(m[1]) & 32)) {
|
|
327
|
+
const row = Number(m[3]) - 1 - footerTop
|
|
328
|
+
if (row < 0 || row >= footerRows) setHover(null)
|
|
329
|
+
}
|
|
330
|
+
return undefined
|
|
331
|
+
}
|
|
332
|
+
const stopListening = c.ui.onTerminalInput(watchPointer)
|
|
333
|
+
// Fullscreen mode's own listener comes first and consumes every mouse report, so this one
|
|
334
|
+
// moves to the front of pi-tui's listener set. Without that field, hover clears only on
|
|
335
|
+
// moves inside the footer.
|
|
336
|
+
const listeners = (tui as unknown as { inputListeners?: Set<unknown> }).inputListeners
|
|
337
|
+
if (listeners instanceof Set && listeners.size > 1) {
|
|
338
|
+
// Pi may wrap the handler, so the one just added, the set's last, is this one.
|
|
339
|
+
const all = [...listeners]
|
|
340
|
+
listeners.clear()
|
|
341
|
+
for (const l of [all[all.length - 1], ...all.slice(0, -1)]) listeners.add(l)
|
|
342
|
+
}
|
|
343
|
+
return {
|
|
344
|
+
dispose() {
|
|
345
|
+
unsubscribe()
|
|
346
|
+
stopListening()
|
|
347
|
+
requestRender = null
|
|
348
|
+
stopTimers()
|
|
349
|
+
},
|
|
350
|
+
invalidate() {},
|
|
351
|
+
render(width: number): string[] {
|
|
352
|
+
const target = readoutTarget(phase, readoutTps, tools)
|
|
353
|
+
const text = phase === 'sending' ? waitingText(Date.now() - sentAt, target.text.length) : target.text
|
|
354
|
+
const branch = footerData.getGitBranch()
|
|
355
|
+
const models = pickableModels()
|
|
356
|
+
const drawn = drawFooter({
|
|
357
|
+
folder: repo.name,
|
|
358
|
+
worktree: repo.worktree,
|
|
359
|
+
branch: branch === 'detached' ? 'HEAD' : branch,
|
|
360
|
+
model,
|
|
361
|
+
effort: model ? pi.getThinkingLevel() : null,
|
|
362
|
+
sessionId,
|
|
363
|
+
context,
|
|
364
|
+
compactAt,
|
|
365
|
+
stats,
|
|
366
|
+
turns: saved.turns,
|
|
367
|
+
activeMs: saved.activeMs,
|
|
368
|
+
costStart: saved.costStart,
|
|
369
|
+
limits,
|
|
370
|
+
limitStart: saved.limitStart,
|
|
371
|
+
extra,
|
|
372
|
+
phase,
|
|
373
|
+
tools,
|
|
374
|
+
readout: readoutFrame(readout, text),
|
|
375
|
+
graph: graphText(graph, isStreaming, phase === 'sending'),
|
|
376
|
+
sweepMs: graph.sweepMs,
|
|
377
|
+
isLit: isStreaming || phase === 'sending',
|
|
378
|
+
hasNerdFont,
|
|
379
|
+
open,
|
|
380
|
+
hover,
|
|
381
|
+
models: models.map(m => ({ label: modelLabel(m.id), isCurrent: m.id === model })),
|
|
382
|
+
efforts: supportedEfforts(),
|
|
383
|
+
lastTurn,
|
|
384
|
+
lastRequestAt,
|
|
385
|
+
cacheTtlMinutes: settings.cacheTtlMinutes,
|
|
386
|
+
money,
|
|
387
|
+
statuses: [...footerData.getExtensionStatuses().values()],
|
|
388
|
+
now: Date.now(),
|
|
389
|
+
}, width)
|
|
390
|
+
hits = drawn.hits
|
|
391
|
+
footerRows = drawn.lines.length
|
|
392
|
+
return drawn.lines
|
|
393
|
+
},
|
|
394
|
+
// Fullscreen mode routes the mouse here; regular mode leaves it to the terminal.
|
|
395
|
+
handleMouse(event) {
|
|
396
|
+
footerTop = event.screenY - event.y
|
|
397
|
+
if (event.type === 'move') {
|
|
398
|
+
setHover(hits.find(h => h.row === event.y && event.x >= h.from && event.x < h.to)?.action ?? null)
|
|
399
|
+
return undefined
|
|
400
|
+
}
|
|
401
|
+
if (event.button !== 'left' || (event.type !== 'press' && event.type !== 'click')) return undefined
|
|
402
|
+
const hit = hits.find(h => h.row === event.y && event.x >= h.from && event.x < h.to)
|
|
403
|
+
if (!hit) return undefined
|
|
404
|
+
if (event.type === 'click') void act(hit.action)
|
|
405
|
+
return { handled: true }
|
|
406
|
+
},
|
|
407
|
+
}
|
|
408
|
+
})
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
function setHover(next: string | null): void {
|
|
412
|
+
if (next === hover) return
|
|
413
|
+
hover = next
|
|
414
|
+
redraw()
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
function setOpen(next: Open): void {
|
|
418
|
+
open = open === next ? null : next
|
|
419
|
+
redraw()
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
// The session's scoped models, as Pi's own picker offers them, or every model with a key.
|
|
423
|
+
function pickableModels(): Model<any>[] {
|
|
424
|
+
if (!ui) return []
|
|
425
|
+
const scoped = ui.scopedModels.map(s => s.model)
|
|
426
|
+
return scoped.length ? scoped : ui.modelRegistry.getAvailable()
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
function supportedEfforts(): string[] {
|
|
430
|
+
return currentModel ? getSupportedThinkingLevels(currentModel) : []
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
async function copySessionId(c: ExtensionContext): Promise<void> {
|
|
434
|
+
const id = c.sessionManager.getSessionId()
|
|
435
|
+
const isCopied = await copyToClipboard(id).then(() => true, () => false)
|
|
436
|
+
c.ui.notify(isCopied ? `session id copied: ${id}` : `session id: ${id}`, 'info')
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
async function act(action: string): Promise<void> {
|
|
440
|
+
if (action === 'ledger' || action === 'model' || action === 'effort') return setOpen(action)
|
|
441
|
+
if (!ui) return
|
|
442
|
+
if (action === 'id') return copySessionId(ui)
|
|
443
|
+
const [kind, value] = action.split(':') as [string, string]
|
|
444
|
+
open = null
|
|
445
|
+
redraw()
|
|
446
|
+
if (kind === 'model') {
|
|
447
|
+
const picked = pickableModels()[Number(value)]
|
|
448
|
+
if (!picked) return
|
|
449
|
+
const isSet = await pi.setModel(picked)
|
|
450
|
+
ui.ui.notify(isSet ? `model ${picked.id}` : `model not changed: ${picked.provider} has no API key`, isSet ? 'info' : 'warning')
|
|
451
|
+
} else if (kind === 'effort') {
|
|
452
|
+
pi.setThinkingLevel(value as Parameters<ExtensionAPI['setThinkingLevel']>[0])
|
|
453
|
+
ui.ui.notify(`thinking ${pi.getThinkingLevel()}`, 'info')
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
pi.registerCommand('hairline', {
|
|
458
|
+
description: 'Show or hide the hairline ledger; in fullscreen mode, a click on the token split does too',
|
|
459
|
+
handler: async () => setOpen('ledger'),
|
|
460
|
+
})
|
|
461
|
+
|
|
462
|
+
pi.registerCommand('hairline-fonts', {
|
|
463
|
+
description: 'Look for a Nerd Font again, after installing or removing one',
|
|
464
|
+
handler: async (_args, c) => {
|
|
465
|
+
c.ui.notify((await readNerdFont(true)) ? 'Nerd Font found: the line shows its glyphs.' : 'No Nerd Font found: the line shows no glyphs.', 'info')
|
|
466
|
+
},
|
|
467
|
+
})
|
|
468
|
+
|
|
469
|
+
pi.registerCommand('hairline-id', {
|
|
470
|
+
description: 'Copy the session ID',
|
|
471
|
+
handler: async (_args, c) => copySessionId(c),
|
|
472
|
+
})
|
|
473
|
+
|
|
474
|
+
pi.on('session_start', async (_e, c) => {
|
|
475
|
+
ui = c
|
|
476
|
+
settings = readSettings((pi.getSettings() as Record<string, unknown>).hairline)
|
|
477
|
+
repo = findRepo(c.cwd)
|
|
478
|
+
model = c.model?.id ?? ''
|
|
479
|
+
currentModel = c.model
|
|
480
|
+
sessionId = c.sessionManager.getSessionId()
|
|
481
|
+
stats = sumUsage(c)
|
|
482
|
+
const store = readStore()
|
|
483
|
+
saved = { turns: 0, activeMs: 0, limitStart: {}, ...store.sessions?.find(s => s.sessionId === sessionId), sessionId, costStart: null }
|
|
484
|
+
saved.costStart = store.sessions?.find(s => s.sessionId === sessionId)?.costStart ?? stats.costUsd
|
|
485
|
+
// Limits belong to the account, so the last ones seen hold until their window resets.
|
|
486
|
+
limits = (store.limits ?? []).filter(l => !l.resetsAt || Date.parse(l.resetsAt) > Date.now())
|
|
487
|
+
readContext(c)
|
|
488
|
+
if (c.mode !== 'tui') return
|
|
489
|
+
install(c)
|
|
490
|
+
void readNerdFont()
|
|
491
|
+
void readExchange()
|
|
492
|
+
void readExtra()
|
|
493
|
+
refresh = setInterval(() => {
|
|
494
|
+
void readExchange()
|
|
495
|
+
void readExtra()
|
|
496
|
+
readIdle()
|
|
497
|
+
if (open === 'ledger') redraw() // the cache countdown changes with no event
|
|
498
|
+
}, REFRESH_MS)
|
|
499
|
+
refresh.unref?.()
|
|
500
|
+
})
|
|
501
|
+
|
|
502
|
+
pi.on('session_shutdown', async () => {
|
|
503
|
+
stopTimers()
|
|
504
|
+
ui = null
|
|
505
|
+
})
|
|
506
|
+
|
|
507
|
+
pi.on('model_select', async (e, c) => {
|
|
508
|
+
model = e.model.id
|
|
509
|
+
currentModel = e.model
|
|
510
|
+
readContext(c)
|
|
511
|
+
redraw()
|
|
512
|
+
})
|
|
513
|
+
|
|
514
|
+
pi.on('thinking_level_select', async () => redraw())
|
|
515
|
+
|
|
516
|
+
pi.on('agent_start', async () => {
|
|
517
|
+
run = { at: Date.now(), tokens: counted(stats), usd: stats.costUsd }
|
|
518
|
+
})
|
|
519
|
+
|
|
520
|
+
pi.on('turn_start', async () => {
|
|
521
|
+
tools = []
|
|
522
|
+
sentAt = Date.now()
|
|
523
|
+
setPhase('sending')
|
|
524
|
+
})
|
|
525
|
+
|
|
526
|
+
pi.on('after_provider_response', async e => setLimits(readLimits(e.headers)))
|
|
527
|
+
|
|
528
|
+
// Streams carry characters, so the speed divides by the characters per token of the last response.
|
|
529
|
+
pi.on('message_update', async e => {
|
|
530
|
+
const ev = e.assistantMessageEvent
|
|
531
|
+
const piece = ev.type === 'text_delta' || ev.type === 'thinking_delta' || ev.type === 'toolcall_delta' ? ev.delta.length : 0
|
|
532
|
+
if (!piece) return
|
|
533
|
+
const now = Date.now()
|
|
534
|
+
if (!isStreaming) {
|
|
535
|
+
isStreaming = true
|
|
536
|
+
stream = { firstAt: now, lastSample: 0, recent: [], chars: 0 }
|
|
537
|
+
setPhase('receiving')
|
|
538
|
+
}
|
|
539
|
+
stream.chars += piece
|
|
540
|
+
stream.recent.push({ at: now, chars: piece })
|
|
541
|
+
while (stream.recent[0]!.at < now - RATE_WINDOW_MS) stream.recent.shift()
|
|
542
|
+
// No warm-up: the figure shows from the first chunk. Claude Code waits 1 s.
|
|
543
|
+
if (now - stream.lastSample >= 1000 / settings.refreshPerSecond) {
|
|
544
|
+
const windowSecs = Math.min(RATE_WINDOW_MS, Math.max(RATE_MIN_WINDOW_MS, now - stream.firstAt)) / 1000
|
|
545
|
+
tps = Math.round(stream.recent.reduce((sum, r) => sum + r.chars, 0) / charsPerToken / windowSecs)
|
|
546
|
+
stream.lastSample = now
|
|
547
|
+
// The graph takes every sample; the readout's figure eases at a pace the eye can read.
|
|
548
|
+
if (now - lastReadout >= READOUT_EASE_MS) {
|
|
549
|
+
readoutTps = readoutTps ? Math.round(readoutTps + (tps - readoutTps) / 2) : tps
|
|
550
|
+
lastReadout = now
|
|
551
|
+
}
|
|
552
|
+
redraw()
|
|
553
|
+
}
|
|
554
|
+
})
|
|
555
|
+
|
|
556
|
+
pi.on('message_end', async (e, c) => {
|
|
557
|
+
if (e.message.role !== 'assistant') return
|
|
558
|
+
const m = e.message as AssistantMessage
|
|
559
|
+
// Only the finished message has real token counts, so it sets the ratio for the next reply.
|
|
560
|
+
if (m.usage?.output >= RATIO_MIN_TOKENS && stream.chars) {
|
|
561
|
+
charsPerToken = Math.min(RATIO_MAX, Math.max(RATIO_MIN, stream.chars / m.usage.output))
|
|
562
|
+
}
|
|
563
|
+
isStreaming = false
|
|
564
|
+
tps = 0
|
|
565
|
+
readoutTps = 0
|
|
566
|
+
stream.chars = 0
|
|
567
|
+
lastRequestAt = Date.now()
|
|
568
|
+
tools = m.content.flatMap(part => (part.type === 'toolCall' ? [{ name: toolName(part.name), arg: toolArg(part.arguments) }] : []))
|
|
569
|
+
stats = sumUsage(c)
|
|
570
|
+
readContext(c)
|
|
571
|
+
setPhase(tools.length ? 'tool' : 'idle')
|
|
572
|
+
})
|
|
573
|
+
|
|
574
|
+
pi.on('session_compact', async (_e, c) => {
|
|
575
|
+
readContext(c)
|
|
576
|
+
redraw()
|
|
577
|
+
})
|
|
578
|
+
|
|
579
|
+
pi.on('agent_settled', async (_e, c) => {
|
|
580
|
+
isStreaming = false
|
|
581
|
+
tps = 0
|
|
582
|
+
readoutTps = 0
|
|
583
|
+
stats = sumUsage(c)
|
|
584
|
+
readContext(c)
|
|
585
|
+
if (run) {
|
|
586
|
+
const ms = Date.now() - run.at
|
|
587
|
+
lastTurn = { tokens: counted(stats) - run.tokens, ms, usd: stats.costUsd !== null ? stats.costUsd - (run.usd ?? 0) : null }
|
|
588
|
+
saved.turns += 1
|
|
589
|
+
saved.activeMs += ms
|
|
590
|
+
saved.costStart ??= run.usd ?? 0
|
|
591
|
+
run = null
|
|
592
|
+
save()
|
|
593
|
+
}
|
|
594
|
+
tools = []
|
|
595
|
+
setPhase('idle')
|
|
596
|
+
})
|
|
597
|
+
|
|
598
|
+
}
|