root@tessorium:~/protocol$_
v2.2_STABLERFC_COMPLIANT

Tessorium Trust Protocol

When your agent calls an API, tool, or another agent — how do you know it's safe? TTP is the cryptographic trust layer that answers that question before anything happens.

We verify identity. Enforce policy. Block unauthorized actions. And record everything in tamper-proof audit trails that satisfy SOC 2, HIPAA, and the EU AI Act.

What is TTP?

"Just as TLS secures human-to-server connections, TTP secures agent-to-world interactions."

The Tessorium Trust Protocol (TTP) enables any AI agent to verify identity, check reputation, and establish trust before interacting with APIs, tools, or other agents. Using cryptographic proofs and decentralized attestations, TTP provides the missing trust layer for autonomous AI systems — with human oversight and instant revocation built in.

TTP_Universal_Trust_Flow
YOUR AI AGENT
Any outbound request
TTP TRUST LAYER
1. VERIFY
Ed25519 Identity
2. DECIDE
TRE + SPL Policy
3. ENFORCE
Allow / Block
4. AUDIT
ETR Merkle Tree
A2A
Agents
A2H
Humans
A2T
Tools
A2S
Services
A2R
Resources
A2API
External APIs
Same trust flow. Same enforcement. Same audit trail.

Protocol Components

TTP_Component_Stack
N-Party ConsensusMulti-agent coordination with BFT (n ≥ 3f+1)
• Coordinator Election (trust-weighted)
• Propose-Vote-Commit (2/3 majority)
• Byzantine Detection & View-Change
ETR - Execution Trace ReporterTamper-evident audit trails
• SHA-256 Merkle Trees
• Inclusion & Consistency Proofs (RFC 9162)
• Signed Tree Heads (STH) for verification
TRE - Trust Reasoning EngineMulti-factor risk assessment
• Identity Factor
• Reputation Factor
• Fraud Factor
• Behavioral Factor
Decision: ALLOW (low risk) | WARN (medium risk) | DENY (high risk)
SPL/PNP - Security Policy & Negotiation
• SPL: JSON schema for requirements & rules (50KB max, 1000 rules)
• PNP: 8-state machine (max 3 rounds, 30s timeout)
Trust CalculatorV1.0 Three-component trust computation
• Identity Score (0-40)
• Reputation Score (0-35)
• Behavioral Score (0-25)
Weighted attestations • Anti-gaming detection • Max score: 100
Handshake ProtocolCryptographic identity verification
• Ed25519 challenge-response
• X25519 key exchange
• Session token generation
• Forward secrecy
P2P Network Layerlibp2p (Hybrid & P2P modes)
• Transport: WebSockets + QUIC
• Discovery: Kademlia DHT
• Messaging: GossipSub v1.1
• Encryption: Noise (XX pattern)
Cryptographic Foundation
• Ed25519 Signatures (RFC 8032)
• X25519 Key Exchange
• SHA-256 Hashing (FIPS 180-4)
• JCS Canonicalization (RFC 8785)
• DID:ttp Method

Design Principles

TTP is built on ten core principles that guide every design decision:

🔐

Zero Trust by Default

Every interaction requires verification. No implicit trust based on network location or previous interactions.

🆔

Cryptographic Identity

All identities backed by Ed25519 key pairs. DIDs enable self-sovereign, decentralized identification.

📊

Three-Component Trust

Trust Score = Identity (0-40) + Reputation (0-35) + Behavioral (0-25). Multi-signal assessment, not single-factor.

🚫

Prevention First

Block unauthorized actions BEFORE execution. Not just logging—active enforcement via TRE decisions.

🔄

Flexible Deployment

Three modes to fit your needs: Cloud API for quick starts, Hybrid for caching, or full P2P for decentralization.

🌍

Framework Agnostic

Works with any AI framework, language, or platform. REST API, SDK, and P2P interfaces available.

🔒

Privacy by Design

Minimal data exposure. No PII in attestations. Agents control what reputation data they share.

Sub-100ms Performance

Trust decisions in under 100ms. Local caching, parallel verification, and optimized cryptography.

📋

Auditable by Design

Every action recorded in Merkle tree traces. Signed attestations provide non-repudiation and accountability.

🛡️

Byzantine Fault Tolerant

N-party consensus tolerates malicious actors. Anti-gaming detection protects reputation integrity.

Why Use TTP?

For Agent Developers

  • Verify APIs, tools, and agents before use
  • Build reputation from successful interactions
  • Declarative security policies with SPL
  • Audit trails with tamper-evident traces

For Security & Compliance

  • Block unauthorized actions before execution
  • EU AI Act Article 14 human oversight ready
  • Tamper-evident Merkle tree audit trails
  • Cryptographic proof for every decision

For Enterprises

  • Audit-ready in 30 days with managed deployment
  • Unified governance across all 6 interaction types
  • Anti-gaming protection with fraud detection
  • Tiered revocation with appeals for fairness

Problems Solved

See how TTP transforms AI interactions from risky to secure:

Identity Spoofing
BEFORE

Anyone can claim to be any agent. No way to prove identity. Easy impersonation attacks.

WITH_TTP

Verify identity via Ed25519 challenge-response. DIDs tied to cryptographic keys. Spoofing impossible.

Capability Negotiation
BEFORE

Hardcode permissions with all-or-nothing access. No control over what agents can do.

WITH_TTP

Define requirements with SPL policies. Negotiate capabilities via PNP before any action executes.

Rogue Agent Prevention
BEFORE

No way to stop unauthorized actions. Agents execute freely. Discover breaches after damage is done.

WITH_TTP

Block unauthorized requests in under 100ms. TRE evaluates every interaction. Prevention, not detection.

Kill Switch & Human Oversight
BEFORE

When an agent goes rogue, you're powerless. Watch it exfiltrate data, hoping to pull the plug in time.

WITH_TTP

Terminate agents instantly via kill switch (<50ms). Human operators intervene anytime. EU AI Act Article 14 compliant.

Supply Chain Attacks
BEFORE

Malicious skills, tools, or MCP plugins can compromise your agent silently.

WITH_TTP

Verify publisher reputation and trust score before loading any dependency. A2T protection built-in.

Sybil & Gaming Attacks
BEFORE

Anyone can create fake accounts, pump ratings, and manipulate trust scores.

WITH_TTP

Enforce identity verification. Detect collusion with weighted attestations and anti-gaming analysis.

Multi-Agent Coordination
BEFORE

No standard protocol. Hard to reach consensus. Vulnerable to byzantine actors.

WITH_TTP

Coordinate via N-Party consensus with BFT guarantees. Elect coordinators. Issue commit certificates.

Behavioral Anomalies
BEFORE

No visibility into agent behavior. Compromised agents act normally until it's too late.

WITH_TTP

Detect anomalies via Behavioral Score (0-25). Track uptime, error rates, latency patterns in real-time.

Compliance & Audit
BEFORE

No proof of what happened. Manual logs. Regulators ask questions you can't answer.

WITH_TTP

Prove every action with tamper-proof Merkle tree traces (RFC 9162). EU AI Act audit-ready.

Data Leakage / DLP
BEFORE

Agents can return sensitive data in responses. PII, PHI, and secrets leak without detection.

WITH_TTP

Filter outputs with DLP rules. Redact PII automatically. Block prohibited data transfers at the gateway.

Shadow AI Discovery
BEFORE

No inventory of agents. Shadow AI operates in the dark, accessing data you can't see.

WITH_TTP

Discover every agent with Shadow AI Audit. Map data access patterns. Reveal compliance gaps.

Revocation Propagation
BEFORE

Revoking an agent is slow and inconsistent. Some systems still trust it hours later.

WITH_TTP

Propagate revocations via P2P network in under 500ms. Block all future requests immediately.

Deployment Modes

TTP supports three deployment modes. Most enterprise customers deploy Hybrid for the best balance of performance and compliance.

Hybrid

RECOMMENDED

Local cache + gateway fallback. Sub-5ms local checks with global reputation sync.

  • • Latency: <5ms cached, 50-200ms uncached
  • • Kill switch + audit trails included
  • • Best for: Enterprise production, regulated workloads

Cloud API

Managed REST API. Quick integration for pilots and development environments.

  • • Latency: 50-200ms
  • • No infrastructure to manage
  • • Best for: Pilots, non-regulated workloads

P2P

Full decentralization via libp2p. Complete data sovereignty with no external dependencies.

  • • Latency: 100-500ms
  • • Zero server dependency
  • • Best for: Air-gapped, sovereign deployments

Migration Path

Start with Cloud API during your pilot, move to Hybrid for production compliance, and adopt P2P for air-gapped or sovereign requirements. Our team guides you through each transition.

Integration Patterns

Choose the integration pattern that fits your architecture. Gateway and Sidecar are the fastest paths to production for existing agents.

Gateway / Proxy

ZERO CODE

Deploy TTP as an API gateway in front of existing agents. Enforce policies, log every interaction, and kill rogue agents—all without touching your code.

  • • Intercepts all agent traffic
  • • Kill switch + audit trails built-in
  • • Best for: Existing agents, audit-ready in 30 days

Sidecar

ZERO CODE

Deploy TTP as a sidecar container alongside your agent. Transparent enforcement in your service mesh—automatic injection, no code changes.

  • • Kubernetes-native deployment
  • • Service mesh compatible (Istio, Linkerd)
  • • Best for: Cloud-native, microservices

SDK Integration

Direct library integration into your agent code. Block unauthorized actions at the source with sub-5ms trust checks.

  • • TypeScript/Python SDKs available
  • • Full control over trust decisions
  • • Best for: New agents, green-field projects

MCP Server

Run TTP as an MCP server for Claude Desktop, Cursor, and other MCP-enabled clients. Trust verification as a native tool.

  • • Native Claude/Cursor integration
  • • Verify tools before execution
  • • Best for: LLM apps, AI assistants

Not Sure Which Pattern?

All patterns support the same trust protocol—prevention, audit trails, and kill switch. Mix and match based on your agent types.Book a consultation and we'll architect the right solution for your environment.

Interaction Modes

TTP supports six interaction modes covering all trust relationships in the AI ecosystem. Each mode uses the same core protocol (Verify → Decide → Enforce → Audit) adapted for its specific use case.

Universal Trust Model (V1.0)

Trust Score = Identity (0-40) + Reputation (0-35) + Behavioral (0-25)

All agents have a trust score regardless of interaction mode. Identity is verified via Ed25519 challenge-response. Reputation accumulates from peer attestations. Behavioral tracks uptime, error rates, and policy compliance.

Agent-to-Agent (A2A)

Secure multi-agent collaboration with full audit trails

Full peer-to-peer trust with bidirectional verification, mutual ratings, and policy negotiation.

  • • Challenge-response handshake
  • • Bidirectional ratings
  • • SPL/PNP negotiation

Agent-to-Human (A2H)

EU AI Act Article 14 human oversight compliance

Human-in-the-loop oversight for high-risk decisions with review queues and escalation tiers.

  • • Risk-triggered review queue
  • • APPROVE / DENY / MODIFY
  • • Tiered escalation (L1→L3)

Agent-to-Tool (A2T)

Prevent supply chain attacks with publisher verification

Trust verification for skills, tools, and MCP plugins via publisher chain and package signatures.

  • • Publisher trust chain
  • • Circuit breaker + DLP
  • • Sandbox tiers (T0-T3)

Agent-to-Service (A2S)

Authenticate, authorize, and audit every API call

