@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
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
// Native request-log inspection, following src/log_analysis.rs and lino_json.rs.
|
|
2
|
+
import { open, lstat, readdir, mkdir, mkdtemp, rename, chmod, rm } from 'node:fs/promises';
|
|
3
|
+
import { constants } from 'node:fs';
|
|
4
|
+
import { resolve, join, dirname, parse } from 'node:path';
|
|
5
|
+
import * as zlib from 'node:zlib';
|
|
6
|
+
import { promisify } from 'node:util';
|
|
7
|
+
import { execFile } from 'node:child_process';
|
|
8
|
+
import { isIP } from 'node:net';
|
|
9
|
+
|
|
10
|
+
const exec = promisify(execFile);
|
|
11
|
+
const tlsTasks = new Map();
|
|
12
|
+
const MAX_BYTES = 256 * 1024 * 1024, MAX_FILES = 10000, MAX_DEPTH = 128;
|
|
13
|
+
const unsupported = message => Object.assign(new Error(message), { code:'unsupported' });
|
|
14
|
+
const bad = message => Object.assign(new Error(message), { code:'invalid_resource' });
|
|
15
|
+
export const supportedResourceOperations = Object.freeze({
|
|
16
|
+
'logs.show': { status:'partial', limitations:['Local logs only; 256 MiB / 10000-file read budget; symlinks refused; zstd needs a Node runtime with zstdDecompressSync.'] },
|
|
17
|
+
'logs.summary': { status:'partial', limitations:['Local logs only; 256 MiB / 10000-file read budget; symlinks refused; zstd needs a Node runtime with zstdDecompressSync.'] },
|
|
18
|
+
'logs.anomalies': { status:'partial', limitations:['Local logs only; 256 MiB / 10000-file read budget; symlinks refused; zstd needs a Node runtime with zstdDecompressSync.'] },
|
|
19
|
+
'tls.ca': { status:'partial', limitations:['Local generated certificate only; symlinks refused; PEM size bounded to 1 MiB.'] },
|
|
20
|
+
'tls.generate': { status:'partial', limitations:['Local only; requires openssl on PATH; validates names; symlinks refused; existing complete pair reused.'] },
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
// The three on-disk generations are JSONL, colon-pair lino, and marked lino.
|
|
24
|
+
export function decodeLogLine(source) {
|
|
25
|
+
const text = source.trim(); if (!text) return undefined;
|
|
26
|
+
if (/^[\[{]/.test(text)) { try { return JSON.parse(text); } catch { return undefined; } }
|
|
27
|
+
let pos = 0;
|
|
28
|
+
const space = () => { while (/\s/.test(text[pos] ?? '') && pos < text.length) pos++; };
|
|
29
|
+
const expect = char => { if (text[pos++] !== char) throw bad('Malformed log record'); };
|
|
30
|
+
const quoted = escaped => {
|
|
31
|
+
expect('"'); let value = '', closed = false;
|
|
32
|
+
while (pos < text.length) {
|
|
33
|
+
const ch = text[pos++]; if (ch === '"') { closed = true; break; }
|
|
34
|
+
if (ch === '\\') { const next = text[pos++]; if (next === undefined) throw bad('Malformed quoted record'); value += next === 'n' ? '\n' : next === 'r' ? '\r' : next; }
|
|
35
|
+
else value += ch;
|
|
36
|
+
}
|
|
37
|
+
if (!closed) throw bad('Malformed quoted record');
|
|
38
|
+
return escaped ? value === '%z' ? '' : value.replace(/%([0-9a-fA-F]{2})/g, (_, hex) => String.fromCharCode(parseInt(hex,16))) : value;
|
|
39
|
+
};
|
|
40
|
+
const value = (escaped = false, depth = 0) => {
|
|
41
|
+
if (depth > MAX_DEPTH) throw bad('Log record nesting exceeds 128');
|
|
42
|
+
space(); if (text[pos] === '"') return quoted(escaped);
|
|
43
|
+
if (text[pos] !== '(') {
|
|
44
|
+
const start = pos; while (pos < text.length && !/[\s()]/.test(text[pos])) pos++;
|
|
45
|
+
const token = text.slice(start,pos);
|
|
46
|
+
if (['null','true','false'].includes(token)) return JSON.parse(token);
|
|
47
|
+
if (!/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(token)) throw bad('Malformed scalar record');
|
|
48
|
+
const number = Number(token); if (!Number.isFinite(number)) throw bad('Invalid number'); return number;
|
|
49
|
+
}
|
|
50
|
+
pos++; space(); let marker = null;
|
|
51
|
+
if (text[pos] === '#') { marker = text.slice(pos,pos+2); pos += 2; if (!['#a','#o'].includes(marker)) throw bad('Invalid marker'); }
|
|
52
|
+
const object = Object.create(null), items = []; let keyed = true, pairs = 0;
|
|
53
|
+
while (true) {
|
|
54
|
+
space(); if (pos >= text.length) throw bad('Unclosed record');
|
|
55
|
+
if (text[pos] === ')') { pos++; break; }
|
|
56
|
+
if (marker === '#o' || (!marker && text[pos] === '(' && text[pos+1] === ':')) {
|
|
57
|
+
expect('('); if (!marker) expect(':'); space(); const name = quoted(marker === '#o');
|
|
58
|
+
object[name] = value(marker === '#o',depth+1); space(); expect(')'); pairs++;
|
|
59
|
+
} else { keyed = false; items.push(value(marker === '#a',depth+1)); }
|
|
60
|
+
}
|
|
61
|
+
if (marker === '#o' || (!marker && keyed && pairs)) return object;
|
|
62
|
+
if (!marker && !pairs && !items.length) return null;
|
|
63
|
+
return items;
|
|
64
|
+
};
|
|
65
|
+
try { const record = value(text[0] !== '('); space(); return pos === text.length ? record : undefined; }
|
|
66
|
+
catch { return undefined; }
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async function statOptional(path) { try { return await lstat(path); } catch (error) { if (error.code === 'ENOENT') return null; throw error; } }
|
|
70
|
+
async function noLinks(path) {
|
|
71
|
+
let current = resolve(path), hops = 0;
|
|
72
|
+
while (true) {
|
|
73
|
+
const stat = await statOptional(current); if (stat?.isSymbolicLink()) throw bad(`Resource path contains a symlink: ${current}`);
|
|
74
|
+
if (current === parse(current).root) break;
|
|
75
|
+
current = dirname(current); if (++hops > 256) throw bad('Resource path is too deep');
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
async function boundedFile(path, budget) {
|
|
79
|
+
await noLinks(path);
|
|
80
|
+
const handle = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
81
|
+
try {
|
|
82
|
+
const stat = await handle.stat(); if (!stat.isFile()) throw bad(`Resource requires a regular file: ${path}`);
|
|
83
|
+
if (stat.size > budget.remaining) throw unsupported(`Resource read exceeds the ${budget.limit} byte budget`);
|
|
84
|
+
const chunks = []; let total = 0;
|
|
85
|
+
while (true) {
|
|
86
|
+
const chunk = Buffer.alloc(Math.min(65536,budget.remaining-total+1));
|
|
87
|
+
const { bytesRead } = await handle.read(chunk,0,chunk.length,null); if (!bytesRead) break;
|
|
88
|
+
total += bytesRead; if (total > budget.remaining) throw unsupported(`Resource read exceeds the ${budget.limit} byte budget`);
|
|
89
|
+
chunks.push(chunk.subarray(0,bytesRead));
|
|
90
|
+
}
|
|
91
|
+
budget.remaining -= total; return Buffer.concat(chunks,total);
|
|
92
|
+
} finally { await handle.close(); }
|
|
93
|
+
}
|
|
94
|
+
function utf8(bytes,path) {
|
|
95
|
+
try { return new TextDecoder('utf-8',{fatal:true}).decode(bytes); }
|
|
96
|
+
catch { throw bad(`Resource is not valid UTF-8: ${path}`); }
|
|
97
|
+
}
|
|
98
|
+
export async function readNativeRequestLogs(root, token) {
|
|
99
|
+
await noLinks(root); const rootStat = await statOptional(root);
|
|
100
|
+
if (!rootStat?.isDirectory()) return { files:[], bytes:0, unparsable:0 };
|
|
101
|
+
const files = [];
|
|
102
|
+
for (const name of (await readdir(root)).sort()) {
|
|
103
|
+
if (token !== undefined && !name.startsWith(token)) continue;
|
|
104
|
+
const directory = join(root,name), stat = await lstat(directory);
|
|
105
|
+
if (stat.isSymbolicLink()) throw bad(`Request-log directory is a symlink: ${directory}`);
|
|
106
|
+
if (!stat.isDirectory()) continue;
|
|
107
|
+
for (const filename of ['requests.lino','requests.jsonl']) {
|
|
108
|
+
const path = join(directory,filename), info = await statOptional(path);
|
|
109
|
+
if (!info) continue;
|
|
110
|
+
if (info.isSymbolicLink() || !info.isFile()) throw bad(`Request-log path is not a regular file: ${path}`);
|
|
111
|
+
files.push(path); if (files.length > MAX_FILES) throw unsupported('Request-log file count exceeds 10000');
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
const budget = {remaining:MAX_BYTES,limit:MAX_BYTES}, decoded = []; let unparsable = 0;
|
|
115
|
+
for (const path of files.sort()) {
|
|
116
|
+
const bytes = await boundedFile(path,budget);
|
|
117
|
+
// Rust read_to_string refuses invalid UTF-8; replacement could hide corruption.
|
|
118
|
+
const text = utf8(bytes,path);
|
|
119
|
+
const records = [];
|
|
120
|
+
for (const line of text.split(/\r?\n/)) {
|
|
121
|
+
if (!line.trim()) continue; const record = decodeLogLine(line);
|
|
122
|
+
if (record === undefined) unparsable++; else records.push(record);
|
|
123
|
+
}
|
|
124
|
+
decoded.push(records);
|
|
125
|
+
}
|
|
126
|
+
return { files:decoded, bytes:MAX_BYTES-budget.remaining, unparsable };
|
|
127
|
+
}
|
|
128
|
+
const terminates = text => ['message_stop','[DONE]','response.completed','finishReason'].some(marker => text.includes(marker));
|
|
129
|
+
function encoding(header) { return (header ?? 'identity').split(',').map(s=>s.trim()).filter(Boolean).at(-1)?.toLowerCase() ?? 'identity'; }
|
|
130
|
+
function base64Bytes(text) { return typeof text === 'string' && /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(text) ? Buffer.from(text,'base64') : null; }
|
|
131
|
+
function decompress(bytes, kind) {
|
|
132
|
+
if (kind === 'identity' || !bytes.length) return null;
|
|
133
|
+
const decoders = {gzip:zlib.gunzipSync,'x-gzip':zlib.gunzipSync,deflate:zlib.inflateRawSync,br:zlib.brotliDecompressSync,zstd:zlib.zstdDecompressSync};
|
|
134
|
+
if (kind === 'zstd' && !decoders.zstd) throw unsupported('zstd request-log decoding requires a Node runtime with zstdDecompressSync');
|
|
135
|
+
if (!decoders[kind]) return null;
|
|
136
|
+
try {
|
|
137
|
+
const decoded = decoders[kind](bytes,{finishFlush:zlib.constants.Z_SYNC_FLUSH,maxOutputLength:MAX_BYTES});
|
|
138
|
+
return decoded.length ? decoded.toString('utf8') : null;
|
|
139
|
+
} catch (error) {
|
|
140
|
+
if (error.code === 'ERR_BUFFER_TOO_LARGE') throw unsupported('Decoded request body exceeds the 256 MiB budget');
|
|
141
|
+
return null;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
function exchanges(log) {
|
|
145
|
+
const map = new Map();
|
|
146
|
+
for (const record of log.files.flat()) {
|
|
147
|
+
if (!record || typeof record.correlation_id !== 'string') continue;
|
|
148
|
+
const id = record.correlation_id;
|
|
149
|
+
const x = map.get(id) ?? {id,records:0,streamed:false,evidence:false,requested:false,inspectable:true,terminated:false,undecodable:0,encoded:[],kind:'identity'};
|
|
150
|
+
map.set(id,x); x.records++;
|
|
151
|
+
if (record.phase === 'client_request') {
|
|
152
|
+
if (record.body && typeof record.body === 'object' && 'base64' in record.body) x.undecodable++;
|
|
153
|
+
if (record.body?.json?.stream === true) x.requested = true;
|
|
154
|
+
}
|
|
155
|
+
if (['client_response','upstream_response'].includes(record.phase)) {
|
|
156
|
+
const status = Number.isSafeInteger(record.status) && record.status >= 0 ? record.status : undefined;
|
|
157
|
+
if (record.phase === 'client_response') x.status = status; else x.upstream = status;
|
|
158
|
+
if (typeof record.headers?.['content-encoding'] === 'string') x.kind = encoding(record.headers['content-encoding']);
|
|
159
|
+
const type = record.headers?.['content-type'];
|
|
160
|
+
if (typeof type === 'string' && type.split(';')[0].trim()) { x.evidence = true; x.streamed = type.split(';')[0].trim().toLowerCase() === 'text/event-stream'; }
|
|
161
|
+
}
|
|
162
|
+
if (['client_response_body','upstream_response_body'].includes(record.phase)) {
|
|
163
|
+
if (typeof record.body?.base64 === 'string') {
|
|
164
|
+
if (record.phase === 'upstream_response_body') { x.undecodable++; const bytes = base64Bytes(record.body.base64); if (bytes) x.encoded.push(bytes); }
|
|
165
|
+
} else if (record.body != null && terminates(typeof record.body === 'string' ? record.body : JSON.stringify(record.body))) x.terminated = true;
|
|
166
|
+
}
|
|
167
|
+
if (record.phase === 'stream_end') {
|
|
168
|
+
if (!x.evidence) x.streamed = true;
|
|
169
|
+
x.outcome = typeof record.outcome === 'string' ? record.outcome : undefined;
|
|
170
|
+
x.complete = typeof record.complete === 'boolean' ? record.complete : undefined;
|
|
171
|
+
if (typeof record.inspectable === 'boolean') x.inspectable = record.inspectable;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
for (const x of map.values()) {
|
|
175
|
+
if (!['identity','gzip','x-gzip','deflate','br','zstd'].includes(x.kind)) x.inspectable = false;
|
|
176
|
+
else if (x.kind !== 'identity' && x.encoded.length) {
|
|
177
|
+
const decoded = decompress(Buffer.concat(x.encoded),x.kind);
|
|
178
|
+
if (!decoded) x.inspectable = false;
|
|
179
|
+
else {
|
|
180
|
+
x.inspectable = true; x.undecodable = 0;
|
|
181
|
+
x.error = decoded.split(/\r?\n/).some(line => {
|
|
182
|
+
const text = line.trim(); if (text.toLowerCase() === 'event: error') return true;
|
|
183
|
+
if (!text.startsWith('data:')) return false;
|
|
184
|
+
try { return JSON.parse(text.slice(5).trim()).type === 'error'; } catch { return false; }
|
|
185
|
+
});
|
|
186
|
+
if (terminates(decoded)) { x.terminated = true; if (x.complete === false) {x.complete = true; x.outcome = 'completed';} }
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
if (!x.evidence && x.requested) x.streamed = true;
|
|
190
|
+
}
|
|
191
|
+
return [...map.values()].sort((a,b)=>a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
|
|
192
|
+
}
|
|
193
|
+
const incomplete = x => x.streamed && x.inspectable && x.complete === false;
|
|
194
|
+
const unterminated = x => x.streamed && x.inspectable && x.outcome === undefined && !x.terminated;
|
|
195
|
+
const unverifiable = x => x.streamed && !x.inspectable;
|
|
196
|
+
function summary(log, all) {
|
|
197
|
+
const result = {exchanges:all.length,records:0,bytes:log.bytes,statuses:{},streamed:0,non_streamed:0,incomplete_streams:0,unterminated_streams:0,unverifiable_streams:0,unparsable_records:log.unparsable,undecodable_bodies:0};
|
|
198
|
+
for (const x of all) {
|
|
199
|
+
result.records += x.records; result.undecodable_bodies += x.undecodable;
|
|
200
|
+
const status = x.status ?? x.upstream; if (status !== undefined) result.statuses[status] = (result.statuses[status] ?? 0)+1;
|
|
201
|
+
result[x.streamed ? 'streamed' : 'non_streamed']++;
|
|
202
|
+
if (incomplete(x)) result.incomplete_streams++;
|
|
203
|
+
if (unterminated(x)) result.unterminated_streams++;
|
|
204
|
+
if (unverifiable(x)) result.unverifiable_streams++;
|
|
205
|
+
}
|
|
206
|
+
return result;
|
|
207
|
+
}
|
|
208
|
+
function anomalies(all) {
|
|
209
|
+
const result = [], add = (kind, detail, test, minimum = 1) => {
|
|
210
|
+
const ids = all.filter(test).map(x=>x.id); if (ids.length >= minimum) result.push({kind,detail:typeof detail === 'function' ? detail(ids.length) : detail,correlation_ids:ids});
|
|
211
|
+
};
|
|
212
|
+
add('stream_ended_without_terminator','a streamed turn stopped before its dialect terminator; the client saw a truncated answer while the status line said 200',incomplete);
|
|
213
|
+
add('no_terminal_record','a streamed exchange has no terminal record, so how it ended is unknown',unterminated);
|
|
214
|
+
add('stream_carried_an_error','a streamed turn carried an error event while the status line said 200, so the transport reported success for a turn that failed',x=>x.error);
|
|
215
|
+
add('stream_not_verifiable','a streamed exchange was relayed under an encoding this router cannot decode, so its frames cannot be inspected for a terminator; how it ended is not knowable from the log',unverifiable);
|
|
216
|
+
add('repeated_authentication_failure',n=>`${n} exchanges were refused with 401/403, which is misconfiguration rather than load`,x=>[401,403].includes(x.status),2);
|
|
217
|
+
add('rate_limited',n=>`${n} exchanges were rate limited`,x=>x.status === 429);
|
|
218
|
+
add('undecodable_bodies','bodies are compressed or binary, so their contents cannot be inspected from the log; recorded so absence of evidence is not read as evidence',x=>x.undecodable > 0);
|
|
219
|
+
return result;
|
|
220
|
+
}
|
|
221
|
+
function show(log,id) {
|
|
222
|
+
const records = [];
|
|
223
|
+
for (const file of log.files) {
|
|
224
|
+
const selected = file.filter(record=>record?.correlation_id === id);
|
|
225
|
+
const header = selected.find(record=>typeof record.headers?.['content-encoding'] === 'string')?.headers['content-encoding'];
|
|
226
|
+
const stored = selected.map(record=>base64Bytes(record.body?.base64)).filter(Boolean);
|
|
227
|
+
const decoded = decompress(Buffer.concat(stored),encoding(header));
|
|
228
|
+
const first = selected.findIndex(record=>typeof record.body?.base64 === 'string');
|
|
229
|
+
for (const [index,record] of selected.entries()) records.push(decoded && typeof record.body?.base64 === 'string' ? {...record,body:index === first ? decoded : '[decoded with the first frame: only the whole stream decodes]'} : record);
|
|
230
|
+
}
|
|
231
|
+
const output = records.length ? records.flatMap(record=>JSON.stringify(record,null,2).split('\n')) : [`no records for correlation id ${id}`];
|
|
232
|
+
return {correlation_id:id,records,output};
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
async function tlsGenerate(dataDir,dns) {
|
|
236
|
+
const directory = join(dataDir,'tls'), cert = join(directory,'cert.pem'), key = join(directory,'key.pem');
|
|
237
|
+
await noLinks(directory); await noLinks(cert); await noLinks(key);
|
|
238
|
+
const certStat = await statOptional(cert), keyStat = await statOptional(key);
|
|
239
|
+
if (certStat?.isFile() && keyStat?.isFile()) return {output:[cert]};
|
|
240
|
+
if ((certStat && !certStat.isFile()) || (keyStat && !keyStat.isFile())) throw bad('TLS certificate and key paths must be regular files');
|
|
241
|
+
const names = [...new Set(String(dns ?? 'localhost').split(',').map(s=>s.trim()).filter(Boolean).concat('localhost','127.0.0.1'))];
|
|
242
|
+
if (names.length > 100 || names.some(name=> !isIP(name) && !/^(?:\*\.)?[A-Za-z0-9](?:[A-Za-z0-9.-]{0,251}[A-Za-z0-9])?$/.test(name))) throw bad('TLS names must be DNS names or IP addresses (at most 100 names)');
|
|
243
|
+
await mkdir(directory,{recursive:true,mode:0o700}); await chmod(directory,0o700);
|
|
244
|
+
const temporary = await mkdtemp(join(directory,'.generate-'));
|
|
245
|
+
try {
|
|
246
|
+
await exec('openssl',['req','-x509','-newkey','ec','-pkeyopt','ec_paramgen_curve:P-256','-nodes','-sha256','-days','3650','-subj','/CN=rcgen self signed cert','-addext',`subjectAltName=${names.map(name=>`${isIP(name) ? 'IP' : 'DNS'}:${name}`).join(',')}`,'-keyout',join(temporary,'key.pem'),'-out',join(temporary,'cert.pem')],{timeout:10000,maxBuffer:1024*1024,windowsHide:true});
|
|
247
|
+
await chmod(join(temporary,'key.pem'),0o600); await chmod(join(temporary,'cert.pem'),0o600);
|
|
248
|
+
await rename(join(temporary,'cert.pem'),cert); await rename(join(temporary,'key.pem'),key);
|
|
249
|
+
} catch (error) {
|
|
250
|
+
if (error.code === 'ENOENT') throw unsupported('Native tls.generate requires openssl on PATH');
|
|
251
|
+
throw bad('Could not generate a self-signed TLS certificate');
|
|
252
|
+
} finally { await rm(temporary,{recursive:true,force:true}); }
|
|
253
|
+
return {output:[cert]};
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
async function serializedTlsGenerate(dataDir,dns) {
|
|
257
|
+
const before = tlsTasks.get(dataDir) ?? Promise.resolve();
|
|
258
|
+
const task = before.catch(()=>{}).then(()=>tlsGenerate(dataDir,dns));
|
|
259
|
+
tlsTasks.set(dataDir,task);
|
|
260
|
+
try { return await task; } finally { if (tlsTasks.get(dataDir) === task) tlsTasks.delete(dataDir); }
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
export async function executeResourceOperation({name,options = {},config = {},core}) {
|
|
264
|
+
if (!supportedResourceOperations[name]) throw unsupported(`Native resource operation ${name} is unavailable`);
|
|
265
|
+
const accepted = new Set(['data_dir','home','local','json',...(name.startsWith('logs.') ? ['token','correlation_id','request_log'] : name === 'tls.generate' ? ['dns'] : [])]);
|
|
266
|
+
for (const [key,value] of Object.entries(options)) if (value !== undefined && value !== false && !accepted.has(key)) throw unsupported(`Native ${name} does not support option ${key}`);
|
|
267
|
+
const resolvedConfig = core?.config ?? config;
|
|
268
|
+
const dataDir = options.data_dir ?? resolvedConfig.data_dir ?? resolvedConfig.dataDir;
|
|
269
|
+
if (typeof dataDir !== 'string' || !dataDir) throw bad('Resource operation requires a resolved data directory');
|
|
270
|
+
if (name === 'tls.generate') return serializedTlsGenerate(resolve(dataDir),options.dns);
|
|
271
|
+
if (name === 'tls.ca') {
|
|
272
|
+
const path = join(resolve(dataDir),'tls','cert.pem');
|
|
273
|
+
try {
|
|
274
|
+
const bytes = await boundedFile(path,{remaining:1024*1024,limit:1024*1024});
|
|
275
|
+
const output = utf8(bytes,path).split(/\r?\n/); if (output.at(-1) === '') output.pop();
|
|
276
|
+
return {output};
|
|
277
|
+
}
|
|
278
|
+
catch (error) { if (error.code === 'ENOENT') throw bad(`no generated certificate at ${path}; start the router with TLS_SELF_SIGNED=1 first`); throw error; }
|
|
279
|
+
}
|
|
280
|
+
if (options.token !== undefined && typeof options.token !== 'string') throw bad('Log token filter must be a string');
|
|
281
|
+
if (name === 'logs.show' && typeof options.correlation_id !== 'string') throw bad('logs.show requires correlation_id');
|
|
282
|
+
const root = options.request_log ?? resolvedConfig.request_log ?? join(dataDir,'requests');
|
|
283
|
+
const log = await readNativeRequestLogs(root,options.token);
|
|
284
|
+
if (name === 'logs.show') return show(log,options.correlation_id);
|
|
285
|
+
const all = exchanges(log);
|
|
286
|
+
if (name === 'logs.summary') return summary(log,all);
|
|
287
|
+
const found = anomalies(all);
|
|
288
|
+
if (found.length) throw Object.assign(new Error('Request-log anomalies found'),{data:found,exitCode:1});
|
|
289
|
+
return found;
|
|
290
|
+
}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { ProtocolError } from './protocols.mjs';
|
|
2
|
+
|
|
3
|
+
// Sources: proxy_openai_resource.rs::state_for_previous_response,
|
|
4
|
+
// native_service_resources.rs::response_references, responses_lifecycle.rs.
|
|
5
|
+
// Provider-owned background jobs are relayed; this module creates no worker.
|
|
6
|
+
export function responseContract(method, path) {
|
|
7
|
+
const match = /^(\/api\/services\/(openai|codex|qwen)\/v1|\/v1)\/responses(?:\/(.*))?$/.exec(path);
|
|
8
|
+
if (!match) return null;
|
|
9
|
+
const namespace = `${match[1]}/responses`, service = match[2] ?? 'openai', tail = match[3];
|
|
10
|
+
if (tail === undefined && method === 'POST') return { namespace, service, create: true };
|
|
11
|
+
if (['compact', 'input_tokens'].includes(tail) && method === 'POST') return { namespace, service, helper: tail };
|
|
12
|
+
if (tail && !['compact', 'input_tokens'].includes(tail)) return { namespace, service, lifecycle: true };
|
|
13
|
+
return null;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function validateResponseCreate(contract, document) {
|
|
17
|
+
if (!contract?.create) return;
|
|
18
|
+
if (!document || typeof document !== 'object' || Array.isArray(document)) throw new ProtocolError('The Responses request body must be a JSON object');
|
|
19
|
+
if (typeof document.model !== 'string' || !document.model) {
|
|
20
|
+
const error = new ProtocolError('request model must be a non-empty exact catalog id'); error.code = 'model_required'; throw error;
|
|
21
|
+
}
|
|
22
|
+
if (Object.hasOwn(document, 'previous_response_id') && (typeof document.previous_response_id !== 'string' || !document.previous_response_id)) throw new ProtocolError('previous_response_id must be a non-empty string');
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function responseReferences(contract, document) {
|
|
26
|
+
if (!contract || !document || typeof document !== 'object') return [];
|
|
27
|
+
const references = [];
|
|
28
|
+
if ((contract.create || contract.helper) && typeof document.previous_response_id === 'string' && document.previous_response_id) {
|
|
29
|
+
// Rust deliberately preserves older provider-created continuation IDs on
|
|
30
|
+
// create. Helpers require a known owner affinity; they cannot route a legacy
|
|
31
|
+
// identifier to an arbitrary provider.
|
|
32
|
+
references.push({ namespace: contract.namespace, id: document.previous_response_id, allowMissing: Boolean(contract.create) });
|
|
33
|
+
}
|
|
34
|
+
if (contract.helper === 'input_tokens' && contract.service === 'openai') {
|
|
35
|
+
const id = typeof document.conversation === 'string' ? document.conversation : document.conversation?.id;
|
|
36
|
+
if (typeof id === 'string' && id) references.push({ namespace: contract.namespace.replace(/\/responses$/, '/conversations'), id, allowMissing: false });
|
|
37
|
+
}
|
|
38
|
+
return references;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function responseNotFound() {
|
|
42
|
+
return Response.json({ error: { message: 'Response not found', type: 'invalid_request_error', param: null, code: 'response_not_found' } }, { status: 404 });
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function responseReferenceMissing() {
|
|
46
|
+
return Response.json({ error: { type: 'not_found_error', message: 'the referenced response resource is unavailable' } }, { status: 404 });
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function responseReferenceConflict() {
|
|
50
|
+
return Response.json({ error: { type: 'invalid_request_error', message: 'the referenced response resources do not share one provider account' } }, { status: 409 });
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function responseAffinityStorageError(error) {
|
|
54
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
55
|
+
return Response.json({ error: { type: 'api_error', message: `response affinity is unavailable: ${message}` } }, { status: 503 });
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Conversations are provider-owned resources, including child identities. The
|
|
59
|
+
// source handlers consume opaque bodies; item-list parse failures mean no IDs
|
|
60
|
+
// were captured, rather than replacing the provider's successful body.
|
|
61
|
+
export function conversationContract(method, path) {
|
|
62
|
+
const match = /^\/api\/services\/(openai|codex|qwen)\/v1\/conversations(?:\/([^/]+)(?:\/(items)(?:\/([^/]+))?)?)?$/.exec(path);
|
|
63
|
+
if (!match) return null;
|
|
64
|
+
let id, item;
|
|
65
|
+
try { id = match[2] === undefined ? undefined : decodeURIComponent(match[2]); item = match[4] === undefined ? undefined : decodeURIComponent(match[4]); }
|
|
66
|
+
catch { throw new ProtocolError('Conversation resource path contains invalid percent encoding'); }
|
|
67
|
+
const namespace = `/api/services/${match[1]}/v1/conversations`, itemNamespace = namespace + '/items';
|
|
68
|
+
const target = id === undefined ? 'create' : !match[3] ? 'conversation' : item === undefined ? 'items' : 'item';
|
|
69
|
+
const allowed = { create: ['POST'], conversation: ['GET', 'PATCH', 'DELETE'], items: ['GET', 'POST'], item: ['GET', 'DELETE'] };
|
|
70
|
+
const segment = value => [...Buffer.from(value)].map(byte => byte >= 65 && byte <= 90 || byte >= 97 && byte <= 122 || byte >= 48 && byte <= 57 || [45,46,95,126].includes(byte) ? String.fromCharCode(byte) : '%' + byte.toString(16).toUpperCase().padStart(2,'0')).join('');
|
|
71
|
+
const forwardPath = namespace + (id === undefined ? '' : '/' + segment(id)) + (match[3] ? '/items' : '') + (item === undefined ? '' : '/' + segment(item));
|
|
72
|
+
return { namespace, itemNamespace, service: match[1], target, id, item, forwardPath, allowed: allowed[target].includes(method) };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function conversationNotFound(item = false) {
|
|
76
|
+
return Response.json({ error: { message: item ? 'Conversation item not found' : 'Conversation not found', type: 'invalid_request_error', param: null, code: item ? 'conversation_item_not_found' : 'conversation_not_found' } }, { status: 404 });
|
|
77
|
+
}
|
|
78
|
+
export function conversationUnsupported() {
|
|
79
|
+
return Response.json({ error: { type: 'invalid_request_error', message: 'the selected service does not support native Conversations resources' } }, { status: 400 });
|
|
80
|
+
}
|
|
81
|
+
export function conversationMethodNotAllowed() {
|
|
82
|
+
return Response.json({ error: { type: 'invalid_request_error', message: 'the requested Conversations operation is not supported' } }, { status: 405 });
|
|
83
|
+
}
|
|
84
|
+
export function conversationAffinityError(error) {
|
|
85
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
86
|
+
return Response.json({ error: { type: 'api_error', message: `resource affinity is unavailable: ${message}` } }, { status: 503 });
|
|
87
|
+
}
|
|
88
|
+
export function conversationUpstreamError(message) {
|
|
89
|
+
return Response.json({ error: { type: 'api_error', message } }, { status: 502 });
|
|
90
|
+
}
|
|
91
|
+
export function conversationIds(raw, list = false) {
|
|
92
|
+
let document; try { document = captureJsonValue(new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(raw)); } catch { return []; }
|
|
93
|
+
const items = list ? Array.isArray(document?.data) ? document.data : [] : [document];
|
|
94
|
+
return items.map(item => item?.id).filter(id => typeof id === 'string' && id);
|
|
95
|
+
}
|
|
96
|
+
export function validConversationId(id) {
|
|
97
|
+
return typeof id === 'string' && id.length > 0 && Buffer.byteLength(id) <= 256 && !/[\/\x00-\x1f\x7f-\x9f]/u.test(id);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// resource_capture.rs reads each SSE data line independently. Presence of a
|
|
101
|
+
// root id takes precedence even when its value is unusable; malformed lines
|
|
102
|
+
// are ignored while the bounded prefix waits for another resource identity.
|
|
103
|
+
function captureJsonValue(text) {
|
|
104
|
+
let value; try { value = JSON.parse(text); } catch { return undefined; }
|
|
105
|
+
// serde_json constructs Rust UTF-8 Strings, so isolated UTF-16 surrogate
|
|
106
|
+
// escapes are not usable JSON even in otherwise unused metadata or keys.
|
|
107
|
+
const scalar = string => {
|
|
108
|
+
for (let index=0;index<string.length;index++) {
|
|
109
|
+
const unit=string.charCodeAt(index);
|
|
110
|
+
if(unit>=0xd800 && unit<=0xdbff) { const next=string.charCodeAt(++index);if(!(next>=0xdc00 && next<=0xdfff))return false; }
|
|
111
|
+
else if(unit>=0xdc00 && unit<=0xdfff)return false;
|
|
112
|
+
}
|
|
113
|
+
return true;
|
|
114
|
+
};
|
|
115
|
+
const pending=[value];
|
|
116
|
+
while(pending.length) {
|
|
117
|
+
const current=pending.pop();
|
|
118
|
+
if(typeof current==='number' && !Number.isFinite(current))return undefined;
|
|
119
|
+
if(typeof current==='string' && !scalar(current))return undefined;
|
|
120
|
+
if(current && typeof current==='object') for(const [key,child] of Object.entries(current)) {
|
|
121
|
+
if(!scalar(key))return undefined;pending.push(child);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return value;
|
|
125
|
+
}
|
|
126
|
+
export function captureSseId(block) {
|
|
127
|
+
for (const line of block.split(/\r?\n/)) {
|
|
128
|
+
if (!line.startsWith('data:')) continue;
|
|
129
|
+
const payload = line.slice(5).replace(/^[\u0009-\u000d\u0020\u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]+|[\u0009-\u000d\u0020\u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]+$/gu,'');
|
|
130
|
+
const value = captureJsonValue(payload);
|
|
131
|
+
const id = value && typeof value === 'object' && Object.hasOwn(value,'id') ? value.id : value?.response?.id;
|
|
132
|
+
if (typeof id === 'string' && id) return id;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
export function captureJsonId(raw, fields = ['id']) {
|
|
136
|
+
let value; try { value = captureJsonValue(new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(raw)); } catch { return undefined; }
|
|
137
|
+
return fields.map(field => value?.[field]).find(id => typeof id === 'string' && id);
|
|
138
|
+
}
|
|
139
|
+
export function captureLocationId(headers) {
|
|
140
|
+
const location = headers.get('location');
|
|
141
|
+
if (!location) return undefined;
|
|
142
|
+
const path = location.split('?')[0].replace(/\/+$/,'');
|
|
143
|
+
return path.split('/').at(-1) || undefined;
|
|
144
|
+
}
|
|
145
|
+
export function resourceCaptureError(status, message) {
|
|
146
|
+
return Response.json({ error: { message, type: 'api_error', param: null, code: null } }, { status });
|
|
147
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { ProtocolError } from './protocols.mjs';
|
|
3
|
+
// Precharge the maximum extra JSON for runtime-owned cancel/fail transitions.
|
|
4
|
+
// The measured transition below must fit this allocation before it mutates.
|
|
5
|
+
const TRANSITION_RESERVE_BYTES = 256;
|
|
6
|
+
|
|
7
|
+
/** Foreground resources retained only in this runtime, with explicit bounds. */
|
|
8
|
+
export class ResponsesStore {
|
|
9
|
+
constructor({ clock = Date.now, ttlMs = 3_600_000, maxRecords = 1000, maxBytes = 16 * 1024 * 1024, maxRecordBytes = 1024 * 1024 } = {}) {
|
|
10
|
+
for (const [key, value] of Object.entries({ ttlMs, maxRecords, maxBytes, maxRecordBytes })) if (!Number.isSafeInteger(value) || value < 1) throw new TypeError(`${key} must be a positive safe integer`);
|
|
11
|
+
this.clock = clock; this.ttlMs = ttlMs; this.maxRecords = maxRecords; this.maxBytes = maxBytes; this.maxRecordBytes = maxRecordBytes; this.records = new Map(); this.bytes = 0;
|
|
12
|
+
}
|
|
13
|
+
key(namespace, owner, id) { return JSON.stringify([namespace, owner, id]); }
|
|
14
|
+
serializedBytes(record) { return Buffer.byteLength(JSON.stringify({ namespace: record.namespace, owner: record.owner, input: record.input, response: record.response })); }
|
|
15
|
+
size(record) { return TRANSITION_RESERVE_BYTES + this.serializedBytes(record); }
|
|
16
|
+
transition(record, fields) {
|
|
17
|
+
const next = { ...record, response: { ...record.response, ...fields } };
|
|
18
|
+
const bytes = this.serializedBytes(next);
|
|
19
|
+
if (bytes > record.bytes || bytes > this.maxRecordBytes) throw new ProtocolError('Response transition exceeds retention allocation', 507);
|
|
20
|
+
record.response = next.response;
|
|
21
|
+
}
|
|
22
|
+
sweep() {
|
|
23
|
+
for (const [key, record] of this.records) if (record.expiresAt <= this.clock()) { this.records.delete(key); this.bytes -= record.bytes; record.abort?.(); }
|
|
24
|
+
}
|
|
25
|
+
save(namespace, owner, response, input, { abort, update = false } = {}) {
|
|
26
|
+
if (typeof response.id !== 'string' || !response.id || response.id.length > 512) throw new ProtocolError('Upstream returned an invalid response id', 502);
|
|
27
|
+
this.sweep();
|
|
28
|
+
const key = this.key(namespace, owner, response.id), previous = this.records.get(key);
|
|
29
|
+
if (update && !previous) throw new ProtocolError('Response not found', 404);
|
|
30
|
+
if (previous && !update) throw new ProtocolError('Response id is already retained', 409);
|
|
31
|
+
if (previous?.response.status === 'cancelled') throw new ProtocolError('Response was cancelled', 409);
|
|
32
|
+
const record = { namespace, owner, response: structuredClone(response), input: structuredClone(input), abort, expiresAt: this.clock() + this.ttlMs };
|
|
33
|
+
record.bytes = this.size(record);
|
|
34
|
+
if (record.bytes > this.maxRecordBytes || record.bytes > this.maxBytes) throw new ProtocolError('Response exceeds retention storage limit', 507);
|
|
35
|
+
while (this.records.size - (previous ? 1 : 0) >= this.maxRecords || this.bytes - (previous?.bytes ?? 0) + record.bytes > this.maxBytes) {
|
|
36
|
+
const evict = [...this.records].find(([k, r]) => k !== key && !['in_progress', 'queued'].includes(r.response.status));
|
|
37
|
+
if (!evict) throw new ProtocolError('Response retention storage is full', 507);
|
|
38
|
+
this.records.delete(evict[0]); this.bytes -= evict[1].bytes;
|
|
39
|
+
}
|
|
40
|
+
this.bytes -= previous?.bytes ?? 0; this.bytes += record.bytes; this.records.set(key, record);
|
|
41
|
+
return structuredClone(record.response);
|
|
42
|
+
}
|
|
43
|
+
get(namespace, owner, id) {
|
|
44
|
+
this.sweep(); const record = this.records.get(this.key(namespace, owner, id));
|
|
45
|
+
if (!record) throw new ProtocolError('Response not found', 404);
|
|
46
|
+
return structuredClone(record.response);
|
|
47
|
+
}
|
|
48
|
+
delete(namespace, owner, id) {
|
|
49
|
+
this.get(namespace, owner, id); const key = this.key(namespace, owner, id), record = this.records.get(key);
|
|
50
|
+
this.records.delete(key); this.bytes -= record.bytes; record.abort?.();
|
|
51
|
+
return { id, object: 'response.deleted', deleted: true };
|
|
52
|
+
}
|
|
53
|
+
cancel(namespace, owner, id) {
|
|
54
|
+
const response = this.get(namespace, owner, id), record = this.records.get(this.key(namespace, owner, id));
|
|
55
|
+
if (!['in_progress', 'queued'].includes(response.status) || !record.abort) throw new ProtocolError('Only an active foreground response can be cancelled', 409);
|
|
56
|
+
this.transition(record, { status: 'cancelled', error: null, incomplete_details: null });
|
|
57
|
+
const abort = record.abort; record.abort = undefined; abort();
|
|
58
|
+
return structuredClone(record.response);
|
|
59
|
+
}
|
|
60
|
+
fail(namespace, owner, id) {
|
|
61
|
+
const record = this.records.get(this.key(namespace, owner, id));
|
|
62
|
+
if (!record || record.response.status === 'cancelled') return;
|
|
63
|
+
this.transition(record, { status: 'failed', error: { code: 'upstream_stream_error', message: 'Upstream stream failed or ended prematurely' } }); record.abort = undefined;
|
|
64
|
+
}
|
|
65
|
+
inputItems(namespace, owner, id, query = new URLSearchParams()) {
|
|
66
|
+
this.get(namespace, owner, id); const record = this.records.get(this.key(namespace, owner, id));
|
|
67
|
+
const limit = query.has('limit') ? Number(query.get('limit')) : 20;
|
|
68
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100) throw new ProtocolError('limit must be an integer from 1 to 100');
|
|
69
|
+
const order = query.get('order') ?? 'desc'; if (!['asc', 'desc'].includes(order)) throw new ProtocolError('order must be asc or desc');
|
|
70
|
+
let items = structuredClone(record.input); if (order === 'desc') items.reverse();
|
|
71
|
+
for (const key of ['after', 'before']) if (query.has(key)) {
|
|
72
|
+
const index = items.findIndex(item => item.id === query.get(key));
|
|
73
|
+
if (index < 0) throw new ProtocolError('Input-item cursor not found');
|
|
74
|
+
items = key === 'after' ? items.slice(index + 1) : items.slice(0, index);
|
|
75
|
+
}
|
|
76
|
+
const data = items.slice(0, limit);
|
|
77
|
+
return { object: 'list', data, first_id: data[0]?.id ?? null, last_id: data.at(-1)?.id ?? null, has_more: items.length > limit };
|
|
78
|
+
}
|
|
79
|
+
close() { for (const record of this.records.values()) record.abort?.(); this.records.clear(); this.bytes = 0; }
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function responseOwner(claims, credential) {
|
|
83
|
+
const value = claims.client_kind && claims.principal_id ? ['principal', claims.client_kind, claims.principal_id] : claims.sub ?? claims.id ? ['token', claims.sub ?? claims.id] : credential ? ['credential', credential] : null;
|
|
84
|
+
if (!value) throw new ProtocolError('A stable credential identity is required for Responses storage', 403);
|
|
85
|
+
return createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
|
86
|
+
}
|
|
87
|
+
export function normalizeResponseInput(body) {
|
|
88
|
+
if (!body || typeof body.input !== 'string' && !Array.isArray(body.input)) throw new ProtocolError('input must be a string or array');
|
|
89
|
+
const input = typeof body.input === 'string' ? [{ role: 'user', content: body.input }] : body.input;
|
|
90
|
+
const ids = new Set();
|
|
91
|
+
return input.map(raw => {
|
|
92
|
+
const item = typeof raw === 'string' ? { role: 'user', content: raw } : structuredClone(raw);
|
|
93
|
+
if (!item || typeof item !== 'object' || Array.isArray(item)) throw new ProtocolError('Response input items must be objects or strings');
|
|
94
|
+
if (!item.id) item.id = `item_${randomUUID().replaceAll('-', '')}`;
|
|
95
|
+
if (typeof item.id !== 'string' || item.id.length > 512 || ids.has(item.id)) throw new ProtocolError('Input-item IDs must be unique nonempty strings of at most 512 characters');
|
|
96
|
+
ids.add(item.id);
|
|
97
|
+
if (!item.type || item.type === 'message') {
|
|
98
|
+
item.type = 'message'; item.status ??= 'completed';
|
|
99
|
+
if (typeof item.content === 'string') item.content = [{ type: item.role === 'assistant' ? 'output_text' : 'input_text', text: item.content }];
|
|
100
|
+
}
|
|
101
|
+
return item;
|
|
102
|
+
});
|
|
103
|
+
}
|
package/src/routing.mjs
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { providerModelId } from '../portable/policy.mjs';
|
|
2
|
+
import { accountVisibleModels } from './accounts.mjs';
|
|
3
|
+
import { RouterError } from './tokens.mjs';
|
|
4
|
+
|
|
5
|
+
export function modelCandidates(providers, accounts, context = {}) {
|
|
6
|
+
const requested = context.model;
|
|
7
|
+
if (typeof requested !== 'string' || !requested) throw new RouterError('model_required','An exact model id is required',400);
|
|
8
|
+
const candidates = [];
|
|
9
|
+
for (const provider of providers) {
|
|
10
|
+
if (provider.enabled === false || context.provider && context.provider !== provider.name) continue;
|
|
11
|
+
if (context.client && !provider.supported_clients.includes(context.client)) continue;
|
|
12
|
+
for (const account of accounts.values()) {
|
|
13
|
+
if (account.provider !== provider.name || account.enabled === false) continue;
|
|
14
|
+
for (const upstream of provider.models) for (const visible of accountVisibleModels(account,upstream)) {
|
|
15
|
+
if (requested !== visible.selector) continue;
|
|
16
|
+
const headers = { ...account.policy.headers };
|
|
17
|
+
candidates.push({ provider:provider.name, kind:provider.kind, model:visible.model, requested_model:requested,
|
|
18
|
+
selector:visible.selector, account:account.name, base_url:provider.base_url,baseUrl:provider.base_url,
|
|
19
|
+
api_key:account.api_key ?? provider.api_key,apiKey:account.api_key ?? provider.api_key,protocol:provider.protocol,
|
|
20
|
+
headers, supported_clients:provider.supported_clients, default_model:provider.default_model });
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
const owners = new Set(candidates.map(c => c.provider));
|
|
25
|
+
if (owners.size > 1 && !context.provider) throw new RouterError('model_conflict',`Exact model id '${requested}' is advertised by more than one provider`,409);
|
|
26
|
+
if (!candidates.length) throw new RouterError('model_not_found',`Exact model id '${requested}' is not advertised by an eligible provider`,404);
|
|
27
|
+
return candidates;
|
|
28
|
+
}
|
|
29
|
+
export function catalogModels(providers, accounts) {
|
|
30
|
+
const result = new Map();
|
|
31
|
+
for (const provider of providers) if (provider.enabled !== false) for (const account of accounts.values()) if (account.provider === provider.name && account.enabled !== false) {
|
|
32
|
+
for (const model of provider.models) for (const visible of accountVisibleModels(account,model)) {
|
|
33
|
+
for (const id of [visible.selector]) {
|
|
34
|
+
const key = providerModelId(provider.name,id);
|
|
35
|
+
if (!result.has(key)) result.set(key,{id,object:'model',created:0,owned_by:provider.name,provider:provider.name,upstream_model:visible.model,supported_clients:provider.supported_clients});
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return [...result.values()];
|
|
40
|
+
}
|