@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,392 @@
1
+ import { ProtocolError } from './protocols.mjs';
2
+ import { responseOwner } from './responses.mjs';
3
+ import { matchHTTPRoute } from './http-route-contract.mjs';
4
+ import {createHash} from 'node:crypto';
5
+ import {isGeolocationHeader,sharesGeolocation,sanitizeGeolocation,geolocationInferencePath} from './geolocation.mjs';
6
+ import {UsageTracker} from './usage.mjs';
7
+ import { responseContract, validateResponseCreate, responseReferences, responseNotFound, responseReferenceMissing, responseReferenceConflict, responseAffinityStorageError } from './response-contracts.mjs';
8
+ import { conversationContract, conversationNotFound, conversationUnsupported, conversationMethodNotAllowed, conversationAffinityError, conversationUpstreamError, conversationIds, validConversationId } from './response-contracts.mjs';
9
+ import { captureSseId, captureJsonId, captureLocationId, resourceCaptureError } from './response-contracts.mjs';
10
+
11
+ const transport = new Set(['authorization','x-api-key','x-goog-api-key','anthropic-auth-token','proxy-authorization','proxy-authenticate','host','connection','proxy-connection','keep-alive','transfer-encoding','upgrade','te','trailer','content-length','accept-encoding','cookie','chatgpt-account-id','sec-websocket-key','sec-websocket-version','sec-websocket-extensions','sec-websocket-accept']);
12
+ const ingress = new Set(['forwarded','x-original-forwarded-for','x-real-ip','x-client-ip','x-cluster-client-ip','cf-connecting-ip','cf-connecting-ipv6','cf-pseudo-ipv4','true-client-ip','fastly-client-ip','fly-client-ip','x-envoy-external-address','x-azure-clientip','x-appengine-user-ip','cloudfront-viewer-address']);
13
+ const responseCredentials = new Set(['authorization','x-api-key','x-goog-api-key','anthropic-auth-token','set-cookie','cookie','chatgpt-account-id']);
14
+ const connectionNames = headers => new Set((headers.get('connection') ?? '').split(',').map(v => v.trim().toLowerCase()));
15
+ export function isIngressNetworkHeader(name) {
16
+ const lower=name.toLowerCase();
17
+ return ingress.has(lower) || lower.startsWith('x-forwarded-');
18
+ }
19
+ export function nativeRequestHeaders(incoming, candidate) {
20
+ const headers = new Headers(), nominated = connectionNames(incoming), share = sharesGeolocation(incoming);
21
+ for (const [name,value] of incoming) if (!transport.has(name) && !isIngressNetworkHeader(name) && !nominated.has(name) && !name.startsWith('x-router-') && !name.startsWith('x-link-assistant-') && (share || !isGeolocationHeader(name))) headers.append(name,value);
22
+ const credential = candidate.apiKey ?? candidate.api_key;
23
+ if (credential) headers.set('authorization', `Bearer ${credential}`);
24
+ for (const [name,value] of Object.entries(candidate.oauth_headers ?? {})) if (typeof value === 'string' && ['chatgpt-account-id','originator','anthropic-beta','anthropic-version'].includes(name.toLowerCase())) headers.set(name,value);
25
+ return headers;
26
+ }
27
+ export function nativeResponseHeaders(incoming) {
28
+ const headers = new Headers(), nominated = connectionNames(incoming);
29
+ const hop = new Set(['connection','proxy-connection','keep-alive','transfer-encoding','upgrade','te','trailer','content-length']);
30
+ for (const [name,value] of incoming) if (!hop.has(name) && !responseCredentials.has(name) && !nominated.has(name) && !name.startsWith('x-router-') && !name.startsWith('x-link-assistant-') && !/^x-codex-(?:plan-type|active-limit|credits-balance)/.test(name)) headers.append(name,value);
31
+ return headers;
32
+ }
33
+ export async function boundedBytes(request, limit) {
34
+ if (!request.body) return new Uint8Array();
35
+ const reader = request.body.getReader(), parts = []; let length = 0;
36
+ try {
37
+ for (;;) { const {done,value} = await reader.read(); if (done) break; length += value.byteLength; if (length > limit) { await reader.cancel(); throw new ProtocolError('Request body exceeds limit',413); } parts.push(value); }
38
+ } finally { reader.releaseLock(); }
39
+ return Buffer.concat(parts,length);
40
+ }
41
+ const captureFailure = (status,message) => Object.assign(new ProtocolError(message,status),{resourceCapture:true});
42
+ async function recordCapturedResource(affinities,namespace,owner,id,selected,model) {
43
+ try {
44
+ if (!validConversationId(id)) throw new Error('invalid response id');
45
+ await affinities.set(namespace,owner,id,{destination:selected,model});
46
+ } catch (error) { throw captureFailure(503,`could not persist resource ownership: ${error.message ?? String(error)}`); }
47
+ }
48
+ async function captureNativeStream(upstream,{namespace,owner,selected,affinities,model,cleanup,controller,limit=1024*1024}) {
49
+ if (!upstream.body) {cleanup();throw captureFailure(502,'stored stream ended before exposing a resource id');}
50
+ const reader=upstream.body.getReader(),chunks=[];let framed=Buffer.alloc(0),bytes=0,id;
51
+ try {
52
+ while(!id) {
53
+ const {done,value}=await reader.read();if(done)throw captureFailure(502,'stored stream ended before exposing a resource id');
54
+ chunks.push(value);bytes+=value.byteLength;framed=Buffer.concat([framed,value]);
55
+ for (;;) {
56
+ const crlf=framed.indexOf('\r\n\r\n'),lf=framed.indexOf('\n\n');
57
+ const end=crlf>=0 && (lf<0 || crlf<=lf) ? crlf : lf;
58
+ if (end<0) break;
59
+ const separator=end===crlf ? 4 : 2;
60
+ const block=framed.subarray(0,end).toString('utf8');framed=framed.subarray(end+separator);
61
+ id=captureSseId(block);if(id)break;
62
+ }
63
+ // Original ordering: search every complete block in the current chunk
64
+ // before checking the still-unidentified prefix's accumulated size.
65
+ if(!id && bytes>limit)throw captureFailure(502,'stored stream did not expose a bounded resource id');
66
+ }
67
+ await recordCapturedResource(affinities,namespace,owner,id,selected,model);
68
+ }catch(error){controller.abort(error);cleanup();await reader.cancel().catch(()=>{});reader.releaseLock();throw error.resourceCapture ? error : captureFailure(502,`upstream stream failed: ${error.message ?? String(error)}`);}
69
+ const prefix=Buffer.concat(chunks,bytes);chunks.length=0;framed=Buffer.alloc(0);
70
+ let initial=true;
71
+ return new ReadableStream({async pull(c){try{if(initial){initial=false;c.enqueue(prefix);return;}const {done,value}=await reader.read();if(done){cleanup();reader.releaseLock();c.close();}else c.enqueue(value);}catch(error){cleanup();reader.releaseLock();c.error(error);}},async cancel(reason){controller.abort(reason);cleanup();try{await reader.cancel(reason);}finally{reader.releaseLock();}}});
72
+ }
73
+ export function nativeURL(base, service, pathname, search = '') {
74
+ let url; try { url = new URL(base); } catch { throw new ProtocolError('Native provider base URL is invalid',503); }
75
+ if (!['http:','https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) throw new ProtocolError('Native provider base URL is invalid',503);
76
+ const prefix = service === 'codex-backend' ? '/api/services/codex/backend-api' : `/api/services/${service}`;
77
+ let tail = pathname.startsWith(prefix) ? pathname.slice(prefix.length) : pathname;
78
+ let root = url.pathname.replace(/\/$/,'');
79
+ if (service === 'codex-backend') root = root.replace(/\/codex$/,'');
80
+ else if (root.endsWith('/v1') && tail.startsWith('/v1/')) tail = tail.slice(3);
81
+ if (service === 'codex' && pathname === '/api/services/codex/v1/live') { tail = '/v1/realtime/calls'; search += `${search ? '&' : '?'}intent=quicksilver&architecture=avas`; }
82
+ url.pathname = root + tail; url.search = search; return url;
83
+ }
84
+ const destination = c => ({provider:c.destination_kind === 'subscription' ? c.provider_kind : typeof c.provider === 'string' ? c.provider : c.provider?.name,account:c.destination_kind === 'stored_provider' ? typeof c.provider === 'string' ? c.provider:c.provider?.name : c.native_account ?? (typeof c.account === 'string' ? c.account : c.account?.name),protocol:c.protocol === 'chat' ? 'openai' : c.protocol,base_url:c.baseUrl ?? c.base_url ?? c.provider?.base_url,account_id:c.destination_kind === 'stored_provider' ? undefined:c.account_id ?? undefined,provider_kind:c.provider_kind ?? c.kind,destination_kind:c.destination_kind});
85
+ const sameDestination = (a,b) => ['provider','account','protocol','base_url','account_id','provider_kind','destination_kind'].every(key => a[key] === b[key]);
86
+ export class NativeAffinityStore {
87
+ constructor({maxRecords=10000} = {}) { this.records = new Map(); this.maxRecords = maxRecords; }
88
+ key(namespace,owner,id,parent_id) { return JSON.stringify([namespace,typeof owner === 'object' ? [owner.client_kind,owner.principal_id] : owner,id,parent_id ?? null]); }
89
+ get(namespace,owner,id,parent_id) {
90
+ if (parent_id !== undefined) return structuredClone(this.records.get(this.key(namespace,owner,id,parent_id)) ?? null);
91
+ const matching = this.list(namespace,owner).filter(record => record.id === id);
92
+ return matching.length === 1 ? matching[0] : null;
93
+ }
94
+ set(namespace,owner,id,record) {
95
+ const key = this.key(namespace,owner,id,record.parent_id), previous = this.records.get(key);
96
+ if (previous && !sameDestination(previous.destination,record.destination)) throw new ProtocolError('Resource id belongs to another exact account',409);
97
+ if (!previous && this.records.size >= this.maxRecords) throw new ProtocolError('Resource affinity storage is full',507);
98
+ this.records.set(key,{...structuredClone(record),namespace,owner,id});
99
+ }
100
+ delete(namespace,owner,id,parent_id,expected) {
101
+ const key = this.key(namespace,owner,id,parent_id), record = this.records.get(key);
102
+ if (!record || expected && !sameDestination(record.destination,expected.destination ?? expected)) return false;
103
+ return this.records.delete(key);
104
+ }
105
+ list(namespace,owner,parent_id) { return [...this.records.values()].filter(r => r.namespace === namespace && this.key(namespace,r.owner,'') === this.key(namespace,owner,'') && (parent_id === undefined || r.parent_id === parent_id)).map(r => structuredClone(r)); }
106
+ deleteChildren(namespace,owner,parent_id,selected) {
107
+ let count = 0;
108
+ for (const record of this.list(namespace,owner,parent_id)) if (sameDestination(record.destination,selected)) { this.records.delete(this.key(namespace,owner,record.id,parent_id)); count++; }
109
+ return count;
110
+ }
111
+ }
112
+ function resourceFor(path, method, headers) {
113
+ const backend='/api/services/codex/backend-api';
114
+ if(path === backend+'/public/plugins/workspace/upload-url' && method === 'POST')return {namespace:backend+'/plugin-uploads',create:true,idFields:['file_id']};
115
+ if(path === backend+'/public/plugins/workspace')return {namespace:backend+'/public/plugins/workspace',create:method === 'POST',list:method === 'GET',itemsField:'plugins',idFields:['plugin_id','id']};
116
+ const plugin=/^\/api\/services\/codex\/backend-api\/(?:plugins|ps\/plugins)\/([^/]+)\/(enable|install|uninstall)$/.exec(path);
117
+ if(plugin && method === 'POST')return {namespace:backend+'/plugin-installs',...(plugin[2] === 'uninstall' ? {id:decodeURIComponent(plugin[1]),remove:true}:{declaredId:decodeURIComponent(plugin[1]),create:true})};
118
+ const workspace=/^\/api\/services\/codex\/backend-api\/(?:public\/plugins\/workspace\/([^/]+)|ps\/plugins\/([^/]+)\/shares)$/.exec(path);
119
+ if(workspace)return {namespace:backend+'/public/plugins/workspace',id:decodeURIComponent(workspace[1] ?? workspace[2]),remove:method === 'DELETE'};
120
+ const roots = [
121
+ ['/api/services/anthropic/v1/files',true], ['/api/services/anthropic/v1/messages/batches',false],
122
+ ['/api/services/anthropic/v1/skills',false], ['/api/services/codex/backend-api/files',false],
123
+ ['/api/services/openai/v1/realtime/calls',false], ['/api/services/codex/v1/realtime/calls',false],
124
+ ['/api/services/codex/v1/live',false],
125
+ ];
126
+ const lifecycle = /^(\/api\/services\/(?:openai|codex|qwen)\/v1|\/v1)\/(conversations|chat\/completions|responses)(.*)$/.exec(path);
127
+ if (lifecycle) roots.push([`${lifecycle[1]}/${lifecycle[2]}`,false]);
128
+ for (const [root,listable] of roots) {
129
+ if (path !== root && !path.startsWith(root+'/')) continue;
130
+ const segments = path.slice(root.length).split('/').filter(Boolean).map(decodeURIComponent);
131
+ const namespace = root === '/api/services/codex/v1/live' ? '/api/services/codex/v1/realtime/calls' : root;
132
+ if(root.endsWith('/responses') && segments[0] === 'compact' && method === 'POST')return {namespace:root,create:true};
133
+ if(root.endsWith('/responses') && segments[0] === 'input_tokens')return null;
134
+ if (!segments.length) return {namespace,create:method === 'POST',list:method === 'GET' && (listable || root.endsWith('batches') || root.endsWith('skills') || root.endsWith('chat/completions'))};
135
+ if (root.endsWith('skills') && segments[1] === 'versions') return {namespace:root+'/versions',parent:segments[0],id:segments[2],create:method === 'POST' && segments.length === 2,list:method === 'GET' && segments.length === 2,remove:method === 'DELETE',idFields:['version','id']};
136
+ if (root.endsWith('conversations') && segments[1] === 'items') return {namespace:root+'/items',parent:segments[0],id:segments[2],create:method === 'POST' && segments.length === 2,list:method === 'GET' && segments.length === 2,remove:method === 'DELETE',captureList:true};
137
+ return {namespace,id:segments[0],remove:method === 'DELETE'};
138
+ }
139
+ if (path === '/api/services/codex/backend-api/ps/mcp') {
140
+ const id = headers.get('mcp-session-id'); if (id && (id.length > 256 || id.includes(','))) throw new ProtocolError('Mcp-Session-Id is invalid');
141
+ return id ? {namespace:path,id,remove:method === 'DELETE'} : method === 'POST' ? {namespace:path,create:true,mcp:true} : null;
142
+ }
143
+ return null;
144
+ }
145
+
146
+ /** Opaque vendor operations: preserve bytes and bind owner resources to an exact account. */
147
+ export function createNativeService({core,authorize,routingContext,fetch:upstreamFetch=globalThis.fetch,maxBodyBytes=4*1024*1024,maxResponseBytes=32*1024*1024,timeoutMs=120000,affinities=core.affinities ?? new NativeAffinityStore(),identityResponse=false}) {
148
+ async function select(request, claims, service, document, exact) {
149
+ const pathModel = /\/publishers\/anthropic\/models\/([^/:]+)(?:\/count-tokens)?:(?:rawPredict|streamRawPredict)$/.exec(new URL(request.url).pathname)?.[1];
150
+ const context = {...routingContext(request,claims),service,model:document?.model ?? (pathModel ? decodeURIComponent(pathModel) : undefined),protocol:['anthropic','bedrock','vertex'].includes(service) ? 'anthropic' : 'chat'};
151
+ if (exact && (responseContract(request.method,new URL(request.url).pathname) || conversationContract(request.method,new URL(request.url).pathname))) {
152
+ context.provider = exact.provider;
153
+ context.resourceDestination = exact;
154
+ // Recorded subscription bindings use logical names (implicit providers
155
+ // expose "primary"). Core maps those through principalAccountScope;
156
+ // pinnedAccount instead means a physical account record key.
157
+ if (exact.destination_kind === 'subscription') context.principalAccount = exact.account;
158
+ }
159
+ const candidates = core.nativeCandidates ? await core.nativeCandidates(context) : context.model ? await core.candidates(context) : [];
160
+ const raw = candidates.find(c => !exact || ['provider','account','base_url'].every(key => exact[key] === destination(c)[key]));
161
+ if (!raw) throw new ProtocolError(exact ? 'The native resource exact account is unavailable' : 'Native service provider is unavailable',503);
162
+ const candidate = core.prepareCandidate ? await core.prepareCandidate(raw) : raw;
163
+ core.requestLog?.select(candidate.account);
164
+ if (exact && !sameDestination(exact,destination(candidate))) throw new ProtocolError('Native resource account changed',503);
165
+ return candidate;
166
+ }
167
+ return {
168
+ affinities,
169
+ async websocketTarget(request) {
170
+ const url=new URL(request.url),path=url.pathname,service=/^\/api\/services\/(openai|codex|qwen)\//.exec(path)?.[1];
171
+ if(!service || !matchHTTPRoute('GET',path) || !/\/(?:responses|realtime|live)(?:\/[^/]+)?$/.test(path))throw new ProtocolError('Route not found',404);
172
+ const claims=await authorize(request,false),client=claims.client_kind ?? claims.client;
173
+ if(!client || !claims.principal_id)throw new ProtocolError('Native services require a client and principal bound Router token',403);
174
+ if(service === 'qwen')throw new ProtocolError('Qwen does not support Responses WebSocket transport',501);
175
+ if(service === 'codex' && client !== 'codex')throw new ProtocolError('Codex service requires a Codex-bound Router token',403);
176
+ const owner={client_kind:claims.client_kind,principal_id:claims.principal_id};
177
+ let exact;
178
+ const calls=url.searchParams.getAll('call_id');if(calls.length > 1 || calls.length === 1 && !calls[0])throw new ProtocolError('Exactly one nonempty Realtime call_id is allowed');
179
+ const liveId=/\/live\/([^/]+)$/.exec(path)?.[1],id=liveId ? decodeURIComponent(liveId):calls[0];
180
+ if(id){const namespace=`/api/services/${service}/v1/realtime/calls`,record=await affinities.get(namespace,owner,id);if(!record)throw new ProtocolError('Realtime call not found',404);exact=record.destination;}
181
+ const candidate=await select(request,claims,service,{model:url.searchParams.get('model') ?? undefined},exact),selected=destination(candidate);
182
+ if(service === 'openai' && selected.provider_kind !== 'openai-compatible')throw new ProtocolError('Selected provider does not implement native OpenAI resource APIs',503);
183
+ return {url:nativeURL(selected.base_url,service,path,url.search),headers:nativeRequestHeaders(request.headers,candidate),claims};
184
+ },
185
+ async fetch(request) {
186
+ const url = new URL(request.url), path = url.pathname;
187
+ if (!matchHTTPRoute(request.method,path)) throw new ProtocolError('Route not found',404);
188
+ const serviceMatch = /^\/api\/services\/(openai|anthropic|codex|qwen|bedrock|vertex)(?:\/|$)/.exec(path);
189
+ const service = path.startsWith('/api/services/codex/backend-api/') ? 'codex-backend' : serviceMatch?.[1] ?? 'openai';
190
+ const claims = await authorize(request,false);
191
+ const client = claims.client_kind ?? claims.client;
192
+ if (!client || !claims.principal_id) throw new ProtocolError('Native services require a client and principal bound Router token',403);
193
+ if (service === 'anthropic' && client !== 'claude' || service.startsWith('codex') && client !== 'codex') throw new ProtocolError('Native service requires a credential bound to its official client',403);
194
+ if (service === 'codex-backend' && !request.headers.get('authorization')?.startsWith('Bearer at-')) throw new ProtocolError('Codex backend requires the paired Router-issued at- token',401);
195
+ if (path === '/api/services/openai/v1/realtime/client_secrets') throw new ProtocolError('Router does not expose upstream Realtime client secrets',501);
196
+ const conversation = conversationContract(request.method,path);
197
+ if (conversation?.service === 'qwen') return conversationUnsupported();
198
+ const owner = claims.client_kind && claims.principal_id ? {client_kind:claims.client_kind,principal_id:claims.principal_id} : responseOwner(claims,request.headers.get('authorization') ?? request.headers.get('x-api-key'));
199
+ let conversationRecord, conversationItem;
200
+ if (conversation && conversation.target !== 'create') {
201
+ try {
202
+ conversationRecord = await affinities.get(conversation.namespace,owner,conversation.id);
203
+ if (!conversationRecord) return conversationNotFound();
204
+ if (conversation.target === 'item') {
205
+ conversationItem = await affinities.get(conversation.itemNamespace,owner,conversation.item);
206
+ if (!conversationItem || conversationItem.parent_id !== conversation.id || !sameDestination(conversationItem.destination,conversationRecord.destination)) return conversationNotFound(true);
207
+ }
208
+ } catch (error) { return conversationAffinityError(error); }
209
+ }
210
+ if (conversation && !conversation.allowed) return conversationMethodNotAllowed();
211
+ const conversationDestination = conversationItem?.destination ?? conversationRecord?.destination;
212
+ if (conversationDestination?.destination_kind === 'subscription' && (claims.account ?? 'primary') !== conversationDestination.account) return responseNotFound();
213
+ const identityRoute=path === '/api/services/codex/v1/user-auth-credential/whoami' || path === '/api/services/codex/backend-api/wham/accounts/check';
214
+ const tokenId=claims.sub ?? claims.id;
215
+ if(!identityRoute && tokenId && core.tokens?.admit){const admitted=await core.tokens.admit(tokenId,0);if(admitted === false || typeof admitted === 'string' && admitted !== 'admitted')throw new ProtocolError(typeof admitted === 'string'?admitted:'Token budget exceeded',429);}
216
+ let bytes = await boundedBytes(request,maxBodyBytes);
217
+ const privateInference = geolocationInferencePath(path) && !sharesGeolocation(request.headers);
218
+ if (privateInference && !['','identity'].includes(request.headers.get('content-encoding') ?? '')) throw new ProtocolError('Encoded inference requires a supported decoder before location metadata can be protected',415);
219
+ let document; try { document = bytes.length ? JSON.parse(Buffer.from(bytes).toString('utf8')) : undefined; } catch { /* opaque multipart/binary bodies are forwarded */ }
220
+ if (privateInference && sanitizeGeolocation(document)) bytes = Buffer.from(JSON.stringify(document));
221
+ const responses = responseContract(request.method,path);
222
+ try { validateResponseCreate(responses,document); }
223
+ catch (error) {
224
+ if (!(error instanceof ProtocolError)) throw error;
225
+ return Response.json({error:{type:error.code === 'model_required' ? 'model_required' : 'invalid_request_error',message:error.message}},{status:error.status ?? 400});
226
+ }
227
+ if (request.method === 'POST' && /\/(?:responses\/(?:compact|input_tokens)|images\/generations|audio\/speech|alpha\/search)$/.test(path) && (!document || typeof document !== 'object' || Array.isArray(document))) throw new ProtocolError('The native service request body must be a JSON object');
228
+ if (!conversation && document?.model) await authorize(request,false,document.model);
229
+ if (['bedrock','vertex'].includes(service) && (!document || !Array.isArray(document.messages))) throw new ProtocolError('messages must be an array');
230
+ if (!conversation) for (const batch of document?.requests ?? []) if (batch.params?.model) await authorize(request,false,batch.params.model);
231
+ const resource = conversation ? null : resourceFor(path,request.method,request.headers);
232
+ if(document?.store === false && resource?.namespace.endsWith('/responses'))resource.create=false;
233
+ let exact = conversationDestination, resourceRecord;
234
+ const bind = record => { if (!record) throw new ProtocolError('Native resource not found',404); if (exact && !sameDestination(exact,record.destination)) throw new ProtocolError('Resources do not share one provider account',409); exact = record.destination; };
235
+ if (resource?.id) {
236
+ try { resourceRecord = await affinities.get(resource.namespace,owner,resource.id,resource.parent); }
237
+ catch(error) { if(responses?.lifecycle)return responseAffinityStorageError(error);throw error; }
238
+ if (!resourceRecord && responses?.lifecycle) return responseNotFound();
239
+ bind(resourceRecord);
240
+ if (responses?.lifecycle && resourceRecord.destination.destination_kind === 'subscription' && (claims.account ?? 'primary') !== resourceRecord.destination.account) return responseNotFound();
241
+ }
242
+ if (resource?.parent) bind(await affinities.get(resource.namespace.replace(/\/(?:items|versions)$/,''),owner,resource.parent));
243
+ for (const reference of responseReferences(responses,document)) {
244
+ let record;
245
+ try { record = await affinities.get(reference.namespace,owner,reference.id); }
246
+ catch(error) {
247
+ if(responses?.create)return responseAffinityStorageError(error);
248
+ return Response.json({error:{type:'api_error',message:'resource affinity is unavailable'}},{status:503});
249
+ }
250
+ if (!record && reference.allowMissing) continue;
251
+ if (!record) return responseReferenceMissing();
252
+ if (responses?.create && record.destination.destination_kind === 'subscription' && (claims.account ?? 'primary') !== record.destination.account) return responseNotFound();
253
+ if (exact && !sameDestination(exact,record.destination)) return responseReferenceConflict();
254
+ bind(record);
255
+ }
256
+ const listed = resource?.list ? await affinities.list(resource.namespace,owner,resource.parent) : [];
257
+ if(!resource?.captureList)for (const record of listed) bind(record);
258
+ if(service === 'codex-backend' && document?.file_id && path.startsWith('/api/services/codex/backend-api/public/plugins/workspace'))bind(await affinities.get('/api/services/codex/backend-api/plugin-uploads',owner,document.file_id));
259
+ const candidate = await select(request,claims,service,conversation ? undefined : document,exact), selected = destination(candidate);
260
+ if (conversation && !(conversation.service === 'openai' && selected.provider_kind === 'openai-compatible' && selected.destination_kind !== 'subscription' || conversation.service === 'codex' && selected.provider_kind === 'codex' && selected.destination_kind === 'subscription')) return conversationUnsupported();
261
+ if (service === 'openai' && selected.provider_kind !== 'openai-compatible') throw new ProtocolError('Selected provider does not implement native OpenAI resource APIs',503);
262
+ if(path === '/api/services/codex/v1/user-auth-credential/whoami' || path === '/api/services/codex/backend-api/wham/accounts/check') {
263
+ if(!request.headers.get('authorization')?.startsWith('Bearer at-'))throw new ProtocolError('Codex identity requires the paired Router-issued at- token',401);
264
+ const handle=(prefix,value)=>`${prefix}_${createHash('sha256').update(value).digest('hex').slice(0,24)}`;
265
+ const account=handle('acct',`${claims.principal_id}:${selected.account}:${candidate.account_id ?? ''}`),user=handle('usr',claims.principal_id);
266
+ let metadata;try{const key=candidate.apiKey ?? candidate.api_key;metadata=JSON.parse(Buffer.from(key.split('.')[1],'base64url').toString('utf8'))['https://api.openai.com/auth'];}catch{/* Credential metadata may be absent; never expose the raw token. */}
267
+ const plan=typeof metadata?.chatgpt_plan_type === 'string' && metadata.chatgpt_plan_type.trim().length <= 128 ? metadata.chatgpt_plan_type.trim() || 'unknown':'unknown';
268
+ const body=path.endsWith('/whoami') ? {email:null,chatgpt_user_id:user,chatgpt_account_id:account,chatgpt_plan_type:plan,chatgpt_account_is_fedramp:metadata?.chatgpt_account_is_fedramp === true}:{accounts:[{id:account,plan_type:plan,workspace_backend_origin:new URL(selected.base_url).protocol === 'https:' ? new URL(selected.base_url).origin:'https://chatgpt.com',account_routing_override:'NO_CONSTRAINT'}],account_ordering:[account],default_account_id:account};
269
+ return Response.json(body);
270
+ }
271
+ const controller = new AbortController(), abort = () => controller.abort(request.signal.reason);
272
+ request.signal.addEventListener('abort',abort,{once:true});
273
+ const timer = setTimeout(() => controller.abort(new Error('Native upstream timeout')),timeoutMs); timer.unref?.();
274
+ const cleanup = () => {clearTimeout(timer);request.signal.removeEventListener('abort',abort);};
275
+ let upstream;
276
+ const upstreamHeaders = nativeRequestHeaders(request.headers,candidate);
277
+ if (identityResponse) upstreamHeaders.set('accept-encoding','identity');
278
+ try { upstream = await upstreamFetch(nativeURL(selected.base_url,service,conversation?.forwardPath ?? path,url.search),{method:request.method,headers:upstreamHeaders,...(['GET','HEAD'].includes(request.method) ? {} : {body:bytes}),signal:controller.signal,redirect:'manual'}); }
279
+ catch { cleanup(); throw new ProtocolError('Native upstream request failed',502); }
280
+ const headers = nativeResponseHeaders(upstream.headers);
281
+ if (conversation) {
282
+ let raw;
283
+ try { raw = await boundedBytes(upstream,maxBodyBytes); }
284
+ catch (error) { return conversationUpstreamError(error.status === 413 ? 'upstream response exceeds the proxy limit' : `upstream body read failed: ${error.message ?? String(error)}`); }
285
+ finally { cleanup(); }
286
+ const remove = async () => {
287
+ if (conversation.target === 'item') return affinities.delete(conversation.itemNamespace,owner,conversation.item,conversation.id,conversationItem);
288
+ await affinities.deleteChildren(conversation.itemNamespace,owner,conversation.id,conversationRecord.destination);
289
+ return affinities.delete(conversation.namespace,owner,conversation.id,undefined,conversationRecord);
290
+ };
291
+ if (conversation.target !== 'create' && [404,410].includes(upstream.status)) {
292
+ try { await remove(); } catch {}
293
+ return conversationNotFound(conversation.target === 'item');
294
+ }
295
+ if (upstream.ok) {
296
+ try {
297
+ if (conversation.target === 'create') {
298
+ const id = conversationIds(raw)[0];
299
+ if (!id) return conversationUpstreamError('conversation create response did not contain an id');
300
+ if (!validConversationId(id)) throw new Error('invalid response id');
301
+ await affinities.set(conversation.namespace,owner,id,{destination:selected});
302
+ } else if (conversation.target === 'items') {
303
+ for (const id of conversationIds(raw,true)) {
304
+ if (!validConversationId(id)) throw new Error('invalid response id');
305
+ await affinities.set(conversation.itemNamespace,owner,id,{destination:conversationRecord.destination,parent_id:conversation.id});
306
+ }
307
+ } else if (request.method === 'DELETE') await remove();
308
+ } catch (error) { return conversationAffinityError(error); }
309
+ }
310
+ return new Response([204,205,304].includes(upstream.status) ? null : raw,{status:upstream.status,headers});
311
+ }
312
+ if (responses?.lifecycle && resourceRecord) {
313
+ // Rust's lifecycle relay reads the body before any retirement. This
314
+ // also keeps a failed successful-DELETE body read from losing affinity.
315
+ let raw;
316
+ try { raw = await boundedBytes(upstream,maxResponseBytes); }
317
+ catch { throw new ProtocolError('Upstream lifecycle body could not be read within the response limit',502); }
318
+ finally { cleanup(); }
319
+ if ([404,410].includes(upstream.status)) {
320
+ // Rust treats this cleanup as best-effort: a store error cannot turn
321
+ // an upstream missing response into an availability error.
322
+ try { await affinities.delete(resource.namespace,owner,resource.id,resource.parent,resourceRecord); } catch {}
323
+ return responseNotFound();
324
+ }
325
+ if (resource.remove && upstream.ok) {
326
+ try { await affinities.delete(resource.namespace,owner,resource.id,resource.parent,resourceRecord); }
327
+ catch (error) { return responseAffinityStorageError(error); }
328
+ }
329
+ return new Response([204,205,304].includes(upstream.status) ? null : raw,{status:upstream.status,headers});
330
+ }
331
+ const tracksUsage=/\/(?:responses(?:\/compact)?|images\/(?:generations|edits|variations)|audio\/(?:speech|transcriptions|translations)|alpha\/search)$/.test(path);
332
+ if(tracksUsage && tokenId && core.tokens?.settle && upstream.body) {
333
+ const usage=new UsageTracker({maxBytes:maxResponseBytes}),reader=upstream.body.getReader();let settled=false;
334
+ const settle=async()=>{if(settled)return;settled=true;await core.tokens.settle(tokenId,0,usage.finish().tokens);};
335
+ const measured=new ReadableStream({async pull(c){try{const {done,value}=await reader.read();if(done){await settle();reader.releaseLock();c.close();}else{usage.feed(value);c.enqueue(value);}}catch(error){await settle();c.error(error);}},async cancel(reason){await settle();await reader.cancel(reason);reader.releaseLock();}});
336
+ upstream=new Response(measured,{status:upstream.status,headers:upstream.headers});
337
+ }
338
+ if(resource?.create && resource.namespace.endsWith('/responses') && upstream.ok) {
339
+ try {
340
+ if(upstream.headers.get('content-type')?.toLowerCase().includes('text/event-stream')) {
341
+ const stream=await captureNativeStream(upstream,{namespace:resource.namespace,owner,selected,affinities,model:document?.model,cleanup,controller});
342
+ return new Response(stream,{status:upstream.status,headers});
343
+ }
344
+ let raw;
345
+ try { raw=await boundedBytes(upstream,Math.min(maxResponseBytes,32*1024*1024)); }
346
+ catch (error) { throw captureFailure(502,`stored response is too large: ${error.message ?? String(error)}`); }
347
+ finally { cleanup(); }
348
+ const id=captureJsonId(raw) ?? captureLocationId(headers);
349
+ if(!id)throw captureFailure(502,'stored response did not include a resource id');
350
+ await recordCapturedResource(affinities,resource.namespace,owner,id,selected,document?.model);
351
+ return new Response([204,205,304].includes(upstream.status) ? null : raw,{status:upstream.status,headers});
352
+ } catch (error) {
353
+ if(!error.resourceCapture)throw error;
354
+ return resourceCaptureError(error.status,error.message);
355
+ }
356
+ }
357
+ if (resource && (resource.create || resource.list) && upstream.ok) {
358
+ let raw; try { raw = await boundedBytes(upstream,maxResponseBytes); } finally { cleanup(); }
359
+ let value; try { value = JSON.parse(Buffer.from(raw).toString('utf8')); } catch { if (!resource.mcp && !path.includes('/realtime/') && !path.endsWith('/live')) throw new ProtocolError('Native upstream resource response is malformed',502); }
360
+ if(resource.captureList) {
361
+ if(!Array.isArray(value?.data))throw new ProtocolError('Conversation items response is malformed',502);
362
+ for(const item of value.data)if(typeof item.id === 'string' && item.id)await affinities.set(resource.namespace,owner,item.id,{destination:selected,parent_id:resource.parent});
363
+ }
364
+ else if (resource.create) {
365
+ const fields=resource.idFields ?? (path.endsWith('/realtime/calls') || path.endsWith('/live') ? ['call_id','id'] : path === '/api/services/codex/backend-api/files' ? ['file_id','id'] : ['id']);
366
+ const id = resource.declaredId ?? (resource.mcp ? headers.get('mcp-session-id') : fields.map(field=>value?.[field]).find(value=>typeof value === 'string' && value) ?? headers.get('location')?.split('/').at(-1));
367
+ if(resource.mcp && !id)return new Response(raw,{status:upstream.status,headers});
368
+ if (!id || typeof id !== 'string' || id.length > 512) throw new ProtocolError('Native resource response did not contain a valid id',502);
369
+ await affinities.set(resource.namespace,owner,id,{destination:selected,parent_id:resource.parent,model:document?.model});
370
+ if (path.includes('/realtime/calls') || path.endsWith('/live')) headers.set('location',`${path.replace(/\/$/,'')}/${encodeURIComponent(id)}`);
371
+ }
372
+ if (resource.list && !resource.captureList) {
373
+ const field=resource.itemsField ?? 'data',ids=resource.idFields ?? ['id'];
374
+ if (!Array.isArray(value?.[field])) throw new ProtocolError('Native resource list response is malformed',502);
375
+ const allowed = new Set(listed.map(r => r.id)); value[field] = value[field].filter(item => allowed.has(ids.map(key=>item[key]).find(value=>typeof value === 'string' && value)));
376
+ if(Object.hasOwn(value,'first_id'))value.first_id = ids.map(key=>value[field][0]?.[key]).find(Boolean) ?? null;
377
+ if(Object.hasOwn(value,'last_id'))value.last_id = ids.map(key=>value[field].at(-1)?.[key]).find(Boolean) ?? null;
378
+ raw = Buffer.from(JSON.stringify(value));
379
+ }
380
+ return new Response(raw,{status:upstream.status,headers});
381
+ }
382
+ if (resource?.remove && (upstream.ok || [404,410].includes(upstream.status))) {
383
+ if(resource.namespace.endsWith('/skills') || resource.namespace.endsWith('/conversations'))for(const child of await affinities.list(resource.namespace+(resource.namespace.endsWith('/skills')?'/versions':'/items'),owner,resource.id))await affinities.delete(child.namespace,owner,child.id,child.parent_id);
384
+ await affinities.delete(resource.namespace,owner,resource.id,resource.parent);
385
+ }
386
+ if (!upstream.body) {cleanup();return new Response(null,{status:upstream.status,headers});}
387
+ const reader = upstream.body.getReader();
388
+ const stream = new ReadableStream({async pull(c) { try { const {done,value} = await reader.read(); if (done) {cleanup();reader.releaseLock();c.close();} else c.enqueue(value); } catch(error) {cleanup();c.error(error);} },async cancel(reason) {controller.abort(reason);cleanup();await reader.cancel(reason);reader.releaseLock();}});
389
+ return new Response(stream,{status:upstream.status,headers});
390
+ },
391
+ };
392
+ }