Documentation
¶
Overview ¶
Package flyedge is a Go agent-protection SDK, wire-compatible with the prism/policy-enforcer gateway. It is deliberately explicit ("gothonic"): construct a *Guard, pass it, and route calls through Guard.Check — no import-time monkeypatching, no ambient singletons, and a policy denial is a typed value (*DenyError), not an exception or a synthesized message.
SPDX-License-Identifier: Apache-2.0 Copyright 2026 CompFly AI
SPDX-License-Identifier: Apache-2.0 Copyright 2026 CompFly AI
Index ¶
- Constants
- Variables
- func ContextWithAgentIdentity(ctx context.Context, sid, urn string) context.Context
- func ContextWithDelegation(ctx context.Context, token string) context.Context
- func ContextWithEndpointAgent(ctx context.Context, agent EndpointAgent) context.Context
- func ContextWithPrincipal(ctx context.Context, p Principal) context.Context
- func ContextWithSession(ctx context.Context, id string) context.Context
- func ContextWithTrace(ctx context.Context, traceID, spanID string) context.Context
- func InboundHandler(next http.Handler) http.Handler
- func WithVerdictRelay(ctx context.Context, relay string) context.Context
- type Action
- type Attachment
- type AuthContext
- type CheckRequest
- type Config
- type Content
- type Decision
- type DenyError
- type EndpointAgent
- type ExecutionContext
- type FailMode
- type Guard
- func (g *Guard) AcknowledgeSessionTaint(ctx context.Context, sessionID string) error
- func (g *Guard) BeforeScenarioTool(ctx context.Context, session, tool string, args any, allowMock bool) (value json.RawMessage, mocked bool, err error)
- func (g *Guard) Check(ctx context.Context, req CheckRequest) (decision Decision, err error)
- func (g *Guard) CheckModelResponse(ctx context.Context, session, model, text string) (Decision, error)
- func (g *Guard) CheckToolCall(ctx context.Context, session, toolName string, args any) (Decision, error)
- func (g *Guard) CheckToolResponse(ctx context.Context, session, toolName string, result any) (Decision, error)
- func (g *Guard) Close() error
- func (g *Guard) Connect(ctx context.Context, info ManifestInfo) error
- func (g *Guard) DID() string
- func (g *Guard) GovernToolResult(ctx context.Context, session, toolName, result string) (string, Decision, error)
- func (g *Guard) LocalControlDetectors() []string
- func (g *Guard) ModelMode() ModelMode
- func (g *Guard) NontextPayloadAllowed() bool
- func (g *Guard) RecordInvocationUsage(ctx context.Context, callID, model string, usage *ModelUsage)
- func (g *Guard) RecordLLMCall(sessionID, requestID, model, provider string, inputTokens, outputTokens int64, ...)
- func (g *Guard) RecordLLMCallDetail(c LLMCall)
- func (g *Guard) RecordLLMCallStreamed(sessionID, requestID, model, provider string, inputTokens, outputTokens int64, ...)
- func (g *Guard) RecordSessionStart(sessionID string, data map[string]any)
- func (g *Guard) RecordSessionSummary(sessionID string, data map[string]any)
- func (g *Guard) RecordToolIO(sessionID, requestID, toolName, argsJSON, resultJSON string)
- func (g *Guard) RecordToolIODetail(c ToolIO)
- func (g *Guard) RecordTurnOutcome(c TurnOutcome)
- func (g *Guard) RecordUsageObservation(c UsageObservation)
- func (g *Guard) Report() Summary
- func (g *Guard) ScenarioMockStatus() map[string]any
- func (g *Guard) ServeInvocations(ctx context.Context, opts InvocationOptions, handler InvocationHandler) (*InvocationConnection, error)
- func (g *Guard) SessionTaint(ctx context.Context, sessionID string) (*Taint, error)
- func (g *Guard) SetLocalControls(cfg localcontrol.Config) error
- func (g *Guard) SimulationActive() bool
- func (g *Guard) SimulationConfig() *SimulationConfig
- func (g *Guard) StopLocalControlSync()
- func (g *Guard) SyncLocalControls(opts ...LocalControlSyncOption) error
- func (g *Guard) WrapRoundTripper(base http.RoundTripper, opts ...WrapOption) http.RoundTripper
- type InvocationConnection
- type InvocationContract
- type InvocationHTTPError
- type InvocationHandler
- type InvocationMessage
- type InvocationOptions
- type InvocationPurpose
- type InvocationRequest
- type InvocationToolCall
- type InvocationWriter
- type KillInfo
- type KillSwitchError
- type LLMCall
- type LocalControlSyncOption
- type ManifestInfo
- type Mode
- type ModelMode
- type ModelUsage
- type Operation
- type Option
- func WithAttachments() Option
- func WithCloudTelemetry(interval time.Duration) Option
- func WithDecisionHandler(fn func(CheckRequest, Decision)) Option
- func WithEnforcer(e enforce.Enforcer) Option
- func WithFailMode(f FailMode) Option
- func WithHeartbeat(interval time.Duration) Option
- func WithLocalControlEngine(e *localcontrol.Engine) Option
- func WithLocalControls(cfg localcontrol.Config) Option
- func WithManifestRefreshHandler(fn func()) Option
- func WithMode(m Mode) Option
- func WithModeChangeHandler(fn func(old, cur ModelMode)) Option
- func WithSigner(s identity.Signer) Option
- func WithSimulation(enabled bool) Option
- func WithSimulationTelemetryURL(url string) Option
- func WithTelemetry(t telemetry.Telemetry) Option
- func WithoutCloudTelemetry() Option
- type Principal
- type SimulationConfig
- type SkillInfo
- type Stage
- type StateContract
- type StateField
- type StateFieldType
- type Summary
- type Taint
- type TaintEntry
- type ToolIO
- type TurnOutcome
- type UsageObservation
- type WrapOption
Constants ¶
const ( StagePreLLM = enforce.StagePreLLM StageToolCall = enforce.StageToolCall StageToolCallResponse = enforce.StageToolCallResponse StagePostLLM = enforce.StagePostLLM ActionAllow = enforce.ActionAllow ActionDeny = enforce.ActionDeny ActionWarn = enforce.ActionWarn // OriginType* are the valid CheckRequest.OriginType values (prism enum, snake_case). OriginTypeUser = enforce.OriginTypeUser OriginTypeAgent = enforce.OriginTypeAgent OriginTypeAutonomous = enforce.OriginTypeAutonomous )
const DefaultAPIURL = "https://prism.p.compfly.ai"
DefaultAPIURL is the prism gateway base URL used when Config.APIURL is empty.
const DefaultLocalControlInterval = 5 * time.Minute
DefaultLocalControlInterval is the poll cadence. Config distribution changes far less often than it is polled, and the conditional GET makes an unchanged tick nearly free, so this is chosen for "a rule change reaches the fleet promptly" rather than to limit bandwidth.
const LocalControlPollPath = "/v1/flyedge/local-controls"
LocalControlPollPath is prism's distribution endpoint for the org's local-control rule set.
const LocalControlReportPath = "/v1/flyedge/local-controls/report"
LocalControlReportPath is where an agent reports the rule set it actually applied, so an operator can see convergence rather than assuming it.
const MetadataTokens = "tokens"
MetadataTokens is the CheckRequest.Metadata key the token-budget detector reads.
It lives in metadata rather than as a CheckRequest field because the request JSON is the frozen wire schema shared with prism and the other SDKs; adding a field to feed a purely local detector would be a wire change for no server-side reader.
Variables ¶
var ErrConnectionExpired = errors.New("flyedge: invocation lease expired")
var ErrConnectionRevoked = errors.New("flyedge: invocation connection revoked")
var ErrInvocationOutcomeUnknown = errors.New("flyedge: invocation connection lost; in-flight outcomes may be unknown")
Functions ¶
func ContextWithAgentIdentity ¶
ContextWithAgentIdentity returns a context carrying the acting agent's non-human-identity attribution: sid (subject id) and/or urn (structured identity). Both empty is ignored. These ride alongside the crypto DID (set by the signer) as additional attribution.
func ContextWithDelegation ¶
ContextWithDelegation returns a context carrying a raw delegation-token JWT (agent-to-agent authority). prism verifies it and unpacks the intent/task mandate chain encoded inside the token. Empty token is ignored.
func ContextWithEndpointAgent ¶
func ContextWithEndpointAgent(ctx context.Context, agent EndpointAgent) context.Context
ContextWithEndpointAgent attaches the exact local endpoint-agent instance observed for a check. The instance key becomes part of the signed request body when Guard.Check runs.
func ContextWithPrincipal ¶
ContextWithPrincipal returns a context carrying the end-user an agent is acting on behalf of. Every governed call (Check*, the WrapRoundTripper LLM path, Connect, telemetry) made with this context attaches the OBO header, so a single served agent identity can be governed per-user at the gateway. The zero Principal is ignored.
A production deployment also passes the underlying credential (the raw OBO token) in the request body it forwards to the provider; this envelope is prism's extraction/attribution hint.
func ContextWithSession ¶
ContextWithSession returns a context carrying an explicit flyedge session id. The transport wrap (and any Check that reads it) uses this id for multi-turn correlation, so a proxy or a per-conversation agent can scope sessions per request instead of per client. Empty id is ignored.
func ContextWithTrace ¶
ContextWithTrace attaches the caller's W3C trace so a Check and its telemetry nest under the caller's span. traceID must be 32 hex chars, spanID 16 hex.
spanID is the span the check nests UNDER — the operation being governed, not the check. It is sent as the traceparent's span field, which is what prism records as the check's parent_span_id (prism mints the check's own span). Pass "" when the caller has no enclosing span and the check is a root of the trace.
func InboundHandler ¶ added in v0.11.0
InboundHandler scopes each request with its eval/playground simulation correlation, so checks made with the request context use the simulation session in place of the one passed. Wrap the server's handler once. Headers provide correlation only, never identity or authority; ordinary traffic masks an enclosing scope.
Types ¶
type Action ¶
Re-export the wire types so callers depend only on the flyedge package for the common surface.
type Attachment ¶ added in v0.8.0
type Attachment = enforce.Attachment
Re-export the wire types so callers depend only on the flyedge package for the common surface.
func ExtractAttachments ¶ added in v0.8.0
func ExtractAttachments(value any) []Attachment
ExtractAttachments normalizes recognized inline provider content, without URL fetches or file reads. Callers must check per-agent permission first. Traversal and encoded transport size are bounded.
type AuthContext ¶
type AuthContext = enforce.AuthContext
Re-export the wire types so callers depend only on the flyedge package for the common surface.
type CheckRequest ¶
type CheckRequest = enforce.CheckRequest
Re-export the wire types so callers depend only on the flyedge package for the common surface.
type Config ¶
type Config struct {
// CloudTelemetry controls cloud event delivery (FLYEDGE_CLOUD_TELEMETRY).
// Nil defaults to true; false keeps telemetry local. Explicit Options override it.
CloudTelemetry *bool
// TelemetryInterval is the cloud flush cadence. Values below one second use five seconds.
TelemetryInterval time.Duration
// APIURL is the prism gateway base (COMPFLY_API_URL). Empty → DefaultAPIURL.
APIURL string
// DID is the agent's decentralized identifier (COMPFLY_AGENT_DID), e.g.
// did:compfly:<org_short>:<fingerprint>. Required to sign requests.
DID string
// KeyPEMPath is the path to the Ed25519 private key PEM (COMPFLY_AGENT_PRIVATE_KEY_PATH).
// KeyPEM is the inline PEM (COMPFLY_AGENT_PRIVATE_KEY); it takes precedence when set.
KeyPEMPath string
KeyPEM []byte
// Mode + FailMode; empty values default to ModeWarn / FailOpen in New.
Mode Mode
FailMode FailMode
// ModelMode optionally selects check, passthrough, or gateway (FLYEDGE_MODEL_MODE).
// Empty inherits server policy. Explicit per-agent server policy takes precedence.
ModelMode ModelMode
// ProxyMode is the legacy explicit proxy opt-in. Prefer ModelMode for new code.
ProxyMode bool
// Timeout bounds each enforcement HTTP call. Zero → 30s.
Timeout time.Duration
// SimTelemetryURL overrides the simulation telemetry WebSocket URL the server advertises in the
// config's `simulation` block (COMPFLY_SIM_TELEMETRY_URL). Server-authoritative by default (empty);
// set it only as an advanced override when the gateway hands back a telemetry URL the client
// cannot resolve, and you need to point it at a reachable address.
SimTelemetryURL string
// contains filtered or unexported fields
}
Config is the full configuration for a Guard. Zero values are sane: an empty Config yields a warn-mode, fail-open, check-only guard against the default API URL. Populate via LoadEnv or set fields directly — there are no scattered env reads elsewhere in the package.
type Content ¶
Re-export the wire types so callers depend only on the flyedge package for the common surface.
type Decision ¶
Re-export the wire types so callers depend only on the flyedge package for the common surface.
type DenyError ¶
type DenyError struct {
Decision Decision
}
DenyError is returned by Check when the policy decision is a denial. Callers handle it as a value — errors.As(err, &de) — instead of catching an exception or inspecting a fake message.
func AsDenyError ¶
AsDenyError is a convenience for callers: returns the *DenyError if err is one.
type EndpointAgent ¶
type EndpointAgent = enforce.EndpointAgent
Re-export the wire types so callers depend only on the flyedge package for the common surface.
type ExecutionContext ¶
type ExecutionContext = enforce.ExecutionContext
Enrichment context types (opt-in fields on CheckRequest).
type FailMode ¶
type FailMode string
FailMode decides what happens when the enforcement call itself fails (network/5xx). It is distinct from Mode: FailOpen allows the request through, FailClosed denies it.
type Guard ¶
type Guard struct {
// contains filtered or unexported fields
}
Guard is the protection handle. Construct once with New, pass it explicitly, Close when done.
func New ¶
New builds a Guard from cfg (+ options). If a key is configured it builds a Signer; otherwise the guard runs check-only/unsigned (useful for tests/offline). Returns an error on invalid config — it never silently degrades. Importing this package has no side effects; nothing starts until New.
func (*Guard) AcknowledgeSessionTaint ¶
AcknowledgeSessionTaint acknowledges all taints on a session (POST /v1/sessions/{id}/taint/acknowledge), clearing the taint gate.
func (*Guard) BeforeScenarioTool ¶ added in v0.9.0
func (g *Guard) BeforeScenarioTool(ctx context.Context, session, tool string, args any, allowMock bool) (value json.RawMessage, mocked bool, err error)
BeforeScenarioTool implements a scenario-owned fixture without executing the real tool. Call AFTER CheckToolCall, execute only when mocked is false, and govern either result with GovernToolResult. RecordToolIO is for real executions only. allowMock is deployment authorization, never a user-supplied flag.
func (*Guard) Check ¶
Check applies platform decisions unchanged. Mode is retained only for legacy SDK-local detectors and never skips, weakens, or escalates a platform result.
func (*Guard) CheckModelResponse ¶
func (g *Guard) CheckModelResponse(ctx context.Context, session, model, text string) (Decision, error)
CheckModelResponse gates a model completion (the post_llm stage): run it on the model's output before returning it to the user, so policy can inspect generated content.
func (*Guard) CheckToolCall ¶
func (g *Guard) CheckToolCall(ctx context.Context, session, toolName string, args any) (Decision, error)
CheckToolCall gates a tool invocation (the tool_call stage). Tool arguments are serialized both as inspected content and as structured policy input.
func (*Guard) CheckToolResponse ¶
func (g *Guard) CheckToolResponse(ctx context.Context, session, toolName string, result any) (Decision, error)
CheckToolResponse gates a tool's output (the tool_call_response stage): run it on the result before feeding it back to the model, so policy can inspect returned content.
func (*Guard) Close ¶
Close flushes and releases resources: it stops the config poller (if Connect started one) and the telemetry sink's owned goroutine. Safe to call once.
func (*Guard) Connect ¶
func (g *Guard) Connect(ctx context.Context, info ManifestInfo) error
Connect registers the agent's manifest with the gateway (POST /v1/flyedge/connect), enabling presence tracking and manifest-seeded baselines. Explicit — call it once at startup. Requires a signed enforcer (a real Guard); a stub/offline enforcer returns an error.
On success it also starts the config heartbeat poller (an owned goroutine, stopped by Close): the ConnectResponse carries the heartbeat cadence + initial model_mode, and the poller then keeps model_mode current, honors manifest-refresh requests, and surfaces the simulation block.
func (*Guard) GovernToolResult ¶
func (g *Guard) GovernToolResult(ctx context.Context, session, toolName, result string) (string, Decision, error)
GovernToolResult gates a tool result AND returns the content the caller should feed back to the model. It is the value-returning companion to CheckToolResponse: use it wherever the tool result flows onward, because the governed content may differ from the raw result —
- During an active simulation in attack mode, the attack injector may MUTATE the result (tool_poison merges adversarial fields; error_inject replaces it with a crafted error). The injection is emitted as telemetry for the platform's outcome correlation.
- The result is always run through the tool_call_response check (enforcement + telemetry). A policy denial returns a *DenyError — the caller should withhold the result from the model.
This is the seam the injector needs for injection and that a production agent needs for response redaction: one place where the response content can be transformed, not merely allowed/denied.
func (*Guard) LocalControlDetectors ¶
LocalControlDetectors reports the currently active local detectors, for diagnostics and for the sync channel's status report. Nil when local controls are not configured.
func (*Guard) ModelMode ¶
ModelMode returns the effective routing mode: per-agent policy, explicit SDK preference, organization policy, then check. Older servers without a known policy source remain authoritative.
func (*Guard) NontextPayloadAllowed ¶ added in v0.8.0
NontextPayloadAllowed reads the existing heartbeat's expiring, per-agent permission. Missing/invalid settings and stale permission never enable attachment inspection.
func (*Guard) RecordInvocationUsage ¶ added in v0.11.0
func (g *Guard) RecordInvocationUsage(ctx context.Context, callID, model string, usage *ModelUsage)
RecordInvocationUsage records one model attempt within this Guard's admitted invocation context. It does not emit another telemetry event. Reusing callID deduplicates observations; separate attempts need separate IDs. Nil usage records an unknown attempt, so a later measured call cannot hide it. Other guards, unbound contexts and observations after completion are ignored. Invalid/bounded observations suppress the envelope rather than exposing an incomplete total.
func (*Guard) RecordLLMCall ¶
func (g *Guard) RecordLLMCall(sessionID, requestID, model, provider string, inputTokens, outputTokens int64, latencyMS float64)
RecordLLMCall emits an llm_io event — a model call's model/provider/token/latency facts — so cost/usage observability lands on the platform (prism records GenAI metrics for llm_io). Pass a streaming bool via RecordLLMCallStreamed when relevant.
func (*Guard) RecordLLMCallDetail ¶
RecordLLMCallDetail emits an llm_io event from a full LLMCall, including cache tiers. Prefer it over RecordLLMCall for any provider that reports prompt caching: without the cache counts the platform's view of input volume is wrong by orders of magnitude, not by a rounding error.
func (*Guard) RecordLLMCallStreamed ¶
func (g *Guard) RecordLLMCallStreamed(sessionID, requestID, model, provider string, inputTokens, outputTokens int64, latencyMS float64, streamed bool)
RecordLLMCallStreamed is RecordLLMCall with an explicit streamed flag (stream_lifecycle).
func (*Guard) RecordSessionStart ¶
RecordSessionStart / RecordSessionSummary emit agent-session lifecycle telemetry. data is an optional payload (e.g. rolled-up stats on summary).
func (*Guard) RecordSessionSummary ¶
func (*Guard) RecordToolIO ¶
RecordToolIO emits a tool_io event (tool name + args/result). argsJSON/resultJSON are carried as the audit request/response payloads.
func (*Guard) RecordToolIODetail ¶
RecordToolIODetail emits an attributed tool_io event from a full ToolIO.
func (*Guard) RecordTurnOutcome ¶ added in v0.7.0
func (g *Guard) RecordTurnOutcome(c TurnOutcome)
RecordTurnOutcome emits a turn_outcome event. Outcomes without a session or data are discarded.
func (*Guard) RecordUsageObservation ¶ added in v0.6.0
func (g *Guard) RecordUsageObservation(c UsageObservation)
RecordUsageObservation emits a skill_usage or hook_usage trace event. Unsupported kinds and observations without a name/session are discarded.
func (*Guard) Report ¶
Report returns the aggregate protection summary (checks, allowed/denied/warned/errors, timings). The caller decides whether/how to surface it — nothing is printed implicitly.
func (*Guard) ScenarioMockStatus ¶ added in v0.9.0
ScenarioMockStatus returns installation and match evidence, not a run verdict.
func (*Guard) ServeInvocations ¶ added in v0.8.0
func (g *Guard) ServeInvocations(ctx context.Context, opts InvocationOptions, handler InvocationHandler) (*InvocationConnection, error)
ServeInvocations explicitly registers ONE handler and opens an outbound socket. Ordinary New/Connect never call it. Leases renew by default until canceled or revoked. Handlers run up to MaxConcurrentInvocations at a time. Supported brokers recover transport failures automatically within the existing lease. AllowOperatorReconnect additionally permits an operator to request a new lease after a terminal failure.
func (*Guard) SessionTaint ¶
SessionTaint reads the current taint state for a session. Returns (nil, nil) when the session has no taint (prism 404s an untainted session). A returned Taint with a non-zero SessionSeverity means earlier steps tripped injection/PII/etc. signals — callers can gate on it (e.g. refuse autonomous actions above a threshold).
func (*Guard) SetLocalControls ¶
func (g *Guard) SetLocalControls(cfg localcontrol.Config) error
SetLocalControls swaps the active local-control configuration at runtime. This is what the sync channel calls when the platform publishes a new rule set.
On a bad configuration the previous engine is KEPT and the error returned: a rule set that fails to compile must not disarm the protection that was already running. Callers should log and retry on the next sync rather than treating it as fatal.
func (*Guard) SimulationActive ¶
SimulationActive reports whether the last config poll saw an active simulation run.
func (*Guard) SimulationConfig ¶
func (g *Guard) SimulationConfig() *SimulationConfig
SimulationConfig returns a copy of the last-seen simulation block, or nil if none is active.
func (*Guard) StopLocalControlSync ¶
func (g *Guard) StopLocalControlSync()
StopLocalControlSync stops the channel. Safe to call when it was never started.
func (*Guard) SyncLocalControls ¶
func (g *Guard) SyncLocalControls(opts ...LocalControlSyncOption) error
SyncLocalControls starts the local-controls sync channel on this Guard.
The Guard's enforcer must be a signed HTTP enforcer (the default from New with a configured key) — the poll and report are both sensor/agent-signed. Returns an error if the transport cannot sign, rather than silently running an unauthenticated, and therefore unserved, loop.
Stop it with StopLocalControlSync, or leave it to Close.
func (*Guard) WrapRoundTripper ¶
func (g *Guard) WrapRoundTripper(base http.RoundTripper, opts ...WrapOption) http.RoundTripper
WrapRoundTripper returns an http.RoundTripper that runs a flyedge pre_llm policy check before each outbound LLM-provider request, then forwards on Allow. It is provider-agnostic: any HTTP LLM client (the Anthropic SDK, the OpenAI SDK, raw net/http) is governed by installing this one transport — no per-framework adapter required:
hc := &http.Client{Transport: guard.WrapRoundTripper(http.DefaultTransport)}
client := anthropic.NewClient(option.WithHTTPClient(hc)) // or openai.NewClient(option.WithHTTPClient(hc))
On a policy Deny the RoundTrip returns a *DenyError (wrapped by net/http in *url.Error, still reachable via errors.As), and the provider is never called. Requests to hosts without a registered extractor pass through unchecked.
type InvocationConnection ¶ added in v0.8.0
type InvocationConnection struct {
ContractVersion string
ID string
// contains filtered or unexported fields
}
InvocationConnection represents a serving session. ID and ContractVersion describe its initial lease. Use ActiveLeaseID to identify the currently connected lease.
func (*InvocationConnection) ActiveLeaseID ¶ added in v0.11.0
func (c *InvocationConnection) ActiveLeaseID() string
ActiveLeaseID returns the current lease ID, or an empty string when disconnected.
func (*InvocationConnection) Close ¶ added in v0.8.0
func (c *InvocationConnection) Close() error
Close stops accepting work and signals cancellation. It does not wait for an uncooperative handler or undo its external side effects.
func (*InvocationConnection) ExpiresAt ¶ added in v0.8.0
func (c *InvocationConnection) ExpiresAt() time.Time
ExpiresAt returns the latest acknowledged lease expiry. Automatic renewal advances it.
func (*InvocationConnection) Wait ¶ added in v0.8.0
func (c *InvocationConnection) Wait() error
type InvocationContract ¶ added in v0.8.0
type InvocationContract struct {
State StateContract `json:"state"`
}
InvocationContract declares logical input state, independent of endpoint mappings.
type InvocationHTTPError ¶ added in v0.11.3
InvocationHTTPError preserves a broker rejection without retaining its body or credentials.
func (*InvocationHTTPError) Error ¶ added in v0.11.3
func (e *InvocationHTTPError) Error() string
type InvocationHandler ¶ added in v0.8.0
type InvocationHandler func(context.Context, InvocationRequest, InvocationWriter) error
type InvocationMessage ¶ added in v0.8.0
type InvocationMessage struct {
Role string `json:"role"`
Content string `json:"content"`
ToolCalls []InvocationToolCall `json:"toolCalls,omitempty"`
ToolCallID string `json:"toolCallId,omitempty"`
}
type InvocationOptions ¶ added in v0.8.0
type InvocationOptions struct {
// MaxConcurrentInvocations explicitly opts into parallel handlers; zero defaults to one.
MaxConcurrentInvocations int `json:"max_concurrent_invocations"`
// AllowClientHistory opts in to test history; defaults to false.
AllowClientHistory bool `json:"allow_client_history"`
// Contract is published by the platform before this connection can serve.
Contract *InvocationContract `json:"contract,omitempty"`
// AllowClientState defaults to true when nil. Set a pointer to false to reject client state.
AllowClientState *bool `json:"allow_client_state"`
Name string `json:"name"`
Environment string `json:"environment"`
Purposes []InvocationPurpose `json:"purposes"`
// LeaseDuration defaults to one hour; renewal keeps the same serving connection alive.
LeaseDuration time.Duration `json:"-"`
// AutoRenew defaults to true when nil. Set a pointer to false for a finite session.
AutoRenew *bool `json:"auto_renew,omitempty"`
RequestTimeout time.Duration `json:"-"`
// AllowInsecureLoopback permits HTTP only to a literal loopback address for local tests.
AllowInsecureLoopback bool `json:"-"`
// AllowOperatorReconnect lets a platform operator request a fresh lease after a disconnect.
AllowOperatorReconnect bool `json:"-"`
// AllowSimulationInjection defaults to true when nil for reverse invocation.
// Set a pointer to false to reject injected mocks.
AllowSimulationInjection *bool `json:"allow_simulation_injection"`
}
InvocationOptions grants only the listed purposes for this serving session. The handler runs with the application's real credentials. This is not a sandbox.
type InvocationPurpose ¶ added in v0.8.0
type InvocationPurpose string
const ( PurposePlayground InvocationPurpose = "playground" PurposeSimulation InvocationPurpose = "simulation" PurposeEval InvocationPurpose = "eval" )
type InvocationRequest ¶ added in v0.8.0
type InvocationRequest struct {
// Traceparent scopes checks to this turn; missing or invalid W3C v00 values are ignored.
Traceparent string `json:"traceparent,omitempty"`
ScenarioPlan json.RawMessage `json:"scenario_plan,omitempty"`
// History is a caller-provided test fixture, separate from live Messages.
// The handler owns applying it; nil is absent, pointer to empty is explicit empty.
History *[]InvocationMessage `json:"history,omitempty"`
ContractVersion string `json:"contract_version,omitempty"`
// State contains client-owned UI/session context, never authorization claims.
// Nil means absent; a non-nil empty map means an explicitly empty profile.
State map[string]json.RawMessage `json:"state,omitempty"`
ID string `json:"id"`
Purpose InvocationPurpose `json:"purpose"`
Messages []InvocationMessage `json:"messages"`
SessionID string `json:"session_id"`
RunID string `json:"run_id,omitempty"`
Deadline time.Time `json:"deadline"`
}
type InvocationToolCall ¶ added in v0.9.0
type InvocationWriter ¶ added in v0.8.0
InvocationWriter streams text to Platform. Returning nil from the handler completes the response; returning an error fails it. A *DenyError (including a wrapped one) reports a policy denial with Decision.Message to Platform. Calls after handler completion fail.
type KillSwitchError ¶
type KillSwitchError struct {
Kills []KillInfo
}
KillSwitchError is returned when a request is blocked by an operator kill switch — distinct from a policy DenyError because a kill ALWAYS enforces, bypassing FailMode (a kill can never be fail-open'd through). Kills carries the matching kill switch(es).
func AsKillSwitchError ¶
func AsKillSwitchError(err error) (*KillSwitchError, bool)
AsKillSwitchError reports whether err is a *KillSwitchError.
func (*KillSwitchError) Error ¶
func (e *KillSwitchError) Error() string
type LLMCall ¶
type LLMCall struct {
// AgentFramework identifies the observing framework. Operation defaults to "chat".
AgentFramework string
Operation string
// Data carries optional metadata such as native turn IDs, finish reasons, or
// content truncation indicators. Delegation keys are reserved by the SDK.
Data map[string]any
// Err describes a failed call, independent of policy-check decisions.
Err string
// Optional observed content for the call; callers decide what to capture.
RequestFull string
ResponseFull string
SessionID string
RequestID string
Model string
Provider string
// EndpointID / InstanceKey attribute the call to the endpoint-agent instance that made it.
// Optional — a plain agent call leaves them empty and emits exactly as before.
EndpointID string
InstanceKey string
// UserID is the person the sensor attributed the instance to (internal id, never
// an email). Optional — empty leaves the record unattributed.
UserID string
InputTokens int64 // uncached input, as the provider reports it
OutputTokens int64
CacheReadTokens int64 // prompt-cache hits; frequently orders of magnitude above InputTokens
CacheWriteTokens int64 // prompt-cache creation
LatencyMS float64
Streamed *bool
// Trace placement. TraceID/SpanID put the call in the caller's span tree, so a check that
// names this span as its parent (ContextWithTrace) renders nested under the call it governs
// rather than as an orphan root. Optional — leave both empty and the event ships untraced, as
// before.
TraceID string
SpanID string
// OccurredAt is when the call actually happened. An observer reporting a call it read from a
// transcript or a log is not reporting it at the instant it emits, and the platform orders a
// trace by this timestamp — so a passive sensor must say when, not let the emit time stand in.
// Zero means now.
OccurredAt time.Time
// Delegation, for a call made by a subagent rather than by the agent's main loop. A subagent
// runs inside its parent and reports the parent's SessionID, so without these its spend is
// indistinguishable from work the parent did itself.
//
// AgentID names the subagent; ParentSpanID nests the call under the work that spawned it;
// ComponentName carries the subagent's type when the host reports one. All optional — a call
// from the main loop leaves them empty and emits exactly as before.
AgentID string
ParentSpanID string
ComponentName string
}
LLMCall carries the facts of one model call. Token counts are the provider's own, reported as the provider reports them: InputTokens is the UNCACHED count, with cache reads/writes separate. The wire sums them into input_tokens and ships the breakdown alongside — callers never have to decide how to combine the tiers.
type LocalControlSyncOption ¶
type LocalControlSyncOption func(*localControlSyncSettings)
LocalControlSyncOption customizes the sync channel.
func WithLocalControlApplyHook ¶
func WithLocalControlApplyHook(fn func(cfg localcontrol.Config, err error)) LocalControlSyncOption
WithLocalControlApplyHook observes each applied (or rejected) rule set. The SDK has no logger of its own, so this is how a host surfaces "the published rules did not compile" — without it, that failure is only visible in the report the platform receives.
func WithLocalControlInterval ¶
func WithLocalControlInterval(d time.Duration) LocalControlSyncOption
WithLocalControlInterval overrides the poll cadence.
type ManifestInfo ¶
type ManifestInfo struct {
Framework string // e.g. "langchaingo", "anthropic-sdk-go"
Tools []string // tool names the agent can call
Models []string // model ids the agent uses
Skills []SkillInfo // Anthropic Agent Skills available to the agent (frontmatter only)
Environment string // dev|staging|prod
// Enterprise is an optional enterprise-identity block (provider, tenantId, roles, groups,
// scopes, issuer, …). prism stores it on the agent (pass-through) for enterprise governance.
Enterprise map[string]any
// EnterpriseToken is the optional raw enterprise identity JWT (a body credential prism carries
// through without interpreting). Set alongside Enterprise for enterprise-authenticated agents.
EnterpriseToken string
}
ManifestInfo is what an agent declares about itself at Connect: its framework and the tools/ models/skills it uses. The platform uses this for presence + manifest-seeded behavioral baselines.
type Mode ¶
type Mode string
Mode is retained for legacy SDK-local detector configuration only. It never skips a platform check, weakens a platform deny, or escalates a platform warn.
type ModelMode ¶
type ModelMode string
ModelMode selects direct checked calls, proxy passthrough, or gateway routing.
const ( ModelModeCheck ModelMode = "check" // default: call the provider directly, check via /v1/flyedge/check ModelModePassthrough ModelMode = "passthrough" // route through prism carrying the agent's own key ModelModeGateway ModelMode = "gateway" // send to prism; prism supplies agent-scoped credentials )
type ModelUsage ¶ added in v0.11.0
type ModelUsage struct {
InputTokens *uint64 `json:"input_tokens"`
CachedInputTokens *uint64 `json:"cached_input_tokens"`
OutputTokens *uint64 `json:"output_tokens"`
ReasoningTokens *uint64 `json:"reasoning_tokens"`
TotalTokens *uint64 `json:"total_tokens"`
}
ModelUsage contains provider-measured counts for one started model attempt. Nil means unknown; a pointer to zero means measured zero. InputTokens includes cached input, unlike LLMCall's legacy uncached scalar. Do not supply an estimated total. Failed or interrupted attempts must leave output/reasoning/total unknown.
type Operation ¶
Re-export the wire types so callers depend only on the flyedge package for the common surface.
type Option ¶
Option customizes a Guard at construction. Options make the seams explicit and testable: inject a fake Enforcer for offline tests, or a custom Signer (KMS, agent runtime) without env plumbing.
func WithAttachments ¶ added in v0.8.0
func WithAttachments() Option
WithAttachments sends inline images and PDFs with every check, independent of the per-agent nontext_payload setting. For a caller that decides media capture itself, such as flyedged, whose Claude Code plugin is the opt-in.
func WithCloudTelemetry ¶
WithCloudTelemetry ships protection events to the gateway (/v1/flyedge/telemetry) via a batched, owned-goroutine sink (flushed on Close), in addition to keeping Report() working locally. Cloud telemetry is enabled by default. interval is the flush cadence (0 → 5s). Requires an enforcer supporting signed POSTs; the default HTTP enforcer does.
func WithDecisionHandler ¶ added in v0.11.1
func WithDecisionHandler(fn func(CheckRequest, Decision)) Option
WithDecisionHandler observes the final decision once per Check, including checks made by the HTTP transport, plus explicit proxy policy denials and warning metadata. Proxy successes without warning metadata do not emit a decision. The handler runs synchronously before Check or the proxy transport returns and may run concurrently. It must be concurrency-safe and must not mutate the request or decision.
func WithEnforcer ¶
WithEnforcer injects the policy decision point — e.g. a stub in tests, or an offline/record implementation. Overrides the default HTTP enforcer.
func WithHeartbeat ¶
WithHeartbeat overrides the config-poll interval. By default the cadence comes from the ConnectResponse (heartbeat_interval_seconds), falling back to 30s. Set a shorter interval to pick up model-mode / simulation changes faster (e.g. during local testing).
func WithLocalControlEngine ¶
func WithLocalControlEngine(e *localcontrol.Engine) Option
WithLocalControlEngine injects an already-built engine. Useful when a caller wants to share one engine across several Guards, or to inject a stub in tests.
func WithLocalControls ¶
func WithLocalControls(cfg localcontrol.Config) Option
WithLocalControls enables in-process evaluation with an explicit configuration.
Most deployments should let the platform supply this through the sync channel (SyncLocalControls) rather than hardcoding it, so a rule change does not require redeploying every agent. This option exists for local development and for tests.
It returns an error when a configured pattern does not compile, so a broken rule set fails at New rather than looking active and enforcing nothing.
func WithManifestRefreshHandler ¶
func WithManifestRefreshHandler(fn func()) Option
WithManifestRefreshHandler overrides what happens when prism sets manifest_refresh_required. The default is to re-send the manifest (reconnect); provide a handler to customize (e.g. rebuild the manifest from live introspection first).
func WithModeChangeHandler ¶
WithModeChangeHandler observes effective routing changes from connect, reconnect, and heartbeat updates. The handler must be concurrency-safe.
func WithSigner ¶
WithSigner injects a Signer, overriding the one New would build from Config. Pass nil explicitly to run unsigned.
func WithSimulation ¶
WithSimulation enables or disables the simulation client (default: enabled). When disabled, the agent will not act as a simulation / eval target even if the platform starts a run against it — the config poller still tracks the simulation block, but no telemetry is streamed and protection is never bypassed.
func WithSimulationTelemetryURL ¶
WithSimulationTelemetryURL overrides the telemetry WebSocket URL the gateway advertises in the simulation config. Server-authoritative by default; set this only for split-horizon local dev (agent on the host, gateway in-cluster) so the controller dials a host-reachable URL instead of the in-cluster one. Equivalent to Config.SimTelemetryURL / COMPFLY_SIM_TELEMETRY_URL.
func WithTelemetry ¶
WithTelemetry injects the telemetry sink (e.g. Noop, a cloud batcher, or an OTel bridge), overriding the default cloud batcher.
func WithoutCloudTelemetry ¶ added in v0.8.0
func WithoutCloudTelemetry() Option
WithoutCloudTelemetry disables cloud event delivery and keeps an in-memory Recorder. A custom sink supplied with WithTelemetry still takes precedence.
type Principal ¶
Principal is the on-behalf-of envelope — the end-user an agent is acting for on a request. Re-exported from enforce so callers depend only on the flyedge package. See ContextWithPrincipal.
type SimulationConfig ¶
type SimulationConfig struct {
Active bool `json:"active"`
RunID string `json:"run_id"`
Middlewares []string `json:"middlewares"`
TelemetryJWT string `json:"telemetry_jwt"`
TelemetryURL string `json:"telemetry_url"`
ProtectionDisabled bool `json:"protection_disabled"`
Extra json.RawMessage `json:"extra,omitempty"`
}
SimulationConfig is prism's `simulation` block from GET /v1/flyedge/config (frozen wire — matches prism SimulationConfig). Delivered only while a run is active. The simulation controller reacts to it, and it is surfaced via Guard.SimulationConfig / SimulationActive.
type SkillInfo ¶
type SkillInfo struct {
Name string // frontmatter `name` — the identity drift recognition matches on
Description string // frontmatter `description`
AllowedTools []string // frontmatter `allowed-tools`
Scripts []string // filenames under <skill>/scripts/ — names only, never contents
Source string // "framework" | "config" | "filesystem" — how it was discovered
SourcePath string // where it was found, e.g. the materialized pack path
}
SkillInfo is one Anthropic Agent Skill the agent has available — SKILL.md frontmatter only. Skill bodies and script contents are never shipped: the platform governs which skills exist on an agent, not what they say.
This is what makes an edge-pack-distributed skill visible to the platform: the daemon materializes it on disk, the agent declares it here, and drift recognition matches it against the org's published packs (governed) or flags it for review (not from any pack).
type Stage ¶
Re-export the wire types so callers depend only on the flyedge package for the common surface.
type StateContract ¶ added in v0.8.0
type StateContract struct {
Fields map[string]StateField `json:"fields"`
Required []string `json:"required,omitempty"`
}
type StateField ¶ added in v0.8.0
type StateField struct {
Type StateFieldType `json:"type"`
// PlaygroundDefault prefills the Playground editor only. It never fills runtime or scenario state.
PlaygroundDefault json.RawMessage `json:"playground_default,omitempty"`
}
type StateFieldType ¶ added in v0.8.0
type StateFieldType string
const ( StateString StateFieldType = "string" StateNumber StateFieldType = "number" StateBoolean StateFieldType = "boolean" StateJSON StateFieldType = "json" )
type Taint ¶
type Taint struct {
Version int `json:"version"`
NamespaceID string `json:"namespace_id"`
SessionID string `json:"session_id"`
Taints []TaintEntry `json:"taints"`
SessionSeverity float64 `json:"session_severity"`
TaintHash string `json:"taint_hash"`
CurrentTurn int `json:"current_turn"`
}
Taint is prism's SessionTaintDocument: the rolled-up taint state for a session. SessionSeverity is the aggregate score; Taints holds the individual signals.
type TaintEntry ¶
type TaintEntry struct {
ToolCallID string `json:"tool_call_id,omitempty"`
ToolName string `json:"tool_name,omitempty"`
Labels []string `json:"labels,omitempty"`
InjectionScore *float64 `json:"injection_score,omitempty"`
PIIScore *float64 `json:"pii_score,omitempty"`
Turn int `json:"turn"`
Severity float64 `json:"severity"`
CreatedAt string `json:"created_at"`
}
TaintEntry is one accrued taint signal (prism TaintEntry).
type ToolIO ¶
type ToolIO struct {
// LatencyMS is the observed execution duration; zero means unknown.
LatencyMS float64
// Err describes a failed tool execution, independent of policy decisions.
Err string
SessionID string
RequestID string
ToolName string
// EndpointID / InstanceKey attribute the tool call to the endpoint-agent instance that made it.
// Optional — a plain agent call leaves them empty and emits exactly as before.
EndpointID string
InstanceKey string
// UserID is the person the sensor attributed the instance to (internal id, never
// an email). Optional — empty leaves the record unattributed.
UserID string
// Delegation, for a tool call made by a subagent rather than by the agent's main loop. A
// subagent runs inside its parent and reports the parent's SessionID, so without these its
// tool use is indistinguishable from the parent's own. AgentID names the subagent;
// ComponentName carries its type when the host reports one. Both optional — a main-loop call
// leaves them empty and emits exactly as before. Mirrors LLMCall's delegation fields.
AgentID string
ComponentName string
ArgsJSON string
ResultJSON string
TraceID string
SpanID string
ParentSpanID string
AgentFramework string
Data map[string]any
// OccurredAt is when the tool actually ran. Zero means now — see LLMCall.OccurredAt for why an
// observer has to say when rather than let the emit time stand in.
OccurredAt time.Time
}
ToolIO carries one observed tool invocation. ArgsJSON/ResultJSON are optional audit payloads; callers that only need usage attribution can leave them empty.
type TurnOutcome ¶ added in v0.7.0
type TurnOutcome struct {
SessionID, RequestID string
EndpointID, InstanceKey, UserID string
TraceID, SpanID, ParentSpanID string
AgentFramework string
Err string
OccurredAt time.Time
Data map[string]any
}
TurnOutcome reports how an agent turn ended when the host names no single model or tool call: a user abort or an error that ended the turn. Data carries the outcome fields (execution_status, decided_by, outcome_stage, error_kind); Err is the host's error text.
type UsageObservation ¶ added in v0.6.0
type UsageObservation struct {
Kind, Name string // Kind is "skill" or "hook".
SessionID, RequestID string
EndpointID, InstanceKey, UserID string
TraceID, SpanID, ParentSpanID string
AgentFramework string
OccurredAt time.Time
Data map[string]any
}
UsageObservation identifies observed skill or hook use. It carries no policy verdict or content payload; Data describes the evidence, not enforcement.
type WrapOption ¶
type WrapOption func(*guardRoundTripper)
WrapOption customizes WrapRoundTripper.
func WithResponseCheck ¶
func WithResponseCheck() WrapOption
WithResponseCheck enables a post_llm policy check on model responses (block for non-streaming, monitor for streaming). Enabled by default; retained for source compatibility.
Source Files
¶
- attachments.go
- config.go
- config_poll.go
- connect.go
- flyedge.go
- governed.go
- identity_context.go
- inbound.go
- invocation.go
- invocation_contract.go
- invocation_history.go
- invocation_recovery.go
- invocation_usage.go
- local_controls.go
- local_controls_sync.go
- observation.go
- options.go
- proxy_policy.go
- response.go
- responses.go
- scenario.go
- session.go
- sim_bridge.go
- stages.go
- taint.go
- telemetry_emit.go
- trace.go
- transport.go
- transport_usage.go
- verdict_relay.go
- version.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package edgesync is the generic poll/report rails behind every edge sync channel — edge packs, local controls, and whatever comes after.
|
Package edgesync is the generic poll/report rails behind every edge sync channel — edge packs, local controls, and whatever comes after. |
|
Package enforce is the policy decision-point client: it signs a CheckRequest and POSTs it to prism's /v1/flyedge/check, returning a typed Decision.
|
Package enforce is the policy decision-point client: it signs a CheckRequest and POSTs it to prism's /v1/flyedge/check, returning a typed Decision. |
|
Package identity implements the flyedge DID + Ed25519 request-signing contract.
|
Package identity implements the flyedge DID + Ed25519 request-signing contract. |
|
Package localcontrol is the in-process policy layer: detectors that decide without a network round trip, so an obviously-destructive call is stopped at the edge and an offline agent is not an ungoverned one.
|
Package localcontrol is the in-process policy layer: detectors that decide without a network round trip, so an obviously-destructive call is stopped at the edge and an offline agent is not an ungoverned one. |
|
SPDX-License-Identifier: Apache-2.0 Copyright 2026 CompFly AI
|
SPDX-License-Identifier: Apache-2.0 Copyright 2026 CompFly AI |
|
Package telemetry defines the flyedge protection-telemetry seam.
|
Package telemetry defines the flyedge protection-telemetry seam. |
|
otel
module
|