tools

package
v0.45.2 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2026 License: MIT Imports: 39 Imported by: 0

Documentation

Index

Constants

View Source
const (
	PatchOperationAdd    PatchOperation = "add"
	PatchOperationUpdate PatchOperation = "update"
	PatchOperationDelete PatchOperation = "delete"
	PatchOperationMove   PatchOperation = "move"

	PatchOutcomeApplied PatchOutcome = "applied"
	PatchOutcomePartial PatchOutcome = "partial"
)

Variables

View Source
var (
	// ErrInvalidOptions reports unusable executor construction options.
	ErrInvalidOptions = errors.New("invalid tool executor options")
	// ErrInvalidLimits reports a limit set that cannot bound tool work.
	ErrInvalidLimits = errors.New("invalid tool limits")
	// ErrNotDirectory reports a path that exists but is not a directory.
	ErrNotDirectory = errors.New("path is not a directory")
	// ErrNotRegularFile reports a path that is not a regular file.
	ErrNotRegularFile = errors.New("path is not a regular file")
	// ErrBinaryContent reports a text operation refused on binary content.
	ErrBinaryContent = errors.New("binary content is not supported")
	// ErrImageContent reports a file named as an image whose bytes are not
	// that image format.
	ErrImageContent = errors.New("file is not the image its extension names")
	// ErrNotObserved reports a mutation on a path never read in this turn.
	ErrNotObserved = errors.New("path was not observed in the current turn")
	// ErrStaleHash reports a mismatch between expected and actual content.
	ErrStaleHash = errors.New("expected content hash does not match")
	// ErrHashRequired reports a mutation missing its expected content hash.
	ErrHashRequired = errors.New("expected content hash is required")
	// ErrMatchNotFound reports edit text absent from the file.
	ErrMatchNotFound = errors.New("exact text was not found")
	// ErrMatchNotUnique reports edit text present more than once.
	ErrMatchNotUnique = errors.New("exact text matched more than once")
	// ErrOverlappingEdits reports edits that replace the same region.
	ErrOverlappingEdits = errors.New("edits overlap")
	// ErrInvalidPatch reports malformed applyPatch input.
	ErrInvalidPatch = errors.New("invalid patch")
	// ErrPatchConflict reports file operations whose source or target collides.
	ErrPatchConflict = errors.New("patch paths conflict")
	// ErrPatchMatchNotFound reports strict update context absent from a source.
	ErrPatchMatchNotFound = errors.New("patch context was not found")
	// ErrPatchMatchNotUnique reports ambiguous strict update context.
	ErrPatchMatchNotUnique = errors.New("patch context matched more than once")
	// ErrDirectoryNotEmpty reports a non-recursive removal of a full tree.
	ErrDirectoryNotEmpty = errors.New("directory is not empty")
	// ErrLimitExceeded reports input too large to bound by truncation.
	ErrLimitExceeded = errors.New("tool limit exceeded")
	// ErrUnsupportedURL reports a webFetch URL that is not http or https, or
	// a redirect to one.
	ErrUnsupportedURL = errors.New("only http and https URLs are supported")
	// ErrCommandStartFailed reports a command that could not be launched.
	ErrCommandStartFailed = errors.New("command could not be started")
)

Functions

func ApplyPatchPaths

func ApplyPatchPaths(document string) ([]string, error)

ApplyPatchPaths returns every source and destination named by a valid patch in document order. It performs no filesystem operation.

func ContextWithToolCallID

func ContextWithToolCallID(
	ctx context.Context,
	toolCallID string,
) context.Context

ContextWithToolCallID attaches the tool-call ID that started this invocation of runCommand, so the resulting job records which specific call started it. The tools package cannot learn this ID from the model's JSON arguments; the caller must set it on ctx before invoking RunCommand.

func ValidateLimits added in v0.22.0

func ValidateLimits(limits Limits) error

ValidateLimits validates zero-defaulted bounds before runtime construction.

Types

type ApplyPatchFileResult

type ApplyPatchFileResult struct {
	Operation   PatchOperation `json:"operation"`
	Outcome     PatchOutcome   `json:"outcome"`
	Path        string         `json:"path"`
	Destination string         `json:"destination,omitempty"`
	Bytes       int            `json:"bytes"`
	SHA256      string         `json:"sha256,omitempty"`
}

ApplyPatchFileResult reports one file operation that reached the filesystem.

type ApplyPatchInput

type ApplyPatchInput struct {
	Patch string `json:"patch"`
}

ApplyPatchInput carries one complete Codex-compatible patch document.

type ApplyPatchOutput

type ApplyPatchOutput struct {
	Files         []ApplyPatchFileResult `json:"files"`
	Diff          string                 `json:"diff"`
	DiffTruncated bool                   `json:"diffTruncated"`
	Error         string                 `json:"error,omitempty"`
}

