Skip to content
Source on GitHub (opens in a new tab)
import "github.com/barevoidco/zelk/core/tool"

Package tool defines tools: named, described actions the model can ask zelk to run, with an input schema derived from a Go type.

A tool’s input schema is fixed at definition time and must fit zelk’s canonical schema subset, so it means the same thing to every model. DefineOpenSchema carries a foreign object-root JSON Schema without narrowing; providers render it non-strict and Run validates it locally, preserving null. Its arguments are validated locally before it runs, whatever the provider claims. How a run ends is classified by error class (docs/design/durability.md, E5), which decides whether zelk may retry it after a crash. A Call carries its stable idempotency key, attempt number and fencing token. Tools declaring WithEnforcedIdempotency must enforce at-most-once action per key themselves.

Schema field tags accepted by Define and DefineCall are json (names and omitempty/omitzero), desc, enum, minimum, maximum, minItems, maxItems, pattern and format. Sized integer types imply their range; explicit bounds may tighten it. A float64 carries no implied bounds, since validation refuses any number beyond its range itself, and float32 is refused. Fields with omitempty or omitzero are optional; others are required. Unsupported types or constraints fail definition instead of weakening validation.

Call is the author-facing session view. The driver owns runtime recording and builtin bookkeeping internally. Call.Environment supplies the host-owned confined environment, which tools must not close.

var (
// ErrNotDispatched marks an error after which the tool provably did
// nothing, so running it again is safe.
ErrNotDispatched = errors.New("tool did not run")
// ErrFailed marks a definite failure: the tool ran and failed, and the
// error goes to the model.
ErrFailed = errors.New("tool failed")
// ErrInvalidInput is returned by Run for arguments that don't fit the
// tool's schema; the tool didn't run. The error lists every problem.
ErrInvalidInput = errors.New("invalid tool arguments")
// ErrPanicked is returned by Run when the tool's function panicked.
// The tool may have acted before it did, so the outcome is unknown.
ErrPanicked = errors.New("tool panicked")
)
func Classify(err error) event.Outcome

Classify maps how a run ended to its outcome. A nil error is done (a result with IsError is reported as failed by the caller). Errors wrapping ErrNotDispatched, ErrFailed or ErrInvalidInput are not dispatched or failed; every other error, including a panic, leaves the outcome unknown, and such a run is never retried automatically.

func Untrusted(label, text string, limit int) history.Part

Untrusted returns text as one part fenced as untrusted data: a label line naming where it came from, then the text between <untrusted> tags. Tags in the label and text are broken with a zero-width space so they can’t open or close the fence, regardless of case or spacing. After escaping, the text is cut to limit bytes. A note outside the fence marks truncation. Use this for content from a web page, a server or another source the model must not take instructions from.

type Call interface {
// Cwd returns the working directory relative to the workspace.
Cwd() string
// Session returns the session identity.
Session() string
// Environment returns the host's tool environment, or nil if absent.
Environment() env.Environment
// Observed returns the last recorded observation of path at call start.
Observed(path string) (event.FileObserved, bool)
// Observe records a file observation for later calls.
Observe(event.FileObserved)
// Chdir records a new workspace-relative working directory for later calls.
Chdir(dir string)
// Print sends live output without adding it to the durable log.
Print(text string)
// IdempotencyKey is stable across attempts; tools promising enforced
// idempotency must deduplicate external actions by this key.
IdempotencyKey() string
// Token is the current lease fence for cooperating external systems.
Token() lease.Token
// Attempt is the dispatch attempt number.
Attempt() int
}

Call is a tool author’s fixed session view and observation sink. The driver appends observations with the result; later calls see them through the log. It is safe for concurrent use during one tool invocation. The host owns the environment; tools must use it for workspace I/O and must not close it.

