@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,133 @@
|
|
|
1
|
+
// Transport-independent JSON configuration operations for the runtime document.
|
|
2
|
+
|
|
3
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
4
|
+
|
|
5
|
+
const localCliSettings = [
|
|
6
|
+
'token-secret', 'admin-key', 'upstream-base-url', 'openai-compatible-base-url',
|
|
7
|
+
'openai-compatible-api-key-env', 'gonka-source-url', 'crater-forgefed-inbox',
|
|
8
|
+
'account-egress-proxy', 'model-catalog-sources', 'claude-code-home',
|
|
9
|
+
'additional-account-dirs', 'login-cli-command', 'login-cli-args', 'claude-cli-bin',
|
|
10
|
+
'codex-cli-bin', 'audit-log', 'request-log', 'listener', 'admin-host', 'admin-port',
|
|
11
|
+
'management-allow-remote', 'management-lockout-failures', 'management-lockout-secs',
|
|
12
|
+
'management-lockout-exempt-loopback',
|
|
13
|
+
];
|
|
14
|
+
|
|
15
|
+
export function assertConfigWriterCanEdit(before, after) {
|
|
16
|
+
for (const key of localCliSettings) {
|
|
17
|
+
if (!isDeepStrictEqual(before?.cli?.[key], after?.cli?.[key])) {
|
|
18
|
+
throw new Error('this CLI setting may only be changed in the local TOML file');
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function pointerSegments(pointer) {
|
|
24
|
+
if (pointer === '') return [];
|
|
25
|
+
if (!pointer.startsWith('/')) throw new Error('JSON Pointer must start with /');
|
|
26
|
+
return pointer.slice(1).split('/').map((part) => {
|
|
27
|
+
if (/~(?![01])/u.test(part)) throw new Error('invalid JSON Pointer escape');
|
|
28
|
+
return part.replaceAll('~1', '/').replaceAll('~0', '~');
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function mergeConfigPatch(current, patch) {
|
|
33
|
+
if (!isObject(patch)) return structuredClone(patch);
|
|
34
|
+
const entries = new Map(Object.entries(isObject(current) ? current : {}));
|
|
35
|
+
for (const [key, value] of Object.entries(patch)) {
|
|
36
|
+
if (value === null) entries.delete(key);
|
|
37
|
+
else entries.set(key, mergeConfigPatch(entries.get(key), value));
|
|
38
|
+
}
|
|
39
|
+
return Object.fromEntries(entries);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function configPointer(document, pointer, operation = 'get', value) {
|
|
43
|
+
const segments = pointerSegments(pointer);
|
|
44
|
+
if (segments.length === 0) {
|
|
45
|
+
if (operation === 'get') return structuredClone(document);
|
|
46
|
+
if (operation === 'put') return structuredClone(value);
|
|
47
|
+
throw new Error('cannot delete the configuration root');
|
|
48
|
+
}
|
|
49
|
+
const result = structuredClone(document);
|
|
50
|
+
const key = segments.pop();
|
|
51
|
+
let container = result;
|
|
52
|
+
for (const segment of segments) container = child(container, segment);
|
|
53
|
+
if (operation === 'get') return child(container, key);
|
|
54
|
+
if (Array.isArray(container)) {
|
|
55
|
+
const index = arrayIndex(key, container.length, operation === 'put');
|
|
56
|
+
if (operation === 'delete') container.splice(index, 1);
|
|
57
|
+
else container[index] = structuredClone(value);
|
|
58
|
+
} else if (isObject(container)) {
|
|
59
|
+
if (operation === 'delete') {
|
|
60
|
+
child(container, key);
|
|
61
|
+
delete container[key];
|
|
62
|
+
} else {
|
|
63
|
+
Object.defineProperty(container, key, { value: structuredClone(value), enumerable: true, configurable: true, writable: true });
|
|
64
|
+
}
|
|
65
|
+
} else {
|
|
66
|
+
throw new Error('configuration parent is not a container');
|
|
67
|
+
}
|
|
68
|
+
return result;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function isObject(value) {
|
|
72
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function child(container, key) {
|
|
76
|
+
if (Array.isArray(container)) return container[arrayIndex(key, container.length, false)];
|
|
77
|
+
if (isObject(container) && Object.hasOwn(container, key)) return container[key];
|
|
78
|
+
throw new Error('configuration path does not exist');
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function arrayIndex(key, length, append) {
|
|
82
|
+
if (append && key === '-') return length;
|
|
83
|
+
if (!/^(0|[1-9][0-9]*)$/u.test(key) || Number(key) >= length) {
|
|
84
|
+
throw new Error('configuration array index does not exist');
|
|
85
|
+
}
|
|
86
|
+
return Number(key);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const redacted = '[REDACTED]';
|
|
90
|
+
const secretKey = /(?:^|[._/-])(?:api[-_]?key|admin[-_]?key|private[-_]?key|password|secret|token|cookie|authorization)(?:$|[._/-])/iu;
|
|
91
|
+
|
|
92
|
+
export function redactRuntimeConfig(value) {
|
|
93
|
+
if (Array.isArray(value)) return value.map(redactRuntimeConfig);
|
|
94
|
+
if (isObject(value)) {
|
|
95
|
+
return Object.fromEntries(Object.entries(value).map(([key, child]) => [
|
|
96
|
+
key, secretKey.test(key) ? redacted : redactRuntimeConfig(child),
|
|
97
|
+
]));
|
|
98
|
+
}
|
|
99
|
+
if (typeof value === 'string') {
|
|
100
|
+
if (/^(bearer\s|la_(sk|admin)_)/iu.test(value)) return redacted;
|
|
101
|
+
if (value.includes('://')) {
|
|
102
|
+
try {
|
|
103
|
+
const url = new URL(value);
|
|
104
|
+
if (url.username || url.password || [...url.searchParams.keys()].some((key) => secretKey.test(key))) return redacted;
|
|
105
|
+
} catch {
|
|
106
|
+
// A string containing a URL fragment can still be ordinary payload text.
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
if (value.startsWith('{') || value.startsWith('[')) {
|
|
110
|
+
try {
|
|
111
|
+
const json = JSON.parse(value);
|
|
112
|
+
if (JSON.stringify(json) !== JSON.stringify(redactRuntimeConfig(json))) return redacted;
|
|
113
|
+
} catch {
|
|
114
|
+
// Only complete raw JSON values participate in recursive redaction.
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return value;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function validateCors({ origins = [], methods = ['GET', 'POST'], headers = [], credentials = false } = {}) {
|
|
122
|
+
if (credentials && [...origins, ...methods, ...headers].includes('*')) throw new Error('credentialed CORS requires explicit values');
|
|
123
|
+
for (const values of [origins, methods, headers]) {
|
|
124
|
+
if (values.includes('*') && values.length !== 1) throw new Error('CORS wildcard must be used alone');
|
|
125
|
+
}
|
|
126
|
+
for (const origin of origins) {
|
|
127
|
+
if (origin === '*') continue;
|
|
128
|
+
const url = new URL(origin);
|
|
129
|
+
if (url.origin !== origin || !['http:', 'https:'].includes(url.protocol)) throw new Error('invalid CORS origin');
|
|
130
|
+
}
|
|
131
|
+
const httpToken = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u;
|
|
132
|
+
if (![...methods, ...headers].every((name) => httpToken.test(name))) throw new Error('invalid CORS method or header');
|
|
133
|
+
}
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
2
|
+
import { isObject, pointerSegments } from './runtime-config.mjs';
|
|
3
|
+
|
|
4
|
+
const stages = ['default', 'default-raw', 'override', 'override-raw', 'filter'];
|
|
5
|
+
const protectedFields = new Set(['model', 'modelId', 'stream', 'type', 'stream_id', 'conversation']);
|
|
6
|
+
|
|
7
|
+
function pathParts(path) {
|
|
8
|
+
if (path.startsWith('/')) {
|
|
9
|
+
const parts = pointerSegments(path);
|
|
10
|
+
if (parts.some((part) => !part) || parts.length > 32) throw new Error('invalid payload path');
|
|
11
|
+
return parts;
|
|
12
|
+
}
|
|
13
|
+
const parts = [];
|
|
14
|
+
let start = 0;
|
|
15
|
+
let inQuery = false;
|
|
16
|
+
let quoted = false;
|
|
17
|
+
let escaped = false;
|
|
18
|
+
for (let index = 0; index < path.length; index += 1) {
|
|
19
|
+
const character = path[index];
|
|
20
|
+
if (inQuery) {
|
|
21
|
+
if (escaped) escaped = false;
|
|
22
|
+
else if (quoted && character === '\\') escaped = true;
|
|
23
|
+
else if (character === '"') quoted = !quoted;
|
|
24
|
+
else if (!quoted && character === ')') inQuery = false;
|
|
25
|
+
} else if (index === start && path.startsWith('#(', index)) {
|
|
26
|
+
inQuery = true;
|
|
27
|
+
} else if (character === '.') {
|
|
28
|
+
parts.push(path.slice(start, index));
|
|
29
|
+
start = index + 1;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
parts.push(path.slice(start));
|
|
33
|
+
if (inQuery || parts.some((part) => !part) || parts.length > 32) throw new Error('invalid payload path');
|
|
34
|
+
return parts;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function read(root, path) {
|
|
38
|
+
return path.reduce((value, key) => value != null && Object.hasOwn(value, key) ? value[key] : undefined, root);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function matchesConditions(body, selector) {
|
|
42
|
+
const found = (path, predicate) => paths(body, pathParts(path)).some((parts) => predicate(read(body, parts)));
|
|
43
|
+
const matches = (checks, positive) => checks.every((check) => Object.entries(check).every(
|
|
44
|
+
([path, value]) => found(path, (current) => isDeepStrictEqual(current, value)) === positive,
|
|
45
|
+
));
|
|
46
|
+
const exists = (checks, positive) => checks.every(
|
|
47
|
+
(path) => found(path, (current) => current != null) === positive,
|
|
48
|
+
);
|
|
49
|
+
return matches(selector.match ?? [], true)
|
|
50
|
+
&& matches(selector['not-match'] ?? [], false)
|
|
51
|
+
&& exists(selector.exist ?? [], true)
|
|
52
|
+
&& exists(selector['not-exist'] ?? [], false);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function glob(pattern, value) {
|
|
56
|
+
const pieces = pattern.split('*');
|
|
57
|
+
if (pieces.length === 1) return pattern === value;
|
|
58
|
+
const start = pieces.shift();
|
|
59
|
+
const end = pieces.pop();
|
|
60
|
+
if (!value.startsWith(start) || !value.endsWith(end) || value.length < start.length + end.length) return false;
|
|
61
|
+
let offset = start.length;
|
|
62
|
+
for (const piece of pieces) {
|
|
63
|
+
const index = value.indexOf(piece, offset);
|
|
64
|
+
if (index < 0) return false;
|
|
65
|
+
offset = index + piece.length;
|
|
66
|
+
}
|
|
67
|
+
return offset <= value.length - end.length;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function canonicalProtocol(protocol) {
|
|
71
|
+
return protocol === 'anthropic' ? 'claude' : protocol;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function select(selector, context) {
|
|
75
|
+
return glob(selector.name, context.model ?? '')
|
|
76
|
+
&& (!selector.protocol || canonicalProtocol(selector.protocol) === context.protocol)
|
|
77
|
+
&& (!selector['from-protocol'] || canonicalProtocol(selector['from-protocol']) === context.fromProtocol)
|
|
78
|
+
&& (!selector.token || [context.tokenId, context.tokenLabel].includes(selector.token));
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function write(root, parts, value, filter) {
|
|
82
|
+
const key = parts.at(-1);
|
|
83
|
+
let container = root;
|
|
84
|
+
for (const part of parts.slice(0, -1)) {
|
|
85
|
+
if (Array.isArray(container)) {
|
|
86
|
+
if (!/^(0|[1-9][0-9]*)$/u.test(part) || Number(part) >= container.length) {
|
|
87
|
+
if (filter) return;
|
|
88
|
+
throw new Error('payload rule array index does not exist');
|
|
89
|
+
}
|
|
90
|
+
} else if (!isObject(container)) {
|
|
91
|
+
if (filter) return;
|
|
92
|
+
throw new Error('payload rule traverses a scalar');
|
|
93
|
+
} else if (!Object.hasOwn(container, part)) {
|
|
94
|
+
if (filter) return;
|
|
95
|
+
Object.defineProperty(container, part, { value: {}, enumerable: true, configurable: true, writable: true });
|
|
96
|
+
}
|
|
97
|
+
container = container[part];
|
|
98
|
+
}
|
|
99
|
+
if (Array.isArray(container)) {
|
|
100
|
+
if (!/^(0|[1-9][0-9]*)$/u.test(key) || Number(key) >= container.length) {
|
|
101
|
+
if (filter) return;
|
|
102
|
+
throw new Error('payload rule array index does not exist');
|
|
103
|
+
}
|
|
104
|
+
if (filter) container.splice(Number(key), 1);
|
|
105
|
+
else container[key] = value;
|
|
106
|
+
} else if (isObject(container)) {
|
|
107
|
+
if (filter) delete container[key];
|
|
108
|
+
else Object.defineProperty(container, key, { value, enumerable: true, configurable: true, writable: true });
|
|
109
|
+
} else if (!filter) {
|
|
110
|
+
throw new Error('payload rule traverses a scalar');
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function paths(root, parts, offset = 0) {
|
|
115
|
+
if (offset === parts.length) return [[]];
|
|
116
|
+
const part = parts[offset];
|
|
117
|
+
const query = /^#\(([^=]+)==(.+)\)(#?)$/u.exec(part);
|
|
118
|
+
if (!query) return paths(read(root, [part]), parts, offset + 1).map((tail) => [part, ...tail]);
|
|
119
|
+
if (!Array.isArray(root)) return [];
|
|
120
|
+
const [, key, literal, all] = query;
|
|
121
|
+
const expected = JSON.parse(literal);
|
|
122
|
+
const matches = [];
|
|
123
|
+
for (const [index, item] of root.entries()) {
|
|
124
|
+
if (isDeepStrictEqual(read(item, pathParts(key)), expected)) {
|
|
125
|
+
matches.push(...paths(item, parts, offset + 1).map((tail) => [String(index), ...tail]));
|
|
126
|
+
if (!all) break;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return matches;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export function applyPayloadRules(rules, body, context) {
|
|
133
|
+
const applicable = (stage) => (rules[stage] ?? []).filter((rule) => rule.models.some((selector) => select(selector, context)));
|
|
134
|
+
if (!stages.some((stage) => applicable(stage).length)) return { body, applied: [] };
|
|
135
|
+
if (!isObject(body)) throw new Error('payload rules require a JSON object');
|
|
136
|
+
const result = structuredClone(body);
|
|
137
|
+
const applied = [];
|
|
138
|
+
const changed = new Set();
|
|
139
|
+
for (const stage of stages) {
|
|
140
|
+
for (const rule of applicable(stage)) {
|
|
141
|
+
if (!rule.models.some((selector) => select(selector, context) && matchesConditions(result, selector))) continue;
|
|
142
|
+
const filter = stage === 'filter';
|
|
143
|
+
for (const [path, input] of filter ? rule.params.map((path) => [path, null]) : Object.entries(rule.params).sort()) {
|
|
144
|
+
const parts = pathParts(path);
|
|
145
|
+
if (parts[0] === 'previous_response_id' && (!filter || parts.length !== 1)) {
|
|
146
|
+
throw new Error('payload rules may only remove a continuation ID');
|
|
147
|
+
}
|
|
148
|
+
if (protectedFields.has(parts[0])) throw new Error('payload rule changes a protected field');
|
|
149
|
+
const targets = paths(result, parts);
|
|
150
|
+
if (!filter && targets.length === 0) throw new Error('payload rule matches no parameter');
|
|
151
|
+
for (const resolved of targets.reverse()) {
|
|
152
|
+
const before = read(result, resolved);
|
|
153
|
+
if (stage.startsWith('default') && before !== undefined) continue;
|
|
154
|
+
if (filter && before === undefined) continue;
|
|
155
|
+
const value = stage.endsWith('-raw') && typeof input === 'string' ? JSON.parse(input) : structuredClone(input);
|
|
156
|
+
write(result, resolved, value, filter);
|
|
157
|
+
applied.push({ stage, path, ...(filter ? {} : { value }) });
|
|
158
|
+
changed.add(resolved[0]);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
if (['claude', 'bedrock', 'vertex'].includes(context.protocol) && (changed.has('temperature') || changed.has('top_p'))
|
|
164
|
+
&& result.temperature != null && result.top_p != null) {
|
|
165
|
+
throw new Error('payload rules left incompatible sampling parameters');
|
|
166
|
+
}
|
|
167
|
+
if (['claude', 'bedrock', 'vertex', 'openai', 'codex'].includes(context.protocol)) {
|
|
168
|
+
for (const key of ['max_tokens', 'max_output_tokens']) {
|
|
169
|
+
if (changed.has(key) && Object.hasOwn(result, key) && (!Number.isSafeInteger(result[key]) || result[key] < 1)) {
|
|
170
|
+
throw new Error(`payload rule ${key} requires a positive integer`);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
return { body: result, applied };
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export function applyCodexSubscriptionPayloadRules(rules, body, context, outputLimit, supportsSampling = true) {
|
|
178
|
+
const virtualLimit = outputLimit !== undefined && isObject(body) && !Object.hasOwn(body, 'max_output_tokens');
|
|
179
|
+
const candidate = virtualLimit ? { ...body, max_output_tokens: outputLimit } : body;
|
|
180
|
+
const result = applyPayloadRules(rules, candidate, context);
|
|
181
|
+
if (!result.applied.length) return { ...result, body, outputLimit };
|
|
182
|
+
const affected = (field) => result.applied.some(({ path }) => pathParts(path)[0] === field);
|
|
183
|
+
if (!supportsSampling && ['temperature', 'top_p'].some((field) => affected(field) && Object.hasOwn(result.body, field))) {
|
|
184
|
+
throw new Error('the Codex subscription backend does not support configured sampling parameters');
|
|
185
|
+
}
|
|
186
|
+
const changed = affected('max_output_tokens');
|
|
187
|
+
const effectiveLimit = changed ? result.body.max_output_tokens : outputLimit;
|
|
188
|
+
if (virtualLimit || changed) delete result.body.max_output_tokens;
|
|
189
|
+
return { ...result, outputLimit: effectiveLimit };
|
|
190
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
const lineLimit = 256 * 1024;
|
|
2
|
+
const queueLimit = 64;
|
|
3
|
+
const maximumTokenLength = 116;
|
|
4
|
+
const decoder = new TextDecoder('utf-8',{fatal:true});
|
|
5
|
+
|
|
6
|
+
// The same event can carry several independent text outputs. Keep fragments
|
|
7
|
+
// separate even when the provider interleaves their events.
|
|
8
|
+
function visitDeltas(event,visit) {
|
|
9
|
+
switch (event.type) {
|
|
10
|
+
case 'response.output_text.delta':
|
|
11
|
+
case 'response.text.delta':
|
|
12
|
+
visit(event,'delta',['response',event.response_id,event.item_id,event.output_index,event.content_index]);
|
|
13
|
+
return;
|
|
14
|
+
case 'content_block_delta':
|
|
15
|
+
if (event.delta?.type === 'text_delta') visit(event.delta,'text',['anthropic',event.index]);
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
if (Array.isArray(event.choices)) {
|
|
19
|
+
event.choices.forEach((choice,index) => {
|
|
20
|
+
if (choice?.delta) visit(choice.delta,'content',['choices',event.id,choice.index ?? index]);
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
if (Array.isArray(event.candidates)) {
|
|
24
|
+
event.candidates.forEach((candidate,index) => {
|
|
25
|
+
if (Array.isArray(candidate?.content?.parts)) {
|
|
26
|
+
candidate.content.parts.forEach((part,partIndex) => visit(part,'text',['candidates',candidate.index ?? index,partIndex]));
|
|
27
|
+
}
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function trailingPrefix(text,tokens) {
|
|
33
|
+
const start = Math.max(0,text.length - maximumTokenLength + 1);
|
|
34
|
+
for (let at = text.indexOf('[',start); at !== -1; at = text.indexOf('[',at + 1)) {
|
|
35
|
+
const tail = text.slice(at);
|
|
36
|
+
if (tokens.some(token => token.length > tail.length && token.startsWith(tail))) return tail;
|
|
37
|
+
}
|
|
38
|
+
return '';
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Hold a bounded group only while a delta ends in a prefix of a known token.
|
|
42
|
+
// If interrupted, relay every original record so an incomplete match cannot
|
|
43
|
+
// remove ordinary provider text. The byte-level restorer runs afterward.
|
|
44
|
+
export function joinSensitiveDataDeltas(body,replacements) {
|
|
45
|
+
const tokens = [...replacements.keys()];
|
|
46
|
+
const pending = new Map();
|
|
47
|
+
const queue = [];
|
|
48
|
+
let queueBytes = 0;
|
|
49
|
+
let line = Buffer.alloc(0);
|
|
50
|
+
let skipLine = false;
|
|
51
|
+
function drain(controller,changed) {
|
|
52
|
+
for (const entry of queue) controller.enqueue(changed ? entry.joined : entry.original);
|
|
53
|
+
queue.length = 0;
|
|
54
|
+
queueBytes = 0;
|
|
55
|
+
pending.clear();
|
|
56
|
+
}
|
|
57
|
+
function eventLine(original,controller) {
|
|
58
|
+
let joined = original;
|
|
59
|
+
let terminal = false;
|
|
60
|
+
if (original.subarray(0,5).toString('latin1') === 'data:') {
|
|
61
|
+
try {
|
|
62
|
+
const text = decoder.decode(original);
|
|
63
|
+
const payload = text.slice(5).trim();
|
|
64
|
+
terminal = payload === '[DONE]';
|
|
65
|
+
if (!terminal) {
|
|
66
|
+
const event = JSON.parse(payload);
|
|
67
|
+
if (event && typeof event === 'object' && !Array.isArray(event)) {
|
|
68
|
+
terminal = /^(?:response\.(?:completed|done|failed|incomplete)|message_stop)$/.test(event.type);
|
|
69
|
+
let changed = false;
|
|
70
|
+
visitDeltas(event,(field,key,lane) => {
|
|
71
|
+
if (typeof field?.[key] !== 'string' || lane.some(part => part != null &&
|
|
72
|
+
!(typeof part === 'string' && part.length <= 256) && !Number.isSafeInteger(part))) return;
|
|
73
|
+
const id = JSON.stringify(lane);
|
|
74
|
+
const text = (pending.get(id) ?? '') + field[key];
|
|
75
|
+
const tail = trailingPrefix(text,tokens);
|
|
76
|
+
if (tail) pending.set(id,tail);
|
|
77
|
+
else pending.delete(id);
|
|
78
|
+
const output = text.slice(0,text.length - tail.length);
|
|
79
|
+
if (output !== field[key]) { field[key] = output; changed = true; }
|
|
80
|
+
});
|
|
81
|
+
if (changed) joined = Buffer.from(`data: ${JSON.stringify(event)}${text.endsWith('\r\n') ? '\r\n' : '\n'}`);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
} catch {
|
|
85
|
+
// Malformed or opaque data lines retain their original bytes.
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
queue.push({original,joined});
|
|
89
|
+
queueBytes += original.length;
|
|
90
|
+
if (terminal || queue.length >= queueLimit || queueBytes > lineLimit || pending.size > queueLimit) drain(controller,false);
|
|
91
|
+
else if (!pending.size) drain(controller,true);
|
|
92
|
+
}
|
|
93
|
+
return body.pipeThrough(new TransformStream({
|
|
94
|
+
transform(chunk,controller) {
|
|
95
|
+
const input = Buffer.from(chunk);
|
|
96
|
+
for (let start = 0; start < input.length;) {
|
|
97
|
+
const newline = input.indexOf(10,start);
|
|
98
|
+
const end = newline < 0 ? input.length : newline + 1;
|
|
99
|
+
const next = input.subarray(start,end);
|
|
100
|
+
if (skipLine || line.length + next.length > lineLimit) {
|
|
101
|
+
drain(controller,false);
|
|
102
|
+
if (line.length) controller.enqueue(line);
|
|
103
|
+
controller.enqueue(next);
|
|
104
|
+
line = Buffer.alloc(0);
|
|
105
|
+
skipLine = newline < 0;
|
|
106
|
+
} else {
|
|
107
|
+
line = line.length ? Buffer.concat([line,next]) : next;
|
|
108
|
+
if (newline >= 0) {
|
|
109
|
+
eventLine(line,controller);
|
|
110
|
+
line = Buffer.alloc(0);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
start = end;
|
|
114
|
+
}
|
|
115
|
+
},
|
|
116
|
+
flush(controller) {
|
|
117
|
+
drain(controller,false);
|
|
118
|
+
if (line.length) controller.enqueue(line);
|
|
119
|
+
},
|
|
120
|
+
}));
|
|
121
|
+
}
|