openresponses

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 5, 2026 License: Apache-2.0 Imports: 14 Imported by: 0

Documentation

Overview

Package openresponses is an independent OpenResponses remote backend emulator.

It implements black-box server behavior for the OpenResponses 2026-04-24 profile: HTTP JSON create, SSE create, standalone compaction, and direct WebSocket turns. It serves portable and opaque items, tools, reasoning, assistant phase, prefixed extensions, and full required response presence; it can force auth, rate-limit, 4xx/5xx, malformed-event/resource/content-type, disconnect, virtual-delay, slow-write, backpressure, and cancellation-observation modes.

The server keeps an atomic request counter and a redacted bounded capture so tests can prove zero-upstream rejection and strict request shape.

Independence: this package is test-only support. Its non-test source MUST NOT import production OpenResponses protocol, frontend, backend, or state-machine packages, and it must not reuse their wire structs or parsers. Only stdlib plus github.com/gorilla/websocket are used here. The immutable official fixtures under the reference client's testdata are the only protocol inputs shared with production.

Index

Constants

View Source
const (
	ItemMessage            = "message"
	ItemFunctionCall       = "function_call"
	ItemFunctionCallOutput = "function_call_output"
	ItemReasoning          = "reasoning"
	ItemItemReference      = "item_reference"
	ItemCompaction         = "compaction"
)

Item discriminator constants for the independent server-side wire model.

View Source
const DefaultMaxBodyBytes = 8 << 20

DefaultMaxBodyBytes bounds request bodies served by the emulator.

View Source
const RedactedAuthorization = "[REDACTED]"

RedactedAuthorization is the placeholder written over credential headers.

Variables

View Source
var (
	// ErrNoScriptSelected is returned when a request arrives while no script is active.
	ErrNoScriptSelected = errors.New("refbackend/openresponses: no script selected")
	// ErrUnknownScript is returned when Select names an unregistered script ID.
	ErrUnknownScript = errors.New("refbackend/openresponses: unknown script id")
)

Sentinel errors for the independent reference backend emulator.

Functions

func ValidMalformed

func ValidMalformed(m MalformedMode) bool

ValidMalformed reports whether m is a known malformed mode.

Types

type AuthExpectation

type AuthExpectation string

AuthExpectation asserts the request credential posture.

const (
	AuthOptional AuthExpectation = "optional" // accept with or without credentials
	AuthBearer   AuthExpectation = "bearer"   // require a Bearer token
	AuthNone     AuthExpectation = "none"     // require no Authorization header
)

type Capture

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

Capture is a thread-safe, bounded, redacting recorder of request observations plus atomic per-path counters used to prove zero-upstream rejection.

func NewCapture

func NewCapture(maxBytes int, redactHeaders []string, redactBodies bool) *Capture

NewCapture constructs a bounded capture. maxBytes <= 0 uses the default bound. redactHeaders lists header names (case-insensitive) that must be redacted; redactBodies controls whether bodies are replaced by a redaction marker.

func (*Capture) Count

func (c *Capture) Count(path string) int64

Count returns the atomic per-path request count.

func (*Capture) Last

func (c *Capture) Last() (Observation, bool)

Last returns the most recent observation, if any.

func (*Capture) Len

func (c *Capture) Len() int

Len returns the number of stored observations.

func (*Capture) Observations

func (c *Capture) Observations() []Observation

Observations returns a defensive copy of the bounded capture.

func (*Capture) Overflow

func (c *Capture) Overflow() int

Overflow returns how many observations were dropped past the bound.

func (*Capture) Record

func (c *Capture) Record(r *http.Request, body []byte) Observation

Record captures one HTTP request and increments the total and per-path counters.

func (*Capture) RecordFrame

func (c *Capture) RecordFrame(path string, headers http.Header, body []byte) Observation

RecordFrame captures a WebSocket turn envelope as an observation and counts it.

func (*Capture) RecordHandshake

func (c *Capture) RecordHandshake(r *http.Request) Observation

RecordHandshake captures a WebSocket upgrade handshake without counting it as a semantic create request (turn envelopes are counted by RecordFrame).

func (*Capture) Reset

func (c *Capture) Reset()

Reset clears the stored observations, overflow count, and all counters.

func (*Capture) Total

func (c *Capture) Total() int64

Total returns the atomic number of captured requests/frames.

type Clock

type Clock interface {
	Now() time.Time
}

