proxy

package
v0.0.0-...-230ac96 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: Apache-2.0 Imports: 34 Imported by: 0 modules, 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 proxy provides an embedded HTTP proxy for intercepting outbound requests from the sandboxed agent. It supports multiple LLM providers (Anthropic, OpenAI) in passthrough mode with optional DLP (Data Loss Prevention) processing. In later releases it will also host generic egress substitution for non-LLM services.

internal/proxy/usage.go

Index

Constants

View Source
const AttrUpstreamURL = "proxy.upstream_url"

AttrUpstreamURL is the Attrs key under which the proxy stores the resolved upstream *url.URL for the request.

It exists because r.Host is the proxy's own listen address: the agent is configured to talk to 127.0.0.1, and the real destination is resolved from the dialect. A hook making a policy decision about where a request is going must use this, not the request's Host.

View Source
const DefaultInspectMaxBodyBytes int64 = 8 << 20 // 8 MiB

DefaultInspectMaxBodyBytes caps how much of a request body is buffered for inspection.

The agent controls the body, so an unbounded read is a denial-of-service surface against the daemon rather than against the upstream. Exceeding the cap is treated as a failed inspection, not as a skip: a body too large to inspect is uninspected content, and the rule's on_failure decides what happens to it -- which is a deny by default.

8 MiB rather than something tighter because this proxy carries LLM traffic, and a request with a long context legitimately runs to several megabytes. A cap set below real payload sizes would turn fail_closed into a blanket block on ordinary use, and the operator would have no way to tell that from a policy that was working.

View Source
const DefaultMCPArgMaxBytes = 1 << 20

DefaultMCPArgMaxBytes caps how much of a streamed tool argument is accumulated before inspection.

On the streaming paths the arguments arrive as fragments and must be held until complete, so an unbounded accumulator is a memory surface the model on the other end controls. Exceeding the cap is a failed inspection, not a skip: arguments too large to inspect are uninspected arguments, and the rule's on_failure decides -- a deny by default.

1 MiB because a tool argument is a function call's parameters, not a payload. Real ones run to kilobytes; anything near this is already anomalous.

Variables

This section is empty.

Functions

func DefaultDialectConfigs

func DefaultDialectConfigs() map[Dialect]*DialectConfig

DefaultDialectConfigs returns the default configuration for each dialect.

func HashBody

func HashBody(body []byte) string

HashBody computes a SHA256 hash of the body for integrity verification. Returns an empty string for empty bodies. Format: "sha256:hexdigest"

func IsChatGPTToken

func IsChatGPTToken(r *http.Request) bool

IsChatGPTToken returns true if the Authorization header contains an OAuth token (non-sk-* Bearer token), indicating ChatGPT login flow.

func IsSSEResponse

func IsSSEResponse(resp *http.Response) bool

IsSSEResponse returns true if the response is a Server-Sent Events stream.

Types

type Config

type Config struct {
	// SessionID is the current session ID (set by agentmon).
	SessionID string

	// Proxy contains proxy mode and upstream settings.
	Proxy config.ProxyConfig

	// DLP is the DLP configuration.
	DLP config.DLPConfig

	// Storage is the storage configuration.
	Storage config.LLMStorageConfig

	// MCP is the MCP security policy configuration.
	MCP config.SandboxMCPConfig
}

Config holds the proxy configuration using config package types.

type CredsSubHook

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

CredsSubHook performs credential substitution using a credsub.Table. PreHook replaces fake credentials with real ones in request bodies. PostHook replaces real credentials with fakes in response bodies.

func NewCredsSubHook

func NewCredsSubHook(table *credsub.Table, scrubServices map[string]bool) *CredsSubHook

NewCredsSubHook returns a CredsSubHook that uses the given table. scrubServices controls which services have response scrubbing enabled. Pass nil to scrub all responses (backward-compatible default).

func (*CredsSubHook) Name

func (h *CredsSubHook) Name() string

func (*CredsSubHook) PostHook

func (h *CredsSubHook) PostHook(resp *http.Response, ctx *RequestContext) error

PostHook replaces real credentials with fakes in the response body. When scrubServices is non-nil, scrubbing is skipped for services not in the map.

func (*CredsSubHook) PreHook

func (h *CredsSubHook) PreHook(r *http.Request, _ *RequestContext) error

PreHook replaces fake credentials with real ones in the request body, header values, URL query string, and URL path.

type DLPInfo

type DLPInfo struct {
	Redactions []Redaction `json:"redactions"`
}

DLPInfo contains DLP processing information.

type DLPProcessor

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

DLPProcessor processes data for PII detection and redaction/tokenization.

