useful-pi-extensions 1.7.0 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "useful-pi-extensions",
3
- "version": "1.7.0",
3
+ "version": "1.8.0",
4
4
  "description": "A small collection of pi extensions, installed with one command — a labelled status line with context pressure, cache, cost, effort, TTFT and tokens/sec.",
5
5
  "keywords": [
6
6
  "bun",
@@ -54,7 +54,8 @@ Configuration lives at the top of [`render.ts`](render.ts):
54
54
  ## Currency
55
55
 
56
56
  pi prices every model in USD and its `cost` field carries no unit at all, so the footer cannot know
57
- what you were actually billed. The currency and the rate live in `~/.pi/agent/statusline.json`:
57
+ what you were actually billed. The currency and the rate live in `~/.pi/agent/statusline/config.json` — everything this
58
+ extension keeps (config plus the reload-proof state file) sits in that one folder:
58
59
 
59
60
  ```json
60
61
  {
@@ -52,7 +52,7 @@ LSP Active: typescript
52
52
  ## 币种
53
53
 
54
54
  pi 里所有模型价格都是美元,而且它的 `cost` 字段**不带任何单位**,所以 footer 无从知道你实际是按什么币种付的。
55
- 币种与汇率放在 `~/.pi/agent/statusline.json`:
55
+ 币种与汇率放在 `~/.pi/agent/statusline/config.json`——本扩展的所有文件(配置加状态)都集中在这个文件夹里:
56
56
 
57
57
  ```json
58
58
  {
@@ -18,10 +18,10 @@
18
18
  * stepStartTime; decodeMs = completedTime - firstTokenTime; tok/s = usage.output / (decodeMs / 1000)
19
19
  */
20
20
 
21
- import { readFile, readdir, writeFile } from 'node:fs/promises'
21
+ import { mkdir, readFile, readdir, rename, writeFile } from 'node:fs/promises'
22
22
  import { stat } from 'node:fs/promises'
23
23
  import { homedir } from 'node:os'
24
- import { join } from 'node:path'
24
+ import { dirname, join } from 'node:path'
25
25
 
26
26
  import type {
27
27
  ExtensionAPI,
@@ -61,13 +61,18 @@ const TICK_MS = 250
61
61
  const FALLBACK_TOKENS_PER_CHAR = 0.25
62
62
 
63
63
  /** The status line's own settings file, alongside pi's other per-tool config. */
64
- const CONFIG_PATH = join(homedir(), '.pi', 'agent', 'statusline.json')
64
+ /** Everything this extension keeps lives in one folder, not loose files relying on name prefixes. */
65
+ const STATUSLINE_DIR = join(homedir(), '.pi', 'agent', 'statusline')
66
+ const CONFIG_PATH = join(STATUSLINE_DIR, 'config.json')
67
+ /** Pre-1.8 locations, migrated out of on first start. */
68
+ const LEGACY_CONFIG = join(homedir(), '.pi', 'agent', 'statusline.json')
65
69
  /** Free, keyless, and one request returns every currency — so the cache serves instant switching. */
66
70
  const RATES_URL = 'https://open.er-api.com/v6/latest/USD'
67
71
  /** Every session on this machine, for the day-cost total that spans projects and models. */
68
72
  const SESSIONS_DIR = join(homedir(), '.pi', 'agent', 'sessions')
69
73
  /** Where throughput metrics wait out a /reload: keyed by session file, so a reload restores. */
70
- const STATE_PATH = join(homedir(), '.pi', 'agent', 'statusline-state.json')
74
+ const STATE_PATH = join(STATUSLINE_DIR, 'state.json')
75
+ const LEGACY_STATE = join(homedir(), '.pi', 'agent', 'statusline-state.json')
71
76
  const FETCH_TIMEOUT_MS = 5000
72
77
 
73
78
  function today(): string {
@@ -118,6 +123,16 @@ function num(value: unknown): number {
118
123
  return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : 0
119
124
  }
120
125
 
126
+ /** Moves a pre-1.8 flat file into the extension folder; missing files are the normal case. */
127
+ async function migrateLegacyFile(legacy: string, current: string): Promise<void> {
128
+ try {
129
+ await mkdir(dirname(current), { recursive: true })
130
+ await rename(legacy, current)
131
+ } catch {
132
+ // Nothing at the old path, or already migrated: either way the current file rules.
133
+ }
134
+ }
135
+
121
136
  /** Today's provider cost of one session-file line, or null when the line bills nothing today. */
122
137
  function entryCost(line: string, since: number): number | null {
123
138
  if (!line.includes('"usage"')) return null
@@ -191,6 +206,8 @@ async function loadCurrency(notify: (message: string) => void): Promise<Currency
191
206
  const { currency, pending, problem } = currencyFromConfig(text)
192
207
  if (problem !== null) notify(problem)
193
208
  if (pending === null) return currency
209
+ // Costs are already USD; a rates fetch could only ever return 1.
210
+ if (pending.code === 'USD') return USD
194
211
 
195
212
  const cached = cachedRates(text)
196
213
  const known = cached?.rates[pending.code]
@@ -337,6 +354,12 @@ export default function (pi: ExtensionAPI) {
337
354
  let totalTtftMs = 0
338
355
  let ttftCount = 0
339
356
  let todayBase = 0
357
+ /** Last context usage pi reported with real numbers, shown when pi's current answer is stale. */
358
+ let lastKnownUsage: {
359
+ tokens: number | null
360
+ percent: number | null
361
+ contextWindow: number
362
+ } | null = null
340
363
  let ticker: ReturnType<typeof setInterval> | null = null
341
364
  let windowAt = 0
342
365
  let windowTokens = 0
@@ -428,15 +451,22 @@ export default function (pi: ExtensionAPI) {
428
451
  },
429
452
  render(width: number): string[] {
430
453
  const usage = ctx.getContextUsage()
454
+ // pi nulls tokens and percent when the last usage predates a compaction and no response
455
+ // has landed since: the numbers it could hand over are stale, not zero. Show the last
456
+ // reading we trusted instead; a brand-new session starts at 0, which is near the truth.
457
+ const trusted =
458
+ usage !== undefined && usage.tokens !== null && usage.percent !== null ? usage : null
459
+ if (trusted !== null) lastKnownUsage = trusted
460
+ const shown = trusted ?? lastKnownUsage
431
461
  const totals = collectTotals(ctx, startOfToday())
432
462
  const avg = avgTokPerSec(totalMeasuredOutput, totalDecodeMs)
433
463
  const row1 = contextRow(
434
464
  theme,
435
465
  width,
436
466
  {
437
- percent: usage?.percent ?? null,
438
- tokens: usage?.tokens ?? 0,
439
- window: usage?.contextWindow ?? ctx.model?.contextWindow ?? 0,
467
+ percent: shown?.percent ?? 0,
468
+ tokens: shown?.tokens ?? 0,
469
+ window: usage?.contextWindow ?? shown?.contextWindow ?? ctx.model?.contextWindow ?? 0,
440
470
  input: totals.input,
441
471
  output: totals.output,
442
472
  cacheHitRate: totals.cacheHitRate,
@@ -547,6 +577,9 @@ export default function (pi: ExtensionAPI) {
547
577
  stopTicker()
548
578
  resetStream()
549
579
  currency = await loadCurrency((message) => ctx.ui.notify(message, 'warning'))
580
+ lastKnownUsage = null
581
+ await migrateLegacyFile(LEGACY_CONFIG, CONFIG_PATH)
582
+ await migrateLegacyFile(LEGACY_STATE, STATE_PATH)
550
583
  const file = ctx.sessionManager.getSessionFile()
551
584
  await restore(file ?? null)
552
585
  todayBase = await sumOtherTodaysCost(file ?? null, startOfToday())
@@ -429,7 +429,7 @@ export function contextRow(
429
429
  const percent = theme.fg(
430
430
  percentColor(parts.percent),
431
431
  // Whole percents: the meter carries the precision, and a decimal here is noise.
432
- parts.percent === null ? '?' : `${Math.round(parts.percent)}%`,
432
+ parts.percent === null ? '--' : `${Math.round(parts.percent)}%`,
433
433
  )
434
434
  const meter = `${theme.fg('dim', 'Context')} ${bar(theme, BAR_CELLS, fraction)} ${percent}`
435
435
  const detail =