// 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 }