script

package
v1.261203.2 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: MPL-2.0 Imports: 13 Imported by: 1 module, 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 script is the scripted-conversation behaviour of vmodel: a scene of predefined replies that real agent clients (Claude Code, the Projects coordinator and its threads, their subagents) run against, many at once.

A script is a set of tracks, one per conversation. A request is routed to the track whose earlier reply it carries (the tool_use ids and texts we emitted come back verbatim in the client's history), so concurrent conversations never steal each other's steps; a new conversation claims a track by a declared selector. Each step answers one request and may assert what that request and the results of its tool calls contain. Anything no track or background rule expects fails the run. See .design/vmodel-script.md.

Index

Constants

View Source
const (
	IssueUnmatched    = "unmatched"     // no track, step or background rule expected the request
	IssueAmbiguous    = "ambiguous"     // a new conversation matched several tracks
	IssueMismatch     = "mismatch"      // the next step's when did not hold
	IssueExhausted    = "exhausted"     // the track had no step left
	IssueExpect       = "expect"        // a step's expect failed
	IssueExpectResult = "expect_result" // a tool call's expect_result failed
	IssueTemplate     = "template"      // a {{var}} had no value
	IssueCapture      = "capture"       // a capture found nothing
	IssueAfterTimeout = "after_timeout" // a held step's after conditions never held
	IssueUnconsumed   = "unconsumed"    // a step was never served
	IssueResultMissed = "result_missed" // a call with expect_result never had its result seen
	IssueBackground   = "background"    // a background rule ran outside min/max
	IssueRetry        = "retry"         // a request repeated an answered one (warning)
	IssueFinished     = "finished"      // a request arrived after Finish
)

Issue kinds.

View Source
const (
	ClassMain      = "main"
	ClassSubagent  = "subagent"
	ClassAuxiliary = "auxiliary"
)

Request classes: the main loop of a conversation, a subagent, or an auxiliary request of the client (titles, classifiers: no tools).

Variables

This section is empty.

Functions

This section is empty.

Types

type Background

type Background struct {
	ID    string `json:"id"`
	When  *Match `json:"when"`
	Reply Reply  `json:"reply"`
	Min   int    `json:"min,omitempty"`
	Max   int    `json:"max,omitempty"`
}

Background is a reply for requests outside every track.

type Call

type Call struct {
	// ID names the call for references (tool_result:step.call); the wire id
	// is derived from the script, track, step and call, so it is stable.
	ID        string         `json:"id,omitempty"`
	Name      string         `json:"name"`
	Arguments map[string]any `json:"arguments,omitempty"`
	// Spawns is the track of the conversation this call starts (a thread,
	// a subagent).
	Spawns string `json:"spawns,omitempty"`
	// ExpectResult is checked on the request that brings the call's result.
	ExpectResult *ResultMatch `json:"expect_result,omitempty"`
}

Call is one tool_use block of a reply.

type Check

type Check struct {
	On     string `json:"on"`
	OK     bool   `json:"ok"`
	Detail string `json:"detail,omitempty"`
}

Check is one assertion evaluated on a request.

type Duration

type Duration time.Duration

Duration accepts "30s" or integer nanoseconds.

func (Duration) MarshalJSON

func (d Duration) MarshalJSON() ([]byte, error)

func (*Duration) UnmarshalJSON

func (d *Duration) UnmarshalJSON(b []byte) error

type Engine

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

Engine runs one script: it routes requests to tracks and keeps what happened. One engine is one run; build a new one to run again.

func New

func New(id string, s *Script) (*Engine, error)

New builds an engine for a validated script; id names it in wire ids and reports.

func (*Engine) Finish

func (e *Engine) Finish() Report

Finish ends the run: later requests fail, steps never served and background rules outside their bounds become failures.

func (*Engine) ID

func (e *Engine) ID() string

ID is the script's id.

func (*Engine) Report

func (e *Engine) Report() Report

Report is the run so far.

func (*Engine) ServeHTTP

func (e *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP answers Anthropic Messages requests (and count_tokens) from the script; HEAD probes get 200, anything else 404.

func (*Engine) Signal

func (e *Engine) Signal(name string)

Signal raises a signal for steps held with after: signal:<name>.

func (*Engine) Trace

func (e *Engine) Trace() []Entry

Trace is every request so far, in arrival order.

func (*Engine) WaitReached

func (e *Engine) WaitReached(ctx context.Context, ref string) error

WaitReached blocks until a request claimed the step "track.step"; its reply may still be held by after. A driver uses it to act while the client is waiting for that reply.

func (*Engine) WaitServed

func (e *Engine) WaitServed(ctx context.Context, ref string) error

WaitServed blocks until the step "track.step" was answered.

type Entry

type Entry struct {
	Seq     int      `json:"seq"`
	Track   string   `json:"track,omitempty"`
	Step    string   `json:"step,omitempty"`
	Via     string   `json:"via"` // bind, continuation, retry, background, unmatched
	Class   string   `json:"class"`
	Model   string   `json:"model,omitempty"`
	Session string   `json:"session,omitempty"`
	HeldMS  int64    `json:"held_ms,omitempty"`
	Status  int      `json:"status"`
	Checks  []Check  `json:"checks,omitempty"`
	Text    string   `json:"text,omitempty"`
	Tools   []string `json:"tools,omitempty"`
	Error   string   `json:"error,omitempty"`
}

Entry is one request as the script saw it.

type Extract

type Extract struct {
	From  string `json:"from"`
	Regex string `json:"regex"`
}

Extract reads one value: the first group of Regex (or the whole match) in From: system, first_user, last_user, last_text, header:<name> or tool_result:<step>.<call>.

type Issue

type Issue struct {
	Kind   string `json:"kind"`
	Track  string `json:"track,omitempty"`
	Step   string `json:"step,omitempty"`
	Seq    int    `json:"seq,omitempty"`
	Detail string `json:"detail"`
}

Issue is one failure or warning of a run.

func (Issue) String

func (i Issue) String() string

type Match

type Match struct {
	Class             []string `json:"class,omitempty"`
	Model             string   `json:"model,omitempty"`
	SystemContains    string   `json:"system_contains,omitempty"`
	SystemRegex       string   `json:"system_regex,omitempty"`
	FirstUserContains string   `json:"first_user_contains,omitempty"`
	LastUserContains  string   `json:"last_user_contains,omitempty"`
	LastUserRegex     string   `json:"last_user_regex,omitempty"`
	LastTextContains  string   `json:"last_text_contains,omitempty"`
	// InsertedContains matches a message the user wrote while the turn ran:
	// Claude Code puts it in a role "system" entry after our last reply.
	InsertedContains string            `json:"inserted_contains,omitempty"`
	ToolsInclude     []string          `json:"tools_include,omitempty"`
	ToolsExclude     []string          `json:"tools_exclude,omitempty"`
	HasToolResult    string            `json:"has_tool_result,omitempty"`
	Header           map[string]string `json:"header,omitempty"`
	All              []*Match          `json:"all,omitempty"`
	Any              []*Match          `json:"any,omitempty"`
	Not              *Match            `json:"not,omitempty"`
}

Match is a predicate on a request. Every set field must hold.

type Reply

type Reply struct {
	Content      string   `json:"content,omitempty"`
	ToolCalls    []*Call  `json:"tool_calls,omitempty"`
	StreamChunks []string `json:"stream_chunks,omitempty"`
	Delay        Duration `json:"delay,omitempty"`
	StopReason   string   `json:"stop_reason,omitempty"`
	Usage        *Usage   `json:"usage,omitempty"`
	// Error answers with an API error before any content instead.
	Error *vmodel.ErrorInjection `json:"error,omitempty"`
}

Reply is what a step answers. Field names follow the vmodel mock block.

type Report

type Report struct {
	Script     string         `json:"script"`
	Finished   bool           `json:"finished"`
	OK         bool           `json:"ok"`
	Requests   int            `json:"requests"`
	Failures   []Issue        `json:"failures"`
	Warnings   []Issue        `json:"warnings"`
	Tracks     []TrackReport  `json:"tracks"`
	Background map[string]int `json:"background"`
}

Report is the outcome of a run so far (final after Finish).

func (Report) String

func (r Report) String() string

type ResultMatch

type ResultMatch struct {
	Contains string `json:"contains,omitempty"`
	Regex    string `json:"regex,omitempty"`
	IsError  *bool  `json:"is_error,omitempty"`
}

ResultMatch is a predicate on a tool result.

type Script

type Script struct {
	// Strict fails requests nothing expects (the default). Off, they get the
	// Unmatched reply and a warning, for writing a script against a client.
	Strict *bool `json:"strict,omitempty"`
	// HoldTimeout bounds how long a step waits for its after conditions.
	HoldTimeout Duration `json:"hold_timeout,omitempty"`
	// CountTokens answers /v1/messages/count_tokens (default 100).
	CountTokens int `json:"count_tokens,omitempty"`
	// Unmatched is what a non-strict script answers to an unexpected request.
	Unmatched *Reply `json:"unmatched,omitempty"`
	// Background answers requests that belong to no track (titles,
	// classifiers) without using a step.
	Background []Background      `json:"background,omitempty"`
	Tracks     map[string]*Track `json:"tracks"`
}

Script is one scene.

func Decode

func Decode(data []byte) (*Script, error)

Decode reads a script from JSON or YAML, rejecting unknown fields.

func (*Script) TrackNames

func (s *Script) TrackNames() []string

TrackNames are the tracks in a stable order.

func (*Script) Validate

func (s *Script) Validate() error

Validate checks references and selectors and fills step ids.

type Step

type Step struct {
	ID string `json:"id,omitempty"`
	// When guards the step: a request that does not match skips an optional
	// step and is a mismatch for any other.
	When     *Match `json:"when,omitempty"`
	Optional bool   `json:"optional,omitempty"`
	// After holds the reply until other steps were served ("track.step") or
	// the driver raised signals ("signal:name").
	After []string `json:"after,omitempty"`
	// Expect is checked on the request; a failure is reported and the step
	// still answers, so the run goes on and the trace stays whole.
	Expect  *Match             `json:"expect,omitempty"`
	Capture map[string]Extract `json:"capture,omitempty"`
	Reply   Reply              `json:"reply"`
}

Step answers one request of its track.

type Track

type Track struct {
	// Bind claims a new conversation (a request with none of our replies in
	// it). A track some call spawns needs none: it binds to the request that
	// carries the call's title/prompt/description.
	Bind *Match `json:"bind,omitempty"`
	// Capture reads values from the binding request for {{var}} templates.
	Capture map[string]Extract `json:"capture,omitempty"`
	Steps   []*Step            `json:"steps"`
}

Track is one conversation.

type TrackReport

type TrackReport struct {
	Name      string   `json:"name"`
	Bound     bool     `json:"bound"`
	Session   string   `json:"session,omitempty"`
	Served    []string `json:"served"`
	Remaining []string `json:"remaining"`
}

TrackReport is where one track ended.

type Usage

type Usage struct {
	InputTokens  int `json:"input_tokens,omitempty"`
	OutputTokens int `json:"output_tokens,omitempty"`
}

Usage is the token usage a reply reports.

Jump to

Keyboard shortcuts

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