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

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 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.
38
+ This slash command is shown only when CLIProxyAPI is **not yet configured** (no usable credentials from env, `cliproxyapi.json`, or `/login` auth). After a successful `/login` or `/cliproxyapi` setup, it is removed from the command registry and filtered out of `/` autocomplete. Reconfigure with `/login CLIProxyAPI`, or clear credentials (`/logout` and/or remove `cliproxyapi.json` / env) to bring `/cliproxyapi` back. Restart pi or run `/reload` after upgrading so the new visibility logic is loaded.
39
39
 
40
40
  ### Or use /login shortcuts (skip the menu)
41
41
 
@@ -189,14 +189,12 @@ Disable just this helper via `pi config` if you only want the CLIProxyAPI provid
189
189
  ## Failure behavior
190
190
 
191
191
  - Before setup / without credentials: provider still appears in `/login`; `/cliproxyapi` is shown; no models are listed yet.
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.
192
+ - After successful `/login` or `/cliproxyapi`: `/cliproxyapi` is hidden; reconfigure via `/login CLIProxyAPI` or by clearing stored credentials/config.
194
193
  - 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`.
194
+ - The built-in `/logout` command removes only the matching `auth.json` credential; environment variables and `cliproxyapi.json` are unchanged. `/cliproxyapi` reappears only when no connection source remains (after logout **and** config/env are cleared), or when model loading fails with a reconfiguration prompt.
195
+ - If a models request returns **HTTP 401** or CPA is unreachable during startup, `/cliproxyapi` is shown again so credentials can be fixed.
198
196
  - Login/setup final step validates credentials by requesting models:
199
- - HTTP 200 (including empty catalog) → credentials are persisted; `/login` hides `/cliproxyapi`
197
+ - HTTP 200 (including empty catalog) → credentials are persisted; `/cliproxyapi` is hidden
200
198
  - non-200 / network / invalid baseUrl → nothing is persisted; re-enter baseUrl + API key
201
199
  - If CPA returns HTTP 200 with zero usable models: login still succeeds; re-run setup later after models become available.
202
200
  - 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.
@@ -6,7 +6,7 @@
6
6
  * skip the API-key vs account selector and go straight to multi-field prompts
7
7
  * (pi only supports multi-field prompts on the account/OAuth path).
8
8
  * 2. Preferred shortcuts: `/login CLIProxyAPI`, `/login cliproxyapi`,
9
- * or the dedicated `/cliproxyapi` command (hidden after successful /login).
9
+ * or the dedicated `/cliproxyapi` command (hidden once configured).
10
10
  * 3. Setup prompts for baseUrl + apiKey.
11
11
  * 4. Final login step validates credentials via /v1/models?client_version=pi
12
12
  * (HTTP 200 = success even if the catalog is empty; otherwise re-prompt).
@@ -53,8 +53,29 @@ interface SetupCommandsController {
53
53
  show(): void;
54
54
  hide(): void;
55
55
  isVisible(): boolean;
56
- /** Hide when /login credentials exist; show otherwise. */
57
- syncFromAuth(): void;
56
+ /**
57
+ * Hide when CLIProxyAPI is already configured (env / cliproxyapi.json / auth.json).
58
+ * Show when no connection is available. Pass forceShow after 401 so the user can fix credentials.
59
+ */
60
+ syncVisibility(options?: { forceShow?: boolean }): void;
61
+ /** Whether any connection source currently provides credentials. */
62
+ isConfigured(): boolean;
63
+ }
64
+
65
+ function hasLoginCredential(agentDir: string, providerId: string): boolean {
66
+ try {
67
+ return Boolean(loadAuthConnection(agentDir, providerId)?.apiKey);
68
+ } catch {
69
+ return false;
70
+ }
71
+ }
72
+
73
+ function isProviderConfigured(agentDir: string, providerId: string): boolean {
74
+ try {
75
+ return resolveConnection(agentDir, providerId) !== null;
76
+ } catch {
77
+ return false;
78
+ }
58
79
  }
59
80
 
60
81
  class ConfigPersistenceError extends Error {
@@ -237,7 +258,7 @@ function createOAuthHandlers(options: {
237
258
  fastMode,
238
259
  });
239
260
 
240
- // /login succeeded — dedicated setup is unnecessary until logout.
261
+ // /login succeeded — dedicated setup is unnecessary until config is cleared.
241
262
  setupCommands.hide();
242
263
  logInfo(`login ok: registered ${result.modelCount} models from ${result.modelsUrl}`);
243
264
  return buildOAuthCredentials(baseUrlInput, apiKey);
@@ -250,7 +271,7 @@ function createOAuthHandlers(options: {
250
271
  }
251
272
  // Auth failures should keep the setup command available for reconfiguration.
252
273
  if (isUnauthorizedModelsError(error)) {
253
- setupCommands.show();
274
+ setupCommands.syncVisibility({ forceShow: true });
254
275
  }
255
276
  callbacks.onProgress?.(`Login validation failed: ${message}\nPlease re-enter base URL and API key.`);
256
277
  // Keep last baseUrl as the next default so retyping is easier.
@@ -374,9 +395,12 @@ function createSetupCommandsController(options: {
374
395
  isVisible() {
375
396
  return false;
376
397
  },
377
- syncFromAuth() {
398
+ syncVisibility() {
378
399
  /* replaced below */
379
400
  },
401
+ isConfigured() {
402
+ return false;
403
+ },
380
404
  };
381
405
 
382
406
  let visible = false;
@@ -392,7 +416,7 @@ function createSetupCommandsController(options: {
392
416
  return;
393
417
  }
394
418
 
395
- if (loadAuthConnection(agentDir, providerId)?.apiKey) {
419
+ if (hasLoginCredential(agentDir, providerId)) {
396
420
  // Still authenticated via /login — hide the dedicated command and redirect.
397
421
  setupCommands.hide();
398
422
  ctx.ui.notify(
@@ -452,6 +476,8 @@ function createSetupCommandsController(options: {
452
476
  registerConfiguredApiKey: true,
453
477
  });
454
478
 
479
+ // Config saved — hide dedicated setup until credentials are cleared.
480
+ setupCommands.hide();
455
481
  logInfo(`command setup ok: registered ${result.modelCount} models from ${result.modelsUrl}`);
456
482
  ctx.ui.notify(`CLIProxyAPI configured: ${result.modelCount} models from ${result.modelsUrl}`, "info");
457
483
  return;
@@ -463,7 +489,7 @@ function createSetupCommandsController(options: {
463
489
  return;
464
490
  }
465
491
  if (isUnauthorizedModelsError(error)) {
466
- setupCommands.show();
492
+ setupCommands.syncVisibility({ forceShow: true });
467
493
  }
468
494
  ctx.ui.notify(`CLIProxyAPI validation failed: ${message}. Please re-enter base URL and API key.`, "error");
469
495
  }
@@ -554,13 +580,19 @@ function createSetupCommandsController(options: {
554
580
  }
555
581
  commandMap.delete("cliproxyapi");
556
582
  visible = false;
557
- logInfo("setup command hidden (CLIProxyAPI already authenticated via /login)");
583
+ logInfo("setup command hidden (CLIProxyAPI already configured)");
558
584
  };
559
585
 
560
586
  setupCommands.isVisible = (): boolean => visible;
561
587
 
562
- setupCommands.syncFromAuth = (): void => {
563
- if (loadAuthConnection(agentDir, providerId)?.apiKey) {
588
+ setupCommands.isConfigured = (): boolean => isProviderConfigured(agentDir, providerId);
589
+
590
+ setupCommands.syncVisibility = (options?: { forceShow?: boolean }): void => {
591
+ if (options?.forceShow) {
592
+ setupCommands.show();
593
+ return;
594
+ }
595
+ if (isProviderConfigured(agentDir, providerId)) {
564
596
  setupCommands.hide();
565
597
  } else {
566
598
  setupCommands.show();
@@ -570,6 +602,55 @@ function createSetupCommandsController(options: {
570
602
  return setupCommands;
571
603
  }
572
604
 
605
+ /**
606
+ * pi's slash autocomplete snapshots commands at setup time. Deleting from the
607
+ * extension command Map alone does not refresh that snapshot, so also filter
608
+ * `/cliproxyapi` out of live suggestions while the provider is configured.
609
+ */
610
+ function installSetupCommandAutocompleteFilter(options: {
611
+ pi: ExtensionAPI;
612
+ agentDir: string;
613
+ providerId: string;
614
+ setupCommands: SetupCommandsController;
615
+ }): void {
616
+ const { pi, agentDir, providerId, setupCommands } = options;
617
+ let installed = false;
618
+
619
+ pi.on("session_start", (_event, ctx) => {
620
+ setupCommands.syncVisibility();
621
+
622
+ if (installed) {
623
+ return;
624
+ }
625
+ if (typeof ctx.ui.addAutocompleteProvider !== "function") {
626
+ return;
627
+ }
628
+ installed = true;
629
+
630
+ ctx.ui.addAutocompleteProvider((current) => ({
631
+ triggerCharacters: current.triggerCharacters,
632
+ shouldTriggerFileCompletion: current.shouldTriggerFileCompletion?.bind(current),
633
+ applyCompletion: current.applyCompletion.bind(current),
634
+ async getSuggestions(lines, cursorLine, cursorCol, suggestionOptions) {
635
+ // Keep Map visibility in sync when the user opens `/`.
636
+ setupCommands.syncVisibility();
637
+
638
+ const result = await current.getSuggestions(lines, cursorLine, cursorCol, suggestionOptions);
639
+ if (!result?.items?.length || !isProviderConfigured(agentDir, providerId)) {
640
+ return result;
641
+ }
642
+
643
+ const items = result.items.filter((item) => item.value !== "cliproxyapi" && item.label !== "cliproxyapi");
644
+ if (items.length === 0) {
645
+ return null;
646
+ }
647
+ return { ...result, items };
648
+ },
649
+ }));
650
+ logInfo("installed /cliproxyapi autocomplete filter for configured sessions");
651
+ });
652
+ }
653
+
573
654
  export function registerFastCommand(options: {
574
655
  pi: ExtensionAPI;
575
656
  agentDir: string;
@@ -659,17 +740,26 @@ export default async function (pi: ExtensionAPI): Promise<void> {
659
740
  fastMode,
660
741
  });
661
742
 
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();
743
+ // Reconcile Map visibility + autocomplete filtering when configuration changes.
744
+ // pi has no logout extension event and slash autocomplete is snapshotted, so we:
745
+ // 1) delete/re-add the command Map entry
746
+ // 2) filter suggestions live while any connection source is configured
747
+ // 3) re-check on submitted input after /logout or config edits
748
+ installSetupCommandAutocompleteFilter({
749
+ pi,
750
+ agentDir,
751
+ providerId: identity.providerId,
752
+ setupCommands,
666
753
  });
667
754
  pi.on("input", () => {
668
- setupCommands.syncFromAuth();
755
+ setupCommands.syncVisibility();
669
756
  });
670
757
 
671
- // Initial visibility: hide when already logged in via /login.
672
- setupCommands.syncFromAuth();
758
+ // Initial visibility: hide when already configured via env / config / /login.
759
+ setupCommands.syncVisibility();
760
+ if (setupCommands.isConfigured()) {
761
+ logInfo("CLIProxyAPI already configured; /cliproxyapi stays hidden");
762
+ }
673
763
 
674
764
  // Always register oauth so the provider is visible in /login immediately after install.
675
765
  registerProvider(pi, {
@@ -685,7 +775,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
685
775
 
686
776
  const connection = resolveConnection(agentDir, identity.providerId);
687
777
  if (!connection) {
688
- setupCommands.syncFromAuth();
778
+ setupCommands.syncVisibility();
689
779
  logInfo(
690
780
  `not configured yet. Prefer /cliproxyapi or /login ${identity.providerName}. ` +
691
781
  `Menu path: /login → Sign in with an account → ${identity.providerName}. ` +
@@ -700,7 +790,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
700
790
  // Prefer OAuth-only registration when /login already stored credentials so
701
791
  // `/login <provider>` jumps straight into the multi-field flow. Fall back to
702
792
  // ambient apiKey only for config-file / env setups without auth.json.
703
- const hasStoredLogin = Boolean(loadAuthConnection(agentDir, identity.providerId)?.apiKey);
793
+ const hasStoredLogin = hasLoginCredential(agentDir, identity.providerId);
704
794
  registerProvider(pi, {
705
795
  providerId: identity.providerId,
706
796
  providerName: identity.providerName,
@@ -713,26 +803,19 @@ export default async function (pi: ExtensionAPI): Promise<void> {
713
803
  setupCommands,
714
804
  fastMode,
715
805
  });
716
- // Keep /cliproxyapi hidden when authenticated via /login; show for config-only setups.
717
- setupCommands.syncFromAuth();
806
+ // Configured successfully — keep /cliproxyapi hidden.
807
+ setupCommands.hide();
718
808
  } catch (error) {
719
809
  const message = error instanceof Error ? error.message : String(error);
720
810
  if (isUnauthorizedModelsError(error)) {
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
- );
811
+ // 401 → show setup so the user can fix baseUrl/key.
812
+ setupCommands.syncVisibility({ forceShow: true });
813
+ logWarn(`models request unauthorized (${message}). Setup command available: /cliproxyapi or /login.`);
729
814
  } else {
730
- // Other failures (network, etc.): still offer setup when not logged in via /login.
731
- setupCommands.syncFromAuth();
815
+ // Other failures (network, etc.): still offer setup for reconfiguration.
816
+ setupCommands.syncVisibility({ forceShow: true });
732
817
  logWarn(
733
- `failed to load models (${message}). Provider remains available via ` +
734
- (setupCommands.isVisible() ? "/cliproxyapi or " : "") +
735
- `/login for reconfiguration.`,
818
+ `failed to load models (${message}). Provider remains available via /cliproxyapi or /login for reconfiguration.`,
736
819
  );
737
820
  }
738
821
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@router-for-me/pi-cliproxyapi-provider",
3
- "version": "1.4.3",
3
+ "version": "1.4.5",
4
4
  "description": "Pi provider extension that auto-registers CLIProxyAPI models, plus TUI elapsed/TPS status",
5
5
  "type": "module",
6
6
  "keywords": [