tools

package
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Overview

Match the upstream session checkpoint policy for cancellation before dispatch. Return an isError result with a stable code before entering the tool body, rather than executing with partially canceled state.

Match the upstream agent loop's argument parsing: empty input becomes an empty object, valid JSON becomes its decoded value, and invalid JSON remains a string for the tool to handle. Malformed model output must not abort the whole turn at the dispatch boundary.

ToolRunContext provides runtime metadata, deferred cleanup, and turn conclusion (M25), matching upstream tools/types. ConcludeTurn is authoritative: tools such as goal report_blocker can end the current turn, and the agent checks that state before continuing. Context propagation exposes the agent-level control inside the pipeline.

The monotonic guard sits between pre-execute policy middleware and execution. Once assigned, a decision may only become stricter: deny > ask > allow. The first explicit decision may resolve the initial ask state; later updates cannot relax it. Deny is final, while allow can still be tightened to ask or deny.

The tool execution pipeline has four middleware stages (M23), matching upstream tools: pre-execute can deny or rewrite inputs; execute invokes the tool and can cancel; post-execute can block, truncate, or annotate results; result performs final wrapping and instrumentation. A denial skips execution and produces an isError result. Cancellation or post-execute blocking also marks the result as an error.

Provide a generic bounded rolling pool matching the upstream agent loop. Parallel tool calls within a step are capped by DefaultMaxParallelToolCalls. Tasks run concurrently, but their results retain the model's input order.

Opt-in tool pipeline pooling (H06) reuses ExecContext and its Meta map through sync.Pool. ToolCallResult must never be reused: callers can retain it after Run returns, so later mutation would cause races and corrupt earlier results. Copy the result to a fresh object before returning, and reset all execution fields before reuse.

Pre-execute decisions use allow, deny, and ask from pkg/approval (M22). Deny short-circuits execution with an error. Ask delegates to AskFunc, and approval permits only the current invocation; it never creates a permanent tool-name exemption. DecisionFromApproval connects the approval service's layered overrides and one-time approval handling to this pipeline stage.

Tool presentation provides a neutral vocabulary matching upstream presentation.ts (M47). Tools declare call and result cards; UIs dispatch on card type, never on tool name. Calls support generic, terminal, and diff cards; results support generic, terminal, diff, search, read, and web cards. String discriminators permit custom cards.

Programmatic tool calling bridges upstream ptc.ts without its full scheduler. The model supplies an async function body to run_code, and tools.name(args) invokes registered tools through the normal pipeline, preserving permissions, sandboxing, and guards. The injected code runtime returns logs and a completion value; only the formatted outer result enters model history. Each binding runs its pipeline synchronously; runtime backends manage any program-level concurrency.

Advisory repeat detection mirrors the upstream repeat-tool reminder. It never blocks or rewrites calls; it emits reminders when consecutive calls use the same tool and arguments. Full canonical arguments form the chain key so property-order changes do not evade detection.

Layered tool restrictions follow nearest-scope-wins semantics (M24). Search from the nearest scope toward the host; the first layer mentioning a tool decides access. A local allow can exempt a host denial, local deny remains denied, and unmentioned tools are allowed. Presets and subagents use these masks to filter available tools.

Output retention (S16) preserves canonical tool-result bytes at commit. Post-execute consumers may read large results concurrently for context, display, and auditing, so Retain stores an immutable copy keyed by ToolCallID and Read returns an independent complete copy under an RWMutex. Remove affects future reads without invalidating copies already returned.

Package tools defines tools and their execution pipeline. Its JSON Schema subset (M48) validates tool arguments and structured subagent/workflow output before execution. It supports oneOf, closed objects, items, enum, const, defaults, examples, and numeric/string/array constraints. Unsupported keywords fail at definition time rather than silently giving the model and executor different contracts.

Cooperative timeouts mirror upstream guard/timeout-policy. Tools declare TimeoutMs and must honor ctx.Done(). The wrapper returns structured TOOL_TIMEOUT only when its own timer expires. Go cannot forcibly stop a goroutine: a tool ignoring cancellation may continue in the background and leak resources after the wrapper returns.

