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.
- package/README.md +86 -230
- package/bin/nanobridge.js +1 -1
- package/dist/api/openai.d.ts +135 -0
- package/dist/api/openai.js +210 -0
- package/dist/api/openai.js.map +1 -0
- package/dist/benchmark/runner.d.ts +27 -0
- package/dist/benchmark/runner.js +37 -0
- package/dist/benchmark/runner.js.map +1 -0
- package/dist/benchmark/stats.d.ts +10 -0
- package/dist/benchmark/stats.js +33 -0
- package/dist/benchmark/stats.js.map +1 -0
- package/dist/bin/nanobridge.d.ts +2 -0
- package/dist/bin/nanobridge.js +4 -0
- package/dist/bin/nanobridge.js.map +1 -0
- package/dist/chat/commands.d.ts +9 -0
- package/dist/chat/commands.js +52 -0
- package/dist/chat/commands.js.map +1 -0
- package/dist/chat/config.d.ts +22 -0
- package/dist/chat/config.js +55 -0
- package/dist/chat/config.js.map +1 -0
- package/dist/chat/history.d.ts +12 -0
- package/dist/chat/history.js +74 -0
- package/dist/chat/history.js.map +1 -0
- package/dist/chat/session.d.ts +42 -0
- package/dist/chat/session.js +107 -0
- package/dist/chat/session.js.map +1 -0
- package/dist/chat/storage.d.ts +17 -0
- package/dist/chat/storage.js +71 -0
- package/dist/chat/storage.js.map +1 -0
- package/dist/cli.d.ts +7 -0
- package/dist/cli.js +363 -0
- package/dist/cli.js.map +1 -0
- package/dist/commands/ask.d.ts +4 -0
- package/dist/commands/ask.js +288 -0
- package/dist/commands/ask.js.map +1 -0
- package/dist/commands/bench.d.ts +2 -0
- package/dist/commands/bench.js +92 -0
- package/dist/commands/bench.js.map +1 -0
- package/dist/commands/chat.d.ts +2 -0
- package/dist/commands/chat.js +701 -0
- package/dist/commands/chat.js.map +1 -0
- package/dist/commands/config.d.ts +2 -0
- package/dist/commands/config.js +102 -0
- package/dist/commands/config.js.map +1 -0
- package/dist/commands/daemon.d.ts +2 -0
- package/dist/commands/daemon.js +225 -0
- package/dist/commands/daemon.js.map +1 -0
- package/dist/commands/embed.d.ts +2 -0
- package/dist/commands/embed.js +79 -0
- package/dist/commands/embed.js.map +1 -0
- package/dist/commands/models.d.ts +5 -0
- package/dist/commands/models.js +244 -0
- package/dist/commands/models.js.map +1 -0
- package/dist/commands/serve.d.ts +2 -0
- package/dist/commands/serve.js +52 -0
- package/dist/commands/serve.js.map +1 -0
- package/dist/commands/status.d.ts +2 -0
- package/dist/commands/status.js +81 -0
- package/dist/commands/status.js.map +1 -0
- package/dist/daemon/client.d.ts +74 -0
- package/dist/daemon/client.js +447 -0
- package/dist/daemon/client.js.map +1 -0
- package/dist/daemon/server.d.ts +43 -0
- package/dist/daemon/server.js +661 -0
- package/dist/daemon/server.js.map +1 -0
- package/dist/daemon/service.d.ts +29 -0
- package/dist/daemon/service.js +173 -0
- package/dist/daemon/service.js.map +1 -0
- package/dist/daemon/state.d.ts +4 -0
- package/dist/daemon/state.js +54 -0
- package/dist/daemon/state.js.map +1 -0
- package/dist/engine/llama-engine.d.ts +49 -0
- package/dist/engine/llama-engine.js +465 -0
- package/dist/engine/llama-engine.js.map +1 -0
- package/dist/engine/model-pool.d.ts +36 -0
- package/dist/engine/model-pool.js +202 -0
- package/dist/engine/model-pool.js.map +1 -0
- package/dist/engine/sampling.d.ts +13 -0
- package/dist/engine/sampling.js +43 -0
- package/dist/engine/sampling.js.map +1 -0
- package/dist/models/catalog.d.ts +6 -0
- package/dist/models/catalog.js +124 -0
- package/dist/models/catalog.js.map +1 -0
- package/dist/models/config.d.ts +10 -0
- package/dist/models/config.js +141 -0
- package/dist/models/config.js.map +1 -0
- package/dist/models/downloader.d.ts +21 -0
- package/dist/models/downloader.js +98 -0
- package/dist/models/downloader.js.map +1 -0
- package/dist/models/profiles.d.ts +10 -0
- package/dist/models/profiles.js +68 -0
- package/dist/models/profiles.js.map +1 -0
- package/dist/models/store.d.ts +9 -0
- package/dist/models/store.js +142 -0
- package/dist/models/store.js.map +1 -0
- package/dist/types.d.ts +189 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/utils/errors.d.ts +18 -0
- package/dist/utils/errors.js +33 -0
- package/dist/utils/errors.js.map +1 -0
- package/dist/utils/files.d.ts +14 -0
- package/dist/utils/files.js +88 -0
- package/dist/utils/files.js.map +1 -0
- package/dist/utils/output.d.ts +29 -0
- package/dist/utils/output.js +116 -0
- package/dist/utils/output.js.map +1 -0
- package/package.json +28 -11
- package/examples/openai-client.js +0 -112
- package/examples/openai-sdk.js +0 -46
- package/examples/openai_python.py +0 -42
- package/src/api/openai.js +0 -115
- package/src/benchmark/runner.js +0 -48
- package/src/benchmark/stats.js +0 -33
- package/src/chat/commands.js +0 -68
- package/src/chat/config.js +0 -65
- package/src/chat/history.js +0 -103
- package/src/chat/session.js +0 -337
- package/src/chrome/bridge.js +0 -473
- package/src/chrome/capabilities.js +0 -99
- package/src/chrome/detect.js +0 -199
- package/src/chrome/launch.js +0 -248
- package/src/cli.js +0 -216
- package/src/commands/ask.js +0 -179
- package/src/commands/bench.js +0 -79
- package/src/commands/chat.js +0 -416
- package/src/commands/daemon.js +0 -89
- package/src/commands/download.js +0 -71
- package/src/commands/serve.js +0 -56
- package/src/commands/status.js +0 -87
- package/src/daemon/client.js +0 -274
- package/src/daemon/server.js +0 -650
- package/src/daemon/state.js +0 -46
- package/src/utils/errors.js +0 -26
- package/src/utils/files.js +0 -93
- package/src/utils/output.js +0 -59
- package/test/chat.test.js +0 -252
- package/test/cli.test.js +0 -49
- package/test/daemon.test.js +0 -31
- package/test/detect.test.js +0 -24
- package/test/files.test.js +0 -41
- package/test/openai.test.js +0 -63
- package/test/stats.test.js +0 -29
package/src/commands/daemon.js
DELETED
|
@@ -1,89 +0,0 @@
|
|
|
1
|
-
import { getActiveDaemon, startDaemonInBackground, stopDaemon, resetDaemon } from '../daemon/client.js';
|
|
2
|
-
import { style, log, logError } from '../utils/output.js';
|
|
3
|
-
|
|
4
|
-
export async function handleDaemonCommand(subCommand = 'status', options = {}) {
|
|
5
|
-
if (subCommand === 'start') {
|
|
6
|
-
const active = await getActiveDaemon();
|
|
7
|
-
if (active) {
|
|
8
|
-
if (options.json) {
|
|
9
|
-
console.log(JSON.stringify({ status: 'running', pid: active.pid, port: active.port }, null, 2));
|
|
10
|
-
} else {
|
|
11
|
-
log(`Daemon is already running (PID: ${style(active.pid, 'bold')}, port: ${style(active.port, 'cyan')})`);
|
|
12
|
-
}
|
|
13
|
-
return;
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
if (!options.json) {
|
|
17
|
-
log('Starting NanoBridge background daemon...');
|
|
18
|
-
}
|
|
19
|
-
const started = await startDaemonInBackground();
|
|
20
|
-
if (options.json) {
|
|
21
|
-
console.log(JSON.stringify({ status: 'started', pid: started.pid, port: started.port }, null, 2));
|
|
22
|
-
} else {
|
|
23
|
-
log(`${style('Daemon started successfully', 'green')} ✓ (PID: ${style(started.pid, 'bold')}, port: ${style(started.port, 'cyan')})`);
|
|
24
|
-
}
|
|
25
|
-
return;
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
if (subCommand === 'restart') {
|
|
29
|
-
if (!options.json) {
|
|
30
|
-
log('Restarting NanoBridge background daemon...');
|
|
31
|
-
}
|
|
32
|
-
await stopDaemon();
|
|
33
|
-
const started = await startDaemonInBackground();
|
|
34
|
-
if (options.json) {
|
|
35
|
-
console.log(JSON.stringify({ status: 'restarted', pid: started.pid, port: started.port }, null, 2));
|
|
36
|
-
} else {
|
|
37
|
-
log(`${style('Daemon restarted successfully', 'green')} ✓ (PID: ${style(started.pid, 'bold')}, port: ${style(started.port, 'cyan')})`);
|
|
38
|
-
}
|
|
39
|
-
return;
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
if (subCommand === 'reset') {
|
|
43
|
-
const res = await resetDaemon();
|
|
44
|
-
if (options.json) {
|
|
45
|
-
console.log(JSON.stringify(res, null, 2));
|
|
46
|
-
} else {
|
|
47
|
-
if (res.success) {
|
|
48
|
-
log(`${style('Model session and KV context cache reset successfully', 'green')} ✓`);
|
|
49
|
-
} else {
|
|
50
|
-
log(`${style('Notice:', 'yellow')} ${res.message || res.error}`);
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
return;
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
if (subCommand === 'stop') {
|
|
57
|
-
const res = await stopDaemon();
|
|
58
|
-
if (options.json) {
|
|
59
|
-
console.log(JSON.stringify(res, null, 2));
|
|
60
|
-
} else {
|
|
61
|
-
if (res.wasRunning) {
|
|
62
|
-
log(`${style('Daemon stopped', 'green')} ✓`);
|
|
63
|
-
} else {
|
|
64
|
-
log('Daemon was not running.');
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
return;
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
if (subCommand === 'status') {
|
|
71
|
-
const active = await getActiveDaemon();
|
|
72
|
-
if (options.json) {
|
|
73
|
-
console.log(JSON.stringify(active ? { status: 'running', ...active } : { status: 'stopped' }, null, 2));
|
|
74
|
-
} else {
|
|
75
|
-
if (active) {
|
|
76
|
-
const uptimeSec = Math.round((active.uptimeMs || 0) / 1000);
|
|
77
|
-
log(`Status: ${style('running', 'green')}`);
|
|
78
|
-
log(`PID: ${active.pid}`);
|
|
79
|
-
log(`Port: ${active.port}`);
|
|
80
|
-
log(`Uptime: ${uptimeSec}s`);
|
|
81
|
-
} else {
|
|
82
|
-
log(`Status: ${style('stopped', 'dim')}`);
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
return;
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
logError(`Unknown daemon subcommand: ${subCommand}`);
|
|
89
|
-
}
|
package/src/commands/download.js
DELETED
|
@@ -1,71 +0,0 @@
|
|
|
1
|
-
import process from 'node:process';
|
|
2
|
-
import { launchChrome } from '../chrome/launch.js';
|
|
3
|
-
import { ChromeBridge } from '../chrome/bridge.js';
|
|
4
|
-
import { isModelDownloaded } from '../chrome/detect.js';
|
|
5
|
-
import { style, log, renderProgressBar } from '../utils/output.js';
|
|
6
|
-
|
|
7
|
-
export async function handleDownload(options = {}) {
|
|
8
|
-
if (isModelDownloaded()) {
|
|
9
|
-
if (options.json) {
|
|
10
|
-
console.log(JSON.stringify({ status: 'ready', alreadyAvailable: true }, null, 2));
|
|
11
|
-
} else {
|
|
12
|
-
log(`${style('Model already available', 'green')} ✓`);
|
|
13
|
-
}
|
|
14
|
-
return;
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
let chromeInstance = null;
|
|
18
|
-
let bridge = null;
|
|
19
|
-
|
|
20
|
-
try {
|
|
21
|
-
if (!options.json) {
|
|
22
|
-
log('Preparing Chrome Built-in AI...\n');
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
chromeInstance = await launchChrome(options);
|
|
26
|
-
bridge = new ChromeBridge(chromeInstance);
|
|
27
|
-
await bridge.connect();
|
|
28
|
-
|
|
29
|
-
let lastRenderedPercent = -1;
|
|
30
|
-
let isTty = Boolean(process.stdout.isTTY) && !options.json;
|
|
31
|
-
|
|
32
|
-
const result = await bridge.downloadModel({
|
|
33
|
-
onProgress: ({ loaded, total, percent }) => {
|
|
34
|
-
const rounded = Math.round(percent);
|
|
35
|
-
if (rounded !== lastRenderedPercent) {
|
|
36
|
-
lastRenderedPercent = rounded;
|
|
37
|
-
if (options.json) return;
|
|
38
|
-
|
|
39
|
-
const bar = renderProgressBar(rounded, 28);
|
|
40
|
-
if (isTty) {
|
|
41
|
-
process.stdout.write(`\r${style(bar, 'cyan')} Downloading model components...`);
|
|
42
|
-
} else {
|
|
43
|
-
log(`${bar} Downloading model components`);
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
}
|
|
47
|
-
});
|
|
48
|
-
|
|
49
|
-
if (result.alreadyAvailable) {
|
|
50
|
-
if (options.json) {
|
|
51
|
-
console.log(JSON.stringify({ status: 'ready', alreadyAvailable: true }, null, 2));
|
|
52
|
-
} else {
|
|
53
|
-
log(`${style('Model already available', 'green')} ✓`);
|
|
54
|
-
}
|
|
55
|
-
return;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
if (isTty) {
|
|
59
|
-
process.stdout.write('\n\n');
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
if (options.json) {
|
|
63
|
-
console.log(JSON.stringify({ status: 'ready', downloaded: true }, null, 2));
|
|
64
|
-
} else {
|
|
65
|
-
log(`${style('Model ready', 'green')} ✓`);
|
|
66
|
-
}
|
|
67
|
-
} finally {
|
|
68
|
-
if (bridge) await bridge.close();
|
|
69
|
-
if (chromeInstance) chromeInstance.close();
|
|
70
|
-
}
|
|
71
|
-
}
|
package/src/commands/serve.js
DELETED
|
@@ -1,56 +0,0 @@
|
|
|
1
|
-
import process from 'node:process';
|
|
2
|
-
import { DaemonServer } from '../daemon/server.js';
|
|
3
|
-
import { style, log, logError } from '../utils/output.js';
|
|
4
|
-
|
|
5
|
-
export async function handleServe(options = {}) {
|
|
6
|
-
const port = options.port || 8000;
|
|
7
|
-
const host = options.host || '127.0.0.1';
|
|
8
|
-
|
|
9
|
-
log(style('NanoBridge OpenAI-Compatible API Server', 'bold'));
|
|
10
|
-
log('Starting background Chrome and warming Gemini Nano...');
|
|
11
|
-
|
|
12
|
-
const server = new DaemonServer({
|
|
13
|
-
port,
|
|
14
|
-
host,
|
|
15
|
-
idleTimeoutMs: 0 // Do not auto-shutdown when explicitly running in serve mode
|
|
16
|
-
});
|
|
17
|
-
|
|
18
|
-
try {
|
|
19
|
-
await server.start();
|
|
20
|
-
|
|
21
|
-
const baseUrl = `http://${host}:${server.port}/v1`;
|
|
22
|
-
|
|
23
|
-
log('');
|
|
24
|
-
log(`${style('OpenAI-Compatible Server Ready!', 'green')} ✓`);
|
|
25
|
-
log(`Base URL: ${style(baseUrl, 'cyan')}`);
|
|
26
|
-
log(`Models: ${style(`${baseUrl}/models`, 'dim')}`);
|
|
27
|
-
log(`Chat: ${style(`${baseUrl}/chat/completions`, 'dim')}`);
|
|
28
|
-
log(`Completions: ${style(`${baseUrl}/completions`, 'dim')}`);
|
|
29
|
-
log('');
|
|
30
|
-
log(style('Example curl (Streaming SSE):', 'bold'));
|
|
31
|
-
log(` curl -N ${baseUrl}/chat/completions \\
|
|
32
|
-
-H "Content-Type: application/json" \\
|
|
33
|
-
-d '{
|
|
34
|
-
"model": "gemini-nano",
|
|
35
|
-
"messages": [{"role": "user", "content": "Nasılsın?"}],
|
|
36
|
-
"stream": true
|
|
37
|
-
}'`);
|
|
38
|
-
log('');
|
|
39
|
-
log(style('Example OpenAI Python SDK:', 'bold'));
|
|
40
|
-
log(` from openai import OpenAI
|
|
41
|
-
client = OpenAI(base_url="${baseUrl}", api_key="nanobridge")
|
|
42
|
-
response = client.chat.completions.create(
|
|
43
|
-
model="gemini-nano",
|
|
44
|
-
messages=[{"role": "user", "content": "Explain Web Locks"}]
|
|
45
|
-
)
|
|
46
|
-
print(response.choices[0].message.content)`);
|
|
47
|
-
log('');
|
|
48
|
-
log(`Press ${style('Ctrl+C', 'bold')} to stop server.`);
|
|
49
|
-
|
|
50
|
-
// Keep running until interrupt
|
|
51
|
-
await new Promise(() => {});
|
|
52
|
-
} catch (err) {
|
|
53
|
-
logError(`Failed to start serve server: ${err.message}`);
|
|
54
|
-
process.exit(1);
|
|
55
|
-
}
|
|
56
|
-
}
|
package/src/commands/status.js
DELETED
|
@@ -1,87 +0,0 @@
|
|
|
1
|
-
import { getPlatformInfo, isModelDownloaded } from '../chrome/detect.js';
|
|
2
|
-
import { launchChrome } from '../chrome/launch.js';
|
|
3
|
-
import { ChromeBridge } from '../chrome/bridge.js';
|
|
4
|
-
import { getActiveDaemon } from '../daemon/client.js';
|
|
5
|
-
import { style, log, logError } from '../utils/output.js';
|
|
6
|
-
import { BuiltInAiUnavailableError, ModelUnavailableError } from '../utils/errors.js';
|
|
7
|
-
|
|
8
|
-
export async function handleStatus(options = {}) {
|
|
9
|
-
let chromeInstance = null;
|
|
10
|
-
let bridge = null;
|
|
11
|
-
|
|
12
|
-
try {
|
|
13
|
-
const platformInfo = getPlatformInfo();
|
|
14
|
-
const modelOnDisk = isModelDownloaded();
|
|
15
|
-
const daemon = await getActiveDaemon();
|
|
16
|
-
let status = null;
|
|
17
|
-
|
|
18
|
-
if (daemon && daemon.bridgeConnected) {
|
|
19
|
-
status = {
|
|
20
|
-
builtInAiAvailable: true,
|
|
21
|
-
languageModelAvailable: true,
|
|
22
|
-
availability: 'readily'
|
|
23
|
-
};
|
|
24
|
-
} else {
|
|
25
|
-
chromeInstance = await launchChrome(options);
|
|
26
|
-
bridge = new ChromeBridge(chromeInstance);
|
|
27
|
-
await bridge.connect();
|
|
28
|
-
status = await bridge.checkStatus();
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
let modelDisplayStatus = 'unavailable';
|
|
32
|
-
const rawAvail = String(status.availability || '').toLowerCase();
|
|
33
|
-
if (modelOnDisk || rawAvail === 'readily' || rawAvail === 'available' || rawAvail === 'ready') {
|
|
34
|
-
modelDisplayStatus = 'ready';
|
|
35
|
-
} else if (rawAvail === 'after-download' || rawAvail === 'downloadable') {
|
|
36
|
-
modelDisplayStatus = 'downloadable';
|
|
37
|
-
} else if (rawAvail === 'downloading') {
|
|
38
|
-
modelDisplayStatus = 'downloading';
|
|
39
|
-
} else if (rawAvail === 'no') {
|
|
40
|
-
modelDisplayStatus = 'unavailable';
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
if (options.json) {
|
|
44
|
-
console.log(JSON.stringify({
|
|
45
|
-
chrome: platformInfo.chromeVersion || 'Unknown',
|
|
46
|
-
platform: platformInfo.platformLabel,
|
|
47
|
-
arch: platformInfo.arch,
|
|
48
|
-
builtInAi: status.builtInAiAvailable ? 'available' : 'unavailable',
|
|
49
|
-
languageModel: status.languageModelAvailable ? 'available' : 'unavailable',
|
|
50
|
-
model: modelDisplayStatus,
|
|
51
|
-
execution: 'on-device',
|
|
52
|
-
daemon: daemon ? { status: 'running', pid: daemon.pid, port: daemon.port } : { status: 'stopped' },
|
|
53
|
-
details: status
|
|
54
|
-
}, null, 2));
|
|
55
|
-
return;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
log(style('NanoBridge', 'bold'));
|
|
59
|
-
log('');
|
|
60
|
-
log(`Chrome ${style(platformInfo.chromeVersion || 'Not found', platformInfo.chromeVersion ? 'cyan' : 'red')}`);
|
|
61
|
-
log(`Platform ${platformInfo.platformLabel} ${platformInfo.arch}`);
|
|
62
|
-
log(`Built-in AI ${style(status.builtInAiAvailable ? 'available' : 'unavailable', status.builtInAiAvailable ? 'green' : 'red')}`);
|
|
63
|
-
log(`LanguageModel ${style(status.languageModelAvailable ? 'available' : 'unavailable', status.languageModelAvailable ? 'green' : 'red')}`);
|
|
64
|
-
log(`Model ${style(modelDisplayStatus, modelDisplayStatus === 'ready' ? 'green' : 'yellow')}`);
|
|
65
|
-
log(`Execution ${style('on-device', 'green')}`);
|
|
66
|
-
log(`Daemon ${daemon ? style(`running (PID: ${daemon.pid}, port: ${daemon.port})`, 'green') : style('stopped', 'dim')}`);
|
|
67
|
-
|
|
68
|
-
if (modelDisplayStatus === 'downloadable') {
|
|
69
|
-
log('');
|
|
70
|
-
log(`Run ${style('nanobridge download', 'bold')} to download on-device Gemini Nano components.`);
|
|
71
|
-
}
|
|
72
|
-
} catch (err) {
|
|
73
|
-
if (options.json) {
|
|
74
|
-
console.log(JSON.stringify({
|
|
75
|
-
error: err.message,
|
|
76
|
-
code: err.code || 'UNKNOWN_ERROR'
|
|
77
|
-
}, null, 2));
|
|
78
|
-
} else {
|
|
79
|
-
logError(style('NanoBridge Status Error:', 'red'));
|
|
80
|
-
logError(err.message);
|
|
81
|
-
}
|
|
82
|
-
throw err;
|
|
83
|
-
} finally {
|
|
84
|
-
if (bridge) await bridge.close();
|
|
85
|
-
if (chromeInstance) chromeInstance.close();
|
|
86
|
-
}
|
|
87
|
-
}
|
package/src/daemon/client.js
DELETED
|
@@ -1,274 +0,0 @@
|
|
|
1
|
-
import http from 'node:http';
|
|
2
|
-
import { spawn, execSync } from 'node:child_process';
|
|
3
|
-
import fs from 'node:fs';
|
|
4
|
-
import os from 'node:os';
|
|
5
|
-
import path from 'node:path';
|
|
6
|
-
import { StringDecoder } from 'node:string_decoder';
|
|
7
|
-
import { fileURLToPath } from 'node:url';
|
|
8
|
-
import { getDaemonState, clearDaemonState } from './state.js';
|
|
9
|
-
import { debug } from '../utils/output.js';
|
|
10
|
-
|
|
11
|
-
const __filename = fileURLToPath(import.meta.url);
|
|
12
|
-
const __dirname = path.dirname(__filename);
|
|
13
|
-
const SERVER_SCRIPT = path.join(__dirname, 'server.js');
|
|
14
|
-
|
|
15
|
-
function isPidRunning(pid) {
|
|
16
|
-
try {
|
|
17
|
-
process.kill(pid, 0);
|
|
18
|
-
return true;
|
|
19
|
-
} catch (_) {
|
|
20
|
-
return false;
|
|
21
|
-
}
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
export async function pingDaemon(port, timeoutMs = 3000) {
|
|
25
|
-
return new Promise((resolve) => {
|
|
26
|
-
const req = http.request(`http://127.0.0.1:${port}/status`, { timeout: timeoutMs }, (res) => {
|
|
27
|
-
if (res.statusCode === 200) {
|
|
28
|
-
let body = '';
|
|
29
|
-
res.on('data', (c) => { body += c; });
|
|
30
|
-
res.on('end', () => {
|
|
31
|
-
try {
|
|
32
|
-
resolve(JSON.parse(body));
|
|
33
|
-
} catch (_) {
|
|
34
|
-
resolve(null);
|
|
35
|
-
}
|
|
36
|
-
});
|
|
37
|
-
} else {
|
|
38
|
-
resolve(null);
|
|
39
|
-
}
|
|
40
|
-
});
|
|
41
|
-
req.on('error', () => resolve(null));
|
|
42
|
-
req.on('timeout', () => { req.destroy(); resolve(null); });
|
|
43
|
-
req.end();
|
|
44
|
-
});
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
export async function getActiveDaemon() {
|
|
48
|
-
const state = getDaemonState();
|
|
49
|
-
if (!state || !state.pid) return null;
|
|
50
|
-
|
|
51
|
-
if (!isPidRunning(state.pid)) {
|
|
52
|
-
clearDaemonState();
|
|
53
|
-
return null;
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
if (state.port) {
|
|
57
|
-
const health = await pingDaemon(state.port, 2000);
|
|
58
|
-
if (health && health.status === 'ready') {
|
|
59
|
-
return { ...state, ...health };
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
// If PID is running, wait a moment for startup to finish
|
|
64
|
-
const start = Date.now();
|
|
65
|
-
while (Date.now() - start < 8000) {
|
|
66
|
-
await new Promise((r) => setTimeout(r, 400));
|
|
67
|
-
const currentState = getDaemonState();
|
|
68
|
-
if (!currentState || !currentState.port) continue;
|
|
69
|
-
const health = await pingDaemon(currentState.port, 1500);
|
|
70
|
-
if (health && health.status === 'ready') {
|
|
71
|
-
return { ...currentState, ...health };
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
return null;
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
export async function startDaemonInBackground() {
|
|
79
|
-
debug('client', 'Spawning daemon process in background:', SERVER_SCRIPT);
|
|
80
|
-
|
|
81
|
-
clearDaemonState();
|
|
82
|
-
|
|
83
|
-
const logDir = path.join(os.homedir(), '.nanobridge');
|
|
84
|
-
if (!fs.existsSync(logDir)) {
|
|
85
|
-
fs.mkdirSync(logDir, { recursive: true });
|
|
86
|
-
}
|
|
87
|
-
const logFile = path.join(logDir, 'daemon.log');
|
|
88
|
-
const out = fs.openSync(logFile, 'a');
|
|
89
|
-
const err = fs.openSync(logFile, 'a');
|
|
90
|
-
|
|
91
|
-
const env = { ...process.env };
|
|
92
|
-
const child = spawn(process.execPath, [SERVER_SCRIPT], {
|
|
93
|
-
detached: true,
|
|
94
|
-
stdio: ['ignore', out, err],
|
|
95
|
-
env
|
|
96
|
-
});
|
|
97
|
-
child.unref();
|
|
98
|
-
|
|
99
|
-
debug('client', `Spawned daemon child PID: ${child.pid}. Waiting for readiness...`);
|
|
100
|
-
|
|
101
|
-
// Poll until daemon is ready
|
|
102
|
-
const startTime = Date.now();
|
|
103
|
-
const maxWaitMs = 35000;
|
|
104
|
-
|
|
105
|
-
while (Date.now() - startTime < maxWaitMs) {
|
|
106
|
-
const state = getDaemonState();
|
|
107
|
-
if (state && state.port) {
|
|
108
|
-
const ping = await pingDaemon(state.port);
|
|
109
|
-
if (ping && ping.status === 'ready') {
|
|
110
|
-
debug('client', `Daemon is ready on port ${state.port} in ${Date.now() - startTime}ms`);
|
|
111
|
-
return { ...state, ...ping };
|
|
112
|
-
}
|
|
113
|
-
}
|
|
114
|
-
await new Promise((r) => setTimeout(r, 300));
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
let lastError = '';
|
|
118
|
-
try {
|
|
119
|
-
if (fs.existsSync(logFile)) {
|
|
120
|
-
const logContent = fs.readFileSync(logFile, 'utf8');
|
|
121
|
-
const lines = logContent.trim().split('\n');
|
|
122
|
-
lastError = lines.slice(-15).join('\n');
|
|
123
|
-
}
|
|
124
|
-
} catch (_) {}
|
|
125
|
-
|
|
126
|
-
throw new Error(`Timed out waiting for NanoBridge daemon to start.${lastError ? `\nDaemon log:\n${lastError}` : ''}`);
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
export async function ensureDaemon() {
|
|
130
|
-
const active = await getActiveDaemon();
|
|
131
|
-
if (active) return active;
|
|
132
|
-
return await startDaemonInBackground();
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
export async function streamPromptFromDaemon(daemonOrOpts, maybeOpts = {}) {
|
|
136
|
-
const opts = (daemonOrOpts && typeof daemonOrOpts.port === 'number' && maybeOpts && Object.keys(maybeOpts).length > 0)
|
|
137
|
-
? { ...maybeOpts, port: daemonOrOpts.port }
|
|
138
|
-
: (daemonOrOpts || {});
|
|
139
|
-
|
|
140
|
-
const {
|
|
141
|
-
port,
|
|
142
|
-
promptText,
|
|
143
|
-
systemPrompt,
|
|
144
|
-
samplingMode,
|
|
145
|
-
sessionType,
|
|
146
|
-
initialPrompts,
|
|
147
|
-
responseConstraint,
|
|
148
|
-
stream = true,
|
|
149
|
-
onChunk
|
|
150
|
-
} = opts;
|
|
151
|
-
|
|
152
|
-
return new Promise((resolve, reject) => {
|
|
153
|
-
const payload = JSON.stringify({
|
|
154
|
-
promptText,
|
|
155
|
-
systemPrompt,
|
|
156
|
-
samplingMode,
|
|
157
|
-
sessionType,
|
|
158
|
-
initialPrompts,
|
|
159
|
-
responseConstraint,
|
|
160
|
-
stream
|
|
161
|
-
});
|
|
162
|
-
const req = http.request(`http://127.0.0.1:${port}/prompt`, {
|
|
163
|
-
method: 'POST',
|
|
164
|
-
headers: {
|
|
165
|
-
'Content-Type': 'application/json; charset=utf-8',
|
|
166
|
-
'Content-Length': Buffer.byteLength(payload)
|
|
167
|
-
}
|
|
168
|
-
}, (res) => {
|
|
169
|
-
const decoder = new StringDecoder('utf8');
|
|
170
|
-
let buffer = '';
|
|
171
|
-
let finalText = '';
|
|
172
|
-
let streamAccumulated = '';
|
|
173
|
-
|
|
174
|
-
res.on('data', (chunk) => {
|
|
175
|
-
buffer += decoder.write(chunk);
|
|
176
|
-
const lines = buffer.split('\n');
|
|
177
|
-
buffer = lines.pop(); // Keep partial line in buffer
|
|
178
|
-
|
|
179
|
-
for (const line of lines) {
|
|
180
|
-
if (!line.trim()) continue;
|
|
181
|
-
try {
|
|
182
|
-
const data = JSON.parse(line);
|
|
183
|
-
if (data.type === 'chunk') {
|
|
184
|
-
if (data.delta) streamAccumulated += data.delta;
|
|
185
|
-
if (onChunk) onChunk(data.delta, data.full);
|
|
186
|
-
} else if (data.type === 'done') {
|
|
187
|
-
finalText = data.text;
|
|
188
|
-
} else if (data.type === 'error') {
|
|
189
|
-
reject(new Error(data.error));
|
|
190
|
-
return;
|
|
191
|
-
}
|
|
192
|
-
} catch (_) {}
|
|
193
|
-
}
|
|
194
|
-
});
|
|
195
|
-
|
|
196
|
-
res.on('end', () => {
|
|
197
|
-
buffer += decoder.end();
|
|
198
|
-
if (buffer.trim()) {
|
|
199
|
-
try {
|
|
200
|
-
const data = JSON.parse(buffer);
|
|
201
|
-
if (data.type === 'done') finalText = data.text;
|
|
202
|
-
} catch (_) {}
|
|
203
|
-
}
|
|
204
|
-
resolve(finalText || streamAccumulated);
|
|
205
|
-
});
|
|
206
|
-
});
|
|
207
|
-
|
|
208
|
-
req.on('socket', (socket) => {
|
|
209
|
-
socket.setNoDelay(true);
|
|
210
|
-
});
|
|
211
|
-
|
|
212
|
-
req.on('error', reject);
|
|
213
|
-
req.write(payload);
|
|
214
|
-
req.end();
|
|
215
|
-
});
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
export async function resetDaemon(options = {}) {
|
|
219
|
-
const active = await getActiveDaemon();
|
|
220
|
-
if (!active) {
|
|
221
|
-
return { success: false, message: 'Daemon is not running' };
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
const query = options.session ? `?session=${encodeURIComponent(options.session)}` : '';
|
|
225
|
-
return new Promise((resolve, reject) => {
|
|
226
|
-
const req = http.request(`http://127.0.0.1:${active.port}/reset${query}`, { method: 'POST', timeout: 5000 }, (res) => {
|
|
227
|
-
let data = '';
|
|
228
|
-
res.on('data', (c) => { data += c; });
|
|
229
|
-
res.on('end', () => {
|
|
230
|
-
try {
|
|
231
|
-
resolve(JSON.parse(data));
|
|
232
|
-
} catch (_) {
|
|
233
|
-
resolve({ success: true });
|
|
234
|
-
}
|
|
235
|
-
});
|
|
236
|
-
});
|
|
237
|
-
req.on('error', reject);
|
|
238
|
-
req.end();
|
|
239
|
-
});
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
export async function stopDaemon() {
|
|
243
|
-
const active = await getActiveDaemon();
|
|
244
|
-
const profileDir = path.join(os.homedir(), '.nanobridge', 'profile');
|
|
245
|
-
|
|
246
|
-
if (!active) {
|
|
247
|
-
try {
|
|
248
|
-
execSync(`pkill -9 -f "${profileDir}"`, { stdio: 'ignore' });
|
|
249
|
-
} catch (_) {}
|
|
250
|
-
clearDaemonState();
|
|
251
|
-
return { stopped: true, wasRunning: false };
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
return new Promise((resolve) => {
|
|
255
|
-
const req = http.request(`http://127.0.0.1:${active.port}/stop`, { method: 'POST', timeout: 2000 }, (res) => {
|
|
256
|
-
clearDaemonState();
|
|
257
|
-
try {
|
|
258
|
-
execSync(`pkill -9 -f "${profileDir}"`, { stdio: 'ignore' });
|
|
259
|
-
} catch (_) {}
|
|
260
|
-
resolve({ stopped: true, wasRunning: true, pid: active.pid });
|
|
261
|
-
});
|
|
262
|
-
req.on('error', () => {
|
|
263
|
-
try {
|
|
264
|
-
if (active.pid) process.kill(active.pid, 'SIGKILL');
|
|
265
|
-
} catch (_) {}
|
|
266
|
-
try {
|
|
267
|
-
execSync(`pkill -9 -f "${profileDir}"`, { stdio: 'ignore' });
|
|
268
|
-
} catch (_) {}
|
|
269
|
-
clearDaemonState();
|
|
270
|
-
resolve({ stopped: true, wasRunning: true, pid: active.pid });
|
|
271
|
-
});
|
|
272
|
-
req.end();
|
|
273
|
-
});
|
|
274
|
-
}
|