middleware

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Feb 27, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Chain

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

Chain executes middleware sequentially and enforces short-circuit semantics.

func NewChain

func NewChain(mw []Middleware, opts ...ChainOption) *Chain

NewChain constructs a chain with the provided middleware. Nil items are ignored to keep the calling code simple.

func (*Chain) Execute

func (c *Chain) Execute(ctx context.Context, stage Stage, st *State) error

Execute runs the requested stage on all middleware in order. It stops on the first error and returns it.

func (*Chain) Use

func (c *Chain) Use(m Middleware)

Use appends middleware at runtime.

type ChainOption

type ChainOption func(*Chain)

ChainOption mutates the chain configuration.

func WithTimeout

func WithTimeout(d time.Duration) ChainOption

WithTimeout configures a per-stage timeout. Zero means no timeout.

type FileHTTPTraceWriter

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

FileHTTPTraceWriter appends JSONL events to a single file.

func NewFileHTTPTraceWriter

func NewFileHTTPTraceWriter(dir string) (*FileHTTPTraceWriter, error)

NewFileHTTPTraceWriter creates/opens a JSONL log file under dir following Claude Code's log naming convention.

func (*FileHTTPTraceWriter) Close

func (w *FileHTTPTraceWriter) Close() error

Close releases the underlying file handle.

func (*FileHTTPTraceWriter) Path

func (w *FileHTTPTraceWriter) Path() string

Path returns the backing file path for observability/testing.

func (*FileHTTPTraceWriter) WriteHTTPTrace

func (w *FileHTTPTraceWriter) WriteHTTPTrace(event *HTTPTraceEvent) error

WriteHTTPTrace writes the event as a single JSON line.

type Funcs

type Funcs struct {
	Identifier string

	OnBeforeAgent func(ctx context.Context, st *State) error
	OnBeforeModel func(ctx context.Context, st *State) error
	OnAfterModel  func(ctx context.Context, st *State) error
	OnBeforeTool  func(ctx context.Context, st *State) error
	OnAfterTool   func(ctx context.Context, st *State) error
	OnAfterAgent  func(ctx context.Context, st *State) error
}

Funcs is a helper that turns a set of function pointers into a Middleware. Unspecified hooks default to no-ops.

func (Funcs) AfterAgent

func (f Funcs) AfterAgent(ctx context.Context, st *State) error

func (Funcs) AfterModel

func (f Funcs) AfterModel(ctx context.Context, st *State) error

func (Funcs) AfterTool

func (f Funcs) AfterTool(ctx context.Context, st *State) error

func (Funcs) BeforeAgent

func (f Funcs) BeforeAgent(ctx context.Context, st *State) error

func (Funcs) BeforeModel

func (f Funcs) BeforeModel(ctx context.Context, st *State) error

func (Funcs) BeforeTool

func (f Funcs) BeforeTool(ctx context.Context, st *State) error

func (Funcs) Name

func (f Funcs) Name() string

type HTTPTraceEvent

type HTTPTraceEvent struct {
	Request  HTTPTraceRequest  `json:"request"`
	Response HTTPTraceResponse `json:"response"`
	LoggedAt string            `json:"logged_at"`
}

HTTPTraceEvent captures a single HTTP exchange in JSONL-friendly form.

type HTTPTraceMiddleware

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

HTTPTraceMiddleware captures inbound/outbound payloads at the HTTP layer.

func NewHTTPTraceMiddleware

func NewHTTPTraceMiddleware(writer HTTPTraceWriter, opts ...HTTPTraceOption) *HTTPTraceMiddleware

NewHTTPTraceMiddleware wires the middleware with the provided writer.

func (*HTTPTraceMiddleware) Handler

func (m *HTTPTraceMiddleware) Handler(next http.Handler) http.Handler

Handler is an alias for Wrap to align with conventional middleware naming.

func (*HTTPTraceMiddleware) Wrap

Wrap returns an http.Handler that records a trace per request.

type HTTPTraceOption

type HTTPTraceOption func(*HTTPTraceMiddleware)

HTTPTraceOption configures the middleware.

func WithHTTPTraceClock

func WithHTTPTraceClock(clock func() time.Time) HTTPTraceOption

WithHTTPTraceClock injects a deterministic clock (useful for tests).

func WithHTTPTraceMaxBodyBytes

func WithHTTPTraceMaxBodyBytes(limit int64) HTTPTraceOption

WithHTTPTraceMaxBodyBytes overrides the capture limit. limit == 0 disables capture, limit <0 captures the full payload.

type HTTPTraceRequest

type HTTPTraceRequest struct {
	Timestamp float64           `json:"timestamp"`
	Method    string            `json:"method"`
	URL       string            `json:"url"`
	Headers   map[string]string `json:"headers,omitempty"`
	Body      any               `json:"body,omitempty"`
}

