agenttest

package
v2.1.1 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: MIT Imports: 41 Imported by: ? modules, 0 packages

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

Documentation

Overview

Package agenttest provides deterministic model scripts and an isolated, in-memory agent runtime harness for iteration under go test.

New uses the test context, registers application components, installs scripted model overrides, and reports leaks at test cleanup. NewHarness exposes the same construction for callers that manage Close themselves. Construction seals runtime registration after installing capture gates; register all components in the callback. The harness owns its engine, run/content stores, session store and hook bus. WithRuntimeOptions may configure other runtime policies, memory and interceptors, but cannot replace those owned components or the tracer.

Run accepts User text or arbitrary Input messages and returns the final output, sealed RunRecord, causal Trajectory and answered awaits. An agent failure is a Result.RunErr, not a harness error. Setup errors, unanswered awaits, timeouts and evidence reconstruction failures use the error return. Stub dispatch failures return a populated Result and joined harness error after normal run completion. The default run timeout is 30 seconds, including external waits. Cancellation drains the run; Close joins script diagnostics and any remaining lifecycle leaks.

WithResponder supplies first-match AwaitRules for confirmation, clarification, questions, typed input and external tools. Callbacks execute outside hook publication and must be safe for concurrent runs and return promptly. Answer emits the standard answers/question_id/selected_ids JSON shape; QuestionsFunc supports application-owned result schemas. Result.Awaits retains typed signal answers and their observed prompts. If any registered BeforeEvent interceptor can alter events, observed trajectory evidence is marked unverified.

RunSession starts ordered runs in a shared new session. Earlier turns are visible only through the agent's configured memory policy: the harness does no transcript carry-over. WithTracerProvider opens agenttest.run spans and wires runtime planner/model tracing to the supplied provider without modifying the global provider. TraceID is omitted when no provider is supplied. The caller owns provider shutdown and export configuration.

Application-registered models are preserved unless a scripted override uses the same ID. LiveModel(id) requires LOOM_LIVE_MODEL=1 before registration and confirms that the application supplied that client. New skips when disabled; invalid environment values fail. SkipUnlessLive gates standalone Decide tests. This opt-in gates only these explicit helpers, not undeclared application clients. The harness has no Temporal mode.

CaptureFirstRequest records the first fully decorated request without calling the underlying model; the planner must propagate its sentinel error. Tools scheduled before the model follow the normal strict stub rules. Model returns the pre-gate client for direct Decide calls. Request transforms return immutable copies and defer errors; SaveRequest/LoadRequest use deterministic, verified version-1 fixtures containing full prompts. Private completion validators are omitted and provider thinking signatures must not be replayed across providers. Decide performs one validated model call without CallInfo, recording or tool execution. Check Decision.Calls with expect.Calls. Repeat runs sequential func(testing.TB) attempts, isolating Fatal, panics and cleanup failures before applying its minimum passing threshold. Only a skip without failure skips the parent. Attempt cleanup restores Setenv/Chdir and removes TempDir directories.

Activity tools are strict by default: declare Stub responses or opt into Passthrough / PassthroughAll. Stubs preserve registration, payload preparation, AfterTool and result materialization. Close reports every dispatch failure and unused finite response. RawStub supports registered tools without descriptors; registered result-decoder failures are StubErrors reported by Run and Close. Inline and agent-as-tool stubbing remain a runtime follow-up.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrCaptureSentinel stops a capture at the first recorded model request.
	ErrCaptureSentinel = errors.New("agenttest: capture first request sentinel")
	// ErrCaptureNoModelCall means the planner made no recorded model call.
	ErrCaptureNoModelCall = errors.New("agenttest: capture made no model call")
	// ErrCaptureHandled means the planner did not propagate the capture sentinel.
	ErrCaptureHandled = errors.New("agenttest: the planner handled the capture sentinel instead of returning it")
)
View Source
var ErrLiveModelDisabled = errors.New("agenttest: live model disabled")

ErrLiveModelDisabled indicates that explicit live-model opt-in is absent.

View Source
var ErrScriptExhausted = errors.New("agenttest: script exhausted")

