@router-for-me/pi-cliproxyapi-provider 1.3.0 → 1.4.1

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
@@ -4,7 +4,7 @@ Pi provider extension that discovers models from [CLIProxyAPI](https://github.co
4
4
 
5
5
  ## What it does
6
6
 
7
- 1. Registers a provider that always appears in `/login` (subscription path) and via `/cliproxyapi` / `/cpa`.
7
+ 1. Registers a provider that always appears in `/login` (account sign-in path) and via `/cliproxyapi`.
8
8
  2. Interactive setup collects `baseUrl` + `apiKey`.
9
9
  3. Fetches `{root}/v1/models?client_version=pi`.
10
10
  4. Maps the CLIProxyAPI catalog into pi models, including Fast service-tier capability.
@@ -27,26 +27,15 @@ pi -e /absolute/path/to/pi-cliproxyapi-provider
27
27
 
28
28
  ## Login-style setup (recommended)
29
29
 
30
- This plugin needs both **baseUrl** and **apiKey**. pi's built-in `/login` only supports multi-field prompts on the OAuth/subscription path, so CLIProxyAPI appears under **Use a subscription** (not API key).
30
+ This plugin needs both **baseUrl** and **apiKey**. pi's built-in `/login` only supports multi-field prompts on the account/OAuth path, so CLIProxyAPI appears under **Sign in with an account** (not API key).
31
31
 
32
- ### Preferred: dedicated command (when not yet authenticated)
32
+ ### Preferred: dedicated command
33
33
 
34
34
  ```text
35
35
  /cliproxyapi
36
36
  ```
37
37
 
38
- or short alias:
39
-
40
- ```text
41
- /cpa
42
- ```
43
-
44
- These slash commands appear only when setup is needed. After a successful login they are **hidden** from the `/` menu. They reappear when:
45
-
46
- - you run `/logout` and remove CLIProxyAPI credentials
47
- - a models request returns **HTTP 401**
48
-
49
- To reconfigure while still authenticated, use `/login CLIProxyAPI`.
38
+ This slash command remains available so the connection can be reconfigured at any time. If the provider currently has credentials saved by `/login`, use `/login CLIProxyAPI` to replace them, or run `/logout` before using a dedicated command. This avoids reporting a successful reconfiguration while pi is still prioritizing the stored login credential.
50
39
 
51
40
  ### Or use /login shortcuts (skip the menu)
52
41
 
@@ -68,7 +57,7 @@ or:
68
57
 
69
58
  Then choose:
70
59
 
71
- 1. **Use a subscription**
60
+ 1. **Sign in with an account**
72
61
  (required for multi-field baseUrl + API key prompts)
73
62
  2. **CLIProxyAPI**
74
63
  3. Enter:
@@ -83,10 +72,10 @@ Final login validation calls `{root}/v1/models?client_version=pi`:
83
72
  On success (any of the paths above):
84
73
 
85
74
  - models are registered immediately in the current session (0 models is allowed)
86
- - credentials are stored in `~/.pi/agent/auth.json`
87
- - `baseUrl` / `apiKey` are also written to `~/.pi/agent/cliproxyapi.json`
75
+ - `baseUrl` / `apiKey` are written to `~/.pi/agent/cliproxyapi.json`
76
+ - when using `/login`, pi also stores the returned credential in `~/.pi/agent/auth.json`
88
77
 
89
- Re-run `/cliproxyapi`, `/cpa`, or `/login CLIProxyAPI` anytime to reconfigure.
78
+ Re-run `/cliproxyapi` or `/login CLIProxyAPI` anytime to reconfigure. Dedicated commands require any existing `/login` credential to be removed first. The built-in `/logout` command only removes credentials saved in `auth.json`; it does not erase `cliproxyapi.json`. Remove or update that file if you also need to clear the provider configuration.
90
79
 
91
80
  ## Non-interactive configuration
92
81
 
@@ -112,7 +101,7 @@ Optional fields:
112
101
  | `apiKey` | _(required unless set via /login or env)_ | Bearer token / CPA API key |
113
102
  | `providerId` | `cliproxyapi` | Provider id shown in `/model` |
114
103
  | `providerName` | `CLIProxyAPI` | Display name in `/login` and UI |
115
- | `fast` | `false` | Default Fast mode for new sessions; only applies to catalog-supported models |
104
+ | `fast` | `false` | Persisted Fast mode preference; only applies to catalog-supported models |
116
105
 
117
106
  ### Environment overrides
118
107
 
@@ -131,7 +120,7 @@ Resolution order for connection settings:
131
120
  3. `/login` credentials in `auth.json`
132
121
  4. Default baseUrl `http://127.0.0.1:8317`
133
122
 
134
- Fast defaults resolve separately as `CLIPROXYAPI_FAST` → `cliproxyapi.json` → `false`.
123
+ The Fast preference resolves separately as `CLIPROXYAPI_FAST` → `cliproxyapi.json` → `false`.
135
124
 
136
125
  ### baseUrl normalization
137
126
 
@@ -150,15 +139,15 @@ pi then sends inference traffic to `{inference}/codex/responses`.
150
139
 
151
140
  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
141
 
153
- Fast is **off by default**. Toggle it for the current pi session with:
142
+ Fast is **off by default**. Toggle the global preference with:
154
143
 
155
144
  ```text
156
145
  /fast
157
146
  ```
158
147
 
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`.
148
+ 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
149
 
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.`
150
+ 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
151
 
163
152
  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
153
 
@@ -197,13 +186,14 @@ Disable just this helper via `pi config` if you only want the CLIProxyAPI provid
197
186
 
198
187
  ## Failure behavior
199
188
 
200
- - Before setup / without credentials: provider still appears in `/login`; `/cliproxyapi` and `/cpa` are shown; no models are listed yet.
201
- - After successful login: `/cliproxyapi` and `/cpa` are hidden; reconfigure via `/login CLIProxyAPI` if needed.
202
- - After `/logout` for CLIProxyAPI: setup commands reappear for reconfiguration.
203
- - If a models request returns **HTTP 401**: setup commands reappear for reconfiguration.
204
- - If CPA is unreachable during startup (non-401): a warning is logged; setup commands stay available via `/cliproxyapi` or `/login`.
189
+ - Before setup / without credentials: provider still appears in `/login`; `/cliproxyapi` is shown; no models are listed yet.
190
+ - After successful login or setup: `/cliproxyapi` remains available for reconfiguration.
191
+ - If an `auth.json` credential exists, the dedicated command asks you to use `/login CLIProxyAPI` or run `/logout` first so the old credential cannot override the new key.
192
+ - The built-in `/logout` command removes only the matching `auth.json` credential; environment variables and `cliproxyapi.json` are unchanged.
193
+ - If a models request returns **HTTP 401**, the setup command remains available for reconfiguration.
194
+ - If CPA is unreachable during startup (non-401), a warning is logged; the setup command remains available via `/cliproxyapi` or `/login`.
205
195
  - Login/setup final step validates credentials by requesting models:
206
- - HTTP 200 (including empty catalog) → credentials are persisted; setup commands hidden
196
+ - HTTP 200 (including empty catalog) → credentials are persisted; the setup command remains available
207
197
  - non-200 / network / invalid baseUrl → nothing is persisted; re-enter baseUrl + API key
208
198
  - 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.`
199
+ - 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.
@@ -131,6 +131,9 @@ function patchCodexSource(source: string, providerIds: string[]): string {
131
131
  // Keep assistant message api metadata aligned with the registered custom api id.
132
132
  src = src.replaceAll(`api: "openai-codex-responses"`, `api: ${JSON.stringify(CLIPROXYAPI_CODEX_API)}`);
133
133
 
134
+ // The generated module lives outside the original source map directory.
135
+ src = src.replace(/^\/\/# sourceMappingURL=.*$/gm, "");
136
+
134
137
  return src;
135
138
  }
136
139
 
@@ -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
  }
@@ -1,17 +1,16 @@
1
1
  /**
2
2
  * CLIProxyAPI dynamic model provider for pi.
3
3
  *
4
- * Supports login-style setup via `/login` and dedicated commands:
5
- * 1. Provider always appears under "Use a subscription" as CLIProxyAPI
6
- * (pi only supports multi-field prompts on the oauth/subscription path).
4
+ * Supports login-style setup via `/login` and a dedicated command:
5
+ * 1. Provider always appears under "Sign in with an account" as CLIProxyAPI
6
+ * (pi only supports multi-field prompts on the account/OAuth path).
7
7
  * 2. Preferred shortcuts: `/login CLIProxyAPI`, `/login cliproxyapi`,
8
- * or dedicated commands `/cliproxyapi` / `/cpa` (shown only when not authenticated).
8
+ * or the dedicated `/cliproxyapi` command.
9
9
  * 3. Setup prompts for baseUrl + apiKey.
10
10
  * 4. Final login step validates credentials via /v1/models?client_version=pi
11
11
  * (HTTP 200 = success even if the catalog is empty; otherwise re-prompt).
12
- * 5. On success, models/credentials are saved and `/cliproxyapi` `/cpa` are hidden.
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.
12
+ * 5. On success, models/credentials are saved and registered immediately.
13
+ * 6. `/fast` globally controls catalog-driven priority service tier injection.
15
14
  *
16
15
  * Uses a patched openai-codex-responses implementation that does not require
17
16
  * extracting chatgpt_account_id from the API key (plain CPA keys work).
@@ -27,7 +26,7 @@ import {
27
26
  getAgentDir,
28
27
  } from "@earendil-works/pi-coding-agent";
29
28
  import { CLIPROXYAPI_CODEX_API, type CliproxyCodexStreamSimple, loadCliproxyCodexStreams } from "./codex-stream.ts";
30
- import { FAST_MODE_ENTRY_TYPE, FastModeController, restoreFastModeFromEntries } from "./fast.ts";
29
+ import { FastModeController } from "./fast.ts";
31
30
  import { FastFooterController } from "./fast-footer.ts";
32
31
  import {
33
32
  CONFIG_FILE_NAME,
@@ -48,11 +47,17 @@ import {
48
47
  saveConfigFile,
49
48
  } from "./lib.ts";
50
49
 
51
- /** Controls visibility of /cliproxyapi and /cpa in the slash-command menu. */
50
+ /** Registers /cliproxyapi in the slash-command menu. */
52
51
  interface SetupCommandsController {
53
52
  show(): void;
54
- hide(): void;
55
- isVisible(): boolean;
53
+ }
54
+
55
+ class ConfigPersistenceError extends Error {
56
+ constructor(cause: unknown) {
57
+ const message = cause instanceof Error ? cause.message : String(cause);
58
+ super(`Failed to save ${CONFIG_FILE_NAME}: ${message}`, { cause });
59
+ this.name = "ConfigPersistenceError";
60
+ }
56
61
  }
57
62
 
58
63
  function logWarn(message: string): void {
@@ -150,14 +155,17 @@ async function configureAndRegister(options: {
150
155
  } = options;
151
156
 
152
157
  const loaded = await loadMappedModels(baseUrlInput, apiKey);
153
- fastMode.setSupportedModelIds(loaded.fastModelIds);
154
158
 
155
- saveConfigFile(agentDir, {
156
- baseUrl: baseUrlInput,
157
- apiKey,
158
- providerId,
159
- providerName,
160
- });
159
+ try {
160
+ saveConfigFile(agentDir, {
161
+ baseUrl: baseUrlInput,
162
+ apiKey,
163
+ providerId,
164
+ providerName,
165
+ });
166
+ } catch (error) {
167
+ throw new ConfigPersistenceError(error);
168
+ }
161
169
 
162
170
  registerProvider(pi, {
163
171
  providerId,
@@ -171,9 +179,7 @@ async function configureAndRegister(options: {
171
179
  setupCommands,
172
180
  fastMode,
173
181
  });
174
-
175
- // Login succeeded — hide dedicated setup commands from the slash menu.
176
- setupCommands.hide();
182
+ fastMode.setSupportedModelIds(loaded.fastModelIds);
177
183
 
178
184
  return { modelCount: loaded.models.length, modelsUrl: loaded.modelsUrl };
179
185
  }
@@ -223,7 +229,11 @@ function createOAuthHandlers(options: {
223
229
  } catch (error) {
224
230
  const message = error instanceof Error ? error.message : String(error);
225
231
  logWarn(`login validation failed: ${message}`);
226
- // Auth failures should keep setup commands available for reconfiguration.
232
+ if (error instanceof ConfigPersistenceError) {
233
+ callbacks.onProgress?.(message);
234
+ throw error;
235
+ }
236
+ // Auth failures should keep the setup command available for reconfiguration.
227
237
  if (isUnauthorizedModelsError(error)) {
228
238
  setupCommands.show();
229
239
  }
@@ -316,40 +326,7 @@ function registerProvider(
316
326
  });
317
327
  }
318
328
 
319
- const SETUP_COMMAND_NAMES = ["cliproxyapi", "cpa"] as const;
320
-
321
- /** Avoid double-wrapping the same AuthStorage instance across session reloads. */
322
- const logoutWatchedStorages = new WeakSet<object>();
323
-
324
- /**
325
- * pi has no logout extension event. Wrap authStorage.logout so we can re-show
326
- * setup commands when this provider is removed via /logout.
327
- */
328
- function watchProviderLogout(
329
- authStorage: { logout(provider: string): void },
330
- providerId: string,
331
- onLogout: () => void,
332
- ): void {
333
- if (logoutWatchedStorages.has(authStorage as object)) {
334
- return;
335
- }
336
- logoutWatchedStorages.add(authStorage as object);
337
-
338
- const originalLogout = authStorage.logout.bind(authStorage);
339
- authStorage.logout = (provider: string): void => {
340
- originalLogout(provider);
341
- if (provider === providerId) {
342
- onLogout();
343
- }
344
- };
345
- }
346
-
347
- /**
348
- * Show/hide /cliproxyapi and /cpa.
349
- *
350
- * pi has registerCommand but no unregisterCommand, so hide() removes entries from the
351
- * extension's internal commands Map captured during the first registration.
352
- */
329
+ /** Register the always-available /cliproxyapi setup command. */
353
330
  function createSetupCommandsController(options: {
354
331
  pi: ExtensionAPI;
355
332
  agentDir: string;
@@ -361,22 +338,14 @@ function createSetupCommandsController(options: {
361
338
  }): SetupCommandsController {
362
339
  const { pi, agentDir, providerId, providerName, defaultBaseUrl, streamSimple, fastMode } = options;
363
340
 
364
- // Self-referential controller so handlers can hide/show after validation.
341
+ // Self-referential controller so validation failures can ensure commands are registered.
365
342
  const setupCommands: SetupCommandsController = {
366
343
  show() {
367
344
  /* replaced below */
368
345
  },
369
- hide() {
370
- /* replaced below */
371
- },
372
- isVisible() {
373
- return false;
374
- },
375
346
  };
376
347
 
377
348
  let visible = false;
378
- // Captured extension.commands Map (pi has no public unregisterCommand API).
379
- let commandMap: Map<string, unknown> | null = null;
380
349
 
381
350
  const handler = async (_args: string, ctx: ExtensionCommandContext): Promise<void> => {
382
351
  if (!ctx.hasUI) {
@@ -387,6 +356,14 @@ function createSetupCommandsController(options: {
387
356
  return;
388
357
  }
389
358
 
359
+ if (loadAuthConnection(agentDir, providerId)?.apiKey) {
360
+ ctx.ui.notify(
361
+ `CLIProxyAPI credentials are already stored by /login. Use /login ${providerName} to replace them, or run /logout before /cliproxyapi.`,
362
+ "error",
363
+ );
364
+ return;
365
+ }
366
+
390
367
  const promptDefaultBaseUrl = resolveDefaultBaseUrl(agentDir, providerId) || defaultBaseUrl;
391
368
 
392
369
  const baseUrlRaw = await ctx.ui.input(`CLIProxyAPI base URL [${promptDefaultBaseUrl}]:`, promptDefaultBaseUrl);
@@ -434,18 +411,16 @@ function createSetupCommandsController(options: {
434
411
  fastMode,
435
412
  });
436
413
 
437
- // Persist only after successful validation; keep AuthStorage in-memory too.
438
- ctx.modelRegistry.authStorage.set(providerId, {
439
- type: "oauth",
440
- ...buildOAuthCredentials(currentBaseUrl, currentApiKey),
441
- });
442
-
443
414
  logInfo(`command setup ok: registered ${result.modelCount} models from ${result.modelsUrl}`);
444
415
  ctx.ui.notify(`CLIProxyAPI configured: ${result.modelCount} models from ${result.modelsUrl}`, "info");
445
416
  return;
446
417
  } catch (error) {
447
418
  const message = error instanceof Error ? error.message : String(error);
448
419
  logWarn(`command setup failed: ${message}`);
420
+ if (error instanceof ConfigPersistenceError) {
421
+ ctx.ui.notify(message, "error");
422
+ return;
423
+ }
449
424
  if (isUnauthorizedModelsError(error)) {
450
425
  setupCommands.show();
451
426
  }
@@ -486,114 +461,61 @@ function createSetupCommandsController(options: {
486
461
  }
487
462
  };
488
463
 
489
- const commandSpecs: Array<{ name: (typeof SETUP_COMMAND_NAMES)[number]; description: string }> = [
490
- {
491
- name: "cliproxyapi",
464
+ const registerCommand = (): void => {
465
+ pi.registerCommand("cliproxyapi", {
492
466
  description: "Configure CLIProxyAPI (baseUrl + API key) and load models. Prefer this or /login CLIProxyAPI.",
493
- },
494
- {
495
- name: "cpa",
496
- description: "Alias for /cliproxyapi — configure CLIProxyAPI and load models.",
497
- },
498
- ];
499
-
500
- const registerAll = (): void => {
501
- for (const spec of commandSpecs) {
502
- pi.registerCommand(spec.name, {
503
- description: spec.description,
504
- handler,
505
- });
506
- }
467
+ handler,
468
+ });
507
469
  };
508
470
 
509
471
  setupCommands.show = (): void => {
510
472
  if (visible) {
511
473
  return;
512
474
  }
513
-
514
- if (!commandMap) {
515
- // Capture the extension.commands Map during first registration.
516
- const originalSet = Map.prototype.set;
517
- Map.prototype.set = function setWithCapture(this: Map<unknown, unknown>, key: unknown, value: unknown) {
518
- if (
519
- key === "cliproxyapi" &&
520
- value &&
521
- typeof value === "object" &&
522
- "handler" in (value as Record<string, unknown>)
523
- ) {
524
- commandMap = this as Map<string, unknown>;
525
- }
526
- return originalSet.call(this, key, value);
527
- } as typeof Map.prototype.set;
528
- try {
529
- registerAll();
530
- } finally {
531
- Map.prototype.set = originalSet;
532
- }
533
- if (!commandMap) {
534
- logWarn("could not capture command map; /cliproxyapi and /cpa cannot be hidden after login");
535
- }
536
- } else {
537
- registerAll();
538
- }
539
-
475
+ registerCommand();
540
476
  visible = true;
541
- logInfo("setup commands shown: /cliproxyapi, /cpa");
542
- };
543
-
544
- setupCommands.hide = (): void => {
545
- if (!visible) {
546
- return;
547
- }
548
- if (!commandMap) {
549
- logWarn("setup commands remain visible (no command map capture for unregister)");
550
- return;
551
- }
552
- for (const name of SETUP_COMMAND_NAMES) {
553
- commandMap.delete(name);
554
- }
555
- visible = false;
556
- logInfo("setup commands hidden (CLIProxyAPI already authenticated)");
477
+ logInfo("setup command registered: /cliproxyapi");
557
478
  };
558
479
 
559
- setupCommands.isVisible = (): boolean => visible;
560
-
561
480
  return setupCommands;
562
481
  }
563
482
 
564
483
  export function registerFastCommand(options: {
565
484
  pi: ExtensionAPI;
485
+ agentDir: string;
566
486
  providerId: string;
567
487
  fastMode: FastModeController;
568
488
  onStatusChange?: (ctx: ExtensionContext) => void;
569
489
  }): 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
- });
490
+ const { pi, agentDir, providerId, fastMode, onStatusChange } = options;
579
491
 
580
492
  pi.registerCommand("fast", {
581
- description: "Toggle CLIProxyAPI Fast mode for this session.",
493
+ description: "Toggle CLIProxyAPI Fast mode globally.",
582
494
  handler: async (args, ctx) => {
583
495
  if (args.trim()) {
584
496
  ctx.ui.notify("Usage: /fast", "error");
585
497
  return;
586
498
  }
587
499
 
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");
500
+ const enabled = !fastMode.isEnabled();
501
+ try {
502
+ saveConfigFile(agentDir, { fast: enabled });
503
+ } catch (error) {
504
+ const message = error instanceof Error ? error.message : String(error);
505
+ ctx.ui.notify(`Failed to save Fast mode: ${message}`, "error");
591
506
  return;
592
507
  }
593
-
594
- const enabled = fastMode.toggleSessionEnabled();
595
- pi.appendEntry(FAST_MODE_ENTRY_TYPE, { enabled });
508
+ fastMode.setEnabled(enabled);
596
509
  onStatusChange?.(ctx);
510
+
511
+ const currentModel = ctx.model;
512
+ if (!currentModel || currentModel.provider !== providerId || !fastMode.isModelSupported(currentModel.id)) {
513
+ if (enabled) {
514
+ ctx.ui.notify("Fast mode is enabled globally, but the current model does not support it.", "warning");
515
+ } else {
516
+ ctx.ui.notify("Fast mode is disabled globally.", "info");
517
+ }
518
+ }
597
519
  },
598
520
  });
599
521
  }
@@ -606,14 +528,14 @@ export default async function (pi: ExtensionAPI): Promise<void> {
606
528
  const identity = resolveIdentity(agentDir);
607
529
  const defaultBaseUrl = resolveDefaultBaseUrl(agentDir, identity.providerId);
608
530
 
609
- let fastDefault = false;
531
+ let fastEnabled = false;
610
532
  try {
611
- fastDefault = resolveFastDefault(agentDir);
533
+ fastEnabled = resolveFastDefault(agentDir);
612
534
  } catch (error) {
613
535
  const message = error instanceof Error ? error.message : String(error);
614
536
  logWarn(`invalid Fast configuration (${message}); using fast=false`);
615
537
  }
616
- const fastMode = new FastModeController(fastDefault);
538
+ const fastMode = new FastModeController(fastEnabled);
617
539
 
618
540
  let streamSimple: CliproxyCodexStreamSimple;
619
541
  try {
@@ -630,6 +552,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
630
552
  const fastFooter = new FastFooterController(identity.providerId, fastMode);
631
553
  registerFastCommand({
632
554
  pi,
555
+ agentDir,
633
556
  providerId: identity.providerId,
634
557
  fastMode,
635
558
  onStatusChange: (ctx) => fastFooter.refresh(ctx),
@@ -646,14 +569,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
646
569
  fastMode,
647
570
  });
648
571
 
649
- // Re-show setup commands when the user /logout this provider.
650
- // Installed on session_start because AuthStorage is only available via ctx then.
651
- pi.on("session_start", (_event, ctx) => {
652
- watchProviderLogout(ctx.modelRegistry.authStorage, identity.providerId, () => {
653
- setupCommands.show();
654
- logInfo(`logout detected for ${identity.providerId}: setup commands restored: /cliproxyapi, /cpa`);
655
- });
656
- });
572
+ setupCommands.show();
657
573
 
658
574
  // Always register oauth so the provider is visible in /login immediately after install.
659
575
  registerProvider(pi, {
@@ -671,8 +587,8 @@ export default async function (pi: ExtensionAPI): Promise<void> {
671
587
  if (!connection) {
672
588
  setupCommands.show();
673
589
  logInfo(
674
- `not configured yet. Prefer /cliproxyapi (or /cpa), or /login ${identity.providerName}. ` +
675
- `Menu path: /login → Use a subscription → ${identity.providerName}. ` +
590
+ `not configured yet. Prefer /cliproxyapi or /login ${identity.providerName}. ` +
591
+ `Menu path: /login → Sign in with an account → ${identity.providerName}. ` +
676
592
  `Or set ${CONFIG_FILE_NAME} / CLIPROXYAPI_API_KEY.`,
677
593
  );
678
594
  return;
@@ -693,14 +609,12 @@ export default async function (pi: ExtensionAPI): Promise<void> {
693
609
  setupCommands,
694
610
  fastMode,
695
611
  });
696
- // Already authenticated — keep /cliproxyapi and /cpa hidden.
697
- setupCommands.hide();
698
612
  } catch (error) {
699
613
  const message = error instanceof Error ? error.message : String(error);
700
614
  if (isUnauthorizedModelsError(error)) {
701
- // 401 → credentials rejected; re-show setup commands for reconfiguration.
615
+ // 401 → credentials rejected; keep the setup command available for reconfiguration.
702
616
  setupCommands.show();
703
- logWarn(`models request unauthorized (${message}). Setup commands restored: /cliproxyapi, /cpa.`);
617
+ logWarn(`models request unauthorized (${message}). Setup command remains available: /cliproxyapi.`);
704
618
  } else {
705
619
  // Other failures (network, etc.): still offer setup so the user can fix baseUrl/key.
706
620
  setupCommands.show();
package/extensions/lib.ts CHANGED
@@ -4,6 +4,7 @@
4
4
 
5
5
  import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
6
6
  import { dirname, join } from "node:path";
7
+ import { readStoredCredential } from "@earendil-works/pi-coding-agent";
7
8
 
8
9
  // Local shape matching pi ThinkingLevelMap; avoid hard runtime peer imports here.
9
10
  export type ThinkingLevelMap = Partial<
@@ -172,8 +173,11 @@ export function loadConfigFile(agentDir: string): CliproxyConfigFile {
172
173
  const configPath = join(agentDir, CONFIG_FILE_NAME);
173
174
  try {
174
175
  const raw = readFileSync(configPath, "utf8");
175
- const parsed = JSON.parse(raw) as CliproxyConfigFile;
176
- return parsed && typeof parsed === "object" ? parsed : {};
176
+ const parsed: unknown = JSON.parse(raw);
177
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
178
+ throw new Error(`${CONFIG_FILE_NAME} must contain a JSON object`);
179
+ }
180
+ return parsed as CliproxyConfigFile;
177
181
  } catch (error) {
178
182
  const err = error as NodeJS.ErrnoException;
179
183
  if (err.code !== "ENOENT") {
@@ -187,13 +191,7 @@ export function saveConfigFile(agentDir: string, config: CliproxyConfigFile): vo
187
191
  const configPath = join(agentDir, CONFIG_FILE_NAME);
188
192
  mkdirSync(dirname(configPath), { recursive: true });
189
193
 
190
- let existing: CliproxyConfigFile = {};
191
- try {
192
- existing = loadConfigFile(agentDir);
193
- } catch {
194
- existing = {};
195
- }
196
-
194
+ const existing = loadConfigFile(agentDir);
197
195
  const next: CliproxyConfigFile = {
198
196
  ...existing,
199
197
  ...config,
@@ -202,31 +200,17 @@ export function saveConfigFile(agentDir: string, config: CliproxyConfigFile): vo
202
200
  }
203
201
 
204
202
  export function loadAuthConnection(agentDir: string, providerId: string): { baseUrl?: string; apiKey?: string } | null {
205
- const authPath = join(agentDir, AUTH_FILE_NAME);
206
- try {
207
- const raw = readFileSync(authPath, "utf8");
208
- const data = JSON.parse(raw) as Record<string, any>;
209
- const entry = data?.[providerId];
210
- if (!entry || typeof entry !== "object") {
211
- return null;
212
- }
213
-
214
- if (entry.type === "oauth" && typeof entry.access === "string" && entry.access.trim()) {
215
- const meta = decodeRefreshMeta(typeof entry.refresh === "string" ? entry.refresh : undefined);
216
- return {
217
- apiKey: entry.access.trim(),
218
- baseUrl: meta?.baseUrl,
219
- };
220
- }
203
+ const entry = readStoredCredential(providerId, join(agentDir, AUTH_FILE_NAME));
204
+ if (entry?.type === "oauth" && typeof entry.access === "string" && entry.access.trim()) {
205
+ const meta = decodeRefreshMeta(typeof entry.refresh === "string" ? entry.refresh : undefined);
206
+ return {
207
+ apiKey: entry.access.trim(),
208
+ baseUrl: meta?.baseUrl,
209
+ };
210
+ }
221
211
 
222
- if (entry.type === "api_key" && typeof entry.key === "string" && entry.key.trim()) {
223
- return { apiKey: entry.key.trim() };
224
- }
225
- } catch (error) {
226
- const err = error as NodeJS.ErrnoException;
227
- if (err.code !== "ENOENT") {
228
- throw error;
229
- }
212
+ if (entry?.type === "api_key" && typeof entry.key === "string" && entry.key.trim()) {
213
+ return { apiKey: entry.key.trim() };
230
214
  }
231
215
  return null;
232
216
  }
@@ -262,7 +246,7 @@ export function parseBooleanSetting(value: string): boolean | undefined {
262
246
  }
263
247
  }
264
248
 
265
- /** Resolve the Fast default from env, then cliproxyapi.json, then false. */
249
+ /** Resolve the Fast preference from env, then cliproxyapi.json, then false. */
266
250
  export function resolveFastDefault(agentDir: string): boolean {
267
251
  const envValue = firstNonEmpty(process.env.CLIPROXYAPI_FAST);
268
252
  if (envValue !== undefined) {
@@ -403,7 +387,7 @@ export function toPiModel(model: CodexClientModel): PiProviderModel | null {
403
387
  };
404
388
  }
405
389
 
406
- /** HTTP error from /v1/models (used to detect 401 and re-show setup commands). */
390
+ /** HTTP error from /v1/models (used to detect 401 and keep the setup command available). */
407
391
  export class ModelsHttpError extends Error {
408
392
  readonly status: number;
409
393
  readonly statusText: string;
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.1",
4
4
  "description": "Pi provider extension that auto-registers CLIProxyAPI models, plus TUI elapsed/TPS status",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -39,12 +39,12 @@
39
39
  },
40
40
  "peerDependencies": {
41
41
  "@earendil-works/pi-ai": "*",
42
- "@earendil-works/pi-coding-agent": ">=0.80.6 <0.81.0"
42
+ "@earendil-works/pi-coding-agent": ">=0.80.9 <0.81.0"
43
43
  },
44
44
  "devDependencies": {
45
45
  "@biomejs/biome": "2.5.3",
46
- "@earendil-works/pi-ai": "^0.80.6",
47
- "@earendil-works/pi-coding-agent": "0.80.6",
46
+ "@earendil-works/pi-ai": "0.80.9",
47
+ "@earendil-works/pi-coding-agent": "0.80.9",
48
48
  "@types/node": "^22.15.21",
49
49
  "typescript": "6.0.3",
50
50
  "vitest": "4.1.9"