agenttools

package
v0.6.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 5, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Overview

Package agenttools is the operation layer the aerolvm CLI and the aerolvm MCP server share (plans/mcp-server-and-agent-cli.md §5.1). It holds the behaviour that has to be identical in both front ends: how a "<id-or-name>" reference resolves, idempotent create, output bounds, and error codes.

It talks to sandboxd only through the Go SDK (sdk/go/pkg/microvm) and imports nothing from the server tree, so the CLI stays a small static binary. Each front end keeps its own surface on top: the CLI has positional args, stdin and live output; MCP has JSON schemas and bounded results.

Index

Constants

View Source
const (
	CodeInvalidArgument    = "invalid_argument"
	CodeUnauthorized       = "unauthorized"
	CodeForbidden          = "forbidden"
	CodeNotFound           = "not_found"
	CodeConflict           = "conflict"
	CodeGone               = "gone"
	CodeTooLarge           = "too_large"
	CodeUnavailable        = "unavailable"
	CodeInternal           = "internal"
	CodeUnreachable        = "unreachable"
	CodeTimeout            = "timeout"
	CodeCanceled           = "canceled"
	CodeServerUnsupported  = "server_unsupported"
	CodeUnsupportedRuntime = "unsupported_runtime"
	CodeOutputTooLarge     = "output_too_large"
	CodeBinaryFile         = "binary_file"
	CodeEditConflict       = "edit_conflict"
	CodeCreateLimit        = "create_limit"
)

Error codes. They are a stable contract: the CLI prints them in its --json error envelope and the MCP server puts them in tool errors, so agents and scripts branch on them. Add codes; never repurpose one.

View Source
const (
	DefaultReadLines = 2000
	MaxReadBytes     = 256 * 1024
	MaxEditBytes     = 1 << 20
	MaxListEntries   = 1000
	MaxSearchResults = 500
	MaxGrepMatches   = 200
)

Read and listing bounds (§5.3). They protect the model's context window and this process's memory: a read returns one window and a continuation offset, never a whole large file.

View Source
const CreatedByTag = "aerolvm.created_by"

CreatedByTag is added to every sandbox the CLI or MCP server creates (CEO review C6) so agent usage and cleanup are visible with the existing tag filters. A value the caller sets explicitly wins.

View Source
const DefaultMaxOutputBytes = 16 * 1024

DefaultMaxOutputBytes bounds the output kept per stream (stdout, stderr) for one exec: head 4 KiB + tail 12 KiB. Errors and summaries live at the end of output, so the tail gets the larger share. The bound protects the model's context window and the MCP process's memory against `yes`-style floods (§5.3).

View Source
const MaxBufferedExecResponseBytes = 4 << 20

MaxBufferedExecResponseBytes caps how much of a buffered exec response is read (eng review D10). Buffered exec returns stdout and stderr in one JSON body, and toolbox /process/execute doesn't cap output, so a larger body is refused rather than decoded into memory. It can't be truncated instead: a JSON body cut short doesn't decode.

View Source
const TimeoutExitCode = 124

TimeoutExitCode is what a command stopped by its timeout reports, matching GNU timeout.

Variables

This section is empty.

Functions

func DefaultMCPLifecycle

func DefaultMCPLifecycle() *models.Lifecycle

DefaultMCPLifecycle is the cleanup policy for sandboxes the MCP server creates (eng review D7): stop after 30 minutes idle (files are kept), and destroy after 24 hours idle. The server-side timers are the cleanup guarantee; MCP hosts often SIGKILL their servers, so process exit is not.

func IsCode

func IsCode(err error, code string) bool

IsCode reports whether err classifies to code.

func IsWasm

func IsWasm(sb *microvm.Sandbox) bool

IsWasm reports whether sb runs on the WASM runtime.

func RequireShell

func RequireShell(sb *microvm.Sandbox) error

RequireShell refuses runtimes that have no shell or filesystem, before any toolbox call, so the caller gets a clear reason instead of a raw 501 (eng review D11).

Types

type Config

type Config struct {
	// APIURL and Token default to SB_API_URL and SB_PAT_TOKEN, the same
	// variables every SDK reads.
	APIURL string
	Token  string
	Source Source
	// HTTPClient overrides the transport: the --debug logger, the remote
	// MCP endpoint's in-process transport, and tests.
	HTTPClient *http.Client
	// Warn receives non-fatal notices, such as an existing sandbox whose
	// image differs from a create request. Nil discards them.
	Warn func(string)
}