ErrScriptExhausted means a request arrived after all turns were consumed.

View Source
var ErrStubExhausted = errors.New("stub exhausted")

ErrStubExhausted marks a call for which all declared responses were consumed.

View Source
var ErrUnansweredAwait = errors.New("agenttest: unanswered await")

ErrUnansweredAwait indicates that no responder rule matched an observed await.

Functions

func LiveModelEnabled

func LiveModelEnabled() (bool, error)

LiveModelEnabled validates LOOM_LIVE_MODEL: unset or 0 disables, 1 enables.

func MarshalRequest

func MarshalRequest(r Request) ([]byte, error)

MarshalRequest encodes a deterministic version-1 fixture holding full prompts. Private completion validators and portable provider thinking signatures are not carried over; do not replay thinking signatures across providers.

func SaveRequest

func SaveRequest(path string, r Request) error

SaveRequest writes a full-prompt fixture, creating new files with mode 0600. Private completion validators are absent; thinking signatures are not portable.

func SkipUnlessLive

func SkipUnlessLive(t testing.TB, modelID string)

SkipUnlessLive skips t unless LOOM_LIVE_MODEL=1, naming the opted-in model ID. Invalid values fail t. Undeclared application clients are not blocked.

Types

type AnsweredAwait

type AnsweredAwait struct {
	Kind   hooks.EventType
	ID     string
	Event  hooks.Event
	Answer any
}

AnsweredAwait records an await and the typed answer delivered to the runtime.

type ArgMatch

type ArgMatch[P any] func(P) error

ArgMatch checks one decoded payload. Nil means a match. Matchers run only at dispatch, under the stub table lock; they must not call harness/stub methods.

func ArgsEqual

func ArgsEqual[P, R any](tool tools.TypedTool[P, R], want P) ArgMatch[P]

ArgsEqual compares payloads encoded through the tool codec after JSON canonicalization. Want is encoded once. Its encoding error is returned on every match, becoming an unmatched-call StubError when used with When.

func ArgsWhere

func ArgsWhere[P any](description string, predicate func(P) bool) ArgMatch[P]

ArgsWhere matches a payload using a predicate and describes rejected calls.

type AttemptReport

type AttemptReport struct {
	Index       int
	Diagnostics []string
}

AttemptReport contains one failed attempt's ordered diagnostics.

type AwaitRule

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

AwaitRule selects and constructs one kind of external-input answer. Construct rules using Approve, Deny, Clarify, Answer, TypedInput or callbacks.

func Answer

func Answer(questionID string, optionIDs ...string) AwaitRule

Answer selects option IDs for a matching question. The JSON result is {"answers":[{"question_id":"...","selected_ids":["..."]}]}. Use QuestionsFunc when one await needs multiple question answers or a custom schema.

func Approve

func Approve(tools ...tools.Named) AwaitRule

Approve approves confirmations for the named tools; no tools matches all.

func Clarify

func Clarify(answer string) AwaitRule

Clarify answers every clarification with the supplied text.

func ClarifyFunc

func ClarifyFunc(answer func(*hooks.AwaitClarificationEvent) (string, error)) AwaitRule

ClarifyFunc derives a clarification answer from its observed prompt.

func Deny

func Deny(tools ...tools.Named) AwaitRule

Deny denies confirmations for the named tools; no tools matches all.

func ExternalToolsFunc

func ExternalToolsFunc(answer func(*hooks.AwaitExternalToolsEvent) ([]*api.ProvidedToolResult, error)) AwaitRule

ExternalToolsFunc constructs the wire-safe results for an external-tools await.

func QuestionsFunc

func QuestionsFunc(answer func(*hooks.AwaitQuestionsEvent) (rawjson.Message, error)) AwaitRule

QuestionsFunc returns the application-owned JSON result for a questions tool.

func TypedInput

func TypedInput(payload rawjson.Message) AwaitRule

TypedInput answers typed-input awaits with an owned copy of the JSON payload.

func TypedInputFunc

func TypedInputFunc(answer func(*hooks.AwaitTypedInputEvent) (rawjson.Message, error)) AwaitRule

