nanobridge 0.1.0 → 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.
@@ -1,6 +1,9 @@
1
1
  import http from 'node:http';
2
2
  import { spawn } from 'node:child_process';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
3
5
  import path from 'node:path';
6
+ import { StringDecoder } from 'node:string_decoder';
4
7
  import { fileURLToPath } from 'node:url';
5
8
  import { getDaemonState, clearDaemonState } from './state.js';
6
9
  import { debug } from '../utils/output.js';
@@ -77,10 +80,18 @@ export async function startDaemonInBackground() {
77
80
 
78
81
  clearDaemonState();
79
82
 
83
+ const logDir = path.join(os.homedir(), '.nanobridge');
84
+ if (!fs.existsSync(logDir)) {
85
+ fs.mkdirSync(logDir, { recursive: true });
86
+ }
87
+ const logFile = path.join(logDir, 'daemon.log');
88
+ const out = fs.openSync(logFile, 'a');
89
+ const err = fs.openSync(logFile, 'a');
90
+
80
91
  const env = { ...process.env };
81
92
  const child = spawn(process.execPath, [SERVER_SCRIPT], {
82
93
  detached: true,
83
- stdio: 'ignore',
94
+ stdio: ['ignore', out, err],
84
95
  env
85
96
  });
86
97
  child.unref();
@@ -103,7 +114,16 @@ export async function startDaemonInBackground() {
103
114
  await new Promise((r) => setTimeout(r, 300));
104
115
  }
105
116
 
106
- throw new Error('Timed out waiting for NanoBridge daemon to start');
117
+ let lastError = '';
118
+ try {
119
+ if (fs.existsSync(logFile)) {
120
+ const logContent = fs.readFileSync(logFile, 'utf8');
121
+ const lines = logContent.trim().split('\n');
122
+ lastError = lines.slice(-15).join('\n');
123
+ }
124
+ } catch (_) {}
125
+
126
+ throw new Error(`Timed out waiting for NanoBridge daemon to start.${lastError ? `\nDaemon log:\n${lastError}` : ''}`);
107
127
  }
108
128
 
