nanobridge 0.1.1 → 0.2.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 +15 -10
- package/package.json +1 -1
- package/src/chat/commands.js +67 -0
- package/src/chat/config.js +65 -0
- package/src/chat/history.js +103 -0
- package/src/chat/session.js +340 -0
- package/src/chrome/bridge.js +38 -15
- package/src/chrome/capabilities.js +99 -0
- package/src/chrome/launch.js +44 -13
- package/src/commands/chat.js +283 -101
- package/src/commands/status.js +14 -5
- package/src/daemon/client.js +29 -4
- package/src/daemon/server.js +54 -16
- package/src/daemon/state.js +0 -3
- package/test/chat.test.js +250 -0
package/src/daemon/server.js
CHANGED
|
@@ -118,10 +118,15 @@ 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
|
-
|
|
122
|
-
|
|
121
|
+
if (!window.__nanobridge_session) {
|
|
122
|
+
window.__nanobridge_session = await window.LanguageModel.create();
|
|
123
|
+
window.__nanobridge_session_config = { systemPrompt: null, samplingMode: null };
|
|
124
|
+
try {
|
|
125
|
+
await window.__nanobridge_session.prompt('hi');
|
|
126
|
+
} catch (_) {}
|
|
127
|
+
}
|
|
123
128
|
}
|
|
124
|
-
})()`, { userGesture: true });
|
|
129
|
+
})()`, { userGesture: true, timeout: 180000 });
|
|
125
130
|
this.isWarmed = true;
|
|
126
131
|
debug('daemon', 'Warmup completed successfully.');
|
|
127
132
|
}
|
|
@@ -286,9 +291,15 @@ export class DaemonServer {
|
|
|
286
291
|
if ((req.method === 'POST' || req.method === 'GET') && url.pathname === '/reset') {
|
|
287
292
|
try {
|
|
288
293
|
await this.runExclusive(async () => {
|
|
289
|
-
debug('daemon', 'Resetting Chrome AI session context &
|
|
294
|
+
debug('daemon', 'Resetting Chrome AI session context & destroying active session...');
|
|
290
295
|
if (this.bridge && this.bridge.isConnected()) {
|
|
291
|
-
await this.bridge.
|
|
296
|
+
await this.bridge.evaluate(`(() => {
|
|
297
|
+
if (window.__nanobridge_session && typeof window.__nanobridge_session.destroy === 'function') {
|
|
298
|
+
try { window.__nanobridge_session.destroy(); } catch (_) {}
|
|
299
|
+
}
|
|
300
|
+
window.__nanobridge_session = null;
|
|
301
|
+
window.__nanobridge_session_config = null;
|
|
302
|
+
})()`);
|
|
292
303
|
}
|
|
293
304
|
await this.warmupSession();
|
|
294
305
|
});
|
|
@@ -321,6 +332,7 @@ export class DaemonServer {
|
|
|
321
332
|
const payload = JSON.parse(body || '{}');
|
|
322
333
|
const promptText = payload.promptText || '';
|
|
323
334
|
const systemPrompt = payload.systemPrompt;
|
|
335
|
+
const samplingMode = payload.samplingMode;
|
|
324
336
|
const stream = payload.stream !== false;
|
|
325
337
|
|
|
326
338
|
if (res.socket) res.socket.setNoDelay(true);
|
|
@@ -346,8 +358,10 @@ export class DaemonServer {
|
|
|
346
358
|
const fullResult = await this.promptWithRetry({
|
|
347
359
|
promptText,
|
|
348
360
|
systemPrompt,
|
|
361
|
+
samplingMode,
|
|
349
362
|
stream,
|
|
350
363
|
requestId: reqId,
|
|
364
|
+
responseConstraint: payload.responseConstraint,
|
|
351
365
|
onChunk: (delta, full) => sendChunk(delta, full)
|
|
352
366
|
});
|
|
353
367
|
|
|
@@ -395,7 +409,7 @@ export class DaemonServer {
|
|
|
395
409
|
});
|
|
396
410
|
}
|
|
397
411
|
|
|
398
|
-
async prompt({ promptText, systemPrompt, stream = true, onChunk, requestId } = {}) {
|
|
412
|
+
async prompt({ promptText, systemPrompt, samplingMode, stream = true, onChunk, requestId, responseConstraint, temperature, topK } = {}) {
|
|
399
413
|
if (this.warmupPromise) {
|
|
400
414
|
await this.warmupPromise.catch(() => {});
|
|
401
415
|
}
|
|
@@ -403,6 +417,8 @@ export class DaemonServer {
|
|
|
403
417
|
const reqId = requestId || `req_${Date.now()}_${Math.random().toString(36).slice(2)}`;
|
|
404
418
|
const escapedPrompt = JSON.stringify(promptText);
|
|
405
419
|
const escapedSystem = systemPrompt ? JSON.stringify(systemPrompt) : 'null';
|
|
420
|
+
const escapedSampling = samplingMode ? JSON.stringify(samplingMode) : 'null';
|
|
421
|
+
const escapedConstraint = responseConstraint ? JSON.stringify(responseConstraint) : 'null';
|
|
406
422
|
const prefix = `__NANOBRIDGE_CHUNK_${reqId}__:`;
|
|
407
423
|
|
|
408
424
|
if (stream && onChunk) {
|
|
@@ -427,33 +443,55 @@ export class DaemonServer {
|
|
|
427
443
|
window.__nanobridge_current_req = '${reqId}';
|
|
428
444
|
|
|
429
445
|
const sysPrompt = ${escapedSystem};
|
|
430
|
-
const
|
|
431
|
-
|
|
446
|
+
const sampling = ${escapedSampling};
|
|
447
|
+
|
|
448
|
+
// Check if warm session exists and matches configuration
|
|
449
|
+
const currentConfig = window.__nanobridge_session_config || {};
|
|
450
|
+
const configMatches = window.__nanobridge_session &&
|
|
451
|
+
currentConfig.systemPrompt === sysPrompt &&
|
|
452
|
+
currentConfig.samplingMode === sampling;
|
|
453
|
+
|
|
454
|
+
if (!configMatches) {
|
|
455
|
+
if (window.__nanobridge_session && typeof window.__nanobridge_session.destroy === 'function') {
|
|
456
|
+
try { window.__nanobridge_session.destroy(); } catch (_) {}
|
|
457
|
+
}
|
|
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
|
+
}
|
|
432
464
|
|
|
433
|
-
const
|
|
465
|
+
const session = window.__nanobridge_session;
|
|
466
|
+
const constraint = ${escapedConstraint};
|
|
467
|
+
const stream = constraint
|
|
468
|
+
? session.promptStreaming(${escapedPrompt}, { responseConstraint: constraint })
|
|
469
|
+
: session.promptStreaming(${escapedPrompt});
|
|
434
470
|
let finalResult = '';
|
|
435
471
|
let prev = '';
|
|
436
472
|
|
|
437
473
|
for await (const chunk of stream) {
|
|
438
474
|
if (window.__nanobridge_abort_req === '${reqId}') {
|
|
439
|
-
if (typeof session.destroy === 'function') session.destroy();
|
|
440
475
|
return { success: false, error: 'Request cancelled' };
|
|
441
476
|
}
|
|
442
477
|
finalResult = chunk;
|
|
443
478
|
const delta = chunk.startsWith(prev) ? chunk.slice(prev.length) : chunk;
|
|
444
479
|
prev = chunk;
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
if (typeof session.destroy === 'function') {
|
|
449
|
-
session.destroy();
|
|
480
|
+
if (delta) {
|
|
481
|
+
console.debug('${prefix}' + JSON.stringify({ d: delta }));
|
|
482
|
+
}
|
|
450
483
|
}
|
|
451
484
|
|
|
452
485
|
return { success: true, text: finalResult };
|
|
453
486
|
} catch (e) {
|
|
487
|
+
if (window.__nanobridge_session && typeof window.__nanobridge_session.destroy === 'function') {
|
|
488
|
+
try { window.__nanobridge_session.destroy(); } catch (_) {}
|
|
489
|
+
}
|
|
490
|
+
window.__nanobridge_session = null;
|
|
491
|
+
window.__nanobridge_session_config = null;
|
|
454
492
|
return { success: false, error: e.message };
|
|
455
493
|
}
|
|
456
|
-
})()`, { userGesture: true });
|
|
494
|
+
})()`, { userGesture: true, timeout: 180000 });
|
|
457
495
|
|
|
458
496
|
if (!evalResult.success) {
|
|
459
497
|
throw new Error(evalResult.error);
|
package/src/daemon/state.js
CHANGED
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
import { test, describe } from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
import { parseCommand, formatChatHelp } from '../src/chat/commands.js';
|
|
7
|
+
import { createDefaultChatConfig, validateSamplingMode, validateLanguageCode, loadAndValidateJsonSchema } from '../src/chat/config.js';
|
|
8
|
+
import { ConversationHistory } from '../src/chat/history.js';
|
|
9
|
+
import { ChatSessionManager } from '../src/chat/session.js';
|
|
10
|
+
|
|
11
|
+
describe('Chat Slash Command Parser', () => {
|
|
12
|
+
test('parses standard slash commands correctly', () => {
|
|
13
|
+
assert.deepEqual(parseCommand('/sampling creative'), {
|
|
14
|
+
isCommand: true,
|
|
15
|
+
command: 'sampling',
|
|
16
|
+
value: 'creative',
|
|
17
|
+
args: ['creative'],
|
|
18
|
+
raw: '/sampling creative'
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
assert.deepEqual(parseCommand('/system Answer in Turkish.'), {
|
|
22
|
+
isCommand: true,
|
|
23
|
+
command: 'system',
|
|
24
|
+
value: 'Answer in Turkish.',
|
|
25
|
+
args: ['Answer', 'in', 'Turkish.'],
|
|
26
|
+
raw: '/system Answer in Turkish.'
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
assert.deepEqual(parseCommand('/json on'), {
|
|
30
|
+
isCommand: true,
|
|
31
|
+
command: 'json',
|
|
32
|
+
value: 'on',
|
|
33
|
+
args: ['on'],
|
|
34
|
+
raw: '/json on'
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
assert.deepEqual(parseCommand('/schema ./data.json'), {
|
|
38
|
+
isCommand: true,
|
|
39
|
+
command: 'schema',
|
|
40
|
+
value: './data.json',
|
|
41
|
+
args: ['./data.json'],
|
|
42
|
+
raw: '/schema ./data.json'
|
|
43
|
+
});
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
test('recognizes parameterless commands', () => {
|
|
47
|
+
assert.strictEqual(parseCommand('/context').command, 'context');
|
|
48
|
+
assert.strictEqual(parseCommand('/clear').command, 'clear');
|
|
49
|
+
assert.strictEqual(parseCommand('/new').command, 'new');
|
|
50
|
+
assert.strictEqual(parseCommand('/settings').command, 'settings');
|
|
51
|
+
assert.strictEqual(parseCommand('/help').command, 'help');
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
test('recognizes exit aliases', () => {
|
|
55
|
+
assert.strictEqual(parseCommand('/exit').command, 'exit');
|
|
56
|
+
assert.strictEqual(parseCommand('/quit').command, 'quit');
|
|
57
|
+
assert.strictEqual(parseCommand('exit').command, 'exit');
|
|
58
|
+
assert.strictEqual(parseCommand('quit').command, 'quit');
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
test('distinguishes normal user prompts from commands', () => {
|
|
62
|
+
assert.strictEqual(parseCommand('What is 2+2?').isCommand, false);
|
|
63
|
+
assert.strictEqual(parseCommand('Explain /dev/null in Linux').isCommand, false);
|
|
64
|
+
});
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
describe('Conversation History & Strict Role Ordering', () => {
|
|
68
|
+
test('formats initialPrompts with system message first and alternating turns', () => {
|
|
69
|
+
const history = new ConversationHistory();
|
|
70
|
+
history.addTurn('user', 'Hello');
|
|
71
|
+
history.addTurn('assistant', 'Hi there!');
|
|
72
|
+
history.addTurn('user', 'How are you?');
|
|
73
|
+
history.addTurn('assistant', 'Doing great!');
|
|
74
|
+
|
|
75
|
+
const prompts = history.formatInitialPrompts('You are helpful.');
|
|
76
|
+
assert.strictEqual(prompts.length, 5);
|
|
77
|
+
assert.deepEqual(prompts[0], { role: 'system', content: 'You are helpful.' });
|
|
78
|
+
assert.deepEqual(prompts[1], { role: 'user', content: 'Hello' });
|
|
79
|
+
assert.deepEqual(prompts[2], { role: 'assistant', content: 'Hi there!' });
|
|
80
|
+
assert.deepEqual(prompts[3], { role: 'user', content: 'How are you?' });
|
|
81
|
+
assert.deepEqual(prompts[4], { role: 'assistant', content: 'Doing great!' });
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
test('drops incomplete trailing user turn from initialPrompts', () => {
|
|
85
|
+
const history = new ConversationHistory();
|
|
86
|
+
history.addTurn('user', 'Hello');
|
|
87
|
+
history.addTurn('assistant', 'Hi');
|
|
88
|
+
history.addTurn('user', 'Incomplete trailing query');
|
|
89
|
+
|
|
90
|
+
const prompts = history.formatInitialPrompts();
|
|
91
|
+
assert.strictEqual(prompts.length, 2);
|
|
92
|
+
assert.strictEqual(prompts[prompts.length - 1].role, 'assistant');
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
test('trims older turns while preserving recent turns in pairs', () => {
|
|
96
|
+
const history = new ConversationHistory();
|
|
97
|
+
for (let i = 1; i <= 10; i++) {
|
|
98
|
+
history.addTurn('user', `User message ${i}`);
|
|
99
|
+
history.addTurn('assistant', `Assistant reply ${i}`);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
assert.strictEqual(history.length, 20);
|
|
103
|
+
history.trimOlderTurns(6);
|
|
104
|
+
assert.strictEqual(history.length, 6);
|
|
105
|
+
assert.strictEqual(history.getMessages()[0].content, 'User message 8');
|
|
106
|
+
assert.strictEqual(history.getMessages()[5].content, 'Assistant reply 10');
|
|
107
|
+
});
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
describe('Chat Configuration & Schema Validation', () => {
|
|
111
|
+
test('validates sampling modes', () => {
|
|
112
|
+
assert.strictEqual(validateSamplingMode('creative'), 'creative');
|
|
113
|
+
assert.strictEqual(validateSamplingMode('PREDICTABLE'), 'predictable');
|
|
114
|
+
assert.strictEqual(validateSamplingMode('invalid_mode'), null);
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
test('validates language codes', () => {
|
|
118
|
+
assert.strictEqual(validateLanguageCode('en'), 'en');
|
|
119
|
+
assert.strictEqual(validateLanguageCode('tr'), 'tr');
|
|
120
|
+
assert.strictEqual(validateLanguageCode('en-US'), 'en-us');
|
|
121
|
+
assert.strictEqual(validateLanguageCode('12345'), null);
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
test('loads and validates JSON schema files', () => {
|
|
125
|
+
const tmpDir = os.tmpdir();
|
|
126
|
+
const validSchemaPath = path.join(tmpDir, 'test_valid.schema.json');
|
|
127
|
+
fs.writeFileSync(validSchemaPath, JSON.stringify({ type: 'object', properties: { name: { type: 'string' } } }));
|
|
128
|
+
|
|
129
|
+
const res = loadAndValidateJsonSchema(validSchemaPath);
|
|
130
|
+
assert.ok(res.schema);
|
|
131
|
+
assert.strictEqual(res.schema.type, 'object');
|
|
132
|
+
|
|
133
|
+
const invalidPath = path.join(tmpDir, 'test_invalid.json');
|
|
134
|
+
fs.writeFileSync(invalidPath, 'NOT_VALID_JSON');
|
|
135
|
+
assert.throws(() => loadAndValidateJsonSchema(invalidPath), /Invalid JSON/);
|
|
136
|
+
|
|
137
|
+
fs.unlinkSync(validSchemaPath);
|
|
138
|
+
fs.unlinkSync(invalidPath);
|
|
139
|
+
});
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
describe('ChatSessionManager Lifecycle & Capability Adherence', () => {
|
|
143
|
+
function createMockBridge(customCaps = {}) {
|
|
144
|
+
const evalCalls = [];
|
|
145
|
+
return {
|
|
146
|
+
evalCalls,
|
|
147
|
+
isConnected: () => true,
|
|
148
|
+
async evaluate(script) {
|
|
149
|
+
evalCalls.push(script);
|
|
150
|
+
return { success: true, contextUsage: 120, contextWindow: 4096 };
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
test('sampling update with unsupported runtime returns honest error', async () => {
|
|
156
|
+
const bridge = createMockBridge();
|
|
157
|
+
const manager = new ChatSessionManager(bridge, {
|
|
158
|
+
capabilities: { samplingMode: false, supportedSamplingModes: [] }
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
const res = await manager.setSamplingMode('creative');
|
|
162
|
+
assert.strictEqual(res.success, false);
|
|
163
|
+
assert.strictEqual(res.error, 'Sampling mode is not supported by this Chrome runtime.');
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
test('sampling update with supported runtime updates config and recreates session', async () => {
|
|
167
|
+
const bridge = createMockBridge();
|
|
168
|
+
const manager = new ChatSessionManager(bridge, {
|
|
169
|
+
capabilities: { samplingMode: true, supportedSamplingModes: ['balanced', 'creative', 'predictable'] }
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
manager.history.addTurn('user', 'Hi');
|
|
173
|
+
manager.history.addTurn('assistant', 'Hello');
|
|
174
|
+
|
|
175
|
+
const res = await manager.setSamplingMode('creative');
|
|
176
|
+
assert.strictEqual(res.success, true);
|
|
177
|
+
assert.strictEqual(manager.config.samplingMode, 'creative');
|
|
178
|
+
assert.strictEqual(manager.history.length, 2); // History preserved!
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
test('temperature update with unsupported runtime returns honest error', async () => {
|
|
182
|
+
const bridge = createMockBridge();
|
|
183
|
+
const manager = new ChatSessionManager(bridge, {
|
|
184
|
+
capabilities: { temperature: false }
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
const res = await manager.setTemperature(0.2);
|
|
188
|
+
assert.strictEqual(res.success, false);
|
|
189
|
+
assert.strictEqual(res.error, 'temperature is not available in this Chrome context.');
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
test('system prompt update recreates session and preserves conversation', async () => {
|
|
193
|
+
const bridge = createMockBridge();
|
|
194
|
+
const manager = new ChatSessionManager(bridge, {
|
|
195
|
+
capabilities: { initialPrompts: true }
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
manager.history.addTurn('user', 'Turn 1');
|
|
199
|
+
manager.history.addTurn('assistant', 'Answer 1');
|
|
200
|
+
|
|
201
|
+
const res = await manager.setSystemPrompt('New prompt');
|
|
202
|
+
assert.strictEqual(res.success, true);
|
|
203
|
+
assert.strictEqual(manager.config.systemPrompt, 'New prompt');
|
|
204
|
+
assert.strictEqual(manager.history.length, 2);
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
test('/json on/off toggles jsonMode without session recreation', () => {
|
|
208
|
+
const bridge = createMockBridge();
|
|
209
|
+
const manager = new ChatSessionManager(bridge);
|
|
210
|
+
|
|
211
|
+
manager.setJsonMode(true);
|
|
212
|
+
assert.strictEqual(manager.config.jsonMode, true);
|
|
213
|
+
|
|
214
|
+
manager.setJsonMode(false);
|
|
215
|
+
assert.strictEqual(manager.config.jsonMode, false);
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
test('/clear resets history while preserving configuration', async () => {
|
|
219
|
+
const bridge = createMockBridge();
|
|
220
|
+
const manager = new ChatSessionManager(bridge, {
|
|
221
|
+
systemPrompt: 'Keep me',
|
|
222
|
+
samplingMode: 'creative'
|
|
223
|
+
});
|
|
224
|
+
|
|
225
|
+
manager.history.addTurn('user', 'To be deleted');
|
|
226
|
+
assert.strictEqual(manager.history.length, 1);
|
|
227
|
+
|
|
228
|
+
await manager.clearConversation();
|
|
229
|
+
assert.strictEqual(manager.history.length, 0);
|
|
230
|
+
assert.strictEqual(manager.config.systemPrompt, 'Keep me');
|
|
231
|
+
assert.strictEqual(manager.config.samplingMode, 'creative');
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
test('/new resets both history and configuration to defaults', async () => {
|
|
235
|
+
const bridge = createMockBridge();
|
|
236
|
+
const manager = new ChatSessionManager(bridge, {
|
|
237
|
+
systemPrompt: 'Reset me',
|
|
238
|
+
samplingMode: 'creative',
|
|
239
|
+
jsonMode: true
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
manager.history.addTurn('user', 'To be deleted');
|
|
243
|
+
|
|
244
|
+
await manager.resetAll();
|
|
245
|
+
assert.strictEqual(manager.history.length, 0);
|
|
246
|
+
assert.strictEqual(manager.config.systemPrompt, null);
|
|
247
|
+
assert.strictEqual(manager.config.samplingMode, 'balanced');
|
|
248
|
+
assert.strictEqual(manager.config.jsonMode, false);
|
|
249
|
+
});
|
|
250
|
+
});
|