# Agent Session Flow

This document details the complete lifecycle of an AI Agent interacting with external resources through the zkMe Agent Trust Gateway. It outlines the step-by-step process of how an agent establishes trust, receives authorization, executes its task, and logs the outcome.

## The 8-Step Session Lifecycle

A typical Agent Session involves four key entities: the **Agent** (the autonomous actor), the **zkMe Agent Trust Gateway** (running in a secure TEE), the **User’s SSI Wallet** (managing policies and credentials), and the **Target Resource** (e.g., an API, a smart contract, or a DeFi protocol).

The flow ensures that the Agent can execute its tasks seamlessly while the User retains absolute control and visibility over their identity and assets.

```mermaid
sequenceDiagram
    participant Agent as AI Agent
    participant Gateway as Agent Trust Gateway (TEE)
    participant Wallet as User SSI Wallet
    participant Target as Target Resource (API/Contract)

    Agent->>Gateway: 1. Session Initiation (DID, Payload, Credential)
    activate Gateway
    Gateway->>Gateway: 2. TEE Ingress & Agent Auth
    Gateway->>Gateway: 3. Credential Verification
    Gateway->>Gateway: 4. Policy Engine Evaluation

    alt High Risk / Requires Manual Approval
        Gateway->>Wallet: 5a. Push Notification (Request Details)
        activate Wallet
        Wallet-->>Gateway: 5b. User Signed Authorization
        deactivate Wallet
    else Low Risk / Auto-Approved
        Gateway->>Gateway: 5c. Proceed automatically
    end

    Gateway->>Gateway: 6. Context Provisioning (Generate Token/ZKP)
    Gateway->>Target: 7a. Proxy Request (with Token/ZKP)
    activate Target
    Target-->>Gateway: 7b. Execution Result
    deactivate Target

    Gateway->>Gateway: 8a. Anchor Audit Hash to Ledger
    Gateway-->>Agent: 8b. Return Result
    deactivate Gateway
```

{% stepper %}
{% step %}

#### **Session Initiation**

The process begins when the Agent determines it needs to access a protected resource to fulfill a user prompt (e.g., “Swap 100 USDC for ETH on Uniswap”). The Agent initiates a connection to the Gateway via a supported protocol, such as an MCP JSON-RPC call.

The initial request payload includes:

* **Agent Identifier:** The Agent’s DID or verifiable identity.
* **Target Resource:** The specific URI, API endpoint, or smart contract address.
* **Action Payload:** The intended action parameters (e.g., the specific trade details).
* **Delegated Credential:** The Agent-Ready Credential previously delegated by the user, proving the Agent has the right to act on the user’s behalf.
  {% endstep %}

{% step %}

#### **TEE Ingress & Authentication**

The request enters the Gateway’s hardware-secured Trusted Execution Environment (TEE). This ensures that the evaluation process cannot be tampered with by the host system or external attackers.

Inside the TEE, the Gateway first authenticates the Agent by verifying the cryptographic signature on the request against the Agent’s DID document, ensuring the request genuinely originated from the claimed Agent.
{% endstep %}

{% step %}

#### **Credential Verification**

Once the Agent is authenticated, the Gateway verifies the provided Agent-Ready Credential within the secure enclave. This involves a rigorous cryptographic check:

* **Signature Validation:** Ensuring the credential was issued by a trusted entity and has not been forged.
* **Revocation Check:** Querying the blockchain state to confirm that neither the delegated credential nor the underlying primary credential has been revoked by the user or the issuer.
* **Expiration Check:** Validating that the credential is still within its active validity period.
  {% endstep %}

{% step %}

#### **Policy Engine Evaluation**

With a verified credential, the Gateway passes the request to the Policy Engine. The Policy Engine evaluates the intended action against the User’s predefined, granular policies stored securely in the zkVault.

The evaluation includes:

* **Context Check:** Is this specific Agent authorized to access this specific Target Resource?
* **Scope Check:** Does the action fall within the permitted boundaries? (e.g., “Is the trade value under the $500 daily limit?”, “Is the transaction frequency within the allowed rate?”).
* **Risk Scoring:** The Gateway calculates a dynamic risk score based on the action type, the target’s reputation, and historical context.
  {% endstep %}

{% step %}

#### **Human-in-the-Loop Authorization (Conditional)**

The Gateway employs a dynamic authorization model. If the request passes all policy checks and the risk score is low, it proceeds automatically. However, if the risk score exceeds a predefined threshold, or if the user’s policy explicitly requires manual approval for specific actions (e.g., “Always ask before transferring assets over $1000”), the Gateway pauses the automated session.

