summaryrefslogtreecommitdiff
path: root/bot.go
blob: bf3a2392cf2c402e318bba2613d1a520daca6b91 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
package main

import (
	"bufio"
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"gf-lt/config"
	"gf-lt/models"
	"gf-lt/rag"
	"gf-lt/storage"
	"html"
	"io"
	"log/slog"
	"net"
	"net/http"
	"net/url"
	"os"
	"regexp"
	"slices"
	"strconv"
	"strings"
	"sync"
	"time"
)

var (
	httpClient      = &http.Client{}
	cfg             *config.Config
	logger          *slog.Logger
	logLevel        = new(slog.LevelVar)
	ctx, cancel     = context.WithCancel(context.Background())
	activeChatName  string
	chatRoundChan   = make(chan *models.ChatRoundReq, 1)
	chunkChan       = make(chan string, 10)
	openAIToolChan  = make(chan string, 10)
	streamDone      = make(chan bool, 1)
	chatBody        *models.ChatBody
	store           storage.FullRepo
	defaultFirstMsg = "Hello! What can I do for you?"
	defaultStarter  = []models.RoleMsg{}
	interruptResp   = false
	ragger          *rag.RAG
	chunkParser     ChunkParser
	lastToolCall    *models.FuncCall
	lastRespStats   *models.ResponseStats
	//nolint:unused // TTS_ENABLED conditionally uses this
	orator          Orator
	asr             STT
	localModelsMu   sync.RWMutex
	defaultLCPProps = map[string]float32{
		"temperature":    0.8,
		"dry_multiplier": 0.0,
		"min_p":          0.05,
		"n_predict":      -1.0,
	}
	ORFreeModels = []string{
		"google/gemini-2.0-flash-exp:free",
		"deepseek/deepseek-chat-v3-0324:free",
		"mistralai/mistral-small-3.2-24b-instruct:free",
		"qwen/qwen3-14b:free",
		"google/gemma-3-27b-it:free",
		"meta-llama/llama-3.3-70b-instruct:free",
	}
	LocalModels = []string{}
)

var thinkBlockRE = regexp.MustCompile(`(?s)<think>.*?</think>`)

// parseKnownToTag extracts known_to list from content using configured tag.
// Returns cleaned content and list of character names.
func parseKnownToTag(content string) []string {
	if cfg == nil || !cfg.CharSpecificContextEnabled {
		return nil
	}
	tag := cfg.CharSpecificContextTag
	if tag == "" {
		tag = "@"
	}
	// Pattern: tag + list + "@"
	pattern := regexp.QuoteMeta(tag) + `(.*?)@`
	re := regexp.MustCompile(pattern)
	matches := re.FindAllStringSubmatch(content, -1)
	if len(matches) == 0 {
		return nil
	}
	// There may be multiple tags; we combine all.
	var knownTo []string
	for _, match := range matches {
		if len(match) < 2 {
			continue
		}
		// Remove the entire matched tag from content
		list := strings.TrimSpace(match[1])
		if list == "" {
			continue
		}
		strings.SplitSeq(list, ",")
		// parts := strings.Split(list, ",")
		// for _, p := range parts {
		for p := range strings.SplitSeq(list, ",") {
			p = strings.TrimSpace(p)
			if p != "" {
				knownTo = append(knownTo, p)
			}
		}
	}
	// Also remove any leftover trailing "__" that might be orphaned? Not needed.
	return knownTo
}

// processMessageTag processes a message for known_to tag and sets KnownTo field.
// It also ensures the sender's role is included in KnownTo.
// If KnownTo already set (e.g., from DB), preserves it unless new tag found.
func processMessageTag(msg *models.RoleMsg) *models.RoleMsg {
	if cfg == nil || !cfg.CharSpecificContextEnabled {
		return msg
	}
	// If KnownTo already set, assume tag already processed (content cleaned).
	// However, we still check for new tags (maybe added later).
	knownTo := parseKnownToTag(msg.GetText())
	// If tag found, replace KnownTo with new list (merge with existing?)
	// For simplicity, if knownTo is not nil, replace.
	if knownTo == nil {
		return msg
	}
	msg.KnownTo = knownTo
	if msg.Role == "" {
		return msg
	}
	if !slices.Contains(msg.KnownTo, msg.Role) {
		msg.KnownTo = append(msg.KnownTo, msg.Role)
	}
	return msg
}

// filterMessagesForCharacter returns messages visible to the specified character.
// If CharSpecificContextEnabled is false, returns all messages.
func filterMessagesForCharacter(messages []models.RoleMsg, character string) []models.RoleMsg {
	if strings.Contains(cfg.CurrentAPI, "chat") {
		return messages
	}
	if cfg == nil || !cfg.CharSpecificContextEnabled || character == "" {
		return messages
	}
	if character == "system" { // system sees every message
		return messages
	}
	filtered := make([]models.RoleMsg, 0, len(messages))
	for i := range messages {
		// If KnownTo is nil or empty, message is visible to all
		// system msg cannot be filtered
		if len(messages[i].KnownTo) == 0 || messages[i].Role == "system" {
			filtered = append(filtered, messages[i])
			continue
		}
		if slices.Contains(messages[i].KnownTo, character) {
			// Check if character is in KnownTo lis
			filtered = append(filtered, messages[i])
		}
	}
	return filtered
}

func consolidateAssistantMessages(messages []models.RoleMsg) []models.RoleMsg {
	if len(messages) == 0 {
		return messages
	}
	result := make([]models.RoleMsg, 0, len(messages))
	for i := range messages {
		// Non-assistant messages are appended as-is
		if messages[i].Role != cfg.AssistantRole {
			result = append(result, messages[i])
			continue
		}
		// Assistant message: start a new block or merge with the last one
		if len(result) == 0 || result[len(result)-1].Role != cfg.AssistantRole {
			// First assistant in a block: append a copy (avoid mutating input)
			result = append(result, messages[i].Copy())
			continue
		}
		// Merge with the last assistant message
		last := &result[len(result)-1]
		// If either message has structured content, unify to ContentParts
		if last.IsContentParts() || messages[i].IsContentParts() {
			// Convert last to ContentParts if needed, preserving ToolCallID
			if !last.IsContentParts() {
				toolCallID := last.ToolCallID
				*last = models.NewMultimodalMsg(last.Role, []interface{}{
					models.TextContentPart{Type: "text", Text: last.Content},
				})
				last.ToolCallID = toolCallID
			}
			// Add current message's content to last
			if messages[i].IsContentParts() {
				last.ContentParts = append(last.ContentParts, messages[i].GetContentParts()...)
			} else if messages[i].Content != "" {
				last.AddTextPart(messages[i].Content)
			}
		} else {
			// Both simple strings: concatenate with newline
			if last.Content != "" && messages[i].Content != "" {
				last.Content += "\n" + messages[i].Content
			} else if messages[i].Content != "" {
				last.Content = messages[i].Content
			}
			// ToolCallID is already preserved in last
		}
	}
	return result
}

