@theokit/sdk 5.9.1 → 5.10.0
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 +119 -0
- package/dist/{agent-enXXu447.d.ts → agent-CmKwSyyD.d.ts} +27 -0
- package/dist/{agent-5M7WLUWH.cjs → agent-TLRURB7W.cjs} +18 -16
- package/dist/{agent-5M7WLUWH.cjs.map → agent-TLRURB7W.cjs.map} +1 -1
- package/dist/{agent-Dh2YHSLj.d.cts → agent-XMkGzff_.d.cts} +27 -0
- package/dist/{agent-R5RERYFU.js → agent-XTLAVVYC.js} +17 -15
- package/dist/{agent-R5RERYFU.js.map → agent-XTLAVVYC.js.map} +1 -1
- package/dist/agent-session-store-ODD3IZCW.js +6 -0
- package/dist/{agent-session-store-AFML3AXC.js.map → agent-session-store-ODD3IZCW.js.map} +1 -1
- package/dist/agent-session-store-SVEJHSUA.cjs +23 -0
- package/dist/{agent-session-store-MTSIY3MH.cjs.map → agent-session-store-SVEJHSUA.cjs.map} +1 -1
- package/dist/auth/index.cjs +8 -7
- package/dist/auth/index.cjs.map +1 -1
- package/dist/auth/index.js +3 -2
- package/dist/auth/index.js.map +1 -1
- package/dist/{chunk-QCIARBLS.js → chunk-523O5UYB.js} +3 -3
- package/dist/{chunk-QCIARBLS.js.map → chunk-523O5UYB.js.map} +1 -1
- package/dist/chunk-7KIN3L2S.js +103 -0
- package/dist/chunk-7KIN3L2S.js.map +1 -0
- package/dist/chunk-ASK2OQM5.cjs +84 -0
- package/dist/chunk-ASK2OQM5.cjs.map +1 -0
- package/dist/{chunk-56BCEM26.cjs → chunk-CVEQ5366.cjs} +105 -91
- package/dist/chunk-CVEQ5366.cjs.map +1 -0
- package/dist/{chunk-R2C3HXR3.js → chunk-DPY2M74T.js} +3 -3
- package/dist/{chunk-R2C3HXR3.js.map → chunk-DPY2M74T.js.map} +1 -1
- package/dist/chunk-EHD25JBZ.cjs +10 -0
- package/dist/chunk-EHD25JBZ.cjs.map +1 -0
- package/dist/{chunk-NOO6GZTZ.js → chunk-EVH3OUMY.js} +13 -12
- package/dist/chunk-EVH3OUMY.js.map +1 -0
- package/dist/{chunk-5522X223.js → chunk-EXI7EHDN.js} +4 -4
- package/dist/{chunk-5522X223.js.map → chunk-EXI7EHDN.js.map} +1 -1
- package/dist/{chunk-PSLCVSCS.cjs → chunk-FR6COQXZ.cjs} +6 -6
- package/dist/{chunk-PSLCVSCS.cjs.map → chunk-FR6COQXZ.cjs.map} +1 -1
- package/dist/{chunk-JOFVLOFY.js → chunk-FTZTZBCU.js} +12 -4
- package/dist/chunk-FTZTZBCU.js.map +1 -0
- package/dist/{chunk-T5KOSR5Y.cjs → chunk-FYEHYQ7T.cjs} +8 -8
- package/dist/{chunk-T5KOSR5Y.cjs.map → chunk-FYEHYQ7T.cjs.map} +1 -1
- package/dist/{chunk-HOHR75KF.js → chunk-HI3W37FY.js} +4 -3
- package/dist/chunk-HI3W37FY.js.map +1 -0
- package/dist/chunk-HU666T3Q.cjs +1891 -0
- package/dist/chunk-HU666T3Q.cjs.map +1 -0
- package/dist/{chunk-53RDNK3H.js → chunk-I2ORT6QD.js} +3 -3
- package/dist/{chunk-53RDNK3H.js.map → chunk-I2ORT6QD.js.map} +1 -1
- package/dist/{chunk-UNZOJVVC.js → chunk-IZDDSLL2.js} +5 -4
- package/dist/chunk-IZDDSLL2.js.map +1 -0
- package/dist/{chunk-TTBIQTO5.cjs → chunk-L3C6CCBG.cjs} +15 -15
- package/dist/{chunk-TTBIQTO5.cjs.map → chunk-L3C6CCBG.cjs.map} +1 -1
- package/dist/{chunk-B3XXQX6L.cjs → chunk-NQVWSSX2.cjs} +10 -9
- package/dist/chunk-NQVWSSX2.cjs.map +1 -0
- package/dist/{chunk-LL4QA3DI.cjs → chunk-PCLRIQPX.cjs} +4 -4
- package/dist/{chunk-LL4QA3DI.cjs.map → chunk-PCLRIQPX.cjs.map} +1 -1
- package/dist/chunk-Q7GYMXVC.js +8 -0
- package/dist/chunk-Q7GYMXVC.js.map +1 -0
- package/dist/{chunk-ARMFXTY6.cjs → chunk-QY3CIMUV.cjs} +34 -33
- package/dist/chunk-QY3CIMUV.cjs.map +1 -0
- package/dist/chunk-R5YPDAKD.cjs +108 -0
- package/dist/chunk-R5YPDAKD.cjs.map +1 -0
- package/dist/chunk-RGQICWFU.js +82 -0
- package/dist/chunk-RGQICWFU.js.map +1 -0
- package/dist/{chunk-OOM236Z4.js → chunk-RTE2DD4S.js} +32 -18
- package/dist/chunk-RTE2DD4S.js.map +1 -0
- package/dist/chunk-SGC7LSHF.cjs +18 -0
- package/dist/{chunk-R3ZQBPA5.cjs.map → chunk-SGC7LSHF.cjs.map} +1 -1
- package/dist/{chunk-RA7IE4NK.cjs → chunk-SKDNCTXG.cjs} +4 -3
- package/dist/chunk-SKDNCTXG.cjs.map +1 -0
- package/dist/chunk-SVCPJRUB.js +1874 -0
- package/dist/chunk-SVCPJRUB.js.map +1 -0
- package/dist/{chunk-EJROML3Q.js → chunk-TX56N7FR.js} +4 -3
- package/dist/chunk-TX56N7FR.js.map +1 -0
- package/dist/{chunk-QDQQYRJI.js → chunk-W2ZVTEOD.js} +3 -3
- package/dist/{chunk-QDQQYRJI.js.map → chunk-W2ZVTEOD.js.map} +1 -1
- package/dist/{chunk-TC4RWP3Y.js → chunk-X3LOJJMO.js} +89 -29
- package/dist/chunk-X3LOJJMO.js.map +1 -0
- package/dist/{chunk-2WXHA33T.js → chunk-XERM7PDQ.js} +3 -3
- package/dist/{chunk-2WXHA33T.js.map → chunk-XERM7PDQ.js.map} +1 -1
- package/dist/{chunk-MEUBLCM4.cjs → chunk-YEHQ3SIC.cjs} +4 -3
- package/dist/chunk-YEHQ3SIC.cjs.map +1 -0
- package/dist/{chunk-YIFFF23U.cjs → chunk-ZAM7BJXJ.cjs} +5 -5
- package/dist/{chunk-YIFFF23U.cjs.map → chunk-ZAM7BJXJ.cjs.map} +1 -1
- package/dist/{chunk-76PIKR4P.cjs → chunk-ZD66GFH5.cjs} +91 -29
- package/dist/chunk-ZD66GFH5.cjs.map +1 -0
- package/dist/{chunk-GZV6AVRL.cjs → chunk-ZWACQM5U.cjs} +11 -3
- package/dist/chunk-ZWACQM5U.cjs.map +1 -0
- package/dist/{compact-session-RBPLUPCK.cjs → compact-session-4QHBBGEY.cjs} +16 -15
- package/dist/{compact-session-RBPLUPCK.cjs.map → compact-session-4QHBBGEY.cjs.map} +1 -1
- package/dist/{compact-session-2N3ZYJTW.js → compact-session-PVAWTKKL.js} +7 -6
- package/dist/{compact-session-2N3ZYJTW.js.map → compact-session-PVAWTKKL.js.map} +1 -1
- package/dist/{cron-DTuaPMVI.d.ts → cron-BPccQCO8.d.ts} +1 -1
- package/dist/{cron-QTgcwcZt.d.cts → cron-Blj6wMYg.d.cts} +1 -1
- package/dist/cron.cjs +17 -15
- package/dist/cron.d.cts +2 -2
- package/dist/cron.d.ts +2 -2
- package/dist/cron.js +16 -14
- package/dist/eval.cjs +20 -18
- package/dist/eval.cjs.map +1 -1
- package/dist/eval.js +16 -14
- package/dist/eval.js.map +1 -1
- package/dist/fs-session-store-3VI4CPTX.js +11 -0
- package/dist/{fs-session-store-STZZFXH2.js.map → fs-session-store-3VI4CPTX.js.map} +1 -1
- package/dist/fs-session-store-IQ6PEHYF.cjs +20 -0
- package/dist/{fs-session-store-JHBJFKVV.cjs.map → fs-session-store-IQ6PEHYF.cjs.map} +1 -1
- package/dist/{index-manager-ONQJSWX5.js → index-manager-JVYIVTZG.js} +6 -5
- package/dist/{index-manager-ONQJSWX5.js.map → index-manager-JVYIVTZG.js.map} +1 -1
- package/dist/{index-manager-ZGJN25FD.cjs → index-manager-YGXRFJMZ.cjs} +7 -6
- package/dist/{index-manager-ZGJN25FD.cjs.map → index-manager-YGXRFJMZ.cjs.map} +1 -1
- package/dist/index.cjs +68 -60
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +42 -6
- package/dist/index.d.ts +42 -6
- package/dist/index.js +31 -23
- package/dist/index.js.map +1 -1
- package/dist/{inject-session-YNNOE3O6.js → inject-session-O24XGRR6.js} +5 -5
- package/dist/{inject-session-YNNOE3O6.js.map → inject-session-O24XGRR6.js.map} +1 -1
- package/dist/{inject-session-3FPXJDJP.cjs → inject-session-OMLFL2V3.cjs} +7 -7
- package/dist/{inject-session-3FPXJDJP.cjs.map → inject-session-OMLFL2V3.cjs.map} +1 -1
- package/dist/internal/memory/adapters/index.cjs +3 -2
- package/dist/internal/memory/adapters/index.js +2 -1
- package/dist/internal/memory/dreaming/phases.d.ts +2 -0
- package/dist/internal/memory/dreaming/run.d.ts +5 -0
- package/dist/internal/memory/sdk-memory-peer-loader.d.ts +2 -0
- package/dist/internal/memory/storage/fact-ceiling.d.cts +19 -0
- package/dist/internal/memory/storage/fact-ceiling.d.ts +19 -0
- package/dist/internal/memory/storage/index.cjs +41 -32
- package/dist/internal/memory/storage/index.d.cts +1 -0
- package/dist/internal/memory/storage/index.d.ts +1 -0
- package/dist/internal/memory/storage/index.js +4 -3
- package/dist/internal/memory/storage/markdown-store.d.cts +3 -1
- package/dist/internal/memory/storage/markdown-store.d.ts +3 -1
- package/dist/internal/memory/types.d.ts +6 -0
- package/dist/internal/persistence/index.cjs +7 -6
- package/dist/internal/persistence/index.cjs.map +1 -1
- package/dist/internal/persistence/index.js +2 -1
- package/dist/internal/persistence/index.js.map +1 -1
- package/dist/internal/persistence/persistence-schema.d.cts +1 -1
- package/dist/internal/persistence/persistence-schema.d.ts +1 -1
- package/dist/internal/providers/catalog-loader.d.ts +30 -3
- package/dist/internal/runtime/registry/agent-registry-store.d.ts +2 -0
- package/dist/internal/runtime-fetch.d.ts +1 -0
- package/dist/models.cjs +12 -11
- package/dist/models.cjs.map +1 -1
- package/dist/models.js +4 -3
- package/dist/models.js.map +1 -1
- package/dist/persistence.cjs +14 -13
- package/dist/persistence.cjs.map +1 -1
- package/dist/persistence.js +4 -3
- package/dist/persistence.js.map +1 -1
- package/dist/providers.cjs +6 -5
- package/dist/providers.js +4 -3
- package/dist/{session-transcript-VTBTCGQX.js → session-transcript-AR7IBICT.js} +3 -3
- package/dist/{session-transcript-VTBTCGQX.js.map → session-transcript-AR7IBICT.js.map} +1 -1
- package/dist/{session-transcript-LGHSNVY5.cjs → session-transcript-RACG7BK2.cjs} +16 -16
- package/dist/{session-transcript-LGHSNVY5.cjs.map → session-transcript-RACG7BK2.cjs.map} +1 -1
- package/dist/subagents-loader.d.cts +1 -1
- package/dist/subagents-loader.d.ts +1 -1
- package/dist/subscription/index.cjs +2 -1
- package/dist/subscription/index.cjs.map +1 -1
- package/dist/subscription/index.js +2 -1
- package/dist/subscription/index.js.map +1 -1
- package/dist/types/agent.d.ts +27 -0
- package/docs/error-codes.md +40 -38
- package/docs/harness-capability-map.md +6 -1
- package/package.json +2 -2
- package/dist/agent-session-store-AFML3AXC.js +0 -6
- package/dist/agent-session-store-MTSIY3MH.cjs +0 -23
- package/dist/chunk-56BCEM26.cjs.map +0 -1
- package/dist/chunk-76PIKR4P.cjs.map +0 -1
- package/dist/chunk-ARMFXTY6.cjs.map +0 -1
- package/dist/chunk-B3XXQX6L.cjs.map +0 -1
- package/dist/chunk-BKMDRBJ7.js +0 -180
- package/dist/chunk-BKMDRBJ7.js.map +0 -1
- package/dist/chunk-EJROML3Q.js.map +0 -1
- package/dist/chunk-GZV6AVRL.cjs.map +0 -1
- package/dist/chunk-HOHR75KF.js.map +0 -1
- package/dist/chunk-JOFVLOFY.js.map +0 -1
- package/dist/chunk-MEUBLCM4.cjs.map +0 -1
- package/dist/chunk-MFZODA5Y.js +0 -583
- package/dist/chunk-MFZODA5Y.js.map +0 -1
- package/dist/chunk-NOO6GZTZ.js.map +0 -1
- package/dist/chunk-OF2CLCTH.cjs +0 -186
- package/dist/chunk-OF2CLCTH.cjs.map +0 -1
- package/dist/chunk-OOM236Z4.js.map +0 -1
- package/dist/chunk-R3ZQBPA5.cjs +0 -18
- package/dist/chunk-RA7IE4NK.cjs.map +0 -1
- package/dist/chunk-TC4RWP3Y.js.map +0 -1
- package/dist/chunk-UNZOJVVC.js.map +0 -1
- package/dist/chunk-YRJA2POB.cjs +0 -601
- package/dist/chunk-YRJA2POB.cjs.map +0 -1
- package/dist/fs-session-store-JHBJFKVV.cjs +0 -19
- package/dist/fs-session-store-STZZFXH2.js +0 -10
- package/dist/provider-catalog.json +0 -1295
|
@@ -1,8 +1,35 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* Provider catalog loader (T10.1, ADR D447).
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
4
|
+
* Provider metadata, EMBEDDED at build time. Malformed entries are skipped with WARN (EC-1) — never
|
|
5
|
+
* crash.
|
|
6
|
+
*
|
|
7
|
+
* ## Why embedded and not read from disk
|
|
8
|
+
*
|
|
9
|
+
* It used to be `readFileSync` from a directory computed as
|
|
10
|
+
* `dirname(fileURLToPath(import.meta.url))` at module scope. Both halves break on a runtime with no
|
|
11
|
+
* filesystem, in that order, and this file is only model METADATA — so an environment that could not
|
|
12
|
+
* read it could not run a turn at all.
|
|
13
|
+
*
|
|
14
|
+
* Measured end to end on 2026-09-28, driving a real deploy of a TheoKit app (theokit#705):
|
|
15
|
+
*
|
|
16
|
+
* 1. Cloudflare EXECUTES the top-level module during validation, so the upload was refused before
|
|
17
|
+
* any request existed — `The "path" argument must be of type string … Received undefined`,
|
|
18
|
+
* code 10021.
|
|
19
|
+
* 2. With `import.meta.url` substituted by the consumer's bundler, the module initialised and the
|
|
20
|
+
* TURN failed: `[unenv] fs.readFileSync is not implemented yet!`
|
|
21
|
+
* 3. With a newer `compatibility_date`, workerd implements `readFileSync` and the error became the
|
|
22
|
+
* honest one: `ENOENT: readAll '/provider-catalog.json'`. The same `ENOENT` reached a deployed
|
|
23
|
+
* Vercel function, whose bundle carries the JS and not the JSON.
|
|
24
|
+
*
|
|
25
|
+
* No consumer's bundler can fix that from outside. Probed from inside a deployed worker, workerd's
|
|
26
|
+
* whole virtual filesystem is `/bundle/worker.js`, an empty `/tmp` and `/dev` — there is nowhere to
|
|
27
|
+
* put this package's private data file such that `join(dirname(<a file URL>), …)` finds it, short of
|
|
28
|
+
* hardcoding our internal layout into their build.
|
|
29
|
+
*
|
|
30
|
+
* `with { type: "json" }` follows `internal/budget/pricing-registry.ts`, which has imported a sibling
|
|
31
|
+
* JSON exactly this way in this package for as long as it has existed. Bundlers inline it, so the
|
|
32
|
+
* emitted module carries the data and reaches for nothing.
|
|
6
33
|
*
|
|
7
34
|
* @internal
|
|
8
35
|
*/
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/models.cjs
CHANGED
|
@@ -2,11 +2,12 @@
|
|
|
2
2
|
|
|
3
3
|
var chunk72CPLZPC_cjs = require('./chunk-72CPLZPC.cjs');
|
|
4
4
|
var chunk3EE6LVWT_cjs = require('./chunk-3EE6LVWT.cjs');
|
|
5
|
-
var
|
|
5
|
+
var chunkHU666T3Q_cjs = require('./chunk-HU666T3Q.cjs');
|
|
6
6
|
require('./chunk-NVXXWAU7.cjs');
|
|
7
|
-
require('./chunk-
|
|
7
|
+
require('./chunk-SKDNCTXG.cjs');
|
|
8
8
|
require('./chunk-NAGPKWOD.cjs');
|
|
9
9
|
require('./chunk-OLSEWLK5.cjs');
|
|
10
|
+
var chunkEHD25JBZ_cjs = require('./chunk-EHD25JBZ.cjs');
|
|
10
11
|
require('./chunk-UNFBHV46.cjs');
|
|
11
12
|
var chunk6LHQPOMI_cjs = require('./chunk-6LHQPOMI.cjs');
|
|
12
13
|
var crypto = require('crypto');
|
|
@@ -36,11 +37,11 @@ function capsFromCatalog(m) {
|
|
|
36
37
|
}
|
|
37
38
|
function resolveModelCapabilities(modelId) {
|
|
38
39
|
const bare = stripVariantSuffix(stripRoutingPrefix(modelId));
|
|
39
|
-
const fromIndex =
|
|
40
|
+
const fromIndex = chunkHU666T3Q_cjs.getCatalogModelInfo(bare);
|
|
40
41
|
if (fromIndex !== void 0) return capsFromCatalog(fromIndex);
|
|
41
42
|
const withVendor = inferVendorPrefix(bare);
|
|
42
43
|
if (withVendor !== bare) {
|
|
43
|
-
const vendored =
|
|
44
|
+
const vendored = chunkHU666T3Q_cjs.getCatalogModelInfo(withVendor);
|
|
44
45
|
if (vendored !== void 0) return capsFromCatalog(vendored);
|
|
45
46
|
}
|
|
46
47
|
return CONSERVATIVE_DEFAULTS;
|
|
@@ -132,7 +133,7 @@ function catalogTargets() {
|
|
|
132
133
|
if (_catalogTargets !== void 0) return _catalogTargets;
|
|
133
134
|
_catalogTargets = /* @__PURE__ */ new Map();
|
|
134
135
|
try {
|
|
135
|
-
for (const entry of Object.values(
|
|
136
|
+
for (const entry of Object.values(chunkHU666T3Q_cjs.loadProviderCatalog())) {
|
|
136
137
|
const keys = [entry.id, ...entry.aliases ?? []];
|
|
137
138
|
for (const k of keys) {
|
|
138
139
|
if (!_catalogTargets.has(k)) _catalogTargets.set(k, { keys });
|
|
@@ -146,7 +147,7 @@ function resolvePatchKeys(externalId) {
|
|
|
146
147
|
const mapped = MODELS_DEV_ID_MAP[externalId] ?? externalId;
|
|
147
148
|
const fromCatalog = catalogTargets().get(mapped);
|
|
148
149
|
if (fromCatalog !== void 0) return fromCatalog.keys;
|
|
149
|
-
const profile =
|
|
150
|
+
const profile = chunkHU666T3Q_cjs.getProviderProfile(mapped);
|
|
150
151
|
if (profile !== void 0) return [profile.name, ...profile.aliases ?? []];
|
|
151
152
|
return void 0;
|
|
152
153
|
}
|
|
@@ -163,9 +164,9 @@ function patchIndexFromApiJson(raw) {
|
|
|
163
164
|
continue;
|
|
164
165
|
}
|
|
165
166
|
for (const [modelId, rawModel] of Object.entries(models)) {
|
|
166
|
-
const parsed =
|
|
167
|
+
const parsed = chunkHU666T3Q_cjs.catalogModelSchema.safeParse(rawModel);
|
|
167
168
|
if (!parsed.success) continue;
|
|
168
|
-
for (const key of keys)
|
|
169
|
+
for (const key of keys) chunkHU666T3Q_cjs.patchModelInfo(`${key}/${modelId}`, parsed.data);
|
|
169
170
|
patched++;
|
|
170
171
|
}
|
|
171
172
|
}
|
|
@@ -265,7 +266,7 @@ function persistAndPatch(path, body) {
|
|
|
265
266
|
}
|
|
266
267
|
}
|
|
267
268
|
async function refreshModelCatalog(opts = {}) {
|
|
268
|
-
|
|
269
|
+
chunkHU666T3Q_cjs.registerBuiltins();
|
|
269
270
|
if (fetchDisabledByEnv()) return { source: "skipped", models: 0 };
|
|
270
271
|
const url = opts.url ?? process.env.THEOKIT_MODELS_URL ?? DEFAULT_URL;
|
|
271
272
|
const path = cachePathFor(url);
|
|
@@ -274,12 +275,12 @@ async function refreshModelCatalog(opts = {}) {
|
|
|
274
275
|
const cached = servedFromFreshCache(url, path, now);
|
|
275
276
|
if (cached !== void 0) return cached;
|
|
276
277
|
}
|
|
277
|
-
const body = await fetchCatalogBody(url, opts.deps?.fetch
|
|
278
|
+
const body = await fetchCatalogBody(url, chunkEHD25JBZ_cjs.boundFetch(opts.deps?.fetch));
|
|
278
279
|
if (body === void 0) return { source: "cache", models: loadCacheIntoIndex(url) };
|
|
279
280
|
return persistAndPatch(path, body);
|
|
280
281
|
}
|
|
281
282
|
function getModelInfo(modelId) {
|
|
282
|
-
return
|
|
283
|
+
return chunkHU666T3Q_cjs.getCatalogModelInfo(modelId);
|
|
283
284
|
}
|
|
284
285
|
|
|
285
286
|
Object.defineProperty(exports, "parseModelId", {
|
package/dist/models.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/llm/model-capabilities.ts","../src/internal/llm/model-option.ts","../src/internal/providers/catalog-source-models-dev.ts"],"names":["getCatalogModelInfo","parseModelId","join","homedir","createHash","path","mkdirSync","dirname","randomBytes","writeFileSync","renameSync","unlinkSync","loadProviderCatalog","getProviderProfile","catalogModelSchema","patchModelInfo","diag","readFileSync","statSync","Retry","registerBuiltins"],"mappings":";;;;;;;;;;;;;;;;;AAgCA,IAAM,qBAAA,GAA2C;AAAA,EAC/C,cAAA,EAAgB,KAAA;AAA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AA,CAAQ,IAAI,kBAAA,IAAsB,WAAA;AAC1D,EAAA,MAAM,IAAA,GAAO,aAAa,GAAG,CAAA;AAC7B,EAAA,MAAM,MAAM,IAAA,CAAK,IAAA,EAAM,GAAA,KAAQ,MAAM,KAAK,GAAA,EAAI,CAAA;AAE9C,EAAA,IAAI,IAAA,CAAK,UAAU,IAAA,EAAM;AACvB,IAAA,MAAM,MAAA,GAAS,oBAAA,CAAqB,GAAA,EAAK,IAAA,EAAM,GAAG,CAAA;AAClD,IAAA,IAAI,MAAA,KAAW,QAAW,OAAO,MAAA;AAAA,EACnC;AAEA,EAAA,MAAM,OAAO,MAAM,gBAAA,CAAiB,KAAK,IAAA,CAAK,IAAA,EAAM,SAAS,KAAK,CAAA;AAElE,EAAA,IAAI,IAAA,KAAS,QAAW,OAAO,EAAE,QAAQ,OAAA,EAAS,MAAA,EAAQ,kBAAA,CAAmB,GAAG,CAAA,EAAE;AAElF,EAAA,OAAO,eAAA,CAAgB,MAAM,IAAI,CAAA;AACnC;AAGO,SAAS,aAAa,OAAA,EAAyD;AACpF,EAAA,OAAOpB,sCAAoB,OAAO,CAAA;AACpC","file":"models.cjs","sourcesContent":["/**\n * T3.10c — Model capability registry (DR3 #17).\n *\n * Typed per-model flags that let the SDK gate features at the boundary\n * (before hitting the provider) instead of letting opaque 400s surface.\n *\n * Resolution algorithm:\n * 1. Strip routing prefixes (openrouter/, vertex/, bedrock/) AND the\n * OpenRouter `:variant` suffix (:free/:nitro/…) to find the bare vendor id.\n * 2. Exact match in the `EXACT` catalog → return entry.\n * 3. Vendor inference (e.g., `claude-*` → `anthropic/claude-*`) → return entry.\n * 4. No match → conservative defaults (all false, minimum tokens).\n *\n * Module is internal, but `ModelCapabilities` + `resolveModelCapabilities` are\n * re-exported publicly via the `@theokit/sdk/models` subpath (see their @public tags).\n */\n\n/**\n * Per-model capability shape. Consumers use this to gate features at\n * the SDK boundary (before request construction, not after 400).\n *\n * @public\n */\nexport interface ModelCapabilities {\n supportsVision: boolean;\n supportsStructuredOutput: boolean;\n supportsToolUse: boolean;\n supportsCacheControl: boolean;\n maxContextTokens: number;\n maxOutputTokens: number;\n}\n\nconst CONSERVATIVE_DEFAULTS: ModelCapabilities = {\n supportsVision: false,\n supportsStructuredOutput: false,\n supportsToolUse: false,\n supportsCacheControl: false,\n maxContextTokens: 4096,\n maxOutputTokens: 4096,\n};\n\n/** Routing prefixes to strip to find the underlying vendor model. */\nconst ROUTING_PREFIXES = [\"openrouter/\", \"vertex/\", \"bedrock/\"] as const;\n\nimport { getCatalogModelInfo } from \"../providers/catalog-loader.js\";\nimport type { CatalogModel } from \"../providers/catalog-schema.js\";\n\n/** Map a catalog model block (models.dev shape) to the SDK's ModelCapabilities (M44 — catalog-backed). */\nfunction capsFromCatalog(m: CatalogModel): ModelCapabilities {\n return {\n supportsVision: m.modalities?.input?.includes(\"image\") ?? m.attachment ?? false,\n supportsStructuredOutput: m.structured_output ?? false,\n supportsToolUse: m.tool_call ?? false,\n supportsCacheControl: (m as { cache_control?: boolean }).cache_control ?? false,\n maxContextTokens: m.limit?.context ?? CONSERVATIVE_DEFAULTS.maxContextTokens,\n maxOutputTokens: m.limit?.output ?? CONSERVATIVE_DEFAULTS.maxOutputTokens,\n };\n}\n\n/**\n * Resolve per-model capability flags (vision/structured-output/tool-use/cache +\n * `maxContextTokens`/`maxOutputTokens`) for a model id. Pure, sync, offline (a\n * static catalog — no network). Strips routing prefixes (`openrouter/`/`vertex/`/\n * `bedrock/`) and OpenRouter `:variant` suffixes before lookup; unknown models get\n * conservative defaults. Public via `@theokit/sdk/models`.\n *\n * @public\n */\nexport function resolveModelCapabilities(modelId: string): ModelCapabilities {\n const bare = stripVariantSuffix(stripRoutingPrefix(modelId));\n // M44 — the catalog model-info index replaced the hand-curated EXACT map (single source of truth; the\n // vendored provider-catalog.json carries the migrated data — parity-tested against the old map snapshot).\n const fromIndex = getCatalogModelInfo(bare);\n if (fromIndex !== undefined) return capsFromCatalog(fromIndex);\n // Routing-prefixed models (vertex/claude-3-5-sonnet) strip to bare\n // model name without vendor. Try inferring the vendor from the name.\n const withVendor = inferVendorPrefix(bare);\n if (withVendor !== bare) {\n const vendored = getCatalogModelInfo(withVendor);\n if (vendored !== undefined) return capsFromCatalog(vendored);\n }\n return CONSERVATIVE_DEFAULTS;\n}\n\nfunction stripRoutingPrefix(modelId: string): string {\n for (const prefix of ROUTING_PREFIXES) {\n if (modelId.startsWith(prefix)) return modelId.slice(prefix.length);\n }\n return modelId;\n}\n\n/**\n * Strip an OpenRouter variant suffix (`:free`/`:nitro`/`:floor`/`:beta`/…) so the\n * catalog lookup hits the underlying model. Model slugs contain no `:` except the\n * variant separator, so cutting at the first `:` is safe.\n */\nfunction stripVariantSuffix(modelId: string): string {\n const i = modelId.indexOf(\":\");\n return i >= 0 ? modelId.slice(0, i) : modelId;\n}\n\n/** Infer vendor prefix from bare model name for routing-prefixed lookups. */\nfunction inferVendorPrefix(bare: string): string {\n if (bare.startsWith(\"claude\")) return `anthropic/${bare}`;\n if (bare.startsWith(\"gpt-\") || bare.startsWith(\"o1\") || bare.startsWith(\"o3\"))\n return `openai/${bare}`;\n if (bare.startsWith(\"gemini\")) return `google/${bare}`;\n return bare;\n}\n","import { parseModelId } from \"./model-identifier.js\";\n\n/**\n * A UI-friendly model option — the shape a `<select>`/dropdown consumes.\n *\n * Public via `@theokit/sdk/models`.\n *\n * @public\n */\nexport interface ModelOption {\n /** The original model id (what you pass back to the SDK). */\n value: string;\n /** Best-effort human label (see {@link humanizeModelName}). */\n label: string;\n /** Provider from the slug prefix, or `undefined` when none. */\n provider: string | undefined;\n}\n\n/** Tokens rendered upper-case rather than title-case. */\nconst ACRONYMS = new Set([\"gpt\", \"ai\", \"hd\", \"ui\", \"api\", \"sdk\", \"llm\", \"xl\"]);\n\nfunction prettyToken(token: string): string {\n if (ACRONYMS.has(token.toLowerCase())) return token.toUpperCase();\n return token.charAt(0).toUpperCase() + token.slice(1);\n}\n\n/**\n * Turn a model id into a best-effort human label: strip the routing/vendor\n * prefix to the core model segment, split on `-`/`_`/`.`/whitespace, title-case\n * each token (known acronyms upper-cased), and append an OpenRouter `:variant`\n * in parentheses. Deterministic, pure, dependency-free.\n *\n * Best-effort, NOT vendor-canonical: `\"anthropic/claude-3-5-sonnet\"` →\n * `\"Claude 3 5 Sonnet\"`. A UI wanting exact marketing names overrides per id.\n *\n * Public via `@theokit/sdk/models`.\n *\n * @public\n */\nexport function humanizeModelName(modelId: string): string {\n const { name } = parseModelId(modelId);\n if (name.length === 0) return \"\";\n const colon = name.indexOf(\":\");\n // Strip a trailing slash so a typo'd `gpt-4o/` keeps its name (not lost to an\n // empty last segment).\n //\n // Done by index rather than with `/\\/+$/`, and the difference is not stylistic: that pattern\n // consumes slashes to the end of the string at every start position and then backtracks\n // looking for an end-anchor that is not there (CodeQL js/polynomial-redos #6). This function\n // is `@public` and takes a caller-supplied model id. Measured on a run of slashes followed by\n // one other character: 25_000 took 496 ms, 100_000 took 31_305 ms — half a minute of pinned\n // CPU to render a label. Walking back from the end is linear and cannot backtrack.\n const base = trimTrailingSlashes(colon >= 0 ? name.slice(0, colon) : name);\n const variant = colon >= 0 ? name.slice(colon + 1) : \"\";\n const lastSlash = base.lastIndexOf(\"/\");\n const core = lastSlash >= 0 ? base.slice(lastSlash + 1) : base;\n const label = core\n .split(/[-_.\\s]+/)\n .filter((t) => t.length > 0)\n .map(prettyToken)\n .join(\" \");\n if (label.length === 0) return variant; // no base label (e.g. \":free\") → bare variant\n return variant.length > 0 ? `${label} (${variant})` : label;\n}\n\n/**\n * Build a {@link ModelOption} (`{ value, label, provider }`) for a model id —\n * a dropdown-ready entry composing {@link humanizeModelName} + `parseModelId`.\n *\n * Public via `@theokit/sdk/models`.\n *\n * @public\n */\nexport function toModelOption(modelId: string): ModelOption {\n return {\n value: modelId,\n label: humanizeModelName(modelId),\n provider: parseModelId(modelId).provider,\n };\n}\n\nconst SLASH_CODE = 47; // \"/\"\n\n/** Removes trailing `/` characters in one linear pass. See the call site for why not a regex. */\nfunction trimTrailingSlashes(value: string): string {\n let end = value.length;\n while (end > 0 && value.charCodeAt(end - 1) === SLASH_CODE) end--;\n return end === value.length ? value : value.slice(0, end);\n}\n","import { createHash, randomBytes } from \"node:crypto\";\nimport { mkdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nimport { Retry } from \"../../retry.js\";\nimport { diag } from \"../diagnostics.js\";\nimport { registerBuiltins } from \"./builtin/index.js\";\nimport { getCatalogModelInfo, loadProviderCatalog, patchModelInfo } from \"./catalog-loader.js\";\nimport { catalogModelSchema } from \"./catalog-schema.js\";\nimport { getProviderProfile } from \"./registry.js\";\n\n/**\n * M44 — the OPTIONAL models.dev catalog source. Explicit opt-in ONLY (`refreshModelCatalog()`): the SDK\n * NEVER fetches at startup or per-request — the vendored catalog + any existing disk cache are the offline\n * base, and every failure mode fails CLOSED back to them (ROADMAP constraint: no runtime hard network dep).\n *\n * The models.dev consumption mechanism:\n * disk cache with mtime TTL, atomic tempfile+rename write, corrupt-cache delete-and-fall-through, kill-switch\n * env. Library adaptations: NO background refresh loop (a consumer composes refresh with the SDK's cron);\n * TTL 1h (not 5min — no background refresher to keep it warm); no cross-process flock v1 (atomic rename +\n * idempotent upstream content — at most one wasted fetch).\n *\n * @internal (the public surface is `refreshModelCatalog` re-exported via `@theokit/sdk/models`)\n */\n\nconst DEFAULT_URL = \"https://models.dev/api.json\";\n\n/**\n * Ceiling on a fetched catalog, before it is parsed or written to the cache.\n *\n * The response body was read with `res.text()` and persisted with no bound, so a host serving a\n * multi-gigabyte document would have been materialised in memory and then written to disk. The\n * default URL is trusted, but `THEOKIT_MODELS_URL` lets an operator point this anywhere, and a\n * limit is the difference between \"we only fetch from a host we trust\" and \"we cannot be hurt by\n * one we do not\".\n *\n * 32 MiB is roughly 40x the real catalog (~800 KiB in 2026-08), so it bounds the failure without\n * being a number anyone has to tune when models.dev grows.\n */\nconst MAX_CATALOG_BYTES = 32 * 1024 * 1024;\nconst TTL_MS = 60 * 60 * 1000; // 1 hour\nconst FETCH_TIMEOUT_MS = 10_000;\n\n/**\n * Arguments to `refreshModelCatalog`, the SDK's only network trigger for model metadata.\n *\n * `url` wins over the `THEOKIT_MODELS_URL` environment variable, which in turn wins over\n * `https://models.dev/api.json`. A non-default URL gets its own cache file, named by a hash of\n * the URL, so switching sources never reads another source's cache.\n *\n * `force` skips only the freshness check — it does not skip the kill switch. When\n * `THEOKIT_DISABLE_MODELS_FETCH` is set to anything other than an empty string, `\"0\"` or\n * `\"false\"`, the call returns `source: \"skipped\"` with no fetch and no cache read, whatever\n * `force` says.\n *\n * Without `force`, a cache file whose mtime is under an hour old is served directly and no\n * request is made.\n *\n * `deps` exists so tests can drive the fetch and the clock; production leaves it unset.\n */\nexport interface RefreshModelCatalogOptions {\n /** Override the source URL (`THEOKIT_MODELS_URL` env also honored). */\n url?: string;\n /** Bypass the TTL freshness gate. */\n force?: boolean;\n /** Injected for tests. */\n deps?: { fetch?: typeof fetch; now?: () => number };\n}\n\n/**\n * What `refreshModelCatalog` did. It never throws on a failed refresh, so this is the only place\n * the outcome is reported.\n *\n * `source` is `\"network\"` only when a request succeeded, its body parsed as JSON, and the models\n * were patched in. Every failure path — kill switch aside — returns `\"cache\"`: an HTTP error\n * after retries, a timeout, an unparseable body, or a patch that threw. `\"cache\"` therefore means\n * \"serving what was already there\", which may be a fresh cache, a stale one, or nothing but the\n * vendored catalog. Read `models` to tell those apart. `\"skipped\"` means the kill switch was set.\n *\n * `models` counts the models patched into the index during this call, not the catalog's size. It\n * counts each model once even when the provider has aliases and the model is written under several\n * index keys, and it excludes models whose payload failed schema validation and models under\n * providers the SDK does not know. It is 0 whenever there was no cache to fall back on, and 0 for\n * `\"skipped\"`.\n *\n * A cache write that fails is logged and otherwise ignored: the result can still say `\"network\"`\n * with the data live in memory and nothing on disk.\n */\nexport interface RefreshModelCatalogResult {\n /** Where the data came from: a fresh network fetch, the still-fresh disk cache, or skipped entirely. */\n source: \"network\" | \"cache\" | \"skipped\";\n /** How many models were patched into the index. */\n models: number;\n}\n\n/** The cache file for a source URL (custom URLs get a hash-suffixed name). */\nexport function cachePathFor(url: string): string {\n // M44 L8 fix — honor the SDK home override so tests and multi-home setups never touch the real ~/.theokit.\n const base = process.env.THEOKIT_HOME?.trim() || join(homedir(), \".theokit\");\n const dir = join(base, \"cache\", \"models-dev\");\n if (url === DEFAULT_URL) return join(dir, \"api.json\");\n const hash = createHash(\"sha256\").update(url).digest(\"hex\").slice(0, 12);\n return join(dir, `api-${hash}.json`);\n}\n\n/** Atomic write: temp file + rename (crash mid-write never leaves a partial cache). */\nfunction writeCacheAtomic(path: string, body: string): void {\n mkdirSync(dirname(path), { recursive: true });\n const tmp = `${path}.tmp-${randomBytes(6).toString(\"hex\")}`;\n try {\n writeFileSync(tmp, body);\n renameSync(tmp, path);\n } catch (err) {\n try {\n unlinkSync(tmp);\n } catch {\n // best effort\n }\n throw err;\n }\n}\n\n/**\n * M44 H3 fix — models.dev provider ids ≠ theokit ids (google↔google-gemini, zai↔zhipu, togetherai↔together,\n * fireworks-ai↔fireworks, amazon-bedrock↔bedrock, google-vertex↔vertex). The RUNTIME mapping mirrors the\n * maintenance script's table; targets resolve against the CATALOG entries (id + aliases — the same namespace\n * the vendored index uses) first, then the registry.\n */\nconst MODELS_DEV_ID_MAP: Record<string, string> = {\n google: \"google-gemini\",\n zai: \"zhipu\",\n togetherai: \"together\",\n \"fireworks-ai\": \"fireworks\",\n \"amazon-bedrock\": \"bedrock\",\n \"google-vertex\": \"vertex\",\n};\n\nlet _catalogTargets: Map<string, { keys: string[] }> | undefined;\n/** external-id → the index keys (entry id + aliases) its models patch under. Lazy; catalog-first. */\nfunction catalogTargets(): Map<string, { keys: string[] }> {\n if (_catalogTargets !== undefined) return _catalogTargets;\n _catalogTargets = new Map();\n try {\n for (const entry of Object.values(loadProviderCatalog())) {\n const keys = [entry.id, ...(entry.aliases ?? [])];\n for (const k of keys) {\n if (!_catalogTargets.has(k)) _catalogTargets.set(k, { keys });\n }\n }\n } catch {\n // catalog unavailable — registry fallback below still works\n }\n return _catalogTargets;\n}\n\nfunction resolvePatchKeys(externalId: string): string[] | undefined {\n const mapped = MODELS_DEV_ID_MAP[externalId] ?? externalId;\n const fromCatalog = catalogTargets().get(mapped);\n if (fromCatalog !== undefined) return fromCatalog.keys;\n const profile = getProviderProfile(mapped);\n if (profile !== undefined) return [profile.name, ...(profile.aliases ?? [])];\n return undefined;\n}\n\n/** Parse + patch the index from an api.json payload. Unknown providers are skipped with WARN (once each). */\n// PRE-EXISTING debt, exposed when M75 fixed the Biome config that used to abort before\n// sweeping these files (a nested root under refactor/). It is not new code and was not touched\n// by M75; refactoring SDK internals without review would trade a visible problem for a diff\n// risky. Tracked in usetheodev/theokit-sdk#151.\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: validates and merges an UNTRUSTED upstream payload (models.dev api.json) shape by shape, dropping a single bad model rather than the file. Each branch is a distinct malformed input; merging them loses which one was seen.\nfunction patchIndexFromApiJson(raw: unknown): number {\n if (typeof raw !== \"object\" || raw === null) return 0;\n let patched = 0;\n const skipped: string[] = [];\n for (const [providerId, provider] of Object.entries(raw as Record<string, unknown>)) {\n const models = (provider as { models?: Record<string, unknown> })?.models;\n if (models === undefined || typeof models !== \"object\") continue;\n // Enrich ONLY providers the SDK knows — models.dev's npm/api fields cannot be mapped to a theokit\n // apiMode/authType safely, so unknown providers are data we cannot route.\n const keys = resolvePatchKeys(providerId);\n if (keys === undefined) {\n skipped.push(providerId);\n continue;\n }\n for (const [modelId, rawModel] of Object.entries(models)) {\n const parsed = catalogModelSchema.safeParse(rawModel);\n if (!parsed.success) continue; // malformed model — drop silently (live data, additive drift expected)\n for (const key of keys) patchModelInfo(`${key}/${modelId}`, parsed.data);\n patched++;\n }\n }\n if (skipped.length > 0) {\n diag(\n `[theokit-sdk] WARN: models-dev refresh skipped ${skipped.length} unknown provider(s) (e.g. ${skipped.slice(0, 3).join(\", \")})\\n`,\n );\n }\n return patched;\n}\n\n/**\n * Load an existing disk cache into the index (called by refresh when fresh, or opportunistically by a\n * consumer at startup — NEVER fetches). Corrupt cache → delete + fall through to vendored data.\n */\nexport function loadCacheIntoIndex(url: string = DEFAULT_URL): number {\n const path = cachePathFor(url);\n let body: string;\n try {\n body = readFileSync(path, \"utf-8\");\n } catch {\n return 0; // no cache — vendored data only\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(body);\n } catch {\n // corrupt cache: delete and fall through to the vendored catalog.\n // M44 L9 fix — only a PARSE failure is cache corruption; a patch error must never delete a valid cache.\n try {\n unlinkSync(path);\n } catch {\n // best effort\n }\n diag(`[theokit-sdk] WARN: corrupt models-dev cache deleted (${path})\\n`);\n return 0;\n }\n try {\n return patchIndexFromApiJson(parsed);\n } catch (err) {\n diag(`[theokit-sdk] WARN: models-dev cache patch failed (${(err as Error).message})\\n`);\n return 0;\n }\n}\n\n/**\n * The kill switch, read from the environment.\n *\n * Truthy-only by design (M44 L11): a presence check would treat `THEOKIT_DISABLE_MODELS_FETCH=0`\n * and `=false` as \"disabled\", which is the opposite of what anyone writing them means.\n */\nfunction fetchDisabledByEnv(): boolean {\n const kill = process.env.THEOKIT_DISABLE_MODELS_FETCH;\n return kill !== undefined && kill !== \"\" && kill !== \"0\" && kill.toLowerCase() !== \"false\";\n}\n\n/**\n * The TTL gate: a cache file younger than {@link TTL_MS} serves without touching the network.\n *\n * Returns `undefined` when there is no usable cache — including when `statSync` throws, which is\n * how \"no cache file\" arrives. That is the ONE failure this step owns, and its fallback is simply\n * to let the caller proceed to the fetch.\n */\nfunction servedFromFreshCache(\n url: string,\n path: string,\n now: () => number,\n): RefreshModelCatalogResult | undefined {\n try {\n if (now() - statSync(path).mtimeMs >= TTL_MS) return undefined;\n } catch {\n return undefined; // no cache — proceed to fetch\n }\n return { source: \"cache\", models: loadCacheIntoIndex(url) };\n}\n\n/**\n * Fetch the catalog, bound its size, and prove it parses before anyone persists it.\n *\n * Returns `undefined` after logging when ANY of that fails — timeout, non-2xx, oversize, unparseable\n * body. The fallback this step owns is \"serve what we already have\", and the caller applies it.\n * Splitting the step from its fallback was the objection recorded in the suppression this replaces;\n * the fallback is not separated, it is named — `undefined` means \"this step could not produce a\n * body\", and there is exactly one thing to do about that.\n */\nasync function fetchCatalogBody(url: string, fetchImpl: typeof fetch): Promise<string | undefined> {\n try {\n const res = await Retry.run(\n async () => {\n const r = await fetchImpl(url, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });\n if (!r.ok) throw new Error(`HTTP ${r.status}`);\n return r;\n },\n // 2 transient retries with backoff; every error here is worth one more try —\n // the whole call is already fail-closed at the caller.\n { retries: 2, isRetryable: () => true, initialDelayMs: 200 },\n );\n const declaredLength = Number(res.headers.get(\"content-length\") ?? Number.NaN);\n if (Number.isFinite(declaredLength) && declaredLength > MAX_CATALOG_BYTES) {\n throw new Error(`catalog too large: ${declaredLength} bytes declared`);\n }\n const body = await res.text();\n // Checked again after reading: `content-length` is the server's claim, and a server that\n // omits it or lies about it is exactly the one worth bounding. Both checks are cheap and\n // neither alone is sufficient.\n if (body.length > MAX_CATALOG_BYTES) {\n throw new Error(`catalog too large: ${body.length} bytes received`);\n }\n JSON.parse(body); // validate before persisting — never cache garbage\n return body;\n } catch (err) {\n diag(\n `[theokit-sdk] WARN: models-dev refresh failed (${(err as Error).message}) — serving existing data\\n`,\n );\n return undefined;\n }\n}\n\n/**\n * Persist the fetched body and patch it into the index.\n *\n * Two independent failures with two different consequences, which is why they are two try blocks\n * and not one: a cache write that fails costs the NEXT process a fetch and nothing more, so the run\n * continues; a patch that fails means this body never reached the index, so the index is whatever it\n * was and the result says `cache`.\n */\nfunction persistAndPatch(path: string, body: string): RefreshModelCatalogResult {\n try {\n writeCacheAtomic(path, body);\n } catch (err) {\n diag(`[theokit-sdk] WARN: models-dev cache write failed (${(err as Error).message})\\n`);\n }\n try {\n return { source: \"network\", models: patchIndexFromApiJson(JSON.parse(body)) };\n } catch (err) {\n diag(\n `[theokit-sdk] WARN: models-dev patch failed (${(err as Error).message}) — serving existing data\\n`,\n );\n return { source: \"cache\", models: 0 };\n }\n}\n\n/**\n * Explicitly refresh the model catalog from models.dev (the ONLY network trigger in the subsystem).\n * Fail-closed: any failure keeps serving the current index (cache or vendored). Kill-switch:\n * `THEOKIT_DISABLE_MODELS_FETCH`.\n *\n * The sequence carried a cognitive-complexity suppression whose reason said splitting it would\n * \"separate a step from the fallback it owns\". The four helpers above each KEEP their fallback: the\n * TTL gate owns \"no cache\", the fetch owns every network and validation failure, the persist owns\n * the write and the patch. What is left here is the order they run in, which is what this function\n * was always for.\n *\n * Still true, and NOT fixed by the split: three of the paths return `{ source: \"cache\" }`, so a\n * caller cannot tell a timeout from an unparseable body from a patch failure. Distinguishing them\n * means adding a field to the PUBLIC `RefreshModelCatalogResult`, which is a release decision rather\n * than a refactor. The `diag` line already names the cause for an operator.\n */\nexport async function refreshModelCatalog(\n opts: RefreshModelCatalogOptions = {},\n): Promise<RefreshModelCatalogResult> {\n // M44 M4 fix — self-initialize provider registration so the `@theokit/sdk/models` subpath works\n // standalone (without the consumer having built an Agent first).\n registerBuiltins();\n if (fetchDisabledByEnv()) return { source: \"skipped\", models: 0 };\n\n const url = opts.url ?? process.env.THEOKIT_MODELS_URL ?? DEFAULT_URL;\n const path = cachePathFor(url);\n const now = opts.deps?.now ?? (() => Date.now());\n\n if (opts.force !== true) {\n const cached = servedFromFreshCache(url, path, now);\n if (cached !== undefined) return cached;\n }\n\n const body = await fetchCatalogBody(url, opts.deps?.fetch ?? fetch);\n // fail-closed: serve whatever we already have (stale cache if present, else vendored)\n if (body === undefined) return { source: \"cache\", models: loadCacheIntoIndex(url) };\n\n return persistAndPatch(path, body);\n}\n\n/** The enriched per-model view (public via `@theokit/sdk/models`): index lookup by (possibly prefixed) id. */\nexport function getModelInfo(modelId: string): ReturnType<typeof getCatalogModelInfo> {\n return getCatalogModelInfo(modelId);\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/internal/llm/model-capabilities.ts","../src/internal/llm/model-option.ts","../src/internal/providers/catalog-source-models-dev.ts"],"names":["getCatalogModelInfo","parseModelId","join","homedir","createHash","path","mkdirSync","dirname","randomBytes","writeFileSync","renameSync","unlinkSync","loadProviderCatalog","getProviderProfile","catalogModelSchema","patchModelInfo","diag","readFileSync","statSync","Retry","registerBuiltins","boundFetch"],"mappings":";;;;;;;;;;;;;;;;;;AAgCA,IAAM,qBAAA,GAA2C;AAAA,EAC/C,cAAA,EAAgB,KAAA;AAAA,EAChB,wBAAA,EAA0B,KAAA;AAAA,EAC1B,eAAA,EAAiB,KAAA;AAAA,EACjB,oBAAA,EAAsB,KAAA;AAAA,EACtB,gBAAA,EAAkB,IAAA;AAAA,EAClB,eAAA,EAAiB;AACnB,CAAA;AAGA,IAAM,gBAAA,GAAmB,CAAC,aAAA,EAAe,SAAA,EAAW,UAAU,CAAA;AAM9D,SAAS,gBAAgB,CAAA,EAAoC;AAC3D,EAAA,OAAO;AAAA,IACL,cAAA,EAAgB,EAAE,UAAA,EAAY,KAAA,EAAO,SAAS,OAAO,CAAA,IAAK,EAAE,UAAA,IAAc,KAAA;AAAA,IAC1E,wBAAA,EAA0B,EAAE,iBAAA,IAAqB,KAAA;AAAA,IACjD,eAAA,EAAiB,EAAE,SAAA,IAAa,KAAA;AAAA,IAChC,oBAAA,EAAuB,EAAkC,aAAA,IAAiB,KAAA;AAAA,IAC1E,gBAAA,EAAkB,CAAA,CAAE,KAAA,EAAO,OAAA,IAAW,qBAAA,CAAsB,gBAAA;AAAA,IAC5D,eAAA,EAAiB,CAAA,CAAE,KAAA,EAAO,MAAA,IAAU,qBAAA,CAAsB;AAAA,GAC5D;AACF;AAWO,SAAS,yBAAyB,OAAA,EAAoC;AAC3E,EAAA,MAAM,IAAA,GAAO,kBAAA,CAAmB,kBAAA,CAAmB,OAAO,CAAC,CAAA;AAG3D,EAAA,MAAM,SAAA,GAAYA,s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EAAiD,IAAc,OAAO,CAAA;AAAA;AAAA,KACxE;AACA,IAAA,OAAO,EAAE,MAAA,EAAQ,OAAA,EAAS,MAAA,EAAQ,CAAA,EAAE;AAAA,EACtC;AACF;AAkBA,eAAsB,mBAAA,CACpB,IAAA,GAAmC,EAAC,EACA;AAGpC,EAAAI,kCAAA,EAAiB;AACjB,EAAA,IAAI,oBAAmB,EAAG,OAAO,EAAE,MAAA,EAAQ,SAAA,EAAW,QAAQ,CAAA,EAAE;AAEhE,EAAA,MAAM,GAAA,GAAM,IAAA,CAAK,GAAA,IAAO,OAAA,CAAQ,IAAI,kBAAA,IAAsB,WAAA;AAC1D,EAAA,MAAM,IAAA,GAAO,aAAa,GAAG,CAAA;AAC7B,EAAA,MAAM,MAAM,IAAA,CAAK,IAAA,EAAM,GAAA,KAAQ,MAAM,KAAK,GAAA,EAAI,CAAA;AAE9C,EAAA,IAAI,IAAA,CAAK,UAAU,IAAA,EAAM;AACvB,IAAA,MAAM,MAAA,GAAS,oBAAA,CAAqB,GAAA,EAAK,IAAA,EAAM,GAAG,CAAA;AAClD,IAAA,IAAI,MAAA,KAAW,QAAW,OAAO,MAAA;AAAA,EACnC;AAEA,EAAA,MAAM,IAAA,GAAO,MAAM,gBAAA,CAAiB,GAAA,EAAKC,6BAAW,IAAA,CAAK,IAAA,EAAM,KAAK,CAAC,CAAA;AAErE,EAAA,IAAI,IAAA,KAAS,QAAW,OAAO,EAAE,QAAQ,OAAA,EAAS,MAAA,EAAQ,kBAAA,CAAmB,GAAG,CAAA,EAAE;AAElF,EAAA,OAAO,eAAA,CAAgB,MAAM,IAAI,CAAA;AACnC;AAGO,SAAS,aAAa,OAAA,EAAyD;AACpF,EAAA,OAAOrB,sCAAoB,OAAO,CAAA;AACpC","file":"models.cjs","sourcesContent":["/**\n * T3.10c — Model capability registry (DR3 #17).\n *\n * Typed per-model flags that let the SDK gate features at the boundary\n * (before hitting the provider) instead of letting opaque 400s surface.\n *\n * Resolution algorithm:\n * 1. Strip routing prefixes (openrouter/, vertex/, bedrock/) AND the\n * OpenRouter `:variant` suffix (:free/:nitro/…) to find the bare vendor id.\n * 2. Exact match in the `EXACT` catalog → return entry.\n * 3. Vendor inference (e.g., `claude-*` → `anthropic/claude-*`) → return entry.\n * 4. No match → conservative defaults (all false, minimum tokens).\n *\n * Module is internal, but `ModelCapabilities` + `resolveModelCapabilities` are\n * re-exported publicly via the `@theokit/sdk/models` subpath (see their @public tags).\n */\n\n/**\n * Per-model capability shape. Consumers use this to gate features at\n * the SDK boundary (before request construction, not after 400).\n *\n * @public\n */\nexport interface ModelCapabilities {\n supportsVision: boolean;\n supportsStructuredOutput: boolean;\n supportsToolUse: boolean;\n supportsCacheControl: boolean;\n maxContextTokens: number;\n maxOutputTokens: number;\n}\n\nconst CONSERVATIVE_DEFAULTS: ModelCapabilities = {\n supportsVision: false,\n supportsStructuredOutput: false,\n supportsToolUse: false,\n supportsCacheControl: false,\n maxContextTokens: 4096,\n maxOutputTokens: 4096,\n};\n\n/** Routing prefixes to strip to find the underlying vendor model. */\nconst ROUTING_PREFIXES = [\"openrouter/\", \"vertex/\", \"bedrock/\"] as const;\n\nimport { getCatalogModelInfo } from \"../providers/catalog-loader.js\";\nimport type { CatalogModel } from \"../providers/catalog-schema.js\";\n\n/** Map a catalog model block (models.dev shape) to the SDK's ModelCapabilities (M44 — catalog-backed). */\nfunction capsFromCatalog(m: CatalogModel): ModelCapabilities {\n return {\n supportsVision: m.modalities?.input?.includes(\"image\") ?? m.attachment ?? false,\n supportsStructuredOutput: m.structured_output ?? false,\n supportsToolUse: m.tool_call ?? false,\n supportsCacheControl: (m as { cache_control?: boolean }).cache_control ?? false,\n maxContextTokens: m.limit?.context ?? CONSERVATIVE_DEFAULTS.maxContextTokens,\n maxOutputTokens: m.limit?.output ?? CONSERVATIVE_DEFAULTS.maxOutputTokens,\n };\n}\n\n/**\n * Resolve per-model capability flags (vision/structured-output/tool-use/cache +\n * `maxContextTokens`/`maxOutputTokens`) for a model id. Pure, sync, offline (a\n * static catalog — no network). Strips routing prefixes (`openrouter/`/`vertex/`/\n * `bedrock/`) and OpenRouter `:variant` suffixes before lookup; unknown models get\n * conservative defaults. Public via `@theokit/sdk/models`.\n *\n * @public\n */\nexport function resolveModelCapabilities(modelId: string): ModelCapabilities {\n const bare = stripVariantSuffix(stripRoutingPrefix(modelId));\n // M44 — the catalog model-info index replaced the hand-curated EXACT map (single source of truth; the\n // vendored provider-catalog.json carries the migrated data — parity-tested against the old map snapshot).\n const fromIndex = getCatalogModelInfo(bare);\n if (fromIndex !== undefined) return capsFromCatalog(fromIndex);\n // Routing-prefixed models (vertex/claude-3-5-sonnet) strip to bare\n // model name without vendor. Try inferring the vendor from the name.\n const withVendor = inferVendorPrefix(bare);\n if (withVendor !== bare) {\n const vendored = getCatalogModelInfo(withVendor);\n if (vendored !== undefined) return capsFromCatalog(vendored);\n }\n return CONSERVATIVE_DEFAULTS;\n}\n\nfunction stripRoutingPrefix(modelId: string): string {\n for (const prefix of ROUTING_PREFIXES) {\n if (modelId.startsWith(prefix)) return modelId.slice(prefix.length);\n }\n return modelId;\n}\n\n/**\n * Strip an OpenRouter variant suffix (`:free`/`:nitro`/`:floor`/`:beta`/…) so the\n * catalog lookup hits the underlying model. Model slugs contain no `:` except the\n * variant separator, so cutting at the first `:` is safe.\n */\nfunction stripVariantSuffix(modelId: string): string {\n const i = modelId.indexOf(\":\");\n return i >= 0 ? modelId.slice(0, i) : modelId;\n}\n\n/** Infer vendor prefix from bare model name for routing-prefixed lookups. */\nfunction inferVendorPrefix(bare: string): string {\n if (bare.startsWith(\"claude\")) return `anthropic/${bare}`;\n if (bare.startsWith(\"gpt-\") || bare.startsWith(\"o1\") || bare.startsWith(\"o3\"))\n return `openai/${bare}`;\n if (bare.startsWith(\"gemini\")) return `google/${bare}`;\n return bare;\n}\n","import { parseModelId } from \"./model-identifier.js\";\n\n/**\n * A UI-friendly model option — the shape a `<select>`/dropdown consumes.\n *\n * Public via `@theokit/sdk/models`.\n *\n * @public\n */\nexport interface ModelOption {\n /** The original model id (what you pass back to the SDK). */\n value: string;\n /** Best-effort human label (see {@link humanizeModelName}). */\n label: string;\n /** Provider from the slug prefix, or `undefined` when none. */\n provider: string | undefined;\n}\n\n/** Tokens rendered upper-case rather than title-case. */\nconst ACRONYMS = new Set([\"gpt\", \"ai\", \"hd\", \"ui\", \"api\", \"sdk\", \"llm\", \"xl\"]);\n\nfunction prettyToken(token: string): string {\n if (ACRONYMS.has(token.toLowerCase())) return token.toUpperCase();\n return token.charAt(0).toUpperCase() + token.slice(1);\n}\n\n/**\n * Turn a model id into a best-effort human label: strip the routing/vendor\n * prefix to the core model segment, split on `-`/`_`/`.`/whitespace, title-case\n * each token (known acronyms upper-cased), and append an OpenRouter `:variant`\n * in parentheses. Deterministic, pure, dependency-free.\n *\n * Best-effort, NOT vendor-canonical: `\"anthropic/claude-3-5-sonnet\"` →\n * `\"Claude 3 5 Sonnet\"`. A UI wanting exact marketing names overrides per id.\n *\n * Public via `@theokit/sdk/models`.\n *\n * @public\n */\nexport function humanizeModelName(modelId: string): string {\n const { name } = parseModelId(modelId);\n if (name.length === 0) return \"\";\n const colon = name.indexOf(\":\");\n // Strip a trailing slash so a typo'd `gpt-4o/` keeps its name (not lost to an\n // empty last segment).\n //\n // Done by index rather than with `/\\/+$/`, and the difference is not stylistic: that pattern\n // consumes slashes to the end of the string at every start position and then backtracks\n // looking for an end-anchor that is not there (CodeQL js/polynomial-redos #6). This function\n // is `@public` and takes a caller-supplied model id. Measured on a run of slashes followed by\n // one other character: 25_000 took 496 ms, 100_000 took 31_305 ms — half a minute of pinned\n // CPU to render a label. Walking back from the end is linear and cannot backtrack.\n const base = trimTrailingSlashes(colon >= 0 ? name.slice(0, colon) : name);\n const variant = colon >= 0 ? name.slice(colon + 1) : \"\";\n const lastSlash = base.lastIndexOf(\"/\");\n const core = lastSlash >= 0 ? base.slice(lastSlash + 1) : base;\n const label = core\n .split(/[-_.\\s]+/)\n .filter((t) => t.length > 0)\n .map(prettyToken)\n .join(\" \");\n if (label.length === 0) return variant; // no base label (e.g. \":free\") → bare variant\n return variant.length > 0 ? `${label} (${variant})` : label;\n}\n\n/**\n * Build a {@link ModelOption} (`{ value, label, provider }`) for a model id —\n * a dropdown-ready entry composing {@link humanizeModelName} + `parseModelId`.\n *\n * Public via `@theokit/sdk/models`.\n *\n * @public\n */\nexport function toModelOption(modelId: string): ModelOption {\n return {\n value: modelId,\n label: humanizeModelName(modelId),\n provider: parseModelId(modelId).provider,\n };\n}\n\nconst SLASH_CODE = 47; // \"/\"\n\n/** Removes trailing `/` characters in one linear pass. See the call site for why not a regex. */\nfunction trimTrailingSlashes(value: string): string {\n let end = value.length;\n while (end > 0 && value.charCodeAt(end - 1) === SLASH_CODE) end--;\n return end === value.length ? value : value.slice(0, end);\n}\n","import { createHash, randomBytes } from \"node:crypto\";\nimport { mkdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nimport { Retry } from \"../../retry.js\";\nimport { diag } from \"../diagnostics.js\";\nimport { boundFetch } from \"../runtime-fetch.js\";\nimport { registerBuiltins } from \"./builtin/index.js\";\nimport { getCatalogModelInfo, loadProviderCatalog, patchModelInfo } from \"./catalog-loader.js\";\nimport { catalogModelSchema } from \"./catalog-schema.js\";\nimport { getProviderProfile } from \"./registry.js\";\n\n/**\n * M44 — the OPTIONAL models.dev catalog source. Explicit opt-in ONLY (`refreshModelCatalog()`): the SDK\n * NEVER fetches at startup or per-request — the vendored catalog + any existing disk cache are the offline\n * base, and every failure mode fails CLOSED back to them (ROADMAP constraint: no runtime hard network dep).\n *\n * The models.dev consumption mechanism:\n * disk cache with mtime TTL, atomic tempfile+rename write, corrupt-cache delete-and-fall-through, kill-switch\n * env. Library adaptations: NO background refresh loop (a consumer composes refresh with the SDK's cron);\n * TTL 1h (not 5min — no background refresher to keep it warm); no cross-process flock v1 (atomic rename +\n * idempotent upstream content — at most one wasted fetch).\n *\n * @internal (the public surface is `refreshModelCatalog` re-exported via `@theokit/sdk/models`)\n */\n\nconst DEFAULT_URL = \"https://models.dev/api.json\";\n\n/**\n * Ceiling on a fetched catalog, before it is parsed or written to the cache.\n *\n * The response body was read with `res.text()` and persisted with no bound, so a host serving a\n * multi-gigabyte document would have been materialised in memory and then written to disk. The\n * default URL is trusted, but `THEOKIT_MODELS_URL` lets an operator point this anywhere, and a\n * limit is the difference between \"we only fetch from a host we trust\" and \"we cannot be hurt by\n * one we do not\".\n *\n * 32 MiB is roughly 40x the real catalog (~800 KiB in 2026-08), so it bounds the failure without\n * being a number anyone has to tune when models.dev grows.\n */\nconst MAX_CATALOG_BYTES = 32 * 1024 * 1024;\nconst TTL_MS = 60 * 60 * 1000; // 1 hour\nconst FETCH_TIMEOUT_MS = 10_000;\n\n/**\n * Arguments to `refreshModelCatalog`, the SDK's only network trigger for model metadata.\n *\n * `url` wins over the `THEOKIT_MODELS_URL` environment variable, which in turn wins over\n * `https://models.dev/api.json`. A non-default URL gets its own cache file, named by a hash of\n * the URL, so switching sources never reads another source's cache.\n *\n * `force` skips only the freshness check — it does not skip the kill switch. When\n * `THEOKIT_DISABLE_MODELS_FETCH` is set to anything other than an empty string, `\"0\"` or\n * `\"false\"`, the call returns `source: \"skipped\"` with no fetch and no cache read, whatever\n * `force` says.\n *\n * Without `force`, a cache file whose mtime is under an hour old is served directly and no\n * request is made.\n *\n * `deps` exists so tests can drive the fetch and the clock; production leaves it unset.\n */\nexport interface RefreshModelCatalogOptions {\n /** Override the source URL (`THEOKIT_MODELS_URL` env also honored). */\n url?: string;\n /** Bypass the TTL freshness gate. */\n force?: boolean;\n /** Injected for tests. */\n deps?: { fetch?: typeof fetch; now?: () => number };\n}\n\n/**\n * What `refreshModelCatalog` did. It never throws on a failed refresh, so this is the only place\n * the outcome is reported.\n *\n * `source` is `\"network\"` only when a request succeeded, its body parsed as JSON, and the models\n * were patched in. Every failure path — kill switch aside — returns `\"cache\"`: an HTTP error\n * after retries, a timeout, an unparseable body, or a patch that threw. `\"cache\"` therefore means\n * \"serving what was already there\", which may be a fresh cache, a stale one, or nothing but the\n * vendored catalog. Read `models` to tell those apart. `\"skipped\"` means the kill switch was set.\n *\n * `models` counts the models patched into the index during this call, not the catalog's size. It\n * counts each model once even when the provider has aliases and the model is written under several\n * index keys, and it excludes models whose payload failed schema validation and models under\n * providers the SDK does not know. It is 0 whenever there was no cache to fall back on, and 0 for\n * `\"skipped\"`.\n *\n * A cache write that fails is logged and otherwise ignored: the result can still say `\"network\"`\n * with the data live in memory and nothing on disk.\n */\nexport interface RefreshModelCatalogResult {\n /** Where the data came from: a fresh network fetch, the still-fresh disk cache, or skipped entirely. */\n source: \"network\" | \"cache\" | \"skipped\";\n /** How many models were patched into the index. */\n models: number;\n}\n\n/** The cache file for a source URL (custom URLs get a hash-suffixed name). */\nexport function cachePathFor(url: string): string {\n // M44 L8 fix — honor the SDK home override so tests and multi-home setups never touch the real ~/.theokit.\n const base = process.env.THEOKIT_HOME?.trim() || join(homedir(), \".theokit\");\n const dir = join(base, \"cache\", \"models-dev\");\n if (url === DEFAULT_URL) return join(dir, \"api.json\");\n const hash = createHash(\"sha256\").update(url).digest(\"hex\").slice(0, 12);\n return join(dir, `api-${hash}.json`);\n}\n\n/** Atomic write: temp file + rename (crash mid-write never leaves a partial cache). */\nfunction writeCacheAtomic(path: string, body: string): void {\n mkdirSync(dirname(path), { recursive: true });\n const tmp = `${path}.tmp-${randomBytes(6).toString(\"hex\")}`;\n try {\n writeFileSync(tmp, body);\n renameSync(tmp, path);\n } catch (err) {\n try {\n unlinkSync(tmp);\n } catch {\n // best effort\n }\n throw err;\n }\n}\n\n/**\n * M44 H3 fix — models.dev provider ids ≠ theokit ids (google↔google-gemini, zai↔zhipu, togetherai↔together,\n * fireworks-ai↔fireworks, amazon-bedrock↔bedrock, google-vertex↔vertex). The RUNTIME mapping mirrors the\n * maintenance script's table; targets resolve against the CATALOG entries (id + aliases — the same namespace\n * the vendored index uses) first, then the registry.\n */\nconst MODELS_DEV_ID_MAP: Record<string, string> = {\n google: \"google-gemini\",\n zai: \"zhipu\",\n togetherai: \"together\",\n \"fireworks-ai\": \"fireworks\",\n \"amazon-bedrock\": \"bedrock\",\n \"google-vertex\": \"vertex\",\n};\n\nlet _catalogTargets: Map<string, { keys: string[] }> | undefined;\n/** external-id → the index keys (entry id + aliases) its models patch under. Lazy; catalog-first. */\nfunction catalogTargets(): Map<string, { keys: string[] }> {\n if (_catalogTargets !== undefined) return _catalogTargets;\n _catalogTargets = new Map();\n try {\n for (const entry of Object.values(loadProviderCatalog())) {\n const keys = [entry.id, ...(entry.aliases ?? [])];\n for (const k of keys) {\n if (!_catalogTargets.has(k)) _catalogTargets.set(k, { keys });\n }\n }\n } catch {\n // catalog unavailable — registry fallback below still works\n }\n return _catalogTargets;\n}\n\nfunction resolvePatchKeys(externalId: string): string[] | undefined {\n const mapped = MODELS_DEV_ID_MAP[externalId] ?? externalId;\n const fromCatalog = catalogTargets().get(mapped);\n if (fromCatalog !== undefined) return fromCatalog.keys;\n const profile = getProviderProfile(mapped);\n if (profile !== undefined) return [profile.name, ...(profile.aliases ?? [])];\n return undefined;\n}\n\n/** Parse + patch the index from an api.json payload. Unknown providers are skipped with WARN (once each). */\n// PRE-EXISTING debt, exposed when M75 fixed the Biome config that used to abort before\n// sweeping these files (a nested root under refactor/). It is not new code and was not touched\n// by M75; refactoring SDK internals without review would trade a visible problem for a diff\n// risky. Tracked in usetheodev/theokit-sdk#151.\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: validates and merges an UNTRUSTED upstream payload (models.dev api.json) shape by shape, dropping a single bad model rather than the file. Each branch is a distinct malformed input; merging them loses which one was seen.\nfunction patchIndexFromApiJson(raw: unknown): number {\n if (typeof raw !== \"object\" || raw === null) return 0;\n let patched = 0;\n const skipped: string[] = [];\n for (const [providerId, provider] of Object.entries(raw as Record<string, unknown>)) {\n const models = (provider as { models?: Record<string, unknown> })?.models;\n if (models === undefined || typeof models !== \"object\") continue;\n // Enrich ONLY providers the SDK knows — models.dev's npm/api fields cannot be mapped to a theokit\n // apiMode/authType safely, so unknown providers are data we cannot route.\n const keys = resolvePatchKeys(providerId);\n if (keys === undefined) {\n skipped.push(providerId);\n continue;\n }\n for (const [modelId, rawModel] of Object.entries(models)) {\n const parsed = catalogModelSchema.safeParse(rawModel);\n if (!parsed.success) continue; // malformed model — drop silently (live data, additive drift expected)\n for (const key of keys) patchModelInfo(`${key}/${modelId}`, parsed.data);\n patched++;\n }\n }\n if (skipped.length > 0) {\n diag(\n `[theokit-sdk] WARN: models-dev refresh skipped ${skipped.length} unknown provider(s) (e.g. ${skipped.slice(0, 3).join(\", \")})\\n`,\n );\n }\n return patched;\n}\n\n/**\n * Load an existing disk cache into the index (called by refresh when fresh, or opportunistically by a\n * consumer at startup — NEVER fetches). Corrupt cache → delete + fall through to vendored data.\n */\nexport function loadCacheIntoIndex(url: string = DEFAULT_URL): number {\n const path = cachePathFor(url);\n let body: string;\n try {\n body = readFileSync(path, \"utf-8\");\n } catch {\n return 0; // no cache — vendored data only\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(body);\n } catch {\n // corrupt cache: delete and fall through to the vendored catalog.\n // M44 L9 fix — only a PARSE failure is cache corruption; a patch error must never delete a valid cache.\n try {\n unlinkSync(path);\n } catch {\n // best effort\n }\n diag(`[theokit-sdk] WARN: corrupt models-dev cache deleted (${path})\\n`);\n return 0;\n }\n try {\n return patchIndexFromApiJson(parsed);\n } catch (err) {\n diag(`[theokit-sdk] WARN: models-dev cache patch failed (${(err as Error).message})\\n`);\n return 0;\n }\n}\n\n/**\n * The kill switch, read from the environment.\n *\n * Truthy-only by design (M44 L11): a presence check would treat `THEOKIT_DISABLE_MODELS_FETCH=0`\n * and `=false` as \"disabled\", which is the opposite of what anyone writing them means.\n */\nfunction fetchDisabledByEnv(): boolean {\n const kill = process.env.THEOKIT_DISABLE_MODELS_FETCH;\n return kill !== undefined && kill !== \"\" && kill !== \"0\" && kill.toLowerCase() !== \"false\";\n}\n\n/**\n * The TTL gate: a cache file younger than {@link TTL_MS} serves without touching the network.\n *\n * Returns `undefined` when there is no usable cache — including when `statSync` throws, which is\n * how \"no cache file\" arrives. That is the ONE failure this step owns, and its fallback is simply\n * to let the caller proceed to the fetch.\n */\nfunction servedFromFreshCache(\n url: string,\n path: string,\n now: () => number,\n): RefreshModelCatalogResult | undefined {\n try {\n if (now() - statSync(path).mtimeMs >= TTL_MS) return undefined;\n } catch {\n return undefined; // no cache — proceed to fetch\n }\n return { source: \"cache\", models: loadCacheIntoIndex(url) };\n}\n\n/**\n * Fetch the catalog, bound its size, and prove it parses before anyone persists it.\n *\n * Returns `undefined` after logging when ANY of that fails — timeout, non-2xx, oversize, unparseable\n * body. The fallback this step owns is \"serve what we already have\", and the caller applies it.\n * Splitting the step from its fallback was the objection recorded in the suppression this replaces;\n * the fallback is not separated, it is named — `undefined` means \"this step could not produce a\n * body\", and there is exactly one thing to do about that.\n */\nasync function fetchCatalogBody(url: string, fetchImpl: typeof fetch): Promise<string | undefined> {\n try {\n const res = await Retry.run(\n async () => {\n const r = await fetchImpl(url, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });\n if (!r.ok) throw new Error(`HTTP ${r.status}`);\n return r;\n },\n // 2 transient retries with backoff; every error here is worth one more try —\n // the whole call is already fail-closed at the caller.\n { retries: 2, isRetryable: () => true, initialDelayMs: 200 },\n );\n const declaredLength = Number(res.headers.get(\"content-length\") ?? Number.NaN);\n if (Number.isFinite(declaredLength) && declaredLength > MAX_CATALOG_BYTES) {\n throw new Error(`catalog too large: ${declaredLength} bytes declared`);\n }\n const body = await res.text();\n // Checked again after reading: `content-length` is the server's claim, and a server that\n // omits it or lies about it is exactly the one worth bounding. Both checks are cheap and\n // neither alone is sufficient.\n if (body.length > MAX_CATALOG_BYTES) {\n throw new Error(`catalog too large: ${body.length} bytes received`);\n }\n JSON.parse(body); // validate before persisting — never cache garbage\n return body;\n } catch (err) {\n diag(\n `[theokit-sdk] WARN: models-dev refresh failed (${(err as Error).message}) — serving existing data\\n`,\n );\n return undefined;\n }\n}\n\n/**\n * Persist the fetched body and patch it into the index.\n *\n * Two independent failures with two different consequences, which is why they are two try blocks\n * and not one: a cache write that fails costs the NEXT process a fetch and nothing more, so the run\n * continues; a patch that fails means this body never reached the index, so the index is whatever it\n * was and the result says `cache`.\n */\nfunction persistAndPatch(path: string, body: string): RefreshModelCatalogResult {\n try {\n writeCacheAtomic(path, body);\n } catch (err) {\n diag(`[theokit-sdk] WARN: models-dev cache write failed (${(err as Error).message})\\n`);\n }\n try {\n return { source: \"network\", models: patchIndexFromApiJson(JSON.parse(body)) };\n } catch (err) {\n diag(\n `[theokit-sdk] WARN: models-dev patch failed (${(err as Error).message}) — serving existing data\\n`,\n );\n return { source: \"cache\", models: 0 };\n }\n}\n\n/**\n * Explicitly refresh the model catalog from models.dev (the ONLY network trigger in the subsystem).\n * Fail-closed: any failure keeps serving the current index (cache or vendored). Kill-switch:\n * `THEOKIT_DISABLE_MODELS_FETCH`.\n *\n * The sequence carried a cognitive-complexity suppression whose reason said splitting it would\n * \"separate a step from the fallback it owns\". The four helpers above each KEEP their fallback: the\n * TTL gate owns \"no cache\", the fetch owns every network and validation failure, the persist owns\n * the write and the patch. What is left here is the order they run in, which is what this function\n * was always for.\n *\n * Still true, and NOT fixed by the split: three of the paths return `{ source: \"cache\" }`, so a\n * caller cannot tell a timeout from an unparseable body from a patch failure. Distinguishing them\n * means adding a field to the PUBLIC `RefreshModelCatalogResult`, which is a release decision rather\n * than a refactor. The `diag` line already names the cause for an operator.\n */\nexport async function refreshModelCatalog(\n opts: RefreshModelCatalogOptions = {},\n): Promise<RefreshModelCatalogResult> {\n // M44 M4 fix — self-initialize provider registration so the `@theokit/sdk/models` subpath works\n // standalone (without the consumer having built an Agent first).\n registerBuiltins();\n if (fetchDisabledByEnv()) return { source: \"skipped\", models: 0 };\n\n const url = opts.url ?? process.env.THEOKIT_MODELS_URL ?? DEFAULT_URL;\n const path = cachePathFor(url);\n const now = opts.deps?.now ?? (() => Date.now());\n\n if (opts.force !== true) {\n const cached = servedFromFreshCache(url, path, now);\n if (cached !== undefined) return cached;\n }\n\n const body = await fetchCatalogBody(url, boundFetch(opts.deps?.fetch));\n // fail-closed: serve whatever we already have (stale cache if present, else vendored)\n if (body === undefined) return { source: \"cache\", models: loadCacheIntoIndex(url) };\n\n return persistAndPatch(path, body);\n}\n\n/** The enriched per-model view (public via `@theokit/sdk/models`): index lookup by (possibly prefixed) id. */\nexport function getModelInfo(modelId: string): ReturnType<typeof getCatalogModelInfo> {\n return getCatalogModelInfo(modelId);\n}\n"]}
|
package/dist/models.js
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { Retry } from './chunk-7F7XE6CM.js';
|
|
2
2
|
import { parseModelId } from './chunk-R7WIIPUR.js';
|
|
3
3
|
export { parseModelId } from './chunk-R7WIIPUR.js';
|
|
4
|
-
import { getCatalogModelInfo, registerBuiltins, catalogModelSchema, patchModelInfo, getProviderProfile, loadProviderCatalog } from './chunk-
|
|
4
|
+
import { getCatalogModelInfo, registerBuiltins, catalogModelSchema, patchModelInfo, getProviderProfile, loadProviderCatalog } from './chunk-SVCPJRUB.js';
|
|
5
5
|
import './chunk-AGACYRJ2.js';
|
|
6
|
-
import './chunk-
|
|
6
|
+
import './chunk-TX56N7FR.js';
|
|
7
7
|
import './chunk-5Q4RTLMP.js';
|
|
8
8
|
import './chunk-H3CVJSFC.js';
|
|
9
|
+
import { boundFetch } from './chunk-Q7GYMXVC.js';
|
|
9
10
|
import './chunk-B5MHRQJZ.js';
|
|
10
11
|
import { diag } from './chunk-CZJ6Q7CW.js';
|
|
11
12
|
import { createHash, randomBytes } from 'crypto';
|
|
@@ -273,7 +274,7 @@ async function refreshModelCatalog(opts = {}) {
|
|
|
273
274
|
const cached = servedFromFreshCache(url, path, now);
|
|
274
275
|
if (cached !== void 0) return cached;
|
|
275
276
|
}
|
|
276
|
-
const body = await fetchCatalogBody(url, opts.deps?.fetch
|
|
277
|
+
const body = await fetchCatalogBody(url, boundFetch(opts.deps?.fetch));
|
|
277
278
|
if (body === void 0) return { source: "cache", models: loadCacheIntoIndex(url) };
|
|
278
279
|
return persistAndPatch(path, body);
|
|
279
280
|
}
|
package/dist/models.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/llm/model-capabilities.ts","../src/internal/llm/model-option.ts","../src/internal/providers/catalog-source-models-dev.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAgCA,IAAM,qBAAA,GAA2C;AAAA,EAC/C,cAAA,EAAgB,KAAA;AAAA,EAChB,wBAAA,EAA0B,KAAA;AAAA,EAC1B,eAAA,EAAiB,KAAA;AAAA,EACjB,oBAAA,EAAsB,KAAA;AAAA,EACtB,gBAAA,EAAkB,IAAA;AAAA,EAClB,eAAA,EAAiB;AACnB,CAAA;AAGA,IAAM,gBAAA,GAAmB,CAAC,aAAA,EAAe,SAAA,EAAW,UAAU,CAAA;AAM9D,SAAS,gBAAgB,CAAA,EAAoC;AAC3D,EAAA,OAAO;AAAA,IACL,cAAA,EAAgB,EAAE,UAAA,EAAY,KAAA,EAAO,SAAS,OAAO,CAAA,IAAK,EAAE,UAAA,IAAc,KAAA;AAAA,IAC1E,wBAAA,EAA0B,EAAE,iBAAA,IAAqB,KAAA;AAAA,IACjD,eAAA,EAAiB,EAAE,SAAA,IAAa,KAAA;AAAA,IAChC,oBAAA,EAAuB,EAAkC,aAAA,IAAiB,KAAA;AAAA,IAC1E,gBAAA,EAAkB,CAAA,CAAE,KAAA,EAAO,OAAA,IAAW,qBAAA,CAAsB,gBAAA;AAAA,IAC5D,eAAA,EAAiB,CAAA,CAAE,KAAA,EAAO,MAAA,IAAU,qBAAA,CAAsB;AAAA,GAC5D;AACF;AAWO,SAAS,yBAAyB,OAAA,EAAoC;AAC3E,EAAA,MAAM,IAAA,GAAO,kBAAA,CAAmB,kBA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A,6CAAA,EAAiD,IAAc,OAAO,CAAA;AAAA;AAAA,KACxE;AACA,IAAA,OAAO,EAAE,MAAA,EAAQ,OAAA,EAAS,MAAA,EAAQ,CAAA,EAAE;AAAA,EACtC;AACF;AAkBA,eAAsB,mBAAA,CACpB,IAAA,GAAmC,EAAC,EACA;AAGpC,EAAA,gBAAA,EAAiB;AACjB,EAAA,IAAI,oBAAmB,EAAG,OAAO,EAAE,MAAA,EAAQ,SAAA,EAAW,QAAQ,CAAA,EAAE;AAEhE,EAAA,MAAM,GAAA,GAAM,IAAA,CAAK,GAAA,IAAO,OAAA,CAAQ,IAAI,kBAAA,IAAsB,WAAA;AAC1D,EAAA,MAAM,IAAA,GAAO,aAAa,GAAG,CAAA;AAC7B,EAAA,MAAM,MAAM,IAAA,CAAK,IAAA,EAAM,GAAA,KAAQ,MAAM,KAAK,GAAA,EAAI,CAAA;AAE9C,EAAA,IAAI,IAAA,CAAK,UAAU,IAAA,EAAM;AACvB,IAAA,MAAM,MAAA,GAAS,oBAAA,CAAqB,GAAA,EAAK,IAAA,EAAM,GAAG,CAAA;AAClD,IAAA,IAAI,MAAA,KAAW,QAAW,OAAO,MAAA;AAAA,EACnC;AAEA,EAAA,MAAM,OAAO,MAAM,gBAAA,CAAiB,KAAK,IAAA,CAAK,IAAA,EAAM,SAAS,KAAK,CAAA;AAElE,EAAA,IAAI,IAAA,KAAS,QAAW,OAAO,EAAE,QAAQ,OAAA,EAAS,MAAA,EAAQ,kBAAA,CAAmB,GAAG,CAAA,EAAE;AAElF,EAAA,OAAO,eAAA,CAAgB,MAAM,IAAI,CAAA;AACnC;AAGO,SAAS,aAAa,OAAA,EAAyD;AACpF,EAAA,OAAO,oBAAoB,OAAO,CAAA;AACpC","file":"models.js","sourcesContent":["/**\n * T3.10c — Model capability registry (DR3 #17).\n *\n * Typed per-model flags that let the SDK gate features at the boundary\n * (before hitting the provider) instead of letting opaque 400s surface.\n *\n * Resolution algorithm:\n * 1. Strip routing prefixes (openrouter/, vertex/, bedrock/) AND the\n * OpenRouter `:variant` suffix (:free/:nitro/…) to find the bare vendor id.\n * 2. Exact match in the `EXACT` catalog → return entry.\n * 3. Vendor inference (e.g., `claude-*` → `anthropic/claude-*`) → return entry.\n * 4. No match → conservative defaults (all false, minimum tokens).\n *\n * Module is internal, but `ModelCapabilities` + `resolveModelCapabilities` are\n * re-exported publicly via the `@theokit/sdk/models` subpath (see their @public tags).\n */\n\n/**\n * Per-model capability shape. Consumers use this to gate features at\n * the SDK boundary (before request construction, not after 400).\n *\n * @public\n */\nexport interface ModelCapabilities {\n supportsVision: boolean;\n supportsStructuredOutput: boolean;\n supportsToolUse: boolean;\n supportsCacheControl: boolean;\n maxContextTokens: number;\n maxOutputTokens: number;\n}\n\nconst CONSERVATIVE_DEFAULTS: ModelCapabilities = {\n supportsVision: false,\n supportsStructuredOutput: false,\n supportsToolUse: false,\n supportsCacheControl: false,\n maxContextTokens: 4096,\n maxOutputTokens: 4096,\n};\n\n/** Routing prefixes to strip to find the underlying vendor model. */\nconst ROUTING_PREFIXES = [\"openrouter/\", \"vertex/\", \"bedrock/\"] as const;\n\nimport { getCatalogModelInfo } from \"../providers/catalog-loader.js\";\nimport type { CatalogModel } from \"../providers/catalog-schema.js\";\n\n/** Map a catalog model block (models.dev shape) to the SDK's ModelCapabilities (M44 — catalog-backed). */\nfunction capsFromCatalog(m: CatalogModel): ModelCapabilities {\n return {\n supportsVision: m.modalities?.input?.includes(\"image\") ?? m.attachment ?? false,\n supportsStructuredOutput: m.structured_output ?? false,\n supportsToolUse: m.tool_call ?? false,\n supportsCacheControl: (m as { cache_control?: boolean }).cache_control ?? false,\n maxContextTokens: m.limit?.context ?? CONSERVATIVE_DEFAULTS.maxContextTokens,\n maxOutputTokens: m.limit?.output ?? CONSERVATIVE_DEFAULTS.maxOutputTokens,\n };\n}\n\n/**\n * Resolve per-model capability flags (vision/structured-output/tool-use/cache +\n * `maxContextTokens`/`maxOutputTokens`) for a model id. Pure, sync, offline (a\n * static catalog — no network). Strips routing prefixes (`openrouter/`/`vertex/`/\n * `bedrock/`) and OpenRouter `:variant` suffixes before lookup; unknown models get\n * conservative defaults. Public via `@theokit/sdk/models`.\n *\n * @public\n */\nexport function resolveModelCapabilities(modelId: string): ModelCapabilities {\n const bare = stripVariantSuffix(stripRoutingPrefix(modelId));\n // M44 — the catalog model-info index replaced the hand-curated EXACT map (single source of truth; the\n // vendored provider-catalog.json carries the migrated data — parity-tested against the old map snapshot).\n const fromIndex = getCatalogModelInfo(bare);\n if (fromIndex !== undefined) return capsFromCatalog(fromIndex);\n // Routing-prefixed models (vertex/claude-3-5-sonnet) strip to bare\n // model name without vendor. Try inferring the vendor from the name.\n const withVendor = inferVendorPrefix(bare);\n if (withVendor !== bare) {\n const vendored = getCatalogModelInfo(withVendor);\n if (vendored !== undefined) return capsFromCatalog(vendored);\n }\n return CONSERVATIVE_DEFAULTS;\n}\n\nfunction stripRoutingPrefix(modelId: string): string {\n for (const prefix of ROUTING_PREFIXES) {\n if (modelId.startsWith(prefix)) return modelId.slice(prefix.length);\n }\n return modelId;\n}\n\n/**\n * Strip an OpenRouter variant suffix (`:free`/`:nitro`/`:floor`/`:beta`/…) so the\n * catalog lookup hits the underlying model. Model slugs contain no `:` except the\n * variant separator, so cutting at the first `:` is safe.\n */\nfunction stripVariantSuffix(modelId: string): string {\n const i = modelId.indexOf(\":\");\n return i >= 0 ? modelId.slice(0, i) : modelId;\n}\n\n/** Infer vendor prefix from bare model name for routing-prefixed lookups. */\nfunction inferVendorPrefix(bare: string): string {\n if (bare.startsWith(\"claude\")) return `anthropic/${bare}`;\n if (bare.startsWith(\"gpt-\") || bare.startsWith(\"o1\") || bare.startsWith(\"o3\"))\n return `openai/${bare}`;\n if (bare.startsWith(\"gemini\")) return `google/${bare}`;\n return bare;\n}\n","import { parseModelId } from \"./model-identifier.js\";\n\n/**\n * A UI-friendly model option — the shape a `<select>`/dropdown consumes.\n *\n * Public via `@theokit/sdk/models`.\n *\n * @public\n */\nexport interface ModelOption {\n /** The original model id (what you pass back to the SDK). */\n value: string;\n /** Best-effort human label (see {@link humanizeModelName}). */\n label: string;\n /** Provider from the slug prefix, or `undefined` when none. */\n provider: string | undefined;\n}\n\n/** Tokens rendered upper-case rather than title-case. */\nconst ACRONYMS = new Set([\"gpt\", \"ai\", \"hd\", \"ui\", \"api\", \"sdk\", \"llm\", \"xl\"]);\n\nfunction prettyToken(token: string): string {\n if (ACRONYMS.has(token.toLowerCase())) return token.toUpperCase();\n return token.charAt(0).toUpperCase() + token.slice(1);\n}\n\n/**\n * Turn a model id into a best-effort human label: strip the routing/vendor\n * prefix to the core model segment, split on `-`/`_`/`.`/whitespace, title-case\n * each token (known acronyms upper-cased), and append an OpenRouter `:variant`\n * in parentheses. Deterministic, pure, dependency-free.\n *\n * Best-effort, NOT vendor-canonical: `\"anthropic/claude-3-5-sonnet\"` →\n * `\"Claude 3 5 Sonnet\"`. A UI wanting exact marketing names overrides per id.\n *\n * Public via `@theokit/sdk/models`.\n *\n * @public\n */\nexport function humanizeModelName(modelId: string): string {\n const { name } = parseModelId(modelId);\n if (name.length === 0) return \"\";\n const colon = name.indexOf(\":\");\n // Strip a trailing slash so a typo'd `gpt-4o/` keeps its name (not lost to an\n // empty last segment).\n //\n // Done by index rather than with `/\\/+$/`, and the difference is not stylistic: that pattern\n // consumes slashes to the end of the string at every start position and then backtracks\n // looking for an end-anchor that is not there (CodeQL js/polynomial-redos #6). This function\n // is `@public` and takes a caller-supplied model id. Measured on a run of slashes followed by\n // one other character: 25_000 took 496 ms, 100_000 took 31_305 ms — half a minute of pinned\n // CPU to render a label. Walking back from the end is linear and cannot backtrack.\n const base = trimTrailingSlashes(colon >= 0 ? name.slice(0, colon) : name);\n const variant = colon >= 0 ? name.slice(colon + 1) : \"\";\n const lastSlash = base.lastIndexOf(\"/\");\n const core = lastSlash >= 0 ? base.slice(lastSlash + 1) : base;\n const label = core\n .split(/[-_.\\s]+/)\n .filter((t) => t.length > 0)\n .map(prettyToken)\n .join(\" \");\n if (label.length === 0) return variant; // no base label (e.g. \":free\") → bare variant\n return variant.length > 0 ? `${label} (${variant})` : label;\n}\n\n/**\n * Build a {@link ModelOption} (`{ value, label, provider }`) for a model id —\n * a dropdown-ready entry composing {@link humanizeModelName} + `parseModelId`.\n *\n * Public via `@theokit/sdk/models`.\n *\n * @public\n */\nexport function toModelOption(modelId: string): ModelOption {\n return {\n value: modelId,\n label: humanizeModelName(modelId),\n provider: parseModelId(modelId).provider,\n };\n}\n\nconst SLASH_CODE = 47; // \"/\"\n\n/** Removes trailing `/` characters in one linear pass. See the call site for why not a regex. */\nfunction trimTrailingSlashes(value: string): string {\n let end = value.length;\n while (end > 0 && value.charCodeAt(end - 1) === SLASH_CODE) end--;\n return end === value.length ? value : value.slice(0, end);\n}\n","import { createHash, randomBytes } from \"node:crypto\";\nimport { mkdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nimport { Retry } from \"../../retry.js\";\nimport { diag } from \"../diagnostics.js\";\nimport { registerBuiltins } from \"./builtin/index.js\";\nimport { getCatalogModelInfo, loadProviderCatalog, patchModelInfo } from \"./catalog-loader.js\";\nimport { catalogModelSchema } from \"./catalog-schema.js\";\nimport { getProviderProfile } from \"./registry.js\";\n\n/**\n * M44 — the OPTIONAL models.dev catalog source. Explicit opt-in ONLY (`refreshModelCatalog()`): the SDK\n * NEVER fetches at startup or per-request — the vendored catalog + any existing disk cache are the offline\n * base, and every failure mode fails CLOSED back to them (ROADMAP constraint: no runtime hard network dep).\n *\n * The models.dev consumption mechanism:\n * disk cache with mtime TTL, atomic tempfile+rename write, corrupt-cache delete-and-fall-through, kill-switch\n * env. Library adaptations: NO background refresh loop (a consumer composes refresh with the SDK's cron);\n * TTL 1h (not 5min — no background refresher to keep it warm); no cross-process flock v1 (atomic rename +\n * idempotent upstream content — at most one wasted fetch).\n *\n * @internal (the public surface is `refreshModelCatalog` re-exported via `@theokit/sdk/models`)\n */\n\nconst DEFAULT_URL = \"https://models.dev/api.json\";\n\n/**\n * Ceiling on a fetched catalog, before it is parsed or written to the cache.\n *\n * The response body was read with `res.text()` and persisted with no bound, so a host serving a\n * multi-gigabyte document would have been materialised in memory and then written to disk. The\n * default URL is trusted, but `THEOKIT_MODELS_URL` lets an operator point this anywhere, and a\n * limit is the difference between \"we only fetch from a host we trust\" and \"we cannot be hurt by\n * one we do not\".\n *\n * 32 MiB is roughly 40x the real catalog (~800 KiB in 2026-08), so it bounds the failure without\n * being a number anyone has to tune when models.dev grows.\n */\nconst MAX_CATALOG_BYTES = 32 * 1024 * 1024;\nconst TTL_MS = 60 * 60 * 1000; // 1 hour\nconst FETCH_TIMEOUT_MS = 10_000;\n\n/**\n * Arguments to `refreshModelCatalog`, the SDK's only network trigger for model metadata.\n *\n * `url` wins over the `THEOKIT_MODELS_URL` environment variable, which in turn wins over\n * `https://models.dev/api.json`. A non-default URL gets its own cache file, named by a hash of\n * the URL, so switching sources never reads another source's cache.\n *\n * `force` skips only the freshness check — it does not skip the kill switch. When\n * `THEOKIT_DISABLE_MODELS_FETCH` is set to anything other than an empty string, `\"0\"` or\n * `\"false\"`, the call returns `source: \"skipped\"` with no fetch and no cache read, whatever\n * `force` says.\n *\n * Without `force`, a cache file whose mtime is under an hour old is served directly and no\n * request is made.\n *\n * `deps` exists so tests can drive the fetch and the clock; production leaves it unset.\n */\nexport interface RefreshModelCatalogOptions {\n /** Override the source URL (`THEOKIT_MODELS_URL` env also honored). */\n url?: string;\n /** Bypass the TTL freshness gate. */\n force?: boolean;\n /** Injected for tests. */\n deps?: { fetch?: typeof fetch; now?: () => number };\n}\n\n/**\n * What `refreshModelCatalog` did. It never throws on a failed refresh, so this is the only place\n * the outcome is reported.\n *\n * `source` is `\"network\"` only when a request succeeded, its body parsed as JSON, and the models\n * were patched in. Every failure path — kill switch aside — returns `\"cache\"`: an HTTP error\n * after retries, a timeout, an unparseable body, or a patch that threw. `\"cache\"` therefore means\n * \"serving what was already there\", which may be a fresh cache, a stale one, or nothing but the\n * vendored catalog. Read `models` to tell those apart. `\"skipped\"` means the kill switch was set.\n *\n * `models` counts the models patched into the index during this call, not the catalog's size. It\n * counts each model once even when the provider has aliases and the model is written under several\n * index keys, and it excludes models whose payload failed schema validation and models under\n * providers the SDK does not know. It is 0 whenever there was no cache to fall back on, and 0 for\n * `\"skipped\"`.\n *\n * A cache write that fails is logged and otherwise ignored: the result can still say `\"network\"`\n * with the data live in memory and nothing on disk.\n */\nexport interface RefreshModelCatalogResult {\n /** Where the data came from: a fresh network fetch, the still-fresh disk cache, or skipped entirely. */\n source: \"network\" | \"cache\" | \"skipped\";\n /** How many models were patched into the index. */\n models: number;\n}\n\n/** The cache file for a source URL (custom URLs get a hash-suffixed name). */\nexport function cachePathFor(url: string): string {\n // M44 L8 fix — honor the SDK home override so tests and multi-home setups never touch the real ~/.theokit.\n const base = process.env.THEOKIT_HOME?.trim() || join(homedir(), \".theokit\");\n const dir = join(base, \"cache\", \"models-dev\");\n if (url === DEFAULT_URL) return join(dir, \"api.json\");\n const hash = createHash(\"sha256\").update(url).digest(\"hex\").slice(0, 12);\n return join(dir, `api-${hash}.json`);\n}\n\n/** Atomic write: temp file + rename (crash mid-write never leaves a partial cache). */\nfunction writeCacheAtomic(path: string, body: string): void {\n mkdirSync(dirname(path), { recursive: true });\n const tmp = `${path}.tmp-${randomBytes(6).toString(\"hex\")}`;\n try {\n writeFileSync(tmp, body);\n renameSync(tmp, path);\n } catch (err) {\n try {\n unlinkSync(tmp);\n } catch {\n // best effort\n }\n throw err;\n }\n}\n\n/**\n * M44 H3 fix — models.dev provider ids ≠ theokit ids (google↔google-gemini, zai↔zhipu, togetherai↔together,\n * fireworks-ai↔fireworks, amazon-bedrock↔bedrock, google-vertex↔vertex). The RUNTIME mapping mirrors the\n * maintenance script's table; targets resolve against the CATALOG entries (id + aliases — the same namespace\n * the vendored index uses) first, then the registry.\n */\nconst MODELS_DEV_ID_MAP: Record<string, string> = {\n google: \"google-gemini\",\n zai: \"zhipu\",\n togetherai: \"together\",\n \"fireworks-ai\": \"fireworks\",\n \"amazon-bedrock\": \"bedrock\",\n \"google-vertex\": \"vertex\",\n};\n\nlet _catalogTargets: Map<string, { keys: string[] }> | undefined;\n/** external-id → the index keys (entry id + aliases) its models patch under. Lazy; catalog-first. */\nfunction catalogTargets(): Map<string, { keys: string[] }> {\n if (_catalogTargets !== undefined) return _catalogTargets;\n _catalogTargets = new Map();\n try {\n for (const entry of Object.values(loadProviderCatalog())) {\n const keys = [entry.id, ...(entry.aliases ?? [])];\n for (const k of keys) {\n if (!_catalogTargets.has(k)) _catalogTargets.set(k, { keys });\n }\n }\n } catch {\n // catalog unavailable — registry fallback below still works\n }\n return _catalogTargets;\n}\n\nfunction resolvePatchKeys(externalId: string): string[] | undefined {\n const mapped = MODELS_DEV_ID_MAP[externalId] ?? externalId;\n const fromCatalog = catalogTargets().get(mapped);\n if (fromCatalog !== undefined) return fromCatalog.keys;\n const profile = getProviderProfile(mapped);\n if (profile !== undefined) return [profile.name, ...(profile.aliases ?? [])];\n return undefined;\n}\n\n/** Parse + patch the index from an api.json payload. Unknown providers are skipped with WARN (once each). */\n// PRE-EXISTING debt, exposed when M75 fixed the Biome config that used to abort before\n// sweeping these files (a nested root under refactor/). It is not new code and was not touched\n// by M75; refactoring SDK internals without review would trade a visible problem for a diff\n// risky. Tracked in usetheodev/theokit-sdk#151.\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: validates and merges an UNTRUSTED upstream payload (models.dev api.json) shape by shape, dropping a single bad model rather than the file. Each branch is a distinct malformed input; merging them loses which one was seen.\nfunction patchIndexFromApiJson(raw: unknown): number {\n if (typeof raw !== \"object\" || raw === null) return 0;\n let patched = 0;\n const skipped: string[] = [];\n for (const [providerId, provider] of Object.entries(raw as Record<string, unknown>)) {\n const models = (provider as { models?: Record<string, unknown> })?.models;\n if (models === undefined || typeof models !== \"object\") continue;\n // Enrich ONLY providers the SDK knows — models.dev's npm/api fields cannot be mapped to a theokit\n // apiMode/authType safely, so unknown providers are data we cannot route.\n const keys = resolvePatchKeys(providerId);\n if (keys === undefined) {\n skipped.push(providerId);\n continue;\n }\n for (const [modelId, rawModel] of Object.entries(models)) {\n const parsed = catalogModelSchema.safeParse(rawModel);\n if (!parsed.success) continue; // malformed model — drop silently (live data, additive drift expected)\n for (const key of keys) patchModelInfo(`${key}/${modelId}`, parsed.data);\n patched++;\n }\n }\n if (skipped.length > 0) {\n diag(\n `[theokit-sdk] WARN: models-dev refresh skipped ${skipped.length} unknown provider(s) (e.g. ${skipped.slice(0, 3).join(\", \")})\\n`,\n );\n }\n return patched;\n}\n\n/**\n * Load an existing disk cache into the index (called by refresh when fresh, or opportunistically by a\n * consumer at startup — NEVER fetches). Corrupt cache → delete + fall through to vendored data.\n */\nexport function loadCacheIntoIndex(url: string = DEFAULT_URL): number {\n const path = cachePathFor(url);\n let body: string;\n try {\n body = readFileSync(path, \"utf-8\");\n } catch {\n return 0; // no cache — vendored data only\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(body);\n } catch {\n // corrupt cache: delete and fall through to the vendored catalog.\n // M44 L9 fix — only a PARSE failure is cache corruption; a patch error must never delete a valid cache.\n try {\n unlinkSync(path);\n } catch {\n // best effort\n }\n diag(`[theokit-sdk] WARN: corrupt models-dev cache deleted (${path})\\n`);\n return 0;\n }\n try {\n return patchIndexFromApiJson(parsed);\n } catch (err) {\n diag(`[theokit-sdk] WARN: models-dev cache patch failed (${(err as Error).message})\\n`);\n return 0;\n }\n}\n\n/**\n * The kill switch, read from the environment.\n *\n * Truthy-only by design (M44 L11): a presence check would treat `THEOKIT_DISABLE_MODELS_FETCH=0`\n * and `=false` as \"disabled\", which is the opposite of what anyone writing them means.\n */\nfunction fetchDisabledByEnv(): boolean {\n const kill = process.env.THEOKIT_DISABLE_MODELS_FETCH;\n return kill !== undefined && kill !== \"\" && kill !== \"0\" && kill.toLowerCase() !== \"false\";\n}\n\n/**\n * The TTL gate: a cache file younger than {@link TTL_MS} serves without touching the network.\n *\n * Returns `undefined` when there is no usable cache — including when `statSync` throws, which is\n * how \"no cache file\" arrives. That is the ONE failure this step owns, and its fallback is simply\n * to let the caller proceed to the fetch.\n */\nfunction servedFromFreshCache(\n url: string,\n path: string,\n now: () => number,\n): RefreshModelCatalogResult | undefined {\n try {\n if (now() - statSync(path).mtimeMs >= TTL_MS) return undefined;\n } catch {\n return undefined; // no cache — proceed to fetch\n }\n return { source: \"cache\", models: loadCacheIntoIndex(url) };\n}\n\n/**\n * Fetch the catalog, bound its size, and prove it parses before anyone persists it.\n *\n * Returns `undefined` after logging when ANY of that fails — timeout, non-2xx, oversize, unparseable\n * body. The fallback this step owns is \"serve what we already have\", and the caller applies it.\n * Splitting the step from its fallback was the objection recorded in the suppression this replaces;\n * the fallback is not separated, it is named — `undefined` means \"this step could not produce a\n * body\", and there is exactly one thing to do about that.\n */\nasync function fetchCatalogBody(url: string, fetchImpl: typeof fetch): Promise<string | undefined> {\n try {\n const res = await Retry.run(\n async () => {\n const r = await fetchImpl(url, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });\n if (!r.ok) throw new Error(`HTTP ${r.status}`);\n return r;\n },\n // 2 transient retries with backoff; every error here is worth one more try —\n // the whole call is already fail-closed at the caller.\n { retries: 2, isRetryable: () => true, initialDelayMs: 200 },\n );\n const declaredLength = Number(res.headers.get(\"content-length\") ?? Number.NaN);\n if (Number.isFinite(declaredLength) && declaredLength > MAX_CATALOG_BYTES) {\n throw new Error(`catalog too large: ${declaredLength} bytes declared`);\n }\n const body = await res.text();\n // Checked again after reading: `content-length` is the server's claim, and a server that\n // omits it or lies about it is exactly the one worth bounding. Both checks are cheap and\n // neither alone is sufficient.\n if (body.length > MAX_CATALOG_BYTES) {\n throw new Error(`catalog too large: ${body.length} bytes received`);\n }\n JSON.parse(body); // validate before persisting — never cache garbage\n return body;\n } catch (err) {\n diag(\n `[theokit-sdk] WARN: models-dev refresh failed (${(err as Error).message}) — serving existing data\\n`,\n );\n return undefined;\n }\n}\n\n/**\n * Persist the fetched body and patch it into the index.\n *\n * Two independent failures with two different consequences, which is why they are two try blocks\n * and not one: a cache write that fails costs the NEXT process a fetch and nothing more, so the run\n * continues; a patch that fails means this body never reached the index, so the index is whatever it\n * was and the result says `cache`.\n */\nfunction persistAndPatch(path: string, body: string): RefreshModelCatalogResult {\n try {\n writeCacheAtomic(path, body);\n } catch (err) {\n diag(`[theokit-sdk] WARN: models-dev cache write failed (${(err as Error).message})\\n`);\n }\n try {\n return { source: \"network\", models: patchIndexFromApiJson(JSON.parse(body)) };\n } catch (err) {\n diag(\n `[theokit-sdk] WARN: models-dev patch failed (${(err as Error).message}) — serving existing data\\n`,\n );\n return { source: \"cache\", models: 0 };\n }\n}\n\n/**\n * Explicitly refresh the model catalog from models.dev (the ONLY network trigger in the subsystem).\n * Fail-closed: any failure keeps serving the current index (cache or vendored). Kill-switch:\n * `THEOKIT_DISABLE_MODELS_FETCH`.\n *\n * The sequence carried a cognitive-complexity suppression whose reason said splitting it would\n * \"separate a step from the fallback it owns\". The four helpers above each KEEP their fallback: the\n * TTL gate owns \"no cache\", the fetch owns every network and validation failure, the persist owns\n * the write and the patch. What is left here is the order they run in, which is what this function\n * was always for.\n *\n * Still true, and NOT fixed by the split: three of the paths return `{ source: \"cache\" }`, so a\n * caller cannot tell a timeout from an unparseable body from a patch failure. Distinguishing them\n * means adding a field to the PUBLIC `RefreshModelCatalogResult`, which is a release decision rather\n * than a refactor. The `diag` line already names the cause for an operator.\n */\nexport async function refreshModelCatalog(\n opts: RefreshModelCatalogOptions = {},\n): Promise<RefreshModelCatalogResult> {\n // M44 M4 fix — self-initialize provider registration so the `@theokit/sdk/models` subpath works\n // standalone (without the consumer having built an Agent first).\n registerBuiltins();\n if (fetchDisabledByEnv()) return { source: \"skipped\", models: 0 };\n\n const url = opts.url ?? process.env.THEOKIT_MODELS_URL ?? DEFAULT_URL;\n const path = cachePathFor(url);\n const now = opts.deps?.now ?? (() => Date.now());\n\n if (opts.force !== true) {\n const cached = servedFromFreshCache(url, path, now);\n if (cached !== undefined) return cached;\n }\n\n const body = await fetchCatalogBody(url, opts.deps?.fetch ?? fetch);\n // fail-closed: serve whatever we already have (stale cache if present, else vendored)\n if (body === undefined) return { source: \"cache\", models: loadCacheIntoIndex(url) };\n\n return persistAndPatch(path, body);\n}\n\n/** The enriched per-model view (public via `@theokit/sdk/models`): index lookup by (possibly prefixed) id. */\nexport function getModelInfo(modelId: string): ReturnType<typeof getCatalogModelInfo> {\n return getCatalogModelInfo(modelId);\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/internal/llm/model-capabilities.ts","../src/internal/llm/model-option.ts","../src/internal/providers/catalog-source-models-dev.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAgCA,IAAM,qBAAA,GAA2C;AAAA,EAC/C,cAAA,EAAgB,KAAA;AAAA,EAChB,wBAAA,EAA0B,KAAA;AAAA,EAC1B,eAAA,EAAiB,KAAA;AAAA,EACjB,oBAAA,EAAsB,KAAA;AAAA,EACtB,gBAAA,EAAkB,IAAA;AAAA,EAClB,eAAA,EAAiB;AACnB,CAAA;AAGA,IAAM,gBAAA,GAAmB,CAAC,aAAA,EAAe,SAAA,EAAW,UAAU,CAAA;AAM9D,SAAS,gBAAgB,CAAA,EAAoC;AAC3D,EAAA,OAAO;AAAA,IACL,cAAA,EAAgB,EAAE,UAAA,EAAY,KAAA,EAAO,SAAS,OAAO,CAAA,IAAK,EAAE,UAAA,IAAc,KAAA;AAAA,IAC1E,wBAAA,EAA0B,EAAE,iBAAA,IAAqB,KAAA;AAAA,IACjD,eAAA,EAAiB,EAAE,SAAA,IAAa,KAAA;AAAA,IAChC,oBAAA,EAAuB,EAAkC,aAAA,IAAiB,KAAA;AAAA,IAC1E,gBAAA,EAAkB,CAAA,CAAE,KAAA,EAAO,OAAA,IAAW,qBAAA,CAAsB,gBAAA;AAAA,IAC5D,eAAA,EAAiB,CAAA,CA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ACpC","file":"models.js","sourcesContent":["/**\n * T3.10c — Model capability registry (DR3 #17).\n *\n * Typed per-model flags that let the SDK gate features at the boundary\n * (before hitting the provider) instead of letting opaque 400s surface.\n *\n * Resolution algorithm:\n * 1. Strip routing prefixes (openrouter/, vertex/, bedrock/) AND the\n * OpenRouter `:variant` suffix (:free/:nitro/…) to find the bare vendor id.\n * 2. Exact match in the `EXACT` catalog → return entry.\n * 3. Vendor inference (e.g., `claude-*` → `anthropic/claude-*`) → return entry.\n * 4. No match → conservative defaults (all false, minimum tokens).\n *\n * Module is internal, but `ModelCapabilities` + `resolveModelCapabilities` are\n * re-exported publicly via the `@theokit/sdk/models` subpath (see their @public tags).\n */\n\n/**\n * Per-model capability shape. Consumers use this to gate features at\n * the SDK boundary (before request construction, not after 400).\n *\n * @public\n */\nexport interface ModelCapabilities {\n supportsVision: boolean;\n supportsStructuredOutput: boolean;\n supportsToolUse: boolean;\n supportsCacheControl: boolean;\n maxContextTokens: number;\n maxOutputTokens: number;\n}\n\nconst CONSERVATIVE_DEFAULTS: ModelCapabilities = {\n supportsVision: false,\n supportsStructuredOutput: false,\n supportsToolUse: false,\n supportsCacheControl: false,\n maxContextTokens: 4096,\n maxOutputTokens: 4096,\n};\n\n/** Routing prefixes to strip to find the underlying vendor model. */\nconst ROUTING_PREFIXES = [\"openrouter/\", \"vertex/\", \"bedrock/\"] as const;\n\nimport { getCatalogModelInfo } from \"../providers/catalog-loader.js\";\nimport type { CatalogModel } from \"../providers/catalog-schema.js\";\n\n/** Map a catalog model block (models.dev shape) to the SDK's ModelCapabilities (M44 — catalog-backed). */\nfunction capsFromCatalog(m: CatalogModel): ModelCapabilities {\n return {\n supportsVision: m.modalities?.input?.includes(\"image\") ?? m.attachment ?? false,\n supportsStructuredOutput: m.structured_output ?? false,\n supportsToolUse: m.tool_call ?? false,\n supportsCacheControl: (m as { cache_control?: boolean }).cache_control ?? false,\n maxContextTokens: m.limit?.context ?? CONSERVATIVE_DEFAULTS.maxContextTokens,\n maxOutputTokens: m.limit?.output ?? CONSERVATIVE_DEFAULTS.maxOutputTokens,\n };\n}\n\n/**\n * Resolve per-model capability flags (vision/structured-output/tool-use/cache +\n * `maxContextTokens`/`maxOutputTokens`) for a model id. Pure, sync, offline (a\n * static catalog — no network). Strips routing prefixes (`openrouter/`/`vertex/`/\n * `bedrock/`) and OpenRouter `:variant` suffixes before lookup; unknown models get\n * conservative defaults. Public via `@theokit/sdk/models`.\n *\n * @public\n */\nexport function resolveModelCapabilities(modelId: string): ModelCapabilities {\n const bare = stripVariantSuffix(stripRoutingPrefix(modelId));\n // M44 — the catalog model-info index replaced the hand-curated EXACT map (single source of truth; the\n // vendored provider-catalog.json carries the migrated data — parity-tested against the old map snapshot).\n const fromIndex = getCatalogModelInfo(bare);\n if (fromIndex !== undefined) return capsFromCatalog(fromIndex);\n // Routing-prefixed models (vertex/claude-3-5-sonnet) strip to bare\n // model name without vendor. Try inferring the vendor from the name.\n const withVendor = inferVendorPrefix(bare);\n if (withVendor !== bare) {\n const vendored = getCatalogModelInfo(withVendor);\n if (vendored !== undefined) return capsFromCatalog(vendored);\n }\n return CONSERVATIVE_DEFAULTS;\n}\n\nfunction stripRoutingPrefix(modelId: string): string {\n for (const prefix of ROUTING_PREFIXES) {\n if (modelId.startsWith(prefix)) return modelId.slice(prefix.length);\n }\n return modelId;\n}\n\n/**\n * Strip an OpenRouter variant suffix (`:free`/`:nitro`/`:floor`/`:beta`/…) so the\n * catalog lookup hits the underlying model. Model slugs contain no `:` except the\n * variant separator, so cutting at the first `:` is safe.\n */\nfunction stripVariantSuffix(modelId: string): string {\n const i = modelId.indexOf(\":\");\n return i >= 0 ? modelId.slice(0, i) : modelId;\n}\n\n/** Infer vendor prefix from bare model name for routing-prefixed lookups. */\nfunction inferVendorPrefix(bare: string): string {\n if (bare.startsWith(\"claude\")) return `anthropic/${bare}`;\n if (bare.startsWith(\"gpt-\") || bare.startsWith(\"o1\") || bare.startsWith(\"o3\"))\n return `openai/${bare}`;\n if (bare.startsWith(\"gemini\")) return `google/${bare}`;\n return bare;\n}\n","import { parseModelId } from \"./model-identifier.js\";\n\n/**\n * A UI-friendly model option — the shape a `<select>`/dropdown consumes.\n *\n * Public via `@theokit/sdk/models`.\n *\n * @public\n */\nexport interface ModelOption {\n /** The original model id (what you pass back to the SDK). */\n value: string;\n /** Best-effort human label (see {@link humanizeModelName}). */\n label: string;\n /** Provider from the slug prefix, or `undefined` when none. */\n provider: string | undefined;\n}\n\n/** Tokens rendered upper-case rather than title-case. */\nconst ACRONYMS = new Set([\"gpt\", \"ai\", \"hd\", \"ui\", \"api\", \"sdk\", \"llm\", \"xl\"]);\n\nfunction prettyToken(token: string): string {\n if (ACRONYMS.has(token.toLowerCase())) return token.toUpperCase();\n return token.charAt(0).toUpperCase() + token.slice(1);\n}\n\n/**\n * Turn a model id into a best-effort human label: strip the routing/vendor\n * prefix to the core model segment, split on `-`/`_`/`.`/whitespace, title-case\n * each token (known acronyms upper-cased), and append an OpenRouter `:variant`\n * in parentheses. Deterministic, pure, dependency-free.\n *\n * Best-effort, NOT vendor-canonical: `\"anthropic/claude-3-5-sonnet\"` →\n * `\"Claude 3 5 Sonnet\"`. A UI wanting exact marketing names overrides per id.\n *\n * Public via `@theokit/sdk/models`.\n *\n * @public\n */\nexport function humanizeModelName(modelId: string): string {\n const { name } = parseModelId(modelId);\n if (name.length === 0) return \"\";\n const colon = name.indexOf(\":\");\n // Strip a trailing slash so a typo'd `gpt-4o/` keeps its name (not lost to an\n // empty last segment).\n //\n // Done by index rather than with `/\\/+$/`, and the difference is not stylistic: that pattern\n // consumes slashes to the end of the string at every start position and then backtracks\n // looking for an end-anchor that is not there (CodeQL js/polynomial-redos #6). This function\n // is `@public` and takes a caller-supplied model id. Measured on a run of slashes followed by\n // one other character: 25_000 took 496 ms, 100_000 took 31_305 ms — half a minute of pinned\n // CPU to render a label. Walking back from the end is linear and cannot backtrack.\n const base = trimTrailingSlashes(colon >= 0 ? name.slice(0, colon) : name);\n const variant = colon >= 0 ? name.slice(colon + 1) : \"\";\n const lastSlash = base.lastIndexOf(\"/\");\n const core = lastSlash >= 0 ? base.slice(lastSlash + 1) : base;\n const label = core\n .split(/[-_.\\s]+/)\n .filter((t) => t.length > 0)\n .map(prettyToken)\n .join(\" \");\n if (label.length === 0) return variant; // no base label (e.g. \":free\") → bare variant\n return variant.length > 0 ? `${label} (${variant})` : label;\n}\n\n/**\n * Build a {@link ModelOption} (`{ value, label, provider }`) for a model id —\n * a dropdown-ready entry composing {@link humanizeModelName} + `parseModelId`.\n *\n * Public via `@theokit/sdk/models`.\n *\n * @public\n */\nexport function toModelOption(modelId: string): ModelOption {\n return {\n value: modelId,\n label: humanizeModelName(modelId),\n provider: parseModelId(modelId).provider,\n };\n}\n\nconst SLASH_CODE = 47; // \"/\"\n\n/** Removes trailing `/` characters in one linear pass. See the call site for why not a regex. */\nfunction trimTrailingSlashes(value: string): string {\n let end = value.length;\n while (end > 0 && value.charCodeAt(end - 1) === SLASH_CODE) end--;\n return end === value.length ? value : value.slice(0, end);\n}\n","import { createHash, randomBytes } from \"node:crypto\";\nimport { mkdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nimport { Retry } from \"../../retry.js\";\nimport { diag } from \"../diagnostics.js\";\nimport { boundFetch } from \"../runtime-fetch.js\";\nimport { registerBuiltins } from \"./builtin/index.js\";\nimport { getCatalogModelInfo, loadProviderCatalog, patchModelInfo } from \"./catalog-loader.js\";\nimport { catalogModelSchema } from \"./catalog-schema.js\";\nimport { getProviderProfile } from \"./registry.js\";\n\n/**\n * M44 — the OPTIONAL models.dev catalog source. Explicit opt-in ONLY (`refreshModelCatalog()`): the SDK\n * NEVER fetches at startup or per-request — the vendored catalog + any existing disk cache are the offline\n * base, and every failure mode fails CLOSED back to them (ROADMAP constraint: no runtime hard network dep).\n *\n * The models.dev consumption mechanism:\n * disk cache with mtime TTL, atomic tempfile+rename write, corrupt-cache delete-and-fall-through, kill-switch\n * env. Library adaptations: NO background refresh loop (a consumer composes refresh with the SDK's cron);\n * TTL 1h (not 5min — no background refresher to keep it warm); no cross-process flock v1 (atomic rename +\n * idempotent upstream content — at most one wasted fetch).\n *\n * @internal (the public surface is `refreshModelCatalog` re-exported via `@theokit/sdk/models`)\n */\n\nconst DEFAULT_URL = \"https://models.dev/api.json\";\n\n/**\n * Ceiling on a fetched catalog, before it is parsed or written to the cache.\n *\n * The response body was read with `res.text()` and persisted with no bound, so a host serving a\n * multi-gigabyte document would have been materialised in memory and then written to disk. The\n * default URL is trusted, but `THEOKIT_MODELS_URL` lets an operator point this anywhere, and a\n * limit is the difference between \"we only fetch from a host we trust\" and \"we cannot be hurt by\n * one we do not\".\n *\n * 32 MiB is roughly 40x the real catalog (~800 KiB in 2026-08), so it bounds the failure without\n * being a number anyone has to tune when models.dev grows.\n */\nconst MAX_CATALOG_BYTES = 32 * 1024 * 1024;\nconst TTL_MS = 60 * 60 * 1000; // 1 hour\nconst FETCH_TIMEOUT_MS = 10_000;\n\n/**\n * Arguments to `refreshModelCatalog`, the SDK's only network trigger for model metadata.\n *\n * `url` wins over the `THEOKIT_MODELS_URL` environment variable, which in turn wins over\n * `https://models.dev/api.json`. A non-default URL gets its own cache file, named by a hash of\n * the URL, so switching sources never reads another source's cache.\n *\n * `force` skips only the freshness check — it does not skip the kill switch. When\n * `THEOKIT_DISABLE_MODELS_FETCH` is set to anything other than an empty string, `\"0\"` or\n * `\"false\"`, the call returns `source: \"skipped\"` with no fetch and no cache read, whatever\n * `force` says.\n *\n * Without `force`, a cache file whose mtime is under an hour old is served directly and no\n * request is made.\n *\n * `deps` exists so tests can drive the fetch and the clock; production leaves it unset.\n */\nexport interface RefreshModelCatalogOptions {\n /** Override the source URL (`THEOKIT_MODELS_URL` env also honored). */\n url?: string;\n /** Bypass the TTL freshness gate. */\n force?: boolean;\n /** Injected for tests. */\n deps?: { fetch?: typeof fetch; now?: () => number };\n}\n\n/**\n * What `refreshModelCatalog` did. It never throws on a failed refresh, so this is the only place\n * the outcome is reported.\n *\n * `source` is `\"network\"` only when a request succeeded, its body parsed as JSON, and the models\n * were patched in. Every failure path — kill switch aside — returns `\"cache\"`: an HTTP error\n * after retries, a timeout, an unparseable body, or a patch that threw. `\"cache\"` therefore means\n * \"serving what was already there\", which may be a fresh cache, a stale one, or nothing but the\n * vendored catalog. Read `models` to tell those apart. `\"skipped\"` means the kill switch was set.\n *\n * `models` counts the models patched into the index during this call, not the catalog's size. It\n * counts each model once even when the provider has aliases and the model is written under several\n * index keys, and it excludes models whose payload failed schema validation and models under\n * providers the SDK does not know. It is 0 whenever there was no cache to fall back on, and 0 for\n * `\"skipped\"`.\n *\n * A cache write that fails is logged and otherwise ignored: the result can still say `\"network\"`\n * with the data live in memory and nothing on disk.\n */\nexport interface RefreshModelCatalogResult {\n /** Where the data came from: a fresh network fetch, the still-fresh disk cache, or skipped entirely. */\n source: \"network\" | \"cache\" | \"skipped\";\n /** How many models were patched into the index. */\n models: number;\n}\n\n/** The cache file for a source URL (custom URLs get a hash-suffixed name). */\nexport function cachePathFor(url: string): string {\n // M44 L8 fix — honor the SDK home override so tests and multi-home setups never touch the real ~/.theokit.\n const base = process.env.THEOKIT_HOME?.trim() || join(homedir(), \".theokit\");\n const dir = join(base, \"cache\", \"models-dev\");\n if (url === DEFAULT_URL) return join(dir, \"api.json\");\n const hash = createHash(\"sha256\").update(url).digest(\"hex\").slice(0, 12);\n return join(dir, `api-${hash}.json`);\n}\n\n/** Atomic write: temp file + rename (crash mid-write never leaves a partial cache). */\nfunction writeCacheAtomic(path: string, body: string): void {\n mkdirSync(dirname(path), { recursive: true });\n const tmp = `${path}.tmp-${randomBytes(6).toString(\"hex\")}`;\n try {\n writeFileSync(tmp, body);\n renameSync(tmp, path);\n } catch (err) {\n try {\n unlinkSync(tmp);\n } catch {\n // best effort\n }\n throw err;\n }\n}\n\n/**\n * M44 H3 fix — models.dev provider ids ≠ theokit ids (google↔google-gemini, zai↔zhipu, togetherai↔together,\n * fireworks-ai↔fireworks, amazon-bedrock↔bedrock, google-vertex↔vertex). The RUNTIME mapping mirrors the\n * maintenance script's table; targets resolve against the CATALOG entries (id + aliases — the same namespace\n * the vendored index uses) first, then the registry.\n */\nconst MODELS_DEV_ID_MAP: Record<string, string> = {\n google: \"google-gemini\",\n zai: \"zhipu\",\n togetherai: \"together\",\n \"fireworks-ai\": \"fireworks\",\n \"amazon-bedrock\": \"bedrock\",\n \"google-vertex\": \"vertex\",\n};\n\nlet _catalogTargets: Map<string, { keys: string[] }> | undefined;\n/** external-id → the index keys (entry id + aliases) its models patch under. Lazy; catalog-first. */\nfunction catalogTargets(): Map<string, { keys: string[] }> {\n if (_catalogTargets !== undefined) return _catalogTargets;\n _catalogTargets = new Map();\n try {\n for (const entry of Object.values(loadProviderCatalog())) {\n const keys = [entry.id, ...(entry.aliases ?? [])];\n for (const k of keys) {\n if (!_catalogTargets.has(k)) _catalogTargets.set(k, { keys });\n }\n }\n } catch {\n // catalog unavailable — registry fallback below still works\n }\n return _catalogTargets;\n}\n\nfunction resolvePatchKeys(externalId: string): string[] | undefined {\n const mapped = MODELS_DEV_ID_MAP[externalId] ?? externalId;\n const fromCatalog = catalogTargets().get(mapped);\n if (fromCatalog !== undefined) return fromCatalog.keys;\n const profile = getProviderProfile(mapped);\n if (profile !== undefined) return [profile.name, ...(profile.aliases ?? [])];\n return undefined;\n}\n\n/** Parse + patch the index from an api.json payload. Unknown providers are skipped with WARN (once each). */\n// PRE-EXISTING debt, exposed when M75 fixed the Biome config that used to abort before\n// sweeping these files (a nested root under refactor/). It is not new code and was not touched\n// by M75; refactoring SDK internals without review would trade a visible problem for a diff\n// risky. Tracked in usetheodev/theokit-sdk#151.\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: validates and merges an UNTRUSTED upstream payload (models.dev api.json) shape by shape, dropping a single bad model rather than the file. Each branch is a distinct malformed input; merging them loses which one was seen.\nfunction patchIndexFromApiJson(raw: unknown): number {\n if (typeof raw !== \"object\" || raw === null) return 0;\n let patched = 0;\n const skipped: string[] = [];\n for (const [providerId, provider] of Object.entries(raw as Record<string, unknown>)) {\n const models = (provider as { models?: Record<string, unknown> })?.models;\n if (models === undefined || typeof models !== \"object\") continue;\n // Enrich ONLY providers the SDK knows — models.dev's npm/api fields cannot be mapped to a theokit\n // apiMode/authType safely, so unknown providers are data we cannot route.\n const keys = resolvePatchKeys(providerId);\n if (keys === undefined) {\n skipped.push(providerId);\n continue;\n }\n for (const [modelId, rawModel] of Object.entries(models)) {\n const parsed = catalogModelSchema.safeParse(rawModel);\n if (!parsed.success) continue; // malformed model — drop silently (live data, additive drift expected)\n for (const key of keys) patchModelInfo(`${key}/${modelId}`, parsed.data);\n patched++;\n }\n }\n if (skipped.length > 0) {\n diag(\n `[theokit-sdk] WARN: models-dev refresh skipped ${skipped.length} unknown provider(s) (e.g. ${skipped.slice(0, 3).join(\", \")})\\n`,\n );\n }\n return patched;\n}\n\n/**\n * Load an existing disk cache into the index (called by refresh when fresh, or opportunistically by a\n * consumer at startup — NEVER fetches). Corrupt cache → delete + fall through to vendored data.\n */\nexport function loadCacheIntoIndex(url: string = DEFAULT_URL): number {\n const path = cachePathFor(url);\n let body: string;\n try {\n body = readFileSync(path, \"utf-8\");\n } catch {\n return 0; // no cache — vendored data only\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(body);\n } catch {\n // corrupt cache: delete and fall through to the vendored catalog.\n // M44 L9 fix — only a PARSE failure is cache corruption; a patch error must never delete a valid cache.\n try {\n unlinkSync(path);\n } catch {\n // best effort\n }\n diag(`[theokit-sdk] WARN: corrupt models-dev cache deleted (${path})\\n`);\n return 0;\n }\n try {\n return patchIndexFromApiJson(parsed);\n } catch (err) {\n diag(`[theokit-sdk] WARN: models-dev cache patch failed (${(err as Error).message})\\n`);\n return 0;\n }\n}\n\n/**\n * The kill switch, read from the environment.\n *\n * Truthy-only by design (M44 L11): a presence check would treat `THEOKIT_DISABLE_MODELS_FETCH=0`\n * and `=false` as \"disabled\", which is the opposite of what anyone writing them means.\n */\nfunction fetchDisabledByEnv(): boolean {\n const kill = process.env.THEOKIT_DISABLE_MODELS_FETCH;\n return kill !== undefined && kill !== \"\" && kill !== \"0\" && kill.toLowerCase() !== \"false\";\n}\n\n/**\n * The TTL gate: a cache file younger than {@link TTL_MS} serves without touching the network.\n *\n * Returns `undefined` when there is no usable cache — including when `statSync` throws, which is\n * how \"no cache file\" arrives. That is the ONE failure this step owns, and its fallback is simply\n * to let the caller proceed to the fetch.\n */\nfunction servedFromFreshCache(\n url: string,\n path: string,\n now: () => number,\n): RefreshModelCatalogResult | undefined {\n try {\n if (now() - statSync(path).mtimeMs >= TTL_MS) return undefined;\n } catch {\n return undefined; // no cache — proceed to fetch\n }\n return { source: \"cache\", models: loadCacheIntoIndex(url) };\n}\n\n/**\n * Fetch the catalog, bound its size, and prove it parses before anyone persists it.\n *\n * Returns `undefined` after logging when ANY of that fails — timeout, non-2xx, oversize, unparseable\n * body. The fallback this step owns is \"serve what we already have\", and the caller applies it.\n * Splitting the step from its fallback was the objection recorded in the suppression this replaces;\n * the fallback is not separated, it is named — `undefined` means \"this step could not produce a\n * body\", and there is exactly one thing to do about that.\n */\nasync function fetchCatalogBody(url: string, fetchImpl: typeof fetch): Promise<string | undefined> {\n try {\n const res = await Retry.run(\n async () => {\n const r = await fetchImpl(url, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });\n if (!r.ok) throw new Error(`HTTP ${r.status}`);\n return r;\n },\n // 2 transient retries with backoff; every error here is worth one more try —\n // the whole call is already fail-closed at the caller.\n { retries: 2, isRetryable: () => true, initialDelayMs: 200 },\n );\n const declaredLength = Number(res.headers.get(\"content-length\") ?? Number.NaN);\n if (Number.isFinite(declaredLength) && declaredLength > MAX_CATALOG_BYTES) {\n throw new Error(`catalog too large: ${declaredLength} bytes declared`);\n }\n const body = await res.text();\n // Checked again after reading: `content-length` is the server's claim, and a server that\n // omits it or lies about it is exactly the one worth bounding. Both checks are cheap and\n // neither alone is sufficient.\n if (body.length > MAX_CATALOG_BYTES) {\n throw new Error(`catalog too large: ${body.length} bytes received`);\n }\n JSON.parse(body); // validate before persisting — never cache garbage\n return body;\n } catch (err) {\n diag(\n `[theokit-sdk] WARN: models-dev refresh failed (${(err as Error).message}) — serving existing data\\n`,\n );\n return undefined;\n }\n}\n\n/**\n * Persist the fetched body and patch it into the index.\n *\n * Two independent failures with two different consequences, which is why they are two try blocks\n * and not one: a cache write that fails costs the NEXT process a fetch and nothing more, so the run\n * continues; a patch that fails means this body never reached the index, so the index is whatever it\n * was and the result says `cache`.\n */\nfunction persistAndPatch(path: string, body: string): RefreshModelCatalogResult {\n try {\n writeCacheAtomic(path, body);\n } catch (err) {\n diag(`[theokit-sdk] WARN: models-dev cache write failed (${(err as Error).message})\\n`);\n }\n try {\n return { source: \"network\", models: patchIndexFromApiJson(JSON.parse(body)) };\n } catch (err) {\n diag(\n `[theokit-sdk] WARN: models-dev patch failed (${(err as Error).message}) — serving existing data\\n`,\n );\n return { source: \"cache\", models: 0 };\n }\n}\n\n/**\n * Explicitly refresh the model catalog from models.dev (the ONLY network trigger in the subsystem).\n * Fail-closed: any failure keeps serving the current index (cache or vendored). Kill-switch:\n * `THEOKIT_DISABLE_MODELS_FETCH`.\n *\n * The sequence carried a cognitive-complexity suppression whose reason said splitting it would\n * \"separate a step from the fallback it owns\". The four helpers above each KEEP their fallback: the\n * TTL gate owns \"no cache\", the fetch owns every network and validation failure, the persist owns\n * the write and the patch. What is left here is the order they run in, which is what this function\n * was always for.\n *\n * Still true, and NOT fixed by the split: three of the paths return `{ source: \"cache\" }`, so a\n * caller cannot tell a timeout from an unparseable body from a patch failure. Distinguishing them\n * means adding a field to the PUBLIC `RefreshModelCatalogResult`, which is a release decision rather\n * than a refactor. The `diag` line already names the cause for an operator.\n */\nexport async function refreshModelCatalog(\n opts: RefreshModelCatalogOptions = {},\n): Promise<RefreshModelCatalogResult> {\n // M44 M4 fix — self-initialize provider registration so the `@theokit/sdk/models` subpath works\n // standalone (without the consumer having built an Agent first).\n registerBuiltins();\n if (fetchDisabledByEnv()) return { source: \"skipped\", models: 0 };\n\n const url = opts.url ?? process.env.THEOKIT_MODELS_URL ?? DEFAULT_URL;\n const path = cachePathFor(url);\n const now = opts.deps?.now ?? (() => Date.now());\n\n if (opts.force !== true) {\n const cached = servedFromFreshCache(url, path, now);\n if (cached !== undefined) return cached;\n }\n\n const body = await fetchCatalogBody(url, boundFetch(opts.deps?.fetch));\n // fail-closed: serve whatever we already have (stale cache if present, else vendored)\n if (body === undefined) return { source: \"cache\", models: loadCacheIntoIndex(url) };\n\n return persistAndPatch(path, body);\n}\n\n/** The enriched per-model view (public via `@theokit/sdk/models`): index lookup by (possibly prefixed) id. */\nexport function getModelInfo(modelId: string): ReturnType<typeof getCatalogModelInfo> {\n return getCatalogModelInfo(modelId);\n}\n"]}
|
package/dist/persistence.cjs
CHANGED
|
@@ -2,10 +2,11 @@
|
|
|
2
2
|
|
|
3
3
|
var chunkVTYY7XL5_cjs = require('./chunk-VTYY7XL5.cjs');
|
|
4
4
|
var chunkNKIQTLFA_cjs = require('./chunk-NKIQTLFA.cjs');
|
|
5
|
-
var
|
|
5
|
+
var chunkZWACQM5U_cjs = require('./chunk-ZWACQM5U.cjs');
|
|
6
6
|
var chunkA4RAL2ER_cjs = require('./chunk-A4RAL2ER.cjs');
|
|
7
7
|
var chunkP22BZE7G_cjs = require('./chunk-P22BZE7G.cjs');
|
|
8
|
-
var
|
|
8
|
+
var chunkR5YPDAKD_cjs = require('./chunk-R5YPDAKD.cjs');
|
|
9
|
+
var chunkASK2OQM5_cjs = require('./chunk-ASK2OQM5.cjs');
|
|
9
10
|
var chunkZF2LDKQQ_cjs = require('./chunk-ZF2LDKQQ.cjs');
|
|
10
11
|
var chunkJLRLCBJ4_cjs = require('./chunk-JLRLCBJ4.cjs');
|
|
11
12
|
var chunkUNFBHV46_cjs = require('./chunk-UNFBHV46.cjs');
|
|
@@ -16,7 +17,7 @@ var path = require('path');
|
|
|
16
17
|
|
|
17
18
|
var DEFAULT_ID_SCAN_BYTES = 64 * 1024;
|
|
18
19
|
async function listSessions(cwd, options = {}) {
|
|
19
|
-
const dir = path.join(options.baseDir ??
|
|
20
|
+
const dir = path.join(options.baseDir ?? chunkZWACQM5U_cjs.transcriptRoot(), "projects", chunkZWACQM5U_cjs.encodeProjectDir(cwd));
|
|
20
21
|
let names;
|
|
21
22
|
try {
|
|
22
23
|
names = await promises.readdir(dir);
|
|
@@ -178,23 +179,23 @@ Object.defineProperty(exports, "sessionHasWriter", {
|
|
|
178
179
|
});
|
|
179
180
|
Object.defineProperty(exports, "encodeProjectDir", {
|
|
180
181
|
enumerable: true,
|
|
181
|
-
get: function () { return
|
|
182
|
+
get: function () { return chunkZWACQM5U_cjs.encodeProjectDir; }
|
|
182
183
|
});
|
|
183
184
|
Object.defineProperty(exports, "legacyTranscriptPath", {
|
|
184
185
|
enumerable: true,
|
|
185
|
-
get: function () { return
|
|
186
|
+
get: function () { return chunkZWACQM5U_cjs.legacyTranscriptPath; }
|
|
186
187
|
});
|
|
187
188
|
Object.defineProperty(exports, "sessionUuidFor", {
|
|
188
189
|
enumerable: true,
|
|
189
|
-
get: function () { return
|
|
190
|
+
get: function () { return chunkZWACQM5U_cjs.sessionUuidFor; }
|
|
190
191
|
});
|
|
191
192
|
Object.defineProperty(exports, "transcriptPath", {
|
|
192
193
|
enumerable: true,
|
|
193
|
-
get: function () { return
|
|
194
|
+
get: function () { return chunkZWACQM5U_cjs.transcriptPath; }
|
|
194
195
|
});
|
|
195
196
|
Object.defineProperty(exports, "transcriptRoot", {
|
|
196
197
|
enumerable: true,
|
|
197
|
-
get: function () { return
|
|
198
|
+
get: function () { return chunkZWACQM5U_cjs.transcriptRoot; }
|
|
198
199
|
});
|
|
199
200
|
Object.defineProperty(exports, "sanitizeFts5Query", {
|
|
200
201
|
enumerable: true,
|
|
@@ -214,23 +215,23 @@ Object.defineProperty(exports, "openSqliteResilient", {
|
|
|
214
215
|
});
|
|
215
216
|
Object.defineProperty(exports, "JsonlParseError", {
|
|
216
217
|
enumerable: true,
|
|
217
|
-
get: function () { return
|
|
218
|
+
get: function () { return chunkR5YPDAKD_cjs.JsonlParseError; }
|
|
218
219
|
});
|
|
219
220
|
Object.defineProperty(exports, "appendJsonl", {
|
|
220
221
|
enumerable: true,
|
|
221
|
-
get: function () { return
|
|
222
|
+
get: function () { return chunkR5YPDAKD_cjs.appendJsonl; }
|
|
222
223
|
});
|
|
223
224
|
Object.defineProperty(exports, "loadJsonl", {
|
|
224
225
|
enumerable: true,
|
|
225
|
-
get: function () { return
|
|
226
|
+
get: function () { return chunkR5YPDAKD_cjs.loadJsonl; }
|
|
226
227
|
});
|
|
227
228
|
Object.defineProperty(exports, "readJsonlIds", {
|
|
228
229
|
enumerable: true,
|
|
229
|
-
get: function () { return
|
|
230
|
+
get: function () { return chunkR5YPDAKD_cjs.readJsonlIds; }
|
|
230
231
|
});
|
|
231
232
|
Object.defineProperty(exports, "withFileLock", {
|
|
232
233
|
enumerable: true,
|
|
233
|
-
get: function () { return
|
|
234
|
+
get: function () { return chunkASK2OQM5_cjs.withFileLock; }
|
|
234
235
|
});
|
|
235
236
|
Object.defineProperty(exports, "withCwdMutex", {
|
|
236
237
|
enumerable: true,
|