Index

Constants

View Source
const (
	PreAllow = approval.DecideAllow
	PreDeny  = approval.DecideDeny
	PreAsk   = approval.DecideAsk
)

Decision constants share approval semantics.

View Source
const AbortedBeforeDispatch = "TOOL_ABORTED_BEFORE_DISPATCH"

AbortedBeforeDispatch is the stable code for a tool canceled before dispatch.

View Source
const AbortedBeforeDispatchMessage = "tool call aborted before dispatch"

AbortedBeforeDispatchMessage is the model-visible cancellation message.

View Source
const DefaultMaxParallelToolCalls = 10

DefaultMaxParallelToolCalls caps in-flight parallel tool calls within an agent step.

View Source
const GentleReminder = "你在以完全相同的参数重复同一工具调用。请先仔细分析上一次结果," +
	"若任务未完成,换一种方式或换一组参数,而不是重复调用。"

GentleReminder is the first-threshold reminder.

View Source
const RunCodeName = "run_code"

RunCodeName is the model-visible name of the programmatic tool-calling entry point.

View Source
const ToolTimeoutCode = "TOOL_TIMEOUT"

ToolTimeoutCode is the stable TOOL_TIMEOUT error code.

Variables

View Source
var DefaultRepeatThresholds = []int{3, 5, 8}

DefaultRepeatThresholds escalate from gentle to detailed reminders.

View Source
var ErrGuardRelaxed = errors.New("tools monotonic guard: cannot relax an already stricter decision")

ErrGuardRelaxed reports an attempt to relax an established guard decision.

View Source
var ErrToolTimeout = errors.New("tool call timed out")

ErrToolTimeout reports that a tool exceeded its declared time budget.

Functions

func Canonicalize

func Canonicalize(value any) []byte

Canonicalize converts a result value to bytes: byte slices and strings are copied, other values are JSON-encoded, and nil produces empty output.

func CanonicalizeArgs

func CanonicalizeArgs(input map[string]any) string

CanonicalizeArgs serializes arguments with recursively sorted keys.

func CardOf

func CardOf(v any) string

CardOf returns the discriminator of a call or result card; custom types can expose the same field.

func DetailedReminder

func DetailedReminder(toolName string, count int, canonical string, previewCap int) string

DetailedReminder builds the reminder for later thresholds.

func Equal

func Equal(a, b []byte) bool

Equal compares bytes for atomicity assertions.

func HitThreshold

func HitThreshold(count int, thresholds []int) bool

HitThreshold reports whether the count matches a reminder threshold.

func ParseArguments

func ParseArguments(raw string) any

ParseArguments parses the model's raw argument string.

func PreDecisionMiddleware

func PreDecisionMiddleware(decide DecisionFunc, ask AskFunc) waterfall.Handler[ExecContext]

PreDecisionMiddleware passes allowed calls through, marks denied calls as errors without execution, and delegates ask decisions to AskFunc. A successful answer allows this invocation only; rejection or failure denies it.

func RunParallel

func RunParallel[T any](ctx context.Context, tasks []func(context.Context) (T, error), maxConcurrent int) ([]T, error)

RunParallel runs tasks with at most maxConcurrent workers and returns results in input order. A task error cancels outstanding work and is returned to the caller; running tasks must cooperate with cancellation.

func WithConclude

func WithConclude(ctx context.Context, fn ConcludeFunc) context.Context

WithConclude attaches a conclusion callback to ctx.

Types

type AskFunc

type AskFunc func(req *ToolCallRequest) (bool, error)

AskFunc asks whether to allow the current invocation. A true result grants one-time permission only.

func AskFromApproval

func AskFromApproval(evaluate func(req *ToolCallRequest) (approval.Decision, error)) AskFunc

AskFromApproval adapts an approval evaluator to AskFunc. The evaluator is expected to resolve user interaction to allow or deny before returning; only allow grants execution.

type ConcludeFunc

type ConcludeFunc func(reason string)

ConcludeFunc ends the current turn and is registered by the agent.

