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.
Files changed (143) hide show
  1. package/README.md +86 -230
  2. package/bin/nanobridge.js +1 -1
  3. package/dist/api/openai.d.ts +135 -0
  4. package/dist/api/openai.js +210 -0
  5. package/dist/api/openai.js.map +1 -0
  6. package/dist/benchmark/runner.d.ts +27 -0
  7. package/dist/benchmark/runner.js +37 -0
  8. package/dist/benchmark/runner.js.map +1 -0
  9. package/dist/benchmark/stats.d.ts +10 -0
  10. package/dist/benchmark/stats.js +33 -0
  11. package/dist/benchmark/stats.js.map +1 -0
  12. package/dist/bin/nanobridge.d.ts +2 -0
  13. package/dist/bin/nanobridge.js +4 -0
  14. package/dist/bin/nanobridge.js.map +1 -0
  15. package/dist/chat/commands.d.ts +9 -0
  16. package/dist/chat/commands.js +52 -0
  17. package/dist/chat/commands.js.map +1 -0
  18. package/dist/chat/config.d.ts +22 -0
  19. package/dist/chat/config.js +55 -0
  20. package/dist/chat/config.js.map +1 -0
  21. package/dist/chat/history.d.ts +12 -0
  22. package/dist/chat/history.js +74 -0
  23. package/dist/chat/history.js.map +1 -0
  24. package/dist/chat/session.d.ts +42 -0
  25. package/dist/chat/session.js +107 -0
  26. package/dist/chat/session.js.map +1 -0
  27. package/dist/chat/storage.d.ts +17 -0
  28. package/dist/chat/storage.js +71 -0
  29. package/dist/chat/storage.js.map +1 -0
  30. package/dist/cli.d.ts +7 -0
  31. package/dist/cli.js +363 -0
  32. package/dist/cli.js.map +1 -0
  33. package/dist/commands/ask.d.ts +4 -0
  34. package/dist/commands/ask.js +288 -0
  35. package/dist/commands/ask.js.map +1 -0
  36. package/dist/commands/bench.d.ts +2 -0
  37. package/dist/commands/bench.js +92 -0
  38. package/dist/commands/bench.js.map +1 -0
  39. package/dist/commands/chat.d.ts +2 -0
  40. package/dist/commands/chat.js +701 -0
  41. package/dist/commands/chat.js.map +1 -0
  42. package/dist/commands/config.d.ts +2 -0
  43. package/dist/commands/config.js +102 -0
  44. package/dist/commands/config.js.map +1 -0
  45. package/dist/commands/daemon.d.ts +2 -0
  46. package/dist/commands/daemon.js +225 -0
  47. package/dist/commands/daemon.js.map +1 -0
  48. package/dist/commands/embed.d.ts +2 -0
  49. package/dist/commands/embed.js +79 -0
  50. package/dist/commands/embed.js.map +1 -0
  51. package/dist/commands/models.d.ts +5 -0
  52. package/dist/commands/models.js +244 -0
  53. package/dist/commands/models.js.map +1 -0
  54. package/dist/commands/serve.d.ts +2 -0
  55. package/dist/commands/serve.js +52 -0
  56. package/dist/commands/serve.js.map +1 -0
  57. package/dist/commands/status.d.ts +2 -0
  58. package/dist/commands/status.js +81 -0
  59. package/dist/commands/status.js.map +1 -0
  60. package/dist/daemon/client.d.ts +74 -0
  61. package/dist/daemon/client.js +447 -0
  62. package/dist/daemon/client.js.map +1 -0
  63. package/dist/daemon/server.d.ts +43 -0
  64. package/dist/daemon/server.js +661 -0
  65. package/dist/daemon/server.js.map +1 -0
  66. package/dist/daemon/service.d.ts +29 -0
  67. package/dist/daemon/service.js +173 -0
  68. package/dist/daemon/service.js.map +1 -0
  69. package/dist/daemon/state.d.ts +4 -0
  70. package/dist/daemon/state.js +54 -0
  71. package/dist/daemon/state.js.map +1 -0
  72. package/dist/engine/llama-engine.d.ts +49 -0
  73. package/dist/engine/llama-engine.js +465 -0
  74. package/dist/engine/llama-engine.js.map +1 -0
  75. package/dist/engine/model-pool.d.ts +36 -0
  76. package/dist/engine/model-pool.js +202 -0
  77. package/dist/engine/model-pool.js.map +1 -0
  78. package/dist/engine/sampling.d.ts +13 -0
  79. package/dist/engine/sampling.js +43 -0
  80. package/dist/engine/sampling.js.map +1 -0
  81. package/dist/models/catalog.d.ts +6 -0
  82. package/dist/models/catalog.js +124 -0
  83. package/dist/models/catalog.js.map +1 -0
  84. package/dist/models/config.d.ts +10 -0
  85. package/dist/models/config.js +141 -0
  86. package/dist/models/config.js.map +1 -0
  87. package/dist/models/downloader.d.ts +21 -0
  88. package/dist/models/downloader.js +98 -0
  89. package/dist/models/downloader.js.map +1 -0
  90. package/dist/models/profiles.d.ts +10 -0
  91. package/dist/models/profiles.js +68 -0
  92. package/dist/models/profiles.js.map +1 -0
  93. package/dist/models/store.d.ts +9 -0
  94. package/dist/models/store.js +142 -0
  95. package/dist/models/store.js.map +1 -0
  96. package/dist/types.d.ts +189 -0
  97. package/dist/types.js +2 -0
  98. package/dist/types.js.map +1 -0
  99. package/dist/utils/errors.d.ts +18 -0
  100. package/dist/utils/errors.js +33 -0
  101. package/dist/utils/errors.js.map +1 -0
  102. package/dist/utils/files.d.ts +14 -0
  103. package/dist/utils/files.js +88 -0
  104. package/dist/utils/files.js.map +1 -0
  105. package/dist/utils/output.d.ts +29 -0
  106. package/dist/utils/output.js +116 -0
  107. package/dist/utils/output.js.map +1 -0
  108. package/package.json +28 -11
  109. package/examples/openai-client.js +0 -112
  110. package/examples/openai-sdk.js +0 -46
  111. package/examples/openai_python.py +0 -42
  112. package/src/api/openai.js +0 -115
  113. package/src/benchmark/runner.js +0 -48
  114. package/src/benchmark/stats.js +0 -33
  115. package/src/chat/commands.js +0 -68
  116. package/src/chat/config.js +0 -65
  117. package/src/chat/history.js +0 -103
  118. package/src/chat/session.js +0 -337
  119. package/src/chrome/bridge.js +0 -473
  120. package/src/chrome/capabilities.js +0 -99
  121. package/src/chrome/detect.js +0 -199
  122. package/src/chrome/launch.js +0 -248
  123. package/src/cli.js +0 -216
  124. package/src/commands/ask.js +0 -217
  125. package/src/commands/bench.js +0 -79
  126. package/src/commands/chat.js +0 -426
  127. package/src/commands/daemon.js +0 -89
  128. package/src/commands/download.js +0 -71
  129. package/src/commands/serve.js +0 -56
  130. package/src/commands/status.js +0 -87
  131. package/src/daemon/client.js +0 -274
  132. package/src/daemon/server.js +0 -650
  133. package/src/daemon/state.js +0 -46
  134. package/src/utils/errors.js +0 -26
  135. package/src/utils/files.js +0 -93
  136. package/src/utils/output.js +0 -107
  137. package/test/chat.test.js +0 -252
  138. package/test/cli.test.js +0 -49
  139. package/test/daemon.test.js +0 -31
  140. package/test/detect.test.js +0 -24
  141. package/test/files.test.js +0 -41
  142. package/test/openai.test.js +0 -63
  143. package/test/stats.test.js +0 -29
