Documentation
¶
Overview ¶
Package toolsy provides a type-safe engine for building and executing LLM-callable tools.
Overview ¶
Pipeline: Go typed handler + args struct -> NewTypedTool -> Registry.View -> Session.RunCall. Input JSON is validated against generated schema, policy runs before handlers, and results are returned as ToolOutcome values. Low-level Execute remains available for streaming adapters and transport glue that need direct Chunk handling.
Runtime contracts ¶
- Tool interface: Manifest() ToolManifest Execute(ctx, run, input, yield)
- ToolCall carries Input ToolInput (CallID + ArgsJSON + Attachments).
- Chunk data-plane: Event, Data, MimeType, IsError, Progress.
- Chunk control-plane: EventControl + typed ControlSignal (Pause/Yield/Halt/HostEvent).
- ToolManifest SSOT: ReadOnly, RequiresConfirmation, Dangerous, Idempotent, CompletionPolicy.
- Session: in-memory state via SetSessionState/GetSessionState; ExportSnapshot/ImportSnapshot; StateCodecRegistry for typed snapshot roundtrips (see docs/migration-task28.md and docs/adr/adr-task28-hardening.md).
- RunCall + ToolOutcome + DecodeOutcomeAs: sync aggregation; business errors in ExecutionError (Error-as-Value).
- ValidateManifestContract + ManifestSet: declarative contract checks without Registry.Build.
- NewTypedTool, NewDynamicToolFromSpec, ManifestSet, ToolRequirements.
- RunEnv: Put/Require/Lookup (deps); SetState/GetState delegate to bound Session; NewRunEnv(session, opts...); session may be nil for DI-only usage.
- ToolError: structured errors with Code and Retryable (replaces ClientError/SystemError).
- CallParser + DecodeChunkAs for typed host integration (see docs/migration-task28.md).
- Registry runtime is immutable; use RegistryBuilder for setup-time mutation.
- AsAsyncTool: register via RegistryBuilder.Use(...).Add(AsAsyncTool(base)).Build() so global middleware runs inside the background goroutine (unwrap-wrap in Build). Nested AsAsyncTool layers anywhere in the tool chain are rejected at Build (walk uses ChainUnwrapper; external middleware before Add must implement it). Default background chunk buffer cap is DefaultMaxCollectedChunks (1000); see WithMaxCollectedChunks and ErrAsyncCollectedLimitExceeded.
Use Extractor when you only need schema generation/validation. Use NewDynamicToolFromSpec or NewProxyTool for runtime schemas (OpenAPI, MCP, etc.). Output schemas validate successful JSON wire values before delivery/persistence. Use historycodec for raw transcripts with explicit delivery metadata, ResultCodec for complete typed replay, and textprocessor for standalone UTF-8 text truncation. JSON output must never be sliced as text.
Example ¶
The primary synchronous host path is typed tool + registry view + RunCall.
type Args struct { City string `json:"city" jsonschema:"City name"` }
type Out struct { Temp float64 `json:"temp"` }
type Subject struct { ID string }
type Scope struct { Workspace string }
tool, _ := toolsy.NewTypedTool(toolsy.TypedToolSpec[Subject, Scope, Args, Out, struct{}]{
Name: "weather",
Description: "Get weather",
Handler: func(_ context.Context, _ toolsy.TypedCallContext[Subject, Scope], _ *toolsy.RunEnv, a toolsy.ValidatedArgs[Args]) (toolsy.ToolResult[Out, struct{}], error) {
return toolsy.NewToolResult[Out, struct{}](Out{Temp: 22.5}), nil
},
})
reg, _ := toolsy.NewRegistryBuilder().Add(tool).Build()
view, _ := reg.View(toolsy.RegistryViewSpec{
ToolNames: []string{"weather"},
RequiredToolNames: []string{"weather"},
})
sess, _ := view.NewSession()
call := toolsy.ToolCall{
ToolName: "weather",
Input: toolsy.ToolInput{CallID: "1", ArgsJSON: []byte(`{"city":"Moscow"}`)},
Env: toolsy.NewRunEnv(sess),
CallContext: toolsy.NewCallContext(
Subject{ID: "user-1"},
Scope{Workspace: "default"},
),
}
outcome, err := sess.RunCall(ctx, call)
if err != nil { /* infrastructure */ }
if outcome.ExecutionError != nil { /* business — toolsy.AsToolError */ }
result, err := toolsy.DecodeOutcomeAs[Out](outcome)
Index ¶
- Constants
- Variables
- func ClientCorrectable(code ErrorCode) bool
- func ControlErrorFromSignal(sig ControlSignal) error
- func DecodeChunkAs[T any](c Chunk) (*T, error)
- func DecodeChunkAsText(c Chunk) (string, error)
- func DecodeOutcomeAs[T any](o ToolOutcome) (*T, error)
- func DecodeOutcomeEffectsAs[T any](o ToolOutcome) ([]T, error)
- func ErrorChunkSummaryText(c Chunk, execErr error) string
- func ExecutePrepared(ctx context.Context, env *RunEnv, manifest ToolManifest, input ToolInput, ...) error
- func GetSessionState[T any](s *Session, key string) (T, bool)
- func GetState[T any](env *RunEnv, key string) (T, bool)
- func IsContextInterrupt(err error) bool
- func IsControlError(err error) bool
- func Lookup[T any](env *RunEnv, key string) (T, bool)
- func MapReadLimitError(err error, maxBytes int) error
- func MapReadLimitErrorFor(err error, maxBytes int, subject string, hint string) error
- func MapSandboxReadLimitError(err error) error
- func MapToolkitCapError(ctx context.Context, op string, maxBytes int, subject, hint string) error
- func MapToolkitReadError(ctx context.Context, err error, op string, maxBytes int, subject, hint string) error
- func ParseExactlyOne[T any](parts []ContentPart, toolName string) (*T, error)
- func Put[T any](env *RunEnv, key string, val T) error
- func ReconcileOperation(ctx context.Context, store OperationStore, binding OperationBinding, ...) error
- func RegisterJSONCodec[T any](r *StateCodecRegistry, key string, opts ...StateSlotOption) error
- func RegisterStateCodec[T any](r *StateCodecRegistry, key string, codec StateCodec[T], ...) error
- func Require[T any](env *RunEnv, key string) (T, error)
- func SetSessionState[T any](s *Session, key string, val T) error
- func SetState[T any](env *RunEnv, key string, val T) error
- func ToolkitContextError(ctx context.Context, op string) error
- func ValidateManifestContract(ms ManifestSet, requiredNames []string) error
- func ValidateRunEnvSession(session *Session, env *RunEnv) error
- func ValidateRunPolicy(p RunPolicy) error
- func YieldControl(yield func(Chunk) error, sig ControlSignal) error
- type ApprovalChallenge
- type ApprovalGrant
- type ApprovalIssuerStore
- type ArgValidator
- type ArgsBindRequest
- type ArgsBinder
- type AsyncAccepted
- type AsyncCallback
- type AsyncOption
- type Attachment
- type Authorizer
- type AuthorizerFunc
- type BudgetTracker
- type CacheEligibility
- type CachePartition
- type CallContext
- type CallContextOption
- type CallMetadata
- type CallParser
- type ChainUnwrapper
- type Chunk
- type ClaimResult
- type CompletionPolicy
- type ContentPart
- type ControlSignal
- type CredentialsProvider
- type Decision
- type DynamicToolSpec
- type EffectValidator
- type ErrorCode
- type EventType
- type ExecutionProfile
- type ExecutionSummary
- type Extractor
- type HaltSignal
- type HostEventSignal
- type InputAdmitter
- type InvocationHandler
- type JSONResultCodec
- type JSONStateCodec
- type ManifestSet
- type MapSchemaProvider
- type MemoryAccess
- type MemoryOperationStore
- func (s *MemoryOperationStore) Claim(ctx context.Context, claim OperationClaim) (ClaimResult, error)
- func (s *MemoryOperationStore) Finish(ctx context.Context, finish OperationFinish) error
- func (s *MemoryOperationStore) Inspect(ctx context.Context, binding OperationBinding) (OperationRecord, bool, error)
- func (s *MemoryOperationStore) PutGrant(ctx context.Context, grant ApprovalGrant) error
- func (s *MemoryOperationStore) Resolve(ctx context.Context, resolution OperationResolution) error
- func (s *MemoryOperationStore) Snapshot() OperationSnapshot
- type MemoryResultCacheStore
- type Middleware
- type NoScope
- type NoSubject
- type OperationBinding
- type OperationClaim
- type OperationError
- type OperationFinish
- type OperationIntent
- type OperationOutcomeError
- type OperationProfile
- type OperationProfileConfig
- type OperationReconciler
- type OperationRecord
- type OperationResolution
- type OperationSnapshot
- type OperationState
- type OperationStateError
- type OperationStore
- type OperationStoreError
- type OutcomeStatus
- type OverrideOption
- type PauseSignal
- type PendingApprovalError
- type Permission
- type Policy
- type PolicyFunc
- type PolicyRequest
- type PostconditionValidator
- type PrepareOperation
- type PreparedCall
- type PreparedExecutionTool
- type ProgressInfo
- type ReconciliationDecision
- type ReconciliationError
- type Registry
- func (r *Registry) Execute(ctx context.Context, call ToolCall, yield func(Chunk) error) error
- func (r *Registry) ExecuteBatchStream(ctx context.Context, calls []ToolCall, yield func(Chunk) error) error
- func (r *Registry) ExecuteIter(ctx context.Context, call ToolCall) iter.Seq2[Chunk, error]
- func (r *Registry) GetAllTools() []Tool
- func (r *Registry) GetTool(name string) (Tool, bool)
- func (r *Registry) Has(name string) bool
- func (r *Registry) ManifestSet() (ManifestSet, error)
- func (r *Registry) RestoreView(snapshot RegistryViewSnapshot, policy Policy, policyID ...string) (*RegistryView, error)
- func (r *Registry) Shutdown(ctx context.Context) error
- func (r *Registry) Subset(allowedNames ...string) (*Registry, error)
- func (r *Registry) ToolNames() []string
- func (r *Registry) View(spec RegistryViewSpec) (*RegistryView, error)
- type RegistryBuilder
- type RegistryOption
- func WithExecutionProfile(profile ExecutionProfile) RegistryOption
- func WithOnAfterExecute(fn func(context.Context, ToolCall, ExecutionSummary, time.Duration)) RegistryOption
- func WithOnBeforeExecute(fn func(context.Context, ToolCall)) RegistryOption
- func WithOnChunk(fn func(context.Context, Chunk)) RegistryOption
- func WithPolicy(policyID string, p Policy) RegistryOption
- func WithRecoverPanics(enable bool) RegistryOption
- func WithRequirementsPolicy[TSubject, TScope any](policyID string, fn RequirementsDecisionFunc[TSubject, TScope]) RegistryOption
- func WithValidator(v Validator) RegistryOption
- func WithValidatorFromRegistry(provider RegistryProvider, delegate func(*Registry) Validator) RegistryOption
- type RegistryProvider
- type RegistryView
- func (v *RegistryView) Execute(ctx context.Context, call ToolCall, yield func(Chunk) error) error
- func (v *RegistryView) ExecuteIter(ctx context.Context, call ToolCall) iter.Seq2[Chunk, error]
- func (v *RegistryView) ManifestSet() (ManifestSet, error)
- func (v *RegistryView) NewSession(opts ...SessionOption) (*Session, error)
- func (v *RegistryView) NewSessionFromCheckpoint(checkpoint SessionCheckpoint, opts ...SessionOption) (*Session, error)
- func (v *RegistryView) RebindSession(s *Session) error
- func (v *RegistryView) Shutdown(ctx context.Context) error
- func (v *RegistryView) Snapshot() RegistryViewSnapshot
- func (v *RegistryView) ToolNames() []string
- func (v *RegistryView) ValidateManifestContract(requiredNames []string) error
- type RegistryViewSnapshot
- type RegistryViewSpec
- type RequirementsDecisionFunc
- type RequirementsPolicyRequest
- type ResultCache
- type ResultCacheStore
- type ResultCodec
- type ResultContractError
- type ResultValidator
- type RunEnv
- type RunEnvOption
- type RunPolicy
- type SchemaConfig
- type SchemaProvider
- type SchemaRegistry
- type Session
- func (s *Session) Binding() SessionBinding
- func (s *Session) Execute(ctx context.Context, call ToolCall, yield func(Chunk) error) error
- func (s *Session) ExecuteIter(ctx context.Context, call ToolCall) iter.Seq2[Chunk, error]
- func (s *Session) ExportCheckpoint() (SessionCheckpoint, error)
- func (s *Session) ExportSnapshot() (SessionSnapshot, error)
- func (s *Session) ImportSnapshot(snap SessionSnapshot) error
- func (s *Session) Rebind(reg *Registry) error
- func (s *Session) RunCall(ctx context.Context, call ToolCall) (ToolOutcome, error)
- func (s *Session) Track() *SessionTrack
- type SessionBinding
- type SessionCheckpoint
- type SessionOption
- type SessionSnapshot
- type SessionTrack
- type StandardCallParser
- type StateCodec
- type StateCodecRegistry
- type StateSlotOption
- type StateSlotPolicy
- type StateStore
- type StreamContractError
- type StreamSemantics
- type Tool
- func AsAsyncTool(baseTool Tool, opts ...AsyncOption) Tool
- func NewDynamicToolFromSpec(spec DynamicToolSpec) (Tool, error)
- func NewPolicyTool[TSubject, TScope, TArgs any](spec ToolPolicySpec[TSubject, TScope, TArgs]) (Tool, error)
- func NewPolicyToolFromSpec[TSubject, TScope, TArgs any](spec ToolPolicyConstructorSpec[TSubject, TScope, TArgs]) (Tool, error)
- func NewProxyTool(name, description string, rawJSONSchema []byte, ...) (Tool, error)
- func NewStreamTool[T any](name, description string, ...) (Tool, error)
- func NewTool[T any, R any](name, description string, ...) (Tool, error)
- func NewTypedTool[TSubject, TScope, TArgs, TResult, TEffect any](spec TypedToolSpec[TSubject, TScope, TArgs, TResult, TEffect]) (Tool, error)
- func OverrideTool(base Tool, opts ...OverrideOption) Tool
- type ToolAudience
- type ToolCall
- type ToolConfig
- type ToolDeliveryClass
- type ToolEnvelope
- type ToolEnvelopeKind
- type ToolError
- func AsToolError(err error) (*ToolError, bool)
- func NewBudgetExceededError(reason string) *ToolError
- func NewCapabilityDeniedError(toolName string, view RegistryViewSnapshot) *ToolError
- func NewDependencyMissingError(key string) *ToolError
- func NewInternalError(err error) *ToolError
- func NewJSONParseError(err error) *ToolError
- func NewMaxCallsExceededError() *ToolError
- func NewPolicyDeniedError(reason string, fixableArgs ...string) *ToolError
- func NewPolicyDeniedErrorFrom(err error) *ToolError
- func NewRegistryStateError() *ToolError
- func NewSchemaError(reason string) *ToolError
- func NewShutdownError() *ToolError
- func NewSnapshotHydrationError(reason string, err error) *ToolError
- func NewStateCodecMissingError(key string) *ToolError
- func NewTimeoutError(retryable bool) *ToolError
- func NewTimeoutErrorFrom(cause error, retryable bool) *ToolError
- func NewToolNotFoundError() *ToolError
- func NewToolNotFoundInSubsetError(name string) *ToolError
- func NewToolsContractMissingError(required, missing []string) *ToolError
- func NewValidationError(reason string, fixableFields ...string) *ToolError
- func WithSafeMessage(te *ToolError, safe string) *ToolError
- type ToolInput
- type ToolManifest
- type ToolOption
- func WithCompletionPolicy(policy CompletionPolicy) ToolOption
- func WithDangerous() ToolOption
- func WithIdempotent() ToolOption
- func WithIndependentStream() ToolOption
- func WithOutputSchema(schema map[string]any) ToolOption
- func WithReadOnly() ToolOption
- func WithRequirements(req ToolRequirements) ToolOption
- func WithRequiresConfirmation() ToolOption
- func WithSchemaRegistry(r *SchemaRegistry) ToolOption
- func WithStrict() ToolOption
- func WithTags(tags ...string) ToolOption
- func WithTerminalStream(maxBytes int) ToolOption
- func WithVersion(version string) ToolOption
- type ToolOutcome
- type ToolPolicyConstructorSpec
- type ToolPolicySpec
- type ToolRequirements
- type ToolResult
- type TruncationOption
- type TypedCallContext
- type TypedPolicy
- type TypedPolicyRequest
- type TypedToolSpec
- type Validatable
- type ValidatedArgs
- type Validator
- type WireJSONResult
- type YieldSignal
Examples ¶
Constants ¶
const ( ContentTypeText = "text" ContentTypeToolCall = "tool_call" )
Content type constants for ContentPart.Type.
const ( // ReplaySourceCache denotes reuse of a result under current host freshness policy. ReplaySourceCache = "result_cache" // ReplaySourceOperation denotes delivery of an already completed logical operation. ReplaySourceOperation = "completed_operation" )
const ( MimeTypeText = "text/plain; charset=utf-8" MimeTypeJSON = "application/json" MimeTypeOctetStream = "application/octet-stream" MimeTypePNG = "image/png" MimeTypeJPEG = "image/jpeg" )
MIME type constants for Chunk payloads.
const DefaultMaxCollectedChunks = 1000
DefaultMaxCollectedChunks is the default cap on chunks buffered during async background execution.
const DepKeyBudget = "toolsy.budget"
DepKeyBudget is the dependency map key for BudgetTracker used by WithBudget.
const MaxControlBytes = 64 * 1024
MaxControlBytes bounds the sum of text/name/payload field bytes per control and per result control list. It is a delivery contract, not a producer allocation cap.
const MaxControlSignals = 64
MaxControlSignals bounds controls declared on one terminal result.
const MaxHostEventNameBytes = 128
MaxHostEventNameBytes bounds a host event's ASCII routing name.
const MimeTypeToolErrorJSON = "application/vnd.toolsy.tool-error+json"
MimeTypeToolErrorJSON carries a structured ToolError envelope in error result chunks.
const ReplaySourceMetadata = "toolsy.replay_source"
ReplaySourceMetadata identifies library replay provenance. Reducers must not apply replayed effect declarations again; current call correlation is retained.
Variables ¶
var ( ErrPause = errors.New("toolsy: control pause") ErrYield = errors.New("toolsy: control yield") ErrHalt = errors.New("toolsy: control halt") ErrHostEvent = errors.New("toolsy: control host event") )
Control errors are not tool execution failures; middleware must pass them through unchanged.
var ( ErrToolNotFound = errors.New("tool not found") ErrTimeout = errors.New("tool execution timeout") ErrValidation = errors.New("validation failed") ErrShutdown = errors.New("registry is shutting down") ErrRegistryState = errors.New("registry runtime state is not initialized") ErrStreamAborted = errors.New("stream aborted by caller") ErrMaxCallsExceeded = errors.New("maximum session calls exceeded") // ErrAsyncCollectedLimitExceeded is returned when background chunk collection exceeds WithMaxCollectedChunks. ErrAsyncCollectedLimitExceeded = errors.New("toolsy: async collected chunks limit exceeded") ErrBudgetExceeded = errors.New("budget exceeded") )
Sentinel errors for toolsy. Use errors.Is to check.
var ErrBudgetConfiguration = errors.New("toolsy: invalid budget configuration")
ErrBudgetConfiguration identifies a missing or malformed required budget gate.
var ErrCapabilityDenied = errors.New("capability denied")
ErrCapabilityDenied is the sentinel for view/capability denial.
var ErrInputAdmissionUnsupported = errors.New("toolsy: unsupported input admission")
ErrInputAdmissionUnsupported identifies tools without a separate input boundary, including opaque custom wrappers and invalid or excessive native wrapper chains.
var ErrMutationConfiguration = errors.New("toolsy: invalid mutation configuration")
ErrMutationConfiguration identifies an unusable target or key for required mutation.
var ErrOperationProfileConfiguration = errors.New("toolsy: invalid operation profile configuration")
ErrOperationProfileConfiguration identifies invalid operation-profile setup.
var ErrPolicyConfiguration = errors.New("toolsy: invalid policy configuration")
ErrPolicyConfiguration identifies an explicitly installed invalid policy gate.
var ErrPolicyDenied = errors.New("policy denied")
ErrPolicyDenied is the sentinel for fail-closed policy/capability denial.
var ErrStateCodecRegistryFrozen = errors.New("toolsy: state codec registry is frozen")
ErrStateCodecRegistryFrozen reports registration attempted after schema finalization.
var ErrToolHandlerNil = errors.New("toolsy: tool handler must not be nil")
ErrToolHandlerNil identifies a nil handler rejected during tool construction.
Functions ¶
func ClientCorrectable ¶ added in v0.8.0
ClientCorrectable reports whether the error code is correctable by the caller (LLM/agent).
Returns true for SCHEMA_INVALID, VALIDATION_FAILED, and TOOL_NOT_FOUND — the LLM can fix arguments or pick another tool. Returns false for orchestrator/host issues such as DEPENDENCY_MISSING, TOOLS_CONTRACT_MISSING, INTERNAL, TIMEOUT, SHUTDOWN, MAX_CALLS_EXCEEDED, and REGISTRY_NOT_READY; route those by comparing ToolError.Code explicitly.
Example:
te, ok := AsToolError(err)
if !ok {
return handleUnexpected(err)
}
switch {
case ClientCorrectable(te.Code):
return retryWithLLMFix(te)
case te.Code == CodeTimeout && te.Retryable:
return retryLater()
case te.Code == CodeToolsContractMissing:
return registerMissingTools(te.FixableArgs)
default:
return escalate(te)
}
func ControlErrorFromSignal ¶ added in v0.7.0
func ControlErrorFromSignal(sig ControlSignal) error
ControlErrorFromSignal maps a control signal to its sentinel error for Execute return values.
func DecodeChunkAs ¶ added in v0.8.0
DecodeChunkAs unmarshals a JSON result chunk into T after validating event and mime type.
func DecodeChunkAsText ¶ added in v0.8.0
DecodeChunkAsText returns plain-text payload from a result chunk.
func DecodeOutcomeAs ¶ added in v0.10.0
func DecodeOutcomeAs[T any](o ToolOutcome) (*T, error)
DecodeOutcomeAs unmarshals a successful outcome result into T.
func DecodeOutcomeEffectsAs ¶ added in v0.12.0
func DecodeOutcomeEffectsAs[T any](o ToolOutcome) ([]T, error)
DecodeOutcomeEffectsAs returns typed host effects from an outcome.
func ErrorChunkSummaryText ¶ added in v0.10.1
ErrorChunkSummaryText returns a short human-readable summary of an error result chunk. Error chunks are normalized first so callers (logging, otel) see the same text as delivered wire.
func ExecutePrepared ¶ added in v0.16.0
func ExecutePrepared( ctx context.Context, env *RunEnv, manifest ToolManifest, input ToolInput, canonicalArgs any, handler func(ToolInput, func(Chunk) error) error, yield func(Chunk) error, ) error
ExecutePrepared is the boundary used by custom tools after their binding and authorization. The continuation receives a private copy of canonical input.
func GetSessionState ¶ added in v0.8.1
GetSessionState returns an in-memory value when present and non-nil. The map is synchronized; referenced pointers/maps/slices remain host-owned and aliased. The caller must synchronize or keep those values immutable.
func GetState ¶ added in v0.8.0
GetState returns session-scoped data from the bound Session when present and non-nil.
func IsContextInterrupt ¶ added in v0.11.2
IsContextInterrupt reports whether err is or wraps a context cancel, deadline, or ErrTimeout.
func IsControlError ¶ added in v0.7.0
IsControlError reports whether err is a control-plane signal error. Diagnostic control causes inside known contract/outcome failures are not signals.
func MapReadLimitError ¶ added in v0.11.2
MapReadLimitError maps textprocessor.ErrReadLimitExceeded to CodeValidationFailed for LLM-facing tools. When maxBytes > 0, Reason includes the limit; otherwise a generic message is used. If maxBytes is 0, textprocessor.ReadLimitMaxBytes scans the unwrap chain for "exceeds N byte limit".
func MapReadLimitErrorFor ¶ added in v0.11.2
MapReadLimitErrorFor maps textprocessor.ErrReadLimitExceeded to CodeValidationFailed with a domain-specific subject. Optional hint is appended after the limit message (e.g. "use WithMaxPageBytes to raise the budget").
func MapSandboxReadLimitError ¶ added in v0.11.2
MapSandboxReadLimitError maps sandbox textprocessor.ErrReadLimitExceeded chains to CodeValidationFailed. Returns nil for bare sentinel or non-sandbox-formatted limits; callers should use MapReadLimitError.
func MapToolkitCapError ¶ added in v0.11.2
MapToolkitCapError enforces golden order for locally detected budget exceed (stat size, semantic table/markdown/wire cap) without an underlying read error.
func MapToolkitReadError ¶ added in v0.11.2
func MapToolkitReadError( ctx context.Context, err error, op string, maxBytes int, subject, hint string, ) error
MapToolkitReadError enforces golden order for toolkit post-read paths: ctx interrupt → read-limit validation → nil for other errors (caller wraps).
func ParseExactlyOne ¶ added in v0.12.0
func ParseExactlyOne[T any](parts []ContentPart, toolName string) (*T, error)
ParseExactlyOne extracts and decodes exactly one tool call for toolName.
func Put ¶ added in v0.8.0
Put stores a dependency in the environment's shared synchronized store. A DI-only NewRunEnv(nil) is valid. Nil/zero env or empty key returns INTERNAL with ErrMutationConfiguration. Nil values are allowed; Lookup treats them as absent. Referenced values remain host-owned, not universally deep-copied.
Example ¶
package main
import (
"errors"
"fmt"
"github.com/skosovsky/toolsy"
)
func main() {
// Dependencies can be installed without binding a state session.
env := toolsy.NewRunEnv(nil)
if err := toolsy.Put(env, "host", "tenant-a"); err != nil {
panic(err)
}
host, err := toolsy.Require[string](env, "host")
if err != nil {
panic(err)
}
fmt.Println(host)
// State mutation needs an explicitly bound Session.
err = toolsy.SetState(env, "counter", 1)
fmt.Println(errors.Is(err, toolsy.ErrMutationConfiguration))
}
Output: tenant-a true
func ReconcileOperation ¶ added in v0.16.0
func ReconcileOperation(ctx context.Context, store OperationStore, binding OperationBinding, clock func() time.Time, reconcile OperationReconciler, ) error
ReconcileOperation is an explicit trusted-host action. The host authenticates callers and supplies a callback that queries external outcome/downstream idempotency semantics. Never register this function as a tool for model input.
func RegisterJSONCodec ¶ added in v0.10.0
func RegisterJSONCodec[T any](r *StateCodecRegistry, key string, opts ...StateSlotOption) error
RegisterJSONCodec registers JSON marshal/unmarshal for type T at key.
func RegisterStateCodec ¶ added in v0.10.0
func RegisterStateCodec[T any](r *StateCodecRegistry, key string, codec StateCodec[T], opts ...StateSlotOption) error
RegisterStateCodec associates key with codec for type T.
func Require ¶ added in v0.8.0
Require returns a dependency or a ToolError with CodeDependencyMissing.
func SetSessionState ¶ added in v0.8.1
SetSessionState stores a value in the synchronized state map. It does not deep copy pointers/maps/slices; referenced value synchronization belongs to the host. Nil session or empty key returns INTERNAL with ErrMutationConfiguration.
func SetState ¶ added in v0.8.0
SetState stores mutable data on the bound Session and returns an error if env/session is missing or key is empty. A DI-only environment has no state target.
func ToolkitContextError ¶ added in v0.11.2
ToolkitContextError wraps ctx cancel/deadline as an internal tool error when ctx is done. Use before stat/size pre-checks so cooperative cancel wins over read-limit mapping.
func ValidateManifestContract ¶ added in v0.10.0
func ValidateManifestContract(ms ManifestSet, requiredNames []string) error
ValidateManifestContract checks that every name in requiredNames exists in ms. Empty requiredNames is a no-op.
func ValidateRunEnvSession ¶ added in v0.8.1
ValidateRunEnvSession reports when env is not bound to session.
func ValidateRunPolicy ¶ added in v0.7.0
ValidateRunPolicy checks internal consistency of a run policy.
func YieldControl ¶ added in v0.7.0
func YieldControl(yield func(Chunk) error, sig ControlSignal) error
YieldControl validates and snapshots a control, delivers it, then returns its sentinel. Return this error from the producer; a producer ignoring it is not preempted.
Types ¶
type ApprovalChallenge ¶ added in v0.16.0
type ApprovalChallenge struct {
Binding OperationBinding `json:"binding"`
DisplayJSON json.RawMessage `json:"display"`
}
ApprovalChallenge is a host continuation request, not an approval credential.
type ApprovalGrant ¶ added in v0.16.0
type ApprovalGrant struct {
ID string `json:"id"`
Issuer string `json:"issuer"`
Binding OperationBinding `json:"binding"`
IssuedAt time.Time `json:"issued_at"`
ExpiresAt time.Time `json:"expires_at"`
Rejected bool `json:"rejected"`
AllowRecovery bool `json:"allow_recovery"`
}
ApprovalGrant is written only through a trusted host issuer port. Grant IDs, signatures and model-provided strings alone never authorize replay.
type ApprovalIssuerStore ¶ added in v0.16.0
type ApprovalIssuerStore interface {
PutGrant(context.Context, ApprovalGrant) error
}
ApprovalIssuerStore is a host-only durable grant writer. Never expose it to tool code or use a model's text as an authenticated approval decision.
type ArgValidator ¶ added in v0.10.0
ArgValidator validates typed arguments after schema parse.
type ArgsBindRequest ¶ added in v0.13.0
type ArgsBindRequest struct {
Manifest ToolManifest
Input ToolInput
CallContext CallContext
}
ArgsBindRequest is the raw execution boundary passed to an ArgsBinder.
type ArgsBinder ¶ added in v0.13.0
type ArgsBinder[T any] func(ctx context.Context, req ArgsBindRequest) (ValidatedArgs[T], error)
ArgsBinder validates raw input and returns canonical typed args for the handler.
type AsyncAccepted ¶ added in v0.4.1
AsyncAccepted is the payload returned immediately when an async tool is invoked. The client (orchestrator) receives it via the first Chunk; the actual tool runs in a goroutine.
type AsyncCallback ¶ added in v0.4.1
AsyncCallback is invoked when the wrapped tool finishes (success or error). chunks holds all chunks collected from the base tool's yield; err is the error returned by Execute.
type AsyncOption ¶ added in v0.4.1
type AsyncOption func(*asyncOptions)
AsyncOption configures AsAsyncTool.
func WithBackgroundTimeout ¶ added in v0.8.3
func WithBackgroundTimeout(d time.Duration) AsyncOption
WithBackgroundTimeout limits how long the background goroutine may run after the accepted response is returned. Parent cancellation is stripped via context.WithoutCancel; this option applies an independent deadline to background work only.
func WithMaxCollectedChunks ¶ added in v0.9.0
func WithMaxCollectedChunks(n int) AsyncOption
WithMaxCollectedChunks overrides the default cap on chunks buffered for WithOnComplete. Values n <= 0 are ignored. Default is DefaultMaxCollectedChunks (1000). When the cap is exceeded, ErrAsyncCollectedLimitExceeded is surfaced in WithOnComplete.
func WithOnComplete ¶ added in v0.4.1
func WithOnComplete(cb AsyncCallback) AsyncOption
WithOnComplete registers a hook called when the async task completes (with all collected chunks and final error).
type Attachment ¶ added in v0.5.5
Attachment is binary input passed together with JSON args.
type Authorizer ¶ added in v0.7.0
type Authorizer interface {
Authorize(context.Context, PolicyRequest) error
}
Authorizer is a narrow error-returning adapter port for host authorization. Use NewAuthorizerPolicy and WithPolicy with a stable host-owned policy ID.
type AuthorizerFunc ¶ added in v0.12.0
type AuthorizerFunc func(context.Context, PolicyRequest) error
func (AuthorizerFunc) Authorize ¶ added in v0.12.0
func (f AuthorizerFunc) Authorize(ctx context.Context, req PolicyRequest) error
type BudgetTracker ¶ added in v0.5.6
type BudgetTracker interface {
Allow(ctx context.Context, manifest ToolManifest, input ToolInput) (allowed bool, reason string, err error)
}
BudgetTracker admits each wrapped call, including calls that later replay. Input is a raw-call snapshot before binding; host owns pricing and accounting.
type CacheEligibility ¶ added in v0.18.0
type CacheEligibility func(context.Context, PreparedCall) (bool, error)
CacheEligibility explicitly decides whether the current authorized call may reuse a stored result. Idempotence/read-only hints are not freshness guarantees. The host callback must be concurrency-safe and is evaluated on every attempt.
type CachePartition ¶ added in v0.16.0
type CachePartition func(context.Context, PreparedCall) (string, error)
CachePartition supplies a trusted scope/data partition after current policy. Include domain identity and dependency freshness affecting the result. Toolsy additionally binds the key to canonical input, attachments and manifest/view.
type CallContext ¶ added in v0.12.0
type CallContext struct {
Subject any
Scope any
Metadata CallMetadata
Values map[string]any
}
CallContext carries typed subject/scope values through the execution pipeline. It is intentionally type-erased at the Registry boundary; typed handlers recover compile-time types with TypedContext.
func NewCallContext ¶ added in v0.12.0
func NewCallContext[TSubject, TScope any](subject TSubject, scope TScope, opts ...CallContextOption) CallContext
NewCallContext creates a type-erased execution context from host-owned types.
type CallContextOption ¶ added in v0.12.0
type CallContextOption func(*CallContext)
CallContextOption configures a CallContext.
func WithCallMetadata ¶ added in v0.12.0
func WithCallMetadata(meta CallMetadata) CallContextOption
WithCallMetadata sets immutable metadata on a CallContext.
func WithCallValue ¶ added in v0.12.0
func WithCallValue(key string, value any) CallContextOption
WithCallValue attaches request-local metadata that must not be persisted as session state.
type CallMetadata ¶ added in v0.12.0
CallMetadata is immutable metadata attached to one tool call.
type CallParser ¶ added in v0.8.0
type CallParser interface {
ExtractExactlyOne(parts []ContentPart, toolName string) ([]byte, error)
}
CallParser extracts tool call arguments from LLM content parts.
type ChainUnwrapper ¶ added in v0.9.0
type ChainUnwrapper interface {
UnwrapNext() Tool
}
ChainUnwrapper is implemented by tool wrappers that delegate to an inner Tool. Required for nested-async detection when middleware is applied before RegistryBuilder.Add.
type Chunk ¶ added in v0.3.0
type Chunk struct {
CallID string
ToolName string
Event EventType
Data []byte
MimeType string
IsError bool
// TypedResult carries the host-typed result for in-process outcome aggregation.
TypedResult any
// EmptyResult marks an intentional successful no-op/empty result.
EmptyResult bool
// Noop marks an intentional successful no-op with no state/effect changes.
Noop bool
// Effects carries host-owned declarative effects for reducers outside toolsy.
Effects []any
// Controls carries declarative control-plane signals attached to a result.
Controls []ControlSignal
// Control carries typed orchestrator signals when Event == EventControl.
Control ControlSignal
// Progress carries optional progress metadata for EventProgress.
Progress *ProgressInfo
// Envelope classifies structured result/error payloads for downstream delivery.
Envelope *ToolEnvelope
// contains filtered or unexported fields
}
Chunk is a single stream event from a tool execution. Data-plane payloads use Data/MimeType. Control-plane signals use EventControl + Control.
func NewErrorChunkFromErr ¶ added in v0.10.0
NewErrorChunkFromErr builds a structured error result chunk with MimeTypeToolErrorJSON.
func (Chunk) ToolEnvelope ¶ added in v0.13.0
func (c Chunk) ToolEnvelope() ToolEnvelope
ToolEnvelope returns a typed delivery envelope for this chunk.
type ClaimResult ¶ added in v0.16.0
type ClaimResult struct {
Dispatch bool
Record OperationRecord
}
ClaimResult reports whether this attempt may dispatch. A stored completed result is replayed only after current invocation policy has already succeeded.
type CompletionPolicy ¶ added in v0.7.0
type CompletionPolicy string
CompletionPolicy defines how the orchestrator should treat successful tool completion.
const ( // CompletionContinue is the default host routing hint: continue after success. CompletionContinue CompletionPolicy = "continue" // CompletionSilentYield asks the host to end its continuation quietly after success. CompletionSilentYield CompletionPolicy = "silent_yield" // CompletionHalt asks the host to stop its continuation after success. // Core does not enforce these hints or cancel other calls. CompletionHalt CompletionPolicy = "halt" )
type ContentPart ¶ added in v0.8.0
type ContentPart struct {
Type string
Text string
ToolCallID string
ToolName string
Args string
ArgsChunk string
}
ContentPart is a provider-agnostic fragment of an LLM response for tool-call extraction.
func NormalizeToolCallParts ¶ added in v0.12.0
func NormalizeToolCallParts(parts []ContentPart) ([]ContentPart, error)
NormalizeToolCallParts fills continuation chunks with a known ToolName from the same ToolCallID. Conflicting tool names for the same call id are rejected.
type ControlSignal ¶ added in v0.7.0
type ControlSignal interface {
// contains filtered or unexported methods
}
ControlSignal is a sealed control-plane marker. Implementations live in this package only.
type CredentialsProvider ¶ added in v0.5.5
type CredentialsProvider interface {
GetAuth(ctx context.Context, toolName string) (string, error)
}
CredentialsProvider resolves runtime Authorization header values for outbound requests. GetAuth returns the complete header value (for example "Bearer ..." or "Basic ...").
type Decision ¶ added in v0.12.0
type Decision struct {
Allow bool
Code ErrorCode
Reason string
SafeMessage string
FixableArgs []string
Retryable bool
Err error
}
Decision is a machine-readable allow/deny result from policy/capability checks.
func AllowDecision ¶ added in v0.12.0
func AllowDecision() Decision
AllowDecision explicitly permits a call.
func DenyDecision ¶ added in v0.12.0
DenyDecision rejects a call with a structured policy error.
type DynamicToolSpec ¶ added in v0.10.0
type DynamicToolSpec struct {
Name, Description string
Schema SchemaProvider
ValidateArgs func(ctx context.Context, decoded map[string]any) error
Handler func(ctx context.Context, env *RunEnv, decoded map[string]any, yield func(Chunk) error) error
Options []ToolOption
}
DynamicToolSpec describes a dynamic tool with schema validation and decoded args. Numbers in ValidateArgs/Handler maps are json.Number. Duplicate keys and input values above depth 128 or 100,000 nodes are rejected before dispatch.
type EffectValidator ¶ added in v0.12.0
EffectValidator validates host-owned effects after the handler. Failures never authorize argument repair or rollback of external effects.
type ErrorCode ¶ added in v0.8.0
type ErrorCode string
ErrorCode is a machine-readable tool execution error category.
const ( CodeSchemaInvalid ErrorCode = "SCHEMA_INVALID" CodeValidationFailed ErrorCode = "VALIDATION_FAILED" CodeTimeout ErrorCode = "TIMEOUT" CodeToolNotFound ErrorCode = "TOOL_NOT_FOUND" CodeDependencyMissing ErrorCode = "DEPENDENCY_MISSING" CodeInternal ErrorCode = "INTERNAL" CodeShutdown ErrorCode = "SHUTDOWN" CodeMaxCallsExceeded ErrorCode = "MAX_CALLS_EXCEEDED" CodeRegistryNotReady ErrorCode = "REGISTRY_NOT_READY" CodeToolsContractMissing ErrorCode = "TOOLS_CONTRACT_MISSING" CodeBudgetExceeded ErrorCode = "BUDGET_EXCEEDED" CodeStateCodecMissing ErrorCode = "STATE_CODEC_MISSING" CodePolicyDenied ErrorCode = "POLICY_DENIED" CodeCapabilityDenied ErrorCode = "CAPABILITY_DENIED" CodeRemoteExecution ErrorCode = "REMOTE_EXECUTION" )
type EventType ¶ added in v0.5.5
type EventType string
EventType enumerates chunk event kinds for Chunk: EventProgress for intermediate UI status, EventResult for final data or a stream chunk; EventControl for orchestrator-managed signals.
const (
EventControl EventType = "control"
)
type ExecutionProfile ¶ added in v0.16.0
type ExecutionProfile interface {
ExecutePrepared(context.Context, PreparedCall, InvocationHandler, func(Chunk) error) error
}
ExecutionProfile controls dispatch or replay after current binding and policy. A profile must treat its handler as a single attempt, not a retry loop.
type ExecutionSummary ¶ added in v0.3.0
type ExecutionSummary struct {
CallID string
ToolName string
Error error
ChunksDelivered int
TotalBytes int64
ErrorChunks int
LastErrorText string
}
ExecutionSummary is passed to the after-execution hook (WithOnAfterExecute) when a tool execution finishes (success or error). ChunksDelivered and TotalBytes count only chunks with !IsError (successfully delivered result chunks). ErrorChunks and LastErrorText describe delivered soft errors (chunks with IsError=true).
type Extractor ¶ added in v0.2.0
type Extractor[T any] struct { // contains filtered or unexported fields }
Extractor provides JSON Schema generation and two-layer validation (schema + Validatable) for type T without binding to the Tool interface. Use it in custom orchestrators that need schema export and validated parsing but not the full Tool Execute(ctx, argsJSON, yield) pipeline.
func NewExtractor ¶ added in v0.2.0
NewExtractor creates an Extractor for type T. When strict is true, the generated schema has additionalProperties: false for all objects and all properties required (OpenAI Structured Outputs).
func NewExtractorWithConfig ¶ added in v0.5.5
func NewExtractorWithConfig[T any](cfg SchemaConfig) (*Extractor[T], error)
NewExtractorWithConfig creates an Extractor for type T using the provided schema configuration.
func (*Extractor[T]) ParseAndValidate ¶ added in v0.2.0
ParseAndValidate deserializes argsJSON into T, runs Layer 1 (schema validation) and Layer 2 (Validatable.Validate() if T implements it). Returns ToolError for invalid JSON or validation failures so the caller can pass the message to the LLM for self-correction. Interface-valued numbers use json.Number; concrete numeric fields keep their type. Duplicate keys, multiple documents, depth above 128 and over 100,000 value nodes are rejected before schema validation and typed decoding.
Example ¶
type WeatherInput struct {
City string `json:"city" jsonschema:"City name"`
}
ext, err := NewExtractor[WeatherInput](false)
if err != nil {
return
}
args, err := ext.ParseAndValidate([]byte(`{"city":"London"}`))
if err != nil {
return
}
fmt.Println(args.City)
Output: London
func (*Extractor[T]) Schema ¶ added in v0.2.0
Schema returns a shallow copy of the JSON Schema (top-level keys only). Nested maps are shared; callers must not mutate them.
Example ¶
type Params struct {
Q string `json:"q" jsonschema:"Query"`
}
ext, err := NewExtractor[Params](false)
if err != nil {
return
}
schema := ext.Schema()
fmt.Println(schema["type"])
Output: object
type HaltSignal ¶ added in v0.7.0
type HaltSignal struct {
Reason string
}
HaltSignal asks the host to stop its continuation after this call. It does not cancel this context, other calls or a registry/session.
type HostEventSignal ¶ added in v0.18.0
HostEventSignal carries named data for a host-owned event adapter. Name has no built-in meaning; delivery never executes an action or grants authority. PayloadJSON is optional strict UTF-8 JSON, bounded with Name by MaxControlBytes.
type InputAdmitter ¶ added in v0.19.2
type InputAdmitter interface {
AdmitInput(ctx context.Context, call CallContext, in ToolInput) (ToolInput, error)
}
InputAdmitter optionally checks input without dispatching a tool. Implementations must use the same input transformation and validation as Execute, return a defensive canonical snapshot, and never treat success as authorization. User callbacks must be repeatable and avoid business effects; their purity is host-owned. Panics propagate to the caller, including through WithRecovery.
type InvocationHandler ¶ added in v0.16.0
InvocationHandler dispatches an already authorized invocation. It must not be retried by a profile after an unknown external outcome.
type JSONResultCodec ¶ added in v0.16.0
type JSONResultCodec[R, E any] struct{}
JSONResultCodec preserves the declared result/effect types, the complete delivery envelope and built-in control signals. Metadata must be JSON-shaped. Hosts with non-JSON values provide their own ResultCodec instead. Dynamic JSON numbers decode as json.Number without float64 rounding; arbitrary concrete Go types inside interfaces are not reconstructed.
func (JSONResultCodec[R, E]) DecodeResult ¶ added in v0.16.0
func (JSONResultCodec[R, E]) DecodeResult(raw []byte) (Chunk, error)
DecodeResult restores the declared result/effect types and delivery semantics.
func (JSONResultCodec[R, E]) EncodeResult ¶ added in v0.16.0
func (JSONResultCodec[R, E]) EncodeResult(chunk Chunk) ([]byte, error)
EncodeResult encodes one successful terminal result without type erasure.
type JSONStateCodec ¶ added in v0.10.0
type JSONStateCodec[T any] struct{}
JSONStateCodec is a StateCodec using encoding/json.
func (JSONStateCodec[T]) Decode ¶ added in v0.10.0
func (JSONStateCodec[T]) Decode(data []byte) (T, error)
func (JSONStateCodec[T]) Encode ¶ added in v0.10.0
func (JSONStateCodec[T]) Encode(v T) ([]byte, error)
type ManifestSet ¶ added in v0.10.0
type ManifestSet struct {
// contains filtered or unexported fields
}
ManifestSet is a declarative collection of tool manifests without executable registry state.
func ManifestSetFromManifests ¶ added in v0.10.0
func ManifestSetFromManifests(manifests ...ToolManifest) (ManifestSet, error)
ManifestSetFromManifests builds a set from raw manifests.
func NewManifestSet ¶ added in v0.10.0
func NewManifestSet(tools ...Tool) (ManifestSet, error)
NewManifestSet builds a manifest set from tools (Manifest() only; no Build required).
func (ManifestSet) Has ¶ added in v0.10.0
func (m ManifestSet) Has(name string) bool
Has reports whether name is present in the set.
func (ManifestSet) Manifest ¶ added in v0.10.0
func (m ManifestSet) Manifest(name string) (ToolManifest, bool)
Manifest returns a defensive copy of the manifest for name and whether it exists.
func (ManifestSet) Names ¶ added in v0.10.0
func (m ManifestSet) Names() []string
Names returns sorted tool names in the set.
type MapSchemaProvider ¶ added in v0.10.0
MapSchemaProvider wraps a schema map as SchemaProvider.
func (MapSchemaProvider) ParametersSchema ¶ added in v0.10.0
func (m MapSchemaProvider) ParametersSchema() map[string]any
ParametersSchema returns a defensive copy of the schema map.
type MemoryAccess ¶ added in v0.10.0
type MemoryAccess string
MemoryAccess describes how a tool uses session in-memory state.
const ( MemoryAccessNone MemoryAccess = "none" MemoryAccessRead MemoryAccess = "read" MemoryAccessReadWrite MemoryAccess = "readwrite" )
type MemoryOperationStore ¶ added in v0.16.0
type MemoryOperationStore struct {
// contains filtered or unexported fields
}
MemoryOperationStore implements the journal transition contract, not durable recovery. Hosts needing crash recovery must select a durable adapter.
func NewMemoryOperationStore ¶ added in v0.16.0
func NewMemoryOperationStore() *MemoryOperationStore
func RestoreOperationStore ¶ added in v0.16.0
func RestoreOperationStore(snapshot OperationSnapshot) (*MemoryOperationStore, error)
RestoreOperationStore copies a trusted, complete image for atomic adapters. It validates structural consistency in both directions, not authenticity or external outcome truth. Historical approval expiry does not invalidate an image.
func (*MemoryOperationStore) Claim ¶ added in v0.16.0
func (s *MemoryOperationStore) Claim(ctx context.Context, claim OperationClaim) (ClaimResult, error)
func (*MemoryOperationStore) Finish ¶ added in v0.16.0
func (s *MemoryOperationStore) Finish(ctx context.Context, finish OperationFinish) error
func (*MemoryOperationStore) Inspect ¶ added in v0.16.0
func (s *MemoryOperationStore) Inspect(ctx context.Context, binding OperationBinding) (OperationRecord, bool, error)
func (*MemoryOperationStore) PutGrant ¶ added in v0.16.0
func (s *MemoryOperationStore) PutGrant(ctx context.Context, grant ApprovalGrant) error
func (*MemoryOperationStore) Resolve ¶ added in v0.16.0
func (s *MemoryOperationStore) Resolve(ctx context.Context, resolution OperationResolution) error
func (*MemoryOperationStore) Snapshot ¶ added in v0.16.0
func (s *MemoryOperationStore) Snapshot() OperationSnapshot
type MemoryResultCacheStore ¶ added in v0.16.0
type MemoryResultCacheStore struct {
// contains filtered or unexported fields
}
MemoryResultCacheStore is a bounded-by-caller process-local test cache. It is not durable and does not coordinate dispatch; hosts own eviction/expiry policy.
func NewMemoryResultCacheStore ¶ added in v0.16.0
func NewMemoryResultCacheStore() *MemoryResultCacheStore
NewMemoryResultCacheStore creates a process-local result store.
type Middleware ¶
Middleware wraps a Tool with cross-cutting behavior (logging, recovery). Wrappers applied manually before RegistryBuilder.Add must implement ChainUnwrapper so RegistryBuilder.Build can detect invalid nested AsAsyncTool chains.
func WithBudget ¶ added in v0.5.6
func WithBudget() Middleware
WithBudget requires a valid BudgetTracker at DepKeyBudget on RunEnv.
func WithErrorFormatter ¶ added in v0.5.6
func WithErrorFormatter() Middleware
WithErrorFormatter converts terminal execution errors from the wrapped tool/middleware execution path into an error chunk for LLM self-correction.
Registry/session pre-tool failures (for example ErrToolNotFound, ErrMaxCallsExceeded, shutdown, validator rejection) happen before middleware execution and remain hard errors.
func WithLogging ¶
func WithLogging(logger *slog.Logger) Middleware
WithLogging returns a middleware that logs start, end, duration, and errors.
func WithOptionalBudget ¶ added in v0.18.0
func WithOptionalBudget() Middleware
WithOptionalBudget bypasses only an absent dependency. A supplied invalid tracker still fails closed. Use only for an intentional host no-budget mode.
func WithRecovery
deprecated
func WithRecovery() Middleware
WithRecovery returns a middleware that recovers panics and returns ToolError with CodeInternal.
Deprecated: Registry is built with panic recovery enabled by default (NewRegistryBuilder sets recoverPanics). Using WithRecovery in Use() recovers panics before the registry's recovery and onAfter hooks can observe them. Prefer relying on registry recovery only; this middleware remains for rare direct Tool.Execute paths without a registry.
func WithTruncation ¶ added in v0.5.6
func WithTruncation(maxRunes int, opts ...TruncationOption) Middleware
WithTruncation truncates large textual chunk payloads by rune count. By default it applies to text/plain and text/markdown payloads.
type NoScope ¶ added in v0.12.0
type NoScope struct{}
NoScope marks calls that intentionally do not bind a policy scope.
type NoSubject ¶ added in v0.12.0
type NoSubject struct{}
NoSubject marks calls that intentionally do not bind a policy subject.
type OperationBinding ¶ added in v0.16.0
type OperationBinding struct {
Namespace string `json:"namespace"`
Scope string `json:"scope"`
Subject string `json:"subject"`
OperationID string `json:"operation_id"`
Tool string `json:"tool"`
ManifestFingerprint string `json:"manifest_fingerprint"`
ViewFingerprint string `json:"view_fingerprint"`
PolicyFingerprint string `json:"policy_fingerprint"`
CanonicalDigest string `json:"canonical_digest"`
CanonicalRules string `json:"canonical_rules"`
DownstreamKey string `json:"downstream_key"`
}
OperationBinding binds one host-defined logical intent to authorized inputs. Scope/Subject are opaque host identifiers, not library business identity types. CanonicalDigest may be keyed by the host when arguments contain secret refs.
type OperationClaim ¶ added in v0.16.0
type OperationClaim struct {
Binding OperationBinding
AttemptID string
GrantID string
Issuer string
RequiresApproval bool
Now time.Time
LeaseUntil time.Time
}
OperationClaim requests one atomic approval reservation and dispatch claim. Lease expiry changes uncertainty, not permission to start another effect. GrantID must be empty when RequiresApproval is false. Recovery retains the original approval mode; it cannot erase a consumed reservation.
type OperationError ¶ added in v0.16.0
type OperationError struct{ Kind string }
OperationError is a non-retryable operation decision. Unknown outcomes require trusted reconciliation, never an automatic retry of the handler.
func (*OperationError) Error ¶ added in v0.16.0
func (e *OperationError) Error() string
type OperationFinish ¶ added in v0.16.0
type OperationFinish struct {
Binding OperationBinding
AttemptID string
State OperationState
Result []byte
}
OperationFinish fences a terminal state update to the reserved attempt. Unknown is required if the handler started but its external outcome is unproven.
type OperationIntent ¶ added in v0.16.0
type OperationIntent struct {
Namespace, Scope, Subject, OperationID string
PolicyFingerprint, CanonicalDigest, CanonicalRules string
DownstreamKey, AttemptID, GrantID string
DisplayJSON json.RawMessage
}
OperationIntent comes from an authenticated host, never model arguments. Digest must bind canonical arguments AND attachments, including secret identity changes. DisplayJSON is a bounded redacted description of that same snapshot.
type OperationOutcomeError ¶ added in v0.16.0
type OperationOutcomeError struct {
Cause error
Binding OperationBinding
AttemptID string
// DispatchInvoked records whether this profile called the dispatch continuation.
// It does not prove an external effect or authorize rolling back a claim.
DispatchInvoked bool
}
OperationOutcomeError preserves the cause while explicitly forbidding blind retry after claim. Dispatch may have occurred; the journal decides recovery.
func (*OperationOutcomeError) Error ¶ added in v0.16.0
func (e *OperationOutcomeError) Error() string
func (*OperationOutcomeError) Unwrap ¶ added in v0.16.0
func (e *OperationOutcomeError) Unwrap() error
type OperationProfile ¶ added in v0.16.0
type OperationProfile struct {
// contains filtered or unexported fields
}
OperationProfile couples atomic approval and operation claims to the prepared boundary. It buffers one complete terminal result until producer success and durable persistence. It never retries handlers or treats cancellation as rollback.
func NewOperationProfile ¶ added in v0.16.0
func NewOperationProfile(config OperationProfileConfig) (*OperationProfile, error)
NewOperationProfile validates and captures a named configuration without calling host ports. The profile never schedules retries or replaces a consumed grant.
func (*OperationProfile) ExecutePrepared ¶ added in v0.16.0
func (p *OperationProfile) ExecutePrepared( ctx context.Context, call PreparedCall, invoke InvocationHandler, yield func(Chunk) error, ) error
type OperationProfileConfig ¶ added in v0.18.0
type OperationProfileConfig struct {
Store OperationStore
Prepare PrepareOperation
Codec ResultCodec
Issuer string
Clock func() time.Time
Lease time.Duration
// MaxBytes bounds both display JSON and encoded terminal result. Zero defaults
// to 1 MiB; negative values fail construction. A positive value is inclusive.
MaxBytes int
}
OperationProfileConfig names host ports and bounds for the prepared dispatch gate. Config fields are captured by value; host-owned referenced ports and callbacks must remain valid and support concurrent calls. Toolsy does not close them.
type OperationReconciler ¶ added in v0.16.0
type OperationReconciler func(context.Context, OperationRecord) (ReconciliationDecision, error)
OperationReconciler is an authenticated host callback, not a model-facing tool. It receives a private copy of the uncertain operation and original downstream key. It cannot redirect resolution to another binding or fencing attempt.
type OperationRecord ¶ added in v0.16.0
type OperationRecord struct {
Binding OperationBinding `json:"binding"`
State OperationState `json:"state"`
AttemptID string `json:"attempt_id"`
LeaseUntil time.Time `json:"lease_until"`
Result []byte `json:"result"`
GrantID string `json:"grant_id"`
ApprovalExpiresAt time.Time `json:"approval_expires_at"`
Attempts []string `json:"attempts"`
ResolutionProofID string `json:"resolution_proof_id"`
ResolvedAt time.Time `json:"resolved_at"`
}
OperationRecord exposes a durable result or uncertainty, never a new grant.
type OperationResolution ¶ added in v0.16.0
type OperationResolution struct {
Binding OperationBinding
ExpectedAttemptID string
State OperationState
Result []byte
ProofID string
Now time.Time
}
OperationResolution is a trusted host reconciliation decision. ProofID is provenance, not authentication. A host may authorize a retry only with verified reconciliation or declared downstream idempotency using the original key.
type OperationSnapshot ¶ added in v0.16.0
type OperationSnapshot struct {
Records map[string]OperationRecord `json:"records"`
Grants map[string]ApprovalGrant `json:"grants"`
Consumed map[string]string `json:"consumed"`
}
OperationSnapshot is the complete atomic journal image. Only trusted storage adapters may restore it. Neither grants nor snapshots are model input.
type OperationState ¶ added in v0.16.0
type OperationState string
OperationState is the durable state, distinct from transport delivery status.
const ( OperationInProgress OperationState = "in_progress" OperationCompleted OperationState = "completed" OperationUnknown OperationState = "unknown_outcome" OperationRejected OperationState = "rejected" OperationRetryAuthorized OperationState = "retry_authorized" )
type OperationStateError ¶ added in v0.16.0
type OperationStateError struct{ Record OperationRecord }
OperationStateError gives the host a bound continuation reference, not a grant or dispatch permission. Resume must still use the current authorized executor.
func (*OperationStateError) Error ¶ added in v0.16.0
func (e *OperationStateError) Error() string
func (*OperationStateError) Unwrap ¶ added in v0.16.0
func (e *OperationStateError) Unwrap() error
type OperationStore ¶ added in v0.16.0
type OperationStore interface {
// Inspect is a host-only read: it must not reserve, consume approval, expire
// a lease, create an operation or authorize dispatch.
Inspect(context.Context, OperationBinding) (OperationRecord, bool, error)
Claim(context.Context, OperationClaim) (ClaimResult, error)
Finish(context.Context, OperationFinish) error
Resolve(context.Context, OperationResolution) error
}
OperationStore atomically owns approval reservation and operation state. Implementations must enforce binding conflicts, issuer/expiry, fencing and crash recovery. Separate independent grant-consume and operation-claim writes do not satisfy this contract.
type OperationStoreError ¶ added in v0.16.0
OperationStoreError identifies infrastructure failure separately from a binding/approval decision or handler error. Cause stays host-only diagnostics.
func (*OperationStoreError) Error ¶ added in v0.16.0
func (e *OperationStoreError) Error() string
func (*OperationStoreError) Unwrap ¶ added in v0.16.0
func (e *OperationStoreError) Unwrap() error
type OutcomeStatus ¶ added in v0.12.0
type OutcomeStatus string
OutcomeStatus describes the terminal semantic state of RunCall.
const ( OutcomeSuccess OutcomeStatus = "success" OutcomeEmptySuccess OutcomeStatus = "empty_success" OutcomeNoopSuccess OutcomeStatus = "noop_success" OutcomeBusinessError OutcomeStatus = "business_error" OutcomeInfrastructureError OutcomeStatus = "infrastructure_error" )
type OverrideOption ¶ added in v0.4.1
type OverrideOption func(*overrideOptions)
OverrideOption configures OverrideTool.
func WithNewDescription ¶ added in v0.4.1
func WithNewDescription(desc string) OverrideOption
WithNewDescription overrides the tool manifest description.
func WithNewName ¶ added in v0.4.1
func WithNewName(name string) OverrideOption
WithNewName overrides the tool manifest name.
func WithNewParameters ¶ added in v0.4.1
func WithNewParameters(params map[string]any) OverrideOption
WithNewParameters overrides the JSON Schema parameters map. Pass nil to keep the base schema.
type PauseSignal ¶ added in v0.7.0
type PauseSignal struct {
Reason string
}
PauseSignal asks the host to pause its continuation after this call. It does not persist a continuation, block other calls or issue approval authority.
type PendingApprovalError ¶ added in v0.16.0
type PendingApprovalError struct{ Challenge ApprovalChallenge }
func (*PendingApprovalError) Error ¶ added in v0.16.0
func (e *PendingApprovalError) Error() string
func (*PendingApprovalError) Unwrap ¶ added in v0.16.0
func (e *PendingApprovalError) Unwrap() error
type Permission ¶ added in v0.10.0
type Permission string
Permission is a host-defined capability label declared on a tool manifest.
type Policy ¶ added in v0.12.0
type Policy interface {
Decide(ctx context.Context, req PolicyRequest) Decision
}
Policy performs universal fail-closed call authorization.
func NewAuthorizerPolicy ¶ added in v0.18.0
func NewAuthorizerPolicy(authorizer Authorizer) (Policy, error)
NewAuthorizerPolicy captures a required authorizer; nil, typed-nil and nil functions fail construction. It never resolves a dependency from RunEnv. All authorization failures become nonretryable, noncorrectable policy denials. The original cause remains inspectable; structured argument decisions belong to Policy/typed argument policy rather than this simple adapter.
Example ¶
package main
import (
"context"
"errors"
"fmt"
"github.com/skosovsky/toolsy"
)
func main() {
// Capture the host port rather than resolving authorization through RunEnv.
authorizer := toolsy.AuthorizerFunc(func(_ context.Context, request toolsy.PolicyRequest) error {
if request.CallContext.Subject != "alice" {
return errors.New("caller is not authorized")
}
return nil
})
policy, err := toolsy.NewAuthorizerPolicy(authorizer)
if err != nil {
panic(err)
}
echo, err := toolsy.NewTool(
"echo",
"Echo",
func(_ context.Context, _ *toolsy.RunEnv, input struct{ Text string }) (string, error) {
return input.Text, nil
},
)
if err != nil {
panic(err)
}
registry, err := toolsy.NewRegistryBuilder(toolsy.WithPolicy("host-auth-v1", policy)).Add(echo).Build()
if err != nil {
panic(err)
}
err = registry.Execute(context.Background(), toolsy.ToolCall{
ToolName: "echo", Input: toolsy.ToolInput{ArgsJSON: []byte(`{"Text":"hello"}`)},
CallContext: toolsy.NewCallContext("alice", "tenant"),
}, func(chunk toolsy.Chunk) error { fmt.Println(string(chunk.Data)); return nil })
if err != nil {
panic(err)
}
}
Output: "hello"
func NewRequirementsPolicy ¶ added in v0.12.0
func NewRequirementsPolicy[TSubject, TScope any]( fn RequirementsDecisionFunc[TSubject, TScope], ) Policy
NewRequirementsPolicy converts manifest requirements into fail-closed registry/session enforcement.
type PolicyFunc ¶ added in v0.12.0
type PolicyFunc func(context.Context, PolicyRequest) Decision
PolicyFunc adapts a function to Policy.
func (PolicyFunc) Decide ¶ added in v0.12.0
func (f PolicyFunc) Decide(ctx context.Context, req PolicyRequest) Decision
Decide implements Policy.
type PolicyRequest ¶ added in v0.12.0
type PolicyRequest struct {
Manifest ToolManifest
Input ToolInput
CallContext CallContext
View RegistryViewSnapshot
}
PolicyRequest is the type-erased request evaluated before tool execution.
type PostconditionValidator ¶ added in v0.12.0
type PostconditionValidator[R, E any] func(ToolResult[R, E]) error
PostconditionValidator validates the complete typed result/effects/control envelope after the handler; failures never authorize argument repair or redispatch.
type PrepareOperation ¶ added in v0.16.0
type PrepareOperation func(context.Context, PreparedCall) (OperationIntent, error)
type PreparedCall ¶ added in v0.16.0
type PreparedCall struct {
Manifest ToolManifest
Input ToolInput
Context CallContext
View RegistryViewSnapshot
}
PreparedCall is a defensive snapshot after argument binding and authorization. Input contains canonical arguments; Context and View remain host-owned contracts.
type PreparedExecutionTool ¶ added in v0.16.0
type PreparedExecutionTool interface {
SupportsPreparedExecution() bool
}
PreparedExecutionTool advertises an execution boundary preserved by a tool chain. Custom implementations must call ExecutePrepared after all binding and policy checks and before every handler invocation.
type ProgressInfo ¶ added in v0.7.0
type ProgressInfo struct {
Current *float64
Total *float64
Message string
Label string
Status string
Token string
}
ProgressInfo carries optional data-plane progress for EventProgress chunks.
type ReconciliationDecision ¶ added in v0.16.0
type ReconciliationDecision struct {
State OperationState
Result []byte
ProofID string
}
ReconciliationDecision describes trusted external evidence. RetryAuthorized requires verified absence or downstream idempotency with the original key; no lease/timeout inference or model-supplied proof is sufficient.
type ReconciliationError ¶ added in v0.16.0
type ReconciliationError struct{ Cause error }
func (*ReconciliationError) Error ¶ added in v0.16.0
func (e *ReconciliationError) Error() string
func (*ReconciliationError) Unwrap ¶ added in v0.16.0
func (e *ReconciliationError) Unwrap() error
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry holds tools and executes them with optional panic recovery.
func NewRegistry ¶
NewRegistry creates an immutable registry from tools with default options.
func (*Registry) Execute ¶
Execute runs one tool call and streams chunks to yield. Returns on first yield error or tool error. The after-execution hook (WithOnAfterExecute) is always invoked via defer with ExecutionSummary. ChunksDelivered and TotalBytes count only chunks with !IsError. ErrorChunks/LastErrorText describe delivered soft-error chunks.
Execute does not validate that call.Env is bound to a Session. For stateful agent tracks use Session.Execute or call ValidateRunEnvSession before Execute when env must match a session.
Example ¶
type Args struct {
X int `json:"x"`
}
type Out struct {
Y int `json:"y"`
}
tool, err := NewTool("add_one", "Add one", func(_ context.Context, _ *RunEnv, a Args) (Out, error) {
return Out{Y: a.X + 1}, nil
})
if err != nil {
return
}
reg, err := NewRegistryBuilder().Add(tool).Build()
if err != nil {
return
}
var out Out
err = reg.Execute(context.Background(), ToolCall{
ToolName: "add_one",
Input: ToolInput{CallID: "1", ArgsJSON: []byte(`{"x": 5}`)},
}, func(c Chunk) error {
return json.Unmarshal(c.Data, &out)
})
if err != nil {
panic(err)
}
_ = out
func (*Registry) ExecuteBatchStream ¶ added in v0.3.0
func (r *Registry) ExecuteBatchStream(ctx context.Context, calls []ToolCall, yield func(Chunk) error) error
ExecuteBatchStream runs all calls in parallel and streams chunks via yield. Each chunk is tagged with CallID and ToolName. Non-suspend execution failures (including pre-tool dispatch errors and tool/middleware failures) are sent as Chunk with IsError: true; the method returns error only for critical failures (context canceled, stream aborted, suspend). After Registry.Shutdown, new calls receive a soft error chunk (IsError: true) per call, not ErrShutdown from ExecuteBatchStream itself. For AsAsyncTool, batch yields sync chunks (typically AsyncAccepted) and returns while background work continues; Registry.Shutdown still waits for those background jobs via the async runtime tracker. The library serializes calls to yield with a mutex so the caller's callback need not be thread-safe.
Example ¶
type Args struct {
A int `json:"a"`
B int `json:"b"`
}
type Out struct {
Sum int `json:"sum"`
}
tool, err := NewTool("add", "Add two numbers", func(_ context.Context, _ *RunEnv, a Args) (Out, error) {
return Out{Sum: a.A + a.B}, nil
})
if err != nil {
return
}
reg, err := NewRegistryBuilder().Add(tool).Build()
if err != nil {
return
}
calls := []ToolCall{
{ToolName: "add", Input: ToolInput{CallID: "1", ArgsJSON: []byte(`{"a": 1, "b": 2}`)}},
{ToolName: "add", Input: ToolInput{CallID: "2", ArgsJSON: []byte(`{"a": 10, "b": 20}`)}},
}
err = reg.ExecuteBatchStream(context.Background(), calls, func(_ Chunk) error { return nil })
if err != nil {
panic(err)
}
func (*Registry) ExecuteIter ¶ added in v0.4.0
ExecuteIter runs one tool call and returns an iterator over (Chunk, error) pairs. Push-to-push: no channels or extra goroutines; the iterator calls Execute with a callback that forwards to yield. When the consumer breaks out of the loop, cancel() is called and Execute exits via context.Canceled. Once yield returns false, the iterator must not call yield again (iter contract). Env/session binding: same as Registry.Execute (no automatic ValidateRunEnvSession).
func (*Registry) GetAllTools ¶
GetAllTools returns all registered tools, sorted by manifest name. This is a map-view helper only; it does not check runtime readiness. A nil receiver returns nil (no panic).
func (*Registry) GetTool ¶
GetTool returns the tool with the given name, or (nil, false) if not found. A nil receiver returns (nil, false).
func (*Registry) Has ¶ added in v0.6.2
Has reports whether a tool with the given name is registered in this view's tool map. It does not check runtime readiness; use ValidateManifestContract or Registry.Execute for that. A nil receiver returns false.
func (*Registry) ManifestSet ¶ added in v0.10.0
func (r *Registry) ManifestSet() (ManifestSet, error)
ManifestSet returns a declarative manifest view of registered tools (no runtime state required).
func (*Registry) RestoreView ¶ added in v0.12.0
func (r *Registry) RestoreView( snapshot RegistryViewSnapshot, policy Policy, policyID ...string, ) (*RegistryView, error)
RestoreView recreates a view from a previously saved snapshot.
func (*Registry) Shutdown ¶
Shutdown closes the registry for new calls and waits for in-flight executions or ctx to cancel. Both synchronous executions and background jobs started by AsAsyncTool (when run via Registry) are tracked; Shutdown blocks until all of them finish or ctx is cancelled.
Registry views share runtime state with their parent. Calling Shutdown on any view closes the shared lifecycle for the entire registry tree (idempotent via sync.Once). Only the application owner of the root registry (for example App or Server on SIGTERM) should call Shutdown; do not call Shutdown on a per-request view to "clean up" after an agent run.
func (*Registry) Subset ¶ added in v0.6.2
Subset returns a capability-backed registry view containing only the named tools from r. Duplicate names in allowedNames are ignored (silent dedup). Returns an error if any name is not present in r (strict fail-fast). The parent registry is not modified. Registry options (hooks, validator) are inherited. Subset shares runtime state (Shutdown, in-flight tracking) with r and all sibling views. Shutdown on either parent or subset stops the entire tree (see Registry.Shutdown). Prefer Registry.View when the caller needs snapshot identity, required tool validation, or view policy.
func (*Registry) ToolNames ¶ added in v0.6.2
ToolNames returns all registered tool names, sorted lexicographically. Useful for prompt manifests and contract validation. This is a map-view helper only; it does not check runtime readiness. A nil receiver returns nil (no panic).
func (*Registry) View ¶ added in v0.12.0
func (r *Registry) View(spec RegistryViewSpec) (*RegistryView, error)
View creates a durable capability view with its own policy layered over the root registry policy.
type RegistryBuilder ¶ added in v0.5.5
type RegistryBuilder struct {
// contains filtered or unexported fields
}
RegistryBuilder is mutable setup API that produces an immutable Registry for runtime use.
func NewRegistryBuilder ¶ added in v0.5.5
func NewRegistryBuilder(opts ...RegistryOption) *RegistryBuilder
NewRegistryBuilder creates a mutable registry builder with defaults and applies options.
func (*RegistryBuilder) Add ¶ added in v0.5.5
func (b *RegistryBuilder) Add(tools ...Tool) *RegistryBuilder
Add appends tools to the builder.
Example ¶
type Args struct {
X int `json:"x"`
}
type Out struct {
Y int `json:"y"`
}
tool, err := NewTool("with_opts", "Tool with options", func(_ context.Context, _ *RunEnv, a Args) (Out, error) {
return Out{Y: a.X * 2}, nil
}, WithStrict())
if err != nil {
return
}
reg, err := NewRegistryBuilder().Add(tool).Build()
if err != nil {
return
}
_, ok := reg.GetTool("with_opts")
if ok {
fmt.Println("registered")
}
Output: registered
func (*RegistryBuilder) Build ¶ added in v0.5.5
func (b *RegistryBuilder) Build() (*Registry, error)
Build creates an immutable runtime registry. Rejects tools with more than one AsAsyncTool layer anywhere in the chain (see ChainUnwrapper).
func (*RegistryBuilder) Use ¶ added in v0.5.5
func (b *RegistryBuilder) Use(middlewares ...Middleware) *RegistryBuilder
Use appends middlewares. The first middleware is outermost.
Example ¶
type Args struct {
N int `json:"n"`
}
type Out struct {
Double int `json:"double"`
}
tool, err := NewTool("double", "Double the number", func(_ context.Context, _ *RunEnv, a Args) (Out, error) {
return Out{Double: a.N * 2}, nil
})
if err != nil {
return
}
reg, err := NewRegistryBuilder().Use(
WithLogging(slog.New(slog.DiscardHandler)),
).Add(tool).Build()
if err != nil {
return
}
var out Out
_ = reg.Execute(context.Background(), ToolCall{
ToolName: "double",
Input: ToolInput{CallID: "1", ArgsJSON: []byte(`{"n": 21}`)},
}, func(c Chunk) error {
return json.Unmarshal(c.Data, &out)
})
b, _ := json.Marshal(out)
fmt.Printf("result: %s", b)
Output: result: {"double":42}
func (*RegistryBuilder) WithOptions ¶ added in v0.5.5
func (b *RegistryBuilder) WithOptions(opts ...RegistryOption) *RegistryBuilder
WithOptions applies registry options to the builder.
type RegistryOption ¶
type RegistryOption func(*registryOptions)
RegistryOption configures a Registry.
func WithExecutionProfile ¶ added in v0.16.0
func WithExecutionProfile(profile ExecutionProfile) RegistryOption
WithExecutionProfile installs a prepared execution profile for a registry.
func WithOnAfterExecute ¶
func WithOnAfterExecute(fn func(context.Context, ToolCall, ExecutionSummary, time.Duration)) RegistryOption
WithOnAfterExecute sets a hook called after each tool execution (always invoked via defer, even on partial success or error). Summary reports delivered success chunks/bytes, delivered error chunks (soft errors), and final hard error.
func WithOnBeforeExecute ¶
func WithOnBeforeExecute(fn func(context.Context, ToolCall)) RegistryOption
WithOnBeforeExecute sets a hook called before each tool execution.
func WithOnChunk ¶ added in v0.3.0
func WithOnChunk(fn func(context.Context, Chunk)) RegistryOption
WithOnChunk sets a hook called for each non-error chunk successfully delivered (when yield returns nil). Observability only.
func WithPolicy ¶ added in v0.12.0
func WithPolicy(policyID string, p Policy) RegistryOption
WithPolicy configures fail-closed policy/capability enforcement before tool handlers run. Explicit nil/typed-nil/nil-function policies fail Build; omission installs no gate. policyID is part of session/checkpoint binding and must change when policy semantics change.
func WithRecoverPanics ¶
func WithRecoverPanics(enable bool) RegistryOption
WithRecoverPanics enables panic recovery in Execute (returns ToolError with CodeInternal).
func WithRequirementsPolicy ¶ added in v0.12.0
func WithRequirementsPolicy[TSubject, TScope any]( policyID string, fn RequirementsDecisionFunc[TSubject, TScope], ) RegistryOption
WithRequirementsPolicy configures fail-closed typed enforcement for manifest requirements. policyID is part of session/checkpoint binding and must change when policy semantics change.
func WithValidator ¶ added in v0.4.1
func WithValidator(v Validator) RegistryOption
WithValidator configures a low-level reject-only validator run before tool unmarshaling (fail-closed).
Use ArgsBinder through NewTypedTool or NewPolicyTool when validation needs to return canonical typed/sanitized args to the handler.
func WithValidatorFromRegistry ¶ added in v0.7.0
func WithValidatorFromRegistry(provider RegistryProvider, delegate func(*Registry) Validator) RegistryOption
WithValidatorFromRegistry binds validation to a lazily resolved registry. delegate must be non-nil and must not return another lazy validator.
type RegistryProvider ¶ added in v0.7.0
RegistryProvider resolves a registry lazily after builder configuration (validator late binding).
type RegistryView ¶ added in v0.12.0
type RegistryView struct {
// contains filtered or unexported fields
}
RegistryView is a first-class capability object over a registry subset.
func (*RegistryView) ExecuteIter ¶ added in v0.12.0
ExecuteIter runs one view-scoped tool call and returns an iterator over chunks.
func (*RegistryView) ManifestSet ¶ added in v0.12.0
func (v *RegistryView) ManifestSet() (ManifestSet, error)
ManifestSet returns the manifest set visible through the view.
func (*RegistryView) NewSession ¶ added in v0.12.0
func (v *RegistryView) NewSession(opts ...SessionOption) (*Session, error)
NewSession creates a session bound to this view's registry.
func (*RegistryView) NewSessionFromCheckpoint ¶ added in v0.13.0
func (v *RegistryView) NewSessionFromCheckpoint(checkpoint SessionCheckpoint, opts ...SessionOption) (*Session, error)
NewSessionFromCheckpoint restores a session only when this view matches the checkpoint binding.
func (*RegistryView) RebindSession ¶ added in v0.13.0
func (v *RegistryView) RebindSession(s *Session) error
RebindSession moves an existing session to this view after binding compatibility validation.
func (*RegistryView) Shutdown ¶ added in v0.12.0
func (v *RegistryView) Shutdown(ctx context.Context) error
Shutdown delegates lifecycle control to the shared root runtime state.
func (*RegistryView) Snapshot ¶ added in v0.12.0
func (v *RegistryView) Snapshot() RegistryViewSnapshot
Snapshot returns the durable view identity.
func (*RegistryView) ToolNames ¶ added in v0.12.0
func (v *RegistryView) ToolNames() []string
ToolNames returns the tools visible through the view.
func (*RegistryView) ValidateManifestContract ¶ added in v0.12.0
func (v *RegistryView) ValidateManifestContract(requiredNames []string) error
ValidateManifestContract validates required tools against this view.
type RegistryViewSnapshot ¶ added in v0.12.0
type RegistryViewSnapshot struct {
ID string `json:"id"`
ToolNames []string `json:"tool_names"`
RequiredToolNames []string `json:"required_tool_names"`
ManifestDigest string `json:"manifest_digest"`
PolicyDigest string `json:"policy_digest,omitempty"`
Reason string `json:"reason"`
Owner string `json:"owner"`
}
RegistryViewSnapshot is the serializable identity of a registry view.
type RegistryViewSpec ¶ added in v0.12.0
type RegistryViewSpec struct {
ToolNames []string
RequiredToolNames []string
Reason string
Owner string
Policy Policy
PolicyID string
}
RegistryViewSpec describes a durable capability view over a root registry.
type RequirementsDecisionFunc ¶ added in v0.12.0
type RequirementsDecisionFunc[TSubject, TScope any] func( context.Context, RequirementsPolicyRequest[TSubject, TScope], ) Decision
RequirementsDecisionFunc evaluates manifest requirements against a typed subject/scope.
type RequirementsPolicyRequest ¶ added in v0.12.0
type RequirementsPolicyRequest[TSubject, TScope any] struct { Manifest ToolManifest Requirements ToolRequirements Input ToolInput Context TypedCallContext[TSubject, TScope] View RegistryViewSnapshot }
RequirementsPolicyRequest is the typed request passed to requirements policy.
type ResultCache ¶ added in v0.16.0
type ResultCache struct {
// contains filtered or unexported fields
}
ResultCache is an optional post-authorization execution profile. It offers no atomic dispatch or remote exactly-once guarantee; use an operation journal for those semantics. A successful result is persisted before delivery.
func NewResultCache ¶ added in v0.16.0
func NewResultCache( store ResultCacheStore, eligibility CacheEligibility, partition CachePartition, codec ResultCodec, maxBytes int, ) (*ResultCache, error)
NewResultCache requires explicit eligibility, a host partition and complete outcome codec. maxBytes bounds encoded storage and replay; zero selects a bounded default.
func (*ResultCache) ExecutePrepared ¶ added in v0.16.0
func (c *ResultCache) ExecutePrepared( ctx context.Context, call PreparedCall, invoke InvocationHandler, yield func(Chunk) error, ) error
ExecutePrepared caches exactly one successful result after argument binding.
type ResultCacheStore ¶ added in v0.16.0
type ResultCacheStore interface {
Get(context.Context, string) ([]byte, bool, error)
Put(context.Context, string, []byte) error
}
ResultCacheStore persists encoded successful results, not operation intents.
type ResultCodec ¶ added in v0.16.0
type ResultCodec interface {
EncodeResult(Chunk) ([]byte, error)
DecodeResult([]byte) (Chunk, error)
}
ResultCodec preserves a complete result including host-owned typed values. It must reject values it cannot round-trip without losing delivery semantics.
type ResultContractError ¶ added in v0.17.0
ResultContractError reports an invalid tool output, not correctable arguments. A handler may already have caused effects; this error never authorizes retry. Kind identifies the wire failure or post-handler phase: result_validator, effect_validator, postcondition or result_algebra. Cause retains the original callback error or a description of contradictory result declarations.
func (*ResultContractError) Error ¶ added in v0.17.0
func (e *ResultContractError) Error() string
func (*ResultContractError) Unwrap ¶ added in v0.17.0
func (e *ResultContractError) Unwrap() error
type ResultValidator ¶ added in v0.10.0
ResultValidator validates typed results after the handler and before marshaling. Failures become noncorrectable ResultContractError values, preserving the cause.
type RunEnv ¶ added in v0.8.0
type RunEnv struct {
Credentials CredentialsProvider
StateStore StateStore
// contains filtered or unexported fields
}
RunEnv is the per-call execution environment: credentials, persisted state store, keyed dependencies (deps), and optional binding to a Session for in-memory state.
func NewRunEnv ¶ added in v0.8.0
func NewRunEnv(session *Session, opts ...RunEnvOption) *RunEnv
NewRunEnv creates a run environment. When session is non-nil, SetState and GetState delegate to that session's in-memory state. session may be nil for DI-only usage.
func (*RunEnv) Attachments ¶ added in v0.8.0
func (e *RunEnv) Attachments() []Attachment
Attachments returns runtime attachments for the current call (cloned).
func (*RunEnv) CallContext ¶ added in v0.12.0
func (e *RunEnv) CallContext() CallContext
CallContext returns the typed execution context bound to this environment.
func (*RunEnv) RegistryViewSnapshot ¶ added in v0.12.0
func (e *RunEnv) RegistryViewSnapshot() RegistryViewSnapshot
RegistryViewSnapshot returns the capability view bound to the current execution, if any.
type RunEnvOption ¶ added in v0.8.0
type RunEnvOption func(*RunEnv)
RunEnvOption configures NewRunEnv.
func WithCredentials ¶ added in v0.8.0
func WithCredentials(p CredentialsProvider) RunEnvOption
WithCredentials sets the credentials provider on the environment.
func WithRunCallContext ¶ added in v0.16.0
func WithRunCallContext(call CallContext) RunEnvOption
WithRunCallContext binds trusted host identity to a direct tool invocation. This does not authenticate model data or replace Registry/Session policy and budgets. Adapters must use their supplied scoped executor, not direct dispatch.
func WithRunExecutionProfile ¶ added in v0.16.0
func WithRunExecutionProfile(profile ExecutionProfile) RunEnvOption
WithRunExecutionProfile installs a profile for direct Tool.Execute calls.
func WithStateStore ¶ added in v0.8.0
func WithStateStore(s StateStore) RunEnvOption
WithStateStore sets the persisted state store on the environment.
type RunPolicy ¶ added in v0.7.0
RunPolicy describes session-level catalog requirements and call selection. Enforcement is applied only by Session.Execute, not by Registry.Execute. Use Registry.View for static capability scoping at registry level.
Semantics:
- ForcedTool: every Execute must target this tool name.
- AllowedTools: when non-empty, Execute tool name must be in this whitelist.
- CatalogRequiredTools: these names must exist in the visible session catalog at construction; this does not require calling them or restrict call selection.
type SchemaConfig ¶ added in v0.5.5
type SchemaConfig struct {
Strict bool
Registry *SchemaRegistry
}
SchemaConfig contains JSON Schema generation settings for typed tools/extractors.
type SchemaProvider ¶ added in v0.10.0
SchemaProvider supplies a JSON Schema map for dynamic tools.
type SchemaRegistry ¶ added in v0.5.5
type SchemaRegistry struct {
// contains filtered or unexported fields
}
SchemaRegistry stores custom type to JSON Schema mappings for typed builders/extractors.
func NewSchemaRegistry ¶ added in v0.5.5
func NewSchemaRegistry() *SchemaRegistry
NewSchemaRegistry creates an empty schema registry.
func (*SchemaRegistry) RegisterType ¶ added in v0.5.5
func (r *SchemaRegistry) RegisterType(emptyInstance any, jsonType, format string)
RegisterType registers a custom Go type to be mapped to a JSON Schema type/format in generated schemas. emptyInstance is a value of the type to register (for example, a UUID or money value); it must not be nil. jsonType is the JSON Schema type (e.g. "string", "number"); it must not be empty. format is optional (e.g. "uuid", "decimal"). Registration is by reflect.TypeOf(emptyInstance). Pointer fields (*T) use the same mapping as T; call RegisterType once for the value type.
type Session ¶ added in v0.5.5
type Session struct {
// contains filtered or unexported fields
}
Session is a stateful, concurrency-safe executor built on top of a stateless registry.
func NewSession ¶ added in v0.5.5
func NewSession(reg *Registry, opts ...SessionOption) (*Session, error)
NewSession creates a session bound to reg and freezes its codec registry after run-policy/registry validation. Register every codec before creating a session; use a new codec registry to define a different schema.
func NewSessionFromCheckpoint ¶ added in v0.13.0
func NewSessionFromCheckpoint(reg *Registry, checkpoint SessionCheckpoint, opts ...SessionOption) (*Session, error)
NewSessionFromCheckpoint creates a session and imports a state+binding checkpoint. The supplied options define current authority/budget; previous RunPolicy and execution counts are not restored. Codec registration is finalized by NewSession even if subsequent checkpoint validation/hydration fails.
func (*Session) Binding ¶ added in v0.13.0
func (s *Session) Binding() SessionBinding
Binding returns the current execution binding for this session.
func (*Session) Execute ¶ added in v0.5.5
Execute runs one tool call through the session budget tracker. When call.Env is non-nil, it must be created with NewRunEnv(s) for this session (see ValidateRunEnvSession). call.Env may be nil for DI-only paths. Optional state reads report a missing value; required SetState writes return an error without a usable session. Use NewRunEnv(s) when tools require session state.
func (*Session) ExecuteIter ¶ added in v0.5.5
ExecuteIter runs one tool call and returns an iterator over (Chunk, error) pairs.
func (*Session) ExportCheckpoint ¶ added in v0.13.0
func (s *Session) ExportCheckpoint() (SessionCheckpoint, error)
ExportCheckpoint exports state together with the binding required to resume it safely.
func (*Session) ExportSnapshot ¶ added in v0.10.0
func (s *Session) ExportSnapshot() (SessionSnapshot, error)
ExportSnapshot returns an opaque snapshot of in-memory session state. Dependencies, attachments, and StateStore are not included. The state map and execution binding are captured before encoding. Host codecs and MarshalJSON callbacks run without state/configuration locks. Referenced values must remain immutable while encoding; the library does not deep-copy host-owned types.
func (*Session) ImportSnapshot ¶ added in v0.10.0
func (s *Session) ImportSnapshot(snap SessionSnapshot) error
ImportSnapshot atomically replaces in-memory session state from snap. On hydration error the library does not replace the state map. Host callback side effects, including explicit state writes during decode, are not rolled back.
func (*Session) Rebind ¶ added in v0.13.0
Rebind atomically moves this session to a compatible registry/view without rebuilding state. In-flight calls keep their captured registry; subsequent calls see the published configuration. Registry/manifest callbacks run without a configuration lock.
func (*Session) RunCall ¶ added in v0.10.0
RunCall executes one tool call and returns an aggregated ToolOutcome. Business failures are returned as (outcome, nil) with outcome.ExecutionError set. Infrastructure failures return (outcome with OutcomeInfrastructureError, err), including structured error chunks from WithErrorFormatter when the decoded ToolError.Code is an orchestrator/infra code. Control-plane signals return (outcome, err) with partial Progress/Controls preserved. Multiple non-error EventResult chunks overwrite Result (last wins).
func (*Session) Track ¶ added in v0.5.5
func (s *Session) Track() *SessionTrack
Track returns the session execution track.
type SessionBinding ¶ added in v0.13.0
type SessionBinding struct {
View RegistryViewSnapshot `json:"view"`
ToolNames []string `json:"tool_names"`
ManifestDigest string `json:"manifest_digest"`
PolicyDigest string `json:"policy_digest,omitempty"`
StateSchemaDigest string `json:"state_schema_digest,omitempty"`
}
SessionBinding describes the registry/view/state schema boundary a session is bound to.
type SessionCheckpoint ¶ added in v0.13.0
type SessionCheckpoint struct {
Binding SessionBinding `json:"binding"`
Snapshot SessionSnapshot `json:"snapshot"`
}
SessionCheckpoint is a state+binding checkpoint, not a full workflow continuation. It excludes RunPolicy, call limits/counts, dependencies and external effects. Hosts restore current authority and durable budgets explicitly.
type SessionOption ¶ added in v0.5.5
type SessionOption func(*sessionOptions)
SessionOption configures a Session.
func WithMaxCalls ¶ added in v0.18.0
func WithMaxCalls(n int) SessionOption
WithMaxCalls limits outer session call admissions. Zero is unlimited; negatives fail NewSession. CallAttempts also includes attempts rejected by this limit.
func WithRunPolicy ¶ added in v0.7.0
func WithRunPolicy(p RunPolicy) SessionOption
WithRunPolicy attaches session-level tool choice constraints enforced before each Execute.
func WithStateCodecRegistry ¶ added in v0.10.0
func WithStateCodecRegistry(r *StateCodecRegistry) SessionOption
WithStateCodecRegistry supplies a codec builder for snapshot encode/decode. NewSession finalizes registration by freezing this shared registry after constructor validation. Configure all slots before creating any session.
func WithStrictStateCodecs ¶ added in v0.10.1
func WithStrictStateCodecs(strict bool) SessionOption
WithStrictStateCodecs requires every imported/exported session state key to have a registered StateCodec. Empty snapshots are allowed; unknown JSON null values fail because there is no slot policy to authorize clearing.
type SessionSnapshot ¶ added in v0.10.0
type SessionSnapshot struct {
// contains filtered or unexported fields
}
SessionSnapshot is an opaque, versioned session state blob for persistence.
func NewSessionSnapshotFromJSON ¶ added in v0.10.0
func NewSessionSnapshotFromJSON(data []byte) (SessionSnapshot, error)
NewSessionSnapshotFromJSON parses snapshot bytes from storage.
func (SessionSnapshot) Binding ¶ added in v0.13.0
func (s SessionSnapshot) Binding() SessionBinding
func (SessionSnapshot) MarshalJSON ¶ added in v0.10.0
func (s SessionSnapshot) MarshalJSON() ([]byte, error)
MarshalJSON serializes the snapshot for persistence.
func (*SessionSnapshot) UnmarshalJSON ¶ added in v0.10.0
func (s *SessionSnapshot) UnmarshalJSON(data []byte) error
UnmarshalJSON restores snapshot from JSON storage.
type SessionTrack ¶ added in v0.5.5
type SessionTrack struct {
// contains filtered or unexported fields
}
SessionTrack stores session-level call admission state.
func (*SessionTrack) CallAttempts ¶ added in v0.18.0
func (t *SessionTrack) CallAttempts() int64
CallAttempts counts outer Execute/RunCall admissions, including budget rejection, subsequent environment/registry/argument errors, cancellation and replay. A nil registry or RunPolicy rejection consumes nothing. Internal retries count once.
func (*SessionTrack) MaxCalls ¶ added in v0.18.0
func (t *SessionTrack) MaxCalls() int64
MaxCalls returns the configured call admission limit. Zero means unlimited.
type StandardCallParser ¶ added in v0.8.0
type StandardCallParser struct{}
StandardCallParser is the default CallParser implementation.
func (StandardCallParser) ExtractExactlyOne ¶ added in v0.8.0
func (StandardCallParser) ExtractExactlyOne(parts []ContentPart, toolName string) ([]byte, error)
ExtractExactlyOne returns merged JSON arguments for exactly one tool_call matching toolName. Parts with the same non-empty ContentPart.ToolCallID are merged (Args + ArgsChunk).
type StateCodec ¶ added in v0.10.0
StateCodec encodes and decodes a typed session state value.
type StateCodecRegistry ¶ added in v0.10.0
type StateCodecRegistry struct {
// contains filtered or unexported fields
}
StateCodecRegistry builds session state codecs. NewSession freezes it after constructor validation; every session sharing it then uses one stable schema. Codec implementations remain host-owned and must be safe for concurrent calls.
func NewStateCodecRegistry ¶ added in v0.10.0
func NewStateCodecRegistry() *StateCodecRegistry
NewStateCodecRegistry creates an empty codec registry.
func (*StateCodecRegistry) Freeze ¶ added in v0.18.0
func (r *StateCodecRegistry) Freeze()
Freeze finalizes this builder's schema. It is safe to repeat and to race with registration: an entry either completes before freeze or registration fails. To change a schema, build a new registry. Nil is the absence of registered codecs.
func (*StateCodecRegistry) RegisterFromPrototype ¶ added in v0.10.0
func (r *StateCodecRegistry) RegisterFromPrototype(key string, prototype any, opts ...StateSlotOption) error
RegisterFromPrototype registers a JSON codec using the concrete type of prototype.
type StateSlotOption ¶ added in v0.13.0
type StateSlotOption func(*stateSlotOptions)
StateSlotOption configures a registered state slot.
func WithStateSlotNullable ¶ added in v0.13.0
func WithStateSlotNullable(nullable bool) StateSlotOption
WithStateSlotNullable allows explicit JSON null to be decoded by the slot codec.
func WithStateSlotRequired ¶ added in v0.13.0
func WithStateSlotRequired() StateSlotOption
WithStateSlotRequired marks a state slot as required during snapshot export and import.
func WithStateSlotSchemaID ¶ added in v0.13.0
func WithStateSlotSchemaID(id string) StateSlotOption
WithStateSlotSchemaID pins a host-owned schema version into session binding compatibility.
type StateSlotPolicy ¶ added in v0.13.0
StateSlotPolicy controls export and import semantics for a registered state slot.
type StateStore ¶ added in v0.5.5
type StateStore interface {
Save(ctx context.Context, key string, data []byte) error
Load(ctx context.Context, key string) ([]byte, error)
}
StateStore stores tool execution state outside the tool process.
type StreamContractError ¶ added in v0.16.0
StreamContractError identifies a failed stream delivery/validation contract. Handler effects may already have happened; this error never authorizes retry.
func (*StreamContractError) Error ¶ added in v0.16.0
func (e *StreamContractError) Error() string
func (*StreamContractError) Unwrap ¶ added in v0.16.0
func (e *StreamContractError) Unwrap() error
type StreamSemantics ¶ added in v0.16.0
type StreamSemantics string
StreamSemantics is an explicit contract, never inferred from MIME.
const ( StreamIndependent StreamSemantics = "independent_results" StreamTerminal StreamSemantics = "terminal_result" )
type Tool ¶
type Tool interface {
// Manifest returns tool definition for orchestrators and LLM adapters.
Manifest() ToolManifest
// Execute runs the tool and streams chunks via yield. The tool may call yield
// once (simple response) or multiple times (streaming). If yield returns an error,
// execution must stop and that error is returned (wrapped as ErrStreamAborted).
Execute(ctx context.Context, env *RunEnv, input ToolInput, yield func(Chunk) error) error
}
Tool is the contract for an LLM-callable instrument. It is provider-agnostic (no knowledge of OpenAI, Anthropic, etc.).
func AsAsyncTool ¶ added in v0.4.1
func AsAsyncTool(baseTool Tool, opts ...AsyncOption) Tool
AsAsyncTool wraps a standard Tool to execute its core logic in a background goroutine, immediately returning an AsyncAccepted chunk to the caller. If the client's yield returns an error (e.g. stream closed), the goroutine is not started (yield-guard).
WARNING: Do not manually wrap the result of AsAsyncTool with middleware (e.g. WithBudget(AsAsyncTool(base))). Middleware applied that way runs only during the synchronous accept path and does not observe background work.
CORRECT USAGE: register async tools via RegistryBuilder:
builder.Use(WithBudget).Add(AsAsyncTool(base)).Build()
RegistryBuilder.Build unwraps the tool, applies Use() middleware inside the background goroutine, and re-wraps it safely. For direct Execute without a registry, wrap middleware around the base tool before AsAsyncTool. Nested AsAsyncTool(AsAsyncTool(...)) is invalid and rejected at RegistryBuilder.Build (including when manual middleware wraps nested async tools before Add). Manual middleware before Add must implement ChainUnwrapper. Direct Execute without a registry does not re-check nesting.
When executed via Registry, the registry injects an async tracker via *RunEnv; the background job is tracked so Registry.Shutdown waits for it to finish.
func NewDynamicToolFromSpec ¶ added in v0.10.0
func NewDynamicToolFromSpec(spec DynamicToolSpec) (Tool, error)
NewDynamicToolFromSpec creates a Tool from DynamicToolSpec.
func NewPolicyTool ¶ added in v0.13.0
func NewPolicyTool[TSubject, TScope, TArgs any](spec ToolPolicySpec[TSubject, TScope, TArgs]) (Tool, error)
NewPolicyTool builds a production-ready generic tool without host-local policy wrappers.
func NewPolicyToolFromSpec ¶ added in v0.13.0
func NewPolicyToolFromSpec[TSubject, TScope, TArgs any]( spec ToolPolicyConstructorSpec[TSubject, TScope, TArgs], ) (Tool, error)
NewPolicyToolFromSpec builds a policy-aware generic tool without first exposing a bare tool.
func NewProxyTool ¶ added in v0.3.1
func NewProxyTool( name, description string, rawJSONSchema []byte, handler func(ctx context.Context, env *RunEnv, rawArgs []byte, yield func(Chunk) error) error, opts ...ToolOption, ) (Tool, error)
NewProxyTool creates a Tool from a raw JSON Schema (e.g. from an MCP server) and a handler that receives validated raw args and yield func(Chunk) error. No Go struct reflection; schema is used only for validation. rawJSONSchema and handler must be non-nil.
func NewStreamTool ¶ added in v0.3.0
func NewStreamTool[T any]( name, description string, fn func(ctx context.Context, env *RunEnv, args T, yield func(Chunk) error) error, opts ...ToolOption, ) (Tool, error)
NewStreamTool builds a Tool from a typed streaming function that also receives *RunEnv.
Unlike NewTool, stream tools do not have a single typed result type R, so ToolManifest.OutputSchema is not generated automatically. Set it with WithOutputSchema for final JSON results. Callers must explicitly select WithTerminalStream or WithIndependentStream; MIME does not select semantics.
func NewTool ¶
func NewTool[T any, R any]( name, description string, fn func(ctx context.Context, env *RunEnv, args T) (R, error), opts ...ToolOption, ) (Tool, error)
NewTool builds a low-level Tool from a typed function that also receives *RunEnv.
For production agent execution prefer NewTypedTool with ArgsBinder or wrap generic tools with NewPolicyTool. NewTool is a low-level helper for tools that do not need canonical args binding or typed policy.
Example ¶
type Args struct {
City string `json:"city" jsonschema:"City name"`
}
type Out struct {
Temp float64 `json:"temp"`
}
tool, err := NewTool(
"weather",
"Get temperature for a city",
func(_ context.Context, _ *RunEnv, _ Args) (Out, error) {
return Out{Temp: 22.5}, nil
},
)
if err != nil {
return
}
m := tool.Manifest()
_ = m.Name
_ = m.Description
_ = m.Parameters
func NewTypedTool ¶ added in v0.10.0
func NewTypedTool[TSubject, TScope, TArgs, TResult, TEffect any]( spec TypedToolSpec[TSubject, TScope, TArgs, TResult, TEffect], ) (Tool, error)
NewTypedTool builds a Tool from TypedToolSpec with native raw validation, typed decode, policy binding, result validation, effect validation, and stable error mapping.
func OverrideTool ¶ added in v0.4.1
func OverrideTool(base Tool, opts ...OverrideOption) Tool
OverrideTool returns a tool that delegates to base but overrides manifest fields.
type ToolAudience ¶ added in v0.13.0
type ToolAudience string
ToolAudience describes the intended consumer of a tool payload.
const ( AudienceModel ToolAudience = "model" AudienceUser ToolAudience = "user" AudienceInternal ToolAudience = "internal" )
type ToolCall ¶
type ToolCall struct {
ToolName string
Input ToolInput
Env *RunEnv
CallContext CallContext
}
ToolCall is a single execution request (as produced by the LLM).
type ToolConfig ¶ added in v0.5.5
type ToolConfig struct {
Schema SchemaConfig
Manifest ToolManifest
}
ToolConfig is the internal split configuration for a tool.
type ToolDeliveryClass ¶ added in v0.13.0
type ToolDeliveryClass string
ToolDeliveryClass tells downstream renderers how technical the payload is.
const ( DeliveryClassStructured ToolDeliveryClass = "structured" DeliveryClassText ToolDeliveryClass = "text" DeliveryClassBinary ToolDeliveryClass = "binary" )
type ToolEnvelope ¶ added in v0.13.0
type ToolEnvelope struct {
Kind ToolEnvelopeKind
Error *ToolError
DeliveryClass ToolDeliveryClass
Audience ToolAudience
Raw []byte
MimeType string
Result any
Metadata map[string]any
}
ToolEnvelope is the typed result/error delivery contract for downstream inspection.
func NewErrorEnvelope ¶ added in v0.13.0
func NewErrorEnvelope( err *ToolError, raw []byte, mimeType string, deliveryClass ToolDeliveryClass, audience ToolAudience, metadata map[string]any, ) *ToolEnvelope
NewErrorEnvelope builds a typed error envelope.
func NewResultEnvelope ¶ added in v0.13.0
func NewResultEnvelope( result any, raw []byte, mimeType string, deliveryClass ToolDeliveryClass, audience ToolAudience, metadata map[string]any, ) *ToolEnvelope
NewResultEnvelope builds a typed success envelope.
type ToolEnvelopeKind ¶ added in v0.13.0
type ToolEnvelopeKind string
ToolEnvelopeKind classifies a delivered tool payload without inspecting JSON shape.
const ( ToolEnvelopeKindResult ToolEnvelopeKind = "result" ToolEnvelopeKindError ToolEnvelopeKind = "error" )
type ToolError ¶ added in v0.8.0
type ToolError struct {
Code ErrorCode
Retryable bool
Reason string
FixableArgs []string
SafeMessage string
Err error
}
ToolError is the structured execution error envelope for orchestrator routing. Use AsToolError and errors.Is on [Err] for sentinel checks.
func AsToolError ¶ added in v0.8.0
AsToolError returns a *ToolError when err is or wraps one.
func NewBudgetExceededError ¶ added in v0.10.0
NewBudgetExceededError reports a token or execution budget denial.
func NewCapabilityDeniedError ¶ added in v0.12.0
func NewCapabilityDeniedError(toolName string, view RegistryViewSnapshot) *ToolError
NewCapabilityDeniedError reports a tool call outside the active capability view.
func NewDependencyMissingError ¶ added in v0.8.0
NewDependencyMissingError reports a missing or nil typed dependency.
func NewInternalError ¶ added in v0.8.0
NewInternalError wraps an internal failure as ToolError. Technical details are available via ToolError.Unwrap; ToolError.Reason is generic.
func NewJSONParseError ¶ added in v0.8.0
NewJSONParseError reports invalid tool argument JSON with details in ToolError.Unwrap.
func NewMaxCallsExceededError ¶ added in v0.18.0
func NewMaxCallsExceededError() *ToolError
NewMaxCallsExceededError reports session call admission exhaustion.
func NewPolicyDeniedError ¶ added in v0.12.0
NewPolicyDeniedError creates a structured ToolError for policy/capability denial.
func NewPolicyDeniedErrorFrom ¶ added in v0.12.0
NewPolicyDeniedErrorFrom preserves a lower-level authorization cause while exposing policy denial.
func NewRegistryStateError ¶ added in v0.8.0
func NewRegistryStateError() *ToolError
NewRegistryStateError reports uninitialized registry runtime state.
func NewSchemaError ¶ added in v0.8.0
NewSchemaError builds a non-retryable schema or parse ToolError.
func NewShutdownError ¶ added in v0.8.0
func NewShutdownError() *ToolError
NewShutdownError reports registry shutdown.
func NewSnapshotHydrationError ¶ added in v0.10.1
NewSnapshotHydrationError reports a fatal snapshot import/export failure (version mismatch, corrupt payload).
func NewStateCodecMissingError ¶ added in v0.10.1
NewStateCodecMissingError reports a session state key without a registered codec in strict mode.
func NewTimeoutError ¶ added in v0.8.0
NewTimeoutError reports execution timeout; set retryable when the orchestrator may retry.
func NewTimeoutErrorFrom ¶ added in v0.11.2
NewTimeoutErrorFrom reports execution timeout while preserving cause (e.g. context.DeadlineExceeded) in the unwrap chain.
func NewToolNotFoundError ¶ added in v0.8.0
func NewToolNotFoundError() *ToolError
NewToolNotFoundError reports an unknown tool name.
func NewToolNotFoundInSubsetError ¶ added in v0.8.0
NewToolNotFoundInSubsetError reports an unknown tool name when building a registry subset.
func NewToolsContractMissingError ¶ added in v0.8.0
NewToolsContractMissingError reports required tools missing from the registry contract.
func NewValidationError ¶ added in v0.8.0
NewValidationError builds a non-retryable validation ToolError.
func WithSafeMessage ¶ added in v0.8.0
WithSafeMessage sets ToolError.SafeMessage for user-facing or LLM-safe copy.
type ToolInput ¶ added in v0.5.5
type ToolInput struct {
// CallID is the orchestrator/LLM identifier for this tool call.
// It may be empty for non-LLM callers.
CallID string
ArgsJSON []byte
Attachments []Attachment
}
ToolInput is the runtime input envelope for tool execution.
func AdmitInput ¶ added in v0.19.2
AdmitInput checks typed/dynamic constructor inputs through native wrappers. It never calls Execute, policy, authorization, profiles, controls or budgets. Only known native execution wrappers are transparent; ChainUnwrapper alone does not authorize bypassing a custom wrapper. Custom tools must implement InputAdmitter, including any transformation performed by their Execute method. Success returns canonical input, not a PreparedCall or an execution grant. Dispatch must bind and authorize again with its current context and arguments. Callback panics propagate; this boundary does not invoke Registry recovery.
Example ¶
package main
import (
"context"
"fmt"
"github.com/skosovsky/toolsy"
)
func main() {
// Arrange: a host owns the batch and its trusted call context.
ctx := context.Background()
handlers := 0
tool, err := toolsy.NewDynamicToolFromSpec(toolsy.DynamicToolSpec{
Name: "write",
Schema: toolsy.MapSchemaProvider{
"type": "object",
"properties": map[string]any{"text": map[string]any{"type": "string"}},
"required": []string{"text"},
},
Handler: func(_ context.Context, _ *toolsy.RunEnv, _ map[string]any, yield func(toolsy.Chunk) error) error {
handlers++
return yield(toolsy.Chunk{Event: toolsy.EventResult, Data: []byte(`"ok"`), MimeType: toolsy.MimeTypeJSON})
},
})
if err != nil {
panic(err)
}
reg, err := toolsy.NewRegistryBuilder().Add(tool).Build()
if err != nil {
panic(err)
}
runBatch := func(inputs []toolsy.ToolInput) error {
for _, input := range inputs {
if _, admitErr := toolsy.AdmitInput(ctx, tool, toolsy.CallContext{}, input); admitErr != nil {
return admitErr
}
}
for _, input := range inputs {
if executeErr := reg.Execute(
ctx,
toolsy.ToolCall{ToolName: "write", Input: input},
func(toolsy.Chunk) error { return nil },
); executeErr != nil {
return executeErr
}
}
return nil
}
// Act: no handler runs when a later slot fails input validation.
err = runBatch([]toolsy.ToolInput{{ArgsJSON: []byte(`{"text":"first"}`)}, {ArgsJSON: []byte(`{}`)}})
// Assert.
fmt.Println("rejected:", err != nil, "handlers:", handlers)
// Act: dispatch always repeats binding and authorization for the current input.
err = runBatch([]toolsy.ToolInput{{ArgsJSON: []byte(`{"text":"first"}`)}, {ArgsJSON: []byte(`{"text":"second"}`)}})
// Assert.
fmt.Println("accepted:", err == nil, "handlers:", handlers)
}
Output: rejected: true handlers: 0 accepted: true handlers: 2
type ToolManifest ¶ added in v0.5.5
type ToolManifest struct {
StreamSemantics StreamSemantics
StreamMaxBytes int
Name string
Description string
Parameters map[string]any
OutputSchema map[string]any
Tags []string
Version string
Requirements ToolRequirements
CompletionPolicy CompletionPolicy
ReadOnly bool
RequiresConfirmation bool
Dangerous bool
Idempotent bool
}
ToolManifest contains metadata exposed to orchestrators and discovery layers.
type ToolOption ¶
type ToolOption func(*ToolConfig)
ToolOption configures a tool (e.g. WithStrict, WithSchemaRegistry).
func WithCompletionPolicy ¶ added in v0.7.0
func WithCompletionPolicy(policy CompletionPolicy) ToolOption
WithCompletionPolicy sets manifest completion policy for orchestrator routing.
func WithIdempotent ¶ added in v0.7.0
func WithIdempotent() ToolOption
WithIdempotent marks mutating tools as safe to retry with identical arguments.
func WithIndependentStream ¶ added in v0.16.0
func WithIndependentStream() ToolOption
WithIndependentStream selects independent results/progress without a terminal promise. Aggregate consumers must declare their own assembly contract.
func WithOutputSchema ¶ added in v0.8.0
func WithOutputSchema(schema map[string]any) ToolOption
WithOutputSchema sets the executable JSON Schema for successful JSON wire results. Builders compile it at construction and validate before persistence and delivery. It does not validate progress, controls, business errors, empty/noop or text/binary results.
func WithReadOnly ¶ added in v0.4.1
func WithReadOnly() ToolOption
WithReadOnly marks the tool as read-only.
func WithRequirements ¶ added in v0.10.0
func WithRequirements(req ToolRequirements) ToolOption
WithRequirements sets typed declarative requirements on the tool manifest. Enforcement belongs to registry/session policy (see NewRequirementsPolicy).
func WithRequiresConfirmation ¶ added in v0.4.1
func WithRequiresConfirmation() ToolOption
WithRequiresConfirmation marks the tool as requiring human confirmation before execution.
func WithSchemaRegistry ¶ added in v0.5.5
func WithSchemaRegistry(r *SchemaRegistry) ToolOption
WithSchemaRegistry configures the schema registry used for typed schema generation. When omitted, typed builders and extractors create an isolated registry automatically.
func WithStrict ¶
func WithStrict() ToolOption
WithStrict sets strict mode for schema: additionalProperties: false for all objects, and all properties become required. Use for OpenAI Structured Outputs compatibility.
func WithTags ¶
func WithTags(tags ...string) ToolOption
WithTags sets tool tags (metadata for discovery/orchestrator).
func WithTerminalStream ¶ added in v0.16.0
func WithTerminalStream(maxBytes int) ToolOption
WithTerminalStream requires exactly one schema-valid final result and bounds raw output bytes. WithOutputSchema is required. Zero selects a bounded default.
type ToolOutcome ¶ added in v0.10.0
type ToolOutcome struct {
ToolName string
Result []byte
ResultMimeType string
TypedResult any
Envelope ToolEnvelope
EmptyResult bool
Noop bool
Effects []any
Progress []Chunk
Controls []ControlSignal
CompletionPolicy CompletionPolicy
Status OutcomeStatus
ExecutionError *ToolError
}
ToolOutcome aggregates a synchronous tool call result without manual chunk glue.
type ToolPolicyConstructorSpec ¶ added in v0.13.0
type ToolPolicyConstructorSpec[TSubject, TScope, TArgs any] struct { Name string Description string RawJSONSchema []byte Handler func(ctx context.Context, env *RunEnv, rawArgs []byte, yield func(Chunk) error) error Requirements ToolRequirements ArgsBinder ArgsBinder[TArgs] ArgValidator ArgValidator[TArgs] Policy TypedPolicy[TSubject, TScope, TArgs] CallContext func(context.Context, *RunEnv, ToolInput) (CallContext, error) DeliveryClass ToolDeliveryClass Audience ToolAudience EnvelopeMetadata map[string]any Options []ToolOption }
ToolPolicyConstructorSpec builds a policy-aware generic tool in one step.
type ToolPolicySpec ¶ added in v0.13.0
type ToolPolicySpec[TSubject, TScope, TArgs any] struct { Tool Tool Requirements ToolRequirements ArgsBinder ArgsBinder[TArgs] ArgValidator ArgValidator[TArgs] Policy TypedPolicy[TSubject, TScope, TArgs] CallContext func(context.Context, *RunEnv, ToolInput) (CallContext, error) DeliveryClass ToolDeliveryClass Audience ToolAudience EnvelopeMetadata map[string]any }
ToolPolicySpec adds binder/policy/requirements to an existing generic tool.
type ToolRequirements ¶ added in v0.10.0
type ToolRequirements struct {
MemoryAccess MemoryAccess
NeedsSession bool
Permissions []Permission
}
ToolRequirements holds typed declarative requirements for authorization and routing. Registry/session policy can enforce these requirements before execution with NewRequirementsPolicy.
type ToolResult ¶
type ToolResult[TResult, TEffect any] struct { Value TResult Empty bool Noop bool Effects []TEffect Controls []ControlSignal Raw []byte RawMimeType string DeliveryClass ToolDeliveryClass Audience ToolAudience EnvelopeMetadata map[string]any }
ToolResult is the typed result/effects contract returned by production typed tools. Empty and Noop are exclusive statuses without wire bytes; they retain Value. Empty may declare effects; Noop may not. Both may declare controls. Nonempty Raw replaces wire encoding only, preserving Value, and cannot accompany Empty or Noop. RawMimeType requires nonempty Raw; otherwise ordinary Value is encoded as JSON.
func NewEmptyToolResult ¶ added in v0.12.0
func NewEmptyToolResult[TResult, TEffect any]() ToolResult[TResult, TEffect]
NewEmptyToolResult returns a successful result without a wire payload. It may report effects and controls; this does not assert absence of side effects.
func NewNoopToolResult ¶ added in v0.12.0
func NewNoopToolResult[TResult, TEffect any]() ToolResult[TResult, TEffect]
NewNoopToolResult declares no effects and carries no wire payload. Controls and delivery metadata are allowed; this declaration does not prove that an arbitrary host handler performed no external side effect.
func NewToolResult ¶ added in v0.12.0
func NewToolResult[TResult, TEffect any](value TResult) ToolResult[TResult, TEffect]
NewToolResult returns a successful typed result with no effects.
type TruncationOption ¶ added in v0.5.6
type TruncationOption func(*truncationConfig)
TruncationOption configures truncation middleware behavior.
func WithTruncationIncludeJSON ¶ added in v0.5.6
func WithTruncationIncludeJSON(enable bool) TruncationOption
WithTruncationIncludeJSON enables truncation for application/json payloads.
func WithTruncationSuffix ¶ added in v0.5.6
func WithTruncationSuffix(suffix string) TruncationOption
WithTruncationSuffix overrides the suffix appended to truncated text.
type TypedCallContext ¶ added in v0.12.0
type TypedCallContext[TSubject, TScope any] struct { Subject TSubject Scope TScope Metadata CallMetadata Values map[string]any }
TypedCallContext is the compile-time view used by typed tools and typed policy.
func TypedContext ¶ added in v0.12.0
func TypedContext[TSubject, TScope any](c CallContext) (TypedCallContext[TSubject, TScope], error)
TypedContext converts a type-erased CallContext into a compile-time view.
type TypedPolicy ¶ added in v0.12.0
type TypedPolicy[TSubject, TScope, TArgs any] func(context.Context, TypedPolicyRequest[TSubject, TScope, TArgs]) Decision
TypedPolicy validates typed subject/scope/args before handler execution.
type TypedPolicyRequest ¶ added in v0.12.0
type TypedPolicyRequest[TSubject, TScope, TArgs any] struct { Manifest ToolManifest Input ToolInput Context TypedCallContext[TSubject, TScope] Args TArgs BoundArgs ValidatedArgs[TArgs] }
TypedPolicyRequest is the compile-time policy request for typed tools.
type TypedToolSpec ¶ added in v0.10.0
type TypedToolSpec[TSubject, TScope, TArgs, TResult, TEffect any] struct { Name, Description string ArgsBinder ArgsBinder[TArgs] ArgValidator ArgValidator[TArgs] ResultValidator ResultValidator[TResult] EffectValidator EffectValidator[TEffect] Postcondition PostconditionValidator[TResult, TEffect] Policy TypedPolicy[TSubject, TScope, TArgs] Handler func(ctx context.Context, call TypedCallContext[TSubject, TScope], env *RunEnv, args ValidatedArgs[TArgs]) (ToolResult[TResult, TEffect], error) Options []ToolOption }
TypedToolSpec describes a first-class typed tool contract.
type Validatable ¶
type Validatable interface {
Validate() error
}
Validatable is implemented by argument structs that need custom business validation. Called after schema validation and unmarshaling.
type ValidatedArgs ¶ added in v0.13.0
ValidatedArgs is the canonical output of an ArgsBinder.
type Validator ¶ added in v0.4.2
Validator checks JSON arguments before tool execution (e.g. guardrails). If Validate returns an error, execution is aborted and the error is returned to the caller (fail-closed). Applications can wrap external policy engines (e.g. guardy) without coupling toolsy to them.
Validator is reject-only and cannot return canonical args. Use ArgsBinder through NewTypedTool or NewPolicyTool for production agent execution paths.
type WireJSONResult ¶ added in v0.11.0
type WireJSONResult interface {
WireJSON() json.RawMessage
}
WireJSONResult is implemented by tool handler results that are already JSON-encoded for the wire. Bytes must contain exactly one valid JSON value. Supply WithOutputSchema to describe the wire shape; the wrapper Go type is not used to infer that shape.
type YieldSignal ¶ added in v0.7.0
type YieldSignal struct {
Result string
}
YieldSignal asks the host to end its continuation quietly after this call. It is not a successful terminal result or a scheduler instruction.
Source Files
¶
- async.go
- authorizer.go
- builder.go
- call_context.go
- callparser.go
- chunk_decode.go
- chunk_normalize.go
- clone_memo.go
- completion.go
- control.go
- doc.go
- dynamic_spec.go
- envelope.go
- errors.go
- extractor.go
- input_admission.go
- manifest_set.go
- middleware.go
- middleware_budget.go
- middleware_error_formatter.go
- middleware_truncation.go
- operation_contract.go
- operation_profile.go
- operation_reconcile.go
- operation_store.go
- options.go
- outcome.go
- override.go
- policy.go
- policy_tool.go
- prepared_execution.go
- read_helpers.go
- registry.go
- registry_view.go
- requirements.go
- result_cache.go
- result_codec.go
- result_contract.go
- runenv.go
- runpolicy.go
- schema.go
- session.go
- session_binding.go
- state_api.go
- state_codec.go
- stream_contract.go
- tool_error_wire.go
- toolsy.go
- typed_tool.go
- validation.go
- validator_lazy.go
Directories
¶
| Path | Synopsis |
|---|---|
|
adapters
|
|
|
execution/filejournal
Package filejournal provides a local durable operation/approval journal.
|
Package filejournal provides a local durable operation/approval journal. |
|
agents
module
|
|
|
cmd
|
|
|
toolsy-gen
command
Command toolsy-gen generates Go DTOs, handlers, and tool factories from YAML/JSON manifests.
|
Command toolsy-gen generates Go DTOs, handlers, and tool factories from YAML/JSON manifests. |
|
examples
|
|
|
approval_journal
command
approval_journal is a standalone trusted-local-host example, not an agent loop.
|
approval_journal is a standalone trusted-local-host example, not an agent loop. |
|
calculator
command
Package main demonstrates a simple calculator tool with Session.RunCall.
|
Package main demonstrates a simple calculator tool with Session.RunCall. |
|
contract_recovery
command
Example host routing after a typed post-handler contract failure.
|
Example host routing after a typed post-handler contract failure. |
|
full_agent
command
Package main demonstrates multiple tools, ExecuteBatchStream, and streaming with toolsy.
|
Package main demonstrates multiple tools, ExecuteBatchStream, and streaming with toolsy. |
|
generated_presence
command
Code generated by toolsy-gen.
|
Code generated by toolsy-gen. |
|
generated_stream
command
Code generated by toolsy-gen.
|
Code generated by toolsy-gen. |
|
host_dispatch
command
host_dispatch is a provider-neutral host application with a sequential barrier.
|
host_dispatch is a provider-neutral host application with a sequential barrier. |
|
host_dispatch/recipe
Package recipe demonstrates a host-owned sequential dispatch boundary.
|
Package recipe demonstrates a host-owned sequential dispatch boundary. |
|
host_event
command
Host-owned routing of neutral control data.
|
Host-owned routing of neutral control data. |
|
nested_contract
command
|
|
|
run_call
command
Package main demonstrates RunCall, ToolOutcome, and DecodeOutcomeAs.
|
Package main demonstrates RunCall, ToolOutcome, and DecodeOutcomeAs. |
|
session_snapshot
command
Package main demonstrates ExportSnapshot → JSON → ImportSnapshot roundtrip (toolsy v1.0).
|
Package main demonstrates ExportSnapshot → JSON → ImportSnapshot roundtrip (toolsy v1.0). |
|
stream_terminal
command
Package main demonstrates schema-validated streaming export without an agent.
|
Package main demonstrates schema-validated streaming export without an agent. |
|
streaming
command
Package main demonstrates NewStreamTool and chunk-by-chunk streaming with toolsy.
|
Package main demonstrates NewStreamTool and chunk-by-chunk streaming with toolsy. |
|
Package exectool provides a generic LLM-facing code execution tool plus the low-level contracts used by sandbox adapters.
|
Package exectool provides a generic LLM-facing code execution tool plus the low-level contracts used by sandbox adapters. |
|
ext
|
|
|
toolsyotel
module
|
|
|
Package historycodec encodes a narrow transcript representation of tool calls and delivered results.
|
Package historycodec encodes a narrow transcript representation of tool calls and delivered results. |
|
internal
|
|
|
jsonschemax
Package jsonschemax provides lossless JSON Schema compilation for schemas received over wire protocols.
|
Package jsonschemax provides lossless JSON Schema compilation for schemas received over wire protocols. |
|
sandboxfs
Package sandboxfs contains shared helpers for materializing and validating in-memory sandbox workspaces on the host filesystem.
|
Package sandboxfs contains shared helpers for materializing and validating in-memory sandbox workspaces on the host filesystem. |
|
testhttp
Package testhttp supplies connection accounting for public HTTP adapter tests.
|
Package testhttp supplies connection accounting for public HTTP adapter tests. |
|
toolsygen
Package toolsygen generates Go tool wrappers from YAML and JSON manifest files.
|
Package toolsygen generates Go tool wrappers from YAML and JSON manifest files. |
|
mcp
module
|
|
|
Package testutil provides test helpers for toolsy (e.g.
|
Package testutil provides test helpers for toolsy (e.g. |
|
toolkits
|
|
|
httptool
module
|
|
|
internal/format
module
|
|
|
memory
module
|
|
|
rag
module
|
|
|
timetool
module
|
|
|
web
module
|