@link-assistant/router 0.0.0-stage → 1.25.6

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 (159) hide show
  1. package/README.md +35 -2
  2. package/catalog.json +68422 -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 +61 -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/sensitive-data-sse.mjs +121 -0
  149. package/src/sensitive-data.mjs +254 -0
  150. package/src/server.mjs +552 -0
  151. package/src/storage.mjs +367 -0
  152. package/src/streams.mjs +232 -0
  153. package/src/token-import.mjs +68 -0
  154. package/src/token-reservation.mjs +8 -0
  155. package/src/tokens.mjs +172 -0
  156. package/src/usage.mjs +54 -0
  157. package/src/websocket-relay.mjs +131 -0
  158. package/testing.d.ts +7 -0
  159. package/testing.js +57 -0
@@ -0,0 +1,367 @@
1
+ import { mkdir, open, readFile, rename, unlink, rm, stat } from 'node:fs/promises';
2
+ import { dirname, basename, join } from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { rustLockPath, withAdvisoryFileLock } from './file-lock.mjs';
5
+ import { encodeBinaryTokenRecords, readBinaryTokenRecords } from './doublets.mjs';
6
+
7
+ const queues = new Map();
8
+ export async function serialized(key, operation) {
9
+ const previous = queues.get(key) ?? Promise.resolve();
10
+ let release;
11
+ const held = new Promise(resolve => { release = resolve; });
12
+ const tail = previous.catch(() => {}).then(() => held);
13
+ queues.set(key, tail);
14
+ await previous.catch(() => {});
15
+ try { return await operation(); }
16
+ finally { release(); if (queues.get(key) === tail) queues.delete(key); }
17
+ }
18
+ export async function atomicWrite(path, text) {
19
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
20
+ const temporary = `${path}.${randomUUID()}.tmp`;
21
+ let file;
22
+ try {
23
+ file = await open(temporary, 'wx', 0o600);
24
+ await file.writeFile(text, 'utf8'); await file.sync(); await file.close(); file = null;
25
+ await rename(temporary, path);
26
+ await syncDirectory(dirname(path));
27
+ } finally { await file?.close(); await unlink(temporary).catch(e => { if (e.code !== 'ENOENT') throw e; }); }
28
+ }
29
+ // Separate from Rust's advisory flock file: native writers coordinate via an
30
+ // exclusive directory. Mixed Rust/native writers are deliberately unsupported.
31
+ export async function withNativeFileLock(path, operation, timeout = 30000) {
32
+ const lock = `${path}.native-lock`;
33
+ await mkdir(dirname(path), {recursive:true,mode:0o700});
34
+ const started = Date.now();
35
+ for (;;) {
36
+ try {
37
+ await mkdir(lock,{mode:0o700});
38
+ try { await atomicWrite(`${lock}/owner.json`,JSON.stringify({pid:process.pid})); }
39
+ catch (error) { await rm(lock,{recursive:true,force:true}); throw error; }
40
+ break;
41
+ } catch (error) {
42
+ if (error.code !== 'EEXIST') throw error;
43
+ let dead = false;
44
+ try {
45
+ const owner = JSON.parse(await readFile(`${lock}/owner.json`,'utf8'));
46
+ if (!Number.isSafeInteger(owner.pid) || owner.pid <= 0) throw new Error('Invalid native lock owner');
47
+ try { process.kill(owner.pid,0); } catch (error) { if (error.code === 'ESRCH') dead = true; else if (error.code !== 'EPERM') throw error; }
48
+ } catch (error) {
49
+ if (error.code === 'ENOENT') {
50
+ try { dead = Date.now()-(await stat(lock)).mtimeMs > timeout; } catch (e) { if (e.code !== 'ENOENT') throw e; }
51
+ } else throw error;
52
+ }
53
+ if (dead) {
54
+ const reaper = `${lock}.reap`;
55
+ try {
56
+ await mkdir(reaper,{mode:0o700});
57
+ try {
58
+ let stillDead = false;
59
+ try {
60
+ const owner = JSON.parse(await readFile(`${lock}/owner.json`,'utf8'));
61
+ try { process.kill(owner.pid,0); } catch (e) { stillDead = e.code === 'ESRCH'; }
62
+ } catch (e) { if (e.code === 'ENOENT') { try { stillDead = Date.now()-(await stat(lock)).mtimeMs > timeout; } catch {} } }
63
+ if (stillDead) await rm(lock,{recursive:true,force:true});
64
+ } finally { await rm(reaper,{recursive:true,force:true}); }
65
+ } catch (e) { if (e.code !== 'EEXIST') throw e; }
66
+ continue;
67
+ }
68
+ if (Date.now()-started >= timeout) throw new Error('Timed out waiting for native storage lock');
69
+ await new Promise(resolve => setTimeout(resolve,20));
70
+ }
71
+ }
72
+ try { return await operation(); }
73
+ finally { await rm(lock,{recursive:true,force:true}); }
74
+ }
75
+ export async function readOptional(path, fallback = '') {
76
+ try { return await readFile(path, 'utf8'); } catch (error) { if (error.code === 'ENOENT') return fallback; throw error; }
77
+ }
78
+ const transactionPaths = path => ({rollback:join(dirname(path),`.${basename(path)}.router-rollback`),commit:join(dirname(path),`.${basename(path)}.router-commit`)});
79
+ const removeOptional = async path => { try { await unlink(path); } catch (error) { if (error.code !== 'ENOENT') throw error; } };
80
+ async function syncDirectory(path) {
81
+ if (process.platform === 'win32') return;
82
+ const directory = await open(path,'r'); try { await directory.sync(); } finally { await directory.close(); }
83
+ }
84
+ export async function recoverTransactionalWrite(path) {
85
+ const {rollback,commit} = transactionPaths(path);
86
+ const marker = await readOptional(commit,null);
87
+ if (marker != null) { await removeOptional(rollback); await syncDirectory(dirname(path)); await removeOptional(commit); await syncDirectory(dirname(path)); return; }
88
+ let previous;
89
+ try { previous = await readFile(rollback); } catch (error) { if (error.code === 'ENOENT') return; throw error; }
90
+ if (previous[0] === 0) await removeOptional(path);
91
+ else if (previous[0] === 1) await atomicWrite(path,previous.subarray(1));
92
+ else throw new Error('Invalid transactional rollback document');
93
+ await unlink(rollback); await syncDirectory(dirname(path));
94
+ }
95
+ export async function transactionalWrite(path,contents) {
96
+ await recoverTransactionalWrite(path);
97
+ const {rollback,commit} = transactionPaths(path);
98
+ let previous;
99
+ try { previous = Buffer.concat([Buffer.from([1]),await readFile(path)]); }
100
+ catch (error) { if (error.code !== 'ENOENT') throw error; previous = Buffer.from([0]); }
101
+ await atomicWrite(rollback,previous);
102
+ try { await atomicWrite(path,contents); await atomicWrite(commit,'committed\n'); }
103
+ catch (error) { await removeOptional(commit); await syncDirectory(dirname(path)); await recoverTransactionalWrite(path); throw error; }
104
+ await recoverTransactionalWrite(path).catch(() => {});
105
+ }
106
+
107
+ function quote(text) {
108
+ if (!text.includes('"')) return `"${text}"`;
109
+ if (!text.includes("'")) return `'${text}'`;
110
+ const delimiter = text.startsWith('"') ? "'" : '"';
111
+ const runs = text.match(new RegExp(`${delimiter}+`, 'g')) ?? [];
112
+ const count = Math.max(3, ...runs.map(run => run.length + 1));
113
+ return delimiter.repeat(count) + text + delimiter.repeat(count);
114
+ }
115
+ // Rust lino-objects-codec 0.7 readable format. Strings are literal, not JSON escaped.
116
+ export function encodeLino(value, level = 0) {
117
+ if (typeof value === 'string') {
118
+ if (/[\x00-\x08\x0b-\x1f\x7f]/.test(value)) {
119
+ const escaped = value.replace(/[%\x00-\x08\x0b-\x1f\x7f]/g, c => `%${c.charCodeAt(0).toString(16).padStart(2, '0').toUpperCase()}`);
120
+ return `(escaped ${quote(escaped)})`;
121
+ }
122
+ return quote(value);
123
+ }
124
+ if (value === null || typeof value === 'boolean') return String(value);
125
+ if (typeof value === 'bigint') return value.toString(10);
126
+ if (typeof value === 'number') { if (!Number.isSafeInteger(value)) throw new Error('Storage numbers must be safe integers'); return String(value); }
127
+ const indent = ' '.repeat(level + 1), close = ' '.repeat(level);
128
+ if (Array.isArray(value)) return value.length ? `(\n${value.map(v => indent + encodeLino(v, level + 1)).join('\n')}\n${close})` : '()';
129
+ const entries = Object.entries(value);
130
+ return `(\n${entries.map(([key, v]) => `${indent}${key} ${encodeLino(v, level + 1)}`).join('\n')}${entries.length ? '\n' : ''}${close})`;
131
+ }
132
+ export function decodeLino(text, {integer,scalar:unquotedScalar,escaped,object:makeObject,whitespace} = {}) {
133
+ let i = 0;
134
+ const firstKeys=new WeakMap();
135
+ const space=character=>whitespace?whitespace(character):/\s/.test(character??'');
136
+ const skip = () => { while (i<text.length && (whitespace ? text[i]!=='\n' && space(text[i]) : text[i] === ' ' || text[i] === '\t' || text[i] === '\r')) i++; };
137
+ function scalar(raw, quoted = false) {
138
+ if (quoted) return raw;
139
+ if (unquotedScalar) return unquotedScalar(raw);
140
+ if (raw === 'null') return null;
141
+ if (raw === 'true' || raw === 'false') return raw === 'true';
142
+ if (integer && /^[+-]?\d+$/.test(raw)) return integer(raw);
143
+ if (/^-?\d+$/.test(raw)) { const n = Number(raw); if (!Number.isSafeInteger(n)) throw new Error('Unsafe storage integer'); return n; }
144
+ return raw;
145
+ }
146
+ function value() {
147
+ skip();
148
+ if (text[i] === '(') {
149
+ i++; skip();
150
+ const rows = [], quotedRows=[],keyRows=[]; let row = [], quotedRow=[],keyRow=[], multiline = false;
151
+ while (i < text.length && text[i] !== ')') {
152
+ if (text[i] === '\n') { multiline = true; if (row.length) {rows.push(row);quotedRows.push(quotedRow);keyRows.push(keyRow);} row = [];quotedRow=[];keyRow=[]; i++; skip(); continue; }
153
+ const start=i,quoted=['"',"'",'`'].includes(text[i]);quotedRow.push(quoted);
154
+ const child=value();row.push(child);
155
+ keyRow.push(quoted || text[start]==='(' ? typeof child==='string'?child:null : text.slice(start,i));
156
+ skip();
157
+ }
158
+ if (text[i++] !== ')') throw new Error('Unclosed Links Notation container');
159
+ if (row.length) {rows.push(row);quotedRows.push(quotedRow);keyRows.push(keyRow);}
160
+ if (rows.length === 1 && rows[0][0] === 'escaped' && rows[0].length === 2 && (!escaped || !quotedRows[0][0] && quotedRows[0][1])) {
161
+ if(escaped) {
162
+ const source=Buffer.from(rows[0][1],'utf8'),bytes=[];
163
+ for(let offset=0;offset<source.length;offset++) {
164
+ if(source[offset]!==37) {bytes.push(source[offset]);continue;}
165
+ const hex=source.subarray(offset+1,offset+3).toString('ascii');
166
+ if(hex.length!==2 || !/^(?:[0-9A-Fa-f]{2}|\+[0-9A-Fa-f])$/.test(hex))throw new Error('Invalid escaped UTF8 byte');
167
+ bytes.push(Number.parseInt(hex,16));offset+=2;
168
+ }
169
+ return escaped(Buffer.from(bytes));
170
+ }
171
+ return rows[0][1].replace(/(?:%[0-9A-Fa-f]{2})+/g, run => Buffer.from(run.replaceAll('%', ''), 'hex').toString('utf8'));
172
+ }
173
+ if(escaped && rows.length===1 && rows[0][0]==='base64' && rows[0].length===2 && !quotedRows[0][0] && quotedRows[0][1]) {
174
+ const payload=rows[0][1];
175
+ if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(payload))throw new Error('Invalid base64 string');
176
+ const bytes=Buffer.from(payload,'base64');
177
+ if(bytes.toString('base64')!==payload)throw new Error('Invalid base64 trailing bits');
178
+ return escaped(bytes);
179
+ }
180
+ if (rows.length === 1 && rows[0][0] === 'o:' && (!makeObject || !quotedRows[0][0])) {
181
+ const object = Object.create(null);
182
+ const collected=[];
183
+ for (const pair of rows[0].slice(1)) {
184
+ const entries = Array.isArray(pair) ? [pair] : Object.entries(pair);
185
+ if (entries.length !== 1 || entries[0].length !== 2) throw new Error('Invalid Lino object pair');
186
+ const key=makeObject && Array.isArray(pair)?firstKeys.get(pair):entries[0][0];
187
+ if(makeObject && typeof key!=='string')throw new Error('Invalid Lino object key');
188
+ collected.push([key,entries[0][1]]);object[entries[0][0]] = entries[0][1];
189
+ }
190
+ if(makeObject)return makeObject(collected);
191
+ return object;
192
+ }
193
+ if(makeObject && multiline && rows.every((row,index)=>row.length===2 && typeof keyRows[index][0]==='string'))return makeObject(rows.map((row,index)=>[keyRows[index][0],row[1]]));
194
+ if (multiline && rows.every(r => r.length === 2 && typeof r[0] === 'string')) {
195
+ const object = Object.create(null);
196
+ for (const [key, v] of rows) { if (Object.hasOwn(object, key)) throw new Error('Duplicate Lino key'); object[key] = v; }
197
+ return object;
198
+ }
199
+ const list=rows.flat();
200
+ if(rows.length===1)firstKeys.set(list,keyRows[0][0]);
201
+ return list;
202
+ }
203
+ if (text[i] === '"' || text[i] === "'" || text[i] === '`') {
204
+ const delimiter = text[i]; let count = 0;
205
+ while (text[i + count] === delimiter) count++;
206
+ if (count === 2) { i += 2; return ''; }
207
+ i += count; let raw = '';
208
+ while (i < text.length) {
209
+ if (text[i] !== delimiter) { raw += text[i++]; continue; }
210
+ let run = 0; while (text[i+run] === delimiter) run++;
211
+ if (count === 1) {
212
+ if (run >= 2) { raw += delimiter; i += 2; continue; }
213
+ i++; return scalar(raw,true);
214
+ }
215
+ if (run >= count) { raw += delimiter.repeat(run-count); i += run; return scalar(raw,true); }
216
+ raw += delimiter.repeat(run); i += run;
217
+ }
218
+ throw new Error('Unclosed Lino string');
219
+ }
220
+ const start = i;
221
+ while (i < text.length && !space(text[i]) && !/[()]/.test(text[i])) i++;
222
+ if (i === start) throw new Error('Invalid Links Notation input');
223
+ return scalar(text.slice(start, i));
224
+ }
225
+ while (i < text.length && space(text[i])) i++;
226
+ const result = value();
227
+ while (i < text.length && space(text[i])) i++;
228
+ if (i !== text.length) throw new Error('Trailing Links Notation data');
229
+ return result;
230
+ }
231
+
232
+ const strings = ['max_requests', 'used_requests', 'max_tokens', 'used_tokens', 'reserved_tokens', 'rate_limit_per_minute', 'rate_window_started_at', 'rate_window_requests', 'sliding_window_seconds', 'run_lease_expires_at'];
233
+ export function encodeTokenRecords(records) {
234
+ const values = records.slice().sort((a,b) => a.id.localeCompare(b.id)).map(record => {
235
+ const value = { ...record };
236
+ for (const field of strings) if (value[field] != null) value[field] = String(value[field]);
237
+ value.github_repos = (value.github_repos ?? []).join(',');
238
+ value.model_policy = JSON.stringify(value.model_policy ?? {});
239
+ return { type: 'TokenRecord', subtype: record.id, value };
240
+ });
241
+ return encodeLino({ type: 'RouterState', subtype: 'TokenStore', value: values });
242
+ }
243
+ export function decodeTokenRecords(text) {
244
+ if (!text.trim()) return [];
245
+ const root = decodeLino(text);
246
+ if (root.type !== 'RouterState' || root.subtype !== 'TokenStore' || !Array.isArray(root.value)) throw new Error('Unsupported token storage format');
247
+ const ids = new Set();
248
+ return root.value.map(row => {
249
+ if (row.type !== 'TokenRecord' || row.subtype !== row.value?.id || ids.has(row.subtype)) throw new Error('Invalid/duplicate token record');
250
+ ids.add(row.subtype);
251
+ const record = { ...row.value };
252
+ for (const field of strings) if (record[field] != null) {
253
+ if (!/^-?\d+$/.test(String(record[field]))) throw new Error(`Invalid token field ${field}`);
254
+ record[field] = Number(record[field]);
255
+ if (!Number.isSafeInteger(record[field]) || (field !== 'rate_window_started_at' && record[field] < 0)) throw new Error(`Unsafe token field ${field}`);
256
+ }
257
+ if (typeof record.id !== 'string' || typeof record.revoked !== 'boolean' || !Number.isSafeInteger(record.expires_at) || !Number.isSafeInteger(record.issued_at)) throw new Error('Invalid token record');
258
+ record.github_repos = record.github_repos ? record.github_repos.split(',') : [];
259
+ record.model_policy = JSON.parse(record.model_policy ?? '{}');
260
+ return record;
261
+ });
262
+ }
263
+ export class MemoryTokenStore {
264
+ constructor(records = []) { this.records = new Map(records.map(r => [r.id, structuredClone(r)])); this.key = {}; }
265
+ async transaction(operation) {
266
+ return serialized(this.key, async () => {
267
+ const records = new Map([...this.records].map(([id,r]) => [id, structuredClone(r)]));
268
+ const result = await operation(records); this.records = records; return structuredClone(result);
269
+ });
270
+ }
271
+ async list() { return structuredClone([...this.records.values()]); }
272
+ async get(id) { return structuredClone(this.records.get(id) ?? null); }
273
+ async put(record) { return this.transaction(records => records.set(record.id, structuredClone(record)) && record); }
274
+ async delete(id) { return this.transaction(records => records.delete(id)); }
275
+ }
276
+ export class TextTokenStore extends MemoryTokenStore {
277
+ constructor(path) { super(); this.path = path; }
278
+ // Refresh under the native process lock before every mutation; read access
279
+ // sees either complete projection because replacement is atomic.
280
+ async transaction(operation) {
281
+ return serialized(this.path, () => withAdvisoryFileLock(rustLockPath(this.path), async () => {
282
+ await recoverTransactionalWrite(this.path);
283
+ const records = new Map(decodeTokenRecords(await readOptional(this.path)).map(r => [r.id, r]));
284
+ const result = await operation(records);
285
+ await transactionalWrite(this.path, encodeTokenRecords([...records.values()]));
286
+ this.records = records; return structuredClone(result);
287
+ }));
288
+ }
289
+ async list() { return withAdvisoryFileLock(rustLockPath(this.path),async () => { await recoverTransactionalWrite(this.path); return decodeTokenRecords(await readOptional(this.path)); }); }
290
+ async get(id) { return (await this.list()).find(r => r.id === id) ?? null; }
291
+ }
292
+ export class BinaryTokenStore extends MemoryTokenStore {
293
+ constructor(path) { super(); this.path = path; }
294
+ async transaction(operation) {
295
+ return serialized(this.path,() => withAdvisoryFileLock(rustLockPath(this.path),async () => {
296
+ const records = new Map((await readBinaryTokenRecords(this.path)).map(record => [record.id,record]));
297
+ const result = await operation(records);
298
+ await atomicWrite(this.path,encodeBinaryTokenRecords([...records.values()]));
299
+ this.records = records; return structuredClone(result);
300
+ }));
301
+ }
302
+ async list() { return withAdvisoryFileLock(rustLockPath(this.path),() => readBinaryTokenRecords(this.path),{shared:true}); }
303
+ async get(id) { return (await this.list()).find(record => record.id === id) ?? null; }
304
+ }
305
+ export function mergeSaferRecord(current,other) {
306
+ current.revoked ||= other.revoked;
307
+ for (const field of ['used_requests','used_tokens','reserved_tokens']) current[field] = Math.max(current[field] ?? 0,other[field] ?? 0);
308
+ if ((other.rate_window_started_at ?? 0) > (current.rate_window_started_at ?? 0)) {
309
+ current.rate_window_started_at = other.rate_window_started_at; current.rate_window_requests = other.rate_window_requests;
310
+ } else if (other.rate_window_started_at === current.rate_window_started_at) current.rate_window_requests = Math.max(current.rate_window_requests ?? 0,other.rate_window_requests ?? 0);
311
+ return current;
312
+ }
313
+ export class DualTokenStore extends MemoryTokenStore {
314
+ constructor(dataDir) {
315
+ super(); this.path = join(dataDir,'tokens.transaction.lock'); this.journal = join(dataDir,'tokens.transaction.json');
316
+ this.text = new TextTokenStore(join(dataDir,'tokens.lino')); this.binary = new BinaryTokenStore(join(dataDir,'tokens.bin'));
317
+ }
318
+ async install(records) {
319
+ await this.text.transaction(current => { current.clear(); for (const record of records) current.set(record.id,record); });
320
+ const projection = await this.binary.list();
321
+ const canonical = rows => encodeTokenRecords(rows);
322
+ if (canonical(projection) !== canonical(records)) await this.binary.transaction(current => { current.clear(); for (const record of records) current.set(record.id,record); });
323
+ await removeOptional(this.journal); await syncDirectory(dirname(this.journal));
324
+ }
325
+ async recover() {
326
+ const source = await readOptional(this.journal,null);
327
+ if (source != null) {
328
+ const records = source.trimStart().startsWith('[') ? JSON.parse(source) : decodeLino(source);
329
+ if (!Array.isArray(records)) throw new Error('Invalid token transaction journal');
330
+ await this.install(records);
331
+ }
332
+ }
333
+ async mergedRecords() {
334
+ const records = new Map((await this.text.list()).map(record => [record.id,record]));
335
+ for (const record of await this.binary.list()) {
336
+ if (records.has(record.id)) mergeSaferRecord(records.get(record.id),record); else records.set(record.id,record);
337
+ }
338
+ return records;
339
+ }
340
+ async transaction(operation) {
341
+ return serialized(this.path,() => withAdvisoryFileLock(this.path,async () => {
342
+ await this.recover();
343
+ const records = await this.mergedRecords(), result = await operation(records);
344
+ const sorted = [...records.values()].sort((left,right) => Buffer.compare(Buffer.from(left.id),Buffer.from(right.id)));
345
+ await atomicWrite(this.journal,encodeLino(sorted)); await this.install(sorted);
346
+ this.records = records; return structuredClone(result);
347
+ }));
348
+ }
349
+ async list() {
350
+ const read = async () => {
351
+ const records = await this.text.list();
352
+ return records.length ? records : [...(await this.mergedRecords()).values()];
353
+ };
354
+ const result = await withAdvisoryFileLock(this.path,async () => (await readOptional(this.journal,null)) != null ? null : read(),{shared:true});
355
+ if (result != null) return result;
356
+ return withAdvisoryFileLock(this.path,async () => { await this.recover(); return read(); });
357
+ }
358
+ async get(id) { return (await this.list()).find(record => record.id === id) ?? null; }
359
+ }
360
+ export function createTokenStore({ storage_policy = 'memory', data_dir = '.', storage } = {}) {
361
+ if (storage) return storage;
362
+ if (['memory','mem','none'].includes(storage_policy)) return new MemoryTokenStore();
363
+ if (['text','txt','lino'].includes(storage_policy)) return new TextTokenStore(`${data_dir}/tokens.lino`);
364
+ if (['binary','bin','link-cli','linkcli','clink'].includes(storage_policy)) return new BinaryTokenStore(`${data_dir}/tokens.bin`);
365
+ if (['both','dual'].includes(storage_policy)) return new DualTokenStore(data_dir);
366
+ throw Object.assign(new Error(`Unknown token storage policy '${storage_policy}'`),{code:'invalid_config'});
367
+ }
@@ -0,0 +1,232 @@
1
+ import { canonicalResponse, normalizeUsage, ProtocolError } from './protocols.mjs';
2
+ const encoder = new TextEncoder();
3
+ const frame = (data, event) => `${event ? `event: ${event}\n` : ''}data: ${typeof data === 'string' ? data : JSON.stringify(data)}\n\n`;
4
+
5
+ /** SSE decoder handles UTF-8 boundaries, CRLF, comments and multiline data. */
6
+ export async function* decodeSSE(body, { maxFrameBytes = 1024 * 1024 } = {}) {
7
+ const reader = body.getReader(), decoder = new TextDecoder();
8
+ let buffer = '', data = [], event = '';
9
+ const consume = line => {
10
+ if (encoder.encode(line).byteLength > maxFrameBytes) throw new ProtocolError('Upstream SSE line exceeds limit', 502);
11
+ if (!line) { const value = data.length ? { event, data: data.join('\n') } : null; data = []; event = ''; return value; }
12
+ if (line[0] === ':') return null;
13
+ const colon = line.indexOf(':'), key = colon < 0 ? line : line.slice(0, colon);
14
+ let value = colon < 0 ? '' : line.slice(colon + 1); if (value[0] === ' ') value = value.slice(1);
15
+ if (key === 'data') data.push(value); else if (key === 'event') event = value;
16
+ if (data.reduce((n, value) => n + encoder.encode(value).byteLength + 1, 0) > maxFrameBytes) throw new ProtocolError('Upstream SSE frame exceeds limit', 502);
17
+ return null;
18
+ };
19
+ try {
20
+ while (true) {
21
+ const { value, done } = await reader.read(); buffer += decoder.decode(value, { stream: !done });
22
+ let match;
23
+ while ((match = /\r\n|\n|\r/.exec(buffer))) {
24
+ if (match[0] === '\r' && match.index === buffer.length - 1 && !done) break;
25
+ const line = buffer.slice(0, match.index); buffer = buffer.slice(match.index + match[0].length);
26
+ const parsed = consume(line); if (parsed) yield parsed;
27
+ }
28
+ if (encoder.encode(buffer).byteLength > maxFrameBytes) throw new ProtocolError('Upstream SSE line exceeds limit', 502);
29
+ if (done) { if (buffer) consume(buffer); const parsed = consume(''); if (parsed) yield parsed; return; }
30
+ }
31
+ } finally { await reader.cancel().catch(() => {}); reader.releaseLock(); }
32
+ }
33
+
34
+ async function* normalizedEvents(body, protocol) {
35
+ const tools = new Map(); let ended = false, finish = 'stop', usage = normalizeUsage(), id, started = false;
36
+ for await (const f of decodeSSE(body)) {
37
+ if (f.data === '[DONE]') { ended = true; break; }
38
+ let p; try { p = JSON.parse(f.data); } catch { throw new ProtocolError('Malformed upstream SSE JSON', 502); }
39
+ if (p.error || p.type === 'error' || ['response.failed', 'response.incomplete'].includes(p.type) && p.response?.error) throw new ProtocolError(p.error?.message ?? p.response?.error?.message ?? 'Upstream stream failed', 502);
40
+ const type = p.type ?? f.event;
41
+ if (protocol === 'chat') {
42
+ if (!started) { id = p.id; started = true; yield { type: 'start', id }; }
43
+ if (p.usage) { usage = normalizeUsage(p.usage); yield { type: 'usage', usage }; }
44
+ if (p.choices?.length > 1 || p.choices?.[0]?.index > 0) throw new ProtocolError('Cannot translate multiple streamed choices', 502);
45
+ const c = p.choices?.[0]; if (!c) continue;
46
+ if (c.delta?.content) yield { type: 'text', text: c.delta.content };
47
+ if (c.delta?.refusal) throw new ProtocolError('Cannot translate streamed refusal', 502);
48
+ for (const t of c.delta?.tool_calls ?? []) {
49
+ const index = t.index ?? 0;
50
+ if (!tools.has(index)) { if (!t.id || !t.function?.name) throw new ProtocolError('Cannot translate fragmented tool identity', 502); const tool = { id: t.id, name: t.function.name, index }; tools.set(index, tool); yield { type: 'tool', ...tool }; }
51
+ else if (t.id || t.function?.name) throw new ProtocolError('Cannot translate fragmented tool identity', 502);
52
+ if (t.function?.arguments) yield { type: 'arguments', index, text: t.function.arguments };
53
+ }
54
+ if (c.finish_reason) { if (!['stop', 'length', 'tool_calls','content_filter'].includes(c.finish_reason)) throw new ProtocolError(`Cannot translate finish reason ${c.finish_reason}`, 502); finish = c.finish_reason; }
55
+ } else if (protocol === 'gemini') {
56
+ const value = p.response ?? p, candidate = value.candidates?.[0];
57
+ if (!started) {started = true;id = value.responseId;yield {type:'start',id};}
58
+ if (value.candidates?.length > 1) throw new ProtocolError('Cannot translate multiple Gemini candidates',502);
59
+ for (const part of candidate?.content?.parts ?? []) {
60
+ if (part.text !== undefined) {yield {type:'text',text:part.text};}
61
+ else if (part.functionCall) {const call=part.functionCall,index=tools.size,tool={id:call.id ?? `call_${index}`,name:call.name,index};tools.set(index,tool);yield {type:'tool',...tool};yield {type:'arguments',index,text:JSON.stringify(call.args ?? {})};}
62
+ else throw new ProtocolError('Gemini output part cannot be represented',502);
63
+ }
64
+ if(value.usageMetadata){usage=normalizeUsage(value.usageMetadata,'gemini');yield {type:'usage',usage};}
65
+ const reason=candidate?.finishReason ?? value.promptFeedback?.blockReason;if(reason){finish=reason === 'MAX_TOKENS'?'length':reason==='STOP'?tools.size?'tool_calls':'stop':'content_filter';ended=true;}
66
+ } else if (protocol === 'anthropic') {
67
+ if (type === 'message_start') { started = true; id = p.message.id; usage = normalizeUsage(p.message.usage, protocol); yield { type: 'start', id }; yield { type: 'usage', usage }; }
68
+ else if (type === 'content_block_start') {
69
+ const b = p.content_block;
70
+ if (b.type === 'tool_use') { const tool = { id: b.id, name: b.name, index: p.index }; tools.set(p.index, tool); yield { type: 'tool', ...tool }; if (b.input && Object.keys(b.input).length) yield { type: 'arguments', index: p.index, text: JSON.stringify(b.input) }; }
71
+ else if (b.type === 'text') { if (b.text) yield { type: 'text', text: b.text }; }
72
+ else throw new ProtocolError(`Cannot translate streamed block ${b.type}`, 502);
73
+ } else if (type === 'content_block_delta') {
74
+ if (p.delta.type === 'text_delta') yield { type: 'text', text: p.delta.text };
75
+ else if (p.delta.type === 'input_json_delta') yield { type: 'arguments', index: p.index, text: p.delta.partial_json };
76
+ else throw new ProtocolError(`Cannot translate streamed delta ${p.delta.type}`, 502);
77
+ } else if (type === 'message_delta') {
78
+ if (p.delta.stop_reason) { finish = { end_turn: 'stop', stop_sequence: 'stop', tool_use: 'tool_calls', max_tokens: 'length' }[p.delta.stop_reason]; if (!finish) throw new ProtocolError(`Cannot translate stop reason ${p.delta.stop_reason}`, 502); }
79
+ if (p.usage) { usage = { ...usage, output: p.usage.output_tokens ?? usage.output }; usage.total = usage.input + usage.output; yield { type: 'usage', usage }; }
80
+ } else if (type === 'message_stop') { ended = true; break; }
81
+ } else if (protocol === 'responses') {
82
+ if (type === 'response.created') { started = true; id = p.response.id; yield { type: 'start', id }; }
83
+ else if (type === 'response.output_text.delta') yield { type: 'text', text: p.delta };
84
+ else if (type === 'response.output_item.added') {
85
+ if (p.item.type === 'function_call') { const tool = { id: p.item.call_id, name: p.item.name, index: p.output_index }; tools.set(p.output_index, tool); yield { type: 'tool', ...tool }; }
86
+ else if (p.item.type !== 'message') throw new ProtocolError(`Cannot translate streamed item ${p.item.type}`, 502);
87
+ } else if (type === 'response.function_call_arguments.delta') yield { type: 'arguments', index: p.output_index, text: p.delta };
88
+ else if (['response.completed', 'response.incomplete'].includes(type)) { usage = normalizeUsage(p.response.usage); finish = type === 'response.incomplete' ? p.response.incomplete_details?.reason==='content_filter'?'content_filter':'length' : tools.size ? 'tool_calls' : 'stop'; yield { type: 'usage', usage }; ended = true; break; }
89
+ else if (type === 'response.refusal.delta') throw new ProtocolError('Cannot translate streamed refusal', 502);
90
+ }
91
+ }
92
+ if (!ended) throw new ProtocolError('Upstream stream ended before its terminal event', 502);
93
+ if (!started) yield { type: 'start', id };
94
+ yield { type: 'finish', finish, usage };
95
+ }
96
+
97
+ /** Incremental conversion: errors are in-band and never fabricated success. */
98
+ export function translateStream(body, source, target, model, { clock = Date.now, onStart, onComplete, onError, onCancel, maxStateBytes = 32 * 1024 * 1024 } = {}) {
99
+ const events = normalizedEvents(body, source)[Symbol.asyncIterator]();
100
+ const state = { id: undefined, text: '', tools: [], usage: normalizeUsage(), finish: 'stop' };
101
+ const toolMap = new Map(), openToolBlocks = new Set(); let stateBytes = 0, begun = false, finished = false, sequence = 0, activeBlock, nextBlock = 0, messageItem, outputIndex = 0;
102
+ const now = clock();
103
+ const responses = (type, payload) => frame({ type, sequence_number: sequence++, ...payload }, type);
104
+ const chat = (delta, finish_reason = null, usage) => frame({ id: state.id, object: 'chat.completion.chunk', created: Math.floor(now / 1000), model, choices: usage ? [] : [{ index: 0, delta, finish_reason }], ...(usage ? { usage } : {}) });
105
+ const closeBlock = () => { if (activeBlock === undefined) return ''; const result = frame({ type: 'content_block_stop', index: activeBlock }, 'content_block_stop'); activeBlock = undefined; return result; };
106
+ const render = e => {
107
+ let out = '';
108
+ stateBytes += encoder.encode(e.text ?? '').byteLength + (e.type === 'tool' ? 1024 : 0);
109
+ if (stateBytes > maxStateBytes) throw new ProtocolError('Upstream stream exceeds translation memory limit', 502);
110
+ if (!begun) {
111
+ begun = true; state.id = e.id ?? `native_${Math.floor(now / 1000)}`;
112
+ if (target === 'chat') out += chat({ role: 'assistant', content: '' });
113
+ else if (target === 'anthropic') out += frame({ type: 'message_start', message: { id: state.id, type: 'message', role: 'assistant', model, content: [], stop_reason: null, stop_sequence: null, usage: { input_tokens: 0, output_tokens: 0 } } }, 'message_start');
114
+ else if (target !== 'gemini') { const response = { ...canonicalResponse(state, target, model, now), status: 'in_progress', usage: null }; out += responses('response.created', { response }); out += responses('response.in_progress', { response }); }
115
+ }
116
+ if (e.type === 'text') {
117
+ state.text += e.text;
118
+ if (target === 'chat') out += chat({ content: e.text });
119
+ else if (target === 'gemini') out += frame({candidates:[{index:0,content:{role:'model',parts:[{text:e.text}]}}],modelVersion:model});
120
+ else if (target === 'anthropic') {
121
+ if (activeBlock === undefined) { activeBlock = nextBlock++; out += frame({ type: 'content_block_start', index: activeBlock, content_block: { type: 'text', text: '' } }, 'content_block_start'); }
122
+ out += frame({ type: 'content_block_delta', index: activeBlock, delta: { type: 'text_delta', text: e.text } }, 'content_block_delta');
123
+ } else {
124
+ if (!messageItem) { messageItem = { id: `msg_${state.id}`, type: 'message', role: 'assistant', status: 'in_progress', content: [] }; messageItem.output_index = outputIndex++; out += responses('response.output_item.added', { output_index: messageItem.output_index, item: { ...messageItem, output_index: undefined } }); out += responses('response.content_part.added', { item_id: messageItem.id, output_index: messageItem.output_index, content_index: 0, part: { type: 'output_text', text: '', annotations: [] } }); }
125
+ out += responses('response.output_text.delta', { item_id: messageItem.id, output_index: messageItem.output_index, content_index: 0, delta: e.text });
126
+ }
127
+ } else if (e.type === 'tool') {
128
+ const index = state.tools.length, tool = { id: e.id ?? `call_${index}`, type: 'function', function: { name: e.name ?? '', arguments: '' } }; state.tools.push(tool);
129
+ const record = { index, tool, block: undefined, output_index: outputIndex++ }; toolMap.set(e.index, record);
130
+ if (target === 'chat') out += chat({ tool_calls: [{ index, ...tool }] });
131
+ else if (target === 'anthropic') { out += closeBlock(); record.block = nextBlock++; openToolBlocks.add(record.block); out += frame({ type: 'content_block_start', index: record.block, content_block: { type: 'tool_use', id: tool.id, name: tool.function.name, input: {} } }, 'content_block_start'); }
132
+ else if (target !== 'gemini') out += responses('response.output_item.added', { output_index: record.output_index, item: { id: `fc_${tool.id}`, type: 'function_call', status: 'in_progress', call_id: tool.id, name: tool.function.name, arguments: '' } });
133
+ } else if (e.type === 'arguments') {
134
+ const r = toolMap.get(e.index); if (!r) throw new ProtocolError('Tool arguments arrived without a tool call', 502);
135
+ r.tool.function.arguments += e.text;
136
+ if (target === 'chat') out += chat({ tool_calls: [{ index: r.index, function: { arguments: e.text } }] });
137
+ else if (target === 'anthropic') out += frame({ type: 'content_block_delta', index: r.block, delta: { type: 'input_json_delta', partial_json: e.text } }, 'content_block_delta');
138
+ else if (target !== 'gemini') out += responses('response.function_call_arguments.delta', { item_id: `fc_${r.tool.id}`, output_index: r.output_index, delta: e.text });
139
+ } else if (e.type === 'usage') state.usage = e.usage;
140
+ else if (e.type === 'finish') {
141
+ state.finish = e.finish; state.usage = e.usage;
142
+ for (const tool of state.tools) { if (!tool.function.arguments) tool.function.arguments = '{}'; try { JSON.parse(tool.function.arguments); } catch { throw new ProtocolError('Upstream streamed invalid tool arguments', 502); } }
143
+ if (target === 'chat') { out += chat({}, state.finish); const u = canonicalResponse(state, 'chat', model, now).usage; out += chat({}, null, u); out += frame('[DONE]'); }
144
+ else if (target === 'gemini') out += frame(canonicalResponse({...state,text:''},'gemini',model,now));
145
+ else if (target === 'anthropic') { out += closeBlock(); for (const index of openToolBlocks) out += frame({ type: 'content_block_stop', index }, 'content_block_stop'); const message = canonicalResponse(state, 'anthropic', model, now); out += frame({ type: 'message_delta', delta: { stop_reason: message.stop_reason, stop_sequence: message.stop_sequence }, usage: message.usage }, 'message_delta'); out += frame({ type: 'message_stop' }, 'message_stop'); }
146
+ else {
147
+ if (messageItem) { out += responses('response.output_text.done', { item_id: messageItem.id, output_index: messageItem.output_index, content_index: 0, text: state.text }); const item = { id: messageItem.id, type: 'message', role: 'assistant', status: ['length','content_filter'].includes(state.finish)?'incomplete':'completed', content: [{ type: 'output_text', text: state.text, annotations: [] }] }; out += responses('response.content_part.done', { item_id: messageItem.id, output_index: messageItem.output_index, content_index: 0, part: item.content[0] }); out += responses('response.output_item.done', { output_index: messageItem.output_index, item }); }
148
+ for (const r of toolMap.values()) { out += responses('response.function_call_arguments.done', { item_id: `fc_${r.tool.id}`, output_index: r.output_index, arguments: r.tool.function.arguments }); out += responses('response.output_item.done', { output_index: r.output_index, item: { id: `fc_${r.tool.id}`, type: 'function_call', status: ['length','content_filter'].includes(state.finish)?'incomplete':'completed', call_id: r.tool.id, name: r.tool.function.name, arguments: r.tool.function.arguments } }); }
149
+ const response = canonicalResponse(state, target, model, now),type = response.status === 'incomplete' ? 'response.incomplete' : 'response.completed';
150
+ const order = new Map([...toolMap.values()].map(r => [`fc_${r.tool.id}`, r.output_index])); if (messageItem) order.set(messageItem.id, messageItem.output_index);
151
+ response.output.sort((a, b) => order.get(a.id) - order.get(b.id));
152
+ state.response = response;
153
+ out += responses(type, { response });
154
+ }
155
+ finished = true;
156
+ }
157
+ return out;
158
+ };
159
+ return new ReadableStream({
160
+ async pull(controller) {
161
+ try {
162
+ while (!finished) {
163
+ const { value, done } = await events.next(); if (done) break;
164
+ const wasBegun = begun, output = render(value);
165
+ if (!wasBegun && begun) await onStart?.({ ...canonicalResponse(state, target, model, now), status: 'in_progress', usage: null });
166
+ if (finished) await onComplete?.(state);
167
+ if (output) { controller.enqueue(encoder.encode(output)); if (finished) controller.close(); return; }
168
+ }
169
+ if (!finished) controller.close();
170
+ } catch (error) {
171
+ await onError?.(error, state);
172
+ const payload = { error: { type: 'upstream_stream_error', message: 'Upstream stream failed or ended prematurely' } };
173
+ controller.enqueue(encoder.encode(target === 'responses' ? responses('error', payload) : frame(target === 'anthropic' ? { type: 'error', ...payload } : payload, target === 'anthropic' ? 'error' : undefined)));
174
+ controller.close(); finished = true; await events.return?.();
175
+ }
176
+ },
177
+ async cancel() { finished = true; await onCancel?.(); await events.return?.(); },
178
+ });
179
+ }
180
+
181
+ /** Preserve native event payloads while checking terminal events and usage. */
182
+ export function monitorNativeStream(body, protocol, { model, onStart, onComplete, onError, onCancel } = {}) {
183
+ const events = decodeSSE(body)[Symbol.asyncIterator](); let terminal = false, usage = normalizeUsage(), anthropicUsage = {}, response, started = false;
184
+ return new ReadableStream({
185
+ async pull(controller) {
186
+ try {
187
+ const { value: f, done } = await events.next();
188
+ if (done) {
189
+ if (!terminal) throw new ProtocolError('Upstream stream ended before its terminal event', 502);
190
+ await onComplete?.({ usage, response }); controller.close(); return;
191
+ }
192
+ let frameData = f.data;
193
+ if (f.data === '[DONE]') terminal = true;
194
+ else {
195
+ let p; try { p = JSON.parse(f.data); } catch { throw new ProtocolError('Malformed upstream SSE JSON', 502); }
196
+ if (protocol === 'gemini') p = p.response ?? p;
197
+ if (p.error || p.type === 'error' || p.type === 'response.failed') throw new ProtocolError('Upstream stream reported failure', 502);
198
+ if (model) {
199
+ if (p.model) p.model = model;
200
+ if (p.message?.model) p.message.model = model;
201
+ if (p.response?.model) p.response.model = model;
202
+ if (p.modelVersion) p.modelVersion = model;
203
+ frameData = JSON.stringify(p);
204
+ }
205
+ if (p.usage) {
206
+ if (protocol === 'anthropic') { anthropicUsage = { ...anthropicUsage, ...p.usage }; usage = normalizeUsage(anthropicUsage, protocol); }
207
+ else usage = normalizeUsage(p.usage, protocol);
208
+ }
209
+ if (p.message?.usage) { anthropicUsage = p.message.usage; usage = normalizeUsage(p.message.usage, protocol); }
210
+ if (p.response?.usage) usage = normalizeUsage(p.response.usage, protocol);
211
+ if (p.usageMetadata) usage = normalizeUsage(p.usageMetadata,'gemini');
212
+ if (p.response?.id) {
213
+ response = p.response;
214
+ if (!started) { started = true; await onStart?.({ ...response, status: 'in_progress', usage: null }); }
215
+ }
216
+ if (p.type === 'message_stop' || ['response.completed', 'response.incomplete'].includes(p.type)) terminal = true;
217
+ if (protocol === 'gemini' && (p.candidates?.some(candidate => candidate.finishReason) || p.promptFeedback?.blockReason)) {
218
+ terminal = true;frameData = JSON.stringify(p);
219
+ }
220
+ }
221
+ if (terminal) await onComplete?.({ usage, response });
222
+ controller.enqueue(encoder.encode(frame(frameData, f.event)));
223
+ if (terminal) { controller.close(); await events.return?.(); }
224
+ } catch (error) {
225
+ await onError?.(error, { usage, response });
226
+ const payload = { error: { type: 'upstream_stream_error', message: 'Upstream stream failed or ended prematurely' } };
227
+ controller.enqueue(encoder.encode(frame(protocol === 'anthropic' ? { type: 'error', ...payload } : payload, protocol === 'chat' ? undefined : 'error'))); controller.close(); await events.return?.();
228
+ }
229
+ },
230
+ async cancel() { await onCancel?.(); await events.return?.(); },
231
+ });
232
+ }