📦
Production Packages
ATF Framework Integrations
🦜
atf-langchain
ATF-RGC-Compliant
pip install -e ./integrations/langchain

ATFCallbackHandler intercepts every LLM call and tool invocation. Verifies ATF-INV-001–006, samples CES, implements the HALT protocol (RGC-INV-003 — CES < 10.0 → ATFHaltError). LCEL-compatible via ATFGovernedRunnable.

ATFCallbackHandler ATFGovernedRunnable ATFVerifierTool
View source →
atf-fastapi
ATF-RGC Conformant
pip install -e ./integrations/fastapi

Starlette middleware + FastAPI dependency. Validates DR from Authorization header. HALT → HTTP 503. Adds X-ATF-RCR-ID, X-ATF-CES-Score, X-ATF-Status audit headers to every response.

ATFMiddleware require_atf() X-ATF-* headers
View source →
🤖
atf-openai-agents
ATF-RGC Conformant
pip install -e ./integrations/openai-agents

ATFAgentGuard wraps OpenAI Agents SDK runs. ATFHandoffGuard validates sub-delegations before handoffs (ATF-INV-001 MAR). ATFRunHooks implements the native RunHooks interface for inline governance.

ATFAgentGuard ATFHandoffGuard ATFRunHooks
View source →
Step 1 — Register an agent identityATF-INV-003
register_agent.py
from atf_core import ATFClient, AgentIdentityRecord, RegistrationTier

  # Initialize ATF client with the issuing principal's credentials
  client = ATFClient(
      principal_id="HUMAN-harold-nunes-001",     # TIER-1 human root
      private_key_b64=os.environ["ATF_PRIVATE_KEY_B64"],
      public_key_b64=os.environ["ATF_PUBLIC_KEY_B64"],
  )

  # Register an AI agent — budget MUST be ≤ principal's budget (ATF-INV-001)
  air = client.register_agent(
      display_name="Trading Governance Agent v2",
      domain="FINANCE",
      vertical="equity_trading",
      authority_budget=75.0,    # 75% of principal's 100.0 budget
      tier=RegistrationTier.TIER_2,
      capabilities=["governance_decision", "risk_assessment"],
  )

  print(f"Agent registered: {air.agent_id}")
  # Agent registered: AID-FINANCE-3A7F9B2C1D4E5F6A

  assert air.registration_tier == 2
  assert air.authority_budget <= client.principal_budget   # ATF-INV-001
Step 2 — Issue a Delegation ReceiptATF-INV-001 · ATF-INV-002
issue_dr.py
from atf_core import TaskScope

  # Delegate authority for a specific task scope
  dr = client.issue_delegation_receipt(
      delegate_id=air.agent_id,
      task_scope=TaskScope(
          action="governance_decision",
          domain="FINANCE",
          vertical="equity_trading",
          max_position_usd=500_000,
      ),
      budget_granted=75.0,       # ATF-INV-001: 75.0 ≤ 100.0 (principal budget)
      ttl_seconds=3600,          # DR expires in 1 hour
  )

  # DR is PQC-signed (ML-DSA-65) and content-hashed (ATF-INV-002, ATF-INV-005)
  print(f"DR issued:    {dr.delegation_id}")
  print(f"Budget:       {dr.budget_granted}/{dr.budget_delegator}")
  print(f"Chain root:   {dr.chain_root_id}")
  print(f"Expires:      {dr.expires_at}")
  print(f"Content hash: {dr.content_hash[:32]}...")

  # DR issued:    ATFDR-3A7F9B2C1D4E5F6A7890ABCD12345678
  # Budget:       75.0/100.0
  # Chain root:   HUMAN-harold-nunes-001
  # Expires:      2026-05-16T11:00:00.000000000Z
  # Content hash: sha256:a3f4b2c1d5e6f7890a1b2c3d4e5f6a7b...
