> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sec0.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Core Concepts

> Understand hops, custody chains, agent state, and how Sec0 layers security across device and network boundaries.

## Hops

A **hop** is any unit of work in an agentic runtime that Sec0 instruments. Every hop gets a consistent identity, audit trail, and state propagation envelope.

Sec0 supports seven hop types:

| Hop Type       | Description                                                 | Decorator              |
| -------------- | ----------------------------------------------------------- | ---------------------- |
| `agent`        | An AI agent performing inference or work                    | `@sec0.agent()`        |
| `orchestrator` | A coordinator that plans and delegates to agents/tools      | `@sec0.orchestrator()` |
| `gateway`      | A network-boundary router that forwards to upstream servers | `@sec0.gateway()`      |
| `server`       | A tool server (MCP or otherwise)                            | `@sec0.server()`       |
| `middleware`   | An enforcement layer wrapping tool execution                | `@sec0.middleware()`   |
| `tool`         | A specific tool invocation on a server                      | `@sec0.tool()`         |
| `skill`        | A versioned agent skill/package invocation                  | `@sec0.skill()`        |

Each hop is registered in `sec0.config.yaml` under `app.hops` with its type, `nodeId`, and type-specific metadata. Decorators resolve their configuration from this registry automatically.

For package installation and import paths, see [Installation](/docs/installation) (and use the [Quickstart](/docs/quickstart) for an end-to-end setup).

## Custody Chain

Sec0 maintains a **custody chain**, an unbroken, signed audit trail across every hop in a request graph. This is achieved through:

1. **Trace propagation**: W3C-compatible `traceId` and `spanId` flow through every hop
2. **Agent state headers**: Canonical state (`x-node-id`, `x-agent-ref`, `x-agent-state`) propagated via HTTP headers
3. **Signed audit envelopes**: Each hop emits an Ed25519-signed NDJSON record with input/output integrity hashes
4. **Cause linking**: Parent `traceId`/`spanId` are recorded as `cause_trace_id`/`cause_span_id` for graph reconstruction

## Architecture

Sec0 enforces security at two distinct boundaries:

### In-Device Security

These controls run **within** your application process:

| Control                | Package                    | What It Does                                                                                    |
| ---------------------- | -------------------------- | ----------------------------------------------------------------------------------------------- |
| Hop decorators         | `sec0-sdk/instrumentation` | Audit trails, state propagation, trace linking for every hop                                    |
| Agent state            | `sec0-sdk/agent-state`     | Canonical encoding/decoding of agent state across hops                                          |
| Middleware enforcement | `sec0-sdk/middleware`      | Wraps tool execution with policy, audit, and runtime decision hooks                             |
| Guard API              | `sec0-sdk/guard`           | App-level allow, redact, block, and escalate checks for outbound messages, tool calls, and APIs |
| Agent Guard            | `sec0-sdk/middleware`      | Inline scanning for prompt injection, PII, secrets, toxic content, malicious code               |
| Registry freeze        | `sec0-sdk/middleware`      | Prevents handler swaps and registry mutation after initialization                               |
| Source hashing         | `sec0-sdk/middleware`      | Detects code changes in tool handlers and server code                                           |
| SAST                   | `sec0-sdk/middleware`      | Static analysis triggered on handler code/version change; blocks until scan passes              |
| DAST                   | `sec0-sdk/middleware`      | Dynamic analysis triggered on code/version change; generates runtime block rules with TTL       |

### Network Boundary Security

These controls enforce policy when execution crosses process or network boundaries:

| Control                | Package                | What It Does                                                                           |
| ---------------------- | ---------------------- | -------------------------------------------------------------------------------------- |
| Policy enforcement     | `sec0-sdk/middleware`  | Tool allowlists, version pinning, deny rules on every invocation                       |
| Bridge client          | `sec0-sdk/middleware`  | Preserves custody, trace, idempotency, and agent-state continuity across gateway calls |
| Gateway auth           | `sec0-sdk/gateway`     | OIDC JWT validation at the network edge                                                |
| Entitlements           | `sec0-sdk/gateway`     | Per-tenant/per-user tool allowlists and limits                                         |
| Quotas                 | `sec0-sdk/gateway`     | Rate limits and daily call limits per tenant/tool                                      |
| Vendor token brokering | `sec0-sdk/gateway`     | Inject upstream API keys without exposing them to agents                               |
| Idempotency/dedupe     | `sec0-sdk/gateway`     | Replay or reject duplicate side-effect calls                                           |
| Boundary guardrails    | `sec0-sdk/gateway`     | Egress allowlists, filesystem allowlists, payload limits                               |
| AP2 mandates           | `sec0-sdk/mandate-ap2` | Multi-hop intent/cart verification for authorized actions                              |

