flyedge

package module
v0.11.3 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: Apache-2.0 Imports: 36 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.

README

Flyedge Go SDK

Govern AI agents at the edge, where model requests, tool calls, and data cross application boundaries.

Flyedge is the Go edge runtime SDK for CompFly. It connects your agent to the CompFly control plane and applies policy at runtime, before governed model requests and tool calls execute. Use it to enforce allow, warn, or deny decisions, honor remote kill switches, and produce auditable runtime telemetry.

The SDK is deliberately explicit and idiomatic Go: construct a Guard, pass it through your application, and wire it into the boundaries you want governed. Policy denials are typed errors. There is no global singleton, import-time side effect, or framework-specific monkeypatching.

Go applications use this independent Go runtime. Rust applications use the FlyEdge Rust core; Python and TypeScript map to that core through PyO3 and NAPI-RS native bindings. See the shared-core architecture.

How it works

                         policy checks and decisions
Your agent ──▶ Flyedge Guard ◀────────────────────────▶ CompFly control plane
                    │
                    ├── allowed model request ────────▶ model provider
                    └── allowed tool call ────────────▶ tool or service

By default, Flyedge checks policy out of band and sends allowed model requests directly to the provider. Proxy mode is available when model traffic must pass through the CompFly gateway. Tool calls remain explicit because your application owns the agent loop and the moment a tool is executed.

Install

go get github.com/compfly-ai/flyedge-go

Requires Go 1.23+.

Quick start

Register an agent in CompFly, then provide its DID and Ed25519 signing key:

export COMPFLY_AGENT_DID="did:compfly:..."
export COMPFLY_AGENT_PRIVATE_KEY_PATH="/path/to/agent-key.pem"

Wrap the HTTP transport used by your model client to govern outbound requests:

guard, err := flyedge.New(flyedge.LoadEnv())
if err != nil {
    return err
}
defer guard.Close()

hc := &http.Client{Transport: guard.WrapRoundTripper(http.DefaultTransport)}
client := anthropic.NewClient(
    anthropicopt.WithAPIKey(os.Getenv("ANTHROPIC_API_KEY")),
    anthropicopt.WithHTTPClient(hc),
)

ctx := flyedge.ContextWithSession(context.Background(), "demo-session")
resp, err := client.Messages.New(ctx, params) // a denial surfaces as a typed error

Call CheckToolCall before executing a tool and CheckToolResponse before returning its result to the model. This is what lets Flyedge stop a dangerous action instead of merely observing it.

Use WithDecisionHandler(func(CheckRequest, Decision)) at Guard construction to observe final policy decisions, including transport warnings that allow a provider request to continue. Read Decision.Warnings and Decision.Message; an allowed decision can carry warnings. The optional callback runs once per Check, before it returns, and must be concurrency-safe and treat its arguments as read-only. Explicit proxy policy denials and gateway warning metadata also reach this callback. Proxy denials return *DenyError with the authored Decision.Message; warning metadata is delivered before the unchanged provider response, including streams. Ordinary provider errors retain their HTTP status and body.

See the complete developer guide for Anthropic, OpenAI, Gemini, langchaingo, tool-use loops, identity, telemetry, and production configuration.

WrapRoundTripper also recognizes Google Vertex generateContent and streamGenerateContent, and Anthropic Vertex rawPredict and streamRawPredict, on global/regional aiplatform.googleapis.com endpoints (v1 and v1beta1). In passthrough or gateway mode, these calls use the existing signed gateway route and preserve gateway HTTP errors. In direct mode, non-streaming denials withhold the response; streamed output is audited after delivery. Other Vertex operations, such as embeddings and token counting, remain outside this transport wrapper.

OpenAI Responses (client.Responses.New) is covered by the same wrapped HTTP transport, including function-call output and streaming audits. See Responses coverage and limits, including partial conversation context and coordinated Prism proxy rollout and background-mode limits.

Model routing preference

Set Config.ModelMode to ModelModeCheck, ModelModePassthrough, or ModelModeGateway, or use FLYEDGE_MODEL_MODE with LoadEnv. Empty means inherit. Invalid values are rejected by New.

Explicit per-agent platform settings take precedence over the SDK preference; the SDK preference takes precedence over the organization default. Without either, routing defaults to check. Servers that return a mode without recognized model_mode_source metadata remain authoritative for compatibility.

Chat Completions and Responses use the same effective mode. Heartbeats and reconnects preserve the SDK preference, and WithModeChangeHandler reports changes to the effective mode. Proxy requests send X-CompFly-Model-Mode only for an explicit SDK preference. The platform still applies per-agent policy and all normal enforcement checks.

