← Catalog

pi-token-speed

Pi extension to measure tokens per second via sliding window.

Extension

Install

Install with PiG

pig install npm:pi-token-speed

Install with Pi

pi install npm:pi-token-speed
Review before installing

Packages run code with your permissions and influence agent behavior. Catalog inclusion is not a security audit. Review the source before installing a third-party package.

Pi manifest JSON

The pi field of package.json.

{
  "extensions": [
    "./src/index.ts"
  ]
}

README

Written by the package's publisher, shown as published in version 0.13.1 (README.md). PiG does not review it.

pi-token-speed

A Pi Coding Agent extension that displays real-time tokens-per-second (TPS) performance metrics in the status bar while the AI is streaming responses.

Features

  • Real-time TPS tracking — measures token throughput as the assistant generates text and thinking content
  • Time-to-first-token (TTFT) — measures latency from user message to the first token being generated
  • Configurable sliding window — adjust the window size to suit your server speed (default: 1s)
  • Color-coded speed indicators — visual feedback based on performance thresholds
  • Configurable update interval — throttle status bar updates to reduce visual flickering
  • Provider-reported counting — opt in to using provider-reported counts (e.g. Anthropic, OpenAI) instead of the extension's own counter
  • Per-provider overrides — different thresholds, display mode, etc. per provider (e.g. anthropic vs openai)
  • Fully configurable — customize display, thresholds and colors via ~/.pi/agent/settings.json

Speed Tiers

TierTPSColor
🟥 Slow0–15#ff4444 (red)
🟨 Medium15–30#ffaa00 (orange)
🟩 Fast30–45#00ff88 (green)
🟦 Blazing45+#44ddff (cyan)

Installation

This package is a Pi extension. Install it with

npm install pi-token-speed

or

pi install https://github.com/gsanhueza/pi-token-speed

Configuration

You can customize the display, speed thresholds and colors by adding a tokenSpeed section to your ~/.pi/agent/settings.json:

{
  "tokenSpeed": {
    "thresholds": {
      "slow": 0,
      "medium": 15,
      "fast": 30,
      "blazing": 45
    },
    "colors": {
      "slow": "#ff4444",
      "medium": "#ffaa00",
      "fast": "#00ff88",
      "blazing": "#44ddff"
    },
    "display": "tps",
    "useProviderTokens": false,
    "countStrategy": "direct",
    "endTpsBehavior": "average",
    "icon": "⚡",
    "prefix": "TPS",
    "slidingWindow": 1000,
    "updateInterval": 0,
    "formatDuration": false,
    "suffixTheme": ""
  }
}

All keys are optional.

Provider Overrides

Different providers stream at very different speeds and report tokens differently. The optional providerOverrides key lets you define per-provider configuration blocks with the exact same schema as the base config, applied whenever the active model's provider matches:

{
  "tokenSpeed": {
    "thresholds": {
      "slow": 0,
      "medium": 15,
      "fast": 30,
      "blazing": 45
    },
    "display": "tps",
    "useProviderTokens": false,
    "countStrategy": "direct",
    "displayColors": {
      "count": "#00ff88",
      "elapsed": "#ffaa00",
      "ttft": "#44ddff"
    },
    "providerOverrides": {
      "anthropic": {
        "thresholds": {
          "slow": 0,
          "medium": 30,
          "fast": 60,
          "blazing": 90
        },
        "display": "ttft",
        "useProviderTokens": true,
        "countStrategy": "estimate"
      }
    }
  }
}

Keys are matched against the model's provider id (e.g. anthropic, openai, google, github-copilot). Override blocks may be partial: any key you omit falls back to the base config, and thresholds/colors merge per-tier (an override specifying only thresholds.fast doesn't wipe the sibling tiers). Invalid keys are dropped with a warning at session start, falling back to base.

Resolution timing per key group:

  • Renderer-side keys (display, icon, thresholds, colors, updateInterval) apply as soon as the provider changes.
  • Engine-side keys (slidingWindow, useProviderTokens, countStrategy, endTpsBehavior) apply at the next stream start, so the current measurement is never skewed mid-stream.