// GetLogLevel returns the current log level as a string
func GetLogLevel() string {
	level := logLevel.Level()
	switch level {
	case slog.LevelDebug:
		return "Debug"
	case slog.LevelInfo:
		return "Info"
	case slog.LevelWarn:
		return "Warn"
	default:
		// For any other values, return "Info" as default
		return "Info"
	}
}

func createClient(connectTimeout time.Duration) *http.Client {
	// Custom transport with connection timeout
	transport := &http.Transport{
		DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
			// Create a dialer with connection timeout
			dialer := &net.Dialer{
				Timeout:   connectTimeout,
				KeepAlive: 30 * time.Second, // Optional
			}
			return dialer.DialContext(ctx, network, addr)
		},
		// Other transport settings (optional)
		TLSHandshakeTimeout:   connectTimeout,
		ResponseHeaderTimeout: connectTimeout,
	}
	// Client with no overall timeout (or set to streaming-safe duration)
	return &http.Client{
		Transport: transport,
		Timeout:   0, // No overall timeout (for streaming)
	}
}

func warmUpModel() {
	u, err := url.Parse(cfg.CurrentAPI)
	if err != nil {
		return
	}
	host := u.Hostname()
	if host != "localhost" && host != "127.0.0.1" && host != "::1" {
		return
	}
	// Check if model is already loaded
	loaded, err := isModelLoaded(chatBody.Model)
	if err != nil {
		logger.Debug("failed to check model status", "model", chatBody.Model, "error", err)
		// Continue with warmup attempt anyway
	}
	if loaded {
		if err := notifyUser("model already loaded", "Model "+chatBody.Model+" is already loaded."); err != nil {
			logger.Debug("failed to notify user", "error", err)
		}
		return
	}
	go func() {
		var data []byte
		var err error
		switch {
		case strings.HasSuffix(cfg.CurrentAPI, "/completion"):
			// Old completion endpoint
			req := models.NewLCPReq(".", chatBody.Model, nil, map[string]float32{
				"temperature":    0.8,
				"dry_multiplier": 0.0,
				"min_p":          0.05,
				"n_predict":      0,
			}, []string{})
			req.Stream = false
			data, err = json.Marshal(req)
		case strings.Contains(cfg.CurrentAPI, "/v1/chat/completions"):
			// OpenAI-compatible chat endpoint
			req := models.OpenAIReq{
				ChatBody: &models.ChatBody{
					Model: chatBody.Model,
					Messages: []models.RoleMsg{
						{Role: "system", Content: "."},
					},
					Stream: false,
				},
				Tools: nil,
			}
			data, err = json.Marshal(req)
		default:
			// Unknown local endpoint, skip
			return
		}
		if err != nil {
			logger.Debug("failed to marshal warmup request", "error", err)
			return
		}
		resp, err := httpClient.Post(cfg.CurrentAPI, "application/json", bytes.NewReader(data))
		if err != nil {
			logger.Debug("warmup request failed", "error", err)
			return
		}
		resp.Body.Close()
		// Start monitoring for model load completion
		monitorModelLoad(chatBody.Model)
	}()
}

// nolint
func fetchDSBalance() *models.DSBalance {
	url := "https://api.deepseek.com/user/balance"
	method := "GET"
	// nolint
	req, err := http.NewRequest(method, url, nil)
	if err != nil {
		logger.Warn("failed to create request", "error", err)
		return nil
	}
	req.Header.Add("Accept", "application/json")
	req.Header.Add("Authorization", "Bearer "+cfg.DeepSeekToken)
	res, err := httpClient.Do(req)
	if err != nil {
		logger.Warn("failed to make request", "error", err)
		return nil
	}
	defer res.Body.Close()
	resp := models.DSBalance{}
	if err := json.NewDecoder(res.Body).Decode(&resp); err != nil {
		return nil
	}
	return &resp
}

func fetchORModels(free bool) ([]string, error) {
	resp, err := http.Get("https://openrouter.ai/api/v1/models")
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != 200 {
		err := fmt.Errorf("failed to fetch or models; status: %s", resp.Status)
		return nil, err
	}
	data := &models.ORModels{}
	if err := json.NewDecoder(resp.Body).Decode(data); err != nil {
		return nil, err
	}
	freeModels := data.ListModels(free)
	return freeModels, nil
}

func fetchLCPModels() ([]string, error) {
	resp, err := http.Get(cfg.FetchModelNameAPI)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != 200 {
		err := fmt.Errorf("failed to fetch or models; status: %s", resp.Status)
		return nil, err
	}
	data := &models.LCPModels{}
	if err := json.NewDecoder(resp.Body).Decode(data); err != nil {
		return nil, err
	}
	localModels := data.ListModels()
	return localModels, nil
}

// fetchLCPModelsWithLoadStatus returns models with "(loaded)" indicator for loaded models
func fetchLCPModelsWithLoadStatus() ([]string, error) {
	modelList, err := fetchLCPModelsWithStatus()
	if err != nil {
		return nil, err
	}
	result := make([]string, 0, len(modelList.Data))
	li := 0 // loaded index
	for i, m := range modelList.Data {
		modelName := m.ID
		if m.Status.Value == "loaded" {
			modelName = models.LoadedMark + modelName
			li = i
		}
		result = append(result, modelName)
	}
	if li == 0 {
		return result, nil // no loaded modelList
	}
	loadedModel := result[li]
	result = append(result[:li], result[li+1:]...)
	return slices.Concat([]string{loadedModel}, result), nil
}

// fetchLCPModelsWithStatus returns the full LCPModels struct including status information.
func fetchLCPModelsWithStatus() (*models.LCPModels, error) {
	resp, err := http.Get(cfg.FetchModelNameAPI)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != 200 {
		err := fmt.Errorf("failed to fetch llama.cpp models; status: %s", resp.Status)
		return nil, err
	}
	data := &models.LCPModels{}
	if err := json.NewDecoder(resp.Body).Decode(data); err != nil {
		return nil, err
	}
	return data, nil
}

// isModelLoaded checks if the given model ID is currently loaded in llama.cpp server.
func isModelLoaded(modelID string) (bool, error) {
	models, err := fetchLCPModelsWithStatus()
	if err != nil {
		return false, err
	}
	for _, m := range models.Data {
		if m.ID == modelID {
			return m.Status.Value == "loaded", nil
		}
	}
	return false, nil
}