Config builds a Tools.

type CreateResult

type CreateResult struct {
	Sandbox *microvm.Sandbox
	// Created is true only when this call's POST created the sandbox. A
	// name that already existed, or a 409 that resolved to the same name,
	// reports false.
	Created bool
}

CreateResult reports which sandbox a get-or-create landed on.

type CreateSpec

type CreateSpec struct {
	// Name is the sandbox name. Empty generates "agent-<12 base32>" before
	// the first attempt, so every retry targets the same name.
	Name     string
	Image    string
	Runtime  string
	CPU      float64
	MemoryMB int
	Env      map[string]string
	Tags     map[string]string
	// Lifecycle sets idle stop/destroy timers. The MCP server passes its
	// defaults here (stop after 30m idle, destroy after 24h, eng review D7).
	Lifecycle    *models.Lifecycle
	BlockNetwork bool
}

CreateSpec is a get-or-create request. Zero fields take the server default.

type Error

type Error struct {
	Code       string `json:"code"`
	Message    string `json:"message"`
	HTTPStatus int    `json:"http_status,omitempty"`
	Retryable  bool   `json:"retryable"`
	Hint       string `json:"hint,omitempty"`
	// contains filtered or unexported fields
}

Error is the machine-readable failure every agenttools operation returns. Message is for a person or a model; Hint, when set, names the next step (MCP tool errors carry it so the model can recover without guessing).

func Classify

func Classify(err error) *Error

Classify maps any error from the SDK, the network or agenttools onto an *Error. The code comes from the server's machine-readable code when it sent one, otherwise from the HTTP status, so the CLI and MCP report identical codes for identical failures.

func WithHint

func WithHint(err error, hint string) *Error

WithHint returns err classified, with hint attached when it has none yet.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

type ExecRequest

type ExecRequest struct {
	Command string
	Cwd     string
	Env     map[string]string
	// Timeout stops the command (KILL) and reports exit code 124. Zero means
	// no client-side timeout on the streaming path; the buffered path then
	// uses the toolbox default of 5 minutes.
	Timeout time.Duration
	// Stdin is forwarded to the command, then closed at EOF. Nil closes
	// stdin immediately. Not supported on the buffered path.
	Stdin io.Reader
	// TTY requests a pseudo-terminal of Cols x Rows. Streaming path only.
	TTY        bool
	Cols, Rows int
	// MaxOutputBytes bounds the captured output per stream; zero means
	// DefaultMaxOutputBytes.
	MaxOutputBytes int
	// OnStdout and OnStderr receive output live, in addition to capture.
	OnStdout func([]byte)
	OnStderr func([]byte)
	// Buffered forces the buffered path for every runtime. The remote MCP
	// endpoint sets it: its in-process transport can't carry a WebSocket.
	Buffered bool
}

ExecRequest runs one command in a sandbox.

type ExecResult

type ExecResult struct {
	ExitCode           int    `json:"exit_code"`
	Signal             string `json:"signal,omitempty"`
	TimedOut           bool   `json:"timed_out,omitempty"`
	Stdout             string `json:"stdout"`
	Stderr             string `json:"stderr"`
	StdoutTruncated    bool   `json:"stdout_truncated,omitempty"`
	StderrTruncated    bool   `json:"stderr_truncated,omitempty"`
	StdoutDroppedBytes int64  `json:"stdout_dropped_bytes,omitempty"`
	StderrDroppedBytes int64  `json:"stderr_dropped_bytes,omitempty"`
	DurationMS         int64  `json:"duration_ms"`
}

ExecResult is a finished command. ExitCode follows `docker exec`: the command's own code, 128+n when a signal killed it, 124 on timeout.

type FileEntry

type FileEntry struct {
	Name    string `json:"name"`
	IsDir   bool   `json:"is_dir"`
	Size    int64  `json:"size,omitempty"`
	Mode    string `json:"mode,omitempty"`
	ModTime string `json:"mod_time,omitempty"`
}

FileEntry is one directory entry.

type GrepMatch

type GrepMatch struct {
	File    string `json:"file"`
	Line    int    `json:"line"`
	Content string `json:"content"`
}

GrepMatch is one matching line.

type GrepResult

