@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.
Files changed (161) hide show
  1. package/README.md +35 -2
  2. package/catalog.json +68542 -0
  3. package/index.d.ts +5932 -0
  4. package/index.js +224 -0
  5. package/native.d.ts +106 -0
  6. package/package.json +62 -4
  7. package/portable/policy.mjs +117 -0
  8. package/schemas/accounts-list.v1.json +323 -0
  9. package/schemas/accounts-pause.v1.json +97 -0
  10. package/schemas/accounts-policy.v1.json +214 -0
  11. package/schemas/accounts-resume.v1.json +97 -0
  12. package/schemas/auth-claude.v1.json +97 -0
  13. package/schemas/auth-clear.v1.json +97 -0
  14. package/schemas/auth-codex.v1.json +97 -0
  15. package/schemas/auth-gh.v1.json +97 -0
  16. package/schemas/auth-import.v1.json +167 -0
  17. package/schemas/auth-status.v1.json +387 -0
  18. package/schemas/cli-error.v1.json +97 -0
  19. package/schemas/clients-backup-create.v1.json +97 -0
  20. package/schemas/clients-backup-list.v1.json +234 -0
  21. package/schemas/clients-backup-restore.v1.json +97 -0
  22. package/schemas/clients-backup-verify.v1.json +125 -0
  23. package/schemas/clients-doctor.v1.json +249 -0
  24. package/schemas/clients-install.v1.json +164 -0
  25. package/schemas/clients-list.v1.json +194 -0
  26. package/schemas/clients-reinstall.v1.json +164 -0
  27. package/schemas/clients-remove.v1.json +97 -0
  28. package/schemas/clients-repair.v1.json +109 -0
  29. package/schemas/clients-reset.v1.json +113 -0
  30. package/schemas/clients-setup.v1.json +97 -0
  31. package/schemas/clients-show.v1.json +191 -0
  32. package/schemas/clients-update.v1.json +164 -0
  33. package/schemas/configure.v1.json +97 -0
  34. package/schemas/contracts.v1.json +106 -0
  35. package/schemas/data-backup.v1.json +32 -0
  36. package/schemas/deploy.v1.json +546 -0
  37. package/schemas/doctor.v1.json +324 -0
  38. package/schemas/local-deployment.v1.json +364 -0
  39. package/schemas/logs-anomalies.v1.json +112 -0
  40. package/schemas/logs-show.v1.json +127 -0
  41. package/schemas/logs-summary.v1.json +129 -0
  42. package/schemas/model-catalog.v1.json +117 -0
  43. package/schemas/models-explain.v1.json +325 -0
  44. package/schemas/preservation.v1.json +47 -0
  45. package/schemas/providers-add.v1.json +185 -0
  46. package/schemas/providers-import.v1.json +97 -0
  47. package/schemas/providers-list.v1.json +182 -0
  48. package/schemas/providers-remove.v1.json +97 -0
  49. package/schemas/providers-show.v1.json +179 -0
  50. package/schemas/serve.v1.json +97 -0
  51. package/schemas/server-claim.v1.json +97 -0
  52. package/schemas/server-reap.v1.json +97 -0
  53. package/schemas/server-remove.v1.json +97 -0
  54. package/schemas/server-start.v1.json +97 -0
  55. package/schemas/server-status.v1.json +197 -0
  56. package/schemas/server-stop.v1.json +97 -0
  57. package/schemas/server-use.v1.json +97 -0
  58. package/schemas/staging.v1.json +47 -0
  59. package/schemas/tls-ca.v1.json +97 -0
  60. package/schemas/tls-generate.v1.json +97 -0
  61. package/schemas/tokens-expire.v1.json +97 -0
  62. package/schemas/tokens-import.v1.json +192 -0
  63. package/schemas/tokens-issue.v1.json +94 -0
  64. package/schemas/tokens-list.v1.json +272 -0
  65. package/schemas/tokens-recover-admin.v1.json +116 -0
  66. package/schemas/tokens-revoke.v1.json +97 -0
  67. package/schemas/tokens-rotate.v1.json +94 -0
  68. package/schemas/tokens-show.v1.json +269 -0
  69. package/schemas/tunnel-down.v1.json +97 -0
  70. package/schemas/tunnel-status.v1.json +165 -0
  71. package/schemas/tunnel-up.v1.json +97 -0
  72. package/schemas/usage.v1.json +621 -0
  73. package/schemas/verification.v1.json +254 -0
  74. package/schemas/verify.v1.json +338 -0
  75. package/schemas/version.v1.json +103 -0
  76. package/schemas/with.v1.json +105 -0
  77. package/src/accounts.mjs +233 -0
  78. package/src/activitypub.mjs +23 -0
  79. package/src/admin-assets.mjs +16 -0
  80. package/src/admin.mjs +108 -0
  81. package/src/affinities.mjs +180 -0
  82. package/src/affinity-schema-descriptor.mjs +2 -0
  83. package/src/affinity-schema.mjs +185 -0
  84. package/src/assets/admin/assets/app.js +1 -0
  85. package/src/assets/admin/assets/react.js +9 -0
  86. package/src/assets/admin/assets/rolldown-runtime.js +1 -0
  87. package/src/assets/admin/assets/ui-vendor.js +3 -0
  88. package/src/assets/admin/index.html +16 -0
  89. package/src/auth-service.mjs +149 -0
  90. package/src/claude-process-session.mjs +26 -0
  91. package/src/cli-output.mjs +21 -0
  92. package/src/cli.mjs +84 -0
  93. package/src/client-ca.mjs +8 -0
  94. package/src/client-catalog.mjs +52 -0
  95. package/src/client-codex-catalog.mjs +18 -0
  96. package/src/client-configure.mjs +72 -0
  97. package/src/client-files.mjs +82 -0
  98. package/src/client-global-repair.mjs +19 -0
  99. package/src/client-global-state.mjs +19 -0
  100. package/src/client-global.mjs +43 -0
  101. package/src/client-json.mjs +54 -0
  102. package/src/client-launch-plan.mjs +28 -0
  103. package/src/client-launch.mjs +35 -0
  104. package/src/client-persistent.mjs +66 -0
  105. package/src/client-process-profile.mjs +52 -0
  106. package/src/client-process-settings.mjs +36 -0
  107. package/src/client-process.mjs +44 -0
  108. package/src/client-profile-backup.mjs +29 -0
  109. package/src/client-remote-health.mjs +7 -0
  110. package/src/client-remote.mjs +55 -0
  111. package/src/client-run-credential.mjs +38 -0
  112. package/src/client-setup.mjs +97 -0
  113. package/src/client-status.mjs +102 -0
  114. package/src/client-toml-cst.mjs +71 -0
  115. package/src/client-transaction.mjs +48 -0
  116. package/src/codex-login.mjs +121 -0
  117. package/src/codex-loopback-transport.mjs +34 -0
  118. package/src/codex-loopback.mjs +60 -0
  119. package/src/config.mjs +198 -0
  120. package/src/core.mjs +198 -0
  121. package/src/credential-operations.mjs +119 -0
  122. package/src/doublets.mjs +157 -0
  123. package/src/emergency-auth.mjs +91 -0
  124. package/src/file-lock.mjs +107 -0
  125. package/src/gemini-protocol.mjs +133 -0
  126. package/src/geolocation.mjs +46 -0
  127. package/src/git-proxy.mjs +52 -0
  128. package/src/github-proxy.mjs +74 -0
  129. package/src/http-management.mjs +36 -0
  130. package/src/http-route-contract.mjs +479 -0
  131. package/src/index.mjs +4 -0
  132. package/src/local-router-discovery.mjs +31 -0
  133. package/src/managed-server.mjs +411 -0
  134. package/src/management-access.mjs +76 -0
  135. package/src/native-service.mjs +392 -0
  136. package/src/oauth.mjs +547 -0
  137. package/src/operation-input.mjs +20 -0
  138. package/src/operations.mjs +378 -0
  139. package/src/protocols.mjs +229 -0
  140. package/src/provider-manifest.mjs +46 -0
  141. package/src/provider-provision.mjs +24 -0
  142. package/src/remote-operations.mjs +166 -0
  143. package/src/request-log.mjs +99 -0
  144. package/src/resources.mjs +290 -0
  145. package/src/response-contracts.mjs +147 -0
  146. package/src/responses.mjs +103 -0
  147. package/src/routing.mjs +40 -0
  148. package/src/runtime-config.mjs +133 -0
  149. package/src/runtime-payload.mjs +190 -0
  150. package/src/sensitive-data-sse.mjs +121 -0
  151. package/src/sensitive-data.mjs +254 -0
  152. package/src/server.mjs +552 -0
  153. package/src/storage.mjs +367 -0
  154. package/src/streams.mjs +232 -0
  155. package/src/token-import.mjs +68 -0
  156. package/src/token-reservation.mjs +8 -0
  157. package/src/tokens.mjs +172 -0
  158. package/src/usage.mjs +54 -0
  159. package/src/websocket-relay.mjs +131 -0
  160. package/testing.d.ts +7 -0
  161. package/testing.js +57 -0