// monitorModelLoad starts a goroutine that periodically checks if the specified model is loaded.
func monitorModelLoad(modelID string) {
	go func() {
		timeout := time.After(2 * time.Minute) // max wait 2 minutes
		ticker := time.NewTicker(2 * time.Second)
		defer ticker.Stop()
		for {
			select {
			case <-timeout:
				logger.Debug("model load monitoring timeout", "model", modelID)
				return
			case <-ticker.C:
				loaded, err := isModelLoaded(modelID)
				if err != nil {
					logger.Debug("failed to check model status", "model", modelID, "error", err)
					continue
				}
				if loaded {
					if err := notifyUser("model loaded", "Model "+modelID+" is now loaded and ready."); err != nil {
						logger.Debug("failed to notify user", "error", err)
					}
					refreshChatDisplay()
					return
				}
			}
		}
	}()
}

// extractDetailedErrorFromBytes extracts detailed error information from response body bytes
func extractDetailedErrorFromBytes(body []byte, statusCode int) string {
	// Try to parse as JSON to extract detailed error information
	var errorResponse map[string]any
	if err := json.Unmarshal(body, &errorResponse); err == nil {
		// Check if it's an error response with detailed information
		if errorData, ok := errorResponse["error"]; ok {
			if errorMap, ok := errorData.(map[string]any); ok {
				var errorMsg string
				if msg, ok := errorMap["message"]; ok {
					errorMsg = fmt.Sprintf("%v", msg)
				}
				var details []string
				if code, ok := errorMap["code"]; ok {
					details = append(details, fmt.Sprintf("Code: %v", code))
				}
				if metadata, ok := errorMap["metadata"]; ok {
					// Handle metadata which might contain raw error details
					if metadataMap, ok := metadata.(map[string]any); ok {
						if raw, ok := metadataMap["raw"]; ok {
							// Parse the raw error string if it's JSON
							var rawError map[string]any
							if rawStr, ok := raw.(string); ok && json.Unmarshal([]byte(rawStr), &rawError) == nil {
								if rawErrorData, ok := rawError["error"]; ok {
									if rawErrorMap, ok := rawErrorData.(map[string]any); ok {
										if rawMsg, ok := rawErrorMap["message"]; ok {
											return fmt.Sprintf("API Error: %s", rawMsg)
										}
									}
								}
							}
						}
					}
					details = append(details, fmt.Sprintf("Metadata: %v", metadata))
				}
				if len(details) > 0 {
					return fmt.Sprintf("API Error: %s (%s)", errorMsg, strings.Join(details, ", "))
				}
				return "API Error: " + errorMsg
			}
		}
	}
	// If not a structured error response, return the raw body with status
	return fmt.Sprintf("HTTP Status: %d, Response Body: %s", statusCode, string(body))
}

func finalizeRespStats(tokenCount int, startTime time.Time) {
	duration := time.Since(startTime).Seconds()
	var tps float64
	if duration > 0 {
		tps = float64(tokenCount) / duration
	}
	lastRespStats = &models.ResponseStats{
		Tokens:       tokenCount,
		Duration:     duration,
		TokensPerSec: tps,
	}
}

// sendMsgToLLM expects streaming resp
func sendMsgToLLM(body io.Reader) {
	choseChunkParser()
	// openrouter does not respect stop strings, so we have to cut the message ourselves
	stopStrings := chatBody.MakeStopSliceExcluding("", listChatRoles())
	req, err := http.NewRequest("POST", cfg.CurrentAPI, body)
	if err != nil {
		logger.Error("newreq error", "error", err)
		if err := notifyUser("error", "apicall failed:"+err.Error()); err != nil {
			logger.Error("failed to notify", "error", err)
		}
		streamDone <- true
		return
	}
	req.Header.Add("Accept", "application/json")
	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Authorization", "Bearer "+chunkParser.GetToken())
	req.Header.Set("Accept-Encoding", "gzip")
	// nolint
	resp, err := httpClient.Do(req)
	if err != nil {
		logger.Error("llamacpp api", "error", err)
		if err := notifyUser("error", "apicall failed:"+err.Error()); err != nil {
			logger.Error("failed to notify", "error", err)
		}
		streamDone <- true
		return
	}
	// Check if the initial response is an error before starting to stream
	if resp.StatusCode >= 400 {
		// Read the response body to get detailed error information
		bodyBytes, err := io.ReadAll(resp.Body)
		if err != nil {
			logger.Error("failed to read error response body", "error", err, "status_code", resp.StatusCode)
			detailedError := fmt.Sprintf("HTTP Status: %d, Failed to read response body: %v", resp.StatusCode, err)
			if err := notifyUser("API Error", detailedError); err != nil {
				logger.Error("failed to notify", "error", err)
			}
			resp.Body.Close()
			streamDone <- true
			return
		}
		// Parse the error response for detailed information
		detailedError := extractDetailedErrorFromBytes(bodyBytes, resp.StatusCode)
		logger.Error("API returned error status", "status_code", resp.StatusCode, "detailed_error", detailedError)
		if err := notifyUser("API Error", detailedError); err != nil {
			logger.Error("failed to notify", "error", err)
		}
		resp.Body.Close()
		streamDone <- true
		return
	}
	//
	defer resp.Body.Close()
	reader := bufio.NewReader(resp.Body)
	counter := uint32(0)
	tokenCount := 0
	startTime := time.Now()
	hasReasoning := false
	reasoningSent := false
	defer func() {
		finalizeRespStats(tokenCount, startTime)
	}()
	for {
		var (
			answerText string
			chunk      *models.TextChunk
		)
		counter++
		// to stop from spiriling in infinity read of bad bytes that happens with poor connection
		if cfg.ChunkLimit > 0 && counter > cfg.ChunkLimit {
			logger.Warn("response hit chunk limit", "limit", cfg.ChunkLimit)
			streamDone <- true
			break
		}
		line, err := reader.ReadBytes('\n')
		if err != nil {
			// Check if this is an EOF error and if the response contains detailed error information
			if err == io.EOF {
				// For streaming responses, we may have already consumed the error body
				// So we'll use the original status code to provide context
				detailedError := fmt.Sprintf("Streaming connection closed unexpectedly (Status: %d). This may indicate an API error. Check your API provider and model settings.", resp.StatusCode)
				logger.Error("error reading response body", "error", err, "detailed_error", detailedError,
					"status_code", resp.StatusCode, "user_role", cfg.UserRole, "parser", chunkParser, "link", cfg.CurrentAPI)
				if err := notifyUser("API Error", detailedError); err != nil {
					logger.Error("failed to notify", "error", err)
				}
			} else {
				logger.Error("error reading response body", "error", err, "line", string(line),
					"user_role", cfg.UserRole, "parser", chunkParser, "link", cfg.CurrentAPI)
				// if err.Error() != "EOF" {
				if err := notifyUser("API error", err.Error()); err != nil {
					logger.Error("failed to notify", "error", err)
				}
			}
			streamDone <- true
			break
			// }
			// continue
		}
		if len(line) <= 1 {
			if interruptResp {
				goto interrupt // get unstuck from bad connection
			}
			continue // skip \n
		}
		// starts with -> data:
		line = line[6:]
		logger.Debug("debugging resp", "line", string(line))
		if bytes.Equal(line, []byte("[DONE]\n")) {
			streamDone <- true
			break
		}
		if bytes.Equal(line, []byte("ROUTER PROCESSING\n")) {
			continue
		}
		chunk, err = chunkParser.ParseChunk(line)
		if err != nil {
			logger.Error("error parsing response body", "error", err,
				"line", string(line), "url", cfg.CurrentAPI)
			if err := notifyUser("LLM Response Error", "Failed to parse LLM response: "+err.Error()); err != nil {
				logger.Error("failed to notify user", "error", err)
			}
			streamDone <- true
			break
		}
		// // problem: this catches any mention of the word 'error'
		// Handle error messages in response content
		// example needed, since llm could use the word error in the normal msg
		// if string(line) != "" && strings.Contains(strings.ToLower(string(line)), "error") {
		// 	logger.Error("API error response detected", "line", line, "url", cfg.CurrentAPI)
		// 	streamDone <- true
		// 	break
		// }
		if chunk.Finished {
			// Close the thinking block if we were streaming reasoning and haven't closed it yet
			if hasReasoning && !reasoningSent {
				chunkChan <- "</think>"
				tokenCount++
			}
			if chunk.Chunk != "" {
				logger.Warn("text inside of finish llmchunk", "chunk", chunk, "counter", counter)
				answerText = strings.ReplaceAll(chunk.Chunk, "\n\n", "\n")
				chunkChan <- answerText
				tokenCount++
			}
			streamDone <- true
			break
		}
		if counter == 0 {
			chunk.Chunk = strings.TrimPrefix(chunk.Chunk, " ")
		}
		// Handle reasoning chunks - stream them immediately as they arrive
		if chunk.Reasoning != "" && !reasoningSent {
			if !hasReasoning {
				// First reasoning chunk - send opening tag
				chunkChan <- "<think>"
				tokenCount++
				hasReasoning = true
			}
			// Stream reasoning content immediately
			answerText = strings.ReplaceAll(chunk.Reasoning, "\n\n", "\n")
			if answerText != "" {
				chunkChan <- answerText
				tokenCount++
			}
		}
		// When we get content and have been streaming reasoning, close the thinking block
		if chunk.Chunk != "" && hasReasoning && !reasoningSent {
			// Close the thinking block before sending actual content
			chunkChan <- "</think>"
			tokenCount++
			reasoningSent = true
		}
		// bot sends way too many \n
		answerText = strings.ReplaceAll(chunk.Chunk, "\n\n", "\n")
		// Accumulate text to check for stop strings that might span across chunks
		// check if chunk is in stopstrings => stop
		// this check is needed only for openrouter /v1/completion, since it does not respect stop slice
		if chunkParser.GetAPIType() == models.APITypeCompletion &&
			slices.Contains(stopStrings, answerText) {
			logger.Debug("stop string detected on client side for completion endpoint", "stop_string", answerText)
			streamDone <- true
			break
		}
		if answerText != "" {
			chunkChan <- answerText
			tokenCount++
		}
		openAIToolChan <- chunk.ToolChunk
		if chunk.FuncName != "" {
			lastToolCall.Name = chunk.FuncName
			// Store the tool call ID for the response
			lastToolCall.ID = chunk.ToolID
		}
	interrupt:
		if interruptResp { // read bytes, so it would not get into beginning of the next req
			interruptResp = false
			logger.Info("interrupted bot response", "chunk_counter", counter)
			streamDone <- true
			break
		}
	}
}

