@link-assistant/router 1.25.6 → 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/catalog.json +121 -1
- package/package.json +7 -6
- package/src/client-launch-plan.mjs +3 -3
- package/src/runtime-config.mjs +133 -0
- package/src/runtime-payload.mjs +190 -0
package/catalog.json
CHANGED
|
@@ -64604,6 +64604,126 @@
|
|
|
64604
64604
|
"method": "POST",
|
|
64605
64605
|
"name": "CooldownReset",
|
|
64606
64606
|
"path": "/api/management/routing/cooldown/reset"
|
|
64607
|
+
},
|
|
64608
|
+
{
|
|
64609
|
+
"auth": "ConfigRead",
|
|
64610
|
+
"class": "Management",
|
|
64611
|
+
"dialect": "Anthropic",
|
|
64612
|
+
"listeners": [
|
|
64613
|
+
"Combined",
|
|
64614
|
+
"Admin"
|
|
64615
|
+
],
|
|
64616
|
+
"method": "GET",
|
|
64617
|
+
"name": "RuntimeConfig",
|
|
64618
|
+
"path": "/api/management/config"
|
|
64619
|
+
},
|
|
64620
|
+
{
|
|
64621
|
+
"auth": "ConfigWrite",
|
|
64622
|
+
"class": "Management",
|
|
64623
|
+
"dialect": "Anthropic",
|
|
64624
|
+
"listeners": [
|
|
64625
|
+
"Combined",
|
|
64626
|
+
"Admin"
|
|
64627
|
+
],
|
|
64628
|
+
"method": "PUT",
|
|
64629
|
+
"name": "RuntimeConfig",
|
|
64630
|
+
"path": "/api/management/config"
|
|
64631
|
+
},
|
|
64632
|
+
{
|
|
64633
|
+
"auth": "ConfigWrite",
|
|
64634
|
+
"class": "Management",
|
|
64635
|
+
"dialect": "Anthropic",
|
|
64636
|
+
"listeners": [
|
|
64637
|
+
"Combined",
|
|
64638
|
+
"Admin"
|
|
64639
|
+
],
|
|
64640
|
+
"method": "PATCH",
|
|
64641
|
+
"name": "RuntimeConfig",
|
|
64642
|
+
"path": "/api/management/config"
|
|
64643
|
+
},
|
|
64644
|
+
{
|
|
64645
|
+
"auth": "ConfigRead",
|
|
64646
|
+
"class": "Management",
|
|
64647
|
+
"dialect": "Anthropic",
|
|
64648
|
+
"listeners": [
|
|
64649
|
+
"Combined",
|
|
64650
|
+
"Admin"
|
|
64651
|
+
],
|
|
64652
|
+
"method": "GET",
|
|
64653
|
+
"name": "RuntimeConfigYaml",
|
|
64654
|
+
"path": "/api/management/config.yaml"
|
|
64655
|
+
},
|
|
64656
|
+
{
|
|
64657
|
+
"auth": "ConfigRead",
|
|
64658
|
+
"class": "Management",
|
|
64659
|
+
"dialect": "Anthropic",
|
|
64660
|
+
"listeners": [
|
|
64661
|
+
"Combined",
|
|
64662
|
+
"Admin"
|
|
64663
|
+
],
|
|
64664
|
+
"method": "GET",
|
|
64665
|
+
"name": "RuntimeConfigSchema",
|
|
64666
|
+
"path": "/api/management/config/schema"
|
|
64667
|
+
},
|
|
64668
|
+
{
|
|
64669
|
+
"auth": "ConfigRead",
|
|
64670
|
+
"class": "Management",
|
|
64671
|
+
"dialect": "Anthropic",
|
|
64672
|
+
"listeners": [
|
|
64673
|
+
"Combined",
|
|
64674
|
+
"Admin"
|
|
64675
|
+
],
|
|
64676
|
+
"method": "GET",
|
|
64677
|
+
"name": "RuntimeConfigStatus",
|
|
64678
|
+
"path": "/api/management/config/status"
|
|
64679
|
+
},
|
|
64680
|
+
{
|
|
64681
|
+
"auth": "ConfigWrite",
|
|
64682
|
+
"class": "Management",
|
|
64683
|
+
"dialect": "Anthropic",
|
|
64684
|
+
"listeners": [
|
|
64685
|
+
"Combined",
|
|
64686
|
+
"Admin"
|
|
64687
|
+
],
|
|
64688
|
+
"method": "POST",
|
|
64689
|
+
"name": "RuntimeConfigReload",
|
|
64690
|
+
"path": "/api/management/config/reload"
|
|
64691
|
+
},
|
|
64692
|
+
{
|
|
64693
|
+
"auth": "ConfigRead",
|
|
64694
|
+
"class": "Management",
|
|
64695
|
+
"dialect": "Anthropic",
|
|
64696
|
+
"listeners": [
|
|
64697
|
+
"Combined",
|
|
64698
|
+
"Admin"
|
|
64699
|
+
],
|
|
64700
|
+
"method": "GET",
|
|
64701
|
+
"name": "RuntimeConfigPointer",
|
|
64702
|
+
"path": "/api/management/config/{*pointer}"
|
|
64703
|
+
},
|
|
64704
|
+
{
|
|
64705
|
+
"auth": "ConfigWrite",
|
|
64706
|
+
"class": "Management",
|
|
64707
|
+
"dialect": "Anthropic",
|
|
64708
|
+
"listeners": [
|
|
64709
|
+
"Combined",
|
|
64710
|
+
"Admin"
|
|
64711
|
+
],
|
|
64712
|
+
"method": "PUT",
|
|
64713
|
+
"name": "RuntimeConfigPointer",
|
|
64714
|
+
"path": "/api/management/config/{*pointer}"
|
|
64715
|
+
},
|
|
64716
|
+
{
|
|
64717
|
+
"auth": "ConfigWrite",
|
|
64718
|
+
"class": "Management",
|
|
64719
|
+
"dialect": "Anthropic",
|
|
64720
|
+
"listeners": [
|
|
64721
|
+
"Combined",
|
|
64722
|
+
"Admin"
|
|
64723
|
+
],
|
|
64724
|
+
"method": "DELETE",
|
|
64725
|
+
"name": "RuntimeConfigPointer",
|
|
64726
|
+
"path": "/api/management/config/{*pointer}"
|
|
64607
64727
|
}
|
|
64608
64728
|
],
|
|
64609
64729
|
"schema": "link-assistant-router/operation-catalog/v1",
|
|
@@ -68418,5 +68538,5 @@
|
|
|
68418
68538
|
"type": "object"
|
|
68419
68539
|
}
|
|
68420
68540
|
},
|
|
68421
|
-
"version": "1.
|
|
68541
|
+
"version": "1.26.0"
|
|
68422
68542
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@link-assistant/router",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.26.0",
|
|
4
4
|
"description": "Official typed Router operations and testing helpers for Node and Bun",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"engines": {
|
|
@@ -34,18 +34,19 @@
|
|
|
34
34
|
],
|
|
35
35
|
"scripts": {
|
|
36
36
|
"test": "node --test test/*.test.js",
|
|
37
|
-
"typecheck": "tsc --noEmit --strict --module nodenext --moduleResolution nodenext test/types.ts",
|
|
37
|
+
"typecheck": "node node_modules/typescript-native/bin/tsc --noEmit --strict --module nodenext --moduleResolution nodenext test/types.ts",
|
|
38
38
|
"native:test": "node --test test/native-*.test.*",
|
|
39
39
|
"native:test:bun": "bun test test/native-*.test.*",
|
|
40
|
-
"native:typecheck": "tsc --noEmit --strict --module nodenext --moduleResolution nodenext test/native-types.ts"
|
|
40
|
+
"native:typecheck": "node node_modules/typescript-native/bin/tsc --noEmit --strict --module nodenext --moduleResolution nodenext test/native-types.ts"
|
|
41
41
|
},
|
|
42
42
|
"dependencies": {
|
|
43
43
|
"@iarna/toml": "3.0.0",
|
|
44
|
-
"ajv": "^8.
|
|
44
|
+
"ajv": "^8.20.0"
|
|
45
45
|
},
|
|
46
46
|
"devDependencies": {
|
|
47
|
-
"@types/node": "^
|
|
48
|
-
"typescript": "
|
|
47
|
+
"@types/node": "^26.6.11",
|
|
48
|
+
"typescript": "5.9.3",
|
|
49
|
+
"typescript-native": "npm:typescript@7.0.2"
|
|
49
50
|
},
|
|
50
51
|
"repository": {
|
|
51
52
|
"type": "git",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/** Native launch policy DATA and argv planning; this module never spawns a process. */
|
|
2
2
|
import {clientIntegration,clientFailure} from './client-files.mjs';
|
|
3
|
-
const rules={"clients":{"codex":{"commands":["agents","exec","e","review","login","logout","mcp","plugin","mcp-server","app-server","remote-control","app","completion","update","doctor","sandbox","debug","apply","a","resume","queue","archive","delete","migrate-rollouts","unarchive","fork","cloud","cloud-tasks","exec-server","features"],"modelFlag":"--model","mode":"exec","aliases":[],"modeTakesValue":false},"claude":{"commands":["agents","attach","auth","auto-mode","doctor","gateway","import","install","logs","mcp","plugin","plugins","project","respawn","rm","setup-token","stop","kill","ultrareview","update","upgrade"],"modelFlag":"--model","mode":"--print","aliases":["-p"],"modeTakesValue":false},"cursor-agent":{"commands":[],"modelFlag":null,"mode":null,"aliases":[],"modeTakesValue":false},"gemini":{"commands":["mcp","extensions","extension","skills","skill","hooks","hook","gemma"],"modelFlag":"--model","mode":"-p","aliases":["--prompt"],"modeTakesValue":true},"grok":{"commands":["git","mcp"],"modelFlag":"--model","mode":"-p","aliases":["--prompt"],"modeTakesValue":true},"opencode":{"commands":["completion","acp","mcp","attach","run","debug","providers","auth","agent","upgrade","uninstall","serve","web","models","stats","export","import","github","pr","session","plugin","plug","db"],"modelFlag":"--model","mode":"run","aliases":[],"modeTakesValue":false},"qwen":{"commands":["
|
|
3
|
+
const rules={"clients":{"codex":{"commands":["agents","exec","e","review","login","logout","mcp","plugin","mcp-server","app-server","remote-control","app","completion","update","doctor","sandbox","debug","apply","a","resume","queue","archive","delete","migrate-rollouts","unarchive","fork","cloud","cloud-tasks","exec-server","features"],"modelFlag":"--model","mode":"exec","aliases":[],"modeTakesValue":false},"claude":{"commands":["agents","attach","auth","auto-mode","doctor","gateway","import","install","logs","mcp","plugin","plugins","project","respawn","rm","setup-token","stop","kill","ultrareview","update","upgrade"],"modelFlag":"--model","mode":"--print","aliases":["-p"],"modeTakesValue":false},"cursor-agent":{"commands":[],"modelFlag":null,"mode":null,"aliases":[],"modeTakesValue":false},"gemini":{"commands":["mcp","extensions","extension","skills","skill","hooks","hook","gemma"],"modelFlag":"--model","mode":"-p","aliases":["--prompt"],"modeTakesValue":true},"grok":{"commands":["git","mcp"],"modelFlag":"--model","mode":"-p","aliases":["--prompt"],"modeTakesValue":true},"opencode":{"commands":["completion","acp","mcp","attach","run","debug","providers","auth","agent","upgrade","uninstall","serve","web","models","stats","export","import","github","pr","session","plugin","plug","db"],"modelFlag":"--model","mode":"run","aliases":[],"modeTakesValue":false},"qwen":{"commands":["agents","attach","autofix-pr","auth","batch","board","channel","extensions","hooks","mcp","memory","review","sandbox","serve","daemon","sessions","update"],"modelFlag":"--model","mode":null,"aliases":["-p","--prompt"],"modeTakesValue":true},"agent":{"commands":["auth"],"modelFlag":"--model","mode":"--prompt","aliases":["-p"],"modeTakesValue":true}},"codexValueOptions":["-c","--config","--enable","--disable","-i","--image","-m","--model","--local-provider","--profile","-s","--sandbox","-a","--ask-for-approval","-C","--cd","--add-dir"],"codexBooleanOptions":["--oss","--search","--full-auto","--dangerously-bypass-approvals-and-sandbox","--no-alt-screen","-h","--help","-V","--version"],"claudeNativeServiceError":"this Claude.ai operation cannot be routed because released Claude Code (checked through 2.1.283) has no supported split-auth mechanism; run it directly with Claude.ai authentication instead; no Router token was minted and no client was launched","codexCloudError":"Codex Cloud tasks cannot be routed: the official Codex client does not support a split credential or custom backend for Cloud; no Router token was minted and no client was launched","noPromptNote":"note: this client's one-shot mode takes the prompt as an argument and none was given, so it is launched as an ordinary session"};
|
|
4
4
|
function argumentsData(value){if(!Array.isArray(value)||value.length>10000||value.some(row=>typeof row!=='string'||row.includes('\0'))||Buffer.byteLength(value.join('\0'))>2097152)throw clientFailure('Client argv must contain bounded strings without NUL');return [...value];}
|
|
5
5
|
export function forwardedClientModel(value){
|
|
6
6
|
const args=argumentsData(value);let found=null;
|
|
@@ -17,10 +17,10 @@ export function unsupportedClientNativeCommand(client,value){
|
|
|
17
17
|
export function nativeClientRequiresModel(client){return ['opencode','qwen','agent'].includes(clientIntegration(client).client);}
|
|
18
18
|
export function planNativeClientLaunch(client,options={},resolvedModel=null,attachedToTerminal=false){
|
|
19
19
|
const info=clientIntegration(client),rule=rules.clients[info.client],forwarded=argumentsData(options.client_args??[]),exact=forwarded[0]==='--';if(exact)forwarded.shift();if(options.interactive&&options.non_interactive)throw clientFailure('interactive and non_interactive conflict');if(resolvedModel!==null&&(typeof resolvedModel!=='string'||!resolvedModel||resolvedModel.includes('\0')))throw clientFailure('Resolved model must be a nonempty string without NUL');
|
|
20
|
-
const native=exact||rule.commands.includes(forwarded[0]),prompt=forwarded.length>0&&!forwarded[0].startsWith('-')&&!rule.commands.includes(forwarded[0]),oneShot=!native&&(options.non_interactive?true:options.interactive?false:prompt||!attachedToTerminal),commandMode=['codex','opencode'].includes(info.client),hasMode=
|
|
20
|
+
const native=exact||rule.commands.includes(forwarded[0]),prompt=forwarded.length>0&&!forwarded[0].startsWith('-')&&!rule.commands.includes(forwarded[0]),oneShot=!native&&(options.non_interactive?true:options.interactive?false:prompt||!attachedToTerminal),commandMode=['codex','opencode'].includes(info.client),hasMode=commandMode?[rule.mode,...rule.aliases].includes(forwarded[0]):forwarded.some(word=>[rule.mode,...rule.aliases].includes(word)),result=[];let note=null;
|
|
21
21
|
if(commandMode&&hasMode){const first=forwarded.shift();if(first!==undefined)result.push(first);}else if(commandMode&&oneShot&&rule.mode)result.push(rule.mode);
|
|
22
22
|
if(resolvedModel!==null&&rule.modelFlag&&!forwarded.some(word=>word==='-m'||word==='--model'||word.startsWith('--model='))){result.push(rule.modelFlag,['opencode','agent'].includes(info.client)&&!resolvedModel.includes('/')?'link-assistant/'+resolvedModel:resolvedModel);}
|
|
23
|
-
if(!commandMode&&oneShot&&!hasMode
|
|
23
|
+
if(!commandMode&&oneShot&&!hasMode){if(rule.modeTakesValue&&!prompt)note=rules.noPromptNote;else if(rule.mode)result.push(rule.mode);}
|
|
24
24
|
result.push(...forwarded);return {arguments:result,one_shot:oneShot,note};
|
|
25
25
|
}
|
|
26
26
|
export function preflightNativeClientLaunch(client,options={}){
|
|
@@ -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
|
+
}
|