-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoder.go
More file actions
1232 lines (1086 loc) · 35.1 KB
/
coder.go
File metadata and controls
1232 lines (1086 loc) · 35.1 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
package main
import (
"bufio"
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"io/fs"
"log"
"net/http"
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
"time"
"github.com/anthropics/anthropic-sdk-go"
"github.com/anthropics/anthropic-sdk-go/option"
)
const (
defaultModelID = "claude-sonnet-4-6"
defaultModelName = "Sonnet 4.6"
defaultMaxTokens = int64(8192)
defaultTemp = 0.2
requestTimeout = 120 * time.Second
defaultListFilesMaxEntries = 500
hardListFilesMaxEntries = 2000
defaultReadFilesMaxBytes = 32_000
hardReadFilesMaxBytes = 256_000
defaultBashTimeoutSeconds = 30
hardBashTimeoutSeconds = 120
defaultBashMaxOutputBytes = 32_000
hardBashMaxOutputBytes = 256_000
maxToolRoundsPerTurn = 16
maxRepeatedToolFailures = 2
toolUseSystemPrompt = `You are a coding agent that can use filesystem and shell tools.
Use tools with strict JSON inputs that match each schema exactly.
- For creating a new file or replacing an entire file, use write_file.
- For targeted edits, use edit_file or edit_files with path, old_str, and new_str.
- Never call bash without a non-empty "command" field.
- If a tool returns an input-validation error, fix the JSON and retry with corrected arguments.`
userColor = "\x1b[38;2;102;178;255m"
claudeColor = "\x1b[38;2;217;119;6m"
toolColor = "\x1b[96m"
resultColor = "\x1b[92m"
errorColor = "\x1b[91m"
colorReset = "\x1b[0m"
)
var errListLimitReached = errors.New("list_files entry limit reached")
type Config struct {
APIKey string
ModelID string
ModelName string
Verbose bool
ColorOutput bool
}
type ToolDefinition struct {
Name string
Description string
InputSchema anthropic.ToolInputSchemaParam
Function func(input json.RawMessage) (string, error)
}
type ToolUse struct {
ID string
Name string
Input json.RawMessage
}
type ListFilesInput struct {
Path string `json:"path,omitempty"`
Recursive *bool `json:"recursive,omitempty"`
MaxEntries int `json:"max_entries,omitempty"`
}
type ReadFilesInput struct {
Path *string `json:"path"`
MaxBytes int `json:"max_bytes,omitempty"`
}
type BashInput struct {
Command *string `json:"command"`
Cmd *string `json:"cmd,omitempty"`
TimeoutSeconds int `json:"timeout_seconds,omitempty"`
MaxOutputBytes int `json:"max_output_bytes,omitempty"`
}
type EditFilesInput struct {
Path *string `json:"path"`
OldStr *string `json:"old_str"`
NewStr *string `json:"new_str"`
}
type WriteFileInput struct {
Path *string `json:"path"`
Content *string `json:"content"`
Text *string `json:"text,omitempty"`
Body *string `json:"body,omitempty"`
NewStr *string `json:"new_str,omitempty"`
Overwrite *bool `json:"overwrite,omitempty"`
}
func main() {
cfg, err := loadConfig()
if err != nil {
fmt.Fprintln(os.Stderr, "Error:", err)
os.Exit(1)
}
toolDefs := registeredTools()
toolMap, anthropicTools, err := buildToolRegistry(toolDefs)
if err != nil {
fmt.Fprintln(os.Stderr, "Error:", err)
os.Exit(1)
}
configureLogging(cfg.Verbose)
debugf(
"startup init model_id=%q model_name=%q api_key_present=%t color_output=%t tool_count=%d",
cfg.ModelID,
cfg.ModelName,
cfg.APIKey != "",
cfg.ColorOutput,
len(toolDefs),
)
client := anthropic.NewClient(option.WithAPIKey(cfg.APIKey))
if err := runChatLoop(cfg, &client, toolMap, anthropicTools); err != nil {
fmt.Fprintln(os.Stderr, "Error:", err)
os.Exit(1)
}
}
func loadConfig() (Config, error) {
verbose := flag.Bool("verbose", false, "Enable verbose debug logs")
modelID := flag.String("model", defaultModelID, "Anthropic model ID")
flag.Parse()
apiKey := strings.TrimSpace(os.Getenv("ANTHROPIC_API_KEY"))
if apiKey == "" {
return Config{}, errors.New("ANTHROPIC_API_KEY is not set")
}
selectedModel := strings.TrimSpace(*modelID)
if selectedModel == "" {
selectedModel = defaultModelID
}
return Config{
APIKey: apiKey,
ModelID: selectedModel,
ModelName: modelDisplayName(selectedModel),
Verbose: *verbose,
ColorOutput: supportsColor(os.Stdout),
}, nil
}
func configureLogging(verbose bool) {
if !verbose {
log.SetOutput(io.Discard)
return
}
log.SetOutput(os.Stderr)
log.SetFlags(log.LstdFlags | log.Lshortfile)
log.SetPrefix("DEBUG ")
}
func debugf(format string, args ...any) {
_ = log.Output(2, fmt.Sprintf(format, args...))
}
func runChatLoop(cfg Config, client *anthropic.Client, toolMap map[string]ToolDefinition, anthropicTools []anthropic.ToolUnionParam) error {
scanner := bufio.NewScanner(os.Stdin)
history := make([]anthropic.MessageParam, 0, 32)
turn := 0
for {
fmt.Fprint(os.Stdout, userPrefix(cfg.ColorOutput))
if !scanner.Scan() {
if err := scanner.Err(); err != nil {
return fmt.Errorf("failed to read input: %w", err)
}
fmt.Fprintln(os.Stdout)
debugf("shutdown end_of_loop reason=%q", "stdin_eof")
return nil
}
prompt := strings.TrimSpace(scanner.Text())
if prompt == "" {
continue
}
if prompt == "/quit" || prompt == "/exit" {
debugf("shutdown end_of_loop reason=%q command=%q", "user_command", prompt)
return nil
}
turn++
history = append(history, anthropic.NewUserMessage(anthropic.NewTextBlock(prompt)))
debugf("user_input_received turn=%d prompt_chars=%d conversation_len=%d", turn, len(prompt), len(history))
call := 0
callFailed := false
lastFailureSignature := ""
repeatedFailureCount := 0
for {
if call >= maxToolRoundsPerTurn {
stopMsg := fmt.Sprintf("Stopped after %d tool rounds in this turn to prevent a tool loop. Please provide corrected instructions and try again.", maxToolRoundsPerTurn)
fmt.Fprintf(os.Stdout, "%s%s\n", assistantPrefix(cfg.ModelName, cfg.ColorOutput), stopMsg)
debugf("tool_loop_stop turn=%d reason=%q call=%d", turn, "max_tool_rounds", call)
break
}
call++
start := time.Now()
debugf(
"api_call_start turn=%d call=%d model_id=%q conversation_len=%d tool_count=%d",
turn,
call,
cfg.ModelID,
len(history),
len(anthropicTools),
)
ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
message, requestID, err := sendAnthropicMessage(ctx, client, cfg.ModelID, history, anthropicTools)
cancel()
latencyMs := time.Since(start).Milliseconds()
if err != nil {
debugf("api_call_result turn=%d call=%d ok=false latency_ms=%d request_id=%q error=%q", turn, call, latencyMs, requestID, err.Error())
fmt.Fprintf(os.Stderr, "API error: %v\n", err)
callFailed = true
break
}
history = append(history, message.ToParam())
text, toolUses := parseContent(message.Content)
debugf(
"api_call_result turn=%d call=%d ok=true latency_ms=%d request_id=%q message_id=%q response_model=%q stop_reason=%q input_tokens=%d output_tokens=%d tool_use_count=%d",
turn,
call,
latencyMs,
requestID,
message.ID,
message.Model,
message.StopReason,
message.Usage.InputTokens,
message.Usage.OutputTokens,
len(toolUses),
)
if text != "" {
fmt.Fprintf(os.Stdout, "%s%s\n", assistantPrefix(cfg.ModelName, cfg.ColorOutput), text)
}
if len(toolUses) == 0 {
if text == "" {
fmt.Fprintf(os.Stdout, "%s%s\n", assistantPrefix(cfg.ModelName, cfg.ColorOutput), "(no text content returned)")
}
debugf("api_response_tool_use_none turn=%d call=%d", turn, call)
break
}
toolResults := make([]anthropic.ContentBlockParamUnion, 0, len(toolUses))
allToolsFailed := true
failureSig := make([]string, 0, len(toolUses))
hasValidationError := false
for i, tool := range toolUses {
debugf("api_response_tool_use turn=%d call=%d index=%d tool_id=%q tool_name=%q tool_input=%q", turn, call, i, tool.ID, tool.Name, string(tool.Input))
failureSig = append(failureSig, tool.Name+"="+strings.TrimSpace(string(tool.Input)))
fmt.Fprintf(os.Stdout, "%s: %s(%s)\n", colorLabel("tool", toolColor, cfg.ColorOutput), tool.Name, string(tool.Input))
resultText, isError := runTool(toolMap, tool)
if !isError {
allToolsFailed = false
}
if isError && isToolInputValidationError(resultText) {
hasValidationError = true
}
if isError {
fmt.Fprintf(os.Stdout, "%s: %s\n", colorLabel("error", errorColor, cfg.ColorOutput), resultText)
} else {
fmt.Fprintf(os.Stdout, "%s: %s\n", colorLabel("result", resultColor, cfg.ColorOutput), resultText)
}
toolResults = append(toolResults, anthropic.NewToolResultBlock(tool.ID, resultText, isError))
}
if hasValidationError {
toolResults = append(toolResults, anthropic.NewTextBlock(
"One or more tool calls had invalid JSON input. Retry with exact required fields from each error message. For full file contents, use write_file with path and content. Do not call bash unless command is non-empty.",
))
}
history = append(history, anthropic.NewUserMessage(toolResults...))
debugf("tool_results_submitted turn=%d call=%d result_count=%d conversation_len=%d", turn, call, len(toolResults), len(history))
if allToolsFailed {
signature := strings.Join(failureSig, "|")
if signature == lastFailureSignature {
repeatedFailureCount++
} else {
lastFailureSignature = signature
repeatedFailureCount = 1
}
if repeatedFailureCount >= maxRepeatedToolFailures {
stopMsg := "Stopping tool loop after repeated identical tool failures. I need corrected tool inputs to continue."
fmt.Fprintf(os.Stdout, "%s%s\n", assistantPrefix(cfg.ModelName, cfg.ColorOutput), stopMsg)
debugf("tool_loop_stop turn=%d reason=%q call=%d repeat_count=%d signature=%q", turn, "repeated_tool_failures", call, repeatedFailureCount, signature)
break
}
} else {
lastFailureSignature = ""
repeatedFailureCount = 0
}
}
if callFailed {
continue
}
}
}
func sendAnthropicMessage(
ctx context.Context,
client *anthropic.Client,
modelID string,
history []anthropic.MessageParam,
tools []anthropic.ToolUnionParam,
) (*anthropic.Message, string, error) {
var rawResp *http.Response
message, err := client.Messages.New(
ctx,
anthropic.MessageNewParams{
Model: anthropic.Model(modelID),
MaxTokens: defaultMaxTokens,
Temperature: anthropic.Float(defaultTemp),
Messages: history,
System: []anthropic.TextBlockParam{{Text: toolUseSystemPrompt}},
Tools: tools,
},
option.WithResponseInto(&rawResp),
)
requestID := ""
if rawResp != nil {
requestID = rawResp.Header.Get("request-id")
}
if err != nil {
if requestID != "" {
return nil, requestID, fmt.Errorf("%w (request_id=%s)", err, requestID)
}
return nil, requestID, err
}
return message, requestID, nil
}
func parseContent(blocks []anthropic.ContentBlockUnion) (string, []ToolUse) {
var text strings.Builder
tools := make([]ToolUse, 0)
for _, block := range blocks {
switch block.Type {
case "text":
text.WriteString(block.Text)
case "tool_use":
input := json.RawMessage(append([]byte(nil), block.Input...))
if strings.TrimSpace(string(input)) == "" {
input = json.RawMessage([]byte("{}"))
}
tools = append(tools, ToolUse{ID: block.ID, Name: block.Name, Input: input})
}
}
return strings.TrimSpace(text.String()), tools
}
func runTool(toolMap map[string]ToolDefinition, toolUse ToolUse) (string, bool) {
tool, ok := toolMap[toolUse.Name]
if !ok {
errMsg := fmt.Sprintf("unknown tool: %s", toolUse.Name)
debugf("tool_call_result tool_name=%q ok=false error=%q", toolUse.Name, errMsg)
return errMsg, true
}
debugf("tool_call_start tool_name=%q", toolUse.Name)
result, err := tool.Function(toolUse.Input)
if err != nil {
errMsg := err.Error()
debugf("tool_call_result tool_name=%q ok=false error=%q", toolUse.Name, errMsg)
return errMsg, true
}
debugf("tool_call_result tool_name=%q ok=true result_chars=%d", toolUse.Name, len(result))
return result, false
}
func registeredTools() []ToolDefinition {
return []ToolDefinition{
{
Name: "write_file",
Description: "Create or overwrite a text file in the current workspace. Use this to write full file contents in one call.",
InputSchema: writeFileInputSchema(),
Function: writeFile,
},
{
Name: "edit_file",
Description: `Apply a targeted edit to an existing text file.
If old_str is empty and the file exists, new_str is appended.
If old_str is non-empty, it must match exactly once and will be replaced by new_str.`,
InputSchema: editFilesInputSchema(),
Function: editFiles,
},
{
Name: "edit_files",
Description: `Apply a targeted edit to an existing text file.
If old_str is empty and the file exists, new_str is appended.
If old_str is non-empty, it must match exactly once and will be replaced by new_str.`,
InputSchema: editFilesInputSchema(),
Function: editFiles,
},
{
Name: "bash",
Description: "Execute a bash command in the current workspace and return combined stdout/stderr output. Always include a non-empty command field.",
InputSchema: bashInputSchema(),
Function: bashTool,
},
{
Name: "read_file",
Description: "Read a file in the current workspace. Use this to inspect exact file contents.",
InputSchema: readFilesInputSchema(),
Function: readFiles,
},
{
Name: "read_files",
Description: "Read the contents of a file in the current workspace. Use this to inspect specific files after discovering paths with list_files.",
InputSchema: readFilesInputSchema(),
Function: readFiles,
},
{
Name: "list_files",
Description: "List files and directories in the current workspace. Use this to inspect the filesystem before reading or editing files.",
InputSchema: listFilesInputSchema(),
Function: listFiles,
},
}
}
func buildToolRegistry(defs []ToolDefinition) (map[string]ToolDefinition, []anthropic.ToolUnionParam, error) {
toolMap := make(map[string]ToolDefinition, len(defs))
anthropicTools := make([]anthropic.ToolUnionParam, 0, len(defs))
for _, def := range defs {
if strings.TrimSpace(def.Name) == "" {
return nil, nil, errors.New("tool name cannot be empty")
}
if _, exists := toolMap[def.Name]; exists {
return nil, nil, fmt.Errorf("duplicate tool name: %s", def.Name)
}
toolMap[def.Name] = def
anthropicTools = append(anthropicTools, anthropic.ToolUnionParam{
OfTool: &anthropic.ToolParam{
Name: def.Name,
Description: anthropic.String(def.Description),
InputSchema: def.InputSchema,
},
})
}
return toolMap, anthropicTools, nil
}
func writeFileInputSchema() anthropic.ToolInputSchemaParam {
return anthropic.ToolInputSchemaParam{
Properties: map[string]any{
"path": map[string]any{
"type": "string",
"description": "Relative file path within the current workspace.",
},
"content": map[string]any{
"type": "string",
"description": "Full text content to write to the file.",
},
"overwrite": map[string]any{
"type": "boolean",
"description": "Whether to overwrite an existing file. Defaults to false.",
},
},
Required: []string{"path", "content"},
ExtraFields: map[string]any{
"additionalProperties": false,
},
}
}
func editFilesInputSchema() anthropic.ToolInputSchemaParam {
return anthropic.ToolInputSchemaParam{
Properties: map[string]any{
"path": map[string]any{
"type": "string",
"description": "Relative file path within the current workspace.",
},
"old_str": map[string]any{
"type": "string",
"description": "Text to replace. Use an empty string to create a new file or append to an existing file.",
},
"new_str": map[string]any{
"type": "string",
"description": "Replacement text, or content to create/append when old_str is empty.",
},
},
Required: []string{"path", "old_str", "new_str"},
ExtraFields: map[string]any{
"additionalProperties": false,
},
}
}
func bashInputSchema() anthropic.ToolInputSchemaParam {
return anthropic.ToolInputSchemaParam{
Properties: map[string]any{
"command": map[string]any{
"type": "string",
"description": "The bash command to execute.",
},
"cmd": map[string]any{
"type": "string",
"description": "Alias of command. Prefer command.",
},
"timeout_seconds": map[string]any{
"type": "integer",
"description": fmt.Sprintf("Optional timeout in seconds. Defaults to %d, capped at %d.", defaultBashTimeoutSeconds, hardBashTimeoutSeconds),
"minimum": 1,
"maximum": hardBashTimeoutSeconds,
},
"max_output_bytes": map[string]any{
"type": "integer",
"description": fmt.Sprintf("Maximum bytes of command output to return. Defaults to %d, capped at %d.", defaultBashMaxOutputBytes, hardBashMaxOutputBytes),
"minimum": 1,
"maximum": hardBashMaxOutputBytes,
},
},
Required: []string{"command"},
ExtraFields: map[string]any{
"additionalProperties": false,
},
}
}
func readFilesInputSchema() anthropic.ToolInputSchemaParam {
return anthropic.ToolInputSchemaParam{
Properties: map[string]any{
"path": map[string]any{
"type": "string",
"description": "Relative file path within the current workspace.",
},
"max_bytes": map[string]any{
"type": "integer",
"description": fmt.Sprintf("Maximum bytes to read from the file. Defaults to %d, capped at %d.", defaultReadFilesMaxBytes, hardReadFilesMaxBytes),
"minimum": 1,
"maximum": hardReadFilesMaxBytes,
},
},
Required: []string{"path"},
ExtraFields: map[string]any{
"additionalProperties": false,
},
}
}
func listFilesInputSchema() anthropic.ToolInputSchemaParam {
return anthropic.ToolInputSchemaParam{
Properties: map[string]any{
"path": map[string]any{
"type": "string",
"description": "Optional relative directory path. Defaults to current directory.",
},
"recursive": map[string]any{
"type": "boolean",
"description": "Whether to recursively include nested files and directories. Defaults to true.",
},
"max_entries": map[string]any{
"type": "integer",
"description": fmt.Sprintf("Maximum number of entries to return. Defaults to %d, capped at %d.", defaultListFilesMaxEntries, hardListFilesMaxEntries),
"minimum": 1,
"maximum": hardListFilesMaxEntries,
},
},
ExtraFields: map[string]any{
"additionalProperties": false,
},
}
}
func toolInputValidationError(toolName, reason, expected string) error {
if expected == "" {
return fmt.Errorf("invalid %s input: %s", toolName, reason)
}
return fmt.Errorf("invalid %s input: %s. expected input like %s", toolName, reason, expected)
}
func isToolInputValidationError(resultText string) bool {
lower := strings.ToLower(strings.TrimSpace(resultText))
return strings.HasPrefix(lower, "invalid ")
}
func requireToolString(toolName, fieldName string, value *string, allowEmpty bool, expected string) (string, error) {
if value == nil {
return "", toolInputValidationError(toolName, fmt.Sprintf("missing required field %q", fieldName), expected)
}
if !allowEmpty && strings.TrimSpace(*value) == "" {
return "", toolInputValidationError(toolName, fmt.Sprintf("field %q cannot be empty", fieldName), expected)
}
return *value, nil
}
func writeFile(input json.RawMessage) (string, error) {
const expected = `{"path":"src/main.py","content":"print(\"hello\")","overwrite":true}`
args := WriteFileInput{}
raw := strings.TrimSpace(string(input))
if raw == "" {
raw = "{}"
}
if err := json.Unmarshal([]byte(raw), &args); err != nil {
return "", toolInputValidationError("write_file", err.Error(), expected)
}
pathValue, err := requireToolString("write_file", "path", args.Path, false, expected)
if err != nil {
return "", err
}
contentSource := args.Content
if contentSource == nil {
contentSource = args.Text
}
if contentSource == nil {
contentSource = args.Body
}
if contentSource == nil {
contentSource = args.NewStr
}
if contentSource == nil {
return "", toolInputValidationError(
"write_file",
`missing required field "content" (accepted aliases: "text", "body", "new_str"); include the full file contents`,
expected,
)
}
content, err := requireToolString("write_file", "content", contentSource, true, expected)
if err != nil {
return "", err
}
pathValue = strings.TrimSpace(pathValue)
overwrite := false
if args.Overwrite != nil {
overwrite = *args.Overwrite
}
absFile, displayPath, err := resolveWorkspaceFileForWrite(pathValue)
if err != nil {
return "", err
}
exists := false
info, statErr := os.Stat(absFile)
if statErr == nil {
exists = true
if info.IsDir() {
return "", fmt.Errorf("path is a directory: %s", displayPath)
}
} else if !os.IsNotExist(statErr) {
return "", fmt.Errorf("failed to access path %q: %w", displayPath, statErr)
}
if exists && !overwrite {
return "", toolInputValidationError("write_file", fmt.Sprintf("file already exists: %s (set overwrite=true to replace it)", displayPath), expected)
}
if err := os.MkdirAll(filepath.Dir(absFile), 0o755); err != nil {
return "", fmt.Errorf("failed to create parent directory for %q: %w", displayPath, err)
}
if err := os.WriteFile(absFile, []byte(content), 0o644); err != nil {
return "", fmt.Errorf("failed to write file %q: %w", displayPath, err)
}
if exists {
fmt.Fprintf(os.Stdout, "Overwrote %s (%d bytes)\n", displayPath, len(content))
} else {
fmt.Fprintf(os.Stdout, "Created %s (%d bytes)\n", displayPath, len(content))
}
return fmt.Sprintf("wrote file %s", displayPath), nil
}
func editFiles(input json.RawMessage) (string, error) {
const expected = `{"path":"src/main.py","old_str":"before","new_str":"after"}`
args := EditFilesInput{}
raw := strings.TrimSpace(string(input))
if raw == "" {
raw = "{}"
}
if err := json.Unmarshal([]byte(raw), &args); err != nil {
return "", toolInputValidationError("edit_files", err.Error(), expected)
}
pathValue, err := requireToolString("edit_files", "path", args.Path, false, expected)
if err != nil {
return "", err
}
oldStr, err := requireToolString("edit_files", "old_str", args.OldStr, true, expected)
if err != nil {
return "", err
}
newStr, err := requireToolString("edit_files", "new_str", args.NewStr, true, expected)
if err != nil {
return "", err
}
pathValue = strings.TrimSpace(pathValue)
if oldStr == newStr {
return "", toolInputValidationError("edit_files", `"old_str" and "new_str" must be different`, expected)
}
absFile, displayPath, err := resolveWorkspaceFileForWrite(pathValue)
if err != nil {
return "", err
}
info, statErr := os.Stat(absFile)
if statErr != nil {
if !os.IsNotExist(statErr) {
return "", fmt.Errorf("failed to access path %q: %w", displayPath, statErr)
}
if oldStr != "" {
return "", fmt.Errorf("file does not exist: %s (old_str must be empty to create it; otherwise use write_file)", displayPath)
}
if err := os.MkdirAll(filepath.Dir(absFile), 0o755); err != nil {
return "", fmt.Errorf("failed to create parent directory for %q: %w", displayPath, err)
}
if err := os.WriteFile(absFile, []byte(newStr), 0o644); err != nil {
return "", fmt.Errorf("failed to create file %q: %w", displayPath, err)
}
fmt.Fprintf(os.Stdout, "Created %s (%d bytes)\n", displayPath, len(newStr))
return fmt.Sprintf("created file %s", displayPath), nil
}
if info.IsDir() {
return "", fmt.Errorf("path is a directory: %s", displayPath)
}
contentBytes, err := os.ReadFile(absFile)
if err != nil {
return "", fmt.Errorf("failed to read file %q: %w", displayPath, err)
}
content := string(contentBytes)
var newContent string
switch {
case oldStr == "":
newContent = content + newStr
case strings.Count(content, oldStr) == 0:
return "", fmt.Errorf("old_str not found in file: %s", displayPath)
case strings.Count(content, oldStr) > 1:
return "", fmt.Errorf("old_str appears multiple times in file: %s; provide more specific text", displayPath)
default:
newContent = strings.Replace(content, oldStr, newStr, 1)
}
if err := os.WriteFile(absFile, []byte(newContent), 0o644); err != nil {
return "", fmt.Errorf("failed to write file %q: %w", displayPath, err)
}
fmt.Fprintf(os.Stdout, "Edited %s\n", displayPath)
return fmt.Sprintf("edited file %s", displayPath), nil
}
func bashTool(input json.RawMessage) (string, error) {
const expected = `{"command":"python3 app.py","timeout_seconds":30}`
args := BashInput{}
raw := strings.TrimSpace(string(input))
if raw == "" {
raw = "{}"
}
if err := json.Unmarshal([]byte(raw), &args); err != nil {
return "", toolInputValidationError("bash", err.Error(), expected)
}
command := ""
if args.Command != nil {
command = *args.Command
}
if strings.TrimSpace(command) == "" && args.Cmd != nil {
command = *args.Cmd
}
command = strings.TrimSpace(command)
if command == "" {
return "", toolInputValidationError("bash", `missing required field "command"`, expected)
}
timeoutSeconds := defaultBashTimeoutSeconds
if args.TimeoutSeconds > 0 {
timeoutSeconds = args.TimeoutSeconds
}
if timeoutSeconds > hardBashTimeoutSeconds {
timeoutSeconds = hardBashTimeoutSeconds
}
maxOutputBytes := defaultBashMaxOutputBytes
if args.MaxOutputBytes > 0 {
maxOutputBytes = args.MaxOutputBytes
}
if maxOutputBytes > hardBashMaxOutputBytes {
maxOutputBytes = hardBashMaxOutputBytes
}
cwd, err := os.Getwd()
if err != nil {
return "", fmt.Errorf("failed to resolve working directory: %w", err)
}
debugf("bash_tool_start command=%q timeout_seconds=%d max_output_bytes=%d", command, timeoutSeconds, maxOutputBytes)
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeoutSeconds)*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, "bash", "-lc", command)
cmd.Dir = cwd
output, runErr := cmd.CombinedOutput()
truncatedOutput, wasTruncated := truncateOutput(output, maxOutputBytes)
trimmedOutput := strings.TrimSpace(truncatedOutput)
if ctx.Err() == context.DeadlineExceeded {
msg := fmt.Sprintf("Command timed out after %d seconds.", timeoutSeconds)
if trimmedOutput != "" {
msg += "\n\nPartial output:\n" + trimmedOutput
}
if wasTruncated {
msg += fmt.Sprintf("\n\n(output truncated at max_output_bytes=%d)", maxOutputBytes)
}
return msg, nil
}
if runErr != nil {
var exitErr *exec.ExitError
if errors.As(runErr, &exitErr) {
msg := fmt.Sprintf("Command exited with code %d.", exitErr.ExitCode())
if trimmedOutput != "" {
msg += "\n\nOutput:\n" + trimmedOutput
}
if wasTruncated {
msg += fmt.Sprintf("\n\n(output truncated at max_output_bytes=%d)", maxOutputBytes)
}
return msg, nil
}
return "", fmt.Errorf("failed to execute command: %w", runErr)
}
if trimmedOutput == "" {
return "Command completed successfully with no output.", nil
}
if wasTruncated {
return trimmedOutput + fmt.Sprintf("\n\n(output truncated at max_output_bytes=%d)", maxOutputBytes), nil
}
return trimmedOutput, nil
}
func readFiles(input json.RawMessage) (string, error) {
const expected = `{"path":"main.py","max_bytes":32000}`
args := ReadFilesInput{}
raw := strings.TrimSpace(string(input))
if raw == "" {
raw = "{}"
}
if err := json.Unmarshal([]byte(raw), &args); err != nil {
return "", toolInputValidationError("read_files", err.Error(), expected)
}
pathValue, err := requireToolString("read_files", "path", args.Path, false, expected)
if err != nil {
return "", err
}
pathValue = strings.TrimSpace(pathValue)
maxBytes := defaultReadFilesMaxBytes
if args.MaxBytes > 0 {
maxBytes = args.MaxBytes
}
if maxBytes > hardReadFilesMaxBytes {
maxBytes = hardReadFilesMaxBytes
}
absFile, displayPath, err := resolveWorkspaceFile(pathValue)
if err != nil {
return "", err
}
content, err := os.ReadFile(absFile)
if err != nil {
return "", fmt.Errorf("failed to read file %q: %w", displayPath, err)
}
truncated := false
if len(content) > maxBytes {
content = content[:maxBytes]
truncated = true
}
if truncated {
fmt.Fprintf(os.Stdout, "Read %s (%d bytes, truncated at max_bytes=%d)\n", displayPath, len(content), maxBytes)
} else {
fmt.Fprintf(os.Stdout, "Read %s (%d bytes)\n", displayPath, len(content))
}
return string(content), nil
}
func truncateOutput(output []byte, maxBytes int) (string, bool) {
if maxBytes < 1 {
maxBytes = defaultBashMaxOutputBytes
}
if len(output) <= maxBytes {
return string(output), false
}
return string(output[:maxBytes]), true
}
func listFiles(input json.RawMessage) (string, error) {
args := ListFilesInput{}
raw := strings.TrimSpace(string(input))
if raw == "" {
raw = "{}"
}
if err := json.Unmarshal([]byte(raw), &args); err != nil {
return "", fmt.Errorf("invalid list_files input: %w", err)
}
recursive := true
if args.Recursive != nil {
recursive = *args.Recursive
}
maxEntries := defaultListFilesMaxEntries
if args.MaxEntries > 0 {
maxEntries = args.MaxEntries
}
if maxEntries > hardListFilesMaxEntries {
maxEntries = hardListFilesMaxEntries
}
absDir, displayPath, err := resolveWorkspaceDir(args.Path)
if err != nil {
return "", err
}
entries, truncated, err := collectFileEntries(absDir, recursive, maxEntries)
if err != nil {
return "", err
}
if truncated {
fmt.Fprintf(os.Stdout, "Searched %s\nListed %d files (truncated at max_entries=%d)\n", displayPath, len(entries), maxEntries)
} else {
fmt.Fprintf(os.Stdout, "Searched %s\nListed %d files\n", displayPath, len(entries))
}
encoded, err := json.Marshal(entries)
if err != nil {
return "", fmt.Errorf("failed to encode list_files output: %w", err)
}
return string(encoded), nil
}
func resolveWorkspaceFileForWrite(pathArg string) (string, string, error) {
cwd, err := os.Getwd()
if err != nil {
return "", "", fmt.Errorf("failed to resolve working directory: %w", err)
}
pathArg = strings.TrimSpace(pathArg)
if pathArg == "" {
return "", "", errors.New("path is required")
}
if filepath.IsAbs(pathArg) {
return "", "", errors.New("path must be relative to the current workspace")