@theokit/sdk 4.12.2 → 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 +12 -0
- package/dist/cron.cjs +201 -78
- package/dist/cron.cjs.map +1 -1
- package/dist/cron.js +201 -78
- package/dist/cron.js.map +1 -1
- package/dist/eval.cjs +201 -78
- package/dist/eval.cjs.map +1 -1
- package/dist/eval.js +201 -78
- package/dist/eval.js.map +1 -1
- package/dist/index.cjs +215 -92
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +215 -92
- package/dist/index.js.map +1 -1
- package/dist/internal/providers/catalog-loader.d.ts +8 -0
- package/dist/internal/providers/catalog-schema.d.ts +53 -0
- package/dist/internal/providers/catalog-source-models-dev.d.ts +33 -0
- package/dist/models.cjs +954 -257
- package/dist/models.cjs.map +1 -1
- package/dist/models.d.cts +2 -0
- package/dist/models.d.ts +2 -0
- package/dist/models.js +952 -258
- package/dist/models.js.map +1 -1
- package/dist/provider-catalog.json +574 -5
- package/package.json +1 -1
package/dist/models.js
CHANGED
|
@@ -1,3 +1,187 @@
|
|
|
1
|
+
import { statSync, readFileSync, unlinkSync, mkdirSync, writeFileSync, renameSync, chmodSync, openSync, fsyncSync, closeSync } from 'fs';
|
|
2
|
+
import { dirname, join } from 'path';
|
|
3
|
+
import { fileURLToPath } from 'url';
|
|
4
|
+
import { z } from 'zod';
|
|
5
|
+
import { createHash, randomBytes } from 'crypto';
|
|
6
|
+
import { homedir } from 'os';
|
|
7
|
+
|
|
8
|
+
// src/internal/providers/catalog-loader.ts
|
|
9
|
+
var MODALITIES = ["text", "audio", "image", "video", "pdf"];
|
|
10
|
+
var costSchema = z.object({
|
|
11
|
+
/** USD per 1M tokens (models.dev convention). */
|
|
12
|
+
input: z.number().nonnegative(),
|
|
13
|
+
output: z.number().nonnegative(),
|
|
14
|
+
cache_read: z.number().nonnegative().optional(),
|
|
15
|
+
cache_write: z.number().nonnegative().optional()
|
|
16
|
+
}).loose();
|
|
17
|
+
var limitSchema = z.object({
|
|
18
|
+
context: z.number().positive(),
|
|
19
|
+
input: z.number().positive().optional(),
|
|
20
|
+
output: z.number().positive().optional()
|
|
21
|
+
}).loose();
|
|
22
|
+
var modalitiesSchema = z.object({
|
|
23
|
+
input: z.array(z.enum(MODALITIES)).optional(),
|
|
24
|
+
output: z.array(z.enum(MODALITIES)).optional()
|
|
25
|
+
}).loose();
|
|
26
|
+
var catalogModelSchema = z.object({
|
|
27
|
+
name: z.string().optional(),
|
|
28
|
+
release_date: z.string().optional(),
|
|
29
|
+
attachment: z.boolean().optional(),
|
|
30
|
+
reasoning: z.boolean().optional(),
|
|
31
|
+
temperature: z.boolean().optional(),
|
|
32
|
+
tool_call: z.boolean().optional(),
|
|
33
|
+
/** theokit extension — maps to ModelCapabilities.supportsStructuredOutput. */
|
|
34
|
+
structured_output: z.boolean().optional(),
|
|
35
|
+
/** theokit extension — maps to ModelCapabilities.supportsCacheControl. */
|
|
36
|
+
cache_control: z.boolean().optional(),
|
|
37
|
+
cost: costSchema.optional(),
|
|
38
|
+
limit: limitSchema.optional(),
|
|
39
|
+
modalities: modalitiesSchema.optional(),
|
|
40
|
+
status: z.enum(["alpha", "beta", "deprecated"]).optional()
|
|
41
|
+
}).loose();
|
|
42
|
+
|
|
43
|
+
// src/internal/providers/registry.ts
|
|
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
|
+
}
|
|
72
|
+
function getProviderProfile(name) {
|
|
73
|
+
const canonical = ALIASES.get(name) ?? name;
|
|
74
|
+
return REGISTRY.get(canonical);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// src/internal/providers/catalog-loader.ts
|
|
78
|
+
var __dirname_resolved = dirname(fileURLToPath(import.meta.url));
|
|
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
|
+
}));
|
|
96
|
+
function getCatalogModelInfo(key) {
|
|
97
|
+
ensureModelIndexLoaded();
|
|
98
|
+
return modelInfoIndex.get(key);
|
|
99
|
+
}
|
|
100
|
+
function patchModelInfo(key, model) {
|
|
101
|
+
ensureModelIndexLoaded();
|
|
102
|
+
const existing = modelInfoIndex.get(key);
|
|
103
|
+
modelInfoIndex.set(key, existing === void 0 ? model : { ...existing, ...model });
|
|
104
|
+
patchedModelKeys.add(key);
|
|
105
|
+
}
|
|
106
|
+
function ensureModelIndexLoaded() {
|
|
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
|
+
);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
function indexEntryModels(entry) {
|
|
122
|
+
if (entry.models === void 0 || typeof entry.models !== "object") return;
|
|
123
|
+
for (const [modelId, raw] of Object.entries(entry.models)) {
|
|
124
|
+
const parsed = catalogModelSchema.safeParse(raw);
|
|
125
|
+
if (!parsed.success) {
|
|
126
|
+
process.stderr.write(
|
|
127
|
+
`[theokit-sdk] WARN: Skipping malformed catalog model "${entry.id}/${modelId}": ${parsed.error.issues[0]?.message ?? "invalid"}
|
|
128
|
+
`
|
|
129
|
+
);
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
modelInfoIndex.set(`${entry.id}/${modelId}`, parsed.data);
|
|
133
|
+
for (const alias of entry.aliases ?? []) {
|
|
134
|
+
const key = `${alias}/${modelId}`;
|
|
135
|
+
if (!modelInfoIndex.has(key)) modelInfoIndex.set(key, parsed.data);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
function validateEntry(raw) {
|
|
140
|
+
if (typeof raw.id !== "string" || typeof raw.displayName !== "string" || typeof raw.apiMode !== "string" || typeof raw.authType !== "string" || typeof raw.baseUrl !== "string" || !Array.isArray(raw.envVars) || !Array.isArray(raw.fallbackModels) || raw.capabilities == null || typeof raw.capabilities !== "object") {
|
|
141
|
+
return null;
|
|
142
|
+
}
|
|
143
|
+
return raw;
|
|
144
|
+
}
|
|
145
|
+
function loadProviderCatalog(opts) {
|
|
146
|
+
const catalogPath = join(__dirname_resolved, "provider-catalog.json");
|
|
147
|
+
const rawText = readFileSync(catalogPath, "utf-8");
|
|
148
|
+
let entries = JSON.parse(rawText);
|
|
149
|
+
const result = {};
|
|
150
|
+
for (const raw of entries) {
|
|
151
|
+
const validated = validateEntry(raw);
|
|
152
|
+
if (validated === null) {
|
|
153
|
+
process.stderr.write(
|
|
154
|
+
`[theokit-sdk] WARN: Skipping malformed catalog entry: ${JSON.stringify(raw).slice(0, 100)}
|
|
155
|
+
`
|
|
156
|
+
);
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
result[validated.id] = validated;
|
|
160
|
+
}
|
|
161
|
+
return result;
|
|
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
|
+
}
|
|
184
|
+
|
|
1
185
|
// src/internal/llm/model-capabilities.ts
|
|
2
186
|
var CONSERVATIVE_DEFAULTS = {
|
|
3
187
|
supportsVision: false,
|
|
@@ -7,268 +191,25 @@ var CONSERVATIVE_DEFAULTS = {
|
|
|
7
191
|
maxContextTokens: 4096,
|
|
8
192
|
maxOutputTokens: 4096
|
|
9
193
|
};
|
|
10
|
-
var EXACT = /* @__PURE__ */ new Map([
|
|
11
|
-
// OpenAI family
|
|
12
|
-
[
|
|
13
|
-
"openai/gpt-4o",
|
|
14
|
-
{
|
|
15
|
-
supportsVision: true,
|
|
16
|
-
supportsStructuredOutput: true,
|
|
17
|
-
supportsToolUse: true,
|
|
18
|
-
supportsCacheControl: false,
|
|
19
|
-
maxContextTokens: 128e3,
|
|
20
|
-
maxOutputTokens: 16384
|
|
21
|
-
}
|
|
22
|
-
],
|
|
23
|
-
[
|
|
24
|
-
"openai/gpt-4o-mini",
|
|
25
|
-
{
|
|
26
|
-
supportsVision: true,
|
|
27
|
-
supportsStructuredOutput: true,
|
|
28
|
-
supportsToolUse: true,
|
|
29
|
-
supportsCacheControl: false,
|
|
30
|
-
maxContextTokens: 128e3,
|
|
31
|
-
maxOutputTokens: 16384
|
|
32
|
-
}
|
|
33
|
-
],
|
|
34
|
-
[
|
|
35
|
-
"openai/gpt-4-turbo",
|
|
36
|
-
{
|
|
37
|
-
supportsVision: true,
|
|
38
|
-
supportsStructuredOutput: false,
|
|
39
|
-
supportsToolUse: true,
|
|
40
|
-
supportsCacheControl: false,
|
|
41
|
-
maxContextTokens: 128e3,
|
|
42
|
-
maxOutputTokens: 4096
|
|
43
|
-
}
|
|
44
|
-
],
|
|
45
|
-
[
|
|
46
|
-
"openai/o1",
|
|
47
|
-
{
|
|
48
|
-
supportsVision: false,
|
|
49
|
-
supportsStructuredOutput: true,
|
|
50
|
-
supportsToolUse: true,
|
|
51
|
-
supportsCacheControl: false,
|
|
52
|
-
maxContextTokens: 2e5,
|
|
53
|
-
maxOutputTokens: 1e5
|
|
54
|
-
}
|
|
55
|
-
],
|
|
56
|
-
[
|
|
57
|
-
"openai/o3",
|
|
58
|
-
{
|
|
59
|
-
supportsVision: false,
|
|
60
|
-
supportsStructuredOutput: true,
|
|
61
|
-
supportsToolUse: true,
|
|
62
|
-
supportsCacheControl: false,
|
|
63
|
-
maxContextTokens: 2e5,
|
|
64
|
-
maxOutputTokens: 1e5
|
|
65
|
-
}
|
|
66
|
-
],
|
|
67
|
-
[
|
|
68
|
-
// GPT-4.1 — 1M-context flagship; multimodal + structured output (RADAR #92.a).
|
|
69
|
-
"openai/gpt-4.1",
|
|
70
|
-
{
|
|
71
|
-
supportsVision: true,
|
|
72
|
-
supportsStructuredOutput: true,
|
|
73
|
-
supportsToolUse: true,
|
|
74
|
-
supportsCacheControl: false,
|
|
75
|
-
maxContextTokens: 1047576,
|
|
76
|
-
maxOutputTokens: 32768
|
|
77
|
-
}
|
|
78
|
-
],
|
|
79
|
-
// Anthropic family
|
|
80
|
-
[
|
|
81
|
-
"anthropic/claude-opus-4",
|
|
82
|
-
{
|
|
83
|
-
supportsVision: true,
|
|
84
|
-
supportsStructuredOutput: false,
|
|
85
|
-
supportsToolUse: true,
|
|
86
|
-
supportsCacheControl: true,
|
|
87
|
-
maxContextTokens: 2e5,
|
|
88
|
-
maxOutputTokens: 32e3
|
|
89
|
-
}
|
|
90
|
-
],
|
|
91
|
-
[
|
|
92
|
-
"anthropic/claude-sonnet-4",
|
|
93
|
-
{
|
|
94
|
-
supportsVision: true,
|
|
95
|
-
supportsStructuredOutput: false,
|
|
96
|
-
supportsToolUse: true,
|
|
97
|
-
supportsCacheControl: true,
|
|
98
|
-
maxContextTokens: 2e5,
|
|
99
|
-
maxOutputTokens: 16e3
|
|
100
|
-
}
|
|
101
|
-
],
|
|
102
|
-
[
|
|
103
|
-
"anthropic/claude-3-5-sonnet",
|
|
104
|
-
{
|
|
105
|
-
supportsVision: true,
|
|
106
|
-
supportsStructuredOutput: false,
|
|
107
|
-
supportsToolUse: true,
|
|
108
|
-
supportsCacheControl: true,
|
|
109
|
-
maxContextTokens: 2e5,
|
|
110
|
-
maxOutputTokens: 8192
|
|
111
|
-
}
|
|
112
|
-
],
|
|
113
|
-
[
|
|
114
|
-
"anthropic/claude-3-5-sonnet-latest",
|
|
115
|
-
{
|
|
116
|
-
supportsVision: true,
|
|
117
|
-
supportsStructuredOutput: false,
|
|
118
|
-
supportsToolUse: true,
|
|
119
|
-
supportsCacheControl: true,
|
|
120
|
-
maxContextTokens: 2e5,
|
|
121
|
-
maxOutputTokens: 8192
|
|
122
|
-
}
|
|
123
|
-
],
|
|
124
|
-
[
|
|
125
|
-
"anthropic/claude-3-5-haiku-latest",
|
|
126
|
-
{
|
|
127
|
-
supportsVision: false,
|
|
128
|
-
supportsStructuredOutput: false,
|
|
129
|
-
supportsToolUse: true,
|
|
130
|
-
supportsCacheControl: true,
|
|
131
|
-
maxContextTokens: 2e5,
|
|
132
|
-
maxOutputTokens: 8192
|
|
133
|
-
}
|
|
134
|
-
],
|
|
135
|
-
[
|
|
136
|
-
"anthropic/claude-3-haiku",
|
|
137
|
-
{
|
|
138
|
-
supportsVision: true,
|
|
139
|
-
supportsStructuredOutput: false,
|
|
140
|
-
supportsToolUse: true,
|
|
141
|
-
supportsCacheControl: true,
|
|
142
|
-
maxContextTokens: 2e5,
|
|
143
|
-
maxOutputTokens: 4096
|
|
144
|
-
}
|
|
145
|
-
],
|
|
146
|
-
[
|
|
147
|
-
"anthropic/claude-3-opus",
|
|
148
|
-
{
|
|
149
|
-
supportsVision: true,
|
|
150
|
-
supportsStructuredOutput: false,
|
|
151
|
-
supportsToolUse: true,
|
|
152
|
-
supportsCacheControl: true,
|
|
153
|
-
maxContextTokens: 2e5,
|
|
154
|
-
maxOutputTokens: 4096
|
|
155
|
-
}
|
|
156
|
-
],
|
|
157
|
-
// Dot-form OpenRouter slugs theocode uses (RADAR #92.a). These are the same
|
|
158
|
-
// models as their dash-form siblings above; capability parity is intentional.
|
|
159
|
-
// Without these entries the dotted slugs fall through to the 4096 default
|
|
160
|
-
// (`anthropic/claude-3.5-sonnet` ≠ `anthropic/claude-3-5-sonnet`).
|
|
161
|
-
[
|
|
162
|
-
"anthropic/claude-opus-4.1",
|
|
163
|
-
{
|
|
164
|
-
supportsVision: true,
|
|
165
|
-
supportsStructuredOutput: false,
|
|
166
|
-
supportsToolUse: true,
|
|
167
|
-
supportsCacheControl: true,
|
|
168
|
-
maxContextTokens: 2e5,
|
|
169
|
-
maxOutputTokens: 32e3
|
|
170
|
-
}
|
|
171
|
-
],
|
|
172
|
-
[
|
|
173
|
-
"anthropic/claude-sonnet-4.5",
|
|
174
|
-
{
|
|
175
|
-
supportsVision: true,
|
|
176
|
-
supportsStructuredOutput: false,
|
|
177
|
-
supportsToolUse: true,
|
|
178
|
-
supportsCacheControl: true,
|
|
179
|
-
maxContextTokens: 2e5,
|
|
180
|
-
maxOutputTokens: 16e3
|
|
181
|
-
}
|
|
182
|
-
],
|
|
183
|
-
[
|
|
184
|
-
"anthropic/claude-3.5-sonnet",
|
|
185
|
-
{
|
|
186
|
-
supportsVision: true,
|
|
187
|
-
supportsStructuredOutput: false,
|
|
188
|
-
supportsToolUse: true,
|
|
189
|
-
supportsCacheControl: true,
|
|
190
|
-
maxContextTokens: 2e5,
|
|
191
|
-
maxOutputTokens: 8192
|
|
192
|
-
}
|
|
193
|
-
],
|
|
194
|
-
// Cheap OpenRouter slugs (RADAR #92.a) — previously fell to the 4096
|
|
195
|
-
// CONSERVATIVE default. toolUse on; vision/structuredOutput only for Gemini.
|
|
196
|
-
[
|
|
197
|
-
"qwen/qwen3-coder-30b-a3b-instruct",
|
|
198
|
-
{
|
|
199
|
-
supportsVision: false,
|
|
200
|
-
supportsStructuredOutput: false,
|
|
201
|
-
supportsToolUse: true,
|
|
202
|
-
supportsCacheControl: false,
|
|
203
|
-
maxContextTokens: 16e4,
|
|
204
|
-
maxOutputTokens: 8e3
|
|
205
|
-
}
|
|
206
|
-
],
|
|
207
|
-
[
|
|
208
|
-
"deepseek/deepseek-v4-flash",
|
|
209
|
-
{
|
|
210
|
-
supportsVision: false,
|
|
211
|
-
supportsStructuredOutput: false,
|
|
212
|
-
supportsToolUse: true,
|
|
213
|
-
supportsCacheControl: false,
|
|
214
|
-
maxContextTokens: 1048576,
|
|
215
|
-
maxOutputTokens: 8e3
|
|
216
|
-
}
|
|
217
|
-
],
|
|
218
|
-
[
|
|
219
|
-
"deepseek/deepseek-v3.2",
|
|
220
|
-
{
|
|
221
|
-
supportsVision: false,
|
|
222
|
-
supportsStructuredOutput: false,
|
|
223
|
-
supportsToolUse: true,
|
|
224
|
-
supportsCacheControl: false,
|
|
225
|
-
maxContextTokens: 131072,
|
|
226
|
-
maxOutputTokens: 8e3
|
|
227
|
-
}
|
|
228
|
-
],
|
|
229
|
-
[
|
|
230
|
-
"z-ai/glm-4.7-flash",
|
|
231
|
-
{
|
|
232
|
-
supportsVision: false,
|
|
233
|
-
supportsStructuredOutput: false,
|
|
234
|
-
supportsToolUse: true,
|
|
235
|
-
supportsCacheControl: false,
|
|
236
|
-
maxContextTokens: 202752,
|
|
237
|
-
maxOutputTokens: 8e3
|
|
238
|
-
}
|
|
239
|
-
],
|
|
240
|
-
[
|
|
241
|
-
"google/gemini-2.5-flash-lite",
|
|
242
|
-
{
|
|
243
|
-
supportsVision: true,
|
|
244
|
-
supportsStructuredOutput: true,
|
|
245
|
-
supportsToolUse: true,
|
|
246
|
-
supportsCacheControl: false,
|
|
247
|
-
maxContextTokens: 1048576,
|
|
248
|
-
maxOutputTokens: 8e3
|
|
249
|
-
}
|
|
250
|
-
],
|
|
251
|
-
[
|
|
252
|
-
"google/gemini-2.5-pro",
|
|
253
|
-
{
|
|
254
|
-
supportsVision: true,
|
|
255
|
-
supportsStructuredOutput: true,
|
|
256
|
-
supportsToolUse: true,
|
|
257
|
-
supportsCacheControl: false,
|
|
258
|
-
maxContextTokens: 1048576,
|
|
259
|
-
maxOutputTokens: 8e3
|
|
260
|
-
}
|
|
261
|
-
]
|
|
262
|
-
]);
|
|
263
194
|
var ROUTING_PREFIXES = ["openrouter/", "vertex/", "bedrock/"];
|
|
195
|
+
function capsFromCatalog(m) {
|
|
196
|
+
return {
|
|
197
|
+
supportsVision: m.modalities?.input?.includes("image") ?? m.attachment ?? false,
|
|
198
|
+
supportsStructuredOutput: m.structured_output ?? false,
|
|
199
|
+
supportsToolUse: m.tool_call ?? false,
|
|
200
|
+
supportsCacheControl: m.cache_control ?? false,
|
|
201
|
+
maxContextTokens: m.limit?.context ?? CONSERVATIVE_DEFAULTS.maxContextTokens,
|
|
202
|
+
maxOutputTokens: m.limit?.output ?? CONSERVATIVE_DEFAULTS.maxOutputTokens
|
|
203
|
+
};
|
|
204
|
+
}
|
|
264
205
|
function resolveModelCapabilities(modelId) {
|
|
265
206
|
const bare = stripVariantSuffix(stripRoutingPrefix(modelId));
|
|
266
|
-
const
|
|
267
|
-
if (
|
|
207
|
+
const fromIndex = getCatalogModelInfo(bare);
|
|
208
|
+
if (fromIndex !== void 0) return capsFromCatalog(fromIndex);
|
|
268
209
|
const withVendor = inferVendorPrefix(bare);
|
|
269
210
|
if (withVendor !== bare) {
|
|
270
|
-
const vendored =
|
|
271
|
-
if (vendored !== void 0) return vendored;
|
|
211
|
+
const vendored = getCatalogModelInfo(withVendor);
|
|
212
|
+
if (vendored !== void 0) return capsFromCatalog(vendored);
|
|
272
213
|
}
|
|
273
214
|
return CONSERVATIVE_DEFAULTS;
|
|
274
215
|
}
|
|
@@ -340,6 +281,759 @@ function toModelOption(modelId) {
|
|
|
340
281
|
};
|
|
341
282
|
}
|
|
342
283
|
|
|
343
|
-
|
|
284
|
+
// src/errors.ts
|
|
285
|
+
var TheokitAgentError = class extends Error {
|
|
286
|
+
name = "TheokitAgentError";
|
|
287
|
+
isRetryable;
|
|
288
|
+
code;
|
|
289
|
+
protoErrorCode;
|
|
290
|
+
metadata;
|
|
291
|
+
constructor(message, options = {}) {
|
|
292
|
+
super(message, options.cause !== void 0 ? { cause: options.cause } : void 0);
|
|
293
|
+
this.isRetryable = options.isRetryable ?? false;
|
|
294
|
+
if (options.code !== void 0) this.code = options.code;
|
|
295
|
+
if (options.protoErrorCode !== void 0) this.protoErrorCode = options.protoErrorCode;
|
|
296
|
+
if (options.metadata !== void 0) this.metadata = options.metadata;
|
|
297
|
+
}
|
|
298
|
+
};
|
|
299
|
+
var ConfigurationError = class extends TheokitAgentError {
|
|
300
|
+
name = "ConfigurationError";
|
|
301
|
+
constructor(message, options = {}) {
|
|
302
|
+
super(message, { ...options, isRetryable: false });
|
|
303
|
+
}
|
|
304
|
+
};
|
|
305
|
+
function isTransientError(err) {
|
|
306
|
+
return err instanceof TheokitAgentError && err.isRetryable === true;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// src/internal/runtime/retry/with-retry.ts
|
|
310
|
+
function defaultSleep(ms, signal) {
|
|
311
|
+
return new Promise((resolve, reject) => {
|
|
312
|
+
if (signal?.aborted) {
|
|
313
|
+
reject(signal.reason instanceof Error ? signal.reason : new Error("withRetry: aborted"));
|
|
314
|
+
return;
|
|
315
|
+
}
|
|
316
|
+
const timer = setTimeout(() => {
|
|
317
|
+
signal?.removeEventListener("abort", onAbort);
|
|
318
|
+
resolve();
|
|
319
|
+
}, ms);
|
|
320
|
+
function onAbort() {
|
|
321
|
+
clearTimeout(timer);
|
|
322
|
+
reject(signal?.reason instanceof Error ? signal.reason : new Error("withRetry: aborted"));
|
|
323
|
+
}
|
|
324
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
325
|
+
});
|
|
326
|
+
}
|
|
327
|
+
function resolveRetryOptions(options) {
|
|
328
|
+
const retries = options?.retries ?? 3;
|
|
329
|
+
if (!Number.isInteger(retries) || retries < 0) {
|
|
330
|
+
throw new ConfigurationError(
|
|
331
|
+
`withRetry: retries must be a non-negative integer, got ${retries}`,
|
|
332
|
+
{ code: "invalid_retry_config" }
|
|
333
|
+
);
|
|
334
|
+
}
|
|
335
|
+
return {
|
|
336
|
+
retries,
|
|
337
|
+
isRetryable: options?.isRetryable ?? isTransientError,
|
|
338
|
+
initialDelayMs: options?.initialDelayMs ?? 100,
|
|
339
|
+
maxDelayMs: options?.maxDelayMs ?? 3e4,
|
|
340
|
+
backoffMultiplier: options?.backoffMultiplier ?? 2,
|
|
341
|
+
rng: options?.rng ?? Math.random,
|
|
342
|
+
sleep: options?.sleep ?? defaultSleep,
|
|
343
|
+
signal: options?.signal
|
|
344
|
+
};
|
|
345
|
+
}
|
|
346
|
+
function backoffMs(cfg, attempt) {
|
|
347
|
+
const ceiling = Math.min(cfg.maxDelayMs, cfg.initialDelayMs * cfg.backoffMultiplier ** attempt);
|
|
348
|
+
return Math.floor(cfg.rng() * ceiling);
|
|
349
|
+
}
|
|
350
|
+
async function withRetry(fn, options) {
|
|
351
|
+
const cfg = resolveRetryOptions(options);
|
|
352
|
+
let attempt = 0;
|
|
353
|
+
for (; ; ) {
|
|
354
|
+
try {
|
|
355
|
+
return await fn();
|
|
356
|
+
} catch (err) {
|
|
357
|
+
if (attempt >= cfg.retries || !cfg.isRetryable(err)) throw err;
|
|
358
|
+
await cfg.sleep(backoffMs(cfg, attempt), cfg.signal);
|
|
359
|
+
attempt += 1;
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
// src/retry.ts
|
|
365
|
+
var Retry = class {
|
|
366
|
+
constructor() {
|
|
367
|
+
}
|
|
368
|
+
static create(fn, options) {
|
|
369
|
+
return withRetry(fn, options);
|
|
370
|
+
}
|
|
371
|
+
};
|
|
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
|
+
|
|
862
|
+
// src/internal/providers/catalog-source-models-dev.ts
|
|
863
|
+
var DEFAULT_URL = "https://models.dev/api.json";
|
|
864
|
+
var TTL_MS = 60 * 60 * 1e3;
|
|
865
|
+
var FETCH_TIMEOUT_MS = 1e4;
|
|
866
|
+
function cachePathFor(url) {
|
|
867
|
+
const base = process.env.THEOKIT_HOME?.trim() || join(homedir(), ".theokit");
|
|
868
|
+
const dir = join(base, "cache", "models-dev");
|
|
869
|
+
if (url === DEFAULT_URL) return join(dir, "api.json");
|
|
870
|
+
const hash = createHash("sha256").update(url).digest("hex").slice(0, 12);
|
|
871
|
+
return join(dir, `api-${hash}.json`);
|
|
872
|
+
}
|
|
873
|
+
function writeCacheAtomic(path, body) {
|
|
874
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
875
|
+
const tmp = `${path}.tmp-${randomBytes(6).toString("hex")}`;
|
|
876
|
+
try {
|
|
877
|
+
writeFileSync(tmp, body);
|
|
878
|
+
renameSync(tmp, path);
|
|
879
|
+
} catch (err) {
|
|
880
|
+
try {
|
|
881
|
+
unlinkSync(tmp);
|
|
882
|
+
} catch {
|
|
883
|
+
}
|
|
884
|
+
throw err;
|
|
885
|
+
}
|
|
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
|
+
}
|
|
918
|
+
function patchIndexFromApiJson(raw) {
|
|
919
|
+
if (typeof raw !== "object" || raw === null) return 0;
|
|
920
|
+
let patched = 0;
|
|
921
|
+
const skipped = [];
|
|
922
|
+
for (const [providerId, provider] of Object.entries(raw)) {
|
|
923
|
+
const models = provider?.models;
|
|
924
|
+
if (models === void 0 || typeof models !== "object") continue;
|
|
925
|
+
const keys = resolvePatchKeys(providerId);
|
|
926
|
+
if (keys === void 0) {
|
|
927
|
+
skipped.push(providerId);
|
|
928
|
+
continue;
|
|
929
|
+
}
|
|
930
|
+
for (const [modelId, rawModel] of Object.entries(models)) {
|
|
931
|
+
const parsed = catalogModelSchema.safeParse(rawModel);
|
|
932
|
+
if (!parsed.success) continue;
|
|
933
|
+
for (const key of keys) patchModelInfo(`${key}/${modelId}`, parsed.data);
|
|
934
|
+
patched++;
|
|
935
|
+
}
|
|
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
|
+
}
|
|
943
|
+
return patched;
|
|
944
|
+
}
|
|
945
|
+
function loadCacheIntoIndex(url = DEFAULT_URL) {
|
|
946
|
+
const path = cachePathFor(url);
|
|
947
|
+
let body;
|
|
948
|
+
try {
|
|
949
|
+
body = readFileSync(path, "utf-8");
|
|
950
|
+
} catch {
|
|
951
|
+
return 0;
|
|
952
|
+
}
|
|
953
|
+
let parsed;
|
|
954
|
+
try {
|
|
955
|
+
parsed = JSON.parse(body);
|
|
956
|
+
} catch {
|
|
957
|
+
try {
|
|
958
|
+
unlinkSync(path);
|
|
959
|
+
} catch {
|
|
960
|
+
}
|
|
961
|
+
process.stderr.write(`[theokit-sdk] WARN: corrupt models-dev cache deleted (${path})
|
|
962
|
+
`);
|
|
963
|
+
return 0;
|
|
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
|
+
}
|
|
974
|
+
}
|
|
975
|
+
async function refreshModelCatalog(opts = {}) {
|
|
976
|
+
registerBuiltins();
|
|
977
|
+
const kill = process.env.THEOKIT_DISABLE_MODELS_FETCH;
|
|
978
|
+
if (kill !== void 0 && kill !== "" && kill !== "0" && kill.toLowerCase() !== "false") {
|
|
979
|
+
return { source: "skipped", models: 0 };
|
|
980
|
+
}
|
|
981
|
+
const url = opts.url ?? process.env.THEOKIT_MODELS_URL ?? DEFAULT_URL;
|
|
982
|
+
const path = cachePathFor(url);
|
|
983
|
+
const now = opts.deps?.now ?? (() => Date.now());
|
|
984
|
+
if (opts.force !== true) {
|
|
985
|
+
try {
|
|
986
|
+
const age = now() - statSync(path).mtimeMs;
|
|
987
|
+
if (age < TTL_MS) {
|
|
988
|
+
return { source: "cache", models: loadCacheIntoIndex(url) };
|
|
989
|
+
}
|
|
990
|
+
} catch {
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
const fetchImpl = opts.deps?.fetch ?? fetch;
|
|
994
|
+
let body;
|
|
995
|
+
try {
|
|
996
|
+
const res = await Retry.create(
|
|
997
|
+
async () => {
|
|
998
|
+
const r = await fetchImpl(url, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
|
|
999
|
+
if (!r.ok) throw new Error(`HTTP ${r.status}`);
|
|
1000
|
+
return r;
|
|
1001
|
+
},
|
|
1002
|
+
// 2 transient retries with backoff (OpenCode does the same); every error here is worth one more try —
|
|
1003
|
+
// the whole call is already fail-closed at the caller.
|
|
1004
|
+
{ retries: 2, isRetryable: () => true, initialDelayMs: 200 }
|
|
1005
|
+
);
|
|
1006
|
+
body = await res.text();
|
|
1007
|
+
JSON.parse(body);
|
|
1008
|
+
} catch (err) {
|
|
1009
|
+
process.stderr.write(
|
|
1010
|
+
`[theokit-sdk] WARN: models-dev refresh failed (${err.message}) \u2014 serving existing data
|
|
1011
|
+
`
|
|
1012
|
+
);
|
|
1013
|
+
return { source: "cache", models: loadCacheIntoIndex(url) };
|
|
1014
|
+
}
|
|
1015
|
+
try {
|
|
1016
|
+
writeCacheAtomic(path, body);
|
|
1017
|
+
} catch (err) {
|
|
1018
|
+
process.stderr.write(
|
|
1019
|
+
`[theokit-sdk] WARN: models-dev cache write failed (${err.message})
|
|
1020
|
+
`
|
|
1021
|
+
);
|
|
1022
|
+
}
|
|
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
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
function getModelInfo(modelId) {
|
|
1034
|
+
return getCatalogModelInfo(modelId);
|
|
1035
|
+
}
|
|
1036
|
+
|
|
1037
|
+
export { getModelInfo, humanizeModelName, parseModelId, refreshModelCatalog, resolveModelCapabilities, toModelOption };
|
|
344
1038
|
//# sourceMappingURL=models.js.map
|
|
345
1039
|
//# sourceMappingURL=models.js.map
|