ko-qmd 2.8.3-ko.2

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 (56) hide show
  1. package/CHANGELOG.md +1376 -0
  2. package/LICENSE +21 -0
  3. package/README.ko.md +86 -0
  4. package/README.md +1307 -0
  5. package/bin/qmd +192 -0
  6. package/dist/ast.d.ts +65 -0
  7. package/dist/ast.js +334 -0
  8. package/dist/bench/bench.d.ts +35 -0
  9. package/dist/bench/bench.js +327 -0
  10. package/dist/bench/score.d.ts +33 -0
  11. package/dist/bench/score.js +88 -0
  12. package/dist/bench/types.d.ts +80 -0
  13. package/dist/bench/types.js +8 -0
  14. package/dist/cli/build-info.json +4 -0
  15. package/dist/cli/embed-lock.d.ts +24 -0
  16. package/dist/cli/embed-lock.js +94 -0
  17. package/dist/cli/formatter.d.ts +120 -0
  18. package/dist/cli/formatter.js +355 -0
  19. package/dist/cli/mcp-pid.d.ts +25 -0
  20. package/dist/cli/mcp-pid.js +86 -0
  21. package/dist/cli/qmd.d.ts +43 -0
  22. package/dist/cli/qmd.js +4424 -0
  23. package/dist/cli/version.d.ts +42 -0
  24. package/dist/cli/version.js +80 -0
  25. package/dist/collections.d.ts +167 -0
  26. package/dist/collections.js +410 -0
  27. package/dist/db.d.ts +63 -0
  28. package/dist/db.js +130 -0
  29. package/dist/hangul.d.ts +54 -0
  30. package/dist/hangul.js +140 -0
  31. package/dist/index.d.ts +237 -0
  32. package/dist/index.js +244 -0
  33. package/dist/llm.d.ts +543 -0
  34. package/dist/llm.js +1747 -0
  35. package/dist/maintenance.d.ts +33 -0
  36. package/dist/maintenance.js +52 -0
  37. package/dist/mcp/origin-guard.d.ts +67 -0
  38. package/dist/mcp/origin-guard.js +137 -0
  39. package/dist/mcp/server.d.ts +116 -0
  40. package/dist/mcp/server.js +883 -0
  41. package/dist/paths.d.ts +1 -0
  42. package/dist/paths.js +4 -0
  43. package/dist/store.d.ts +1100 -0
  44. package/dist/store.js +4965 -0
  45. package/dist/trust.d.ts +152 -0
  46. package/dist/trust.js +249 -0
  47. package/package.json +114 -0
  48. package/scripts/build.mjs +72 -0
  49. package/scripts/check-package-grammars.mjs +29 -0
  50. package/scripts/package-smoke.mjs +65 -0
  51. package/scripts/test-all.mjs +38 -0
  52. package/skills/qmd/SKILL.md +316 -0
  53. package/skills/qmd/references/mcp-setup.md +119 -0
  54. package/skills/release/SKILL.md +141 -0
  55. package/skills/release/scripts/install-hooks.sh +38 -0
  56. package/skills/release/scripts/release-context.sh +129 -0
