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
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
|
package main
import (
"context"
"encoding/json"
"fmt"
"gf-lt/agent"
"gf-lt/models"
"io"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"time"
"gf-lt/rag"
"github.com/GrailFinder/searchagent/searcher"
)
var (
toolCallRE = regexp.MustCompile(`__tool_call__\s*([\s\S]*?)__tool_call__`)
quotesRE = regexp.MustCompile(`(".*?")`)
starRE = regexp.MustCompile(`(\*.*?\*)`)
thinkRE = regexp.MustCompile(`(<think>\s*([\s\S]*?)</think>)`)
codeBlockRE = regexp.MustCompile(`(?s)\x60{3}(?:.*?)\n(.*?)\n\s*\x60{3}\s*`)
singleBacktickRE = regexp.MustCompile(`\x60([^\x60]*)\x60`)
roleRE = regexp.MustCompile(`^(\w+):`)
rpDefenitionSysMsg = `
For this roleplay immersion is at most importance.
Every character thinks and acts based on their personality and setting of the roleplay.
Meta discussions outside of roleplay is allowed if clearly labeled as out of character, for example: (ooc: {msg}) or <ooc>{msg}</ooc>.
`
basicSysMsg = `Large Language Model that helps user with any of his requests.`
toolSysMsg = `You can do functions call if needed.
Your current tools:
<tools>
[
{
"name":"recall",
"args": ["topic"],
"when_to_use": "when asked about topic that user previously asked to memorise"
},
{
"name":"memorise",
"args": ["topic", "data"],
"when_to_use": "when asked to memorise information under a topic"
},
{
"name":"recall_topics",
"args": [],
"when_to_use": "to see what topics are saved in memory"
},
{
"name":"websearch",
"args": ["query", "limit"],
"when_to_use": "when asked to search the web for information; returns clean summary without html,css and other web elements; limit is optional (default 3)"
},
{
"name":"rag_search",
"args": ["query", "limit"],
"when_to_use": "when asked to search the local document database for information; performs query refinement, semantic search, reranking, and synthesis; returns clean summary with sources; limit is optional (default 3)"
},
{
"name":"read_url",
"args": ["url"],
"when_to_use": "when asked to get content for specific webpage or url; returns clean summary without html,css and other web elements"
},
{
"name":"read_url_raw",
"args": ["url"],
"when_to_use": "when asked to get content for specific webpage or url; returns raw data as is without processing"
},
{
"name":"file_create",
"args": ["path", "content"],
"when_to_use": "when asked to create a new file with optional content"
},
{
"name":"file_read",
"args": ["path"],
"when_to_use": "when asked to read the content of a file"
},
{
"name":"file_read_image",
"args": ["path"],
"when_to_use": "when asked to read or view an image file"
},
{
"name":"file_write",
"args": ["path", "content"],
"when_to_use": "when needed to overwrite content to a file"
},
{
"name":"file_write_append",
"args": ["path", "content"],
"when_to_use": "when asked to append content to a file; use sed to edit content"
},
{
"name":"file_edit",
"args": ["path", "oldString", "newString", "lineNumber"],
"when_to_use": "when you need to make targeted changes to a specific section of a file without rewriting the entire file; lineNumber is optional - if provided, only edits that specific line; if not provided, replaces all occurrences of oldString"
},
{
"name":"file_delete",
"args": ["path"],
"when_to_use": "when asked to delete a file"
},
{
"name":"file_move",
"args": ["src", "dst"],
"when_to_use": "when asked to move a file from source to destination"
},
{
"name":"file_copy",
"args": ["src", "dst"],
"when_to_use": "when asked to copy a file from source to destination"
},
{
"name":"file_list",
"args": ["path"],
"when_to_use": "when asked to list files in a directory; path is optional (default: current directory)"
},
{
"name":"execute_command",
"args": ["command", "args"],
"when_to_use": "when asked to execute a system command; args is optional; allowed commands: grep, sed, awk, find, cat, head, tail, sort, uniq, wc, ls, echo, cut, tr, cp, mv, rm, mkdir, rmdir, pwd, df, free, ps, top, du, whoami, date, uname, go"
}
]
</tools>
To make a function call return a json object within __tool_call__ tags;
<example_request>
__tool_call__
{
"name":"recall",
"args": {"topic": "Adam's number"}
}
__tool_call__
</example_request>
<example_request>
__tool_call__
{
"name":"execute_command",
"args": {"command": "ls", "args": "-la /home"}
}
__tool_call__
</example_request>
Tool call is addressed to the tool agent, avoid sending more info than tool call itself, while making a call.
When done right, tool call will be delivered to the tool agent. tool agent will respond with the results of the call.
<example_response>
tool:
under the topic: Adam's number is stored:
559-996
</example_response>
After that you are free to respond to the user.
`
webSearchSysPrompt = `Summarize the web search results, extracting key information and presenting a concise answer. Provide sources and URLs where relevant.`
ragSearchSysPrompt = `Synthesize the document search results, extracting key information and presenting a concise answer. Provide sources and document IDs where relevant.`
readURLSysPrompt = `Extract and summarize the content from the webpage. Provide key information, main points, and any relevant details.`
summarySysPrompt = `Please provide a concise summary of the following conversation. Focus on key points, decisions, and actions. Provide only the summary, no additional commentary.`
basicCard = &models.CharCard{
SysPrompt: basicSysMsg,
FirstMsg: defaultFirstMsg,
Role: "",
FilePath: "",
}
sysMap = map[string]*models.CharCard{"basic_sys": basicCard}
sysLabels = []string{"basic_sys"}
webAgentClient *agent.AgentClient
webAgentClientOnce sync.Once
webAgentsOnce sync.Once
)
var windowToolSysMsg = `
Additional window tools (available only if xdotool and maim are installed):
[
{
"name":"list_windows",
"args": [],
"when_to_use": "when asked to list visible windows; returns map of window ID to window name"
},
{
"name":"capture_window",
"args": ["window"],
"when_to_use": "when asked to take a screenshot of a specific window; saves to /tmp; window can be ID or name substring; returns file path"
},
{
"name":"capture_window_and_view",
"args": ["window"],
"when_to_use": "when asked to take a screenshot of a specific window and show it; saves to /tmp and returns image for viewing; window can be ID or name substring"
}
]
`
var WebSearcher searcher.WebSurfer
var (
windowToolsAvailable bool
xdotoolPath string
maimPath string
modelHasVision bool
)
func init() {
sa, err := searcher.NewWebSurfer(searcher.SearcherTypeScraper, "")
if err != nil {
panic("failed to init seachagent; error: " + err.Error())
}
WebSearcher = sa
if err := rag.Init(cfg, logger, store); err != nil {
logger.Warn("failed to init rag; rag_search tool will not be available", "error", err)
}
checkWindowTools()
registerWindowTools()
}
func checkWindowTools() {
xdotoolPath, _ = exec.LookPath("xdotool")
maimPath, _ = exec.LookPath("maim")
windowToolsAvailable = xdotoolPath != "" && maimPath != ""
if windowToolsAvailable {
logger.Info("window tools available: xdotool and maim found")
} else {
if xdotoolPath == "" {
logger.Warn("xdotool not found, window listing tools will not be available")
}
if maimPath == "" {
logger.Warn("maim not found, window capture tools will not be available")
}
}
}
func UpdateToolCapabilities() {
if !cfg.ToolUse {
return
}
modelHasVision = false
if cfg == nil || cfg.CurrentAPI == "" {
logger.Warn("cannot determine model capabilities: cfg or CurrentAPI is nil")
registerWindowTools()
return
}
prevHasVision := modelHasVision
modelHasVision = ModelHasVision(cfg.CurrentAPI, cfg.CurrentModel)
if modelHasVision {
logger.Info("model has vision support", "model", cfg.CurrentModel, "api", cfg.CurrentAPI)
} else {
logger.Info("model does not have vision support", "model", cfg.CurrentModel, "api", cfg.CurrentAPI)
if windowToolsAvailable && !prevHasVision && !modelHasVision {
_ = notifyUser("window tools", "Window capture-and-view unavailable: model lacks vision support")
}
}
registerWindowTools()
}
// getWebAgentClient returns a singleton AgentClient for web agents.
func getWebAgentClient() *agent.AgentClient {
webAgentClientOnce.Do(func() {
if cfg == nil {
panic("cfg not initialized")
}
if logger == nil {
panic("logger not initialized")
}
getToken := func() string {
if chunkParser == nil {
return ""
}
return chunkParser.GetToken()
}
webAgentClient = agent.NewAgentClient(cfg, *logger, getToken)
})
return webAgentClient
}
// registerWebAgents registers WebAgentB instances for websearch and read_url tools.
func registerWebAgents() {
webAgentsOnce.Do(func() {
client := getWebAgentClient()
// Register rag_search agent
agent.Register("rag_search", agent.NewWebAgentB(client, ragSearchSysPrompt))
// Register websearch agent
agent.Register("websearch", agent.NewWebAgentB(client, webSearchSysPrompt))
// Register read_url agent
agent.Register("read_url", agent.NewWebAgentB(client, readURLSysPrompt))
// Register summarize_chat agent
agent.Register("summarize_chat", agent.NewWebAgentB(client, summarySysPrompt))
})
}
// web search (depends on extra server)
func websearch(args map[string]string) []byte {
// make http request return bytes
query, ok := args["query"]
if !ok || query == "" {
msg := "query not provided to web_search tool"
logger.Error(msg)
return []byte(msg)
}
limitS, ok := args["limit"]
if !ok || limitS == "" {
limitS = "3"
}
limit, err := strconv.Atoi(limitS)
if err != nil || limit == 0 {
logger.Warn("websearch limit; passed bad value; setting to default (3)",
"limit_arg", limitS, "error", err)
limit = 3
}
resp, err := WebSearcher.Search(context.Background(), query, limit)
if err != nil {
msg := "search tool failed; error: " + err.Error()
logger.Error(msg)
return []byte(msg)
}
data, err := json.Marshal(resp)
if err != nil {
msg := "failed to marshal search result; error: " + err.Error()
logger.Error(msg)
return []byte(msg)
}
return data
}
// rag search (searches local document database)
func ragsearch(args map[string]string) []byte {
query, ok := args["query"]
if !ok || query == "" {
msg := "query not provided to rag_search tool"
logger.Error(msg)
return []byte(msg)
}
limitS, ok := args["limit"]
if !ok || limitS == "" {
limitS = "3"
}
limit, err := strconv.Atoi(limitS)
if err != nil || limit == 0 {
logger.Warn("ragsearch limit; passed bad value; setting to default (3)",
"limit_arg", limitS, "error", err)
limit = 3
}
ragInstance := rag.GetInstance()
if ragInstance == nil {
msg := "rag not initialized; rag_search tool is not available"
logger.Error(msg)
return []byte(msg)
}
results, err := ragInstance.Search(query, limit)
if err != nil {
msg := "rag search failed; error: " + err.Error()
logger.Error(msg)
return []byte(msg)
}
data, err := json.Marshal(results)
if err != nil {
msg := "failed to marshal rag search result; error: " + err.Error()
logger.Error(msg)
return []byte(msg)
}
return data
}
// web search raw (returns raw data without processing)
func websearchRaw(args map[string]string) []byte {
// make http request return bytes
query, ok := args["query"]
if !ok || query == "" {
msg := "query not provided to websearch_raw tool"
logger.Error(msg)
return []byte(msg)
}
limitS, ok := args["limit"]
if !ok || limitS == "" {
limitS = "3"
}
limit, err := strconv.Atoi(limitS)
if err != nil || limit == 0 {
logger.Warn("websearch_raw limit; passed bad value; setting to default (3)",
"limit_arg", limitS, "error", err)
limit = 3
}
resp, err := WebSearcher.Search(context.Background(), query, limit)
if err != nil {
msg := "search tool failed; error: " + err.Error()
logger.Error(msg)
return []byte(msg)
}
// Return raw response without any processing
return []byte(fmt.Sprintf("%+v", resp))
}
// retrieves url content (text)
func readURL(args map[string]string) []byte {
// make http request return bytes
link, ok := args["url"]
if !ok || link == "" {
msg := "link not provided to read_url tool"
logger.Error(msg)
return []byte(msg)
}
resp, err := WebSearcher.RetrieveFromLink(context.Background(), link)
if err != nil {
msg := "search tool failed; error: " + err.Error()
logger.Error(msg)
return []byte(msg)
}
data, err := json.Marshal(resp)
if err != nil {
msg := "failed to marshal search result; error: " + err.Error()
logger.Error(msg)
return []byte(msg)
}
return data
}
// retrieves url content raw (returns raw content without processing)
func readURLRaw(args map[string]string) []byte {
// make http request return bytes
link, ok := args["url"]
if !ok || link == "" {
msg := "link not provided to read_url_raw tool"
logger.Error(msg)
return []byte(msg)
}
resp, err := WebSearcher.RetrieveFromLink(context.Background(), link)
if err != nil {
msg := "search tool failed; error: " + err.Error()
logger.Error(msg)
return []byte(msg)
}
// Return raw response without any processing
return []byte(fmt.Sprintf("%+v", resp))
}
/*
consider cases:
- append mode (treat it like a journal appendix)
- replace mode (new info/mind invalidates old ones)
also:
- some writing can be done without consideration of previous data;
- others do;
*/
func memorise(args map[string]string) []byte {
agent := cfg.AssistantRole
if len(args) < 2 {
msg := "not enough args to call memorise tool; need topic and data to remember"
logger.Error(msg)
return []byte(msg)
}
memory := &models.Memory{
Agent: agent,
Topic: args["topic"],
Mind: args["data"],
UpdatedAt: time.Now(),
CreatedAt: time.Now(),
}
if _, err := store.Memorise(memory); err != nil {
logger.Error("failed to save memory", "err", err, "memoory", memory)
return []byte("failed to save info")
}
msg := "info saved under the topic:" + args["topic"]
return []byte(msg)
}
func recall(args map[string]string) []byte {
agent := cfg.AssistantRole
if len(args) < 1 {
logger.Warn("not enough args to call recall tool")
return nil
}
mind, err := store.Recall(agent, args["topic"])
if err != nil {
msg := fmt.Sprintf("failed to recall; error: %v; args: %v", err, args)
logger.Error(msg)
return []byte(msg)
}
answer := fmt.Sprintf("under the topic: %s is stored:\n%s", args["topic"], mind)
return []byte(answer)
}
func recallTopics(args map[string]string) []byte {
agent := cfg.AssistantRole
topics, err := store.RecallTopics(agent)
if err != nil {
logger.Error("failed to use tool", "error", err, "args", args)
return nil
}
joinedS := strings.Join(topics, ";")
return []byte(joinedS)
}
// File Manipulation Tools
func fileCreate(args map[string]string) []byte {
path, ok := args["path"]
if !ok || path == "" {
msg := "path not provided to file_create tool"
logger.Error(msg)
return []byte(msg)
}
path = resolvePath(path)
content, ok := args["content"]
if !ok {
content = ""
}
if err := writeStringToFile(path, content); err != nil {
msg := "failed to create file; error: " + err.Error()
logger.Error(msg)
return []byte(msg)
}
msg := "file created successfully at " + path
return []byte(msg)
}
func fileRead(args map[string]string) []byte {
path, ok := args["path"]
if !ok || path == "" {
msg := "path not provided to file_read tool"
logger.Error(msg)
return []byte(msg)
}
path = resolvePath(path)
content, err := readStringFromFile(path)
if err != nil {
msg := "failed to read file; error: " + err.Error()
logger.Error(msg)
return []byte(msg)
}
result := map[string]string{
"content": content,
"path": path,
}
jsonResult, err := json.Marshal(result)
if err != nil {
msg := "failed to marshal result; error: " + err.Error()
logger.Error(msg)
return []byte(msg)
}
return jsonResult
}
func fileReadImage(args map[string]string) []byte {
path, ok := args["path"]
if !ok || path == "" {
msg := "path not provided to file_read_image tool"
logger.Error(msg)
return []byte(msg)
}
path = resolvePath(path)
dataURL, err := models.CreateImageURLFromPath(path)
if err != nil {
msg := "failed to read image; error: " + err.Error()
logger.Error(msg)
return []byte(msg)
}
// result := map[string]any{
// "type": "multimodal_content",
// "parts": []map[string]string{
// {"type": "text", "text": "Image at " + path},
// {"type": "image_url", "url": dataURL},
// },
// }
result := models.MultimodalToolResp{
Type: "multimodal_content",
Parts: []map[string]string{
{"type": "text", "text": "Image at " + path},
{"type": "image_url", "url": dataURL},
},
}
jsonResult, err := json.Marshal(result)
if err != nil {
msg := "failed to marshal result; error: " + err.Error()
logger.Error(msg)
return []byte(msg)
}
return jsonResult
}
func fileWrite(args map[string]string) []byte {
path, ok := args["path"]
if !ok || path == "" {
msg := "path not provided to file_write tool"
logger.Error(msg)
return []byte(msg)
}
path = resolvePath(path)
content, ok := args["content"]
if !ok {
content = ""
}
if err := writeStringToFile(path, content); err != nil {
msg := "failed to write to file; error: " + err.Error()
logger.Error(msg)
return []byte(msg)
}
msg := "file written successfully at " + path
return []byte(msg)
}
func fileWriteAppend(args map[string]string) []byte {
path, ok := args["path"]
if !ok || path == "" {
msg := "path not provided to file_write_append tool"
logger.Error(msg)
return []byte(msg)
}
path = resolvePath(path)
content, ok := args["content"]
if !ok {
content = ""
}
if err := appendStringToFile(path, content); err != nil {
msg := "failed to append to file; error: " + err.Error()
logger.Error(msg)
return []byte(msg)
}
msg := "file written successfully at " + path
return []byte(msg)
}
func fileEdit(args map[string]string) []byte {
path, ok := args["path"]
if !ok || path == "" {
msg := "path not provided to file_edit tool"
logger.Error(msg)
return []byte(msg)
}
path = resolvePath(path)
oldString, ok := args["oldString"]
if !ok || oldString == "" {
msg := "oldString not provided to file_edit tool"
logger.Error(msg)
return []byte(msg)
}
newString, ok := args["newString"]
if !ok {
newString = ""
}
lineNumberStr, hasLineNumber := args["lineNumber"]
// Read file content
content, err := os.ReadFile(path)
if err != nil {
msg := "failed to read file: " + err.Error()
logger.Error(msg)
return []byte(msg)
}
fileContent := string(content)
var replacementCount int
if hasLineNumber && lineNumberStr != "" {
// Line-number based edit
lineNum, err := strconv.Atoi(lineNumberStr)
if err != nil {
msg := "invalid lineNumber: must be a valid integer"
logger.Error(msg)
return []byte(msg)
}
lines := strings.Split(fileContent, "\n")
if lineNum < 1 || lineNum > len(lines) {
msg := fmt.Sprintf("lineNumber %d out of range (file has %d lines)", lineNum, len(lines))
logger.Error(msg)
return []byte(msg)
}
// Find oldString in the specific line
targetLine := lines[lineNum-1]
if !strings.Contains(targetLine, oldString) {
msg := fmt.Sprintf("oldString not found on line %d", lineNum)
logger.Error(msg)
return []byte(msg)
}
lines[lineNum-1] = strings.Replace(targetLine, oldString, newString, 1)
replacementCount = 1
fileContent = strings.Join(lines, "\n")
} else {
// Replace all occurrences
if !strings.Contains(fileContent, oldString) {
msg := "oldString not found in file"
logger.Error(msg)
return []byte(msg)
}
fileContent = strings.ReplaceAll(fileContent, oldString, newString)
replacementCount = strings.Count(fileContent, newString)
}
if err := os.WriteFile(path, []byte(fileContent), 0644); err != nil {
msg := "failed to write file: " + err.Error()
logger.Error(msg)
return []byte(msg)
}
msg := fmt.Sprintf("file edited successfully at %s (%d replacement(s))", path, replacementCount)
return []byte(msg)
}
func fileDelete(args map[string]string) []byte {
path, ok := args["path"]
if !ok || path == "" {
msg := "path not provided to file_delete tool"
logger.Error(msg)
return []byte(msg)
}
path = resolvePath(path)
if err := removeFile(path); err != nil {
msg := "failed to delete file; error: " + err.Error()
logger.Error(msg)
return []byte(msg)
}
msg := "file deleted successfully at " + path
return []byte(msg)
}
func fileMove(args map[string]string) []byte {
src, ok := args["src"]
if !ok || src == "" {
msg := "source path not provided to file_move tool"
logger.Error(msg)
return []byte(msg)
}
src = resolvePath(src)
dst, ok := args["dst"]
if !ok || dst == "" {
msg := "destination path not provided to file_move tool"
logger.Error(msg)
return []byte(msg)
}
dst = resolvePath(dst)
if err := moveFile(src, dst); err != nil {
msg := "failed to move file; error: " + err.Error()
logger.Error(msg)
return []byte(msg)
}
msg := fmt.Sprintf("file moved successfully from %s to %s", src, dst)
return []byte(msg)
}
func fileCopy(args map[string]string) []byte {
src, ok := args["src"]
if !ok || src == "" {
msg := "source path not provided to file_copy tool"
logger.Error(msg)
return []byte(msg)
}
src = resolvePath(src)
dst, ok := args["dst"]
if !ok || dst == "" {
msg := "destination path not provided to file_copy tool"
logger.Error(msg)
return []byte(msg)
}
dst = resolvePath(dst)
if err := copyFile(src, dst); err != nil {
msg := "failed to copy file; error: " + err.Error()
logger.Error(msg)
return []byte(msg)
}
msg := fmt.Sprintf("file copied successfully from %s to %s", src, dst)
return []byte(msg)
}
func fileList(args map[string]string) []byte {
path, ok := args["path"]
if !ok || path == "" {
path = "." // default to current directory
}
path = resolvePath(path)
files, err := listDirectory(path)
if err != nil {
msg := "failed to list directory; error: " + err.Error()
logger.Error(msg)
return []byte(msg)
}
result := map[string]interface{}{
"directory": path,
"files": files,
}
jsonResult, err := json.Marshal(result)
if err != nil {
msg := "failed to marshal result; error: " + err.Error()
logger.Error(msg)
return []byte(msg)
}
return jsonResult
}
// Helper functions for file operations
func resolvePath(p string) string {
if filepath.IsAbs(p) {
return p
}
return filepath.Join(cfg.FilePickerDir, p)
}
func readStringFromFile(filename string) (string, error) {
data, err := os.ReadFile(filename)
if err != nil {
return "", err
}
return string(data), nil
}
func writeStringToFile(filename string, data string) error {
return os.WriteFile(filename, []byte(data), 0644)
}
func appendStringToFile(filename string, data string) error {
file, err := os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return err
}
defer file.Close()
_, err = file.WriteString(data)
return err
}
func removeFile(filename string) error {
return os.Remove(filename)
}
func moveFile(src, dst string) error {
// First try with os.Rename (works within same filesystem)
if err := os.Rename(src, dst); err == nil {
return nil
}
// If that fails (e.g., cross-filesystem), copy and delete
return copyAndRemove(src, dst)
}
func copyFile(src, dst string) error {
srcFile, err := os.Open(src)
if err != nil {
return err
}
defer srcFile.Close()
dstFile, err := os.Create(dst)
if err != nil {
return err
}
defer dstFile.Close()
_, err = io.Copy(dstFile, srcFile)
return err
}
func copyAndRemove(src, dst string) error {
// Copy the file
if err := copyFile(src, dst); err != nil {
return err
}
// Remove the source file
return os.Remove(src)
}
func listDirectory(path string) ([]string, error) {
entries, err := os.ReadDir(path)
if err != nil {
return nil, err
}
var files []string
for _, entry := range entries {
if entry.IsDir() {
files = append(files, entry.Name()+"/") // Add "/" to indicate directory
} else {
files = append(files, entry.Name())
}
}
return files, nil
}
// Command Execution Tool
func executeCommand(args map[string]string) []byte {
commandStr := args["command"]
if commandStr == "" {
msg := "command not provided to execute_command tool"
logger.Error(msg)
return []byte(msg)
}
// Handle commands passed as single string with spaces (e.g., "go run main.go" or "cd /tmp")
// Split into base command and arguments
parts := strings.Fields(commandStr)
if len(parts) == 0 {
msg := "command not provided to execute_command tool"
logger.Error(msg)
return []byte(msg)
}
command := parts[0]
cmdArgs := parts[1:]
if !isCommandAllowed(command, cmdArgs...) {
msg := fmt.Sprintf("command '%s' is not allowed", command)
logger.Error(msg)
return []byte(msg)
}
// Special handling for cd command - update FilePickerDir
if command == "cd" {
return handleCdCommand(cmdArgs)
}
// Execute with timeout for safety
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, command, cmdArgs...)
cmd.Dir = cfg.FilePickerDir
output, err := cmd.CombinedOutput()
if err != nil {
msg := fmt.Sprintf("command '%s' failed; error: %v; output: %s", command, err, string(output))
logger.Error(msg)
return []byte(msg)
}
// Check if output is empty and return success message
if len(output) == 0 {
successMsg := fmt.Sprintf("command '%s' executed successfully and exited with code 0", commandStr)
return []byte(successMsg)
}
return output
}
// handleCdCommand handles the cd command to update FilePickerDir
func handleCdCommand(args []string) []byte {
var targetDir string
if len(args) == 0 {
// cd with no args goes to home directory
homeDir, err := os.UserHomeDir()
if err != nil {
msg := "cd: cannot determine home directory: " + err.Error()
logger.Error(msg)
return []byte(msg)
}
targetDir = homeDir
} else {
targetDir = args[0]
}
// Resolve relative paths against current FilePickerDir
if !filepath.IsAbs(targetDir) {
targetDir = filepath.Join(cfg.FilePickerDir, targetDir)
}
// Verify the directory exists
info, err := os.Stat(targetDir)
if err != nil {
msg := "cd: " + targetDir + ": " + err.Error()
logger.Error(msg)
return []byte(msg)
}
if !info.IsDir() {
msg := "cd: " + targetDir + ": not a directory"
logger.Error(msg)
return []byte(msg)
}
// Update FilePickerDir
absDir, err := filepath.Abs(targetDir)
if err != nil {
msg := "cd: failed to resolve path: " + err.Error()
logger.Error(msg)
return []byte(msg)
}
cfg.FilePickerDir = absDir
msg := "FilePickerDir changed to: " + absDir
return []byte(msg)
}
// Helper functions for command execution
// Todo structure
type TodoItem struct {
ID string `json:"id"`
Task string `json:"task"`
Status string `json:"status"` // "pending", "in_progress", "completed"
}
type TodoList struct {
Items []TodoItem `json:"items"`
}
func (t TodoList) ToString() string {
sb := strings.Builder{}
for i := range t.Items {
fmt.Fprintf(&sb, "\n[%s] %s. %s\n", t.Items[i].Status, t.Items[i].ID, t.Items[i].Task)
}
return sb.String()
}
// Global todo list storage
var globalTodoList = TodoList{
Items: []TodoItem{},
}
// Todo Management Tools
func todoCreate(args map[string]string) []byte {
task, ok := args["task"]
if !ok || task == "" {
msg := "task not provided to todo_create tool"
logger.Error(msg)
return []byte(msg)
}
// Generate simple ID
id := fmt.Sprintf("todo_%d", len(globalTodoList.Items)+1)
newItem := TodoItem{
ID: id,
Task: task,
Status: "pending",
}
globalTodoList.Items = append(globalTodoList.Items, newItem)
result := map[string]string{
"message": "todo created successfully",
"id": id,
"task": task,
"status": "pending",
"todos": globalTodoList.ToString(),
}
jsonResult, err := json.Marshal(result)
if err != nil {
msg := "failed to marshal result; error: " + err.Error()
logger.Error(msg)
return []byte(msg)
}
return jsonResult
}
func todoRead(args map[string]string) []byte {
// Return all todos if no ID specified
result := map[string]interface{}{
"todos": globalTodoList.ToString(),
}
jsonResult, err := json.Marshal(result)
if err != nil {
msg := "failed to marshal result; error: " + err.Error()
logger.Error(msg)
return []byte(msg)
}
return jsonResult
}
func todoUpdate(args map[string]string) []byte {
id, ok := args["id"]
if !ok || id == "" {
msg := "id not provided to todo_update tool"
logger.Error(msg)
return []byte(msg)
}
task, taskOk := args["task"]
status, statusOk := args["status"]
if !taskOk && !statusOk {
msg := "neither task nor status provided to todo_update tool"
logger.Error(msg)
return []byte(msg)
}
// Find and update the todo
for i, item := range globalTodoList.Items {
if item.ID == id {
if taskOk {
globalTodoList.Items[i].Task = task
}
if statusOk {
// Validate status
if status == "pending" || status == "in_progress" || status == "completed" {
globalTodoList.Items[i].Status = status
} else {
result := map[string]string{
"error": "status must be one of: pending, in_progress, completed",
}
jsonResult, err := json.Marshal(result)
if err != nil {
msg := "failed to marshal result; error: " + err.Error()
logger.Error(msg)
return []byte(msg)
}
return jsonResult
}
}
result := map[string]string{
"message": "todo updated successfully",
"id": id,
"todos": globalTodoList.ToString(),
}
jsonResult, err := json.Marshal(result)
if err != nil {
msg := "failed to marshal result; error: " + err.Error()
logger.Error(msg)
return []byte(msg)
}
return jsonResult
}
}
// ID not found
result := map[string]string{
"error": fmt.Sprintf("todo with id %s not found", id),
}
jsonResult, err := json.Marshal(result)
if err != nil {
msg := "failed to marshal result; error: " + err.Error()
logger.Error(msg)
return []byte(msg)
}
return jsonResult
}
func todoDelete(args map[string]string) []byte {
id, ok := args["id"]
if !ok || id == "" {
msg := "id not provided to todo_delete tool"
logger.Error(msg)
return []byte(msg)
}
// Find and remove the todo
for i, item := range globalTodoList.Items {
if item.ID == id {
// Remove item from slice
globalTodoList.Items = append(globalTodoList.Items[:i], globalTodoList.Items[i+1:]...)
result := map[string]string{
"message": "todo deleted successfully",
"id": id,
"todos": globalTodoList.ToString(),
}
jsonResult, err := json.Marshal(result)
if err != nil {
msg := "failed to marshal result; error: " + err.Error()
logger.Error(msg)
return []byte(msg)
}
return jsonResult
}
}
// ID not found
result := map[string]string{
"error": fmt.Sprintf("todo with id %s not found", id),
}
jsonResult, err := json.Marshal(result)
if err != nil {
msg := "failed to marshal result; error: " + err.Error()
logger.Error(msg)
return []byte(msg)
}
return jsonResult
}
var gitReadSubcommands = map[string]bool{
"status": true,
"log": true,
"diff": true,
"show": true,
"branch": true,
"reflog": true,
"rev-parse": true,
"shortlog": true,
"describe": true,
}
func isCommandAllowed(command string, args ...string) bool {
allowedCommands := map[string]bool{
"cd": true,
"grep": true,
"sed": true,
"awk": true,
"find": true,
"cat": true,
"head": true,
"tail": true,
"sort": true,
"uniq": true,
"wc": true,
"ls": true,
"echo": true,
"cut": true,
"tr": true,
"cp": true,
"mv": true,
"rm": true,
"mkdir": true,
"rmdir": true,
"pwd": true,
"df": true,
"free": true,
"ps": true,
"top": true,
"du": true,
"whoami": true,
"date": true,
"uname": true,
"git": true,
"go": true,
}
// Allow all go subcommands (go run, go mod tidy, go test, etc.)
if strings.HasPrefix(command, "go ") && allowedCommands["go"] {
return true
}
if command == "git" && len(args) > 0 {
return gitReadSubcommands[args[0]]
}
if !allowedCommands[command] {
return false
}
return true
}
func summarizeChat(args map[string]string) []byte {
if len(chatBody.Messages) == 0 {
return []byte("No chat history to summarize.")
}
// Format chat history for the agent
chatText := chatToText(chatBody.Messages, true) // include system and tool messages
return []byte(chatText)
}
func windowIDToHex(decimalID string) string {
id, err := strconv.ParseInt(decimalID, 10, 64)
if err != nil {
return decimalID
}
return fmt.Sprintf("0x%x", id)
}
func listWindows(args map[string]string) []byte {
if !windowToolsAvailable {
return []byte("window tools not available: xdotool or maim not found")
}
cmd := exec.Command(xdotoolPath, "search", "--name", ".")
output, err := cmd.Output()
if err != nil {
msg := "failed to list windows: " + err.Error()
logger.Error(msg)
return []byte(msg)
}
windowIDs := strings.Fields(string(output))
windows := make(map[string]string)
for _, id := range windowIDs {
id = strings.TrimSpace(id)
if id == "" {
continue
}
nameCmd := exec.Command(xdotoolPath, "getwindowname", id)
nameOutput, err := nameCmd.Output()
if err != nil {
continue
}
name := strings.TrimSpace(string(nameOutput))
windows[id] = name
}
data, err := json.Marshal(windows)
if err != nil {
msg := "failed to marshal window list: " + err.Error()
logger.Error(msg)
return []byte(msg)
}
return data
}
func captureWindow(args map[string]string) []byte {
if !windowToolsAvailable {
return []byte("window tools not available: xdotool or maim not found")
}
window, ok := args["window"]
if !ok || window == "" {
return []byte("window parameter required (window ID or name)")
}
var windowID string
if _, err := strconv.Atoi(window); err == nil {
windowID = window
} else {
cmd := exec.Command(xdotoolPath, "search", "--name", window)
output, err := cmd.Output()
if err != nil || len(strings.Fields(string(output))) == 0 {
return []byte("window not found: " + window)
}
windowID = strings.Fields(string(output))[0]
}
nameCmd := exec.Command(xdotoolPath, "getwindowname", windowID)
nameOutput, _ := nameCmd.Output()
windowName := strings.TrimSpace(string(nameOutput))
windowName = regexp.MustCompile(`[^a-zA-Z]+`).ReplaceAllString(windowName, "")
if windowName == "" {
windowName = "window"
}
timestamp := time.Now().Unix()
filename := fmt.Sprintf("/tmp/%s_%d.jpg", windowName, timestamp)
cmd := exec.Command(maimPath, "-i", windowIDToHex(windowID), filename)
if err := cmd.Run(); err != nil {
msg := "failed to capture window: " + err.Error()
logger.Error(msg)
return []byte(msg)
}
return []byte("screenshot saved: " + filename)
}
func captureWindowAndView(args map[string]string) []byte {
if !windowToolsAvailable {
return []byte("window tools not available: xdotool or maim not found")
}
window, ok := args["window"]
if !ok || window == "" {
return []byte("window parameter required (window ID or name)")
}
var windowID string
if _, err := strconv.Atoi(window); err == nil {
windowID = window
} else {
cmd := exec.Command(xdotoolPath, "search", "--name", window)
output, err := cmd.Output()
if err != nil || len(strings.Fields(string(output))) == 0 {
return []byte("window not found: " + window)
}
windowID = strings.Fields(string(output))[0]
}
nameCmd := exec.Command(xdotoolPath, "getwindowname", windowID)
nameOutput, _ := nameCmd.Output()
windowName := strings.TrimSpace(string(nameOutput))
windowName = regexp.MustCompile(`[^a-zA-Z]+`).ReplaceAllString(windowName, "")
if windowName == "" {
windowName = "window"
}
timestamp := time.Now().Unix()
filename := fmt.Sprintf("/tmp/%s_%d.jpg", windowName, timestamp)
captureCmd := exec.Command(maimPath, "-i", windowIDToHex(windowID), filename)
if err := captureCmd.Run(); err != nil {
msg := "failed to capture window: " + err.Error()
logger.Error(msg)
return []byte(msg)
}
dataURL, err := models.CreateImageURLFromPath(filename)
if err != nil {
msg := "failed to create image URL: " + err.Error()
logger.Error(msg)
return []byte(msg)
}
result := models.MultimodalToolResp{
Type: "multimodal_content",
Parts: []map[string]string{
{"type": "text", "text": "Screenshot saved: " + filename},
{"type": "image_url", "url": dataURL},
},
}
jsonResult, err := json.Marshal(result)
if err != nil {
msg := "failed to marshal result: " + err.Error()
logger.Error(msg)
return []byte(msg)
}
return jsonResult
}
type fnSig func(map[string]string) []byte
var fnMap = map[string]fnSig{
"recall": recall,
"recall_topics": recallTopics,
"memorise": memorise,
"rag_search": ragsearch,
"websearch": websearch,
"websearch_raw": websearchRaw,
"read_url": readURL,
"read_url_raw": readURLRaw,
"file_create": fileCreate,
"file_read": fileRead,
"file_read_image": fileReadImage,
"file_write": fileWrite,
"file_write_append": fileWriteAppend,
"file_edit": fileEdit,
"file_delete": fileDelete,
"file_move": fileMove,
"file_copy": fileCopy,
"file_list": fileList,
"execute_command": executeCommand,
"todo_create": todoCreate,
"todo_read": todoRead,
"todo_update": todoUpdate,
"todo_delete": todoDelete,
"summarize_chat": summarizeChat,
}
func registerWindowTools() {
if windowToolsAvailable {
fnMap["list_windows"] = listWindows
fnMap["capture_window"] = captureWindow
windowTools := []models.Tool{
{
Type: "function",
Function: models.ToolFunc{
Name: "list_windows",
Description: "List all visible windows with their IDs and names. Returns a map of window ID to window name.",
Parameters: models.ToolFuncParams{
Type: "object",
Required: []string{},
Properties: map[string]models.ToolArgProps{},
},
},
},
{
Type: "function",
Function: models.ToolFunc{
Name: "capture_window",
Description: "Capture a screenshot of a specific window and save it to /tmp. Requires window parameter (window ID or name substring).",
Parameters: models.ToolFuncParams{
Type: "object",
Required: []string{"window"},
Properties: map[string]models.ToolArgProps{
"window": models.ToolArgProps{
Type: "string",
Description: "window ID or window name (partial match)",
},
},
},
},
},
}
if modelHasVision {
fnMap["capture_window_and_view"] = captureWindowAndView
windowTools = append(windowTools, models.Tool{
Type: "function",
Function: models.ToolFunc{
Name: "capture_window_and_view",
Description: "Capture a screenshot of a specific window, save it to /tmp, and return the image for viewing. Requires window parameter (window ID or name substring).",
Parameters: models.ToolFuncParams{
Type: "object",
Required: []string{"window"},
Properties: map[string]models.ToolArgProps{
"window": models.ToolArgProps{
Type: "string",
Description: "window ID or window name (partial match)",
},
},
},
},
})
}
baseTools = append(baseTools, windowTools...)
toolSysMsg += windowToolSysMsg
}
}
// callToolWithAgent calls the tool and applies any registered agent.
func callToolWithAgent(name string, args map[string]string) []byte {
registerWebAgents()
f, ok := fnMap[name]
if !ok {
return []byte(fmt.Sprintf("tool %s not found", name))
}
raw := f(args)
if a := agent.Get(name); a != nil {
return a.Process(args, raw)
}
return raw
}
// openai style def
var baseTools = []models.Tool{
// rag_search
models.Tool{
Type: "function",
Function: models.ToolFunc{
Name: "rag_search",
Description: "Search local document database given query, limit of sources (default 3). Performs query refinement, semantic search, reranking, and synthesis.",
Parameters: models.ToolFuncParams{
Type: "object",
Required: []string{"query", "limit"},
Properties: map[string]models.ToolArgProps{
"query": models.ToolArgProps{
Type: "string",
Description: "search query",
},
"limit": models.ToolArgProps{
Type: "string",
Description: "limit of the document results",
},
},
},
},
},
// websearch
models.Tool{
Type: "function",
Function: models.ToolFunc{
Name: "websearch",
Description: "Search web given query, limit of sources (default 3).",
Parameters: models.ToolFuncParams{
Type: "object",
Required: []string{"query", "limit"},
Properties: map[string]models.ToolArgProps{
"query": models.ToolArgProps{
Type: "string",
Description: "search query",
},
"limit": models.ToolArgProps{
Type: "string",
Description: "limit of the website results",
},
},
},
},
},
// read_url
models.Tool{
Type: "function",
Function: models.ToolFunc{
Name: "read_url",
Description: "Retrieves text content of given link, providing clean summary without html,css and other web elements.",
Parameters: models.ToolFuncParams{
Type: "object",
Required: []string{"url"},
Properties: map[string]models.ToolArgProps{
"url": models.ToolArgProps{
Type: "string",
Description: "link to the webpage to read text from",
},
},
},
},
},
// websearch_raw
models.Tool{
Type: "function",
Function: models.ToolFunc{
Name: "websearch_raw",
Description: "Search web given query, returning raw data as is without processing. Use when you need the raw response data instead of a clean summary.",
Parameters: models.ToolFuncParams{
Type: "object",
Required: []string{"query", "limit"},
Properties: map[string]models.ToolArgProps{
"query": models.ToolArgProps{
Type: "string",
Description: "search query",
},
"limit": models.ToolArgProps{
Type: "string",
Description: "limit of the website results",
},
},
},
},
},
// read_url_raw
models.Tool{
Type: "function",
Function: models.ToolFunc{
Name: "read_url_raw",
Description: "Retrieves raw content of given link without processing. Use when you need the raw response data instead of a clean summary.",
Parameters: models.ToolFuncParams{
Type: "object",
Required: []string{"url"},
Properties: map[string]models.ToolArgProps{
"url": models.ToolArgProps{
Type: "string",
Description: "link to the webpage to read text from",
},
},
},
},
},
// memorise
models.Tool{
Type: "function",
Function: models.ToolFunc{
Name: "memorise",
Description: "Save topic-data in key-value cache. Use when asked to remember something/keep in mind.",
Parameters: models.ToolFuncParams{
Type: "object",
Required: []string{"topic", "data"},
Properties: map[string]models.ToolArgProps{
"topic": models.ToolArgProps{
Type: "string",
Description: "topic is the key under which data is saved",
},
"data": models.ToolArgProps{
Type: "string",
Description: "data is the value that is saved under the topic-key",
},
},
},
},
},
// recall
models.Tool{
Type: "function",
Function: models.ToolFunc{
Name: "recall",
Description: "Recall topic-data from key-value cache. Use when precise info about the topic is needed.",
Parameters: models.ToolFuncParams{
Type: "object",
Required: []string{"topic"},
Properties: map[string]models.ToolArgProps{
"topic": models.ToolArgProps{
Type: "string",
Description: "topic is the key to recall data from",
},
},
},
},
},
// recall_topics
models.Tool{
Type: "function",
Function: models.ToolFunc{
Name: "recall_topics",
Description: "Recall all topics from key-value cache. Use when need to know what topics are currently stored in memory.",
Parameters: models.ToolFuncParams{
Type: "object",
Required: []string{},
Properties: map[string]models.ToolArgProps{},
},
},
},
// file_create
models.Tool{
Type: "function",
Function: models.ToolFunc{
Name: "file_create",
Description: "Create a new file with specified content. Use when you need to create a new file.",
Parameters: models.ToolFuncParams{
Type: "object",
Required: []string{"path"},
Properties: map[string]models.ToolArgProps{
"path": models.ToolArgProps{
Type: "string",
Description: "path where the file should be created",
},
"content": models.ToolArgProps{
Type: "string",
Description: "content to write to the file (optional, defaults to empty string)",
},
},
},
},
},
// file_read
models.Tool{
Type: "function",
Function: models.ToolFunc{
Name: "file_read",
Description: "Read the content of a file. Use when you need to see the content of a file.",
Parameters: models.ToolFuncParams{
Type: "object",
Required: []string{"path"},
Properties: map[string]models.ToolArgProps{
"path": models.ToolArgProps{
Type: "string",
Description: "path of the file to read",
},
},
},
},
},
// file_read_image
models.Tool{
Type: "function",
Function: models.ToolFunc{
Name: "file_read_image",
Description: "Read an image file and return it for multimodal LLM viewing. Supports png, jpg, jpeg, gif, webp formats. Use when you need the LLM to see and analyze an image.",
Parameters: models.ToolFuncParams{
Type: "object",
Required: []string{"path"},
Properties: map[string]models.ToolArgProps{
"path": models.ToolArgProps{
Type: "string",
Description: "path of the image file to read",
},
},
},
},
},
// file_write
models.Tool{
Type: "function",
Function: models.ToolFunc{
Name: "file_write",
Description: "Write content to a file. Will overwrite any content present.",
Parameters: models.ToolFuncParams{
Type: "object",
Required: []string{"path", "content"},
Properties: map[string]models.ToolArgProps{
"path": models.ToolArgProps{
Type: "string",
Description: "path of the file to write to",
},
"content": models.ToolArgProps{
Type: "string",
Description: "content to write to the file",
},
},
},
},
},
// file_write_append
models.Tool{
Type: "function",
Function: models.ToolFunc{
Name: "file_write_append",
Description: "Append content to a file.",
Parameters: models.ToolFuncParams{
Type: "object",
Required: []string{"path", "content"},
Properties: map[string]models.ToolArgProps{
"path": models.ToolArgProps{
Type: "string",
Description: "path of the file to write to",
},
"content": models.ToolArgProps{
Type: "string",
Description: "content to write to the file",
},
},
},
},
},
// file_edit
models.Tool{
Type: "function",
Function: models.ToolFunc{
Name: "file_edit",
Description: "Edit a specific section of a file by replacing oldString with newString. Use for targeted changes without rewriting the entire file.",
Parameters: models.ToolFuncParams{
Type: "object",
Required: []string{"path", "oldString", "newString"},
Properties: map[string]models.ToolArgProps{
"path": models.ToolArgProps{
Type: "string",
Description: "path of the file to edit",
},
"oldString": models.ToolArgProps{
Type: "string",
Description: "the exact string to find and replace",
},
"newString": models.ToolArgProps{
Type: "string",
Description: "the string to replace oldString with",
},
"lineNumber": models.ToolArgProps{
Type: "string",
Description: "optional line number (1-indexed) to edit - if provided, only that line is edited",
},
},
},
},
},
// file_delete
models.Tool{
Type: "function",
Function: models.ToolFunc{
Name: "file_delete",
Description: "Delete a file. Use when you need to remove a file.",
Parameters: models.ToolFuncParams{
Type: "object",
Required: []string{"path"},
Properties: map[string]models.ToolArgProps{
"path": models.ToolArgProps{
Type: "string",
Description: "path of the file to delete",
},
},
},
},
},
// file_move
models.Tool{
Type: "function",
Function: models.ToolFunc{
Name: "file_move",
Description: "Move a file from one location to another. Use when you need to relocate a file.",
Parameters: models.ToolFuncParams{
Type: "object",
Required: []string{"src", "dst"},
Properties: map[string]models.ToolArgProps{
"src": models.ToolArgProps{
Type: "string",
Description: "source path of the file to move",
},
"dst": models.ToolArgProps{
Type: "string",
Description: "destination path where the file should be moved",
},
},
},
},
},
// file_copy
models.Tool{
Type: "function",
Function: models.ToolFunc{
Name: "file_copy",
Description: "Copy a file from one location to another. Use when you need to duplicate a file.",
Parameters: models.ToolFuncParams{
Type: "object",
Required: []string{"src", "dst"},
Properties: map[string]models.ToolArgProps{
"src": models.ToolArgProps{
Type: "string",
Description: "source path of the file to copy",
},
"dst": models.ToolArgProps{
Type: "string",
Description: "destination path where the file should be copied",
},
},
},
},
},
// file_list
models.Tool{
Type: "function",
Function: models.ToolFunc{
Name: "file_list",
Description: "List files and directories in a directory. Use when you need to see what files are in a directory.",
Parameters: models.ToolFuncParams{
Type: "object",
Required: []string{},
Properties: map[string]models.ToolArgProps{
"path": models.ToolArgProps{
Type: "string",
Description: "path of the directory to list (optional, defaults to current directory)",
},
},
},
},
},
// execute_command
models.Tool{
Type: "function",
Function: models.ToolFunc{
Name: "execute_command",
Description: "Execute a shell command safely. Use when you need to run system commands like cd grep sed awk find cat head tail sort uniq wc ls echo cut tr cp mv rm mkdir rmdir pwd df free ps top du whoami date uname go git. Git is allowed for read-only operations: status, log, diff, show, branch, reflog, rev-parse, shortlog, describe. Use 'cd /path' to change working directory.",
Parameters: models.ToolFuncParams{
Type: "object",
Required: []string{"command"},
Properties: map[string]models.ToolArgProps{
"command": models.ToolArgProps{
Type: "string",
Description: "command to execute with arguments (e.g., 'go run main.go', 'ls -la /tmp', 'cd /home/user'). Use a single string; arguments should be space-separated after the command.",
},
},
},
},
},
// todo_create
models.Tool{
Type: "function",
Function: models.ToolFunc{
Name: "todo_create",
Description: "Create a new todo item with a task. Returns the created todo with its ID.",
Parameters: models.ToolFuncParams{
Type: "object",
Required: []string{"task"},
Properties: map[string]models.ToolArgProps{
"task": models.ToolArgProps{
Type: "string",
Description: "the task description to add to the todo list",
},
},
},
},
},
// todo_read
models.Tool{
Type: "function",
Function: models.ToolFunc{
Name: "todo_read",
Description: "Read todo items. Without ID returns all todos, with ID returns specific todo.",
Parameters: models.ToolFuncParams{
Type: "object",
Required: []string{},
Properties: map[string]models.ToolArgProps{
"id": models.ToolArgProps{
Type: "string",
Description: "optional id of the specific todo item to read",
},
},
},
},
},
// todo_update
models.Tool{
Type: "function",
Function: models.ToolFunc{
Name: "todo_update",
Description: "Update a todo item by ID with new task or status. Status must be one of: pending, in_progress, completed.",
Parameters: models.ToolFuncParams{
Type: "object",
Required: []string{"id"},
Properties: map[string]models.ToolArgProps{
"id": models.ToolArgProps{
Type: "string",
Description: "id of the todo item to update",
},
"task": models.ToolArgProps{
Type: "string",
Description: "new task description (optional)",
},
"status": models.ToolArgProps{
Type: "string",
Description: "new status: pending, in_progress, or completed (optional)",
},
},
},
},
},
// todo_delete
models.Tool{
Type: "function",
Function: models.ToolFunc{
Name: "todo_delete",
Description: "Delete a todo item by ID. Returns success message.",
Parameters: models.ToolFuncParams{
Type: "object",
Required: []string{"id"},
Properties: map[string]models.ToolArgProps{
"id": models.ToolArgProps{
Type: "string",
Description: "id of the todo item to delete",
},
},
},
},
},
}
func init() {
if windowToolsAvailable {
baseTools = append(baseTools,
models.Tool{
Type: "function",
Function: models.ToolFunc{
Name: "list_windows",
Description: "List all visible windows with their IDs and names. Returns a map of window ID to window name.",
Parameters: models.ToolFuncParams{
Type: "object",
Required: []string{},
Properties: map[string]models.ToolArgProps{},
},
},
},
models.Tool{
Type: "function",
Function: models.ToolFunc{
Name: "capture_window",
Description: "Capture a screenshot of a specific window and save it to /tmp. Requires window parameter (window ID or name substring).",
Parameters: models.ToolFuncParams{
Type: "object",
Required: []string{"window"},
Properties: map[string]models.ToolArgProps{
"window": models.ToolArgProps{
Type: "string",
Description: "window ID or window name (partial match)",
},
},
},
},
},
models.Tool{
Type: "function",
Function: models.ToolFunc{
Name: "capture_window_and_view",
Description: "Capture a screenshot of a specific window, save it to /tmp, and return the image for viewing. Requires window parameter (window ID or name substring).",
Parameters: models.ToolFuncParams{
Type: "object",
Required: []string{"window"},
Properties: map[string]models.ToolArgProps{
"window": models.ToolArgProps{
Type: "string",
Description: "window ID or window name (partial match)",
},
},
},
},
},
)
}
}
|