-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
1210 lines (1081 loc) · 30.1 KB
/
main.go
File metadata and controls
1210 lines (1081 loc) · 30.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"
"log"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"github.com/openai/openai-go"
"github.com/openai/openai-go/option"
"github.com/openai/openai-go/responses"
"github.com/openai/openai-go/shared"
"github.com/openai/openai-go/shared/constant"
)
const (
// maxReadChars caps how many characters the assistant reads per request.
maxReadChars = 4000
// maxThinkText limits how much reasoning text we surface in the TUI.
maxThinkText = 500
)
// chatEvent represents a single event streamed back to the interactive UI.
type chatEvent struct {
Kind string
Data map[string]string
}
// chatResult captures the final reply plus the events emitted while reasoning.
type chatResult struct {
Final string
Events []chatEvent
}
// toolInvocation represents a single tool call that must be executed.
type toolInvocation struct {
Name string
CallID string
Arguments map[string]any
}
// responseRound captures the streamed response metadata for a single model turn.
type responseRound struct {
response *responses.Response
toolCalls []toolInvocation
}
// toolCallState tracks incremental streaming updates for a single tool call.
type toolCallState struct {
itemID string
callID string
name string
buffer strings.Builder
arguments map[string]any
emitted bool
dispatched bool
}
func newToolCallState(itemID string) *toolCallState {
return &toolCallState{
itemID: itemID,
arguments: map[string]any{},
}
}
func (s *toolCallState) appendArguments(delta string) {
if delta == "" {
return
}
s.buffer.WriteString(delta)
}
func (s *toolCallState) setArguments(full string) {
if full != "" {
s.buffer.Reset()
s.buffer.WriteString(full)
}
s.finalizeArguments()
}
func (s *toolCallState) finalizeArguments() {
raw := s.buffer.String()
parsed, err := parseArguments(raw)
if err != nil {
log.Printf("Error parsing arguments for %s: %v", s.name, err)
s.arguments = map[string]any{}
return
}
if parsed == nil {
s.arguments = map[string]any{}
return
}
s.arguments = parsed
}
func (s *toolCallState) argumentsCopy() map[string]any {
if len(s.arguments) == 0 {
return map[string]any{}
}
clone := make(map[string]any, len(s.arguments))
for k, v := range s.arguments {
clone[k] = v
}
return clone
}
type toolCallRegistry struct {
byItem map[string]*toolCallState
byCall map[string]*toolCallState
}
func newToolCallRegistry() *toolCallRegistry {
return &toolCallRegistry{
byItem: make(map[string]*toolCallState),
byCall: make(map[string]*toolCallState),
}
}
func (r *toolCallRegistry) get(itemID, callID string) *toolCallState {
if id := strings.TrimSpace(itemID); id != "" {
if state, ok := r.byItem[id]; ok {
return state
}
}
if cid := strings.TrimSpace(callID); cid != "" {
if state, ok := r.byCall[cid]; ok {
return state
}
}
return nil
}
func (r *toolCallRegistry) put(state *toolCallState, itemID, callID string) {
if id := strings.TrimSpace(itemID); id != "" {
r.byItem[id] = state
state.itemID = id
}
if cid := strings.TrimSpace(callID); cid != "" {
r.byCall[cid] = state
state.callID = cid
}
}
func (r *toolCallRegistry) states() []*toolCallState {
seen := make(map[*toolCallState]struct{})
result := make([]*toolCallState, 0, len(r.byItem)+len(r.byCall))
for _, state := range r.byItem {
if _, ok := seen[state]; ok {
continue
}
seen[state] = struct{}{}
result = append(result, state)
}
for _, state := range r.byCall {
if _, ok := seen[state]; ok {
continue
}
seen[state] = struct{}{}
result = append(result, state)
}
return result
}
func (a *aiAgent) streamResponse(
ctx context.Context,
params responses.ResponseNewParams,
emit eventHandler,
) (responseRound, error) {
stream := a.client.Responses.NewStreaming(ctx, params)
if stream == nil {
return responseRound{}, fmt.Errorf("failed to open response stream")
}
defer stream.Close()
registry := newToolCallRegistry()
toolCalls := make([]toolInvocation, 0)
var finalResponse *responses.Response
var reasoningBuffer strings.Builder
lastThinking := ""
var messageBuffer strings.Builder
emitThinking := func() {
if emit == nil {
return
}
trimmed := trimText(reasoningBuffer.String())
if trimmed == "" || trimmed == lastThinking {
return
}
emit(chatEvent{Kind: "thinking", Data: map[string]string{"text": trimmed}})
lastThinking = trimmed
}
emitAssistantChunk := func(chunk string, reset bool) {
if emit == nil || chunk == "" {
return
}
data := map[string]string{"chunk": chunk}
if reset {
data["reset"] = "true"
}
emit(chatEvent{Kind: "assistant_delta", Data: data})
}
for stream.Next() {
evt := stream.Current()
switch evt.Type {
case "response.reasoning_summary_text.delta":
delta := evt.AsResponseReasoningSummaryTextDelta()
reasoningBuffer.WriteString(delta.Delta)
emitThinking()
case "response.reasoning_summary_text.done":
done := evt.AsResponseReasoningSummaryTextDone()
reasoningBuffer.Reset()
reasoningBuffer.WriteString(done.Text)
emitThinking()
case "response.reasoning_summary_part.added":
part := evt.AsResponseReasoningSummaryPartAdded()
reasoningBuffer.WriteString(part.Part.Text)
emitThinking()
case "response.reasoning_summary_part.done":
done := evt.AsResponseReasoningSummaryPartDone()
reasoningBuffer.WriteString(done.Part.Text)
emitThinking()
case "response.output_text.delta":
delta := evt.AsResponseOutputTextDelta()
chunk := delta.Delta
if chunk != "" {
messageBuffer.WriteString(chunk)
emitAssistantChunk(chunk, false)
}
case "response.output_text.done":
done := evt.AsResponseOutputTextDone()
text := done.Text
if text != "" {
current := messageBuffer.String()
if strings.HasPrefix(text, current) {
extra := text[len(current):]
if extra != "" {
messageBuffer.WriteString(extra)
emitAssistantChunk(extra, false)
}
} else {
messageBuffer.Reset()
messageBuffer.WriteString(text)
emitAssistantChunk(text, true)
}
}
case "response.output_item.added":
added := evt.AsResponseOutputItemAdded()
if strings.EqualFold(added.Item.Type, "function_call") {
itemID := strings.TrimSpace(added.Item.ID)
callState := registry.get(itemID, added.Item.CallID)
if callState == nil {
callState = newToolCallState(itemID)
registry.put(callState, itemID, added.Item.CallID)
} else {
registry.put(callState, itemID, added.Item.CallID)
}
if added.Item.Name != "" {
callState.name = added.Item.Name
}
if added.Item.Arguments != "" {
callState.setArguments(added.Item.Arguments)
}
}
case "response.function_call_arguments.delta":
delta := evt.AsResponseFunctionCallArgumentsDelta()
callState := registry.get(delta.ItemID, "")
if callState == nil {
callState = newToolCallState(delta.ItemID)
registry.put(callState, delta.ItemID, "")
}
callState.appendArguments(delta.Delta)
case "response.function_call_arguments.done":
done := evt.AsResponseFunctionCallArgumentsDone()
callState := registry.get(done.ItemID, "")
if callState == nil {
callState = newToolCallState(done.ItemID)
registry.put(callState, done.ItemID, "")
}
callState.setArguments(done.Arguments)
if callState.callID == "" {
callState.callID = done.ItemID
}
registry.put(callState, done.ItemID, callState.callID)
if callState.name == "" {
callState.name = "tool"
}
if emit != nil && !callState.emitted {
summary := summarizeArguments(callState.arguments)
emit(
chatEvent{
Kind: "tool_call",
Data: map[string]string{"name": callState.name, "summary": summary},
},
)
callState.emitted = true
}
callState.dispatched = true
toolCalls = append(toolCalls, toolInvocation{
Name: callState.name,
CallID: callState.callID,
Arguments: callState.argumentsCopy(),
})
case "response.completed":
completed := evt.AsResponseCompleted()
resp := completed.Response
finalResponse = &resp
case "response.failed":
failed := evt.AsResponseFailed()
resp := failed.Response
finalResponse = &resp
return responseRound{}, fmt.Errorf("response failed")
case "error":
errEvt := evt.AsError()
return responseRound{}, fmt.Errorf("api error (%s): %s", errEvt.Code, errEvt.Message)
}
}
if err := stream.Err(); err != nil {
return responseRound{}, err
}
if finalResponse == nil {
return responseRound{}, fmt.Errorf("no response received from stream")
}
existingByCallID := make(map[string]int)
for idx, call := range toolCalls {
if call.CallID != "" {
existingByCallID[call.CallID] = idx
}
}
for _, state := range registry.states() {
if state.dispatched {
continue
}
if state.callID == "" {
continue
}
state.finalizeArguments()
if emit != nil && !state.emitted {
summary := summarizeArguments(state.arguments)
emit(
chatEvent{
Kind: "tool_call",
Data: map[string]string{"name": state.name, "summary": summary},
},
)
state.emitted = true
}
toolCalls = append(toolCalls, toolInvocation{
Name: state.name,
CallID: state.callID,
Arguments: state.argumentsCopy(),
})
state.dispatched = true
if state.callID != "" {
existingByCallID[state.callID] = len(toolCalls) - 1
}
}
extra := extractFunctionCalls(finalResponse)
for _, call := range extra {
args, err := parseArguments(call.Arguments)
if err != nil {
log.Printf("Error parsing arguments for %s: %v", call.Name, err)
args = map[string]any{}
}
if args == nil {
args = map[string]any{}
}
if idx, ok := existingByCallID[call.CallID]; ok {
if toolCalls[idx].Name == "" && call.Name != "" {
toolCalls[idx].Name = call.Name
}
if len(toolCalls[idx].Arguments) == 0 && len(args) > 0 {
toolCalls[idx].Arguments = args
}
continue
}
if emit != nil {
emit(
chatEvent{
Kind: "tool_call",
Data: map[string]string{"name": call.Name, "summary": summarizeArguments(args)},
},
)
}
toolCalls = append(toolCalls, toolInvocation{
Name: call.Name,
CallID: call.CallID,
Arguments: args,
})
if call.CallID != "" {
existingByCallID[call.CallID] = len(toolCalls) - 1
}
}
return responseRound{response: finalResponse, toolCalls: toolCalls}, nil
}
// eventHandler forwards emitted events to the UI layer.
type eventHandler func(chatEvent)
// toolHandler executes the underlying logic for a tool invocation.
type toolHandler func(map[string]any) string
// tool records the schema metadata and handler used to expose capabilities to the model.
type tool struct {
Name string
Description string
InputSchema map[string]any
Handler toolHandler
}
// aiAgent manages Responses API interactions and the registered tools.
type aiAgent struct {
client *openai.Client
instructions string
previousResponseID string
toolDefinitions []responses.ToolUnionParam
tools map[string]tool
}
// newAIAgent constructs an agent wired to the OpenAI client with default instructions.
func newAIAgent(apiKey string) (*aiAgent, error) {
client := openai.NewClient(option.WithAPIKey(apiKey))
agent := &aiAgent{
client: &client,
instructions: fmt.Sprintf(
"You are a helpful expert coding assistant operating in a terminal environment. "+
"Output only plain text without markdown formatting, as your responses appear "+
"directly in the terminal. Follow best practices, write clean efficient code. "+
"Always use the latest language features and libraries. "+
"Be concise but thorough, providing clear and practical information. Don't use "+
"any asterisk characters in your responses. To conserve context, the read_file "+
"tool returns at most %d characters per call; use its optional offset and length "+
"arguments to page through larger files when needed.",
maxReadChars,
),
}
agent.setupTools()
return agent, nil
}
// setupTools registers the built-in tools and materializes their schemas for the API.
func (a *aiAgent) setupTools() {
readFileSchema := map[string]any{
"type": "object",
"additionalProperties": false,
"properties": map[string]any{
"path": map[string]any{
"type": "string",
"description": "Absolute or relative path to read",
},
"offset": map[string]any{
"type": "integer",
"description": "Starting character offset (use 0 to read from start)",
"minimum": 0,
},
"length": map[string]any{
"type": "integer",
"description": fmt.Sprintf(
"Number of characters to read (default %d)",
maxReadChars,
),
"minimum": 1,
},
},
"required": []string{"path"},
}
listFilesSchema := map[string]any{
"type": "object",
"additionalProperties": false,
"properties": map[string]any{
"path": map[string]any{
"type": "string",
"description": "Directory path to list (use '.' for current directory)",
},
},
"required": []string{},
}
editFileSchema := map[string]any{
"type": "object",
"additionalProperties": false,
"properties": map[string]any{
"path": map[string]any{
"type": "string",
"description": "File path to create or update",
},
"old_text": map[string]any{
"type": "string",
"description": "Existing text to replace (use empty string to skip lookup)",
},
"new_text": map[string]any{
"type": "string",
"description": "Replacement text or full file contents",
},
},
"required": []string{"path", "new_text"},
}
tools := []tool{
{
Name: "read_file",
Description: "Read file contents with explicit offset/length (use 0 and default length if not paging)",
InputSchema: readFileSchema,
Handler: a.handleReadFile,
},
{
Name: "list_files",
Description: "List files for a directory (pass '.' for the current working directory)",
InputSchema: listFilesSchema,
Handler: a.handleListFiles,
},
{
Name: "edit_file",
Description: "Replace text in a file (set old_text to empty string to overwrite without matching)",
InputSchema: editFileSchema,
Handler: a.handleEditFile,
},
}
a.tools = make(map[string]tool, len(tools))
a.toolDefinitions = make([]responses.ToolUnionParam, 0, len(tools))
for _, t := range tools {
a.tools[t.Name] = t
definition := responses.ToolUnionParam{
OfFunction: &responses.FunctionToolParam{
Name: t.Name,
Description: openai.String(t.Description),
Parameters: t.InputSchema,
Strict: openai.Bool(false),
Type: constant.ValueOf[constant.Function](),
},
}
a.toolDefinitions = append(a.toolDefinitions, definition)
}
}
// chat orchestrates multi-turn conversations, emitting events as reasoning unfolds.
func (a *aiAgent) chat(ctx context.Context, userInput string, handler eventHandler) chatResult {
log.Printf("User input: %s", userInput)
events := make([]chatEvent, 0)
emit := func(evt chatEvent) {
events = append(events, evt)
if handler != nil {
handler(evt)
}
}
inputs := responses.ResponseInputParam{
responses.ResponseInputItemParamOfMessage(userInput, responses.EasyInputMessageRoleUser),
}
previousID := a.previousResponseID
for {
params := responses.ResponseNewParams{
Model: shared.ResponsesModel("gpt-5"),
Instructions: openai.String(a.instructions),
Input: responses.ResponseNewParamsInputUnion{
OfInputItemList: inputs,
},
Tools: a.toolDefinitions,
Reasoning: shared.ReasoningParam{
Summary: shared.ReasoningSummaryAuto,
},
}
if previousID != "" {
params.PreviousResponseID = openai.String(previousID)
}
round, err := a.streamResponse(ctx, params, emit)
if err != nil {
log.Printf("Error streaming response: %v", err)
return chatResult{Final: fmt.Sprintf("Error: %v", err), Events: events}
}
if round.response == nil {
return chatResult{Final: "Error: missing response", Events: events}
}
previousID = round.response.ID
if len(round.toolCalls) == 0 {
a.previousResponseID = round.response.ID
finalText := strings.TrimSpace(round.response.OutputText())
return chatResult{Final: finalText, Events: events}
}
toolOutputs := make(responses.ResponseInputParam, 0, len(round.toolCalls))
for _, call := range round.toolCalls {
result := a.executeTool(call.Name, call.Arguments)
log.Printf("Tool result: %s", summarizeToolResult(result))
payload := encodeToolResult(result)
toolOutputs = append(toolOutputs, responses.ResponseInputItemUnionParam{
OfFunctionCallOutput: &responses.ResponseInputItemFunctionCallOutputParam{
CallID: call.CallID,
Output: payload,
Type: constant.ValueOf[constant.FunctionCallOutput](),
},
})
emit(chatEvent{
Kind: "tool_result",
Data: map[string]string{
"name": call.Name,
"summary": summarizeToolResult(result),
},
})
}
inputs = toolOutputs
}
}
// executeTool routes tool invocations to the appropriate handler with logging.
func (a *aiAgent) executeTool(name string, args map[string]any) string {
toolDef, ok := a.tools[name]
if !ok {
return fmt.Sprintf("Unknown tool: %s", name)
}
log.Printf("Executing tool: %s with args: %v", name, args)
return toolDef.Handler(args)
}
// handleReadFile streams a window of file contents anchored by optional offset/length.
func (a *aiAgent) handleReadFile(args map[string]any) string {
path, ok := getString(args["path"])
if !ok || path == "" {
return "Error: 'path' is required"
}
info, err := os.Stat(path)
if errors.Is(err, os.ErrNotExist) {
return fmt.Sprintf("File not found: %s", path)
}
if err != nil {
return fmt.Sprintf("Error reading file: %v", err)
}
total := int(info.Size())
start := clampNonNegative(getInt(args["offset"]))
if total == 0 {
return fmt.Sprintf("File %s: returning characters 0-0 of 0.\n", path)
}
if start >= total {
return fmt.Sprintf(
"File %s has %d characters; offset %d is beyond the end.",
path,
total,
start,
)
}
length := maxReadChars
if requested := getInt(args["length"]); requested > 0 {
length = requested
}
if length > total-start {
length = total - start
}
file, err := os.Open(path)
if err != nil {
return fmt.Sprintf("Error reading file: %v", err)
}
defer file.Close()
if _, err := file.Seek(int64(start), io.SeekStart); err != nil {
return fmt.Sprintf("Error reading file: %v", err)
}
snippetBuf := make([]byte, length)
n, readErr := io.ReadFull(file, snippetBuf)
if readErr != nil && !errors.Is(readErr, io.ErrUnexpectedEOF) && !errors.Is(readErr, io.EOF) {
return fmt.Sprintf("Error reading file: %v", readErr)
}
end := start + n
var builder strings.Builder
builder.WriteString(
fmt.Sprintf("File %s: returning characters %d-%d of %d.", path, start, end, total),
)
builder.WriteByte('\n')
builder.WriteString(string(snippetBuf[:n]))
if end < total {
builder.WriteString(
fmt.Sprintf("\nTruncated output. Call read_file with offset %d to continue.", end),
)
}
return builder.String()
}
// handleListFiles lists directory entries, tagging directories and files separately.
func (a *aiAgent) handleListFiles(args map[string]any) string {
path := "."
if supplied, ok := getString(args["path"]); ok && supplied != "" {
path = supplied
}
entries, err := os.ReadDir(path)
if errors.Is(err, os.ErrNotExist) {
return fmt.Sprintf("Path not found: %s", path)
}
if err != nil {
return fmt.Sprintf("Error listing files: %v", err)
}
if len(entries) == 0 {
return fmt.Sprintf("Empty directory: %s", path)
}
items := make([]struct {
name string
isDir bool
}, len(entries))
for i, entry := range entries {
items[i] = struct {
name string
isDir bool
}{name: entry.Name(), isDir: entry.IsDir()}
}
sort.Slice(items, func(i, j int) bool { return items[i].name < items[j].name })
var builder strings.Builder
builder.WriteString(fmt.Sprintf("Contents of %s:\n", path))
for idx, item := range items {
if idx > 0 {
builder.WriteByte('\n')
}
if item.isDir {
builder.WriteString(fmt.Sprintf("[DIR] %s/", item.name))
} else {
builder.WriteString(fmt.Sprintf("[FILE] %s", item.name))
}
}
return builder.String()
}
// handleEditFile overwrites or edits a file, replacing existing text when requested.
func (a *aiAgent) handleEditFile(args map[string]any) string {
path, ok := getString(args["path"])
if !ok || path == "" {
return "Error: 'path' is required"
}
newText, ok := getString(args["new_text"])
if !ok {
return "Error: 'new_text' is required"
}
oldText, _ := getString(args["old_text"])
if _, err := os.Stat(path); err == nil && oldText != "" {
contentBytes, err := os.ReadFile(path)
if err != nil {
return fmt.Sprintf("Error editing file: %v", err)
}
content := string(contentBytes)
if !strings.Contains(content, oldText) {
return fmt.Sprintf("Text not found in file: %s", oldText)
}
updated := strings.ReplaceAll(content, oldText, newText)
if err := os.WriteFile(path, []byte(updated), 0o644); err != nil {
return fmt.Sprintf("Error editing file: %v", err)
}
return fmt.Sprintf("Successfully edited %s", path)
}
dir := filepath.Dir(path)
if dir != "." && dir != "" {
if err := os.MkdirAll(dir, 0o755); err != nil {
return fmt.Sprintf("Error editing file: %v", err)
}
}
if err := os.WriteFile(path, []byte(newText), 0o644); err != nil {
return fmt.Sprintf("Error editing file: %v", err)
}
return fmt.Sprintf("Successfully created %s", path)
}
// extractFunctionCalls pulls function tool call items from a response payload.
func extractFunctionCalls(response *responses.Response) []responses.ResponseFunctionToolCall {
if response == nil {
return nil
}
calls := make([]responses.ResponseFunctionToolCall, 0)
for _, item := range response.Output {
if item.Type == "function_call" {
calls = append(calls, item.AsFunctionCall())
}
}
return calls
}
// parseArguments converts JSON function call payloads into a map.
func parseArguments(raw string) (map[string]any, error) {
if strings.TrimSpace(raw) == "" {
return map[string]any{}, nil
}
var parsed map[string]any
if err := json.Unmarshal([]byte(raw), &parsed); err != nil {
return nil, err
}
if parsed == nil {
return map[string]any{}, nil
}
return parsed, nil
}
// summarizeArguments produces a deterministic, concise description of tool arguments.
func summarizeArguments(args map[string]any) string {
if len(args) == 0 {
return "(no arguments)"
}
keys := make([]string, 0, len(args))
for k := range args {
keys = append(keys, k)
}
sort.Strings(keys)
parts := make([]string, 0, len(keys))
for _, key := range keys {
parts = append(parts, fmt.Sprintf("%s=%s", key, formatArgValue(key, args[key])))
}
return strings.Join(parts, ", ")
}
// formatArgValue normalizes argument values for presentation.
func formatArgValue(key string, value any) string {
switch v := value.(type) {
case string:
if key == "new_text" || key == "old_text" {
return fmt.Sprintf("<str len %d>", len(v))
}
if len(v) <= 60 {
return v
}
return v[:57] + "..."
case float64:
return fmt.Sprintf("%g", v)
case int:
return fmt.Sprintf("%d", v)
case int64:
return fmt.Sprintf("%d", v)
case nil:
return "None"
default:
return "<complex>"
}
}
// summarizeToolResult returns the first non-empty line of tool output.
func summarizeToolResult(result string) string {
if result == "" {
return "(no result text)"
}
lines := strings.Split(result, "\n")
if len(lines) == 0 || strings.TrimSpace(lines[0]) == "" {
return "(no result text)"
}
return lines[0]
}
// trimText ensures thinking output stays within the configured rune budget.
func trimText(text string) string {
cleaned := strings.TrimSpace(text)
runes := []rune(cleaned)
if len(runes) <= maxThinkText {
return cleaned
}
if maxThinkText <= 3 {
return string(runes[:maxThinkText])
}
truncated := strings.TrimRight(string(runes[:maxThinkText-3]), " \t\r\n")
return truncated + "..."
}
// extractReasoningSummary aggregates reasoning summaries into a single trimmed string.
func extractReasoningSummary(response *responses.Response) string {
if response == nil {
return ""
}
parts := make([]string, 0)
for _, item := range response.Output {
if item.Type != "reasoning" {
continue
}
for _, summary := range item.Summary {
text := strings.TrimSpace(summary.Text)
if text != "" {
parts = append(parts, text)
}
}
}
if len(parts) == 0 {
return ""
}
combined := strings.TrimSpace(strings.Join(parts, " "))
if combined == "" {
return ""
}
return trimText(combined)
}
// encodeToolResult wraps tool results in the structure expected by the API.
func encodeToolResult(result string) string {
payload := map[string]string{"result": result}
data, err := json.Marshal(payload)
if err != nil {
return fmt.Sprintf("{\"result\":%s}", strconv.Quote(result))
}
return string(data)
}
// getString attempts to coerce a value into a string while reporting success.
func getString(value any) (string, bool) {
switch v := value.(type) {
case string:
return v, true
case fmt.Stringer:
return v.String(), true
default:
return "", false
}
}
// getInt reads various numeric encodings and normalizes them to int.
func getInt(value any) int {
switch v := value.(type) {
case float64:
return int(v)
case float32:
return int(v)
case int:
return v
case int64:
return int(v)
case json.Number:
i, err := v.Int64()
if err == nil {
return int(i)
}
case string:
if parsed, err := strconv.Atoi(strings.TrimSpace(v)); err == nil {
return parsed
}
}
return 0
}
// clampNonNegative keeps offsets from becoming negative in tool handlers.
func clampNonNegative(value int) int {
if value < 0 {
return 0
}
return value
}
func resolveAPIKey(flagValue string) (string, error) {
apiKey := strings.TrimSpace(flagValue)
if apiKey == "" {
apiKey = strings.TrimSpace(os.Getenv("OPENAI_API_KEY"))
}
if apiKey == "" {