func NewDLPProcessor

func NewDLPProcessor(cfg config.DLPConfig) *DLPProcessor

NewDLPProcessor creates a new DLP processor using config.DLPConfig.

func (*DLPProcessor) Detokenize

func (dp *DLPProcessor) Detokenize(text string) string

Detokenize reverses tokenization for a given text.

func (*DLPProcessor) DetokenizeReader

func (dp *DLPProcessor) DetokenizeReader(r io.Reader) io.Reader

DetokenizeReader wraps r so tokens are replaced with their originals as the stream is read.

Streaming needs its own path because a token can straddle a chunk boundary. A per-chunk ReplaceAllString would leave "TOK_abcd" at the end of one read and "ef0123456789" at the start of the next, and neither half matches, so the token would reach the client intact and unresolvable. This holds back a short tail until either enough bytes arrive to decide or the stream ends.

When tokenization is not the active mode there is nothing to reverse, so r is returned unwrapped and the stream keeps its original read boundaries.

func (*DLPProcessor) ExportTokenMap

func (dp *DLPProcessor) ExportTokenMap() map[string]string

ExportTokenMap exports the token mapping for external storage.

func (*DLPProcessor) ImportTokenMap

func (dp *DLPProcessor) ImportTokenMap(m map[string]string)

ImportTokenMap imports a token mapping.

func (*DLPProcessor) Mode

func (dp *DLPProcessor) Mode() string

Mode returns the DLP mode (redact, tokenize, or disabled).

func (*DLPProcessor) PatternCount

func (dp *DLPProcessor) PatternCount() int

PatternCount returns the number of active DLP patterns.

func (*DLPProcessor) PatternNames

func (dp *DLPProcessor) PatternNames() []string

PatternNames returns the names of active DLP patterns.

func (*DLPProcessor) Process

func (dp *DLPProcessor) Process(data []byte, dialect Dialect) *DLPResult

Process applies DLP to the given data.

func (*DLPProcessor) Tokenize

func (dp *DLPProcessor) Tokenize(original string) string

Tokenize mints (or reuses) the reversible pseudonym for a value.

It is the same store the regex DLP path uses, deliberately: one token space per session means Detokenize on the response reverses both, and a value found by both a regex pattern and an inspection profile gets one token rather than two.

type DLPResult

type DLPResult struct {
	// ProcessedData is the data after DLP processing.
	ProcessedData []byte

	// Redactions is a list of redactions that were applied.
	Redactions []Redaction

	// Modified indicates if any changes were made.
	Modified bool
}

DLPResult contains the result of DLP processing.

type Dialect

type Dialect string

Dialect represents an LLM API provider dialect.

const (
	DialectUnknown   Dialect = "unknown"
	DialectAnthropic Dialect = "anthropic"
	DialectOpenAI    Dialect = "openai"
)

type DialectConfig

type DialectConfig struct {
	// Upstream is the base URL for the provider's API.
	Upstream *url.URL

	// AuthHeader is the header name used for authentication.
	// e.g., "x-api-key" for Anthropic, "Authorization" for OpenAI
	AuthHeader string

	// PathPrefixes are path prefixes that identify this dialect.
	PathPrefixes []string
}

DialectConfig holds configuration for a specific LLM provider dialect.

type DialectDetector

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

DialectDetector detects the LLM provider dialect from HTTP requests.

func NewDialectDetector

func NewDialectDetector(configs map[Dialect]*DialectConfig) *DialectDetector

NewDialectDetector creates a new dialect detector with the given configs.

func (*DialectDetector) Detect

func (d *DialectDetector) Detect(r *http.Request) Dialect

Detect determines the dialect from the request. Detection order: 1. x-api-key header -> Anthropic 2. anthropic-version header -> Anthropic 3. Authorization header present -> OpenAI 4. No auth -> Unknown

func (*DialectDetector) GetUpstream

func (d *DialectDetector) GetUpstream(dialect Dialect) *url.URL

GetUpstream returns the upstream URL for the given dialect.

type HTTPServiceApprovalsManager

type HTTPServiceApprovalsManager interface {
	RequestApproval(ctx context.Context, req approvals.Request) (approvals.Resolution, error)
}

HTTPServiceApprovalsManager is the subset of approvals.Manager needed by the declared-service path. Declared here as a local interface to keep the import surface narrow and to simplify testing — tests install a fake implementation via SetApprovalsForTest and don't have to spin up a real approvals.Manager with its TTY/TOTP/WebAuthn machinery.

type HeaderInjectionHook

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

HeaderInjectionHook injects the real credential into a request header. Registered per service name so it only fires for matched requests.