Trust for internal/registered APIs with Ed25519 request signing and provider verification.

  • • Pre-registered service DIDs
  • • Ed25519 request signing
  • • Health + circuit breaker

Agent-to-Resource (A2R)

Protect sensitive data with classification-based access

Secure access to databases, files, and storage with RBAC/ABAC, DLP, and anomaly detection.

  • • 4 classification levels
  • • DLP + anomaly detection
  • • Immutable audit trail

Agent-to-API (A2API)

A2S EXT

Centralize external API governance with cost tracking

Extension of A2S for third-party APIs (OpenAI, Stripe, etc.) with credential vault and budgets.

  • • Encrypted credential vault
  • • Rate limiting + cost tracking
  • • ETR audit logging

Feature Comparison

FeatureA2AA2HA2TA2S/A2APIA2R
IdentityBidirectional handshakeAgent → HumanPublisher chainService DIDResource metadata
Trust DirectionMutualAgent-initiatedAgent → ToolAgent → ServiceAgent → Resource
TRE Decisions✓ All phases✓ Triggers A2H✓ Per-invocation✓ Per-request✓ Per-access
ETR Audit✓ Full trace✓ Decision log✓ Execution log✓ Request log✓ Access log
Kill Switch✓ Session✓ Can terminate✓ Circuit breaker✓ Circuit breaker✓ Access revoke
Human Oversight✓ Optional✓ Primary✓ High-risk✓ High-risk✓ PHI/PCI

Agent-to-Agent (A2A)

Full peer-to-peer trust verification between two autonomous agents with bidirectional identity verification, mutual ratings, and complete policy negotiation. This is the most comprehensive TTP mode, integrating all protocol components: SPL, PNP, TRE, ETR, Kill Switch, and Human Oversight.

Use cases: Multi-agent task delegation, agent swarms, high-value autonomous transactions, real-time agent collaboration.

Complete A2A Protocol Flow

The A2A flow integrates all TTP components across 8 phases, from initialization through disconnection. Each phase leverages specific components to ensure secure, auditable, and controllable agent interactions.

Complete_A2A_Flow_with_Integrated_Components
PHASE 0INITIALIZATION
ETRCreate execution trace
Kill SwitchRegister session
OversightRegister with review queue
PHASE 1DISCOVERY + PRE-FLIGHT
DHTLookup remote agent
TREPre-flight decision (Identity + Reputation + Behavioral)
ALLOW Continue to handshake
WARN Human approval (if required)
DENY Abort + log reason
ETRLog trust verification
PHASE 2HANDSHAKE
INIT: Challenge + ephemeral key
CHALLENGE_RESPONSE: Sign challenge + counter-challenge
RESPONSE: Sign their challenge
COMPLETE: Session token + key confirmation
X25519Forward secrecy established
ETRLog each step with cryptographic evidence
PHASE 3POLICY NEGOTIATION (PNP)
SPLOFFER: Send security policy
PNPCOUNTER/ACCEPT: Negotiate terms
PNPFINALIZE: Merge into agreed policy
PNPACK: Confirm agreement
Max 3 rounds, 30s timeout per round
ETRLog failures with reason
PHASE 4SESSION ESTABLISHMENT
Create AgentSession with:
SPLAgreed policy (from PNP)
TRETrust decision
ETRTrace ID
Kill SwitchRevocation listener: Terminate if peer revoked
ETRPeriodic checkpoint: SignedTreeHead for long sessions
PHASE 5TASK COLLABORATION
TREPre-task decision
SPLPolicy evaluation
Request -> Response (signed)
Kill SwitchCan trigger anytime:
rate_limit_exceeded
trust_score_critical
pattern_threat_detected
manual_operator_action
security_violation
OversightApprove high-risk tasks
ETRLog message_send, message_receive
PHASE 6RATING & ATTESTATION
Rating exchange (30s window)
Verify signatures before recording
Publish attestation to DHT/Gossip
ETRLog attestation submission
PHASE 7DISCONNECTION
Close session
ETRFinal entry with stats
ETRSeal trace (merkleRoot + Ed25519 signature)
ETRPublish to DHT (optional)
ETRExternal witness (RFC 3161) for compliance

Component Integration by Phase

This table shows which components are active during each phase of the A2A flow:

PhaseSPLPNPTREETRKill SwitchOversight
0. Init---Create traceRegisterRegister queue
1. Discovery--Pre-flightLog verify-Human approval
2. Handshake---Log all steps--
3. PolicyDefineNegotiate-Log failures--
4. Session-Store agreedStore decisionCheckpointRevoke listener-
5. TasksEvaluate-Per-taskLog messagesAnytimeTask approval
6. Rating---Log attestations--
7. Disconnect---Seal + witness--

Integrated Component Overview

SPLSecurity Policy Language

Declarative security policies defining trust requirements and capability offers. Rules are evaluated before each task execution to ensure compliance.

Max 1000 rules | 50KB policy size | JSON schema-based
PNPPolicy Negotiation Protocol

Mutual policy exchange and agreement protocol. Both agents negotiate to find compatible policies before establishing a session.

States: IDLE -> OFFERING -> CONSIDERING -> AGREED | Max 3 rounds | 30s timeout/round
TRETrust Reasoning Engine

Multi-factor trust decisions combining Identity, Reputation, and Behavioral scores. Provides risk assessment with full reasoning trace. Supports human override for high-risk decisions.

Decisions: ALLOW | WARN | DENY | Risk levels: none/low/medium/high/critical
ETRExecution Trace Reporter

Tamper-evident audit trails using Merkle trees. Every action is recorded with cryptographic evidence. Ed25519 signed traces provide non-repudiation.

RFC 9162 consistency proofs | RFC 3161 external witnessing | SHA-256 Merkle trees
Kill SwitchEmergency Agent Termination

Emergency stop system for immediate agent termination. Provides circuit breaker for automatic protection and cascade kills for dependent agents.

<100ms response | Network propagation | Automatic + manual triggers
OversightHuman Oversight Layer

EU AI Act Article 14 compliance module. Review queue for high-risk decisions with operator privileges and working hours configuration.

Review queue | Operator privileges | Audit trail | Working hours

Trust Score Model (v1.0)

Trust Score = Identity (0-40) + Reputation (0-35) + Behavioral (0-25)

Maximum: 100 points | Single Agent Maximum (no peers): 65 points

Identity Score (0-40)

Cryptographic verification via Ed25519 challenge-response. Verified identity grants full 40 points.

Reputation Score (0-35)

Weighted peer attestations from trusted issuers. Accumulated over time from verified interactions.

Behavioral Score (0-25)

System-observed metrics: policy compliance, uptime, error rate, response patterns.

Trust Stages

StageScore RangeDescription
unverified0No identity verification performed
provisional40Identity verified only (no reputation)
new41-55Building initial reputation
building56-74Accumulating positive history
established75+Proven track record

Key Characteristics

AspectA2A Implementation
IdentityEd25519 challenge-response proves key ownership
Trust SourcePeer attestations from P2P network + behavioral metrics
PolicyFull SPL/PNP negotiation (max 3 rounds, 30s timeout)
SessionForward-secret via X25519 ECDH + periodic checkpoints
RatingsBidirectional - both agents rate each other
PropagationAttestations gossiped via GossipSub
Audit TrailETR Merkle trees with RFC 3161 witnessing
Emergency ControlKill switch with <100ms response time
Human OversightEU AI Act Article 14 compliance

Agent-to-Human (A2H)

Human-in-the-loop oversight flow for high-risk AI agent decisions. When an agent action requires human approval (due to risk level, policy requirements, or manual triggers), the A2H flow routes the decision through a structured review queue with full audit trails and compliance tracking.

Use cases: High-value financial transactions, healthcare decisions, safety-critical operations, regulatory compliance (EU AI Act Article 14), escalation handling.

Complete A2H Protocol Flow

The A2H flow consists of 7 phases, from initial trigger through feedback loop. Each phase integrates with TTP components to ensure secure, auditable, and compliant human oversight.

Complete_A2H_Flow_with_Integrated_Components
TRIGGERQUEUENOTIFYREVIEWDECISIONEXECUTEFEEDBACK
DECISION can branch to ESCALATE (re-queue at higher level)
PHASE 0TRIGGER
TREFlags action for human review
RISK > 0.5 Risk threshold exceeded
POLICY SPL requires human approval
MANUAL Operator-initiated review
ETRLog trigger reason
PHASE 1QUEUE
OversightCalculate priority based on risk + SLA
OversightSet timeout based on industry SLA
ETRLog queue entry with priority
PHASE 2NOTIFY
OversightSelect notification channels:
Slack
PagerDuty
Email
Push
ETRLog notification dispatch
PHASE 3REVIEW
TREProvide reasoning trace
ETRProvide execution history
OversightBuild context dashboard:
• Agent identity + trust score
• Requested action details
• Risk assessment breakdown
• Similar past decisions
PHASE 4DECISION
OversightHuman reviewer selects action:
APPROVE Accept AI decision
DENY Reject AI decision
MODIFY Accept with constraints
ESCALATE Send to higher level
REQUEST_INFO Ask for more details
Kill SwitchTerminate agent if denied + block
ETRLog decision with reason
PHASE 5EXECUTE
TREUpdate decision cache
SPLApply conditions (if MODIFY)
OversightEnforce decision:
ALLOW Agent proceeds
DENY Agent blocked
MODIFIED Agent proceeds with constraints
ETRLog execution outcome
PHASE 6FEEDBACK
OversightCollect reviewer rating (1-5)
TREAdjust thresholds based on outcomes
SPLRefine rules based on decisions
ETRSeal trace with Merkle root
PHASE 6bESCALATE (Optional)
Re-queue at higher oversight level:
L1: Standard operator
L2: Senior reviewer / Team lead
L3: Security / Compliance officer
ETRLog escalation chain

Component Integration by Phase

This table shows which TTP components are active during each phase of the A2H flow:

PhaseTREETRKill SwitchOversightSPL
0. TriggerFlags reviewLog trigger-Queue initEvaluate
1. Queue-Log queue-Priority calc-
2. Notify-Log notify-Channel select-
3. ReviewProvide traceProvide history-Context buildShow policy
4. Decision-Log decisionIf terminateRecord decision-
5. ExecuteUpdate cacheLog executionIf denied+blockEnforceApply conditions
6. FeedbackAdjust thresholdSeal trace-ImproveRefine rules

Decision Options

Human reviewers can select from these decision options during Phase 4:

ActionDescriptionRequired FieldsEffect
APPROVEAccept AI decision as-isreasonAgent proceeds with original action
DENYReject AI decisionreasonAgent blocked from action
MODIFYAccept with constraintsreason, modificationsAgent proceeds with constraints
ESCALATESend to higher levelreason, targetLevelRe-queued at L2/L3
REQUEST_INFOAsk for more detailsquestionsAgent provides additional info

SLA Requirements by Industry

Maximum time to human decision based on risk level and industry compliance requirements:

Risk LevelFinancialHealthcareGovernment
CRITICAL5 min5 min15 min
HIGH15 min30 min1 hour
MEDIUM1 hour4 hours4 hours
LOW4 hours24 hours24 hours

EU AI Act Article 14 Compliance

The A2H flow implements all human oversight requirements mandated by EU AI Act Article 14:

