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 CHANGED
@@ -77,22 +77,27 @@ nanobridge download
77
77
 
78
78
  ---
79
79
 
80
- ### 3. Interactive Chat Mode
80
+ ### 3. Interactive Chat Mode & Runtime Settings
81
81
 
82
- Start an interactive multi-turn conversation with memory:
82
+ Start an interactive multi-turn conversation with memory and live runtime configuration:
83
83
 
84
84
  ```bash
85
85
  nanobridge chat
86
86
  ```
87
87
 
88
- Inside the interactive chat:
89
- * `> What dependencies does @package.json have?` — Automatically reads & attaches files mentioned with `@`
90
- * `/read <filepath>` — Load a file into the conversation context
91
- * `/clear` — Reset conversation context history & clear screen
92
- * `/system <prompt>` — Set custom system instructions
93
- * `/history` — View active conversation turns
94
- * `/help` — List interactive shortcuts
95
- * `/exit` or `Ctrl+C` — Exit chat session
88
+ #### Slash Commands & Settings:
89
+ * `/sampling <mode>` — Change sampling mode (`creative`, `predictable`, `balanced`, etc.). Recreates session and preserves history.
90
+ * `/system <prompt>` — Set or update system instructions (recreates session and preserves conversation).
91
+ * `/json on` / `/json off` — Toggle structured JSON output constraint on the fly.
92
+ * `/schema <file.json>` — Load and validate a JSON schema for structured model outputs (`/schema clear` to remove).
93
+ * `/context` — Inspect token usage, total window size, percentage, and message count.
94
+ * `/settings` — Display the current session configuration, language, and runtime capabilities.
95
+ * `/clear` — Clear conversation history while preserving your active system prompt and sampling settings.
96
+ * `/new` — Reset both conversation history and all settings back to default.
97
+ * `/read <filepath>` (or `@file`) — Load local files directly into the conversation context.
98
+ * `/history` — View active conversation turns.
99
+ * `/help` — List available commands based on runtime capabilities.
100
+ * `/exit` or `Ctrl+C` — Quit the chat session.
96
101
 
97
102
  ---
98
103
 