func NewHeaderInjectionHook

func NewHeaderInjectionHook(serviceName, headerName, template string, table *credsub.Table) *HeaderInjectionHook

NewHeaderInjectionHook creates a hook that injects the real credential for serviceName into the header specified by headerName using template. The template must contain "{{secret}}" which is replaced with the real credential at request time.

func (*HeaderInjectionHook) HeaderName

func (h *HeaderInjectionHook) HeaderName() string

HeaderName returns the header that this hook injects. Used by the declared-service log path to redact the injected value from audit records.

func (*HeaderInjectionHook) Name

func (h *HeaderInjectionHook) Name() string

func (*HeaderInjectionHook) PostHook

func (*HeaderInjectionHook) PreHook

type Hook

type Hook interface {
	// Name returns a stable identifier for this hook, used in logs and
	// audit events.
	Name() string

	// PreHook is called before the request is forwarded upstream.
	PreHook(*http.Request, *RequestContext) error

	// PostHook is called after the upstream response arrives and before
	// it is returned to the agent.
	PostHook(*http.Response, *RequestContext) error
}

Hook is an extension point registered with the proxy. Hooks are keyed by service name and invoked for every request routed to that service. A hook registered under the empty service name runs for every request regardless of which service (if any) matched.

PreHook runs BEFORE the proxy forwards the request to the upstream. At this point the request body still contains whatever the agent sent (including any fake credentials that a later substitution pass will replace). A hook that needs to see the post-substitution body is out of scope for this plan — the Hook interface may grow a third phase in a later plan if that need is real.

Returning a non-nil error from PreHook aborts the request. The proxy returns an HTTP 502 to the agent and logs the error. Remaining pre-hooks for the same request are NOT invoked.

PostHook runs AFTER the upstream responds, but BEFORE the response is returned to the agent. This is where response-time concerns live (audit logging, response scrubbing, token accounting).

Returning a non-nil error from PostHook is logged but does not change the response the agent sees. All post-hooks for the same request are invoked even if one fails.

type HookAbortError

type HookAbortError struct {
	StatusCode int
	Message    string
}

HookAbortError is returned by a PreHook to abort the request with a specific HTTP status code. When the proxy receives this error from ApplyPreHooks, it responds with the given status code and message instead of forwarding the request. Any other error type results in a 502 Bad Gateway.

func (*HookAbortError) Error

func (e *HookAbortError) Error() string

type InspectConfig

type InspectConfig struct {
	// Resolve supplies the engine and inspector per request.
	Resolve InspectContextFunc
	// MaxBodyBytes overrides DefaultInspectMaxBodyBytes. Zero uses it.
	MaxBodyBytes int64
	// MCPArgMaxBytes overrides DefaultMCPArgMaxBytes, the cap on a single
	// MCP tool call's accumulated arguments. Zero uses it.
	MCPArgMaxBytes int
}

InspectConfig is what a session hands the LLM proxy to enable inspection.

func (InspectConfig) Enabled

func (c InspectConfig) Enabled() bool

Enabled reports whether inspection should be wired for this session.

type InspectContextFunc

type InspectContextFunc func() (*policy.Engine, policy.InspectChecker)

InspectContextFunc supplies the policy engine and its inspector for the current request.

It is a function rather than two stored pointers so the engine is resolved per request. Proxy.SetPolicyEngine captures an engine at construction, and that capture is why the network, transparent-TCP and DNS paths keep enforcing the previous policy after a live update (documented at internal/api/session_policy.go:47). Inspection does not need a fourth instance of that bug.

type InspectHook

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

InspectHook runs content inspection over request bodies.

It resolves only decisions that carry an inspection spec. A plain network deny is left alone: the proxy, the macOS network filter and the Linux netmonitor each enforce network policy on their own path, and a second enforcement point here would change behaviour for every deployment that does not use inspection at all.

func NewInspectHook

func NewInspectHook(resolve InspectContextFunc, maxBody int64, logger *slog.Logger) *InspectHook

NewInspectHook returns a hook that inspects request bodies. A zero or negative maxBody uses DefaultInspectMaxBodyBytes.

func (*InspectHook) Name

func (h *InspectHook) Name() string

Name implements Hook.

func (*InspectHook) PostHook

func (h *InspectHook) PostHook(*http.Response, *RequestContext) error

PostHook implements Hook. Response inspection is not wired: a policy decision is about what the agent sends, and the response path has its own scrubbing in CredsSubHook and the DLP processor.

func (*InspectHook) PreHook

func (h *InspectHook) PreHook(r *http.Request, ctx *RequestContext) error

PreHook implements Hook.