You can also manage overrides interactively with /tps overrides (see Commands).

Configuration Validation

Invalid configuration values are automatically corrected to their defaults. A warning notification is displayed in the Pi status bar at session start listing any corrections made. The slidingWindow value is also clamped between 100ms and 30000ms (30s).

Configuration Options

OptionTypeDefaultDescription
thresholds.slownumber0Minimum TPS threshold ("slow")
thresholds.mediumnumber15TPS above this is "medium"
thresholds.fastnumber30TPS above this is "fast"
thresholds.blazingnumber45TPS above this is "blazing"
colors.slowstring"#ff4444"Color for slow tier
colors.mediumstring"#ffaa00"Color for medium tier
colors.faststring"#00ff88"Color for fast tier
colors.blazingstring"#44ddff"Color for blazing tier
slidingWindownumber1000Sliding window duration in ms
displaytps, ttft, stats, fulltpsDisplay mode (see Display Modes)
useProviderTokensbooleanfalseOpt-in: use provider-reported count instead of the extension one
countStrategyestimate, directdirectToken counting strategy used by the extension's own counter
endTpsBehavioraverage, lastaverageWhat to show after streaming ends
iconstring"⚡"Icon shown before the prefix label in the status bar
prefixstring"TPS"Prefix label shown before the measurement
updateIntervalnumber0Status bar update interval in ms (0 = every delta)
formatDurationbooleanfalseShow elapsed time in human-readable units (see Duration Formatting)
suffixTheme"", "dim", "muted"""Style for uncolored suffix parts (empty, dim, or muted)
displayColorsobject{}Hex colors for the suffix parts (see Display Color Customization)
providerOverridesobject{}Per-provider config overrides (see Provider Overrides)

Interactive Menu

A small interactive menu is available when running /tps in the editor, where you can adjust:

  • Display mode — what to show in the status bar
  • Status icon — choose the icon shown before the prefix label (⚡, 🔥, 💨, 🚀, or none)
  • Status prefix — customize the label before the measurement ("TPS", "Speed", or none)
  • Status update interval — throttle status bar updates (see Status Update Interval)
  • Use provider tokens — use provider-reported counts instead of the extension's counter
  • Count strategy — how the extension counts tokens (estimate or direct)
  • Sliding window — time window for TPS calculation (see Sliding Window)
  • End-of-stream TPS — what to show after streaming ends (average or last)
  • Format duration — show elapsed time in human-readable units (see Duration Formatting)
  • Thresholds — customize the TPS threshold values for each tier (see Threshold Customization)
  • Colors — customize the hex color for each TPS tier (see Color Customization)
  • Display colors — customize the hex color for the suffix parts (count, elapsed, ttft) (see Display Color Customization)
  • Suffix theming — choose how uncolored suffix parts are styled (empty, dim, or muted) (see Suffix Theming)

Per-provider overrides are managed separately via /tps overrides (see Provider Overrides).

Sliding Window

The sliding window determines how many recent tokens are used to calculate TPS. A larger window produces smoother readings at the cost of responsiveness; a smaller window reacts faster but can be noisier. To avoid burst spikes, the time span used in the calculation is clamped to a minimum threshold of 100ms.

Burst & Stall Handling

When a provider buffers output and flushes it all at once, all tokens arrive with the same timestamp. In this case, the TPS calculation extends the time span backward to include the gap since the last token, giving a more representative reading:

20 tokens → 5s stall → 500 tokens flushed

Without this handling, TPS would show 5000 tok/s (500 tokens / 100ms clamp). With it, the reading reflects the actual throughput including the stall period (~100 tok/s).

A legitimate burst spread over time (different timestamps) is not affected — the span uses the actual time between the first and last token in the window.

Server speedRecommended windowWhy
Fast (30+ tok/s)1000 (default)Plenty of tokens in the window — accurate and responsive
Medium (5–30 tok/s)1000–3000Enough tokens for stable readings
Slow (< 5 tok/s)5000–15000Captures more tokens, avoiding spiky or unreliable values

For example, if your server streams at ~1 tok/s, a 10-second window gives ~10 tokens per window — enough for a reasonable calculation:

