interaction

package
v0.16.0 Latest Latest
Warning

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

Go to latest
Published: Sep 9, 2026 License: Apache-2.0 Imports: 20 Imported by: 0

Documentation

Overview

Package interaction provides the model-directed execution Strategy for the Agent Framework.

A Definition owns the serializable working context, bounded model/Tool state machine, exact managed Delegate bindings, typed Delegate Artifacts, and an optional pure completion validator. A Dispatcher owns model I/O. A ToolSet binds ordinary executable Tools to a separate Deployment; the Engine must resolve that exact child binding. Definition allocates an explicit budget to each Tool child and schedules calls within their declared concurrency bounds. Each call owns one Effect, its result, and any input continuation. Completed siblings retain their settlements when another call remains unknown or waits for input. Model context receives the complete results in original call order.

Interaction requests ordinary Tool and Delegate children only through Framework Effects. Engine owns their Process lifecycles. Product conversation history, persistence, application artifact stores, pricing, approval policy, and UI remain outside this Strategy. Direct model calls remain available through package chatclient without constructing an Interaction or Engine.

PendingToolInputs reads current Tool waits from one TreeSnapshot. A response is sent to the returned PendingToolInput.ProcessID, because that child owns its WaitID and continuation independently of its parent and siblings.

Only FinishReasonToolCalls admits Tool and Delegate execution. Length-truncated calls receive model-visible feedback for another bounded model attempt; calls accompanying other finish reasons fail the Process without execution. Restored pending batches must satisfy the same admission rule.

An ordinary Tool error produces a model-visible ToolResult. Host failures, cancellation, deadlines, and panics that produce no definite ToolResult leave the Tool Effect unknown. The Engine retains that identity across tree capture and restoration and requires explicit settlement before execution continues. Terminating the Process retains unresolved identities in its Result; it does not establish that external work failed. Observer callbacks describe attempts and never replace the Engine's authoritative settlement boundary.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrToolAdvertisementUnavailable = errors.New("interaction: tool advertisement unavailable")
	ErrInvalidToolAdvertisement     = errors.New("interaction: invalid tool advertisement")
)
View Source
var (
	ErrInvalidDefinitionConfig = errors.New("interaction: invalid definition configuration")
	ErrInvalidDispatcherConfig = errors.New("interaction: invalid dispatcher configuration")
	ErrInvalidToolSet          = errors.New("interaction: invalid tool set")
	ErrInvalidDelegate         = errors.New("interaction: invalid delegate")
	ErrInvalidArtifact         = errors.New("interaction: invalid artifact")
	ErrInvalidInput            = errors.New("interaction: invalid input")
	ErrInvalidExecutionState   = errors.New("interaction: invalid execution state")
)
View Source
var (
	ErrInvalidToolInputRequest = errors.New("interaction: invalid tool input request")
	ErrToolInputRequired       = errors.New("interaction: tool input required")
)
View Source
var ErrHostFailure = errors.New("interaction: host failure")

ErrHostFailure separates host infrastructure failure from model or tool behavior.

View Source
var ErrInvalidPendingToolInput = errors.New("interaction: invalid pending tool input")
View Source
var ErrInvalidSteer = errors.New("interaction: invalid steer")

Functions

func AdvertiseTools

func AdvertiseTools(ctx context.Context, names ...string) error

AdvertiseTools stages already-bound deferred Tools for model visibility from the next model call onward. The change commits only if the current Tool call succeeds. It never adds executable authority. Names must be exact deferred Tool names; repeated names are idempotent.

func DelegateChildKey

func DelegateChildKey(modelCallSequence uint32, toolCall chat.ToolCall) (agent.ChildKey, error)

DelegateChildKey derives the exact managed ChildKey used for one Delegate ToolCall. Consumers can use the same value to correlate model observation with the child Process without exposing ToolCall to the Kernel.

func HostFailure

func HostFailure(cause error) error

HostFailure marks cause as an Interaction-host failure. A nil cause remains nil, and an already marked error is returned unchanged. A Tool returning this error supplies no definite ToolResult: its Effect remains unknown until the Host explicitly resolves it. Marking an error does not prove that external work failed or authorize replay.

func NewSteerSignal