package/dist/llm.js ADDED
@@ -0,0 +1,1747 @@
1
+ /**
2
+ * llm.ts - LLM abstraction layer for QMD using node-llama-cpp
3
+ *
4
+ * Provides embeddings, text generation, and reranking using local GGUF models.
5
+ */
6
+ let nodeLlamaCppImport = null;
7
+ async function loadNodeLlamaCpp() {
8
+ nodeLlamaCppImport ??= withNativeStdoutRedirectedToStderr(() => import("node-llama-cpp"));
9
+ return nodeLlamaCppImport;
10
+ }
11
+ export function setNodeLlamaCppModuleForTest(module) {
12
+ nodeLlamaCppImport = module ? Promise.resolve(module) : null;
13
+ failedGpuInitModes.clear();
14
+ noGpuAccelerationWarningShown = false;
15
+ cpuForcedPrebuiltFallbackWarningShown = false;
16
+ llamaDirWritableOverride = undefined;
17
+ }
18
+ let nativeStdoutRedirectDepth = 0;
19
+ let originalStdoutWrite = null;
20
+ /**
21
+ * Some node-llama-cpp native build/probe paths write library noise to stdout.
22
+ * JSON APIs must reserve stdout for machine-readable payloads, so route that
23
+ * noise to stderr while native llama initialization is in progress.
24
+ */
25
+ export async function withNativeStdoutRedirectedToStderr(fn) {
26
+ if (nativeStdoutRedirectDepth === 0) {
27
+ originalStdoutWrite = process.stdout.write.bind(process.stdout);
28
+ process.stdout.write = ((chunk, encodingOrCallback, callback) => {
29
+ if (typeof encodingOrCallback === "function") {
30
+ return process.stderr.write(chunk, encodingOrCallback);
31
+ }
32
+ return process.stderr.write(chunk, encodingOrCallback, callback);
33
+ });
34
+ }
35
+ nativeStdoutRedirectDepth++;
36
+ try {
37
+ return await fn();
38
+ }
39
+ finally {
40
+ nativeStdoutRedirectDepth--;
41
+ if (nativeStdoutRedirectDepth === 0 && originalStdoutWrite) {
42
+ process.stdout.write = originalStdoutWrite;
43
+ originalStdoutWrite = null;
44
+ }
45
+ }
46
+ }
47
+ import { homedir } from "os";
48
+ import { dirname, join } from "path";
49
+ import { accessSync, constants, existsSync, mkdirSync, statSync, unlinkSync, readdirSync, readFileSync, writeFileSync, openSync, readSync, closeSync } from "fs";
50
+ import { createRequire } from "node:module";
51
+ // =============================================================================
52
+ // Embedding Formatting Functions
53
+ // =============================================================================
54
+ /**
55
+ * Detect if a model URI uses the Qwen3-Embedding format.
56
+ * Qwen3-Embedding uses a different prompting style than nomic/embeddinggemma.
57
+ */
58
+ export function isQwen3EmbeddingModel(modelUri) {
59
+ return /qwen.*embed/i.test(modelUri) || /embed.*qwen/i.test(modelUri);
60
+ }
61
+ /**
62
+ * Format a query for embedding.
63
+ * Uses Qwen3-Embedding instruct format when a Qwen embedding model is active (default).
64
+ * Uses nomic-style task prefix format for embeddinggemma and other models.
65
+ */
66
+ export function formatQueryForEmbedding(query, modelUri) {
67
+ const uri = modelUri ?? resolveEmbedModel();
68
+ if (isQwen3EmbeddingModel(uri)) {
69
+ return `Instruct: Retrieve relevant documents for the given query\nQuery: ${query}`;
70
+ }
71
+ return `task: search result | query: ${query}`;
72
+ }
73
+ /**
74
+ * Format a document for embedding.
75
+ * Uses nomic-style format with title and text fields for non-Qwen models.
76
+ * Qwen3-Embedding (default) encodes documents as raw text without special prefixes.
77
+ */
78
+ export function formatDocForEmbedding(text, title, modelUri) {
79
+ const uri = modelUri ?? resolveEmbedModel();
80
+ if (isQwen3EmbeddingModel(uri)) {
81
+ // Qwen3-Embedding: documents are raw text, no task prefix
82
+ return title ? `${title}\n${text}` : text;
83
+ }
84
+ return `title: ${title || "none"} | text: ${text}`;
85
+ }
86
+ // =============================================================================
87
+ // Build Writability Check
88
+ // =============================================================================
89
+ const llamaCppRequire = createRequire(import.meta.url);
90
+ /** Test override for canWriteLlamaDir(); `undefined` uses the real probe. */
91
+ let llamaDirWritableOverride;
92
+ export function setLlamaDirWritableForTest(writable) {
93
+ llamaDirWritableOverride = writable;
94
+ }
95
+ /** Whether node-llama-cpp can write to its llama/ directory (false on NixOS). */
96
+ export function canWriteLlamaDir(pkgDir) {
97
+ if (llamaDirWritableOverride !== undefined)
98
+ return llamaDirWritableOverride;
99
+ try {
100
+ const dir = pkgDir ?? dirname(llamaCppRequire.resolve("node-llama-cpp/package.json"));
101
+ accessSync(join(dir, "llama"), constants.W_OK);
102
+ return true;
103
+ }
104
+ catch {
105
+ return false;
106
+ }
107
+ }
108
+ // =============================================================================
109
+ // Model Configuration
110
+ // =============================================================================
111
+ // HuggingFace model URIs for node-llama-cpp
112
+ // Format: hf:<user>/<repo>/<file>
113
+ // Override via QMD_EMBED_MODEL env var (e.g. hf:ggml-org/embeddinggemma-300M-GGUF/embeddinggemma-300M-Q8_0.gguf)
114
+ // ko-qmd: multilingual Qwen3-Embedding is the default for Korean vaults (upstream: embeddinggemma).
115
+ const DEFAULT_EMBED_MODEL = "hf:Qwen/Qwen3-Embedding-0.6B-GGUF/Qwen3-Embedding-0.6B-Q8_0.gguf";
116
+ const DEFAULT_RERANK_MODEL = "hf:ggml-org/Qwen3-Reranker-0.6B-Q8_0-GGUF/qwen3-reranker-0.6b-q8_0.gguf";
117
+ // const DEFAULT_GENERATE_MODEL = "hf:ggml-org/Qwen3-0.6B-GGUF/Qwen3-0.6B-Q8_0.gguf";
118
+ const DEFAULT_GENERATE_MODEL = "hf:tobil/qmd-query-expansion-1.7B-gguf/qmd-query-expansion-1.7B-q4_k_m.gguf";
119
+ // Alternative generation models for query expansion:
120
+ // LiquidAI LFM2 - hybrid architecture optimized for edge/on-device inference
121
+ // Use these as base for fine-tuning with configs/sft_lfm2.yaml
122
+ export const LFM2_GENERATE_MODEL = "hf:LiquidAI/LFM2-1.2B-GGUF/LFM2-1.2B-Q4_K_M.gguf";
123
+ export const LFM2_INSTRUCT_MODEL = "hf:LiquidAI/LFM2.5-1.2B-Instruct-GGUF/LFM2.5-1.2B-Instruct-Q4_K_M.gguf";
124
+ export const DEFAULT_EMBED_MODEL_URI = DEFAULT_EMBED_MODEL;
125
+ export const DEFAULT_RERANK_MODEL_URI = DEFAULT_RERANK_MODEL;
126
+ export const DEFAULT_GENERATE_MODEL_URI = DEFAULT_GENERATE_MODEL;
127
+ export function resolveEmbedModel(config) {
128
+ return config?.embed || process.env.QMD_EMBED_MODEL || DEFAULT_EMBED_MODEL;
129
+ }
130
+ export function resolveGenerateModel(config) {
131
+ return config?.generate || process.env.QMD_GENERATE_MODEL || DEFAULT_GENERATE_MODEL;
132
+ }
133
+ export function resolveRerankModel(config) {
134
+ return config?.rerank || process.env.QMD_RERANK_MODEL || DEFAULT_RERANK_MODEL;
135
+ }
136
+ export function resolveModels(config) {
137
+ return {
138
+ embed: resolveEmbedModel(config),
139
+ generate: resolveGenerateModel(config),
140
+ rerank: resolveRerankModel(config),
141
+ };
142
+ }
143
+ // Local model cache directory
144
+ const MODEL_CACHE_DIR = process.env.XDG_CACHE_HOME
145
+ ? join(process.env.XDG_CACHE_HOME, "qmd", "models")
146
+ : join(homedir(), ".cache", "qmd", "models");
147
+ export const DEFAULT_MODEL_CACHE_DIR = MODEL_CACHE_DIR;
148
+ function parseHfUri(model) {
149
+ if (!model.startsWith("hf:"))
150
+ return null;
151
+ const without = model.slice(3);
152
+ const parts = without.split("/");
153
+ if (parts.length < 3)
154
+ return null;
155
+ const repo = parts.slice(0, 2).join("/");
156
+ const file = parts.slice(2).join("/");
157
+ return { repo, file };
158
+ }
159
+ async function getRemoteEtag(ref) {
160
+ const url = `https://huggingface.co/${ref.repo}/resolve/main/${ref.file}`;
161
+ try {
162
+ const resp = await fetch(url, { method: "HEAD" });
163
+ if (!resp.ok)
164
+ return null;
165
+ const etag = resp.headers.get("etag");
166
+ return etag || null;
167
+ }
168
+ catch {
169
+ return null;
170
+ }
171
+ }
172
+ const GGUF_MAGIC = Buffer.from("GGUF");
173
+ function formatModelFileSize(sizeBytes) {
174
+ return `${(sizeBytes / 1024).toFixed(0)} KB`;
175
+ }
176
+ function printableMagic(header) {
177
+ const text = header.toString("utf-8");
178
+ return /^[\x20-\x7e]{1,4}$/.test(text) ? text : `0x${header.toString("hex")}`;
179
+ }
180
+ /**
181
+ * Inspect a potential GGUF model file without mutating it.
182
+ * Used by doctor for early diagnostics and by runtime validation before load.
183
+ */
184
+ export function inspectGgufFile(filePath) {
185
+ if (!existsSync(filePath)) {
186
+ return { exists: false, valid: false, kind: "missing", details: "file does not exist" };
187
+ }
188
+ let sizeBytes = 0;
189
+ try {
190
+ sizeBytes = statSync(filePath).size;
191
+ const fd = openSync(filePath, "r");
192
+ const sniff = Buffer.alloc(512);
193
+ try {
194
+ readSync(fd, sniff, 0, 512, 0);
195
+ }
196
+ finally {
197
+ closeSync(fd);
198
+ }
199
+ const header = sniff.subarray(0, 4);
200
+ if (header.equals(GGUF_MAGIC)) {
201
+ return {
202
+ exists: true,
203
+ valid: true,
204
+ kind: "gguf",
205
+ sizeBytes,
206
+ magic: "GGUF",
207
+ details: `valid GGUF (${formatModelFileSize(sizeBytes)})`,
208
+ };
209
+ }
210
+ const magic = printableMagic(header);
211
+ const text = sniff.toString("utf-8").toLowerCase();
212
+ const isHtml = text.includes("<!doctype") || text.includes("<html");
213
+ if (isHtml) {
214
+ return {
215
+ exists: true,
216
+ valid: false,
217
+ kind: "html",
218
+ sizeBytes,
219
+ magic,
220
+ details: `HTML page, not a GGUF model (${formatModelFileSize(sizeBytes)}); likely proxy/firewall/captive portal response`,
221
+ };
222
+ }
223
+ return {
224
+ exists: true,
225
+ valid: false,
226
+ kind: "invalid",
227
+ sizeBytes,
228
+ magic,
229
+ details: `not valid GGUF (expected magic "GGUF", got "${magic}", ${formatModelFileSize(sizeBytes)})`,
230
+ };
231
+ }
232
+ catch (error) {
233
+ return {
234
+ exists: true,
235
+ valid: false,
236
+ kind: "invalid",
237
+ sizeBytes,
238
+ details: `cannot read model file: ${error instanceof Error ? error.message : String(error)}`,
239
+ };
240
+ }
241
+ }
242
+ /**
243
+ * Validate that a file is actually a GGUF model, not an HTML error page
244
+ * from a proxy, firewall, or failed download.
245
+ * Throws a descriptive error if the file is not valid GGUF.
246
+ */
247
+ function validateGgufFile(filePath, modelUri) {
248
+ const inspection = inspectGgufFile(filePath);
249
+ if (!inspection.exists || inspection.valid)
250
+ return; // let downstream handle missing files
251
+ // Remove the bad file so the next attempt re-downloads
252
+ try {
253
+ unlinkSync(filePath);
254
+ }
255
+ catch { /* best effort */ }
256
+ if (inspection.kind === "html") {
257
+ throw new Error(`Downloaded model file is an HTML page, not a GGUF model (${formatModelFileSize(inspection.sizeBytes ?? 0)}).\n` +
258
+ `Something is intercepting the download from huggingface.co (a proxy, firewall, or captive portal).\n\n` +
259
+ `Model: ${modelUri}\n` +
260
+ `Path: ${filePath}\n\n` +
261
+ `To fix this, either:\n` +
262
+ ` 1. Try a HuggingFace mirror: HF_ENDPOINT=https://hf-mirror.com qmd embed\n` +
263
+ ` 2. Download the model manually and set the env var, e.g.:\n` +
264
+ ` QMD_EMBED_MODEL=/path/to/model.gguf qmd embed\n\n` +
265
+ `Note: 'qmd search' works without any model downloads.`);
266
+ }
267
+ throw new Error(`Model file is not valid GGUF (expected magic "GGUF", got "${inspection.magic ?? "unknown"}", file is ${formatModelFileSize(inspection.sizeBytes ?? 0)}).\n` +
268
+ `Model: ${modelUri}\n` +
269
+ `Path: ${filePath}\n\n` +
270
+ `The file has been removed. Run the command again to re-download.`);
271
+ }
272
+ /**
273
+ * node-llama-cpp prints a multi-line download progress bar when the second
274
+ * argument is a directory string (`cli` defaults to true). Agent transcripts
275
+ * capture that as thousands of tokens. Always pass an options object so the
276
+ * bar is off unless the caller opts in (#776).
277
+ */
278
+ function resolveModelFileArgs(cacheDir, cli = false) {
279
+ return { directory: cacheDir, cli };
280
+ }
281
+ export async function pullModels(models, options = {}) {
282
+ const cacheDir = options.cacheDir || MODEL_CACHE_DIR;
283
+ if (!existsSync(cacheDir)) {
284
+ mkdirSync(cacheDir, { recursive: true });
285
+ }
286
+ const results = [];
287
+ for (const model of models) {
288
+ let refreshed = false;
289
+ const hfRef = parseHfUri(model);
290
+ const filename = model.split("/").pop();
291
+ const entries = readdirSync(cacheDir, { withFileTypes: true });
292
+ const cached = filename
293
+ ? entries
294
+ .filter((entry) => entry.isFile() && entry.name.includes(filename))
295
+ .map((entry) => join(cacheDir, entry.name))
296
+ : [];
297
+ if (hfRef && filename) {
298
+ const etagPath = join(cacheDir, `${filename}.etag`);
299
+ const remoteEtag = await getRemoteEtag(hfRef);
300
+ const localEtag = existsSync(etagPath)
301
+ ? readFileSync(etagPath, "utf-8").trim()
302
+ : null;
303
+ const shouldRefresh = options.refresh || !remoteEtag || remoteEtag !== localEtag || cached.length === 0;
304
+ if (shouldRefresh) {
305
+ for (const candidate of cached) {
306
+ if (existsSync(candidate))
307
+ unlinkSync(candidate);
308
+ }
309
+ if (existsSync(etagPath))
310
+ unlinkSync(etagPath);
311
+ refreshed = cached.length > 0;
312
+ }
313
+ }
314
+ else if (options.refresh && filename) {
315
+ for (const candidate of cached) {
316
+ if (existsSync(candidate))
317
+ unlinkSync(candidate);
318
+ refreshed = true;
319
+ }
320
+ }
321
+ const { resolveModelFile } = await loadNodeLlamaCpp();
322
+ const path = await resolveModelFile(model, resolveModelFileArgs(cacheDir, options.cli === true));
323
+ validateGgufFile(path, model);
324
+ const sizeBytes = existsSync(path) ? statSync(path).size : 0;
325
+ if (hfRef && filename) {
326
+ const remoteEtag = await getRemoteEtag(hfRef);
327
+ if (remoteEtag) {
328
+ const etagPath = join(cacheDir, `${filename}.etag`);
329
+ writeFileSync(etagPath, remoteEtag + "\n", "utf-8");
330
+ }
331
+ }
332
+ results.push({ model, path, sizeBytes, refreshed });
333
+ }
334
+ return results;
335
+ }
336
+ /**
337
+ * LLM implementation using node-llama-cpp
338
+ */
339
+ // Default inactivity timeout: 5 minutes (keep models warm during typical search sessions)
340
+ const DEFAULT_INACTIVITY_TIMEOUT_MS = 5 * 60 * 1000;
341
+ const DEFAULT_EXPAND_CONTEXT_SIZE = 2048;
342
+ export function resolveParallelismOverride(envValue = process.env.QMD_EMBED_PARALLELISM) {
343
+ const normalized = envValue?.trim() ?? "";
344
+ if (!normalized)
345
+ return undefined;
346
+ const parsed = Number(normalized);
347
+ if (!Number.isInteger(parsed) || parsed < 1) {
348
+ process.stderr.write(`QMD Warning: invalid QMD_EMBED_PARALLELISM="${envValue}", using automatic parallelism.\n`);
349
+ return undefined;
350
+ }
351
+ return Math.min(8, parsed);
352
+ }
353
+ export function resolveSafeParallelism(options) {
354
+ const override = resolveParallelismOverride(options.envValue);
355
+ if (override !== undefined)
356
+ return override;
357
+ // node-llama-cpp/llama.cpp CUDA on Windows is unstable with multiple
358
+ // simultaneous contexts (ggml-cuda.cu:98 in #519). Vulkan and CPU do not
359
+ // show the same failure mode, so only serialize Windows CUDA by default.
360
+ if ((options.platform ?? process.platform) === "win32" && options.gpu === "cuda") {
361
+ return 1;
362
+ }
363
+ return Math.max(1, options.computed);
364
+ }
365
+ /** Measured nomic-embed / embeddinggemma-300M embedding-context cost at 2048 tokens. */
366
+ export const BASELINE_EMBED_CONTEXT_MB = 150;
367
+ /**
368
+ * VRAM to leave free when sizing the embedding-context pool so `query` can
369
+ * still create a rerank context afterwards. Matches the 1000 MB figure
370
+ * `ensureRerankContexts` already uses as its per-context cost.
371
+ */
372
+ export const EMBED_POOL_RERANK_RESERVE_MB = 1000;
373
+ /**
374
+ * GPU embedding-context pool size from free VRAM.
375
+ *
376
+ * Uses 25% of (free − reserve), then clamps to `[1, cap]`. The reserve keeps
377
+ * the pool from consuming the memory `query` needs next for the reranker (#799).
378
+ */
379
+ export function computeGpuContextPoolSize(options) {
380
+ const perContextMB = Math.max(1, options.perContextMB);
381
+ const reserveMB = Math.max(0, options.reserveMB ?? 0);
382
+ const cap = options.cap ?? 8;
383
+ const usableMB = Math.max(0, options.freeMB - reserveMB);
384
+ const maxByVram = Math.floor((usableMB * 0.25) / perContextMB);
385
+ return Math.max(1, Math.min(cap, maxByVram));
386
+ }
387
+ /**
388
+ * Estimate one embedding context's VRAM from the GGUF weight-file size.
389
+ *
390
+ * Small models (nomic / embeddinggemma-class, ≲350 MB) stay at the measured
391
+ * 150 MB baseline so default `qmd embed` throughput is unchanged. Larger
392
+ * files — Qwen3-Embedding-0.6B-Q8 is ~640 MB — were measured at ~1190 MB per
393
+ * 2048-token context, about 1.85× the weight file, because the KV cache
394
+ * dominates (#799).
395
+ */
396
+ export function estimateEmbedContextMB(options) {
397
+ const contextSize = options.contextSize && options.contextSize > 0 ? options.contextSize : 2048;
398
+ const modelMB = options.modelBytes / (1024 * 1024);
399
+ const ctxScale = contextSize / 2048;
400
+ if (!(modelMB > 0) || !Number.isFinite(modelMB)) {
401
+ return Math.max(1, Math.round(BASELINE_EMBED_CONTEXT_MB * ctxScale));
402
+ }
403
+ const SMALL_MODEL_MB = 350;
404
+ if (modelMB <= SMALL_MODEL_MB) {
405
+ return Math.max(1, Math.round(BASELINE_EMBED_CONTEXT_MB * ctxScale));
406
+ }
407
+ return Math.max(1, Math.round(modelMB * 1.85 * ctxScale));
408
+ }
409
+ export function resolveLlamaGpuMode(envValue = process.env.QMD_LLAMA_GPU, forceCpuValue = process.env.QMD_FORCE_CPU) {
410
+ const forceCpu = forceCpuValue?.trim().toLowerCase() ?? "";
411
+ if (forceCpu && !["false", "off", "none", "disable", "disabled", "0"].includes(forceCpu)) {
412
+ return false;
413
+ }
414
+ const normalized = envValue?.trim().toLowerCase() ?? "";
415
+ if (!normalized)
416
+ return "auto";
417
+ if (["false", "off", "none", "disable", "disabled", "0"].includes(normalized))
418
+ return false;
419
+ if (normalized === "metal" || normalized === "vulkan" || normalized === "cuda")
420
+ return normalized;
421
+ process.stderr.write(`QMD Warning: invalid QMD_LLAMA_GPU="${envValue}", using auto GPU selection.\n`);
422
+ return "auto";
423
+ }
424
+ /** node-llama-cpp 3.20 made LlamaContextSequence.dispose() async (llama.cpp b10361).
425
+ * Context.onDispose fires sequence.dispose() without awaiting, so dispose the
426
+ * sequence first and wait, then dispose the parent context.
427
+ */
428
+ async function disposeSequenceThenContext(sequence, context) {
429
+ if (sequence)
430
+ await sequence.dispose();
431
+ await context.dispose();
432
+ }
433
+ async function disposeWithTimeout(resourceName, dispose, timeoutMs = 1000) {
434
+ const timeoutPromise = new Promise((resolve) => {
435
+ setTimeout(() => resolve("timeout"), timeoutMs).unref();
436
+ });
437
+ try {
438
+ const result = await Promise.race([dispose(), timeoutPromise]);
439
+ if (result === "timeout") {
440
+ process.stderr.write(`QMD Warning: timed out disposing ${resourceName}; continuing shutdown.\n`);
441
+ }
442
+ }
443
+ catch (error) {
444
+ process.stderr.write(`QMD Warning: failed to dispose ${resourceName} (${error instanceof Error ? error.message : String(error)}); continuing shutdown.\n`);
445
+ }
446
+ }
447
+ function resolveExpandContextSize(configValue) {
448
+ if (configValue !== undefined) {
449
+ if (!Number.isInteger(configValue) || configValue <= 0) {
450
+ throw new Error(`Invalid expandContextSize: ${configValue}. Must be a positive integer.`);
451
+ }
452
+ return configValue;
453
+ }
454
+ const envValue = process.env.QMD_EXPAND_CONTEXT_SIZE?.trim();
455
+ if (!envValue)
456
+ return DEFAULT_EXPAND_CONTEXT_SIZE;
457
+ const parsed = Number.parseInt(envValue, 10);
458
+ if (!Number.isInteger(parsed) || parsed <= 0) {
459
+ process.stderr.write(`QMD Warning: invalid QMD_EXPAND_CONTEXT_SIZE="${envValue}", using default ${DEFAULT_EXPAND_CONTEXT_SIZE}.\n`);
460
+ return DEFAULT_EXPAND_CONTEXT_SIZE;
461
+ }
462
+ return parsed;
463
+ }
464
+ const failedGpuInitModes = new Set();
465
+ let noGpuAccelerationWarningShown = false;
466
+ let cpuForcedPrebuiltFallbackWarningShown = false;
467
+ function isCpuModeRequested() {
468
+ return resolveLlamaGpuMode() === false;
469
+ }
470
+ export class LlamaCpp {
471
+ _ciMode = !!process.env.CI;
472
+ llama = null;
473
+ embedModel = null;
474
+ embedModelPath = null;
475
+ embedContexts = [];
476
+ generateModel = null;
477
+ rerankModel = null;
478
+ rerankContexts = [];
479
+ embedModelUri;
480
+ generateModelUri;
481
+ rerankModelUri;
482
+ modelCacheDir;
483
+ expandContextSize;
484
+ // Ensure we don't load the same model/context concurrently (which can allocate duplicate VRAM).
485
+ embedModelLoadPromise = null;
486
+ generateModelLoadPromise = null;
487
+ rerankModelLoadPromise = null;
488
+ rerankContextsCreatePromise = null;
489
+ // Guard against concurrent ensureLlama() calls creating duplicate Llama
490
+ // instances. Without this, two concurrent callers each build their own
491
+ // runtime and the last write to this.llama wins, leaving models/grammars
492
+ // bound to different Llama instances ("different Llama instance" errors).
493
+ llamaLoadPromise = null;
494
+ // Inactivity timer for auto-unloading models
495
+ inactivityTimer = null;
496
+ inactivityTimeoutMs;
497
+ disposeModelsOnInactivity;
498
+ // Track disposal state to prevent double-dispose
499
+ disposed = false;
500
+ constructor(config = {}) {
501
+ // STRUCTURAL INVARIANT: the launcher (bin/qmd) and the Nix flake wrapper
502
+ // set GGML_METAL_NO_RESIDENCY=1 on darwin BEFORE the native binding loads,
503
+ // which prevents the libggml-metal static destructor assertion at process
504
+ // exit (ggml-org/llama.cpp#22593). Nix installs skip bin/qmd (#723).
505
+ // See isDarwinMetalMitigationActive() for the runtime check exposed to
506
+ // diagnostics. No constructor-time guard installation is needed.
507
+ this.embedModelUri = resolveEmbedModel({ embed: config.embedModel });
508
+ this.generateModelUri = resolveGenerateModel({ generate: config.generateModel });
509
+ this.rerankModelUri = resolveRerankModel({ rerank: config.rerankModel });
510
+ this.modelCacheDir = config.modelCacheDir || MODEL_CACHE_DIR;
511
+ this.expandContextSize = resolveExpandContextSize(config.expandContextSize);
512
+ this.inactivityTimeoutMs = config.inactivityTimeoutMs ?? DEFAULT_INACTIVITY_TIMEOUT_MS;
513
+ this.disposeModelsOnInactivity = config.disposeModelsOnInactivity ?? false;
514
+ }
515
+ get embedModelName() {
516
+ return this.embedModelUri;
517
+ }
518
+ get generateModelName() {
519
+ return this.generateModelUri;
520
+ }
521
+ get rerankModelName() {
522
+ return this.rerankModelUri;
523
+ }
524
+ /**
525
+ * Reset the inactivity timer. Called after each model operation.
526
+ * When timer fires, models are unloaded to free memory (if no active sessions).
527
+ */
528
+ touchActivity() {
529
+ // Clear existing timer
530
+ if (this.inactivityTimer) {
531
+ clearTimeout(this.inactivityTimer);
532
+ this.inactivityTimer = null;
533
+ }
534
+ // Only set timer if we have disposable contexts and timeout is enabled
535
+ if (this.inactivityTimeoutMs > 0 && this.hasLoadedContexts()) {
536
+ this.inactivityTimer = setTimeout(() => {
537
+ // Check if session manager allows unloading
538
+ // canUnloadLLM is defined later in this file - it checks the session manager
539
+ // We use dynamic import pattern to avoid circular dependency issues
540
+ if (typeof canUnloadLLM === 'function' && !canUnloadLLM()) {
541
+ // Active sessions/operations - reschedule timer
542
+ this.touchActivity();
543
+ return;
544
+ }
545
+ this.unloadIdleResources().catch(err => {
546
+ console.error("Error unloading idle resources:", err);
547
+ });
548
+ }, this.inactivityTimeoutMs);
549
+ // Don't keep process alive just for this timer
550
+ this.inactivityTimer.unref();
551
+ }
552
+ }
553
+ /**
554
+ * Check if any contexts are currently loaded (and therefore worth unloading on inactivity).
555
+ */
556
+ hasLoadedContexts() {
557
+ return !!(this.embedContexts.length > 0 || this.rerankContexts.length > 0);
558
+ }
559
+ /**
560
+ * Unload idle resources but keep the instance alive for future use.
561
+ *
562
+ * By default, this disposes contexts (and their dependent sequences), while keeping models loaded.
563
+ * This matches the intended lifecycle: model → context → sequence, where contexts are per-session.
564
+ */
565
+ async unloadIdleResources() {
566
+ // Don't unload if already disposed
567
+ if (this.disposed) {
568
+ return;
569
+ }
570
+ // Clear timer
571
+ if (this.inactivityTimer) {
572
+ clearTimeout(this.inactivityTimer);
573
+ this.inactivityTimer = null;
574
+ }
575
+ // Dispose contexts first
576
+ for (const ctx of this.embedContexts) {
577
+ await ctx.dispose();
578
+ }
579
+ this.embedContexts = [];
580
+ for (const ctx of this.rerankContexts) {
581
+ await ctx.dispose();
582
+ }
583
+ this.rerankContexts = [];
584
+ // Optionally dispose models too (opt-in)
585
+ if (this.disposeModelsOnInactivity) {
586
+ if (this.embedModel) {
587
+ await this.embedModel.dispose();
588
+ this.embedModel = null;
589
+ this.embedModelPath = null;
590
+ }
591
+ if (this.generateModel) {
592
+ await this.generateModel.dispose();
593
+ this.generateModel = null;
594
+ }
595
+ if (this.rerankModel) {
596
+ await this.rerankModel.dispose();
597
+ this.rerankModel = null;
598
+ }
599
+ // Reset load promises so models can be reloaded later
600
+ this.embedModelLoadPromise = null;
601
+ this.generateModelLoadPromise = null;
602
+ this.rerankModelLoadPromise = null;
603
+ this.rerankContextsCreatePromise = null;
604
+ }
605
+ // Note: We keep llama instance alive - it's lightweight
606
+ }
607
+ /**
608
+ * Ensure model cache directory exists
609
+ */
610
+ ensureModelCacheDir() {
611
+ if (!existsSync(this.modelCacheDir)) {
612
+ mkdirSync(this.modelCacheDir, { recursive: true });
613
+ }
614
+ }
615
+ /**
616
+ * Initialize the llama instance (lazy)
617
+ */
618
+ async ensureLlama(allowBuild = true) {
619
+ if (this.llama) {
620
+ return this.llama;
621
+ }
622
+ if (this.llamaLoadPromise) {
623
+ return await this.llamaLoadPromise;
624
+ }
625
+ this.llamaLoadPromise = this.loadLlamaRuntime(allowBuild);
626
+ try {
627
+ return await this.llamaLoadPromise;
628
+ }
629
+ finally {
630
+ this.llamaLoadPromise = null;
631
+ }
632
+ }
633
+ async loadLlamaRuntime(allowBuild = true) {
634
+ if (!this.llama) {
635
+ const gpuMode = resolveLlamaGpuMode();
636
+ // Skip source build when install dir is read-only (e.g. NixOS store).
637
+ const canBuild = allowBuild && canWriteLlamaDir();
638
+ const { getLlama, getLlamaGpuTypes, LlamaLogLevel } = await loadNodeLlamaCpp();
639
+ const loadLlama = async (gpu, sourceBuildAllowed = canBuild, buildOverride) => await withNativeStdoutRedirectedToStderr(() => getLlama({
640
+ // Prefer packaged prebuilt bindings before compiling llama.cpp locally.
641
+ // node-llama-cpp documents gpu:"auto" as the best default: Metal on
642
+ // Apple Silicon, CUDA when fully available, Vulkan where available,
643
+ // then CPU. Use build:"auto" for normal loads and build:"never" for
644
+ // diagnostic/probe paths that must not compile llama.cpp.
645
+ build: buildOverride ?? (sourceBuildAllowed ? "auto" : "never"),
646
+ logLevel: LlamaLogLevel.error,
647
+ gpu,
648
+ progressLogs: false,
649
+ skipDownload: !sourceBuildAllowed,
650
+ }));
651
+ const loadCpuCompatibleLlama = async () => {
652
+ try {
653
+ return await loadLlama(false, false);
654
+ }
655
+ catch (err) {
656
+ // Some platforms, notably Apple Silicon, ship a Metal prebuilt but no
657
+ // CPU-only prebuilt. Do a fast no-build lookup for an actual CPU
658
+ // binding first; if it does not exist, use the packaged auto/Metal
659
+ // binding and disable model offloading via gpuLayers: 0.
660
+ if (!cpuForcedPrebuiltFallbackWarningShown) {
661
+ cpuForcedPrebuiltFallbackWarningShown = true;
662
+ process.stderr.write(`QMD Warning: CPU-only llama.cpp prebuilt not available (${err instanceof Error ? err.message : String(err)}); using packaged backend with GPU offloading disabled.\n`);
663
+ }
664
+ return await loadLlama("auto", false);
665
+ }
666
+ };
667
+ let llama;
668
+ if (gpuMode === false) {
669
+ llama = await loadCpuCompatibleLlama();
670
+ }
671
+ else if (failedGpuInitModes.has(gpuMode)) {
672
+ process.stderr.write(`QMD Warning: skipping previously failed GPU init${gpuMode === "auto" ? "" : ` for QMD_LLAMA_GPU=${gpuMode}`}, using CPU.\n`);
673
+ llama = await loadCpuCompatibleLlama();
674
+ }
675
+ else {
676
+ try {
677
+ llama = await loadLlama(gpuMode);
678
+ // If node-llama-cpp auto-detection chose CPU, do one no-build pass
679
+ // over all OS-valid packaged GPU backends. This preserves the
680
+ // documented auto mode for Metal/CUDA/Vulkan while recovering on
681
+ // systems where a packaged backend can load but detection is too
682
+ // conservative. Never compile during these extra probes.
683
+ if (gpuMode === "auto" && llama.gpu === false && getLlamaGpuTypes) {
684
+ const candidates = (await getLlamaGpuTypes("allValid"))
685
+ .filter((candidate) => candidate !== false && candidate !== "auto");
686
+ for (const candidate of candidates) {
687
+ if (failedGpuInitModes.has(candidate))
688
+ continue;
689
+ try {
690
+ const gpuLlama = await loadLlama(candidate, false, "never");
691
+ if (gpuLlama.gpu !== false) {
692
+ await disposeWithTimeout("CPU llama runtime", () => llama.dispose());
693
+ llama = gpuLlama;
694
+ break;
695
+ }
696
+ await disposeWithTimeout(`${candidate} probe runtime`, () => gpuLlama.dispose());
697
+ }
698
+ catch {
699
+ failedGpuInitModes.add(candidate);
700
+ }
701
+ }
702
+ }
703
+ }
704
+ catch (err) {
705
+ // GPU backend (e.g. Vulkan/CUDA on headless/driverless machines) can throw at init.
706
+ // Fall back to CPU so qmd still works, and cache the failure to avoid repeated
707
+ // expensive native build/probe attempts in this process.
708
+ failedGpuInitModes.add(gpuMode);
709
+ process.stderr.write(`QMD Warning: GPU init failed${gpuMode === "auto" ? "" : ` for QMD_LLAMA_GPU=${gpuMode}`} (${err instanceof Error ? err.message : String(err)}), falling back to CPU.\n`);
710
+ llama = await loadCpuCompatibleLlama();
711
+ }
712
+ }
713
+ if (llama.gpu === false && !noGpuAccelerationWarningShown) {
714
+ noGpuAccelerationWarningShown = true;
715
+ process.stderr.write("QMD Warning: no GPU acceleration, running on CPU (slow). Run 'qmd doctor' for device diagnostics.\n");
716
+ }
717
+ this.llama = llama;
718
+ }
719
+ return this.llama;
720
+ }
721
+ isCpuOffloadForced() {
722
+ return isCpuModeRequested();
723
+ }
724
+ modelLoadOptions(modelPath) {
725
+ return {
726
+ modelPath,
727
+ ...(this.isCpuOffloadForced() ? { gpuLayers: 0 } : {}),
728
+ };
729
+ }
730
+ /**
731
+ * Resolve a model URI to a local path, downloading if needed.
732
+ * Validates the downloaded file is actually a GGUF model (not an HTML error page
733
+ * from a proxy or firewall).
734
+ */
735
+ async resolveModel(modelUri) {
736
+ this.ensureModelCacheDir();
737
+ // resolveModelFile handles HF URIs and downloads to the cache dir
738
+ const { resolveModelFile } = await loadNodeLlamaCpp();
739
+ const modelPath = await resolveModelFile(modelUri, resolveModelFileArgs(this.modelCacheDir));
740
+ validateGgufFile(modelPath, modelUri);
741
+ return modelPath;
742
+ }
743
+ /**
744
+ * Load embedding model (lazy)
745
+ */
746
+ async ensureEmbedModel() {
747
+ if (this.embedModel) {
748
+ return this.embedModel;
749
+ }
750
+ if (this.embedModelLoadPromise) {
751
+ return await this.embedModelLoadPromise;
752
+ }
753
+ this.embedModelLoadPromise = (async () => {
754
+ const llama = await this.ensureLlama();
755
+ const modelPath = await this.resolveModel(this.embedModelUri);
756
+ const model = await llama.loadModel(this.modelLoadOptions(modelPath));
757
+ this.embedModel = model;
758
+ this.embedModelPath = modelPath;
759
+ // Model loading counts as activity - ping to keep alive
760
+ this.touchActivity();
761
+ return model;
762
+ })();
763
+ try {
764
+ return await this.embedModelLoadPromise;
765
+ }
766
+ finally {
767
+ // Keep the resolved model cached; clear only the in-flight promise.
768
+ this.embedModelLoadPromise = null;
769
+ }
770
+ }
771
+ /**
772
+ * Compute how many parallel contexts to create.
773
+ *
774
+ * GPU: constrained by VRAM (25% of free, capped at 8).
775
+ * CPU: constrained by cores. Splitting threads across contexts enables
776
+ * true parallelism (each context runs on its own cores). Use at most
777
+ * half the math cores, with at least 4 threads per context.
778
+ */
779
+ async computeParallelism(perContextMB, reserveMB = 0) {
780
+ const llama = await this.ensureLlama();
781
+ if (!this.isCpuOffloadForced() && llama.gpu) {
782
+ try {
783
+ const vram = await llama.getVramState();
784
+ const freeMB = vram.free / (1024 * 1024);
785
+ const computed = computeGpuContextPoolSize({ freeMB, perContextMB, reserveMB });
786
+ return resolveSafeParallelism({ gpu: llama.gpu, computed });
787
+ }
788
+ catch {
789
+ return resolveSafeParallelism({ gpu: llama.gpu, computed: 2 });
790
+ }
791
+ }
792
+ // CPU: split cores across contexts. At least 4 threads per context.
793
+ const cores = llama.cpuMathCores || 4;
794
+ const maxContexts = Math.floor(cores / 4);
795
+ const computed = Math.max(1, Math.min(4, maxContexts));
796
+ return resolveSafeParallelism({ gpu: false, computed });
797
+ }
798
+ /**
799
+ * Get the number of threads each context should use, given N parallel contexts.
800
+ * Splits available math cores evenly across contexts.
801
+ */
802
+ async threadsPerContext(parallelism) {
803
+ const llama = await this.ensureLlama();
804
+ if (!this.isCpuOffloadForced() && llama.gpu)
805
+ return 0; // GPU: let the library decide
806
+ const cores = llama.cpuMathCores || 4;
807
+ return Math.max(1, Math.floor(cores / parallelism));
808
+ }
809
+ /**
810
+ * Load embedding contexts (lazy). Creates multiple for parallel embedding.
811
+ * Uses promise guard to prevent concurrent context creation race condition.
812
+ */
813
+ embedContextsCreatePromise = null;
814
+ async ensureEmbedContexts() {
815
+ if (this.embedContexts.length > 0) {
816
+ this.touchActivity();
817
+ return this.embedContexts;
818
+ }
819
+ if (this.embedContextsCreatePromise) {
820
+ return await this.embedContextsCreatePromise;
821
+ }
822
+ this.embedContextsCreatePromise = (async () => {
823
+ const model = await this.ensureEmbedModel();
824
+ // Per-context cost depends on the loaded GGUF. The old hardcoded 150 MB
825
+ // figure was measured for nomic-embed; Qwen3-Embedding-0.6B is ~1190 MB
826
+ // and opening 8 of those exhausted VRAM so the reranker could not load (#799).
827
+ let perContextMB = BASELINE_EMBED_CONTEXT_MB;
828
+ if (this.embedModelPath) {
829
+ try {
830
+ perContextMB = estimateEmbedContextMB({
831
+ modelBytes: statSync(this.embedModelPath).size,
832
+ contextSize: LlamaCpp.EMBED_CONTEXT_SIZE,
833
+ });
834
+ }
835
+ catch {
836
+ // Keep the baseline if the file cannot be stat'd.
837
+ }
838
+ }
839
+ const n = await this.computeParallelism(perContextMB, EMBED_POOL_RERANK_RESERVE_MB);
840
+ const threads = await this.threadsPerContext(n);
841
+ for (let i = 0; i < n; i++) {
842
+ try {
843
+ this.embedContexts.push(await model.createEmbeddingContext({
844
+ contextSize: LlamaCpp.EMBED_CONTEXT_SIZE,
845
+ ...(threads > 0 ? { threads } : {}),
846
+ }));
847
+ }
848
+ catch {
849
+ if (this.embedContexts.length === 0)
850
+ throw new Error("Failed to create any embedding context");
851
+ break;
852
+ }
853
+ }
854
+ this.touchActivity();
855
+ return this.embedContexts;
856
+ })();
857
+ try {
858
+ return await this.embedContextsCreatePromise;
859
+ }
860
+ finally {
861
+ this.embedContextsCreatePromise = null;
862
+ }
863
+ }
864
+ /**
865
+ * Get a single embed context (for single-embed calls). Uses first from pool.
866
+ */
867
+ async ensureEmbedContext() {
868
+ const contexts = await this.ensureEmbedContexts();
869
+ return contexts[0];
870
+ }
871
+ /**
872
+ * Load generation model (lazy) - context is created fresh per call
873
+ */
874
+ async ensureGenerateModel() {
875
+ if (!this.generateModel) {
876
+ if (this.generateModelLoadPromise) {
877
+ return await this.generateModelLoadPromise;
878
+ }
879
+ this.generateModelLoadPromise = (async () => {
880
+ const llama = await this.ensureLlama();
881
+ const modelPath = await this.resolveModel(this.generateModelUri);
882
+ const model = await llama.loadModel(this.modelLoadOptions(modelPath));
883
+ this.generateModel = model;
884
+ return model;
885
+ })();
886
+ try {
887
+ await this.generateModelLoadPromise;
888
+ }
889
+ finally {
890
+ this.generateModelLoadPromise = null;
891
+ }
892
+ }
893
+ this.touchActivity();
894
+ if (!this.generateModel) {
895
+ throw new Error("Generate model not loaded");
896
+ }
897
+ return this.generateModel;
898
+ }
899
+ /**
900
+ * Load rerank model (lazy)
901
+ */
902
+ async ensureRerankModel() {
903
+ if (this.rerankModel) {
904
+ return this.rerankModel;
905
+ }
906
+ if (this.rerankModelLoadPromise) {
907
+ return await this.rerankModelLoadPromise;
908
+ }
909
+ this.rerankModelLoadPromise = (async () => {
910
+ const llama = await this.ensureLlama();
911
+ const modelPath = await this.resolveModel(this.rerankModelUri);
912
+ const model = await llama.loadModel(this.modelLoadOptions(modelPath));
913
+ this.rerankModel = model;
914
+ // Model loading counts as activity - ping to keep alive
915
+ this.touchActivity();
916
+ return model;
917
+ })();
918
+ try {
919
+ return await this.rerankModelLoadPromise;
920
+ }
921
+ finally {
922
+ this.rerankModelLoadPromise = null;
923
+ }
924
+ }
925
+ /**
926
+ * Load rerank contexts (lazy). Creates multiple contexts for parallel ranking.
927
+ * Each context has its own sequence, so they can evaluate independently.
928
+ *
929
+ * VRAM per context is governed by contextSize alone —
930
+ * LlamaRankingContextOptions has no flashAttention option.
931
+ */
932
+ // Qwen3 reranker template adds ~200 tokens overhead (system prompt, tags, etc.)
933
+ // Default 2048 was too small for longer documents (e.g. session transcripts,
934
+ // CJK text, or large markdown files) — callers hit "input lengths exceed
935
+ // context size" errors even after truncation because the overhead estimate
936
+ // was insufficient. 4096 comfortably fits the largest real-world chunks
937
+ // while staying well below the 40 960-token auto size.
938
+ // Override with QMD_RERANK_CONTEXT_SIZE env var if you need more headroom.
939
+ static RERANK_CONTEXT_SIZE = (() => {
940
+ const v = parseInt(process.env.QMD_RERANK_CONTEXT_SIZE ?? "", 10);
941
+ return Number.isFinite(v) && v > 0 ? v : 4096;
942
+ })();
943
+ static EMBED_CONTEXT_SIZE = (() => {
944
+ const v = parseInt(process.env.QMD_EMBED_CONTEXT_SIZE ?? "", 10);
945
+ return Number.isFinite(v) && v > 0 ? v : 2048;
946
+ })();
947
+ async ensureRerankContexts() {
948
+ if (this.rerankContexts.length > 0) {
949
+ this.touchActivity();
950
+ return this.rerankContexts;
951
+ }
952
+ if (this.rerankContextsCreatePromise) {
953
+ return await this.rerankContextsCreatePromise;
954
+ }
955
+ // Same mutex as ensureEmbedContexts: two overlapping query/rerank calls on a
956
+ // cold MCP server both saw length === 0, both created ranking contexts, and
957
+ // the inactivity timer disposed the loser → "Object is disposed" (#682).
958
+ this.rerankContextsCreatePromise = (async () => {
959
+ this.touchActivity();
960
+ const model = await this.ensureRerankModel();
961
+ const n = Math.min(await this.computeParallelism(1000), 4);
962
+ const threads = await this.threadsPerContext(n);
963
+ for (let i = 0; i < n; i++) {
964
+ try {
965
+ this.rerankContexts.push(await model.createRankingContext({
966
+ contextSize: LlamaCpp.RERANK_CONTEXT_SIZE,
967
+ ...(threads > 0 ? { threads } : {}),
968
+ }));
969
+ }
970
+ catch (error) {
971
+ if (this.rerankContexts.length === 0) {
972
+ // Surface the underlying failure (e.g. out of VRAM). A previous
973
+ // "retry without flash attention" path was dead: ranking contexts
974
+ // never accepted that option, so the retry repeated identical
975
+ // arguments and the real error was discarded.
976
+ const detail = error instanceof Error ? error.message : String(error);
977
+ console.warn(`Reranker unavailable — skipping reranking (${detail}). ` +
978
+ "Use --no-rerank to silence this warning.");
979
+ return [];
980
+ }
981
+ // At least one context exists — continue with reduced parallelism.
982
+ break;
983
+ }
984
+ }
985
+ this.touchActivity();
986
+ return this.rerankContexts;
987
+ })();
988
+ try {
989
+ return await this.rerankContextsCreatePromise;
990
+ }
991
+ finally {
992
+ this.rerankContextsCreatePromise = null;
993
+ }
994
+ }
995
+ // ==========================================================================
996
+ // Tokenization
997
+ // ==========================================================================
998
+ /**
999
+ * Tokenize text using the embedding model's tokenizer
1000
+ * Returns tokenizer tokens (opaque type from node-llama-cpp)
1001
+ */
1002
+ async tokenize(text) {
1003
+ await this.ensureEmbedContext(); // Ensure model is loaded
1004
+ if (!this.embedModel) {
1005
+ throw new Error("Embed model not loaded");
1006
+ }
1007
+ return this.embedModel.tokenize(text);
1008
+ }
1009
+ /**
1010
+ * Count tokens in text using the embedding model's tokenizer
1011
+ */
1012
+ async countTokens(text) {
1013
+ const tokens = await this.tokenize(text);
1014
+ return tokens.length;
1015
+ }
1016
+ /**
1017
+ * Detokenize token IDs back to text
1018
+ */
1019
+ async detokenize(tokens) {
1020
+ await this.ensureEmbedContext();
1021
+ if (!this.embedModel) {
1022
+ throw new Error("Embed model not loaded");
1023
+ }
1024
+ return this.embedModel.detokenize(tokens);
1025
+ }
1026
+ // ==========================================================================
1027
+ // Core API methods
1028
+ // ==========================================================================
1029
+ /**
1030
+ * Truncate text to fit within the embedding model's context window.
1031
+ * Uses the model's own tokenizer for accurate token counting, then
1032
+ * detokenizes back to text if truncation is needed.
1033
+ * Returns the (possibly truncated) text and whether truncation occurred.
1034
+ */
1035
+ resolveEmbedTokenLimit() {
1036
+ const trainedContextSize = this.embedModel?.trainContextSize;
1037
+ if (typeof trainedContextSize === "number" && Number.isFinite(trainedContextSize) && trainedContextSize > 0) {
1038
+ return Math.max(1, Math.min(LlamaCpp.EMBED_CONTEXT_SIZE, trainedContextSize));
1039
+ }
1040
+ return LlamaCpp.EMBED_CONTEXT_SIZE;
1041
+ }
1042
+ async truncateToContextSize(text) {
1043
+ if (!this.embedModel)
1044
+ return { text, truncated: false, limit: LlamaCpp.EMBED_CONTEXT_SIZE };
1045
+ const maxTokens = this.resolveEmbedTokenLimit();
1046
+ if (maxTokens <= 0)
1047
+ return { text, truncated: false, limit: maxTokens };
1048
+ const tokens = this.embedModel.tokenize(text);
1049
+ if (tokens.length <= maxTokens)
1050
+ return { text, truncated: false, limit: maxTokens };
1051
+ // Leave a small margin (4 tokens) for BOS/EOS overhead
1052
+ const safeLimit = Math.max(1, maxTokens - 4);
1053
+ const truncatedTokens = tokens.slice(0, safeLimit);
1054
+ const truncatedText = this.embedModel.detokenize(truncatedTokens);
1055
+ return { text: truncatedText, truncated: true, limit: maxTokens };
1056
+ }
1057
+ async embed(text, options = {}) {
1058
+ // Ping activity at start to keep models alive during this operation
1059
+ this.touchActivity();
1060
+ try {
1061
+ const context = await this.ensureEmbedContext();
1062
+ // Guard: truncate text that exceeds model context window to prevent GGML crash
1063
+ const { text: safeText, truncated, limit } = await this.truncateToContextSize(text);
1064
+ if (truncated) {
1065
+ console.warn(`⚠ Text truncated to fit embedding context (${limit} tokens)`);
1066
+ }
1067
+ const embedding = await context.getEmbeddingFor(safeText);
1068
+ return {
1069
+ embedding: Array.from(embedding.vector),
1070
+ model: options.model ?? this.embedModelUri,
1071
+ };
1072
+ }
1073
+ catch (error) {
1074
+ console.error("Embedding error:", error);
1075
+ return null;
1076
+ }
1077
+ }
1078
+ /**
1079
+ * Batch embed multiple texts efficiently
1080
+ * Uses Promise.all for parallel embedding - node-llama-cpp handles batching internally
1081
+ */
1082
+ async embedBatch(texts, options = {}) {
1083
+ if (this._ciMode)
1084
+ throw new Error("LLM operations are disabled in CI (set CI=true)");
1085
+ // Ping activity at start to keep models alive during this operation
1086
+ this.touchActivity();
1087
+ if (texts.length === 0)
1088
+ return [];
1089
+ try {
1090
+ const contexts = await this.ensureEmbedContexts();
1091
+ const n = contexts.length;
1092
+ if (n === 1) {
1093
+ // Single context: sequential (no point splitting)
1094
+ const context = contexts[0];
1095
+ const embeddings = [];
1096
+ for (const text of texts) {
1097
+ try {
1098
+ const { text: safeText, truncated, limit } = await this.truncateToContextSize(text);
1099
+ if (truncated) {
1100
+ console.warn(`⚠ Batch text truncated to fit embedding context (${limit} tokens)`);
1101
+ }
1102
+ const embedding = await context.getEmbeddingFor(safeText);
1103
+ this.touchActivity();
1104
+ embeddings.push({ embedding: Array.from(embedding.vector), model: options.model ?? this.embedModelUri });
1105
+ }
1106
+ catch (err) {
1107
+ console.error("Embedding error for text:", err);
1108
+ embeddings.push(null);
1109
+ }
1110
+ }
1111
+ return embeddings;
1112
+ }
1113
+ // Multiple contexts: split texts across contexts for parallel evaluation
1114
+ const chunkSize = Math.ceil(texts.length / n);
1115
+ const chunks = Array.from({ length: n }, (_, i) => texts.slice(i * chunkSize, (i + 1) * chunkSize));
1116
+ const chunkResults = await Promise.all(chunks.map(async (chunk, i) => {
1117
+ const ctx = contexts[i];
1118
+ const results = [];
1119
+ for (const text of chunk) {
1120
+ try {
1121
+ const { text: safeText, truncated, limit } = await this.truncateToContextSize(text);
1122
+ if (truncated) {
1123
+ console.warn(`⚠ Batch text truncated to fit embedding context (${limit} tokens)`);
1124
+ }
1125
+ const embedding = await ctx.getEmbeddingFor(safeText);
1126
+ this.touchActivity();
1127
+ results.push({ embedding: Array.from(embedding.vector), model: options.model ?? this.embedModelUri });
1128
+ }
1129
+ catch (err) {
1130
+ console.error("Embedding error for text:", err);
1131
+ results.push(null);
1132
+ }
1133
+ }
1134
+ return results;
1135
+ }));
1136
+ return chunkResults.flat();
1137
+ }
1138
+ catch (error) {
1139
+ console.error("Batch embedding error:", error);
1140
+ return texts.map(() => null);
1141
+ }
1142
+ }
1143
+ async generate(prompt, options = {}) {
1144
+ if (this._ciMode)
1145
+ throw new Error("LLM operations are disabled in CI (set CI=true)");
1146
+ // Ping activity at start to keep models alive during this operation
1147
+ this.touchActivity();
1148
+ // Ensure model is loaded
1149
+ await this.ensureGenerateModel();
1150
+ // Create fresh context -> sequence -> session for each call
1151
+ const context = await this.generateModel.createContext();
1152
+ const sequence = context.getSequence();
1153
+ const { LlamaChatSession } = await loadNodeLlamaCpp();
1154
+ const session = new LlamaChatSession({ contextSequence: sequence });
1155
+ const maxTokens = options.maxTokens ?? 150;
1156
+ // Qwen3 recommends temp=0.7, topP=0.8, topK=20 for non-thinking mode
1157
+ // DO NOT use greedy decoding (temp=0) - causes repetition loops
1158
+ const temperature = options.temperature ?? 0.7;
1159
+ let result = "";
1160
+ try {
1161
+ await session.prompt(prompt, {
1162
+ maxTokens,
1163
+ temperature,
1164
+ topK: 20,
1165
+ topP: 0.8,
1166
+ onTextChunk: (text) => {
1167
+ result += text;
1168
+ },
1169
+ });
1170
+ return {
1171
+ text: result,
1172
+ model: this.generateModelUri,
1173
+ done: true,
1174
+ };
1175
+ }
1176
+ finally {
1177
+ // Sequence dispose is async as of node-llama-cpp 3.20; await it before the parent context.
1178
+ await disposeSequenceThenContext(sequence, context);
1179
+ }
1180
+ }
1181
+ async modelExists(modelUri) {
1182
+ // For HuggingFace URIs, we assume they exist
1183
+ // For local paths, check if file exists
1184
+ if (modelUri.startsWith("hf:")) {
1185
+ return { name: modelUri, exists: true };
1186
+ }
1187
+ const exists = existsSync(modelUri);
1188
+ return {
1189
+ name: modelUri,
1190
+ exists,
1191
+ path: exists ? modelUri : undefined,
1192
+ };
1193
+ }
1194
+ // ==========================================================================
1195
+ // High-level abstractions
1196
+ // ==========================================================================
1197
+ async expandQuery(query, options = {}) {
1198
+ if (this._ciMode)
1199
+ throw new Error("LLM operations are disabled in CI (set CI=true)");
1200
+ // Ping activity at start to keep models alive during this operation
1201
+ this.touchActivity();
1202
+ const llama = await this.ensureLlama();
1203
+ await this.ensureGenerateModel();
1204
+ const includeLexical = options.includeLexical ?? true;
1205
+ const context = options.context;
1206
+ // The expansion prompt consumes ONLY the query text. Caller intent is
1207
+ // free-form meta-language that the expansion model reproduced verbatim as
1208
+ // lex/vec sub-queries — degenerate terms that match nothing. Intent still
1209
+ // shapes retrieval where it belongs: the reranker query prefix and
1210
+ // keyword-based chunk/snippet selection.
1211
+ const prompt = `/no_think Expand this search query: ${query}`;
1212
+ // Set up inside the try so any failure (grammar creation, context
1213
+ // allocation/VRAM, session prompt) falls back to the original query
1214
+ // instead of propagating and failing the caller's operation.
1215
+ let genContext;
1216
+ let sequence;
1217
+ try {
1218
+ const grammar = await llama.createGrammar({
1219
+ grammar: `
1220
+ root ::= line+
1221
+ line ::= type ": " content "\\n"
1222
+ type ::= "lex" | "vec" | "hyde"
1223
+ content ::= [^\\n]+
1224
+ `
1225
+ });
1226
+ // Create a bounded context for expansion to prevent large default VRAM allocations.
1227
+ genContext = await this.generateModel.createContext({
1228
+ contextSize: this.expandContextSize,
1229
+ });
1230
+ sequence = genContext.getSequence();
1231
+ const { LlamaChatSession } = await loadNodeLlamaCpp();
1232
+ const session = new LlamaChatSession({ contextSequence: sequence });
1233
+ // Qwen3 recommended settings for non-thinking mode:
1234
+ // temp=0.7, topP=0.8, topK=20, presence_penalty for repetition
1235
+ // DO NOT use greedy decoding (temp=0) - causes infinite loops
1236
+ const result = await session.prompt(prompt, {
1237
+ grammar,
1238
+ maxTokens: 600,
1239
+ temperature: 0.7,
1240
+ topK: 20,
1241
+ topP: 0.8,
1242
+ repeatPenalty: {
1243
+ lastTokens: 64,
1244
+ presencePenalty: 0.5,
1245
+ },
1246
+ });
1247
+ const lines = result.trim().split("\n");
1248
+ const queryLower = query.toLowerCase();
1249
+ const queryTerms = queryLower.replace(/[^a-z0-9\s]/g, " ").split(/\s+/).filter(Boolean);
1250
+ const hasQueryTerm = (text) => {
1251
+ const lower = text.toLowerCase();
1252
+ if (queryTerms.length === 0)
1253
+ return true;
1254
+ return queryTerms.some(term => lower.includes(term));
1255
+ };
1256
+ const queryables = lines.map(line => {
1257
+ const colonIdx = line.indexOf(":");
1258
+ if (colonIdx === -1)
1259
+ return null;
1260
+ const type = line.slice(0, colonIdx).trim();
1261
+ if (type !== 'lex' && type !== 'vec' && type !== 'hyde')
1262
+ return null;
1263
+ const text = line.slice(colonIdx + 1).trim();
1264
+ if (!hasQueryTerm(text))
1265
+ return null;
1266
+ return { type: type, text };
1267
+ }).filter((q) => q !== null);
1268
+ // Filter out lex entries if not requested
1269
+ const filtered = includeLexical ? queryables : queryables.filter(q => q.type !== 'lex');
1270
+ if (filtered.length > 0)
1271
+ return filtered;
1272
+ const fallback = [
1273
+ { type: 'hyde', text: `Information about ${query}` },
1274
+ { type: 'lex', text: query },
1275
+ { type: 'vec', text: query },
1276
+ ];
1277
+ return includeLexical ? fallback : fallback.filter(q => q.type !== 'lex');
1278
+ }
1279
+ catch (error) {
1280
+ console.error("Structured query expansion failed:", error);
1281
+ // Fallback to original query
1282
+ const fallback = [{ type: 'vec', text: query }];
1283
+ if (includeLexical)
1284
+ fallback.unshift({ type: 'lex', text: query });
1285
+ return fallback;
1286
+ }
1287
+ finally {
1288
+ if (genContext)
1289
+ await disposeSequenceThenContext(sequence, genContext);
1290
+ }
1291
+ }
1292
+ // Qwen3 reranker chat template overhead (system prompt, tags, separators).
1293
+ // Measured at ~350 tokens on real queries; use 512 as a safe upper bound so
1294
+ // the truncation budget never lets a document slip past the context limit.
1295
+ static RERANK_TEMPLATE_OVERHEAD = 512;
1296
+ static RERANK_TARGET_DOCS_PER_CONTEXT = 10;
1297
+ async rerank(query, documents, options = {}) {
1298
+ if (this._ciMode)
1299
+ throw new Error("LLM operations are disabled in CI (set CI=true)");
1300
+ // Ping activity at start to keep models alive during this operation
1301
+ this.touchActivity();
1302
+ const contexts = await this.ensureRerankContexts();
1303
+ if (contexts.length === 0) {
1304
+ return {
1305
+ results: documents.map((d) => ({ ...d, score: 0.5, index: 0 })),
1306
+ model: "fallback",
1307
+ };
1308
+ }
1309
+ const model = await this.ensureRerankModel();
1310
+ // Truncate documents that would exceed the rerank context size.
1311
+ // Budget = contextSize - template overhead - query tokens
1312
+ const queryTokens = model.tokenize(query).length;
1313
+ const maxDocTokens = LlamaCpp.RERANK_CONTEXT_SIZE - LlamaCpp.RERANK_TEMPLATE_OVERHEAD - queryTokens;
1314
+ const truncationCache = new Map();
1315
+ const truncatedDocs = documents.map((doc) => {
1316
+ const cached = truncationCache.get(doc.text);
1317
+ if (cached !== undefined) {
1318
+ return cached === doc.text ? doc : { ...doc, text: cached };
1319
+ }
1320
+ const tokens = model.tokenize(doc.text);
1321
+ const truncatedText = tokens.length <= maxDocTokens
1322
+ ? doc.text
1323
+ : model.detokenize(tokens.slice(0, maxDocTokens));
1324
+ truncationCache.set(doc.text, truncatedText);
1325
+ if (truncatedText === doc.text)
1326
+ return doc;
1327
+ return { ...doc, text: truncatedText };
1328
+ });
1329
+ // Deduplicate identical effective texts before scoring.
1330
+ // This avoids redundant work for repeated chunks and fixes collisions where
1331
+ // multiple docs map to the same chunk text.
1332
+ const textToDocs = new Map();
1333
+ truncatedDocs.forEach((doc, index) => {
1334
+ const existing = textToDocs.get(doc.text);
1335
+ if (existing) {
1336
+ existing.push({ file: doc.file, index });
1337
+ }
1338
+ else {
1339
+ textToDocs.set(doc.text, [{ file: doc.file, index }]);
1340
+ }
1341
+ });
1342
+ // Extract just the text for ranking
1343
+ const texts = Array.from(textToDocs.keys());
1344
+ // Split documents across contexts for parallel evaluation.
1345
+ // Each context has its own sequence with a lock, so parallelism comes
1346
+ // from multiple contexts evaluating different chunks simultaneously.
1347
+ const activeContextCount = Math.max(1, Math.min(contexts.length, Math.ceil(texts.length / LlamaCpp.RERANK_TARGET_DOCS_PER_CONTEXT)));
1348
+ const activeContexts = contexts.slice(0, activeContextCount);
1349
+ const chunkSize = Math.ceil(texts.length / activeContexts.length);
1350
+ const chunks = Array.from({ length: activeContexts.length }, (_, i) => texts.slice(i * chunkSize, (i + 1) * chunkSize)).filter(chunk => chunk.length > 0);
1351
+ const allScores = await Promise.all(chunks.map((chunk, i) => activeContexts[i].rankAll(query, chunk)));
1352
+ // Reassemble scores in original order and sort
1353
+ const flatScores = allScores.flat();
1354
+ const ranked = texts
1355
+ .map((text, i) => ({ document: text, score: flatScores[i] }))
1356
+ .sort((a, b) => b.score - a.score);
1357
+ // Map back to our result format.
1358
+ const results = [];
1359
+ for (const item of ranked) {
1360
+ const docInfos = textToDocs.get(item.document) ?? [];
1361
+ for (const docInfo of docInfos) {
1362
+ results.push({
1363
+ file: docInfo.file,
1364
+ score: item.score,
1365
+ index: docInfo.index,
1366
+ });
1367
+ }
1368
+ }
1369
+ return {
1370
+ results,
1371
+ model: this.rerankModelUri,
1372
+ };
1373
+ }
1374
+ /**
1375
+ * Get device/GPU info for status display.
1376
+ * Initializes llama if not already done.
1377
+ */
1378
+ async getDeviceInfo(options = {}) {
1379
+ const llama = await this.ensureLlama(options.allowBuild ?? true);
1380
+ const cpuForced = this.isCpuOffloadForced();
1381
+ const gpuDevices = cpuForced ? [] : await llama.getGpuDeviceNames();
1382
+ let vram;
1383
+ if (!cpuForced && llama.gpu) {
1384
+ try {
1385
+ const state = await llama.getVramState();
1386
+ vram = { total: state.total, used: state.used, free: state.free };
1387
+ }
1388
+ catch { /* no vram info */ }
1389
+ }
1390
+ return {
1391
+ gpu: cpuForced ? false : llama.gpu,
1392
+ gpuOffloading: !cpuForced && llama.supportsGpuOffloading,
1393
+ gpuDevices,
1394
+ vram,
1395
+ cpuCores: llama.cpuMathCores,
1396
+ };
1397
+ }
1398
+ async dispose() {
1399
+ // Prevent double-dispose
1400
+ if (this.disposed) {
1401
+ return;
1402
+ }
1403
+ this.disposed = true;
1404
+ // Clear inactivity timer
1405
+ if (this.inactivityTimer) {
1406
+ clearTimeout(this.inactivityTimer);
1407
+ this.inactivityTimer = null;
1408
+ }
1409
+ // Explicitly dispose in dependency order: contexts first, then models, then llama.
1410
+ // Relying only on llama.dispose() leaves Metal resource sets alive until process
1411
+ // finalization on Apple Silicon, where ggml_metal_device_free can abort after
1412
+ // otherwise-successful CLI output (#368).
1413
+ for (const ctx of this.embedContexts) {
1414
+ await disposeWithTimeout("embedding context", () => ctx.dispose());
1415
+ }
1416
+ this.embedContexts = [];
1417
+ for (const ctx of this.rerankContexts) {
1418
+ await disposeWithTimeout("rerank context", () => ctx.dispose());
1419
+ }
1420
+ this.rerankContexts = [];
1421
+ if (this.embedModel) {
1422
+ await disposeWithTimeout("embedding model", () => this.embedModel.dispose());
1423
+ this.embedModel = null;
1424
+ this.embedModelPath = null;
1425
+ }
1426
+ if (this.generateModel) {
1427
+ await disposeWithTimeout("generation model", () => this.generateModel.dispose());
1428
+ this.generateModel = null;
1429
+ }
1430
+ if (this.rerankModel) {
1431
+ await disposeWithTimeout("rerank model", () => this.rerankModel.dispose());
1432
+ this.rerankModel = null;
1433
+ }
1434
+ if (this.llama) {
1435
+ await disposeWithTimeout("llama runtime", () => this.llama.dispose());
1436
+ this.llama = null;
1437
+ }
1438
+ // Clear any in-flight load/create promises
1439
+ this.embedModelLoadPromise = null;
1440
+ this.embedContextsCreatePromise = null;
1441
+ this.generateModelLoadPromise = null;
1442
+ this.rerankModelLoadPromise = null;
1443
+ this.rerankContextsCreatePromise = null;
1444
+ this.llamaLoadPromise = null;
1445
+ }
1446
+ }
1447
+ // =============================================================================
1448
+ // Session Management Layer
1449
+ // =============================================================================
1450
+ /**
1451
+ * Manages LLM session lifecycle with reference counting.
1452
+ * Coordinates with LlamaCpp idle timeout to prevent disposal during active sessions.
1453
+ */
1454
+ class LLMSessionManager {
1455
+ llm;
1456
+ _activeSessionCount = 0;
1457
+ _inFlightOperations = 0;
1458
+ constructor(llm) {
1459
+ this.llm = llm;
1460
+ }
1461
+ get activeSessionCount() {
1462
+ return this._activeSessionCount;
1463
+ }
1464
+ get inFlightOperations() {
1465
+ return this._inFlightOperations;
1466
+ }
1467
+ /**
1468
+ * Returns true only when both session count and in-flight operations are 0.
1469
+ * Used by LlamaCpp to determine if idle unload is safe.
1470
+ */
1471
+ canUnload() {
1472
+ return this._activeSessionCount === 0 && this._inFlightOperations === 0;
1473
+ }
1474
+ acquire() {
1475
+ this._activeSessionCount++;
1476
+ }
1477
+ release() {
1478
+ this._activeSessionCount = Math.max(0, this._activeSessionCount - 1);
1479
+ }
1480
+ operationStart() {
1481
+ this._inFlightOperations++;
1482
+ }
1483
+ operationEnd() {
1484
+ this._inFlightOperations = Math.max(0, this._inFlightOperations - 1);
1485
+ }
1486
+ getLlamaCpp() {
1487
+ return this.llm;
1488
+ }
1489
+ }
1490
+ /**
1491
+ * Error thrown when an operation is attempted on a released or aborted session.
1492
+ */
1493
+ export class SessionReleasedError extends Error {
1494
+ constructor(message = "LLM session has been released or aborted") {
1495
+ super(message);
1496
+ this.name = "SessionReleasedError";
1497
+ }
1498
+ }
1499
+ /**
1500
+ * Scoped LLM session with automatic lifecycle management.
1501
+ * Wraps LlamaCpp methods with operation tracking and abort handling.
1502
+ */
1503
+ class LLMSession {
1504
+ manager;
1505
+ released = false;
1506
+ abortController;
1507
+ maxDurationTimer = null;
1508
+ name;
1509
+ constructor(manager, options = {}) {
1510
+ this.manager = manager;
1511
+ this.name = options.name || "unnamed";
1512
+ this.abortController = new AbortController();
1513
+ // Link external abort signal if provided
1514
+ if (options.signal) {
1515
+ if (options.signal.aborted) {
1516
+ this.abortController.abort(options.signal.reason);
1517
+ }
1518
+ else {
1519
+ options.signal.addEventListener("abort", () => {
1520
+ this.abortController.abort(options.signal.reason);
1521
+ }, { once: true });
1522
+ }
1523
+ }
1524
+ // Set up max duration timer
1525
+ const maxDuration = options.maxDuration ?? 10 * 60 * 1000; // Default 10 minutes
1526
+ if (maxDuration > 0) {
1527
+ this.maxDurationTimer = setTimeout(() => {
1528
+ this.abortController.abort(new Error(`Session "${this.name}" exceeded max duration of ${maxDuration}ms`));
1529
+ }, maxDuration);
1530
+ this.maxDurationTimer.unref(); // Don't keep process alive
1531
+ }
1532
+ // Acquire session lease
1533
+ this.manager.acquire();
1534
+ }
1535
+ get isValid() {
1536
+ return !this.released && !this.abortController.signal.aborted;
1537
+ }
1538
+ get signal() {
1539
+ return this.abortController.signal;
1540
+ }
1541
+ /**
1542
+ * Release the session and decrement ref count.
1543
+ * Called automatically by withLLMSession when the callback completes.
1544
+ */
1545
+ release() {
1546
+ if (this.released)
1547
+ return;
1548
+ this.released = true;
1549
+ if (this.maxDurationTimer) {
1550
+ clearTimeout(this.maxDurationTimer);
1551
+ this.maxDurationTimer = null;
1552
+ }
1553
+ this.abortController.abort(new Error("Session released"));
1554
+ this.manager.release();
1555
+ }
1556
+ /**
1557
+ * Wrap an operation with tracking and abort checking.
1558
+ */
1559
+ async withOperation(fn) {
1560
+ if (!this.isValid) {
1561
+ throw new SessionReleasedError();
1562
+ }
1563
+ this.manager.operationStart();
1564
+ try {
1565
+ // Check abort before starting
1566
+ if (this.abortController.signal.aborted) {
1567
+ throw new SessionReleasedError(this.abortController.signal.reason?.message || "Session aborted");
1568
+ }
1569
+ return await fn();
1570
+ }
1571
+ finally {
1572
+ this.manager.operationEnd();
1573
+ }
1574
+ }
1575
+ async embed(text, options) {
1576
+ return this.withOperation(() => this.manager.getLlamaCpp().embed(text, options));
1577
+ }
1578
+ async embedBatch(texts, options) {
1579
+ return this.withOperation(() => this.manager.getLlamaCpp().embedBatch(texts, options));
1580
+ }
1581
+ async expandQuery(query, options) {
1582
+ return this.withOperation(() => this.manager.getLlamaCpp().expandQuery(query, options));
1583
+ }
1584
+ async rerank(query, documents, options) {
1585
+ return this.withOperation(() => this.manager.getLlamaCpp().rerank(query, documents, options));
1586
+ }
1587
+ }
1588
+ // Session manager for the default LlamaCpp instance
1589
+ let defaultSessionManager = null;
1590
+ /**
1591
+ * Get the session manager for the default LlamaCpp instance.
1592
+ */
1593
+ function getSessionManager() {
1594
+ const llm = getDefaultLlamaCpp();
1595
+ if (!defaultSessionManager || defaultSessionManager.getLlamaCpp() !== llm) {
1596
+ defaultSessionManager = new LLMSessionManager(llm);
1597
+ }
1598
+ return defaultSessionManager;
1599
+ }
1600
+ /**
1601
+ * Execute a function with a scoped LLM session.
1602
+ * The session provides lifecycle guarantees - resources won't be disposed mid-operation.
1603
+ *
1604
+ * @example
1605
+ * ```typescript
1606
+ * await withLLMSession(async (session) => {
1607
+ * const expanded = await session.expandQuery(query);
1608
+ * const embeddings = await session.embedBatch(texts);
1609
+ * const reranked = await session.rerank(query, docs);
1610
+ * return reranked;
1611
+ * }, { maxDuration: 10 * 60 * 1000, name: 'querySearch' });
1612
+ * ```
1613
+ */
1614
+ export async function withLLMSession(fn, options) {
1615
+ const manager = getSessionManager();
1616
+ const session = new LLMSession(manager, options);
1617
+ try {
1618
+ return await fn(session);
1619
+ }
1620
+ finally {
1621
+ session.release();
1622
+ }
1623
+ }
1624
+ /**
1625
+ * Execute a function with a scoped LLM session using a specific LlamaCpp instance.
1626
+ * Unlike withLLMSession, this does not use the global singleton.
1627
+ */
1628
+ export async function withLLMSessionForLlm(llm, fn, options) {
1629
+ const manager = new LLMSessionManager(llm);
1630
+ const session = new LLMSession(manager, options);
1631
+ try {
1632
+ return await fn(session);
1633
+ }
1634
+ finally {
1635
+ session.release();
1636
+ }
1637
+ }
1638
+ /**
1639
+ * Check if idle unload is safe (no active sessions or operations).
1640
+ * Used internally by LlamaCpp idle timer.
1641
+ */
1642
+ export function canUnloadLLM() {
1643
+ if (!defaultSessionManager)
1644
+ return true;
1645
+ return defaultSessionManager.canUnload();
1646
+ }
1647
+ // =============================================================================
1648
+ // Darwin Metal exit-crash mitigation
1649
+ // =============================================================================
1650
+ //
1651
+ // libggml-metal on macOS keeps allocated model memory wired via "residency
1652
+ // sets" with a 180-second keep_alive timer (added in ggml-org/llama.cpp#11427).
1653
+ // The process-static `std::vector<std::unique_ptr<ggml_metal_device>>`
1654
+ // destructor fires during libc `exit()` → `__cxa_finalize_ranges` and asserts
1655
+ // `[rsets->data count] == 0` — but the keep_alive hasn't expired, so the
1656
+ // assertion fails and `ggml_abort` dumps a multi-kilobyte stack trace to
1657
+ // stderr after the user-visible output. See ggml-org/llama.cpp#22593.
1658
+ //
1659
+ // No JS-side dispose call (`llama.dispose()`, `model.dispose()`, etc.) can
1660
+ // prevent it: the static destructor runs after every JS-reachable cleanup,
1661
+ // and `process.reallyExit` on Node calls libc `exit()` not `_exit()` (it
1662
+ // does NOT skip C++ static destructors — verified in
1663
+ // node/src/api/environment.cc).
1664
+ //
1665
+ // The actual fix is to disable residency sets via `GGML_METAL_NO_RESIDENCY=1`,
1666
+ // which we set from `bin/qmd` before Node loads the native binding. For QMD's
1667
+ // short-lived CLI workflow this has no measurable cost (subsequent calls
1668
+ // don't reuse the warm mapping). The functions below report whether that
1669
+ // mitigation is in effect — kept here, in the module that depends on the
1670
+ // underlying resource, so doctor can answer "is the protection active?"
1671
+ // without reaching into env handling directly.
1672
+ //
1673
+ // Setting `QMD_METAL_KEEP_RESIDENCY=1` opts back into residency sets (with
1674
+ // the visible-noise consequences). The legacy `QMD_DISABLE_DARWIN_SAFE_EXIT`
1675
+ // env var is accepted as a no-op alias for back-compat; it had no effect on
1676
+ // Node prior to this fix.
1677
+ /**
1678
+ * Whether QMD's darwin Metal exit-crash mitigation is active in this process:
1679
+ * true → residency sets disabled, process exit completes silently
1680
+ * false → either non-darwin, or `QMD_METAL_KEEP_RESIDENCY=1` overrode it,
1681
+ * in which case the libggml-metal teardown assertion may fire
1682
+ */
1683
+ export function isDarwinMetalMitigationActive() {
1684
+ if (process.platform !== "darwin")
1685
+ return false;
1686
+ if (process.env.QMD_METAL_KEEP_RESIDENCY === "1")
1687
+ return false;
1688
+ return process.env.GGML_METAL_NO_RESIDENCY === "1";
1689
+ }
1690
+ /**
1691
+ * Compatibility shim: previous releases installed a `process.on('exit')` hook
1692
+ * that tried to skip the C++ static destructor by calling `process.reallyExit`.
1693
+ * That mechanism didn't work on Node (Environment::Exit still calls libc
1694
+ * `exit()`), so it was replaced by `GGML_METAL_NO_RESIDENCY=1` from bin/qmd.
1695
+ * Kept as a no-op for code paths that still call it; safe to remove once no
1696
+ * production launcher predates the residency-set fix.
1697
+ */
1698
+ export function installDarwinExitGuard() {
1699
+ // Intentional no-op. See isDarwinMetalMitigationActive() for the real check.
1700
+ }
1701
+ /** @deprecated Replaced by isDarwinMetalMitigationActive. */
1702
+ export function isDarwinExitGuardInstalled() {
1703
+ return isDarwinMetalMitigationActive();
1704
+ }
1705
+ // =============================================================================
1706
+ // Singleton for default LlamaCpp instance
1707
+ // =============================================================================
1708
+ let defaultLlamaCpp = null;
1709
+ /**
1710
+ * Get the default LlamaCpp instance (creates one if needed). The LlamaCpp
1711
+ * constructor installs the darwin exit guard, so any code path that obtains
1712
+ * the singleton is protected.
1713
+ */
1714
+ export function getDefaultLlamaCpp() {
1715
+ if (!defaultLlamaCpp) {
1716
+ defaultLlamaCpp = new LlamaCpp();
1717
+ }
1718
+ return defaultLlamaCpp;
1719
+ }
1720
+ /**
1721
+ * Set a custom default LlamaCpp instance (useful for testing). Setting a
1722
+ * non-null instance also ensures the darwin exit guard is installed — keeps
1723
+ * the invariant intact for test doubles that didn't go through the real
1724
+ * constructor.
1725
+ */
1726
+ export function setDefaultLlamaCpp(llm) {
1727
+ if (llm !== null)
1728
+ installDarwinExitGuard();
1729
+ defaultLlamaCpp = llm;
1730
+ }
1731
+ /**
1732
+ * Peek at the default LlamaCpp instance without instantiating one. Used by
1733
+ * doctor and lifecycle diagnostics.
1734
+ */
1735
+ export function hasDefaultLlamaCpp() {
1736
+ return defaultLlamaCpp !== null;
1737
+ }
1738
+ /**
1739
+ * Dispose the default LlamaCpp instance if it exists.
1740
+ * Call this before process exit to prevent NAPI crashes.
1741
+ */
1742
+ export async function disposeDefaultLlamaCpp() {
1743
+ if (defaultLlamaCpp) {
1744
+ await defaultLlamaCpp.dispose();
1745
+ defaultLlamaCpp = null;
1746
+ }
1747
+ }