interaction

package
v0.21.0 Latest Latest
Warning

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

Go to latest
Published: Sep 12, 2026 License: Apache-2.0 Imports: 21 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. ToolSet freezes independent input validators and scheduling classifiers; Definition retains these pure declarations without retaining executable Tools or their backends. Hosts cover declaration identity in deployment digests. 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. A Tool child's input describes only its initial invocation, and its output describes only completion. Resumption belongs to the child's dispatcher protocol; its checkpoint retains the validated input request and Tool-owned continuation.

Interaction requests ordinary Tool and Delegate children only through Framework Effects. One child-call batch owns start confirmations, wait identity, boundary validation, and ordered results for both bindings. Tools refill their bounded window after any child drains; Delegates await their entire batch. Execution snapshots retain this single batch and its policy. Engine owns child 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.

NewSteerSignal supplies additional user messages through the ordinary mailbox. Steering accepted during model or child work applies at the next safe model boundary after the current result batch; it does not preempt a model request or answer a Tool input wait. A parent can deliver the same SignalRequest through agent.SignalChild without another steering protocol.

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. Advertised names must refer to bound deferred Tools, including during restoration. Model preparation errors settle as definite host failures before external work begins.

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. When a Tool child terminates, its Failure propagates unchanged to the parent. Cancellation and timeout diagnostics retain the child identity and termination cause.

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. A nil ctx is invalid and panics; a context without an active Tool call returns ErrToolAdvertisementUnavailable.

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/strategy/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.

Prompt is a Tool-defined JSON value for the consumer; responseSchema governs its answer. ContinuationState is returned only to the requesting Tool through ToolInputContinuationFromContext. The request freezes all three values and holds no Process or wait identity. JSON numbers retain their precision; prompt and continuationState must each fit within one MiB before and after normalization. Use errors.Is with ErrToolInputRequired to classify this control outcome.

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 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() []Artifact

Artifacts returns an independently owned slice of successful Delegate outputs in original model ToolCall order across model calls. Each Artifact is immutable.

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 {
	// ConcurrencyPolicy returns an immutable classifier, frozen at ToolSet
	// construction. It must not retain the Tool or any execution backend,
	// including through a bound method or closure. Nil requires exclusive calls.
	// The classifier receives an admitted invocation and must be deterministic,
	// bounded, side-effect-free, concurrent-safe, and not retain its input.
	// Its identity and captured configuration belong in ConfigurationDigest.
	ConcurrencyPolicy() func(tool.Invocation) (key string, concurrent bool)
}

ConcurrentTool supplies an independent scheduling policy for calls within one model-requested batch. Tools without a policy, 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. It accepts the current Interaction state schema and rejects unknown fields.

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 model capability 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. A nil ctx is invalid and panics before the request is processed.

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 {
	// Exactly one of Model and Streamer is required. The selected capability
	// owns the entire response lifecycle; streaming is accumulated before settlement.
	Model    chat.Model
	Streamer chat.Streamer

	// Observer receives exact model response facts. Nil disables observation.
	// It is separate from Engine Events/Deltas, which describe execution mechanics.
	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 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. A nil context has no attribution.

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) TreeIncarnationID added in v0.21.0

func (m ModelInvocation) TreeIncarnationID() (agent.TreeIncarnationID, bool)

TreeIncarnationID identifies the durable writer activation, when present.

func (ModelInvocation) Valid

func (m ModelInvocation) Valid() bool

type ModelObserver

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

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

ResponseDelta returns an independently owned transport increment.

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

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

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 and a nil context 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 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. A nil context has no attribution.

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) 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) TreeIncarnationID added in v0.21.0

func (t ToolInvocation) TreeIncarnationID() (agent.TreeIncarnationID, bool)

TreeIncarnationID identifies the durable writer activation, when present.

func (ToolInvocation) Valid

func (t ToolInvocation) Valid() bool

type ToolObserver

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

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

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

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

func (t ToolSet) ObservationFailures() ObservationFailureCounts

ObservationFailures returns isolated Tool observer panic counts.

func (ToolSet) Valid

func (t ToolSet) Valid() bool

type ToolSetConfig

type ToolSetConfig struct {
	Name          string
	Description   string
	Tools         []tool.Tool
	DeferredTools []tool.Tool
	// Observer receives exact Tool call facts. Nil disables observation.
	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