func ConcludeFrom

func ConcludeFrom(ctx context.Context) ConcludeFunc

ConcludeFrom returns the conclusion callback, or nil if absent.

type DecisionFunc

type DecisionFunc func(req *ToolCallRequest) (PreToolDecision, error)

DecisionFunc evaluates the policy for one tool invocation.

func DecisionFromApproval

func DecisionFromApproval(decide func(req *ToolCallRequest) (approval.Decision, error)) DecisionFunc

DecisionFromApproval adapts the approval service to DecisionFunc. Service.Evaluate already resolves ask through user questions, so this adapter forwards the resolved decision without asking twice.

type DiffCallView

type DiffCallView struct {
	Card      string         `json:"card"`
	Title     string         `json:"title"`
	Diffs     []FileDiff     `json:"diffs"`
	Locations []FileLocation `json:"locations,omitempty"`
}

DiffCallView displays an inline diff for file creation or modification.

func NewDiffCallView

func NewDiffCallView(title string, diffs []FileDiff) *DiffCallView

NewDiffCallView creates a diff invocation card.

type DiffResultView

type DiffResultView struct {
	Card  string     `json:"card"`
	Title string     `json:"title,omitempty"`
	Diffs []FileDiff `json:"diffs"`
}

DiffResultView displays a completed file change.

type ExecContext

type ExecContext struct {
	// Request is the original invocation request.
	Request *ToolCallRequest
	// Result is populated by the pipeline stages.
	Result *ToolCallResult
	// Signal controls execution and may be changed by execute middleware.
	Signal Signal
	// Denied reports rejection by pre-execute or post-execute middleware.
	Denied bool
	// Meta holds display and audit metadata added by middleware.
	Meta map[string]any
	// Ctx carries the parent execution context, propagating cancellation, deadlines, and tracing to
	// tools (H01).
	Ctx context.Context
}

ExecContext carries shared state through all four pipeline stages.

func ExecContextFrom

func ExecContextFrom(ctx context.Context) (*ExecContext, bool)

ExecContextFrom retrieves execution state inside a tool implementation.

type FileDiff

type FileDiff struct {
	// Path is the file path.
	Path string `json:"path"`
	// OldText is the previous content, or nil when no prior content is available for a new file or
	// overwrite.
	OldText *string `json:"oldText,omitempty"`
	// NewText is the resulting content.
	NewText string `json:"newText"`
}

FileDiff describes a proposed single-file change for inline rendering.

type FileLocation

type FileLocation struct {
	// Path is the model-facing path operated on by the tool.
	Path string `json:"path"`
	// Line is an optional one-based focus line.
	Line int `json:"line,omitempty"`
}

FileLocation identifies a file position for editor navigation.

type GenericCallView

type GenericCallView struct {
	Card      string         `json:"card"`
	Title     string         `json:"title"`
	Kind      ToolCallKind   `json:"kind,omitempty"`
	RawInput  any            `json:"rawInput,omitempty"`
	Content   []any          `json:"content,omitempty"`
	Locations []FileLocation `json:"locations,omitempty"`
}

GenericCallView provides a title with optional category, highlighted input, extra content, and location.

func NewGenericCallView

func NewGenericCallView(title string) *GenericCallView

NewGenericCallView creates a generic invocation card.

type GenericResultView

type GenericResultView struct {
	Card    string `json:"card"`
	Title   string `json:"title,omitempty"`
	Content []any  `json:"content,omitempty"`
}

GenericResultView is the default completion card.

func NewGenericResultView

func NewGenericResultView() *GenericResultView

NewGenericResultView creates a generic result card.

type JsonSchemaNode

