nanobridge 0.1.0 → 0.1.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 +14 -4
- package/examples/openai-client.js +112 -0
- package/examples/openai-sdk.js +46 -0
- package/examples/openai_python.py +42 -0
- package/package.json +1 -1
- package/src/chrome/bridge.js +18 -13
- package/src/chrome/launch.js +3 -3
- package/src/cli.js +11 -1
- package/src/commands/chat.js +11 -3
- package/src/commands/daemon.js +29 -1
- package/src/daemon/client.js +34 -2
- package/src/daemon/server.js +25 -2
- package/src/utils/files.js +25 -9
- package/test/cli.test.js +6 -0
- package/test/files.test.js +11 -6
package/README.md
CHANGED
|
@@ -202,9 +202,9 @@ for await (const chunk of stream) {
|
|
|
202
202
|
|
|
203
203
|
---
|
|
204
204
|
|
|
205
|
-
### 6. Background Daemon Management
|
|
205
|
+
### 6. Background Daemon Management & Context Reset
|
|
206
206
|
|
|
207
|
-
NanoBridge
|
|
207
|
+
NanoBridge runs a warm Chrome background daemon to eliminate the ~2.5s cold-start penalty on every query:
|
|
208
208
|
|
|
209
209
|
```bash
|
|
210
210
|
# Start the background daemon
|
|
@@ -213,12 +213,22 @@ nanobridge daemon start
|
|
|
213
213
|
# Check daemon status (PID, Port, Uptime)
|
|
214
214
|
nanobridge daemon status
|
|
215
215
|
|
|
216
|
+
# Reset model session and clear KV context cache (<100ms)
|
|
217
|
+
nanobridge reset
|
|
218
|
+
|
|
219
|
+
# Restart the background daemon process
|
|
220
|
+
nanobridge restart
|
|
221
|
+
# or:
|
|
222
|
+
nanobridge daemon restart
|
|
223
|
+
|
|
216
224
|
# Stop the running background daemon
|
|
217
|
-
nanobridge daemon stop
|
|
218
|
-
# or simply:
|
|
219
225
|
nanobridge stop
|
|
226
|
+
# or:
|
|
227
|
+
nanobridge daemon stop
|
|
220
228
|
```
|
|
221
229
|
|
|
230
|
+
> **Memory & Halucination Reset**: If you have long-running chat sessions or heavy multi-file prompts, running `nanobridge reset` (or typing `/reset` in `nanobridge chat`) instantly clears Chrome's on-device session and KV cache without needing to cold-relaunch Chrome.
|
|
231
|
+
|
|
222
232
|
---
|
|
223
233
|
|
|
224
234
|
### 7. Benchmarking On-Device Performance
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* NanoBridge OpenAI API Compatibility Test Script
|
|
3
|
+
*
|
|
4
|
+
* Demonstrates:
|
|
5
|
+
* 1. GET /v1/models
|
|
6
|
+
* 2. POST /v1/chat/completions (Non-Streaming)
|
|
7
|
+
* 3. POST /v1/chat/completions (Streaming SSE)
|
|
8
|
+
*
|
|
9
|
+
* Usage:
|
|
10
|
+
* 1. Start the server: nanobridge serve --port 8000
|
|
11
|
+
* (or use the warm background daemon port)
|
|
12
|
+
* 2. Run this script: node examples/openai-client.js
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
const BASE_URL = process.env.NANOBRIDGE_BASE_URL || 'http://127.0.0.1:8000/v1';
|
|
16
|
+
|
|
17
|
+
async function testModels() {
|
|
18
|
+
console.log('\n=== 1. Testing GET /v1/models ===');
|
|
19
|
+
const res = await fetch(`${BASE_URL}/models`);
|
|
20
|
+
const data = await res.json();
|
|
21
|
+
console.log('Available Models:', JSON.stringify(data, null, 2));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
async function testNonStreaming() {
|
|
25
|
+
console.log('\n=== 2. Testing POST /v1/chat/completions (Non-Streaming) ===');
|
|
26
|
+
const payload = {
|
|
27
|
+
model: 'gemini-nano',
|
|
28
|
+
messages: [
|
|
29
|
+
{ role: 'system', content: 'You are a concise, helpful AI assistant.' },
|
|
30
|
+
{ role: 'user', content: 'Explain Node.js in one clear sentence.' }
|
|
31
|
+
],
|
|
32
|
+
temperature: 0.2
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
const startTime = Date.now();
|
|
36
|
+
const res = await fetch(`${BASE_URL}/chat/completions`, {
|
|
37
|
+
method: 'POST',
|
|
38
|
+
headers: { 'Content-Type': 'application/json' },
|
|
39
|
+
body: JSON.stringify(payload)
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
const json = await res.json();
|
|
43
|
+
const elapsed = Date.now() - startTime;
|
|
44
|
+
|
|
45
|
+
console.log(`Response (${elapsed}ms):`);
|
|
46
|
+
console.log(json.choices[0]?.message?.content);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async function testStreaming() {
|
|
50
|
+
console.log('\n=== 3. Testing POST /v1/chat/completions (Streaming SSE) ===');
|
|
51
|
+
const payload = {
|
|
52
|
+
model: 'gemini-nano',
|
|
53
|
+
messages: [
|
|
54
|
+
{ role: 'user', content: 'Count from 1 to 5 with emojis.' }
|
|
55
|
+
],
|
|
56
|
+
stream: true
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
const startTime = Date.now();
|
|
60
|
+
const res = await fetch(`${BASE_URL}/chat/completions`, {
|
|
61
|
+
method: 'POST',
|
|
62
|
+
headers: { 'Content-Type': 'application/json' },
|
|
63
|
+
body: JSON.stringify(payload)
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
process.stdout.write('Stream Output: ');
|
|
67
|
+
const reader = res.body.getReader();
|
|
68
|
+
const decoder = new TextDecoder('utf-8');
|
|
69
|
+
let buffer = '';
|
|
70
|
+
|
|
71
|
+
while (true) {
|
|
72
|
+
const { done, value } = await reader.read();
|
|
73
|
+
if (done) break;
|
|
74
|
+
|
|
75
|
+
buffer += decoder.decode(value, { stream: true });
|
|
76
|
+
const lines = buffer.split('\n');
|
|
77
|
+
buffer = lines.pop() || '';
|
|
78
|
+
|
|
79
|
+
for (const line of lines) {
|
|
80
|
+
const trimmed = line.trim();
|
|
81
|
+
if (!trimmed || !trimmed.startsWith('data: ')) continue;
|
|
82
|
+
const dataStr = trimmed.slice(6);
|
|
83
|
+
if (dataStr === '[DONE]') {
|
|
84
|
+
break;
|
|
85
|
+
}
|
|
86
|
+
try {
|
|
87
|
+
const parsed = JSON.parse(dataStr);
|
|
88
|
+
const delta = parsed.choices[0]?.delta?.content || '';
|
|
89
|
+
process.stdout.write(delta);
|
|
90
|
+
} catch (_) {}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const elapsed = Date.now() - startTime;
|
|
95
|
+
console.log(`\n\nStream finished in ${elapsed}ms`);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async function main() {
|
|
99
|
+
console.log(`Connecting to NanoBridge OpenAI Server at ${BASE_URL}...`);
|
|
100
|
+
try {
|
|
101
|
+
await testModels();
|
|
102
|
+
await testNonStreaming();
|
|
103
|
+
await testStreaming();
|
|
104
|
+
console.log('\nAll OpenAI API tests completed successfully! ✓');
|
|
105
|
+
} catch (err) {
|
|
106
|
+
console.error('\nTest failed:', err.message);
|
|
107
|
+
console.log('\nMake sure the server is running:');
|
|
108
|
+
console.log(' nanobridge serve --port 8000');
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
main();
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* NanoBridge with Official OpenAI SDK (JavaScript / Node.js)
|
|
3
|
+
*
|
|
4
|
+
* Requirements:
|
|
5
|
+
* npm install openai
|
|
6
|
+
*
|
|
7
|
+
* Usage:
|
|
8
|
+
* 1. Start server: nanobridge serve --port 8000
|
|
9
|
+
* 2. Run script: node examples/openai-sdk.js
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import OpenAI from 'openai';
|
|
13
|
+
|
|
14
|
+
const openai = new OpenAI({
|
|
15
|
+
baseURL: 'http://127.0.0.1:8000/v1',
|
|
16
|
+
apiKey: 'nanobridge' // Any dummy string works (no API key required)
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
async function run() {
|
|
20
|
+
console.log('--- 1. Non-Streaming Completion ---');
|
|
21
|
+
const completion = await openai.chat.completions.create({
|
|
22
|
+
model: 'gemini-nano',
|
|
23
|
+
messages: [
|
|
24
|
+
{ role: 'system', content: 'You are a helpful assistant.' },
|
|
25
|
+
{ role: 'user', content: 'What is Chrome Built-in AI?' }
|
|
26
|
+
]
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
console.log(completion.choices[0].message.content);
|
|
30
|
+
|
|
31
|
+
console.log('\n--- 2. Streaming Completion ---');
|
|
32
|
+
const stream = await openai.chat.completions.create({
|
|
33
|
+
model: 'gemini-nano',
|
|
34
|
+
messages: [
|
|
35
|
+
{ role: 'user', content: 'List 3 benefits of local on-device AI models.' }
|
|
36
|
+
],
|
|
37
|
+
stream: true
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
for await (const chunk of stream) {
|
|
41
|
+
process.stdout.write(chunk.choices[0]?.delta?.content || '');
|
|
42
|
+
}
|
|
43
|
+
console.log('\n');
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
run().catch(console.error);
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""
|
|
2
|
+
NanoBridge with Official OpenAI Python SDK
|
|
3
|
+
|
|
4
|
+
Requirements:
|
|
5
|
+
pip install openai
|
|
6
|
+
|
|
7
|
+
Usage:
|
|
8
|
+
1. Start server: nanobridge serve --port 8000
|
|
9
|
+
2. Run script: python3 examples/openai_python.py
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from openai import OpenAI
|
|
13
|
+
|
|
14
|
+
client = OpenAI(
|
|
15
|
+
base_url="http://127.0.0.1:8000/v1",
|
|
16
|
+
api_key="nanobridge", # Any string (no auth required)
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
print("=== 1. Testing Non-Streaming ===")
|
|
20
|
+
response = client.chat.completions.create(
|
|
21
|
+
model="gemini-nano",
|
|
22
|
+
messages=[
|
|
23
|
+
{"role": "system", "content": "You are a concise assistant."},
|
|
24
|
+
{"role": "user", "content": "Explain WebSocket in one sentence."}
|
|
25
|
+
],
|
|
26
|
+
)
|
|
27
|
+
print(response.choices[0].message.content)
|
|
28
|
+
|
|
29
|
+
print("\n=== 2. Testing Streaming ===")
|
|
30
|
+
stream = client.chat.completions.create(
|
|
31
|
+
model="gemini-nano",
|
|
32
|
+
messages=[
|
|
33
|
+
{"role": "user", "content": "List 3 programming tips."}
|
|
34
|
+
],
|
|
35
|
+
stream=True,
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
for chunk in stream:
|
|
39
|
+
content = chunk.choices[0].delta.content or ""
|
|
40
|
+
print(content, end="", flush=True)
|
|
41
|
+
|
|
42
|
+
print("\n")
|
package/package.json
CHANGED
package/src/chrome/bridge.js
CHANGED
|
@@ -107,28 +107,33 @@ export class ChromeBridge {
|
|
|
107
107
|
return Boolean(this.ws && this.ws.readyState === WebSocket.OPEN);
|
|
108
108
|
}
|
|
109
109
|
|
|
110
|
-
send(method, params = {}) {
|
|
110
|
+
send(method, params = {}, options = {}) {
|
|
111
111
|
return new Promise((resolve, reject) => {
|
|
112
112
|
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
|
|
113
113
|
return reject(new Error('CDP WebSocket is closed or not connected'));
|
|
114
114
|
}
|
|
115
115
|
const id = this.msgId++;
|
|
116
|
-
const
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
116
|
+
const timeoutMs = options.timeout ?? 60000;
|
|
117
|
+
let timer = null;
|
|
118
|
+
|
|
119
|
+
if (timeoutMs > 0) {
|
|
120
|
+
timer = setTimeout(() => {
|
|
121
|
+
if (this.pendingCallbacks.has(id)) {
|
|
122
|
+
this.pendingCallbacks.delete(id);
|
|
123
|
+
reject(new Error(`CDP command timed out: ${method}`));
|
|
124
|
+
}
|
|
125
|
+
}, timeoutMs);
|
|
126
|
+
if (timer.unref) timer.unref();
|
|
127
|
+
}
|
|
123
128
|
|
|
124
129
|
this.pendingCallbacks.set(id, {
|
|
125
|
-
resolve: (val) => { clearTimeout(timer); resolve(val); },
|
|
126
|
-
reject: (err) => { clearTimeout(timer); reject(err); }
|
|
130
|
+
resolve: (val) => { if (timer) clearTimeout(timer); resolve(val); },
|
|
131
|
+
reject: (err) => { if (timer) clearTimeout(timer); reject(err); }
|
|
127
132
|
});
|
|
128
133
|
|
|
129
134
|
this.ws.send(JSON.stringify({ id, method, params }), (err) => {
|
|
130
135
|
if (err) {
|
|
131
|
-
clearTimeout(timer);
|
|
136
|
+
if (timer) clearTimeout(timer);
|
|
132
137
|
this.pendingCallbacks.delete(id);
|
|
133
138
|
reject(err);
|
|
134
139
|
}
|
|
@@ -150,7 +155,7 @@ export class ChromeBridge {
|
|
|
150
155
|
awaitPromise: options.awaitPromise ?? true,
|
|
151
156
|
returnByValue: options.returnByValue ?? true,
|
|
152
157
|
userGesture: options.userGesture ?? true
|
|
153
|
-
});
|
|
158
|
+
}, { timeout: options.timeout });
|
|
154
159
|
|
|
155
160
|
if (res.exceptionDetails) {
|
|
156
161
|
const desc = res.exceptionDetails.exception?.description || res.exceptionDetails.text;
|
|
@@ -237,7 +242,7 @@ export class ChromeBridge {
|
|
|
237
242
|
} catch (e) {
|
|
238
243
|
return { success: false, error: e.message, stack: e.stack };
|
|
239
244
|
}
|
|
240
|
-
})()`, { userGesture: true });
|
|
245
|
+
})()`, { userGesture: true, timeout: 900000 });
|
|
241
246
|
|
|
242
247
|
if (!evalResult.success) {
|
|
243
248
|
throw new NanoBridgeError(`Failed to prepare/download model: ${evalResult.error}`);
|
package/src/chrome/launch.js
CHANGED
|
@@ -25,7 +25,7 @@ export async function launchChrome(options = {}) {
|
|
|
25
25
|
'Content-Type': 'text/html; charset=utf-8',
|
|
26
26
|
'Cache-Control': 'no-cache'
|
|
27
27
|
});
|
|
28
|
-
res.end('<!DOCTYPE html><html><head><title>NanoBridge Host</title></head><body><h1>NanoBridge</h1></body></html>');
|
|
28
|
+
res.end('<!DOCTYPE html><html><head><meta charset="utf-8"><title>NanoBridge Host</title></head><body><h1>NanoBridge</h1></body></html>');
|
|
29
29
|
});
|
|
30
30
|
|
|
31
31
|
await new Promise((resolve, reject) => {
|
|
@@ -77,7 +77,7 @@ export async function launchChrome(options = {}) {
|
|
|
77
77
|
'--disable-popup-blocking',
|
|
78
78
|
'--disable-prompt-on-repost',
|
|
79
79
|
'--disable-hang-monitor',
|
|
80
|
-
'--disable-dev-shm-usage',
|
|
80
|
+
...(isDarwin ? [] : ['--disable-dev-shm-usage']),
|
|
81
81
|
'--password-store=basic',
|
|
82
82
|
'--use-mock-keychain',
|
|
83
83
|
'--disable-background-timer-throttling',
|
|
@@ -88,7 +88,7 @@ export async function launchChrome(options = {}) {
|
|
|
88
88
|
'--enable-gpu-rasterization',
|
|
89
89
|
'--enable-zero-copy',
|
|
90
90
|
...(isDarwin ? ['--use-angle=metal', '--enable-metal'] : []),
|
|
91
|
-
'--enable-blink-features=AIPromptAPI
|
|
91
|
+
'--enable-blink-features=AIPromptAPI',
|
|
92
92
|
'--enable-features=PromptAPIForGeminiNano,OptimizationGuideOnDeviceModel',
|
|
93
93
|
'--optimization-guide-on-device-model-override-switch=bypass-ram-check',
|
|
94
94
|
...(options.extraArgs || []),
|
package/src/cli.js
CHANGED
|
@@ -27,7 +27,9 @@ ${style('COMMANDS:', 'bold')}
|
|
|
27
27
|
serve Start OpenAI-compatible API server (/v1/chat/completions)
|
|
28
28
|
download Download and prepare the Chrome on-device AI model components
|
|
29
29
|
bench Run benchmark measuring startup, TTFT, and generation rate
|
|
30
|
-
daemon [start|stop]
|
|
30
|
+
daemon [start|stop|restart|reset] Manage the background warm daemon process
|
|
31
|
+
reset Reset the active model session and clear KV context cache
|
|
32
|
+
restart Restart the background warm daemon
|
|
31
33
|
stop Stop the running background daemon
|
|
32
34
|
|
|
33
35
|
${style('OPTIONS:', 'bold')}
|
|
@@ -165,6 +167,14 @@ export async function runCli(argv = process.argv) {
|
|
|
165
167
|
break;
|
|
166
168
|
}
|
|
167
169
|
|
|
170
|
+
case 'reset':
|
|
171
|
+
await handleDaemonCommand('reset', options);
|
|
172
|
+
break;
|
|
173
|
+
|
|
174
|
+
case 'restart':
|
|
175
|
+
await handleDaemonCommand('restart', options);
|
|
176
|
+
break;
|
|
177
|
+
|
|
168
178
|
case 'stop':
|
|
169
179
|
await handleDaemonCommand('stop', options);
|
|
170
180
|
break;
|
package/src/commands/chat.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import readline from 'node:readline';
|
|
2
2
|
import process from 'node:process';
|
|
3
|
-
import { ensureDaemon, streamPromptFromDaemon } from '../daemon/client.js';
|
|
3
|
+
import { ensureDaemon, streamPromptFromDaemon, resetDaemon } from '../daemon/client.js';
|
|
4
4
|
import { launchChrome } from '../chrome/launch.js';
|
|
5
5
|
import { ChromeBridge } from '../chrome/bridge.js';
|
|
6
6
|
import { log, style, debug } from '../utils/output.js';
|
|
@@ -8,7 +8,7 @@ import { NanoBridgeError } from '../utils/errors.js';
|
|
|
8
8
|
import { readFileContent, formatFileAsContext, extractAndAttachFiles } from '../utils/files.js';
|
|
9
9
|
|
|
10
10
|
export async function handleChat(options = {}) {
|
|
11
|
-
let systemPrompt = options.system || 'You are a helpful,
|
|
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
12
|
const conversation = [];
|
|
13
13
|
let daemon = null;
|
|
14
14
|
let standaloneBridge = null;
|
|
@@ -81,8 +81,11 @@ ${style('Commands:', 'dim')} ${style('/clear', 'yellow')} to reset history, ${st
|
|
|
81
81
|
|
|
82
82
|
if (input.toLowerCase() === '/clear' || input.toLowerCase() === '/reset') {
|
|
83
83
|
conversation.length = 0;
|
|
84
|
+
if (daemon) {
|
|
85
|
+
await resetDaemon().catch(() => {});
|
|
86
|
+
}
|
|
84
87
|
console.clear();
|
|
85
|
-
log(`${style('Conversation
|
|
88
|
+
log(`${style('Conversation context and model session reset successfully.', 'green')}\n`);
|
|
86
89
|
promptUser();
|
|
87
90
|
continue;
|
|
88
91
|
}
|
|
@@ -154,6 +157,11 @@ ${style('Chat Commands:', 'bold')}
|
|
|
154
157
|
// Append to conversation
|
|
155
158
|
conversation.push({ role: 'user', content: finalPrompt });
|
|
156
159
|
|
|
160
|
+
// Truncate older context if conversation is too long for on-device context window
|
|
161
|
+
while (conversation.length > 8) {
|
|
162
|
+
conversation.shift();
|
|
163
|
+
}
|
|
164
|
+
|
|
157
165
|
// Build context prompt
|
|
158
166
|
const fullPromptText = conversation.map((m) => `${m.role === 'user' ? 'User' : 'Assistant'}: ${m.content}`).join('\n\n') + '\n\nAssistant:';
|
|
159
167
|
|
package/src/commands/daemon.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { getActiveDaemon, startDaemonInBackground, stopDaemon } from '../daemon/client.js';
|
|
1
|
+
import { getActiveDaemon, startDaemonInBackground, stopDaemon, resetDaemon } from '../daemon/client.js';
|
|
2
2
|
import { style, log, logError } from '../utils/output.js';
|
|
3
3
|
|
|
4
4
|
export async function handleDaemonCommand(subCommand = 'status', options = {}) {
|
|
@@ -25,6 +25,34 @@ export async function handleDaemonCommand(subCommand = 'status', options = {}) {
|
|
|
25
25
|
return;
|
|
26
26
|
}
|
|
27
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
|
+
|
|
28
56
|
if (subCommand === 'stop') {
|
|
29
57
|
const res = await stopDaemon();
|
|
30
58
|
if (options.json) {
|
package/src/daemon/client.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import http from 'node:http';
|
|
2
2
|
import { spawn } from 'node:child_process';
|
|
3
3
|
import path from 'node:path';
|
|
4
|
+
import { StringDecoder } from 'node:string_decoder';
|
|
4
5
|
import { fileURLToPath } from 'node:url';
|
|
5
6
|
import { getDaemonState, clearDaemonState } from './state.js';
|
|
6
7
|
import { debug } from '../utils/output.js';
|
|
@@ -118,15 +119,16 @@ export async function streamPromptFromDaemon({ port, promptText, systemPrompt, s
|
|
|
118
119
|
const req = http.request(`http://127.0.0.1:${port}/prompt`, {
|
|
119
120
|
method: 'POST',
|
|
120
121
|
headers: {
|
|
121
|
-
'Content-Type': 'application/json',
|
|
122
|
+
'Content-Type': 'application/json; charset=utf-8',
|
|
122
123
|
'Content-Length': Buffer.byteLength(payload)
|
|
123
124
|
}
|
|
124
125
|
}, (res) => {
|
|
126
|
+
const decoder = new StringDecoder('utf8');
|
|
125
127
|
let buffer = '';
|
|
126
128
|
let finalText = '';
|
|
127
129
|
|
|
128
130
|
res.on('data', (chunk) => {
|
|
129
|
-
buffer +=
|
|
131
|
+
buffer += decoder.write(chunk);
|
|
130
132
|
const lines = buffer.split('\n');
|
|
131
133
|
buffer = lines.pop(); // Keep partial line in buffer
|
|
132
134
|
|
|
@@ -147,6 +149,13 @@ export async function streamPromptFromDaemon({ port, promptText, systemPrompt, s
|
|
|
147
149
|
});
|
|
148
150
|
|
|
149
151
|
res.on('end', () => {
|
|
152
|
+
buffer += decoder.end();
|
|
153
|
+
if (buffer.trim()) {
|
|
154
|
+
try {
|
|
155
|
+
const data = JSON.parse(buffer);
|
|
156
|
+
if (data.type === 'done') finalText = data.text;
|
|
157
|
+
} catch (_) {}
|
|
158
|
+
}
|
|
150
159
|
resolve(finalText);
|
|
151
160
|
});
|
|
152
161
|
});
|
|
@@ -161,6 +170,29 @@ export async function streamPromptFromDaemon({ port, promptText, systemPrompt, s
|
|
|
161
170
|
});
|
|
162
171
|
}
|
|
163
172
|
|
|
173
|
+
export async function resetDaemon() {
|
|
174
|
+
const active = await getActiveDaemon();
|
|
175
|
+
if (!active) {
|
|
176
|
+
return { success: false, message: 'Daemon is not running' };
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
return new Promise((resolve, reject) => {
|
|
180
|
+
const req = http.request(`http://127.0.0.1:${active.port}/reset`, { method: 'POST', timeout: 5000 }, (res) => {
|
|
181
|
+
let data = '';
|
|
182
|
+
res.on('data', (c) => { data += c; });
|
|
183
|
+
res.on('end', () => {
|
|
184
|
+
try {
|
|
185
|
+
resolve(JSON.parse(data));
|
|
186
|
+
} catch (_) {
|
|
187
|
+
resolve({ success: true });
|
|
188
|
+
}
|
|
189
|
+
});
|
|
190
|
+
});
|
|
191
|
+
req.on('error', reject);
|
|
192
|
+
req.end();
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
|
|
164
196
|
export async function stopDaemon() {
|
|
165
197
|
const active = await getActiveDaemon();
|
|
166
198
|
if (!active) {
|
package/src/daemon/server.js
CHANGED
|
@@ -282,6 +282,25 @@ export class DaemonServer {
|
|
|
282
282
|
return;
|
|
283
283
|
}
|
|
284
284
|
|
|
285
|
+
// Reset / Recycle Context Endpoint
|
|
286
|
+
if ((req.method === 'POST' || req.method === 'GET') && url.pathname === '/reset') {
|
|
287
|
+
try {
|
|
288
|
+
await this.runExclusive(async () => {
|
|
289
|
+
debug('daemon', 'Resetting Chrome AI session context & reloading host page...');
|
|
290
|
+
if (this.bridge && this.bridge.isConnected()) {
|
|
291
|
+
await this.bridge.send('Page.reload').catch(() => {});
|
|
292
|
+
}
|
|
293
|
+
await this.warmupSession();
|
|
294
|
+
});
|
|
295
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
296
|
+
res.end(JSON.stringify({ success: true, message: 'Model session and context reset successfully' }));
|
|
297
|
+
} catch (err) {
|
|
298
|
+
res.writeHead(500, { 'Content-Type': 'application/json' });
|
|
299
|
+
res.end(JSON.stringify({ success: false, error: err.message }));
|
|
300
|
+
}
|
|
301
|
+
return;
|
|
302
|
+
}
|
|
303
|
+
|
|
285
304
|
// Native NanoBridge /prompt Endpoint
|
|
286
305
|
if (req.method === 'POST' && url.pathname === '/prompt') {
|
|
287
306
|
let body = '';
|
|
@@ -383,7 +402,7 @@ export class DaemonServer {
|
|
|
383
402
|
|
|
384
403
|
const reqId = requestId || `req_${Date.now()}_${Math.random().toString(36).slice(2)}`;
|
|
385
404
|
const escapedPrompt = JSON.stringify(promptText);
|
|
386
|
-
const
|
|
405
|
+
const escapedSystem = systemPrompt ? JSON.stringify(systemPrompt) : 'null';
|
|
387
406
|
const prefix = `__NANOBRIDGE_CHUNK_${reqId}__:`;
|
|
388
407
|
|
|
389
408
|
if (stream && onChunk) {
|
|
@@ -406,11 +425,15 @@ export class DaemonServer {
|
|
|
406
425
|
return { success: false, error: 'LanguageModel API not available' };
|
|
407
426
|
}
|
|
408
427
|
window.__nanobridge_current_req = '${reqId}';
|
|
409
|
-
|
|
428
|
+
|
|
429
|
+
const sysPrompt = ${escapedSystem};
|
|
430
|
+
const createOptions = sysPrompt ? { systemPrompt: sysPrompt } : {};
|
|
431
|
+
const session = await window.LanguageModel.create(createOptions);
|
|
410
432
|
|
|
411
433
|
const stream = session.promptStreaming(${escapedPrompt});
|
|
412
434
|
let finalResult = '';
|
|
413
435
|
let prev = '';
|
|
436
|
+
|
|
414
437
|
for await (const chunk of stream) {
|
|
415
438
|
if (window.__nanobridge_abort_req === '${reqId}') {
|
|
416
439
|
if (typeof session.destroy === 'function') session.destroy();
|
package/src/utils/files.js
CHANGED
|
@@ -44,24 +44,40 @@ export function formatFileAsContext(fileInfo) {
|
|
|
44
44
|
}
|
|
45
45
|
|
|
46
46
|
/**
|
|
47
|
-
* Detects and expands @filepath in user input
|
|
48
|
-
* e.g. "Explain @src/cli.js please"
|
|
47
|
+
* Detects and expands @filepath or @file <filepath> in user input
|
|
48
|
+
* e.g. "Explain @src/cli.js please" or "@file package.json hangi paketler var"
|
|
49
49
|
*/
|
|
50
50
|
export function extractAndAttachFiles(input) {
|
|
51
|
-
const fileRegex = /@([^\s"']+)/g;
|
|
52
51
|
const attachedFiles = [];
|
|
53
52
|
let cleanedInput = input;
|
|
54
|
-
let match;
|
|
55
53
|
|
|
56
|
-
|
|
54
|
+
// 1. Check for @file <path> or @file:<path>
|
|
55
|
+
const fileCmdRegex = /@file[:\s]+([^\s"']+)/gi;
|
|
56
|
+
let cmdMatch;
|
|
57
|
+
while ((cmdMatch = fileCmdRegex.exec(input)) !== null) {
|
|
58
|
+
const candidatePath = cmdMatch[1];
|
|
59
|
+
try {
|
|
60
|
+
const fileInfo = readFileContent(candidatePath);
|
|
61
|
+
if (!attachedFiles.some((f) => f.path === fileInfo.path)) {
|
|
62
|
+
attachedFiles.push(fileInfo);
|
|
63
|
+
}
|
|
64
|
+
cleanedInput = cleanedInput.replace(cmdMatch[0], `[File: ${fileInfo.relativePath}]`);
|
|
65
|
+
} catch (_) {}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// 2. Check for @<path>
|
|
69
|
+
const fileRegex = /@([^\s"']+)/g;
|
|
70
|
+
let match;
|
|
71
|
+
while ((match = fileRegex.exec(cleanedInput)) !== null) {
|
|
57
72
|
const candidatePath = match[1];
|
|
73
|
+
if (candidatePath.toLowerCase() === 'file') continue;
|
|
58
74
|
try {
|
|
59
75
|
const fileInfo = readFileContent(candidatePath);
|
|
60
|
-
attachedFiles.
|
|
76
|
+
if (!attachedFiles.some((f) => f.path === fileInfo.path)) {
|
|
77
|
+
attachedFiles.push(fileInfo);
|
|
78
|
+
}
|
|
61
79
|
cleanedInput = cleanedInput.replace(match[0], `[File: ${fileInfo.relativePath}]`);
|
|
62
|
-
} catch (_) {
|
|
63
|
-
// If file doesn't exist or fails to read, keep raw string
|
|
64
|
-
}
|
|
80
|
+
} catch (_) {}
|
|
65
81
|
}
|
|
66
82
|
|
|
67
83
|
let finalPrompt = cleanedInput;
|
package/test/cli.test.js
CHANGED
|
@@ -22,6 +22,12 @@ test('parseArgs correctly parses commands and flags', () => {
|
|
|
22
22
|
const parsed3 = parseArgs(['node', 'nanobridge', 'bench', '--runs', '5']);
|
|
23
23
|
assert.equal(parsed3.command, 'bench');
|
|
24
24
|
assert.equal(parsed3.options.runs, 5);
|
|
25
|
+
|
|
26
|
+
const parsed4 = parseArgs(['node', 'nanobridge', 'reset']);
|
|
27
|
+
assert.equal(parsed4.command, 'reset');
|
|
28
|
+
|
|
29
|
+
const parsed5 = parseArgs(['node', 'nanobridge', 'restart']);
|
|
30
|
+
assert.equal(parsed5.command, 'restart');
|
|
25
31
|
});
|
|
26
32
|
|
|
27
33
|
test('combinePromptAndContext merges prompt and stdin predictably', () => {
|
package/test/files.test.js
CHANGED
|
@@ -20,12 +20,17 @@ describe('File Reading & Context Utilities', () => {
|
|
|
20
20
|
});
|
|
21
21
|
|
|
22
22
|
test('extracts @file mentions from user input', () => {
|
|
23
|
-
const
|
|
24
|
-
const
|
|
25
|
-
assert.strictEqual(attachedFiles.length, 1);
|
|
26
|
-
assert.strictEqual(attachedFiles[0].filename, 'package.json');
|
|
27
|
-
assert.ok(finalPrompt.includes('--- File: package.json ---'));
|
|
28
|
-
|
|
23
|
+
const input1 = 'Please explain @package.json dependencies';
|
|
24
|
+
const res1 = extractAndAttachFiles(input1);
|
|
25
|
+
assert.strictEqual(res1.attachedFiles.length, 1);
|
|
26
|
+
assert.strictEqual(res1.attachedFiles[0].filename, 'package.json');
|
|
27
|
+
assert.ok(res1.finalPrompt.includes('--- File: package.json ---'));
|
|
28
|
+
|
|
29
|
+
const input2 = '@file package.json hangi paketler kullanılmış?';
|
|
30
|
+
const res2 = extractAndAttachFiles(input2);
|
|
31
|
+
assert.strictEqual(res2.attachedFiles.length, 1);
|
|
32
|
+
assert.strictEqual(res2.attachedFiles[0].filename, 'package.json');
|
|
33
|
+
assert.ok(res2.finalPrompt.includes('--- File: package.json ---'));
|
|
29
34
|
});
|
|
30
35
|
|
|
31
36
|
test('throws error on non-existent file', () => {
|