X-Git-Url: https://git.giacomolli.uk/onechat/blobdiff_plain/77f29e78734dc16cfcea5f41b8e0185f8b33534a..2124c559da8f164a43a3da987b399b6ac6125035:/agent.go diff --git a/agent.go b/agent.go index 790e18b..274806b 100644 --- a/agent.go +++ b/agent.go @@ -10,6 +10,7 @@ import ( "io" "os" "path/filepath" + "slices" "strings" ) @@ -103,6 +104,78 @@ func (a *Agent) Prompt() (string, error) { 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) {