Clock provides deterministic time for the emulator server.

type CompactRequest

type CompactRequest struct {
	Model          string
	Input          *InputValue
	Instructions   *string
	Reasoning      json.RawMessage
	PromptCacheKey string
	Extensions     map[string]json.RawMessage
}

CompactRequest is the independent server-side wire model of a compact request body.

func (*CompactRequest) Items

func (p *CompactRequest) Items() []Item

Items returns the ordered compact input items.

type CompactResource

type CompactResource struct {
	ID         string
	Object     string
	CreatedAt  int64
	Status     string
	Model      string
	Output     []Item
	Usage      Usage
	Extensions map[string]json.RawMessage
}

CompactResource is the independent server-side wire model of the response.compaction resource.

func NewCompactResource

func NewCompactResource(id, model string, createdAt int64, output []Item) *CompactResource

NewCompactResource returns a completed compaction resource.

func (*CompactResource) MarshalJSON

func (c *CompactResource) MarshalJSON() ([]byte, error)

MarshalJSON renders the compaction resource with required presence.

type ContentPart

type ContentPart struct {
	Type        string
	Text        string
	Refusal     string
	Summary     string
	Filename    string
	ImageURL    json.RawMessage
	FileURL     json.RawMessage
	FileData    json.RawMessage
	VideoURL    json.RawMessage
	Annotations json.RawMessage
	Logprobs    json.RawMessage
	Opaque      json.RawMessage
}

ContentPart is a discriminated content part inside a message.

func NewTextPart

func NewTextPart(text string) ContentPart

NewTextPart builds an output_text content part.

func (ContentPart) IsExtension

func (p ContentPart) IsExtension() bool

IsExtension reports whether the content part uses a prefixed implementor slug.

func (ContentPart) MarshalJSON

func (p ContentPart) MarshalJSON() ([]byte, error)

MarshalJSON renders the content part back onto the wire.

func (*ContentPart) UnmarshalJSON

func (p *ContentPart) UnmarshalJSON(data []byte) error

UnmarshalJSON parses a discriminated content part.

type CreateRequest

type CreateRequest struct {
	Model                string
	Input                *InputValue
	Instructions         *string
	Tools                []Tool
	ToolChoice           json.RawMessage
	ParallelToolCalls    *bool
	Temperature          *float64
	TopP                 *float64
	MaxOutputTokens      *int
	MaxToolCalls         *int
	Truncation           string
	Text                 json.RawMessage
	Reasoning            json.RawMessage
	Store                *bool
	Background           *bool
	PreviousResponseID   *string
	Metadata             json.RawMessage
	ServiceTier          string
	SafetyIdentifier     string
	PromptCacheKey       string
	PromptCacheRetention string
	Stream               bool
	Extensions           map[string]json.RawMessage
}

CreateRequest is the independent server-side wire model of a create request body (also used to parse compaction bodies, which are a subset).

func (*CreateRequest) ExtensionItemTypes

func (p *CreateRequest) ExtensionItemTypes() []string

ExtensionItemTypes returns the distinct prefixed input item types.

func (*CreateRequest) Items

func (p *CreateRequest) Items() []Item

Items returns the ordered input items (empty for string input).

type DelayPlan

type DelayPlan struct {
	BeforeFirst   time.Duration // sleep before the first event/response
	BetweenEvents time.Duration // sleep between streamed events
	SlowWrite     time.Duration // additional per-event write sleep (slow-write mode)
}

DelayPlan applies virtual/controlled delays around serving.

type ErrorObject

type ErrorObject struct {
	Type    string
	Code    string
	Message string
	Param   string
}

ErrorObject is the structured OpenResponses error payload.

func (ErrorObject) MarshalJSON

func (e ErrorObject) MarshalJSON() ([]byte, error)

MarshalJSON renders the structured error envelope.

type ErrorStep

type ErrorStep struct {
	Status     int    // HTTP status; 0 defaults to 400
	Type       string // e.g. invalid_request, requests, server_error
	Code       string // stable code, e.g. model_not_found, rate_limit_exceeded
	Message    string
	Param      string
	RetryAfter string // sent as Retry-After when Status is 429
}

ErrorStep forces a structured HTTP/WS error response.

type ExpectedRequest

