Repository navigation
Expand file tree
/
Copy pathPlatformAgentToolHandlers.java
More file actions
1625 lines (1535 loc) · 62 KB
/
Copy pathPlatformAgentToolHandlers.java
File metadata and controls
1625 lines (1535 loc) · 62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*******************************************************************************
* Copyright 2015 Defense Health Agency (DHA)
*
* If your use of this software does not include any GPLv2 components:
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ----------------------------------------------------------------------------
* If your use of this software includes any GPLv2 components:
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*******************************************************************************/
package prerna.reactor.agent.runtime;
import java.io.File;
import java.io.RandomAccessFile;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import java.util.stream.Stream;
import org.apache.commons.io.FilenameUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import prerna.auth.User;
import prerna.auth.utils.AbstractSecurityUtils;
import prerna.cluster.util.ClusterUtil;
import prerna.ds.node.NodeTranslator;
import prerna.ds.node.NodeUtils;
import prerna.ds.py.PyTranslator;
import prerna.ds.py.PyUtils;
import prerna.om.Insight;
import prerna.reactor.agent.AgentRunContext;
import prerna.reactor.agent.mcp.MCPUtility;
import prerna.reactor.agent.mcp.MCPUtility.MCPExecution;
import prerna.reactor.agent.skill.Skill;
import prerna.reactor.agent.skill.SkillScanner;
import prerna.reactor.agent.skill.SkillScanner.DiscoveredSkill;
import prerna.tcp.client.SocketClient;
import prerna.util.CmdExecUtil;
import prerna.util.Constants;
import prerna.util.FileSystemUtil;
import prerna.util.Utility;
import prerna.util.pptx.SemossPptxInspector;
final class PlatformAgentToolHandlers {
private static final Logger logger = LogManager.getLogger(PlatformAgentToolHandlers.class);
private static final String TOOL_KIND = "semoss_platform_default";
private static final int DEFAULT_READ_MAX_LINES = 2000;
private static final List<String> DOCLING_READ_EXTENSIONS = List.of("pdf", "docx", "pptx", "xlsx");
private static final int MAX_GLOB_RESULTS = 500;
private static final int DEFAULT_GREP_HEAD_LIMIT = 200;
private static final int MAX_MULTI_EDITS = 200;
private static final String TODOS_FILE = "todos.json";
private static final Set<String> VALID_TODO_STATUSES = Set.of("pending", "in_progress", "completed");
private static final Set<String> VALID_TODO_PRIORITIES = Set.of("high", "medium", "low");
private static final int MAX_TODO_CONTENT_LEN = 2000;
private static final int MAX_TODO_ID_LEN = 64;
private static final int MAX_TODO_ITEMS = 200;
private static final int DEFAULT_SKILL_MAX_BYTES = 8 * 1024;
private static final int HARD_SKILL_MAX_BYTES = 200 * 1024;
private static final int MAX_COMMAND_LENGTH = 4000;
private static final String PROP_ENABLE_BASH = "AGENT_DEFAULT_TOOLS_ENABLE_BASH";
private static final int MAX_PYTHON_CODE_LENGTH = 200_000;
private static final int MAX_PYTHON_OUTPUT_LENGTH = 40_000;
private static final int MAX_NODE_CODE_LENGTH = 200_000;
private static final int MAX_NODE_OUTPUT_LENGTH = 40_000;
private static final int DEFAULT_NODE_TIMEOUT_SECONDS = 60;
private static final int MAX_NODE_TIMEOUT_SECONDS = 600;
private static final String PARAM_PATH = "path";
private static final String PARAM_NEW_PATH = "new_path";
private static final Set<String> ALLOWED_COMMANDS = new HashSet<>(Arrays.asList("pwd", "ls", "dir", "find", "cat",
"head", "tail", "wc", "stat", "grep", "rg", "sed", "awk", "cut", "sort", "uniq", "tr", "diff", "python",
"python3", "mkdir", "touch", "cp", "mv", "curl", "wget", "zip", "unzip", "jq", "which"));
private PlatformAgentToolHandlers() {
}
static String describeAllowedCommands() {
return String.join(", ", ALLOWED_COMMANDS.stream().sorted().toList());
}
interface ToolHandler {
String getName();
JSONObject asToolDefinition();
String execute(Map<String, Object> params, AgentRunContext ctx) throws Exception;
}
static Map<String, ToolHandler> handlersByName() {
Map<String, ToolHandler> tools = new LinkedHashMap<>();
add(tools,
handler("InspectPptx",
"""
Render a PowerPoint through UnoServer and inspect its slides with a vision model using your review instructions. \
Returns structured issues, exact slide coverage, source hash and image/report paths. \
A pass requires status=complete and verdict=pass. Does not edit the source deck.\
""",
SemossPptxInspector.inputSchema(),
(params, tc) -> SemossPptxInspector.inspect(Path.of(tc.root), params, tc.ctx.getInsight(),
tc.ctx.getRoom().getId(), tc.ctx.getAgentConfig().getModelId()).toString()));
add(tools,
handler("ReadFile", """
Reads a file from the working directory. Returns content with line numbers \
and a continuation marker when more lines remain. PDF, DOCX, PPTX and XLSX files \
are returned as extracted Markdown text; other binary files are rejected.\
""",
objectSchema(
props(prop(PARAM_PATH, stringProp("Path to read, relative to the working directory.")),
prop("offset", integerProp("1-based first line to read. Defaults to 1.")),
prop("limit", integerProp("Maximum lines to return. Defaults to 2000."))),
List.of(PARAM_PATH)),
PlatformAgentToolHandlers::readFile));
add(tools, handler("WriteFile",
"Writes text to a file under the working directory, creating parent directories as needed.",
objectSchema(props(prop(PARAM_PATH, stringProp("Path to write, relative to the working directory.")),
prop("content", stringProp("Complete file content."))), List.of(PARAM_PATH, "content")),
PlatformAgentToolHandlers::writeFile));
add(tools, handler("EditFile",
"Performs one exact string replacement in a file. Fails if the old string is not unique unless replace_all=true.",
objectSchema(
props(prop(PARAM_PATH, stringProp("Path to edit, relative to the working directory.")),
prop("old_string", stringProp("Exact text to replace.")),
prop("new_string", stringProp("Replacement text.")),
prop("replace_all",
booleanProp("Replace every occurrence instead of requiring uniqueness."))),
List.of(PARAM_PATH, "old_string", "new_string")),
PlatformAgentToolHandlers::editFile));
add(tools,
handler("MultiEdit",
"Applies multiple exact string replacements to one file in a single all-or-nothing operation.",
objectSchema(
props(prop(PARAM_PATH, stringProp("Path to edit, relative to the working directory.")),
prop("edits_json",
stringProp(
"""
JSON array of edits: [{"old_string":"...","new_string":"...","replace_all":false}].\
"""))),
List.of(PARAM_PATH, "edits_json")),
PlatformAgentToolHandlers::multiEdit));
add(tools,
handler("MoveFile", "Moves or renames a path under the working directory.",
objectSchema(
props(prop(PARAM_PATH, stringProp("Existing path, relative to the working directory.")),
prop(PARAM_NEW_PATH,
stringProp("New path, relative to the working directory."))),
List.of(PARAM_PATH, PARAM_NEW_PATH)),
PlatformAgentToolHandlers::moveFile));
add(tools,
handler("DeleteFile", "Deletes a file or directory under the working directory.", objectSchema(
props(prop(PARAM_PATH, stringProp("Path to delete, relative to the working directory."))),
List.of(PARAM_PATH)), PlatformAgentToolHandlers::deleteFile));
add(tools,
handler("GlobFiles", "Finds files matching a glob pattern under the working directory.",
objectSchema(
props(prop("pattern", stringProp("Glob pattern such as **/*.java or src/**/*.ts.")),
prop("path", stringProp(
"Optional directory to search, relative to the working directory."))),
List.of("pattern")),
PlatformAgentToolHandlers::globFiles));
add(tools,
handler("GrepFiles", "Searches file contents with a regular expression.", objectSchema(
props(prop("pattern", stringProp("Regex pattern to search for.")),
prop("path", stringProp("Optional path to search, relative to the working directory.")),
prop("glob", stringProp("Optional file glob filter, such as *.java.")),
prop("output_mode", stringProp(
"files_with_matches, content, or count. Defaults to files_with_matches.")),
prop("after_context", integerProp("Lines after each match.")),
prop("before_context", integerProp("Lines before each match.")),
prop("context", integerProp("Lines before and after each match.")),
prop("case_insensitive", booleanProp("Case-insensitive matching.")),
prop("head_limit", integerProp("Maximum result lines. Defaults to 200."))),
List.of("pattern")), PlatformAgentToolHandlers::grepFiles));
add(tools,
handler("ListDirectory", "Lists directory contents under the working directory.", objectSchema(
props(prop("path", stringProp("Optional directory path. Defaults to working directory."))),
Collections.emptyList()), PlatformAgentToolHandlers::listDirectory));
if (isBashEnabled()) {
add(tools, handler("BashCommand", """
Executes one command in the working directory. Allowed commands: %s. \
One command per call: no pipes, chaining, redirects (including 2>&1), $(), or backticks. \
Use working-directory-relative paths; no absolute paths, ~ paths, or .. . \
node, npm, npx are not available here; use ExecuteNodeCode for JavaScript. \
Capture output via the tool result, not shell redirects.\
""".formatted(describeAllowedCommands()), objectSchema(props(prop("command", stringProp(
"Single command to execute. Shell chains, pipes, redirects, and command substitution are blocked.")),
prop("description", stringProp("Short reason for running the command."))), List.of("command")),
PlatformAgentToolHandlers::bashCommand));
}
if (isPythonToolEnabled()) {
add(tools, handler("ExecutePythonCode", """
Executes inline Python in the platform's managed Python runtime. Python state persists \
across calls in this room during the current login session while the managed worker \
remains alive; use files under ROOT for durable state. The bare ROOT and \
USER_ROOT variables are available with the same semantics as PyReactor: ROOT is the \
agent working directory and USER_ROOT is the authenticated user's asset-app root. \
APP_ROOT is additionally available when the insight has a current app context. \
For file I/O, import Path from pathlib and smss_get_runtime_var from smssutil, then use \
Path(smss_get_runtime_var("ROOT")) / "<filename>". Python's current directory may differ \
from ROOT; a relative Python filename is not proof of a room file. Verify outputs through \
working-directory file tools before claiming success. The value of the \
last expression is returned.\
""",
objectSchema(props(prop("code", stringProp("Inline Python source to execute."))), List.of("code")),
PlatformAgentToolHandlers::executePythonCode));
}
if (NodeUtils.isNodeToolEnabled()) {
add(tools, handler("ExecuteNodeCode", """
Executes JavaScript in the platform's isolated Node.js environment. State persists across \
calls in this room during the current login session while the managed worker remains \
alive. Put every require/const/let/class/function declaration \
inside a single (async () => { ... })(); top-level declarations collide with earlier calls. \
Use globalThis for durable state. Await all asynchronous work and return the result \
from inside the function; console output is captured too. ROOT is the working directory; \
APP_ROOT is the project's assets directory and USER_ROOT is the user's assets directory \
when available. Relative paths resolve to the working directory. Use path.join(ROOT, \
"<exact filename>") for output files. Bare require() resolves against curated packages: \
%s. There is no npm install.\
""".formatted(NodeUtils.describeCuratedPackages()), objectSchema(
props(prop("code", stringProp("JavaScript source to execute.")),
prop("timeout_seconds", integerProp(
"Maximum execution seconds before the run is killed. Defaults to 60, max 600."))),
List.of("code")), PlatformAgentToolHandlers::executeNodeCode));
}
add(tools, handler("TodoWrite", "Replaces the current todo list with a validated full-state JSON array.",
objectSchema(props(prop("items_json", stringProp("""
JSON array of todo items: [{"id":"...","content":"...",\
"status":"pending|in_progress|completed","priority":"high|medium|low"}].\
"""))), List.of("items_json")), PlatformAgentToolHandlers::todoWrite));
add(tools, handler("TodoRead", "Reads the current todo list from todos.json in the working directory.",
objectSchema(new LinkedHashMap<>(), Collections.emptyList()), PlatformAgentToolHandlers::todoRead));
add(tools, handler("ListSkill", """
Rescans the working directory for skills and returns each name, path, and description. \
The available_skills block in the system prompt already lists the same set, so use \
this only to pick up a skill created or attached partway through the run.\
""", objectSchema(new LinkedHashMap<>(), Collections.emptyList()),
PlatformAgentToolHandlers::listSkill));
add(tools,
handler("LoadSkill", """
Loads a named skill's instructions so you can follow them. Call this before starting work \
the skill covers, rather than working from memory -- a skill exists because that \
task is unreliable to get right by guessing. Returns up to max_bytes and reports \
what remains; call again with offset to read the rest. A skill's other files are \
listed at the end of its body and load the same way, by folder-relative path.\
""",
objectSchema(
props(prop("skill_name", stringProp("""
Skill folder name, such as "app-bootstrap", to load that skill's \
instructions. To load one of its other files instead, append that \
file's path as the skill's own docs write it, such as \
"app-bootstrap/references/react-app.md".\
""")), prop("offset", integerProp("Byte offset to start at. Defaults to 0.")),
prop("max_bytes", integerProp("Maximum bytes to return. Defaults to 8192."))),
List.of("skill_name")),
PlatformAgentToolHandlers::loadSkill));
return Collections.unmodifiableMap(tools);
}
private static void add(Map<String, ToolHandler> tools, ToolHandler handler) {
tools.put(handler.getName(), handler);
}
private static ToolHandler handler(String name, String description, JSONObject inputSchema, ToolExecutor executor) {
return new ToolHandler() {
@Override
public String getName() {
return name;
}
@Override
public JSONObject asToolDefinition() {
JSONObject tool = new JSONObject();
tool.put("name", name);
tool.put("title", MCPUtility.formatToTitleCase(name));
tool.put("description", description);
tool.put("inputSchema", inputSchema);
JSONObject meta = new JSONObject();
meta.put("SMSS_TOOL_KIND", TOOL_KIND);
meta.put(MCPUtility.SMSS_MCP_EXECUTION, MCPExecution.AUTO.getValue());
tool.put("_meta", meta);
return tool;
}
@Override
public String execute(Map<String, Object> params, AgentRunContext ctx) throws Exception {
return executor.execute(params != null ? params : Collections.emptyMap(), toolContext(ctx));
}
};
}
private static ToolContext toolContext(AgentRunContext ctx) {
if (ctx == null) {
throw new IllegalArgumentException("Agent run context is required");
}
String workingDir = ctx.getAgentConfig() != null ? ctx.getAgentConfig().getWorkingDir() : null;
if ((workingDir == null || workingDir.trim().isEmpty()) && ctx.getInsight() != null) {
workingDir = ctx.getInsight().getInsightFolder();
}
if (workingDir == null || workingDir.trim().isEmpty()) {
throw new IllegalArgumentException("Agent working directory is not set");
}
return new ToolContext(ctx, normalizePath(workingDir));
}
private static String readFile(Map<String, Object> params, ToolContext tc) throws Exception {
String filePath = stringParam(params, PARAM_PATH);
if (filePath == null || filePath.trim().isEmpty()) {
return "Error: path is required";
}
int offset = parseIntOr(params.get("offset"), 1);
int limit = parseIntOr(params.get("limit"), DEFAULT_READ_MAX_LINES);
if (offset < 1) {
offset = 1;
}
if (limit < 1) {
limit = DEFAULT_READ_MAX_LINES;
}
File file = tc.resolve(filePath);
if (!file.exists()) {
return "Error: file not found: " + filePath;
}
if (!file.isFile()) {
return "Error: not a file: " + filePath;
}
String content;
String extension = FilenameUtils.getExtension(file.getName()).toLowerCase(Locale.ROOT);
if (DOCLING_READ_EXTENSIONS.contains(extension)) {
// office/pdf files are zips or binary; read them as markdown via docling
try {
content = extractDocumentMarkdown(file, tc);
} catch (Exception e) {
logger.warn("ReadFile document extraction failed for " + filePath, e);
return "Error: could not extract text from " + filePath + ": " + lastLine(e.getMessage());
}
} else {
byte[] bytes = Files.readAllBytes(file.toPath());
content = decodeTextOrNull(bytes);
if (content == null) {
return "Error: " + filePath + " is a binary file (" + bytes.length
+ " bytes); ReadFile only returns text. Supported documents: "
+ String.join(", ", DOCLING_READ_EXTENSIONS) + ".";
}
}
List<String> lines = content.lines().toList();
int start = offset - 1;
if (start >= lines.size()) {
return "";
}
int end = Math.min(start + limit, lines.size());
StringBuilder sb = new StringBuilder();
for (int i = start; i < end; i++) {
sb.append(String.format("%6d\t%s%n", i + 1, lines.get(i)));
}
if (end < lines.size()) {
sb.append(String.format("%n[--- file continues: showing lines %d-%d of %d; continue with offset=%d. ---]%n",
start + 1, end, lines.size(), end + 1));
}
return sb.toString();
}
// strict utf-8 decode; null for binary (nul bytes or invalid utf-8)
private static String decodeTextOrNull(byte[] bytes) {
for (int i = 0, n = Math.min(bytes.length, 8192); i < n; i++) {
if (bytes[i] == 0) {
return null;
}
}
try {
return StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT).decode(ByteBuffer.wrap(bytes)).toString();
} catch (CharacterCodingException e) {
return null;
}
}
// runs smssutil.get_document_markdown in the room's python process
private static String extractDocumentMarkdown(File file, ToolContext tc) throws Exception {
if (!isPythonToolEnabled()) {
throw new IllegalStateException("Document extraction requires Python, which is disabled on this instance.");
}
if (tc.ctx.getInsight() == null || tc.ctx.getInsight().getUser() == null) {
throw new IllegalStateException("no user is associated with this agent run");
}
// pass the path as base64 so no quoting/escaping can break the script
String encodedPath = Base64.getEncoder()
.encodeToString(file.getAbsolutePath().getBytes(StandardCharsets.UTF_8));
String script = "from smssutil import get_document_markdown as _smss_doc_md\n" + "import base64 as _smss_b64\n"
+ "print(_smss_doc_md(_smss_b64.b64decode('" + encodedPath + "').decode('utf-8')), end='')";
Insight executionInsight = tc.ctx.getInsight();
User user = executionInsight.getUser();
Object output = AgentCodeExecutionContext.executeForRoom(tc.ctx.getRoom(), executionInsight, tc.root,
roomInsight -> {
SocketClient sc = user.getPythonSocketClient(true);
PyTranslator translator = new PyTranslator(sc, roomInsight);
try {
return translator.runScript(script);
} catch (RuntimeException e) {
interruptRoomExecutionIfCancelled(sc, roomInsight, tc.ctx);
throw e;
}
});
return output == null ? "" : output.toString();
}
private static String lastLine(String message) {
if (message == null || message.isBlank()) {
return "extraction failed";
}
String[] lines = message.strip().split("\\R");
return lines[lines.length - 1].strip();
}
private static String writeFile(Map<String, Object> params, ToolContext tc) {
String filePath = stringParam(params, PARAM_PATH);
String content = stringParam(params, "content");
if (filePath == null || filePath.trim().isEmpty()) {
return "Error: path is required";
}
File file = tc.resolve(filePath);
tc.requireWritable(file);
saveTextFile(file, content, tc);
return "Wrote file: " + tc.toRelative(file.getAbsolutePath());
}
private static String editFile(Map<String, Object> params, ToolContext tc) throws Exception {
String filePath = stringParam(params, PARAM_PATH);
if (filePath == null || filePath.trim().isEmpty()) {
return "Error: path is required";
}
String oldString = stringParam(params, "old_string");
String newString = stringParam(params, "new_string");
boolean replaceAll = parseBoolean(params.get("replace_all"));
if (oldString == null || oldString.isEmpty()) {
return "Error: old_string must not be empty";
}
if (newString == null) {
newString = "";
}
File file = tc.resolve(filePath);
tc.requireWritable(file);
if (!file.exists() || !file.isFile()) {
return "Error: file not found: " + filePath;
}
String content = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
int occurrences = countOccurrences(content, oldString);
if (occurrences == 0) {
return "Error: old_string not found in file: " + filePath;
}
if (!replaceAll && occurrences > 1) {
return "Error: old_string appears " + occurrences + " times in " + filePath
+ ". Provide more surrounding context to make it unique, or use replace_all=true.";
}
String updated = replaceAll ? content.replace(oldString, newString)
: content.replaceFirst(Pattern.quote(oldString), Matcher.quoteReplacement(newString));
saveTextFile(file, updated, tc);
return "Replaced " + occurrences + " occurrence(s) in: " + tc.toRelative(file.getAbsolutePath());
}
private static String multiEdit(Map<String, Object> params, ToolContext tc) throws Exception {
String filePath = stringParam(params, PARAM_PATH);
if (filePath == null || filePath.trim().isEmpty()) {
return "Error: path is required";
}
String editsJson = stringParam(params, "edits_json");
if (editsJson == null || editsJson.trim().isEmpty()) {
return "Error: edits_json is required";
}
JSONArray edits;
try {
edits = new JSONArray(editsJson.trim());
} catch (Exception e) {
return "Error: edits_json must be a valid JSON array - " + e.getMessage();
}
if (edits.length() == 0) {
return "Error: edits_json must contain at least one edit";
}
if (edits.length() > MAX_MULTI_EDITS) {
return "Error: too many edits (" + edits.length() + " > " + MAX_MULTI_EDITS + ")";
}
File file = tc.resolve(filePath);
tc.requireWritable(file);
if (!file.exists() || !file.isFile()) {
return "Error: file not found: " + filePath;
}
String working = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
int totalReplacements = 0;
for (int i = 0; i < edits.length(); i++) {
JSONObject edit;
try {
edit = edits.getJSONObject(i);
} catch (Exception e) {
return "Error: edits[" + i + "] is not an object";
}
String oldString = optString(edit, "old_string");
String newString = optString(edit, "new_string");
boolean replaceAll = edit.optBoolean("replace_all", false);
if (oldString == null || oldString.isEmpty()) {
return "Error: edits[" + i + "].old_string is required and must not be empty";
}
if (newString == null) {
newString = "";
}
if (oldString.equals(newString)) {
return "Error: edits[" + i + "].old_string and new_string are identical";
}
int occurrences = countOccurrences(working, oldString);
if (occurrences == 0) {
return "Error: edits[" + i + "].old_string not found"
+ (i > 0 ? " (note: edits apply in order; an earlier edit may have changed this text)" : "");
}
if (!replaceAll && occurrences > 1) {
return "Error: edits[" + i + "].old_string appears " + occurrences + " times. "
+ "Provide more surrounding context to make it unique, or set replace_all=true.";
}
working = replaceAll ? working.replace(oldString, newString)
: working.replaceFirst(Pattern.quote(oldString), Matcher.quoteReplacement(newString));
totalReplacements += occurrences;
}
saveTextFile(file, working, tc);
return "Applied " + edits.length() + " edit(s) (" + totalReplacements + " replacement(s)) to: "
+ tc.toRelative(file.getAbsolutePath());
}
private static String moveFile(Map<String, Object> params, ToolContext tc) throws Exception {
String filePath = stringParam(params, PARAM_PATH);
String newValue = stringParam(params, PARAM_NEW_PATH);
if (filePath == null || filePath.trim().isEmpty()) {
return "Error: path is required";
}
if (newValue == null || newValue.trim().isEmpty()) {
return "Error: new_path is required";
}
File source = tc.resolve(filePath);
File target = tc.resolve(newValue);
tc.requireWritable(source);
tc.requireWritable(target);
if (!source.exists()) {
return "Error: file not found: " + filePath;
}
File parent = target.getParentFile();
if (parent != null && !parent.exists()) {
parent.mkdirs();
}
Files.move(source.toPath(), target.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING);
pushRoom(tc);
return "Moved " + tc.toRelative(source.getAbsolutePath()) + " to " + tc.toRelative(target.getAbsolutePath());
}
private static String deleteFile(Map<String, Object> params, ToolContext tc) throws Exception {
String filePath = stringParam(params, PARAM_PATH);
if (filePath == null || filePath.trim().isEmpty()) {
return "Error: path is required";
}
File target = tc.resolve(filePath);
tc.requireWritable(target);
if (!target.exists()) {
return "Error: path not found: " + filePath;
}
deleteTree(target.toPath());
pushRoom(tc);
return "Deleted: " + filePath;
}
private static String globFiles(Map<String, Object> params, ToolContext tc) throws Exception {
String pattern = stringParam(params, "pattern");
String basePath = stringParam(params, "path");
File baseDir = tc.resolve(basePath);
if (!baseDir.exists() || !baseDir.isDirectory()) {
return "Error: directory not found: " + (basePath != null ? basePath : ".");
}
PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);
List<Path> matches = new ArrayList<>();
try (Stream<Path> paths = Files.walk(baseDir.toPath())) {
paths.filter(p -> !Files.isDirectory(p)).filter(p -> {
Path rel = baseDir.toPath().relativize(p);
return matcher.matches(rel) || matcher.matches(p.getFileName());
}).limit(MAX_GLOB_RESULTS).forEach(matches::add);
}
if (matches.isEmpty()) {
return "No files matched pattern: " + pattern;
}
matches.sort(Comparator.comparingLong(p -> {
try {
return -Files.getLastModifiedTime(p).toMillis();
} catch (Exception e) {
return 0L;
}
}));
List<String> results = new ArrayList<>();
for (Path p : matches) {
results.add(tc.toRelative(p.toAbsolutePath().toString()));
}
return String.join("\n", results);
}
private static String grepFiles(Map<String, Object> params, ToolContext tc) throws Exception {
String patternStr = stringParam(params, "pattern");
String basePath = stringParam(params, "path");
String glob = stringParam(params, "glob");
String outputMode = stringParam(params, "output_mode");
if (outputMode == null || outputMode.trim().isEmpty()) {
outputMode = "files_with_matches";
}
int after = parseIntOr(params.get("after_context"), 0);
int before = parseIntOr(params.get("before_context"), 0);
int context = parseIntOr(params.get("context"), 0);
if (context > 0) {
after = context;
before = context;
}
int headLimit = parseIntOr(params.get("head_limit"), DEFAULT_GREP_HEAD_LIMIT);
if (headLimit <= 0) {
headLimit = DEFAULT_GREP_HEAD_LIMIT;
}
int flags = parseBoolean(params.get("case_insensitive")) ? Pattern.CASE_INSENSITIVE : 0;
Pattern regex;
try {
regex = Pattern.compile(patternStr, flags);
} catch (PatternSyntaxException e) {
return "Error: invalid regex pattern: " + e.getMessage();
}
File baseDir = tc.resolve(basePath);
if (!baseDir.exists()) {
return "Error: path not found: " + (basePath != null ? basePath : ".");
}
PathMatcher fileMatcher = (glob != null && !glob.trim().isEmpty())
? FileSystems.getDefault().getPathMatcher("glob:" + glob.trim())
: null;
boolean isFilesMode = "files_with_matches".equals(outputMode);
boolean isCountMode = "count".equals(outputMode);
List<String> results = new ArrayList<>();
List<Path> paths = new ArrayList<>();
try (Stream<Path> walk = Files.walk(baseDir.toPath())) {
walk.filter(p -> !Files.isDirectory(p)).filter(p -> fileMatcher == null
|| fileMatcher.matches(p.getFileName()) || fileMatcher.matches(baseDir.toPath().relativize(p)))
.sorted().forEach(paths::add);
}
for (Path p : paths) {
if (results.size() >= headLimit) {
break;
}
try {
String content = new String(Files.readAllBytes(p), StandardCharsets.UTF_8);
String[] lines = content.split("\n", -1);
String relPath = tc.toRelative(p.toAbsolutePath().toString());
if (isFilesMode) {
for (String line : lines) {
if (regex.matcher(line).find()) {
results.add(relPath);
break;
}
}
} else if (isCountMode) {
long count = 0;
for (String line : lines) {
if (regex.matcher(line).find()) {
count++;
}
}
if (count > 0) {
results.add(relPath + ":" + count);
}
} else {
addContentMatches(results, regex, lines, relPath, before, after, headLimit);
}
} catch (Exception ignored) {
// skip unreadable files
}
}
return results.isEmpty() ? "No matches found for: " + patternStr : String.join("\n", results);
}
private static String listDirectory(Map<String, Object> params, ToolContext tc) {
String path = stringParam(params, "path");
File dir = tc.resolve(path);
if (!dir.exists()) {
return "Error: directory not found: " + (path != null ? path : ".");
}
if (!dir.isDirectory()) {
return "Error: not a directory: " + path;
}
File[] files = dir.listFiles();
if (files == null || files.length == 0) {
return "(empty directory)";
}
Arrays.sort(files, (a, b) -> {
if (a.isDirectory() != b.isDirectory()) {
return a.isDirectory() ? -1 : 1;
}
return a.getName().compareToIgnoreCase(b.getName());
});
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
StringBuilder sb = new StringBuilder();
for (File f : files) {
String type = f.isDirectory() ? "DIR " : "FILE";
String size = f.isDirectory() ? " " : String.format("%9d", f.length());
sb.append(String.format("%s %s %s %s%n", type, sdf.format(new java.util.Date(f.lastModified())), size,
f.getName()));
}
return sb.toString().trim();
}
private static String bashCommand(Map<String, Object> params, ToolContext tc) {
if (!isBashEnabled()) {
return "Error: BashCommand is disabled. Enable CHROOT_ENABLE or " + PROP_ENABLE_BASH + " to use it.";
}
String command = stringParam(params, "command");
String description = stringParam(params, "description");
if (command == null || command.trim().isEmpty()) {
return "Error: command is required";
}
command = command.trim();
if (command.length() > MAX_COMMAND_LENGTH) {
return "Error: command exceeds maximum length of " + MAX_COMMAND_LENGTH;
}
String validationError = validateCommand(command);
if (validationError != null) {
return "Error: " + validationError;
}
if (description != null && !description.trim().isEmpty()) {
logger.info("[BashCommand] [{}] executing: {}", description, command);
} else {
logger.info("[BashCommand] executing: {}", command);
}
CmdExecUtil cmdUtil = tc.ctx.getInsight().getCmdUtil();
if (cmdUtil == null) {
cmdUtil = new CmdExecUtil(tc.ctx.getInsight().getUser(), tc.ctx.getInsight().getInsightId(), tc.root);
}
if (!isWithinRoot(normalizePath(cmdUtil.getWorkingDir()), tc.root)) {
cmdUtil.setWorkingDir(tc.root);
}
String[] commandResult = cmdUtil.executeCommandWithStatus(command);
String output = commandResult[1];
if (!Boolean.parseBoolean(commandResult[0])) {
output = "Error: " + (output == null || output.isBlank() ? "Command failed" : output);
}
String updatedDir = normalizePath(cmdUtil.getWorkingDir());
if (!isWithinRoot(updatedDir, tc.root)) {
cmdUtil.setWorkingDir(tc.root);
throw new IllegalArgumentException("Command attempted to navigate outside the working directory sandbox.");
}
return output == null ? "" : output;
}
private static String executePythonCode(Map<String, Object> params, ToolContext tc) {
if (!isPythonToolEnabled()) {
return "Error: ExecutePythonCode is disabled on this instance.";
}
String code = stringParam(params, "code");
if (code == null || code.trim().isEmpty()) {
return "Error: code is required";
}
if (code.length() > MAX_PYTHON_CODE_LENGTH) {
return "Error: code exceeds maximum length of " + MAX_PYTHON_CODE_LENGTH;
}
if (tc.ctx.getInsight() == null || tc.ctx.getInsight().getUser() == null) {
return "Error: no user is associated with this agent run";
}
try {
Insight executionInsight = tc.ctx.getInsight();
User user = executionInsight.getUser();
Object output = AgentCodeExecutionContext.executeForRoom(tc.ctx.getRoom(), executionInsight, tc.root,
roomInsight -> {
SocketClient sc = user.getPythonSocketClient(true);
PyTranslator translator = new PyTranslator(sc, roomInsight);
try {
return translator.runScript(code);
} catch (RuntimeException e) {
interruptRoomExecutionIfCancelled(sc, roomInsight, tc.ctx);
throw e;
}
});
return formatPythonOutput(output);
} catch (Exception e) {
logger.warn("ExecutePythonCode failed", e);
String message = e.getMessage() != null ? e.getMessage() : e.toString();
return "Error: " + message;
}
}
private static String formatPythonOutput(Object output) {
String formatted;
if (output == null || "\"\"".equals(output)) {
formatted = "(no output)";
} else if (output instanceof String) {
formatted = (String) output;
} else {
try {
formatted = JSONObject.valueToString(output);
} catch (Exception e) {
formatted = output.toString();
}
}
if (formatted.length() > MAX_PYTHON_OUTPUT_LENGTH) {
String marker = "\n[output truncated at " + MAX_PYTHON_OUTPUT_LENGTH + " characters]";
return formatted.substring(0, MAX_PYTHON_OUTPUT_LENGTH - marker.length()) + marker;
}
return formatted;
}
private static String executeNodeCode(Map<String, Object> params, ToolContext tc) {
if (!NodeUtils.isNodeToolEnabled()) {
return "Error: ExecuteNodeCode is disabled on this instance.";
}
String code = stringParam(params, "code");
if (code == null || code.trim().isEmpty()) {
return "Error: code is required";
}
if (code.length() > MAX_NODE_CODE_LENGTH) {
return "Error: code exceeds maximum length of " + MAX_NODE_CODE_LENGTH;
}
int timeoutSeconds = parseIntOr(params.get("timeout_seconds"), DEFAULT_NODE_TIMEOUT_SECONDS);
if (timeoutSeconds < 1) {
timeoutSeconds = DEFAULT_NODE_TIMEOUT_SECONDS;
}
if (timeoutSeconds > MAX_NODE_TIMEOUT_SECONDS) {
timeoutSeconds = MAX_NODE_TIMEOUT_SECONDS;
}
User user = tc.ctx.getInsight().getUser();
if (user == null) {
return "Error: no user is associated with this agent run";
}
try {
Insight executionInsight = tc.ctx.getInsight();
long timeoutMs = timeoutSeconds * 1000L;
Object output = AgentCodeExecutionContext.executeForRoom(tc.ctx.getRoom(), executionInsight, tc.root,
roomInsight -> {
SocketClient sc = user.getNodeSocketClient(true);
NodeTranslator translator = new NodeTranslator(sc, roomInsight);
try {
return translator.runScript(executionInsight, code, timeoutMs, tc.root);
} catch (RuntimeException e) {
interruptRoomExecutionIfCancelled(sc, roomInsight, tc.ctx);
throw e;
}
});
return formatNodeOutput(output);
} catch (Exception e) {
logger.warn("ExecuteNodeCode failed", e);
String message = e.getMessage() != null ? e.getMessage() : e.toString();
return "Error: " + message;
}
}
private static void interruptRoomExecutionIfCancelled(SocketClient socketClient, Insight roomInsight,
AgentRunContext ctx) {
if (!Thread.currentThread().isInterrupted()) {
return;
}
try {
socketClient.interruptInsightJob(roomInsight.getInsightId(), ctx.getRunId());
} catch (RuntimeException e) {
logger.warn("Failed to interrupt managed code execution for room '{}' and run '{}'", ctx.getRoom().getId(),
ctx.getRunId(), e);
}
}
private static String formatNodeOutput(Object output) {
String stdout = null;
Object result = output;
if (output instanceof Map) {
Map<?, ?> map = (Map<?, ?>) output;
Object stdoutValue = map.get("stdout");
stdout = stdoutValue != null ? stdoutValue.toString() : null;
result = map.get("result");
}
StringBuilder sb = new StringBuilder();
if (stdout != null && !stdout.isEmpty()) {
sb.append(stdout);
}
if (result != null) {
if (sb.length() > 0) {
sb.append("\n\n=> ");
} else {
sb.append("=> ");
}
if (result instanceof String) {
sb.append((String) result);
} else {
try {
sb.append(JSONObject.valueToString(result));
} catch (Exception e) {
sb.append(result.toString());
}
}
}
if (sb.length() == 0) {
return "(no output)";
}
if (sb.length() > MAX_NODE_OUTPUT_LENGTH) {
return sb.substring(0, MAX_NODE_OUTPUT_LENGTH) + "\n[output truncated at " + MAX_NODE_OUTPUT_LENGTH
+ " characters]";
}
return sb.toString();
}
private static String todoWrite(Map<String, Object> params, ToolContext tc) {
String itemsJson = stringParam(params, "items_json");
if (itemsJson == null || itemsJson.trim().isEmpty()) {
return "Error: items_json is required";
}
JSONArray items;
try {
items = new JSONArray(itemsJson.trim());
} catch (Exception e) {
return "Error: items_json must be a valid JSON array - " + e.getMessage();
}
if (items.length() > MAX_TODO_ITEMS) {
return "Error: too many items (" + items.length() + " > " + MAX_TODO_ITEMS + ")";
}
Set<String> seenIds = new HashSet<>();
int pending = 0;
int inProgress = 0;
int completed = 0;
JSONArray validated = new JSONArray();
for (int i = 0; i < items.length(); i++) {
JSONObject raw;
try {
raw = items.getJSONObject(i);
} catch (Exception e) {
return "Error: items[" + i + "] is not an object";
}
String id = optTrimmed(raw, "id");
String content = optTrimmed(raw, "content");
String status = optTrimmed(raw, "status");
String priority = optTrimmed(raw, "priority");
String error = validateTodoItem(i, id, content, status, priority, seenIds);
if (error != null) {
return error;
}
if ("pending".equals(status)) {
pending++;
} else if ("in_progress".equals(status)) {
inProgress++;
} else if ("completed".equals(status)) {
completed++;
}
JSONObject clean = new JSONObject();
clean.put("id", id);
clean.put("content", content);
clean.put("status", status);
if (priority != null && !priority.isEmpty()) {
clean.put("priority", priority);
}
validated.put(clean);
}
JSONObject doc = new JSONObject();
doc.put("updated_at", Instant.now().toString());
doc.put("items", validated);
saveTextFile(tc.resolve(TODOS_FILE), doc.toString(2), tc);
return String.format("Wrote %d todo(s): %d pending, %d in_progress, %d completed", validated.length(), pending,
inProgress, completed);
}
private static String todoRead(Map<String, Object> params, ToolContext tc) throws Exception {