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,494 @@
1
+ import http from 'node:http';
2
+ import process from 'node:process';
3
+ import crypto from 'node:crypto';
4
+ import { launchChrome } from '../chrome/launch.js';
5
+ import { ChromeBridge } from '../chrome/bridge.js';
6
+ import { saveDaemonState, clearDaemonState } from './state.js';
7
+ import {
8
+ parseChatMessages,
9
+ formatModelsList,
10
+ formatChatCompletion,
11
+ formatChatCompletionChunk
12
+ } from '../api/openai.js';
13
+ import { debug, setDebugMode } from '../utils/output.js';
14
+
15
+ const DEFAULT_IDLE_TIMEOUT_MS = 10 * 60 * 1000; // 10 minutes
16
+
17
+ export class DaemonServer {
18
+ constructor(options = {}) {
19
+ this.options = options;
20
+ this.server = null;
21
+ this.port = options.port || 0;
22
+ this.host = options.host || '127.0.0.1';
23
+ this.chromeInstance = null;
24
+ this.bridge = null;
25
+ this.idleTimeoutMs = options.idleTimeoutMs !== undefined ? options.idleTimeoutMs : DEFAULT_IDLE_TIMEOUT_MS;
26
+ this.idleTimer = null;
27
+ this.startTime = Date.now();
28
+ this.isStopping = false;
29
+ this.isWarmed = false;
30
+ this.isInitializing = false;
31
+ }
32
+
33
+ resetIdleTimer() {
34
+ if (this.idleTimer) clearTimeout(this.idleTimer);
35
+ if (this.idleTimeoutMs > 0) {
36
+ this.idleTimer = setTimeout(() => {
37
+ debug('daemon', 'Daemon idle timeout reached. Shutting down...');
38
+ this.stop();
39
+ }, this.idleTimeoutMs);
40
+ if (this.idleTimer.unref) this.idleTimer.unref();
41
+ }
42
+ }
43
+
44
+ async initChrome() {
45
+ if (this.isInitializing) return;
46
+ this.isInitializing = true;
47
+ debug('daemon', 'Initializing / recovering Chrome instance and CDP bridge...');
48
+
49
+ if (this.bridge) {
50
+ try { await this.bridge.close(); } catch (_) {}
51
+ this.bridge = null;
52
+ }
53
+ if (this.chromeInstance) {
54
+ try { this.chromeInstance.close(); } catch (_) {}
55
+ this.chromeInstance = null;
56
+ }
57
+
58
+ try {
59
+ this.chromeInstance = await launchChrome(this.options);
60
+ this.bridge = new ChromeBridge(this.chromeInstance);
61
+ await this.bridge.connect();
62
+ } finally {
63
+ this.isInitializing = false;
64
+ }
65
+ }
66
+
67
+ async ensureReady() {
68
+ if (!this.bridge || !this.bridge.isConnected() || !this.chromeInstance) {
69
+ debug('daemon', 'Bridge not connected (possibly after OS sleep). Reconnecting Chrome...');
70
+ await this.initChrome();
71
+ }
72
+ }
73
+
74
+ async start() {
75
+ debug('daemon', 'Starting background Chrome daemon...');
76
+
77
+ // 1. Launch Chrome and bridge
78
+ await this.initChrome();
79
+
80
+ // 2. Start HTTP server and write state immediately
81
+ this.server = http.createServer((req, res) => this.handleRequest(req, res));
82
+
83
+ await new Promise((resolve, reject) => {
84
+ this.server.listen(this.port, this.host, () => {
85
+ this.port = this.server.address().port;
86
+ resolve();
87
+ });
88
+ this.server.on('error', reject);
89
+ });
90
+
91
+ saveDaemonState({
92
+ pid: process.pid,
93
+ port: this.port,
94
+ host: this.host,
95
+ startTime: this.startTime,
96
+ chromePid: this.chromeInstance?.pid
97
+ });
98
+
99
+ debug('daemon', `Daemon listening on http://${this.host}:${this.port} (PID: ${process.pid})`);
100
+
101
+ // 3. Warm up session in background
102
+ this.warmupSession().catch((err) => {
103
+ debug('daemon', 'Warmup background error:', err.message);
104
+ });
105
+
106
+ this.resetIdleTimer();
107
+
108
+ const cleanup = () => this.stop();
109
+ process.on('SIGINT', cleanup);
110
+ process.on('SIGTERM', cleanup);
111
+ process.on('exit', () => clearDaemonState());
112
+ }
113
+
114
+ async warmupSession() {
115
+ this.warmupPromise = (async () => {
116
+ debug('daemon', 'Warming up LanguageModel on-device model in Chrome...');
117
+ try {
118
+ if (this.bridge && this.bridge.isConnected()) {
119
+ await this.bridge.evaluate(`(async () => {
120
+ if ('LanguageModel' in window) {
121
+ const s = await window.LanguageModel.create();
122
+ if (s && typeof s.destroy === 'function') s.destroy();
123
+ }
124
+ })()`, { userGesture: true });
125
+ this.isWarmed = true;
126
+ debug('daemon', 'Warmup completed successfully.');
127
+ }
128
+ } catch (warmErr) {
129
+ debug('daemon', 'Warmup notice:', warmErr.message);
130
+ }
131
+ })();
132
+ return this.warmupPromise;
133
+ }
134
+
135
+ setCorsHeaders(res) {
136
+ res.setHeader('Access-Control-Allow-Origin', '*');
137
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
138
+ res.setHeader('Access-Control-Allow-Headers', 'Authorization, Content-Type, Accept, Origin, User-Agent, X-Requested-With');
139
+ }
140
+
141
+ async handleRequest(req, res) {
142
+ this.resetIdleTimer();
143
+ this.setCorsHeaders(res);
144
+
145
+ if (req.method === 'OPTIONS') {
146
+ res.writeHead(204);
147
+ res.end();
148
+ return;
149
+ }
150
+
151
+ const url = new URL(req.url, `http://${this.host}:${this.port}`);
152
+
153
+ // Standard Health/Status
154
+ if (req.method === 'GET' && (url.pathname === '/status' || url.pathname === '/health')) {
155
+ const bridgeConnected = Boolean(this.bridge && this.bridge.isConnected());
156
+ res.writeHead(200, { 'Content-Type': 'application/json' });
157
+ res.end(JSON.stringify({
158
+ status: 'ready',
159
+ pid: process.pid,
160
+ port: this.port,
161
+ host: this.host,
162
+ uptimeMs: Date.now() - this.startTime,
163
+ warmed: this.isWarmed,
164
+ bridgeConnected,
165
+ openai_base_url: `http://${this.host}:${this.port}/v1`
166
+ }));
167
+ return;
168
+ }
169
+
170
+ // Stop Daemon
171
+ if (req.method === 'POST' && url.pathname === '/stop') {
172
+ res.writeHead(200, { 'Content-Type': 'application/json' });
173
+ res.end(JSON.stringify({ stopped: true }));
174
+ setTimeout(() => this.stop(), 50);
175
+ return;
176
+ }
177
+
178
+ // OpenAI Models Endpoint
179
+ if (req.method === 'GET' && url.pathname === '/v1/models') {
180
+ res.writeHead(200, { 'Content-Type': 'application/json' });
181
+ res.end(JSON.stringify(formatModelsList(), null, 2));
182
+ return;
183
+ }
184
+
185
+ // OpenAI Chat Completions Endpoint
186
+ if (req.method === 'POST' && url.pathname === '/v1/chat/completions') {
187
+ let body = '';
188
+ req.on('data', (chunk) => { body += chunk; });
189
+ req.on('end', async () => {
190
+ const reqId = `chatcmpl-${crypto.randomBytes(8).toString('hex')}`;
191
+ let isClientClosed = false;
192
+ res.on('close', () => {
193
+ if (!res.writableEnded) {
194
+ isClientClosed = true;
195
+ this.cancelPrompt(reqId);
196
+ }
197
+ });
198
+
199
+ try {
200
+ await this.ensureReady();
201
+
202
+ const payload = JSON.parse(body || '{}');
203
+ const messages = payload.messages || [];
204
+ const model = payload.model || 'gemini-nano';
205
+ const stream = payload.stream === true;
206
+ const { systemPrompt, promptText } = parseChatMessages(messages);
207
+
208
+ if (stream) {
209
+ if (res.socket) res.socket.setNoDelay(true);
210
+ if (req.socket) req.socket.setNoDelay(true);
211
+
212
+ res.writeHead(200, {
213
+ 'Content-Type': 'text/event-stream; charset=utf-8',
214
+ 'Cache-Control': 'no-cache',
215
+ 'Connection': 'keep-alive'
216
+ });
217
+ if (typeof res.flushHeaders === 'function') res.flushHeaders();
218
+
219
+ let isFirst = true;
220
+ const onDelta = (delta) => {
221
+ if (isClientClosed) return;
222
+ if (!delta && !isFirst) return;
223
+ const chunk = formatChatCompletionChunk({
224
+ id: reqId,
225
+ model,
226
+ delta,
227
+ isFirst
228
+ });
229
+ isFirst = false;
230
+ res.write(`data: ${JSON.stringify(chunk)}\n\n`);
231
+ };
232
+
233
+ await this.promptWithRetry({
234
+ promptText,
235
+ systemPrompt,
236
+ stream: true,
237
+ requestId: reqId,
238
+ onChunk: (delta) => onDelta(delta)
239
+ });
240
+
241
+ if (!isClientClosed) {
242
+ const lastChunk = formatChatCompletionChunk({
243
+ id: reqId,
244
+ model,
245
+ delta: '',
246
+ isLast: true
247
+ });
248
+ res.write(`data: ${JSON.stringify(lastChunk)}\n\n`);
249
+ res.write('data: [DONE]\n\n');
250
+ res.end();
251
+ }
252
+ } else {
253
+ const resultText = await this.promptWithRetry({
254
+ promptText,
255
+ systemPrompt,
256
+ stream: false,
257
+ requestId: reqId
258
+ });
259
+
260
+ if (!isClientClosed) {
261
+ res.writeHead(200, { 'Content-Type': 'application/json' });
262
+ res.end(JSON.stringify(formatChatCompletion({
263
+ id: reqId,
264
+ model,
265
+ content: resultText
266
+ }), null, 2));
267
+ }
268
+ }
269
+ } catch (err) {
270
+ if (!isClientClosed) {
271
+ res.writeHead(500, { 'Content-Type': 'application/json' });
272
+ res.end(JSON.stringify({
273
+ error: {
274
+ message: err.message,
275
+ type: 'nanobridge_error',
276
+ code: 'inference_error'
277
+ }
278
+ }));
279
+ }
280
+ }
281
+ });
282
+ return;
283
+ }
284
+
285
+ // Native NanoBridge /prompt Endpoint
286
+ if (req.method === 'POST' && url.pathname === '/prompt') {
287
+ let body = '';
288
+ req.on('data', (chunk) => { body += chunk; });
289
+ req.on('end', async () => {
290
+ const reqId = `req_${crypto.randomBytes(8).toString('hex')}`;
291
+ let isClientClosed = false;
292
+ res.on('close', () => {
293
+ if (!res.writableEnded) {
294
+ isClientClosed = true;
295
+ this.cancelPrompt(reqId);
296
+ }
297
+ });
298
+
299
+ try {
300
+ await this.ensureReady();
301
+
302
+ const payload = JSON.parse(body || '{}');
303
+ const promptText = payload.promptText || '';
304
+ const systemPrompt = payload.systemPrompt;
305
+ const stream = payload.stream !== false;
306
+
307
+ if (res.socket) res.socket.setNoDelay(true);
308
+ if (req.socket) req.socket.setNoDelay(true);
309
+
310
+ res.writeHead(200, {
311
+ 'Content-Type': 'application/x-ndjson',
312
+ 'Transfer-Encoding': 'chunked',
313
+ 'Cache-Control': 'no-cache',
314
+ 'Connection': 'keep-alive'
315
+ });
316
+ if (typeof res.flushHeaders === 'function') {
317
+ res.flushHeaders();
318
+ }
319
+
320
+ const sendChunk = (delta, full) => {
321
+ if (isClientClosed) return;
322
+ try {
323
+ res.write(JSON.stringify({ type: 'chunk', delta, full }) + '\n');
324
+ } catch (_) {}
325
+ };
326
+
327
+ const fullResult = await this.promptWithRetry({
328
+ promptText,
329
+ systemPrompt,
330
+ stream,
331
+ requestId: reqId,
332
+ onChunk: (delta, full) => sendChunk(delta, full)
333
+ });
334
+
335
+ if (!isClientClosed) {
336
+ res.write(JSON.stringify({ type: 'done', text: fullResult }) + '\n');
337
+ res.end();
338
+ }
339
+ } catch (err) {
340
+ if (!isClientClosed) {
341
+ try {
342
+ res.write(JSON.stringify({ type: 'error', error: err.message }) + '\n');
343
+ res.end();
344
+ } catch (_) {}
345
+ }
346
+ }
347
+ });
348
+ return;
349
+ }
350
+
351
+ res.writeHead(404, { 'Content-Type': 'application/json' });
352
+ res.end(JSON.stringify({ error: 'Not Found' }));
353
+ }
354
+
355
+ async runExclusive(task) {
356
+ const prev = this.currentPromptPromise || Promise.resolve();
357
+ let resolveTask;
358
+ this.currentPromptPromise = new Promise((r) => { resolveTask = r; });
359
+ try {
360
+ await prev.catch(() => {});
361
+ return await task();
362
+ } finally {
363
+ resolveTask();
364
+ }
365
+ }
366
+
367
+ async promptWithRetry(args) {
368
+ return this.runExclusive(async () => {
369
+ try {
370
+ return await this.prompt(args);
371
+ } catch (err) {
372
+ debug('daemon', 'Prompt execution failed, attempting self-healing reconnect:', err.message);
373
+ await this.initChrome();
374
+ return await this.prompt(args);
375
+ }
376
+ });
377
+ }
378
+
379
+ async prompt({ promptText, systemPrompt, stream = true, onChunk, requestId } = {}) {
380
+ if (this.warmupPromise) {
381
+ await this.warmupPromise.catch(() => {});
382
+ }
383
+
384
+ const reqId = requestId || `req_${Date.now()}_${Math.random().toString(36).slice(2)}`;
385
+ const escapedPrompt = JSON.stringify(promptText);
386
+ const createArgs = systemPrompt ? JSON.stringify({ systemPrompt }) : '';
387
+ const prefix = `__NANOBRIDGE_CHUNK_${reqId}__:`;
388
+
389
+ if (stream && onChunk) {
390
+ this.bridge.addConsoleHandler(prefix, (payload) => {
391
+ try {
392
+ const data = JSON.parse(payload);
393
+ if (data.d) {
394
+ onChunk(data.d);
395
+ }
396
+ } catch (err) {
397
+ debug('daemon', 'Error in stream chunk handler:', err.message);
398
+ }
399
+ });
400
+ }
401
+
402
+ try {
403
+ const evalResult = await this.bridge.evaluate(`(async () => {
404
+ try {
405
+ if (!('LanguageModel' in window)) {
406
+ return { success: false, error: 'LanguageModel API not available' };
407
+ }
408
+ window.__nanobridge_current_req = '${reqId}';
409
+ const session = await window.LanguageModel.create(${createArgs});
410
+
411
+ const stream = session.promptStreaming(${escapedPrompt});
412
+ let finalResult = '';
413
+ let prev = '';
414
+ for await (const chunk of stream) {
415
+ if (window.__nanobridge_abort_req === '${reqId}') {
416
+ if (typeof session.destroy === 'function') session.destroy();
417
+ return { success: false, error: 'Request cancelled' };
418
+ }
419
+ finalResult = chunk;
420
+ const delta = chunk.startsWith(prev) ? chunk.slice(prev.length) : chunk;
421
+ prev = chunk;
422
+ console.debug('${prefix}' + JSON.stringify({ d: delta }));
423
+ }
424
+
425
+ if (typeof session.destroy === 'function') {
426
+ session.destroy();
427
+ }
428
+
429
+ return { success: true, text: finalResult };
430
+ } catch (e) {
431
+ return { success: false, error: e.message };
432
+ }
433
+ })()`, { userGesture: true });
434
+
435
+ if (!evalResult.success) {
436
+ throw new Error(evalResult.error);
437
+ }
438
+ return evalResult.text;
439
+ } finally {
440
+ if (stream && onChunk) {
441
+ this.bridge.removeConsoleHandler(prefix);
442
+ }
443
+ }
444
+ }
445
+
446
+ async cancelPrompt(reqId) {
447
+ try {
448
+ if (this.bridge && this.bridge.isConnected()) {
449
+ await this.bridge.evaluate(`window.__nanobridge_abort_req = '${reqId}';`);
450
+ }
451
+ } catch (_) {}
452
+ }
453
+
454
+ async stop() {
455
+ if (this.isStopping) return;
456
+ this.isStopping = true;
457
+ debug('daemon', 'Stopping NanoBridge Daemon...');
458
+
459
+ if (this.idleTimer) clearTimeout(this.idleTimer);
460
+ clearDaemonState();
461
+
462
+ if (this.server) {
463
+ try {
464
+ this.server.close();
465
+ } catch (_) {}
466
+ this.server = null;
467
+ }
468
+
469
+ if (this.bridge) {
470
+ await this.bridge.close().catch(() => {});
471
+ this.bridge = null;
472
+ }
473
+
474
+ if (this.chromeInstance) {
475
+ this.chromeInstance.close();
476
+ this.chromeInstance = null;
477
+ }
478
+
479
+ debug('daemon', 'Daemon stopped successfully.');
480
+ process.exit(0);
481
+ }
482
+ }
483
+
484
+ // If executed directly (via background spawn)
485
+ if (process.argv[1] && process.argv[1].endsWith('daemon/server.js')) {
486
+ if (process.env.NANOBRIDGE_DEBUG === '1') {
487
+ setDebugMode(true);
488
+ }
489
+ const daemon = new DaemonServer();
490
+ daemon.start().catch((err) => {
491
+ console.error('Failed to start daemon:', err);
492
+ process.exit(1);
493
+ });
494
+ }
@@ -0,0 +1,49 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import process from 'node:process';
5
+
6
+ const CONFIG_DIR = path.join(os.homedir(), '.nanobridge');
7
+ const STATE_FILE = path.join(CONFIG_DIR, 'daemon.json');
8
+
9
+ export function getDaemonState() {
10
+ try {
11
+ if (fs.existsSync(STATE_FILE)) {
12
+ const data = JSON.parse(fs.readFileSync(STATE_FILE, 'utf8'));
13
+ if (data && data.pid) {
14
+ // Check if process is still alive
15
+ try {
16
+ process.kill(data.pid, 0);
17
+ return data;
18
+ } catch (_) {
19
+ // Process not alive, stale file
20
+ clearDaemonState();
21
+ return null;
22
+ }
23
+ }
24
+ }
25
+ } catch (_) {
26
+ clearDaemonState();
27
+ }
28
+ return null;
29
+ }
30
+
31
+ export function saveDaemonState(state) {
32
+ try {
33
+ if (!fs.existsSync(CONFIG_DIR)) {
34
+ fs.mkdirSync(CONFIG_DIR, { recursive: true });
35
+ }
36
+ fs.writeFileSync(STATE_FILE, JSON.stringify(state, null, 2), 'utf8');
37
+ } catch (_) {}
38
+ }
39
+
40
+ export function clearDaemonState() {
41
+ try {
42
+ if (fs.existsSync(STATE_FILE)) {
43
+ fs.unlinkSync(STATE_FILE);
44
+ }
45
+ if (fs.existsSync(LEGACY_STATE_FILE)) {
46
+ fs.unlinkSync(LEGACY_STATE_FILE);
47
+ }
48
+ } catch (_) {}
49
+ }
@@ -0,0 +1,26 @@
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
+ }
@@ -0,0 +1,77 @@
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 in user input
48
+ * e.g. "Explain @src/cli.js please" -> extracts file and attaches as context
49
+ */
50
+ export function extractAndAttachFiles(input) {
51
+ const fileRegex = /@([^\s"']+)/g;
52
+ const attachedFiles = [];
53
+ let cleanedInput = input;
54
+ let match;
55
+
56
+ while ((match = fileRegex.exec(input)) !== null) {
57
+ const candidatePath = match[1];
58
+ try {
59
+ const fileInfo = readFileContent(candidatePath);
60
+ attachedFiles.push(fileInfo);
61
+ cleanedInput = cleanedInput.replace(match[0], `[File: ${fileInfo.relativePath}]`);
62
+ } catch (_) {
63
+ // If file doesn't exist or fails to read, keep raw string
64
+ }
65
+ }
66
+
67
+ let finalPrompt = cleanedInput;
68
+ if (attachedFiles.length > 0) {
69
+ const filesContext = attachedFiles.map(formatFileAsContext).join('\n\n');
70
+ finalPrompt = `${filesContext}\n\n${cleanedInput}`;
71
+ }
72
+
73
+ return {
74
+ finalPrompt,
75
+ attachedFiles
76
+ };
77
+ }
@@ -0,0 +1,59 @@
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
+ }