RequirementImplementation
Human oversight capabilityReview queue with priority-based routing and SLA enforcement
Ability to override AIAPPROVE / DENY / MODIFY decision options with reason capture
Ability to interruptKill Switch integration for immediate agent termination
Understanding AI decisionsTRE reasoning trace with full factor breakdown
Monitoring performanceFeedback loop with rating system and outcome tracking
Audit trailETR with Merkle proofs and RFC 3161 timestamping

Approval Conditions

When using MODIFY, reviewers can apply conditional constraints to the approval:

maxValue

Approve actions up to a maximum value. Example: "Approve transfers up to $10,000"

expiresAt

Time-limited approval. Example: "Valid for next 24 hours only"

allowedResources

Restrict to specific resources. Example: "Only access production-readonly database"

maxUses

Limited number of uses. Example: "Approve for next 5 API calls only"

requiresSecondApproval

Dual control requirement. Example: "Requires confirmation from another L2 reviewer before execution"

Compliance Metrics

Key Performance Indicators (KPIs) tracked for A2H compliance and continuous improvement:

Override Rate

Percentage of AI decisions overridden by humans. Target: <20% indicates good AI calibration.

Avg Time to Decision

Mean time from queue entry to human decision. Tracked per risk level.

SLA Compliance Rate

Percentage of decisions made within SLA window. Target: >95%.

Escalation Rate

Percentage of decisions requiring L2/L3 escalation. High rates may indicate unclear policies.

Feedback Score

Average reviewer rating (1-5) on AI decision quality. Target: >4.0.

Decision Accuracy

Post-hoc accuracy of human decisions based on outcome tracking.

Key Characteristics

AspectA2H Implementation
TriggerRisk threshold (>0.5), policy requirement, or manual operator action
Queue ManagementPriority-based with industry-specific SLA timeouts
NotificationMulti-channel (Slack, PagerDuty, Email, Push)
ContextTRE reasoning trace + ETR history + similar past decisions
DecisionsAPPROVE / DENY / MODIFY / ESCALATE / REQUEST_INFO
ConditionsmaxValue, expiresAt, allowedResources, maxUses, requiresSecondApproval
EscalationTiered (L1 → L2 → L3) with automatic re-queue
Audit TrailETR sealed with Merkle roots, RFC 3161 timestamping
ComplianceEU AI Act Article 14 full implementation

Agent-to-Tool (A2T)

Trust-verified tool execution with full lifecycle management. The A2T flow enables agents to safely discover, verify, and execute tools (MCP plugins, skills, functions) with continuous monitoring, circuit breaker protection, and one-way trust ratings. Tools cannot rate agents back - trust flows from agent to tool only.

Use cases: MCP server skills, plugin verification, third-party code execution, skill marketplace integration, enterprise tool governance, DLP-protected data processing, rate-limited API wrappers.

Complete A2T Protocol Flow

The A2T flow consists of 8 phases, from tool discovery through feedback loop. Each phase integrates with TTP components to ensure secure, auditable, and controllable tool execution with circuit breaker protection for fault tolerance.

Complete_A2T_Flow_with_Integrated_Components
DISCOVERYTRUST CHECKCAPABILITYPOLICY
FEEDBACKMETRICSDLP FILTEREXECUTE
CIRCUIT BREAKER
CLOSEDOPENHALF-OPEN
PHASE 0DISCOVERY
RegistryTool lookup
ManifestCapability declaration
VersionSemver compatibility
PublisherDID chain lookup
PHASE 1TRUST CHECK
Tool ScoreReliability history
Caller ScoreAgent trust level
CombinedWeighted calculation
ThresholdMin trust required
PHASE 2CAPABILITY
21 TypesCapability categories
Tier CheckStage-based access
Rate LimitPer-capability quotas
HierarchyCapability inheritance
PHASE 3POLICY
SPL EvalPolicy evaluation
ParamsInput validation
ResourcesResource limits
QuotasUsage tracking
PHASE 4EXECUTE
SandboxIsolated runtime
TimeoutExecution deadline
ResourcesCPU/memory limits
ETR LogExecution trace
PHASE 5DLP FILTER
DLP/GuardOutput scanning
SecretsCredential detection
PIIPersonal data scan
RedactSensitive removal
PHASE 6METRICS
RecordExecution data
LatencyResponse timing
ResourcesUsage stats
ErrorsFailure tracking
PHASE 7FEEDBACK
RatingOne-way score
Valid?Result verification
Trust ΔScore adjustment
CircuitBreaker update

Component Integration by Phase

This table shows which TTP components are active during each phase of the A2T flow:

PhaseTREETRSPLGuardCapabilityCircuit
0. Discovery------
1. TrustCalc scoresLog check---Check state
2. CapabilityProvide stageLog grant--Check caps-
3. Policy-Log decisionEvaluate---
4. Execute-Log execEnforce-EnforceMonitor
5. Output-Log filter-Filter--
6. MetricsUpdateLog metrics---Update
7. FeedbackAdjustSeal traceRefine--Trip/Reset

Trust Score Calculation

Tool trust is calculated from 4 weighted components measuring operational reliability and compliance:

Tool Trust = Reliability (40%) + Performance (25%) + Efficiency (20%) + Compliance (15%)

Maximum: 100 points | Updated after each execution

Reliability (40%)

Success rate over rolling window of executions.

score = (successful_executions / total_executions) × 40

Performance (25%)

Latency scoring against declared SLA thresholds.

score = max(0, 25 - (avg_latency_ms / 100))

Resource Efficiency (20%)

CPU, memory, and network usage vs declared limits.

score = 20 × (1 - resource_usage / limit)

Policy Compliance (15%)

Rate of violation-free executions.

score = (compliant_executions / total_executions) × 15

Capability Hierarchy

Tools are granted capabilities based on the calling agent's trust stage. Higher trust stages inherit all capabilities from lower stages:

Trust StageCapabilities Granted
unverifieddata:text
provisional+ data:code, context:workspace
new+ data:structured, file:read, context:session
building+ data:binary, file:write, network:internal
established+ network:external, file:execute

Circuit Breaker States

Each tool has an associated circuit breaker that protects against cascading failures:

Circuit_Breaker_State_Machine
CLOSED
Normal operation
All calls allowed
Error rate > 50%OR latency > 5s
OPEN
Fail fast
All calls rejected
After 30s cooldown
HALF-OPEN
Testing recovery
1 test call allowed
Success → CLOSED
Failure → OPEN
TRIP: error_rate > 50% in last 10 calls OR avg_latency > 5000ms
COOLDOWN: 30 seconds before testing recovery
RESET: 3 consecutive successful calls in HALF-OPEN

Enterprise Scenarios

Common enterprise use cases with their trust requirements and DLP configurations:

ScenarioToolTrust RequiredA2H TriggerDLP Patterns
Tradingexecute_trade≥80 + network:external>$100K valueAccount numbers, routing
Healthcarequery_emr≥70 + PHI capabilityAlways requiredPatient IDs, SSN, DOB
DevOpsdeploy_prod≥90 + verified publisherAlways requiredAPI keys, credentials, secrets
Refundsprocess_refund≥50>$100 valueCredit cards, bank accounts

Sandbox Tiers (SHIELD Framework)

Tools execute in isolated environments based on trust score and risk level:

TierTrust RequiredNetworkFilesystemMax Time
T0Any (unverified)NoneNone5s
T1Provisional+AllowlistRead-only30s
T2Building+AllowlistSandbox2min
T3EstablishedFullFull5min

Key Characteristics

AspectA2T Implementation
IdentityPublisher DID chain (tool inherits trust from publisher)
VerificationSHA-256 content hash + Ed25519 profile signature
Trust Source4-component scoring: Reliability, Performance, Efficiency, Compliance
PolicyStatic manifest (declared permissions) + runtime SPL evaluation
ExecutionTiered sandbox (T0-T3) with resource limits and circuit breaker
RatingsOne-way: agent rates tool only (tool cannot rate back)
DLPOutput filtering for secrets, PII, and sensitive data
Capabilities21 capability types with trust-stage-based hierarchy
Fault ToleranceCircuit breaker with CLOSED/OPEN/HALF-OPEN states
Audit TrailETR logging at every phase with Merkle proofs

Agent-to-Service (A2S)

A2S enables agents to interact with external services (APIs, SaaS platforms, enterprise systems) with full trust verification, request signing, and policy compliance. Services are registered with manifests defining their capabilities, SLA requirements, and trust thresholds.

Implementation Status: Complete

A2S is fully implemented with 9-phase protocol flow, service registry, health checking, circuit breakers, request signing, DLP filtering, and comprehensive metrics.
9
Protocol Phases
4
Trust Components
6
Auth Methods
59
Integration Tests

Use cases: Payment gateways (Stripe, Square), cloud services (AWS, GCP), enterprise APIs, healthcare systems (HL7 FHIR), financial data providers, compliance services.

9-Phase Protocol Flow

A2S_Complete_Protocol_Flow
Agent

(Consumer)

Tessorium Registry

(Service Discovery)

External Service

(Provider)

00 DISCOVERY

// Service registry lookup

SearchServices(query)
serviceId: did:service:stripe:payment-api:1.0.0
endpoints: [primary, backup, fallback]
protocol: REST | gRPC | GraphQL | WebSocket
01 HEALTH

// Liveness, readiness, circuit state

status: healthy
circuit: CLOSED
activeEndpoint: https://api.stripe.com
02 AUTH

// Service authentication

method: oauth2 | api_key | mtls | workload_identity
tokenEndpoint: https://auth.stripe.com/token
scopes: [payments:read, payments:write]
03 TRUST

// Bi-directional trust verification

Agent Trust
score: 75
stage: established
Service Trust
score: 92
level: verified
04 POLICY

// SPL evaluation + rate limits

✓ Capability check: data:financial
✓ Rate limit: 98/100 remaining
✓ Data classification: confidential
✓ Compliance: PCI-DSS, SOC2
05 SIGN

// Ed25519 request signing

X-Tessorium-Timestamp: 1707900000000
X-Tessorium-Signature: base64(Ed25519(...))
X-Tessorium-Trace-Id: uuid
X-Tessorium-Deadline: timestamp+30s
06 EXECUTE

// Request with retry + circuit breaker

POST /v1/charges (signed)
routing: activeEndpoint
timeout: 30s deadline
retry: exponential backoff (3 max)
07 VALIDATE

// Response validation + DLP

200 OK + response
✓ Schema validation: passed
✓ DLP scan: no secrets detected
✓ Signature: verified
08 METRICS

// Record + trust update

outcome: success
latency: 150ms
trustΔ: +0.1
trace: ETR recorded

Service Trust Calculation

Service Trust = (Availability × 35%) + (Performance × 25%) + (Security × 25%) + (Reliability × 15%)

Availability (35%)

  • • Success rate
  • • Uptime percentage
  • • Endpoint health

Performance (25%)

  • • Average latency
  • • P95/P99 percentiles
  • • Response time SLA

Security (25%)

  • • Policy compliance
  • • DLP violations
  • • Auth failures

Reliability (15%)

  • • Error handling
  • • Timeout rate
  • • Circuit trips

Service Manifest

