@router-for-me/pi-cliproxyapi-provider 1.4.16 → 1.4.18

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.
@@ -18,10 +18,22 @@
18
18
  * Non-interactive setup still works via env vars or ~/.pi/agent/cliproxyapi.json.
19
19
  */
20
20
 
21
- import type { Api, Model, OAuthCredentials, OAuthLoginCallbacks } from "@earendil-works/pi-ai";
21
+ import type {
22
+ Api,
23
+ Model,
24
+ OAuthCredentials,
25
+ OAuthLoginCallbacks,
26
+ SimpleStreamOptions,
27
+ StreamFunction,
28
+ } from "@earendil-works/pi-ai";
22
29
  import { type ExtensionAPI, type ExtensionContext, getAgentDir } from "@earendil-works/pi-coding-agent";
23
30
  import { ProactiveCompactionController } from "./auto-compact.ts";
24
- import { CLIPROXYAPI_CODEX_API, type CliproxyCodexStreamSimple, loadCliproxyCodexStreams } from "./codex-stream.ts";
31
+ import {
32
+ applyFastPayloadHook,
33
+ CLIPROXYAPI_CODEX_API,
34
+ type CliproxyCodexStreamSimple,
35
+ loadCliproxyCodexStreams,
36
+ } from "./codex-stream.ts";
25
37
  import { FastModeController } from "./fast.ts";
26
38
  import { FastFooterController } from "./fast-footer.ts";