type JsonSchemaNode struct {
	// Type declares the node's value type.
	Type SchemaType `json:"type,omitempty"`

	// Description explains the field to the model.
	Description string `json:"description,omitempty"`

	// Properties maps object property names to child schemas.
	Properties map[string]*JsonSchemaNode `json:"properties,omitempty"`

	// Required lists mandatory object properties.
	Required []string `json:"required,omitempty"`

	// AdditionalProperties controls undeclared object fields. Nil allows them by default; false
	// rejects them in strict mode.
	AdditionalProperties *bool `json:"additionalProperties,omitempty"`

	// Items specifies the array-element schema.
	Items *JsonSchemaNode `json:"items,omitempty"`

	// Enum restricts values to this list and takes precedence over Const when both are set.
	Enum []any `json:"enum,omitempty"`

	// Const restricts the value to an exact constant.
	Const any `json:"const,omitempty"`

	// Default suggests a value to the model without affecting validation.
	Default any `json:"default,omitempty"`

	// Examples provides model-facing examples without affecting validation.
	Examples []any `json:"examples,omitempty"`

	// OneOf accepts a value matching any child schema in this subset.
	OneOf []*JsonSchemaNode `json:"oneOf,omitempty"`

	// Number and integer constraints.
	Minimum          *float64 `json:"minimum,omitempty"`
	Maximum          *float64 `json:"maximum,omitempty"`
	ExclusiveMinimum *bool    `json:"exclusiveMinimum,omitempty"`
	ExclusiveMaximum *bool    `json:"exclusiveMaximum,omitempty"`

	// String constraints.
	MinLength *int   `json:"minLength,omitempty"`
	MaxLength *int   `json:"maxLength,omitempty"`
	Pattern   string `json:"pattern,omitempty"`

	// Array constraints.
	MinItems *int `json:"minItems,omitempty"`
	MaxItems *int `json:"maxItems,omitempty"`
}

JsonSchemaNode represents the validated DefineTool schema subset, aligned with the upstream tool-definition fields.

func Compile

func Compile(raw []byte) (*JsonSchemaNode, error)

Compile parses a schema and rejects unsupported keywords. Use it when defining tools so unknown constraints fail closed.

func Infer

func Infer(v any) (*JsonSchemaNode, error)

Infer derives a schema from primitive values, slices, maps, and structs, matching the upstream INFER capability. Unsupported types return an error.

func (*JsonSchemaNode) Marshal

func (n *JsonSchemaNode) Marshal() ([]byte, error)

Marshal produces deterministic JSON Schema with ordered properties, required fields, and enum values.

func (*JsonSchemaNode) Validate

func (n *JsonSchemaNode) Validate(v any) error

Validate returns nil when a Go value satisfies the schema.

type MonotonicGuard

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

MonotonicGuard converges policy decisions for a single tool call.

func NewMonotonicGuard

func NewMonotonicGuard() *MonotonicGuard

NewMonotonicGuard creates an unassigned guard with ask semantics.

func (*MonotonicGuard) Decision

func (g *MonotonicGuard) Decision() PreToolDecision

Decision returns the current guard decision.

func (*MonotonicGuard) IsDenied

func (g *MonotonicGuard) IsDenied() bool

IsDenied reports a fail-closed denial.

func (*MonotonicGuard) Update

func (g *MonotonicGuard) Update(next PreToolDecision) error

Update accepts the first assignment and subsequent decisions with an equal or higher strictness rank. Attempts to relax the decision return ErrGuardRelaxed without changing the existing decision.

type Pipeline

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

Pipeline implements the four-stage tool execution chain.

func NewPipeline

func NewPipeline() *Pipeline

NewPipeline creates an empty pipeline whose stages accept middleware.

func (*Pipeline) Lookup

func (p *Pipeline) Lookup(name string) *Tool

Lookup resolves a tool registered during pipeline construction.

func (*Pipeline) PooledState

func (p *Pipeline) PooledState() bool

PooledState reports whether pooling is enabled for diagnostics and tests.

func (*Pipeline) Run

func (p *Pipeline) Run(ctx context.Context, req *ToolCallRequest, tool *Tool) *ToolCallResult

Run executes one invocation through all four stages and returns its result. When pooling is enabled, RunPooled provides equivalent semantics while reusing internal state.

func (*Pipeline) RunPooled

func (p *Pipeline) RunPooled(ctx context.Context, req *ToolCallRequest, tool *Tool) *ToolCallResult

