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

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.
@@ -13,10 +13,10 @@
13
13
  */
14
14
 
15
15
  import { createHash } from "node:crypto";
16
- import { existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
16
+ import { existsSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
17
17
  import { createRequire, isBuiltin } from "node:module";
18
- import { tmpdir } from "node:os";
19
- import { dirname, join } from "node:path";
18
+ import { homedir, tmpdir } from "node:os";
19
+ import { dirname, join, resolve } from "node:path";
20
20
  import { fileURLToPath, pathToFileURL } from "node:url";
21
21
  import type { Api, AssistantMessageEventStream, Context, Model, SimpleStreamOptions } from "@earendil-works/pi-ai";
22
22
 
@@ -289,6 +289,57 @@ export function wellKnownCodexModuleCandidates(homeDirectory: string): string[]
289
289
  "pi-coding-agent",
290
290
  CODEX_MODULE_RELATIVE,
291
291
  ),
292
+ join(homeDirectory, ".bun", "install", "global", CODEX_MODULE_RELATIVE),
293
+ join(
294
+ homeDirectory,
295
+ ".bun",
296
+ "install",
297
+ "global",
298
+ "node_modules",
299
+ "@earendil-works",
300
+ "pi-coding-agent",
301
+ CODEX_MODULE_RELATIVE,
302
+ ),
303
+ join(homeDirectory, ".npm-global", CODEX_MODULE_RELATIVE),
304
+ join(homeDirectory, ".npm-global", "lib", CODEX_MODULE_RELATIVE),
305
+ join(
306
+ homeDirectory,
307
+ ".npm-global",
308
+ "lib",
309
+ "node_modules",
310
+ "@earendil-works",
311
+ "pi-coding-agent",
312
+ CODEX_MODULE_RELATIVE,
313
+ ),
314
+ join(homeDirectory, "Library", "pnpm", "global", "5", CODEX_MODULE_RELATIVE),
315
+ join(
316
+ homeDirectory,
317
+ "Library",
318
+ "pnpm",
319
+ "global",
320
+ "5",
321
+ "node_modules",
322
+ "@earendil-works",
323
+ "pi-coding-agent",
324
+ CODEX_MODULE_RELATIVE,
325
+ ),
326
+ join(homeDirectory, ".local", "share", "pnpm", "global", "5", CODEX_MODULE_RELATIVE),
327
+ join(
328
+ homeDirectory,
329
+ ".local",
330
+ "share",
331
+ "pnpm",
332
+ "global",
333
+ "5",
334
+ "node_modules",
335
+ "@earendil-works",
336
+ "pi-coding-agent",
337
+ CODEX_MODULE_RELATIVE,
338
+ ),
339
+ join("/usr", "local", "lib", CODEX_MODULE_RELATIVE),
340
+ join("/usr", "local", "lib", "node_modules", "@earendil-works", "pi-coding-agent", CODEX_MODULE_RELATIVE),
341
+ join("/opt", "homebrew", "lib", CODEX_MODULE_RELATIVE),
342
+ join("/opt", "homebrew", "lib", "node_modules", "@earendil-works", "pi-coding-agent", CODEX_MODULE_RELATIVE),
292
343
  ];
293
344
  }
294
345
 
@@ -443,16 +494,54 @@ export function patchCodexSource(source: string, providerIds: string[]): string
443
494
  }
444
495
 