TypedInputFunc derives a typed-input payload from the await schema and title.

type Decision

type Decision struct {
	ModelID  string
	Request  *model.Request
	Response *model.Response
	Calls    []model.ToolCall
	Latency  time.Duration
}

Decision is the evidence from a single model invocation, without tool execution.

func Decide

func Decide(t testing.TB, client model.Client, r Request) *Decision

Decide invokes one model using t's context and fails t on any error.

func DecideContext

func DecideContext(ctx context.Context, client model.Client, r Request) (*Decision, error)

DecideContext invokes a client directly without adding CallInfo or recording a run. Streaming requests are drained and finalized before returning evidence.

type EvidenceSnapshot

type EvidenceSnapshot = evidence.Snapshot

EvidenceSnapshot contains raw canonical records from a private local capture. Unlinked preserves call runs without a committed link in any root tree. These records are replay evidence, not filtered artifacts for sharing.

func ReadEvidence

func ReadEvidence(ctx context.Context, dir string) (*EvidenceSnapshot, error)

ReadEvidence reopens a private capture without requiring a completed run or eval. Canonical adoption determines incomplete/abandoned classes; no success is inferred. It returns any readable records alongside explicit reconstruction errors.

type Harness

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

Harness owns an isolated in-memory runtime and its test lifecycle. Runs may execute concurrently; Close prevents further starts and reports leaks.

func New

func New(t testing.TB, register Register, opts ...Option) *Harness

New constructs a harness using the test context and reports cleanup leaks to t.

func NewHarness

func NewHarness(ctx context.Context, register Register, opts ...Option) (*Harness, error)

NewHarness constructs owned stores, engine and bus, then registers application components followed by scripted overrides. It never enables live clients itself.

func (*Harness) CaptureFirstRequest

func (h *Harness) CaptureFirstRequest(ctx context.Context, id agent.Ident, input Input, opts ...RunOption) (Request, error)

CaptureFirstRequest runs a fresh session until the first model request is recorded, then fails that model invocation without consuming its client. Planners must return the sentinel error. Tools scheduled before that invocation follow the normal strict stub rules; model interceptors may short-circuit it.

func (*Harness) Close

func (h *Harness) Close() error

Close reports every unconsumed script/error and open run, cancelling open runs.

func (*Harness) EvidenceDir

func (h *Harness) EvidenceDir() string

EvidenceDir returns the selected private capture directory, or empty by default.

func (*Harness) Model

func (h *Harness) Model(id string) model.Client

Model returns the pre-gate registered client for direct Decide calls, or nil when the ID is unknown.

func (*Harness) OpenSession

func (h *Harness) OpenSession(ctx context.Context) (*Session, error)

OpenSession creates an empty session without submitting a workflow.

func (*Harness) Passthrough

func (h *Harness) Passthrough(tools ...tools.Named)

Passthrough allows real execution of the named activity tools without stubs. Calls are recorded with Passthrough true, raw arguments and correlation IDs; their real outcomes remain available in the runtime trajectory.

func (*Harness) Run

func (h *Harness) Run(ctx context.Context, id agent.Ident, input Input, opts ...RunOption) (*Result, error)

Run executes one turn in a fresh session. Failed agent outcomes populate RunErr. Stub dispatch failures return a populated Result and a joined harness error after completion; setup, timeout and reconstruction also use the error return.

func (*Harness) RunSession

func (h *Harness) RunSession(ctx context.Context, id agent.Ident, turns ...Input) (*SessionResult, error)

RunSession runs turns sequentially in one new session, stopping at the first harness error and returning the completed prefix. Agent failures are outcomes. Prior history comes only from the agent's memory policy; the harness carries no messages between turns.

func (*Harness) Runtime

func (h *Harness) Runtime() *runtime.Runtime

Runtime returns the sealed harness-owned runtime for application inspection. Register models, agents and toolsets in the construction callback.

func (*Harness) Script

func (h *Harness) Script(id string) *Script

Script returns a scripted override, or nil when the ID has no script.

func (*Harness) ToolCalls

func (h *Harness) ToolCalls() []RecordedCall