func (*InspectHook) SetDLP

func (h *InspectHook) SetDLP(dp *DLPProcessor)

SetDLP installs the DLP processor whose token store backs reversible redaction. Without it, on_violation: redact writes a placeholder.

type InterceptResult

type InterceptResult struct {
	Events        []mcpinspect.MCPToolCallInterceptedEvent
	HasBlocked    bool
	RewrittenBody []byte // Non-nil if tool calls were blocked or arguments redacted
}

InterceptResult holds the outcome of MCP tool call interception.

type LLMRateLimiter

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

LLMRateLimiter enforces RPM (requests per minute) and TPM (tokens per minute) rate limits on LLM API calls to prevent denial-of-wallet attacks.

func NewLLMRateLimiter

func NewLLMRateLimiter(cfg config.LLMRateLimitsConfig) *LLMRateLimiter

NewLLMRateLimiter creates a new LLM rate limiter from configuration.

func (*LLMRateLimiter) AcquireInFlight

func (l *LLMRateLimiter) AcquireInFlight() bool

AcquireInFlight attempts to acquire an in-flight slot (when TPM is enabled). Returns false if TPM is not configured or the concurrency cap is reached. Non-blocking: if all slots are occupied, returns false immediately so the caller can reject the request (e.g. 429) instead of piling up goroutines.

func (*LLMRateLimiter) AllowRequest

func (l *LLMRateLimiter) AllowRequest() bool

AllowRequest checks whether a new request is allowed under the RPM limit.

func (*LLMRateLimiter) AllowTokens

func (l *LLMRateLimiter) AllowTokens(n int) bool

AllowTokens checks whether the given number of tokens is allowed under the TPM limit.

func (*LLMRateLimiter) ConsumeTokens

func (l *LLMRateLimiter) ConsumeTokens(n int)

ConsumeTokens deducts tokens from the TPM budget after a response is received. Uses force-consume since the operation already happened and must be accounted for.

func (*LLMRateLimiter) ReleaseInFlight

func (l *LLMRateLimiter) ReleaseInFlight()

ReleaseInFlight releases an in-flight slot. Must be called after AcquireInFlight returns true, typically in a defer.

func (*LLMRateLimiter) TPMEnabled

func (l *LLMRateLimiter) TPMEnabled() bool

TPMEnabled returns true if tokens-per-minute limiting is active.

func (*LLMRateLimiter) TokenBudgetAvailable

func (l *LLMRateLimiter) TokenBudgetAvailable() bool

TokenBudgetAvailable returns true if the TPM bucket is not depleted. Use this as a pre-request gate: if previous responses have driven the token bucket negative (via ForceConsumeN), block new requests until tokens replenish.

type LeakGuardHook

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

LeakGuardHook blocks requests that contain known fake credentials.

func NewLeakGuardHook

func NewLeakGuardHook(table *credsub.Table, logger *slog.Logger) *LeakGuardHook

NewLeakGuardHook returns a LeakGuardHook that scans for fakes.

func (*LeakGuardHook) Name

func (h *LeakGuardHook) Name() string

func (*LeakGuardHook) PostHook

func (h *LeakGuardHook) PostHook(_ *http.Response, _ *RequestContext) error

func (*LeakGuardHook) PreHook

func (h *LeakGuardHook) PreHook(r *http.Request, ctx *RequestContext) error

type Proxy

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

Proxy is an HTTP proxy that intercepts LLM API requests.

func New

func New(cfg Config, storagePath string, logger *slog.Logger) (*Proxy, error)

New creates a new LLM proxy.

func (*Proxy) Addr

func (p *Proxy) Addr() net.Addr

Addr returns the proxy's listening address.

func (*Proxy) DLP

func (p *Proxy) DLP() *DLPProcessor

DLP returns the proxy's DLP processor, or nil.

func (*Proxy) EnvVars

func (p *Proxy) EnvVars() map[string]string

EnvVars returns the environment variables to set for the agent process. In addition to the LLM base URLs, this includes one <NAME>_API_URL entry per declared http_services entry, each pointing at /svc/<name> on the proxy listener so cooperating child processes can route through the gateway via a base URL override.

func (*Proxy) HookRegistry

func (p *Proxy) HookRegistry() *Registry

HookRegistry returns the proxy's hook registry. Callers use this to register Hook implementations that participate in the request pipeline.

func (*Proxy) ServeHTTP

func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler.

func (*Proxy) SetApprovalsForTest

func (p *Proxy) SetApprovalsForTest(m HTTPServiceApprovalsManager)

