# Introduction

{% hint style="info" %}
Treza is the node editor for generative media. Chain the best video, image, and language models into a pipeline on a visual canvas, run it from a prompt, then publish it behind one API.
{% endhint %}

***

## What is Treza?

Treza turns one prompt into video, images, and text. You build a workflow by wiring models, tools, and guardrails together as nodes on a drag-and-drop canvas, with no glue code between the pieces.

Every pipeline becomes a versioned HTTP endpoint you can call from your product, your scripts, or an AI agent, either with the typed `/invoke` API or an OpenAI-compatible `/chat/completions` drop-in.

***

## Why teams use Treza

* **Every modality on one canvas.** Video with Veo 3.1 and Sora 2, images with Gemini image models, and text with open models like Llama, DeepSeek, and Qwen, plus transcription and embeddings. Pick a model per node and change it any time.
* **No lock-in.** Models run through an OpenAI-compatible backend across providers like Together, OpenRouter, Fireworks, and DeepSeek. Not listed? Type any Hugging Face or OpenRouter model id straight into the node. Bring your own provider keys, stored encrypted.
* **One API, two ways to call it.** Every published pipeline gets a versioned endpoint. Use the typed `/invoke` API for JSON in and JSON out, or point any OpenAI SDK at the `/chat/completions` endpoint, streaming included.
* **Guardrails when you want them.** Drop redaction, PII, and conditional-routing nodes into any pipeline so sensitive data is handled before it reaches a model or an external system.
* **Team and Enterprise plans available.**
* **Production-ready.** Automatic retries and fallback models, a KMS-encrypted secrets manager, and hardware-attested Treza Enclaves on Enterprise, with provable evidence that the right code handled your data.

***

## Start here

* [**Concepts**](/getting-started/concepts) - pipelines, nodes, models, runs, and published endpoints.
* [**Build your first pipeline**](/pipelines/quickstart) - go from a prompt to a published API in a few minutes.
* [**Models**](/pipelines/models) - the model catalog and how to use any model id.
* [**Pipeline API**](/api/pipeline-api) - call a published pipeline over HTTP.

***

## Build with Treza

* [**Pipeline API**](/api/pipeline-api) - the typed `/invoke` and OpenAI-compatible `/chat/completions` endpoints on every published pipeline.
* [**AI Gateway**](/ai-gateway/ai-control-plane) - the redaction gateway that also powers the PII guardrail node.

***

![Build with Treza - one prompt into video, images, and text behind one API](/files/ScIrqkTsJPVVHEkBZE1v)

### Links