ToolCalls returns an arrival-ordered snapshot, including failures and passthrough. Payload and Result are shallow copies; Raw bytes are copied.

type Input

type Input []*model.Message

Input is one turn's caller-supplied messages.

func User

func User(text string) Input

User constructs one user text message.

type Match

type Match func(*model.Request) error

Match checks whether a request can consume a turn; nil means it matches.

func HasTool

func HasTool(tool tools.Named) Match

HasTool matches requests advertising the named tool.

func LacksTool

func LacksTool(tool tools.Named) Match

LacksTool matches requests that do not advertise the named tool.

func LastToolResult

func LastToolResult(tool tools.Named, contains string) Match

LastToolResult matches the latest result of the named tool by tracing its ToolUseID to a preceding tool use. String results are plain text; other values are JSON encoded before checking the substring.

func LastToolResultParts

func LastToolResultParts(tool tools.Named, parts ...model.ToolResultContentPart) Match

LastToolResultParts matches the latest named result's attachments in order.

func LastUserContains

func LastUserContains(text string) Match

LastUserContains matches text in the last user message, ignoring older messages.

func ModelClass

func ModelClass(class model.ModelClass) Match

ModelClass matches the logical model class requested by the caller.

type Option

type Option func(*harnessOptions) error

Option configures harness construction.

func LiveModel

func LiveModel(id string) Option

LiveModel opts a named application-registered client in to live evaluation. It creates no provider and rejects disabled opt-in before application registration. Undeclared application clients remain available.

func PassthroughAll

func PassthroughAll() Option

PassthroughAll allows real execution of every activity tool without a stub. Explicit stubs still take precedence, including when their responses exhaust.

func ScriptedModel

func ScriptedModel(id string, turns ...Turn) Option

ScriptedModel builds a deterministic model override during construction.

func ScriptedModelFrom

func ScriptedModelFrom(id string, script *Script) Option

ScriptedModelFrom installs a script, including its AnyOrder and context settings.

func WithDefaultRunOptions

func WithDefaultRunOptions(opts ...RunOption) Option

WithDefaultRunOptions applies opts to every Run, RunSession and CaptureFirstRequest invocation before caller options. WithRunID remains reserved.

func WithEvidenceDir

func WithEvidenceDir(dir string) Option

WithEvidenceDir persists canonical evidence in a fresh harness-owned capture. The directory can exist, but its evidence database must not already exist. Stores and engine ownership remain with the harness. Capture errors fail runs.

func WithResponder

func WithResponder(responder Responder) Option

WithResponder configures the rules used by every run, including session turns.

func WithRunTimeout

func WithRunTimeout(timeout time.Duration) Option

WithRunTimeout sets the wall-clock limit, including external waits, for each run.

func WithRuntimeOptions

func WithRuntimeOptions(opts ...runtime.RuntimeOption) Option

WithRuntimeOptions passes application runtime settings through, rejecting the engine, stores, hooks and tracer owned by the harness.

func WithTracerProvider

func WithTracerProvider(provider trace.TracerProvider) Option

WithTracerProvider supplies an isolated provider for root and runtime spans. The harness never sets or shuts down the global or supplied provider.

type Part

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

Part configures a response's content or metadata.

func CallID

func CallID(id string) Part

CallID sets the ID of the immediately preceding tool call.

func OutputLimited

func OutputLimited() Part

OutputLimited marks output as incomplete; the validated client rejects it.

func RawToolCall

func RawToolCall(name tools.Ident, payload rawjson.Message) Part

RawToolCall adds a tool call with raw JSON arguments. The validated client checks the identity and arguments against the actual request's tool schema.

func StopReason

func StopReason(reason string) Part

StopReason overrides the default tool_use or end_turn stop reason.

func Text

func Text(text string) Part

Text adds an assistant text part.

func Thinking

func Thinking(text string) Part

Thinking adds an assistant reasoning part, emitted before text.

func ToolCall

func ToolCall[P, R any](tool tools.TypedTool[P, R], payload P) Part