* **Secure Notification:** The Gateway sends a secure, encrypted push notification directly to the User’s SSI Wallet app.
* **User Review:** The User reviews the exact details of the requested action on their device.
* **Cryptographic Approval:** The User signs an authorization transaction using their private key, which is then routed back to the Gateway to resume the session. If denied, the session is terminated.
  {% endstep %}

{% step %}

#### **Context Provisioning & Token Issuance**

Once fully authorized, either automatically via the Policy Engine or manually by the User, the Gateway prepares the necessary context for the Agent to interact with the Target Resource.

* **For Web2 APIs:** The Gateway may inject a short-lived, strictly scoped authorization token (such as a PASETO or JWT) into the request headers. This token is generated inside the TEE and is valid only for this specific session and target.
* **For Web3 Smart Contracts:** If the target requires a Zero-Knowledge Proof (ZKP), the Gateway triggers the generation of the necessary proof based on the verified credentials, acting as a secure prover on behalf of the user.
  {% endstep %}

{% step %}

#### **Execution Proxying**

The Gateway acts as a secure proxy, forwarding the authorized, context-enriched request to the Target Resource.

The Target Resource processes the request. Because the request comes through the trusted Gateway (often verified via TLS or cryptographic attestation), the Target Resource can trust that the action has been fully vetted and authorized according to the user’s strict policies, without needing to perform complex identity verification itself. The Target Resource then returns the execution result to the Gateway.
{% endstep %}

{% step %}

#### **Egress & Audit Logging**

In the final step, the Gateway forwards the execution result back to the Agent, completing the operational loop.

Simultaneously, the Gateway generates a cryptographic hash of the session metadata. This metadata includes the Agent DID, a timestamp, the specific policy ID that authorized the action, a hash of the action payload, and the final result status. This hash is anchored to an immutable decentralized ledger.

This creates a verifiable, tamper-proof audit trail of the agent’s activity without exposing the sensitive payload data or user PII to the public blockchain.
{% endstep %}
{% endstepper %}

***

## Error Handling & Edge Cases

During the session lifecycle, various checks may fail. The Gateway is designed to fail securely and return structured error responses to the Agent, enabling it to diagnose the failure and decide whether to retry, escalate to the user, or abort the session.

<table><thead><tr><th width="181.025390625">Failure Point</th><th width="201.751953125">Trigger Condition</th><th width="169.091796875">Gateway Action</th><th>Error Type</th></tr></thead><tbody><tr><td><strong>Step 2: Auth</strong></td><td>Agent signature is invalid or DID is not resolvable.</td><td>Drop request immediately.</td><td>Authentication Error</td></tr><tr><td><strong>Step 3: Verification</strong></td><td>Credential is expired, revoked, or signature is invalid.</td><td>Reject request, log failure.</td><td>Credential Validation Error</td></tr><tr><td><strong>Step 4: Policy</strong></td><td>Action exceeds value limit or targets an unauthorized resource.</td><td>Reject request, log policy violation.</td><td>Policy Violation Error</td></tr><tr><td><strong>Step 5: Human Auth</strong></td><td>User actively rejects the request in their SSI Wallet.</td><td>Terminate session, log user denial.</td><td>User Denial Error</td></tr><tr><td><strong>Step 5: Human Auth</strong></td><td>User does not respond within the session timeout window.</td><td>Terminate session, log timeout.</td><td>Session Timeout Error</td></tr><tr><td><strong>Step 7: Execution</strong></td><td>Target Resource is down or returns an error.</td><td>Pass error back to Agent, log failure.</td><td>Upstream Execution Error</td></tr></tbody></table>

***

## Session Security Guarantees

The 8-step flow is designed to provide several critical security guarantees for the Agent Economy:

* **No Credential Leakage:** The Agent never possesses the raw user credentials or private keys. It only holds a delegated proxy credential, and all sensitive evaluation happens inside the Gateway’s TEE.
* **No Policy Bypass:** Because policy evaluation occurs inside a hardware-secured enclave, the Agent cannot alter, bypass, or trick the rules set by the user.
* **Ephemeral Access:** Any authorization tokens issued during the session are strictly scoped to the specific target resource and expire immediately after use, minimizing the blast radius if an agent is compromised.
* **Non-Repudiation:** The immutable audit logs ensure that both the Agent’s actions and the User’s authorizations (or policy configurations) are cryptographically recorded and undeniable, providing clear accountability in autonomous systems.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.zk.me/hub/how-built/agent-trust-gateway/agent-session-flow.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
