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 // toolShellWaitDelay is how long a command can keep its output open
31 // after it ends or after its kill.
32 toolShellWaitDelay = 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 the log of a subagent. The
53 // toolbox of the agent has the runs of its subagents for spawn and tell, the
54 // WhatsApp link for the WhatsApp tools, and the schedules for the schedule
55 // tools. A child has no WhatsApp link. The toolbox of a subagent has none of
56 // them, so these are unknown tools there.
67 // Call logs the call of the tool name with its JSON arguments, makes the log
68 // durable, runs the tool, and logs its clipped output, which it returns. A
69 // failed tool gives its error as the output. An error of Call itself is an
70 // error of the log. When ctx ends before the flush, the tool does not run.
71 func (b *Toolbox) Call(ctx context.Context, name, arguments string) (string, error) {
72 _, err := b.log.Append("tool", toolCallText(name, arguments))
74 return "", fmt.Errorf("append tool call: %w", err)
77 err = b.log.Flush(ctx)
78 if err != nil && ctx.Err() == nil {
79 return "", fmt.Errorf("flush tool call: %w", err)
82 output := "not run: the turn was interrupted"
84 output = toolClip(b.run(ctx, name, arguments))
87 _, err = b.log.Append("echo", output)
89 return "", fmt.Errorf("append tool result: %w", err)
95 // run runs one tool and returns its output, or its error as text.
96 func (b *Toolbox) run(ctx context.Context, name, arguments string) string {
104 var args ToolZoomArguments
106 err = toolDecodeArguments(arguments, &args)
109 case args.Name != nil:
110 output, err = b.zoomAgent(ctx, *args.Name)
112 output, err = b.zoom(args.ID, args.N)
115 var args ToolDateArguments
117 err = toolDecodeArguments(arguments, &args)
119 output, err = b.date(args.ID)
122 var args ToolShellArguments
124 err = toolDecodeArguments(arguments, &args)
126 output = b.shell(ctx, args.Command)
129 var args ToolPathArguments
131 err = toolDecodeArguments(arguments, &args)
133 output, err = b.read(args.Path)
136 var args ToolWriteArguments
138 err = toolDecodeArguments(arguments, &args)
140 output, err = b.write(args.Path, args.Text)
143 var args ToolEditArguments
145 err = toolDecodeArguments(arguments, &args)
147 output, err = b.edit(args.Path, args.Old, args.New)
150 var args ToolSpawnArguments
152 err = toolDecodeArguments(arguments, &args)
155 err = fmt.Errorf("unknown tool %q", name)
157 output, err = b.runs.Spawn(ctx, args.Tasks, args.Effort)
160 var args ToolTellArguments
162 err = toolDecodeArguments(arguments, &args)
165 err = fmt.Errorf("unknown tool %q", name)
167 output, err = b.runs.Tell(ctx, args.Name, args.Message)
169 case "whatsapp_find":
170 var args ToolWhatsAppFindArguments
172 err = toolDecodeArguments(arguments, &args)
174 case b.whatsapp == nil:
175 err = fmt.Errorf("unknown tool %q", name)
177 output, err = b.whatsapp.Find(ctx, args.Name)
179 case "whatsapp_send":
180 var args ToolWhatsAppSendArguments
182 err = toolDecodeArguments(arguments, &args)
184 case b.whatsapp == nil:
185 err = fmt.Errorf("unknown tool %q", name)
187 output, err = b.whatsapp.Send(ctx, args.ID, args.Chat, args.Text)
190 var args ToolScheduleSetArguments
192 err = toolDecodeArguments(arguments, &args)
194 case b.schedules == nil:
195 err = fmt.Errorf("unknown tool %q", name)
197 output, err = b.schedules.Set(args.Text, args.At, args.Cron)
199 case "schedule_list":
200 err = toolDecodeArguments(arguments, &struct{}{})
202 case b.schedules == nil:
203 err = fmt.Errorf("unknown tool %q", name)
205 output = b.schedules.List()
207 case "schedule_remove":
208 var args ToolScheduleRemoveArguments
210 err = toolDecodeArguments(arguments, &args)
212 case b.schedules == nil:
213 err = fmt.Errorf("unknown tool %q", name)
215 output, err = b.schedules.Remove(args.ID)
218 err = fmt.Errorf("unknown tool %q", name)
222 return "error: " + err.Error()
228 // zoomAgent returns the whole log of the subagent name.
229 func (b *Toolbox) zoomAgent(ctx context.Context, name string) (string, error) {
230 subagent, err := b.subagents.Get(ctx, name)
235 return subagent.Show()
238 // zoom returns message id whole for n = 1, or else the two lines under the line
240 func (b *Toolbox) zoom(id, n int) (string, error) {
241 if n < 1 || bits.OnesCount(uint(n)) != 1 || id < 0 || id%n != 0 {
242 return "", fmt.Errorf("line %d+%d does not exist: n must be a power of 2 and id a multiple of n", id, n)
245 if id+n > b.chat.Len() {
246 return "", fmt.Errorf("line %d+%d goes past the last message, %d", id, n, b.chat.Len()-1)
250 message, err := b.chat.Message(id)
252 return "", fmt.Errorf("read zoom message: %w", err)
255 return leafSource(message), nil
258 level := bits.TrailingZeros(uint(n)) - 1
262 for _, index := range []int{2 * id / n, 2*id/n + 1} {
263 node, built, err := b.chat.Node(level, index)
265 return "", fmt.Errorf("read zoom node: %w", err)
270 text = strings.ReplaceAll(node.Text, "\n", " ")
273 lines = append(lines, fmt.Sprintf("%d+%d|%s", index<<level, 1<<level, text))
276 return strings.Join(lines, "\n"), nil
279 // date returns the date and time of message id, with its weekday.
280 func (b *Toolbox) date(id int) (string, error) {
281 if id < 0 || id >= b.chat.Len() {
282 return "", fmt.Errorf("message %d does not exist", id)
285 message, err := b.chat.Message(id)
287 return "", fmt.Errorf("read dated message: %w", err)
290 date, err := time.Parse(time.RFC3339Nano, message.Date)
292 return "", fmt.Errorf("parse message date: %w", err)
295 return date.Local().Format("Monday 2006-01-02 15:04:05 -07:00"), nil
298 // shell runs command with bash in the working directory and returns its output
299 // and error output. A failed command adds its exit status. When ctx ends, the
300 // whole process group of the command is killed.
301 func (b *Toolbox) shell(ctx context.Context, command string) string {
302 cmd := exec.CommandContext(ctx, "bash", "-c", command)
304 cmd.SysProcAttr = &syscall.SysProcAttr{
307 cmd.Cancel = func() error {
308 return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
310 cmd.WaitDelay = toolShellWaitDelay
312 output := &ToolHeadTail{}
317 text := output.String()
319 var exit *exec.ExitError
322 case ctx.Err() != nil:
323 text += "\n[interrupted]"
324 case errors.As(err, &exit):
325 text += "\n[" + exit.String() + "]"
327 text += "\n[error: " + err.Error() + "]"
335 // read returns the text of the file at path.
336 func (b *Toolbox) read(path string) (text string, err error) {
337 file, err := os.Open(b.path(path))
339 return "", fmt.Errorf("open tool file: %w", err)
343 err = errors.Join(err, file.Close())
346 output := &ToolHeadTail{}
347 _, err = io.Copy(output, file)
349 return "", fmt.Errorf("read tool file: %w", err)
352 return output.String(), nil
355 // write replaces the file at path with text, and makes its missing
357 func (b *Toolbox) write(path, text string) (string, error) {
359 err := os.MkdirAll(filepath.Dir(path), 0o755)
361 return "", fmt.Errorf("create tool file directory: %w", err)
364 err = os.WriteFile(path, []byte(text), 0o644)
366 return "", fmt.Errorf("write tool file: %w", err)
369 return fmt.Sprintf("wrote %d bytes to %s", len(text), path), nil
372 // edit replaces the one occurrence of old in the file at path with
373 // replacement. It keeps the mode of the file.
374 func (b *Toolbox) edit(path, old, replacement string) (string, error) {
376 data, err := os.ReadFile(path)
378 return "", fmt.Errorf("read file to edit: %w", err)
382 return "", errors.New("old is empty")
385 count := strings.Count(string(data), old)
387 return "", fmt.Errorf("old occurs %d times in %s, not once", count, path)
390 info, err := os.Stat(path)
392 return "", fmt.Errorf("read file mode: %w", err)
395 err = os.WriteFile(path, []byte(strings.Replace(string(data), old, replacement, 1)), info.Mode().Perm())
397 return "", fmt.Errorf("write edited file: %w", err)
400 return "edited " + path, nil
403 // path returns path, relative to the working directory when it is not
405 func (b *Toolbox) path(path string) string {
406 if filepath.IsAbs(path) {
410 return filepath.Join(b.workdir, path)
413 // ToolZoomArguments are the arguments of zoom. A Name that is not nil names
414 // the subagent whose whole log zoom gives, and then ID and N are not used.
415 type ToolZoomArguments struct {
418 Name *string `json:"name"`
421 // ToolDateArguments are the arguments of date.
422 type ToolDateArguments struct {
426 // ToolShellArguments are the arguments of shell.
427 type ToolShellArguments struct {
428 Command string `json:"command"`
431 // ToolPathArguments are the arguments of read.
432 type ToolPathArguments struct {
433 Path string `json:"path"`
436 // ToolWriteArguments are the arguments of write.
437 type ToolWriteArguments struct {
438 Path string `json:"path"`
439 Text string `json:"text"`
442 // ToolEditArguments are the arguments of edit.
443 type ToolEditArguments struct {
444 Path string `json:"path"`
445 Old string `json:"old"`
446 New string `json:"new"`
449 // ToolSpawnArguments are the arguments of spawn. A nil Effort is the effort of
451 type ToolSpawnArguments struct {
452 Tasks []string `json:"tasks"`
453 Effort *string `json:"effort"`
456 // ToolTellArguments are the arguments of tell.
457 type ToolTellArguments struct {
458 Name string `json:"name"`
459 Message string `json:"message"`
462 // ToolWhatsAppFindArguments are the arguments of whatsapp_find.
463 type ToolWhatsAppFindArguments struct {
464 Name string `json:"name"`
467 // ToolWhatsAppSendArguments are the arguments of whatsapp_send.
468 type ToolWhatsAppSendArguments struct {
469 ID string `json:"id"`
470 Chat string `json:"chat"`
471 Text string `json:"text"`
474 // ToolScheduleSetArguments are the arguments of schedule_set. Exactly one of At
475 // and Cron is not nil.
476 type ToolScheduleSetArguments struct {
477 Text string `json:"text"`
478 At *string `json:"at"`
479 Cron *string `json:"cron"`
482 // ToolScheduleRemoveArguments are the arguments of schedule_remove.
483 type ToolScheduleRemoveArguments struct {
487 // ToolHeadTail keeps the first and the last toolClipBytes bytes written to it,
488 // and counts the bytes between them that it drops.
489 type ToolHeadTail struct {
495 // String returns the output, clipped when it is too long. Invalid UTF-8 becomes
496 // the replacement character.
497 func (h *ToolHeadTail) String() string {
498 replacement := string(utf8.RuneError)
500 return toolClip(strings.ToValidUTF8(string(h.head)+string(h.tail), replacement))
503 head := toolFirstCharacters(strings.ToValidUTF8(string(h.head), replacement), toolClipCharacters/2)
504 tail := toolLastCharacters(strings.ToValidUTF8(string(h.tail), replacement), toolClipCharacters/2)
505 cut := len(h.head) + h.dropped + len(h.tail) - len(head) - len(tail)
507 return toolJoinClipped(head, tail, cut)
510 // Write keeps the bytes of p at the ends of the output.
511 func (h *ToolHeadTail) Write(p []byte) (int, error) {
513 room := min(toolClipBytes-len(h.head), len(p))
514 h.head = append(h.head, p[:room]...)
517 h.tail = append(h.tail, p...)
518 if len(h.tail) > toolClipBytes {
519 cut := len(h.tail) - toolClipBytes
521 h.tail = bytes.Clone(h.tail[cut:])
527 // toolCallText returns the log text of a tool call: the name and the JSON
529 func toolCallText(name, arguments string) string {
530 return name + " " + arguments
533 // toolClip returns text when it has at most toolClipCharacters characters.
534 // Otherwise it returns the first and the last toolClipCharacters/2 characters,
535 // with a mark of the cut between them.
536 func toolClip(text string) string {
537 if utf8.RuneCountInString(text) <= toolClipCharacters {
541 head := toolFirstCharacters(text, toolClipCharacters/2)
542 tail := toolLastCharacters(text, toolClipCharacters/2)
544 return toolJoinClipped(head, tail, len(text)-len(head)-len(tail))
547 // toolDecodeArguments decodes the JSON arguments of a call into args. An
548 // unknown field is an error.
549 func toolDecodeArguments(arguments string, args any) error {
550 decoder := json.NewDecoder(strings.NewReader(arguments))
551 decoder.DisallowUnknownFields()
553 err := decoder.Decode(args)
555 return fmt.Errorf("arguments: %w", err)
561 // toolFirstCharacters returns the first count characters of text.
562 func toolFirstCharacters(text string, count int) string {
565 if end >= len(text) {
569 _, size := utf8.DecodeRuneInString(text[end:])
576 // toolLastCharacters returns the last count characters of text.
577 func toolLastCharacters(text string, count int) string {
584 _, size := utf8.DecodeLastRuneInString(text[:start])
591 // toolJoinClipped joins the head and the tail of a clipped output with a mark
593 func toolJoinClipped(head, tail string, cut int) string {
594 return head + "\n[... " + strconv.Itoa(cut) + " bytes cut ...]\n" + tail