SetApprovalsForTest installs an approvals manager for the declared- service path. Test-only; production wiring goes through SetHTTPServiceApprovals.

func (*Proxy) SetEventCallback

func (p *Proxy) SetEventCallback(fn func(mcpinspect.MCPToolCallInterceptedEvent))

SetEventCallback sets a callback that is invoked for each MCP tool call intercept event. It is safe for concurrent use.

func (*Proxy) SetHTTPServiceApprovals

func (p *Proxy) SetHTTPServiceApprovals(m HTTPServiceApprovalsManager)

SetHTTPServiceApprovals wires the approvals manager consulted for `approve` decisions on declared services. Called once during startup from app.go alongside SetPolicyEngine and SetHTTPServices.

func (*Proxy) SetHTTPServiceTransportForTest

func (p *Proxy) SetHTTPServiceTransportForTest(rt http.RoundTripper)

SetHTTPServiceTransportForTest injects a RoundTripper used for declared-service forwarding. Test-only.

func (*Proxy) SetHTTPServices

func (p *Proxy) SetHTTPServices(svcs []policy.HTTPService)

SetHTTPServices stores the declared HTTP services for env var injection. Called once during proxy startup in app.go. Thread-safe. The slice is stored as-is — SetHTTPServices replaces it whole on each call and EnvVars snapshots it under lock, so no in-place mutation is safe.

func (*Proxy) SetMCPArgInspection

func (p *Proxy) SetMCPArgInspection(resolve InspectContextFunc, maxArgs int)

SetMCPArgInspection installs argument inspection for MCP tool calls. A nil resolve disables it.

func (*Proxy) SetPolicyEngine

func (p *Proxy) SetPolicyEngine(e *policy.Engine)

SetPolicyEngine wires the policy engine for http_services dispatch. Called once during startup.

func (*Proxy) SetRegistry

func (p *Proxy) SetRegistry(r *mcpregistry.Registry)

SetRegistry sets the MCP tool registry on the proxy. It is safe for concurrent use and is called once the shim has finished discovering tools.

func (*Proxy) SetSessionAnalyzer

func (p *Proxy) SetSessionAnalyzer(analyzer *mcpinspect.SessionAnalyzer)

SetSessionAnalyzer sets the cross-server analyzer on the proxy. It is safe for concurrent use and is called once the analyzer has been created.

func (*Proxy) SetStorageForTest

func (p *Proxy) SetStorageForTest(s *Storage)

SetStorageForTest installs a Storage instance for the declared-service logging path. Production uses the same Storage that the LLM path uses; tests point it at a temp dir. Test-only setter to keep the dependency visible.

func (*Proxy) Start

func (p *Proxy) Start(ctx context.Context) error

Start starts the proxy server.

func (*Proxy) Stats

func (p *Proxy) Stats() (ProxyStatus, error)

Stats returns the current proxy status including usage statistics.

func (*Proxy) Stop

func (p *Proxy) Stop(ctx context.Context) error

Stop stops the proxy server.

type ProxyStats

type ProxyStats struct {
	TotalRequests          int `json:"total_requests"`
	RequestsWithRedactions int `json:"requests_with_redactions"`
	TotalInputTokens       int `json:"total_input_tokens"`
	TotalOutputTokens      int `json:"total_output_tokens"`
	TotalRedactions        int `json:"total_redactions"`
}

ProxyStats contains aggregated statistics from the proxy log.

type ProxyStatus

type ProxyStatus struct {
	State                  string   `json:"state"`
	Address                string   `json:"address"`
	Mode                   string   `json:"mode"`
	DLPMode                string   `json:"dlp_mode"`
	ActivePatterns         int      `json:"active_patterns"`
	PatternNames           []string `json:"pattern_names,omitempty"`
	TotalRequests          int      `json:"total_requests"`
	RequestsWithRedactions int      `json:"requests_with_redactions"`
	TotalInputTokens       int      `json:"total_input_tokens"`
	TotalOutputTokens      int      `json:"total_output_tokens"`
}

ProxyStatus contains the complete status of the proxy.

type Redaction

type Redaction struct {
	// Field is the JSON path where the redaction occurred (if applicable).
	Field string `json:"field,omitempty"`

	// Type is the internal type name of PII that was detected (for logs).
	Type string `json:"type"`

	// Count is the number of unique instances redacted.
	Count int `json:"count"`
}

Redaction describes a single redaction event.

type Registry

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

Registry stores hooks keyed by service name. It is safe for concurrent use. Hooks registered for the same service name are invoked in registration order.

The zero value of Registry is NOT usable — call NewRegistry.

func NewRegistry

func NewRegistry() *Registry

NewRegistry returns an empty hook registry.