type ExpectedRequest struct {
	Method                string          // exact method, e.g. POST
	PathSuffix            string          // URL path suffix, e.g. /responses/compact
	ContentType           string          // request Content-Type, e.g. application/json
	Auth                  AuthExpectation // credential posture assertion
	Model                 string          // exact model when non-empty
	Stream                *bool           // exact stream flag when non-nil
	MinInputItems         int             // minimum input item count (0 = unconstrained)
	MaxInputItems         int             // maximum input item count (0 = unconstrained)
	RequireTools          int             // minimum declared tool count
	RequireExtensionItems []string        // input item types that must be present
	Contains              []string        // raw body substrings that must be present
	MustOmit              []string        // raw body substrings that must be absent
}

ExpectedRequest is a strict assertion over the captured request. Every declared constraint must hold; a mismatch is recorded and surfaced as a 400-style error.

type InputValue

type InputValue struct {
	Text    string
	TextSet bool
	Items   []Item
}

InputValue is the request `input` field: a string or an ordered item array.

func (InputValue) MarshalJSON

func (i InputValue) MarshalJSON() ([]byte, error)

MarshalJSON renders string or item-array input; empty input marshals as null.

func (*InputValue) UnmarshalJSON

func (i *InputValue) UnmarshalJSON(data []byte) error

UnmarshalJSON parses a string or item-array input.

type Item

type Item struct {
	Type             string
	ID               string
	Status           string
	Role             string
	Phase            string
	Content          []ContentPart
	CallID           string
	Name             string
	Arguments        string
	Output           json.RawMessage
	Reasoning        *ReasoningItem
	EncapsulatedID   string
	EncryptedContent string
	Opaque           json.RawMessage
}

Item is the discriminated ordered unit of context on the OpenResponses wire.

func NewCompactionItem

func NewCompactionItem(id string, raw string) Item

NewCompactionItem builds a pinned-schema-valid compaction item. The pinned profile requires a non-empty encrypted_content blob on compaction output items; `raw`, when supplied and valid JSON, is merged into the preserved opaque body so callers can attach extra fields deterministically.

func NewExtensionItem

func NewExtensionItem(typeName, raw string) Item

NewExtensionItem builds an opaque prefixed extension item. The type discriminator is injected into the preserved raw object when absent.

func NewFunctionCallItem

func NewFunctionCallItem(id, callID, name, arguments string) Item

NewFunctionCallItem builds a function_call output item.

func NewFunctionCallOutputItem

func NewFunctionCallOutputItem(callID, output string) Item

NewFunctionCallOutputItem builds a function_call_output item from a call id.

func NewItemReference

func NewItemReference(encapsulatedID, id string) Item

NewItemReference builds an item_reference item.

func NewMessageItem

func NewMessageItem(role, partType, text string) Item

NewMessageItem builds a portable message item with one content part.

func NewMessagePartsItem

func NewMessagePartsItem(role, phase string, parts ...ContentPart) Item

NewMessagePartsItem builds a message item with arbitrary content parts.

func NewReasoningItem

func NewReasoningItem(id string, summary, content []ContentPart) Item

NewReasoningItem builds a reasoning item with summary and content parts.

func (Item) IsExtension

func (it Item) IsExtension() bool

IsExtension reports whether the item uses a prefixed implementor slug.

func (Item) MarshalJSON

func (it Item) MarshalJSON() ([]byte, error)

MarshalJSON renders the item back onto the wire, preserving opaque extension bytes.

func (*Item) UnmarshalJSON

func (it *Item) UnmarshalJSON(data []byte) error

UnmarshalJSON parses a discriminated wire item. Known portable types are typed; unknown valid prefixed types are preserved opaquely; unknown unprefixed types fail.

type MalformedMode

type MalformedMode string

MalformedMode deliberately violates the profile so the independent client's parser must reject the served body/stream without panicking.

const (
	MalformedNone                   MalformedMode = ""
	MalformedResourceMissingField   MalformedMode = "resource_missing_field"
	MalformedResourceBadType        MalformedMode = "resource_bad_type"
	MalformedItemDiscriminator      MalformedMode = "item_discriminator"
	MalformedBodyNotJSON            MalformedMode = "body_not_json"
	MalformedOversizedBody          MalformedMode = "oversized_body"
	MalformedEventNoHeader          MalformedMode = "event_no_header"
	MalformedEventMismatch          MalformedMode = "event_mismatch"
	MalformedEventDuplicateTerminal MalformedMode = "event_duplicate_terminal"
	MalformedEventAfterTerminal     MalformedMode = "event_after_terminal"
	MalformedDoneBeforeTerminal     MalformedMode = "done_before_terminal"
	MalformedMissingDONE            MalformedMode = "missing_done"
	MalformedContentType            MalformedMode = "content_type"
)

