agenttrace

package
v2.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: AGPL-3.0 Imports: 16 Imported by: ? 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 agenttrace is the capture contract for Agent Call Tracing, shared by the gateway hooks in proxy/, the embedded and edge transports, and the Enterprise assembler (spec: enterprise/features/agenttracing/SPEC.md).

It holds three things:

  • The flag. Enabled is an atomic set once at start-up by the Enterprise service (services/agenttracing) or the Enterprise microgateway; it is false in Community builds. Gateway code reads it once per request.
  • The capture event. Event is one observed span (an LLM call, a tool or MCP call, a datasource call, a plugin endpoint or a gateway event) as the gateway saw it, plus its correlation extracts. ToProto and FromProto convert it for the edge pulse and the staging table.
  • The per-request recorder. Begin attaches a Recorder to the request context; hooks find it with From and fill the span; Finish hands the events to the registered Sink. Every entry point is a no-op that allocates nothing when the flag is off or no recorder is attached, so call sites need no guard of their own.

The package must not depend on proxy/, models/ or GORM (a test enforces this) so both runtimes and the assembler can import it.

Index

Constants

View Source
const (
	ResourceLLM        = "llm"
	ResourceTool       = "tool"
	ResourceDatasource = "datasource"
	ResourcePlugin     = "plugin"
)

Resource types (spec §3.4 spans.resource_type).

View Source
const (
	ContentOff      = "off"
	ContentMetadata = "metadata"
	ContentHashed   = "hashed"
	ContentRedacted = "redacted"
	ContentFull     = "full"
)

Content modes in disclosure order (spec §5.5): off < metadata < hashed < redacted < full.

View Source
const (
	StateNotCaptured = "not_captured"
	StateMetadata    = "metadata"
	StateHashed      = "hashed"
	StateRedacted    = "redacted"
	StateFull        = "full"
	StateTruncated   = "truncated"
	StateDropped     = "dropped" // queue overflow (spec §10 drop policy)
)

Content states of a payload part or span (spec §3.4, §5.5). The UI and export distinguish all of them.

View Source
const (
	PartRequest            = "request"
	PartResponse           = "response"
	PartSystemInstructions = "system_instructions"
	PartToolDefinitions    = "tool_definitions"
	PartToolArgs           = "tool_args"
	PartToolResult         = "tool_result"
	PartErrorBody          = "error_body"
)

Payload parts (spec §3.4 agent_trace_payloads.part).

View Source
const (
	GatewayEventAttempt   = "attempt"
	GatewayEventFallback  = "fallback"
	GatewayEventGuardrail = "guardrail"
	GatewayEventFilter    = "filter"
	GatewayEventBudget    = "budget"
	GatewayEventRateLimit = "rate_limit"
	GatewayEventAuth      = "auth"
	GatewayEventPolicy    = "policy"
	GatewayEventRouter    = "router"
	GatewayEventOverload  = "overload"
	GatewayEventCache     = "cache"
)

Gateway event types (spec §3.2 gateway_event, §4.5 retries and fallbacks).

View Source
const (
	OutcomeAllow   = "allow"
	OutcomeBlock   = "block"
	OutcomeModify  = "modify"
	OutcomeSkip    = "skip"
	OutcomeError   = "error"
	OutcomeSuccess = "success"
	OutcomeShadow  = "shadow" // a guardrail in shadow mode that would have blocked
)

Gateway event outcomes.

View Source
const (
	DropPayload            = "payload"              // payload bytes removed, span kept (§10 step 1)
	DropGatewayEventDetail = "gateway_event_detail" // gateway event details removed (§10 step 2)
	DropSpan               = "span"                 // whole span dropped (§10 step 3)
	DropNoSealer           = "no_sealer"            // payload bytes removed: no key to seal them
	DropWriteError         = "write_error"          // the staging write or the send failed for good
)

Capture drop reasons (spec §10; tyk_tracing_capture_dropped{reason}).

View Source
const AttrRequestID = "tyk.request.id"

AttrRequestID is the capture attribute holding the gateway's request id.

View Source
const SourceEmbedded = "embedded"

SourceEmbedded is Event.Source for the hub's embedded gateway. Edges use their edge id.

View Source
const WithheldEdgeLinkUnverifiedTLS = "edge_link_unverified_tls"

WithheldEdgeLinkUnverifiedTLS is the tyk.content.withheld reason of an edge whose link to the hub is not verified TLS (jyx.164).

Variables

View Source
var ErrStagedSealed = errors.New("agenttrace: staged event is sealed and no sealer is installed")

ErrStagedSealed is returned by DecodeStaged for a sealed row when no Sealer is installed.

Functions

func AddGatewayEvent

func AddGatewayEvent(ctx context.Context, ge GatewayEvent)

AddGatewayEvent adds a gateway event to the request's primary span.

