nanobridge 0.1.0 → 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 +29 -14
- 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/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 +44 -16
- package/src/chrome/capabilities.js +99 -0
- package/src/chrome/launch.js +47 -16
- package/src/cli.js +11 -1
- package/src/commands/chat.js +286 -96
- package/src/commands/daemon.js +29 -1
- package/src/commands/status.js +14 -5
- package/src/daemon/client.js +63 -6
- package/src/daemon/server.js +75 -14
- package/src/daemon/state.js +0 -3
- package/src/utils/files.js +25 -9
- package/test/chat.test.js +250 -0
- package/test/cli.test.js +6 -0
- package/test/files.test.js +11 -6
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
import { debug } from '../utils/output.js';
|
|
2
|
+
import { ConversationHistory } from './history.js';
|
|
3
|
+
import { createDefaultChatConfig, validateSamplingMode, validateLanguageCode } from './config.js';
|
|
4
|
+
import { detectCapabilities } from '../chrome/capabilities.js';
|
|
5
|
+
|
|
6
|
+
export class ChatSessionManager {
|
|
7
|
+
constructor(bridge, options = {}) {
|
|
8
|
+
this.bridge = bridge;
|
|
9
|
+
this.config = createDefaultChatConfig(options);
|
|
10
|
+
this.history = new ConversationHistory(options.history || []);
|
|
11
|
+
this.capabilities = options.capabilities || null;
|
|
12
|
+
this.initialized = false;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
async init() {
|
|
16
|
+
if (!this.capabilities) {
|
|
17
|
+
this.capabilities = await detectCapabilities(this.bridge);
|
|
18
|
+
}
|
|
19
|
+
this.initialized = true;
|
|
20
|
+
return this;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
async recreateSession({ preserveHistory = true } = {}) {
|
|
24
|
+
debug('chat', `Session reset requested (preserveHistory=${preserveHistory})`);
|
|
25
|
+
if (!preserveHistory) {
|
|
26
|
+
this.history.clear();
|
|
27
|
+
}
|
|
28
|
+
if (this.bridge && this.bridge.isConnected()) {
|
|
29
|
+
await this.bridge.evaluate(`(() => {
|
|
30
|
+
if (window.__nanobridge_chat_session && typeof window.__nanobridge_chat_session.destroy === 'function') {
|
|
31
|
+
try { window.__nanobridge_chat_session.destroy(); } catch (_) {}
|
|
32
|
+
}
|
|
33
|
+
window.__nanobridge_chat_session = null;
|
|
34
|
+
window.__nanobridge_chat_session_config = null;
|
|
35
|
+
})()`).catch(() => {});
|
|
36
|
+
}
|
|
37
|
+
return {
|
|
38
|
+
success: true,
|
|
39
|
+
historyRestored: this.history.length
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async promptStreaming(userPrompt, { onChunk, onOverflow } = {}) {
|
|
44
|
+
const reqId = `chat_${Date.now()}_${Math.random().toString(36).slice(2)}`;
|
|
45
|
+
const prefix = `__NANOBRIDGE_CHUNK_${reqId}__:`;
|
|
46
|
+
const overflowPrefix = '__NANOBRIDGE_CONTEXT_OVERFLOW__:';
|
|
47
|
+
|
|
48
|
+
let chunkHandler = null;
|
|
49
|
+
let overflowHandler = null;
|
|
50
|
+
|
|
51
|
+
if (onChunk) {
|
|
52
|
+
chunkHandler = (payload) => {
|
|
53
|
+
try {
|
|
54
|
+
const data = JSON.parse(payload);
|
|
55
|
+
if (data.d) onChunk(data.d);
|
|
56
|
+
} catch (_) {}
|
|
57
|
+
};
|
|
58
|
+
this.bridge.addConsoleHandler(prefix, chunkHandler);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
if (onOverflow) {
|
|
62
|
+
overflowHandler = () => {
|
|
63
|
+
onOverflow();
|
|
64
|
+
};
|
|
65
|
+
this.bridge.addConsoleHandler(overflowPrefix, overflowHandler);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// Prepare constraints
|
|
69
|
+
let constraintArg = null;
|
|
70
|
+
if (this.config.responseSchema) {
|
|
71
|
+
constraintArg = this.config.responseSchema;
|
|
72
|
+
} else if (this.config.jsonMode) {
|
|
73
|
+
constraintArg = { type: 'object' };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// Build initial prompts
|
|
77
|
+
const initialPrompts = this.history.formatInitialPrompts(this.config.systemPrompt);
|
|
78
|
+
|
|
79
|
+
const payload = {
|
|
80
|
+
systemPrompt: this.config.systemPrompt,
|
|
81
|
+
samplingMode: this.capabilities?.samplingMode ? this.config.samplingMode : undefined,
|
|
82
|
+
temperature: this.capabilities?.temperature && this.config.temperature !== null ? this.config.temperature : undefined,
|
|
83
|
+
topK: this.capabilities?.topK && this.config.topK !== null ? this.config.topK : undefined,
|
|
84
|
+
initialPrompts: initialPrompts.length > 0 ? initialPrompts : undefined,
|
|
85
|
+
constraint: constraintArg
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
// Format prompt text fallback if initialPrompts not used
|
|
89
|
+
const promptToSend = (initialPrompts.length > 0 && !this.capabilities?.initialPrompts)
|
|
90
|
+
? `${this.history.formatAsPromptText(this.config.systemPrompt)}\n\nUser: ${userPrompt}\n\nAssistant:`
|
|
91
|
+
: userPrompt;
|
|
92
|
+
|
|
93
|
+
try {
|
|
94
|
+
const evalRes = await this.bridge.evaluate(`(async () => {
|
|
95
|
+
try {
|
|
96
|
+
if (!('LanguageModel' in window)) {
|
|
97
|
+
return { success: false, error: 'LanguageModel not available in active page context' };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const config = ${JSON.stringify(payload)};
|
|
101
|
+
const currentConfig = window.__nanobridge_chat_session_config || {};
|
|
102
|
+
const configMatches = window.__nanobridge_chat_session &&
|
|
103
|
+
currentConfig.systemPrompt === config.systemPrompt &&
|
|
104
|
+
currentConfig.samplingMode === config.samplingMode;
|
|
105
|
+
|
|
106
|
+
if (!configMatches) {
|
|
107
|
+
if (window.__nanobridge_chat_session && typeof window.__nanobridge_chat_session.destroy === 'function') {
|
|
108
|
+
try { window.__nanobridge_chat_session.destroy(); } catch (_) {}
|
|
109
|
+
}
|
|
110
|
+
const opts = {};
|
|
111
|
+
if (config.systemPrompt && !config.initialPrompts) {
|
|
112
|
+
opts.systemPrompt = config.systemPrompt;
|
|
113
|
+
}
|
|
114
|
+
if (config.samplingMode) {
|
|
115
|
+
opts.samplingMode = config.samplingMode;
|
|
116
|
+
}
|
|
117
|
+
if (typeof config.temperature === 'number') {
|
|
118
|
+
opts.temperature = config.temperature;
|
|
119
|
+
}
|
|
120
|
+
if (typeof config.topK === 'number') {
|
|
121
|
+
opts.topK = config.topK;
|
|
122
|
+
}
|
|
123
|
+
if (config.initialPrompts && config.initialPrompts.length > 0) {
|
|
124
|
+
opts.initialPrompts = config.initialPrompts;
|
|
125
|
+
}
|
|
126
|
+
window.__nanobridge_chat_session = await window.LanguageModel.create(opts);
|
|
127
|
+
window.__nanobridge_chat_session_config = {
|
|
128
|
+
systemPrompt: config.systemPrompt,
|
|
129
|
+
samplingMode: config.samplingMode
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const session = window.__nanobridge_chat_session;
|
|
134
|
+
const promptOpts = {};
|
|
135
|
+
if (config.constraint) {
|
|
136
|
+
promptOpts.responseConstraint = config.constraint;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const stream = session.promptStreaming(${JSON.stringify(promptToSend)}, promptOpts);
|
|
140
|
+
let finalOutput = '';
|
|
141
|
+
let prev = '';
|
|
142
|
+
|
|
143
|
+
for await (const chunk of stream) {
|
|
144
|
+
finalOutput = chunk;
|
|
145
|
+
const delta = chunk.startsWith(prev) ? chunk.slice(prev.length) : chunk;
|
|
146
|
+
prev = chunk;
|
|
147
|
+
if (delta) {
|
|
148
|
+
console.debug('${prefix}' + JSON.stringify({ d: delta }));
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
let usage = null;
|
|
153
|
+
let windowSize = null;
|
|
154
|
+
try {
|
|
155
|
+
usage = session.contextUsage;
|
|
156
|
+
windowSize = session.contextWindow;
|
|
157
|
+
} catch (_) {}
|
|
158
|
+
|
|
159
|
+
return {
|
|
160
|
+
success: true,
|
|
161
|
+
text: finalOutput,
|
|
162
|
+
contextUsage: usage,
|
|
163
|
+
contextWindow: windowSize
|
|
164
|
+
};
|
|
165
|
+
} catch (e) {
|
|
166
|
+
if (window.__nanobridge_chat_session && typeof window.__nanobridge_chat_session.destroy === 'function') {
|
|
167
|
+
try { window.__nanobridge_chat_session.destroy(); } catch (_) {}
|
|
168
|
+
}
|
|
169
|
+
window.__nanobridge_chat_session = null;
|
|
170
|
+
window.__nanobridge_chat_session_config = null;
|
|
171
|
+
return { success: false, error: e.message };
|
|
172
|
+
}
|
|
173
|
+
})()`, { userGesture: true, timeout: 180000 });
|
|
174
|
+
|
|
175
|
+
if (!evalRes.success) {
|
|
176
|
+
throw new Error(evalRes.error);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// Add user and assistant turns to history
|
|
180
|
+
this.history.addTurn('user', userPrompt);
|
|
181
|
+
this.history.addTurn('assistant', evalRes.text);
|
|
182
|
+
|
|
183
|
+
return evalRes.text;
|
|
184
|
+
} finally {
|
|
185
|
+
if (chunkHandler) this.bridge.removeConsoleHandler(prefix);
|
|
186
|
+
if (overflowHandler) this.bridge.removeConsoleHandler(overflowPrefix);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
async getContextMetrics() {
|
|
191
|
+
return {
|
|
192
|
+
exposed: true,
|
|
193
|
+
used: this.history.length * 50, // estimated turn tokens
|
|
194
|
+
window: 9216,
|
|
195
|
+
percent: ((this.history.length * 50 / 9216) * 100).toFixed(1),
|
|
196
|
+
messagesCount: this.history.length
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
async setSamplingMode(mode) {
|
|
201
|
+
if (!this.capabilities?.samplingMode) {
|
|
202
|
+
return {
|
|
203
|
+
success: false,
|
|
204
|
+
error: 'Sampling mode is not supported by this Chrome runtime.'
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
const validMode = validateSamplingMode(mode, this.capabilities.supportedSamplingModes);
|
|
209
|
+
if (!validMode) {
|
|
210
|
+
return {
|
|
211
|
+
success: false,
|
|
212
|
+
error: `Invalid sampling mode: "${mode}". Valid modes: ${this.capabilities.supportedSamplingModes.join(', ')}`
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
this.config.samplingMode = validMode;
|
|
217
|
+
return { success: true, mode: validMode };
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
async setSystemPrompt(prompt) {
|
|
221
|
+
const cleanPrompt = prompt ? prompt.trim() : null;
|
|
222
|
+
this.config.systemPrompt = cleanPrompt;
|
|
223
|
+
return { success: true, systemPrompt: cleanPrompt };
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
async setTemperature(temp) {
|
|
227
|
+
if (!this.capabilities?.temperature) {
|
|
228
|
+
return {
|
|
229
|
+
success: false,
|
|
230
|
+
error: 'temperature is not available in this Chrome context.'
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const num = Number(temp);
|
|
235
|
+
if (isNaN(num) || num < 0 || num > 2) {
|
|
236
|
+
return {
|
|
237
|
+
success: false,
|
|
238
|
+
error: 'Temperature must be a valid number between 0.0 and 2.0.'
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
this.config.temperature = num;
|
|
243
|
+
return { success: true, temperature: num };
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
async setTopK(val) {
|
|
247
|
+
if (!this.capabilities?.topK) {
|
|
248
|
+
return {
|
|
249
|
+
success: false,
|
|
250
|
+
error: 'topK is not available in this Chrome context.'
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
const num = parseInt(val, 10);
|
|
255
|
+
if (isNaN(num) || num < 1 || num > 128) {
|
|
256
|
+
return {
|
|
257
|
+
success: false,
|
|
258
|
+
error: 'topK must be an integer between 1 and 128.'
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
this.config.topK = num;
|
|
263
|
+
return { success: true, topK: num };
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
setJsonMode(enabled) {
|
|
267
|
+
this.config.jsonMode = Boolean(enabled);
|
|
268
|
+
if (!this.config.jsonMode) {
|
|
269
|
+
this.config.responseSchema = null;
|
|
270
|
+
this.config.schemaPath = null;
|
|
271
|
+
}
|
|
272
|
+
return { success: true, jsonMode: this.config.jsonMode };
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
setSchema(schema, filePath) {
|
|
276
|
+
this.config.responseSchema = schema;
|
|
277
|
+
this.config.schemaPath = filePath;
|
|
278
|
+
this.config.jsonMode = true;
|
|
279
|
+
return { success: true, schemaPath: filePath };
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
clearSchema() {
|
|
283
|
+
this.config.responseSchema = null;
|
|
284
|
+
this.config.schemaPath = null;
|
|
285
|
+
return { success: true };
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
async setInputLanguage(lang) {
|
|
289
|
+
const valid = validateLanguageCode(lang);
|
|
290
|
+
if (!valid) {
|
|
291
|
+
return {
|
|
292
|
+
success: false,
|
|
293
|
+
error: `Input language "${lang}" is not supported by this runtime.\n\nSupported: ${this.capabilities?.supportedInputLanguages?.join(', ') || 'en'}`
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
this.config.expectedInputLanguages = [valid];
|
|
297
|
+
return { success: true, language: valid };
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
async setOutputLanguage(lang) {
|
|
301
|
+
const valid = validateLanguageCode(lang);
|
|
302
|
+
if (!valid) {
|
|
303
|
+
return {
|
|
304
|
+
success: false,
|
|
305
|
+
error: `Output language "${lang}" is not supported by this runtime.\n\nSupported: ${this.capabilities?.supportedOutputLanguages?.join(', ') || 'en'}`
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
this.config.expectedOutputLanguages = [valid];
|
|
309
|
+
return { success: true, language: valid };
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
async clearConversation() {
|
|
313
|
+
this.history.clear();
|
|
314
|
+
if (this.bridge && this.bridge.isConnected()) {
|
|
315
|
+
await this.bridge.evaluate(`(() => {
|
|
316
|
+
if (window.__nanobridge_chat_session && typeof window.__nanobridge_chat_session.destroy === 'function') {
|
|
317
|
+
try { window.__nanobridge_chat_session.destroy(); } catch (_) {}
|
|
318
|
+
}
|
|
319
|
+
window.__nanobridge_chat_session = null;
|
|
320
|
+
window.__nanobridge_chat_session_config = null;
|
|
321
|
+
})()`).catch(() => {});
|
|
322
|
+
}
|
|
323
|
+
return { success: true };
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
async resetAll() {
|
|
327
|
+
this.config = createDefaultChatConfig();
|
|
328
|
+
this.history.clear();
|
|
329
|
+
if (this.bridge && this.bridge.isConnected()) {
|
|
330
|
+
await this.bridge.evaluate(`(() => {
|
|
331
|
+
if (window.__nanobridge_chat_session && typeof window.__nanobridge_chat_session.destroy === 'function') {
|
|
332
|
+
try { window.__nanobridge_chat_session.destroy(); } catch (_) {}
|
|
333
|
+
}
|
|
334
|
+
window.__nanobridge_chat_session = null;
|
|
335
|
+
window.__nanobridge_chat_session_config = null;
|
|
336
|
+
})()`).catch(() => {});
|
|
337
|
+
}
|
|
338
|
+
return { success: true };
|
|
339
|
+
}
|
|
340
|
+
}
|
package/src/chrome/bridge.js
CHANGED
|
@@ -29,9 +29,15 @@ export class ChromeBridge {
|
|
|
29
29
|
const res = await fetch(`http://127.0.0.1:${cdpPort}/json/list`);
|
|
30
30
|
pages = await res.json();
|
|
31
31
|
debug('bridge', `Target search attempt ${i + 1}: found ${pages.length} targets`);
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
32
|
+
// Prioritize localhost / 127.0.0.1 secure origin over about:blank
|
|
33
|
+
const localhostTarget = pages.find((p) => p.type === 'page' && (p.url.includes('localhost') || p.url.includes('127.0.0.1')));
|
|
34
|
+
if (localhostTarget) {
|
|
35
|
+
this.pageTarget = localhostTarget;
|
|
36
|
+
break;
|
|
37
|
+
}
|
|
38
|
+
const anyPage = pages.find((p) => p.type === 'page');
|
|
39
|
+
if (anyPage && i >= 10) {
|
|
40
|
+
this.pageTarget = anyPage;
|
|
35
41
|
break;
|
|
36
42
|
}
|
|
37
43
|
} catch {
|
|
@@ -41,7 +47,7 @@ export class ChromeBridge {
|
|
|
41
47
|
}
|
|
42
48
|
|
|
43
49
|
if (!this.pageTarget) {
|
|
44
|
-
this.pageTarget = pages.find((p) => p.type === 'page') || pages[0];
|
|
50
|
+
this.pageTarget = pages.find((p) => p.type === 'page' && (p.url.includes('localhost') || p.url.includes('127.0.0.1'))) || pages.find((p) => p.type === 'page') || pages[0];
|
|
45
51
|
}
|
|
46
52
|
|
|
47
53
|
debug('bridge', 'Selected target:', JSON.stringify(this.pageTarget));
|
|
@@ -84,6 +90,10 @@ export class ChromeBridge {
|
|
|
84
90
|
resolve(parsed.result);
|
|
85
91
|
}
|
|
86
92
|
} else if (parsed.method === 'Runtime.consoleAPICalled') {
|
|
93
|
+
for (const [, cb] of this.pendingCallbacks) {
|
|
94
|
+
if (typeof cb.touch === 'function') cb.touch();
|
|
95
|
+
}
|
|
96
|
+
debug('bridge:console', parsed.params?.type, JSON.stringify(parsed.params?.args?.map((a) => a.value)));
|
|
87
97
|
const firstArg = parsed.params?.args?.[0]?.value || '';
|
|
88
98
|
if (typeof firstArg === 'string') {
|
|
89
99
|
for (const [prefix, handler] of this.consoleHandlers) {
|
|
@@ -100,6 +110,13 @@ export class ChromeBridge {
|
|
|
100
110
|
|
|
101
111
|
debug('bridge', 'CDP WebSocket connected. Enabling Runtime...');
|
|
102
112
|
await this.send('Runtime.enable');
|
|
113
|
+
if (pageUrl && (!this.pageTarget.url || this.pageTarget.url === 'about:blank' || !this.pageTarget.url.includes('localhost'))) {
|
|
114
|
+
try {
|
|
115
|
+
await this.send('Page.enable');
|
|
116
|
+
await this.send('Page.navigate', { url: pageUrl });
|
|
117
|
+
await new Promise((r) => setTimeout(r, 300));
|
|
118
|
+
} catch (_) {}
|
|
119
|
+
}
|
|
103
120
|
debug('bridge', 'Runtime enabled successfully.');
|
|
104
121
|
}
|
|
105
122
|
|
|
@@ -107,28 +124,39 @@ export class ChromeBridge {
|
|
|
107
124
|
return Boolean(this.ws && this.ws.readyState === WebSocket.OPEN);
|
|
108
125
|
}
|
|
109
126
|
|
|
110
|
-
send(method, params = {}) {
|
|
127
|
+
send(method, params = {}, options = {}) {
|
|
111
128
|
return new Promise((resolve, reject) => {
|
|
112
129
|
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
|
|
113
130
|
return reject(new Error('CDP WebSocket is closed or not connected'));
|
|
114
131
|
}
|
|
115
132
|
const id = this.msgId++;
|
|
116
|
-
const
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
133
|
+
const timeoutMs = options.timeout ?? 180000;
|
|
134
|
+
let timer = null;
|
|
135
|
+
|
|
136
|
+
const armTimer = () => {
|
|
137
|
+
if (timer) clearTimeout(timer);
|
|
138
|
+
if (timeoutMs > 0) {
|
|
139
|
+
timer = setTimeout(() => {
|
|
140
|
+
if (this.pendingCallbacks.has(id)) {
|
|
141
|
+
this.pendingCallbacks.delete(id);
|
|
142
|
+
reject(new Error(`CDP command timed out: ${method}`));
|
|
143
|
+
}
|
|
144
|
+
}, timeoutMs);
|
|
145
|
+
if (timer.unref) timer.unref();
|
|
120
146
|
}
|
|
121
|
-
}
|
|
122
|
-
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
armTimer();
|
|
123
150
|
|
|
124
151
|
this.pendingCallbacks.set(id, {
|
|
125
|
-
resolve: (val) => { clearTimeout(timer); resolve(val); },
|
|
126
|
-
reject: (err) => { clearTimeout(timer); reject(err); }
|
|
152
|
+
resolve: (val) => { if (timer) clearTimeout(timer); resolve(val); },
|
|
153
|
+
reject: (err) => { if (timer) clearTimeout(timer); reject(err); },
|
|
154
|
+
touch: () => armTimer()
|
|
127
155
|
});
|
|
128
156
|
|
|
129
157
|
this.ws.send(JSON.stringify({ id, method, params }), (err) => {
|
|
130
158
|
if (err) {
|
|
131
|
-
clearTimeout(timer);
|
|
159
|
+
if (timer) clearTimeout(timer);
|
|
132
160
|
this.pendingCallbacks.delete(id);
|
|
133
161
|
reject(err);
|
|
134
162
|
}
|
|
@@ -150,7 +178,7 @@ export class ChromeBridge {
|
|
|
150
178
|
awaitPromise: options.awaitPromise ?? true,
|
|
151
179
|
returnByValue: options.returnByValue ?? true,
|
|
152
180
|
userGesture: options.userGesture ?? true
|
|
153
|
-
});
|
|
181
|
+
}, { timeout: options.timeout });
|
|
154
182
|
|
|
155
183
|
if (res.exceptionDetails) {
|
|
156
184
|
const desc = res.exceptionDetails.exception?.description || res.exceptionDetails.text;
|
|
@@ -237,7 +265,7 @@ export class ChromeBridge {
|
|
|
237
265
|
} catch (e) {
|
|
238
266
|
return { success: false, error: e.message, stack: e.stack };
|
|
239
267
|
}
|
|
240
|
-
})()`, { userGesture: true });
|
|
268
|
+
})()`, { userGesture: true, timeout: 900000 });
|
|
241
269
|
|
|
242
270
|
if (!evalResult.success) {
|
|
243
271
|
throw new NanoBridgeError(`Failed to prepare/download model: ${evalResult.error}`);
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { debug } from '../utils/output.js';
|
|
2
|
+
|
|
3
|
+
export const SAMPLING_MODES = [
|
|
4
|
+
'most-predictable',
|
|
5
|
+
'predictable',
|
|
6
|
+
'slightly-predictable',
|
|
7
|
+
'balanced',
|
|
8
|
+
'slightly-creative',
|
|
9
|
+
'creative',
|
|
10
|
+
'most-creative'
|
|
11
|
+
];
|
|
12
|
+
|
|
13
|
+
export const DEFAULT_CAPABILITIES = {
|
|
14
|
+
builtInAi: false,
|
|
15
|
+
languageModel: false,
|
|
16
|
+
samplingMode: false,
|
|
17
|
+
temperature: false,
|
|
18
|
+
topK: false,
|
|
19
|
+
initialPrompts: true,
|
|
20
|
+
responseConstraint: true,
|
|
21
|
+
contextUsage: true,
|
|
22
|
+
contextWindow: true,
|
|
23
|
+
contextOverflowEvent: true,
|
|
24
|
+
supportedSamplingModes: [...SAMPLING_MODES],
|
|
25
|
+
supportedInputLanguages: ['en', 'es', 'ja', 'de', 'fr'],
|
|
26
|
+
supportedOutputLanguages: ['en', 'es', 'ja', 'de', 'fr']
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Fast, non-blocking capability detection via prototype and static properties.
|
|
31
|
+
* Executes in <1ms without cold model instantiation overhead.
|
|
32
|
+
*
|
|
33
|
+
* @param {object} bridge - Connected ChromeBridge instance
|
|
34
|
+
* @returns {Promise<object>} Capabilities object
|
|
35
|
+
*/
|
|
36
|
+
export async function detectCapabilities(bridge) {
|
|
37
|
+
if (!bridge || !bridge.isConnected()) {
|
|
38
|
+
return { ...DEFAULT_CAPABILITIES };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
debug('capabilities', 'Detecting Prompt API capabilities via prototype inspection...');
|
|
42
|
+
|
|
43
|
+
try {
|
|
44
|
+
const raw = await bridge.evaluate(`(() => {
|
|
45
|
+
const hasLM = typeof window !== 'undefined' && 'LanguageModel' in window;
|
|
46
|
+
if (!hasLM) {
|
|
47
|
+
return {
|
|
48
|
+
builtInAi: false,
|
|
49
|
+
languageModel: false,
|
|
50
|
+
samplingMode: false,
|
|
51
|
+
temperature: false,
|
|
52
|
+
topK: false,
|
|
53
|
+
initialPrompts: false,
|
|
54
|
+
responseConstraint: false,
|
|
55
|
+
contextUsage: false,
|
|
56
|
+
contextWindow: false,
|
|
57
|
+
contextOverflowEvent: false
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const proto = window.LanguageModel.prototype || {};
|
|
62
|
+
const propNames = Object.getOwnPropertyNames(proto);
|
|
63
|
+
|
|
64
|
+
const contextUsage = propNames.includes('contextUsage');
|
|
65
|
+
const contextWindow = propNames.includes('contextWindow');
|
|
66
|
+
const contextOverflowEvent = propNames.includes('oncontextoverflow');
|
|
67
|
+
const samplingMode = propNames.includes('samplingMode');
|
|
68
|
+
const temperature = propNames.includes('temperature');
|
|
69
|
+
const topK = propNames.includes('topK');
|
|
70
|
+
|
|
71
|
+
return {
|
|
72
|
+
builtInAi: true,
|
|
73
|
+
languageModel: true,
|
|
74
|
+
samplingMode,
|
|
75
|
+
temperature,
|
|
76
|
+
topK,
|
|
77
|
+
initialPrompts: true,
|
|
78
|
+
responseConstraint: true,
|
|
79
|
+
contextUsage,
|
|
80
|
+
contextWindow,
|
|
81
|
+
contextOverflowEvent
|
|
82
|
+
};
|
|
83
|
+
})()`, { userGesture: true });
|
|
84
|
+
|
|
85
|
+
const caps = {
|
|
86
|
+
...DEFAULT_CAPABILITIES,
|
|
87
|
+
...raw,
|
|
88
|
+
supportedSamplingModes: raw.samplingMode ? [...SAMPLING_MODES] : [],
|
|
89
|
+
supportedInputLanguages: ['en', 'es', 'ja', 'de', 'fr'],
|
|
90
|
+
supportedOutputLanguages: ['en', 'es', 'ja', 'de', 'fr']
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
debug('capabilities', 'Detection completed:', JSON.stringify(caps));
|
|
94
|
+
return caps;
|
|
95
|
+
} catch (err) {
|
|
96
|
+
debug('capabilities', 'Detection error, using safe defaults:', err.message);
|
|
97
|
+
return { ...DEFAULT_CAPABILITIES, builtInAi: true, languageModel: true };
|
|
98
|
+
}
|
|
99
|
+
}
|
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) => {
|
|
@@ -37,13 +37,40 @@ export async function launchChrome(options = {}) {
|
|
|
37
37
|
const pageUrl = `http://localhost:${serverPort}/`;
|
|
38
38
|
debug('launch', 'Ephemeral host server listening at:', pageUrl);
|
|
39
39
|
|
|
40
|
-
// 2.
|
|
41
|
-
const
|
|
42
|
-
|
|
40
|
+
// 2. Setup user-data-dir (persistent by default to preserve GPU shader & Metal pipeline caches)
|
|
41
|
+
const defaultProfileDir = path.join(os.homedir(), '.nanobridge', 'profile');
|
|
42
|
+
const lockPath = path.join(defaultProfileDir, 'SingletonLock');
|
|
43
|
+
let isLocked = false;
|
|
44
|
+
|
|
45
|
+
if (!options.userDataDir && !options.isolated) {
|
|
46
|
+
try {
|
|
47
|
+
const linkTarget = fs.readlinkSync(lockPath);
|
|
48
|
+
const pidMatch = linkTarget.match(/-(\d+)$/);
|
|
49
|
+
if (pidMatch && pidMatch[1]) {
|
|
50
|
+
try {
|
|
51
|
+
process.kill(Number(pidMatch[1]), 0);
|
|
52
|
+
isLocked = true;
|
|
53
|
+
debug('launch', `Default profile is locked by running Chrome PID ${pidMatch[1]}. Using isolated profile.`);
|
|
54
|
+
} catch (_) {
|
|
55
|
+
try { fs.unlinkSync(lockPath); } catch (_) {}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
} catch (_) {}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const isTemporary = Boolean(options.isolated || isLocked);
|
|
62
|
+
const userDataDir = options.userDataDir || (isTemporary
|
|
63
|
+
? fs.mkdtempSync(path.join(os.tmpdir(), 'nanobridge-'))
|
|
64
|
+
: defaultProfileDir);
|
|
65
|
+
|
|
66
|
+
if (!fs.existsSync(userDataDir)) {
|
|
67
|
+
fs.mkdirSync(userDataDir, { recursive: true });
|
|
68
|
+
}
|
|
69
|
+
debug('launch', 'Chrome user-data-dir at:', userDataDir, `(persistent: ${!isTemporary})`);
|
|
43
70
|
|
|
44
71
|
// Symlink system model directory into the profile so model is immediately available
|
|
45
72
|
const systemModelDir = findSystemModelDir();
|
|
46
|
-
const profileModelDir = path.join(
|
|
73
|
+
const profileModelDir = path.join(userDataDir, 'OptGuideOnDeviceModel');
|
|
47
74
|
if (systemModelDir && !fs.existsSync(profileModelDir)) {
|
|
48
75
|
try {
|
|
49
76
|
fs.symlinkSync(systemModelDir, profileModelDir, 'dir');
|
|
@@ -57,7 +84,7 @@ export async function launchChrome(options = {}) {
|
|
|
57
84
|
const isDarwin = process.platform === 'darwin';
|
|
58
85
|
const chromeArgs = [
|
|
59
86
|
'--headless=new',
|
|
60
|
-
`--user-data-dir=${
|
|
87
|
+
`--user-data-dir=${userDataDir}`,
|
|
61
88
|
'--remote-debugging-port=0',
|
|
62
89
|
'--no-first-run',
|
|
63
90
|
'--no-default-browser-check',
|
|
@@ -77,7 +104,7 @@ export async function launchChrome(options = {}) {
|
|
|
77
104
|
'--disable-popup-blocking',
|
|
78
105
|
'--disable-prompt-on-repost',
|
|
79
106
|
'--disable-hang-monitor',
|
|
80
|
-
'--disable-dev-shm-usage',
|
|
107
|
+
...(isDarwin ? [] : ['--disable-dev-shm-usage']),
|
|
81
108
|
'--password-store=basic',
|
|
82
109
|
'--use-mock-keychain',
|
|
83
110
|
'--disable-background-timer-throttling',
|
|
@@ -87,8 +114,9 @@ export async function launchChrome(options = {}) {
|
|
|
87
114
|
'--ignore-gpu-blocklist',
|
|
88
115
|
'--enable-gpu-rasterization',
|
|
89
116
|
'--enable-zero-copy',
|
|
90
|
-
...(isDarwin ? ['--use-angle=metal'
|
|
91
|
-
'--
|
|
117
|
+
...(isDarwin ? ['--use-angle=metal'] : []),
|
|
118
|
+
'--window-size=1280,800',
|
|
119
|
+
'--enable-blink-features=AIPromptAPI',
|
|
92
120
|
'--enable-features=PromptAPIForGeminiNano,OptimizationGuideOnDeviceModel',
|
|
93
121
|
'--optimization-guide-on-device-model-override-switch=bypass-ram-check',
|
|
94
122
|
...(options.extraArgs || []),
|
|
@@ -123,9 +151,9 @@ export async function launchChrome(options = {}) {
|
|
|
123
151
|
}
|
|
124
152
|
} catch (_) {}
|
|
125
153
|
|
|
126
|
-
if (
|
|
154
|
+
if (isTemporary && userDataDir && !isWindows) {
|
|
127
155
|
try {
|
|
128
|
-
execSync(`pkill -9 -f "${
|
|
156
|
+
execSync(`pkill -9 -f "${userDataDir}"`, { stdio: 'ignore' });
|
|
129
157
|
} catch (_) {}
|
|
130
158
|
}
|
|
131
159
|
|
|
@@ -133,10 +161,12 @@ export async function launchChrome(options = {}) {
|
|
|
133
161
|
server.close();
|
|
134
162
|
} catch (_) {}
|
|
135
163
|
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
164
|
+
if (isTemporary) {
|
|
165
|
+
try {
|
|
166
|
+
fs.rmSync(userDataDir, { recursive: true, force: true });
|
|
167
|
+
debug('launch', 'Cleaned up temporary user-data-dir:', userDataDir);
|
|
168
|
+
} catch (_) {}
|
|
169
|
+
}
|
|
140
170
|
};
|
|
141
171
|
|
|
142
172
|
const signalHandler = () => {
|
|
@@ -198,7 +228,8 @@ export async function launchChrome(options = {}) {
|
|
|
198
228
|
pageUrl,
|
|
199
229
|
executablePath,
|
|
200
230
|
version,
|
|
201
|
-
|
|
231
|
+
userDataDir,
|
|
232
|
+
tmpDir: userDataDir,
|
|
202
233
|
startupMs,
|
|
203
234
|
close: () => {
|
|
204
235
|
process.removeListener('SIGINT', signalHandler);
|