func NewSteerSignal(id agent.SignalID, messages ...chat.Message) (agent.SignalRequest, error)

NewSteerSignal wraps caller messages as a signal instead of mutating the running conversation. Going through the mailbox is what makes steering deduplicated, ordered, and snapshot-visible, so a resumed Process sees the same guidance the original one did. Steering admitted before a Tool input wait remains pending until the Tool batch settles, including admission during the Step that enters Waiting.

Example
package main

import (
	"fmt"

	"github.com/Tangerg/scope/agent"
	"github.com/Tangerg/scope/agent/interaction"
	"github.com/Tangerg/scope/core/chat"
)

func main() {
	id, err := agent.ParseSignalID("signal:user-correction")
	if err != nil {
		panic(err)
	}
	request, err := interaction.NewSteerSignal(
		id,
		chat.NewUserMessage(chat.NewTextPart("Use the newer requirements.")),
	)
	if err != nil {
		panic(err)
	}
	_, addressesWait := request.WaitID()

	fmt.Println(request.ID(), request.Valid(), addressesWait)
}
Output:
signal:user-correction true false

func NewToolInputResponseSignal

func NewToolInputResponseSignal(
	id agent.SignalID,
	waitID agent.WaitID,
	response json.RawMessage,
) (agent.SignalRequest, error)

NewToolInputResponseSignal addresses an answer to the exact wait that asked for it. Requiring the wait identity is what prevents a late or duplicated response from satisfying a different pause than the one it was written for. It validates JSON only; the Execution checks the authoritative response schema. PendingToolInput.ResponseSignal composes local schema validation with this constructor.

func RequireToolInput

func RequireToolInput(
	prompt json.RawMessage,
	responseSchema json.RawMessage,
	continuationState json.RawMessage,
) error

RequireToolInput validates the request and returns an error matching ErrToolInputRequired. A Tool returns this before external side effects, or after storing enough ContinuationState to prove safe re-entry. A HostFailure, cancellation, or deadline in the same error chain takes precedence: the Effect remains unknown instead of committing an input checkpoint.

Types

type ActiveDelegateChild

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

ActiveDelegateChild is the immutable Interaction-owned attribution of one model ToolCall to its currently active managed child Process. It contains no Engine handle, persistence identity, or Host metadata.

func ActiveDelegateChildrenFromSnapshot

func ActiveDelegateChildrenFromSnapshot(
	snapshot agent.ProcessSnapshot,
) (children []ActiveDelegateChild, found bool, err error)

ActiveDelegateChildrenFromSnapshot interprets only Interaction-owned state. A valid snapshot without an active Interaction Delegate segment returns found=false. Returned children preserve model ToolCall order.

func (ActiveDelegateChild) ChildKey

func (a ActiveDelegateChild) ChildKey() agent.ChildKey

ChildKey returns the parent-scoped logical child identity.

func (ActiveDelegateChild) ModelCallSequence

func (a ActiveDelegateChild) ModelCallSequence() uint32

ModelCallSequence returns the one-based model call that requested the child.

func (ActiveDelegateChild) ProcessID

func (a ActiveDelegateChild) ProcessID() agent.ProcessID

ProcessID returns the Engine-minted child Process identity.

func (ActiveDelegateChild) ToolCall

func (a ActiveDelegateChild) ToolCall() chat.ToolCall

ToolCall returns the exact model ToolCall represented by the child.

func (ActiveDelegateChild) ToolCallIndex

func (a ActiveDelegateChild) ToolCallIndex() uint32

ToolCallIndex returns the zero-based ToolCall position in the model response.

func (ActiveDelegateChild) Valid

func (a ActiveDelegateChild) Valid() bool

type Artifact

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

Artifact is one successful, schema-validated Delegate output. It is identified by the exact Delegate binding, never by a Go runtime type name or an application artifact store.

func (Artifact) Decode

func (a Artifact) Decode[T any]() (T, error)

Decode strictly decodes a's output into T. The output was already validated against the exact Delegate Descriptor before the Artifact was admitted to Interaction state; T is only an edge convenience.

func (Artifact) DelegateName

func (a Artifact) DelegateName() string

DelegateName returns the exact model-facing Delegate name.

func (Artifact) Output

func (a Artifact) Output() agent.Output

Output returns the immutable, schema-validated child output.