func roleToIcon(role string) string {
	return "<" + role + ">: "
}

func chatWatcher(ctx context.Context) {
	for {
		select {
		case <-ctx.Done():
			return
		case chatRoundReq := <-chatRoundChan:
			if err := chatRound(chatRoundReq); err != nil {
				logger.Error("failed to chatRound", "err", err)
			}
		}
	}
}

// inpired by https://github.com/rivo/tview/issues/225
func showSpinner() {
	spinners := []string{"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"}
	var i int
	botPersona := cfg.AssistantRole
	if cfg.WriteNextMsgAsCompletionAgent != "" {
		botPersona = cfg.WriteNextMsgAsCompletionAgent
	}
	for botRespMode || toolRunningMode {
		time.Sleep(400 * time.Millisecond)
		spin := i % len(spinners)
		app.QueueUpdateDraw(func() {
			switch {
			case toolRunningMode:
				textArea.SetTitle(spinners[spin] + " tool")
			case botRespMode:
				textArea.SetTitle(spinners[spin] + " " + botPersona + " (F6 to interrupt)")
			default:
				textArea.SetTitle(spinners[spin] + " input")
			}
		})
		i++
	}
	app.QueueUpdateDraw(func() {
		textArea.SetTitle("input")
	})
}

func chatRound(r *models.ChatRoundReq) error {
	botRespMode = true
	go showSpinner()
	updateStatusLine()
	botPersona := cfg.AssistantRole
	if cfg.WriteNextMsgAsCompletionAgent != "" {
		botPersona = cfg.WriteNextMsgAsCompletionAgent
	}
	defer func() {
		botRespMode = false
		ClearImageAttachment()
	}()
	// check that there is a model set to use if is not local
	choseChunkParser()
	reader, err := chunkParser.FormMsg(r.UserMsg, r.Role, r.Resume)
	if reader == nil || err != nil {
		logger.Error("empty reader from msgs", "role", r.Role, "error", err)
		return err
	}
	if cfg.SkipLLMResp {
		return nil
	}
	go sendMsgToLLM(reader)
	logger.Debug("looking at vars in chatRound", "msg", r.UserMsg, "regen", r.Regen, "resume", r.Resume)
	msgIdx := len(chatBody.Messages)
	if !r.Resume {
		// Add empty message to chatBody immediately so it persists during Alt+T toggle
		chatBody.Messages = append(chatBody.Messages, models.RoleMsg{
			Role: botPersona, Content: "",
		})
		nl := "\n\n"
		prevText := textView.GetText(true)
		if strings.HasSuffix(prevText, nl) {
			nl = ""
		} else if strings.HasSuffix(prevText, "\n") {
			nl = "\n"
		}
		fmt.Fprintf(textView, "%s[-:-:b](%d) %s[-:-:-]\n", nl, msgIdx, roleToIcon(botPersona))
	} else {
		msgIdx = len(chatBody.Messages) - 1
	}
	respText := strings.Builder{}
	toolResp := strings.Builder{}
	// Variables for handling thinking blocks during streaming
	inThinkingBlock := false
	thinkingBuffer := strings.Builder{}
	justExitedThinkingCollapsed := false
out:
	for {
		select {
		case chunk := <-chunkChan:
			// Handle thinking blocks during streaming
			if strings.HasPrefix(chunk, "<think>") && !inThinkingBlock {
				// Start of thinking block
				inThinkingBlock = true
				thinkingBuffer.Reset()
				thinkingBuffer.WriteString(chunk)
				if thinkingCollapsed {
					// Show placeholder immediately when thinking starts in collapsed mode
					fmt.Fprint(textView, "[yellow::i][thinking... (press Alt+T to expand)][-:-:-]")
					if scrollToEndEnabled {
						textView.ScrollToEnd()
					}
					respText.WriteString(chunk)
					continue
				}
			} else if inThinkingBlock {
				thinkingBuffer.WriteString(chunk)
				if strings.Contains(chunk, "</think>") {
					// End of thinking block
					inThinkingBlock = false
					if thinkingCollapsed {
						// Thinking already displayed as placeholder, just update respText
						respText.WriteString(chunk)
						justExitedThinkingCollapsed = true
						if scrollToEndEnabled {
							textView.ScrollToEnd()
						}
						continue
					}
					// If not collapsed, fall through to normal display
				} else if thinkingCollapsed {
					// Still in thinking block and collapsed - just buffer, don't display
					respText.WriteString(chunk)
					continue
				}
				// If not collapsed, fall through to normal display
			}
			// Add spacing after collapsed thinking block before real response
			if justExitedThinkingCollapsed {
				chunk = "\n\n" + chunk
				justExitedThinkingCollapsed = false
			}
			fmt.Fprint(textView, chunk)
			respText.WriteString(chunk)
			// Update the message in chatBody.Messages so it persists during Alt+T
			chatBody.Messages[msgIdx].Content = respText.String()
			if scrollToEndEnabled {
				textView.ScrollToEnd()
			}
			// Send chunk to audio stream handler
			if cfg.TTS_ENABLED {
				TTSTextChan <- chunk
			}
		case toolChunk := <-openAIToolChan:
			fmt.Fprint(textView, toolChunk)
			toolResp.WriteString(toolChunk)
			if scrollToEndEnabled {
				textView.ScrollToEnd()
			}
		case <-streamDone:
			for len(chunkChan) > 0 {
				chunk := <-chunkChan
				fmt.Fprint(textView, chunk)
				respText.WriteString(chunk)
				if scrollToEndEnabled {
					textView.ScrollToEnd()
				}
				if cfg.TTS_ENABLED {
					TTSTextChan <- chunk
				}
			}
			if cfg.TTS_ENABLED {
				TTSFlushChan <- true
			}
			break out
		}
	}
	var msgStats *models.ResponseStats
	if lastRespStats != nil {
		msgStats = &models.ResponseStats{
			Tokens:       lastRespStats.Tokens,
			Duration:     lastRespStats.Duration,
			TokensPerSec: lastRespStats.TokensPerSec,
		}
		lastRespStats = nil
	}
	botRespMode = false
	if r.Resume {
		chatBody.Messages[len(chatBody.Messages)-1].Content += respText.String()
		updatedMsg := chatBody.Messages[len(chatBody.Messages)-1]
		processedMsg := processMessageTag(&updatedMsg)
		chatBody.Messages[len(chatBody.Messages)-1] = *processedMsg
		if msgStats != nil && chatBody.Messages[len(chatBody.Messages)-1].Role != cfg.ToolRole {
			chatBody.Messages[len(chatBody.Messages)-1].Stats = msgStats
		}
	} else {
		chatBody.Messages[msgIdx].Content = respText.String()
		processedMsg := processMessageTag(&chatBody.Messages[msgIdx])
		chatBody.Messages[msgIdx] = *processedMsg
		if msgStats != nil && chatBody.Messages[msgIdx].Role != cfg.ToolRole {
			chatBody.Messages[msgIdx].Stats = msgStats
		}
		stopTTSIfNotForUser(&chatBody.Messages[msgIdx])
	}
	cleanChatBody()
	refreshChatDisplay()
	updateStatusLine()
	// bot msg is done;
	// now check it for func call
	// logChat(activeChatName, chatBody.Messages)
	if err := updateStorageChat(activeChatName, chatBody.Messages); err != nil {
		logger.Warn("failed to update storage", "error", err, "name", activeChatName)
	}
	// Strip think blocks before parsing for tool calls
	respTextNoThink := thinkBlockRE.ReplaceAllString(respText.String(), "")
	if findCall(respTextNoThink, toolResp.String()) {
		return nil
	}
	// Check if this message was sent privately to specific characters
	// If so, trigger those characters to respond if that char is not controlled by user
	// perhaps we should have narrator role to determine which char is next to act
	if cfg.AutoTurn {
		lastMsg := chatBody.Messages[len(chatBody.Messages)-1]
		if len(lastMsg.KnownTo) > 0 {
			triggerPrivateMessageResponses(&lastMsg)
		}
	}
	return nil
}

