-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchatEngine.js
More file actions
6052 lines (5660 loc) · 290 KB
/
Copy pathchatEngine.js
File metadata and controls
6052 lines (5660 loc) · 290 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, isVisibleToolArtifact, looksLikeToolAttempt, suggestClosestToolName, extractPartialWriteFileFromToolJson, normalizeStreamingFilePath, resolveStreamingFileKey, _inferFilePath } = 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, resolveSamplingProfile, resolveAgentDryRepeatPenalty } = require('./modelProfiles');
const {
PLAN_MODE_ALLOWED_TOOLS,
filterPlanModeToolCalls,
isPlanFilePath,
resolvePlanPhase,
resolveAgentMode,
getAgentSystemPrompt,
} = require('./agentModeResolver');
const streamTrace = require('./streamTrace');
/** 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,
};
/** Whether file-content UI may stream during plan mode (plan files only until Build). */
function shouldStreamFileContentForAgent(options, filePath) {
if (!options?.planMode || options.agentPhase === 'building') return true;
return isPlanFilePath(filePath || '');
}
function _sfStripFenceMarkers(fenceBuf) {
const trimmed = String(fenceBuf || '').trim();
const open = trimmed.match(/^(`{3,})\s*(\w*)\s*\n?/);
if (!open) return trimmed;
let inner = trimmed.slice(open[0].length);
const close = inner.match(/\n?(`{3,})\s*$/);
if (close) inner = inner.slice(0, -close[0].length);
return inner.trim();
}
/** Parse write_file / edit_file payload from a closed tool-json fence buffer. */
function _sfExtractFileWriteFromToolFence(fenceBuf) {
try {
const calls = parseToolCalls(fenceBuf);
for (const c of calls) {
if (RE_FILE_STREAM_TOOLS.test(c.tool)) {
const p = c.params || {};
const filePath = p.filePath || p.path;
if (!filePath) continue;
return {
tool: c.tool,
filePath: String(filePath),
content: p.content ?? p.newText ?? '',
oldText: p.oldText,
isEdit: FILE_EDIT_OPS.has(c.tool),
};
}
}
} catch (_) { /* parseToolCalls may fail on partial buffers */ }
const inner = _sfStripFenceMarkers(fenceBuf);
if (!inner) return null;
try {
const parsed = JSON.parse(inner);
const tool = parsed.tool || parsed.name;
const params = parsed.params || parsed.parameters || parsed.arguments || parsed;
if (tool && RE_FILE_STREAM_TOOLS.test(tool) && (params.filePath || params.path)) {
return {
tool,
filePath: params.filePath || params.path,
content: params.content ?? params.newText ?? '',
oldText: params.oldText,
isEdit: FILE_EDIT_OPS.has(tool),
};
}
} catch (_) {}
return null;
}
/** Bulk-replay file-content IPC when tool JSON fence closes without live char streaming. */
function _sfBulkReplayFileContentFromFence(fenceBuf, ctx) {
const {
onStreamEvent, options, streamedSet, normalizePath, allowNewStart, endCompleted, markActive,
} = ctx;
if (!fenceBuf || !onStreamEvent) return false;
const info = _sfExtractFileWriteFromToolFence(fenceBuf);
if (!info?.filePath || info.content == null) return false;
if (!shouldStreamFileContentForAgent(options, info.filePath)) return false;
const np = normalizePath(info.filePath);
if (streamedSet.has(np)) {
if (endCompleted.has(np)) {
endCompleted.delete(np);
} else {
return false;
}
}
if (!allowNewStart(info.filePath)) return false;
const fileName = info.filePath.split(/[\\/]/).pop() || info.filePath;
const ext = fileName.includes('.') ? fileName.split('.').pop().toLowerCase() : '';
const content = String(info.content);
onStreamEvent('file-content-start', {
filePath: info.filePath,
fileName,
language: ext,
fileKey: np,
op: info.isEdit ? 'edit' : 'write',
oldText: info.oldText != null ? String(info.oldText) : undefined,
});
streamedSet.add(np);
markActive(info.filePath);
const CHUNK = 4096;
for (let i = 0; i < content.length; i += CHUNK) {
onStreamEvent('file-content-token', content.slice(i, i + CHUNK));
}
onStreamEvent('file-content-end', { filePath: info.filePath, fileKey: np });
endCompleted.add(np);
markActive(null);
return true;
}
/** Emit one atomic IPC event for a complete file write (native FC / batch prose path). */
function emitCompleteFileContentBlock(onStreamEvent, filePath, content, options, meta = {}) {
if (!onStreamEvent || content == null) return;
if (options && !shouldStreamFileContentForAgent(options, filePath)) return;
const fp = filePath || '';
const fn = fp.split(/[\\/]/).pop() || fp;
const ext = fn.includes('.') ? fn.split('.').pop().toLowerCase() : '';
const fileKey = resolveStreamingFileKey(fp, options?.projectPath);
onStreamEvent('file-content-block-complete', {
filePath: fp,
fileName: fn,
language: ext,
fileKey,
content: String(content),
op: meta.op || 'write',
oldText: meta.oldText != null ? String(meta.oldText) : undefined,
newText: meta.newText != null ? String(meta.newText) : undefined,
});
}
/**
* 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
*/
const {
jsonStringChunkDecode: _jsonStringChunkDecode,
createJsonStringStreamState: _createJsonStringStreamState,
jsonStringStreamStep: _jsonStringStreamStep,
} = require('./tools/jsonStringChunkDecode');
function _decodeFenceContentEscape(ch) {
switch (ch) {
case 'n': return '\n';
case 't': return '\t';
case 'r': return '\r';
case '"': return '"';
case '\\': return '\\';
case '/': return '/';
case 'b': return '\b';
case 'f': return '\f';
default: return '\\' + ch;
}
}
// 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/;
/** Prose-only fence langs that may stream live to chat; code langs buffer until close → CodeBlock. */
const SF_PLAIN_FENCE_LANGS = new Set(['md', 'markdown']);
function _sfPlainFenceLang(fenceBuf) {
const m = String(fenceBuf || '').match(/^```\s*(\w*)/i);
return (m?.[1] || '').toLowerCase();
}
function _sfIsPlainMarkdownFence(fenceBuf) {
return SF_PLAIN_FENCE_LANGS.has(_sfPlainFenceLang(fenceBuf));
}
/** Fence languages that must buffer until close — never stream tool JSON to prose. */
const SF_TOOL_FENCE_LANGS = new Set(['json', 'tool', 'tool_call', 'text', 'plaintext']);
function _sfIsToolFenceLang(lang) {
const l = (lang || '').toLowerCase();
if (!l) return false;
if (SF_TOOL_FENCE_LANGS.has(l)) return true;
if (l.includes('json') || l.includes('tool')) return true;
if (/^j+s*o?n/.test(l)) return true;
return false;
}
const SF_FENCE_PLAIN_MIN_BODY = 24;
/**
* Whether a fence buffer at header detection should stream to prose chat.
* Used by the stream filter and regression tests.
* All non-tool markdown/code fences (html, css, js, md, …) stream live.
*/
function _sfFenceHeaderShouldStreamPlain(fenceBuf) {
if (!RE_FENCE_HEADER.test(fenceBuf)) return false;
const hm = fenceBuf.match(RE_FENCE_HEADER);
const lang = (hm[1] || '').toLowerCase();
const afterHeader = fenceBuf.slice(hm[0].length);
if (_sfIsToolFenceLang(lang)) return false;
if (afterHeader.length < SF_FENCE_PLAIN_MIN_BODY) return false;
const looksLikeToolBody = _sfFenceBufferLooksLikeToolJson(afterHeader.slice(0, 8000))
|| _sfIsToolLikeJson(afterHeader.slice(0, 6000));
if (looksLikeToolBody) return false;
return true;
}
/** Agent/build mode where code fences should route to FileContentBlock instead of prose. */
function _sfIsAgentFileFenceMode(options) {
if (!options) return false;
if (options.askOnly || options.chatMode === 'ask') return false;
if ((options.planMode || options.chatMode === 'plan') && options.agentPhase !== 'building') return false;
return true;
}
/** Whether an in-progress fence should stream to FileContentBlock (agent mode, non-md, non-tool). */
function _sfShouldRouteAgentCodeFence(fenceBuf, options) {
if (!_sfIsAgentFileFenceMode(options)) return false;
if (!RE_FENCE_HEADER.test(fenceBuf)) return false;
const hm = fenceBuf.match(RE_FENCE_HEADER);
const lang = (hm[1] || '').toLowerCase();
if (_sfIsToolFenceLang(lang)) return false;
if (SF_PLAIN_FENCE_LANGS.has(lang)) return false;
const afterHeader = fenceBuf.slice(hm[0].length);
if (afterHeader.length < SF_FENCE_PLAIN_MIN_BODY) return false;
const looksLikeToolBody = _sfFenceBufferLooksLikeToolJson(afterHeader.slice(0, 8000))
|| _sfIsToolLikeJson(afterHeader.slice(0, 6000));
if (looksLikeToolBody) return false;
return true;
}
function _sfExtractAgentFenceBody(fenceBuf) {
const hm = String(fenceBuf || '').match(RE_FENCE_HEADER);
if (!hm) return '';
let body = fenceBuf.slice(hm[0].length);
const closeMatch = body.match(/\n?`{3,}\s*$/);
if (closeMatch) body = body.slice(0, -closeMatch[0].length);
return body;
}
/** Infer project file path for a plain code fence in agent mode. */
function _sfInferAgentFenceFilePath(fenceBuf, contextText = '') {
const hm = String(fenceBuf || '').match(RE_FENCE_HEADER);
const lang = hm ? (hm[1] || '').toLowerCase() : '';
const body = _sfExtractAgentFenceBody(fenceBuf);
return _inferFilePath(`${contextText}\n${fenceBuf}`, body, lang);
}
/** Re-route think-buffer content that is really file/tool payload (not reasoning prose). */
function _sfRerouteThinkContentToFile(text, options, contextText = '') {
if (!text || !_sfIsAgentFileFenceMode(options)) return null;
const sample = String(text);
if (_sfIsToolLikeJson(sample)) {
const partial = extractPartialWriteFileFromToolJson(sample, { stripCompleteSuffix: true });
if (partial?.filePath && partial.content != null) {
return { filePath: partial.filePath, content: partial.content, op: partial.isEdit ? 'edit' : 'write', oldText: partial.oldText };
}
}
const fenceRe = /```(\w*)\s*\n([\s\S]*)/;
const fm = sample.match(fenceRe);
if (fm) {
const lang = (fm[1] || '').toLowerCase();
if (!_sfIsToolFenceLang(lang) && !SF_PLAIN_FENCE_LANGS.has(lang)) {
const body = fm[2].replace(/\n?`{3,}\s*$/, '');
const filePath = _inferFilePath(`${contextText}\n${sample}`, body, lang);
if (filePath) return { filePath, content: body, op: 'write' };
}
}
if (/<!DOCTYPE|<html[\s>]/i.test(sample)) {
const filePath = _inferFilePath(`${contextText}\n${sample}`, sample);
if (filePath) return { filePath, content: sample, op: 'write' };
}
return null;
}
function _sfStripPlainCodeFencesFromProse(text) {
if (!text) return text;
return text.replace(/```(?!markdown\b|md\b)[\w-]*\s*\n[\s\S]*?```/gi, '').trim();
}
/** Keep fence markers; append closing ``` when generation ended mid-fence. */
function _sfPreparePlainFenceFlushPayload(fenceBuf) {
if (!fenceBuf) return '';
let payload = fenceBuf;
const openMatch = payload.match(/^(`{3,})\s*(\w*)/);
if (openMatch) {
const tickLen = openMatch[1].length;
const trimmed = payload.trimEnd();
const closeRe = new RegExp('\\n`{' + tickLen + ',}\\s*$');
if (!closeRe.test(trimmed)) {
payload = trimmed + '\n' + '`'.repeat(tickLen);
}
}
return payload;
}
// 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_BARE_NAME_TOOL = /\{\s*"[a-z][a-z0-9_]+"\s*,\s*"params"\s*:/i; // {"find_files","params":{...}}
function _sfIsToolLikeJson(buf) {
return RE_TOOL_KEY.test(buf)
|| (RE_NAME_KEY.test(buf) && RE_PARAMS_KEY.test(buf))
|| RE_BARE_NAME_TOOL.test(buf);
}
function _sfFenceBufferLooksLikeToolJson(buf) {
if (!buf) return false;
if (_sfIsToolLikeJson(buf)) return true;
if (/^```(?:json|tool|tool_call|jjson)\s/i.test(buf.trimStart())) return true;
if (/"tool"\s*:\s*"/.test(buf)) return true;
return false;
}
/** Sanitize user message / digest text that embeds truncated editor file snippets. */
function _sanitizeFileSnippetText(text) {
if (!text || typeof text !== 'string') return text;
return text.replace(
/\[Current file:\s*([^\]]+)\]\n[\s\S]*/,
(_match, filePath) => `Current file: ${String(filePath).trim()} (snippet only — full content on disk; use read_file for complete file)`,
);
}
/**
* One-line hint after tool batches when todos exist but update_todo was not called.
* @param {Array<{id:number,text?:string,status?:string}>} activeTodos
* @param {string[]} executedTools
* @param {number} consecutiveWithoutUpdate
*/
function buildTodoProgressHint(activeTodos, executedTools, consecutiveWithoutUpdate = 0) {
if (!Array.isArray(activeTodos) || activeTodos.length === 0) return '';
const tools = Array.isArray(executedTools) ? executedTools : [];
if (tools.some((t) => t === 'update_todo' || t === 'write_todos')) return '';
const open = activeTodos.filter((t) => t.status === 'pending' || t.status === 'in-progress');
if (open.length === 0) return '';
const pending = open.filter((t) => t.status === 'pending').length;
const inProgress = open.filter((t) => t.status === 'in-progress').length;
const counts = [
pending > 0 ? `${pending} pending` : '',
inProgress > 0 ? `${inProgress} in-progress` : '',
].filter(Boolean).join(', ');
const idList = open.map((t) => `id ${t.id}: ${(t.text || '').slice(0, 60)}`).join('; ');
let hint = `[System: Active todo list (${counts}). If you finished a step, call update_todo with that id and status "done" before starting the next tool. Items: ${idList}.]`;
if (consecutiveWithoutUpdate >= 3) {
hint += ' [Reminder: several tools ran without update_todo — mark finished steps done so the todo list stays accurate.]';
}
return `${hint}\n\n`;
}
function _sfExtractGeneratingToolName(buf) {
const standard = buf.match(/"(?:tool|name)"\s*:\s*"([^"]+)"/);
if (standard) return standard[1];
const bare = buf.match(RE_BARE_NAME_TOOL);
return bare ? bare[1] : 'unknown';
}
const RE_FILE_WRITE_TOOLS = /write_file|create_file|append_to_file/;
const RE_FILE_EDIT_TOOLS = /edit_file|replace_in_file/;
const RE_FILE_STREAM_TOOLS = /write_file|create_file|append_to_file|edit_file|replace_in_file/;
const RE_CONTENT_START = /"content"\s*:\s*"$/;
const RE_NEW_TEXT_START = /"newText"\s*:\s*"$/;
const RE_OLD_TEXT_CAPTURE = /"oldText"\s*:\s*"((?:\\.|[^"\\])*)"/;
const FILE_EDIT_OPS = new Set(['edit_file', 'replace_in_file']);
const RE_FILE_PATH = /"(?:filePath|path)"\s*:\s*"([^"]*)"/;
const RE_TOOL_OR_SYSTEM_INJECT = /^\[(?:Tool Results|System)\]/i;
const RE_CONTEXT_ROTATED = /\[System: (?:Context rotated|Session memory condensed)\]/i;
const LIST_DIRECTORY_INJECT_MAX_ITEMS = 50;
const DUPLICATE_TOOL_HINT_MESSAGE = '[System: You already called this exact tool with the same parameters twice in a row. Use the prior tool results or try a different approach.]';
function stableToolFingerprint(tool, params) {
try {
const keys = Object.keys(params ?? {}).sort();
const sorted = {};
for (const k of keys) sorted[k] = params[k];
return `${tool}:${JSON.stringify(sorted)}`;
} catch {
return `${tool}:${String(params)}`;
}
}
function trimListDirectoryInjectPayload(toolResult) {
if (!toolResult?.success || !Array.isArray(toolResult.items)) return toolResult;
if (toolResult.items.length <= LIST_DIRECTORY_INJECT_MAX_ITEMS) return toolResult;
const omitted = toolResult.items.length - LIST_DIRECTORY_INJECT_MAX_ITEMS;
return {
...toolResult,
items: toolResult.items.slice(0, LIST_DIRECTORY_INJECT_MAX_ITEMS),
listingNote: `NOT a complete listing — ${omitted} more entries omitted; use find_files or list a subdirectory.`,
};
}
/** 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: maximize gpuLayers; layer search uses minimum context budget so VRAM goes to weights.
if (mode === 'speed') {
let bestPartial = null;
let bestCpuOnly = null;
for (let gpuLayers = totalLayers; gpuLayers >= 0; gpuLayers--) {
const fit = computeLayerVramFit({
...fitParams,
gpuLayers,
desiredMaxContext: minContext,
});
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) {
const finalFit = computeLayerVramFit({
...fitParams,
gpuLayers: bestPartial.gpuLayers,
desiredMaxContext,
});
return {
gpuLayers: bestPartial.gpuLayers,
contextSize: finalFit?.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.
*/
/** Tier-0 tool parts: header + Browser + Core Files + Terminal — never dropped in Agent mode. */
const AGENT_TOOL_TIER0_PART_COUNT = 4;
/** Legacy default — use resolveAgentMinToolPromptChars(tier) for agent mode. */
const AGENT_MIN_TOOL_PROMPT_CHARS = 10000;
/** Minimum tool-catalog chars reserved in agent prefill, scaled by model size tier. */
function resolveAgentMinToolPromptChars(sizeTier) {
switch (sizeTier) {
case 'tiny': return 0;
case 'small': return 2048;
case 'medium': return 4096;
case 'large': return 8192;
case 'xlarge': return AGENT_MIN_TOOL_PROMPT_CHARS;
default: return AGENT_MIN_TOOL_PROMPT_CHARS;
}
}
/** Small models use compact tool parts only — skip injecting the full prose catalog. */
function preferCompactToolCatalogForTier(sizeTier) {
return sizeTier === 'tiny' || sizeTier === 'small';
}
/** Prefer compact tool catalog when prefill is crowded or full catalog won't fit. */
function shouldPreferCompactToolCatalog({
contextTokens,
basePromptChars,
historyChars = 0,
userMessageChars = 0,
fullToolPromptChars = 0,
sizeTier = 'large',
}) {
if (preferCompactToolCatalogForTier(sizeTier)) return true;
const consumed = basePromptChars + historyChars + userMessageChars;
const prefillPressure = contextTokens > 0 ? consumed / contextTokens : 0;
const reservedTokens = Math.floor(contextTokens * 0.22) + 512;
const remainingChars = Math.max(0, (contextTokens - reservedTokens) * TOOL_PROMPT_CHARS_PER_TOKEN - consumed);
return prefillPressure > 0.35 || (fullToolPromptChars > 0 && fullToolPromptChars > remainingChars);
}
function buildBudgetProportionalToolPrompt({
contextTokens,
basePromptChars,
historyChars = 0,
userMessageChars = 0,
toolPrompt = '',
compactToolParts = null,
compactToolPrompt = '',
minGenerationReserve = 512,
maxToolBudgetPct = 0.35,
maxToolBudgetTokens = 4096,
agentMode = false,
agentMinToolPromptChars = AGENT_MIN_TOOL_PROMPT_CHARS,
preferCompactCatalog = false,
}) {
const tier0PartCount = (Array.isArray(compactToolParts) && compactToolParts._tier0PartCount) || AGENT_TOOL_TIER0_PART_COUNT;
const fullToolTokens = Math.ceil((toolPrompt?.length || 0) / TOOL_PROMPT_CHARS_PER_TOKEN);
const minToolChars = agentMode ? Math.max(0, agentMinToolPromptChars) : 0;
const reservedToolTokens = agentMode
? Math.min(fullToolTokens, Math.max(Math.floor(minToolChars / TOOL_PROMPT_CHARS_PER_TOKEN), Math.floor(contextTokens * 0.22)))
: 0;
const consumedTokens = Math.ceil((basePromptChars + historyChars + userMessageChars) / TOOL_PROMPT_CHARS_PER_TOKEN);
const promptBudgetTokens = Math.max(256, contextTokens - minGenerationReserve - consumedTokens - reservedToolTokens);
const maxToolTokens = agentMode
? Math.max(reservedToolTokens, Math.min(Math.floor(promptBudgetTokens * maxToolBudgetPct), maxToolBudgetTokens))
: Math.min(Math.floor(promptBudgetTokens * maxToolBudgetPct), maxToolBudgetTokens);
let maxToolChars = Math.floor(maxToolTokens * TOOL_PROMPT_CHARS_PER_TOKEN);
const parts = Array.isArray(compactToolParts) && compactToolParts.length > 0
? compactToolParts
: (compactToolPrompt ? [compactToolPrompt] : []);
if (!preferCompactCatalog && toolPrompt && fullToolTokens <= maxToolTokens) {
return { prompt: toolPrompt, mode: 'full', budgetTokens: maxToolTokens, usedTokens: fullToolTokens, tier0Ok: true };
}
if (parts.length > 0 && preferCompactCatalog) {
const built = parts.join('');
const tier0Ok = !agentMode || (built.includes('browser_navigate') && built.includes('browser_snapshot'));
return {
prompt: built,
mode: 'compact-all',
budgetTokens: maxToolTokens,
partsUsed: parts.length,
usedTokens: Math.ceil(built.length / TOOL_PROMPT_CHARS_PER_TOKEN),
tier0Ok,
reservedToolTokens,
};
}
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), tier0Ok: !agentMode };
}
let built = '';
let partsUsed = 0;
const headerPart = parts[0] || '';
const tier0End = agentMode ? Math.min(tier0PartCount, parts.length) : 0;
if (agentMode && tier0End > 0) {
for (let i = 0; i < tier0End; i++) {
built += parts[i];
partsUsed++;
}
maxToolChars = Math.max(maxToolChars, built.length);
}
for (let i = tier0End; i < parts.length; i++) {
const part = parts[i];
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)) {
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';
}
const tier0Ok = !agentMode || (built.includes('browser_navigate') && built.includes('browser_snapshot'));
return {
prompt: built,
mode: agentMode && tier0End > 0 ? 'agent-tier0' : 'budget-parts',
budgetTokens: maxToolTokens,
partsUsed,
usedTokens: Math.ceil(built.length / TOOL_PROMPT_CHARS_PER_TOKEN),
tier0Ok,
reservedToolTokens,
};
}
/**
* 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),
},
};
}
};
}
// Default session system entry — agent mode; per-request chat() uses resolveAgentMode().baseSystemPrompt
const SYSTEM_PROMPT = getAgentSystemPrompt();
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;