func (*Registry) ApplyPostHooks

func (r *Registry) ApplyPostHooks(serviceName string, resp *http.Response, ctx *RequestContext) error

ApplyPostHooks invokes PostHook on every hook registered under the empty service name and serviceName, in registration order. Unlike ApplyPreHooks, errors do NOT short-circuit — every hook is invoked even if an earlier one fails. The first error encountered is returned; subsequent errors are silently dropped (hooks that need their own error reporting should log internally).

func (*Registry) ApplyPreHooks

func (r *Registry) ApplyPreHooks(serviceName string, req *http.Request, ctx *RequestContext) error

ApplyPreHooks invokes PreHook on each hook registered under the empty service name followed by each hook registered under serviceName, in registration order. It stops at the first non-nil error and returns it. Hooks that have not been reached are not invoked.

func (*Registry) InjectedHeaderNamesForService

func (r *Registry) InjectedHeaderNamesForService(serviceName string) []string

InjectedHeaderNamesForService returns the set of header names that HeaderInjectionHook entries registered for serviceName will write. Declared-service request/response logging consults this list so the audit sanitizer can redact the injected values even when the header name is not in the fixed auth denylist. Includes hooks registered under the empty service name (which run globally).

func (*Registry) Register

func (r *Registry) Register(serviceName string, h Hook)

Register adds a hook under the given service name. A hook may be registered multiple times under different service names; a single service may have multiple hooks registered. Use the empty string as the service name to register a hook that runs for every request.

Register panics if h is nil — all hooks must be non-nil interface values. This catches programmer errors at registration time rather than producing a confusing nil pointer dereference later inside ApplyPreHooks or ApplyPostHooks. Both bare nil (an untyped nil interface) and typed-nil hooks (e.g. a nil *concreteHook assigned to a Hook variable) are rejected.

type RequestContext

type RequestContext struct {
	// RequestID is a unique identifier assigned by the proxy for each
	// incoming request. Hooks may use it for correlation across logs.
	RequestID string

	// SessionID is the agentmon session ID that owns the spawned process
	// making this request.
	SessionID string

	// ServiceName is the name of the service this request was matched
	// to, or the empty string if no service matched. Hooks registered
	// under the empty service name run for every request regardless of
	// match.
	ServiceName string

	// StartTime is when the proxy first saw this request.
	StartTime time.Time

	// Attrs is a hook-private scratch area. Hooks must namespace their
	// keys to avoid colliding with other hooks.
	Attrs map[string]any
}

RequestContext carries per-request state shared between the proxy and any registered hooks. It is created by the proxy at the start of each request and passed to PreHook and PostHook callbacks.

Attrs is a free-form map intended for hooks to communicate with each other — for example, a DLP hook storing its redaction result so a later logging hook can include it in the audit event. Keys should be namespaced with the hook's package name (e.g. "llm.dlp.result") to avoid collisions.

type RequestInfo

type RequestInfo struct {
	Method   string              `json:"method"`
	Path     string              `json:"path"`
	Headers  map[string][]string `json:"headers"`
	BodySize int                 `json:"body_size"`
	BodyHash string              `json:"body_hash"`
}

RequestInfo contains request details.

type RequestLogEntry

type RequestLogEntry struct {
	ID          string      `json:"id"`
	SessionID   string      `json:"session_id"`
	Timestamp   time.Time   `json:"timestamp"`
	Dialect     Dialect     `json:"dialect,omitempty"`
	ServiceKind string      `json:"service_kind,omitempty"` // "llm" or "http_service"
	ServiceName string      `json:"service_name,omitempty"` // e.g. "github"
	RuleName    string      `json:"rule_name,omitempty"`    // e.g. "read-issues"
	Request     RequestInfo `json:"request"`
	DLP         *DLPInfo    `json:"dlp,omitempty"`
}

RequestLogEntry represents a logged request.

type RequestRewriter

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

RequestRewriter rewrites requests for forwarding to upstream.

func NewRequestRewriter

func NewRequestRewriter(detector *DialectDetector) *RequestRewriter

NewRequestRewriter creates a new request rewriter.

func (*RequestRewriter) Rewrite

func (rw *RequestRewriter) Rewrite(r *http.Request, dialect Dialect, upstream *url.URL) (*http.Request, error)

Rewrite modifies the request for forwarding to the upstream provider. It updates the URL scheme/host and adjusts headers as needed.

type ResponseInfo

type ResponseInfo struct {
	Status   int                 `json:"status"`
	Headers  map[string][]string `json:"headers"`
	BodySize int                 `json:"body_size,omitempty"`
	BodyHash string              `json:"body_hash,omitempty"`
}

