nanobridge 0.2.4 → 2.0.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 +86 -230
- package/bin/nanobridge.js +1 -1
- package/dist/api/openai.d.ts +135 -0
- package/dist/api/openai.js +210 -0
- package/dist/api/openai.js.map +1 -0
- package/dist/benchmark/runner.d.ts +27 -0
- package/dist/benchmark/runner.js +37 -0
- package/dist/benchmark/runner.js.map +1 -0
- package/dist/benchmark/stats.d.ts +10 -0
- package/dist/benchmark/stats.js +33 -0
- package/dist/benchmark/stats.js.map +1 -0
- package/dist/bin/nanobridge.d.ts +2 -0
- package/dist/bin/nanobridge.js +4 -0
- package/dist/bin/nanobridge.js.map +1 -0
- package/dist/chat/commands.d.ts +9 -0
- package/dist/chat/commands.js +52 -0
- package/dist/chat/commands.js.map +1 -0
- package/dist/chat/config.d.ts +22 -0
- package/dist/chat/config.js +55 -0
- package/dist/chat/config.js.map +1 -0
- package/dist/chat/history.d.ts +12 -0
- package/dist/chat/history.js +74 -0
- package/dist/chat/history.js.map +1 -0
- package/dist/chat/session.d.ts +42 -0
- package/dist/chat/session.js +107 -0
- package/dist/chat/session.js.map +1 -0
- package/dist/chat/storage.d.ts +17 -0
- package/dist/chat/storage.js +71 -0
- package/dist/chat/storage.js.map +1 -0
- package/dist/cli.d.ts +7 -0
- package/dist/cli.js +363 -0
- package/dist/cli.js.map +1 -0
- package/dist/commands/ask.d.ts +4 -0
- package/dist/commands/ask.js +288 -0
- package/dist/commands/ask.js.map +1 -0
- package/dist/commands/bench.d.ts +2 -0
- package/dist/commands/bench.js +92 -0
- package/dist/commands/bench.js.map +1 -0
- package/dist/commands/chat.d.ts +2 -0
- package/dist/commands/chat.js +701 -0
- package/dist/commands/chat.js.map +1 -0
- package/dist/commands/config.d.ts +2 -0
- package/dist/commands/config.js +102 -0
- package/dist/commands/config.js.map +1 -0
- package/dist/commands/daemon.d.ts +2 -0
- package/dist/commands/daemon.js +225 -0
- package/dist/commands/daemon.js.map +1 -0
- package/dist/commands/embed.d.ts +2 -0
- package/dist/commands/embed.js +79 -0
- package/dist/commands/embed.js.map +1 -0
- package/dist/commands/models.d.ts +5 -0
- package/dist/commands/models.js +244 -0
- package/dist/commands/models.js.map +1 -0
- package/dist/commands/serve.d.ts +2 -0
- package/dist/commands/serve.js +52 -0
- package/dist/commands/serve.js.map +1 -0
- package/dist/commands/status.d.ts +2 -0
- package/dist/commands/status.js +81 -0
- package/dist/commands/status.js.map +1 -0
- package/dist/daemon/client.d.ts +74 -0
- package/dist/daemon/client.js +447 -0
- package/dist/daemon/client.js.map +1 -0
- package/dist/daemon/server.d.ts +43 -0
- package/dist/daemon/server.js +661 -0
- package/dist/daemon/server.js.map +1 -0
- package/dist/daemon/service.d.ts +29 -0
- package/dist/daemon/service.js +173 -0
- package/dist/daemon/service.js.map +1 -0
- package/dist/daemon/state.d.ts +4 -0
- package/dist/daemon/state.js +54 -0
- package/dist/daemon/state.js.map +1 -0
- package/dist/engine/llama-engine.d.ts +49 -0
- package/dist/engine/llama-engine.js +465 -0
- package/dist/engine/llama-engine.js.map +1 -0
- package/dist/engine/model-pool.d.ts +36 -0
- package/dist/engine/model-pool.js +202 -0
- package/dist/engine/model-pool.js.map +1 -0
- package/dist/engine/sampling.d.ts +13 -0
- package/dist/engine/sampling.js +43 -0
- package/dist/engine/sampling.js.map +1 -0
- package/dist/models/catalog.d.ts +6 -0
- package/dist/models/catalog.js +124 -0
- package/dist/models/catalog.js.map +1 -0
- package/dist/models/config.d.ts +10 -0
- package/dist/models/config.js +141 -0
- package/dist/models/config.js.map +1 -0
- package/dist/models/downloader.d.ts +21 -0
- package/dist/models/downloader.js +98 -0
- package/dist/models/downloader.js.map +1 -0
- package/dist/models/profiles.d.ts +10 -0
- package/dist/models/profiles.js +68 -0
- package/dist/models/profiles.js.map +1 -0
- package/dist/models/store.d.ts +9 -0
- package/dist/models/store.js +142 -0
- package/dist/models/store.js.map +1 -0
- package/dist/types.d.ts +189 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/utils/errors.d.ts +18 -0
- package/dist/utils/errors.js +33 -0
- package/dist/utils/errors.js.map +1 -0
- package/dist/utils/files.d.ts +14 -0
- package/dist/utils/files.js +88 -0
- package/dist/utils/files.js.map +1 -0
- package/dist/utils/output.d.ts +29 -0
- package/dist/utils/output.js +116 -0
- package/dist/utils/output.js.map +1 -0
- package/package.json +28 -11
- package/examples/openai-client.js +0 -112
- package/examples/openai-sdk.js +0 -46
- package/examples/openai_python.py +0 -42
- package/src/api/openai.js +0 -115
- package/src/benchmark/runner.js +0 -48
- package/src/benchmark/stats.js +0 -33
- package/src/chat/commands.js +0 -68
- package/src/chat/config.js +0 -65
- package/src/chat/history.js +0 -103
- package/src/chat/session.js +0 -337
- package/src/chrome/bridge.js +0 -473
- package/src/chrome/capabilities.js +0 -99
- package/src/chrome/detect.js +0 -199
- package/src/chrome/launch.js +0 -248
- package/src/cli.js +0 -216
- package/src/commands/ask.js +0 -217
- package/src/commands/bench.js +0 -79
- package/src/commands/chat.js +0 -426
- package/src/commands/daemon.js +0 -89
- package/src/commands/download.js +0 -71
- package/src/commands/serve.js +0 -56
- package/src/commands/status.js +0 -87
- package/src/daemon/client.js +0 -274
- package/src/daemon/server.js +0 -650
- package/src/daemon/state.js +0 -46
- package/src/utils/errors.js +0 -26
- package/src/utils/files.js +0 -93
- package/src/utils/output.js +0 -107
- package/test/chat.test.js +0 -252
- package/test/cli.test.js +0 -49
- package/test/daemon.test.js +0 -31
- package/test/detect.test.js +0 -24
- package/test/files.test.js +0 -41
- package/test/openai.test.js +0 -63
- package/test/stats.test.js +0 -29
package/src/commands/chat.js
DELETED
|
@@ -1,426 +0,0 @@
|
|
|
1
|
-
import readline from 'node:readline';
|
|
2
|
-
import process from 'node:process';
|
|
3
|
-
import { ensureDaemon, streamPromptFromDaemon, resetDaemon } from '../daemon/client.js';
|
|
4
|
-
import { launchChrome } from '../chrome/launch.js';
|
|
5
|
-
import { ChromeBridge } from '../chrome/bridge.js';
|
|
6
|
-
import { log, style, debug, createSpinner } from '../utils/output.js';
|
|
7
|
-
import { NanoBridgeError } from '../utils/errors.js';
|
|
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';
|
|
13
|
-
|
|
14
|
-
export async function handleChat(options = {}) {
|
|
15
|
-
let daemon = null;
|
|
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();
|
|
24
|
-
|
|
25
|
-
// 1. Try connecting to background daemon first (sub-second startup, no GPU lock contention)
|
|
26
|
-
if (options.daemon !== false) {
|
|
27
|
-
try {
|
|
28
|
-
debug('chat', 'Checking or starting background daemon...');
|
|
29
|
-
daemon = await ensureDaemon();
|
|
30
|
-
} catch (err) {
|
|
31
|
-
debug('chat', 'Daemon unavailable, falling back to direct standalone Chrome:', err.message);
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
// 2. Standalone fallback if daemon disabled or unavailable
|
|
36
|
-
if (!daemon) {
|
|
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
|
-
}
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
// Welcome banner
|
|
55
|
-
log(`
|
|
56
|
-
${style('NanoBridge Interactive Chat', 'bold')} ${style('(Gemini Nano on-device)', 'cyan')}
|
|
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')}
|
|
58
|
-
`);
|
|
59
|
-
|
|
60
|
-
const rl = readline.createInterface({
|
|
61
|
-
input: process.stdin,
|
|
62
|
-
output: process.stdout,
|
|
63
|
-
prompt: `\x1b[36m>\x1b[0m `
|
|
64
|
-
});
|
|
65
|
-
|
|
66
|
-
const promptUser = () => {
|
|
67
|
-
rl.prompt();
|
|
68
|
-
};
|
|
69
|
-
|
|
70
|
-
const cleanup = async () => {
|
|
71
|
-
rl.close();
|
|
72
|
-
if (standaloneBridge) await standaloneBridge.close().catch(() => {});
|
|
73
|
-
if (standaloneChrome) standaloneChrome.close();
|
|
74
|
-
log(`\n${style('Goodbye!', 'dim')}`);
|
|
75
|
-
process.exit(0);
|
|
76
|
-
};
|
|
77
|
-
|
|
78
|
-
rl.on('SIGINT', () => {
|
|
79
|
-
cleanup();
|
|
80
|
-
});
|
|
81
|
-
|
|
82
|
-
promptUser();
|
|
83
|
-
|
|
84
|
-
for await (const line of rl) {
|
|
85
|
-
let rawInput = line.trim();
|
|
86
|
-
|
|
87
|
-
if (!rawInput) {
|
|
88
|
-
promptUser();
|
|
89
|
-
continue;
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
let parsed = parseCommand(rawInput);
|
|
93
|
-
|
|
94
|
-
if (parsed.isCommand && (parsed.command === 'continue' || parsed.command === 'c')) {
|
|
95
|
-
rawInput = parsed.value ? `continue from where you left off: ${parsed.value}` : 'continue from where you left off';
|
|
96
|
-
parsed = { isCommand: false };
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
if (parsed.isCommand) {
|
|
100
|
-
const cmd = parsed.command;
|
|
101
|
-
const val = parsed.value;
|
|
102
|
-
|
|
103
|
-
if (cmd === 'exit' || cmd === 'quit') {
|
|
104
|
-
await cleanup();
|
|
105
|
-
break;
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
if (cmd === 'help') {
|
|
109
|
-
log(`\n${formatChatHelp({ samplingMode: true, initialPrompts: true, responseConstraint: true })}\n`);
|
|
110
|
-
promptUser();
|
|
111
|
-
continue;
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
if (cmd === 'sampling') {
|
|
115
|
-
if (!val) {
|
|
116
|
-
log(`\nSampling mode: ${style(config.samplingMode || 'balanced', 'bold')}\n`);
|
|
117
|
-
promptUser();
|
|
118
|
-
continue;
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
const validMode = validateSamplingMode(val);
|
|
122
|
-
if (validMode) {
|
|
123
|
-
config.samplingMode = validMode;
|
|
124
|
-
if (sessionManager) {
|
|
125
|
-
await sessionManager.recreateSession({ preserveHistory: true }).catch(() => {});
|
|
126
|
-
}
|
|
127
|
-
log(`
|
|
128
|
-
Sampling: ${style(validMode, 'bold')}
|
|
129
|
-
Session recreated.
|
|
130
|
-
Conversation preserved.
|
|
131
|
-
`);
|
|
132
|
-
} else {
|
|
133
|
-
log(`\n${style(`Invalid sampling mode: "${val}". Valid: creative, predictable, balanced, most-predictable, most-creative`, 'red')}\n`);
|
|
134
|
-
}
|
|
135
|
-
promptUser();
|
|
136
|
-
continue;
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
if (cmd === 'system') {
|
|
140
|
-
if (!val) {
|
|
141
|
-
log(`\nSystem prompt: ${config.systemPrompt ? `"${config.systemPrompt}"` : 'none'}\n`);
|
|
142
|
-
promptUser();
|
|
143
|
-
continue;
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
config.systemPrompt = val.trim();
|
|
147
|
-
if (daemon) {
|
|
148
|
-
const initialPrompts = history.formatInitialPrompts(config.systemPrompt);
|
|
149
|
-
await streamPromptFromDaemon(daemon, {
|
|
150
|
-
promptText: '',
|
|
151
|
-
systemPrompt: config.systemPrompt,
|
|
152
|
-
sessionType: 'chat',
|
|
153
|
-
initialPrompts,
|
|
154
|
-
stream: false
|
|
155
|
-
}).catch(() => {});
|
|
156
|
-
} else if (sessionManager) {
|
|
157
|
-
await sessionManager.recreateSession({ preserveHistory: true }).catch(() => {});
|
|
158
|
-
}
|
|
159
|
-
log(`
|
|
160
|
-
System prompt updated.
|
|
161
|
-
Session recreated.
|
|
162
|
-
Conversation preserved.
|
|
163
|
-
`);
|
|
164
|
-
promptUser();
|
|
165
|
-
continue;
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
if (cmd === 'json') {
|
|
169
|
-
const lower = val.toLowerCase();
|
|
170
|
-
if (lower === 'on' || lower === 'true' || lower === '1') {
|
|
171
|
-
config.jsonMode = true;
|
|
172
|
-
log(`\nJSON mode ${style('enabled', 'green')}.\n`);
|
|
173
|
-
} else if (lower === 'off' || lower === 'false' || lower === '0') {
|
|
174
|
-
config.jsonMode = false;
|
|
175
|
-
config.responseSchema = null;
|
|
176
|
-
config.schemaPath = null;
|
|
177
|
-
log(`\nJSON mode ${style('disabled', 'yellow')}.\n`);
|
|
178
|
-
} else {
|
|
179
|
-
log(`${style('Usage:', 'dim')} /json on | /json off\n`);
|
|
180
|
-
}
|
|
181
|
-
promptUser();
|
|
182
|
-
continue;
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
if (cmd === 'schema') {
|
|
186
|
-
if (!val) {
|
|
187
|
-
if (config.schemaPath) {
|
|
188
|
-
log(`\nActive schema: ${config.schemaPath}\n`);
|
|
189
|
-
} else {
|
|
190
|
-
log(`\nNo schema loaded. Usage: /schema <filepath> or /schema clear\n`);
|
|
191
|
-
}
|
|
192
|
-
promptUser();
|
|
193
|
-
continue;
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
if (val.toLowerCase() === 'clear' || val.toLowerCase() === 'off') {
|
|
197
|
-
config.responseSchema = null;
|
|
198
|
-
config.schemaPath = null;
|
|
199
|
-
config.jsonMode = false;
|
|
200
|
-
log(`
|
|
201
|
-
Schema cleared.
|
|
202
|
-
JSON mode disabled.
|
|
203
|
-
`);
|
|
204
|
-
promptUser();
|
|
205
|
-
continue;
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
try {
|
|
209
|
-
const { schema, relativePath } = loadAndValidateJsonSchema(val);
|
|
210
|
-
config.responseSchema = schema;
|
|
211
|
-
config.schemaPath = relativePath;
|
|
212
|
-
config.jsonMode = true;
|
|
213
|
-
log(`
|
|
214
|
-
Schema loaded: ${style(relativePath, 'bold')}
|
|
215
|
-
JSON mode enabled.
|
|
216
|
-
`);
|
|
217
|
-
} catch (schemaErr) {
|
|
218
|
-
log(`\n${style('Schema error:', 'red')} ${schemaErr.message}\n`);
|
|
219
|
-
}
|
|
220
|
-
promptUser();
|
|
221
|
-
continue;
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
if (cmd === 'context') {
|
|
225
|
-
const turnCount = history.length;
|
|
226
|
-
let estimatedTokens = turnCount * 50;
|
|
227
|
-
let windowSize = 9216;
|
|
228
|
-
if (daemon) {
|
|
229
|
-
try {
|
|
230
|
-
const res = await fetch(`http://127.0.0.1:${daemon.port}/status`);
|
|
231
|
-
const data = await res.json();
|
|
232
|
-
if (data.chatStats && typeof data.chatStats.contextUsage === 'number') {
|
|
233
|
-
estimatedTokens = data.chatStats.contextUsage;
|
|
234
|
-
windowSize = data.chatStats.contextWindow || 9216;
|
|
235
|
-
}
|
|
236
|
-
} catch (_) {}
|
|
237
|
-
}
|
|
238
|
-
const pct = ((estimatedTokens / windowSize) * 100).toFixed(1);
|
|
239
|
-
|
|
240
|
-
log(`
|
|
241
|
-
${style('Context', 'bold')}
|
|
242
|
-
|
|
243
|
-
Used ${estimatedTokens}
|
|
244
|
-
Window ${windowSize}
|
|
245
|
-
Usage ${pct}%
|
|
246
|
-
Messages ${turnCount}
|
|
247
|
-
`);
|
|
248
|
-
promptUser();
|
|
249
|
-
continue;
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
if (cmd === 'settings') {
|
|
253
|
-
log(`
|
|
254
|
-
${style('NanoBridge Chat Settings', 'bold')}
|
|
255
|
-
|
|
256
|
-
Sampling ${config.samplingMode || 'balanced'}
|
|
257
|
-
System ${config.systemPrompt ? 'custom' : 'none'}
|
|
258
|
-
JSON mode ${config.jsonMode ? 'on' : 'off'}
|
|
259
|
-
Schema ${config.schemaPath || 'none'}
|
|
260
|
-
Input language ${config.expectedInputLanguages.join(', ')}
|
|
261
|
-
Output language ${config.expectedOutputLanguages.join(', ')}
|
|
262
|
-
Context ${history.length * 50} / 9216
|
|
263
|
-
Temperature unsupported
|
|
264
|
-
TopK unsupported
|
|
265
|
-
`);
|
|
266
|
-
promptUser();
|
|
267
|
-
continue;
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
if (cmd === 'clear' || cmd === 'reset') {
|
|
271
|
-
history.clear();
|
|
272
|
-
if (daemon) {
|
|
273
|
-
await resetDaemon({ session: 'chat' }).catch(() => {});
|
|
274
|
-
}
|
|
275
|
-
log(`
|
|
276
|
-
Conversation cleared.
|
|
277
|
-
Configuration preserved.
|
|
278
|
-
`);
|
|
279
|
-
promptUser();
|
|
280
|
-
continue;
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
if (cmd === 'new') {
|
|
284
|
-
history.clear();
|
|
285
|
-
config.samplingMode = 'balanced';
|
|
286
|
-
config.systemPrompt = null;
|
|
287
|
-
config.jsonMode = false;
|
|
288
|
-
config.responseSchema = null;
|
|
289
|
-
config.schemaPath = null;
|
|
290
|
-
if (daemon) {
|
|
291
|
-
await resetDaemon({ session: 'chat' }).catch(() => {});
|
|
292
|
-
}
|
|
293
|
-
log(`
|
|
294
|
-
New session started.
|
|
295
|
-
`);
|
|
296
|
-
promptUser();
|
|
297
|
-
continue;
|
|
298
|
-
}
|
|
299
|
-
|
|
300
|
-
if (cmd === 'history') {
|
|
301
|
-
const msgs = history.getMessages();
|
|
302
|
-
log(`\n${style('Conversation History:', 'bold')} (${msgs.length} messages)`);
|
|
303
|
-
msgs.forEach((m) => {
|
|
304
|
-
const roleStyle = m.role === 'user' ? 'cyan' : (m.role === 'assistant' ? 'green' : 'dim');
|
|
305
|
-
log(`${style(`[${m.role.toUpperCase()}]:`, roleStyle)} ${m.content.slice(0, 80)}${m.content.length > 80 ? '...' : ''}`);
|
|
306
|
-
});
|
|
307
|
-
log('');
|
|
308
|
-
promptUser();
|
|
309
|
-
continue;
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
if (cmd === 'read' || cmd === 'file') {
|
|
313
|
-
const filePath = val;
|
|
314
|
-
if (!filePath) {
|
|
315
|
-
log(`${style('Usage:', 'dim')} /read <filepath>\n`);
|
|
316
|
-
promptUser();
|
|
317
|
-
continue;
|
|
318
|
-
}
|
|
319
|
-
try {
|
|
320
|
-
const fileInfo = readFileContent(filePath);
|
|
321
|
-
const formatted = formatFileAsContext(fileInfo);
|
|
322
|
-
history.addTurn('user', `Here is the content of ${fileInfo.relativePath}:\n\n${formatted}`);
|
|
323
|
-
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?`);
|
|
324
|
-
log(`${style('📎 Loaded file:', 'green')} ${fileInfo.relativePath} (${Math.round(fileInfo.size / 1024 * 10) / 10} KB)\n`);
|
|
325
|
-
} catch (err) {
|
|
326
|
-
log(`${style('Error loading file:', 'red')} ${err.message}\n`);
|
|
327
|
-
}
|
|
328
|
-
promptUser();
|
|
329
|
-
continue;
|
|
330
|
-
}
|
|
331
|
-
|
|
332
|
-
if (cmd === 'temperature') {
|
|
333
|
-
log(`\ntemperature is not available in this Chrome context.\n`);
|
|
334
|
-
promptUser();
|
|
335
|
-
continue;
|
|
336
|
-
}
|
|
337
|
-
|
|
338
|
-
if (cmd === 'topk') {
|
|
339
|
-
log(`\ntopK is not available in this Chrome context.\n`);
|
|
340
|
-
promptUser();
|
|
341
|
-
continue;
|
|
342
|
-
}
|
|
343
|
-
|
|
344
|
-
// Unknown slash command
|
|
345
|
-
log(`
|
|
346
|
-
Unknown command: ${style(rawInput, 'yellow')}
|
|
347
|
-
|
|
348
|
-
Run ${style('/help', 'bold')} to see available commands.
|
|
349
|
-
`);
|
|
350
|
-
promptUser();
|
|
351
|
-
continue;
|
|
352
|
-
}
|
|
353
|
-
|
|
354
|
-
// Normal User Prompt
|
|
355
|
-
const { finalPrompt, attachedFiles } = extractAndAttachFiles(rawInput);
|
|
356
|
-
if (attachedFiles.length > 0) {
|
|
357
|
-
const names = attachedFiles.map((f) => `${f.relativePath} (${Math.round(f.size / 1024 * 10) / 10} KB)`).join(', ');
|
|
358
|
-
log(`${style('📎 Attached:', 'dim')} ${names}`);
|
|
359
|
-
}
|
|
360
|
-
|
|
361
|
-
let responseConstraint = null;
|
|
362
|
-
if (config.responseSchema) {
|
|
363
|
-
responseConstraint = config.responseSchema;
|
|
364
|
-
} else if (config.jsonMode) {
|
|
365
|
-
responseConstraint = { type: 'object' };
|
|
366
|
-
}
|
|
367
|
-
|
|
368
|
-
rl.pause();
|
|
369
|
-
const spinner = createSpinner('Thinking...');
|
|
370
|
-
try {
|
|
371
|
-
let accumulated = '';
|
|
372
|
-
let isFirstChunk = true;
|
|
373
|
-
const onDelta = (delta) => {
|
|
374
|
-
if (isFirstChunk) {
|
|
375
|
-
spinner.stop();
|
|
376
|
-
isFirstChunk = false;
|
|
377
|
-
}
|
|
378
|
-
process.stdout.write(delta);
|
|
379
|
-
};
|
|
380
|
-
|
|
381
|
-
if (daemon) {
|
|
382
|
-
accumulated = await streamPromptFromDaemon(daemon, {
|
|
383
|
-
promptText: finalPrompt,
|
|
384
|
-
systemPrompt: config.systemPrompt,
|
|
385
|
-
samplingMode: config.samplingMode,
|
|
386
|
-
sessionType: 'chat',
|
|
387
|
-
responseConstraint,
|
|
388
|
-
onChunk: onDelta
|
|
389
|
-
});
|
|
390
|
-
} else if (sessionManager) {
|
|
391
|
-
accumulated = await sessionManager.promptStreaming(finalPrompt, {
|
|
392
|
-
onChunk: onDelta
|
|
393
|
-
});
|
|
394
|
-
}
|
|
395
|
-
|
|
396
|
-
spinner.stop();
|
|
397
|
-
|
|
398
|
-
history.addTurn('user', finalPrompt);
|
|
399
|
-
history.addTurn('assistant', accumulated);
|
|
400
|
-
process.stdout.write('\n');
|
|
401
|
-
|
|
402
|
-
const trimmedAcc = (accumulated || '').trim();
|
|
403
|
-
const likelyTruncated = trimmedAcc.length > 300 &&
|
|
404
|
-
!/[.?!:;]\s*$/.test(trimmedAcc) &&
|
|
405
|
-
!trimmedAcc.endsWith('```') &&
|
|
406
|
-
!trimmedAcc.endsWith('}') &&
|
|
407
|
-
!trimmedAcc.endsWith(']');
|
|
408
|
-
|
|
409
|
-
if (likelyTruncated) {
|
|
410
|
-
log(style('↳ [Response reached token limit. Type "continue" or /c to resume]', 'dim'));
|
|
411
|
-
}
|
|
412
|
-
process.stdout.write('\n');
|
|
413
|
-
} catch (err) {
|
|
414
|
-
spinner.stop();
|
|
415
|
-
log(`\n${style('Error:', 'red')} ${err.message}\n`);
|
|
416
|
-
} finally {
|
|
417
|
-
spinner.stop();
|
|
418
|
-
rl.resume();
|
|
419
|
-
}
|
|
420
|
-
|
|
421
|
-
promptUser();
|
|
422
|
-
}
|
|
423
|
-
|
|
424
|
-
if (standaloneBridge) await standaloneBridge.close().catch(() => {});
|
|
425
|
-
if (standaloneChrome) standaloneChrome.close();
|
|
426
|
-
}
|
package/src/commands/daemon.js
DELETED
|
@@ -1,89 +0,0 @@
|
|
|
1
|
-
import { getActiveDaemon, startDaemonInBackground, stopDaemon, resetDaemon } from '../daemon/client.js';
|
|
2
|
-
import { style, log, logError } from '../utils/output.js';
|
|
3
|
-
|
|
4
|
-
export async function handleDaemonCommand(subCommand = 'status', options = {}) {
|
|
5
|
-
if (subCommand === 'start') {
|
|
6
|
-
const active = await getActiveDaemon();
|
|
7
|
-
if (active) {
|
|
8
|
-
if (options.json) {
|
|
9
|
-
console.log(JSON.stringify({ status: 'running', pid: active.pid, port: active.port }, null, 2));
|
|
10
|
-
} else {
|
|
11
|
-
log(`Daemon is already running (PID: ${style(active.pid, 'bold')}, port: ${style(active.port, 'cyan')})`);
|
|
12
|
-
}
|
|
13
|
-
return;
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
if (!options.json) {
|
|
17
|
-
log('Starting NanoBridge background daemon...');
|
|
18
|
-
}
|
|
19
|
-
const started = await startDaemonInBackground();
|
|
20
|
-
if (options.json) {
|
|
21
|
-
console.log(JSON.stringify({ status: 'started', pid: started.pid, port: started.port }, null, 2));
|
|
22
|
-
} else {
|
|
23
|
-
log(`${style('Daemon started successfully', 'green')} ✓ (PID: ${style(started.pid, 'bold')}, port: ${style(started.port, 'cyan')})`);
|
|
24
|
-
}
|
|
25
|
-
return;
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
if (subCommand === 'restart') {
|
|
29
|
-
if (!options.json) {
|
|
30
|
-
log('Restarting NanoBridge background daemon...');
|
|
31
|
-
}
|
|
32
|
-
await stopDaemon();
|
|
33
|
-
const started = await startDaemonInBackground();
|
|
34
|
-
if (options.json) {
|
|
35
|
-
console.log(JSON.stringify({ status: 'restarted', pid: started.pid, port: started.port }, null, 2));
|
|
36
|
-
} else {
|
|
37
|
-
log(`${style('Daemon restarted successfully', 'green')} ✓ (PID: ${style(started.pid, 'bold')}, port: ${style(started.port, 'cyan')})`);
|
|
38
|
-
}
|
|
39
|
-
return;
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
if (subCommand === 'reset') {
|
|
43
|
-
const res = await resetDaemon();
|
|
44
|
-
if (options.json) {
|
|
45
|
-
console.log(JSON.stringify(res, null, 2));
|
|
46
|
-
} else {
|
|
47
|
-
if (res.success) {
|
|
48
|
-
log(`${style('Model session and KV context cache reset successfully', 'green')} ✓`);
|
|
49
|
-
} else {
|
|
50
|
-
log(`${style('Notice:', 'yellow')} ${res.message || res.error}`);
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
return;
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
if (subCommand === 'stop') {
|
|
57
|
-
const res = await stopDaemon();
|
|
58
|
-
if (options.json) {
|
|
59
|
-
console.log(JSON.stringify(res, null, 2));
|
|
60
|
-
} else {
|
|
61
|
-
if (res.wasRunning) {
|
|
62
|
-
log(`${style('Daemon stopped', 'green')} ✓`);
|
|
63
|
-
} else {
|
|
64
|
-
log('Daemon was not running.');
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
return;
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
if (subCommand === 'status') {
|
|
71
|
-
const active = await getActiveDaemon();
|
|
72
|
-
if (options.json) {
|
|
73
|
-
console.log(JSON.stringify(active ? { status: 'running', ...active } : { status: 'stopped' }, null, 2));
|
|
74
|
-
} else {
|
|
75
|
-
if (active) {
|
|
76
|
-
const uptimeSec = Math.round((active.uptimeMs || 0) / 1000);
|
|
77
|
-
log(`Status: ${style('running', 'green')}`);
|
|
78
|
-
log(`PID: ${active.pid}`);
|
|
79
|
-
log(`Port: ${active.port}`);
|
|
80
|
-
log(`Uptime: ${uptimeSec}s`);
|
|
81
|
-
} else {
|
|
82
|
-
log(`Status: ${style('stopped', 'dim')}`);
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
return;
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
logError(`Unknown daemon subcommand: ${subCommand}`);
|
|
89
|
-
}
|
package/src/commands/download.js
DELETED
|
@@ -1,71 +0,0 @@
|
|
|
1
|
-
import process from 'node:process';
|
|
2
|
-
import { launchChrome } from '../chrome/launch.js';
|
|
3
|
-
import { ChromeBridge } from '../chrome/bridge.js';
|
|
4
|
-
import { isModelDownloaded } from '../chrome/detect.js';
|
|
5
|
-
import { style, log, renderProgressBar } from '../utils/output.js';
|
|
6
|
-
|
|
7
|
-
export async function handleDownload(options = {}) {
|
|
8
|
-
if (isModelDownloaded()) {
|
|
9
|
-
if (options.json) {
|
|
10
|
-
console.log(JSON.stringify({ status: 'ready', alreadyAvailable: true }, null, 2));
|
|
11
|
-
} else {
|
|
12
|
-
log(`${style('Model already available', 'green')} ✓`);
|
|
13
|
-
}
|
|
14
|
-
return;
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
let chromeInstance = null;
|
|
18
|
-
let bridge = null;
|
|
19
|
-
|
|
20
|
-
try {
|
|
21
|
-
if (!options.json) {
|
|
22
|
-
log('Preparing Chrome Built-in AI...\n');
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
chromeInstance = await launchChrome(options);
|
|
26
|
-
bridge = new ChromeBridge(chromeInstance);
|
|
27
|
-
await bridge.connect();
|
|
28
|
-
|
|
29
|
-
let lastRenderedPercent = -1;
|
|
30
|
-
let isTty = Boolean(process.stdout.isTTY) && !options.json;
|
|
31
|
-
|
|
32
|
-
const result = await bridge.downloadModel({
|
|
33
|
-
onProgress: ({ loaded, total, percent }) => {
|
|
34
|
-
const rounded = Math.round(percent);
|
|
35
|
-
if (rounded !== lastRenderedPercent) {
|
|
36
|
-
lastRenderedPercent = rounded;
|
|
37
|
-
if (options.json) return;
|
|
38
|
-
|
|
39
|
-
const bar = renderProgressBar(rounded, 28);
|
|
40
|
-
if (isTty) {
|
|
41
|
-
process.stdout.write(`\r${style(bar, 'cyan')} Downloading model components...`);
|
|
42
|
-
} else {
|
|
43
|
-
log(`${bar} Downloading model components`);
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
}
|
|
47
|
-
});
|
|
48
|
-
|
|
49
|
-
if (result.alreadyAvailable) {
|
|
50
|
-
if (options.json) {
|
|
51
|
-
console.log(JSON.stringify({ status: 'ready', alreadyAvailable: true }, null, 2));
|
|
52
|
-
} else {
|
|
53
|
-
log(`${style('Model already available', 'green')} ✓`);
|
|
54
|
-
}
|
|
55
|
-
return;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
if (isTty) {
|
|
59
|
-
process.stdout.write('\n\n');
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
if (options.json) {
|
|
63
|
-
console.log(JSON.stringify({ status: 'ready', downloaded: true }, null, 2));
|
|
64
|
-
} else {
|
|
65
|
-
log(`${style('Model ready', 'green')} ✓`);
|
|
66
|
-
}
|
|
67
|
-
} finally {
|
|
68
|
-
if (bridge) await bridge.close();
|
|
69
|
-
if (chromeInstance) chromeInstance.close();
|
|
70
|
-
}
|
|
71
|
-
}
|
package/src/commands/serve.js
DELETED
|
@@ -1,56 +0,0 @@
|
|
|
1
|
-
import process from 'node:process';
|
|
2
|
-
import { DaemonServer } from '../daemon/server.js';
|
|
3
|
-
import { style, log, logError } from '../utils/output.js';
|
|
4
|
-
|
|
5
|
-
export async function handleServe(options = {}) {
|
|
6
|
-
const port = options.port || 8000;
|
|
7
|
-
const host = options.host || '127.0.0.1';
|
|
8
|
-
|
|
9
|
-
log(style('NanoBridge OpenAI-Compatible API Server', 'bold'));
|
|
10
|
-
log('Starting background Chrome and warming Gemini Nano...');
|
|
11
|
-
|
|
12
|
-
const server = new DaemonServer({
|
|
13
|
-
port,
|
|
14
|
-
host,
|
|
15
|
-
idleTimeoutMs: 0 // Do not auto-shutdown when explicitly running in serve mode
|
|
16
|
-
});
|
|
17
|
-
|
|
18
|
-
try {
|
|
19
|
-
await server.start();
|
|
20
|
-
|
|
21
|
-
const baseUrl = `http://${host}:${server.port}/v1`;
|
|
22
|
-
|
|
23
|
-
log('');
|
|
24
|
-
log(`${style('OpenAI-Compatible Server Ready!', 'green')} ✓`);
|
|
25
|
-
log(`Base URL: ${style(baseUrl, 'cyan')}`);
|
|
26
|
-
log(`Models: ${style(`${baseUrl}/models`, 'dim')}`);
|
|
27
|
-
log(`Chat: ${style(`${baseUrl}/chat/completions`, 'dim')}`);
|
|
28
|
-
log(`Completions: ${style(`${baseUrl}/completions`, 'dim')}`);
|
|
29
|
-
log('');
|
|
30
|
-
log(style('Example curl (Streaming SSE):', 'bold'));
|
|
31
|
-
log(` curl -N ${baseUrl}/chat/completions \\
|
|
32
|
-
-H "Content-Type: application/json" \\
|
|
33
|
-
-d '{
|
|
34
|
-
"model": "gemini-nano",
|
|
35
|
-
"messages": [{"role": "user", "content": "Hello!"}],
|
|
36
|
-
"stream": true
|
|
37
|
-
}'`);
|
|
38
|
-
log('');
|
|
39
|
-
log(style('Example OpenAI Python SDK:', 'bold'));
|
|
40
|
-
log(` from openai import OpenAI
|
|
41
|
-
client = OpenAI(base_url="${baseUrl}", api_key="nanobridge")
|
|
42
|
-
response = client.chat.completions.create(
|
|
43
|
-
model="gemini-nano",
|
|
44
|
-
messages=[{"role": "user", "content": "Explain Web Locks"}]
|
|
45
|
-
)
|
|
46
|
-
print(response.choices[0].message.content)`);
|
|
47
|
-
log('');
|
|
48
|
-
log(`Press ${style('Ctrl+C', 'bold')} to stop server.`);
|
|
49
|
-
|
|
50
|
-
// Keep running until interrupt
|
|
51
|
-
await new Promise(() => {});
|
|
52
|
-
} catch (err) {
|
|
53
|
-
logError(`Failed to start serve server: ${err.message}`);
|
|
54
|
-
process.exit(1);
|
|
55
|
-
}
|
|
56
|
-
}
|