Legacy ProxyMode: true opts into proxy routing: it retains a non-check server mode when present, otherwise selects passthrough. Explicit ModelMode takes precedence over that legacy flag; per-agent and older-server authority still apply.

Governance points

Wire in only the boundaries you need:

Stage Guards Call
pre_llm the outgoing model request guard.WrapRoundTripper(base)
tool_call a tool the model wants to run guard.CheckToolCall(...)
tool_call_response a tool's output before it re-enters context guard.CheckToolResponse(...)
post_llm the model's response text WithResponseCheck() or guard.CheckModelResponse(...)

Flyedge governs only operations routed through these integration points. Keep your application's normal authentication and authorization in place; Flyedge adds runtime policy at the model and tool boundary. A buffered model response can be blocked before delivery. Streaming output is observed when the stream completes and cannot be retracted.

Configuration

flyedge.LoadEnv() is the single place environment is read; override fields on the returned Config before calling New.

Variable Meaning
COMPFLY_API_URL gateway base URL; defaults to https://prism.p.compfly.ai
COMPFLY_AGENT_DID the agent's DID
COMPFLY_AGENT_PRIVATE_KEY_PATH Ed25519 signing key (or COMPFLY_AGENT_PRIVATE_KEY inline)
FLYEDGE_CLOUD_TELEMETRY true (default) or false; controls cloud event delivery
FLYEDGE_MODE enforce | warn (default) | audit | off
FLYEDGE_FAIL_MODE fail_open (default) | fail_closed — what happens when the gateway is unreachable

The posture settings are intentionally separate:

  • In warn and audit, platform warnings are advisory. In enforce, a warning blocks.
  • A platform denial or kill-switch decision blocks in every checking mode.
  • off bypasses policy checks entirely and is intended for local development.
  • Local detectors have a separate posture, supplied by CompFly or configured in process. They can add a fast local denial but cannot override one from the control plane.

The default is fail_open: if the gateway is unreachable, the action proceeds and the error is recorded. Set fail_closed when blocking is safer than continuing during an outage. A kill-switch decision always blocks and cannot be failed open.

Cloud telemetry is enabled by default: events are batched to /v1/flyedge/telemetry every five seconds and flushed on Close(). Report() remains available locally. Set Config.CloudTelemetry to a *bool (nil means enabled), or set FLYEDGE_CLOUD_TELEMETRY=false when using LoadEnv(), to disable cloud delivery. Invalid environment values are rejected by New unless you replace the field. Set Config.TelemetryInterval to customize the cadence; values below one second use the five-second default. Explicit telemetry options override configuration. Use WithCloudTelemetry(interval) to enable delivery and set the cadence, or WithoutCloudTelemetry() for local-only recording. A WithTelemetry(sink) custom sink takes precedence over cloud delivery.

Denials are values

A check returns a Decision and an error. A policy denial is a typed *DenyError, not a panic or an opaque failure. Your agent decides whether to refuse, retry, or take another path. Kill switches surface separately as *KillSwitchError.

Packages

Package Purpose
flyedge the Guard, config, stages, sessions
enforce the wire contract and enforcement client
identity DID + Ed25519 request signing
telemetry telemetry sinks and the protection report
telemetry/otel OpenTelemetry sink (separate module)
langchaingo Platform-invocation conversation to langchaingo messages (separate module)
simulation simulation client and attack injection

Examples

Runnable programs in examples/, each with its own README:

  • reference-agent — the complete integration surface (Connect, heartbeat, local controls, all four stages, on-behalf-of identity) over standard platform invocation, with optional chat REPL, one-off, or HTTP modes, with a ready-made custom control to test enforcement
  • agent — one governed transport wrap across the Anthropic and OpenAI SDKs
  • openai, gemini — single-provider governed model + tool calls
  • agentframework — Microsoft Agent Framework Go with governed model and automatic tool calls
  • docs-quickstart — the snippets from the developer guide, compiled
  • langchaingo, otel, manual, tools — framework, telemetry and low-level wiring
  • sim-target, attack-target — Simulation Lab / red-team targets

Docs

License

Apache-2.0. See NOTICE for attribution.

Observed call telemetry

RecordLLMCallDetail accepts optional request/response content, framework identity, operation (defaults to chat), and Data metadata. Callers can preserve native turn IDs, finish reasons, or content truncation indicators in Data. When a subagent is supplied, the SDK reserves delegated, subagent_id, and subagent_type for delegation attribution.