## How It Works

### In-Device Security

Decorators instrument each hop in your application process. The middleware wraps your tool server to enforce policy and emit signed audit logs.

```mermaid theme={null}
flowchart TD
  Orch["Orchestrator"]
  A1["Agent A"]
  A2["Agent B"]
  TS["Tool Server"]
  MW["sec0-sdk/middleware"]
  SAST["Security Testing"]
  AL[("Signed Audit Log")]

  Orch -- "delegates" --> A1
  Orch -- "delegates" --> A2
  A1 -- "calls tools" --> TS
  A2 -- "calls tools" --> TS
  TS -- "wrapped by" --> MW

  MW -- "on code/version change" --> SAST
  SAST -- "findings" --> MW

  MW -- "writes" --> AL
  Orch -- "writes" --> AL
  A1 -- "writes" --> AL
```

Each layer is decorated independently:

| Decorator                  | What it instruments                                                             |
| -------------------------- | ------------------------------------------------------------------------------- |
| `@sec0.orchestrator()`     | Coordinates agents, tracks plan vs. execution                                   |
| `@sec0.agent()`            | Performs reasoning, sets objectives and state                                   |
| `@sec0.tool()`             | Individual tool invocations                                                     |
| `sec0SecurityMiddleware()` | Wraps the tool server with policy enforcement, Agent Guard, and registry freeze |

On every tool invocation the middleware computes a source hash of the handler. When the hash changes (code update or version change), Security Hook scans (Claude Security/SAST/DAST) are triggered automatically. Execution can be blocked until the scan passes, based on configured severity thresholds.

Every decorated hop emits a signed audit envelope to the append-only audit log.

### Network Boundary Security

When tool calls cross a network boundary, the gateway enforces auth, quotas, and custody at the edge.

#### Tool call via gateway

```mermaid theme={null}
flowchart LR
  A["Agent / Orchestrator"]
  GW["sec0-sdk/gateway"]
  R["Remote Tool Server"]
  AL[("Signed Audit Log")]

  A -- "callToolViaGateway()" --> GW
  GW -- "forwards with custody" --> R
  GW -- "writes" --> AL
```

The agent calls `callToolViaGateway()` with the server name, tool\@version, arguments, auth header, trace context, and agent state. The gateway validates auth, checks entitlements and quotas, injects vendor tokens, enforces idempotency, then forwards to the remote tool server.

See [Gateway Bridge](/docs/bridge) for client usage and [Network Gateway](/docs/gateway) for gateway setup, endpoints, and enforcement options.

#### Agent-to-agent via gateway

```mermaid theme={null}
flowchart LR
  A1["Agent A"]
  GW["sec0-sdk/gateway"]
  A2["Agent B"]
  AL[("Signed Audit Log")]

  A1 -- "callToolViaGatewayWithAgent()" --> GW
  GW -- "forwards with agent context" --> A2
  GW -- "writes" --> AL
```

`callToolViaGatewayWithAgent()` is a convenience wrapper that attaches the calling agent's `nodeId`, `runId`, variables, and metadata so the receiving agent has full context about who is calling and why.

The gateway also exposes `POST /a2a/invoke` for agent-to-agent routing where the target server and tool are specified in the request body.

For a complete gateway capability breakdown and configuration examples, see [Network Gateway](/docs/gateway) and the [Gateway Config Reference](/docs/reference/gateway-config).

## Agent State

Agent state is the canonical runtime context that flows through every hop. It carries the executing `nodeId`, a `runId` reference for correlation, and scoped variables/metadata that downstream hops can use for contextual policy enforcement.

When crossing process/network boundaries, agent state is transported via three canonical headers:

* `x-node-id`
* `x-agent-ref`
* `x-agent-state`

For the full schema, encoding/decoding utilities, and analytics conventions, see [Agent State](/docs/agent-state).

## Policy

Sec0 policies are YAML documents that define runtime governance controls: tool allowlists, scanning, privacy/retention, side-effects, and enforcement behavior. Policies can be loaded locally or fetched dynamically, and can be scoped per agent (`nodeId`).

Start in observe mode (`enforcement.deny_on: []`) and progressively enable enforcement by adding `deny_on` reasons and optional `escalate_on` reasons for escalation workflows.

See the [Policy Guide](/docs/policy) and the [Policy Schema Reference](/docs/reference/policy-schema).

## Audit Trail

Every hop emits a signed audit envelope (append-only NDJSON) containing trace/span context, hop identity, policy decision, and integrity hashes. This yields an end-to-end custody chain across your runtime graph.

See [Audit & Custody](/docs/audit) for envelope schema, file layout, and uploads.