27
39
  import {
@@ -31,9 +43,12 @@ import {
31
43
  decodeRefreshMeta,
32
44
  encodeRefreshMeta,
33
45
  firstNonEmpty,
46
+ isModelReferencedAsDefault,
34
47
  isUnauthorizedModelsError,
35
48
  loadAuthConnection,
36
49
  loadConfigFile,
50
+ loadConfiguredDefaultSettings,
51
+ type MappedModels,
37
52
  type PiProviderModel,
38
53
  resolveConnection,
39
54
  resolveEndpoints,
@@ -58,13 +73,28 @@ class ConfigPersistenceError extends Error {
58
73
  interface RefreshResult {
59
74
  modelCount: number;
60
75
  modelsUrl: string;
76
+ staleCount?: number;
77
+ }
78
+
79
+ export const DEFAULT_AUTO_RECOVERY_DELAY_MS = 60_000;
80
+ export const MAX_AUTO_RECOVERY_DELAY_MS = 300_000;
81
+
82
+ export interface RecoverySnapshot {
83
+ action: () => Promise<unknown>;
84
+ attempt: number;
85
+ delayMs: number;
61
86
  }
62
87
 
63
88
  class ModelRefreshCoordinator {
64
89
  private generation = 0;
65
90
  private activeController: AbortController | undefined;
91
+ private recoveryTimer: NodeJS.Timeout | undefined;
92
+ private recoveryAttempt = 0;
93
+ private activeRecovery: RecoverySnapshot | undefined;
94
+ private stopped = false;
66
95
 
67
96
  begin(): { generation: number; signal: AbortSignal } {
97
+ this.clearRecoveryTimer();
68
98
  this.activeController?.abort();
69
99
  const controller = new AbortController();
70
100
  this.activeController = controller;
@@ -73,7 +103,73 @@ class ModelRefreshCoordinator {
73
103
  }
74
104
 
75
105
  isCurrent(generation: number): boolean {
76
- return this.generation === generation;
106
+ return !this.stopped && this.generation === generation;
107
+ }
108
+
109
+ scheduleRecovery(
110
+ action: () => Promise<unknown>,
111
+ baseDelayMs = DEFAULT_AUTO_RECOVERY_DELAY_MS,
112
+ maxDelayMs = MAX_AUTO_RECOVERY_DELAY_MS,
113
+ ): void {
114
+ if (this.stopped) return;
115
+ this.clearRecoveryTimer();
116
+ const delay = Math.min(baseDelayMs * 1.5 ** this.recoveryAttempt, maxDelayMs);
117
+ this.recoveryAttempt += 1;
118
+ this.activeRecovery = { action, attempt: this.recoveryAttempt, delayMs: delay };
119
+
120
+ this.recoveryTimer = setTimeout(() => {
121
+ this.recoveryTimer = undefined;
122
+ if (this.stopped) return;
123
+ void action().catch((error) => {
124
+ const message = error instanceof Error ? error.message : String(error);
125
+ logWarn(`auto-recovery refresh failed (${message}); will retry`);
126
+ });
127
+ }, delay);
128
+ this.recoveryTimer.unref?.();
129
+ }
130
+
131
+ snapshotRecovery(): RecoverySnapshot | undefined {
132
+ if (!this.stopped && this.activeRecovery) {
133
+ return { ...this.activeRecovery };
134
+ }
135
+ return undefined;
136
+ }
137
+
138
+ restoreRecovery(snapshot: RecoverySnapshot): void {
139
+ if (this.stopped || !snapshot) return;
140
+ this.clearRecoveryTimer();
141
+ this.recoveryAttempt = snapshot.attempt;
142
+ this.activeRecovery = snapshot;
143
+ this.recoveryTimer = setTimeout(() => {
144
+ this.recoveryTimer = undefined;
145
+ if (this.stopped) return;
146
+ void snapshot.action().catch((error) => {
147
+ const message = error instanceof Error ? error.message : String(error);
148
+ logWarn(`auto-recovery refresh failed (${message}); will retry`);
149
+ });
150
+ }, snapshot.delayMs);
151
+ this.recoveryTimer.unref?.();
152
+ }
153
+
154
+ clearRecoveryTimer(): void {
155
+ if (this.recoveryTimer) {
156
+ clearTimeout(this.recoveryTimer);
157
+ this.recoveryTimer = undefined;
158
+ }
159
+ }
160
+
161
+ clearRecovery(): void {
162
+ this.clearRecoveryTimer();
163
+ this.recoveryAttempt = 0;
164
+ this.activeRecovery = undefined;
165
+ }
166
+
167
+ stop(): void {
168
+ this.stopped = true;
169
+ this.clearRecovery();
170
+ this.activeController?.abort();
171
+ this.activeController = undefined;
172
+ this.generation += 1;
77
173
  }
78
174
  }
79
175
 
@@ -85,6 +181,45 @@ function logInfo(message: string): void {
85
181
  console.info(`[pi-cliproxyapi-provider] ${message}`);
86
182
  }
87
183
 
184
+ const COMPAT_COORDINATOR_KEY = Symbol.for("pi-cliproxyapi-provider.compat-coordinator");
185
+ export const COMPAT_SOURCE_ID = "pi-cliproxyapi-provider-global";
186
+
187
+ interface CompatRegistrationEntry {
188
+ instanceId: string;
189
+ providerId: string;
190
+ rawStream: CliproxyCodexStreamSimple;
191
+ rawStreamSimple: CliproxyCodexStreamSimple;
192
+ }
193
+
194
+ interface CompatCoordinator {
195
+ stack: CompatRegistrationEntry[];
196
+ }
197
+
198
+ function getCompatCoordinator(): CompatCoordinator {
199
+ const globalState = globalThis as unknown as { [COMPAT_COORDINATOR_KEY]?: CompatCoordinator };
200
+ if (!globalState[COMPAT_COORDINATOR_KEY]) {
201
+ globalState[COMPAT_COORDINATOR_KEY] = { stack: [] };
202
+ }
203
+ return globalState[COMPAT_COORDINATOR_KEY]!;
204
+ }
205
+
206
+ export function resetCompatCoordinator(): void {
207
+ const coordinator = getCompatCoordinator();
208
+ coordinator.stack = [];
209
+ }
210
+
211
+ function findActiveCompatEntry(
212
+ stack: CompatRegistrationEntry[],
213
+ providerId: string,
214
+ ): CompatRegistrationEntry | undefined {
215
+ for (let i = stack.length - 1; i >= 0; i--) {
216
+ if (stack[i].providerId === providerId) {
217
+ return stack[i];
218
+ }
219
+ }
220
+ return undefined;
221
+ }
222
+
88
223
  function hasLoginCredential(agentDir: string, providerId: string): boolean {
89
224
  try {
90
225
  return Boolean(loadAuthConnection(agentDir, providerId)?.apiKey);
@@ -166,6 +301,7 @@ async function configureAndRegister(options: {
166
301
  fastMode: FastModeController;
167
302
  refreshCoordinator: ModelRefreshCoordinator;
168
303
  onFastModeChange?: (enabled: boolean, ctx: ExtensionContext) => Promise<void>;
304
+ onRefreshOutcome?: (loaded: MappedModels) => void;
169
305
  }): Promise<RefreshResult> {
170
306
  const {
171
307
  pi,
@@ -179,6 +315,7 @@ async function configureAndRegister(options: {
179
315
  fastMode,
180
316
  refreshCoordinator,
181
317
  onFastModeChange,
318
+ onRefreshOutcome,
182
319
  } = options;
183
320
 
184
321
  const refresh = refreshCoordinator.begin();
@@ -216,10 +353,18 @@ async function configureAndRegister(options: {
216
353
  fastMode,
217
354
  refreshCoordinator,
218
355
  onFastModeChange,
356
+ onRefreshOutcome,
219
357
  });
220
358
  fastMode.setSupportedModelIds(loaded.fastModelIds);
221
359
 
222
- return { modelCount: loaded.models.length, modelsUrl: loaded.modelsUrl };
360
+ onRefreshOutcome?.(loaded);
361
+ const staleModels = loaded.models.filter((m) => m.stale);
362
+
363
+ return {
364
+ modelCount: loaded.models.length,
365
+ modelsUrl: loaded.modelsUrl,
366
+ staleCount: staleModels.length,
367
+ };
223
368
  }
224
369
 
225
370
  function createOAuthHandlers(options: {
@@ -232,6 +377,7 @@ function createOAuthHandlers(options: {
232
377
  fastMode: FastModeController;
233
378
  refreshCoordinator: ModelRefreshCoordinator;
234
379
  onFastModeChange?: (enabled: boolean, ctx: ExtensionContext) => Promise<void>;
380
+ onRefreshOutcome?: (loaded: MappedModels) => void;
235
381
  }) {
236
382
  const {
237
383
  pi,
@@ -243,6 +389,7 @@ function createOAuthHandlers(options: {
243
389
  fastMode,
244
390
  refreshCoordinator,
245
391
  onFastModeChange,
392
+ onRefreshOutcome,
246
393
  } = options;
247
394
 
248
395
  return {
@@ -259,6 +406,7 @@ function createOAuthHandlers(options: {
259
406
  });
260
407
 
261
408
  callbacks.onProgress?.("Validating credentials via models endpoint...");
409
+ const previousRecovery = refreshCoordinator.snapshotRecovery();
262
410
  try {
263
411
  const result = await configureAndRegister({
264
412
  pi,
@@ -272,11 +420,15 @@ function createOAuthHandlers(options: {
272
420
  fastMode,
273
421
  refreshCoordinator,
274
422
  onFastModeChange,
423
+ onRefreshOutcome,
275
424
  });
276
425
 
277
426
  logInfo(`login ok: registered ${result.modelCount} models from ${result.modelsUrl}`);
278
427
  return buildOAuthCredentials(baseUrlInput, apiKey);
279
428
  } catch (error) {
429
+ if (previousRecovery) {
430
+ refreshCoordinator.restoreRecovery(previousRecovery);
431
+ }
280
432
  const message = error instanceof Error ? error.message : String(error);
281
433
  logWarn(`login validation failed: ${message}`);
282
434
  if (error instanceof ConfigPersistenceError) {
@@ -333,6 +485,7 @@ function registerProvider(
333
485
  fastMode: FastModeController;
334
486
  refreshCoordinator?: ModelRefreshCoordinator;
335
487
  onFastModeChange?: (enabled: boolean, ctx: ExtensionContext) => Promise<void>;
488
+ onRefreshOutcome?: (loaded: MappedModels) => void;
336
489
  },
337
490
  ): void {
338
491
  const {
@@ -346,6 +499,7 @@ function registerProvider(
346
499
  streamSimple,
347
500
  fastMode,
348
501
  onFastModeChange,
502
+ onRefreshOutcome,
349
503
  } = options;
350
504
  const refreshCoordinator = options.refreshCoordinator ?? new ModelRefreshCoordinator();
351
505
 
@@ -360,6 +514,7 @@ function registerProvider(
360
514
  fastMode,
361
515
  refreshCoordinator,
362
516
  onFastModeChange,
517
+ onRefreshOutcome,
363
518
  });
364
519
 
365
520
  // Replace any previous registration so an earlier ambient apiKey does not linger
@@ -577,10 +732,19 @@ export function registerRefreshCommand(options: {
577
732
  refreshCoordinator,
578
733
  });
579
734
 
580
- result = { modelCount: loaded.models.length, modelsUrl: loaded.modelsUrl };
735
+ result = {
736
+ modelCount: loaded.models.length,
737
+ modelsUrl: loaded.modelsUrl,
738
+ staleCount: loaded.models.filter((m) => m.stale).length,
739
+ };
581
740
  }
582
741
 
583
- ctx.ui.notify(`Refreshed ${result.modelCount} CLIProxyAPI models from ${result.modelsUrl}.`, "info");
742
+ const staleSuffix =
743
+ result.staleCount && result.staleCount > 0 ? ` (${result.staleCount} retained from cache)` : "";
744
+ ctx.ui.notify(
745
+ `Refreshed ${result.modelCount} CLIProxyAPI models${staleSuffix} from ${result.modelsUrl}.`,
746
+ "info",
747
+ );
584
748
  } catch (error) {
585
749
  const message = error instanceof Error ? error.message : String(error);
586
750
  ctx.ui.notify(`Failed to refresh CLIProxyAPI models: ${message}`, "error");
@@ -626,7 +790,90 @@ export default async function (pi: ExtensionAPI): Promise<void> {
626
790
  const streams = await loadCliproxyCodexStreams([identity.providerId, "cliproxyapi"], {
627
791
  shouldUseFast: (model) => model.provider === identity.providerId && fastMode.isEffectiveFor(model.id),
628
792
  });
793
+ proactiveCompaction.setCloseWebSocketSessions(streams.closeOpenAICodexWebSocketSessions);
629
794
  streamSimple = proactiveCompaction.wrapStreamSimple(streams.streamSimple);
795
+
796
+ pi.on("session_shutdown", () => {
797
+ try {
798
+ streams.closeOpenAICodexWebSocketSessions();
799
+ } catch (error) {
800
+ const message = error instanceof Error ? error.message : String(error);
801
+ logWarn(`failed to close Codex WebSocket sessions on shutdown: ${message}`);
802
+ }
803
+ });
804
+
805
+ try {
806
+ const { registerApiProvider, unregisterApiProviders } = await import("@earendil-works/pi-ai/compat");
807
+
808
+ const coordinator = getCompatCoordinator();
809
+ const instanceId = `${identity.providerId}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
810
+
811
+ const entry: CompatRegistrationEntry = {
812
+ instanceId,
813
+ providerId: identity.providerId,
814
+ rawStream: streams.rawStream,
815
+ rawStreamSimple: streams.rawStreamSimple,
816
+ };
817
+
818
+ coordinator.stack.push(entry);
819
+
820
+ const dispatchStream: CliproxyCodexStreamSimple = (model, context, options) => {
821
+ const active = findActiveCompatEntry(coordinator.stack, model.provider);
822
+ if (!active) {
823
+ throw new Error(
824
+ `No active provider stream handler registered for provider: ${model.provider} (api: ${CLIPROXYAPI_CODEX_API})`,
825
+ );
826
+ }
827
+ const shouldFast = (options as any)?.serviceTier === "priority" || (options as any)?.fast === true;
828
+ if (shouldFast) {
829
+ return active.rawStream(model, context, {
830
+ ...options,
831
+ onPayload: (payload, payloadModel) => applyFastPayloadHook(payload, payloadModel, options?.onPayload),
832
+ });
833
+ }
834
+ return active.rawStream(model, context, options);
835
+ };
836
+
837
+ const dispatchStreamSimple: CliproxyCodexStreamSimple = (model, context, options) => {
838
+ const active = findActiveCompatEntry(coordinator.stack, model.provider);
839
+ if (!active) {
840
+ throw new Error(
841
+ `No active provider streamSimple handler registered for provider: ${model.provider} (api: ${CLIPROXYAPI_CODEX_API})`,
842
+ );
843
+ }
844
+ const shouldFast = (options as any)?.serviceTier === "priority" || (options as any)?.fast === true;
845
+ if (shouldFast) {
846
+ return active.rawStreamSimple(model, context, {
847
+ ...options,
848
+ onPayload: (payload, payloadModel) => applyFastPayloadHook(payload, payloadModel, options?.onPayload),
849
+ });
850
+ }
851
+ return active.rawStreamSimple(model, context, options);
852
+ };
853
+
854
+ unregisterApiProviders(COMPAT_SOURCE_ID);
855
+ registerApiProvider(
856
+ {
857
+ api: CLIPROXYAPI_CODEX_API,
858
+ stream: dispatchStream as StreamFunction<typeof CLIPROXYAPI_CODEX_API>,
859
+ streamSimple: dispatchStreamSimple as StreamFunction<typeof CLIPROXYAPI_CODEX_API, SimpleStreamOptions>,
860
+ },
861
+ COMPAT_SOURCE_ID,
862
+ );
863
+
864
+ pi.on("session_shutdown", () => {
865
+ const index = coordinator.stack.findIndex((item) => item.instanceId === instanceId);
866
+ if (index !== -1) {
867
+ coordinator.stack.splice(index, 1);
868
+ }
869
+ if (coordinator.stack.length === 0) {
870
+ unregisterApiProviders(COMPAT_SOURCE_ID);
871
+ }
872
+ });
873
+ } catch (error) {
874
+ const message = error instanceof Error ? error.message : String(error);
875
+ logWarn(`failed to register compat API provider: ${message}`);
876
+ }
630
877
  } catch (error) {
631
878
  const message = error instanceof Error ? error.message : String(error);
632
879
  logWarn(`failed to load patched codex protocol: ${message}`);
@@ -650,6 +897,35 @@ export default async function (pi: ExtensionAPI): Promise<void> {
650
897
  });
651
898
  fastFooter.register(pi);
652
899
 
900
+ const scheduleActiveRecovery = (): void => {
901
+ modelRefreshCoordinator.scheduleRecovery(async () => {
902
+ const activeConn = resolveConnection(agentDir, identity.providerId);
903
+ if (!activeConn) {
904
+ modelRefreshCoordinator.clearRecovery();
905
+ return;
906
+ }
907
+ await registerConfiguredProvider(activeConn, { forceRefresh: true });
908
+ }, DEFAULT_AUTO_RECOVERY_DELAY_MS);
909
+ };
910
+
911
+ const handleRefreshOutcome = (loaded: MappedModels): void => {
912
+ const staleModels = loaded.models.filter((m) => m.stale);
913
+ latestStaleModelIds = staleModels.map((m) => m.id);
914
+
915
+ if (staleModels.length > 0) {
916
+ logWarn(
917
+ `upstream catalog omitted ${staleModels.length} model(s) (${latestStaleModelIds.join(", ")}); retaining cached entries temporarily.`,
918
+ );
919
+ if (activeContext) {
920
+ checkAndNotifyStaleModel(activeContext);
921
+ }
922
+ scheduleActiveRecovery();
923
+ } else {
924
+ notifiedStaleModelId = undefined;
925
+ modelRefreshCoordinator.clearRecovery();
926
+ }
927
+ };
928
+
653
929
  // Always register oauth so the provider is visible in /login immediately after install.
654
930
  registerProvider(pi, {
655
931
  providerId: identity.providerId,
@@ -661,12 +937,50 @@ export default async function (pi: ExtensionAPI): Promise<void> {
661
937
  fastMode,
662
938
  refreshCoordinator: modelRefreshCoordinator,
663
939
  onFastModeChange: onFastModeChange,
940
+ onRefreshOutcome: handleRefreshOutcome,
664
941
  });
665
942
  registerTransientNetworkErrorRetry(pi, identity.providerId);
666
943
 
944
+ let activeContext: ExtensionContext | undefined;
945
+ let latestStaleModelIds: string[] = [];
946
+ let notifiedStaleModelId: string | undefined;
947
+
948
+ const checkAndNotifyStaleModel = (ctx: ExtensionContext): void => {
949
+ const currentModel = ctx.model;
950
+ const configured = loadConfiguredDefaultSettings(agentDir);
951
+ const affectedStaleId = latestStaleModelIds.find(
952
+ (staleId) =>
953
+ (currentModel && currentModel.provider === identity.providerId && currentModel.id === staleId) ||
954
+ isModelReferencedAsDefault(configured, staleId, identity.providerId),
955
+ );
956
+
957
+ if (affectedStaleId) {
958
+ if (notifiedStaleModelId !== affectedStaleId) {
959
+ notifiedStaleModelId = affectedStaleId;
960
+ ctx.ui.notify(
961
+ `Model '${affectedStaleId}' is temporarily unavailable from upstream (retaining cached entry).`,
962
+ "warning",
963
+ );
964
+ }
965
+ } else {
966
+ notifiedStaleModelId = undefined;
967
+ }
968
+ };
969
+
970
+ pi.on("session_start", (_event, ctx) => {
971
+ activeContext = ctx;
972
+ checkAndNotifyStaleModel(ctx);
973
+ });
974
+ pi.on("session_shutdown", () => {
975
+ activeContext = undefined;
976
+ latestStaleModelIds = [];
977
+ notifiedStaleModelId = undefined;
978
+ modelRefreshCoordinator.stop();
979
+ });
980
+
667
981
  const connection = resolveConnection(agentDir, identity.providerId);
668
982
  const registerConfiguredProvider = async (
669
- currentConnection: NonNullable<ReturnType<typeof resolveConnection>>,
983
+ currentConnection: { baseUrlInput: string; apiKey: string },
670
984
  options: { forceRefresh?: boolean } = {},
671
985
  ): Promise<RefreshResult | undefined> => {
672
986
  const refresh = modelRefreshCoordinator.begin();
@@ -702,18 +1016,37 @@ export default async function (pi: ExtensionAPI): Promise<void> {
702
1016
  fastMode,
703
1017
  refreshCoordinator: modelRefreshCoordinator,
704
1018
  onFastModeChange,
1019
+ onRefreshOutcome: handleRefreshOutcome,
705
1020
  });
706
1021
 
707
- if (fromCache && !options.forceRefresh) {
708
- void registerConfiguredProvider(currentConnection, { forceRefresh: true }).catch((error) => {
709
- const message = error instanceof Error ? error.message : String(error);
710
- logWarn(`failed to refresh cached models (${message}); keeping the cached model list.`);
711
- });
1022
+ if (fromCache) {
1023
+ const cachedStaleModels = loaded.models.filter((m) => m.stale);
1024
+ if (cachedStaleModels.length > 0) {
1025
+ latestStaleModelIds = cachedStaleModels.map((m) => m.id);
1026
+ if (activeContext) {
1027
+ checkAndNotifyStaleModel(activeContext);
1028
+ }
1029
+ }
1030
+ if (!options.forceRefresh) {
1031
+ void registerConfiguredProvider(currentConnection, { forceRefresh: true }).catch((error) => {
1032
+ const message = error instanceof Error ? error.message : String(error);
1033
+ logWarn(`failed to refresh cached models (${message}); keeping the cached model list.`);
1034
+ });
1035
+ }
1036
+ } else {
1037
+ handleRefreshOutcome(loaded);
712
1038
  }
713
1039
 
714
- return { modelCount: loaded.models.length, modelsUrl: loaded.modelsUrl };
1040
+ return {
1041
+ modelCount: loaded.models.length,
1042
+ modelsUrl: loaded.modelsUrl,
1043
+ staleCount: loaded.models.filter((m) => m.stale).length,
1044
+ };
715
1045
  } catch (error) {
716
1046
  if (!modelRefreshCoordinator.isCurrent(refresh.generation)) return undefined;
1047
+ if (options.forceRefresh) {
1048
+ scheduleActiveRecovery();
1049
+ }
717
1050
  throw error;
718
1051
  }
719
1052
  };