ApplyPatchOutput reports applied files and one bounded combined diff. Error is populated by the agent adapter when a later filesystem operation fails.

type EditFileInput

type EditFileInput struct {
	Path  string     `json:"path"`
	Edits []TextEdit `json:"edits"`
}

EditFileInput applies non-overlapping exact replacements to one file.

type EditFileOutput

type EditFileOutput struct {
	Path          string `json:"path"`
	Diff          string `json:"diff"`
	DiffTruncated bool   `json:"diffTruncated"`
	Applied       int    `json:"applied"`
	SHA256        string `json:"sha256"`
}

EditFileOutput carries a bounded unified diff and the new content hash.

type EntryType

type EntryType = string

EntryType names what a listed path is on the host filesystem. It is an alias because it carries no behavior and crosses the JSON tool boundary as a plain string.

const (
	// EntryTypeFile marks a regular file.
	EntryTypeFile EntryType = "file"
	// EntryTypeDirectory marks a directory.
	EntryTypeDirectory EntryType = "directory"
	// EntryTypeSymlink marks a symbolic link, reported without following it.
	EntryTypeSymlink EntryType = "symlink"
	// EntryTypeOther marks sockets, devices, and named pipes.
	EntryTypeOther EntryType = "other"
)

type EventPublisher

type EventPublisher = events.Publisher

EventPublisher publishes job completion notices without coupling jobs to a concrete bus. A nil publisher means "do not publish".

type Executor

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

Executor runs one turn's host filesystem and command tools. It resolves paths against the turn workspace, records what the turn has observed, and serializes mutations so a stale-write check cannot race another tool call.

The workspace is a default directory, never a boundary. Paths outside it, including `..` segments, dotfiles, and symlink targets, are resolved and used. Operating-system ownership and mode bits are the only restriction.

func NewExecutor

func NewExecutor(options Options) (*Executor, error)

NewExecutor validates the turn workspace and bounds. The workspace must be an existing absolute directory; the runtime canonicalizes it beforehand.

func (*Executor) ApplyPatch

func (e *Executor) ApplyPatch(
	ctx context.Context,
	input ApplyPatchInput,
) (ApplyPatchOutput, error)

ApplyPatch parses and applies one bounded Codex-compatible patch. Every path, observation, destination, and update hunk is checked before the first filesystem mutation. Each file write is atomic, but a multi-file patch is not globally transactional.

func (*Executor) AtDirectory added in v0.23.0

func (e *Executor) AtDirectory(
	ctx context.Context,
	directory string,
) (*Executor, error)

AtDirectory returns an independent executor at a canonical existing path. It retains this agent's observations and leaves the original unchanged.

func (*Executor) EditFile

func (e *Executor) EditFile(
	ctx context.Context,
	input EditFileInput,
) (EditFileOutput, error)

EditFile applies one or more exact-text replacements to a file the current turn has already observed. Every edit's Old text must appear in the original content exactly once; every match is located against that original content, so edit order never changes what another edit sees. New may be empty to delete the matched text. Edits whose matched ranges overlap fail the entire call, and nothing is written to disk unless every edit resolves to a single, non-overlapping match.

func (*Executor) Limits

func (e *Executor) Limits() Limits

Limits reports the bounds applied to every result.

func (*Executor) ListFiles

func (e *Executor) ListFiles(
	ctx context.Context,
	input ListFilesInput,
) (ListFilesOutput, error)

ListFiles lists the contents of one directory, bounded by the executor's list limits. An empty Path resolves to the workspace; any other Path is resolved per Executor.resolvePath, including outside the workspace.

func (*Executor) MakeDirectory

func (e *Executor) MakeDirectory(
	ctx context.Context,
	input MakeDirectoryInput,
) (MakeDirectoryOutput, error)

MakeDirectory creates a directory tree, creating any missing ancestors. An already-existing directory succeeds with an empty Created list.

func (*Executor) MovePath

func (e *Executor) MovePath(
	ctx context.Context,
	input MovePathInput,
) (MovePathOutput, error)

MovePath renames a file or directory. The source must have been observed this turn and the destination must not already exist; MovePath never overwrites.

func (*Executor) Observed

func (e *Executor) Observed(path string) bool

Observed reports whether this turn has already seen the resolved path.

func (*Executor) ReadFile

func (e *Executor) ReadFile(
	ctx context.Context,
	input ReadFileInput,
) (ReadFileOutput, error)

ReadFile reads a bounded line window from one regular file. SHA256 is computed over the whole file, not the returned window, so a caller can detect the file changing between reads regardless of which window it requested.

func (*Executor) RemovePath

func (e *Executor) RemovePath(
	ctx context.Context,
	input RemovePathInput,
) (RemovePathOutput, error)

RemovePath removes a file, symlink, or directory. A regular file requires a matching ExpectedSHA256, a symlink is removed as itself and never follows its target, and a non-empty directory requires Recursive and is bounded by MaxRemoveEntries.

