-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchatEngine.js
More file actions
4605 lines (4281 loc) · 235 KB
/
chatEngine.js
File metadata and controls
4605 lines (4281 loc) · 235 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
const EventEmitter = require('events');
const path = require('path');
const fs = require('fs');
const os = require('os');
const { pathToFileURL } = require('url');
const { parseToolCalls, repairToolCalls, stripToolCallText } = require('./tools/toolParser');
const { formatToolResultForInject, buildToolResultsUserMessage } = require('./tools/toolResultInjection');
const { canonicalizeToolParams } = require('./tools/canonicalizeToolParams');
const { visionServer } = require('./visionServer');
const { detectFamily, detectFamilyFromArch, detectParamSize } = require('./modelDetection');
const { getModelProfile } = require('./modelProfiles');
/** Base max chars of each tool result injected into chat history.
* Actual cap is computed at runtime proportional to the model's context size
* (Rule 9: no hardcoded context numbers) so it works for any model from 2K to 128K context.
*/
const BASE_TOOL_RESULT_INJECT_CHARS = 32000;
// PL2: Per-tool-type multipliers (fraction of context-based cap).
// Browser tools need more because snapshots contain both element refs and page text.
// File/web tools need less because the model can re-read or re-fetch.
const TOOL_INJECT_MULTIPLIERS = {
browser_snapshot: 1.5, browser_navigate: 1.5, browser_click: 1.5,
browser_type: 1.5, browser_screenshot: 0.5,
read_file: 0.5, fetch_webpage: 0.5, web_search: 0.25,
};
/** Emit one atomic IPC event for a complete file write (native FC / batch prose path). */
function emitCompleteFileContentBlock(onStreamEvent, filePath, content) {
if (!onStreamEvent || content == null) return;
const fp = filePath || '';
const fn = fp.split(/[\\/]/).pop() || fp;
const ext = fn.includes('.') ? fn.split('.').pop().toLowerCase() : '';
onStreamEvent('file-content-block-complete', {
filePath: fp,
fileName: fn,
language: ext,
fileKey: fp,
content: String(content),
});
}
/**
* Unescape a JSON string value fragment (no surrounding quotes).
* Used to decode filePath from accumulated FC params buffer.
*/
function _jsonUnescape(s) {
try { return JSON.parse('"' + s + '"'); } catch { return s; }
}
/**
* Stream-decode a fragment of a JSON string value (no surrounding quotes).
* Handles escape sequences that may be split across chunk boundaries.
* Returns { out, escPending, ended }:
* out — decoded content for this chunk
* escPending — true if trailing \ needs next chunk to resolve
* ended — true if unescaped " (end of JSON string) was found
*/
function _jsonStringChunkDecode(chunk, escPending) {
let out = '';
let i = 0;
if (escPending && chunk.length > 0) {
const c = chunk[0];
switch (c) {
case '"': out += '"'; break;
case '\\': out += '\\'; break;
case '/': out += '/'; break;
case 'n': out += '\n'; break;
case 'r': out += '\r'; break;
case 't': out += '\t'; break;
case 'b': out += '\b'; break;
case 'f': out += '\f'; break;
default: out += '\\' + c;
}
i = 1;
}
while (i < chunk.length) {
const c = chunk[i];
if (c === '\\') {
if (i + 1 < chunk.length) {
const nc = chunk[i + 1];
switch (nc) {
case '"': out += '"'; break;
case '\\': out += '\\'; break;
case '/': out += '/'; break;
case 'n': out += '\n'; break;
case 'r': out += '\r'; break;
case 't': out += '\t'; break;
case 'b': out += '\b'; break;
case 'f': out += '\f'; break;
default: out += '\\' + nc;
}
i += 2;
} else {
return { out, escPending: true, ended: false };
}
} else if (c === '"') {
return { out, escPending: false, ended: true };
} else {
out += c;
i++;
}
}
return { out, escPending: false, ended: false };
}
// Pre-compiled regex patterns for the streaming tool call filter.
// These are tested on line boundaries only — never on every character.
const RE_FENCE_HEADER = /^```\s*(\w*)\r?\n/;
// Tightened: only match tool-call schema, not arbitrary JSON with "tool" or "name" keys
const RE_TOOL_KEY = /"tool"\s*:\s*"[a-zA-Z0-9_]+"/; // {"tool":"write_file"} or {"tool":"vscode_askQuestions"} — requires string value
const RE_NAME_KEY = /"name"\s*:\s*"[a-zA-Z0-9_]+(?:_[a-zA-Z0-9_]+)*"/; // {"name":"read_file"} or mixed-case
const RE_PARAMS_KEY = /"(?:params|parameters|arguments)"\s*:\s*\{/; // {"params":{ — strong tool-call signal
const RE_FILE_WRITE_TOOLS = /write_file|create_file|append_to_file/;
const RE_CONTENT_START = /"content"\s*:\s*"$/;
const RE_FILE_PATH = /"(?:filePath|path)"\s*:\s*"([^"]*)"/;
const RE_TOOL_OR_SYSTEM_INJECT = /^\[(?:Tool Results|System)\]/i;
/** Reserved generation headroom — matches chat() MIN_GENERATION_TOKENS. */
const MIN_GENERATION_TOKENS_RESERVE = 512;
const RE_CONTEXT_ROTATED = /\[System: Context rotated\]/i;
/** Web-facing tools — if these share a batch with workspace navigation tools, drop the latter (structural conflict rule). */
const WEB_TOOL_BATCH = new Set(['web_search', 'fetch_webpage', 'http_request']);
const WORKSPACE_NAV_TOOLS = new Set(['list_directory', 'get_project_structure']);
function filterWebWorkspaceToolConflict(calls) {
if (!calls?.length) return calls;
const hasWeb = calls.some((c) => WEB_TOOL_BATCH.has(c.tool));
const hasWs = calls.some((c) => WORKSPACE_NAV_TOOLS.has(c.tool));
if (!hasWeb || !hasWs) return calls;
const dropped = calls.filter((c) => WORKSPACE_NAV_TOOLS.has(c.tool));
const kept = calls.filter((c) => !WORKSPACE_NAV_TOOLS.has(c.tool));
console.log(
`[ChatEngine] Same-batch conflict: dropped workspace tool(s) ${dropped.map((d) => d.tool).join(', ')} because web tool(s) are present`,
);
return kept;
}
/** Hard floor for context window (aligned with llama.cpp 256-token alignment). */
const MIN_CONTEXT_FLOOR = 2048;
/** When requireMinContextForGpu is true, prefer at least this before accepting GPU offload. */
const MIN_CONTEXT_WHEN_GPU_REQUIRED = 4096;
/** VRAM reserved for activations, CUDA context, and allocator overhead during generation. */
const VRAM_GENERATION_OVERHEAD = 512 * 1024 * 1024;
/** Safety buffer subtracted from free VRAM before KV allocation. */
const VRAM_KV_BUFFER = 256 * 1024 * 1024;
const GiB = 1024 * 1024 * 1024;
/**
* Runtime minimum usable context for auto mode — tiered by total VRAM (bytes), not GPU model.
*/
function computeAutoTargetContext({ vramTotal, vramFree, kvBytesPerToken, desiredMaxContext, trainMaxContext }) {
let tierTarget = 4096;
if (vramTotal >= 48 * GiB) tierTarget = 65536;
else if (vramTotal >= 24 * GiB) tierTarget = 32768;
else if (vramTotal >= 8 * GiB) tierTarget = 8192;
let cap = tierTarget;
if (trainMaxContext != null) cap = Math.min(cap, trainMaxContext);
cap = Math.min(cap, desiredMaxContext);
if (kvBytesPerToken > 0 && vramFree > 0) {
const kvBudget = Math.max(0, vramFree - VRAM_GENERATION_OVERHEAD - VRAM_KV_BUFFER);
const vramBounded = Math.floor(kvBudget / kvBytesPerToken / 2);
if (vramBounded > 0) cap = Math.min(cap, vramBounded);
}
return Math.max(MIN_CONTEXT_FLOOR, cap);
}
/** Descending unique context targets for step-down when VRAM is tight. */
function buildContextTargetSteps(autoTarget, minContext) {
const seen = new Set();
const targets = [];
for (const t of [autoTarget, MIN_CONTEXT_WHEN_GPU_REQUIRED, MIN_CONTEXT_FLOOR, minContext]) {
const v = Math.floor(t);
if (v > 0 && !seen.has(v)) {
seen.add(v);
targets.push(v);
}
}
return targets.sort((a, b) => b - a);
}
/**
* For one gpuLayers count: max context that fits in vramFree, or null.
* @returns {{ gpuLayers: number, maxCtx: number, contextSize: number } | null}
*/
function computeLayerVramFit({
vramFree,
modelSizeBytes,
totalLayers,
gpuLayers,
kvBytesPerToken,
desiredMaxContext,
minContext,
vramOverheadBytes,
vramBufferBytes,
gpuConstrainedContext,
weightsAlreadyLoaded = false,
}) {
if (!vramFree || vramFree <= 0 || !totalLayers || !modelSizeBytes || !kvBytesPerToken) {
return null;
}
const bytesPerLayer = modelSizeBytes / totalLayers;
const gpuRatio = totalLayers > 0 ? gpuLayers / totalLayers : 0;
const modelVram = weightsAlreadyLoaded ? 0 : gpuLayers * bytesPerLayer;
// Post-load: overhead/buffer already consumed during load — do not double-subtract.
const effectiveOverhead = weightsAlreadyLoaded ? 0 : vramOverheadBytes;
const effectiveBuffer = weightsAlreadyLoaded ? 0 : vramBufferBytes;
const availForKv = vramFree - modelVram - effectiveOverhead - effectiveBuffer;
if (availForKv <= 0) return null;
let maxCtx;
if (gpuRatio > 0) {
maxCtx = Math.floor(availForKv / (kvBytesPerToken * gpuRatio));
if (gpuConstrainedContext && gpuRatio < 0.3) {
const vramBoundedCtx = Math.floor(availForKv / kvBytesPerToken);
if (vramBoundedCtx > 0) maxCtx = Math.min(maxCtx, vramBoundedCtx);
}
} else {
maxCtx = Math.floor(availForKv / kvBytesPerToken);
}
const contextSize = Math.max(minContext, Math.min(maxCtx, desiredMaxContext));
const kvOnGpu = kvBytesPerToken * contextSize * gpuRatio;
if (modelVram + kvOnGpu + effectiveOverhead > vramFree) return null;
return { gpuLayers, maxCtx, contextSize };
}
/**
* Unified VRAM budget: pick (gpuLayers, contextSize) from runtime VRAM + GGUF metadata.
* Post-load (fixedGpuLayers): context only. Pre-load: mode from vramBalance setting.
*
* @returns {{ gpuLayers: number, contextSize: number, budgetMeta?: object }}
*/
function computeUnifiedVramBudget({
vramFree,
vramTotal = 0,
modelSizeBytes,
totalLayers,
kvBytesPerToken,
desiredMaxContext,
minContext = MIN_CONTEXT_FLOOR,
vramOverheadBytes = VRAM_GENERATION_OVERHEAD,
vramBufferBytes = VRAM_KV_BUFFER,
gpuConstrainedContext = true,
fixedGpuLayers = null,
vramBalance = 'balanced',
trainMaxContext = null,
}) {
const fallback = {
gpuLayers: fixedGpuLayers ?? 0,
contextSize: Math.max(minContext, Math.min(desiredMaxContext, minContext)),
};
if (!vramFree || vramFree <= 0 || !totalLayers || totalLayers <= 0 || !modelSizeBytes) {
return fallback;
}
if (!kvBytesPerToken || kvBytesPerToken <= 0) {
return {
gpuLayers: fixedGpuLayers ?? totalLayers,
contextSize: desiredMaxContext,
};
}
const fitParams = {
vramFree,
modelSizeBytes,
totalLayers,
kvBytesPerToken,
desiredMaxContext,
minContext,
vramOverheadBytes,
vramBufferBytes,
gpuConstrainedContext,
};
// Post-load: layers locked, weights already in VRAM — maximize context for available memory.
if (fixedGpuLayers != null) {
const fit = computeLayerVramFit({ ...fitParams, gpuLayers: fixedGpuLayers, weightsAlreadyLoaded: true });
if (fit) {
return { gpuLayers: fixedGpuLayers, contextSize: fit.contextSize };
}
// fit returned null (measured free < remaining overhead) — re-run layer search without pre-load overhead.
const postLoadRefit = computeUnifiedVramBudget({
vramFree,
vramTotal: vramTotal || vramFree,
modelSizeBytes,
totalLayers,
kvBytesPerToken,
desiredMaxContext,
minContext,
vramOverheadBytes,
vramBufferBytes,
gpuConstrainedContext,
fixedGpuLayers: null,
vramBalance,
trainMaxContext,
});
return {
gpuLayers: postLoadRefit.gpuLayers,
contextSize: postLoadRefit.contextSize,
};
}
const mode = vramBalance === 'speed' || vramBalance === 'context' ? vramBalance : 'balanced';
const autoTarget = computeAutoTargetContext({
vramTotal: vramTotal || vramFree,
vramFree,
kvBytesPerToken,
desiredMaxContext,
trainMaxContext,
});
const targetSteps = buildContextTargetSteps(autoTarget, minContext);
// Speed: v0.3.87 layer-dominant scoring (unchanged behavior for speed mode).
if (mode === 'speed') {
let bestPartial = null;
let bestCpuOnly = null;
for (let gpuLayers = totalLayers; gpuLayers >= 0; gpuLayers--) {
const fit = computeLayerVramFit({ ...fitParams, gpuLayers });
if (!fit) continue;
if (gpuLayers > 0) {
const score = gpuLayers * 1_000_000 + fit.contextSize;
if (!bestPartial || score > bestPartial.score) {
bestPartial = { ...fit, score };
}
} else {
const score = fit.contextSize;
if (!bestCpuOnly || score > bestCpuOnly.score) {
bestCpuOnly = { ...fit, score };
}
}
}
if (bestPartial) {
return {
gpuLayers: bestPartial.gpuLayers,
contextSize: bestPartial.contextSize,
budgetMeta: { mode, autoTarget, targetUsed: null },
};
}
if (bestCpuOnly) {
return {
gpuLayers: 0,
contextSize: bestCpuOnly.contextSize,
budgetMeta: { mode, autoTarget, targetUsed: null },
};
}
return { ...fallback, budgetMeta: { mode, autoTarget, targetUsed: null } };
}
// Context: maximize contextSize among fits meeting target; tie-break higher gpuLayers.
if (mode === 'context') {
for (const target of targetSteps) {
let best = null;
for (let gpuLayers = 1; gpuLayers <= totalLayers; gpuLayers++) {
const fit = computeLayerVramFit({ ...fitParams, gpuLayers });
if (!fit || fit.maxCtx < target) continue;
if (!best || fit.contextSize > best.contextSize
|| (fit.contextSize === best.contextSize && fit.gpuLayers > best.gpuLayers)) {
best = { ...fit, targetUsed: target };
}
}
if (best) {
return {
gpuLayers: best.gpuLayers,
contextSize: best.contextSize,
budgetMeta: { mode, autoTarget, targetUsed: best.targetUsed },
};
}
}
const cpuFit = computeLayerVramFit({ ...fitParams, gpuLayers: 0 });
if (cpuFit) {
return {
gpuLayers: 0,
contextSize: cpuFit.contextSize,
budgetMeta: { mode, autoTarget, targetUsed: MIN_CONTEXT_FLOOR, cpuFallback: true },
};
}
return { ...fallback, budgetMeta: { mode, autoTarget, targetUsed: null } };
}
// Balanced (default): highest gpuLayers where maxCtx >= target; step down target if needed.
for (const target of targetSteps) {
for (let gpuLayers = totalLayers; gpuLayers >= 1; gpuLayers--) {
const fit = computeLayerVramFit({ ...fitParams, gpuLayers });
if (!fit || fit.maxCtx < target) continue;
const contextSize = Math.max(minContext, Math.min(fit.maxCtx, desiredMaxContext));
return {
gpuLayers,
contextSize,
budgetMeta: {
mode,
autoTarget,
targetUsed: target,
targetSteppedDown: target < autoTarget,
},
};
}
}
const cpuFit = computeLayerVramFit({ ...fitParams, gpuLayers: 0 });
if (cpuFit) {
return {
gpuLayers: 0,
contextSize: cpuFit.contextSize,
budgetMeta: { mode, autoTarget, targetUsed: null, cpuFallback: true },
};
}
return { ...fallback, budgetMeta: { mode, autoTarget, targetUsed: null } };
}
/** Approximate chars per token for English tool prompts. */
const TOOL_PROMPT_CHARS_PER_TOKEN = 3.5;
/**
* Size tool catalog to remaining prompt budget (Bug 5).
* Appends compact category parts until budget exhausted; falls back to full if it fits.
*/
function buildBudgetProportionalToolPrompt({
contextTokens,
basePromptChars,
historyChars = 0,
userMessageChars = 0,
toolPrompt = '',
compactToolParts = null,
compactToolPrompt = '',
minGenerationReserve = 512,
maxToolBudgetPct = 0.35,
maxToolBudgetTokens = 4096,
}) {
const consumedTokens = Math.ceil((basePromptChars + historyChars + userMessageChars) / TOOL_PROMPT_CHARS_PER_TOKEN);
const promptBudgetTokens = Math.max(256, contextTokens - minGenerationReserve - consumedTokens);
const maxToolTokens = Math.min(
Math.floor(promptBudgetTokens * maxToolBudgetPct),
maxToolBudgetTokens,
);
const maxToolChars = Math.floor(maxToolTokens * TOOL_PROMPT_CHARS_PER_TOKEN);
const fullToolTokens = Math.ceil((toolPrompt?.length || 0) / TOOL_PROMPT_CHARS_PER_TOKEN);
if (toolPrompt && fullToolTokens <= maxToolTokens) {
return { prompt: toolPrompt, mode: 'full', budgetTokens: maxToolTokens, usedTokens: fullToolTokens };
}
const parts = Array.isArray(compactToolParts) && compactToolParts.length > 0
? compactToolParts
: (compactToolPrompt ? [compactToolPrompt] : []);
if (parts.length === 0) {
const trimmed = toolPrompt && toolPrompt.length > maxToolChars
? toolPrompt.slice(0, maxToolChars) + '\n…and more tools available\n'
: (toolPrompt || '');
return { prompt: trimmed, mode: 'trimmed-full', budgetTokens: maxToolTokens, usedTokens: Math.ceil(trimmed.length / TOOL_PROMPT_CHARS_PER_TOKEN) };
}
let built = '';
let partsUsed = 0;
const headerPart = parts[0] || '';
for (const part of parts) {
const next = built + part;
if (next.length > maxToolChars && built.length > 0) break;
built = next;
partsUsed++;
}
if (!built && headerPart) {
built = headerPart.length > maxToolChars ? headerPart.slice(0, maxToolChars) : headerPart;
partsUsed = 1;
} else if (headerPart && !built.startsWith(headerPart)) {
// Always preserve format header even when budget is tight
const body = built.slice(headerPart.length);
const maxBody = Math.max(0, maxToolChars - headerPart.length);
built = headerPart + (maxBody > 0 ? body.slice(0, maxBody) : '');
partsUsed = Math.max(partsUsed, 1);
}
if (partsUsed < parts.length) {
built += '\n…and more tools available\n';
}
return {
prompt: built,
mode: 'budget-parts',
budgetTokens: maxToolTokens,
partsUsed,
usedTokens: Math.ceil(built.length / TOOL_PROMPT_CHARS_PER_TOKEN),
};
}
/**
* Normalize settings / IPC payload for model load. Matches settingsManager defaults when fields are missing.
* @param {object} raw
* @returns {{ gpuPreference: 'auto'|'cpu', gpuLayers: number, contextSize: number, requireMinContextForGpu: boolean }}
*/
/**
* Absolute floor for the computed hardware context cap when GGUF metadata is
* missing (so we cannot compute a KV-derived cap). Equal to the llama.cpp-aligned
* minimum — used only as a last resort; the normal path computes from architecture.
*/
const CONTEXT_MAX_FALLBACK_NO_GGUF_FLOOR = 2048;
/**
* Estimate KV-cache bytes per token from GGUF architecture metadata.
* Transformer-standard, architecture-agnostic:
* KV per token = n_layer * n_head_kv * (key_length + value_length) * bytes_per_element
* Assumes fp16 KV cache (2 bytes/element), the llama.cpp default.
*
* GGUF metadata shape (llama.cpp convention):
* architectureMetadata.block_count → n_layer
* architectureMetadata.attention.head_count_kv → n_head_kv
* architectureMetadata.attention.head_count → n_head (fallback)
* architectureMetadata.attention.key_length → head_dim_k
* architectureMetadata.attention.value_length → head_dim_v
* architectureMetadata.embedding_length → embedding dim (fallback)
*/
function estimateKvBytesPerToken(am, kvCacheType) {
if (!am) return null;
const nLayer = am.block_count;
if (!nLayer) return null;
const att = am.attention || {};
const nHeadKv = att.head_count_kv || att.head_count;
if (!nHeadKv) return null;
let keyLen = att.key_length;
let valLen = att.value_length;
// Fallback: derive head_dim from embedding_length / head_count if per-head lengths missing
if ((!keyLen || !valLen) && am.embedding_length && att.head_count) {
const headDim = am.embedding_length / att.head_count;
if (Number.isFinite(headDim) && headDim > 0) {
if (!keyLen) keyLen = headDim;
if (!valLen) valLen = headDim;
}
}
if (!keyLen || !valLen) return null;
// Bytes per element depends on KV cache quantization type:
// f16 = 2 bytes/element (no compression)
// q8_0 = 1 byte/element (2x compression)
// q4_0 = 0.5 bytes/element (4x compression)
const bytesPerElement = kvCacheType === 'q3_0' ? 0.375
: kvCacheType === 'q4_0' ? 0.5
: kvCacheType === 'q4_1' ? 0.5625
: kvCacheType === 'q5_0' ? 0.625
: kvCacheType === 'q5_1' ? 0.6875
: kvCacheType === 'q8_0' ? 1
: 2; // f16 or default
return nLayer * nHeadKv * (keyLen + valLen) * bytesPerElement;
}
function buildEngineLoadSettings(raw = {}) {
const gpuPreference = raw.gpuPreference === 'cpu' ? 'cpu' : 'auto';
const gpuLayers = typeof raw.gpuLayers === 'number' ? raw.gpuLayers : -1;
const ctx = Number(raw.contextSize);
// 0 = auto — use model train cap (and VRAM) as upper bound, not a fixed 16k default
const contextSize = !Number.isFinite(ctx) || ctx < 0 ? 0 : Math.floor(ctx);
return {
gpuPreference,
gpuLayers,
contextSize,
requireMinContextForGpu: !!raw.requireMinContextForGpu,
gpuConstrainedContext: raw.gpuConstrainedContext !== false, // default true
vramBalance: raw.vramBalance === 'speed' || raw.vramBalance === 'context' ? raw.vramBalance : 'balanced',
kvCacheType: raw.kvCacheType || 'q8_0',
enableThinking: raw.enableThinking !== false, // default true
// 'C' = ThinkingOpenJinja (prefix injection), 'B' = raw Jinja (no prefix), 'auto' = node-llama-cpp auto, 'off' = Jinja enable_thinking=false
thinkingMode: raw.thinkingMode || 'C',
};
}
/**
* Mode C (independent harness): open the thought segment at generation start via
* noPrefixTrigger. Used only for custom Jinja + enable_thinking wrappers — not for
* chatWrapper=auto (QwenChatWrapper, Phi instruct, etc.).
*/
function createThinkingOpenJinjaWrapper(JinjaTemplateChatWrapper, LlamaText) {
return class ThinkingOpenJinjaChatWrapper extends JinjaTemplateChatWrapper {
generateContextState({ chatHistory, availableFunctions, documentFunctionParams }) {
const state = super.generateContextState({ chatHistory, availableFunctions, documentFunctionParams });
if (this.additionalRenderParameters?.enable_thinking !== true) return state;
const thoughtSeg = this.settings?.segments?.thought;
if (thoughtSeg?.prefix == null) return state;
return {
...state,
noPrefixTrigger: {
type: 'segment',
segmentType: 'thought',
inject: LlamaText(thoughtSeg.prefix),
},
};
}
};
}
// Agent identity prompt — behavior and grounding only; tool format/catalog live in getToolPrompt()
const SYSTEM_PROMPT = `You are guIDE, an AI assistant embedded in a general-purpose IDE. You help users with software projects: reading and writing code, running commands, searching the web, using the browser, and answering questions.
## How to respond
- If the user's message is conversational (greetings, thanks, clarifying questions, opinions) and needs no action, reply in plain prose only. Do not call tools.
- If the user asks you to do something you cannot do with text alone — create or change files, run commands, search the project or web, use the browser, inspect git state, etc. — use the appropriate tool from the ## Tools section below.
- You have real tools. When action is required, use them. Do not say you cannot access files, the terminal, or the network when a tool can perform the task.
## Tools (required reading)
Tool definitions, call format, parameter schemas, and examples are in the ## Tools section appended below this message. Follow that section exactly for tool names, parameter names, and JSON format. Do not invent tool names or parameter names.
After calling a tool, wait for the result before continuing. Never output fabricated tool results or blocks labeled [Tool Results] or [System: Tool Results] — the system injects real results.
## Grounding
- Base answers on tool results, file contents, and user-provided context — not assumptions.
- If you need information only the user can provide, ask in prose or use ask_question when offered in ## Tools.
- If a tool fails, read the error, adjust, and retry once with corrected parameters; then explain or ask the user.
## Images
When you receive an image description from the vision system, treat it as what you observed. Do not use read_file on image files to "see" them.
## Planning
For multi-step work, you may use planning tools from ## Tools when they fit the task. For simple requests, act directly without unnecessary planning overhead.
## Context rotation
When you see [System: Context rotated], older turns were removed from the live context window. The progress summary embedded in the rotation notice contains the key details you need to continue. Do not call read_file to recover context — the summary is already in your context.
## Cloud response style (cloud models only)
When this block is present you are guIDE Cloud AI: keep answers concise — short paragraphs, minimal preamble, no filler. Still use tools whenever the task requires real actions in the project.
## Only call a tool when required. Never call a tool when plain prose is sufficient.
Examples of when to call tools:
Pattern — user wants to create or write a file:
Call write_file with the target path and the full file content. Do not output the content as a markdown code block.
Pattern — user asks to edit or modify an existing file:
Call read_file to get the current content, then call edit_file or write_file with the updated version.
Pattern — user asks to run a command, script, or terminal operation:
Call run_terminal_command with the command string. Do not describe what the command would do — run it.
Pattern — user asks to search the web, find current information, or look up something online:
Call web_search with a rephrased query. Do not generate an answer from memory if the information may be outdated.
Pattern — user asks to open, navigate, or interact with a website or browser:
Call browser_navigate first, then use browser_click, browser_type, etc. as needed.
Pattern — user wants to find files in the project, list a directory, or search codebase:
Call list_directory, search_codebase, or find_files as appropriate. Do not guess at file contents.
Pattern — user asks a conversational question or makes a greeting:
Reply in prose only. Do not call any tool.`;
class ChatEngine extends EventEmitter {
constructor() {
super();
console.log('[ChatEngine] constructor START');
this.isReady = false;
this.isLoading = false;
/** @type {'idle'|'loading'|'ready'|'disposing'} */
this._loadState = 'idle';
this._loadPromise = null;
this.modelInfo = null;
this.currentModelPath = null;
this.gpuPreference = 'auto';
this._projectPath = null;
this._llama = null;
this._model = null;
this._context = null;
this._sequence = null;
this._chat = null;
this._baseCtxOpts = null; // saved from loadModel() for summarizer VRAM reclaim
this._chatHistory = [];
this._lastEvaluation = null;
this._abortController = null;
this._pendingUserMessage = null; // injected by user interrupt during tool loop
this._templateSupportsThinking = false;
this._thinkingCapable = false;
this._recentlyWrittenFiles = new Map(); // filePath → content written in current chat() call
this._sessionId = 0; // increments on resetSession to detect stale tool results
console.log('[ChatEngine] constructor DONE');
}
async waitForReady() {
if (this._loadPromise) {
try { await this._loadPromise; } catch (_) { /* load failed */ }
}
return this.isReady && this._loadState === 'ready';
}
/**
* @param {string} modelPath
* @param {object} [rawLoadSettings] — from settingsManager.get() (gpuPreference, gpuLayers, contextSize, requireMinContextForGpu)
*/
async initialize(modelPath, rawLoadSettings) {
// If a load is already in progress, wait for it to finish, then proceed with this new request.
// This prevents "Already loading a model" errors when the user switches models quickly.
if (this._loadPromise) {
console.log('[ChatEngine] Model load already in progress — queuing new request');
try { await this._loadPromise; } catch (_) { /* previous load failed — proceed */ }
}
// Build a new promise for this load so subsequent requests can await it
this._loadPromise = this._doInitialize(modelPath, rawLoadSettings);
try {
return await this._loadPromise;
} finally {
this._loadPromise = null;
}
}
async _doInitialize(modelPath, rawLoadSettings) {
this._loadState = 'loading';
this.isLoading = true;
this.isReady = false;
this.emit('status', { state: 'loading', message: 'Loading model...' });
try {
const llamaCppPath = this._getNodeLlamaCppPath();
const { getLlama, LlamaChat, readGgufFileInfo, JinjaTemplateChatWrapper, LlamaText } = await import(pathToFileURL(llamaCppPath).href);
const ThinkingOpenJinjaChatWrapper = createThinkingOpenJinjaWrapper(JinjaTemplateChatWrapper, LlamaText);
// Save class refs so setWrapperMode can recreate wrappers without a model reload
this._LlamaChat = LlamaChat;
this._JinjaTemplateChatWrapper = JinjaTemplateChatWrapper;
this._ThinkingOpenJinjaChatWrapper = ThinkingOpenJinjaChatWrapper;
const s = buildEngineLoadSettings(rawLoadSettings || {});
this.gpuPreference = s.gpuPreference;
if (this._model) {
this._loadState = 'disposing';
await this._dispose();
this._loadState = 'loading';
}
let trainMaxContext = null;
let totalLayersFromGguf = null;
let ggufArchMeta = null;
let ggufArchString = null; // metadata.general.architecture (e.g. "chatglm", "qwen35", "gemma3")
let ggufChatTemplate = null; // tokenizer.chat_template — Jinja template string from GGUF metadata
try {
const gguf = await readGgufFileInfo(modelPath, { readTensorInfo: false, logWarnings: false });
const am = gguf.architectureMetadata;
ggufArchMeta = am || null;
if (gguf.metadata?.general?.architecture) ggufArchString = gguf.metadata.general.architecture;
if (am && typeof am.context_length === 'number') trainMaxContext = am.context_length;
if (am && typeof am.block_count === 'number') totalLayersFromGguf = am.block_count;
// Tier 1: Extract chat template from GGUF metadata for auto-detection.
// tokenizer.chat_template is a Jinja2 string embedded in the GGUF file.
// It's the authoritative source for what the model's chat format supports.
// Models with thinking capability include `enable_thinking` as a Jinja variable.
if (gguf.metadata?.tokenizer?.chat_template) {
ggufChatTemplate = gguf.metadata.tokenizer.chat_template;
}
} catch (e) {
console.warn(`[ChatEngine] readGgufFileInfo: ${e.message}`);
}
// Initialize llama runtime early so we can query VRAM state before context sizing.
const gpuOpt = s.gpuPreference === 'cpu' ? false : 'auto';
this._llama = await this._createLlamaRuntime(getLlama, gpuOpt);
const modelStats = fs.statSync(modelPath);
// ─── Hardware-aware context ceiling computation ───
// Compute the maximum context window that the user's hardware can realistically support,
// derived from GGUF architecture + available memory. No hardcoded ceilings.
const kvBytesPerToken = estimateKvBytesPerToken(ggufArchMeta, s.kvCacheType);
let hardwareCap = null;
let kvSourceMem = 'none';
let vramTotal = 0;
let vramFree = 0;
// Diagnostic: log raw GGUF architecture metadata for KV estimate verification
if (ggufArchMeta) {
const att = ggufArchMeta.attention || {};
console.log(`[ChatEngine] GGUF arch metadata: block_count=${ggufArchMeta.block_count}, head_count_kv=${att.head_count_kv}, head_count=${att.head_count}, key_length=${att.key_length}, value_length=${att.value_length}, embedding_length=${ggufArchMeta.embedding_length}, kvCacheType=${s.kvCacheType}, kvBytesPerToken=${kvBytesPerToken}`);
}
if (kvBytesPerToken) {
// Compute hwCap from both VRAM and RAM, pick whichever gives larger context.
// Previously we preferred VRAM whenever possible, but for small models that
// nearly fill VRAM, this gave tiny contexts (e.g. 12K) when RAM would give 32K+.
let vramHwCap = null;
let ramHwCap = null;
if (s.gpuPreference !== 'cpu') {
try {
const vramState = await this._llama.getVramState();
vramTotal = vramState?.total || 0;
vramFree = vramState?.free || 0;
} catch (e) { console.warn('[ChatEngine] VRAM state query failed:', e.message); }
}
// VRAM path: free VRAM minus model weights, half reserved for KV
if (vramFree > modelStats.size) {
const vramAvail = vramFree - modelStats.size;
const vramKvBudget = vramAvail / 2;
vramHwCap = Math.max(MIN_CONTEXT_FLOOR, Math.floor(vramKvBudget / kvBytesPerToken));
}
// RAM path. useMmap=true (line 445) means model weights are
// memory-mapped and shared with the OS page cache, NOT consuming
// anonymous RAM upfront. Deriving from os.freemem() and subtracting
// modelStats.size double-counts on every OS with mmap and collapses
// to MIN_CONTEXT_FLOOR when free memory is tight at load time.
// Use os.totalmem() (deterministic upper bound, independent of
// transient memory state) minus the model file size minus a fixed
// runtime overhead for activations, the JS/Electron heap, sub-agent
// context, and OS slack. A precise computation would need gpuLayers,
// which is computed AFTER hardwareCap (chicken-and-egg) — fixed
// constant is the right tradeoff here.
const RAM_RUNTIME_OVERHEAD = 1.5 * 1024 * 1024 * 1024;
const ramAvail = Math.max(0, os.totalmem() - modelStats.size - RAM_RUNTIME_OVERHEAD);
const ramKvBudget = ramAvail / 2;
ramHwCap = Math.max(MIN_CONTEXT_FLOOR, Math.floor(ramKvBudget / kvBytesPerToken));
// Pick whichever source gives the larger context
if (vramHwCap != null && vramHwCap >= ramHwCap) {
hardwareCap = vramHwCap;
kvSourceMem = 'vram';
} else {
hardwareCap = ramHwCap;
kvSourceMem = 'ram';
}
console.log(`[ChatEngine] Memory diagnostic: vramTotal=${(vramTotal/1e9).toFixed(2)}GB, vramFree=${(vramFree/1e9).toFixed(2)}GB, freeRam=${(os.freemem()/1e9).toFixed(2)}GB, modelSize=${(modelStats.size/1e9).toFixed(2)}GB, vramHwCap=${vramHwCap}, ramHwCap=${ramHwCap}, source=${kvSourceMem}, hwCap=${hardwareCap}`);
}
const testMaxCtx = parseInt(process.env.TEST_MAX_CONTEXT, 10) || 0;
let desiredMax;
if (testMaxCtx > 0) {
desiredMax = testMaxCtx;
} else if (s.contextSize <= 0) {
// P4: Auto sizing uses only hardware cap and train cap (no hardcoded ceiling).
// Per RULES.md Rule 9: never hardcode context numbers — compute from actual resources.
// The hardware cap already accounts for VRAM/RAM headroom, so it self-limits to safe sizes.
if (hardwareCap != null && trainMaxContext != null) {
desiredMax = Math.min(hardwareCap, trainMaxContext);
} else if (hardwareCap != null) {
desiredMax = hardwareCap;
} else if (trainMaxContext != null) {
desiredMax = trainMaxContext;
} else {
desiredMax = CONTEXT_MAX_FALLBACK_NO_GGUF_FLOOR;
}
} else {
desiredMax = s.contextSize;
if (trainMaxContext != null) desiredMax = Math.min(desiredMax, trainMaxContext);
desiredMax = Math.max(MIN_CONTEXT_FLOOR, desiredMax);
}
const minBase = s.requireMinContextForGpu ? MIN_CONTEXT_WHEN_GPU_REQUIRED : MIN_CONTEXT_FLOOR;
let contextMin = Math.min(minBase, desiredMax);
// When model weights exceed VRAM, RAM hwCap can inflate desiredMax to 100K+ and the
// unified budget picks gpuLayers=0 with a mega KV cache. Cap desiredMax from VRAM so
// partial GPU offload remains viable on 4GB GPUs.
if (s.gpuPreference !== 'cpu' && kvBytesPerToken > 0 && modelStats.size > vramFree * 0.85) {
const vramKvBudget = vramFree - VRAM_GENERATION_OVERHEAD - VRAM_KV_BUFFER;
const vramCtxCap = Math.max(MIN_CONTEXT_FLOOR, Math.floor(vramKvBudget / kvBytesPerToken));
if (desiredMax > vramCtxCap) {
console.log(`[ChatEngine] Model (${(modelStats.size / 1e9).toFixed(2)}GB) exceeds VRAM (${(vramFree / 1e9).toFixed(2)}GB free) — capping desiredMax ${desiredMax} → ${vramCtxCap} to preserve GPU layer budget`);
desiredMax = vramCtxCap;
contextMin = Math.min(minBase, desiredMax);
}
}
console.log(
`[ChatEngine] Context sizing: train=${trainMaxContext}, hwCap=${hardwareCap} (source=${kvSourceMem}, kvBytesPerToken=${kvBytesPerToken}), user=${s.contextSize <= 0 ? 'auto' : s.contextSize}, test=${testMaxCtx || 'none'} → desiredMax=${desiredMax}`,
);
// Pre-flight validation: catch undefined variables before they cause runtime errors
const _preflightVars = { kvBytesPerToken, hardwareCap, kvSourceMem, vramTotal, vramFree, trainMaxContext, totalLayersFromGguf, ggufArchMeta, desiredMax, contextMin, modelStats };
for (const [name, val] of Object.entries(_preflightVars)) {
if (val === undefined) {
throw new Error(`Internal error: ${name} is undefined at loadModel. This is a bug — please report.`);
}
}
const loadModelOpts = {
modelPath,
defaultContextFlashAttention: s.gpuPreference !== 'cpu',
ignoreMemorySafetyChecks: true,
useMmap: true,
// Lock model pages in RAM to prevent OS from swapping them to disk (causes stalls)
useMlock: os.totalmem() > modelStats.size * 2,
onLoadProgress: (p) => {
this.emit('status', { state: 'loading', message: `Loading model... ${Math.round(p * 100)}%`, progress: p });
},
};
// KV cache quantization: resolve BEFORE loadModel so we can adjust fitContext.
// Default 'f16' matches llama.cpp upstream and enables the fastest fused flash-attention
// kernel path on consumer NVIDIA GPUs (this is what LM Studio / llama-server use). Lower
// precision options (q8_0, q4_0, q4_1, q5_0, q5_1, q3_0) are user-selectable for trading
// VRAM headroom against generation speed. 'currentQuant' lets node-llama-cpp match the
// model's weight quantization (legacy behaviour, retained for explicit selection).
const ALLOWED_KV_TYPES = new Set(['currentQuant', 'q3_0', 'q4_0', 'q4_1', 'q5_0', 'q5_1', 'q8_0', 'f16']);
const rawKvType = rawLoadSettings.kvCacheType || 'q8_0';
const kvCacheType = ALLOWED_KV_TYPES.has(rawKvType) ? rawKvType : undefined;
if (s.gpuPreference === 'cpu') {
loadModelOpts.gpuLayers = 0;
} else if (s.gpuLayers >= 0) {
loadModelOpts.gpuLayers = s.gpuLayers;
} else {
// Unified VRAM budget: pick gpuLayers + estimated context in one pass (Bug 4).
const totalLayers = totalLayersFromGguf || 32;
const budget = computeUnifiedVramBudget({
vramFree,
vramTotal,
modelSizeBytes: modelStats.size,
totalLayers,
kvBytesPerToken: kvBytesPerToken || 0,
desiredMaxContext: desiredMax,
minContext: contextMin,
gpuConstrainedContext: s.gpuConstrainedContext !== false,
vramBalance: s.vramBalance,
trainMaxContext: trainMaxContext ?? null,
});
const kvOnGpuFinal = (kvBytesPerToken || 0) * budget.contextSize * (budget.gpuLayers / totalLayers);
const meta = budget.budgetMeta;
const metaStr = meta
? `, mode=${meta.mode}, autoTarget=${meta.autoTarget}${meta.targetUsed != null ? `, targetUsed=${meta.targetUsed}` : ''}${meta.targetSteppedDown ? ', targetSteppedDown=true' : ''}${meta.cpuFallback ? ', cpuFallback=true' : ''}`
: '';
console.log(`[ChatEngine] Unified VRAM budget: vramFree=${(vramFree / 1e9).toFixed(2)}GB, vramTotal=${(vramTotal / 1e9).toFixed(2)}GB, gpuLayers=${budget.gpuLayers}/${totalLayers}, estCtx=${budget.contextSize}, kvOnGpu=${(kvOnGpuFinal / 1e6).toFixed(1)}MB, overhead=${(VRAM_GENERATION_OVERHEAD / 1e9).toFixed(2)}GB${metaStr}`);
loadModelOpts.gpuLayers = budget.gpuLayers;
this._preLoadContextEstimate = budget.contextSize;
}
this._model = await this._llama.loadModel(loadModelOpts);
// P1: Use node-llama-cpp's cpuMathCores (probed by llama.cpp from actual CPU topology)
// instead of os.cpus().length / 2 which was wrong on:
// - AMD Ryzen without SMT (formula halved usable cores)
// - Apple Silicon (no hyperthreading — formula halved usable cores)
// - Intel with E-cores (formula misclassified E-cores)
// Falls back to os.cpus().length if cpuMathCores is missing or zero.
const cpuMathCores = (typeof this._llama.cpuMathCores === 'number' && this._llama.cpuMathCores > 0)
? this._llama.cpuMathCores
: os.cpus().length;
const threadCount = Math.max(1, cpuMathCores);
// P2: Adaptive batchSize from actual VRAM headroom after model load.
// Larger batchSize = faster prompt processing (prefill). Output tok/s unchanged.
// Measured free VRAM determines safe upper bound. CPU stays conservative.
let vramFreeAfterModel = vramFree;
if (s.gpuPreference !== 'cpu') {
try {
const vs = await this._llama.getVramState();
vramFreeAfterModel = vs?.free || vramFree;
} catch (e) { console.warn('[ChatEngine] VRAM query (batchSize) failed:', e.message); }
}
let batchSize;
if (s.gpuPreference === 'cpu') batchSize = 512;
else if (vramFreeAfterModel < 2 * 1024 * 1024 * 1024) batchSize = 1024;
else if (vramFreeAfterModel < 4 * 1024 * 1024 * 1024) batchSize = 2048;
else batchSize = 4096;
console.log(`[ChatEngine] Perf: cpuMathCores=${cpuMathCores} (threads=${threadCount}), vramFreeAfterModel=${(vramFreeAfterModel/1e9).toFixed(2)}GB, batchSize=${batchSize}`);
// P5: SWA models (Gemma, Mistral with sliding window) — set swaFullCache to enable
// prefix reuse on multi-turn chats. Without this, multi-turn re-evaluates entire history.
const swaSize = this._model?.fileInsights?.swaSize || 0;
const swaFullCache = swaSize > 0;
if (swaFullCache) console.log(`[ChatEngine] P5: SWA detected (swaSize=${swaSize}) — swaFullCache enabled for prefix reuse`);
// Compute exact context size after model loading.
// node-llama-cpp's createContext with { min, max } uses f16 for KV estimation,
// which inflates 4x when using q4_0, causing all retries to fail and collapse
// to the minimum (2048). We bypass this by computing the exact size ourselves
// using actual post-load VRAM measurements and q4_0-aware KV estimates,
// then passing a single number to createContext.
const actualGpuLayers = this._model.gpuLayers || 0;
const totalLayersForCtx = totalLayersFromGguf || 32;
const gpuLayerRatio = totalLayersForCtx > 0 ? actualGpuLayers / totalLayersForCtx : 0;
let computedCtxSize = desiredMax;
if (kvBytesPerToken > 0 && s.gpuPreference !== 'cpu') {
// Post-load: refine context using measured VRAM and locked gpuLayers (same unified budget).
const postBudget = computeUnifiedVramBudget({
vramFree: vramFreeAfterModel,
vramTotal,
modelSizeBytes: modelStats.size,
totalLayers: totalLayersForCtx,
kvBytesPerToken,
desiredMaxContext: desiredMax,
minContext: contextMin,
gpuConstrainedContext: s.gpuConstrainedContext !== false,
fixedGpuLayers: actualGpuLayers,
trainMaxContext: trainMaxContext ?? null,
});
computedCtxSize = postBudget.contextSize;
console.log(`[ChatEngine] Post-load unified context: vramFreeAfterModel=${(vramFreeAfterModel/1e9).toFixed(2)}GB, kvBpt=${kvBytesPerToken}, gpuRatio=${gpuLayerRatio.toFixed(2)}, computedCtxSize=${computedCtxSize}${this._preLoadContextEstimate != null ? `, preLoadEst=${this._preLoadContextEstimate}` : ''}`);
this._preLoadContextEstimate = null;
}
// Build createContext options. Only attach experimentalKvCacheKeyType / ValueType when
// the user has selected a non-f16 KV type. Passing 'f16' explicitly is supported by
// node-llama-cpp but bypasses the upstream-default code path; omitting the override lets
// llama.cpp pick the fastest fused flash-attention kernel for the model + GPU combination.
const baseCtxOpts = {
contextSize: computedCtxSize,
flashAttention: s.gpuPreference !== 'cpu',
ignoreMemorySafetyChecks: true,
batchSize,
threads: { ideal: threadCount, min: Math.max(1, threadCount - 1) },
swaFullCache,
};
if (kvCacheType && kvCacheType !== 'f16' && kvCacheType !== 'q8_0') {
baseCtxOpts.experimentalKvCacheKeyType = kvCacheType;
baseCtxOpts.experimentalKvCacheValueType = kvCacheType;
}