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 ¶
- Variables
- func LiveModelEnabled() (bool, error)
- func MarshalRequest(r Request) ([]byte, error)
- func SaveRequest(path string, r Request) error
- func SkipUnlessLive(t testing.TB, modelID string)
- type AnsweredAwait
- type ArgMatch
- type AttemptReport
- type AwaitRule
- func Answer(questionID string, optionIDs ...string) AwaitRule
- func Approve(tools ...tools.Named) AwaitRule
- func Clarify(answer string) AwaitRule
- func ClarifyFunc(answer func(*hooks.AwaitClarificationEvent) (string, error)) AwaitRule
- func Deny(tools ...tools.Named) AwaitRule
- func ExternalToolsFunc(answer func(*hooks.AwaitExternalToolsEvent) ([]*api.ProvidedToolResult, error)) AwaitRule
- func QuestionsFunc(answer func(*hooks.AwaitQuestionsEvent) (rawjson.Message, error)) AwaitRule
- func TypedInput(payload rawjson.Message) AwaitRule
- func TypedInputFunc(answer func(*hooks.AwaitTypedInputEvent) (rawjson.Message, error)) AwaitRule
- type Decision
- type EvidenceSnapshot
- type Harness
- func (h *Harness) CaptureFirstRequest(ctx context.Context, id agent.Ident, input Input, opts ...RunOption) (Request, error)
- func (h *Harness) Close() error
- func (h *Harness) EvidenceDir() string
- func (h *Harness) Model(id string) model.Client
- func (h *Harness) OpenSession(ctx context.Context) (*Session, error)
- func (h *Harness) Passthrough(tools ...tools.Named)
- func (h *Harness) Run(ctx context.Context, id agent.Ident, input Input, opts ...RunOption) (*Result, error)
- func (h *Harness) RunSession(ctx context.Context, id agent.Ident, turns ...Input) (*SessionResult, error)
- func (h *Harness) Runtime() *runtime.Runtime
- func (h *Harness) Script(id string) *Script
- func (h *Harness) ToolCalls() []RecordedCall
- type Input
- type Match
- func HasTool(tool tools.Named) Match
- func LacksTool(tool tools.Named) Match
- func LastToolResult(tool tools.Named, contains string) Match
- func LastToolResultParts(tool tools.Named, parts ...model.ToolResultContentPart) Match
- func LastUserContains(text string) Match
- func ModelClass(class model.ModelClass) Match
- type Option
- func LiveModel(id string) Option
- func PassthroughAll() Option
- func ScriptedModel(id string, turns ...Turn) Option
- func ScriptedModelFrom(id string, script *Script) Option
- func WithDefaultRunOptions(opts ...RunOption) Option
- func WithEvidenceDir(dir string) Option
- func WithResponder(responder Responder) Option
- func WithRunTimeout(timeout time.Duration) Option
- func WithRuntimeOptions(opts ...runtime.RuntimeOption) Option
- func WithTracerProvider(provider trace.TracerProvider) Option
- type Part
- func CallID(id string) Part
- func OutputLimited() Part
- func RawToolCall(name tools.Ident, payload rawjson.Message) Part
- func StopReason(reason string) Part
- func Text(text string) Part
- func Thinking(text string) Part
- func ToolCall[P, R any](tool tools.TypedTool[P, R], payload P) Part
- func Usage(input, output int) Part
- type RecordedCall
- type Register
- type RepeatReport
- type Request
- func (r Request) Err() error
- func (r Request) ModelID() string
- func (r Request) Request() (*model.Request, error)
- func (r Request) Source() *Source
- func (r Request) WithModel(provider string) Request
- func (r Request) WithRunID(id string) Request
- func (r Request) WithSystem(text string) Request
- func (r Request) WithToolSpecs(specs ...tools.ToolSpec) Request
- func (r Request) WithUserMessage(text string) Request
- type Responder
- type Response
- func (r *Response[P, R]) After(delay time.Duration) *Response[P, R]
- func (r *Response[P, R]) Always() *Response[P, R]
- func (r *Response[P, R]) Bounds(bounds agent.Bounds) *Response[P, R]
- func (r *Response[P, R]) Times(n int) *Response[P, R]
- func (r *Response[P, R]) When(matches ...ArgMatch[P]) *Response[P, R]
- type Result
- type RunOption
- type Script
- func (s *Script) AnyOrder() *Script
- func (s *Script) Client() model.Client
- func (s *Script) Complete(ctx context.Context, request *model.Request) (*model.Response, error)
- func (s *Script) ContextLimits(_ context.Context, request *model.Request) (model.ContextLimits, string, bool)
- func (s *Script) Err() error
- func (s *Script) Remaining() int
- func (s *Script) Requests() []*model.Request
- func (s *Script) Stream(ctx context.Context, request *model.Request) (model.Streamer, error)
- func (s *Script) WithContextLimits(limits model.ContextLimits) *Script
- type ScriptError
- type Session
- type SessionResult
- type Source
- type StubCall
- type StubError
- type ToolStub
- type Turn
Constants ¶
This section is empty.
Variables ¶
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") )
var ErrLiveModelDisabled = errors.New("agenttest: live model disabled")
ErrLiveModelDisabled indicates that explicit live-model opt-in is absent.
var ErrScriptExhausted = errors.New("agenttest: script exhausted")
ErrScriptExhausted means a request arrived after all turns were consumed.
var ErrStubExhausted = errors.New("stub exhausted")
ErrStubExhausted marks a call for which all declared responses were consumed.
var ErrUnansweredAwait = errors.New("agenttest: unanswered await")
ErrUnansweredAwait indicates that no responder rule matched an observed await.
Functions ¶
func LiveModelEnabled ¶
LiveModelEnabled validates LOOM_LIVE_MODEL: unset or 0 disables, 1 enables.
func MarshalRequest ¶
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 ¶
SaveRequest writes a full-prompt fixture, creating new files with mode 0600. Private completion validators are absent; thinking signatures are not portable.
func SkipUnlessLive ¶
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 ¶
AnsweredAwait records an await and the typed answer delivered to the runtime.
type ArgMatch ¶
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.
type AttemptReport ¶
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 ¶
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 ClarifyFunc ¶
func ClarifyFunc(answer func(*hooks.AwaitClarificationEvent) (string, error)) AwaitRule
ClarifyFunc derives a clarification answer from its observed prompt.
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 ¶
QuestionsFunc returns the application-owned JSON result for a questions tool.
func TypedInput ¶
TypedInput answers typed-input awaits with an owned copy of the JSON payload.
func TypedInputFunc ¶
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.
type EvidenceSnapshot ¶
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 NewHarness ¶
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 ¶
Close reports every unconsumed script/error and open run, cancelling open runs.
func (*Harness) EvidenceDir ¶
EvidenceDir returns the selected private capture directory, or empty by default.
func (*Harness) Model ¶
Model returns the pre-gate registered client for direct Decide calls, or nil when the ID is unknown.
func (*Harness) OpenSession ¶
OpenSession creates an empty session without submitting a workflow.
func (*Harness) Passthrough ¶
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 ¶
Runtime returns the sealed harness-owned runtime for application inspection. Register models, agents and toolsets in the construction callback.
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 Match ¶
Match checks whether a request can consume a turn; nil means it matches.
func LastToolResult ¶
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 ¶
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 ¶
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 ¶
ScriptedModel builds a deterministic model override during construction.
func ScriptedModelFrom ¶
ScriptedModelFrom installs a script, including its AnyOrder and context settings.
func WithDefaultRunOptions ¶
WithDefaultRunOptions applies opts to every Run, RunSession and CaptureFirstRequest invocation before caller options. WithRunID remains reserved.
func WithEvidenceDir ¶
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 ¶
WithResponder configures the rules used by every run, including session turns.
func WithRunTimeout ¶
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 OutputLimited ¶
func OutputLimited() Part
OutputLimited marks output as incomplete; the validated client rejects it.
func RawToolCall ¶
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 ¶
StopReason overrides the default tool_use or end_turn stop reason.
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 RepeatReport ¶
type RepeatReport struct {
Attempts int
Passed int
Failed []AttemptReport
}
RepeatReport summarizes sequential attempts. Indices are one-based.
func Repeat ¶
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 ¶
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 ¶
NewRequest snapshots req without its private completion validator. Fixtures contain full prompts; provider thinking signatures are not portable for replay.
func UnmarshalRequest ¶
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) ModelID ¶
ModelID returns the registered model ID, rather than the provider model name.
func (Request) Request ¶
Request decodes a fresh owned request, excluding the private completion validator. Provider thinking signatures must not be replayed across providers.
func (Request) Source ¶
Source returns an owned copy of the captured call key, or nil for a fixture constructed without capture provenance.
func (Request) WithModel ¶
WithModel sets the provider-specific model name without changing ModelID.
func (Request) WithSystem ¶
WithSystem replaces all system messages at the first system position, or inserts the system message at the beginning when none exists.
func (Request) WithToolSpecs ¶
WithToolSpecs replaces definitions by name and appends new names in order. Other definitions, including tool_unavailable, remain in the request.
func (Request) WithUserMessage ¶
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 ¶
After delays execution of this response and respects context cancellation.
func (*Response[P, R]) Always ¶
Always makes the response reusable without an unused-response cleanup error.
func (*Response[P, R]) Bounds ¶
Bounds supplies metadata for a successful bounded result. Pointer fields are copied now and per invocation; error responses carry no bounds.
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 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 ScriptClient ¶
ScriptClient builds a validated client and reports script diagnostics at cleanup.
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 ¶
Err joins all script diagnostics and lists every unconsumed turn. Intentional Fail turns and output validation failures are not script diagnostics.
func (*Script) Requests ¶
Requests returns a detached slice of request pointers as received by the provider.
func (*Script) WithContextLimits ¶
func (s *Script) WithContextLimits(limits model.ContextLimits) *Script
WithContextLimits sets the limits exposed by Client's ContextInfo capability.
type ScriptError ¶
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.
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.
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 ¶
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 ¶
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 ¶
Fail appends a model-visible tool error. It does not fail the run itself.
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 ProviderFailure ¶
func ProviderFailure(kind model.ProviderErrorKind, message string) Turn
ProviderFailure constructs a classified scripted provider failure.
func (Turn) FailStreamAfter ¶
FailStreamAfter makes Recv fail after n emitted chunks; Complete is unaffected. NewScript rejects n greater than the turn's total chunk count.