@router-for-me/pi-cliproxyapi-provider 1.4.20 → 1.4.22

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));
@@ -721,6 +721,7 @@ export function registerRefreshCommand(options: {
721
721
  const refresh = refreshCoordinator?.begin();
722
722
  const { loaded } = await resolveMappedModels(agentDir, connection.baseUrlInput, connection.apiKey, {
723
723
  forceRefresh: true,
724
+ replaceCache: true,
724
725
  fastMode: fastMode.isEnabled(),
725
726
  signal: refresh?.signal,
726
727
  shouldCommit: refresh ? () => refreshCoordinator?.isCurrent(refresh.generation) ?? true : undefined,
@@ -795,7 +796,11 @@ export default async function (pi: ExtensionAPI): Promise<void> {
795
796
  const fastMode = new FastModeController(fastEnabled);
796
797
  const modelRefreshCoordinator = new ModelRefreshCoordinator();
797
798
 
798
- let streamSimple: CliproxyCodexStreamSimple;
799
+ let streamSimple: CliproxyCodexStreamSimple = () => {
800
+ throw new Error(
801
+ `Codex protocol stream is unavailable for provider: ${identity.providerId} (api: ${CLIPROXYAPI_CODEX_API})`,
802
+ );
803
+ };
799
804
  try {
800
805
  const streams = await loadCliproxyCodexStreams([identity.providerId, "cliproxyapi"], {
801
806
  shouldUseFast: (model) => model.provider === identity.providerId && fastMode.isEffectiveFor(model.id),
@@ -887,7 +892,6 @@ export default async function (pi: ExtensionAPI): Promise<void> {
887
892
  } catch (error) {
888
893
  const message = error instanceof Error ? error.message : String(error);
889
894
  logWarn(`failed to load patched codex protocol: ${message}`);
890
- return;
891
895
  }
892
896
 
893
897
  const fastFooter = new FastFooterController(identity.providerId, fastMode, () =>
@@ -997,7 +1001,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
997
1001
  const connection = resolveConnection(agentDir, identity.providerId);
998
1002
  const registerConfiguredProvider = async (
999
1003
  currentConnection: { baseUrlInput: string; apiKey: string },
1000
- options: { forceRefresh?: boolean } = {},
1004
+ options: { forceRefresh?: boolean; replaceCache?: boolean } = {},
1001
1005
  ): Promise<RefreshResult | undefined> => {
1002
1006
  const refresh = modelRefreshCoordinator.begin();
1003
1007
  try {
@@ -1007,6 +1011,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
1007
1011
  currentConnection.apiKey,
1008
1012
  {
1009
1013
  forceRefresh: options.forceRefresh,
1014
+ replaceCache: options.replaceCache,
1010
1015
  fastMode: fastMode.isEnabled(),
1011
1016
  signal: refresh.signal,
1012
1017
  shouldCommit: () => modelRefreshCoordinator.isCurrent(refresh.generation),
@@ -1098,7 +1103,8 @@ export default async function (pi: ExtensionAPI): Promise<void> {
1098
1103
  streamSimple,
1099
1104
  fastMode,
1100
1105
  refreshCoordinator: modelRefreshCoordinator,
1101
- onRefresh: (currentConnection) => registerConfiguredProvider(currentConnection, { forceRefresh: true }),
1106
+ onRefresh: (currentConnection) =>
1107
+ registerConfiguredProvider(currentConnection, { forceRefresh: true, replaceCache: true }),
1102
1108
  });
1103
1109
 
1104
1110
  if (!connection) {
package/extensions/lib.ts CHANGED
@@ -1043,7 +1043,8 @@ export function mergeModelsWithExistingCache(
1043
1043
 
1044
1044
  /**
1045
1045
  * Load mapped models from the matching cache, or fetch remotely and update the cache.
1046
- * A forced refresh always bypasses the cache.
1046
+ * A forced refresh bypasses the cache read but still retains models missing from the
1047
+ * fresh catalog. replaceCache writes that catalog as-is after a successful fetch.
1047
1048
  */
1048
1049
  export async function resolveMappedModels(
1049
1050
  agentDir: string,
@@ -1051,6 +1052,7 @@ export async function resolveMappedModels(
1051
1052
  apiKey: string,
1052
1053
  options: {
1053
1054
  forceRefresh?: boolean;
1055
+ replaceCache?: boolean;
1054
1056
  fastMode?: boolean;
1055
1057
  signal?: AbortSignal;
1056
1058
  shouldCommit?: () => boolean;
@@ -1061,14 +1063,19 @@ export async function resolveMappedModels(
1061
1063
  options.fastMode === undefined || (cache.fastMode ?? false) === options.fastMode;
1062
1064
 
1063
1065
  const existingCache = loadModelsCache(agentDir, baseUrlInput);
1064
- if (!options.forceRefresh) {
1066
+ if (!options.forceRefresh && !options.replaceCache) {
1065
1067
  if (existingCache && cacheMatchesFastMode(existingCache)) {
1066
1068
  return { loaded: existingCache, fromCache: true };
1067
1069
  }
1068
1070
  }
1069
1071
 
1070
1072
  const fresh = await loadMappedModels(baseUrlInput, apiKey, options.fastMode, agentDir, options.signal);
1071
- const { merged } = mergeModelsWithExistingCache(existingCache, fresh, Date.now(), options.staleTtlMs);
1073
+ const { merged } = mergeModelsWithExistingCache(
1074
+ options.replaceCache ? null : existingCache,
1075
+ fresh,
1076
+ Date.now(),
1077
+ options.staleTtlMs,
1078
+ );
1072
1079
  if (!options.signal?.aborted && (options.shouldCommit?.() ?? true)) {
1073
1080
  saveModelsCache(agentDir, merged);
1074
1081
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@router-for-me/pi-cliproxyapi-provider",
3
- "version": "1.4.20",
3
+ "version": "1.4.22",
4
4
  "description": "Pi provider extension that auto-registers CLIProxyAPI models, plus TUI elapsed/TPS status",
5
5
  "type": "module",
6
6
  "keywords": [