ResponseInfo contains response details.

type ResponseLogEntry

type ResponseLogEntry struct {
	RequestID  string       `json:"request_id"`
	SessionID  string       `json:"session_id"`
	Timestamp  time.Time    `json:"timestamp"`
	DurationMs int64        `json:"duration_ms"`
	Response   ResponseInfo `json:"response"`
	Usage      Usage        `json:"usage,omitempty"`
}

ResponseLogEntry represents a logged response.

type RetentionConfig

type RetentionConfig struct {
	MaxAgeDays int    // Delete sessions older than this (0 = disabled)
	MaxSizeMB  int    // Max total storage size in MB (0 = disabled)
	Eviction   string // "oldest_first" or "largest_first"
}

RetentionConfig configures session cleanup policy.

type RetentionResult

type RetentionResult struct {
	SessionsRemoved int
	BytesReclaimed  int64
	Sessions        []string // IDs of removed sessions
}

RetentionResult reports cleanup results.

func RunRetention

func RunRetention(
	sessionsDir string,
	config RetentionConfig,
	currentSessionID string,
	logger *slog.Logger,
) (*RetentionResult, error)

RunRetention cleans up old sessions based on retention policy. currentSessionID is excluded from cleanup. Runs synchronously - caller should use goroutine if non-blocking behavior is needed.

type SSEInterceptor

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

SSEInterceptor processes an SSE stream line-by-line, evaluating MCP tool calls against a policy and suppressing/replacing blocked tool_use events mid-stream. It replaces the previous io.Copy approach where SSE interception was audit-only.

func NewSSEInterceptor

func NewSSEInterceptor(
	registry *mcpregistry.Registry,
	policy *mcpinspect.PolicyEvaluator,
	dialect Dialect,
	sessionID, requestID string,
	onEvent func(mcpinspect.MCPToolCallInterceptedEvent),
	logger *slog.Logger,
	analyzer *mcpinspect.SessionAnalyzer,
	rateLimiter *mcpinspect.RateLimiterRegistry,
	versionPinCfg *config.MCPVersionPinningConfig,
	mcpArgs *mcpArgInspector,
) *SSEInterceptor

NewSSEInterceptor creates a new SSE stream interceptor. The analyzer parameter enables cross-server pattern detection; pass nil to disable.

func (*SSEInterceptor) Stream

func (s *SSEInterceptor) Stream(ctx context.Context, upstream io.Reader, client io.Writer) []byte

Stream reads SSE lines from upstream, evaluates tool calls against policy, and writes (possibly modified) output to client. Returns the buffered output for logging/auditing.

type Storage

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

Storage handles request/response logging to disk.

func NewStorage

func NewStorage(basePath, sessionID string, storeBodies bool) (*Storage, error)

NewStorage creates a new storage instance. basePath is the base storage directory (e.g., ~/.agentmon/sessions). sessionID is the current session ID. storeBodies enables storing full request/response bodies to disk.

func (*Storage) BodiesPath

func (s *Storage) BodiesPath() string

BodiesPath returns the path to the bodies directory.

func (*Storage) Close

func (s *Storage) Close() error

Close closes the storage file.

func (*Storage) GetStats

func (s *Storage) GetStats() (ProxyStats, error)

GetStats reads the log file and computes aggregated statistics.

func (*Storage) LogPath

func (s *Storage) LogPath() string

LogPath returns the path to the JSONL log file.

func (*Storage) LogRequest

func (s *Storage) LogRequest(entry *RequestLogEntry) error

LogRequest logs a request entry to the JSONL file.

func (*Storage) LogResponse

func (s *Storage) LogResponse(entry *ResponseLogEntry) error

LogResponse logs a response entry to the JSONL file.

func (*Storage) ReadLogEntries

func (s *Storage) ReadLogEntries() ([]json.RawMessage, error)

ReadLogEntries reads all log entries from storage. This is useful for testing and debugging.

func (*Storage) ReadRequestBody

func (s *Storage) ReadRequestBody(requestID string) ([]byte, error)

ReadRequestBody reads a stored request body from disk. Returns nil if the file doesn't exist.

func (*Storage) ReadResponseBody

func (s *Storage) ReadResponseBody(requestID string) ([]byte, error)

ReadResponseBody reads a stored response body from disk. Returns nil if the file doesn't exist.

func (*Storage) StoreBodiesEnabled

func (s *Storage) StoreBodiesEnabled() bool

StoreBodiesEnabled returns whether body storage is enabled.

func (*Storage) StoreRequestBody

func (s *Storage) StoreRequestBody(requestID string, body []byte) error