ToolCall adds a typed tool call encoded through the descriptor's payload codec. Encoding failures are returned by NewScript as builder errors.

func Usage

func Usage(input, output int) Part

Usage sets uncached input and output token counts; model attribution comes from the request.

type RecordedCall

type RecordedCall struct {
	Tool                                tools.Ident
	Call                                int
	RunID, ToolCallID, ParentToolCallID string
	Payload                             any
	Raw                                 rawjson.Message
	Response                            int
	Result                              any
	Err                                 error
	Passthrough                         bool
}

RecordedCall records every activity call reaching the harness, in arrival order. Call and Response are one-based; Response is zero when none was selected. A selected response remains consumed when its delay or decoding fails.

type Register

type Register func(context.Context, *runtime.Runtime) error

Register wires application agents, tools and model clients into a fresh runtime.

type RepeatReport

type RepeatReport struct {
	Attempts int
	Passed   int
	Failed   []AttemptReport
}

RepeatReport summarizes sequential attempts. Indices are one-based.

func Repeat

func Repeat(t testing.TB, n, minPass int, fn func(testing.TB)) RepeatReport

Repeat runs all n attempts sequentially, accepting at least minPass successes. Each attempt isolates failures, Fatal, panics and cleanup from the parent. A skipped attempt with no failure skips the parent and stops further attempts. The parent artifact directory is obtained on the caller goroutine before any attempt starts; failure there terminates the caller, not an attempt.

type Request

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

Request is an immutable model request with optional capture provenance. Transforms defer errors until Err, Request, MarshalRequest or Decide is used.

func LoadRequest

func LoadRequest(t testing.TB, path string) Request

LoadRequest loads a full-prompt fixture and fails t on read or verification errors. Private completion validators are absent; thinking signatures are not portable.

func NewRequest

func NewRequest(modelID string, req *model.Request) (Request, error)

NewRequest snapshots req without its private completion validator. Fixtures contain full prompts; provider thinking signatures are not portable for replay.

func UnmarshalRequest

func UnmarshalRequest(data []byte) (Request, error)

UnmarshalRequest verifies a version-1 fixture and rejects unknown members, including inside the request, by checking its canonical re-encoding. Fixtures contain full prompts and omit private completion validators. Provider thinking signatures must not be replayed across providers.

func (Request) Err

func (r Request) Err() error

Err returns any deferred transform error.

func (Request) ModelID

func (r Request) ModelID() string

ModelID returns the registered model ID, rather than the provider model name.

func (Request) Request

func (r Request) Request() (*model.Request, error)

Request decodes a fresh owned request, excluding the private completion validator. Provider thinking signatures must not be replayed across providers.

func (Request) Source

func (r Request) Source() *Source

Source returns an owned copy of the captured call key, or nil for a fixture constructed without capture provenance.

func (Request) WithModel

func (r Request) WithModel(provider string) Request

WithModel sets the provider-specific model name without changing ModelID.

func (Request) WithRunID

func (r Request) WithRunID(id string) Request

WithRunID sets the model request's run ID.

func (Request) WithSystem

func (r Request) WithSystem(text string) Request

WithSystem replaces all system messages at the first system position, or inserts the system message at the beginning when none exists.

func (Request) WithToolSpecs

func (r Request) WithToolSpecs(specs ...tools.ToolSpec) Request

WithToolSpecs replaces definitions by name and appends new names in order. Other definitions, including tool_unavailable, remain in the request.

func (Request) WithUserMessage

func (r Request) WithUserMessage(text string) Request

WithUserMessage replaces the last user message without tool results.

type Responder

type Responder []AwaitRule

Responder answers awaits using the first matching rule in declaration order. Callbacks may run concurrently for different runs and must return promptly.

type Response

type Response[P, R any] struct {
	// contains filtered or unexported fields
}

Response is one declared stub outcome. Configure responses before calling Run.

func (*Response[P, R]) After

func (r *Response[P, R]) After(delay time.Duration) *Response[P, R]

After delays execution of this response and respects context cancellation.

func (*Response[P, R]) Always

func (r *Response[P, R]) Always() *Response[P, R]

Always makes the response reusable without an unused-response cleanup error.