type Artifacts

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

Artifacts is an immutable, ordered snapshot of successful Delegate outputs. All returns defensive copies, so a validator cannot mutate Execution state.

func (Artifacts) All

func (a Artifacts) All() []Artifact

All returns Artifacts in original model ToolCall order across model calls.

func (Artifacts) Len

func (a Artifacts) Len() int

Len returns the number of successful Delegate outputs accumulated so far.

type CompletionCandidate

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

CompletionCandidate is the immutable model context and semantic output proposed by an Interaction together with all successful Delegate Artifacts available at that boundary.

func (CompletionCandidate) Artifacts

func (c CompletionCandidate) Artifacts() Artifacts

Artifacts returns the immutable Delegate output snapshot.

func (CompletionCandidate) Output

func (c CompletionCandidate) Output() Output

Output returns an independently owned candidate Output.

func (CompletionCandidate) WorkingContext

func (c CompletionCandidate) WorkingContext() *chat.Request

WorkingContext returns an independently owned copy of the model context preceding this candidate. It is Interaction state, not Host conversation or transcript history, and it does not yet contain the candidate Output.

type CompletionDecision

type CompletionDecision struct {
	// Accepted permits completion with the proposed final semantic output.
	Accepted bool
	// Feedback explains a rejection to the model and is empty when accepted.
	Feedback string
}

CompletionDecision is the explicit result of a CompletionValidator. Accepted=true requires empty Feedback. Accepted=false requires concise, non-empty Feedback that will be appended as a user message before the next model call.

func (CompletionDecision) Valid

func (c CompletionDecision) Valid() bool

type CompletionSource

type CompletionSource string

CompletionSource identifies the semantic value that completed an Interaction. It is Strategy-owned and does not add a Framework lifecycle status.

const (
	// CompletionSourceModelResponse means the model produced a final response
	// without requesting another tool round.
	CompletionSourceModelResponse CompletionSource = "model_response"

	// CompletionSourceDirectToolResults means every call in one model-requested
	// batch targeted a DirectResultTool and returned successfully.
	CompletionSourceDirectToolResults CompletionSource = "direct_tool_results"
)

func (CompletionSource) Valid

func (c CompletionSource) Valid() bool

type CompletionValidator

type CompletionValidator func(candidate CompletionCandidate) (CompletionDecision, error)

CompletionValidator decides whether a model or direct-Tool candidate is a valid semantic completion. It must be bounded, deterministic and side-effect-free: no I/O, clock, randomness, shared mutation or goroutines. A rejected candidate must return actionable Feedback; MaxModelCalls remains the hard bound on retry rounds. Evaluation requiring external work belongs in a managed child Process, not this callback.

type ConcurrentTool

type ConcurrentTool interface {
	// ConcurrencyKey classifies one exact JSON argument document before any Tool
	// in the batch executes. concurrent=false requires exclusive execution;
	// concurrent=true with the same non-empty key serializes calls to that
	// resource. The method must be deterministic, bounded, side-effect-free, and
	// must not retain arguments.
	ConcurrencyKey(invocation tool.Invocation) (key string, concurrent bool)
}

ConcurrentTool is an optional Tool capability declaring which calls are safe to overlap within one model-requested batch. Tools without this capability, or calls returning concurrent=false, execute alone. A non-empty key names a mutually exclusive resource: calls with the same key in that batch never overlap. Cross-Process resource coordination remains the Tool owner's job.

Each call keeps its own Effect and may wait for external input while siblings continue. The limit counts a waiting child as active until its Tool result is complete. Pure scheduling declarations may be reevaluated during recovery.

type Definition

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

Definition is an immutable managed model/Tool-loop definition. It contains no model client or executable Tool; those external capabilities belong to the model Dispatcher and ToolSet child Deployment.

func NewDefinition

func NewDefinition(config DefinitionConfig) (*Definition, error)

NewDefinition freezes the managed contract, delegates, completion policy, and model-call limit for one interaction loop. The provider client and executable Tools remain bound to their external dispatch boundaries.

func (*Definition) Descriptor

func (d *Definition) Descriptor() agent.Descriptor

Descriptor returns the immutable model-visible Definition contract.

func (*Definition) Restore

