nanobridge 0.1.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.
@@ -0,0 +1,446 @@
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
+ const found = pages.find((p) => p.type === 'page' && (p.url.includes('localhost') || p.url.includes('127.0.0.1') || p.url === 'about:blank'));
33
+ if (found) {
34
+ this.pageTarget = found;
35
+ break;
36
+ }
37
+ } catch {
38
+ // Retry
39
+ }
40
+ await new Promise((r) => setTimeout(r, 100));
41
+ }
42
+
43
+ if (!this.pageTarget) {
44
+ this.pageTarget = pages.find((p) => p.type === 'page') || pages[0];
45
+ }
46
+
47
+ debug('bridge', 'Selected target:', JSON.stringify(this.pageTarget));
48
+
49
+ if (!this.pageTarget || !this.pageTarget.webSocketDebuggerUrl) {
50
+ throw new NanoBridgeError('Failed to locate suitable CDP page target in Chrome');
51
+ }
52
+
53
+ debug('bridge', 'Connecting to page target WebSocket:', this.pageTarget.webSocketDebuggerUrl);
54
+
55
+ this.ws = new WebSocket(this.pageTarget.webSocketDebuggerUrl);
56
+
57
+ await new Promise((resolve, reject) => {
58
+ this.ws.once('open', resolve);
59
+ this.ws.once('error', reject);
60
+ });
61
+
62
+ this.ws.on('close', () => {
63
+ debug('bridge', 'CDP WebSocket connection closed.');
64
+ for (const [, { reject }] of this.pendingCallbacks) {
65
+ reject(new Error('CDP WebSocket disconnected'));
66
+ }
67
+ this.pendingCallbacks.clear();
68
+ });
69
+
70
+ this.ws.on('error', (err) => {
71
+ debug('bridge', 'CDP WebSocket error:', err.message);
72
+ });
73
+
74
+ this.ws.on('message', (data) => {
75
+ try {
76
+ const text = typeof data === 'string' ? data : data.toString('utf8');
77
+ const parsed = JSON.parse(text);
78
+ if (parsed.id && this.pendingCallbacks.has(parsed.id)) {
79
+ const { resolve, reject } = this.pendingCallbacks.get(parsed.id);
80
+ this.pendingCallbacks.delete(parsed.id);
81
+ if (parsed.error) {
82
+ reject(new Error(parsed.error.message || JSON.stringify(parsed.error)));
83
+ } else {
84
+ resolve(parsed.result);
85
+ }
86
+ } else if (parsed.method === 'Runtime.consoleAPICalled') {
87
+ const firstArg = parsed.params?.args?.[0]?.value || '';
88
+ if (typeof firstArg === 'string') {
89
+ for (const [prefix, handler] of this.consoleHandlers) {
90
+ if (firstArg.startsWith(prefix)) {
91
+ handler(firstArg.slice(prefix.length));
92
+ }
93
+ }
94
+ }
95
+ }
96
+ } catch (err) {
97
+ debug('bridge', 'Error parsing CDP incoming message:', err.message);
98
+ }
99
+ });
100
+
101
+ debug('bridge', 'CDP WebSocket connected. Enabling Runtime...');
102
+ await this.send('Runtime.enable');
103
+ debug('bridge', 'Runtime enabled successfully.');
104
+ }
105
+
106
+ isConnected() {
107
+ return Boolean(this.ws && this.ws.readyState === WebSocket.OPEN);
108
+ }
109
+
110
+ send(method, params = {}) {
111
+ return new Promise((resolve, reject) => {
112
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
113
+ return reject(new Error('CDP WebSocket is closed or not connected'));
114
+ }
115
+ const id = this.msgId++;
116
+ const timer = setTimeout(() => {
117
+ if (this.pendingCallbacks.has(id)) {
118
+ this.pendingCallbacks.delete(id);
119
+ reject(new Error(`CDP command timed out: ${method}`));
120
+ }
121
+ }, 60000);
122
+ if (timer.unref) timer.unref();
123
+
124
+ this.pendingCallbacks.set(id, {
125
+ resolve: (val) => { clearTimeout(timer); resolve(val); },
126
+ reject: (err) => { clearTimeout(timer); reject(err); }
127
+ });
128
+
129
+ this.ws.send(JSON.stringify({ id, method, params }), (err) => {
130
+ if (err) {
131
+ clearTimeout(timer);
132
+ this.pendingCallbacks.delete(id);
133
+ reject(err);
134
+ }
135
+ });
136
+ });
137
+ }
138
+
139
+ addConsoleHandler(prefix, handler) {
140
+ this.consoleHandlers.set(prefix, handler);
141
+ }
142
+
143
+ removeConsoleHandler(prefix) {
144
+ this.consoleHandlers.delete(prefix);
145
+ }
146
+
147
+ async evaluate(expression, options = {}) {
148
+ const res = await this.send('Runtime.evaluate', {
149
+ expression,
150
+ awaitPromise: options.awaitPromise ?? true,
151
+ returnByValue: options.returnByValue ?? true,
152
+ userGesture: options.userGesture ?? true
153
+ });
154
+
155
+ if (res.exceptionDetails) {
156
+ const desc = res.exceptionDetails.exception?.description || res.exceptionDetails.text;
157
+ throw new Error(desc || 'CDP Evaluation Exception');
158
+ }
159
+
160
+ return res.result?.value;
161
+ }
162
+
163
+ async checkStatus() {
164
+ debug('bridge', 'Checking Built-in AI and LanguageModel status in page context...');
165
+ const result = await this.evaluate(`(async () => {
166
+ const hasLanguageModel = 'LanguageModel' in window;
167
+ let availability = 'unavailable';
168
+ let capabilities = null;
169
+ let reason = null;
170
+
171
+ if (!hasLanguageModel) {
172
+ reason = 'LanguageModel API is not exposed by this Chrome installation.';
173
+ } else {
174
+ try {
175
+ if (typeof window.LanguageModel.availability === 'function') {
176
+ const availPromise = window.LanguageModel.availability();
177
+ const timeoutPromise = new Promise((resolve) => setTimeout(() => resolve('downloadable'), 1500));
178
+ availability = await Promise.race([availPromise, timeoutPromise]);
179
+ } else if (typeof window.LanguageModel.capabilities === 'function') {
180
+ capabilities = await window.LanguageModel.capabilities();
181
+ availability = capabilities.available || 'available';
182
+ } else {
183
+ availability = 'available';
184
+ }
185
+ } catch (e) {
186
+ reason = e.message;
187
+ availability = 'unavailable';
188
+ }
189
+ }
190
+
191
+ return {
192
+ builtInAiAvailable: hasLanguageModel,
193
+ languageModelAvailable: hasLanguageModel,
194
+ availability, // 'readily' | 'after-download' | 'downloadable' | 'downloading' | 'no' | 'unavailable'
195
+ capabilities,
196
+ reason
197
+ };
198
+ })()`, { userGesture: true });
199
+
200
+ debug('bridge', 'Status detection result:', JSON.stringify(result));
201
+ return result;
202
+ }
203
+
204
+ async downloadModel({ onProgress } = {}) {
205
+ debug('bridge', 'Initiating model download / preparation...');
206
+ const prefix = '__NANOBRIDGE_DOWNLOAD_PROG__:';
207
+
208
+ if (onProgress && typeof onProgress === 'function') {
209
+ this.addConsoleHandler(prefix, (raw) => {
210
+ try {
211
+ const data = JSON.parse(raw);
212
+ const loaded = Number(data.loaded) || 0;
213
+ const total = Number(data.total) || 1;
214
+ const percent = total > 0 ? (loaded / total) * 100 : 0;
215
+ onProgress({ loaded, total, percent });
216
+ } catch (err) {
217
+ debug('bridge', 'Error parsing download progress:', err.message);
218
+ }
219
+ });
220
+ }
221
+
222
+ try {
223
+ debug('bridge', 'Calling LanguageModel.create with userGesture...');
224
+ const evalResult = await this.evaluate(`(async () => {
225
+ try {
226
+ const session = await window.LanguageModel.create({
227
+ monitor(m) {
228
+ m.addEventListener('downloadprogress', (e) => {
229
+ console.debug('${prefix}' + JSON.stringify({ loaded: e.loaded, total: e.total }));
230
+ });
231
+ }
232
+ });
233
+ if (session && typeof session.destroy === 'function') {
234
+ session.destroy();
235
+ }
236
+ return { success: true };
237
+ } catch (e) {
238
+ return { success: false, error: e.message, stack: e.stack };
239
+ }
240
+ })()`, { userGesture: true });
241
+
242
+ if (!evalResult.success) {
243
+ throw new NanoBridgeError(`Failed to prepare/download model: ${evalResult.error}`);
244
+ }
245
+
246
+ return { alreadyAvailable: false, success: true };
247
+ } finally {
248
+ this.removeConsoleHandler(prefix);
249
+ }
250
+ }
251
+
252
+ async prompt({ promptText, systemPrompt, stream = true, onChunk } = {}) {
253
+ debug('bridge', 'Executing prompt in browser session. Stream mode:', stream);
254
+ const escapedPrompt = JSON.stringify(promptText);
255
+ const createArgs = systemPrompt ? JSON.stringify({ systemPrompt }) : '';
256
+
257
+ if (stream && onChunk) {
258
+ const prefix = `__NANOBRIDGE_CHUNK_${Date.now()}__:`;
259
+
260
+ this.addConsoleHandler(prefix, (payload) => {
261
+ try {
262
+ const data = JSON.parse(payload);
263
+ if (data.d) {
264
+ onChunk(data.d);
265
+ }
266
+ } catch (err) {
267
+ debug('bridge', 'Error in stream chunk handler:', err.message);
268
+ }
269
+ });
270
+
271
+ try {
272
+ const res = await this.evaluate(`(async () => {
273
+ try {
274
+ if (!('LanguageModel' in window)) {
275
+ return { success: false, error: 'LanguageModel API is not exposed by this Chrome.' };
276
+ }
277
+ const session = await window.LanguageModel.create(${createArgs});
278
+ const stream = session.promptStreaming(${escapedPrompt});
279
+ let finalResult = '';
280
+ let prev = '';
281
+ for await (const chunk of stream) {
282
+ finalResult = chunk;
283
+ const delta = chunk.startsWith(prev) ? chunk.slice(prev.length) : chunk;
284
+ prev = chunk;
285
+ console.debug('${prefix}' + JSON.stringify({ d: delta }));
286
+ }
287
+ if (typeof session.destroy === 'function') {
288
+ session.destroy();
289
+ }
290
+ return { success: true, text: finalResult };
291
+ } catch (e) {
292
+ return { success: false, error: e.message };
293
+ }
294
+ })()`, { userGesture: true });
295
+
296
+ if (!res.success) {
297
+ if (/download|gesture|ready/i.test(res.error)) {
298
+ throw new NanoBridgeError(`Chrome Built-in AI model is not ready. Run \`nanobridge download\` to prepare it. Details: ${res.error}`);
299
+ }
300
+ throw new NanoBridgeError(res.error);
301
+ }
302
+ return res.text;
303
+ } finally {
304
+ this.removeConsoleHandler(prefix);
305
+ }
306
+ } else {
307
+ const res = await this.evaluate(`(async () => {
308
+ try {
309
+ if (!('LanguageModel' in window)) {
310
+ return { success: false, error: 'LanguageModel API is not exposed by this Chrome.' };
311
+ }
312
+ const session = await window.LanguageModel.create(${createArgs});
313
+ const result = await session.prompt(${escapedPrompt});
314
+ if (typeof session.destroy === 'function') {
315
+ session.destroy();
316
+ }
317
+ return { success: true, text: result };
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
+ }
331
+ }
332
+
333
+ async benchmarkRun({ promptText, isWarm = false } = {}) {
334
+ debug('bridge', 'Running single benchmark iteration (warm:', isWarm, ')...');
335
+ const escapedPrompt = JSON.stringify(promptText || 'Explain the concept of Web Locks in modern browser APIs in two concise paragraphs.');
336
+ const prefix = `__NANOBRIDGE_BENCH_${Date.now()}__:`;
337
+
338
+ let firstTokenTime = 0;
339
+ let chunksCount = 0;
340
+
341
+ this.addConsoleHandler(prefix, (payload) => {
342
+ try {
343
+ const data = JSON.parse(payload);
344
+ if (data.type === 'first_chunk') {
345
+ firstTokenTime = performance.now();
346
+ } else if (data.type === 'chunk') {
347
+ chunksCount++;
348
+ }
349
+ } catch (err) {
350
+ debug('bridge', 'Bench handler error:', err.message);
351
+ }
352
+ });
353
+
354
+ try {
355
+ const evalResult = await this.evaluate(`(async () => {
356
+ try {
357
+ const tStart = performance.now();
358
+ if (!('LanguageModel' in window)) {
359
+ return { success: false, error: 'LanguageModel API is not exposed by this Chrome.' };
360
+ }
361
+
362
+ const tCreateStart = performance.now();
363
+ const session = await window.LanguageModel.create();
364
+ const tCreateEnd = performance.now();
365
+
366
+ const tPromptStart = performance.now();
367
+ const stream = session.promptStreaming(${escapedPrompt});
368
+
369
+ let finalOutput = '';
370
+ let tFirstToken = 0;
371
+ let chunkCount = 0;
372
+
373
+ for await (const chunk of stream) {
374
+ if (!tFirstToken) {
375
+ tFirstToken = performance.now();
376
+ console.debug('${prefix}' + JSON.stringify({ type: 'first_chunk' }));
377
+ }
378
+ chunkCount++;
379
+ finalOutput = chunk;
380
+ console.debug('${prefix}' + JSON.stringify({ type: 'chunk' }));
381
+ }
382
+
383
+ const tEnd = performance.now();
384
+ if (typeof session.destroy === 'function') {
385
+ session.destroy();
386
+ }
387
+
388
+ const sessionCreateMs = tCreateEnd - tCreateStart;
389
+ const ttftMs = tFirstToken ? (tFirstToken - tPromptStart) : 0;
390
+ const generationMs = tFirstToken ? (tEnd - tFirstToken) : (tEnd - tPromptStart);
391
+ const totalMs = tEnd - tStart;
392
+
393
+ return {
394
+ success: true,
395
+ inBrowser: {
396
+ sessionCreateMs,
397
+ ttftMs,
398
+ generationMs,
399
+ totalMs
400
+ },
401
+ outputLength: finalOutput.length,
402
+ outputChars: finalOutput.length,
403
+ chunkCount,
404
+ outputSample: finalOutput.slice(0, 120)
405
+ };
406
+ } catch (e) {
407
+ return { success: false, error: e.message };
408
+ }
409
+ })()`, { userGesture: true });
410
+
411
+ if (!evalResult.success) {
412
+ throw new NanoBridgeError(`Benchmark execution failed: ${evalResult.error}`);
413
+ }
414
+
415
+ const b = evalResult.inBrowser;
416
+ const sessionCreateMs = b.sessionCreateMs;
417
+ const ttftMs = b.ttftMs;
418
+ const generationMs = b.generationMs;
419
+ const totalInferenceMs = b.totalMs;
420
+ const outputChars = evalResult.outputChars;
421
+ const generationRate = generationMs > 0 ? (outputChars / (generationMs / 1000)) : 0;
422
+
423
+ return {
424
+ sessionCreateMs,
425
+ ttftMs,
426
+ generationMs,
427
+ totalInferenceMs,
428
+ outputChars,
429
+ generationRate,
430
+ chunkCount: evalResult.chunkCount,
431
+ outputSample: evalResult.outputSample
432
+ };
433
+ } finally {
434
+ this.removeConsoleHandler(prefix);
435
+ }
436
+ }
437
+
438
+ async close() {
439
+ if (this.ws) {
440
+ try {
441
+ this.ws.close();
442
+ } catch (_) {}
443
+ this.ws = null;
444
+ }
445
+ }
446
+ }
@@ -0,0 +1,199 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import os from 'node:os';
4
+ import { execFileSync } from 'node:child_process';
5
+ import process from 'node:process';
6
+ import { debug } from '../utils/output.js';
7
+
8
+ export function getPlatformInfo() {
9
+ const platform = process.platform;
10
+ const arch = process.arch;
11
+ let platformLabel = platform;
12
+ if (platform === 'darwin') platformLabel = 'macOS';
13
+ else if (platform === 'win32') platformLabel = 'Windows';
14
+ else if (platform === 'linux') platformLabel = 'Linux';
15
+
16
+ const chromeExecutable = findChromeExecutable();
17
+ const chromeVersion = chromeExecutable ? getChromeVersion(chromeExecutable) : null;
18
+
19
+ return {
20
+ platform,
21
+ arch,
22
+ platformLabel,
23
+ chromeExecutable,
24
+ chromeVersion
25
+ };
26
+ }
27
+
28
+ export function findChromeExecutable() {
29
+ if (process.env.CHROME_PATH && fs.existsSync(process.env.CHROME_PATH)) {
30
+ debug('detect', 'Using CHROME_PATH override:', process.env.CHROME_PATH);
31
+ return process.env.CHROME_PATH;
32
+ }
33
+ if (process.env.CHROMIUM_PATH && fs.existsSync(process.env.CHROMIUM_PATH)) {
34
+ debug('detect', 'Using CHROMIUM_PATH override:', process.env.CHROMIUM_PATH);
35
+ return process.env.CHROMIUM_PATH;
36
+ }
37
+
38
+ const platform = process.platform;
39
+ const homeDir = os.homedir();
40
+ const candidates = [];
41
+
42
+ if (platform === 'darwin') {
43
+ candidates.push(
44
+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
45
+ '/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary',
46
+ '/Applications/Google Chrome Beta.app/Contents/MacOS/Google Chrome Beta',
47
+ '/Applications/Google Chrome Dev.app/Contents/MacOS/Google Chrome Dev',
48
+ '/Applications/Chromium.app/Contents/MacOS/Chromium',
49
+ path.join(homeDir, 'Applications/Google Chrome.app/Contents/MacOS/Google Chrome'),
50
+ path.join(homeDir, 'Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary'),
51
+ path.join(homeDir, 'Applications/Chromium.app/Contents/MacOS/Chromium')
52
+ );
53
+ } else if (platform === 'win32') {
54
+ const programFiles = process.env['ProgramFiles'] || 'C:\\Program Files';
55
+ const programFilesX86 = process.env['ProgramFiles(x86)'] || 'C:\\Program Files (x86)';
56
+ const localAppData = process.env['LOCALAPPDATA'] || path.join(homeDir, 'AppData', 'Local');
57
+
58
+ candidates.push(
59
+ path.join(programFiles, 'Google', 'Chrome', 'Application', 'chrome.exe'),
60
+ path.join(programFilesX86, 'Google', 'Chrome', 'Application', 'chrome.exe'),
61
+ path.join(localAppData, 'Google', 'Chrome', 'Application', 'chrome.exe'),
62
+ path.join(localAppData, 'Google', 'Chrome SxS', 'Application', 'chrome.exe'),
63
+ path.join(programFiles, 'Chromium', 'Application', 'chrome.exe'),
64
+ path.join(localAppData, 'Chromium', 'Application', 'chrome.exe')
65
+ );
66
+ } else if (platform === 'linux') {
67
+ candidates.push(
68
+ '/usr/bin/google-chrome',
69
+ '/usr/bin/google-chrome-stable',
70
+ '/usr/bin/google-chrome-beta',
71
+ '/usr/bin/google-chrome-unstable',
72
+ '/usr/bin/chromium',
73
+ '/usr/bin/chromium-browser',
74
+ '/snap/bin/chromium',
75
+ '/snap/bin/google-chrome'
76
+ );
77
+ }
78
+
79
+ for (const candidate of candidates) {
80
+ try {
81
+ if (fs.existsSync(candidate)) {
82
+ debug('detect', 'Found candidate binary:', candidate);
83
+ return candidate;
84
+ }
85
+ } catch {
86
+ // Continue searching
87
+ }
88
+ }
89
+
90
+ // Fallback to searching PATH via 'which' or 'where'
91
+ const binaryNames = platform === 'win32' ? ['chrome.exe'] : ['google-chrome', 'google-chrome-stable', 'chromium-browser', 'chromium'];
92
+ for (const binName of binaryNames) {
93
+ try {
94
+ const tool = platform === 'win32' ? 'where' : 'which';
95
+ const output = execFileSync(tool, [binName], { stdio: ['ignore', 'pipe', 'ignore'], encoding: 'utf8' }).trim();
96
+ const firstPath = output.split(/\r?\n/)[0]?.trim();
97
+ if (firstPath && fs.existsSync(firstPath)) {
98
+ debug('detect', `Found binary via ${tool}:`, firstPath);
99
+ return firstPath;
100
+ }
101
+ } catch {
102
+ // Not in PATH
103
+ }
104
+ }
105
+
106
+ return null;
107
+ }
108
+
109
+ export function findSystemModelDir() {
110
+ const platform = process.platform;
111
+ const homeDir = os.homedir();
112
+ const candidates = [];
113
+
114
+ if (platform === 'darwin') {
115
+ candidates.push(
116
+ path.join(homeDir, 'Library/Application Support/Google/Chrome/OptGuideOnDeviceModel'),
117
+ path.join(homeDir, 'Library/Application Support/Google/Chrome Canary/OptGuideOnDeviceModel'),
118
+ path.join(homeDir, 'Library/Application Support/Chromium/OptGuideOnDeviceModel')
119
+ );
120
+ } else if (platform === 'win32') {
121
+ const localAppData = process.env['LOCALAPPDATA'] || path.join(homeDir, 'AppData', 'Local');
122
+ candidates.push(
123
+ path.join(localAppData, 'Google', 'Chrome', 'User Data', 'OptGuideOnDeviceModel'),
124
+ path.join(localAppData, 'Google', 'Chrome SxS', 'User Data', 'OptGuideOnDeviceModel'),
125
+ path.join(localAppData, 'Chromium', 'User Data', 'OptGuideOnDeviceModel')
126
+ );
127
+ } else if (platform === 'linux') {
128
+ candidates.push(
129
+ path.join(homeDir, '.config/google-chrome/OptGuideOnDeviceModel'),
130
+ path.join(homeDir, '.config/chromium/OptGuideOnDeviceModel')
131
+ );
132
+ }
133
+
134
+ for (const candidate of candidates) {
135
+ try {
136
+ if (fs.existsSync(candidate)) {
137
+ debug('detect', 'Found system model directory:', candidate);
138
+ return candidate;
139
+ }
140
+ } catch {
141
+ // Continue
142
+ }
143
+ }
144
+ return null;
145
+ }
146
+
147
+ export function isModelDownloaded() {
148
+ const modelDir = findSystemModelDir();
149
+ if (!modelDir) return false;
150
+ try {
151
+ const entries = fs.readdirSync(modelDir);
152
+ for (const entry of entries) {
153
+ const fullPath = path.join(modelDir, entry);
154
+ if (fs.statSync(fullPath).isDirectory()) {
155
+ const weightsPath = path.join(fullPath, 'weights.bin');
156
+ if (fs.existsSync(weightsPath)) return true;
157
+ }
158
+ if (entry === 'weights.bin') return true;
159
+ }
160
+ } catch (_) {}
161
+ return false;
162
+ }
163
+
164
+ export function getChromeVersion(executablePath) {
165
+ if (!executablePath) return null;
166
+
167
+ // On macOS, extract directly from Info.plist in < 1ms
168
+ if (process.platform === 'darwin') {
169
+ try {
170
+ const appIndex = executablePath.indexOf('.app');
171
+ if (appIndex !== -1) {
172
+ const plistPath = path.join(executablePath.slice(0, appIndex + 4), 'Contents', 'Info.plist');
173
+ if (fs.existsSync(plistPath)) {
174
+ const plistContent = fs.readFileSync(plistPath, 'utf8');
175
+ const match = plistContent.match(/<key>CFBundleShortVersionString<\/key>\s*<string>([^<]+)<\/string>/i);
176
+ if (match && match[1]) {
177
+ return match[1].trim();
178
+ }
179
+ }
180
+ }
181
+ } catch (_) {}
182
+ }
183
+
184
+ try {
185
+ const output = execFileSync(executablePath, ['--version'], {
186
+ stdio: ['ignore', 'pipe', 'ignore'],
187
+ encoding: 'utf8',
188
+ timeout: 5000
189
+ }).trim();
190
+ debug('detect', 'Raw version output:', output);
191
+ // Matches "Google Chrome 151.0.7922.174" or "Chromium 150.0.0.0"
192
+ const match = output.match(/(?:Google Chrome|Chromium|Chrome)\s+([\d.]+)/i);
193
+ if (match) return match[1];
194
+ return output;
195
+ } catch (err) {
196
+ debug('detect', 'Failed to get chrome version via CLI:', err.message);
197
+ return null;
198
+ }
199
+ }