func AddPart

func AddPart(ctx context.Context, p PayloadPart)

AddPart adds a payload part to the request's primary span.

func CaptureAttributeKeys

func CaptureAttributeKeys() []string

CaptureAttributeKeys lists the attributes a capture may carry (tests pin it).

func CaptureRaw

func CaptureRaw(ctx context.Context, part, mediaType string, data []byte)

CaptureRaw adds a raw part to the request's primary span. The data is copied (up to the cap), so the caller may reuse its buffer. A no-op without a Recorder: in off mode the hook should not even buffer the body.

func DroppedNoSink

func DroppedNoSink() uint64

DroppedNoSink counts events finished while no Sink was installed.

func EdgeKey

func EdgeKey() (id byte, key []byte, ok bool)

EdgeKey returns the key the installed Fingerprinter hands to edges. ok is false when tracing is not running on this node or the Fingerprinter does not export one.

func Emit

func Emit(ctx context.Context, ev *Event)

Emit adds an extra event to the request's Recorder (for example a gateway_event span with no parent span of its own). No-op when there is no Recorder. The Recorder owns ev afterwards.

func Enabled

func Enabled() bool

Enabled reports whether agent tracing is on for this process. It is set once at start-up and read once per request; it allocates nothing.

Only the Enterprise start gate (services/agenttracing, or the Enterprise microgateway) turns it on: the factory is registered, the licence is valid and AGENT_TRACING_ENABLED=true. In Community builds it stays false. On an edge it is also off while its hub has agent tracing off.

func EncodeStaged

func EncodeStaged(e *Event) (blob []byte, stripped bool, err error)

EncodeStaged turns an event into the staging table's blob. With a Sealer the whole event is sealed, bound to its idempotency key. Without one it fails closed: payload data is stripped (parts become content_state dropped) so no content ever reaches the table in plaintext; stripped reports whether that happened.

The event must have its idempotency key set. EncodeStaged may modify the event's parts when it strips them.

func ExportActive

func ExportActive() bool

ExportActive reports whether assembled spans are being exported.

func InstallEdgeKey

func InstallEdgeKey(id byte, key []byte)

InstallEdgeKey installs, on an edge, the fingerprint key the hub sent in the config snapshot. The key is held in memory only. Id 0 or an empty key removes the Fingerprinter, so the edge computes no fingerprints.

func IsContentAttribute

func IsContentAttribute(name string) bool

IsContentAttribute reports whether a span attribute carries captured content.

func KeepLiveSpan

func KeepLiveSpan() bool

KeepLiveSpan reports the opt-in.

func ProcessContent

func ProcessContent(ev *Event)

ProcessContent runs the content pipeline on ev's raw parts and clears them, once per event. Transports call it in their worker before encoding (EncodeStaged calls it too; the edge pulse transport must call it before ToProto). Without a ContentProcessor it fails closed: each raw part becomes a dropped part with its size and no data. Error messages are redacted only by a processor; without one an error message longer than maxUnprocessedError is cut.

func RegisterContentProcessorFactory

func RegisterContentProcessorFactory(f ContentProcessorFactory)

RegisterContentProcessorFactory is called by the Enterprise pipeline's init().

func RequireHubTracing

func RequireHubTracing(on bool)