{
  "tokenSpeed": {
    "slidingWindow": 10000
  }
}

Provider Token Counts

By default, this extension uses its own token counter — the same engine behind countStrategy. As an alternative, you can opt in to using the provider's own reported counts instead:

ValueBehavior
false (default)Use this extension's own counter (controlled by countStrategy)
trueUse the provider's reported counts instead; fall back to countStrategy when not available

The extension's own counter is the default and always available. Enable useProviderTokens: true when your provider reports accurate token counts and you'd prefer to use them instead.

Count Strategy

When useProviderTokens is false (default) or when the provider doesn't report counts, the countStrategy determines how the extension's own counter works:

StrategyBehavior
direct (default)Counts each delta as 1 token
estimateApproximates tokens from delta text

The direct strategy is fast and preserves the original behavior — it counts each streaming delta as 1 token, including toolcall deltas. Use estimate when your server streams in small chunks — it approximates the real token count from the delta text, giving a more meaningful TPS reading.

Note: All assistant tool-call deltas are counted — the model generates every tool's arguments during decoding, so they all consume output tokens. Tool execution time is excluded via the timer-pause mechanism.

Timer Pausing

The extension automatically pauses the TPS timer when a tool call ends, regardless of tool type. This prevents tool execution time from skewing the TPS calculation. The timer resumes when the next token delta arrives.

End-of-Stream TPS Behavior

After streaming ends, the endTpsBehavior option controls what TPS value is displayed:

BehaviorBehavior
average (default)Returns the overall average TPS (total tokens / total elapsed seconds). Consistent with the stats display.
lastReturns the last sliding window TPS measurement from the moment streaming stopped. Useful for seeing how fast the model was streaming at the end.

This is also configurable via the /tps interactive menu.

Color Customization

The four TPS tier colors can be customized via the /tps interactive menu by selecting Colors. Each tier opens a hex color input where you can enter a custom #RRGGBB value.

As you type, the input live-previews the color: once the value forms a complete valid hex string, the text is rendered in that color (and reverts if you delete characters).

Alternatively, you can set colors directly in ~/.pi/agent/settings.json:

{
  "tokenSpeed": {
    "colors": {
      "slow": "#cc3333",
      "medium": "#cc8800",
      "fast": "#00cc66",
      "blazing": "#33bbdd"
    }
  }
}

Display Color Customization

When using a display mode different than tps, the suffix parts (count, elapsed time, and TTFT) can be colorized independently via the /tps interactive menu by selecting Display colors. Each part opens a hex color input where you can enter a custom #RRGGBB value. By default, these parts remain uncolored (opt-in feature).

Alternatively, you can set display colors directly in ~/.pi/agent/settings.json:

{
  "tokenSpeed": {
    "displayColors": {
      "count": "#00ff88",
      "elapsed": "#ffaa00",
      "ttft": "#44ddff"
    }
  }
}

When set, the status bar suffix renders like:

⚡ TPS: 25.0 tok/s (150 tok in 6.0s · TTFT: 450 ms)

where "150 tok" is green, "6.0s" is orange, and "450 ms" is cyan.

Display colors are independent from tier colors — they can be used together for a fully customized status bar.

Suffix Theming

When displayColors is not set (or a part is empty), the suffix renders with the terminal's default foreground color. Set suffixTheme to "dim" or "muted" to style uncolored parts with the active theme instead:

{
  "tokenSpeed": {
    "suffixTheme": "dim"
  }
}

Available values:

  • "" (default) — no styling (terminal default)
  • "dim" — use the theme's dim color
  • "muted" — use the theme's muted color

With suffixTheme set and no displayColors, the entire suffix follows the chosen theme color. With both suffixTheme and displayColors set, colored parts use the specified hex colors while uncolored parts use the chosen theme color.

Suffix theming is independent from display colors and tier colors — they can be used together for a fully customized status bar.

Threshold Customization

The four TPS tier thresholds can be customized via the /tps interactive menu by selecting Thresholds. Each tier opens a numeric input where you can enter a non-negative integer value. Thresholds must be in strict ascending order (slow < medium < fast < blazing); invalid values are rejected with a warning.