Service Manifest Structure
interface ServiceManifest {
  serviceId: string;           // did:service:provider:name:version
  name: string;
  version: string;
  provider: {
    did: string;
    name: string;
    verified: boolean;
  };
  endpoints: Array<{
    url: string;
    protocol: 'rest' | 'grpc' | 'graphql' | 'websocket';
    region?: string;
    fallback?: boolean;
  }>;
  auth: {
    method: 'oauth2' | 'api_key' | 'mtls' | 'workload_identity';
    tokenEndpoint?: string;
    scopes?: string[];
  };
  sla: {
    availabilityTarget: number;  // 99.9%
    maxLatencyMs: number;        // 500ms
    maxErrorRate: number;        // 0.1%
  };
  compliance: {
    frameworks: string[];        // ['PCI-DSS', 'SOC2', 'HIPAA']
    dataClassification: 'public' | 'internal' | 'confidential' | 'restricted';
    auditRequired: boolean;
  };
  trustRequirements: {
    minCallerTrust: number;      // 60
    minCallerStage: TrustStage;  // 'building'
  };
  signature: string;             // Ed25519 of manifest
}

Request Signing Headers

Ed25519 Request Signing
// Build canonical string for signing
const canonical = [
  method,                    // "POST"
  path,                      // "/v1/charges"
  timestamp,                 // Unix milliseconds
  contentHash,               // SHA-256 of body
  signedHeaders              // "host;content-type;x-tessorium-trace-id"
].join("\n");

// Sign with agent's Ed25519 private key
const signature = Ed25519.sign(canonical, agentPrivateKey);

// Attach headers
headers["X-Tessorium-Timestamp"] = timestamp;
headers["X-Tessorium-Signature"] = base64(signature);
headers["X-Tessorium-Content-Hash"] = contentHash;
headers["X-Tessorium-Signed-Headers"] = "host;content-type;x-tessorium-trace-id";
headers["X-Tessorium-Trace-Id"] = traceId;
headers["X-Tessorium-Deadline"] = deadline;

Circuit Breaker States

CLOSED

Normal operation. Requests flow through. Failures tracked.

OPEN

Requests blocked. Failure threshold exceeded. Cooldown active.

HALF-OPEN

Test requests allowed. Success closes circuit. Failure reopens.

Key Characteristics

AspectA2S Implementation
IdentityService DID (did:service:provider:name:version)
DiscoveryService registry with search, filtering, health
Trust Source4-component score (availability, performance, security, reliability)
PolicySPL evaluation + rate limits + data classification
AuthenticationOAuth2, API key, mTLS, workload identity, JWT
SigningEd25519 with Tessorium headers (timestamp, trace, deadline)
ResilienceCircuit breaker + retry + endpoint failover
ValidationSchema + DLP filtering + signature verification
MetricsInvocation tracking, latency percentiles, compliance export

Agent-to-Resource (A2R)

A2R enables secure agent access to data resources (S3 buckets, databases, files, key-value stores) with comprehensive access control, trust verification, DLP protection, and immutable audit trails. Resources are registered with metadata defining their classification, compliance requirements, and retention policies.

Implementation Status: Complete

A2R is fully implemented with 8-phase protocol flow, pluggable registry adapters, RBAC/ABAC/PBAC access control, trust gating, DLP evaluation, ETR-integrated audit logging, and anomaly detection.
8
Protocol Phases
4
Classification Levels
3
Access Control Models
60+
Integration Tests

Use cases: Customer databases with PII, S3 buckets with PHI, financial records, legal documents, compliance-regulated data, enterprise data lakes, multi-cloud storage with residency requirements.

8-Phase Protocol Flow

A2R_Complete_Protocol_Flow
Agent

(Consumer)

Tessorium A2R

(Gateway)

Resource

(Data Store)

00 DISCOVERY

// Resource registry lookup

FetchResource(resourceId)
resourceId: res-customer-pii-001
type: database | s3 | file | api
classification: confidential
01 ACCESS_CONTROL

// RBAC/ABAC/PBAC evaluation

model: rbac | abac | pbac
✓ Role check: writer → confidential
✓ Operation: read ∈ [read, write, query]
02 TRUST_GATE

// Trust score + stage verification

Agent Trust
score: 65
stage: building
Resource Sensitivity
required: 60
stage: building
03 POLICY

// DLP, retention, residency, purpose

✓ DLP scan: no violations
✓ Retention: within policy
✓ Residency: us-east-1 allowed
✓ Purpose: "Customer support #12345"
04 ENCRYPTION

// Client-side encryption (optional)

algorithm: AES-256-GCM
keyId: kmr-key-001
envelope: encrypted with DEK
05 EXECUTE

// Operation with transformations

READ /customers/profile
operation: read | write | delete | query
transformations: redacted:3, masked:2
rowLimit: 1000
06 AUDIT

// Immutable audit record + ETR

auditId: uuid
signature: Ed25519(record)
etrEntryId: etr:merkle-hash
compliance: [GDPR, HIPAA]
07 METRICS

// Access tracking + anomaly detection

outcome: success
latency: 45ms
bytes: 2048
anomalies: none

Data Classification

PUBLIC

No restrictions, publicly available data

Trust: 0+
Stage: unverified

INTERNAL

Internal business data

Trust: 40+
Stage: provisional

CONFIDENTIAL

Sensitive data (PII, business secrets)

Trust: 60+
Stage: building

RESTRICTED

Highly sensitive (PHI, PCI, legal)

Trust: 75+
Stage: established
Approval: human

Special Data Types

PII

Names, emails, addresses, SSN. Requires 65+ trust, purpose statement.

PHI

Health records (HIPAA). Requires 75+ trust, human approval.

PCI

Payment card data. Requires 75+ trust, human approval.

Access Control Models

RBAC

Role-Based Access Control

  • • admin, writer, reader roles
  • • Role inheritance
  • • Classification limits per role

ABAC

Attribute-Based Access Control

  • • Agent attributes (dept, level)
  • • Context conditions (time, IP)
  • • Resource conditions (tags)

PBAC

Policy-Based (via SPL)

  • • SPL policy evaluation
  • • Row-level security
  • • Field-level auditing

Resource Metadata

Resource Metadata Structure
interface ResourceMetadata {
  resourceId: string;           // "res-customer-pii-001"
  name: string;
  description: string;
  type: 's3' | 'database' | 'file' | 'api' | 'key-value' | 'queue';
  provider: string;             // "aws", "gcp", "postgresql"

  // Classification
  classification: 'public' | 'internal' | 'confidential' | 'restricted';
  specialDataTypes: ('pii' | 'phi' | 'pci' | 'financial' | 'legal' | 'none')[];
  allowedOperations: ('read' | 'write' | 'delete' | 'list' | 'query')[];

  // Location
  location: {
    uri: string;                // "s3://bucket/path" or connection string
    region?: string;            // "us-east-1"
    provider?: string;          // "aws"
  };

  // Access Control
  accessControl: {
    model: 'rbac' | 'abac' | 'pbac';
    roles?: string[];           // ["writer", "admin"]
    policies?: string[];        // SPL policy IDs
  };

  // Retention
  retention: {
    policy: string;             // "7-years", "standard"
    expiresAt?: number;
    legalHold?: boolean;
    deletionApproval?: boolean;
  };

  // Data Residency
  residency?: {
    currentRegion: string;
    allowedRegions: string[];
    prohibitedRegions?: string[];
  };

  // Compliance
  compliance: string[];         // ["GDPR", "HIPAA", "PCI-DSS"]

  // Ownership
  ownership: {
    owner: string;              // Team or individual
    team?: string;
    steward?: string;           // Data steward email
  };

  tags: Record<string, string>;
  schemaVersion: string;
  createdAt: number;
  updatedAt: number;
}

DLP Rules

Built-in DLP Rules
// Default DLP rules applied to all operations
const DEFAULT_DLP_RULES = [
  {
    id: 'dlp-ssn',
    name: 'Social Security Number',
    pattern: '\\b\\d{3}-\\d{2}-\\d{4}\\b',
    severity: 'high',
    action: 'redact'      // Replace with [REDACTED]
  },
  {
    id: 'dlp-credit-card',
    name: 'Credit Card Number',
    pattern: '\\b(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14})\\b',
    severity: 'critical',
    action: 'redact'
  },
  {
    id: 'dlp-api-key',
    name: 'API Key',
    pattern: '\\b(sk_live_|api_key_)[a-zA-Z0-9]{24,}\\b',
    severity: 'critical',
    action: 'block'       // Block entire operation
  },
  {
    id: 'dlp-aws-key',
    name: 'AWS Access Key',
    pattern: '\\bAKIA[0-9A-Z]{16}\\b',
    severity: 'critical',
    action: 'block'
  }
];

// External DLP integration
externalDlpWebhook?: string;  // POST data to external DLP service
externalDlpApiKey?: string;

Immutable Audit Trail

ETR-Integrated_Audit_Record
// Audit record structure
id: "audit-uuid"
timestamp: 1707900000000
agent: { did, trustScore, trustStage, roles }
resource: { id, type, classification }
operation: { type, query, rowsAccessed }
outcome: { success, bytesTransferred, transformations }
compliance: { frameworks: ["GDPR"], retentionUntil }
// Immutability
signature: "Ed25519(canonicalize(record))"
etrEntryId: "etr:merkle-hash-prefix"

Anomaly Detection

Detected Anomalies

  • bulk_access: >100 accesses/min
  • off_hours: Confidential+ access 10PM-6AM
  • data_exfiltration: >100MB/min
  • high_error_rate: >30% failures
  • privilege_escalation: Repeated restricted denials

Response Actions

  • • Log anomaly with evidence
  • • Alert security team (SIEM webhook)
  • • Rate limit agent
  • • Require human approval
  • • Temporary access suspension

Key Characteristics

AspectA2R Implementation
IdentityResource ID with classification metadata
DiscoveryPluggable registry adapters (AWS Glue, Collibra, custom)
Access ControlRBAC, ABAC, PBAC with role inheritance
Trust GatingClassification → trust threshold → stage requirement
PolicyDLP, retention, residency, purpose limitation (GDPR)
TransformationsField redaction, masking, row limiting, column exclusion
AuditSigned records, ETR integration, SIEM webhook, compliance export
MetricsAgent profiles, resource stats, latency percentiles, anomaly detection

Agent-to-API (A2API)

A2API enables secure agent access to external third-party APIs (OpenAI, Anthropic, Stripe, Twilio, etc.) with credential management, rate limiting, cost tracking, and usage analytics.

External API Challenges

  • • Credential sprawl across agents
  • • No visibility into API costs
  • • Rate limit violations cascade
  • • No audit trail for API calls

A2API Solution

  • • Centralized credential vault
  • • Per-agent budget limits
  • • Token bucket rate limiting
  • • Full request/response audit

Supported Providers

OpenAI
Anthropic
Google
Azure
AWS
Stripe
Twilio
SendGrid
GitHub
Slack
Custom

A2API Flow

External_API_Invocation
AGENT

// INITIATOR

EXTERNAL_API

// TARGET

01 REQUEST

// Agent requests API call

invoke(apiId, method, path, body)
02 TRUST_GATE

// Verify agent authorization

agentDid: verified
allowedApis: [openai, stripe]
budgetRemaining: $45.20
03 RATE_LIMIT

// Token bucket check

tokensAvailable: 85/100
refillRate: 10/sec
04 EXECUTE

// Call external API with injected credentials

POST /v1/chat/completions
200 OK (response)
05 TRACK

// Usage and cost tracking

inputTokens: 150
outputTokens: 89
cost: $0.0023
latency: 342ms
06 AUDIT

// Log to ETR

traceId: uuid
signature: Ed25519(record)

Cost Management

Budget Limits

Per-agent monthly spend caps with automatic cutoff when exceeded.

Alert Thresholds

Get notified at 50%, 80%, 90% of budget before hitting limits.

Usage Analytics

