@theokit/sdk 4.13.0 → 4.13.1
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 +6 -0
- package/dist/cron.cjs +49 -12
- package/dist/cron.cjs.map +1 -1
- package/dist/cron.js +49 -12
- package/dist/cron.js.map +1 -1
- package/dist/eval.cjs +49 -12
- package/dist/eval.cjs.map +1 -1
- package/dist/eval.js +49 -12
- package/dist/eval.js.map +1 -1
- package/dist/index.cjs +49 -12
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +49 -12
- package/dist/index.js.map +1 -1
- package/dist/models.cjs +639 -17
- package/dist/models.cjs.map +1 -1
- package/dist/models.js +640 -18
- package/dist/models.js.map +1 -1
- package/dist/provider-catalog.json +6 -3
- package/package.json +1 -1
package/dist/models.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { statSync, readFileSync, unlinkSync, mkdirSync, writeFileSync, renameSync } from 'fs';
|
|
1
|
+
import { statSync, readFileSync, unlinkSync, mkdirSync, writeFileSync, renameSync, chmodSync, openSync, fsyncSync, closeSync } from 'fs';
|
|
2
2
|
import { dirname, join } from 'path';
|
|
3
3
|
import { fileURLToPath } from 'url';
|
|
4
4
|
import { z } from 'zod';
|
|
@@ -41,8 +41,34 @@ var catalogModelSchema = z.object({
|
|
|
41
41
|
}).loose();
|
|
42
42
|
|
|
43
43
|
// src/internal/providers/registry.ts
|
|
44
|
-
|
|
45
|
-
|
|
44
|
+
function globalSingleton(key, create) {
|
|
45
|
+
const g = globalThis;
|
|
46
|
+
const sym = Symbol.for(key);
|
|
47
|
+
if (g[sym] === void 0) g[sym] = create();
|
|
48
|
+
return g[sym];
|
|
49
|
+
}
|
|
50
|
+
var REGISTRY = globalSingleton(
|
|
51
|
+
"theokit-sdk.providers.registry",
|
|
52
|
+
() => /* @__PURE__ */ new Map()
|
|
53
|
+
);
|
|
54
|
+
var ALIASES = globalSingleton("theokit-sdk.providers.aliases", () => /* @__PURE__ */ new Map());
|
|
55
|
+
function registerProvider(profile) {
|
|
56
|
+
if (REGISTRY.has(profile.name)) {
|
|
57
|
+
process.stderr.write(`[theokit-sdk] Provider "${profile.name}" overridden by user plugin.
|
|
58
|
+
`);
|
|
59
|
+
}
|
|
60
|
+
REGISTRY.set(profile.name, profile);
|
|
61
|
+
for (const alias of profile.aliases ?? []) {
|
|
62
|
+
const previous = ALIASES.get(alias);
|
|
63
|
+
if (previous !== void 0 && previous !== profile.name) {
|
|
64
|
+
process.stderr.write(
|
|
65
|
+
`[theokit-sdk] Alias "${alias}" collision: was "${previous}", now "${profile.name}".
|
|
66
|
+
`
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
ALIASES.set(alias, profile.name);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
46
72
|
function getProviderProfile(name) {
|
|
47
73
|
const canonical = ALIASES.get(name) ?? name;
|
|
48
74
|
return REGISTRY.get(canonical);
|
|
@@ -50,22 +76,46 @@ function getProviderProfile(name) {
|
|
|
50
76
|
|
|
51
77
|
// src/internal/providers/catalog-loader.ts
|
|
52
78
|
var __dirname_resolved = dirname(fileURLToPath(import.meta.url));
|
|
53
|
-
|
|
79
|
+
function globalSingleton2(key, create) {
|
|
80
|
+
const g = globalThis;
|
|
81
|
+
const sym = Symbol.for(key);
|
|
82
|
+
if (g[sym] === void 0) g[sym] = create();
|
|
83
|
+
return g[sym];
|
|
84
|
+
}
|
|
85
|
+
var modelInfoIndex = globalSingleton2(
|
|
86
|
+
"theokit-sdk.providers.model-info-index",
|
|
87
|
+
() => /* @__PURE__ */ new Map()
|
|
88
|
+
);
|
|
89
|
+
var patchedModelKeys = globalSingleton2(
|
|
90
|
+
"theokit-sdk.providers.model-info-patched",
|
|
91
|
+
() => /* @__PURE__ */ new Set()
|
|
92
|
+
);
|
|
93
|
+
var indexState = globalSingleton2("theokit-sdk.providers.model-info-loaded", () => ({
|
|
94
|
+
loaded: false
|
|
95
|
+
}));
|
|
54
96
|
function getCatalogModelInfo(key) {
|
|
55
97
|
ensureModelIndexLoaded();
|
|
56
98
|
return modelInfoIndex.get(key);
|
|
57
99
|
}
|
|
58
100
|
function patchModelInfo(key, model) {
|
|
59
101
|
ensureModelIndexLoaded();
|
|
60
|
-
modelInfoIndex.
|
|
102
|
+
const existing = modelInfoIndex.get(key);
|
|
103
|
+
modelInfoIndex.set(key, existing === void 0 ? model : { ...existing, ...model });
|
|
104
|
+
patchedModelKeys.add(key);
|
|
61
105
|
}
|
|
62
|
-
var _modelIndexLoaded = false;
|
|
63
106
|
function ensureModelIndexLoaded() {
|
|
64
|
-
if (
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
107
|
+
if (indexState.loaded) return;
|
|
108
|
+
indexState.loaded = true;
|
|
109
|
+
try {
|
|
110
|
+
const catalog = loadProviderCatalog();
|
|
111
|
+
for (const entry of Object.values(catalog)) {
|
|
112
|
+
indexEntryModels(entry);
|
|
113
|
+
}
|
|
114
|
+
} catch (err) {
|
|
115
|
+
process.stderr.write(
|
|
116
|
+
`[theokit-sdk] WARN: provider catalog unavailable (${err.message}) \u2014 per-model data disabled
|
|
117
|
+
`
|
|
118
|
+
);
|
|
69
119
|
}
|
|
70
120
|
}
|
|
71
121
|
function indexEntryModels(entry) {
|
|
@@ -110,6 +160,27 @@ function loadProviderCatalog(opts) {
|
|
|
110
160
|
}
|
|
111
161
|
return result;
|
|
112
162
|
}
|
|
163
|
+
function registerCatalogProviders(opts) {
|
|
164
|
+
const catalog = loadProviderCatalog();
|
|
165
|
+
for (const entry of Object.values(catalog)) {
|
|
166
|
+
if (getProviderProfile(entry.id) !== void 0) continue;
|
|
167
|
+
if (entry.aliases?.some((a) => getProviderProfile(a) !== void 0)) continue;
|
|
168
|
+
const profile = {
|
|
169
|
+
name: entry.id,
|
|
170
|
+
apiMode: entry.apiMode,
|
|
171
|
+
authType: entry.authType,
|
|
172
|
+
baseUrl: entry.baseUrl,
|
|
173
|
+
envVars: entry.envVars,
|
|
174
|
+
fallbackModels: entry.fallbackModels,
|
|
175
|
+
displayName: entry.displayName,
|
|
176
|
+
aliases: entry.aliases,
|
|
177
|
+
modelsUrl: entry.modelsUrl,
|
|
178
|
+
hostname: entry.hostname,
|
|
179
|
+
extraHeaders: entry.extraHeaders
|
|
180
|
+
};
|
|
181
|
+
registerProvider(profile);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
113
184
|
|
|
114
185
|
// src/internal/llm/model-capabilities.ts
|
|
115
186
|
var CONSERVATIVE_DEFAULTS = {
|
|
@@ -299,12 +370,502 @@ var Retry = class {
|
|
|
299
370
|
}
|
|
300
371
|
};
|
|
301
372
|
|
|
373
|
+
// src/internal/providers/builtin/anthropic.ts
|
|
374
|
+
var ANTHROPIC = {
|
|
375
|
+
name: "anthropic",
|
|
376
|
+
apiMode: "anthropic_messages",
|
|
377
|
+
envVars: ["ANTHROPIC_API_KEY"],
|
|
378
|
+
authType: "api_key",
|
|
379
|
+
baseUrl: "https://api.anthropic.com",
|
|
380
|
+
modelsUrl: "https://api.anthropic.com/v1/models",
|
|
381
|
+
hostname: "api.anthropic.com",
|
|
382
|
+
fallbackModels: ["claude-opus-4-7", "claude-sonnet-4-6", "claude-haiku-4-5-20251001"]
|
|
383
|
+
};
|
|
384
|
+
|
|
385
|
+
// src/internal/providers/builtin/bedrock.ts
|
|
386
|
+
var BEDROCK = {
|
|
387
|
+
name: "bedrock",
|
|
388
|
+
apiMode: "bedrock_anthropic",
|
|
389
|
+
envVars: ["AWS_BEARER_TOKEN_BEDROCK"],
|
|
390
|
+
authType: "aws_bearer",
|
|
391
|
+
baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
|
|
392
|
+
modelsUrl: void 0,
|
|
393
|
+
hostname: "bedrock-runtime.amazonaws.com",
|
|
394
|
+
fallbackModels: [
|
|
395
|
+
"bedrock/us.anthropic.claude-sonnet-4-5-v1:0",
|
|
396
|
+
"bedrock/us.anthropic.claude-opus-4-7-v1:0",
|
|
397
|
+
"bedrock/global.anthropic.claude-haiku-4-5-v1:0"
|
|
398
|
+
]
|
|
399
|
+
};
|
|
400
|
+
|
|
401
|
+
// src/internal/providers/builtin/gemini.ts
|
|
402
|
+
var GEMINI = {
|
|
403
|
+
name: "gemini",
|
|
404
|
+
apiMode: "chat_completions",
|
|
405
|
+
envVars: ["OPENROUTER_API_KEY"],
|
|
406
|
+
authType: "api_key",
|
|
407
|
+
baseUrl: "https://openrouter.ai/api",
|
|
408
|
+
hostname: "openrouter.ai",
|
|
409
|
+
fallbackModels: ["google/gemini-2.0-flash-001"]
|
|
410
|
+
};
|
|
411
|
+
|
|
412
|
+
// src/internal/providers/builtin/llamacpp.ts
|
|
413
|
+
var LLAMACPP = {
|
|
414
|
+
name: "llamacpp",
|
|
415
|
+
aliases: ["llama-cpp", "llama.cpp"],
|
|
416
|
+
apiMode: "chat_completions",
|
|
417
|
+
envVars: ["LLAMACPP_API_KEY"],
|
|
418
|
+
authType: "none",
|
|
419
|
+
baseUrl: "http://localhost:8080",
|
|
420
|
+
modelsUrl: "http://localhost:8080/v1/models",
|
|
421
|
+
hostname: "localhost",
|
|
422
|
+
fallbackModels: ["loaded-model"]
|
|
423
|
+
};
|
|
424
|
+
|
|
425
|
+
// src/internal/providers/builtin/lmstudio.ts
|
|
426
|
+
var LMSTUDIO = {
|
|
427
|
+
name: "lmstudio",
|
|
428
|
+
aliases: ["lm-studio", "lm_studio"],
|
|
429
|
+
apiMode: "chat_completions",
|
|
430
|
+
envVars: ["LMSTUDIO_API_KEY"],
|
|
431
|
+
authType: "none",
|
|
432
|
+
baseUrl: "http://localhost:1234",
|
|
433
|
+
modelsUrl: "http://localhost:1234/v1/models",
|
|
434
|
+
hostname: "localhost",
|
|
435
|
+
fallbackModels: ["loaded-model"]
|
|
436
|
+
};
|
|
437
|
+
|
|
438
|
+
// src/internal/providers/builtin/ollama.ts
|
|
439
|
+
var OLLAMA = {
|
|
440
|
+
name: "ollama",
|
|
441
|
+
apiMode: "chat_completions",
|
|
442
|
+
envVars: ["OLLAMA_API_KEY"],
|
|
443
|
+
authType: "none",
|
|
444
|
+
baseUrl: "http://localhost:11434",
|
|
445
|
+
modelsUrl: "http://localhost:11434/v1/models",
|
|
446
|
+
hostname: "localhost",
|
|
447
|
+
fallbackModels: ["llama3.2", "qwen2.5", "mistral"]
|
|
448
|
+
};
|
|
449
|
+
|
|
450
|
+
// src/internal/providers/builtin/openai.ts
|
|
451
|
+
var OPENAI = {
|
|
452
|
+
name: "openai",
|
|
453
|
+
apiMode: "chat_completions",
|
|
454
|
+
envVars: ["OPENAI_API_KEY"],
|
|
455
|
+
authType: "api_key",
|
|
456
|
+
baseUrl: "https://api.openai.com",
|
|
457
|
+
modelsUrl: "https://api.openai.com/v1/models",
|
|
458
|
+
hostname: "api.openai.com",
|
|
459
|
+
fallbackModels: ["gpt-4o", "gpt-4o-mini"]
|
|
460
|
+
};
|
|
461
|
+
function credentialHome(config, env = {}) {
|
|
462
|
+
const override = config.homeEnvVar !== void 0 ? env[config.homeEnvVar]?.trim() : void 0;
|
|
463
|
+
return override !== void 0 && override.length > 0 ? override : join(config.home, config.dirName);
|
|
464
|
+
}
|
|
465
|
+
function authFilePath(config, env = {}) {
|
|
466
|
+
return join(credentialHome(config, env), config.fileName);
|
|
467
|
+
}
|
|
468
|
+
var CredentialError = class extends Error {
|
|
469
|
+
constructor(message) {
|
|
470
|
+
super(message);
|
|
471
|
+
this.name = "CredentialError";
|
|
472
|
+
}
|
|
473
|
+
};
|
|
474
|
+
var apiFileSchema = z.object({
|
|
475
|
+
type: z.literal("api").optional(),
|
|
476
|
+
provider: z.string().min(1).optional(),
|
|
477
|
+
api_key: z.string()
|
|
478
|
+
}).strict();
|
|
479
|
+
var oauthFileSchema = z.object({
|
|
480
|
+
type: z.literal("oauth"),
|
|
481
|
+
provider: z.string().min(1),
|
|
482
|
+
access: z.string().min(1),
|
|
483
|
+
refresh: z.string().min(1),
|
|
484
|
+
expires: z.number(),
|
|
485
|
+
account_id: z.string().optional()
|
|
486
|
+
}).strict();
|
|
487
|
+
var fileSchema = z.union([oauthFileSchema, apiFileSchema]);
|
|
488
|
+
function assertSecureModes(dirPath, path) {
|
|
489
|
+
const dirMode = statSync(dirPath).mode & 511;
|
|
490
|
+
if ((dirMode & 18) !== 0) {
|
|
491
|
+
throw new CredentialError(
|
|
492
|
+
`${dirPath} is writable by other users (mode ${dirMode.toString(8)}), so the credential file inside it can be replaced. Fix it with: chmod 700 ${dirPath}`
|
|
493
|
+
);
|
|
494
|
+
}
|
|
495
|
+
const mode = statSync(path).mode & 511;
|
|
496
|
+
if ((mode & 63) !== 0) {
|
|
497
|
+
throw new CredentialError(
|
|
498
|
+
`${path} is readable by other users (mode ${mode.toString(8)}). A credential file must not be. Fix it with: chmod 600 ${path}`
|
|
499
|
+
);
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
function describeUnionError(parsed, err, path) {
|
|
503
|
+
const looksOAuth = typeof parsed === "object" && parsed !== null && parsed.type === "oauth";
|
|
504
|
+
const specific = looksOAuth ? oauthFileSchema.safeParse(parsed) : apiFileSchema.safeParse(parsed);
|
|
505
|
+
let issue;
|
|
506
|
+
if (!specific.success) {
|
|
507
|
+
issue = specific.error.issues[0];
|
|
508
|
+
} else if (err instanceof z.ZodError) {
|
|
509
|
+
issue = err.issues[0];
|
|
510
|
+
}
|
|
511
|
+
return new CredentialError(
|
|
512
|
+
`${path}: ${issue?.message ?? String(err)} [${issue?.path.join(".") || "root"}]`
|
|
513
|
+
);
|
|
514
|
+
}
|
|
515
|
+
function parseStoredFile(raw, path) {
|
|
516
|
+
let parsed;
|
|
517
|
+
try {
|
|
518
|
+
parsed = JSON.parse(raw);
|
|
519
|
+
} catch {
|
|
520
|
+
throw new CredentialError(
|
|
521
|
+
`${path} is not valid JSON. Expected: {"provider": "<name>", "api_key": "..."}`
|
|
522
|
+
);
|
|
523
|
+
}
|
|
524
|
+
try {
|
|
525
|
+
return fileSchema.parse(parsed);
|
|
526
|
+
} catch (err) {
|
|
527
|
+
throw describeUnionError(parsed, err, path);
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
function readAuthFile(config, env = {}) {
|
|
531
|
+
const path = authFilePath(config, env);
|
|
532
|
+
let raw;
|
|
533
|
+
try {
|
|
534
|
+
raw = readFileSync(path, "utf8");
|
|
535
|
+
} catch (err) {
|
|
536
|
+
if (err.code === "ENOENT") return void 0;
|
|
537
|
+
throw new CredentialError(`cannot read ${path}: ${err.message}`);
|
|
538
|
+
}
|
|
539
|
+
assertSecureModes(credentialHome(config, env), path);
|
|
540
|
+
return parseStoredFile(raw, path);
|
|
541
|
+
}
|
|
542
|
+
function readStoredOAuth(config, env = {}) {
|
|
543
|
+
const stored = readAuthFile(config, env);
|
|
544
|
+
return stored !== void 0 && stored.type === "oauth" ? stored : void 0;
|
|
545
|
+
}
|
|
546
|
+
function isOAuthWrite(c) {
|
|
547
|
+
return "type" in c && c.type === "oauth";
|
|
548
|
+
}
|
|
549
|
+
function buildStorePayload(cred) {
|
|
550
|
+
if (isOAuthWrite(cred)) {
|
|
551
|
+
if (cred.access.length === 0 || cred.refresh.length === 0) {
|
|
552
|
+
throw new CredentialError(
|
|
553
|
+
"refusing to write an oauth credential with an empty access/refresh token"
|
|
554
|
+
);
|
|
555
|
+
}
|
|
556
|
+
return {
|
|
557
|
+
type: "oauth",
|
|
558
|
+
provider: cred.provider,
|
|
559
|
+
access: cred.access,
|
|
560
|
+
refresh: cred.refresh,
|
|
561
|
+
expires: cred.expires,
|
|
562
|
+
...cred.account_id !== void 0 ? { account_id: cred.account_id } : {}
|
|
563
|
+
};
|
|
564
|
+
}
|
|
565
|
+
if (typeof cred.apiKey !== "string" || cred.apiKey.length === 0) {
|
|
566
|
+
throw new CredentialError("refusing to write an empty API key");
|
|
567
|
+
}
|
|
568
|
+
return { provider: cred.provider, api_key: cred.apiKey };
|
|
569
|
+
}
|
|
570
|
+
function writeCredential(cred, config, env = {}) {
|
|
571
|
+
const payload = buildStorePayload(cred);
|
|
572
|
+
const dir = credentialHome(config, env);
|
|
573
|
+
mkdirSync(dir, { recursive: true, mode: 448 });
|
|
574
|
+
chmodSync(dir, 448);
|
|
575
|
+
const path = authFilePath(config, env);
|
|
576
|
+
const tmp = `${path}.tmp-${randomBytes(8).toString("hex")}`;
|
|
577
|
+
try {
|
|
578
|
+
const fd = openSync(tmp, "wx", 384);
|
|
579
|
+
try {
|
|
580
|
+
writeFileSync(fd, `${JSON.stringify(payload, null, 2)}
|
|
581
|
+
`);
|
|
582
|
+
fsyncSync(fd);
|
|
583
|
+
} finally {
|
|
584
|
+
closeSync(fd);
|
|
585
|
+
}
|
|
586
|
+
chmodSync(tmp, 384);
|
|
587
|
+
renameSync(tmp, path);
|
|
588
|
+
} catch (err) {
|
|
589
|
+
try {
|
|
590
|
+
unlinkSync(tmp);
|
|
591
|
+
} catch {
|
|
592
|
+
}
|
|
593
|
+
throw new CredentialError(`cannot write ${path}: ${err.message}`);
|
|
594
|
+
}
|
|
595
|
+
return path;
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
// src/server/auth/errors.ts
|
|
599
|
+
var AuthCallbackError = class extends Error {
|
|
600
|
+
name = "AuthCallbackError";
|
|
601
|
+
code;
|
|
602
|
+
constructor(code, message) {
|
|
603
|
+
super(message ?? `OAuth callback error: ${code}`);
|
|
604
|
+
this.code = code;
|
|
605
|
+
}
|
|
606
|
+
};
|
|
607
|
+
|
|
608
|
+
// src/internal/auth/oauth-engine.ts
|
|
609
|
+
var REFRESH_SKEW_MS = 6e4;
|
|
610
|
+
function parseTokenResponse(body, now) {
|
|
611
|
+
const b = body;
|
|
612
|
+
if (typeof b.access_token !== "string" || b.access_token.length === 0) {
|
|
613
|
+
throw new AuthCallbackError(
|
|
614
|
+
"oauth_token_exchange_failed",
|
|
615
|
+
"token response had no access_token"
|
|
616
|
+
);
|
|
617
|
+
}
|
|
618
|
+
if (typeof b.refresh_token !== "string" || b.refresh_token.length === 0) {
|
|
619
|
+
throw new AuthCallbackError(
|
|
620
|
+
"oauth_token_exchange_failed",
|
|
621
|
+
"token response had no refresh_token"
|
|
622
|
+
);
|
|
623
|
+
}
|
|
624
|
+
const expiresIn = typeof b.expires_in === "number" ? b.expires_in : 3600;
|
|
625
|
+
return {
|
|
626
|
+
access: b.access_token,
|
|
627
|
+
refresh: b.refresh_token,
|
|
628
|
+
expires: now + expiresIn * 1e3,
|
|
629
|
+
...typeof b.account_id === "string" ? { accountId: b.account_id } : {}
|
|
630
|
+
};
|
|
631
|
+
}
|
|
632
|
+
async function postGrant(config, form, deps) {
|
|
633
|
+
let res;
|
|
634
|
+
try {
|
|
635
|
+
res = await deps.fetch(config.tokenEndpoint, {
|
|
636
|
+
method: "POST",
|
|
637
|
+
headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
|
|
638
|
+
body: new URLSearchParams(form).toString()
|
|
639
|
+
});
|
|
640
|
+
} catch (err) {
|
|
641
|
+
throw new AuthCallbackError(
|
|
642
|
+
"oauth_token_exchange_failed",
|
|
643
|
+
`token endpoint request failed: ${err.message}`
|
|
644
|
+
);
|
|
645
|
+
}
|
|
646
|
+
if (!res.ok) {
|
|
647
|
+
throw new AuthCallbackError(
|
|
648
|
+
"oauth_token_exchange_failed",
|
|
649
|
+
`token endpoint returned HTTP ${res.status}`
|
|
650
|
+
);
|
|
651
|
+
}
|
|
652
|
+
let json;
|
|
653
|
+
try {
|
|
654
|
+
json = await res.json();
|
|
655
|
+
} catch {
|
|
656
|
+
throw new AuthCallbackError("oauth_token_exchange_failed", "token response was not valid JSON");
|
|
657
|
+
}
|
|
658
|
+
return parseTokenResponse(json, deps.now());
|
|
659
|
+
}
|
|
660
|
+
function refreshOAuthTokens(config, refresh, deps) {
|
|
661
|
+
return postGrant(
|
|
662
|
+
config,
|
|
663
|
+
{ grant_type: "refresh_token", refresh_token: refresh, client_id: config.clientId },
|
|
664
|
+
deps
|
|
665
|
+
);
|
|
666
|
+
}
|
|
667
|
+
function persistOAuthTokens(provider, tokens, store, env = {}) {
|
|
668
|
+
return writeCredential(
|
|
669
|
+
{
|
|
670
|
+
type: "oauth",
|
|
671
|
+
provider,
|
|
672
|
+
access: tokens.access,
|
|
673
|
+
refresh: tokens.refresh,
|
|
674
|
+
expires: tokens.expires,
|
|
675
|
+
...tokens.accountId !== void 0 ? { account_id: tokens.accountId } : {}
|
|
676
|
+
},
|
|
677
|
+
store,
|
|
678
|
+
env
|
|
679
|
+
);
|
|
680
|
+
}
|
|
681
|
+
var inFlightRefresh = /* @__PURE__ */ new Map();
|
|
682
|
+
async function ensureFreshCredential(resolved, opts, deps) {
|
|
683
|
+
if (resolved.kind !== "oauth") return resolved;
|
|
684
|
+
const now = deps.now();
|
|
685
|
+
if (resolved.expiresAt !== void 0 && resolved.expiresAt > now + REFRESH_SKEW_MS) {
|
|
686
|
+
return resolved;
|
|
687
|
+
}
|
|
688
|
+
const env = opts.env ?? {};
|
|
689
|
+
const path = authFilePath(opts.store, env);
|
|
690
|
+
let refresh = inFlightRefresh.get(path);
|
|
691
|
+
if (refresh === void 0) {
|
|
692
|
+
refresh = (async () => {
|
|
693
|
+
const stored = readStoredOAuth(opts.store, env);
|
|
694
|
+
if (stored === void 0) {
|
|
695
|
+
throw new AuthCallbackError(
|
|
696
|
+
"oauth_token_exchange_failed",
|
|
697
|
+
"no stored oauth credential to refresh"
|
|
698
|
+
);
|
|
699
|
+
}
|
|
700
|
+
const fresh2 = await refreshOAuthTokens(opts.config, stored.refresh, deps);
|
|
701
|
+
const merged = {
|
|
702
|
+
...fresh2,
|
|
703
|
+
accountId: fresh2.accountId ?? stored.account_id
|
|
704
|
+
};
|
|
705
|
+
persistOAuthTokens(resolved.provider, merged, opts.store, env);
|
|
706
|
+
return merged;
|
|
707
|
+
})();
|
|
708
|
+
inFlightRefresh.set(path, refresh);
|
|
709
|
+
refresh.finally(() => inFlightRefresh.delete(path)).catch(() => {
|
|
710
|
+
});
|
|
711
|
+
}
|
|
712
|
+
const fresh = await refresh;
|
|
713
|
+
return {
|
|
714
|
+
kind: "oauth",
|
|
715
|
+
provider: resolved.provider,
|
|
716
|
+
apiKey: fresh.access,
|
|
717
|
+
source: resolved.source,
|
|
718
|
+
inferred: false,
|
|
719
|
+
expiresAt: fresh.expires
|
|
720
|
+
};
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
// src/internal/auth/resolve-credential.ts
|
|
724
|
+
async function resolveOAuth(stored, path, opts, env) {
|
|
725
|
+
if (stored.provider !== opts.provider) return void 0;
|
|
726
|
+
const base = {
|
|
727
|
+
kind: "oauth",
|
|
728
|
+
provider: opts.provider,
|
|
729
|
+
apiKey: stored.access,
|
|
730
|
+
source: path,
|
|
731
|
+
inferred: false,
|
|
732
|
+
expiresAt: stored.expires
|
|
733
|
+
};
|
|
734
|
+
if (opts.oauth === void 0) return base;
|
|
735
|
+
const deps = {
|
|
736
|
+
fetch: opts.deps?.fetch ?? fetch,
|
|
737
|
+
now: opts.deps?.now ?? (() => Date.now())
|
|
738
|
+
};
|
|
739
|
+
return ensureFreshCredential(base, { config: opts.oauth, store: opts.store, env }, deps);
|
|
740
|
+
}
|
|
741
|
+
async function resolveCredential(opts) {
|
|
742
|
+
const env = opts.env ?? {};
|
|
743
|
+
const stored = readAuthFile(opts.store, env);
|
|
744
|
+
if (stored === void 0) return void 0;
|
|
745
|
+
const path = authFilePath(opts.store, env);
|
|
746
|
+
if (stored.type === "oauth") {
|
|
747
|
+
return resolveOAuth(stored, path, opts, env);
|
|
748
|
+
}
|
|
749
|
+
if (stored.api_key.length === 0) return void 0;
|
|
750
|
+
if (stored.provider !== opts.provider) return void 0;
|
|
751
|
+
return {
|
|
752
|
+
kind: "api",
|
|
753
|
+
provider: opts.provider,
|
|
754
|
+
apiKey: stored.api_key,
|
|
755
|
+
source: path,
|
|
756
|
+
inferred: false
|
|
757
|
+
};
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
// src/internal/providers/builtin/openai-chatgpt.ts
|
|
761
|
+
var DEFAULT_STORE = {
|
|
762
|
+
home: homedir(),
|
|
763
|
+
dirName: ".theokit",
|
|
764
|
+
fileName: "auth.json",
|
|
765
|
+
homeEnvVar: "THEOKIT_AUTH_HOME"
|
|
766
|
+
};
|
|
767
|
+
var OPENAI_OAUTH_CONFIG = {
|
|
768
|
+
provider: "openai",
|
|
769
|
+
authorizeEndpoint: "https://auth.openai.com/oauth/authorize",
|
|
770
|
+
tokenEndpoint: "https://auth.openai.com/oauth/token",
|
|
771
|
+
clientId: "app_EMoamEEZ73f0CkXaXp7hrann",
|
|
772
|
+
scopes: ["openid", "profile", "email", "offline_access"],
|
|
773
|
+
redirectUri: "https://auth.openai.com/deviceauth/callback"
|
|
774
|
+
};
|
|
775
|
+
function codexFetch() {
|
|
776
|
+
return (async (input, init) => {
|
|
777
|
+
const env = process.env;
|
|
778
|
+
const resolved = await resolveCredential({
|
|
779
|
+
provider: "openai",
|
|
780
|
+
store: DEFAULT_STORE,
|
|
781
|
+
oauth: OPENAI_OAUTH_CONFIG,
|
|
782
|
+
env
|
|
783
|
+
});
|
|
784
|
+
if (resolved === void 0) {
|
|
785
|
+
throw new Error(
|
|
786
|
+
'openai-chatgpt: no ChatGPT credential found \u2014 run the OpenAI device login (e.g. "/login openai") first.'
|
|
787
|
+
);
|
|
788
|
+
}
|
|
789
|
+
const accountId = readStoredOAuth(DEFAULT_STORE, env)?.account_id;
|
|
790
|
+
const headers = new Headers(init?.headers);
|
|
791
|
+
headers.set("authorization", `Bearer ${resolved.apiKey}`);
|
|
792
|
+
if (accountId !== void 0) headers.set("ChatGPT-Account-Id", accountId);
|
|
793
|
+
return fetch(input, { ...init, headers });
|
|
794
|
+
});
|
|
795
|
+
}
|
|
796
|
+
var OPENAI_CHATGPT = {
|
|
797
|
+
name: "openai-chatgpt",
|
|
798
|
+
apiMode: "responses_api",
|
|
799
|
+
authType: "oauth_device_code",
|
|
800
|
+
baseUrl: "https://chatgpt.com/backend-api/codex",
|
|
801
|
+
envVars: [],
|
|
802
|
+
fallbackModels: [
|
|
803
|
+
"openai-chatgpt/gpt-5.4",
|
|
804
|
+
"openai-chatgpt/gpt-5.4-mini",
|
|
805
|
+
"openai-chatgpt/gpt-5.5"
|
|
806
|
+
],
|
|
807
|
+
extraHeaders: { originator: "codex_cli_rs" },
|
|
808
|
+
transform: {
|
|
809
|
+
// Only `fetch` (async) can await the credential refresh; `headers` is sync and cannot.
|
|
810
|
+
fetch: () => codexFetch()
|
|
811
|
+
}
|
|
812
|
+
};
|
|
813
|
+
|
|
814
|
+
// src/internal/providers/builtin/openrouter.ts
|
|
815
|
+
var OPENROUTER = {
|
|
816
|
+
name: "openrouter",
|
|
817
|
+
apiMode: "chat_completions",
|
|
818
|
+
aliases: ["or"],
|
|
819
|
+
// Ordered fallback (EC-10): OPENROUTER_API_KEY preferred, OPENAI_API_KEY as compat.
|
|
820
|
+
envVars: ["OPENROUTER_API_KEY", "OPENAI_API_KEY"],
|
|
821
|
+
authType: "api_key",
|
|
822
|
+
baseUrl: "https://openrouter.ai/api",
|
|
823
|
+
modelsUrl: "https://openrouter.ai/api/v1/models",
|
|
824
|
+
hostname: "openrouter.ai",
|
|
825
|
+
fallbackModels: ["openai/gpt-4o-mini", "anthropic/claude-3-haiku"]
|
|
826
|
+
};
|
|
827
|
+
|
|
828
|
+
// src/internal/providers/builtin/vertex.ts
|
|
829
|
+
var VERTEX = {
|
|
830
|
+
name: "vertex",
|
|
831
|
+
apiMode: "anthropic_messages",
|
|
832
|
+
// sub-dispatched in selectTransport by profile.name
|
|
833
|
+
envVars: ["GOOGLE_APPLICATION_CREDENTIALS"],
|
|
834
|
+
authType: "gcp_oauth",
|
|
835
|
+
baseUrl: "https://us-central1-aiplatform.googleapis.com",
|
|
836
|
+
modelsUrl: void 0,
|
|
837
|
+
hostname: "aiplatform.googleapis.com",
|
|
838
|
+
fallbackModels: [
|
|
839
|
+
"vertex/anthropic/claude-sonnet-4-5@20250929",
|
|
840
|
+
"vertex/google/gemini-2.0-flash-001"
|
|
841
|
+
]
|
|
842
|
+
};
|
|
843
|
+
|
|
844
|
+
// src/internal/providers/builtin/index.ts
|
|
845
|
+
var registered = false;
|
|
846
|
+
function registerBuiltins() {
|
|
847
|
+
if (registered) return;
|
|
848
|
+
registered = true;
|
|
849
|
+
registerProvider(ANTHROPIC);
|
|
850
|
+
registerProvider(OPENAI);
|
|
851
|
+
registerProvider(OPENAI_CHATGPT);
|
|
852
|
+
registerProvider(OPENROUTER);
|
|
853
|
+
registerProvider(GEMINI);
|
|
854
|
+
registerProvider(OLLAMA);
|
|
855
|
+
registerProvider(LMSTUDIO);
|
|
856
|
+
registerProvider(LLAMACPP);
|
|
857
|
+
registerProvider(BEDROCK);
|
|
858
|
+
registerProvider(VERTEX);
|
|
859
|
+
registerCatalogProviders();
|
|
860
|
+
}
|
|
861
|
+
|
|
302
862
|
// src/internal/providers/catalog-source-models-dev.ts
|
|
303
863
|
var DEFAULT_URL = "https://models.dev/api.json";
|
|
304
864
|
var TTL_MS = 60 * 60 * 1e3;
|
|
305
865
|
var FETCH_TIMEOUT_MS = 1e4;
|
|
306
866
|
function cachePathFor(url) {
|
|
307
|
-
const
|
|
867
|
+
const base = process.env.THEOKIT_HOME?.trim() || join(homedir(), ".theokit");
|
|
868
|
+
const dir = join(base, "cache", "models-dev");
|
|
308
869
|
if (url === DEFAULT_URL) return join(dir, "api.json");
|
|
309
870
|
const hash = createHash("sha256").update(url).digest("hex").slice(0, 12);
|
|
310
871
|
return join(dir, `api-${hash}.json`);
|
|
@@ -323,21 +884,62 @@ function writeCacheAtomic(path, body) {
|
|
|
323
884
|
throw err;
|
|
324
885
|
}
|
|
325
886
|
}
|
|
887
|
+
var MODELS_DEV_ID_MAP = {
|
|
888
|
+
google: "google-gemini",
|
|
889
|
+
zai: "zhipu",
|
|
890
|
+
togetherai: "together",
|
|
891
|
+
"fireworks-ai": "fireworks",
|
|
892
|
+
"amazon-bedrock": "bedrock",
|
|
893
|
+
"google-vertex": "vertex"
|
|
894
|
+
};
|
|
895
|
+
var _catalogTargets;
|
|
896
|
+
function catalogTargets() {
|
|
897
|
+
if (_catalogTargets !== void 0) return _catalogTargets;
|
|
898
|
+
_catalogTargets = /* @__PURE__ */ new Map();
|
|
899
|
+
try {
|
|
900
|
+
for (const entry of Object.values(loadProviderCatalog())) {
|
|
901
|
+
const keys = [entry.id, ...entry.aliases ?? []];
|
|
902
|
+
for (const k of keys) {
|
|
903
|
+
if (!_catalogTargets.has(k)) _catalogTargets.set(k, { keys });
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
} catch {
|
|
907
|
+
}
|
|
908
|
+
return _catalogTargets;
|
|
909
|
+
}
|
|
910
|
+
function resolvePatchKeys(externalId) {
|
|
911
|
+
const mapped = MODELS_DEV_ID_MAP[externalId] ?? externalId;
|
|
912
|
+
const fromCatalog = catalogTargets().get(mapped);
|
|
913
|
+
if (fromCatalog !== void 0) return fromCatalog.keys;
|
|
914
|
+
const profile = getProviderProfile(mapped);
|
|
915
|
+
if (profile !== void 0) return [profile.name, ...profile.aliases ?? []];
|
|
916
|
+
return void 0;
|
|
917
|
+
}
|
|
326
918
|
function patchIndexFromApiJson(raw) {
|
|
327
919
|
if (typeof raw !== "object" || raw === null) return 0;
|
|
328
920
|
let patched = 0;
|
|
921
|
+
const skipped = [];
|
|
329
922
|
for (const [providerId, provider] of Object.entries(raw)) {
|
|
330
923
|
const models = provider?.models;
|
|
331
924
|
if (models === void 0 || typeof models !== "object") continue;
|
|
332
|
-
const
|
|
333
|
-
if (
|
|
925
|
+
const keys = resolvePatchKeys(providerId);
|
|
926
|
+
if (keys === void 0) {
|
|
927
|
+
skipped.push(providerId);
|
|
928
|
+
continue;
|
|
929
|
+
}
|
|
334
930
|
for (const [modelId, rawModel] of Object.entries(models)) {
|
|
335
931
|
const parsed = catalogModelSchema.safeParse(rawModel);
|
|
336
932
|
if (!parsed.success) continue;
|
|
337
|
-
patchModelInfo(`${
|
|
933
|
+
for (const key of keys) patchModelInfo(`${key}/${modelId}`, parsed.data);
|
|
338
934
|
patched++;
|
|
339
935
|
}
|
|
340
936
|
}
|
|
937
|
+
if (skipped.length > 0) {
|
|
938
|
+
process.stderr.write(
|
|
939
|
+
`[theokit-sdk] WARN: models-dev refresh skipped ${skipped.length} unknown provider(s) (e.g. ${skipped.slice(0, 3).join(", ")})
|
|
940
|
+
`
|
|
941
|
+
);
|
|
942
|
+
}
|
|
341
943
|
return patched;
|
|
342
944
|
}
|
|
343
945
|
function loadCacheIntoIndex(url = DEFAULT_URL) {
|
|
@@ -348,8 +950,9 @@ function loadCacheIntoIndex(url = DEFAULT_URL) {
|
|
|
348
950
|
} catch {
|
|
349
951
|
return 0;
|
|
350
952
|
}
|
|
953
|
+
let parsed;
|
|
351
954
|
try {
|
|
352
|
-
|
|
955
|
+
parsed = JSON.parse(body);
|
|
353
956
|
} catch {
|
|
354
957
|
try {
|
|
355
958
|
unlinkSync(path);
|
|
@@ -359,9 +962,20 @@ function loadCacheIntoIndex(url = DEFAULT_URL) {
|
|
|
359
962
|
`);
|
|
360
963
|
return 0;
|
|
361
964
|
}
|
|
965
|
+
try {
|
|
966
|
+
return patchIndexFromApiJson(parsed);
|
|
967
|
+
} catch (err) {
|
|
968
|
+
process.stderr.write(
|
|
969
|
+
`[theokit-sdk] WARN: models-dev cache patch failed (${err.message})
|
|
970
|
+
`
|
|
971
|
+
);
|
|
972
|
+
return 0;
|
|
973
|
+
}
|
|
362
974
|
}
|
|
363
975
|
async function refreshModelCatalog(opts = {}) {
|
|
364
|
-
|
|
976
|
+
registerBuiltins();
|
|
977
|
+
const kill = process.env.THEOKIT_DISABLE_MODELS_FETCH;
|
|
978
|
+
if (kill !== void 0 && kill !== "" && kill !== "0" && kill.toLowerCase() !== "false") {
|
|
365
979
|
return { source: "skipped", models: 0 };
|
|
366
980
|
}
|
|
367
981
|
const url = opts.url ?? process.env.THEOKIT_MODELS_URL ?? DEFAULT_URL;
|
|
@@ -406,7 +1020,15 @@ async function refreshModelCatalog(opts = {}) {
|
|
|
406
1020
|
`
|
|
407
1021
|
);
|
|
408
1022
|
}
|
|
409
|
-
|
|
1023
|
+
try {
|
|
1024
|
+
return { source: "network", models: patchIndexFromApiJson(JSON.parse(body)) };
|
|
1025
|
+
} catch (err) {
|
|
1026
|
+
process.stderr.write(
|
|
1027
|
+
`[theokit-sdk] WARN: models-dev patch failed (${err.message}) \u2014 serving existing data
|
|
1028
|
+
`
|
|
1029
|
+
);
|
|
1030
|
+
return { source: "cache", models: 0 };
|
|
1031
|
+
}
|
|
410
1032
|
}
|
|
411
1033
|
function getModelInfo(modelId) {
|
|
412
1034
|
return getCatalogModelInfo(modelId);
|