@rigelbuild/omp-catalog 18.0.3
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/CHANGELOG.md +1204 -0
- package/LICENSE +22 -0
- package/README.md +43 -0
- package/THIRD-PARTY-NOTICES.txt +22909 -0
- package/dist/types/build.d.ts +19 -0
- package/dist/types/compat/anthropic.d.ts +18 -0
- package/dist/types/compat/apply.d.ts +7 -0
- package/dist/types/compat/bedrock.d.ts +3 -0
- package/dist/types/compat/devin.d.ts +9 -0
- package/dist/types/compat/openai.d.ts +28 -0
- package/dist/types/discovery/antigravity.d.ts +70 -0
- package/dist/types/discovery/codex.d.ts +36 -0
- package/dist/types/discovery/cursor-proto.d.ts +5368 -0
- package/dist/types/discovery/cursor.d.ts +23 -0
- package/dist/types/discovery/devin-proto.d.ts +1549 -0
- package/dist/types/discovery/devin.d.ts +24 -0
- package/dist/types/discovery/gemini-cli.d.ts +33 -0
- package/dist/types/discovery/gemini.d.ts +25 -0
- package/dist/types/discovery/gitlab-duo-workflow.d.ts +30 -0
- package/dist/types/discovery/index.d.ts +7 -0
- package/dist/types/discovery/openai-compatible.d.ts +89 -0
- package/dist/types/discovery/protobuf.d.ts +102 -0
- package/dist/types/effort.d.ts +10 -0
- package/dist/types/fireworks-model-id.d.ts +23 -0
- package/dist/types/hosts.d.ts +169 -0
- package/dist/types/identity/bundled.d.ts +3 -0
- package/dist/types/identity/classify.d.ts +69 -0
- package/dist/types/identity/dialect.d.ts +3 -0
- package/dist/types/identity/family.d.ts +239 -0
- package/dist/types/identity/id.d.ts +12 -0
- package/dist/types/identity/index.d.ts +8 -0
- package/dist/types/identity/markers.d.ts +4 -0
- package/dist/types/identity/priority.d.ts +1 -0
- package/dist/types/identity/reference.d.ts +29 -0
- package/dist/types/index.d.ts +19 -0
- package/dist/types/model-cache.d.ts +23 -0
- package/dist/types/model-manager.d.ts +77 -0
- package/dist/types/model-thinking.d.ts +70 -0
- package/dist/types/model-tokenizer.d.ts +8 -0
- package/dist/types/models.d.ts +14 -0
- package/dist/types/openai-pricing.d.ts +17 -0
- package/dist/types/provider-models/bundled-references.d.ts +13 -0
- package/dist/types/provider-models/cache-provider-id.d.ts +11 -0
- package/dist/types/provider-models/descriptor-types.d.ts +76 -0
- package/dist/types/provider-models/descriptors.d.ts +505 -0
- package/dist/types/provider-models/google.d.ts +29 -0
- package/dist/types/provider-models/index.d.ts +7 -0
- package/dist/types/provider-models/ollama.d.ts +22 -0
- package/dist/types/provider-models/openai-compat.d.ts +646 -0
- package/dist/types/provider-models/special.d.ts +53 -0
- package/dist/types/types.d.ts +876 -0
- package/dist/types/utils.d.ts +20 -0
- package/dist/types/variant-collapse.d.ts +137 -0
- package/dist/types/wire/alibaba-token-plan.d.ts +22 -0
- package/dist/types/wire/codex.d.ts +66 -0
- package/dist/types/wire/coreweave.d.ts +12 -0
- package/dist/types/wire/gemini-headers.d.ts +62 -0
- package/dist/types/wire/github-copilot.d.ts +47 -0
- package/dist/types/wire/image-fetchers.d.ts +76 -0
- package/package.json +102 -0
- package/src/build.ts +103 -0
- package/src/compat/anthropic.ts +179 -0
- package/src/compat/apply.ts +15 -0
- package/src/compat/bedrock.ts +153 -0
- package/src/compat/devin.ts +12 -0
- package/src/compat/openai.ts +864 -0
- package/src/discovery/antigravity.ts +257 -0
- package/src/discovery/codex.ts +456 -0
- package/src/discovery/cursor-proto.ts +8329 -0
- package/src/discovery/cursor.ts +409 -0
- package/src/discovery/devin-proto.ts +2037 -0
- package/src/discovery/devin.ts +152 -0
- package/src/discovery/gemini-cli.ts +198 -0
- package/src/discovery/gemini.ts +260 -0
- package/src/discovery/gitlab-duo-workflow.ts +859 -0
- package/src/discovery/index.ts +7 -0
- package/src/discovery/openai-compatible.ts +266 -0
- package/src/discovery/protobuf.ts +1073 -0
- package/src/effort.ts +18 -0
- package/src/fireworks-model-id.ts +50 -0
- package/src/hosts.ts +178 -0
- package/src/identity/bundled.ts +28 -0
- package/src/identity/classify.ts +242 -0
- package/src/identity/dialect.ts +42 -0
- package/src/identity/family.ts +477 -0
- package/src/identity/id.ts +81 -0
- package/src/identity/index.ts +8 -0
- package/src/identity/markers.ts +49 -0
- package/src/identity/priority.ts +59 -0
- package/src/identity/reference.ts +167 -0
- package/src/index.ts +19 -0
- package/src/model-cache.ts +346 -0
- package/src/model-manager.ts +683 -0
- package/src/model-thinking.ts +925 -0
- package/src/model-tokenizer.ts +75 -0
- package/src/models.json +304657 -0
- package/src/models.json.d.ts +9 -0
- package/src/models.ts +108 -0
- package/src/openai-pricing.ts +29 -0
- package/src/provider-models/bundled-references.ts +87 -0
- package/src/provider-models/cache-provider-id.ts +97 -0
- package/src/provider-models/descriptor-types.ts +85 -0
- package/src/provider-models/descriptors.ts +585 -0
- package/src/provider-models/google.ts +117 -0
- package/src/provider-models/index.ts +7 -0
- package/src/provider-models/ollama.ts +204 -0
- package/src/provider-models/openai-compat.ts +6405 -0
- package/src/provider-models/special.ts +213 -0
- package/src/types.ts +1032 -0
- package/src/utils.ts +69 -0
- package/src/variant-collapse.ts +1555 -0
- package/src/wire/alibaba-token-plan.ts +54 -0
- package/src/wire/codex.ts +117 -0
- package/src/wire/coreweave.ts +51 -0
- package/src/wire/gemini-headers.ts +135 -0
- package/src/wire/github-copilot.ts +147 -0
- package/src/wire/image-fetchers.ts +159 -0
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Proxy/reseller reference lookup: given a custom model id served through a
|
|
3
|
+
* proxy (`[Kiro] claude-opus-4-8`, `gpt-5.4:cloud`, `vendor/claude-sonnet-4-6-thinking`),
|
|
4
|
+
* find the bundled upstream model so missing pricing/capability metadata can be
|
|
5
|
+
* inherited while keeping the custom transport.
|
|
6
|
+
*
|
|
7
|
+
* Kept separate from canonical-id resolution (`./equivalence`): this lookup
|
|
8
|
+
* may strip `search`-style markers and prefers cache-pricing-complete
|
|
9
|
+
* references, both of which would be wrong for canonical coalescing.
|
|
10
|
+
*/
|
|
11
|
+
import type { Api, Model, ThinkingConfig } from "../types";
|
|
12
|
+
import { getBracketStrippedModelIdCandidates, getLongestModelLikeIdSegment, getModelLikeIdSegments } from "./id";
|
|
13
|
+
import { REFERENCE_TRAILING_MARKER_PATTERN } from "./markers";
|
|
14
|
+
|
|
15
|
+
export interface ModelReferenceIndex {
|
|
16
|
+
exact: Map<string, Model<Api>>;
|
|
17
|
+
suffixAlias: Map<string, Model<Api>>;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// xai-oauth subscription entries carry zero public pricing and inflated maxTokens;
|
|
21
|
+
// keep them provider-local so they cannot outrank paid/public Grok references.
|
|
22
|
+
export function isZeroCostXaiOAuthReference(candidate: Model<Api>): boolean {
|
|
23
|
+
return (
|
|
24
|
+
candidate.provider === "xai-oauth" &&
|
|
25
|
+
candidate.cost.input === 0 &&
|
|
26
|
+
candidate.cost.output === 0 &&
|
|
27
|
+
candidate.cost.cacheRead === 0 &&
|
|
28
|
+
candidate.cost.cacheWrite === 0
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// Prefer the reference with the largest limits and complete cache pricing, then
|
|
33
|
+
// first-party OpenAI entries.
|
|
34
|
+
function shouldReplaceReference(existing: Model<Api> | undefined, candidate: Model<Api>): boolean {
|
|
35
|
+
if (!existing) return true;
|
|
36
|
+
if (candidate.contextWindow !== existing.contextWindow) {
|
|
37
|
+
return (candidate.contextWindow ?? 0) > (existing.contextWindow ?? 0);
|
|
38
|
+
}
|
|
39
|
+
if (candidate.maxTokens !== existing.maxTokens) {
|
|
40
|
+
return (candidate.maxTokens ?? 0) > (existing.maxTokens ?? 0);
|
|
41
|
+
}
|
|
42
|
+
const existingHasCachePricing = existing.cost.cacheRead > 0 || existing.cost.cacheWrite > 0;
|
|
43
|
+
const candidateHasCachePricing = candidate.cost.cacheRead > 0 || candidate.cost.cacheWrite > 0;
|
|
44
|
+
if (candidateHasCachePricing !== existingHasCachePricing) {
|
|
45
|
+
return candidateHasCachePricing;
|
|
46
|
+
}
|
|
47
|
+
return existing.provider !== "openai" && candidate.provider === "openai";
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function normalizeReferenceKey(value: string): string {
|
|
51
|
+
return value.trim().toLowerCase();
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Build a reference index from a model catalog (typically the bundled models).
|
|
56
|
+
* Pure: callers are responsible for memoizing the result.
|
|
57
|
+
*/
|
|
58
|
+
export function buildModelReferenceIndex(models: Iterable<Model<Api>>): ModelReferenceIndex {
|
|
59
|
+
const exact = new Map<string, Model<Api>>();
|
|
60
|
+
for (const candidate of models) {
|
|
61
|
+
if (isZeroCostXaiOAuthReference(candidate)) {
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
const key = normalizeReferenceKey(candidate.id);
|
|
65
|
+
if (shouldReplaceReference(exact.get(key), candidate)) {
|
|
66
|
+
exact.set(key, candidate);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return { exact, suffixAlias: buildSuffixAliasMap(exact) };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function buildSuffixAliasMap(exactReferences: ReadonlyMap<string, Model<Api>>): Map<string, Model<Api>> {
|
|
73
|
+
const aliases = new Map<string, Model<Api>>();
|
|
74
|
+
for (const reference of exactReferences.values()) {
|
|
75
|
+
const slashIndex = reference.id.lastIndexOf("/");
|
|
76
|
+
if (slashIndex === -1) {
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
const suffix = reference.id.slice(slashIndex + 1);
|
|
80
|
+
const alias = getLongestModelLikeIdSegment(suffix);
|
|
81
|
+
if (!alias) {
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
if (shouldReplaceReference(aliases.get(alias), reference)) {
|
|
85
|
+
aliases.set(alias, reference);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return aliases;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function stripReferenceTrailingMarker(candidate: string): string | undefined {
|
|
92
|
+
const match = REFERENCE_TRAILING_MARKER_PATTERN.exec(candidate);
|
|
93
|
+
return match ? candidate.slice(0, match.index) : undefined;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function getReferenceCandidateIds(modelId: string): string[] {
|
|
97
|
+
const candidates = new Set<string>();
|
|
98
|
+
const queue = [modelId];
|
|
99
|
+
for (let index = 0; index < queue.length; index += 1) {
|
|
100
|
+
const candidate = queue[index]?.trim();
|
|
101
|
+
if (!candidate || candidates.has(candidate)) continue;
|
|
102
|
+
candidates.add(candidate);
|
|
103
|
+
|
|
104
|
+
for (const stripped of getBracketStrippedModelIdCandidates(candidate)) {
|
|
105
|
+
queue.push(stripped);
|
|
106
|
+
}
|
|
107
|
+
for (const segment of getModelLikeIdSegments(candidate)) {
|
|
108
|
+
queue.push(segment);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
for (const suffix of [":cloud", "-cloud"] as const) {
|
|
112
|
+
if (candidate.toLowerCase().endsWith(suffix)) {
|
|
113
|
+
queue.push(candidate.slice(0, -suffix.length));
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const slashIndex = candidate.lastIndexOf("/");
|
|
118
|
+
if (slashIndex !== -1) {
|
|
119
|
+
queue.push(candidate.slice(slashIndex + 1));
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const colonToDash = candidate.replace(/:/g, "-");
|
|
123
|
+
if (colonToDash !== candidate) {
|
|
124
|
+
queue.push(colonToDash);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const lowercased = candidate.toLowerCase();
|
|
128
|
+
if (lowercased !== candidate) {
|
|
129
|
+
queue.push(lowercased);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const strippedMarker = stripReferenceTrailingMarker(candidate);
|
|
133
|
+
if (strippedMarker) {
|
|
134
|
+
queue.push(strippedMarker);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return [...candidates];
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Inherit bundled reference thinking only for same-provider matches. Wire routing
|
|
142
|
+
* (`effortRouting`) is provider-specific; cross-provider inheritance can rewrite
|
|
143
|
+
* gateway ids (e.g. Portkey `@modal/GLM-5-2-FP8` → devin `glm-5-2`).
|
|
144
|
+
*/
|
|
145
|
+
export function inheritReferenceThinking(
|
|
146
|
+
modelThinking: ThinkingConfig | undefined,
|
|
147
|
+
reference: Pick<Model<Api>, "provider" | "thinking"> | undefined,
|
|
148
|
+
provider: string,
|
|
149
|
+
): ThinkingConfig | undefined {
|
|
150
|
+
if (modelThinking !== undefined) return modelThinking;
|
|
151
|
+
if (!reference?.thinking) return undefined;
|
|
152
|
+
if (reference.provider !== provider) return undefined;
|
|
153
|
+
return reference.thinking;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Resolve a (possibly proxied/affixed) model id to its bundled upstream reference. */
|
|
157
|
+
export function resolveModelReference(modelId: string, index: ModelReferenceIndex): Model<Api> | undefined {
|
|
158
|
+
// Portkey/gateway wire ids (`@provider/model`) are opaque; fuzzy matching would
|
|
159
|
+
// map them to unrelated bundled entries (e.g. `@modal/GLM-5-2-FP8` → devin/glm-5-2).
|
|
160
|
+
if (modelId.startsWith("@")) return undefined;
|
|
161
|
+
for (const candidate of getReferenceCandidateIds(modelId)) {
|
|
162
|
+
const key = normalizeReferenceKey(candidate);
|
|
163
|
+
const reference = index.exact.get(key) ?? index.suffixAlias.get(key);
|
|
164
|
+
if (reference) return reference;
|
|
165
|
+
}
|
|
166
|
+
return undefined;
|
|
167
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export * from "./compat/openai";
|
|
2
|
+
export * from "./discovery";
|
|
3
|
+
export * from "./effort";
|
|
4
|
+
export * from "./fireworks-model-id";
|
|
5
|
+
export * from "./identity";
|
|
6
|
+
export * from "./model-cache";
|
|
7
|
+
export * from "./model-manager";
|
|
8
|
+
export * from "./model-thinking";
|
|
9
|
+
export * from "./model-tokenizer";
|
|
10
|
+
export * from "./models";
|
|
11
|
+
export * from "./provider-models";
|
|
12
|
+
export * from "./types";
|
|
13
|
+
export * from "./utils";
|
|
14
|
+
export * from "./variant-collapse";
|
|
15
|
+
export * from "./wire/codex";
|
|
16
|
+
export * from "./wire/coreweave";
|
|
17
|
+
export * from "./wire/gemini-headers";
|
|
18
|
+
export * from "./wire/github-copilot";
|
|
19
|
+
export * from "./wire/image-fetchers";
|
|
@@ -0,0 +1,346 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SQLite-backed model cache for atomic cross-process access.
|
|
3
|
+
* Replaces per-provider JSON files with a single cache.db.
|
|
4
|
+
*/
|
|
5
|
+
import { Database } from "bun:sqlite";
|
|
6
|
+
import { renameSync } from "node:fs";
|
|
7
|
+
import { getModelDbPath, isEnoent, isSqliteCorruptionError, logger } from "@rigelbuild/omp-utils";
|
|
8
|
+
import type { Api, Model, ModelSpec } from "./types";
|
|
9
|
+
|
|
10
|
+
// Rows persist ModelSpec JSON (sparse `compat`, never the resolved record);
|
|
11
|
+
// the model manager rebuilds via `buildModel` on load. Request headers are
|
|
12
|
+
// intentionally omitted: arbitrary provider-defined header names can carry
|
|
13
|
+
// credentials. v12 invalidates Kimi Code rows carrying the blanket
|
|
14
|
+
// maxTokens: 32000 that predate per-family output caps (k3/k3-256k -> 131072,
|
|
15
|
+
// kimi-for-coding[-highspeed] -> 32768, #6711); v11 invalidates rows that may
|
|
16
|
+
// persist derived computer-use
|
|
17
|
+
// headers and records which model ids lost headers or cannot be rebuilt.
|
|
18
|
+
// v9 invalidated Kimi Code rows predating live effort and protocol metadata;
|
|
19
|
+
// v8 invalidated Codex discovery rows predating provider-native V2 compaction
|
|
20
|
+
// metadata; v7 invalidated rows predating the Antigravity Gemini budget-mode
|
|
21
|
+
// migration (cached specs still carrying `thinking.mode: "google-level"` and
|
|
22
|
+
// the old 3.5-flash effort routing); v6 invalidated rows that may contain the
|
|
23
|
+
// retired unknown-limit sentinels (222222/8888); v5 invalidated rows predating
|
|
24
|
+
// effort-tier variant collapsing (raw `-low`/`-high`/`-thinking` member ids);
|
|
25
|
+
// v4 dropped the pre-efforts ThinkingConfig shape.
|
|
26
|
+
const CACHE_SCHEMA_VERSION = 12;
|
|
27
|
+
const HEADER_RESTORE_VERSION = 1;
|
|
28
|
+
|
|
29
|
+
interface CacheRow {
|
|
30
|
+
provider_id: string;
|
|
31
|
+
version: number;
|
|
32
|
+
updated_at: number;
|
|
33
|
+
authoritative: number;
|
|
34
|
+
static_fingerprint: string;
|
|
35
|
+
models: string;
|
|
36
|
+
header_omitted_model_ids: string;
|
|
37
|
+
unrestorable_header_model_ids: string;
|
|
38
|
+
header_restore_version: number;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
interface TableInfoRow {
|
|
42
|
+
name: string;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
interface CacheEntry<TApi extends Api = Api> {
|
|
46
|
+
models: ModelSpec<TApi>[];
|
|
47
|
+
fresh: boolean;
|
|
48
|
+
authoritative: boolean;
|
|
49
|
+
updatedAt: number;
|
|
50
|
+
/** Model ids whose live headers were intentionally omitted from disk. */
|
|
51
|
+
headerOmittedModelIds: readonly string[];
|
|
52
|
+
/** Header-bearing model ids that cannot be rebuilt from the static source. */
|
|
53
|
+
unrestorableHeaderModelIds: readonly string[];
|
|
54
|
+
/** Whether unrestorable markers predate request-model header matching. */
|
|
55
|
+
legacyHeaderRestoreMarkers: boolean;
|
|
56
|
+
/**
|
|
57
|
+
* Hash of the static catalog slice that was merged into `models` when this
|
|
58
|
+
* row was written. `resolveProviderModels` compares against the current
|
|
59
|
+
* static fingerprint and bypasses the static+cache re-merge when they
|
|
60
|
+
* match — the cache already incorporates the same static state.
|
|
61
|
+
*/
|
|
62
|
+
staticFingerprint: string;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
let sharedDb: Database | null = null;
|
|
66
|
+
let sharedDbPath: string | null = null;
|
|
67
|
+
|
|
68
|
+
function openDb(resolvedPath: string): Database {
|
|
69
|
+
const db = new Database(resolvedPath, { create: true });
|
|
70
|
+
// Install the busy handler BEFORE any lock-taking statement. See
|
|
71
|
+
// https://github.com/can1357/oh-my-pi/issues/2421.
|
|
72
|
+
db.run("PRAGMA busy_timeout = 3000");
|
|
73
|
+
// Schema invalidation can delete rows containing credentials written by old
|
|
74
|
+
// versions. Overwrite deleted SQLite cells instead of leaving their bytes in
|
|
75
|
+
// free pages where a raw scan of models.db can still recover them (#5780).
|
|
76
|
+
db.run("PRAGMA secure_delete = ON");
|
|
77
|
+
db.run("PRAGMA journal_mode = WAL");
|
|
78
|
+
db.run(`
|
|
79
|
+
CREATE TABLE IF NOT EXISTS model_cache (
|
|
80
|
+
provider_id TEXT PRIMARY KEY,
|
|
81
|
+
version INTEGER NOT NULL,
|
|
82
|
+
updated_at INTEGER NOT NULL,
|
|
83
|
+
authoritative INTEGER NOT NULL DEFAULT 0,
|
|
84
|
+
static_fingerprint TEXT NOT NULL DEFAULT '',
|
|
85
|
+
header_omitted_model_ids TEXT NOT NULL DEFAULT '[]',
|
|
86
|
+
unrestorable_header_model_ids TEXT NOT NULL DEFAULT '[]',
|
|
87
|
+
header_restore_version INTEGER NOT NULL DEFAULT 0,
|
|
88
|
+
models TEXT NOT NULL
|
|
89
|
+
)
|
|
90
|
+
`);
|
|
91
|
+
migrateCacheSchema(db);
|
|
92
|
+
return db;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function getSharedDb(resolvedPath: string): Database {
|
|
96
|
+
if (sharedDb && sharedDbPath === resolvedPath) {
|
|
97
|
+
return sharedDb;
|
|
98
|
+
}
|
|
99
|
+
if (sharedDb) {
|
|
100
|
+
sharedDb.close();
|
|
101
|
+
sharedDb = null;
|
|
102
|
+
sharedDbPath = null;
|
|
103
|
+
}
|
|
104
|
+
const db = openDb(resolvedPath);
|
|
105
|
+
sharedDb = db;
|
|
106
|
+
sharedDbPath = resolvedPath;
|
|
107
|
+
return db;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function runModelCacheDb<T>(resolvedPath: string, shared: boolean, useDb: (db: Database) => T): T {
|
|
111
|
+
if (shared) return useDb(getSharedDb(resolvedPath));
|
|
112
|
+
const db = openDb(resolvedPath);
|
|
113
|
+
try {
|
|
114
|
+
return useDb(db);
|
|
115
|
+
} finally {
|
|
116
|
+
db.close();
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// Paths already reported corrupt this process: the first unrecoverable failure
|
|
121
|
+
// is logged at `error`, later heals at `debug`, so a dying disk cannot spam.
|
|
122
|
+
const reportedCorruptPaths = new Set<string>();
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Move a physically corrupt `models.db` (plus its `-wal`/`-shm` sidecars) aside
|
|
126
|
+
* so {@link openDb} can recreate a fresh cache at the original path. Renames are
|
|
127
|
+
* best-effort: a vanished sidecar (already healed by a peer process) is fine,
|
|
128
|
+
* and any other rename failure is left for {@link openDb} to surface.
|
|
129
|
+
*/
|
|
130
|
+
function quarantineCorruptModelCache(resolvedPath: string): void {
|
|
131
|
+
const stamp = Date.now();
|
|
132
|
+
for (const suffix of ["", "-wal", "-shm"]) {
|
|
133
|
+
try {
|
|
134
|
+
renameSync(`${resolvedPath}${suffix}`, `${resolvedPath}.corrupt-${stamp}${suffix}`);
|
|
135
|
+
} catch (err) {
|
|
136
|
+
if (!isEnoent(err)) {
|
|
137
|
+
logger.debug("model cache: could not quarantine corrupt file", { path: `${resolvedPath}${suffix}` });
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Recover from unrecoverable `models.db` corruption: drop the cached handle,
|
|
145
|
+
* quarantine the broken files, and let the next open recreate the cache. A
|
|
146
|
+
* corrupt cache would otherwise be re-queried on every read/write forever,
|
|
147
|
+
* permanently masking a successful live catalog (issue #8867). Only
|
|
148
|
+
* {@link isSqliteCorruptionError} codes reach here; BUSY/permission errors keep
|
|
149
|
+
* their existing best-effort paths.
|
|
150
|
+
*/
|
|
151
|
+
function healCorruptModelCache(resolvedPath: string, shared: boolean, err: unknown): void {
|
|
152
|
+
if (shared && sharedDb) {
|
|
153
|
+
sharedDb.close();
|
|
154
|
+
sharedDb = null;
|
|
155
|
+
sharedDbPath = null;
|
|
156
|
+
}
|
|
157
|
+
quarantineCorruptModelCache(resolvedPath);
|
|
158
|
+
const code = err && typeof err === "object" && "code" in err ? err.code : undefined;
|
|
159
|
+
if (reportedCorruptPaths.has(resolvedPath)) {
|
|
160
|
+
logger.debug("model cache: re-healed corrupt database", { path: resolvedPath, code });
|
|
161
|
+
} else {
|
|
162
|
+
reportedCorruptPaths.add(resolvedPath);
|
|
163
|
+
logger.error("model cache corrupt; quarantined and recreated a fresh cache", { path: resolvedPath, code });
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function withModelCacheDb<T>(dbPath: string | undefined, useDb: (db: Database) => T): T {
|
|
168
|
+
const resolvedPath = dbPath ?? getModelDbPath();
|
|
169
|
+
const shared = dbPath === undefined;
|
|
170
|
+
try {
|
|
171
|
+
return runModelCacheDb(resolvedPath, shared, useDb);
|
|
172
|
+
} catch (err) {
|
|
173
|
+
if (!isSqliteCorruptionError(err)) throw err;
|
|
174
|
+
healCorruptModelCache(resolvedPath, shared, err);
|
|
175
|
+
return runModelCacheDb(resolvedPath, shared, useDb);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function migrateCacheSchema(db: Database): void {
|
|
180
|
+
const stmt = db.prepare("PRAGMA table_info(model_cache)");
|
|
181
|
+
try {
|
|
182
|
+
const columns = stmt.all() as TableInfoRow[];
|
|
183
|
+
if (!columns.some(column => column.name === "static_fingerprint")) {
|
|
184
|
+
db.run("ALTER TABLE model_cache ADD COLUMN static_fingerprint TEXT NOT NULL DEFAULT ''");
|
|
185
|
+
}
|
|
186
|
+
if (!columns.some(column => column.name === "header_omitted_model_ids")) {
|
|
187
|
+
db.run("ALTER TABLE model_cache ADD COLUMN header_omitted_model_ids TEXT NOT NULL DEFAULT '[]'");
|
|
188
|
+
}
|
|
189
|
+
if (!columns.some(column => column.name === "unrestorable_header_model_ids")) {
|
|
190
|
+
db.run("ALTER TABLE model_cache ADD COLUMN unrestorable_header_model_ids TEXT NOT NULL DEFAULT '[]'");
|
|
191
|
+
}
|
|
192
|
+
if (!columns.some(column => column.name === "header_restore_version")) {
|
|
193
|
+
// Existing v10 rows get 0, distinguishing markers produced by the
|
|
194
|
+
// old id-only header matcher from rows written after request-model
|
|
195
|
+
// header matching was introduced.
|
|
196
|
+
db.run("ALTER TABLE model_cache ADD COLUMN header_restore_version INTEGER NOT NULL DEFAULT 0");
|
|
197
|
+
}
|
|
198
|
+
} finally {
|
|
199
|
+
stmt.finalize();
|
|
200
|
+
}
|
|
201
|
+
// Delete rows written under any older schema so they cannot be reused. The
|
|
202
|
+
// legacy `UPDATE ... WHERE version = 2` migration silently promoted the very
|
|
203
|
+
// first cache version to whatever the current one is, defeating every
|
|
204
|
+
// subsequent invalidation (see #4146: pre-V2 Codex rows kept the legacy
|
|
205
|
+
// compaction path even after CACHE_SCHEMA_VERSION was bumped).
|
|
206
|
+
db.run("DELETE FROM model_cache WHERE version <> ?", [CACHE_SCHEMA_VERSION]);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
export function readModelCache<TApi extends Api>(
|
|
210
|
+
providerId: string,
|
|
211
|
+
ttlMs: number,
|
|
212
|
+
now: () => number,
|
|
213
|
+
dbPath?: string,
|
|
214
|
+
): CacheEntry<TApi> | null {
|
|
215
|
+
try {
|
|
216
|
+
return withModelCacheDb(dbPath, db => {
|
|
217
|
+
const stmt = db.query<CacheRow, [string]>("SELECT * FROM model_cache WHERE provider_id = ?");
|
|
218
|
+
try {
|
|
219
|
+
const row = stmt.get(providerId);
|
|
220
|
+
if (!row || row.version !== CACHE_SCHEMA_VERSION) {
|
|
221
|
+
return null;
|
|
222
|
+
}
|
|
223
|
+
const models = JSON.parse(row.models) as ModelSpec<TApi>[];
|
|
224
|
+
const parsedHeaderModelIds: unknown = JSON.parse(row.header_omitted_model_ids);
|
|
225
|
+
const headerOmittedModelIds = Array.isArray(parsedHeaderModelIds)
|
|
226
|
+
? parsedHeaderModelIds.filter((id): id is string => typeof id === "string")
|
|
227
|
+
: [];
|
|
228
|
+
const parsedUnrestorableModelIds: unknown = JSON.parse(row.unrestorable_header_model_ids);
|
|
229
|
+
const unrestorableHeaderModelIds = Array.isArray(parsedUnrestorableModelIds)
|
|
230
|
+
? parsedUnrestorableModelIds.filter((id): id is string => typeof id === "string")
|
|
231
|
+
: [];
|
|
232
|
+
const ageMs = now() - row.updated_at;
|
|
233
|
+
const fresh = Number.isFinite(ageMs) && ageMs >= 0 && ageMs <= ttlMs;
|
|
234
|
+
return {
|
|
235
|
+
models,
|
|
236
|
+
fresh,
|
|
237
|
+
authoritative: row.authoritative === 1,
|
|
238
|
+
updatedAt: row.updated_at,
|
|
239
|
+
headerOmittedModelIds,
|
|
240
|
+
unrestorableHeaderModelIds,
|
|
241
|
+
legacyHeaderRestoreMarkers: row.header_restore_version < HEADER_RESTORE_VERSION,
|
|
242
|
+
staticFingerprint: row.static_fingerprint ?? "",
|
|
243
|
+
};
|
|
244
|
+
} finally {
|
|
245
|
+
stmt.finalize();
|
|
246
|
+
}
|
|
247
|
+
});
|
|
248
|
+
} catch {
|
|
249
|
+
return null;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** Whether a live model carries at least one request header. */
|
|
254
|
+
function hasModelHeaders(model: Model<Api>): boolean {
|
|
255
|
+
const headers = model.headers;
|
|
256
|
+
if (!headers) return false;
|
|
257
|
+
for (const _key in headers) return true;
|
|
258
|
+
return false;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* Project a live model to cache-safe metadata.
|
|
263
|
+
*
|
|
264
|
+
* Headers are never persisted: custom/runtime providers may use arbitrary
|
|
265
|
+
* credential header names, so no name-based filter can be complete. The
|
|
266
|
+
* separately persisted model-id list lets the manager restore matching static
|
|
267
|
+
* headers and reject/refetch dynamic-only cached models that need live headers.
|
|
268
|
+
*/
|
|
269
|
+
function toCachedModelSpec<TApi extends Api>(model: Model<TApi>): ModelSpec<TApi> {
|
|
270
|
+
const { headers: _headers, compatConfig, supportsComputerUseConfig, ...rest } = model;
|
|
271
|
+
return { ...rest, supportsComputerUse: supportsComputerUseConfig, compat: compatConfig };
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** Whether two in-memory header records are byte-for-byte equivalent. */
|
|
275
|
+
function headersEqual(left: Record<string, string> | undefined, right: Record<string, string> | undefined): boolean {
|
|
276
|
+
if (!left || !right) return left === right;
|
|
277
|
+
for (const key in left) {
|
|
278
|
+
if (right[key] !== left[key]) return false;
|
|
279
|
+
}
|
|
280
|
+
for (const key in right) {
|
|
281
|
+
if (!(key in left)) return false;
|
|
282
|
+
}
|
|
283
|
+
return true;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
export function writeModelCache<TApi extends Api>(
|
|
287
|
+
providerId: string,
|
|
288
|
+
updatedAt: number,
|
|
289
|
+
models: Model<TApi>[],
|
|
290
|
+
authoritative: boolean,
|
|
291
|
+
staticFingerprint: string,
|
|
292
|
+
dbPath?: string,
|
|
293
|
+
staticHeaderSources: readonly Model<TApi>[] = [],
|
|
294
|
+
restorableHeaderFallback?: Record<string, string>,
|
|
295
|
+
): void {
|
|
296
|
+
try {
|
|
297
|
+
withModelCacheDb(dbPath, db => {
|
|
298
|
+
const headerOmittedModelIds: string[] = [];
|
|
299
|
+
const unrestorableHeaderModelIds: string[] = [];
|
|
300
|
+
const cachedModels: ModelSpec<TApi>[] = [];
|
|
301
|
+
const staticById = new Map(staticHeaderSources.map(model => [model.id, model]));
|
|
302
|
+
for (const model of models) {
|
|
303
|
+
if (hasModelHeaders(model)) {
|
|
304
|
+
headerOmittedModelIds.push(model.id);
|
|
305
|
+
// Synthesized variants (e.g. Copilot `-1m`) have no same-id static
|
|
306
|
+
// entry; their headers come from the `requestModelId` base. Match
|
|
307
|
+
// against that source too, else they are wrongly flagged
|
|
308
|
+
// unrestorable and dropped on the next offline read (#6037, #6284).
|
|
309
|
+
const staticHeaderSource =
|
|
310
|
+
staticById.get(model.id) ?? (model.requestModelId ? staticById.get(model.requestModelId) : undefined);
|
|
311
|
+
// A model with no static source is still restorable when its live
|
|
312
|
+
// headers equal a trusted provider-wide fallback that the reader can
|
|
313
|
+
// re-derive without persisting it. This keeps reference-less models
|
|
314
|
+
// with constant or configured headers alive offline.
|
|
315
|
+
const matchesStatic = staticHeaderSource
|
|
316
|
+
? headersEqual(model.headers, staticHeaderSource.headers)
|
|
317
|
+
: headersEqual(model.headers, restorableHeaderFallback);
|
|
318
|
+
if (!matchesStatic) {
|
|
319
|
+
unrestorableHeaderModelIds.push(model.id);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
cachedModels.push(toCachedModelSpec(model));
|
|
323
|
+
}
|
|
324
|
+
db.run(
|
|
325
|
+
`INSERT OR REPLACE INTO model_cache (
|
|
326
|
+
provider_id, version, updated_at, authoritative, static_fingerprint,
|
|
327
|
+
header_omitted_model_ids, unrestorable_header_model_ids,
|
|
328
|
+
header_restore_version, models
|
|
329
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
330
|
+
[
|
|
331
|
+
providerId,
|
|
332
|
+
CACHE_SCHEMA_VERSION,
|
|
333
|
+
updatedAt,
|
|
334
|
+
authoritative ? 1 : 0,
|
|
335
|
+
staticFingerprint,
|
|
336
|
+
JSON.stringify(headerOmittedModelIds),
|
|
337
|
+
JSON.stringify(unrestorableHeaderModelIds),
|
|
338
|
+
HEADER_RESTORE_VERSION,
|
|
339
|
+
JSON.stringify(cachedModels),
|
|
340
|
+
],
|
|
341
|
+
);
|
|
342
|
+
});
|
|
343
|
+
} catch {
|
|
344
|
+
// Cache writes are best-effort; failures should not break model resolution.
|
|
345
|
+
}
|
|
346
|
+
}
|