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/commands/chat.js
CHANGED
|
@@ -6,35 +6,55 @@ import { ChromeBridge } from '../chrome/bridge.js';
|
|
|
6
6
|
import { log, style, debug } from '../utils/output.js';
|
|
7
7
|
import { NanoBridgeError } from '../utils/errors.js';
|
|
8
8
|
import { readFileContent, formatFileAsContext, extractAndAttachFiles } from '../utils/files.js';
|
|
9
|
+
import { ChatSessionManager } from '../chat/session.js';
|
|
10
|
+
import { parseCommand, formatChatHelp } from '../chat/commands.js';
|
|
11
|
+
import { createDefaultChatConfig, loadAndValidateJsonSchema, validateSamplingMode, validateLanguageCode } from '../chat/config.js';
|
|
12
|
+
import { ConversationHistory } from '../chat/history.js';
|
|
9
13
|
|
|
10
14
|
export async function handleChat(options = {}) {
|
|
11
|
-
let systemPrompt = options.system || 'You are a helpful, direct AI assistant. Always respond purely in the user\'s language with standard characters and proper UTF-8 grammar.';
|
|
12
|
-
const conversation = [];
|
|
13
15
|
let daemon = null;
|
|
14
|
-
let standaloneBridge = null;
|
|
15
16
|
let standaloneChrome = null;
|
|
17
|
+
let standaloneBridge = null;
|
|
18
|
+
let sessionManager = null;
|
|
19
|
+
|
|
20
|
+
const config = createDefaultChatConfig({
|
|
21
|
+
systemPrompt: options.system || null
|
|
22
|
+
});
|
|
23
|
+
const history = new ConversationHistory();
|
|
16
24
|
|
|
17
|
-
// 1.
|
|
25
|
+
// 1. Try connecting to background daemon first (sub-second startup, no GPU lock contention)
|
|
18
26
|
if (options.daemon !== false) {
|
|
19
27
|
try {
|
|
20
28
|
debug('chat', 'Checking or starting background daemon...');
|
|
21
29
|
daemon = await ensureDaemon();
|
|
22
30
|
} catch (err) {
|
|
23
|
-
debug('chat', 'Daemon unavailable, falling back to direct Chrome:', err.message);
|
|
31
|
+
debug('chat', 'Daemon unavailable, falling back to direct standalone Chrome:', err.message);
|
|
24
32
|
}
|
|
25
33
|
}
|
|
26
34
|
|
|
35
|
+
// 2. Standalone fallback if daemon disabled or unavailable
|
|
27
36
|
if (!daemon) {
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
37
|
+
try {
|
|
38
|
+
debug('chat', 'Launching standalone Chrome instance...');
|
|
39
|
+
standaloneChrome = await launchChrome(options);
|
|
40
|
+
standaloneBridge = new ChromeBridge(standaloneChrome);
|
|
41
|
+
await standaloneBridge.connect();
|
|
42
|
+
|
|
43
|
+
sessionManager = new ChatSessionManager(standaloneBridge, {
|
|
44
|
+
systemPrompt: options.system || null
|
|
45
|
+
});
|
|
46
|
+
await sessionManager.init();
|
|
47
|
+
} catch (err) {
|
|
48
|
+
if (standaloneBridge) await standaloneBridge.close().catch(() => {});
|
|
49
|
+
if (standaloneChrome) standaloneChrome.close();
|
|
50
|
+
throw new NanoBridgeError(`Failed to start interactive chat: ${err.message}`);
|
|
51
|
+
}
|
|
32
52
|
}
|
|
33
53
|
|
|
34
|
-
//
|
|
54
|
+
// Welcome banner
|
|
35
55
|
log(`
|
|
36
56
|
${style('NanoBridge Interactive Chat', 'bold')} ${style('(Gemini Nano on-device)', 'cyan')}
|
|
37
|
-
${style('
|
|
57
|
+
${style('Type', 'dim')} ${style('/help', 'yellow')} ${style('to see available commands,', 'dim')} ${style('@file', 'yellow')} ${style('to attach files,', 'dim')} ${style('/exit', 'yellow')} ${style('to quit.', 'dim')}
|
|
38
58
|
`);
|
|
39
59
|
|
|
40
60
|
const rl = readline.createInterface({
|
|
@@ -49,12 +69,8 @@ ${style('Commands:', 'dim')} ${style('/clear', 'yellow')} to reset history, ${st
|
|
|
49
69
|
|
|
50
70
|
const cleanup = async () => {
|
|
51
71
|
rl.close();
|
|
52
|
-
if (standaloneBridge) {
|
|
53
|
-
|
|
54
|
-
}
|
|
55
|
-
if (standaloneChrome) {
|
|
56
|
-
standaloneChrome.close();
|
|
57
|
-
}
|
|
72
|
+
if (standaloneBridge) await standaloneBridge.close().catch(() => {});
|
|
73
|
+
if (standaloneChrome) standaloneChrome.close();
|
|
58
74
|
log(`\n${style('Goodbye!', 'dim')}`);
|
|
59
75
|
process.exit(0);
|
|
60
76
|
};
|
|
@@ -66,137 +82,318 @@ ${style('Commands:', 'dim')} ${style('/clear', 'yellow')} to reset history, ${st
|
|
|
66
82
|
promptUser();
|
|
67
83
|
|
|
68
84
|
for await (const line of rl) {
|
|
69
|
-
const
|
|
85
|
+
const rawInput = line.trim();
|
|
70
86
|
|
|
71
|
-
if (!
|
|
87
|
+
if (!rawInput) {
|
|
72
88
|
promptUser();
|
|
73
89
|
continue;
|
|
74
90
|
}
|
|
75
91
|
|
|
76
|
-
|
|
77
|
-
if (input.toLowerCase() === '/exit' || input.toLowerCase() === '/quit' || input.toLowerCase() === 'exit' || input.toLowerCase() === 'quit') {
|
|
78
|
-
await cleanup();
|
|
79
|
-
break;
|
|
80
|
-
}
|
|
92
|
+
const parsed = parseCommand(rawInput);
|
|
81
93
|
|
|
82
|
-
if (
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
94
|
+
if (parsed.isCommand) {
|
|
95
|
+
const cmd = parsed.command;
|
|
96
|
+
const val = parsed.value;
|
|
97
|
+
|
|
98
|
+
if (cmd === 'exit' || cmd === 'quit') {
|
|
99
|
+
await cleanup();
|
|
100
|
+
break;
|
|
86
101
|
}
|
|
87
|
-
console.clear();
|
|
88
|
-
log(`${style('Conversation context and model session reset successfully.', 'green')}\n`);
|
|
89
|
-
promptUser();
|
|
90
|
-
continue;
|
|
91
|
-
}
|
|
92
102
|
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
log(`${style('System prompt updated:', 'green')} "${systemPrompt}"\n`);
|
|
98
|
-
} else {
|
|
99
|
-
log(`${style('Current system prompt:', 'dim')} "${systemPrompt}"\n`);
|
|
103
|
+
if (cmd === 'help') {
|
|
104
|
+
log(`\n${formatChatHelp({ samplingMode: true, initialPrompts: true, responseConstraint: true })}\n`);
|
|
105
|
+
promptUser();
|
|
106
|
+
continue;
|
|
100
107
|
}
|
|
101
|
-
promptUser();
|
|
102
|
-
continue;
|
|
103
|
-
}
|
|
104
108
|
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
log('');
|
|
112
|
-
promptUser();
|
|
113
|
-
continue;
|
|
114
|
-
}
|
|
109
|
+
if (cmd === 'sampling') {
|
|
110
|
+
if (!val) {
|
|
111
|
+
log(`\nSampling mode: ${style(config.samplingMode || 'balanced', 'bold')}\n`);
|
|
112
|
+
promptUser();
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
115
|
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
116
|
+
const validMode = validateSamplingMode(val);
|
|
117
|
+
if (validMode) {
|
|
118
|
+
config.samplingMode = validMode;
|
|
119
|
+
if (sessionManager) {
|
|
120
|
+
await sessionManager.recreateSession({ preserveHistory: true }).catch(() => {});
|
|
121
|
+
}
|
|
122
|
+
log(`
|
|
123
|
+
Sampling: ${style(validMode, 'bold')}
|
|
124
|
+
Session recreated.
|
|
125
|
+
Conversation preserved.
|
|
126
|
+
`);
|
|
127
|
+
} else {
|
|
128
|
+
log(`\n${style(`Invalid sampling mode: "${val}". Valid: creative, predictable, balanced, most-predictable, most-creative`, 'red')}\n`);
|
|
129
|
+
}
|
|
120
130
|
promptUser();
|
|
121
131
|
continue;
|
|
122
132
|
}
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
133
|
+
|
|
134
|
+
if (cmd === 'system') {
|
|
135
|
+
if (!val) {
|
|
136
|
+
log(`\nSystem prompt: ${config.systemPrompt ? `"${config.systemPrompt}"` : 'none'}\n`);
|
|
137
|
+
promptUser();
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
config.systemPrompt = val.trim();
|
|
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) {
|
|
152
|
+
await sessionManager.recreateSession({ preserveHistory: true }).catch(() => {});
|
|
153
|
+
}
|
|
154
|
+
log(`
|
|
155
|
+
System prompt updated.
|
|
156
|
+
Session recreated.
|
|
157
|
+
Conversation preserved.
|
|
158
|
+
`);
|
|
159
|
+
promptUser();
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
if (cmd === 'json') {
|
|
164
|
+
const lower = val.toLowerCase();
|
|
165
|
+
if (lower === 'on' || lower === 'true' || lower === '1') {
|
|
166
|
+
config.jsonMode = true;
|
|
167
|
+
log(`\nJSON mode ${style('enabled', 'green')}.\n`);
|
|
168
|
+
} else if (lower === 'off' || lower === 'false' || lower === '0') {
|
|
169
|
+
config.jsonMode = false;
|
|
170
|
+
config.responseSchema = null;
|
|
171
|
+
config.schemaPath = null;
|
|
172
|
+
log(`\nJSON mode ${style('disabled', 'yellow')}.\n`);
|
|
173
|
+
} else {
|
|
174
|
+
log(`${style('Usage:', 'dim')} /json on | /json off\n`);
|
|
175
|
+
}
|
|
176
|
+
promptUser();
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
if (cmd === 'schema') {
|
|
181
|
+
if (!val) {
|
|
182
|
+
if (config.schemaPath) {
|
|
183
|
+
log(`\nActive schema: ${config.schemaPath}\n`);
|
|
184
|
+
} else {
|
|
185
|
+
log(`\nNo schema loaded. Usage: /schema <filepath> or /schema clear\n`);
|
|
186
|
+
}
|
|
187
|
+
promptUser();
|
|
188
|
+
continue;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
if (val.toLowerCase() === 'clear' || val.toLowerCase() === 'off') {
|
|
192
|
+
config.responseSchema = null;
|
|
193
|
+
config.schemaPath = null;
|
|
194
|
+
config.jsonMode = false;
|
|
195
|
+
log(`
|
|
196
|
+
Schema cleared.
|
|
197
|
+
JSON mode disabled.
|
|
198
|
+
`);
|
|
199
|
+
promptUser();
|
|
200
|
+
continue;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
try {
|
|
204
|
+
const { schema, relativePath } = loadAndValidateJsonSchema(val);
|
|
205
|
+
config.responseSchema = schema;
|
|
206
|
+
config.schemaPath = relativePath;
|
|
207
|
+
config.jsonMode = true;
|
|
208
|
+
log(`
|
|
209
|
+
Schema loaded: ${style(relativePath, 'bold')}
|
|
210
|
+
JSON mode enabled.
|
|
211
|
+
`);
|
|
212
|
+
} catch (schemaErr) {
|
|
213
|
+
log(`\n${style('Schema error:', 'red')} ${schemaErr.message}\n`);
|
|
214
|
+
}
|
|
215
|
+
promptUser();
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
if (cmd === 'context') {
|
|
220
|
+
const turnCount = history.length;
|
|
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
|
+
}
|
|
233
|
+
const pct = ((estimatedTokens / windowSize) * 100).toFixed(1);
|
|
234
|
+
|
|
235
|
+
log(`
|
|
236
|
+
${style('Context', 'bold')}
|
|
237
|
+
|
|
238
|
+
Used ${estimatedTokens}
|
|
239
|
+
Window ${windowSize}
|
|
240
|
+
Usage ${pct}%
|
|
241
|
+
Messages ${turnCount}
|
|
242
|
+
`);
|
|
243
|
+
promptUser();
|
|
244
|
+
continue;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
if (cmd === 'settings') {
|
|
248
|
+
log(`
|
|
249
|
+
${style('NanoBridge Chat Settings', 'bold')}
|
|
250
|
+
|
|
251
|
+
Sampling ${config.samplingMode || 'balanced'}
|
|
252
|
+
System ${config.systemPrompt ? 'custom' : 'none'}
|
|
253
|
+
JSON mode ${config.jsonMode ? 'on' : 'off'}
|
|
254
|
+
Schema ${config.schemaPath || 'none'}
|
|
255
|
+
Input language ${config.expectedInputLanguages.join(', ')}
|
|
256
|
+
Output language ${config.expectedOutputLanguages.join(', ')}
|
|
257
|
+
Context ${history.length * 50} / 9216
|
|
258
|
+
Temperature unsupported
|
|
259
|
+
TopK unsupported
|
|
260
|
+
`);
|
|
261
|
+
promptUser();
|
|
262
|
+
continue;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
if (cmd === 'clear' || cmd === 'reset') {
|
|
266
|
+
history.clear();
|
|
267
|
+
if (daemon) {
|
|
268
|
+
await resetDaemon({ session: 'chat' }).catch(() => {});
|
|
269
|
+
}
|
|
270
|
+
log(`
|
|
271
|
+
Conversation cleared.
|
|
272
|
+
Configuration preserved.
|
|
273
|
+
`);
|
|
274
|
+
promptUser();
|
|
275
|
+
continue;
|
|
131
276
|
}
|
|
132
|
-
promptUser();
|
|
133
|
-
continue;
|
|
134
|
-
}
|
|
135
277
|
|
|
136
|
-
|
|
278
|
+
if (cmd === 'new') {
|
|
279
|
+
history.clear();
|
|
280
|
+
config.samplingMode = 'balanced';
|
|
281
|
+
config.systemPrompt = null;
|
|
282
|
+
config.jsonMode = false;
|
|
283
|
+
config.responseSchema = null;
|
|
284
|
+
config.schemaPath = null;
|
|
285
|
+
if (daemon) {
|
|
286
|
+
await resetDaemon({ session: 'chat' }).catch(() => {});
|
|
287
|
+
}
|
|
288
|
+
log(`
|
|
289
|
+
New session started.
|
|
290
|
+
`);
|
|
291
|
+
promptUser();
|
|
292
|
+
continue;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
if (cmd === 'history') {
|
|
296
|
+
const msgs = history.getMessages();
|
|
297
|
+
log(`\n${style('Conversation History:', 'bold')} (${msgs.length} messages)`);
|
|
298
|
+
msgs.forEach((m) => {
|
|
299
|
+
const roleStyle = m.role === 'user' ? 'cyan' : (m.role === 'assistant' ? 'green' : 'dim');
|
|
300
|
+
log(`${style(`[${m.role.toUpperCase()}]:`, roleStyle)} ${m.content.slice(0, 80)}${m.content.length > 80 ? '...' : ''}`);
|
|
301
|
+
});
|
|
302
|
+
log('');
|
|
303
|
+
promptUser();
|
|
304
|
+
continue;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
if (cmd === 'read' || cmd === 'file') {
|
|
308
|
+
const filePath = val;
|
|
309
|
+
if (!filePath) {
|
|
310
|
+
log(`${style('Usage:', 'dim')} /read <filepath>\n`);
|
|
311
|
+
promptUser();
|
|
312
|
+
continue;
|
|
313
|
+
}
|
|
314
|
+
try {
|
|
315
|
+
const fileInfo = readFileContent(filePath);
|
|
316
|
+
const formatted = formatFileAsContext(fileInfo);
|
|
317
|
+
history.addTurn('user', `Here is the content of ${fileInfo.relativePath}:\n\n${formatted}`);
|
|
318
|
+
history.addTurn('assistant', `I have loaded and read \`${fileInfo.relativePath}\` (${Math.round(fileInfo.size / 1024 * 10) / 10} KB). What would you like to know or do with it?`);
|
|
319
|
+
log(`${style('📎 Loaded file:', 'green')} ${fileInfo.relativePath} (${Math.round(fileInfo.size / 1024 * 10) / 10} KB)\n`);
|
|
320
|
+
} catch (err) {
|
|
321
|
+
log(`${style('Error loading file:', 'red')} ${err.message}\n`);
|
|
322
|
+
}
|
|
323
|
+
promptUser();
|
|
324
|
+
continue;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
if (cmd === 'temperature') {
|
|
328
|
+
log(`\ntemperature is not available in this Chrome context.\n`);
|
|
329
|
+
promptUser();
|
|
330
|
+
continue;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
if (cmd === 'topk') {
|
|
334
|
+
log(`\ntopK is not available in this Chrome context.\n`);
|
|
335
|
+
promptUser();
|
|
336
|
+
continue;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// Unknown slash command
|
|
137
340
|
log(`
|
|
138
|
-
${style(
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
${style('/clear', 'yellow')} Clear chat context history and terminal screen
|
|
142
|
-
${style('/system <prompt>', 'yellow')} Set or inspect active system instructions
|
|
143
|
-
${style('/history', 'yellow')} Show turn history
|
|
144
|
-
${style('/exit', 'yellow')} Quit interactive chat session
|
|
341
|
+
Unknown command: ${style(rawInput, 'yellow')}
|
|
342
|
+
|
|
343
|
+
Run ${style('/help', 'bold')} to see available commands.
|
|
145
344
|
`);
|
|
146
345
|
promptUser();
|
|
147
346
|
continue;
|
|
148
347
|
}
|
|
149
348
|
|
|
150
|
-
//
|
|
151
|
-
const { finalPrompt, attachedFiles } = extractAndAttachFiles(
|
|
349
|
+
// Normal User Prompt
|
|
350
|
+
const { finalPrompt, attachedFiles } = extractAndAttachFiles(rawInput);
|
|
152
351
|
if (attachedFiles.length > 0) {
|
|
153
352
|
const names = attachedFiles.map((f) => `${f.relativePath} (${Math.round(f.size / 1024 * 10) / 10} KB)`).join(', ');
|
|
154
353
|
log(`${style('📎 Attached:', 'dim')} ${names}`);
|
|
155
354
|
}
|
|
156
355
|
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
conversation.shift();
|
|
356
|
+
let responseConstraint = null;
|
|
357
|
+
if (config.responseSchema) {
|
|
358
|
+
responseConstraint = config.responseSchema;
|
|
359
|
+
} else if (config.jsonMode) {
|
|
360
|
+
responseConstraint = { type: 'object' };
|
|
163
361
|
}
|
|
164
362
|
|
|
165
|
-
|
|
166
|
-
const fullPromptText = conversation.map((m) => `${m.role === 'user' ? 'User' : 'Assistant'}: ${m.content}`).join('\n\n') + '\n\nAssistant:';
|
|
167
|
-
|
|
168
|
-
let assistantResponse = '';
|
|
169
|
-
|
|
363
|
+
rl.pause();
|
|
170
364
|
try {
|
|
365
|
+
let accumulated = '';
|
|
171
366
|
if (daemon) {
|
|
172
|
-
await streamPromptFromDaemon({
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
367
|
+
accumulated = await streamPromptFromDaemon(daemon, {
|
|
368
|
+
promptText: finalPrompt,
|
|
369
|
+
systemPrompt: config.systemPrompt,
|
|
370
|
+
samplingMode: config.samplingMode,
|
|
371
|
+
sessionType: 'chat',
|
|
372
|
+
responseConstraint,
|
|
177
373
|
onChunk: (delta) => {
|
|
178
|
-
assistantResponse += delta;
|
|
179
374
|
process.stdout.write(delta);
|
|
180
375
|
}
|
|
181
376
|
});
|
|
182
|
-
} else {
|
|
183
|
-
await
|
|
184
|
-
promptText: fullPromptText,
|
|
185
|
-
systemPrompt,
|
|
186
|
-
stream: true,
|
|
377
|
+
} else if (sessionManager) {
|
|
378
|
+
accumulated = await sessionManager.promptStreaming(finalPrompt, {
|
|
187
379
|
onChunk: (delta) => {
|
|
188
|
-
assistantResponse += delta;
|
|
189
380
|
process.stdout.write(delta);
|
|
190
381
|
}
|
|
191
382
|
});
|
|
192
383
|
}
|
|
193
384
|
|
|
194
|
-
|
|
385
|
+
history.addTurn('user', finalPrompt);
|
|
386
|
+
history.addTurn('assistant', accumulated);
|
|
195
387
|
process.stdout.write('\n\n');
|
|
196
388
|
} catch (err) {
|
|
197
389
|
log(`\n${style('Error:', 'red')} ${err.message}\n`);
|
|
390
|
+
} finally {
|
|
391
|
+
rl.resume();
|
|
198
392
|
}
|
|
199
393
|
|
|
200
394
|
promptUser();
|
|
201
395
|
}
|
|
396
|
+
|
|
397
|
+
if (standaloneBridge) await standaloneBridge.close().catch(() => {});
|
|
398
|
+
if (standaloneChrome) standaloneChrome.close();
|
|
202
399
|
}
|
package/src/commands/status.js
CHANGED
|
@@ -10,14 +10,23 @@ export async function handleStatus(options = {}) {
|
|
|
10
10
|
let bridge = null;
|
|
11
11
|
|
|
12
12
|
try {
|
|
13
|
-
chromeInstance = await launchChrome(options);
|
|
14
|
-
bridge = new ChromeBridge(chromeInstance);
|
|
15
|
-
await bridge.connect();
|
|
16
|
-
|
|
17
|
-
const status = await bridge.checkStatus();
|
|
18
13
|
const platformInfo = getPlatformInfo();
|
|
19
14
|
const modelOnDisk = isModelDownloaded();
|
|
20
15
|
const daemon = await getActiveDaemon();
|
|
16
|
+
let status = null;
|
|
17
|
+
|
|
18
|
+
if (daemon && daemon.bridgeConnected) {
|
|
19
|
+
status = {
|
|
20
|
+
builtInAiAvailable: true,
|
|
21
|
+
languageModelAvailable: true,
|
|
22
|
+
availability: 'readily'
|
|
23
|
+
};
|
|
24
|
+
} else {
|
|
25
|
+
chromeInstance = await launchChrome(options);
|
|
26
|
+
bridge = new ChromeBridge(chromeInstance);
|
|
27
|
+
await bridge.connect();
|
|
28
|
+
status = await bridge.checkStatus();
|
|
29
|
+
}
|
|
21
30
|
|
|
22
31
|
let modelDisplayStatus = 'unavailable';
|
|
23
32
|
const rawAvail = String(status.availability || '').toLowerCase();
|
package/src/daemon/client.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import http from 'node:http';
|
|
2
|
-
import { spawn } from 'node:child_process';
|
|
2
|
+
import { spawn, execSync } from 'node:child_process';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import os from 'node:os';
|
|
3
5
|
import path from 'node:path';
|
|
4
6
|
import { StringDecoder } from 'node:string_decoder';
|
|
5
7
|
import { fileURLToPath } from 'node:url';
|
|
@@ -78,10 +80,18 @@ export async function startDaemonInBackground() {
|
|
|
78
80
|
|
|
79
81
|
clearDaemonState();
|
|
80
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
|
+
|
|
81
91
|
const env = { ...process.env };
|
|
82
92
|
const child = spawn(process.execPath, [SERVER_SCRIPT], {
|
|
83
93
|
detached: true,
|
|
84
|
-
stdio: 'ignore',
|
|
94
|
+
stdio: ['ignore', out, err],
|
|
85
95
|
env
|
|
86
96
|
});
|
|
87
97
|
child.unref();
|
|
@@ -104,7 +114,16 @@ export async function startDaemonInBackground() {
|
|
|
104
114
|
await new Promise((r) => setTimeout(r, 300));
|
|
105
115
|
}
|
|
106
116
|
|
|
107
|
-
|
|
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}` : ''}`);
|
|
108
127
|
}
|
|
109
128
|
|
|
110
129
|
export async function ensureDaemon() {
|
|
@@ -113,9 +132,33 @@ export async function ensureDaemon() {
|
|
|
113
132
|
return await startDaemonInBackground();
|
|
114
133
|
}
|
|
115
134
|
|
|
116
|
-
export async function streamPromptFromDaemon(
|
|
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 {
|
|
141
|
+
port,
|
|
142
|
+
promptText,
|
|
143
|
+
systemPrompt,
|
|
144
|
+
samplingMode,
|
|
145
|
+
sessionType,
|
|
146
|
+
initialPrompts,
|
|
147
|
+
responseConstraint,
|
|
148
|
+
stream = true,
|
|
149
|
+
onChunk
|
|
150
|
+
} = opts;
|
|
151
|
+
|
|
117
152
|
return new Promise((resolve, reject) => {
|
|
118
|
-
const payload = JSON.stringify({
|
|
153
|
+
const payload = JSON.stringify({
|
|
154
|
+
promptText,
|
|
155
|
+
systemPrompt,
|
|
156
|
+
samplingMode,
|
|
157
|
+
sessionType,
|
|
158
|
+
initialPrompts,
|
|
159
|
+
responseConstraint,
|
|
160
|
+
stream
|
|
161
|
+
});
|
|
119
162
|
const req = http.request(`http://127.0.0.1:${port}/prompt`, {
|
|
120
163
|
method: 'POST',
|
|
121
164
|
headers: {
|
|
@@ -126,6 +169,7 @@ export async function streamPromptFromDaemon({ port, promptText, systemPrompt, s
|
|
|
126
169
|
const decoder = new StringDecoder('utf8');
|
|
127
170
|
let buffer = '';
|
|
128
171
|
let finalText = '';
|
|
172
|
+
let streamAccumulated = '';
|
|
129
173
|
|
|
130
174
|
res.on('data', (chunk) => {
|
|
131
175
|
buffer += decoder.write(chunk);
|
|
@@ -136,8 +180,9 @@ export async function streamPromptFromDaemon({ port, promptText, systemPrompt, s
|
|
|
136
180
|
if (!line.trim()) continue;
|
|
137
181
|
try {
|
|
138
182
|
const data = JSON.parse(line);
|
|
139
|
-
if (data.type === 'chunk'
|
|
140
|
-
|
|
183
|
+
if (data.type === 'chunk') {
|
|
184
|
+
if (data.delta) streamAccumulated += data.delta;
|
|
185
|
+
if (onChunk) onChunk(data.delta, data.full);
|
|
141
186
|
} else if (data.type === 'done') {
|
|
142
187
|
finalText = data.text;
|
|
143
188
|
} else if (data.type === 'error') {
|
|
@@ -156,7 +201,7 @@ export async function streamPromptFromDaemon({ port, promptText, systemPrompt, s
|
|
|
156
201
|
if (data.type === 'done') finalText = data.text;
|
|
157
202
|
} catch (_) {}
|
|
158
203
|
}
|
|
159
|
-
resolve(finalText);
|
|
204
|
+
resolve(finalText || streamAccumulated);
|
|
160
205
|
});
|
|
161
206
|
});
|
|
162
207
|
|
|
@@ -170,14 +215,15 @@ export async function streamPromptFromDaemon({ port, promptText, systemPrompt, s
|
|
|
170
215
|
});
|
|
171
216
|
}
|
|
172
217
|
|
|
173
|
-
export async function resetDaemon() {
|
|
218
|
+
export async function resetDaemon(options = {}) {
|
|
174
219
|
const active = await getActiveDaemon();
|
|
175
220
|
if (!active) {
|
|
176
221
|
return { success: false, message: 'Daemon is not running' };
|
|
177
222
|
}
|
|
178
223
|
|
|
224
|
+
const query = options.session ? `?session=${encodeURIComponent(options.session)}` : '';
|
|
179
225
|
return new Promise((resolve, reject) => {
|
|
180
|
-
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) => {
|
|
181
227
|
let data = '';
|
|
182
228
|
res.on('data', (c) => { data += c; });
|
|
183
229
|
res.on('end', () => {
|
|
@@ -195,7 +241,12 @@ export async function resetDaemon() {
|
|
|
195
241
|
|
|
196
242
|
export async function stopDaemon() {
|
|
197
243
|
const active = await getActiveDaemon();
|
|
244
|
+
const profileDir = path.join(os.homedir(), '.nanobridge', 'profile');
|
|
245
|
+
|
|
198
246
|
if (!active) {
|
|
247
|
+
try {
|
|
248
|
+
execSync(`pkill -9 -f "${profileDir}"`, { stdio: 'ignore' });
|
|
249
|
+
} catch (_) {}
|
|
199
250
|
clearDaemonState();
|
|
200
251
|
return { stopped: true, wasRunning: false };
|
|
201
252
|
}
|
|
@@ -203,13 +254,18 @@ export async function stopDaemon() {
|
|
|
203
254
|
return new Promise((resolve) => {
|
|
204
255
|
const req = http.request(`http://127.0.0.1:${active.port}/stop`, { method: 'POST', timeout: 2000 }, (res) => {
|
|
205
256
|
clearDaemonState();
|
|
257
|
+
try {
|
|
258
|
+
execSync(`pkill -9 -f "${profileDir}"`, { stdio: 'ignore' });
|
|
259
|
+
} catch (_) {}
|
|
206
260
|
resolve({ stopped: true, wasRunning: true, pid: active.pid });
|
|
207
261
|
});
|
|
208
262
|
req.on('error', () => {
|
|
209
|
-
// Force kill if HTTP request fails
|
|
210
263
|
try {
|
|
211
264
|
if (active.pid) process.kill(active.pid, 'SIGKILL');
|
|
212
265
|
} catch (_) {}
|
|
266
|
+
try {
|
|
267
|
+
execSync(`pkill -9 -f "${profileDir}"`, { stdio: 'ignore' });
|
|
268
|
+
} catch (_) {}
|
|
213
269
|
clearDaemonState();
|
|
214
270
|
resolve({ stopped: true, wasRunning: true, pid: active.pid });
|
|
215
271
|
});
|