type HTTPTraceResponse

type HTTPTraceResponse struct {
	Timestamp float64           `json:"timestamp"`
	Status    int               `json:"status_code"`
	Headers   map[string]string `json:"headers,omitempty"`
	BodyRaw   string            `json:"body_raw,omitempty"`
}

type HTTPTraceWriter

type HTTPTraceWriter interface {
	WriteHTTPTrace(event *HTTPTraceEvent) error
}

HTTPTraceWriter persists events. Implementations must be concurrency safe.

type Middleware

type Middleware interface {
	Name() string
	BeforeAgent(ctx context.Context, st *State) error
	BeforeModel(ctx context.Context, st *State) error
	AfterModel(ctx context.Context, st *State) error
	BeforeTool(ctx context.Context, st *State) error
	AfterTool(ctx context.Context, st *State) error
	AfterAgent(ctx context.Context, st *State) error
}

Middleware defines all six interception points. Implementations may no-op individual methods when the hook is not needed.

type Stage

type Stage int

Stage enumerates the six interception points supported by the chain.

const (
	StageBeforeAgent Stage = iota
	StageBeforeModel
	StageAfterModel
	StageBeforeTool
	StageAfterTool
	StageAfterAgent
)

type State

type State struct {
	Iteration   int
	Agent       any
	ModelInput  any
	ModelOutput any
	ToolCall    any
	ToolResult  any
	Values      map[string]any
}

State carries mutable execution data shared across middleware invocations. The concrete types stored in these fields are left to callers; middleware should type-assert to what it expects.

func (*State) SetModelInput

func (st *State) SetModelInput(v any)

SetModelInput assigns the raw request payload destined for the model.

func (*State) SetModelOutput

func (st *State) SetModelOutput(v any)

SetModelOutput assigns the raw response payload provided by the model layer.

func (*State) SetValue

func (st *State) SetValue(key string, value any)

SetValue stores arbitrary metadata on the state, ensuring the backing map exists.

type TraceContextKey

type TraceContextKey string

TraceContextKey identifies values stored in a context for trace middleware consumers.

const (
	// TraceSessionIDContextKey stores the trace-specific session identifier.
	TraceSessionIDContextKey TraceContextKey = "trace.session_id"
	// SessionIDContextKey stores the generic session identifier fallback.
	SessionIDContextKey TraceContextKey = "session_id"
)

type TraceEvent

type TraceEvent struct {
	Timestamp     time.Time      `json:"timestamp"`
	Stage         string         `json:"stage"`
	Iteration     int            `json:"iteration"`
	SessionID     string         `json:"session_id"`
	Input         any            `json:"input,omitempty"`
	Output        any            `json:"output,omitempty"`
	ModelRequest  map[string]any `json:"model_request,omitempty"`
	ModelResponse map[string]any `json:"model_response,omitempty"`
	ToolCall      map[string]any `json:"tool_call,omitempty"`
	ToolResult    map[string]any `json:"tool_result,omitempty"`
	Error         string         `json:"error,omitempty"`
	DurationMS    int64          `json:"duration_ms,omitempty"`
}

TraceEvent captures a single middleware hook invocation and its payloads.

type TraceMiddleware

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

TraceMiddleware records middleware activity per session and renders a lightweight HTML viewer alongside JSONL logs.

func NewTraceMiddleware

func NewTraceMiddleware(outputDir string, opts ...TraceOption) *TraceMiddleware

NewTraceMiddleware builds a TraceMiddleware that writes to outputDir (defaults to .trace when empty).

func (*TraceMiddleware) AfterAgent

func (m *TraceMiddleware) AfterAgent(ctx context.Context, st *State) error

func (*TraceMiddleware) AfterModel

func (m *TraceMiddleware) AfterModel(ctx context.Context, st *State) error

func (*TraceMiddleware) AfterTool

func (m *TraceMiddleware) AfterTool(ctx context.Context, st *State) error

func (*TraceMiddleware) BeforeAgent

func (m *TraceMiddleware) BeforeAgent(ctx context.Context, st *State) error

func (*TraceMiddleware) BeforeModel

func (m *TraceMiddleware) BeforeModel(ctx context.Context, st *State) error

func (*TraceMiddleware) BeforeTool

func (m *TraceMiddleware) BeforeTool(ctx context.Context, st *State) error

func (*TraceMiddleware) Close

func (m *TraceMiddleware) Close()

Close releases all open file handles held by trace sessions.

func (*TraceMiddleware) Name

func (m *TraceMiddleware) Name() string

type TraceOption

type TraceOption func(*TraceMiddleware)

TraceOption customizes optional TraceMiddleware behavior.

func WithSkillTracing

func WithSkillTracing(enabled bool) TraceOption

WithSkillTracing enables ForceSkills body-size logging.

Jump to

Keyboard shortcuts

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