func (*Executor) ResolvePath

func (e *Executor) ResolvePath(raw string) (string, error)

ResolvePath reports the normalized host path a tool argument refers to. It does not observe, create, or otherwise touch the path.

func (*Executor) RestoreObservations added in v0.25.0

func (e *Executor) RestoreObservations(snapshot []ObservedPath) error

RestoreObservations replaces the ledger after validating the whole snapshot. It grants no new file access and preserves stale-content checks on mutation.

func (*Executor) SearchText

func (e *Executor) SearchText(
	ctx context.Context,
	input SearchTextInput,
) (SearchTextOutput, error)

SearchText searches a file or a directory tree for lines matching Pattern, bounded by the executor's search limits. A directory is walked recursively without following symlinks: a symlinked entry keeps the type Lstat reports for it, so it is never treated as a regular file or descended into as a directory.

Resolving and enumerating the target itself (a missing path, or a top-level directory that cannot be listed) is a hard error. A single candidate file that cannot be read, is too large, or is binary is skipped silently, whether that file is the target itself or was found while walking a directory.

func (*Executor) SnapshotObservations added in v0.25.0

func (e *Executor) SnapshotObservations() []ObservedPath

SnapshotObservations returns independent read state in stable path order.

func (*Executor) WebFetch added in v0.40.0

func (e *Executor) WebFetch(
	ctx context.Context,
	input WebFetchInput,
) (WebFetchOutput, error)

WebFetch reads an http or https URL from the worker's network and returns its body as text. An HTML page is reduced to its readable text. Other text formats come back as they are, and any other content type is refused. At most Limits.MaxFetchBytes of the body is read. A non-2xx status is not an error: the output carries the status and whatever text the server sent.

func (*Executor) Workspace

func (e *Executor) Workspace() string

Workspace reports the default directory for this turn's tool calls.

func (*Executor) WriteFile

func (e *Executor) WriteFile(
	ctx context.Context,
	input WriteFileInput,
) (WriteFileOutput, error)

WriteFile creates a new file or replaces an existing one. Creation at a path proven absent requires no ExpectedSHA256 and rejects one if supplied. Replacing an existing file requires the path to have been observed this turn and requires ExpectedSHA256 to match the file's current content, so a concurrent change is never silently overwritten. Existing permission bits are preserved on replacement.

type FileEntry

type FileEntry struct {
	Path string    `json:"path"`
	Type EntryType `json:"type"`
	Size int64     `json:"size"`
	Mode string    `json:"mode"`
}

FileEntry describes one listed path relative to the listed directory.

type Job

type Job struct {
	ID                 uuid.UUID
	PID                int
	SessionID          uuid.UUID
	TurnID             uuid.UUID
	AgentRunID         uuid.UUID
	WorkerGenerationID string
	ToolCallID         string
	Purpose            string
	Command            string
	Directory          string
	StartedAt          time.Time
	// contains filtered or unexported fields
}

Job is one supervised process: what started it, its host process, and its captured output. The identity fields are set once at creation and never change; state, EndedAt, and ExitCode are read and written through mu so a concurrent reader never observes a torn update.

func (*Job) Done

func (j *Job) Done() <-chan struct{}

func (*Job) ReadStderr

func (j *Job) ReadStderr(cursor, maxLines int) ([]string, int, int)

ReadStderr is ReadStdout for the job's stderr.

func (*Job) ReadStdout

func (j *Job) ReadStdout(cursor, maxLines int) ([]string, int, int)

Done reports the channel this package closes exactly once, the moment the job leaves JobStateRunning. ReadStdout returns a bounded window of the job's stdout from a 1-based cursor, the cursor to resume from, and how many lines were dropped before the window. It exists so a reader outside a turn, such as the HTTP job endpoints, can follow a job without constructing a JobExecutor.

func (*Job) Release added in v0.14.1

func (j *Job) Release()

Release ends a caller's wait on a job that is still running. The job then publishes its completion event like any background job. Release does nothing once the job has finished, because the caller already holds its final result.

func (*Job) Snapshot

func (j *Job) Snapshot() JobSnapshot

Snapshot copies every field a caller outside this package may read, so listJobs, readJobOutput, waitJob, and signalJob never touch a Job's internal locks directly.

type JobExecutor

type JobExecutor struct {
	*Executor
	// contains filtered or unexported fields
}

JobExecutor extends Executor with the session-scoped job registry that process-oriented tools need: runCommand, listJobs, readJobOutput, waitJob, and signalJob. It embeds Executor so every other host tool method stays available unchanged on the same value; a caller can use a JobExecutor everywhere it previously used a plain Executor.

func NewJobExecutor

func NewJobExecutor(
	executor *Executor,
	jobs *JobRegistry,
	turnID uuid.UUID,
	generationIDs ...uuid.UUID,
) (*JobExecutor, error)

