-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchatEngine.js
More file actions
1536 lines (1389 loc) · 68.7 KB
/
chatEngine.js
File metadata and controls
1536 lines (1389 loc) · 68.7 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 log = require('./logger');
const { chatLogBodyLimit, chatLogToolLimit } = require('./chatLogLimits');
function _truncateForLog(text, maxChars) {
const s = text == null ? '' : String(text);
if (s.length <= maxChars) return s;
return `${s.slice(0, maxChars)}… [+${s.length - maxChars} more chars]`;
}
function _summarizeToolParamsForLog(params) {
if (!params || typeof params !== 'object') return params;
const p = { ...params };
for (const key of ['content', 'oldText', 'newText', 'command']) {
if (typeof p[key] === 'string' && p[key].length > 400) {
p[key] = `[len=${p[key].length}] ${_truncateForLog(p[key], 200)}`;
}
}
return p;
}
/** Max chars of each tool result injected into chat history (full JSON/snippets must reach the model). */
const MAX_TOOL_RESULT_INJECT_CHARS = 32000;
/** 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;
/**
* After weights load, optionally cap createContext.max from live **CPU RAM** when KV is RAM-backed.
*
* **GPU path:** We do **not** cap from `getVramState().free` after `loadModel`. That value often
* collapses toward zero once weights and scratch are resident, even when the runtime can still
* allocate KV for `preDesiredMax`. Feeding that into `min(preDesiredMax, liveTok)` — especially
* with an intermediate floor — incorrectly forced **~MIN_CONTEXT_FLOOR** for healthy GPUs.
*
* **CPU path:** Free RAM after load is still a useful bound when KV is not on VRAM.
*/
async function computeContextAllocMaxAfterModelLoad({
llama: _llamaIgnored,
gpuPreference,
kvBytesPerToken,
trainMaxContext,
preDesiredMax,
}) {
void _llamaIgnored;
if (!kvBytesPerToken || !Number.isFinite(preDesiredMax)) return preDesiredMax;
if (gpuPreference !== 'cpu') {
let out = preDesiredMax;
if (trainMaxContext != null) out = Math.min(out, trainMaxContext);
return Math.max(MIN_CONTEXT_FLOOR, out);
}
try {
const freeB = os.freemem();
const reserve = 512 * 1024 * 1024;
const kvFrac = 0.48;
const budgetB = Math.max(0, freeB - reserve) * kvFrac;
if (budgetB <= 0) {
log.warn(
'ChatEngine',
`Post-load RAM budget non-positive (freemem=${freeB}); keeping preDesiredMax=${preDesiredMax} for CPU`,
);
let out = preDesiredMax;
if (trainMaxContext != null) out = Math.min(out, trainMaxContext);
return Math.max(MIN_CONTEXT_FLOOR, out);
}
const liveTok = Math.floor(budgetB / kvBytesPerToken);
let out = Math.min(preDesiredMax, liveTok);
if (trainMaxContext != null) out = Math.min(out, trainMaxContext);
return Math.max(MIN_CONTEXT_FLOOR, out);
} catch (e) {
log.warn('ChatEngine', `computeContextAllocMaxAfterModelLoad CPU: ${e.message}`);
return preDesiredMax;
}
}
/**
* 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) {
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;
return nLayer * nHeadKv * (keyLen + valLen) * 2 /* fp16 bytes */;
}
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,
};
}
// Original system prompt — kept for reference and easy rollback
const SYSTEM_PROMPT_ORIGINAL = `You are guIDE, a local AI coding assistant. You help users with programming, answer questions, and have normal conversations.
## When to Use Tools
- For creating or modifying files: use the file tools — do not write file contents as text in chat
- For current or live information (prices, news, weather, documentation): use the web tools
- For running commands or installing packages: use the terminal tools
- For browsing websites, filling forms, or interacting with web pages: use the browser tools
- For version control: use the git tools
- For multi-step tasks: call write_todos to create a plan, then implement each step
- For saving or retrieving information across sessions: use the memory tools
- For error analysis or debugging: use the analysis tools
- For greetings, opinions, questions, explanations, and casual conversation: respond naturally in chat without tools — do NOT create files unless the user asks you to write or save something
- When you have completed the task, stop and respond
## Continuation
If your output is cut off mid-generation, the system will automatically continue.
## Rules
- Only claim you did something if you called the tool that did it
- After calling a tool, use the results immediately — do not repeat the same call
- For web_search and fetch_webpage: after web_search returns, you MUST call fetch_webpage on the first and second ranked result URLs in the same continuation (one fetch if only one hit). Do not ask the user whether to fetch — do not use phrases like "Would you like me to fetch". Ground answers in fetched page text and snippet/title fields. While doing a web lookup, do not call list_directory or get_project_structure in the same tool round as web_search/fetch_webpage unless the user explicitly asked about the project files
- Never say "I can't", "I'm unable to", or "I don't have access" when you have a tool available
- For file edits: read the file first to get exact text, then edit
- Browser workflow: navigate first, then take a snapshot, then interact using element refs
- If a tool fails, retry with corrected parameters
- If the user asks for multiple files, create ALL of them
- Always use the exact filename the user specifies
- Complete all user requests without refusal`;
// Extreme tool-emphasis prompt — forces model to use tool calls instead of outputting code in chat
const SYSTEM_PROMPT = `You are guIDE, an agentic coding assistant integrated into a local IDE. You have full access to the user's filesystem, terminal, web, browser, git, and memory through tool calls. Act directly: when a request calls for a file change, search, command, or fetch, call the tool. Do not describe the action in prose instead of performing it.
## When to use tools
- File creation, edits, or deletion — file tools (write_file, edit_file, append_to_file, delete_file, rename_file). Never paste file contents into chat as a substitute.
- Live information (prices, news, docs, release notes) — use web_search and fetch_webpage as needed to gather sufficient evidence before answering.
- Running commands, checking services, installing packages — terminal tools.
- Interacting with web pages (forms, clicks, screenshots) — browser tools. Always browser_snapshot before interacting so you have current element refs.
- Version control — git tools.
- Multi-step work — write_todos to plan, then execute each step.
- Cross-session memory — save_memory, get_memory, list_memories.
## When not to use tools
Greetings, clarifying questions, opinions, explanations, and small talk are answered in chat with no tool call.
## Operating rules
- Read before you modify. For any edit, call read_file first to get the exact text, then edit_file.
- Call each tool at most once per distinct argument set. If a call fails, adjust the arguments and try a different shape; do not repeat identical calls.
- After a tool returns, use its result. Do not re-ask for information the tool already provided.
- Ground web answers in fetched page content, not in training memory.
- If output is truncated, continue from the point of interruption. Do not restart or re-summarize what was already produced.
- Complete the user's request. If you hit an error, diagnose and retry rather than giving up.`;
class ChatEngine extends EventEmitter {
constructor() {
super();
this.isReady = false;
this.isLoading = false;
this.modelInfo = null;
this.currentModelPath = null;
this.gpuPreference = 'auto';
this._llama = null;
this._model = null;
this._context = null;
this._sequence = null;
this._chat = null;
this._chatHistory = [];
this._lastEvaluation = null;
this._abortController = null;
}
/**
* @param {string} modelPath
* @param {object} [rawLoadSettings] — from settingsManager.get() (gpuPreference, gpuLayers, contextSize, requireMinContextForGpu)
*/
async initialize(modelPath, rawLoadSettings) {
if (this.isLoading) throw new Error('Already loading a model');
this.isLoading = true;
this.emit('status', { state: 'loading', message: 'Loading model...' });
try {
const llamaCppPath = this._getNodeLlamaCppPath();
const { getLlama, LlamaChat, readGgufFileInfo } = await import(pathToFileURL(llamaCppPath).href);
const s = buildEngineLoadSettings(rawLoadSettings || {});
this.gpuPreference = s.gpuPreference;
if (this._model) await this._dispose();
let trainMaxContext = null;
let totalLayersFromGguf = null;
let ggufArchMeta = null;
try {
const gguf = await readGgufFileInfo(modelPath, { readTensorInfo: false, logWarnings: false });
const am = gguf.architectureMetadata;
ggufArchMeta = am || null;
if (am && typeof am.context_length === 'number') trainMaxContext = am.context_length;
if (am && typeof am.block_count === 'number') totalLayersFromGguf = am.block_count;
} catch (e) {
console.warn(`[ChatEngine] readGgufFileInfo: ${e.message}`);
}
// Initialize llama runtime early so we can query VRAM state before context sizing.
this._llama = await getLlama({
gpu: s.gpuPreference === 'cpu' ? false : 'auto',
});
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);
let hardwareCap = null;
let kvSourceMem = 'none';
if (kvBytesPerToken) {
// Available memory pool: prefer free VRAM when GPU mode and GPU has meaningful free space;
// otherwise fall back to free system RAM minus model weight footprint.
let availableBytes = 0;
let vramTotal = 0;
let vramFree = 0;
if (s.gpuPreference !== 'cpu') {
try {
const vramState = await this._llama.getVramState();
vramTotal = vramState?.total || 0;
vramFree = vramState?.free || 0;
} catch (_) {}
}
// KV can draw from VRAM (GPU-resident cache) and from system RAM (mmap / CPU KV / offload).
// Use **both** pools in the sizing estimate instead of picking only one — matches unified
// memory and split-cache behavior better than "VRAM else RAM only".
const minKvBudget = kvBytesPerToken * MIN_CONTEXT_FLOOR;
const ramAfterModel = Math.max(0, os.freemem() - modelStats.size);
const ramOsReserve = 512 * 1024 * 1024;
const ramKvBudget = Math.max(0, ramAfterModel - ramOsReserve) * 0.52;
let vramKvBudget = 0;
if (s.gpuPreference !== 'cpu') {
if (vramFree > modelStats.size + minKvBudget) {
vramKvBudget = (vramFree - modelStats.size) * 0.62;
} else {
const leftover = Math.max(0, vramFree - 64 * 1024 * 1024);
vramKvBudget = leftover * 0.4;
}
}
const kvBudgetBytes = vramKvBudget + ramKvBudget;
if (s.gpuPreference === 'cpu') {
kvSourceMem = 'ram';
} else if (vramKvBudget > 0 && ramKvBudget > 0) {
kvSourceMem = 'vram+ram';
} else if (vramKvBudget > 0) {
kvSourceMem = 'vram';
} else {
kvSourceMem = 'ram';
}
hardwareCap = Math.max(MIN_CONTEXT_FLOOR, Math.floor(kvBudgetBytes / kvBytesPerToken));
}
// TEST_MAX_CONTEXT caps KV only when GUIDE_ALLOW_TEST_MAX_CONTEXT=1 (dev/CI). Otherwise a
// leftover shell env would silently cap every Electron launch at e.g. 8000/8192 tokens.
const testMaxCtxRaw = parseInt(process.env.TEST_MAX_CONTEXT, 10);
const testMaxCtx =
process.env.GUIDE_ALLOW_TEST_MAX_CONTEXT === '1' &&
Number.isFinite(testMaxCtxRaw) &&
testMaxCtxRaw > 0
? testMaxCtxRaw
: 0;
let desiredMax;
if (testMaxCtx > 0) {
desiredMax = testMaxCtx;
} else if (s.contextSize <= 0) {
// Auto: min(hardware cap, train cap). Fall back to train cap if metadata missing.
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);
// Fixed user context cannot exceed hardware KV budget when we computed one.
const requestedFixed = desiredMax;
if (hardwareCap != null) desiredMax = Math.min(desiredMax, hardwareCap);
desiredMax = Math.max(MIN_CONTEXT_FLOOR, desiredMax);
if (s.contextSize > 0 && hardwareCap != null && requestedFixed > desiredMax) {
log.warn(
'ChatEngine',
`Context clamped: settings requested ${s.contextSize}, train_cap=${trainMaxContext ?? 'n/a'}, hardware_cap=${hardwareCap} → effective desiredMax=${desiredMax}`,
);
}
}
const minBase = s.requireMinContextForGpu ? MIN_CONTEXT_WHEN_GPU_REQUIRED : MIN_CONTEXT_FLOOR;
const 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}`,
);
log.info(
'ChatEngine',
`Context sizing: train=${trainMaxContext}, hwCap=${hardwareCap}, userRequested=${s.contextSize <= 0 ? 'auto' : s.contextSize} → desiredMax=${desiredMax}`,
);
const loadModelOpts = {
modelPath,
defaultContextFlashAttention: false,
ignoreMemorySafetyChecks: true,
useMmap: true,
onLoadProgress: (p) => {
this.emit('status', { state: 'loading', message: `Loading model... ${Math.round(p * 100)}%`, progress: p });
},
};
if (s.gpuPreference === 'cpu') {
loadModelOpts.gpuLayers = 0;
} else if (s.gpuLayers >= 0) {
loadModelOpts.gpuLayers = s.gpuLayers;
} else {
loadModelOpts.gpuLayers = {
fitContext: { contextSize: desiredMax },
};
}
this._model = await this._llama.loadModel(loadModelOpts);
let ctxAllocMax = desiredMax;
if (kvBytesPerToken) {
ctxAllocMax = await computeContextAllocMaxAfterModelLoad({
llama: this._llama,
gpuPreference: s.gpuPreference,
kvBytesPerToken,
trainMaxContext,
preDesiredMax: desiredMax,
});
if (ctxAllocMax < desiredMax) {
log.warn(
'ChatEngine',
`Context alloc capped after model load: desiredMax=${desiredMax} → createContext.max=${ctxAllocMax} (live memory / KV bytes per token; avoids shrink ladder to ~${MIN_CONTEXT_FLOOR})`,
);
}
}
const effContextMin = Math.min(contextMin, ctxAllocMax);
this._context = await this._model.createContext({
contextSize: { min: effContextMin, max: ctxAllocMax },
flashAttention: s.gpuPreference !== 'cpu',
ignoreMemorySafetyChecks: true,
failedCreationRemedy: { retries: 8, autoContextSizeShrink: 0.07 },
});
this._sequence = this._context.getSequence();
this._chat = new LlamaChat({ contextSequence: this._sequence });
this._chatHistory = [{ type: 'system', text: SYSTEM_PROMPT }];
this._lastEvaluation = null;
const actualCtx = this._context.contextSize || 0;
if (actualCtx > 0 && ctxAllocMax > 0 && actualCtx + 128 < ctxAllocMax) {
log.warn(
'ChatEngine',
`createContext settled below target: allocTarget=${ctxAllocMax} actual=${actualCtx} (runtime may have tightened further)`,
);
}
this.modelInfo = {
path: modelPath,
name: path.basename(modelPath),
size: modelStats.size,
contextSize: actualCtx,
contextSizeRequested: s.contextSize <= 0 ? 'auto' : s.contextSize,
contextSizeCap: ctxAllocMax,
contextPreLoadDesiredMax: desiredMax,
contextTrainMax: trainMaxContext,
contextHardwareCap: hardwareCap,
kvBytesPerToken: kvBytesPerToken,
kvMemSource: kvSourceMem,
totalLayers: totalLayersFromGguf != null ? totalLayersFromGguf : undefined,
gpuLayers: this._model.gpuLayers || 0,
gpuMode: s.gpuPreference === 'cpu' ? false : 'auto',
};
this.currentModelPath = modelPath;
this.isReady = true;
this.isLoading = false;
console.log(
`[ChatEngine] Model ready: ctx=${actualCtx} (${s.contextSize <= 0 ? 'auto' : `fixed ${s.contextSize}`}, allocMax ${ctxAllocMax}${desiredMax !== ctxAllocMax ? `, preLoadDesired ${desiredMax}` : ''}${trainMaxContext != null ? `, train ${trainMaxContext}` : ''}), gpuLayers=${this.modelInfo.gpuLayers}`,
);
this.emit('status', { state: 'ready', message: `Model ready: ${this.modelInfo.name}`, modelInfo: this.modelInfo });
return this.modelInfo;
} catch (err) {
this.isLoading = false;
this.isReady = false;
this.emit('status', { state: 'error', message: err.message });
throw err;
}
}
async chat(userMessage, options = {}) {
if (!this.isReady || !this._chat) throw new Error('Model not ready');
const { onToken, onComplete, onContextUsage, onToolCall, onStreamEvent, systemPrompt, functions, toolPrompt, compactToolPrompt, executeToolFn, conversationHistory } = options;
const chatTurnId = `turn_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
const chatBodyLogLimit = chatLogBodyLimit();
const chatToolLogLimit = chatLogToolLimit();
const logStreamChunks = process.env.GUIDE_CHAT_LOG_STREAM === '1';
// Inject text attachment content into user message (text/code files only; images unsupported on text-only models)
const attachments = Array.isArray(options.attachments) ? options.attachments : [];
let effectiveUserMessage = String(userMessage ?? '');
if (attachments.length > 0) {
const textParts = [];
for (const a of attachments) {
if (!a?.data) continue;
const mime = (a.mimeType || a.type || '').toLowerCase();
if (mime.startsWith('image/')) continue; // text model cannot process images
try {
const decoded = Buffer.from(a.data, 'base64').toString('utf8');
textParts.push(`[Attached file: ${a.name || 'file'}]\n${decoded}`);
} catch (_) { /* ignore decode errors */ }
}
if (textParts.length > 0) {
effectiveUserMessage = effectiveUserMessage + '\n\n' + textParts.join('\n\n---\n\n');
}
}
log.info(
'ChatTurn',
`[${chatTurnId}] start model=${this.modelInfo?.name ?? '?'} ctx=${this._context?.contextSize ?? '?'} history_turns=${Array.isArray(conversationHistory) ? conversationHistory.length : 0} user_chars=${effectiveUserMessage.length} attachments=${attachments.length} log_limits body=${chatBodyLogLimit} tool=${chatToolLogLimit}`,
);
// Augment system prompt: base + tool prompt when tools are available.
// Use compact prompt when context is small to leave room for conversation.
const contextTokens = this._context?.contextSize || this.modelInfo?.contextSizeCap || MIN_CONTEXT_FLOOR;
const trainMaxCtx = this.modelInfo?.contextTrainMax;
const useCompactToolDefs =
!!compactToolPrompt &&
((trainMaxCtx != null && Number.isFinite(trainMaxCtx) && trainMaxCtx <= 8192) || contextTokens < 8192);
const basePrompt = systemPrompt || SYSTEM_PROMPT;
if (toolPrompt) {
const useCompact = useCompactToolDefs;
const effectiveToolPrompt = useCompact ? compactToolPrompt : toolPrompt;
this._chatHistory[0].text = basePrompt + '\n\n' + effectiveToolPrompt;
console.log(`[ChatEngine] Tool prompt injected (${effectiveToolPrompt.length} chars${useCompact ? ', compact' : ''}, ctx=${contextTokens})`);
log.info(
'ChatTurn',
`[${chatTurnId}] tool_prompt injected_chars=${effectiveToolPrompt.length} compact=${!!useCompact} ctx=${contextTokens}`,
);
} else if (functions && Object.keys(functions).length > 0) {
this._chatHistory[0].text = basePrompt + this._buildToolPrompt(functions);
console.log(`[ChatEngine] Functions provided (fallback): ${Object.keys(functions).length} tools`);
log.info('ChatTurn', `[${chatTurnId}] functions_fallback tool_defs=${Object.keys(functions).length}`);
} else if (systemPrompt) {
this._chatHistory[0].text = systemPrompt;
}
// node-llama-cpp ChatHistoryItem: user/system use `text`; model uses `response` (string[]), not `text`.
const normalizedHistory = Array.isArray(conversationHistory)
? conversationHistory
.map((m) => {
const role = m?.role === 'assistant' ? 'model' : (m?.role === 'user' ? 'user' : null);
const text = typeof m?.content === 'string' ? m.content.trim() : '';
if (!role || !text) return null;
if (role === 'model') return { type: 'model', response: [text] };
return { type: 'user', text };
})
.filter(Boolean)
: [];
this._chatHistory = [{ type: 'system', text: this._chatHistory[0].text }, ...normalizedHistory];
this._lastEvaluation = null;
this._chatHistory.push({ type: 'user', text: effectiveUserMessage });
const sysPromptText = this._chatHistory[0]?.text || '';
log.info(
'ChatTurn',
`[${chatTurnId}] system_prompt_chars=${sysPromptText.length} preview=\n${_truncateForLog(sysPromptText, chatBodyLogLimit)}`,
);
log.info(
'ChatTurn',
`[${chatTurnId}] user_message_preview=\n${_truncateForLog(effectiveUserMessage, chatBodyLogLimit)}`,
);
if (normalizedHistory.length > 0) {
const maxTurns = Math.min(normalizedHistory.length, 48);
const slice = normalizedHistory.slice(-maxTurns);
const perTurn = Math.max(180, Math.floor(chatBodyLogLimit / Math.max(1, slice.length)));
const startIdx = normalizedHistory.length - slice.length;
const histLines = slice.map((m, i) => `[${startIdx + i}] ${m.type}: ${_truncateForLog(m.text, perTurn)}`);
log.info(
'ChatTurn',
`[${chatTurnId}] prior_history (${normalizedHistory.length} msgs, showing last ${slice.length}):\n${histLines.join('\n---\n')}`,
);
}
this._abortController = new AbortController();
let fullResponse = '';
let tokensSinceLastUsageReport = 0;
let totalToolCalls = 0;
// Generation timeout — optional only (0 = disabled). No default cap on run length.
const timeoutSec = options.generationTimeoutSec ?? 0;
let generationTimer = null;
if (timeoutSec > 0) {
generationTimer = setTimeout(() => {
console.warn(`[ChatEngine] Generation timeout after ${timeoutSec}s — aborting`);
this._abortController?.abort('generation_timeout');
}, timeoutSec * 1000);
}
try {
// ── Streaming tool call filter ──
// Two-layer suppression of tool call JSON from the UI:
//
// Layer 1 (real-time): This filter processes each token character-by-character.
// - When `{` appears at a line boundary, buffer it. If `"tool":` appears
// within the first 80 chars, keep buffering silently until braces close.
// - When ``` appears at a line boundary, enter fence mode. If the fence
// content starts with `{` and contains `"tool":`, suppress the entire fence.
//
// Layer 2 (post-generation): stripToolCallText() catches anything the
// streaming filter missed (e.g., XML <tool_call> tags).
//
// Result: tool call JSON never appears in the chat as raw text.
let _sfBuf = ''; // pending buffer
let _sfDepth = 0; // brace depth
let _sfActive = false; // inside a potential raw JSON tool call
let _sfConfirmed = false; // buffer confirmed to contain "tool":
let _sfInStr = false; // inside a JSON string
let _sfEscaped = false; // previous char was backslash inside string
let _sfLastCharWasNewlineOrStart = true;
// Fence tracking: ```json ... ```
let _sfInFence = false; // inside a code fence
let _sfFenceBuf = ''; // accumulated fence content (markers + body)
let _sfFenceTickCount = 0; // tracks consecutive backticks
/** When true, fence body is plain markdown code (html, etc.) — stream to UI instead of buffering until ``` */
let _sfFenceStreamPlain = false;
let _sfFencePlainTick = 0; // backticks while streaming plain fence (closing ```)
// Real-time file content streaming state — detects write_file/create_file/append_to_file
// content fields inside tool call JSON and streams them to the UI as they arrive
let _sfFileWriteDetected = false;
let _sfContentStreamActive = false;
let _sfContentDone = false;
let _sfContentEsc = false;
let _sfContentBuf = '';
let _sfContentFilePath = '';
let _sfUnicodeCount = 0;
let _sfUnicodeChars = '';
const _sfStreamedFileWrites = new Set();
const _sfForward = (text) => {
if (onToken) onToken(text);
};
const _sfFlush = () => {
if (_sfContentStreamActive && onStreamEvent) {
if (_sfContentBuf) {
onStreamEvent('file-content-token', _sfContentBuf);
_sfContentBuf = '';
}
onStreamEvent('file-content-end', { filePath: _sfContentFilePath, fileKey: _sfContentFilePath });
_sfContentStreamActive = false;
} else if (_sfBuf) {
_sfForward(_sfBuf);
}
_sfBuf = '';
_sfDepth = 0;
_sfActive = false;
_sfConfirmed = false;
_sfInStr = false;
_sfEscaped = false;
_sfFileWriteDetected = false;
_sfContentDone = false;
_sfContentEsc = false;
_sfUnicodeCount = 0;
_sfUnicodeChars = '';
};
const _sfFlushFence = () => {
if (_sfContentStreamActive && onStreamEvent) {
if (_sfContentBuf) {
onStreamEvent('file-content-token', _sfContentBuf);
_sfContentBuf = '';
}
onStreamEvent('file-content-end', { filePath: _sfContentFilePath, fileKey: _sfContentFilePath });
_sfContentStreamActive = false;
}
if (_sfFenceBuf) {
_sfForward(_sfFenceBuf);
_sfFenceBuf = '';
}
_sfInFence = false;
_sfFenceStreamPlain = false;
_sfFencePlainTick = 0;
_sfFenceTickCount = 0;
_sfFileWriteDetected = false;
_sfContentDone = false;
_sfContentEsc = false;
_sfUnicodeCount = 0;
_sfUnicodeChars = '';
};
const _sfProcessChunk = (chunk) => {
for (let i = 0; i < chunk.length; i++) {
const ch = chunk[i];
// ── Fence mode: accumulating content inside ```...``` ──
if (_sfInFence) {
// Stream normal markdown code fences (```html, ```css, …) to the UI immediately.
// Only JSON tool-call fences stay buffered until close (so we can strip/suppress).
if (_sfFenceStreamPlain) {
if (ch === '`') {
_sfFencePlainTick++;
if (_sfFencePlainTick >= 3) {
_sfForward('```');
_sfInFence = false;
_sfFenceStreamPlain = false;
_sfFencePlainTick = 0;
_sfFenceBuf = '';
_sfLastCharWasNewlineOrStart = (ch === '\n' || ch === '\r');
}
} else {
if (_sfFencePlainTick > 0) {
_sfForward('`'.repeat(_sfFencePlainTick));
_sfFencePlainTick = 0;
}
_sfForward(ch);
}
continue;
}
_sfFenceBuf += ch;
if (!_sfFenceStreamPlain && !_sfFileWriteDetected && !_sfContentStreamActive && /^```\s*(\w*)\r?\n/.test(_sfFenceBuf)) {
const hm = _sfFenceBuf.match(/^```\s*(\w*)\r?\n/);
const lang = (hm[1] || '').toLowerCase();
const afterHeader = _sfFenceBuf.slice(hm[0].length);
const PLAIN_LANGS = new Set([
'html', 'htm', 'css', 'scss', 'sass', 'less', 'js', 'javascript', 'jsx', 'mjs', 'cjs',
'ts', 'tsx', 'vue', 'svelte', 'md', 'markdown', 'py', 'python', 'bash', 'sh', 'shell',
'yaml', 'yml', 'xml', 'svg', 'go', 'rust', 'rs', 'java', 'cpp', 'c', 'h', 'cs', 'php',
'rb', 'swift', 'kt', 'txt', 'plaintext', 'sql', 'jsonl',
]);
if (PLAIN_LANGS.has(lang)) {
_sfFenceStreamPlain = true;
_sfForward(_sfFenceBuf);
_sfFenceBuf = '';
continue;
}
if (lang === 'json' || lang === '') {
if (/"tool"\s*:/.test(afterHeader.slice(0, 6000))) {
/* keep buffering — tool JSON fence */
} else if (afterHeader.length >= 100) {
_sfFenceStreamPlain = true;
_sfForward(_sfFenceBuf);
_sfFenceBuf = '';
continue;
}
}
}
// Real-time content streaming from WITHIN a fenced tool call.
// Uses the same shared state variables as the raw JSON path.
if (_sfContentStreamActive) {
if (_sfUnicodeCount > 0) {
_sfUnicodeChars += ch;
_sfUnicodeCount--;
if (_sfUnicodeCount === 0) {
try { _sfContentBuf += String.fromCharCode(parseInt(_sfUnicodeChars, 16)); }
catch { _sfContentBuf += '\\u' + _sfUnicodeChars; }
}
} else if (_sfContentEsc) {
let decoded;
switch (ch) {
case 'n': decoded = '\n'; break;
case 't': decoded = '\t'; break;
case 'r': decoded = '\r'; break;
case '"': decoded = '"'; break;
case '\\': decoded = '\\'; break;
case '/': decoded = '/'; break;
case 'b': decoded = '\b'; break;
case 'f': decoded = '\f'; break;
case 'u': _sfUnicodeCount = 4; _sfUnicodeChars = ''; decoded = null; break;
default: decoded = ch;
}
_sfContentEsc = false;
if (decoded !== null) _sfContentBuf += decoded;
} else if (ch === '\\') {
_sfContentEsc = true;
} else if (ch === '"') {
_sfContentStreamActive = false;
_sfContentDone = true;
if (_sfContentBuf && onStreamEvent) {
onStreamEvent('file-content-token', _sfContentBuf);
_sfContentBuf = '';
}
if (onStreamEvent) {
onStreamEvent('file-content-end', { filePath: _sfContentFilePath, fileKey: _sfContentFilePath });
}
} else {
_sfContentBuf += ch;
}
if (_sfContentStreamActive && _sfContentBuf.length >= 40) {
if (onStreamEvent) {
onStreamEvent('file-content-token', _sfContentBuf);
_sfContentBuf = '';
}
}
} else if (_sfFileWriteDetected && !_sfContentDone) {
if (ch === '"' && /"content"\s*:\s*"$/.test(_sfFenceBuf)) {
_sfContentStreamActive = true;
const fpMatch = _sfFenceBuf.match(/"(?:filePath|path)"\s*:\s*"([^"]*)"/);
_sfContentFilePath = fpMatch ? fpMatch[1] : '';
const fileName = _sfContentFilePath.split(/[\\/]/).pop() || _sfContentFilePath;
const ext = fileName.includes('.') ? fileName.split('.').pop().toLowerCase() : '';
if (onStreamEvent) {
onStreamEvent('file-content-start', { filePath: _sfContentFilePath, fileName, language: ext, fileKey: _sfContentFilePath });
}
_sfStreamedFileWrites.add(_sfContentFilePath);
}
}
if (!_sfFileWriteDetected && _sfFenceBuf.length > 30) {
if ((/write_file|create_file|append_to_file/.test(_sfFenceBuf)) &&
(/"tool"\s*:/.test(_sfFenceBuf) || /"name"\s*:/.test(_sfFenceBuf))) {
_sfFileWriteDetected = true;
}
}
// Detect closing ``` — but NOT while inside the content string
if (_sfContentStreamActive || _sfContentEsc || _sfUnicodeCount > 0) {
_sfFenceTickCount = 0;
} else if (ch === '`') {
_sfFenceTickCount++;
} else {
if (_sfFenceTickCount >= 3) {
// Closing fence found — flush any pending content
if (_sfContentStreamActive && onStreamEvent) {
if (_sfContentBuf) {
onStreamEvent('file-content-token', _sfContentBuf);
_sfContentBuf = '';
}
onStreamEvent('file-content-end', { filePath: _sfContentFilePath, fileKey: _sfContentFilePath });
_sfContentStreamActive = false;
}
if (/"tool"\s*:/.test(_sfFenceBuf) || /"name"\s*:/.test(_sfFenceBuf)) {
_sfFenceBuf = '';
} else {
_sfFlushFence();
}
_sfInFence = false;
_sfFileWriteDetected = false;
_sfContentDone = false;
_sfContentEsc = false;
_sfLastCharWasNewlineOrStart = (ch === '\n' || ch === '\r');
continue;
}
_sfFenceTickCount = 0;
}
continue;
}
// ── Normal mode ──
if (!_sfActive) {
// Detect opening ``` at line start
if (ch === '`' && _sfLastCharWasNewlineOrStart) {
_sfFenceTickCount++;
if (_sfFenceTickCount >= 3) {
_sfInFence = true;
_sfFenceBuf = '```';
_sfFenceTickCount = 0;
_sfFenceStreamPlain = false;
_sfFencePlainTick = 0;
_sfLastCharWasNewlineOrStart = false;
continue;
}
continue;
}
// If we had 1-2 backticks but not 3, flush them
if (_sfFenceTickCount > 0 && ch !== '`') {
_sfForward('`'.repeat(_sfFenceTickCount));
_sfFenceTickCount = 0;
}
// Look for `{` at line start (or after only whitespace on the line)
if (ch === '{' && _sfLastCharWasNewlineOrStart) {
_sfActive = true;
_sfBuf = '{';
_sfDepth = 1;
_sfConfirmed = false;
_sfInStr = false;
_sfEscaped = false;
_sfLastCharWasNewlineOrStart = false;
continue;
}
_sfLastCharWasNewlineOrStart = (ch === '\n' || ch === '\r');
if (ch === ' ' || ch === '\t') { /* keep the flag */ }
else if (ch !== '\n' && ch !== '\r') _sfLastCharWasNewlineOrStart = false;
_sfForward(ch);
continue;
}
// ── Inside a potential raw JSON tool call ──
_sfBuf += ch;
// ── Real-time file content streaming ──
// When inside a confirmed file-write tool call, intercept the "content"
// field value and stream decoded characters to file-content-token events.
if (_sfContentStreamActive) {
if (_sfUnicodeCount > 0) {
_sfUnicodeChars += ch;
_sfUnicodeCount--;
if (_sfUnicodeCount === 0) {
try { _sfContentBuf += String.fromCharCode(parseInt(_sfUnicodeChars, 16)); }
catch { _sfContentBuf += '\\u' + _sfUnicodeChars; }
}
} else if (_sfContentEsc) {
let decoded;
switch (ch) {
case 'n': decoded = '\n'; break;
case 't': decoded = '\t'; break;
case 'r': decoded = '\r'; break;
case '"': decoded = '"'; break;
case '\\': decoded = '\\'; break;
case '/': decoded = '/'; break;
case 'b': decoded = '\b'; break;
case 'f': decoded = '\f'; break;
case 'u': _sfUnicodeCount = 4; _sfUnicodeChars = ''; decoded = null; break;
default: decoded = ch;
}
_sfContentEsc = false;
if (decoded !== null) _sfContentBuf += decoded;
} else if (ch === '\\') {
_sfContentEsc = true;
} else if (ch === '"') {
_sfContentStreamActive = false;
_sfContentDone = true;
if (_sfContentBuf && onStreamEvent) {
onStreamEvent('file-content-token', _sfContentBuf);
_sfContentBuf = '';
}
if (onStreamEvent) {
onStreamEvent('file-content-end', { filePath: _sfContentFilePath, fileKey: _sfContentFilePath });
}
} else {
_sfContentBuf += ch;
}
if (_sfContentStreamActive && _sfContentBuf.length >= 40) {
if (onStreamEvent) {
onStreamEvent('file-content-token', _sfContentBuf);
_sfContentBuf = '';
}
}
} else if (_sfConfirmed && _sfFileWriteDetected && !_sfContentDone) {
if (ch === '"' && /"content"\s*:\s*"$/.test(_sfBuf)) {
_sfContentStreamActive = true;
const fpMatch = _sfBuf.match(/"(?:filePath|path)"\s*:\s*"([^"]*)"/);
_sfContentFilePath = fpMatch ? fpMatch[1] : '';
const fileName = _sfContentFilePath.split(/[\\/]/).pop() || _sfContentFilePath;
const ext = fileName.includes('.') ? fileName.split('.').pop().toLowerCase() : '';
if (onStreamEvent) {
onStreamEvent('file-content-start', { filePath: _sfContentFilePath, fileName, language: ext, fileKey: _sfContentFilePath });
}
_sfStreamedFileWrites.add(_sfContentFilePath);
}
}
if (_sfConfirmed && !_sfFileWriteDetected && _sfBuf.length > 15) {
if (/write_file|create_file|append_to_file/.test(_sfBuf)) {
_sfFileWriteDetected = true;
}
}
if (_sfEscaped) { _sfEscaped = false; continue; }
if (ch === '\\' && _sfInStr) { _sfEscaped = true; continue; }
if (ch === '"') { _sfInStr = !_sfInStr; continue; }
if (_sfInStr) continue;
if (ch === '{') _sfDepth++;
else if (ch === '}') _sfDepth--;
if (!_sfConfirmed && _sfBuf.length <= 80) {
if (/"tool"\s*:/.test(_sfBuf) || /"name"\s*:\s*"[^"]*"/.test(_sfBuf)) {
_sfConfirmed = true;
}
}
if (!_sfConfirmed && _sfBuf.length > 80) {
_sfFlush();
_sfLastCharWasNewlineOrStart = false;
continue;
}
if (_sfDepth === 0) {
if (_sfConfirmed) {
if (_sfContentBuf && _sfContentStreamActive && onStreamEvent) {
onStreamEvent('file-content-token', _sfContentBuf);
_sfContentBuf = '';
}
_sfBuf = '';
} else {
_sfFlush();
}
_sfActive = false;
_sfConfirmed = false;
_sfFileWriteDetected = false;
_sfContentDone = false;
_sfLastCharWasNewlineOrStart = false;
}
}
};
// Build common generation options
const thinkBudget = options.thinkingBudget;
const genOptions = {
signal: this._abortController.signal,
stopOnAbortSignal: true,
temperature: options.temperature ?? 0.7,
topP: options.topP,
topK: options.topK,
repeatPenalty: options.repeatPenalty ? { penalty: options.repeatPenalty } : undefined,
contextShift: { strategy: this._contextShiftStrategy.bind(this) },
onTextChunk: (chunk) => {
fullResponse += chunk;
if (logStreamChunks) log.debug('ChatTurnStream', `[${chatTurnId}]`, chunk);
_sfProcessChunk(chunk);
tokensSinceLastUsageReport++;
if (onContextUsage && tokensSinceLastUsageReport >= 50) {
tokensSinceLastUsageReport = 0;
const used = this._sequence.nextTokenIndex;
const total = this._context.contextSize;