type Mode

type Mode string

Mode selects the transport/output shape the server serves for the active script.

const (
	ModeJSON      Mode = "json"
	ModeSSE       Mode = "sse"
	ModeCompact   Mode = "compact"
	ModeWebSocket Mode = "websocket"
)

type Observation

type Observation struct {
	Path      string
	Method    string
	Headers   http.Header
	Body      []byte
	Timestamp time.Time
	Redacted  bool
}

Observation captures a raw request or WebSocket turn envelope for test assertions. Sensitive headers and (optionally) bodies are redacted before storage.

type Options

type Options struct {
	// AllowMissingBearer, when true, skips the bearer requirement. When false,
	// requests without an Authorization: Bearer header are rejected with 401.
	AllowMissingBearer bool
	// RequiredBearer, when non-empty, requires the exact bearer secret.
	RequiredBearer string
	// MaxBodyBytes bounds request body reads; zero uses DefaultMaxBodyBytes.
	MaxBodyBytes int64
	// RedactBodies replaces captured request bodies with a redaction marker.
	RedactBodies bool
	// Clock supplies deterministic timestamps for observations.
	Clock Clock
	// CaptureMax bounds the stored observation list.
	CaptureMax int
	// Logger, when set, receives emulator warnings.
	Logger *slog.Logger
}

Options tunes the independent server emulator.

type ReasoningItem

type ReasoningItem struct {
	Content             []ContentPart
	EncryptedContent    string
	EncryptedContentSet bool
	Summary             []ContentPart
}

ReasoningItem carries provider-controlled reasoning payloads.

func (ReasoningItem) MarshalJSON

func (r ReasoningItem) MarshalJSON() ([]byte, error)

MarshalJSON renders the reasoning item back onto the wire.

func (*ReasoningItem) UnmarshalJSON

func (r *ReasoningItem) UnmarshalJSON(data []byte) error

UnmarshalJSON parses a reasoning item preserving null presence.

type Resource

type Resource struct {
	ID                   string
	Object               string
	CreatedAt            int64
	Status               string
	CompletedAt          *int64
	Model                string
	Output               []Item
	ParallelToolCalls    bool
	Reasoning            json.RawMessage
	Store                bool
	Background           bool
	Temperature          *float64
	Text                 json.RawMessage
	ToolChoice           json.RawMessage
	Tools                []Tool
	TopP                 *float64
	Truncation           string
	Usage                Usage
	Metadata             json.RawMessage
	ServiceTier          string
	MaxOutputTokens      *int
	MaxToolCalls         *int
	Instructions         *string
	PreviousResponseID   *string
	Error                *ErrorObject
	IncompleteDetails    json.RawMessage
	SafetyIdentifier     *string
	PromptCacheKey       *string
	PromptCacheRetention *string
	Extensions           map[string]json.RawMessage
}

Resource is the independent server-side wire model of the complete OpenResponses response resource. Pointer fields preserve null/default presence on the wire.

func NewResource

func NewResource(id, model string, createdAt int64, output []Item) *Resource

NewResource returns a completed response resource with the pinned required presence populated with profile defaults.

func (*Resource) CorruptField

func (r *Resource) CorruptField(field string) ([]byte, error)

CorruptField re-marshals the resource with one field forced to a wrong type, for the malformed-resource-bad-type mode.

func (*Resource) MarshalJSON

func (r *Resource) MarshalJSON() ([]byte, error)

MarshalJSON emits every required field (null where permitted) plus optional extensions, guaranteeing the pinned required-presence contract.

func (*Resource) OmitRequiredField

func (r *Resource) OmitRequiredField(field string) ([]byte, error)

OmitRequiredField re-marshals the resource without one required field, for the malformed-resource-missing-field mode.

func (*Resource) WithError

func (r *Resource) WithError(status string, e *ErrorObject) *Resource

WithError marks the resource failed with a structured error.

func (*Resource) WithUsage

func (r *Resource) WithUsage(u Usage) *Resource

WithUsage overrides the token counters.

type Script