* [Website](https://trezalabs.com)
* [Platform](https://trezalabs.com)
* [Documentation](https://docs.trezalabs.com)
* [Twitter](https://twitter.com/trezalabs)
* [Telegram](https://t.me/trezalabs)

***


# Concepts

The core of Treza is the **pipeline**: a graph of nodes that turns inputs into generated media. Everything else, from the visual editor to the published API, is built around it. Start with the concepts below, then move on to the advanced and enterprise building blocks further down the page.

***

### Pipelines

#### What they are

A pipeline is a directed graph of nodes that you build on the visual canvas. Data flows along the edges from one node to the next: an input becomes a prompt, a prompt becomes a video, a video gets a caption. A pipeline has a **draft** you edit and, once you publish, a versioned **published** snapshot that serves API traffic.

#### Core ideas

* **Draft vs. published.** You edit the draft freely. Publishing takes a snapshot and assigns it a version number. API calls always run the published snapshot, never your in-progress draft.
* **Contract.** Treza derives an input/output contract from your input and output nodes. The input keys you send to the API, and the output keys you get back, come from this contract.
* **Ownership.** Pipelines and API keys are scoped to your account. A key can only invoke pipelines owned by the same account.

#### Typical flow

1. Start from a prompt or a template on the canvas.
2. Wire nodes together and run the pipeline to test it.
3. Publish to get a versioned endpoint.
4. Call the endpoint from your product, scripts, or an agent.

***

### Nodes

#### What they are

Nodes are the building blocks on the canvas. Each node does one job and passes its output to the next. You add them from the palette and connect them by dragging edges.

#### Common node types

* **Input** - the entry point that accepts a value from the editor or an API call.
* **Model / generation** - video, image, language, audio, or embedding models. Pick a model per node.
* **Prompt / transform** - reshape text between steps, for example refining a brief into a shot prompt.
* **Guardrail** - redaction, PII, and conditional-routing nodes that handle sensitive data before it reaches a model or an external system.
* **Output** - the value returned by the pipeline. Output nodes define the response contract.

***

### Models

#### What they are

Every generation node runs a model. Treza reaches models through an OpenAI-compatible backend spanning providers like Together, OpenRouter, Fireworks, and DeepSeek, so you are never tied to one vendor.

#### Core ideas

* **One model per node**, changeable at any time with no rewrites.
* **Any model id.** Pick from the catalog or type any Hugging Face or OpenRouter model id straight into the node.
* **Bring your own keys.** Provider keys are stored encrypted and used server-side.

See the [Models](/pipelines/models) page for the catalog and the [Secrets](#secrets) concept for provider keys.

***

### Runs & versions

#### What they are

A **run** is a single execution of a pipeline, whether triggered from the editor or over the API. Every run is recorded with per-node timing, token counts, cost, and status.

#### Core ideas

* **Run history.** Inspect any run node by node to see exactly how a prompt became an output. Filter by trigger (editor vs. API).
* **Versioning.** Each publish creates a new version. You can roll back to an earlier version at any time.
* **Export.** Export run history for SOC 2, HIPAA, or an internal audit.

***

### Published endpoints & API keys

#### What they are

Publishing a pipeline exposes it as a versioned HTTP endpoint under `https://trezalabs.com/api/pipelines/<id>`. You authenticate with a Treza API key (`treza_live_...`), created on the **API keys** page and sent as a bearer token.

#### Two ways to call it

* **Typed** - `POST /api/pipelines/<id>/invoke` with `{ "inputs": { ... } }` returns a `runId`; poll `GET .../invoke?runId=...` for JSON keyed by the output contract.
* **OpenAI-compatible** - `POST /api/pipelines/<id>/chat/completions`, a drop-in for any OpenAI SDK, streaming included.

See the [Pipeline API](/api/pipeline-api) reference for full request and response shapes.

***

### Guardrails

#### What they are

Guardrail nodes handle sensitive data inside a pipeline. The redaction and PII nodes strip personal data before it reaches a model or an external system; conditional-routing nodes branch the graph based on the data.

The same redaction engine is also available as a standalone OpenAI-compatible gateway. See the [AI Gateway](/ai-gateway/ai-control-plane) for details.

***

### Secrets

#### What they are

The secrets manager stores provider API keys and other credentials your nodes need. Values are envelope-encrypted with KMS at rest, never returned by any API, and injected server-side at run time, so your pipeline can call a provider without your application handling the key.

***

### Billing & credits

#### What it is

Treza is **prepaid credits**, with no subscription and no recurring charge. You buy a credit pack once (starting at $10), and credits are spent as your pipelines run models. Only successful runs are charged. New accounts start with $5 in free credits, and credits never expire. Track your balance and spend in billing settings.

Enterprise adds dedicated Treza Enclaves, SSO, and postpaid invoicing. See [Plans & Pricing](/ai-gateway/plans-and-pricing).

***

## Advanced & Enterprise

The building blocks below power guardrails, hardware-attested execution, key management, and on-chain verification. Most pipelines never touch them directly, but they are available when you need hardware isolation, cryptographic attestation, or zero-knowledge identity.

***

### Providers

#### What they are

Backends capable of running secure enclaves. AWS Nitro Enclaves is the provider available today (additional providers are on the roadmap). Providers expose supported regions and a config schema (e.g., dockerImage, cpuCount, memoryMiB).

#### Why it matters

Each provider has different runtime limits, compliance certifications, and regional availability. You pick one and pass provider-specific providerConfig when creating an enclave.

#### Key objects & calls

* getProviders() → list all available providers, regions, and config schemas
* getProvider(providerId) → fetch details for a specific provider
* providerConfig → per-provider runtime settings (validated against schema)

#### Typical flow

1. List providers → choose one based on your compliance/region needs
2. Read provider's configSchema → understand required fields
3. Validate your config against schema
4. Create enclave with providerId + providerConfig

***

### Enclaves

#### What they are

Isolated, attested compute environments that run your container image in a hardware-protected enclave. They provide cryptographically verifiable isolation from cloud operators and other tenants.

#### Core ideas

* Creation: You provide providerId, region, providerConfig (e.g., Docker image + resources), and a sourceType (registry, private-registry, or github)
* Ownership: All resources are scoped to your wallet address
* Integration: Optionally link a GitHub repo/branch — Treza builds the image for you
* Attestation: Every deployed enclave can generate cryptographic proof of its integrity

#### Key objects & calls

* createEnclave(request) → deploy a new enclave
* getEnclave(enclaveId) → fetch enclave details and status
* getEnclaves(walletAddress) → list all your enclaves
* updateEnclave(request) → modify configuration or GitHub connection
* deleteEnclave(enclaveId, walletAddress) → permanently remove
* getEnclaveLogs(enclaveId, logType, limit) → fetch logs

#### What runs inside

Your Docker image (from a public registry, a private registry, or built from your GitHub repository and pushed to ECR) plus environment variables you configure through your provider's settings.

#### When to use

* Running sensitive computations that require hardware-level isolation
* Processing confidential data (PII, healthcare, financial)
* Building zero-trust applications with cryptographic verification
* Multi-party computation scenarios

***

### Lifecycle

#### What it is

The operational state machine that manages enclave deployment, operation, and teardown.

#### States

Build Flow (GitHub-sourced enclaves only):

* PENDING\_BUILD → build queued
* BUILDING → CodeBuild is building the image from your repo
* BUILD\_FAILED → build error (see Build logs)

Deployment Flow:

* PENDING\_DEPLOY → awaiting deployment initiation
* DEPLOYING → infrastructure provisioning in progress
* DEPLOYED → enclave is running and ready

Pause/Resume Flow:

* PAUSING → stopping compute resources
* PAUSED → enclave suspended, no compute costs
* RESUMING → restarting from paused state
* DEPLOYED → back to running state

Termination Flow:

* PENDING\_DESTROY → awaiting termination initiation
* DESTROYING → infrastructure teardown in progress
* DESTROYED → final state — enclave removed, resources freed (irreversible)

Error State:

* FAILED → deployment or operation error (see error\_message)

#### Actions

* pauseEnclave(enclaveId, walletAddress) → stop compute without destroying
* resumeEnclave(enclaveId, walletAddress) → restart a paused enclave
* terminateEnclave(enclaveId, walletAddress) → permanently destroy (irreversible)

#### When to use what

| Action    | Use When                                      | Result                                    |
| --------- | --------------------------------------------- | ----------------------------------------- |
| Pause     | Stop spending temporarily; keep configuration | No compute costs, quick restart           |
| Resume    | Bring paused enclave back online              | Returns to DEPLOYED state                 |
| Terminate | Done with enclave permanently                 | All data destroyed, cannot undo           |
| Delete    | Remove enclave record completely              | Enclave must be DESTROYED or FAILED first |

***

### Attestation & Verification

#### What it is

Cryptographic proof that your enclave is running genuine, unmodified code inside a hardware-protected secure enclave. Uses Platform Configuration Registers (PCRs), certificate chains, and signed attestation documents.

#### Why it matters

Allows you and third parties to verify:

* The exact code running in your enclave (via PCR measurements)
* The enclave is running in genuine AWS Nitro hardware
* No tampering has occurred since deployment
* Compliance with security standards (FIPS 140-2, SOC2, HIPAA, etc.)

#### Key concepts

**PCR Measurements**

Hardware-generated cryptographic hashes:

* PCR0: Hash of the enclave image file
* PCR1: Linux kernel and bootstrap hash
* PCR2: Application/container hash
* PCR8: Signing certificate hash

**Attestation Document**

Contains:

* PCR measurements
* X.509 certificate for verification
* Certificate authority bundle
* Timestamp and module ID
* Optional user data and nonce for replay protection

**Verification Details**

* Trust Level: HIGH, MEDIUM, LOW, or UNKNOWN
* Integrity Score: 0-100% confidence rating
* Verification Status: VERIFIED, PENDING, or FAILED
* Compliance Checks: SOC2, HIPAA, FIPS 140-2, Common Criteria
* Risk Score: Lower is better (0-100)

#### Key objects & calls

* getAttestation(enclaveId) → retrieve attestation document + verification details
* getVerificationStatus(enclaveId) → quick status check
* verifyAttestation(enclaveId, request?) → comprehensive verification with checks
* generateIntegrationSnippet(enclaveId, language) → code for third-party verification

#### Typical flow

1. Deploy enclave → wait for DEPLOYED status
2. Call getAttestation(enclaveId) → get attestation document
3. Share verification URL with third parties
4. Third parties call verification endpoint with optional nonce
5. Receive trust level, PCR hashes, and compliance status

#### When to use

* Before processing sensitive data: Verify enclave integrity first
* Compliance audits: Provide cryptographic proof of secure execution
* Multi-party scenarios: Let partners verify your enclave independently
* Zero-trust architectures: Continuously verify, never trust blindly
* Integration with external systems: Provide verification endpoints to partners

#### What you get

```json
{
  "attestationDocument": {
    "pcrs": {
      "0": "abc123...",
      "1": "def456...",
      "2": "ghi789...",
      "8": "jkl012..."
    },
    "certificate": "-----BEGIN CERTIFICATE-----...",
    "timestamp": 1234567890,
    "moduleId": "i-abc123..."
  },
  "verification": {
    "trustLevel": "HIGH",
    "verificationStatus": "VERIFIED",
    "integrityScore": 95
  },
  "endpoints": {
    "verificationUrl": "https://trezalabs.com/api/enclaves/{id}/attestation/verify",
    "apiEndpoint": "https://trezalabs.com/api/enclaves/{id}/attestation",
    "webhookUrl": "https://trezalabs.com/webhooks/attestation/{id}"
  }
}
```

***

### Tasks

#### What they are

Scheduled operations that run inside your enclaves. Tasks use cron expressions for flexible scheduling and can automate recurring workloads.

#### Core ideas

* Scheduling: Cron-style expressions (e.g., 0 0 \* \* \* for daily at midnight)
* Association: Each task is linked to a specific enclave
* Ownership: Scoped to your wallet address
* Execution tracking: History of runs with timestamps

#### States

* running → task is active and executing on schedule
* stopped → task is paused, not executing
* failed → last execution encountered an error
* pending → task created but not yet started

#### Key objects & calls

* createTask(request) → create new scheduled task
* getTasks(walletAddress) → list all your tasks
* updateTask(request) → modify schedule, status, or configuration
* deleteTask(taskId, walletAddress) → remove task

#### Typical flow

1. Create enclave → wait for DEPLOYED status
2. Create task with enclaveId, schedule, and description
3. Task runs automatically on schedule
4. Monitor via lastRun timestamp and status
5. Update status: 'stopped' to pause execution

#### When to use

* Batch processing: Run data processing jobs nightly
* Health checks: Periodic monitoring and alerts
* Data synchronization: Regular backups or sync operations
* Scheduled maintenance: Cleanup, archival, or rotation tasks
* Report generation: Daily/weekly/monthly automated reports

#### What you need

```json
{
  name: "Risk Assessment",
  description: "Calculate portfolio risk metrics every 6 hours",
  enclaveId: "enc_abc123",
  schedule: "0 */6 * * *",  // Every 6 hours
  walletAddress: "0x4B0897b0513fdc7C541B6d9D7E929C4e5364D2dB"
}
```

***

### Logs & Monitoring

#### What it is

Comprehensive logging system aggregating logs from multiple sources across your enclave lifecycle.

#### Log sources

**Application Logs**

Stdout/stderr from your Docker container. View what your application prints.

**ECS Deployment Logs**

AWS ECS service logs showing infrastructure-level events (task starting, stopping, health checks).

**Step Functions Logs**

Workflow orchestration logs from deployment/termination state machines.

**Lambda Logs**

Execution logs from trigger functions, validators, and error handlers.

**Build Logs**

CodeBuild output for GitHub-sourced enclaves (clone → build → push to ECR).

**Error Logs**

Aggregated errors from all sources for quick troubleshooting.

#### Key objects & calls

* getEnclaveLogs(enclaveId, logType, limit) → fetch logs
* logType: 'all', 'application', 'ecs', 'stepfunctions', 'lambda', 'build', 'errors'
* limit: max entries to return (default 100)

#### Log structure

```json
{
  timestamp: 1234567890,
  message: "Application started",
  source: "application",     // or "ecs", "stepfunctions", "lambda"
  stream: "stdout",
  logGroup: "/aws/ecs/...",
  type: "application"
}
```

#### When to use what

| Log Type      | Use When                                       |
| ------------- | ---------------------------------------------- |
| application   | Debugging your container code                  |
| ecs           | Infrastructure issues (deployment failures)    |
| stepfunctions | Understanding workflow state transitions       |
| lambda        | Troubleshooting triggers or validators         |
| build         | Following GitHub builds (clone → build → push) |
| errors        | Quick overview of all problems                 |
| all           | Comprehensive investigation across all sources |

#### Typical flow

1. Enclave enters FAILED or unexpected state
2. Call getEnclaveLogs(enclaveId, 'errors', 50)
3. Identify error source
4. Call specific log type for detailed context
5. Fix issue and redeploy

***

### API Keys & Authentication

#### What they are

Programmatic access credentials for using the Treza SDK. API keys provide scoped permissions and are tied to your wallet address.

#### Why it matters

Enables CI/CD pipelines, automation scripts, and third-party integrations to manage your enclaves without manual UI interaction.

#### Permission scopes

* enclaves:read → list and view enclave details
* enclaves:write → create, update, delete, pause, resume, terminate enclaves
* tasks:read → view tasks and execution history
* tasks:write → create, update, delete tasks
* logs:read → access logs from all sources

#### Key objects & calls

* createApiKey(request) → generate new API key (key shown once!)
* getApiKeys(walletAddress) → list your API keys
* updateApiKey(request) → change permissions or status
* deleteApiKey(apiKeyId, walletAddress) → revoke access

#### States

* active → key is valid and can authenticate requests
* inactive → key is disabled but not deleted (can be reactivated)

#### When to use

* CI/CD pipelines: Automate deployments from GitHub Actions, GitLab CI
* Infrastructure as Code: Manage enclaves with Terraform or Pulumi
* Monitoring systems: Automated health checks and log retrieval
* Multi-user scenarios: Different keys for different team members/systems
* Security rotation: Regular key rotation without affecting other systems

#### Best practices

```typescript
// Create limited-scope keys
const readOnlyKey = await client.createApiKey({
  name: "Monitoring Bot",
  permissions: ['enclaves:read', 'logs:read'],
  walletAddress: myWallet
});

// Production key with full access
const prodKey = await client.createApiKey({
  name: "Production Deploy",
  permissions: ['enclaves:read', 'enclaves:write', 'logs:read'],
  walletAddress: myWallet
});
```

***

### GitHub Integration

#### What it is

OAuth-based connection linking your enclaves to GitHub repositories and branches. Treza clones the selected repo and branch, builds the Docker image with AWS CodeBuild, and pushes it to a private ECR repository — no local Docker tooling required.

#### Core ideas

* OAuth flow: Secure authentication with GitHub (repo and read:user scopes)
* Repository linking: Connect specific repos to enclaves
* Branch selection: Choose which branch to build from (defaults to main)
* Token management: Access tokens are stored in AWS Secrets Manager for the duration of the build, then deleted

#### Key objects & calls

* getGitHubAuthUrl(state?) → start OAuth flow, get authorization URL
* exchangeGitHubCode(request) → exchange OAuth code for access token
* getGitHubRepositories(accessToken) → list user's repos
* getRepositoryBranches(request) → list branches for a repo
* updateEnclave({ githubConnection }) → link GitHub to enclave

#### GitHub connection object

```json
{
  isConnected: true,
  username: "yourusername",
  selectedRepo: "owner/repo-name",
  selectedBranch: "main",
  accessToken: "encrypted..."  // Never exposed to client
}
```

#### Typical flow

1. User initiates GitHub connection in UI
2. Call getGitHubAuthUrl() → redirect user to GitHub
3. User authorizes → GitHub redirects with code
4. Call exchangeGitHubCode({ code }) → get access\_token and user info
5. Call getGitHubRepositories(access\_token) → show user their repos
6. User selects repo → call getRepositoryBranches() → show branches
7. User selects branch → call updateEnclave() with githubConnection

#### When to use

* Managed builds: Deploy straight from source — Treza builds the image for you
* Development workflows: Feature branch → ephemeral test enclave
* Team collaboration: Share enclave configs via Git
* Version tracking: Each build is tagged with the enclave ID and branch
* Private repositories: Build from private repos without exposing credentials

***

### Docker Images

#### What they are

Container images that define your enclave's runtime environment. Treza supports public Docker Hub images, private registries, and ECR.

#### Why it matters

Your enclave runs whatever's in the Docker image. The image contains your application code, dependencies, runtime, and configuration.

#### Key concepts

* Image names: library/hello-world, nginx:latest, myorg/myapp:v1.2.3
* Tags: Version identifiers (:latest, :v1.0, :sha-abc123)
* Registries: Docker Hub (public), ECR (private AWS), custom registries

#### Key objects & calls

* searchDockerImages(query) → search Docker Hub for images
* getDockerTags(repository) → list available tags for an image

#### In provider config

```json
{
  dockerImage: "library/hello-world:latest"  // Public image
}

// or

{
  dockerImage: "123456789.dkr.ecr.us-west-2.amazonaws.com/myapp:v1.0"  // Private ECR
}
```

#### When to use what

| Image Type         | Use When                            | Example                                 |
| ------------------ | ----------------------------------- | --------------------------------------- |
| Public Docker Hub  | Testing, demos, open-source tools   | nginx:alpine                            |
| Private Docker Hub | Your proprietary apps (small teams) | yourorg/app:latest                      |
| AWS ECR            | Production workloads, enterprise    | 123.dkr.ecr.region.amazonaws.com/app:v1 |
| Custom registry    | On-prem, air-gapped environments    | registry.internal.com/app               |

#### Best practices

```typescript
// ✅ Good: Specific version tag
dockerImage: "postgres:15.2-alpine"

// ⚠️ Risky: Latest tag (changes without notice)
dockerImage: "postgres:latest"

// ✅ Good: Semantic versioning
dockerImage: "myapp:v1.2.3"

// ❌ Not supported: digest references (@sha256:...) are rejected by image URI validation
dockerImage: "postgres@sha256:abc123..."
```

***

### AI Control Plane (PII Redaction Proxy)

#### What it is

An OpenAI-compatible proxy that strips PII from your LLM traffic before it reaches the model provider. Your agents send chat completions to a Treza proxy endpoint instead of the provider directly; Treza redacts sensitive entities, forwards the request upstream, and returns the response.

#### Core ideas

* Proxies: Customer-configured redaction endpoints. Each proxy points at an upstream provider (openai, azure-openai, anthropic, or custom) and carries a redaction policy. Select one per request via the x-treza-proxy header.
* Redaction policy: Which PII entity types to strip (NAME, EMAIL, PHONE, ADDRESS, SSN, CC, MRN, DOB, ACCOUNT, URL, DATE, SECRET). Custom policies are plan-gated.
* Upstream keys: Send your provider API key per-request (x-model-key header) or store it KMS-encrypted on the proxy and let Treza use it server-side.
* TEE redaction: On Enterprise, redaction runs inside a Treza Nitro Enclave with hardware attestation; lower tiers use managed software redaction.
* Audit trail: Every redaction request is written to an audit log (export is plan-gated).

#### Key objects & calls

* POST /api/redact/chat/completions → OpenAI-compatible chat endpoint with redaction applied
* POST /api/redact/run → redact a raw text string, returns detected entities
* GET /api/redact/attest → fetch enclave attestation for the redaction pipeline (Enterprise)
* /api/proxies → create, list, update, and delete redaction proxies

#### Typical flow

1. Create a proxy → choose upstream provider and redaction policy
2. Point your agent's base URL at the Treza proxy endpoint
3. Treza redacts PII → forwards to the model → returns the response
4. Review usage and the audit log in the control plane

#### When to use

* Routing LLM traffic that may contain customer PII
* Compliance regimes (HIPAA, GDPR) where prompts can't leave with raw identifiers
* Adding redaction to existing OpenAI-based agents with only a base-URL change

Learn more: [AI Control Plane](/ai-gateway/ai-control-plane)

***

### Plans & Billing

#### What it is

Prepaid credits, with no subscription. You buy credit packs once through Stripe, and your balance is drawn down as pipelines run models.

#### Credit packs

| Price | Credits added | Bonus |
| ----- | ------------- | ----- |
| $10   | $10           | -     |
| $25   | $25           | -     |
| $50   | $52.50        | +5%   |

#### Core ideas

* No subscription: you pay for credits once, not on a recurring basis.
* Model usage: credits are spent as your pipelines run models. Only successful runs are charged.
* Free to start: new accounts begin with $5 in free credits, and credits never expire.
* Enterprise: dedicated enclaves, SSO, and postpaid invoicing instead of prepaid credits.

#### When to use what

Credit packs for everything from first prototype to production pipelines. Enterprise when you need hardware-attested execution, SSO, or invoicing on net terms.

Learn more: [Plans & Pricing](/ai-gateway/plans-and-pricing)

***

### Signers & Key Management

#### What they are

Pluggable signing strategies that decouple transaction signing from private key storage. Instead of storing raw private keys in environment variables or configuration files, you choose a SignerProvider that matches your security requirements. The SDK ships with three built-in signers: EnclaveSigner (production), LocalSigner (development), and BrowserWalletSigner (client-side).

#### Why it matters

* Key isolation: In production, private keys are generated and stored inside Treza Nitro Enclaves. They never leave the hardware-isolated TEE boundary.
* Attestation-backed signing: Before each signing operation, the EnclaveSigner can cryptographically verify that the enclave hasn't been tampered with.
* Flexibility: Swap between enclave, local, or browser wallet signing with a single config change -- same SDK code, different security posture.
* No PII exposure: Private keys never appear in logs, environment variables, or configuration files in production.
* Compliance: Hardware-isolated key management satisfies requirements for SOC2, FIPS 140-2, and financial services regulations.

#### Core ideas

SignerProviderInterface that all signers implement. Defines two methods: getSigner() returns an ethers.js Signer; getAddress() returns the signing address. Any custom key management system (AWS KMS, HashiCorp Vault, hardware wallets) can be integrated by implementing this interface.EnclaveSignerProduction-grade signer that routes signing requests through the Treza Platform API to a Nitro Enclave. The enclave holds the private key in memory-only storage (no persistent disk). Supports attestation verification before signing.LocalSignerDevelopment-only signer that wraps a raw private key string into an ethers.js Wallet. Emits a console warning if used in a production environment. Intended for local development, demos, and automated testing.BrowserWalletSignerClient-side signer that delegates to MetaMask or any injected Web3 wallet (window\.ethereum). Prompts the user to approve each transaction. Suitable for dApp frontends.Signer resolution priorityWhen TrezaKYCClient needs to sign a transaction, it resolves a signer using this priority chain:

1. Explicit signer passed to the method call
2. signerProvider from blockchain config (recommended)
3. Deprecated privateKey from blockchain config (backward compat only)

#### Signing flow (EnclaveSigner)

1. Your app calls submitProofOnChain() or verifyProofOnChain()
2. TrezaKYCClient resolves the signer via signerProvider.getSigner()
3. EnclaveSigner optionally verifies enclave attestation (PCR checks)
4. Unsigned transaction is sent to the enclave via POST /api/enclaves/{id}/sign/transaction
5. Enclave signs the transaction inside the TEE and returns the signed bytes
6. TrezaKYCClient submits the signed transaction to the blockchain
7. Your app receives the transaction hash

#### Key objects & calls

SignerProvider interface

* getSigner(provider?) -- Returns an ethers.js Signer connected to the given provider
* getAddress() -- Returns the signer's Ethereum address
* type -- Human-readable signer type name ('enclave', 'local', 'browser-wallet')

EnclaveSigner

* Constructor: new EnclaveSigner(platformClient, config)
* platformClient -- An authenticated TrezaClient instance
* config.enclaveId -- The enclave ID holding the signing key
* config.verifyAttestation -- Verify enclave integrity before signing (default: true)
* config.attestationNonce -- Optional nonce for replay protection

LocalSigner

* Constructor: new LocalSigner(privateKey)
* privateKey -- Hex-encoded private key (with or without 0x prefix)

BrowserWalletSigner

* Constructor: new BrowserWalletSigner()
* No arguments -- connects to window\.ethereum on first use
* disconnect() -- Clear cached wallet connection

#### When to use what

| Signer                | Environment        | Key Location                      | Attestation | Use Case                            |
| --------------------- | ------------------ | --------------------------------- | ----------- | ----------------------------------- |
| EnclaveSigner         | Production servers | Inside Nitro Enclave (TEE)        | Yes         | Backend services, automated systems |
| LocalSigner           | Local development  | .env file or environment variable | No          | Dev, testing, demos, CI             |
| BrowserWalletSigner   | Client-side dApps  | User's browser wallet             | No          | Frontend applications               |
| Custom SignerProvider | Any                | Your KMS / HSM / Vault            | Optional    | Enterprise, custom infrastructure   |

#### Configuration examples

```typescript
// Production (EnclaveSigner)
import { TrezaClient, TrezaKYCClient, EnclaveSigner } from '@treza/sdk';

const platform = new TrezaClient();
const signer = new EnclaveSigner(platform, {
  enclaveId: process.env.TREZA_ENCLAVE_ID,
  verifyAttestation: true,
});

const client = new TrezaKYCClient({
  apiUrl: process.env.TREZA_API_URL,
  blockchain: {
    rpcUrl: process.env.SEPOLIA_RPC_URL,
    contractAddress: process.env.SEPOLIA_KYC_VERIFIER_ADDRESS,
    signerProvider: signer,
  },
});
```

```typescript
// Custom signer (e.g., AWS KMS)
import { SignerProvider } from '@treza/sdk';
import { ethers } from 'ethers';

class KMSSigner implements SignerProvider {
  readonly type = 'aws-kms';

  async getSigner(provider?: ethers.Provider): Promise<ethers.Signer> {
    // Your KMS signing logic here
  }

  async getAddress(): Promise<string> {
    // Return the address derived from your KMS key
  }
}
```

```typescript
// Client side BrowserWalletSigner
import { TrezaKYCClient, BrowserWalletSigner } from '@treza/sdk';

const client = new TrezaKYCClient({
  apiUrl: 'https://api.trezalabs.com/api',
  blockchain: {
    rpcUrl: 'https://rpc.sepolia.org',
    contractAddress: '0x...',
    signerProvider: new BrowserWalletSigner(),
  },
});
// User will be prompted to connect their wallet on first signing operation
```

#### Best practices

* Always use EnclaveSigner in production -- never store private keys in environment variables, config files, or source code on production servers
* Enable verifyAttestation: true (the default) to cryptographically verify enclave integrity before each signing operation
* Use LocalSigner only for local development and testing; it emits a warning if NODE\_ENV=production
* For CI/CD pipelines, consider a custom SignerProvider that integrates with your secrets manager (AWS KMS, HashiCorp Vault, etc.)
* The deprecated privateKey field in TrezaKYCConfig.blockchain still works for backward compatibility but will be removed in a future major version
* Read-only operations (e.g., isAdult(), getClaims(), hasValidKYC()) don't require a signer at all -- only on-chain write operations need one

#### States

| State                | Description                                        | Can Sign?          |
| -------------------- | -------------------------------------------------- | ------------------ |
| Connected            | Signer resolved and ready                          | Yes                |
| Attestation verified | Enclave integrity confirmed (EnclaveSigner only)   | Yes                |
| Attestation failed   | Enclave integrity check failed                     | No (throws error)  |
| Disconnected         | Browser wallet disconnected or enclave unavailable | No (throws error)  |
| Deprecated           | Using raw privateKey fallback                      | Yes (with warning) |

***

### KYC & Zero-Knowledge Proofs

#### What they are

Privacy-preserving identity verification using zero-knowledge cryptography. Users prove they meet KYC requirements (e.g., age verification, identity checks) without revealing underlying personal data. Proofs are cryptographically verifiable, stored in DynamoDB, and optionally anchored on-chain for immutability.

#### Why it matters

**Privacy**: Users prove attributes (e.g., "I'm over 18") without sharing passport data, birth dates, or photos.

**Compliance**: Satisfy regulatory requirements (KYC/AML) while minimizing PII exposure and data breach risk.

**Portability**: One proof works across multiple services—verify once, use everywhere.

**Auditability**: Blockchain anchoring provides tamper-proof verification history.

**Cost reduction**: Eliminate redundant verification flows and reduce storage of sensitive data.

#### Core ideas

**Zero-Knowledge Proofs (ZK)**

Cryptographic method proving a statement is true without revealing why. Example: "I'm over 18" without sharing your birth date.

**Commitments**

64-character hex hash that binds the prover to specific data without revealing it. Acts as a fingerprint for the proof.

**Public Inputs**

Non-sensitive data visible to verifiers (e.g., commitment hash, proof type). Used to validate the proof without exposing private information.

**Proof Lifecycle**

1. **Generation**: Mobile app or client generates ZK proof from user's credentials
2. **Submission**: Proof submitted to Treza API (POST `/api/kyc/proof`)
3. **Verification**: Cryptographic validation + timestamp checks
4. **Storage**: Proof stored in DynamoDB with metadata
5. **Blockchain**: Optional on-chain submission for immutability
6. **Expiration**: Proofs expire after 7 days (configurable)

#### Key objects & calls

**submitProof(request)** → Submit new ZK proof for verification

Returns: `proofId`, `blockchainProofId`, `verificationUrl`, `expiresAt`, `chainTxHash`

**getProof(proofId, includePrivate?)** → Retrieve proof details

Returns public data by default; use `includePrivate=true` for proof signature (requires auth)

**verifyProof(proofId)** → Verify proof validity and check expiration

Returns: `isValid`, `publicInputs`, `chainVerified`, `expiresAt`

#### Proof structure

```json
{
  commitment: "1234...abcd",           // 64-char hex commitment hash
  proof: "0x1234...9876",              // ZK proof data (min 65 chars)
  publicInputs: ["0xabc...", "0xdef..."], // Public verification data
  timestamp: "2024-12-15T10:30:00Z",   // Must be within 1 hour
  algorithm: "Pedersen-SHA256"         // Cryptographic algorithm
}
```

**For Users (Mobile/Client)**

1. User provides credentials (passport, ID, etc.) to mobile app
2. App generates ZK proof locally using device secure enclave (iOS: Secure Enclave, Android: TEE)
3. Call `submitProof({ userId, proof, deviceInfo })`
4. Receive `proofId` and `verificationUrl`
5. Share `proofId` with services requiring KYC verification

**For Service Providers (Verifiers)**

1. User provides their `proofId` during onboarding
2. Call `verifyProof(proofId)` to check validity
3. Check `isValid`, `chainVerified`, and `expiresAt`
4. Optionally verify on blockchain using `chainTxHash`
5. Grant access based on verification result

**For Developers (Integration)**

1. Generate proof on client-side (mobile/web)
2. Submit to `/api/kyc/proof` endpoint
3. Store returned `proofId` with user account
4. Re-verify periodically using `/api/kyc/proof/{proofId}/verify`
5. Handle expiration by requesting new proof from user

#### When to use

| Scenario                     | Why KYC Proofs Help                                             |
| ---------------------------- | --------------------------------------------------------------- |
| **Age verification**         | Prove age without revealing birth date or ID documents          |
| **Identity checks**          | Verify user identity without storing PII (GDPR/CCPA compliance) |
| **Financial services**       | Meet KYC/AML requirements with minimal data exposure            |
| **Healthcare**               | Verify credentials while maintaining HIPAA compliance           |
| **Multi-platform access**    | One proof works across multiple services/platforms              |
| **Audit requirements**       | Blockchain anchoring provides immutable verification trail      |
| **International compliance** | Satisfy different jurisdictions without data transfer           |

#### Validation rules

**Commitment**

* Must be exactly 64 characters
* Hex format only (0-9, a-f, A-F)
* Unique per user/session

**Proof**

* Minimum 65 characters
* Contains cryptographic signature
* Generated by trusted client (device secure enclave)

**Timestamp**

* Must be within 1 hour of submission
* Prevents replay attacks
* Ensures proof freshness

**Public Inputs**

* Array of hex strings
* Contains non-sensitive verification data
* Minimum 1 input required

#### States

| State      | Description                                              | Queryable          |
| ---------- | -------------------------------------------------------- | ------------------ |
| `verified` | Proof passed cryptographic verification                  | ✅ Yes              |
| `pending`  | Proof submitted, awaiting blockchain confirmation        | ✅ Yes              |
| `failed`   | Verification failed (invalid proof or expired timestamp) | ✅ Yes              |
| `expired`  | Proof passed expiration date (7 days)                    | ❌ Returns HTTP 410 |

#### Integration examples

```typescript
import { TrezaKYCClient } from '@treza/sdk';

const kycClient = new TrezaKYCClient({ apiUrl: 'https://trezalabs.com' });
// Submit proof const result = await kycClient.submitProof({ userId: user.id, proof: zkProof, deviceInfo: { platform: 'web', version: '1.0.0' } });

console.log('Proof ID:', result.proofId); console.log('Verification URL:', result.verificationUrl);
// Verify proof const verification = await kycClient.verifyProof(result.proofId); if (verification.isValid && verification.chainVerified) { console.log('✅ Verified on blockchain'); }Backend Verification

app.post('/onboard', async (req, res) => { 
const { proofId } = req.body;
// Verify proof const result = await fetch( https://trezalabs.com/api/kyc/proof/${proofId}/verify ); const verification = await result.json();

if (!verification.isValid) { 
        return res.status(403).json({ error: 'Invalid KYC proof' }); 
    }
    // Grant access 
    await createUserAccount({ ...userData, kycProofId: proofId }); 
    res.json({ success: true }); 
});

```

* **Privacy-first verification**: Prove attributes without revealing sensitive data
* **Blockchain immutability**: Optional on-chain anchoring for audit trails
* **Automatic expiration**: 7-day validity reduces stale verification risk
* **Device tracking**: Platform and version info for security analysis
* **Flexible verification**: Public endpoints for third-party verification
* **Compliance ready**: GDPR, CCPA, HIPAA-friendly architecture

***

### On-Chain Proof Verification (zkVerify)

#### What it is

Integration with the zkVerify proof-verification chain (via the Horizen Relayer) for verifying ZK proofs on-chain and aggregating them for inexpensive smart-contract verification.

#### Core ideas

* Verification keys: Register a VK once per circuit; reuse the returned vkHash for all subsequent proof submissions
* Proof types: groth16 (default), risc0, ultrahonk, ultraplonk, sp1, ezkl
* Job lifecycle: Queued → Valid → Submitted → IncludedInBlock → Finalized, then AggregationPending → Aggregated → AggregationPublished
* Aggregation: Proofs are batched into a Merkle tree; the aggregation data (Merkle path, domain ID, leaf index, root) lets your smart contract verify the proof via verifyProofAggregation()

#### Key objects & calls

* POST /api/zkverify/register-vk → register a verification key (one-time per circuit)
* POST /api/zkverify/submit-proof → submit proof, publicSignals, and vk (defaults: groth16, Sepolia chainId 11155111)
* GET /api/zkverify/job-status/{jobId} → poll verification job status
* GET /api/zkverify/aggregation/{aggregationId} → fetch aggregation details for on-chain verification

#### Typical flow

1. Register your verification key → store the vkHash
2. Submit a proof → receive a jobId
3. Poll job status until Finalized / Aggregated
4. Fetch aggregation details → verify on-chain in your contract

#### When to use

* Anchoring KYC or compliance proofs on-chain without running your own verifier
* Reducing on-chain verification cost via proof aggregation
* Building smart contracts that consume Treza-issued ZK proofs

Learn more: [zkVerify](https://github.com/treza-labs/treza-docs-site/tree/main/developers/zkverify.md)

***

### zkPassport Verification

#### What it is

Privacy-preserving identity verification from government-issued IDs. Users prove claims about themselves ("I am over 18", "my nationality is X") directly from the NFC chip of their passport or ID card, using zero-knowledge proofs generated on their own phone. No document photos are uploaded, and only the requested claims are revealed.

#### Core ideas

* Server-owned policy: the claim constraints for a verification request are registered with the Treza server before the user scans — the client cannot weaken or modify them
* On-device proving: the ZKPassport mobile app reads the document chip via NFC and generates proofs for exactly the requested claims
* Claim constraints: disclose, gte, gt, lte, lt, eq, in, out, range over fields like age, nationality, birthdate, document\_number
* TEE-attested verification: in production, proof verification runs inside an AWS Nitro Enclave and the result can be wrapped in a hardware-signed attestation document

#### Key objects & calls

* POST /api/zkpassport/request → register a verification request and its claim constraints (server-owned policy)
* POST /api/zkpassport/verify → verify the proofs generated by the user's device, returns an attestation
* GET /api/zkpassport/verify?requestId= → poll the status of a verification request

#### Typical flow

1. Browser creates the request with the ZKPassport SDK → displays a QR code
2. Register the request and its claims with Treza (tamper prevention)
3. User scans the QR code with the ZKPassport app → proofs generated on-device
4. Browser submits the proofs to Treza → verification runs server-side (in a TEE in production)
5. Your app receives an attestation with the claim results

#### When to use

* Age or nationality checks without collecting document data
* KYC onboarding with minimal PII exposure
* Pairing with zkVerify to anchor verification results on-chain

Learn more: [zkPassport](https://github.com/treza-labs/treza-docs-site/tree/main/developers/zkpassport.md)

***

### See Also

* [**Build your first pipeline**](/pipelines/quickstart) → *Go from a prompt to a published API*
* [**Models**](/pipelines/models) → *The model catalog and how to use any model id*
* [**Pipeline API**](/api/pipeline-api) → *Call a published pipeline over HTTP*
* [**Publishing & versioning**](/pipelines/publishing) → *Publish, version, and roll back*
* [**AI Gateway**](/ai-gateway/ai-control-plane) → *The redaction gateway behind the PII guardrail*
* [**Plans & Pricing**](/ai-gateway/plans-and-pricing) → *Pro and Enterprise*

***


# Overview

A **pipeline** is a graph of nodes that turns one prompt into video, images, and text. You build it on a drag-and-drop canvas, wiring models, prompts, and guardrails together with no glue code between the pieces. When it works, you publish it behind one versioned API.

***

## How it works

1. **Start with a prompt.** Type what you want to make, a product video, a campaign image, launch copy, or open a template like Product Demo Video and tweak the brief.
2. **Chain the models.** Wire Veo, Gemini Image, Llama, or any open model together on the canvas. One node refines your brief into a shot prompt, the next renders it. Swap models per node, no rewrites.
3. **Publish behind one API.** Every pipeline becomes a versioned endpoint. Generate from your product, scripts, or agents with the typed `/invoke` API or an OpenAI-compatible streaming endpoint.

***

## What a pipeline is made of

* **Nodes** - the building blocks on the canvas. Input nodes accept values, model nodes generate media, prompt and transform nodes reshape data between steps, guardrail nodes handle sensitive data, and output nodes define the response.
* **Edges** - the connections that pass each node's output to the next.
* **Contract** - the input and output keys, derived from your input and output nodes, that define the pipeline's API surface.
* **Versions** - each publish snapshots the graph and assigns a version number that API traffic runs against.

See [Concepts](/getting-started/concepts) for the full model.

***

## What you can build

* **Video** with Veo 3.1 and Sora 2.
* **Images** with Gemini image models.
* **Text** with open models like Llama, DeepSeek, and Qwen.
* **Audio and embeddings** for transcription and retrieval steps.

Because each generator is a node, a single prompt can drive several modalities in one pipeline: refine a brief, render a clip, draft a caption, and transcribe the result, all in one run.

***

## In this section

* [**Build your first pipeline**](/pipelines/quickstart) - from a prompt to a published API in a few minutes.
* [**Models**](/pipelines/models) - the catalog and how to use any Hugging Face or OpenRouter model id.
* [**Publishing & versioning**](/pipelines/publishing) - publish, version, roll back, and read run history.

For calling a published pipeline from code, see the [Pipeline API](/api/pipeline-api).


# Build your first pipeline

Go from a prompt to a published API in a few minutes. You will build a small pipeline on the canvas, run it, publish it, then call it over HTTP.

***

## Prerequisites

* A Treza account. Sign in at [trezalabs.com](https://trezalabs.com/).
* A few credits for model runs. New accounts start with free credits, and you can top up in billing settings any time. See [Plans & Pricing](/ai-gateway/plans-and-pricing).

***

## 1. Create a pipeline

In the dashboard, open **Pipelines** and create a new pipeline, or start from a template like **Product Demo Video** and tweak it. You land on the canvas with an empty graph.

***

## 2. Add and wire nodes

Drag nodes from the palette onto the canvas and connect them by dragging an edge from one node's output to the next node's input. A simple starter graph:

1. **Input** - accepts the brief, for example a product description.
2. **Prompt / transform** - refines the brief into a proper shot prompt.
3. **Model (video or image)** - renders the prompt with a model like Veo 3.1 or a Gemini image model.
4. **Output** - returns the generated asset.

Pick a model on each generation node. You can change it any time, or type any Hugging Face or OpenRouter model id directly into the node. See [Models](/pipelines/models).

***

## 3. Run it

Click **Run**. Treza executes the graph and shows each node's status, output, timing, and token counts. Runs happen in the background, so you can keep editing while a video renders. Open **Run history** to inspect any past run node by node.

If a node needs a provider key, add it to the [secrets manager](/getting-started/concepts#secrets) first. Keys are stored encrypted and injected at run time.

***

## 4. Publish

When the pipeline works, click **Publish**. Publishing takes a snapshot of the graph and assigns it a **version number**. API traffic always runs the published snapshot, never your in-progress draft. Re-publish any time to cut a new version, and roll back from **Publishing & versioning** if you need to. See [Publishing & versioning](/pipelines/publishing).

***

## 5. Create an API key

Open the **API keys** page and create a key. The key (`treza_live_...`) is shown once at creation, so store it in a secrets manager. You send it as the `Authorization: Bearer` header on every call. A key can only invoke pipelines owned by the same account.

***

## 6. Call your pipeline

Every published pipeline exposes two endpoints. Use the typed `/invoke` endpoint for JSON in and JSON out:

```bash
curl https://trezalabs.com/api/pipelines/<pipeline-id>/invoke \
  -H "Authorization: Bearer treza_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "inputs": {
      "brief": "A 6-second product demo of a matte-black water bottle on a kitchen counter"
    }
  }'
```

The input keys (`brief` above) come from your input nodes. Runs execute in the background, so `/invoke` returns a `runId` right away:

```json
{
  "runId": "2026-07-10T18:30:00.000Z#a1b2c3d4",
  "status": "running",
  "version": 3,
  "statusUrl": "https://trezalabs.com/api/pipelines/<pipeline-id>/invoke?runId=..."
}
```

Poll `statusUrl` (a `GET .../invoke?runId=...` with the same key) until `status` is no longer `running`; the finished response is keyed by your output nodes:

```json
{
  "runId": "2026-07-10T18:30:00.000Z#a1b2c3d4",
  "status": "success",
  "version": 3,
  "outputs": { "video": "https://.../output.mp4" },
  "usage": { "total": 1234, "costUsd": 0.42 },
  "durationMs": 48213
}
```

Prefer an OpenAI-compatible call, or want streaming? Point any OpenAI SDK at the `/chat/completions` endpoint instead. See the full [Pipeline API](/api/pipeline-api) reference.

***

## Next steps

* [**Models**](/pipelines/models) - the catalog and using any model id.
* [**Publishing & versioning**](/pipelines/publishing) - versions, rollback, and run history.
* [**Pipeline API**](/api/pipeline-api) - both endpoints, auth, errors, and streaming.


# Models

Every generation node in a pipeline runs a model. Treza reaches models through an OpenAI-compatible backend that spans providers like Together, OpenRouter, Fireworks, and DeepSeek, so you can pick the best model for each step and never get locked into one vendor.

***

## The catalog

The catalog covers every modality. Pick a model per node from the lists below, or type any model id straight in (see [Any model id](#any-model-id)).

### Video

Cinematic clips from a sentence, with duration and aspect ratio set per node.

* Veo 3.1
* Veo 3.1 Fast
* Sora 2 Pro

### Image

Product shots, illustrations, and campaign art with full response metadata.

* Gemini 2.5 Flash Image
* Gemini 3 Pro Image

### Language

Drafting, rewriting, classification, and reasoning with open-weight models.

* Llama 3.3 70B
* DeepSeek R1
* Qwen2.5 72B
* Mixtral 8x22B

The catalog also covers the major open families: Llama, Mistral, Qwen, DeepSeek, Gemma, and Phi.

### Audio & embeddings

Transcribe speech and vectorize text for search and retrieval steps.

* Whisper Large v3
* BGE Large EN

***

## Any model id

Not listed? Type any Hugging Face or OpenRouter model id directly into the node and Treza will route to it through the OpenAI-compatible backend. This means new models are usable the day they ship, without waiting for them to be added to the catalog.

***

## Swap models, no lock-in

* **One model per node**, changeable at any time. Swapping a model never requires rewriting the rest of the pipeline.
* **Per-node choice.** Use a fast, cheap model to refine a brief and a premium model to render the final asset.
* **Bring your own keys.** Store provider API keys in the encrypted [secrets manager](/getting-started/concepts#secrets). Keys are used server-side and never returned by any API, so you are never tied to one price or one vendor.

***

## Cost

Model runs are paid for with prepaid credits, and only successful runs are charged. There is no subscription: you buy credits once and spend them as you run models. Every run records its token counts and cost in [run history](/pipelines/publishing#run-history). See [Plans & Pricing](/ai-gateway/plans-and-pricing).


# Publishing & versioning

Publishing turns a pipeline into a versioned HTTP endpoint. This page covers how versions work, how to roll back, and how to read run history.

***

## Draft vs. published

Every pipeline has two states:

* **Draft** - the graph you edit on the canvas. Running from the editor executes the draft.
* **Published** - a frozen snapshot that serves API traffic. The `/invoke` and `/chat/completions` endpoints always run the published snapshot, never your in-progress draft.

This separation means you can keep editing a live pipeline without affecting production calls until you publish again.

***

## Versions

Each time you publish, Treza snapshots the current graph and assigns it an incrementing **version number**. The version is returned on every API response (the `version` field on `/invoke`, and the `x-treza-pipeline-version` header on `/chat/completions`), so you always know which snapshot produced a result.

* Re-publish to cut a new version after editing the draft.
* API keys and the endpoint URL stay the same across versions. Only the running snapshot changes.

***

## Rollback

If a new version misbehaves, roll back to an earlier one from the pipeline's publishing controls. Rollback re-points the published snapshot at a previous version without changing your draft, so live traffic recovers immediately while you fix the draft.

***

## Run history

Every execution, whether triggered from the editor or over the API, is recorded as a **run**. Each run captures:

* **Per-node timing** - how long each node took.
* **Tokens and cost** - token counts and the provider cost charged.
* **Status** - success or error, with the failing node surfaced on errors.
* **Trigger** - whether the run came from the editor or the API.
* **Version** - which published version served the run.

Open **Run history** on a pipeline to inspect any run node by node and see exactly how a prompt became an output.

***

## Usage & insights

The **Usage & insights** view aggregates across your account: total runs, runs via API, tokens, credits used, and success rate over the last 30 days, plus a per-pipeline breakdown. Use it to watch spend and reliability at a glance. You can export run history for SOC 2, HIPAA, or an internal audit.

***

## Requirements for API calls

For a pipeline to serve API traffic it must:

* Be **published** (an unpublished pipeline returns `409`).
* Have at least one **input node** (an entry point to accept the request).
* Have at least one **output node** (to return a result).

See the [Pipeline API](/api/pipeline-api) for the full request and response contract.


# Pipeline API

Every published pipeline is a versioned HTTP endpoint. There are two ways to call it: the typed **`/invoke`** endpoint for JSON in and JSON out, and an OpenAI-compatible **`/chat/completions`** endpoint that works as a drop-in for any OpenAI SDK, streaming included.

***

## Base URL

```
https://trezalabs.com
```

Both endpoints live under `/api/pipelines/<id>`, where `<id>` is the pipeline's id from the dashboard. They accept and return `application/json` (the streaming variant returns Server-Sent Events).

***

## Authentication

Authenticate with a Treza API key, created on the **API keys** page in the dashboard and sent as a bearer token:

```
Authorization: Bearer treza_live_...
```

The key (`treza_live_...`) is shown once at creation. Store it in a secrets manager. A key can only invoke pipelines owned by the same account, and the pipeline must be **published**.

***

## Prerequisites

For a pipeline to accept API calls it must be published and have at least one input node and one output node. The **input keys** you send and the **output keys** you receive are derived from those nodes (the pipeline's contract). See [Publishing & versioning](/pipelines/publishing).

***

## `POST /api/pipelines/{id}/invoke`

Starts a run of the published pipeline with typed inputs. Runs execute asynchronously on Treza's background workers, so this returns a `runId` immediately — poll [`GET .../invoke`](#get-apipipelinesidinvoke) for the result.

### Request

```bash
curl https://trezalabs.com/api/pipelines/<id>/invoke \
  -H "Authorization: Bearer treza_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "inputs": {
      "brief": "A 6-second product demo of a matte-black water bottle on a kitchen counter"
    }
  }'
```

| Field    | Type   | Description                                                                  |
| -------- | ------ | ---------------------------------------------------------------------------- |
| `inputs` | object | Map of the pipeline's input keys to values. Keys come from your input nodes. |

### Response `202 Accepted`

```json
{
  "runId": "2026-07-10T18:30:00.000Z#a1b2c3d4",
  "status": "running",
  "version": 3,
  "statusUrl": "https://trezalabs.com/api/pipelines/<id>/invoke?runId=2026-07-10T18%3A30%3A00.000Z%23a1b2c3d4"
}
```

| Field       | Description                                         |
| ----------- | --------------------------------------------------- |
| `runId`     | Id of the run to poll. Also appears in run history. |
| `status`    | Always `running` on accept.                         |
| `version`   | The published version serving the run.              |
| `statusUrl` | Ready-made URL to poll for status and outputs.      |

***

## `GET /api/pipelines/{id}/invoke`

Polls a run started by `POST .../invoke`. Same bearer API key.

### Request

```bash
curl "https://trezalabs.com/api/pipelines/<id>/invoke?runId=<runId>" \
  -H "Authorization: Bearer treza_live_..."
```

| Query param | Description                                                |
| ----------- | ---------------------------------------------------------- |
| `runId`     | The `runId` returned by `POST .../invoke` (URL-encode it). |

### Response

While the run is in progress:

```json
{ "runId": "…", "status": "running", "version": 3, "startedAt": "…" }
```

Once finished:

```json
{
  "runId": "…",
  "status": "success",
  "version": 3,
  "startedAt": "2026-07-10T18:30:00.000Z",
  "finishedAt": "2026-07-10T18:30:48.000Z",
  "durationMs": 48213,
  "usage": { "prompt": 0, "completion": 0, "total": 1234, "costUsd": 0.42 },
  "outputs": { "video": "https://.../output.mp4" }
}
```

| Field        | Description                                                   |
| ------------ | ------------------------------------------------------------- |
| `status`     | `running`, `success`, `error`, or `partial`.                  |
| `outputs`    | Map keyed by your output nodes' keys (present once finished). |
| `usage`      | Token counts and provider cost (`costUsd`) for the run.       |
| `durationMs` | Wall-clock run time in milliseconds (once finished).          |

{% hint style="info" %}
Poll `statusUrl` every few seconds until `status` is no longer `running`. Video and image generation poll asynchronous provider jobs, so a run can take a while. Output **media URLs** are returned verbatim; long **text** outputs are truncated in the polled result.
{% endhint %}

***

## `POST /api/pipelines/{id}/chat/completions`

An OpenAI-compatible chat-completions endpoint. Point any OpenAI SDK at it by changing the base URL and API key. The latest user message is fed into the pipeline's entry node, and the output node's value is returned as the assistant message.

### curl

```bash
curl https://trezalabs.com/api/pipelines/<id>/chat/completions \
  -H "Authorization: Bearer treza_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "model": "treza",
    "messages": [
      { "role": "user", "content": "A serene mountain lake at sunrise, cinematic" }
    ]
  }'
```

The `model` field is accepted but not used to pick a model (the pipeline's nodes decide that); send any string.

### Python (OpenAI SDK)

```python
from openai import OpenAI

client = OpenAI(
    api_key="treza_live_...",
    base_url="https://trezalabs.com/api/pipelines/<id>",  # SDK appends /chat/completions
)

completion = client.chat.completions.create(
    model="treza",
    messages=[{"role": "user", "content": "A serene mountain lake at sunrise, cinematic"}],
)

print(completion.choices[0].message.content)
```

### TypeScript (OpenAI SDK)

```typescript
import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'treza_live_...',
  baseURL: 'https://trezalabs.com/api/pipelines/<id>', // SDK appends /chat/completions
});

const completion = await client.chat.completions.create({
  model: 'treza',
  messages: [{ role: 'user', content: 'A serene mountain lake at sunrise, cinematic' }],
});

console.log(completion.choices[0].message.content);
```

### Response

A standard OpenAI chat-completion object:

```json
{
  "id": "chatcmpl-...",
  "object": "chat.completion",
  "created": 1751904000,
  "model": "treza",
  "choices": [
    {
      "index": 0,
      "message": { "role": "assistant", "content": "https://.../output.mp4" },
      "finish_reason": "stop"
    }
  ],
  "usage": { "prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 1234 }
}
```

Two response headers help you tie a completion back to a run:

| Header                     | Meaning                                        |
| -------------------------- | ---------------------------------------------- |
| `x-treza-run-id`           | Id of the recorded run.                        |
| `x-treza-pipeline-version` | The published version that served the request. |

### Streaming

Set `"stream": true` to receive the response as Server-Sent Events, emitted as `chat.completion.chunk` objects and terminated by `data: [DONE]`. The final chunk carries `finish_reason: "stop"` and a `usage` block. Any OpenAI SDK's streaming mode works unchanged.

***

## Errors

Both endpoints share the same authorization and status model. `/invoke` returns `{ "error": "..." }`; `/chat/completions` returns OpenAI-style `{ "error": { "message": ..., "type": ... } }`.

| Status | Meaning                                                                     |
| ------ | --------------------------------------------------------------------------- |
| `400`  | Malformed request (for example, missing `messages` on `/chat/completions`). |
| `401`  | Missing or invalid API key.                                                 |
| `402`  | Insufficient credits. Top up in billing settings.                           |
| `403`  | The key does not own this pipeline.                                         |
| `404`  | Pipeline not found.                                                         |
| `409`  | Pipeline is not published.                                                  |
| `422`  | The pipeline has no entry node or no output node to serve chat completions. |
| `502`  | The pipeline ran but a node failed. The failing node's error is included.   |
| `500`  | Internal server error.                                                      |

***

## Related

* [Build your first pipeline](/pipelines/quickstart) - end-to-end from the canvas.
* [Publishing & versioning](/pipelines/publishing) - versions, rollback, and run history.
* [REST API](https://github.com/treza-labs/treza-docs-site/tree/main/developers/rest-api.md) - the rest of the Treza Platform API (keys, enclaves, gateway, and more).


# API Keys

Treza API keys authenticate programmatic access to the platform: calling a published [pipeline](/pipelines/pipelines) and using the [AI Gateway](/ai-gateway/ai-control-plane). A key looks like `treza_live_...`, is scoped to your account, and is sent as a bearer token.

***

## Create a key

In the dashboard, open the **API keys** page and create a key.

{% hint style="warning" %}
The key (`treza_live_...`) is shown **once**, at creation. Store it in a secrets manager immediately. If you lose it, revoke it and create a new one.
{% endhint %}

***

## Use a key

Send the key in the `Authorization` header as a bearer token on every request:

```
Authorization: Bearer treza_live_...
```

For example, invoking a published pipeline:

```bash
curl https://trezalabs.com/api/pipelines/<id>/invoke \
  -H "Authorization: Bearer treza_live_..." \
  -H "Content-Type: application/json" \
  -d '{ "inputs": { "brief": "A 6-second product demo" } }'
```

The same key works with the OpenAI-compatible endpoint. Point any OpenAI SDK at your pipeline and pass the key as the `api_key`. See the [Pipeline API](/api/pipeline-api).

***

## Ownership and scope

* **Account-scoped.** A key can only act on resources owned by the same account. In particular, a key can only invoke pipelines your account owns; calls to another account's pipeline return `403`.
* **Published only.** Pipeline endpoints serve the published snapshot. An unpublished pipeline returns `409`.
* **Credits.** Calls that run a pipeline draw from your account's prepaid credit balance. If the balance is empty, requests return `402`.

***

## Scopes

Keys carry scoped permissions that gate access per feature. Grant only the scopes a key needs.

| Scope                                                                           | Grants                                                                                        |
| ------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
| `pipelines:read`                                                                | List pipelines and read run history over the [MCP server](/api/mcp-server)                    |
| `pipelines:run`                                                                 | Start pipeline runs over the [MCP server](/api/mcp-server)                                    |
| `redact:proxy`                                                                  | OpenAI-compatible redacting chat completions (the [AI Gateway](/ai-gateway/ai-control-plane)) |
| `redact:run`                                                                    | Standalone text redaction                                                                     |
| `redact:log`                                                                    | Read the redaction audit log                                                                  |
| `pii:ingest`, `pii:read`, `pii:write`, `pii:delete`, `pii:consent`, `pii:audit` | PII vault operations                                                                          |

Invoking a published pipeline requires a valid key that owns the pipeline; the gateway and PII endpoints additionally require the scopes above.

***

## Manage and rotate

* **Revoke** a key from the API keys page the moment you suspect it is exposed.
* **Rotate** keys periodically: create a new key, move your integrations over, then delete the old one.
* **Never** embed a key in client-side code or a public repository. Call Treza from your backend, where the key stays secret.

***

## Related

* [Pipeline API](/api/pipeline-api) - call a published pipeline with your key.
* [MCP Server](/api/mcp-server) - connect Claude and other AI assistants with `pipelines:*` scopes.
* [Build your first pipeline](/pipelines/quickstart) - end-to-end, including creating a key.
* [AI Gateway](/ai-gateway/ai-control-plane) - redaction proxy that uses `redact:*` scopes.


# MCP Server

Treza ships a remote [Model Context Protocol](https://modelcontextprotocol.io/) server, so AI assistants like Claude can list your pipelines, inspect runs, and start new runs on your behalf.

```
https://trezalabs.com/api/mcp
```

The server speaks Streamable HTTP and authenticates every request. You can connect with OAuth (sign in with your Treza account, no key handling) or with an API key.

***

## Connect from claude.ai

Claude's web and desktop apps support custom connectors:

1. Open **Settings → Connectors → Add custom connector**.
2. Enter a name (for example, `Treza`) and the URL `https://trezalabs.com/api/mcp`. Leave the OAuth fields empty.
3. Click **Add**, then **Connect**. You'll be sent to Treza to sign in and approve access, then returned to Claude.

That's it. Ask Claude things like "list my Treza pipelines" or "run my daily short pipeline and tell me when it finishes."

***

## Connect from Claude Code

```bash
claude mcp add --transport http treza https://trezalabs.com/api/mcp
```

Claude Code discovers the OAuth flow automatically and opens a browser window to sign in. To use an [API key](/api/api-keys) instead:

```bash
claude mcp add --transport http treza https://trezalabs.com/api/mcp \
  --header "Authorization: Bearer treza_live_..."
```

Any other MCP client that supports Streamable HTTP works the same way: point it at the URL, and either complete the OAuth flow or send your key as a bearer token.

***

## Authentication and scopes

| Method  | How                                                         | Scopes                            |
| ------- | ----------------------------------------------------------- | --------------------------------- |
| OAuth   | Sign in with your Treza account when the client prompts you | `pipelines:read`, `pipelines:run` |
| API key | `Authorization: Bearer treza_live_...` header               | Whatever the key was granted      |

API keys must carry the `pipelines:read` scope to connect, and `pipelines:run` to start runs. Grant scopes when you create the key on the **API keys** page. See [API Keys](/api/api-keys).

Access is account-scoped either way: the server only ever sees pipelines owned by the signed-in account, and requests for anything else return an error.

***

## Available tools

| Tool             | Description                                                      |
| ---------------- | ---------------------------------------------------------------- |
| `list_pipelines` | List your pipelines with status and a summary of recent runs     |
| `get_pipeline`   | One pipeline's metadata plus a summary of its node graph         |
| `list_runs`      | Recent runs for a pipeline, newest first                         |
| `get_run`        | One run's status, per-node results, and output media URLs        |
| `run_pipeline`   | Start a run in the background and return its `runId` immediately |

***

## Runs are asynchronous

Video generation takes minutes, so `run_pipeline` never blocks. It starts the run on Treza's background workers and returns a `runId` right away; the assistant then polls `get_run` until the status is no longer `running`. Finished runs include output URLs for the generated media.

{% hint style="warning" %}
Runs started over MCP are real runs: they draw from your prepaid credit balance and appear in run history, exactly like runs started from the dashboard or the [Pipeline API](/api/pipeline-api).
{% endhint %}

***

## Related

* [API Keys](/api/api-keys) - create a key with `pipelines:*` scopes.
* [Pipeline API](/api/pipeline-api) - call a published pipeline over plain HTTP.
* [Build your first pipeline](/pipelines/quickstart) - end-to-end from the canvas.


# Overview

The Treza AI Gateway is a managed **PII redaction proxy** for LLM traffic. Instead of sending prompts directly to OpenAI (or another provider), your application sends them to a Treza proxy endpoint. Treza detects and redacts personally identifiable information, forwards the sanitized request to your configured upstream provider, and returns the provider's response, so raw PII never reaches the model provider.

You keep your existing OpenAI-compatible client and SDK. Switching to the gateway is a base-URL change plus two headers.

{% hint style="info" %}
The gateway's redaction engine is the same one behind the **PII guardrail node** inside pipelines. Use the gateway to protect an existing OpenAI-based app with a base-URL change, or drop a redaction node into a [pipeline](/pipelines/pipelines) to handle PII mid-graph.
{% endhint %}

### Why route LLM traffic through Treza?

* **PII never leaves your trust boundary in plaintext prompts.** Emails, phone numbers, SSNs, credit cards, and other sensitive values are replaced with placeholders like `[EMAIL_1]` before the request is forwarded upstream.
* **Per-proxy policies.** Each proxy bundles an upstream provider, a stored (encrypted) provider key, and a redaction policy describing which entity types to strip.
* **Audit trail.** Every request writes a redaction audit entry — entity counts by type, engine versions, and an attestation reference — retrievable via API or the dashboard.
* **Attested redaction (Enterprise).** Redaction can run inside a Treza Enclave (AWS Nitro) with hardware attestation, so you can prove *where* the redaction happened.

### Architecture

```
Your app / agent                Treza AI Control Plane                 LLM Provider
┌──────────────┐   OpenAI-     ┌─────────────────────────┐           ┌─────────────┐
│ OpenAI SDK / │   compatible  │ 1. Authenticate API key │  redacted │ OpenAI /    │
│ fetch        │──────────────▶│ 2. Redact PII           │──────────▶│ Azure /     │
│              │               │    [EMAIL_1], [SSN_1]…  │           │ Anthropic / │
│              │◀──────────────│ 3. Forward upstream     │◀──────────│ custom      │
└──────────────┘   response +  │ 4. Write audit entry    │  response └─────────────┘
                   x-treza-*   │ 5. Meter usage          │
                   headers     └─────────────────────────┘
```

The proxy endpoint is OpenAI-compatible:

```
POST https://trezalabs.com/api/redact/chat/completions
```

It authenticates with a Treza API key (`redact:proxy` scope), selects an upstream via the `x-treza-proxy` header, redacts every message, and forwards the request body unchanged otherwise. The response is returned with `x-treza-request-id` and `x-treza-mode` headers.

{% hint style="info" %}
The model only ever sees placeholders. If the model's reply references a placeholder (e.g. "I'll email \[EMAIL\_1] tomorrow"), send the `x-treza-rehydrate: 1` request header to receive the placeholder → original-value map in the `x-treza-rehydration` response header and restore values client-side. Original values are never sent upstream.
{% endhint %}

{% hint style="warning" %}
Streaming is not yet supported by the redaction proxy. Requests with `"stream": true` are rejected with `400` — omit `stream` or set it to `false`.
{% endhint %}

### What gets redacted

The redaction pipeline detects the following entity types (used in placeholders and policies):

| Entity type | Description                              |
| ----------- | ---------------------------------------- |
| `NAME`      | Person names                             |
| `EMAIL`     | Email addresses                          |
| `PHONE`     | Phone numbers                            |
| `ADDRESS`   | Physical addresses                       |
| `SSN`       | US Social Security numbers               |
| `CC`        | Credit card numbers (checksum-validated) |
| `MRN`       | Medical record numbers                   |
| `DOB`       | Dates of birth (contextual)              |
| `ACCOUNT`   | Account numbers                          |
| `URL`       | URLs                                     |
| `DATE`      | Dates                                    |
| `SECRET`    | Secrets / credentials                    |

By default a proxy redacts everything the pipeline detects. On Pro and above you can narrow this with a [custom redaction policy](/ai-gateway/proxies-and-policies#custom-redaction-policies-pro).

### Endpoints at a glance

| Endpoint                       | Method | API key scope     | Purpose                                     |
| ------------------------------ | ------ | ----------------- | ------------------------------------------- |
| `/api/redact/chat/completions` | POST   | `redact:proxy`    | The redaction proxy (billable)              |
| `/api/redact/run`              | POST   | `redact:run`      | Redact text without forwarding (not billed) |
| `/api/redact/log`              | GET    | `redact:log`      | Redaction audit log for your API key        |
| `/api/redact/attest`           | GET    | `redact:run`      | Enclave attestation summary (Enterprise)    |
| `/api/proxies` (+ `/test`)     | CRUD   | dashboard session | Manage upstream proxy configurations        |
| `/api/usage` (+ `/export`)     | GET    | dashboard session | Usage insights and audit CSV export         |
| `/api/pii/*`                   | varies | `pii:*`           | Encrypted PII vault with consent + audit    |

### Features by plan

| Feature                                | Pro | Enterprise |
| -------------------------------------- | :-: | :--------: |
| Redaction proxies                      |  ✅  |      ✅     |
| Custom redaction policies              |  ✅  |      ✅     |
| Multiple upstream providers            |  ✅  |      ✅     |
| Usage insights                         |  ✅  |      ✅     |
| Audit log export                       |  ✅  |      ✅     |
| TEE redaction + hardware attestation   |  ❌  |      ✅     |
| Enhanced redaction engine (in enclave) |  ❌  |      ✅     |
| Attestation / trust reports            |  ❌  |      ✅     |

The gateway is included with your account; redaction requests draw from your prepaid credits like any other model usage. See [Plans & Pricing](/ai-gateway/plans-and-pricing).

### In this section

* [Quickstart](/ai-gateway/quickstart) — first redacted request in five minutes
* [Proxies & Policies](/ai-gateway/proxies-and-policies) — upstream providers and redaction policies
* [PII Vault](/ai-gateway/pii-vault) — encrypted PII storage with consent and audit APIs
* [Attestation](/ai-gateway/attestation) — TEE-attested redaction (Enterprise)
* [Usage & Billing](/ai-gateway/usage-and-billing) — usage insights, audit export, and how requests are counted
* [Plans & Pricing](/ai-gateway/plans-and-pricing) — tiers, metering, and billing


# Quickstart

Send your first PII-redacted LLM request through the Treza AI Control Plane. You'll create an API key, configure a proxy, point your OpenAI client at Treza, and check the audit log.

### Prerequisites

* A Treza account — sign in at [trezalabs.com](https://trezalabs.com/) (email sign-in; the Starter plan is free)
* An API key from your LLM provider (e.g. an OpenAI `sk-...` key)

### 1. Create a Treza API key

In the dashboard, go to **API Keys** and create a key with the `redact:proxy` scope. Add `redact:run` and `redact:log` if you also want the standalone redaction and log endpoints.

{% hint style="warning" %}
The key (`treza_live_...`) is shown **once** at creation. Store it in a secrets manager — you'll send it as the `Authorization: Bearer` header on every request.
{% endhint %}

### 2. Create a proxy

Go to **Control Plane** in the dashboard and create a proxy:

1. Choose the upstream provider (OpenAI on Starter; Azure OpenAI, Anthropic, or a custom endpoint on Pro+).
2. Paste your upstream provider key. It is envelope-encrypted with KMS at rest, never returned by any API, and used server-side — so your application never needs to handle the provider key again.
3. Copy the proxy id (`proxy_...`).

{% hint style="info" %}
Don't want Treza to store your provider key? Leave it off the proxy and pass it per-request in the `x-model-key` header instead.
{% endhint %}

### 3. Point your client at Treza

The proxy endpoint is OpenAI-compatible, so existing SDKs work with a base-URL change.

**curl**

```bash
curl https://trezalabs.com/api/redact/chat/completions \
  -H "Authorization: Bearer $TREZA_API_KEY" \
  -H "x-treza-proxy: proxy_1718039482_ab12cd34e" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4o-mini",
    "messages": [
      { "role": "user", "content": "Draft a reply to jane.doe@acme.com confirming her SSN 123-45-6789 was updated." }
    ]
  }'
```

The upstream provider receives the redacted prompt:

```
Draft a reply to [EMAIL_1] confirming her SSN [SSN_1] was updated.
```

**TypeScript (OpenAI SDK)**

```typescript
import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: process.env.TREZA_API_KEY,                  // treza_live_...
  baseURL: 'https://trezalabs.com/api/redact',    // SDK appends /chat/completions
  defaultHeaders: { 'x-treza-proxy': 'proxy_1718039482_ab12cd34e' },
});

const completion = await client.chat.completions.create({
  model: 'gpt-4o-mini',
  messages: [
    { role: 'user', content: 'Draft a reply to jane.doe@acme.com confirming her SSN 123-45-6789 was updated.' },
  ],
});

console.log(completion.choices[0].message.content);
```

**Python (OpenAI SDK)**

```python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["TREZA_API_KEY"],                 # treza_live_...
    base_url="https://trezalabs.com/api/redact",     # SDK appends /chat/completions
    default_headers={"x-treza-proxy": "proxy_1718039482_ab12cd34e"},
)

completion = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[
        {"role": "user", "content": "Draft a reply to jane.doe@acme.com confirming her SSN 123-45-6789 was updated."},
    ],
)

print(completion.choices[0].message.content)
```

{% hint style="info" %}
**Streaming is supported.** Set `stream: true` and the proxy forwards the upstream provider's Server-Sent Events stream straight through, so token-by-token output works with the standard OpenAI SDKs. Treza never rewrites the response body — placeholders are rehydrated client-side from the `x-treza-rehydration` map, which is sent as a response header before the first token. Because a placeholder can be split across SSE chunks, rehydrate against the accumulated text rather than individual deltas.
{% endhint %}

### 4. Inspect the response

Every proxied response carries Treza headers:

| Header                | Meaning                                                               |
| --------------------- | --------------------------------------------------------------------- |
| `x-treza-request-id`  | Unique id for this redaction request (matches the audit log)          |
| `x-treza-mode`        | `standard` (managed software redaction) or `tee` (Enterprise enclave) |
| `x-treza-rehydration` | Placeholder → original map (only when requested, see below)           |

If the model's reply references placeholders, request the rehydration map and restore values client-side:

```bash
curl -i https://trezalabs.com/api/redact/chat/completions \
  -H "Authorization: Bearer $TREZA_API_KEY" \
  -H "x-treza-proxy: proxy_1718039482_ab12cd34e" \
  -H "x-treza-rehydrate: 1" \
  -H "Content-Type: application/json" \
  -d '{"model":"gpt-4o-mini","messages":[{"role":"user","content":"Reply to jane.doe@acme.com"}]}'

# Response header:
# x-treza-rehydration: {"[EMAIL_1]":"jane.doe@acme.com"}
```

```typescript
const { data, response } = await client.chat.completions
  .create(
    { model: 'gpt-4o-mini', messages },
    { headers: { 'x-treza-rehydrate': '1' } },
  )
  .withResponse();

const map: Record<string, string> = JSON.parse(
  response.headers.get('x-treza-rehydration') ?? '{}',
);
let text = data.choices[0].message.content ?? '';
for (const [placeholder, original] of Object.entries(map)) {
  text = text.split(placeholder).join(original);
}
```

### 5. Try redaction without forwarding

To see what the pipeline detects — without calling any upstream and without using your request quota — use `POST /api/redact/run` (requires the `redact:run` scope):

```bash
curl https://trezalabs.com/api/redact/run \
  -H "Authorization: Bearer $TREZA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"text": "Call John Smith at (555) 123-4567 about card 4111 1111 1111 1111"}'
```

```json
{
  "redacted": "Call John Smith at [PHONE_1] about card [CC_1]",
  "entities": [
    { "type": "PHONE", "placeholder": "[PHONE_1]", "start": 19, "end": 28 },
    { "type": "CC", "placeholder": "[CC_1]", "start": 40, "end": 46 }
  ],
  "requestId": "req_lx2k9a_1f3b7c2d",
  "mode": "standard",
  "modelVersion": "...",
  "recognizerVersion": "..."
}
```

### 6. View the audit log

Each request (proxied or standalone) writes an audit entry scoped to the API key that made it. Fetch entries with the `redact:log` scope:

```bash
curl "https://trezalabs.com/api/redact/log?limit=20" \
  -H "Authorization: Bearer $TREZA_API_KEY"
```

```json
{
  "entries": [
    {
      "ts": "2026-06-11T18:21:09.412Z",
      "requestId": "req_lx2k9a_1f3b7c2d",
      "source": "proxy",
      "entityCountsByType": { "EMAIL": 1, "SSN": 1 },
      "attestationRef": "shared-software-redaction",
      "modelVersion": "...",
      "recognizerVersion": "..."
    }
  ]
}
```

Query parameters: `limit` (1–500, default 20) and `since` (ISO timestamp). Audit entries contain entity **counts by type** — never the redacted values themselves. Request counts and entities-redacted insights are also available in the dashboard under **Usage & insights**.

### Next steps

* [Proxies & Policies](/ai-gateway/proxies-and-policies) — multiple providers, pausing proxies, custom policies
* [Usage & Billing](/ai-gateway/usage-and-billing) — usage insights, audit export, and how requests are counted
* [Plans & Pricing](/ai-gateway/plans-and-pricing) — included volumes and what happens when you hit your limit
* [Attestation](/ai-gateway/attestation) — prove redaction ran inside a Treza Enclave (Enterprise)


# Proxies & Policies

A **proxy** is a customer-configured redaction endpoint: it bundles an upstream LLM provider, an optional stored provider key, and a redaction policy describing which PII entity types to strip. Your application selects a proxy per request with the `x-treza-proxy` header.

Proxies are managed from the **Control Plane** page in the dashboard, or programmatically via the `/api/proxies` REST endpoints described below.

{% hint style="info" %}
The `/api/proxies` management endpoints authenticate as the **dashboard user** — send your Treza session access token as `Authorization: Bearer <token>`. They are not Treza-API-key endpoints; runtime traffic through `/api/redact/chat/completions` is what uses your `treza_live_...` key.
{% endhint %}

### Supported upstream providers

| Provider     | `upstreamProvider` | Default upstream URL                         | `upstreamUrl` required? | Plan     |
| ------------ | ------------------ | -------------------------------------------- | ----------------------- | -------- |
| OpenAI       | `openai`           | `https://api.openai.com/v1/chat/completions` | No                      | Starter+ |
| Azure OpenAI | `azure-openai`     | — (your resource URL)                        | Yes                     | Pro+     |
| Anthropic    | `anthropic`        | `https://api.anthropic.com/v1/messages`      | No                      | Pro+     |
| Custom       | `custom`           | —                                            | Yes                     | Pro+     |

Non-OpenAI providers require the **multiple providers** entitlement (Pro and above); creating one on Starter returns `402` with `code: "PLAN_FEATURE"`.

{% hint style="warning" %}
The proxy forwards the redacted request body as-is and authenticates upstream with `Authorization: Bearer <your upstream key>`. Custom endpoints must therefore accept OpenAI-style chat-completion JSON with Bearer authentication — OpenAI-compatible gateways (vLLM, LiteLLM, OpenRouter, and similar) work out of the box.
{% endhint %}

### The proxy object

```json
{
  "id": "proxy_1718039482_ab12cd34e",
  "accountId": "acct_...",
  "name": "Production OpenAI",
  "upstreamProvider": "openai",
  "upstreamUrl": "https://api.openai.com/v1/chat/completions",
  "redactionPolicy": { "entities": [] },
  "status": "active",
  "hasUpstreamKey": true,
  "createdAt": "2026-06-10T12:00:00.000Z",
  "updatedAt": "2026-06-11T09:30:00.000Z",
  "lastRequestAt": "2026-06-11T09:30:00.000Z"
}
```

The stored upstream key is never returned — only the `hasUpstreamKey` flag.

### List proxies

```bash
curl https://trezalabs.com/api/proxies \
  -H "Authorization: Bearer $TREZA_SESSION_TOKEN"
```

Returns `{ "proxies": [...] }`.

### Create a proxy

```bash
curl -X POST https://trezalabs.com/api/proxies \
  -H "Authorization: Bearer $TREZA_SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Production OpenAI",
    "upstreamProvider": "openai",
    "upstreamKey": "sk-...",
    "entities": []
  }'
```

| Field              | Type      | Notes                                                               |
| ------------------ | --------- | ------------------------------------------------------------------- |
| `upstreamProvider` | string    | Required. One of `openai`, `azure-openai`, `anthropic`, `custom`    |
| `name`             | string    | Optional; defaults to `"<provider> proxy"`                          |
| `upstreamUrl`      | string    | Required for `azure-openai` and `custom`; overrides the default URL |
| `upstreamKey`      | string    | Optional. Encrypted with KMS envelope encryption at rest            |
| `entities`         | string\[] | Optional custom redaction policy (Pro+, see below)                  |

Returns `201` with `{ "proxy": {...} }`. Plan limits are enforced server-side: exceeding your plan's proxy cap returns `402` with `code: "PLAN_LIMIT"`.

### Update a proxy

`PUT /api/proxies` updates fields by proxy `id`:

```bash
curl -X PUT https://trezalabs.com/api/proxies \
  -H "Authorization: Bearer $TREZA_SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "id": "proxy_1718039482_ab12cd34e",
    "status": "paused"
  }'
```

Updatable fields: `name`, `status` (`active` | `paused`), `upstreamUrl`, `entities`, `upstreamKey` (rotate the stored key), `clearUpstreamKey: true` (remove the stored key — callers must then send `x-model-key` per request).

Requests routed to a paused proxy are rejected with `403 Proxy is paused`.

### Delete a proxy

```bash
curl -X DELETE "https://trezalabs.com/api/proxies?id=proxy_1718039482_ab12cd34e" \
  -H "Authorization: Bearer $TREZA_SESSION_TOKEN"
```

### Test a policy (dry run)

`POST /api/proxies/test` previews what a proxy's policy strips from sample text. It makes no upstream call and is **not billed**:

```bash
curl -X POST https://trezalabs.com/api/proxies/test \
  -H "Authorization: Bearer $TREZA_SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "text": "Email jane.doe@acme.com, card 4111 1111 1111 1111",
    "proxyId": "proxy_1718039482_ab12cd34e"
  }'
```

```json
{
  "redacted": "Email [EMAIL_1], card [CC_1]",
  "entities": [
    { "type": "EMAIL", "placeholder": "[EMAIL_1]", "start": 6, "end": 15 },
    { "type": "CC", "placeholder": "[CC_1]", "start": 23, "end": 29 }
  ],
  "entityCount": 2,
  "mode": "standard"
}
```

Omit `proxyId` to preview the default policy (redact everything detected).

### Custom redaction policies (Pro+)

A proxy's `redactionPolicy.entities` array lists the entity types to redact:

* **Empty array (default):** redact *every* entity type the pipeline detects.
* **Non-empty array:** redact only the listed types; anything else detected is left in the prompt and passed through to the provider.

```bash
curl -X PUT https://trezalabs.com/api/proxies \
  -H "Authorization: Bearer $TREZA_SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "id": "proxy_1718039482_ab12cd34e",
    "entities": ["EMAIL", "PHONE", "SSN", "CC"]
  }'
```

Setting a non-empty policy requires the **custom policies** entitlement (Pro and above); otherwise the API returns `402` with `code: "PLAN_FEATURE"`.

Valid entity types: `NAME`, `EMAIL`, `PHONE`, `ADDRESS`, `SSN`, `CC`, `MRN`, `DOB`, `ACCOUNT`, `URL`, `DATE`, `SECRET`. See the [overview](/ai-gateway/ai-control-plane#what-gets-redacted) for descriptions.

{% hint style="info" %}
Policies are applied **after** detection: excluded entity types are restored from the redaction map before forwarding, and only the entities actually redacted are counted in the audit log.
{% endhint %}

### Selecting a proxy at request time

Runtime requests pick their configuration with headers on `POST /api/redact/chat/completions`:

| Header              | Purpose                                                                                |
| ------------------- | -------------------------------------------------------------------------------------- |
| `x-treza-proxy`     | Proxy id to use (upstream URL, stored key, and policy). `404` if unknown               |
| `x-model-key`       | Upstream provider key, when the proxy has no stored key (or no proxy is selected)      |
| `x-treza-rehydrate` | Set to `1` to receive the placeholder map in the `x-treza-rehydration` response header |

Without `x-treza-proxy`, the request is forwarded to the default OpenAI upstream with the full redact-everything policy, and `x-model-key` is required. If neither a stored key nor `x-model-key` is available the request fails with `400`.

{% hint style="info" %}
**Streaming.** Set `stream: true` in the request body to receive the upstream Server-Sent Events stream piped straight through. Redaction happens on the request before the first token, so the placeholder→original map is sent up-front in the `x-treza-rehydration` header — rehydrate client-side against accumulated text, since a placeholder may span SSE chunks. The [`treza redact proxy`](https://github.com/treza-labs/treza-docs-site/tree/main/developers/treza-cli.md) CLI handles this for you. Both streaming and buffered responses are billed per request.
{% endhint %}

{% hint style="warning" %}
If the redaction step fails, the request is **not** forwarded upstream — the proxy fails closed and returns `502 redaction_failed`. Your original messages never leave Treza unredacted.
{% endhint %}


# PII Vault

The PII Vault is an encrypted store for sensitive user records with **consent-gated retrieval**, **GDPR-style deletion**, and a **queryable audit trail**. It complements the redaction proxy: the proxy keeps PII out of LLM prompts, while the vault gives you a compliant place to keep the PII you do need to store.

Every record is encrypted with AES-256-GCM envelope encryption (KMS-backed) before it is written. Plaintext is never stored, and read endpoints return either metadata or the encrypted envelope — decryption happens in your approved environment.

### Authentication & scopes

Vault endpoints authenticate with a Treza API key plus an account header:

```
Authorization: Bearer treza_live_...
x-treza-account: <your account identifier>
```

The `x-treza-account` value must match the account that owns the API key (the identifier shown in the dashboard — your sign-in email or wallet address). Each endpoint requires a specific scope on the key:

| Scope         | Grants                                      |
| ------------- | ------------------------------------------- |
| `pii:ingest`  | Store new records (`pii:write` is an alias) |
| `pii:read`    | List record metadata, retrieve envelopes    |
| `pii:delete`  | Delete records                              |
| `pii:consent` | Grant, revoke, and list consents            |
| `pii:audit`   | Query the access audit log                  |

Create keys with only the scopes each service needs.

### Ingest a record

`POST /api/pii/ingest` — requires `pii:ingest`

```bash
curl -X POST https://trezalabs.com/api/pii/ingest \
  -H "Authorization: Bearer $TREZA_API_KEY" \
  -H "x-treza-account: $TREZA_ACCOUNT" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "passport",
    "payload": { "number": "X1234567", "country": "US" },
    "consentGiven": true,
    "metadata": { "source": "onboarding" }
  }'
```

| Field                | Type          | Notes                                                             |
| -------------------- | ------------- | ----------------------------------------------------------------- |
| `type`               | string        | Required. Your data-type label (e.g. `passport`, `email`)         |
| `payload`            | string/object | Required. Encrypted before storage; objects are JSON-serialized   |
| `consentGiven`       | boolean       | Optional consent flag recorded on the row                         |
| `processorEnclaveId` | string        | Optional. Pins the record to one of your `PII_PROCESSOR` enclaves |
| `metadata`           | object        | Optional non-sensitive metadata                                   |

```json
{
  "piiId": "pii_1718039482_x9y8z7w6v",
  "processorEnclaveId": null,
  "encryption": "AES_256_GCM_KMS_ENVELOPE"
}
```

Every ingest is recorded in the audit log.

### List records

`GET /api/pii/list?account=<your account identifier>` — requires `pii:read`

```bash
curl "https://trezalabs.com/api/pii/list?account=$TREZA_ACCOUNT" \
  -H "Authorization: Bearer $TREZA_API_KEY" \
  -H "x-treza-account: $TREZA_ACCOUNT"
```

Returns metadata only — never ciphertext or plaintext:

```json
{
  "records": [
    {
      "piiId": "pii_1718039482_x9y8z7w6v",
      "dataType": "passport",
      "status": "active",
      "createdAt": "2026-06-10T12:00:00.000Z",
      "processorEnclaveId": null
    }
  ]
}
```

### Retrieve a record (consent-gated)

`POST /api/pii/retrieve` — requires `pii:read`

Retrieval only succeeds when an **active consent** exists for the record's data type and the stated purpose. Denied attempts are recorded in the audit log as violations.

```bash
curl -X POST https://trezalabs.com/api/pii/retrieve \
  -H "Authorization: Bearer $TREZA_API_KEY" \
  -H "x-treza-account: $TREZA_ACCOUNT" \
  -H "Content-Type: application/json" \
  -d '{
    "piiId": "pii_1718039482_x9y8z7w6v",
    "purpose": "kyc-verification"
  }'
```

```json
{
  "piiId": "pii_1718039482_x9y8z7w6v",
  "dataType": "passport",
  "purpose": "kyc-verification",
  "envelope": { "algorithm": "AES_256_GCM_KMS_ENVELOPE", "...": "..." },
  "processorEnclaveId": null,
  "note": "Decrypt envelope inside an approved TEE using KMS."
}
```

The response contains the **encrypted envelope**, not plaintext — decrypt it inside your approved processing environment.

Optionally pass `processorEnclaveId` (and an `attestationDocument`) to require attestation verification of a `PII_PROCESSOR` enclave before the envelope is released; verification failure returns `403`.

| Error                                                  | Meaning                                     |
| ------------------------------------------------------ | ------------------------------------------- |
| `403 No active consent for this data type and purpose` | Grant consent first (logged as a violation) |
| `403 Attestation verification failed`                  | Enclave attestation check did not pass      |
| `404 PII record not found`                             | Unknown, deleted, or not-active record      |

### Consent management

`GET /api/pii/consent?account=<id>` — list consents (requires `pii:consent`) `POST /api/pii/consent` — grant or revoke (requires `pii:consent`)

**Grant** consent for a data type and recipient/purpose:

```bash
curl -X POST https://trezalabs.com/api/pii/consent \
  -H "Authorization: Bearer $TREZA_API_KEY" \
  -H "x-treza-account: $TREZA_ACCOUNT" \
  -H "Content-Type: application/json" \
  -d '{ "dataType": "passport", "recipient": "kyc-verification" }'
```

```json
{ "consentId": "consent_1718039482_q1w2e3r4t", "dataType": "passport", "recipient": "kyc-verification", "active": true }
```

The `recipient` is matched against the `purpose` supplied at retrieval time. Use `any` (or `*`) as a wildcard recipient to allow all purposes for that data type.

**Revoke** a consent:

```bash
curl -X POST https://trezalabs.com/api/pii/consent \
  -H "Authorization: Bearer $TREZA_API_KEY" \
  -H "x-treza-account: $TREZA_ACCOUNT" \
  -H "Content-Type: application/json" \
  -d '{ "revoke": true, "consentId": "consent_1718039482_q1w2e3r4t" }'
```

Grants and revocations are both written to the audit log. Consents expire automatically after three years.

### Delete a record (right to erasure)

`POST /api/pii/delete` — requires `pii:delete`

```bash
curl -X POST https://trezalabs.com/api/pii/delete \
  -H "Authorization: Bearer $TREZA_API_KEY" \
  -H "x-treza-account: $TREZA_ACCOUNT" \
  -H "Content-Type: application/json" \
  -d '{ "piiId": "pii_1718039482_x9y8z7w6v" }'
```

```json
{ "piiId": "pii_1718039482_x9y8z7w6v", "status": "pending_delete", "ttl": 1750705269 }
```

Deletion is designed for GDPR/CCPA erasure requests:

1. The **ciphertext is removed immediately** — the record is unrecoverable from this moment.
2. The row is marked `pending_delete` and the residual metadata is purged automatically within 30 days.
3. The deletion is written to the audit log.

Deleting a non-active record returns `409`; a record you don't own returns `404`.

### Audit log

`GET /api/pii/audit` — requires `pii:audit` when querying by account

Every vault operation (ingest, retrieve, delete, consent grant/revoke) and PII-access events flushed from Treza SDK workflows are queryable:

```bash
curl "https://trezalabs.com/api/pii/audit?account=$TREZA_ACCOUNT&violations=true&limit=50" \
  -H "Authorization: Bearer $TREZA_API_KEY" \
  -H "x-treza-account: $TREZA_ACCOUNT"
```

| Query param     | Description                                                     |
| --------------- | --------------------------------------------------------------- |
| `account`       | Your account identifier (required unless `workflowId` is given) |
| `workflowId`    | Filter to one SDK workflow                                      |
| `workflowRunId` | Filter to one workflow run                                      |
| `violations`    | `true` to return only events flagged as violations              |
| `startDate`     | ISO date lower bound                                            |
| `limit`         | Max events (default 100, cap 500)                               |

```json
{
  "summary": { "total": 2, "violations": 1, "workflows": ["wf_onboarding"] },
  "events": [ { "eventId": "pii_...", "hadViolation": true, "timestamp": "..." } ]
}
```

Audit events are retained for 90 days.

{% hint style="info" %}
The PII Vault audit log (`/api/pii/audit`) tracks access to **stored records**. The redaction proxy has its own log (`GET /api/redact/log`) tracking entities redacted from LLM traffic — see the [Quickstart](/ai-gateway/quickstart#6-view-the-audit-log).
{% endhint %}


# Attestation

On the Enterprise plan, redaction runs inside a **Treza Enclave** (AWS Nitro) instead of the managed software pipeline. Hardware attestation lets you cryptographically verify *where* your prompts were redacted — before any of them left your trust boundary for the LLM provider.

{% hint style="info" %}
TEE-attested redaction is an **Enterprise** entitlement. Starter and Pro accounts always use managed software redaction (`x-treza-mode: standard`) and never route through a Treza Enclave. See [Plans & Pricing](/ai-gateway/plans-and-pricing).
{% endhint %}

### Redaction modes

| Mode       | Plans        | Where redaction runs                         | Attested |
| ---------- | ------------ | -------------------------------------------- | -------- |
| `standard` | Starter, Pro | Managed software redaction                   | No       |
| `tee`      | Enterprise   | Treza Enclave (AWS Nitro), hardware-isolated | Yes      |

The mode is reported on every request:

* `POST /api/redact/chat/completions` — the `x-treza-mode` response header
* `POST /api/redact/run` — the `mode` field, plus an `attestation` object (`enclaveId`, `region`, `attested`) on Enterprise
* `GET /api/redact/log` — each audit entry's `attestationRef` records which environment performed the redaction (`shared-software-redaction` for standard mode, the enclave id for TEE mode)

{% hint style="warning" %}
`x-treza-mode: tee` is only set when the redaction actually ran inside an attested enclave. If the enclave cannot be reached, the proxy fails closed (`502 redaction_failed`) rather than silently downgrading — your unredacted messages are never forwarded upstream.
{% endhint %}

### What the attestation proves

A Treza Enclave produces a signed attestation document with Platform Configuration Register (PCR) measurements. For the redaction service this proves:

* **Code identity** — the exact redaction enclave image (`pcr0`), kernel and bootstrap (`pcr1`), and application (`pcr2`) that processed your text
* **Isolation** — redaction ran inside a hardware-isolated Nitro Enclave with no operator or host access to the plaintext
* **Engine versions** — the `modelVersion` and `recognizerVersion` of the redaction engine, matching what is stamped on your audit entries

It does **not** attest the upstream LLM provider — only the Treza redaction step that runs before your request is forwarded.

For background on PCR measurements and attestation documents, see [Attestation & Verification](/getting-started/concepts#attestation-and-verification).

### Get the attestation summary

`GET /api/redact/attest` — requires a Treza API key with the `redact:run` scope.

```bash
curl https://trezalabs.com/api/redact/attest \
  -H "Authorization: Bearer $TREZA_API_KEY"
```

```json
{
  "enclaveId": "eg-0a1b2c3d4e5f6a7b8",
  "region": "us-west-2",
  "pcr0": "e3b0c44298fc1c149afbf4c8996fb924...",
  "pcr1": "9f86d081884c7d659a2feaa0c55ad015...",
  "pcr2": "2c26b46b68ffc68ff99b453c1d304134...",
  "modelVersion": "1.4.2",
  "recognizerVersion": "2.1.0",
  "attested": true
}
```

| Field                    | Meaning                                                                                 |
| ------------------------ | --------------------------------------------------------------------------------------- |
| `enclaveId`              | The Treza Enclave performing your redaction (matches `attestationRef` in the audit log) |
| `region`                 | AWS region the enclave runs in                                                          |
| `pcr0` / `pcr1` / `pcr2` | PCR measurements of the enclave image, kernel, and application                          |
| `modelVersion`           | Redaction model version running in the enclave                                          |
| `recognizerVersion`      | Entity recognizer version                                                               |
| `attested`               | `true` when the summary comes from a verified enclave attestation                       |

On non-Enterprise plans the endpoint returns `403` with `code: "PLAN_FEATURE"`:

```json
{
  "error": "Hardware attestation requires an Enterprise plan.",
  "code": "PLAN_FEATURE"
}
```

### Tying attestation to individual requests

Every redaction request — proxied or standalone — writes an audit entry whose `attestationRef` is the id of the environment that redacted it. To build an auditable chain:

1. Capture the `x-treza-request-id` response header on each proxied request.
2. Look the request up in `GET /api/redact/log` (or the [CSV export](/ai-gateway/usage-and-billing#audit-log-export-pro)); its `attestationRef`, `modelVersion`, and `recognizerVersion` identify the redaction environment.
3. Compare `attestationRef` against the `enclaveId` from `GET /api/redact/attest` and verify the PCR measurements against your approved values.

### Related

* [Quickstart](/ai-gateway/quickstart) — send your first redacted request
* [Usage & Billing](/ai-gateway/usage-and-billing) — audit log export
* [Attestation & Verification concepts](/getting-started/concepts#attestation-and-verification)


# Usage & Billing

The AI Control Plane meters one thing: **redaction requests**. This page covers how requests are counted, the usage-insights API behind the dashboard, and the audit log export.

### How requests are counted

* **Billable:** each `POST /api/redact/chat/completions` call routed through the proxy counts as one redaction request, recorded at request time. On metered plans (Pro, Enterprise) each request also emits a Stripe meter event with an idempotency key, so a request is never double-billed.
* **Not billed:** `POST /api/redact/run` (standalone redaction), `POST /api/proxies/test` (policy dry runs), and all dashboard/management calls.
* Usage recording is best-effort and never delays or blocks the proxy response.

What happens when you exhaust the requests included in your plan depends on the tier:

| Plan       | Included requests / period | Beyond the included amount                             |
| ---------- | -------------------------- | ------------------------------------------------------ |
| Starter    | 1,000                      | Requests are rejected with `402`, `code: "PLAN_LIMIT"` |
| Pro        | 50,000                     | Requests keep flowing; overage billed at $0.002 each   |
| Enterprise | 1,000,000                  | Requests keep flowing; per custom contract             |

The included quota resets at the start of each billing period. See [Plans & Pricing](/ai-gateway/plans-and-pricing) for the full tier comparison.

### Usage insights

The **Usage & insights** tab in the Control Plane dashboard shows request volume over time, per-proxy totals, and PII entities redacted by type. The same data is available from the API:

`GET /api/usage?days=30` — authenticates as the **dashboard user** (Treza session access token), not a `treza_live_...` API key. `days` ranges from 1 to 90 (default 30).

```bash
curl "https://trezalabs.com/api/usage?days=30" \
  -H "Authorization: Bearer $TREZA_SESSION_TOKEN"
```

```json
{
  "totalRequests": 1284,
  "meteredRequests": 1284,
  "totalEntitiesRedacted": 3911,
  "series": [
    { "date": "2026-06-10", "count": 412 },
    { "date": "2026-06-11", "count": 872 }
  ],
  "byProxy": { "proxy_1718039482_ab12cd34e": 1284 },
  "entitiesByType": { "EMAIL": 1450, "PHONE": 1203, "SSN": 644, "CC": 614 },
  "recent": [
    {
      "requestId": "req_lx2k9a_1f3b7c2d",
      "ts": "2026-06-11T18:21:09.412Z",
      "source": "proxy",
      "counts": { "EMAIL": 1, "SSN": 1 }
    }
  ],
  "entitlements": {
    "planId": "pro",
    "usage": { "requestsThisPeriod": 1284, "includedRequests": 50000, "overLimit": false }
  }
}
```

| Field                   | Meaning                                              |
| ----------------------- | ---------------------------------------------------- |
| `totalRequests`         | Proxied requests in the window                       |
| `meteredRequests`       | Requests that emitted a Stripe meter event           |
| `totalEntitiesRedacted` | Sum of PII entities redacted across all requests     |
| `series`                | Per-day request counts                               |
| `byProxy`               | Request counts per proxy id                          |
| `entitiesByType`        | Redacted entity counts by type (`EMAIL`, `SSN`, …)   |
| `recent`                | The 25 most recent redaction audit entries           |
| `entitlements`          | Your current plan, feature flags, and quota position |

For a per-API-key view from your application, use `GET /api/redact/log` instead — see the [Quickstart](/ai-gateway/quickstart#6-view-the-audit-log).

### Audit log export (Pro+)

`GET /api/usage/export?days=30` downloads the redaction audit log as CSV. Requires the **audit export** entitlement (Pro and above); other plans receive `403` with `code: "PLAN_FEATURE"`. Like `/api/usage`, it authenticates as the dashboard user, and `days` ranges from 1 to 90.

```bash
curl -OJ "https://trezalabs.com/api/usage/export?days=30" \
  -H "Authorization: Bearer $TREZA_SESSION_TOKEN"
# → treza-redaction-audit-30d-2026-06-12.csv
```

CSV columns:

| Column               | Description                                                           |
| -------------------- | --------------------------------------------------------------------- |
| `timestamp`          | When the request was redacted (ISO 8601)                              |
| `request_id`         | Matches the `x-treza-request-id` response header                      |
| `source`             | `proxy` (chat completions) or `run` (standalone redaction)            |
| `attestation_ref`    | Redaction environment id (see [Attestation](/ai-gateway/attestation)) |
| `model_version`      | Redaction model version                                               |
| `recognizer_version` | Entity recognizer version                                             |
| `entities_redacted`  | Total entities redacted in the request                                |
| `entity_breakdown`   | Per-type counts, e.g. `EMAIL:1;SSN:2`                                 |

Each export covers up to 5,000 of the most recent entries in the selected window. Audit entries contain entity **counts by type** only — never the original or redacted values.

### Plan-gating errors

API responses use two error codes for plan enforcement:

| Code           | Status      | Meaning                                                                 |
| -------------- | ----------- | ----------------------------------------------------------------------- |
| `PLAN_LIMIT`   | `402`       | A numeric limit was hit (included requests used up, proxy cap reached)  |
| `PLAN_FEATURE` | `402`/`403` | The feature requires a higher tier (e.g. custom policies, audit export) |

```json
{
  "error": "You've used all 1000 redaction requests included in your Starter plan. Upgrade to keep routing requests.",
  "code": "PLAN_LIMIT"
}
```

{% hint style="info" %}
Redaction proxy usage draws from your prepaid credit balance, like any other model usage. See [Plans & Pricing](/ai-gateway/plans-and-pricing).
{% endhint %}

### Related

* [Plans & Pricing](/ai-gateway/plans-and-pricing) — tiers, included volumes, and overage rates
* [Quickstart](/ai-gateway/quickstart) — the per-API-key redaction log
* [Attestation](/ai-gateway/attestation) — what `attestation_ref` proves


# Plans & Pricing

Treza is prepaid credits. There is **no subscription and no recurring charge**. You buy a credit pack once, and your credits are spent only when you run models. New accounts start with **$5 in free credits**, and **credits never expire**.

***

## Credit packs

One-time purchase through Stripe. Credits land in your balance immediately.

| Price | Credits added | Bonus |
| ----- | ------------- | ----- |
| $10   | $10           | -     |
| $25   | $25           | -     |
| $50   | $52.50        | +5%   |

Prices are in USD. Packs and bonuses are set on the **Credits** page in the dashboard, which is the source of truth if these numbers ever change.

***

## How credits work

* **Buy once, use whenever.** Credits are prepaid and never expire.
* **Pay only for what runs.** Credits are spent as your pipelines run models. Only successful runs are charged, so a failed generation costs nothing.
* **Every run is metered.** Each run records its cost, which you can see in [run history](/pipelines/publishing#run-history) and track under **Usage & insights**.
* **Free to start.** New accounts begin with $5 in free credits so you can try model runs before buying.

***

## What's included

Every account gets the full product. There are no feature tiers gated behind a plan:

* All models, with no per-model fees.
* Unlimited pipelines and published API endpoints.
* Guardrails, PII redaction, versioning, run history, and audit export.
* The [Pipeline API](/api/pipeline-api) on every published pipeline.

***

## Enterprise and volume

Building at scale, or need dedicated Treza Enclaves, SSO, or invoicing on net terms instead of prepaid credits? [Contact us](https://trezalabs.com) about a custom agreement.

***

## Related

* [Usage & Billing](/ai-gateway/usage-and-billing) - how runs are counted and metered.
* [Models](/pipelines/models) - the catalog and how model runs spend credits.


# Roadmap


# Overview

## Investors Overview

### Executive Summary

Treza Network is building the privacy infrastructure that will enable the next generation of private DeFi applications. By combining zero-knowledge proofs with hardware-protected enclaves, Treza solves the fundamental tension between regulatory compliance and user privacy—unlocking a **$3+ trillion institutional DeFi opportunity**.

**Key Investment Highlights:**

* **Large Market**: $3T+ institutional capital waiting for compliant DeFi rails
* **Defensible Technology**: zero-knowledge compliance with dual verification modes
* **Regulatory Tailwinds**: Global regulators demanding KYC/AML in DeFi
* **Revenue Model**: Transaction fees, SaaS licensing, attestation services

***

### The Problem

#### DeFi's $3 Trillion Compliance Paradox

Decentralized Finance (DeFi) has proven the technical viability of permissionless financial infrastructure, with **$100B+ in Total Value Locked** at its peak. However, institutional adoption remains elusive due to an unsolvable paradox:

**1. Regulators Demand Identity Verification**

* **KYC/AML Requirements**: Financial institutions cannot legally use anonymous protocols
* **OFAC Sanctions Screening**: Mandatory in most jurisdictions for financial services
* **Travel Rule Compliance**: Required for crypto transactions over $3,000
* **Banking License Requirements**: Impossible to obtain without identity verification

**Result**: Major institutions remain on the sidelines despite interest, limiting DeFi to \~2% of global financial assets.

**2. Users Demand Privacy**

* **Data Breach Risk**: Traditional KYC systems leak sensitive personal information regularly
* **Regulatory Overreach**: Fear of government surveillance and capital controls
* **Competitive Intelligence**: Exposing trading strategies to competitors
* **Identity Theft**: Centralized databases are honeypots for hackers

**Result**: Privacy-conscious users and institutions reject traditional KYC solutions.

**3. Existing Solutions Create Centralization Risk**

Current approaches all involve trade-offs:

| Solution                | Problem                                    | Why It Fails                              |
| ----------------------- | ------------------------------------------ | ----------------------------------------- |
| **Centralized KYC**     | Stores personal data in hackable databases | 500M+ records breached annually           |
| **Permissioned DeFi**   | Requires trusted intermediaries            | Defeats the purpose of decentralization   |
| **No Compliance**       | Legal risk, regulatory crackdowns          | Protocols face shutdown and sanctions     |
| **Oracle-Only Systems** | Single point of failure, trust required    | Centralization risk, potential censorship |

**Market Impact**: An estimated **$3+ trillion** in institutional capital cannot access DeFi infrastructure due to this unsolved compliance-privacy paradox.

***

### The Solution

#### Privacy-Preserving Compliance Infrastructure

Treza Network resolves the compliance-privacy paradox through a revolutionary architecture combining **zero-knowledge proofs** and **hardware-protected enclaves**:

**Core Technology Stack**

**1. Zero-Knowledge Identity Verification**

* **ZKPassport Integration**: Users verify their identity through government-issued documents
* **Proof Generation**: Create cryptographic proofs of compliance attributes (age, country, sanctions status)
* **No Data Storage**: Only proofs stored on-chain, never personal information
* **Selective Disclosure**: Prove "over 18 and not sanctioned" without revealing actual age or nationality

**Technical Innovation**: Users scan their government ID with a mobile app → Zero-knowledge proof generated locally on device → Proof verified through cryptographic validation → Smart contracts verify proof validity without accessing personal data.

**2. Dual Verification System**

Treza offers two verification modes to optimize for different use cases:

| Mode                     | Speed         | Trust Model                | Cost      | Use Case                        |
| ------------------------ | ------------- | -------------------------- | --------- | ------------------------------- |
| **Oracle System**        | 30-60 seconds | Multi-oracle consensus     | \~$7.50   | High-volume DeFi (>1000 tx/day) |
| **Smart Contract**       | 5-10 minutes  | Zero trust (cryptographic) | \~$2.50   | High-value transactions (>$10k) |
| **Attestation**          | Manual review | Professional attesters     | Variable  | Special cases, edge cases       |
| **Hybrid** (Recommended) | Adaptive      | Combined                   | Optimized | Production environments         |

**3. Hardware-Protected Enclaves**

* **Secure Execution**: Run sensitive computations in hardware-isolated environments
* **Multi-Cloud Support**: AWS Nitro Enclaves, Azure Confidential Computing (planned), Intel SGX (planned)
* **Automated Deployment**: One-click deployment with Terraform automation
* **Real-Time Monitoring**: CloudWatch integration for operational visibility

**Developer Experience**: Simple SDK and React components make integration possible in days, not months.


# Deck


# Lite Paper


# Tokenomics

### Overview

`$TREZA` is the native token of the Treza Protocol — a secure transaction execution platform built for crypto teams running high-trust workflows.

As Treza grows, `$TREZA` acts as a coordination layer for platform access, protocol governance, and long-term value alignment between contributors, users, and token holders.

* **Ticker**: `$TREZA`
* **Total Supply**: `100,000,000`
* **Blockchain**: `Ethereum`
* **Trading Fee**: `5%` (can be reduced, never raised)
* **Liquidity Lock**: `48 months`
* **Official Contract Address**: `[ADD CONTRACT]`

***

### Token Allocation

| Category          | Allocation |
| ----------------- | ---------- |
| Team              | 65%        |
| Initial Liquidity | 10%        |
| Marketing         | 10%        |
| R\&D              | 5%         |
| Seed Investors    | 5%         |
| CEX Listing       | 5%         |

***

### Token Utility

Treza’s long-term model aligns token holders with the platform’s trajectory and value creation.

As the protocol scales, token holders represent the stakeholder community with governance rights and economic upside. If the protocol undergoes a future acquisition or structured exit, token governance may provide representation, participation rights, or claim structures — aligning token utility with platform growth.

This structure ensures Treza remains focused on delivering secure infrastructure with real usage — while enabling long-term alignment between the team, community, and stakeholders.

***

### Security & Vesting

**Multi-Sig Protection**\
All protocol-owned wallets—including treasury, liquidity, and marketing—are secured with multi-signature authorization, ensuring no single party can access or move funds unilaterally.

**Team Token Vesting**\
Team allocations are subject to a 48-month linear vesting schedule, promoting long-term alignment and commitment.


# Token Utility

### `$TREZA` Value Proposition

`$TREZA` is the native asset of the Treza execution platform — powering secure, high-trust transaction workflows for crypto-native teams.

It aligns usage, governance, and long-term platform value. Token holders represent the core stakeholder group that grows alongside Treza’s adoption and strategic evolution.

***

### Core Token Utility

#### 1. Governance Participation

* `$TREZA` holders participate in protocol governance.
* Decisions may include:
  * Feature prioritization
  * Treasury allocation
  * Policy setting for usage tiers or access control
  * Roadmap and upgrade approval

#### 2. Ecosystem Incentives

* Treza may issue `$TREZA` to developers, researchers, and partners who contribute meaningfully to the platform.
* This includes building new integrations, deploying strategic workflows, or expanding Treza’s footprint within the crypto ecosystem.

#### 3. Platform Access

* Certain advanced features — including high-throughput execution, private enclave access, or premium integrations — may require holding or staking `$TREZA`.
* This aligns user commitment with platform usage, ensuring that long-term participants benefit most from protocol growth.

***

### Value Accrual Model

Treza’s model is usage-driven, access-oriented, and designed for long-term alignment between the protocol and its stakeholders.

#### Demand Through Usage

* As more teams use Treza to secure and automate on-chain activity, demand for platform access increases.
* Holding or staking `$TREZA` may be required to unlock higher tiers of usage or advanced infrastructure access.

#### Participation in Growth

* Token holders help guide the protocol’s evolution — and may benefit from future models that reflect their early alignment.
* In a structured exit or liquidity event, governance rights may translate into representation, participation, or distribution — aligning `$TREZA` with Treza’s long-term success.

***

### Compliance & Future Unlocks

Treza is built with a compliance-first approach, preparing for a world of maturing digital asset regulation.

* **Flexible Legal Architecture**\
  The token structure allows for evolving participation models, including governance-based access, community ownership, and value-sharing — pending legal clarity.
* **Future Utility Paths**\
  Potential unlocks may include:
  * Token-gated services
  * On-chain rewards or dividends
  * Structured distributions or tiered access models
* **Early Supporter Priority**\
  Early holders will be prioritized for any future value-sharing or participation mechanisms as they become legally viable.

***

### Strategic Vision

`$TREZA` is the core coordination asset of the Treza platform. It enables access, governs the protocol, and aligns the stakeholder community around shared growth.

In a world where secure execution is a competitive edge, `$TREZA` represents a long-term stake in the infrastructure powering the next generation of crypto workflows.


# $TREZA

### Treza Tokenomics ($TREZA)

The $TREZA token is the native asset of the Treza Protocol, serving as a fundamental coordination layer for platform access, protocol governance, and the alignment of long term value among contributors, users, and token holders. Its design is integral to the economic security and operational efficiency of the entire ecosystem.

### Token Details

* **Total Supply**: 100,000,000 $TREZA. This represents a hard cap, indicating a non-inflationary design.
* **Blockchain**: Ethereum, selected for its robust security, extensive developer community, and broad compatibility within the decentralized finance (DeFi) ecosystem.
* **Trading Fee**: A 5% fee is applied to transactions, a parameter that can be reduced through governance but never increased. The specific purpose of this fee (e.g., contributing to a treasury, supporting a burn mechanism) will be elaborated in subsequent documentation.
* **Liquidity**: Initial liquidity is subject to a 48-month lock, demonstrating a commitment to stability and long-term project viability.

### Token Allocation

The total supply of $TREZA is strategically allocated to ensure the long-term sustainability, growth, and equitable distribution within the Treza Protocol. This transparent allocation model is crucial for building trust and providing clarity to all stakeholders.

| Category          | Percentage (%) | Token Amount ($TREZA) |
| ----------------- | -------------- | --------------------- |
| Team              | 65%            | 65,000,000            |
| Initial Liquidity | 10%            | 10,000,000            |
| Marketing         | 10%            | 10,000,000            |
| Strategic Sale    | 5%             | 5,000,000             |
| Operations        | 5%             | 5,000,000             |
| R\&D              | 5%             | 5,000,000             |

This table provides a clear visual representation of the token distribution, enhancing transparency and enabling rapid comprehension of the economic structure by potential investors and community members.

### **Security and Vesting**

Security and vesting schedules are paramount aspects of the $TREZA tokenomics, designed to ensure stability, transparency, and long-term commitment.

* All protocol-owned wallets are secured via multi-signature wallets to ensure transparency and prevent unilateral access, providing a robust layer of protection against single points of failure.
* Investor tokens are 100% unlocked and vested linearly over 6 months, ensuring a controlled and predictable release into the market.
* Ecosystem grants and incentives are distributed based on impact and community contribution, subject to appropriate vesting schedules to promote sustained long-term engagement and discourage short-term speculation.
* Node rewards for Compute Providers are distributed over an 18-month period, based on network utilization and compute task volume. This incentivizes consistent and valuable contributions from Compute Providers, aligning their economic interests with the network's health and growth.

Vesting schedules for the team, ecosystem, and node rewards are more than just mechanisms for token distribution; they are powerful commitment mechanisms. Longer vesting periods for core contributors and node operators signal a long-term alignment of incentives, significantly reducing the risk of "pump-and-dump" schemes or early abandonment of the project. This fosters confidence among investors and users, assuring them that the project's success is tied to sustained effort and network growth, rather than short-term gains. This directly contributes to the economic security of the protocol by incentivizing honest and consistent participation from all key stakeholders.


# Fees

## Anti-Sniping Launch Protections

To ensure a fair token distribution at launch and prevent sniper bots from gaining an unfair advantage, a tiered system of temporary trading fees and wallet size limits has been implemented.

### Time-Based Protection Phases

| Time Since Launch | Trading Fee | Max Wallet Size (% of Total Supply) |
| ----------------- | ----------- | ----------------------------------- |
| 0–1 minute        | 40%         | 0.10%                               |
| 1–5 minutes       | 30%         | 0.15%                               |
| 5–8 minutes       | 20%         | 0.20%                               |
| 8–15 minutes      | 10%         | 0.30%                               |

### After 15 Minutes

* **Trading fee** is reduced to **5%**
* **All wallet size limits are removed**

***

### Simple, Transparent Fee Structure

Treza uses a transparent trading fee model designed to bootstrap protocol development, reward early contributors, and support long-term sustainability.

* **Trading Fee**: &#x35;**% on all buys and sells**
* **Fee can be lowered, but never raised**

This structure ensures predictability for users and contributors while giving the community flexibility to reduce fees over time through governance.

***

### Why a Trading Fee?

The trading fee serves several purposes:

* **Bootstrap Protocol Growth**\
  Early activity helps fund core development, infrastructure, and ecosystem incentives.
* **Incentivize Early Supporters**\
  Revenue generated during the early phase is used to grow the protocol and build long-term value.
* **Sustainability Without Inflation**\
  Rather than issuing new tokens to fund operations, Treza uses trading fees to support growth — with no emissions or dilution.

***

### Fee Reduction Plan

While the trading fee starts at 5%, it may be reduced over time as the protocol hits major usage or adoption milestones.

* **Governance-Controlled**\
  Any fee reductions will be voted on by `$TREZA` holders.
* **Never Increased**\
  The fee can **only go down**, ensuring long-term predictability and user trust.

***

### Fee Allocation

Fees collected from trading are used to support:

* Protocol development
* Treasury growth
* Strategic ecosystem grants
* Community and marketing efforts

All funds are held in a **transparent, multi-signature treasury** and governed by the community. Treasury usage is tracked on-chain and auditable by anyone.

***

### Time-Based Anti-Sniper Launch Mechanism

* Phase 1 (0-1min): 40% fee, 0.10% max wallet
* Phase 2 (1-5min): 30% fee, 0.15% max wallet
* Phase 3 (5-8min): 20% fee, 0.20% max wallet
* Phase 4 (8-15min): 10% fee, 0.30% max wallet
* Normal (15+min): 5% fee, no max wallet

***

### Strategic Vision

Treza’s trading fee model is simple, fair, and aligned with long-term sustainability:

* Starts at &#x35;**%**
* Can be lowered, never raised
* Used to fund core protocol growth
* Fully governed and transparent

As adoption increases, `$TREZA` holders will have the power to reduce fees — ensuring that long-term users benefit from lower costs while early contributors help bootstrap the future of secure crypto execution.


# Terms Of Service

**Effective Date: July 11, 2026**\
Welcome to **Treza** ("Company," "we," "our," or "us"). These Terms of Service ("Terms") govern your access to and use of our platform, available at trezalabs.com and app.trezalabs.com (collectively, the "Service"). By accessing or using the Service, you agree to be bound by these Terms.

{% hint style="info" %}
This document describes how the Service works today. It is provided for transparency and is not a substitute for legal advice. Please review it with your own counsel before relying on it.
{% endhint %}

***

#### 1. The Service

Treza is a platform for building generative-media pipelines. You wire AI models, tools, and guardrails together on a visual canvas, run them to generate video, images, and text, and can publish a pipeline as an HTTP API that you or your applications call. The Service is offered on an ongoing basis and its features may change over time.

***

#### 2. Accounts and API Keys

You need an account to use the Service. You are responsible for your account credentials and API keys, and for all activity that occurs under them. Treza API keys (`treza_live_...`) are secrets: keep them confidential, do not embed them in client-side code, and revoke any key you believe has been exposed. See [API Keys](/api/api-keys).

***

#### 3. Models and Third-Party Providers

The Service runs your prompts and content through third-party model and infrastructure providers, which may include, but are not limited to:

* Google (including Veo and Gemini models, and the YouTube Data API v3 when you connect a YouTube channel)
* TikTok (including the TikTok Content Posting API when you connect a TikTok account)
* OpenAI (including Sora models)
* Anthropic
* DeepSeek, Qwen, Meta (Llama), Mistral, and other open-model providers
* Together, OpenRouter, Fireworks, and Hugging Face
* Amazon Web Services (AWS)
* Stripe
* Vercel
* Privy

We do not control the accuracy, availability, or reliability of these providers, and Treza is not responsible for their outputs, errors, or downtime. Your use of a particular model or integration may also be subject to that provider's own terms and usage policies, and you agree to comply with them.

***

#### 4. Connected YouTube Accounts

The Service optionally lets you connect one or more YouTube channels you own through Google OAuth (YouTube Data API v3). This feature is optional. If you use it:

* **Your authorization.** You authorize Treza to upload videos you generate in the Service to the YouTube channel(s) you select. Uploads occur only when you run a pipeline or otherwise initiate a publish action; Treza does not post to your channel without your direction.
* **Your obligations.** You are solely responsible for videos published to your channel, including compliance with [YouTube's Terms of Service](https://www.youtube.com/t/terms), [Community Guidelines](https://www.youtube.com/howyoutubeworks/policies/community-guidelines/), and applicable copyright and privacy laws. You must only publish content you have the rights to distribute.
* **Scopes.** We request only the OAuth scopes required for this feature: `youtube.upload` (upload videos you generate) and `youtube.readonly` (read basic metadata for channels you own, such as channel name and avatar, so you can confirm the publish target).
* **Limited use.** Treza does not edit, delete, or manage your existing YouTube videos, comments, analytics, channel memberships, or broader Google account settings through this integration.
* **Third-party terms.** Your use of YouTube is also governed by Google's terms and privacy policies. Treza is not affiliated with, endorsed by, or sponsored by Google or YouTube.
* **Disconnect.** You can disconnect a YouTube channel at any time in Settings → Connected accounts. Disconnecting removes Treza's ability to publish to that channel on your behalf going forward.

***

#### 5. Connected TikTok Accounts

The Service optionally lets you connect one or more TikTok accounts you own through TikTok OAuth (TikTok Content Posting API). This feature is optional. If you use it:

* **Your authorization.** You authorize Treza to publish videos you generate in the Service to the TikTok account(s) you select. Posts occur only when you run a pipeline or otherwise initiate a publish action; Treza does not post to your account without your direction.
* **Your obligations.** You are solely responsible for videos published to your account, including compliance with [TikTok's Terms of Service](https://www.tiktok.com/legal/terms-of-service), [Community Guidelines](https://www.tiktok.com/community-guidelines), and applicable copyright, music-licensing, and privacy laws. You must only publish content you have the rights to distribute. By posting through the Service, you agree that your content complies with TikTok's requirements, including TikTok's music-usage and branded-content rules where applicable.
* **Scopes.** We request only the OAuth scopes required for this feature: `video.publish` (publish videos you generate via Direct Post) and `user.info.basic` (read basic profile metadata such as display name, username, and avatar so you can confirm the publish target and show allowed privacy options).
* **Limited use.** Treza does not edit, delete, or manage your existing TikTok videos, comments, analytics, followers, or broader TikTok account settings through this integration.
* **Privacy and interaction settings.** Before publishing, the Service queries TikTok for your account's allowed privacy levels and interaction settings (such as comments, duet, and stitch). You choose the visibility and interaction options for each post; Treza does not post without your explicit confirmation in the publish flow.
* **Developer audit.** Until Treza's TikTok developer application passes TikTok's content-posting audit, TikTok may restrict posts from unaudited integrations to private visibility (`SELF_ONLY`) regardless of the visibility you select. Treza is not responsible for TikTok-imposed visibility limits during audit or testing.
* **Third-party terms.** Your use of TikTok is also governed by TikTok's terms and privacy policies. Treza is not affiliated with, endorsed by, or sponsored by TikTok or ByteDance.
* **Disconnect.** You can disconnect a TikTok account at any time in Settings → Connected accounts. Disconnecting removes Treza's ability to publish to that account on your behalf going forward.

***

#### 6. Your Content and Generated Output

* **Inputs.** You retain all rights to the prompts, files, and other content you submit ("Inputs").
* **Outputs.** As between you and Treza, and to the extent permitted by law and by the applicable model provider's terms, you own the video, images, text, and other content you generate ("Outputs"). Because of the nature of generative models, Outputs may not be unique, and similar or identical content may be generated for other users.
* **Responsibility.** You are responsible for your Inputs and Outputs and for ensuring you have the rights necessary to use them. You must not submit content you do not have the rights to use, or generate content that infringes, is unlawful, or otherwise violates these Terms.
* **License to operate.** You grant Treza the limited rights needed to operate the Service, namely to process, store, and transmit your Inputs and Outputs to and from the providers above in order to run your pipelines and provide the Service to you.

***

#### 7. Acceptable Use

You agree not to use the Service to:

* Generate or distribute unlawful content, or content that infringes the intellectual property or privacy rights of others.
* Create child sexual abuse material or any content that sexualizes minors.
* Create non-consensual, deceptive, or defamatory impersonations or "deepfakes" of real people.
* Harass, threaten, or defraud others, or generate malware or other harmful code.
* Reverse-engineer, exploit, overload, or attempt to gain unauthorized access to the Service.
* Violate the usage policies of any underlying model provider.

We may suspend or terminate accounts that violate this section.

***

#### 8. Fees, Credits, and Payment

* **Prepaid credits.** The Service is paid for with prepaid credits, purchased through Stripe. There is no subscription or recurring charge. Enterprise may instead be billed under a separate written agreement.
* **Model usage.** Model runs are paid for from your prepaid credit balance. Only successful runs are charged.
* **Credits.** Credits are prepaid and are non-refundable except where required by law. Charges are final and we do not provide refunds except where required by law.
* **Changes.** We may modify pricing, credit packs, or credit terms, with notice for material changes. See the [pricing page](https://trezalabs.com/pricing).

***

#### 9. Guardrails and Data Handling

The Service offers guardrail and redaction features to help you handle sensitive data. These features are provided to assist you, but they do not guarantee compliance with any law or standard, and you remain responsible for meeting your own regulatory and contractual obligations. You are responsible for not submitting sensitive data you are not permitted to process.

***

#### 10. Intellectual Property

The Service, including its software, design, and content (excluding your Inputs and Outputs), is owned by Treza and protected by intellectual property laws. These Terms do not grant you any right to our trademarks or branding.

***

#### 11. Disclaimers

The Service is provided "AS IS" and "AS AVAILABLE" without warranties of any kind, whether express or implied. We do not warrant that the Service will be uninterrupted, error-free, or that any Output will be accurate, appropriate, or fit for a particular purpose.

***

#### 12. Limitation of Liability

To the maximum extent permitted by law, Treza is not liable for any indirect, incidental, special, consequential, or punitive damages, or for any loss of profits, data, or goodwill, arising from your use of the Service. Our total liability for any claim arising out of or relating to the Service is limited to the amounts you paid us for the Service in the three months preceding the event giving rise to the claim.

***

#### 13. Termination

You may stop using the Service at any time. We may suspend or terminate your access if you violate these Terms or to protect the Service. Provisions that by their nature should survive termination will survive.

***

#### 14. Changes to These Terms

We may update these Terms from time to time. If we make significant changes, we will notify you through the Service or by other means. Your continued use of the Service after any modifications constitutes acceptance of the updated Terms.

***

#### 15. Contact Information

If you have any questions about these Terms, please contact us at: <hello@trezalabs.com>

***

By accessing or using Treza, you acknowledge that you have read, understood, and agree to these Terms of Service.


# Privacy Policy

**Effective Date: July 11, 2026**\
Welcome to **Treza** ("Company," "we," "our," or "us"). This Privacy Policy explains how we collect, use, disclose, and protect your information when you use our platform for building and running generative-media pipelines, available at trezalabs.com (collectively, the "Service"). By accessing or using the Service, you agree to the collection and use of information in accordance with this Privacy Policy.

{% hint style="info" %}
This document describes how the Service handles data today. It is provided for transparency and is not a substitute for legal advice. Please review it with your own counsel before relying on it.
{% endhint %}

***

#### 1. Information We Collect

We collect the following types of information:

**Account Information:** When you create an account or contact us, we collect information such as your name, email address, authentication identifiers, and payment details. Authentication is handled by our identity provider (Privy).\
**Pipeline Content:** We process the prompts, files, and other content you submit ("Inputs"), the pipelines (graphs of nodes) you build, and the video, images, text, and other content you generate ("Outputs"). We also store run history, including per-node timing, token and credit usage, and status.\
**Usage Data:** We collect data on how you interact with the Service, including IP address, browser type, device information, pages visited, API requests, and timestamps.\
**API Keys and Secrets:** We store the provider keys and secrets you add to the Service in encrypted form so your pipelines can run. Treza API keys (`treza_live_...`) are stored hashed.\
**Connected YouTube Accounts (optional):** If you choose to connect a YouTube channel, we receive and store your YouTube channel identifier, channel display name, channel handle or custom URL, channel avatar URL, and an OAuth refresh token that we encrypt and store server-side. We use this information only to display your connected channel(s) in the Service and to upload videos to your channel when you instruct the Service to do so. We do not access your YouTube watch history, private analytics, comments, playlists, subscriptions, or other Google account data beyond this channel metadata.\
**Connected TikTok Accounts (optional):** If you choose to connect a TikTok account, we receive and store your TikTok open identifier, display name, username, avatar URL, and an OAuth refresh token that we encrypt and store server-side. We use this information only to display your connected account(s) in the Service, query allowed publish settings from TikTok, and publish videos when you instruct the Service to do so. We do not access your TikTok watch history, private analytics, direct messages, followers list, or other TikTok account data beyond this basic profile metadata.

***

#### 2. Third-Party Model and Infrastructure Providers

To run your pipelines, the Service transmits your Inputs and Outputs to third-party model and infrastructure providers, which may include, but are not limited to:

* Google (including Veo and Gemini models, and the YouTube Data API v3 when you connect a YouTube channel)
* TikTok (including the TikTok Content Posting API when you connect a TikTok account)
* OpenAI (including Sora models)
* Anthropic
* DeepSeek, Qwen, Meta (Llama), Mistral, and other open-model providers
* Together, OpenRouter, Fireworks, and Hugging Face
* Amazon Web Services (AWS)
* Pinecone
* Stripe (payments)
* Privy (authentication)
* Vercel (hosting)

These services process data according to their own privacy policies and terms. We do not control how third-party providers handle data once it is transmitted to them, and your use of a particular model or integration may be subject to that provider's policies.

***

#### 2.1 YouTube Data (when you connect a channel)

If you connect a YouTube channel, Treza accesses Google user data through the YouTube Data API v3 subject to the [Google API Services User Data Policy](https://developers.google.com/terms/api-services-user-data-policy), including its Limited Use requirements.

We access and use this data as follows:

* **Channel ID, title, handle, and thumbnail** — to show which channel is connected and let you select a publish target. Stored while the channel remains connected.
* **OAuth refresh token** — to obtain short-lived access tokens when you initiate an upload. Stored in encrypted form while the channel remains connected.

We use YouTube and Google user data only to provide the connected-account and video-upload features you request. We do not use it for advertising, sell it, or use it to train models. We share it only with Google as necessary to perform uploads you request and with infrastructure providers (such as AWS) solely to operate the Service.

You can disconnect a YouTube channel at any time in Settings → Connected accounts, which deletes Treza's stored OAuth credentials for that channel. You can also revoke Treza's access in your [Google Account permissions](https://myaccount.google.com/permissions).

***

#### 2.2 TikTok Data (when you connect an account)

If you connect a TikTok account, Treza accesses TikTok user data through the TikTok Content Posting API subject to [TikTok's developer terms](https://developers.tiktok.com/doc/terms-and-conditions) and applicable TikTok policies.

We access and use this data as follows:

* **Open ID, display name, username, and avatar** — to show which TikTok account is connected and let you select a publish target. Stored while the account remains connected.
* **Creator publish settings** (such as allowed privacy levels and interaction toggles) — queried from TikTok when you configure or confirm a publish action, so the Service can present only options TikTok allows for your account. Not stored beyond what is needed for the active publish flow.
* **OAuth refresh token** — to obtain short-lived access tokens when you initiate a publish. Stored in encrypted form while the account remains connected. TikTok may rotate refresh tokens; we store the latest token TikTok issues.

We use TikTok user data only to provide the connected-account and video-publishing features you request. We do not use it for advertising, sell it, or use it to train models. We share it only with TikTok as necessary to perform publishes you request and with infrastructure providers (such as AWS) solely to operate the Service.

You can disconnect a TikTok account at any time in Settings → Connected accounts, which deletes Treza's stored OAuth credentials for that account. You can also revoke Treza's access in your TikTok account settings or through TikTok's connected-apps controls where available.

***

#### 3. How We Use Your Information

We use your information to:

* Provide, maintain, and improve the Service
* Execute your pipelines and return generated Outputs
* Connect YouTube channels and publish videos you generate, when you choose to use that feature
* Connect TikTok accounts and publish videos you generate, when you choose to use that feature
* Process transactions and manage prepaid credits and payments
* Maintain run history, usage insights, and audit records
* Monitor usage and security, and detect fraud, abuse, or violations of our Terms of Service
* Comply with legal obligations and enforce our Terms of Service

We do not use your Inputs or Outputs to train our own models.

***

#### 4. Data Retention and Deletion

We retain collected data for as long as necessary to provide the Service or as required by law. Run history and generated assets are retained so you can access them from your account, and you can delete pipelines and assets from the dashboard. Connected YouTube channel credentials and metadata are retained until you disconnect the channel in Settings → Connected accounts or revoke access in your Google Account. Connected TikTok account credentials and metadata are retained until you disconnect the account in Settings → Connected accounts or revoke Treza's access through TikTok.

You may request deletion of your personal data by contacting [**hello@trezalabs.com**](mailto:hello@trezalabs.com), subject to our legal and contractual obligations. Some information may be retained where required for legal, accounting, or security purposes.

***

#### 5. Data Sharing and Disclosure

We do not sell your personal data. We may share data with:

**Service Providers:** Third-party providers that help us operate the Service, including the model, hosting, authentication, and payment providers listed above.\
**Legal Compliance:** If required by law, we may disclose information to law enforcement or regulatory authorities.\
**Business Transfers:** In the event of a merger, acquisition, or sale of assets, your information may be transferred as part of that transaction.

***

#### 6. Security

We implement reasonable technical and organizational measures to protect your data, including encryption of stored secrets, provider keys, and OAuth refresh tokens for connected YouTube and TikTok accounts. However, no system is completely secure, and we cannot guarantee absolute security. You are responsible for keeping your account credentials and Treza API keys confidential and for not embedding them in client-side code.

***

#### 7. Your Content and Generated Output

You retain your rights to your Inputs, and, to the extent permitted by law and the applicable model provider's terms, you own your Outputs. Because of the nature of generative models, Outputs may not be unique. Generative models can also produce inaccurate content, and you should verify Outputs before relying on them. See our [Terms of Service](/terms-and-privacy/terms-of-service) for details on content ownership and acceptable use.

***

#### 8. Your Rights

Depending on your jurisdiction, you may have the right to:

* Access, update, or delete your personal information
* Object to or restrict certain processing of your data
* Request a portable copy of your data
* File a complaint with a regulatory authority

To exercise these rights, please contact [**hello@trezalabs.com**](mailto:hello@trezalabs.com).

***

#### 9. International Data Transfers

The Service and its providers may process and store data in countries other than your own. Where we transfer personal data across borders, we take steps to ensure it receives an appropriate level of protection consistent with applicable law.

***

#### 10. Children's Privacy

The Service is not directed to children under 13 (or the minimum age required in your jurisdiction), and we do not knowingly collect personal information from them. If you believe a child has provided us with personal information, please contact us so we can delete it.

***

#### 11. Changes to This Privacy Policy

We may update this Privacy Policy from time to time. If we make significant changes, we will notify you through the Service or by other means. Your continued use of the Service after any modifications constitutes acceptance of the updated Privacy Policy.

***

#### 12. Contact Information

If you have any questions about this Privacy Policy, please contact us at: [**hello@trezalabs.com**](mailto:hello@trezalabs.com)

***

By accessing or using Treza, you acknowledge that you have read, understood, and agree to this Privacy Policy.


# SOC 2 Compliance

Treza is designed to handle sensitive tasks — from delegated key access to autonomous execution — which is why security, privacy, and operational integrity are core to our infrastructure. As part of our long-term commitment to enterprise-grade trust, we are actively working toward **SOC 2 compliance**.

***

### What is SOC 2?

SOC 2 (System and Organization Controls 2) is a leading security and compliance framework developed by the American Institute of CPAs (AICPA). It assesses how a service provider handles customer data across five key trust principles:

* **Security**
* **Availability**
* **Processing Integrity**
* **Confidentiality**
* **Privacy**

***

### Our Path to Compliance

* **Status:** SOC 2 Type I process initiated
* **Partner:** Currently finalizing with a third-party auditor
* **Scope:** Treza's execution infrastructure, agent access systems, key management protocols, and monitoring services
* **Timeline:** Aiming to complete Type I certification prior to public rollout of enterprise and institutional features
* **Type II Assessment:** Scheduled for post-launch operational maturity (ongoing control verification)

***

### Transparency Commitment

Once certification is complete, we will:

* Publish a summary report and audit letter
* Share documentation on security practices for enterprise users
* Update this page with status and compliance updates

***

> Autonomous agents need secure foundations. SOC 2 is a key step in scaling Treza to support institutional-grade use cases across crypto, finance, and beyond.