Step 3 — Verify the DR (offline, no platform access)ATF-INV-006
verify_dr.py
from atf_verifier import ReceiptVerifier, VerificationResult

  # Verify offline — only the receipt JSON and the issuer's public key are needed
  verifier = ReceiptVerifier(issuer_public_key_b64=os.environ["ATF_PUBLIC_KEY_B64"])

  result: VerificationResult = verifier.verify(dr)

  assert result.verdict == "PASS"
  assert result.checks["atf_inv_001_mar"]       # budget_granted ≤ budget_delegator
  assert result.checks["atf_inv_002_pqc_sig"]   # ML-DSA-65 signature valid
  assert result.checks["atf_inv_005_hash"]      # SHA-256 content hash match
  assert result.checks["atf_inv_006_independent"]  # verified offline

  print(f"Verdict: {result.verdict} ({len(result.checks)} checks passed)")
  # Verdict: PASS (6 checks passed)

  # Verification is fully reproducible — same result on any machine,
  # with no network access, using only the JSON receipt + public key.
$ python verify_dr.py
✓ ATF-INV-001 (MAR): budget_granted 75.0 ≤ budget_delegator 100.0
✓ ATF-INV-002 (PQC): ML-DSA-65 signature verified
✓ ATF-INV-003 (Root): chain traces to HUMAN-harold-nunes-001
✓ ATF-INV-004 (Ceiling): budget within registered ceiling
✓ ATF-INV-005 (Hash): SHA-256 content hash verified
✓ ATF-INV-006 (Independent): offline verification confirmed
VERDICT: PASS — 6/6 invariants satisfied
TypeScript — Issue & Verify a Delegation ReceiptATF-INV-001/002/005/006
atf-integration.ts
import { ATFClient, DelegationReceipt, ReceiptVerifier, TaskScope } from "@atf-protocol/sdk";

  const client = new ATFClient({
    principalId: "HUMAN-harold-nunes-001",
    privateKeyB64: process.env.ATF_PRIVATE_KEY_B64!,
    publicKeyB64: process.env.ATF_PUBLIC_KEY_B64!,
  });

  // Step 1 — Register agent
  const air = await client.registerAgent({
    displayName: "Trading Governance Agent v2",
    domain: "FINANCE",
    vertical: "equity_trading",
    authorityBudget: 75.0,  // ATF-INV-001: must be ≤ principal's 100.0
    tier: 2,
    capabilities: ["governance_decision", "risk_assessment"],
  });

  console.log(`Agent registered: ${air.agentId}`);

  // Step 2 — Issue DR with typed scope
  const scope: TaskScope = {
    action: "governance_decision",
    domain: "FINANCE",
    vertical: "equity_trading",
    maxPositionUsd: 500_000,
  };

  const dr: DelegationReceipt = await client.issueDelegationReceipt({
    delegateId: air.agentId,
    taskScope: scope,
    budgetGranted: 75.0,   // ATF-INV-001 enforced — throws if budgetGranted > principal budget
    ttlSeconds: 3600,
  });

  console.log(`DR: ${dr.delegationId}`);
  console.log(`Chain root: ${dr.chainRootId}`);

  // Step 3 — Verify offline (no network call — only receipt JSON + public key)
  const verifier = new ReceiptVerifier(process.env.ATF_PUBLIC_KEY_B64!);
  const result = await verifier.verify(dr);

  if (result.verdict !== "PASS") {
    throw new Error(`DR verification failed: ${JSON.stringify(result.failures)}`);
  }

  console.log(`Verdict: ${result.verdict} — ${result.checks.size} checks passed`);
TypeScript — Error handling & MAR violation detectionATF-INV-001
atf-error-handling.ts
import { ATFClient, MARViolationError, BudgetExceededError } from "@atf-protocol/sdk";

  async function safeDelegation(
    client: ATFClient,
    delegateId: string,
    requestedBudget: number,
  ): Promise {
    try {
      return await client.issueDelegationReceipt({
        delegateId,
        taskScope: { action: "governance_decision", domain: "FINANCE" },
        budgetGranted: requestedBudget,
        ttlSeconds: 3600,
      });
    } catch (err) {
      if (err instanceof MARViolationError) {
        // ATF-INV-001: budget_granted > budget_delegator — protocol violation
        console.error(`MAR violation: requested ${requestedBudget}, delegator has ${err.delegatorBudget}`);
        return null;
      }
      if (err instanceof BudgetExceededError) {
        // ATF-INV-004: exceeds registered agent ceiling
        console.error(`Budget ceiling: agent ceiling is ${err.ceiling}`);
        return null;
      }
      throw err;  // re-throw unexpected errors
    }
  }

  // This will succeed: 75.0 ≤ 100.0
  const dr1 = await safeDelegation(client, agentId, 75.0);   // ✓ PASS

  // This will throw MARViolationError: 110.0 > 100.0
  const dr2 = await safeDelegation(client, agentId, 110.0);  // ✗ ATF-INV-001