type GrepResult struct {
	Matches   []GrepMatch `json:"matches"`
	Truncated bool        `json:"truncated,omitempty"`
}

GrepResult is a content search, cut at MaxGrepMatches.

type ListFilesResult

type ListFilesResult struct {
	Path      string      `json:"path"`
	Entries   []FileEntry `json:"entries"`
	Truncated bool        `json:"truncated,omitempty"`
}

ListFilesResult is a directory listing, cut at MaxListEntries.

type Process

type Process struct {
	SessionID  string `json:"session_id"`
	Name       string `json:"name"`
	Status     string `json:"status"`
	ExitCode   int    `json:"exit_code,omitempty"`
	ExitSignal string `json:"exit_signal,omitempty"`
}

Process is a background command running in a session.

type ProcessLogs

type ProcessLogs struct {
	Process
	Output       string `json:"output"`
	Truncated    bool   `json:"truncated,omitempty"`
	DroppedBytes int64  `json:"dropped_bytes,omitempty"`
}

ProcessLogs is the tail of a background command's output.

type ReadFileResult

type ReadFileResult struct {
	Path       string `json:"path"`
	Content    string `json:"content"`
	StartLine  int    `json:"start_line"`
	EndLine    int    `json:"end_line"`
	NextOffset int    `json:"next_offset,omitempty"`
	// LineTruncated is set when one line alone exceeded the byte window and
	// was cut; NextOffset then skips the rest of that line.
	LineTruncated bool `json:"line_truncated,omitempty"`
}

ReadFileResult is one window of a text file. Lines are 1-based. NextOffset is the line to pass as Offset to read on; zero means the window reached the end of the file.

type SearchResult

type SearchResult struct {
	Files     []string `json:"files"`
	Truncated bool     `json:"truncated,omitempty"`
}

SearchResult lists paths whose names match a glob, cut at MaxSearchResults.

type Source

type Source string

Source records which front end created a sandbox.

const (
	SourceCLI Source = "cli"
	SourceMCP Source = "mcp"
)

type Tools

type Tools struct {
	// contains filtered or unexported fields
}

Tools runs agent operations against one sandboxd.

func New

func New(cfg Config) (*Tools, error)

New connects to sandboxd. Nothing is sent until the first operation.

func (*Tools) Client

func (t *Tools) Client() *microvm.Client

Client is the underlying SDK client, for operations agenttools doesn't wrap (start/stop, snapshots, health).

func (*Tools) EditFile

func (t *Tools) EditFile(ctx context.Context, sb *microvm.Sandbox, path, oldString, newString string) error

EditFile replaces the one occurrence of oldString in path with newString. It refuses when oldString is missing or appears more than once, so an edit never lands somewhere the caller didn't mean. Read and write are separate requests: a concurrent writer's change between them is lost (agent sessions are effectively single-writer).

func (*Tools) EnsureStarted

func (t *Tools) EnsureStarted(ctx context.Context, sb *microvm.Sandbox) (*microvm.Sandbox, error)

EnsureStarted starts a stopped sandbox. Toolbox calls don't wake a stopped sandbox, and agent sandboxes are stopped after 30 minutes idle by default (eng review D7), so file and exec operations start it first.

func (*Tools) Exec

func (t *Tools) Exec(ctx context.Context, sb *microvm.Sandbox, req ExecRequest) (ExecResult, error)

Exec runs req in sb and returns its exit status with bounded output. A non-zero exit is a normal result, not an error; errors are API, transport and argument failures.

The channel depends on the runtime (eng review D10): WASM sandboxes refuse streaming exec, so they use buffered /process/execute under MaxBufferedExecResponseBytes; every other runtime streams over the exec WebSocket into head/tail buffers.

func (*Tools) GetOrCreate

func (t *Tools) GetOrCreate(ctx context.Context, spec CreateSpec) (CreateResult, error)

GetOrCreate returns the caller's sandbox called spec.Name, creating it if it doesn't exist. It is safe to retry and to run concurrently (§5.4):

create(name?)
  name := given ?: "agent-" + rand12                     (D5: before any attempt)
  reject reserved names (owner: prefix, sb-<16 hex>)     (D9, D12)
  GET ?name=name ── hit ──► {created:false}  (warn if the image or runtime differs)
        │ miss
  POST {name, tags + aerolvm.created_by}                  (C6)
        ├─ 201 ──────────────► {created:true}
        ├─ 409 ─► GET ?name= ─► the caller's sandbox   (names are unique per owner, D4)
        └─ lost reply ─► SDK retries the same POST ─► 201, or 409 as above

