nanobridge 0.1.1 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -10
- package/package.json +1 -1
- package/src/chat/commands.js +67 -0
- package/src/chat/config.js +65 -0
- package/src/chat/history.js +103 -0
- package/src/chat/session.js +340 -0
- package/src/chrome/bridge.js +38 -15
- package/src/chrome/capabilities.js +99 -0
- package/src/chrome/launch.js +44 -13
- package/src/commands/chat.js +283 -101
- package/src/commands/status.js +14 -5
- package/src/daemon/client.js +29 -4
- package/src/daemon/server.js +54 -16
- package/src/daemon/state.js +0 -3
- package/test/chat.test.js +250 -0
package/src/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,303 @@ ${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 (sessionManager) {
|
|
143
|
+
await sessionManager.recreateSession({ preserveHistory: true }).catch(() => {});
|
|
144
|
+
}
|
|
145
|
+
log(`
|
|
146
|
+
System prompt updated.
|
|
147
|
+
Session recreated.
|
|
148
|
+
Conversation preserved.
|
|
149
|
+
`);
|
|
150
|
+
promptUser();
|
|
151
|
+
continue;
|
|
131
152
|
}
|
|
132
|
-
promptUser();
|
|
133
|
-
continue;
|
|
134
|
-
}
|
|
135
153
|
|
|
136
|
-
|
|
154
|
+
if (cmd === 'json') {
|
|
155
|
+
const lower = val.toLowerCase();
|
|
156
|
+
if (lower === 'on' || lower === 'true' || lower === '1') {
|
|
157
|
+
config.jsonMode = true;
|
|
158
|
+
log(`\nJSON mode ${style('enabled', 'green')}.\n`);
|
|
159
|
+
} else if (lower === 'off' || lower === 'false' || lower === '0') {
|
|
160
|
+
config.jsonMode = false;
|
|
161
|
+
config.responseSchema = null;
|
|
162
|
+
config.schemaPath = null;
|
|
163
|
+
log(`\nJSON mode ${style('disabled', 'yellow')}.\n`);
|
|
164
|
+
} else {
|
|
165
|
+
log(`${style('Usage:', 'dim')} /json on | /json off\n`);
|
|
166
|
+
}
|
|
167
|
+
promptUser();
|
|
168
|
+
continue;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
if (cmd === 'schema') {
|
|
172
|
+
if (!val) {
|
|
173
|
+
if (config.schemaPath) {
|
|
174
|
+
log(`\nActive schema: ${config.schemaPath}\n`);
|
|
175
|
+
} else {
|
|
176
|
+
log(`\nNo schema loaded. Usage: /schema <filepath> or /schema clear\n`);
|
|
177
|
+
}
|
|
178
|
+
promptUser();
|
|
179
|
+
continue;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
if (val.toLowerCase() === 'clear' || val.toLowerCase() === 'off') {
|
|
183
|
+
config.responseSchema = null;
|
|
184
|
+
config.schemaPath = null;
|
|
185
|
+
config.jsonMode = false;
|
|
186
|
+
log(`
|
|
187
|
+
Schema cleared.
|
|
188
|
+
JSON mode disabled.
|
|
189
|
+
`);
|
|
190
|
+
promptUser();
|
|
191
|
+
continue;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
try {
|
|
195
|
+
const { schema, relativePath } = loadAndValidateJsonSchema(val);
|
|
196
|
+
config.responseSchema = schema;
|
|
197
|
+
config.schemaPath = relativePath;
|
|
198
|
+
config.jsonMode = true;
|
|
199
|
+
log(`
|
|
200
|
+
Schema loaded: ${style(relativePath, 'bold')}
|
|
201
|
+
JSON mode enabled.
|
|
202
|
+
`);
|
|
203
|
+
} catch (schemaErr) {
|
|
204
|
+
log(`\n${style('Schema error:', 'red')} ${schemaErr.message}\n`);
|
|
205
|
+
}
|
|
206
|
+
promptUser();
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
if (cmd === 'context') {
|
|
211
|
+
const turnCount = history.length;
|
|
212
|
+
const estimatedTokens = turnCount * 50;
|
|
213
|
+
const windowSize = 9216;
|
|
214
|
+
const pct = ((estimatedTokens / windowSize) * 100).toFixed(1);
|
|
215
|
+
|
|
216
|
+
log(`
|
|
217
|
+
${style('Context', 'bold')}
|
|
218
|
+
|
|
219
|
+
Used ${estimatedTokens}
|
|
220
|
+
Window ${windowSize}
|
|
221
|
+
Usage ${pct}%
|
|
222
|
+
Messages ${turnCount}
|
|
223
|
+
`);
|
|
224
|
+
promptUser();
|
|
225
|
+
continue;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
if (cmd === 'settings') {
|
|
229
|
+
log(`
|
|
230
|
+
${style('NanoBridge Chat Settings', 'bold')}
|
|
231
|
+
|
|
232
|
+
Sampling ${config.samplingMode || 'balanced'}
|
|
233
|
+
System ${config.systemPrompt ? 'custom' : 'none'}
|
|
234
|
+
JSON mode ${config.jsonMode ? 'on' : 'off'}
|
|
235
|
+
Schema ${config.schemaPath || 'none'}
|
|
236
|
+
Input language ${config.expectedInputLanguages.join(', ')}
|
|
237
|
+
Output language ${config.expectedOutputLanguages.join(', ')}
|
|
238
|
+
Context ${history.length * 50} / 9216
|
|
239
|
+
Temperature unsupported
|
|
240
|
+
TopK unsupported
|
|
241
|
+
`);
|
|
242
|
+
promptUser();
|
|
243
|
+
continue;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
if (cmd === 'clear' || cmd === 'reset') {
|
|
247
|
+
history.clear();
|
|
248
|
+
if (daemon) {
|
|
249
|
+
await resetDaemon().catch(() => {});
|
|
250
|
+
}
|
|
251
|
+
log(`
|
|
252
|
+
Conversation cleared.
|
|
253
|
+
Configuration preserved.
|
|
254
|
+
`);
|
|
255
|
+
promptUser();
|
|
256
|
+
continue;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
if (cmd === 'new') {
|
|
260
|
+
history.clear();
|
|
261
|
+
config.samplingMode = 'balanced';
|
|
262
|
+
config.systemPrompt = null;
|
|
263
|
+
config.jsonMode = false;
|
|
264
|
+
config.responseSchema = null;
|
|
265
|
+
config.schemaPath = null;
|
|
266
|
+
if (daemon) {
|
|
267
|
+
await resetDaemon().catch(() => {});
|
|
268
|
+
}
|
|
269
|
+
log(`
|
|
270
|
+
New session started.
|
|
271
|
+
`);
|
|
272
|
+
promptUser();
|
|
273
|
+
continue;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
if (cmd === 'history') {
|
|
277
|
+
const msgs = history.getMessages();
|
|
278
|
+
log(`\n${style('Conversation History:', 'bold')} (${msgs.length} messages)`);
|
|
279
|
+
msgs.forEach((m) => {
|
|
280
|
+
const roleStyle = m.role === 'user' ? 'cyan' : (m.role === 'assistant' ? 'green' : 'dim');
|
|
281
|
+
log(`${style(`[${m.role.toUpperCase()}]:`, roleStyle)} ${m.content.slice(0, 80)}${m.content.length > 80 ? '...' : ''}`);
|
|
282
|
+
});
|
|
283
|
+
log('');
|
|
284
|
+
promptUser();
|
|
285
|
+
continue;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
if (cmd === 'read' || cmd === 'file') {
|
|
289
|
+
const filePath = val;
|
|
290
|
+
if (!filePath) {
|
|
291
|
+
log(`${style('Usage:', 'dim')} /read <filepath>\n`);
|
|
292
|
+
promptUser();
|
|
293
|
+
continue;
|
|
294
|
+
}
|
|
295
|
+
try {
|
|
296
|
+
const fileInfo = readFileContent(filePath);
|
|
297
|
+
const formatted = formatFileAsContext(fileInfo);
|
|
298
|
+
history.addTurn('user', `Here is the content of ${fileInfo.relativePath}:\n\n${formatted}`);
|
|
299
|
+
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?`);
|
|
300
|
+
log(`${style('📎 Loaded file:', 'green')} ${fileInfo.relativePath} (${Math.round(fileInfo.size / 1024 * 10) / 10} KB)\n`);
|
|
301
|
+
} catch (err) {
|
|
302
|
+
log(`${style('Error loading file:', 'red')} ${err.message}\n`);
|
|
303
|
+
}
|
|
304
|
+
promptUser();
|
|
305
|
+
continue;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
if (cmd === 'temperature') {
|
|
309
|
+
log(`\ntemperature is not available in this Chrome context.\n`);
|
|
310
|
+
promptUser();
|
|
311
|
+
continue;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
if (cmd === 'topk') {
|
|
315
|
+
log(`\ntopK is not available in this Chrome context.\n`);
|
|
316
|
+
promptUser();
|
|
317
|
+
continue;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// Unknown slash command
|
|
137
321
|
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
|
|
322
|
+
Unknown command: ${style(rawInput, 'yellow')}
|
|
323
|
+
|
|
324
|
+
Run ${style('/help', 'bold')} to see available commands.
|
|
145
325
|
`);
|
|
146
326
|
promptUser();
|
|
147
327
|
continue;
|
|
148
328
|
}
|
|
149
329
|
|
|
150
|
-
//
|
|
151
|
-
const { finalPrompt, attachedFiles } = extractAndAttachFiles(
|
|
330
|
+
// Normal User Prompt
|
|
331
|
+
const { finalPrompt, attachedFiles } = extractAndAttachFiles(rawInput);
|
|
152
332
|
if (attachedFiles.length > 0) {
|
|
153
333
|
const names = attachedFiles.map((f) => `${f.relativePath} (${Math.round(f.size / 1024 * 10) / 10} KB)`).join(', ');
|
|
154
334
|
log(`${style('📎 Attached:', 'dim')} ${names}`);
|
|
155
335
|
}
|
|
156
336
|
|
|
157
|
-
//
|
|
158
|
-
|
|
337
|
+
// Format full prompt text with history
|
|
338
|
+
const promptToSend = history.length > 0
|
|
339
|
+
? `${history.formatAsPromptText(config.systemPrompt)}\n\nUser: ${finalPrompt}\n\nAssistant:`
|
|
340
|
+
: finalPrompt;
|
|
159
341
|
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
342
|
+
let responseConstraint = null;
|
|
343
|
+
if (config.responseSchema) {
|
|
344
|
+
responseConstraint = config.responseSchema;
|
|
345
|
+
} else if (config.jsonMode) {
|
|
346
|
+
responseConstraint = { type: 'object' };
|
|
163
347
|
}
|
|
164
348
|
|
|
165
|
-
|
|
166
|
-
const fullPromptText = conversation.map((m) => `${m.role === 'user' ? 'User' : 'Assistant'}: ${m.content}`).join('\n\n') + '\n\nAssistant:';
|
|
167
|
-
|
|
168
|
-
let assistantResponse = '';
|
|
169
|
-
|
|
349
|
+
rl.pause();
|
|
170
350
|
try {
|
|
351
|
+
let accumulated = '';
|
|
171
352
|
if (daemon) {
|
|
172
|
-
await streamPromptFromDaemon({
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
353
|
+
accumulated = await streamPromptFromDaemon(daemon, {
|
|
354
|
+
promptText: promptToSend,
|
|
355
|
+
systemPrompt: config.systemPrompt,
|
|
356
|
+
samplingMode: config.samplingMode,
|
|
357
|
+
responseConstraint,
|
|
177
358
|
onChunk: (delta) => {
|
|
178
|
-
assistantResponse += delta;
|
|
179
359
|
process.stdout.write(delta);
|
|
180
360
|
}
|
|
181
361
|
});
|
|
182
|
-
} else {
|
|
183
|
-
await
|
|
184
|
-
promptText: fullPromptText,
|
|
185
|
-
systemPrompt,
|
|
186
|
-
stream: true,
|
|
362
|
+
} else if (sessionManager) {
|
|
363
|
+
accumulated = await sessionManager.promptStreaming(finalPrompt, {
|
|
187
364
|
onChunk: (delta) => {
|
|
188
|
-
assistantResponse += delta;
|
|
189
365
|
process.stdout.write(delta);
|
|
190
366
|
}
|
|
191
367
|
});
|
|
192
368
|
}
|
|
193
369
|
|
|
194
|
-
|
|
370
|
+
history.addTurn('user', finalPrompt);
|
|
371
|
+
history.addTurn('assistant', accumulated);
|
|
195
372
|
process.stdout.write('\n\n');
|
|
196
373
|
} catch (err) {
|
|
197
374
|
log(`\n${style('Error:', 'red')} ${err.message}\n`);
|
|
375
|
+
} finally {
|
|
376
|
+
rl.resume();
|
|
198
377
|
}
|
|
199
378
|
|
|
200
379
|
promptUser();
|
|
201
380
|
}
|
|
381
|
+
|
|
382
|
+
if (standaloneBridge) await standaloneBridge.close().catch(() => {});
|
|
383
|
+
if (standaloneChrome) standaloneChrome.close();
|
|
202
384
|
}
|
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
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';
|
|
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,15 @@ 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 { port, promptText, systemPrompt, samplingMode, responseConstraint, stream = true, onChunk } = opts;
|
|
141
|
+
|
|
117
142
|
return new Promise((resolve, reject) => {
|
|
118
|
-
const payload = JSON.stringify({ promptText, systemPrompt, stream });
|
|
143
|
+
const payload = JSON.stringify({ promptText, systemPrompt, samplingMode, responseConstraint, stream });
|
|
119
144
|
const req = http.request(`http://127.0.0.1:${port}/prompt`, {
|
|
120
145
|
method: 'POST',
|
|
121
146
|
headers: {
|