nanobridge 0.2.4 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +86 -230
- package/bin/nanobridge.js +1 -1
- package/dist/api/openai.d.ts +135 -0
- package/dist/api/openai.js +210 -0
- package/dist/api/openai.js.map +1 -0
- package/dist/benchmark/runner.d.ts +27 -0
- package/dist/benchmark/runner.js +37 -0
- package/dist/benchmark/runner.js.map +1 -0
- package/dist/benchmark/stats.d.ts +10 -0
- package/dist/benchmark/stats.js +33 -0
- package/dist/benchmark/stats.js.map +1 -0
- package/dist/bin/nanobridge.d.ts +2 -0
- package/dist/bin/nanobridge.js +4 -0
- package/dist/bin/nanobridge.js.map +1 -0
- package/dist/chat/commands.d.ts +9 -0
- package/dist/chat/commands.js +52 -0
- package/dist/chat/commands.js.map +1 -0
- package/dist/chat/config.d.ts +22 -0
- package/dist/chat/config.js +55 -0
- package/dist/chat/config.js.map +1 -0
- package/dist/chat/history.d.ts +12 -0
- package/dist/chat/history.js +74 -0
- package/dist/chat/history.js.map +1 -0
- package/dist/chat/session.d.ts +42 -0
- package/dist/chat/session.js +107 -0
- package/dist/chat/session.js.map +1 -0
- package/dist/chat/storage.d.ts +17 -0
- package/dist/chat/storage.js +71 -0
- package/dist/chat/storage.js.map +1 -0
- package/dist/cli.d.ts +7 -0
- package/dist/cli.js +363 -0
- package/dist/cli.js.map +1 -0
- package/dist/commands/ask.d.ts +4 -0
- package/dist/commands/ask.js +288 -0
- package/dist/commands/ask.js.map +1 -0
- package/dist/commands/bench.d.ts +2 -0
- package/dist/commands/bench.js +92 -0
- package/dist/commands/bench.js.map +1 -0
- package/dist/commands/chat.d.ts +2 -0
- package/dist/commands/chat.js +701 -0
- package/dist/commands/chat.js.map +1 -0
- package/dist/commands/config.d.ts +2 -0
- package/dist/commands/config.js +102 -0
- package/dist/commands/config.js.map +1 -0
- package/dist/commands/daemon.d.ts +2 -0
- package/dist/commands/daemon.js +225 -0
- package/dist/commands/daemon.js.map +1 -0
- package/dist/commands/embed.d.ts +2 -0
- package/dist/commands/embed.js +79 -0
- package/dist/commands/embed.js.map +1 -0
- package/dist/commands/models.d.ts +5 -0
- package/dist/commands/models.js +244 -0
- package/dist/commands/models.js.map +1 -0
- package/dist/commands/serve.d.ts +2 -0
- package/dist/commands/serve.js +52 -0
- package/dist/commands/serve.js.map +1 -0
- package/dist/commands/status.d.ts +2 -0
- package/dist/commands/status.js +81 -0
- package/dist/commands/status.js.map +1 -0
- package/dist/daemon/client.d.ts +74 -0
- package/dist/daemon/client.js +447 -0
- package/dist/daemon/client.js.map +1 -0
- package/dist/daemon/server.d.ts +43 -0
- package/dist/daemon/server.js +661 -0
- package/dist/daemon/server.js.map +1 -0
- package/dist/daemon/service.d.ts +29 -0
- package/dist/daemon/service.js +173 -0
- package/dist/daemon/service.js.map +1 -0
- package/dist/daemon/state.d.ts +4 -0
- package/dist/daemon/state.js +54 -0
- package/dist/daemon/state.js.map +1 -0
- package/dist/engine/llama-engine.d.ts +49 -0
- package/dist/engine/llama-engine.js +465 -0
- package/dist/engine/llama-engine.js.map +1 -0
- package/dist/engine/model-pool.d.ts +36 -0
- package/dist/engine/model-pool.js +202 -0
- package/dist/engine/model-pool.js.map +1 -0
- package/dist/engine/sampling.d.ts +13 -0
- package/dist/engine/sampling.js +43 -0
- package/dist/engine/sampling.js.map +1 -0
- package/dist/models/catalog.d.ts +6 -0
- package/dist/models/catalog.js +124 -0
- package/dist/models/catalog.js.map +1 -0
- package/dist/models/config.d.ts +10 -0
- package/dist/models/config.js +141 -0
- package/dist/models/config.js.map +1 -0
- package/dist/models/downloader.d.ts +21 -0
- package/dist/models/downloader.js +98 -0
- package/dist/models/downloader.js.map +1 -0
- package/dist/models/profiles.d.ts +10 -0
- package/dist/models/profiles.js +68 -0
- package/dist/models/profiles.js.map +1 -0
- package/dist/models/store.d.ts +9 -0
- package/dist/models/store.js +142 -0
- package/dist/models/store.js.map +1 -0
- package/dist/types.d.ts +189 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/utils/errors.d.ts +18 -0
- package/dist/utils/errors.js +33 -0
- package/dist/utils/errors.js.map +1 -0
- package/dist/utils/files.d.ts +14 -0
- package/dist/utils/files.js +88 -0
- package/dist/utils/files.js.map +1 -0
- package/dist/utils/output.d.ts +29 -0
- package/dist/utils/output.js +116 -0
- package/dist/utils/output.js.map +1 -0
- package/package.json +28 -11
- package/examples/openai-client.js +0 -112
- package/examples/openai-sdk.js +0 -46
- package/examples/openai_python.py +0 -42
- package/src/api/openai.js +0 -115
- package/src/benchmark/runner.js +0 -48
- package/src/benchmark/stats.js +0 -33
- package/src/chat/commands.js +0 -68
- package/src/chat/config.js +0 -65
- package/src/chat/history.js +0 -103
- package/src/chat/session.js +0 -337
- package/src/chrome/bridge.js +0 -473
- package/src/chrome/capabilities.js +0 -99
- package/src/chrome/detect.js +0 -199
- package/src/chrome/launch.js +0 -248
- package/src/cli.js +0 -216
- package/src/commands/ask.js +0 -217
- package/src/commands/bench.js +0 -79
- package/src/commands/chat.js +0 -426
- package/src/commands/daemon.js +0 -89
- package/src/commands/download.js +0 -71
- package/src/commands/serve.js +0 -56
- package/src/commands/status.js +0 -87
- package/src/daemon/client.js +0 -274
- package/src/daemon/server.js +0 -650
- package/src/daemon/state.js +0 -46
- package/src/utils/errors.js +0 -26
- package/src/utils/files.js +0 -93
- package/src/utils/output.js +0 -107
- package/test/chat.test.js +0 -252
- package/test/cli.test.js +0 -49
- package/test/daemon.test.js +0 -31
- package/test/detect.test.js +0 -24
- package/test/files.test.js +0 -41
- package/test/openai.test.js +0 -63
- package/test/stats.test.js +0 -29
package/src/utils/errors.js
DELETED
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
export class NanoBridgeError extends Error {
|
|
2
|
-
constructor(message, exitCode = 1, details = null) {
|
|
3
|
-
super(message);
|
|
4
|
-
this.name = this.constructor.name;
|
|
5
|
-
this.exitCode = exitCode;
|
|
6
|
-
this.details = details;
|
|
7
|
-
}
|
|
8
|
-
}
|
|
9
|
-
|
|
10
|
-
export class ChromeUnavailableError extends NanoBridgeError {
|
|
11
|
-
constructor(message = 'Chrome executable not found or failed to launch', details = null) {
|
|
12
|
-
super(message, 2, details);
|
|
13
|
-
}
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
export class BuiltInAiUnavailableError extends NanoBridgeError {
|
|
17
|
-
constructor(message = 'Built-in AI / LanguageModel API is not exposed by this Chrome installation', details = null) {
|
|
18
|
-
super(message, 3, details);
|
|
19
|
-
}
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
export class ModelUnavailableError extends NanoBridgeError {
|
|
23
|
-
constructor(message = 'Chrome Built-in AI model is not ready.', details = null) {
|
|
24
|
-
super(message, 4, details);
|
|
25
|
-
}
|
|
26
|
-
}
|
package/src/utils/files.js
DELETED
|
@@ -1,93 +0,0 @@
|
|
|
1
|
-
import fs from 'node:fs';
|
|
2
|
-
import path from 'node:path';
|
|
3
|
-
import os from 'node:os';
|
|
4
|
-
|
|
5
|
-
const MAX_FILE_SIZE_BYTES = 500 * 1024; // 500 KB limit for on-device context
|
|
6
|
-
|
|
7
|
-
export function resolveFilePath(rawPath) {
|
|
8
|
-
if (!rawPath) return null;
|
|
9
|
-
let target = rawPath.trim();
|
|
10
|
-
if (target.startsWith('~')) {
|
|
11
|
-
target = path.join(os.homedir(), target.slice(1));
|
|
12
|
-
}
|
|
13
|
-
return path.resolve(process.cwd(), target);
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
export function readFileContent(rawPath) {
|
|
17
|
-
const fullPath = resolveFilePath(rawPath);
|
|
18
|
-
if (!fullPath || !fs.existsSync(fullPath)) {
|
|
19
|
-
throw new Error(`File not found: ${rawPath}`);
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
const stat = fs.statSync(fullPath);
|
|
23
|
-
if (stat.isDirectory()) {
|
|
24
|
-
throw new Error(`Path is a directory, not a file: ${rawPath}`);
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
if (stat.size > MAX_FILE_SIZE_BYTES) {
|
|
28
|
-
throw new Error(`File is too large (${Math.round(stat.size / 1024)} KB). On-device model limit is ${MAX_FILE_SIZE_BYTES / 1024} KB.`);
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
const content = fs.readFileSync(fullPath, 'utf8');
|
|
32
|
-
return {
|
|
33
|
-
path: fullPath,
|
|
34
|
-
relativePath: path.relative(process.cwd(), fullPath) || path.basename(fullPath),
|
|
35
|
-
filename: path.basename(fullPath),
|
|
36
|
-
content,
|
|
37
|
-
size: stat.size
|
|
38
|
-
};
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
export function formatFileAsContext(fileInfo) {
|
|
42
|
-
const ext = path.extname(fileInfo.filename).slice(1) || '';
|
|
43
|
-
return `--- File: ${fileInfo.relativePath} ---\n\`\`\`${ext}\n${fileInfo.content}\n\`\`\`\n--- End of File ---`;
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
/**
|
|
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
|
-
*/
|
|
50
|
-
export function extractAndAttachFiles(input) {
|
|
51
|
-
const attachedFiles = [];
|
|
52
|
-
let cleanedInput = input;
|
|
53
|
-
|
|
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) {
|
|
72
|
-
const candidatePath = match[1];
|
|
73
|
-
if (candidatePath.toLowerCase() === 'file') continue;
|
|
74
|
-
try {
|
|
75
|
-
const fileInfo = readFileContent(candidatePath);
|
|
76
|
-
if (!attachedFiles.some((f) => f.path === fileInfo.path)) {
|
|
77
|
-
attachedFiles.push(fileInfo);
|
|
78
|
-
}
|
|
79
|
-
cleanedInput = cleanedInput.replace(match[0], `[File: ${fileInfo.relativePath}]`);
|
|
80
|
-
} catch (_) {}
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
let finalPrompt = cleanedInput;
|
|
84
|
-
if (attachedFiles.length > 0) {
|
|
85
|
-
const filesContext = attachedFiles.map(formatFileAsContext).join('\n\n');
|
|
86
|
-
finalPrompt = `${filesContext}\n\n${cleanedInput}`;
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
return {
|
|
90
|
-
finalPrompt,
|
|
91
|
-
attachedFiles
|
|
92
|
-
};
|
|
93
|
-
}
|
package/src/utils/output.js
DELETED
|
@@ -1,107 +0,0 @@
|
|
|
1
|
-
import process from 'node:process';
|
|
2
|
-
|
|
3
|
-
let isJsonMode = false;
|
|
4
|
-
let isDebugMode = false;
|
|
5
|
-
|
|
6
|
-
export function setJsonMode(value) {
|
|
7
|
-
isJsonMode = !!value;
|
|
8
|
-
}
|
|
9
|
-
|
|
10
|
-
export function setDebugMode(value) {
|
|
11
|
-
isDebugMode = !!value;
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
export function shouldUseColors() {
|
|
15
|
-
if (isJsonMode) return false;
|
|
16
|
-
if (process.env.NO_COLOR !== undefined) return false;
|
|
17
|
-
return Boolean(process.stdout.isTTY);
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
const colors = {
|
|
21
|
-
reset: '\x1b[0m',
|
|
22
|
-
bold: '\x1b[1m',
|
|
23
|
-
dim: '\x1b[2m',
|
|
24
|
-
green: '\x1b[32m',
|
|
25
|
-
red: '\x1b[31m',
|
|
26
|
-
yellow: '\x1b[33m',
|
|
27
|
-
blue: '\x1b[34m',
|
|
28
|
-
cyan: '\x1b[36m',
|
|
29
|
-
gray: '\x1b[90m',
|
|
30
|
-
};
|
|
31
|
-
|
|
32
|
-
export function style(text, colorName) {
|
|
33
|
-
if (!shouldUseColors() || !colors[colorName]) return text;
|
|
34
|
-
return `${colors[colorName]}${text}${colors.reset}`;
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
export function debug(label, ...args) {
|
|
38
|
-
if (!isDebugMode) return;
|
|
39
|
-
const prefix = style(`[debug ${new Date().toISOString().slice(11, 23)}] [${label}]`, 'gray');
|
|
40
|
-
console.error(prefix, ...args);
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
export function log(...args) {
|
|
44
|
-
if (isJsonMode) return;
|
|
45
|
-
console.log(...args);
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
export function logError(...args) {
|
|
49
|
-
console.error(...args);
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
export function renderProgressBar(percent, length = 24) {
|
|
53
|
-
const clamped = Math.max(0, Math.min(100, percent));
|
|
54
|
-
const filledLength = Math.round((clamped / 100) * length);
|
|
55
|
-
const emptyLength = length - filledLength;
|
|
56
|
-
const filled = '█'.repeat(filledLength);
|
|
57
|
-
const empty = '-'.repeat(emptyLength);
|
|
58
|
-
return `[${filled}${empty}] ${Math.round(clamped)}%`;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
export function createSpinner(initialText = 'Thinking...') {
|
|
62
|
-
if (!process.stderr.isTTY || isJsonMode) {
|
|
63
|
-
return {
|
|
64
|
-
setText: () => {},
|
|
65
|
-
stop: () => {}
|
|
66
|
-
};
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
const frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
|
|
70
|
-
let frameIdx = 0;
|
|
71
|
-
let text = initialText;
|
|
72
|
-
let stopped = false;
|
|
73
|
-
const startTime = Date.now();
|
|
74
|
-
|
|
75
|
-
const render = () => {
|
|
76
|
-
if (stopped) return;
|
|
77
|
-
const elapsed = Date.now() - startTime;
|
|
78
|
-
if (elapsed > 2200 && text === initialText) {
|
|
79
|
-
text = 'Warming up on-device model (compiling WebGPU shaders)...';
|
|
80
|
-
} else if (elapsed > 8000 && text === 'Warming up on-device model (compiling WebGPU shaders)...') {
|
|
81
|
-
text = 'Loading model weights, preparing first token...';
|
|
82
|
-
}
|
|
83
|
-
const frame = style(frames[frameIdx % frames.length], 'cyan');
|
|
84
|
-
const label = style(text, 'dim');
|
|
85
|
-
process.stderr.write(`\r${frame} ${label} `);
|
|
86
|
-
frameIdx++;
|
|
87
|
-
};
|
|
88
|
-
|
|
89
|
-
render();
|
|
90
|
-
const timer = setInterval(render, 80);
|
|
91
|
-
if (timer.unref) timer.unref();
|
|
92
|
-
|
|
93
|
-
return {
|
|
94
|
-
setText(newText) {
|
|
95
|
-
text = newText;
|
|
96
|
-
},
|
|
97
|
-
stop() {
|
|
98
|
-
if (stopped) return;
|
|
99
|
-
stopped = true;
|
|
100
|
-
clearInterval(timer);
|
|
101
|
-
if (process.stderr.isTTY) {
|
|
102
|
-
process.stderr.write('\r\x1b[K');
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
};
|
|
106
|
-
}
|
|
107
|
-
|
package/test/chat.test.js
DELETED
|
@@ -1,252 +0,0 @@
|
|
|
1
|
-
import { test, describe } from 'node:test';
|
|
2
|
-
import assert from 'node:assert/strict';
|
|
3
|
-
import fs from 'node:fs';
|
|
4
|
-
import path from 'node:path';
|
|
5
|
-
import os from 'node:os';
|
|
6
|
-
import { parseCommand, formatChatHelp } from '../src/chat/commands.js';
|
|
7
|
-
import { createDefaultChatConfig, validateSamplingMode, validateLanguageCode, loadAndValidateJsonSchema } from '../src/chat/config.js';
|
|
8
|
-
import { ConversationHistory } from '../src/chat/history.js';
|
|
9
|
-
import { ChatSessionManager } from '../src/chat/session.js';
|
|
10
|
-
|
|
11
|
-
describe('Chat Slash Command Parser', () => {
|
|
12
|
-
test('parses standard slash commands correctly', () => {
|
|
13
|
-
assert.deepEqual(parseCommand('/sampling creative'), {
|
|
14
|
-
isCommand: true,
|
|
15
|
-
command: 'sampling',
|
|
16
|
-
value: 'creative',
|
|
17
|
-
args: ['creative'],
|
|
18
|
-
raw: '/sampling creative'
|
|
19
|
-
});
|
|
20
|
-
|
|
21
|
-
assert.deepEqual(parseCommand('/system Answer concisely and factually.'), {
|
|
22
|
-
isCommand: true,
|
|
23
|
-
command: 'system',
|
|
24
|
-
value: 'Answer concisely and factually.',
|
|
25
|
-
args: ['Answer', 'concisely', 'and', 'factually.'],
|
|
26
|
-
raw: '/system Answer concisely and factually.'
|
|
27
|
-
});
|
|
28
|
-
|
|
29
|
-
assert.deepEqual(parseCommand('/json on'), {
|
|
30
|
-
isCommand: true,
|
|
31
|
-
command: 'json',
|
|
32
|
-
value: 'on',
|
|
33
|
-
args: ['on'],
|
|
34
|
-
raw: '/json on'
|
|
35
|
-
});
|
|
36
|
-
|
|
37
|
-
assert.deepEqual(parseCommand('/schema ./data.json'), {
|
|
38
|
-
isCommand: true,
|
|
39
|
-
command: 'schema',
|
|
40
|
-
value: './data.json',
|
|
41
|
-
args: ['./data.json'],
|
|
42
|
-
raw: '/schema ./data.json'
|
|
43
|
-
});
|
|
44
|
-
});
|
|
45
|
-
|
|
46
|
-
test('recognizes parameterless commands', () => {
|
|
47
|
-
assert.strictEqual(parseCommand('/context').command, 'context');
|
|
48
|
-
assert.strictEqual(parseCommand('/clear').command, 'clear');
|
|
49
|
-
assert.strictEqual(parseCommand('/new').command, 'new');
|
|
50
|
-
assert.strictEqual(parseCommand('/settings').command, 'settings');
|
|
51
|
-
assert.strictEqual(parseCommand('/help').command, 'help');
|
|
52
|
-
assert.strictEqual(parseCommand('/continue').command, 'continue');
|
|
53
|
-
assert.strictEqual(parseCommand('/c').command, 'c');
|
|
54
|
-
});
|
|
55
|
-
|
|
56
|
-
test('recognizes exit aliases', () => {
|
|
57
|
-
assert.strictEqual(parseCommand('/exit').command, 'exit');
|
|
58
|
-
assert.strictEqual(parseCommand('/quit').command, 'quit');
|
|
59
|
-
assert.strictEqual(parseCommand('exit').command, 'exit');
|
|
60
|
-
assert.strictEqual(parseCommand('quit').command, 'quit');
|
|
61
|
-
});
|
|
62
|
-
|
|
63
|
-
test('distinguishes normal user prompts from commands', () => {
|
|
64
|
-
assert.strictEqual(parseCommand('What is 2+2?').isCommand, false);
|
|
65
|
-
assert.strictEqual(parseCommand('Explain /dev/null in Linux').isCommand, false);
|
|
66
|
-
});
|
|
67
|
-
});
|
|
68
|
-
|
|
69
|
-
describe('Conversation History & Strict Role Ordering', () => {
|
|
70
|
-
test('formats initialPrompts with system message first and alternating turns', () => {
|
|
71
|
-
const history = new ConversationHistory();
|
|
72
|
-
history.addTurn('user', 'Hello');
|
|
73
|
-
history.addTurn('assistant', 'Hi there!');
|
|
74
|
-
history.addTurn('user', 'How are you?');
|
|
75
|
-
history.addTurn('assistant', 'Doing great!');
|
|
76
|
-
|
|
77
|
-
const prompts = history.formatInitialPrompts('You are helpful.');
|
|
78
|
-
assert.strictEqual(prompts.length, 5);
|
|
79
|
-
assert.deepEqual(prompts[0], { role: 'system', content: 'You are helpful.' });
|
|
80
|
-
assert.deepEqual(prompts[1], { role: 'user', content: 'Hello' });
|
|
81
|
-
assert.deepEqual(prompts[2], { role: 'assistant', content: 'Hi there!' });
|
|
82
|
-
assert.deepEqual(prompts[3], { role: 'user', content: 'How are you?' });
|
|
83
|
-
assert.deepEqual(prompts[4], { role: 'assistant', content: 'Doing great!' });
|
|
84
|
-
});
|
|
85
|
-
|
|
86
|
-
test('drops incomplete trailing user turn from initialPrompts', () => {
|
|
87
|
-
const history = new ConversationHistory();
|
|
88
|
-
history.addTurn('user', 'Hello');
|
|
89
|
-
history.addTurn('assistant', 'Hi');
|
|
90
|
-
history.addTurn('user', 'Incomplete trailing query');
|
|
91
|
-
|
|
92
|
-
const prompts = history.formatInitialPrompts();
|
|
93
|
-
assert.strictEqual(prompts.length, 2);
|
|
94
|
-
assert.strictEqual(prompts[prompts.length - 1].role, 'assistant');
|
|
95
|
-
});
|
|
96
|
-
|
|
97
|
-
test('trims older turns while preserving recent turns in pairs', () => {
|
|
98
|
-
const history = new ConversationHistory();
|
|
99
|
-
for (let i = 1; i <= 10; i++) {
|
|
100
|
-
history.addTurn('user', `User message ${i}`);
|
|
101
|
-
history.addTurn('assistant', `Assistant reply ${i}`);
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
assert.strictEqual(history.length, 20);
|
|
105
|
-
history.trimOlderTurns(6);
|
|
106
|
-
assert.strictEqual(history.length, 6);
|
|
107
|
-
assert.strictEqual(history.getMessages()[0].content, 'User message 8');
|
|
108
|
-
assert.strictEqual(history.getMessages()[5].content, 'Assistant reply 10');
|
|
109
|
-
});
|
|
110
|
-
});
|
|
111
|
-
|
|
112
|
-
describe('Chat Configuration & Schema Validation', () => {
|
|
113
|
-
test('validates sampling modes', () => {
|
|
114
|
-
assert.strictEqual(validateSamplingMode('creative'), 'creative');
|
|
115
|
-
assert.strictEqual(validateSamplingMode('PREDICTABLE'), 'predictable');
|
|
116
|
-
assert.strictEqual(validateSamplingMode('invalid_mode'), null);
|
|
117
|
-
});
|
|
118
|
-
|
|
119
|
-
test('validates language codes', () => {
|
|
120
|
-
assert.strictEqual(validateLanguageCode('en'), 'en');
|
|
121
|
-
assert.strictEqual(validateLanguageCode('tr'), 'tr');
|
|
122
|
-
assert.strictEqual(validateLanguageCode('en-US'), 'en-us');
|
|
123
|
-
assert.strictEqual(validateLanguageCode('12345'), null);
|
|
124
|
-
});
|
|
125
|
-
|
|
126
|
-
test('loads and validates JSON schema files', () => {
|
|
127
|
-
const tmpDir = os.tmpdir();
|
|
128
|
-
const validSchemaPath = path.join(tmpDir, 'test_valid.schema.json');
|
|
129
|
-
fs.writeFileSync(validSchemaPath, JSON.stringify({ type: 'object', properties: { name: { type: 'string' } } }));
|
|
130
|
-
|
|
131
|
-
const res = loadAndValidateJsonSchema(validSchemaPath);
|
|
132
|
-
assert.ok(res.schema);
|
|
133
|
-
assert.strictEqual(res.schema.type, 'object');
|
|
134
|
-
|
|
135
|
-
const invalidPath = path.join(tmpDir, 'test_invalid.json');
|
|
136
|
-
fs.writeFileSync(invalidPath, 'NOT_VALID_JSON');
|
|
137
|
-
assert.throws(() => loadAndValidateJsonSchema(invalidPath), /Invalid JSON/);
|
|
138
|
-
|
|
139
|
-
fs.unlinkSync(validSchemaPath);
|
|
140
|
-
fs.unlinkSync(invalidPath);
|
|
141
|
-
});
|
|
142
|
-
});
|
|
143
|
-
|
|
144
|
-
describe('ChatSessionManager Lifecycle & Capability Adherence', () => {
|
|
145
|
-
function createMockBridge(customCaps = {}) {
|
|
146
|
-
const evalCalls = [];
|
|
147
|
-
return {
|
|
148
|
-
evalCalls,
|
|
149
|
-
isConnected: () => true,
|
|
150
|
-
async evaluate(script) {
|
|
151
|
-
evalCalls.push(script);
|
|
152
|
-
return { success: true, contextUsage: 120, contextWindow: 4096 };
|
|
153
|
-
}
|
|
154
|
-
};
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
test('sampling update with unsupported runtime returns honest error', async () => {
|
|
158
|
-
const bridge = createMockBridge();
|
|
159
|
-
const manager = new ChatSessionManager(bridge, {
|
|
160
|
-
capabilities: { samplingMode: false, supportedSamplingModes: [] }
|
|
161
|
-
});
|
|
162
|
-
|
|
163
|
-
const res = await manager.setSamplingMode('creative');
|
|
164
|
-
assert.strictEqual(res.success, false);
|
|
165
|
-
assert.strictEqual(res.error, 'Sampling mode is not supported by this Chrome runtime.');
|
|
166
|
-
});
|
|
167
|
-
|
|
168
|
-
test('sampling update with supported runtime updates config and recreates session', async () => {
|
|
169
|
-
const bridge = createMockBridge();
|
|
170
|
-
const manager = new ChatSessionManager(bridge, {
|
|
171
|
-
capabilities: { samplingMode: true, supportedSamplingModes: ['balanced', 'creative', 'predictable'] }
|
|
172
|
-
});
|
|
173
|
-
|
|
174
|
-
manager.history.addTurn('user', 'Hi');
|
|
175
|
-
manager.history.addTurn('assistant', 'Hello');
|
|
176
|
-
|
|
177
|
-
const res = await manager.setSamplingMode('creative');
|
|
178
|
-
assert.strictEqual(res.success, true);
|
|
179
|
-
assert.strictEqual(manager.config.samplingMode, 'creative');
|
|
180
|
-
assert.strictEqual(manager.history.length, 2); // History preserved!
|
|
181
|
-
});
|
|
182
|
-
|
|
183
|
-
test('temperature update with unsupported runtime returns honest error', async () => {
|
|
184
|
-
const bridge = createMockBridge();
|
|
185
|
-
const manager = new ChatSessionManager(bridge, {
|
|
186
|
-
capabilities: { temperature: false }
|
|
187
|
-
});
|
|
188
|
-
|
|
189
|
-
const res = await manager.setTemperature(0.2);
|
|
190
|
-
assert.strictEqual(res.success, false);
|
|
191
|
-
assert.strictEqual(res.error, 'temperature is not available in this Chrome context.');
|
|
192
|
-
});
|
|
193
|
-
|
|
194
|
-
test('system prompt update recreates session and preserves conversation', async () => {
|
|
195
|
-
const bridge = createMockBridge();
|
|
196
|
-
const manager = new ChatSessionManager(bridge, {
|
|
197
|
-
capabilities: { initialPrompts: true }
|
|
198
|
-
});
|
|
199
|
-
|
|
200
|
-
manager.history.addTurn('user', 'Turn 1');
|
|
201
|
-
manager.history.addTurn('assistant', 'Answer 1');
|
|
202
|
-
|
|
203
|
-
const res = await manager.setSystemPrompt('New prompt');
|
|
204
|
-
assert.strictEqual(res.success, true);
|
|
205
|
-
assert.strictEqual(manager.config.systemPrompt, 'New prompt');
|
|
206
|
-
assert.strictEqual(manager.history.length, 2);
|
|
207
|
-
});
|
|
208
|
-
|
|
209
|
-
test('/json on/off toggles jsonMode without session recreation', () => {
|
|
210
|
-
const bridge = createMockBridge();
|
|
211
|
-
const manager = new ChatSessionManager(bridge);
|
|
212
|
-
|
|
213
|
-
manager.setJsonMode(true);
|
|
214
|
-
assert.strictEqual(manager.config.jsonMode, true);
|
|
215
|
-
|
|
216
|
-
manager.setJsonMode(false);
|
|
217
|
-
assert.strictEqual(manager.config.jsonMode, false);
|
|
218
|
-
});
|
|
219
|
-
|
|
220
|
-
test('/clear resets history while preserving configuration', async () => {
|
|
221
|
-
const bridge = createMockBridge();
|
|
222
|
-
const manager = new ChatSessionManager(bridge, {
|
|
223
|
-
systemPrompt: 'Keep me',
|
|
224
|
-
samplingMode: 'creative'
|
|
225
|
-
});
|
|
226
|
-
|
|
227
|
-
manager.history.addTurn('user', 'To be deleted');
|
|
228
|
-
assert.strictEqual(manager.history.length, 1);
|
|
229
|
-
|
|
230
|
-
await manager.clearConversation();
|
|
231
|
-
assert.strictEqual(manager.history.length, 0);
|
|
232
|
-
assert.strictEqual(manager.config.systemPrompt, 'Keep me');
|
|
233
|
-
assert.strictEqual(manager.config.samplingMode, 'creative');
|
|
234
|
-
});
|
|
235
|
-
|
|
236
|
-
test('/new resets both history and configuration to defaults', async () => {
|
|
237
|
-
const bridge = createMockBridge();
|
|
238
|
-
const manager = new ChatSessionManager(bridge, {
|
|
239
|
-
systemPrompt: 'Reset me',
|
|
240
|
-
samplingMode: 'creative',
|
|
241
|
-
jsonMode: true
|
|
242
|
-
});
|
|
243
|
-
|
|
244
|
-
manager.history.addTurn('user', 'To be deleted');
|
|
245
|
-
|
|
246
|
-
await manager.resetAll();
|
|
247
|
-
assert.strictEqual(manager.history.length, 0);
|
|
248
|
-
assert.strictEqual(manager.config.systemPrompt, null);
|
|
249
|
-
assert.strictEqual(manager.config.samplingMode, 'balanced');
|
|
250
|
-
assert.strictEqual(manager.config.jsonMode, false);
|
|
251
|
-
});
|
|
252
|
-
});
|
package/test/cli.test.js
DELETED
|
@@ -1,49 +0,0 @@
|
|
|
1
|
-
import test from 'node:test';
|
|
2
|
-
import assert from 'node:assert/strict';
|
|
3
|
-
import { parseArgs } from '../src/cli.js';
|
|
4
|
-
import { combinePromptAndContext } from '../src/commands/ask.js';
|
|
5
|
-
import {
|
|
6
|
-
ChromeUnavailableError,
|
|
7
|
-
BuiltInAiUnavailableError,
|
|
8
|
-
ModelUnavailableError
|
|
9
|
-
} from '../src/utils/errors.js';
|
|
10
|
-
|
|
11
|
-
test('parseArgs correctly parses commands and flags', () => {
|
|
12
|
-
const parsed1 = parseArgs(['node', 'nanobridge', 'status', '--json']);
|
|
13
|
-
assert.equal(parsed1.command, 'status');
|
|
14
|
-
assert.equal(parsed1.options.json, true);
|
|
15
|
-
|
|
16
|
-
const parsed2 = parseArgs(['node', 'nanobridge', 'ask', 'Explain Web Locks', '--no-stream', '--download']);
|
|
17
|
-
assert.equal(parsed2.command, 'ask');
|
|
18
|
-
assert.deepEqual(parsed2.options.positional, ['Explain Web Locks']);
|
|
19
|
-
assert.equal(parsed2.options.stream, false);
|
|
20
|
-
assert.equal(parsed2.options.download, true);
|
|
21
|
-
|
|
22
|
-
const parsed3 = parseArgs(['node', 'nanobridge', 'bench', '--runs', '5']);
|
|
23
|
-
assert.equal(parsed3.command, 'bench');
|
|
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');
|
|
31
|
-
});
|
|
32
|
-
|
|
33
|
-
test('combinePromptAndContext merges prompt and stdin predictably', () => {
|
|
34
|
-
const result1 = combinePromptAndContext('summarize this', 'const x = 10;');
|
|
35
|
-
assert.ok(result1.includes('Context:\nconst x = 10;'));
|
|
36
|
-
assert.ok(result1.includes('Task / Question:\nsummarize this'));
|
|
37
|
-
|
|
38
|
-
const result2 = combinePromptAndContext(null, 'file content');
|
|
39
|
-
assert.equal(result2, 'file content');
|
|
40
|
-
|
|
41
|
-
const result3 = combinePromptAndContext('hello world', null);
|
|
42
|
-
assert.equal(result3, 'hello world');
|
|
43
|
-
});
|
|
44
|
-
|
|
45
|
-
test('Error classes contain proper exit codes', () => {
|
|
46
|
-
assert.equal(new ChromeUnavailableError().exitCode, 2);
|
|
47
|
-
assert.equal(new BuiltInAiUnavailableError().exitCode, 3);
|
|
48
|
-
assert.equal(new ModelUnavailableError().exitCode, 4);
|
|
49
|
-
});
|
package/test/daemon.test.js
DELETED
|
@@ -1,31 +0,0 @@
|
|
|
1
|
-
import { describe, it, beforeEach, afterEach } from 'node:test';
|
|
2
|
-
import assert from 'node:assert/strict';
|
|
3
|
-
import { getDaemonState, saveDaemonState, clearDaemonState } from '../src/daemon/state.js';
|
|
4
|
-
|
|
5
|
-
describe('Daemon State Management', () => {
|
|
6
|
-
beforeEach(() => {
|
|
7
|
-
clearDaemonState();
|
|
8
|
-
});
|
|
9
|
-
|
|
10
|
-
afterEach(() => {
|
|
11
|
-
clearDaemonState();
|
|
12
|
-
});
|
|
13
|
-
|
|
14
|
-
it('saves and clears daemon state', () => {
|
|
15
|
-
assert.equal(getDaemonState(), null);
|
|
16
|
-
|
|
17
|
-
saveDaemonState({
|
|
18
|
-
pid: process.pid,
|
|
19
|
-
port: 54321,
|
|
20
|
-
startTime: Date.now()
|
|
21
|
-
});
|
|
22
|
-
|
|
23
|
-
const state = getDaemonState();
|
|
24
|
-
assert.ok(state);
|
|
25
|
-
assert.equal(state.pid, process.pid);
|
|
26
|
-
assert.equal(state.port, 54321);
|
|
27
|
-
|
|
28
|
-
clearDaemonState();
|
|
29
|
-
assert.equal(getDaemonState(), null);
|
|
30
|
-
});
|
|
31
|
-
});
|
package/test/detect.test.js
DELETED
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
import test from 'node:test';
|
|
2
|
-
import assert from 'node:assert/strict';
|
|
3
|
-
import { getPlatformInfo, findChromeExecutable, getChromeVersion } from '../src/chrome/detect.js';
|
|
4
|
-
|
|
5
|
-
test('getPlatformInfo returns platform label and arch', () => {
|
|
6
|
-
const info = getPlatformInfo();
|
|
7
|
-
assert.ok(info.platform);
|
|
8
|
-
assert.ok(info.arch);
|
|
9
|
-
assert.ok(info.platformLabel);
|
|
10
|
-
});
|
|
11
|
-
|
|
12
|
-
test('findChromeExecutable finds Chrome on host machine', () => {
|
|
13
|
-
const exe = findChromeExecutable();
|
|
14
|
-
assert.ok(exe, 'Should find Chrome executable');
|
|
15
|
-
});
|
|
16
|
-
|
|
17
|
-
test('getChromeVersion parses version string', () => {
|
|
18
|
-
const exe = findChromeExecutable();
|
|
19
|
-
if (exe) {
|
|
20
|
-
const version = getChromeVersion(exe);
|
|
21
|
-
assert.ok(version, 'Version should be extracted');
|
|
22
|
-
assert.match(version, /^\d+\.\d+/);
|
|
23
|
-
}
|
|
24
|
-
});
|
package/test/files.test.js
DELETED
|
@@ -1,41 +0,0 @@
|
|
|
1
|
-
import { test, describe } from 'node:test';
|
|
2
|
-
import assert from 'node:assert/strict';
|
|
3
|
-
import { readFileContent, formatFileAsContext, extractAndAttachFiles } from '../src/utils/files.js';
|
|
4
|
-
|
|
5
|
-
describe('File Reading & Context Utilities', () => {
|
|
6
|
-
test('reads an existing file correctly', () => {
|
|
7
|
-
const file = readFileContent('package.json');
|
|
8
|
-
assert.ok(file);
|
|
9
|
-
assert.strictEqual(file.filename, 'package.json');
|
|
10
|
-
assert.ok(file.content.includes('"name": "nanobridge"'));
|
|
11
|
-
assert.ok(file.size > 0);
|
|
12
|
-
});
|
|
13
|
-
|
|
14
|
-
test('formats file as structured markdown context', () => {
|
|
15
|
-
const file = readFileContent('package.json');
|
|
16
|
-
const formatted = formatFileAsContext(file);
|
|
17
|
-
assert.ok(formatted.includes('--- File: package.json ---'));
|
|
18
|
-
assert.ok(formatted.includes('```json'));
|
|
19
|
-
assert.ok(formatted.includes('--- End of File ---'));
|
|
20
|
-
});
|
|
21
|
-
|
|
22
|
-
test('extracts @file mentions from user input', () => {
|
|
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 which packages are used?';
|
|
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 ---'));
|
|
34
|
-
});
|
|
35
|
-
|
|
36
|
-
test('throws error on non-existent file', () => {
|
|
37
|
-
assert.throws(() => {
|
|
38
|
-
readFileContent('non_existent_file_xyz_123.txt');
|
|
39
|
-
}, /File not found/);
|
|
40
|
-
});
|
|
41
|
-
});
|
package/test/openai.test.js
DELETED
|
@@ -1,63 +0,0 @@
|
|
|
1
|
-
import { describe, it } from 'node:test';
|
|
2
|
-
import assert from 'node:assert/strict';
|
|
3
|
-
import {
|
|
4
|
-
parseChatMessages,
|
|
5
|
-
formatModelsList,
|
|
6
|
-
formatChatCompletion,
|
|
7
|
-
formatChatCompletionChunk
|
|
8
|
-
} from '../src/api/openai.js';
|
|
9
|
-
|
|
10
|
-
describe('OpenAI Compatibility API Transformers', () => {
|
|
11
|
-
it('parses single user message cleanly', () => {
|
|
12
|
-
const { systemPrompt, promptText } = parseChatMessages([
|
|
13
|
-
{ role: 'user', content: 'What is WebGPU?' }
|
|
14
|
-
]);
|
|
15
|
-
assert.equal(systemPrompt, undefined);
|
|
16
|
-
assert.equal(promptText, 'What is WebGPU?');
|
|
17
|
-
});
|
|
18
|
-
|
|
19
|
-
it('parses system prompt and multi-turn messages', () => {
|
|
20
|
-
const { systemPrompt, promptText } = parseChatMessages([
|
|
21
|
-
{ role: 'system', content: 'You are a code reviewer.' },
|
|
22
|
-
{ role: 'user', content: 'Review my code.' },
|
|
23
|
-
{ role: 'assistant', content: 'Sure, show me.' },
|
|
24
|
-
{ role: 'user', content: 'const a = 1;' }
|
|
25
|
-
]);
|
|
26
|
-
assert.equal(systemPrompt, 'You are a code reviewer.');
|
|
27
|
-
assert.match(promptText, /User: Review my code/);
|
|
28
|
-
assert.match(promptText, /Assistant: Sure, show me/);
|
|
29
|
-
assert.match(promptText, /User: const a = 1;/);
|
|
30
|
-
});
|
|
31
|
-
|
|
32
|
-
it('formats models list in OpenAI format', () => {
|
|
33
|
-
const list = formatModelsList();
|
|
34
|
-
assert.equal(list.object, 'list');
|
|
35
|
-
assert.ok(Array.isArray(list.data));
|
|
36
|
-
assert.equal(list.data[0].id, 'gemini-nano');
|
|
37
|
-
});
|
|
38
|
-
|
|
39
|
-
it('formats chat completion JSON object', () => {
|
|
40
|
-
const res = formatChatCompletion({
|
|
41
|
-
id: 'chatcmpl-test',
|
|
42
|
-
model: 'gemini-nano',
|
|
43
|
-
content: 'Hello world!'
|
|
44
|
-
});
|
|
45
|
-
assert.equal(res.id, 'chatcmpl-test');
|
|
46
|
-
assert.equal(res.object, 'chat.completion');
|
|
47
|
-
assert.equal(res.choices[0].message.role, 'assistant');
|
|
48
|
-
assert.equal(res.choices[0].message.content, 'Hello world!');
|
|
49
|
-
assert.equal(res.choices[0].finish_reason, 'stop');
|
|
50
|
-
});
|
|
51
|
-
|
|
52
|
-
it('formats streaming SSE chunk', () => {
|
|
53
|
-
const chunk = formatChatCompletionChunk({
|
|
54
|
-
id: 'chatcmpl-test',
|
|
55
|
-
model: 'gemini-nano',
|
|
56
|
-
delta: 'Hello',
|
|
57
|
-
isFirst: true
|
|
58
|
-
});
|
|
59
|
-
assert.equal(chunk.object, 'chat.completion.chunk');
|
|
60
|
-
assert.equal(chunk.choices[0].delta.role, 'assistant');
|
|
61
|
-
assert.equal(chunk.choices[0].delta.content, 'Hello');
|
|
62
|
-
});
|
|
63
|
-
});
|