nanobridge 0.1.1 → 0.2.1
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 +2 -2
- 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 +347 -0
- package/src/chrome/bridge.js +38 -15
- package/src/chrome/capabilities.js +99 -0
- package/src/chrome/launch.js +47 -13
- package/src/cli.js +11 -1
- package/src/commands/chat.js +299 -102
- package/src/commands/status.js +14 -5
- package/src/daemon/client.js +67 -11
- package/src/daemon/server.js +164 -21
- package/src/daemon/state.js +0 -3
- package/test/chat.test.js +250 -0
package/src/daemon/server.js
CHANGED
|
@@ -118,10 +118,16 @@ 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_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 (_) {}
|
|
123
129
|
}
|
|
124
|
-
})()`, { userGesture: true });
|
|
130
|
+
})()`, { userGesture: true, timeout: 180000 });
|
|
125
131
|
this.isWarmed = true;
|
|
126
132
|
debug('daemon', 'Warmup completed successfully.');
|
|
127
133
|
}
|
|
@@ -153,6 +159,19 @@ export class DaemonServer {
|
|
|
153
159
|
// Standard Health/Status
|
|
154
160
|
if (req.method === 'GET' && (url.pathname === '/status' || url.pathname === '/health')) {
|
|
155
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
|
+
}
|
|
156
175
|
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
157
176
|
res.end(JSON.stringify({
|
|
158
177
|
status: 'ready',
|
|
@@ -162,6 +181,7 @@ export class DaemonServer {
|
|
|
162
181
|
uptimeMs: Date.now() - this.startTime,
|
|
163
182
|
warmed: this.isWarmed,
|
|
164
183
|
bridgeConnected,
|
|
184
|
+
chatStats,
|
|
165
185
|
openai_base_url: `http://${this.host}:${this.port}/v1`
|
|
166
186
|
}));
|
|
167
187
|
return;
|
|
@@ -284,16 +304,38 @@ export class DaemonServer {
|
|
|
284
304
|
|
|
285
305
|
// Reset / Recycle Context Endpoint
|
|
286
306
|
if ((req.method === 'POST' || req.method === 'GET') && url.pathname === '/reset') {
|
|
307
|
+
const resetType = url.searchParams.get('session');
|
|
287
308
|
try {
|
|
288
309
|
await this.runExclusive(async () => {
|
|
289
|
-
debug('daemon', 'Resetting Chrome AI session context & reloading host page...');
|
|
290
310
|
if (this.bridge && this.bridge.isConnected()) {
|
|
291
|
-
|
|
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
|
+
}
|
|
292
335
|
}
|
|
293
|
-
await this.warmupSession();
|
|
294
336
|
});
|
|
295
337
|
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
296
|
-
res.end(JSON.stringify({ success: true, message: '
|
|
338
|
+
res.end(JSON.stringify({ success: true, message: 'Reset successfully' }));
|
|
297
339
|
} catch (err) {
|
|
298
340
|
res.writeHead(500, { 'Content-Type': 'application/json' });
|
|
299
341
|
res.end(JSON.stringify({ success: false, error: err.message }));
|
|
@@ -321,6 +363,9 @@ export class DaemonServer {
|
|
|
321
363
|
const payload = JSON.parse(body || '{}');
|
|
322
364
|
const promptText = payload.promptText || '';
|
|
323
365
|
const systemPrompt = payload.systemPrompt;
|
|
366
|
+
const samplingMode = payload.samplingMode;
|
|
367
|
+
const sessionType = payload.sessionType || 'stateless';
|
|
368
|
+
const initialPrompts = payload.initialPrompts;
|
|
324
369
|
const stream = payload.stream !== false;
|
|
325
370
|
|
|
326
371
|
if (res.socket) res.socket.setNoDelay(true);
|
|
@@ -346,8 +391,12 @@ export class DaemonServer {
|
|
|
346
391
|
const fullResult = await this.promptWithRetry({
|
|
347
392
|
promptText,
|
|
348
393
|
systemPrompt,
|
|
394
|
+
samplingMode,
|
|
395
|
+
sessionType,
|
|
396
|
+
initialPrompts,
|
|
349
397
|
stream,
|
|
350
398
|
requestId: reqId,
|
|
399
|
+
responseConstraint: payload.responseConstraint,
|
|
351
400
|
onChunk: (delta, full) => sendChunk(delta, full)
|
|
352
401
|
});
|
|
353
402
|
|
|
@@ -395,7 +444,19 @@ export class DaemonServer {
|
|
|
395
444
|
});
|
|
396
445
|
}
|
|
397
446
|
|
|
398
|
-
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
|
+
} = {}) {
|
|
399
460
|
if (this.warmupPromise) {
|
|
400
461
|
await this.warmupPromise.catch(() => {});
|
|
401
462
|
}
|
|
@@ -403,6 +464,10 @@ export class DaemonServer {
|
|
|
403
464
|
const reqId = requestId || `req_${Date.now()}_${Math.random().toString(36).slice(2)}`;
|
|
404
465
|
const escapedPrompt = JSON.stringify(promptText);
|
|
405
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';
|
|
406
471
|
const prefix = `__NANOBRIDGE_CHUNK_${reqId}__:`;
|
|
407
472
|
|
|
408
473
|
if (stream && onChunk) {
|
|
@@ -420,6 +485,7 @@ export class DaemonServer {
|
|
|
420
485
|
|
|
421
486
|
try {
|
|
422
487
|
const evalResult = await this.bridge.evaluate(`(async () => {
|
|
488
|
+
let sessionToDestroy = null;
|
|
423
489
|
try {
|
|
424
490
|
if (!('LanguageModel' in window)) {
|
|
425
491
|
return { success: false, error: 'LanguageModel API not available' };
|
|
@@ -427,33 +493,110 @@ export class DaemonServer {
|
|
|
427
493
|
window.__nanobridge_current_req = '${reqId}';
|
|
428
494
|
|
|
429
495
|
const sysPrompt = ${escapedSystem};
|
|
430
|
-
const
|
|
431
|
-
const
|
|
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
|
+
}
|
|
432
540
|
|
|
433
|
-
|
|
434
|
-
|
|
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 = '';
|
|
435
550
|
let prev = '';
|
|
436
551
|
|
|
437
552
|
for await (const chunk of stream) {
|
|
438
553
|
if (window.__nanobridge_abort_req === '${reqId}') {
|
|
439
|
-
if (
|
|
554
|
+
if (sessionToDestroy) {
|
|
555
|
+
try { sessionToDestroy.destroy(); } catch (_) {}
|
|
556
|
+
}
|
|
440
557
|
return { success: false, error: 'Request cancelled' };
|
|
441
558
|
}
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
559
|
+
let delta = '';
|
|
560
|
+
if (chunk.startsWith(prev) && prev.length > 0) {
|
|
561
|
+
delta = chunk.slice(prev.length);
|
|
562
|
+
prev = chunk;
|
|
563
|
+
fullResult = chunk;
|
|
564
|
+
} else {
|
|
565
|
+
delta = chunk;
|
|
566
|
+
prev = chunk;
|
|
567
|
+
fullResult += chunk;
|
|
568
|
+
}
|
|
569
|
+
if (delta) {
|
|
570
|
+
console.debug('${prefix}' + JSON.stringify({ d: delta }));
|
|
571
|
+
}
|
|
446
572
|
}
|
|
447
573
|
|
|
448
|
-
|
|
449
|
-
|
|
574
|
+
let usage = null;
|
|
575
|
+
let windowSize = null;
|
|
576
|
+
try {
|
|
577
|
+
usage = session.contextUsage;
|
|
578
|
+
windowSize = session.contextWindow;
|
|
579
|
+
} catch (_) {}
|
|
580
|
+
|
|
581
|
+
if (sessionToDestroy) {
|
|
582
|
+
try { sessionToDestroy.destroy(); } catch (_) {}
|
|
450
583
|
}
|
|
451
584
|
|
|
452
|
-
return { success: true, text:
|
|
585
|
+
return { success: true, text: fullResult, contextUsage: usage, contextWindow: windowSize };
|
|
453
586
|
} catch (e) {
|
|
587
|
+
if (sessionToDestroy) {
|
|
588
|
+
try { sessionToDestroy.destroy(); } catch (_) {}
|
|
589
|
+
}
|
|
590
|
+
if (${isChat}) {
|
|
591
|
+
if (window.__nanobridge_chat_session && typeof window.__nanobridge_chat_session.destroy === 'function') {
|
|
592
|
+
try { window.__nanobridge_chat_session.destroy(); } catch (_) {}
|
|
593
|
+
}
|
|
594
|
+
window.__nanobridge_chat_session = null;
|
|
595
|
+
window.__nanobridge_chat_session_config = null;
|
|
596
|
+
}
|
|
454
597
|
return { success: false, error: e.message };
|
|
455
598
|
}
|
|
456
|
-
})()`, { userGesture: true });
|
|
599
|
+
})()`, { userGesture: true, timeout: 180000 });
|
|
457
600
|
|
|
458
601
|
if (!evalResult.success) {
|
|
459
602
|
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
|
+
});
|