NewJobExecutor attaches a session-scoped job registry and the current turn's ID to an already constructed Executor. jobs must be shared across every turn in one session, never rebuilt per turn, so a job started in one turn stays visible in a later one.

func (*JobExecutor) AtCanonicalDirectory added in v0.25.0

func (e *JobExecutor) AtCanonicalDirectory(
	ctx context.Context,
	directory string,
) (*JobExecutor, error)

AtCanonicalDirectory restores a saved virtual path from the filesystem root. Host paths retain AtDirectory's absolute-path behavior.

func (*JobExecutor) AtDirectory added in v0.23.0

func (e *JobExecutor) AtDirectory(
	ctx context.Context,
	directory string,
) (*JobExecutor, error)

AtDirectory keeps supervision session-scoped while changing file paths.

func (*JobExecutor) ForAgentRun added in v0.25.0

func (e *JobExecutor) ForAgentRun(agentRunID uuid.UUID) *JobExecutor

ForAgentRun changes process ownership without changing shared supervision. A zero identity selects the root conversation.

func (*JobExecutor) Fork added in v0.23.0

func (e *JobExecutor) Fork(ctx context.Context) (*JobExecutor, error)

Fork gives a child a private observation ledger at its parent's directory.

func (*JobExecutor) ListJobs

func (e *JobExecutor) ListJobs(
	_ context.Context,
	input ListJobsInput,
) (ListJobsOutput, error)

ListJobs reports this session's jobs, oldest first, bounded by Limits.MaxListJobs.

func (*JobExecutor) ReadJobOutput

func (e *JobExecutor) ReadJobOutput(
	_ context.Context,
	input ReadJobOutputInput,
) (ReadJobOutputOutput, error)

ReadJobOutput returns a bounded incremental window of one job's output, starting at the requested cursors. Found is false when JobID names no job in this session, including a job ID that belongs to a different session.

func (*JobExecutor) RunCommand

func (e *JobExecutor) RunCommand(
	ctx context.Context,
	input RunCommandInput,
) (RunCommandOutput, error)

RunCommand executes one shell command immediately: no approval step, no allowlist or denylist, no sandbox. Isolation is the operator's job, not this method's.

A timeout here bounds only how long this call WAITS, never the process's life: a command still running when the wait bound elapses, or started with Background, is left running and reported as a job handle. Invalid input, an invalid working directory, caller cancellation or a launch failure returns an error. Non-zero exits are reported in the output. Caller cancellation while awaiting a foreground command kills its process group. A returned job handle has detached and survives later cancellation.

func (*JobExecutor) SignalJob

func (e *JobExecutor) SignalJob(
	ctx context.Context,
	input SignalJobInput,
) (SignalJobOutput, error)

SignalJob asks one job's process group to stop or die. Signalling an unknown, exited, or already signalled job is idempotent: it reports the job's current state rather than failing.

func (*JobExecutor) WaitJob

func (e *JobExecutor) WaitJob(
	ctx context.Context,
	input WaitJobInput,
) (WaitJobOutput, error)

WaitJob blocks up to the requested time for one job to leave the running state, then reports its status and whatever output arrived while waiting. Found is false when JobID names no job in this session.

type JobObserver added in v0.4.0

type JobObserver interface {
	JobStarted(context.Context, JobSnapshot) error
	// JobOutput receives one or more lines of one stream, in order.
	JobOutput(context.Context, JobSnapshot, []JobOutputRecord) error
	JobSignal(context.Context, JobSnapshot, JobSignal) error
	JobFinished(context.Context, JobSnapshot) error
}

JobObserver persists process lifecycle data before this registry exposes it to live readers. A nil observer leaves the registry usable for standalone callers that do not configure durable storage.

type JobOutputRecord added in v0.4.0

type JobOutputRecord struct {
	Stream    JobStream
	Content   string
	CreatedAt time.Time
}

JobOutputRecord is one captured line before it reaches an in-memory buffer.

type JobRegistry

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

JobRegistry owns every process job for one session, deliberately outliving any single turn: a job started in one turn stays visible, readable, and killable from a later one.

func NewJobRegistry

func NewJobRegistry(
	sessionID uuid.UUID,
	publisher EventPublisher,
	limits Limits,
	collectors ...*metrics.Metrics,
) (*JobRegistry, error)

NewJobRegistry builds a session-scoped job registry. publisher may be nil, meaning completion events are not published.

func (*JobRegistry) Get

func (r *JobRegistry) Get(id uuid.UUID) (*Job, bool)

Get looks up one job by ID within this session's registry.

func (*JobRegistry) List

func (r *JobRegistry) List() []*Job

List returns every job this registry has ever started, in no particular order.

func (*JobRegistry) SetCommandRunner added in v0.22.0

func (r *JobRegistry) SetCommandRunner(runner commander.Commander)

SetCommandRunner selects the process backend before any jobs start.

func (*JobRegistry) SetObserver added in v0.4.0

