22 // toolClipCharacters is the most characters of a tool output: its head
23 // and its tail, half each.
24 toolClipCharacters = 30000
26 // toolClipBytes is the most bytes that a tool keeps of each end of an
27 // output, enough for toolClipCharacters/2 characters of 4 bytes.
28 toolClipBytes = 4 * toolClipCharacters / 2
30 // toolShellOutputTimeout is how long a command can keep its output open
31 // after it ends or after its kill.
32 toolShellOutputTimeout = 2 * time.Second
35 // ToolLog is the log that the tools write their calls and results to.
36 type ToolLog interface {
37 Append(kind, text string) (Message, error)
38 Flush(ctx context.Context) error
41 // ToolChat gives the messages and the nodes that zoom and date read.
42 type ToolChat interface {
44 Message(id int) (Message, error)
45 Node(level, index int) (Node, bool, error)
48 // Toolbox runs the tool calls of one agent. Each call and each result goes to
49 // the log as it happens: the call as a tool message, the result as an echo
50 // message. The call is durable before its tool runs, so the log never misses an
51 // action outside the agent. Commands and files run as the user in the working
52 // directory, with no sandbox. Zoom with a name reads a child's view or a
53 // subagent's log. The toolbox of the agent has the runs of its subagents for
54 // spawn and tell, the WhatsApp link for the WhatsApp tools, and the schedules
55 // for the schedule tools. Each permanent agent has the parent-child queue. Only
56 // the root has child creation and source routes. A child has neither of them
57 // nor a WhatsApp link. Only the root can show images to the user. The toolbox
58 // of a subagent has none of them, so these are unknown tools there.
68 messages *DaemonMessages
69 children *DaemonChildren
75 // ToolZoomArguments are the arguments of zoom. A Name that is not nil names the
76 // child whose view or the subagent whose whole log zoom gives. ID and N are
78 type ToolZoomArguments struct {
81 Name *string `json:"name"`
84 // ToolDateArguments are the arguments of date.
85 type ToolDateArguments struct {
89 // ToolShellArguments are the arguments of shell.
90 type ToolShellArguments struct {
91 Command string `json:"command"`
94 // ToolPathArguments are the arguments of read.
95 type ToolPathArguments struct {
96 Path string `json:"path"`
99 // ToolWriteArguments are the arguments of write.
100 type ToolWriteArguments struct {
101 Path string `json:"path"`
102 Text string `json:"text"`
105 // ToolEditArguments are the arguments of edit.
106 type ToolEditArguments struct {
107 Path string `json:"path"`
108 Old string `json:"old"`
109 New string `json:"new"`
112 // ToolSpawnArguments are the arguments of spawn. A nil Effort is the effort of
114 type ToolSpawnArguments struct {
115 Tasks []string `json:"tasks"`
116 Effort *string `json:"effort"`
119 // ToolAgentCreateArguments are the arguments of agent_create.
120 type ToolAgentCreateArguments struct {
121 Name string `json:"name"`
122 Responsibility string `json:"responsibility"`
125 // ToolRouteArguments are the arguments of route.
126 type ToolRouteArguments struct {
127 Source string `json:"source"`
128 Agent string `json:"agent"`
131 // ToolRouteSourceArguments are the arguments of unroute.
132 type ToolRouteSourceArguments struct {
133 Source string `json:"source"`
136 // ToolTellArguments are the arguments of tell.
137 type ToolTellArguments struct {
138 Name string `json:"name"`
139 Message string `json:"message"`
142 // ToolImageShowArguments are the arguments of image_show.
143 type ToolImageShowArguments struct {
144 Image string `json:"image"`
145 Caption string `json:"caption"`
148 // ToolWhatsAppFindArguments are the arguments of whatsapp_find.
149 type ToolWhatsAppFindArguments struct {
150 Name string `json:"name"`
153 // ToolWhatsAppSendArguments are the arguments of whatsapp_send.
154 type ToolWhatsAppSendArguments struct {
155 ID string `json:"id"`
156 Chat string `json:"chat"`
157 Text string `json:"text"`
158 Image string `json:"image"`
161 // ToolScheduleSetArguments are the arguments of schedule_set. Exactly one of At
162 // and Cron is not nil.
163 type ToolScheduleSetArguments struct {
164 Text string `json:"text"`
165 At *string `json:"at"`
166 Cron *string `json:"cron"`
169 // ToolScheduleRemoveArguments are the arguments of schedule_remove.
170 type ToolScheduleRemoveArguments struct {
174 // ToolHeadTail keeps the first and the last toolClipBytes bytes written to it,
175 // and counts the bytes between them that it drops.
176 type ToolHeadTail struct {
182 // Call logs the call of the tool name with its JSON arguments, makes the log
183 // durable, runs the tool, and logs its clipped text. It returns that text or
184 // the text and image parts of a single-message zoom. Pixels never enter the
185 // log. A failed tool gives its error as the output. An error of Call itself is
186 // an error of the log. When ctx ends before the flush, the tool does not run.
187 func (b *Toolbox) Call(ctx context.Context, name, arguments string) (any, error) {
188 _, err := b.log.Append("tool", toolCallText(name, arguments))
190 return "", fmt.Errorf("append tool call: %w", err)
193 err = b.log.Flush(ctx)
194 if err != nil && ctx.Err() == nil {
195 return "", fmt.Errorf("flush tool call: %w", err)
198 output := "not run: the turn was interrupted"
200 output = toolClip(b.run(ctx, name, arguments))
209 result, resultErr = imageToolOutput(b, name, arguments, output)
212 if resultErr != nil {
213 output = "error: " + resultErr.Error()
217 _, err = b.log.Append("echo", output)
219 return "", fmt.Errorf("append tool result: %w", err)
225 // run runs one tool and returns its output, or its error as text.
226 func (b *Toolbox) run(ctx context.Context, name, arguments string) string {
234 var args ToolZoomArguments
236 err = toolDecodeArguments(arguments, &args)
239 case args.Name != nil:
240 output, err = b.zoomAgent(ctx, *args.Name)
242 output, err = b.zoom(args.ID, args.N)
245 var args ToolDateArguments
247 err = toolDecodeArguments(arguments, &args)
249 output, err = b.date(args.ID)
252 var args ToolShellArguments
254 err = toolDecodeArguments(arguments, &args)
256 output = b.shell(ctx, args.Command)
259 var args ToolPathArguments
261 err = toolDecodeArguments(arguments, &args)
263 output, err = b.read(args.Path)
266 var args ToolWriteArguments
268 err = toolDecodeArguments(arguments, &args)
270 output, err = b.write(args.Path, args.Text)
273 var args ToolEditArguments
275 err = toolDecodeArguments(arguments, &args)
277 output, err = b.edit(args.Path, args.Old, args.New)
280 var args ToolSpawnArguments
282 err = toolDecodeArguments(arguments, &args)
285 err = fmt.Errorf("unknown tool %q", name)
287 output, err = b.runs.Spawn(ctx, args.Tasks, args.Effort)
290 var args ToolAgentCreateArguments
292 err = toolDecodeArguments(arguments, &args)
294 case b.children == nil:
295 err = fmt.Errorf("unknown tool %q", name)
297 output, err = b.children.Create(args.Name, args.Responsibility)
299 case "route", "unroute", "routes":
300 var args ToolRouteArguments
304 err = toolDecodeArguments(arguments, &struct{}{})
306 var source ToolRouteSourceArguments
308 err = toolDecodeArguments(arguments, &source)
309 args.Source = source.Source
311 err = toolDecodeArguments(arguments, &args)
315 case b.routes == nil:
316 err = fmt.Errorf("unknown tool %q", name)
318 case name == "routes":
319 output = b.routes.List()
320 case name == "route" && (b.messages == nil || b.messages.Child(b.agentName, args.Agent) == nil):
321 err = errors.New("the agent must be a child of the root")
323 err = b.routes.Set(args.Source, args.Agent)
324 output = "Route removed."
326 output = "Route set."
330 var args ToolTellArguments
332 err = toolDecodeArguments(arguments, &args)
335 err = fmt.Errorf("unknown tool %q", name)
336 case err == nil && b.messages != nil && b.messages.Child(b.agentName, args.Name) != nil:
337 err = b.messages.Tell(b.agentName, args.Name, args.Message)
338 output = "Sent. " + args.Name + "'s reply will reach you as a message."
340 output, err = b.runs.Tell(ctx, args.Name, args.Message)
343 var args ToolImageShowArguments
345 err = toolDecodeArguments(arguments, &args)
347 case b.imageShow == nil:
348 err = fmt.Errorf("unknown tool %q", name)
350 output, err = b.imageShow.Show(ctx, args.Image, args.Caption)
352 case "whatsapp_find":
353 var args ToolWhatsAppFindArguments
355 err = toolDecodeArguments(arguments, &args)
357 case b.whatsapp == nil:
358 err = fmt.Errorf("unknown tool %q", name)
360 output, err = b.whatsapp.Find(ctx, args.Name)
362 case "whatsapp_send":
363 var args ToolWhatsAppSendArguments
365 err = toolDecodeArguments(arguments, &args)
367 case b.whatsapp == nil:
368 err = fmt.Errorf("unknown tool %q", name)
370 output, err = b.whatsapp.Send(ctx, args.ID, args.Chat, args.Text, args.Image)
373 var args ToolScheduleSetArguments
375 err = toolDecodeArguments(arguments, &args)
377 case b.schedules == nil:
378 err = fmt.Errorf("unknown tool %q", name)
380 output, err = b.schedules.Set(args.Text, args.At, args.Cron)
382 case "schedule_list":
383 err = toolDecodeArguments(arguments, &struct{}{})
385 case b.schedules == nil:
386 err = fmt.Errorf("unknown tool %q", name)
388 output = b.schedules.List()
390 case "schedule_remove":
391 var args ToolScheduleRemoveArguments
393 err = toolDecodeArguments(arguments, &args)
395 case b.schedules == nil:
396 err = fmt.Errorf("unknown tool %q", name)
398 output, err = b.schedules.Remove(args.ID)
401 err = fmt.Errorf("unknown tool %q", name)
405 return "error: " + err.Error()
411 // zoomAgent returns a child's view or the whole log of a subagent.
412 func (b *Toolbox) zoomAgent(ctx context.Context, name string) (string, error) {
413 if b.messages != nil {
414 child := b.messages.Child(b.agentName, name)
416 return strings.Join(child.memory.ViewLines(nil), ""), nil
420 subagent, err := b.subagents.Get(ctx, name)
422 return "", fmt.Errorf("open worker log: %w", err)
425 text, err := subagent.Show()
427 return text, fmt.Errorf("read worker log: %w", err)
433 // zoom returns message id whole for n = 1, or else the two lines under the line
435 func (b *Toolbox) zoom(id, n int) (string, error) {
436 if n < 1 || bits.OnesCount(uint(n)) != 1 || id < 0 || id%n != 0 {
437 return "", fmt.Errorf("line %d+%d does not exist: n must be a power of 2 and id a multiple of n", id, n)
440 if id+n > b.chat.Len() {
441 return "", fmt.Errorf("line %d+%d goes past the last message, %d", id, n, b.chat.Len()-1)
445 message, err := b.chat.Message(id)
447 return "", fmt.Errorf("read zoom message: %w", err)
450 return leafSource(message), nil
453 level := bits.TrailingZeros(uint(n)) - 1
457 for _, index := range []int{2 * id / n, 2*id/n + 1} {
458 node, built, err := b.chat.Node(level, index)
460 return "", fmt.Errorf("read zoom node: %w", err)
465 text = strings.ReplaceAll(node.Text, "\n", " ")
468 lines = append(lines, fmt.Sprintf("%d+%d|%s", index<<level, 1<<level, text))
471 return strings.Join(lines, "\n"), nil
474 // date returns the date and time of message id, with its weekday.
475 func (b *Toolbox) date(id int) (string, error) {
476 if id < 0 || id >= b.chat.Len() {
477 return "", fmt.Errorf("message %d does not exist", id)
480 message, err := b.chat.Message(id)
482 return "", fmt.Errorf("read dated message: %w", err)
485 date, err := time.Parse(time.RFC3339Nano, message.Date)
487 return "", fmt.Errorf("parse message date: %w", err)
490 return date.Local().Format("Monday 2006-01-02 15:04:05 -07:00"), nil
493 // shell runs command with bash in the working directory and returns its output
494 // and error output. A failed command adds its exit status. When ctx ends, the
495 // whole process group of the command is killed.
496 func (b *Toolbox) shell(ctx context.Context, command string) string {
497 cmd := exec.CommandContext(ctx, "bash", "-c", command)
499 cmd.SysProcAttr = &syscall.SysProcAttr{
503 cmd.Cancel = func() error {
504 return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
507 cmd.WaitDelay = toolShellOutputTimeout
509 output := &ToolHeadTail{}
514 text := output.String()
516 var exit *exec.ExitError
519 case ctx.Err() != nil:
520 text += "\n[interrupted]"
521 case errors.As(err, &exit):
522 text += "\n[" + exit.String() + "]"
524 text += "\n[error: " + err.Error() + "]"
532 // read returns the text of the file at path.
533 func (b *Toolbox) read(path string) (text string, err error) {
534 file, err := os.Open(b.path(path))
536 return "", fmt.Errorf("open tool file: %w", err)
540 err = errors.Join(err, file.Close())
543 output := &ToolHeadTail{}
544 _, err = io.Copy(output, file)
546 return "", fmt.Errorf("read tool file: %w", err)
549 return output.String(), nil
552 // write replaces the file at path with text, and makes its missing directories.
553 func (b *Toolbox) write(path, text string) (string, error) {
555 err := os.MkdirAll(filepath.Dir(path), 0o755)
557 return "", fmt.Errorf("create tool file directory: %w", err)
560 err = os.WriteFile(path, []byte(text), 0o644)
562 return "", fmt.Errorf("write tool file: %w", err)
565 return fmt.Sprintf("wrote %d bytes to %s", len(text), path), nil
568 // edit replaces the one occurrence of old in the file at path with replacement.
569 // It keeps the mode of the file.
570 func (b *Toolbox) edit(path, old, replacement string) (string, error) {
572 data, err := os.ReadFile(path)
574 return "", fmt.Errorf("read file to edit: %w", err)
578 return "", errors.New("old is empty")
581 count := strings.Count(string(data), old)
583 return "", fmt.Errorf("old occurs %d times in %s, not once", count, path)
586 info, err := os.Stat(path)
588 return "", fmt.Errorf("read file mode: %w", err)
591 err = os.WriteFile(path, []byte(strings.Replace(string(data), old, replacement, 1)), info.Mode().Perm())
593 return "", fmt.Errorf("write edited file: %w", err)
596 return "edited " + path, nil
599 // path returns path, relative to the working directory when it is not absolute.
600 func (b *Toolbox) path(path string) string {
601 if filepath.IsAbs(path) {
605 return filepath.Join(b.workdir, path)
608 // String returns the output, clipped when it is too long. Invalid UTF-8 becomes
609 // the replacement character.
610 func (h *ToolHeadTail) String() string {
611 replacement := string(utf8.RuneError)
613 return toolClip(strings.ToValidUTF8(string(h.head)+string(h.tail), replacement))
616 head := toolFirstCharacters(strings.ToValidUTF8(string(h.head), replacement), toolClipCharacters/2)
617 tail := toolLastCharacters(strings.ToValidUTF8(string(h.tail), replacement), toolClipCharacters/2)
618 cut := len(h.head) + h.dropped + len(h.tail) - len(head) - len(tail)
620 return toolJoinClipped(head, tail, cut)
623 // Write keeps the bytes of p at the ends of the output.
624 func (h *ToolHeadTail) Write(p []byte) (int, error) {
626 room := min(toolClipBytes-len(h.head), len(p))
627 h.head = append(h.head, p[:room]...)
630 h.tail = append(h.tail, p...)
631 if len(h.tail) > toolClipBytes {
632 cut := len(h.tail) - toolClipBytes
634 h.tail = bytes.Clone(h.tail[cut:])
640 // toolCallText returns the log text of a tool call: the name and the JSON
642 func toolCallText(name, arguments string) string {
643 return name + " " + arguments
646 // toolClip returns text when it has at most toolClipCharacters characters.
647 // Otherwise it returns the first and the last toolClipCharacters/2 characters,
648 // with a mark of the cut between them.
649 func toolClip(text string) string {
650 if utf8.RuneCountInString(text) <= toolClipCharacters {
654 head := toolFirstCharacters(text, toolClipCharacters/2)
655 tail := toolLastCharacters(text, toolClipCharacters/2)
657 return toolJoinClipped(head, tail, len(text)-len(head)-len(tail))
660 // toolDecodeArguments decodes the JSON arguments of a call into args. An
661 // unknown field is an error.
662 func toolDecodeArguments(arguments string, args any) error {
663 decoder := json.NewDecoder(strings.NewReader(arguments))
664 decoder.DisallowUnknownFields()
666 err := decoder.Decode(args)
668 return fmt.Errorf("arguments: %w", err)
674 // toolFirstCharacters returns the first count characters of text.
675 func toolFirstCharacters(text string, count int) string {
678 if end >= len(text) {
682 _, size := utf8.DecodeRuneInString(text[end:])
689 // toolLastCharacters returns the last count characters of text.
690 func toolLastCharacters(text string, count int) string {
697 _, size := utf8.DecodeLastRuneInString(text[:start])
704 // toolJoinClipped joins the head and the tail of a clipped output with a mark
706 func toolJoinClipped(head, tail string, cut int) string {
707 return head + "\n[... " + strconv.Itoa(cut) + " bytes cut ...]\n" + tail