Go — Issue & Verify a Delegation ReceiptATF-INV-001/002/005/006
main.go
package main

  import (
      "fmt"
      "log"
      "os"

      atf "github.com/atf-protocol/sdk-go"
  )

  func main() {
      // Initialize client with TIER-1 principal credentials
      client, err := atf.NewClient(atf.ClientConfig{
          PrincipalID:   "HUMAN-harold-nunes-001",
          PrivateKeyB64: os.Getenv("ATF_PRIVATE_KEY_B64"),
          PublicKeyB64:  os.Getenv("ATF_PUBLIC_KEY_B64"),
      })
      if err != nil {
          log.Fatalf("client init: %v", err)
      }

      // Register agent — authority_budget must be ≤ principal's budget (ATF-INV-001)
      air, err := client.RegisterAgent(atf.AgentConfig{
          DisplayName:     "Trading Governance Agent v2",
          Domain:          "FINANCE",
          Vertical:        "equity_trading",
          AuthorityBudget: 75.0,
          Tier:            atf.Tier2,
          Capabilities:   []string{"governance_decision", "risk_assessment"},
      })
      if err != nil {
          log.Fatalf("register agent: %v", err)
      }
      fmt.Printf("Agent: %s\n", air.AgentID)

      // Issue Delegation Receipt — MAR validated at SDK level
      dr, err := client.IssueDR(atf.DRConfig{
          DelegateID:    air.AgentID,
          TaskScope:     atf.TaskScope{Action: "governance_decision", Domain: "FINANCE"},
          BudgetGranted: 75.0,     // ATF-INV-001: 75.0 ≤ 100.0 ✓
          TTLSeconds:    3600,
      })
      if err != nil {
          // errors.As(err, &atf.MARViolationError{}) for budget violations
          log.Fatalf("issue DR: %v", err)
      }
      fmt.Printf("DR: %s (budget: %.1f/%.1f)\n", dr.DelegationID, dr.BudgetGranted, dr.BudgetDelegator)

      // Verify offline — only receipt + public key, no network
      verifier := atf.NewVerifier(os.Getenv("ATF_PUBLIC_KEY_B64"))
      result, err := verifier.Verify(dr)
      if err != nil {
          log.Fatalf("verify: %v", err)
      }
      if result.Verdict != atf.VerdictPass {
          log.Fatalf("verification FAIL: %v", result.Failures)
      }
      fmt.Printf("Verdict: %s (%d checks)\n", result.Verdict, len(result.Checks))
      // Verdict: PASS (6 checks)
  }
Monitor runtime continuity with CESRGC-INV-001 · RGC-INV-003
runtime_continuity.py
from atf_core import ATFSession, CESSnapshot, ContinuityStatus
  from atf_core.exceptions import HALTException

  session = ATFSession(dr=dr, tar=tar)   # Attach to issued DR + TAR

  # Sample CES at regular intervals (or before each execution decision)
  def sample_and_check(session: ATFSession) -> bool:
      snap: CESSnapshot = session.sample_ces(
          ces_temporal=session.remaining_ttl_pct(),   # % of time window remaining
          ces_budget=session.remaining_budget_pct(),  # % of authority budget remaining
          ces_context=session.context_stability_pct(),# 100 - drift_pct
          ces_integrity=session.chain_integrity_pct(),# chain hash verification score
      )
      # CES = T×0.30 + B×0.30 + D×0.20 + I×0.20 — RGC-INV-001 (fixed formula)
      rcr = session.commit_rcr(snap)

      print(f"CES: {rcr.ces_score:.1f} — Status: {rcr.continuity_status}")

      # RGC-INV-003: HALT if CES < 10.0 — this is a protocol invariant
      if rcr.continuity_status == ContinuityStatus.HALT:
          raise HALTException(
              f"CES {rcr.ces_score:.1f} below halt threshold. "
              f"Reauthorization required. RCR: {rcr.rcr_id}"
          )

      return rcr.continuity_status in (
          ContinuityStatus.NOMINAL,
          ContinuityStatus.MONITORING,
      )

  # Sampling loop — call before every governance decision
  for decision in pending_decisions:
      try:
          can_proceed = sample_and_check(session)
          if can_proceed:
              execute_decision(decision)
          else:
              escalate_to_operator(decision, session.latest_rcr)
      except HALTException as e:
          halt_all_execution(str(e))   # RGC-INV-003 — no decisions until reauth
          break
