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.
60 // Call logs the call of the tool name with its JSON arguments, makes the log
61 // durable, runs the tool, and logs its clipped output, which it returns. A
62 // failed tool gives its error as the output. An error of Call itself is an
63 // error of the log. When ctx ends before the flush, the tool does not run.
64 func (b *Toolbox) Call(ctx context.Context, name, arguments string) (string, error) {
65 _, err := b.log.Append("tool", toolCallText(name, arguments))
70 err = b.log.Flush(ctx)
71 if err != nil && ctx.Err() == nil {
75 output := "not run: the turn was interrupted"
77 output = toolClip(b.run(ctx, name, arguments))
80 _, err = b.log.Append("echo", output)
88 // run runs one tool and returns its output, or its error as text.
89 func (b *Toolbox) run(ctx context.Context, name, arguments string) string {
94 var args ToolZoomArguments
95 err = toolDecodeArguments(arguments, &args)
98 case args.Name != nil:
99 output, err = b.zoomAgent(ctx, *args.Name)
101 output, err = b.zoom(args.ID, args.N)
104 var args ToolDateArguments
105 err = toolDecodeArguments(arguments, &args)
107 output, err = b.date(args.ID)
110 var args ToolShellArguments
111 err = toolDecodeArguments(arguments, &args)
113 output = b.shell(ctx, args.Command)
116 var args ToolPathArguments
117 err = toolDecodeArguments(arguments, &args)
119 output, err = b.read(args.Path)
122 var args ToolWriteArguments
123 err = toolDecodeArguments(arguments, &args)
125 output, err = b.write(args.Path, args.Text)
128 var args ToolEditArguments
129 err = toolDecodeArguments(arguments, &args)
131 output, err = b.edit(args.Path, args.Old, args.New)
134 err = fmt.Errorf("unknown tool %q", name)
138 return "error: " + err.Error()
144 // zoomAgent returns the whole log of the subagent name.
145 func (b *Toolbox) zoomAgent(ctx context.Context, name string) (string, error) {
146 subagent, err := b.subagents.Get(ctx, name)
151 return subagent.Show()
154 // zoom returns message id whole for n = 1, or else the two lines under the line
156 func (b *Toolbox) zoom(id, n int) (string, error) {
157 if n < 1 || bits.OnesCount(uint(n)) != 1 || id < 0 || id%n != 0 {
158 return "", fmt.Errorf("line %d+%d does not exist: n must be a power of 2 and id a multiple of n", id, n)
161 if id+n > b.chat.Len() {
162 return "", fmt.Errorf("line %d+%d goes past the last message, %d", id, n, b.chat.Len()-1)
166 message, err := b.chat.Message(id)
171 return leafSource(message), nil
174 level := bits.TrailingZeros(uint(n)) - 1
176 for _, index := range []int{2 * id / n, 2*id/n + 1} {
177 node, built, err := b.chat.Node(level, index)
184 text = strings.ReplaceAll(node.Text, "\n", " ")
187 lines = append(lines, fmt.Sprintf("%d+%d|%s", index<<level, 1<<level, text))
190 return strings.Join(lines, "\n"), nil
193 // date returns the date and time of message id, with its weekday.
194 func (b *Toolbox) date(id int) (string, error) {
195 if id < 0 || id >= b.chat.Len() {
196 return "", fmt.Errorf("message %d does not exist", id)
199 message, err := b.chat.Message(id)
204 date, err := time.Parse(time.RFC3339Nano, message.Date)
209 return date.Local().Format("Monday 2006-01-02 15:04:05 -07:00"), nil
212 // shell runs command with bash in the working directory and returns its output
213 // and error output. A failed command adds its exit status. When ctx ends, the
214 // whole process group of the command is killed.
215 func (b *Toolbox) shell(ctx context.Context, command string) string {
216 cmd := exec.CommandContext(ctx, "bash", "-c", command)
218 cmd.SysProcAttr = &syscall.SysProcAttr{
221 cmd.Cancel = func() error {
222 return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
224 cmd.WaitDelay = toolShellWaitDelay
226 output := &ToolHeadTail{}
231 text := output.String()
232 var exit *exec.ExitError
234 case ctx.Err() != nil:
235 text += "\n[interrupted]"
236 case errors.As(err, &exit):
237 text += "\n[" + exit.String() + "]"
239 text += "\n[error: " + err.Error() + "]"
247 // read returns the text of the file at path.
248 func (b *Toolbox) read(path string) (text string, err error) {
249 file, err := os.Open(b.path(path))
255 err = errors.Join(err, file.Close())
258 output := &ToolHeadTail{}
259 _, err = io.Copy(output, file)
264 return output.String(), nil
267 // write replaces the file at path with text, and makes its missing
269 func (b *Toolbox) write(path, text string) (string, error) {
271 err := os.MkdirAll(filepath.Dir(path), 0o755)
276 err = os.WriteFile(path, []byte(text), 0o644)
281 return fmt.Sprintf("wrote %d bytes to %s", len(text), path), nil
284 // edit replaces the one occurrence of old in the file at path with
285 // replacement. It keeps the mode of the file.
286 func (b *Toolbox) edit(path, old, replacement string) (string, error) {
288 data, err := os.ReadFile(path)
294 return "", errors.New("old is empty")
297 count := strings.Count(string(data), old)
299 return "", fmt.Errorf("old occurs %d times in %s, not once", count, path)
302 info, err := os.Stat(path)
307 err = os.WriteFile(path, []byte(strings.Replace(string(data), old, replacement, 1)), info.Mode().Perm())
312 return "edited " + path, nil
315 // path returns path, relative to the working directory when it is not
317 func (b *Toolbox) path(path string) string {
318 if filepath.IsAbs(path) {
322 return filepath.Join(b.workdir, path)
325 // ToolZoomArguments are the arguments of zoom. A Name that is not nil names
326 // the subagent whose whole log zoom gives, and then ID and N are not used.
327 type ToolZoomArguments struct {
330 Name *string `json:"name"`
333 // ToolDateArguments are the arguments of date.
334 type ToolDateArguments struct {
338 // ToolShellArguments are the arguments of shell.
339 type ToolShellArguments struct {
340 Command string `json:"command"`
343 // ToolPathArguments are the arguments of read.
344 type ToolPathArguments struct {
345 Path string `json:"path"`
348 // ToolWriteArguments are the arguments of write.
349 type ToolWriteArguments struct {
350 Path string `json:"path"`
351 Text string `json:"text"`
354 // ToolEditArguments are the arguments of edit.
355 type ToolEditArguments struct {
356 Path string `json:"path"`
357 Old string `json:"old"`
358 New string `json:"new"`
361 // ToolHeadTail keeps the first and the last toolClipBytes bytes written to it,
362 // and counts the bytes between them that it drops.
363 type ToolHeadTail struct {
369 // String returns the output, clipped when it is too long. Invalid UTF-8 becomes
370 // the replacement character.
371 func (h *ToolHeadTail) String() string {
372 replacement := string(utf8.RuneError)
374 return toolClip(strings.ToValidUTF8(string(h.head)+string(h.tail), replacement))
377 head := toolFirstCharacters(strings.ToValidUTF8(string(h.head), replacement), toolClipCharacters/2)
378 tail := toolLastCharacters(strings.ToValidUTF8(string(h.tail), replacement), toolClipCharacters/2)
379 cut := len(h.head) + h.dropped + len(h.tail) - len(head) - len(tail)
381 return toolJoinClipped(head, tail, cut)
384 // Write keeps the bytes of p at the ends of the output.
385 func (h *ToolHeadTail) Write(p []byte) (int, error) {
387 room := min(toolClipBytes-len(h.head), len(p))
388 h.head = append(h.head, p[:room]...)
391 h.tail = append(h.tail, p...)
392 if len(h.tail) > toolClipBytes {
393 cut := len(h.tail) - toolClipBytes
395 h.tail = bytes.Clone(h.tail[cut:])
401 // toolCallText returns the log text of a tool call: the name and the JSON
403 func toolCallText(name, arguments string) string {
404 return name + " " + arguments
407 // toolClip returns text when it has at most toolClipCharacters characters.
408 // Otherwise it returns the first and the last toolClipCharacters/2 characters,
409 // with a mark of the cut between them.
410 func toolClip(text string) string {
411 if utf8.RuneCountInString(text) <= toolClipCharacters {
415 head := toolFirstCharacters(text, toolClipCharacters/2)
416 tail := toolLastCharacters(text, toolClipCharacters/2)
418 return toolJoinClipped(head, tail, len(text)-len(head)-len(tail))
421 // toolDecodeArguments decodes the JSON arguments of a call into args. An
422 // unknown field is an error.
423 func toolDecodeArguments(arguments string, args any) error {
424 decoder := json.NewDecoder(strings.NewReader(arguments))
425 decoder.DisallowUnknownFields()
426 err := decoder.Decode(args)
428 return fmt.Errorf("arguments: %w", err)
434 // toolFirstCharacters returns the first count characters of text.
435 func toolFirstCharacters(text string, count int) string {
438 if end >= len(text) {
442 _, size := utf8.DecodeRuneInString(text[end:])
449 // toolLastCharacters returns the last count characters of text.
450 func toolLastCharacters(text string, count int) string {
457 _, size := utf8.DecodeLastRuneInString(text[:start])
464 // toolJoinClipped joins the head and the tail of a clipped output with a mark
466 func toolJoinClipped(head, tail string, cut int) string {
467 return head + "\n[... " + strconv.Itoa(cut) + " bytes cut ...]\n" + tail