@link-assistant/router 0.0.0-stage → 1.25.6
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/README.md +35 -2
- package/catalog.json +68422 -0
- package/index.d.ts +5932 -0
- package/index.js +224 -0
- package/native.d.ts +106 -0
- package/package.json +61 -4
- package/portable/policy.mjs +117 -0
- package/schemas/accounts-list.v1.json +323 -0
- package/schemas/accounts-pause.v1.json +97 -0
- package/schemas/accounts-policy.v1.json +214 -0
- package/schemas/accounts-resume.v1.json +97 -0
- package/schemas/auth-claude.v1.json +97 -0
- package/schemas/auth-clear.v1.json +97 -0
- package/schemas/auth-codex.v1.json +97 -0
- package/schemas/auth-gh.v1.json +97 -0
- package/schemas/auth-import.v1.json +167 -0
- package/schemas/auth-status.v1.json +387 -0
- package/schemas/cli-error.v1.json +97 -0
- package/schemas/clients-backup-create.v1.json +97 -0
- package/schemas/clients-backup-list.v1.json +234 -0
- package/schemas/clients-backup-restore.v1.json +97 -0
- package/schemas/clients-backup-verify.v1.json +125 -0
- package/schemas/clients-doctor.v1.json +249 -0
- package/schemas/clients-install.v1.json +164 -0
- package/schemas/clients-list.v1.json +194 -0
- package/schemas/clients-reinstall.v1.json +164 -0
- package/schemas/clients-remove.v1.json +97 -0
- package/schemas/clients-repair.v1.json +109 -0
- package/schemas/clients-reset.v1.json +113 -0
- package/schemas/clients-setup.v1.json +97 -0
- package/schemas/clients-show.v1.json +191 -0
- package/schemas/clients-update.v1.json +164 -0
- package/schemas/configure.v1.json +97 -0
- package/schemas/contracts.v1.json +106 -0
- package/schemas/data-backup.v1.json +32 -0
- package/schemas/deploy.v1.json +546 -0
- package/schemas/doctor.v1.json +324 -0
- package/schemas/local-deployment.v1.json +364 -0
- package/schemas/logs-anomalies.v1.json +112 -0
- package/schemas/logs-show.v1.json +127 -0
- package/schemas/logs-summary.v1.json +129 -0
- package/schemas/model-catalog.v1.json +117 -0
- package/schemas/models-explain.v1.json +325 -0
- package/schemas/preservation.v1.json +47 -0
- package/schemas/providers-add.v1.json +185 -0
- package/schemas/providers-import.v1.json +97 -0
- package/schemas/providers-list.v1.json +182 -0
- package/schemas/providers-remove.v1.json +97 -0
- package/schemas/providers-show.v1.json +179 -0
- package/schemas/serve.v1.json +97 -0
- package/schemas/server-claim.v1.json +97 -0
- package/schemas/server-reap.v1.json +97 -0
- package/schemas/server-remove.v1.json +97 -0
- package/schemas/server-start.v1.json +97 -0
- package/schemas/server-status.v1.json +197 -0
- package/schemas/server-stop.v1.json +97 -0
- package/schemas/server-use.v1.json +97 -0
- package/schemas/staging.v1.json +47 -0
- package/schemas/tls-ca.v1.json +97 -0
- package/schemas/tls-generate.v1.json +97 -0
- package/schemas/tokens-expire.v1.json +97 -0
- package/schemas/tokens-import.v1.json +192 -0
- package/schemas/tokens-issue.v1.json +94 -0
- package/schemas/tokens-list.v1.json +272 -0
- package/schemas/tokens-recover-admin.v1.json +116 -0
- package/schemas/tokens-revoke.v1.json +97 -0
- package/schemas/tokens-rotate.v1.json +94 -0
- package/schemas/tokens-show.v1.json +269 -0
- package/schemas/tunnel-down.v1.json +97 -0
- package/schemas/tunnel-status.v1.json +165 -0
- package/schemas/tunnel-up.v1.json +97 -0
- package/schemas/usage.v1.json +621 -0
- package/schemas/verification.v1.json +254 -0
- package/schemas/verify.v1.json +338 -0
- package/schemas/version.v1.json +103 -0
- package/schemas/with.v1.json +105 -0
- package/src/accounts.mjs +233 -0
- package/src/activitypub.mjs +23 -0
- package/src/admin-assets.mjs +16 -0
- package/src/admin.mjs +108 -0
- package/src/affinities.mjs +180 -0
- package/src/affinity-schema-descriptor.mjs +2 -0
- package/src/affinity-schema.mjs +185 -0
- package/src/assets/admin/assets/app.js +1 -0
- package/src/assets/admin/assets/react.js +9 -0
- package/src/assets/admin/assets/rolldown-runtime.js +1 -0
- package/src/assets/admin/assets/ui-vendor.js +3 -0
- package/src/assets/admin/index.html +16 -0
- package/src/auth-service.mjs +149 -0
- package/src/claude-process-session.mjs +26 -0
- package/src/cli-output.mjs +21 -0
- package/src/cli.mjs +84 -0
- package/src/client-ca.mjs +8 -0
- package/src/client-catalog.mjs +52 -0
- package/src/client-codex-catalog.mjs +18 -0
- package/src/client-configure.mjs +72 -0
- package/src/client-files.mjs +82 -0
- package/src/client-global-repair.mjs +19 -0
- package/src/client-global-state.mjs +19 -0
- package/src/client-global.mjs +43 -0
- package/src/client-json.mjs +54 -0
- package/src/client-launch-plan.mjs +28 -0
- package/src/client-launch.mjs +35 -0
- package/src/client-persistent.mjs +66 -0
- package/src/client-process-profile.mjs +52 -0
- package/src/client-process-settings.mjs +36 -0
- package/src/client-process.mjs +44 -0
- package/src/client-profile-backup.mjs +29 -0
- package/src/client-remote-health.mjs +7 -0
- package/src/client-remote.mjs +55 -0
- package/src/client-run-credential.mjs +38 -0
- package/src/client-setup.mjs +97 -0
- package/src/client-status.mjs +102 -0
- package/src/client-toml-cst.mjs +71 -0
- package/src/client-transaction.mjs +48 -0
- package/src/codex-login.mjs +121 -0
- package/src/codex-loopback-transport.mjs +34 -0
- package/src/codex-loopback.mjs +60 -0
- package/src/config.mjs +198 -0
- package/src/core.mjs +198 -0
- package/src/credential-operations.mjs +119 -0
- package/src/doublets.mjs +157 -0
- package/src/emergency-auth.mjs +91 -0
- package/src/file-lock.mjs +107 -0
- package/src/gemini-protocol.mjs +133 -0
- package/src/geolocation.mjs +46 -0
- package/src/git-proxy.mjs +52 -0
- package/src/github-proxy.mjs +74 -0
- package/src/http-management.mjs +36 -0
- package/src/http-route-contract.mjs +479 -0
- package/src/index.mjs +4 -0
- package/src/local-router-discovery.mjs +31 -0
- package/src/managed-server.mjs +411 -0
- package/src/management-access.mjs +76 -0
- package/src/native-service.mjs +392 -0
- package/src/oauth.mjs +547 -0
- package/src/operation-input.mjs +20 -0
- package/src/operations.mjs +378 -0
- package/src/protocols.mjs +229 -0
- package/src/provider-manifest.mjs +46 -0
- package/src/provider-provision.mjs +24 -0
- package/src/remote-operations.mjs +166 -0
- package/src/request-log.mjs +99 -0
- package/src/resources.mjs +290 -0
- package/src/response-contracts.mjs +147 -0
- package/src/responses.mjs +103 -0
- package/src/routing.mjs +40 -0
- package/src/sensitive-data-sse.mjs +121 -0
- package/src/sensitive-data.mjs +254 -0
- package/src/server.mjs +552 -0
- package/src/storage.mjs +367 -0
- package/src/streams.mjs +232 -0
- package/src/token-import.mjs +68 -0
- package/src/token-reservation.mjs +8 -0
- package/src/tokens.mjs +172 -0
- package/src/usage.mjs +54 -0
- package/src/websocket-relay.mjs +131 -0
- package/testing.d.ts +7 -0
- package/testing.js +57 -0
package/src/server.mjs
ADDED
|
@@ -0,0 +1,552 @@
|
|
|
1
|
+
import { createServer } from 'node:http';
|
|
2
|
+
import {createServer as createHTTPSServer} from 'node:https';
|
|
3
|
+
import {lstat,readFile} from 'node:fs/promises';
|
|
4
|
+
import {join} from 'node:path';
|
|
5
|
+
import { Readable } from 'node:stream';
|
|
6
|
+
import { timingSafeEqual } from 'node:crypto';
|
|
7
|
+
import { ProtocolError, translateRequest, translateResponse, normalizeUsage, projectModels } from './protocols.mjs';
|
|
8
|
+
import { translateStream, monitorNativeStream } from './streams.mjs';
|
|
9
|
+
import { ResponsesStore, responseOwner, normalizeResponseInput } from './responses.mjs';
|
|
10
|
+
import { createNativeService,boundedBytes,isIngressNetworkHeader } from './native-service.mjs';
|
|
11
|
+
import {estimateRequestBudget} from './token-reservation.mjs';
|
|
12
|
+
import {retryableStatus} from './accounts.mjs';
|
|
13
|
+
import {managementOperation} from './http-management.mjs';
|
|
14
|
+
import {relayWebSocket} from './websocket-relay.mjs';
|
|
15
|
+
import {UsageTracker} from './usage.mjs';
|
|
16
|
+
import {activityResponse} from './activitypub.mjs';
|
|
17
|
+
import {githubConfiguration,relayGithub} from './github-proxy.mjs';
|
|
18
|
+
import {relayGit} from './git-proxy.mjs';
|
|
19
|
+
import {serveAdminAsset,hardenAdmin} from './admin-assets.mjs';
|
|
20
|
+
import {matchHTTPRoute,HTTP_ROUTES} from './http-route-contract.mjs';
|
|
21
|
+
import {isIP} from 'node:net';
|
|
22
|
+
import {NativeRequestLog} from './request-log.mjs';
|
|
23
|
+
import {isGeolocationHeader,sharesGeolocation,sanitizeGeolocation} from './geolocation.mjs';
|
|
24
|
+
import {createSensitiveDataProtection,opaqueSensitiveDataRoute,protectsSensitiveData} from './sensitive-data.mjs';
|
|
25
|
+
|
|
26
|
+
const JSON_HEADERS = { 'content-type': 'application/json; charset=utf-8' };
|
|
27
|
+
const json = (body, status = 200, headers = {}) => new Response(JSON.stringify(body), { status, headers: { ...JSON_HEADERS, ...headers } });
|
|
28
|
+
const redactedKeys = /(?:api[_-]?key|password|secret|authorization|credential|cookie|(?:access|refresh|id)[_-]?token|^token$)/i;
|
|
29
|
+
export function redact(value) {
|
|
30
|
+
if (Array.isArray(value)) return value.map(redact);
|
|
31
|
+
if (!value || typeof value !== 'object') return value;
|
|
32
|
+
return Object.fromEntries(Object.entries(value).map(([key, v]) => [key, redactedKeys.test(key) ? '[REDACTED]' : redact(v)]));
|
|
33
|
+
}
|
|
34
|
+
const equal = (a, b) => typeof a === 'string' && typeof b === 'string' && Buffer.byteLength(a) === Buffer.byteLength(b) && timingSafeEqual(Buffer.from(a), Buffer.from(b));
|
|
35
|
+
function socketPeer(peer) {
|
|
36
|
+
if(typeof peer !== 'string' || !isIP(peer))return undefined;
|
|
37
|
+
if(isIP(peer) === 4)return peer;
|
|
38
|
+
const normalized=new URL(`http://[${peer}]/`).hostname.slice(1,-1),mapped=/^::ffff:([a-f0-9]+):([a-f0-9]+)$/i.exec(normalized);
|
|
39
|
+
if(!mapped)return normalized;
|
|
40
|
+
const high=parseInt(mapped[1],16),low=parseInt(mapped[2],16);return `${high>>>8}.${high&255}.${low>>>8}.${low&255}`;
|
|
41
|
+
}
|
|
42
|
+
const bearer = headers => { const a = headers.get('authorization'); return a?.match(/^Bearer\s+(.+)$/i)?.[1] ?? headers.get('x-api-key'); };
|
|
43
|
+
const protocolOf = candidate => {
|
|
44
|
+
const value = candidate.protocol ?? candidate.provider?.protocol ?? candidate.provider?.type ?? candidate.provider;
|
|
45
|
+
if (['anthropic', 'messages'].includes(value)) return 'anthropic';
|
|
46
|
+
if (['responses', 'openai-responses', 'codex'].includes(value)) return 'responses';
|
|
47
|
+
if (['chat', 'openai', 'openai-compatible', 'openai_compatible'].includes(value)) return 'chat';
|
|
48
|
+
if (['gemini','vertex'].includes(value)) return 'gemini';
|
|
49
|
+
throw new ProtocolError(`Unsupported upstream protocol ${typeof value === 'string' ? value : 'unknown'}`, 501);
|
|
50
|
+
};
|
|
51
|
+
const paths = { chat: 'chat/completions', anthropic: 'messages', responses: 'responses' };
|
|
52
|
+
const serviceOf = path => /^\/api\/services\/(openai|anthropic|codex|qwen|gemini|vertex|bedrock)(?:\/|$)/.exec(path)?.[1];
|
|
53
|
+
function upstreamURL(base, protocol, endpointPath) {
|
|
54
|
+
let u; try { u = new URL(base); } catch { throw new ProtocolError('Provider base URL is invalid', 500); }
|
|
55
|
+
if (!['http:', 'https:'].includes(u.protocol) || u.username || u.password || u.search || u.hash) throw new ProtocolError('Provider base URL must be an HTTP(S) URL without credentials, query or fragment', 500);
|
|
56
|
+
if (endpointPath !== undefined) {
|
|
57
|
+
if (typeof endpointPath !== 'string' || !/^\/[a-zA-Z0-9/:_-]+$/.test(endpointPath) || endpointPath.startsWith('//')) throw new ProtocolError('Provider endpoint path is invalid', 500);
|
|
58
|
+
u.pathname = `${u.pathname.replace(/\/$/, '')}${endpointPath}`;
|
|
59
|
+
} else u.pathname = `${u.pathname.replace(/\/$/, '')}${/\/v1$/.test(u.pathname.replace(/\/$/, '')) ? '/' : '/v1/'}${paths[protocol]}`;
|
|
60
|
+
return u;
|
|
61
|
+
}
|
|
62
|
+
function upstreamHeaders(candidate, protocol, request, identityResponse = false) {
|
|
63
|
+
const headers = new Headers({ 'content-type': 'application/json', accept: 'application/json, text/event-stream' });
|
|
64
|
+
// Only operator-defined static headers are forwarded. Client credentials,
|
|
65
|
+
// cookies, proxy headers and browser origin never become upstream headers.
|
|
66
|
+
const forbidden = /^(?:authorization|x-api-key|x-goog-api-key|anthropic-auth-token|chatgpt-account-id|cookie|set-cookie|host|connection|content-length|content-encoding|transfer-encoding|upgrade|te|trailer|keep-alive|proxy-.*|forwarded|x-forwarded-.*|x-router-.*|x-link-assistant-.*)$/i;
|
|
67
|
+
const copies=new Set(['x-request-id','x-correlation-id','traceparent','tracestate','x-claude-code-session-id','x-codex-session-id','x-session-id','session-id']);
|
|
68
|
+
for (const [key, value] of Object.entries(candidate.headers ?? candidate.account?.headers ?? {})) {
|
|
69
|
+
if (forbidden.test(key) || isIngressNetworkHeader(key)) continue;
|
|
70
|
+
if (!sharesGeolocation(request.headers) && isGeolocationHeader(key)) continue;
|
|
71
|
+
if (typeof value !== 'string') continue;
|
|
72
|
+
if(value.startsWith('$')){const source=value.slice(1).toLowerCase();if(copies.has(source) && request.headers.has(source))headers.set(key,request.headers.get(source));}
|
|
73
|
+
else headers.set(key, value);
|
|
74
|
+
}
|
|
75
|
+
const key = candidate.apiKey ?? candidate.api_key ?? candidate.account?.api_key;
|
|
76
|
+
if (key) headers.set(protocol === 'anthropic' && candidate.auth_type !== 'oauth' ? 'x-api-key' : 'authorization', protocol === 'anthropic' && candidate.auth_type !== 'oauth' ? key : `Bearer ${key}`);
|
|
77
|
+
if (protocol === 'anthropic') headers.set('anthropic-version', '2023-06-01');
|
|
78
|
+
if (candidate.auth_type === 'oauth') {
|
|
79
|
+
for (const [key, value] of Object.entries(candidate.oauth_headers ?? {})) if (['anthropic-beta', 'anthropic-version', 'chatgpt-account-id', 'originator'].includes(key.toLowerCase()) && typeof value === 'string') headers.set(key, value);
|
|
80
|
+
}
|
|
81
|
+
const requestId = request.headers.get('x-request-id');
|
|
82
|
+
if (requestId && /^[a-zA-Z0-9._:-]{1,128}$/.test(requestId)) headers.set('x-request-id', requestId);
|
|
83
|
+
if (identityResponse) headers.set('accept-encoding','identity');
|
|
84
|
+
return headers;
|
|
85
|
+
}
|
|
86
|
+
function relayHeaders(upstream) {
|
|
87
|
+
const result = {};
|
|
88
|
+
for (const [key, value] of upstream.headers) if (/^(?:x-request-id|request-id|retry-after|x-ratelimit-[a-z_-]+|anthropic-ratelimit-[a-z_-]+)$/.test(key)) result[key] = value;
|
|
89
|
+
return result;
|
|
90
|
+
}
|
|
91
|
+
async function boundedJSON(request, maxBytes,objectOnly=true) {
|
|
92
|
+
if (!request.body) throw new ProtocolError('Request body is required');
|
|
93
|
+
const length = Number(request.headers.get('content-length'));
|
|
94
|
+
if (Number.isFinite(length) && length > maxBytes) throw new ProtocolError('Request body exceeds limit', 413);
|
|
95
|
+
const reader = request.body.getReader(); const parts = []; let total = 0;
|
|
96
|
+
try { while (true) { const { value, done } = await reader.read(); if (done) break; total += value.byteLength; if (total > maxBytes) { await reader.cancel(); throw new ProtocolError('Request body exceeds limit', 413); } parts.push(value); } }
|
|
97
|
+
finally { reader.releaseLock(); }
|
|
98
|
+
let value; try { value = JSON.parse(Buffer.concat(parts).toString('utf8')); } catch { throw new ProtocolError('Request body must contain valid JSON'); }
|
|
99
|
+
if (objectOnly && (!value || typeof value !== 'object' || Array.isArray(value))) throw new ProtocolError('Request body must be a JSON object');
|
|
100
|
+
return value;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** A native Web Request/Response router. All selection and state live in core. */
|
|
104
|
+
export function createNativeRouter(options = {}) {
|
|
105
|
+
const { core, authenticate, fetch: suppliedFetch = globalThis.fetch, clock = Date.now, maxBodyBytes = 4 * 1024 * 1024, maxResponseBytes = 32 * 1024 * 1024, timeoutMs = 120_000, maxAttempts = 3 } = options;
|
|
106
|
+
if (!core) throw new TypeError('createNativeRouter requires core; use startNativeServer to create one from configuration');
|
|
107
|
+
const tlsConfig = { ...core.config, ...options };
|
|
108
|
+
const useTLS=Boolean(tlsConfig.tls_self_signed || tlsConfig.tlsSelfSigned || tlsConfig.tls_cert || tlsConfig.tlsCert || tlsConfig.tls_key || tlsConfig.tlsKey || tlsConfig.https || tlsConfig.tls || (Array.isArray(tlsConfig.listeners) ? tlsConfig.listeners : Object.values(tlsConfig.listeners ?? {})).some(listener=>listener?.tls || listener?.https || listener?.protocol === 'https' || typeof listener === 'string' && listener.startsWith('https:')));
|
|
109
|
+
const privacy = createSensitiveDataProtection(options.env ?? core.env ?? process.env);
|
|
110
|
+
const responseStore = options.responseStore ?? new ResponsesStore({ clock, ...options.responseStoreOptions });
|
|
111
|
+
const logs = []; const counters = { requests: 0, failures: 0, upstream_attempts: 0, input_tokens: 0, output_tokens: 0 };
|
|
112
|
+
const peers=new WeakMap();
|
|
113
|
+
const requestLog=options.requestLog ?? core.requestLog ?? (core.config?.data_dir ? new NativeRequestLog({config:core.config,env:options.env ?? core.env ?? {},clock}):null);
|
|
114
|
+
if(requestLog && !core.requestLog)core.requestLog=requestLog;
|
|
115
|
+
const upstreamFetch=requestLog ? requestLog.fetch(suppliedFetch):suppliedFetch;
|
|
116
|
+
const listenerKind=options.listenerKind ?? (core.config?.inference_only ? 'inference-only':'combined');
|
|
117
|
+
let githubConfig;
|
|
118
|
+
let server;
|
|
119
|
+
const configuration = () => core.config ?? options.config ?? {};
|
|
120
|
+
const errorResponse = (error, protocol) => {
|
|
121
|
+
const status = error.status ?? 500;
|
|
122
|
+
const message = status >= 500 && !(error instanceof ProtocolError) ? 'Router request failed' : error.message;
|
|
123
|
+
return json(protocol === 'gemini' ? {error:{code:status,message,status:({400:'INVALID_ARGUMENT',401:'PERMISSION_DENIED',403:'PERMISSION_DENIED',404:'NOT_FOUND',429:'RESOURCE_EXHAUSTED',503:'UNAVAILABLE'})[status] ?? 'INTERNAL'}} : protocol === 'anthropic' ? { type: 'error', error: { type: status === 401 ? 'authentication_error' : status === 429 ? 'rate_limit_error' : 'api_error', message } } : { error: { message, type: status === 401 ? 'authentication_error' : status === 400 ? 'invalid_request_error' : 'api_error', code: error.code ?? null } }, status);
|
|
124
|
+
};
|
|
125
|
+
async function authorize(request, admin, model) {
|
|
126
|
+
if (authenticate) {
|
|
127
|
+
const claims = await authenticate(request, { admin, model });
|
|
128
|
+
if (!claims) throw new ProtocolError('Invalid or missing Router credential', 401);
|
|
129
|
+
if (admin && claims.admin !== true && claims.is_admin !== true) throw new ProtocolError('Administrator credential required', 403);
|
|
130
|
+
return claims;
|
|
131
|
+
}
|
|
132
|
+
const token = bearer(request.headers), config = configuration();
|
|
133
|
+
if(core.authenticate)return core.authenticate(token,{admin,model,headers:request.headers,listener:listenerKind,repository:request.headers.get('x-router-repository') ?? undefined});
|
|
134
|
+
const adminKey = config.admin_token ?? config.adminToken ?? config.api?.admin_token;
|
|
135
|
+
if (adminKey && equal(token, adminKey)) return { admin: true };
|
|
136
|
+
const clientKey = config.api_key ?? config.apiKey ?? config.client_token;
|
|
137
|
+
if (!admin && clientKey && equal(token, clientKey)) return { admin: false };
|
|
138
|
+
const claims = token && core.tokens?.validate ? await core.tokens.validate(token, { admin, model, repository: request.headers.get('x-router-repository') ?? undefined }) : null;
|
|
139
|
+
if (claims) return claims;
|
|
140
|
+
throw new ProtocolError(admin ? 'Administrator credential required' : 'Invalid or missing Router credential', 401);
|
|
141
|
+
}
|
|
142
|
+
function routingContext(request, claims) {
|
|
143
|
+
const path = new URL(request.url).pathname, service = serviceOf(path);
|
|
144
|
+
const client = typeof claims.client === 'string' ? claims.client : typeof claims.client_kind === 'string' ? claims.client_kind : undefined;
|
|
145
|
+
const pin = service ? configuration().services?.[service]?.provider : undefined;
|
|
146
|
+
if (pin !== undefined && (typeof pin !== 'string' || !pin)) throw new ProtocolError('Configured service provider pin is invalid', 500);
|
|
147
|
+
return { client, principalAccount: claims.account ?? undefined, provider: pin, service, path };
|
|
148
|
+
}
|
|
149
|
+
const nativeService = createNativeService({core,authorize,routingContext,fetch:upstreamFetch,maxBodyBytes,maxResponseBytes,timeoutMs,affinities:options.affinities ?? core.affinities,identityResponse:privacy !== null});
|
|
150
|
+
async function models(request, claims) {
|
|
151
|
+
if ((claims.sub ?? claims.id) && !claims.record && !(claims.label==='emergency-bypass' && claims.sub?.startsWith('emergency-bypass-'))) throw new ProtocolError('Durable model authority is unavailable', 403);
|
|
152
|
+
const context = routingContext(request, claims);
|
|
153
|
+
const value = core.catalogFor ? await core.catalogFor(context) : core.models ? await core.models() : configuration().models ?? [];
|
|
154
|
+
const list = Array.isArray(value) ? value : value?.data ?? Object.keys(value ?? {});
|
|
155
|
+
const allowed = claims.record?.model_policy?.allowed_models ?? [];
|
|
156
|
+
const filtered = list.map(m => typeof m === 'string' ? { id: m, object: 'model', created: 0, owned_by: 'router' } : { object: 'model', created: 0, owned_by: m.provider ?? 'router', ...m, id: m.id ?? m.name }).filter(m => (!allowed.length || allowed.includes(m.id)) && (!context.client || m.supported_clients?.includes(context.client)) && (!context.provider || (m.provider ?? m.owned_by) === context.provider) && (!context.principalAccount || core.catalogFor || m.account === context.principalAccount));
|
|
157
|
+
const seen = new Set();
|
|
158
|
+
for (const m of filtered) { if (seen.has(m.id)) throw new ProtocolError(`Exact model id '${m.id}' is advertised more than once`, 409); seen.add(m.id); }
|
|
159
|
+
return filtered;
|
|
160
|
+
}
|
|
161
|
+
async function management(request, path) {
|
|
162
|
+
const open=['/api/management/admin/status','/api/management/admin/bootstrap','/api/management/admin/bootstrap/confirm'].includes(path);
|
|
163
|
+
if(open) {const result=await managementOperation(core,request,path,request.body ? await boundedJSON(request,maxBodyBytes) : {});if(result === undefined)throw new ProtocolError('Route not found',404);return json(result);}
|
|
164
|
+
if(path.startsWith('/api/management/login') && configuration().login?.enabled === false)throw new ProtocolError('Route not found',404);
|
|
165
|
+
let adminClaims;
|
|
166
|
+
try {adminClaims = await authorize(request, true);}catch(error){error.managementAuthenticationFailure=true;throw error;}
|
|
167
|
+
core.managementAccess?.success(socketPeer(peers.get(request) ?? options.peer));
|
|
168
|
+
const method = request.method, body = ['POST', 'PATCH'].includes(method) ? request.body ? await boundedJSON(request, maxBodyBytes) : {} : undefined;
|
|
169
|
+
if(path === '/api/management/logs/errors' && method === 'GET')return json({enabled:Boolean(requestLog?.errorRoot),files:await requestLog?.errorFiles() ?? []});
|
|
170
|
+
const requestId=/^\/api\/management\/logs\/requests\/([^/]+)$/.exec(path);
|
|
171
|
+
if(requestId && method === 'GET'){const id=decodeURIComponent(requestId[1]),records=await requestLog?.lookup(id) ?? [];if(!records.length)throw new ProtocolError('request id is not retained',404);return json({id,records});}
|
|
172
|
+
const errorFile=/^\/api\/management\/logs\/errors\/([^/]+)$/.exec(path);
|
|
173
|
+
if(errorFile && method === 'GET'){if(!requestLog?.errorRoot)throw new ProtocolError('error capture is disabled',404);return new Response(await requestLog.readError(decodeURIComponent(errorFile[1])),{headers:{'content-type':'application/json','content-disposition':'attachment','cache-control':'no-store'}});}
|
|
174
|
+
if(path === '/api/management/logs' && method === 'DELETE'){if(!requestLog)throw new ProtocolError('Request log storage is unavailable',503);await requestLog.clear();return json({cleared:true});}
|
|
175
|
+
if(path === '/api/management/usage/queue' && method === 'GET'){if(!requestLog)throw new ProtocolError('Request tracking is unavailable',503);return json(requestLog.queueSnapshot([...core.accounts?.records?.keys() ?? ['primary']]));}
|
|
176
|
+
if(path === '/api/management/logging' && method === 'PATCH'){if(typeof body.debug!=='boolean' || Object.keys(body).some(key=>key!=='debug'))throw new ProtocolError('debug must be a boolean and unknown logging fields are not accepted');if(!core.logging?.set)throw new ProtocolError('runtime logging control is not installed',503);const specified=Number((options.env ?? core.env)?.LOG_DEBUG_TTL_SECS),ttl=Number.isSafeInteger(specified) && specified>=1 && specified<=86400 ? specified:300;await core.logging.set(body.debug,ttl);return json({debug:body.debug,ttl_secs:body.debug?ttl:0});}
|
|
177
|
+
const delegated=await managementOperation(core,request,path,body);if(delegated !== undefined)return json(delegated);
|
|
178
|
+
if (path === '/api/management/tokens' && method === 'GET') return json({ data: redact(await core.tokens.list()) });
|
|
179
|
+
if (['/api/management/tokens', '/api/management/tokens/client'].includes(path) && method === 'POST') {
|
|
180
|
+
const client = path.endsWith('/client');
|
|
181
|
+
const input = {...body,...(body.allowed_models ? {model_policy:{allowed_models:body.allowed_models,allow_substitution:body.allow_model_substitution ?? false,substitution_source:body.model_substitution_source ?? null}}:{}),...(client ? {scope:'',admin:false,account:'primary',principal_id:'primary'}:{})};
|
|
182
|
+
if (client && !body.client_kind) throw new ProtocolError('client_kind is required');
|
|
183
|
+
if (body.run_lease && !body.ephemeral) throw new ProtocolError('run_lease requires an ephemeral wrapper credential');
|
|
184
|
+
if(body.sliding_expiry)input.sliding_window_seconds=(body.ttl_hours ?? 24)*3600;
|
|
185
|
+
if(body.run_lease)input.run_lease_seconds=body.run_lease_seconds ?? 120;
|
|
186
|
+
const result = await core.tokens.issue(input);
|
|
187
|
+
return json({token:typeof result === 'string' ? result : result.token,ttl_hours:body.ttl_hours ?? 24,label:result.record?.label ?? body.label ?? '',...(client ? {client_kind:result.record?.client_kind ?? body.client_kind,principal_id:'primary',model_policy:result.record?.model_policy ?? input.model_policy ?? {}} : {account:body.account ?? null,max_requests:body.max_requests ?? null,max_tokens:body.max_tokens ?? null,rate_limit_per_minute:body.rate_limit_per_minute ?? null,scope:body.scope ?? ''})});
|
|
188
|
+
}
|
|
189
|
+
if (path === '/api/management/tokens/revoke' && method === 'POST') {const id=body.id ?? body.token_id;await core.tokens.revoke(id);return json({revoked:id});}
|
|
190
|
+
if (['/api/management/tokens/rotate','/api/management/tokens/rotate-client'].includes(path) && method === 'POST') {
|
|
191
|
+
const own = path.endsWith('/rotate'),id=own ? adminClaims.sub ?? adminClaims.id : body.id;
|
|
192
|
+
if(!id)throw new ProtocolError('Rotation requires an admin-scoped token; the flat admin key has no subject to revoke');
|
|
193
|
+
const held=await core.tokens.get(id);if(!held)throw new ProtocolError('Token not found',404);
|
|
194
|
+
if(!own && held.scope === 'admin')throw new ProtocolError('Use /api/management/tokens/rotate to rotate an admin credential');
|
|
195
|
+
const result=await core.tokens.rotate(id,body);return json({token:typeof result === 'string' ? result : result.token,revoked:id,...(own ? {ttl_hours:body.ttl_hours ?? 24,label:result.record?.label ?? body.label ?? held.label,scope:'admin'}:{})});
|
|
196
|
+
}
|
|
197
|
+
if (path === '/api/management/providers' && method === 'GET') {
|
|
198
|
+
const list = core.listProviders ? await core.listProviders() : core.providers?.list ? await core.providers.list() : configuration().providers ?? [];
|
|
199
|
+
return json({ data: redact(list) });
|
|
200
|
+
}
|
|
201
|
+
if (path === '/api/management/providers' && method === 'POST') {
|
|
202
|
+
const result = core.upsertProvider ? await core.upsertProvider(body) : core.providers?.upsert ? await core.providers.upsert(body) : undefined;
|
|
203
|
+
if (result === undefined) throw new ProtocolError('Provider mutation is not supported by this core', 501);
|
|
204
|
+
if(result == null)throw new ProtocolError('Provider not found',404);
|
|
205
|
+
return json(redact(result));
|
|
206
|
+
}
|
|
207
|
+
const provider = /^\/api\/management\/providers\/([^/]+)$/.exec(path);
|
|
208
|
+
if (provider && ['GET', 'DELETE'].includes(method)) {
|
|
209
|
+
const name = decodeURIComponent(provider[1]); let result;
|
|
210
|
+
if (method === 'GET') result = core.showProvider ? await core.showProvider(name) : await core.providers?.get?.(name);
|
|
211
|
+
else result = core.removeProvider ? await core.removeProvider(name) : await core.providers?.remove?.(name);
|
|
212
|
+
if (result === undefined) throw new ProtocolError('Provider operation is not supported by this core', 501);
|
|
213
|
+
if(result == null)throw new ProtocolError('Provider not found',404);
|
|
214
|
+
return json(method === 'DELETE' ? {deleted:name} : redact(result));
|
|
215
|
+
}
|
|
216
|
+
if (path === '/api/management/accounts' && method === 'GET') return json({ accounts: redact(core.listAccounts ? await core.listAccounts() : await core.accounts?.list?.() ?? []) });
|
|
217
|
+
const account = /^\/api\/management\/accounts\/([^/]+)\/(pause|resume|policy)$/.exec(path);
|
|
218
|
+
if (account) {
|
|
219
|
+
const name = decodeURIComponent(account[1]), action = account[2]; let result;
|
|
220
|
+
if (action === 'policy' && method === 'GET') {
|
|
221
|
+
result = core.accounts?.getPolicy ? await core.accounts.getPolicy(name) : core.accounts?.records?.has(name) ? { account: name, policy: structuredClone(core.accounts.records.get(name).policy) } : undefined;
|
|
222
|
+
}
|
|
223
|
+
else if (method === 'POST') result = core.accountAction ? await core.accountAction(name, action, body) : await core.accounts?.[action === 'policy' ? 'setPolicy' : action]?.(name, body);
|
|
224
|
+
if (result === undefined) throw new ProtocolError('Account operation is not supported by this core', 501);
|
|
225
|
+
return json(redact(action === 'policy' ? result.policy ?? result : result));
|
|
226
|
+
}
|
|
227
|
+
if (path === '/api/management/routing' && method === 'PATCH') {
|
|
228
|
+
const result = core.updateRouting ? await core.updateRouting(body) : undefined;
|
|
229
|
+
if (result === undefined) throw new ProtocolError('Routing mutation is not supported by this core', 501);
|
|
230
|
+
return json(redact(result));
|
|
231
|
+
}
|
|
232
|
+
if (path === '/api/management/routing/cooldown/reset' && method === 'POST') {
|
|
233
|
+
if (body.model && !body.account || body.account != null && (typeof body.account !== 'string' || !body.account.trim()) || body.model != null && (typeof body.model !== 'string' || !body.model.trim())) throw new ProtocolError('A model reset requires a nonempty account and model');
|
|
234
|
+
const result = body.account ? await core.resetCooldown?.(body.account, body.model) : await core.resetCooldowns?.();
|
|
235
|
+
if (result === undefined) throw new ProtocolError('Cooldown reset is not supported by this core', 501);
|
|
236
|
+
return json(result);
|
|
237
|
+
}
|
|
238
|
+
if (path === '/api/management/usage' && method === 'GET') return json({ ...counters });
|
|
239
|
+
throw new ProtocolError('Route not found', 404);
|
|
240
|
+
}
|
|
241
|
+
async function inference(request, source, body) {
|
|
242
|
+
if (typeof body.model !== 'string' || !body.model.trim()) throw new ProtocolError('model must be a nonempty string');
|
|
243
|
+
if (['chat','anthropic'].includes(source) && !Array.isArray(body.messages)) throw new ProtocolError('messages must be an array');
|
|
244
|
+
if (source === 'gemini' && !Array.isArray(body.contents)) throw new ProtocolError('contents must be an array');
|
|
245
|
+
if (source === 'responses' && typeof body.input !== 'string' && !Array.isArray(body.input)) throw new ProtocolError('input must be a string or array');
|
|
246
|
+
if (body.stream !== undefined && typeof body.stream !== 'boolean') throw new ProtocolError('stream must be a boolean');
|
|
247
|
+
if (source === 'responses') {
|
|
248
|
+
if (body.background || body.conversation || body.previous_response_id) throw new ProtocolError('Background, conversation and previous-response execution are not implemented by the native lifecycle store', 501);
|
|
249
|
+
if (body.store !== undefined && typeof body.store !== 'boolean') throw new ProtocolError('store must be a boolean');
|
|
250
|
+
}
|
|
251
|
+
for (const key of ['max_tokens', 'max_completion_tokens', 'max_output_tokens']) if (body[key] !== undefined && (!Number.isSafeInteger(body[key]) || body[key] < 1)) throw new ProtocolError(`${key} must be a positive integer`);
|
|
252
|
+
const claims = await authorize(request, false, body.model);
|
|
253
|
+
sanitizeGeolocation(body,sharesGeolocation(request.headers));
|
|
254
|
+
const retain = source === 'responses' && body.store !== false;
|
|
255
|
+
const namespace = new URL(request.url).pathname.match(/^\/api\/services\/(?:openai|codex|qwen)\/v1/)?.[0] ?? '/v1';
|
|
256
|
+
const owner = retain ? responseOwner(claims, bearer(request.headers)) : undefined;
|
|
257
|
+
const responseInput = retain ? normalizeResponseInput(body) : undefined;
|
|
258
|
+
let retainedId;
|
|
259
|
+
const context = { ...routingContext(request, claims), model: body.model, protocol: source, sessionKey: request.headers.get('x-router-session') ?? undefined, exclude: [] };
|
|
260
|
+
const candidates = core.candidates ? await core.candidates(context) : [await core.route(context)];
|
|
261
|
+
if (!candidates?.length) throw new ProtocolError('No eligible upstream account for this model', 503);
|
|
262
|
+
const reserve = estimateRequestBudget(body).total;
|
|
263
|
+
const tokenId = claims.sub ?? claims.id;
|
|
264
|
+
if (tokenId && core.tokens?.admit) {
|
|
265
|
+
const denial = await core.tokens.admit(tokenId, reserve);
|
|
266
|
+
if (typeof denial === 'string' && denial !== 'admitted' || denial === false) { const error = new ProtocolError(typeof denial === 'string' ? denial : 'Token budget exceeded', 429); error.code = typeof denial === 'string' ? denial : 'token_limit_exceeded'; throw error; }
|
|
267
|
+
}
|
|
268
|
+
let settled = false;
|
|
269
|
+
const settle = async usage => {
|
|
270
|
+
if (settled) return;
|
|
271
|
+
if (tokenId && core.tokens?.settle) await core.tokens.settle(tokenId, reserve, usage?.total ?? 0);
|
|
272
|
+
settled = true;
|
|
273
|
+
if (usage) { counters.input_tokens += usage.input; counters.output_tokens += usage.output; }
|
|
274
|
+
};
|
|
275
|
+
let finalError,finalResponse;
|
|
276
|
+
try {
|
|
277
|
+
const retryOverride=core.accounts?.records?.get(candidates[0].account)?.policy?.request_retry;
|
|
278
|
+
const principalBound=context.principalAccount && !['openai-compatible','openai','litellm','lefine','z.ai-coding-plan'].includes(candidates[0].kind ?? candidates[0].provider_kind);
|
|
279
|
+
const attemptLimit = context.pinnedAccount || principalBound || retryOverride===0 || configuration().account_failover === false && !(retryOverride>0) ? 1 : retryOverride!=null?retryOverride+1:Math.max(1, Math.min(100, maxAttempts));
|
|
280
|
+
for (const rawCandidate of candidates.slice(0, attemptLimit)) {
|
|
281
|
+
let candidate = rawCandidate;
|
|
282
|
+
try { candidate = core.prepareCandidate ? await core.prepareCandidate(rawCandidate) : rawCandidate; }
|
|
283
|
+
catch (error) { finalError = new ProtocolError('Upstream credential is unavailable', error.status ?? 502); await core.reportFailure?.(rawCandidate, { status: finalError.status, scope: 'account' }); continue; }
|
|
284
|
+
let protocol, payload;
|
|
285
|
+
try { protocol = protocolOf(candidate); payload = translateRequest(body, source, protocol, candidate.model ?? body.model); }
|
|
286
|
+
catch (error) { if (!(error instanceof ProtocolError)) throw error; finalError = error; continue; }
|
|
287
|
+
const controller = new AbortController(), abort = () => controller.abort(request.signal.reason);
|
|
288
|
+
core.accounts?.recordUse?.(candidate, context);
|
|
289
|
+
requestLog?.select(candidate.account);
|
|
290
|
+
request.signal.addEventListener('abort', abort, { once: true });
|
|
291
|
+
const timer = setTimeout(() => controller.abort(new Error('Upstream timeout')), timeoutMs); timer.unref?.();
|
|
292
|
+
let response;
|
|
293
|
+
try {
|
|
294
|
+
counters.upstream_attempts++;
|
|
295
|
+
let endpoint;
|
|
296
|
+
if (protocol === 'gemini') {
|
|
297
|
+
const base = candidate.baseUrl ?? candidate.base_url ?? candidate.provider?.base_url;
|
|
298
|
+
const {model:_model,stream:_stream,...native} = payload;
|
|
299
|
+
if (candidate.auth_type === 'oauth' || candidate.code_assist) {
|
|
300
|
+
endpoint = upstreamURL(base,protocol,`/v1internal:${body.stream ? 'streamGenerateContent' : 'generateContent'}`);
|
|
301
|
+
if(body.stream)endpoint.search='?alt=sse';
|
|
302
|
+
payload={model:(candidate.model ?? body.model).replace(/^models\//,''),request:native,...(candidate.project ? {project:candidate.project}:{})};
|
|
303
|
+
} else {
|
|
304
|
+
endpoint=new URL(base);endpoint.pathname=`${endpoint.pathname.replace(/\/$/,'')}${endpoint.pathname.endsWith('/v1beta') ? '' : '/v1beta'}/models/${encodeURIComponent((candidate.model ?? body.model).replace(/^models\//,''))}:${body.stream ? 'streamGenerateContent':'generateContent'}`;
|
|
305
|
+
if(body.stream)endpoint.search='?alt=sse';payload=native;
|
|
306
|
+
}
|
|
307
|
+
} else endpoint = upstreamURL(candidate.baseUrl ?? candidate.base_url ?? candidate.provider?.base_url, protocol, candidate.endpointPath);
|
|
308
|
+
response = await upstreamFetch(endpoint, { method: 'POST', headers: upstreamHeaders(candidate, protocol, request, privacy !== null), body: JSON.stringify(payload), signal: controller.signal, redirect: 'error' });
|
|
309
|
+
} catch (error) {
|
|
310
|
+
clearTimeout(timer); request.signal.removeEventListener('abort', abort);
|
|
311
|
+
if (request.signal.aborted) throw new ProtocolError('Client disconnected', 499);
|
|
312
|
+
await core.reportFailure?.(candidate, {scope:'account',message:'Upstream connection failed',reason:'transport'});
|
|
313
|
+
finalError = new ProtocolError('Upstream connection failed', 502); continue;
|
|
314
|
+
}
|
|
315
|
+
const cleanup = () => { clearTimeout(timer); request.signal.removeEventListener('abort', abort); };
|
|
316
|
+
if (!response.ok) {
|
|
317
|
+
const status = response.status,retryAfter = response.headers.get('retry-after');let bytes;try{bytes=await boundedBytes(response,maxResponseBytes);}catch(error){throw new ProtocolError('Upstream error response exceeds limit or could not be read',502);}finally{cleanup();}
|
|
318
|
+
const prefix=bytes.subarray(0,16384),message=Buffer.from(prefix).toString('utf8');
|
|
319
|
+
const disposition = await core.reportFailure?.(candidate, { status, retryAfter, scope: retryableStatus(status) ? 'account' : 'request',message,body:prefix,headers:response.headers });
|
|
320
|
+
finalError = new ProtocolError(`Upstream returned HTTP ${status}`, status); finalError.code = 'upstream_error';
|
|
321
|
+
const errorHeaders=relayHeaders(response);if(response.headers.has('content-type'))errorHeaders['content-type']=response.headers.get('content-type');
|
|
322
|
+
if(source===protocol)finalResponse=new Response(bytes,{status,headers:errorHeaders});
|
|
323
|
+
else {let value;try{value=JSON.parse(message);}catch{}finalError.message=value?.error?.message ?? value?.message ?? message ?? finalError.message;finalResponse=errorResponse(finalError,source);for(const [name,value] of Object.entries(errorHeaders))if(name!=='content-type')finalResponse.headers.set(name,value);}
|
|
324
|
+
if (!['relay','cooldown'].includes(disposition) && (retryableStatus(status) || disposition === 'retry-next')) continue;
|
|
325
|
+
await settle();return finalResponse;
|
|
326
|
+
}
|
|
327
|
+
const headers = relayHeaders(response);
|
|
328
|
+
if (body.stream) {
|
|
329
|
+
if (!response.headers.get('content-type')?.includes('text/event-stream') || !response.body) { cleanup(); await response.body?.cancel(); throw new ProtocolError('Upstream did not return an SSE stream', 502); }
|
|
330
|
+
let resourceCancelled = false;
|
|
331
|
+
const usageTracker=new UsageTracker({maxBytes:maxResponseBytes});
|
|
332
|
+
const measuredBody=response.body.pipeThrough(new TransformStream({transform(chunk,controller){usageTracker.feed(chunk);controller.enqueue(chunk);}}));
|
|
333
|
+
const measuredUsage = usage => ({...(usage ?? normalizeUsage()),total:Math.max(usage?.total ?? 0,usageTracker.finish().tokens)});
|
|
334
|
+
const callbacks = {
|
|
335
|
+
clock, model: body.model,
|
|
336
|
+
onStart: async response => { if (retain) { responseStore.save(namespace, owner, response, responseInput, { abort: () => { resourceCancelled = true; controller.abort(new Error('Response cancelled')); } }); retainedId = response.id; } },
|
|
337
|
+
onComplete: async state => {
|
|
338
|
+
cleanup(); await settle(measuredUsage(state.usage));
|
|
339
|
+
if (retain) {
|
|
340
|
+
if (!state.response || !['completed', 'incomplete'].includes(state.response.status)) throw new ProtocolError('Upstream stream did not supply a completed response resource', 502);
|
|
341
|
+
responseStore.save(namespace, owner, state.response, responseInput, { update: true });
|
|
342
|
+
}
|
|
343
|
+
await core.reportSuccess?.(candidate);
|
|
344
|
+
},
|
|
345
|
+
onError: async (_error, state) => { cleanup(); if (retain && retainedId) responseStore.fail(namespace, owner, retainedId); if (!resourceCancelled && !request.signal.aborted) await core.reportFailure?.(candidate, { status: 502 }); await settle(measuredUsage(state?.usage)); },
|
|
346
|
+
onCancel: async () => { cleanup(); controller.abort(); if (retain && retainedId) responseStore.fail(namespace, owner, retainedId); await settle(measuredUsage()); },
|
|
347
|
+
};
|
|
348
|
+
const stream = source === protocol ? monitorNativeStream(measuredBody, protocol, callbacks) : translateStream(measuredBody, protocol, source, body.model, callbacks);
|
|
349
|
+
return new Response(stream, { status: 200, headers: { ...headers, 'content-type': 'text/event-stream', 'cache-control': 'no-cache', 'x-accel-buffering': 'no' } });
|
|
350
|
+
}
|
|
351
|
+
let raw;
|
|
352
|
+
try { raw = await boundedJSON(response, maxResponseBytes); }
|
|
353
|
+
catch (error) { throw new ProtocolError(error.status === 413 ? 'Upstream response exceeds limit' : 'Upstream returned malformed JSON', 502); }
|
|
354
|
+
finally { cleanup(); }
|
|
355
|
+
const result = translateResponse(raw, protocol, source, body.model, clock());
|
|
356
|
+
const usage = normalizeUsage(protocol === 'gemini' ? (raw.response ?? raw).usageMetadata : raw.usage, protocol);
|
|
357
|
+
await core.reportSuccess?.(candidate); await settle(usage);
|
|
358
|
+
if (retain) responseStore.save(namespace, owner, result, responseInput);
|
|
359
|
+
return json(result, response.status, headers);
|
|
360
|
+
}
|
|
361
|
+
if(finalResponse){await settle();return finalResponse;}
|
|
362
|
+
throw finalError ?? new ProtocolError('All upstream accounts are unavailable', 503);
|
|
363
|
+
} catch (error) { await settle(); throw error; }
|
|
364
|
+
}
|
|
365
|
+
async function handle(request) {
|
|
366
|
+
// Local computed handlers use GET dispatch for HEAD, but a native relay
|
|
367
|
+
// must forward the original method as Rust's lifecycle/native handlers do.
|
|
368
|
+
const nativeRequest=request;
|
|
369
|
+
const incomingMethod=request.method;
|
|
370
|
+
const head=request.method === 'HEAD';
|
|
371
|
+
if(head){const original=request;request=new Request(original,{method:'GET'});if(peers.has(original))peers.set(request,peers.get(original));}
|
|
372
|
+
const path = new URL(request.url).pathname, service = serviceOf(path), source = service === 'gemini' || service === 'vertex' && !path.includes('/publishers/anthropic/') ? 'gemini' : service === 'anthropic' || service === 'bedrock' || path.includes('/publishers/anthropic/') || path.endsWith('/messages') ? 'anthropic' : path.endsWith('/responses') ? 'responses' : 'chat';
|
|
373
|
+
const adapter=path.startsWith('/api/v3/') || path==='/api/graphql' || path.startsWith('/git/');
|
|
374
|
+
const started = clock(); counters.requests++;
|
|
375
|
+
let response;
|
|
376
|
+
try {
|
|
377
|
+
const managementPath=path === '/api/management' || path.startsWith('/api/management/');
|
|
378
|
+
if(listenerKind === 'admin' && !managementPath)response=await serveAdminAsset(request,{directory:options.adminAssetDirectory});
|
|
379
|
+
else {
|
|
380
|
+
const privateService=path.startsWith('/api/services/activitypub/') || path.startsWith('/api/services/github/');
|
|
381
|
+
if(listenerKind === 'admin' && !managementPath || listenerKind === 'inference-only' && (managementPath || privateService || adapter) || listenerKind === 'github-adapter' && !adapter || listenerKind === 'combined' && adapter)throw new ProtocolError('Route not found',404);
|
|
382
|
+
if(configuration().enable_openai_api === false && ['openai','codex','qwen','gemini'].includes(service) || configuration().enable_anthropic_api === false && (service === 'anthropic' || service === 'bedrock' || path.includes('/publishers/anthropic/')))throw new ProtocolError('Route not found',404);
|
|
383
|
+
if(managementPath) {
|
|
384
|
+
const peer=socketPeer(peers.get(request) ?? options.peer);
|
|
385
|
+
if(!peer || !isIP(peer))throw new ProtocolError('management requires socket peer metadata',403);
|
|
386
|
+
const config=core.managementAccess?.config?.() ?? {allow_remote:configuration().management?.allow_remote};
|
|
387
|
+
if(listenerKind !== 'admin' && !config.allow_remote && peer !== '::1' && !peer.startsWith('127.'))throw new ProtocolError('remote management requires MANAGEMENT_ALLOW_REMOTE / --management-allow-remote or the admin listener',403);
|
|
388
|
+
const remaining=core.managementAccess?.check(peer);
|
|
389
|
+
if(remaining) {const error=new ProtocolError('management authentication temporarily locked for this client IP',429);error.retryAfter=remaining;throw error;}
|
|
390
|
+
if(!matchHTTPRoute(request.method,path) && HTTP_ROUTES.some(route=>matchHTTPRoute(route.method,path)))throw new ProtocolError('Method not allowed',405);
|
|
391
|
+
}
|
|
392
|
+
if (['/health', '/api/health'].includes(path) && request.method === 'GET'){response=new Response('ok',{headers:{'content-type':'text/plain; charset=utf-8'}});const until=core.emergency?.activeUntil();if(until)response.headers.set('x-link-assistant-emergency-auth',`active; expires_at=${until}`);}
|
|
393
|
+
else if(path === '/api/run-lease' && request.method === 'POST') {
|
|
394
|
+
const claims=await authorize(request,false);if(!core.tokens?.renewRunLease)throw new ProtocolError('This credential has no renewable live run lease',409);
|
|
395
|
+
response=json({run_lease_expires_at:await core.tokens.renewRunLease(claims.sub ?? claims.id)});
|
|
396
|
+
}
|
|
397
|
+
else if (path.startsWith('/api/management/')) response = await management(request, path);
|
|
398
|
+
else if(path.startsWith('/api/services/activitypub/')) {response=await activityResponse(request,configuration(),value=>boundedJSON(value,maxBodyBytes,false));if(!response)throw new ProtocolError('Route not found',404);}
|
|
399
|
+
else if(path.startsWith('/api/services/github/') || adapter) {
|
|
400
|
+
githubConfig ??= githubConfiguration(configuration(),options.env ?? core.env ?? {});
|
|
401
|
+
const config=await githubConfig;if(!config.token)throw new ProtocolError('Route not found',404);
|
|
402
|
+
const claims=await authorize(request,false),relay=path.startsWith('/git/') || path.startsWith('/api/services/github/git/') ? relayGit:relayGithub;
|
|
403
|
+
response=await relay(request,{config,claims,fetch:upstreamFetch,maxBodyBytes,maxResponseBytes,timeoutMs});
|
|
404
|
+
}
|
|
405
|
+
else if (path.startsWith('/api/services/gemini/v1beta/models') && request.method === 'GET') {
|
|
406
|
+
const claims=await authorize(request,false), entries=await models(request,claims);
|
|
407
|
+
const project = model => Object.fromEntries(Object.entries({name:model.id,...(model.raw ?? model)}).filter(([key])=>['name','baseModelId','version','displayName','description','inputTokenLimit','outputTokenLimit','supportedGenerationMethods','temperature','maxTemperature','topP','topK'].includes(key)));
|
|
408
|
+
if(path === '/api/services/gemini/v1beta/models')response=json({models:entries.map(project)});
|
|
409
|
+
else {const id=decodeURIComponent(path.slice('/api/services/gemini/v1beta/models/'.length));const found=entries.find(m=>m.id.replace(/^models\//,'') === id);if(!found)throw new ProtocolError('Model not found',404);response=json(project(found));}
|
|
410
|
+
}
|
|
411
|
+
else if ((service === 'gemini' || service === 'vertex' && !path.includes('/publishers/anthropic/')) && request.method === 'POST') {
|
|
412
|
+
const match=/\/models\/([^/]+):(generateContent|streamGenerateContent)$/.exec(path);if(!match)throw new ProtocolError('Route not found',404);
|
|
413
|
+
response=await inference(request,'gemini',{...await boundedJSON(request,maxBodyBytes),model:decodeURIComponent(match[1]),stream:match[2] === 'streamGenerateContent'});
|
|
414
|
+
}
|
|
415
|
+
else if (service === 'bedrock' || service === 'vertex' && path.includes('/publishers/anthropic/')) {
|
|
416
|
+
if(service === 'vertex' && !/\/publishers\/anthropic\/models\/[^/:]+(?:(?::(?:rawPredict|streamRawPredict))|(?:\/count-tokens:rawPredict))$/.test(path))throw new ProtocolError('Route not found',404);
|
|
417
|
+
response=await nativeService.fetch(nativeRequest);
|
|
418
|
+
}
|
|
419
|
+
else if (/^(?:\/v1|\/api\/services\/(?:openai|codex|qwen)\/v1)\/responses\/(?!compact$|input_tokens$)[^/]+(?:\/(?:cancel|input_items))?$/.test(path)) {
|
|
420
|
+
const match = /^(\/v1|\/api\/services\/(?:openai|codex|qwen)\/v1)\/responses\/([^/]+)(?:\/(cancel|input_items))?$/.exec(path);
|
|
421
|
+
const claims = await authorize(request, false), owner = responseOwner(claims, bearer(request.headers)), id = decodeURIComponent(match[2]);
|
|
422
|
+
let existing; try { existing = responseStore.get(match[1], owner, id); }
|
|
423
|
+
catch (error) { if (error.status !== 404 || !core.nativeCandidates) throw error; response = await nativeService.fetch(nativeRequest); }
|
|
424
|
+
if (existing) {
|
|
425
|
+
await authorize(request, false, existing.model);
|
|
426
|
+
if (!match[3] && request.method === 'GET') response = json(existing);
|
|
427
|
+
else if (!match[3] && request.method === 'DELETE') response = json(responseStore.delete(match[1], owner, id));
|
|
428
|
+
else if (match[3] === 'cancel' && request.method === 'POST') response = json(responseStore.cancel(match[1], owner, id));
|
|
429
|
+
else if (match[3] === 'input_items' && request.method === 'GET') response = json(responseStore.inputItems(match[1], owner, id, new URL(request.url).searchParams));
|
|
430
|
+
else throw new ProtocolError('Route not found', 404);
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
else if (['/v1/models', '/api/models', ...['openai','anthropic','codex','qwen'].map(service => `/api/services/${service}/v1/models`)].includes(path) && request.method === 'GET') {
|
|
434
|
+
const claims = await authorize(request, false); response = json(projectModels(await models(request, claims), source, new URL(request.url).searchParams));
|
|
435
|
+
}
|
|
436
|
+
else if (/^(?:\/v1|\/api\/services\/(?:openai|anthropic|codex|qwen)\/v1)\/models\/[^/]+$/.test(path) && request.method === 'GET') {
|
|
437
|
+
const id = decodeURIComponent(path.slice(path.lastIndexOf('/') + 1)), claims = await authorize(request, false);
|
|
438
|
+
if (!id || id.length > 512 || /[\/\x00-\x1f\x7f]/.test(id)) throw new ProtocolError('Model not found', 404);
|
|
439
|
+
const model = (await models(request, claims)).find(m => m.id === id);
|
|
440
|
+
if (!model) throw new ProtocolError('Model not found', 404);
|
|
441
|
+
const projected = projectModels([model], source).data[0]; if (source === 'anthropic') projected.display_name ??= id;
|
|
442
|
+
response = json(projected);
|
|
443
|
+
}
|
|
444
|
+
else if (['/v1/chat/completions', '/v1/messages', '/v1/responses', ...['openai','codex','qwen'].flatMap(service => [`/api/services/${service}/v1/responses`,`/api/services/${service}/v1/chat/completions`]), '/api/services/anthropic/v1/messages'].includes(path) && request.method === 'POST') {
|
|
445
|
+
const body = await boundedJSON(request.clone(),maxBodyBytes);
|
|
446
|
+
response = core.nativeCandidates && source === 'responses' && /^\/api\/services\/(?:openai|codex)\/v1\/responses$/.test(path) ? await nativeService.fetch(nativeRequest) : await inference(request,source,body);
|
|
447
|
+
}
|
|
448
|
+
else if (/^\/api\/services\/(?:openai|anthropic|codex|qwen)(?:\/|$)/.test(path)) response = await nativeService.fetch(nativeRequest);
|
|
449
|
+
else throw new ProtocolError('Route not found', 404);
|
|
450
|
+
}
|
|
451
|
+
} catch (error) {
|
|
452
|
+
counters.failures++;
|
|
453
|
+
if(error.managementAuthenticationFailure || path === '/api/management/admin/bootstrap/confirm' && error.status === 401) {
|
|
454
|
+
const peer=socketPeer(peers.get(request) ?? options.peer);
|
|
455
|
+
await core.managementAccess?.failure(peer);
|
|
456
|
+
const retryAfter=core.managementAccess?.check(peer);if(retryAfter){error=new ProtocolError('management authentication temporarily locked for this client IP',429);error.retryAfter=retryAfter;}
|
|
457
|
+
}
|
|
458
|
+
response=path.startsWith('/api/services/github/') || adapter ? json({message:error.message},error.status ?? 500) : errorResponse(error,source);
|
|
459
|
+
if(error.retryAfter)response.headers.set('retry-after',String(error.retryAfter));
|
|
460
|
+
}
|
|
461
|
+
if(path === '/api/management/admin/bootstrap/confirm' && response.ok)core.managementAccess?.success(socketPeer(peers.get(request) ?? options.peer));
|
|
462
|
+
if(listenerKind === 'admin')hardenAdmin(response);
|
|
463
|
+
if(head){await response.body?.cancel().catch(()=>{});response=new Response(null,{status:response.status,headers:response.headers});}
|
|
464
|
+
logs.push({ time: started, method: incomingMethod, path, status: response.status, duration_ms: clock() - started }); if (logs.length > 1000) logs.shift();
|
|
465
|
+
return response;
|
|
466
|
+
}
|
|
467
|
+
const router = {
|
|
468
|
+
core, responseStore, requestLog, fetch: dispatch, get address() { return server?.address(); },
|
|
469
|
+
async listen({ host = configuration().host ?? '127.0.0.1', port = configuration().port ?? 3000 } = {}) {
|
|
470
|
+
if (server) throw new Error('Router is already listening');
|
|
471
|
+
core.emergency?.checkListeners([host]);
|
|
472
|
+
let secureOptions;
|
|
473
|
+
if (useTLS) {
|
|
474
|
+
const certPath=tlsConfig.tls_cert ?? tlsConfig.tlsCert,keyPath=tlsConfig.tls_key ?? tlsConfig.tlsKey;
|
|
475
|
+
let certificate=certPath,key=keyPath;
|
|
476
|
+
if(tlsConfig.tls_self_signed || tlsConfig.tlsSelfSigned) {
|
|
477
|
+
if(certPath || keyPath)throw new ProtocolError('Self-signed TLS and explicit certificate paths cannot both be configured',500);
|
|
478
|
+
if(!tlsConfig.data_dir)throw new ProtocolError('Self-signed TLS requires a data directory',500);
|
|
479
|
+
await (await import('./resources.mjs')).executeResourceOperation({name:'tls.generate',options:{dns:tlsConfig.tls_dns_names ?? host},config:tlsConfig});
|
|
480
|
+
certificate=join(tlsConfig.data_dir,'tls','cert.pem');key=join(tlsConfig.data_dir,'tls','key.pem');
|
|
481
|
+
}
|
|
482
|
+
if(!certificate || !key)throw new ProtocolError('TLS requires both certificate and key paths',500);
|
|
483
|
+
const pem = async path => {const stat=await lstat(path);if(!stat.isFile() || stat.isSymbolicLink() || stat.size > 1024*1024)throw new ProtocolError('TLS PEM must be a regular file of at most 1 MiB',500);return readFile(path);};
|
|
484
|
+
secureOptions={cert:await pem(certificate),key:await pem(key)};
|
|
485
|
+
}
|
|
486
|
+
const serve = async (incoming, outgoing) => {
|
|
487
|
+
const controller = new AbortController(); incoming.on('aborted', () => controller.abort()); outgoing.on('close', () => { if (!outgoing.writableEnded) controller.abort(); });
|
|
488
|
+
try {
|
|
489
|
+
const headers = new Headers(); for (const [key, value] of Object.entries(incoming.headers)) if (value !== undefined) headers.set(key, Array.isArray(value) ? value.join(', ') : value);
|
|
490
|
+
const request = new Request(`${useTLS ? 'https':'http'}://${host.includes(':') ? `[${host}]` : host}:${server.address().port}${incoming.url}`, { method: incoming.method, headers, signal: controller.signal, ...(['GET', 'HEAD'].includes(incoming.method) ? {} : { body: Readable.toWeb(incoming), duplex: 'half' }) });
|
|
491
|
+
peers.set(request,incoming.socket.remoteAddress);
|
|
492
|
+
const result = await dispatch(request); outgoing.writeHead(result.status, Object.fromEntries(result.headers));
|
|
493
|
+
if (!result.body) outgoing.end(); else Readable.fromWeb(result.body).on('error', () => outgoing.destroy()).pipe(outgoing);
|
|
494
|
+
} catch { if (!outgoing.headersSent) outgoing.writeHead(500, JSON_HEADERS); outgoing.end(JSON.stringify({ error: { message: 'Router request failed' } })); }
|
|
495
|
+
};
|
|
496
|
+
server=useTLS ? createHTTPSServer(secureOptions,serve) : createServer(serve);
|
|
497
|
+
server.on('upgrade',(incoming,socket,head)=>{
|
|
498
|
+
if(!['combined','inference-only'].includes(listenerKind)){socket.end('HTTP/1.1 404 Not Found\r\nConnection: close\r\nContent-Length: 0\r\n\r\n');return;}
|
|
499
|
+
const headers=new Headers();for(const [name,value] of Object.entries(incoming.headers))if(value !== undefined)headers.set(name,Array.isArray(value)?value.join(', '):value);
|
|
500
|
+
const controller = new AbortController();
|
|
501
|
+
socket.once('close',() => controller.abort());
|
|
502
|
+
const request=new Request(`${useTLS?'https':'http'}://${host.includes(':')?`[${host}]`:host}:${server.address().port}${incoming.url}`,{headers,signal:controller.signal});
|
|
503
|
+
const target = async () => {
|
|
504
|
+
const url = new URL(request.url);
|
|
505
|
+
if (!privacy || !protectsSensitiveData(url.pathname)) return nativeService.websocketTarget(request);
|
|
506
|
+
await authorize(request,false);
|
|
507
|
+
if (opaqueSensitiveDataRoute(url.pathname) || url.searchParams.has('call_id')) throw new ProtocolError('Sensitive data protection cannot inspect direct media calls',415);
|
|
508
|
+
const policy = await privacy.protect(request,bearer(headers) ?? headers.get('x-goog-api-key'),maxBodyBytes,true);
|
|
509
|
+
return {...await nativeService.websocketTarget(policy.request),privacy:policy};
|
|
510
|
+
};
|
|
511
|
+
relayWebSocket(incoming,socket,head,{target,authorize:model=>authorize(request,false,model),core,maxMessageBytes:maxBodyBytes,timeoutMs:Math.min(timeoutMs,15000)}).catch(()=>socket.destroy());
|
|
512
|
+
});
|
|
513
|
+
try { await new Promise((resolve, reject) => { server.once('error', reject); server.listen(port, host, () => { server.off('error', reject); resolve(); }); }); }
|
|
514
|
+
catch (error) { server = undefined; throw error; }
|
|
515
|
+
return router;
|
|
516
|
+
},
|
|
517
|
+
async close() { responseStore.close?.(); if (!server) return; const current = server; server = undefined; if (!current.listening) return; await new Promise((resolve, reject) => { current.close(error => error ? reject(error) : resolve()); current.closeIdleConnections?.(); }); },
|
|
518
|
+
};
|
|
519
|
+
async function dispatch(request) {
|
|
520
|
+
async function run() {
|
|
521
|
+
const path = new URL(request.url).pathname;
|
|
522
|
+
const inference = listenerKind === 'combined' || listenerKind === 'inference-only';
|
|
523
|
+
let restore;
|
|
524
|
+
if (privacy && inference && protectsSensitiveData(path)) {
|
|
525
|
+
try {
|
|
526
|
+
await authorize(request,false);
|
|
527
|
+
if (opaqueSensitiveDataRoute(path)) throw new ProtocolError('Sensitive data protection cannot inspect direct media calls',415);
|
|
528
|
+
const protectedRequest = await privacy.protect(request,bearer(request.headers) ?? request.headers.get('x-goog-api-key'),maxBodyBytes);
|
|
529
|
+
if (peers.has(request)) peers.set(protectedRequest.request,peers.get(request));
|
|
530
|
+
request = protectedRequest.request;
|
|
531
|
+
restore = protectedRequest.restore;
|
|
532
|
+
} catch (error) {
|
|
533
|
+
const source = path.includes('/gemini/') || path.includes('/publishers/google/') ? 'gemini' :
|
|
534
|
+
path.includes('/anthropic/') || path.includes('/bedrock/') || path.includes('/publishers/anthropic/') || path.includes('/messages') ? 'anthropic' : 'chat';
|
|
535
|
+
return errorResponse(error,source);
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
const response = requestLog ? await requestLog.exchange(request,logged=>{
|
|
539
|
+
if (peers.has(request)) peers.set(logged,peers.get(request));
|
|
540
|
+
return handle(logged);
|
|
541
|
+
},{core}) : await handle(request);
|
|
542
|
+
return restore ? restore(response) : response;
|
|
543
|
+
}
|
|
544
|
+
return core.withAuthenticationScope ? core.withAuthenticationScope(run) : run();
|
|
545
|
+
}
|
|
546
|
+
return router;
|
|
547
|
+
}
|
|
548
|
+
export async function startNativeServer(options = {}) {
|
|
549
|
+
const core = options.core ?? await (await import('./core.mjs')).createRouterCore(options);
|
|
550
|
+
const router = createNativeRouter({ ...options, core });
|
|
551
|
+
return router.listen({ host: options.host, port: options.port });
|
|
552
|
+
}
|