func (d *Definition) Restore(state agent.ExecutionState) (agent.Execution, error)

Restore recreates an Interaction solely from its opaque state.

func (*Definition) Start

func (d *Definition) Start(input agent.Input) (agent.Execution, error)

Start creates a fresh Interaction from validated caller input.

type DefinitionConfig

type DefinitionConfig struct {
	// Name is the stable qualified Definition name.
	Name string

	// Description states the managed behavior for discovery.
	Description string

	// MaxModelCalls bounds model Effects in one Interaction. It must be positive.
	MaxModelCalls uint32

	// Tools is the frozen ordinary Tool authority. Its Deployment must be
	// available through Engine's exact DeploymentResolver.
	Tools ToolSet

	// ToolBudget is allocated from the parent for each ordinary Tool child.
	// It is required when Tools is present and also bounds input continuations.
	ToolBudget agent.Budget

	// ToolCapabilities is the attenuated authority granted to each Tool child.
	ToolCapabilities agent.CapabilitySet

	// MaxConcurrentToolCalls bounds active calls declared safe to overlap.
	// Zero means one; calls without a concurrency declaration execute alone.
	MaxConcurrentToolCalls int

	// Delegates is the frozen model-visible manifest of exact child
	// Deployments. Names must be unique within this slice and must not collide
	// with ordinary Tools in ToolSet.
	Delegates []Delegate

	// CompletionValidator optionally verifies a proposed final semantic output
	// against the current WorkingContext and accumulated typed Delegate
	// Artifacts. It is a pure Strategy callback whose identity must be covered by
	// the Deployment's ConfigurationDigest. Nil accepts every otherwise valid
	// completion.
	CompletionValidator CompletionValidator
}

DefinitionConfig describes immutable Interaction behavior. MaxModelCalls is required because a model-directed loop must have an explicit local stop condition in addition to Engine-wide Effect and Step limits.

type Delegate

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

Delegate is an immutable, model-visible binding to one exact managed child Deployment. It is a composition value owned by Interaction, not an executable Tool or a second Process-start entry point.

func NewDelegate

func NewDelegate(config DelegateConfig) (Delegate, error)

NewDelegate exposes exactly one child Deployment to the model as a tool. The target is fixed at construction so a model cannot choose which agent to invoke: routing is a host decision, and a model-selected Deployment would be an unbounded authority grant.

func (Delegate) Valid

func (d Delegate) Valid() bool

type DelegateConfig

type DelegateConfig struct {
	// Name is the provider-compatible model Tool name.
	Name string

	// Description tells the model when and why to delegate this work.
	Description string

	// Deployment is the exact child behavior binding. The Delegate retains only
	// its immutable reference and Descriptor schemas.
	Deployment agent.Deployment

	// Budget is permanently allocated from the parent for each invocation.
	Budget agent.Budget

	// Capabilities is the attenuated authority set granted to each child.
	Capabilities agent.CapabilitySet
}

DelegateConfig exposes one exact child Deployment as a model-selectable Interaction capability. Name and Description are written for the model; lifecycle identity and resource authority remain frozen Framework values.

type DirectResultTool

type DirectResultTool interface {
	// ReturnsDirectResult declares whether a successful invocation can terminate
	// Interaction with the ToolResult itself. The answer is read and frozen at
	// ToolSet construction and therefore must not depend on mutable state or
	// perform I/O.
	ReturnsDirectResult() bool
}

DirectResultTool is an optional Tool capability declaring that a successful model-requested batch containing only such tools returns its ordered results directly instead of making another model call. The declaration is frozen by NewToolSet; a panic or capability-resolution error rejects construction.

type Dispatcher

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

Dispatcher executes model calls emitted by an Interaction Execution. Its configuration is immutable after construction; internal observation health counters are concurrency-safe. It may serve Processes concurrently when the supplied Client supports concurrent use.

func NewDispatcher

func NewDispatcher(definition *Definition, config DispatcherConfig) (*Dispatcher, error)

NewDispatcher binds the model boundary to its immutable Interaction manifest. Ordinary Tools run in the separate Deployment supplied by Definition's ToolSet.

func (*Dispatcher) Dispatch

func (d *Dispatcher) Dispatch(
	ctx context.Context,
	request agent.EffectRequest,
	emit agent.DeltaEmitter,
) (agent.Settlement, error)