func (r *JobRegistry) SetObserver(observer JobObserver)

SetObserver configures lifecycle persistence for jobs this registry starts. Call it during session setup, before the registry becomes visible to tools.

func (*JobRegistry) Shutdown

func (r *JobRegistry) Shutdown(ctx context.Context) error

Shutdown starts bounded graceful stops and waits for durable finalization. Cancellation ends this wait. A later call also waits for the prior stop goroutines, so their observers and logs cannot outlive resource cleanup.

func (*JobRegistry) Signal

func (r *JobRegistry) Signal(
	ctx context.Context,
	id uuid.UUID,
	signal JobSignal,
) (JobSnapshot, bool)

Signal asks one job to stop or die. Found is false when id names no job in this session. Signalling a job that is not running is a no-op: it reports the job's current (terminal) state rather than failing, and signalling a running job dispatches the request asynchronously and reports JobStateRunning, since the process has not necessarily exited by the time this call returns.

func (*JobRegistry) SignalContext added in v0.4.0

func (r *JobRegistry) SignalContext(
	ctx context.Context,
	id uuid.UUID,
	signal JobSignal,
) (JobSnapshot, bool, error)

SignalContext persists the request before it dispatches a process signal.

func (*JobRegistry) Start

func (r *JobRegistry) Start(
	ctx context.Context,
	input StartJobInput,
) (*Job, error)

Start launches one process through commander and registers it. The process's own execution context is detached from ctx on purpose: cancelling ctx (a turn ending or its own bound expiring) must never kill a job, only an explicit signal, Shutdown, or the process exiting does. ctx is only used for a pre-flight cancellation check and to log from the goroutines this call spawns.

type JobSignal

type JobSignal = string

JobSignal selects how signalJob asks a job's process group to stop.

const (
	// JobSignalStop requests a graceful SIGTERM, escalating to SIGKILL if
	// the process group does not exit within the configured grace period.
	JobSignalStop JobSignal = "stop"
	// JobSignalKill requests an immediate SIGKILL with no grace period.
	JobSignalKill JobSignal = "kill"
)

type JobSnapshot

type JobSnapshot struct {
	ID                  uuid.UUID
	PID                 int
	SessionID           uuid.UUID
	TurnID              uuid.UUID
	AgentRunID          uuid.UUID
	WorkerGenerationID  string
	ToolCallID          string
	Purpose             string
	Command             string
	Directory           string
	State               JobState
	StartedAt           time.Time
	EndedAt             time.Time
	ExitCode            int
	FailureDetail       string
	StdoutBufferedLines int
	StdoutDroppedLines  int
	StderrBufferedLines int
	StderrDroppedLines  int
}

JobSnapshot is one point-in-time, race-free view of a job.

type JobState

type JobState = string

JobState names the lifecycle stage of one supervised process job. It is an alias because it carries no behavior and crosses the JSON tool boundary as a plain string.

const (
	// JobStateRunning marks a job whose process has not yet exited.
	JobStateRunning JobState = "running"
	// JobStateExited marks a job whose process exited on its own, whatever
	// its exit code.
	JobStateExited JobState = "exited"
	// JobStateSignalled marks a job terminated by a signal, whether sent
	// through signalJob, shutdown, or an outside actor.
	JobStateSignalled JobState = "signalled"
	// JobStateFailed marks a job that could not be launched or whose wait
	// failed in a way that is neither a normal exit nor a signal.
	JobStateFailed JobState = "failed"
)

type JobStream

type JobStream = string

JobStream selects which output stream(s) readJobOutput returns.

const (
	// JobStreamStdout selects only standard output.
	JobStreamStdout JobStream = "stdout"
	// JobStreamStderr selects only standard error.
	JobStreamStderr JobStream = "stderr"
	// JobStreamBoth selects both streams. The default when Stream is empty.
	JobStreamBoth JobStream = "both"
)

type JobSummary

type JobSummary struct {
	JobID      uuid.UUID `json:"jobId"`
	PID        int       `json:"pid"`
	TurnID     uuid.UUID `json:"turnId"`
	ToolCallID string    `json:"toolCallId"`
	Purpose    string    `json:"purpose"`
	Command    string    `json:"command"`
	Directory  string    `json:"directory"`
	State      JobState  `json:"state"`
	StartedAt  time.Time `json:"startedAt"`
	// omitzero, not omitempty: omitempty does nothing on a struct, so a
	// running job would serialize a zero timestamp instead of no timestamp.
	EndedAt             time.Time `json:"endedAt,omitzero"`
	ExitCode            int       `json:"exitCode"`
	StdoutBufferedLines int       `json:"stdoutBufferedLines"`
	StdoutDroppedLines  int       `json:"stdoutDroppedLines"`
	StderrBufferedLines int       `json:"stderrBufferedLines"`
	StderrDroppedLines  int       `json:"stderrDroppedLines"`
}

