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 agent, err := createAgent(dir)
66 return agent, fmt.Errorf("create agent: %w", err)
73 return nil, fmt.Errorf("read agent config: %w", err)
76 config, err := defaultAgentConfig()
78 return nil, fmt.Errorf("prepare agent defaults: %w", err)
81 decoder := json.NewDecoder(bytes.NewReader(data))
82 decoder.DisallowUnknownFields()
84 err = decoder.Decode(&config)
85 if err == nil && !errors.Is(decoder.Decode(&struct{}{}), io.EOF) {
86 err = errors.New("data after the JSON object")
90 err = config.validate()
94 return nil, fmt.Errorf("%s: %w", path, err)
103 // Images returns the shared data-directory image store, also for a child.
104 func (a *Agent) Images() *ImageStore {
106 if a.config.Parent != "" {
107 root = filepath.Dir(filepath.Dir(root))
110 return &ImageStore{dir: filepath.Join(filepath.Dir(root), imageDirName)}
113 // Voices returns the shared data-directory audio store, also for a child.
114 func (a *Agent) Voices() *VoiceStore {
116 if a.config.Parent != "" {
117 root = filepath.Dir(filepath.Dir(root))
120 return &VoiceStore{dir: filepath.Join(filepath.Dir(root), voiceDirName)}
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 // instructions reads the user's instructions from instructions.md. A missing
145 // file means no instructions.
146 func (a *Agent) instructions() (string, error) {
147 data, err := os.ReadFile(filepath.Join(a.dir, agentInstructionsFileName))
148 if err != nil && !errors.Is(err, os.ErrNotExist) {
149 return "", fmt.Errorf("read instructions: %w", err)
152 return string(data), nil
155 // Tools returns the tools shared by the turns and compactions of this agent. A
156 // child has no image output, WhatsApp, child creation, or route tools.
157 func (a *Agent) Tools() []ModelTool {
158 tools := promptTools()
159 if a.config.Parent != "" {
160 tools = slices.DeleteFunc(tools, func(tool ModelTool) bool {
161 return strings.HasPrefix(tool.Name, "whatsapp_") || tool.Name == "image_show" || tool.Name == "agent_create" || tool.Name == "route" || tool.Name == "unroute" || tool.Name == "routes"
168 // Children reads the direct children in directory order. Each child needs an
169 // existing config with its directory name and this agent as parent. Children
170 // cannot have children. A missing children directory means no children.
171 func (a *Agent) Children() ([]*Agent, error) {
172 dir := filepath.Join(a.dir, "children")
173 entries, err := os.ReadDir(dir)
174 if errors.Is(err, os.ErrNotExist) {
179 return nil, fmt.Errorf("read children: %w", err)
182 if a.config.Parent != "" && len(entries) != 0 {
183 return nil, errors.New("children cannot have children")
186 var children []*Agent
188 keys := map[string]bool{a.CacheKey(): true}
190 for _, entry := range entries {
193 return nil, fmt.Errorf("child %q must be a directory", name)
196 path := filepath.Join(dir, name)
197 _, err = os.Stat(filepath.Join(path, "config.json"))
199 return nil, fmt.Errorf("child %q config: %w", name, err)
202 child, err := openAgent(path)
204 return nil, fmt.Errorf("open child %q: %w", name, err)
207 if child.config.Name != name || child.config.Parent != a.config.Name {
208 return nil, fmt.Errorf("child %q needs name %q and parent %q", name, name, a.config.Name)
211 if child.config.Name == a.config.Name || keys[child.CacheKey()] {
212 return nil, fmt.Errorf("child %q must have its own name and ID", name)
215 keys[child.CacheKey()] = true
216 _, err = child.Children()
218 return nil, fmt.Errorf("read child %q: %w", name, err)
221 children = append(children, child)
227 // CacheKey returns the prompt cache key of every model call of the agent.
228 func (a *Agent) CacheKey() string {
229 return "onechat-" + a.config.ID
232 // CreateChild writes a new direct child with its own ID and the model, effort,
233 // and working directory of the root. Child and subagent names share a
234 // namespace. The config is complete before an atomic rename publishes the
235 // child. Preparation stays outside children, so an interrupted write cannot
237 func (a *Agent) CreateChild(name, responsibility string, subagents *Subagents) (_ *Agent, err error) {
238 if a.config.Parent != "" {
239 return nil, errors.New("only the root can create children")
242 if !agentChildNameValid(name) {
243 return nil, errors.New("name must have 2 to 32 ASCII letters and start with a capital letter")
246 if name == a.config.Name {
247 return nil, errors.New("the name is already used by the root")
250 responsibility = strings.TrimSpace(responsibility)
251 if responsibility == "" {
252 return nil, errors.New("responsibility must not be empty")
255 err = subagents.Reserve(name)
257 return nil, fmt.Errorf("reserve child name: %w", err)
263 subagents.Release(name)
267 staged, err := os.MkdirTemp(a.dir, ".child-*")
269 return nil, fmt.Errorf("prepare child directory: %w", err)
273 cleanupErr := os.RemoveAll(staged)
274 if cleanupErr != nil {
275 err = errors.Join(err, fmt.Errorf("remove prepared child: %w", cleanupErr))
282 config.Parent = a.config.Name
283 config.Responsibility = responsibility
284 child, err := writeAgent(staged, config)
286 return nil, fmt.Errorf("write child: %w", err)
289 dir := filepath.Join(a.dir, "children")
290 err = os.MkdirAll(dir, 0o700)
292 return nil, fmt.Errorf("create children directory: %w", err)
295 dir = filepath.Join(dir, name)
296 err = unix.Renameat2(unix.AT_FDCWD, staged, unix.AT_FDCWD, dir, unix.RENAME_NOREPLACE)
298 return nil, fmt.Errorf("publish child directory: %w", err)
307 // SubagentPrompt returns the system prompt of a subagent of the agent, with the
308 // user's instructions as Prompt reads them.
309 func (a *Agent) SubagentPrompt() (string, error) {
310 instructions, err := a.instructions()
315 return promptSubagent(a.config.Name, instructions), nil
318 // validate makes sure that each setting has a valid value.
319 func (c AgentConfig) validate() error {
320 if c.Name == "" || strings.ContainsAny(c.Name, "\r\n") {
321 return errors.New("name must be one line of text")
324 id, err := hex.DecodeString(c.ID)
325 if err != nil || len(id) != agentIDBytes {
326 return fmt.Errorf("id must be %d hexadecimal digits", 2*agentIDBytes)
329 if c.Model == "" || c.Effort == "" {
330 return errors.New("agent needs a model and an effort")
333 if (strings.TrimSpace(c.Responsibility) == "") != (c.Parent == "") {
334 return errors.New("a child needs both responsibility and parent")
337 if strings.ContainsAny(c.Parent, "\r\n") {
338 return errors.New("parent must be one line of text")
341 if !filepath.IsAbs(c.Workdir) {
342 return fmt.Errorf("workdir %q is not an absolute path", c.Workdir)
348 // createAgent writes the config.json of a new agent in dir with the defaults
350 func createAgent(dir string) (*Agent, error) {
351 config, err := defaultAgentConfig()
353 return nil, fmt.Errorf("prepare agent defaults: %w", err)
356 agent, err := writeAgent(dir, config)
358 return agent, fmt.Errorf("write new agent: %w", err)
364 // defaultAgentConfig returns the settings of a new agent, without an ID. The
365 // commands run in the home directory of the user.
366 func defaultAgentConfig() (AgentConfig, error) {
367 home, err := os.UserHomeDir()
369 return AgentConfig{}, fmt.Errorf("find working directory: %w", err)
374 Model: "gpt-6.1-sol",
380 // agentChildNameValid accepts one word of 2 to 32 ASCII letters with an initial
381 // capital letter. Child names describe their area.
382 func agentChildNameValid(name string) bool {
383 if len(name) < 2 || len(name) > 32 || name[0] < 'A' || name[0] > 'Z' {
387 for i := 1; i < len(name); i++ {
389 if (letter < 'A' || letter > 'Z') && (letter < 'a' || letter > 'z') {
397 // writeAgent gives config a new ID and writes it in dir.
398 func writeAgent(dir string, config AgentConfig) (*Agent, error) {
399 id := make([]byte, agentIDBytes)
400 _, err := rand.Read(id)
402 return nil, fmt.Errorf("make agent ID: %w", err)
405 config.ID = hex.EncodeToString(id)
406 data, err := json.MarshalIndent(config, "", " ")
408 return nil, fmt.Errorf("encode agent config: %w", err)
411 err = writeFileAtomic(filepath.Join(dir, "config.json"), append(data, '\n'))
413 return nil, fmt.Errorf("write agent config: %w", err)