nanobridge 0.2.0 → 0.2.2
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/package.json +2 -2
- package/src/chat/session.js +3 -6
- package/src/chrome/bridge.js +5 -6
- package/src/chrome/launch.js +4 -1
- package/src/cli.js +11 -1
- package/src/commands/chat.js +26 -11
- package/src/daemon/client.js +40 -9
- package/src/daemon/server.js +141 -46
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nanobridge",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.2",
|
|
4
4
|
"description": "Chrome Built-in AI CLI bridge to on-device language models via CDP",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
},
|
|
9
9
|
"scripts": {
|
|
10
10
|
"start": "node ./bin/nanobridge.js",
|
|
11
|
-
"test": "node --test test
|
|
11
|
+
"test": "node --test test/"
|
|
12
12
|
},
|
|
13
13
|
"keywords": [
|
|
14
14
|
"chrome",
|
package/src/chat/session.js
CHANGED
|
@@ -138,14 +138,11 @@ export class ChatSessionManager {
|
|
|
138
138
|
|
|
139
139
|
const stream = session.promptStreaming(${JSON.stringify(promptToSend)}, promptOpts);
|
|
140
140
|
let finalOutput = '';
|
|
141
|
-
let prev = '';
|
|
142
141
|
|
|
143
142
|
for await (const chunk of stream) {
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
if (delta) {
|
|
148
|
-
console.debug('${prefix}' + JSON.stringify({ d: delta }));
|
|
143
|
+
if (chunk) {
|
|
144
|
+
finalOutput += chunk;
|
|
145
|
+
console.debug('${prefix}' + JSON.stringify({ d: chunk }));
|
|
149
146
|
}
|
|
150
147
|
}
|
|
151
148
|
|
package/src/chrome/bridge.js
CHANGED
|
@@ -305,12 +305,11 @@ export class ChromeBridge {
|
|
|
305
305
|
const session = await window.LanguageModel.create(${createArgs});
|
|
306
306
|
const stream = session.promptStreaming(${escapedPrompt});
|
|
307
307
|
let finalResult = '';
|
|
308
|
-
let prev = '';
|
|
309
308
|
for await (const chunk of stream) {
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
309
|
+
if (chunk) {
|
|
310
|
+
finalResult += chunk;
|
|
311
|
+
console.debug('${prefix}' + JSON.stringify({ d: chunk }));
|
|
312
|
+
}
|
|
314
313
|
}
|
|
315
314
|
if (typeof session.destroy === 'function') {
|
|
316
315
|
session.destroy();
|
|
@@ -404,7 +403,7 @@ export class ChromeBridge {
|
|
|
404
403
|
console.debug('${prefix}' + JSON.stringify({ type: 'first_chunk' }));
|
|
405
404
|
}
|
|
406
405
|
chunkCount++;
|
|
407
|
-
finalOutput
|
|
406
|
+
finalOutput += chunk;
|
|
408
407
|
console.debug('${prefix}' + JSON.stringify({ type: 'chunk' }));
|
|
409
408
|
}
|
|
410
409
|
|
package/src/chrome/launch.js
CHANGED
|
@@ -140,6 +140,9 @@ export async function launchChrome(options = {}) {
|
|
|
140
140
|
try {
|
|
141
141
|
if (proc.pid) {
|
|
142
142
|
if (!isWindows) {
|
|
143
|
+
try {
|
|
144
|
+
execSync(`pkill -9 -P ${proc.pid}`, { stdio: 'ignore' });
|
|
145
|
+
} catch (_) {}
|
|
143
146
|
try {
|
|
144
147
|
process.kill(-proc.pid, 'SIGKILL');
|
|
145
148
|
} catch (_) {
|
|
@@ -151,7 +154,7 @@ export async function launchChrome(options = {}) {
|
|
|
151
154
|
}
|
|
152
155
|
} catch (_) {}
|
|
153
156
|
|
|
154
|
-
if (
|
|
157
|
+
if (userDataDir && !isWindows) {
|
|
155
158
|
try {
|
|
156
159
|
execSync(`pkill -9 -f "${userDataDir}"`, { stdio: 'ignore' });
|
|
157
160
|
} catch (_) {}
|
package/src/cli.js
CHANGED
|
@@ -9,7 +9,17 @@ import { handleServe } from './commands/serve.js';
|
|
|
9
9
|
import { setJsonMode, setDebugMode, log, logError, style } from './utils/output.js';
|
|
10
10
|
import { NanoBridgeError } from './utils/errors.js';
|
|
11
11
|
|
|
12
|
-
|
|
12
|
+
import fs from 'node:fs';
|
|
13
|
+
import path from 'node:path';
|
|
14
|
+
import { fileURLToPath } from 'node:url';
|
|
15
|
+
|
|
16
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
17
|
+
const __dirname = path.dirname(__filename);
|
|
18
|
+
let VERSION = '0.2.0';
|
|
19
|
+
try {
|
|
20
|
+
const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, '../package.json'), 'utf8'));
|
|
21
|
+
if (pkg.version) VERSION = pkg.version;
|
|
22
|
+
} catch (_) {}
|
|
13
23
|
|
|
14
24
|
export function printHelp() {
|
|
15
25
|
log(`
|
package/src/commands/chat.js
CHANGED
|
@@ -139,7 +139,16 @@ Conversation preserved.
|
|
|
139
139
|
}
|
|
140
140
|
|
|
141
141
|
config.systemPrompt = val.trim();
|
|
142
|
-
if (
|
|
142
|
+
if (daemon) {
|
|
143
|
+
const initialPrompts = history.formatInitialPrompts(config.systemPrompt);
|
|
144
|
+
await streamPromptFromDaemon(daemon, {
|
|
145
|
+
promptText: '',
|
|
146
|
+
systemPrompt: config.systemPrompt,
|
|
147
|
+
sessionType: 'chat',
|
|
148
|
+
initialPrompts,
|
|
149
|
+
stream: false
|
|
150
|
+
}).catch(() => {});
|
|
151
|
+
} else if (sessionManager) {
|
|
143
152
|
await sessionManager.recreateSession({ preserveHistory: true }).catch(() => {});
|
|
144
153
|
}
|
|
145
154
|
log(`
|
|
@@ -209,8 +218,18 @@ JSON mode enabled.
|
|
|
209
218
|
|
|
210
219
|
if (cmd === 'context') {
|
|
211
220
|
const turnCount = history.length;
|
|
212
|
-
|
|
213
|
-
|
|
221
|
+
let estimatedTokens = turnCount * 50;
|
|
222
|
+
let windowSize = 9216;
|
|
223
|
+
if (daemon) {
|
|
224
|
+
try {
|
|
225
|
+
const res = await fetch(`http://127.0.0.1:${daemon.port}/status`);
|
|
226
|
+
const data = await res.json();
|
|
227
|
+
if (data.chatStats && typeof data.chatStats.contextUsage === 'number') {
|
|
228
|
+
estimatedTokens = data.chatStats.contextUsage;
|
|
229
|
+
windowSize = data.chatStats.contextWindow || 9216;
|
|
230
|
+
}
|
|
231
|
+
} catch (_) {}
|
|
232
|
+
}
|
|
214
233
|
const pct = ((estimatedTokens / windowSize) * 100).toFixed(1);
|
|
215
234
|
|
|
216
235
|
log(`
|
|
@@ -246,7 +265,7 @@ TopK unsupported
|
|
|
246
265
|
if (cmd === 'clear' || cmd === 'reset') {
|
|
247
266
|
history.clear();
|
|
248
267
|
if (daemon) {
|
|
249
|
-
await resetDaemon().catch(() => {});
|
|
268
|
+
await resetDaemon({ session: 'chat' }).catch(() => {});
|
|
250
269
|
}
|
|
251
270
|
log(`
|
|
252
271
|
Conversation cleared.
|
|
@@ -264,7 +283,7 @@ Configuration preserved.
|
|
|
264
283
|
config.responseSchema = null;
|
|
265
284
|
config.schemaPath = null;
|
|
266
285
|
if (daemon) {
|
|
267
|
-
await resetDaemon().catch(() => {});
|
|
286
|
+
await resetDaemon({ session: 'chat' }).catch(() => {});
|
|
268
287
|
}
|
|
269
288
|
log(`
|
|
270
289
|
New session started.
|
|
@@ -334,11 +353,6 @@ Run ${style('/help', 'bold')} to see available commands.
|
|
|
334
353
|
log(`${style('📎 Attached:', 'dim')} ${names}`);
|
|
335
354
|
}
|
|
336
355
|
|
|
337
|
-
// Format full prompt text with history
|
|
338
|
-
const promptToSend = history.length > 0
|
|
339
|
-
? `${history.formatAsPromptText(config.systemPrompt)}\n\nUser: ${finalPrompt}\n\nAssistant:`
|
|
340
|
-
: finalPrompt;
|
|
341
|
-
|
|
342
356
|
let responseConstraint = null;
|
|
343
357
|
if (config.responseSchema) {
|
|
344
358
|
responseConstraint = config.responseSchema;
|
|
@@ -351,9 +365,10 @@ Run ${style('/help', 'bold')} to see available commands.
|
|
|
351
365
|
let accumulated = '';
|
|
352
366
|
if (daemon) {
|
|
353
367
|
accumulated = await streamPromptFromDaemon(daemon, {
|
|
354
|
-
promptText:
|
|
368
|
+
promptText: finalPrompt,
|
|
355
369
|
systemPrompt: config.systemPrompt,
|
|
356
370
|
samplingMode: config.samplingMode,
|
|
371
|
+
sessionType: 'chat',
|
|
357
372
|
responseConstraint,
|
|
358
373
|
onChunk: (delta) => {
|
|
359
374
|
process.stdout.write(delta);
|
package/src/daemon/client.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import http from 'node:http';
|
|
2
|
-
import { spawn } from 'node:child_process';
|
|
2
|
+
import { spawn, execSync } from 'node:child_process';
|
|
3
3
|
import fs from 'node:fs';
|
|
4
4
|
import os from 'node:os';
|
|
5
5
|
import path from 'node:path';
|
|
@@ -137,10 +137,28 @@ export async function streamPromptFromDaemon(daemonOrOpts, maybeOpts = {}) {
|
|
|
137
137
|
? { ...maybeOpts, port: daemonOrOpts.port }
|
|
138
138
|
: (daemonOrOpts || {});
|
|
139
139
|
|
|
140
|
-
const {
|
|
140
|
+
const {
|
|
141
|
+
port,
|
|
142
|
+
promptText,
|
|
143
|
+
systemPrompt,
|
|
144
|
+
samplingMode,
|
|
145
|
+
sessionType,
|
|
146
|
+
initialPrompts,
|
|
147
|
+
responseConstraint,
|
|
148
|
+
stream = true,
|
|
149
|
+
onChunk
|
|
150
|
+
} = opts;
|
|
141
151
|
|
|
142
152
|
return new Promise((resolve, reject) => {
|
|
143
|
-
const payload = JSON.stringify({
|
|
153
|
+
const payload = JSON.stringify({
|
|
154
|
+
promptText,
|
|
155
|
+
systemPrompt,
|
|
156
|
+
samplingMode,
|
|
157
|
+
sessionType,
|
|
158
|
+
initialPrompts,
|
|
159
|
+
responseConstraint,
|
|
160
|
+
stream
|
|
161
|
+
});
|
|
144
162
|
const req = http.request(`http://127.0.0.1:${port}/prompt`, {
|
|
145
163
|
method: 'POST',
|
|
146
164
|
headers: {
|
|
@@ -151,6 +169,7 @@ export async function streamPromptFromDaemon(daemonOrOpts, maybeOpts = {}) {
|
|
|
151
169
|
const decoder = new StringDecoder('utf8');
|
|
152
170
|
let buffer = '';
|
|
153
171
|
let finalText = '';
|
|
172
|
+
let streamAccumulated = '';
|
|
154
173
|
|
|
155
174
|
res.on('data', (chunk) => {
|
|
156
175
|
buffer += decoder.write(chunk);
|
|
@@ -161,8 +180,9 @@ export async function streamPromptFromDaemon(daemonOrOpts, maybeOpts = {}) {
|
|
|
161
180
|
if (!line.trim()) continue;
|
|
162
181
|
try {
|
|
163
182
|
const data = JSON.parse(line);
|
|
164
|
-
if (data.type === 'chunk'
|
|
165
|
-
|
|
183
|
+
if (data.type === 'chunk') {
|
|
184
|
+
if (data.delta) streamAccumulated += data.delta;
|
|
185
|
+
if (onChunk) onChunk(data.delta, data.full);
|
|
166
186
|
} else if (data.type === 'done') {
|
|
167
187
|
finalText = data.text;
|
|
168
188
|
} else if (data.type === 'error') {
|
|
@@ -181,7 +201,7 @@ export async function streamPromptFromDaemon(daemonOrOpts, maybeOpts = {}) {
|
|
|
181
201
|
if (data.type === 'done') finalText = data.text;
|
|
182
202
|
} catch (_) {}
|
|
183
203
|
}
|
|
184
|
-
resolve(finalText);
|
|
204
|
+
resolve(finalText || streamAccumulated);
|
|
185
205
|
});
|
|
186
206
|
});
|
|
187
207
|
|
|
@@ -195,14 +215,15 @@ export async function streamPromptFromDaemon(daemonOrOpts, maybeOpts = {}) {
|
|
|
195
215
|
});
|
|
196
216
|
}
|
|
197
217
|
|
|
198
|
-
export async function resetDaemon() {
|
|
218
|
+
export async function resetDaemon(options = {}) {
|
|
199
219
|
const active = await getActiveDaemon();
|
|
200
220
|
if (!active) {
|
|
201
221
|
return { success: false, message: 'Daemon is not running' };
|
|
202
222
|
}
|
|
203
223
|
|
|
224
|
+
const query = options.session ? `?session=${encodeURIComponent(options.session)}` : '';
|
|
204
225
|
return new Promise((resolve, reject) => {
|
|
205
|
-
const req = http.request(`http://127.0.0.1:${active.port}/reset`, { method: 'POST', timeout: 5000 }, (res) => {
|
|
226
|
+
const req = http.request(`http://127.0.0.1:${active.port}/reset${query}`, { method: 'POST', timeout: 5000 }, (res) => {
|
|
206
227
|
let data = '';
|
|
207
228
|
res.on('data', (c) => { data += c; });
|
|
208
229
|
res.on('end', () => {
|
|
@@ -220,7 +241,12 @@ export async function resetDaemon() {
|
|
|
220
241
|
|
|
221
242
|
export async function stopDaemon() {
|
|
222
243
|
const active = await getActiveDaemon();
|
|
244
|
+
const profileDir = path.join(os.homedir(), '.nanobridge', 'profile');
|
|
245
|
+
|
|
223
246
|
if (!active) {
|
|
247
|
+
try {
|
|
248
|
+
execSync(`pkill -9 -f "${profileDir}"`, { stdio: 'ignore' });
|
|
249
|
+
} catch (_) {}
|
|
224
250
|
clearDaemonState();
|
|
225
251
|
return { stopped: true, wasRunning: false };
|
|
226
252
|
}
|
|
@@ -228,13 +254,18 @@ export async function stopDaemon() {
|
|
|
228
254
|
return new Promise((resolve) => {
|
|
229
255
|
const req = http.request(`http://127.0.0.1:${active.port}/stop`, { method: 'POST', timeout: 2000 }, (res) => {
|
|
230
256
|
clearDaemonState();
|
|
257
|
+
try {
|
|
258
|
+
execSync(`pkill -9 -f "${profileDir}"`, { stdio: 'ignore' });
|
|
259
|
+
} catch (_) {}
|
|
231
260
|
resolve({ stopped: true, wasRunning: true, pid: active.pid });
|
|
232
261
|
});
|
|
233
262
|
req.on('error', () => {
|
|
234
|
-
// Force kill if HTTP request fails
|
|
235
263
|
try {
|
|
236
264
|
if (active.pid) process.kill(active.pid, 'SIGKILL');
|
|
237
265
|
} catch (_) {}
|
|
266
|
+
try {
|
|
267
|
+
execSync(`pkill -9 -f "${profileDir}"`, { stdio: 'ignore' });
|
|
268
|
+
} catch (_) {}
|
|
238
269
|
clearDaemonState();
|
|
239
270
|
resolve({ stopped: true, wasRunning: true, pid: active.pid });
|
|
240
271
|
});
|
package/src/daemon/server.js
CHANGED
|
@@ -118,13 +118,14 @@ export class DaemonServer {
|
|
|
118
118
|
if (this.bridge && this.bridge.isConnected()) {
|
|
119
119
|
await this.bridge.evaluate(`(async () => {
|
|
120
120
|
if ('LanguageModel' in window) {
|
|
121
|
-
if (!window.
|
|
122
|
-
window.
|
|
123
|
-
window.__nanobridge_session_config = { systemPrompt: null, samplingMode: null };
|
|
124
|
-
try {
|
|
125
|
-
await window.__nanobridge_session.prompt('hi');
|
|
126
|
-
} catch (_) {}
|
|
121
|
+
if (!window.__nanobridge_base_session) {
|
|
122
|
+
window.__nanobridge_base_session = await window.LanguageModel.create();
|
|
127
123
|
}
|
|
124
|
+
try {
|
|
125
|
+
const s = await window.__nanobridge_base_session.clone();
|
|
126
|
+
await s.prompt('hi');
|
|
127
|
+
s.destroy();
|
|
128
|
+
} catch (_) {}
|
|
128
129
|
}
|
|
129
130
|
})()`, { userGesture: true, timeout: 180000 });
|
|
130
131
|
this.isWarmed = true;
|
|
@@ -158,6 +159,19 @@ export class DaemonServer {
|
|
|
158
159
|
// Standard Health/Status
|
|
159
160
|
if (req.method === 'GET' && (url.pathname === '/status' || url.pathname === '/health')) {
|
|
160
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
|
+
}
|
|
161
175
|
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
162
176
|
res.end(JSON.stringify({
|
|
163
177
|
status: 'ready',
|
|
@@ -167,6 +181,7 @@ export class DaemonServer {
|
|
|
167
181
|
uptimeMs: Date.now() - this.startTime,
|
|
168
182
|
warmed: this.isWarmed,
|
|
169
183
|
bridgeConnected,
|
|
184
|
+
chatStats,
|
|
170
185
|
openai_base_url: `http://${this.host}:${this.port}/v1`
|
|
171
186
|
}));
|
|
172
187
|
return;
|
|
@@ -289,22 +304,38 @@ export class DaemonServer {
|
|
|
289
304
|
|
|
290
305
|
// Reset / Recycle Context Endpoint
|
|
291
306
|
if ((req.method === 'POST' || req.method === 'GET') && url.pathname === '/reset') {
|
|
307
|
+
const resetType = url.searchParams.get('session');
|
|
292
308
|
try {
|
|
293
309
|
await this.runExclusive(async () => {
|
|
294
|
-
debug('daemon', 'Resetting Chrome AI session context & destroying active session...');
|
|
295
310
|
if (this.bridge && this.bridge.isConnected()) {
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
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
|
+
}
|
|
303
335
|
}
|
|
304
|
-
await this.warmupSession();
|
|
305
336
|
});
|
|
306
337
|
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
307
|
-
res.end(JSON.stringify({ success: true, message: '
|
|
338
|
+
res.end(JSON.stringify({ success: true, message: 'Reset successfully' }));
|
|
308
339
|
} catch (err) {
|
|
309
340
|
res.writeHead(500, { 'Content-Type': 'application/json' });
|
|
310
341
|
res.end(JSON.stringify({ success: false, error: err.message }));
|
|
@@ -333,6 +364,8 @@ export class DaemonServer {
|
|
|
333
364
|
const promptText = payload.promptText || '';
|
|
334
365
|
const systemPrompt = payload.systemPrompt;
|
|
335
366
|
const samplingMode = payload.samplingMode;
|
|
367
|
+
const sessionType = payload.sessionType || 'stateless';
|
|
368
|
+
const initialPrompts = payload.initialPrompts;
|
|
336
369
|
const stream = payload.stream !== false;
|
|
337
370
|
|
|
338
371
|
if (res.socket) res.socket.setNoDelay(true);
|
|
@@ -359,6 +392,8 @@ export class DaemonServer {
|
|
|
359
392
|
promptText,
|
|
360
393
|
systemPrompt,
|
|
361
394
|
samplingMode,
|
|
395
|
+
sessionType,
|
|
396
|
+
initialPrompts,
|
|
362
397
|
stream,
|
|
363
398
|
requestId: reqId,
|
|
364
399
|
responseConstraint: payload.responseConstraint,
|
|
@@ -409,7 +444,19 @@ export class DaemonServer {
|
|
|
409
444
|
});
|
|
410
445
|
}
|
|
411
446
|
|
|
412
|
-
async prompt({
|
|
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
|
+
} = {}) {
|
|
413
460
|
if (this.warmupPromise) {
|
|
414
461
|
await this.warmupPromise.catch(() => {});
|
|
415
462
|
}
|
|
@@ -417,8 +464,10 @@ export class DaemonServer {
|
|
|
417
464
|
const reqId = requestId || `req_${Date.now()}_${Math.random().toString(36).slice(2)}`;
|
|
418
465
|
const escapedPrompt = JSON.stringify(promptText);
|
|
419
466
|
const escapedSystem = systemPrompt ? JSON.stringify(systemPrompt) : 'null';
|
|
467
|
+
const escapedInitial = initialPrompts && Array.isArray(initialPrompts) ? JSON.stringify(initialPrompts) : 'null';
|
|
420
468
|
const escapedSampling = samplingMode ? JSON.stringify(samplingMode) : 'null';
|
|
421
469
|
const escapedConstraint = responseConstraint ? JSON.stringify(responseConstraint) : 'null';
|
|
470
|
+
const isChat = sessionType === 'chat';
|
|
422
471
|
const prefix = `__NANOBRIDGE_CHUNK_${reqId}__:`;
|
|
423
472
|
|
|
424
473
|
if (stream && onChunk) {
|
|
@@ -436,6 +485,7 @@ export class DaemonServer {
|
|
|
436
485
|
|
|
437
486
|
try {
|
|
438
487
|
const evalResult = await this.bridge.evaluate(`(async () => {
|
|
488
|
+
let sessionToDestroy = null;
|
|
439
489
|
try {
|
|
440
490
|
if (!('LanguageModel' in window)) {
|
|
441
491
|
return { success: false, error: 'LanguageModel API not available' };
|
|
@@ -443,52 +493,97 @@ export class DaemonServer {
|
|
|
443
493
|
window.__nanobridge_current_req = '${reqId}';
|
|
444
494
|
|
|
445
495
|
const sysPrompt = ${escapedSystem};
|
|
446
|
-
const
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
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;
|
|
457
538
|
}
|
|
458
|
-
const createOpts = {};
|
|
459
|
-
if (sysPrompt) createOpts.systemPrompt = sysPrompt;
|
|
460
|
-
if (sampling) createOpts.samplingMode = sampling;
|
|
461
|
-
window.__nanobridge_session = await window.LanguageModel.create(createOpts);
|
|
462
|
-
window.__nanobridge_session_config = { systemPrompt: sysPrompt, samplingMode: sampling };
|
|
463
539
|
}
|
|
464
540
|
|
|
465
|
-
|
|
541
|
+
if (${escapedPrompt} === "") {
|
|
542
|
+
return { success: true, text: "" };
|
|
543
|
+
}
|
|
544
|
+
|
|
466
545
|
const constraint = ${escapedConstraint};
|
|
467
546
|
const stream = constraint
|
|
468
547
|
? session.promptStreaming(${escapedPrompt}, { responseConstraint: constraint })
|
|
469
548
|
: session.promptStreaming(${escapedPrompt});
|
|
470
|
-
let
|
|
471
|
-
let prev = '';
|
|
549
|
+
let fullResult = '';
|
|
472
550
|
|
|
473
551
|
for await (const chunk of stream) {
|
|
474
552
|
if (window.__nanobridge_abort_req === '${reqId}') {
|
|
553
|
+
if (sessionToDestroy) {
|
|
554
|
+
try { sessionToDestroy.destroy(); } catch (_) {}
|
|
555
|
+
}
|
|
475
556
|
return { success: false, error: 'Request cancelled' };
|
|
476
557
|
}
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
if (delta) {
|
|
481
|
-
console.debug('${prefix}' + JSON.stringify({ d: delta }));
|
|
558
|
+
if (chunk) {
|
|
559
|
+
fullResult += chunk;
|
|
560
|
+
console.debug('${prefix}' + JSON.stringify({ d: chunk }));
|
|
482
561
|
}
|
|
483
562
|
}
|
|
484
563
|
|
|
485
|
-
|
|
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 };
|
|
486
576
|
} catch (e) {
|
|
487
|
-
if (
|
|
488
|
-
try {
|
|
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;
|
|
489
586
|
}
|
|
490
|
-
window.__nanobridge_session = null;
|
|
491
|
-
window.__nanobridge_session_config = null;
|
|
492
587
|
return { success: false, error: e.message };
|
|
493
588
|
}
|
|
494
589
|
})()`, { userGesture: true, timeout: 180000 });
|