// cleanChatBody removes messages with null or empty content to prevent API issues
func cleanChatBody() {
	if chatBody == nil || chatBody.Messages == nil {
		return
	}
	// Tool request cleaning is now configurable via AutoCleanToolCallsFromCtx (default false)
	// /completion msg where part meant for user and other part tool call
	// chatBody.Messages = cleanToolCalls(chatBody.Messages)
	chatBody.Messages = consolidateAssistantMessages(chatBody.Messages)
}

// convertJSONToMapStringString unmarshals JSON into map[string]interface{} and converts all values to strings.
func convertJSONToMapStringString(jsonStr string) (map[string]string, error) {
	// Extract JSON object from string - models may output extra text after JSON
	jsonStr = extractJSON(jsonStr)
	var raw map[string]interface{}
	if err := json.Unmarshal([]byte(jsonStr), &raw); err != nil {
		return nil, err
	}
	result := make(map[string]string, len(raw))
	for k, v := range raw {
		switch val := v.(type) {
		case string:
			result[k] = val
		case float64:
			result[k] = strconv.FormatFloat(val, 'f', -1, 64)
		case int, int64, int32:
			// json.Unmarshal converts numbers to float64, but handle other integer types if they appear
			result[k] = fmt.Sprintf("%v", val)
		case bool:
			result[k] = strconv.FormatBool(val)
		case nil:
			result[k] = ""
		default:
			result[k] = fmt.Sprintf("%v", val)
		}
	}
	return result, nil
}

