nanobridge 0.2.4 → 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 -217
  125. package/src/commands/bench.js +0 -79
  126. package/src/commands/chat.js +0 -426
  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 -107
  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,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
- }
@@ -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
- }