RecordToolIODetail accepts arguments/results and observed execution duration in LatencyMS. Both call types accept Err for execution failures; cloud telemetry carries it in the reserved data.error key. These failures do not count as policy checks. Metadata is retained by ingestion, but dedicated UI columns require consumer support. Callers choose which content to capture and must populate these optional fields; the SDK does not collect it automatically.

Explicit platform invocations

Platform invocation is the standard connection for Playground, simulations, and evaluations. The agent opens an authenticated outbound WebSocket; no public HTTP listener or tunnel is required. Follow the Playground setup guide for state, history, and tool-mocking walkthroughs, and the scenario integration guide for handler and tool code.

The SDK sends a WebSocket Ping every 10 seconds and waits up to 30 seconds for the matching Pong using the WebSocket library. This runs independently of HTTP configuration polling, lease renewal, and agent work. A heartbeat failure triggers automatic recovery when the broker supports it, without replaying requests. Socket errors retain the underlying cause while remaining compatible with errors.Is(err, flyedge.ErrInvocationOutcomeUnknown).

Guard.ServeInvocations lets Playground, simulations, and evaluations invoke an application handler over an outbound WebSocket. Calling New or Connect does not enable it: your application must explicitly register a handler and authorize its purposes. The handler runs with your application's credentials, so wire policy checks into its model and tool boundaries as you would for a normal invocation.

connection, err := guard.ServeInvocations(ctx, flyedge.InvocationOptions{
    Name:        "Support agent",
    Environment: "staging",
    Purposes: []flyedge.InvocationPurpose{
        flyedge.PurposePlayground,
        flyedge.PurposeSimulation,
        flyedge.PurposeEval,
    },
    Contract: &flyedge.InvocationContract{
        State: flyedge.StateContract{
            Fields: map[string]flyedge.StateField{
                "selected_order_id": {Type: flyedge.StateString},
                "form":              {Type: flyedge.StateJSON},
            },
        },
    },
}, func(ctx context.Context, request flyedge.InvocationRequest, out flyedge.InvocationWriter) error {
    // Optional state is application input. Convert it into your own domain or
    // protobuf types, initialize test context, and run your application logic.
    var selectedOrder string
    if raw, supplied := request.State["selected_order_id"]; supplied {
        if err := json.Unmarshal(raw, &selectedOrder); err != nil {
            return err
        }
    }
    // Invoke your governed application here. TextDelta may be called repeatedly
    // as your model produces text. Returning nil completes this invocation.
    return out.TextDelta(ctx, "Selected order: " + selectedOrder)
})
if err != nil {
    return err
}
defer connection.Close()
return connection.Wait()

This snippet uses encoding/json. Configure the Guard with its DID and Ed25519 private key as in Quick start. Registration is signed, requires an existing platform agent, and publishes the state contract before accepting invocations. HTTPS is required; AllowInsecureLoopback: true permits only literal loopback HTTP for local development. Environment selects an agent environment; APIURL selects the local or hosted deployment.

API Behavior
AllowSimulationInjection Defaults to enabled when nil for platform invocation. Set a *bool pointing to false to disable injected mocks.
InvocationOptions.Purposes Explicitly permits PurposePlayground, PurposeSimulation, and/or PurposeEval.
LeaseDuration Renewable authorization window, default one hour; accepted range 1 second–24 hours.
AutoRenew *bool, default true when nil. A pointer to false creates a finite lease. Renewal keeps the same connection alive until stopped or revoked.
AllowOperatorReconnect Defaults to false. Allows an authorized Platform operator to request a fresh lease through the signed config heartbeat after the socket closes. Requires a compatible Platform deployment.
AllowClientState *bool, default true when nil. A pointer to false rejects state. A declared state contract requires it to be enabled.
AllowClientHistory Opt-in permission for caller-supplied conversation history. Map request.History followed by request.Messages into your provider conversation without re-executing past tool calls.
Contract.State Declares Fields and optional Required names. Types: StateString, StateNumber, StateBoolean, StateJSON. No state defaults are injected.
RequestTimeout Invocation timeout, default two minutes; accepted range 1 second–10 minutes.
InvocationRequest Contains ID, Purpose, Messages, SessionID, RunID, Deadline, optional State, History, and Traceparent, and ContractVersion. A valid W3C v00 Traceparent scopes handler-context checks to the turn trace without changing SessionID; absent or malformed values keep the existing trace fallback.
InvocationWriter.TextDelta Sends a text chunk immediately over the outbound WebSocket. The current platform broker collects chunks before returning the full response to Playground.
InvocationConnection Exposes the initial lease ID and pinned ContractVersion, the current ActiveLeaseID(), ExpiresAt(), Close(), and blocking Wait().