Dispatch executes one validated Interaction protocol operation and returns a definite owner-defined Signal payload. An error means the external outcome is not provable; Engine therefore records an unknown settlement instead of retrying the operation.

func (*Dispatcher) ObservationFailures

func (d *Dispatcher) ObservationFailures() ObservationFailureCounts

ObservationFailures returns a concurrency-safe snapshot of ModelObserver panics isolated by this Dispatcher. The counts do not alter settlements.

func (*Dispatcher) ReplayPolicy

func (*Dispatcher) ReplayPolicy(effect agent.Effect) agent.ReplayPolicy

ReplayPolicy is deliberately conservative: model calls may incur cost and produce a different answer. Recovery requires explicit Process resolution.

type DispatcherConfig

type DispatcherConfig struct {
	// Client is the single model dependency. Stream mode requires the same value
	// to implement chat.Streamer so call and stream settings cannot diverge.
	Client ModelClient
	// ResponseMode selects complete or streaming model responses.
	ResponseMode ModelResponseMode

	// Observer receives exact model and Tool call facts. It is intentionally
	// separate from Engine Events/Deltas: those describe execution mechanics,
	// while this boundary exposes typed model and Tool semantics.
	Observer ModelObserver

	// ModelContextReducer optionally replaces only the provider-neutral message
	// context at the last safe boundary before each model call. The Dispatcher
	// installs the effective messages back into Interaction recovery state when
	// the call settles, so later calls and checkpoints cannot regrow a reduced
	// context from the pre-reduction Effect payload.
	ModelContextReducer ModelContextReducer
}

DispatcherConfig binds external capabilities for one Deployment.

type Input

type Input struct {
	// Messages is the initial provider-neutral WorkingContext.
	Messages []chat.Message `json:"messages"`

	// Options contains request-specific generation overrides.
	Options chat.Options `json:"options,omitzero"`
}

Input is the complete caller-supplied starting working context. Tools are deliberately absent: a Deployment freezes executable Tools in its Dispatcher so model-visible definitions and executable behavior cannot drift per Process.

func (Input) Validate

func (i Input) Validate() error

type ModelClient

type ModelClient interface {
	// Call invokes the configured model for one complete response.
	Call(ctx context.Context, request *chat.Request) (*chat.Response, error)
}

ModelClient stays consumer-owned so Interaction does not depend on one concrete Core client implementation.

type ModelContextReducer

type ModelContextReducer interface {
	// ReduceModelContext returns the complete messages for the attributed model
	// invocation. The result must be non-empty, valid, and independently owned.
	ReduceModelContext(
		ctx context.Context,
		invocation ModelInvocation,
		request *chat.Request,
	) ([]chat.Message, error)
}

ModelContextReducer owns an optional, provider-neutral reduction immediately before one actual model call. The request is an independently owned snapshot containing the exact Tool manifest and options that the model would receive; implementations may inspect it but return only the complete replacement message sequence, so they cannot change model options or Tool authority. The settlement carries a replacement only when those messages changed. Once consumed, WorkingContext owns the replacement and the mailbox retains only the Signal's content digest and runtime routing facts.

ReduceModelContext must return a definite outcome. A non-nil error means the main model was not called and is settled as a Host failure. Implementations that perform I/O must therefore resolve their own ambiguity before returning.

type ModelInvocation

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

ModelInvocation is the immutable execution attribution of one actual model call. It contains no Engine handle or Host metadata.

func ModelInvocationFromContext

func ModelInvocationFromContext(ctx context.Context) (ModelInvocation, bool)

ModelInvocationFromContext returns the attribution installed only for the duration of an Interaction model call.

func (ModelInvocation) AppliedSteerSignalIDs

func (m ModelInvocation) AppliedSteerSignalIDs() []agent.SignalID

AppliedSteerSignalIDs returns the ordered identities of steer Signals whose messages were first made visible to this exact model request. The returned slice is independently owned. An empty slice means the request applied no new steer input; previously applied messages may still remain in WorkingContext.

func (ModelInvocation) DeploymentRef

func (m ModelInvocation) DeploymentRef() agent.DeploymentRef

DeploymentRef returns the exact Interaction binding that owns the model call.