// extractJSON finds the first { and last } to extract only the JSON object
// This handles cases where models output extra text after JSON
func extractJSON(s string) string {
	// Try direct parse first - if it works, return as-is
	var dummy map[string]interface{}
	if err := json.Unmarshal([]byte(s), &dummy); err == nil {
		return s
	}
	// Otherwise find JSON boundaries
	start := strings.Index(s, "{")
	end := strings.LastIndex(s, "}")
	if start >= 0 && end > start {
		return s[start : end+1]
	}
	return s
}

// unmarshalFuncCall unmarshals a JSON tool call, converting numeric arguments to strings.
func unmarshalFuncCall(jsonStr string) (*models.FuncCall, error) {
	type tempFuncCall struct {
		ID   string                 `json:"id,omitempty"`
		Name string                 `json:"name"`
		Args map[string]interface{} `json:"args"`
	}
	var temp tempFuncCall
	if err := json.Unmarshal([]byte(jsonStr), &temp); err != nil {
		return nil, err
	}
	fc := &models.FuncCall{
		ID:   temp.ID,
		Name: temp.Name,
		Args: make(map[string]string, len(temp.Args)),
	}
	for k, v := range temp.Args {
		switch val := v.(type) {
		case string:
			fc.Args[k] = val
		case float64:
			fc.Args[k] = strconv.FormatFloat(val, 'f', -1, 64)
		case int, int64, int32:
			fc.Args[k] = fmt.Sprintf("%v", val)
		case bool:
			fc.Args[k] = strconv.FormatBool(val)
		case nil:
			fc.Args[k] = ""
		default:
			fc.Args[k] = fmt.Sprintf("%v", val)
		}
	}
	return fc, nil
}

// findCall: adds chatRoundReq into the chatRoundChan and returns true if does
func findCall(msg, toolCall string) bool {
	var fc *models.FuncCall
	if toolCall != "" {
		// HTML-decode the tool call string to handle encoded characters like &lt; -> <=
		decodedToolCall := html.UnescapeString(toolCall)
		openAIToolMap, err := convertJSONToMapStringString(decodedToolCall)
		if err != nil {
			logger.Error("failed to unmarshal openai tool call", "call", decodedToolCall, "error", err)
			// Ensure lastToolCall.ID is set for the error response (already set from chunk)
			// Send error response to LLM so it can retry or handle the error
			toolResponseMsg := models.RoleMsg{
				Role:       cfg.ToolRole,
				Content:    fmt.Sprintf("Error processing tool call: %v. Please check the JSON format and try again.", err),
				ToolCallID: lastToolCall.ID, // Use the stored tool call ID
			}
			chatBody.Messages = append(chatBody.Messages, toolResponseMsg)
			// Clear the stored tool call ID after using it (no longer needed)
			// Trigger the assistant to continue processing with the error message
			crr := &models.ChatRoundReq{
				Role: cfg.AssistantRole,
			}
			// provoke next llm msg after failed tool call
			chatRoundChan <- crr
			// chatRound("", cfg.AssistantRole, tv, false, false)
			return true
		}
		lastToolCall.Args = openAIToolMap
		fc = lastToolCall
		// NOTE: We do NOT override lastToolCall.ID from arguments.
		// The ID should come from the streaming response (chunk.ToolID) set earlier.
		// Some tools like todo_create have "id" in their arguments which is NOT the tool call ID.
	} else {
		jsStr := toolCallRE.FindString(msg)
		if jsStr == "" { // no tool call case
			return false
		}
		// Remove prefix/suffix with flexible whitespace handling
		jsStr = strings.TrimSpace(jsStr)
		jsStr = strings.TrimPrefix(jsStr, "__tool_call__")
		jsStr = strings.TrimSuffix(jsStr, "__tool_call__")
		jsStr = strings.TrimSpace(jsStr)
		// HTML-decode the JSON string to handle encoded characters like &lt; -> <=
		decodedJsStr := html.UnescapeString(jsStr)
		// Try to find valid JSON bounds (first { to last })
		start := strings.Index(decodedJsStr, "{")
		end := strings.LastIndex(decodedJsStr, "}")
		if start == -1 || end == -1 || end <= start {
			logger.Error("failed to find valid JSON in tool call", "json_string", decodedJsStr)
			toolResponseMsg := models.RoleMsg{
				Role:    cfg.ToolRole,
				Content: "Error processing tool call: no valid JSON found. Please check the JSON format.",
			}
			chatBody.Messages = append(chatBody.Messages, toolResponseMsg)
			crr := &models.ChatRoundReq{
				Role: cfg.AssistantRole,
			}
			chatRoundChan <- crr
			return true
		}
		decodedJsStr = decodedJsStr[start : end+1]
		var err error
		fc, err = unmarshalFuncCall(decodedJsStr)
		if err != nil {
			logger.Error("failed to unmarshal tool call", "error", err, "json_string", decodedJsStr)
			// Send error response to LLM so it can retry or handle the error
			toolResponseMsg := models.RoleMsg{
				Role:    cfg.ToolRole,
				Content: fmt.Sprintf("Error processing tool call: %v. Please check the JSON format and try again.", err),
			}
			chatBody.Messages = append(chatBody.Messages, toolResponseMsg)
			logger.Debug("findCall: added tool error response", "role", toolResponseMsg.Role, "content_len", len(toolResponseMsg.Content), "message_count_after_add", len(chatBody.Messages))
			// Trigger the assistant to continue processing with the error message
			// chatRound("", cfg.AssistantRole, tv, false, false)
			crr := &models.ChatRoundReq{
				Role: cfg.AssistantRole,
			}
			// provoke next llm msg after failed tool call
			chatRoundChan <- crr
			return true
		}
		// Update lastToolCall with parsed function call
		lastToolCall.ID = fc.ID
		lastToolCall.Name = fc.Name
		lastToolCall.Args = fc.Args
	}
	// we got here => last msg recognized as a tool call (correct or not)
	// Use the tool call ID from streaming response (lastToolCall.ID)
	// Don't generate random ID - the ID should match between assistant message and tool response
	lastMsgIdx := len(chatBody.Messages) - 1
	if lastToolCall.ID != "" {
		chatBody.Messages[lastMsgIdx].ToolCallID = lastToolCall.ID
	}
	// Store tool call info in the assistant message
	// Convert Args map to JSON string for storage
	chatBody.Messages[lastMsgIdx].ToolCall = &models.ToolCall{
		ID:   lastToolCall.ID,
		Name: lastToolCall.Name,
		Args: mapToString(lastToolCall.Args),
	}
	// call a func
	_, ok := fnMap[fc.Name]
	if !ok {
		m := fc.Name + " is not implemented"
		// Create tool response message with the proper tool_call_id
		toolResponseMsg := models.RoleMsg{
			Role:       cfg.ToolRole,
			Content:    m,
			ToolCallID: lastToolCall.ID, // Use the stored tool call ID
		}
		chatBody.Messages = append(chatBody.Messages, toolResponseMsg)
		logger.Debug("findCall: added tool not implemented response", "role", toolResponseMsg.Role, "content_len", len(toolResponseMsg.Content), "tool_call_id", toolResponseMsg.ToolCallID, "message_count_after_add", len(chatBody.Messages))
		// Clear the stored tool call ID after using it
		lastToolCall.ID = ""
		// Trigger the assistant to continue processing with the new tool response
		// by calling chatRound with empty content to continue the assistant's response
		crr := &models.ChatRoundReq{
			Role: cfg.AssistantRole,
		}
		// failed to find tool
		chatRoundChan <- crr
		return true
	}
	// Show tool call progress indicator before execution
	fmt.Fprintf(textView, "\n[yellow::i][tool: %s...][-:-:-]", fc.Name)
	toolRunningMode = true
	resp := callToolWithAgent(fc.Name, fc.Args)
	toolRunningMode = false
	toolMsg := string(resp)
	logger.Info("llm used a tool call", "tool_name", fc.Name, "too_args", fc.Args, "id", fc.ID, "tool_resp", toolMsg)
	fmt.Fprintf(textView, "%s[-:-:b](%d) <%s>: [-:-:-]\n%s\n",
		"\n\n", len(chatBody.Messages), cfg.ToolRole, toolMsg)
	// Create tool response message with the proper tool_call_id
	// Mark shell commands as always visible
	isShellCommand := fc.Name == "execute_command"
	toolResponseMsg := models.RoleMsg{
		Role:           cfg.ToolRole,
		Content:        toolMsg,
		ToolCallID:     lastToolCall.ID,
		IsShellCommand: isShellCommand,
	}
	chatBody.Messages = append(chatBody.Messages, toolResponseMsg)
	logger.Debug("findCall: added actual tool response", "role", toolResponseMsg.Role, "content_len", len(toolResponseMsg.Content), "tool_call_id", toolResponseMsg.ToolCallID, "message_count_after_add", len(chatBody.Messages))
	// Clear the stored tool call ID after using it
	lastToolCall.ID = ""
	// Trigger the assistant to continue processing with the new tool response
	// by calling chatRound with empty content to continue the assistant's response
	crr := &models.ChatRoundReq{
		Role: cfg.AssistantRole,
	}
	chatRoundChan <- crr
	return true
}

