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.
- package/README.md +291 -0
- package/bin/nanobridge.js +5 -0
- package/package.json +31 -0
- package/src/api/openai.js +115 -0
- package/src/benchmark/runner.js +48 -0
- package/src/benchmark/stats.js +33 -0
- package/src/chrome/bridge.js +446 -0
- package/src/chrome/detect.js +199 -0
- package/src/chrome/launch.js +214 -0
- package/src/cli.js +196 -0
- package/src/commands/ask.js +179 -0
- package/src/commands/bench.js +79 -0
- package/src/commands/chat.js +194 -0
- package/src/commands/daemon.js +61 -0
- package/src/commands/download.js +71 -0
- package/src/commands/serve.js +56 -0
- package/src/commands/status.js +78 -0
- package/src/daemon/client.js +186 -0
- package/src/daemon/server.js +494 -0
- package/src/daemon/state.js +49 -0
- package/src/utils/errors.js +26 -0
- package/src/utils/files.js +77 -0
- package/src/utils/output.js +59 -0
- package/test/cli.test.js +43 -0
- package/test/daemon.test.js +31 -0
- package/test/detect.test.js +24 -0
- package/test/files.test.js +36 -0
- package/test/openai.test.js +63 -0
- package/test/stats.test.js +29 -0
|
@@ -0,0 +1,214 @@
|
|
|
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><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. Create isolated temporary profile directory
|
|
41
|
+
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nanobridge-'));
|
|
42
|
+
debug('launch', 'Isolated user-data-dir at:', tmpDir);
|
|
43
|
+
|
|
44
|
+
// Symlink system model directory into the profile so model is immediately available
|
|
45
|
+
const systemModelDir = findSystemModelDir();
|
|
46
|
+
const profileModelDir = path.join(tmpDir, 'OptGuideOnDeviceModel');
|
|
47
|
+
if (systemModelDir && !fs.existsSync(profileModelDir)) {
|
|
48
|
+
try {
|
|
49
|
+
fs.symlinkSync(systemModelDir, profileModelDir, 'dir');
|
|
50
|
+
debug('launch', `Symlinked system model directory from ${systemModelDir} to ${profileModelDir}`);
|
|
51
|
+
} catch (err) {
|
|
52
|
+
debug('launch', `Could not symlink model dir: ${err.message}`);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// 3. Flags for Built-in AI / LanguageModel API & High-Performance Hardware Acceleration
|
|
57
|
+
const isDarwin = process.platform === 'darwin';
|
|
58
|
+
const chromeArgs = [
|
|
59
|
+
'--headless=new',
|
|
60
|
+
`--user-data-dir=${tmpDir}`,
|
|
61
|
+
'--remote-debugging-port=0',
|
|
62
|
+
'--no-first-run',
|
|
63
|
+
'--no-default-browser-check',
|
|
64
|
+
'--mute-audio',
|
|
65
|
+
'--disable-audio-output',
|
|
66
|
+
'--disable-speech-api',
|
|
67
|
+
'--disable-extensions',
|
|
68
|
+
'--disable-default-apps',
|
|
69
|
+
'--disable-sync',
|
|
70
|
+
'--disable-translate',
|
|
71
|
+
'--disable-background-networking',
|
|
72
|
+
'--disable-client-side-phishing-detection',
|
|
73
|
+
'--disable-component-extensions-with-background-pages',
|
|
74
|
+
'--disable-domain-reliability',
|
|
75
|
+
'--disable-breakpad',
|
|
76
|
+
'--disable-ipc-flooding-protection',
|
|
77
|
+
'--disable-popup-blocking',
|
|
78
|
+
'--disable-prompt-on-repost',
|
|
79
|
+
'--disable-hang-monitor',
|
|
80
|
+
'--disable-dev-shm-usage',
|
|
81
|
+
'--password-store=basic',
|
|
82
|
+
'--use-mock-keychain',
|
|
83
|
+
'--disable-background-timer-throttling',
|
|
84
|
+
'--disable-backgrounding-occluded-windows',
|
|
85
|
+
'--disable-renderer-backgrounding',
|
|
86
|
+
'--disable-features=CalculateNativeWinOcclusion,PaintHolding,Translate,MediaRouter,DialMediaRouteProvider,InterestFeedContentSuggestions',
|
|
87
|
+
'--ignore-gpu-blocklist',
|
|
88
|
+
'--enable-gpu-rasterization',
|
|
89
|
+
'--enable-zero-copy',
|
|
90
|
+
...(isDarwin ? ['--use-angle=metal', '--enable-metal'] : []),
|
|
91
|
+
'--enable-blink-features=AIPromptAPI,AIPromptAPIParams,AIPromptAPIStructuredOutput',
|
|
92
|
+
'--enable-features=PromptAPIForGeminiNano,OptimizationGuideOnDeviceModel',
|
|
93
|
+
'--optimization-guide-on-device-model-override-switch=bypass-ram-check',
|
|
94
|
+
...(options.extraArgs || []),
|
|
95
|
+
pageUrl
|
|
96
|
+
];
|
|
97
|
+
|
|
98
|
+
debug('launch', 'Spawning Chrome with arguments:', chromeArgs.join(' '));
|
|
99
|
+
|
|
100
|
+
const startTime = performance.now();
|
|
101
|
+
const isWindows = process.platform === 'win32';
|
|
102
|
+
const proc = spawn(executablePath, chromeArgs, {
|
|
103
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
104
|
+
detached: !isWindows
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
let isClosed = false;
|
|
108
|
+
const cleanup = () => {
|
|
109
|
+
if (isClosed) return;
|
|
110
|
+
isClosed = true;
|
|
111
|
+
debug('launch', 'Terminating Chrome instance...');
|
|
112
|
+
try {
|
|
113
|
+
if (proc.pid) {
|
|
114
|
+
if (!isWindows) {
|
|
115
|
+
try {
|
|
116
|
+
process.kill(-proc.pid, 'SIGKILL');
|
|
117
|
+
} catch (_) {
|
|
118
|
+
try { proc.kill('SIGKILL'); } catch (_) {}
|
|
119
|
+
}
|
|
120
|
+
} else {
|
|
121
|
+
try { proc.kill('SIGKILL'); } catch (_) {}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
} catch (_) {}
|
|
125
|
+
|
|
126
|
+
if (tmpDir && !isWindows) {
|
|
127
|
+
try {
|
|
128
|
+
execSync(`pkill -9 -f "${tmpDir}"`, { stdio: 'ignore' });
|
|
129
|
+
} catch (_) {}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
try {
|
|
133
|
+
server.close();
|
|
134
|
+
} catch (_) {}
|
|
135
|
+
|
|
136
|
+
try {
|
|
137
|
+
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
138
|
+
debug('launch', 'Cleaned up temporary user-data-dir:', tmpDir);
|
|
139
|
+
} catch (_) {}
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
const signalHandler = () => {
|
|
143
|
+
cleanup();
|
|
144
|
+
process.exit(130);
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
process.once('SIGINT', signalHandler);
|
|
148
|
+
process.once('SIGTERM', signalHandler);
|
|
149
|
+
process.once('exit', cleanup);
|
|
150
|
+
|
|
151
|
+
// 4. Wait for DevTools listening port from stderr
|
|
152
|
+
let cdpPort = null;
|
|
153
|
+
let cdpWsEndpoint = null;
|
|
154
|
+
|
|
155
|
+
try {
|
|
156
|
+
let timeoutId;
|
|
157
|
+
const devToolsPromise = new Promise((resolve, reject) => {
|
|
158
|
+
let stderrOutput = '';
|
|
159
|
+
let resolved = false;
|
|
160
|
+
|
|
161
|
+
const onData = (chunk) => {
|
|
162
|
+
stderrOutput += chunk.toString();
|
|
163
|
+
if (!resolved) {
|
|
164
|
+
const match = stderrOutput.match(/DevTools listening on (ws:\/\/127\.0\.0\.1:(\d+)\/[^\s]+)/);
|
|
165
|
+
if (match) {
|
|
166
|
+
resolved = true;
|
|
167
|
+
cdpWsEndpoint = match[1];
|
|
168
|
+
cdpPort = match[2];
|
|
169
|
+
resolve();
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
proc.stderr.on('data', onData);
|
|
175
|
+
proc.once('error', reject);
|
|
176
|
+
proc.once('exit', (code) => {
|
|
177
|
+
if (!cdpPort) {
|
|
178
|
+
reject(new ChromeUnavailableError(`Chrome exited unexpectedly with code ${code}. Stderr: ${stderrOutput}`));
|
|
179
|
+
}
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
timeoutId = setTimeout(() => {
|
|
183
|
+
reject(new ChromeUnavailableError(`Timed out waiting for Chrome DevTools endpoint. Stderr: ${stderrOutput}`));
|
|
184
|
+
}, options.launchTimeout || 15000);
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
await devToolsPromise;
|
|
188
|
+
if (timeoutId) clearTimeout(timeoutId);
|
|
189
|
+
|
|
190
|
+
const startupMs = performance.now() - startTime;
|
|
191
|
+
debug('launch', `Chrome launched in ${startupMs.toFixed(1)}ms. CDP Port: ${cdpPort}`);
|
|
192
|
+
|
|
193
|
+
return {
|
|
194
|
+
proc,
|
|
195
|
+
cdpPort,
|
|
196
|
+
cdpWsEndpoint,
|
|
197
|
+
serverPort,
|
|
198
|
+
pageUrl,
|
|
199
|
+
executablePath,
|
|
200
|
+
version,
|
|
201
|
+
tmpDir,
|
|
202
|
+
startupMs,
|
|
203
|
+
close: () => {
|
|
204
|
+
process.removeListener('SIGINT', signalHandler);
|
|
205
|
+
process.removeListener('SIGTERM', signalHandler);
|
|
206
|
+
process.removeListener('exit', cleanup);
|
|
207
|
+
cleanup();
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
} catch (err) {
|
|
211
|
+
cleanup();
|
|
212
|
+
throw err;
|
|
213
|
+
}
|
|
214
|
+
}
|
package/src/cli.js
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
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
|
+
const VERSION = '0.1.0';
|
|
13
|
+
|
|
14
|
+
export function printHelp() {
|
|
15
|
+
log(`
|
|
16
|
+
${style('NanoBridge', 'bold')} — Chrome Built-in AI CLI & OpenAI-Compatible Server
|
|
17
|
+
|
|
18
|
+
${style('USAGE:', 'bold')}
|
|
19
|
+
nanobridge <command> [options]
|
|
20
|
+
nanobridge chat Start interactive chat REPL session
|
|
21
|
+
cat file.txt | nanobridge ask "prompt"
|
|
22
|
+
|
|
23
|
+
${style('COMMANDS:', 'bold')}
|
|
24
|
+
chat Start interactive chat session with multi-turn memory
|
|
25
|
+
ask <prompt> Prompt the local on-device model (sub-second with warm daemon)
|
|
26
|
+
status Check Chrome installation, model availability, and daemon status
|
|
27
|
+
serve Start OpenAI-compatible API server (/v1/chat/completions)
|
|
28
|
+
download Download and prepare the Chrome on-device AI model components
|
|
29
|
+
bench Run benchmark measuring startup, TTFT, and generation rate
|
|
30
|
+
daemon [start|stop] Manage the background warm daemon process
|
|
31
|
+
stop Stop the running background daemon
|
|
32
|
+
|
|
33
|
+
${style('OPTIONS:', 'bold')}
|
|
34
|
+
-f, --file <path> Attach a local file context (can be specified multiple times)
|
|
35
|
+
--port <n> Port for serve command or daemon (default: 8000)
|
|
36
|
+
--host <ip> Host interface to bind (default: 127.0.0.1)
|
|
37
|
+
--json Output results in JSON format (for status, bench, download)
|
|
38
|
+
--debug Display diagnostic and CDP lifecycle information to stderr
|
|
39
|
+
--download Auto-download model components if not ready when asking
|
|
40
|
+
--no-stream Disable streaming response in ask command
|
|
41
|
+
--no-daemon Bypass background daemon and run cold standalone Chrome
|
|
42
|
+
--quick Run single quick benchmark pass (default in bench)
|
|
43
|
+
--runs <n> Number of benchmark iterations to compute percentiles (e.g. --runs 5)
|
|
44
|
+
-h, --help Show help information
|
|
45
|
+
-v, --version Show CLI version
|
|
46
|
+
|
|
47
|
+
${style('EXAMPLES:', 'bold')}
|
|
48
|
+
nanobridge status
|
|
49
|
+
nanobridge ask "Explain Web Locks simply"
|
|
50
|
+
nanobridge ask -f package.json "List dependencies"
|
|
51
|
+
nanobridge serve --port 8000
|
|
52
|
+
nanobridge daemon status
|
|
53
|
+
nanobridge stop
|
|
54
|
+
cat README.md | nanobridge ask "Summarize this document"
|
|
55
|
+
git diff | nanobridge ask "Review this git diff"
|
|
56
|
+
`);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function parseArgs(rawArgs) {
|
|
60
|
+
const args = rawArgs.slice(2);
|
|
61
|
+
let command = null;
|
|
62
|
+
const options = {
|
|
63
|
+
json: false,
|
|
64
|
+
debug: false,
|
|
65
|
+
download: false,
|
|
66
|
+
stream: true,
|
|
67
|
+
daemon: true,
|
|
68
|
+
port: 8000,
|
|
69
|
+
host: '127.0.0.1',
|
|
70
|
+
quick: false,
|
|
71
|
+
runs: 1,
|
|
72
|
+
help: false,
|
|
73
|
+
version: false,
|
|
74
|
+
files: [],
|
|
75
|
+
positional: []
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
for (let i = 0; i < args.length; i++) {
|
|
79
|
+
const arg = args[i];
|
|
80
|
+
if (arg === '--json') {
|
|
81
|
+
options.json = true;
|
|
82
|
+
} else if (arg === '--debug') {
|
|
83
|
+
options.debug = true;
|
|
84
|
+
} else if (arg === '--download') {
|
|
85
|
+
options.download = true;
|
|
86
|
+
} else if (arg === '--no-stream') {
|
|
87
|
+
options.stream = false;
|
|
88
|
+
} else if (arg === '--no-daemon') {
|
|
89
|
+
options.daemon = false;
|
|
90
|
+
} else if (arg === '-f' || arg === '--file') {
|
|
91
|
+
const next = args[++i];
|
|
92
|
+
if (next) options.files.push(next);
|
|
93
|
+
} else if (arg === '--port') {
|
|
94
|
+
const next = args[++i];
|
|
95
|
+
options.port = Number(next) || 8000;
|
|
96
|
+
} else if (arg === '--host') {
|
|
97
|
+
const next = args[++i];
|
|
98
|
+
options.host = next || '127.0.0.1';
|
|
99
|
+
} else if (arg === '--quick') {
|
|
100
|
+
options.quick = true;
|
|
101
|
+
} else if (arg === '--runs') {
|
|
102
|
+
const next = args[++i];
|
|
103
|
+
options.runs = Number(next) || 1;
|
|
104
|
+
} else if (arg === '-h' || arg === '--help' || arg === 'help') {
|
|
105
|
+
options.help = true;
|
|
106
|
+
} else if (arg === '-v' || arg === '--version' || arg === 'version') {
|
|
107
|
+
options.version = true;
|
|
108
|
+
} else if (!arg.startsWith('-') && !command) {
|
|
109
|
+
command = arg;
|
|
110
|
+
} else {
|
|
111
|
+
options.positional.push(arg);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
return { command, options };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export async function runCli(argv = process.argv) {
|
|
119
|
+
const { command, options } = parseArgs(argv);
|
|
120
|
+
|
|
121
|
+
if (options.json) setJsonMode(true);
|
|
122
|
+
if (options.debug) setDebugMode(true);
|
|
123
|
+
|
|
124
|
+
if (options.version) {
|
|
125
|
+
console.log(`nanobridge v${VERSION}`);
|
|
126
|
+
process.exit(0);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
if (options.help || !command) {
|
|
130
|
+
printHelp();
|
|
131
|
+
process.exit(0);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
try {
|
|
135
|
+
switch (command) {
|
|
136
|
+
case 'chat':
|
|
137
|
+
await handleChat(options);
|
|
138
|
+
break;
|
|
139
|
+
|
|
140
|
+
case 'status':
|
|
141
|
+
await handleStatus(options);
|
|
142
|
+
break;
|
|
143
|
+
|
|
144
|
+
case 'download':
|
|
145
|
+
await handleDownload(options);
|
|
146
|
+
break;
|
|
147
|
+
|
|
148
|
+
case 'ask': {
|
|
149
|
+
const promptText = options.positional.join(' ');
|
|
150
|
+
await handleAsk(promptText, options);
|
|
151
|
+
break;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
case 'serve':
|
|
155
|
+
await handleServe(options);
|
|
156
|
+
break;
|
|
157
|
+
|
|
158
|
+
case 'bench':
|
|
159
|
+
await handleBench(options);
|
|
160
|
+
break;
|
|
161
|
+
|
|
162
|
+
case 'daemon': {
|
|
163
|
+
const sub = options.positional[0] || 'status';
|
|
164
|
+
await handleDaemonCommand(sub, options);
|
|
165
|
+
break;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
case 'stop':
|
|
169
|
+
await handleDaemonCommand('stop', options);
|
|
170
|
+
break;
|
|
171
|
+
|
|
172
|
+
default:
|
|
173
|
+
if (!command && process.stdin.isTTY) {
|
|
174
|
+
await handleChat(options);
|
|
175
|
+
} else if (!command) {
|
|
176
|
+
printHelp();
|
|
177
|
+
} else {
|
|
178
|
+
logError(`Unknown command: ${command}`);
|
|
179
|
+
printHelp();
|
|
180
|
+
process.exit(1);
|
|
181
|
+
}
|
|
182
|
+
break;
|
|
183
|
+
}
|
|
184
|
+
process.exit(0);
|
|
185
|
+
} catch (err) {
|
|
186
|
+
if (err instanceof NanoBridgeError) {
|
|
187
|
+
logError(style('Error:', 'red'));
|
|
188
|
+
logError(err.message);
|
|
189
|
+
process.exit(err.exitCode || 1);
|
|
190
|
+
}
|
|
191
|
+
if (options.debug) {
|
|
192
|
+
console.error(err);
|
|
193
|
+
}
|
|
194
|
+
process.exit(1);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import process from 'node:process';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import { launchChrome } from '../chrome/launch.js';
|
|
4
|
+
import { ChromeBridge } from '../chrome/bridge.js';
|
|
5
|
+
import { ensureDaemon, streamPromptFromDaemon } from '../daemon/client.js';
|
|
6
|
+
import { style, log, logError, debug } from '../utils/output.js';
|
|
7
|
+
import { ModelUnavailableError, NanoBridgeError } from '../utils/errors.js';
|
|
8
|
+
import { readFileContent, formatFileAsContext, extractAndAttachFiles } from '../utils/files.js';
|
|
9
|
+
|
|
10
|
+
export async function readStdin() {
|
|
11
|
+
if (process.stdin.isTTY) {
|
|
12
|
+
return null;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
try {
|
|
16
|
+
const stats = fs.fstatSync(0);
|
|
17
|
+
if (!stats.isFIFO() && !stats.isFile()) {
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
} catch (_) {
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
return new Promise((resolve) => {
|
|
25
|
+
let data = '';
|
|
26
|
+
process.stdin.setEncoding('utf8');
|
|
27
|
+
|
|
28
|
+
const onData = (chunk) => {
|
|
29
|
+
data += chunk;
|
|
30
|
+
};
|
|
31
|
+
const onEnd = () => {
|
|
32
|
+
cleanup();
|
|
33
|
+
resolve(data.trim() ? data : null);
|
|
34
|
+
};
|
|
35
|
+
const onError = () => {
|
|
36
|
+
cleanup();
|
|
37
|
+
resolve(null);
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
const cleanup = () => {
|
|
41
|
+
process.stdin.off('data', onData);
|
|
42
|
+
process.stdin.off('end', onEnd);
|
|
43
|
+
process.stdin.off('error', onError);
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
process.stdin.on('data', onData);
|
|
47
|
+
process.stdin.on('end', onEnd);
|
|
48
|
+
process.stdin.on('error', onError);
|
|
49
|
+
|
|
50
|
+
const timer = setTimeout(() => {
|
|
51
|
+
cleanup();
|
|
52
|
+
resolve(data.trim() ? data : null);
|
|
53
|
+
}, 150);
|
|
54
|
+
if (timer.unref) timer.unref();
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function combinePromptAndContext(promptText, stdinContext) {
|
|
59
|
+
if (stdinContext && promptText) {
|
|
60
|
+
return `Context:\n${stdinContext}\n\nTask / Question:\n${promptText}`;
|
|
61
|
+
}
|
|
62
|
+
if (stdinContext) {
|
|
63
|
+
return stdinContext;
|
|
64
|
+
}
|
|
65
|
+
return promptText || '';
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export async function handleAsk(promptArg, options = {}) {
|
|
69
|
+
const stdinContent = await readStdin();
|
|
70
|
+
|
|
71
|
+
// 1. Process files from -f / --file flags
|
|
72
|
+
const flagFileContexts = [];
|
|
73
|
+
if (options.files && options.files.length > 0) {
|
|
74
|
+
for (const rawPath of options.files) {
|
|
75
|
+
try {
|
|
76
|
+
const fileInfo = readFileContent(rawPath);
|
|
77
|
+
flagFileContexts.push(formatFileAsContext(fileInfo));
|
|
78
|
+
debug('ask', `Attached file via flag: ${fileInfo.relativePath} (${fileInfo.size} bytes)`);
|
|
79
|
+
} catch (err) {
|
|
80
|
+
logError(`Error reading file "${rawPath}": ${err.message}`);
|
|
81
|
+
process.exit(1);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// 2. Process @file mentions in prompt text
|
|
87
|
+
const { finalPrompt: expandedPrompt, attachedFiles } = extractAndAttachFiles(promptArg || '');
|
|
88
|
+
if (attachedFiles.length > 0) {
|
|
89
|
+
debug('ask', `Extracted @file mentions: ${attachedFiles.map(f => f.relativePath).join(', ')}`);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// 3. Combine file contexts, stdin, and prompt
|
|
93
|
+
let combinedContext = flagFileContexts.join('\n\n');
|
|
94
|
+
if (stdinContent) {
|
|
95
|
+
combinedContext = combinedContext ? `${combinedContext}\n\n${stdinContent}` : stdinContent;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const finalPrompt = combinePromptAndContext(expandedPrompt, combinedContext);
|
|
99
|
+
|
|
100
|
+
if (!finalPrompt.trim()) {
|
|
101
|
+
logError('Error: No prompt, file, or stdin input provided.');
|
|
102
|
+
logError(`Usage: ${style('nanobridge ask "your prompt"', 'bold')} or ${style('nanobridge ask -f file.js "review"', 'bold')}`);
|
|
103
|
+
process.exit(1);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const useDaemon = options.daemon !== false;
|
|
107
|
+
|
|
108
|
+
if (useDaemon) {
|
|
109
|
+
try {
|
|
110
|
+
debug('ask', 'Attempting prompt via background daemon...');
|
|
111
|
+
const daemon = await ensureDaemon();
|
|
112
|
+
const stream = options.stream !== false;
|
|
113
|
+
|
|
114
|
+
let fullOutput = '';
|
|
115
|
+
if (stream) {
|
|
116
|
+
fullOutput = await streamPromptFromDaemon({
|
|
117
|
+
port: daemon.port,
|
|
118
|
+
promptText: finalPrompt,
|
|
119
|
+
systemPrompt: options.system,
|
|
120
|
+
stream: true,
|
|
121
|
+
onChunk: (delta) => {
|
|
122
|
+
process.stdout.write(delta);
|
|
123
|
+
}
|
|
124
|
+
});
|
|
125
|
+
if (!fullOutput.endsWith('\n')) {
|
|
126
|
+
process.stdout.write('\n');
|
|
127
|
+
}
|
|
128
|
+
} else {
|
|
129
|
+
fullOutput = await streamPromptFromDaemon({
|
|
130
|
+
port: daemon.port,
|
|
131
|
+
promptText: finalPrompt,
|
|
132
|
+
systemPrompt: options.system,
|
|
133
|
+
stream: false
|
|
134
|
+
});
|
|
135
|
+
process.stdout.write(fullOutput + (fullOutput.endsWith('\n') ? '' : '\n'));
|
|
136
|
+
}
|
|
137
|
+
return;
|
|
138
|
+
} catch (err) {
|
|
139
|
+
debug('ask', 'Daemon prompt failed, falling back to standalone launch:', err.message);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// Standalone fallback (or --no-daemon)
|
|
144
|
+
let chromeInstance = null;
|
|
145
|
+
let bridge = null;
|
|
146
|
+
|
|
147
|
+
try {
|
|
148
|
+
chromeInstance = await launchChrome(options);
|
|
149
|
+
bridge = new ChromeBridge(chromeInstance);
|
|
150
|
+
await bridge.connect();
|
|
151
|
+
|
|
152
|
+
const stream = options.stream !== false;
|
|
153
|
+
let fullOutput = '';
|
|
154
|
+
|
|
155
|
+
if (stream) {
|
|
156
|
+
fullOutput = await bridge.prompt({
|
|
157
|
+
promptText: finalPrompt,
|
|
158
|
+
systemPrompt: options.system,
|
|
159
|
+
stream: true,
|
|
160
|
+
onChunk: (delta) => {
|
|
161
|
+
process.stdout.write(delta);
|
|
162
|
+
}
|
|
163
|
+
});
|
|
164
|
+
if (!fullOutput.endsWith('\n')) {
|
|
165
|
+
process.stdout.write('\n');
|
|
166
|
+
}
|
|
167
|
+
} else {
|
|
168
|
+
fullOutput = await bridge.prompt({
|
|
169
|
+
promptText: finalPrompt,
|
|
170
|
+
systemPrompt: options.system,
|
|
171
|
+
stream: false
|
|
172
|
+
});
|
|
173
|
+
process.stdout.write(fullOutput + (fullOutput.endsWith('\n') ? '' : '\n'));
|
|
174
|
+
}
|
|
175
|
+
} finally {
|
|
176
|
+
if (bridge) await bridge.close();
|
|
177
|
+
if (chromeInstance) chromeInstance.close();
|
|
178
|
+
}
|
|
179
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { launchChrome } from '../chrome/launch.js';
|
|
2
|
+
import { ChromeBridge } from '../chrome/bridge.js';
|
|
3
|
+
import { runBenchmark } from '../benchmark/runner.js';
|
|
4
|
+
import { style, log, logError } from '../utils/output.js';
|
|
5
|
+
import { ModelUnavailableError } from '../utils/errors.js';
|
|
6
|
+
|
|
7
|
+
export async function handleBench(options = {}) {
|
|
8
|
+
let chromeInstance = null;
|
|
9
|
+
let bridge = null;
|
|
10
|
+
|
|
11
|
+
try {
|
|
12
|
+
const runs = options.quick ? 1 : (Number(options.runs) || 1);
|
|
13
|
+
|
|
14
|
+
chromeInstance = await launchChrome(options);
|
|
15
|
+
bridge = new ChromeBridge(chromeInstance);
|
|
16
|
+
await bridge.connect();
|
|
17
|
+
|
|
18
|
+
const benchResult = await runBenchmark(bridge, {
|
|
19
|
+
runs,
|
|
20
|
+
prompt: options.prompt
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
if (options.json) {
|
|
24
|
+
const jsonOutput = {
|
|
25
|
+
chrome: {
|
|
26
|
+
version: chromeInstance.version || 'unknown',
|
|
27
|
+
startupMs: Number(chromeInstance.startupMs.toFixed(1))
|
|
28
|
+
},
|
|
29
|
+
benchmark: {
|
|
30
|
+
runs: benchResult.runsCount,
|
|
31
|
+
coldRun: benchResult.coldRun,
|
|
32
|
+
warmRuns: benchResult.warmRuns,
|
|
33
|
+
stats: benchResult.stats
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
console.log(JSON.stringify(jsonOutput, null, 2));
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const pad = (label, width = 20) => label.padEnd(width, ' ');
|
|
41
|
+
const padVal = (val, unit = 'ms') => `${String(val).padStart(8, ' ')} ${unit}`;
|
|
42
|
+
|
|
43
|
+
if (runs === 1) {
|
|
44
|
+
const single = benchResult.runs[0];
|
|
45
|
+
const total = Number(chromeInstance.startupMs + single.totalInferenceMs).toFixed(0);
|
|
46
|
+
|
|
47
|
+
log(style('NanoBridge Benchmark', 'bold') + '\n');
|
|
48
|
+
log(`${pad('Chrome startup')}${padVal(chromeInstance.startupMs.toFixed(0))}`);
|
|
49
|
+
log(`${pad('Session creation')}${padVal(single.sessionCreateMs.toFixed(0))}`);
|
|
50
|
+
log(`${pad('TTFT')}${padVal(single.ttftMs !== null ? single.ttftMs.toFixed(0) : 'N/A')}`);
|
|
51
|
+
log(`${pad('Generation')}${padVal(single.generationMs.toFixed(0))}`);
|
|
52
|
+
log(`${pad('Total')}${padVal(total)}\n`);
|
|
53
|
+
|
|
54
|
+
log(`${pad('Output chars')}${String(single.outputChars).padStart(8, ' ')}`);
|
|
55
|
+
log(`${pad('Generation rate')}${padVal(single.generationRate.toFixed(0), 'chars/s')}`);
|
|
56
|
+
} else {
|
|
57
|
+
log(style(`NanoBridge Benchmark (${runs} runs)`, 'bold') + '\n');
|
|
58
|
+
log(`${pad('Chrome startup')}${padVal(chromeInstance.startupMs.toFixed(0))}\n`);
|
|
59
|
+
|
|
60
|
+
const printMetricBlock = (title, metricKey, unit = 'ms') => {
|
|
61
|
+
const s = benchResult.stats[metricKey];
|
|
62
|
+
log(style(title, 'bold'));
|
|
63
|
+
log(`${pad(' min')}${padVal(s.min, unit)}`);
|
|
64
|
+
log(`${pad(' avg')}${padVal(s.avg, unit)}`);
|
|
65
|
+
log(`${pad(' p50')}${padVal(s.p50, unit)}`);
|
|
66
|
+
log(`${pad(' p95')}${padVal(s.p95, unit)}\n`);
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
printMetricBlock('TTFT (Time To First Token/Chunk)', 'ttftMs', 'ms');
|
|
70
|
+
printMetricBlock('Session creation', 'sessionCreateMs', 'ms');
|
|
71
|
+
printMetricBlock('Generation duration', 'generationMs', 'ms');
|
|
72
|
+
printMetricBlock('Total inference', 'totalInferenceMs', 'ms');
|
|
73
|
+
printMetricBlock('Generation rate', 'generationRateCharsPerSec', 'chars/s');
|
|
74
|
+
}
|
|
75
|
+
} finally {
|
|
76
|
+
if (bridge) await bridge.close();
|
|
77
|
+
if (chromeInstance) chromeInstance.close();
|
|
78
|
+
}
|
|
79
|
+
}
|