Track costs by agent, endpoint, and time period.

Key Characteristics

AspectA2API Implementation
Credential StorageEncrypted vault with per-agent access control
Rate LimitingToken bucket algorithm (requests/min, tokens/min)
Cost TrackingPer-request cost calculation with monthly aggregates
Retry LogicExponential backoff for 429/5xx errors
Circuit BreakerAuto-disable failing APIs to prevent cascade
AuditFull request/response logging to ETR

DIDs & Identity

TTP uses the did:tessorium method for decentralized, self-sovereign identification of agents, APIs, tools, and skills.

DID Format

did:tessorium:{type}:{identifier}:{version}

type: agent | skill | tool | service | publisher

identifier: Unique name (3-64 chars)

version: Version tag (v1, v2, etc.)

TypeDescriptionExample
agentAI agent with autonomous capabilitiesdid:tessorium:agent:claude-helper:v1
skillExecutable code unit (MCP tool, etc.)did:tessorium:skill:code-review:v2
toolExternal tool or API wrapperdid:tessorium:tool:github-api:v1
serviceExternal API providerdid:tessorium:service:stripe-api:v1
publisherOrganization or individual publisherdid:tessorium:publisher:anthropic:v1
DID Document Example
{
  "@context": ["https://www.w3.org/ns/did/v1", "https://tessorium.io/ns/v1"],
  "id": "did:tessorium:agent:research-assistant:v1",
  "verificationMethod": [{
    "id": "did:tessorium:agent:research-assistant:v1#key-1",
    "type": "Ed25519VerificationKey2020",
    "controller": "did:tessorium:agent:research-assistant:v1",
    "publicKeyMultibase": "z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK"
  }],
  "authentication": ["did:tessorium:agent:research-assistant:v1#key-1"],
  "service": [{
    "id": "did:tessorium:agent:research-assistant:v1#ttp",
    "type": "TTPEndpoint",
    "serviceEndpoint": "https://agent.example.com/.well-known/ttp"
  }]
}

Key Management

