@router-for-me/pi-cliproxyapi-provider 1.3.0 → 1.4.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/README.md CHANGED
@@ -112,7 +112,7 @@ Optional fields:
112
112
  | `apiKey` | _(required unless set via /login or env)_ | Bearer token / CPA API key |
113
113
  | `providerId` | `cliproxyapi` | Provider id shown in `/model` |
114
114
  | `providerName` | `CLIProxyAPI` | Display name in `/login` and UI |
115
- | `fast` | `false` | Default Fast mode for new sessions; only applies to catalog-supported models |
115
+ | `fast` | `false` | Persisted Fast mode preference; only applies to catalog-supported models |
116
116
 
117
117
  ### Environment overrides
118
118
 
@@ -131,7 +131,7 @@ Resolution order for connection settings:
131
131
  3. `/login` credentials in `auth.json`
132
132
  4. Default baseUrl `http://127.0.0.1:8317`
133
133
 
134
- Fast defaults resolve separately as `CLIPROXYAPI_FAST` → `cliproxyapi.json` → `false`.
134
+ The Fast preference resolves separately as `CLIPROXYAPI_FAST` → `cliproxyapi.json` → `false`.
135
135
 
136
136
  ### baseUrl normalization
137
137
 
@@ -150,15 +150,15 @@ pi then sends inference traffic to `{inference}/codex/responses`.
150
150
 
151
151
  OpenAI Fast mode requests the priority service tier. It can reduce latency for supported models, but consumes more OpenAI/Codex credits or incurs priority-processing pricing.
152
152
 
153
- Fast is **off by default**. Toggle it for the current pi session with:
153
+ Fast is **off by default**. Toggle the global preference with:
154
154
 
155
155
  ```text
156
156
  /fast
157
157
  ```
158
158
 
159
- Each invocation switches Fast between on and off. The setting is stored with the current pi session and restored when that session is resumed; it does not change the global default. To choose the default for new sessions, set `"fast": true` in `cliproxyapi.json` or set `CLIPROXYAPI_FAST=true`.
159
+ Each invocation switches Fast between on and off and writes the result to `~/.pi/agent/cliproxyapi.json`. On the next startup, a persisted `true` value immediately enables Fast for catalog-supported models. Fast remains ineffective for unsupported models, so their requests are left unchanged. If `CLIPROXYAPI_FAST` is set, that environment variable still takes precedence on startup.
160
160
 
161
- 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, the original model status remains unchanged. Supported models do not produce a separate status notification; selecting an unsupported model and running `/fast` shows `This model does not support Fast mode.`
161
+ 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.
162
162
 
163
163
  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.
164
164
 
@@ -206,4 +206,4 @@ Disable just this helper via `pi config` if you only want the CLIProxyAPI provid
206
206
  - HTTP 200 (including empty catalog) → credentials are persisted; setup commands hidden
207
207
  - non-200 / network / invalid baseUrl → nothing is persisted; re-enter baseUrl + API key
208
208
  - If CPA returns HTTP 200 with zero usable models: login still succeeds; re-run setup later after models become available.
