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.
59 // Call logs the call of the tool name with its JSON arguments, makes the log
60 // durable, runs the tool, and logs its clipped output, which it returns. A
61 // failed tool gives its error as the output. An error of Call itself is an
62 // error of the log. When ctx ends before the flush, the tool does not run.
63 func (b *Toolbox) Call(ctx context.Context, name, arguments string) (string, error) {
64 _, err := b.log.Append("tool", toolCallText(name, arguments))
69 err = b.log.Flush(ctx)
70 if err != nil && ctx.Err() == nil {
74 output := "not run: the turn was interrupted"
76 output = toolClip(b.run(ctx, name, arguments))
79 _, err = b.log.Append("echo", output)
87 // run runs one tool and returns its output, or its error as text.
88 func (b *Toolbox) run(ctx context.Context, name, arguments string) string {
93 var args ToolZoomArguments
94 err = toolDecodeArguments(arguments, &args)
96 output, err = b.zoom(args.ID, args.N)
99 var args ToolDateArguments
100 err = toolDecodeArguments(arguments, &args)
102 output, err = b.date(args.ID)
105 var args ToolShellArguments
106 err = toolDecodeArguments(arguments, &args)
108 output = b.shell(ctx, args.Command)
111 var args ToolPathArguments
112 err = toolDecodeArguments(arguments, &args)
114 output, err = b.read(args.Path)
117 var args ToolWriteArguments
118 err = toolDecodeArguments(arguments, &args)
120 output, err = b.write(args.Path, args.Text)
123 var args ToolEditArguments
124 err = toolDecodeArguments(arguments, &args)
126 output, err = b.edit(args.Path, args.Old, args.New)
129 err = fmt.Errorf("unknown tool %q", name)
133 return "error: " + err.Error()
139 // zoom returns message id whole for n = 1, or else the two lines under the line
141 func (b *Toolbox) zoom(id, n int) (string, error) {
142 if n < 1 || bits.OnesCount(uint(n)) != 1 || id < 0 || id%n != 0 {
143 return "", fmt.Errorf("line %d+%d does not exist: n must be a power of 2 and id a multiple of n", id, n)
146 if id+n > b.chat.Len() {
147 return "", fmt.Errorf("line %d+%d goes past the last message, %d", id, n, b.chat.Len()-1)
151 message, err := b.chat.Message(id)
156 return leafSource(message), nil
159 level := bits.TrailingZeros(uint(n)) - 1
161 for _, index := range []int{2 * id / n, 2*id/n + 1} {
162 node, built, err := b.chat.Node(level, index)
169 text = strings.ReplaceAll(node.Text, "\n", " ")
172 lines = append(lines, fmt.Sprintf("%d+%d|%s", index<<level, 1<<level, text))
175 return strings.Join(lines, "\n"), nil
178 // date returns the date and time of message id, with its weekday.
179 func (b *Toolbox) date(id int) (string, error) {
180 if id < 0 || id >= b.chat.Len() {
181 return "", fmt.Errorf("message %d does not exist", id)
184 message, err := b.chat.Message(id)
189 date, err := time.Parse(time.RFC3339Nano, message.Date)
194 return date.Local().Format("Monday 2006-01-02 15:04:05 -07:00"), nil
197 // shell runs command with bash in the working directory and returns its output
198 // and error output. A failed command adds its exit status. When ctx ends, the
199 // whole process group of the command is killed.
200 func (b *Toolbox) shell(ctx context.Context, command string) string {
201 cmd := exec.CommandContext(ctx, "bash", "-c", command)
203 cmd.SysProcAttr = &syscall.SysProcAttr{
206 cmd.Cancel = func() error {
207 return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
209 cmd.WaitDelay = toolShellWaitDelay
211 output := &ToolHeadTail{}
216 text := output.String()
217 var exit *exec.ExitError
219 case ctx.Err() != nil:
220 text += "\n[interrupted]"
221 case errors.As(err, &exit):
222 text += "\n[" + exit.String() + "]"
224 text += "\n[error: " + err.Error() + "]"
232 // read returns the text of the file at path.
233 func (b *Toolbox) read(path string) (text string, err error) {
234 file, err := os.Open(b.path(path))
240 err = errors.Join(err, file.Close())
243 output := &ToolHeadTail{}
244 _, err = io.Copy(output, file)
249 return output.String(), nil
252 // write replaces the file at path with text, and makes its missing
254 func (b *Toolbox) write(path, text string) (string, error) {
256 err := os.MkdirAll(filepath.Dir(path), 0o755)
261 err = os.WriteFile(path, []byte(text), 0o644)
266 return fmt.Sprintf("wrote %d bytes to %s", len(text), path), nil
269 // edit replaces the one occurrence of old in the file at path with
270 // replacement. It keeps the mode of the file.
271 func (b *Toolbox) edit(path, old, replacement string) (string, error) {
273 data, err := os.ReadFile(path)
279 return "", errors.New("old is empty")
282 count := strings.Count(string(data), old)
284 return "", fmt.Errorf("old occurs %d times in %s, not once", count, path)
287 info, err := os.Stat(path)
292 err = os.WriteFile(path, []byte(strings.Replace(string(data), old, replacement, 1)), info.Mode().Perm())
297 return "edited " + path, nil
300 // path returns path, relative to the working directory when it is not
302 func (b *Toolbox) path(path string) string {
303 if filepath.IsAbs(path) {
307 return filepath.Join(b.workdir, path)
310 // ToolZoomArguments are the arguments of zoom.
311 type ToolZoomArguments struct {
316 // ToolDateArguments are the arguments of date.
317 type ToolDateArguments struct {
321 // ToolShellArguments are the arguments of shell.
322 type ToolShellArguments struct {
323 Command string `json:"command"`
326 // ToolPathArguments are the arguments of read.
327 type ToolPathArguments struct {
328 Path string `json:"path"`
331 // ToolWriteArguments are the arguments of write.
332 type ToolWriteArguments struct {
333 Path string `json:"path"`
334 Text string `json:"text"`
337 // ToolEditArguments are the arguments of edit.
338 type ToolEditArguments struct {
339 Path string `json:"path"`
340 Old string `json:"old"`
341 New string `json:"new"`
344 // ToolHeadTail keeps the first and the last toolClipBytes bytes written to it,
345 // and counts the bytes between them that it drops.
346 type ToolHeadTail struct {
352 // String returns the output, clipped when it is too long. Invalid UTF-8 becomes
353 // the replacement character.
354 func (h *ToolHeadTail) String() string {
355 replacement := string(utf8.RuneError)
357 return toolClip(strings.ToValidUTF8(string(h.head)+string(h.tail), replacement))
360 head := toolFirstCharacters(strings.ToValidUTF8(string(h.head), replacement), toolClipCharacters/2)
361 tail := toolLastCharacters(strings.ToValidUTF8(string(h.tail), replacement), toolClipCharacters/2)
362 cut := len(h.head) + h.dropped + len(h.tail) - len(head) - len(tail)
364 return toolJoinClipped(head, tail, cut)
367 // Write keeps the bytes of p at the ends of the output.
368 func (h *ToolHeadTail) Write(p []byte) (int, error) {
370 room := min(toolClipBytes-len(h.head), len(p))
371 h.head = append(h.head, p[:room]...)
374 h.tail = append(h.tail, p...)
375 if len(h.tail) > toolClipBytes {
376 cut := len(h.tail) - toolClipBytes
378 h.tail = bytes.Clone(h.tail[cut:])
384 // toolCallText returns the log text of a tool call: the name and the JSON
386 func toolCallText(name, arguments string) string {
387 return name + " " + arguments
390 // toolClip returns text when it has at most toolClipCharacters characters.
391 // Otherwise it returns the first and the last toolClipCharacters/2 characters,
392 // with a mark of the cut between them.
393 func toolClip(text string) string {
394 if utf8.RuneCountInString(text) <= toolClipCharacters {
398 head := toolFirstCharacters(text, toolClipCharacters/2)
399 tail := toolLastCharacters(text, toolClipCharacters/2)
401 return toolJoinClipped(head, tail, len(text)-len(head)-len(tail))
404 // toolDecodeArguments decodes the JSON arguments of a call into args. An
405 // unknown field is an error.
406 func toolDecodeArguments(arguments string, args any) error {
407 decoder := json.NewDecoder(strings.NewReader(arguments))
408 decoder.DisallowUnknownFields()
409 err := decoder.Decode(args)
411 return fmt.Errorf("arguments: %w", err)
417 // toolFirstCharacters returns the first count characters of text.
418 func toolFirstCharacters(text string, count int) string {
421 if end >= len(text) {
425 _, size := utf8.DecodeRuneInString(text[end:])
432 // toolLastCharacters returns the last count characters of text.
433 func toolLastCharacters(text string, count int) string {
440 _, size := utf8.DecodeLastRuneInString(text[:start])
447 // toolJoinClipped joins the head and the tail of a clipped output with a mark
449 func toolJoinClipped(head, tail string, cut int) string {
450 return head + "\n[... " + strconv.Itoa(cut) + " bytes cut ...]\n" + tail