RunPooled preserves Run semantics while reusing ExecContext and Meta to reduce allocation pressure. It returns a fresh result that callers may retain or modify.

func (*Pipeline) SetPooled

func (p *Pipeline) SetPooled(enabled bool) *Pipeline

SetPooled enables opt-in ExecContext and Meta-map reuse to reduce allocations. Results remain separately allocated and safe for callers to retain.

func (*Pipeline) Tools

func (p *Pipeline) Tools() []*Tool

Tools returns registered tools in stable name order for model requests.

func (*Pipeline) UseExecute

func (p *Pipeline) UseExecute(h ...waterfall.Handler[ExecContext]) *Pipeline

UseExecute appends middleware wrapping tool execution and its signal.

func (*Pipeline) UsePost

func (p *Pipeline) UsePost(h ...waterfall.Handler[ExecContext]) *Pipeline

UsePost appends middleware that can accept, block, truncate, or annotate results.

func (*Pipeline) UsePre

func (p *Pipeline) UsePre(h ...waterfall.Handler[ExecContext]) *Pipeline

UsePre appends middleware that can inspect, rewrite, or deny inputs.

func (*Pipeline) UseResult

func (p *Pipeline) UseResult(h ...waterfall.Handler[ExecContext]) *Pipeline

UseResult appends final-result middleware.

func (*Pipeline) WithTool

func (p *Pipeline) WithTool(tool *Tool) *Pipeline

WithTool copies the pipeline and appends the tool's execute stage.

type PreToolDecision

type PreToolDecision = approval.Decision

PreToolDecision is the three-state policy decision for a tool invocation.

type ReadFileLine

type ReadFileLine struct {
	Number int    `json:"number"`
	Text   string `json:"text"`
}

ReadFileLine contains one file line and its one-based line number.

type ReadResultView

type ReadResultView struct {
	Card       string         `json:"card"`
	Title      string         `json:"title,omitempty"`
	Path       string         `json:"path"`
	Offset     int            `json:"offset"`
	Lines      []ReadFileLine `json:"lines"`
	TotalLines int            `json:"totalLines"`
	Lang       string         `json:"lang,omitempty"`
	Content    []any          `json:"content,omitempty"`
}

ReadResultView displays file content with line numbers.

func NewReadResultView

func NewReadResultView(path string, offset int, lines []ReadFileLine, totalLines int) *ReadResultView

NewReadResultView creates a file-read result card.

type RepeatState

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

RepeatState tracks one agent's consecutive repeated calls.

func (*RepeatState) Observe

func (r *RepeatState) Observe(toolName string, args map[string]any) int

Observe records a call and returns its consecutive repetition count; a different call resets the count to one.

func (*RepeatState) Reset

func (r *RepeatState) Reset()

Reset clears the chain after user input so repetitions across interruptions do not count as loops.

type Restriction

type Restriction struct {
	// Allow contains explicitly exempted tool names.
	Allow []string `json:"allow,omitempty"`
	// Deny contains explicitly rejected tool names.
	Deny []string `json:"deny,omitempty"`
}

Restriction is one layer of tool-access policy. Allow explicitly exempts a tool from outer denials; Deny explicitly rejects it.

func RestrictionAllow

func RestrictionAllow(names ...string) Restriction

RestrictionAllow creates a mask containing only explicit allowances.

func RestrictionDeny

func RestrictionDeny(names ...string) Restriction

RestrictionDeny creates a mask containing only explicit denials.

type RestrictionLayer

type RestrictionLayer struct {
	// Key identifies the scope for auditing, such as host, session:xxx, user:xxx, or subagent:xxx.
	Key string
	// Mask contains this layer's policy.
	Mask Restriction
}

RestrictionLayer associates a policy mask with a scope name.

type RestrictionSet

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

RestrictionSet stores an ordered stack of tool-access masks.

func NewRestrictionSet

func NewRestrictionSet() *RestrictionSet

NewRestrictionSet creates an empty restriction stack.

func (*RestrictionSet) Allowed

func (rs *RestrictionSet) Allowed(tool string) bool

