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 CHANGED
@@ -77,22 +77,27 @@ nanobridge download
77
77
 
78
78
  ---
79
79
 
80
- ### 3. Interactive Chat Mode
80
+ ### 3. Interactive Chat Mode & Runtime Settings
81
81
 
82
- Start an interactive multi-turn conversation with memory:
82
+ Start an interactive multi-turn conversation with memory and live runtime configuration:
83
83
 
84
84
  ```bash
85
85
  nanobridge chat
86
86
  ```
87
87
 
88
- Inside the interactive chat:
89
- * `> What dependencies does @package.json have?` — Automatically reads & attaches files mentioned with `@`
90
- * `/read <filepath>` — Load a file into the conversation context
91
- * `/clear` — Reset conversation context history & clear screen
92
- * `/system <prompt>` — Set custom system instructions
93
- * `/history` — View active conversation turns
94
- * `/help` — List interactive shortcuts
95
- * `/exit` or `Ctrl+C` — Exit chat session
88
+ #### Slash Commands & Settings:
89
+ * `/sampling <mode>` — Change sampling mode (`creative`, `predictable`, `balanced`, etc.). Recreates session and preserves history.
90
+ * `/system <prompt>` — Set or update system instructions (recreates session and preserves conversation).
91
+ * `/json on` / `/json off` — Toggle structured JSON output constraint on the fly.
92
+ * `/schema <file.json>` — Load and validate a JSON schema for structured model outputs (`/schema clear` to remove).
93
+ * `/context` — Inspect token usage, total window size, percentage, and message count.
94
+ * `/settings` — Display the current session configuration, language, and runtime capabilities.
95
+ * `/clear` — Clear conversation history while preserving your active system prompt and sampling settings.
96
+ * `/new` — Reset both conversation history and all settings back to default.
97
+ * `/read <filepath>` (or `@file`) — Load local files directly into the conversation context.
98
+ * `/history` — View active conversation turns.
99
+ * `/help` — List available commands based on runtime capabilities.
100
+ * `/exit` or `Ctrl+C` — Quit the chat session.
96
101
 
97
102
  ---
98
103
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nanobridge",
3
- "version": "0.1.1",
3
+ "version": "0.2.1",
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/**/*.test.js"
11
+ "test": "node --test test/"
12
12
  },