type Script struct {
	ID              string
	Description     string
	Mode            Mode
	Expected        ExpectedRequest
	Resource        *Resource        // success body for JSON; stream source for SSE/WS
	CompactResource *CompactResource // success body for compact mode
	SSE             []WireStep       // optional explicit stream when Resource is nil
	RawBody         []byte           // optional verbatim body (e.g. pinned official fixture bytes)
	Error           *ErrorStep
	Delay           DelayPlan
	Malformed       MalformedMode
	DisconnectAfter int // close the connection after this many streamed events (0 = never)
	Status          int // success status override; 0 = 200
}

Script is the declarative contract for one server interaction.

func (*Script) Validate

func (s *Script) Validate() error

Validate enforces script-state hygiene: every declared script must be well-formed, non-empty, and self-consistent.

type Server

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

Server is an independent OpenResponses remote backend emulator. A test selects one script at a time; every request is captured (atomic counters + redacted bounded capture) and validated against the active script's expectations.

func NewServer

func NewServer(opts Options) *Server

NewServer constructs an independent emulator server.

func (*Server) ActiveScript

func (s *Server) ActiveScript() (*Script, error)

ActiveScript returns the currently selected script.

func (*Server) CancelCount

func (s *Server) CancelCount() int64

CancelCount returns how many times the server observed request cancellation.

func (*Server) Capture

func (s *Server) Capture() *Capture

Capture exposes the atomic counters and redacted bounded capture.

func (*Server) Clock

func (s *Server) Clock() Clock

Clock exposes the server's deterministic clock.

func (*Server) Handler

func (s *Server) Handler() http.Handler

Handler returns the HTTP surface: POST /responses (JSON/SSE), POST /responses/compact (JSON), GET /responses (WebSocket).

func (*Server) MismatchCount

func (s *Server) MismatchCount() int64

MismatchCount returns how many requests violated the active script's expectations.

func (*Server) Register

func (s *Server) Register(sd ...*Script) error

Register validates and registers one or more scripts. Duplicate IDs fail.

func (*Server) Select

func (s *Server) Select(id string) error

Select makes id the active script for subsequent requests.

func (*Server) WriteErrorCount

func (s *Server) WriteErrorCount() int64

WriteErrorCount returns how many times the server observed a writer failure.

type StreamEvent

type StreamEvent struct {
	Type   string
	Seq    int64
	Fields map[string]any
}

StreamEvent is one independent server-side lifecycle event. Fields is rendered as the JSON `data:` payload with `type` and `sequence_number` included.

type Tool

type Tool struct {
	Type        string
	Name        string
	Description string
	Parameters  json.RawMessage
	Strict      *bool
	Opaque      json.RawMessage
}

Tool is a function tool or a prefixed hosted tool.

func (Tool) IsExtension

func (t Tool) IsExtension() bool

IsExtension reports whether the tool uses a prefixed implementor slug.

func (Tool) MarshalJSON

func (t Tool) MarshalJSON() ([]byte, error)

MarshalJSON renders the tool definition back onto the wire.

func (*Tool) UnmarshalJSON

func (t *Tool) UnmarshalJSON(data []byte) error

UnmarshalJSON parses a wire tool definition.

type Usage

type Usage struct {
	InputTokens     int
	CachedTokens    int
	OutputTokens    int
	ReasoningTokens int
	TotalTokens     int
}

Usage carries token counters.

func (Usage) MarshalJSON

func (u Usage) MarshalJSON() ([]byte, error)

MarshalJSON renders usage with the required input/output/total token presence plus the standard detail sub-objects.

type VirtualClock

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

VirtualClock is a deterministic, goroutine-safe clock for emulator tests.

func NewClock

func NewClock(initial time.Time) *VirtualClock

NewClock returns a VirtualClock seeded to a fixed reference instant.

func (*VirtualClock) Advance

func (c *VirtualClock) Advance(d time.Duration)

Advance moves the virtual clock forward deterministically.

func (*VirtualClock) Now

func (c *VirtualClock) Now() time.Time

Now returns the current virtual time.

func (*VirtualClock) Set

func (c *VirtualClock) Set(t time.Time)

Set pins the virtual clock to an exact instant.

type WireStep

type WireStep struct {
	Type     string
	Sequence int64
	Data     json.RawMessage
}

WireStep is an explicit scripted stream event (used when the stream is not derived from a Resource by the independent stream builder).

Jump to

Keyboard shortcuts

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