@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/index.js
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
/** Official CLI JSON transport. Operational decisions belong to the Rust library. */
|
|
2
|
+
import { spawn } from 'node:child_process';
|
|
3
|
+
import { readFileSync, constants } from 'node:fs';
|
|
4
|
+
import { mkdtemp, mkdir, readFile, writeFile, rename, rm, chmod, copyFile, lstat, access } from 'node:fs/promises';
|
|
5
|
+
import { tmpdir, homedir } from 'node:os';
|
|
6
|
+
import { dirname, join, resolve, delimiter } from 'node:path';
|
|
7
|
+
import { fileURLToPath } from 'node:url';
|
|
8
|
+
import { createHash } from 'node:crypto';
|
|
9
|
+
import { StringDecoder } from 'node:string_decoder';
|
|
10
|
+
import Ajv2020 from 'ajv/dist/2020.js';
|
|
11
|
+
|
|
12
|
+
const root = dirname(fileURLToPath(import.meta.url));
|
|
13
|
+
export const catalog = JSON.parse(readFileSync(join(root, 'catalog.json'), 'utf8'));
|
|
14
|
+
export const version = catalog.version;
|
|
15
|
+
export const operationNames = Object.freeze(catalog.operations.map(operation => operation.name));
|
|
16
|
+
const validators = new Map();
|
|
17
|
+
const ajv = new Ajv2020({ strict: true, allowUnionTypes: true, validateFormats: false });
|
|
18
|
+
const camel = value => value.replace(/[-_]([a-z])/g, (_, letter) => letter.toUpperCase());
|
|
19
|
+
|
|
20
|
+
/** A transport, version, contract or Router operation failure with diagnostics. */
|
|
21
|
+
export class RouterError extends Error {
|
|
22
|
+
constructor(message, { code = 'operation', exitCode = null, stderr = '', result = null, cause } = {}) {
|
|
23
|
+
super(message, { cause });
|
|
24
|
+
this.name = 'RouterError'; Object.assign(this, { code, exitCode, stderr, result });
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function terminate(child) {
|
|
29
|
+
if (child.pid && process.platform !== 'win32') {
|
|
30
|
+
try { process.kill(-child.pid, 'SIGKILL'); } catch { /* Already exited. */ }
|
|
31
|
+
} else child.kill('SIGKILL');
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Bounded process primitive; credentials enter through env/stdin only. */
|
|
35
|
+
export function runProcess(binary, args, { env = {}, stdin, deadlineMs = 60_000, signal, cwd, maxOutputBytes = 8_388_608 } = {}) {
|
|
36
|
+
if (!Number.isFinite(deadlineMs) || deadlineMs <= 0) throw new RouterError('deadlineMs must be positive', { code: 'options' });
|
|
37
|
+
return new Promise((resolve, reject) => {
|
|
38
|
+
if (signal?.aborted) { reject(new RouterError('Operation cancelled', { code: 'cancelled' })); return; }
|
|
39
|
+
const child = spawn(binary, args, { env: { ...process.env, ...env }, cwd, detached: process.platform !== 'win32', stdio: ['pipe', 'pipe', 'pipe'] });
|
|
40
|
+
let stdout = '', stderr = '', bytes = 0, failure;
|
|
41
|
+
const decoders = { stdout: new StringDecoder('utf8'), stderr: new StringDecoder('utf8') };
|
|
42
|
+
const fail = error => { failure ??= error; terminate(child); };
|
|
43
|
+
const collect = name => chunk => {
|
|
44
|
+
bytes += chunk.length;
|
|
45
|
+
if (bytes > maxOutputBytes) { fail(new RouterError('Router output exceeds limit', { code: 'output-limit' })); return; }
|
|
46
|
+
if (name === 'stdout') stdout += decoders.stdout.write(chunk); else stderr += decoders.stderr.write(chunk);
|
|
47
|
+
};
|
|
48
|
+
child.stdout.on('data', collect('stdout')); child.stderr.on('data', collect('stderr'));
|
|
49
|
+
const timer = setTimeout(() => fail(new RouterError('Router deadline exceeded', { code: 'deadline' })), deadlineMs);
|
|
50
|
+
const abort = () => fail(new RouterError('Operation cancelled', { code: 'cancelled' }));
|
|
51
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
52
|
+
child.on('error', error => { failure ??= new RouterError(`Cannot execute ${binary}`, { code: 'spawn', cause: error }); });
|
|
53
|
+
child.on('close', exitCode => {
|
|
54
|
+
stdout += decoders.stdout.end(); stderr += decoders.stderr.end();
|
|
55
|
+
clearTimeout(timer); signal?.removeEventListener('abort', abort);
|
|
56
|
+
// Clean up grandchildren which inherited pipes or survived their leader.
|
|
57
|
+
terminate(child);
|
|
58
|
+
if (failure) { failure.exitCode = exitCode; failure.stderr = stderr; reject(failure); }
|
|
59
|
+
else resolve({ stdout, stderr, exitCode });
|
|
60
|
+
});
|
|
61
|
+
child.stdin.on('error', error => { if (error.code !== 'EPIPE') fail(error); });
|
|
62
|
+
child.stdin.end(stdin ?? '');
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function schemaFor(operation) {
|
|
67
|
+
if (!validators.has(operation.name)) {
|
|
68
|
+
const filename = operation.name.replaceAll('.', '-') + '.v1.json';
|
|
69
|
+
const schema = JSON.parse(readFileSync(join(root, 'schemas', filename), 'utf8'));
|
|
70
|
+
validators.set(operation.name, ajv.compile(schema));
|
|
71
|
+
}
|
|
72
|
+
return validators.get(operation.name);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Validate a complete result using the same offline contracts as Router. */
|
|
76
|
+
export function validateOperation(name, result) {
|
|
77
|
+
const operation = catalog.operations.find(operation => operation.name === name);
|
|
78
|
+
if (!operation || !schemaFor(operation)(result)) throw new RouterError(`Invalid ${name} response`, { code: 'schema', result });
|
|
79
|
+
return result;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function argumentsFor(operation, options) {
|
|
83
|
+
const allowed = new Map(operation.options.map(option => [camel(option.name), option]));
|
|
84
|
+
const flags = [], positional = [];
|
|
85
|
+
for (const [name, value] of Object.entries(options)) {
|
|
86
|
+
if (value === undefined || value === null) continue;
|
|
87
|
+
const option = allowed.get(camel(name));
|
|
88
|
+
if (!option) throw new RouterError(`Unknown ${operation.name} option: ${name}`, { code: 'options' });
|
|
89
|
+
if (option.secret) throw new RouterError(`${name} is secret; use env or stdin transport`, { code: 'secret-argv' });
|
|
90
|
+
const values = Array.isArray(value) ? value : [value];
|
|
91
|
+
if (option.positional) { positional.push([operation.options.indexOf(option), values]); continue; }
|
|
92
|
+
if (!option.flag) throw new RouterError(`No CLI flag for ${name}`, { code: 'options' });
|
|
93
|
+
if (option.boolean) {
|
|
94
|
+
if (typeof value !== 'boolean') throw new RouterError(`${name} must be boolean`, { code: 'options' });
|
|
95
|
+
if (option.boolean_value) flags.push(`--${option.flag}=${value}`);
|
|
96
|
+
else if (value) flags.push('--' + option.flag);
|
|
97
|
+
}
|
|
98
|
+
else for (const item of values) flags.push('--' + option.flag, String(item));
|
|
99
|
+
}
|
|
100
|
+
positional.sort((a, b) => a[0] - b[0]);
|
|
101
|
+
const args = [...operation.command, '--json', ...flags];
|
|
102
|
+
// The launcher forwards everything after its client argument. Put Router
|
|
103
|
+
// options first and preserve caller arguments, including vendor --json.
|
|
104
|
+
for (const [, values] of positional) args.push(...values.map(String));
|
|
105
|
+
return args;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Resolve/download exactly this package's binary, with fail-closed provenance. */
|
|
109
|
+
export async function resolveBinary({ binary = process.env.ROUTER_BIN, allowDownload = true, allowVersionMismatch = false, env = {}, deadlineMs = 60_000, cacheDir = join(homedir(), '.cache', 'link-assistant-router') } = {}) {
|
|
110
|
+
let candidate = binary ?? env.ROUTER_BIN ?? 'router';
|
|
111
|
+
// Preserve PATH resolution across subsequent per-call environment overrides.
|
|
112
|
+
if (!candidate.includes('/') && !candidate.includes('\\')) {
|
|
113
|
+
for (const directory of (env.PATH ?? process.env.PATH ?? '').split(delimiter)) {
|
|
114
|
+
const location = resolve(directory, candidate);
|
|
115
|
+
try { await access(location, constants.X_OK); candidate = location; break; } catch { /* Try the next PATH entry. */ }
|
|
116
|
+
}
|
|
117
|
+
} else candidate = resolve(candidate);
|
|
118
|
+
let response;
|
|
119
|
+
try { response = await runProcess(candidate, ['version', '--json'], { env, deadlineMs }); }
|
|
120
|
+
catch (error) {
|
|
121
|
+
if (binary || env.ROUTER_BIN || !allowDownload || error.code !== 'spawn' || error.cause?.code !== 'ENOENT') throw error;
|
|
122
|
+
candidate = await downloadBinary({ cacheDir, deadlineMs });
|
|
123
|
+
response = await runProcess(candidate, ['version', '--json'], { env, deadlineMs });
|
|
124
|
+
}
|
|
125
|
+
let result;
|
|
126
|
+
try { result = JSON.parse(response.stdout); } catch (cause) { throw new RouterError('Binary does not implement the version JSON contract', { code: 'version', stderr: response.stderr, cause }); }
|
|
127
|
+
const operation = catalog.operations.find(operation => operation.name === 'version');
|
|
128
|
+
if (!schemaFor(operation)(result)) throw new RouterError('Invalid binary version contract', { code: 'schema', stderr: response.stderr, result });
|
|
129
|
+
if (response.exitCode !== 0 || !result.success) throw new RouterError('Binary version probe failed', { code: 'version', exitCode: response.exitCode, stderr: response.stderr, result });
|
|
130
|
+
if (!allowVersionMismatch && result.data.version !== version) throw new RouterError(`Package ${version} cannot use binary ${result.data.version}; opt in with allowVersionMismatch`, { code: 'version', result });
|
|
131
|
+
return candidate;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async function downloadBinary({ cacheDir, deadlineMs }) {
|
|
135
|
+
const platform = process.platform === 'darwin' ? 'darwin' : process.platform === 'linux' ? 'linux' : null;
|
|
136
|
+
const arch = process.arch === 'arm64' ? 'arm64' : process.arch === 'x64' ? 'amd64' : null;
|
|
137
|
+
if (!platform || !arch) throw new RouterError('No verified binary asset for this platform; set ROUTER_BIN', { code: 'platform' });
|
|
138
|
+
const destination = join(cacheDir, version, `${platform}-${arch}`, 'router');
|
|
139
|
+
// A verified receipt protects cached content against replacement.
|
|
140
|
+
try {
|
|
141
|
+
const receipt = JSON.parse(await readFile(destination + '.verified.json', 'utf8'));
|
|
142
|
+
const digest = createHash('sha256').update(await readFile(destination)).digest('hex');
|
|
143
|
+
if (receipt.version === version && receipt.sha256 === digest) return destination;
|
|
144
|
+
} catch { /* Re-download invalid/missing cache. */ }
|
|
145
|
+
await mkdir(dirname(destination), { recursive: true });
|
|
146
|
+
const work = await mkdtemp(join(tmpdir(), 'router-download-'));
|
|
147
|
+
try {
|
|
148
|
+
const asset = `link-assistant-router-${version}-${platform}-${arch}.tar.gz`;
|
|
149
|
+
const checksum = asset.replace('.tar.gz', '.sha256');
|
|
150
|
+
const base = `https://github.com/link-assistant/router/releases/download/v${version}/`;
|
|
151
|
+
for (const name of [asset, checksum]) {
|
|
152
|
+
const response = await fetch(base + name, { signal: AbortSignal.timeout(deadlineMs) });
|
|
153
|
+
if (!response.ok) throw new RouterError(`Download failed: ${response.status} ${name}`, { code: 'download' });
|
|
154
|
+
const chunks = []; let total = 0;
|
|
155
|
+
for await (const chunk of response.body) {
|
|
156
|
+
total += chunk.length;
|
|
157
|
+
if (total > 150_000_000) throw new RouterError('Release download exceeds size limit', { code: 'download' });
|
|
158
|
+
chunks.push(chunk);
|
|
159
|
+
}
|
|
160
|
+
const bytes = Buffer.concat(chunks);
|
|
161
|
+
await writeFile(join(work, name), bytes);
|
|
162
|
+
}
|
|
163
|
+
const lines = (await readFile(join(work, checksum), 'utf8')).split('\n');
|
|
164
|
+
const entry = lines.map(line => line.trim().split(/\s+/)).find(([, name]) => name?.replace(/^\*/, '') === asset);
|
|
165
|
+
const digest = createHash('sha256').update(await readFile(join(work, asset))).digest('hex');
|
|
166
|
+
if (!entry || entry[0] !== digest) throw new RouterError('Release checksum mismatch', { code: 'checksum' });
|
|
167
|
+
const verification = await runProcess('gh', ['attestation', 'verify', join(work, asset), '--repo', 'link-assistant/router', '--source-ref', `refs/tags/v${version}`], { deadlineMs });
|
|
168
|
+
if (verification.exitCode !== 0) throw new RouterError('Release attestation verification failed', { code: 'attestation', stderr: verification.stderr, exitCode: verification.exitCode });
|
|
169
|
+
// Extract only the named regular binary, never arbitrary archive paths.
|
|
170
|
+
const extraction = await runProcess('tar', ['-xzf', join(work, asset), '-C', work, './router'], { deadlineMs });
|
|
171
|
+
if (extraction.exitCode !== 0) throw new RouterError('Binary extraction failed', { code: 'download', stderr: extraction.stderr });
|
|
172
|
+
if (!(await lstat(join(work, 'router'))).isFile()) throw new RouterError('Release binary must be a regular file', { code: 'download' });
|
|
173
|
+
const stagingDirectory = await mkdtemp(join(dirname(destination), 'staging-'));
|
|
174
|
+
const staged = join(stagingDirectory, 'router');
|
|
175
|
+
await copyFile(join(work, 'router'), staged);
|
|
176
|
+
await chmod(staged, 0o755);
|
|
177
|
+
await rename(staged, destination);
|
|
178
|
+
await rm(stagingDirectory, { recursive: true, force: true });
|
|
179
|
+
const receipt = { version, sha256: createHash('sha256').update(await readFile(destination)).digest('hex') };
|
|
180
|
+
await writeFile(destination + '.verified.json', JSON.stringify(receipt), { mode: 0o600 });
|
|
181
|
+
return destination;
|
|
182
|
+
} finally { await rm(work, { recursive: true, force: true }); }
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** Full operation namespace, generated from the Rust command catalog. */
|
|
186
|
+
export class Router {
|
|
187
|
+
constructor(options = {}) {
|
|
188
|
+
this.options = options; this.binaryPromise = null;
|
|
189
|
+
for (const operation of catalog.operations) {
|
|
190
|
+
let namespace = this;
|
|
191
|
+
const names = operation.name.split('.').map(camel);
|
|
192
|
+
for (const name of names.slice(0, -1)) namespace = namespace[name] ??= {};
|
|
193
|
+
namespace[names.at(-1)] = (options = {}, invocation = {}) => this.invoke(operation.name, options, invocation);
|
|
194
|
+
}
|
|
195
|
+
this.deployStatus = (options = {}, invocation = {}) => this.deploy({ ...options, status: true }, invocation);
|
|
196
|
+
this.logs = Object.assign((options = {}, invocation = {}) => this.invoke('logs.show', options, invocation), this.logs);
|
|
197
|
+
const launch = this.with;
|
|
198
|
+
this.with = (client, args, options = {}, invocation = {}) => typeof client === 'string'
|
|
199
|
+
? launch({ ...options, client, clientArgs: args }, invocation) : launch(client, args);
|
|
200
|
+
}
|
|
201
|
+
async invoke(name, options = {}, invocation = {}) {
|
|
202
|
+
const operation = catalog.operations.find(operation => operation.name === name);
|
|
203
|
+
if (!operation) throw new RouterError(`Unknown operation ${name}`, { code: 'options' });
|
|
204
|
+
const args = argumentsFor(operation, options);
|
|
205
|
+
const settings = { ...this.options, ...invocation, env: { ...this.options.env, ...invocation.env } };
|
|
206
|
+
this.binaryPromise ??= resolveBinary(settings);
|
|
207
|
+
const binary = await this.binaryPromise;
|
|
208
|
+
const response = await runProcess(binary, args, settings);
|
|
209
|
+
let result;
|
|
210
|
+
try { result = JSON.parse(response.stdout); } catch (cause) { throw new RouterError(`Invalid JSON from ${name}`, { code: 'schema', ...response, cause }); }
|
|
211
|
+
if (result?.operation === 'cli-error') {
|
|
212
|
+
if (!schemaFor({ name: 'cli-error' })(result)) throw new RouterError('Invalid CLI error response', { code: 'schema', exitCode: response.exitCode, stderr: response.stderr, result });
|
|
213
|
+
throw new RouterError(result.diagnostics.join('; ') || 'CLI arguments rejected', { exitCode: response.exitCode, stderr: [response.stderr, ...result.diagnostics].join('\n'), result });
|
|
214
|
+
}
|
|
215
|
+
if (!schemaFor(operation)(result)) throw new RouterError(`Invalid ${name} response: ${ajv.errorsText(schemaFor(operation).errors)}`, { code: 'schema', exitCode: response.exitCode, stderr: response.stderr, result });
|
|
216
|
+
if (result.exit_code !== response.exitCode) throw new RouterError('Exit status disagrees with the result contract', { code: 'schema', exitCode: response.exitCode, stderr: response.stderr, result });
|
|
217
|
+
if (!result.success) throw new RouterError(result.diagnostics.join('; ') || `${name} failed`, { exitCode: response.exitCode, stderr: [response.stderr, ...result.diagnostics].join('\n'), result });
|
|
218
|
+
return result;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
export const createRouter = options => new Router(options);
|
|
222
|
+
|
|
223
|
+
// Native execution is explicitly opt-in; the existing Router transport is unchanged.
|
|
224
|
+
export { NativeRouter, NativeRouterError, createNativeRouter } from './src/operations.mjs';
|
package/native.d.ts
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import type { Router, Result, Invocation, TokenRecord, AccountRoutingPolicy } from './index.js';
|
|
2
|
+
/** Native JS runtime. Defaults to native core configuration; never executes Rust. */
|
|
3
|
+
export interface NativeRouterOptions {
|
|
4
|
+
config?: Record<string, unknown>;
|
|
5
|
+
configPath?: string;
|
|
6
|
+
env?: Record<string, string | undefined>;
|
|
7
|
+
storage?: unknown;
|
|
8
|
+
core?: unknown;
|
|
9
|
+
fetch?: typeof fetch;
|
|
10
|
+
authenticate?: (request: Request) => unknown | Promise<unknown>;
|
|
11
|
+
/** Core clock in Unix seconds. */
|
|
12
|
+
clock?: () => number;
|
|
13
|
+
/** HTTP runtime clock in milliseconds. */
|
|
14
|
+
serverClock?: () => number;
|
|
15
|
+
/** Native OAuth validation/endpoint overrides, useful for isolated integrations. */
|
|
16
|
+
oauth?: { endpoints?: Partial<Record<'claude' | 'codex', string>>; allowLoopback?: boolean; catalogBaseURL?: string;
|
|
17
|
+
validateCatalog?: (options: Record<string, unknown>) => Promise<string[]> };
|
|
18
|
+
responseStore?: ResponsesStore;
|
|
19
|
+
responseStoreOptions?: { ttlMs?: number; maxRecords?: number; maxBytes?: number; maxRecordBytes?: number };
|
|
20
|
+
}
|
|
21
|
+
export class NativeRouterError extends Error {
|
|
22
|
+
constructor(message: string, options?: { code?: string; result?: Result | null; cause?: unknown });
|
|
23
|
+
code: string; exitCode: number | null; stderr: string; result: Result | null;
|
|
24
|
+
}
|
|
25
|
+
export interface NativeRouter extends Omit<Router, 'options' | 'binaryPromise'> {}
|
|
26
|
+
export class NativeRouter {
|
|
27
|
+
constructor(options?: NativeRouterOptions);
|
|
28
|
+
options: NativeRouterOptions;
|
|
29
|
+
/** Returns a failed operation envelope instead of throwing for operation failures. */
|
|
30
|
+
execute(name: string, options?: Record<string, unknown>, invocation?: Invocation): Promise<Result>;
|
|
31
|
+
fetch(request: Request): Promise<Response>;
|
|
32
|
+
listen(options?: { host?: string; port?: number }): Promise<NativeHttpRouter>;
|
|
33
|
+
close(): Promise<void>;
|
|
34
|
+
}
|
|
35
|
+
export function createNativeRouter(options?: NativeRouterOptions): NativeRouter;
|
|
36
|
+
|
|
37
|
+
export interface NativeHttpRouter {
|
|
38
|
+
core: unknown;
|
|
39
|
+
readonly address: { address: string; family: string; port: number } | string | null | undefined;
|
|
40
|
+
fetch(request: Request): Promise<Response>;
|
|
41
|
+
listen(options?: { host?: string; port?: number }): Promise<NativeHttpRouter>;
|
|
42
|
+
close(): Promise<void>;
|
|
43
|
+
}
|
|
44
|
+
export interface NativeTokenOptions {
|
|
45
|
+
ttl_hours?: number;
|
|
46
|
+
label?: string;
|
|
47
|
+
account?: string;
|
|
48
|
+
scope?: '' | 'admin';
|
|
49
|
+
max_requests?: number;
|
|
50
|
+
max_tokens?: number;
|
|
51
|
+
rate_limit_per_minute?: number;
|
|
52
|
+
github_repos?: string[];
|
|
53
|
+
model_policy?: { allowed_models?: string[]; allow_substitution?: boolean; substitution_source?: string };
|
|
54
|
+
}
|
|
55
|
+
export interface NativeTokenManager {
|
|
56
|
+
issue(options?: NativeTokenOptions): Promise<{ token: string; id: string; record: TokenRecord }>;
|
|
57
|
+
list(): Promise<TokenRecord[]>;
|
|
58
|
+
get(id: string): Promise<TokenRecord | null>;
|
|
59
|
+
validate(token: string, options?: { admin?: boolean; model?: string; repository?: string }): Promise<Record<string, unknown>>;
|
|
60
|
+
revoke(id: string): Promise<boolean>;
|
|
61
|
+
expire(id: string): Promise<TokenRecord>;
|
|
62
|
+
rotate(id: string, options?: NativeTokenOptions): Promise<{ token: string; id: string; record: TokenRecord }>;
|
|
63
|
+
admit(id: string, reserve?: number): Promise<string>;
|
|
64
|
+
settle(id: string, reserved: number, used: number): Promise<void>;
|
|
65
|
+
}
|
|
66
|
+
export class RouterCore {
|
|
67
|
+
constructor(options: NativeRouterOptions & { config: Record<string, unknown> });
|
|
68
|
+
config: Record<string, unknown>;
|
|
69
|
+
tokens: NativeTokenManager;
|
|
70
|
+
listProviders(): Promise<Array<Record<string, unknown>>>;
|
|
71
|
+
showProvider(name: string): Promise<Record<string, unknown> | null>;
|
|
72
|
+
upsertProvider(provider: Record<string, unknown>): Promise<Record<string, unknown>>;
|
|
73
|
+
removeProvider(name: string): Promise<boolean>;
|
|
74
|
+
listAccounts(): Promise<Array<Record<string, unknown>>>;
|
|
75
|
+
accountAction(name: string, action: 'pause' | 'resume' | 'policy', body?: AccountRoutingPolicy | Record<string, unknown>): Promise<Record<string, unknown>>;
|
|
76
|
+
resetCooldowns(): Promise<{ cleared: number }>;
|
|
77
|
+
resetCooldown(name: string, model?: string): Promise<{ cleared: number }>;
|
|
78
|
+
models(): Promise<Array<Record<string, unknown>>>;
|
|
79
|
+
candidates(context?: Record<string, unknown>): Promise<Array<Record<string, unknown>>>;
|
|
80
|
+
route(context?: Record<string, unknown>): Promise<Record<string, unknown>>;
|
|
81
|
+
catalogFor(context?: Record<string, unknown>): Promise<Array<Record<string, unknown>>>;
|
|
82
|
+
prepareCandidate(candidate: Record<string, unknown>, context?: Record<string, unknown>): Promise<Record<string, unknown>>;
|
|
83
|
+
updateRouting(update: Record<string, unknown>): Promise<Record<string, unknown>>;
|
|
84
|
+
reportFailure(candidate: Record<string, unknown>, details: Record<string, unknown>): Promise<string>;
|
|
85
|
+
reportSuccess(candidate: Record<string, unknown>): Promise<void>;
|
|
86
|
+
}
|
|
87
|
+
export function createRouterCore(options?: NativeRouterOptions): Promise<RouterCore>;
|
|
88
|
+
export function createNativeServerRouter(options: NativeRouterOptions & { core: unknown }): NativeHttpRouter;
|
|
89
|
+
export function startNativeServer(options?: NativeRouterOptions & { host?: string; port?: number }): Promise<NativeHttpRouter>;
|
|
90
|
+
export const nativeOperationSupport: Readonly<Record<string, 'implemented' | 'partial'>>;
|
|
91
|
+
export function validateNativeResult(name: string, result: unknown): Result;
|
|
92
|
+
export function operationResult(name: string, data: unknown, diagnostics?: string[], exitCode?: number): Result;
|
|
93
|
+
export { catalog, version, operationNames } from './index.js';
|
|
94
|
+
|
|
95
|
+
/** Bounded process-retained foreground Responses resources, isolated by owner and namespace. */
|
|
96
|
+
export class ResponsesStore {
|
|
97
|
+
constructor(options?: { clock?: () => number; ttlMs?: number; maxRecords?: number; maxBytes?: number; maxRecordBytes?: number });
|
|
98
|
+
save(namespace: string, owner: string, response: Record<string, unknown>, input: unknown[], options?: { abort?: () => void; update?: boolean }): Record<string, unknown>;
|
|
99
|
+
get(namespace: string, owner: string, id: string): Record<string, unknown>;
|
|
100
|
+
delete(namespace: string, owner: string, id: string): { id: string; object: string; deleted: boolean };
|
|
101
|
+
cancel(namespace: string, owner: string, id: string): Record<string, unknown>;
|
|
102
|
+
inputItems(namespace: string, owner: string, id: string, query?: URLSearchParams): Record<string, unknown>;
|
|
103
|
+
close(): void;
|
|
104
|
+
}
|
|
105
|
+
export function responseOwner(claims: Record<string, unknown>, credential?: string): string;
|
|
106
|
+
export function normalizeResponseInput(body: { input: string | unknown[] }): Array<Record<string, unknown>>;
|
package/package.json
CHANGED
|
@@ -1,6 +1,63 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@link-assistant/router",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.25.6",
|
|
4
|
+
"description": "Official typed Router operations and testing helpers for Node and Bun",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"engines": {
|
|
7
|
+
"node": ">=20"
|
|
8
|
+
},
|
|
9
|
+
"main": "index.js",
|
|
10
|
+
"types": "index.d.ts",
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"types": "./index.d.ts",
|
|
14
|
+
"import": "./index.js"
|
|
15
|
+
},
|
|
16
|
+
"./testing": {
|
|
17
|
+
"types": "./testing.d.ts",
|
|
18
|
+
"import": "./testing.js"
|
|
19
|
+
},
|
|
20
|
+
"./native": {
|
|
21
|
+
"types": "./native.d.ts",
|
|
22
|
+
"import": "./src/index.mjs"
|
|
23
|
+
}
|
|
24
|
+
},
|
|
25
|
+
"files": [
|
|
26
|
+
"*.js",
|
|
27
|
+
"*.d.ts",
|
|
28
|
+
"catalog.json",
|
|
29
|
+
"schemas",
|
|
30
|
+
"README.md",
|
|
31
|
+
"src",
|
|
32
|
+
"runtime",
|
|
33
|
+
"portable"
|
|
34
|
+
],
|
|
35
|
+
"scripts": {
|
|
36
|
+
"test": "node --test test/*.test.js",
|
|
37
|
+
"typecheck": "tsc --noEmit --strict --module nodenext --moduleResolution nodenext test/types.ts",
|
|
38
|
+
"native:test": "node --test test/native-*.test.*",
|
|
39
|
+
"native:test:bun": "bun test test/native-*.test.*",
|
|
40
|
+
"native:typecheck": "tsc --noEmit --strict --module nodenext --moduleResolution nodenext test/native-types.ts"
|
|
41
|
+
},
|
|
42
|
+
"dependencies": {
|
|
43
|
+
"@iarna/toml": "3.0.0",
|
|
44
|
+
"ajv": "^8.17.1"
|
|
45
|
+
},
|
|
46
|
+
"devDependencies": {
|
|
47
|
+
"@types/node": "^20.19.0",
|
|
48
|
+
"typescript": "^5.9.3"
|
|
49
|
+
},
|
|
50
|
+
"repository": {
|
|
51
|
+
"type": "git",
|
|
52
|
+
"url": "https://github.com/link-assistant/router.git",
|
|
53
|
+
"directory": "js"
|
|
54
|
+
},
|
|
55
|
+
"license": "Unlicense",
|
|
56
|
+
"publishConfig": {
|
|
57
|
+
"access": "public",
|
|
58
|
+
"provenance": true
|
|
59
|
+
},
|
|
60
|
+
"bin": {
|
|
61
|
+
"router-native": "src/cli.mjs"
|
|
62
|
+
}
|
|
63
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
// Authoritative JavaScript policy kernels. Both native target languages are
|
|
2
|
+
// regenerated from these declarations, never maintained as parallel copies.
|
|
3
|
+
|
|
4
|
+
/** @param {number} used @param {number} reserved @param {number} reserve @param {number} max @returns {boolean} */
|
|
5
|
+
export function tokenBudgetPermits(used, reserved, reserve, max) {
|
|
6
|
+
return max < 0 || used + reserved < max && used + reserved + reserve <= max;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** @param {number} until @param {number} now @returns {boolean} */
|
|
10
|
+
export function cooldownActive(until, now) {
|
|
11
|
+
return until > now;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** @param {string} provider @param {string} model @returns {string} */
|
|
15
|
+
export function providerModelId(provider, model) {
|
|
16
|
+
return provider + '/' + model;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** @param {number} value @param {number} minimum @param {number} maximum @returns {number} */
|
|
20
|
+
export function clamp(value, minimum, maximum) {
|
|
21
|
+
return Math.min(Math.max(value, minimum), maximum);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** @param {number} previous @param {number} next @returns {number} */
|
|
25
|
+
export function longestCooldown(previous, next) {
|
|
26
|
+
return Math.max(previous, next);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** @param {number} seconds @param {number} now @param {number} maximum @returns {number} */
|
|
30
|
+
export function retryAfterDeadline(seconds, now, maximum) {
|
|
31
|
+
if (!Number.isFinite(seconds) || seconds < 0) {
|
|
32
|
+
return now;
|
|
33
|
+
}
|
|
34
|
+
return now + clamp(seconds, 0, maximum);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** @param {number} input @param {number} output @param {number} inputPerMillion @param {number} outputPerMillion @returns {number} */
|
|
38
|
+
export function tokenCost(input, output, inputPerMillion, outputPerMillion) {
|
|
39
|
+
return (input * inputPerMillion + output * outputPerMillion) / 1000000;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** @param {number} value @returns {boolean} */
|
|
43
|
+
export function validTokenCount(value) {
|
|
44
|
+
return Number.isFinite(value) && value >= 0 && Math.floor(value) === value;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** @param {number} total @param {number} reserved @param {number} actual @returns {number} */
|
|
48
|
+
export function settledTokenUsage(total, reserved, actual) {
|
|
49
|
+
return Math.max(0, total - reserved) + actual;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** @param {number} used @param {number} reserved @param {number} max @returns {number} */
|
|
53
|
+
export function remainingTokenBudget(used, reserved, max) {
|
|
54
|
+
if (max < 0) {
|
|
55
|
+
return -1;
|
|
56
|
+
}
|
|
57
|
+
return Math.max(0, max - used - reserved);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** @param {number} requested @param {number} available @param {number} limit @returns {number} */
|
|
61
|
+
export function completionTokenLimit(requested, available, limit) {
|
|
62
|
+
return Math.max(0, Math.floor(Math.min(requested, Math.min(available, limit))));
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** @param {number} failures @param {number} base @param {number} maximum @returns {number} */
|
|
66
|
+
export function retryBackoff(failures, base, maximum) {
|
|
67
|
+
let delay = base;
|
|
68
|
+
let remaining = Math.max(0, Math.floor(failures));
|
|
69
|
+
while (remaining > 0 && delay < maximum) {
|
|
70
|
+
delay = Math.min(delay * 2, maximum);
|
|
71
|
+
remaining = remaining - 1;
|
|
72
|
+
}
|
|
73
|
+
return Math.min(delay, maximum);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** @param {number} status @returns {boolean} */
|
|
77
|
+
export function retryableStatus(status) {
|
|
78
|
+
return status === 408 || status === 429 || status >= 500 && status <= 599;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** @param {number} status @returns {boolean} */
|
|
82
|
+
export function successStatus(status) {
|
|
83
|
+
return status >= 200 && status <= 299;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** @param {number} weight @param {number} load @returns {number} */
|
|
87
|
+
export function weightedCapacity(weight, load) {
|
|
88
|
+
if (weight <= 0 || !Number.isFinite(weight) || load < 0) {
|
|
89
|
+
return 0;
|
|
90
|
+
}
|
|
91
|
+
return weight / (load + 1);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** @param {number} now @param {number} expires @param {number} skew @returns {boolean} */
|
|
95
|
+
export function tokenExpired(now, expires, skew) {
|
|
96
|
+
return now >= expires + skew;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** @param {string} model @returns {boolean} */
|
|
100
|
+
export function isQualifiedModel(model) {
|
|
101
|
+
return model.includes('/');
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** @param {string} value @param {string} prefix @returns {boolean} */
|
|
105
|
+
export function credentialPrefixMatches(value, prefix) {
|
|
106
|
+
return value.startsWith(prefix);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** @param {string} value @returns {number} */
|
|
110
|
+
export function utf16Length(value) {
|
|
111
|
+
return value.length;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** @param {string} value @param {number} maximum @returns {boolean} */
|
|
115
|
+
export function modelNameLengthPermits(value, maximum) {
|
|
116
|
+
return utf16Length(value) > 0 && utf16Length(value) <= maximum;
|
|
117
|
+
}
|