@router-for-me/pi-cliproxyapi-provider 1.4.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
 
@@ -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
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,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` globally controls catalog-driven priority service tier injection.
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).
@@ -48,11 +47,9 @@ 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;
56
53
  }
57
54
 
58
55
  class ConfigPersistenceError extends Error {
@@ -184,9 +181,6 @@ async function configureAndRegister(options: {
184
181
  });
185
182
  fastMode.setSupportedModelIds(loaded.fastModelIds);
186
183
 
187
- // Login succeeded — hide dedicated setup commands from the slash menu.
188
- setupCommands.hide();
189
-
190
184
  return { modelCount: loaded.models.length, modelsUrl: loaded.modelsUrl };
191
185
  }
192
186
 
@@ -239,7 +233,7 @@ function createOAuthHandlers(options: {
239
233
  callbacks.onProgress?.(message);
240
234
  throw error;
241
235
  }
242
- // Auth failures should keep setup commands available for reconfiguration.
236
+ // Auth failures should keep the setup command available for reconfiguration.
243
237
  if (isUnauthorizedModelsError(error)) {
244
238
  setupCommands.show();
245
239
  }
@@ -332,40 +326,7 @@ function registerProvider(
332
326
  });
333
327
  }
334
328
 
335
- const SETUP_COMMAND_NAMES = ["cliproxyapi", "cpa"] as const;
336
-
337
- /** Avoid double-wrapping the same AuthStorage instance across session reloads. */
338
- const logoutWatchedStorages = new WeakSet<object>();
339
-
340
- /**
341
- * pi has no logout extension event. Wrap authStorage.logout so we can re-show
342
- * setup commands when this provider is removed via /logout.
343
- */
344
- function watchProviderLogout(
345
- authStorage: { logout(provider: string): void },
346
- providerId: string,
347
- onLogout: () => void,
348
- ): void {
349
- if (logoutWatchedStorages.has(authStorage as object)) {
350
- return;
351
- }
352
- logoutWatchedStorages.add(authStorage as object);
353
-
354
- const originalLogout = authStorage.logout.bind(authStorage);
355
- authStorage.logout = (provider: string): void => {
356
- originalLogout(provider);
357
- if (provider === providerId) {
358
- onLogout();
359
- }
360
- };
361
- }
362
-
363
- /**
364
- * Show/hide /cliproxyapi and /cpa.
365
- *
366
- * pi has registerCommand but no unregisterCommand, so hide() removes entries from the
367
- * extension's internal commands Map captured during the first registration.
368
- */
329
+ /** Register the always-available /cliproxyapi setup command. */
369
330
  function createSetupCommandsController(options: {
370
331
  pi: ExtensionAPI;
371
332
  agentDir: string;
@@ -377,22 +338,14 @@ function createSetupCommandsController(options: {
377
338
  }): SetupCommandsController {
378
339
  const { pi, agentDir, providerId, providerName, defaultBaseUrl, streamSimple, fastMode } = options;
379
340
 
380
- // Self-referential controller so handlers can hide/show after validation.
341
+ // Self-referential controller so validation failures can ensure commands are registered.
381
342
  const setupCommands: SetupCommandsController = {
382
343
  show() {
383
344
  /* replaced below */
384
345
  },
385
- hide() {
386
- /* replaced below */
387
- },
388
- isVisible() {
389
- return false;
390
- },
391
346
  };
392
347
 
393
348
  let visible = false;
394
- // Captured extension.commands Map (pi has no public unregisterCommand API).
395
- let commandMap: Map<string, unknown> | null = null;
396
349
 
397
350
  const handler = async (_args: string, ctx: ExtensionCommandContext): Promise<void> => {
398
351
  if (!ctx.hasUI) {
@@ -403,6 +356,14 @@ function createSetupCommandsController(options: {
403
356
  return;
404
357
  }
405
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
+
406
367
  const promptDefaultBaseUrl = resolveDefaultBaseUrl(agentDir, providerId) || defaultBaseUrl;
407
368
 
408
369
  const baseUrlRaw = await ctx.ui.input(`CLIProxyAPI base URL [${promptDefaultBaseUrl}]:`, promptDefaultBaseUrl);
@@ -450,12 +411,6 @@ function createSetupCommandsController(options: {
450
411
  fastMode,
451
412
  });
452
413
 
453
- // Persist only after successful validation; keep AuthStorage in-memory too.
454
- ctx.modelRegistry.authStorage.set(providerId, {
455
- type: "oauth",
456
- ...buildOAuthCredentials(currentBaseUrl, currentApiKey),
457
- });
458
-
459
414
  logInfo(`command setup ok: registered ${result.modelCount} models from ${result.modelsUrl}`);
460
415
  ctx.ui.notify(`CLIProxyAPI configured: ${result.modelCount} models from ${result.modelsUrl}`, "info");
461
416
  return;
@@ -506,78 +461,22 @@ function createSetupCommandsController(options: {
506
461
  }
507
462
  };
508
463
 
509
- const commandSpecs: Array<{ name: (typeof SETUP_COMMAND_NAMES)[number]; description: string }> = [
510
- {
511
- name: "cliproxyapi",
464
+ const registerCommand = (): void => {
465
+ pi.registerCommand("cliproxyapi", {
512
466
  description: "Configure CLIProxyAPI (baseUrl + API key) and load models. Prefer this or /login CLIProxyAPI.",
513
- },
514
- {
515
- name: "cpa",
516
- description: "Alias for /cliproxyapi — configure CLIProxyAPI and load models.",
517
- },
518
- ];
519
-
520
- const registerAll = (): void => {
521
- for (const spec of commandSpecs) {
522
- pi.registerCommand(spec.name, {
523
- description: spec.description,
524
- handler,
525
- });
526
- }
467
+ handler,
468
+ });
527
469
  };
528
470
 
529
471
  setupCommands.show = (): void => {
530
472
  if (visible) {
531
473
  return;
532
474
  }
533
-
534
- if (!commandMap) {
535
- // Capture the extension.commands Map during first registration.
536
- const originalSet = Map.prototype.set;
537
- Map.prototype.set = function setWithCapture(this: Map<unknown, unknown>, key: unknown, value: unknown) {
538
- if (
539
- key === "cliproxyapi" &&
540
- value &&
541
- typeof value === "object" &&
542
- "handler" in (value as Record<string, unknown>)
543
- ) {
544
- commandMap = this as Map<string, unknown>;
545
- }
546
- return originalSet.call(this, key, value);
547
- } as typeof Map.prototype.set;
548
- try {
549
- registerAll();
550
- } finally {
551
- Map.prototype.set = originalSet;
552
- }
553
- if (!commandMap) {
554
- logWarn("could not capture command map; /cliproxyapi and /cpa cannot be hidden after login");
555
- }
556
- } else {
557
- registerAll();
558
- }
559
-
475
+ registerCommand();
560
476
  visible = true;
561
- logInfo("setup commands shown: /cliproxyapi, /cpa");
562
- };
563
-
564
- setupCommands.hide = (): void => {
565
- if (!visible) {
566
- return;
567
- }
568
- if (!commandMap) {
569
- logWarn("setup commands remain visible (no command map capture for unregister)");
570
- return;
571
- }
572
- for (const name of SETUP_COMMAND_NAMES) {
573
- commandMap.delete(name);
574
- }
575
- visible = false;
576
- logInfo("setup commands hidden (CLIProxyAPI already authenticated)");
477
+ logInfo("setup command registered: /cliproxyapi");
577
478
  };
578
479
 
579
- setupCommands.isVisible = (): boolean => visible;
580
-
581
480
  return setupCommands;
582
481
  }
583
482
 
@@ -670,14 +569,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
670
569
  fastMode,
671
570
  });
672
571
 
673
- // Re-show setup commands when the user /logout this provider.
674
- // Installed on session_start because AuthStorage is only available via ctx then.
675
- pi.on("session_start", (_event, ctx) => {
676
- watchProviderLogout(ctx.modelRegistry.authStorage, identity.providerId, () => {
677
- setupCommands.show();
678
- logInfo(`logout detected for ${identity.providerId}: setup commands restored: /cliproxyapi, /cpa`);
679
- });
680
- });
572
+ setupCommands.show();
681
573
 
682
574
  // Always register oauth so the provider is visible in /login immediately after install.
683
575
  registerProvider(pi, {
@@ -695,8 +587,8 @@ export default async function (pi: ExtensionAPI): Promise<void> {
695
587
  if (!connection) {
696
588
  setupCommands.show();
697
589
  logInfo(
698
- `not configured yet. Prefer /cliproxyapi (or /cpa), or /login ${identity.providerName}. ` +
699
- `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}. ` +
700
592
  `Or set ${CONFIG_FILE_NAME} / CLIPROXYAPI_API_KEY.`,
701
593
  );
702
594
  return;
@@ -717,14 +609,12 @@ export default async function (pi: ExtensionAPI): Promise<void> {
717
609
  setupCommands,
718
610
  fastMode,
719
611
  });
720
- // Already authenticated — keep /cliproxyapi and /cpa hidden.
721
- setupCommands.hide();
722
612
  } catch (error) {
723
613
  const message = error instanceof Error ? error.message : String(error);
724
614
  if (isUnauthorizedModelsError(error)) {
725
- // 401 → credentials rejected; re-show setup commands for reconfiguration.
615
+ // 401 → credentials rejected; keep the setup command available for reconfiguration.
726
616
  setupCommands.show();
727
- logWarn(`models request unauthorized (${message}). Setup commands restored: /cliproxyapi, /cpa.`);
617
+ logWarn(`models request unauthorized (${message}). Setup command remains available: /cliproxyapi.`);
728
618
  } else {
729
619
  // Other failures (network, etc.): still offer setup so the user can fix baseUrl/key.
730
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<
@@ -199,31 +200,17 @@ export function saveConfigFile(agentDir: string, config: CliproxyConfigFile): vo
199
200
  }
200
201
 
201
202
  export function loadAuthConnection(agentDir: string, providerId: string): { baseUrl?: string; apiKey?: string } | null {
202
- const authPath = join(agentDir, AUTH_FILE_NAME);
203
- try {
204
- const raw = readFileSync(authPath, "utf8");
205
- const data = JSON.parse(raw) as Record<string, any>;
206
- const entry = data?.[providerId];
207
- if (!entry || typeof entry !== "object") {
208
- return null;
209
- }
210
-
211
- if (entry.type === "oauth" && typeof entry.access === "string" && entry.access.trim()) {
212
- const meta = decodeRefreshMeta(typeof entry.refresh === "string" ? entry.refresh : undefined);
213
- return {
214
- apiKey: entry.access.trim(),
215
- baseUrl: meta?.baseUrl,
216
- };
217
- }
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
+ }
218
211
 
219
- if (entry.type === "api_key" && typeof entry.key === "string" && entry.key.trim()) {
220
- return { apiKey: entry.key.trim() };
221
- }
222
- } catch (error) {
223
- const err = error as NodeJS.ErrnoException;
224
- if (err.code !== "ENOENT") {
225
- throw error;
226
- }
212
+ if (entry?.type === "api_key" && typeof entry.key === "string" && entry.key.trim()) {
213
+ return { apiKey: entry.key.trim() };
227
214
  }
228
215
  return null;
229
216
  }
@@ -400,7 +387,7 @@ export function toPiModel(model: CodexClientModel): PiProviderModel | null {
400
387
  };
401
388
  }
402
389
 
403
- /** 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). */
404
391
  export class ModelsHttpError extends Error {
405
392
  readonly status: number;
406
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.4.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"