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,650 +0,0 @@
1
- import http from 'node:http';
2
- import process from 'node:process';
3
- import crypto from 'node:crypto';
4
- import { launchChrome } from '../chrome/launch.js';
5
- import { ChromeBridge } from '../chrome/bridge.js';
6
- import { saveDaemonState, clearDaemonState } from './state.js';
7
- import {
8
- parseChatMessages,
9
- formatModelsList,
10
- formatChatCompletion,
11
- formatChatCompletionChunk
12
- } from '../api/openai.js';
13
- import { debug, setDebugMode } from '../utils/output.js';
14
-
15
- const DEFAULT_IDLE_TIMEOUT_MS = 10 * 60 * 1000; // 10 minutes
16
-
17
- export class DaemonServer {
18
- constructor(options = {}) {
19
- this.options = options;
20
- this.server = null;
21
- this.port = options.port || 0;
22
- this.host = options.host || '127.0.0.1';
23
- this.chromeInstance = null;
24
- this.bridge = null;
25
- this.idleTimeoutMs = options.idleTimeoutMs !== undefined ? options.idleTimeoutMs : DEFAULT_IDLE_TIMEOUT_MS;
26
- this.idleTimer = null;
27
- this.startTime = Date.now();
28
- this.isStopping = false;
29
- this.isWarmed = false;
30
- this.isInitializing = false;
31
- }
32
-
33
- resetIdleTimer() {
34
- if (this.idleTimer) clearTimeout(this.idleTimer);
35
- if (this.idleTimeoutMs > 0) {
36
- this.idleTimer = setTimeout(() => {
37
- debug('daemon', 'Daemon idle timeout reached. Shutting down...');
38
- this.stop();
39
- }, this.idleTimeoutMs);
40
- if (this.idleTimer.unref) this.idleTimer.unref();
41
- }
42
- }
43
-
44
- async initChrome() {
45
- if (this.isInitializing) return;
46
- this.isInitializing = true;
47
- debug('daemon', 'Initializing / recovering Chrome instance and CDP bridge...');
48
-
49
- if (this.bridge) {
50
- try { await this.bridge.close(); } catch (_) {}
51
- this.bridge = null;
52
- }
53
- if (this.chromeInstance) {
54
- try { this.chromeInstance.close(); } catch (_) {}
55
- this.chromeInstance = null;
56
- }
57
-
58
- try {
59
- this.chromeInstance = await launchChrome(this.options);
60
- this.bridge = new ChromeBridge(this.chromeInstance);
61
- await this.bridge.connect();
62
- } finally {
63
- this.isInitializing = false;
64
- }
65
- }
66
-
67
- async ensureReady() {
68
- if (!this.bridge || !this.bridge.isConnected() || !this.chromeInstance) {
69
- debug('daemon', 'Bridge not connected (possibly after OS sleep). Reconnecting Chrome...');
70
- await this.initChrome();
71
- }
72
- }
73
-
74
- async start() {
75
- debug('daemon', 'Starting background Chrome daemon...');
76
-
77
- // 1. Launch Chrome and bridge
78
- await this.initChrome();
79
-
80
- // 2. Start HTTP server and write state immediately
81
- this.server = http.createServer((req, res) => this.handleRequest(req, res));
82
-
83
- await new Promise((resolve, reject) => {
84
- this.server.listen(this.port, this.host, () => {
85
- this.port = this.server.address().port;
86
- resolve();
87
- });
88
- this.server.on('error', reject);
89
- });
90
-
91
- saveDaemonState({
92
- pid: process.pid,
93
- port: this.port,
94
- host: this.host,
95
- startTime: this.startTime,
96
- chromePid: this.chromeInstance?.pid
97
- });
98
-
99
- debug('daemon', `Daemon listening on http://${this.host}:${this.port} (PID: ${process.pid})`);
100
-
101
- // 3. Warm up session in background
102
- this.warmupSession().catch((err) => {
103
- debug('daemon', 'Warmup background error:', err.message);
104
- });
105
-
106
- this.resetIdleTimer();
107
-
108
- const cleanup = () => this.stop();
109
- process.on('SIGINT', cleanup);
110
- process.on('SIGTERM', cleanup);
111
- process.on('exit', () => clearDaemonState());
112
- }
113
-
114
- async warmupSession() {
115
- this.warmupPromise = (async () => {
116
- debug('daemon', 'Warming up LanguageModel on-device model in Chrome...');
117
- try {
118
- if (this.bridge && this.bridge.isConnected()) {
119
- await this.bridge.evaluate(`(async () => {
120
- if ('LanguageModel' in window) {
121
- if (!window.__nanobridge_base_session) {
122
- window.__nanobridge_base_session = await window.LanguageModel.create();
123
- }
124
- try {
125
- const s = await window.__nanobridge_base_session.clone();
126
- await s.prompt('hi');
127
- s.destroy();
128
- } catch (_) {}
129
- }
130
- })()`, { userGesture: true, timeout: 180000 });
131
- this.isWarmed = true;
132
- debug('daemon', 'Warmup completed successfully.');
133
- }
134
- } catch (warmErr) {
135
- debug('daemon', 'Warmup notice:', warmErr.message);
136
- }
137
- })();
138
- return this.warmupPromise;
139
- }
140
-
141
- setCorsHeaders(res) {
142
- res.setHeader('Access-Control-Allow-Origin', '*');
143
- res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
144
- res.setHeader('Access-Control-Allow-Headers', 'Authorization, Content-Type, Accept, Origin, User-Agent, X-Requested-With');
145
- }
146
-
147
- async handleRequest(req, res) {
148
- this.resetIdleTimer();
149
- this.setCorsHeaders(res);
150
-
151
- if (req.method === 'OPTIONS') {
152
- res.writeHead(204);
153
- res.end();
154
- return;
155
- }
156
-
157
- const url = new URL(req.url, `http://${this.host}:${this.port}`);
158
-
159
- // Standard Health/Status
160
- if (req.method === 'GET' && (url.pathname === '/status' || url.pathname === '/health')) {
161
- const bridgeConnected = Boolean(this.bridge && this.bridge.isConnected());
162
- let chatStats = null;
163
- if (bridgeConnected) {
164
- try {
165
- chatStats = await this.bridge.evaluate(`(() => {
166
- const s = window.__nanobridge_chat_session;
167
- if (!s) return null;
168
- return {
169
- contextUsage: typeof s.contextUsage === 'number' ? s.contextUsage : null,
170
- contextWindow: typeof s.contextWindow === 'number' ? s.contextWindow : 9216
171
- };
172
- })()`);
173
- } catch (_) {}
174
- }
175
- res.writeHead(200, { 'Content-Type': 'application/json' });
176
- res.end(JSON.stringify({
177
- status: 'ready',
178
- pid: process.pid,
179
- port: this.port,
180
- host: this.host,
181
- uptimeMs: Date.now() - this.startTime,
182
- warmed: this.isWarmed,
183
- bridgeConnected,
184
- chatStats,
185
- openai_base_url: `http://${this.host}:${this.port}/v1`
186
- }));
187
- return;
188
- }
189
-
190
- // Stop Daemon
191
- if (req.method === 'POST' && url.pathname === '/stop') {
192
- res.writeHead(200, { 'Content-Type': 'application/json' });
193
- res.end(JSON.stringify({ stopped: true }));
194
- setTimeout(() => this.stop(), 50);
195
- return;
196
- }
197
-
198
- // OpenAI Models Endpoint
199
- if (req.method === 'GET' && url.pathname === '/v1/models') {
200
- res.writeHead(200, { 'Content-Type': 'application/json' });
201
- res.end(JSON.stringify(formatModelsList(), null, 2));
202
- return;
203
- }
204
-
205
- // OpenAI Chat Completions Endpoint
206
- if (req.method === 'POST' && url.pathname === '/v1/chat/completions') {
207
- let body = '';
208
- req.on('data', (chunk) => { body += chunk; });
209
- req.on('end', async () => {
210
- const reqId = `chatcmpl-${crypto.randomBytes(8).toString('hex')}`;
211
- let isClientClosed = false;
212
- res.on('close', () => {
213
- if (!res.writableEnded) {
214
- isClientClosed = true;
215
- this.cancelPrompt(reqId);
216
- }
217
- });
218
-
219
- try {
220
- await this.ensureReady();
221
-
222
- const payload = JSON.parse(body || '{}');
223
- const messages = payload.messages || [];
224
- const model = payload.model || 'gemini-nano';
225
- const stream = payload.stream === true;
226
- const { systemPrompt, promptText } = parseChatMessages(messages);
227
-
228
- if (stream) {
229
- if (res.socket) res.socket.setNoDelay(true);
230
- if (req.socket) req.socket.setNoDelay(true);
231
-
232
- res.writeHead(200, {
233
- 'Content-Type': 'text/event-stream; charset=utf-8',
234
- 'Cache-Control': 'no-cache',
235
- 'Connection': 'keep-alive'
236
- });
237
- if (typeof res.flushHeaders === 'function') res.flushHeaders();
238
-
239
- let isFirst = true;
240
- const onDelta = (delta) => {
241
- if (isClientClosed) return;
242
- if (!delta && !isFirst) return;
243
- const chunk = formatChatCompletionChunk({
244
- id: reqId,
245
- model,
246
- delta,
247
- isFirst
248
- });
249
- isFirst = false;
250
- res.write(`data: ${JSON.stringify(chunk)}\n\n`);
251
- };
252
-
253
- await this.promptWithRetry({
254
- promptText,
255
- systemPrompt,
256
- stream: true,
257
- requestId: reqId,
258
- onChunk: (delta) => onDelta(delta)
259
- });
260
-
261
- if (!isClientClosed) {
262
- const lastChunk = formatChatCompletionChunk({
263
- id: reqId,
264
- model,
265
- delta: '',
266
- isLast: true
267
- });
268
- res.write(`data: ${JSON.stringify(lastChunk)}\n\n`);
269
- res.write('data: [DONE]\n\n');
270
- res.end();
271
- }
272
- } else {
273
- const resultText = await this.promptWithRetry({
274
- promptText,
275
- systemPrompt,
276
- stream: false,
277
- requestId: reqId
278
- });
279
-
280
- if (!isClientClosed) {
281
- res.writeHead(200, { 'Content-Type': 'application/json' });
282
- res.end(JSON.stringify(formatChatCompletion({
283
- id: reqId,
284
- model,
285
- content: resultText
286
- }), null, 2));
287
- }
288
- }
289
- } catch (err) {
290
- if (!isClientClosed) {
291
- res.writeHead(500, { 'Content-Type': 'application/json' });
292
- res.end(JSON.stringify({
293
- error: {
294
- message: err.message,
295
- type: 'nanobridge_error',
296
- code: 'inference_error'
297
- }
298
- }));
299
- }
300
- }
301
- });
302
- return;
303
- }
304
-
305
- // Reset / Recycle Context Endpoint
306
- if ((req.method === 'POST' || req.method === 'GET') && url.pathname === '/reset') {
307
- const resetType = url.searchParams.get('session');
308
- try {
309
- await this.runExclusive(async () => {
310
- if (this.bridge && this.bridge.isConnected()) {
311
- if (resetType === 'chat') {
312
- debug('daemon', 'Resetting chat session context...');
313
- await this.bridge.evaluate(`(() => {
314
- if (window.__nanobridge_chat_session && typeof window.__nanobridge_chat_session.destroy === 'function') {
315
- try { window.__nanobridge_chat_session.destroy(); } catch (_) {}
316
- }
317
- window.__nanobridge_chat_session = null;
318
- window.__nanobridge_chat_session_config = null;
319
- })()`);
320
- } else {
321
- debug('daemon', 'Resetting all Chrome AI sessions & recycling context...');
322
- await this.bridge.evaluate(`(() => {
323
- if (window.__nanobridge_chat_session && typeof window.__nanobridge_chat_session.destroy === 'function') {
324
- try { window.__nanobridge_chat_session.destroy(); } catch (_) {}
325
- }
326
- if (window.__nanobridge_base_session && typeof window.__nanobridge_base_session.destroy === 'function') {
327
- try { window.__nanobridge_base_session.destroy(); } catch (_) {}
328
- }
329
- window.__nanobridge_chat_session = null;
330
- window.__nanobridge_chat_session_config = null;
331
- window.__nanobridge_base_session = null;
332
- })()`);
333
- await this.warmupSession();
334
- }
335
- }
336
- });
337
- res.writeHead(200, { 'Content-Type': 'application/json' });
338
- res.end(JSON.stringify({ success: true, message: 'Reset successfully' }));
339
- } catch (err) {
340
- res.writeHead(500, { 'Content-Type': 'application/json' });
341
- res.end(JSON.stringify({ success: false, error: err.message }));
342
- }
343
- return;
344
- }
345
-
346
- // Native NanoBridge /prompt Endpoint
347
- if (req.method === 'POST' && url.pathname === '/prompt') {
348
- let body = '';
349
- req.on('data', (chunk) => { body += chunk; });
350
- req.on('end', async () => {
351
- const reqId = `req_${crypto.randomBytes(8).toString('hex')}`;
352
- let isClientClosed = false;
353
- res.on('close', () => {
354
- if (!res.writableEnded) {
355
- isClientClosed = true;
356
- this.cancelPrompt(reqId);
357
- }
358
- });
359
-
360
- try {
361
- await this.ensureReady();
362
-
363
- const payload = JSON.parse(body || '{}');
364
- const promptText = payload.promptText || '';
365
- const systemPrompt = payload.systemPrompt;
366
- const samplingMode = payload.samplingMode;
367
- const sessionType = payload.sessionType || 'stateless';
368
- const initialPrompts = payload.initialPrompts;
369
- const stream = payload.stream !== false;
370
-
371
- if (res.socket) res.socket.setNoDelay(true);
372
- if (req.socket) req.socket.setNoDelay(true);
373
-
374
- res.writeHead(200, {
375
- 'Content-Type': 'application/x-ndjson',
376
- 'Transfer-Encoding': 'chunked',
377
- 'Cache-Control': 'no-cache',
378
- 'Connection': 'keep-alive'
379
- });
380
- if (typeof res.flushHeaders === 'function') {
381
- res.flushHeaders();
382
- }
383
-
384
- const sendChunk = (delta, full) => {
385
- if (isClientClosed) return;
386
- try {
387
- res.write(JSON.stringify({ type: 'chunk', delta, full }) + '\n');
388
- } catch (_) {}
389
- };
390
-
391
- const fullResult = await this.promptWithRetry({
392
- promptText,
393
- systemPrompt,
394
- samplingMode,
395
- sessionType,
396
- initialPrompts,
397
- stream,
398
- requestId: reqId,
399
- responseConstraint: payload.responseConstraint,
400
- onChunk: (delta, full) => sendChunk(delta, full)
401
- });
402
-
403
- if (!isClientClosed) {
404
- res.write(JSON.stringify({ type: 'done', text: fullResult }) + '\n');
405
- res.end();
406
- }
407
- } catch (err) {
408
- if (!isClientClosed) {
409
- try {
410
- res.write(JSON.stringify({ type: 'error', error: err.message }) + '\n');
411
- res.end();
412
- } catch (_) {}
413
- }
414
- }
415
- });
416
- return;
417
- }
418
-
419
- res.writeHead(404, { 'Content-Type': 'application/json' });
420
- res.end(JSON.stringify({ error: 'Not Found' }));
421
- }
422
-
423
- async runExclusive(task) {
424
- const prev = this.currentPromptPromise || Promise.resolve();
425
- let resolveTask;
426
- this.currentPromptPromise = new Promise((r) => { resolveTask = r; });
427
- try {
428
- await prev.catch(() => {});
429
- return await task();
430
- } finally {
431
- resolveTask();
432
- }
433
- }
434
-
435
- async promptWithRetry(args) {
436
- return this.runExclusive(async () => {
437
- try {
438
- return await this.prompt(args);
439
- } catch (err) {
440
- debug('daemon', 'Prompt execution failed, attempting self-healing reconnect:', err.message);
441
- await this.initChrome();
442
- return await this.prompt(args);
443
- }
444
- });
445
- }
446
-
447
- async prompt({
448
- promptText,
449
- systemPrompt,
450
- samplingMode,
451
- sessionType = 'stateless',
452
- initialPrompts = null,
453
- stream = true,
454
- onChunk,
455
- requestId,
456
- responseConstraint,
457
- temperature,
458
- topK
459
- } = {}) {
460
- if (this.warmupPromise) {
461
- await this.warmupPromise.catch(() => {});
462
- }
463
-
464
- const reqId = requestId || `req_${Date.now()}_${Math.random().toString(36).slice(2)}`;
465
- const escapedPrompt = JSON.stringify(promptText);
466
- const escapedSystem = systemPrompt ? JSON.stringify(systemPrompt) : 'null';
467
- const escapedInitial = initialPrompts && Array.isArray(initialPrompts) ? JSON.stringify(initialPrompts) : 'null';
468
- const escapedSampling = samplingMode ? JSON.stringify(samplingMode) : 'null';
469
- const escapedConstraint = responseConstraint ? JSON.stringify(responseConstraint) : 'null';
470
- const isChat = sessionType === 'chat';
471
- const prefix = `__NANOBRIDGE_CHUNK_${reqId}__:`;
472
-
473
- if (stream && onChunk) {
474
- this.bridge.addConsoleHandler(prefix, (payload) => {
475
- try {
476
- const data = JSON.parse(payload);
477
- if (data.d) {
478
- onChunk(data.d);
479
- }
480
- } catch (err) {
481
- debug('daemon', 'Error in stream chunk handler:', err.message);
482
- }
483
- });
484
- }
485
-
486
- try {
487
- const evalResult = await this.bridge.evaluate(`(async () => {
488
- let sessionToDestroy = null;
489
- try {
490
- if (!('LanguageModel' in window)) {
491
- return { success: false, error: 'LanguageModel API not available' };
492
- }
493
- window.__nanobridge_current_req = '${reqId}';
494
-
495
- const sysPrompt = ${escapedSystem};
496
- const initPrompts = ${escapedInitial};
497
- const isChatSession = ${isChat};
498
-
499
- // Ensure base session exists
500
- if (!window.__nanobridge_base_session) {
501
- window.__nanobridge_base_session = await window.LanguageModel.create();
502
- }
503
-
504
- let session;
505
- if (isChatSession) {
506
- // Chat session management: stateful across turns
507
- const currentConfig = window.__nanobridge_chat_session_config || {};
508
- const sysMatches = currentConfig.systemPrompt === sysPrompt;
509
- const needsRecreate = !window.__nanobridge_chat_session || !sysMatches || (initPrompts && initPrompts.length > 0);
510
-
511
- if (needsRecreate) {
512
- if (window.__nanobridge_chat_session && typeof window.__nanobridge_chat_session.destroy === 'function') {
513
- try { window.__nanobridge_chat_session.destroy(); } catch (_) {}
514
- }
515
- if (sysPrompt || (initPrompts && initPrompts.length > 0)) {
516
- const opts = {};
517
- if (sysPrompt) opts.systemPrompt = sysPrompt;
518
- if (initPrompts && initPrompts.length > 0) opts.initialPrompts = initPrompts;
519
- window.__nanobridge_chat_session = await window.LanguageModel.create(opts);
520
- } else {
521
- window.__nanobridge_chat_session = await window.__nanobridge_base_session.clone();
522
- }
523
- window.__nanobridge_chat_session_config = { systemPrompt: sysPrompt };
524
- }
525
- session = window.__nanobridge_chat_session;
526
- } else {
527
- // Stateless execution (ask, one-off prompts, curl):
528
- if (sysPrompt || (initPrompts && initPrompts.length > 0)) {
529
- const opts = {};
530
- if (sysPrompt) opts.systemPrompt = sysPrompt;
531
- if (initPrompts && initPrompts.length > 0) opts.initialPrompts = initPrompts;
532
- session = await window.LanguageModel.create(opts);
533
- sessionToDestroy = session;
534
- } else {
535
- // Instant clone (1.7ms) from warm base session
536
- session = await window.__nanobridge_base_session.clone();
537
- sessionToDestroy = session;
538
- }
539
- }
540
-
541
- if (${escapedPrompt} === "") {
542
- return { success: true, text: "" };
543
- }
544
-
545
- const constraint = ${escapedConstraint};
546
- const stream = constraint
547
- ? session.promptStreaming(${escapedPrompt}, { responseConstraint: constraint })
548
- : session.promptStreaming(${escapedPrompt});
549
- let fullResult = '';
550
-
551
- for await (const chunk of stream) {
552
- if (window.__nanobridge_abort_req === '${reqId}') {
553
- if (sessionToDestroy) {
554
- try { sessionToDestroy.destroy(); } catch (_) {}
555
- }
556
- return { success: false, error: 'Request cancelled' };
557
- }
558
- if (chunk) {
559
- fullResult += chunk;
560
- console.debug('${prefix}' + JSON.stringify({ d: chunk }));
561
- }
562
- }
563
-
564
- let usage = null;
565
- let windowSize = null;
566
- try {
567
- usage = session.contextUsage;
568
- windowSize = session.contextWindow;
569
- } catch (_) {}
570
-
571
- if (sessionToDestroy) {
572
- try { sessionToDestroy.destroy(); } catch (_) {}
573
- }
574
-
575
- return { success: true, text: fullResult, contextUsage: usage, contextWindow: windowSize };
576
- } catch (e) {
577
- if (sessionToDestroy) {
578
- try { sessionToDestroy.destroy(); } catch (_) {}
579
- }
580
- if (${isChat}) {
581
- if (window.__nanobridge_chat_session && typeof window.__nanobridge_chat_session.destroy === 'function') {
582
- try { window.__nanobridge_chat_session.destroy(); } catch (_) {}
583
- }
584
- window.__nanobridge_chat_session = null;
585
- window.__nanobridge_chat_session_config = null;
586
- }
587
- return { success: false, error: e.message };
588
- }
589
- })()`, { userGesture: true, timeout: 180000 });
590
-
591
- if (!evalResult.success) {
592
- throw new Error(evalResult.error);
593
- }
594
- return evalResult.text;
595
- } finally {
596
- if (stream && onChunk) {
597
- this.bridge.removeConsoleHandler(prefix);
598
- }
599
- }
600
- }
601
-
602
- async cancelPrompt(reqId) {
603
- try {
604
- if (this.bridge && this.bridge.isConnected()) {
605
- await this.bridge.evaluate(`window.__nanobridge_abort_req = '${reqId}';`);
606
- }
607
- } catch (_) {}
608
- }
609
-
610
- async stop() {
611
- if (this.isStopping) return;
612
- this.isStopping = true;
613
- debug('daemon', 'Stopping NanoBridge Daemon...');
614
-
615
- if (this.idleTimer) clearTimeout(this.idleTimer);
616
- clearDaemonState();
617
-
618
- if (this.server) {
619
- try {
620
- this.server.close();
621
- } catch (_) {}
622
- this.server = null;
623
- }
624
-
625
- if (this.bridge) {
626
- await this.bridge.close().catch(() => {});
627
- this.bridge = null;
628
- }
629
-
630
- if (this.chromeInstance) {
631
- this.chromeInstance.close();
632
- this.chromeInstance = null;
633
- }
634
-
635
- debug('daemon', 'Daemon stopped successfully.');
636
- process.exit(0);
637
- }
638
- }
639
-
640
- // If executed directly (via background spawn)
641
- if (process.argv[1] && process.argv[1].endsWith('daemon/server.js')) {
642
- if (process.env.NANOBRIDGE_DEBUG === '1') {
643
- setDebugMode(true);
644
- }
645
- const daemon = new DaemonServer();
646
- daemon.start().catch((err) => {
647
- console.error('Failed to start daemon:', err);
648
- process.exit(1);
649
- });
650
- }
@@ -1,46 +0,0 @@
1
- import fs from 'node:fs';
2
- import os from 'node:os';
3
- import path from 'node:path';
4
- import process from 'node:process';
5
-
6
- const CONFIG_DIR = path.join(os.homedir(), '.nanobridge');
7
- const STATE_FILE = path.join(CONFIG_DIR, 'daemon.json');
8
-
9
- export function getDaemonState() {
10
- try {
11
- if (fs.existsSync(STATE_FILE)) {
12
- const data = JSON.parse(fs.readFileSync(STATE_FILE, 'utf8'));
13
- if (data && data.pid) {
14
- // Check if process is still alive
15
- try {
16
- process.kill(data.pid, 0);
17
- return data;
18
- } catch (_) {
19
- // Process not alive, stale file
20
- clearDaemonState();
21
- return null;
22
- }
23
- }
24
- }
25
- } catch (_) {
26
- clearDaemonState();
27
- }
28
- return null;
29
- }
30
-
31
- export function saveDaemonState(state) {
32
- try {
33
- if (!fs.existsSync(CONFIG_DIR)) {
34
- fs.mkdirSync(CONFIG_DIR, { recursive: true });
35
- }
36
- fs.writeFileSync(STATE_FILE, JSON.stringify(state, null, 2), 'utf8');
37
- } catch (_) {}
38
- }
39
-
40
- export function clearDaemonState() {
41
- try {
42
- if (fs.existsSync(STATE_FILE)) {
43
- fs.unlinkSync(STATE_FILE);
44
- }
45
- } catch (_) {}
46
- }