JobSummary describes one job for listJobs: identity, attribution, timing, and how much of its output is currently buffered or already dropped.

type Limits

type Limits struct {
	MaxListEntries        int
	MaxListDepth          int
	MaxSearchMatches      int
	MaxSearchFileBytes    int64
	MaxReadBytes          int
	MaxReadLines          int
	MaxWriteBytes         int
	MaxEdits              int
	MaxDiffBytes          int
	MaxPatchBytes         int
	MaxPatchFiles         int
	MaxPatchHunks         int
	MaxPatchChangedBytes  int
	MaxRemoveEntries      int
	MaxCommandOutputBytes int
	// CommandTimeout is how long runCommand waits when a call passes no
	// timeout. A call may ask for any wait.
	CommandTimeout time.Duration

	// MaxJobOutputLines bounds how many lines a job's stdout/stderr ring
	// buffer retains. MaxCommandOutputBytes bounds the same buffer's total
	// bytes; whichever bound is hit first evicts the oldest lines.
	MaxJobOutputLines int
	// MaxReadJobOutputLines bounds one readJobOutput/waitJob window,
	// independent of how much a job's ring buffer retains overall.
	MaxReadJobOutputLines int
	// WaitJobTimeout is how long waitJob waits when a call passes no
	// timeout. A call may ask for any wait.
	WaitJobTimeout time.Duration
	// JobStopGracePeriod bounds how long signalJob's stop and the registry's
	// Shutdown wait after SIGTERM before escalating to SIGKILL.
	JobStopGracePeriod time.Duration
	// MaxListJobs bounds how many jobs listJobs returns in one call.
	MaxListJobs int
	// MaxImageBytes bounds an image file readFile returns as an image,
	// instead of MaxReadBytes, which bounds text.
	MaxImageBytes int
	// MaxFetchBytes bounds how much of a response body webFetch reads.
	MaxFetchBytes int
	// MaxPDFBytes bounds a PDF readFile reads whole to extract its text,
	// instead of MaxReadBytes, which bounds text.
	MaxPDFBytes int
}

Limits bounds every host tool result. Zero fields take the default.

func DefaultLimits

func DefaultLimits() Limits

DefaultLimits returns the bounded defaults every deployment starts from.

type ListFilesInput

type ListFilesInput struct {
	Path      string `json:"path"`
	Recursive bool   `json:"recursive"`
	MaxDepth  int    `json:"maxDepth"`
}

ListFilesInput selects one directory listing.

type ListFilesOutput

type ListFilesOutput struct {
	Directory string      `json:"directory"`
	Entries   []FileEntry `json:"entries"`
	Truncated bool        `json:"truncated"`
}

ListFilesOutput carries a bounded directory listing in stable path order.

type ListJobsInput

type ListJobsInput struct {
	State JobState `json:"state"`
}

ListJobsInput selects this session's jobs. An empty State lists every job.

type ListJobsOutput

type ListJobsOutput struct {
	Jobs      []JobSummary `json:"jobs"`
	Truncated bool         `json:"truncated"`
}

ListJobsOutput carries a bounded, oldest-first list of this session's jobs.

type MakeDirectoryInput

type MakeDirectoryInput struct {
	Path string `json:"path"`
}

MakeDirectoryInput creates a bounded directory tree.

type MakeDirectoryOutput

type MakeDirectoryOutput struct {
	Path    string   `json:"path"`
	Created []string `json:"created"`
}

MakeDirectoryOutput lists the directories this call actually created.

type MovePathInput

type MovePathInput struct {
	Source      string `json:"source"`
	Destination string `json:"destination"`
}

MovePathInput renames one file or directory. Destination must not exist.

type MovePathOutput

type MovePathOutput struct {
	Source      string `json:"source"`
	Destination string `json:"destination"`
}

MovePathOutput reports the resolved endpoints of one rename.

type ObservedPath added in v0.25.0

type ObservedPath struct {
	Path     string `json:"path"`
	Hash     string `json:"hash,omitempty"`
	HasHash  bool   `json:"hasHash"`
	Revision uint64 `json:"revision,omitempty"`
}

type Options

type Options struct {
	Filesystem workspacefs.FS
	Virtual    bool
	// Workspace is the already canonicalized default directory for the turn.
	Workspace string
	// ProtectedDirectory retains the session workspace removal guard on hops.
	ProtectedDirectory string
	Limits             Limits

	// Environment is the base environment of every command, as KEY=VALUE
	// entries. Nil means the process environment. A deployment that holds
	// secrets in its own environment passes a copy without them.
	Environment []string
}

Options configures one per-turn executor.

type PatchOperation

type PatchOperation string

PatchOperation identifies one file-level applyPatch action.

type PatchOutcome

type PatchOutcome string

PatchOutcome identifies whether one reported operation fully completed.

type ReadFileInput