RequireHubTracing makes capture depend on the hub (the edge's start gate calls it): events a hub with tracing off would discard are never built.

func SetContentProcessor

func SetContentProcessor(p ContentProcessor)

SetContentProcessor installs the process-wide ContentProcessor. Nil removes it.

func SetEdgeContentGlobals

func SetEdgeContentGlobals(g *ContentGlobals)

SetEdgeContentGlobals publishes the content settings the hub sends edges in the config snapshot (the Enterprise service sets them while tracing runs). Nil withdraws them, and edges then capture no content.

func SetEnabled

func SetEnabled(on bool)

SetEnabled is called by the start gate. Tests use it too; restore the old value with t.Cleanup.

func SetExportActive

func SetExportActive(on bool)

SetExportActive is called by the exporter when it starts and stops.

func SetFingerprinter

func SetFingerprinter(f Fingerprinter)

SetFingerprinter installs the process-wide Fingerprinter (the key provider calls it at start-up and on rotation). Nil removes it.

func SetGatewayNode

func SetGatewayNode(id string)

SetGatewayNode names the gateway every capture of this process comes from (spans.gateway_node): the hub's cluster node id, or the edge's id. The hub overwrites an edge event's value with the authenticated edge id at ingest.

func SetHubTracing

func SetHubTracing(on bool)

SetHubTracing records whether the hub has agent tracing on: its latest config snapshot carried the content policy. The edge's config sync calls it on every applied snapshot.

func SetKeepLiveSpan

func SetKeepLiveSpan(on bool)

SetKeepLiveSpan sets the opt-in; edges call it at start-up.

func SetMaxRawPartBytes

func SetMaxRawPartBytes(n int64)

SetMaxRawPartBytes sets the per-part raw capture cap (start-up).

func SetSealer

func SetSealer(s Sealer)

SetSealer installs the process-wide Sealer (the key provider calls it at start-up). Nil removes it.

func SetSink

func SetSink(s Sink)

SetSink installs the process-wide Sink. Nil removes it.

func StripGatewayEventDetail

func StripGatewayEventDetail(e *Event) bool

StripGatewayEventDetail removes gateway event details (spec §10 drop policy, step 2). It reports whether anything was removed.

func StripPayloadData

func StripPayloadData(e *Event) bool

StripPayloadData removes payload content, keeping each part's metadata and fingerprint with content_state dropped (spec §10 drop policy, step 1). Parts without content (metadata, hashed) are left as they are. It reports whether anything was removed.

func ToProto

func ToProto(e *Event) *pb.CaptureEventProto

ToProto converts an Event for the edge pulse and the staging table.

Types

type Batch

type Batch struct {
	Events []*Event
	Bytes  int64
	// contains filtered or unexported fields
}

Batch is a run of events taken from a Queue.

type ContentGlobals

type ContentGlobals struct {
	// Ceiling bounds every span's mode; DefaultMode applies to Apps without
	// their own (jyx.172). An empty ceiling is off.
	Ceiling            string
	DefaultMode        string
	MaxRequestOverride string
	StoreCap           string
	MaxPartBytes       int
	MaxSpanBytes       int
	StoreBinary        bool
	Detectors          []string
}

ContentGlobals are the install-wide content settings (spec §11): the hub's configuration, which edges receive in the config snapshot.

func EdgeContentGlobals

func EdgeContentGlobals() (ContentGlobals, bool)

EdgeContentGlobals returns the published settings; ok is false when none are published.

type ContentOverrides

type ContentOverrides struct {
	AppMode               string
	AppMaxRequestOverride string
	ResourceMax           string
}

ContentOverrides are the App and resource settings of one span ("" inherits or means no cap).

type ContentOverridesFunc

type ContentOverridesFunc func(appID uint, resource Resource) ContentOverrides

ContentOverridesFunc looks up a span's App and resource settings: from the database on the hub, from the synced configuration on an edge.

type ContentProcessor

type ContentProcessor interface {
	Process(ev *Event)
}

ContentProcessor turns an event's raw parts into persisted-safe parts for its effective content mode (§5.5, §9.3): secret stripping, binary replacement, redaction, truncation, fingerprints. The Enterprise content pipeline implements it, at the capturing gateway (hub or edge), before the event is staged or sent on the pulse. Process sets ev.ContentMode and ev.Parts and redacts ev.ErrorMessage; ProcessContent clears ev.Raw.

func CurrentContentProcessor

func CurrentContentProcessor() ContentProcessor

CurrentContentProcessor returns the installed ContentProcessor, or nil.

func NewContentProcessor

func NewContentProcessor(globals ContentGlobals, overrides ContentOverridesFunc) ContentProcessor

NewContentProcessor builds the registered pipeline, or returns nil when none is registered (Community builds), in which case content stays dropped.

type ContentProcessorFactory

type ContentProcessorFactory func(globals ContentGlobals, overrides ContentOverridesFunc) ContentProcessor

ContentProcessorFactory builds the content pipeline. The Enterprise implementation registers one; core code (the edge's config sync, the hub's service) calls NewContentProcessor and installs the result.

type DeclaredContext

type DeclaredContext struct {
	// TraceID and ParentSpanID from traceparent (or X-Tyk-Trace-Id /
	// compat trace headers when traceparent is absent).
	TraceID      TraceID
	ParentSpanID SpanID
	TraceState   string
	Sampled      bool
	// TraceSource names where the trace id came from: "traceparent",
	// "mcp_meta", "x-tyk", or a compat family (§4.3).
	TraceSource string

	// SessionID is the client session id (§3.4 sessions.external_id) and
	// SessionSource the header family that supplied it
	// (sessions.external_source).
	SessionID     string
	SessionSource string
	SessionName   string

	// Agent identity (§4.3 X-Tyk-Agent-*; baggage gen_ai.agent.name).
	AgentName string
	AgentID   string
	AgentPath string
	// ClientSpanID is X-Tyk-Span-Id: the client's id for the agent step.
	ClientSpanID string

	// EndUserID is X-Tyk-User-Id or baggage user.id.
	EndUserID string
	// CaptureMode is X-Tyk-Trace-Capture as sent; the content pipeline
	// decides what it may change (§5.5).
	CaptureMode string
	// ExternalTraceID keeps a non-W3C trace id (Portkey) that was hashed to
	// W3C length (§4.3, tyk.external.trace_id).
	ExternalTraceID string
	// ConversationID is gen_ai.conversation.id, client-supplied only (Q3).
	ConversationID string
	// MCPSessionID is Mcp-Session-Id: a weak session hint only (§4.3).
	MCPSessionID string
	// ClientInfo is the MCP clientInfo discriminator (§4.2 priority 4).
	ClientInfo string
	// Baggage holds the allowlisted W3C baggage keys (§4.6).
	Baggage map[string]string

	// Coding-harness declarations (bead jyx.52), client-supplied like the
	// rest: Harness names the harness recognised (claude_code, codex_cli,
	// opencode); TurnID is a turn id it declares (Codex CLI), the same for
	// every request of one user turn; SubAgentID is a sub-agent instance it
	// declares (Claude Code), empty on the main agent's requests.
	Harness    string
	TurnID     string
	SubAgentID string
}

DeclaredContext is what the client declared, after precedence (§4.2) and the header set (§4.3). Empty fields were not declared.

type EdgeKeyExporter

type EdgeKeyExporter interface {
	EdgeKey() (id byte, key []byte)
}

EdgeKeyExporter is implemented by the hub's Fingerprinter (the Enterprise key provider). The config snapshot builder sends this key to edges (D4): the derived HMAC key and its id, never the root key.

type Event

type Event struct {
	// Kind of span (§3.2).
	Kind Kind
	// SpanID is minted by the gateway (crypto/rand) when the recorder begins
	// (§3.4 spans.span_id; also proxy_logs.trace_span_id, request-identity bead).
	SpanID SpanID
	// TraceID is the provisional trace id: the declared one when the client
	// sent traceparent, otherwise a best-effort local choice used for outbound
	// propagation. The assembler may replace it and then links back with
	// provisional_context (§4.1).
	TraceID TraceID
	// ParentSpanID is the declared parent span (traceparent parent, or
	// X-Tyk-Parent-Span-Id) (§4.2 priority 1-2). Zero when none was declared.
	ParentSpanID SpanID
	// Seq orders several events for one span id (0 for the final event;
	// Phase 2 span-started events use their own value). Part of the
	// idempotency key (D3).
	Seq uint32
	// IdempotencyKey is "<source>:<span hex>:<seq>" (D3), set by the
	// transport with SetIdempotencyKey; the staging table is unique on it.
	IdempotencyKey string
	// Source is SourceEmbedded or the edge id (D3), set by the transport.
	Source string

	// Identity of the caller (§3.4 app_id, credential_id, user_id; D4 scope).
	Identity Identity
	// Resource is the Studio catalogue entry served (§3.4 resource_type/id).
	Resource Resource
	// Provider is the gen_ai.provider.name value, e.g. "openai" (§3.4, §5.3).
	Provider string
	// Operation is gen_ai.operation.name ("chat", "embeddings") or
	// mcp.method.name ("tools/call") (§3.4, §5.3).
	Operation string
	// RequestModel and ResponseModel; ResponseModel is the model that answered
	// after any fallback (§4.5).
	RequestModel  string
	ResponseModel string
	// ToolName is the tool for tool_call spans (§3.4 tool_name, §4.4 R2).
	ToolName string

	// StartTime and EndTime are gateway wall-clock times (§3.4). TTFT is the
	// time to first token on streams (§4.5, §5.7), zero when not streamed.
	StartTime time.Time
	EndTime   time.Time
	TTFT      time.Duration
	// Status, ErrorType and ErrorMessage (§4.5 errors). ErrorMessage is
	// redacted per policy before persistence (content pipeline bead).
	Status       Status
	ErrorType    string
	ErrorMessage string
	// HTTPStatus returned to the client.
	HTTPStatus int
	// GatewayNode is the hub node or edge id that served the request.
	GatewayNode string
	// Attempt is the number of upstream attempts the logical call made
	// (1 when there was no retry or fallback; §4.5).
	Attempt uint32
	// AttemptOf is set on the inner hop of the /ai/ loopback (and on each of
	// its failover rungs): the span id of the outer logical call this request
	// is one attempt of. The assembler folds such events into the outer
	// llm_inference span as attempt gateway events (§4.5).
	AttemptOf SpanID

	// Usage and cost, copied from the existing chat-record computation
	// (buildChatRecordFor) and never recomputed (epic deviation 6, §3.4).
	Usage Usage
	// AnalyticsRef links the existing per-request record (proxy_logs id)
	// instead of duplicating it (§3.4 analytics_ref).
	AnalyticsRef string

	// Declared is the client-declared context (§4.2, §4.3), filled by the
	// declared-context bead.
	Declared DeclaredContext
	// Extracts are the correlation fingerprints and ids (§4.4 R1-R3, §4.5).
	// They are computed in every content mode, including off (§4.1).
	Extracts Extracts
	// GatewayEvents are policy outcomes, attempts and fallbacks on this span
	// (§3.2 gateway_event, §4.5). The assembler renders each as a child.
	GatewayEvents []GatewayEvent

	// Parts are the captured payloads, already through the content pipeline
	// (§3.4 payloads, §5.5). Empty in off mode.
	Parts []PayloadPart
	// Raw is content captured on the request path, before the content
	// pipeline (CaptureRaw). It is never serialised: ProcessContent turns it
	// into Parts in the capture worker, and the converters ignore it.
	Raw []RawPart

	// ContentMode is the effective mode for this span (§5.5).
	ContentMode string
	// Attributes are extra semconv / tyk.* attributes (§3.4 spans.attributes),
	// e.g. tyk.upstream.request_id (§4.6).
	Attributes map[string]string
	// contains filtered or unexported fields
}

Event is one observed span as the gateway saw it. The gateway fills it on the request path; the transports carry it; the assembler resolves it into rows. Nothing here is authoritative about trace or session membership: those are the assembler's (spec §4.1).

func DecodeStaged

func DecodeStaged(blob []byte, idempotencyKey string) (*Event, error)

DecodeStaged reverses EncodeStaged for the row with idempotencyKey.

func FromProto

func FromProto(p *pb.CaptureEventProto) *Event

FromProto converts a received event back. Malformed ids (wrong lengths) become zero ids; the assembler treats those as unset.

func (*Event) ApproxSize

func (e *Event) ApproxSize() int

ApproxSize estimates the event's encoded size in bytes, for the queue's byte cap (§10 memory budget). It counts payload data and variable strings.

func (*Event) GatewayEventsDropped

func (e *Event) GatewayEventsDropped() int

GatewayEventsDropped is how many of a received event's gateway events FromProto dropped as out of bounds (an unknown type or outcome, or over maxGatewayEvents).

func (*Event) SetIdempotencyKey

func (e *Event) SetIdempotencyKey(source string)

SetIdempotencyKey stamps Source and the "<source>:<span hex>:<seq>" idempotency key (D3). Transports call it before enqueueing.

type Extracts

type Extracts struct {
	// ToolCalls the model requested in this response (R1), in order. A
	// streaming overflow keeps ids and names and sets ArgsUnavailable (§4.5).
	ToolCalls []ToolCallRequest
	// ToolResults are the trailing tool results in this request, after the
	// last assistant message (R1); earlier ones are history.
	ToolResults []ToolResult
	// ResponseID and PreviousResponseID for the Responses API chain (R3).
	ResponseID         string
	PreviousResponseID string
	// FinishReasons as the provider reported them (§3.1 turn boundary).
	FinishReasons []string
	// OfferedTools are the tool names the request offered the model (its
	// tool definitions): the span's "tools available" (jyx.51).
	OfferedTools []string

	// For tool_call / datasource_call spans (R2): the canonical argument and
	// result fingerprints of the executed call, the tool call id when the
	// request carried one (gen_ai.tool.call.id), and MCP isError.
	ArgsFP     Fingerprint
	ResultFP   Fingerprint
	ToolCallID string
	ToolError  bool

	// Stream is true for streamed responses; StreamIncomplete when the stream
	// ended without a terminal event (§4.5 streaming).
	Stream           bool
	StreamIncomplete bool
}

Extracts are the correlation material for one span (§4.4). Ids appear in clear (they are not content); arguments and results only as fingerprints.

func (*Extracts) Bound

func (x *Extracts) Bound()

Bound applies the extract bounds: over-long ids are dropped (a cut id could link falsely), names are cut, and the lists are capped.

type Fingerprint

type Fingerprint []byte

Fingerprint is a key id byte followed by HMAC-SHA-256 of canonical bytes (D4). The key id lets a rotated key coexist with the previous one. A nil Fingerprint means "not available".

func (Fingerprint) KeyID

func (f Fingerprint) KeyID() byte

KeyID returns the key id byte, or 0 for an empty fingerprint.

func (Fingerprint) String

func (f Fingerprint) String() string

String renders the fingerprint as hex, key id first.

type Fingerprinter

type Fingerprinter interface {
	// KeyID is the id byte of the current key.
	KeyID() byte
	// Fingerprint returns KeyID() followed by HMAC-SHA-256(key, canonical).
	Fingerprint(canonical []byte) Fingerprint
}

Fingerprinter computes fingerprints with the install-wide HMAC key (D4). The Enterprise key provider implements it; the edge receives only the derived HMAC key through config sync.

Callers canonicalise first: JSON is RFC 8785 (JCS) bytes, text is trimmed, whitespace-collapsed NFC (§4.4). Implementations must be safe for concurrent use and use stdlib crypto only (FIPS rule).

func CurrentFingerprinter

func CurrentFingerprinter() Fingerprinter

CurrentFingerprinter returns the installed Fingerprinter, or nil. Gateway code computes no fingerprints without one.

type GatewayEvent

type GatewayEvent struct {
	Type    string
	Outcome string
	Name    string // the filter, guardrail, budget or model involved
	Detail  string
	At      time.Time
}

GatewayEvent is one policy outcome, attempt or fallback (§3.2, §4.5). Detail is a short, already-redacted string (e.g. "attempt=2 status=503" or a guardrail name), never content.

type Identity

type Identity struct {
	AppID        uint
	TeamID       uint
	CredentialID string // key or client id, never a secret
	UserID       uint   // Studio user owning the credential
	EndUserID    string // declared end user (X-Tyk-User-Id, baggage user.id), §4.3
	OnBehalfOf   string // authidentity: who the call was for (auth plugin)
	ActingAgent  string // authidentity: the agent that made it (auth plugin)
}

Identity is who made the call (§3.4; D4: scoped by App, team denormalised).

type Kind

type Kind string

Kind is the kind of an observed span (spec §3.2). The assembler adds the synthetic kinds (agent, inferred_client_tool); the gateway never sends them.

const (
	KindLLMInference   Kind = "llm_inference"   // one logical LLM call, covering all attempts
	KindToolCall       Kind = "tool_call"       // MCP tools/call, resources/read, prompts/get
	KindDatasourceCall Kind = "datasource_call" // REST datasource, OpenAPI-to-MCP upstream
	KindPluginEndpoint Kind = "plugin_endpoint" // /plugins/{slug}/ custom endpoint (opaque body)
	KindGatewayEvent   Kind = "gateway_event"   // a policy outcome with no parent span of its own
)

type PayloadPart

type PayloadPart struct {
	Part           string
	ContentState   string
	MediaType      string
	Bytes          int64
	Truncated      bool
	RedactionCount int32
	Fingerprint    Fingerprint
	Data           []byte
}

PayloadPart is one captured payload (§3.4 payloads, §5.5). Data holds the content after the content pipeline (stripped, redacted, truncated); the hub encrypts it at rest. Bytes is the original size before truncation.

type Queue

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

Queue is the bounded capture queue between the request path and a transport (the hub's staging writer, the edge's pulse). Add never blocks: when the caps are reached the incoming event is degraded in the §10 order (payload bytes, then gateway event details) until it fits, or dropped. Events count against the caps from Add until Release, so a transport that is stalled or retrying holds memory within the caps.

func NewQueue

func NewQueue(maxEvents int, maxBytes int64, batchSize int, onDrop func(reason string, n int64)) *Queue

NewQueue builds a queue. onDrop (optional) is called for every drop, for metrics; it must not call back into the queue.

func (*Queue) Add

func (q *Queue) Add(events ...*Event) (batchReady bool)

Add admits events, degrading or dropping them to fit the caps. The queue owns the events afterwards. It reports whether a full batch is pending.

func (*Queue) Depth

func (q *Queue) Depth() int64

Depth is the number of events held (pending or taken, not yet released).

func (*Queue) Drop

func (q *Queue) Drop(reason string, n int64)

Drop counts n drops for reason (for losses the transport sees itself).

func (*Queue) Dropped

func (q *Queue) Dropped(reason string) uint64

Dropped returns the total drops counted for reason.

func (*Queue) Pending

func (q *Queue) Pending() int

Pending is the number of events not yet taken.

func (*Queue) Release

func (q *Queue) Release(b Batch)

Release frees a taken batch's room once it was delivered (or given up on).

func (*Queue) Restore

func (q *Queue) Restore(b Batch)

Restore puts a taken batch back in front of the pending events, for a transport that will retry it. It stays counted against the caps.

func (*Queue) ReturnUnreported

func (q *Queue) ReturnUnreported(m map[string]uint64)

ReturnUnreported adds undelivered drop counts back.

func (*Queue) Take

func (q *Queue) Take() Batch

Take removes up to the batch size of pending events, oldest first. They stay counted against the caps until Release or Restore.

func (*Queue) TakeUnreported

func (q *Queue) TakeUnreported() map[string]uint64

TakeUnreported returns the drops counted since the last call and resets them, for a transport that reports drops upstream. Give them back with ReturnUnreported if the report was not delivered.

type RawPart

type RawPart struct {
	Part      string // PartRequest, PartResponse, ...
	MediaType string
	Data      []byte
	// Bytes is the size on the wire; larger than len(Data) when the capture
	// kept only MaxRawPartBytes of it.
	Bytes int64
}

RawPart is content captured at the gateway before the content pipeline (§5.5): a request or response body, tool arguments or a tool result, as the wire carried it. It never leaves the process: the converters (ToProto, EncodeStaged) carry only processed Parts, and ProcessContent turns raw parts into processed ones in the capture worker, off the request path.

type Recorder

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

Recorder collects the capture for one gateway request: its primary span and any extra events. It is safe for concurrent use (the streaming parser runs in its own goroutine). Every method is a no-op on a nil Recorder, and every write after Finish or Discard is ignored.

func Begin

func Begin(ctx context.Context) (context.Context, *Recorder)

Begin attaches a Recorder to ctx and returns both. With the flag off it returns ctx unchanged and a nil Recorder, allocating nothing. If ctx already carries a Recorder (nested handlers), that one is returned.

The primary span gets a fresh span id and StartTime now.

func Fork

func Fork(ctx context.Context) (context.Context, *Recorder)

Fork begins a capture of its own for work that outlives the request that carried it: an MCP tools/call on the legacy SSE transport is answered on the event stream after its POST already returned 202. The new Recorder continues the request's context (trace id, declared trace context and parent, caller identity, gateway node) under a fresh span id with StartTime now; the caller finishes it. With no Recorder on ctx (or the flag off) it returns ctx unchanged and nil.

func From

func From(ctx context.Context) *Recorder

From returns the request's Recorder, or nil when the flag is off or none was begun. It allocates nothing.

func (*Recorder) AddGatewayEvent

func (r *Recorder) AddGatewayEvent(ge GatewayEvent)

AddGatewayEvent adds a gateway event to the primary span. A zero At is stamped with the current time.

func (*Recorder) AddPart

func (r *Recorder) AddPart(p PayloadPart)

AddPart adds a payload part to the primary span.

func (*Recorder) CaptureRaw

func (r *Recorder) CaptureRaw(part, mediaType string, data []byte)

CaptureRaw adds a raw part to the primary span. Set the span's App and resource (Update) first: the content mode is resolved from them here, and a span without them resolves to off and keeps no content.

func (*Recorder) Discard

func (r *Recorder) Discard()

Discard ends the capture without emitting anything (for example when the App has tracing off). Later Finish calls do nothing, and From returns nil for the request from then on, so no hook does any further work.

func (*Recorder) Emit

func (r *Recorder) Emit(ev *Event)

Emit adds an extra event. A zero span id gets a fresh one and a zero StartTime is stamped now.

func (*Recorder) Finish

func (r *Recorder) Finish()

Finish completes the capture and hands the events to the Sink installed when the capture began (none: the events are dropped): the primary span when it has a Kind, then the extra events. A zero EndTime is stamped now and an empty Status becomes ok. Only the first call has an effect.

func (*Recorder) Hold

func (r *Recorder) Hold() (release func())

Hold keeps the capture open for work that completes after the request handler returns (the analytics goroutine): a Finish while held waits until every release has been called. The release is idempotent; on a nil Recorder Hold returns a no-op and allocates nothing.

func (*Recorder) LogicalSpanID

func (r *Recorder) LogicalSpanID() SpanID

LogicalSpanID is the span id of the logical call this request belongs to: the outer call's for an attempt, otherwise its own. proxy_logs rows carry it (trace_span_id), so every failover rung of one call shares it.

func (*Recorder) MarkAttemptOf

func (r *Recorder) MarkAttemptOf(outer SpanID)

MarkAttemptOf records that this request is one attempt of the outer logical call whose span id is outer (the inner hop of the /ai/ loopback).

func (*Recorder) SetTraceID

func (r *Recorder) SetTraceID(t TraceID)

SetTraceID sets the provisional trace id (the declared one, or one the gateway minted) when none is set yet.

func (*Recorder) SpanID

func (r *Recorder) SpanID() SpanID

SpanID returns the primary span id, or the zero id on a nil Recorder.

func (*Recorder) TraceID

func (r *Recorder) TraceID() TraceID

TraceID returns the primary span's provisional trace id.

func (*Recorder) Update

func (r *Recorder) Update(fn func(ev *Event))

Update runs fn on the primary span under the Recorder's lock. fn must not retain the pointer or call back into the Recorder. Ignored after Finish.

type Resource

type Resource struct {
	Type string // ResourceLLM, ResourceTool, ResourceDatasource, ResourcePlugin
	ID   string // catalogue id
	Name string
}

Resource is the Studio catalogue entry a span used (§3.4).

type Sealer

type Sealer interface {
	Seal(plain, aad []byte) ([]byte, error)
	Open(sealed, aad []byte) ([]byte, error)
}

Sealer encrypts staged capture events at rest (D4: payloads are encrypted at the hub with AES-256-GCM). The Enterprise key provider implements it; the sealed form carries its own key id so a rotated key still opens old rows. Implementations use stdlib crypto only (FIPS rule).

func CurrentSealer

func CurrentSealer() Sealer

CurrentSealer returns the installed Sealer, or nil.

type Sink

type Sink interface {
	Enqueue(ev *Event) bool
}

Sink receives finished events. The embedded transport (CaptureRecorder on the analytics handler) and the edge transport (pulse sub-buffer) implement it. Enqueue must never block the request (§10): it returns false when the event was dropped.

type SpanID

type SpanID [8]byte

SpanID is a W3C span id (8 bytes). The zero value means unset.

func NewSpanID

func NewSpanID() SpanID

NewSpanID returns a random non-zero span id from crypto/rand.

func ParseSpanID

func ParseSpanID(s string) (SpanID, bool)

ParseSpanID parses 16 hex characters. It returns false for anything else, including the all-zero id.

func (SpanID) Bytes

func (s SpanID) Bytes() []byte

Bytes returns the id as a slice, or nil when unset (the column is NULL).

func (SpanID) IsZero

func (s SpanID) IsZero() bool

IsZero reports whether the id is unset.

func (SpanID) String

func (s SpanID) String() string

String renders the id as lowercase hex (W3C format), or "" when unset.

type StaticFingerprinter

type StaticFingerprinter struct {
	ID  byte
	Key []byte
}

StaticFingerprinter is a deterministic Fingerprinter over a fixed key. It is for tests and fixtures (goldens need stable fingerprints); production keys come from the key provider.

func (StaticFingerprinter) Fingerprint

func (s StaticFingerprinter) Fingerprint(canonical []byte) Fingerprint

Fingerprint implements Fingerprinter.

func (StaticFingerprinter) KeyID

func (s StaticFingerprinter) KeyID() byte

KeyID implements Fingerprinter.

type Status

type Status string

Status is a span outcome (spec §3.4 spans.status).

const (
	StatusOK    Status = "ok"
	StatusError Status = "error"
)

type ToolCallRequest

type ToolCallRequest struct {
	ID              string
	Name            string
	ArgsFP          Fingerprint
	ArgsUnavailable bool
}

ToolCallRequest is one tool call in an LLM response (R1).

type ToolResult

type ToolResult struct {
	ID         string
	Name       string
	CallArgsFP Fingerprint
	ResultFP   Fingerprint
	IsError    bool
}

ToolResult is one trailing tool result in an LLM request (R1). A result sent back without its call's id (Gemini makes it optional, Ollama has none, some clients drop it) carries instead the call's Name and CallArgsFP, the fingerprint of the call's arguments as the request's history repeats them, for the name and arguments fallback.

type TraceID

type TraceID [16]byte

TraceID is a W3C trace id (16 bytes). The zero value means unset.

func NewTraceID

func NewTraceID() TraceID

NewTraceID returns a random non-zero trace id from crypto/rand.

func ParseTraceID

func ParseTraceID(s string) (TraceID, bool)

ParseTraceID parses 32 hex characters. It returns false for anything else, including the all-zero id, which W3C defines as invalid.

func (TraceID) Bytes

func (t TraceID) Bytes() []byte

Bytes returns the id as a slice, or nil when unset (the column is NULL).

func (TraceID) IsZero

func (t TraceID) IsZero() bool

IsZero reports whether the id is unset.

func (TraceID) String

func (t TraceID) String() string

String renders the id as lowercase hex (W3C format), or "" when unset.

type Usage

type Usage struct {
	InputTokens      int64
	OutputTokens     int64
	CacheReadTokens  int64
	CacheWriteTokens int64
	ReasoningTokens  int64
	CostMicros       int64
	Currency         string
}

Usage is token usage and cost (§3.4). CostMicros is cost * 1e6.

Directories

Path Synopsis
Package declared extracts the context a client declares about a gateway request (spec enterprise/features/agenttracing/SPEC.md §4.2 and §4.3): W3C trace context and baggage, the X-Tyk-* tracing headers, the compatibility header families of other gateways, a few body fields, and the session ids of verified coding harnesses.
Package declared extracts the context a client declares about a gateway request (spec enterprise/features/agenttracing/SPEC.md §4.2 and §4.3): W3C trace context and baggage, the X-Tyk-* tracing headers, the compatibility header families of other gateways, a few body fields, and the session ids of verified coding harnesses.
Package extract turns LLM request and response bodies into the correlation extracts of Agent Call Tracing (spec §4.4): the tool calls a response requests, the trailing tool results a request sends back, response ids and finish reasons.
Package extract turns LLM request and response bodies into the correlation extracts of Agent Call Tracing (spec §4.4): the tool calls a response requests, the trailing tool results a request sends back, response ids and finish reasons.
Package traceschema holds the JSON Schema of the agent-trace export format (application/vnd.tyk.agent-trace+json; v=1, spec §7).
Package traceschema holds the JSON Schema of the agent-trace export format (application/vnd.tyk.agent-trace+json; v=1, spec §7).

Jump to

Keyboard shortcuts

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