@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.
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 {
@@ -150,6 +155,44 @@ export function adaptTranscriptContext(context: Context | { messages?: unknown[]
150
155
  };
151
156
  }
152
157
 
158
+ /**
159
+ * Ensure a classic context with top-level systemPrompt/tools is represented as a TranscriptContext.
160
+ * If the context already contains a system message in context.messages, it is returned untouched.
161
+ */
162
+ export function ensureTranscriptContext(context: Context | { messages?: unknown[]; [key: string]: unknown }): Context {
163
+ if (!context || !Array.isArray(context.messages)) return context as Context;
164
+ const hasSystemMessage = (context.messages as Array<{ role?: string }>).some((m) => m && m.role === "system");
165
+ if (hasSystemMessage) return context as Context;
166
+
167
+ const hasSystemPrompt = typeof context.systemPrompt === "string" && context.systemPrompt.length > 0;
168
+ const hasTools = Array.isArray(context.tools) && context.tools.length > 0;
169
+ if (!hasSystemPrompt && !hasTools) return context as Context;
170
+
171
+ return {
172
+ ...(context as Record<string, unknown>),
173
+ messages: [
174
+ {
175
+ role: "system",
176
+ content: context.systemPrompt ?? "",
177
+ ...(hasTools ? { toolsAdded: context.tools } : {}),
178
+ timestamp: 0,
179
+ },
180
+ ...context.messages,
181
+ ] as Context["messages"],
182
+ };
183
+ }
184
+
185
+ export function supportsTranscriptSource(source: string): boolean {
186
+ return source.includes("resolveTranscriptTools") || source.includes("resolveTranscript");
187
+ }
188
+
189
+ export function adaptContextForModule(
190
+ context: Context | { messages?: unknown[]; [key: string]: unknown },
191
+ supportsTranscript: boolean,
192
+ ): Context {
193
+ return supportsTranscript ? ensureTranscriptContext(context) : adaptTranscriptContext(context);
194
+ }
195
+
153
196
  export function withPriorityServiceTier(payload: unknown): unknown {
154
197
  if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
155
198
  return payload;
@@ -176,11 +219,10 @@ export function wrapStreamSimpleForFast(
176
219
  shouldUseFast?: (model: Model<Api>) => boolean,
177
220
  ): CliproxyCodexStreamSimple {
178
221
  return (model, context, streamOptions) => {
179
- const adaptedContext = adaptTranscriptContext(context);
180
222
  if (!shouldUseFast?.(model)) {
181
- return streamSimple(model, adaptedContext, streamOptions);
223
+ return streamSimple(model, context, streamOptions);
182
224
  }
183
- return streamSimple(model, adaptedContext, {
225
+ return streamSimple(model, context, {
184
226
  ...streamOptions,
185
227
  onPayload: (payload, payloadModel) => applyFastPayloadHook(payload, payloadModel, streamOptions?.onPayload),
186
228
  });
@@ -203,40 +245,120 @@ const EXTRACT_ACCOUNT_ID_PATCH = `function extractAccountId(token) {
203
245
  }
204
246
  }`;
205
247
 
206
- function rewriteRelativeImports(source: string, originalDir: string): string {
207
- return source.replace(/from\s+"((?:\.\.?\/)[^"]+)"/g, (_full, relPath: string) => {
208
- const absolute = pathToFileURL(join(originalDir, relPath)).href;
209
- return `from ${JSON.stringify(absolute)}`;
210
- });
248
+ const IMPORT_FROM_SPECIFIER = /from\s+(["'])([^"']+)\1/g;
249
+
250
+ function stripSourceMappingUrl(source: string): string {
251
+ return source.replace(/^\/\/# sourceMappingURL=.*$/gm, "");
211
252
  }
212
253
 
213
- function patchWebSocketOnlyTransport(source: string): string {
214
- const sessionIdExpression = String.raw`(?:options\?\.sessionId|cacheSessionId)`;
215
- const disabledForSession = new RegExp(
216
- 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
+ }),
217
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)`;
218
336
  const retryVariables = /let retriedWebSocketConnectionLimit\s*=\s*false;/;
219
337
  const connectionLimitRetry =
220
338
  /if \(!aborted && connectionLimitBeforeStart && !retriedWebSocketConnectionLimit\) \{\s*retriedWebSocketConnectionLimit = true;\s*continue;\s*\}/;
221
339
  const websocketFailureHandling = new RegExp(
222
340
  String.raw`if \(aborted \|\| \(isCodexNonTransportError\(error\) && !connectionLimitBeforeStart\)\) \{[\s\S]*?recordWebSocketFailure\((${sessionIdExpression}), error\);[\s\S]*?recordWebSocketSseFallback\(\1\);\s*break;`,
223
341
  );
224
- const fallbackSessionRecord = "websocketSseFallbackSessions.add(sessionId);";
225
- 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";';
226
344
 
227
- for (const fragment of [fallbackSessionRecord, fallbackActiveRecord]) {
228
- if (!source.includes(fragment)) {
229
- throw new Error("openai-codex-responses source no longer supports the WebSocket-only transport patch");
230
- }
345
+ if (!source.includes(idleTtlDefinition)) {
346
+ throw new Error("openai-codex-responses source no longer defines SESSION_WEBSOCKET_CACHE_TTL_MS");
347
+ }
348
+ if (!source.includes(transportDefinition)) {
349
+ throw new Error("openai-codex-responses source no longer defines transport");
231
350
  }
232
- for (const pattern of [disabledForSession, retryVariables, connectionLimitRetry, websocketFailureHandling]) {
351
+ for (const pattern of [retryVariables, connectionLimitRetry, websocketFailureHandling]) {
233
352
  if (!pattern.test(source)) {
234
- 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");
235
354
  }
236
355
  }
237
356
 
238
357
  return source
239
- .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
+ )
240
362
  .replace(
241
363
  retryVariables,
242
364
  `let websocketRetries = 0;
@@ -259,16 +381,22 @@ function patchWebSocketOnlyTransport(source: string): string {
259
381
  }
260
382
  appendAssistantMessageDiagnostic(output, createAssistantMessageDiagnostic("provider_transport_failure", error, {
261
383
  configuredTransport: transport,
262
- fallbackTransport: undefined,
384
+ fallbackTransport: websocketStarted ? undefined : "sse",
263
385
  eventsEmitted: websocketStarted,
264
386
  phase: websocketStarted ? "after_message_stream_start" : "before_message_stream_start",
265
387
  requestBytes: new TextEncoder().encode(bodyJson).byteLength,
266
388
  }));
267
389
  recordWebSocketFailure(${activeSessionId}, error);
268
- throw error;`,
390
+ if (websocketStarted) {
391
+ throw error;
392
+ }
393
+ recordWebSocketSseFallback(${activeSessionId});
394
+ break;`,
269
395
  )
270
- .replace(fallbackSessionRecord, "")
271
- .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
+ );
272
400
  }
273
401
 
274
402
  export function patchCodexSource(source: string, providerIds: string[]): string {
@@ -304,9 +432,9 @@ export function patchCodexSource(source: string, providerIds: string[]): string
304
432
  // Keep assistant message api metadata aligned with the registered custom api id.
305
433
  src = src.replaceAll(`api: "openai-codex-responses"`, `api: ${JSON.stringify(CLIPROXYAPI_CODEX_API)}`);
306
434
 
307
- // CLIProxyAPI needs a persistent WebSocket transport. Reconnect before the
308
- // response starts and surface a failure rather than silently switching to SSE.
309
- 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);
310
438
 
311
439
  // The generated module lives outside the original source map directory.
312
440
  src = src.replace(/^\/\/# sourceMappingURL=.*$/gm, "");
@@ -329,21 +457,72 @@ export function resolveCodexModuleFromNodeEntry(entryPath: string): string | und
329
457
  return undefined;
330
458
  }
331
459
 
332
- 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
+ } {
333
497
  // Under pi's extension loader, `@earendil-works/pi-ai` may resolve to dist/compat.js
334
498
  // and package subpath resolve for `/api/*` can fail. Prefer locating the physical
335
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;
336
504
  const candidates: string[] = [];
337
505
 
506
+ // pi bundled Node CLI exposes pi-ai as a virtual module to
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) };
514
+ }
515
+ }
516
+
338
517
  try {
339
- 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");
340
519
  candidates.push(fileURLToPath(subpath));
341
520
  } catch {
342
521
  // ignore and try filesystem candidates
343
522
  }
