]> git.giacomolli.uk - onechat/blobdiff - agent.go
Run each child with its own files and loop
[onechat] / agent.go
index 4892840786da9a7ff4567d4c4321cd9e45172dd8..274806be60c2f5d772f5d4d38de1693ef4f1bb76 100644 (file)
--- a/agent.go
+++ b/agent.go
@@ -10,6 +10,7 @@ import (
        "io"
        "os"
        "path/filepath"
+       "slices"
        "strings"
 )
 
@@ -50,6 +51,7 @@ func openAgent(dir string) (*Agent, error) {
 
        decoder := json.NewDecoder(bytes.NewReader(data))
        decoder.DisallowUnknownFields()
+
        err = decoder.Decode(&config)
        if err == nil && !errors.Is(decoder.Decode(&struct{}{}), io.EOF) {
                err = errors.New("data after the JSON object")
@@ -85,25 +87,130 @@ func (a *Agent) CacheKey() string {
 // from instructions.md. It reads the file on each call, so a change applies at
 // the next call. A missing file means no instructions.
 func (a *Agent) Prompt() (string, error) {
+       instructions, err := a.instructions()
+       if err != nil {
+               return "", fmt.Errorf("read prompt instructions: %w", err)
+       }
+
+       path, err := filepath.Abs(filepath.Join(a.dir, agentInstructionsFileName))
+       if err != nil {
+               return "", fmt.Errorf("find instructions path: %w", err)
+       }
+
+       if a.config.Parent != "" {
+               return promptChild(a.config.Name, a.config.Parent, a.config.Responsibility, path, instructions), nil
+       }
+
+       return prompt(a.config.Name, path, instructions), nil
+}
+
+// Tools returns the tools shared by the turns and compactions of this agent. A
+// child has no WhatsApp tools.
+func (a *Agent) Tools() []ModelTool {
+       tools := promptTools()
+       if a.config.Parent != "" {
+               tools = slices.DeleteFunc(tools, func(tool ModelTool) bool {
+                       return strings.HasPrefix(tool.Name, "whatsapp_")
+               })
+       }
+
+       return tools
+}
+
+// Children reads the direct children in directory order. Each child needs an
+// existing config with its directory name and this agent as parent. Children
+// cannot have children. A missing children directory means no children.
+func (a *Agent) Children() ([]*Agent, error) {
+       dir := filepath.Join(a.dir, "children")
+       entries, err := os.ReadDir(dir)
+       if errors.Is(err, os.ErrNotExist) {
+               return nil, nil
+       }
+
+       if err != nil {
+               return nil, fmt.Errorf("read children: %w", err)
+       }
+
+       if a.config.Parent != "" && len(entries) != 0 {
+               return nil, errors.New("children cannot have children")
+       }
+
+       var children []*Agent
+
+       keys := map[string]bool{a.CacheKey(): true}
+
+       for _, entry := range entries {
+               name := entry.Name()
+               if !entry.IsDir() {
+                       return nil, fmt.Errorf("child %q must be a directory", name)
+               }
+
+               path := filepath.Join(dir, name)
+               _, err = os.Stat(filepath.Join(path, "config.json"))
+               if err != nil {
+                       return nil, fmt.Errorf("child %q config: %w", name, err)
+               }
+
+               child, err := openAgent(path)
+               if err != nil {
+                       return nil, fmt.Errorf("open child %q: %w", name, err)
+               }
+
+               if child.config.Name != name || child.config.Parent != a.config.Name {
+                       return nil, fmt.Errorf("child %q needs name %q and parent %q", name, name, a.config.Name)
+               }
+
+               if child.config.Name == a.config.Name || keys[child.CacheKey()] {
+                       return nil, fmt.Errorf("child %q must have its own name and ID", name)
+               }
+
+               keys[child.CacheKey()] = true
+               _, err = child.Children()
+               if err != nil {
+                       return nil, fmt.Errorf("read child %q: %w", name, err)
+               }
+
+               children = append(children, child)
+       }
+
+       return children, nil
+}
+
+// SubagentPrompt returns the system prompt of a subagent of the agent, with the
+// user's instructions as Prompt reads them.
+func (a *Agent) SubagentPrompt() (string, error) {
+       instructions, err := a.instructions()
+       if err != nil {
+               return "", err
+       }
+
+       return promptSubagent(a.config.Name, instructions), nil
+}
+
+// instructions reads the user's instructions from instructions.md. A missing
+// file means no instructions.
+func (a *Agent) instructions() (string, error) {
        data, err := os.ReadFile(filepath.Join(a.dir, agentInstructionsFileName))
        if err != nil && !errors.Is(err, os.ErrNotExist) {
                return "", fmt.Errorf("read instructions: %w", err)
        }
 
-       return prompt(a.config.Name, string(data)), nil
+       return string(data), nil
 }
 
 // AgentConfig holds the settings of the config.json of an agent. ID is random,
 // made once when the file is made, and never changes. The cache key comes from
 // the ID, so a rename keeps the prompt cache and two agents with one name do
 // not share a key. Workdir is the directory where the commands of the agent
-// run.
+// run. Responsibility and Parent are set together for a child agent.
 type AgentConfig struct {
-       Name    string `json:"name"`
-       ID      string `json:"id"`
-       Model   string `json:"model"`
-       Effort  string `json:"effort"`
-       Workdir string `json:"workdir"`
+       Name           string `json:"name"`
+       ID             string `json:"id"`
+       Model          string `json:"model"`
+       Effort         string `json:"effort"`
+       Workdir        string `json:"workdir"`
+       Responsibility string `json:"responsibility,omitempty"`
+       Parent         string `json:"parent,omitempty"`
 }
 
 // validate makes sure that each setting has a valid value.
@@ -121,6 +228,14 @@ func (c AgentConfig) validate() error {
                return errors.New("agent needs a model and an effort")
        }
 
+       if (strings.TrimSpace(c.Responsibility) == "") != (c.Parent == "") {
+               return errors.New("a child needs both responsibility and parent")
+       }
+
+       if strings.ContainsAny(c.Parent, "\r\n") {
+               return errors.New("parent must be one line of text")
+       }
+
        if !filepath.IsAbs(c.Workdir) {
                return fmt.Errorf("workdir %q is not an absolute path", c.Workdir)
        }