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 // openAgent reads the config.json of the agent in dir. When the file does not
29 // exist, it makes the directory and writes the file with the defaults and a new
30 // ID. A missing field of an existing file takes the default, but the ID must be
31 // there. An unknown field is an error, so a typo does not become a silent
33 func openAgent(dir string) (*Agent, error) {
34 err := os.MkdirAll(dir, 0o700)
36 return nil, fmt.Errorf("create agent directory: %w", err)
39 path := filepath.Join(dir, "config.json")
40 data, err := os.ReadFile(path)
41 if errors.Is(err, os.ErrNotExist) {
42 return createAgent(dir)
46 return nil, fmt.Errorf("read agent config: %w", err)
49 config, err := defaultAgentConfig()
54 decoder := json.NewDecoder(bytes.NewReader(data))
55 decoder.DisallowUnknownFields()
57 err = decoder.Decode(&config)
58 if err == nil && !errors.Is(decoder.Decode(&struct{}{}), io.EOF) {
59 err = errors.New("data after the JSON object")
63 err = config.validate()
67 return nil, fmt.Errorf("%s: %w", path, err)
76 // Agent is one agent and its directory. The directory holds config.json, the
77 // user's instructions in instructions.md, the chat, and the usage file.
83 // Images returns the shared data-directory image store, also for a child.
84 func (a *Agent) Images() *ImageStore {
86 if a.config.Parent != "" {
87 root = filepath.Dir(filepath.Dir(root))
90 return &ImageStore{dir: filepath.Join(filepath.Dir(root), imageDirName)}
93 // CacheKey returns the prompt cache key of every model call of the agent.
94 func (a *Agent) CacheKey() string {
95 return "onechat-" + a.config.ID
98 // Prompt returns the system prompt of the agent with the user's instructions
99 // from instructions.md. It reads the file on each call, so a change applies at
100 // the next call. A missing file means no instructions.
101 func (a *Agent) Prompt() (string, error) {
102 instructions, err := a.instructions()
104 return "", fmt.Errorf("read prompt instructions: %w", err)
107 path, err := filepath.Abs(filepath.Join(a.dir, agentInstructionsFileName))
109 return "", fmt.Errorf("find instructions path: %w", err)
112 if a.config.Parent != "" {
113 return promptChild(a.config.Name, a.config.Parent, a.config.Responsibility, path, instructions), nil
116 return prompt(a.config.Name, path, instructions), nil
119 // Tools returns the tools shared by the turns and compactions of this agent. A
120 // child has no WhatsApp, child creation, or route tools.
121 func (a *Agent) Tools() []ModelTool {
122 tools := promptTools()
123 if a.config.Parent != "" {
124 tools = slices.DeleteFunc(tools, func(tool ModelTool) bool {
125 return strings.HasPrefix(tool.Name, "whatsapp_") || tool.Name == "agent_create" || tool.Name == "route" || tool.Name == "unroute" || tool.Name == "routes"
132 // Children reads the direct children in directory order. Each child needs an
133 // existing config with its directory name and this agent as parent. Children
134 // cannot have children. A missing children directory means no children.
135 func (a *Agent) Children() ([]*Agent, error) {
136 dir := filepath.Join(a.dir, "children")
137 entries, err := os.ReadDir(dir)
138 if errors.Is(err, os.ErrNotExist) {
143 return nil, fmt.Errorf("read children: %w", err)
146 if a.config.Parent != "" && len(entries) != 0 {
147 return nil, errors.New("children cannot have children")
150 var children []*Agent
152 keys := map[string]bool{a.CacheKey(): true}
154 for _, entry := range entries {
157 return nil, fmt.Errorf("child %q must be a directory", name)
160 path := filepath.Join(dir, name)
161 _, err = os.Stat(filepath.Join(path, "config.json"))
163 return nil, fmt.Errorf("child %q config: %w", name, err)
166 child, err := openAgent(path)
168 return nil, fmt.Errorf("open child %q: %w", name, err)
171 if child.config.Name != name || child.config.Parent != a.config.Name {
172 return nil, fmt.Errorf("child %q needs name %q and parent %q", name, name, a.config.Name)
175 if child.config.Name == a.config.Name || keys[child.CacheKey()] {
176 return nil, fmt.Errorf("child %q must have its own name and ID", name)
179 keys[child.CacheKey()] = true
180 _, err = child.Children()
182 return nil, fmt.Errorf("read child %q: %w", name, err)
185 children = append(children, child)
191 // CreateChild writes a new direct child with its own ID and the model, effort,
192 // and working directory of the root. Child and subagent names share a
193 // namespace. The config is complete before an atomic rename publishes the
194 // child. Preparation stays outside children, so an interrupted write cannot
196 func (a *Agent) CreateChild(name, responsibility string, subagents *Subagents) (_ *Agent, err error) {
197 if a.config.Parent != "" {
198 return nil, errors.New("only the root can create children")
201 if !agentChildNameValid(name) {
202 return nil, errors.New("name must have 2 to 32 ASCII letters and start with a capital letter")
205 if name == a.config.Name {
206 return nil, errors.New("the name is already used by the root")
209 responsibility = strings.TrimSpace(responsibility)
210 if responsibility == "" {
211 return nil, errors.New("responsibility must not be empty")
214 err = subagents.Reserve(name)
216 return nil, fmt.Errorf("reserve child name: %w", err)
222 subagents.Release(name)
226 staged, err := os.MkdirTemp(a.dir, ".child-*")
228 return nil, fmt.Errorf("prepare child directory: %w", err)
232 cleanupErr := os.RemoveAll(staged)
233 if cleanupErr != nil {
234 err = errors.Join(err, fmt.Errorf("remove prepared child: %w", cleanupErr))
241 config.Parent = a.config.Name
242 config.Responsibility = responsibility
243 child, err := writeAgent(staged, config)
245 return nil, fmt.Errorf("write child: %w", err)
248 dir := filepath.Join(a.dir, "children")
249 err = os.MkdirAll(dir, 0o700)
251 return nil, fmt.Errorf("create children directory: %w", err)
254 dir = filepath.Join(dir, name)
255 err = unix.Renameat2(unix.AT_FDCWD, staged, unix.AT_FDCWD, dir, unix.RENAME_NOREPLACE)
257 return nil, fmt.Errorf("publish child directory: %w", err)
266 // SubagentPrompt returns the system prompt of a subagent of the agent, with the
267 // user's instructions as Prompt reads them.
268 func (a *Agent) SubagentPrompt() (string, error) {
269 instructions, err := a.instructions()
274 return promptSubagent(a.config.Name, instructions), nil
277 // instructions reads the user's instructions from instructions.md. A missing
278 // file means no instructions.
279 func (a *Agent) instructions() (string, error) {
280 data, err := os.ReadFile(filepath.Join(a.dir, agentInstructionsFileName))
281 if err != nil && !errors.Is(err, os.ErrNotExist) {
282 return "", fmt.Errorf("read instructions: %w", err)
285 return string(data), nil
288 // AgentConfig holds the settings of the config.json of an agent. ID is random,
289 // made once when the file is made, and never changes. The cache key comes from
290 // the ID, so a rename keeps the prompt cache and two agents with one name do
291 // not share a key. Workdir is the directory where the commands of the agent
292 // run. Responsibility and Parent are set together for a child agent.
293 type AgentConfig struct {
294 Name string `json:"name"`
295 ID string `json:"id"`
296 Model string `json:"model"`
297 Effort string `json:"effort"`
298 Workdir string `json:"workdir"`
299 Responsibility string `json:"responsibility,omitempty"`
300 Parent string `json:"parent,omitempty"`
303 // validate makes sure that each setting has a valid value.
304 func (c AgentConfig) validate() error {
305 if c.Name == "" || strings.ContainsAny(c.Name, "\r\n") {
306 return errors.New("name must be one line of text")
309 id, err := hex.DecodeString(c.ID)
310 if err != nil || len(id) != agentIDBytes {
311 return fmt.Errorf("id must be %d hexadecimal digits", 2*agentIDBytes)
314 if c.Model == "" || c.Effort == "" {
315 return errors.New("agent needs a model and an effort")
318 if (strings.TrimSpace(c.Responsibility) == "") != (c.Parent == "") {
319 return errors.New("a child needs both responsibility and parent")
322 if strings.ContainsAny(c.Parent, "\r\n") {
323 return errors.New("parent must be one line of text")
326 if !filepath.IsAbs(c.Workdir) {
327 return fmt.Errorf("workdir %q is not an absolute path", c.Workdir)
333 // agentChildNameValid accepts one word of 2 to 32 ASCII letters with an initial
334 // capital letter. Child names describe their area.
335 func agentChildNameValid(name string) bool {
336 if len(name) < 2 || len(name) > 32 || name[0] < 'A' || name[0] > 'Z' {
340 for i := 1; i < len(name); i++ {
342 if (letter < 'A' || letter > 'Z') && (letter < 'a' || letter > 'z') {
350 // createAgent writes the config.json of a new agent in dir with the defaults
352 func createAgent(dir string) (*Agent, error) {
353 config, err := defaultAgentConfig()
358 return writeAgent(dir, config)
361 // writeAgent gives config a new ID and writes it in dir.
362 func writeAgent(dir string, config AgentConfig) (*Agent, error) {
363 id := make([]byte, agentIDBytes)
364 _, err := rand.Read(id)
366 return nil, fmt.Errorf("make agent ID: %w", err)
369 config.ID = hex.EncodeToString(id)
370 data, err := json.MarshalIndent(config, "", " ")
372 return nil, fmt.Errorf("encode agent config: %w", err)
375 err = writeFileAtomic(filepath.Join(dir, "config.json"), append(data, '\n'))
377 return nil, fmt.Errorf("write agent config: %w", err)
386 // defaultAgentConfig returns the settings of a new agent, without an ID. The
387 // commands run in the home directory of the user.
388 func defaultAgentConfig() (AgentConfig, error) {
389 home, err := os.UserHomeDir()
391 return AgentConfig{}, fmt.Errorf("find working directory: %w", err)
396 Model: "gpt-6.1-sol",