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
|
// The file half of the client: what the agent may ask the editor to read and
// write for it, and how a mentioned file's text is fetched when a prompt is
// sent. The editor's own buffers are consulted first, so the agent sees what
// you can see rather than what was last saved.
package acp
import (
"encoding/json"
"errors"
"os"
"rickub.com/turbo-editors/turbo-core/jsonrpc"
)
// readFile returns a file's text as the editor sees it — the same view the
// agent gets from fs/read_text_file — falling back to the disk when the editor
// gave no way to ask it.
func (s *Session) readFile(path string) (string, error) {
if s.options.ReadTextFile != nil {
return s.options.ReadTextFile(path)
}
data, err := os.ReadFile(path)
if err != nil {
return "", err
}
return string(data), nil
}
// readTextFile answers with the text the editor sees, which is the buffer's
// when the file is open and modified.
func (s *Session) readTextFile(raw json.RawMessage) (any, error) {
var params ReadTextFileParams
if err := json.Unmarshal(raw, ¶ms); err != nil {
return nil, &jsonrpc.ResponseError{Code: jsonrpc.CodeInvalidParams, Message: err.Error()}
}
if s.options.ReadTextFile == nil {
return nil, errors.New("this editor cannot read files for an agent")
}
content, err := s.options.ReadTextFile(params.Path)
if err != nil {
return nil, err
}
return ReadTextFileResult{Content: slice(content, params.Line, params.Limit)}, nil
}
// slice returns the lines the agent asked for, counting from one as the
// protocol does. Asking for neither gives the whole file.
func slice(content string, line, limit *int) string {
if line == nil && limit == nil {
return content
}
lines := splitLines(content)
from := 0
if line != nil && *line > 0 {
from = min(*line-1, len(lines))
}
to := len(lines)
if limit != nil && *limit >= 0 {
to = min(from+*limit, len(lines))
}
return joinLines(lines[from:to])
}
// writeTextFile puts the agent's text where the editor can show it.
func (s *Session) writeTextFile(raw json.RawMessage) (any, error) {
var params WriteTextFileParams
if err := json.Unmarshal(raw, ¶ms); err != nil {
return nil, &jsonrpc.ResponseError{Code: jsonrpc.CodeInvalidParams, Message: err.Error()}
}
if s.options.WriteTextFile == nil {
return nil, errors.New("this editor cannot write files for an agent")
}
if err := s.options.WriteTextFile(params.Path, params.Content); err != nil {
return nil, err
}
return map[string]any{}, nil
}
|