Alternatively, you can set thresholds directly in ~/.pi/agent/settings.json:

{
  "tokenSpeed": {
    "thresholds": {
      "slow": 0,
      "medium": 20,
      "fast": 40,
      "blazing": 60
    }
  }
}

Status Update Interval

By default, the status bar updates on every token delta. If you're experiencing visual flickering, you can configure the update interval in milliseconds via the /tps interactive menu (0, 50, 100, 200, 500).

You can also set a custom value in ~/.pi/agent/settings.json:

{
  "tokenSpeed": {
    "updateInterval": 80
  }
}

The TPS calculation continues normally regardless of the update interval — only the status bar rendering is throttled.

Duration Formatting

When formatDuration is enabled, elapsed time in the stats display is formatted into the largest sensible units:

ElapsedWithout formatDurationWith formatDuration
45.67s45.7s45.7s
92.34s92.3s1m 32.3s
7325s7325.0s2h 2m
3d 7h286940.0s3d 7h
0s0.0s0.0s

Formatting rules:

  • < 1min → seconds with 0.1s precision (0.0s, 0.5s, 45.7s)
  • 1min – 1h → minutes (int) + seconds at 0.1s (1m 0.0s, 1m 32.3s)
  • 1h – 1d → hours (int) + minutes (int) (1h 0m, 2h 5m)
  • ≥ 1d → days (int) + hours (int) (1d 0h, 3d 7h)
  • All components down to the smallest unit are shown (trailing zeroes allowed)
  • Sub-second values show as-is with 0.1s precision (0.0s, 0.5s)

Display Modes

ModeDescription
tps⚡ TPS: 25.0 tok/s — TPS with color-coded speed tier
ttft⚡ TPS: 25.0 tok/s (TTFT: 450 ms) — TPS + time-to-first-token
stats⚡ TPS: 25.0 tok/s (150 tok in 6.0s) — TPS + token count and elapsed time
full⚡ TPS: 25.0 tok/s (150 tok in 6.0s · TTFT: 450 ms) — everything

Note: Set icon: "" to hide the icon prefix, rendering just TPS: 25.0 tok/s.

Example: Minimal status bar

With icon: "" and display: "tps", the status bar shows:

TPS: 25.0 tok/s

Custom icons

The /tps command offers ⚡, 🔥, 💨, 🚀 and none. You can also set any custom icon directly in your settings.json:

{
  "tokenSpeed": {
    "icon": "🎯"
  }
}

Commands

CommandDescription
/tpsOpen the settings menu to configure available options.
/tps overridesManage per-provider overrides

The settings menu is described in detail in Interactive Menu. All menus share the same keys:

  • Enter/Space — change the selected value (or open its submenu)
  • r — reset the selected row to its default: a setting, a threshold/color tier, or a provider's whole override block (confirmed before applying)
  • Esc — go back
  • In /tps overrides only: a adds a provider override, d deletes it (after confirmation). Unset fields show (base); resetting a field to (base) removes it from the block

How It Works

  1. Session Start — Renders the initial status bar entry showing the configured icon and prefix label (default: ⚡ TPS: --)
  2. Message Start — When a user message starts, TTFT measurement begins
  3. First Token & Streaming Start — The moment the first content block starts (text_start, thinking_start, or toolcall_start), the TTFT is recorded and the streaming engine starts tracking
  4. Token Update — Each text, thinking, and tool-call delta is recorded. If useProviderTokens is true and the provider reports token counts, those are used directly; otherwise the extension's own counter (controlled by countStrategy) is used
  5. Sliding Window — TPS is calculated using a configurable time window of token timestamps. If all events in the window share the same timestamp (a flush after a stall), the span extends backward to include the gap. When streaming ends, behavior depends on endTpsBehavior:
    • average (default): returns the overall average TPS for consistency with stats.
    • last: returns the last sliding window measurement.
  6. Agent End — The authoritative token count (if available) is used to snap the total, ensuring the final average is exact. Streaming is stopped.

Dependencies

Peer dependencyPurpose
@earendil-works/pi-coding-agentPi Coding Agent SDK
@earendil-works/pi-tuiPi TUI SDK