]> git.giacomolli.uk - onechat/blob - agent.go
Order functions by their first use
[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 "golang.org/x/sys/unix"
17 )
18
19 const (
20 // agentInstructionsFileName is the file of the user's instructions in
21 // the directory of an agent.
22 agentInstructionsFileName = "instructions.md"
23
24 // agentIDBytes is the number of random bytes of an agent ID.
25 agentIDBytes = 16
26 )
27
28 // Agent is one agent and its directory. The directory holds config.json, the
29 // user's instructions in instructions.md, the chat, and the usage file.
30 type Agent struct {
31 dir string
32 config AgentConfig
33 }
34
35 // AgentConfig holds the settings of the config.json of an agent. ID is random,
36 // made once when the file is made, and never changes. The cache key comes from
37 // the ID, so a rename keeps the prompt cache and two agents with one name do
38 // not share a key. Workdir is the directory where the commands of the agent
39 // run. Responsibility and Parent are set together for a child agent.
40 type AgentConfig struct {
41 Name string `json:"name"`
42 ID string `json:"id"`
43 Model string `json:"model"`
44 Effort string `json:"effort"`
45 Workdir string `json:"workdir"`
46 Responsibility string `json:"responsibility,omitempty"`
47 Parent string `json:"parent,omitempty"`
48 }
49
50 // openAgent reads the config.json of the agent in dir. When the file does not
51 // exist, it makes the directory and writes the file with the defaults and a new
52 // ID. A missing field of an existing file takes the default, but the ID must be
53 // there. An unknown field is an error, so a typo does not become a silent
54 // default.
55 func openAgent(dir string) (*Agent, error) {
56 err := os.MkdirAll(dir, 0o700)
57 if err != nil {
58 return nil, fmt.Errorf("create agent directory: %w", err)
59 }
60
61 path := filepath.Join(dir, "config.json")
62 data, err := os.ReadFile(path)
63 if errors.Is(err, os.ErrNotExist) {
64 return createAgent(dir)
65 }
66
67 if err != nil {
68 return nil, fmt.Errorf("read agent config: %w", err)
69 }
70
71 config, err := defaultAgentConfig()
72 if err != nil {
73 return nil, err
74 }
75
76 decoder := json.NewDecoder(bytes.NewReader(data))
77 decoder.DisallowUnknownFields()
78
79 err = decoder.Decode(&config)
80 if err == nil && !errors.Is(decoder.Decode(&struct{}{}), io.EOF) {
81 err = errors.New("data after the JSON object")
82 }
83
84 if err == nil {
85 err = config.validate()
86 }
87
88 if err != nil {
89 return nil, fmt.Errorf("%s: %w", path, err)
90 }
91
92 return &Agent{
93 dir: dir,
94 config: config,
95 }, nil
96 }
97
98 // Images returns the shared data-directory image store, also for a child.
99 func (a *Agent) Images() *ImageStore {
100 root := a.dir
101 if a.config.Parent != "" {
102 root = filepath.Dir(filepath.Dir(root))
103 }
104
105 return &ImageStore{dir: filepath.Join(filepath.Dir(root), imageDirName)}
106 }
107
108 // Voices returns the shared data-directory audio store, also for a child.
109 func (a *Agent) Voices() *VoiceStore {
110 root := a.dir
111 if a.config.Parent != "" {
112 root = filepath.Dir(filepath.Dir(root))
113 }
114
115 return &VoiceStore{dir: filepath.Join(filepath.Dir(root), voiceDirName)}
116 }
117
118 // Prompt returns the system prompt of the agent with the user's instructions
119 // from instructions.md. It reads the file on each call, so a change applies at
120 // the next call. A missing file means no instructions.
121 func (a *Agent) Prompt() (string, error) {
122 instructions, err := a.instructions()
123 if err != nil {
124 return "", fmt.Errorf("read prompt instructions: %w", err)
125 }
126
127 path, err := filepath.Abs(filepath.Join(a.dir, agentInstructionsFileName))
128 if err != nil {
129 return "", fmt.Errorf("find instructions path: %w", err)
130 }
131
132 if a.config.Parent != "" {
133 return promptChild(a.config.Name, a.config.Parent, a.config.Responsibility, path, instructions), nil
134 }
135
136 return prompt(a.config.Name, path, instructions), nil
137 }
138
139 // instructions reads the user's instructions from instructions.md. A missing
140 // file means no instructions.
141 func (a *Agent) instructions() (string, error) {
142 data, err := os.ReadFile(filepath.Join(a.dir, agentInstructionsFileName))
143 if err != nil && !errors.Is(err, os.ErrNotExist) {
144 return "", fmt.Errorf("read instructions: %w", err)
145 }
146
147 return string(data), nil
148 }
149
150 // Tools returns the tools shared by the turns and compactions of this agent. A
151 // child has no image output, WhatsApp, child creation, or route tools.
152 func (a *Agent) Tools() []ModelTool {
153 tools := promptTools()
154 if a.config.Parent != "" {
155 tools = slices.DeleteFunc(tools, func(tool ModelTool) bool {
156 return strings.HasPrefix(tool.Name, "whatsapp_") || tool.Name == "image_show" || tool.Name == "agent_create" || tool.Name == "route" || tool.Name == "unroute" || tool.Name == "routes"
157 })
158 }
159
160 return tools
161 }
162
163 // Children reads the direct children in directory order. Each child needs an
164 // existing config with its directory name and this agent as parent. Children
165 // cannot have children. A missing children directory means no children.
166 func (a *Agent) Children() ([]*Agent, error) {
167 dir := filepath.Join(a.dir, "children")
168 entries, err := os.ReadDir(dir)
169 if errors.Is(err, os.ErrNotExist) {
170 return nil, nil
171 }
172
173 if err != nil {
174 return nil, fmt.Errorf("read children: %w", err)
175 }
176
177 if a.config.Parent != "" && len(entries) != 0 {
178 return nil, errors.New("children cannot have children")
179 }
180
181 var children []*Agent
182
183 keys := map[string]bool{a.CacheKey(): true}
184
185 for _, entry := range entries {
186 name := entry.Name()
187 if !entry.IsDir() {
188 return nil, fmt.Errorf("child %q must be a directory", name)
189 }
190
191 path := filepath.Join(dir, name)
192 _, err = os.Stat(filepath.Join(path, "config.json"))
193 if err != nil {
194 return nil, fmt.Errorf("child %q config: %w", name, err)
195 }
196
197 child, err := openAgent(path)
198 if err != nil {
199 return nil, fmt.Errorf("open child %q: %w", name, err)
200 }
201
202 if child.config.Name != name || child.config.Parent != a.config.Name {
203 return nil, fmt.Errorf("child %q needs name %q and parent %q", name, name, a.config.Name)
204 }
205
206 if child.config.Name == a.config.Name || keys[child.CacheKey()] {
207 return nil, fmt.Errorf("child %q must have its own name and ID", name)
208 }
209
210 keys[child.CacheKey()] = true
211 _, err = child.Children()
212 if err != nil {
213 return nil, fmt.Errorf("read child %q: %w", name, err)
214 }
215
216 children = append(children, child)
217 }
218
219 return children, nil
220 }
221
222 // CacheKey returns the prompt cache key of every model call of the agent.
223 func (a *Agent) CacheKey() string {
224 return "onechat-" + a.config.ID
225 }
226
227 // CreateChild writes a new direct child with its own ID and the model, effort,
228 // and working directory of the root. Child and subagent names share a
229 // namespace. The config is complete before an atomic rename publishes the
230 // child. Preparation stays outside children, so an interrupted write cannot
231 // stop startup.
232 func (a *Agent) CreateChild(name, responsibility string, subagents *Subagents) (_ *Agent, err error) {
233 if a.config.Parent != "" {
234 return nil, errors.New("only the root can create children")
235 }
236
237 if !agentChildNameValid(name) {
238 return nil, errors.New("name must have 2 to 32 ASCII letters and start with a capital letter")
239 }
240
241 if name == a.config.Name {
242 return nil, errors.New("the name is already used by the root")
243 }
244
245 responsibility = strings.TrimSpace(responsibility)
246 if responsibility == "" {
247 return nil, errors.New("responsibility must not be empty")
248 }
249
250 err = subagents.Reserve(name)
251 if err != nil {
252 return nil, fmt.Errorf("reserve child name: %w", err)
253 }
254
255 published := false
256 defer func() {
257 if !published {
258 subagents.Release(name)
259 }
260 }()
261
262 staged, err := os.MkdirTemp(a.dir, ".child-*")
263 if err != nil {
264 return nil, fmt.Errorf("prepare child directory: %w", err)
265 }
266
267 defer func() {
268 cleanupErr := os.RemoveAll(staged)
269 if cleanupErr != nil {
270 err = errors.Join(err, fmt.Errorf("remove prepared child: %w", cleanupErr))
271 }
272 }()
273
274 config := a.config
275 config.Name = name
276 config.ID = ""
277 config.Parent = a.config.Name
278 config.Responsibility = responsibility
279 child, err := writeAgent(staged, config)
280 if err != nil {
281 return nil, fmt.Errorf("write child: %w", err)
282 }
283
284 dir := filepath.Join(a.dir, "children")
285 err = os.MkdirAll(dir, 0o700)
286 if err != nil {
287 return nil, fmt.Errorf("create children directory: %w", err)
288 }
289
290 dir = filepath.Join(dir, name)
291 err = unix.Renameat2(unix.AT_FDCWD, staged, unix.AT_FDCWD, dir, unix.RENAME_NOREPLACE)
292 if err != nil {
293 return nil, fmt.Errorf("publish child directory: %w", err)
294 }
295
296 published = true
297 child.dir = dir
298
299 return child, nil
300 }
301
302 // SubagentPrompt returns the system prompt of a subagent of the agent, with the
303 // user's instructions as Prompt reads them.
304 func (a *Agent) SubagentPrompt() (string, error) {
305 instructions, err := a.instructions()
306 if err != nil {
307 return "", err
308 }
309
310 return promptSubagent(a.config.Name, instructions), nil
311 }
312
313 // validate makes sure that each setting has a valid value.
314 func (c AgentConfig) validate() error {
315 if c.Name == "" || strings.ContainsAny(c.Name, "\r\n") {
316 return errors.New("name must be one line of text")
317 }
318
319 id, err := hex.DecodeString(c.ID)
320 if err != nil || len(id) != agentIDBytes {
321 return fmt.Errorf("id must be %d hexadecimal digits", 2*agentIDBytes)
322 }
323
324 if c.Model == "" || c.Effort == "" {
325 return errors.New("agent needs a model and an effort")
326 }
327
328 if (strings.TrimSpace(c.Responsibility) == "") != (c.Parent == "") {
329 return errors.New("a child needs both responsibility and parent")
330 }
331
332 if strings.ContainsAny(c.Parent, "\r\n") {
333 return errors.New("parent must be one line of text")
334 }
335
336 if !filepath.IsAbs(c.Workdir) {
337 return fmt.Errorf("workdir %q is not an absolute path", c.Workdir)
338 }
339
340 return nil
341 }
342
343 // createAgent writes the config.json of a new agent in dir with the defaults
344 // and a new ID.
345 func createAgent(dir string) (*Agent, error) {
346 config, err := defaultAgentConfig()
347 if err != nil {
348 return nil, err
349 }
350
351 return writeAgent(dir, config)
352 }
353
354 // defaultAgentConfig returns the settings of a new agent, without an ID. The
355 // commands run in the home directory of the user.
356 func defaultAgentConfig() (AgentConfig, error) {
357 home, err := os.UserHomeDir()
358 if err != nil {
359 return AgentConfig{}, fmt.Errorf("find working directory: %w", err)
360 }
361
362 return AgentConfig{
363 Name: "OneChat",
364 Model: "gpt-6.1-sol",
365 Effort: "medium",
366 Workdir: home,
367 }, nil
368 }
369
370 // agentChildNameValid accepts one word of 2 to 32 ASCII letters with an initial
371 // capital letter. Child names describe their area.
372 func agentChildNameValid(name string) bool {
373 if len(name) < 2 || len(name) > 32 || name[0] < 'A' || name[0] > 'Z' {
374 return false
375 }
376
377 for i := 1; i < len(name); i++ {
378 letter := name[i]
379 if (letter < 'A' || letter > 'Z') && (letter < 'a' || letter > 'z') {
380 return false
381 }
382 }
383
384 return true
385 }
386
387 // writeAgent gives config a new ID and writes it in dir.
388 func writeAgent(dir string, config AgentConfig) (*Agent, error) {
389 id := make([]byte, agentIDBytes)
390 _, err := rand.Read(id)
391 if err != nil {
392 return nil, fmt.Errorf("make agent ID: %w", err)
393 }
394
395 config.ID = hex.EncodeToString(id)
396 data, err := json.MarshalIndent(config, "", " ")
397 if err != nil {
398 return nil, fmt.Errorf("encode agent config: %w", err)
399 }
400
401 err = writeFileAtomic(filepath.Join(dir, "config.json"), append(data, '\n'))
402 if err != nil {
403 return nil, fmt.Errorf("write agent config: %w", err)
404 }
405
406 return &Agent{
407 dir: dir,
408 config: config,
409 }, nil
410 }