Allowed searches from the nearest scope toward the host. The first layer mentioning the tool determines access: Allow grants an exemption and Deny rejects. Tools absent from all layers are allowed.

func (*RestrictionSet) Denied

func (rs *RestrictionSet) Denied(tool string) bool

Denied negates Allowed for auditing and assertions.

func (*RestrictionSet) Filter

func (rs *RestrictionSet) Filter(tools []*Tool) []*Tool

Filter returns allowed tools in their original order for preset filtering and subagent restrictions.

func (*RestrictionSet) Host

func (rs *RestrictionSet) Host(mask Restriction)

Host sets the outermost host policy.

func (*RestrictionSet) Layers

func (rs *RestrictionSet) Layers() []RestrictionLayer

Layers returns a shallow copy of the host-to-nearest stack for auditing and tests.

func (*RestrictionSet) Scope

func (rs *RestrictionSet) Scope(key string, mask Restriction)

Scope appends the nearest policy layer, taking precedence over all existing layers. Keys typically use session:xxx, user:xxx, or subagent:xxx.

func (*RestrictionSet) SetLayer

func (rs *RestrictionSet) SetLayer(key string, mask Restriction)

SetLayer adds or updates a named layer, moving an existing layer to the nearest position.

type ResultRetention

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

ResultRetention stores canonical tool-result values for concurrent readers.

func NewResultRetention

func NewResultRetention() *ResultRetention

NewResultRetention creates an empty retention store.

func (*ResultRetention) Len

func (r *ResultRetention) Len() int

Len returns the number of entries currently retained for diagnostics.

func (*ResultRetention) Read

func (r *ResultRetention) Read(callID string) ([]byte, bool)

Read returns an independent complete copy, or nil, false when the entry is absent or no longer retained.

func (*ResultRetention) Remove

func (r *ResultRetention) Remove(callID string)

Remove deletes a retained entry without affecting copies already returned.

func (*ResultRetention) Retain

func (r *ResultRetention) Retain(callID string, value []byte)

Retain copies canonical bytes at commit. Repeated writes for the same call ID use the latest value.

func (*ResultRetention) RetainResult

func (r *ResultRetention) RetainResult(res *ToolCallResult)

RetainResult stores the canonical value from a ToolCallResult.

type RetainedEntry

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

RetainedEntry stores immutable raw bytes and a logical-presence flag.

type RunCodeInput

type RunCodeInput struct {
	// Code is an async function body supporting top-level await and return.
	Code string `json:"code"`
	// Description is a short active-voice summary of the program.
	Description string `json:"description"`
}

RunCodeInput contains run_code arguments.

type RunCodeOutput

type RunCodeOutput struct {
	Logs   []string `json:"logs"`
	Result any      `json:"result,omitempty"`
}

RunCodeOutput is the structured run_code result.

func PresentRunCodeResult

func PresentRunCodeResult(res *coderuntime.RunResult) RunCodeOutput

PresentRunCodeResult concatenates ordered logs and the completion value into model-visible text.

type SchemaType

type SchemaType string

SchemaType names a supported JSON Schema type.

const (
	TypeString  SchemaType = "string"
	TypeNumber  SchemaType = "number"
	TypeInteger SchemaType = "integer"
	TypeBoolean SchemaType = "boolean"
	TypeArray   SchemaType = "array"
	TypeObject  SchemaType = "object"
	TypeNull    SchemaType = "null"
)

Supported JSON Schema types.

type SearchFileMatches

type SearchFileMatches struct {
	Path    string            `json:"path"`
	Matches []SearchLineMatch `json:"matches"`
}

SearchFileMatches groups matches by file.

type SearchLineMatch

type SearchLineMatch struct {
	LineNumber int    `json:"lineNumber"`
	Line       string `json:"line"`
}

SearchLineMatch describes one matching line in a file.

type SearchResultView