StoreRequestBody stores the request body to disk. The body is stored as JSON in llm-bodies/<request_id>.json Returns nil if body storage is disabled or body is empty.

func (*Storage) StoreResponseBody

func (s *Storage) StoreResponseBody(requestID string, body []byte) error

StoreResponseBody stores the response body to disk. The body is stored as JSON in llm-bodies/<request_id>.resp.json Returns nil if body storage is disabled or body is empty.

type ToolCall

type ToolCall struct {
	ID    string          // "toolu_..." or "call_..."
	Name  string          // tool name
	Input json.RawMessage // arguments
}

ToolCall represents a tool invocation extracted from an LLM response.

func ExtractToolCalls

func ExtractToolCalls(body []byte, dialect Dialect) []ToolCall

ExtractToolCalls parses tool call blocks from an LLM response body. It returns nil if no tool calls are found or the body is malformed.

func ExtractToolCallsFromSSE

func ExtractToolCallsFromSSE(sseBody []byte, dialect Dialect) []ToolCall

ExtractToolCallsFromSSE parses tool calls from a buffered SSE response body. It dispatches to dialect-specific extractors based on the dialect parameter. Returns nil if no tool calls are found.

For SSE extraction, ToolCall.Input will be nil because we do not accumulate streamed argument deltas -- we only need the tool name and ID for policy evaluation.

type Usage

type Usage struct {
	InputTokens  int  `json:"input_tokens"`
	OutputTokens int  `json:"output_tokens"`
	HasUsage     bool `json:"-"` // true when the response contained a parseable usage field
}

Usage represents normalized token usage from LLM responses. Different providers use different field names, but we normalize to input_tokens and output_tokens for consistent logging and cost attribution.

func ExtractSSEUsage

func ExtractSSEUsage(body []byte, dialect Dialect) Usage

ExtractSSEUsage extracts token usage from an SSE event stream body. It scans each "data:" line for usage information.

func ExtractUsage

func ExtractUsage(body []byte, dialect Dialect) Usage

ExtractUsage extracts token usage from an LLM response body. It normalizes the provider-specific field names to the standard InputTokens and OutputTokens fields.

For Anthropic responses:

{"usage": {"input_tokens": 150, "output_tokens": 892}}

For OpenAI/ChatGPT responses:

{"usage": {"prompt_tokens": 150, "completion_tokens": 892, "total_tokens": 1042}}

Returns zero Usage if the body is empty, invalid JSON, or the dialect is unknown.

Directories

Path Synopsis
Package credsub implements the per-session credential substitution table that maps fake credentials (the bytes an agent sees in its environment) to real credentials (the bytes sent upstream).
Package credsub implements the per-session credential substitution table that maps fake credentials (the bytes an agent sees in its environment) to real credentials (the bytes sent upstream).
Package secrets defines the SecretProvider interface that agentmon uses to fetch real credentials from external secret stores at session start, plus the URI grammar, sentinel errors, and the provider Registry shared by all provider implementations.
Package secrets defines the SecretProvider interface that agentmon uses to fetch real credentials from external secret stores at session start, plus the URI grammar, sentinel errors, and the provider Registry shared by all provider implementations.
awssm
Package awssm implements secrets.SecretProvider using AWS Secrets Manager.
Package awssm implements secrets.SecretProvider using AWS Secrets Manager.
azurekv
Package azurekv implements secrets.SecretProvider using Azure Key Vault.
Package azurekv implements secrets.SecretProvider using Azure Key Vault.
gcpsm
Package gcpsm implements secrets.SecretProvider using GCP Secret Manager.
Package gcpsm implements secrets.SecretProvider using GCP Secret Manager.
keyring
Package keyring implements secrets.SecretProvider using the OS keyring: macOS Keychain (via /usr/bin/security), Linux Secret Service (via D-Bus), or Windows Credential Manager.
Package keyring implements secrets.SecretProvider using the OS keyring: macOS Keychain (via /usr/bin/security), Linux Secret Service (via D-Bus), or Windows Credential Manager.
onepassword
Package onepassword implements secrets.SecretProvider using the 1Password Connect API.
Package onepassword implements secrets.SecretProvider using the 1Password Connect API.
secretstest
Package secretstest provides test doubles for the secrets.SecretProvider interface.
Package secretstest provides test doubles for the secrets.SecretProvider interface.
vault
Package vault implements secrets.SecretProvider using HashiCorp Vault's KV v2 secrets engine.
Package vault implements secrets.SecretProvider using HashiCorp Vault's KV v2 secrets engine.

Jump to

Keyboard shortcuts

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