@@ -0,0 +1,661 @@
1
+ import http from 'node:http';
2
+ import process from 'node:process';
3
+ import crypto from 'node:crypto';
4
+ import { WarmModelPool } from '../engine/model-pool.js';
5
+ import { loadConfig } from '../models/config.js';
6
+ import { listInstalledModels } from '../models/store.js';
7
+ import { saveDaemonState, clearDaemonState } from './state.js';
8
+ import { parseChatMessages, formatModelsList, formatChatCompletion, formatChatCompletionChunk, formatTextCompletion, formatTextCompletionChunk, formatEmbeddingsResponse } from '../api/openai.js';
9
+ import { debug, setDebugMode } from '../utils/output.js';
10
+ function readRequestBody(req) {
11
+ return new Promise((resolve, reject) => {
12
+ let body = '';
13
+ req.on('data', (chunk) => {
14
+ body += chunk;
15
+ });
16
+ req.on('end', () => resolve(body));
17
+ req.on('error', reject);
18
+ });
19
+ }
20
+ export class DaemonServer {
21
+ options;
22
+ server = null;
23
+ port;
24
+ host;
25
+ pool;
26
+ idleTimeoutMs;
27
+ idleTimer = null;
28
+ startTime;
29
+ isStopping = false;
30
+ isWarmed = false;
31
+ status = 'starting';
32
+ phase = 'initializing';
33
+ lastError = null;
34
+ gpuBackend = false;
35
+ chatStats = null;
36
+ initPromise = null;
37
+ persistState;
38
+ exitOnStop;
39
+ constructor(options = {}) {
40
+ const cfg = loadConfig();
41
+ this.options = options;
42
+ this.port = options.port ?? (Number(process.env.NANOBRIDGE_PORT) || 0);
43
+ this.host = options.host || '127.0.0.1';
44
+ this.pool = options.pool || new WarmModelPool();
45
+ this.idleTimeoutMs =
46
+ options.idleTimeoutMs !== undefined ? options.idleTimeoutMs : cfg.idleTimeoutMs;
47
+ this.startTime = Date.now();
48
+ this.persistState = options.persistState !== false;
49
+ this.exitOnStop = options.exitOnStop !== false;
50
+ }
51
+ persistCurrentState() {
52
+ if (!this.persistState || !this.server || !this.port)
53
+ return;
54
+ saveDaemonState({
55
+ pid: process.pid,
56
+ port: this.port,
57
+ host: this.host,
58
+ startTime: this.startTime,
59
+ status: this.status,
60
+ phase: this.phase,
61
+ activeModel: this.pool.getActiveModelId(),
62
+ loadedModels: this.pool.listLoadedModels().map((m) => m.id),
63
+ error: this.lastError
64
+ });
65
+ }
66
+ resetIdleTimer() {
67
+ if (this.idleTimer)
68
+ clearTimeout(this.idleTimer);
69
+ if (this.idleTimeoutMs > 0) {
70
+ this.idleTimer = setTimeout(() => {
71
+ debug('daemon', 'Daemon idle timeout reached. Shutting down...');
72
+ void this.stop();
73
+ }, this.idleTimeoutMs);
74
+ this.idleTimer.unref();
75
+ }
76
+ }
77
+ async start() {
78
+ debug('daemon', 'Starting NanoBridge node-llama-cpp daemon...');
79
+ this.status = 'starting';
80
+ this.phase = 'initializing_runtime';
81
+ // 1. Bind HTTP server immediately so port & state file are available fast
82
+ this.server = http.createServer((req, res) => {
83
+ void this.handleRequest(req, res);
84
+ });
85
+ await new Promise((resolve, reject) => {
86
+ this.server.listen(this.port, this.host, () => {
87
+ const addr = this.server.address();
88
+ if (addr) {
89
+ this.port = addr.port;
90
+ }
91
+ resolve();
92
+ });
93
+ this.server.on('error', reject);
94
+ });
95
+ this.persistCurrentState();
96
+ debug('daemon', `Daemon HTTP server listening on http://${this.host}:${this.port} (PID: ${process.pid})`);
97
+ const cleanup = () => {
98
+ void this.stop();
99
+ };
100
+ process.on('SIGINT', cleanup);
101
+ process.on('SIGTERM', cleanup);
102
+ if (this.persistState) {
103
+ process.on('exit', () => clearDaemonState());
104
+ }
105
+ // 2. Initialize runtime & optionally preload/warm default model
106
+ this.initPromise = (async () => {
107
+ try {
108
+ const hw = await this.pool.getEngine().getHardwareInfo().catch(() => null);
109
+ if (hw) {
110
+ this.gpuBackend = hw.gpu;
111
+ }
112
+ const shouldPreload = this.options.preload !== false;
113
+ const installed = listInstalledModels();
114
+ const targetModel = this.options.model || loadConfig().defaultModel || installed[0]?.id;
115
+ if (shouldPreload && targetModel) {
116
+ this.phase = 'loading_model';
117
+ this.persistCurrentState();
118
+ try {
119
+ const loaded = await this.pool.loadAndWarm(targetModel);
120
+ this.isWarmed = loaded.warmed;
121
+ debug('daemon', `Preloaded and warmed model "${loaded.id}"`);
122
+ }
123
+ catch (preloadErr) {
124
+ debug('daemon', 'Preload notice (daemon still ready to accept model loads):', preloadErr instanceof Error ? preloadErr.message : String(preloadErr));
125
+ }
126
+ }
127
+ this.status = 'ready';
128
+ this.phase = 'ready';
129
+ this.persistCurrentState();
130
+ this.resetIdleTimer();
131
+ }
132
+ catch (err) {
133
+ this.status = 'error';
134
+ this.phase = 'error';
135
+ this.lastError = err instanceof Error ? err.message : String(err);
136
+ this.persistCurrentState();
137
+ debug('daemon', 'Initialization failed:', this.lastError);
138
+ throw err;
139
+ }
140
+ })();
141
+ await this.initPromise;
142
+ }
143
+ setCorsHeaders(res) {
144
+ res.setHeader('Access-Control-Allow-Origin', '*');
145
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
146
+ res.setHeader('Access-Control-Allow-Headers', 'Authorization, Content-Type, Accept, Origin, User-Agent, X-Requested-With');
147
+ }
148
+ sendJson(res, statusCode, data) {
149
+ res.writeHead(statusCode, { 'Content-Type': 'application/json' });
150
+ res.end(JSON.stringify(data, null, 2));
151
+ }
152
+ async handleRequest(req, res) {
153
+ this.resetIdleTimer();
154
+ this.setCorsHeaders(res);
155
+ if (req.method === 'OPTIONS') {
156
+ res.writeHead(204);
157
+ res.end();
158
+ return;
159
+ }
160
+ const url = new URL(req.url || '/', `http://${this.host}:${this.port}`);
161
+ // GET /status | /health
162
+ if (req.method === 'GET' && (url.pathname === '/status' || url.pathname === '/health')) {
163
+ const payload = {
164
+ status: this.status,
165
+ phase: this.phase,
166
+ pid: process.pid,
167
+ port: this.port,
168
+ host: this.host,
169
+ uptimeMs: Date.now() - this.startTime,
170
+ warmed: this.isWarmed,
171
+ activeModel: this.pool.getActiveModelId(),
172
+ loadedModels: this.pool.listLoadedModels(),
173
+ gpu: this.gpuBackend,
174
+ chatStats: this.chatStats,
175
+ openai_base_url: `http://${this.host}:${this.port}/v1`,
176
+ error: this.lastError
177
+ };
178
+ this.sendJson(res, 200, payload);
179
+ return;
180
+ }
181
+ // POST /stop
182
+ if (req.method === 'POST' && url.pathname === '/stop') {
183
+ this.sendJson(res, 200, { stopped: true });
184
+ setTimeout(() => {
185
+ void this.stop();
186
+ }, 50);
187
+ return;
188
+ }
189
+ // POST /models/load — hot-swap / preload a model into the warm pool
190
+ if (req.method === 'POST' && url.pathname === '/models/load') {
191
+ try {
192
+ const raw = await readRequestBody(req);
193
+ const body = JSON.parse(raw || '{}');
194
+ const info = await this.pool.loadAndWarm(body.model);
195
+ this.isWarmed = info.warmed;
196
+ this.persistCurrentState();
197
+ this.sendJson(res, 200, { success: true, model: info });
198
+ }
199
+ catch (err) {
200
+ this.sendJson(res, 400, {
201
+ success: false,
202
+ error: err instanceof Error ? err.message : String(err)
203
+ });
204
+ }
205
+ return;
206
+ }
207
+ // POST /models/unload — unload one or all models from RAM/VRAM
208
+ if (req.method === 'POST' && url.pathname === '/models/unload') {
209
+ try {
210
+ const raw = await readRequestBody(req);
211
+ const body = JSON.parse(raw || '{}');
212
+ const unloaded = await this.pool.unloadModel(body.model);
213
+ this.isWarmed = this.pool.listLoadedModels().some((m) => m.warmed);
214
+ this.persistCurrentState();
215
+ this.sendJson(res, 200, { success: true, unloaded });
216
+ }
217
+ catch (err) {
218
+ this.sendJson(res, 500, {
219
+ success: false,
220
+ error: err instanceof Error ? err.message : String(err)
221
+ });
222
+ }
223
+ return;
224
+ }
225
+ // POST|GET /reset — clear KV cache & chat session while keeping model warm
226
+ if ((req.method === 'POST' || req.method === 'GET') && url.pathname === '/reset') {
227
+ const model = url.searchParams.get('model');
228
+ try {
229
+ await this.pool.resetContext(model);
230
+ this.chatStats = null;
231
+ this.sendJson(res, 200, { success: true, message: 'Context reset successfully' });
232
+ }
233
+ catch (err) {
234
+ this.sendJson(res, 500, {
235
+ success: false,
236
+ error: err instanceof Error ? err.message : String(err)
237
+ });
238
+ }
239
+ return;
240
+ }
241
+ // GET /v1/models
242
+ if (req.method === 'GET' && url.pathname === '/v1/models') {
243
+ const installed = listInstalledModels();
244
+ this.sendJson(res, 200, formatModelsList(installed, this.pool.getActiveModelId()));
245
+ return;
246
+ }
247
+ // POST /v1/chat/completions
248
+ if (req.method === 'POST' && url.pathname === '/v1/chat/completions') {
249
+ const reqId = `chatcmpl-${crypto.randomBytes(8).toString('hex')}`;
250
+ let isClientClosed = false;
251
+ res.on('close', () => {
252
+ if (!res.writableEnded) {
253
+ isClientClosed = true;
254
+ this.pool.cancelRequest(reqId);
255
+ }
256
+ });
257
+ try {
258
+ if (this.initPromise)
259
+ await this.initPromise;
260
+ const raw = await readRequestBody(req);
261
+ const payload = JSON.parse(raw || '{}');
262
+ const { systemPrompt, promptText, messages } = parseChatMessages(payload.messages || []);
263
+ const stream = payload.stream === true;
264
+ const requestedModel = payload.model;
265
+ const cfg = loadConfig();
266
+ const thinkSetting = payload.think !== undefined ? payload.think : cfg.defaultThink;
267
+ let jsonMode = false;
268
+ let responseConstraint = null;
269
+ if (payload.response_format?.type === 'json_object') {
270
+ jsonMode = true;
271
+ }
272
+ else if (payload.response_format?.type === 'json_schema' &&
273
+ payload.response_format.json_schema?.schema) {
274
+ responseConstraint = payload.response_format.json_schema.schema;
275
+ }
276
+ if (stream) {
277
+ res.socket?.setNoDelay(true);
278
+ req.socket?.setNoDelay(true);
279
+ res.writeHead(200, {
280
+ 'Content-Type': 'text/event-stream; charset=utf-8',
281
+ 'Cache-Control': 'no-cache',
282
+ Connection: 'keep-alive'
283
+ });
284
+ res.flushHeaders?.();
285
+ let isFirst = true;
286
+ const activeModelLabel = requestedModel || this.pool.getActiveModelId() || 'local-model';
287
+ const result = await this.pool.prompt({
288
+ model: requestedModel,
289
+ promptText,
290
+ systemPrompt,
291
+ messages,
292
+ tools: payload.tools,
293
+ temperature: payload.temperature,
294
+ topP: payload.top_p,
295
+ topK: payload.top_k,
296
+ maxTokens: payload.max_tokens,
297
+ think: thinkSetting,
298
+ thoughtBudget: payload.thought_budget,
299
+ jsonMode,
300
+ responseConstraint,
301
+ sessionType: 'stateless',
302
+ stream: true,
303
+ requestId: reqId,
304
+ onChunk: (delta) => {
305
+ if (isClientClosed)
306
+ return;
307
+ if (!delta && !isFirst)
308
+ return;
309
+ const chunk = formatChatCompletionChunk({
310
+ id: reqId,
311
+ model: activeModelLabel,
312
+ delta,
313
+ isFirst
314
+ });
315
+ isFirst = false;
316
+ res.write(`data: ${JSON.stringify(chunk)}\n\n`);
317
+ }
318
+ });
319
+ if (!isClientClosed) {
320
+ if (result.toolCalls && result.toolCalls.length > 0) {
321
+ const tcChunk = formatChatCompletionChunk({
322
+ id: reqId,
323
+ model: result.model,
324
+ toolCalls: result.toolCalls,
325
+ isFirst
326
+ });
327
+ res.write(`data: ${JSON.stringify(tcChunk)}\n\n`);
328
+ }
329
+ const lastChunk = formatChatCompletionChunk({
330
+ id: reqId,
331
+ model: result.model,
332
+ delta: '',
333
+ isLast: true,
334
+ finishReason: result.toolCalls && result.toolCalls.length > 0 ? 'tool_calls' : 'stop'
335
+ });
336
+ res.write(`data: ${JSON.stringify(lastChunk)}\n\n`);
337
+ res.write('data: [DONE]\n\n');
338
+ res.end();
339
+ }
340
+ }
341
+ else {
342
+ const result = await this.pool.prompt({
343
+ model: requestedModel,
344
+ promptText,
345
+ systemPrompt,
346
+ messages,
347
+ tools: payload.tools,
348
+ temperature: payload.temperature,
349
+ topP: payload.top_p,
350
+ topK: payload.top_k,
351
+ maxTokens: payload.max_tokens,
352
+ think: thinkSetting,
353
+ thoughtBudget: payload.thought_budget,
354
+ jsonMode,
355
+ responseConstraint,
356
+ sessionType: 'stateless',
357
+ stream: false,
358
+ requestId: reqId
359
+ });
360
+ if (!isClientClosed) {
361
+ this.sendJson(res, 200, formatChatCompletion({
362
+ id: reqId,
363
+ model: result.model,
364
+ content: result.text,
365
+ toolCalls: result.toolCalls,
366
+ promptTokens: result.promptTokens,
367
+ completionTokens: result.completionTokens
368
+ }));
369
+ }
370
+ }
371
+ }
372
+ catch (err) {
373
+ if (!isClientClosed && !res.headersSent) {
374
+ this.sendJson(res, 500, {
375
+ error: {
376
+ message: err instanceof Error ? err.message : String(err),
377
+ type: 'nanobridge_error',
378
+ code: 'inference_error'
379
+ }
380
+ });
381
+ }
382
+ else if (!isClientClosed) {
383
+ res.end();
384
+ }
385
+ }
386
+ return;
387
+ }
388
+ // POST /v1/completions
389
+ if (req.method === 'POST' && url.pathname === '/v1/completions') {
390
+ const reqId = `cmpl-${crypto.randomBytes(8).toString('hex')}`;
391
+ let isClientClosed = false;
392
+ res.on('close', () => {
393
+ if (!res.writableEnded) {
394
+ isClientClosed = true;
395
+ this.pool.cancelRequest(reqId);
396
+ }
397
+ });
398
+ try {
399
+ if (this.initPromise)
400
+ await this.initPromise;
401
+ const raw = await readRequestBody(req);
402
+ const payload = JSON.parse(raw || '{}');
403
+ const promptText = Array.isArray(payload.prompt)
404
+ ? payload.prompt.join('\n')
405
+ : String(payload.prompt || '');
406
+ const stream = payload.stream === true;
407
+ const requestedModel = payload.model;
408
+ if (stream) {
409
+ res.socket?.setNoDelay(true);
410
+ res.writeHead(200, {
411
+ 'Content-Type': 'text/event-stream; charset=utf-8',
412
+ 'Cache-Control': 'no-cache',
413
+ Connection: 'keep-alive'
414
+ });
415
+ res.flushHeaders?.();
416
+ const activeModelLabel = requestedModel || this.pool.getActiveModelId() || 'local-model';
417
+ const result = await this.pool.prompt({
418
+ model: requestedModel,
419
+ promptText,
420
+ temperature: payload.temperature,
421
+ topP: payload.top_p,
422
+ maxTokens: payload.max_tokens,
423
+ sessionType: 'stateless',
424
+ stream: true,
425
+ requestId: reqId,
426
+ onChunk: (delta) => {
427
+ if (isClientClosed || !delta)
428
+ return;
429
+ const chunk = formatTextCompletionChunk({
430
+ id: reqId,
431
+ model: activeModelLabel,
432
+ text: delta
433
+ });
434
+ res.write(`data: ${JSON.stringify(chunk)}\n\n`);
435
+ }
436
+ });
437
+ if (!isClientClosed) {
438
+ const lastChunk = formatTextCompletionChunk({
439
+ id: reqId,
440
+ model: result.model,
441
+ text: '',
442
+ isLast: true
443
+ });
444
+ res.write(`data: ${JSON.stringify(lastChunk)}\n\n`);
445
+ res.write('data: [DONE]\n\n');
446
+ res.end();
447
+ }
448
+ }
449
+ else {
450
+ const result = await this.pool.prompt({
451
+ model: requestedModel,
452
+ promptText,
453
+ temperature: payload.temperature,
454
+ topP: payload.top_p,
455
+ maxTokens: payload.max_tokens,
456
+ sessionType: 'stateless',
457
+ stream: false,
458
+ requestId: reqId
459
+ });
460
+ if (!isClientClosed) {
461
+ this.sendJson(res, 200, formatTextCompletion({
462
+ id: reqId,
463
+ model: result.model,
464
+ text: result.text,
465
+ promptTokens: result.promptTokens,
466
+ completionTokens: result.completionTokens
467
+ }));
468
+ }
469
+ }
470
+ }
471
+ catch (err) {
472
+ if (!isClientClosed && !res.headersSent) {
473
+ this.sendJson(res, 500, {
474
+ error: {
475
+ message: err instanceof Error ? err.message : String(err),
476
+ type: 'nanobridge_error',
477
+ code: 'inference_error'
478
+ }
479
+ });
480
+ }
481
+ else if (!isClientClosed) {
482
+ res.end();
483
+ }
484
+ }
485
+ return;
486
+ }
487
+ // POST /v1/embeddings
488
+ if (req.method === 'POST' && url.pathname === '/v1/embeddings') {
489
+ try {
490
+ if (this.initPromise)
491
+ await this.initPromise;
492
+ const raw = await readRequestBody(req);
493
+ const payload = JSON.parse(raw || '{}');
494
+ if (!payload.input || (Array.isArray(payload.input) && payload.input.length === 0)) {
495
+ this.sendJson(res, 400, {
496
+ error: {
497
+ message: 'Field "input" is required (string or non-empty string array).',
498
+ type: 'invalid_request_error'
499
+ }
500
+ });
501
+ return;
502
+ }
503
+ const result = await this.pool.embed({
504
+ model: payload.model,
505
+ input: payload.input
506
+ });
507
+ this.sendJson(res, 200, formatEmbeddingsResponse(result));
508
+ }
509
+ catch (err) {
510
+ this.sendJson(res, 500, {
511
+ error: {
512
+ message: err instanceof Error ? err.message : String(err),
513
+ type: 'nanobridge_error',
514
+ code: 'embedding_error'
515
+ }
516
+ });
517
+ }
518
+ return;
519
+ }
520
+ // POST /prompt — Native NanoBridge NDJSON streaming endpoint
521
+ if (req.method === 'POST' && url.pathname === '/prompt') {
522
+ const reqId = `req_${crypto.randomBytes(8).toString('hex')}`;
523
+ let isClientClosed = false;
524
+ res.on('close', () => {
525
+ if (!res.writableEnded) {
526
+ isClientClosed = true;
527
+ this.pool.cancelRequest(reqId);
528
+ }
529
+ });
530
+ try {
531
+ if (this.initPromise)
532
+ await this.initPromise;
533
+ const raw = await readRequestBody(req);
534
+ const payload = JSON.parse(raw || '{}');
535
+ res.socket?.setNoDelay(true);
536
+ req.socket?.setNoDelay(true);
537
+ res.writeHead(200, {
538
+ 'Content-Type': 'application/x-ndjson',
539
+ 'Transfer-Encoding': 'chunked',
540
+ 'Cache-Control': 'no-cache',
541
+ Connection: 'keep-alive'
542
+ });
543
+ res.flushHeaders?.();
544
+ const sendChunk = (delta) => {
545
+ if (isClientClosed)
546
+ return;
547
+ try {
548
+ res.write(JSON.stringify({ type: 'chunk', delta }) + '\n');
549
+ }
550
+ catch {
551
+ // Ignore broken pipe
552
+ }
553
+ };
554
+ const sendThoughtChunk = (delta) => {
555
+ if (isClientClosed)
556
+ return;
557
+ try {
558
+ res.write(JSON.stringify({ type: 'thought', delta }) + '\n');
559
+ }
560
+ catch {
561
+ // Ignore broken pipe
562
+ }
563
+ };
564
+ const cfg = loadConfig();
565
+ const thinkSetting = payload.think !== undefined && payload.think !== null
566
+ ? payload.think
567
+ : cfg.defaultThink;
568
+ const result = await this.pool.prompt({
569
+ model: payload.model,
570
+ promptText: payload.promptText ?? '',
571
+ systemPrompt: payload.systemPrompt,
572
+ samplingMode: payload.samplingMode,
573
+ temperature: payload.temperature,
574
+ topK: payload.topK,
575
+ topP: payload.topP,
576
+ maxTokens: payload.maxTokens,
577
+ think: thinkSetting,
578
+ thoughtBudget: payload.thoughtBudget,
579
+ showThinking: payload.showThinking,
580
+ sessionType: payload.sessionType || 'stateless',
581
+ initialPrompts: payload.initialPrompts,
582
+ responseConstraint: payload.responseConstraint,
583
+ jsonMode: payload.jsonMode,
584
+ stream: payload.stream !== false,
585
+ requestId: reqId,
586
+ onChunk: (delta) => sendChunk(delta),
587
+ onThoughtChunk: (delta) => sendThoughtChunk(delta)
588
+ });
589
+ this.chatStats = {
590
+ contextUsage: result.contextUsage,
591
+ contextWindow: result.contextWindow
592
+ };
593
+ this.persistCurrentState();
594
+ if (!isClientClosed) {
595
+ res.write(JSON.stringify({
596
+ type: 'done',
597
+ text: result.text,
598
+ model: result.model,
599
+ usage: {
600
+ promptTokens: result.promptTokens,
601
+ completionTokens: result.completionTokens,
602
+ contextUsage: result.contextUsage,
603
+ contextWindow: result.contextWindow
604
+ }
605
+ }) + '\n');
606
+ res.end();
607
+ }
608
+ }
609
+ catch (err) {
610
+ if (!isClientClosed) {
611
+ try {
612
+ res.write(JSON.stringify({
613
+ type: 'error',
614
+ error: err instanceof Error ? err.message : String(err)
615
+ }) + '\n');
616
+ res.end();
617
+ }
618
+ catch {
619
+ // Ignore
620
+ }
621
+ }
622
+ }
623
+ return;
624
+ }
625
+ this.sendJson(res, 404, { error: 'Not Found' });
626
+ }
627
+ async stop() {
628
+ if (this.isStopping)
629
+ return;
630
+ this.isStopping = true;
631
+ debug('daemon', 'Stopping NanoBridge Daemon...');
632
+ if (this.idleTimer)
633
+ clearTimeout(this.idleTimer);
634
+ if (this.persistState)
635
+ clearDaemonState();
636
+ if (this.server) {
637
+ await new Promise((resolve) => {
638
+ this.server.close(() => resolve());
639
+ }).catch(() => { });
640
+ this.server = null;
641
+ }
642
+ await this.pool.disposeAll().catch(() => { });
643
+ debug('daemon', 'Daemon stopped successfully.');
644
+ if (this.exitOnStop) {
645
+ process.exit(0);
646
+ }
647
+ }
648
+ }
649
+ // Direct background execution entrypoint
650
+ if (process.argv[1] &&
651
+ (process.argv[1].endsWith('daemon/server.js') || process.argv[1].endsWith('daemon/server.ts'))) {
652
+ if (process.env.NANOBRIDGE_DEBUG === '1') {
653
+ setDebugMode(true);
654
+ }
655
+ const daemon = new DaemonServer();
656
+ daemon.start().catch((err) => {
657
+ console.error('Failed to start daemon:', err);
658
+ process.exit(1);
659
+ });
660
+ }
661
+ //# sourceMappingURL=server.js.map