type SearchResultView struct {
	Card      string              `json:"card"`
	Shape     string              `json:"shape"` // "matches" | "paths"
	Title     string              `json:"title,omitempty"`
	Files     []SearchFileMatches `json:"files,omitempty"`
	Paths     []string            `json:"paths,omitempty"`
	Truncated bool                `json:"truncated"`
	Total     int                 `json:"total"`
}

SearchResultView displays matches or matching paths.

func NewSearchMatchesView

func NewSearchMatchesView(files []SearchFileMatches, truncated bool, total int) *SearchResultView

NewSearchMatchesView creates a result card with matches grouped by file.

func NewSearchPathsView

func NewSearchPathsView(paths []string, truncated bool, total int) *SearchResultView

NewSearchPathsView creates a result card containing a flat path list.

type Signal

type Signal string

Signal controls tool execution.

const (
	// SignalContinue allows execution to continue.
	SignalContinue Signal = "continue"
	// SignalCancel cancels execution and may be set by execute middleware.
	SignalCancel Signal = "cancel"
)

Supported execution signals.

type TerminalCallView

type TerminalCallView struct {
	Card        string `json:"card"`
	Title       string `json:"title"`
	Description string `json:"description,omitempty"`
	Cwd         string `json:"cwd,omitempty"`
}

TerminalCallView displays a terminal command with its working directory as the header.

func NewTerminalCallView

func NewTerminalCallView(command string) *TerminalCallView

NewTerminalCallView creates a terminal invocation card.

type TerminalResultView

type TerminalResultView struct {
	Card     string `json:"card"`
	Title    string `json:"title,omitempty"`
	Output   string `json:"output,omitempty"`
	ExitCode *int   `json:"exitCode,omitempty"`
	Signal   string `json:"signal,omitempty"`
}

TerminalResultView describes terminal-command completion.

func NewTerminalResultView

func NewTerminalResultView(output string) *TerminalResultView

NewTerminalResultView creates a terminal result card.

type TimeoutError

type TimeoutError struct {
	Code   string
	Budget time.Duration
	Cause  error
}

TimeoutError carries TOOL_TIMEOUT for retry and sandbox routing.

func (*TimeoutError) Error

func (e *TimeoutError) Error() string

Error implements error.

func (*TimeoutError) Unwrap

func (e *TimeoutError) Unwrap() error

Unwrap supports errors.Is and errors.As.

type Tool

type Tool struct {
	// Name is the model-visible tool name.
	Name string
	// Description describes the tool in the prompt.
	Description string
	// Schema describes and validates tool arguments.
	Schema *JsonSchemaNode
	// TimeoutMs is a cooperative time budget; zero is unlimited. Tools must honor ctx, and deadline
	// expiry maps to TOOL_TIMEOUT.
	TimeoutMs int
	// Execute is the tool implementation.
	Execute ToolExecuteFunc
}

Tool defines a tool's name, schema, and implementation.

func NewRunCodeTool

func NewRunCodeTool(runtime coderuntime.Runtime, lookup ToolLookup, pipeline *Pipeline) *Tool

NewRunCodeTool creates the run_code bridge using an injected code runtime and tool lookup. Each programmatic call runs through pipeline; nil selects a minimal pipeline containing only the tool implementation.

type ToolCallKind

type ToolCallKind string

ToolCallKind selects a UI icon or style; other is the default.

const (
	CallKindRead    ToolCallKind = "read"
	CallKindEdit    ToolCallKind = "edit"
	CallKindDelete  ToolCallKind = "delete"
	CallKindMove    ToolCallKind = "move"
	CallKindSearch  ToolCallKind = "search"
	CallKindExecute ToolCallKind = "execute"
	CallKindFetch   ToolCallKind = "fetch"
	CallKindOther   ToolCallKind = "other"
)

Supported tool-call categories.

type ToolCallRequest

type ToolCallRequest struct {
	// CallID pairs tool/call with tool/result.
	CallID brand.ToolCallID
	// Tool is the tool name.
	Tool string
	// Input contains parsed arguments.
	Input map[string]any
}

ToolCallRequest describes one tool invocation.

type ToolCallResult

type ToolCallResult struct {
	// CallID pairs this result with its request.
	CallID brand.ToolCallID
	// IsError reports denial, blocking, cancellation, or a tool execution error.
	IsError bool
	// Value is the structured result.
	Value any
	// Error describes a failure when IsError is true.
	Error string
	// ErrorCode is an optional stable code for routing and replay.
	ErrorCode string
}

ToolCallResult holds the outcome of a tool invocation.

func AbortedBeforeDispatchResult

func AbortedBeforeDispatchResult(callID brand.ToolCallID) *ToolCallResult

AbortedBeforeDispatchResult constructs a pre-dispatch cancellation result.

type ToolCallView

type ToolCallView interface {
	// contains filtered or unexported methods
}

ToolCallView describes a pending invocation using a card discriminator.

type ToolExecuteFunc

type ToolExecuteFunc func(ctx context.Context, input map[string]any) (any, error)

ToolExecuteFunc implements a tool's execution function.

func WrapTimeout

func WrapTimeout(exec ToolExecuteFunc, timeoutMs int) ToolExecuteFunc

WrapTimeout applies timeoutMs to an execution function; nonpositive values leave it unchanged.

type ToolLookup

type ToolLookup func(name string) (*Tool, bool)

ToolLookup resolves registered tools by name for program bindings.

type ToolResultView

type ToolResultView interface {
	// contains filtered or unexported methods
}

ToolResultView describes a completed invocation using a card discriminator. Search supports matches and paths; web supports search and fetch variants.

type ToolRunContext

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

ToolRunContext holds runtime state for one tool execution.

func NewToolRunContext

func NewToolRunContext(conclude ConcludeFunc) *ToolRunContext

NewToolRunContext creates a tool runtime context.

func ToolRunContextFrom

func ToolRunContextFrom(ctx context.Context) (*ToolRunContext, bool)

ToolRunContextFrom retrieves ToolRunContext from ctx.

func (*ToolRunContext) ConcludeTurn

func (tc *ToolRunContext) ConcludeTurn(reason string) bool

ConcludeTurn marks the current turn as concluded and runs deferred callbacks. Repeated calls do not invoke the conclusion callback again.

func (*ToolRunContext) Context

func (tc *ToolRunContext) Context() context.Context

Context returns a context carrying this ToolRunContext for tool implementations.

func (*ToolRunContext) DeferContext

func (tc *ToolRunContext) DeferContext(fn func())

DeferContext registers cleanup to run when the tool finishes, like Go defer.

func (*ToolRunContext) GetMeta

func (tc *ToolRunContext) GetMeta(k string) (any, bool)

GetMeta reads runtime metadata.

func (*ToolRunContext) IsConcluded

func (tc *ToolRunContext) IsConcluded() bool

IsConcluded reports whether the agent should stop advancing the turn.

func (*ToolRunContext) SetMeta

func (tc *ToolRunContext) SetMeta(k string, v any)

SetMeta stores runtime metadata.

type WebResultView

type WebResultView struct {
	Card       string      `json:"card"`
	Kind       string      `json:"kind"` // "search" | "fetch"
	Title      string      `json:"title,omitempty"`
	Sources    []WebSource `json:"sources,omitempty"`
	Answer     string      `json:"answer,omitempty"`
	URL        string      `json:"url,omitempty"`
	StatusCode int         `json:"statusCode,omitempty"`
	Truncated  bool        `json:"truncated"`
}

WebResultView displays completed web search or fetch results.

func NewWebFetchResultView

func NewWebFetchResultView(url string, statusCode int, truncated bool) *WebResultView

NewWebFetchResultView creates a web-fetch result card.

func NewWebSearchResultView

func NewWebSearchResultView(sources []WebSource, answer string, truncated bool) *WebResultView

NewWebSearchResultView creates a web-search result card.

type WebSource

type WebSource struct {
	URL         string `json:"url"`
	Title       string `json:"title,omitempty"`
	Snippet     string `json:"snippet,omitempty"`
	PublishedAt string `json:"publishedAt,omitempty"`
}

WebSource identifies a citable web-search source.

Jump to

Keyboard shortcuts

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