nanobridge 0.2.3 → 2.0.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 (143) hide show
  1. package/README.md +86 -230
  2. package/bin/nanobridge.js +1 -1
  3. package/dist/api/openai.d.ts +135 -0
  4. package/dist/api/openai.js +210 -0
  5. package/dist/api/openai.js.map +1 -0
  6. package/dist/benchmark/runner.d.ts +27 -0
  7. package/dist/benchmark/runner.js +37 -0
  8. package/dist/benchmark/runner.js.map +1 -0
  9. package/dist/benchmark/stats.d.ts +10 -0
  10. package/dist/benchmark/stats.js +33 -0
  11. package/dist/benchmark/stats.js.map +1 -0
  12. package/dist/bin/nanobridge.d.ts +2 -0
  13. package/dist/bin/nanobridge.js +4 -0
  14. package/dist/bin/nanobridge.js.map +1 -0
  15. package/dist/chat/commands.d.ts +9 -0
  16. package/dist/chat/commands.js +52 -0
  17. package/dist/chat/commands.js.map +1 -0
  18. package/dist/chat/config.d.ts +22 -0
  19. package/dist/chat/config.js +55 -0
  20. package/dist/chat/config.js.map +1 -0
  21. package/dist/chat/history.d.ts +12 -0
  22. package/dist/chat/history.js +74 -0
  23. package/dist/chat/history.js.map +1 -0
  24. package/dist/chat/session.d.ts +42 -0
  25. package/dist/chat/session.js +107 -0
  26. package/dist/chat/session.js.map +1 -0
  27. package/dist/chat/storage.d.ts +17 -0
  28. package/dist/chat/storage.js +71 -0
  29. package/dist/chat/storage.js.map +1 -0
  30. package/dist/cli.d.ts +7 -0
  31. package/dist/cli.js +363 -0
  32. package/dist/cli.js.map +1 -0
  33. package/dist/commands/ask.d.ts +4 -0
  34. package/dist/commands/ask.js +288 -0
  35. package/dist/commands/ask.js.map +1 -0
  36. package/dist/commands/bench.d.ts +2 -0
  37. package/dist/commands/bench.js +92 -0
  38. package/dist/commands/bench.js.map +1 -0
  39. package/dist/commands/chat.d.ts +2 -0
  40. package/dist/commands/chat.js +701 -0
  41. package/dist/commands/chat.js.map +1 -0
  42. package/dist/commands/config.d.ts +2 -0
  43. package/dist/commands/config.js +102 -0
  44. package/dist/commands/config.js.map +1 -0
  45. package/dist/commands/daemon.d.ts +2 -0
  46. package/dist/commands/daemon.js +225 -0
  47. package/dist/commands/daemon.js.map +1 -0
  48. package/dist/commands/embed.d.ts +2 -0
  49. package/dist/commands/embed.js +79 -0
  50. package/dist/commands/embed.js.map +1 -0
  51. package/dist/commands/models.d.ts +5 -0
  52. package/dist/commands/models.js +244 -0
  53. package/dist/commands/models.js.map +1 -0
  54. package/dist/commands/serve.d.ts +2 -0
  55. package/dist/commands/serve.js +52 -0
  56. package/dist/commands/serve.js.map +1 -0
  57. package/dist/commands/status.d.ts +2 -0
  58. package/dist/commands/status.js +81 -0
  59. package/dist/commands/status.js.map +1 -0
  60. package/dist/daemon/client.d.ts +74 -0
  61. package/dist/daemon/client.js +447 -0
  62. package/dist/daemon/client.js.map +1 -0
  63. package/dist/daemon/server.d.ts +43 -0
  64. package/dist/daemon/server.js +661 -0
  65. package/dist/daemon/server.js.map +1 -0
  66. package/dist/daemon/service.d.ts +29 -0
  67. package/dist/daemon/service.js +173 -0
  68. package/dist/daemon/service.js.map +1 -0
  69. package/dist/daemon/state.d.ts +4 -0
  70. package/dist/daemon/state.js +54 -0
  71. package/dist/daemon/state.js.map +1 -0
  72. package/dist/engine/llama-engine.d.ts +49 -0
  73. package/dist/engine/llama-engine.js +465 -0
  74. package/dist/engine/llama-engine.js.map +1 -0
  75. package/dist/engine/model-pool.d.ts +36 -0
  76. package/dist/engine/model-pool.js +202 -0
  77. package/dist/engine/model-pool.js.map +1 -0
  78. package/dist/engine/sampling.d.ts +13 -0
  79. package/dist/engine/sampling.js +43 -0
  80. package/dist/engine/sampling.js.map +1 -0
  81. package/dist/models/catalog.d.ts +6 -0
  82. package/dist/models/catalog.js +124 -0
  83. package/dist/models/catalog.js.map +1 -0
  84. package/dist/models/config.d.ts +10 -0
  85. package/dist/models/config.js +141 -0
  86. package/dist/models/config.js.map +1 -0
  87. package/dist/models/downloader.d.ts +21 -0
  88. package/dist/models/downloader.js +98 -0
  89. package/dist/models/downloader.js.map +1 -0
  90. package/dist/models/profiles.d.ts +10 -0
  91. package/dist/models/profiles.js +68 -0
  92. package/dist/models/profiles.js.map +1 -0
  93. package/dist/models/store.d.ts +9 -0
  94. package/dist/models/store.js +142 -0
  95. package/dist/models/store.js.map +1 -0
  96. package/dist/types.d.ts +189 -0
  97. package/dist/types.js +2 -0
  98. package/dist/types.js.map +1 -0
  99. package/dist/utils/errors.d.ts +18 -0
  100. package/dist/utils/errors.js +33 -0
  101. package/dist/utils/errors.js.map +1 -0
  102. package/dist/utils/files.d.ts +14 -0
  103. package/dist/utils/files.js +88 -0
  104. package/dist/utils/files.js.map +1 -0
  105. package/dist/utils/output.d.ts +29 -0
  106. package/dist/utils/output.js +116 -0
  107. package/dist/utils/output.js.map +1 -0
  108. package/package.json +28 -11
  109. package/examples/openai-client.js +0 -112
  110. package/examples/openai-sdk.js +0 -46
  111. package/examples/openai_python.py +0 -42
  112. package/src/api/openai.js +0 -115
  113. package/src/benchmark/runner.js +0 -48
  114. package/src/benchmark/stats.js +0 -33
  115. package/src/chat/commands.js +0 -68
  116. package/src/chat/config.js +0 -65
  117. package/src/chat/history.js +0 -103
  118. package/src/chat/session.js +0 -337
  119. package/src/chrome/bridge.js +0 -473
  120. package/src/chrome/capabilities.js +0 -99
  121. package/src/chrome/detect.js +0 -199
  122. package/src/chrome/launch.js +0 -248
  123. package/src/cli.js +0 -216
  124. package/src/commands/ask.js +0 -179
  125. package/src/commands/bench.js +0 -79
  126. package/src/commands/chat.js +0 -416
  127. package/src/commands/daemon.js +0 -89
  128. package/src/commands/download.js +0 -71
  129. package/src/commands/serve.js +0 -56
  130. package/src/commands/status.js +0 -87
  131. package/src/daemon/client.js +0 -274
  132. package/src/daemon/server.js +0 -650
  133. package/src/daemon/state.js +0 -46
  134. package/src/utils/errors.js +0 -26
  135. package/src/utils/files.js +0 -93
  136. package/src/utils/output.js +0 -59
  137. package/test/chat.test.js +0 -252
  138. package/test/cli.test.js +0 -49
  139. package/test/daemon.test.js +0 -31
  140. package/test/detect.test.js +0 -24
  141. package/test/files.test.js +0 -41
  142. package/test/openai.test.js +0 -63
  143. package/test/stats.test.js +0 -29