@@ -0,0 +1,46 @@
1
+ /** Rust-compatible provider import syntax, parsed before any provisioning. */
2
+ const fail = message=>Object.assign(new Error(message),{code:'provider_import',exitCode:2});
3
+ const fields = new Set(['name','kind','base_url','default_model','models','supported_clients','api_key','api_key_env','encrypted_api_key','enabled','subscriber_id','acknowledge_intermediary_risk','acknowledge_unsupported_clients','if_absent']);
4
+ function record(input) {
5
+ if (!input || typeof input !== 'object' || Array.isArray(input) || typeof input.name !== 'string' || typeof input.base_url !== 'string') throw fail('Provider declarations require name and base_url strings');
6
+ const result = {if_absent:false,...Object.fromEntries(Object.entries(input).filter(([key])=>fields.has(key)))};
7
+ for (const name of ['kind','default_model','api_key','api_key_env','encrypted_api_key','subscriber_id']) if (result[name] != null && typeof result[name] !== 'string') throw fail(`${name} must be a string`);
8
+ for (const name of ['models','supported_clients','acknowledge_unsupported_clients']) if (result[name] != null && (!Array.isArray(result[name]) || result[name].some(value=>typeof value !== 'string'))) throw fail(`${name} must contain strings`);
9
+ for (const name of ['enabled','acknowledge_intermediary_risk','if_absent']) if (result[name] != null && typeof result[name] !== 'boolean') throw fail(`${name} must be boolean`);
10
+ if ((result.kind ?? '').toLowerCase() === 'lefine' && result.api_key) throw fail('Lefine import files cannot contain plaintext api_key material; use api_key_env or providers add --api-key-stdin');
11
+ return result;
12
+ }
13
+ export function parseProviderImport(text) {
14
+ if (typeof text !== 'string') throw fail('Provider import requires UTF-8 text');
15
+ const trimmed=text.trimStart();let inputs;
16
+ if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
17
+ const value=JSON.parse(text);inputs=Array.isArray(value) ? value : Array.isArray(value?.providers) ? value.providers : [value];
18
+ } else if (text.split(/\r?\n/).some(line=>line.startsWith('PROVIDER: '))) {
19
+ inputs=text.split(/\r?\n/).map(line=>line.trim()).filter(line=>line.startsWith('PROVIDER: ')).map(line=>JSON.parse(line.slice(10)));
20
+ } else {
21
+ inputs=[];let current;
22
+ const aliases={'base-url':'base_url',api_base:'base_url','api-base':'base_url',model:'default_model','default-model':'default_model','supported-clients':'supported_clients','api-key':'api_key','api-key-env':'api_key_env','subscriber-id':'subscriber_id','acknowledge-intermediary-risk':'acknowledge_intermediary_risk','acknowledge-unsupported-clients':'acknowledge_unsupported_clients'};
23
+ for (const raw of text.split(/\r?\n/)) {
24
+ if (!raw.trim() || raw.trimStart().startsWith('#')) continue;
25
+ if (!/^[ \t]/.test(raw)) {current={name:raw.trim(),kind:'openai-compatible',base_url:'',models:[],supported_clients:[],enabled:true,if_absent:false};inputs.push(current);continue;}
26
+ if (!current) throw fail('Indented provider field without provider name');
27
+ const match=/^(\S+)\s+(.*)$/.exec(raw.trim());if (!match) throw fail('Provider field must be key value');
28
+ const key=aliases[match[1]] ?? match[1];let value=match[2].trim();if (value.startsWith('"') && value.endsWith('"')) value=value.slice(1,-1);
29
+ if (!fields.has(key) || ['name','encrypted_api_key','if_absent'].includes(key)) throw fail(`Unknown provider field: ${match[1]}`);
30
+ if (['models','supported_clients','acknowledge_unsupported_clients'].includes(key)) value=value.split(',').map(value=>value.trim()).filter(Boolean);
31
+ else if (['enabled','acknowledge_intermediary_risk'].includes(key)) value=['true','1','yes'].includes(value);
32
+ current[key]=value;
33
+ }
34
+ if (!inputs.length) throw fail('Provider import did not contain any providers');
35
+ }
36
+ return inputs.map(record);
37
+ }
38
+
39
+ /** Decode the public typed acceptance DTO; discard unexpected secret fields. */
40
+ export function providerProvisionResponse(answer) {
41
+ if (!answer || !['created','replaced','already_present'].includes(answer.outcome) || typeof answer.name !== 'string' || !['openai-compatible','lefine','zai-coding-plan'].includes(answer.kind) || typeof answer.base_url !== 'string') throw fail('Remote provider acceptance is unverified');
42
+ for (const key of ['models','supported_clients','unsupported_clients']) if (!Array.isArray(answer[key]) || answer[key].some(value=>typeof value !== 'string')) throw fail('Remote provider acceptance is unverified');
43
+ for (const key of ['has_encrypted_api_key','enabled','intermediary_risk_acknowledged']) if (typeof answer[key] !== 'boolean') throw fail('Remote provider acceptance is unverified');
44
+ for (const key of ['default_model','api_key_env']) if (answer[key] != null && typeof answer[key] !== 'string') throw fail('Remote provider acceptance is unverified');
45
+ return Object.fromEntries(['outcome','name','kind','base_url','models','supported_clients','has_encrypted_api_key','enabled','intermediary_risk_acknowledged','unsupported_clients','default_model','api_key_env'].filter(key=>answer[key] != null).map(key=>[key,answer[key]]));
46
+ }
@@ -0,0 +1,24 @@
1
+ /** Local provider acceptance. Specialized providers require separate reviewed probes. */
2
+ import {providerProvisionResponse} from './provider-manifest.mjs';
3
+ const failure = (outcome,message)=>Object.assign(new Error(message),{code:'provider_acceptance',outcome,exitCode:1});
4
+ export async function provisionLocalProvider(core,input) {
5
+ const kind=(input.kind ?? 'openai-compatible').toLowerCase();
6
+ if (!['openai-compatible','openai','openai_like','litellm','open-a-i-compatible'].includes(kind)) throw failure('unverified','Specialized provider acceptance requires its reviewed live catalog probe');
7
+ try {
8
+ if (!core.installProvider && !core.providers?.install) throw failure('unverified','Injected provider store cannot confirm atomic installation');
9
+ const installed=core.installProvider ? await core.installProvider(input) : await core.providers.install(input);
10
+ return providerProvisionResponse({...installed.record,outcome:installed.outcome});
11
+ } catch(error) {
12
+ if (error.outcome) throw error;
13
+ if (error.code === 'invalid_provider' || error.code === 'invalid_config') throw failure('invalid_candidate','Provider candidate is invalid');
14
+ throw failure('persistence_uncertain','Provider store could not confirm installation');
15
+ }
16
+ }
17
+ export async function importLocalProviders(core,records) {
18
+ const report={complete:true,results:[]};
19
+ for(const record of records) {
20
+ try {report.results.push(await provisionLocalProvider(core,record));}
21
+ catch(error) {report.complete=false;report.results.push({name:record.name,outcome:error.outcome ?? 'unverified'});break;}
22
+ }
23
+ return report;
24
+ }
@@ -0,0 +1,166 @@
1
+ /** Exact management requests used by the state CLI; no local fallback. */
2
+ import { open } from 'node:fs/promises';
3
+ import { constants } from 'node:fs';
4
+ import { resolve } from 'node:path';
5
+ import { request as httpsRequest } from 'node:https';
6
+ import { rootCertificates } from 'node:tls';
7
+ import { Readable } from 'node:stream';
8
+ import {parseProviderImport,providerProvisionResponse} from './provider-manifest.mjs';
9
+
10
+ const error = (message,exitCode = 1) => Object.assign(new Error(message),{code:'remote-operation',exitCode});
11
+ const out = (...output) => ({output});
12
+ const segment = value => encodeURIComponent(String(value)).replace(/[!'()*]/g,ch=>`%${ch.charCodeAt(0).toString(16).toUpperCase()}`);
13
+ const list = value => value === undefined ? [] : Array.isArray(value) ? value : [value];
14
+ const nullish = value => value === undefined ? null : value;
15
+ const positive = (value,fallback,zero = false) => {
16
+ const parsed = value === undefined ? fallback : Number(value);
17
+ if (!Number.isSafeInteger(parsed) || parsed < (zero ? 0 : 1)) throw error('Numeric limit must be a safe integer in the supported range',2);
18
+ return parsed;
19
+ };
20
+
21
+ export function parsePauseUntil(value,now = Math.floor(Date.now()/1000)) {
22
+ if (value === undefined) return null;
23
+ const text = String(value).trim();let result;
24
+ if (/^\d+$/.test(text)) result = Number(text);
25
+ else if (/^\d+[smhd]$/.test(text)) result = now + Number(text.slice(0,-1)) * ({s:1,m:60,h:3600,d:86400})[text.at(-1)];
26
+ else if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/.test(text)) result = Math.floor(Date.parse(text)/1000);
27
+ if (!Number.isSafeInteger(result) || result < 0) throw error('Pause deadline must be Unix seconds, RFC 3339, or a delay like 90m in the safe integer range',2);
28
+ return result;
29
+ }
30
+
31
+ export const remoteStateFamilies = new Set(['accounts','auth','tokens','providers','logs','tls','doctor','usage','models']);
32
+ export function nativeRemoteCall(name,options = {},invocation = {}) {
33
+ if (name === 'tokens.issue') return {method:'POST',path:'/api/management/tokens',body:{
34
+ ttl_hours:positive(options.ttl_hours,24),label:options.label ?? '',account:nullish(options.account),
35
+ max_requests:options.max_requests === undefined ? null : positive(options.max_requests,0,true),
36
+ max_tokens:options.max_tokens === undefined ? null : positive(options.max_tokens,0,true),
37
+ rate_limit_per_minute:options.rate_limit_per_minute === undefined ? null : positive(options.rate_limit_per_minute,0,true),
38
+ scope:options.admin ? 'admin' : null,github_repos:list(options.github_repo).length ? list(options.github_repo) : null,
39
+ allowed_models:list(options.allowed_model).length ? list(options.allowed_model) : null}};
40
+ if (name === 'tokens.rotate') return {method:'POST',path:'/api/management/tokens/rotate-client',body:{id:options.id,
41
+ ttl_hours:positive(options.ttl_hours,24),label:options.label ? options.label : null,
42
+ max_requests:options.max_requests === undefined ? null : positive(options.max_requests,0,true),max_tokens:options.max_tokens === undefined ? null : positive(options.max_tokens,0,true),
43
+ rate_limit_per_minute:options.rate_limit_per_minute === undefined ? null : positive(options.rate_limit_per_minute,0,true),account:nullish(options.account)}};
44
+ if (name === 'tokens.list' || name === 'tokens.show') return {method:'GET',path:'/api/management/tokens'};
45
+ if (name === 'tokens.revoke' || name === 'tokens.expire') return {method:'POST',path:'/api/management/tokens/revoke',body:{id:options.id}};
46
+ if (name === 'accounts.list') return {method:'GET',path:'/api/management/accounts'};
47
+ if (name === 'accounts.pause') return {method:'POST',path:`/api/management/accounts/${segment(options.name)}/pause`,body:{reason:options.reason ?? 'paused by an operator',until_unix:parsePauseUntil(options.until,invocation.nowUnix)}};
48
+ if (name === 'accounts.resume') return {method:'POST',path:`/api/management/accounts/${segment(options.name)}/resume`,body:{}};
49
+ if (name === 'accounts.policy') return {method:options.file ? 'POST' : 'GET',path:`/api/management/accounts/${segment(options.name)}/policy`};
50
+ if (name === 'providers.list') return {method:'GET',path:'/api/management/providers'};
51
+ if (name === 'providers.show' || name === 'providers.remove') return {method:name.endsWith('remove') ? 'DELETE' : 'GET',path:`/api/management/providers/${segment(options.name)}`};
52
+ if (name === 'providers.add') {
53
+ const apiKey = options.api_key_stdin ? String(invocation.stdin ?? '').split(/\r?\n/)[0].trim() : undefined;
54
+ if (options.api_key_stdin && !apiKey) throw error('api-key-stdin requires a nonempty input line',2);
55
+ return {method:'POST',path:'/api/management/providers',body:{name:options.name,kind:options.kind ?? 'openai-compatible',
56
+ base_url:nullish(options.base_url),default_model:nullish(options.model),models:list(options.models),
57
+ supported_clients:list(options.supported_clients),api_key:nullish(apiKey),api_key_env:nullish(options.api_key_env),
58
+ encrypted_api_key:null,enabled:options.enabled ?? true,subscriber_id:nullish(options.subscriber_id),
59
+ acknowledge_intermediary_risk:options.acknowledge_intermediary_risk ?? false,
60
+ acknowledge_unsupported_clients:list(options.acknowledge_unsupported_client),if_absent:options.if_absent ?? false}};
61
+ }
62
+ if (name === 'auth.status') return {method:'GET',path:'/api/management/auth/status'};
63
+ return null;
64
+ }
65
+
66
+ async function inputText(filename,cwd) {
67
+ const path = resolve(cwd,filename),file = await open(path,constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
68
+ try {
69
+ const stat = await file.stat(); if (!stat.isFile() || stat.size > 4 * 1024 * 1024) throw error('Operation input must be a regular file within 4 MiB',2);
70
+ const buffer = Buffer.alloc(4 * 1024 * 1024 + 1);const {bytesRead} = await file.read(buffer,0,buffer.length,0);
71
+ if (bytesRead === buffer.length) throw error('Operation input exceeds 4 MiB',2);
72
+ return new TextDecoder('utf-8',{fatal:true}).decode(buffer.subarray(0,bytesRead));
73
+ } finally { await file.close(); }
74
+ }
75
+
76
+ async function trustedFetch(url,options,certificatePath,cwd) {
77
+ const file = await open(resolve(cwd,certificatePath),constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));let ca;
78
+ try {
79
+ const stat = await file.stat();if (!stat.isFile() || stat.size > 1024 * 1024) throw error('Management CA must be a regular file within 1 MiB');
80
+ ca = await file.readFile();if (!ca.includes(Buffer.from('-----BEGIN CERTIFICATE-----'))) throw error('Management CA does not contain a PEM certificate');
81
+ } finally {await file.close();}
82
+ if (new URL(url).protocol !== 'https:') throw error('Custom management CA requires HTTPS');
83
+ return new Promise((resolveResponse,reject)=> {
84
+ const request = httpsRequest(url,{method:options.method,headers:options.headers,signal:options.signal,ca:[...rootCertificates,ca]},response=> {
85
+ resolveResponse({status:response.statusCode,ok:response.statusCode >= 200 && response.statusCode < 300,url,body:Readable.toWeb(response)});
86
+ });
87
+ request.once('error',reject);request.end(options.body);
88
+ });
89
+ }
90
+
91
+ export async function sendRemoteManagement(target,call,{fetch = globalThis.fetch,signal,deadlineMs = 30000,maxOutputBytes = 4 * 1024 * 1024,cwd = process.cwd()} = {}) {
92
+ positive(deadlineMs,30000);positive(maxOutputBytes,4 * 1024 * 1024);
93
+ const controller = new AbortController(),timer = setTimeout(()=>controller.abort(),deadlineMs);
94
+ const combined = signal ? AbortSignal.any([signal,controller.signal]) : controller.signal;
95
+ let reader;const aborted = new Promise((_,reject)=> {
96
+ const abort = ()=>reject(error('Remote operation cancelled or its deadline elapsed'));
97
+ if (combined.aborted) abort();else combined.addEventListener('abort',abort,{once:true});
98
+ });
99
+ // Cancellation wins ties: an injected fetch may already be settled when the
100
+ // caller's signal was aborted, and race order decides between settled inputs.
101
+ aborted.catch(()=>{});const within = promise=>Promise.race([aborted,promise]);
102
+ try {
103
+ if (combined.aborted) await aborted;
104
+ const url = target.managementServer+call.path;
105
+ const request = {method:call.method,redirect:'error',signal:combined,
106
+ headers:{accept:'application/json',...(call.client ? {'x-link-assistant-client':call.client} : {}),...(target.token ? {authorization:`Bearer ${target.token}`} : {}),...(call.body !== undefined ? {'content-type':'application/json'} : {})},
107
+ ...(call.body !== undefined ? {body:JSON.stringify(call.body)} : {})};
108
+ const response = await within(target.managementCaCert ? trustedFetch(url,request,target.managementCaCert,cwd) : fetch(url,request));
109
+ if (response.url && new URL(response.url).origin !== target.managementServer) throw error('Remote management response changed origin');
110
+ const chunks = [];let bytes = 0;reader = response.body?.getReader();
111
+ if(call.response==='status-only')return {status:response.status};
112
+ if (reader) while (true) {
113
+ const part = await within(reader.read());if (part.done) break;bytes += part.value.byteLength;
114
+ if (bytes > maxOutputBytes) throw error('Remote management response exceeds the output budget');chunks.push(part.value);
115
+ }
116
+ const text = new TextDecoder('utf-8',{fatal:true}).decode(Buffer.concat(chunks,bytes));
117
+ let answer;try {answer = call.response==='router-health'&&text.trim()==='ok' ? {status:'ok'} : text ? JSON.parse(text) : {};}catch {throw error(`Selected router ${target.server} returned invalid JSON`);}
118
+ if (!response.ok) {
119
+ const failure = error(`Selected router ${target.server} returned HTTP ${response.status}`,response.status === 404 && call.method === 'GET' ? 2 : 1);
120
+ failure.status = response.status;failure.remoteOutcome = answer?.error?.outcome;throw failure;
121
+ }
122
+ return answer;
123
+ } catch (failure) {
124
+ if (failure.code === 'remote-operation') throw failure;
125
+ throw error(combined.aborted ? 'Remote operation cancelled or its deadline elapsed' : `Selected router ${target.server} request failed`);
126
+ } finally {
127
+ clearTimeout(timer);controller.abort();
128
+ // A hostile/injected stream may never settle cancel(). Deadline enforcement
129
+ // must not wait for that stream to cooperate.
130
+ if (reader) {Promise.resolve(reader.cancel()).catch(()=>{});try {reader.releaseLock();} catch {}}
131
+ }
132
+ }
133
+
134
+ export async function executeRemoteOperation({name,options = {},invocation = {},target,fetch = globalThis.fetch}) {
135
+ if (['tokens.import','tokens.recover-admin'].includes(name)) throw error(`${name} proves local store ownership and has no remote form for ${target.server}; pass --local.`,2);
136
+ if (name === 'providers.import') {
137
+ const records = parseProviderImport(await inputText(options.path,invocation.cwd ?? process.cwd()));
138
+ const report = {complete:true,results:[]};
139
+ for (const record of records) {
140
+ try {
141
+ const result = await sendRemoteManagement(target,{method:'POST',path:'/api/management/providers',body:record},{fetch,...invocation});
142
+ const accepted = providerProvisionResponse(result);if (accepted.name !== record.name) throw error('Remote provider acceptance named a different candidate');
143
+ report.results.push(accepted);
144
+ } catch (failure) {
145
+ report.complete = false;report.results.push({name:record.name,outcome:['invalid_candidate','credential_rejected','rate_limited','unverified','persistence_uncertain'].includes(failure.remoteOutcome) ? failure.remoteOutcome : 'unverified'});break;
146
+ }
147
+ }
148
+ if (!report.complete) {const failure = error('Provider import stopped at the first failed acceptance');failure.data = out(JSON.stringify(report,null,2));throw failure;}
149
+ return out(JSON.stringify(report,null,2));
150
+ }
151
+ const call = nativeRemoteCall(name,options,invocation);
152
+ if (!call) throw error(`${name} cannot answer for selected router ${target.server} from here; pass --local to act on this machine.`);
153
+ if (name === 'accounts.policy' && options.file) call.body = JSON.parse(await inputText(options.file,invocation.cwd ?? process.cwd()));
154
+ const answer = await sendRemoteManagement(target,call,{fetch,...invocation});
155
+ if (name === 'tokens.list') {if (!Array.isArray(answer.data)) throw error('Remote token list is malformed');return answer.data;}
156
+ if (name === 'tokens.show') {if (!Array.isArray(answer.data)) throw error('Remote token list is malformed');const held = answer.data.find(record=>record.id === options.id);if (!held) throw error(`not found: ${options.id}`,2);return held;}
157
+ if (name === 'tokens.issue' || name === 'tokens.rotate') {if (typeof answer.token !== 'string' || !answer.token) throw error('Remote token issuance is malformed');return {token:answer.token};}
158
+ if (name === 'tokens.revoke' || name === 'tokens.expire') return out(`revoked ${options.id}`);
159
+ if (name === 'providers.list') {if (!Array.isArray(answer.data)) throw error('Remote provider list is malformed');return answer.data;}
160
+ if (name === 'providers.add') return providerProvisionResponse(answer);
161
+ if (name === 'providers.remove') return out(`removed ${options.name}`);
162
+ if (name === 'accounts.pause') return out(`server: ${target.server} (${target.source})`,answer.until_unix == null ? `paused ${options.name} until it is resumed` : `paused ${options.name} until ${new Date(answer.until_unix * 1000).toISOString().replace('.000Z','+00:00')}`);
163
+ if (name === 'accounts.resume') return out(`server: ${target.server} (${target.source})`,answer.was_paused === false ? `${options.name} was not paused` : `resumed ${options.name}`);
164
+ if (name === 'auth.status') {if (!Array.isArray(answer.credentials)) throw error('Remote credential status is malformed');return {server:target.server,credentials:answer.credentials,sources:[],api_key_providers:[],output:[]};}
165
+ return answer;
166
+ }
@@ -0,0 +1,99 @@
1
+ import {createHash,randomUUID} from 'node:crypto';
2
+ import {AsyncLocalStorage} from 'node:async_hooks';
3
+ import {mkdir,lstat,readdir,unlink,rename,chmod,open,rm} from 'node:fs/promises';
4
+ import {join,dirname,resolve} from 'node:path';
5
+ import {constants} from 'node:fs';
6
+ import {atomicWrite,serialized} from './storage.mjs';
7
+ import {decodeLogLine} from './resources.mjs';
8
+ import {ProtocolError} from './protocols.mjs';
9
+ import {matchHTTPRoute,OPAQUE_NATIVE_ROUTES} from './http-route-contract.mjs';
10
+ const context=new AsyncLocalStorage();
11
+ const errorName=name=>/^error-\d{20}-[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}\.json$/i.test(name);
12
+ const keyName=name=>name.replace(/([a-z0-9])([A-Z])/g,'$1_$2').replace(/[^a-z0-9]+/gi,'_').toLowerCase();
13
+ const secretName=name=>/^(?:authorization|proxy_authorization|x_api_key|api_key|key|cookie|set_cookie|access_token|refresh_token|oauth_token|auth_token|security_token|x_auth_token|x_goog_api_key|x_amz_security_token|token|password|secret|client_secret|private_key)$/.test(keyName(name)) || /_(?:password|secret|token|api_key)$/.test(keyName(name));
14
+ const secretValue=value=>/^bearer /i.test(value.trim()) || /(?:sk-ant-|la_sk_|at-|la_admin_)/.test(value) || /^eyJ[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}$/.test(value.trim());
15
+ const mask=value=>{const text=String(value).trim(),bearer=/^(Bearer )(.*)$/i.exec(text),parts=[...(bearer?.[2] ?? text)],masked=parts.length<12?'[REDACTED]':parts.slice(0,3).join('')+'*'.repeat(parts.length-6)+parts.slice(-3).join('');return (bearer?.[1] ?? '')+masked;};
16
+ export function logRedact(value) {
17
+ if(Array.isArray(value))return value.map(logRedact);
18
+ if(value && typeof value==='object')return Object.fromEntries(Object.entries(value).map(([name,child])=>[name,['metadata','safety_identifier','user_id','prompt_cache_key'].includes(keyName(name)) ? '[REDACTED]' : secretName(name) ? typeof child==='string'?mask(child):'[REDACTED]' : keyName(name)==='uri' && typeof child==='string' ? logURI(child):logRedact(child)]));
19
+ return typeof value==='string' && secretValue(value) ? mask(value):value;
20
+ }
21
+ export function logURI(value) {const [path,...query]=value.split('?');if(!query.length)return value;return path+'?'+query.join('?').split('&').map(part=>{const index=part.indexOf('='),name=index<0?part:part.slice(0,index),raw=index<0?'':part.slice(index+1);let decoded=raw,decodedName=name;try{decoded=decodeURIComponent(raw);decodedName=decodeURIComponent(name);}catch{}return secretName(decodedName) || secretValue(decoded) ? name+'='+mask(decoded):part;}).join('&');}
22
+ const bodyValue=bytes=>{let text;try{text=new TextDecoder('utf8',{fatal:true}).decode(bytes);}catch{return {base64:Buffer.from(bytes).toString('base64'),bytes:bytes.length};}try{return logRedact(JSON.parse(text));}catch{return text;}};
23
+ export function encodeLogLine(value) {
24
+ const quote=text=>'"'+(text===''?'%z':text.replace(/[%"\\()\n\r\t]/g,char=>'%'+char.charCodeAt(0).toString(16).toUpperCase().padStart(2,'0')))+'"';
25
+ if(value==null)return '()';if(typeof value==='string')return quote(value);if(Array.isArray(value))return '(#a'+value.map(child=>' '+encodeLogLine(child)).join('')+')';if(typeof value==='object')return '(#o'+Object.keys(value).sort().map(name=>' ('+quote(name)+' '+encodeLogLine(value[name])+')').join('')+')';return JSON.stringify(value);
26
+ }
27
+ async function stat(path) {try{return await lstat(path);}catch(error){if(error.code==='ENOENT')return null;throw error;}}
28
+ async function realPath(path) {let current=resolve(path);for(;;){const entry=await stat(current);if(entry?.isSymbolicLink())throw new ProtocolError('Log path cannot contain symlinks',400);if(current===dirname(current))return;current=dirname(current);}}
29
+ async function regularBytes(path,limit) {await realPath(path);const file=await open(path,constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));try{const entry=await file.stat();if(!entry.isFile())throw new ProtocolError('Log path must be a regular file',400);if(entry.size>limit)throw new ProtocolError('Log document exceeds limit',500);return file.readFile();}finally{await file.close();}}
30
+ /** Actual bounded, private retained exchanges; never a synthetic management log. */
31
+ export class NativeRequestLog {
32
+ constructor({config={},env={},clock=Date.now}={}) {
33
+ this.root=env.REQUEST_LOG || join(config.data_dir,'requests');this.maxBytes=positive(env.REQUEST_LOG_MAX_BYTES,100*1024*1024);this.maxTotal=nonnegative(env.REQUEST_LOG_MAX_TOTAL_BYTES,4*1024*1024*1024);
34
+ this.errorRoot=env.ERROR_LOG_DIR || null;this.errorMax=nonnegative(env.ERROR_LOG_MAX_BYTES,10*1024*1024);this.clock=clock;this.active=new Map();this.generation=0;this.lastError=null;
35
+ }
36
+ async files() {
37
+ await realPath(this.root);const entry=await stat(this.root);if(!entry)return [];if(!entry.isDirectory())throw new ProtocolError('Request log root must be a directory',400);const files=[];
38
+ for(const dir of (await readdir(this.root)).sort()){const directory=join(this.root,dir),info=await stat(directory);if(!info?.isDirectory() || info.isSymbolicLink())continue;for(const name of ['requests.lino','requests.jsonl']){const path=join(directory,name),file=await stat(path);if(file?.isFile() && !file.isSymbolicLink())files.push({path,bytes:file.size,modified:file.mtimeMs,token:dir});}}
39
+ return files;
40
+ }
41
+ async record(id,phase,fields,{opaque=false}={}) {
42
+ const route=this.active.get(id),identity=route?.identity ?? {hash:'unauthenticated',id:null,label:null};
43
+ let event={time:new Date(this.clock()).toISOString(),correlation_id:id,phase,...(opaque?{}:{token_hash:identity.hash,token_id:identity.id,token_label:identity.label}),...logRedact(fields)};
44
+ let line=encodeLogLine(event)+'\n';if(Buffer.byteLength(line)>this.maxBytes){event={time:event.time,correlation_id:id,phase,...(opaque?{}:{token_hash:identity.hash,token_id:identity.id,token_label:identity.label}),body:`[OMITTED: ${Buffer.byteLength(line)} byte record exceeds log limit]`};line=encodeLogLine(event)+'\n';}
45
+ if(Buffer.byteLength(line)>this.maxBytes)return;
46
+ try{await serialized(this.root+'request',async()=>{
47
+ const directory=join(this.root,identity.hash),path=join(directory,'requests.lino'),legacy=join(directory,'requests.jsonl');await realPath(directory);await mkdir(directory,{recursive:true,mode:0o700});await chmod(this.root,0o700);await chmod(directory,0o700);
48
+ if(!await stat(path) && (await stat(legacy))?.isFile()){await realPath(legacy);await rename(legacy,path);}
49
+ let previous=Buffer.alloc(0);if(await stat(path))previous=await regularBytes(path,this.maxBytes);
50
+ const incoming=Buffer.from(line);if(previous.length+incoming.length>this.maxBytes){const marker=(discarded,retained)=>Buffer.from(encodeLogLine({time:new Date(this.clock()).toISOString(),phase:'log_compaction',body:`[OMITTED: ${discarded} bytes of older records discarded to stay within the request log limit; ${retained} bytes retained]`})+'\n'),budget=this.maxBytes-incoming.length,reserved=marker(previous.length,previous.length).length,marked=reserved<budget,capacity=marked?budget-reserved:budget;let floor=Math.max(0,previous.length-capacity);if(floor>0){const boundary=previous.indexOf(10,floor);floor=boundary<0?previous.length:boundary+1;}previous=Buffer.concat([...(marked && floor>0?[marker(floor,previous.length-floor)]:[]),previous.subarray(floor)]);}
51
+ await atomicWrite(path,Buffer.concat([previous,incoming]));
52
+ if(this.maxTotal){const files=await this.files(),groups=new Map();let total=0;for(const file of files){total+=file.bytes;const held=groups.get(file.token) ?? {bytes:0,modified:0};held.bytes+=file.bytes;held.modified=Math.max(held.modified,file.modified);groups.set(file.token,held);}for(const [token,group] of [...groups].sort(([,a],[,b])=>a.modified-b.modified)){if(total<=this.maxTotal)break;if(token===identity.hash)continue;await rm(join(this.root,token),{recursive:true});total-=group.bytes;}}
53
+ });}catch(error){this.lastError=error.code ?? error.message;}
54
+ }
55
+ async lookup(id) {
56
+ if(!id || Buffer.byteLength(id)>128)throw new ProtocolError('Invalid request id',400);const records=[];let size=0;
57
+ for(const file of await this.files()){const text=(await regularBytes(file.path,this.maxBytes)).toString('utf8');for(const line of text.split('\n'))if(line.includes(id)){const value=decodeLogLine(line);if(value?.correlation_id===id){size+=Buffer.byteLength(line);if(size>10*1024*1024)throw new ProtocolError('request exceeds lookup limit',500);records.push(value);}}}
58
+ return records;
59
+ }
60
+ async errorFiles() {if(!this.errorRoot)return [];await realPath(this.errorRoot);const entry=await stat(this.errorRoot);if(!entry)return [];if(!entry.isDirectory())throw new ProtocolError('Error log root must be a directory',400);const files=[];for(const name of (await readdir(this.errorRoot)).sort()){const entry=await stat(join(this.errorRoot,name));if(errorName(name) && entry?.isFile() && !entry.isSymbolicLink())files.push({name,bytes:entry.size});}return files;}
61
+ async readError(name) {if(!errorName(name))throw new ProtocolError('invalid error filename',400);if(!(await this.errorFiles()).some(file=>file.name===name))throw new ProtocolError('Error capture not found',404);return regularBytes(join(this.errorRoot,name),Math.min(this.errorMax,8*1024*1024));}
62
+ async captureError(id,status,bytes,{complete=true,truncated=false,generation=this.generation}={}) {
63
+ if(!this.errorRoot || !this.errorMax)return;await serialized(this.errorRoot+'error',async()=>{if(generation!==this.generation)return;
64
+ const document=Buffer.from(JSON.stringify({id,status,body:truncated || !complete?'[OMITTED: incomplete or oversized error body]':bodyValue(bytes),complete,truncated}));if(document.length>Math.min(this.errorMax,8*1024*1024))return;
65
+ const files=await this.errorFiles();let total=files.reduce((sum,file)=>sum+file.bytes,0);for(const file of files){if(total+document.length<=this.errorMax)break;await unlink(join(this.errorRoot,file.name));total-=file.bytes;}
66
+ await realPath(this.errorRoot);await mkdir(this.errorRoot,{recursive:true,mode:0o700});await chmod(this.errorRoot,0o700);const time=(BigInt(Math.floor(this.clock()))*1000000n).toString().padStart(20,'0');await atomicWrite(join(this.errorRoot,`error-${time}-${randomUUID()}.json`),document);
67
+ });
68
+ }
69
+ async clear() {await serialized(this.root+'request',async()=>{for(const file of await this.files())await unlink(file.path);if(this.errorRoot)await serialized(this.errorRoot+'error',async()=>{this.generation++;for(const file of await this.errorFiles())await unlink(join(this.errorRoot,file.name));});});}
70
+ queueSnapshot(configured=[]) {const counts=new Map(configured.map(name=>[name,0]));let unassigned=0;for(const route of this.active.values())if(route.account)counts.set(route.account,(counts.get(route.account) ?? 0)+1);else unassigned++;return {accounts:[...counts].sort(([a],[b])=>a.localeCompare(b)).map(([name,in_flight])=>({name,in_flight,queued:0})),in_flight:this.active.size,queued:0,unassigned};}
71
+ select(account) {const id=context.getStore();if(id && this.active.has(id))this.active.get(id).account=account ?? 'primary';}
72
+ async exchange(request,dispatch,{core}={}) {
73
+ const id=randomUUID(),token=request.headers.get('authorization')?.replace(/^Bearer /i,'') ?? request.headers.get('x-api-key');let claims;
74
+ try{if(token)claims=await core?.tokens?.validate(token);}catch{/* Unauthenticated identities share the retained diagnostic directory. */}
75
+ this.active.set(id,{identity:claims?{hash:createHash('sha256').update(token).digest('hex').slice(0,32),id:claims.sub,label:claims.label ?? null}:{hash:'unauthenticated',id:null,label:null},account:null,opaque:false});
76
+ const path=new URL(request.url).pathname,route=matchHTTPRoute(request.method,path),opaque=route && OPAQUE_NATIVE_ROUTES.some(item=>item.path===route.path && item.method===(request.method==='HEAD'?'GET':request.method)),uri=opaque?route.path:logURI(new URL(request.url).pathname+new URL(request.url).search);
77
+ this.active.get(id).opaque=Boolean(opaque);let captured=false,length=0,omitted=false;const chunks=[];
78
+ const requestRecord=async complete=>{if(captured)return;captured=true;await this.record(id,'client_request',{method:request.method,uri,...(opaque?{}:{version:'HTTP/1.1',headers:Object.fromEntries(request.headers),body:complete && !omitted?bodyValue(Buffer.concat(chunks)):length?'[OMITTED: incomplete or oversized request body]':'[NOT READ: request was rejected before the body was consumed]'})},{opaque});};
79
+ let logged=request;
80
+ if(!request.body || opaque){await requestRecord(true);}else {
81
+ const reader=request.body.getReader();const stream=new ReadableStream({async pull(sink){try{const value=await reader.read();if(value.done){await requestRecord(true);reader.releaseLock();sink.close();return;}length+=value.value.length;if(length<=10*1024*1024)chunks.push(Buffer.from(value.value));else omitted=true;sink.enqueue(value.value);}catch(error){await requestRecord(false);sink.error(error);}},async cancel(reason){await requestRecord(false);await reader.cancel(reason);reader.releaseLock();}});
82
+ logged=new Request(request,{body:stream,duplex:'half'});
83
+ }
84
+ let response;try{response=await context.run(id,()=>dispatch(logged));}catch(error){await requestRecord(false);this.active.delete(id);throw error;}
85
+ await requestRecord(false);
86
+ await this.record(id,'client_response',{status:response.status,...(opaque?{uri,upstream_request_id:response.headers.get('x-request-id') ?? response.headers.get('x-oai-request-id')}:{headers:Object.fromEntries(response.headers)})},{opaque});
87
+ return this.wrapResponse(response,{id,phase:'client_response_body',opaque,finish:()=>this.active.delete(id)});
88
+ }
89
+ wrapResponse(response,{id,phase,opaque=false,errorCapture=false,finish=()=>{}}) {
90
+ const reader=response.body?.getReader();if(!reader){finish();return response;}const log=this,generation=this.generation,chunks=[],started=this.clock(),streamed=!response.headers.has('content-type') || response.headers.get('content-type').split(';')[0].trim().toLowerCase()==='text/event-stream',inspectable=!(response.headers.get('content-encoding') ?? '').split(',').some(value=>value.trim() && value.trim().toLowerCase()!=='identity');let total=0,frames=0,truncated=false,finished=false,terminated=false,tail=Buffer.alloc(0),remaining=response.headers.has('content-length')?Number(response.headers.get('content-length')):null;
91
+ const done=async(complete,detail=null)=>{if(finished)return;finished=true;if(errorCapture)await log.captureError(id,response.status,Buffer.concat(chunks),{complete:complete || remaining===0,truncated,generation}).catch(error=>{log.lastError=error.message;});if(!opaque && phase==='upstream_response_body')await log.record(id,'stream_end',{outcome:detail?'upstream_error':!streamed?'completed_not_streamed':terminated?'completed':inspectable?'ended_without_terminator':'encoded_not_verifiable',streamed,inspectable,complete:!detail && (!streamed || inspectable && terminated),frames,bytes:total,duration_ms:Math.max(0,log.clock()-started),detail});finish();};
92
+ const stream=new ReadableStream({async pull(sink){try{const value=await reader.read();if(value.done){await done(true);reader.releaseLock();sink.close();return;}frames++;total+=value.value.length;if(remaining!=null)remaining=remaining>=value.value.length?remaining-value.value.length:null;if(inspectable){tail=Buffer.concat([tail,value.value]);terminated ||= /message_stop|\[DONE\]|response\.completed|finishReason/.test(tail.toString('utf8'));tail=tail.subarray(Math.max(0,tail.length-32));}if(!opaque && phase)await log.record(id,phase,{body:bodyValue(value.value)});if(errorCapture){const held=chunks.reduce((sum,chunk)=>sum+chunk.length,0),take=Math.min(value.value.length,Math.max(0,Math.min(1024*1024,log.errorMax)-held));if(take)chunks.push(Buffer.from(value.value.subarray(0,take)));truncated ||= take<value.value.length;}sink.enqueue(value.value);}catch(error){await done(false,String(error.message ?? error));sink.error(error);}},async cancel(reason){await done(false,String(reason ?? 'response body cancelled'));await reader.cancel(reason);reader.releaseLock();}});
93
+ return new Response(stream,{status:response.status,headers:response.headers});
94
+ }
95
+ fetch(fetch) {return async(url,options)=>{const id=context.getStore(),opaque=this.active.get(id)?.opaque;if(id){this.select(this.active.get(id)?.account);await this.record(id,'upstream_request',opaque?{method:options?.method ?? 'GET'}:{method:options?.method ?? 'GET',uri:String(url),headers:Object.fromEntries(new Headers(options?.headers)),body:typeof options?.body==='string'?bodyValue(Buffer.from(options.body)):'[OMITTED: opaque upstream body]'},{opaque});}
96
+ let response;try{response=await fetch(url,options);}catch(error){if(id)await this.record(id,'upstream_error',opaque?{}:{error:String(error.message ?? error)},{opaque});throw error;}if(id)await this.record(id,'upstream_response',{status:response.status,...(opaque?{}:{headers:Object.fromEntries(response.headers)})},{opaque});return this.wrapResponse(response,{id:id ?? randomUUID(),phase:id?'upstream_response_body':undefined,opaque,errorCapture:!opaque && response.status>=400});};}
97
+ }
98
+ function nonnegative(value,fallback){const n=Number(value);return value!=null && Number.isSafeInteger(n) && n>=0?n:fallback;}
99
+ function positive(value,fallback){return nonnegative(value,fallback) || fallback;}