@stage-labs/metro 0.1.0-beta.220 → 0.1.0-beta.221
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/package.json +1 -1
- package/runtime/marketplace/plugin/.claude-plugin/plugin.json +1 -1
- package/runtime/node_modules/@metro-labs/daemon/src/gateway/codex.ts +9 -1
- package/runtime/node_modules/@metro-labs/daemon/src/gateway/effort.ts +17 -1
- package/runtime/node_modules/@metro-labs/daemon/src/gateway/gateway.ts +38 -9
- package/runtime/node_modules/@metro-labs/daemon/src/gateway/model-lists.ts +57 -0
- package/runtime/node_modules/@metro-labs/daemon/src/gateway/model-signin.ts +10 -1
- package/runtime/node_modules/@metro-labs/daemon/src/gateway/openrouter.ts +19 -3
- package/runtime/node_modules/@metro-labs/daemon/src/gateway/provider-models.ts +74 -22
- package/runtime/runtime.json +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "metro",
|
|
3
|
-
"version": "0.1.0-beta.
|
|
3
|
+
"version": "0.1.0-beta.221",
|
|
4
4
|
"description": "Metro for Claude Code, installed by the metro daemon on this machine: every connector the agent holds as its own MCP server relayed through the daemon, the orchestrator-only guard on the main thread, and the standing rules loaded at each session start. No vendor credential ever sits in a config file.",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "Bonustrack",
|
|
@@ -8,6 +8,7 @@ import { ToolNames, toResponsesRequest } from './codex-translate.js';
|
|
|
8
8
|
import { GatewayError, providerStatus, sendError, upstreamMessage, type Watch } from './forward.js';
|
|
9
9
|
import { parseEvent, SseParser, type SseEvent } from './frames.js';
|
|
10
10
|
import type { Connection } from './model-config.js';
|
|
11
|
+
import { listCache } from './model-lists.js';
|
|
11
12
|
import { answerWhole, currentOf, errorKind, reach, refreshed, relayTranslated, sessionHeader, type TokenSource, type TokenState } from './subscription.js';
|
|
12
13
|
import { noteUsageHeaders } from './usage.js';
|
|
13
14
|
|
|
@@ -25,6 +26,8 @@ export type CodexState = TokenState<CodexTokens>;
|
|
|
25
26
|
|
|
26
27
|
export const sharedCodexState: CodexState = new Map();
|
|
27
28
|
|
|
29
|
+
const codexLists = listCache<string>('codex');
|
|
30
|
+
|
|
28
31
|
const sourceOf = (deps: CodexDeps): TokenSource<CodexTokens> => ({
|
|
29
32
|
label: 'Codex',
|
|
30
33
|
stale: (tokens) => tokensStale(tokens),
|
|
@@ -109,7 +112,12 @@ export async function codexMessages(
|
|
|
109
112
|
|
|
110
113
|
export async function codexModels(tokens: CodexTokens, deps: Omit<CodexDeps, 'save'>): Promise<string[]> {
|
|
111
114
|
const version = await learnCodexVersion();
|
|
112
|
-
const
|
|
115
|
+
const base = deps.base ?? CODEX_BASE;
|
|
116
|
+
return codexLists.get(`${base}:${tokens.accountId}:${version}`, () => listCodex(tokens, version, base, deps.fetchImpl ?? fetch));
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async function listCodex(tokens: CodexTokens, version: string, base: string, fetchImpl: typeof fetch): Promise<string[]> {
|
|
120
|
+
const res = await fetchImpl(`${base}/models?client_version=${version}`, {
|
|
113
121
|
headers: { ...headersFor(tokens, randomUUID()), accept: 'application/json' },
|
|
114
122
|
redirect: 'manual',
|
|
115
123
|
});
|
|
@@ -64,12 +64,28 @@ export function effortToApply(body: Body): string | null {
|
|
|
64
64
|
export const cappedEffort = (effort: string): string => (ABOVE_HIGH.has(effort) ? 'high' : effort);
|
|
65
65
|
|
|
66
66
|
const THINKING_ALWAYS_ON = /claude-(fable|mythos)-5|claude-opus-5-5/;
|
|
67
|
+
const REFUSES_THINKING_OFF = '"thinking.type.disabled" is not supported';
|
|
68
|
+
const thinkingAlwaysOn = new Set<string>();
|
|
69
|
+
|
|
70
|
+
export const thinkingOff = (body: Body): boolean => record(body.thinking).type === 'disabled';
|
|
71
|
+
|
|
72
|
+
const alwaysThinks = (model: string): boolean => THINKING_ALWAYS_ON.test(model) || thinkingAlwaysOn.has(model);
|
|
67
73
|
|
|
68
74
|
export function withThinkingFor(body: Body, model: string): Body {
|
|
69
|
-
if (!
|
|
75
|
+
if (!alwaysThinks(model) || !thinkingOff(body)) return body;
|
|
70
76
|
return Object.fromEntries(Object.entries(body).filter(([key]) => key !== 'thinking'));
|
|
71
77
|
}
|
|
72
78
|
|
|
79
|
+
export function learnAlwaysThinks(model: string, refusal: string): boolean {
|
|
80
|
+
if (!refusal.includes(REFUSES_THINKING_OFF)) return false;
|
|
81
|
+
thinkingAlwaysOn.add(model);
|
|
82
|
+
return true;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function forgetLearnedThinking(): void {
|
|
86
|
+
thinkingAlwaysOn.clear();
|
|
87
|
+
}
|
|
88
|
+
|
|
73
89
|
export function withBlockBinding(body: Body): Body {
|
|
74
90
|
const thinking = body.thinking;
|
|
75
91
|
if (!isRecord(thinking) || thinking.block_binding !== undefined) return body;
|
|
@@ -9,8 +9,19 @@ import {
|
|
|
9
9
|
freshAdaptations,
|
|
10
10
|
type Adaptations,
|
|
11
11
|
} from './bedrock.js';
|
|
12
|
-
import { addBeta, anthropicHeaders, forwardedHeaders, GatewayError, parseJson, pipeResponse, readBody, sendError, watchUpstream } from './forward.js';
|
|
13
|
-
import {
|
|
12
|
+
import { addBeta, anthropicHeaders, forwardedHeaders, GatewayError, parseJson, pipeResponse, readBody, sendError, upstreamMessage, watchUpstream } from './forward.js';
|
|
13
|
+
import {
|
|
14
|
+
BINDING_BETA,
|
|
15
|
+
cappedEffort,
|
|
16
|
+
effortToApply,
|
|
17
|
+
forgetLearnedThinking,
|
|
18
|
+
learnAlwaysThinks,
|
|
19
|
+
plannedEffort,
|
|
20
|
+
thinkingOff,
|
|
21
|
+
withBlockBinding,
|
|
22
|
+
withEffort,
|
|
23
|
+
withThinkingFor,
|
|
24
|
+
} from './effort.js';
|
|
14
25
|
import { notReady, readModelConfig, resolveRoute, routeLabel, setCodexAuth, setGeminiAuth, writeModelConfig, type Connection, type ModelConfig, type Route } from './model-config.js';
|
|
15
26
|
import { codexMessages, sharedCodexState } from './codex.js';
|
|
16
27
|
import { geminiMessages, sharedGeminiState } from './gemini.js';
|
|
@@ -23,10 +34,10 @@ import { isRecord } from '@metro-labs/core/is-record';
|
|
|
23
34
|
import { forgetServed, noteServed } from './served.js';
|
|
24
35
|
import { forgetUsage, noteUsageHeaders, UsageScanner } from './usage.js';
|
|
25
36
|
import { fitToolSearch } from './tool-search.js';
|
|
37
|
+
import { ANTHROPIC_API, refreshLoginModels } from './provider-models.js';
|
|
26
38
|
import type { CodexTokens } from './codex-auth.js';
|
|
27
39
|
|
|
28
40
|
const GATEWAY_PREFIX = '/gateway';
|
|
29
|
-
const ANTHROPIC_BASE = 'https://api.anthropic.com';
|
|
30
41
|
const MESSAGES = '/v1/messages';
|
|
31
42
|
const COUNT = '/v1/messages/count_tokens';
|
|
32
43
|
const MODELS = '/v1/models';
|
|
@@ -49,6 +60,7 @@ export function resetGatewayState(): void {
|
|
|
49
60
|
forgetUsage();
|
|
50
61
|
learned.fields.clear();
|
|
51
62
|
learned.dropBetas = false;
|
|
63
|
+
forgetLearnedThinking();
|
|
52
64
|
sharedCodexState.clear();
|
|
53
65
|
sharedGeminiState.clear();
|
|
54
66
|
}
|
|
@@ -97,8 +109,9 @@ interface Payloads {
|
|
|
97
109
|
}
|
|
98
110
|
|
|
99
111
|
function anthropicPayloads(raw: Buffer, sent: Record<string, unknown>, shaped: Record<string, unknown>, model: string): Payloads {
|
|
100
|
-
const
|
|
101
|
-
const
|
|
112
|
+
const runnable = withThinkingFor(sent, model);
|
|
113
|
+
const rewrite = runnable !== sent || (typeof sent.model === 'string' && sent.model !== model);
|
|
114
|
+
const asSent = rewrite ? Buffer.from(JSON.stringify({ ...runnable, model })) : raw;
|
|
102
115
|
const bound = withBlockBinding(withThinkingFor(shaped, model));
|
|
103
116
|
if (bound === sent) return { metro: asSent, asSent: null, bound: false };
|
|
104
117
|
return { metro: Buffer.from(JSON.stringify(rewrite ? { ...bound, model } : bound)), asSent, bound: bound !== shaped };
|
|
@@ -115,6 +128,20 @@ async function asAnthropicWants(send: Send, base: Record<string, string>, payloa
|
|
|
115
128
|
return send(asSent, base);
|
|
116
129
|
}
|
|
117
130
|
|
|
131
|
+
async function refusedThinkingOff(upstream: Response, shaped: Record<string, unknown>, model: string): Promise<boolean> {
|
|
132
|
+
if (upstream.status !== 400 || !thinkingOff(shaped)) return false;
|
|
133
|
+
if (!learnAlwaysThinks(model, upstreamMessage(await upstream.clone().text(), ''))) return false;
|
|
134
|
+
await upstream.body?.cancel();
|
|
135
|
+
log.info({ model }, 'gateway: this model cannot run with thinking off, so metro leaves that setting out for it from now on');
|
|
136
|
+
return true;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function listLoginModels(req: IncomingMessage, anthropicBase: string): void {
|
|
140
|
+
refreshLoginModels(req.headers, anthropicBase).catch((err: unknown) => {
|
|
141
|
+
log.warn({ err: errMsg(err) }, 'gateway: could not list the models of the Claude Code login');
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
|
|
118
145
|
async function toAnthropic(
|
|
119
146
|
req: IncomingMessage,
|
|
120
147
|
res: ServerResponse,
|
|
@@ -125,7 +152,8 @@ async function toAnthropic(
|
|
|
125
152
|
deps: GatewayDeps,
|
|
126
153
|
): Promise<void> {
|
|
127
154
|
const conn = route.connection;
|
|
128
|
-
const
|
|
155
|
+
const anthropicBase = deps.anthropicBase ?? ANTHROPIC_API;
|
|
156
|
+
const url = `${anthropicBase}${(req.url ?? '').slice(GATEWAY_PREFIX.length)}`;
|
|
129
157
|
const key = conn.apiKey;
|
|
130
158
|
if (key === '' && standsInFor(req))
|
|
131
159
|
throw new GatewayError(
|
|
@@ -134,10 +162,13 @@ async function toAnthropic(
|
|
|
134
162
|
'Claude Code on this machine has no Anthropic login of its own; choose Bedrock, OpenRouter, Codex or Gemini on the Model page, or sign in on the Claude tab',
|
|
135
163
|
);
|
|
136
164
|
const watch = watchUpstream(res);
|
|
165
|
+
if (key === '') listLoginModels(req, anthropicBase);
|
|
137
166
|
const base = key === '' ? forwardedHeaders(req) : anthropicHeaders(req, key);
|
|
138
167
|
const send = (payload: Buffer, headers: Record<string, string>): Promise<Response> =>
|
|
139
168
|
fetch(url, { method: 'POST', headers, body: new Uint8Array(payload), signal: watch.signal, redirect: 'manual' });
|
|
140
|
-
const
|
|
169
|
+
const attempt = (): Promise<Response> => asAnthropicWants(send, base, anthropicPayloads(raw, sent, shaped, route.model), conn.label, route.model);
|
|
170
|
+
const first = await attempt();
|
|
171
|
+
const upstream = (await refusedThinkingOff(first, shaped, route.model)) ? await attempt() : first;
|
|
141
172
|
noteRefusal(conn.label, route.model, upstream);
|
|
142
173
|
noteUsageHeaders('anthropic', conn.id, upstream.headers);
|
|
143
174
|
const scanner = new UsageScanner(conn.id);
|
|
@@ -177,8 +208,6 @@ async function toOpenRouter(
|
|
|
177
208
|
await pipeResponse(upstream, res, watch, { keepalive: true, ownCredential: true, scanner: new UsageScanner(conn.id) });
|
|
178
209
|
}
|
|
179
210
|
|
|
180
|
-
const thinkingOff = (body: Record<string, unknown>): boolean => isRecord(body.thinking) && body.thinking.type === 'disabled';
|
|
181
|
-
|
|
182
211
|
function openrouterBody(body: Record<string, unknown>, model: string, zdr: boolean): Record<string, unknown> {
|
|
183
212
|
const sent: Record<string, unknown> = { ...body, model };
|
|
184
213
|
if (thinkingOff(body)) delete sent.thinking;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { errMsg, log } from '@metro-labs/core/log';
|
|
3
|
+
|
|
4
|
+
export const LIST_TTL_MS = 60 * 60_000;
|
|
5
|
+
export const RETRY_MS = 5 * 60_000;
|
|
6
|
+
|
|
7
|
+
export interface ListCache<T> {
|
|
8
|
+
get: (key: string, load: () => Promise<T[]>) => Promise<T[]>;
|
|
9
|
+
peek: (key: string) => T[] | null;
|
|
10
|
+
refresh: (key: string, load: () => Promise<T[]>) => Promise<void>;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const clears = new Set<() => void>();
|
|
14
|
+
|
|
15
|
+
export function listCache<T>(name: string, now: () => number = Date.now): ListCache<T> {
|
|
16
|
+
const kept = new Map<string, { at: number; list: T[] }>();
|
|
17
|
+
const tried = new Map<string, number>();
|
|
18
|
+
clears.add(() => {
|
|
19
|
+
kept.clear();
|
|
20
|
+
tried.clear();
|
|
21
|
+
});
|
|
22
|
+
const fresh = (key: string): boolean => {
|
|
23
|
+
const hit = kept.get(key);
|
|
24
|
+
return hit !== undefined && now() - hit.at < LIST_TTL_MS;
|
|
25
|
+
};
|
|
26
|
+
return {
|
|
27
|
+
async get(key, load) {
|
|
28
|
+
const hit = kept.get(key);
|
|
29
|
+
if (hit !== undefined && fresh(key)) return hit.list;
|
|
30
|
+
try {
|
|
31
|
+
const list = await load();
|
|
32
|
+
kept.set(key, { at: now(), list });
|
|
33
|
+
return list;
|
|
34
|
+
} catch (err) {
|
|
35
|
+
if (hit === undefined) throw err;
|
|
36
|
+
log.warn({ list: name, err: errMsg(err) }, 'model-lists: the provider would not list its models, so the last list it gave stands');
|
|
37
|
+
return hit.list;
|
|
38
|
+
}
|
|
39
|
+
},
|
|
40
|
+
peek: (key) => kept.get(key)?.list ?? null,
|
|
41
|
+
async refresh(key, load) {
|
|
42
|
+
if (fresh(key) || now() - (tried.get(key) ?? Number.NEGATIVE_INFINITY) < RETRY_MS) return;
|
|
43
|
+
tried.set(key, now());
|
|
44
|
+
try {
|
|
45
|
+
kept.set(key, { at: now(), list: await load() });
|
|
46
|
+
} catch (err) {
|
|
47
|
+
log.warn({ list: name, err: errMsg(err) }, 'model-lists: the provider would not list its models, so the last list it gave stands');
|
|
48
|
+
}
|
|
49
|
+
},
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function forgetModelLists(): void {
|
|
54
|
+
for (const clear of clears) clear();
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export const fingerprint = (...parts: string[]): string => createHash('sha256').update(parts.join('\n')).digest('hex').slice(0, 16);
|
|
@@ -11,6 +11,7 @@ import { onboard, parseGeminiProject } from './gemini-setup.js';
|
|
|
11
11
|
import { currentGeminiTokens, listGeminiModels, sharedGeminiState, type GeminiDeps } from './gemini.js';
|
|
12
12
|
import { openrouterCredits } from './openrouter.js';
|
|
13
13
|
import { lastServed } from './served.js';
|
|
14
|
+
import { listCache } from './model-lists.js';
|
|
14
15
|
import { geminiUsage, noteUsage, openrouterUsage, usageOf } from './usage.js';
|
|
15
16
|
import {
|
|
16
17
|
addConnection,
|
|
@@ -140,12 +141,20 @@ async function connectGemini(req: IncomingMessage, deps: ModelApiDeps, store: St
|
|
|
140
141
|
return saved(store, setGeminiAuth(cfg, id, full), 'model-api: Gemini connected', { connection: id, tier: onboarded.tier });
|
|
141
142
|
}
|
|
142
143
|
|
|
144
|
+
const geminiLists = listCache<string>('gemini');
|
|
145
|
+
|
|
146
|
+
async function geminiIds(req: IncomingMessage, deps: ModelApiDeps, store: Store): Promise<string[]> {
|
|
147
|
+
const conn = connectionFor(store.read(), req, 'gemini');
|
|
148
|
+
const key = `${deps.geminiBase ?? ''}:${conn.id}:${conn.gemini?.email ?? ''}:${conn.gemini?.project ?? ''}`;
|
|
149
|
+
return geminiLists.get(key, async () => (await geminiModelsOf(conn, deps, store)).map((m) => m.id));
|
|
150
|
+
}
|
|
151
|
+
|
|
143
152
|
export const GEMINI_ROUTES: Record<string, Route> = {
|
|
144
153
|
login: { method: 'POST', run: (_req, deps) => Promise.resolve(beginGeminiLogin(deps.geminiAuthBase)) },
|
|
145
154
|
code: { method: 'POST', run: connectGemini },
|
|
146
155
|
models: {
|
|
147
156
|
method: 'GET',
|
|
148
|
-
run: async (req, deps, store) => ({ models:
|
|
157
|
+
run: async (req, deps, store) => ({ models: await geminiIds(req, deps, store).catch(asApiError) }),
|
|
149
158
|
},
|
|
150
159
|
};
|
|
151
160
|
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { isRecord } from '@metro-labs/core/is-record';
|
|
2
2
|
import { GatewayError } from './forward.js';
|
|
3
|
+
import { listCache } from './model-lists.js';
|
|
3
4
|
import { stringOf } from '@metro-labs/http/api-http';
|
|
4
5
|
|
|
5
6
|
export const OPENROUTER_BASE = 'https://openrouter.ai/api';
|
|
@@ -13,6 +14,8 @@ export interface OpenRouterModel {
|
|
|
13
14
|
created: number | null;
|
|
14
15
|
}
|
|
15
16
|
|
|
17
|
+
const modelLists = listCache<OpenRouterModel>('openrouter');
|
|
18
|
+
const zdrLists = listCache<string>('openrouter-zdr');
|
|
16
19
|
|
|
17
20
|
function price(raw: unknown): number | null {
|
|
18
21
|
const value = typeof raw === 'string' ? Number(raw) : typeof raw === 'number' ? raw : Number.NaN;
|
|
@@ -23,8 +26,16 @@ function released(raw: unknown): number | null {
|
|
|
23
26
|
return typeof raw === 'number' && Number.isFinite(raw) && raw > 0 ? raw : null;
|
|
24
27
|
}
|
|
25
28
|
|
|
29
|
+
const strings = (value: unknown): string[] | null => (Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string') : null);
|
|
30
|
+
|
|
31
|
+
function chatCapable(entry: Record<string, unknown>): boolean {
|
|
32
|
+
const output = strings(isRecord(entry.architecture) ? entry.architecture.output_modalities : undefined);
|
|
33
|
+
const params = strings(entry.supported_parameters);
|
|
34
|
+
return (output === null || output.includes('text')) && (params === null || params.includes('tools'));
|
|
35
|
+
}
|
|
36
|
+
|
|
26
37
|
function modelOf(entry: unknown): OpenRouterModel | null {
|
|
27
|
-
if (!isRecord(entry)) return null;
|
|
38
|
+
if (!isRecord(entry) || !chatCapable(entry)) return null;
|
|
28
39
|
const id = stringOf(entry.id);
|
|
29
40
|
if (id === '') return null;
|
|
30
41
|
const pricing = isRecord(entry.pricing) ? entry.pricing : {};
|
|
@@ -42,7 +53,7 @@ function newestFirst(a: OpenRouterModel, b: OpenRouterModel): number {
|
|
|
42
53
|
return when !== 0 ? when : a.id.localeCompare(b.id);
|
|
43
54
|
}
|
|
44
55
|
|
|
45
|
-
|
|
56
|
+
async function listModels(base: string, fetchImpl: typeof fetch): Promise<OpenRouterModel[]> {
|
|
46
57
|
const res = await fetchImpl(`${base}/v1/models`, { headers: { accept: 'application/json' }, redirect: 'manual' });
|
|
47
58
|
if (!res.ok) throw new GatewayError(res.status, 'api_error', `OpenRouter would not list its models (${String(res.status)})`);
|
|
48
59
|
const body: unknown = await res.json();
|
|
@@ -55,6 +66,9 @@ export async function openrouterModels(base = OPENROUTER_BASE, fetchImpl: typeof
|
|
|
55
66
|
.slice(0, MODELS_MAX);
|
|
56
67
|
}
|
|
57
68
|
|
|
69
|
+
export const openrouterModels = (base = OPENROUTER_BASE, fetchImpl: typeof fetch = fetch): Promise<OpenRouterModel[]> =>
|
|
70
|
+
modelLists.get(base, () => listModels(base, fetchImpl));
|
|
71
|
+
|
|
58
72
|
export interface OpenRouterCredits {
|
|
59
73
|
total: number;
|
|
60
74
|
spent: number;
|
|
@@ -78,7 +92,7 @@ export async function openrouterCredits(
|
|
|
78
92
|
return { total, spent };
|
|
79
93
|
}
|
|
80
94
|
|
|
81
|
-
|
|
95
|
+
async function listZdr(base: string, fetchImpl: typeof fetch): Promise<string[]> {
|
|
82
96
|
const res = await fetchImpl(`${base}/v1/endpoints/zdr`, { headers: { accept: 'application/json' }, redirect: 'manual' });
|
|
83
97
|
if (!res.ok) throw new GatewayError(res.status, 'api_error', `OpenRouter would not list its zero data retention endpoints (${String(res.status)})`);
|
|
84
98
|
const body: unknown = await res.json();
|
|
@@ -88,3 +102,5 @@ export async function openrouterZdrModels(base = OPENROUTER_BASE, fetchImpl: typ
|
|
|
88
102
|
for (const entry of data) if (isRecord(entry) && stringOf(entry.model_id) !== '') ids.add(stringOf(entry.model_id));
|
|
89
103
|
return [...ids].sort();
|
|
90
104
|
}
|
|
105
|
+
|
|
106
|
+
export const openrouterZdrModels = (base = OPENROUTER_BASE, fetchImpl: typeof fetch = fetch): Promise<string[]> => zdrLists.get(base, () => listZdr(base, fetchImpl));
|
|
@@ -1,49 +1,102 @@
|
|
|
1
|
+
import type { IncomingHttpHeaders } from 'node:http';
|
|
1
2
|
import { isRecord } from '@metro-labs/core/is-record';
|
|
2
3
|
import { GatewayError } from './forward.js';
|
|
3
4
|
import type { Connection } from './model-config.js';
|
|
5
|
+
import { fingerprint, listCache } from './model-lists.js';
|
|
4
6
|
import { stringOf } from '@metro-labs/http/api-http';
|
|
5
7
|
|
|
6
|
-
const ANTHROPIC_API = 'https://api.anthropic.com';
|
|
8
|
+
export const ANTHROPIC_API = 'https://api.anthropic.com';
|
|
7
9
|
const ANTHROPIC_VERSION = '2023-06-01';
|
|
8
10
|
const LIST_MAX = 1000;
|
|
11
|
+
const LIST_TIMEOUT_MS = 10_000;
|
|
12
|
+
const OAUTH_BETA = 'oauth-2025-04-20';
|
|
13
|
+
const BEARER = 'Bearer ';
|
|
9
14
|
|
|
10
15
|
export interface ProviderModel {
|
|
11
16
|
id: string;
|
|
12
17
|
name: string;
|
|
13
18
|
}
|
|
14
19
|
|
|
20
|
+
interface Dated extends ProviderModel {
|
|
21
|
+
created: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
15
24
|
const KNOWN_CLAUDE: ProviderModel[] = [
|
|
16
|
-
{ id: 'claude-
|
|
25
|
+
{ id: 'claude-sonnet-5-5', name: 'Claude Sonnet 5.5' },
|
|
17
26
|
{ id: 'claude-opus-5-5', name: 'Claude Opus 5.5' },
|
|
27
|
+
{ id: 'claude-fable-5-1', name: 'Claude Fable 5.1' },
|
|
18
28
|
{ id: 'claude-opus-5', name: 'Claude Opus 5' },
|
|
19
29
|
{ id: 'claude-sonnet-5', name: 'Claude Sonnet 5' },
|
|
20
30
|
{ id: 'claude-haiku-4-5', name: 'Claude Haiku 4.5' },
|
|
21
31
|
];
|
|
22
32
|
|
|
33
|
+
const claudeLists = listCache<ProviderModel>('anthropic');
|
|
34
|
+
const bedrockLists = listCache<ProviderModel>('bedrock');
|
|
23
35
|
|
|
24
|
-
|
|
25
|
-
|
|
36
|
+
const newestFirst = (list: Dated[]): ProviderModel[] =>
|
|
37
|
+
list.sort((a, b) => b.created.localeCompare(a.created) || a.id.localeCompare(b.id)).map(({ id, name }) => ({ id, name }));
|
|
38
|
+
|
|
39
|
+
function claudeEntry(entry: unknown): Dated[] {
|
|
40
|
+
if (!isRecord(entry) || stringOf(entry.id) === '') return [];
|
|
41
|
+
const type = stringOf(entry.type);
|
|
42
|
+
if (type !== '' && type !== 'model') return [];
|
|
43
|
+
const id = stringOf(entry.id);
|
|
44
|
+
return [{ id, name: stringOf(entry.display_name) || id, created: stringOf(entry.created_at) }];
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async function listClaude(auth: Record<string, string>, what: string, base: string, fetchImpl: typeof fetch): Promise<ProviderModel[]> {
|
|
26
48
|
const res = await fetchImpl(`${base}/v1/models?limit=${String(LIST_MAX)}`, {
|
|
27
|
-
headers: {
|
|
49
|
+
headers: { ...auth, 'anthropic-version': ANTHROPIC_VERSION, accept: 'application/json' },
|
|
28
50
|
redirect: 'manual',
|
|
51
|
+
signal: AbortSignal.timeout(LIST_TIMEOUT_MS),
|
|
29
52
|
});
|
|
30
|
-
if (!res.ok) throw new GatewayError(res.status, 'api_error', `Anthropic would not list its models with
|
|
53
|
+
if (!res.ok) throw new GatewayError(res.status, 'api_error', `Anthropic would not list its models with ${what} (${String(res.status)})`);
|
|
31
54
|
const body: unknown = await res.json();
|
|
32
55
|
const data = isRecord(body) && Array.isArray(body.data) ? body.data : null;
|
|
33
56
|
if (data === null) throw new GatewayError(502, 'api_error', 'Anthropic answered with no model list');
|
|
34
|
-
return data
|
|
35
|
-
|
|
36
|
-
|
|
57
|
+
return newestFirst(data.flatMap(claudeEntry));
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const loginKey = (base: string): string => `login:${base}`;
|
|
61
|
+
|
|
62
|
+
const first = (value: string | string[] | undefined): string => (Array.isArray(value) ? value[0] : value)?.trim() ?? '';
|
|
63
|
+
|
|
64
|
+
function loginAuth(headers: IncomingHttpHeaders): Record<string, string> | null {
|
|
65
|
+
const bearer = first(headers.authorization);
|
|
66
|
+
if (bearer.startsWith(BEARER) && bearer.length > BEARER.length) return { authorization: bearer, 'anthropic-beta': OAUTH_BETA };
|
|
67
|
+
const key = first(headers['x-api-key']);
|
|
68
|
+
return key === '' ? null : { 'x-api-key': key };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function refreshLoginModels(headers: IncomingHttpHeaders, base = ANTHROPIC_API, fetchImpl: typeof fetch = fetch): Promise<void> {
|
|
72
|
+
const auth = loginAuth(headers);
|
|
73
|
+
if (auth === null) return Promise.resolve();
|
|
74
|
+
return claudeLists.refresh(loginKey(base), () => listClaude(auth, 'the Claude Code login', base, fetchImpl));
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export async function anthropicModels(settings: Connection, base = ANTHROPIC_API, fetchImpl: typeof fetch = fetch): Promise<ProviderModel[]> {
|
|
78
|
+
if (settings.apiKey === '') {
|
|
79
|
+
const live = claudeLists.peek(loginKey(base)) ?? [];
|
|
80
|
+
return live.length > 0 ? live : KNOWN_CLAUDE;
|
|
81
|
+
}
|
|
82
|
+
return claudeLists.get(`key:${base}:${fingerprint(settings.apiKey)}`, () => listClaude({ 'x-api-key': settings.apiKey }, 'the stored key', base, fetchImpl));
|
|
37
83
|
}
|
|
38
84
|
|
|
39
85
|
export const bedrockControlBase = (region: string): string => `https://bedrock.${region}.amazonaws.com`;
|
|
40
86
|
|
|
41
|
-
|
|
42
|
-
if (
|
|
43
|
-
|
|
44
|
-
const
|
|
87
|
+
function bedrockEntry(entry: unknown): Dated[] {
|
|
88
|
+
if (!isRecord(entry)) return [];
|
|
89
|
+
const id = stringOf(entry.inferenceProfileId);
|
|
90
|
+
const status = stringOf(entry.status);
|
|
91
|
+
if (id === '' || !id.includes('anthropic') || (status !== '' && status !== 'ACTIVE')) return [];
|
|
92
|
+
return [{ id, name: stringOf(entry.inferenceProfileName) || id, created: stringOf(entry.createdAt) }];
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
async function listBedrock(settings: Connection, base: string, fetchImpl: typeof fetch): Promise<ProviderModel[]> {
|
|
96
|
+
const res = await fetchImpl(`${base}/inference-profiles?maxResults=${String(LIST_MAX)}`, {
|
|
45
97
|
headers: { authorization: `Bearer ${settings.apiKey}`, accept: 'application/json' },
|
|
46
98
|
redirect: 'manual',
|
|
99
|
+
signal: AbortSignal.timeout(LIST_TIMEOUT_MS),
|
|
47
100
|
});
|
|
48
101
|
if (!res.ok)
|
|
49
102
|
throw new GatewayError(
|
|
@@ -54,13 +107,12 @@ export async function bedrockModels(settings: Connection, base?: string, fetchIm
|
|
|
54
107
|
const body: unknown = await res.json();
|
|
55
108
|
const list = isRecord(body) && Array.isArray(body.inferenceProfileSummaries) ? body.inferenceProfileSummaries : null;
|
|
56
109
|
if (list === null) throw new GatewayError(502, 'api_error', 'Bedrock answered with no inference profile list');
|
|
57
|
-
return list
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
.sort((a, b) => a.id.localeCompare(b.id));
|
|
110
|
+
return newestFirst(list.flatMap(bedrockEntry));
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export async function bedrockModels(settings: Connection, base?: string, fetchImpl: typeof fetch = fetch): Promise<ProviderModel[]> {
|
|
114
|
+
if (settings.region === '') throw new GatewayError(400, 'invalid_request_error', 'Bedrock needs a region before its models can be listed');
|
|
115
|
+
if (settings.apiKey === '') throw new GatewayError(400, 'invalid_request_error', 'Bedrock needs an API key before its models can be listed');
|
|
116
|
+
const from = base ?? bedrockControlBase(settings.region);
|
|
117
|
+
return bedrockLists.get(`${from}:${fingerprint(settings.apiKey)}`, () => listBedrock(settings, from, fetchImpl));
|
|
66
118
|
}
|
package/runtime/runtime.json
CHANGED