Documentation
¶
Overview ¶
Package agent composes a chat model, executable tools, and policies into a github.com/Tangerg/scope/agent/run.Program with Input and Output. Compile freezes their identities. Use run.Runtime.Run for a foreground call, or run.Runtime.Start with a stable StartID for a managed invocation. Higher-level strategies use the same program as a child. Input and Output carry core/chat values.
A Definition binds immutable model/Tool behavior, exact managed Delegates, and an optional pure completion validator. Each execution owns its serializable working context and state-machine progress. A Dispatcher owns model I/O. A ToolSet binds ordinary executable Tools to a separate child Program that the Definition binds; its scheduling retains only frozen input validators and classifiers, never executable Tools or their backends. Working context and model-call Effects carry only messages and options; the Dispatcher projects executable Tool definitions from the Program. Persisted requests that declare tools or tool_choice are rejected. Hosts cover declaration identity in program digests. Direct model calls remain available through package chatclient without an Interaction or Runtime.
Model-call and child work quotas default to unlimited; a finite zero MaxModelCalls is rejected at construction. Model boundary errors, including nil or structurally invalid responses, leave the Effect Unknown and require explicit Host resolution; chat.ClassifyFailure reads a scoped chat.CallFailure, such as a safeguard input or output rejection, to settle a definite failure. A structurally valid response that violates Interaction constraints terminates with external / interaction.model.invalid_response without retrying the model or committing the rejected Step. Model preparation errors settle as definite host failures before external work begins. ModelObserver retains the whole invocation outcome as succeeded, failed, not_executed, or unknown independently of durable settlement. Valid generation and usage survive failed or uncertain middleware postprocessing; a response never establishes that postprocessing succeeded. Only not_executed proves that the provider performed no work. An unobserved outcome belongs to recordings missing a callback and is never emitted by the Dispatcher.
Only FinishReasonToolCalls admits Tool and Delegate execution. Length-truncated calls receive model-visible feedback for another model attempt; calls accompanying other finish reasons fail the Process without execution. Restored pending batches satisfy the same rule, and advertised names must refer to bound deferred Tools.
Tool and Delegate children are requested 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. Admission progress derives from the ordered invocation records, including retained settlements, so recovery needs no separate scheduling cursor. Each invocation is absent until its start is declared, then the same record retains its start receipt and result without a parallel requested marker. A rejected Tool child start terminates the Interaction with the original Failure, because the ToolSet is required infrastructure. A rejected Delegate start is a model-visible rejected result, because choosing another worker is the model's delegation policy. A Tool child's Failure propagates unchanged to the parent. A drained Delegate subtree with unresolved Effects fails the parent without another model call. A canceled parent never resumes to collect or publish children.
Each Tool call owns one Effect, its result, and any input continuation. Completed siblings retain their settlements when another call remains unknown or waits for input. A valid tool.Failure produces its model-visible error ToolResult and disposition; its Cause cannot turn it into cancellation, input, or host control. Transparent single-cause wrappers preserve that outcome; independent joined errors leave the invocation unknown. Ordinary errors, invalid output, cancellation, deadlines, and a panic from Tool.Call leave the Tool Effect unknown until the Host settles it; terminating the Process retains those identities without establishing that external work failed. A panic from a tool's input validator is instead a definite failure classified before Tool.Call runs: it fails the Step without reaching the model and leaves no unknown Effect. Observer callbacks describe attempts and never replace the Runtime's settlement boundary. A complete round continues to the model or completes directly only after its Checkpoint is acknowledged. Recovery never replays Tools or models: Hosts settle investigated outcomes with ToolSet.SettleToolResult, SettlePreparedContext, or SettleModelResult, using requests retained by github.com/Tangerg/scope/agent/run.TreeSnapshot.EffectRequest, and submit them through run.Handle.ResolveUnknownEffect. Model context receives complete results in original call order. AdvertisingTool projects a successful result through a pure callback. Live declarations are sorted and deduplicated; persisted declarations must already be canonical. An invalid declaration or callback failure retains the completed Tool result and then fails the child with a contract Failure. It never makes known external work unknown or permits replay.
SettledResults projects exact known results from the authoritative tree; it has no storage or acknowledgment role. ToolCallRef correlates one logical call across ToolInvocation.Reference, RoundResults.Reference, and DelegateAttribution.Reference; its ProcessID is the requesting Interaction, not the Tool child. A Tool child's reference comes only from the ToolChildKey its parent gave it, so a ToolSet run as a root or under any other ChildKey has none.
Descriptor.SignalSchema admits only steering envelopes as unaddressed input. NewSteerSignal steering accepted during model or child work applies before the next model call, after the current result batch; it never preempts a model request or answers a Tool input wait. Tool answers address the Tool child's wait through PendingToolInputs. The answer payload is the original response JSON, validated against the unchanged response Schema by that wait; its canonical bytes must also fit tool.MaxInputBytes. Both constraints persist in the wait's opening contract, and a rejected answer leaves that wait open. Schema resources and local references retain their original scope. A parent Strategy delivers the same SignalRequest through run.NewChildSignalEffect. Unsupported envelopes are rejected before admission; semantic protocol violations discard the Step with a contract Failure, and a Step error never consumes input.
Index ¶
- Variables
- func Adapt[I, O any](ctx context.Context, config AdapterConfig[I, O]) (run.Program[I, O], error)
- func Compile(ctx context.Context, cfg Config) (run.Program[Input, Output], error)
- func DelegateChildKey(modelCallSequence uint64, toolCall chat.ToolCall) (run.ChildKey, error)
- func NewSteerSignal(id run.SignalID, messages ...chat.Message) (run.SignalRequest, error)
- func SettleModelResult[I, O any](p run.Program[I, O], req run.EffectRequest, response *chat.Response) (run.Settlement, error)
- func SettlePreparedContext[I, O any](p run.Program[I, O], req run.EffectRequest, messages []chat.Message) (run.Settlement, error)
- func ToolChildKey(modelCallSequence uint64, toolCallIndex uint32) (run.ChildKey, error)
- type AdapterConfig
- type AdvertisingTool
- type Artifact
- type CompletionCandidate
- type CompletionDecision
- type CompletionValidator
- type ConcurrentTool
- type Config
- type ContextFailure
- type ContextInvocation
- type ContextPolicy
- type ContextProcessor
- type Definition
- type DefinitionConfig
- type Delegate
- type DelegateAttribution
- func (d DelegateAttribution) ChildKey() run.ChildKey
- func (d DelegateAttribution) ModelCallSequence() uint64
- func (d DelegateAttribution) ProcessID() run.ProcessID
- func (d DelegateAttribution) Reference() (ToolCallRef, bool)
- func (d DelegateAttribution) ToolCall() chat.ToolCall
- func (d DelegateAttribution) ToolCallIndex() uint32
- func (d DelegateAttribution) Valid() bool
- type DelegateConfig
- type DirectResultTool
- type Dispatcher
- type DispatcherConfig
- type Input
- type ModelInvocation
- func (m ModelInvocation) AppliedSteerSignalIDs() []run.SignalID
- func (m ModelInvocation) AttemptID() (run.EffectAttemptID, bool)
- func (m ModelInvocation) EffectID() run.EffectID
- func (m ModelInvocation) ModelCallSequence() uint64
- func (m ModelInvocation) ProgramRef() run.ProgramRef
- func (m ModelInvocation) Relation() run.ProcessRelation
- func (m ModelInvocation) StepSequence() uint64
- func (m ModelInvocation) TreeIncarnationID() (run.TreeIncarnationID, bool)
- func (m ModelInvocation) Valid() bool
- type ModelObserver
- type ModelOutcome
- type ModelResponseDelta
- type ModelSettlement
- type ObservationFailures
- func (o ObservationFailures) LastModelSettledPanic() (ObserverPanic, bool)
- func (o ObservationFailures) LastModelStartedPanic() (ObserverPanic, bool)
- func (o ObservationFailures) LastToolSettledPanic() (ObserverPanic, bool)
- func (o ObservationFailures) LastToolStartedPanic() (ObserverPanic, bool)
- func (o ObservationFailures) ModelSettledPanics() uint64
- func (o ObservationFailures) ModelStartedPanics() uint64
- func (o ObservationFailures) ToolSettledPanics() uint64
- func (o ObservationFailures) ToolStartedPanics() uint64
- type ObserverPanic
- type Output
- type PendingToolInput
- func (p PendingToolInput) ProcessID() run.ProcessID
- func (p PendingToolInput) Prompt() json.RawMessage
- func (p PendingToolInput) ResponseSchema() json.RawMessage
- func (p PendingToolInput) ResponseSignal(id run.SignalID, response json.RawMessage) (run.SignalRequest, error)
- func (p PendingToolInput) Valid() bool
- func (p PendingToolInput) WaitID() run.WaitID
- type ResultDisposition
- type ResultEntry
- type RoundResults
- func (r RoundResults) CallCount() uint32
- func (r RoundResults) Complete() bool
- func (r RoundResults) Digest() run.Digest
- func (r RoundResults) Entries() []ResultEntry
- func (r RoundResults) JSON() json.RawMessage
- func (r RoundResults) ModelCallSequence() uint64
- func (r RoundResults) Reference(toolCallIndex uint32) (ToolCallRef, bool)
- func (r RoundResults) Relation() run.ProcessRelation
- type ToolCallRef
- func (ToolCallRef) JSONSchemaModel() any
- func (t ToolCallRef) MarshalText() ([]byte, error)
- func (t ToolCallRef) ModelCallSequence() uint64
- func (t ToolCallRef) ProcessID() run.ProcessID
- func (t ToolCallRef) String() string
- func (t ToolCallRef) ToolCallIndex() uint32
- func (t *ToolCallRef) UnmarshalText(text []byte) error
- func (t ToolCallRef) Valid() bool
- type ToolInvocation
- func (t ToolInvocation) AttemptID() (run.EffectAttemptID, bool)
- func (t ToolInvocation) EffectID() run.EffectID
- func (t ToolInvocation) ProgramRef() run.ProgramRef
- func (t ToolInvocation) Reference() (ToolCallRef, bool)
- func (t ToolInvocation) Relation() run.ProcessRelation
- func (t ToolInvocation) StepSequence() uint64
- func (t ToolInvocation) ToolCall() chat.ToolCall
- func (t ToolInvocation) TreeIncarnationID() (run.TreeIncarnationID, bool)
- func (t ToolInvocation) Valid() bool
- type ToolObserver
- type ToolSet
- type ToolSetConfig
- type ToolSettlement
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( ErrInvalidResult = errors.New("interaction: invalid result") ErrInvalidModelSettlement = errors.New("interaction: invalid model settlement") ErrInvalidToolAdvertisement = errors.New("interaction: invalid tool advertisement") ErrInvalidPendingToolInput = errors.New("interaction: invalid pending tool input") ErrInvalidDefinitionConfig = errors.New("interaction: invalid definition configuration") ErrInvalidDispatcherConfig = errors.New("interaction: invalid dispatcher configuration") ErrInvalidToolSet = errors.New("interaction: invalid tool set") ErrInvalidToolCallRef = errors.New("interaction: invalid tool call reference") ErrInvalidDelegate = errors.New("interaction: invalid delegate") ErrInvalidInput = errors.New("interaction: invalid input") )
These sentinels belong to construction, domain values, Dispatcher operations, and Tool control flow rather than Steps, so they carry no Failure classification.
var ( ErrInvalidSteer = run.NewClassifiedError( run.FailureKindContract, "interaction.signal.invalid", "interaction: invalid steer", ) ErrInvalidExecutionState = run.NewClassifiedError( run.FailureKindContract, "interaction.state.invalid", "interaction: invalid execution state", ) ErrInvalidProtocol = run.NewClassifiedError( run.FailureKindContract, "interaction.protocol.invalid", "interaction: invalid protocol payload", ) // ErrInvalidModelResponse rejects the whole Step, so a structurally valid // response that violates Interaction constraints never enters its state. ErrInvalidModelResponse = run.NewClassifiedError( run.FailureKindExternal, "interaction.model.invalid_response", "interaction: invalid model response", ) )
Execution sentinels own the Failure persisted when they reach Step. Wrapping one is the only way a Step error acquires its classification. Protocol and restored-state errors stay distinct because their recovery responsibilities differ.
var ErrInvalidAdapter = errors.New("agent: invalid adapter configuration")
var ErrModelResponseTooLarge = errors.New("interaction: model response exceeds byte limit")
ErrModelResponseTooLarge reports response resource admission failure. After model execution starts, the incomplete response is discarded and its Effect remains unknown. Oversize replacement context is rejected before calling the model and settles as a definite host failure.
Functions ¶
func Adapt ¶ added in v0.59.0
Adapt composes the role into one ordinary run.Program with an I -> O contract, reusing the canonical workflow and interaction atoms.
Example ¶
package main
import (
"context"
jsonv2 "encoding/json/v2"
"errors"
"fmt"
"github.com/Tangerg/scope/agent"
"github.com/Tangerg/scope/agent/run"
"github.com/Tangerg/scope/core/chat"
"github.com/Tangerg/scope/core/chatclient"
)
func main() {
ctx := context.Background()
format := chatclient.JSON[greeting]()
greeter := exampleValue(agent.Adapt(ctx, agent.AdapterConfig[greetRequest, greeting]{
Name: "example.greeter", Description: "Greet a caller by name.",
Interaction: greetDeployment(),
BuildInput: func(_ context.Context, req greetRequest) (agent.Input, error) {
data, err := jsonv2.Marshal(req)
if err != nil {
return agent.Input{}, err
}
return agent.Input{Messages: []chat.Message{chat.NewUserMessage(chat.NewTextPart(string(data)))}}, nil
},
DecodeOutput: func(_ context.Context, output agent.Output) (greeting, error) {
return format.Decode(output.ModelResponse)
},
Budget: run.Budget{Steps: run.NewQuota(16), Effects: run.NewQuota(16), Signals: run.NewQuota(16)},
ImplementationDigest: run.ComputeDigest([]byte("example-greeter")),
ConfigurationDigest: run.ComputeDigest([]byte("example-greeter-config")),
}))
engine := exampleValue(run.New(context.Background(), run.Config{Store: run.NewMemoryStore()}))
defer func() {
if err := engine.Close(ctx); err != nil {
panic(err)
}
}()
output := exampleValue(engine.Run(ctx, greeter, greetRequest{Name: "ada"}))
fmt.Println(output.Message)
}
type greetRequest struct {
Name string `json:"name"`
}
type greeting struct {
Message string `json:"message"`
}
type greetModel struct{}
func (greetModel) Call(_ context.Context, request *chat.Request) (*chat.Response, error) {
var req greetRequest
if err := jsonv2.Unmarshal([]byte(request.Messages[len(request.Messages)-1].Text()), &req); err != nil || req.Name == "" {
return nil, errors.New("greet model received an invalid request")
}
data, err := jsonv2.Marshal(greeting{Message: "hi " + req.Name})
if err != nil {
return nil, err
}
message := chat.NewAssistantMessage(chat.NewTextPart(string(data)))
return chat.NewResponse(&chat.Output{Message: &message, FinishReason: chat.FinishReasonStop}, nil)
}
func greetDeployment() run.Program[agent.Input, agent.Output] {
client := exampleValue(chatclient.New(greetModel{}, chatclient.Config{}))
definition := exampleValue(agent.NewDefinition(agent.DefinitionConfig{
Name: "example.greet", Description: "Produce a greeting from the request.", MaxModelCalls: run.NewQuota(1),
}))
dispatcher := exampleValue(agent.NewDispatcher(definition, agent.DispatcherConfig{Model: client}))
return exampleValue(run.Bind[agent.Input, agent.Output](run.BindingConfig{
Definition: definition, Dispatcher: dispatcher,
ImplementationDigest: run.ComputeDigest([]byte("example-greet")),
ConfigurationDigest: run.ComputeDigest([]byte("example-greet-config")),
}))
}
func exampleValue[T any](value T, err error) T {
if err != nil {
panic(err)
}
return value
}
Output: hi ada
func Compile ¶ added in v0.59.0
Compile freezes the real model loop, binds its child programs and checks its Go input/output against the same schemas used at dispatch and recovery.
func DelegateChildKey ¶ added in v0.59.0
func NewSteerSignal ¶ added in v0.59.0
NewSteerSignal wraps user messages as an unaddressed Signal. The mailbox makes steering deduplicated, ordered, and snapshot-visible, so a resumed Process sees the same guidance. 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/run"
"github.com/Tangerg/scope/core/chat"
)
func main() {
id, err := run.ParseSignalID("signal:user-correction")
if err != nil {
panic(err)
}
request, err := agent.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 SettleModelResult ¶ added in v0.59.0
func SettleModelResult[I, O any](p run.Program[I, O], req run.EffectRequest, response *chat.Response) (run.Settlement, error)
SettleModelResult validates an investigated model response against the exact bound program and original effect. The effective input is already frozen.
func SettlePreparedContext ¶ added in v0.59.0
func SettlePreparedContext[I, O any](p run.Program[I, O], req run.EffectRequest, messages []chat.Message) (run.Settlement, error)
SettlePreparedContext validates investigated messages for a context effect without repeating the processor or the model.
func ToolChildKey ¶ added in v0.59.0
ToolChildKey names the Tool child Process that serves the ToolCall at toolCallIndex in the response to modelCallSequence. The Runtime keeps a ChildKey unique under its parent, so the key, not the child's input, owns the ToolCallRef a Tool child reports.
Types ¶
type AdapterConfig ¶ added in v0.59.0
type AdapterConfig[I, O any] struct { Name string Description string Interaction run.Program[Input, Output] BuildInput func(context.Context, I) (Input, error) // DecodeOutput should reuse an authoritative decode rule, such as // [github.com/Tangerg/scope/core/chatclient.OutputFormat.Decode], so the role // does not grow a second, weaker structured-output rule. DecodeOutput func(context.Context, Output) (O, error) Budget run.Budget // Capabilities is the explicit attenuated grant to the Interaction child. // Its zero value grants no authority. Capabilities run.CapabilitySet ImplementationDigest run.Digest ConfigurationDigest run.Digest }
AdapterConfig binds one agent program to a business input and output through pure adapters. The bound child retains ownership of its model and tool loop.
type AdvertisingTool ¶ added in v0.59.0
type AdvertisingTool interface {
AdvertiseDeferred(ctx context.Context, invocation tool.Invocation, result tool.Result) ([]string, error)
}
AdvertisingTool is a Tool that reveals already-bound deferred Tools to the model after it runs under an Interaction. When a managed call settles with a successful result, the Interaction calls AdvertiseDeferred with that call's invocation and result and makes the returned deferred Tool names visible from the next model call onward. The capability lives in the Tool's type, not in the call context: a Tool that does not implement it never advertises, the same Tool run outside an Interaction has no advertising authority, and a rejected, failed, or input-pending call never reaches AdvertiseDeferred, so its declaration cannot commit. Advertising adds visibility only, never executable authority. Names must be exact deferred Tool names; the Interaction normalizes order and duplicates and rejects any name that is not a bound deferred Tool. AdvertiseDeferred is a bounded, deterministic, side-effect-free projection of invocation and result. External work belongs in Tool.Call. A declaration defect fails the Tool child without retracting its already completed call.
type Artifact ¶ added in v0.59.0
type Artifact struct {
// contains filtered or unexported fields
}
Artifact is one successful, schema-validated Delegate output, identified by its exact Delegate binding rather than a Go type.
func (Artifact) DelegateName ¶ added in v0.59.0
func (Artifact) ModelCallSequence ¶ added in v0.59.0
ModelCallSequence identifies the model call within this Interaction Process. Together with ToolCallID it identifies an Artifact across snapshot restoration.
func (Artifact) Output ¶ added in v0.59.0
Output is already validated against the exact Delegate Descriptor. Its Payload owns typed decoding, without a separate Artifact conversion rule.
func (Artifact) ToolCallID ¶ added in v0.59.0
type CompletionCandidate ¶ added in v0.59.0
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 ¶ added in v0.59.0
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 ¶ added in v0.59.0
func (c CompletionCandidate) Output() Output
Output returns an independently owned candidate Output.
func (CompletionCandidate) WorkingContext ¶ added in v0.59.0
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 ¶ added in v0.59.0
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 ¶ added in v0.59.0
func (c CompletionDecision) Valid() bool
type CompletionValidator ¶ added in v0.59.0
type CompletionValidator func(ctx context.Context, 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; a finite MaxModelCalls remains the hard bound on retry rounds. Evaluation requiring external work belongs in a managed child Process, not this callback. Computation must honor cancellation of the current Step context.
type ConcurrentTool ¶ added in v0.59.0
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 Config ¶ added in v0.59.0
type Config struct {
ContextPolicy ContextPolicy
ContextProcessor ContextProcessor
// ContextIdentity identifies opaque callback configuration; no function is hashed.
ContextIdentity run.Digest
Name string
Description string
BuildIdentity run.Digest
ModelIdentity run.Digest
Model chat.Model
Streamer chat.Streamer
Tools []tool.Tool
DeferredTools []tool.Tool
ToolIdentity run.Digest
// MaxModelCalls is unlimited by default; a finite zero cannot call a model.
MaxModelCalls run.Quota
// ToolBudget grants authority to each ordinary tool child.
ToolBudget run.Budget
ToolCapabilities run.CapabilitySet
MaxConcurrentToolCalls int
MaxResponseBytes int
Delegates []Delegate
}
Config declares a model-and-tool loop. BuildIdentity identifies the exact executable code; ModelIdentity and ToolIdentity identify opaque collaborator settings. Declared policies, manifests and child bindings are hashed here.
type ContextFailure ¶ added in v0.59.0
type ContextFailure struct{ Cause error }
ContextFailure reports a definite rejection by a context processor; an ordinary transport error cannot establish this guarantee.
func (*ContextFailure) Error ¶ added in v0.59.0
func (c *ContextFailure) Error() string
func (*ContextFailure) Unwrap ¶ added in v0.59.0
func (c *ContextFailure) Unwrap() error
type ContextInvocation ¶ added in v0.59.0
type ContextInvocation struct {
Effect run.EffectRequest
Sequence uint64
}
ContextInvocation identifies preparation for a model call. Its Effect is the preparation's own logical operation, not the subsequent model operation.
type ContextPolicy ¶ added in v0.59.0
ContextPolicy is a deterministic, bounded local transformation. It must not perform I/O or retain input. Use ContextProcessor for retrieval or model-based summaries.
type ContextProcessor ¶ added in v0.59.0
type ContextProcessor interface {
PrepareContext(ctx context.Context, invocation ContextInvocation, request *chat.Request) ([]chat.Message, error)
}
ContextProcessor prepares the complete message sequence as a separately committed external effect. An error leaves the effect Unknown unless it is a ContextFailure proving a definite outcome.
type Definition ¶
type Definition struct {
// contains filtered or unexported fields
}
Definition is an immutable managed model/Tool-loop definition. It never calls a model client or an executable Tool: the model Dispatcher owns model I/O, and the ToolSet's child Program, which the Definition holds only as its binding, owns Tool execution.
func NewDefinition ¶ added in v0.59.0
func NewDefinition(config DefinitionConfig) (*Definition, error)
func (*Definition) ChildDeployments ¶ added in v0.41.0
ChildDeployments reports the Tool child binding, when Tools are configured, and every Delegate binding.
func (*Definition) Descriptor ¶
func (d *Definition) Descriptor() run.Descriptor
func (*Definition) Restore ¶
func (d *Definition) Restore(ctx context.Context, state run.ExecutionState) (run.Execution, error)
Restore recreates an Interaction solely from its opaque state. It accepts the current Interaction state schema and rejects unknown fields.
type DefinitionConfig ¶ added in v0.59.0
type DefinitionConfig struct {
// MaxResponseBytes bounds each prepared-context and model-result settlement. Zero uses the runtime payload limit.
MaxResponseBytes int
ContextPolicy ContextPolicy
PrepareContext bool
Name string
Description string
// MaxModelCalls bounds model Effects in one Interaction. Its zero value is
// unlimited; a finite zero is rejected because an Interaction needs a model call.
MaxModelCalls run.Quota
// Tools is the frozen ordinary Tool authority. The Interaction owns its
// Program as one of its ChildDeployments.
Tools ToolSet
// ToolBudget is allocated from the parent for each ordinary Tool child.
// Its quotas also apply to input continuations; zero quotas are unlimited.
ToolBudget run.Budget
// ToolCapabilities is the attenuated authority granted to each Tool child.
ToolCapabilities run.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
// Programs. 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 Program's ConfigurationDigest. Nil accepts every otherwise valid
// completion.
CompletionValidator CompletionValidator
}
DefinitionConfig describes immutable Interaction behavior. Cumulative quotas default to unlimited; the Host retains cancellation and capacity controls.
type Delegate ¶ added in v0.59.0
type Delegate struct {
// contains filtered or unexported fields
}
Delegate is an immutable, model-visible binding to one exact managed child Program. It is a composition value owned by Interaction, not an executable Tool or a second Process-start entry point.
func NewDelegate ¶ added in v0.59.0
func NewDelegate(config DelegateConfig) (Delegate, error)
NewDelegate fixes the target at construction; model selection cannot change its Program, budget, or capabilities.
type DelegateAttribution ¶ added in v0.59.0
type DelegateAttribution struct {
// contains filtered or unexported fields
}
DelegateAttribution is the immutable Interaction-owned attribution of one model ToolCall to the child Process it was delegated to. It is read from the parent's committed tool round, so it persists into terminal snapshots and records only the delegation relationship; it does not assert the child is still running. Deciding whether a child is active requires its runtime status from a same-moment TreeSnapshot. It contains no Runtime handle, persistence identity, or Host metadata.
func DelegateAttributions ¶ added in v0.59.0
func DelegateAttributions( snapshot run.ProcessSnapshot, ) (attributions []DelegateAttribution, found bool, err error)
DelegateAttributions interprets only Interaction-owned committed state and returns the delegation relationships from the parent's tool round in model ToolCall order. A valid snapshot without an Interaction Delegate segment returns found=false. Because it reads committed state, it also reports relationships whose child Processes have since finished or been canceled; callers that need current child liveness must consult a TreeSnapshot.
func (DelegateAttribution) ChildKey ¶ added in v0.59.0
func (d DelegateAttribution) ChildKey() run.ChildKey
ChildKey derives the child's key from the ToolCall that requested it.
func (DelegateAttribution) ModelCallSequence ¶ added in v0.59.0
func (d DelegateAttribution) ModelCallSequence() uint64
ModelCallSequence returns the one-based model call that requested the child.
func (DelegateAttribution) ProcessID ¶ added in v0.59.0
func (d DelegateAttribution) ProcessID() run.ProcessID
func (DelegateAttribution) Reference ¶ added in v0.59.0
func (d DelegateAttribution) Reference() (ToolCallRef, bool)
func (DelegateAttribution) ToolCall ¶ added in v0.59.0
func (d DelegateAttribution) ToolCall() chat.ToolCall
func (DelegateAttribution) ToolCallIndex ¶ added in v0.59.0
func (d DelegateAttribution) ToolCallIndex() uint32
ToolCallIndex returns the zero-based ToolCall position in the model response.
func (DelegateAttribution) Valid ¶ added in v0.59.0
func (d DelegateAttribution) Valid() bool
type DelegateConfig ¶ added in v0.59.0
type DelegateConfig struct {
// Name is the provider-compatible model Tool name.
Name string
Description string
// Deployment is the exact child program. An Interaction
// configured with this Delegate owns it as one of its ChildDeployments.
Deployment run.Program[run.Payload, run.Payload]
// Budget is permanently allocated from the parent for each invocation.
Budget run.Budget
Capabilities run.CapabilitySet
}
DelegateConfig exposes one exact child Program 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 ¶ added in v0.59.0
type DirectResultTool interface {
// ReturnsDirectResult is read once by NewToolSet; it 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. It is immutable after construction and may serve Processes concurrently when the supplied model capability supports concurrent use.
func NewDispatcher ¶ added in v0.59.0
func NewDispatcher(definition *Definition, config DispatcherConfig) (*Dispatcher, error)
func (*Dispatcher) Dispatch ¶
func (d *Dispatcher) Dispatch( ctx context.Context, request run.EffectRequest, emit run.DeltaEmitter, ) (run.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; Runtime 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 ¶ added in v0.59.0
func (d *Dispatcher) ObservationFailures() ObservationFailures
ObservationFailures returns a concurrency-safe snapshot of ModelObserver panics isolated by this Dispatcher. The counts do not alter settlements.
func (*Dispatcher) Policy ¶ added in v0.44.0
func (*Dispatcher) Policy(_ run.Effect) run.EffectPolicy
Policy forbids model replay and requires no capabilities.
type DispatcherConfig ¶ added in v0.59.0
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.
Observer ModelObserver
// ContextProcessor optionally replaces the message context immediately
// before each model call. Nil sends WorkingContext unchanged.
ContextProcessor ContextProcessor
}
type Input ¶
type Input struct {
Messages []chat.Message `json:"messages"`
Options chat.Options `json:"options,omitzero"`
}
Input excludes executable Tools: the Program fixes their ToolSet authority.
type ModelInvocation ¶ added in v0.59.0
type ModelInvocation struct {
// contains filtered or unexported fields
}
ModelInvocation is the immutable execution attribution of one actual model call. It contains no Runtime handle or Host metadata.
func ModelInvocationFromContext ¶ added in v0.59.0
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 ¶ added in v0.59.0
func (m ModelInvocation) AppliedSteerSignalIDs() []run.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) AttemptID ¶ added in v0.59.0
func (m ModelInvocation) AttemptID() (run.EffectAttemptID, bool)
AttemptID identifies this physical invocation. Logical requests retained in snapshots have no attempt identity until the Runtime dispatches them again.
func (ModelInvocation) EffectID ¶ added in v0.59.0
func (m ModelInvocation) EffectID() run.EffectID
func (ModelInvocation) ModelCallSequence ¶ added in v0.59.0
func (m ModelInvocation) ModelCallSequence() uint64
ModelCallSequence returns the one-based model call position in this Interaction.
func (ModelInvocation) ProgramRef ¶ added in v0.59.0
func (m ModelInvocation) ProgramRef() run.ProgramRef
func (ModelInvocation) Relation ¶ added in v0.59.0
func (m ModelInvocation) Relation() run.ProcessRelation
func (ModelInvocation) StepSequence ¶ added in v0.59.0
func (m ModelInvocation) StepSequence() uint64
StepSequence returns the one-based Process Step that declared the model Effect.
func (ModelInvocation) TreeIncarnationID ¶ added in v0.59.0
func (m ModelInvocation) TreeIncarnationID() (run.TreeIncarnationID, bool)
TreeIncarnationID identifies the durable writer activation, when present.
func (ModelInvocation) Valid ¶ added in v0.59.0
func (m ModelInvocation) Valid() bool
type ModelObserver ¶ added in v0.59.0
type ModelObserver interface {
// OnModelStarted receives the effective request after context reduction and
// local admission, immediately before calling the model. It is detached.
OnModelStarted(ctx context.Context, invocation ModelInvocation, request *chat.Request)
// OnModelSettled receives exactly one host-boundary outcome for a started
// call, including cancellation, invalid responses and panics. A valid
// response is observed before settlement encoding and capacity admission;
// a later admission failure does not retract this response fact.
OnModelSettled(ctx context.Context, invocation ModelInvocation, settlement ModelSettlement)
}
ModelObserver receives provider-neutral model attempts. Callbacks are observational, must return in bounded time, and have their panics isolated.
type ModelOutcome ¶ added in v0.59.0
type ModelOutcome string
ModelOutcome belongs to the complete model invocation, including middleware. Unobserved belongs only to a recording missing its settlement callback; it is never an emitted ModelSettlement. Failed does not establish token use.
const ( ModelOutcomeInvalid ModelOutcome = "" ModelOutcomeSucceeded ModelOutcome = "succeeded" ModelOutcomeFailed ModelOutcome = "failed" ModelOutcomeNotExecuted ModelOutcome = "not_executed" ModelOutcomeUnknown ModelOutcome = "unknown" ModelOutcomeUnobserved ModelOutcome = "unobserved" )
func (ModelOutcome) Valid ¶ added in v0.59.0
func (m ModelOutcome) Valid() bool
type ModelResponseDelta ¶ added in v0.59.0
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 ¶ added in v0.59.0
func ParseModelResponseDelta(payload json.RawMessage) (ModelResponseDelta, error)
func (ModelResponseDelta) ResponseDelta ¶ added in v0.59.0
func (m ModelResponseDelta) ResponseDelta() *chat.ResponseDelta
ResponseDelta returns an independently owned transport increment.
type ModelSettlement ¶ added in v0.59.0
type ModelSettlement struct {
Outcome ModelOutcome `json:"outcome"`
Response *chat.Response `json:"response,omitzero"`
Failure string `json:"failure,omitzero"`
}
ModelSettlement describes the model invocation, independently of durable Effect settlement. Outcome belongs to that complete invocation. Response retains validated generation even when postprocessing failed or is unknown; its presence never proves middleware success. A later durable admission failure cannot retract it. Only NotExecuted establishes no provider work ran.
func (ModelSettlement) Validate ¶ added in v0.59.0
func (m ModelSettlement) Validate() error
type ObservationFailures ¶ added in v0.18.0
type ObservationFailures struct {
// contains filtered or unexported fields
}
ObservationFailures snapshots panics isolated by one Dispatcher or ToolSet. Counts saturate at math.MaxUint64. Only the latest panic per callback is kept; editing a returned diagnostic cannot change the retained evidence.
func (ObservationFailures) LastModelSettledPanic ¶ added in v0.59.0
func (o ObservationFailures) LastModelSettledPanic() (ObserverPanic, bool)
func (ObservationFailures) LastModelStartedPanic ¶ added in v0.59.0
func (o ObservationFailures) LastModelStartedPanic() (ObserverPanic, bool)
func (ObservationFailures) LastToolSettledPanic ¶ added in v0.59.0
func (o ObservationFailures) LastToolSettledPanic() (ObserverPanic, bool)
func (ObservationFailures) LastToolStartedPanic ¶ added in v0.59.0
func (o ObservationFailures) LastToolStartedPanic() (ObserverPanic, bool)
func (ObservationFailures) ModelSettledPanics ¶ added in v0.59.0
func (o ObservationFailures) ModelSettledPanics() uint64
func (ObservationFailures) ModelStartedPanics ¶ added in v0.59.0
func (o ObservationFailures) ModelStartedPanics() uint64
func (ObservationFailures) ToolSettledPanics ¶ added in v0.59.0
func (o ObservationFailures) ToolSettledPanics() uint64
func (ObservationFailures) ToolStartedPanics ¶ added in v0.59.0
func (o ObservationFailures) ToolStartedPanics() uint64
type ObserverPanic ¶ added in v0.59.0
type ObserverPanic struct {
ObserverType string
ProcessID run.ProcessID
EffectID run.EffectID
AttemptID run.EffectAttemptID
Message string
Stack string
}
ObserverPanic is a detached diagnostic for one isolated callback failure. Message retains at most 4 KiB of the formatted panic value and Stack retains at most 64 KiB of the failing goroutine's stack. ProcessID and EffectID bind the failure to the exact invocation without retaining its request or response.
type Output ¶
type Output struct {
ModelResponse *chat.Response `json:"model_response,omitzero"`
// DirectToolResults preserves model ToolCall order.
DirectToolResults []chat.ToolResult `json:"direct_tool_results,omitempty"`
// ModelCalls is the number of model Effects issued by this Interaction.
ModelCalls uint64 `json:"model_calls"`
}
Output is the final semantic Interaction result. Exactly one completion is present: ModelResponse when the model produced a final response without requesting another tool round, or DirectToolResults when every call in one model-requested batch targeted a DirectResultTool and returned successfully. ModelResponse is accumulated independently of best-effort stream Delta delivery, so it remains complete after observer loss or snapshot restoration.
type PendingToolInput ¶ added in v0.59.0
type PendingToolInput struct {
// contains filtered or unexported fields
}
PendingToolInput is the consumer-facing view of one current Tool input wait. It excludes the Tool's continuation state.
func PendingToolInputs ¶ added in v0.59.0
func PendingToolInputs(snapshot run.TreeSnapshot) ([]PendingToolInput, error)
PendingToolInputs reads every current Tool input wait in a captured tree, including while Paused. An answer clears the wait; only Resume releases a pause. 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.59.0
func (p PendingToolInput) ProcessID() run.ProcessID
ProcessID returns the Tool child that must receive the response.
func (PendingToolInput) Prompt ¶ added in v0.59.0
func (p PendingToolInput) Prompt() json.RawMessage
Prompt returns an independently owned Tool-defined JSON prompt.
func (PendingToolInput) ResponseSchema ¶ added in v0.59.0
func (p PendingToolInput) ResponseSchema() json.RawMessage
func (PendingToolInput) ResponseSignal ¶ added in v0.59.0
func (p PendingToolInput) ResponseSignal( id run.SignalID, response json.RawMessage, ) (run.SignalRequest, error)
ResponseSignal validates response locally against ResponseSchema and returns one WaitID-addressed SignalRequest with caller-supplied deduplication ID.
func (PendingToolInput) Valid ¶ added in v0.59.0
func (p PendingToolInput) Valid() bool
func (PendingToolInput) WaitID ¶ added in v0.59.0
func (p PendingToolInput) WaitID() run.WaitID
type ResultDisposition ¶ added in v0.59.0
type ResultDisposition string
ResultDisposition describes a definite outcome. Unknown execution outcomes and input checkpoints never enter RoundResults. Rejection does not assert that a Tool's business operation ran.
const ( ResultInvalid ResultDisposition = "" ResultSucceeded ResultDisposition = "succeeded" ResultFailed ResultDisposition = "failed" ResultRejected ResultDisposition = "rejected" )
func (ResultDisposition) String ¶ added in v0.59.0
func (r ResultDisposition) String() string
func (ResultDisposition) Valid ¶ added in v0.59.0
func (r ResultDisposition) Valid() bool
type ResultEntry ¶ added in v0.59.0
type ResultEntry struct {
ToolCallIndex uint32 `json:"tool_call_index"`
Call chat.ToolCall `json:"call"`
Result chat.ToolResult `json:"result"`
Disposition ResultDisposition `json:"disposition"`
}
ResultEntry keeps exact provider attribution and output together. Entries returned by RoundResults are independent copies and cannot alter the snapshot.
type RoundResults ¶ added in v0.59.0
type RoundResults struct {
// contains filtered or unexported fields
}
RoundResults is an immutable, possibly sparse view of definite results for one Interaction round. Entries retain original call indexes. Complete reports knowledge, never permission to continue a canceled Process; only the Interaction state machine admits a complete round through a Checkpoint before continuation.
func SettledResults ¶ added in v0.59.0
func SettledResults(snapshot run.TreeSnapshot) ([]RoundResults, error)
SettledResults interprets Scope-owned facts in one complete tree cut, ordered child-before-parent and then by original call index. Unknown operations, waiting checkpoints and calls that never started produce no synthetic result. Definite tool settlements remain visible even when cancellation prevented the Tool or parent Step from consuming them. Delegate projection requires a fully terminal subtree without unresolved Effects.
This is a read-only projection of current recovery facts, not a transcript: later cuts may retire an admitted round, and overlapping cuts repeat facts that RoundResults.Reference identifies. A Host that keeps result history derives it inside its TreeCommitter transactions. Reading or storing this projection never authorizes tool reexecution.
func (RoundResults) CallCount ¶ added in v0.59.0
func (r RoundResults) CallCount() uint32
func (RoundResults) Complete ¶ added in v0.59.0
func (r RoundResults) Complete() bool
func (RoundResults) Digest ¶ added in v0.59.0
func (r RoundResults) Digest() run.Digest
Digest binds the exact JSON content and attribution, independently of EffectIDs and tree incarnation. It is a content hash, not a storage acknowledgment.
func (RoundResults) Entries ¶ added in v0.59.0
func (r RoundResults) Entries() []ResultEntry
func (RoundResults) JSON ¶ added in v0.59.0
func (r RoundResults) JSON() json.RawMessage
func (RoundResults) ModelCallSequence ¶ added in v0.59.0
func (r RoundResults) ModelCallSequence() uint64
func (RoundResults) Reference ¶ added in v0.59.0
func (r RoundResults) Reference(toolCallIndex uint32) (ToolCallRef, bool)
Reference uses the original model response index, not an entry's position in this possibly sparse projection. A missing result does not invalidate a call's reference; false means that index is outside the admitted round.
func (RoundResults) Relation ¶ added in v0.59.0
func (r RoundResults) Relation() run.ProcessRelation
type ToolCallRef ¶ added in v0.59.0
type ToolCallRef struct {
// contains filtered or unexported fields
}
ToolCallRef identifies one logical call by its requesting Interaction Process, one-based model call sequence and zero-based position in that response. It is immutable and comparable. Provider call IDs, execution attempts and managed child identities do not participate in equality. A reference identifies a call; it does not prove execution, settlement or permission to replay it.
Example ¶
package main
import (
"fmt"
"github.com/Tangerg/scope/agent"
)
func main() {
// A Host persists the value returned by an invocation or result round's
// Reference method, independently of its product record identity.
retained, err := agent.ParseToolCallRef("process:analysis/2/0")
if err != nil {
panic(err)
}
items := map[agent.ToolCallRef]string{retained: "item-7"}
encoded, err := retained.MarshalText()
if err != nil {
panic(err)
}
var restored agent.ToolCallRef
if err := restored.UnmarshalText(encoded); err != nil {
panic(err)
}
fmt.Println(restored == retained, items[restored])
fmt.Println(restored.ProcessID(), restored.ModelCallSequence(), restored.ToolCallIndex())
}
Output: true item-7 process:analysis 2 0
func ParseToolCallRef ¶ added in v0.59.0
func ParseToolCallRef(value string) (ToolCallRef, error)
ParseToolCallRef accepts only the canonical text encoding. Parsing restores a reference, never an execution authority or a managed child identity.
func (ToolCallRef) JSONSchemaModel ¶ added in v0.59.0
func (ToolCallRef) JSONSchemaModel() any
func (ToolCallRef) MarshalText ¶ added in v0.59.0
func (t ToolCallRef) MarshalText() ([]byte, error)
func (ToolCallRef) ModelCallSequence ¶ added in v0.59.0
func (t ToolCallRef) ModelCallSequence() uint64
func (ToolCallRef) ProcessID ¶ added in v0.59.0
func (t ToolCallRef) ProcessID() run.ProcessID
func (ToolCallRef) String ¶ added in v0.59.0
func (t ToolCallRef) String() string
String is the canonical, lossless text encoding used by MarshalText. The zero value has an empty encoding and cannot be marshaled.
func (ToolCallRef) ToolCallIndex ¶ added in v0.59.0
func (t ToolCallRef) ToolCallIndex() uint32
func (*ToolCallRef) UnmarshalText ¶ added in v0.59.0
func (t *ToolCallRef) UnmarshalText(text []byte) error
func (ToolCallRef) Valid ¶ added in v0.59.0
func (t ToolCallRef) Valid() bool
type ToolInvocation ¶ added in v0.59.0
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 ¶ added in v0.59.0
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 ToolInvocationFromRequest ¶ added in v0.59.0
func ToolInvocationFromRequest(request run.EffectRequest) (ToolInvocation, error)
ToolInvocationFromRequest decodes the exact attribution retained by a Tool EffectRequest, including requests recovered from TreeSnapshot.EffectRequest. Retained requests have no physical AttemptID until dispatched again. This operation performs no Tool call and does not resolve an unknown Effect.
func (ToolInvocation) AttemptID ¶ added in v0.59.0
func (t ToolInvocation) AttemptID() (run.EffectAttemptID, bool)
AttemptID identifies this physical invocation, when dispatched by the Runtime.
func (ToolInvocation) EffectID ¶ added in v0.59.0
func (t ToolInvocation) EffectID() run.EffectID
func (ToolInvocation) ProgramRef ¶ added in v0.59.0
func (t ToolInvocation) ProgramRef() run.ProgramRef
func (ToolInvocation) Reference ¶ added in v0.59.0
func (t ToolInvocation) Reference() (ToolCallRef, bool)
Reference correlates this attempt with its requesting Interaction's results. It comes from the ChildKey an Interaction gives the Tool child, which the Runtime keeps unique under the parent. A ToolSet run as a root, or started under any other ChildKey, has no reference; its physical invocation attribution remains available through this value.
func (ToolInvocation) Relation ¶ added in v0.59.0
func (t ToolInvocation) Relation() run.ProcessRelation
func (ToolInvocation) StepSequence ¶ added in v0.59.0
func (t ToolInvocation) StepSequence() uint64
StepSequence returns the one-based Tool child Step that declared this attempt.
func (ToolInvocation) ToolCall ¶ added in v0.59.0
func (t ToolInvocation) ToolCall() chat.ToolCall
func (ToolInvocation) TreeIncarnationID ¶ added in v0.59.0
func (t ToolInvocation) TreeIncarnationID() (run.TreeIncarnationID, bool)
TreeIncarnationID identifies the durable writer activation, when present.
func (ToolInvocation) Valid ¶ added in v0.59.0
func (t ToolInvocation) Valid() bool
type ToolObserver ¶ added in v0.59.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. Callbacks do not acknowledge durable Effect settlement.
type ToolSet ¶ added in v0.59.0
type ToolSet struct {
// contains filtered or unexported fields
}
ToolSet binds an immutable Tool manifest to one Program 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.59.0
func NewToolSet(config ToolSetConfig) (ToolSet, error)
func (ToolSet) Configured ¶ added in v0.59.0
Configured distinguishes a constructed ToolSet from the optional absence of Tools.
func (ToolSet) ObservationFailures ¶ added in v0.59.0
func (t ToolSet) ObservationFailures() ObservationFailures
ObservationFailures returns isolated Tool observer panic counts and diagnostics.
func (ToolSet) Program ¶ added in v0.59.0
Program returns the exact child binding each Tool call runs under. An Interaction configured with this ToolSet owns it as one of its ChildDeployments.
func (ToolSet) SettleToolResult ¶ added in v0.59.0
func (t ToolSet) SettleToolResult(request run.EffectRequest, output tool.Output, disposition ResultDisposition, advertisedToolNames []string) (run.Settlement, error)
SettleToolResult converts an investigated external outcome into the same completion protocol used by live dispatch, without calling or replaying the Tool. request must be the original Runtime-minted request for this exact Program; its call identifies the result, and disposition alone decides whether the output reports an error. Direct-return policy comes only from the binding; rejected and failed results cannot advertise Tools.
type ToolSetConfig ¶ added in v0.59.0
type ToolSetConfig struct {
Name string
Description string
Tools []tool.Tool
DeferredTools []tool.Tool
// Observer receives exact Tool call facts. Nil disables observation.
Observer ToolObserver
// DecorateDispatcher optionally wraps the Tool child's Dispatcher once at
// construction, reaching the full Dispatch boundary that ToolObserver and
// per-Tool wrappers cannot. The wrapper must delegate and preserve the
// Settlement, Policy, and replay semantics; SettleToolResult recovery uses the
// undecorated Dispatcher, and the Host folds the decoration into the digests.
DecorateDispatcher func(run.Dispatcher) (run.Dispatcher, error)
ImplementationDigest run.Digest
ConfigurationDigest run.Digest
}
ToolSetConfig freezes ordinary Tool authority and its exact execution binding. The digests cover the executable Tools, optional capabilities, and observer.
type ToolSettlement ¶ added in v0.59.0
type ToolSettlement struct {
Result *chat.ToolResult
InputRequired bool
Failure string
// Evidence is non-final output from an unknown call. It is never promoted
// to Result and cannot establish whether the external operation succeeded.
Evidence *toolcontract.Output
}
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 Runtime has not yet committed its wait. With neither, the call's external outcome remains unestablished, including host failures, cancellation, deadlines, and panics, and Failure diagnoses it. Observation never settles the Effect.
func (ToolSettlement) Unknown ¶ added in v0.59.0
func (t ToolSettlement) Unknown() bool
Unknown reports a call whose external outcome remains unestablished.
Source Files
¶
- adapt.go
- advertisement.go
- artifact.go
- capability.go
- child_batch.go
- child_key.go
- child_signals.go
- clone.go
- compile.go
- context_reducer.go
- definition.go
- delegate.go
- delegate_attribution.go
- dispatcher.go
- doc.go
- errors.go
- execution.go
- input.go
- invocation.go
- model_tool_result.go
- observer.go
- output.go
- pending_input.go
- protocol.go
- reconcile.go
- round_results.go
- state.go
- steer.go
- stream.go
- tool_call_ref.go
- tool_dispatcher.go
- tool_execution.go
- tool_round.go
- tool_set.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package coordination provides bounded coordination through ordinary Agent Definitions.
|
Package coordination provides bounded coordination through ordinary Agent Definitions. |
|
examples
|
|
|
autonomous
command
Command autonomous demonstrates an Interaction in which the model chooses a Tool from environment feedback and decides when to stop.
|
Command autonomous demonstrates an Interaction in which the model chooses a Tool from environment feedback and decides when to stop. |
|
composition
command
Command composition demonstrates that direct Runtime embedding and a cross-Strategy Agent composed from Workflow and Role atoms use the same Definition/Execution/Process contracts.
|
Command composition demonstrates that direct Runtime embedding and a cross-Strategy Agent composed from Workflow and Role atoms use the same Definition/Execution/Process contracts. |
|
evaluator_optimizer
command
Command evaluator_optimizer demonstrates bounded evaluator-optimizer composition with exact managed child Processes.
|
Command evaluator_optimizer demonstrates bounded evaluator-optimizer composition with exact managed child Processes. |
|
orchestrator_workers
command
Command orchestrator_workers demonstrates model-directed task decomposition, deterministic managed worker fan-out, and model synthesis without a collaboration Strategy.
|
Command orchestrator_workers demonstrates model-directed task decomposition, deterministic managed worker fan-out, and model synthesis without a collaboration Strategy. |
|
workflow
command
Command workflow demonstrates an ordered managed Workflow whose Call and Fork Stages create independently recoverable child Processes.
|
Command workflow demonstrates an ordered managed Workflow whose Call and Fork Stages create independently recoverable child Processes. |
|
workflow_patterns
command
Command workflow_patterns demonstrates prompt chaining, routing, parallel sectioning, and parallel voting through one managed Workflow.
|
Command workflow_patterns demonstrates prompt chaining, routing, parallel sectioning, and parallel voting through one managed Workflow. |
|
internal
|
|
|
conformancetest
Package conformancetest captures real Runtime boundaries for built-in Strategy tests.
|
Package conformancetest captures real Runtime boundaries for built-in Strategy tests. |
|
panicinfo
Package panicinfo bounds the diagnostics retained for a recovered Host callback panic.
|
Package panicinfo bounds the diagnostics retained for a recovered Host callback panic. |
|
strategy/childcall
Package childcall owns recoverable child handshake progress.
|
Package childcall owns recoverable child handshake progress. |
|
strategy/restore
Package restore owns the Restore protocol shared by built-in strategies: strict state decoding, Definition-consistency validation, and cooperative cancellation around that validation.
|
Package restore owns the Restore protocol shared by built-in strategies: strict state decoding, Definition-consistency validation, and cooperative cancellation around that validation. |
|
strategy/stepfail
Package stepfail builds the classified failures built-in strategies end their Steps with, so every strategy normalizes diagnostic text the same way.
|
Package stepfail builds the classified failures built-in strategies end their Steps with, so every strategy normalizes diagnostic text the same way. |
|
Package messaging delivers intermediate input through ordinary Dispatcher Effects.
|
Package messaging delivers intermediate input through ordinary Dispatcher Effects. |
|
Package planning provides goal-directed state planning as an Agent execution strategy.
|
Package planning provides goal-directed state planning as an Agent execution strategy. |
|
goap
Package goap provides deterministic goal-oriented action planning over immutable planning.WorldState values.
|
Package goap provides deterministic goal-oriented action planning over immutable planning.WorldState values. |
|
Package run provides the Scope Agent Framework execution kernel.
|
Package run provides the Scope Agent Framework execution kernel. |
|
runtest
Package runtest provides deterministic consumer-side fixtures and reusable conformance suites for the Agent Framework's public execution boundaries.
|
Package runtest provides deterministic consumer-side fixtures and reusable conformance suites for the Agent Framework's public execution boundaries. |
|
postgres
module
|
|
|
Package team provides decision-driven multi-agent work.
|
Package team provides decision-driven multi-agent work. |
|
Package workflow provides deterministic orchestration of Framework-managed child Processes.
|
Package workflow provides deterministic orchestration of Framework-managed child Processes. |