X-Git-Url: https://git.giacomolli.uk/onechat/blobdiff_plain/4a605fa39078354654ae648e489c117c7a445197..b1be0ee8530df5db8973bfe355f2f6d3149383a0:/agent.go?ds=inline diff --git a/agent.go b/agent.go index 1b4873a..b86880e 100644 --- a/agent.go +++ b/agent.go @@ -10,38 +10,21 @@ import ( "io" "os" "path/filepath" + "slices" "strings" + + "golang.org/x/sys/unix" ) const ( - // instructionsFileName is the file of the user's instructions in the - // directory of an agent. - instructionsFileName = "instructions.md" + // agentInstructionsFileName is the file of the user's instructions in + // the directory of an agent. + agentInstructionsFileName = "instructions.md" // agentIDBytes is the number of random bytes of an agent ID. agentIDBytes = 16 ) -// 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. -type AgentConfig struct { - Name string `json:"name"` - ID string `json:"id"` - Model string `json:"model"` - Effort string `json:"effort"` - Workdir string `json:"workdir"` -} - -// Agent is one agent and its directory. The directory holds config.json, the -// user's instructions in instructions.md, the chat, and the usage file. -type Agent struct { - dir string - config AgentConfig -} - // openAgent reads the config.json of the agent in dir. When the file does not // exist, it makes the directory and writes the file with the defaults and a new // ID. A missing field of an existing file takes the default, but the ID must be @@ -70,6 +53,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") @@ -89,51 +73,231 @@ func openAgent(dir string) (*Agent, error) { }, nil } -// createAgent writes the config.json of a new agent in dir with the defaults -// and a new ID. -func createAgent(dir string) (*Agent, error) { - config, err := defaultAgentConfig() +// Agent is one agent and its directory. The directory holds config.json, the +// user's instructions in instructions.md, the chat, and the usage file. +type Agent struct { + dir string + 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 +} + +// Prompt returns the system prompt of the agent with the user's instructions +// 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 nil, err + return "", fmt.Errorf("read prompt instructions: %w", err) } - id := make([]byte, agentIDBytes) - _, err = rand.Read(id) + path, err := filepath.Abs(filepath.Join(a.dir, agentInstructionsFileName)) if err != nil { - return nil, fmt.Errorf("make agent ID: %w", err) + 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 image output, 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 { + return strings.HasPrefix(tool.Name, "whatsapp_") || tool.Name == "image_show" || tool.Name == "agent_create" || tool.Name == "route" || tool.Name == "unroute" || tool.Name == "routes" + }) + } + + 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 } - config.ID = hex.EncodeToString(id) - data, err := json.MarshalIndent(config, "", " ") if err != nil { - return nil, fmt.Errorf("encode agent config: %w", err) + return nil, fmt.Errorf("read children: %w", err) } - err = writeFileAtomic(filepath.Join(dir, "config.json"), append(data, '\n')) + 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 +} + +// 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("write agent config: %w", err) + return nil, fmt.Errorf("reserve child name: %w", err) } - return &Agent{ - dir: dir, - config: config, - }, nil + 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 } -// defaultAgentConfig returns the settings of a new agent, without an ID. The -// commands run in the home directory of the user. -func defaultAgentConfig() (AgentConfig, error) { - home, err := os.UserHomeDir() +// 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 AgentConfig{}, fmt.Errorf("find working directory: %w", err) + return "", err } - return AgentConfig{ - Name: "OneChat", - Model: "gpt-6.1-sol", - Effort: "medium", - Workdir: home, - }, nil + 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 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. 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"` + Responsibility string `json:"responsibility,omitempty"` + Parent string `json:"parent,omitempty"` } // validate makes sure that each setting has a valid value. @@ -151,6 +315,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) } @@ -158,19 +330,71 @@ func (c AgentConfig) validate() error { return nil } -// CacheKey returns the prompt cache key of every model call of the agent. -func (a *Agent) CacheKey() string { - return "onechat-" + a.config.ID +// 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 } -// Prompt returns the system prompt of the agent with the user's instructions -// 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) { - data, err := os.ReadFile(filepath.Join(a.dir, instructionsFileName)) - if err != nil && !errors.Is(err, os.ErrNotExist) { - return "", fmt.Errorf("read instructions: %w", err) +// createAgent writes the config.json of a new agent in dir with the defaults +// and a new ID. +func createAgent(dir string) (*Agent, error) { + config, err := defaultAgentConfig() + if err != nil { + 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) + _, err := rand.Read(id) + if err != nil { + return nil, fmt.Errorf("make agent ID: %w", err) + } + + config.ID = hex.EncodeToString(id) + data, err := json.MarshalIndent(config, "", " ") + if err != nil { + return nil, fmt.Errorf("encode agent config: %w", err) + } + + err = writeFileAtomic(filepath.Join(dir, "config.json"), append(data, '\n')) + if err != nil { + return nil, fmt.Errorf("write agent config: %w", err) } - return prompt(a.config.Name, string(data)), nil + return &Agent{ + dir: dir, + config: config, + }, nil +} + +// defaultAgentConfig returns the settings of a new agent, without an ID. The +// commands run in the home directory of the user. +func defaultAgentConfig() (AgentConfig, error) { + home, err := os.UserHomeDir() + if err != nil { + return AgentConfig{}, fmt.Errorf("find working directory: %w", err) + } + + return AgentConfig{ + Name: "OneChat", + Model: "gpt-6.1-sol", + Effort: "medium", + Workdir: home, + }, nil }