# Normal execution
CES: 94.4 — Status: NOMINAL
CES: 87.1 — Status: NOMINAL
CES: 62.3 — Status: MONITORING
CES: 34.8 — Status: WARNING
CES: 11.2 — Status: CRITICAL — reauthorization required
CES: 7.6 — HALTException: CES below halt threshold. Reauth required.
TypeScript — Runtime Continuity MonitoringRGC-INV-001 · RGC-INV-003
continuity-monitor.ts
import { ATFSession, ContinuityStatus, HALTError } from "@atf-protocol/sdk";

  const session = new ATFSession({ dr, tar });

  async function checkContinuity(): Promise {
    const snap = await session.sampleCES({
      cesTemporal: session.remainingTTLPercent(),
      cesBudget: session.remainingBudgetPercent(),
      cesContext: 100 - session.contextDriftPercent(),
      cesIntegrity: session.chainIntegrityPercent(),
    });
    // Formula: CES = T×0.30 + B×0.30 + D×0.20 + I×0.20 (RGC-INV-001 — immutable)
    const rcr = await session.commitRCR(snap);
    console.log(`CES: ${rcr.cesScore.toFixed(1)} — ${rcr.continuityStatus}`);

    if (rcr.continuityStatus === ContinuityStatus.HALT) {
      throw new HALTError(rcr); // RGC-INV-003 — execution must cease
    }
    return rcr.cesScore >= 50;  // NOMINAL or MONITORING
  }

  // Guard every execution with a CES check
  for (const decision of pendingDecisions) {
    const ok = await checkContinuity().catch((err) => {
      if (err instanceof HALTError) { haltExecution(err.rcr); return false; }
      throw err;
    });
    if (ok) await executeDecision(decision);
    else     await escalateToOperator(decision);
  }
Go — Runtime Continuity MonitoringRGC-INV-001 · RGC-INV-003
continuity.go
package main

  import (
      "errors"
      atf "github.com/atf-protocol/sdk-go"
  )

  func monitorAndExecute(session *atf.Session, decisions []Decision) error {
      for _, d := range decisions {
          snap := atf.CESSnapshot{
              CesTemporal:  session.RemainingTTLPercent(),
              CesBudget:    session.RemainingBudgetPercent(),
              CesContext:   100 - session.ContextDriftPercent(),
              CesIntegrity: session.ChainIntegrityPercent(),
          }
          // CES = T*0.30 + B*0.30 + D*0.20 + I*0.20 — RGC-INV-001
          rcr, err := session.CommitRCR(snap)
          if err != nil {
              return fmt.Errorf("RCR commit: %w", err)
          }

          var haltErr *atf.HALTError
          if errors.As(err, &haltErr) {
              // RGC-INV-003: CES < 10.0 — execution MUST cease
              return fmt.Errorf("HALT: CES %.1f, RCR: %s", rcr.CESScore, rcr.RCRID)
          }

          if rcr.ContinuityStatus == atf.StatusNominal ||
             rcr.ContinuityStatus == atf.StatusMonitoring {
              if err := executeDecision(d); err != nil {
                  return err
              }
          }
      }
      return nil
  }