func (*Response[P, R]) Bounds

func (r *Response[P, R]) Bounds(bounds agent.Bounds) *Response[P, R]

Bounds supplies metadata for a successful bounded result. Pointer fields are copied now and per invocation; error responses carry no bounds.

func (*Response[P, R]) Times

func (r *Response[P, R]) Times(n int) *Response[P, R]

Times sets a positive consumption count, replacing Always. The default is one.

func (*Response[P, R]) When

func (r *Response[P, R]) When(matches ...ArgMatch[P]) *Response[P, R]

When restricts this response to calls whose matchers all pass. The first available matching response wins; identical parallel calls race for FIFO slots.

type Result

type Result struct {
	// EventsUnverified reports that a BeforeEvent interceptor may have altered observed events.
	EventsUnverified bool
	RunID            string
	SessionID        string
	TraceID          string
	Output           *api.RunOutput
	RunErr           error
	Record           *runrecord.RunRecord
	Trajectory       *trajectory.Trajectory
	Awaits           []AnsweredAwait
}

Result separates the agent outcome from harness setup and observation failures.

type RunOption

type RunOption = runtime.RunOption

RunOption configures a runtime run. WithRunID is reserved by the harness.

type Script

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

Script implements model.Provider with deterministic, inspectable turns. Use Client to enforce real model request and output contracts.

func NewScript

func NewScript(turns ...Turn) (*Script, error)

NewScript builds a script, rejecting invalid builders and duplicate call IDs.

func ScriptClient

func ScriptClient(t testing.TB, turns ...Turn) (model.Client, *Script)

ScriptClient builds a validated client and reports script diagnostics at cleanup.

func (*Script) AnyOrder

func (s *Script) AnyOrder() *Script

AnyOrder selects the first unconsumed turn whose matchers all pass.

func (*Script) Client

func (s *Script) Client() model.Client

Client returns the single validated client built by NewScript.

func (*Script) Complete

func (s *Script) Complete(ctx context.Context, request *model.Request) (*model.Response, error)

Complete consumes a matching turn and returns its raw provider response.

func (*Script) ContextLimits

func (s *Script) ContextLimits(_ context.Context, request *model.Request) (model.ContextLimits, string, bool)

ContextLimits reports configured limits and the request's model identity.

func (*Script) Err

func (s *Script) Err() error

Err joins all script diagnostics and lists every unconsumed turn. Intentional Fail turns and output validation failures are not script diagnostics.

func (*Script) Remaining

func (s *Script) Remaining() int

Remaining reports the number of unconsumed turns.

func (*Script) Requests

func (s *Script) Requests() []*model.Request

Requests returns a detached slice of request pointers as received by the provider.

func (*Script) Stream

func (s *Script) Stream(ctx context.Context, request *model.Request) (model.Streamer, error)

Stream consumes a matching turn and returns a raw scripted stream.

func (*Script) WithContextLimits

func (s *Script) WithContextLimits(limits model.ContextLimits) *Script

WithContextLimits sets the limits exposed by Client's ContextInfo capability.

type ScriptError

type ScriptError struct {
	CallIndex int
	TurnIndex int
	Summary   string
	Cause     error
}

ScriptError reports a matcher failure or exhaustion with request context. CallIndex and TurnIndex are one-based; TurnIndex is zero on exhaustion.

func (*ScriptError) Error

func (e *ScriptError) Error() string

Error renders the failing call, turn, matcher, and bounded request summary.

func (*ScriptError) Unwrap

func (e *ScriptError) Unwrap() error

Unwrap exposes the matcher error or ErrScriptExhausted.

type Session

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

Session runs dynamically constructed inputs in one shared runtime session. Run calls are serialized. Callers supply conversation history explicitly; registered runtime continuation and memory policies retain their normal effect.

func (*Session) Result

func (s *Session) Result() *SessionResult

Result returns an owned snapshot of the completed run lists. The individual results are the same immutable evidence objects returned by Run.

func (*Session) Run

func (s *Session) Run(ctx context.Context, id agent.Ident, input Input, opts ...RunOption) (*Result, error)

