]> git.giacomolli.uk - onechat/blob - agent.go
Define child agent areas and reporting rules
[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
54         err = decoder.Decode(&config)
55         if err == nil && !errors.Is(decoder.Decode(&struct{}{}), io.EOF) {
56                 err = errors.New("data after the JSON object")
57         }
58
59         if err == nil {
60                 err = config.validate()
61         }
62
63         if err != nil {
64                 return nil, fmt.Errorf("%s: %w", path, err)
65         }
66
67         return &Agent{
68                 dir:    dir,
69                 config: config,
70         }, nil
71 }
72
73 // Agent is one agent and its directory. The directory holds config.json, the
74 // user's instructions in instructions.md, the chat, and the usage file.
75 type Agent struct {
76         dir    string
77         config AgentConfig
78 }
79
80 // CacheKey returns the prompt cache key of every model call of the agent.
81 func (a *Agent) CacheKey() string {
82         return "onechat-" + a.config.ID
83 }
84
85 // Prompt returns the system prompt of the agent with the user's instructions
86 // from instructions.md. It reads the file on each call, so a change applies at
87 // the next call. A missing file means no instructions.
88 func (a *Agent) Prompt() (string, error) {
89         instructions, err := a.instructions()
90         if err != nil {
91                 return "", fmt.Errorf("read prompt instructions: %w", err)
92         }
93
94         path, err := filepath.Abs(filepath.Join(a.dir, agentInstructionsFileName))
95         if err != nil {
96                 return "", fmt.Errorf("find instructions path: %w", err)
97         }
98
99         if a.config.Parent != "" {
100                 return promptChild(a.config.Name, a.config.Parent, a.config.Responsibility, path, instructions), nil
101         }
102
103         return prompt(a.config.Name, path, instructions), nil
104 }
105
106 // SubagentPrompt returns the system prompt of a subagent of the agent, with the
107 // user's instructions as Prompt reads them.
108 func (a *Agent) SubagentPrompt() (string, error) {
109         instructions, err := a.instructions()
110         if err != nil {
111                 return "", err
112         }
113
114         return promptSubagent(a.config.Name, instructions), nil
115 }
116
117 // instructions reads the user's instructions from instructions.md. A missing
118 // file means no instructions.
119 func (a *Agent) instructions() (string, error) {
120         data, err := os.ReadFile(filepath.Join(a.dir, agentInstructionsFileName))
121         if err != nil && !errors.Is(err, os.ErrNotExist) {
122                 return "", fmt.Errorf("read instructions: %w", err)
123         }
124
125         return string(data), nil
126 }
127
128 // AgentConfig holds the settings of the config.json of an agent. ID is random,
129 // made once when the file is made, and never changes. The cache key comes from
130 // the ID, so a rename keeps the prompt cache and two agents with one name do
131 // not share a key. Workdir is the directory where the commands of the agent
132 // run. Responsibility and Parent are set together for a child agent.
133 type AgentConfig struct {
134         Name           string `json:"name"`
135         ID             string `json:"id"`
136         Model          string `json:"model"`
137         Effort         string `json:"effort"`
138         Workdir        string `json:"workdir"`
139         Responsibility string `json:"responsibility,omitempty"`
140         Parent         string `json:"parent,omitempty"`
141 }
142
143 // validate makes sure that each setting has a valid value.
144 func (c AgentConfig) validate() error {
145         if c.Name == "" || strings.ContainsAny(c.Name, "\r\n") {
146                 return errors.New("name must be one line of text")
147         }
148
149         id, err := hex.DecodeString(c.ID)
150         if err != nil || len(id) != agentIDBytes {
151                 return fmt.Errorf("id must be %d hexadecimal digits", 2*agentIDBytes)
152         }
153
154         if c.Model == "" || c.Effort == "" {
155                 return errors.New("agent needs a model and an effort")
156         }
157
158         if (strings.TrimSpace(c.Responsibility) == "") != (c.Parent == "") {
159                 return errors.New("a child needs both responsibility and parent")
160         }
161
162         if strings.ContainsAny(c.Parent, "\r\n") {
163                 return errors.New("parent must be one line of text")
164         }
165
166         if !filepath.IsAbs(c.Workdir) {
167                 return fmt.Errorf("workdir %q is not an absolute path", c.Workdir)
168         }
169
170         return nil
171 }
172
173 // createAgent writes the config.json of a new agent in dir with the defaults
174 // and a new ID.
175 func createAgent(dir string) (*Agent, error) {
176         config, err := defaultAgentConfig()
177         if err != nil {
178                 return nil, err
179         }
180
181         id := make([]byte, agentIDBytes)
182         _, err = rand.Read(id)
183         if err != nil {
184                 return nil, fmt.Errorf("make agent ID: %w", err)
185         }
186
187         config.ID = hex.EncodeToString(id)
188         data, err := json.MarshalIndent(config, "", "  ")
189         if err != nil {
190                 return nil, fmt.Errorf("encode agent config: %w", err)
191         }
192
193         err = writeFileAtomic(filepath.Join(dir, "config.json"), append(data, '\n'))
194         if err != nil {
195                 return nil, fmt.Errorf("write agent config: %w", err)
196         }
197
198         return &Agent{
199                 dir:    dir,
200                 config: config,
201         }, nil
202 }
203
204 // defaultAgentConfig returns the settings of a new agent, without an ID. The
205 // commands run in the home directory of the user.
206 func defaultAgentConfig() (AgentConfig, error) {
207         home, err := os.UserHomeDir()
208         if err != nil {
209                 return AgentConfig{}, fmt.Errorf("find working directory: %w", err)
210         }
211
212         return AgentConfig{
213                 Name:    "OneChat",
214                 Model:   "gpt-6.1-sol",
215                 Effort:  "medium",
216                 Workdir: home,
217         }, nil
218 }