Export an Evidence Package for regulatorsOEP-INV-001/002 · FEA-INV-001
export_oep.py
from atf_core import ForensicExporter, OEPBundle, ExportAuthorization
  from atf_core.exceptions import ExportAuthorizationError

  # OEP export requires explicit authorization (FEA-INV-001 — RBAC export gate)
  auth = ExportAuthorization(
      authorized_by="HUMAN-harold-nunes-001",
      scope="session_id:SESSION-20260516-001",
      purpose="DFSA regulatory audit 2026-Q2",
      export_format="OEP_V1",
  )

  exporter = ForensicExporter(
      platform_private_key_b64=os.environ["ATF_PRIVATE_KEY_B64"],
      # NOTE: Caller's keys are NEVER embedded in the bundle (FEA-INV-005 / FEA-INV-003)
  )

  try:
      bundle: OEPBundle = exporter.export(
          session_id="SESSION-20260516-001",
          authorization=auth,
          include_rcrs=True,     # Runtime Continuity Records
          include_tars=True,     # Temporal Admissibility Records
          include_drs=True,      # Delegation Receipts
      )
  except ExportAuthorizationError as e:
      print(f"Export denied: {e}")   # FEA-INV-001 gate rejected the request
      raise

  # Bundle is self-contained — verifiable offline with only the platform's public key
  print(f"OEP bundle: {bundle.package_id}")
  print(f"Evidence items: {bundle.item_count}")
  print(f"Merkle root: {bundle.merkle_root[:32]}...")
  print(f"Bundle size: {bundle.size_bytes:,} bytes")
  print(f"PQC signature: ML-DSA-65 by {bundle.signed_by}")

  # Save to disk — send to regulator
  bundle.save("export_DFSA_2026Q2.oep.json")

  # OEP bundle: OEP-1A2B3C4D5E6F7890
  # Evidence items: 1,247
  # Merkle root: 8a3f2b1c4d5e6f7890a1b2c3...
  # Bundle size: 2,341,892 bytes
  # PQC signature: ML-DSA-65 by AID-FINANCE-3A7F9B2C1D4E5F6A
TypeScript — Export Evidence PackageOEP-INV-001/002
export-oep.ts
import { ForensicExporter, ExportAuthorization, OEPBundle } from "@atf-protocol/sdk";
  import { writeFileSync } from "fs";

  const exporter = new ForensicExporter({
    platformPrivateKeyB64: process.env.ATF_PRIVATE_KEY_B64!,
    // Caller keys are never embedded in OEP (FEA-INV-003, FEA-INV-005)
  });

  const auth: ExportAuthorization = {
    authorizedBy: "HUMAN-harold-nunes-001",
    scope: "session_id:SESSION-20260516-001",
    purpose: "DFSA regulatory audit 2026-Q2",
    exportFormat: "OEP_V1",
  };

  const bundle: OEPBundle = await exporter.export({
    sessionId: "SESSION-20260516-001",
    authorization: auth,
    includeRCRs: true,
    includeTARs: true,
    includeDRs: true,
  });

  // Self-contained — verifiable with only the platform public key (OEP-INV-002)
  console.log(`Package: ${bundle.packageId}`);
  console.log(`Items: ${bundle.itemCount}`);
  console.log(`Merkle: ${bundle.merkleRoot.slice(0, 32)}...`);

  writeFileSync("export_DFSA_2026Q2.oep.json", JSON.stringify(bundle.toJSON(), null, 2));
  console.log(`Saved: export_DFSA_2026Q2.oep.json (${bundle.sizeBytes.toLocaleString()} bytes)`);
Go — Export Evidence PackageOEP-INV-001/002
export_oep.go
package main

  import (
      "encoding/json"
      "os"
      atf "github.com/atf-protocol/sdk-go"
  )

  func exportForRegulator(sessionID string) error {
      exporter, _ := atf.NewForensicExporter(atf.ExporterConfig{
          PlatformPrivateKeyB64: os.Getenv("ATF_PRIVATE_KEY_B64"),
          // Caller keys never embedded (FEA-INV-003, FEA-INV-005)
      })

      auth := atf.ExportAuthorization{
          AuthorizedBy: "HUMAN-harold-nunes-001",
          Scope:        "session_id:" + sessionID,
          Purpose:      "DFSA regulatory audit 2026-Q2",
      }

      bundle, err := exporter.Export(atf.ExportConfig{
          SessionID:     sessionID,
          Authorization: auth,
          IncludeRCRs:  true,
          IncludeTARs:  true,
          IncludeDRs:   true,
      })
      if err != nil {
          return fmt.Errorf("export: %w", err)
      }

      data, _ := json.MarshalIndent(bundle, "", "  ")
      if err := os.WriteFile("export_DFSA_2026Q2.oep.json", data, 0600); err != nil {
          return err
      }
      fmt.Printf("OEP: %s (%d items, %d bytes)\n", bundle.PackageID, bundle.ItemCount, bundle.SizeBytes)
      return nil
  }