State is map[string]json.RawMessage: nil means no state was supplied; a non-nil empty map means explicit empty state. A dataset scenario supplies its own literal state object, and Playground supplies values entered in the state editor. The platform validates supplied values against the declared contract. Optional typed fields should be omitted rather than set to null; required fields are checked when state is supplied. State is not an authenticated identity or authorization grant. Your application explicitly decides how to consume it before the agentic layer runs. New evaluations do not select run-wide state profiles or substitute tokens inside state.

The handler context is canceled on timeout, shutdown, or revocation. Returning an error fails that invocation. With a recovery-capable broker, transport failures recover automatically. Wait() ends on terminal failure and reports ErrConnectionRevoked, ErrConnectionExpired, or ErrInvocationOutcomeUnknown when appropriate. With AllowOperatorReconnect enabled, Wait() stays blocked until local shutdown. Each operator request authorizes one fresh registration using the original invocation options and handler. Recovery is automatic when the broker acknowledges recovery protocol v1. No configuration switch is required. Older brokers remain usable, but cannot recover automatically. Transport failures enter one serialized recovery loop. Retries use jittered exponential backoff (0.5–1 second initially, up to 30 seconds) and respect Retry-After. Temporary HTTP 409 conflicts keep a short 0.5–1 second retry delay. Signed recovery requests prove ownership with the current socket token so compatible brokers can fence the old socket immediately, without waiting for its heartbeat timeout. HTTP 409 (including a pending handshake), 429, 5xx, and network failures are retryable. Authentication failures, missing/revoked leases, unsupported protocols, and changed authorization are terminal. Cancellation and the last acknowledged lease deadline bound recovery. Recovery never renews a lease, changes its scope, or falls back to ordinary registration. It accepts a previously committed renewal even if its acknowledgement was lost. Initial registration failures still return to the caller; this loop starts after a ready connection.

In-flight work is never replayed. Cancellation is cooperative and cannot reverse completed side effects. Each connection serves one active invocation at a time, with a maximum aggregate text output of 1 MiB.

The reference concierge serves platform invocations by default, with optional location state, provider conversation history, and before-tool mock hooks. Use go run ./reference-agent -provider openai -model <your-model> from examples/ with the configured agent identity and provider key.

See the runnable support agent and its scenario-owned state dataset for an example with tool calls, policy checks, colored logs, and simulation telemetry.

Optional Playground defaults

StateField.PlaygroundDefault is optional JSON editor metadata:

"selected_order_id": {
    Type: flyedge.StateString,
    PlaygroundDefault: json.RawMessage(`"DEMO-42"`),
},

The SDK and Platform validate the default against the declared type. Playground prefills it when the user enables Supply starting state, and preserves edits when toggling state off and back on. No default is sent while state is disabled. Scenarios and runtime requests never have missing fields filled automatically; they continue to carry exactly their supplied state. Omit the default when it is not useful. Boolean false, numeric zero, empty strings, and JSON null are retained.

Platform-invocation injection is enabled by default; endpoint integrations are unchanged. AllowSimulationInjection is now *bool, matching the optional-state convention. Existing callers setting it to true can omit it; callers disabling it should use disabled := false and AllowSimulationInjection: &disabled. This default does not create mocks: scenario overrides and the application's before-tool hook still control them.

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

View Source
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
)
View Source
const DefaultAPIURL = "https://prism.p.compfly.ai"

DefaultAPIURL is the prism gateway base URL used when Config.APIURL is empty.

View Source
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.

View Source
const LocalControlPollPath = "/v1/flyedge/local-controls"

LocalControlPollPath is prism's distribution endpoint for the org's local-control rule set.

View Source
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.

View Source
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

View Source
var ErrConnectionExpired = errors.New("flyedge: invocation lease expired")
View Source
var ErrConnectionRevoked = errors.New("flyedge: invocation connection revoked")
View Source
var ErrInvocationOutcomeUnknown = errors.New("flyedge: invocation connection lost; in-flight outcomes may be unknown")

Functions

func ContextWithAgentIdentity

func ContextWithAgentIdentity(ctx context.Context, sid, urn string) context.Context

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

func ContextWithDelegation(ctx context.Context, token string) context.Context

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

func ContextWithPrincipal(ctx context.Context, p Principal) context.Context

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

func ContextWithSession(ctx context.Context, id string) context.Context

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

func ContextWithTrace(ctx context.Context, traceID, spanID string) context.Context

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

func InboundHandler(next http.Handler) http.Handler

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.

func WithVerdictRelay added in v0.5.0

func WithVerdictRelay(ctx context.Context, relay string) context.Context

WithVerdictRelay describes whether this host can apply a verdict. It does not alter the verdict. Passive/unsupported stages must never count as blocked.

