@router-for-me/pi-cliproxyapi-provider 1.4.9 → 1.4.11
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 +53 -31
- package/extensions/fast-footer.ts +27 -4
- package/extensions/index.ts +372 -39
- package/extensions/lib.ts +457 -7
- package/extensions/pause.ts +65 -0
- package/extensions/retry.ts +3 -2
- package/extensions/tps.ts +23 -4
- package/package.json +1 -1
package/extensions/lib.ts
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
5
|
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
6
|
+
import { tmpdir } from "node:os";
|
|
6
7
|
import { dirname, join } from "node:path";
|
|
7
8
|
import { readStoredCredential } from "@earendil-works/pi-coding-agent";
|
|
8
9
|
|
|
@@ -15,11 +16,14 @@ export const DEFAULT_PROVIDER_ID = "cliproxyapi";
|
|
|
15
16
|
export const DEFAULT_PROVIDER_NAME = "CLIProxyAPI";
|
|
16
17
|
export const DEFAULT_BASE_URL = "http://127.0.0.1:8317";
|
|
17
18
|
export const CONFIG_FILE_NAME = "cliproxyapi.json";
|
|
19
|
+
export const MODELS_CACHE_FILE_NAME = "cliproxyapi-models.json";
|
|
18
20
|
export const AUTH_FILE_NAME = "auth.json";
|
|
19
21
|
export const CLIENT_VERSION = "pi";
|
|
22
|
+
export const MODELS_REQUEST_TIMEOUT_MS = 60_000;
|
|
20
23
|
|
|
21
24
|
/** Keep login credentials effectively permanent; reconfigure via /login. */
|
|
22
25
|
export const CREDENTIAL_TTL_MS = 100 * 365 * 24 * 60 * 60 * 1000;
|
|
26
|
+
export const MODELS_DEV_CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
|
|
23
27
|
|
|
24
28
|
export const ZERO_COST = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 } as const;
|
|
25
29
|
export const DEFAULT_MAX_TOKENS = 16384;
|
|
@@ -33,6 +37,7 @@ export interface CliproxyConfigFile {
|
|
|
33
37
|
providerId?: string;
|
|
34
38
|
providerName?: string;
|
|
35
39
|
fast?: boolean;
|
|
40
|
+
pause?: boolean;
|
|
36
41
|
}
|
|
37
42
|
|
|
38
43
|
export interface ResolvedIdentity {
|
|
@@ -79,17 +84,78 @@ export interface CodexClientModelsResponse {
|
|
|
79
84
|
data?: CodexClientModel[];
|
|
80
85
|
}
|
|
81
86
|
|
|
87
|
+
export interface PiProviderCostTier {
|
|
88
|
+
input: number;
|
|
89
|
+
output: number;
|
|
90
|
+
cacheRead: number;
|
|
91
|
+
cacheWrite: number;
|
|
92
|
+
/** Apply this rate when total input-side usage is above this threshold. */
|
|
93
|
+
inputTokensAbove: number;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export interface PiProviderCost {
|
|
97
|
+
input: number;
|
|
98
|
+
output: number;
|
|
99
|
+
cacheRead: number;
|
|
100
|
+
cacheWrite: number;
|
|
101
|
+
tiers?: PiProviderCostTier[];
|
|
102
|
+
}
|
|
103
|
+
|
|
82
104
|
export interface PiProviderModel {
|
|
83
105
|
id: string;
|
|
84
106
|
name: string;
|
|
85
107
|
reasoning: boolean;
|
|
86
108
|
input: Array<"text" | "image">;
|
|
87
|
-
cost:
|
|
109
|
+
cost: PiProviderCost;
|
|
88
110
|
contextWindow: number;
|
|
89
111
|
maxTokens: number;
|
|
90
112
|
thinkingLevelMap?: ThinkingLevelMap;
|
|
91
113
|
}
|
|
92
114
|
|
|
115
|
+
export interface MappedModels {
|
|
116
|
+
models: PiProviderModel[];
|
|
117
|
+
fastModelIds: string[];
|
|
118
|
+
inferenceBaseUrl: string;
|
|
119
|
+
modelsUrl: string;
|
|
120
|
+
fastMode?: boolean;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export interface ModelsCacheFile extends MappedModels {
|
|
124
|
+
fetchedAt: number;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
interface ModelsDevCostPayload {
|
|
128
|
+
input?: unknown;
|
|
129
|
+
output?: unknown;
|
|
130
|
+
cache_read?: unknown;
|
|
131
|
+
cache_write?: unknown;
|
|
132
|
+
tiers?: unknown;
|
|
133
|
+
context_over_200k?: unknown;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
interface ModelsDevModePayload {
|
|
137
|
+
cost?: ModelsDevCostPayload;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
interface ModelsDevModelPayload {
|
|
141
|
+
cost?: ModelsDevCostPayload;
|
|
142
|
+
experimental?: {
|
|
143
|
+
modes?: Record<string, ModelsDevModePayload | undefined>;
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export interface ModelsDevCostEntry {
|
|
148
|
+
providerId: string;
|
|
149
|
+
modelId: string;
|
|
150
|
+
standard: PiProviderCost;
|
|
151
|
+
fast?: PiProviderCost;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export interface ModelsDevCostCatalog {
|
|
155
|
+
exact: Map<string, ModelsDevCostEntry[]>;
|
|
156
|
+
normalized: Map<string, ModelsDevCostEntry[]>;
|
|
157
|
+
}
|
|
158
|
+
|
|
93
159
|
export interface OAuthRefreshMeta {
|
|
94
160
|
baseUrl: string;
|
|
95
161
|
}
|
|
@@ -199,6 +265,32 @@ export function saveConfigFile(agentDir: string, config: CliproxyConfigFile): vo
|
|
|
199
265
|
writeFileSync(configPath, `${JSON.stringify(next, null, 2)}\n`, "utf8");
|
|
200
266
|
}
|
|
201
267
|
|
|
268
|
+
export function loadModelsCache(agentDir: string, baseUrlInput: string): ModelsCacheFile | null {
|
|
269
|
+
const cachePath = join(agentDir, MODELS_CACHE_FILE_NAME);
|
|
270
|
+
try {
|
|
271
|
+
const parsed = JSON.parse(readFileSync(cachePath, "utf8")) as Partial<ModelsCacheFile>;
|
|
272
|
+
const endpoints = resolveEndpoints(baseUrlInput);
|
|
273
|
+
if (
|
|
274
|
+
typeof parsed.fetchedAt !== "number" ||
|
|
275
|
+
parsed.modelsUrl !== endpoints.modelsUrl ||
|
|
276
|
+
parsed.inferenceBaseUrl !== endpoints.inferenceBaseUrl ||
|
|
277
|
+
!Array.isArray(parsed.models) ||
|
|
278
|
+
!Array.isArray(parsed.fastModelIds)
|
|
279
|
+
) {
|
|
280
|
+
return null;
|
|
281
|
+
}
|
|
282
|
+
return parsed as ModelsCacheFile;
|
|
283
|
+
} catch {
|
|
284
|
+
return null;
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
export function saveModelsCache(agentDir: string, loaded: MappedModels, fetchedAt = Date.now()): void {
|
|
289
|
+
const cachePath = join(agentDir, MODELS_CACHE_FILE_NAME);
|
|
290
|
+
mkdirSync(dirname(cachePath), { recursive: true });
|
|
291
|
+
writeFileSync(cachePath, `${JSON.stringify({ ...loaded, fetchedAt }, null, 2)}\n`, "utf8");
|
|
292
|
+
}
|
|
293
|
+
|
|
202
294
|
export function loadAuthConnection(agentDir: string, providerId: string): { baseUrl?: string; apiKey?: string } | null {
|
|
203
295
|
const entry = readStoredCredential(providerId, join(agentDir, AUTH_FILE_NAME));
|
|
204
296
|
if (entry?.type === "oauth" && typeof entry.access === "string" && entry.access.trim()) {
|
|
@@ -267,6 +359,18 @@ export function resolveFastDefault(agentDir: string): boolean {
|
|
|
267
359
|
return file.fast;
|
|
268
360
|
}
|
|
269
361
|
|
|
362
|
+
/** Resolve the request pause preference from cliproxyapi.json, defaulting to false. */
|
|
363
|
+
export function resolvePauseDefault(agentDir: string): boolean {
|
|
364
|
+
const file = loadConfigFile(agentDir);
|
|
365
|
+
if (file.pause === undefined) {
|
|
366
|
+
return false;
|
|
367
|
+
}
|
|
368
|
+
if (typeof file.pause !== "boolean") {
|
|
369
|
+
throw new Error(`${CONFIG_FILE_NAME} field "pause" must be a boolean`);
|
|
370
|
+
}
|
|
371
|
+
return file.pause;
|
|
372
|
+
}
|
|
373
|
+
|
|
270
374
|
/**
|
|
271
375
|
* Resolve connection settings.
|
|
272
376
|
* Priority: env > cliproxyapi.json > auth.json (/login) > default baseUrl
|
|
@@ -357,7 +461,11 @@ export function supportsFastServiceTier(model: CodexClientModel): boolean {
|
|
|
357
461
|
return Array.isArray(model.service_tiers) && model.service_tiers.length > 0;
|
|
358
462
|
}
|
|
359
463
|
|
|
360
|
-
export function toPiModel(
|
|
464
|
+
export function toPiModel(
|
|
465
|
+
model: CodexClientModel,
|
|
466
|
+
costCatalog?: ModelsDevCostCatalog,
|
|
467
|
+
fastMode = false,
|
|
468
|
+
): PiProviderModel | null {
|
|
361
469
|
const id = codexModelId(model);
|
|
362
470
|
if (!id) {
|
|
363
471
|
return null;
|
|
@@ -375,12 +483,16 @@ export function toPiModel(model: CodexClientModel): PiProviderModel | null {
|
|
|
375
483
|
: undefined) ??
|
|
376
484
|
DEFAULT_CONTEXT_WINDOW;
|
|
377
485
|
|
|
486
|
+
const cost = costCatalog
|
|
487
|
+
? matchModelCost(id, costCatalog, fastMode && supportsFastServiceTier(model))
|
|
488
|
+
: { ...ZERO_COST };
|
|
489
|
+
|
|
378
490
|
return {
|
|
379
491
|
id,
|
|
380
492
|
name: (model.display_name ?? model.name ?? id).trim() || id,
|
|
381
493
|
reasoning: hasReasoning,
|
|
382
494
|
input: buildInputModalities(model),
|
|
383
|
-
cost
|
|
495
|
+
cost,
|
|
384
496
|
contextWindow,
|
|
385
497
|
maxTokens: DEFAULT_MAX_TOKENS,
|
|
386
498
|
thinkingLevelMap: buildThinkingLevelMap(efforts),
|
|
@@ -404,12 +516,20 @@ export function isUnauthorizedModelsError(error: unknown): boolean {
|
|
|
404
516
|
return error instanceof ModelsHttpError && error.status === 401;
|
|
405
517
|
}
|
|
406
518
|
|
|
407
|
-
export async function fetchCodexModels(
|
|
519
|
+
export async function fetchCodexModels(
|
|
520
|
+
modelsUrl: string,
|
|
521
|
+
apiKey: string,
|
|
522
|
+
timeoutMs = MODELS_REQUEST_TIMEOUT_MS,
|
|
523
|
+
signal?: AbortSignal,
|
|
524
|
+
): Promise<CodexClientModel[]> {
|
|
525
|
+
const timeoutSignal = AbortSignal.timeout(timeoutMs);
|
|
526
|
+
const requestSignal = signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal;
|
|
408
527
|
const response = await fetch(modelsUrl, {
|
|
409
528
|
headers: {
|
|
410
529
|
Authorization: `Bearer ${apiKey}`,
|
|
411
530
|
Accept: "application/json",
|
|
412
531
|
},
|
|
532
|
+
signal: requestSignal,
|
|
413
533
|
});
|
|
414
534
|
|
|
415
535
|
// Login validation only requires HTTP 200; non-2xx means credentials/baseUrl failed.
|
|
@@ -441,13 +561,310 @@ export async function fetchCodexModels(modelsUrl: string, apiKey: string): Promi
|
|
|
441
561
|
return [];
|
|
442
562
|
}
|
|
443
563
|
|
|
564
|
+
export interface ResolvedModelsResult {
|
|
565
|
+
loaded: MappedModels;
|
|
566
|
+
fromCache: boolean;
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
const MODEL_NAMESPACE_PREFIX =
|
|
570
|
+
/^(openai|anthropic|google(?:-vertex)?|xai|deepseek|mistral|cohere|zhipuai|moonshotai|minimax|meta)[/:.]/i;
|
|
571
|
+
|
|
572
|
+
const MODEL_PROVIDER_PREFERENCES: Array<{ pattern: RegExp; providers: string[] }> = [
|
|
573
|
+
{ pattern: /^(?:gpt-|o[134](?:-|$)|chatgpt-|codex-)/, providers: ["openai", "openai-codex", "opencode"] },
|
|
574
|
+
{ pattern: /^claude-/, providers: ["anthropic"] },
|
|
575
|
+
{ pattern: /^(?:gemini-|gemma-)/, providers: ["google", "google-vertex"] },
|
|
576
|
+
{ pattern: /^grok-/, providers: ["xai"] },
|
|
577
|
+
{ pattern: /^deepseek-/, providers: ["deepseek"] },
|
|
578
|
+
{ pattern: /^mistral-/, providers: ["mistral"] },
|
|
579
|
+
{ pattern: /^command-/, providers: ["cohere"] },
|
|
580
|
+
{ pattern: /^glm-/, providers: ["zhipuai"] },
|
|
581
|
+
{ pattern: /^(?:kimi-|moonshot-)/, providers: ["moonshotai"] },
|
|
582
|
+
{ pattern: /^minimax-/, providers: ["minimax"] },
|
|
583
|
+
{ pattern: /^llama-/, providers: ["meta"] },
|
|
584
|
+
];
|
|
585
|
+
|
|
586
|
+
/** Explicit aliases for proxy-specific model ids whose billable base model is known. */
|
|
587
|
+
const MODEL_PRICE_ALIASES: Record<string, string[]> = {
|
|
588
|
+
"gemini-pro-agent": ["gemini-3.1-pro-preview"],
|
|
589
|
+
"gemini-3.1-pro-low": ["gemini-3.1-pro-preview"],
|
|
590
|
+
"gemini-3.6-flash-high": ["gemini-3.6-flash"],
|
|
591
|
+
"gemini-3-flash-agent": ["gemini-3.5-flash"],
|
|
592
|
+
"grok-composer-2.5-fast": ["grok-4.3"],
|
|
593
|
+
"grok-3-mini": ["xai/grok-3-mini"],
|
|
594
|
+
};
|
|
595
|
+
|
|
596
|
+
function asRecord(value: unknown): Record<string, unknown> | undefined {
|
|
597
|
+
return value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
function finiteNumber(value: unknown): number | undefined {
|
|
601
|
+
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
function readCostRate(
|
|
605
|
+
source: Record<string, unknown>,
|
|
606
|
+
key: "input" | "output" | "cacheRead" | "cacheWrite",
|
|
607
|
+
fallback: number,
|
|
608
|
+
): number {
|
|
609
|
+
const rawKey = key === "cacheRead" ? "cache_read" : key === "cacheWrite" ? "cache_write" : key;
|
|
610
|
+
return finiteNumber(source[key] ?? source[rawKey]) ?? fallback;
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
function parseModelsDevCost(raw: ModelsDevCostPayload | undefined): PiProviderCost | undefined {
|
|
614
|
+
if (!raw) return undefined;
|
|
615
|
+
const source = raw as Record<string, unknown>;
|
|
616
|
+
const input = finiteNumber(source.input);
|
|
617
|
+
const output = finiteNumber(source.output);
|
|
618
|
+
if (input === undefined && output === undefined) return undefined;
|
|
619
|
+
|
|
620
|
+
const cost: PiProviderCost = {
|
|
621
|
+
input: input ?? 0,
|
|
622
|
+
output: output ?? 0,
|
|
623
|
+
cacheRead: readCostRate(source, "cacheRead", 0),
|
|
624
|
+
cacheWrite: readCostRate(source, "cacheWrite", 0),
|
|
625
|
+
};
|
|
626
|
+
const tiers = new Map<number, PiProviderCostTier>();
|
|
627
|
+
|
|
628
|
+
const addTier = (rawTier: unknown, fallbackThreshold?: number): void => {
|
|
629
|
+
const tierSource = asRecord(rawTier);
|
|
630
|
+
if (!tierSource) return;
|
|
631
|
+
const descriptor = asRecord(tierSource.tier);
|
|
632
|
+
if (descriptor?.type !== undefined && descriptor.type !== "context") return;
|
|
633
|
+
const threshold =
|
|
634
|
+
finiteNumber(tierSource.inputTokensAbove) ?? finiteNumber(descriptor?.size) ?? fallbackThreshold;
|
|
635
|
+
if (threshold === undefined || threshold <= 0) return;
|
|
636
|
+
tiers.set(threshold, {
|
|
637
|
+
input: readCostRate(tierSource, "input", cost.input),
|
|
638
|
+
output: readCostRate(tierSource, "output", cost.output),
|
|
639
|
+
cacheRead: readCostRate(tierSource, "cacheRead", cost.cacheRead),
|
|
640
|
+
cacheWrite: readCostRate(tierSource, "cacheWrite", cost.cacheWrite),
|
|
641
|
+
inputTokensAbove: threshold,
|
|
642
|
+
});
|
|
643
|
+
};
|
|
644
|
+
|
|
645
|
+
if (Array.isArray(source.tiers)) {
|
|
646
|
+
for (const tier of source.tiers) addTier(tier);
|
|
647
|
+
}
|
|
648
|
+
if (tiers.size === 0) {
|
|
649
|
+
// Older models.dev records may expose only this compatibility shortcut.
|
|
650
|
+
addTier(source.context_over_200k, 200000);
|
|
651
|
+
}
|
|
652
|
+
if (tiers.size > 0) {
|
|
653
|
+
cost.tiers = Array.from(tiers.values()).sort((a, b) => a.inputTokensAbove - b.inputTokensAbove);
|
|
654
|
+
}
|
|
655
|
+
return cost;
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
function cloneCost(cost: PiProviderCost): PiProviderCost {
|
|
659
|
+
return {
|
|
660
|
+
input: cost.input,
|
|
661
|
+
output: cost.output,
|
|
662
|
+
cacheRead: cost.cacheRead,
|
|
663
|
+
cacheWrite: cost.cacheWrite,
|
|
664
|
+
...(cost.tiers ? { tiers: cost.tiers.map((tier) => ({ ...tier })) } : {}),
|
|
665
|
+
};
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
function stripModelNamespace(modelId: string): string {
|
|
669
|
+
return modelId.trim().toLowerCase().replace(MODEL_NAMESPACE_PREFIX, "");
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
function normalizeModelKey(modelId: string): string {
|
|
673
|
+
return stripModelNamespace(modelId).replace(/[^a-z0-9]/g, "");
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
function uniqueStrings(values: string[]): string[] {
|
|
677
|
+
return Array.from(new Set(values.filter((value) => value.length > 0)));
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
function preferredProvidersForModel(modelId: string): string[] {
|
|
681
|
+
const normalizedId = stripModelNamespace(modelId);
|
|
682
|
+
const namespace = modelId.trim().toLowerCase().match(MODEL_NAMESPACE_PREFIX)?.[1];
|
|
683
|
+
const familyProviders =
|
|
684
|
+
MODEL_PROVIDER_PREFERENCES.find(({ pattern }) => pattern.test(normalizedId))?.providers ?? [];
|
|
685
|
+
return uniqueStrings([namespace ?? "", ...familyProviders]);
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
function addCatalogEntry(catalog: Map<string, ModelsDevCostEntry[]>, key: string, entry: ModelsDevCostEntry): void {
|
|
689
|
+
if (!key) return;
|
|
690
|
+
const entries = catalog.get(key) ?? [];
|
|
691
|
+
if (!entries.some((candidate) => candidate.providerId === entry.providerId && candidate.modelId === entry.modelId)) {
|
|
692
|
+
entries.push(entry);
|
|
693
|
+
catalog.set(key, entries);
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
function addModelsDevEntry(catalog: ModelsDevCostCatalog, entry: ModelsDevCostEntry): void {
|
|
698
|
+
const rawId = entry.modelId.trim().toLowerCase();
|
|
699
|
+
const strippedId = stripModelNamespace(rawId);
|
|
700
|
+
for (const key of uniqueStrings([rawId, strippedId])) {
|
|
701
|
+
addCatalogEntry(catalog.exact, key, entry);
|
|
702
|
+
}
|
|
703
|
+
addCatalogEntry(catalog.normalized, normalizeModelKey(rawId), entry);
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
function sameCostVariants(entries: ModelsDevCostEntry[]): boolean {
|
|
707
|
+
const fingerprints = new Set(entries.map((entry) => JSON.stringify({ standard: entry.standard, fast: entry.fast })));
|
|
708
|
+
return fingerprints.size === 1;
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
function selectModelsDevEntry(entries: ModelsDevCostEntry[], modelId: string): ModelsDevCostEntry | undefined {
|
|
712
|
+
if (entries.length === 0) return undefined;
|
|
713
|
+
const preferredProviders = preferredProvidersForModel(modelId);
|
|
714
|
+
for (const providerId of preferredProviders) {
|
|
715
|
+
const match = entries.find((entry) => entry.providerId === providerId);
|
|
716
|
+
if (match) return match;
|
|
717
|
+
}
|
|
718
|
+
if (entries.length === 1 || sameCostVariants(entries)) {
|
|
719
|
+
return [...entries].sort((a, b) => a.providerId.localeCompare(b.providerId))[0];
|
|
720
|
+
}
|
|
721
|
+
// Do not silently pick an arbitrary reseller price when the source is ambiguous.
|
|
722
|
+
return undefined;
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
function findDirectModelsDevEntry(modelId: string, catalog: ModelsDevCostCatalog): ModelsDevCostEntry | undefined {
|
|
726
|
+
const rawId = modelId.trim().toLowerCase();
|
|
727
|
+
const exactKeys = uniqueStrings([rawId, stripModelNamespace(rawId)]);
|
|
728
|
+
for (const key of exactKeys) {
|
|
729
|
+
const match = selectModelsDevEntry(catalog.exact.get(key) ?? [], modelId);
|
|
730
|
+
if (match) return match;
|
|
731
|
+
}
|
|
732
|
+
return selectModelsDevEntry(catalog.normalized.get(normalizeModelKey(rawId)) ?? [], modelId);
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
function findModelsDevEntry(modelId: string, catalog: ModelsDevCostCatalog): ModelsDevCostEntry | undefined {
|
|
736
|
+
const rawId = modelId.trim().toLowerCase();
|
|
737
|
+
const lookupIds = uniqueStrings([rawId, ...(MODEL_PRICE_ALIASES[rawId] ?? [])]);
|
|
738
|
+
for (const lookupId of lookupIds) {
|
|
739
|
+
const match = findDirectModelsDevEntry(lookupId, catalog);
|
|
740
|
+
if (match) return match;
|
|
741
|
+
}
|
|
742
|
+
return undefined;
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
interface ModelsDevCacheFile {
|
|
746
|
+
timestamp: number;
|
|
747
|
+
providers: Record<string, unknown>;
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
function getModelsDevCachePath(agentDir?: string): string {
|
|
751
|
+
if (agentDir?.trim()) {
|
|
752
|
+
return join(agentDir, "tmp", "models-dev-cache.json");
|
|
753
|
+
}
|
|
754
|
+
return join(tmpdir(), "pi-cliproxyapi-models-dev-cache.json");
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
function readModelsDevCacheFile(cachePath: string): ModelsDevCacheFile | null {
|
|
758
|
+
try {
|
|
759
|
+
const raw = readFileSync(cachePath, "utf8");
|
|
760
|
+
const parsed = asRecord(JSON.parse(raw));
|
|
761
|
+
if (!parsed || typeof parsed.timestamp !== "number" || !Number.isFinite(parsed.timestamp)) return null;
|
|
762
|
+
const providers = asRecord(parsed.providers);
|
|
763
|
+
if (!providers || !isModelsDevProviders(providers)) return null;
|
|
764
|
+
return { timestamp: parsed.timestamp, providers };
|
|
765
|
+
} catch {
|
|
766
|
+
return null;
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
function writeModelsDevCacheFile(cachePath: string, providers: Record<string, unknown>): void {
|
|
771
|
+
try {
|
|
772
|
+
mkdirSync(dirname(cachePath), { recursive: true });
|
|
773
|
+
const payload: ModelsDevCacheFile = {
|
|
774
|
+
timestamp: Date.now(),
|
|
775
|
+
providers,
|
|
776
|
+
};
|
|
777
|
+
writeFileSync(cachePath, JSON.stringify(payload), "utf8");
|
|
778
|
+
} catch {
|
|
779
|
+
// Ignore write failure (e.g. read-only filesystem)
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
function isModelsDevProviders(value: Record<string, unknown>): boolean {
|
|
784
|
+
return Object.values(value).some((providerValue) => {
|
|
785
|
+
const provider = asRecord(providerValue);
|
|
786
|
+
return asRecord(provider?.models) !== undefined;
|
|
787
|
+
});
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
function buildCatalogFromProviders(providers: Record<string, unknown>): ModelsDevCostCatalog {
|
|
791
|
+
const catalog: ModelsDevCostCatalog = { exact: new Map(), normalized: new Map() };
|
|
792
|
+
for (const [providerId, providerValue] of Object.entries(providers)) {
|
|
793
|
+
const provider = asRecord(providerValue);
|
|
794
|
+
const models = asRecord(provider?.models);
|
|
795
|
+
if (!models) continue;
|
|
796
|
+
for (const [modelId, modelValue] of Object.entries(models)) {
|
|
797
|
+
const model = asRecord(modelValue) as ModelsDevModelPayload | undefined;
|
|
798
|
+
const standard = parseModelsDevCost(model?.cost);
|
|
799
|
+
if (!standard) continue;
|
|
800
|
+
const fast = parseModelsDevCost(model?.experimental?.modes?.fast?.cost);
|
|
801
|
+
addModelsDevEntry(catalog, { providerId, modelId, standard, fast });
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
return catalog;
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
export async function fetchModelsDevCostMap(
|
|
808
|
+
agentDir?: string,
|
|
809
|
+
forceRefresh = false,
|
|
810
|
+
signal?: AbortSignal,
|
|
811
|
+
): Promise<ModelsDevCostCatalog> {
|
|
812
|
+
const cachePath = getModelsDevCachePath(agentDir);
|
|
813
|
+
const cached = readModelsDevCacheFile(cachePath);
|
|
814
|
+
|
|
815
|
+
if (!forceRefresh && cached && Date.now() - cached.timestamp < MODELS_DEV_CACHE_TTL_MS) {
|
|
816
|
+
return buildCatalogFromProviders(cached.providers);
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
const controller = new AbortController();
|
|
820
|
+
const timeoutId = setTimeout(() => controller.abort(), 3000);
|
|
821
|
+
const requestSignal = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;
|
|
822
|
+
try {
|
|
823
|
+
const response = await fetch("https://models.dev/api.json", { signal: requestSignal });
|
|
824
|
+
if (response.ok) {
|
|
825
|
+
const providers = asRecord(await response.json());
|
|
826
|
+
if (providers && isModelsDevProviders(providers)) {
|
|
827
|
+
writeModelsDevCacheFile(cachePath, providers);
|
|
828
|
+
return buildCatalogFromProviders(providers);
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
} catch {
|
|
832
|
+
// Retain stale cache if network/JSON fails
|
|
833
|
+
} finally {
|
|
834
|
+
clearTimeout(timeoutId);
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
if (cached) {
|
|
838
|
+
return buildCatalogFromProviders(cached.providers);
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
return { exact: new Map(), normalized: new Map() };
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
export function matchModelCost(modelId: string, costCatalog: ModelsDevCostCatalog, isFastMode = false): PiProviderCost {
|
|
845
|
+
const entry = findModelsDevEntry(modelId, costCatalog);
|
|
846
|
+
if (!entry) return { ...ZERO_COST };
|
|
847
|
+
return cloneCost(isFastMode && entry.fast ? entry.fast : entry.standard);
|
|
848
|
+
}
|
|
849
|
+
|
|
444
850
|
export async function loadMappedModels(
|
|
445
851
|
baseUrlInput: string,
|
|
446
852
|
apiKey: string,
|
|
447
|
-
|
|
853
|
+
timeoutOrFastMode: number | boolean = MODELS_REQUEST_TIMEOUT_MS,
|
|
854
|
+
agentDir?: string,
|
|
855
|
+
signal?: AbortSignal,
|
|
856
|
+
): Promise<MappedModels> {
|
|
857
|
+
const pricingEnabled = typeof timeoutOrFastMode === "boolean";
|
|
858
|
+
const effectiveFastMode = typeof timeoutOrFastMode === "boolean" ? timeoutOrFastMode : false;
|
|
859
|
+
const timeoutMs = typeof timeoutOrFastMode === "number" ? timeoutOrFastMode : MODELS_REQUEST_TIMEOUT_MS;
|
|
448
860
|
const endpoints = resolveEndpoints(baseUrlInput);
|
|
449
|
-
const remoteModels = await
|
|
450
|
-
|
|
861
|
+
const [remoteModels, costCatalog] = await Promise.all([
|
|
862
|
+
fetchCodexModels(endpoints.modelsUrl, apiKey, timeoutMs, signal),
|
|
863
|
+
pricingEnabled ? fetchModelsDevCostMap(agentDir, false, signal) : Promise.resolve(undefined),
|
|
864
|
+
]);
|
|
865
|
+
const models = remoteModels
|
|
866
|
+
.map((model) => toPiModel(model, costCatalog, effectiveFastMode))
|
|
867
|
+
.filter((model): model is PiProviderModel => model !== null);
|
|
451
868
|
const fastModelIds = Array.from(
|
|
452
869
|
new Set(
|
|
453
870
|
remoteModels
|
|
@@ -463,5 +880,38 @@ export async function loadMappedModels(
|
|
|
463
880
|
fastModelIds,
|
|
464
881
|
inferenceBaseUrl: endpoints.inferenceBaseUrl,
|
|
465
882
|
modelsUrl: endpoints.modelsUrl,
|
|
883
|
+
...(pricingEnabled ? { fastMode: effectiveFastMode } : {}),
|
|
466
884
|
};
|
|
467
885
|
}
|
|
886
|
+
|
|
887
|
+
/**
|
|
888
|
+
* Load mapped models from the matching cache, or fetch remotely and update the cache.
|
|
889
|
+
* A forced refresh always bypasses the cache.
|
|
890
|
+
*/
|
|
891
|
+
export async function resolveMappedModels(
|
|
892
|
+
agentDir: string,
|
|
893
|
+
baseUrlInput: string,
|
|
894
|
+
apiKey: string,
|
|
895
|
+
options: {
|
|
896
|
+
forceRefresh?: boolean;
|
|
897
|
+
fastMode?: boolean;
|
|
898
|
+
signal?: AbortSignal;
|
|
899
|
+
shouldCommit?: () => boolean;
|
|
900
|
+
} = {},
|
|
901
|
+
): Promise<ResolvedModelsResult> {
|
|
902
|
+
const cacheMatchesFastMode = (cache: ModelsCacheFile): boolean =>
|
|
903
|
+
options.fastMode === undefined || (cache.fastMode ?? false) === options.fastMode;
|
|
904
|
+
|
|
905
|
+
if (!options.forceRefresh) {
|
|
906
|
+
const cache = loadModelsCache(agentDir, baseUrlInput);
|
|
907
|
+
if (cache && cacheMatchesFastMode(cache)) {
|
|
908
|
+
return { loaded: cache, fromCache: true };
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
const loaded = await loadMappedModels(baseUrlInput, apiKey, options.fastMode, agentDir, options.signal);
|
|
913
|
+
if (!options.signal?.aborted && (options.shouldCommit?.() ?? true)) {
|
|
914
|
+
saveModelsCache(agentDir, loaded);
|
|
915
|
+
}
|
|
916
|
+
return { loaded, fromCache: false };
|
|
917
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/** Shared pause state for request gating and elapsed-time accounting. */
|
|
2
|
+
|
|
3
|
+
import { resolvePauseDefault } from "./lib.ts";
|
|
4
|
+
|
|
5
|
+
export const PAUSE_POLL_INTERVAL_MS = 200;
|
|
6
|
+
|
|
7
|
+
export class PauseController {
|
|
8
|
+
private enabled = false;
|
|
9
|
+
private pauseStartedAtMs: number | undefined;
|
|
10
|
+
private pausedDurationMs = 0;
|
|
11
|
+
|
|
12
|
+
constructor(enabled = false) {
|
|
13
|
+
this.setEnabled(enabled);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
setEnabled(enabled: boolean, now = Date.now()): void {
|
|
17
|
+
if (enabled === this.enabled) return;
|
|
18
|
+
|
|
19
|
+
if (enabled) {
|
|
20
|
+
this.pauseStartedAtMs = now;
|
|
21
|
+
} else if (this.pauseStartedAtMs !== undefined) {
|
|
22
|
+
this.pausedDurationMs += Math.max(0, now - this.pauseStartedAtMs);
|
|
23
|
+
this.pauseStartedAtMs = undefined;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
this.enabled = enabled;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
isEnabled(): boolean {
|
|
30
|
+
return this.enabled;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
getPausedDurationMs(now = Date.now()): number {
|
|
34
|
+
if (this.pauseStartedAtMs === undefined) return this.pausedDurationMs;
|
|
35
|
+
return this.pausedDurationMs + Math.max(0, now - this.pauseStartedAtMs);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
getElapsedMs(startMs: number, pausedDurationAtStartMs: number, now = Date.now()): number {
|
|
39
|
+
const pausedSinceStartMs = Math.max(0, this.getPausedDurationMs(now) - pausedDurationAtStartMs);
|
|
40
|
+
return Math.max(0, now - startMs - pausedSinceStartMs);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export const pauseController = new PauseController();
|
|
45
|
+
|
|
46
|
+
export function readPauseSetting(agentDir: string, fallback = false): boolean {
|
|
47
|
+
try {
|
|
48
|
+
return resolvePauseDefault(agentDir);
|
|
49
|
+
} catch {
|
|
50
|
+
// Keep the current in-memory state when the setting cannot be read.
|
|
51
|
+
return fallback;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export async function waitForPauseToEnd(
|
|
56
|
+
agentDir: string,
|
|
57
|
+
controller: PauseController = pauseController,
|
|
58
|
+
): Promise<void> {
|
|
59
|
+
while (true) {
|
|
60
|
+
const enabled = readPauseSetting(agentDir, controller.isEnabled());
|
|
61
|
+
controller.setEnabled(enabled);
|
|
62
|
+
if (!enabled) return;
|
|
63
|
+
await new Promise<void>((resolve) => setTimeout(resolve, PAUSE_POLL_INTERVAL_MS));
|
|
64
|
+
}
|
|
65
|
+
}
|
package/extensions/retry.ts
CHANGED
|
@@ -1,14 +1,15 @@
|
|
|
1
1
|
import { type AssistantMessage, isRetryableAssistantError } from "@earendil-works/pi-ai";
|
|
2
2
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
3
3
|
|
|
4
|
-
const
|
|
4
|
+
const TRANSIENT_STREAM_ERROR_PATTERN =
|
|
5
|
+
/\bclosed network connection\b|\bstream disconnected before completion: stream closed before response\.completed\b|\binvalid SSE data JSON\b/i;
|
|
5
6
|
const NETWORK_ERROR_PREFIX = "network error:";
|
|
6
7
|
|
|
7
8
|
export function normalizeTransientNetworkError(message: AssistantMessage): AssistantMessage {
|
|
8
9
|
if (message.stopReason !== "error" || !message.errorMessage) {
|
|
9
10
|
return message;
|
|
10
11
|
}
|
|
11
|
-
if (isRetryableAssistantError(message) || !
|
|
12
|
+
if (isRetryableAssistantError(message) || !TRANSIENT_STREAM_ERROR_PATTERN.test(message.errorMessage)) {
|
|
12
13
|
return message;
|
|
13
14
|
}
|
|
14
15
|
|