109
129
  export async function ensureDaemon() {
@@ -112,21 +132,28 @@ export async function ensureDaemon() {
112
132
  return await startDaemonInBackground();
113
133
  }
114
134
 
115
- export async function streamPromptFromDaemon({ port, promptText, systemPrompt, stream = true, onChunk } = {}) {
135
+ export async function streamPromptFromDaemon(daemonOrOpts, maybeOpts = {}) {
136
+ const opts = (daemonOrOpts && typeof daemonOrOpts.port === 'number' && maybeOpts && Object.keys(maybeOpts).length > 0)
137
+ ? { ...maybeOpts, port: daemonOrOpts.port }
138
+ : (daemonOrOpts || {});
139
+
140
+ const { port, promptText, systemPrompt, samplingMode, responseConstraint, stream = true, onChunk } = opts;
141
+
116
142
  return new Promise((resolve, reject) => {
117
- const payload = JSON.stringify({ promptText, systemPrompt, stream });
143
+ const payload = JSON.stringify({ promptText, systemPrompt, samplingMode, responseConstraint, stream });
118
144
  const req = http.request(`http://127.0.0.1:${port}/prompt`, {
119
145
  method: 'POST',
120
146
  headers: {
121
- 'Content-Type': 'application/json',
147
+ 'Content-Type': 'application/json; charset=utf-8',
122
148
  'Content-Length': Buffer.byteLength(payload)
123
149
  }
124
150
  }, (res) => {
151
+ const decoder = new StringDecoder('utf8');
125
152
  let buffer = '';
126
153
  let finalText = '';
127
154
 
128
155
  res.on('data', (chunk) => {
129
- buffer += chunk.toString('utf8');
156
+ buffer += decoder.write(chunk);
130
157
  const lines = buffer.split('\n');
131
158
  buffer = lines.pop(); // Keep partial line in buffer
132
159
 
@@ -147,6 +174,13 @@ export async function streamPromptFromDaemon({ port, promptText, systemPrompt, s
147
174
  });
148
175
 
149
176
  res.on('end', () => {
177
+ buffer += decoder.end();
178
+ if (buffer.trim()) {
179
+ try {
180
+ const data = JSON.parse(buffer);
181
+ if (data.type === 'done') finalText = data.text;
182
+ } catch (_) {}
183
+ }
150
184
  resolve(finalText);
151
185
  });
152
186
  });
@@ -161,6 +195,29 @@ export async function streamPromptFromDaemon({ port, promptText, systemPrompt, s
161
195
  });
162
196
  }
163
197
 
198
+ export async function resetDaemon() {
199
+ const active = await getActiveDaemon();
200
+ if (!active) {
201
+ return { success: false, message: 'Daemon is not running' };
202
+ }
203
+
204
+ return new Promise((resolve, reject) => {
205
+ const req = http.request(`http://127.0.0.1:${active.port}/reset`, { method: 'POST', timeout: 5000 }, (res) => {
206
+ let data = '';
207
+ res.on('data', (c) => { data += c; });
208
+ res.on('end', () => {
209
+ try {
210
+ resolve(JSON.parse(data));
211
+ } catch (_) {
212
+ resolve({ success: true });
213
+ }
214
+ });
215
+ });
216
+ req.on('error', reject);
217
+ req.end();
218
+ });
219
+ }
220
+
164
221
  export async function stopDaemon() {
165
222
  const active = await getActiveDaemon();
166
223
  if (!active) {
@@ -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
- const s = await window.LanguageModel.create();
122
- if (s && typeof s.destroy === 'function') s.destroy();
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
  }
@@ -282,6 +287,31 @@ export class DaemonServer {
282
287
  return;
283
288
  }
284
289
 
290
+ // Reset / Recycle Context Endpoint
291
+ if ((req.method === 'POST' || req.method === 'GET') && url.pathname === '/reset') {
292
+ try {
293
+ await this.runExclusive(async () => {
294
+ debug('daemon', 'Resetting Chrome AI session context & destroying active session...');
295
+ if (this.bridge && this.bridge.isConnected()) {
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
+ })()`);
303
+ }
304
+ await this.warmupSession();
305
+ });
306
+ res.writeHead(200, { 'Content-Type': 'application/json' });
307
+ res.end(JSON.stringify({ success: true, message: 'Model session and context reset successfully' }));
308
+ } catch (err) {
309
+ res.writeHead(500, { 'Content-Type': 'application/json' });
310
+ res.end(JSON.stringify({ success: false, error: err.message }));
311
+ }
312
+ return;
313
+ }
314
+
285
315
  // Native NanoBridge /prompt Endpoint
286
316
  if (req.method === 'POST' && url.pathname === '/prompt') {
287
317
  let body = '';
@@ -302,6 +332,7 @@ export class DaemonServer {
302
332
  const payload = JSON.parse(body || '{}');
303
333
  const promptText = payload.promptText || '';
304
334
  const systemPrompt = payload.systemPrompt;
335
+ const samplingMode = payload.samplingMode;
305
336
  const stream = payload.stream !== false;
306
337
 
307
338
  if (res.socket) res.socket.setNoDelay(true);
@@ -327,8 +358,10 @@ export class DaemonServer {
327
358
  const fullResult = await this.promptWithRetry({
328
359
  promptText,
329
360
  systemPrompt,
361
+ samplingMode,
330
362
  stream,
331
363
  requestId: reqId,
364
+ responseConstraint: payload.responseConstraint,
332
365
  onChunk: (delta, full) => sendChunk(delta, full)
333
366
  });
334
367
 
@@ -376,14 +409,16 @@ export class DaemonServer {
376
409
  });
377
410
  }
378
411
 
379
- async prompt({ promptText, systemPrompt, stream = true, onChunk, requestId } = {}) {
412
+ async prompt({ promptText, systemPrompt, samplingMode, stream = true, onChunk, requestId, responseConstraint, temperature, topK } = {}) {
380
413
  if (this.warmupPromise) {
381
414
  await this.warmupPromise.catch(() => {});
382
415
  }
383
416
 
384
417
  const reqId = requestId || `req_${Date.now()}_${Math.random().toString(36).slice(2)}`;
385
418
  const escapedPrompt = JSON.stringify(promptText);
386
- const createArgs = systemPrompt ? JSON.stringify({ systemPrompt }) : '';
419
+ const escapedSystem = systemPrompt ? JSON.stringify(systemPrompt) : 'null';
420
+ const escapedSampling = samplingMode ? JSON.stringify(samplingMode) : 'null';
421
+ const escapedConstraint = responseConstraint ? JSON.stringify(responseConstraint) : 'null';
387
422
  const prefix = `__NANOBRIDGE_CHUNK_${reqId}__:`;
388
423
 
389
424
  if (stream && onChunk) {
@@ -406,31 +441,57 @@ export class DaemonServer {
406
441
  return { success: false, error: 'LanguageModel API not available' };
407
442
  }
408
443
  window.__nanobridge_current_req = '${reqId}';
409
- const session = await window.LanguageModel.create(${createArgs});
444
+
445
+ const sysPrompt = ${escapedSystem};
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
+ }
410
464
 
411
- const stream = session.promptStreaming(${escapedPrompt});
465
+ const session = window.__nanobridge_session;
466
+ const constraint = ${escapedConstraint};
467
+ const stream = constraint
468
+ ? session.promptStreaming(${escapedPrompt}, { responseConstraint: constraint })
469
+ : session.promptStreaming(${escapedPrompt});
412
470
  let finalResult = '';
413
471
  let prev = '';
472
+
414
473
  for await (const chunk of stream) {
415
474
  if (window.__nanobridge_abort_req === '${reqId}') {
416
- if (typeof session.destroy === 'function') session.destroy();
417
475
  return { success: false, error: 'Request cancelled' };
418
476
  }
419
477
  finalResult = chunk;
420
478
  const delta = chunk.startsWith(prev) ? chunk.slice(prev.length) : chunk;
421
479
  prev = chunk;
422
- console.debug('${prefix}' + JSON.stringify({ d: delta }));
423
- }
424
-
425
- if (typeof session.destroy === 'function') {
426
- session.destroy();
480
+ if (delta) {
481
+ console.debug('${prefix}' + JSON.stringify({ d: delta }));
482
+ }
427
483
  }
428
484
 
429
485
  return { success: true, text: finalResult };
430
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;
431
492
  return { success: false, error: e.message };
432
493
  }
433
- })()`, { userGesture: true });
494
+ })()`, { userGesture: true, timeout: 180000 });
434
495
 
435
496
  if (!evalResult.success) {
436
497
  throw new Error(evalResult.error);
@@ -42,8 +42,5 @@ export function clearDaemonState() {
42
42
  if (fs.existsSync(STATE_FILE)) {
43
43
  fs.unlinkSync(STATE_FILE);
44
44
  }
45
- if (fs.existsSync(LEGACY_STATE_FILE)) {
46
- fs.unlinkSync(LEGACY_STATE_FILE);
47
- }
48
45
  } catch (_) {}
49
46
  }
@@ -44,24 +44,40 @@ export function formatFileAsContext(fileInfo) {
44
44
  }
45
45
 
46
46
  /**
47
- * Detects and expands @filepath in user input
48
- * e.g. "Explain @src/cli.js please" -> extracts file and attaches as context
47
+ * Detects and expands @filepath or @file <filepath> in user input
48
+ * e.g. "Explain @src/cli.js please" or "@file package.json hangi paketler var"
49
49
  */
50
50
  export function extractAndAttachFiles(input) {
51
- const fileRegex = /@([^\s"']+)/g;
52
51
  const attachedFiles = [];
53
52
  let cleanedInput = input;
54
- let match;
55
53
 
56
- while ((match = fileRegex.exec(input)) !== null) {
54
+ // 1. Check for @file <path> or @file:<path>
55
+ const fileCmdRegex = /@file[:\s]+([^\s"']+)/gi;
56
+ let cmdMatch;
57
+ while ((cmdMatch = fileCmdRegex.exec(input)) !== null) {
58
+ const candidatePath = cmdMatch[1];
59
+ try {
60
+ const fileInfo = readFileContent(candidatePath);
61
+ if (!attachedFiles.some((f) => f.path === fileInfo.path)) {
62
+ attachedFiles.push(fileInfo);
63
+ }
64
+ cleanedInput = cleanedInput.replace(cmdMatch[0], `[File: ${fileInfo.relativePath}]`);
65
+ } catch (_) {}
66
+ }
67
+
68
+ // 2. Check for @<path>
69
+ const fileRegex = /@([^\s"']+)/g;
70
+ let match;
71
+ while ((match = fileRegex.exec(cleanedInput)) !== null) {
57
72
  const candidatePath = match[1];
73
+ if (candidatePath.toLowerCase() === 'file') continue;
58
74
  try {
59
75
  const fileInfo = readFileContent(candidatePath);
60
- attachedFiles.push(fileInfo);
76
+ if (!attachedFiles.some((f) => f.path === fileInfo.path)) {
77
+ attachedFiles.push(fileInfo);
78
+ }
61
79
  cleanedInput = cleanedInput.replace(match[0], `[File: ${fileInfo.relativePath}]`);
62
- } catch (_) {
63
- // If file doesn't exist or fails to read, keep raw string
64
- }
80
+ } catch (_) {}
65
81
  }
66
82
 
67
83
  let finalPrompt = cleanedInput;
@@ -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
+ });
package/test/cli.test.js CHANGED
@@ -22,6 +22,12 @@ test('parseArgs correctly parses commands and flags', () => {
22
22
  const parsed3 = parseArgs(['node', 'nanobridge', 'bench', '--runs', '5']);
23
23
  assert.equal(parsed3.command, 'bench');
24
24
  assert.equal(parsed3.options.runs, 5);
25
+
26
+ const parsed4 = parseArgs(['node', 'nanobridge', 'reset']);
27
+ assert.equal(parsed4.command, 'reset');
28
+
29
+ const parsed5 = parseArgs(['node', 'nanobridge', 'restart']);
30
+ assert.equal(parsed5.command, 'restart');
25
31
  });
26
32
 
27
33
  test('combinePromptAndContext merges prompt and stdin predictably', () => {
@@ -20,12 +20,17 @@ describe('File Reading & Context Utilities', () => {
20
20
  });
21
21
 
22
22
  test('extracts @file mentions from user input', () => {
23
- const input = 'Please explain @package.json dependencies';
24
- const { finalPrompt, attachedFiles } = extractAndAttachFiles(input);
25
- assert.strictEqual(attachedFiles.length, 1);
26
- assert.strictEqual(attachedFiles[0].filename, 'package.json');
27
- assert.ok(finalPrompt.includes('--- File: package.json ---'));
28
- assert.ok(finalPrompt.includes('Please explain [File: package.json] dependencies'));
23
+ const input1 = 'Please explain @package.json dependencies';
24
+ const res1 = extractAndAttachFiles(input1);
25
+ assert.strictEqual(res1.attachedFiles.length, 1);
26
+ assert.strictEqual(res1.attachedFiles[0].filename, 'package.json');
27
+ assert.ok(res1.finalPrompt.includes('--- File: package.json ---'));
28
+
29
+ const input2 = '@file package.json hangi paketler kullanılmış?';
30
+ const res2 = extractAndAttachFiles(input2);
31
+ assert.strictEqual(res2.attachedFiles.length, 1);
32
+ assert.strictEqual(res2.attachedFiles[0].filename, 'package.json');
33
+ assert.ok(res2.finalPrompt.includes('--- File: package.json ---'));
29
34
  });
30
35
 
31
36
  test('throws error on non-existent file', () => {