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,199 +0,0 @@
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
- }
@@ -1,248 +0,0 @@
1
- import { spawn, execSync } from 'node:child_process';
2
- import http from 'node:http';
3
- import fs from 'node:fs';
4
- import os from 'node:os';
5
- import path from 'node:path';
6
- import process from 'node:process';
7
- import { findChromeExecutable, getChromeVersion, findSystemModelDir } from './detect.js';
8
- import { ChromeUnavailableError } from '../utils/errors.js';
9
- import { debug } from '../utils/output.js';
10
-
11
- export async function launchChrome(options = {}) {
12
- const executablePath = options.executablePath || findChromeExecutable();
13
- if (!executablePath) {
14
- throw new ChromeUnavailableError(
15
- 'Chrome executable was not found on your system. Please install Google Chrome or set the CHROME_PATH environment variable.'
16
- );
17
- }
18
-
19
- const version = options.version || getChromeVersion(executablePath);
20
- debug('launch', 'Using Chrome executable:', executablePath, 'version:', version);
21
-
22
- // 1. Create ephemeral localhost HTTP server for secure context
23
- const server = http.createServer((req, res) => {
24
- res.writeHead(200, {
25
- 'Content-Type': 'text/html; charset=utf-8',
26
- 'Cache-Control': 'no-cache'
27
- });
28
- res.end('<!DOCTYPE html><html><head><meta charset="utf-8"><title>NanoBridge Host</title></head><body><h1>NanoBridge</h1></body></html>');
29
- });
30
-
31
- await new Promise((resolve, reject) => {
32
- server.listen(0, '127.0.0.1', () => resolve());
33
- server.on('error', reject);
34
- });
35
-
36
- const serverPort = server.address().port;
37
- const pageUrl = `http://localhost:${serverPort}/`;
38
- debug('launch', 'Ephemeral host server listening at:', pageUrl);
39
-
40
- // 2. Setup user-data-dir (persistent by default to preserve GPU shader & Metal pipeline caches)
41
- const defaultProfileDir = path.join(os.homedir(), '.nanobridge', 'profile');
42
- const lockPath = path.join(defaultProfileDir, 'SingletonLock');
43
- let isLocked = false;
44
-
45
- if (!options.userDataDir && !options.isolated) {
46
- try {
47
- const linkTarget = fs.readlinkSync(lockPath);
48
- const pidMatch = linkTarget.match(/-(\d+)$/);
49
- if (pidMatch && pidMatch[1]) {
50
- try {
51
- process.kill(Number(pidMatch[1]), 0);
52
- isLocked = true;
53
- debug('launch', `Default profile is locked by running Chrome PID ${pidMatch[1]}. Using isolated profile.`);
54
- } catch (_) {
55
- try { fs.unlinkSync(lockPath); } catch (_) {}
56
- }
57
- }
58
- } catch (_) {}
59
- }
60
-
61
- const isTemporary = Boolean(options.isolated || isLocked);
62
- const userDataDir = options.userDataDir || (isTemporary
63
- ? fs.mkdtempSync(path.join(os.tmpdir(), 'nanobridge-'))
64
- : defaultProfileDir);
65
-
66
- if (!fs.existsSync(userDataDir)) {
67
- fs.mkdirSync(userDataDir, { recursive: true });
68
- }
69
- debug('launch', 'Chrome user-data-dir at:', userDataDir, `(persistent: ${!isTemporary})`);
70
-
71
- // Symlink system model directory into the profile so model is immediately available
72
- const systemModelDir = findSystemModelDir();
73
- const profileModelDir = path.join(userDataDir, 'OptGuideOnDeviceModel');
74
- if (systemModelDir && !fs.existsSync(profileModelDir)) {
75
- try {
76
- fs.symlinkSync(systemModelDir, profileModelDir, 'dir');
77
- debug('launch', `Symlinked system model directory from ${systemModelDir} to ${profileModelDir}`);
78
- } catch (err) {
79
- debug('launch', `Could not symlink model dir: ${err.message}`);
80
- }
81
- }
82
-
83
- // 3. Flags for Built-in AI / LanguageModel API & High-Performance Hardware Acceleration
84
- const isDarwin = process.platform === 'darwin';
85
- const chromeArgs = [
86
- '--headless=new',
87
- `--user-data-dir=${userDataDir}`,
88
- '--remote-debugging-port=0',
89
- '--no-first-run',
90
- '--no-default-browser-check',
91
- '--mute-audio',
92
- '--disable-audio-output',
93
- '--disable-speech-api',
94
- '--disable-extensions',
95
- '--disable-default-apps',
96
- '--disable-sync',
97
- '--disable-translate',
98
- '--disable-background-networking',
99
- '--disable-client-side-phishing-detection',
100
- '--disable-component-extensions-with-background-pages',
101
- '--disable-domain-reliability',
102
- '--disable-breakpad',
103
- '--disable-ipc-flooding-protection',
104
- '--disable-popup-blocking',
105
- '--disable-prompt-on-repost',
106
- '--disable-hang-monitor',
107
- ...(isDarwin ? [] : ['--disable-dev-shm-usage']),
108
- '--password-store=basic',
109
- '--use-mock-keychain',
110
- '--disable-background-timer-throttling',
111
- '--disable-backgrounding-occluded-windows',
112
- '--disable-renderer-backgrounding',
113
- '--disable-features=CalculateNativeWinOcclusion,PaintHolding,Translate,MediaRouter,DialMediaRouteProvider,InterestFeedContentSuggestions',
114
- '--ignore-gpu-blocklist',
115
- '--enable-gpu-rasterization',
116
- '--enable-zero-copy',
117
- ...(isDarwin ? ['--use-angle=metal'] : []),
118
- '--window-size=1280,800',
119
- '--enable-blink-features=AIPromptAPI',
120
- '--enable-features=PromptAPIForGeminiNano,OptimizationGuideOnDeviceModel',
121
- '--optimization-guide-on-device-model-override-switch=bypass-ram-check',
122
- ...(options.extraArgs || []),
123
- pageUrl
124
- ];
125
-
126
- debug('launch', 'Spawning Chrome with arguments:', chromeArgs.join(' '));
127
-
128
- const startTime = performance.now();
129
- const isWindows = process.platform === 'win32';
130
- const proc = spawn(executablePath, chromeArgs, {
131
- stdio: ['ignore', 'pipe', 'pipe'],
132
- detached: !isWindows
133
- });
134
-
135
- let isClosed = false;
136
- const cleanup = () => {
137
- if (isClosed) return;
138
- isClosed = true;
139
- debug('launch', 'Terminating Chrome instance...');
140
- try {
141
- if (proc.pid) {
142
- if (!isWindows) {
143
- try {
144
- execSync(`pkill -9 -P ${proc.pid}`, { stdio: 'ignore' });
145
- } catch (_) {}
146
- try {
147
- process.kill(-proc.pid, 'SIGKILL');
148
- } catch (_) {
149
- try { proc.kill('SIGKILL'); } catch (_) {}
150
- }
151
- } else {
152
- try { proc.kill('SIGKILL'); } catch (_) {}
153
- }
154
- }
155
- } catch (_) {}
156
-
157
- if (userDataDir && !isWindows) {
158
- try {
159
- execSync(`pkill -9 -f "${userDataDir}"`, { stdio: 'ignore' });
160
- } catch (_) {}
161
- }
162
-
163
- try {
164
- server.close();
165
- } catch (_) {}
166
-
167
- if (isTemporary) {
168
- try {
169
- fs.rmSync(userDataDir, { recursive: true, force: true });
170
- debug('launch', 'Cleaned up temporary user-data-dir:', userDataDir);
171
- } catch (_) {}
172
- }
173
- };
174
-
175
- const signalHandler = () => {
176
- cleanup();
177
- process.exit(130);
178
- };
179
-
180
- process.once('SIGINT', signalHandler);
181
- process.once('SIGTERM', signalHandler);
182
- process.once('exit', cleanup);
183
-
184
- // 4. Wait for DevTools listening port from stderr
185
- let cdpPort = null;
186
- let cdpWsEndpoint = null;
187
-
188
- try {
189
- let timeoutId;
190
- const devToolsPromise = new Promise((resolve, reject) => {
191
- let stderrOutput = '';
192
- let resolved = false;
193
-
194
- const onData = (chunk) => {
195
- stderrOutput += chunk.toString();
196
- if (!resolved) {
197
- const match = stderrOutput.match(/DevTools listening on (ws:\/\/127\.0\.0\.1:(\d+)\/[^\s]+)/);
198
- if (match) {
199
- resolved = true;
200
- cdpWsEndpoint = match[1];
201
- cdpPort = match[2];
202
- resolve();
203
- }
204
- }
205
- };
206
-
207
- proc.stderr.on('data', onData);
208
- proc.once('error', reject);
209
- proc.once('exit', (code) => {
210
- if (!cdpPort) {
211
- reject(new ChromeUnavailableError(`Chrome exited unexpectedly with code ${code}. Stderr: ${stderrOutput}`));
212
- }
213
- });
214
-
215
- timeoutId = setTimeout(() => {
216
- reject(new ChromeUnavailableError(`Timed out waiting for Chrome DevTools endpoint. Stderr: ${stderrOutput}`));
217
- }, options.launchTimeout || 15000);
218
- });
219
-
220
- await devToolsPromise;
221
- if (timeoutId) clearTimeout(timeoutId);
222
-
223
- const startupMs = performance.now() - startTime;
224
- debug('launch', `Chrome launched in ${startupMs.toFixed(1)}ms. CDP Port: ${cdpPort}`);
225
-
226
- return {
227
- proc,
228
- cdpPort,
229
- cdpWsEndpoint,
230
- serverPort,
231
- pageUrl,
232
- executablePath,
233
- version,
234
- userDataDir,
235
- tmpDir: userDataDir,
236
- startupMs,
237
- close: () => {
238
- process.removeListener('SIGINT', signalHandler);
239
- process.removeListener('SIGTERM', signalHandler);
240
- process.removeListener('exit', cleanup);
241
- cleanup();
242
- }
243
- };
244
- } catch (err) {
245
- cleanup();
246
- throw err;
247
- }
248
- }
package/src/cli.js DELETED
@@ -1,216 +0,0 @@
1
- import process from 'node:process';
2
- import { handleStatus } from './commands/status.js';
3
- import { handleDownload } from './commands/download.js';
4
- import { handleAsk } from './commands/ask.js';
5
- import { handleChat } from './commands/chat.js';
6
- import { handleBench } from './commands/bench.js';
7
- import { handleDaemonCommand } from './commands/daemon.js';
8
- import { handleServe } from './commands/serve.js';
9
- import { setJsonMode, setDebugMode, log, logError, style } from './utils/output.js';
10
- import { NanoBridgeError } from './utils/errors.js';
11
-
12
- import fs from 'node:fs';
13
- import path from 'node:path';
14
- import { fileURLToPath } from 'node:url';
15
-
16
- const __filename = fileURLToPath(import.meta.url);
17
- const __dirname = path.dirname(__filename);
18
- let VERSION = '0.2.0';
19
- try {
20
- const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, '../package.json'), 'utf8'));
21
- if (pkg.version) VERSION = pkg.version;
22
- } catch (_) {}
23
-
24
- export function printHelp() {
25
- log(`
26
- ${style('NanoBridge', 'bold')} — Chrome Built-in AI CLI & OpenAI-Compatible Server
27
-
28
- ${style('USAGE:', 'bold')}
29
- nanobridge <command> [options]
30
- nanobridge chat Start interactive chat REPL session
31
- cat file.txt | nanobridge ask "prompt"
32
-
33
- ${style('COMMANDS:', 'bold')}
34
- chat Start interactive chat session with multi-turn memory
35
- ask <prompt> Prompt the local on-device model (sub-second with warm daemon)
36
- status Check Chrome installation, model availability, and daemon status
37
- serve Start OpenAI-compatible API server (/v1/chat/completions)
38
- download Download and prepare the Chrome on-device AI model components
39
- bench Run benchmark measuring startup, TTFT, and generation rate
40
- daemon [start|stop|restart|reset] Manage the background warm daemon process
41
- reset Reset the active model session and clear KV context cache
42
- restart Restart the background warm daemon
43
- stop Stop the running background daemon
44
-
45
- ${style('OPTIONS:', 'bold')}
46
- -f, --file <path> Attach a local file context (can be specified multiple times)
47
- --port <n> Port for serve command or daemon (default: 8000)
48
- --host <ip> Host interface to bind (default: 127.0.0.1)
49
- --json Output results in JSON format (for status, bench, download)
50
- --debug Display diagnostic and CDP lifecycle information to stderr
51
- --download Auto-download model components if not ready when asking
52
- --no-stream Disable streaming response in ask command
53
- --no-daemon Bypass background daemon and run cold standalone Chrome
54
- --quick Run single quick benchmark pass (default in bench)
55
- --runs <n> Number of benchmark iterations to compute percentiles (e.g. --runs 5)
56
- -h, --help Show help information
57
- -v, --version Show CLI version
58
-
59
- ${style('EXAMPLES:', 'bold')}
60
- nanobridge status
61
- nanobridge ask "Explain Web Locks simply"
62
- nanobridge ask -f package.json "List dependencies"
63
- nanobridge serve --port 8000
64
- nanobridge daemon status
65
- nanobridge stop
66
- cat README.md | nanobridge ask "Summarize this document"
67
- git diff | nanobridge ask "Review this git diff"
68
- `);
69
- }
70
-
71
- export function parseArgs(rawArgs) {
72
- const args = rawArgs.slice(2);
73
- let command = null;
74
- const options = {
75
- json: false,
76
- debug: false,
77
- download: false,
78
- stream: true,
79
- daemon: true,
80
- port: 8000,
81
- host: '127.0.0.1',
82
- quick: false,
83
- runs: 1,
84
- help: false,
85
- version: false,
86
- files: [],
87
- positional: []
88
- };
89
-
90
- for (let i = 0; i < args.length; i++) {
91
- const arg = args[i];
92
- if (arg === '--json') {
93
- options.json = true;
94
- } else if (arg === '--debug') {
95
- options.debug = true;
96
- } else if (arg === '--download') {
97
- options.download = true;
98
- } else if (arg === '--no-stream') {
99
- options.stream = false;
100
- } else if (arg === '--no-daemon') {
101
- options.daemon = false;
102
- } else if (arg === '-f' || arg === '--file') {
103
- const next = args[++i];
104
- if (next) options.files.push(next);
105
- } else if (arg === '--port') {
106
- const next = args[++i];
107
- options.port = Number(next) || 8000;
108
- } else if (arg === '--host') {
109
- const next = args[++i];
110
- options.host = next || '127.0.0.1';
111
- } else if (arg === '--quick') {
112
- options.quick = true;
113
- } else if (arg === '--runs') {
114
- const next = args[++i];
115
- options.runs = Number(next) || 1;
116
- } else if (arg === '-h' || arg === '--help' || arg === 'help') {
117
- options.help = true;
118
- } else if (arg === '-v' || arg === '--version' || arg === 'version') {
119
- options.version = true;
120
- } else if (!arg.startsWith('-') && !command) {
121
- command = arg;
122
- } else {
123
- options.positional.push(arg);
124
- }
125
- }
126
-
127
- return { command, options };
128
- }
129
-
130
- export async function runCli(argv = process.argv) {
131
- const { command, options } = parseArgs(argv);
132
-
133
- if (options.json) setJsonMode(true);
134
- if (options.debug) setDebugMode(true);
135
-
136
- if (options.version) {
137
- console.log(`nanobridge v${VERSION}`);
138
- process.exit(0);
139
- }
140
-
141
- if (options.help || !command) {
142
- printHelp();
143
- process.exit(0);
144
- }
145
-
146
- try {
147
- switch (command) {
148
- case 'chat':
149
- await handleChat(options);
150
- break;
151
-
152
- case 'status':
153
- await handleStatus(options);
154
- break;
155
-
156
- case 'download':
157
- await handleDownload(options);
158
- break;
159
-
160
- case 'ask': {
161
- const promptText = options.positional.join(' ');
162
- await handleAsk(promptText, options);
163
- break;
164
- }
165
-
166
- case 'serve':
167
- await handleServe(options);
168
- break;
169
-
170
- case 'bench':
171
- await handleBench(options);
172
- break;
173
-
174
- case 'daemon': {
175
- const sub = options.positional[0] || 'status';
176
- await handleDaemonCommand(sub, options);
177
- break;
178
- }
179
-
180
- case 'reset':
181
- await handleDaemonCommand('reset', options);
182
- break;
183
-
184
- case 'restart':
185
- await handleDaemonCommand('restart', options);
186
- break;
187
-
188
- case 'stop':
189
- await handleDaemonCommand('stop', options);
190
- break;
191
-
192
- default:
193
- if (!command && process.stdin.isTTY) {
194
- await handleChat(options);
195
- } else if (!command) {
196
- printHelp();
197
- } else {
198
- logError(`Unknown command: ${command}`);
199
- printHelp();
200
- process.exit(1);
201
- }
202
- break;
203
- }
204
- process.exit(0);
205
- } catch (err) {
206
- if (err instanceof NanoBridgeError) {
207
- logError(style('Error:', 'red'));
208
- logError(err.message);
209
- process.exit(err.exitCode || 1);
210
- }
211
- if (options.debug) {
212
- console.error(err);
213
- }
214
- process.exit(1);
215
- }
216
- }