type ReadFileInput struct {
	Path   string `json:"path"`
	Offset int    `json:"offset"`
	Limit  int    `json:"limit"`
}

ReadFileInput selects one line window. Offset is the 1-based first line.

type ReadFileOutput

type ReadFileOutput struct {
	Path       string `json:"path"`
	Content    string `json:"content"`
	FirstLine  int    `json:"firstLine"`
	LastLine   int    `json:"lastLine"`
	TotalLines int    `json:"totalLines"`
	NextOffset int    `json:"nextOffset"`
	Truncated  bool   `json:"truncated"`
	SHA256     string `json:"sha256"`

	// MediaType and SizeBytes describe an image file. Its bytes are in
	// Image, which the agent attaches as an image instead of encoding it in
	// the text result.
	MediaType string `json:"mediaType,omitempty"`
	SizeBytes int    `json:"sizeBytes,omitempty"`
	Image     []byte `json:"-"`

	// Pages is a PDF's page count. Its text is in Content, a marker line
	// before each page.
	Pages int `json:"pages,omitempty"`
	// Note says something the model needs to know about the content, such as
	// a PDF with no text layer.
	Note string `json:"note,omitempty"`
}

ReadFileOutput carries the window plus continuation and identity metadata. NextOffset is zero when the window reached the end of the file.

type ReadJobOutputInput

type ReadJobOutputInput struct {
	JobID        uuid.UUID `json:"jobId"`
	Stream       JobStream `json:"stream"`
	StdoutCursor int       `json:"stdoutCursor"`
	StderrCursor int       `json:"stderrCursor"`
	MaxLines     int       `json:"maxLines"`
}

ReadJobOutputInput selects a bounded incremental window of one job's output. StdoutCursor and StderrCursor are the cursors returned by a previous call, or zero to read from the oldest line still buffered.

type ReadJobOutputOutput

type ReadJobOutputOutput struct {
	JobID              uuid.UUID `json:"jobId"`
	Found              bool      `json:"found"`
	State              JobState  `json:"state"`
	Stdout             string    `json:"stdout"`
	Stderr             string    `json:"stderr"`
	NextStdoutCursor   int       `json:"nextStdoutCursor"`
	NextStderrCursor   int       `json:"nextStderrCursor"`
	StdoutDroppedLines int       `json:"stdoutDroppedLines"`
	StderrDroppedLines int       `json:"stderrDroppedLines"`
}

ReadJobOutputOutput carries the requested window plus the cursor to resume from and how many lines were dropped before the window began. Found is false when JobID is not a job in this session.

type RemovePathInput

type RemovePathInput struct {
	Path           string `json:"path"`
	Recursive      bool   `json:"recursive"`
	ExpectedSHA256 string `json:"expectedSha256"`
}

RemovePathInput removes one file or directory. ExpectedSHA256 is required for a regular file. Recursive is required for a non-empty directory.

type RemovePathOutput

type RemovePathOutput struct {
	Path    string `json:"path"`
	Removed int    `json:"removed"`
}

RemovePathOutput reports how many entries the removal deleted.

type RunCommandInput

type RunCommandInput struct {
	Command     string            `json:"command"`
	Directory   string            `json:"directory"`
	Environment map[string]string `json:"environment"`
	Purpose     string            `json:"purpose"`
	Timeout     string            `json:"timeout"`
	Background  bool              `json:"background"`
}

RunCommandInput executes one shell command immediately, no approval step. Purpose is required: one short line saying why the agent is running this, stored with the resulting job. Timeout is a Go duration string such as "90s" or "1h30m" that bounds how long this call WAITS for the command, never how long the command may run; empty takes the configured default. A command still running when the bound elapses is left running and reported as a job handle. Background skips the wait entirely and returns the handle at once.

type RunCommandOutput

type RunCommandOutput struct {
	JobID              uuid.UUID `json:"jobId"`
	PID                int       `json:"pid"`
	Directory          string    `json:"directory"`
	Purpose            string    `json:"purpose"`
	Background         bool      `json:"background"`
	Running            bool      `json:"running"`
	State              JobState  `json:"state"`
	ExitCode           int       `json:"exitCode"`
	Stdout             string    `json:"stdout"`
	Stderr             string    `json:"stderr"`
	StdoutDroppedLines int       `json:"stdoutDroppedLines"`
	StderrDroppedLines int       `json:"stderrDroppedLines"`
	// Note tells the model how to keep waiting when the wait ended with the
	// command still running. Empty otherwise.
	Note string `json:"note,omitempty"`
}

RunCommandOutput reports the job this call started and whatever its wait bound observed. Running is true when the process was still alive when this call returned, whether because Background skipped the wait or because the wait bound elapsed first; a running job is never killed by returning it, only recorded. Stdout and Stderr carry every line captured so far. ExitCode is unknownExitCode until State leaves JobStateRunning with a normal exit.

type SearchMatch