@@ -1,473 +0,0 @@
1
- import WebSocket from 'ws';
2
- import { debug } from '../utils/output.js';
3
- import {
4
- BuiltInAiUnavailableError,
5
- ModelUnavailableError,
6
- NanoBridgeError
7
- } from '../utils/errors.js';
8
-
9
- export class ChromeBridge {
10
- constructor(chromeInstance) {
11
- this.chromeInstance = chromeInstance;
12
- this.ws = null;
13
- this.msgId = 1;
14
- this.pendingCallbacks = new Map();
15
- this.consoleHandlers = new Map();
16
- this.pageTarget = null;
17
- }
18
-
19
- async connect() {
20
- const { cdpPort, pageUrl } = this.chromeInstance;
21
- debug('bridge', `Fetching targets from http://127.0.0.1:${cdpPort}/json/list`);
22
-
23
- // Give Chrome 400ms to initialize targets
24
- await new Promise((r) => setTimeout(r, 400));
25
-
26
- let pages = [];
27
- for (let i = 0; i < 30; i++) {
28
- try {
29
- const res = await fetch(`http://127.0.0.1:${cdpPort}/json/list`);
30
- pages = await res.json();
31
- debug('bridge', `Target search attempt ${i + 1}: found ${pages.length} targets`);
32
- // Prioritize localhost / 127.0.0.1 secure origin over about:blank
33
- const localhostTarget = pages.find((p) => p.type === 'page' && (p.url.includes('localhost') || p.url.includes('127.0.0.1')));
34
- if (localhostTarget) {
35
- this.pageTarget = localhostTarget;
36
- break;
37
- }
38
- const anyPage = pages.find((p) => p.type === 'page');
39
- if (anyPage && i >= 10) {
40
- this.pageTarget = anyPage;
41
- break;
42
- }
43
- } catch {
44
- // Retry
45
- }
46
- await new Promise((r) => setTimeout(r, 100));
47
- }
48
-
49
- if (!this.pageTarget) {
50
- this.pageTarget = pages.find((p) => p.type === 'page' && (p.url.includes('localhost') || p.url.includes('127.0.0.1'))) || pages.find((p) => p.type === 'page') || pages[0];
51
- }
52
-
53
- debug('bridge', 'Selected target:', JSON.stringify(this.pageTarget));
54
-
55
- if (!this.pageTarget || !this.pageTarget.webSocketDebuggerUrl) {
56
- throw new NanoBridgeError('Failed to locate suitable CDP page target in Chrome');
57
- }
58
-
59
- debug('bridge', 'Connecting to page target WebSocket:', this.pageTarget.webSocketDebuggerUrl);
60
-
61
- this.ws = new WebSocket(this.pageTarget.webSocketDebuggerUrl);
62
-
63
- await new Promise((resolve, reject) => {
64
- this.ws.once('open', resolve);
65
- this.ws.once('error', reject);
66
- });
67
-
68
- this.ws.on('close', () => {
69
- debug('bridge', 'CDP WebSocket connection closed.');
70
- for (const [, { reject }] of this.pendingCallbacks) {
71
- reject(new Error('CDP WebSocket disconnected'));
72
- }
73
- this.pendingCallbacks.clear();
74
- });
75
-
76
- this.ws.on('error', (err) => {
77
- debug('bridge', 'CDP WebSocket error:', err.message);
78
- });
79
-
80
- this.ws.on('message', (data) => {
81
- try {
82
- const text = typeof data === 'string' ? data : data.toString('utf8');
83
- const parsed = JSON.parse(text);
84
- if (parsed.id && this.pendingCallbacks.has(parsed.id)) {
85
- const { resolve, reject } = this.pendingCallbacks.get(parsed.id);
86
- this.pendingCallbacks.delete(parsed.id);
87
- if (parsed.error) {
88
- reject(new Error(parsed.error.message || JSON.stringify(parsed.error)));
89
- } else {
90
- resolve(parsed.result);
91
- }
92
- } else if (parsed.method === 'Runtime.consoleAPICalled') {
93
- for (const [, cb] of this.pendingCallbacks) {
94
- if (typeof cb.touch === 'function') cb.touch();
95
- }
96
- debug('bridge:console', parsed.params?.type, JSON.stringify(parsed.params?.args?.map((a) => a.value)));
97
- const firstArg = parsed.params?.args?.[0]?.value || '';
98
- if (typeof firstArg === 'string') {
99
- for (const [prefix, handler] of this.consoleHandlers) {
100
- if (firstArg.startsWith(prefix)) {
101
- handler(firstArg.slice(prefix.length));
102
- }
103
- }
104
- }
105
- }
106
- } catch (err) {
107
- debug('bridge', 'Error parsing CDP incoming message:', err.message);
108
- }
109
- });
110
-
111
- debug('bridge', 'CDP WebSocket connected. Enabling Runtime...');
112
- await this.send('Runtime.enable');
113
- if (pageUrl && (!this.pageTarget.url || this.pageTarget.url === 'about:blank' || !this.pageTarget.url.includes('localhost'))) {
114
- try {
115
- await this.send('Page.enable');
116
- await this.send('Page.navigate', { url: pageUrl });
117
- await new Promise((r) => setTimeout(r, 300));
118
- } catch (_) {}
119
- }
120
- debug('bridge', 'Runtime enabled successfully.');
121
- }
122
-
123
- isConnected() {
124
- return Boolean(this.ws && this.ws.readyState === WebSocket.OPEN);
125
- }
126
-
127
- send(method, params = {}, options = {}) {
128
- return new Promise((resolve, reject) => {
129
- if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
130
- return reject(new Error('CDP WebSocket is closed or not connected'));
131
- }
132
- const id = this.msgId++;
133
- const timeoutMs = options.timeout ?? 180000;
134
- let timer = null;
135
-
136
- const armTimer = () => {
137
- if (timer) clearTimeout(timer);
138
- if (timeoutMs > 0) {
139
- timer = setTimeout(() => {
140
- if (this.pendingCallbacks.has(id)) {
141
- this.pendingCallbacks.delete(id);
142
- reject(new Error(`CDP command timed out: ${method}`));
143
- }
144
- }, timeoutMs);
145
- if (timer.unref) timer.unref();
146
- }
147
- };
148
-
149
- armTimer();
150
-
151
- this.pendingCallbacks.set(id, {
152
- resolve: (val) => { if (timer) clearTimeout(timer); resolve(val); },
153
- reject: (err) => { if (timer) clearTimeout(timer); reject(err); },
154
- touch: () => armTimer()
155
- });
156
-
157
- this.ws.send(JSON.stringify({ id, method, params }), (err) => {
158
- if (err) {
159
- if (timer) clearTimeout(timer);
160
- this.pendingCallbacks.delete(id);
161
- reject(err);
162
- }
163
- });
164
- });
165
- }
166
-
167
- addConsoleHandler(prefix, handler) {
168
- this.consoleHandlers.set(prefix, handler);
169
- }
170
-
171
- removeConsoleHandler(prefix) {
172
- this.consoleHandlers.delete(prefix);
173
- }
174
-
175
- async evaluate(expression, options = {}) {
176
- const res = await this.send('Runtime.evaluate', {
177
- expression,
178
- awaitPromise: options.awaitPromise ?? true,
179
- returnByValue: options.returnByValue ?? true,
180
- userGesture: options.userGesture ?? true
181
- }, { timeout: options.timeout });
182
-
183
- if (res.exceptionDetails) {
184
- const desc = res.exceptionDetails.exception?.description || res.exceptionDetails.text;
185
- throw new Error(desc || 'CDP Evaluation Exception');
186
- }
187
-
188
- return res.result?.value;
189
- }
190
-
191
- async checkStatus() {
192
- debug('bridge', 'Checking Built-in AI and LanguageModel status in page context...');
193
- const result = await this.evaluate(`(async () => {
194
- const hasLanguageModel = 'LanguageModel' in window;
195
- let availability = 'unavailable';
196
- let capabilities = null;
197
- let reason = null;
198
-
199
- if (!hasLanguageModel) {
200
- reason = 'LanguageModel API is not exposed by this Chrome installation.';
201
- } else {
202
- try {
203
- if (typeof window.LanguageModel.availability === 'function') {
204
- const availPromise = window.LanguageModel.availability();
205
- const timeoutPromise = new Promise((resolve) => setTimeout(() => resolve('downloadable'), 1500));
206
- availability = await Promise.race([availPromise, timeoutPromise]);
207
- } else if (typeof window.LanguageModel.capabilities === 'function') {
208
- capabilities = await window.LanguageModel.capabilities();
209
- availability = capabilities.available || 'available';
210
- } else {
211
- availability = 'available';
212
- }
213
- } catch (e) {
214
- reason = e.message;
215
- availability = 'unavailable';
216
- }
217
- }
218
-
219
- return {
220
- builtInAiAvailable: hasLanguageModel,
221
- languageModelAvailable: hasLanguageModel,
222
- availability, // 'readily' | 'after-download' | 'downloadable' | 'downloading' | 'no' | 'unavailable'
223
- capabilities,
224
- reason
225
- };
226
- })()`, { userGesture: true });
227
-
228
- debug('bridge', 'Status detection result:', JSON.stringify(result));
229
- return result;
230
- }
231
-
232
- async downloadModel({ onProgress } = {}) {
233
- debug('bridge', 'Initiating model download / preparation...');
234
- const prefix = '__NANOBRIDGE_DOWNLOAD_PROG__:';
235
-
236
- if (onProgress && typeof onProgress === 'function') {
237
- this.addConsoleHandler(prefix, (raw) => {
238
- try {
239
- const data = JSON.parse(raw);
240
- const loaded = Number(data.loaded) || 0;
241
- const total = Number(data.total) || 1;
242
- const percent = total > 0 ? (loaded / total) * 100 : 0;
243
- onProgress({ loaded, total, percent });
244
- } catch (err) {
245
- debug('bridge', 'Error parsing download progress:', err.message);
246
- }
247
- });
248
- }
249
-
250
- try {
251
- debug('bridge', 'Calling LanguageModel.create with userGesture...');
252
- const evalResult = await this.evaluate(`(async () => {
253
- try {
254
- const session = await window.LanguageModel.create({
255
- monitor(m) {
256
- m.addEventListener('downloadprogress', (e) => {
257
- console.debug('${prefix}' + JSON.stringify({ loaded: e.loaded, total: e.total }));
258
- });
259
- }
260
- });
261
- if (session && typeof session.destroy === 'function') {
262
- session.destroy();
263
- }
264
- return { success: true };
265
- } catch (e) {
266
- return { success: false, error: e.message, stack: e.stack };
267
- }
268
- })()`, { userGesture: true, timeout: 900000 });
269
-
270
- if (!evalResult.success) {
271
- throw new NanoBridgeError(`Failed to prepare/download model: ${evalResult.error}`);
272
- }
273
-
274
- return { alreadyAvailable: false, success: true };
275
- } finally {
276
- this.removeConsoleHandler(prefix);
277
- }
278
- }
279
-
280
- async prompt({ promptText, systemPrompt, stream = true, onChunk } = {}) {
281
- debug('bridge', 'Executing prompt in browser session. Stream mode:', stream);
282
- const escapedPrompt = JSON.stringify(promptText);
283
- const createArgs = systemPrompt ? JSON.stringify({ systemPrompt }) : '';
284
-
285
- if (stream && onChunk) {
286
- const prefix = `__NANOBRIDGE_CHUNK_${Date.now()}__:`;
287
-
288
- this.addConsoleHandler(prefix, (payload) => {
289
- try {
290
- const data = JSON.parse(payload);
291
- if (data.d) {
292
- onChunk(data.d);
293
- }
294
- } catch (err) {
295
- debug('bridge', 'Error in stream chunk handler:', err.message);
296
- }
297
- });
298
-
299
- try {
300
- const res = await this.evaluate(`(async () => {
301
- try {
302
- if (!('LanguageModel' in window)) {
303
- return { success: false, error: 'LanguageModel API is not exposed by this Chrome.' };
304
- }
305
- const session = await window.LanguageModel.create(${createArgs});
306
- const stream = session.promptStreaming(${escapedPrompt});
307
- let finalResult = '';
308
- for await (const chunk of stream) {
309
- if (chunk) {
310
- finalResult += chunk;
311
- console.debug('${prefix}' + JSON.stringify({ d: chunk }));
312
- }
313
- }
314
- if (typeof session.destroy === 'function') {
315
- session.destroy();
316
- }
317
- return { success: true, text: finalResult };
318
- } catch (e) {
319
- return { success: false, error: e.message };
320
- }
321
- })()`, { userGesture: true });
322
-
323
- if (!res.success) {
324
- if (/download|gesture|ready/i.test(res.error)) {
325
- throw new NanoBridgeError(`Chrome Built-in AI model is not ready. Run \`nanobridge download\` to prepare it. Details: ${res.error}`);
326
- }
327
- throw new NanoBridgeError(res.error);
328
- }
329
- return res.text;
330
- } finally {
331
- this.removeConsoleHandler(prefix);
332
- }
333
- } else {
334
- const res = await this.evaluate(`(async () => {
335
- try {
336
- if (!('LanguageModel' in window)) {
337
- return { success: false, error: 'LanguageModel API is not exposed by this Chrome.' };
338
- }
339
- const session = await window.LanguageModel.create(${createArgs});
340
- const result = await session.prompt(${escapedPrompt});
341
- if (typeof session.destroy === 'function') {
342
- session.destroy();
343
- }
344
- return { success: true, text: result };
345
- } catch (e) {
346
- return { success: false, error: e.message };
347
- }
348
- })()`, { userGesture: true });
349
-
350
- if (!res.success) {
351
- if (/download|gesture|ready/i.test(res.error)) {
352
- throw new NanoBridgeError(`Chrome Built-in AI model is not ready. Run \`nanobridge download\` to prepare it. Details: ${res.error}`);
353
- }
354
- throw new NanoBridgeError(res.error);
355
- }
356
- return res.text;
357
- }
358
- }
359
-
360
- async benchmarkRun({ promptText, isWarm = false } = {}) {
361
- debug('bridge', 'Running single benchmark iteration (warm:', isWarm, ')...');
362
- const escapedPrompt = JSON.stringify(promptText || 'Explain the concept of Web Locks in modern browser APIs in two concise paragraphs.');
363
- const prefix = `__NANOBRIDGE_BENCH_${Date.now()}__:`;
364
-
365
- let firstTokenTime = 0;
366
- let chunksCount = 0;
367
-
368
- this.addConsoleHandler(prefix, (payload) => {
369
- try {
370
- const data = JSON.parse(payload);
371
- if (data.type === 'first_chunk') {
372
- firstTokenTime = performance.now();
373
- } else if (data.type === 'chunk') {
374
- chunksCount++;
375
- }
376
- } catch (err) {
377
- debug('bridge', 'Bench handler error:', err.message);
378
- }
379
- });
380
-
381
- try {
382
- const evalResult = await this.evaluate(`(async () => {
383
- try {
384
- const tStart = performance.now();
385
- if (!('LanguageModel' in window)) {
386
- return { success: false, error: 'LanguageModel API is not exposed by this Chrome.' };
387
- }
388
-
389
- const tCreateStart = performance.now();
390
- const session = await window.LanguageModel.create();
391
- const tCreateEnd = performance.now();
392
-
393
- const tPromptStart = performance.now();
394
- const stream = session.promptStreaming(${escapedPrompt});
395
-
396
- let finalOutput = '';
397
- let tFirstToken = 0;
398
- let chunkCount = 0;
399
-
400
- for await (const chunk of stream) {
401
- if (!tFirstToken) {
402
- tFirstToken = performance.now();
403
- console.debug('${prefix}' + JSON.stringify({ type: 'first_chunk' }));
404
- }
405
- chunkCount++;
406
- finalOutput += chunk;
407
- console.debug('${prefix}' + JSON.stringify({ type: 'chunk' }));
408
- }
409
-
410
- const tEnd = performance.now();
411
- if (typeof session.destroy === 'function') {
412
- session.destroy();
413
- }
414
-
415
- const sessionCreateMs = tCreateEnd - tCreateStart;
416
- const ttftMs = tFirstToken ? (tFirstToken - tPromptStart) : 0;
417
- const generationMs = tFirstToken ? (tEnd - tFirstToken) : (tEnd - tPromptStart);
418
- const totalMs = tEnd - tStart;
419
-
420
- return {
421
- success: true,
422
- inBrowser: {
423
- sessionCreateMs,
424
- ttftMs,
425
- generationMs,
426
- totalMs
427
- },
428
- outputLength: finalOutput.length,
429
- outputChars: finalOutput.length,
430
- chunkCount,
431
- outputSample: finalOutput.slice(0, 120)
432
- };
433
- } catch (e) {
434
- return { success: false, error: e.message };
435
- }
436
- })()`, { userGesture: true });
437
-
438
- if (!evalResult.success) {
439
- throw new NanoBridgeError(`Benchmark execution failed: ${evalResult.error}`);
440
- }
441
-
442
- const b = evalResult.inBrowser;
443
- const sessionCreateMs = b.sessionCreateMs;
444
- const ttftMs = b.ttftMs;
445
- const generationMs = b.generationMs;
446
- const totalInferenceMs = b.totalMs;
447
- const outputChars = evalResult.outputChars;
448
- const generationRate = generationMs > 0 ? (outputChars / (generationMs / 1000)) : 0;
449
-
450
- return {
451
- sessionCreateMs,
452
- ttftMs,
453
- generationMs,
454
- totalInferenceMs,
455
- outputChars,
456
- generationRate,
457
- chunkCount: evalResult.chunkCount,
458
- outputSample: evalResult.outputSample
459
- };
460
- } finally {
461
- this.removeConsoleHandler(prefix);
462
- }
463
- }
464
-
465
- async close() {
466
- if (this.ws) {
467
- try {
468
- this.ws.close();
469
- } catch (_) {}
470
- this.ws = null;
471
- }
472
- }
473
- }
@@ -1,99 +0,0 @@
1
- import { debug } from '../utils/output.js';
2
-
3
- export const SAMPLING_MODES = [
4
- 'most-predictable',
5
- 'predictable',
6
- 'slightly-predictable',
7
- 'balanced',
8
- 'slightly-creative',
9
- 'creative',
10
- 'most-creative'
11
- ];
12
-
13
- export const DEFAULT_CAPABILITIES = {
14
- builtInAi: false,
15
- languageModel: false,
16
- samplingMode: false,
17
- temperature: false,
18
- topK: false,
19
- initialPrompts: true,
20
- responseConstraint: true,
21
- contextUsage: true,
22
- contextWindow: true,
23
- contextOverflowEvent: true,
24
- supportedSamplingModes: [...SAMPLING_MODES],
25
- supportedInputLanguages: ['en', 'es', 'ja', 'de', 'fr'],
26
- supportedOutputLanguages: ['en', 'es', 'ja', 'de', 'fr']
27
- };
28
-
29
- /**
30
- * Fast, non-blocking capability detection via prototype and static properties.
31
- * Executes in <1ms without cold model instantiation overhead.
32
- *
33
- * @param {object} bridge - Connected ChromeBridge instance
34
- * @returns {Promise<object>} Capabilities object
35
- */
36
- export async function detectCapabilities(bridge) {
37
- if (!bridge || !bridge.isConnected()) {
38
- return { ...DEFAULT_CAPABILITIES };
39
- }
40
-
41
- debug('capabilities', 'Detecting Prompt API capabilities via prototype inspection...');
42
-
43
- try {
44
- const raw = await bridge.evaluate(`(() => {
45
- const hasLM = typeof window !== 'undefined' && 'LanguageModel' in window;
46
- if (!hasLM) {
47
- return {
48
- builtInAi: false,
49
- languageModel: false,
50
- samplingMode: false,
51
- temperature: false,
52
- topK: false,
53
- initialPrompts: false,
54
- responseConstraint: false,
55
- contextUsage: false,
56
- contextWindow: false,
57
- contextOverflowEvent: false
58
- };
59
- }
60
-
61
- const proto = window.LanguageModel.prototype || {};
62
- const propNames = Object.getOwnPropertyNames(proto);
63
-
64
- const contextUsage = propNames.includes('contextUsage');
65
- const contextWindow = propNames.includes('contextWindow');
66
- const contextOverflowEvent = propNames.includes('oncontextoverflow');
67
- const samplingMode = propNames.includes('samplingMode');
68
- const temperature = propNames.includes('temperature');
69
- const topK = propNames.includes('topK');
70
-
71
- return {
72
- builtInAi: true,
73
- languageModel: true,
74
- samplingMode,
75
- temperature,
76
- topK,
77
- initialPrompts: true,
78
- responseConstraint: true,
79
- contextUsage,
80
- contextWindow,
81
- contextOverflowEvent
82
- };
83
- })()`, { userGesture: true });
84
-
85
- const caps = {
86
- ...DEFAULT_CAPABILITIES,
87
- ...raw,
88
- supportedSamplingModes: raw.samplingMode ? [...SAMPLING_MODES] : [],
89
- supportedInputLanguages: ['en', 'es', 'ja', 'de', 'fr'],
90
- supportedOutputLanguages: ['en', 'es', 'ja', 'de', 'fr']
91
- };
92
-
93
- debug('capabilities', 'Detection completed:', JSON.stringify(caps));
94
- return caps;
95
- } catch (err) {
96
- debug('capabilities', 'Detection error, using safe defaults:', err.message);
97
- return { ...DEFAULT_CAPABILITIES, builtInAi: true, languageModel: true };
98
- }
99
- }