func chatToTextSlice(messages []models.RoleMsg, showSys bool) []string {
	resp := make([]string, len(messages))
	for i := range messages {
		icon := fmt.Sprintf("[-:-:b](%d) <%s>:[-:-:-]", i, messages[i].Role)
		// Handle tool call indicators (assistant messages with tool call but empty content)
		if messages[i].Role == cfg.AssistantRole && messages[i].ToolCall != nil && messages[i].ToolCall.ID != "" {
			// This is a tool call indicator - show collapsed
			if toolCollapsed {
				toolName := messages[i].ToolCall.Name
				resp[i] = strings.ReplaceAll(fmt.Sprintf("%s\n%s\n[yellow::i][tool call: %s (press Ctrl+T to expand)][-:-:-]\n", icon, messages[i].GetText(), toolName), "\n\n", "\n")
			} else {
				// Show full tool call info
				toolName := messages[i].ToolCall.Name
				resp[i] = strings.ReplaceAll(fmt.Sprintf("%s\n%s\n[yellow::i][tool call: %s][-:-:-]\nargs: %s\nid: %s\n", icon, messages[i].GetText(), toolName, messages[i].ToolCall.Args, messages[i].ToolCall.ID), "\n\n", "\n")
			}
			continue
		}
		// Handle tool responses
		if messages[i].Role == cfg.ToolRole || messages[i].Role == "tool" {
			// Always show shell commands
			if messages[i].IsShellCommand {
				resp[i] = MsgToText(i, &messages[i])
				continue
			}
			// Hide non-shell tool responses when collapsed
			if toolCollapsed {
				resp[i] = icon + "\n[yellow::i][tool resp (press Ctrl+T to expand)][-:-:-]\n"
				continue
			}
			// When expanded, show tool responses
			resp[i] = MsgToText(i, &messages[i])
			continue
		}
		// INFO: skips system msg when showSys is false
		if !showSys && messages[i].Role == "system" {
			continue
		}
		resp[i] = MsgToText(i, &messages[i])
	}
	return resp
}

func chatToText(messages []models.RoleMsg, showSys bool) string {
	s := chatToTextSlice(messages, showSys)
	text := strings.Join(s, "\n")
	// Collapse thinking blocks if enabled
	if thinkingCollapsed {
		text = thinkRE.ReplaceAllStringFunc(text, func(match string) string {
			// Extract content between <think> and </think>
			start := len("<think>")
			end := len(match) - len("</think>")
			if start < end && start < len(match) {
				content := match[start:end]
				return fmt.Sprintf("[yellow::i][thinking... (%d chars) (press Alt+T to expand)][-:-:-]", len(content))
			}
			return "[yellow::i][thinking... (press Alt+T to expand)][-:-:-]"
		})
		// Handle incomplete thinking blocks (during streaming when </think> hasn't arrived yet)
		if strings.Contains(text, "<think>") && !strings.Contains(text, "</think>") {
			// Find the incomplete thinking block and replace it
			startIdx := strings.Index(text, "<think>")
			if startIdx != -1 {
				content := text[startIdx+len("<think>"):]
				placeholder := fmt.Sprintf("[yellow::i][thinking... (%d chars) (press Alt+T to expand)][-:-:-]", len(content))
				text = text[:startIdx] + placeholder
			}
		}
	}
	return text
}

func addNewChat(chatName string) {
	id, err := store.ChatGetMaxID()
	if err != nil {
		logger.Error("failed to get max chat id from db;", "id:", id)
		// INFO: will rewrite first chat
	}
	chat := &models.Chat{
		ID:        id + 1,
		CreatedAt: time.Now(),
		UpdatedAt: time.Now(),
		Agent:     cfg.AssistantRole,
	}
	if chatName == "" {
		chatName = fmt.Sprintf("%d_%s", chat.ID, cfg.AssistantRole)
	}
	chat.Name = chatName
	chatMap[chat.Name] = chat
	activeChatName = chat.Name
}

func applyCharCard(cc *models.CharCard, loadHistory bool) {
	cfg.AssistantRole = cc.Role
	history, err := loadAgentsLastChat(cfg.AssistantRole)
	if err != nil || !loadHistory {
		// too much action for err != nil; loadAgentsLastChat needs to be split up
		history = []models.RoleMsg{
			{Role: "system", Content: cc.SysPrompt},
			{Role: cfg.AssistantRole, Content: cc.FirstMsg},
		}
		logger.Warn("failed to load last agent chat;", "agent", cc.Role, "err", err, "new_history", history)
		addNewChat("")
	}
	chatBody.Messages = history
}

