@link-assistant/router 0.0.0-stage → 1.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +35 -2
- package/catalog.json +68542 -0
- package/index.d.ts +5932 -0
- package/index.js +224 -0
- package/native.d.ts +106 -0
- package/package.json +62 -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/runtime-config.mjs +133 -0
- package/src/runtime-payload.mjs +190 -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
|
@@ -0,0 +1,378 @@
|
|
|
1
|
+
/** Native operation dispatcher. This module never resolves or spawns a Rust executable. */
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import {executeCredentialOperation,credentialWithdrawal} from './credential-operations.mjs';
|
|
4
|
+
import {readNativeText} from './operation-input.mjs';
|
|
5
|
+
import {readTokenImportSource,importTokenRecords} from './token-import.mjs';
|
|
6
|
+
import { executeResourceOperation, supportedResourceOperations } from './resources.mjs';
|
|
7
|
+
import { executeAuthOperation } from './oauth.mjs';
|
|
8
|
+
import {CodexLogin} from './codex-login.mjs';
|
|
9
|
+
import {nativeCredentialStatus} from './auth-service.mjs';
|
|
10
|
+
import {nativeConfigOptions} from './config.mjs';
|
|
11
|
+
import {parseProviderImport} from './provider-manifest.mjs';
|
|
12
|
+
import {provisionLocalProvider,importLocalProviders} from './provider-provision.mjs';
|
|
13
|
+
import {parsePauseUntil} from './remote-operations.mjs';
|
|
14
|
+
import {clientIntegrations} from './client-files.mjs';
|
|
15
|
+
import {nativeClientStatus} from './client-status.mjs';
|
|
16
|
+
import {setupNativeClient,removeNativeClient} from './client-setup.mjs';
|
|
17
|
+
import { executeManagedOperation, supportedManagedOperations, selectedManagedTarget } from './managed-server.mjs';
|
|
18
|
+
import { executeRemoteOperation, remoteStateFamilies } from './remote-operations.mjs';
|
|
19
|
+
import Ajv2020 from 'ajv/dist/2020.js';
|
|
20
|
+
|
|
21
|
+
export const catalog = JSON.parse(readFileSync(new URL('../catalog.json', import.meta.url), 'utf8'));
|
|
22
|
+
export const version = catalog.version;
|
|
23
|
+
const sharedOptions = new Set(catalog.operations.find(operation=>operation.name==='version').options.map(option=>option.name));
|
|
24
|
+
export const operationNames = Object.freeze(catalog.operations.map(operation => operation.name));
|
|
25
|
+
const camel = value => value.replace(/[-_]([a-z])/g, (_, letter) => letter.toUpperCase());
|
|
26
|
+
const snake = value => value.replace(/[A-Z]/g, letter => '_' + letter.toLowerCase()).replaceAll('-', '_');
|
|
27
|
+
const validators = new Map();
|
|
28
|
+
const ajv = new Ajv2020({ strict: true, allowUnionTypes: true, validateFormats: false });
|
|
29
|
+
|
|
30
|
+
export class NativeRouterError extends Error {
|
|
31
|
+
constructor(message, { code = 'operation', result = null, cause } = {}) {
|
|
32
|
+
super(message, { cause });
|
|
33
|
+
this.name = 'NativeRouterError'; this.code = code; this.result = result;
|
|
34
|
+
this.exitCode = result?.exit_code ?? null; this.stderr = result?.diagnostics.join('\n') ?? '';
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
export function validateNativeResult(name, result) {
|
|
38
|
+
if (!validators.has(name)) {
|
|
39
|
+
const schema = JSON.parse(readFileSync(new URL(`../schemas/${name.replaceAll('.', '-')}.v1.json`, import.meta.url), 'utf8'));
|
|
40
|
+
validators.set(name, ajv.compile(schema));
|
|
41
|
+
}
|
|
42
|
+
if (!validators.get(name)(result)) throw new NativeRouterError(`Invalid ${name} contract: ${ajv.errorsText(validators.get(name).errors)}`, { code: 'schema', result });
|
|
43
|
+
return result;
|
|
44
|
+
}
|
|
45
|
+
export function operationResult(name, data, diagnostics = [], exitCode = 0) {
|
|
46
|
+
return validateNativeResult(name, {
|
|
47
|
+
schema: `link-assistant-router/${name.replaceAll('.', '-')}/v1`, operation: name,
|
|
48
|
+
success: exitCode === 0, exit_code: exitCode, data, diagnostics,
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
const output = (...lines) => ({ output: lines });
|
|
52
|
+
// with.v1 temporary-launch data is exactly the child status and captured streams;
|
|
53
|
+
// the direct launch API keeps its signal and note lines for local callers.
|
|
54
|
+
const withContractData = ({client_exit_code, stdout, stderr}) => ({client_exit_code, stdout, stderr});
|
|
55
|
+
const unsupported = message => { throw new NativeRouterError(message, { code: 'unsupported' }); };
|
|
56
|
+
export const nativeOperationSupport = Object.freeze({
|
|
57
|
+
...Object.fromEntries(Object.entries(supportedResourceOperations).map(([name, support]) => [name, support.status])),
|
|
58
|
+
...Object.fromEntries(Object.keys(supportedManagedOperations).map(name => [name, 'partial'])),
|
|
59
|
+
'auth.import': 'partial', 'auth.claude': 'partial', 'auth.codex': 'partial', 'auth.clear':'partial','auth.gh':'partial',
|
|
60
|
+
version: 'implemented', contracts: 'implemented', configure:'partial',with:'partial',
|
|
61
|
+
'accounts.list': 'partial', 'accounts.pause': 'partial', 'accounts.resume': 'partial', 'accounts.policy': 'partial',
|
|
62
|
+
'tokens.issue': 'partial', 'tokens.list': 'partial', 'tokens.show': 'partial', 'tokens.revoke': 'partial',
|
|
63
|
+
'tokens.import': 'partial', 'tokens.expire': 'partial', 'tokens.rotate': 'partial', 'tokens.recover-admin': 'partial',
|
|
64
|
+
'providers.list': 'partial', 'providers.show': 'partial', 'providers.add': 'partial', 'providers.remove': 'partial',
|
|
65
|
+
'providers.import': 'partial', 'models.explain': 'partial', serve: 'partial', doctor: 'partial', 'auth.status': 'partial',
|
|
66
|
+
'clients.list':'partial','clients.show':'partial','clients.setup':'partial','clients.remove':'partial',
|
|
67
|
+
});
|
|
68
|
+
function normalizeOptions(operation, options) {
|
|
69
|
+
const allowed = new Map(operation.options.map(option => [snake(option.name), option]));
|
|
70
|
+
const normalized = {};
|
|
71
|
+
for (const [key, value] of Object.entries(options)) {
|
|
72
|
+
if (value === undefined || value === null) continue;
|
|
73
|
+
const name = snake(key), option = allowed.get(name);
|
|
74
|
+
if (!option) throw new NativeRouterError(`Unknown ${operation.name} option: ${key}`, { code: 'options' });
|
|
75
|
+
// logs --token-id selects a hashed directory, never a bearer credential.
|
|
76
|
+
if (option.secret && !(operation.name.startsWith('logs.') && name==='token')) throw new NativeRouterError(`${key} is secret; use invocation env or stdin`, { code: 'secret-argv' });
|
|
77
|
+
if (option.boolean && typeof value !== 'boolean') throw new NativeRouterError(`${key} must be boolean`, { code: 'options' });
|
|
78
|
+
normalized[name] = value;
|
|
79
|
+
}
|
|
80
|
+
for (const option of operation.options) if (option.required && normalized[option.name] === undefined)
|
|
81
|
+
throw new NativeRouterError(`Missing ${operation.name} option: ${camel(option.name)}`, { code: 'options' });
|
|
82
|
+
return normalized;
|
|
83
|
+
}
|
|
84
|
+
function localOnly(options, accepted = []) {
|
|
85
|
+
const consumed = new Set(['local', ...nativeConfigOptions, ...accepted]);
|
|
86
|
+
for (const [name, value] of Object.entries(options)) {
|
|
87
|
+
if (value === false) continue;
|
|
88
|
+
if (!consumed.has(name)) unsupported(`Native local operation does not support ${name}; configure the native runtime explicitly or use the Rust wrapper`);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
function redactedProvider(provider) {
|
|
92
|
+
return {
|
|
93
|
+
name: provider.name, kind: provider.kind ?? 'openai-compatible', base_url: provider.base_url,
|
|
94
|
+
models: provider.models ?? [], supported_clients: provider.supported_clients ?? [],
|
|
95
|
+
has_encrypted_api_key: Boolean(provider.has_encrypted_api_key ?? provider.api_key),
|
|
96
|
+
enabled: provider.enabled !== false, intermediary_risk_acknowledged: Boolean(provider.intermediary_risk_acknowledged),
|
|
97
|
+
unsupported_clients: provider.unsupported_clients ?? [],
|
|
98
|
+
...Object.fromEntries(['api_key_env', 'default_model', 'subscriber_id'].filter(key => provider[key] !== undefined).map(key => [key, provider[key]])),
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
function tokenOptions(options) {
|
|
102
|
+
const result = {};
|
|
103
|
+
for (const key of ['ttl_hours', 'max_requests', 'max_tokens', 'rate_limit_per_minute']) {
|
|
104
|
+
if (options[key] === undefined) continue;
|
|
105
|
+
const number = Number(options[key]);
|
|
106
|
+
if (!Number.isSafeInteger(number) || number < 0 || (key === 'ttl_hours' && number === 0))
|
|
107
|
+
throw new NativeRouterError(`${key} must be a positive safe integer (limits may be zero)`, { code: 'options' });
|
|
108
|
+
result[key] = number;
|
|
109
|
+
}
|
|
110
|
+
for (const key of ['label', 'account']) if (options[key] !== undefined) result[key] = options[key];
|
|
111
|
+
if (options.admin) result.scope = 'admin';
|
|
112
|
+
if (options.github_repo) result.github_repos = Array.isArray(options.github_repo) ? options.github_repo : [options.github_repo];
|
|
113
|
+
if (options.allowed_model) result.model_policy = { allowed_models: Array.isArray(options.allowed_model) ? options.allowed_model : [options.allowed_model] };
|
|
114
|
+
return result;
|
|
115
|
+
}
|
|
116
|
+
const find = (records, key, value) => {
|
|
117
|
+
const record = records.find(record => record[key] === value);
|
|
118
|
+
if (!record) throw new NativeRouterError(`Unknown ${key}: ${value}`, { code: 'not-found' });
|
|
119
|
+
return record;
|
|
120
|
+
};
|
|
121
|
+
async function runtimeFor(router) {
|
|
122
|
+
router.corePromise ??= router.options.core ? Promise.resolve(router.options.core)
|
|
123
|
+
: import('./core.mjs').then(({ createRouterCore }) => createRouterCore(router.options));
|
|
124
|
+
return router.corePromise;
|
|
125
|
+
}
|
|
126
|
+
async function dispatch(router, name, options, invocation) {
|
|
127
|
+
if (name === 'version') { localOnly(options); return { version, source_commit: 'unknown' }; }
|
|
128
|
+
if (name === 'contracts') { localOnly(options); return catalog; }
|
|
129
|
+
const env = {...(router.options.env ?? process.env),...(invocation.env ?? {})};
|
|
130
|
+
if(['clients.list','clients.show'].includes(name)) {
|
|
131
|
+
for(const key of Object.keys(options)) if(!['home','local',...(name==='clients.show' ? ['client'] : [])].includes(key)) unsupported(`Client observation does not consume ${key}`);
|
|
132
|
+
if(invocation.deadlineMs!==undefined || invocation.maxOutputBytes!==undefined) unsupported('Client observation does not yet implement invocation deadline/output limits');
|
|
133
|
+
const context={home:options.home,env,cwd:invocation.cwd};
|
|
134
|
+
if(name==='clients.show') {
|
|
135
|
+
const row=await nativeClientStatus(options.client,context);
|
|
136
|
+
if(row.unreadable) {const error=new NativeRouterError(row.unreadable,{code:'client'});error.data=row;throw error;}return row;
|
|
137
|
+
}
|
|
138
|
+
const rows=[];for(const client of clientIntegrations) rows.push(await nativeClientStatus(client.client,context));
|
|
139
|
+
if(rows.some(row=>row.unreadable || row.conflicts.some(key=>key.endsWith(':invalid')))) {
|
|
140
|
+
const error=new NativeRouterError('One or more client configurations could not be read',{code:'client'});error.data=rows;throw error;
|
|
141
|
+
}
|
|
142
|
+
return rows;
|
|
143
|
+
}
|
|
144
|
+
if(['auth.status','auth.clear','auth.gh'].includes(name) || credentialWithdrawal(name,options)) {
|
|
145
|
+
const target=await selectedManagedTarget({name,options,config:router.options.config,env,cwd:invocation.cwd});
|
|
146
|
+
if(target) {
|
|
147
|
+
if(credentialWithdrawal(name,options))unsupported('Credential withdrawal removes local files and cannot clear a selected remote deployment; pass local to act on this machine');
|
|
148
|
+
return executeRemoteOperation({name,options,invocation,target,fetch:router.options.fetch});
|
|
149
|
+
}
|
|
150
|
+
const accepted=name==='auth.status' ? ['clear_all','yes'] : name==='auth.clear' ? ['provider','all','yes'] : name==='auth.gh' ? ['from_gh_config','token_stdin','status','clear'] : ['clear','home'];
|
|
151
|
+
localOnly(options,accepted);
|
|
152
|
+
const inherited=router.options.core ?? (router.corePromise ? await router.corePromise : undefined);
|
|
153
|
+
return executeCredentialOperation({name,options,invocation,routerOptions:{...router.options,...(inherited ? {core:inherited}:{})},env});
|
|
154
|
+
}
|
|
155
|
+
if (remoteStateFamilies.has(name.split('.')[0])) {
|
|
156
|
+
const target = await selectedManagedTarget({name,options,config:router.options.config,env,cwd:invocation.cwd});
|
|
157
|
+
if (target) return executeRemoteOperation({name,options,invocation,target,fetch:router.options.fetch});
|
|
158
|
+
}
|
|
159
|
+
if (!nativeOperationSupport[name]) unsupported(`Native operation ${name} is not implemented in this draft; use the explicit Rust Router wrapper`);
|
|
160
|
+
for (const key of ['deadlineMs','maxOutputBytes']) if (invocation[key] !== undefined && name !== 'auth.codex' && !(name==='with'&&!options.global&&!options.undo)) unsupported(`Native local per-invocation ${key} requires operation cancellation and output accounting`);
|
|
161
|
+
const configOverrides = Object.fromEntries(Object.entries(options).filter(([key])=>sharedOptions.has(key)));
|
|
162
|
+
for (const key of Object.keys(configOverrides)) if (!nativeConfigOptions.has(key)) unsupported(`Native configuration does not implement ${key}`);
|
|
163
|
+
if(name==='with'&&!options.global&&!options.undo)requestNativeRunModelPolicy(options.client,options);
|
|
164
|
+
const baseCore = await runtimeFor(router);let core = baseCore;
|
|
165
|
+
if (Object.keys(configOverrides).length || invocation.env || invocation.cwd) {
|
|
166
|
+
if (!baseCore.withConfig) unsupported('Injected runtime cannot apply an operation context');
|
|
167
|
+
core = (await (await import('./core.mjs')).createOperationContext(baseCore,{configOverrides,env,cwd:invocation.cwd,signal:invocation.signal})).core;
|
|
168
|
+
}
|
|
169
|
+
if (invocation.signal?.aborted) throw new NativeRouterError('Operation cancelled',{code:'cancelled'});
|
|
170
|
+
if(['configure','with'].includes(name)){localOnly(options,['client','all','undo','global','server','management_server','managed','token','token_stdin','ttl_hours','client_args',...(name==='with'?['non_interactive','interactive','extend_global_config','isolated_config','reset_to_default_configuration','yes','pick_model','model','allowed_models','allow_model_substitution','label','run_ttl_hours','fixed_run_ttl','run_max_requests']:[])]);if(name==='with'&&!options.global&&!options.undo){try{return withContractData(await executeNativeConfigure({name,options,invocation,core,env,fetch:router.options.fetch}));}catch(error){if(Number.isInteger(error?.data?.client_exit_code))error.data=withContractData(error.data);throw error;}}return executeNativeConfigure({name,options,invocation,core,env,fetch:router.options.fetch});}
|
|
171
|
+
if(['clients.setup','clients.remove'].includes(name)) {
|
|
172
|
+
localOnly(options,name==='clients.setup' ? ['client','token','token_stdin','base_url','management_server','ttl_hours'] : ['client','revoke_supplied','force']);
|
|
173
|
+
return (name==='clients.setup' ? setupNativeClient : removeNativeClient)({options,invocation,core,env,fetch:router.options.fetch});
|
|
174
|
+
}
|
|
175
|
+
if (supportedManagedOperations[name]) return executeManagedOperation({ name, options, invocation, core, config: core.config, env, routerOptions: router.options });
|
|
176
|
+
if (['auth.import', 'auth.claude', 'auth.codex'].includes(name)) {
|
|
177
|
+
const accepted = name === 'auth.import' ? ['provider', 'dir', 'home', 'if_absent', 'snapshot', 'follow']
|
|
178
|
+
: name === 'auth.claude' ? ['home', 'code', 'flow', 'mode', 'from_claude_home'] : ['home', 'from_codex_home'];
|
|
179
|
+
localOnly(options, [...accepted,...(name === 'auth.codex' ? ['flow','port'] : [])]);
|
|
180
|
+
if (name === 'auth.codex' && !options.from_codex_home) {
|
|
181
|
+
const login = await CodexLogin.begin({home:core.config.codex_home ?? env.CODEX_HOME ?? (await import('node:path')).join(core.config.data_dir,'codex'),manager:core.oauth,clock:core.clock,dataDir:core.config.data_dir,flow:options.flow,port:options.port,signal:invocation.signal,...(invocation.deadlineMs !== undefined ? {timeoutMs:invocation.deadlineMs} : {}),...router.options.oauth});
|
|
182
|
+
invocation.onProgress?.(`Open this URL:\n${login.authorizationURL()}${login.userCode ? `\nEnter this one-time code:\n${login.userCode}` : ''}`);
|
|
183
|
+
try {await login.wait();return output(`Codex authorization saved in ${login.home}`);}finally {await login.cancel();}
|
|
184
|
+
}
|
|
185
|
+
if (options.follow && options.snapshot) throw new NativeRouterError('follow and snapshot cannot be combined', { code: 'options' });
|
|
186
|
+
const data = await executeAuthOperation({ name, options, core, config: core.config, env, fetch: router.options.fetch,
|
|
187
|
+
clockSeconds: core.clock, oauth: router.options.oauth });
|
|
188
|
+
return name !== 'auth.import' && data.results ? output(`${name.slice(5)} credential ${data.results[0].outcome}.`) : data;
|
|
189
|
+
}
|
|
190
|
+
if (supportedResourceOperations[name]) {
|
|
191
|
+
localOnly(options, name.startsWith('logs.') ? ['correlation_id', 'token'] : name === 'tls.generate' ? ['dns'] : []);
|
|
192
|
+
return executeResourceOperation({ name, options, invocation, core, config: core.config });
|
|
193
|
+
}
|
|
194
|
+
if (name === 'accounts.list') {
|
|
195
|
+
localOnly(options); return { accounts: (await core.accounts.list()).map(account => ({
|
|
196
|
+
name: account.name, healthy: account.healthy ?? !account.paused,
|
|
197
|
+
paused: Boolean(account.limits?.pause && (account.limits.pause.until_unix == null || account.limits.pause.until_unix > core.clock())),
|
|
198
|
+
...(account.policy ? { routing_policy: account.policy } : {}),
|
|
199
|
+
...(account.limits?.pause ? { pause: account.limits.pause } : {}),
|
|
200
|
+
})) };
|
|
201
|
+
}
|
|
202
|
+
if (name === 'accounts.pause') {
|
|
203
|
+
localOnly(options, ['name', 'reason', 'until']);
|
|
204
|
+
const until=options.until!==undefined ? parsePauseUntil(options.until,core.clock()) : undefined;
|
|
205
|
+
await core.accounts.pause(options.name, { reason: options.reason, until_unix: until });
|
|
206
|
+
return output(`Paused account ${options.name}`);
|
|
207
|
+
}
|
|
208
|
+
if (name === 'accounts.resume') {
|
|
209
|
+
localOnly(options, ['name']); await core.accounts.resume(options.name); return output(`Resumed account ${options.name}`);
|
|
210
|
+
}
|
|
211
|
+
if (name === 'accounts.policy') {
|
|
212
|
+
localOnly(options, ['name', 'file']);
|
|
213
|
+
if (options.file) {
|
|
214
|
+
const policy = JSON.parse(await readNativeText(options.file,{cwd:invocation.cwd}));
|
|
215
|
+
// The canonical result schema validates policy before any state change.
|
|
216
|
+
operationResult(name, policy);
|
|
217
|
+
await core.accounts.policy(options.name, policy);
|
|
218
|
+
}
|
|
219
|
+
const account = find(await core.accounts.list(), 'name', options.name);
|
|
220
|
+
return account.policy ?? account.routing_policy ?? {};
|
|
221
|
+
}
|
|
222
|
+
if (name.startsWith('tokens.')) {
|
|
223
|
+
const tokens = core.tokens;
|
|
224
|
+
if (name === 'tokens.import') {
|
|
225
|
+
localOnly(options, ['from','ids','dry_run','replace']);
|
|
226
|
+
const source=await readTokenImportSource(options.from,{cwd:invocation.cwd,validateRecord:record=>operationResult('tokens.show',record)});
|
|
227
|
+
const report=await importTokenRecords({source,store:tokens.store,options,dataDir:core.config.data_dir,clock:core.clock});
|
|
228
|
+
if (report.conflicts.length || report.missing_from_source.length) {
|
|
229
|
+
const error = new NativeRouterError('Token import has unresolved conflicts or missing requested IDs', { code: 'import-conflict' });
|
|
230
|
+
error.data = report; error.exitCode = 2; throw error;
|
|
231
|
+
}
|
|
232
|
+
return report;
|
|
233
|
+
}
|
|
234
|
+
if (name === 'tokens.list') { localOnly(options); return await tokens.list(); }
|
|
235
|
+
if (name === 'tokens.show') { localOnly(options, ['id']); return find(await tokens.list(), 'id', options.id); }
|
|
236
|
+
if (['tokens.revoke', 'tokens.expire'].includes(name)) {
|
|
237
|
+
localOnly(options, ['id']); find(await tokens.list(), 'id', options.id);
|
|
238
|
+
await tokens[name.split('.')[1]](options.id); return output(`${name.split('.')[1]}: ${options.id}`);
|
|
239
|
+
}
|
|
240
|
+
const allowed = ['ttl_hours', 'label', 'account', 'max_requests', 'max_tokens', 'rate_limit_per_minute', 'admin', 'github_repo', 'allowed_model'];
|
|
241
|
+
if (name === 'tokens.issue') {
|
|
242
|
+
localOnly(options, allowed);
|
|
243
|
+
const issued = await tokens.issue(tokenOptions(options)); return { token: issued.token };
|
|
244
|
+
}
|
|
245
|
+
if (name === 'tokens.rotate') {
|
|
246
|
+
localOnly(options, ['id', ...allowed]); find(await tokens.list(), 'id', options.id);
|
|
247
|
+
const issued = await tokens.rotate(options.id, tokenOptions(options)); return { token: issued.token };
|
|
248
|
+
}
|
|
249
|
+
if (name === 'tokens.recover-admin') {
|
|
250
|
+
localOnly(options, ['ttl_hours', 'label', 'revoke_others']);
|
|
251
|
+
const admins = (await tokens.list()).filter(record => record.scope === 'admin' && !record.revoked);
|
|
252
|
+
const issued = await tokens.issue(tokenOptions({ ttl_hours: options.ttl_hours, label: options.label ?? 'recovered-admin', admin: true }));
|
|
253
|
+
const revoked = [];
|
|
254
|
+
if (options.revoke_others) for (const record of admins) { await tokens.revoke(record.id); revoked.push(record.id); }
|
|
255
|
+
return { recovered: true, token: issued.token, token_id: issued.id, retained_admins: options.revoke_others ? 0 : admins.length, revoked };
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
if (name.startsWith('providers.')) {
|
|
259
|
+
const providers = core.providers;
|
|
260
|
+
if (name === 'providers.list') { localOnly(options); return (await providers.list()).map(redactedProvider); }
|
|
261
|
+
if (name === 'providers.show') { localOnly(options, ['name']); return redactedProvider(find(await providers.list(), 'name', options.name)); }
|
|
262
|
+
if (name === 'providers.remove') {
|
|
263
|
+
localOnly(options, ['name']); find(await providers.list(), 'name', options.name); await providers.remove(options.name); return output(`Removed provider ${options.name}`);
|
|
264
|
+
}
|
|
265
|
+
if (name === 'providers.add') {
|
|
266
|
+
localOnly(options, ['name', 'kind', 'base_url', 'model', 'models', 'supported_clients', 'api_key_env', 'api_key_stdin', 'enabled', 'if_absent']);
|
|
267
|
+
const models = Array.isArray(options.models) ? options.models : options.models ? [options.models] : options.model ? [options.model] : [];
|
|
268
|
+
const apiKey = options.api_key_stdin ? String(invocation.stdin ?? '').trim() : undefined;
|
|
269
|
+
if (options.api_key_stdin && !apiKey) throw new NativeRouterError('api-key-stdin requires nonempty stdin', { code: 'options' });
|
|
270
|
+
const provider = { name: options.name, kind: options.kind ?? 'openai-compatible', base_url: options.base_url, models,
|
|
271
|
+
default_model: options.model, if_absent:options.if_absent ?? false, supported_clients: options.supported_clients ?? [],
|
|
272
|
+
api_key_env: options.api_key_env, ...(apiKey ? { api_key: apiKey } : {}), enabled: options.enabled ?? true };
|
|
273
|
+
return provisionLocalProvider(core,provider);
|
|
274
|
+
}
|
|
275
|
+
if (name === 'providers.import') {
|
|
276
|
+
localOnly(options, ['path']);
|
|
277
|
+
const records = parseProviderImport(await readNativeText(options.path,{cwd:invocation.cwd}));
|
|
278
|
+
const report = await importLocalProviders(core,records);
|
|
279
|
+
const data = output(JSON.stringify(report,null,2));
|
|
280
|
+
if (!report.complete) {
|
|
281
|
+
const error=new NativeRouterError('Provider import stopped after a rejected candidate',{code:'provider_acceptance'});
|
|
282
|
+
error.exitCode=1;error.data=data;throw error;
|
|
283
|
+
}
|
|
284
|
+
return data;
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
if (name === 'serve') {
|
|
288
|
+
localOnly(options, ['host', 'port']);
|
|
289
|
+
const port = options.port === undefined ? undefined : Number(options.port);
|
|
290
|
+
if (port !== undefined && (!Number.isInteger(port) || port < 0 || port > 65535)) throw new NativeRouterError('port must be in 0..65535', { code: 'options' });
|
|
291
|
+
const server = await router.listen({ host: options.host, port },core);
|
|
292
|
+
return output('Native server is listening');
|
|
293
|
+
}
|
|
294
|
+
if (name === 'models.explain') {
|
|
295
|
+
localOnly(options, ['id', 'client']);
|
|
296
|
+
const candidates = await core.candidates({ model: options.id });
|
|
297
|
+
const model = (await core.models()).find(model => model.id === options.id);
|
|
298
|
+
const healthy = [...new Set(candidates.map(candidate => candidate.provider?.name ?? candidate.provider).filter(name => typeof name === 'string'))];
|
|
299
|
+
const route = { protocols: ['openai-chat'], ...(model?.provider ? { provider: model.provider } : {}) };
|
|
300
|
+
return { contract_version: 1, requested_selector: options.id, selector_kind: 'concrete',
|
|
301
|
+
model_descriptor: { selector_kind: 'concrete', requested_selector: options.id, route, capabilities: {},
|
|
302
|
+
capability_provenance: { source: 'native-config', verified: false }, allow_substitution: false },
|
|
303
|
+
client_representation: { client: options.client ?? 'generic', advertisements: [] }, route_scope: route,
|
|
304
|
+
capability_provenance: { source: 'native-config', verified: false }, model_policy: { allow_substitution: false },
|
|
305
|
+
health: { healthy_providers: healthy, starting_providers: [], degraded_providers: [], degraded_reasons: {} },
|
|
306
|
+
routing: { state: candidates.length ? 'available' : 'unavailable', candidate_count: candidates.length, catalog_conflicts: [] },
|
|
307
|
+
output: ['Native local candidate inspection; live catalog capabilities and client advertisements are not implemented'] };
|
|
308
|
+
}
|
|
309
|
+
if (name === 'auth.status') {
|
|
310
|
+
localOnly(options);
|
|
311
|
+
return core.credentialStatus ? core.credentialStatus() : nativeCredentialStatus(core,{env,fetch:router.options.fetch,...router.options.oauth});
|
|
312
|
+
}
|
|
313
|
+
if (name === 'doctor') {
|
|
314
|
+
localOnly(options);
|
|
315
|
+
const config = core.config ?? router.options.config ?? {};
|
|
316
|
+
return { status: 'partial', version, checks: [{ name: 'native-runtime', state: 'ok' }, { name: 'subscription-auth', state: 'unverified', detail: 'OAuth discovery and provider verification are not implemented' }],
|
|
317
|
+
providers: [], deployments: [], recommended_models: [], data_dir: config.data_dir ?? '',
|
|
318
|
+
listen_addr: `${config.host ?? '127.0.0.1'}:${config.port ?? 3000}`, forwarded_headers: [],
|
|
319
|
+
output: ['Native configuration loaded; provider connectivity and host deployment checks remain unimplemented'] };
|
|
320
|
+
}
|
|
321
|
+
unsupported(`Native operation ${name} is not implemented`);
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/** Operation namespaces plus the native HTTP runtime. The Rust wrapper remains separate. */
|
|
325
|
+
export class NativeRouter {
|
|
326
|
+
constructor(options = {}) {
|
|
327
|
+
this.options = options; this.corePromise = null; this.serverPromise = null;
|
|
328
|
+
for (const operation of catalog.operations) {
|
|
329
|
+
let namespace = this;
|
|
330
|
+
const names = operation.name.split('.').map(camel);
|
|
331
|
+
for (const name of names.slice(0, -1)) namespace = namespace[name] ??= {};
|
|
332
|
+
namespace[names.at(-1)] = (options = {}, invocation = {}) => this.invoke(operation.name, options, invocation);
|
|
333
|
+
}
|
|
334
|
+
this.deployStatus = (options = {}, invocation = {}) => this.deploy({ ...options, status: true }, invocation);
|
|
335
|
+
this.logs = Object.assign((options = {}, invocation = {}) => this.invoke('logs.show', options, invocation), this.logs);
|
|
336
|
+
const launch = this.with;
|
|
337
|
+
this.with = (client, args, options = {}, invocation = {}) => typeof client === 'string'
|
|
338
|
+
? launch({ ...options, client, clientArgs: args }, invocation) : launch(client, args);
|
|
339
|
+
}
|
|
340
|
+
async execute(name, options = {}, invocation = {}) {
|
|
341
|
+
const operation = catalog.operations.find(operation => operation.name === name);
|
|
342
|
+
if (!operation) return operationResult('cli-error', output(), [`Unknown operation: ${name}`], 2);
|
|
343
|
+
try {
|
|
344
|
+
if (invocation.signal?.aborted) throw new NativeRouterError('Operation cancelled', { code: 'cancelled' });
|
|
345
|
+
const normalized = normalizeOptions(operation, options);
|
|
346
|
+
const data = await dispatch(this, name, normalized, invocation);
|
|
347
|
+
return operationResult(name, data);
|
|
348
|
+
} catch (error) {
|
|
349
|
+
return operationResult(name, error.data ?? output(), [`${error.code ?? 'operation'}: ${error.message}`], (Number.isInteger(error.exitCode) && error.exitCode > 0 ? error.exitCode : null) ?? (error.code === 'options' || error.code === 'secret-argv' ? 2 : 1));
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
async invoke(name, options = {}, invocation = {}) {
|
|
353
|
+
const result = await this.execute(name, options, invocation);
|
|
354
|
+
if (!result.success) throw new NativeRouterError(result.diagnostics.join('; '), { result,
|
|
355
|
+
code: result.diagnostics[0]?.split(':')[0] ?? 'operation' });
|
|
356
|
+
return result;
|
|
357
|
+
}
|
|
358
|
+
async runtime(core) {
|
|
359
|
+
if (core) {
|
|
360
|
+
this.serverContexts ??= new Map();const key=JSON.stringify(core.config);
|
|
361
|
+
if (!this.serverContexts.has(key)) this.serverContexts.set(key,import('./server.mjs').then(({createNativeRouter})=>createNativeRouter({...this.options,core,clock:this.options.serverClock ?? Date.now})));
|
|
362
|
+
this.serverPromise ??= this.serverContexts.get(key);
|
|
363
|
+
return this.serverContexts.get(key);
|
|
364
|
+
}
|
|
365
|
+
this.serverPromise ??= Promise.all([runtimeFor(this), import('./server.mjs')]).then(([core, { createNativeRouter }]) => createNativeRouter({ ...this.options, core, clock: this.options.serverClock ?? Date.now }));
|
|
366
|
+
return this.serverPromise;
|
|
367
|
+
}
|
|
368
|
+
async fetch(request) { return (await this.runtime()).fetch(request); }
|
|
369
|
+
async listen(options,core) { return (await this.runtime(core)).listen(options); }
|
|
370
|
+
async close() { if (this.serverPromise) await (await this.serverPromise).close();for (const runtime of this.serverContexts?.values() ?? []) await (await runtime).close(); }
|
|
371
|
+
}
|
|
372
|
+
export const createNativeRouter = options => new NativeRouter(options);
|
|
373
|
+
|
|
374
|
+
import {executeNativeConfigure} from './client-configure.mjs';
|
|
375
|
+
|
|
376
|
+
import {preflightNativeClientLaunch} from './client-launch-plan.mjs';
|
|
377
|
+
|
|
378
|
+
import {requestNativeRunModelPolicy} from './client-run-credential.mjs';
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
import {chatToGemini,geminiToChat,geminiCanonical,canonicalGemini} from './gemini-protocol.mjs';
|
|
2
|
+
/** Stateless, fail-closed JSON adapters for inference dialects. */
|
|
3
|
+
export class ProtocolError extends Error {
|
|
4
|
+
constructor(message, status = 400) { super(message); this.status = status; this.code = 'unsupported_translation'; }
|
|
5
|
+
}
|
|
6
|
+
const copy = value => structuredClone(value);
|
|
7
|
+
const text = content => typeof content === 'string' ? content : (content ?? []).map(p => p.text ?? '').join('');
|
|
8
|
+
const parseArguments = raw => {
|
|
9
|
+
try { return typeof raw === 'string' ? JSON.parse(raw) : raw ?? {}; }
|
|
10
|
+
catch { throw new ProtocolError('Function arguments must contain valid JSON'); }
|
|
11
|
+
};
|
|
12
|
+
function chatParts(content) {
|
|
13
|
+
if (content == null || typeof content === 'string') return content ?? '';
|
|
14
|
+
if (!Array.isArray(content)) throw new ProtocolError('Message content must be a string or array');
|
|
15
|
+
return content.map(p => {
|
|
16
|
+
if (['text', 'input_text', 'output_text'].includes(p.type)) return { type: 'text', text: p.text };
|
|
17
|
+
if (p.type === 'image_url') {
|
|
18
|
+
const url = p.image_url?.url;
|
|
19
|
+
const match = /^data:([^;]+);base64,(.+)$/s.exec(url ?? '');
|
|
20
|
+
return { type: 'image', source: match ? { type: 'base64', media_type: match[1], data: match[2] } : { type: 'url', url } };
|
|
21
|
+
}
|
|
22
|
+
throw new ProtocolError(`Cannot translate content part ${p.type}`);
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
function anthropicParts(content) {
|
|
26
|
+
if (typeof content === 'string') return content;
|
|
27
|
+
return (content ?? []).map(p => {
|
|
28
|
+
if (p.cache_control || p.citations?.length) throw new ProtocolError('Cache controls and citations require a native Anthropic upstream');
|
|
29
|
+
if (p.type === 'text') return { type: 'text', text: p.text };
|
|
30
|
+
if (p.type === 'image') return { type: 'image_url', image_url: { url: p.source?.type === 'base64' ? `data:${p.source.media_type};base64,${p.source.data}` : p.source?.url } };
|
|
31
|
+
throw new ProtocolError(`Cannot translate Anthropic content part ${p.type}`);
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
export function requestToChat(body, source) {
|
|
35
|
+
if (source === 'chat') return copy(body);
|
|
36
|
+
if (source === 'gemini') return geminiToChat(body);
|
|
37
|
+
const out = { model: body.model, messages: [], stream: body.stream ?? false };
|
|
38
|
+
for (const key of ['temperature', 'top_p', 'parallel_tool_calls']) if (body[key] !== undefined) out[key] = copy(body[key]);
|
|
39
|
+
if (source === 'anthropic') {
|
|
40
|
+
out.max_tokens = body.max_tokens;
|
|
41
|
+
if (body.system) out.messages.push({ role: 'system', content: anthropicParts(body.system) });
|
|
42
|
+
for (const message of body.messages) {
|
|
43
|
+
if (typeof message.content === 'string') { out.messages.push(copy(message)); continue; }
|
|
44
|
+
const ordinary = [], tools = [];
|
|
45
|
+
for (const block of message.content ?? []) {
|
|
46
|
+
if (block.type === 'tool_result') {
|
|
47
|
+
if (block.is_error) throw new ProtocolError('Tool error flags require a native Anthropic upstream');
|
|
48
|
+
out.messages.push({ role: 'tool', tool_call_id: block.tool_use_id, content: anthropicParts(block.content) });
|
|
49
|
+
} else if (block.type === 'tool_use') {
|
|
50
|
+
tools.push({ id: block.id, type: 'function', function: { name: block.name, arguments: JSON.stringify(block.input ?? {}) } });
|
|
51
|
+
} else ordinary.push(block);
|
|
52
|
+
}
|
|
53
|
+
if (ordinary.length || tools.length) out.messages.push({ role: message.role, content: anthropicParts(ordinary), ...(tools.length ? { tool_calls: tools } : {}) });
|
|
54
|
+
}
|
|
55
|
+
if (body.tools) out.tools = body.tools.map(t => {
|
|
56
|
+
if (t.type && t.type !== 'custom') throw new ProtocolError(`Cannot translate server tool ${t.type}`);
|
|
57
|
+
return { type: 'function', function: { name: t.name, description: t.description, parameters: t.input_schema } };
|
|
58
|
+
});
|
|
59
|
+
if (body.tool_choice) {
|
|
60
|
+
const t = body.tool_choice;
|
|
61
|
+
out.tool_choice = t.type === 'tool' ? { type: 'function', function: { name: t.name } } : ({ auto: 'auto', any: 'required', none: 'none' }[t.type]);
|
|
62
|
+
if (!out.tool_choice) throw new ProtocolError('Unsupported Anthropic tool_choice');
|
|
63
|
+
if (t.disable_parallel_tool_use !== undefined) out.parallel_tool_calls = !t.disable_parallel_tool_use;
|
|
64
|
+
}
|
|
65
|
+
if (body.stop_sequences) out.stop = copy(body.stop_sequences);
|
|
66
|
+
if (body.thinking || body.output_config) throw new ProtocolError('Thinking controls require a native Anthropic upstream');
|
|
67
|
+
} else if (source === 'responses') {
|
|
68
|
+
if (body.previous_response_id || body.conversation || body.background) throw new ProtocolError('Stateful Responses controls require a native Responses upstream');
|
|
69
|
+
out.max_completion_tokens = body.max_output_tokens;
|
|
70
|
+
if (body.instructions) out.messages.push({ role: 'system', content: body.instructions });
|
|
71
|
+
const input = typeof body.input === 'string' ? [{ role: 'user', content: body.input }] : body.input;
|
|
72
|
+
for (const item of input ?? []) {
|
|
73
|
+
if (item.type === 'function_call') out.messages.push({ role: 'assistant', content: null, tool_calls: [{ id: item.call_id, type: 'function', function: { name: item.name, arguments: item.arguments } }] });
|
|
74
|
+
else if (item.type === 'function_call_output') out.messages.push({ role: 'tool', tool_call_id: item.call_id, content: typeof item.output === 'string' ? item.output : JSON.stringify(item.output) });
|
|
75
|
+
else if (!item.type || item.type === 'message') out.messages.push({ role: item.role, content: (typeof item.content === 'string') ? item.content : (item.content ?? []).map(p => {
|
|
76
|
+
if (['input_text', 'output_text', 'text'].includes(p.type)) return { type: 'text', text: p.text };
|
|
77
|
+
if (p.type === 'input_image') return { type: 'image_url', image_url: { url: p.image_url, detail: p.detail } };
|
|
78
|
+
throw new ProtocolError(`Cannot translate Responses content ${p.type}`);
|
|
79
|
+
}) });
|
|
80
|
+
else throw new ProtocolError(`Cannot translate Responses input ${item.type}`);
|
|
81
|
+
}
|
|
82
|
+
if (body.tools) out.tools = body.tools.map(t => {
|
|
83
|
+
if (t.type !== 'function') throw new ProtocolError(`Cannot translate Responses tool ${t.type}`);
|
|
84
|
+
const { type, ...fn } = t; return { type, function: fn };
|
|
85
|
+
});
|
|
86
|
+
if (body.tool_choice) out.tool_choice = typeof body.tool_choice === 'string' ? body.tool_choice : { type: 'function', function: { name: body.tool_choice.name } };
|
|
87
|
+
if (body.reasoning || body.text?.format) throw new ProtocolError('Reasoning and structured output require a native Responses upstream');
|
|
88
|
+
} else throw new ProtocolError(`Unknown source protocol ${source}`);
|
|
89
|
+
return out;
|
|
90
|
+
}
|
|
91
|
+
export function translateRequest(body, source, target, model = body.model) {
|
|
92
|
+
if (source === target) return { ...copy(body), model };
|
|
93
|
+
const chat = requestToChat(body, source); chat.model = model;
|
|
94
|
+
if (target === 'chat') return chat;
|
|
95
|
+
if (target === 'gemini') return chatToGemini(chat);
|
|
96
|
+
if (chat.n && chat.n !== 1) throw new ProtocolError('Only n=1 can be translated');
|
|
97
|
+
for (const key of ['response_format', 'audio', 'modalities', 'logprobs', 'logit_bias', 'frequency_penalty', 'presence_penalty', 'seed', 'reasoning', 'reasoning_effort']) {
|
|
98
|
+
if (chat[key] != null && chat[key] !== false) throw new ProtocolError(`${key} requires a native Chat upstream`);
|
|
99
|
+
}
|
|
100
|
+
if (target === 'anthropic') {
|
|
101
|
+
const out = { model, messages: [], max_tokens: chat.max_completion_tokens ?? chat.max_tokens ?? 4096, stream: chat.stream ?? false };
|
|
102
|
+
const systems = [];
|
|
103
|
+
for (const m of chat.messages) {
|
|
104
|
+
if (m.role === 'system' || m.role === 'developer') { systems.push(text(m.content)); continue; }
|
|
105
|
+
if (m.role === 'tool') {
|
|
106
|
+
const block = { type: 'tool_result', tool_use_id: m.tool_call_id, content: chatParts(m.content) };
|
|
107
|
+
const previous = out.messages.at(-1);
|
|
108
|
+
if (previous?.role === 'user') { if (typeof previous.content === 'string') previous.content = [{ type: 'text', text: previous.content }]; previous.content.push(block); }
|
|
109
|
+
else out.messages.push({ role: 'user', content: [block] });
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
if (!['user', 'assistant'].includes(m.role)) throw new ProtocolError(`Cannot translate role ${m.role}`);
|
|
113
|
+
let content = chatParts(m.content);
|
|
114
|
+
if (m.tool_calls?.length) {
|
|
115
|
+
if (typeof content === 'string') content = content ? [{ type: 'text', text: content }] : [];
|
|
116
|
+
content.push(...m.tool_calls.map(t => ({ type: 'tool_use', id: t.id, name: t.function.name, input: parseArguments(t.function.arguments) })));
|
|
117
|
+
}
|
|
118
|
+
out.messages.push({ role: m.role, content });
|
|
119
|
+
}
|
|
120
|
+
if (systems.length) out.system = systems.join('\n\n');
|
|
121
|
+
for (const key of ['temperature', 'top_p']) if (chat[key] !== undefined) out[key] = chat[key];
|
|
122
|
+
if (chat.stop) out.stop_sequences = Array.isArray(chat.stop) ? chat.stop : [chat.stop];
|
|
123
|
+
if (chat.tools) out.tools = chat.tools.map(t => ({ name: t.function.name, description: t.function.description, input_schema: t.function.parameters ?? { type: 'object', properties: {} } }));
|
|
124
|
+
if (chat.tool_choice) out.tool_choice = typeof chat.tool_choice === 'string' ? { type: { auto: 'auto', required: 'any', none: 'none' }[chat.tool_choice] } : { type: 'tool', name: chat.tool_choice.function.name };
|
|
125
|
+
if (chat.parallel_tool_calls !== undefined) out.tool_choice = { ...(out.tool_choice ?? { type: 'auto' }), disable_parallel_tool_use: !chat.parallel_tool_calls };
|
|
126
|
+
return out;
|
|
127
|
+
}
|
|
128
|
+
if (target === 'responses') {
|
|
129
|
+
const out = { model, input: [], stream: chat.stream ?? false };
|
|
130
|
+
if (chat.stop) throw new ProtocolError('Responses has no stop sequence control');
|
|
131
|
+
for (const m of chat.messages) {
|
|
132
|
+
if (m.role === 'tool') out.input.push({ type: 'function_call_output', call_id: m.tool_call_id, output: text(m.content) });
|
|
133
|
+
else {
|
|
134
|
+
if (m.content != null && (typeof m.content === 'string' ? m.content.length : m.content.length)) out.input.push({ role: m.role, content: typeof m.content === 'string' ? m.content : m.content.map(p => {
|
|
135
|
+
if (p.type === 'text') return { type: m.role === 'assistant' ? 'output_text' : 'input_text', text: p.text };
|
|
136
|
+
if (p.type === 'image_url') return { type: 'input_image', image_url: p.image_url.url, detail: p.image_url.detail };
|
|
137
|
+
throw new ProtocolError(`Cannot translate content ${p.type}`);
|
|
138
|
+
}) });
|
|
139
|
+
for (const call of m.tool_calls ?? []) out.input.push({ type: 'function_call', call_id: call.id, name: call.function.name, arguments: call.function.arguments });
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
if (chat.max_completion_tokens ?? chat.max_tokens) out.max_output_tokens = chat.max_completion_tokens ?? chat.max_tokens;
|
|
143
|
+
for (const key of ['temperature', 'top_p', 'parallel_tool_calls']) if (chat[key] !== undefined) out[key] = chat[key];
|
|
144
|
+
if (chat.tools) out.tools = chat.tools.map(t => ({ type: 'function', ...t.function }));
|
|
145
|
+
if (chat.tool_choice) out.tool_choice = typeof chat.tool_choice === 'string' ? chat.tool_choice : { type: 'function', name: chat.tool_choice.function.name };
|
|
146
|
+
return out;
|
|
147
|
+
}
|
|
148
|
+
throw new ProtocolError(`Unsupported upstream protocol ${target}`, 501);
|
|
149
|
+
}
|
|
150
|
+
export function normalizeUsage(usage = {}, protocol = 'chat') {
|
|
151
|
+
const rawInput = usage.input_tokens ?? usage.prompt_tokens ?? usage.promptTokenCount ?? 0;
|
|
152
|
+
const output = usage.output_tokens ?? usage.completion_tokens ?? usage.candidatesTokenCount ?? 0;
|
|
153
|
+
const cached = usage.cache_read_input_tokens ?? usage.input_tokens_details?.cached_tokens ?? usage.prompt_tokens_details?.cached_tokens ?? usage.cachedContentTokenCount ?? 0;
|
|
154
|
+
const created = usage.cache_creation_input_tokens ?? 0;
|
|
155
|
+
const input = rawInput + (protocol === 'anthropic' ? cached + created : 0);
|
|
156
|
+
const normalized = { input, output, cached, created, total: usage.total_tokens ?? usage.totalTokenCount ?? input + output };
|
|
157
|
+
if (Object.values(normalized).some(value => !Number.isSafeInteger(value) || value < 0)) throw new ProtocolError('Upstream returned invalid token usage', 502);
|
|
158
|
+
return normalized;
|
|
159
|
+
}
|
|
160
|
+
export function responseToCanonical(body, protocol) {
|
|
161
|
+
if (protocol === 'gemini') return geminiCanonical(body,normalizeUsage);
|
|
162
|
+
const result = { id: body.id, model: body.model, text: '', tools: [], usage: normalizeUsage(body.usage, protocol), finish: 'stop' };
|
|
163
|
+
if (protocol === 'chat') {
|
|
164
|
+
const choice = body.choices?.[0];
|
|
165
|
+
if (body.choices?.length > 1) throw new ProtocolError('Cannot translate multiple response choices', 502);
|
|
166
|
+
if (!choice?.message) throw new ProtocolError('Upstream Chat response has no message', 502);
|
|
167
|
+
if (Array.isArray(choice.message.content) && choice.message.content.some(p => p.type !== 'text' || p.annotations?.length)) throw new ProtocolError('Cannot translate non-text response content or annotations', 502);
|
|
168
|
+
result.text = text(choice.message.content); result.tools = copy(choice.message.tool_calls ?? []); result.finish = choice.finish_reason ?? 'stop';
|
|
169
|
+
if (!['stop', 'length', 'tool_calls','content_filter'].includes(result.finish)) throw new ProtocolError(`Cannot translate finish reason ${result.finish}`, 502);
|
|
170
|
+
if (choice.message.refusal) throw new ProtocolError('Refusal cannot be translated to this dialect', 502);
|
|
171
|
+
} else if (protocol === 'anthropic') {
|
|
172
|
+
if (!Array.isArray(body.content)) throw new ProtocolError('Upstream Messages response has no content', 502);
|
|
173
|
+
for (const p of body.content) {
|
|
174
|
+
if (p.type === 'text') { if (p.citations?.length) throw new ProtocolError('Cannot translate response citations', 502); result.text += p.text; }
|
|
175
|
+
else if (p.type === 'tool_use') result.tools.push({ id: p.id, type: 'function', function: { name: p.name, arguments: JSON.stringify(p.input) } });
|
|
176
|
+
else throw new ProtocolError(`Cannot translate response block ${p.type}`, 502);
|
|
177
|
+
}
|
|
178
|
+
result.finish = { end_turn: 'stop', stop_sequence: 'stop', max_tokens: 'length', tool_use: 'tool_calls' }[body.stop_reason];
|
|
179
|
+
if (!result.finish) throw new ProtocolError(`Cannot translate stop reason ${body.stop_reason}`, 502);
|
|
180
|
+
result.stopSequence = body.stop_sequence ?? null;
|
|
181
|
+
} else if (protocol === 'responses') {
|
|
182
|
+
if (body.error || body.status && !['completed', 'incomplete'].includes(body.status)) throw new ProtocolError('Upstream Responses operation did not complete successfully', 502);
|
|
183
|
+
if (!Array.isArray(body.output)) throw new ProtocolError('Upstream Responses response has no output', 502);
|
|
184
|
+
for (const item of body.output) {
|
|
185
|
+
if (item.type === 'message') for (const p of item.content ?? []) {
|
|
186
|
+
if (p.type !== 'output_text') throw new ProtocolError(`Cannot translate response part ${p.type}`, 502);
|
|
187
|
+
if (p.annotations?.length) throw new ProtocolError('Cannot translate response annotations', 502);
|
|
188
|
+
result.text += p.text;
|
|
189
|
+
}
|
|
190
|
+
else if (item.type === 'function_call') result.tools.push({ id: item.call_id, type: 'function', function: { name: item.name, arguments: item.arguments } });
|
|
191
|
+
else throw new ProtocolError(`Cannot translate response item ${item.type}`, 502);
|
|
192
|
+
}
|
|
193
|
+
result.finish = body.status === 'incomplete' ? body.incomplete_details?.reason==='content_filter'?'content_filter':'length' : result.tools.length ? 'tool_calls' : 'stop';
|
|
194
|
+
}
|
|
195
|
+
return result;
|
|
196
|
+
}
|
|
197
|
+
export function canonicalResponse(r, protocol, model = r.model, now = Date.now()) {
|
|
198
|
+
if (protocol === 'gemini') return canonicalGemini(r,model);
|
|
199
|
+
const created = Math.floor(now / 1000), id = r.id ?? `native_${created}`;
|
|
200
|
+
const u = r.usage, incomplete=['length','content_filter'].includes(r.finish),status=incomplete?'incomplete':'completed';
|
|
201
|
+
if (protocol === 'chat') return { id, object: 'chat.completion', created, model, choices: [{ index: 0, message: { role: 'assistant', content: r.text || (r.tools.length ? null : ''), ...(r.tools.length ? { tool_calls: r.tools } : {}) }, finish_reason: r.finish }], usage: { prompt_tokens: u.input, completion_tokens: u.output, total_tokens: u.total, prompt_tokens_details: { cached_tokens: u.cached } } };
|
|
202
|
+
if (protocol === 'anthropic') return { id, type: 'message', role: 'assistant', model, content: [...(r.text ? [{ type: 'text', text: r.text }] : []), ...r.tools.map(t => ({ type: 'tool_use', id: t.id, name: t.function.name, input: parseArguments(t.function.arguments) }))], stop_reason: r.finish === 'tool_calls' ? 'tool_use' : r.finish === 'length' ? 'max_tokens' : r.stopSequence ? 'stop_sequence' : 'end_turn', stop_sequence: r.stopSequence ?? null, usage: { input_tokens: Math.max(0, u.input - u.cached - u.created), output_tokens: u.output, cache_read_input_tokens: u.cached, cache_creation_input_tokens: u.created } };
|
|
203
|
+
return { id: id.startsWith('resp_') ? id : `resp_${id}`, object: 'response', created_at: created, model, status, error: null, incomplete_details: incomplete ? {reason:r.finish==='length'?'max_output_tokens':'content_filter'} : null, output: [...(r.text ? [{ id: `msg_${id}`, type: 'message', role: 'assistant', status, content: [{ type: 'output_text', text: r.text, annotations: [] }] }] : []), ...r.tools.map(t => ({ id: `fc_${t.id}`, type: 'function_call', status, call_id: t.id, name: t.function.name, arguments: t.function.arguments }))], usage: { input_tokens: u.input, output_tokens: u.output, total_tokens: u.total, input_tokens_details: { cached_tokens: u.cached }, output_tokens_details: { reasoning_tokens: 0 } } };
|
|
204
|
+
}
|
|
205
|
+
export function translateResponse(body, source, target, model, now) {
|
|
206
|
+
if (source === target && source === 'gemini') return {...copy(body.response ?? body),modelVersion:model};
|
|
207
|
+
try { return source === target ? { ...copy(body), model } : canonicalResponse(responseToCanonical(body, source), target, model, now); }
|
|
208
|
+
catch (error) { if (error instanceof ProtocolError) error.status = 502; throw error; }
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export function projectModels(entries, protocol = 'chat', query = new URLSearchParams()) {
|
|
212
|
+
const data = entries.map(model => protocol === 'anthropic' ? Object.fromEntries(Object.entries({ id: model.id, type: 'model', display_name: model.display_name, created_at: model.created_at, max_input_tokens: model.max_input_tokens, max_tokens: model.max_tokens, capabilities: model.capabilities, router_available: model.router_available, router_unavailable_reason: model.router_unavailable_reason }).filter(([, value]) => value !== undefined)) : Object.fromEntries(Object.entries({ id: model.id, object: 'model', created: model.created, owned_by: model.owned_by, router_available: model.router_available, router_unavailable_reason: model.router_unavailable_reason }).filter(([, value]) => value !== undefined)));
|
|
213
|
+
if (protocol !== 'anthropic') return { object: 'list', data };
|
|
214
|
+
for (const key of ['limit', 'before_id', 'after_id']) if (query.getAll(key).length > 1) throw new ProtocolError(`${key} may be supplied only once`);
|
|
215
|
+
if (query.has('before_id') && query.has('after_id')) throw new ProtocolError('before_id and after_id cannot be used together');
|
|
216
|
+
if (query.has('limit') && !/^\d+$/.test(query.get('limit'))) throw new ProtocolError('limit must be between 1 and 1000');
|
|
217
|
+
const limit = query.has('limit') ? Number(query.get('limit')) : 20;
|
|
218
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1000) throw new ProtocolError('limit must be between 1 and 1000');
|
|
219
|
+
let start = 0, end, has_more;
|
|
220
|
+
if (query.has('before_id')) {
|
|
221
|
+
end = data.findIndex(m => m.id === query.get('before_id')); if (end < 0) throw new ProtocolError('before_id cursor not found');
|
|
222
|
+
start = Math.max(0, end - limit); has_more = start > 0;
|
|
223
|
+
} else {
|
|
224
|
+
if (query.has('after_id')) { const index = data.findIndex(m => m.id === query.get('after_id')); if (index < 0) throw new ProtocolError('after_id cursor not found'); start = index + 1; }
|
|
225
|
+
end = Math.min(data.length, start + limit); has_more = end < data.length;
|
|
226
|
+
}
|
|
227
|
+
const page = data.slice(start, end);
|
|
228
|
+
return { data: page, first_id: page[0]?.id ?? null, last_id: page.at(-1)?.id ?? null, has_more };
|
|
229
|
+
}
|