pi-footer-stats 0.1.0 → 0.1.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/CHANGELOG.md CHANGED
@@ -5,6 +5,44 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [0.1.2] - 2026-12-04
9
+
10
+ ### Fixed
11
+
12
+ - `⚡` tok/s could be badly inflated when the provider's stream is delivered in
13
+ one burst after completion (observed against omlx: a 720 ms generation
14
+ produced an 8 ms `message_start`→`message_end` window, and a session averaged
15
+ 449 tok/s instead of the true ~94). The rate now uses pi-ai's monotonic
16
+ `message.durationMs` as the primary time source, falling back to the
17
+ wall-clock window for messages without it (invalid values — non-finite,
18
+ non-positive, non-numeric — fall back too, so they can never poison the
19
+ accumulator). History seeding likewise prefers `durationMs` over
20
+ entry-timestamp gaps. Regression suite extended with burst-delivery,
21
+ missing-`message_start`, invalid-value, and mixed-seeding cases.
22
+
23
+ ## [0.1.1] - 2026-12-04
24
+
25
+ ### Changed
26
+
27
+ - Packaging: explicit `pi` manifest, `peerDependencies` for host-supplied
28
+ packages (`@earendil-works/pi-coding-agent`, `@earendil-works/pi-tui`),
29
+ normalized `repository.url`.
30
+ - README restructured for users (install options table, community section);
31
+ maintainer documentation moved to CONTRIBUTING.md.
32
+ - `demo.svg` is now generated from the real footer component output
33
+ (`scripts/make-demo.mjs`) and shipped in the package; the README references
34
+ it by absolute URL so it renders on npmjs.com too.
35
+ - Clarified that `⚡` tokens/second is a per-session average, not a model
36
+ benchmark.
37
+
38
+ ### Added
39
+
40
+ - SECURITY.md security policy.
41
+ - CI running the regression suite on every push/PR; issue and pull-request
42
+ templates; AGENTS.md for AI agents.
43
+ - Repository tooling (not part of the npm tarball): `scripts/release.mjs`
44
+ one-command release flow, `scripts/make-demo.mjs` demo generator.
45
+
8
46
  ## [0.1.0] - 2026-12-04
9
47
 
10
48
  Initial release.
