# pi-stats-insight

Observability extension for [pi](https://github.com/nicepkg/pi-coding-agent): cache hit rate, tool stats, and provider errors — data pi doesn't show in its built-in footer.

## Footer

Adds a compact status line via `ctx.ui.setStatus` (does NOT replace pi's native footer):

```
⚡ cache 80%  🔧 12 tools  ⏱ 0.8s avg  ❌ 2 err
```

| Indicator | Meaning | When shown |
|-----------|---------|------------|
| ⚡/🔋/⚠️ cache | Cache hit rate | ≥80% ⚡, ≥50% 🔋, <50% ⚠️. Hidden if provider doesn't support caching |
| 🔧 tools | Tool call count this session | When >0 |
| ⏱ avg | Average tool response time | When >0 |
| ❌ err | Provider error count (HTTP 4xx/5xx) | When >0 |

**No overlap with pi's built-in footer** — pi already shows token/context usage; we show what it doesn't.

## /stats command

Interactive drill-down via `ctx.ui.select`:

- **Tokens & Cost** — input/output/cacheRead/cacheWrite breakdown + total cost
- **Cache Performance** — hit rate per provider
- **Tools** — per-tool call count, errors, avg duration, result size
- **Context & Compaction** — context window usage + compaction history
- **Latency & Errors** — HTTP error details

`/stats reset` — clear session stats.

## Cache hit rate formula

```
hitRate = cacheRead / (cacheRead + input + cacheWrite)
```

Works across providers because pi normalizes cache metrics:

| Provider | cacheRead source | cacheWrite | input |
|----------|-----------------|------------|-------|
| Anthropic | `cache_read_input_tokens` | `cache_creation_input_tokens` | `input_tokens` |
| OpenAI | `cached_tokens` | 0 | `input_tokens - cached_tokens` |
| Google | `cachedContentTokenCount` | 0 | `promptTokenCount - cached` |
| Mistral | 0 (not exposed) | 0 | all tokens |
| Custom/GLM | 0 | 0 | all tokens |

## Persistence

Session stats are saved to `~/.pi/agent/pi-stats-insight/<session-id>.jsonl` (append-only).

## Install

```bash
pi install npm:pi-stats-insight
```

Or add to `~/.pi/agent/settings.json` packages array:

```json
{ "packages": ["npm:pi-stats-insight"] }
```

## Config

No configuration needed. Zero-intrusion — hooks only, no pi file modifications.

## License

MIT