nanobridge 0.2.3 → 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 -179
- package/src/commands/bench.js +0 -79
- package/src/commands/chat.js +0 -416
- 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 -59
- 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/benchmark/stats.js
DELETED
|
@@ -1,33 +0,0 @@
|
|
|
1
|
-
export function calculatePercentile(values, p) {
|
|
2
|
-
if (!values || values.length === 0) return 0;
|
|
3
|
-
const sorted = [...values].sort((a, b) => a - b);
|
|
4
|
-
if (sorted.length === 1) return sorted[0];
|
|
5
|
-
const index = (p / 100) * (sorted.length - 1);
|
|
6
|
-
const lower = Math.floor(index);
|
|
7
|
-
const upper = Math.ceil(index);
|
|
8
|
-
const weight = index - lower;
|
|
9
|
-
return sorted[lower] * (1 - weight) + sorted[upper] * weight;
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
export function computeMetricStats(values) {
|
|
13
|
-
const valid = (values || []).filter((v) => typeof v === 'number' && !isNaN(v));
|
|
14
|
-
if (valid.length === 0) {
|
|
15
|
-
return { min: 0, max: 0, avg: 0, p50: 0, p95: 0, count: 0 };
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
const sum = valid.reduce((acc, v) => acc + v, 0);
|
|
19
|
-
const avg = sum / valid.length;
|
|
20
|
-
const min = Math.min(...valid);
|
|
21
|
-
const max = Math.max(...valid);
|
|
22
|
-
const p50 = calculatePercentile(valid, 50);
|
|
23
|
-
const p95 = calculatePercentile(valid, 95);
|
|
24
|
-
|
|
25
|
-
return {
|
|
26
|
-
min: Number(min.toFixed(1)),
|
|
27
|
-
max: Number(max.toFixed(1)),
|
|
28
|
-
avg: Number(avg.toFixed(1)),
|
|
29
|
-
p50: Number(p50.toFixed(1)),
|
|
30
|
-
p95: Number(p95.toFixed(1)),
|
|
31
|
-
count: valid.length
|
|
32
|
-
};
|
|
33
|
-
}
|
package/src/chat/commands.js
DELETED
|
@@ -1,68 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Pure slash command parser for interactive chat mode.
|
|
3
|
-
*
|
|
4
|
-
* @param {string} line - Raw input line from terminal
|
|
5
|
-
* @returns {object} Parsed command description
|
|
6
|
-
*/
|
|
7
|
-
export function parseCommand(line) {
|
|
8
|
-
if (!line || typeof line !== 'string') {
|
|
9
|
-
return { isCommand: false };
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
const trimmed = line.trim();
|
|
13
|
-
if (!trimmed.startsWith('/')) {
|
|
14
|
-
// Check for direct exit aliases
|
|
15
|
-
const lower = trimmed.toLowerCase();
|
|
16
|
-
if (lower === 'exit' || lower === 'quit') {
|
|
17
|
-
return { isCommand: true, command: lower, value: '', raw: trimmed };
|
|
18
|
-
}
|
|
19
|
-
return { isCommand: false };
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
const parts = trimmed.slice(1).trim().split(/\s+/);
|
|
23
|
-
const command = (parts[0] || '').toLowerCase();
|
|
24
|
-
const value = trimmed.slice(command.length + 1).trim();
|
|
25
|
-
|
|
26
|
-
return {
|
|
27
|
-
isCommand: true,
|
|
28
|
-
command,
|
|
29
|
-
value,
|
|
30
|
-
args: parts.slice(1),
|
|
31
|
-
raw: trimmed
|
|
32
|
-
};
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
/**
|
|
36
|
-
* Generate formatted help text reflecting runtime capabilities.
|
|
37
|
-
*
|
|
38
|
-
* @param {object} capabilities - Runtime capabilities object
|
|
39
|
-
* @returns {string}
|
|
40
|
-
*/
|
|
41
|
-
export function formatChatHelp(capabilities = {}) {
|
|
42
|
-
const lines = [
|
|
43
|
-
'NanoBridge Chat Commands',
|
|
44
|
-
'',
|
|
45
|
-
' /sampling <mode> Change sampling mode (e.g. creative, predictable, balanced)',
|
|
46
|
-
' /system <prompt> Set or update system prompt (recreates session & preserves history)',
|
|
47
|
-
' /json on|off Toggle structured JSON output constraint',
|
|
48
|
-
' /schema <file> Load JSON schema file (/schema clear to remove)',
|
|
49
|
-
' /context Show context window usage and token count',
|
|
50
|
-
' /settings Show current configuration and capabilities',
|
|
51
|
-
' /continue, /c Continue previous generation if cut off by token limit',
|
|
52
|
-
' /clear Clear conversation history (keeps config & sampling)',
|
|
53
|
-
' /new Start a fresh session with default configuration',
|
|
54
|
-
' /history Show turn history',
|
|
55
|
-
' /read <filepath> Load local file content into conversation context',
|
|
56
|
-
' /help Show available commands',
|
|
57
|
-
' /exit Exit chat session'
|
|
58
|
-
];
|
|
59
|
-
|
|
60
|
-
if (capabilities.temperature) {
|
|
61
|
-
lines.splice(2, 0, ' /temperature <n> Set generation temperature (0.0 - 2.0)');
|
|
62
|
-
}
|
|
63
|
-
if (capabilities.topK) {
|
|
64
|
-
lines.splice(3, 0, ' /topk <n> Set top-K sampling parameter');
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
return lines.join('\n');
|
|
68
|
-
}
|
package/src/chat/config.js
DELETED
|
@@ -1,65 +0,0 @@
|
|
|
1
|
-
import fs from 'node:fs';
|
|
2
|
-
import path from 'node:path';
|
|
3
|
-
import { SAMPLING_MODES } from '../chrome/capabilities.js';
|
|
4
|
-
|
|
5
|
-
export function createDefaultChatConfig(overrides = {}) {
|
|
6
|
-
return {
|
|
7
|
-
samplingMode: 'balanced',
|
|
8
|
-
systemPrompt: null,
|
|
9
|
-
temperature: null,
|
|
10
|
-
topK: null,
|
|
11
|
-
jsonMode: false,
|
|
12
|
-
responseSchema: null,
|
|
13
|
-
schemaPath: null,
|
|
14
|
-
expectedInputLanguages: ['en'],
|
|
15
|
-
expectedOutputLanguages: ['en'],
|
|
16
|
-
...overrides
|
|
17
|
-
};
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
export function validateSamplingMode(mode, supportedModes = SAMPLING_MODES) {
|
|
21
|
-
if (!mode || typeof mode !== 'string') return false;
|
|
22
|
-
const normalized = mode.trim().toLowerCase();
|
|
23
|
-
return supportedModes.includes(normalized) ? normalized : null;
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
export function validateLanguageCode(code) {
|
|
27
|
-
if (!code || typeof code !== 'string') return null;
|
|
28
|
-
const clean = code.trim().toLowerCase();
|
|
29
|
-
// Valid BCP-47 / 2-letter ISO language codes
|
|
30
|
-
if (/^[a-z]{2,3}(-[a-z0-9]+)?$/i.test(clean)) {
|
|
31
|
-
return clean;
|
|
32
|
-
}
|
|
33
|
-
return null;
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
export function loadAndValidateJsonSchema(filePath) {
|
|
37
|
-
const resolved = path.resolve(process.cwd(), filePath);
|
|
38
|
-
if (!fs.existsSync(resolved)) {
|
|
39
|
-
throw new Error(`Schema file not found at: ${filePath}`);
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
let content;
|
|
43
|
-
try {
|
|
44
|
-
content = fs.readFileSync(resolved, 'utf8');
|
|
45
|
-
} catch (err) {
|
|
46
|
-
throw new Error(`Failed to read schema file: ${err.message}`);
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
let parsed;
|
|
50
|
-
try {
|
|
51
|
-
parsed = JSON.parse(content);
|
|
52
|
-
} catch (err) {
|
|
53
|
-
throw new Error(`Invalid JSON in schema file: ${err.message}`);
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
57
|
-
throw new Error('Schema must be a valid JSON Object with a "type" definition');
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
return {
|
|
61
|
-
schema: parsed,
|
|
62
|
-
resolvedPath: resolved,
|
|
63
|
-
relativePath: path.relative(process.cwd(), resolved) || path.basename(resolved)
|
|
64
|
-
};
|
|
65
|
-
}
|
package/src/chat/history.js
DELETED
|
@@ -1,103 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* ConversationHistory maintains turn-by-turn chat history independently
|
|
3
|
-
* from Chrome's internal session context.
|
|
4
|
-
*/
|
|
5
|
-
export class ConversationHistory {
|
|
6
|
-
constructor(initialTurns = []) {
|
|
7
|
-
this.turns = [];
|
|
8
|
-
if (Array.isArray(initialTurns)) {
|
|
9
|
-
for (const turn of initialTurns) {
|
|
10
|
-
this.addTurn(turn.role, turn.content);
|
|
11
|
-
}
|
|
12
|
-
}
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
addTurn(role, content) {
|
|
16
|
-
if (!role || !content) return;
|
|
17
|
-
const cleanRole = role.toLowerCase() === 'system' ? 'system' : (role.toLowerCase() === 'assistant' ? 'assistant' : 'user');
|
|
18
|
-
this.turns.push({
|
|
19
|
-
role: cleanRole,
|
|
20
|
-
content: String(content)
|
|
21
|
-
});
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
getMessages() {
|
|
25
|
-
return [...this.turns];
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
get length() {
|
|
29
|
-
return this.turns.length;
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
clear() {
|
|
33
|
-
this.turns = [];
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
/**
|
|
37
|
-
* Format history into valid initialPrompts array for LanguageModel.create().
|
|
38
|
-
* Ensures strict role ordering: optional system prompt first, then alternating user/assistant turns.
|
|
39
|
-
*
|
|
40
|
-
* @param {string|null} systemPrompt
|
|
41
|
-
* @returns {Array<{role: string, content: string}>}
|
|
42
|
-
*/
|
|
43
|
-
formatInitialPrompts(systemPrompt = null) {
|
|
44
|
-
const prompts = [];
|
|
45
|
-
if (systemPrompt && typeof systemPrompt === 'string' && systemPrompt.trim()) {
|
|
46
|
-
prompts.push({
|
|
47
|
-
role: 'system',
|
|
48
|
-
content: systemPrompt.trim()
|
|
49
|
-
});
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
let expectedRole = 'user';
|
|
53
|
-
for (const turn of this.turns) {
|
|
54
|
-
if (turn.role === 'system') continue; // system prompt handled at head
|
|
55
|
-
if (turn.role === expectedRole) {
|
|
56
|
-
prompts.push({ role: turn.role, content: turn.content });
|
|
57
|
-
expectedRole = expectedRole === 'user' ? 'assistant' : 'user';
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
// Must end with an assistant message or be clean pairs
|
|
62
|
-
if (prompts.length > 0 && prompts[prompts.length - 1].role === 'user' && prompts.length > 1) {
|
|
63
|
-
// Drop incomplete trailing user turn from initialPrompts
|
|
64
|
-
prompts.pop();
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
return prompts;
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
/**
|
|
71
|
-
* Format as prompt text for string-based session or fallback execution.
|
|
72
|
-
*/
|
|
73
|
-
formatAsPromptText(systemPrompt = null) {
|
|
74
|
-
const lines = [];
|
|
75
|
-
if (systemPrompt && typeof systemPrompt === 'string' && systemPrompt.trim()) {
|
|
76
|
-
lines.push(`System: ${systemPrompt.trim()}`);
|
|
77
|
-
}
|
|
78
|
-
for (const turn of this.turns) {
|
|
79
|
-
const label = turn.role === 'user' ? 'User' : (turn.role === 'assistant' ? 'Assistant' : 'System');
|
|
80
|
-
lines.push(`${label}: ${turn.content}`);
|
|
81
|
-
}
|
|
82
|
-
return lines.join('\n\n');
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
/**
|
|
86
|
-
* Trim older turns while preserving recent turns and strict user/assistant pairing.
|
|
87
|
-
*
|
|
88
|
-
* @param {number} maxTurns - Maximum user/assistant turns to retain (e.g. 10)
|
|
89
|
-
*/
|
|
90
|
-
trimOlderTurns(maxTurns = 10) {
|
|
91
|
-
if (this.turns.length <= maxTurns) return;
|
|
92
|
-
|
|
93
|
-
// Filter non-system messages
|
|
94
|
-
const nonSystem = this.turns.filter((t) => t.role !== 'system');
|
|
95
|
-
const system = this.turns.filter((t) => t.role === 'system');
|
|
96
|
-
|
|
97
|
-
// Keep the most recent complete pairs
|
|
98
|
-
const excess = nonSystem.length - maxTurns;
|
|
99
|
-
const trimmedNonSystem = nonSystem.slice(excess % 2 === 0 ? excess : excess + 1);
|
|
100
|
-
|
|
101
|
-
this.turns = [...system, ...trimmedNonSystem];
|
|
102
|
-
}
|
|
103
|
-
}
|
package/src/chat/session.js
DELETED
|
@@ -1,337 +0,0 @@
|
|
|
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
|
-
|
|
142
|
-
for await (const chunk of stream) {
|
|
143
|
-
if (chunk) {
|
|
144
|
-
finalOutput += chunk;
|
|
145
|
-
console.debug('${prefix}' + JSON.stringify({ d: chunk }));
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
let usage = null;
|
|
150
|
-
let windowSize = null;
|
|
151
|
-
try {
|
|
152
|
-
usage = session.contextUsage;
|
|
153
|
-
windowSize = session.contextWindow;
|
|
154
|
-
} catch (_) {}
|
|
155
|
-
|
|
156
|
-
return {
|
|
157
|
-
success: true,
|
|
158
|
-
text: finalOutput,
|
|
159
|
-
contextUsage: usage,
|
|
160
|
-
contextWindow: windowSize
|
|
161
|
-
};
|
|
162
|
-
} catch (e) {
|
|
163
|
-
if (window.__nanobridge_chat_session && typeof window.__nanobridge_chat_session.destroy === 'function') {
|
|
164
|
-
try { window.__nanobridge_chat_session.destroy(); } catch (_) {}
|
|
165
|
-
}
|
|
166
|
-
window.__nanobridge_chat_session = null;
|
|
167
|
-
window.__nanobridge_chat_session_config = null;
|
|
168
|
-
return { success: false, error: e.message };
|
|
169
|
-
}
|
|
170
|
-
})()`, { userGesture: true, timeout: 180000 });
|
|
171
|
-
|
|
172
|
-
if (!evalRes.success) {
|
|
173
|
-
throw new Error(evalRes.error);
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
// Add user and assistant turns to history
|
|
177
|
-
this.history.addTurn('user', userPrompt);
|
|
178
|
-
this.history.addTurn('assistant', evalRes.text);
|
|
179
|
-
|
|
180
|
-
return evalRes.text;
|
|
181
|
-
} finally {
|
|
182
|
-
if (chunkHandler) this.bridge.removeConsoleHandler(prefix);
|
|
183
|
-
if (overflowHandler) this.bridge.removeConsoleHandler(overflowPrefix);
|
|
184
|
-
}
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
async getContextMetrics() {
|
|
188
|
-
return {
|
|
189
|
-
exposed: true,
|
|
190
|
-
used: this.history.length * 50, // estimated turn tokens
|
|
191
|
-
window: 9216,
|
|
192
|
-
percent: ((this.history.length * 50 / 9216) * 100).toFixed(1),
|
|
193
|
-
messagesCount: this.history.length
|
|
194
|
-
};
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
async setSamplingMode(mode) {
|
|
198
|
-
if (!this.capabilities?.samplingMode) {
|
|
199
|
-
return {
|
|
200
|
-
success: false,
|
|
201
|
-
error: 'Sampling mode is not supported by this Chrome runtime.'
|
|
202
|
-
};
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
const validMode = validateSamplingMode(mode, this.capabilities.supportedSamplingModes);
|
|
206
|
-
if (!validMode) {
|
|
207
|
-
return {
|
|
208
|
-
success: false,
|
|
209
|
-
error: `Invalid sampling mode: "${mode}". Valid modes: ${this.capabilities.supportedSamplingModes.join(', ')}`
|
|
210
|
-
};
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
this.config.samplingMode = validMode;
|
|
214
|
-
return { success: true, mode: validMode };
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
async setSystemPrompt(prompt) {
|
|
218
|
-
const cleanPrompt = prompt ? prompt.trim() : null;
|
|
219
|
-
this.config.systemPrompt = cleanPrompt;
|
|
220
|
-
return { success: true, systemPrompt: cleanPrompt };
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
async setTemperature(temp) {
|
|
224
|
-
if (!this.capabilities?.temperature) {
|
|
225
|
-
return {
|
|
226
|
-
success: false,
|
|
227
|
-
error: 'temperature is not available in this Chrome context.'
|
|
228
|
-
};
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
const num = Number(temp);
|
|
232
|
-
if (isNaN(num) || num < 0 || num > 2) {
|
|
233
|
-
return {
|
|
234
|
-
success: false,
|
|
235
|
-
error: 'Temperature must be a valid number between 0.0 and 2.0.'
|
|
236
|
-
};
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
this.config.temperature = num;
|
|
240
|
-
return { success: true, temperature: num };
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
async setTopK(val) {
|
|
244
|
-
if (!this.capabilities?.topK) {
|
|
245
|
-
return {
|
|
246
|
-
success: false,
|
|
247
|
-
error: 'topK is not available in this Chrome context.'
|
|
248
|
-
};
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
const num = parseInt(val, 10);
|
|
252
|
-
if (isNaN(num) || num < 1 || num > 128) {
|
|
253
|
-
return {
|
|
254
|
-
success: false,
|
|
255
|
-
error: 'topK must be an integer between 1 and 128.'
|
|
256
|
-
};
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
this.config.topK = num;
|
|
260
|
-
return { success: true, topK: num };
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
setJsonMode(enabled) {
|
|
264
|
-
this.config.jsonMode = Boolean(enabled);
|
|
265
|
-
if (!this.config.jsonMode) {
|
|
266
|
-
this.config.responseSchema = null;
|
|
267
|
-
this.config.schemaPath = null;
|
|
268
|
-
}
|
|
269
|
-
return { success: true, jsonMode: this.config.jsonMode };
|
|
270
|
-
}
|
|
271
|
-
|
|
272
|
-
setSchema(schema, filePath) {
|
|
273
|
-
this.config.responseSchema = schema;
|
|
274
|
-
this.config.schemaPath = filePath;
|
|
275
|
-
this.config.jsonMode = true;
|
|
276
|
-
return { success: true, schemaPath: filePath };
|
|
277
|
-
}
|
|
278
|
-
|
|
279
|
-
clearSchema() {
|
|
280
|
-
this.config.responseSchema = null;
|
|
281
|
-
this.config.schemaPath = null;
|
|
282
|
-
return { success: true };
|
|
283
|
-
}
|
|
284
|
-
|
|
285
|
-
async setInputLanguage(lang) {
|
|
286
|
-
const valid = validateLanguageCode(lang);
|
|
287
|
-
if (!valid) {
|
|
288
|
-
return {
|
|
289
|
-
success: false,
|
|
290
|
-
error: `Input language "${lang}" is not supported by this runtime.\n\nSupported: ${this.capabilities?.supportedInputLanguages?.join(', ') || 'en'}`
|
|
291
|
-
};
|
|
292
|
-
}
|
|
293
|
-
this.config.expectedInputLanguages = [valid];
|
|
294
|
-
return { success: true, language: valid };
|
|
295
|
-
}
|
|
296
|
-
|
|
297
|
-
async setOutputLanguage(lang) {
|
|
298
|
-
const valid = validateLanguageCode(lang);
|
|
299
|
-
if (!valid) {
|
|
300
|
-
return {
|
|
301
|
-
success: false,
|
|
302
|
-
error: `Output language "${lang}" is not supported by this runtime.\n\nSupported: ${this.capabilities?.supportedOutputLanguages?.join(', ') || 'en'}`
|
|
303
|
-
};
|
|
304
|
-
}
|
|
305
|
-
this.config.expectedOutputLanguages = [valid];
|
|
306
|
-
return { success: true, language: valid };
|
|
307
|
-
}
|
|
308
|
-
|
|
309
|
-
async clearConversation() {
|
|
310
|
-
this.history.clear();
|
|
311
|
-
if (this.bridge && this.bridge.isConnected()) {
|
|
312
|
-
await this.bridge.evaluate(`(() => {
|
|
313
|
-
if (window.__nanobridge_chat_session && typeof window.__nanobridge_chat_session.destroy === 'function') {
|
|
314
|
-
try { window.__nanobridge_chat_session.destroy(); } catch (_) {}
|
|
315
|
-
}
|
|
316
|
-
window.__nanobridge_chat_session = null;
|
|
317
|
-
window.__nanobridge_chat_session_config = null;
|
|
318
|
-
})()`).catch(() => {});
|
|
319
|
-
}
|
|
320
|
-
return { success: true };
|
|
321
|
-
}
|
|
322
|
-
|
|
323
|
-
async resetAll() {
|
|
324
|
-
this.config = createDefaultChatConfig();
|
|
325
|
-
this.history.clear();
|
|
326
|
-
if (this.bridge && this.bridge.isConnected()) {
|
|
327
|
-
await this.bridge.evaluate(`(() => {
|
|
328
|
-
if (window.__nanobridge_chat_session && typeof window.__nanobridge_chat_session.destroy === 'function') {
|
|
329
|
-
try { window.__nanobridge_chat_session.destroy(); } catch (_) {}
|
|
330
|
-
}
|
|
331
|
-
window.__nanobridge_chat_session = null;
|
|
332
|
-
window.__nanobridge_chat_session_config = null;
|
|
333
|
-
})()`).catch(() => {});
|
|
334
|
-
}
|
|
335
|
-
return { success: true };
|
|
336
|
-
}
|
|
337
|
-
}
|