@router-for-me/pi-cliproxyapi-provider 1.4.17 → 1.4.19

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
@@ -12,6 +12,7 @@ Pi provider extension that discovers models from [CLIProxyAPI](https://github.co
12
12
  6. Provides `/fast` to toggle OpenAI priority processing for supported models.
13
13
  7. Caches the model catalog in `~/.pi/agent/cliproxyapi-models.json`, refreshes it in the background on startup, and provides `/cliproxyapi-refresh` to force a refresh.
14
14
  8. In interactive TUI sessions, shows footer elapsed time during runs and a TPS / token usage toast when the agent settles.
15
+ 9. After compaction, closes the reused Codex WebSocket for that session so CLIProxyAPI's server-side context resets with the compacted client messages.
15
16
 
16
17
  ## Install
17
18
 
@@ -241,3 +242,4 @@ Disable just this helper via `pi config` if you only want the CLIProxyAPI provid
241
242
  - non-200 / network / invalid baseUrl → nothing is persisted; re-enter baseUrl + API key
242
243
  - If CPA returns HTTP 200 with zero usable models: login still succeeds; re-run `/login CLIProxyAPI` later after models become available.
243
244
  - 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.
245
+ - After `/compact`, threshold compaction, or overflow recovery, the provider closes the reused Codex WebSocket for the current session. CLIProxyAPI binds server-side context to the connection, so a reused socket would keep reporting a near-full `cacheRead` and retrigger proactive compaction even though the client context is now small. SSE is unaffected because it bills from the request body.
@@ -1,6 +1,6 @@
1
1
  import { type Api, type AssistantMessage, createAssistantMessageEventStream, type Model } from "@earendil-works/pi-ai";
2
2
  import { type ExtensionAPI, SettingsManager } from "@earendil-works/pi-coding-agent";
3
- import type { CliproxyCodexStreamSimple } from "./codex-stream.ts";
3
+ import type { CliproxyCodexStreamSimple, CloseCodexWebSocketSessions } from "./codex-stream.ts";
4
4
 
5
5
  export const PROACTIVE_COMPACTION_ERROR_PREFIX = "context_length_exceeded: proactive compaction threshold reached";
6
6
 
@@ -9,6 +9,91 @@ export interface ProactiveCompactionSettings {
9
9
  reserveTokens: number;
10
10
  }
11
11
 
12
+ export type { CloseCodexWebSocketSessions };
13
+
14
+ const DEFAULT_COMPACTION_ENABLED = true;
15
+ const DEFAULT_COMPACTION_RESERVE_TOKENS = 16384;
16
+
17
+ interface CompatibleSettingsManager {
18
+ reload?: () => Promise<void> | void;
19
+ reloadFromDisk?: () => Promise<void> | void;
20
+ getCompactionSettings?: () => { enabled?: unknown; reserveTokens?: unknown };
21
+ get?: (key: string) => unknown;
22
+ }
23
+
24
+ function isCompatibleSettingsManager(value: unknown): value is CompatibleSettingsManager {
25
+ return typeof value === "object" && value !== null;
26
+ }
27
+
28
+ function isPromiseLike(value: unknown): value is PromiseLike<unknown> {
29
+ return (
30
+ ((typeof value === "object" && value !== null) || typeof value === "function") &&
31
+ typeof (value as { then?: unknown }).then === "function"
32
+ );
33
+ }
34
+
35
+ function normalizeCompactionSettings(enabled: unknown, reserveTokens: unknown): ProactiveCompactionSettings {
36
+ return {
37
+ enabled: typeof enabled === "boolean" ? enabled : DEFAULT_COMPACTION_ENABLED,
38
+ reserveTokens:
39
+ typeof reserveTokens === "number" && Number.isFinite(reserveTokens) && reserveTokens >= 0
40
+ ? reserveTokens
41
+ : DEFAULT_COMPACTION_RESERVE_TOKENS,
42
+ };
43
+ }
44
+
45
+ function readCompactionSettings(manager: CompatibleSettingsManager): ProactiveCompactionSettings | undefined {
46
+ if (typeof manager.getCompactionSettings === "function") {
47
+ try {
48
+ const settings = manager.getCompactionSettings();
49
+ return normalizeCompactionSettings(settings?.enabled, settings?.reserveTokens);
50
+ } catch {
51
+ // Fall through to OMP's key-based settings API when available.
52
+ }
53
+ }
54
+ if (typeof manager.get === "function") {
55
+ try {
56
+ return normalizeCompactionSettings(manager.get("compaction.enabled"), manager.get("compaction.reserveTokens"));
57
+ } catch {
58
+ return undefined;
59
+ }
60
+ }
61
+ return undefined;
62
+ }
63
+
64
+ async function reloadSettings(manager: CompatibleSettingsManager): Promise<void> {
65
+ if (typeof manager.reload === "function") {
66
+ try {
67
+ await manager.reload();
68
+ } catch {
69
+ // Keep the last successfully read settings when disk reload fails.
70
+ }
71
+ return;
72
+ }
73
+ if (typeof manager.reloadFromDisk === "function") {
74
+ try {
75
+ await manager.reloadFromDisk();
76
+ } catch {
77
+ // Keep the last successfully read settings when disk reload fails.
78
+ }
79
+ }
80
+ }
81
+
82
+ /** Session id used to key pi-ai's reused Codex WebSocket. */
83
+ export function resolveCompactionSessionId(source?: {
84
+ sessionId?: unknown;
85
+ sessionManager?: { getSessionId?: () => unknown };
86
+ }): string | undefined {
87
+ const fromManager = source?.sessionManager?.getSessionId?.();
88
+ if (typeof fromManager === "string" && fromManager.trim()) {
89
+ return fromManager;
90
+ }
91
+ if (typeof source?.sessionId === "string" && source.sessionId.trim()) {
92
+ return source.sessionId;
93
+ }
94
+ return undefined;
95
+ }
96
+
12
97
  export function shouldScheduleProactiveCompaction(
13
98
  message: AssistantMessage,
14
99
  contextTokens: number,
@@ -65,24 +150,44 @@ export function createProactiveCompactionStream(model: Model<Api>, contextTokens
65
150
  }
66
151
 
67
152
  export class ProactiveCompactionController {
68
- private settingsManager: SettingsManager | undefined;
153
+ private settingsManager: CompatibleSettingsManager | undefined;
154
+ private cachedCompactionSettings: ProactiveCompactionSettings | undefined;
69
155
  private pending: { modelKey: string; contextTokens: number; threshold: number } | undefined;
156
+ private closeWebSocketSessions: CloseCodexWebSocketSessions | undefined;
70
157
 
71
158
  constructor(
72
159
  private readonly agentDir: string,
73
160
  private readonly providerId: string,
74
- ) {}
161
+ closeWebSocketSessions?: CloseCodexWebSocketSessions,
162
+ ) {
163
+ this.closeWebSocketSessions = closeWebSocketSessions;
164
+ }
165
+
166
+ setCloseWebSocketSessions(closeWebSocketSessions: CloseCodexWebSocketSessions): void {
167
+ this.closeWebSocketSessions = closeWebSocketSessions;
168
+ }
75
169
 
76
170
  register(pi: ExtensionAPI): void {
77
- pi.on("session_start", (_event, ctx) => {
78
- this.settingsManager = SettingsManager.create(ctx.cwd, this.agentDir, {
79
- projectTrusted: ctx.isProjectTrusted(),
80
- });
171
+ pi.on("session_start", async (_event, ctx) => {
172
+ this.cachedCompactionSettings = undefined;
173
+ try {
174
+ const created: unknown = SettingsManager.create(ctx.cwd, this.agentDir, {
175
+ projectTrusted: ctx.isProjectTrusted(),
176
+ });
177
+ const manager = isPromiseLike(created) ? await created : created;
178
+ this.settingsManager = isCompatibleSettingsManager(manager) ? manager : undefined;
179
+ this.cachedCompactionSettings = this.settingsManager
180
+ ? readCompactionSettings(this.settingsManager)
181
+ : undefined;
182
+ } catch {
183
+ this.settingsManager = undefined;
184
+ }
81
185
  this.pending = undefined;
82
186
  });
83
187
 
84
188
  pi.on("session_shutdown", () => {
85
189
  this.settingsManager = undefined;
190
+ this.cachedCompactionSettings = undefined;
86
191
  this.pending = undefined;
87
192
  });
88
193
 
@@ -92,8 +197,12 @@ export class ProactiveCompactionController {
92
197
  this.pending = undefined;
93
198
  });
94
199
 
95
- pi.on("session_compact", () => {
200
+ pi.on("session_compact", (_event, ctx) => {
96
201
  this.pending = undefined;
202
+ // CLIProxyAPI binds server-side Codex context to the WebSocket. Compaction
203
+ // only rewrites the client message list, so reuse would keep cacheRead high
204
+ // and retrigger proactive compaction on a now-small session.
205
+ this.resetWebSocketSession(resolveCompactionSessionId(ctx));
97
206
  });
98
207
 
99
208
  pi.on("agent_settled", () => {
@@ -113,8 +222,15 @@ export class ProactiveCompactionController {
113
222
  if (!settingsManager) {
114
223
  return;
115
224
  }
116
- await settingsManager.reload();
117
- const settings = settingsManager.getCompactionSettings();
225
+ await reloadSettings(settingsManager);
226
+ const refreshedSettings = readCompactionSettings(settingsManager);
227
+ if (refreshedSettings) {
228
+ this.cachedCompactionSettings = refreshedSettings;
229
+ }
230
+ const settings = refreshedSettings ?? this.cachedCompactionSettings;
231
+ if (!settings) {
232
+ return;
233
+ }
118
234
  const contextTokens = ctx.getContextUsage()?.tokens;
119
235
  if (contextTokens === null || contextTokens === undefined) {
120
236
  return;
@@ -132,7 +248,11 @@ export class ProactiveCompactionController {
132
248
  }
133
249
 
134
250
  getCompactionSettings(): ProactiveCompactionSettings | undefined {
135
- return this.settingsManager?.getCompactionSettings();
251
+ const current = this.settingsManager ? readCompactionSettings(this.settingsManager) : undefined;
252
+ if (current) {
253
+ this.cachedCompactionSettings = current;
254
+ }
255
+ return current ?? this.cachedCompactionSettings;
136
256
  }
137
257
 
138
258
  wrapStreamSimple(streamSimple: CliproxyCodexStreamSimple): CliproxyCodexStreamSimple {
@@ -143,10 +263,23 @@ export class ProactiveCompactionController {
143
263
  }
144
264
 
145
265
  this.pending = undefined;
266
+ this.resetWebSocketSession(options?.sessionId);
146
267
  return createProactiveCompactionStream(model, pending.contextTokens, pending.threshold);
147
268
  };
148
269
  }
149
270
 
271
+ private resetWebSocketSession(sessionId?: string): void {
272
+ if (!sessionId || !this.closeWebSocketSessions) {
273
+ return;
274
+ }
275
+ try {
276
+ this.closeWebSocketSessions(sessionId);
277
+ } catch (error) {
278
+ const message = error instanceof Error ? error.message : String(error);
279
+ console.warn(`[pi-cliproxyapi-provider] failed to close Codex WebSocket for session ${sessionId}: ${message}`);
280
+ }
281
+ }
282
+
150
283
  private modelKey(model: Pick<Model<Api>, "provider" | "id">): string {
151
284
  return `${model.provider}/${model.id}`;
152
285
  }
@@ -14,7 +14,7 @@
14
14
 
15
15
  import { createHash } from "node:crypto";
16
16
  import { existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
17
- import { createRequire } from "node:module";
17
+ import { createRequire, isBuiltin } from "node:module";
18
18
  import { tmpdir } from "node:os";
19
19
  import { dirname, join } from "node:path";
20
20
  import { fileURLToPath, pathToFileURL } from "node:url";
@@ -28,10 +28,15 @@ export type CliproxyCodexStreamSimple = (
28
28
  options?: SimpleStreamOptions,
29
29
  ) => AssistantMessageEventStream;
30
30
 
31
+ export type CloseCodexWebSocketSessions = (sessionId?: string) => void;
32
+
31
33
  export type CliproxyCodexStreams = {
32
34
  streamSimple: CliproxyCodexStreamSimple;
33
35
  stream: CliproxyCodexStreamSimple;
36
+ rawStreamSimple: CliproxyCodexStreamSimple;
37
+ rawStream: CliproxyCodexStreamSimple;
34
38
  api: typeof CLIPROXYAPI_CODEX_API;
39
+ closeOpenAICodexWebSocketSessions: CloseCodexWebSocketSessions;
35
40
  };
36
41
 
37
42
  export interface CliproxyCodexStreamOptions {
@@ -240,40 +245,120 @@ const EXTRACT_ACCOUNT_ID_PATCH = `function extractAccountId(token) {
240
245
  }
241
246
  }`;
242
247
 
243
- function rewriteRelativeImports(source: string, originalDir: string): string {
244
- return source.replace(/from\s+"((?:\.\.?\/)[^"]+)"/g, (_full, relPath: string) => {
245
- const absolute = pathToFileURL(join(originalDir, relPath)).href;
246
- return `from ${JSON.stringify(absolute)}`;
247
- });
248
+ const IMPORT_FROM_SPECIFIER = /from\s+(["'])([^"']+)\1/g;
249
+
250
+ function stripSourceMappingUrl(source: string): string {
251
+ return source.replace(/^\/\/# sourceMappingURL=.*$/gm, "");
248
252
  }
249
253
 
250
- function patchWebSocketOnlyTransport(source: string): string {
251
- const sessionIdExpression = String.raw`(?:options\?\.sessionId|cacheSessionId)`;
252
- const disabledForSession = new RegExp(
253
- String.raw`const websocketDisabledForSession\s*=\s*transport !== "sse" && isWebSocketSseFallbackActive\(${sessionIdExpression}\);`,
254
+ const CODEX_MODULE_RELATIVE = join(
255
+ "node_modules",
256
+ "@earendil-works",
257
+ "pi-ai",
258
+ "dist",
259
+ "api",
260
+ "openai-codex-responses.js",
261
+ );
262
+
263
+ /**
264
+ * Well-known filesystem locations for openai-codex-responses.js on bundled hosts.
265
+ *
266
+ * @param homeDirectory - User home used as the root for `.omp` and `.pi` plugin trees
267
+ * @returns Candidate absolute paths in probe order
268
+ */
269
+ export function wellKnownCodexModuleCandidates(homeDirectory: string): string[] {
270
+ return [
271
+ join(homeDirectory, ".omp", "plugins", CODEX_MODULE_RELATIVE),
272
+ join(
273
+ homeDirectory,
274
+ ".omp",
275
+ "plugins",
276
+ "node_modules",
277
+ "@earendil-works",
278
+ "pi-coding-agent",
279
+ CODEX_MODULE_RELATIVE,
280
+ ),
281
+ join(homeDirectory, ".pi", "agent", "npm", CODEX_MODULE_RELATIVE),
282
+ join(
283
+ homeDirectory,
284
+ ".pi",
285
+ "agent",
286
+ "npm",
287
+ "node_modules",
288
+ "@earendil-works",
289
+ "pi-coding-agent",
290
+ CODEX_MODULE_RELATIVE,
291
+ ),
292
+ ];
293
+ }
294
+
295
+ /**
296
+ * Rewrite one module so relative and bare imports become absolute file URLs
297
+ * resolved from `originalPath`'s package graph.
298
+ *
299
+ * @param source - Module source containing `from "..."` specifiers
300
+ * @param originalPath - Physical file used as the resolve base
301
+ * @returns Source with resolvable file URL imports
302
+ */
303
+ export function rewritePatchedModuleImports(source: string, originalPath: string): string {
304
+ const requireFromOriginal = createRequire(pathToFileURL(originalPath));
305
+ const originalDir = dirname(originalPath);
306
+ return stripSourceMappingUrl(
307
+ source.replace(IMPORT_FROM_SPECIFIER, (full, _quote: string, specifier: string) => {
308
+ if (specifier.startsWith("node:") || isBuiltin(specifier)) {
309
+ return full;
310
+ }
311
+ if (specifier.startsWith(".")) {
312
+ return `from ${JSON.stringify(pathToFileURL(join(originalDir, specifier)).href)}`;
313
+ }
314
+ const resolved = requireFromOriginal.resolve(specifier);
315
+ return `from ${JSON.stringify(pathToFileURL(resolved).href)}`;
316
+ }),
254
317
  );
318
+ }
319
+
320
+ /**
321
+ * Write a patched module so a cache file outside the original tree
322
+ * can still resolve bare and relative dependencies.
323
+ *
324
+ * @param outputPath - Destination `.mjs` path, typically under tmpdir
325
+ * @param source - Patched entry source
326
+ * @param originalPath - Physical openai-codex-responses.js used for resolution
327
+ */
328
+ export function writePatchedModuleCache(outputPath: string, source: string, originalPath: string): void {
329
+ mkdirSync(dirname(outputPath), { recursive: true });
330
+ const rewritten = rewritePatchedModuleImports(source, originalPath);
331
+ writeFileSync(outputPath, rewritten, "utf8");
332
+ }
333
+
334
+ function patchWebSocketTransport(source: string): string {
335
+ const sessionIdExpression = String.raw`(?:options\?\.sessionId|cacheSessionId)`;
255
336
  const retryVariables = /let retriedWebSocketConnectionLimit\s*=\s*false;/;
256
337
  const connectionLimitRetry =
257
338
  /if \(!aborted && connectionLimitBeforeStart && !retriedWebSocketConnectionLimit\) \{\s*retriedWebSocketConnectionLimit = true;\s*continue;\s*\}/;
258
339
  const websocketFailureHandling = new RegExp(
259
340
  String.raw`if \(aborted \|\| \(isCodexNonTransportError\(error\) && !connectionLimitBeforeStart\)\) \{[\s\S]*?recordWebSocketFailure\((${sessionIdExpression}), error\);[\s\S]*?recordWebSocketSseFallback\(\1\);\s*break;`,
260
341
  );
261
- const fallbackSessionRecord = "websocketSseFallbackSessions.add(sessionId);";
262
- const fallbackActiveRecord = "stats.websocketFallbackActive = true;";
342
+ const idleTtlDefinition = "const SESSION_WEBSOCKET_CACHE_TTL_MS = 5 * 60 * 1000;";
343
+ const transportDefinition = 'const transport = options?.transport || "auto";';
263
344
 
264
- for (const fragment of [fallbackSessionRecord, fallbackActiveRecord]) {
265
- if (!source.includes(fragment)) {
266
- throw new Error("openai-codex-responses source no longer supports the WebSocket-only transport patch");
267
- }
345
+ if (!source.includes(idleTtlDefinition)) {
346
+ throw new Error("openai-codex-responses source no longer defines SESSION_WEBSOCKET_CACHE_TTL_MS");
268
347
  }
269
- for (const pattern of [disabledForSession, retryVariables, connectionLimitRetry, websocketFailureHandling]) {
348
+ if (!source.includes(transportDefinition)) {
349
+ throw new Error("openai-codex-responses source no longer defines transport");
350
+ }
351
+ for (const pattern of [retryVariables, connectionLimitRetry, websocketFailureHandling]) {
270
352
  if (!pattern.test(source)) {
271
- throw new Error("openai-codex-responses source no longer supports the WebSocket-only transport patch");
353
+ throw new Error("openai-codex-responses source no longer supports the WebSocket transport patch");
272
354
  }
273
355
  }
274
356
 
275
357
  return source
276
- .replace(disabledForSession, "const websocketDisabledForSession = false;")
358
+ .replace(
359
+ transportDefinition,
360
+ 'const transport = (process.env.CLIPROXYAPI_TRANSPORT || options?.transport || "auto");\n options = options ? { ...options, transport } : { transport };',
361
+ )
277
362
  .replace(
278
363
  retryVariables,
279
364
  `let websocketRetries = 0;
@@ -296,16 +381,22 @@ function patchWebSocketOnlyTransport(source: string): string {
296
381
  }
297
382
  appendAssistantMessageDiagnostic(output, createAssistantMessageDiagnostic("provider_transport_failure", error, {
298
383
  configuredTransport: transport,
299
- fallbackTransport: undefined,
384
+ fallbackTransport: websocketStarted ? undefined : "sse",
300
385
  eventsEmitted: websocketStarted,
301
386
  phase: websocketStarted ? "after_message_stream_start" : "before_message_stream_start",
302
387
  requestBytes: new TextEncoder().encode(bodyJson).byteLength,
303
388
  }));
304
389
  recordWebSocketFailure(${activeSessionId}, error);
305
- throw error;`,
390
+ if (websocketStarted) {
391
+ throw error;
392
+ }
393
+ recordWebSocketSseFallback(${activeSessionId});
394
+ break;`,
306
395
  )
307
- .replace(fallbackSessionRecord, "")
308
- .replace(fallbackActiveRecord, "stats.websocketFallbackActive = false;");
396
+ .replace(
397
+ idleTtlDefinition,
398
+ 'const SESSION_WEBSOCKET_CACHE_TTL_MS = (() => { const raw = Number.parseInt(process.env.CLIPROXYAPI_WS_IDLE_TTL_MS || "", 10); return Number.isFinite(raw) && raw > 0 && raw <= 2147483647 ? raw : 30 * 60 * 1000; })();',
399
+ );
309
400
  }
310
401
 
311
402
  export function patchCodexSource(source: string, providerIds: string[]): string {
@@ -341,9 +432,9 @@ export function patchCodexSource(source: string, providerIds: string[]): string
341
432
  // Keep assistant message api metadata aligned with the registered custom api id.
342
433
  src = src.replaceAll(`api: "openai-codex-responses"`, `api: ${JSON.stringify(CLIPROXYAPI_CODEX_API)}`);
343
434
 
344
- // CLIProxyAPI needs a persistent WebSocket transport. Reconnect before the
345
- // response starts and surface a failure rather than silently switching to SSE.
346
- src = patchWebSocketOnlyTransport(src);
435
+ // CLIProxyAPI prefers a persistent WebSocket transport. Reconnect before the
436
+ // response starts, and gracefully fall back to SSE if retries are exhausted.
437
+ src = patchWebSocketTransport(src);
347
438
 
348
439
  // The generated module lives outside the original source map directory.
349
440
  src = src.replace(/^\/\/# sourceMappingURL=.*$/gm, "");
@@ -366,31 +457,72 @@ export function resolveCodexModuleFromNodeEntry(entryPath: string): string | und
366
457
  return undefined;
367
458
  }
368
459
 
369
- function resolveOriginalCodexModulePath(): { path: string; dir: string } {
460
+ export function computePatchedModuleCachePath(
461
+ originalPath: string,
462
+ patchedSource: string,
463
+ cacheDir: string = join(tmpdir(), "pi-cliproxyapi-provider"),
464
+ ): string {
465
+ const hash = createHash("sha1")
466
+ .update("resolved-imports-v2\n")
467
+ .update(originalPath)
468
+ .update("\n")
469
+ .update(patchedSource)
470
+ .digest("hex")
471
+ .slice(0, 16);
472
+ return join(cacheDir, `openai-codex-responses-cpa-${hash}.mjs`);
473
+ }
474
+
475
+ export interface ResolveOriginalCodexModulePathOptions {
476
+ /** Override `import.meta.resolve`. Throw to simulate a bundled host with no package graph. */
477
+ resolveSpecifier?: (specifier: string) => string;
478
+ /** Override `process.argv[1]`. Pass a non-Node host path to skip createRequire success. */
479
+ nodeEntry?: string | undefined;
480
+ /** Override `HOME` / `USERPROFILE` for well-known filesystem fallbacks. */
481
+ homeDirectory?: string | undefined;
482
+ }
483
+
484
+ /**
485
+ * Locate the physical openai-codex-responses.js used as the patch source.
486
+ *
487
+ * Probe order: host nodeEntry, import.meta.resolve, then HOME/well-known paths.
488
+ *
489
+ * @param options - Optional resolve/argv/home overrides for tests and bundled hosts
490
+ * @returns Existing module path and its directory
491
+ * @throws If no candidate exists on disk
492
+ */
493
+ export function resolveOriginalCodexModulePath(options: ResolveOriginalCodexModulePathOptions = {}): {
494
+ path: string;
495
+ dir: string;
496
+ } {
370
497
  // Under pi's extension loader, `@earendil-works/pi-ai` may resolve to dist/compat.js
371
498
  // and package subpath resolve for `/api/*` can fail. Prefer locating the physical
372
499
  // dist file next to the resolved package entry.
500
+ const resolveSpecifier = options.resolveSpecifier ?? ((specifier: string) => import.meta.resolve(specifier));
501
+ const nodeEntry = "nodeEntry" in options ? options.nodeEntry : process.argv[1];
502
+ const homeDirectory =
503
+ "homeDirectory" in options ? options.homeDirectory : process.env.HOME || process.env.USERPROFILE;
373
504
  const candidates: string[] = [];
374
505
 
375
506
  // pi bundled Node CLI exposes pi-ai as a virtual module to
376
- // extensions. Resolve its physical nested dependency from the CLI entry so
377
- // the source-patching transport can still read the installed implementation.
378
- if (process.argv[1]) {
379
- const bundledHostModule = resolveCodexModuleFromNodeEntry(process.argv[1]);
380
- if (bundledHostModule) {
381
- candidates.push(bundledHostModule);
507
+ // extensions. Resolve its physical nested dependency from the CLI entry first so
508
+ // the extension shares the exact same module instances (e.g. session resources) with the host.
509
+ // Oh My Pi Mach-O hosts do not have a Node entry at argv[1]; skip quietly.
510
+ if (nodeEntry) {
511
+ const bundledHostModule = resolveCodexModuleFromNodeEntry(nodeEntry);
512
+ if (bundledHostModule && existsSync(bundledHostModule)) {
513
+ return { path: bundledHostModule, dir: dirname(bundledHostModule) };
382
514
  }
383
515
  }
384
516
 
385
517
  try {
386
- const subpath = import.meta.resolve("@earendil-works/pi-ai/api/openai-codex-responses");
518
+ const subpath = resolveSpecifier("@earendil-works/pi-ai/api/openai-codex-responses");
387
519
  candidates.push(fileURLToPath(subpath));
388
520
  } catch {
389
521
  // ignore and try filesystem candidates
390
522
  }
391
523
 
392
524
  try {
393
- const main = fileURLToPath(import.meta.resolve("@earendil-works/pi-ai"));
525
+ const main = fileURLToPath(resolveSpecifier("@earendil-works/pi-ai"));
394
526
  const distDir = dirname(main);
395
527
  candidates.push(join(distDir, "api/openai-codex-responses.js"));
396
528
  candidates.push(join(distDir, "openai-codex-responses.js"));
@@ -398,6 +530,10 @@ function resolveOriginalCodexModulePath(): { path: string; dir: string } {
398
530
  // ignore
399
531
  }
400
532
 
533
+ if (homeDirectory) {
534
+ candidates.push(...wellKnownCodexModuleCandidates(homeDirectory));
535
+ }
536
+
401
537
  for (const path of candidates) {
402
538
  if (path && existsSync(path)) {
403
539
  return { path, dir: dirname(path) };
@@ -411,27 +547,38 @@ export async function loadCliproxyCodexStreams(
411
547
  providerIds: string[] = ["cliproxyapi"],
412
548
  options: CliproxyCodexStreamOptions = {},
413
549
  ): Promise<CliproxyCodexStreams> {
414
- const { path: originalPath, dir: originalDir } = resolveOriginalCodexModulePath();
550
+ const { path: originalPath } = resolveOriginalCodexModulePath();
415
551
  const originalSource = readFileSync(originalPath, "utf8");
416
- const patched = rewriteRelativeImports(patchCodexSource(originalSource, providerIds), originalDir);
552
+ const patched = patchCodexSource(originalSource, providerIds);
417
553
 
418
- const hash = createHash("sha1").update(patched).digest("hex").slice(0, 16);
419
- const cacheDir = join(tmpdir(), "pi-cliproxyapi-provider");
554
+ const outPath = computePatchedModuleCachePath(originalPath, patched);
555
+ const cacheDir = dirname(outPath);
420
556
  mkdirSync(cacheDir, { recursive: true });
421
- const outPath = join(cacheDir, `openai-codex-responses-cpa-${hash}.mjs`);
422
557
  if (!existsSync(outPath)) {
423
- writeFileSync(outPath, patched, "utf8");
558
+ writePatchedModuleCache(outPath, patched, originalPath);
424
559
  }
425
560
 
426
561
  const mod = (await import(pathToFileURL(outPath).href)) as {
427
562
  streamSimple: CliproxyCodexStreamSimple;
428
563
  stream: CliproxyCodexStreamSimple;
564
+ closeOpenAICodexWebSocketSessions?: CloseCodexWebSocketSessions;
429
565
  };
430
566
 
431
567
  if (typeof mod.streamSimple !== "function" || typeof mod.stream !== "function") {
432
568
  throw new Error("patched openai-codex-responses module missing streamSimple/stream exports");
433
569
  }
434
570
 
571
+ // Must come from the patched module: its WebSocket cache is a separate Map
572
+ // from the stock @earendil-works/pi-ai openai-codex-responses instance.
573
+ const closeOpenAICodexWebSocketSessions =
574
+ typeof mod.closeOpenAICodexWebSocketSessions === "function"
575
+ ? mod.closeOpenAICodexWebSocketSessions
576
+ : () => {
577
+ console.warn(
578
+ "[pi-cliproxyapi-provider] patched openai-codex-responses module is missing closeOpenAICodexWebSocketSessions export",
579
+ );
580
+ };
581
+
435
582
  const supportsTranscript = supportsTranscriptSource(originalSource);
436
583
  const adaptContext = (context: Context): Context => adaptContextForModule(context, supportsTranscript);
437
584
 
@@ -443,10 +590,14 @@ export async function loadCliproxyCodexStreams(
443
590
  };
444
591
 
445
592
  const streamSimple = wrapStreamSimpleForFast(adaptedStreamSimple, options.shouldUseFast);
593
+ const stream = wrapStreamSimpleForFast(adaptedStream, options.shouldUseFast);
446
594
 
447
595
  return {
448
596
  api: CLIPROXYAPI_CODEX_API,
449
597
  streamSimple,
450
- stream: adaptedStream,
598
+ stream,
599
+ rawStreamSimple: adaptedStreamSimple,
600
+ rawStream: adaptedStream,
601
+ closeOpenAICodexWebSocketSessions,
451
602
  };
452
603
  }
@@ -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,32 @@ 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
+ if (activeContext) {
917
+ checkAndNotifyStaleModel(activeContext);
918
+ }
919
+ scheduleActiveRecovery();
920
+ } else {
921
+ notifiedStaleModelId = undefined;
922
+ modelRefreshCoordinator.clearRecovery();
923
+ }
924
+ };
925
+
653
926
  // Always register oauth so the provider is visible in /login immediately after install.
654
927
  registerProvider(pi, {
655
928
  providerId: identity.providerId,
@@ -661,12 +934,50 @@ export default async function (pi: ExtensionAPI): Promise<void> {
661
934
  fastMode,
662
935
  refreshCoordinator: modelRefreshCoordinator,
663
936
  onFastModeChange: onFastModeChange,
937
+ onRefreshOutcome: handleRefreshOutcome,
664
938
  });
665
939
  registerTransientNetworkErrorRetry(pi, identity.providerId);
666
940
 
941
+ let activeContext: ExtensionContext | undefined;
942
+ let latestStaleModelIds: string[] = [];
943
+ let notifiedStaleModelId: string | undefined;
944
+
945
+ const checkAndNotifyStaleModel = (ctx: ExtensionContext): void => {
946
+ const currentModel = ctx.model;
947
+ const configured = loadConfiguredDefaultSettings(agentDir);
948
+ const affectedStaleId = latestStaleModelIds.find(
949
+ (staleId) =>
950
+ (currentModel && currentModel.provider === identity.providerId && currentModel.id === staleId) ||
951
+ isModelReferencedAsDefault(configured, staleId, identity.providerId),
952
+ );
953
+
954
+ if (affectedStaleId) {
955
+ if (notifiedStaleModelId !== affectedStaleId) {
956
+ notifiedStaleModelId = affectedStaleId;
957
+ ctx.ui.notify(
958
+ `Model '${affectedStaleId}' is temporarily unavailable from upstream (retaining cached entry).`,
959
+ "warning",
960
+ );
961
+ }
962
+ } else {
963
+ notifiedStaleModelId = undefined;
964
+ }
965
+ };
966
+
967
+ pi.on("session_start", (_event, ctx) => {
968
+ activeContext = ctx;
969
+ checkAndNotifyStaleModel(ctx);
970
+ });
971
+ pi.on("session_shutdown", () => {
972
+ activeContext = undefined;
973
+ latestStaleModelIds = [];
974
+ notifiedStaleModelId = undefined;
975
+ modelRefreshCoordinator.stop();
976
+ });
977
+
667
978
  const connection = resolveConnection(agentDir, identity.providerId);
668
979
  const registerConfiguredProvider = async (
669
- currentConnection: NonNullable<ReturnType<typeof resolveConnection>>,
980
+ currentConnection: { baseUrlInput: string; apiKey: string },
670
981
  options: { forceRefresh?: boolean } = {},
671
982
  ): Promise<RefreshResult | undefined> => {
672
983
  const refresh = modelRefreshCoordinator.begin();
@@ -702,18 +1013,37 @@ export default async function (pi: ExtensionAPI): Promise<void> {
702
1013
  fastMode,
703
1014
  refreshCoordinator: modelRefreshCoordinator,
704
1015
  onFastModeChange,
1016
+ onRefreshOutcome: handleRefreshOutcome,
705
1017
  });
706
1018
 
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
- });
1019
+ if (fromCache) {
1020
+ const cachedStaleModels = loaded.models.filter((m) => m.stale);
1021
+ if (cachedStaleModels.length > 0) {
1022
+ latestStaleModelIds = cachedStaleModels.map((m) => m.id);
1023
+ if (activeContext) {
1024
+ checkAndNotifyStaleModel(activeContext);
1025
+ }
1026
+ }
1027
+ if (!options.forceRefresh) {
1028
+ void registerConfiguredProvider(currentConnection, { forceRefresh: true }).catch((error) => {
1029
+ const message = error instanceof Error ? error.message : String(error);
1030
+ logWarn(`failed to refresh cached models (${message}); keeping the cached model list.`);
1031
+ });
1032
+ }
1033
+ } else {
1034
+ handleRefreshOutcome(loaded);
712
1035
  }
713
1036
 
714
- return { modelCount: loaded.models.length, modelsUrl: loaded.modelsUrl };
1037
+ return {
1038
+ modelCount: loaded.models.length,
1039
+ modelsUrl: loaded.modelsUrl,
1040
+ staleCount: loaded.models.filter((m) => m.stale).length,
1041
+ };
715
1042
  } catch (error) {
716
1043
  if (!modelRefreshCoordinator.isCurrent(refresh.generation)) return undefined;
1044
+ if (options.forceRefresh) {
1045
+ scheduleActiveRecovery();
1046
+ }
717
1047
  throw error;
718
1048
  }
719
1049
  };
package/extensions/lib.ts CHANGED
@@ -71,6 +71,9 @@ export interface CodexClientModel {
71
71
  description?: string;
72
72
  context_window?: number;
73
73
  max_context_window?: number;
74
+ max_tokens?: number;
75
+ max_output_tokens?: number;
76
+ max_completion_tokens?: number;
74
77
  input_modalities?: string[];
75
78
  supported_reasoning_levels?: CodexReasoningLevel[] | string[];
76
79
  default_service_tier?: string | null;
@@ -110,6 +113,9 @@ export interface PiProviderModel {
110
113
  contextWindow: number;
111
114
  maxTokens: number;
112
115
  thinkingLevelMap?: ThinkingLevelMap;
116
+ stale?: boolean;
117
+ lastSeenAt?: number;
118
+ staleSince?: number;
113
119
  }
114
120
 
115
121
  export interface MappedModels {
@@ -253,6 +259,52 @@ export function loadConfigFile(agentDir: string): CliproxyConfigFile {
253
259
  }
254
260
  }
255
261
 
262
+ export const SETTINGS_FILE_NAME = "settings.json";
263
+
264
+ export interface ConfiguredDefaultModelSettings {
265
+ defaultProvider?: string;
266
+ defaultModel?: string;
267
+ }
268
+
269
+ export function loadConfiguredDefaultSettings(agentDir: string): ConfiguredDefaultModelSettings {
270
+ const settingsPath = join(agentDir, SETTINGS_FILE_NAME);
271
+ try {
272
+ const parsed = JSON.parse(readFileSync(settingsPath, "utf8")) as Record<string, unknown>;
273
+ return {
274
+ defaultProvider:
275
+ typeof parsed.defaultProvider === "string" && parsed.defaultProvider.trim()
276
+ ? parsed.defaultProvider.trim()
277
+ : undefined,
278
+ defaultModel:
279
+ typeof parsed.defaultModel === "string" && parsed.defaultModel.trim()
280
+ ? parsed.defaultModel.trim()
281
+ : undefined,
282
+ };
283
+ } catch {
284
+ return {};
285
+ }
286
+ }
287
+
288
+ export function isModelReferencedAsDefault(
289
+ configured: ConfiguredDefaultModelSettings | string | undefined,
290
+ modelId: string,
291
+ providerId: string,
292
+ ): boolean {
293
+ if (!configured) return false;
294
+ const settings: ConfiguredDefaultModelSettings =
295
+ typeof configured === "string" ? { defaultModel: configured } : configured;
296
+
297
+ if (!settings.defaultModel) return false;
298
+ const trimmed = settings.defaultModel.trim();
299
+ if (trimmed === `${providerId}/${modelId}` || trimmed === `${providerId}:${modelId}`) {
300
+ return true;
301
+ }
302
+ if (trimmed === modelId) {
303
+ return settings.defaultProvider === undefined || settings.defaultProvider === providerId;
304
+ }
305
+ return false;
306
+ }
307
+
256
308
  export function saveConfigFile(agentDir: string, config: CliproxyConfigFile): void {
257
309
  const configPath = join(agentDir, CONFIG_FILE_NAME);
258
310
  mkdirSync(dirname(configPath), { recursive: true });
@@ -487,6 +539,22 @@ export function toPiModel(
487
539
  ? matchModelCost(id, costCatalog, fastMode && supportsFastServiceTier(model))
488
540
  : { ...ZERO_COST };
489
541
 
542
+ const maxTokens =
543
+ (typeof model.max_tokens === "number" && Number.isFinite(model.max_tokens) && model.max_tokens > 0
544
+ ? model.max_tokens
545
+ : undefined) ??
546
+ (typeof model.max_output_tokens === "number" &&
547
+ Number.isFinite(model.max_output_tokens) &&
548
+ model.max_output_tokens > 0
549
+ ? model.max_output_tokens
550
+ : undefined) ??
551
+ (typeof model.max_completion_tokens === "number" &&
552
+ Number.isFinite(model.max_completion_tokens) &&
553
+ model.max_completion_tokens > 0
554
+ ? model.max_completion_tokens
555
+ : undefined) ??
556
+ DEFAULT_MAX_TOKENS;
557
+
490
558
  return {
491
559
  id,
492
560
  name: (model.display_name ?? model.name ?? id).trim() || id,
@@ -494,7 +562,7 @@ export function toPiModel(
494
562
  input: buildInputModalities(model),
495
563
  cost,
496
564
  contextWindow,
497
- maxTokens: DEFAULT_MAX_TOKENS,
565
+ maxTokens,
498
566
  thinkingLevelMap: buildThinkingLevelMap(efforts),
499
567
  };
500
568
  }
@@ -884,6 +952,95 @@ export async function loadMappedModels(
884
952
  };
885
953
  }
886
954
 
955
+ export const DEFAULT_MODEL_STALE_TTL_MS = 7 * 24 * 60 * 60 * 1000;
956
+
957
+ export interface MergeModelsResult {
958
+ merged: MappedModels;
959
+ retainedStaleModels: PiProviderModel[];
960
+ droppedModelIds: string[];
961
+ }
962
+
963
+ /**
964
+ * Merge newly fetched models with the existing disk cache to prevent transient
965
+ * upstream pruning (such as HTTP 503 / 429 capacity blips) from wiping out valid models.
966
+ */
967
+ export function mergeModelsWithExistingCache(
968
+ existingCache: ModelsCacheFile | null,
969
+ fresh: MappedModels,
970
+ now = Date.now(),
971
+ staleTtlMs = DEFAULT_MODEL_STALE_TTL_MS,
972
+ ): MergeModelsResult {
973
+ if (!existingCache || !Array.isArray(existingCache.models) || existingCache.models.length === 0) {
974
+ const modelsWithTimestamp = fresh.models.map((model) => ({
975
+ ...model,
976
+ lastSeenAt: now,
977
+ stale: false,
978
+ }));
979
+ return {
980
+ merged: {
981
+ ...fresh,
982
+ models: modelsWithTimestamp,
983
+ },
984
+ retainedStaleModels: [],
985
+ droppedModelIds: [],
986
+ };
987
+ }
988
+
989
+ const freshModelMap = new Map<string, PiProviderModel>();
990
+ const freshFastSet = new Set(fresh.fastModelIds);
991
+
992
+ for (const model of fresh.models) {
993
+ const updated: PiProviderModel = {
994
+ ...model,
995
+ lastSeenAt: now,
996
+ stale: false,
997
+ };
998
+ delete updated.staleSince;
999
+ freshModelMap.set(model.id, updated);
1000
+ }
1001
+
1002
+ const retainedStaleModels: PiProviderModel[] = [];
1003
+ const droppedModelIds: string[] = [];
1004
+
1005
+ for (const prevModel of existingCache.models) {
1006
+ if (freshModelMap.has(prevModel.id)) {
1007
+ continue;
1008
+ }
1009
+ const lastSeen = prevModel.lastSeenAt ?? existingCache.fetchedAt ?? now;
1010
+ const isFirstMissing = prevModel.stale !== true;
1011
+ const staleSince = isFirstMissing ? now : (prevModel.staleSince ?? lastSeen);
1012
+
1013
+ // Retain models from the moment they first go missing until they have been
1014
+ // missing across the full stale retention window.
1015
+ if (now - staleSince < staleTtlMs) {
1016
+ const retained: PiProviderModel = {
1017
+ ...prevModel,
1018
+ lastSeenAt: lastSeen,
1019
+ staleSince,
1020
+ stale: true,
1021
+ };
1022
+ retainedStaleModels.push(retained);
1023
+ if (existingCache.fastModelIds?.includes(prevModel.id) && !freshFastSet.has(prevModel.id)) {
1024
+ freshFastSet.add(prevModel.id);
1025
+ }
1026
+ } else {
1027
+ droppedModelIds.push(prevModel.id);
1028
+ }
1029
+ }
1030
+
1031
+ const mergedModels = [...freshModelMap.values(), ...retainedStaleModels];
1032
+
1033
+ return {
1034
+ merged: {
1035
+ ...fresh,
1036
+ models: mergedModels,
1037
+ fastModelIds: Array.from(freshFastSet),
1038
+ },
1039
+ retainedStaleModels,
1040
+ droppedModelIds,
1041
+ };
1042
+ }
1043
+
887
1044
  /**
888
1045
  * Load mapped models from the matching cache, or fetch remotely and update the cache.
889
1046
  * A forced refresh always bypasses the cache.
@@ -897,21 +1054,23 @@ export async function resolveMappedModels(
897
1054
  fastMode?: boolean;
898
1055
  signal?: AbortSignal;
899
1056
  shouldCommit?: () => boolean;
1057
+ staleTtlMs?: number;
900
1058
  } = {},
901
1059
  ): Promise<ResolvedModelsResult> {
902
1060
  const cacheMatchesFastMode = (cache: ModelsCacheFile): boolean =>
903
1061
  options.fastMode === undefined || (cache.fastMode ?? false) === options.fastMode;
904
1062
 
1063
+ const existingCache = loadModelsCache(agentDir, baseUrlInput);
905
1064
  if (!options.forceRefresh) {
906
- const cache = loadModelsCache(agentDir, baseUrlInput);
907
- if (cache && cacheMatchesFastMode(cache)) {
908
- return { loaded: cache, fromCache: true };
1065
+ if (existingCache && cacheMatchesFastMode(existingCache)) {
1066
+ return { loaded: existingCache, fromCache: true };
909
1067
  }
910
1068
  }
911
1069
 
912
- const loaded = await loadMappedModels(baseUrlInput, apiKey, options.fastMode, agentDir, options.signal);
1070
+ const fresh = await loadMappedModels(baseUrlInput, apiKey, options.fastMode, agentDir, options.signal);
1071
+ const { merged } = mergeModelsWithExistingCache(existingCache, fresh, Date.now(), options.staleTtlMs);
913
1072
  if (!options.signal?.aborted && (options.shouldCommit?.() ?? true)) {
914
- saveModelsCache(agentDir, loaded);
1073
+ saveModelsCache(agentDir, merged);
915
1074
  }
916
- return { loaded, fromCache: false };
1075
+ return { loaded: merged, fromCache: false };
917
1076
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@router-for-me/pi-cliproxyapi-provider",
3
- "version": "1.4.17",
3
+ "version": "1.4.19",
4
4
  "description": "Pi provider extension that auto-registers CLIProxyAPI models, plus TUI elapsed/TPS status",
5
5
  "type": "module",
6
6
  "keywords": [