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

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
@@ -35,7 +35,7 @@ This plugin needs both **baseUrl** and **apiKey**. pi's built-in `/login` only s
35
35
  /cliproxyapi
36
36
  ```
37
37
 
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.
38
+ This slash command is shown only when CLIProxyAPI is **not** already authenticated via `/login` (no matching credential in `auth.json`). After a successful `/login`, it is hidden from the `/` menu; reconfigure with `/login CLIProxyAPI`, or run `/logout` first to bring `/cliproxyapi` back. Config-file / env-only setups (no `/login` credential) keep the command available for reconfiguration.
39
39
 
40
40
  ### Or use /login shortcuts (skip the menu)
41
41
 
@@ -49,6 +49,8 @@ or:
49
49
  /login cliproxyapi
50
50
  ```
51
51
 
52
+ These shortcuts jump straight into CLIProxyAPI's multi-field baseUrl + API key prompts. The provider is registered as OAuth-only, so pi does not ask you to choose between API key and account first.
53
+
52
54
  ### Menu path
53
55
 
54
56
  ```text
@@ -187,13 +189,14 @@ Disable just this helper via `pi config` if you only want the CLIProxyAPI provid
187
189
  ## Failure behavior
188
190
 
189
191
  - 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`.
192
+ - After successful `/login`: `/cliproxyapi` is hidden; reconfigure via `/login CLIProxyAPI`.
193
+ - After successful `/cliproxyapi` (config-only, no `auth.json` login): `/cliproxyapi` stays available for reconfiguration.
194
+ - If an `auth.json` credential exists and `/cliproxyapi` is invoked somehow, it asks you to use `/login CLIProxyAPI` or run `/logout` first so the old credential cannot override the new key.
195
+ - The built-in `/logout` command removes only the matching `auth.json` credential; environment variables and `cliproxyapi.json` are unchanged. After logout, `/cliproxyapi` is shown again (on the next submitted input or session start).
196
+ - If a models request returns **HTTP 401** and no `/login` credential remains, the setup command is shown for reconfiguration; otherwise use `/login`.
197
+ - If CPA is unreachable during startup (non-401), a warning is logged; setup stays available via `/cliproxyapi` (when not logged in) or `/login`.
195
198
  - Login/setup final step validates credentials by requesting models:
196
- - HTTP 200 (including empty catalog) → credentials are persisted; the setup command remains available
199
+ - HTTP 200 (including empty catalog) → credentials are persisted; `/login` hides `/cliproxyapi`
197
200
  - non-200 / network / invalid baseUrl → nothing is persisted; re-enter baseUrl + API key
198
201
  - If CPA returns HTTP 200 with zero usable models: login still succeeds; re-run setup later after models become available.
199
202
  - 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.
@@ -2,10 +2,11 @@
2
2
  * CLIProxyAPI dynamic model provider for pi.
3
3
  *
4
4
  * Supports login-style setup via `/login` and a dedicated command:
5
- * 1. Provider always appears under "Sign in with an account" as CLIProxyAPI
5
+ * 1. Provider is registered as OAuth-only so `/login CLIProxyAPI` / `/login cliproxyapi`
6
+ * skip the API-key vs account selector and go straight to multi-field prompts
6
7
  * (pi only supports multi-field prompts on the account/OAuth path).
7
8
  * 2. Preferred shortcuts: `/login CLIProxyAPI`, `/login cliproxyapi`,
8
- * or the dedicated `/cliproxyapi` command.
9
+ * or the dedicated `/cliproxyapi` command (hidden after successful /login).
9
10
  * 3. Setup prompts for baseUrl + apiKey.
10
11
  * 4. Final login step validates credentials via /v1/models?client_version=pi
11
12
  * (HTTP 200 = success even if the catalog is empty; otherwise re-prompt).
@@ -47,9 +48,13 @@ import {
47
48
  saveConfigFile,
48
49
  } from "./lib.ts";
49
50
 
50
- /** Registers /cliproxyapi in the slash-command menu. */
51
+ /** Show/hide /cliproxyapi in the slash-command menu. */
51
52
  interface SetupCommandsController {
52
53
  show(): void;
54
+ hide(): void;
55
+ isVisible(): boolean;
56
+ /** Hide when /login credentials exist; show otherwise. */
57
+ syncFromAuth(): void;
53
58
  }
