18 // agentInstructionsFileName is the file of the user's instructions in
19 // the directory of an agent.
20 agentInstructionsFileName = "instructions.md"
22 // agentIDBytes is the number of random bytes of an agent ID.
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
31 func openAgent(dir string) (*Agent, error) {
32 err := os.MkdirAll(dir, 0o700)
34 return nil, fmt.Errorf("create agent directory: %w", err)
37 path := filepath.Join(dir, "config.json")
38 data, err := os.ReadFile(path)
39 if errors.Is(err, os.ErrNotExist) {
40 return createAgent(dir)
44 return nil, fmt.Errorf("read agent config: %w", err)
47 config, err := defaultAgentConfig()
52 decoder := json.NewDecoder(bytes.NewReader(data))
53 decoder.DisallowUnknownFields()
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")
61 err = config.validate()
65 return nil, fmt.Errorf("%s: %w", path, err)
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.
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
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()
92 return "", fmt.Errorf("read prompt instructions: %w", err)
95 path, err := filepath.Abs(filepath.Join(a.dir, agentInstructionsFileName))
97 return "", fmt.Errorf("find instructions path: %w", err)
100 if a.config.Parent != "" {
101 return promptChild(a.config.Name, a.config.Parent, a.config.Responsibility, path, instructions), nil
104 return prompt(a.config.Name, path, instructions), nil
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_")
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) {
131 return nil, fmt.Errorf("read children: %w", err)
134 if a.config.Parent != "" && len(entries) != 0 {
135 return nil, errors.New("children cannot have children")
138 var children []*Agent
140 keys := map[string]bool{a.CacheKey(): true}
142 for _, entry := range entries {
145 return nil, fmt.Errorf("child %q must be a directory", name)
148 path := filepath.Join(dir, name)
149 _, err = os.Stat(filepath.Join(path, "config.json"))
151 return nil, fmt.Errorf("child %q config: %w", name, err)
154 child, err := openAgent(path)
156 return nil, fmt.Errorf("open child %q: %w", name, err)
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)
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)
167 keys[child.CacheKey()] = true
168 _, err = child.Children()
170 return nil, fmt.Errorf("read child %q: %w", name, err)
173 children = append(children, child)
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()
187 return promptSubagent(a.config.Name, instructions), nil
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)
198 return string(data), nil
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"`
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")
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)
227 if c.Model == "" || c.Effort == "" {
228 return errors.New("agent needs a model and an effort")
231 if (strings.TrimSpace(c.Responsibility) == "") != (c.Parent == "") {
232 return errors.New("a child needs both responsibility and parent")
235 if strings.ContainsAny(c.Parent, "\r\n") {
236 return errors.New("parent must be one line of text")
239 if !filepath.IsAbs(c.Workdir) {
240 return fmt.Errorf("workdir %q is not an absolute path", c.Workdir)
246 // createAgent writes the config.json of a new agent in dir with the defaults
248 func createAgent(dir string) (*Agent, error) {
249 config, err := defaultAgentConfig()
254 id := make([]byte, agentIDBytes)
255 _, err = rand.Read(id)
257 return nil, fmt.Errorf("make agent ID: %w", err)
260 config.ID = hex.EncodeToString(id)
261 data, err := json.MarshalIndent(config, "", " ")
263 return nil, fmt.Errorf("encode agent config: %w", err)
266 err = writeFileAtomic(filepath.Join(dir, "config.json"), append(data, '\n'))
268 return nil, fmt.Errorf("write agent config: %w", err)
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()
282 return AgentConfig{}, fmt.Errorf("find working directory: %w", err)
287 Model: "gpt-6.1-sol",