type Descriptor struct {
// StopsProcess extracts the owned process handle a call stops, if any.
StopsProcess func(json.RawMessage) string `json:"-"`
// SchemaKind identifies the input contract; only DefineOpenSchema sets it.
SchemaKind event.SchemaKind
// WithEnforcedIdempotency promises at-most-once action for each Call.IdempotencyKey.
EnforcedIdempotency bool
// Name is how the model calls the tool: 1 to 64 letters, digits, '_'
// or '-', which every provider accepts.
Name string
Description string
Origin Origin
// WithReadOnly tools don't change anything; read-only calls in a batch run
// in parallel.
ReadOnly bool
// WithIdempotent tools can run again with the same arguments safely, which
// lets zelk re-run a read-only, idempotent call after a crash.
Idempotent bool
// Trusted says ReadOnly and Idempotent can be believed. Tools defined
// in Go by the host are trusted; MCP tools are not by default.
Trusted bool
// Reserve is the most model tokens one call may spend, for a tool that
// calls a model itself; nil for one that never does. Each call reserves
// it from the budget before it runs and settles what Result.Usage
// reports (docs/design/durability.md, B2).
Reserve *event.Tokens
// RouteReserve, set by WithRouteReservation, gives the reservation for
// a tool whose model calls depend on the session's model route.
RouteReserve func(ctx context.Context, family history.Family, model string) (event.Tokens, bool, error)
// ReadOnlyWhen, set by WithReadOnlyWhen, names the calls of a tool that
// isn't read-only as a whole that are: those whose input field has one
// of the values. It is believed only when Trusted is.
ReadOnlyWhen *event.ReadOnlyWhen
// WritesPath, set by WithWritesPath, names the input field holding
// the workspace path each call may write.
WritesPath string
// URLField, set by WithURL, names the input field holding the URL a
// call acts on, which domain rules match.
URLField string
// ReadsPath, set by WithReadsPath, names the input field holding a
// file a call reads and sends somewhere.
ReadsPath string
// PersonDecides, set by WithPersonDecides, is the tool pattern a
// session grant for the tool's calls names; "" if auto mode's
// reviewer may decide them.
PersonDecides string
// TrustedTab, set by WithTrustedTab, says each call acts in a tab
// the user trusted, unless its input's boolean field NewTabField is
// true.
TrustedTab bool
NewTabField string
// WithRawArguments says Run passes the model's arguments to the tool as
// they are, unvalidated: the tool checks them against its schema
// itself, because it must see, and record, arguments that don't fit.
RawArguments bool
// Deferred, set by WithDeferred, keeps the tool's schema out of the
// model's requests until ToolSearch finds it.
Deferred bool
// contains filtered or unexported fields
}

Descriptor describes a tool.

type Mover interface {
// Root returns the session's workspace root.
Root() string
// Move records the move to the clean absolute slash-separated root to;
// worktree says to is a git worktree of the session's own. It returns
// an error, recording nothing, when the session can't move.
Move(to string, worktree bool, reason string) error
}

Mover is implemented by a Call whose tool may move the session to another workspace root, such as a worktree. The move takes effect once the call has finished: the driver records it with the call’s result, stops the turn until the session has been taken up at the new root, and the turn goes on there, with what was known of the old root’s files dropped (docs/design/transitions.md). A host whose execution ends with driver.ErrMoved takes the session up at the new root.

Example

enter, err := tool.DefineCall("Enter", "Work in another directory.", func(_ context.Context, c tool.Call, in struct {
Dir string `json:"dir"`
}) (tool.Result, error) {
m, ok := c.(tool.Mover)
if !ok {
return tool.Failuref("this host can't move sessions"), nil
}
// The driver records the move with this result; the host whose
// execution then ends with driver.ErrMoved takes the session up
// at in.Dir, and the turn goes on there.
if err := m.Move(in.Dir, false, "the user asked"); err != nil {
return tool.Failuref("can't enter %s: %v", in.Dir, err), nil
}
return tool.Text("Moving from " + m.Root() + " to " + in.Dir + "."), nil
})
if err != nil {
panic(err)
}
// Outside a session there is nothing to move.
result, err := enter.Run(context.Background(), nil, json.RawMessage(`{"dir":"/elsewhere"}`))
if err != nil {
panic(err)
}
fmt.Println(result.Content[0].Text)
// Output: can't enter /elsewhere: this session can't move to another workspace

Output:

can't enter /elsewhere: this session can't move to another workspace
type Option interface {
// contains filtered or unexported methods
}

Option configures a tool.

func WithDeferred() Option

