-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsession.cc
More file actions
2758 lines (2446 loc) · 133 KB
/
Copy pathsession.cc
File metadata and controls
2758 lines (2446 loc) · 133 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
#include "session.h"
#include "tokens.h"
#include "mtp.h"
#include "output.h"
#include "server.h"
#include "model.h"
#include "signals.h"
#include "parsers.h"
#include "filesystem.h"
#include "network.h"
#include "tools.h"
#include "token_generator.h"
#include "tool_executor.h"
#include "session_utils.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
#include <map>
// From main.cc
extern std::string g_model_path;
#include <cstdlib>
#include <chrono>
#include <signal.h>
#include <cctype>
#include <set>
#include <functional>
#include <iomanip>
#include <unistd.h>
#include <ctime>
#include <sys/ioctl.h>
#include <sys/select.h>
#include <sys/stat.h>
#include <termios.h>
// --- Readline Headers ---
#include <readline/readline.h>
#include <readline/history.h>
// Internal readline variable: suppress _rl_callback_newline() after accept.
extern "C" { extern void (*rl_linefunc)(char *); }
// --- Custom readline function: insert literal newline (Ctrl+J) ---
static int rl_insert_newline(int /*count*/, int /*key*/) {
rl_insert_text("\n");
return 0;
}
using namespace std;
using namespace Tokens;
// Forward declarations for functions defined in main.cc
extern void diag(const string& msg, const char* color);
extern bool is_debug;
extern ofstream chat_log;
extern ofstream token_log;
extern bool honest_speed;
extern int chatbot_mode;
extern std::ofstream tps_log;
extern std::string g_dummy_thought_text;
// HOME is declared as extern std::string HOME in network.h
// --- Helper to trim leading/trailing whitespace ---
static string trim(const string& s) {
size_t start = s.find_first_not_of(" \t\r\n");
if (start == string::npos) return "";
size_t end = s.find_last_not_of(" \t\r\n");
return s.substr(start, end - start + 1);
}
// --- Command table: single source of truth for dispatch, alias blocking, and help ---
enum class Cmd : int { NONE, QUIT, CLEAR, RESET, REINCARNATE, CONTINUE, SAVE, RESTORE, DELETE, HELP, UNDO };
enum class ArgType { NONE, PATH };
static const struct CmdInfo {
const char* name;
Cmd cmd;
ArgType arg;
const char* description;
} g_commands[] = {
{ "quit", Cmd::QUIT, ArgType::PATH, "Save session and exit; /quit <path> does a named save with fast cache" },
{ "exit", Cmd::QUIT, ArgType::PATH, nullptr }, // alias, not shown in help
{ "clear", Cmd::CLEAR, ArgType::NONE, "Clear context (auto-saves first to log/<N>-clear.save)" },
{ "undo", Cmd::UNDO, ArgType::NONE, "Interactive undo: select a checkpoint to restore to" },
{ "continue", Cmd::CONTINUE, ArgType::NONE, "Resume generation after interruption" },
{ "reset", Cmd::RESET, ArgType::NONE, "Reset terminal, loop detector, and web search" },
{ "reincarnate", Cmd::REINCARNATE,ArgType::NONE, "Compose new prompt in ~/.config/lim/userprompt, then restart (auto-saves first)" },
{ "save", Cmd::SAVE, ArgType::PATH, "Save session state to <path>.save (default: log/<N>.save)" },
{ "load", Cmd::RESTORE, ArgType::PATH, "Load session from <path>.save (must be used after /clear); --checkpoints skips the fast cache" },
{ "delete", Cmd::DELETE, ArgType::PATH, "Delete <path>.save and its fast restore cache" },
{ "help", Cmd::HELP, ArgType::NONE, "Show this help message" },
};
// --- Load aliases from ~/.lim_aliases ---
static map<string, string> load_aliases() {
// Built-in commands that cannot be overridden by aliases.
static set<string> builtin_commands;
[[maybe_unused]] static bool init_builtin = ([](){
for (const auto& c : g_commands) {
if (c.name) builtin_commands.insert(c.name);
}
return true;
})();
map<string, string> aliases;
string path = string(HOME) + "/.lim_aliases";
ifstream in(path);
if (!in.is_open()) return aliases;
string line;
while (getline(in, line)) {
// Skip comments and blank lines
string trimmed = trim(line);
if (trimmed.empty() || trimmed[0] == '#') continue;
size_t eq = trimmed.find('=');
if (eq == string::npos) continue;
string key = trim(trimmed.substr(0, eq));
string value = trim(trimmed.substr(eq + 1));
if (!key.empty() && key[0] == '/') {
// Strip leading '/' to get the command name
string cmd = key.substr(1);
if (builtin_commands.count(cmd)) {
cerr << "Warning: alias '" << key << "' shadows a built-in command, ignored." << endl;
} else {
aliases[key] = value;
}
} else if (!key.empty()) {
cerr << "Warning: alias key '" << key << "' ignored: update "+HOME+"/.lim_aliases to use '/key=value' syntax." << endl;
}
}
return aliases;
}
// --- Safe Multiline History Handlers ---
static void load_history_safe(const char* filename) {
ifstream in(filename);
string line;
while (getline(in, line)) {
for (char& c : line) { if (c == '\x1E') c = '\n'; }
add_history(line.c_str());
}
}
static void save_history_safe(const char* filename, const string& input) {
ofstream out(filename, ios::app);
string enc = input;
for (char& c : enc) { if (c == '\n') c = '\x1E'; }
out << enc << "\n";
}
// --- Checkpoint selection prompt helpers (shared by /undo and /load) ---
// Format one checkpoint for the selection prompt:
// "<prompt truncated to 120 chars> (<n_past> tokens)".
static string checkpoint_label(const PromptCheckpoint& cp) {
string label = cp.prompt.empty() ? "(empty)" : cp.prompt;
if (label.size() > 120) label = label.substr(0, 120) + "...";
return label + " (" + to_string(cp.n_past) + " tokens)";
}
// Extract the target n_past from the "(N tokens)" suffix of the user's
// selection at the selection prompt. Since n_past is unique per checkpoint,
// this works even when prompts are truncated or duplicated. Returns true and
// sets *n_past on success.
static bool parse_checkpoint_selection(const string& input, int* n_past) {
size_t paren_open = input.rfind('(');
size_t paren_close = input.rfind(')');
if (paren_open == string::npos || paren_close <= paren_open) return false;
try {
*n_past = std::stoi(input.substr(paren_open + 1, paren_close - paren_open - 1));
return true;
} catch (...) {
return false;
}
}
// --- Helper to build context-limit diagnostic string ---
static string context_limit_diag(int n_past, int last_n_past, size_t needed) {
if (n_past == last_n_past) return "";
ostringstream oss;
oss << " (n_past=" << n_past << " + " << needed << ", last_n_past=" << last_n_past << ")";
return oss.str();
}
// --- One-time probe: does this tokenizer space-prefix raw text fragments? ---
// Vocabularies following the SPM convention (Llama, Qwen, etc.; the
// add_space_prefix setting inside llama.cpp) prepend a space to the first raw
// text fragment of a text and to every raw text fragment following a special
// token, so the first word token of each fragment carries a leading space
// (e.g. " system"). The public API does not expose the setting, so probe the
// tokenizer once: encoding "ab12" (which contains no space) yields a first
// token whose piece starts with a space iff the vocabulary space-prefixes.
// detokenize_tracker_to_text (the one-time reconstruction fallback of
// benchmark modes 1/2) uses this to keep the detokenize/re-tokenize round-trip
// lossless (the tokenizer would otherwise re-add the prefix on top of the
// space the detokenized pieces render).
static bool vocab_space_prefixes(const llama_vocab* vocab) {
static bool cached = [](const llama_vocab* v) {
vector<llama_token> toks = common_tokenize(v, "ab12", false, true);
if (toks.empty()) return false;
string piece = common_token_to_piece(v, toks[0], true);
return !piece.empty() && piece.front() == ' ';
} (vocab);
return cached;
}
// --- Benchmark-mode canonical conversation text --------------------------
// Modes 1 (standard chatbot) and 2 (llama-server emulation) maintain
// SessionState::conversation_text -- the fully templated conversation text a
// text-based client would hold -- so each turn appends to it instead of
// detokenizing the cached KV. Mode 0 (normal operation) never touches it.
static bool maintains_conversation_text() {
return chatbot_mode == 1 || chatbot_mode == 2;
}
// Forward declarations for save helpers defined after the class.
static string save_diag(size_t n_checkpoints, size_t n_tokens);
static bool save_session_with_header(const vector<llama_token>& tokens, const string& path,
bool write_v1, llama_context* ctx,
const vector<PromptCheckpoint>* checkpoints, int session_num);
// ============================================================================
// ChatSession class: orchestrates the main chat turn loop
// ============================================================================
class ChatSession {
public:
ChatSession(
llama_context* ctx,
const llama_vocab* vocab,
llama_sampler* smpl,
llama_batch& batch,
int& n_past,
const llama_context_params& cparams,
const vector<llama_token>& system_tokens,
const string& system_prompt_text,
bool use_dummy_thought,
SessionState& state
) : ctx_(ctx), vocab_(vocab), smpl_(smpl), batch_(batch),
n_past_(n_past), cparams_(cparams), system_tokens_(system_tokens),
system_prompt_text_(system_prompt_text),
use_dummy_thought_(use_dummy_thought), state_(state),
g_auto_continue_depth_(0)
{
const char* cur_tty = ttyname(STDIN_FILENO);
prev_tty_ = cur_tty ? string(cur_tty) : "";
}
bool run();
private:
using Command = Cmd;
// Parsed command and optional arguments
Command last_cmd_ = Command::NONE;
string save_prefix_;
string restore_path_;
string delete_path_;
bool restore_checkpoints_ = false; // /load <path> --checkpoints
// Track if the previous turn was a manual save, so /quit can skip redundant auto-save
bool prev_was_save_ = false;
// Track if we already logged assistant output this turn (via process_tool_call),
// so the main loop doesn't duplicate it.
bool assistant_logged_this_turn_ = false;
// Last non-empty user input, used as checkpoint label for tool-call turns
string last_user_input_;
// Readline history length right after loading .lim_history at startup.
// Marks the end of A (persistent) entries in readline history.
int persistent_history_len_ = 0;
// File size of .lim_history after loading A at startup. Used to truncate
// back to this point at /quit before rewriting surviving C entries.
long history_file_size_at_startup_ = 0;
// Number of user inputs actually added to history since last restore/undo.
// Only incremented when add_history() actually adds an entry (not skipped).
int c_count_since_restore_ = 0;
// --- Helper methods (extracted from lambdas) ---
vector<llama_token> tokenize(string text) {
return common_tokenize(ctx_, text, false, true);
}
void repopulate_history() {
using_history();
// Remove stale B entries before pushing fresh checkpoint prompts.
int stale = history_length - persistent_history_len_;
if (stale > 0) pop_history(stale);
for (const auto& cp : state_.prompt_checkpoints) {
if (!cp.prompt.empty()) {
add_history(cp.prompt.c_str());
}
}
c_count_since_restore_ = 0;
}
// Pop the last N entries from readline history.
void pop_history(int n) {
while (n > 0) {
int len = history_length;
if (len <= 0) break;
remove_history(len - 1);
n--;
}
}
// Restore saved B and C entries to readline history (both saved oldest-first;
// add_history appends at the newest end, so chronological order is preserved).
// Re-count the C entries actually added so the /quit flush persists them to
// disk after a cancelled undo (zeroing them here would drop C from .lim_history).
void restore_saved_history(const vector<string>& b, const vector<string>& c) {
for (const auto& s : b) add_history(s.c_str());
c_count_since_restore_ = 0;
for (const auto& s : c) {
int before = history_length;
add_history(s.c_str());
if (history_length > before) c_count_since_restore_++;
}
}
// Flush .lim_history to disk: truncate back to the persistent baseline (A),
// then append only the surviving C entries. Updates the tracked file size
// so subsequent calls treat these entries as the new A.
void flush_history(const char* history_file) {
FILE* f = fopen(history_file, "r+");
if (f) {
ftruncate(fileno(f), history_file_size_at_startup_);
fclose(f);
}
for (const auto& s : collect_recent_user_inputs()) {
save_history_safe(history_file, s);
}
struct stat st;
if (stat(history_file, &st) == 0) {
history_file_size_at_startup_ = st.st_size;
}
}
// Increment the session number and reopen all log files for the new
// session (same layout/headers as startup: see open_session_logs in
// session_utils.cc). Returns the new session number.
int bump_session() {
state_.log_index++;
int idx = state_.log_index;
chat_log.close();
token_log.close();
tps_log.close();
if (!open_session_logs(idx)) {
diag("Failed to open log files for session #" + to_string(idx), "\033[31m");
}
return idx;
}
void log_entry(const string& role, const string& text) {
if (chat_log.is_open()) {
string clean_text = text;
vector<string> tags_to_remove = {FUNC_START, FUNC_END};
// Strip model-specific turn markers from the log
if (!g_model_tokens.user_turn_start.text.empty()) tags_to_remove.push_back(g_model_tokens.user_turn_start.text);
if (!g_model_tokens.assistant_turn_start.text.empty()) tags_to_remove.push_back(g_model_tokens.assistant_turn_start.text);
if (!g_model_tokens.system_turn_start.text.empty()) tags_to_remove.push_back(g_model_tokens.system_turn_start.text);
if (!g_model_tokens.turn_end.text.empty()) tags_to_remove.push_back(g_model_tokens.turn_end.text);
strip_tags(clean_text, tags_to_remove); while (!clean_text.empty() && isspace(clean_text.back())) clean_text.pop_back();
chat_log << "=== " << role << " ===\n" << clean_text << "\n\n";
chat_log.flush();
}
}
// Auto-save the current state to log/<N>-clear.save before clearing,
// undoing, or reincarnating so nothing is truly lost.
void autosave_before_clear() {
string autosave_path = LIM_LOG_DIR + "/" + to_string(state_.log_index) + "-clear.save";
bool ok = save_session_with_header(state_.all_context_tokens, autosave_path, false, nullptr, &state_.prompt_checkpoints, state_.log_index);
if (!ok) {
diag("Auto-save failed: could not write " + autosave_path, "\033[33m");
} else {
diag("Auto-saved to " + autosave_path + " (" + save_diag(state_.prompt_checkpoints.size(), state_.all_context_tokens.size()) + ")", "\033[35m");
}
}
// Collect the C entries (user inputs since last restore/clear), oldest first.
vector<string> collect_recent_user_inputs() {
vector<string> saved_c;
for (int i = c_count_since_restore_ - 1; i >= 0; i--) {
HIST_ENTRY* he = history_get(history_length - i);
if (he) saved_c.push_back(he->line);
}
return saved_c;
}
// Stream the user's input to the browser as a blue code block.
void stream_user_input_html(const string& input) {
if (should_output_to_browser() && pipe_fd >= 0) {
string user_html = "\n\n<div style=\"color: #79c0ff;\"><pre><code>" + html_escape_for_browser(input) + "</code></pre></div>\n\n";
stream_html(user_html);
}
}
// Text form of a new user turn: optional turn-end close (if the previous
// turn was interrupted) + user turn + assistant prefill. Takes the flag
// explicitly so the text can be built before or after the token build
// (build_new_user_turn_tokens consumes state_.prev_was_interrupted).
static string new_user_turn_text(bool prev_was_interrupted, const string& input) {
string text = prev_was_interrupted ? g_model_tokens.turn_end.text : "";
text += build_user_assistant_turn_text(input);
return text;
}
// Build tokens for a new user turn: optional turn-end close (if the
// previous turn was interrupted) + user turn + assistant prefill.
vector<llama_token> build_new_user_turn_tokens(const string& input) {
string turn_close_str = state_.prev_was_interrupted ? g_model_tokens.turn_end.text : "";
state_.prev_was_interrupted = false;
vector<llama_token> tokens;
if (!turn_close_str.empty()) {
auto close_tok = common_tokenize(ctx_, turn_close_str, false, true);
tokens.insert(tokens.end(), close_tok.begin(), close_tok.end());
}
auto user_ass = build_user_assistant_turn(ctx_, input);
tokens.insert(tokens.end(), user_ass.begin(), user_ass.end());
return tokens;
}
// --- Canonical conversation text (benchmark modes 1/2 only) -----------
// Detokenize a cached token sequence back to conversation text, token by
// token. One-time reconstruction fallback for events that discard the
// text (session start, /undo, /load, tool rollback) -- steady-state turns
// append to the maintained text and never pay this. For space-prefixing
// vocabularies, the first content token of every fragment following a
// special token (or the start of text) carries an encoding space that
// common_token_to_piece renders as a literal; re-tokenization would
// re-add its own prefix on top, so strip exactly one leading space from
// those fragments to keep the round-trip lossless (mirrors is_prev_special
// in the tokenizer).
string detokenize_tracker_to_text(const vector<llama_token>& toks) {
bool space_prefixes = vocab_space_prefixes(vocab_);
string text;
bool prev_was_special = true; // start of text is a special boundary
for (llama_token tok : toks) {
bool is_special = (llama_vocab_get_attr(vocab_, tok) &
(LLAMA_TOKEN_ATTR_CONTROL | LLAMA_TOKEN_ATTR_USER_DEFINED | LLAMA_TOKEN_ATTR_UNKNOWN)) != 0;
string piece = common_token_to_piece(vocab_, tok, true);
if (!is_special && prev_was_special && space_prefixes &&
!piece.empty() && piece.front() == ' ') {
piece.erase(0, 1);
}
text += piece;
prev_was_special = is_special;
}
return text;
}
// Should a one-pass re-tokenization of the canonical conversation text
// prepend BOS? Only when the cached stream started with BOS AND the BOS
// detokenizes to an empty piece: if it has a visible piece, that piece is
// already in the text and add_bos=true would double it (degenerating the
// prefix match to 0); without add_bos the literal marker parses back to
// the BOS token instead. (build_system_prompt_tokens likewise leaves the
// BOS decision to common_tokenize(add_bos=true).)
bool should_add_bos(const vector<llama_token>& toks) {
const llama_token bos = llama_vocab_bos(vocab_);
if (toks.empty() || toks[0] != bos) return false;
return common_token_to_piece(vocab_, bos, true).empty();
}
// New user turn text, consuming state_.prev_was_interrupted exactly like
// build_new_user_turn_tokens (used by the mode 1/2 branches, which feed
// the turn themselves instead of going through feed_user_message).
string build_new_user_turn_text(const string& input) {
bool was_interrupted = state_.prev_was_interrupted;
state_.prev_was_interrupted = false;
return new_user_turn_text(was_interrupted, input);
}
// Full conversation text for a benchmark turn: the canonical text plus
// the new turn (steady state, pure append), or a one-time detokenize
// reconstruction of the tracker when the text was discarded (session
// start, /undo, /load, tool rollback).
string build_full_conversation_text(const vector<llama_token>& tracker,
const string& new_turn_text) {
if (!state_.conversation_text.empty()) {
return state_.conversation_text + new_turn_text;
}
return detokenize_tracker_to_text(tracker) + new_turn_text;
}
// --- Rollback instrumentation (correction.md 4) -----------------------
// Written to BOTH stderr and chat_log so the record survives a context
// clobber. Gated on is_debug (LIM_DEBUG=1). `path` is "correction" or "undo".
void log_rollback(const char* path, int n_past_before, long target_pos,
bool seq_rm_ok, int n_past_after) {
if (!is_debug) return;
long delta = (long)n_past_before - target_pos;
ostringstream oss;
oss << "[ROLLBACK path=" << path << "]\n"
<< " n_past_before = " << n_past_before << "\n"
<< " target_pos = " << target_pos << "\n"
<< " delta = " << delta << "\n"
<< " idx = " << state_.tool_correction_checkpoint_idx << "\n"
<< " stack_offset = " << state_.checkpoint_stack_offset << "\n"
<< " n_checkpoints = " << state_.prompt_checkpoints.size() << "\n"
<< " all_ctx_size = " << state_.all_context_tokens.size() << "\n"
<< " --- after ---\n"
<< " n_past_after = " << n_past_after << "\n"
<< " seq_rm_ok = " << (seq_rm_ok ? "true" : "false") << "\n";
string s = oss.str();
cerr << s;
if (chat_log.is_open()) { chat_log << s; chat_log.flush(); }
}
// Log a tool_correction_n_past assignment so we can see when it was last
// set and to what value (correction.md 4). idx_was is the checkpoint index
// at the moment of assignment.
void log_tc_npast_set() {
if (!is_debug) return;
ostringstream oss;
oss << "[TC_NPAST_SET] n_past=" << n_past_
<< " idx_was=" << state_.tool_correction_checkpoint_idx << "\n";
string s = oss.str();
cerr << s;
if (chat_log.is_open()) { chat_log << s; chat_log.flush(); }
}
// Roll back to the tool-correction checkpoint (removes bad call + any
// correction tokens). Returns 0 if seq_rm succeeded, 1 if the KV cache was
// cleared and re-decoded, -1 on failure (caller should eject to prompt).
int rollback_to_tool_checkpoint(bool eject_on_failure) {
llama_memory_t mem = llama_get_memory(ctx_);
int n_past_before = n_past_;
long target_pos = state_.tool_correction_n_past;
llama_memory_rs_checkpoint_restore(mem, 0, (uint32_t)state_.tool_correction_checkpoint_idx);
llama_memory_rs_checkpoint_prune(mem, 0, (uint32_t)state_.tool_correction_checkpoint_idx);
bool rm_ok = llama_memory_seq_rm(mem, 0, state_.tool_correction_n_past, -1);
if (rm_ok) {
n_past_ = state_.tool_correction_n_past;
state_.all_context_tokens.resize(state_.tool_correction_n_past);
// Tracker rewound: the canonical conversation text no longer
// describes it -- invalidate (benchmark modes 1/2 rebuild from the
// tracker on the next turn).
state_.conversation_text.clear();
// Instant rollback leaves the MTP mirror ahead of the main
// context (its hidden-state bookkeeping can't be rolled back).
// Drafting stops until the next /clear or a re-decode.
if (g_mtp) g_mtp->invalidate("mirror stale after tool-correction rollback");
log_rollback("correction", n_past_before, target_pos, true, n_past_);
return 0;
}
diag("System: Correction rollback failed, re-decoding...", "\033[33m");
llama_memory_clear(mem, true);
if (g_mtp) g_mtp->clear(); // re-decode rebuilds the mirror via the hook
n_past_ = 0;
if (!feed_tokens_impl(state_.all_context_tokens)) {
diag("Correction restore failed. Type /clear to reset.", "\033[31m");
log_rollback("correction", n_past_before, target_pos, false, n_past_);
if (eject_on_failure) state_.auto_continue = false;
return -1;
}
n_past_ = state_.tool_correction_n_past;
state_.all_context_tokens.resize(n_past_);
// Tracker rewound (via clear + re-decode): invalidate the canonical
// conversation text, same as the seq_rm path above.
state_.conversation_text.clear();
log_rollback("correction", n_past_before, target_pos, false, n_past_);
return 1;
}
bool feed_tokens_impl(const vector<llama_token>& toks) {
batch_.n_tokens = 0;
for (size_t i = 0; i < (int)toks.size(); i++) {
if (stop_generation) return false;
common_batch_add(batch_, toks[i], n_past_++, {0}, (i == (int)toks.size() - 1));
if (batch_.n_tokens == (int)cparams_.n_batch && i != (int)toks.size() - 1) {
if (!handle_llama_decode_error(ctx_, batch_)) { sync_n_past(ctx_, n_past_); return false; }
batch_.n_tokens = 0;
}
}
if (batch_.n_tokens > 0) {
if (!handle_llama_decode_error(ctx_, batch_, "KV Cache Exhausted. Type '/clear' to reset.", false)) {
sync_n_past(ctx_, n_past_);
return false;
}
sync_n_past(ctx_, n_past_);
}
// Track all tokens fed into context for save/restore
state_.all_context_tokens.insert(state_.all_context_tokens.end(), toks.begin(), toks.end());
return true;
}
// Reload the system prompt from disk (prompt file + localprompt + cwd + date/time).
// Returns true on success, false if the prompt file is missing (old tokens AND
// old text kept -- the pair must stay in lockstep for conversation_text).
bool reload_system_prompt() {
string system_prompt;
if (!load_system_prompt_text(system_prompt)) return false; // Keep old pair.
system_tokens_ = build_system_prompt_tokens(ctx_, system_prompt);
system_prompt_text_ = system_prompt;
return true;
}
void clear_context() {
llama_memory_clear(llama_get_memory(ctx_), true);
// Reset the MTP mirror with the main cache: the re-fed system prompt
// rebuilds the mirror via the mirror hook, re-arming the speculator.
if (g_mtp) g_mtp->clear();
n_past_ = 0;
// Reset context token tracker to empty; feed_tokens_impl will rebuild it.
state_.all_context_tokens.clear();
state_.prompt_checkpoints.clear();
state_.file_cache.clear();
// Reset the current directory to the initial value so no memory of the last session persists.
// Done before reload_system_prompt() so getcwd() reflects the initial directory.
{
chdir(INITIAL_CWD.c_str());
ofstream cwd_file(HOME + "/.cwd");
if (cwd_file.is_open()) {
cwd_file << INITIAL_CWD << endl;
cwd_file.close();
}
}
// Reload system prompt from disk to pick up any edits + fresh timestamp.
if (!reload_system_prompt()) {
diag("Prompt file not found; reusing cached system prompt.", "\033[33m");
}
feed_tokens_impl(system_tokens_);
// Benchmark modes 1/2: re-seed the canonical conversation text to
// exactly what was just fed (an empty prompt means no system turn,
// which is the empty/invalid text).
if (maintains_conversation_text()) {
state_.conversation_text = build_system_turn_text(system_prompt_text_);
}
// Reset sampler state (penalty history, RNG) for a fresh start
llama_sampler_reset(smpl_);
}
void reset_session_state() {
state_.correction_attempted_this_turn = false;
NetworkTools().reset_search();
NetworkTools::reset_context_usage();
g_browser_warning_suppressed = false;
state_.partial_tool_text.clear();
state_.tool_interrupt_pending = false;
}
// --- Main loop methods ---
string get_user_input();
Command handle_command(const string& input);
bool feed_user_message(const string& input);
TokenGenerator::Result generate_response(bool is_correction_gen = false);
bool process_tool_call();
bool handle_reincarnate_completion();
// --- Member variables ---
llama_context* ctx_;
const llama_vocab* vocab_;
llama_sampler* smpl_;
llama_batch& batch_;
int& n_past_;
const llama_context_params& cparams_;
vector<llama_token> system_tokens_;
// The text system_tokens_ was built from (build_system_prompt_tokens).
// Kept in lockstep with the tokens so benchmark modes 1/2 can seed
// state_.conversation_text after a clear/restore without re-reading disk
// (and so "prompt file not found, reusing cached prompt" keeps the old
// pair instead of mixing new text with old tokens).
string system_prompt_text_;
bool use_dummy_thought_;
SessionState& state_;
map<string, string> aliases_;
string prev_tty_;
int g_auto_continue_depth_;
// Generation result shared between generate_response and process_tool_call
TokenGenerator::Result gen_result_;
string generated_text_;
int t_count_;
double elapsed_;
bool was_mid_tool_call_;
int max_auto_continue_;
};
// --- get_user_input: readline callback interface with Ctrl+J newline support ---
string ChatSession::get_user_input() {
string user_input = "";
// If stdin is not a terminal (piped input), read lines directly.
// Empty lines are skipped; EOF returns "/quit" to exit cleanly.
if (!isatty(STDIN_FILENO)) {
if (state_.first_turn_done && state_.last_t_count > 0) {
diag_speed(state_.last_n_past, cparams_.n_ctx, state_.last_t_count,
state_.last_elapsed, state_.last_decode_time);
}
string line;
while (getline(cin, line)) {
if (!line.empty()) return line;
}
return "/quit"; // EOF
}
if (!state_.auto_continue) {
// Print Speed from previous generation right before >>> (skip first turn).
// Deferred here so we have all the information we need.
if (state_.first_turn_done && state_.last_t_count > 0) {
// Ensure the diagnostic appears on its own line.
consoleEnsureNewline();
diag_speed(state_.last_n_past, (int)cparams_.n_ctx, state_.last_t_count,
state_.last_elapsed, state_.last_decode_time, true);
} else if (!state_.first_turn_done && should_output_to_browser()) {
// First turn: show context position while user types their prompt.
double context_percent = (n_past_ / (double)cparams_.n_ctx) * 100.0;
ostringstream oss;
oss << n_past_ << " (" << (int)context_percent << "%)";
stream_speed(oss.str());
}
const char* main_p = "\001\033[1;96m\002>>> \001\033[96m\002";
// Bind Ctrl+J to insert a literal newline instead of accepting the line.
// In callback mode, \r (Enter/Return) remains bound to accept-line (submit).
// rl_bind_key('\n') works in xterm but not VS Code (pty translates \n -> \r).
// For VS Code, the extension sends \x1c (File Separator) for Ctrl+J.
rl_bind_key('\n', rl_insert_newline);
rl_bind_key('\x1c', rl_insert_newline); // File separator = Ctrl+J in VS Code
bool input_complete = false;
string captured_line;
// Callback is invoked by readline when a complete line is available.
// rl_done is unreliable here because _rl_callback_newline() resets it
// to 0 before rl_callback_read_char() returns, so we use static
// variables shared with the callback.
static string g_captured_line;
static bool g_input_complete = false;
g_captured_line.clear();
g_input_complete = false;
auto storing_callback = [](char* line) {
g_captured_line = line ? line : "";
g_input_complete = true;
// Suppress _rl_callback_newline() so readline doesn't redraw the
// prompt after accepting the line.
rl_linefunc = nullptr;
};
// Set screen size BEFORE installing the handler so readline knows
// the terminal width from the start. This avoids needing
// rl_forced_update_display() afterward (which would duplicate the prompt).
// SIGWINCH resizes during the session are handled by readline internally.
{
struct winsize ws;
if (ioctl(0, TIOCGWINSZ, &ws) == 0 && ws.ws_col > 0) {
rl_set_screen_size(ws.ws_row, ws.ws_col);
}
}
rl_callback_handler_install(main_p, storing_callback);
// Save readline's raw termios so we can restore it after Ctrl+Z / fg.
// The shell restores cooked mode during suspend; on resume we need to
// put the terminal back into readline's expected raw-mode state.
struct termios saved_raw_tios{};
tcgetattr(STDIN_FILENO, &saved_raw_tios);
// Event loop: poll for input with select(), check for interrupts
while (!input_complete) {
if (g_was_interrupted) {
break;
}
// After Ctrl+Z / fg, SIGCONT sets g_was_resumed. The shell has
// restored cooked terminal mode, so restore readline's raw settings.
if (g_was_resumed) {
g_was_resumed = 0;
tcsetattr(STDIN_FILENO, TCSANOW, &saved_raw_tios);
rl_forced_update_display();
}
fd_set fds;
FD_ZERO(&fds);
FD_SET(0, &fds); // stdin
// Use pselect with an empty signal mask so that SIGCONT (from fg)
// and SIGINT (Ctrl+C) wake us immediately. Blocks indefinitely --
// no timeout needed since signals provide the wakeup.
sigset_t empty_mask;
sigemptyset(&empty_mask);
int ret = pselect(1, &fds, nullptr, nullptr, nullptr, &empty_mask);
if (ret < 0) {
if (errno == EINTR) continue;
break;
}
if (ret > 0 && FD_ISSET(0, &fds)) {
rl_callback_read_char();
}
// Check our static flag set by the callback instead of rl_done,
// which gets reset to 0 by _rl_callback_newline() inside
// rl_callback_read_char() before we can observe it.
if (g_input_complete) {
input_complete = true;
}
}
rl_callback_handler_remove();
rl_unbind_key('\n'); // Restore default \n binding
// _rl_callback_newline() was suppressed (rl_linefunc = nullptr), so
// readline left the cursor at the end of the accepted input.
captured_line = g_captured_line;
if (!captured_line.empty()) {
user_input = captured_line;
if (!user_input.empty()) {
save_history_safe(".lim_history", user_input);
int before = history_length;
add_history(user_input.c_str());
if (history_length > before) c_count_since_restore_++;
}
} else {
// EOF (Ctrl+D on empty line) -- treat as interrupt/break
g_was_interrupted = 0;
}
}
// Strip leading whitespace so commands like " /quit" work.
{
size_t start = user_input.find_first_not_of(" \t");
if (start != string::npos) {
user_input = user_input.substr(start);
} else if (!user_input.empty()) {
// Input is entirely whitespace -- treat as empty.
user_input.clear();
}
}
// Alias expansion: if user_input matches an alias key, replace with its value (single-level only).
{
auto alias_it = aliases_.find(user_input);
if (alias_it != aliases_.end()) {
user_input = alias_it->second;
}
}
return user_input;
}
// --- handle_command: detect which command the input represents ---
// Commands must be prefixed with '/'. /save, /load, and /undo accept optional arguments.
// Match 'rest' (input after '/') against the command table: the exact command
// name, or the name followed by whitespace separating it from its argument.
// Returns the matching table entry, or nullptr if no command name matches.
static const CmdInfo* match_command(const string& rest) {
for (const auto& c : g_commands) {
if (!c.name) continue;
int len = (int)strlen(c.name);
if (rest.size() == (size_t)len) {
if (rest == c.name) return &c;
} else if (rest.size() > (size_t)len && isspace(rest[len])) {
if (rest.substr(0, len) == c.name) return &c;
}
}
return nullptr;
}
ChatSession::Command ChatSession::handle_command(const string& input) {
if (input.empty() || input[0] != '/') return Command::NONE;
// Strip the leading '/'
string rest = input.substr(1);
const CmdInfo* c = match_command(rest);
if (!c) return Command::NONE;
// Parse optional argument.
string arg = trim(rest.substr((int)strlen(c->name)));
switch (c->arg) {
case ArgType::PATH:
save_prefix_.clear();
restore_path_.clear();
delete_path_.clear();
restore_checkpoints_ = false;
if (c->cmd == Cmd::SAVE) save_prefix_ = arg;
if (c->cmd == Cmd::RESTORE) {
// Optional trailing flag: "/load <path> --checkpoints"
restore_checkpoints_ = strip_checkpoints_flag(arg);
restore_path_ = arg;
}
if (c->cmd == Cmd::DELETE) delete_path_ = arg;
if (c->cmd == Cmd::QUIT) save_prefix_ = arg;
return static_cast<Command>(c->cmd);
case ArgType::NONE:
save_prefix_.clear();
restore_path_.clear();
if (!arg.empty()) {
diag("/" + string(c->name) + " does not accept arguments", "\033[31m");
return Command::NONE;
}
return static_cast<Command>(c->cmd);
}
return Command::NONE;
}
// --- feed_user_message: construct and feed user message tokens ---
bool ChatSession::feed_user_message(const string& input) {
// If user provides regular input (not "continue"), clear any pending tool interrupt state.
if (!state_.auto_continue) state_.tool_interrupt_pending = false;
if (!state_.auto_continue) {
log_entry("USER", input);
stream_user_input_html(input);
}
// Build user turn + assistant prefill using model-type-aware token vectors.
// Read prev_was_interrupted BEFORE build_new_user_turn_tokens: it consumes
// the flag while tokenizing the turn-close, and the text form below needs it.
bool turn_was_closed = state_.prev_was_interrupted;
vector<llama_token> tokens = build_new_user_turn_tokens(input);
// Benchmark modes 1/2: text form of exactly what the feed below adds, so
// the canonical conversation text stays in lockstep with the tracker.
string turn_text;
if (maintains_conversation_text() && !state_.conversation_text.empty()) {
turn_text = new_user_turn_text(turn_was_closed, input);
}
// If using dummy thought, append the thinking block as content tokens.
if (use_dummy_thought_) {
string think_block = g_model_tokens.think_start + "\n" + g_dummy_thought_text + "\n" + g_model_tokens.think_end + "\n";
auto think_tok = common_tokenize(ctx_, think_block, false, true);
tokens.insert(tokens.end(), think_tok.begin(), think_tok.end());
if (!turn_text.empty()) turn_text += think_block;
}
if (n_past_ + (int)tokens.size() >= (int)cparams_.n_ctx) {
string ctx_diag = context_limit_diag(n_past_, state_.last_n_past, tokens.size());
diag("Context Limit Reached! Cannot process input" + ctx_diag + ". Type '/clear' to reset.", "\033[31m");
return false;
}
if (!feed_tokens_impl(tokens)) {
if (stop_generation) {
diag("Input Evaluation Interrupted", "\033[31m");
stop_generation = 0;
}
return false;
}
// The feed succeeded: keep the canonical text in lockstep (only when it
// is currently valid -- an empty text is rebuilt from the tracker by the
// next mode 1/2 turn instead of being appended to stale state).
if (!turn_text.empty()) state_.conversation_text += turn_text;
// Log user input tokens to token_log when debug is enabled
log_tokens("FEED USER_INPUT", tokens, ctx_);
return true;
}
// --- generate_response: invoke TokenGenerator and update state ---
TokenGenerator::Result ChatSession::generate_response(bool is_correction_gen) {
// Reset terminal color to default before LLM text starts printing.
// Readline draws the >>> prompt in cyan; without this reset, all LLM output
// would appear in cyan.
if (should_output_to_stdout()) {
cout << "\033[0m";
cout.flush();
// \033[0m is an escape sequence, not a newline.
// Don't change g_stdout_ended_with_newline - escape codes don't affect cursor position.
}
if (!state_.auto_continue) g_auto_continue_depth_ = 0;
// Reset sampler between user turns so the penalties ring buffer starts
// fresh. Only generated tokens are tracked (user input goes through
// feed_tokens_impl, not the sampler chain), so repetition penalties
// apply only to what the model itself produces this turn.
if (!state_.auto_continue) {
llama_sampler_reset(smpl_);
}
// Compute turn timeout from environment
static constexpr double DEFAULT_TURN_TIMEOUT_SEC = 3600.0;
const char* timeout_env = getenv("LIM_TURN_TIMEOUT");
double turn_timeout_sec = DEFAULT_TURN_TIMEOUT_SEC;
if (timeout_env != nullptr && strlen(timeout_env) > 0) {
char* endp = nullptr;
double val = strtod(timeout_env, &endp);
if (*endp == '\0') turn_timeout_sec = val;