package/README.md CHANGED
@@ -1,50 +1,62 @@
1
- # pi footer-stats
2
-
3
- [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
4
- ![Release](https://img.shields.io/github/v/release/ssa17/pi-footer-stats)
5
-
6
- Custom [pi](https://github.com/earendil-works/pi) footer: colored session stats, a tokens/second average, and a context-window progress bar.
1
+ <p align="center">
2
+ <b>pi footer-stats</b><br>
3
+ Colored session stats, a tokens/second average, and a context-window progress bar for <a href="https://github.com/earendil-works/pi">pi</a>.
4
+ </p>
5
+
6
+ <p align="center">
7
+ <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue" alt="License"></a>
8
+ <a href="https://github.com/ssa17/pi-footer-stats/releases"><img src="https://img.shields.io/github/v/release/ssa17/pi-footer-stats" alt="Release"></a>
9
+ <a href="https://github.com/ssa17/pi-footer-stats/actions/workflows/test.yml"><img src="https://github.com/ssa17/pi-footer-stats/actions/workflows/test.yml/badge.svg" alt="Tests"></a>
10
+ <a href="https://www.npmjs.com/package/pi-footer-stats"><img src="https://img.shields.io/npm/dm/pi-footer-stats" alt="npm downloads"></a>
11
+ </p>
12
+
13
+ <p align="center">
14
+ <a href="#install">Install</a> ·
15
+ <a href="#what-you-get">What you get</a> ·
16
+ <a href="#behavior--privacy">Behavior &amp; privacy</a> ·
17
+ <a href="SECURITY.md">Security</a> ·
18
+ <a href="CONTRIBUTING.md">Contributing</a>
19
+ </p>
20
+
21
+ ---
22
+
23
+ ![pi-footer-stats example footer](https://raw.githubusercontent.com/ssa17/pi-footer-stats/main/demo.svg)
7
24
 
8
25
  ```
9
26
  ~/workspace/apps/toolbox (main)
10
- ↑590 ↓2.4k ↺ R97k ✎ W1.0k ◎ CH99.8% ⚡257 tok/s $0.058 ▄▁▁▁▁▁▁▁▁▁ 2.6%/1.0M (auto) (omlx) Qwen4-35B-A3B-oQ4e-mtp • medium
27
+ ↑10k ↓5.4k ↺ R650k ✎ W0 ◎ CH98.5% ⚡77.1 tok/s $0.000 ▄▁▁▁▁▁▁▁▁▁ 2.5%/1.0M (auto) (omlx) Qwen4-35B-A3B-oQ4e-mtp • medium
11
28
  ```
12
29
 
13
30
  ## Install
14
31
 
15
- ```bash
16
- pi install https://github.com/ssa17/pi-footer-stats
17
- ```
18
-
19
- Pi clones the package and loads `extensions/` automatically. Run `/reload`
20
- (or restart pi) to apply. Update later with `pi update --extensions`;
21
- remove with `pi remove`. Pin a version with
22
- `pi install git:github.com/ssa17/pi-footer-stats@v0.1.0`.
32
+ **Requirement:** [pi](https://github.com/earendil-works/pi) installed — via
33
+ Homebrew (`brew install pi-coding-agent`), the managed installer, or npm.
34
+ That's it for the extension too: no npm login, no dependencies, no build step.
23
35
 
24
- <details>
25
- <summary>Manual / symlinked install (for development)</summary>
36
+ | Method | Command | Updates |
37
+ | --- | --- | --- |
38
+ | **npm (recommended)** | `pi install npm:pi-footer-stats` | automatic — pi checks the registry at startup; new changelog entries show under **Extension Updates** |
39
+ | git source | `pi install https://github.com/ssa17/pi-footer-stats` | `pi update --extensions` (tracks `main`; pin with `@v0.1.0`) |
40
+ | manual / symlink | see [CONTRIBUTING.md](CONTRIBUTING.md#dev-setup) | you manage it |
26
41
 
27
42
  ```bash
28
- git clone https://github.com/ssa17/pi-footer-stats.git ~/workspace/apps/pi-footer-stats
29
- mkdir -p ~/.pi/agent/extensions ~/.pi/agent/tests
30
- ln -s ~/workspace/apps/pi-footer-stats/extensions/footer-stats.ts \
31
- ~/.pi/agent/extensions/footer-stats.ts
32
- ln -s ~/workspace/apps/pi-footer-stats/tests/footer-stats.test.mjs \
33
- ~/.pi/agent/tests/footer-stats.test.mjs
43
+ pi install npm:pi-footer-stats
34
44
  ```
35
45
 
36
- Symlinks apply edits live — pi canonicalizes extension paths and aliases all
37
- `@earendil-works/*` imports itself, so file location never matters.
46
+ Then `/reload` (or restart pi) and the footer replaces the built-in one.
38
47
 
39
- </details>
48
+ - **Remove** — `pi remove npm:pi-footer-stats`
49
+ - **Pin a version** — `pi install npm:pi-footer-stats@0.1.0`
40
50
 
41
51
  ## What you get
42
52
 
43
53
  - **Cumulative session stats** — `↑` input, `↓` output, `↺ R` cache reads,
44
54
  `✎ W` cache writes, `$` cost, each in its own color
45
55
  - **`◎ CH`** cache-hit rate, color-coded (green ≥90 / yellow ≥50 / gray)
46
- - **`⚡` tokens/second** — session-average *generation* throughput (pure
47
- streaming time; reasoning tokens never double-counted)
56
+ - **`⚡` tokens/second** — average generation throughput **for the current
57
+ session** — not a model benchmark: it reflects the model, hardware, and
58
+ load of this session. Measured with pi's per-message monotonic timing
59
+ (`durationMs`); reasoning tokens never double-counted
48
60
  - **Context bar** — `▄▁▁▁▁▁▁▁▁▁`, one cell per 1%, dim → yellow >70% →
49
61
  **bold red >90%** as auto-compact nears, with `(auto)` when enabled
50
62
  - **Stable layout** — every indicator always shown (`0`/`—` placeholders),
@@ -59,23 +71,19 @@ Symlinks apply edits live — pi canonicalizes extension paths and aliases all
59
71
  - **Degrades gracefully**: a render error (e.g. pi API drift on an untested
60
72
  version) collapses to one dim line instead of breaking the TUI
61
73
  - Tested with **pi 1.8.0**; uses only public extension APIs
74
+ - Security policy: [SECURITY.md](SECURITY.md)
62
75
 
63
76
  ## Development
64
77
 
65
- ```bash
66
- node ~/.pi/agent/tests/footer-stats.test.mjs
67
- ```
68
-
69
- 58 assertions (rate accuracy, lifecycle, totals, bar fill, color thresholds,
70
- truncation, render guard); exits non-zero on failure. The suite respects
71
- `PI_CODING_AGENT_DIR` and auto-resolves the active pi install.
78
+ Setup, ground rules, and the regression suite (which CI runs on every push)
79
+ live in [CONTRIBUTING.md](CONTRIBUTING.md).
72
80
 
73
- ## Releasing
81
+ ## Community
74
82
 
75
- 1. Bump `version` in `package.json` (semver)
76
- 2. Add an entry to [CHANGELOG.md](CHANGELOG.md)
77
- 3. `git commit`, then `git tag vX.Y.Z && git push origin main --tags`
78
- 4. `gh release create vX.Y.Z` with notes from the changelog entry
83
+ - 🐛 [Issues](https://github.com/ssa17/pi-footer-stats/issues) — bug reports and feature requests (templates provided)
84
+ - 💬 [Discussions](https://github.com/ssa17/pi-footer-stats/discussions) — questions and ideas
85
+ - 🔒 [Security policy](SECURITY.md)
86
+ - 🤝 [Contributing guide](CONTRIBUTING.md)
79
87
 
80
88
  ## License
81
89
 
package/SECURITY.md ADDED
@@ -0,0 +1,34 @@
1
+ # Security Policy
2
+
3
+ ## Scope
4
+
5
+ `pi-footer-stats` is a **read-only** pi footer extension. By design it:
6
+
7
+ - reads session state (token usage, context size) and two settings files —
8
+ user (`~/.pi/agent/settings.json`) and project (`.pi/settings.json`) —
9
+ purely to render the footer
10
+ - performs **no network access**, **no writes**, **no tool calls**, and
11
+ stores **no credentials**; nothing is persisted outside the pi process
12
+
13
+ Any change that would introduce network access, file writes, or credential
14
+ handling is considered a security regression and should be reported as one.
15
+
16
+ ## Reporting a vulnerability
17
+
18
+ Please use GitHub's **private vulnerability reporting** for this repository
19
+ when available. Otherwise, open a public issue with minimal detail and ask
20
+ for a private contact channel.
21
+
22
+ Include wherever possible:
23
+
24
+ - pi version and `pi-footer-stats` version
25
+ - OS and terminal
26
+ - a minimal reproduction
27
+
28
+ ## Supported versions
29
+
30
+ | Version | Supported |
31
+ | ------- | --------- |
32
+ | 0.1.x | ✅ |
33
+
34
+ Fixes are handled best-effort; there is no bug bounty.
package/demo.svg ADDED
@@ -0,0 +1,27 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="1400" height="230" viewBox="0 0 1400 230" role="img" aria-label="pi footer-stats example footer with color legend">
2
+ <!-- Generated by scripts/make-demo.mjs from the real footer component output. Do not edit by hand. -->
3
+ <rect width="1400" height="230" rx="8" fill="#23232e"/>
4
+ <g font-family="Menlo, Monaco, Consolas, 'DejaVu Sans Mono', monospace" font-size="14">
5
+ <text x="18" y="34" xml:space="preserve"><tspan fill="#8a8fa3">~/workspace/apps/toolbox (main)</tspan></text>
6
+ <text x="18" y="66" xml:space="preserve"><tspan fill="#a78bfa">↑10k</tspan><tspan fill="#8a8fa3"> </tspan><tspan fill="#56d364">↓5.4k</tspan><tspan fill="#8a8fa3"> </tspan><tspan fill="#768390">↺ R650k</tspan><tspan fill="#8a8fa3"> </tspan><tspan fill="#e3b341">✎ W0</tspan><tspan fill="#8a8fa3"> </tspan><tspan fill="#56d364">◎ CH98.5%</tspan><tspan fill="#8a8fa3"> </tspan><tspan fill="#63d9a8">⚡77.1 tok/s</tspan><tspan fill="#8a8fa3"> </tspan><tspan fill="#58a6ff">$0.000</tspan><tspan fill="#8a8fa3"> </tspan><tspan fill="#8a8fa3">▄▁▁▁▁▁▁▁▁▁ 2.5%/1.0M (auto)</tspan><tspan fill="#8a8fa3"> </tspan><tspan fill="#8a8fa3">(omlx) Qwen4-35B-A3B-oQ4e-mtp • medium</tspan></text>
7
+ </g>
8
+ <line x1="18" y1="96" x2="1382" y2="96" stroke="#3a3a48" stroke-width="1"/>
9
+ <g font-family="Menlo, Monaco, Consolas, 'DejaVu Sans Mono', monospace" font-size="15">
10
+ <circle cx="26" cy="130" r="6" fill="#a78bfa"/>
11
+ <text x="42" y="135" fill="#e6e6f0">↑ input tokens</text>
12
+ <circle cx="330" cy="130" r="6" fill="#56d364"/>
13
+ <text x="346" y="135" fill="#e6e6f0">↓ output tokens</text>
14
+ <circle cx="640" cy="130" r="6" fill="#768390"/>
15
+ <text x="656" y="135" fill="#e6e6f0">↺ cache reads</text>
16
+ <circle cx="950" cy="130" r="6" fill="#e3b341"/>
17
+ <text x="966" y="135" fill="#e6e6f0">✎ cache writes</text>
18
+ <circle cx="26" cy="180" r="6" fill="#56d364"/>
19
+ <text x="42" y="185" fill="#e6e6f0">◎ cache-hit rate</text>
20
+ <circle cx="330" cy="180" r="6" fill="#63d9a8"/>
21
+ <text x="346" y="185" fill="#e6e6f0">⚡ session tok/s</text>
22
+ <circle cx="640" cy="180" r="6" fill="#58a6ff"/>
23
+ <text x="656" y="185" fill="#e6e6f0">$ session cost</text>
24
+ <circle cx="950" cy="180" r="6" fill="#8a8fa3"/>
25
+ <text x="966" y="185" fill="#e6e6f0">▄▁ context bar · 1%/cell</text>
26
+ </g>
27
+ </svg>
@@ -16,14 +16,16 @@
16
16
  * "(auto)" suffix when automatic compaction is enabled
17
17
  * Line 3: any other extension statuses via ctx.ui.setStatus() (dim)
18
18
  *
19
- * Token rate: exact wall time between message_start/message_end per assistant
20
- * message. message_start fires when the provider response headers arrive (after
21
- * connection setup and internal retries) and message_end when the stream is
22
- * finalized, so this measures pure generation throughput. Generated tokens use
19
+ * Token rate: per assistant message, pi-ai's `message.durationMs` (monotonic,
20
+ * measured inside pi-ai's AssistantMessageEventStream from stream creation to
21
+ * `done`) is the primary time source, falling back to wall time between
22
+ * message_start/message_end. The fallback matters because some providers/clients
23
+ * deliver a buffered stream in one burst, collapsing the message_start→
24
+ * message_end window to near-zero and inflating the rate. Generated tokens use
23
25
  * usage.output only — usage.reasoning is a subset of output per pi-ai's Usage
24
26
  * docs, so adding both would double-count thinking tokens. On session_start the
25
- * accumulator is reset and re-seeded from session entry timestamps
26
- * (approximate, includes queue/TTFT gaps).
27
+ * accumulator is reset and re-seeded from session entries (durationMs when
28
+ * present, otherwise entry timestamps — approximate, includes queue/TTFT gaps).
27
29
  */
28
30
 
29
31
  import { readFileSync } from "node:fs";
@@ -169,18 +171,26 @@ export default function (pi: ExtensionAPI) {
169
171
  totalMs = 0;
170
172
  turnStartMs = null;
171
173
 
172
- // Seed the rate accumulator from session history (approximate).
174
+ // Seed the rate accumulator from session history. Entries written by
175
+ // recent pi versions carry message.durationMs (exact); older entries fall
176
+ // back to entry-timestamp gaps (approximate, includes queue/TTFT gaps).
173
177
  let prevTs: number | null = null;
174
178
  for (const raw of ctx.sessionManager.getEntries()) {
175
179
  const entry = raw as {
176
180
  type?: string;
177
181
  timestamp?: string;
178
- message?: { role?: string; usage?: UsageLike };
182
+ message?: { role?: string; usage?: UsageLike; durationMs?: number };
179
183
  };
180
184
  const ts = entry.timestamp ? Date.parse(entry.timestamp) : Number.NaN;
181
185
  if (entry.type === "message" && entry.message?.role === "assistant") {
182
186
  const tokens = generatedTokens(entry.message.usage);
183
- if (tokens > 0 && !Number.isNaN(ts) && prevTs !== null && ts > prevTs) {
187
+ const durMs = entry.message.durationMs;
188
+ if (typeof durMs === "number" && Number.isFinite(durMs) && durMs > 0) {
189
+ if (tokens > 0) {
190
+ totalTokens += tokens;
191
+ totalMs += durMs;
192
+ }
193
+ } else if (tokens > 0 && !Number.isNaN(ts) && prevTs !== null && ts > prevTs) {
184
194
  totalTokens += tokens;
185
195
  totalMs += ts - prevTs;
186
196
  }
@@ -356,12 +366,20 @@ export default function (pi: ExtensionAPI) {
356
366
  });
357
367
 
358
368
  pi.on("message_end", async (event) => {
359
- if ((event.message as { role?: string } | undefined)?.role !== "assistant") return;
360
- if (turnStartMs === null) return;
361
- const elapsedMs = Date.now() - turnStartMs;
362
- const tokens = generatedTokens(
363
- (event.message as { usage?: UsageLike }).usage,
364
- );
369
+ const message = event.message as
370
+ | { role?: string; usage?: UsageLike; durationMs?: number }
371
+ | undefined;
372
+ if (message?.role !== "assistant") return;
373
+ // Prefer pi-ai's monotonic durationMs: some streams are delivered in one
374
+ // burst after completion, collapsing the wall-time window between
375
+ // message_start/message_end to near-zero (which would inflate the rate).
376
+ const wallMs = turnStartMs === null ? 0 : Date.now() - turnStartMs;
377
+ const durMs = message.durationMs;
378
+ const elapsedMs =
379
+ typeof durMs === "number" && Number.isFinite(durMs) && durMs > 0
380
+ ? durMs
381
+ : wallMs;
382
+ const tokens = generatedTokens(message.usage);
365
383
  turnStartMs = null;
366
384
  if (tokens > 0 && elapsedMs > 0) {
367
385
  totalTokens += tokens;
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "pi-footer-stats",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Custom pi footer: colored session stats, a tokens/second average, and a context-window progress bar",
5
5
  "license": "MIT",
6
6
  "repository": {
7
7
  "type": "git",
8
- "url": "https://github.com/ssa17/pi-footer-stats.git"
8
+ "url": "git+https://github.com/ssa17/pi-footer-stats.git"
9
9
  },
10
10
  "keywords": [
11
11
  "pi-package",
@@ -15,15 +15,27 @@
15
15
  "stats",
16
16
  "tokens-per-second"
17
17
  ],
18
+ "pi": {
19
+ "extensions": [
20
+ "./extensions/footer-stats.ts"
21
+ ]
22
+ },
23
+ "peerDependencies": {
24
+ "@earendil-works/pi-coding-agent": "*",
25
+ "@earendil-works/pi-tui": "*"
26
+ },
18
27
  "files": [
19
28
  "extensions",
20
29
  "tests",
21
30
  "README.md",
22
31
  "LICENSE",
23
- "CHANGELOG.md"
32
+ "CHANGELOG.md",
33
+ "SECURITY.md",
34
+ "demo.svg"
24
35
  ],
25
36
  "scripts": {
26
37
  "test": "node tests/footer-stats.test.mjs",
27
- "prepublishOnly": "npm test"
38
+ "prepublishOnly": "npm test",
39
+ "release": "node scripts/release.mjs"
28
40
  }
29
- }
41
+ }
@@ -1,18 +1,24 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * Regression tests for the footer-stats extension (~/.pi/agent/extensions/footer-stats.ts).
3
+ * Regression tests for the footer-stats extension.
4
4
  *
5
- * Run: node ~/.pi/agent/tests/footer-stats.test.mjs
5
+ * Run: node tests/footer-stats.test.mjs (from the repo/package root, or via
6
+ * the symlinked copy at ~/.pi/agent/tests/)
6
7
  *
7
- * Loads the extension through pi's own jiti (resolved from install/current-version,
8
- * falling back to the newest release dir) with import aliases for the bare package
9
- * specifiers, then drives it with mock ctx/theme/footerData — no TUI required.
8
+ * The extension is resolved relative to THIS file (../extensions/footer-stats.ts),
9
+ * so the suite works from a git checkout, an npm-installed pi package, or a
10
+ * symlinked agent dir. The pi runtime (jiti + @earendil-works packages) is
11
+ * resolved from: FOOTER_STATS_TEST_MODULES (test hook) → the agent dir's
12
+ * managed install → npm's global root (CI). Import aliases for the bare
13
+ * package specifiers are set up explicitly, then the extension is driven with
14
+ * mock ctx/theme/footerData — no TUI required.
10
15
  * Exits non-zero on any failure so it can gate future edits.
11
16
  */
12
17
 
13
18
  import { readdirSync, existsSync, readFileSync, mkdtempSync, writeFileSync, rmSync, mkdirSync } from "node:fs";
14
19
  import { join } from "node:path";
15
20
  import { homedir, tmpdir } from "node:os";
21
+ import { execSync } from "node:child_process";
16
22
 
17
23
  // The agent dir can be relocated via PI_CODING_AGENT_DIR (--agent-dir sets it
18
24
  // at startup) — respect it so tests work on machines with a custom config
@@ -22,8 +28,27 @@ const AGENT_DIR = process.env.PI_CODING_AGENT_DIR
22
28
  ? expandTilde(process.env.PI_CODING_AGENT_DIR)
23
29
  : join(homedir(), ".pi", "agent");
24
30
 
25
- // --- resolve the active pi install dynamically ---------------------------
26
- function resolvePiModules() {
31
+ // --- resolve the pi runtime (jiti + @earendil-works packages) -------------
32
+ // Dependencies may be hoisted (managed install: everything under one
33
+ // node_modules) or nested (npm-global installs can place jiti inside
34
+ // pi-coding-agent's own node_modules), so resolve each package individually
35
+ // across candidate roots instead of assuming a single modules root.
36
+ function resolvePiRuntime() {
37
+ // Test hook: explicit modules dir wins, strictly (verifies fallback paths).
38
+ if (process.env.FOOTER_STATS_TEST_MODULES) {
39
+ const root = process.env.FOOTER_STATS_TEST_MODULES;
40
+ const jiti = join(root, "jiti");
41
+ const piCodingAgent = join(root, "@earendil-works", "pi-coding-agent");
42
+ const piTui = join(root, "@earendil-works", "pi-tui");
43
+ if (!existsSync(jiti) || !existsSync(piCodingAgent) || !existsSync(piTui))
44
+ throw new Error(`FOOTER_STATS_TEST_MODULES=${root} lacks jiti/@earendil-works packages.`);
45
+ console.log(`Testing against override modules dir (${root})`);
46
+ return { jiti, piCodingAgent, piTui };
47
+ }
48
+
49
+ const roots = [];
50
+
51
+ // Managed install under the agent dir (current-version, newest fallback).
27
52
  const releasesDir = join(AGENT_DIR, "install", "releases");
28
53
  let version = null;
29
54
  try {
@@ -40,29 +65,57 @@ function resolvePiModules() {
40
65
  }
41
66
  version = versions[versions.length - 1] ?? null;
42
67
  }
43
- if (!version) {
68
+ if (version) roots.push(join(releasesDir, version, "node_modules"));
69
+
70
+ // npm-global install (e.g. CI runners: npm i -g @earendil-works/pi-coding-agent).
71
+ let globalRoot = null;
72
+ try {
73
+ const out = execSync("npm root -g", { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
74
+ // npm may emit extra lines (warnings/notices) — the path is the last one.
75
+ globalRoot = out.trim().split("\n").pop().trim();
76
+ } catch {
77
+ // npm unavailable
78
+ }
79
+ if (globalRoot) {
80
+ roots.push(globalRoot);
81
+ roots.push(join(globalRoot, "@earendil-works", "pi-coding-agent", "node_modules"));
82
+ }
83
+
84
+ const find = (rel) => {
85
+ for (const root of roots) {
86
+ const p = join(root, rel);
87
+ if (existsSync(p)) return p;
88
+ }
89
+ return null;
90
+ };
91
+ const jiti = find("jiti");
92
+ const piCodingAgent = find("@earendil-works/pi-coding-agent");
93
+ const piTui = find("@earendil-works/pi-tui");
94
+ if (!jiti || !piCodingAgent || !piTui) {
95
+ const missing = [!jiti && "jiti", !piCodingAgent && "@earendil-works/pi-coding-agent", !piTui && "@earendil-works/pi-tui"].filter(Boolean).join(", ");
44
96
  throw new Error(
45
- `No pi install found under ${AGENT_DIR}/install/releases.\n` +
46
- `These tests need a pi installation; if your pi config lives elsewhere, set PI_CODING_AGENT_DIR.`,
97
+ `No pi install found (checked ${AGENT_DIR}/install/releases and npm global root ${globalRoot ?? "n/a"}).\n` +
98
+ `Missing: ${missing}\n` +
99
+ `These tests need a pi installation: use the managed installer, or\n` +
100
+ ` npm install -g @earendil-works/pi-coding-agent\n` +
101
+ `If your pi config lives elsewhere, set PI_CODING_AGENT_DIR.`,
47
102
  );
48
103
  }
49
- const modules = join(releasesDir, version, "node_modules");
50
- if (!existsSync(join(modules, "jiti"))) {
51
- throw new Error(`pi install at ${modules} is incomplete (missing jiti).`);
52
- }
53
- console.log(`Testing against pi ${version} (${modules})`);
54
- return modules;
104
+ console.log(`Testing against pi runtime: ${piCodingAgent}${version ? ` (${version})` : ""}`);
105
+ return { jiti, piCodingAgent, piTui };
55
106
  }
56
107
 
57
- const MODULES = resolvePiModules();
58
- const { createJiti } = await import(join(MODULES, "jiti", "lib", "jiti.mjs"));
108
+ const runtime = resolvePiRuntime();
109
+ const { createJiti } = await import(join(runtime.jiti, "lib", "jiti.mjs"));
59
110
  const jiti = createJiti(import.meta.url, {
60
111
  alias: {
61
- "@earendil-works/pi-coding-agent": join(MODULES, "@earendil-works", "pi-coding-agent", "dist", "index.js"),
62
- "@earendil-works/pi-tui": join(MODULES, "@earendil-works", "pi-tui", "dist", "index.js"),
112
+ "@earendil-works/pi-coding-agent": join(runtime.piCodingAgent, "dist", "index.js"),
113
+ "@earendil-works/pi-tui": join(runtime.piTui, "dist", "index.js"),
63
114
  },
64
115
  });
65
- const mod = await jiti.import(join(AGENT_DIR, "extensions", "footer-stats.ts"));
116
+ // Resolve the extension relative to THIS file, so the suite works from a git
117
+ // checkout, an npm-installed pi package, or a symlinked agent dir alike.
118
+ const mod = await jiti.import(join(import.meta.dirname, "..", "extensions", "footer-stats.ts"));
66
119
 
67
120
  // --- test scaffolding ------------------------------------------------------
68
121
 
@@ -206,6 +259,126 @@ const rateFrom = (line) => {
206
259
  check("zero-token and aborted-start cases safe", Math.abs(rate - 500) / 500 < 0.3, `got ${rate}, expected ~500`);
207
260
  }
208
261
 
262
+ // --- 5b. durationMs is the primary time source (burst-delivered streams) ---
263
+ {
264
+ const h = makeInstance();
265
+ const { ctx, render } = makeCtx([]);
266
+ await h.session_start[0]({}, ctx);
267
+ h.message_start[0]({ message: { role: "assistant" } });
268
+ await sleep(200);
269
+ // Wall window ≈200ms would give ~500 tok/s; durationMs=1000 must win → ~100.
270
+ h.message_end[0]({ message: { role: "assistant", usage: { output: 100 }, durationMs: 1000 } });
271
+ const rate = parseFloat(rateFrom(render()));
272
+ check("durationMs overrides collapsed wall clock", Math.abs(rate - 100) / 100 < 0.25, `got ${rate}, expected ~100`);
273
+
274
+ // Invalid durationMs falls back to the wall window (started ~now → small).
275
+ h.message_start[0]({ message: { role: "assistant" } });
276
+ await sleep(100);
277
+ h.message_end[0]({ message: { role: "assistant", usage: { output: 50 }, durationMs: 0 } });
278
+ const rate2 = parseFloat(rateFrom(render()));
279
+ check("non-positive durationMs falls back to wall clock", Number.isFinite(rate2) && rate2 > 0, `got ${rate2}`);
280
+ }
281
+
282
+ // --- 5c. seeding prefers durationMs over timestamp gaps ---
283
+ {
284
+ const h = makeInstance();
285
+ // Timestamp gap says 10s (→100 tok/s); durationMs says 5s (→200 tok/s).
286
+ const entries = [
287
+ { type: "message", timestamp: iso(10000), message: { role: "user" } },
288
+ { type: "message", timestamp: iso(0), message: { role: "assistant", usage: { output: 1000 }, durationMs: 5000 } },
289
+ ];
290
+ const { ctx, render } = makeCtx(entries);
291
+ await h.session_start[0]({}, ctx);
292
+ const r = parseFloat(rateFrom(render()));
293
+ check("seeded rate uses durationMs when present", Math.abs(r - 200) <= 2, `got ${r}, expected ~200`);
294
+ }
295
+
296
+ // --- 5d. invalid durationMs values fall back to the wall clock -------------
297
+ // A bad value must never poison the accumulator (Infinity duration would make
298
+ // totalMs permanent-Inf and freeze the rate at —) nor produce a bogus rate.
299
+ {
300
+ const h = makeInstance();
301
+ const { ctx, render } = makeCtx([]);
302
+ await h.session_start[0]({}, ctx);
303
+ const bad = [Number.NaN, Number.POSITIVE_INFINITY, -1000, "1000", null, undefined];
304
+ for (const value of bad) {
305
+ h.message_start[0]({ message: { role: "assistant" } });
306
+ await sleep(50);
307
+ h.message_end[0]({ message: { role: "assistant", usage: { output: 100 }, durationMs: value } });
308
+ const rate = parseFloat(rateFrom(render()));
309
+ check(
310
+ `invalid durationMs ${String(value)} falls back to wall clock`,
311
+ Number.isFinite(rate) && rate > 0,
312
+ `got ${rateFrom(render())}`,
313
+ );
314
+ }
315
+ }
316
+
317
+ // --- 5e. durationMs alone suffices: message_end without message_start ------
318
+ // pi can finalize a message the extension never saw start (buffered burst,
319
+ // missed event ordering); durationMs must still count it.
320
+ {
321
+ const h = makeInstance();
322
+ const { ctx, render } = makeCtx([]);
323
+ await h.session_start[0]({}, ctx);
324
+ h.message_end[0]({ message: { role: "assistant", usage: { output: 200 }, durationMs: 2000 } });
325
+ const rate = parseFloat(rateFrom(render()));
326
+ check("durationMs-only message_end counts (no message_start needed)", Math.abs(rate - 100) / 100 < 0.25, `got ${rate}, expected ~100`);
327
+ }
328
+
329
+ // --- 5f. durationMs on non-assistant messages never affects the accumulator -
330
+ {
331
+ const h = makeInstance();
332
+ const { ctx, render } = makeCtx([]);
333
+ await h.session_start[0]({}, ctx);
334
+ h.message_end[0]({ message: { role: "toolResult", usage: { output: 999 }, durationMs: 5000 } });
335
+ h.message_end[0]({ message: { role: "user", usage: { output: 999 }, durationMs: 5000 } });
336
+ check("non-assistant durationMs ignored", rateFrom(render()) === "—");
337
+ }
338
+
339
+ // --- 5g. mixed seeding: durationMs and timestamp-gap entries combine --------
340
+ // An entry with durationMs must use ONLY that (its ts gap must not double-
341
+ // count); legacy entries without it fall back to the ts gap. 1000 tok / 5000 ms
342
+ // + 500 tok / 5000 ms = 1500 / 10s = 150 tok/s.
343
+ {
344
+ const h = makeInstance();
345
+ const entries = [
346
+ { type: "message", timestamp: iso(20000), message: { role: "user" } },
347
+ { type: "message", timestamp: iso(15000), message: { role: "assistant", usage: { output: 1000 }, durationMs: 5000 } },
348
+ { type: "message", timestamp: iso(10000), message: { role: "assistant", usage: { output: 500 } } },
349
+ ];
350
+ const { ctx, render } = makeCtx(entries);
351
+ await h.session_start[0]({}, ctx);
352
+ const r1 = parseFloat(rateFrom(render()));
353
+ await h.session_start[0]({}, ctx);
354
+ const r2 = parseFloat(rateFrom(render()));
355
+ check("mixed seeding combines durationMs + ts-gap entries", Math.abs(r1 - 150) <= 2, `got ${r1}, expected ~150`);
356
+ check("mixed re-seed is idempotent", r1 === r2, `${r1} vs ${r2}`);
357
+ }
358
+
359
+ // --- 5h. the original omlx failure: every stream burst-delivered ------------
360
+ // Regression fixture for the 449-vs-94 tok/s bug: three assistant messages
361
+ // whose message_start→message_end wall windows are ~0 (the provider delivered
362
+ // each finished stream in one burst), with real durations 4s/1s/5s.
363
+ // Pre-fix behavior: windows ~0ms → tokens dropped or rate wildly inflated.
364
+ // Correct behavior: Σtokens / ΣdurationMs = 1000 / 10s = 100 tok/s.
365
+ {
366
+ const h = makeInstance();
367
+ const { ctx, render } = makeCtx([]);
368
+ await h.session_start[0]({}, ctx);
369
+ const msgs = [
370
+ { output: 400, durationMs: 4000 },
371
+ { output: 100, durationMs: 1000 },
372
+ { output: 500, durationMs: 5000 },
373
+ ];
374
+ for (const m of msgs) {
375
+ h.message_start[0]({ message: { role: "assistant" } });
376
+ h.message_end[0]({ message: { role: "assistant", usage: { output: m.output }, durationMs: m.durationMs } });
377
+ }
378
+ const rate = parseFloat(rateFrom(render()));
379
+ check("burst-delivered session rates from durationMs sum", Math.abs(rate - 100) / 100 < 0.1, `got ${rate}, expected ~100`);
380
+ }
381
+
209
382
  // --- 6. layout: all indicators always present ---
210
383
  {
211
384
  const h = makeInstance();
@@ -274,7 +447,7 @@ const rateFrom = (line) => {
274
447
  const { ctx, render } = makeCtx([]);
275
448
  await h.session_start[0]({}, ctx);
276
449
  const narrow = render(40);
277
- const { visibleWidth } = await import(join(MODULES, "@earendil-works", "pi-tui", "dist", "index.js"));
450
+ const { visibleWidth } = await import(join(runtime.piTui, "dist", "index.js"));
278
451
  check("narrow width truncates without overflow", visibleWidth(narrow) <= 40, `display width ${visibleWidth(narrow)}`);
279
452
  }
280
453