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