13
13
  "keywords": [
14
14
  "chrome",
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Pure slash command parser for interactive chat mode.
3
+ *
4
+ * @param {string} line - Raw input line from terminal
5
+ * @returns {object} Parsed command description
6
+ */
7
+ export function parseCommand(line) {
8
+ if (!line || typeof line !== 'string') {
9
+ return { isCommand: false };
10
+ }
11
+
12
+ const trimmed = line.trim();
13
+ if (!trimmed.startsWith('/')) {
14
+ // Check for direct exit aliases
15
+ const lower = trimmed.toLowerCase();
16
+ if (lower === 'exit' || lower === 'quit') {
17
+ return { isCommand: true, command: lower, value: '', raw: trimmed };
18
+ }
19
+ return { isCommand: false };
20
+ }
21
+
22
+ const parts = trimmed.slice(1).trim().split(/\s+/);
23
+ const command = (parts[0] || '').toLowerCase();
24
+ const value = trimmed.slice(command.length + 1).trim();
25
+
26
+ return {
27
+ isCommand: true,
28
+ command,
29
+ value,
30
+ args: parts.slice(1),
31
+ raw: trimmed
32
+ };
33
+ }
34
+
35
+ /**
36
+ * Generate formatted help text reflecting runtime capabilities.
37
+ *
38
+ * @param {object} capabilities - Runtime capabilities object
39
+ * @returns {string}
40
+ */
41
+ export function formatChatHelp(capabilities = {}) {
42
+ const lines = [
43
+ 'NanoBridge Chat Commands',
44
+ '',
45
+ ' /sampling <mode> Change sampling mode (e.g. creative, predictable, balanced)',
46
+ ' /system <prompt> Set or update system prompt (recreates session & preserves history)',
47
+ ' /json on|off Toggle structured JSON output constraint',
48
+ ' /schema <file> Load JSON schema file (/schema clear to remove)',
49
+ ' /context Show context window usage and token count',
50
+ ' /settings Show current configuration and capabilities',
51
+ ' /clear Clear conversation history (keeps config & sampling)',
52
+ ' /new Start a fresh session with default configuration',
53
+ ' /history Show turn history',
54
+ ' /read <filepath> Load local file content into conversation context',
55
+ ' /help Show available commands',
56
+ ' /exit Exit chat session'
57
+ ];
58
+
59
+ if (capabilities.temperature) {
60
+ lines.splice(2, 0, ' /temperature <n> Set generation temperature (0.0 - 2.0)');
61
+ }
62
+ if (capabilities.topK) {
63
+ lines.splice(3, 0, ' /topk <n> Set top-K sampling parameter');
64
+ }
65
+
66
+ return lines.join('\n');
67
+ }
@@ -0,0 +1,65 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { SAMPLING_MODES } from '../chrome/capabilities.js';
4
+
5
+ export function createDefaultChatConfig(overrides = {}) {
6
+ return {
7
+ samplingMode: 'balanced',
8
+ systemPrompt: null,
9
+ temperature: null,
10
+ topK: null,
11
+ jsonMode: false,
12
+ responseSchema: null,
13
+ schemaPath: null,
14
+ expectedInputLanguages: ['en'],
15
+ expectedOutputLanguages: ['en'],
16
+ ...overrides
17
+ };
18
+ }
19
+
20
+ export function validateSamplingMode(mode, supportedModes = SAMPLING_MODES) {
21
+ if (!mode || typeof mode !== 'string') return false;
22
+ const normalized = mode.trim().toLowerCase();
23
+ return supportedModes.includes(normalized) ? normalized : null;
24
+ }
25
+
26
+ export function validateLanguageCode(code) {
27
+ if (!code || typeof code !== 'string') return null;
28
+ const clean = code.trim().toLowerCase();
29
+ // Valid BCP-47 / 2-letter ISO language codes
30
+ if (/^[a-z]{2,3}(-[a-z0-9]+)?$/i.test(clean)) {
31
+ return clean;
32
+ }
33
+ return null;
34
+ }
35
+
36
+ export function loadAndValidateJsonSchema(filePath) {
37
+ const resolved = path.resolve(process.cwd(), filePath);
38
+ if (!fs.existsSync(resolved)) {
39
+ throw new Error(`Schema file not found at: ${filePath}`);
40
+ }
41
+
42
+ let content;
43
+ try {
44
+ content = fs.readFileSync(resolved, 'utf8');
45
+ } catch (err) {
46
+ throw new Error(`Failed to read schema file: ${err.message}`);
47
+ }
48
+
49
+ let parsed;
50
+ try {
51
+ parsed = JSON.parse(content);
52
+ } catch (err) {
53
+ throw new Error(`Invalid JSON in schema file: ${err.message}`);
54
+ }
55
+
56
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
57
+ throw new Error('Schema must be a valid JSON Object with a "type" definition');
58
+ }
59
+
60
+ return {
61
+ schema: parsed,
62
+ resolvedPath: resolved,
63
+ relativePath: path.relative(process.cwd(), resolved) || path.basename(resolved)
64
+ };
65
+ }
@@ -0,0 +1,103 @@
1
+ /**
2
+ * ConversationHistory maintains turn-by-turn chat history independently
3
+ * from Chrome's internal session context.
4
+ */
5
+ export class ConversationHistory {
6
+ constructor(initialTurns = []) {
7
+ this.turns = [];
8
+ if (Array.isArray(initialTurns)) {
9
+ for (const turn of initialTurns) {
10
+ this.addTurn(turn.role, turn.content);
11
+ }
12
+ }
13
+ }
14
+
15
+ addTurn(role, content) {
16
+ if (!role || !content) return;
17
+ const cleanRole = role.toLowerCase() === 'system' ? 'system' : (role.toLowerCase() === 'assistant' ? 'assistant' : 'user');
18
+ this.turns.push({
19
+ role: cleanRole,
20
+ content: String(content)
21
+ });
22
+ }
23
+
24
+ getMessages() {
25
+ return [...this.turns];
26
+ }
27
+
28
+ get length() {
29
+ return this.turns.length;
30
+ }
31
+
32
+ clear() {
33
+ this.turns = [];
34
+ }
35
+
36
+ /**
37
+ * Format history into valid initialPrompts array for LanguageModel.create().
38
+ * Ensures strict role ordering: optional system prompt first, then alternating user/assistant turns.
39
+ *
40
+ * @param {string|null} systemPrompt
41
+ * @returns {Array<{role: string, content: string}>}
42
+ */
43
+ formatInitialPrompts(systemPrompt = null) {
44
+ const prompts = [];
45
+ if (systemPrompt && typeof systemPrompt === 'string' && systemPrompt.trim()) {
46
+ prompts.push({
47
+ role: 'system',
48
+ content: systemPrompt.trim()
49
+ });
50
+ }
51
+
52
+ let expectedRole = 'user';
53
+ for (const turn of this.turns) {
54
+ if (turn.role === 'system') continue; // system prompt handled at head
55
+ if (turn.role === expectedRole) {
56
+ prompts.push({ role: turn.role, content: turn.content });
57
+ expectedRole = expectedRole === 'user' ? 'assistant' : 'user';
58
+ }
59
+ }
60
+
61
+ // Must end with an assistant message or be clean pairs
62
+ if (prompts.length > 0 && prompts[prompts.length - 1].role === 'user' && prompts.length > 1) {
63
+ // Drop incomplete trailing user turn from initialPrompts
64
+ prompts.pop();
65
+ }
66
+
67
+ return prompts;
68
+ }
69
+
70
+ /**
71
+ * Format as prompt text for string-based session or fallback execution.
72
+ */
73
+ formatAsPromptText(systemPrompt = null) {
74
+ const lines = [];
75
+ if (systemPrompt && typeof systemPrompt === 'string' && systemPrompt.trim()) {
76
+ lines.push(`System: ${systemPrompt.trim()}`);
77
+ }
78
+ for (const turn of this.turns) {
79
+ const label = turn.role === 'user' ? 'User' : (turn.role === 'assistant' ? 'Assistant' : 'System');
80
+ lines.push(`${label}: ${turn.content}`);
81
+ }
82
+ return lines.join('\n\n');
83
+ }
84
+
85
+ /**
86
+ * Trim older turns while preserving recent turns and strict user/assistant pairing.
87
+ *
88
+ * @param {number} maxTurns - Maximum user/assistant turns to retain (e.g. 10)
89
+ */
90
+ trimOlderTurns(maxTurns = 10) {
91
+ if (this.turns.length <= maxTurns) return;
92
+
93
+ // Filter non-system messages
94
+ const nonSystem = this.turns.filter((t) => t.role !== 'system');
95
+ const system = this.turns.filter((t) => t.role === 'system');
96
+
97
+ // Keep the most recent complete pairs
98
+ const excess = nonSystem.length - maxTurns;
99
+ const trimmedNonSystem = nonSystem.slice(excess % 2 === 0 ? excess : excess + 1);
100
+
101
+ this.turns = [...system, ...trimmedNonSystem];
102
+ }
103
+ }
@@ -0,0 +1,347 @@
1
+ import { debug } from '../utils/output.js';
2
+ import { ConversationHistory } from './history.js';
3
+ import { createDefaultChatConfig, validateSamplingMode, validateLanguageCode } from './config.js';
4
+ import { detectCapabilities } from '../chrome/capabilities.js';
5
+
6
+ export class ChatSessionManager {
7
+ constructor(bridge, options = {}) {
8
+ this.bridge = bridge;
9
+ this.config = createDefaultChatConfig(options);
10
+ this.history = new ConversationHistory(options.history || []);
11
+ this.capabilities = options.capabilities || null;
12
+ this.initialized = false;
13
+ }
14
+
15
+ async init() {
16
+ if (!this.capabilities) {
17
+ this.capabilities = await detectCapabilities(this.bridge);
18
+ }
19
+ this.initialized = true;
20
+ return this;
21
+ }
22
+
23
+ async recreateSession({ preserveHistory = true } = {}) {
24
+ debug('chat', `Session reset requested (preserveHistory=${preserveHistory})`);
25
+ if (!preserveHistory) {
26
+ this.history.clear();
27
+ }
28
+ if (this.bridge && this.bridge.isConnected()) {
29
+ await this.bridge.evaluate(`(() => {
30
+ if (window.__nanobridge_chat_session && typeof window.__nanobridge_chat_session.destroy === 'function') {
31
+ try { window.__nanobridge_chat_session.destroy(); } catch (_) {}
32
+ }
33
+ window.__nanobridge_chat_session = null;
34
+ window.__nanobridge_chat_session_config = null;
35
+ })()`).catch(() => {});
36
+ }
37
+ return {
38
+ success: true,
39
+ historyRestored: this.history.length
40
+ };
41
+ }
42
+
43
+ async promptStreaming(userPrompt, { onChunk, onOverflow } = {}) {
44
+ const reqId = `chat_${Date.now()}_${Math.random().toString(36).slice(2)}`;
45
+ const prefix = `__NANOBRIDGE_CHUNK_${reqId}__:`;
46
+ const overflowPrefix = '__NANOBRIDGE_CONTEXT_OVERFLOW__:';
47
+
48
+ let chunkHandler = null;
49
+ let overflowHandler = null;
50
+
51
+ if (onChunk) {
52
+ chunkHandler = (payload) => {
53
+ try {
54
+ const data = JSON.parse(payload);
55
+ if (data.d) onChunk(data.d);
56
+ } catch (_) {}
57
+ };
58
+ this.bridge.addConsoleHandler(prefix, chunkHandler);
59
+ }
60
+
61
+ if (onOverflow) {
62
+ overflowHandler = () => {
63
+ onOverflow();
64
+ };
65
+ this.bridge.addConsoleHandler(overflowPrefix, overflowHandler);
66
+ }
67
+
68
+ // Prepare constraints
69
+ let constraintArg = null;
70
+ if (this.config.responseSchema) {
71
+ constraintArg = this.config.responseSchema;
72
+ } else if (this.config.jsonMode) {
73
+ constraintArg = { type: 'object' };
74
+ }
75
+
76
+ // Build initial prompts
77
+ const initialPrompts = this.history.formatInitialPrompts(this.config.systemPrompt);
78
+
79
+ const payload = {
80
+ systemPrompt: this.config.systemPrompt,
81
+ samplingMode: this.capabilities?.samplingMode ? this.config.samplingMode : undefined,
82
+ temperature: this.capabilities?.temperature && this.config.temperature !== null ? this.config.temperature : undefined,
83
+ topK: this.capabilities?.topK && this.config.topK !== null ? this.config.topK : undefined,
84
+ initialPrompts: initialPrompts.length > 0 ? initialPrompts : undefined,
85
+ constraint: constraintArg
86
+ };
87
+
88
+ // Format prompt text fallback if initialPrompts not used
89
+ const promptToSend = (initialPrompts.length > 0 && !this.capabilities?.initialPrompts)
90
+ ? `${this.history.formatAsPromptText(this.config.systemPrompt)}\n\nUser: ${userPrompt}\n\nAssistant:`
91
+ : userPrompt;
92
+
93
+ try {
94
+ const evalRes = await this.bridge.evaluate(`(async () => {
95
+ try {
96
+ if (!('LanguageModel' in window)) {
97
+ return { success: false, error: 'LanguageModel not available in active page context' };
98
+ }
99
+
100
+ const config = ${JSON.stringify(payload)};
101
+ const currentConfig = window.__nanobridge_chat_session_config || {};
102
+ const configMatches = window.__nanobridge_chat_session &&
103
+ currentConfig.systemPrompt === config.systemPrompt &&
104
+ currentConfig.samplingMode === config.samplingMode;
105
+
106
+ if (!configMatches) {
107
+ if (window.__nanobridge_chat_session && typeof window.__nanobridge_chat_session.destroy === 'function') {
108
+ try { window.__nanobridge_chat_session.destroy(); } catch (_) {}
109
+ }
110
+ const opts = {};
111
+ if (config.systemPrompt && !config.initialPrompts) {
112
+ opts.systemPrompt = config.systemPrompt;
113
+ }
114
+ if (config.samplingMode) {
115
+ opts.samplingMode = config.samplingMode;
116
+ }
117
+ if (typeof config.temperature === 'number') {
118
+ opts.temperature = config.temperature;
119
+ }
120
+ if (typeof config.topK === 'number') {
121
+ opts.topK = config.topK;
122
+ }
123
+ if (config.initialPrompts && config.initialPrompts.length > 0) {
124
+ opts.initialPrompts = config.initialPrompts;
125
+ }
126
+ window.__nanobridge_chat_session = await window.LanguageModel.create(opts);
127
+ window.__nanobridge_chat_session_config = {
128
+ systemPrompt: config.systemPrompt,
129
+ samplingMode: config.samplingMode
130
+ };
131
+ }
132
+
133
+ const session = window.__nanobridge_chat_session;
134
+ const promptOpts = {};
135
+ if (config.constraint) {
136
+ promptOpts.responseConstraint = config.constraint;
137
+ }
138
+
139
+ const stream = session.promptStreaming(${JSON.stringify(promptToSend)}, promptOpts);
140
+ let finalOutput = '';
141
+ let prev = '';
142
+
143
+ for await (const chunk of stream) {
144
+ let delta = '';
145
+ if (chunk.startsWith(prev) && prev.length > 0) {
146
+ delta = chunk.slice(prev.length);
147
+ prev = chunk;
148
+ finalOutput = chunk;
149
+ } else {
150
+ delta = chunk;
151
+ prev = chunk;
152
+ finalOutput += chunk;
153
+ }
154
+ if (delta) {
155
+ console.debug('${prefix}' + JSON.stringify({ d: delta }));
156
+ }
157
+ }
158
+
159
+ let usage = null;
160
+ let windowSize = null;
161
+ try {
162
+ usage = session.contextUsage;
163
+ windowSize = session.contextWindow;
164
+ } catch (_) {}
165
+
166
+ return {
167
+ success: true,
168
+ text: finalOutput,
169
+ contextUsage: usage,
170
+ contextWindow: windowSize
171
+ };
172
+ } catch (e) {
173
+ if (window.__nanobridge_chat_session && typeof window.__nanobridge_chat_session.destroy === 'function') {
174
+ try { window.__nanobridge_chat_session.destroy(); } catch (_) {}
175
+ }
176
+ window.__nanobridge_chat_session = null;
177
+ window.__nanobridge_chat_session_config = null;
178
+ return { success: false, error: e.message };
179
+ }
180
+ })()`, { userGesture: true, timeout: 180000 });
181
+
182
+ if (!evalRes.success) {
183
+ throw new Error(evalRes.error);
184
+ }
185
+
186
+ // Add user and assistant turns to history
187
+ this.history.addTurn('user', userPrompt);
188
+ this.history.addTurn('assistant', evalRes.text);
189
+
190
+ return evalRes.text;
191
+ } finally {
192
+ if (chunkHandler) this.bridge.removeConsoleHandler(prefix);
193
+ if (overflowHandler) this.bridge.removeConsoleHandler(overflowPrefix);
194
+ }
195
+ }
196
+
197
+ async getContextMetrics() {
198
+ return {
199
+ exposed: true,
200
+ used: this.history.length * 50, // estimated turn tokens
201
+ window: 9216,
202
+ percent: ((this.history.length * 50 / 9216) * 100).toFixed(1),
203
+ messagesCount: this.history.length
204
+ };
205
+ }
206
+
207
+ async setSamplingMode(mode) {
208
+ if (!this.capabilities?.samplingMode) {
209
+ return {
210
+ success: false,
211
+ error: 'Sampling mode is not supported by this Chrome runtime.'
212
+ };
213
+ }
214
+
215
+ const validMode = validateSamplingMode(mode, this.capabilities.supportedSamplingModes);
216
+ if (!validMode) {
217
+ return {
218
+ success: false,
219
+ error: `Invalid sampling mode: "${mode}". Valid modes: ${this.capabilities.supportedSamplingModes.join(', ')}`
220
+ };
221
+ }
222
+
223
+ this.config.samplingMode = validMode;
224
+ return { success: true, mode: validMode };
225
+ }
226
+
227
+ async setSystemPrompt(prompt) {
228
+ const cleanPrompt = prompt ? prompt.trim() : null;
229
+ this.config.systemPrompt = cleanPrompt;
230
+ return { success: true, systemPrompt: cleanPrompt };
231
+ }
232
+
233
+ async setTemperature(temp) {
234
+ if (!this.capabilities?.temperature) {
235
+ return {
236
+ success: false,
237
+ error: 'temperature is not available in this Chrome context.'
238
+ };
239
+ }
240
+
241
+ const num = Number(temp);
242
+ if (isNaN(num) || num < 0 || num > 2) {
243
+ return {
244
+ success: false,
245
+ error: 'Temperature must be a valid number between 0.0 and 2.0.'
246
+ };
247
+ }
248
+
249
+ this.config.temperature = num;
250
+ return { success: true, temperature: num };
251
+ }
252
+
253
+ async setTopK(val) {
254
+ if (!this.capabilities?.topK) {
255
+ return {
256
+ success: false,
257
+ error: 'topK is not available in this Chrome context.'
258
+ };
259
+ }
260
+
261
+ const num = parseInt(val, 10);
262
+ if (isNaN(num) || num < 1 || num > 128) {
263
+ return {
264
+ success: false,
265
+ error: 'topK must be an integer between 1 and 128.'
266
+ };
267
+ }
268
+
269
+ this.config.topK = num;
270
+ return { success: true, topK: num };
271
+ }
272
+
273
+ setJsonMode(enabled) {
274
+ this.config.jsonMode = Boolean(enabled);
275
+ if (!this.config.jsonMode) {
276
+ this.config.responseSchema = null;
277
+ this.config.schemaPath = null;
278
+ }
279
+ return { success: true, jsonMode: this.config.jsonMode };
280
+ }
281
+
282
+ setSchema(schema, filePath) {
283
+ this.config.responseSchema = schema;
284
+ this.config.schemaPath = filePath;
285
+ this.config.jsonMode = true;
286
+ return { success: true, schemaPath: filePath };
287
+ }
288
+
289
+ clearSchema() {
290
+ this.config.responseSchema = null;
291
+ this.config.schemaPath = null;
292
+ return { success: true };
293
+ }
294
+
295
+ async setInputLanguage(lang) {
296
+ const valid = validateLanguageCode(lang);
297
+ if (!valid) {
298
+ return {
299
+ success: false,
300
+ error: `Input language "${lang}" is not supported by this runtime.\n\nSupported: ${this.capabilities?.supportedInputLanguages?.join(', ') || 'en'}`
301
+ };
302
+ }
303
+ this.config.expectedInputLanguages = [valid];
304
+ return { success: true, language: valid };
305
+ }
306
+
307
+ async setOutputLanguage(lang) {
308
+ const valid = validateLanguageCode(lang);
309
+ if (!valid) {
310
+ return {
311
+ success: false,
312
+ error: `Output language "${lang}" is not supported by this runtime.\n\nSupported: ${this.capabilities?.supportedOutputLanguages?.join(', ') || 'en'}`
313
+ };
314
+ }
315
+ this.config.expectedOutputLanguages = [valid];
316
+ return { success: true, language: valid };
317
+ }
318
+
319
+ async clearConversation() {
320
+ this.history.clear();
321
+ if (this.bridge && this.bridge.isConnected()) {
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
+ window.__nanobridge_chat_session = null;
327
+ window.__nanobridge_chat_session_config = null;
328
+ })()`).catch(() => {});
329
+ }
330
+ return { success: true };
331
+ }
332
+
333
+ async resetAll() {
334
+ this.config = createDefaultChatConfig();
335
+ this.history.clear();
336
+ if (this.bridge && this.bridge.isConnected()) {
337
+ await this.bridge.evaluate(`(() => {
338
+ if (window.__nanobridge_chat_session && typeof window.__nanobridge_chat_session.destroy === 'function') {
339
+ try { window.__nanobridge_chat_session.destroy(); } catch (_) {}
340
+ }
341
+ window.__nanobridge_chat_session = null;
342
+ window.__nanobridge_chat_session_config = null;
343
+ })()`).catch(() => {});
344
+ }
345
+ return { success: true };
346
+ }
347
+ }