Verify an OEP bundle — complete chain reconstructionATF-INV-006 · FVP-INV-007
verify_oep.py
from atf_verifier import OEPVerifier, TwoPlaneResult

  # Verifier requires ONLY the platform public key — no platform access (ATF-INV-006)
  verifier = OEPVerifier(platform_public_key_b64=PLATFORM_PUBLIC_KEY_B64)

  # Load the OEP bundle from disk (received from OMNIX, stored for years)
  with open("export_DFSA_2026Q2.oep.json") as f:
      bundle = OEPBundle.load(f)

  # FVP-INV-007: Two-Plane Verification — cryptographic + semantic planes are independent
  result: TwoPlaneResult = verifier.verify_full(bundle)

  # Plane A: Cryptographic verification
  print(f"Crypto plane: {result.crypto_verdict}")
  print(f"  Merkle root:      {'✓' if result.merkle_root_match else '✗'} verified")
  print(f"  PQC signatures:   {'✓' if result.all_sigs_valid else '✗'} {result.sig_count} receipts")
  print(f"  Hash chain:       {'✓' if result.hash_chain_intact else '✗'} complete")

  # Plane B: Semantic verification (protocol invariants)
  print(f"Semantic plane: {result.semantic_verdict}")
  print(f"  MAR invariant:    {'✓' if result.mar_satisfied else '✗'} all DRs")
  print(f"  CES integrity:    {'✓' if result.ces_integrity else '✗'} all RCRs")
  print(f"  Chain roots:      {'✓' if result.roots_valid else '✗'} trace to TIER-1")
  print(f"  HALT compliance:  {'✓' if result.halt_compliant else '✗'} no post-HALT decisions")

  print(f"
Final verdict: {result.final_verdict}")
  # Final verdict: PASS — bundle reconstructed and verified offline
$ python verify_oep.py
Crypto plane: PASS
Merkle root: ✓ verified
PQC signatures: ✓ 1,247 receipts
Hash chain: ✓ complete
Semantic plane: PASS
MAR invariant: ✓ all DRs
CES integrity: ✓ all RCRs
Chain roots: ✓ trace to TIER-1
HALT compliance: ✓ no post-HALT decisions
Final verdict: PASS — 1,247 items verified offline
TypeScript — Offline OEP VerificationATF-INV-006 · FVP-INV-007
verify-oep.ts
import { OEPVerifier, OEPBundle, TwoPlaneResult } from "@atf-protocol/sdk";
  import { readFileSync } from "fs";

  const verifier = new OEPVerifier(PLATFORM_PUBLIC_KEY_B64);
  // No network — only receipt JSON + public key (ATF-INV-006)

  const raw = readFileSync("export_DFSA_2026Q2.oep.json", "utf-8");
  const bundle = OEPBundle.fromJSON(JSON.parse(raw));

  // FVP-INV-007: Two independent verification planes
  const result: TwoPlaneResult = await verifier.verifyFull(bundle);

  if (result.finalVerdict !== "PASS") {
    const failures = result.failures.map(f => `  - ${f.invariant}: ${f.detail}`).join("\n");
    throw new Error(`OEP verification FAIL:\n${failures}`);
  }

  console.log(`✓ ${bundle.itemCount} items verified (crypto + semantic planes)`);
Go — Offline OEP VerificationATF-INV-006 · FVP-INV-007
verify_oep.go
verifier := atf.NewOEPVerifier(platformPublicKeyB64)
  bundle, _ := atf.LoadOEPBundle("export_DFSA_2026Q2.oep.json")

  // Two-plane verification — FVP-INV-007
  result, err := verifier.VerifyFull(bundle)
  if err != nil { log.Fatal(err) }

  if result.FinalVerdict != atf.VerdictPass {
      for _, f := range result.Failures {
          fmt.Printf("FAIL %s: %s\n", f.Invariant, f.Detail)
      }
      os.Exit(1)
  }
  fmt.Printf("✓ %d items verified offline\n", bundle.ItemCount)
Interoperability note (GPIL): ATF supports three levels of governance policy interoperability across runtimes — Cryptographic (shared ML-DSA-65 primitives), Protocol (shared wire format and invariants), and Governance Policy (sovereign policy divergence via Policy Parameter Registry). DRs and RCRs from any ATF-conformant runtime are verifiable by the same verifier, regardless of the originating platform. See RFC-ATF-3 for the complete GPIL specification.