toolsy

package module
v0.20.8 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: MIT Imports: 25 Imported by: 8 modules, 9 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

toolsy

Universal AI Tool Engine for Go: build tools from typed handlers, expose JSON Schema to LLM providers, validate arguments, and execute with streaming.

Go Reference Build Status

Go 1.27.1+ · License

Quick start

For ordinary host execution with bound approval and durable replay, see approval_journal. Prepared execution contracts and clear-break migration are documented in execution-contract and migration-task35. Input-number, structure and HTTP policy changes are in migration-task41.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/skosovsky/toolsy"
)

func main() {
	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, err := toolsy.NewTypedTool(toolsy.TypedToolSpec[Subject, Scope, Args, Out, struct{}]{
		Name:        "weather",
		Description: "Get temperature for city",
		Handler: func(
			_ context.Context,
			_ toolsy.TypedCallContext[Subject, Scope],
			_ *toolsy.RunEnv,
			_ toolsy.ValidatedArgs[Args],
		) (toolsy.ToolResult[Out, struct{}], error) {
			return toolsy.NewToolResult[Out, struct{}](Out{Temp: 22.5}), nil
		},
	})
	if err != nil {
		log.Fatal(err)
	}

	reg, err := toolsy.NewRegistryBuilder().Add(tool).Build()
	if err != nil {
		log.Fatal(err)
	}
	view, err := reg.View(toolsy.RegistryViewSpec{
		ToolNames:         []string{"weather"},
		RequiredToolNames: []string{"weather"},
		Reason:            "weather profile",
		Owner:             "agent",
	})
	if err != nil {
		log.Fatal(err)
	}
	sess, err := view.NewSession()
	if err != nil {
		log.Fatal(err)
	}

	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(context.Background(), call)
	if err != nil {
		log.Fatal(err)
	}
	if outcome.ExecutionError != nil {
		log.Fatal(outcome.ExecutionError)
	}
	out, err := toolsy.DecodeOutcomeAs[Out](outcome)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(out.Temp)
}
Sync agent loop

For synchronous host loops, use Session.RunCall + DecodeOutcomeAs instead of manual chunk assembly:

sess, _ := toolsy.NewSession(reg)
call.Env = toolsy.NewRunEnv(sess)
outcome, err := sess.RunCall(ctx, call)
if err != nil { /* infrastructure */ }
if outcome.ExecutionError != nil { /* business — toolsy.AsToolError */ }
result, _ := toolsy.DecodeOutcomeAs[Out](outcome)

See examples/run_call/main.go. Use low-level Registry.Execute only inside streaming adapters or transport glue that must consume chunks directly.

API contracts

Output schemas are executable contracts for successful JSON result bytes. Builders compile schemas before execution and validate before persistence/delivery and on replay. Text/binary, progress, controls, intentional empty/noop and business-error outputs have distinct semantics. Pre-encoded JSON must be valid; formatter wire limits reject oversized values without slicing JSON. See result contract.

  • Tool interface: Manifest() ToolManifest and Execute(ctx, env, input, yield).
  • ToolCall carries Input toolsy.ToolInput and optional CallContext for typed subject/scope.
  • ToolInput contains CallID, ArgsJSON, and optional Attachments.
  • Chunk data-plane: Event, Data, MimeType, IsError, Progress, TypedResult, EmptyResult, Noop, Effects.
  • Chunk control-plane: EventControl + typed ControlSignal (PauseSignal, YieldSignal, HaltSignal, HostEventSignal).
  • Chunk.Event values: EventProgress, EventResult, EventControl.
  • Chunk.RawData is removed.
  • Runtime Registry is immutable. Use RegistryBuilder to add tools and middleware before Build().
  • Production agent handlers: NewTypedTool and NewPolicyToolFromSpec.
  • Existing generic tools can be hardened with NewPolicyTool.
  • Policy-aware generic tools require an ArgsBinder that returns canonical raw bytes for the wrapped raw handler.
  • Low-level constructors: NewTool, NewStreamTool, NewDynamicToolFromSpec, NewProxyTool.

For full native call identity, control barriers and host-owned approval/recovery, see host dispatch, its contract and migration. Real consumer fixtures live in the optional integration module.

Architecture

Core is a stateless tool execution engine: typed manifests, middleware, streaming chunks, call context, registry views, and session policies. External orchestrators own the agent loop, chat persistence, and routing after CompletionPolicy. toolsy executes tools, enforces its configured policy/capability boundary, and emits typed results, effects, and control signals.

Registry setup

Timeouts, retries, and concurrency limits are not configured on the registry. Apply them outside toolsy by wrapping tool execution; see examples/resiliency/main.go (host loop uses Session.RunCall).

The registry recovers panics from tools by default; avoid WithRecovery() in Use() (it runs before the registry hook and is deprecated for registry stacks).

reg, err := toolsy.NewRegistryBuilder().Use(
	toolsy.WithLogging(slog.Default()),
).Add(
	toolA, toolB,
).Build()

