]> git.giacomolli.uk - onechat/blob - agent.go
Deliver messages between parent and child agents
[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         "slices"
14         "strings"
15 )
16
17 const (
18         // agentInstructionsFileName is the file of the user's instructions in
19         // the directory of an agent.
20         agentInstructionsFileName = "instructions.md"
21
22         // agentIDBytes is the number of random bytes of an agent ID.
23         agentIDBytes = 16
24 )
25
26 // openAgent reads the config.json of the agent in dir. When the file does not
27 // exist, it makes the directory and writes the file with the defaults and a new
28 // ID. A missing field of an existing file takes the default, but the ID must be
29 // there. An unknown field is an error, so a typo does not become a silent
30 // default.
31 func openAgent(dir string) (*Agent, error) {
32         err := os.MkdirAll(dir, 0o700)
33         if err != nil {
34                 return nil, fmt.Errorf("create agent directory: %w", err)
35         }
36
37         path := filepath.Join(dir, "config.json")
38         data, err := os.ReadFile(path)
39         if errors.Is(err, os.ErrNotExist) {
40                 return createAgent(dir)
41         }
42
43         if err != nil {
44                 return nil, fmt.Errorf("read agent config: %w", err)
45         }
46
47         config, err := defaultAgentConfig()
48         if err != nil {
49                 return nil, err
50         }
51
52         decoder := json.NewDecoder(bytes.NewReader(data))
53         decoder.DisallowUnknownFields()
54
55         err = decoder.Decode(&config)
56         if err == nil && !errors.Is(decoder.Decode(&struct{}{}), io.EOF) {
57                 err = errors.New("data after the JSON object")
58         }
59
60         if err == nil {
61                 err = config.validate()
62         }
63
64         if err != nil {
65                 return nil, fmt.Errorf("%s: %w", path, err)
66         }
67
68         return &Agent{
69                 dir:    dir,
70                 config: config,
71         }, nil
72 }
73
74 // Agent is one agent and its directory. The directory holds config.json, the
75 // user's instructions in instructions.md, the chat, and the usage file.
76 type Agent struct {
77         dir    string
78         config AgentConfig
79 }
80
81 // CacheKey returns the prompt cache key of every model call of the agent.
82 func (a *Agent) CacheKey() string {
83         return "onechat-" + a.config.ID
84 }
85
86 // Prompt returns the system prompt of the agent with the user's instructions
87 // from instructions.md. It reads the file on each call, so a change applies at
88 // the next call. A missing file means no instructions.
89 func (a *Agent) Prompt() (string, error) {
90         instructions, err := a.instructions()
91         if err != nil {
92                 return "", fmt.Errorf("read prompt instructions: %w", err)
93         }
94
95         path, err := filepath.Abs(filepath.Join(a.dir, agentInstructionsFileName))
96         if err != nil {
97                 return "", fmt.Errorf("find instructions path: %w", err)
98         }
99
100         if a.config.Parent != "" {
101                 return promptChild(a.config.Name, a.config.Parent, a.config.Responsibility, path, instructions), nil
102         }
103
104         return prompt(a.config.Name, path, instructions), nil
105 }
106
107 // Tools returns the tools shared by the turns and compactions of this agent. A
108 // child has no WhatsApp tools.
109 func (a *Agent) Tools() []ModelTool {
110         tools := promptTools()
111         if a.config.Parent != "" {
112                 tools = slices.DeleteFunc(tools, func(tool ModelTool) bool {
113                         return strings.HasPrefix(tool.Name, "whatsapp_")
114                 })
115         }
116
117         return tools
118 }
119
120 // Children reads the direct children in directory order. Each child needs an
121 // existing config with its directory name and this agent as parent. Children
122 // cannot have children. A missing children directory means no children.
123 func (a *Agent) Children() ([]*Agent, error) {
124         dir := filepath.Join(a.dir, "children")
125         entries, err := os.ReadDir(dir)
126         if errors.Is(err, os.ErrNotExist) {
127                 return nil, nil
128         }
129
130         if err != nil {
131                 return nil, fmt.Errorf("read children: %w", err)
132         }
133
134         if a.config.Parent != "" && len(entries) != 0 {
135                 return nil, errors.New("children cannot have children")
136         }
137
138         var children []*Agent
139
140         keys := map[string]bool{a.CacheKey(): true}
141
142         for _, entry := range entries {
143                 name := entry.Name()
144                 if !entry.IsDir() {
145                         return nil, fmt.Errorf("child %q must be a directory", name)
146                 }
147
148                 path := filepath.Join(dir, name)
149                 _, err = os.Stat(filepath.Join(path, "config.json"))
150                 if err != nil {
151                         return nil, fmt.Errorf("child %q config: %w", name, err)
152                 }
153
154                 child, err := openAgent(path)
155                 if err != nil {
156                         return nil, fmt.Errorf("open child %q: %w", name, err)
157                 }
158
159                 if child.config.Name != name || child.config.Parent != a.config.Name {
160                         return nil, fmt.Errorf("child %q needs name %q and parent %q", name, name, a.config.Name)
161                 }
162
163                 if child.config.Name == a.config.Name || keys[child.CacheKey()] {
164                         return nil, fmt.Errorf("child %q must have its own name and ID", name)
165                 }
166
167                 keys[child.CacheKey()] = true
168                 _, err = child.Children()
169                 if err != nil {
170                         return nil, fmt.Errorf("read child %q: %w", name, err)
171                 }
172
173                 children = append(children, child)
174         }
175
176         return children, nil
177 }
178
179 // SubagentPrompt returns the system prompt of a subagent of the agent, with the
180 // user's instructions as Prompt reads them.
181 func (a *Agent) SubagentPrompt() (string, error) {
182         instructions, err := a.instructions()
183         if err != nil {
184                 return "", err
185         }
186
187         return promptSubagent(a.config.Name, instructions), nil
188 }
189
190 // instructions reads the user's instructions from instructions.md. A missing
191 // file means no instructions.
192 func (a *Agent) instructions() (string, error) {
193         data, err := os.ReadFile(filepath.Join(a.dir, agentInstructionsFileName))
194         if err != nil && !errors.Is(err, os.ErrNotExist) {
195                 return "", fmt.Errorf("read instructions: %w", err)
196         }
197
198         return string(data), nil
199 }
200
201 // AgentConfig holds the settings of the config.json of an agent. ID is random,
202 // made once when the file is made, and never changes. The cache key comes from
203 // the ID, so a rename keeps the prompt cache and two agents with one name do
204 // not share a key. Workdir is the directory where the commands of the agent
205 // run. Responsibility and Parent are set together for a child agent.
206 type AgentConfig struct {
207         Name           string `json:"name"`
208         ID             string `json:"id"`
209         Model          string `json:"model"`
210         Effort         string `json:"effort"`
211         Workdir        string `json:"workdir"`
212         Responsibility string `json:"responsibility,omitempty"`
213         Parent         string `json:"parent,omitempty"`
214 }
215
216 // validate makes sure that each setting has a valid value.
217 func (c AgentConfig) validate() error {
218         if c.Name == "" || strings.ContainsAny(c.Name, "\r\n") {
219                 return errors.New("name must be one line of text")
220         }
221
222         id, err := hex.DecodeString(c.ID)
223         if err != nil || len(id) != agentIDBytes {
224                 return fmt.Errorf("id must be %d hexadecimal digits", 2*agentIDBytes)
225         }
226
227         if c.Model == "" || c.Effort == "" {
228                 return errors.New("agent needs a model and an effort")
229         }
230
231         if (strings.TrimSpace(c.Responsibility) == "") != (c.Parent == "") {
232                 return errors.New("a child needs both responsibility and parent")
233         }
234
235         if strings.ContainsAny(c.Parent, "\r\n") {
236                 return errors.New("parent must be one line of text")
237         }
238
239         if !filepath.IsAbs(c.Workdir) {
240                 return fmt.Errorf("workdir %q is not an absolute path", c.Workdir)
241         }
242
243         return nil
244 }
245
246 // createAgent writes the config.json of a new agent in dir with the defaults
247 // and a new ID.
248 func createAgent(dir string) (*Agent, error) {
249         config, err := defaultAgentConfig()
250         if err != nil {
251                 return nil, err
252         }
253
254         id := make([]byte, agentIDBytes)
255         _, err = rand.Read(id)
256         if err != nil {
257                 return nil, fmt.Errorf("make agent ID: %w", err)
258         }
259
260         config.ID = hex.EncodeToString(id)
261         data, err := json.MarshalIndent(config, "", "  ")
262         if err != nil {
263                 return nil, fmt.Errorf("encode agent config: %w", err)
264         }
265
266         err = writeFileAtomic(filepath.Join(dir, "config.json"), append(data, '\n'))
267         if err != nil {
268                 return nil, fmt.Errorf("write agent config: %w", err)
269         }
270
271         return &Agent{
272                 dir:    dir,
273                 config: config,
274         }, nil
275 }
276
277 // defaultAgentConfig returns the settings of a new agent, without an ID. The
278 // commands run in the home directory of the user.
279 func defaultAgentConfig() (AgentConfig, error) {
280         home, err := os.UserHomeDir()
281         if err != nil {
282                 return AgentConfig{}, fmt.Errorf("find working directory: %w", err)
283         }
284
285         return AgentConfig{
286                 Name:    "OneChat",
287                 Model:   "gpt-6.1-sol",
288                 Effort:  "medium",
289                 Workdir: home,
290         }, nil
291 }