209
- - If the selected model does not provide a non-empty `service_tiers` array: the request is left unchanged and `/fast` reports `This model does not support Fast mode.`
209
+ - If the selected model does not provide a non-empty `service_tiers` array: the request is left unchanged; `/fast` still updates the global preference and warns when enabling it.
@@ -1,32 +1,11 @@
1
- export type FastModeSource = "configured-default" | "session-override";
2
-
3
- export const FAST_MODE_ENTRY_TYPE = "cliproxyapi-fast-mode";
4
-
5
- export interface FastModeSessionEntry {
6
- type: string;
7
- customType?: string;
8
- data?: unknown;
9
- }
10
-
11
- /** Session-scoped Fast preference plus the capability set advertised by CPA. */
1
+ /** Global Fast preference plus the capability set advertised by CPA. */
12
2
  export class FastModeController {
13
- private sessionOverride: boolean | undefined;
14
3
  private supportedModelIds = new Set<string>();
15
4
 
16
- constructor(private readonly defaultEnabled: boolean) {}
5
+ constructor(private enabled: boolean) {}
17
6
 
18
- setSessionEnabled(enabled: boolean): void {
19
- this.sessionOverride = enabled;
20
- }
21
-
22
- toggleSessionEnabled(): boolean {
23
- const enabled = !this.isEnabled();
24
- this.setSessionEnabled(enabled);
25
- return enabled;
26
- }
27
-
28
- clearSessionOverride(): void {
29
- this.sessionOverride = undefined;
7
+ setEnabled(enabled: boolean): void {
8
+ this.enabled = enabled;
30
9
  }
31
10
 
32
11
  setSupportedModelIds(modelIds: Iterable<string>): void {
@@ -36,11 +15,7 @@ export class FastModeController {
36
15
  }
37
16
 
38
17
  isEnabled(): boolean {
39
- return this.sessionOverride ?? this.defaultEnabled;
40
- }
41
-
42
- getSource(): FastModeSource {
43
- return this.sessionOverride === undefined ? "configured-default" : "session-override";
18
+ return this.enabled;
44
19
  }
45
20
 
46
21
  isModelSupported(modelId: string): boolean {
@@ -48,22 +23,6 @@ export class FastModeController {
48
23
  }
49
24
 
50
25
  isEffectiveFor(modelId: string): boolean {
51
- return this.isEnabled() && this.isModelSupported(modelId);
52
- }
53
- }
54
-
55
- export function restoreFastModeFromEntries(
56
- fastMode: FastModeController,
57
- entries: Iterable<FastModeSessionEntry>,
58
- ): void {
59
- fastMode.clearSessionOverride();
60
- for (const entry of entries) {
61
- if (entry.type !== "custom" || entry.customType !== FAST_MODE_ENTRY_TYPE) {
62
- continue;
63
- }
64
- const data = entry.data;
65
- if (data && typeof data === "object" && typeof (data as { enabled?: unknown }).enabled === "boolean") {
66
- fastMode.setSessionEnabled((data as { enabled: boolean }).enabled);
67
- }
26
+ return this.enabled && this.isModelSupported(modelId);
68
27
  }
69
28
  }
@@ -11,7 +11,7 @@
11
11
  * (HTTP 200 = success even if the catalog is empty; otherwise re-prompt).
12
12
  * 5. On success, models/credentials are saved and `/cliproxyapi` `/cpa` are hidden.
13
13
  * 6. Setup commands reappear after `/logout` or when a models request returns HTTP 401.
14
- * 7. `/fast` controls catalog-driven priority service tier injection per session.
14
+ * 7. `/fast` globally controls catalog-driven priority service tier injection.
15
15
  *
16
16
  * Uses a patched openai-codex-responses implementation that does not require
17
17
  * extracting chatgpt_account_id from the API key (plain CPA keys work).
@@ -27,7 +27,7 @@ import {
27
27
  getAgentDir,
28
28
  } from "@earendil-works/pi-coding-agent";
29
29
  import { CLIPROXYAPI_CODEX_API, type CliproxyCodexStreamSimple, loadCliproxyCodexStreams } from "./codex-stream.ts";
30
- import { FAST_MODE_ENTRY_TYPE, FastModeController, restoreFastModeFromEntries } from "./fast.ts";
30
+ import { FastModeController } from "./fast.ts";
31
31
  import { FastFooterController } from "./fast-footer.ts";
32
32
  import {
33
33
  CONFIG_FILE_NAME,
@@ -55,6 +55,14 @@ interface SetupCommandsController {
55
55
  isVisible(): boolean;
56
56
  }
57
57
 
58
+ class ConfigPersistenceError extends Error {
59
+ constructor(cause: unknown) {
60
+ const message = cause instanceof Error ? cause.message : String(cause);
61
+ super(`Failed to save ${CONFIG_FILE_NAME}: ${message}`, { cause });
62
+ this.name = "ConfigPersistenceError";
63
+ }
64
+ }
65
+
58
66
  function logWarn(message: string): void {
59
67
  console.warn(`[pi-cliproxyapi-provider] ${message}`);
60
68
  }
@@ -150,14 +158,17 @@ async function configureAndRegister(options: {
150
158
  } = options;
151
159
 
152
160
  const loaded = await loadMappedModels(baseUrlInput, apiKey);
153
- fastMode.setSupportedModelIds(loaded.fastModelIds);
154
161
 
155
- saveConfigFile(agentDir, {
156
- baseUrl: baseUrlInput,
157
- apiKey,
158
- providerId,
159
- providerName,
160
- });
162
+ try {
163
+ saveConfigFile(agentDir, {
164
+ baseUrl: baseUrlInput,
165
+ apiKey,
166
+ providerId,
167
+ providerName,
168
+ });
169
+ } catch (error) {
170
+ throw new ConfigPersistenceError(error);
171
+ }
161
172
 
162
173
  registerProvider(pi, {
163
174
  providerId,
@@ -171,6 +182,7 @@ async function configureAndRegister(options: {
171
182
  setupCommands,
172
183
  fastMode,
173
184
  });
185
+ fastMode.setSupportedModelIds(loaded.fastModelIds);
174
186
 
175
187
  // Login succeeded — hide dedicated setup commands from the slash menu.
176
188
  setupCommands.hide();
@@ -223,6 +235,10 @@ function createOAuthHandlers(options: {
223
235
  } catch (error) {
224
236
  const message = error instanceof Error ? error.message : String(error);
225
237
  logWarn(`login validation failed: ${message}`);
238
+ if (error instanceof ConfigPersistenceError) {
239
+ callbacks.onProgress?.(message);
240
+ throw error;
241
+ }
226
242
  // Auth failures should keep setup commands available for reconfiguration.
227
243
  if (isUnauthorizedModelsError(error)) {
228
244
  setupCommands.show();
@@ -446,6 +462,10 @@ function createSetupCommandsController(options: {
446
462
  } catch (error) {
447
463
  const message = error instanceof Error ? error.message : String(error);
448
464
  logWarn(`command setup failed: ${message}`);
465
+ if (error instanceof ConfigPersistenceError) {
466
+ ctx.ui.notify(message, "error");
467
+ return;
468
+ }
449
469
  if (isUnauthorizedModelsError(error)) {
450
470
  setupCommands.show();
451
471
  }
@@ -563,37 +583,40 @@ function createSetupCommandsController(options: {
563
583
 
564
584
  export function registerFastCommand(options: {
565
585
  pi: ExtensionAPI;
586
+ agentDir: string;
566
587
  providerId: string;
567
588
  fastMode: FastModeController;
568
589
  onStatusChange?: (ctx: ExtensionContext) => void;
569
590
  }): void {
570
- const { pi, providerId, fastMode, onStatusChange } = options;
571
-
572
- pi.on("session_start", (_event, ctx) => {
573
- restoreFastModeFromEntries(fastMode, ctx.sessionManager.getBranch());
574
- });
575
- pi.on("session_tree", (_event, ctx) => {
576
- restoreFastModeFromEntries(fastMode, ctx.sessionManager.getBranch());
577
- onStatusChange?.(ctx);
578
- });
591
+ const { pi, agentDir, providerId, fastMode, onStatusChange } = options;
579
592
 
580
593
  pi.registerCommand("fast", {
581
- description: "Toggle CLIProxyAPI Fast mode for this session.",
594
+ description: "Toggle CLIProxyAPI Fast mode globally.",
582
595
  handler: async (args, ctx) => {
583
596
  if (args.trim()) {
584
597
  ctx.ui.notify("Usage: /fast", "error");
585
598
  return;
586
599
  }
587
600
 
588
- const currentModel = ctx.model;
589
- if (!currentModel || currentModel.provider !== providerId || !fastMode.isModelSupported(currentModel.id)) {
590
- ctx.ui.notify("This model does not support Fast mode.", "warning");
601
+ const enabled = !fastMode.isEnabled();
602
+ try {
603
+ saveConfigFile(agentDir, { fast: enabled });
604
+ } catch (error) {
605
+ const message = error instanceof Error ? error.message : String(error);
606
+ ctx.ui.notify(`Failed to save Fast mode: ${message}`, "error");
591
607
  return;
592
608
  }
593
-
594
- const enabled = fastMode.toggleSessionEnabled();
595
- pi.appendEntry(FAST_MODE_ENTRY_TYPE, { enabled });
609
+ fastMode.setEnabled(enabled);
596
610
  onStatusChange?.(ctx);
611
+
612
+ const currentModel = ctx.model;
613
+ if (!currentModel || currentModel.provider !== providerId || !fastMode.isModelSupported(currentModel.id)) {
614
+ if (enabled) {
615
+ ctx.ui.notify("Fast mode is enabled globally, but the current model does not support it.", "warning");
616
+ } else {
617
+ ctx.ui.notify("Fast mode is disabled globally.", "info");
618
+ }
619
+ }
597
620
  },
598
621
  });
599
622
  }
@@ -606,14 +629,14 @@ export default async function (pi: ExtensionAPI): Promise<void> {
606
629
  const identity = resolveIdentity(agentDir);
607
630
  const defaultBaseUrl = resolveDefaultBaseUrl(agentDir, identity.providerId);
608
631
 
609
- let fastDefault = false;
632
+ let fastEnabled = false;
610
633
  try {
611
- fastDefault = resolveFastDefault(agentDir);
634
+ fastEnabled = resolveFastDefault(agentDir);
612
635
  } catch (error) {
613
636
  const message = error instanceof Error ? error.message : String(error);
614
637
  logWarn(`invalid Fast configuration (${message}); using fast=false`);
615
638
  }
616
- const fastMode = new FastModeController(fastDefault);
639
+ const fastMode = new FastModeController(fastEnabled);
617
640
 
618
641
  let streamSimple: CliproxyCodexStreamSimple;
619
642
  try {
@@ -630,6 +653,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
630
653
  const fastFooter = new FastFooterController(identity.providerId, fastMode);
631
654
  registerFastCommand({
632
655
  pi,
656
+ agentDir,
633
657
  providerId: identity.providerId,
634
658
  fastMode,
635
659
  onStatusChange: (ctx) => fastFooter.refresh(ctx),
package/extensions/lib.ts CHANGED
@@ -172,8 +172,11 @@ export function loadConfigFile(agentDir: string): CliproxyConfigFile {
172
172
  const configPath = join(agentDir, CONFIG_FILE_NAME);
173
173
  try {
174
174
  const raw = readFileSync(configPath, "utf8");
175
- const parsed = JSON.parse(raw) as CliproxyConfigFile;
176
- return parsed && typeof parsed === "object" ? parsed : {};
175
+ const parsed: unknown = JSON.parse(raw);
176
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
177
+ throw new Error(`${CONFIG_FILE_NAME} must contain a JSON object`);
178
+ }
179
+ return parsed as CliproxyConfigFile;
177
180
  } catch (error) {
178
181
  const err = error as NodeJS.ErrnoException;
179
182
  if (err.code !== "ENOENT") {
@@ -187,13 +190,7 @@ export function saveConfigFile(agentDir: string, config: CliproxyConfigFile): vo
187
190
  const configPath = join(agentDir, CONFIG_FILE_NAME);
188
191
  mkdirSync(dirname(configPath), { recursive: true });
189
192
 
190
- let existing: CliproxyConfigFile = {};
191
- try {
192
- existing = loadConfigFile(agentDir);
193
- } catch {
194
- existing = {};
195
- }
196
-
193
+ const existing = loadConfigFile(agentDir);
197
194
  const next: CliproxyConfigFile = {
198
195
  ...existing,
199
196
  ...config,
@@ -262,7 +259,7 @@ export function parseBooleanSetting(value: string): boolean | undefined {
262
259
  }
263
260
  }
264
261
 
265
- /** Resolve the Fast default from env, then cliproxyapi.json, then false. */
262
+ /** Resolve the Fast preference from env, then cliproxyapi.json, then false. */
266
263
  export function resolveFastDefault(agentDir: string): boolean {
267
264
  const envValue = firstNonEmpty(process.env.CLIPROXYAPI_FAST);
268
265
  if (envValue !== undefined) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@router-for-me/pi-cliproxyapi-provider",
3
- "version": "1.3.0",
3
+ "version": "1.4.0",
4
4
  "description": "Pi provider extension that auto-registers CLIProxyAPI models, plus TUI elapsed/TPS status",
5
5
  "type": "module",
6
6
  "keywords": [