type SearchMatch struct {
	Path string `json:"path"`
	Line int    `json:"line"`
	Text string `json:"text"`
}

SearchMatch is one matching line.

type SearchTextInput

type SearchTextInput struct {
	Path       string   `json:"path"`
	Pattern    string   `json:"pattern"`
	Regex      bool     `json:"regex"`
	Include    []string `json:"include"`
	MaxMatches int      `json:"maxMatches"`
}

SearchTextInput selects a bounded literal or regular-expression search.

type SearchTextOutput

type SearchTextOutput struct {
	Matches   []SearchMatch `json:"matches"`
	Truncated bool          `json:"truncated"`
}

SearchTextOutput carries bounded matches in stable path and line order.

type SignalJobInput

type SignalJobInput struct {
	JobID  uuid.UUID `json:"jobId"`
	Signal JobSignal `json:"signal"`
}

SignalJobInput asks one job's process group to stop or die. Signalling an unknown, exited, or already signalled job is idempotent: see SignalJobOutput.Found and SignalJobOutput.State.

type SignalJobOutput

type SignalJobOutput struct {
	JobID  uuid.UUID `json:"jobId"`
	Found  bool      `json:"found"`
	Signal JobSignal `json:"signal"`
	State  JobState  `json:"state"`
}

SignalJobOutput reports the job's state at the moment signalJob was called, not necessarily its state once the signal takes effect. Found is false when JobID is not a job in this session; that is reported, not failed.

type StartJobInput

type StartJobInput struct {
	Command            string
	Directory          string
	Env                []string
	Purpose            string
	TurnID             uuid.UUID
	AgentRunID         uuid.UUID
	WorkerGenerationID string
	ToolCallID         string
	// Awaited starts the job with a caller waiting on it. The caller calls
	// Release when it stops waiting while the job still runs.
	Awaited bool
}

StartJobInput starts one supervised process.

type TextEdit

type TextEdit struct {
	Old string `json:"old"`
	New string `json:"new"`
}

TextEdit is one exact replacement. Old must occur exactly once.

type WaitJobInput

type WaitJobInput struct {
	JobID        uuid.UUID `json:"jobId"`
	Timeout      string    `json:"timeout"`
	StdoutCursor int       `json:"stdoutCursor"`
	StderrCursor int       `json:"stderrCursor"`
}

WaitJobInput blocks for one job to leave the running state, up to a bound. Timeout is a Go duration string such as "30s"; empty takes the configured default. StdoutCursor and StderrCursor windowed exactly as in ReadJobOutputInput.

type WaitJobOutput

type WaitJobOutput struct {
	JobID              uuid.UUID `json:"jobId"`
	Found              bool      `json:"found"`
	Running            bool      `json:"running"`
	State              JobState  `json:"state"`
	ExitCode           int       `json:"exitCode"`
	DurationMs         int64     `json:"durationMs"`
	Duration           string    `json:"duration"`
	Stdout             string    `json:"stdout"`
	Stderr             string    `json:"stderr"`
	NextStdoutCursor   int       `json:"nextStdoutCursor"`
	NextStderrCursor   int       `json:"nextStderrCursor"`
	StdoutDroppedLines int       `json:"stdoutDroppedLines"`
	StderrDroppedLines int       `json:"stderrDroppedLines"`
	// Note tells the model how to keep waiting when the wait ended with the
	// job still running. Empty otherwise.
	Note string `json:"note,omitempty"`
}

WaitJobOutput reports the job's status once waitJob returns, plus whatever output arrived during the wait. Found is false when JobID is not a job in this session; Running is true when the bound elapsed first. Duration is DurationMs rendered as a Go duration string.

type WebFetchInput added in v0.40.0

type WebFetchInput struct {
	URL string `json:"url"`
}

WebFetchInput names the page webFetch reads.

type WebFetchOutput added in v0.40.0

type WebFetchOutput struct {
	URL         string `json:"url"`
	Status      int    `json:"status"`
	ContentType string `json:"contentType"`
	Title       string `json:"title,omitempty"`
	Text        string `json:"text"`
	Truncated   bool   `json:"truncated"`
}

WebFetchOutput is a fetched page as text. URL is where the request ended after redirects. Text is the body, with an HTML page reduced to its readable text. Truncated reports a body cut at the fetch limit.

type WriteFileInput

type WriteFileInput struct {
	Path           string `json:"path"`
	Content        string `json:"content"`
	ExpectedSHA256 string `json:"expectedSha256"`
}

WriteFileInput creates or replaces one text file. ExpectedSHA256 is required when the path already exists and rejected when it does not.

type WriteFileOutput

type WriteFileOutput struct {
	Path    string `json:"path"`
	Created bool   `json:"created"`
	Bytes   int    `json:"bytes"`
	SHA256  string `json:"sha256"`
}

WriteFileOutput reports the durable result of one write.

Jump to

Keyboard shortcuts

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