Run executes one turn, retaining any returned evidence even on harness errors. Agent RunErr is an outcome and does not close the session.

type SessionResult

type SessionResult struct {
	SessionID  string
	Runs       []*Result
	Trajectory trajectory.Session
}

SessionResult holds caller-ordered runs in one new session.

type Source

type Source struct {
	RunID   string `json:"run_id"`
	Seq     int    `json:"seq"`
	Attempt int    `json:"attempt"`
}

Source identifies the captured model call.

type StubCall

type StubCall[P, R any] struct {
	RunID, ToolCallID, ParentToolCallID string
	Payload                             P
	Raw                                 rawjson.Message
	Response                            int
	Result                              R
	Err                                 error
}

StubCall records one stub invocation. Response is the one-based reserved response index, even if delay or decoding fails; zero means none was selected.

type StubError

type StubError struct {
	Tool              tools.Ident
	Call              int
	RunID, ToolCallID string
	Reason            string
	Args              rawjson.Message
	// contains filtered or unexported fields
}

StubError records a harness dispatch failure. The runtime exposes it as a tool error; Run returns it as a harness error after the run finishes.

func (*StubError) Error

func (e *StubError) Error() string

Error includes the tool, call index, correlation IDs and received arguments.

func (*StubError) Unwrap

func (e *StubError) Unwrap() error

Unwrap exposes ErrStubExhausted, payload decode errors and RawStub result decode errors to errors.Is/As.

type ToolStub

type ToolStub[P, R any] struct {
	// contains filtered or unexported fields
}

ToolStub supplies ordered responses for one registered activity tool.

func RawStub

RawStub declares a stub over raw JSON for a tool without a typed descriptor. Successful JSON results are decoded through the registered result codec before the runtime's ordinary AfterTool, materialization and encoding path.

func Stub

func Stub[P, R any](h *Harness, tool tools.TypedTool[P, R]) *ToolStub[P, R]

Stub declares one typed stub. The tool must be registered as an activity tool. Duplicate, unknown and non-activity declarations are reported to New's test immediately, or through Run and Close for NewHarness callers.

func (*ToolStub[P, R]) Calls

func (s *ToolStub[P, R]) Calls() []StubCall[P, R]

Calls returns a snapshot in arrival order. Typed values are shallow copies; raw bytes are copied. The caller owns synchronization for referenced values.

func (*ToolStub[P, R]) Fail

func (s *ToolStub[P, R]) Fail(err error) *Response[P, R]

Fail appends a model-visible tool error. It does not fail the run itself.

func (*ToolStub[P, R]) Handle

func (s *ToolStub[P, R]) Handle(handle func(context.Context, P) (R, error)) *Response[P, R]

Handle appends a callback response. Callbacks run outside the table lock and must support concurrent calls. A non-nil error discards the callback's result.

func (*ToolStub[P, R]) Return

func (s *ToolStub[P, R]) Return(result R) *Response[P, R]

Return appends a successful response, consumed once by default.

type Turn

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

Turn describes one scripted response or failure. Construct it with Respond or Fail.

func ContextOverflow

func ContextOverflow() Turn

ContextOverflow constructs a non-retryable provider context overflow.

func Fail

func Fail(err error) Turn

Fail returns err from Complete or from streaming setup.

func ProviderFailure

func ProviderFailure(kind model.ProviderErrorKind, message string) Turn

ProviderFailure constructs a classified scripted provider failure.

func Respond

func Respond(parts ...Part) Turn

Respond constructs a successful provider turn. Client validation still applies.

func (Turn) Chunked

func (t Turn) Chunked(n int) Turn

Chunked splits each text part into n Unicode-safe fragments.

func (Turn) FailStreamAfter

func (t Turn) FailStreamAfter(n int, err error) Turn

FailStreamAfter makes Recv fail after n emitted chunks; Complete is unaffected. NewScript rejects n greater than the turn's total chunk count.

func (Turn) When

func (t Turn) When(matches ...Match) Turn

When requires every matcher to pass before this turn can be consumed.

Jump to

Keyboard shortcuts

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