func (ModelInvocation) EffectID

func (m ModelInvocation) EffectID() agent.EffectID

EffectID returns the stable model Effect identity.

func (ModelInvocation) ModelCallSequence

func (m ModelInvocation) ModelCallSequence() uint32

ModelCallSequence returns the one-based model call position in this Interaction.

func (ModelInvocation) Relation

func (m ModelInvocation) Relation() agent.ProcessRelation

Relation returns the Process tree location that owns the model call.

func (ModelInvocation) StepSequence

func (m ModelInvocation) StepSequence() uint64

StepSequence returns the one-based Process Step that declared the model Effect.

func (ModelInvocation) Valid

func (m ModelInvocation) Valid() bool

type ModelObserver added in v0.16.0

type ModelObserver interface {
	// OnModelResponse receives the complete provider-neutral response after the
	// model boundary settles and before later Interaction work is observed. The
	// response is detached and may be mutated by the observer. Panics are
	// isolated and the callback has no control authority.
	OnModelResponse(ctx context.Context, invocation ModelInvocation, response *chat.Response)
}

ModelObserver receives provider-neutral model responses. Callbacks are observational, must return in bounded time, and have their panics isolated.

type ModelResponseDelta

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

ModelResponseDelta is one validated provider-neutral streaming increment. It is observational and never a source for final Output or restoration.

func ParseModelResponseDelta

func ParseModelResponseDelta(payload json.RawMessage) (ModelResponseDelta, error)

ParseModelResponseDelta strictly decodes an Interaction model Delta payload.

func (ModelResponseDelta) ResponseDelta added in v0.13.0

func (m ModelResponseDelta) ResponseDelta() *chat.ResponseDelta

ResponseDelta returns an independently owned transport increment.

type ModelResponseMode added in v0.13.0

type ModelResponseMode string

ModelResponseMode selects the single model response lifecycle used by a Dispatcher. Streaming is observational; both modes settle the same complete provider-neutral Response.

const (
	ModelResponseComplete ModelResponseMode = ""
	ModelResponseStream   ModelResponseMode = "stream"
)

Complete mode receives one response; stream mode accumulates response events before settling the same complete response contract.

func (ModelResponseMode) Valid added in v0.13.0

func (m ModelResponseMode) Valid() bool

type ObservationFailureCounts

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

ObservationFailureCounts is an immutable snapshot of observer panics isolated by one model Dispatcher or ToolSet. Counts are monotonic and saturate at math.MaxUint64.

func (ObservationFailureCounts) ModelResponsePanics

func (o ObservationFailureCounts) ModelResponsePanics() uint64

func (ObservationFailureCounts) ToolSettledPanics

func (o ObservationFailureCounts) ToolSettledPanics() uint64

func (ObservationFailureCounts) ToolStartedPanics

func (o ObservationFailureCounts) ToolStartedPanics() uint64

type Output

type Output struct {
	// Source identifies which mutually exclusive result field is authoritative.
	Source CompletionSource `json:"source"`

	// ModelResponse is the authoritative accumulated response when Source is
	// CompletionSourceModelResponse.
	ModelResponse *chat.Response `json:"model_response,omitempty"`

	// DirectToolResults preserves model ToolCall order when Source is
	// CompletionSourceDirectToolResults.
	DirectToolResults []chat.ToolResult `json:"direct_tool_results,omitempty"`

	// ModelCalls is the number of model Effects issued by this Interaction.
	ModelCalls uint32 `json:"model_calls"`
}

Output is the final semantic Interaction result. Response is accumulated independently of best-effort stream Delta delivery, so it remains complete after observer loss or snapshot restoration.

func (Output) Validate

func (o Output) Validate() error

type PendingToolInput

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

PendingToolInput is the consumer-facing view of one current Tool input wait. It deliberately excludes Tool continuation state and all application UI, persistence, approval, or actor concepts.

func PendingToolInputs added in v0.16.0

func PendingToolInputs(snapshot agent.TreeSnapshot) ([]PendingToolInput, error)

PendingToolInputs reads every current Tool input wait in a captured tree. The returned order follows the snapshot's Process order. The caller selects a wait explicitly and sends its ResponseSignal to that wait's ProcessID.

