nanobridge 0.1.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.
@@ -0,0 +1,194 @@
1
+ import readline from 'node:readline';
2
+ import process from 'node:process';
3
+ import { ensureDaemon, streamPromptFromDaemon } from '../daemon/client.js';
4
+ import { launchChrome } from '../chrome/launch.js';
5
+ import { ChromeBridge } from '../chrome/bridge.js';
6
+ import { log, style, debug } from '../utils/output.js';
7
+ import { NanoBridgeError } from '../utils/errors.js';
8
+ import { readFileContent, formatFileAsContext, extractAndAttachFiles } from '../utils/files.js';
9
+
10
+ export async function handleChat(options = {}) {
11
+ let systemPrompt = options.system || 'You are a helpful, concise AI assistant.';
12
+ const conversation = [];
13
+ let daemon = null;
14
+ let standaloneBridge = null;
15
+ let standaloneChrome = null;
16
+
17
+ // 1. Check or start daemon
18
+ if (options.daemon !== false) {
19
+ try {
20
+ debug('chat', 'Checking or starting background daemon...');
21
+ daemon = await ensureDaemon();
22
+ } catch (err) {
23
+ debug('chat', 'Daemon unavailable, falling back to direct Chrome:', err.message);
24
+ }
25
+ }
26
+
27
+ if (!daemon) {
28
+ log(style('Launching local Chrome AI session...', 'dim'));
29
+ standaloneChrome = await launchChrome(options);
30
+ standaloneBridge = new ChromeBridge(standaloneChrome);
31
+ await standaloneBridge.connect();
32
+ }
33
+
34
+ // 2. Interactive Welcome Banner
35
+ log(`
36
+ ${style('NanoBridge Interactive Chat', 'bold')} ${style('(Gemini Nano on-device)', 'cyan')}
37
+ ${style('Commands:', 'dim')} ${style('/clear', 'yellow')} to reset history, ${style('@file', 'yellow')} to attach files, ${style('/exit', 'yellow')} or ${style('Ctrl+C', 'yellow')} to exit.
38
+ `);
39
+
40
+ const rl = readline.createInterface({
41
+ input: process.stdin,
42
+ output: process.stdout,
43
+ prompt: `\x1b[36m>\x1b[0m `
44
+ });
45
+
46
+ const promptUser = () => {
47
+ rl.prompt();
48
+ };
49
+
50
+ const cleanup = async () => {
51
+ rl.close();
52
+ if (standaloneBridge) {
53
+ await standaloneBridge.close().catch(() => {});
54
+ }
55
+ if (standaloneChrome) {
56
+ standaloneChrome.close();
57
+ }
58
+ log(`\n${style('Goodbye!', 'dim')}`);
59
+ process.exit(0);
60
+ };
61
+
62
+ rl.on('SIGINT', () => {
63
+ cleanup();
64
+ });
65
+
66
+ promptUser();
67
+
68
+ for await (const line of rl) {
69
+ const input = line.trim();
70
+
71
+ if (!input) {
72
+ promptUser();
73
+ continue;
74
+ }
75
+
76
+ // Command handling
77
+ if (input.toLowerCase() === '/exit' || input.toLowerCase() === '/quit' || input.toLowerCase() === 'exit' || input.toLowerCase() === 'quit') {
78
+ await cleanup();
79
+ break;
80
+ }
81
+
82
+ if (input.toLowerCase() === '/clear' || input.toLowerCase() === '/reset') {
83
+ conversation.length = 0;
84
+ console.clear();
85
+ log(`${style('Conversation history cleared.', 'green')}\n`);
86
+ promptUser();
87
+ continue;
88
+ }
89
+
90
+ if (input.startsWith('/system')) {
91
+ const newSys = input.slice(7).trim();
92
+ if (newSys) {
93
+ systemPrompt = newSys;
94
+ log(`${style('System prompt updated:', 'green')} "${systemPrompt}"\n`);
95
+ } else {
96
+ log(`${style('Current system prompt:', 'dim')} "${systemPrompt}"\n`);
97
+ }
98
+ promptUser();
99
+ continue;
100
+ }
101
+
102
+ if (input.toLowerCase() === '/history') {
103
+ log(`\n${style('Conversation Turns:', 'bold')} ${conversation.length / 2}`);
104
+ conversation.forEach((msg, idx) => {
105
+ const roleStyle = msg.role === 'user' ? 'cyan' : 'green';
106
+ log(`${style(`[${msg.role.toUpperCase()}]:`, roleStyle)} ${msg.content.slice(0, 80)}${msg.content.length > 80 ? '...' : ''}`);
107
+ });
108
+ log('');
109
+ promptUser();
110
+ continue;
111
+ }
112
+
113
+ if (input.startsWith('/read') || input.startsWith('/file')) {
114
+ const filePath = input.replace(/^\/(read|file)\s*/, '').trim();
115
+ if (!filePath) {
116
+ log(`${style('Usage:', 'dim')} /read <filepath>\n`);
117
+ promptUser();
118
+ continue;
119
+ }
120
+ try {
121
+ const fileInfo = readFileContent(filePath);
122
+ const formatted = formatFileAsContext(fileInfo);
123
+ conversation.push({ role: 'user', content: `Here is the content of ${fileInfo.relativePath}:\n\n${formatted}` });
124
+ conversation.push({ role: 'assistant', content: `I have loaded and read \`${fileInfo.relativePath}\` (${Math.round(fileInfo.size / 1024 * 10) / 10} KB). What would you like to know or do with it?` });
125
+ log(`${style('📎 Loaded file:', 'green')} ${fileInfo.relativePath} (${Math.round(fileInfo.size / 1024 * 10) / 10} KB)\n`);
126
+ } catch (err) {
127
+ log(`${style('Error loading file:', 'red')} ${err.message}\n`);
128
+ }
129
+ promptUser();
130
+ continue;
131
+ }
132
+
133
+ if (input.toLowerCase() === '/help') {
134
+ log(`
135
+ ${style('Chat Commands:', 'bold')}
136
+ ${style('@<filepath>', 'yellow')} Mention any file in your prompt (e.g. @package.json explain dependencies)
137
+ ${style('/read <filepath>', 'yellow')} Load a file into conversation context
138
+ ${style('/clear', 'yellow')} Clear chat context history and terminal screen
139
+ ${style('/system <prompt>', 'yellow')} Set or inspect active system instructions
140
+ ${style('/history', 'yellow')} Show turn history
141
+ ${style('/exit', 'yellow')} Quit interactive chat session
142
+ `);
143
+ promptUser();
144
+ continue;
145
+ }
146
+
147
+ // Auto-detect @file mentions in regular prompts
148
+ const { finalPrompt, attachedFiles } = extractAndAttachFiles(input);
149
+ if (attachedFiles.length > 0) {
150
+ const names = attachedFiles.map((f) => `${f.relativePath} (${Math.round(f.size / 1024 * 10) / 10} KB)`).join(', ');
151
+ log(`${style('📎 Attached:', 'dim')} ${names}`);
152
+ }
153
+
154
+ // Append to conversation
155
+ conversation.push({ role: 'user', content: finalPrompt });
156
+
157
+ // Build context prompt
158
+ const fullPromptText = conversation.map((m) => `${m.role === 'user' ? 'User' : 'Assistant'}: ${m.content}`).join('\n\n') + '\n\nAssistant:';
159
+
160
+ let assistantResponse = '';
161
+
162
+ try {
163
+ if (daemon) {
164
+ await streamPromptFromDaemon({
165
+ port: daemon.port,
166
+ promptText: fullPromptText,
167
+ systemPrompt,
168
+ stream: true,
169
+ onChunk: (delta) => {
170
+ assistantResponse += delta;
171
+ process.stdout.write(delta);
172
+ }
173
+ });
174
+ } else {
175
+ await standaloneBridge.prompt({
176
+ promptText: fullPromptText,
177
+ systemPrompt,
178
+ stream: true,
179
+ onChunk: (delta) => {
180
+ assistantResponse += delta;
181
+ process.stdout.write(delta);
182
+ }
183
+ });
184
+ }
185
+
186
+ conversation.push({ role: 'assistant', content: assistantResponse.trim() });
187
+ process.stdout.write('\n\n');
188
+ } catch (err) {
189
+ log(`\n${style('Error:', 'red')} ${err.message}\n`);
190
+ }
191
+
192
+ promptUser();
193
+ }
194
+ }
@@ -0,0 +1,61 @@
1
+ import { getActiveDaemon, startDaemonInBackground, stopDaemon } from '../daemon/client.js';
2
+ import { style, log, logError } from '../utils/output.js';
3
+
4
+ export async function handleDaemonCommand(subCommand = 'status', options = {}) {
5
+ if (subCommand === 'start') {
6
+ const active = await getActiveDaemon();
7
+ if (active) {
8
+ if (options.json) {
9
+ console.log(JSON.stringify({ status: 'running', pid: active.pid, port: active.port }, null, 2));
10
+ } else {
11
+ log(`Daemon is already running (PID: ${style(active.pid, 'bold')}, port: ${style(active.port, 'cyan')})`);
12
+ }
13
+ return;
14
+ }
15
+
16
+ if (!options.json) {
17
+ log('Starting NanoBridge background daemon...');
18
+ }
19
+ const started = await startDaemonInBackground();
20
+ if (options.json) {
21
+ console.log(JSON.stringify({ status: 'started', pid: started.pid, port: started.port }, null, 2));
22
+ } else {
23
+ log(`${style('Daemon started successfully', 'green')} ✓ (PID: ${style(started.pid, 'bold')}, port: ${style(started.port, 'cyan')})`);
24
+ }
25
+ return;
26
+ }
27
+
28
+ if (subCommand === 'stop') {
29
+ const res = await stopDaemon();
30
+ if (options.json) {
31
+ console.log(JSON.stringify(res, null, 2));
32
+ } else {
33
+ if (res.wasRunning) {
34
+ log(`${style('Daemon stopped', 'green')} ✓`);
35
+ } else {
36
+ log('Daemon was not running.');
37
+ }
38
+ }
39
+ return;
40
+ }
41
+
42
+ if (subCommand === 'status') {
43
+ const active = await getActiveDaemon();
44
+ if (options.json) {
45
+ console.log(JSON.stringify(active ? { status: 'running', ...active } : { status: 'stopped' }, null, 2));
46
+ } else {
47
+ if (active) {
48
+ const uptimeSec = Math.round((active.uptimeMs || 0) / 1000);
49
+ log(`Status: ${style('running', 'green')}`);
50
+ log(`PID: ${active.pid}`);
51
+ log(`Port: ${active.port}`);
52
+ log(`Uptime: ${uptimeSec}s`);
53
+ } else {
54
+ log(`Status: ${style('stopped', 'dim')}`);
55
+ }
56
+ }
57
+ return;
58
+ }
59
+
60
+ logError(`Unknown daemon subcommand: ${subCommand}`);
61
+ }
@@ -0,0 +1,71 @@
1
+ import process from 'node:process';
2
+ import { launchChrome } from '../chrome/launch.js';
3
+ import { ChromeBridge } from '../chrome/bridge.js';
4
+ import { isModelDownloaded } from '../chrome/detect.js';
5
+ import { style, log, renderProgressBar } from '../utils/output.js';
6
+
7
+ export async function handleDownload(options = {}) {
8
+ if (isModelDownloaded()) {
9
+ if (options.json) {
10
+ console.log(JSON.stringify({ status: 'ready', alreadyAvailable: true }, null, 2));
11
+ } else {
12
+ log(`${style('Model already available', 'green')} ✓`);
13
+ }
14
+ return;
15
+ }
16
+
17
+ let chromeInstance = null;
18
+ let bridge = null;
19
+
20
+ try {
21
+ if (!options.json) {
22
+ log('Preparing Chrome Built-in AI...\n');
23
+ }
24
+
25
+ chromeInstance = await launchChrome(options);
26
+ bridge = new ChromeBridge(chromeInstance);
27
+ await bridge.connect();
28
+
29
+ let lastRenderedPercent = -1;
30
+ let isTty = Boolean(process.stdout.isTTY) && !options.json;
31
+
32
+ const result = await bridge.downloadModel({
33
+ onProgress: ({ loaded, total, percent }) => {
34
+ const rounded = Math.round(percent);
35
+ if (rounded !== lastRenderedPercent) {
36
+ lastRenderedPercent = rounded;
37
+ if (options.json) return;
38
+
39
+ const bar = renderProgressBar(rounded, 28);
40
+ if (isTty) {
41
+ process.stdout.write(`\r${style(bar, 'cyan')} Downloading model components...`);
42
+ } else {
43
+ log(`${bar} Downloading model components`);
44
+ }
45
+ }
46
+ }
47
+ });
48
+
49
+ if (result.alreadyAvailable) {
50
+ if (options.json) {
51
+ console.log(JSON.stringify({ status: 'ready', alreadyAvailable: true }, null, 2));
52
+ } else {
53
+ log(`${style('Model already available', 'green')} ✓`);
54
+ }
55
+ return;
56
+ }
57
+
58
+ if (isTty) {
59
+ process.stdout.write('\n\n');
60
+ }
61
+
62
+ if (options.json) {
63
+ console.log(JSON.stringify({ status: 'ready', downloaded: true }, null, 2));
64
+ } else {
65
+ log(`${style('Model ready', 'green')} ✓`);
66
+ }
67
+ } finally {
68
+ if (bridge) await bridge.close();
69
+ if (chromeInstance) chromeInstance.close();
70
+ }
71
+ }
@@ -0,0 +1,56 @@
1
+ import process from 'node:process';
2
+ import { DaemonServer } from '../daemon/server.js';
3
+ import { style, log, logError } from '../utils/output.js';
4
+
5
+ export async function handleServe(options = {}) {
6
+ const port = options.port || 8000;
7
+ const host = options.host || '127.0.0.1';
8
+
9
+ log(style('NanoBridge OpenAI-Compatible API Server', 'bold'));
10
+ log('Starting background Chrome and warming Gemini Nano...');
11
+
12
+ const server = new DaemonServer({
13
+ port,
14
+ host,
15
+ idleTimeoutMs: 0 // Do not auto-shutdown when explicitly running in serve mode
16
+ });
17
+
18
+ try {
19
+ await server.start();
20
+
21
+ const baseUrl = `http://${host}:${server.port}/v1`;
22
+
23
+ log('');
24
+ log(`${style('OpenAI-Compatible Server Ready!', 'green')} ✓`);
25
+ log(`Base URL: ${style(baseUrl, 'cyan')}`);
26
+ log(`Models: ${style(`${baseUrl}/models`, 'dim')}`);
27
+ log(`Chat: ${style(`${baseUrl}/chat/completions`, 'dim')}`);
28
+ log(`Completions: ${style(`${baseUrl}/completions`, 'dim')}`);
29
+ log('');
30
+ log(style('Example curl (Streaming SSE):', 'bold'));
31
+ log(` curl -N ${baseUrl}/chat/completions \\
32
+ -H "Content-Type: application/json" \\
33
+ -d '{
34
+ "model": "gemini-nano",
35
+ "messages": [{"role": "user", "content": "Nasılsın?"}],
36
+ "stream": true
37
+ }'`);
38
+ log('');
39
+ log(style('Example OpenAI Python SDK:', 'bold'));
40
+ log(` from openai import OpenAI
41
+ client = OpenAI(base_url="${baseUrl}", api_key="nanobridge")
42
+ response = client.chat.completions.create(
43
+ model="gemini-nano",
44
+ messages=[{"role": "user", "content": "Explain Web Locks"}]
45
+ )
46
+ print(response.choices[0].message.content)`);
47
+ log('');
48
+ log(`Press ${style('Ctrl+C', 'bold')} to stop server.`);
49
+
50
+ // Keep running until interrupt
51
+ await new Promise(() => {});
52
+ } catch (err) {
53
+ logError(`Failed to start serve server: ${err.message}`);
54
+ process.exit(1);
55
+ }
56
+ }
@@ -0,0 +1,78 @@
1
+ import { getPlatformInfo, isModelDownloaded } from '../chrome/detect.js';
2
+ import { launchChrome } from '../chrome/launch.js';
3
+ import { ChromeBridge } from '../chrome/bridge.js';
4
+ import { getActiveDaemon } from '../daemon/client.js';
5
+ import { style, log, logError } from '../utils/output.js';
6
+ import { BuiltInAiUnavailableError, ModelUnavailableError } from '../utils/errors.js';
7
+
8
+ export async function handleStatus(options = {}) {
9
+ let chromeInstance = null;
10
+ let bridge = null;
11
+
12
+ try {
13
+ chromeInstance = await launchChrome(options);
14
+ bridge = new ChromeBridge(chromeInstance);
15
+ await bridge.connect();
16
+
17
+ const status = await bridge.checkStatus();
18
+ const platformInfo = getPlatformInfo();
19
+ const modelOnDisk = isModelDownloaded();
20
+ const daemon = await getActiveDaemon();
21
+
22
+ let modelDisplayStatus = 'unavailable';
23
+ const rawAvail = String(status.availability || '').toLowerCase();
24
+ if (modelOnDisk || rawAvail === 'readily' || rawAvail === 'available' || rawAvail === 'ready') {
25
+ modelDisplayStatus = 'ready';
26
+ } else if (rawAvail === 'after-download' || rawAvail === 'downloadable') {
27
+ modelDisplayStatus = 'downloadable';
28
+ } else if (rawAvail === 'downloading') {
29
+ modelDisplayStatus = 'downloading';
30
+ } else if (rawAvail === 'no') {
31
+ modelDisplayStatus = 'unavailable';
32
+ }
33
+
34
+ if (options.json) {
35
+ console.log(JSON.stringify({
36
+ chrome: platformInfo.chromeVersion || 'Unknown',
37
+ platform: platformInfo.platformLabel,
38
+ arch: platformInfo.arch,
39
+ builtInAi: status.builtInAiAvailable ? 'available' : 'unavailable',
40
+ languageModel: status.languageModelAvailable ? 'available' : 'unavailable',
41
+ model: modelDisplayStatus,
42
+ execution: 'on-device',
43
+ daemon: daemon ? { status: 'running', pid: daemon.pid, port: daemon.port } : { status: 'stopped' },
44
+ details: status
45
+ }, null, 2));
46
+ return;
47
+ }
48
+
49
+ log(style('NanoBridge', 'bold'));
50
+ log('');
51
+ log(`Chrome ${style(platformInfo.chromeVersion || 'Not found', platformInfo.chromeVersion ? 'cyan' : 'red')}`);
52
+ log(`Platform ${platformInfo.platformLabel} ${platformInfo.arch}`);
53
+ log(`Built-in AI ${style(status.builtInAiAvailable ? 'available' : 'unavailable', status.builtInAiAvailable ? 'green' : 'red')}`);
54
+ log(`LanguageModel ${style(status.languageModelAvailable ? 'available' : 'unavailable', status.languageModelAvailable ? 'green' : 'red')}`);
55
+ log(`Model ${style(modelDisplayStatus, modelDisplayStatus === 'ready' ? 'green' : 'yellow')}`);
56
+ log(`Execution ${style('on-device', 'green')}`);
57
+ log(`Daemon ${daemon ? style(`running (PID: ${daemon.pid}, port: ${daemon.port})`, 'green') : style('stopped', 'dim')}`);
58
+
59
+ if (modelDisplayStatus === 'downloadable') {
60
+ log('');
61
+ log(`Run ${style('nanobridge download', 'bold')} to download on-device Gemini Nano components.`);
62
+ }
63
+ } catch (err) {
64
+ if (options.json) {
65
+ console.log(JSON.stringify({
66
+ error: err.message,
67
+ code: err.code || 'UNKNOWN_ERROR'
68
+ }, null, 2));
69
+ } else {
70
+ logError(style('NanoBridge Status Error:', 'red'));
71
+ logError(err.message);
72
+ }
73
+ throw err;
74
+ } finally {
75
+ if (bridge) await bridge.close();
76
+ if (chromeInstance) chromeInstance.close();
77
+ }
78
+ }
@@ -0,0 +1,186 @@
1
+ import http from 'node:http';
2
+ import { spawn } from 'node:child_process';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { getDaemonState, clearDaemonState } from './state.js';
6
+ import { debug } from '../utils/output.js';
7
+
8
+ const __filename = fileURLToPath(import.meta.url);
9
+ const __dirname = path.dirname(__filename);
10
+ const SERVER_SCRIPT = path.join(__dirname, 'server.js');
11
+
12
+ function isPidRunning(pid) {
13
+ try {
14
+ process.kill(pid, 0);
15
+ return true;
16
+ } catch (_) {
17
+ return false;
18
+ }
19
+ }
20
+
21
+ export async function pingDaemon(port, timeoutMs = 3000) {
22
+ return new Promise((resolve) => {
23
+ const req = http.request(`http://127.0.0.1:${port}/status`, { timeout: timeoutMs }, (res) => {
24
+ if (res.statusCode === 200) {
25
+ let body = '';
26
+ res.on('data', (c) => { body += c; });
27
+ res.on('end', () => {
28
+ try {
29
+ resolve(JSON.parse(body));
30
+ } catch (_) {
31
+ resolve(null);
32
+ }
33
+ });
34
+ } else {
35
+ resolve(null);
36
+ }
37
+ });
38
+ req.on('error', () => resolve(null));
39
+ req.on('timeout', () => { req.destroy(); resolve(null); });
40
+ req.end();
41
+ });
42
+ }
43
+
44
+ export async function getActiveDaemon() {
45
+ const state = getDaemonState();
46
+ if (!state || !state.pid) return null;
47
+
48
+ if (!isPidRunning(state.pid)) {
49
+ clearDaemonState();
50
+ return null;
51
+ }
52
+
53
+ if (state.port) {
54
+ const health = await pingDaemon(state.port, 2000);
55
+ if (health && health.status === 'ready') {
56
+ return { ...state, ...health };
57
+ }
58
+ }
59
+
60
+ // If PID is running, wait a moment for startup to finish
61
+ const start = Date.now();
62
+ while (Date.now() - start < 8000) {
63
+ await new Promise((r) => setTimeout(r, 400));
64
+ const currentState = getDaemonState();
65
+ if (!currentState || !currentState.port) continue;
66
+ const health = await pingDaemon(currentState.port, 1500);
67
+ if (health && health.status === 'ready') {
68
+ return { ...currentState, ...health };
69
+ }
70
+ }
71
+
72
+ return null;
73
+ }
74
+
75
+ export async function startDaemonInBackground() {
76
+ debug('client', 'Spawning daemon process in background:', SERVER_SCRIPT);
77
+
78
+ clearDaemonState();
79
+
80
+ const env = { ...process.env };
81
+ const child = spawn(process.execPath, [SERVER_SCRIPT], {
82
+ detached: true,
83
+ stdio: 'ignore',
84
+ env
85
+ });
86
+ child.unref();
87
+
88
+ debug('client', `Spawned daemon child PID: ${child.pid}. Waiting for readiness...`);
89
+
90
+ // Poll until daemon is ready
91
+ const startTime = Date.now();
92
+ const maxWaitMs = 35000;
93
+
94
+ while (Date.now() - startTime < maxWaitMs) {
95
+ const state = getDaemonState();
96
+ if (state && state.port) {
97
+ const ping = await pingDaemon(state.port);
98
+ if (ping && ping.status === 'ready') {
99
+ debug('client', `Daemon is ready on port ${state.port} in ${Date.now() - startTime}ms`);
100
+ return { ...state, ...ping };
101
+ }
102
+ }
103
+ await new Promise((r) => setTimeout(r, 300));
104
+ }
105
+
106
+ throw new Error('Timed out waiting for NanoBridge daemon to start');
107
+ }
108
+
109
+ export async function ensureDaemon() {
110
+ const active = await getActiveDaemon();
111
+ if (active) return active;
112
+ return await startDaemonInBackground();
113
+ }
114
+
115
+ export async function streamPromptFromDaemon({ port, promptText, systemPrompt, stream = true, onChunk } = {}) {
116
+ return new Promise((resolve, reject) => {
117
+ const payload = JSON.stringify({ promptText, systemPrompt, stream });
118
+ const req = http.request(`http://127.0.0.1:${port}/prompt`, {
119
+ method: 'POST',
120
+ headers: {
121
+ 'Content-Type': 'application/json',
122
+ 'Content-Length': Buffer.byteLength(payload)
123
+ }
124
+ }, (res) => {
125
+ let buffer = '';
126
+ let finalText = '';
127
+
128
+ res.on('data', (chunk) => {
129
+ buffer += chunk.toString('utf8');
130
+ const lines = buffer.split('\n');
131
+ buffer = lines.pop(); // Keep partial line in buffer
132
+
133
+ for (const line of lines) {
134
+ if (!line.trim()) continue;
135
+ try {
136
+ const data = JSON.parse(line);
137
+ if (data.type === 'chunk' && onChunk) {
138
+ onChunk(data.delta, data.full);
139
+ } else if (data.type === 'done') {
140
+ finalText = data.text;
141
+ } else if (data.type === 'error') {
142
+ reject(new Error(data.error));
143
+ return;
144
+ }
145
+ } catch (_) {}
146
+ }
147
+ });
148
+
149
+ res.on('end', () => {
150
+ resolve(finalText);
151
+ });
152
+ });
153
+
154
+ req.on('socket', (socket) => {
155
+ socket.setNoDelay(true);
156
+ });
157
+
158
+ req.on('error', reject);
159
+ req.write(payload);
160
+ req.end();
161
+ });
162
+ }
163
+
164
+ export async function stopDaemon() {
165
+ const active = await getActiveDaemon();
166
+ if (!active) {
167
+ clearDaemonState();
168
+ return { stopped: true, wasRunning: false };
169
+ }
170
+
171
+ return new Promise((resolve) => {
172
+ const req = http.request(`http://127.0.0.1:${active.port}/stop`, { method: 'POST', timeout: 2000 }, (res) => {
173
+ clearDaemonState();
174
+ resolve({ stopped: true, wasRunning: true, pid: active.pid });
175
+ });
176
+ req.on('error', () => {
177
+ // Force kill if HTTP request fails
178
+ try {
179
+ if (active.pid) process.kill(active.pid, 'SIGKILL');
180
+ } catch (_) {}
181
+ clearDaemonState();
182
+ resolve({ stopped: true, wasRunning: true, pid: active.pid });
183
+ });
184
+ req.end();
185
+ });
186
+ }