445
496
  export function resolveCodexModuleFromNodeEntry(entryPath: string): string | undefined {
446
- try {
447
- const require = createRequire(pathToFileURL(realpathSync(entryPath)));
448
- for (const nodeModulesDir of require.resolve.paths("@earendil-works/pi-ai") ?? []) {
449
- const candidate = join(nodeModulesDir, "@earendil-works", "pi-ai", "dist", "api", "openai-codex-responses.js");
450
- if (existsSync(candidate)) {
451
- return candidate;
497
+ const visited = new Set<string>();
498
+ const queue = [entryPath];
499
+
500
+ while (queue.length > 0) {
501
+ const current = queue.shift();
502
+ if (!current || visited.has(current)) continue;
503
+ visited.add(current);
504
+
505
+ try {
506
+ if (!existsSync(current)) continue;
507
+ const real = realpathSync(current);
508
+ const require = createRequire(pathToFileURL(real));
509
+ for (const nodeModulesDir of require.resolve.paths("@earendil-works/pi-ai") ?? []) {
510
+ const candidate = join(
511
+ nodeModulesDir,
512
+ "@earendil-works",
513
+ "pi-ai",
514
+ "dist",
515
+ "api",
516
+ "openai-codex-responses.js",
517
+ );
518
+ if (existsSync(candidate)) {
519
+ return candidate;
520
+ }
521
+ }
522
+
523
+ // If current is a small text script (wrapper / trampoline), inspect it for referenced entry paths or imports
524
+ if (statSync(real).size < 8192) {
525
+ const content = readFileSync(real, "utf8");
526
+ // Look for path-like string literals (e.g. "/foo/bar", "./cli.js", "../dist/cli.js")
527
+ const pathMatches = content.matchAll(/["'`]((\/|[A-Za-z]:[\\/]|\.{1,2}[\\/])[^"'`\r\n]+)["'`]/g);
528
+ for (const match of pathMatches) {
529
+ const ref = match[1]?.trim();
530
+ if (ref) {
531
+ queue.push(resolve(dirname(real), ref));
532
+ }
533
+ }
534
+ const homeJoinMatch = content.match(
535
+ /join\s*\(\s*(?:homedir\(\)|process\.env\.HOME)[^)]*["']([^"']+)["']\s*\)/,
536
+ );
537
+ if (homeJoinMatch) {
538
+ const home = process.env.HOME || process.env.USERPROFILE || homedir();
539
+ queue.push(join(home, homeJoinMatch[1]));
540
+ }
452
541
  }
542
+ } catch {
543
+ // Ignore invalid or unavailable runtime entrypoints.
453
544
  }
454
- } catch {
455
- // Ignore invalid or unavailable runtime entrypoints.
456
545
  }
457
546
  return undefined;
458
547
  }
@@ -514,6 +603,25 @@ export function resolveOriginalCodexModulePath(options: ResolveOriginalCodexModu
514
603
  }
515
604
  }
516
605
 
606
+ // Also check well-known CLI binaries if nodeEntry wasn't explicitly provided in options
607
+ if (!("nodeEntry" in options) && homeDirectory) {
608
+ const wellKnownEntries = [
609
+ join(homeDirectory, ".bun", "bin", "pi"),
610
+ join(homeDirectory, ".local", "bin", "pi"),
611
+ join(homeDirectory, ".npm-global", "bin", "pi"),
612
+ "/usr/local/bin/pi",
613
+ "/opt/homebrew/bin/pi",
614
+ ];
615
+ for (const entry of wellKnownEntries) {
616
+ if (entry !== nodeEntry && existsSync(entry)) {
617
+ const bundledHostModule = resolveCodexModuleFromNodeEntry(entry);
618
+ if (bundledHostModule && existsSync(bundledHostModule)) {
619
+ return { path: bundledHostModule, dir: dirname(bundledHostModule) };
620
+ }
621
+ }
622
+ }
623
+ }
624
+
517
625
  try {
518
626
  const subpath = resolveSpecifier("@earendil-works/pi-ai/api/openai-codex-responses");
519
627
  candidates.push(fileURLToPath(subpath));
@@ -122,7 +122,12 @@ class ModelRefreshCoordinator {
122
122
  if (this.stopped) return;
123
123
  void action().catch((error) => {
124
124
  const message = error instanceof Error ? error.message : String(error);
125
- logWarn(`auto-recovery refresh failed (${message}); will retry`);
125
+ if (message.includes("is stale after session replacement or reload")) {
126
+ this.clearRecovery();
127
+ return;
128
+ }
129
+ // Suppressed: logging this into the TUI corrupts the display.
130
+ // The refresh path already reschedules the next attempt.
126
131
  });
127
132
  }, delay);
128
133
  this.recoveryTimer.unref?.();
@@ -145,7 +150,12 @@ class ModelRefreshCoordinator {
145
150
  if (this.stopped) return;
146
151
  void snapshot.action().catch((error) => {
147
152
  const message = error instanceof Error ? error.message : String(error);
148
- logWarn(`auto-recovery refresh failed (${message}); will retry`);
153
+ if (message.includes("is stale after session replacement or reload")) {
154
+ this.clearRecovery();
155
+ return;
156
+ }
157
+ // Suppressed: logging this into the TUI corrupts the display.
158
+ // The refresh path already reschedules the next attempt.
149
159
  });
150
160
  }, snapshot.delayMs);
151
161
  this.recoveryTimer.unref?.();
@@ -785,7 +795,11 @@ export default async function (pi: ExtensionAPI): Promise<void> {
785
795
  const fastMode = new FastModeController(fastEnabled);
786
796
  const modelRefreshCoordinator = new ModelRefreshCoordinator();
787
797
 
788
- let streamSimple: CliproxyCodexStreamSimple;
798
+ let streamSimple: CliproxyCodexStreamSimple = () => {
799
+ throw new Error(
800
+ `Codex protocol stream is unavailable for provider: ${identity.providerId} (api: ${CLIPROXYAPI_CODEX_API})`,
801
+ );
802
+ };
789
803
  try {
790
804
  const streams = await loadCliproxyCodexStreams([identity.providerId, "cliproxyapi"], {
791
805
  shouldUseFast: (model) => model.provider === identity.providerId && fastMode.isEffectiveFor(model.id),
@@ -877,7 +891,6 @@ export default async function (pi: ExtensionAPI): Promise<void> {
877
891
  } catch (error) {
878
892
  const message = error instanceof Error ? error.message : String(error);
879
893
  logWarn(`failed to load patched codex protocol: ${message}`);
880
- return;
881
894
  }
882
895
 
883
896
  const fastFooter = new FastFooterController(identity.providerId, fastMode, () =>
@@ -943,24 +956,33 @@ export default async function (pi: ExtensionAPI): Promise<void> {
943
956
  let notifiedStaleModelId: string | undefined;
944
957
 
945
958
  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
- );
959
+ try {
960
+ const currentModel = ctx.model;
961
+ const configured = loadConfiguredDefaultSettings(agentDir);
962
+ const affectedStaleId = latestStaleModelIds.find(
963
+ (staleId) =>
964
+ (currentModel && currentModel.provider === identity.providerId && currentModel.id === staleId) ||
965
+ isModelReferencedAsDefault(configured, staleId, identity.providerId),
966
+ );
953
967
 
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
- );
968
+ if (affectedStaleId) {
969
+ if (notifiedStaleModelId !== affectedStaleId) {
970
+ notifiedStaleModelId = affectedStaleId;
971
+ ctx.ui.notify(
972
+ `Model '${affectedStaleId}' is temporarily unavailable from upstream (retaining cached entry).`,
973
+ "warning",
974
+ );
975
+ }
976
+ } else {
977
+ notifiedStaleModelId = undefined;
961
978
  }
962
- } else {
963
- notifiedStaleModelId = undefined;
979
+ } catch (error) {
980
+ const message = error instanceof Error ? error.message : String(error);
981
+ if (message.includes("is stale after session replacement or reload")) {
982
+ activeContext = undefined;
983
+ return;
984
+ }
985
+ throw error;
964
986
  }
965
987
  };
966
988
 
@@ -1041,6 +1063,11 @@ export default async function (pi: ExtensionAPI): Promise<void> {
1041
1063
  };
1042
1064
  } catch (error) {
1043
1065
  if (!modelRefreshCoordinator.isCurrent(refresh.generation)) return undefined;
1066
+ const message = error instanceof Error ? error.message : String(error);
1067
+ if (message.includes("is stale after session replacement or reload")) {
1068
+ modelRefreshCoordinator.clearRecovery();
1069
+ return undefined;
1070
+ }
1044
1071
  if (options.forceRefresh) {
1045
1072
  scheduleActiveRecovery();
1046
1073
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@router-for-me/pi-cliproxyapi-provider",
3
- "version": "1.4.19",
3
+ "version": "1.4.21",
4
4
  "description": "Pi provider extension that auto-registers CLIProxyAPI models, plus TUI elapsed/TPS status",
5
5
  "type": "module",
6
6
  "keywords": [