WithDeferred keeps the tool’s schema out of the model’s requests: the model finds it with ToolSearch, as it finds a deferred MCP tool, so a session that never uses it doesn’t pay for its schema on every turn. For a host tool set too large to send whole, whose tools most sessions use few of. WithoutDeferredTools sends it like any other tool.

func WithEnforcedIdempotency() Option

WithEnforcedIdempotency declares that the tool enforces deduplication by Call.IdempotencyKey.

func WithIdempotent() Option

WithIdempotent marks the tool as safe to run again with the same arguments.

func WithOrigin(o Origin) Option

WithOrigin sets where the tool comes from; the default is event.OriginBuiltin, a Go function in the host process. A tool from an MCP server or a client is always untrusted: its ReadOnly and Idempotent claims are never relied on.

func WithPersonDecides(grant string) Option

WithPersonDecides declares that an allow rule or a person decides each call, never auto mode’s reviewer on its own: a wrong allow would cost too much, as acting in the user’s own browser would. Without a rule, auto mode asks a person, and dont-ask and headless sessions refuse. A person may allow the call’s site for the session: the grant names grant, a tool pattern covering this tool (user_browser_*), so one approval covers a flow across the family’s tools. It is believed only of a trusted tool.

func WithRawArguments() Option

WithRawArguments has Run pass the model’s arguments to the tool unvalidated. Only a tool that validates them itself, against its own InputSchema, should use it.

func WithReadOnly() Option

WithReadOnly marks the tool as changing nothing.

func WithReadOnlyUnless(fields ...string) Option

WithReadOnlyUnless narrows WithReadOnlyWhen, given before it: a call that sets any of fields (to anything but null, false or “”) is never read-only, such as a Task call that makes a worktree for its child.

Example

A call is read-only for some inputs: a dry run, as long as it notifies no one.

deploy, err := tool.Define("deploy", "Deploy the service.",
func(_ context.Context, in deployInput) (tool.Result, error) {
return tool.Text("deployed to " + in.Target), nil
},
tool.WithReadOnlyWhen("target", "staging"), tool.WithReadOnlyUnless("notify"))
if err != nil {
panic(err)
}
w := deploy.Spec().ReadOnlyWhen
fmt.Println(w.Matches(json.RawMessage(`{"target":"staging"}`)))
fmt.Println(w.Matches(json.RawMessage(`{"target":"staging","notify":"ops"}`)))
fmt.Println(w.Matches(json.RawMessage(`{"target":"production"}`)))
// Output:
// true
// false
// false

Output:

true
false
false
func WithReadOnlyWhen(field string, values ...string) Option

WithReadOnlyWhen marks the tool’s calls whose input field has one of values as changing nothing, as plan mode needs to know of a call that delegates to a read-only subagent. The field must be a string.

func WithReadsPath(field string) Option

WithReadsPath declares that each call reads the file at the path in its input’s required string field and sends it on, as an upload does: the path is decided as a file tool’s is, so protected paths apply, and so do Read’s deny and ask rules, though not its allow rules. It is believed only of a trusted tool.

func WithReservation(t event.Tokens) Option

WithReservation declares that each call may spend up to t model tokens, which the call reserves from the budget before it runs.

func WithRouteReservation(reserve func(ctx context.Context, family history.Family, model string) (event.Tokens, bool, error)) Option

WithRouteReservation declares that what a call spends depends on the session’s model route, as a search through the selected model’s provider does. Each time a route is selected, reserve gives its bound, which the session records in Config.ToolReserves and each call reserves; false means calls on that route spend no model tokens. A zero bound is unknown, and a hard budget refuses it. Run refuses a call, without running it, if the route’s bound no longer matches what the call reserved. reserve must be safe for concurrent use and honour ctx.

func WithStopsProcess(handle func(json.RawMessage) string) Option

WithStopsProcess declares the handle whose wake a call withdraws before dispatch. The extractor must be deterministic, safe for concurrent use, and return an empty handle when the input does not name a process to stop.

Example