The built registry is read-only for runtime calls (Execute, ExecuteIter, ExecuteBatchStream).

Contract scoping and validation
// Lightweight manifest-only check (no Registry.Build required):
ms, err := toolsy.NewManifestSet(toolA, toolB)
if err != nil {
    return err
}
if err := toolsy.ValidateManifestContract(ms, []string{"book_appointment", "list_slots"}); err != nil {
    return err
}

// Capability view: static tool visibility plus optional execution policy.
profileView, err := reg.View(toolsy.RegistryViewSpec{
    ToolNames: []string{"book_appointment", "list_slots"},
    Reason: "booking profile",
    Owner: "agent-profile",
    PolicyID: "booking-profile-policy",
    Policy: toolsy.NewRequirementsPolicy(func(ctx context.Context, req toolsy.RequirementsPolicyRequest[UserSubject, WorkspaceScope]) toolsy.Decision {
        if !req.Context.Subject.Can(req.Requirements.Permissions...) {
            return toolsy.DenyDecision("missing permission", "permissions")
        }
        return toolsy.AllowDecision()
    }),
})
if err != nil {
    return err
}

ms, err := profileView.ManifestSet()
if err != nil {
    return err
}
if err := toolsy.ValidateManifestContract(ms, []string{"book_appointment", "list_slots"}); err != nil {
    return err
}
  • Registry.View: creates a first-class capability object with tool names, manifest set, durable snapshot identity, optional policy, execution enforcement, and shared root lifecycle. Calls to tools outside the view manifest return CodeCapabilityDenied.
  • Subset: view-backed alias for a named tool set. Prefer Registry.View when the scope needs snapshot identity, required tool validation, policy, prompt contract, or restore requirements.
  • ValidateManifestContract: returns *ToolError with CodeToolsContractMissing when required tools are missing (AsToolError + FixableArgs lists missing names). Duplicate names in requiredNames are deduplicated. Works with NewManifestSet or reg.ManifestSet() — no runtime readiness required.
  • ToolNames, Has, GetAllTools, GetTool: map-view introspection only (tool names / membership in the current view). They do not validate runtime readiness; use ValidateManifestContract or Execute before running tools. A nil *Registry is safe for these helpers (empty/false results, no panic).

Capability vs runtime authorization: use Registry.View for which tools a profile may use at all, NewRequirementsPolicy / WithRequirementsPolicy for manifest requirements against typed subject/scope, and typed tool policy for per-call args checks. Root registry policies require a stable policy ID through WithPolicy/WithRequirementsPolicy; that ID is part of SessionBinding for checkpoint/rebind safety.

Shutdown: call Shutdown only on the root registry owner (for example your app on SIGTERM). Registry views share lifecycle: view.Shutdown() stops the entire registry tree, not just one agent request.

Tool manifest and policy fields

ToolManifest contains:

  • Name, Description, Parameters
  • Tags, Version
  • Requirements (ToolRequirements: memory access, session need, permissions)
  • ReadOnly, RequiresConfirmation, Dangerous, Idempotent
  • CompletionPolicy (continue, silent_yield, halt)

