]> git.giacomolli.uk - onechat/blobdiff - agent.go
Name timeouts for the operations they limit
[onechat] / agent.go
index 274806be60c2f5d772f5d4d38de1693ef4f1bb76..97d668585dd42d36e7816c3d2870e0d950b613d0 100644 (file)
--- a/agent.go
+++ b/agent.go
@@ -12,6 +12,8 @@ import (
        "path/filepath"
        "slices"
        "strings"
        "path/filepath"
        "slices"
        "strings"
+
+       "golang.org/x/sys/unix"
 )
 
 const (
 )
 
 const (
@@ -78,6 +80,16 @@ type Agent struct {
        config AgentConfig
 }
 
        config AgentConfig
 }
 
+// Images returns the shared data-directory image store, also for a child.
+func (a *Agent) Images() *ImageStore {
+       root := a.dir
+       if a.config.Parent != "" {
+               root = filepath.Dir(filepath.Dir(root))
+       }
+
+       return &ImageStore{dir: filepath.Join(filepath.Dir(root), imageDirName)}
+}
+
 // CacheKey returns the prompt cache key of every model call of the agent.
 func (a *Agent) CacheKey() string {
        return "onechat-" + a.config.ID
 // CacheKey returns the prompt cache key of every model call of the agent.
 func (a *Agent) CacheKey() string {
        return "onechat-" + a.config.ID
@@ -105,12 +117,12 @@ func (a *Agent) Prompt() (string, error) {
 }
 
 // Tools returns the tools shared by the turns and compactions of this agent. A
 }
 
 // Tools returns the tools shared by the turns and compactions of this agent. A
-// child has no WhatsApp tools.
+// child has no WhatsApp, child creation, or route tools.
 func (a *Agent) Tools() []ModelTool {
        tools := promptTools()
        if a.config.Parent != "" {
                tools = slices.DeleteFunc(tools, func(tool ModelTool) bool {
 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 strings.HasPrefix(tool.Name, "whatsapp_") || tool.Name == "agent_create" || tool.Name == "route" || tool.Name == "unroute" || tool.Name == "routes"
                })
        }
 
                })
        }
 
@@ -176,6 +188,81 @@ func (a *Agent) Children() ([]*Agent, error) {
        return children, nil
 }
 
        return children, nil
 }
 
+// CreateChild writes a new direct child with its own ID and the model, effort,
+// and working directory of the root. Child and subagent names share a
+// namespace. The config is complete before an atomic rename publishes the
+// child. Preparation stays outside children, so an interrupted write cannot
+// stop startup.
+func (a *Agent) CreateChild(name, responsibility string, subagents *Subagents) (_ *Agent, err error) {
+       if a.config.Parent != "" {
+               return nil, errors.New("only the root can create children")
+       }
+
+       if !agentChildNameValid(name) {
+               return nil, errors.New("name must have 2 to 32 ASCII letters and start with a capital letter")
+       }
+
+       if name == a.config.Name {
+               return nil, errors.New("the name is already used by the root")
+       }
+
+       responsibility = strings.TrimSpace(responsibility)
+       if responsibility == "" {
+               return nil, errors.New("responsibility must not be empty")
+       }
+
+       err = subagents.Reserve(name)
+       if err != nil {
+               return nil, fmt.Errorf("reserve child name: %w", err)
+       }
+
+       published := false
+       defer func() {
+               if !published {
+                       subagents.Release(name)
+               }
+       }()
+
+       staged, err := os.MkdirTemp(a.dir, ".child-*")
+       if err != nil {
+               return nil, fmt.Errorf("prepare child directory: %w", err)
+       }
+
+       defer func() {
+               cleanupErr := os.RemoveAll(staged)
+               if cleanupErr != nil {
+                       err = errors.Join(err, fmt.Errorf("remove prepared child: %w", cleanupErr))
+               }
+       }()
+
+       config := a.config
+       config.Name = name
+       config.ID = ""
+       config.Parent = a.config.Name
+       config.Responsibility = responsibility
+       child, err := writeAgent(staged, config)
+       if err != nil {
+               return nil, fmt.Errorf("write child: %w", err)
+       }
+
+       dir := filepath.Join(a.dir, "children")
+       err = os.MkdirAll(dir, 0o700)
+       if err != nil {
+               return nil, fmt.Errorf("create children directory: %w", err)
+       }
+
+       dir = filepath.Join(dir, name)
+       err = unix.Renameat2(unix.AT_FDCWD, staged, unix.AT_FDCWD, dir, unix.RENAME_NOREPLACE)
+       if err != nil {
+               return nil, fmt.Errorf("publish child directory: %w", err)
+       }
+
+       published = true
+       child.dir = dir
+
+       return child, 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) {
 // 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) {
@@ -243,6 +330,23 @@ func (c AgentConfig) validate() error {
        return nil
 }
 
        return nil
 }
 
+// agentChildNameValid accepts one word of 2 to 32 ASCII letters with an initial
+// capital letter. Child names describe their area.
+func agentChildNameValid(name string) bool {
+       if len(name) < 2 || len(name) > 32 || name[0] < 'A' || name[0] > 'Z' {
+               return false
+       }
+
+       for i := 1; i < len(name); i++ {
+               letter := name[i]
+               if (letter < 'A' || letter > 'Z') && (letter < 'a' || letter > 'z') {
+                       return false
+               }
+       }
+
+       return true
+}
+
 // createAgent writes the config.json of a new agent in dir with the defaults
 // and a new ID.
 func createAgent(dir string) (*Agent, error) {
 // createAgent writes the config.json of a new agent in dir with the defaults
 // and a new ID.
 func createAgent(dir string) (*Agent, error) {
@@ -251,8 +355,13 @@ func createAgent(dir string) (*Agent, error) {
                return nil, err
        }
 
                return nil, err
        }
 
+       return writeAgent(dir, config)
+}
+
+// writeAgent gives config a new ID and writes it in dir.
+func writeAgent(dir string, config AgentConfig) (*Agent, error) {
        id := make([]byte, agentIDBytes)
        id := make([]byte, agentIDBytes)
-       _, err = rand.Read(id)
+       _, err := rand.Read(id)
        if err != nil {
                return nil, fmt.Errorf("make agent ID: %w", err)
        }
        if err != nil {
                return nil, fmt.Errorf("make agent ID: %w", err)
        }