pi-model-router 1.1.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/PI.md ADDED
@@ -0,0 +1,133 @@
1
+ # pi-model-router
2
+
3
+ Route model group names (strategic, tactical, operational, scout) to concrete provider/model pairs. Balance intelligence, cost, and availability automatically.
4
+
5
+ ## Core loop
6
+
7
+ 1. Groups define candidate pool + selection pipeline (`max_gdpval top_k → min_cost`)
8
+ 2. `effectiveCost = (baseCost || 0.01) × subDiscount(0.5) × costMux[provider]`
9
+ 3. On 429: exponential backoff per model (1m→2m→4m→8m→16m→32m→64m→90m cap), immediate failover
10
+ 4. On 4th consecutive 429: `costMux[provider] += 1` (max 1/day, validated, never decays)
11
+ 5. On success: reset model's consecutive hit count
12
+
13
+ ## Files
14
+
15
+ ```
16
+ index.ts ~450 lines. Extension entry point.
17
+ router-config.json Groups, providers, seed metrics.
18
+ .cache/scan-cache.json GDPval (forever), models (24hr), benchmarks, costMux.
19
+ PI.md This file. Design source of truth.
20
+ README.md Quick-start reference.
21
+ ```
22
+
23
+ ## Data flow (passive except set_model_from_group tool)
24
+
25
+ ```
26
+ session_start → load config + cache, background scan
27
+ turn_start → record time + model ref
28
+ turn_end → update throughput/latency EMA, recordSuccess
29
+ tool_result → detect 429 → backoff + costMux at 4th hit
30
+ ```
31
+
32
+ ## Key functions
33
+
34
+ - `resolve(name)` → pipeline sort, filter rate-limited → {selected, candidates}
35
+ - `effCost(ref)` → base × subDiscount × costMux
36
+ - `recordLimit(ref)` → backoff schedule + costMux bump at hit 4
37
+ - `recordOk(ref)` → reset hit count
38
+ - `lookupGdp(id)` → fuzzy match normalized model name against score table
39
+ - `scan()` → scrape GDPval (once forever) + fetch free models (24hr)
40
+
41
+ ## Backoff schedule
42
+
43
+ | Hit | Cooldown | Effect |
44
+ |-----|----------|--------|
45
+ | 1 | 1m | failover |
46
+ | 2 | 2m | |
47
+ | 3 | 4m | |
48
+ | 4 | 8m | **costMux[provider] += 1** |
49
+ | 5-7 | 16-64m | |
50
+ | 8+ | 90m cap | |
51
+
52
+ Guards: max 1 costMux bump/provider/day. Validates provider still hosts model. Never decays.
53
+
54
+ ## Config shape
55
+
56
+ ```jsonc
57
+ {
58
+ "providers": { "<name>": { "billing": "subscription|pay_per_token" } },
59
+ "model_groups": {
60
+ "<name>": {
61
+ "method": "pipeline",
62
+ "pipeline": [{ "method": "max_gdpval", "top_k": N }, { "method": "min_cost", "top_k": 1 }],
63
+ "models": ["provider/model-id", ...],
64
+ "filter_free": false
65
+ }
66
+ },
67
+ "model_metrics": { "<provider/model-id>": { "gdpval": N, "throughput_tps": N, "avg_latency_ms": N } }
68
+ }
69
+ ```
70
+
71
+ ## Footer
72
+
73
+ ```
74
+ {group}/{provider}/{modelId} | int:{gdpval} tps:{tps} | {in}/{out} ${cost} {ctx%} | ⏱{time} | ⌂ {cwd} | ⎇ {branch} | ⛔{N}
75
+ ```
76
+
77
+ Replaces `~/.pi/agent/extensions/custom-footer.ts` (disabled to `.disabled`).
78
+
79
+ ## Tools
80
+
81
+ | Tool | Purpose |
82
+ |------|---------|
83
+ | `set_model_from_group` | Switch session to best model from a group |
84
+ | `resolve_model_group` | Read-only: what would a group resolve to? |
85
+ | `update_model_metrics` | Manual metric override (rarely needed) |
86
+
87
+ ## Key auto-discovery
88
+
89
+ On session_start, the router scans 3 sources for API keys across 24 providers:
90
+
91
+ 1. **Environment variables** — e.g. `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`
92
+ 2. **`~/.pi/agent/auth.json`** — existing pi auth entries (API keys + OAuth)
93
+ 3. **Pass store** — `pass ls` tree, matching patterns like `api/claude/*`, `api/openrouter/*`
94
+
95
+ Discovered keys merge into in-memory `providers.*.keys[]` (config file keys take priority, never overwritten). Each key gets a label: `env:ANTHROPIC_API_KEY`, `auth.json`, `pass:api/claude/oauth-token`, etc.
96
+
97
+ Local providers (ollama, lm-studio) are marked available without keys.
98
+
99
+ ### Supported providers (24)
100
+
101
+ anthropic, openai, google, openrouter, chutes, mistral, groq, cerebras, xai, zai,
102
+ huggingface, kimi-coding, minimax, minimax-cn, opencode, opencode-go, vercel-ai-gateway,
103
+ azure-openai, deepseek, github-copilot, gemini-cli, antigravity, ollama, lm-studio
104
+
105
+ ## Multi-key rotation
106
+
107
+ Providers can have multiple API keys/tokens. On 429, the router tries rotating to the next available key before falling back to model-level backoff.
108
+
109
+ ```jsonc
110
+ "providers": {
111
+ "anthropic": {
112
+ "billing": "subscription",
113
+ "keys": [
114
+ { "key": "!pass show api/claude/token-1", "label": "primary" },
115
+ { "key": "!pass show api/claude/token-2", "label": "backup" }
116
+ ]
117
+ }
118
+ }
119
+ ```
120
+
121
+ Flow on 429:
122
+ 1. Mark current key exhausted (1hr cooldown)
123
+ 2. Try next non-exhausted key → update `~/.pi/agent/auth.json` → continue (no model backoff)
124
+ 3. If all keys exhausted → normal model backoff + costMux
125
+
126
+ Keys support `!pass show` syntax for secret resolution.
127
+
128
+ ## What NOT to add
129
+
130
+ - Token budget tracking (providers don't expose limits)
131
+ - Proactive load balancing (429 is the signal)
132
+ - Auto-switching mid-session (only via explicit tool call)
133
+ - Complex health checks (backoff + costMux is sufficient)
package/README.md ADDED
@@ -0,0 +1,215 @@
1
+ # pi-model-router
2
+
3
+ > Pi extension that routes model group names to concrete provider/model pairs. Balances intelligence (GDPval), cost, and availability automatically.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ # As a pi extension (symlink)
9
+ ln -s ~/pi-model-router ~/.pi/agent/extensions/pi-model-router
10
+
11
+ # Or via npm (coming soon)
12
+ pi install npm:pi-model-router
13
+ ```
14
+
15
+ Then `/reload` in pi.
16
+
17
+ ## How It Works
18
+
19
+ ### Selection Pipeline
20
+
21
+ Each model group defines a **pipeline** of sorting/filtering steps. For example, `strategic` uses:
22
+
23
+ ```
24
+ max_gdpval top_k:2 → min_cost top_k:1
25
+ ```
26
+
27
+ This means: rank all candidates by GDPval (intelligence score), keep the top 2, then pick the cheapest. The result is the smartest affordable model.
28
+
29
+ ### Effective Cost
30
+
31
+ ```
32
+ effectiveCost = (baseCost || 0.01) × subDiscount(0.5) × costMux[provider]
33
+ ```
34
+
35
+ - **baseCost**: per-million-token cost (free models get 0.01 so costMux still differentiates them)
36
+ - **subDiscount**: 0.5× multiplier for subscription providers (sunk cost preference)
37
+ - **costMux**: permanent per-provider multiplier that increases on repeated rate limits
38
+
39
+ ### Auto-Discovery (24 Providers)
40
+
41
+ On startup, the router automatically discovers API keys from three sources:
42
+
43
+ | Source | Example | Label |
44
+ |--------|---------|-------|
45
+ | Environment variables | `ANTHROPIC_API_KEY=sk-...` | `env:ANTHROPIC_API_KEY` |
46
+ | `~/.pi/agent/auth.json` | `{ "anthropic": { "key": "..." } }` | `auth.json` |
47
+ | Pass store (`pass ls`) | `api/claude/oauth-token` | `pass:api/claude/oauth-token` |
48
+
49
+ **Supported providers:** anthropic, openai, google, openrouter, chutes, mistral, groq, cerebras, xai, zai, huggingface, kimi-coding, minimax, minimax-cn, opencode, opencode-go, vercel-ai-gateway, azure-openai, deepseek, github-copilot, gemini-cli, antigravity, ollama, lm-studio
50
+
51
+ Discovered keys merge into the in-memory provider config (config file keys take priority). Local providers (ollama, lm-studio) are detected without keys. Use `/router` to see all discovered providers and their key counts.
52
+
53
+ ### Multi-Key Rotation
54
+
55
+ Providers can have multiple API keys or OAuth tokens. On 429, the router first tries rotating to the next available key — avoiding model-level backoff entirely:
56
+
57
+ ```jsonc
58
+ "providers": {
59
+ "anthropic": {
60
+ "billing": "subscription",
61
+ "keys": [
62
+ { "key": "!pass show api/claude/token-1", "label": "primary" },
63
+ { "key": "!pass show api/claude/token-2", "label": "backup" }
64
+ ]
65
+ }
66
+ }
67
+ ```
68
+
69
+ On rate limit:
70
+ 1. Current key marked exhausted (1hr cooldown)
71
+ 2. Next available key activated → `~/.pi/agent/auth.json` updated → no model backoff needed
72
+ 3. If all keys exhausted → falls through to model-level backoff below
73
+
74
+ Keys support `!pass show <path>` syntax for secret resolution via `pass`.
75
+
76
+ ### Rate Limit Handling
77
+
78
+ On HTTP 429 (after key rotation is exhausted or unavailable), the model enters exponential backoff and the router fails over to the next candidate:
79
+
80
+ | Hit | Cooldown | Side Effect |
81
+ |-----|----------|-------------|
82
+ | 1 | 1 min | Failover only |
83
+ | 2 | 2 min | |
84
+ | 3 | 4 min | |
85
+ | 4 | 8 min | **costMux[provider] += 1** (max 1/day) |
86
+ | 5 | 16 min | |
87
+ | 6 | 32 min | |
88
+ | 7 | 64 min | |
89
+ | 8+ | 90 min | Cap |
90
+
91
+ On success, the consecutive hit count resets. costMux never decays — providers that rate-limit you stay deprioritized permanently.
92
+
93
+ ### Passive Metrics
94
+
95
+ The router passively observes every turn to track:
96
+ - **Throughput** (tokens/sec) — EMA with α=0.3
97
+ - **Latency** (ms) — EMA with α=0.3
98
+ - **GDPval** — scraped from [Artificial Analysis](https://artificialanalysis.ai/evaluations/gdpval-aa) on first run, with hardcoded fallbacks
99
+
100
+ No probes, no health checks. 429 responses are the only signal.
101
+
102
+ ## Model Groups
103
+
104
+ | Group | Pipeline | Pool | Use For |
105
+ |-------|----------|------|---------|
106
+ | **strategic** | `max_gdpval:2 → min_cost:1` | Top models across providers | Critical decisions, architecture |
107
+ | **tactical** | `max_gdpval:4 → min_cost:1` | Wider pool | Planning, coordination |
108
+ | **operational** | `max_gdpval:8 → min_cost:1` | Broad pool | Coding, execution |
109
+ | **scout** | `max_gdpval:16 → min_cost:1` | Free models only | Exploration, recon |
110
+ | **fallback** | `failover` (ordered) | Minimal chain | Last resort |
111
+
112
+ ## Configuration
113
+
114
+ Edit `router-config.json`:
115
+
116
+ ```jsonc
117
+ {
118
+ "providers": {
119
+ "anthropic": { "billing": "subscription" },
120
+ "chutes": { "billing": "subscription" },
121
+ "openrouter": { "billing": "pay_per_token" }
122
+ },
123
+ "model_groups": {
124
+ "strategic": {
125
+ "method": "pipeline",
126
+ "pipeline": [
127
+ { "method": "max_gdpval", "top_k": 2 },
128
+ { "method": "min_cost", "top_k": 1 }
129
+ ],
130
+ "models": ["anthropic/claude-opus-4-6-20250514", "chutes/zai-org/GLM-5-TEE", "..."]
131
+ }
132
+ },
133
+ "model_metrics": {
134
+ "anthropic/claude-opus-4-6-20250514": {
135
+ "gdpval": 1450, "throughput_tps": 80, "avg_latency_ms": 2000
136
+ }
137
+ }
138
+ }
139
+ ```
140
+
141
+ ### Pipeline Methods
142
+
143
+ | Method | Sorts By | Direction |
144
+ |--------|----------|-----------|
145
+ | `max_gdpval` | Intelligence score | Descending |
146
+ | `min_cost` | Effective cost | Ascending |
147
+ | `max_throughput` | Tokens/sec | Descending |
148
+ | `min_latency` | Response time | Ascending |
149
+ | `roundrobin` | Rotating index | — |
150
+ | `failover` | Config order | — |
151
+
152
+ ### Group Options
153
+
154
+ - **`filter_free: true`** — Only consider models with cost_per_m = 0 (used by `scout`)
155
+ - **`top_k`** — Limit candidates at each pipeline step
156
+
157
+ ## Tools
158
+
159
+ The extension registers three tools available to the pi agent:
160
+
161
+ | Tool | Purpose |
162
+ |------|---------|
163
+ | `set_model_from_group` | Resolve group → switch session to best model |
164
+ | `resolve_model_group` | Read-only: preview what a group would resolve to |
165
+ | `update_model_metrics` | Manual metric override (gdpval, tps, latency) |
166
+
167
+ ## Commands
168
+
169
+ | Command | Description |
170
+ |---------|-------------|
171
+ | `/router` | Overview: providers, groups, current selections, rate limits |
172
+ | `/router <group>` | Detailed view of a specific group with ranked candidates |
173
+ | `/router scan` | Re-scrape GDPval scores + refresh free model lists |
174
+ | `/router reload` | Hot-reload config and cache from disk |
175
+
176
+ ## Footer
177
+
178
+ The router replaces the default pi footer with a rich status line:
179
+
180
+ ```
181
+ strategic/anthropic/claude-opus-4-6 | int:1450 tps:80 | 12k/8k $1.43 62% | ⏱14m | ⌂ proj | ⎇ main | ⛔2
182
+ ```
183
+
184
+ Fields: `group/provider/model | intelligence throughput | tokens_in/out cost context% | elapsed | cwd | branch | rate_limited_count`
185
+
186
+ ## Scanning
187
+
188
+ On session start, the router runs a background scan:
189
+ - **GDPval scores**: scraped once (cached forever) from Artificial Analysis
190
+ - **Free models**: fetched from Chutes + OpenRouter APIs (cached 24hr)
191
+ - Builtin GDPval fallbacks for 30+ models ensure routing works offline
192
+
193
+ ## Data Flow
194
+
195
+ ```
196
+ session_start → load config + cache, background scan, set footer
197
+ turn_start → record timestamp + model ref
198
+ turn_end → update throughput/latency EMA, mark success
199
+ tool_result → detect 429 → backoff + costMux at 4th consecutive hit
200
+ ```
201
+
202
+ The router is fully passive — it only acts when `set_model_from_group` is called or a 429 is detected.
203
+
204
+ ## Files
205
+
206
+ | File | Purpose |
207
+ |------|---------|
208
+ | `index.ts` | Extension entry point (~450 lines) |
209
+ | `router-config.json` | Groups, providers, seed metrics |
210
+ | `.cache/scan-cache.json` | GDPval scores, model lists, benchmarks, costMux |
211
+ | `PI.md` | Design document (source of truth) |
212
+
213
+ ## License
214
+
215
+ MIT