A plain create retried after a lost reply would make a duplicate; keying every create by name is what makes the retry land on the same row. A server that ignores ?name= fails with server_unsupported: without a trustworthy lookup the create can't be made idempotent.

func (*Tools) GrepFiles

func (t *Tools) GrepFiles(ctx context.Context, sb *microvm.Sandbox, path, text string) (GrepResult, error)

GrepFiles finds lines under path that contain text (a plain substring).

func (*Tools) ListFiles

func (t *Tools) ListFiles(ctx context.Context, sb *microvm.Sandbox, path string) (ListFilesResult, error)

ListFiles lists one directory. toolboxd returns rich entries; the WASM toolhost returns bare names. Both decode here.

func (*Tools) ProcessLogs

func (t *Tools) ProcessLogs(ctx context.Context, sb *microvm.Sandbox, sessionID string, maxBytes int) (ProcessLogs, error)

ProcessLogs returns a background command's status and the head/tail of its recorded output, within maxBytes (0 means DefaultMaxOutputBytes). The session keeps at most its replay buffer (1 MiB by default) on the server.

func (*Tools) ReadFile

func (t *Tools) ReadFile(ctx context.Context, sb *microvm.Sandbox, path string, offset, limit int) (ReadFileResult, error)

ReadFile returns up to limit lines (default and maximum 2,000) and at most 256 KiB of path, starting at line offset (1-based; 0 means 1). It streams the file and stops reading one byte after the window (eng review D14): a multi-GB file costs one window, plus whatever precedes offset. Binary files are refused with their size and type.

func (*Tools) Resolve

func (t *Tools) Resolve(ctx context.Context, ref string) (*microvm.Sandbox, error)

Resolve finds the sandbox a "<id-or-name>" reference names, with one request (eng review D12). A ref shaped like a generated ID ("sb-" plus 16 hex) is looked up as an ID only; anything else as a name only. There is no fallback from one to the other, so a name can never shadow an ID, and creates reject names with the ID shape. Name lookups go through GetByName, which refuses a reply from a server that ignored ?name= (server_unsupported) rather than guessing from an unfiltered list.

func (*Tools) SearchFiles

func (t *Tools) SearchFiles(ctx context.Context, sb *microvm.Sandbox, path, pattern string) (SearchResult, error)

SearchFiles finds files under path whose name matches pattern (a glob such as "*.go").

func (*Tools) Source

func (t *Tools) Source() Source

Source reports which front end this Tools creates sandboxes for.

func (*Tools) StartProcess

func (t *Tools) StartProcess(ctx context.Context, sb *microvm.Sandbox, command, cwd string, env map[string]string) (Process, error)

StartProcess runs command in a new session that outlives this call (a dev server, a watcher). Sessions are how work survives a dropped connection; exec streams are killed when their connection drops.

Each call gets its own session name: sessions with the same name are the same session, so a fixed name would make a second start return the first process.

func (*Tools) StopProcess

func (t *Tools) StopProcess(ctx context.Context, sb *microvm.Sandbox, sessionID string) error

StopProcess kills a background command and removes its session. Stopping one that is already gone succeeds, so a retry is harmless.

func (*Tools) Target

func (t *Tools) Target(ctx context.Context, ref string) (*microvm.Sandbox, error)

Target resolves ref for an exec or file operation: resolve, refuse shell-less runtimes, and start the sandbox if it is stopped.

func (*Tools) WriteFile

func (t *Tools) WriteFile(ctx context.Context, sb *microvm.Sandbox, path, content string) error

WriteFile writes content to path, creating parent directories. It is idempotent: writing the same bytes twice leaves the same file.

Directories

Path Synopsis
Package agenttoolstest is an in-memory fake of the parts of sandboxd the aerolvm CLI and MCP server use: v1 sandboxes (create, get, list by name, start, destroy, ports), the toolbox file and exec endpoints, the exec WebSocket, and sessions.
Package agenttoolstest is an in-memory fake of the parts of sandboxd the aerolvm CLI and MCP server use: v1 sandboxes (create, get, list by name, start, destroy, ports), the toolbox file and exec endpoints, the exec WebSocket, and sessions.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL