tool

package
v0.60.0 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2026 License: Apache-2.0 Imports: 18 Imported by: 0

Documentation

Overview

Package tool defines the provider-neutral executable Tool protocol, its immutable Contract and execution Binding, authorization boundary, typed typed signature, function adapter, and instance-scoped registry. Bind freezes the definition once; CallMiddleware decorates execution without becoming a second owner of the tool's schema or capabilities.

Invocation carries the driver's Admission explicitly: the idempotency key of the logical call and any continuation input. Result completes a call or requests external input; neither identity nor suspension travels through context or an error. The driving runtime owns call identity, checkpoint commitment, input waits, and routing each answer back to the requesting call. Func adapts ordinary typed functions of their arguments; Tools that need the call's identity or a Continuation implement Tool around a Signature.

Failure owns a complete unsuccessful invocation outcome. CallError instead carries observed evidence through an ordinary error without declaring an outcome or retry policy; its evidence is not a model-visible ToolResult. Effect declares replay safety independently of concurrency: a replayable tool can still require serialized execution. A safe call's error is a definite Failure unless its execution was canceled.

Example
package main

import (
	"context"
	"fmt"

	"github.com/Tangerg/scope/core/tool"
)

func main() {
	type input struct {
		A int `json:"a"`
		B int `json:"b"`
	}
	add, err := tool.NewFunc(tool.FuncConfig{
		Name:        "add",
		Description: "add two integers",
	}, func(_ context.Context, value input) (int, error) {
		return value.A + value.B, nil
	})
	if err != nil {
		panic(err)
	}
	bound, err := tool.Bind(add)
	if err != nil {
		panic(err)
	}
	registry, err := tool.NewRegistry(bound)
	if err != nil {
		panic(err)
	}

	fmt.Println(registry.Definitions()[0].Name)
	binding, ok := registry.Resolve("add")
	if !ok {
		panic("missing add")
	}
	invocation, err := binding.Contract().Prepare(tool.Request{Name: "add", Arguments: `{"a":2,"b":3}`}, tool.Admission{})
	if err != nil {
		panic(err)
	}
	result, err := binding.Call(context.Background(), invocation)
	if err != nil {
		panic(err)
	}
	text, _ := result.Output.Text()
	fmt.Println(text)
}
Output:
add
5

Index

Examples

Constants

View Source
const MaxInputBytes = 1 << 20

Variables

View Source
var (
	ErrDuplicateTool   = errors.New("tool: duplicate tool")
	ErrInvalidRegistry = errors.New("tool: invalid registry")
)
View Source
var (
	ErrInvalidTool       = errors.New("tool: invalid tool")
	ErrInvalidInvocation = errors.New("tool: invalid invocation")
)
View Source
var ErrInvalidCallError = errors.New("tool: invalid call error")
View Source
var ErrInvalidDefinition = errors.New("tool: invalid definition")
View Source
var ErrInvalidFailure = errors.New("tool: invalid failure")
View Source
var ErrInvalidInputRejection = errors.New("tool: invalid input rejection")
View Source
var ErrInvalidInputRequest = errors.New("tool: invalid input request")
View Source
var ErrInvalidOutput = errors.New("tool: invalid output")
View Source
var ErrInvalidProgress = errors.New("tool: invalid progress")
View Source
var ErrInvalidRequest = errors.New("tool: invalid request")
View Source
var ErrInvalidResult = errors.New("tool: invalid result")

Functions

func ReportProgress added in v0.60.0

func ReportProgress(ctx context.Context, progress Progress) error

ReportProgress forwards progress to the observer the driver installed. It is a no-op when the driver observes none, so a Tool reports unconditionally.

func WithProgressReporter added in v0.60.0

func WithProgressReporter(ctx context.Context, reporter ProgressReporter) context.Context

WithProgressReporter installs the driver's observer for calls made with the returned context. Progress is observation, like a trace span, so it travels with the context; the Invocation stays a value that retains no driver capability and can be handed to scheduling policies.

Types

type Admission added in v0.60.0

type Admission struct {
	IdempotencyKey IdempotencyKey
	// Continuation answers the InputRequest committed by this same logical
	// call; nil starts a new call.
	Continuation *Continuation
}

Admission is what the driving runtime, never the proposer, asserts about one call. It is separate from Request because a model can forge arguments but must not be able to choose the identity external systems deduplicate on.

type Authorization

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

Authorization carries only the frozen model-visible contract and validated arguments, so policy code cannot bypass Contract validation or execute the invocation.

func (Authorization) Arguments

func (a Authorization) Arguments() []byte

Arguments is detached for the same reason as Definition.

func (Authorization) Definition

func (a Authorization) Definition() Definition

Definition is detached because policy implementations may retain or annotate what they inspect without changing the executable contract.

type AuthorizationError added in v0.23.0

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

AuthorizationError means the policy could not establish a decision for the current invocation. The Tool was not executed. Its internal cause is not the Tool's outcome, public output, input request, or execution cancellation. Guard separately preserves cancellation of the execution context.

func (*AuthorizationError) Cause added in v0.23.0

func (a *AuthorizationError) Cause() error

Cause retains the policy diagnostic without exposing it through Error, errors.Is, or errors.As. Callers must explicitly choose to inspect it.

func (*AuthorizationError) Error added in v0.23.0

func (a *AuthorizationError) Error() string

type Authorizer

type Authorizer interface {
	Authorize(ctx context.Context, authorization Authorization) (bool, error)
}

Authorizer is deliberately smaller than an application permission system: identity, consent, tenancy, and policy storage remain caller-owned context. A nil error establishes a decision: true permits execution, false refuses it. Any error means the decision could not be completed; its boolean is ignored. The Tool never executes after refusal or an authorization error. Guard seals policy errors in AuthorizationError; only cancellation of the execution context itself remains an errors.Is-visible control signal.

type AuthorizerFunc

type AuthorizerFunc func(context.Context, Authorization) (bool, error)

func (AuthorizerFunc) Authorize

func (a AuthorizerFunc) Authorize(ctx context.Context, authorization Authorization) (bool, error)

type Binding

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

Binding associates one immutable Contract with the Tool that executes it. Calls may run concurrently when the underlying Tool supports concurrent use.

func Bind

func Bind(executable Tool, middlewares ...CallMiddleware) (Binding, error)

Bind freezes and validates executable. Definition is read exactly once.

func (Binding) Call

func (b Binding) Call(ctx context.Context, invocation Invocation) (Result, error)

Call executes an Invocation prepared by this Binding's exact Contract. It rejects another binding's contract even when the public Tool name matches.

func (Binding) Contract added in v0.19.0

func (b Binding) Contract() Contract

Contract returns the exact frozen contract used to prepare this Binding's invocations. Retaining it does not retain the executable Tool.

type CallError added in v0.38.0

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

CallError preserves evidence that would otherwise be lost when a Tool returns an error. Evidence is available for diagnostics and evaluation; it is not a completed result and must not be submitted to a model as a ToolResult.

CallError assigns no outcome or control meaning. Its transparent cause retains the original error contract; only Failure establishes a definite unsuccessful outcome. Runtimes must not infer retry safety from the presence of evidence.

func NewCallError added in v0.38.0

func NewCallError(config CallErrorConfig) (*CallError, error)

func (*CallError) Error added in v0.38.0

func (c *CallError) Error() string

func (*CallError) Evidence added in v0.38.0

func (c *CallError) Evidence() Output

Evidence returns an independent snapshot of observations made before the error. Missing observations do not prove that effects did not occur.

func (*CallError) Unwrap added in v0.38.0

func (c *CallError) Unwrap() error

func (*CallError) Validate added in v0.38.0

func (c *CallError) Validate() error

type CallErrorConfig added in v0.38.0

type CallErrorConfig struct {
	Cause    error
	Evidence Output
}

CallErrorConfig attaches observed execution evidence to an error. Evidence may acknowledge effects without establishing the invocation's final outcome.

type CallMiddleware added in v0.60.0

type CallMiddleware func(Caller) Caller

CallMiddleware may reject or synchronously forward an invocation once. It preserves invocation identity and cannot manufacture a continuation. A middleware that adds business effects needs a new Tool contract; transparent composition cannot inherit replay guarantees for additional external work. Bind invokes the factory for each call, so it must be concurrency-safe and leave the lifetime of shared resources with its constructor or host.

type Caller added in v0.60.0

type Caller interface {
	Call(context.Context, Invocation) (Result, error)
}

Caller executes one admitted invocation. A completed result is not replaced by cancellation observed after execution; ordinary errors prove no outcome.

type CallerFunc added in v0.60.0

type CallerFunc func(context.Context, Invocation) (Result, error)

func (CallerFunc) Call added in v0.60.0

func (c CallerFunc) Call(ctx context.Context, invocation Invocation) (Result, error)

type Continuation added in v0.54.0

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

Continuation is the immutable checkpoint and validated answer for one logical call. Passing a context does not pass this business input.

func (Continuation) Response added in v0.54.0

func (c Continuation) Response() json.RawMessage

func (Continuation) State added in v0.54.0

func (c Continuation) State() json.RawMessage

type Contract added in v0.19.0

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

Contract is the immutable trust boundary from an untrusted Request to an Invocation. It retains the frozen definition, compiled schema, and input validator without retaining an executable Tool. It is safe for concurrent use independently of the Tool.

func (Contract) Definition added in v0.19.0

func (c Contract) Definition() Definition

Definition projects an independent snapshot of the frozen definition from its single schema owner. InputSchema is the compiled Schema's canonical JSON, so the exposed definition and the enforced contract never disagree on bytes.

func (Contract) Effect added in v0.60.0

func (c Contract) Effect() Effect

func (Contract) Name added in v0.59.0

func (c Contract) Name() string

Name identifies the frozen execution target without copying its schema.

func (Contract) Prepare added in v0.19.0

func (c Contract) Prepare(call Request, admission Admission) (Invocation, error)

Prepare validates identity, RFC 7493 JSON syntax, the frozen input schema, and its independent input validator. It does not invoke the executable Tool or authorization policy. The invocation's arguments are the Request's Input. A driving runtime may supply a Continuation only for the same call that produced its committed InputRequest.

func (Contract) ValidateResult added in v0.60.0

func (c Contract) ValidateResult(result Result) error

ValidateResult applies the same frozen output contract during live execution and recovery without retaining an executable Tool. A request for input has no completed output yet; failed-call diagnostics are not successful Results.

type Definition added in v0.59.0

type Definition struct {
	Name         string          `json:"name"`
	Description  string          `json:"description,omitempty"`
	InputSchema  json.RawMessage `json:"input_schema"`
	OutputSchema json.RawMessage `json:"output_schema,omitzero"`
	Effect       Effect          `json:"effect,omitzero"`
}

Definition describes a tool independently of any model naming or transport convention.

func (Definition) Clone added in v0.59.0

func (d Definition) Clone() Definition

func (Definition) JSONSchemaModel added in v0.59.0

func (Definition) JSONSchemaModel() any

func (Definition) MarshalJSON added in v0.59.0

func (d Definition) MarshalJSON() ([]byte, error)

func (*Definition) UnmarshalJSON added in v0.59.0

func (d *Definition) UnmarshalJSON(data []byte) error

func (Definition) Validate added in v0.59.0

func (d Definition) Validate() error

type Effect added in v0.60.0

type Effect string

Effect is a replay promise, independent of concurrency and the outcome of a particular call. Idempotent requires durable backend deduplication under the same nonzero IdempotencyKey, including intervening calls; assigning a value twice is not sufficient. Safe calls request no mutation of application state; incidental accounting and telemetry do not authorize repeated business effects.

const (
	EffectUnsafe     Effect = ""
	EffectIdempotent Effect = "idempotent"
	EffectSafe       Effect = "safe"
)

func (Effect) Replayable added in v0.60.0

func (e Effect) Replayable() bool

func (Effect) Valid added in v0.60.0

func (e Effect) Valid() bool

type Failure added in v0.17.0

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

Failure owns one complete unsuccessful outcome of the current Tool invocation. Output is explicitly public to the model. Cause is diagnostic only: it cannot change Kind, substitute another invocation's output, or issue a control signal. Ordinary errors, including CallError with execution evidence, do not establish a definite outcome.

func ClassifyFailure added in v0.58.0

func ClassifyFailure(err error) (*Failure, bool)

ClassifyFailure finds the complete outcome of the current invocation. Transparent wrapping preserves one Failure, but joined independent errors require their enclosing owner to establish an outcome. Diagnostic traversal with errors.As cannot distinguish those invocation boundaries. Nil, invalid, and ambiguous failures establish no definite outcome.

func NewFailure added in v0.17.0

func NewFailure(config FailureConfig) (*Failure, error)

NewFailure snapshots public output. Failed outcomes require a cause; rejection may be a policy decision without an error. Wrapping the returned Failure with %w preserves its outcome; inspect Cause explicitly for internal diagnostics.

Example
package main

import (
	"errors"
	"fmt"

	"github.com/Tangerg/scope/core/tool"
)

func main() {
	failure, err := tool.NewFailure(tool.FailureConfig{
		Kind: tool.FailureKindRejected, Cause: errors.New("internal authorization diagnostic"),
		Output: tool.NewTextOutput("this operation is not permitted"),
	})
	if err != nil {
		panic(err)
	}
	wrapped := fmt.Errorf("tool call: %w", failure)
	result, found := tool.ClassifyFailure(wrapped)
	if !found {
		panic("missing definite outcome")
	}
	text, _ := result.Output().Text()
	fmt.Println(result.Kind(), text)
	fmt.Println(errors.Is(wrapped, result.Cause()))
}
Output:
rejected this operation is not permitted
false

func (*Failure) Cause added in v0.23.0

func (f *Failure) Cause() error

Cause does not participate in errors.Is or errors.As. Transparent error wrapping surrounds Failure; diagnostic causes are behind the outcome boundary.

func (*Failure) Error added in v0.17.0

func (f *Failure) Error() string

func (*Failure) Kind added in v0.23.0

func (f *Failure) Kind() FailureKind

func (*Failure) Output added in v0.17.0

func (f *Failure) Output() Output

Output returns an independent copy of the complete failure output.

func (*Failure) Validate added in v0.23.0

func (f *Failure) Validate() error

Validate rejects zero and typed-nil values crossing a Tool boundary.

type FailureConfig added in v0.23.0

type FailureConfig struct {
	Kind   FailureKind
	Output Output
	Cause  error
}

FailureConfig describes one unsuccessful invocation. NewFailure snapshots Output and retains Cause only for explicit diagnostic inspection.

type FailureKind added in v0.23.0

type FailureKind string

FailureKind describes the current invocation, independently of its diagnostic cause. Neither kind assigns retry or runtime control policy.

const (
	// FailureKindFailed is a definite unsuccessful outcome. It does not assert
	// that execution began and may describe acknowledged partial effects.
	FailureKindFailed FailureKind = "failed"
	// FailureKindRejected means the invocation was refused permission to execute.
	FailureKindRejected FailureKind = "rejected"
)

type Func

type Func[In, Out any] struct {
	// contains filtered or unexported fields
}

Func composes a Signature with a function of the call's arguments. A Tool whose effect depends on the call itself, such as one deduplicating on its IdempotencyKey or resuming a Continuation, implements Tool around a Signature instead, because those facts belong to the Invocation.

func NewFunc

func NewFunc[In, Out any](config FuncConfig, function func(context.Context, In) (Out, error)) (Func[In, Out], error)

func (Func[In, Out]) Call

func (f Func[In, Out]) Call(ctx context.Context, invocation Invocation) (Result, error)

func (Func[In, Out]) Definition

func (f Func[In, Out]) Definition() Definition

func (Func[In, Out]) InputValidator added in v0.19.0

func (f Func[In, Out]) InputValidator() func([]byte) error

type FuncConfig

type FuncConfig struct {
	Name        string
	Description string
	Effect      Effect
}

type Guard

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

Guard keeps authorization at the universal Tool.Call boundary, which makes the same policy work for direct calls, registries, and managed runtimes. Refusal produces a generic FailureKindRejected result. A Tool that owns more specific public feedback uses NewFailure at its own invocation boundary.

func NewGuard

func NewGuard(config GuardConfig) (Guard, error)
Example
package main

import (
	"context"
	"fmt"

	"github.com/Tangerg/scope/core/tool"
)

func main() {
	executable, err := tool.NewFunc(tool.FuncConfig{Name: "inspect"}, func(context.Context, struct{}) (string, error) {
		return "inspected", nil
	})
	if err != nil {
		panic(err)
	}
	guard, err := tool.NewGuard(tool.GuardConfig{
		Authorizer: tool.AuthorizerFunc(func(context.Context, tool.Authorization) (bool, error) {
			return false, nil
		}),
	})
	if err != nil {
		panic(err)
	}
	binding, err := tool.Bind(executable, guard.Call)
	if err != nil {
		panic(err)
	}
	invocation, err := binding.Contract().Prepare(tool.Request{Name: "inspect", Arguments: `{}`}, tool.Admission{})
	if err != nil {
		panic(err)
	}
	_, err = binding.Call(context.Background(), invocation)
	failure, found := tool.ClassifyFailure(err)
	if !found {
		panic(err)
	}
	fmt.Println(failure.Kind())
}
Output:
rejected

func (Guard) Call

func (g Guard) Call(next Caller) Caller

type GuardConfig

type GuardConfig struct {
	Authorizer Authorizer
}

type IdempotencyKey added in v0.60.0

type IdempotencyKey string

IdempotencyKey names one logical call across its replays and continuations, so a backend with external effects can deduplicate them. It is opaque: a Tool may forward it to third parties, so it never encodes runtime structure. The zero value means the caller has no durable identity for the call.

type InputRejection added in v0.60.0

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

InputRejection declares model-correctable input with an explicitly public message. Cause is diagnostic only and cannot supply a different rejection, execution outcome, or control signal through errors.Is or errors.As.

func ClassifyInputRejection added in v0.60.0

func ClassifyInputRejection(err error) (*InputRejection, bool)

ClassifyInputRejection finds one explicit rejection through transparent wrapping. Joined independent errors require their owner to decide which message is public; private diagnostic causes are never inspected.

func NewInputRejection added in v0.60.0

func NewInputRejection(config InputRejectionConfig) (*InputRejection, error)

func (*InputRejection) Cause added in v0.60.0

func (i *InputRejection) Cause() error

func (*InputRejection) Error added in v0.60.0

func (i *InputRejection) Error() string

func (*InputRejection) Is added in v0.60.0

func (i *InputRejection) Is(target error) bool

func (*InputRejection) Message added in v0.60.0

func (i *InputRejection) Message() string

func (*InputRejection) Validate added in v0.60.0

func (i *InputRejection) Validate() error

type InputRejectionConfig added in v0.60.0

type InputRejectionConfig struct {
	Message string
	Cause   error
}

type InputRequest added in v0.54.0

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

InputRequest freezes the prompt, answer contract, and Tool-owned checkpoint. The driving runtime binds it to one logical call and owns its wait identity.

func NewInputRequest added in v0.54.0

func NewInputRequest(config InputRequestConfig) (InputRequest, error)

NewInputRequest validates and freezes a re-entry checkpoint. A Tool must request input before external effects, or retain enough state for safe re-entry.

Example
package main

import (
	"fmt"

	"github.com/Tangerg/scope/core/jsonschema"
	"github.com/Tangerg/scope/core/tool"
)

func main() {
	schema, err := jsonschema.Parse([]byte(`{"type":"boolean"}`))
	if err != nil {
		panic(err)
	}
	request, err := tool.NewInputRequest(tool.InputRequestConfig{
		Prompt: []byte(`"Approve the write?"`), ResponseSchema: schema, ContinuationState: []byte(`{"record":"draft"}`),
	})
	if err != nil {
		panic(err)
	}
	result := tool.Result{InputRequest: &request}
	continuation, err := result.InputRequest.Continuation([]byte(`true`))
	if err != nil {
		panic(err)
	}
	// The runtime persists the checkpoint and routes this answer to the same
	// call through binding.Contract().Prepare(call, tool.Admission{Continuation: &continuation}).
	fmt.Println(string(continuation.State()), string(continuation.Response()))
}
Output:
{"record":"draft"} true

func (InputRequest) Continuation added in v0.54.0

func (i InputRequest) Continuation(response json.RawMessage) (Continuation, error)

Continuation validates an answer against this exact request and freezes the state and answer to pass explicitly to Contract.Prepare for the same call.

func (InputRequest) JSONSchemaModel added in v0.57.0

func (InputRequest) JSONSchemaModel() any

func (InputRequest) MarshalJSON added in v0.54.0

func (i InputRequest) MarshalJSON() ([]byte, error)

func (InputRequest) Prompt added in v0.54.0

func (i InputRequest) Prompt() json.RawMessage

func (InputRequest) ResponseSchema added in v0.54.0

func (i InputRequest) ResponseSchema() jsonschema.Schema

func (InputRequest) State added in v0.54.0

func (i InputRequest) State() json.RawMessage

func (*InputRequest) UnmarshalJSON added in v0.54.0

func (i *InputRequest) UnmarshalJSON(data []byte) error

func (InputRequest) Valid added in v0.54.0

func (i InputRequest) Valid() bool

type InputRequestConfig added in v0.54.0

type InputRequestConfig struct {
	Prompt            json.RawMessage
	ResponseSchema    jsonschema.Schema
	ContinuationState json.RawMessage
}

type InputValidatingTool added in v0.19.0

type InputValidatingTool interface {
	// InputValidator returns an independent, immutable validator. Neither the
	// returned function nor anything it captures may retain an executable Tool
	// or execution backend. It must be deterministic, bounded, side-effect-free,
	// safe for concurrent use, and must not mutate or retain its argument.
	// Return an InputRejection only for model-correctable input. Its Message is
	// public; ordinary errors and panics are internal validator defects.
	// Nil means the schema is the complete input admission contract.
	InputValidator() func([]byte) error
}

InputValidatingTool supplies the input admission rules that JSON Schema cannot express, such as Go numeric syntax or a custom JSON decoder's domain constraints. Bind captures the declaration directly from the executable before composing middleware.

type InputValidationError added in v0.60.0

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

InputValidationError contains a defect in an input validator. It carries no public input correction or execution outcome. Inspect Cause explicitly for diagnostics, including a contained InputValidationPanicError.

func (*InputValidationError) Cause added in v0.60.0

func (i *InputValidationError) Cause() error

func (*InputValidationError) Error added in v0.60.0

func (*InputValidationError) Error() string

type InputValidationPanicError added in v0.32.0

type InputValidationPanicError struct{ Value any }

InputValidationPanicError identifies a contained panic while declaring or running input validation. It is retained only behind InputValidationError.Cause; this diagnostic cannot turn a panic into public input rejection or execution evidence. Value retains the recovered value; an error value remains available through Unwrap.

func (*InputValidationPanicError) Error added in v0.32.0

func (i *InputValidationPanicError) Error() string

func (*InputValidationPanicError) Unwrap added in v0.32.0

func (i *InputValidationPanicError) Unwrap() error

type Invocation

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

Invocation is a complete JSON object admitted by one exact frozen Tool contract. Its fields are intentionally private: only Contract.Prepare can promote an untrusted model proposal into an executable invocation.

func (Invocation) Arguments

func (i Invocation) Arguments() []byte

Arguments returns an owned copy of the validated JSON object.

func (Invocation) Continuation added in v0.54.0

func (i Invocation) Continuation() (Continuation, bool)

func (Invocation) Definition added in v0.60.0

func (i Invocation) Definition() Definition

func (Invocation) IdempotencyKey added in v0.60.0

func (i Invocation) IdempotencyKey() IdempotencyKey

type Output added in v0.59.0

type Output struct {
	Content []corecontent.Block `json:"content,omitempty"`
	Details json.RawMessage     `json:"details,omitzero"`
}

Output is the provider-neutral value produced by a Tool. Content is the model-visible ordered text/media representation. Details is optional JSON for structured consumers; providers use its encoded JSON as the model-visible fallback only when Content is empty.

func NewJSONOutput added in v0.59.0

func NewJSONOutput(value json.RawMessage) (Output, error)

NewJSONOutput returns a structured output whose exact JSON encoding is preserved. The value must be one complete RFC 7493 JSON document.

func NewTextOutput added in v0.59.0

func NewTextOutput(text string) Output

NewTextOutput returns a text output. Empty text is represented by the valid zero Output rather than an invalid empty text Part.

func (Output) Clone added in v0.59.0

func (o Output) Clone() Output

func (Output) JSONSchemaModel added in v0.59.0

func (Output) JSONSchemaModel() any

func (Output) MarshalJSON added in v0.59.0

func (o Output) MarshalJSON() ([]byte, error)

func (Output) Text added in v0.59.0

func (o Output) Text() (string, bool)

Text returns the lossless text projection used by providers whose tool result protocol accepts only strings. It reports false when Content contains media so adapters cannot silently discard it. Details is encoded only when Content is empty.

func (*Output) UnmarshalJSON added in v0.59.0

func (o *Output) UnmarshalJSON(data []byte) error

func (Output) Validate added in v0.59.0

func (o Output) Validate() error

type Progress added in v0.60.0

type Progress struct {
	Completed float64 `json:"completed"`
	Total     float64 `json:"total,omitzero"`
	Message   string  `json:"message,omitzero"`
}

Progress reports how far one call has advanced. Total is zero when the Tool cannot bound its work.

func (Progress) Validate added in v0.60.0

func (p Progress) Validate() error

type ProgressReporter added in v0.60.0

type ProgressReporter interface {
	ReportProgress(ctx context.Context, progress Progress) error
}

ProgressReporter delivers a call's Progress to the driver that asked for it. Progress is observation only: it never changes the call's outcome.

type ProgressReporterFunc added in v0.60.0

type ProgressReporterFunc func(ctx context.Context, progress Progress) error

func (ProgressReporterFunc) ReportProgress added in v0.60.0

func (p ProgressReporterFunc) ReportProgress(ctx context.Context, progress Progress) error

type Registry

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

Registry is concurrency-safe with a usable zero value. Registration is atomic for the full batch and snapshots definitions; model-visible views are detached and ordered by name.

func NewRegistry

func NewRegistry(initial ...Binding) (*Registry, error)

func (*Registry) Definitions

func (r *Registry) Definitions() []Definition

func (*Registry) Register

func (r *Registry) Register(values ...Binding) error

func (*Registry) Resolve

func (r *Registry) Resolve(name string) (Binding, bool)

type Request added in v0.59.0

type Request struct {
	Name      string
	Arguments string
}

Request is an untrusted proposal. A provider correlation ID belongs to its transport; execution requires admission by the exact frozen Contract.

func (Request) Input added in v0.60.0

func (r Request) Input() []byte

Input is the JSON document the arguments denote. Providers send blank arguments for a call without parameters; blank denotes the empty object.

func (Request) Validate added in v0.59.0

func (r Request) Validate() error

type Result added in v0.54.0

type Result struct {
	Output       Output
	InputRequest *InputRequest
}

Result is either a completed output or a request for external input. An input request carries no completed output. Errors describe execution failure, never suspension; the runtime alone owns committing and resuming a logical call. The zero result completes with an empty output.

func (Result) Validate added in v0.54.0

func (r Result) Validate() error

type Signature added in v0.60.0

type Signature[In, Out any] struct {
	// contains filtered or unexported fields
}

Signature owns the typed codec and both of its schema projections. Custom decoders must be deterministic, bounded and free of external effects because admission uses the same decoder before execution. Admission of a typed input is that strict decode followed by the input's own Validate method when it declares one, so a request type states its domain rules once. Validate must explicitly return an InputRejection for model-correctable input; other errors are internal defects. Output bypasses the JSON codec to preserve media. Strings are text-only outputs and declare no Details schema; other values encode into Details under the reflected output schema. The declared output type selects the codec once, so interface values cannot change the advertised output contract at runtime.

func NewSignature added in v0.60.0

func NewSignature[In, Out any]() (Signature[In, Out], error)

func (Signature[In, Out]) Decode added in v0.60.0

func (s Signature[In, Out]) Decode(invocation Invocation) (In, error)

func (Signature[In, Out]) Encode added in v0.60.0

func (s Signature[In, Out]) Encode(output Out) (Output, error)

func (Signature[In, Out]) InputSchema added in v0.60.0

func (s Signature[In, Out]) InputSchema() json.RawMessage

func (Signature[In, Out]) InputValidator added in v0.60.0

func (Signature[In, Out]) InputValidator() func([]byte) error

func (Signature[In, Out]) OutputSchema added in v0.60.0

func (s Signature[In, Out]) OutputSchema() json.RawMessage

type Tool

type Tool interface {
	Caller
	// Definition returns a detached, valid schema snapshot. Callers may expose or
	// mutate the returned value without changing subsequent calls or execution.
	Definition() Definition
}

Tool executes invocations admitted by its exact frozen Contract. Errors carry no retry, pause, or abort policy; the driving runtime owns those decisions.

Jump to

Keyboard shortcuts

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