]> git.giacomolli.uk - onechat/blob - agent.go
Separate returns from longer statement blocks
[onechat] / agent.go
1 package main
2
3 import (
4         "bytes"
5         "crypto/rand"
6         "encoding/hex"
7         "encoding/json"
8         "errors"
9         "fmt"
10         "io"
11         "os"
12         "path/filepath"
13         "strings"
14 )
15
16 const (
17         // agentInstructionsFileName is the file of the user's instructions in
18         // the directory of an agent.
19         agentInstructionsFileName = "instructions.md"
20
21         // agentIDBytes is the number of random bytes of an agent ID.
22         agentIDBytes = 16
23 )
24
25 // openAgent reads the config.json of the agent in dir. When the file does not
26 // exist, it makes the directory and writes the file with the defaults and a new
27 // ID. A missing field of an existing file takes the default, but the ID must be
28 // there. An unknown field is an error, so a typo does not become a silent
29 // default.
30 func openAgent(dir string) (*Agent, error) {
31         err := os.MkdirAll(dir, 0o700)
32         if err != nil {
33                 return nil, fmt.Errorf("create agent directory: %w", err)
34         }
35
36         path := filepath.Join(dir, "config.json")
37         data, err := os.ReadFile(path)
38         if errors.Is(err, os.ErrNotExist) {
39                 return createAgent(dir)
40         }
41
42         if err != nil {
43                 return nil, fmt.Errorf("read agent config: %w", err)
44         }
45
46         config, err := defaultAgentConfig()
47         if err != nil {
48                 return nil, err
49         }
50
51         decoder := json.NewDecoder(bytes.NewReader(data))
52         decoder.DisallowUnknownFields()
53         err = decoder.Decode(&config)
54         if err == nil && !errors.Is(decoder.Decode(&struct{}{}), io.EOF) {
55                 err = errors.New("data after the JSON object")
56         }
57
58         if err == nil {
59                 err = config.validate()
60         }
61
62         if err != nil {
63                 return nil, fmt.Errorf("%s: %w", path, err)
64         }
65
66         return &Agent{
67                 dir:    dir,
68                 config: config,
69         }, nil
70 }
71
72 // Agent is one agent and its directory. The directory holds config.json, the
73 // user's instructions in instructions.md, the chat, and the usage file.
74 type Agent struct {
75         dir    string
76         config AgentConfig
77 }
78
79 // CacheKey returns the prompt cache key of every model call of the agent.
80 func (a *Agent) CacheKey() string {
81         return "onechat-" + a.config.ID
82 }
83
84 // Prompt returns the system prompt of the agent with the user's instructions
85 // from instructions.md. It reads the file on each call, so a change applies at
86 // the next call. A missing file means no instructions.
87 func (a *Agent) Prompt() (string, error) {
88         instructions, err := a.instructions()
89         if err != nil {
90                 return "", fmt.Errorf("read prompt instructions: %w", err)
91         }
92
93         path, err := filepath.Abs(filepath.Join(a.dir, agentInstructionsFileName))
94         if err != nil {
95                 return "", fmt.Errorf("find instructions path: %w", err)
96         }
97
98         return prompt(a.config.Name, path, instructions), nil
99 }
100
101 // SubagentPrompt returns the system prompt of a subagent of the agent, with the
102 // user's instructions as Prompt reads them.
103 func (a *Agent) SubagentPrompt() (string, error) {
104         instructions, err := a.instructions()
105         if err != nil {
106                 return "", err
107         }
108
109         return promptSubagent(a.config.Name, instructions), nil
110 }
111
112 // instructions reads the user's instructions from instructions.md. A missing
113 // file means no instructions.
114 func (a *Agent) instructions() (string, error) {
115         data, err := os.ReadFile(filepath.Join(a.dir, agentInstructionsFileName))
116         if err != nil && !errors.Is(err, os.ErrNotExist) {
117                 return "", fmt.Errorf("read instructions: %w", err)
118         }
119
120         return string(data), nil
121 }
122
123 // AgentConfig holds the settings of the config.json of an agent. ID is random,
124 // made once when the file is made, and never changes. The cache key comes from
125 // the ID, so a rename keeps the prompt cache and two agents with one name do
126 // not share a key. Workdir is the directory where the commands of the agent
127 // run.
128 type AgentConfig struct {
129         Name    string `json:"name"`
130         ID      string `json:"id"`
131         Model   string `json:"model"`
132         Effort  string `json:"effort"`
133         Workdir string `json:"workdir"`
134 }
135
136 // validate makes sure that each setting has a valid value.
137 func (c AgentConfig) validate() error {
138         if c.Name == "" || strings.ContainsAny(c.Name, "\r\n") {
139                 return errors.New("name must be one line of text")
140         }
141
142         id, err := hex.DecodeString(c.ID)
143         if err != nil || len(id) != agentIDBytes {
144                 return fmt.Errorf("id must be %d hexadecimal digits", 2*agentIDBytes)
145         }
146
147         if c.Model == "" || c.Effort == "" {
148                 return errors.New("agent needs a model and an effort")
149         }
150
151         if !filepath.IsAbs(c.Workdir) {
152                 return fmt.Errorf("workdir %q is not an absolute path", c.Workdir)
153         }
154
155         return nil
156 }
157
158 // createAgent writes the config.json of a new agent in dir with the defaults
159 // and a new ID.
160 func createAgent(dir string) (*Agent, error) {
161         config, err := defaultAgentConfig()
162         if err != nil {
163                 return nil, err
164         }
165
166         id := make([]byte, agentIDBytes)
167         _, err = rand.Read(id)
168         if err != nil {
169                 return nil, fmt.Errorf("make agent ID: %w", err)
170         }
171
172         config.ID = hex.EncodeToString(id)
173         data, err := json.MarshalIndent(config, "", "  ")
174         if err != nil {
175                 return nil, fmt.Errorf("encode agent config: %w", err)
176         }
177
178         err = writeFileAtomic(filepath.Join(dir, "config.json"), append(data, '\n'))
179         if err != nil {
180                 return nil, fmt.Errorf("write agent config: %w", err)
181         }
182
183         return &Agent{
184                 dir:    dir,
185                 config: config,
186         }, nil
187 }
188
189 // defaultAgentConfig returns the settings of a new agent, without an ID. The
190 // commands run in the home directory of the user.
191 func defaultAgentConfig() (AgentConfig, error) {
192         home, err := os.UserHomeDir()
193         if err != nil {
194                 return AgentConfig{}, fmt.Errorf("find working directory: %w", err)
195         }
196
197         return AgentConfig{
198                 Name:    "OneChat",
199                 Model:   "gpt-6.1-sol",
200                 Effort:  "medium",
201                 Workdir: home,
202         }, nil
203 }