func (PendingToolInput) ProcessID added in v0.16.0

func (p PendingToolInput) ProcessID() agent.ProcessID

ProcessID returns the Tool child that must receive the response.

func (PendingToolInput) Prompt

func (p PendingToolInput) Prompt() json.RawMessage

Prompt returns an independently owned Tool-defined JSON prompt.

func (PendingToolInput) ResponseSchema

func (p PendingToolInput) ResponseSchema() json.RawMessage

ResponseSchema returns the authoritative JSON Schema for a response.

func (PendingToolInput) ResponseSignal

func (p PendingToolInput) ResponseSignal(
	id agent.SignalID,
	response json.RawMessage,
) (agent.SignalRequest, error)

ResponseSignal validates response locally against ResponseSchema and returns one WaitID-addressed SignalRequest with caller-supplied deduplication ID.

func (PendingToolInput) Valid

func (p PendingToolInput) Valid() bool

func (PendingToolInput) WaitID

func (p PendingToolInput) WaitID() agent.WaitID

WaitID returns the Engine-minted identity required to address the response.

type ToolInputContinuation

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

ToolInputContinuation is the immutable state and validated external response attached only while re-entering the Tool that requested input.

func ToolInputContinuationFromContext

func ToolInputContinuationFromContext(ctx context.Context) (ToolInputContinuation, bool)

ToolInputContinuationFromContext returns continuation data only for the active resumed Tool call. Ordinary first attempts return false.

func (ToolInputContinuation) Response

func (t ToolInputContinuation) Response() json.RawMessage

Response returns the schema-validated external input.

func (ToolInputContinuation) State

State returns the Tool-owned continuation state captured at suspension.

type ToolInputRequest

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

ToolInputRequest is an immutable Tool request for external input. Prompt is an owner-defined JSON value for a consumer, ResponseSchema is authoritative, and ContinuationState is returned only to the same Tool when input arrives. It contains no Process identity or WaitID; Engine owns those identities.

func NewToolInputRequest

func NewToolInputRequest(
	prompt json.RawMessage,
	responseSchema json.RawMessage,
	continuationState json.RawMessage,
) (ToolInputRequest, error)

NewToolInputRequest lets a tool pause for external input while carrying its own continuation state. The response schema is validated here so an answer can be checked when it arrives; the request holds no Process or wait identity, because those are minted by the Engine and would otherwise be forgeable by a tool. JSON numbers retain their precision; each JSON value must fit within one MiB before and after normalization.

func (ToolInputRequest) ContinuationState

func (t ToolInputRequest) ContinuationState() json.RawMessage

ContinuationState returns opaque state owned by the requesting Tool.

func (ToolInputRequest) Prompt

func (t ToolInputRequest) Prompt() json.RawMessage

Prompt returns an independently owned consumer-facing JSON value.

func (ToolInputRequest) ResponseSchema

func (t ToolInputRequest) ResponseSchema() json.RawMessage

ResponseSchema returns the authoritative JSON Schema for an answer.

func (ToolInputRequest) Valid

func (t ToolInputRequest) Valid() bool

type ToolInputRequiredError

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

ToolInputRequiredError carries one validated, snapshot-safe ToolInputRequest across a Tool boundary. It is control flow, not a failed ToolResult.

func (*ToolInputRequiredError) Error

func (*ToolInputRequiredError) Error() string

func (*ToolInputRequiredError) Unwrap

func (*ToolInputRequiredError) Unwrap() error

type ToolInvocation

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

ToolInvocation is the immutable execution attribution of one actual Tool call. ToolCall is the exact model request being executed.

func ToolInvocationFromContext

func ToolInvocationFromContext(ctx context.Context) (ToolInvocation, bool)

ToolInvocationFromContext returns the attribution installed only for the duration of the exact Interaction Tool call.

func (ToolInvocation) DeploymentRef

func (t ToolInvocation) DeploymentRef() agent.DeploymentRef

DeploymentRef returns the exact ToolSet binding that owns the Tool call.

func (ToolInvocation) EffectID

func (t ToolInvocation) EffectID() agent.EffectID

EffectID returns the stable identity of this individual Tool Effect.

func (ToolInvocation) ModelCallSequence

func (t ToolInvocation) ModelCallSequence() uint32