@@ -202,9 +207,9 @@ for await (const chunk of stream) {
202
207
 
203
208
  ---
204
209
 
205
- ### 6. Background Daemon Management
210
+ ### 6. Background Daemon Management & Context Reset
206
211
 
207
- NanoBridge can run a warm Chrome background daemon to eliminate the ~2.5s cold-start penalty on every query:
212
+ NanoBridge runs a warm Chrome background daemon to eliminate the ~2.5s cold-start penalty on every query:
208
213
 
209
214
  ```bash
210
215
  # Start the background daemon
@@ -213,12 +218,22 @@ nanobridge daemon start
213
218
  # Check daemon status (PID, Port, Uptime)
214
219
  nanobridge daemon status
215
220
 
221
+ # Reset model session and clear KV context cache (<100ms)
222
+ nanobridge reset
223
+
224
+ # Restart the background daemon process
225
+ nanobridge restart
226
+ # or:
227
+ nanobridge daemon restart
228
+
216
229
  # Stop the running background daemon
217
- nanobridge daemon stop
218
- # or simply:
219
230
  nanobridge stop
231
+ # or:
232
+ nanobridge daemon stop
220
233
  ```
221
234
 
235
+ > **Memory & Halucination Reset**: If you have long-running chat sessions or heavy multi-file prompts, running `nanobridge reset` (or typing `/reset` in `nanobridge chat`) instantly clears Chrome's on-device session and KV cache without needing to cold-relaunch Chrome.
236
+
222
237
  ---
223
238
 
224
239
  ### 7. Benchmarking On-Device Performance
@@ -0,0 +1,112 @@
1
+ /**
2
+ * NanoBridge OpenAI API Compatibility Test Script
3
+ *
4
+ * Demonstrates:
5
+ * 1. GET /v1/models
6
+ * 2. POST /v1/chat/completions (Non-Streaming)
7
+ * 3. POST /v1/chat/completions (Streaming SSE)
8
+ *
9
+ * Usage:
10
+ * 1. Start the server: nanobridge serve --port 8000
11
+ * (or use the warm background daemon port)
12
+ * 2. Run this script: node examples/openai-client.js
13
+ */
14
+
15
+ const BASE_URL = process.env.NANOBRIDGE_BASE_URL || 'http://127.0.0.1:8000/v1';
16
+
17
+ async function testModels() {
18
+ console.log('\n=== 1. Testing GET /v1/models ===');
19
+ const res = await fetch(`${BASE_URL}/models`);
20
+ const data = await res.json();
21
+ console.log('Available Models:', JSON.stringify(data, null, 2));
22
+ }
23
+
24
+ async function testNonStreaming() {
25
+ console.log('\n=== 2. Testing POST /v1/chat/completions (Non-Streaming) ===');
26
+ const payload = {
27
+ model: 'gemini-nano',
28
+ messages: [
29
+ { role: 'system', content: 'You are a concise, helpful AI assistant.' },
30
+ { role: 'user', content: 'Explain Node.js in one clear sentence.' }
31
+ ],
32
+ temperature: 0.2
33
+ };
34
+
35
+ const startTime = Date.now();
36
+ const res = await fetch(`${BASE_URL}/chat/completions`, {
37
+ method: 'POST',
38
+ headers: { 'Content-Type': 'application/json' },
39
+ body: JSON.stringify(payload)
40
+ });
41
+
42
+ const json = await res.json();
43
+ const elapsed = Date.now() - startTime;
44
+
45
+ console.log(`Response (${elapsed}ms):`);
46
+ console.log(json.choices[0]?.message?.content);
47
+ }
48
+
49
+ async function testStreaming() {
50
+ console.log('\n=== 3. Testing POST /v1/chat/completions (Streaming SSE) ===');
51
+ const payload = {
52
+ model: 'gemini-nano',
53
+ messages: [
54
+ { role: 'user', content: 'Count from 1 to 5 with emojis.' }
55
+ ],
56
+ stream: true
57
+ };
58
+
59
+ const startTime = Date.now();
60
+ const res = await fetch(`${BASE_URL}/chat/completions`, {
61
+ method: 'POST',
62
+ headers: { 'Content-Type': 'application/json' },
63
+ body: JSON.stringify(payload)
64
+ });
65
+
66
+ process.stdout.write('Stream Output: ');
67
+ const reader = res.body.getReader();
68
+ const decoder = new TextDecoder('utf-8');
69
+ let buffer = '';
70
+
71
+ while (true) {
72
+ const { done, value } = await reader.read();
73
+ if (done) break;
74
+
75
+ buffer += decoder.decode(value, { stream: true });
76
+ const lines = buffer.split('\n');
77
+ buffer = lines.pop() || '';
78
+
79
+ for (const line of lines) {
80
+ const trimmed = line.trim();
81
+ if (!trimmed || !trimmed.startsWith('data: ')) continue;
82
+ const dataStr = trimmed.slice(6);
83
+ if (dataStr === '[DONE]') {
84
+ break;
85
+ }
86
+ try {
87
+ const parsed = JSON.parse(dataStr);
88
+ const delta = parsed.choices[0]?.delta?.content || '';
89
+ process.stdout.write(delta);
90
+ } catch (_) {}
91
+ }
92
+ }
93
+
94
+ const elapsed = Date.now() - startTime;
95
+ console.log(`\n\nStream finished in ${elapsed}ms`);
96
+ }
97
+
98
+ async function main() {
99
+ console.log(`Connecting to NanoBridge OpenAI Server at ${BASE_URL}...`);
100
+ try {
101
+ await testModels();
102
+ await testNonStreaming();
103
+ await testStreaming();
104
+ console.log('\nAll OpenAI API tests completed successfully! ✓');
105
+ } catch (err) {
106
+ console.error('\nTest failed:', err.message);
107
+ console.log('\nMake sure the server is running:');
108
+ console.log(' nanobridge serve --port 8000');
109
+ }
110
+ }
111
+
112
+ main();
@@ -0,0 +1,46 @@
1
+ /**
2
+ * NanoBridge with Official OpenAI SDK (JavaScript / Node.js)
3
+ *
4
+ * Requirements:
5
+ * npm install openai
6
+ *
7
+ * Usage:
8
+ * 1. Start server: nanobridge serve --port 8000
9
+ * 2. Run script: node examples/openai-sdk.js
10
+ */
11
+
12
+ import OpenAI from 'openai';
13
+
14
+ const openai = new OpenAI({
15
+ baseURL: 'http://127.0.0.1:8000/v1',
16
+ apiKey: 'nanobridge' // Any dummy string works (no API key required)
17
+ });
18
+
19
+ async function run() {
20
+ console.log('--- 1. Non-Streaming Completion ---');
21
+ const completion = await openai.chat.completions.create({
22
+ model: 'gemini-nano',
23
+ messages: [
24
+ { role: 'system', content: 'You are a helpful assistant.' },
25
+ { role: 'user', content: 'What is Chrome Built-in AI?' }
26
+ ]
27
+ });
28
+
29
+ console.log(completion.choices[0].message.content);
30
+
31
+ console.log('\n--- 2. Streaming Completion ---');
32
+ const stream = await openai.chat.completions.create({
33
+ model: 'gemini-nano',
34
+ messages: [
35
+ { role: 'user', content: 'List 3 benefits of local on-device AI models.' }
36
+ ],
37
+ stream: true
38
+ });
39
+
40
+ for await (const chunk of stream) {
41
+ process.stdout.write(chunk.choices[0]?.delta?.content || '');
42
+ }
43
+ console.log('\n');
44
+ }
45
+
46
+ run().catch(console.error);
@@ -0,0 +1,42 @@
1
+ """
2
+ NanoBridge with Official OpenAI Python SDK
3
+
4
+ Requirements:
5
+ pip install openai
6
+
7
+ Usage:
8
+ 1. Start server: nanobridge serve --port 8000
9
+ 2. Run script: python3 examples/openai_python.py
10
+ """
11
+
12
+ from openai import OpenAI
13
+
14
+ client = OpenAI(
15
+ base_url="http://127.0.0.1:8000/v1",
16
+ api_key="nanobridge", # Any string (no auth required)
17
+ )
18
+
19
+ print("=== 1. Testing Non-Streaming ===")
20
+ response = client.chat.completions.create(
21
+ model="gemini-nano",
22
+ messages=[
23
+ {"role": "system", "content": "You are a concise assistant."},
24
+ {"role": "user", "content": "Explain WebSocket in one sentence."}
25
+ ],
26
+ )
27
+ print(response.choices[0].message.content)
28
+
29
+ print("\n=== 2. Testing Streaming ===")
30
+ stream = client.chat.completions.create(
31
+ model="gemini-nano",
32
+ messages=[
33
+ {"role": "user", "content": "List 3 programming tips."}
34
+ ],
35
+ stream=True,
36
+ )
37
+
38
+ for chunk in stream:
39
+ content = chunk.choices[0].delta.content or ""
40
+ print(content, end="", flush=True)
41
+
42
+ print("\n")
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nanobridge",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Chrome Built-in AI CLI bridge to on-device language models via CDP",
5
5
  "type": "module",
6
6
  "bin": {
@@ -0,0 +1,67 @@
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
+ ' /clear Clear conversation history (keeps config & sampling)',
52
+ ' /new Start a fresh session with default configuration',
53
+ ' /history Show turn history',
54
+ ' /read <filepath> Load local file content into conversation context',
55
+ ' /help Show available commands',
56
+ ' /exit Exit chat session'
57
+ ];
58
+
59
+ if (capabilities.temperature) {
60
+ lines.splice(2, 0, ' /temperature <n> Set generation temperature (0.0 - 2.0)');
61
+ }
62
+ if (capabilities.topK) {
63
+ lines.splice(3, 0, ' /topk <n> Set top-K sampling parameter');
64
+ }
65
+
66
+ return lines.join('\n');
67
+ }
@@ -0,0 +1,65 @@
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
+ }
@@ -0,0 +1,103 @@
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
+ }