16 "golang.org/x/sys/unix"
20 // agentInstructionsFileName is the file of the user's instructions in
21 // the directory of an agent.
22 agentInstructionsFileName = "instructions.md"
24 // agentIDBytes is the number of random bytes of an agent ID.
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.
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"`
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"`
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
55 func openAgent(dir string) (*Agent, error) {
56 err := os.MkdirAll(dir, 0o700)
58 return nil, fmt.Errorf("create agent directory: %w", err)
61 path := filepath.Join(dir, "config.json")
62 data, err := os.ReadFile(path)
63 if errors.Is(err, os.ErrNotExist) {
64 return createAgent(dir)
68 return nil, fmt.Errorf("read agent config: %w", err)
71 config, err := defaultAgentConfig()
76 decoder := json.NewDecoder(bytes.NewReader(data))
77 decoder.DisallowUnknownFields()
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")
85 err = config.validate()
89 return nil, fmt.Errorf("%s: %w", path, err)
98 // Images returns the shared data-directory image store, also for a child.
99 func (a *Agent) Images() *ImageStore {
101 if a.config.Parent != "" {
102 root = filepath.Dir(filepath.Dir(root))
105 return &ImageStore{dir: filepath.Join(filepath.Dir(root), imageDirName)}
108 // Voices returns the shared data-directory audio store, also for a child.
109 func (a *Agent) Voices() *VoiceStore {
111 if a.config.Parent != "" {
112 root = filepath.Dir(filepath.Dir(root))
115 return &VoiceStore{dir: filepath.Join(filepath.Dir(root), voiceDirName)}
118 // CacheKey returns the prompt cache key of every model call of the agent.
119 func (a *Agent) CacheKey() string {
120 return "onechat-" + a.config.ID
123 // Prompt returns the system prompt of the agent with the user's instructions
124 // from instructions.md. It reads the file on each call, so a change applies at
125 // the next call. A missing file means no instructions.
126 func (a *Agent) Prompt() (string, error) {
127 instructions, err := a.instructions()
129 return "", fmt.Errorf("read prompt instructions: %w", err)
132 path, err := filepath.Abs(filepath.Join(a.dir, agentInstructionsFileName))
134 return "", fmt.Errorf("find instructions path: %w", err)
137 if a.config.Parent != "" {
138 return promptChild(a.config.Name, a.config.Parent, a.config.Responsibility, path, instructions), nil
141 return prompt(a.config.Name, path, instructions), nil
144 // Tools returns the tools shared by the turns and compactions of this agent. A
145 // child has no image output, WhatsApp, child creation, or route tools.
146 func (a *Agent) Tools() []ModelTool {
147 tools := promptTools()
148 if a.config.Parent != "" {
149 tools = slices.DeleteFunc(tools, func(tool ModelTool) bool {
150 return strings.HasPrefix(tool.Name, "whatsapp_") || tool.Name == "image_show" || tool.Name == "agent_create" || tool.Name == "route" || tool.Name == "unroute" || tool.Name == "routes"
157 // Children reads the direct children in directory order. Each child needs an
158 // existing config with its directory name and this agent as parent. Children
159 // cannot have children. A missing children directory means no children.
160 func (a *Agent) Children() ([]*Agent, error) {
161 dir := filepath.Join(a.dir, "children")
162 entries, err := os.ReadDir(dir)
163 if errors.Is(err, os.ErrNotExist) {
168 return nil, fmt.Errorf("read children: %w", err)
171 if a.config.Parent != "" && len(entries) != 0 {
172 return nil, errors.New("children cannot have children")
175 var children []*Agent
177 keys := map[string]bool{a.CacheKey(): true}
179 for _, entry := range entries {
182 return nil, fmt.Errorf("child %q must be a directory", name)
185 path := filepath.Join(dir, name)
186 _, err = os.Stat(filepath.Join(path, "config.json"))
188 return nil, fmt.Errorf("child %q config: %w", name, err)
191 child, err := openAgent(path)
193 return nil, fmt.Errorf("open child %q: %w", name, err)
196 if child.config.Name != name || child.config.Parent != a.config.Name {
197 return nil, fmt.Errorf("child %q needs name %q and parent %q", name, name, a.config.Name)
200 if child.config.Name == a.config.Name || keys[child.CacheKey()] {
201 return nil, fmt.Errorf("child %q must have its own name and ID", name)
204 keys[child.CacheKey()] = true
205 _, err = child.Children()
207 return nil, fmt.Errorf("read child %q: %w", name, err)
210 children = append(children, child)
216 // CreateChild writes a new direct child with its own ID and the model, effort,
217 // and working directory of the root. Child and subagent names share a
218 // namespace. The config is complete before an atomic rename publishes the
219 // child. Preparation stays outside children, so an interrupted write cannot
221 func (a *Agent) CreateChild(name, responsibility string, subagents *Subagents) (_ *Agent, err error) {
222 if a.config.Parent != "" {
223 return nil, errors.New("only the root can create children")
226 if !agentChildNameValid(name) {
227 return nil, errors.New("name must have 2 to 32 ASCII letters and start with a capital letter")
230 if name == a.config.Name {
231 return nil, errors.New("the name is already used by the root")
234 responsibility = strings.TrimSpace(responsibility)
235 if responsibility == "" {
236 return nil, errors.New("responsibility must not be empty")
239 err = subagents.Reserve(name)
241 return nil, fmt.Errorf("reserve child name: %w", err)
247 subagents.Release(name)
251 staged, err := os.MkdirTemp(a.dir, ".child-*")
253 return nil, fmt.Errorf("prepare child directory: %w", err)
257 cleanupErr := os.RemoveAll(staged)
258 if cleanupErr != nil {
259 err = errors.Join(err, fmt.Errorf("remove prepared child: %w", cleanupErr))
266 config.Parent = a.config.Name
267 config.Responsibility = responsibility
268 child, err := writeAgent(staged, config)
270 return nil, fmt.Errorf("write child: %w", err)
273 dir := filepath.Join(a.dir, "children")
274 err = os.MkdirAll(dir, 0o700)
276 return nil, fmt.Errorf("create children directory: %w", err)
279 dir = filepath.Join(dir, name)
280 err = unix.Renameat2(unix.AT_FDCWD, staged, unix.AT_FDCWD, dir, unix.RENAME_NOREPLACE)
282 return nil, fmt.Errorf("publish child directory: %w", err)
291 // SubagentPrompt returns the system prompt of a subagent of the agent, with the
292 // user's instructions as Prompt reads them.
293 func (a *Agent) SubagentPrompt() (string, error) {
294 instructions, err := a.instructions()
299 return promptSubagent(a.config.Name, instructions), nil
302 // instructions reads the user's instructions from instructions.md. A missing
303 // file means no instructions.
304 func (a *Agent) instructions() (string, error) {
305 data, err := os.ReadFile(filepath.Join(a.dir, agentInstructionsFileName))
306 if err != nil && !errors.Is(err, os.ErrNotExist) {
307 return "", fmt.Errorf("read instructions: %w", err)
310 return string(data), nil
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")
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)
324 if c.Model == "" || c.Effort == "" {
325 return errors.New("agent needs a model and an effort")
328 if (strings.TrimSpace(c.Responsibility) == "") != (c.Parent == "") {
329 return errors.New("a child needs both responsibility and parent")
332 if strings.ContainsAny(c.Parent, "\r\n") {
333 return errors.New("parent must be one line of text")
336 if !filepath.IsAbs(c.Workdir) {
337 return fmt.Errorf("workdir %q is not an absolute path", c.Workdir)
343 // agentChildNameValid accepts one word of 2 to 32 ASCII letters with an initial
344 // capital letter. Child names describe their area.
345 func agentChildNameValid(name string) bool {
346 if len(name) < 2 || len(name) > 32 || name[0] < 'A' || name[0] > 'Z' {
350 for i := 1; i < len(name); i++ {
352 if (letter < 'A' || letter > 'Z') && (letter < 'a' || letter > 'z') {
360 // createAgent writes the config.json of a new agent in dir with the defaults
362 func createAgent(dir string) (*Agent, error) {
363 config, err := defaultAgentConfig()
368 return writeAgent(dir, config)
371 // writeAgent gives config a new ID and writes it in dir.
372 func writeAgent(dir string, config AgentConfig) (*Agent, error) {
373 id := make([]byte, agentIDBytes)
374 _, err := rand.Read(id)
376 return nil, fmt.Errorf("make agent ID: %w", err)
379 config.ID = hex.EncodeToString(id)
380 data, err := json.MarshalIndent(config, "", " ")
382 return nil, fmt.Errorf("encode agent config: %w", err)
385 err = writeFileAtomic(filepath.Join(dir, "config.json"), append(data, '\n'))
387 return nil, fmt.Errorf("write agent config: %w", err)
396 // defaultAgentConfig returns the settings of a new agent, without an ID. The
397 // commands run in the home directory of the user.
398 func defaultAgentConfig() (AgentConfig, error) {
399 home, err := os.UserHomeDir()
401 return AgentConfig{}, fmt.Errorf("find working directory: %w", err)
406 Model: "gpt-6.1-sol",