ModelCallSequence returns the one-based model call that requested the Tool.

func (ToolInvocation) ModelResult

func (t ToolInvocation) ModelResult(output chat.ToolOutput, cause error) (result chat.ToolResult, present bool)

ModelResult maps the executable Tool's Go return values onto the exact provider-neutral ToolResult consumed by Interaction. Invalid output becomes an error ToolResult. present=false means the cause belongs to the host or control plane and must not enter model context.

func (ToolInvocation) Relation

func (t ToolInvocation) Relation() agent.ProcessRelation

Relation returns the Process tree location that owns the Tool call.

func (ToolInvocation) StepSequence

func (t ToolInvocation) StepSequence() uint64

StepSequence returns the one-based Tool child Step that declared this attempt.

func (ToolInvocation) ToolCall

func (t ToolInvocation) ToolCall() chat.ToolCall

ToolCall returns the exact model ToolCall value being executed.

func (ToolInvocation) ToolCallIndex

func (t ToolInvocation) ToolCallIndex() uint32

ToolCallIndex returns the zero-based ToolCall position in the model response.

func (ToolInvocation) Valid

func (t ToolInvocation) Valid() bool

type ToolObserver added in v0.16.0

type ToolObserver interface {
	// OnToolStarted marks the actual external Tool-call boundary; it is not
	// emitted for calls rejected before execution. Concurrently authorized Tool
	// calls may invoke this method in parallel.
	OnToolStarted(ctx context.Context, invocation ToolInvocation)
	// OnToolSettled receives exactly one conclusive or unknown host-boundary
	// outcome for a started Tool call. The ToolResult, when present, is detached;
	// the callback cannot alter the candidate value used for settlement.
	OnToolSettled(ctx context.Context, invocation ToolInvocation, settlement ToolSettlement)
}

ToolObserver receives exact Tool-call facts. Callbacks are observational, must return in bounded time, and have their panics isolated. Tool children may invoke them concurrently when their calls may overlap.

type ToolSet added in v0.16.0

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

ToolSet binds an immutable Tool manifest to one Deployment that executes a single call per child Process. Definition owns scheduling; the child owns its Effect settlement and any input continuation. No model client enters this binding. A zero ToolSet represents the absence of ordinary Tools.

func NewToolSet added in v0.16.0

func NewToolSet(config ToolSetConfig) (ToolSet, error)

NewToolSet freezes Tools and composes the canonical Definition, Dispatcher, and Deployment contracts into a callable Tool collection.

func (ToolSet) Deployment added in v0.16.0

func (t ToolSet) Deployment() agent.Deployment

Deployment returns the exact child binding to include in the Engine's DeploymentResolver alongside any other explicitly referenced children.

func (ToolSet) ObservationFailures added in v0.16.0

func (t ToolSet) ObservationFailures() ObservationFailureCounts

ObservationFailures returns isolated Tool observer panic counts.

func (ToolSet) Valid added in v0.16.0

func (t ToolSet) Valid() bool

type ToolSetConfig added in v0.16.0

type ToolSetConfig struct {
	Name                 string
	Description          string
	Tools                []tool.Tool
	DeferredTools        []tool.Tool
	Observer             ToolObserver
	ImplementationDigest agent.Digest
	ConfigurationDigest  agent.Digest
}

ToolSetConfig freezes ordinary Tool authority and its exact execution binding. The digests cover the executable Tools, optional capabilities, and observer.

type ToolSettlement

type ToolSettlement struct {
	// Result is the exact ordinary Tool result produced by this call.
	Result *chat.ToolResult
	// InputRequired reports that the Tool paused before producing Result.
	InputRequired bool
	// Failure diagnoses an attempt that produced no Result.
	Failure string
	// Unknown reports that the external Tool settlement could not be determined.
	Unknown bool
}

ToolSettlement is the observed outcome of one Tool call attempt. Result is the value produced for the model; it enters the Tool child state only after that Effect settles. InputRequired instead means the Tool returned a continuation request; the Engine has not yet committed its wait. Failure diagnoses an attempt that produced no ordinary ToolResult. Unknown means its external outcome remains unestablished, including host failures, cancellation, deadlines, and panics. Observation never settles the Effect.

Jump to

Keyboard shortcuts

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