Types

type Action

type Action = enforce.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.

func LoadEnv

func LoadEnv() Config

LoadEnv builds a Config from COMPFLY_*/FLYEDGE_* environment variables. This is the single, explicit place env is read — callers may then override fields before calling New.

type Content

type Content = enforce.Content

Re-export the wire types so callers depend only on the flyedge package for the common surface.

type Decision

type Decision = enforce.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

func AsDenyError(err error) (*DenyError, bool)

AsDenyError is a convenience for callers: returns the *DenyError if err is one.

func (*DenyError) Error

func (e *DenyError) Error() string

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.

const (
	FailOpen   FailMode = "fail_open" // default — availability over strictness
	FailClosed FailMode = "fail_closed"
)

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

func New(cfg Config, opts ...Option) (*Guard, error)

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

func (g *Guard) AcknowledgeSessionTaint(ctx context.Context, sessionID string) error

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

func (g *Guard) Check(ctx context.Context, req CheckRequest) (decision Decision, err error)

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

func (g *Guard) Close() error

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) DID

func (g *Guard) DID() string

DID returns the agent DID this guard signs as ("" if unsigned).

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

func (g *Guard) LocalControlDetectors() []string

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

func (g *Guard) ModelMode() 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

func (g *Guard) NontextPayloadAllowed() bool

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

func (g *Guard) RecordLLMCallDetail(c LLMCall)

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

func (g *Guard) RecordSessionStart(sessionID string, data map[string]any)

RecordSessionStart / RecordSessionSummary emit agent-session lifecycle telemetry. data is an optional payload (e.g. rolled-up stats on summary).

func (*Guard) RecordSessionSummary

func (g *Guard) RecordSessionSummary(sessionID string, data map[string]any)

func (*Guard) RecordToolIO

func (g *Guard) RecordToolIO(sessionID, requestID, toolName, argsJSON, resultJSON string)

RecordToolIO emits a tool_io event (tool name + args/result). argsJSON/resultJSON are carried as the audit request/response payloads.

func (*Guard) RecordToolIODetail

func (g *Guard) RecordToolIODetail(c ToolIO)

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

func (g *Guard) Report() Summary

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

func (g *Guard) ScenarioMockStatus() map[string]any

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

func (g *Guard) SessionTaint(ctx context.Context, sessionID string) (*Taint, error)

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

func (g *Guard) SimulationActive() bool

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

type InvocationHTTPError struct {
	StatusCode int
	RetryAfter time.Duration
}

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 InvocationToolCall struct {
	ID        string         `json:"id"`
	Name      string         `json:"name"`
	Arguments map[string]any `json:"arguments"`
}

type InvocationWriter added in v0.8.0

type InvocationWriter interface {
	TextDelta(context.Context, string) error
}

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 KillInfo

type KillInfo = enforce.KillInfo

KillInfo describes an active kill switch (re-exported from enforce).

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.

const (
	ModeEnforce Mode = "enforce"
	ModeWarn    Mode = "warn" // default
	ModeAudit   Mode = "audit"
	ModeOff     Mode = "off"
)

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

type Operation = enforce.Operation

Re-export the wire types so callers depend only on the flyedge package for the common surface.

type Option

type Option func(*Guard) error

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

func WithCloudTelemetry(interval time.Duration) Option

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

func WithEnforcer(e enforce.Enforcer) Option

WithEnforcer injects the policy decision point — e.g. a stub in tests, or an offline/record implementation. Overrides the default HTTP enforcer.

func WithFailMode

func WithFailMode(f FailMode) Option

WithFailMode overrides Config.FailMode.

func WithHeartbeat

func WithHeartbeat(interval time.Duration) Option

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 WithMode

func WithMode(m Mode) Option

WithMode overrides Config.Mode.

func WithModeChangeHandler

func WithModeChangeHandler(fn func(old, cur ModelMode)) Option

WithModeChangeHandler observes effective routing changes from connect, reconnect, and heartbeat updates. The handler must be concurrency-safe.

func WithSigner

func WithSigner(s identity.Signer) Option

WithSigner injects a Signer, overriding the one New would build from Config. Pass nil explicitly to run unsigned.

func WithSimulation

func WithSimulation(enabled bool) Option

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

func WithSimulationTelemetryURL(url string) Option

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

func WithTelemetry(t telemetry.Telemetry) Option

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

type Principal = enforce.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

type Stage = enforce.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 Summary

type Summary = telemetry.Summary

Summary is the aggregate protection report (see Guard.Report).

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.

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

Jump to

Keyboard shortcuts

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