@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,157 @@
1
+ import { open } from 'node:fs/promises';
2
+ import { decodeTokenRecords, encodeLino } from './storage.mjs';
3
+
4
+ const schema = [['StorageFormat','router-token-doublets-v1'],['Type','TokenRecord'],['TokenRecord','SubType'],['SubType','Value']];
5
+ const utf8 = new TextDecoder('utf8',{fatal:true});
6
+ const stringCompare = (left,right) => Buffer.compare(Buffer.from(left),Buffer.from(right));
7
+ const base64 = value => Buffer.from(value).toString('base64').replace(/=+$/,'');
8
+ const valueNode = (parent,raw) => `${parent}/Value/${base64(raw)}`;
9
+ const decode64 = value => {
10
+ if (!/^[A-Za-z0-9+/]*$/.test(value) || value.length%4 === 1) throw new Error('Invalid token doublets base64');
11
+ const bytes = Buffer.from(value,'base64');
12
+ if (base64(bytes) !== value) throw new Error('Noncanonical token doublets base64');
13
+ return utf8.decode(bytes);
14
+ };
15
+ export function tokenSemanticLinks(records) {
16
+ const links = schema.map(pair => pair.slice());
17
+ for (const record of records) {
18
+ const root = `Record/${base64(record.id)}`, subtype = `${root}/SubType`, value = `${root}/Value`;
19
+ links.push([root,'Type'],[root,subtype],[subtype,valueNode(subtype,record.id)],[root,value]);
20
+ for (const [field,raw] of Object.entries(record)) {
21
+ if (raw == null) continue;
22
+ const path = `${value}/Field/${field}`;
23
+ const text = field === 'github_repos' ? raw.join(',') : field === 'model_policy' ? JSON.stringify(raw) : String(raw);
24
+ links.push([value,path],[path,valueNode(path,text)]);
25
+ }
26
+ }
27
+ const unique = new Map(links.map(pair => [JSON.stringify(pair),pair]));
28
+ return [...unique.values()].sort((left,right) => stringCompare(left[0],right[0]) || stringCompare(left[1],right[1]));
29
+ }
30
+ export function semanticTokenRecords(links) {
31
+ const pairs = new Set(links.map(pair => JSON.stringify(pair))), targets = new Map();
32
+ for (const pair of schema) if (!pairs.has(JSON.stringify(pair))) throw new Error('Token doublets schema is incomplete');
33
+ for (const [source,target] of links) { if (!targets.has(source)) targets.set(source,new Set()); targets.get(source).add(target); }
34
+ const one = source => { const values = [...(targets.get(source) ?? [])]; if (values.length !== 1) throw new Error('Token doublets value is missing or ambiguous'); return values[0]; };
35
+ const decodeValue = (parent,value) => { const prefix = `${parent}/Value/`; if (!value.startsWith(prefix)) throw new Error('Invalid doublets value relation'); return decode64(value.slice(prefix.length)); };
36
+ const records = [];
37
+ for (const [root,target] of links) if (target === 'Type' && root.startsWith('Record/')) {
38
+ const id = decode64(root.slice(7)), subtype = `${root}/SubType`, value = `${root}/Value`;
39
+ if (!pairs.has(JSON.stringify([root,subtype])) || !pairs.has(JSON.stringify([root,value])) || decodeValue(subtype,one(subtype)) !== id) throw new Error('Token doublets identity relations disagree');
40
+ const fields = {};
41
+ for (const fieldPath of targets.get(value) ?? []) if (fieldPath.startsWith(`${value}/Field/`)) fields[fieldPath.slice(value.length+7)] = decodeValue(fieldPath,one(fieldPath));
42
+ if (fields.id !== id) throw new Error('Token doublets record id mismatch');
43
+ for (const name of ['issued_at','expires_at']) { if (!/^-?\d+$/.test(fields[name] ?? '')) throw new Error('Invalid token timestamp'); fields[name] = Number(fields[name]); }
44
+ for (const name of ['revoked','ephemeral']) {
45
+ if (name === 'ephemeral' && fields[name] == null) { fields[name] = false; continue; }
46
+ if (!['true','false'].includes(fields[name])) throw new Error('Invalid token boolean'); fields[name] = fields[name] === 'true';
47
+ }
48
+ fields.used_tokens ??= '0'; fields.reserved_tokens ??= '0'; fields.rate_window_started_at ??= '0'; fields.rate_window_requests ??= '0';
49
+ fields.account ??= null; fields.client_kind ??= null; fields.principal_id ??= null; fields.run_lease_expires_at ??= null;
50
+ fields.max_tokens ??= null; fields.max_requests ??= null; fields.rate_limit_per_minute ??= null; fields.sliding_window_seconds ??= null;
51
+ // The text codec supplies the same field validation and defaults.
52
+ records.push(fields);
53
+ }
54
+ const document = {type:'RouterState',subtype:'TokenStore',value:records.map(record => ({type:'TokenRecord',subtype:record.id,value:record}))};
55
+ // Encode the framing only; these fields are already Rust's string scalars.
56
+ return decodeTokenRecords(encodeLino(document));
57
+ }
58
+ /** doublets 0.5 #[repr(C)] LinksHeader/LinkPart, usize, native little endian. */
59
+ export function encodeDoublets(links,{wordBytes = 8,maxLinks = 1000000} = {}) {
60
+ if (![4,8].includes(wordBytes)) throw new Error('Unsupported doublets word width');
61
+ const parts = [Array(8).fill(0)], lookup = new Map();
62
+ const pair = (source,target) => {
63
+ const key = `${source},${target}`;
64
+ if (lookup.has(key)) return lookup.get(key);
65
+ if (parts.length > maxLinks) throw new Error('Token links network exceeds capacity');
66
+ const index = parts.length; parts.push([source,target,0,0,1,0,0,1]); lookup.set(key,index); return index;
67
+ };
68
+ for (let point = 1; point <= 259; point++) if (pair(point,point) !== point) throw new Error('Doublets point initialization failed');
69
+ const strings = new Map();
70
+ const intern = value => {
71
+ if (strings.has(value)) return strings.get(value);
72
+ let tail = 3; const bytes = Buffer.from(value);
73
+ for (let at = bytes.length-1; at >= 0; at--) tail = pair(4+bytes[at],tail);
74
+ const node = pair(1,tail); strings.set(value,node); return node;
75
+ };
76
+ for (const [source,target] of links) pair(2,pair(intern(source),intern(target)));
77
+ const count = parts.length-1;
78
+ const build = (order,left,right,offset) => {
79
+ if (left >= right) return 0;
80
+ const middle = Math.floor((left+right)/2), index = order[middle];
81
+ parts[index][offset] = build(order,left,middle,offset); parts[index][offset+1] = build(order,middle+1,right,offset); parts[index][offset+2] = right-left;
82
+ return index;
83
+ };
84
+ const order = Array.from({length:count},(_,index) => index+1);
85
+ const sources = order.slice().sort((left,right) => parts[left][0]-parts[right][0] || parts[left][1]-parts[right][1]);
86
+ const targets = order.slice().sort((left,right) => parts[left][1]-parts[right][1] || parts[left][0]-parts[right][0]);
87
+ parts[0] = [count,count,0,0,build(sources,0,count,2),build(targets,0,count,5),0,0];
88
+ const result = Buffer.alloc(parts.length*wordBytes*8);
89
+ for (let index = 0; index < parts.length; index++) for (let field = 0; field < 8; field++) {
90
+ const offset = (index*8+field)*wordBytes;
91
+ if (wordBytes === 8) result.writeBigUInt64LE(BigInt(parts[index][field]),offset); else result.writeUInt32LE(parts[index][field],offset);
92
+ }
93
+ return result;
94
+ }
95
+ export function decodeDoublets(bytes,{wordBytes = 8,maxLinks = 1000000} = {}) {
96
+ const stride = wordBytes*8;
97
+ const read = (index,field) => {
98
+ const offset = index*stride+field*wordBytes;
99
+ if (offset+wordBytes > bytes.length) throw new Error('Truncated token doublets store');
100
+ const value = wordBytes === 8 ? Number(bytes.readBigUInt64LE(offset)) : bytes.readUInt32LE(offset);
101
+ if (!Number.isSafeInteger(value)) throw new Error('Unsafe token doublets link reference'); return value;
102
+ };
103
+ const allocated = read(0,0);
104
+ if (allocated < 259 || allocated > maxLinks || (allocated+1)*stride > bytes.length || read(0,1) < allocated || read(0,2) > allocated) throw new Error('Invalid token doublets header');
105
+ const exists = index => index > 0 && index <= allocated && read(index,4) !== 0;
106
+ for (let index = 1; index <= 259; index++) if (!exists(index) || read(index,0) !== index || read(index,1) !== index) throw new Error('Invalid token doublets schema point');
107
+ const cache = new Map();
108
+ const decode = node => {
109
+ if (cache.has(node)) return cache.get(node);
110
+ if (!exists(node) || read(node,0) !== 1) throw new Error('Invalid token doublets string');
111
+ const data = [], visited = new Set(); let tail = read(node,1);
112
+ while (tail !== 3) {
113
+ if (!exists(tail) || visited.has(tail)) throw new Error('Incomplete or cyclic token doublets string');
114
+ visited.add(tail); const byte = read(tail,0)-4;
115
+ if (byte < 0 || byte > 255) throw new Error('Invalid token doublets byte');
116
+ data.push(byte); tail = read(tail,1);
117
+ }
118
+ const text = utf8.decode(new Uint8Array(data)); cache.set(node,text); return text;
119
+ };
120
+ const links = new Map();
121
+ for (let index = 260; index <= allocated; index++) if (exists(index) && read(index,0) === 2) {
122
+ const pair = read(index,1); if (!exists(pair)) throw new Error('Token doublets edge refers to missing pair');
123
+ const relation = [decode(read(pair,0)),decode(read(pair,1))]; links.set(JSON.stringify(relation),relation);
124
+ }
125
+ return [...links.values()].sort((left,right) => stringCompare(left[0],right[0]) || stringCompare(left[1],right[1]));
126
+ }
127
+ export function encodeBinaryTokenRecords(records) { return encodeDoublets(tokenSemanticLinks(records)); }
128
+ export function decodeBinaryTokenRecords(bytes) { return semanticTokenRecords(decodeDoublets(bytes)); }
129
+ export async function readBinaryTokenRecords(path) {
130
+ let file;
131
+ try { file = await open(path,'r'); }
132
+ catch (error) { if (error.code === 'ENOENT') return []; throw error; }
133
+ try {
134
+ const header = Buffer.alloc(64); const read = await file.read(header,0,64,0);
135
+ if (read.bytesRead === 0) return [];
136
+ if (header.subarray(0,8).equals(Buffer.from('LARTOK01'))) {
137
+ const size = (await file.stat()).size;
138
+ if (size > 64*1024*1024) throw new Error('Legacy token projection exceeds capacity');
139
+ const bytes = Buffer.alloc(size); let offset = 0;
140
+ while (offset < size) { const part = await file.read(bytes,offset,size-offset,offset); if (!part.bytesRead) throw new Error('Truncated legacy token store'); offset += part.bytesRead; }
141
+ const records = [];
142
+ for (let cursor = 8; cursor+4 <= bytes.length;) {
143
+ const length = bytes.readUInt32LE(cursor); cursor += 4;
144
+ if (cursor+length > bytes.length) throw new Error('Truncated legacy token record');
145
+ records.push(JSON.parse(utf8.decode(bytes.subarray(cursor,cursor+length)))); cursor += length;
146
+ }
147
+ const {encodeTokenRecords} = await import('./storage.mjs');
148
+ return decodeTokenRecords(encodeTokenRecords(records));
149
+ }
150
+ const allocated = Number(header.readBigUInt64LE(0));
151
+ if (!Number.isSafeInteger(allocated) || allocated > 1000000 || allocated < 259) throw new Error('Invalid token doublets allocation');
152
+ const bytes = Buffer.alloc((allocated+1)*64);
153
+ let offset = 0;
154
+ while (offset < bytes.length) { const part = await file.read(bytes,offset,bytes.length-offset,offset); if (!part.bytesRead) throw new Error('Truncated token doublets store'); offset += part.bytesRead; }
155
+ return decodeBinaryTokenRecords(bytes);
156
+ } finally { await file.close(); }
157
+ }
@@ -0,0 +1,91 @@
1
+ import {createHash} from 'node:crypto';
2
+ import {AsyncLocalStorage} from 'node:async_hooks';
3
+ import {normalizeManagementPeer} from './management-access.mjs';
4
+
5
+ const requestOutcome = new AsyncLocalStorage();
6
+ const truthy = value => ['1','true','yes','on'].includes(String(value ?? '').trim().toLowerCase());
7
+ const failure = message => Object.assign(new Error(message),{code:'invalid_emergency_config',status:400});
8
+ const clientNames = new Set(['claude','codex','cursor','gemini','grok','opencode','qwen','agent']);
9
+ const aliases = {'claude-code':'claude','cursor-agent':'cursor','gemini-cli':'gemini','grok-cli':'grok','qwen-code':'qwen'};
10
+ const clientKind = value => {const name=String(value ?? '').trim().toLowerCase();return aliases[name] ?? (clientNames.has(name) ? name : null);};
11
+ export const isSyntheticTokenId = id => typeof id === 'string' && id.startsWith('emergency-bypass-');
12
+ export const tokenFingerprint = token => createHash('sha256').update(token).digest('hex').slice(0,12);
13
+ export function unverifiedPayload(token) {
14
+ try {
15
+ const part=token.replace(/^(la_sk_|at-)/,'').split('.')[1];
16
+ if (!part || part.length > 65536 || !/^[A-Za-z0-9_-]+={0,2}$/.test(part)) return null;
17
+ const payload=JSON.parse(Buffer.from(part,'base64url').toString('utf8'));
18
+ return payload && typeof payload === 'object' && !Array.isArray(payload) ? payload : null;
19
+ } catch {return null;}
20
+ }
21
+ export const withAuthenticationScope = operation => requestOutcome.run({counted:false},operation);
22
+ export function firstAuthenticationOutcome() {const scope=requestOutcome.getStore();if (!scope) return true;const first=!scope.counted;scope.counted=true;return first;}
23
+ export function diagnosticReason(error) {
24
+ return ({invalid_token:'malformed',not_yet_valid:'malformed',admin_required:'insufficient_scope',
25
+ request_limit_exceeded:'request_budget',token_limit_exceeded:'token_budget',rate_limit_exceeded:'rate_limit',
26
+ model_policy_unavailable:'model_policy',model_not_allowed:'model_policy'})[error?.code] ??
27
+ (['invalid_prefix','signature_invalid','issuer_secret_unset','expired','revoked','missing_record','binding_mismatch','not_found','missing_credential'].includes(error?.code) ? error.code : 'storage');
28
+ }
29
+ export class AuthenticationDiagnostics {
30
+ constructor({clock=()=>Math.floor(Date.now()/1000)}={}) {this.clock=clock;this.counts=new Map();this.recent=[];}
31
+ record(reason,token) {
32
+ this.counts.set(reason,(this.counts.get(reason) ?? 0)+1);
33
+ const value={at:this.clock(),reason};
34
+ if (typeof token === 'string' && token) {
35
+ value.fingerprint=tokenFingerprint(token);
36
+ const subject=unverifiedPayload(token)?.sub;
37
+ if (typeof subject === 'string' && /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(subject)) value.token_id=subject.toLowerCase();
38
+ }
39
+ this.recent.push(value);if (this.recent.length > 64) this.recent.shift();
40
+ }
41
+ recordOutcome(reason,token) {if (firstAuthenticationOutcome()) this.record(reason,token);}
42
+ snapshot() {return {failures_by_reason:Object.fromEntries([...this.counts].sort()),recent_failures:this.recent.slice().reverse().map(value=>({...value}))};}
43
+ renderPrometheus() {
44
+ const rows=[...this.counts].sort().map(([reason,count])=>`link_assistant_auth_failures_total{reason="${reason}"} ${count}`);
45
+ return '# HELP link_assistant_auth_failures_total Router token authentication failures by reason.\n# TYPE link_assistant_auth_failures_total counter\n'+(rows.length ? rows.join('\n') : 'link_assistant_auth_failures_total 0')+'\n';
46
+ }
47
+ }
48
+ export function normalizeEmergencyConfig(input={},env={}) {
49
+ const duration=Number(input.emergency_duration_minutes ?? input.emergency?.duration_minutes ?? env.EMERGENCY_DURATION_MINUTES ?? 60);
50
+ const enabled=truthy(input.emergency_accept_any_token ?? input.emergency?.enabled ?? env.EMERGENCY_ACCEPT_ANY_TOKEN);
51
+ const config={enabled,allow_non_loopback:truthy(input.emergency_allow_non_loopback ?? input.emergency?.allow_non_loopback ?? env.EMERGENCY_ALLOW_NON_LOOPBACK),duration_minutes:duration};
52
+ if (enabled && (!Number.isSafeInteger(duration) || duration < 1 || duration > 1440)) throw failure('Emergency duration must be between 1 and 1440 minutes');
53
+ return config;
54
+ }
55
+ export class EmergencyAuthentication {
56
+ constructor({config={},clock=()=>Math.floor(Date.now()/1000)}={}) {
57
+ this.clock=clock;this.config=config;this.until=0;this.bypassed=0;this.reasons=new Map();
58
+ }
59
+ checkListeners(listeners) {
60
+ if (!this.config.enabled) return;
61
+ if (!Number.isSafeInteger(this.config.duration_minutes) || this.config.duration_minutes < 1 || this.config.duration_minutes > 1440) throw failure('Emergency duration must be between 1 and 1440 minutes');
62
+ const loopback=address=>{const host=typeof address === 'string' ? address : address.address ?? address.host;if (host === 'localhost') return true;try {const peer=normalizeManagementPeer(host);return peer === '::1' || peer.startsWith('127.');} catch {return false;}};
63
+ if (!this.config.allow_non_loopback && listeners.some(address=>!loopback(address))) throw failure('Emergency non-loopback listeners require explicit acknowledgement');
64
+ }
65
+ start(listeners) {this.checkListeners(listeners);if (this.config.enabled) this.until=this.clock()+this.config.duration_minutes*60;}
66
+ activeUntil() {return this.until > this.clock() ? this.until : null;}
67
+ isActive() {return this.activeUntil() != null;}
68
+ disable() {const active=this.isActive();this.until=0;return active;}
69
+ status() {const expiry=this.activeUntil();return {active:expiry != null,...(expiry != null ? {expires_at:expiry} : {}),bypassed_requests:this.bypassed,bypassed_by_reason:Object.fromEntries([...this.reasons].sort())};}
70
+ claims(token,headers={}) {
71
+ const get=name=>typeof headers.get === 'function' ? headers.get(name) : headers[name] ?? headers[name.toLowerCase()];
72
+ const payload=unverifiedPayload(token),agent=String(get('user-agent') ?? '').toLowerCase();
73
+ const inferred=clientKind(get('x-link-assistant-client')) ?? (agent.startsWith('claude') ? 'claude' : agent.startsWith('codex') ? 'codex' : agent.startsWith('opencode/') ? 'opencode' : agent.startsWith('grok') ? 'grok' :
74
+ get('x-goog-api-client') || get('x-goog-api-key') ? 'gemini' : get('x-stainless-package-version') ? 'qwen' : token.startsWith('at-') ? 'codex' : null);
75
+ const client=inferred ?? clientKind(payload?.client_kind),fingerprint=tokenFingerprint(token),now=this.clock();
76
+ return {sub:`emergency-bypass-${fingerprint}`,iat:now,exp:now+60,label:'emergency-bypass',scope:'',github_repos:[],
77
+ client_kind:client,principal_id:client ? typeof payload?.principal_id === 'string' && payload.principal_id.trim() ? payload.principal_id : `emergency-${fingerprint}` : null,
78
+ account:null,record:null,is_admin:false};
79
+ }
80
+ admit(token,headers,reason,count = firstAuthenticationOutcome()) {
81
+ if (count) {this.bypassed++;this.reasons.set(reason,(this.reasons.get(reason) ?? 0)+1);}
82
+ return this.claims(token,headers);
83
+ }
84
+ renderPrometheus() {
85
+ const rows=[...this.reasons].sort().map(([reason,count])=>`link_assistant_emergency_auth_bypassed_total{reason="${reason}"} ${count}`);
86
+ return '# HELP link_assistant_emergency_auth_active 1 while the emergency any-token mode is on.\n# TYPE link_assistant_emergency_auth_active gauge\n'+
87
+ `link_assistant_emergency_auth_active ${Number(this.isActive())}\n`+
88
+ '# HELP link_assistant_emergency_auth_bypassed_total Requests admitted by the emergency any-token mode, by the check they bypassed.\n# TYPE link_assistant_emergency_auth_bypassed_total counter\n'+
89
+ (rows.length ? rows.join('\n') : 'link_assistant_emergency_auth_bypassed_total 0')+'\n';
90
+ }
91
+ }
@@ -0,0 +1,107 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { mkdir } from 'node:fs/promises';
3
+ import { dirname, extname } from 'node:path';
4
+
5
+ // Node has no advisory-lock API. This bounded standard-library OS adapter
6
+ // holds exactly the flock/LockFileEx lock used by std::fs::File::lock. No Rust
7
+ // executable, native build, private lock format or package install is involved.
8
+ const helper = String.raw`
9
+ import os,sys,time
10
+ path,mode,timeout=sys.argv[1:]
11
+ fd=os.open(path,os.O_RDWR|os.O_CREAT,0o600)
12
+ if os.name!='nt':
13
+ import fcntl
14
+ os.fchmod(fd,0o600)
15
+ def take(): fcntl.flock(fd,(fcntl.LOCK_SH if mode=='shared' else fcntl.LOCK_EX)|fcntl.LOCK_NB)
16
+ else:
17
+ import ctypes,msvcrt
18
+ from ctypes import wintypes
19
+ class OVERLAPPED(ctypes.Structure):
20
+ _fields_=[('Internal',ctypes.c_size_t),('InternalHigh',ctypes.c_size_t),('Offset',wintypes.DWORD),('OffsetHigh',wintypes.DWORD),('hEvent',wintypes.HANDLE)]
21
+ kernel=ctypes.WinDLL('kernel32',use_last_error=True)
22
+ kernel.LockFileEx.argtypes=[wintypes.HANDLE,wintypes.DWORD,wintypes.DWORD,wintypes.DWORD,wintypes.DWORD,ctypes.POINTER(OVERLAPPED)]
23
+ kernel.LockFileEx.restype=wintypes.BOOL
24
+ handle=msvcrt.get_osfhandle(fd); overlap=OVERLAPPED()
25
+ def take():
26
+ if not kernel.LockFileEx(handle,1|(2 if mode=='exclusive' else 0),0,0xffffffff,0xffffffff,ctypes.byref(overlap)):
27
+ code=ctypes.get_last_error()
28
+ if code==33: raise BlockingIOError('lock held')
29
+ raise ctypes.WinError(code)
30
+ end=time.monotonic()+float(timeout)/1000
31
+ while True:
32
+ try: take(); break
33
+ except BlockingIOError:
34
+ if time.monotonic()>=end: raise TimeoutError('advisory lock timeout')
35
+ time.sleep(.02)
36
+ sys.stdout.write('locked\n');sys.stdout.flush()
37
+ sys.stdin.buffer.read()
38
+ os.close(fd)
39
+ `;
40
+ let traceSequence = 0;
41
+ function lockTrace(shared) {
42
+ if (process.env.ROUTER_FILE_LOCK_TRACE !== '1') return () => {};
43
+ const started = process.hrtime.bigint(), id = ++traceSequence;
44
+ // Scalar timing only: storage paths, contents and credentials stay private.
45
+ return (phase, detail = {}) => {
46
+ try {
47
+ process.stderr.write(JSON.stringify({
48
+ event:'router-file-lock',pid:process.pid,id,shared:Boolean(shared),phase,
49
+ elapsedMs:Number(process.hrtime.bigint()-started)/1e6,...detail,
50
+ })+'\n');
51
+ } catch {
52
+ // Diagnostics must not interrupt lock acquisition or helper cleanup.
53
+ }
54
+ };
55
+ }
56
+ export function rustLockPath(path) {
57
+ const extension = extname(path);
58
+ return `${extension ? path.slice(0,-extension.length) : path}.lock`;
59
+ }
60
+ async function acquire(path,{shared,timeout,python},trace) {
61
+ trace('helper-start');
62
+ const child = spawn(python,['-u','-c',helper,path,shared ? 'shared' : 'exclusive',String(timeout)],{stdio:['pipe','pipe','pipe'],windowsHide:true});
63
+ child.stdin.on('error',() => {});
64
+ let diagnostic = '';
65
+ child.stderr.setEncoding('utf8'); child.stderr.on('data',chunk => { diagnostic = (diagnostic+chunk).slice(-4096); });
66
+ const closed = new Promise(resolve => child.once('close',(code,signal) => {
67
+ trace('helper-closed',{code,signal}); resolve({code,signal});
68
+ }));
69
+ try {
70
+ await new Promise((resolve,reject) => {
71
+ let buffer = '';
72
+ const timer = setTimeout(() => { child.kill(); reject(new Error('Timed out acquiring advisory file lock')); },timeout+2000);
73
+ const fail = error => { clearTimeout(timer); reject(error); };
74
+ child.once('error',fail);
75
+ child.once('exit',code => { clearTimeout(timer); reject(new Error(`Advisory lock helper exited (${code}): ${diagnostic}`)); });
76
+ child.stdout.setEncoding('utf8'); child.stdout.on('data',chunk => {
77
+ buffer += chunk;
78
+ if (buffer === 'locked\n') { clearTimeout(timer); child.removeListener('error',fail); trace('acquired'); resolve(); }
79
+ else if (buffer.length > 1024) fail(new Error('Invalid advisory lock handshake'));
80
+ });
81
+ });
82
+ return {child,closed};
83
+ } catch (error) { child.kill(); await closed; throw error; }
84
+ }
85
+ /** A shared OS lock makes mixed JavaScript/Rust store transactions serialize. */
86
+ export async function withAdvisoryFileLock(path,operation,{shared = false,timeout = 30000,python = process.env.ROUTER_LOCK_PYTHON} = {}) {
87
+ const trace = lockTrace(shared);
88
+ trace('start');
89
+ await mkdir(dirname(path),{recursive:true,mode:0o700});
90
+ trace('directory-ready');
91
+ let held;
92
+ const commands = python ? [python] : process.platform === 'win32' ? ['python','python3'] : ['python3','python'];
93
+ for (const command of commands) {
94
+ try { held = await acquire(path,{shared,timeout,python:command},trace); break; }
95
+ catch (error) { if (error.code !== 'ENOENT') throw error; }
96
+ }
97
+ if (!held) throw Object.assign(new Error('Advisory file locking requires Python 3; configure ROUTER_LOCK_PYTHON'),{code:'lock_adapter_unavailable'});
98
+ trace('operation-start');
99
+ try { return await operation(); }
100
+ finally {
101
+ trace('operation-finished');
102
+ held.child.stdin.end();
103
+ trace('release-requested');
104
+ const timer = setTimeout(() => { trace('release-force-kill'); held.child.kill(); },2000);
105
+ try { await held.closed; } finally { clearTimeout(timer); }
106
+ }
107
+ }
@@ -0,0 +1,133 @@
1
+ import {ProtocolError} from './protocols.mjs';
2
+ const copy = structuredClone;
3
+ const object = (value,path) => {if (!value || typeof value !== 'object' || Array.isArray(value)) throw new ProtocolError(`${path} must be an object`);return value;};
4
+ const fields = (value,allowed,path) => {object(value,path);for (const key of Object.keys(value)) if (!allowed.includes(key)) throw new ProtocolError(`${path}.${key} cannot be represented by this bridge`);};
5
+ const string = (value,path) => {if (typeof value !== 'string') throw new ProtocolError(`${path} must be a string`);return value;};
6
+ const parseObject = (value,path) => {let parsed;try {parsed = typeof value === 'string' ? JSON.parse(value) : value;} catch {throw new ProtocolError(`${path} must encode a JSON object`);}return object(parsed,path);};
7
+ const alias = (value,a,b) => value[a] ?? value[b];
8
+ const levels={minimal:512,low:1024,medium:8192,high:24576,xhigh:32768,max:128000};
9
+ function effort(value) {if(value==null)return;if(typeof value!=='string')throw new ProtocolError('thinking effort must be a string');const normalized=value.toLowerCase();if(normalized==='-1')return 'auto';if(!['none','auto',...Object.keys(levels)].includes(normalized))throw new ProtocolError(`unsupported thinking effort: ${value}`);return normalized;}
10
+ function chatThinking(body) {
11
+ if(body.reasoning!=null)object(body.reasoning,'reasoning');
12
+ const value=effort(body.reasoning?.effort ?? body.reasoning_effort);if(value===undefined)return;
13
+ const visible=typeof body.reasoning?.summary==='string' ? body.reasoning.summary!=='none' : typeof body.reasoning_effort==='string' ? body.reasoning_effort!=='none':undefined;
14
+ return {thinkingBudget:value==='none'?0:value==='auto'?-1:levels[value],...(visible===undefined?{}:{includeThoughts:visible})};
15
+ }
16
+ function geminiThinking(config) {
17
+ if(!config)return;fields(config,['includeThoughts','include_thoughts','thinkingBudget','thinking_budget','thinkingLevel','thinking_level'],'thinkingConfig');
18
+ for(const key of ['includeThoughts','include_thoughts'])if(config[key]!==undefined && typeof config[key]!=='boolean')throw new ProtocolError(`thinkingConfig.${key} must be a boolean`);
19
+ const level=effort(alias(config,'thinkingLevel','thinking_level'));if(level!==undefined)return level;
20
+ const budget=alias(config,'thinkingBudget','thinking_budget');if(budget==null)return;
21
+ if(!Number.isSafeInteger(budget) || budget< -1 || budget>4294967295)throw new ProtocolError('thinking budget must be -1 or a nonnegative u32 integer');
22
+ return budget===-1?'auto':budget===0?'none':budget<=512?'minimal':budget<=1024?'low':budget<=8192?'medium':budget<=24576?'high':'xhigh';
23
+ }
24
+ function imageMedia(value) {if(!['image/jpeg','image/png','image/gif','image/webp'].includes(value))throw new ProtocolError('Image media type is unsupported');return value;}
25
+ function imageBase64(value) {if(typeof value!=='string' || !value || !/^[A-Za-z0-9+/]+={0,2}$/.test(value) || value.replace(/=+$/,'').length%4===1 || value.includes('=') && value.length%4!==0 || Buffer.from(value,'base64').toString('base64').replace(/=+$/,'')!==value.replace(/=+$/,''))throw new ProtocolError('Image data must be valid base64');return value;}
26
+ const chatContent=parts=>parts.length===1 && parts[0].type==='text' ? parts[0].text:parts;
27
+ function chatParts(content) {
28
+ if (content == null) return [];
29
+ if (typeof content === 'string') return content ? [{text:content}] : [];
30
+ if (!Array.isArray(content)) throw new ProtocolError('Message content must be a string or array');
31
+ return content.map(part => {
32
+ if (part.type === 'text') {fields(part,['type','text'],'content');return {text:string(part.text,'content.text')};}
33
+ if (part.type === 'image_url') {
34
+ fields(part,['type','image_url'],'content');fields(part.image_url,['url','detail'],'image_url');
35
+ if (part.image_url.detail != null && part.image_url.detail !== 'auto') throw new ProtocolError('image detail cannot be represented by Gemini');
36
+ const url=string(part.image_url.url,'image_url.url'), match=/^data:(image\/(?:jpeg|png|gif|webp));base64,([A-Za-z0-9+/]+={0,2})$/.exec(url);
37
+ if (match) return {inlineData:{mimeType:match[1],data:imageBase64(match[2])}};
38
+ let parsed;try {parsed=new URL(url);} catch {throw new ProtocolError('Image URI must be an absolute HTTP(S) URI');}
39
+ if (!['http:','https:'].includes(parsed.protocol))throw new ProtocolError('Image URI must use HTTP(S)');
40
+ return {fileData:{fileUri:url}};
41
+ }
42
+ throw new ProtocolError(`Cannot translate content part ${part.type} to Gemini`);
43
+ });
44
+ }
45
+ export function chatToGemini(body) {
46
+ fields(body,['model','messages','stream','max_tokens','max_completion_tokens','temperature','top_p','top_k','stop','tools','tool_choice','parallel_tool_calls','n','stream_options','user','safety_identifier','response_format','seed','frequency_penalty','presence_penalty','logit_bias','modalities','audio','logprobs','top_logprobs','reasoning','reasoning_effort'],'request');
47
+ if (!Array.isArray(body.messages))throw new ProtocolError('messages must be an array');
48
+ if (body.max_tokens != null && body.max_completion_tokens != null)throw new ProtocolError('max_completion_tokens and max_tokens cannot both be set');
49
+ if (body.n != null && body.n !== 1)throw new ProtocolError('Gemini bridge supports only n=1');
50
+ for (const field of ['audio','user','safety_identifier','stream_options'])if(body[field]!=null)throw new ProtocolError(`${field} cannot be represented by Gemini`);
51
+ if(body.logprobs!=null && body.logprobs!==false || body.top_logprobs!=null && body.top_logprobs!==0)throw new ProtocolError('Log probabilities cannot be represented by Gemini');
52
+ if(body.logit_bias!=null && (typeof body.logit_bias!=='object' || Array.isArray(body.logit_bias) || Object.keys(body.logit_bias).length))throw new ProtocolError('logit_bias cannot be represented by Gemini');
53
+ for(const field of ['frequency_penalty','presence_penalty'])if(body[field]!=null && (typeof body[field]!=='number' || !Number.isFinite(body[field]) || body[field]<-2 || body[field]>2))throw new ProtocolError(`${field} must be between -2 and 2`);
54
+ if(body.seed!=null && !Number.isSafeInteger(body.seed))throw new ProtocolError('seed must be an integer');
55
+ if(body.top_k!=null && (!Number.isSafeInteger(body.top_k) || body.top_k<0))throw new ProtocolError('top_k must be a non-negative integer');
56
+ if(body.parallel_tool_calls!=null && typeof body.parallel_tool_calls!=='boolean')throw new ProtocolError('parallel_tool_calls must be a boolean');
57
+ if(body.parallel_tool_calls === false)throw new ProtocolError('Disabling parallel calls cannot be represented by Gemini');
58
+ if(body.modalities && JSON.stringify(body.modalities) !== '["text"]')throw new ProtocolError('Non-text modalities cannot be represented by Gemini');
59
+ const out={contents:[]},system=[],pending=new Map();
60
+ for (const message of body.messages) {
61
+ fields(message,message.role === 'assistant' ? ['role','content','name','tool_calls'] : message.role === 'tool' ? ['role','content','tool_call_id'] : ['role','content','name'],'message');
62
+ if(message.name)throw new ProtocolError('Message name cannot be represented by Gemini');
63
+ if(['system','developer'].includes(message.role)){system.push(...chatParts(message.content));continue;}
64
+ if(message.role === 'tool') {
65
+ const name=pending.get(message.tool_call_id);if(!name)throw new ProtocolError('Tool result has no preceding matching call');pending.delete(message.tool_call_id);
66
+ const text=typeof message.content === 'string' ? message.content : (message.content ?? []).map(p => {if(p.type !== 'text')throw new ProtocolError('Tool output must be text');return p.text;}).join('');
67
+ let response;try {response=JSON.parse(text);} catch {response={output:text};}if(!response || typeof response !== 'object' || Array.isArray(response))response={output:text};
68
+ out.contents.push({role:'user',parts:[{functionResponse:{id:message.tool_call_id,name,response}}]});continue;
69
+ }
70
+ if(!['user','assistant'].includes(message.role))throw new ProtocolError('Message role cannot be represented by Gemini');
71
+ const parts=chatParts(message.content);
72
+ for(const call of message.tool_calls ?? []) {
73
+ if(call.type !== 'function' || !call.id || !call.function?.name || pending.has(call.id))throw new ProtocolError('Function call identity is invalid or duplicated');
74
+ pending.set(call.id,call.function.name);parts.push({functionCall:{id:call.id,name:call.function.name,args:parseObject(call.function.arguments,'function.arguments')}});
75
+ }
76
+ out.contents.push({role:message.role === 'assistant' ? 'model' : 'user',parts});
77
+ }
78
+ if(system.length)out.systemInstruction={parts:system};
79
+ const generation={};
80
+ for(const [from,to] of [['temperature','temperature'],['top_p','topP'],['top_k','topK'],['frequency_penalty','frequencyPenalty'],['presence_penalty','presencePenalty'],['seed','seed']])if(body[from] !== undefined)generation[to]=body[from];
81
+ if(body.max_completion_tokens ?? body.max_tokens)generation.maxOutputTokens=body.max_completion_tokens ?? body.max_tokens;
82
+ if(body.stop)generation.stopSequences=Array.isArray(body.stop)?copy(body.stop):[body.stop];
83
+ if(body.response_format) {
84
+ if(body.response_format.type === 'json_object'){generation.responseMimeType='application/json';generation.responseJsonSchema={type:'object',additionalProperties:true};}
85
+ else if(body.response_format.type === 'json_schema'){const definition=object(body.response_format.json_schema,'response_format.json_schema');if(typeof definition.name!=='string' || !definition.name || definition.strict!==undefined && typeof definition.strict!=='boolean')throw new ProtocolError('JSON schema requires a nonempty name and boolean strict');generation.responseMimeType='application/json';generation.responseJsonSchema=copy(object(definition.schema,'schema'));}
86
+ else if(body.response_format.type !== 'text')throw new ProtocolError('Unsupported response_format');
87
+ }
88
+ const thinking=chatThinking(body);if(thinking)generation.thinkingConfig=thinking;
89
+ if(Object.keys(generation).length)out.generationConfig=generation;
90
+ if(body.tools)out.tools=[{functionDeclarations:body.tools.map(tool => {fields(tool,['type','function'],'tool');if(tool.type !== 'function')throw new ProtocolError('Gemini only supports function tools');fields(tool.function,['name','description','parameters','strict'],'function');if(tool.function.strict!=null && tool.function.strict!==false)throw new ProtocolError('Function strict cannot be represented by Gemini');if(typeof tool.function.name!=='string' || !tool.function.name)throw new ProtocolError('Function name must not be empty');return {name:tool.function.name,...(tool.function.description ? {description:tool.function.description}:{}),parameters:copy(object(tool.function.parameters ?? {type:'object',properties:{}},'parameters'))};})}];
91
+ if(body.tool_choice) {
92
+ const mode=typeof body.tool_choice === 'string'?{auto:'AUTO',none:'NONE',required:'ANY'}[body.tool_choice]:'ANY';if(!mode)throw new ProtocolError('Unsupported tool_choice');
93
+ out.toolConfig={functionCallingConfig:{mode,...(typeof body.tool_choice === 'object'?{allowedFunctionNames:[body.tool_choice.function.name]}:{})}};
94
+ }
95
+ return out;
96
+ }
97
+ export function geminiToChat(body) {
98
+ fields(body,['model','stream','contents','systemInstruction','system_instruction','generationConfig','generation_config','tools','toolConfig','tool_config'],'request');
99
+ if(!Array.isArray(body.contents))throw new ProtocolError('contents must be an array');
100
+ const out={model:body.model,messages:[],stream:body.stream ?? false},pending=[];let sequence=0;
101
+ const convert = part => {
102
+ if(Object.hasOwn(part,'text')) {fields(part,['text'],'part');return {type:'text',text:string(part.text,'part.text')};}
103
+ const inline=alias(part,'inlineData','inline_data');if(inline){fields(part,['inlineData','inline_data'],'part');fields(inline,['mimeType','mime_type','data'],'inlineData');const mime=imageMedia(alias(inline,'mimeType','mime_type'));imageBase64(inline.data);return {type:'image_url',image_url:{url:`data:${mime};base64,${inline.data}`}};}
104
+ const file=alias(part,'fileData','file_data');if(file){fields(part,['fileData','file_data'],'part');fields(file,['mimeType','mime_type','fileUri','file_uri'],'fileData');const media=alias(file,'mimeType','mime_type');if(media!=null)imageMedia(media);const uri=alias(file,'fileUri','file_uri');let url;try{url=new URL(uri);}catch{throw new ProtocolError('Image URI is invalid');}if(!['http:','https:'].includes(url.protocol))throw new ProtocolError('Image URI must use HTTP(S)');return {type:'image_url',image_url:{url:uri}};}
105
+ throw new ProtocolError('Gemini part cannot be represented by this bridge');
106
+ };
107
+ const system=alias(body,'systemInstruction','system_instruction');if(system){fields(system,['role','parts'],'systemInstruction');out.messages.push({role:'system',content:chatContent(system.parts.map(convert))});}
108
+ for(const content of body.contents) {
109
+ fields(content,['role','parts'],'content');const role=content.role ?? 'user';if(!['user','model'].includes(role) || !Array.isArray(content.parts))throw new ProtocolError('Gemini content role/parts is invalid');
110
+ const ordinary=[],calls=[],results=[];
111
+ for(const part of content.parts) {
112
+ const call=alias(part,'functionCall','function_call'),result=alias(part,'functionResponse','function_response');
113
+ if(call){fields(part,['functionCall','function_call'],'part');fields(call,['id','name','args'],'functionCall');if(role !== 'model' || !call.name)throw new ProtocolError('Function call must be in a model turn');const id=call.id ?? `call_${sequence++}`;if(pending.some(p=>p.id === id))throw new ProtocolError('Function call id is duplicated');pending.push({id,name:call.name});calls.push({id,type:'function',function:{name:call.name,arguments:JSON.stringify(object(call.args ?? {},'args'))}});}
114
+ else if(result){fields(part,['functionResponse','function_response'],'part');fields(result,['id','name','response'],'functionResponse');if(role !== 'user')throw new ProtocolError('Function response must be in a user turn');const matches=pending.filter(c => c.name === result.name && (!result.id || c.id === result.id));if(matches.length !== 1)throw new ProtocolError('Function response is missing or ambiguous; include call id');const matched=matches[0];pending.splice(pending.indexOf(matched),1);results.push({role:'tool',tool_call_id:matched.id,content:JSON.stringify(object(result.response,'response'))});}
115
+ else ordinary.push(convert(part));
116
+ }
117
+ out.messages.push(...results);
118
+ if(ordinary.length || calls.length)out.messages.push({role:role === 'model'?'assistant':'user',content:chatContent(ordinary),...(calls.length?{tool_calls:calls}:{})});
119
+ }
120
+ const generation=alias(body,'generationConfig','generation_config');if(generation){fields(generation,['temperature','topP','topK','maxOutputTokens','stopSequences','thinkingConfig'],'generationConfig');for(const [from,to] of [['temperature','temperature'],['topP','top_p'],['maxOutputTokens','max_tokens'],['stopSequences','stop']])if(generation[from]!==undefined)out[to]=copy(generation[from]);if(generation.topK!==undefined && generation.topK!==64)throw new ProtocolError('generationConfig.topK has no exact cross-provider representation');const thinking=geminiThinking(generation.thinkingConfig);if(thinking!==undefined)out.reasoning_effort=thinking;}
121
+ if(body.tools)out.tools=body.tools.flatMap(tool => {fields(tool,['functionDeclarations','function_declarations'],'tools');const declarations=alias(tool,'functionDeclarations','function_declarations');if(!Array.isArray(declarations))throw new ProtocolError('Function declarations must be an array');return declarations.map(fn => {fields(fn,['name','description','parameters','parametersJsonSchema'],'declaration');return {type:'function',function:{...copy(fn),...(fn.parametersJsonSchema===undefined?{}:{parameters:copy(fn.parametersJsonSchema)})}};}).map(tool=>{delete tool.function.parametersJsonSchema;return tool;});});
122
+ const config=alias(body,'toolConfig','tool_config');if(config){const calling=alias(config,'functionCallingConfig','function_calling_config');fields(calling,['mode','allowedFunctionNames','allowed_function_names'],'functionCallingConfig');const allowed=alias(calling,'allowedFunctionNames','allowed_function_names'),mode=calling.mode?.toUpperCase();if(allowed){if(mode !== 'ANY' || allowed.length !== 1)throw new ProtocolError('Function policy cannot be represented exactly');out.tool_choice={type:'function',function:{name:allowed[0]}};}else {out.tool_choice={AUTO:'auto',NONE:'none',ANY:'required'}[mode];if(!out.tool_choice)throw new ProtocolError('Function policy mode is invalid');}}
123
+ return out;
124
+ }
125
+ export function geminiCanonical(body, normalizeUsage) {
126
+ const value=body.response ?? body,candidate=value.candidates?.[0],reason=candidate?.finishReason ?? value.promptFeedback?.blockReason;if(value.candidates?.length > 1 || !candidate?.content && !reason)throw new ProtocolError('Gemini response must contain one candidate or a terminal prompt block',502);
127
+ const r={id:value.responseId,model:value.modelVersion,text:'',tools:[],usage:normalizeUsage(value.usageMetadata,'gemini'),finish:reason === 'MAX_TOKENS' ? 'length':reason==null || reason==='STOP'?'stop':'content_filter'};
128
+ for(const part of candidate?.content?.parts ?? []){if(part.text !== undefined){r.text+=part.text;}else if(part.functionCall){const c=part.functionCall;r.tools.push({id:c.id ?? `call_${r.tools.length}`,type:'function',function:{name:c.name,arguments:JSON.stringify(c.args ?? {})}});}else throw new ProtocolError('Gemini output part cannot be represented',502);}
129
+ if(r.tools.length && r.finish==='stop')r.finish='tool_calls';return r;
130
+ }
131
+ export function canonicalGemini(r,model) {
132
+ return {candidates:[{index:0,content:{role:'model',parts:[...(r.text?[{text:r.text}]:[]),...r.tools.map(t=>({functionCall:{id:t.id,name:t.function.name,args:parseObject(t.function.arguments,'arguments')}}))]},finishReason:r.finish === 'length'?'MAX_TOKENS':'STOP'}],usageMetadata:{promptTokenCount:r.usage.input,candidatesTokenCount:r.usage.output,totalTokenCount:r.usage.total,cachedContentTokenCount:r.usage.cached},modelVersion:model};
133
+ }
@@ -0,0 +1,46 @@
1
+ /** Explicit location metadata policy. This does not conceal the transport IP. */
2
+ export const GEOLOCATION_OPT_IN = 'x-router-share-geolocation';
3
+
4
+ export function geolocationInferencePath(path) {
5
+ return ['/messages','/messages/count_tokens','/messages/batches','/chat/completions',
6
+ '/responses','/responses/compact','/responses/input_tokens','/invoke','/invoke-with-response-stream',
7
+ ':generateContent',':streamGenerateContent',':countTokens',':rawPredict',':streamRawPredict']
8
+ .some(suffix=>path.endsWith(suffix));
9
+ }
10
+
11
+ export function sharesGeolocation(headers) {
12
+ // Headers joins repeated values with commas: duplicates deliberately fail closed.
13
+ return headers.get(GEOLOCATION_OPT_IN) === 'true';
14
+ }
15
+
16
+ export function isGeolocationHeader(name) {
17
+ const lower = name.toLowerCase();
18
+ return /^(?:cf-(?:ip(?:country|city|continent|latitude|longitude|region|region-code|timezone|postal-code)|region|region-code|metro-code|postal-code|timezone)|x-vercel-ip-.*|cloudfront-viewer-(?:country|country-name|country-region|country-region-name|city|latitude|longitude|postal-code|time-zone)|x-appengine-(?:country|region|city|citylatlong)|x-geo-.*|x-geolocation(?:-.*)?|x-user-location|x-client-(?:country|city|region)|x-latitude|x-longitude)$/.test(lower);
19
+ }
20
+
21
+ /** Mutate only API location metadata, never arbitrary prompt/schema properties. */
22
+ export function sanitizeGeolocation(value, share = false) {
23
+ if (share || !value || typeof value !== 'object' || Array.isArray(value)) return false;
24
+ let changed = false;
25
+ const remove = (object, key) => {
26
+ if (object && typeof object === 'object' && !Array.isArray(object) && Object.hasOwn(object,key)) {
27
+ delete object[key]; changed = true;
28
+ }
29
+ };
30
+ const roots = [value, value.request, value.response, value.session];
31
+ if (Array.isArray(value.requests)) for (const batch of value.requests) roots.push(batch?.params);
32
+ for (const root of roots) {
33
+ if (!root || typeof root !== 'object' || Array.isArray(root)) continue;
34
+ remove(root.web_search_options,'user_location');
35
+ // ProtoJSON accepts either field spelling independently at every level.
36
+ for (const config of ['toolConfig','tool_config']) for (const retrieval of ['retrievalConfig','retrieval_config']) {
37
+ const location = root[config]?.[retrieval];
38
+ remove(location,'latLng');
39
+ remove(location,'lat_lng');
40
+ }
41
+ if (Array.isArray(root.tools)) for (const tool of root.tools) {
42
+ if (typeof tool?.type === 'string' && /^web_search(?:_preview)?(?:_(?:\d{8}|\d{4}_\d{2}_\d{2}))?$/.test(tool.type)) remove(tool,'user_location');
43
+ }
44
+ }
45
+ return changed;
46
+ }
@@ -0,0 +1,52 @@
1
+ import {boundedBytes,nativeResponseHeaders} from './native-service.mjs';
2
+ const ZERO='0'.repeat(40);
3
+ const glob=(pattern,path)=>pattern.endsWith('/**') ? path===pattern.slice(0,-3) || path.startsWith(pattern.slice(0,-3)+'/') : pattern.split('/').length===path.split('/').length && pattern.split('/').every((part,index)=>part==='*' || part===path.split('/')[index]);
4
+ const allowedRef=(policy,repository,name)=>(policy.rules ?? []).some(rule=>rule.effect==='allow' && (!rule.method || rule.method.toUpperCase()==='GIT') && glob(rule.path,`/git/${repository}/${name}`));
5
+ export function parseRefUpdates(body) {
6
+ const updates=[];let cursor=0;const decoder=new TextDecoder('utf-8',{fatal:true});
7
+ while(cursor+4<=body.length) {
8
+ const prefix=Buffer.from(body.subarray(cursor,cursor+4)).toString('ascii');if(!/^[0-9a-fA-F]{4}$/.test(prefix))break;
9
+ const length=parseInt(prefix,16);if(!length || length<4 || cursor+length>body.length)break;
10
+ let payload=body.subarray(cursor+4,cursor+length);cursor+=length;const nul=payload.indexOf(0);if(nul>=0)payload=payload.subarray(0,nul);
11
+ let fields;try{fields=decoder.decode(payload).trim().split(' ');}catch{continue;}
12
+ if(fields.length>=3 && fields[0].length===40 && fields[1].length===40)updates.push({old:fields[0],new:fields[1],name:fields[2]});
13
+ }
14
+ return updates;
15
+ }
16
+ const refusal=(name,operation,reason)=>`Blocked by Link.Assistant.Router git policy: ${operation==='delete' ? `deleting ${name} is refused` : operation==='force' ? `force-updating ${name} is refused` : `could not confirm ${name} is a fast-forward (${reason})`}; allow it in GITHUB_PROXY_POLICY to permit this ref`;
17
+ export async function relayGit(request,{config,claims,fetch=globalThis.fetch,maxBodyBytes=4*1024*1024,maxResponseBytes=32*1024*1024,timeoutMs=120000}) {
18
+ const error=(status,message,blocked=false)=>new Response(message+'\n',{status,headers:{'content-type':'text/plain; charset=utf-8',...(blocked?{'x-link-assistant-policy':'blocked'}:{})}});
19
+ const source=new URL(request.url),path=source.pathname.replace(/^\/api\/services\/github/,'');
20
+ const repository=/^\/git\/([^/]+)\/([^/]+)/.exec(path)?.slice(1).join('/').replace(/(?:\.git)+$/,'');
21
+ if(!repository)return error(404,'not a git repository path');if(!config.token)return error(503,'GitHub proxy is not configured');
22
+ const scope=claims.github_repos ?? claims.record?.github_repos ?? [];if(scope.length && !scope.some(value=>value.toLowerCase()===repository.toLowerCase()))return error(403,"outside this token's repositories",true);
23
+ let body;try{body=await boundedBytes(request,maxBodyBytes);}catch(errorValue){return error(413,errorValue.message);}
24
+ const controller=new AbortController(),abort=()=>controller.abort(request.signal.reason);request.signal.addEventListener('abort',abort,{once:true});if(request.signal.aborted)abort();
25
+ const timer=setTimeout(()=>controller.abort(),timeoutMs);timer.unref?.();const cleanup=()=>{clearTimeout(timer);request.signal.removeEventListener('abort',abort);};
26
+ const authorization='Basic '+Buffer.from(`x-access-token:${config.token}`).toString('base64');
27
+ if(path.endsWith('/git-receive-pack')) {
28
+ const updates=parseRefUpdates(body),window=Buffer.from(body.subarray(0,4096)),start=window.indexOf(0),capabilities=start>=0 ? window.subarray(start).toString('utf8'):'';
29
+ const force=capabilities.includes('force-ref-updates') || capabilities.includes('push-force');
30
+ for(const update of updates) {
31
+ if(allowedRef(config.policy,repository,update.name))continue;
32
+ if(update.new===ZERO){cleanup();return error(403,refusal(update.name,'delete'),true);}
33
+ if(force && update.old!==ZERO){cleanup();return error(403,refusal(update.name,'force'),true);}
34
+ }
35
+ for(const update of updates) {
36
+ if(update.old===ZERO || update.new===ZERO || allowedRef(config.policy,repository,update.name))continue;
37
+ let response,payload;
38
+ try{response=await fetch(`${config.base_url}/repos/${repository}/compare/${update.old}...${update.new}`,{headers:{authorization,accept:'application/vnd.github+json','user-agent':'link-assistant-router'},signal:controller.signal,redirect:'manual'});if(response.ok)payload=JSON.parse(Buffer.from(await boundedBytes(response,maxResponseBytes)).toString('utf8'));else await response.body?.cancel();}
39
+ catch{cleanup();return error(403,refusal(update.name,'unknown','upstream request failed'),true);}
40
+ if(!response.ok){cleanup();return error(403,refusal(update.name,'unknown',`upstream answered ${response.status}`),true);}
41
+ if(['behind','diverged'].includes(payload?.status)){cleanup();return error(403,refusal(update.name,'force'),true);}
42
+ if(!['ahead','identical'].includes(payload?.status)){cleanup();return error(403,refusal(update.name,'unknown','upstream gave no comparable status'),true);}
43
+ }
44
+ }
45
+ const base=config.base_url.replace(/^https:\/\/api\.github\.com(?=\/|$)/,'https://github.com');
46
+ const target=new URL(base+'/'+path.slice('/git/'.length)+source.search);
47
+ const headers=new Headers({authorization});for(const name of ['content-type','accept','user-agent','git-protocol'])if(request.headers.has(name))headers.set(name,request.headers.get(name));
48
+ let response;try{response=await fetch(target,{method:request.method,headers,...(['GET','HEAD'].includes(request.method)?{}:{body}),signal:controller.signal,redirect:'manual'});}catch{cleanup();return error(502,'git upstream request failed');}
49
+ const reader=response.body?.getReader();if(!reader){cleanup();return new Response(null,{status:response.status,headers:nativeResponseHeaders(response.headers)});}
50
+ const stream=new ReadableStream({async pull(sink){try{const value=await reader.read();if(value.done){cleanup();sink.close();}else sink.enqueue(value.value);}catch(reason){cleanup();sink.error(reason);}},async cancel(reason){controller.abort();cleanup();await reader.cancel(reason);}});
51
+ return new Response(stream,{status:response.status,headers:nativeResponseHeaders(response.headers)});
52
+ }