@router-for-me/pi-cliproxyapi-provider 1.4.10 → 1.4.12

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/README.md CHANGED
@@ -10,8 +10,8 @@ Pi provider extension that discovers models from [CLIProxyAPI](https://github.co
10
10
  4. Maps the CLIProxyAPI catalog into pi models, including Fast service-tier capability.
11
11
  5. Registers inference against `{root}/backend-api/`.
12
12
  6. Provides `/fast` to toggle OpenAI priority processing for supported models.
13
- 7. In interactive TUI sessions, shows footer elapsed time during runs and a TPS / token usage toast when the agent settles.
14
- 8. Proactively ends over-threshold CLIProxyAPI tool turns so pi can compact and retry before a long tool chain fills the context window.
13
+ 7. Caches the model catalog in `~/.pi/agent/cliproxyapi-models.json`, refreshes it in the background on startup, and provides `/cliproxyapi-refresh` to force a refresh.
14
+ 8. In interactive TUI sessions, shows footer elapsed time during runs and a TPS / token usage toast when the agent settles.
15
15
 
16
16
  ## Install
17
17
 
@@ -59,9 +59,9 @@ Then choose:
59
59
  - base URL — preferred form is host:port, e.g. `http://127.0.0.1:8317`
60
60
  - API key
61
61
 
62
- Final login validation calls `{root}/v1/models?client_version=pi`:
62
+ Final login validation calls `{root}/v1/models?client_version=pi` (this always bypasses the model cache and forces a fresh remote query):
63
63
 
64
- - **HTTP 200** → login succeeds (empty model list is still OK)
64
+ - **HTTP 200** → login succeeds (empty model list is still OK) and the model cache is rewritten
65
65
  - **non-200 / network error** → login fails and you are prompted to re-enter base URL + API key
66
66
 
67
67
  On success:
@@ -84,7 +84,8 @@ You can still configure without `/login`.
84
84
  {
85
85
  "baseUrl": "http://127.0.0.1:8317",
86
86
  "apiKey": "12345",
87
- "fast": false
87
+ "fast": false,
88
+ "pause": false
88
89
  }
89
90
  ```
90
91
 
@@ -97,6 +98,7 @@ Optional fields:
97
98
  | `providerId` | `cliproxyapi` | Provider id shown in `/model` |
98
99
  | `providerName` | `CLIProxyAPI` | Display name in `/login` and UI |
99
100
  | `fast` | `false` | Persisted Fast mode preference; only applies to catalog-supported models |
101
+ | `pause` | `false` | Persisted request-pause preference; provider requests wait until it is cleared |
100
102
 
101
103
  ### Environment overrides
102
104
 
@@ -144,35 +146,53 @@ Each invocation switches Fast between on and off and writes the result to `~/.pi
144
146
 
145
147
  When Fast is effective, pi's model status appends a yellow lowercase `fast`, for example `gpt-5.6-sol • xhigh • fast`. When Fast is off or the selected model is unsupported, the original model status remains unchanged. Supported models do not produce a separate status notification. Running `/fast` with an unsupported model still updates the global preference; enabling it warns that the current model cannot use Fast.
146
148
 
147
- Fast capability is catalog-driven: the plugin considers a CLIProxyAPI model Fast-capable when its `service_tiers` field is a non-empty array. The `additional_speed_tiers` field is ignored. For supported models, Fast injects `service_tier: "priority"`; unsupported models are left unchanged. Fast is independent from pi's reasoning/thinking level.
149
+ Fast capability is catalog-driven: the plugin considers a CLIProxyAPI model Fast-capable when its `service_tiers` field is a non-empty array. The `additional_speed_tiers` field is ignored. For supported models, Fast injects `service_tier: "priority"`; unsupported models are left unchanged. Fast is independent from pi's reasoning/thinking level. When `models.dev` provides `experimental.modes.fast.cost`, the registered model cost switches to those Fast rates as well; the provider is refreshed when `/fast` is toggled. If no Fast price is published, the standard price is retained. The plugin does not guess Fast prices from `-pro`/`-fast` model IDs.
148
150
 
149
- ## Proactive compaction during tool runs
151
+ ## Pausing provider requests
150
152
 
151
- Pi normally checks its automatic compaction threshold after an agent run settles or before the next user prompt. A single agent run can contain many consecutive tool turns, so it may otherwise grow well beyond the configured threshold before pi gets another check opportunity.
153
+ Pause provider requests with:
152
154
 
153
- For CLIProxyAPI models, this package also checks each completed tool turn. It reloads pi's existing merged compaction settings from `~/.pi/agent/settings.json` and the trusted project `.pi/settings.json`. When all of the following are true:
155
+ ```text
156
+ /pause
157
+ ```
154
158
 
155
- - `compaction.enabled` is `true`
156
- - the completed assistant response requested tools
157
- - reported context usage exceeds `contextWindow - compaction.reserveTokens`
159
+ Use `/continue` to clear the pause:
158
160
 
159
- …the package schedules a recognized `context_length_exceeded` error instead of sending the next provider request. Pi's built-in overflow recovery then compacts the session and retries automatically. The current tool batch finishes before this check, so the package does not discard valid tool calls or repeat completed tool operations.
161
+ ```text
162
+ /continue
163
+ ```
160
164
 
161
- No separate CLIProxyAPI setting is required. For example:
165
+ Both commands persist the `pause` boolean in `~/.pi/agent/cliproxyapi.json`. Before every provider request, the extension rereads this setting. When it is `true`, the request waits asynchronously and checks again every 200 ms until `/continue` sets it to `false`. A pause issued during an active run lets that run finish before Elapsed stops; a run that starts while paused excludes its waiting time from Elapsed and TPS.
162
166
 
163
- ```json
164
- {
165
- "compaction": {
166
- "enabled": true,
167
- "reserveTokens": 65536,
168
- "keepRecentTokens": 20000
169
- }
170
- }
171
- ```
167
+ ## Model cache
168
+
169
+ The provider keeps a separate cache file so startup stays fast when CLIProxyAPI is slow or briefly unreachable:
172
170
 
173
- This only adds an earlier check point for the provider registered by this package. Summary generation, retained context, session persistence, and retry execution remain handled by pi.
171
+ `~/.pi/agent/cliproxyapi-models.json`
174
172
 
175
- In the TUI footer, CLIProxyAPI context usage also uses this effective threshold as its denominator. With a `372000` model window and `reserveTokens: 65536`, the footer displays `/306k`; the percentage is recalculated against `306464`, so `100%` corresponds to the proactive compaction threshold rather than the model's absolute limit. Disabling automatic compaction restores the full model window display.
173
+ The cache stores only model metadata and derived endpoint URLs — the model list, Fast-capable IDs, `inferenceBaseUrl`, `modelsUrl`, and a `fetchedAt` timestamp. It **never** stores your API key or other credentials.
174
+
175
+ | Property | Value |
176
+ |----------|-------|
177
+ | Cache file | `~/.pi/agent/cliproxyapi-models.json` |
178
+ | Remote query timeout | 60 seconds |
179
+ | Scope | tied to the current `baseUrl` (a different base URL ignores the existing cache) |
180
+
181
+ ### Startup / resume behavior
182
+
183
+ When the provider loads (including session resume):
184
+
185
+ 1. If a cache exists for the configured `baseUrl`, its models are registered immediately. A remote query to `{root}/v1/models?client_version=pi` then runs in the background; on success, the cache is rewritten and the registered model list is refreshed. If the query fails, the existing cache remains active.
186
+ 2. If no matching cache exists, the remote query runs synchronously. On success, the cache is written and the fetched models are registered. If it fails, startup logs a warning and no models are registered until the proxy responds.
187
+
188
+ Use `/cliproxyapi-refresh` to force an immediate remote refresh of the model catalog.
189
+
190
+ ### Refresh commands
191
+
192
+ - `/cliproxyapi-refresh` — force an immediate remote refresh of the model catalog, rewrite the cache, and update registered models. Use this after adding or removing models on the proxy without restarting pi.
193
+ - `/login CLIProxyAPI` / `/login cliproxyapi` — re-entering credentials always forces a fresh models query and rewrites the cache.
194
+
195
+ Delete `~/.pi/agent/cliproxyapi-models.json` to clear the cache manually.
176
196
 
177
197
  ## Model mapping
178
198
 
@@ -187,7 +207,9 @@ From CPA catalog entry → pi model:
187
207
  | `supported_reasoning_levels[].effort` | `thinkingLevelMap` + `reasoning` |
188
208
  | `visibility: "hide"` | skipped |
189
209
 
190
- Unsupported pi thinking levels are set to `null` so they are hidden in the UI. Cost is reported as zero (proxy pricing is unknown).
210
+ Unsupported pi thinking levels are set to `null` so they are hidden in the UI. When available, prices are matched against canonical model entries in `models.dev`; `cost.tiers[].tier.size` becomes pi's `inputTokensAbove`, including thresholds such as `272000`. The legacy `context_over_200k` field is used only when no explicit tiers are present. Ambiguous reseller prices are not selected arbitrarily and fall back to zero. These are catalog/list prices, not a guarantee of CPA's own markup or billing.
211
+
212
+ The raw `models.dev` response is cached for 24 hours at `~/.pi/agent/tmp/models-dev-cache.json`. A fresh cache avoids the network request; an expired cache is refreshed with a three-second timeout, and stale data is retained if refresh fails. If neither the network nor a previous cache is available, pricing safely falls back to zero. A small explicit alias table covers known CLIProxyAPI variants such as `gemini-pro-agent` → `gemini-3.1-pro-preview`; unknown variants are not guessed.
191
213
 
192
214
  ## Migration from static models.json
193
215
 
@@ -213,7 +235,7 @@ Disable just this helper via `pi config` if you only want the CLIProxyAPI provid
213
235
  - Before setup / without credentials: provider still appears in `/login`; no models are listed yet.
214
236
  - After successful `/login`: models are registered; credentials are stored in `auth.json` and mirrored to `cliproxyapi.json`.
215
237
  - The built-in `/logout` command removes only the matching `auth.json` credential; environment variables and `cliproxyapi.json` are unchanged.
216
- - If a models request returns **HTTP 401** or CPA is unreachable during startup, a warning is logged; reconfigure via `/login CLIProxyAPI` or fix config/env.
238
+ - If a models request returns **HTTP 401** or CPA is unreachable during startup, an existing matching cache remains in use while the background refresh fails. Only when no cache is available is a warning logged; reconfigure via `/login CLIProxyAPI` or fix config/env.
217
239
  - Login final step validates credentials by requesting models:
218
240
  - HTTP 200 (including empty catalog) → credentials are persisted
219
241
  - non-200 / network / invalid baseUrl → nothing is persisted; re-enter baseUrl + API key
@@ -1,9 +1,14 @@
1
1
  import { type ExtensionAPI, type ExtensionContext, FooterComponent } from "@earendil-works/pi-coding-agent";
2
2
  import type { ProactiveCompactionSettings } from "./auto-compact.ts";
3
3
  import type { FastModeController } from "./fast.ts";
4
+ import { type PauseController, pauseController } from "./pause.ts";
4
5
 
5
6
  const FAST_FOOTER_PATCH = Symbol.for("@router-for-me/pi-cliproxyapi-provider/fast-footer-patch");
6
7
  const FAST_REFRESH_STATUS_KEY = "cliproxyapi-fast-refresh";
8
+ // Orange labels: truecolor #ffa500, xterm 214
9
+ const ORANGE_TRUECOLOR = "\x1b[38;2;255;165;0m";
10
+ const ORANGE_256 = "\x1b[38;5;214m";
11
+ const FG_RESET = "\x1b[39m";
7
12
 
8
13
  interface MutableModel {
9
14
  id: string;
@@ -40,6 +45,8 @@ export function formatFastModelStatus(
40
45
  thinkingLevel: string,
41
46
  fastEnabled: boolean,
42
47
  fastLabel = "fast",
48
+ paused = false,
49
+ pausedLabel = "paused",
43
50
  ): string {
44
51
  let status = modelName;
45
52
  if (supportsReasoning) {
@@ -48,9 +55,19 @@ export function formatFastModelStatus(
48
55
  if (fastEnabled) {
49
56
  status += ` • ${fastLabel}`;
50
57
  }
58
+ if (paused) {
59
+ status += ` • ${pausedLabel}`;
60
+ }
51
61
  return status;
52
62
  }
53
63
 
64
+ /** Colorize status labels in orange (distinct from yellow warning/fast). */
65
+ export function formatOrangeLabel(theme: { getColorMode?: () => string } | undefined, text: string): string {
66
+ if (!theme) return text;
67
+ const ansi = theme.getColorMode?.() === "truecolor" ? ORANGE_TRUECOLOR : ORANGE_256;
68
+ return `${ansi}${text}${FG_RESET}`;
69
+ }
70
+
54
71
  function installFooterPatch(controller: FastFooterController): void {
55
72
  const prototype = FooterComponent.prototype as PatchableFooterPrototype;
56
73
  let patchState = prototype[FAST_FOOTER_PATCH];
@@ -79,11 +96,13 @@ function installFooterPatch(controller: FastFooterController): void {
79
96
  const originalId = model.id;
80
97
  const originalReasoning = model.reasoning;
81
98
  const originalContextWindow = model.contextWindow;
82
- if (activeController.isEffectiveFor(model)) {
99
+ const fastEnabled = activeController.isEffectiveFor(model);
100
+ if (fastEnabled || activeController.isPaused()) {
83
101
  model.id = activeController.formatModelStatus(
84
102
  originalId,
85
103
  originalReasoning,
86
104
  session?.state.thinkingLevel ?? "off",
105
+ fastEnabled,
87
106
  );
88
107
  model.reasoning = false;
89
108
  }
@@ -128,6 +147,7 @@ export class FastFooterController {
128
147
  private readonly providerId: string,
129
148
  private readonly fastMode: FastModeController,
130
149
  private readonly resolveCompactionSettings: () => ProactiveCompactionSettings | undefined = () => undefined,
150
+ private readonly pauseMode: PauseController = pauseController,
131
151
  ) {}
132
152
 
133
153
  register(pi: ExtensionAPI): void {
@@ -146,9 +166,19 @@ export class FastFooterController {
146
166
  });
147
167
  }
148
168
 
149
- formatModelStatus(modelName: string, supportsReasoning: boolean, thinkingLevel: string): string {
150
- const fastLabel = this.activeContext?.ui.theme.fg("warning", "fast") ?? "fast";
151
- return formatFastModelStatus(modelName, supportsReasoning, thinkingLevel, true, fastLabel);
169
+ formatModelStatus(modelName: string, supportsReasoning: boolean, thinkingLevel: string, fastEnabled = true): string {
170
+ const theme = this.activeContext?.ui.theme;
171
+ const fastLabel = theme?.fg("warning", "fast") ?? "fast";
172
+ const pausedLabel = formatOrangeLabel(theme, "paused");
173
+ return formatFastModelStatus(
174
+ modelName,
175
+ supportsReasoning,
176
+ thinkingLevel,
177
+ fastEnabled,
178
+ fastLabel,
179
+ this.pauseMode.isEnabled(),
180
+ pausedLabel,
181
+ );
152
182
  }
153
183
 
154
184
  isProviderModel(model: MutableModel): boolean {
@@ -159,6 +189,10 @@ export class FastFooterController {
159
189
  return this.isProviderModel(model) && this.fastMode.isEffectiveFor(model.id);
160
190
  }
161
191
 
192
+ isPaused(): boolean {
193
+ return this.pauseMode.isEnabled();
194
+ }
195
+
162
196
  getDisplayContextWindow(contextWindow: number, autoCompactEnabled: boolean): number {
163
197
  const settings = this.resolveCompactionSettings();
164
198
  if (!autoCompactEnabled || !settings || !Number.isFinite(settings.reserveTokens) || settings.reserveTokens < 0) {