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
- Variables
- func ValidMalformed(m MalformedMode) bool
- type AuthExpectation
- type Capture
- func (c *Capture) Count(path string) int64
- func (c *Capture) Last() (Observation, bool)
- func (c *Capture) Len() int
- func (c *Capture) Observations() []Observation
- func (c *Capture) Overflow() int
- func (c *Capture) Record(r *http.Request, body []byte) Observation
- func (c *Capture) RecordFrame(path string, headers http.Header, body []byte) Observation
- func (c *Capture) RecordHandshake(r *http.Request) Observation
- func (c *Capture) Reset()
- func (c *Capture) Total() int64
- type Clock
- type CompactRequest
- type CompactResource
- type ContentPart
- type CreateRequest
- type DelayPlan
- type ErrorObject
- type ErrorStep
- type ExpectedRequest
- type InputValue
- type Item
- func NewCompactionItem(id string, raw string) Item
- func NewExtensionItem(typeName, raw string) Item
- func NewFunctionCallItem(id, callID, name, arguments string) Item
- func NewFunctionCallOutputItem(callID, output string) Item
- func NewItemReference(encapsulatedID, id string) Item
- func NewMessageItem(role, partType, text string) Item
- func NewMessagePartsItem(role, phase string, parts ...ContentPart) Item
- func NewReasoningItem(id string, summary, content []ContentPart) Item
- type MalformedMode
- type Mode
- type Observation
- type Options
- type ReasoningItem
- type Resource
- type Script
- type Server
- func (s *Server) ActiveScript() (*Script, error)
- func (s *Server) CancelCount() int64
- func (s *Server) Capture() *Capture
- func (s *Server) Clock() Clock
- func (s *Server) Handler() http.Handler
- func (s *Server) MismatchCount() int64
- func (s *Server) Register(sd ...*Script) error
- func (s *Server) Select(id string) error
- func (s *Server) WriteErrorCount() int64
- type StreamEvent
- type Tool
- type Usage
- type VirtualClock
- type WireStep
Constants ¶
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.
const DefaultMaxBodyBytes = 8 << 20
DefaultMaxBodyBytes bounds request bodies served by the emulator.
const RedactedAuthorization = "[REDACTED]"
RedactedAuthorization is the placeholder written over credential headers.
Variables ¶
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 ¶
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) Last ¶
func (c *Capture) Last() (Observation, bool)
Last returns the most recent observation, if any.
func (*Capture) Observations ¶
func (c *Capture) Observations() []Observation
Observations returns a defensive copy of the bounded capture.
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 ¶
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).
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 ¶
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 ¶
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 ¶
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 ¶
NewExtensionItem builds an opaque prefixed extension item. The type discriminator is injected into the preserved raw object when absent.
func NewFunctionCallItem ¶
NewFunctionCallItem builds a function_call output item.
func NewFunctionCallOutputItem ¶
NewFunctionCallOutputItem builds a function_call_output item from a call id.
func NewItemReference ¶
NewItemReference builds an item_reference item.
func NewMessageItem ¶
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 ¶
IsExtension reports whether the item uses a prefixed implementor slug.
func (Item) MarshalJSON ¶
MarshalJSON renders the item back onto the wire, preserving opaque extension bytes.
func (*Item) UnmarshalJSON ¶
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.
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 ¶
NewResource returns a completed response resource with the pinned required presence populated with profile defaults.
func (*Resource) CorruptField ¶
CorruptField re-marshals the resource with one field forced to a wrong type, for the malformed-resource-bad-type mode.
func (*Resource) MarshalJSON ¶
MarshalJSON emits every required field (null where permitted) plus optional extensions, guaranteeing the pinned required-presence contract.
func (*Resource) OmitRequiredField ¶
OmitRequiredField re-marshals the resource without one required field, for the malformed-resource-missing-field mode.
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.
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 (*Server) ActiveScript ¶
ActiveScript returns the currently selected script.
func (*Server) CancelCount ¶
CancelCount returns how many times the server observed request cancellation.
func (*Server) Handler ¶
Handler returns the HTTP surface: POST /responses (JSON/SSE), POST /responses/compact (JSON), GET /responses (WebSocket).
func (*Server) MismatchCount ¶
MismatchCount returns how many requests violated the active script's expectations.
func (*Server) WriteErrorCount ¶
WriteErrorCount returns how many times the server observed a writer failure.
type StreamEvent ¶
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 ¶
IsExtension reports whether the tool uses a prefixed implementor slug.
func (Tool) MarshalJSON ¶
MarshalJSON renders the tool definition back onto the wire.
func (*Tool) UnmarshalJSON ¶
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 ¶
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.