type input struct {
Handle string `json:"handle"`
}
// The host provides the implementation that stops the named process.
stop := func(_ context.Context, in input) (tool.Result, error) {
return tool.Text("Stopped " + in.Handle), nil
}
t, err := tool.Define("StopJob", "Stop a background job.", stop, tool.WithStopsProcess(func(raw json.RawMessage) string {
var in input
if err := json.Unmarshal(raw, &in); err != nil {
return ""
}
return in.Handle
}))
if err != nil {
panic(err)
}
fmt.Println(t.Descriptor().StopsProcess(json.RawMessage(`{"handle":"bg-9"}`)))
// Output: bg-9

Output:

bg-9
func WithTrustedTab(newTab string) Option

WithTrustedTab declares that each call of a tool a person decides (WithPersonDecides) acts in a tab of the user’s browser they already trusted, by sharing it or approving its opening: with a person attending, it runs without asking, and unattended only an allow rule or one of the user’s hooks lets it act. newTab, if not “”, names the input’s optional boolean field that makes a call open a new tab instead, which a rule or a person decides as before (docs/design/browser-automation.md, A13). It is believed only of a trusted tool, which must act only in tabs the user trusted.

func WithURL(field string) Option

WithURL declares that each call acts on the URL in its input’s required string field, so permission rules written with a domain, as “browser_open(domain:localhost)”, match it as they match WebFetch’s. It is believed only of a trusted tool; the tool must act only on that URL’s site, or refuse.

func WithUntrusted() Option

WithUntrusted marks the tool’s ReadOnly and Idempotent properties as claims zelk shouldn’t rely on.

func WithWritesPath(field string) Option

WithWritesPath declares that each call writes at most one file: the workspace path in its input’s string field, absolute or relative to the session’s working directory, as Write’s and Edit’s file_path. With checkpoints on, the session saves that file’s current version before the call runs, so a restore can undo it (docs/design/checkpoints.md). It is believed only of a trusted tool. A tool that may write other paths mustn’t declare it.

type Origin = event.Origin

Origin is where a tool comes from.

type Problem struct {
Path string
Message string
}

Problem is one way a value doesn’t fit a schema: where, as a JSON Pointer (“” for the whole value), and what is wrong.

type Result struct {
// Content is text and image parts. The driver admits image bytes before
// recording: an unusable image becomes a type/size text placeholder.
Content []history.Part
// IsError reports a failure the tool describes in Content. Its outcome
// is failed.
IsError bool
// FullOutput refers to the tool's complete output, stored as a blob,
// when Content holds only a bounded preview of it.
FullOutput *blob.Ref
// Usage is what the call spent on model calls of its own, within the
// tool's Reserve; nil for none.
Usage *event.Usage
}

Result is what a tool returns to the model.

func Failuref(format string, args ...any) Result

Failuref returns a failed result holding the formatted message, for failures the model should read and act on.

func Text(s string) Result

Text returns a result holding s.

type Scratcher interface {
// Scratch returns the directory, or "" if the session has none.
Scratch() string
}

Scratcher is implemented by a Call in a session that has a scratch directory (zelk.WithScratch): an absolute host path outside the workspace, shared by the root session and its subagents, where a tool may keep files the model can read back without asking, and which goes with the session.

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

Tool is a defined tool. It is immutable and safe for concurrent use.

func Define[In any](name, description string, fn func(ctx context.Context, in In) (Result, error), opts ...Option) (*Tool, error)

Define returns a tool that runs fn on arguments decoded into In. In must be a struct whose schema fits the canonical subset; see the schema tags accepted on its fields in the package documentation.

Example

weather, err := tool.Define("weather", "Look up the current weather.",
func(_ context.Context, in weatherInput) (tool.Result, error) {
return tool.Text("Sunny in " + in.City), nil
},
tool.WithReadOnly(), tool.WithIdempotent())
if err != nil {
panic(err)
}
fmt.Println(string(weather.InputSchema()))
res, _ := weather.Run(context.Background(), nil, json.RawMessage(`{"city":"Lisbon"}`))
fmt.Println(res.Content[0].Text)
_, err = weather.Run(context.Background(), nil, json.RawMessage(`{"units":"kelvin"}`))
fmt.Println(errors.Is(err, tool.ErrInvalidInput), tool.Classify(err))
// Output:
// {"type":"object","properties":{"city":{"type":"string","description":"City name."},"units":{"type":"string","enum":["metric","imperial"]}},"required":["city"],"additionalProperties":false}
// Sunny in Lisbon
// true failed

