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/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
|
|
|
@@ -113,22 +130,28 @@ export class ChromeBridge {
|
|
|
113
130
|
return reject(new Error('CDP WebSocket is closed or not connected'));
|
|
114
131
|
}
|
|
115
132
|
const id = this.msgId++;
|
|
116
|
-
const timeoutMs = options.timeout ??
|
|
133
|
+
const timeoutMs = options.timeout ?? 180000;
|
|
117
134
|
let timer = null;
|
|
118
135
|
|
|
119
|
-
|
|
120
|
-
timer
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
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();
|
|
146
|
+
}
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
armTimer();
|
|
128
150
|
|
|
129
151
|
this.pendingCallbacks.set(id, {
|
|
130
152
|
resolve: (val) => { if (timer) clearTimeout(timer); resolve(val); },
|
|
131
|
-
reject: (err) => { if (timer) clearTimeout(timer); reject(err); }
|
|
153
|
+
reject: (err) => { if (timer) clearTimeout(timer); reject(err); },
|
|
154
|
+
touch: () => armTimer()
|
|
132
155
|
});
|
|
133
156
|
|
|
134
157
|
this.ws.send(JSON.stringify({ id, method, params }), (err) => {
|
|
@@ -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
|
@@ -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',
|
|
@@ -87,7 +114,8 @@ 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'
|
|
117
|
+
...(isDarwin ? ['--use-angle=metal'] : []),
|
|
118
|
+
'--window-size=1280,800',
|
|
91
119
|
'--enable-blink-features=AIPromptAPI',
|
|
92
120
|
'--enable-features=PromptAPIForGeminiNano,OptimizationGuideOnDeviceModel',
|
|
93
121
|
'--optimization-guide-on-device-model-override-switch=bypass-ram-check',
|
|
@@ -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);
|