func charToStart(agentName string, keepSysP bool) bool {
	cc, ok := sysMap[agentName]
	if !ok {
		return false
	}
	applyCharCard(cc, keepSysP)
	return true
}

func updateModelLists() {
	var err error
	if cfg.OpenRouterToken != "" {
		ORFreeModels, err = fetchORModels(true)
		if err != nil {
			logger.Warn("failed to fetch or models", "error", err)
		}
	}
	// if llama.cpp started after gf-lt?
	localModelsMu.Lock()
	LocalModels, err = fetchLCPModelsWithLoadStatus()
	localModelsMu.Unlock()
	if err != nil {
		logger.Warn("failed to fetch llama.cpp models", "error", err)
	}
	// set already loaded model in llama.cpp
	if strings.Contains(cfg.CurrentAPI, "localhost") || strings.Contains(cfg.CurrentAPI, "127.0.0.1") {
		localModelsMu.Lock()
		defer localModelsMu.Unlock()
		for i := range LocalModels {
			if strings.Contains(LocalModels[i], models.LoadedMark) {
				m := strings.TrimPrefix(LocalModels[i], models.LoadedMark)
				cfg.CurrentModel = m
				chatBody.Model = m
				cachedModelColor = "green"
				updateStatusLine()
				app.Draw()
				return
			}
		}
	}
}

func refreshLocalModelsIfEmpty() {
	localModelsMu.RLock()
	if len(LocalModels) > 0 {
		localModelsMu.RUnlock()
		return
	}
	localModelsMu.RUnlock()
	// try to fetch
	models, err := fetchLCPModels()
	if err != nil {
		logger.Warn("failed to fetch llama.cpp models", "error", err)
		return
	}
	localModelsMu.Lock()
	LocalModels = models
	localModelsMu.Unlock()
}

func summarizeAndStartNewChat() {
	if len(chatBody.Messages) == 0 {
		_ = notifyUser("info", "No chat history to summarize")
		return
	}
	_ = notifyUser("info", "Summarizing chat history...")
	// Call the summarize_chat tool via agent
	summaryBytes := callToolWithAgent("summarize_chat", map[string]string{})
	summary := string(summaryBytes)
	if summary == "" {
		_ = notifyUser("error", "Failed to generate summary")
		return
	}
	// Start a new chat
	startNewChat(true)
	// Inject summary as a tool call response
	toolMsg := models.RoleMsg{
		Role:       cfg.ToolRole,
		Content:    summary,
		ToolCallID: "",
	}
	chatBody.Messages = append(chatBody.Messages, toolMsg)
	// Update UI
	textView.SetText(chatToText(chatBody.Messages, cfg.ShowSys))
	colorText()
	// Update storage
	if err := updateStorageChat(activeChatName, chatBody.Messages); err != nil {
		logger.Warn("failed to update storage after injecting summary", "error", err)
	}
	_ = notifyUser("info", "Chat summarized and new chat started with summary as tool response")
}

func init() {
	// ctx, cancel := context.WithCancel(context.Background())
	var err error
	cfg, err = config.LoadConfig("config.toml")
	if err != nil {
		fmt.Println("failed to load config.toml", err)
		cancel()
		os.Exit(1)
		return
	}
	defaultStarter = []models.RoleMsg{
		{Role: "system", Content: basicSysMsg},
		{Role: cfg.AssistantRole, Content: defaultFirstMsg},
	}
	logfile, err := os.OpenFile(cfg.LogFile,
		os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		slog.Error("failed to open log file", "error", err, "filename", cfg.LogFile)
		cancel()
		os.Exit(1)
		return
	}
	// load cards
	basicCard.Role = cfg.AssistantRole
	logLevel.Set(slog.LevelInfo)
	logger = slog.New(slog.NewTextHandler(logfile, &slog.HandlerOptions{Level: logLevel}))
	store = storage.NewProviderSQL(cfg.DBPATH, logger)
	if store == nil {
		cancel()
		os.Exit(1)
		return
	}
	ragger = rag.New(logger, store, cfg)
	// https://github.com/coreydaley/ggerganov-llama.cpp/blob/master/examples/server/README.md
	// load all chats in memory
	if _, err := loadHistoryChats(); err != nil {
		logger.Error("failed to load chat", "error", err)
		cancel()
		os.Exit(1)
		return
	}
	lastToolCall = &models.FuncCall{}
	lastChat := loadOldChatOrGetNew()
	chatBody = &models.ChatBody{
		Model:    "modelname",
		Stream:   true,
		Messages: lastChat,
	}
	choseChunkParser()
	httpClient = createClient(time.Second * 90)
	if cfg.TTS_ENABLED {
		orator = NewOrator(logger, cfg)
	}
	if cfg.STT_ENABLED {
		asr = NewSTT(logger, cfg)
	}
	// Initialize scrollToEndEnabled based on config
	scrollToEndEnabled = cfg.AutoScrollEnabled
	go updateModelLists()
	go chatWatcher(ctx)
}

func getValidKnowToRecipient(msg *models.RoleMsg) (string, bool) {
	if cfg == nil || !cfg.CharSpecificContextEnabled {
		return "", false
	}
	// case where all roles are in the tag => public message
	cr := listChatRoles()
	slices.Sort(cr)
	slices.Sort(msg.KnownTo)
	if slices.Equal(cr, msg.KnownTo) {
		logger.Info("got msg with tag mentioning every role")
		return "", false
	}
	// Check each character in the KnownTo list
	for _, recipient := range msg.KnownTo {
		if recipient == msg.Role || recipient == cfg.ToolRole {
			// weird cases, skip
			continue
		}
		// Skip if this is the user character (user handles their own turn)
		// If user is in KnownTo, stop processing - it's the user's turn
		if recipient == cfg.UserRole || recipient == cfg.WriteNextMsgAs {
			return "", false
		}
		return recipient, true
	}
	return "", false
}

// triggerPrivateMessageResponses checks if a message was sent privately to specific characters
// and triggers those non-user characters to respond
func triggerPrivateMessageResponses(msg *models.RoleMsg) {
	recipient, ok := getValidKnowToRecipient(msg)
	if !ok || recipient == "" {
		return
	}
	// Trigger the recipient character to respond
	triggerMsg := recipient + ":\n"
	// Send empty message so LLM continues naturally from the conversation
	crr := &models.ChatRoundReq{
		UserMsg: triggerMsg,
		Role:    recipient,
		Resume:  true,
	}
	fmt.Fprintf(textView, "\n[-:-:b](%d) ", len(chatBody.Messages))
	fmt.Fprint(textView, roleToIcon(recipient))
	fmt.Fprint(textView, "[-:-:-]\n")
	chatRoundChan <- crr
}