Output:

{"type":"object","properties":{"city":{"type":"string","description":"City name."},"units":{"type":"string","enum":["metric","imperial"]}},"required":["city"],"additionalProperties":false}
Sunny in Lisbon
true failed
func DefineCall[In any](name, description string, fn func(ctx context.Context, c Call, in In) (Result, error), opts ...Option) (*Tool, error)

DefineCall is Define for a tool that uses the session it runs in: its working directory and the files earlier calls read, through the Call passed to fn.

Example

defined, err := tool.DefineCall("Where", "Show the session working directory.", func(_ context.Context, c tool.Call, _ struct{}) (tool.Result, error) { return tool.Text(c.Cwd()), nil }, tool.WithReadOnly())
if err != nil {
panic(err)
}
result, err := defined.Run(context.Background(), nil, json.RawMessage(`{}`))
if err != nil {
panic(err)
}
fmt.Println(result.Content[0].Text)
// Output: .

Output:

.
func DefineOpenSchema(name, description string, inputSchema json.RawMessage, fn func(context.Context, Call, json.RawMessage) (Result, error), opts ...Option) (*Tool, error)

DefineOpenSchema defines a foreign object-root JSON Schema (draft-04 to 2020-12) contract without canonical narrowing. Run always validates it locally before dispatch, and passes arguments unchanged, including null. Providers render it non-strict. Only local fragment references resolve; no network fetch occurs. The returned tool is immutable and safe for concurrent use.

Example

tl, err := tool.DefineOpenSchema("Foreign", "Report a label.", json.RawMessage(`{"type":"object","properties":{"label":{"type":["string","null"]}},"required":["label"]}`), func(_ context.Context, _ tool.Call, input json.RawMessage) (tool.Result, error) {
return tool.Text(string(input)), nil
})
if err != nil {
panic(err)
}
result, err := tl.Run(context.Background(), nil, json.RawMessage(`{"label":null}`))
if err != nil {
panic(err)
}
fmt.Println(result.Content[0].Text)
// Output: {"label":null}

Output:

{"label":null}
func DefineSchema(name, description string, inputSchema json.RawMessage, fn func(ctx context.Context, c Call, input json.RawMessage) (Result, error), opts ...Option) (*Tool, error)

DefineSchema returns a tool whose input schema is given at run time as a JSON Schema document, such as a structured output contract, rather than derived from a Go type. The schema must fit the canonical subset; one outside it is an error, never silently weakened. Use DefineOpenSchema for a foreign contract that cannot fit the subset. fn receives the arguments as JSON, validated against the schema unless the tool is defined with RawArguments.

func (t *Tool) Descriptor() Descriptor

Descriptor returns the tool’s descriptor.

func (t *Tool) InputSchema() json.RawMessage

InputSchema returns the tool’s input contract; Descriptor reports its kind. Each call returns a new copy.

func (t *Tool) Run(ctx context.Context, c Call, input json.RawMessage) (res Result, err error)

Run validates input against the tool’s schema and runs the tool as call c; a nil c is a call in the workspace’s top directory that has seen no files, whose records are discarded. Every JSON spelling of an integer the schema accepts (1e2, 1.0, -0) reaches an integer field as that integer for canonical tools. Open-schema arguments pass through unchanged after validation, including legitimate nulls. Invalid arguments return an error wrapping ErrInvalidInput that lists every problem, and the tool doesn’t run. A panic in the tool is returned as an error wrapping ErrPanicked, with the panic value and stack, instead of crashing the host. A tool defined WithRouteReservation doesn’t run, and the error wraps ErrNotDispatched, when its route’s bound differs from what the call reserved. Use Classify on the error to learn the outcome.

func (t *Tool) Spec() event.ToolSpec

Spec returns the tool as it is recorded in a session’s configuration. Its input schema is a new copy.

func (t *Tool) Validate(input json.RawMessage) error

Validate checks input against the tool’s schema. The error, if any, is a *ValidationError listing every problem with its JSON Pointer path.

type ValidationError struct {
Problems []Problem
// Omitted counts problems beyond the listed ones.
Omitted int
}

ValidationError lists every way a value doesn’t fit a schema.

func (e *ValidationError) Error() string