344
523
 
345
524
  try {
346
- const main = fileURLToPath(import.meta.resolve("@earendil-works/pi-ai"));
525
+ const main = fileURLToPath(resolveSpecifier("@earendil-works/pi-ai"));
347
526
  const distDir = dirname(main);
348
527
  candidates.push(join(distDir, "api/openai-codex-responses.js"));
349
528
  candidates.push(join(distDir, "openai-codex-responses.js"));
@@ -351,14 +530,8 @@ function resolveOriginalCodexModulePath(): { path: string; dir: string } {
351
530
  // ignore
352
531
  }
353
532
 
354
- // pi 0.84.3's bundled Node CLI exposes pi-ai as a virtual module to
355
- // extensions. Resolve its physical nested dependency from the CLI entry so
356
- // the source-patching transport can still read the installed implementation.
357
- if (process.argv[1]) {
358
- const bundledHostModule = resolveCodexModuleFromNodeEntry(process.argv[1]);
359
- if (bundledHostModule) {
360
- candidates.push(bundledHostModule);
361
- }
533
+ if (homeDirectory) {
534
+ candidates.push(...wellKnownCodexModuleCandidates(homeDirectory));
362
535
  }
363
536
 
364
537
  for (const path of candidates) {
@@ -374,39 +547,57 @@ export async function loadCliproxyCodexStreams(
374
547
  providerIds: string[] = ["cliproxyapi"],
375
548
  options: CliproxyCodexStreamOptions = {},
376
549
  ): Promise<CliproxyCodexStreams> {
377
- const { path: originalPath, dir: originalDir } = resolveOriginalCodexModulePath();
550
+ const { path: originalPath } = resolveOriginalCodexModulePath();
378
551
  const originalSource = readFileSync(originalPath, "utf8");
379
- const patched = rewriteRelativeImports(patchCodexSource(originalSource, providerIds), originalDir);
552
+ const patched = patchCodexSource(originalSource, providerIds);
380
553
 
381
- const hash = createHash("sha1").update(patched).digest("hex").slice(0, 16);
382
- const cacheDir = join(tmpdir(), "pi-cliproxyapi-provider");
554
+ const outPath = computePatchedModuleCachePath(originalPath, patched);
555
+ const cacheDir = dirname(outPath);
383
556
  mkdirSync(cacheDir, { recursive: true });
384
- const outPath = join(cacheDir, `openai-codex-responses-cpa-${hash}.mjs`);
385
557
  if (!existsSync(outPath)) {
386
- writeFileSync(outPath, patched, "utf8");
558
+ writePatchedModuleCache(outPath, patched, originalPath);
387
559
  }
388
560
 
389
561
  const mod = (await import(pathToFileURL(outPath).href)) as {
390
562
  streamSimple: CliproxyCodexStreamSimple;
391
563
  stream: CliproxyCodexStreamSimple;
564
+ closeOpenAICodexWebSocketSessions?: CloseCodexWebSocketSessions;
392
565
  };
393
566
 
394
567
  if (typeof mod.streamSimple !== "function" || typeof mod.stream !== "function") {
395
568
  throw new Error("patched openai-codex-responses module missing streamSimple/stream exports");
396
569
  }
397
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
+
582
+ const supportsTranscript = supportsTranscriptSource(originalSource);
583
+ const adaptContext = (context: Context): Context => adaptContextForModule(context, supportsTranscript);
584
+
398
585
  const adaptedStreamSimple: CliproxyCodexStreamSimple = (model, context, streamOptions) => {
399
- return mod.streamSimple(model, adaptTranscriptContext(context), streamOptions);
586
+ return mod.streamSimple(model, adaptContext(context), streamOptions);
400
587
  };
401
588
  const adaptedStream: CliproxyCodexStreamSimple = (model, context, streamOptions) => {
402
- return mod.stream(model, adaptTranscriptContext(context), streamOptions);
589
+ return mod.stream(model, adaptContext(context), streamOptions);
403
590
  };
404
591
 
405
592
  const streamSimple = wrapStreamSimpleForFast(adaptedStreamSimple, options.shouldUseFast);
593
+ const stream = wrapStreamSimpleForFast(adaptedStream, options.shouldUseFast);
406
594
 
407
595
  return {
408
596
  api: CLIPROXYAPI_CODEX_API,
409
597
  streamSimple,
410
- stream: adaptedStream,
598
+ stream,
599
+ rawStreamSimple: adaptedStreamSimple,
600
+ rawStream: adaptedStream,
601
+ closeOpenAICodexWebSocketSessions,
411
602
  };
412
603
  }