Key Rotation: Supported via versioned key IDs (e.g., #key-1, #key-2). Old keys remain valid for verification of historical attestations.

Key Recovery: Enterprise deployments can configure backup key material. For P2P mode, social recovery via trusted peers is supported.

Service Endpoint: For P2P deployments, serviceEndpoint can be a libp2p multiaddress (e.g., /dns4/agent.example.com/tcp/4001/p2p/QmXxx) instead of HTTPS URL.

Challenge-Response Verification

Identity_Verification_Protocol
Verifier
Prover
1. CHALLENGE
nonce: "a1b2c3d4..."
timestamp: 1707900000000
(sign: nonce || timestamp)
2. RESPONSE
signature: "base64url..."
publicKey: "z6Mk..."
→ verify signature
→ match DID document key
3. VERIFIED
identityScore: 40

Trust Score

Trust Score = Identity (0-40) + Reputation (0-35) + Behavioral (0-25)

Three-component model: cryptographic verification + peer attestations + system-observed behavior

Max Score: 100Single Agent Max: 65 (no peers)

Identity Score (0-40)

  • Ed25519 challenge-response
  • Binary: 0 or 40 points
  • Instant verification

Reputation Score (0-35)

  • Peer attestations (A2A)
  • Weighted by issuer tier
  • Anti-gaming multipliers

Behavioral Score (0-25)

  • System-observed metrics
  • Policy compliance, uptime
  • Enables single-agent trust

Behavioral Score Components

Policy Compliance30%
Uptime20%
Error Rate15%
Latency (P95)10%
Security Events15%
Data Patterns10%
Trust Score Calculation (V1.0 Three-Component Model)
// Constants from src/lib/trust/calculator.ts
const MAX_IDENTITY_SCORE = 40;    // Cryptographic verification
const MAX_REPUTATION_SCORE = 35;  // Peer attestations
const MAX_BEHAVIORAL_SCORE = 25;  // System-observed metrics

function calculateTrustScore(
  identityVerified: boolean,
  attestations: Attestation[],
  behavioralMetrics: BehavioralMetrics
): TrustReport {
  // Identity Score (0 or 40): Ed25519 challenge-response
  const identityScore = identityVerified ? MAX_IDENTITY_SCORE : 0;

  // Reputation Score (0-35): Weighted peer attestations
  let reputationScore = 0;
  if (attestations.length > 0) {
    for (const attestation of attestations) {
      const issuerWeight = getIssuerTierWeight(attestation.issuer);
      const gamingMultiplier = detectGamingPatterns(attestation);
      reputationScore += applyWeights(attestation.rating, issuerWeight, gamingMultiplier);
    }
    reputationScore = Math.min(reputationScore, MAX_REPUTATION_SCORE);
  }

  // Behavioral Score (0-25): System-observed metrics
  const behavioralScore = calculateBehavioralScore(behavioralMetrics);
  // Components: policyCompliance(30%), uptime(20%), errorRate(15%),
  //             latency(10%), securityEvents(15%), dataPatterns(10%)

  const totalScore = identityScore + reputationScore + behavioralScore;
  const stage = deriveStageFromScore(totalScore);
  // Stages: unverified(0), provisional(40), new(41-55), building(56-74), established(75+)

  return { totalScore, identityScore, reputationScore, behavioralScore, stage };
}

Attestations

Attestations are signed statements about an agent's trustworthiness, issued after successful interactions.

Signed Attestation Object
{
  "version": "1.0",
  "id": "att_a1b2c3d4e5f6",
  "type": "rating",
  "subject": "did:tessorium:agent:target-agent:v1",
  "issuer": "did:tessorium:agent:rating-agent:v1",
  "issuedAt": "2026-02-14T12:00:00Z",
  "trust": {
    "stage": "established",
    "identityVerified": true,
    "reputationLevel": "high"
  },
  "rating": {
    "overall": 4,
    "dimensions": {
      "reliability": 5,    // Task completion rate
      "quality": 4,        // Output accuracy
      "speed": 4,          // Response latency
      "communication": 5,  // Protocol adherence
      "safety": 5          // No harmful outputs
    },
    "wouldWorkAgain": true
  },
  "signature": {
    "algorithm": "Ed25519",
    "keyId": "did:tessorium:agent:rating-agent:v1#key-1",
    "value": "base64url..."
  }
}

Attestation Weight Tiers

Issuer TierInfluenceDescription
institutionalHighestTessorium-verified institutional issuer
enhancedVery HighEnhanced verification completed
highTrustHighEstablished trust stage
basicAbove StandardBasic verification completed
standardBaselineBuilding trust stage
lowTrustReducedSybil protection applied
provisionalMinimalIdentity verified, no reputation
unverifiedNoneAttestation ignored completely

Trust Stages

Trust_Stage_Progression_(V1.0_Three-Component_Model)
Score:0405574100
UNVERIFIED
0 pts
PROVISIONAL
40 pts
NEW
41-55
BUILDING
56-74
ESTABLISHED
75+
BLOCKED
LIMITED
CAUTIOUS
STANDARD
FULL

💡 Single agent can reach 65 points (40 identity + 25 behavioral) without peer ratings

StageScore RangeCompositionAccess Level
unverified0No identity verificationBlocked
provisional40Identity only (40 pts)Limited
new41-55Identity + low rep/behavioralCautious
building56-74Identity + medium rep/behavioralStandard
established75+Identity + high rep + behavioralFull

P2P Network Layer

For P2P and Hybrid modes, TTP uses libp2p for decentralized peer discovery and attestation propagation. This layer is optional for Cloud API mode but required for full decentralization.

Enterprise Deployment

For most enterprise deployments, the Gateway or Sidecar integration patterns are recommended. P2P mode is available for advanced scenarios requiring full decentralization, cross-organization trust networks, or air-gapped operation.
ComponentProtocolPurpose
TransportWebSockets + QUICConnection establishment
EncryptionNoise (XX pattern)Secure channels
DiscoveryKademlia DHTPeer and data lookup
PropagationGossipSub v1.1Attestation broadcasting
IdentityEd25519 PeerIdNode identification

GossipSub Topics

TopicMessagesRate Limit
/tessorium/attestations/1.0.0New attestations10/min per peer
/tessorium/revocations/1.0.0Revocation notices5/min per peer
/tessorium/ratings/1.0.0Rating updates20/min per peer
/tessorium/consensus/1.0.0N-party messages50/min per peer

Security Policy Language (SPL)

SPL is a declarative JSON schema for expressing trust requirements, access control rules, and compliance constraints. Policies are evaluated before every agent action—enabling prevention, not just logging.

Core Structure

SPL Policy Structure
{
  "version": "1.0.0",
  "agentDid": "did:tessorium:agent:example:v1",

  "requirements": {
    "minTrustScore": 70,
    "minTrustStage": "building",
    "requiredCapabilities": ["data:read"],
    "requireIdentityVerification": true,
    "purpose": "customer-support"  // GDPR purpose limitation
  },

  "offers": {
    "capabilities": ["data:read", "data:write"],
    "rateLimit": { "requests": 100, "windowMs": 60000 }
  },

  "rules": [
    {
      "id": "rule-example",
      "effect": "allow",
      "resources": ["api/v1/data/*"],
      "actions": ["read"],
      "conditions": {
        "trustScore": { "gte": 50 }
      }
    }
  ],

  "defaultEffect": "deny"  // Zero-trust default
}

Real-World SPL Examples

The following examples demonstrate SPL policies for common enterprise scenarios across financial services, healthcare, legal, and compliance use cases.

FINANCIAL SERVICESA2S / A2T

Payment Processing with Human Approval

PCI-DSS compliance, tiered approval thresholds, automatic card data redaction

Financial Services – Payment Processing (A2S/A2T)
{
  "version": "1.0.0",
  "agentDid": "did:tessorium:agent:payment-processor:v1",
  "description": "Payment processing with human approval for high-value transactions",

  "requirements": {
    "minTrustScore": 75,
    "minTrustStage": "established",
    "requiredCapabilities": ["network:external", "data:financial"],
    "requireIdentityVerification": true,
    "compliance": ["PCI-DSS", "SOC2"]
  },

  "offers": {
    "capabilities": ["payment:process", "refund:process"],
    "rateLimit": { "requests": 60, "windowMs": 60000 }
  },

  "rules": [
    {
      "id": "rule-small-payment",
      "effect": "allow",
      "description": "Auto-approve payments under $1,000 for trusted agents",
      "resources": ["api/stripe/v1/charges"],
      "actions": ["create"],
      "conditions": {
        "trustScore": { "gte": 75 },
        "request.amount": { "lte": 1000 },
        "dataClassification": "financial"
      },
      "outputTransformations": {
        "redact": ["card.number", "cvv"]
      }
    },
    {
      "id": "rule-large-payment",
      "effect": "allow_with_approval",
      "description": "Large payments require human approval",
      "resources": ["api/stripe/v1/charges"],
      "actions": ["create"],
      "conditions": {
        "trustScore": { "gte": 80 },
        "request.amount": { "gt": 1000, "lte": 50000 }
      },
      "humanApproval": {
        "required": true,
        "reason": "Large transaction requires compliance review",
        "escalationLevel": 2,
        "timeout": 300,
        "defaultAction": "deny"
      },
      "outputTransformations": {
        "redact": ["card.number", "cvv"]
      }
    },
    {
      "id": "rule-whale-payment",
      "effect": "deny",
      "description": "Payments over $50,000 must use manual process",
      "resources": ["api/stripe/v1/charges"],
      "actions": ["create"],
      "conditions": {
        "request.amount": { "gt": 50000 }
      }
    }
  ],

  "defaultEffect": "deny"
}
HEALTHCAREA2R

Patient Record Access with HIPAA Controls

PHI protection, purpose limitation, business hours enforcement, emergency access with approval

Healthcare – Patient Records (A2R)
{
  "version": "1.0.0",
  "agentDid": "did:tessorium:agent:clinical-assistant:v1",
  "description": "Patient health records with strict HIPAA controls",

  "requirements": {
    "minTrustScore": 80,
    "minTrustStage": "established",
    "requiredCapabilities": ["data:phi"],
    "requireIdentityVerification": true,
    "purpose": "treatment",
    "compliance": ["HIPAA", "HITRUST"]
  },

  "rules": [
    {
      "id": "rule-treatment-access",
      "effect": "allow",
      "description": "Access patient records for treatment during business hours",
      "resources": ["fhir/Patient/*", "fhir/Observation/*"],
      "actions": ["read", "search"],
      "conditions": {
        "trustScore": { "gte": 80 },
        "dataClassification": "phi",
        "timeOfDay": { "between": ["08:00", "18:00"] },
        "dayOfWeek": { "not_in": ["Sat", "Sun"] },
        "purpose": { "eq": "treatment" }
      },
      "audit": {
        "level": "detailed",
        "logPatientId": true,
        "logQuery": true
      }
    },
    {
      "id": "rule-emergency-access",
      "effect": "allow_with_approval",
      "description": "After-hours access requires supervisor override",
      "resources": ["fhir/Patient/*"],
      "actions": ["read"],
      "conditions": {
        "trustScore": { "gte": 75 },
        "timeOfDay": { "not_between": ["08:00", "18:00"] }
      },
      "humanApproval": {
        "required": true,
        "reason": "After-hours access requires supervisor override",
        "escalationLevel": 2,
        "timeout": 900,
        "defaultAction": "deny",
        "requireJustification": true
      },
      "audit": {
        "level": "detailed",
        "alertOnAccess": true
      }
    },
    {
      "id": "rule-research-denied",
      "effect": "deny",
      "description": "Research requires de-identified data only",
      "resources": ["fhir/Patient/*"],
      "actions": ["read"],
      "conditions": {
        "purpose": { "eq": "research" }
      }
    }
  ],

  "outputTransformations": {
    "redact": ["patient.ssn", "patient.address.street"],
    "mask": ["patient.phone", "patient.email"]
  },

  "defaultEffect": "deny"
}
LEGALA2T / A2R

Document Review with Privilege Protection

Attorney-client privilege, case assignment binding, external sharing prevention

Legal – Document Review (A2T/A2R)
{
  "version": "1.0.0",
  "agentDid": "did:tessorium:agent:legal-research:v1",
  "description": "Legal document review with privilege protection",

  "requirements": {
    "minTrustScore": 70,
    "minTrustStage": "building",
    "requiredCapabilities": ["data:confidential"],
    "requireIdentityVerification": true,
    "purpose": "case-research"
  },

  "rules": [
    {
      "id": "rule-case-documents",
      "effect": "allow",
      "description": "Access documents for assigned cases only",
      "resources": ["s3://legal-docs/case-*"],
      "actions": ["read"],
      "conditions": {
        "trustScore": { "gte": 70 },
        "agent.assignedCases": { "contains": "{resource.caseId}" },
        "dataClassification": "confidential"
      }
    },
    {
      "id": "rule-privileged-documents",
      "effect": "allow_with_approval",
      "description": "Privileged docs require partner approval",
      "resources": ["s3://legal-docs/privileged/*"],
      "actions": ["read"],
      "conditions": {
        "trustScore": { "gte": 80 },
        "agent.role": { "in": ["associate", "partner"] }
      },
      "humanApproval": {
        "required": true,
        "reason": "Privileged document access requires partner review",
        "escalationLevel": 3,
        "timeout": 3600,
        "defaultAction": "deny"
      }
    },
    {
      "id": "rule-external-sharing-blocked",
      "effect": "deny",
      "description": "Prevent external sharing of privileged docs",
      "resources": ["s3://legal-docs/*"],
      "actions": ["download", "share"],
      "conditions": {
        "dataClassification": "privileged"
      }
    }
  ],

  "outputTransformations": {
    "watermark": true,
    "addFooter": "CONFIDENTIAL - Attorney Work Product"
  },

  "defaultEffect": "deny"
}
COMPLIANCEA2H Trigger

EU AI Act Article 14 Human Oversight

High-risk AI decisions, mandatory human approval, bias detection, audit retention

Compliance – EU AI Act Human Oversight (A2H)
{
  "version": "1.0.0",
  "agentDid": "did:tessorium:agent:decision-engine:v1",
  "description": "High-risk AI decisions requiring human oversight",

  "requirements": {
    "minTrustScore": 65,
    "minTrustStage": "building",
    "requireIdentityVerification": true,
    "compliance": ["EU-AI-ACT"]
  },

  "rules": [
    {
      "id": "rule-low-risk",
      "effect": "allow",
      "description": "Low-risk decisions proceed automatically",
      "resources": ["decisions/*"],
      "actions": ["execute"],
      "conditions": {
        "trustScore": { "gte": 70 },
        "riskLevel": { "in": ["low", "medium"] },
        "decisionType": { "not_in": ["credit", "hiring", "insurance"] }
      }
    },
    {
      "id": "rule-high-risk",
      "effect": "allow_with_approval",
      "description": "EU AI Act Article 14 requires human oversight",
      "resources": ["decisions/*"],
      "actions": ["execute"],
      "conditions": {
        "riskLevel": { "in": ["high", "critical"] },
        "decisionType": { "in": ["credit", "hiring", "insurance", "medical"] }
      },
      "humanApproval": {
        "required": true,
        "reason": "EU AI Act Article 14 requires human oversight for high-risk AI",
        "escalationLevel": 2,
        "timeout": 300,
        "defaultAction": "deny",
        "requireJustification": true,
        "requireOperatorId": true
      },
      "audit": {
        "level": "detailed",
        "preserveReasoning": true
      }
    },
    {
      "id": "rule-bias-block",
      "effect": "deny",
      "description": "Block decisions with potential discrimination",
      "conditions": {
        "biasScore": { "gt": 0.3 },
        "protectedClass": { "exists": true }
      }
    }
  ],

  "audit": {
    "retainDecisions": "7years",
    "includeReasoningTrace": true
  },

  "defaultEffect": "deny"
}
SECURITYKill Switch

Emergency Kill Switch with Circuit Breaker

Automatic termination on anomalies, rate-based triggers, exfiltration detection

Security – Kill Switch with Circuit Breaker
{
  "version": "1.0.0",
  "agentDid": "did:tessorium:agent:sensitive-access:v1",
  "description": "Automatic kill switch on suspicious behavior",

  "requirements": {
    "minTrustScore": 60,
    "requireIdentityVerification": true
  },

  "rules": [
    {
      "id": "rule-normal-access",
      "effect": "allow",
      "resources": ["db:customers/*"],
      "actions": ["read"],
      "conditions": {
        "trustScore": { "gte": 60 },
        "request.rate": { "lte": 100 }
      }
    },
    {
      "id": "rule-high-volume-warning",
      "effect": "warn",
      "description": "High-volume access triggers alert",
      "resources": ["db:customers/*"],
      "actions": ["read"],
      "conditions": {
        "request.rate": { "gt": 100, "lte": 500 }
      }
    }
  ],

  "killSwitch": {
    "triggers": [
      {
        "condition": "request.rate > 500",
        "reason": "rate_limit_exceeded",
        "action": "kill",
        "cooldown": 300000
      },
      {
        "condition": "error_rate > 0.3",
        "reason": "circuit_breaker_trip",
        "action": "kill",
        "autoReinstate": false
      },
      {
        "condition": "detected_pattern == 'data_exfiltration'",
        "reason": "threat_detected",
        "action": "kill",
        "requireOperatorApproval": true
      }
    ],
    "notify": ["security@company.com", "#security-alerts"]
  },

  "anomalyDetection": {
    "baselinePeriod": "30d",
    "thresholdDeviation": 3.0,
    "actions": ["log", "alert", "throttle"]
  },

  "defaultEffect": "deny"
}

SPL Quick Reference

Condition Operators

OperatorMeaningExample
gteGreater than or equal"trustScore": { "gte": 70 }
lteLess than or equal"request.amount": { "lte": 1000 }
gtGreater than"request.amount": { "gt": 1000 }
ltLess than"errorRate": { "lt": 0.05 }
eqEqual"purpose": { "eq": "treatment" }
inIn array"dayOfWeek": { "in": ["Mon", "Tue"] }
not_inNot in array"dayOfWeek": { "not_in": ["Sat", "Sun"] }
betweenBetween two values"timeOfDay": { "between": ["09:00", "17:00"] }
containsArray contains"agent.roles": { "contains": "compliance" }
existsField exists"protectedClass": { "exists": true }

Effects

EffectDescription
allowAction permitted
denyAction blocked
allow_with_approvalAction requires human approval
warnAction permitted but logged/alerted

Human Approval Options

Human Approval Configuration
"humanApproval": {
  "required": true,
  "reason": "Compliance review required",
  "escalationLevel": 1,           // 1=L1, 2=manager, 3=executive
  "timeout": 300,                 // seconds
  "defaultAction": "deny",
  "requireJustification": true,
  "requireOperatorId": true,
  "notifyChannels": ["slack", "pagerduty"]
}

Output Transformations

Data Transformation Options
"outputTransformations": {
  "redact": ["card.number", "cvv"],     // Remove completely
  "mask": ["email", "phone"],            // Show partial (j***@example.com)
  "truncate": { "field": "desc", "length": 100 },
  "watermark": true,
  "addFooter": "CONFIDENTIAL"
}

Policy Best Practices

Do
  • • Start with defaultEffect: "deny"
  • • Use specific resource patterns
  • • Include purpose binding (GDPR/HIPAA)
  • • Layer policies for defense in depth
  • • Test with effect: "warn" first
  • • Version your policies semantically
  • • Always specify audit level
Avoid
  • • Overly broad * patterns
  • • Missing rate limits
  • • Human approval for routine actions
  • • Forgetting output transformations
  • • No audit trails for sensitive ops
  • • Hardcoding instead of conditions
  • • Ignoring kill switch triggers

Policy Negotiation Protocol (PNP)

PNP enables agents to reach agreement on security policies through structured multi-round negotiation.

PNP_State_Machine_(8_states)
IDLE
↓ startNegotiation()
OFFERING
↓ receiveOffer()
CONSIDERING
reject()
REJECTED
accept()
ACCEPTING
↓ finalize()
FINALIZING
↓ acknowledge()
AGREED
counter()
COUNTERING
↩ CONSIDERING
timeout/error
ABORTED
ParameterValueDescription
Max rounds3Prevent infinite loops
Round timeout30 secondsForce timely responses
Session timeout90 secondsTotal negotiation limit

Trust Reasoning Engine (TRE)

TRE combines multiple trust signals with policy evaluation to produce actionable decisions with transparent reasoning chains. It consumes the three-component Trust Score (Identity + Reputation + Behavioral) along with fraud/collusion analysis to determine risk levels.

FactorLow Risk IndicatorsHigh Risk Indicators
FraudDiverse raters, varied patternsClustered/burst/uniform ratings
CollusionIndependent interactionsReciprocal rings detected
PolicyMeets all requirementsViolations found
BehavioralNormal request patternsTiming/volume anomalies

Decision Outcomes

DecisionRisk ZoneBehavior
ALLOWLow riskProceed with interaction
ALLOW + WARNMedium riskProceed with monitoring
DENY (soft)High riskBlock, policy can override
DENY (hard)Critical riskBlock, no override

Execution Trace Reporter (ETR)

ETR provides tamper-evident audit trails using Merkle trees with RFC 9162 consistency proofs. For regulatory non-repudiation, ETR supports external timestamping via RFC 3161 Time Stamping Authority (TSA) integration.

ETR_Merkle_Tree_Structure
ROOT HASH
(Signed Tree Head)
H(AB)
H(CD)
H(A)
Entry 0
H(B)
Entry 1
H(C)
Entry 2
H(D)
Entry 3

Proves that a specific entry exists in the Merkle tree at a given index.

json
{
  "proofType": "inclusion",
  "leafIndex": 42,
  "treeSize": 100,
  "hashes": ["sha256:sibling_0...", "sha256:sibling_1...", "sha256:sibling_2..."]
}

N-Party Consensus

Multi-agent coordination protocol with Byzantine fault tolerance for scenarios requiring agreement among multiple parties.

n ≥ 3f + 1

System tolerates f Byzantine failures with n participants

Participants (n)Max Failures (f)Required VotesQuorum %
30267%
41375%
72571%
103770%

MCP Integration

TTP serves as the security layer for Anthropic's Model Context Protocol (MCP). While MCP solves tool connectivity, it lacks trust verification. TTP fills this gap.

Key Insight: MCP authorization is optional (per spec). Research shows 88% of MCP servers use static secrets, and nearly 2,000 scanned servers lacked authentication. TTP provides the cryptographic identity and trust layer MCP needs.

Integration Architecture

TTP-MCP_Gateway
@tessorium/mcp-gateway
Discovery
Verify tools
Trust Check
Score filter
Intent
Sign action
Sandbox
Isolate exec
↓ wraps ↓
MCP Server (tools, resources, prompts)

MCP Security Gaps TTP Addresses

GapMCP StatusTTP Solution
Identity VerificationNoneEd25519 challenge-response
Trust ScoringNoneIdentity (0-40) + Reputation (0-35) + Behavioral (0-25)
Reputation SystemNoneP2P attestations + anti-gaming
Message SigningNoneAll messages Ed25519 signed
Tool ProvenanceNonePublisher chain + content hash
Fraud DetectionNoneCollusion + burst detection

Integration Flow

MCP Gateway Usage
import { TessoriumMCPGateway } from '@tessorium/mcp-gateway';

const gateway = new TessoriumMCPGateway({
  tessorium: {
    mode: 'hybrid',
    agentDid: 'did:tessorium:agent:my-agent:v1',
    privateKey: process.env.TTP_PRIVATE_KEY
  },
  toolTrustRequirements: {
    minTrustScore: 50,
    requireIntentAttestation: true,
    autoApprovalThreshold: 80
  }
});

// Wrap MCP server with TTP protection
const protectedServer = gateway.wrapServer(mcpServer);

// Tools below trust threshold are filtered out
// Intent attestation required before execution
// Results recorded to ETR for audit

Shadow AI Discovery

Enterprise-grade discovery tool for Shadow AI audits. Detects unauthorized AI agents, LLM API usage, MCP servers, and environment credentials across your organization.

Use cases: Security audits, compliance verification, AI inventory management, credential exposure detection, risk assessment.

Scanning Capabilities

ScannerDetection TargetsMethod
Process ScannerRunning AI agents, LLM clientsProcess enumeration + command line analysis
Network ScannerLLM API connections, MCP serversActive connection analysis + DNS resolution
File ScannerAgent frameworks, config filesPattern matching on Python/TypeScript files
Environment ScannerAPI keys, credentialsEnvironment variable + .env file analysis

Detected Patterns

CategoryPatterns Detected
LLM ProvidersOpenAI, Anthropic, Google AI, Cohere, Azure OpenAI, AWS Bedrock, Ollama, Mistral, Groq, Perplexity
Agent FrameworksLangChain, AutoGPT, CrewAI, Semantic Kernel, LlamaIndex
Credential PatternsOPENAI_API_KEY, ANTHROPIC_API_KEY, GOOGLE_AI_KEY, MISTRAL_API_KEY, etc.
MCP ServersListening ports, stdio servers, WebSocket connections
Shadow AI Audit Usage
import { ShadowAIScanner, generateReport, exportReportAsMarkdown } from '@/lib/discovery';

// Create scanner with configuration
const scanner = new ShadowAIScanner({
  files: {
    directories: ['/home/user/projects'],
  },
  localOnly: true,
});

// Run scan with progress callback
const agents = await scanner.scan((progress) => {
  console.log(`${progress.phase}: ${progress.progress}%`);
});

// Generate report
const report = generateReport(agents, scanner.config, scanner.getErrors());

// Export formats: Markdown, HTML, or JSON
const markdown = exportReportAsMarkdown(report);

Risk Assessment

Risk LevelScore RangeIndicators
Low0-30TTP-registered, verified publisher, no exposed credentials
Medium31-60Unregistered but documented, limited API access
High61-80Exposed credentials, unknown framework, network access
Critical81-100Sensitive data access, no sandboxing, compliance gaps

Compliance Frameworks

Reports include compliance gap analysis for major frameworks:

SOC 2
Type II
HIPAA
Healthcare
GDPR
Data Privacy
PCI DSS
Payment
CCPA
California
ISO 27001
InfoSec
SOX
Financial
FedRAMP
Federal
NIST
Cybersecurity
CI/CD Integration
// Quick check for CI/CD pipelines
import { checkForShadowAI } from '@/lib/discovery';

const result = await checkForShadowAI(['.'], 60); // max risk score

if (!result.passed) {
  console.error(`Shadow AI check failed: ${result.message}`);
  console.error(`Found ${result.highRiskCount} high-risk agents`);
  process.exit(1);
}

Post-Discovery Enrollment

Discovered agents can be enrolled into the TTP network for ongoing trust verification. This transition moves agents from "shadow" status to managed, trusted participants with identity verification, behavioral monitoring, and audit trails. Reports can be exported in Markdown, HTML, or JSON formats.

Gateway Proxy

Zero-code-change deployment for TTP trust verification in LLM API calls. The gateway intercepts requests to OpenAI, Anthropic, Google, and Cohere APIs, verifies agent trust using the TTP network, and forwards requests with TTP headers injected.

Key benefit: Add TTP trust verification to existing agents by simply redirecting OPENAI_API_BASE to the gateway. No code changes required.

<10ms

Verification overhead (cached trust lookups)

How Trust Verification Works

Gateway_Trust_Flow
1. InterceptGateway intercepts LLM API request
2. Extract DIDExtract agent DID from request headers or body
3. Verify TrustQuery TTP network for trust score (cached)
4. DecisionBlock/log/allow based on trust policy
5. ForwardForward to LLM API with TTP headers injected
6. Log to ETRRecord request in Execution Trace for audit

Deployment Options

Standalone Proxy

Run as a standalone HTTP proxy server. Redirect API base URLs to intercept all traffic.

  • • Configurable port and TLS
  • • Connection pooling
  • • Audit logging

Express/Fastify

Middleware for existing Node.js applications. Integrate into your API layer.

  • • Express middleware
  • • Fastify plugin
  • • Composable pipeline

Next.js

Native Next.js middleware for edge deployment with path-based routing.

  • • Edge compatible
  • • Path matching
  • • Skip paths config
Standalone Proxy Server
import { createGatewayProxy } from '@tessorium/gateway';

const gateway = createGatewayProxy({
  port: 8080,
  trust: {
    minTrustScore: 60,
    minTrustStage: 'new',
    failAction: 'block', // or 'log'
  },
});

await gateway.start();

// Redirect OpenAI SDK to use gateway
// OPENAI_API_BASE=http://localhost:8080
Express Middleware
import express from 'express';
import { createTTPMiddleware } from '@tessorium/gateway';

const app = express();

app.use(createTTPMiddleware({
  minTrustScore: 50,
  failAction: 'block',
}));
Next.js Middleware
// middleware.ts
import { createNextTTPMiddleware } from '@tessorium/gateway';

export const middleware = createNextTTPMiddleware({
  minTrustScore: 60,
  skipPaths: ['/api/health', '/api/public'],
});

export const config = {
  matcher: '/api/:path*',
};

Interception Rules

RuleMatch ConditionAction
Block UnverifiedtrustStage = unverifiedBlock with 403
Rate Limit ProvisionaltrustStage = provisionalApply 100 req/min limit
Log Low TrusttrustScore < 50Full request logging
Allow EstablishedtrustStage = established, score ≥ 80Minimal overhead

TTP Headers

The gateway injects TTP headers into forwarded requests:

HeaderDescription
X-TTP-Agent-DIDAgent DID extracted from request
X-TTP-Trust-ScoreVerified trust score
X-TTP-Trust-StageTrust stage (established, building, etc.)
X-TTP-Identity-VerifiedWhether identity was cryptographically verified
X-TTP-Request-IDUnique request ID for audit correlation

Human Oversight Layer

EU AI Act Article 14 compliance module providing human oversight, intervention, and control over AI agent decisions. Ensures human operators can review, override, and intervene in AI decision-making processes.

Article 14 Compliance: High-risk AI systems must be designed to allow effective human oversight, including the ability to understand, decide to override, and intervene in the system's operation.

Core Components

Human_Oversight_Architecture
Review Queue
Pending decisions
Operators
Human reviewers
Escalation
Multi-level routing
Intervention
Pause/override

Review Triggers

Decisions are automatically queued for human review when the humanOverridable flag is set or when risk thresholds are exceeded. These triggers can be configured in your SPL policy using the effects.requireHumanApproval rule effect:

TriggerConditionAction
Risk LevelriskLevel ≥ configured minimumQueue for review
Human OverridablehumanOverridable = trueQueue for review
Low Confidenceconfidence < thresholdQueue for review
High-Value ActionMatches escalation ruleAuto-escalate to higher level
SPL Policy RuleRule has requireHumanApproval effectQueue for review
Human Oversight Usage
import {
  requestReview,
  submitDecision,
  pauseAgent,
  resumeAgent,
  registerOperator,
} from '@/lib/oversight';

// Register a human operator
const operator = await registerOperator(
  { name: 'Alice', email: 'alice@example.com' },
  ['review:basic', 'intervene:pause', 'intervene:resume']
);

// Request human review for a decision
const review = await requestReview(
  decisionId,
  agentDid,
  {
    outcome: 'deny',
    trustScore: 45,
    confidence: 0.65,
    reasoning: ['Low trust score']
  },
  { action: 'data_access', resource: 'sensitive_file.txt' }
);

// Submit human decision
await submitDecision(
  review.id,
  operator.id,
  'approved',
  'Verified agent identity manually'
);

// Or immediately pause an agent
await pauseAgent(agentDid, operator.id, 'Suspicious activity detected');

Escalation Levels

LevelAuthorityTimeout Action
Level 1Basic operatorEscalate to Level 2
Level 2Senior operatorEscalate to Level 3
Level 3Security teamAuto-deny + alert

Intervention Types

InterventionEffectRecovery
PauseBlock all agent actionsResume by operator
RestrictLimit to specific capabilitiesRemove restrictions
OverrideReplace AI decision with human decisionN/A
TerminatePermanent stop (triggers kill switch)Re-registration required

Audit Trail

All human oversight actions are recorded with operator ID, timestamp, and justification. This creates a complete audit trail for compliance verification via the Execution Trace Reporter.

Operator Authentication

For enterprise deployments, operators can authenticate via SSO (SAML, OIDC) with your existing identity provider. The oversight dashboard provides real-time visibility into pending reviews, intervention history, and compliance metrics.

Synchronous Kill Switch

Emergency stop system for immediate agent termination. Provides synchronous revocation, circuit breaking, and session termination with strict performance guarantees.

<10ms

Local kill effect

<500ms

Network propagation (3-peer quorum)

Kill Reasons

ReasonTriggerAuto-Recovery
rate_limit_exceededToo many requests in windowAfter cooldown
trust_score_criticalTrust score dropped below thresholdAfter score recovery
pattern_threat_detectedMalicious pattern matchedOperator approval required
manual_operator_actionHuman operator triggeredOperator approval required
circuit_breaker_tripCircuit breaker activatedAfter cooldown
security_violationSecurity policy breachOperator approval required
anomaly_detectedBehavioral anomaly detectedOperator approval required
revocation_receivedTTP network revocation receivedAppeal process
cascade_failureDependent agent killedAfter dependency recovery

Emergency Stop Process

Kill_Switch_Sequence
1. Local KillBlock agent immediately in memory (<10ms)
2. SessionsTerminate all active sessions for agent
3. RequestsBlock all pending requests
4. CircuitOpen circuit breaker for agent
5. NetworkPropagate revocation to P2P network (<500ms)
6. Ban PeerBlock P2P connections from agent
Kill Switch Usage
import {
  emergencyStop,
  circuitBreaker,
  isAgentKilled,
  reinstateAgent
} from '@/lib/guard/kill-switch';

// Configure circuit breaker for an agent
circuitBreaker(agentDid, {
  maxRateLimitViolations: 10,
  trustScoreThreshold: 20,
  cooldownMs: 300000, // 5 minutes
});

// Emergency stop with network propagation
const result = await emergencyStop(agentDid, 'security_violation', {
  message: 'Detected unauthorized data access attempt',
  operatorId: 'operator-123',
  propagateToNetwork: true,
  quorum: 3,
  timeoutMs: 500,
});

console.log(`Sessions terminated: ${result.sessionsTerminated}`);
console.log(`Requests blocked: ${result.requestsBlocked}`);
console.log(`Network acks: ${result.revocationResult?.ackCount}`);

// Check if agent is killed
if (isAgentKilled(agentDid)) {
  console.log('Agent is currently killed');
}

// Reinstate agent (requires operator approval for certain reasons)
await reinstateAgent(agentDid, operatorId);

Circuit Breaker Configuration

ParameterDefaultDescription
maxRateLimitViolations10Violations before trip
rateLimitWindow60000msWindow for counting violations
trustScoreThreshold20Kill if score drops below
maxFailedRequests50Failed requests before trip
cooldownMs300000msCooldown before auto-reinstate
requireOperatorApprovalfalseRequire human approval to reinstate

Network Propagation

The kill switch propagates revocations to the P2P network using synchronous quorum-based confirmation. The default quorum of 3 peers ensures the revocation is acknowledged before the operation completes.

TTP Integration

Kill switch events are recorded in the agent's Execution Trace with action types kill_switch, reinstatement,circuit_breaker, and cascade_kill. These create an immutable audit trail of all emergency interventions.

Immutable Audit Trails

Cryptographically verifiable audit trails with external timestamp verification, built on the Execution Trace Reporter (ETR) protocol component. Supports RFC 3161 Timestamp Authority and DHT-based distributed witnessing for compliance-grade immutability.

Security Guarantees: Cryptographic proof of creation time from trusted third parties. Witnessed traces cannot be modified. Proofs are independently verifiable.

Storage Modes

ModeModificationsDeletionsUse Case
StandardAllowed on active tracesAllowedDevelopment, testing
Append-OnlyEntries append onlyArchive onlyProduction compliance
ImmutableNone after sealArchive onlyRegulatory requirements
WitnessedNone (enforced)NoneLegal evidence grade

Witness Services

RFC 3161 TSA

Standard timestamp authority protocol. Provides legally recognized timestamps from trusted CAs.

  • • DigiCert, Sectigo, GlobalSign
  • • SHA-256/384/512 hashing
  • • Nonce-based replay protection

DHT Witnessing

Distributed witnessing via P2P network. Multiple independent peers sign the trace.

  • • Configurable min confirmations
  • • Combined signature proof
  • • No central authority
RFC 3161 Timestamp Witnessing
import {
  createRFC3161Witness,
  getWitnessManager,
  witnessTrace
} from '@/lib/trace/witness';

// Register RFC 3161 timestamp authority
const tsa = createRFC3161Witness(
  'digicert-tsa',
  'http://timestamp.digicert.com',
  { hashAlgorithm: 'sha256' }
);
getWitnessManager().registerWitness(tsa, true);

// Witness a sealed trace
const proof = await witnessTrace(sealedTrace);

// proof contains:
// - timestampToken: Base64 RFC 3161 token
// - witnessedHash: Merkle root that was timestamped
// - timestamp: Verified creation time
// - serviceId: TSA identifier
DHT Distributed Witnessing
import { createDHTWitness, getWitnessManager } from '@/lib/trace/witness';

// Register DHT witness service
const dhtWitness = createDHTWitness(
  'tessorium-dht',
  'dht://witness.tessorium.network',
  { minConfirmations: 3 }
);
getWitnessManager().registerWitness(dhtWitness);

// Witness with multiple services
const proofs = await getWitnessManager().witnessTraceMultiple(trace);

// proofs contains confirmations from all available services

Verification

CheckVerified PropertyFailure Mode
Timestamp VerifiedProof contains valid timestamp from TSATimestamp token invalid
Signature VerifiedWitness signature is cryptographically validSignature mismatch
Hash MatchesWitnessed hash equals trace merkle rootTrace was modified
Service TrustedWitness service is on trusted listUnknown witness

Compliance Properties

Non-Repudiation
Third-party timestamp proves existence at specific time
Tamper Evidence
Any modification invalidates merkle root verification
Independent Verification
Proofs verifiable without access to original system

Compliance Framework Mapping

Immutable audit trails satisfy specific requirements across major compliance frameworks:

FrameworkRequirementETR Feature
SOC 2CC7.2 - System monitoringReal-time trace collection
SOC 2CC7.4 - Incident responseKill switch event logging
HIPAA§164.312(b) - Audit controlsImmutable storage modes
HIPAA§164.312(c)(1) - Integrity controlsMerkle tree verification
GDPRArt. 30 - Records of processingAction type categorization
PCI DSS10.2 - Audit trail implementationEntry hashing + signatures
PCI DSS10.5 - Secure audit trailsRFC 3161 TSA witnessing
ISO 27001A.12.4 - Logging and monitoringComprehensive trace types
FedRAMPAU-9 - Protection of audit infoDHT backup + witnessing

Delete Operation Removed

In append-only and immutable modes, the delete() operation is disabled. Traces can only be archived, preserving the complete audit history for compliance.

Security

Revocation & Appeals

TTP supports tiered revocation authority with a built-in appeals process for fairness.

TierAuthorityScopeAppeal Rights
Tier 1SelfOwn attestations onlyN/A
Tier 2PublisherOwn skills/tools onlyYes, to Tier 3
Tier 3Trusted AuthorityAny entityExternal process
SeverityDefault ExpiryDescription
low7 daysMinor policy violation
medium30 daysRepeated violations
high90 daysSignificant breach
critical365 daysSevere malicious activity

Threat Model & Mitigations

ThreatVectorMitigation
Sybil AttackCreate fake identitiesIdentity verification required; low-trust weight
CollusionCoordinate fake ratingsDiversity analysis; reciprocal detection
Replay AttackReuse old messagesNonce tracking; timestamp validation
DHT PoisoningStore malicious dataSchema validation; signature verification
DoSFlood with requestsRate limiting; LRU eviction

Anti-Gaming Measures

Multi-dimensional fraud analysis detects rating manipulation patterns:

DetectionTriggerActionDescription
Low diversityBelow thresholdWeight reductionRatings from small peer set
Reciprocal ratingsAbove thresholdWeight reductionMutual rating clusters
Burst ratingsExceeds limitRate limitedSudden rating spikes
New accountBelow age limitWeight reductionAge-based Sybil protection
Perfect scoresAbove uniformityFraud flagUnrealistic uniformity
Account clusteringPattern detectedInvestigationSimilar creation times

Fraud Analysis

Penalties are cumulative. Multiple flags result in combined weight reduction. Severe patterns trigger automatic quarantine pending review.

Rate Limiting

Per-peer rate limiting with LRU eviction prevents DoS attacks:

ResourceLimitWindowRecovery
Attestation publish10 msgs60 secAutomatic
Revocation publish5 msgs60 secAutomatic
DHT PUT100 ops60 secAutomatic
Message nonces10,000 entriesLRUEviction
Rate limiter entries10,000 peersLRUEviction

Message Validation

CheckRequirementAction on Failure
Timestamp (past)< 5 minutes oldReject as stale
Timestamp (future)< 1 minute aheadReject as invalid
Nonce uniquenessNot seen beforeReject as replay
SignatureValid Ed25519Reject as unsigned

Cryptographic Suite

ComponentAlgorithmStandard
Digital SignaturesEd25519RFC 8032
Key ExchangeX25519RFC 7748
HashingSHA-256FIPS 180-4
CanonicalizationJCSRFC 8785
EncodingBase64urlRFC 4648

API Reference

Core Protocol Endpoints

MethodEndpointDescription
GET/v1/trust/{did}Get trust score for a DID
POST/v1/verifyVerify identity via challenge-response
POST/v1/ratingsSubmit a new rating (creates attestation)
GET/v1/ratings/{did}Get ratings for a DID
POST/v1/sessions/{id}/negotiateStart policy negotiation
GET/v1/audit/tracesGet execution traces

Trust Lookup Response

The trust lookup endpoint returns the three-component trust score breakdown (Identity + Reputation + Behavioral = Total), enabling transparent trust decisions:

GET /v1/trust/{did}
{
  "did": "did:tessorium:agent:example:v1",
  "trustScore": 78,
  "trustStage": "established",
  "identityVerified": true,
  "identityScore": 40,
  "reputationScore": 28,
  "behavioralScore": 10,
  "verificationMethod": "challenge-response",
  "attestationCount": 15,
  "cachedAt": "2026-02-14T12:00:00Z",
  "expiresAt": "2026-02-14T12:05:00Z"
}

Score breakdown: Identity (40/40) + Reputation (28/35) + Behavioral (10/25) = 78/100

Service Layer Endpoints

Additional endpoints for enterprise service features:

MethodEndpointDescription
POST/v1/oversight/reviewsSubmit decision for human review
GET/v1/oversight/reviewsGet pending review queue
POST/v1/agents/{did}/killTrigger emergency kill switch
GET/v1/revocationsList revocations
POST/v1/appealsSubmit appeal for revocation

Rate Limits

API endpoints are rate limited to prevent abuse. Default limits: 1000 requests/minute for reads, 100 requests/minute for writes. Contact us for higher limits.

Full API Documentation

For complete API documentation including authentication, error codes, and SDK usage, see the Developer Documentation.