54
59
 
55
60
  class ConfigPersistenceError extends Error {
@@ -140,6 +145,13 @@ async function configureAndRegister(options: {
140
145
  streamSimple: CliproxyCodexStreamSimple;
141
146
  setupCommands: SetupCommandsController;
142
147
  fastMode: FastModeController;
148
+ /**
149
+ * When true, register a configured API key for ambient request auth.
150
+ * Only used by `/cliproxyapi` (no auth.json write). `/login` must leave this
151
+ * false so the provider stays OAuth-only and `/login <provider>` skips the
152
+ * API-key vs account selector.
153
+ */
154
+ registerConfiguredApiKey?: boolean;
143
155
  }): Promise<{ modelCount: number; modelsUrl: string }> {
144
156
  const {
145
157
  pi,
@@ -152,6 +164,7 @@ async function configureAndRegister(options: {
152
164
  streamSimple,
153
165
  setupCommands,
154
166
  fastMode,
167
+ registerConfiguredApiKey = false,
155
168
  } = options;
156
169
 
157
170
  const loaded = await loadMappedModels(baseUrlInput, apiKey);
@@ -171,7 +184,7 @@ async function configureAndRegister(options: {
171
184
  providerId,
172
185
  providerName,
173
186
  baseUrlInput,
174
- apiKey,
187
+ apiKey: registerConfiguredApiKey ? apiKey : undefined,
175
188
  models: loaded.models,
176
189
  defaultBaseUrl: baseUrlInput || defaultBaseUrl,
177
190
  agentDir,
@@ -224,6 +237,8 @@ function createOAuthHandlers(options: {
224
237
  fastMode,
225
238
  });
226
239
 
240
+ // /login succeeded — dedicated setup is unnecessary until logout.
241
+ setupCommands.hide();
227
242
  logInfo(`login ok: registered ${result.modelCount} models from ${result.modelsUrl}`);
228
243
  return buildOAuthCredentials(baseUrlInput, apiKey);
229
244
  } catch (error) {
@@ -313,20 +328,30 @@ function registerProvider(
313
328
  fastMode,
314
329
  });
315
330
 
331
+ // Replace any previous registration so an earlier ambient apiKey does not linger
332
+ // via registerProvider merge semantics and reintroduce the auth-type selector.
333
+ pi.unregisterProvider(providerId);
334
+
316
335
  pi.registerProvider(providerId, {
317
336
  name: providerName,
318
337
  baseUrl: endpoints.inferenceBaseUrl,
319
338
  api: CLIPROXYAPI_CODEX_API,
320
339
  streamSimple,
321
- // Keep oauth always registered so /login lists this provider even before models exist.
340
+ // OAuth-only keeps `/login <provider>` on the multi-field account path.
341
+ // Pass apiKey only for ambient request auth when no /login credential exists
342
+ // (config file / env / `/cliproxyapi`). Never pass both for /login flows.
322
343
  oauth,
323
- // apiKey is optional when oauth is present; include it when known for direct use.
324
344
  ...(apiKey ? { apiKey } : {}),
325
345
  ...(models && models.length > 0 ? { models } : {}),
326
346
  });
327
347
  }
328
348
 
329
- /** Register the always-available /cliproxyapi setup command. */
349
+ /**
350
+ * Register /cliproxyapi and allow hiding it after /login.
351
+ *
352
+ * pi has registerCommand but no unregisterCommand, so hide() removes the entry
353
+ * from the extension's internal commands Map captured during first registration.
354
+ */
330
355
  function createSetupCommandsController(options: {
331
356
  pi: ExtensionAPI;
332
357
  agentDir: string;
@@ -338,14 +363,25 @@ function createSetupCommandsController(options: {
338
363
  }): SetupCommandsController {
339
364
  const { pi, agentDir, providerId, providerName, defaultBaseUrl, streamSimple, fastMode } = options;
340
365
 
341
- // Self-referential controller so validation failures can ensure commands are registered.
366
+ // Self-referential controller so handlers can hide/show after validation.
342
367
  const setupCommands: SetupCommandsController = {
343
368
  show() {
344
369
  /* replaced below */
345
370
  },
371
+ hide() {
372
+ /* replaced below */
373
+ },
374
+ isVisible() {
375
+ return false;
376
+ },
377
+ syncFromAuth() {
378
+ /* replaced below */
379
+ },
346
380
  };
347
381
 
348
382
  let visible = false;
383
+ // Captured extension.commands Map (pi has no public unregisterCommand API).
384
+ let commandMap: Map<string, unknown> | null = null;
349
385
 
350
386
  const handler = async (_args: string, ctx: ExtensionCommandContext): Promise<void> => {
351
387
  if (!ctx.hasUI) {
@@ -357,6 +393,8 @@ function createSetupCommandsController(options: {
357
393
  }
358
394
 
359
395
  if (loadAuthConnection(agentDir, providerId)?.apiKey) {
396
+ // Still authenticated via /login — hide the dedicated command and redirect.
397
+ setupCommands.hide();
360
398
  ctx.ui.notify(
361
399
  `CLIProxyAPI credentials are already stored by /login. Use /login ${providerName} to replace them, or run /logout before /cliproxyapi.`,
362
400
  "error",
@@ -409,6 +447,9 @@ function createSetupCommandsController(options: {
409
447
  streamSimple,
410
448
  setupCommands,
411
449
  fastMode,
450
+ // Dedicated command does not write auth.json; keep ambient apiKey
451
+ // so requests work in the current session.
452
+ registerConfiguredApiKey: true,
412
453
  });
413
454
 
414
455
  logInfo(`command setup ok: registered ${result.modelCount} models from ${result.modelsUrl}`);
@@ -472,9 +513,58 @@ function createSetupCommandsController(options: {
472
513
  if (visible) {
473
514
  return;
474
515
  }
475
- registerCommand();
516
+
517
+ if (!commandMap) {
518
+ // Capture the extension.commands Map during first registration.
519
+ const originalSet = Map.prototype.set;
520
+ Map.prototype.set = function setWithCapture(this: Map<unknown, unknown>, key: unknown, value: unknown) {
521
+ if (
522
+ key === "cliproxyapi" &&
523
+ value &&
524
+ typeof value === "object" &&
525
+ "handler" in (value as Record<string, unknown>)
526
+ ) {
527
+ commandMap = this as Map<string, unknown>;
528
+ }
529
+ return originalSet.call(this, key, value);
530
+ } as typeof Map.prototype.set;
531
+ try {
532
+ registerCommand();
533
+ } finally {
534
+ Map.prototype.set = originalSet;
535
+ }
536
+ if (!commandMap) {
537
+ logWarn("could not capture command map; /cliproxyapi cannot be hidden after login");
538
+ }
539
+ } else {
540
+ registerCommand();
541
+ }
542
+
476
543
  visible = true;
477
- logInfo("setup command registered: /cliproxyapi");
544
+ logInfo("setup command shown: /cliproxyapi");
545
+ };
546
+
547
+ setupCommands.hide = (): void => {
548
+ if (!visible) {
549
+ return;
550
+ }
551
+ if (!commandMap) {
552
+ logWarn("setup command remains visible (no command map capture for unregister)");
553
+ return;
554
+ }
555
+ commandMap.delete("cliproxyapi");
556
+ visible = false;
557
+ logInfo("setup command hidden (CLIProxyAPI already authenticated via /login)");
558
+ };
559
+
560
+ setupCommands.isVisible = (): boolean => visible;
561
+
562
+ setupCommands.syncFromAuth = (): void => {
563
+ if (loadAuthConnection(agentDir, providerId)?.apiKey) {
564
+ setupCommands.hide();
565
+ } else {
566
+ setupCommands.show();
567
+ }
478
568
  };
479
569
 
480
570
  return setupCommands;
@@ -569,7 +659,17 @@ export default async function (pi: ExtensionAPI): Promise<void> {
569
659
  fastMode,
570
660
  });
571
661
 
572
- setupCommands.show();
662
+ // Reconcile visibility after /logout (auth.json removed) or when credentials reappear.
663
+ // pi has no logout extension event, so re-check on session lifecycle and submitted input.
664
+ pi.on("session_start", () => {
665
+ setupCommands.syncFromAuth();
666
+ });
667
+ pi.on("input", () => {
668
+ setupCommands.syncFromAuth();
669
+ });
670
+
671
+ // Initial visibility: hide when already logged in via /login.
672
+ setupCommands.syncFromAuth();
573
673
 
574
674
  // Always register oauth so the provider is visible in /login immediately after install.
575
675
  registerProvider(pi, {
@@ -585,7 +685,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
585
685
 
586
686
  const connection = resolveConnection(agentDir, identity.providerId);
587
687
  if (!connection) {
588
- setupCommands.show();
688
+ setupCommands.syncFromAuth();
589
689
  logInfo(
590
690
  `not configured yet. Prefer /cliproxyapi or /login ${identity.providerName}. ` +
591
691
  `Menu path: /login → Sign in with an account → ${identity.providerName}. ` +
@@ -597,11 +697,15 @@ export default async function (pi: ExtensionAPI): Promise<void> {
597
697
  try {
598
698
  const loaded = await loadMappedModels(connection.baseUrlInput, connection.apiKey);
599
699
  fastMode.setSupportedModelIds(loaded.fastModelIds);
700
+ // Prefer OAuth-only registration when /login already stored credentials so
701
+ // `/login <provider>` jumps straight into the multi-field flow. Fall back to
702
+ // ambient apiKey only for config-file / env setups without auth.json.
703
+ const hasStoredLogin = Boolean(loadAuthConnection(agentDir, identity.providerId)?.apiKey);
600
704
  registerProvider(pi, {
601
705
  providerId: identity.providerId,
602
706
  providerName: identity.providerName,
603
707
  baseUrlInput: connection.baseUrlInput,
604
- apiKey: connection.apiKey,
708
+ apiKey: hasStoredLogin ? undefined : connection.apiKey,
605
709
  models: loaded.models,
606
710
  defaultBaseUrl,
607
711
  agentDir,
@@ -609,17 +713,26 @@ export default async function (pi: ExtensionAPI): Promise<void> {
609
713
  setupCommands,
610
714
  fastMode,
611
715
  });
716
+ // Keep /cliproxyapi hidden when authenticated via /login; show for config-only setups.
717
+ setupCommands.syncFromAuth();
612
718
  } catch (error) {
613
719
  const message = error instanceof Error ? error.message : String(error);
614
720
  if (isUnauthorizedModelsError(error)) {
615
- // 401 → credentials rejected; keep the setup command available for reconfiguration.
616
- setupCommands.show();
617
- logWarn(`models request unauthorized (${message}). Setup command remains available: /cliproxyapi.`);
721
+ // 401 → prefer /login when auth.json still has a credential; otherwise show setup.
722
+ setupCommands.syncFromAuth();
723
+ logWarn(
724
+ `models request unauthorized (${message}). ` +
725
+ (setupCommands.isVisible()
726
+ ? "Setup command available: /cliproxyapi."
727
+ : `Use /login ${identity.providerName} or /logout then /cliproxyapi.`),
728
+ );
618
729
  } else {
619
- // Other failures (network, etc.): still offer setup so the user can fix baseUrl/key.
620
- setupCommands.show();
730
+ // Other failures (network, etc.): still offer setup when not logged in via /login.
731
+ setupCommands.syncFromAuth();
621
732
  logWarn(
622
- `failed to load models (${message}). Provider remains available via /cliproxyapi or /login for reconfiguration.`,
733
+ `failed to load models (${message}). Provider remains available via ` +
734
+ (setupCommands.isVisible() ? "/cliproxyapi or " : "") +
735
+ `/login for reconfiguration.`,
623
736
  );
624
737
  }
625
738
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@router-for-me/pi-cliproxyapi-provider",
3
- "version": "1.4.1",
3
+ "version": "1.4.3",
4
4
  "description": "Pi provider extension that auto-registers CLIProxyAPI models, plus TUI elapsed/TPS status",
5
5
  "type": "module",
6
6
  "keywords": [