Built-in toolkits/* set policy flags (ReadOnly, Dangerous, …) on each tool; toolkits/memory declares ToolRequirements (session + read/write memory). Custom tools should declare WithRequirements, then attach WithRequirementsPolicy("stable-policy-id", ...) or RegistryViewSpec.Policy: NewRequirementsPolicy(...) with a stable PolicyID so registry/session execution enforces requirements before validators and handlers run.

Example:

tool, err := toolsy.NewTypedTool(toolsy.TypedToolSpec[UserSubject, WorkspaceScope, DeleteUserArgs, DeleteUserResult, struct{}]{
	Name:        "delete_user",
	Description: "Delete a user account",
	Handler: func(
		ctx context.Context,
		call toolsy.TypedCallContext[UserSubject, WorkspaceScope],
		env *toolsy.RunEnv,
		args toolsy.ValidatedArgs[DeleteUserArgs],
	) (toolsy.ToolResult[DeleteUserResult, struct{}], error) {
		return deleteUserHandler(ctx, call, env, args.Value)
	},
	Options: []toolsy.ToolOption{
		toolsy.WithDangerous(),
		toolsy.WithRequiresConfirmation(),
		toolsy.WithCompletionPolicy(toolsy.CompletionHalt),
		toolsy.WithRequirements(toolsy.ToolRequirements{
			MemoryAccess: toolsy.MemoryAccessReadWrite,
			Permissions:  []toolsy.Permission{"admin"},
		}),
	},
})
if err != nil {
	return err
}
m := tool.Manifest()
_ = m.ReadOnly
_ = m.RequiresConfirmation

toolsy-gen: Contract-First Generator

toolsy-gen generates typed DTOs, handler interfaces, and New...Tool factories from YAML/JSON manifests for internal core tools.

go run github.com/skosovsky/toolsy/cmd/toolsy-gen ./tools

Clean-break rules (generation fails on violation):

  • Every parameter in parameters.properties must have a non-empty description.
  • Nested objects and nested arrays are unsupported.
  • Unknown or inapplicable JSON Schema keywords are rejected, including references and composition.

DTO types and presence: the normative mapping table covers required/optional fields, nullable unions, root objects and array items. The complete runnable manifest/CLI/handler example shows exact integers, missing versus empty fields and raw nullable values.

Nested objects/arrays are outside this generator subset. Use typed/dynamic constructors with executable nested schemas; see the nested input contract.

Schema validation:

  • Generated factories use the existing bounded schema validator; DTOs have no separate Validate() method.
  • required enforces presence. Empty strings/arrays, zero and false remain valid unless the source schema adds constraints.
  • Parse/validate failures in the factory return *ToolError (CodeValidationFailed / CodeSchemaInvalid) for LLM self-correction.

Stream tools (stream: true):

  • Handler interface uses ExecuteStream(...) iter.Seq2[string, error].
  • Factory returns an ordinary synchronous proxy: caller Execute observes progress, terminal result and errors. Invalid arguments fail before handler dispatch; caller cancellation remains attached.
  • Async execution is explicit host composition using AsAsyncTool(base, WithBackgroundTimeout(...), WithMaxCollectedChunks(...), WithOnComplete(...)). Accepted acknowledges scheduling; background terminal/errors arrive through the completion hook, not the returned caller. See the runnable example and generator recovery/lifecycle contract.

Session state and RunEnv (DI)

In-memory mutable state lives on *Session (SetSessionState, GetSessionState, ExportSnapshot, ImportSnapshot). Registry and binding are one immutable session configuration. Rebind validates and publishes atomically; in-flight Execute/RunCall retain their captured registry, while later calls observe the new configuration. Checkpoints export one binding for both outer metadata and inner snapshot. Codecs and MarshalJSON callbacks run without state/configuration locks; state-map slots are copied before encoding, while referenced host values must remain immutable during encoding. Registry configuration must remain stable after setup. NewSession freezes its StateCodecRegistry: register every slot before constructing the first session. Later registration returns ErrStateCodecRegistryFrozen. Codec callbacks and referenced pointers/maps/slices remain host-owned; callers must synchronize their access. See task41 migration.

SessionCheckpoint persists state plus binding. It excludes RunPolicy, call limits/counts, dependencies, and workflow continuation. Restore supplies current host authority and fresh session counters; durable budgets belong to the host. *RunEnv is shared via ToolCall.Env for DI and handler access:

  • StateStore — persisted key/value state (optional)
  • Put / Require / Lookup — dependencies (deps map, not serialized)
  • SetState / GetState — delegate to the bound Session when NewRunEnv(session) was used

Subject, scope, and request-local policy data belong in ToolCall.CallContext, not in string-keyed RunEnv state:

call.CallContext = toolsy.NewCallContext(
    UserSubject{ID: "u1"},
    WorkspaceScope{ID: "w1"},
)
codecs := toolsy.NewStateCodecRegistry()
_ = toolsy.RegisterJSONCodec[MyState](codecs, "agent")
sess, _ := toolsy.NewSession(reg, toolsy.WithStateCodecRegistry(codecs))
env := toolsy.NewRunEnv(sess, toolsy.WithStateStore(store))
if err := toolsy.Put(env, "db", db); err != nil { return err }
if err := toolsy.SetSessionState(sess, "trace_id", traceID); err != nil { return err } // or SetState(env, ...)

call.Env = env
sess.Execute(ctx, call, yield) // validates env is bound to sess

Put, SetState and SetSessionState return errors for unusable targets or empty keys. Check those results. DI-only environments permit Put but cannot SetState; Session.Execute with Env: nil does not bind a state target automatically. A handler propagating SetState failure reports INTERNAL with ErrMutationConfiguration. Lookup/Get remain optional. Referenced values remain host-owned. See task41 migration.

RunCall (sync agent loops)

For synchronous tool calls, Session.RunCall aggregates chunks into a ToolOutcome:

outcome, err := sess.RunCall(ctx, call)
if err != nil {
    // infrastructure — not found, shutdown, max calls, control signals (partial outcome preserved)
    if toolsy.IsControlError(err) {
        _ = outcome.Controls // Pause/Yield/Halt/HostEvent collected before err
    }
    return err
}
if outcome.ExecutionError != nil {
    // business failure — validation, handler errors (Error-as-Value)
    te, _ := toolsy.AsToolError(outcome.ExecutionError)
    _ = te.Code
    return outcome.ExecutionError
}
if outcome.Status == toolsy.OutcomeEmptySuccess {
    return nil
}
result, err := toolsy.DecodeOutcomeAs[MyResult](outcome)
effects, err := toolsy.DecodeOutcomeEffectsAs[MyEffect](outcome)
_ = effects

Business failures must be read from outcome.ExecutionError, not only err != nil, so progress chunks before the error are preserved. Legacy text error chunks (MimeTypeText + IsError) are normalized to structured wire with CodeInternal; RunCall returns them as infrastructure error with OutcomeInfrastructureError, not outcome.ExecutionError (see migration guide). WithErrorFormatter emits structured ToolError JSON in error chunks; RunCall restores Code / Retryable / FixableArgs.

See docs/migration-task31.md, docs/migration-task28.md, docs/adr/adr-task28-hardening.md, and examples/run_call/main.go.

StateCodecRegistry

Register typed codecs for checkpoint roundtrips:

The first NewSession finalizes the shared registry after constructor validation. Explicit codecs.Freeze() is also available and idempotent. Build a new registry for schema changes. Required slots must be present at export and import; registered non-nullable slots cannot encode JSON null. Custom codecs must honor their roundtrip/schema contract and be safe for concurrent calls. Library map replacement is atomic on import; host callback effects are not rolled back on decode failure.

codecs := toolsy.NewStateCodecRegistry()
if err := toolsy.RegisterJSONCodec[MyState](codecs, "agent"); err != nil {
    return err
}
sess, err := toolsy.NewSession(reg,
    toolsy.WithStateCodecRegistry(codecs),
    toolsy.WithStrictStateCodecs(true),
)
snap, _ := sess.ExportSnapshot()
raw, _ := json.Marshal(snap)
restored, _ := toolsy.NewSessionSnapshotFromJSON(raw)
_ = sess.ImportSnapshot(restored)

See docs/migration-task28.md for strict codecs, error chunk normalization, and snapshot hydration. Runnable snapshot example: examples/session_snapshot/main.go.

ToolInput.Attachments are exposed to handlers as env.Attachments() (cloned per call).

ToolInput.CallID is the orchestrator/LLM tool call identifier used for metadata tagging in Registry/Session execution paths and observability middleware. Direct low-level Tool.Execute(...) does not auto-fill Chunk.CallID.

Conversation compaction

Hosts own conversation retention, token budgets and summarization. Compose contexty in the host when needed; toolsy has no mandatory contexty dependency. The generic toolsy/history package has been removed. See capability mapping and migration. Tool-result transcripts and historycodec remain available independently.

Policy and capability recipe

Use registry policy to stop execution before validators and tool handler code run:

reg, err := toolsy.NewRegistryBuilder(
    toolsy.WithPolicy("dangerous-tool-policy", toolsy.PolicyFunc(func(ctx context.Context, req toolsy.PolicyRequest) toolsy.Decision {
        if req.Manifest.Dangerous {
            return toolsy.DenyDecision("dangerous tool requires a narrower capability")
        }
        return toolsy.AllowDecision()
    })),
).Add(tools...).Build()

Error propagation differs by execution path:

  • Registry.Execute(...) returns middleware/tool error directly.
  • Registry.ExecuteIter(...) emits the error as iterator error.
  • Registry.ExecuteBatchStream(...) converts non-suspend execution failures (including pre-tool failures like missing tool, validator rejection, and shutdown, plus tool/middleware failures) to Chunk{IsError: true, MimeType: MimeTypeToolErrorJSON}, while ErrStreamAborted and context cancellation are returned as errors.

Every call using WithBudget() must supply a valid host BudgetTracker with Put(env, DepKeyBudget, tracker). Missing or malformed dependencies fail closed. WithOptionalBudget() permits intentional absence only. See gate contracts.

Recommended stack for enterprise policies (outer -> inner):

reg, err := toolsy.NewRegistryBuilder().
	Use(
		toolsy.WithTruncation(8000),
		toolsy.WithErrorFormatter(),
		toolsy.WithBudget(),
	).
	Add(tools...).
	Build()

Notes:

  • WithTruncation truncates text/plain and text/markdown by default; application/json truncation is opt-in via WithTruncationIncludeJSON(true).
  • Transient retries, timeouts, and bulkheads belong outside toolsy as execution wrappers. See examples/resiliency/main.go.
  • WithErrorFormatter may convert terminal errors into Chunk{IsError: true} and then return nil (soft error).
  • WithErrorFormatter handles only errors from wrapped tool/middleware execution; pre-tool failures (e.g. ErrToolNotFound, ErrMaxCallsExceeded, shutdown/validator failures) remain hard errors.
  • For call outcomes, inspect the Execute error and result chunks, or use RunCall's ToolOutcome. SessionTrack.CallAttempts counts admission attempts, including budget rejection; it does not classify outcomes.

Control flow (typed suspend/yield)

Tools emit control signals via toolsy.YieldControl:

return toolsy.YieldControl(yield, &toolsy.PauseSignal{Reason: payloadJSON})

Orchestrators should treat ErrPause, ErrYield, ErrHalt, and ErrHostEvent as control-plane outcomes (toolsy.IsControlError), not tool failures. These are host continuation requests; core does not cancel other calls or run a scheduler/UI action. See exact control contract and bounds and host event example. Set manifest policy as a host routing hint after successful completion:

toolsy.WithCompletionPolicy(toolsy.CompletionSilentYield) // or CompletionContinue, CompletionHalt

Authorization and idempotency

  • Registry-level: install WithPolicy(stableID, policy) using PolicyRequest and Decision. For an error-returning host port, construct NewAuthorizerPolicy(authorizer) first and install the returned policy with its stable ID. Explicit nil policies fail construction; omission intentionally installs no optional policy. See policy and budget gates.
  • Result cache: supply a per-attempt host CacheEligibility predicate and create NewResultCache(store, eligibility, partition, codec, maxBytes) and install it with WithExecutionProfile. Binding and current typed policy run before replay; the host provides a trusted freshness partition and complete outcome codec. Idempotent/ReadOnly hints alone never enable reuse. This cache does not guarantee atomic duplicate dispatch. See execution contract.
Typed result representations

ToolResult has explicit payload states. Ordinary Value is JSON encoded; nonempty Raw replaces only its wire representation and retains the typed Value. RawMimeType applies only with nonempty Raw (default application/octet-stream). Empty and Noop omit wire bytes while retaining typed Value and delivery metadata/controls, and are mutually exclusive. Empty may report effects; Noop cannot declare effects. Contradictory declarations return an INTERNAL ResultContractError after the handler, without permission to retry its effects.

Nested json.RawMessage in generated output schemas accepts any JSON value; explicit SchemaRegistry type mappings override that default. Input RawMessage keeps its object default. Top-level RawMessage/custom encoders need WithOutputSchema to constrain their wire shape. Explicit output schemas take precedence; JSON wire bytes are validated without re-encoding arbitrary BYOT values. See task41 migration.

Session tool choice (RunPolicy)

RunPolicy is captured by value: AllowedTools and CatalogRequiredTools slices are copied at option creation and session construction. Register/catalog builders remain stable after setup; caller mutations after capture cannot change admission. AllowedTools and ForcedTool restrict session calls. CatalogRequiredTools requires names in the visible catalog at construction; it does not require calls or act as another whitelist. Direct Registry.Execute does not apply RunPolicy; use Registry.View for static visibility and capability policy.

WithMaxCalls(n) limits outer Execute/RunCall admissions, with zero unlimited and negatives rejected by construction. Track().CallAttempts() counts attempts that pass session selection, including budget rejection, environment/argument errors, cancellation and replay. Policy rejection and nil registry consume nothing. Internal retries count once; nested Session calls count separately. This is a session call limit; the host owns agent iterations and durable budgets. See task41 migration for the API and wire-code break.

sess, err := toolsy.NewSession(reg, toolsy.WithRunPolicy(toolsy.RunPolicy{
	AllowedTools: []string{"weather", "search"},
}))
if err != nil {
	return err
}
err = sess.Execute(ctx, call, yield)

Transcript codec and text utilities

Use github.com/skosovsky/toolsy/historycodec for strict version 2 raw transcripts with explicit delivery/audience and replay metadata. Typed values, effects, controls, runtime context and attachments fail explicitly; project an execution record deliberately before encoding. See supported transcript contract. For complete typed cache/journal persistence use ResultCodec, not the transcript codec. Version 1 is unsupported. Use github.com/skosovsky/toolsy/textprocessor for standalone UTF-8 truncation without a registry. Conversation compaction belongs to the host/contexty — see migration.

Budget middleware

env := toolsy.NewRunEnv(nil)
if err := toolsy.Put(env, toolsy.DepKeyBudget, tracker); err != nil { return err }
call.Env = env
reg.Execute(ctx, call, yield)

Streaming and iteration

  • Execute(ctx, call, yield) for callback streaming.
  • ExecuteIter(ctx, call) for Go 1.23+ for range iteration over (Chunk, error).
  • ExecuteBatchStream(ctx, calls, yield) runs calls in parallel and serializes yield delivery.

Yield errors are converted to ErrStreamAborted.

Async tools

Use AsAsyncTool(base, WithOnComplete(...)) for fire-and-forget execution with immediate accepted result (AsyncAccepted JSON payload in first result chunk).

When registered via RegistryBuilder, global middleware from Use() runs inside the background goroutine (not during the synchronous accept path). Use WithBackgroundTimeout on AsAsyncTool to cap background work independently of the caller context.

Manual middleware applied before RegistryBuilder.Add must implement toolsy.ChainUnwrapper so Build can detect invalid nested AsAsyncTool chains (see ext/toolsyotel for an example).

When async tool is executed via Registry, background jobs are tracked so Shutdown can wait for them to finish. Registry hooks such as WithOnAfterExecute run when the synchronous Execute path returns (for async tools that is usually right after AsyncAccepted), not when background work finishes — use WithOnComplete for background completion.

WithOnComplete buffers chunks in memory for the completion callback (default cap: 1000). Override with WithMaxCollectedChunks(n). The cap applies in the background collector even without WithOnComplete, protecting memory during async execution. When the cap is exceeded, collection stops and ErrAsyncCollectedLimitExceeded is passed to WithOnComplete even if the base tool ignores yield errors. For very chatty streams, raise the limit or consume chunks via synchronous yield instead of relying on the callback buffer.

Note on resiliency with async tools

Background execution uses context.WithoutCancel on the parent context: cancellation and deadlines from the caller (e.g. a short HTTP request from the LLM) do not propagate to the background goroutine, while context.Value (tracing, loggers) still does.

Implications for external executor wrappers:

  • A timeout wrapper around toolsy.AsAsyncTool(tool) limits how long the orchestrator waits for the accepted response (enqueue is usually fast). It does not cap how long the background work runs.
  • To cap background work, use WithBackgroundTimeout on AsAsyncTool, or wrap the base tool before converting it to async.
  • If you also need a short limit on the accept phase, compose both limits explicitly.

MCP integration

The optional toolsy/mcp module pins an official MCP Go SDK commit (see the module contract). Import remote SDK tools into the core registry or export a scoped core view as an SDK server; the two directions are independent and the core has no SDK dependency. Hosts own transports, authentication, scope and connection lifetime. Current core policy, approval and replay boundaries apply to imported and exported execution.

This is a breaking migration with documented SDK precision/lifecycle limitations. See the module contract, migration guide and the independent import / export examples.

The separate agents bridge reports confirmed terminal outcomes and accepted background task references. Hosts own persistence and continuation; see the remote bridge contract.

API and migration reference

Use the current documentation index for execution, result, control, policy, generator and adapter contracts, installation/module alignment, and the task41 migration. Runnable host recipes are listed in the examples index.

Zero-resiliency core

The registry no longer applies default execution timeouts, concurrency limits, built-in retry middleware, or per-tool WithTimeout manifest deadlines. Removed APIs include WithDefaultTimeout, WithMaxConcurrency, WithTimeoutMiddleware, WithIdempotentRetry, ToolOption WithTimeout, and ToolManifest.Timeout. Use context deadlines and external execution wrappers instead; see examples/resiliency/main.go. Caller execution deadlines use the context passed to Run; RunRequest has no timeout field. Backends retain their own collection/cleanup deadlines and resource budgets, so a caller deadline is not a universal hard bound on return. See sandbox deadline/capability policy.

gRPC reflection helpers take an injected grpc.ClientConnInterface (no dial inside toolsy). HTTP toolkits (httptool, web, document) use one owned httptool.SafeDialTransport pool per tool set; configure timeout/TLS through WithHTTPSettings(httptool.ClientSettings{...}). Cleanup-returning factories release owned idle connections at disposal; ordinary factories retain bounded idle expiry. See task41 migration for current settings and lifecycle, docs/migration-task29.md for enterprise toolkit IoC and SSRF unification, and docs/migration-task30.md for fail-closed read I/O (ErrReadLimitExceeded, transport vs display tiers).

Contracts modules

contracts/openapi, contracts/graphql, contracts/grpc return []toolsy.Tool. Each adapter publishes a bounded supported subset and rejects unsupported contracts during discovery. Hosts provide output selections, credentials, connections and business policy. See adapter contracts and generator contract.

Register tools at setup time through builder:

builder := toolsy.NewRegistryBuilder()
builder.Add(openapiTools...)
builder.Add(graphqlTools...)
builder.Add(grpcTools...)
reg, err := builder.Build()

Testing helpers

testutil.MockTool provides configurable ManifestVal and ExecuteFn. testutil.NewTestRegistry(...) builds a registry with test-safe defaults.

Repository verification and release

See verification commands and prerequisites and the shell release runbook. Make discovers all modules and runs with GOWORK=off; CI uses the same lint/unit/integration/e2e commands.

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

Examples

Constants

View Source
const (
	ContentTypeText     = "text"
	ContentTypeToolCall = "tool_call"
)

Content type constants for ContentPart.Type.

View Source
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"
)
View Source
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.

View Source
const DefaultMaxCollectedChunks = 1000

DefaultMaxCollectedChunks is the default cap on chunks buffered during async background execution.

View Source
const DepKeyBudget = "toolsy.budget"

DepKeyBudget is the dependency map key for BudgetTracker used by WithBudget.

View Source
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.

View Source
const MaxControlSignals = 64

MaxControlSignals bounds controls declared on one terminal result.

View Source
const MaxHostEventNameBytes = 128

MaxHostEventNameBytes bounds a host event's ASCII routing name.

View Source
const MimeTypeToolErrorJSON = "application/vnd.toolsy.tool-error+json"

MimeTypeToolErrorJSON carries a structured ToolError envelope in error result chunks.

View Source
const ReplaySourceMetadata = "toolsy.replay_source"

ReplaySourceMetadata identifies library replay provenance. Reducers must not apply replayed effect declarations again; current call correlation is retained.

Variables

View Source
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.

View Source
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.

View Source
var ErrBudgetConfiguration = errors.New("toolsy: invalid budget configuration")

ErrBudgetConfiguration identifies a missing or malformed required budget gate.

View Source
var ErrCapabilityDenied = errors.New("capability denied")

ErrCapabilityDenied is the sentinel for view/capability denial.

View Source
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.

View Source
var ErrMutationConfiguration = errors.New("toolsy: invalid mutation configuration")

ErrMutationConfiguration identifies an unusable target or key for required mutation.

View Source
var ErrOperationProfileConfiguration = errors.New("toolsy: invalid operation profile configuration")

ErrOperationProfileConfiguration identifies invalid operation-profile setup.

View Source
var ErrPolicyConfiguration = errors.New("toolsy: invalid policy configuration")

ErrPolicyConfiguration identifies an explicitly installed invalid policy gate.

View Source
var ErrPolicyDenied = errors.New("policy denied")

ErrPolicyDenied is the sentinel for fail-closed policy/capability denial.

View Source
var ErrStateCodecRegistryFrozen = errors.New("toolsy: state codec registry is frozen")

ErrStateCodecRegistryFrozen reports registration attempted after schema finalization.

View Source
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

func ClientCorrectable(code ErrorCode) bool

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

func DecodeChunkAs[T any](c Chunk) (*T, error)

DecodeChunkAs unmarshals a JSON result chunk into T after validating event and mime type.

func DecodeChunkAsText added in v0.8.0

func DecodeChunkAsText(c Chunk) (string, error)

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

func ErrorChunkSummaryText(c Chunk, execErr error) string

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

func GetSessionState[T any](s *Session, key string) (T, bool)

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

func GetState[T any](env *RunEnv, key string) (T, bool)

GetState returns session-scoped data from the bound Session when present and non-nil.

func IsContextInterrupt added in v0.11.2

func IsContextInterrupt(err error) bool

IsContextInterrupt reports whether err is or wraps a context cancel, deadline, or ErrTimeout.

func IsControlError added in v0.7.0

func IsControlError(err error) bool

IsControlError reports whether err is a control-plane signal error. Diagnostic control causes inside known contract/outcome failures are not signals.

func Lookup added in v0.8.0

func Lookup[T any](env *RunEnv, key string) (T, bool)

Lookup returns a dependency and whether it was present and non-nil.

func MapReadLimitError added in v0.11.2

func MapReadLimitError(err error, maxBytes int) error

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

func MapReadLimitErrorFor(err error, maxBytes int, subject string, hint string) error

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

func MapSandboxReadLimitError(err error) error

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

func MapToolkitCapError(ctx context.Context, op string, maxBytes int, subject, hint string) error

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

func Put[T any](env *RunEnv, key string, val T) error

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

func Require[T any](env *RunEnv, key string) (T, error)

Require returns a dependency or a ToolError with CodeDependencyMissing.

func SetSessionState added in v0.8.1

func SetSessionState[T any](s *Session, key string, val T) error

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

func SetState[T any](env *RunEnv, key string, val T) error

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

func ToolkitContextError(ctx context.Context, op string) error

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

func ValidateRunEnvSession(session *Session, env *RunEnv) error

ValidateRunEnvSession reports when env is not bound to session.

func ValidateRunPolicy added in v0.7.0

func ValidateRunPolicy(p RunPolicy) error

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

type ArgValidator[T any] func(T) error

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

type AsyncAccepted struct {
	Status string `json:"status"`
	TaskID string `json:"task_id"`
}

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

type AsyncCallback func(ctx context.Context, taskID string, chunks []Chunk, err error)

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

type Attachment struct {
	MimeType string
	Data     []byte
}

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

type CallMetadata struct {
	CallID   string
	ToolName string
	ViewID   string
	Tags     []string
}

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

func NewErrorChunkFromErr(err error) Chunk

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

func DenyDecision(reason string, fixableArgs ...string) Decision

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

type EffectValidator[E any] func([]E) error

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 (
	EventProgress EventType = "progress"
	EventResult   EventType = "result"
)
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

func NewExtractor[T any](strict bool) (*Extractor[T], error)

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

func (e *Extractor[T]) ParseAndValidate(argsJSON []byte) (T, error)

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

func (e *Extractor[T]) Schema() map[string]any

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

type HostEventSignal struct {
	Name        string
	PayloadJSON []byte
}

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

type InvocationHandler func(func(Chunk) error) error

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

type MapSchemaProvider map[string]any

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 (*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 (*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

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.

func (*MemoryResultCacheStore) Get added in v0.16.0

func (*MemoryResultCacheStore) Put added in v0.16.0

func (s *MemoryResultCacheStore) Put(_ context.Context, key string, raw []byte) error

type Middleware

type Middleware func(Tool) Tool

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

type OperationStoreError struct {
	Stage string
	Cause error
}

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

func NewRegistry(tools ...Tool) (*Registry, error)

NewRegistry creates an immutable registry from tools with default options.

func (*Registry) Execute

func (r *Registry) Execute(ctx context.Context, call ToolCall, yield func(Chunk) error) error

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

func (r *Registry) ExecuteIter(ctx context.Context, call ToolCall) iter.Seq2[Chunk, error]

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

func (r *Registry) GetAllTools() []Tool

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

func (r *Registry) GetTool(name string) (Tool, bool)

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

func (r *Registry) Has(name string) bool

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

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

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

func (r *Registry) Subset(allowedNames ...string) (*Registry, error)

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

func (r *Registry) ToolNames() []string

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

type RegistryProvider func() (*Registry, error)

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) Execute added in v0.12.0

func (v *RegistryView) Execute(ctx context.Context, call ToolCall, yield func(Chunk) error) error

Execute runs a call through the view.

func (*RegistryView) ExecuteIter added in v0.12.0

func (v *RegistryView) ExecuteIter(ctx context.Context, call ToolCall) iter.Seq2[Chunk, error]

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

type ResultContractError struct {
	Kind  string
	Cause error
}

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

type ResultValidator[R any] func(R) error

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

type RunPolicy struct {
	ForcedTool           string
	CatalogRequiredTools []string
	AllowedTools         []string
}

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

type SchemaProvider interface {
	ParametersSchema() map[string]any
}

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

func (s *Session) Execute(ctx context.Context, call ToolCall, yield func(Chunk) error) error

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

func (s *Session) ExecuteIter(ctx context.Context, call ToolCall) iter.Seq2[Chunk, error]

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

func (s *Session) Rebind(reg *Registry) error

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

func (s *Session) RunCall(ctx context.Context, call ToolCall) (ToolOutcome, error)

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

type StateCodec[T any] interface {
	Encode(T) ([]byte, error)
	Decode([]byte) (T, error)
}

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

type StateSlotPolicy struct {
	Required bool
	Nullable bool
	SchemaID string
}

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

type StreamContractError struct {
	Kind  string
	Cause error
}

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

func AsToolError(err error) (*ToolError, bool)

AsToolError returns a *ToolError when err is or wraps one.

func NewBudgetExceededError added in v0.10.0

func NewBudgetExceededError(reason string) *ToolError

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

func NewDependencyMissingError(key string) *ToolError

NewDependencyMissingError reports a missing or nil typed dependency.

func NewInternalError added in v0.8.0

func NewInternalError(err error) *ToolError

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

func NewJSONParseError(err error) *ToolError

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

func NewPolicyDeniedError(reason string, fixableArgs ...string) *ToolError

NewPolicyDeniedError creates a structured ToolError for policy/capability denial.

func NewPolicyDeniedErrorFrom added in v0.12.0

func NewPolicyDeniedErrorFrom(err error) *ToolError

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

func NewSchemaError(reason string) *ToolError

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

func NewSnapshotHydrationError(reason string, err error) *ToolError

NewSnapshotHydrationError reports a fatal snapshot import/export failure (version mismatch, corrupt payload).

func NewStateCodecMissingError added in v0.10.1

func NewStateCodecMissingError(key string) *ToolError

NewStateCodecMissingError reports a session state key without a registered codec in strict mode.

func NewTimeoutError added in v0.8.0

func NewTimeoutError(retryable bool) *ToolError

NewTimeoutError reports execution timeout; set retryable when the orchestrator may retry.

func NewTimeoutErrorFrom added in v0.11.2

func NewTimeoutErrorFrom(cause error, retryable bool) *ToolError

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

func NewToolNotFoundInSubsetError(name string) *ToolError

NewToolNotFoundInSubsetError reports an unknown tool name when building a registry subset.

func NewToolsContractMissingError added in v0.8.0

func NewToolsContractMissingError(required, missing []string) *ToolError

NewToolsContractMissingError reports required tools missing from the registry contract.

func NewValidationError added in v0.8.0

func NewValidationError(reason string, fixableFields ...string) *ToolError

NewValidationError builds a non-retryable validation ToolError.

func WithSafeMessage added in v0.8.0

func WithSafeMessage(te *ToolError, safe string) *ToolError

WithSafeMessage sets ToolError.SafeMessage for user-facing or LLM-safe copy.

func (*ToolError) Error added in v0.8.0

func (e *ToolError) Error() string

func (*ToolError) Unwrap added in v0.8.0

func (e *ToolError) Unwrap() error

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

func AdmitInput(ctx context.Context, t Tool, call CallContext, in ToolInput) (ToolInput, error)

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

func (ToolInput) Clone added in v0.8.3

func (in ToolInput) Clone() ToolInput

Clone returns a deep copy of in (ArgsJSON backing array and attachment bytes).

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 WithDangerous

func WithDangerous() ToolOption

WithDangerous marks the tool as dangerous.

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.

func WithVersion

func WithVersion(version string) ToolOption

WithVersion sets the tool version.

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

type ValidatedArgs[T any] struct {
	Value    T
	Raw      []byte
	Metadata map[string]any
}

ValidatedArgs is the canonical output of an ArgsBinder.

type Validator added in v0.4.2

type Validator interface {
	Validate(ctx context.Context, toolName string, argsJSON string) error
}

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.

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
memory module
rag module
timetool module
web module

Jump to

Keyboard shortcuts

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