Skip to content

Integration Guides AI Framework Integration

dev-mondoshawan edited this page Jul 1, 2026 · 1 revision

AI Framework Integration

**Referenced Files in This Document** - [README.md](file://README.md) - [docs/ai-frameworks.md](file://docs/ai-frameworks.md) - [docs/reputation-model.md](file://docs/reputation-model.md) - [packages/sdk/src/index.ts](file://packages/sdk/src/index.ts) - [packages/sdk/src/agent.ts](file://packages/sdk/src/agent.ts) - [packages/sdk/src/challenge.ts](file://packages/sdk/src/challenge.ts) - [packages/sdk/src/did.ts](file://packages/sdk/src/did.ts) - [packages/sdk/src/verifier.ts](file://packages/sdk/src/verifier.ts) - [packages/sdk/src/keys.ts](file://packages/sdk/src/keys.ts) - [packages/sdk/src/types.ts](file://packages/sdk/src/types.ts) - [packages/sdk/test/integration.test.ts](file://packages/sdk/test/integration.test.ts) - [src/CountersigIdentity.sol](file://src/CountersigIdentity.sol) - [src/CountersigReputation.sol](file://src/CountersigReputation.sol) - [src/CountersigStaking.sol](file://src/CountersigStaking.sol) - [oracle/scoring.js](file://oracle/scoring.js) - [oracle/index.js](file://oracle/index.js)

Table of Contents

  1. Introduction
  2. Project Structure
  3. Core Components
  4. Architecture Overview
  5. Detailed Component Analysis
  6. Dependency Analysis
  7. Performance Considerations
  8. Troubleshooting Guide
  9. Conclusion
  10. Appendices

Introduction

This document explains how to integrate Countersig identity, authentication, and reputation into AI agent workflows across LangChain, AutoGen, and CrewAI. It provides framework-specific integration patterns, code snippet paths, and best practices for building secure, auditable, and reputation-aware multi-agent systems. You will learn how to:

  • Generate deterministic agent identities (DIDs)
  • Perform agent-to-agent challenge-response authentication
  • Gate agent actions on reputation thresholds
  • Audit agent actions with CounterAudit
  • Manage identities, keys, and reputation decisions in production-grade AI applications

Project Structure

The repository is organized into:

  • Smart contracts implementing identity, reputation, and staking
  • A TypeScript SDK for agent creation, challenge-response, and verification
  • Oracle module for off-chain reputation computation and on-chain updates
  • Documentation for AI framework integrations and reputation mechanics
graph TB
subgraph "Contracts"
ID["CountersigIdentity.sol"]
REP["CountersigReputation.sol"]
ST["CountersigStaking.sol"]
end
subgraph "SDK"
IDX["index.ts exports"]
AG["agent.ts"]
CH["challenge.ts"]
DI["did.ts"]
VF["verifier.ts"]
KY["keys.ts"]
TP["types.ts"]
end
subgraph "Oracle"
SC["scoring.js"]
OR["index.js"]
end
subgraph "Docs"
AF["ai-frameworks.md"]
RM["reputation-model.md"]
end
IDX --> AG
IDX --> VF
IDX --> CH
IDX --> DI
IDX --> KY
VF --> ID
VF --> REP
VF --> ST
OR --> SC
OR --> REP
AF --> AG
AF --> VF
RM --> REP
Loading

Diagram sources

  • packages/sdk/src/index.ts:1-36
  • packages/sdk/src/agent.ts:1-80
  • packages/sdk/src/challenge.ts:1-78
  • packages/sdk/src/did.ts:1-29
  • packages/sdk/src/verifier.ts:1-160
  • packages/sdk/src/keys.ts:1-91
  • packages/sdk/src/types.ts:1-66
  • src/CountersigIdentity.sol:1-227
  • src/CountersigReputation.sol:1-181
  • src/CountersigStaking.sol:1-331
  • oracle/scoring.js:1-50
  • oracle/index.js:1-178
  • docs/ai-frameworks.md:1-269
  • docs/reputation-model.md:1-156

Section sources

  • README.md:1-415
  • docs/ai-frameworks.md:1-269
  • docs/reputation-model.md:1-156

Core Components

  • CountersigAgent: creates deterministic DIDs, generates challenges, signs payloads with Ed25519, and exposes public key material for on-chain registration.
  • CountersigVerifier: resolves identities, verifies Ed25519 signatures, checks reputation thresholds, builds W3C DID Documents, and registers agents on-chain.
  • Challenge utilities: generate challenge payloads, sign and verify Ed25519 signatures, parse payloads, and detect expiration.
  • DID utilities: format, parse, and compute didHash deterministically.
  • Keys utilities: encode/decode base58, convert between hex and bytes, derive key pairs from seeds, and produce multibase-encoded public keys.
  • Types: shared interfaces for identities, reputation data, challenges, and DID documents.
  • Contracts: CountersigIdentity (DID anchoring and status), CountersigReputation (6-factor score store), CountersigStaking (slash lifecycle and stake management).
  • Oracle: computes 6-factor scores and writes them on-chain periodically.

Section sources

  • packages/sdk/src/agent.ts:1-80
  • packages/sdk/src/verifier.ts:1-160
  • packages/sdk/src/challenge.ts:1-78
  • packages/sdk/src/did.ts:1-29
  • packages/sdk/src/keys.ts:1-91
  • packages/sdk/src/types.ts:1-66
  • src/CountersigIdentity.sol:1-227
  • src/CountersigReputation.sol:1-181
  • src/CountersigStaking.sol:1-331
  • oracle/scoring.js:1-50
  • oracle/index.js:1-178

Architecture Overview

Countersig provides a layered architecture:

  • Off-chain: agents generate Ed25519 keypairs, issue challenges, and sign payloads.
  • Decentralized Identity: DIDs are deterministically anchored on-chain via didHash.
  • On-chain: Identity, Reputation, and Staking contracts maintain state and enforce policy.
  • Oracle (Phase 2): aggregates attestations and writes reputation scores.
graph TB
A["Agent Node A<br/>Ed25519 Keys"] --> |"PKI challenge-response"| B["Agent Node B"]
B --> |"resolve DID"| R["DID Resolver<br/>did:countersig method"]
R --> |"reads pubkey + status"| ID["CountersigIdentity<br/>DID anchoring · pubkey storage · AgentStatus"]
B --> |"query score"| REP["CountersigReputation<br/>6-factor score store"]
ST["CountersigStaking<br/>CSIG bonds · slash lifecycle"] --> |"updateStatus(Slashed)"| ID
ST --> |"zeroReputation()"| REP
OC["Reputation Oracle<br/>24h epoch aggregation"] --> |"updateReputation()"| REP
Loading

Diagram sources

  • README.md:22-51
  • src/CountersigIdentity.sol:1-227
  • src/CountersigReputation.sol:1-181
  • src/CountersigStaking.sol:1-331
  • oracle/index.js:1-178

Detailed Component Analysis

LangChain Integration Patterns

Patterns:

  • Wrap tools to include agent_did and audit every action.
  • Gate agent execution on reputation thresholds before performing sensitive operations.

Implementation references:

  • Tool wrapper and audit ingestion: docs/ai-frameworks.md:13-58
  • Reputation-gated execution: docs/ai-frameworks.md:62-73

Best practices:

  • Use fire-and-forget audit calls to avoid blocking the critical path.
  • Cache didHash and DID for the agent’s lifetime to reduce repeated computations.
  • Enforce a minimum threshold (e.g., 40–60) depending on task sensitivity.

Section sources

  • docs/ai-frameworks.md:7-73

AutoGen Integration Patterns

Patterns:

  • Extend AssistantAgent to audit replies and include agent_did in every audit call.
  • Maintain a single CountersigAgent instance per assistant to reuse identity and keys.

Implementation references:

  • Assistant subclass with audit hook: docs/ai-frameworks.md:81-121

Best practices:

  • Ensure audit posting occurs after reply generation but before returning control to the framework.
  • Keep CA API key in environment variables and scope permissions appropriately.

Section sources

  • docs/ai-frameworks.md:77-121

CrewAI Integration Patterns

Patterns:

  • Add callbacks to tasks to audit results and include agent_did.
  • Embed agent_did in the agent’s system/backstory for discoverability.

Implementation references:

  • Crew task auditing: docs/ai-frameworks.md:129-167

Best practices:

  • Use short previews for raw_event payloads to stay within API limits.
  • Consider per-task thresholds if tasks vary widely in risk.

Section sources

  • docs/ai-frameworks.md:125-167

Node.js/TypeScript Middleware Pattern

Pattern:

  • A thin middleware that executes an async function and fires an audit request afterwards.
  • Handles challenge-response for peer-to-peer trust verification.

Implementation references:

  • Middleware wrapper: docs/ai-frameworks.md:177-216
  • Challenge-response flow: docs/ai-frameworks.md:222-248

Section sources

  • docs/ai-frameworks.md:171-248

Agent Authentication and Challenge-Response

End-to-end flow:

  • Peer A issues a challenge with a payload containing its DID, nonce, and timestamp.
  • Peer B signs the payload with its Ed25519 private key and returns the signature.
  • Peer A resolves the public key from chain, verifies the signature, and checks reputation threshold.
sequenceDiagram
participant A as "Agent A"
participant B as "Agent B"
participant ID as "CountersigIdentity"
participant REP as "CountersigReputation"
A->>B : "issueChallenge(did)"
B->>B : "signChallenge(payload)"
B-->>A : "{ did, signature }"
A->>ID : "getIdentity(didHash)"
ID-->>A : "{ ed25519PubKey, status }"
A->>A : "verifyChallenge(payload, signature, pubKey)"
A->>REP : "meetsThreshold(didHash, threshold)"
REP-->>A : "true/false"
alt "signature valid AND meets threshold"
A-->>B : "trusted"
else
A-->>B : "rejected"
end
Loading

Diagram sources

  • packages/sdk/src/agent.ts:70-78
  • packages/sdk/src/challenge.ts:11-35
  • packages/sdk/src/verifier.ts:100-107
  • packages/sdk/src/verifier.ts:85-88
  • src/CountersigIdentity.sol:195-202
  • src/CountersigReputation.sol:171-173

Section sources

  • packages/sdk/src/agent.ts:70-78
  • packages/sdk/src/challenge.ts:11-35
  • packages/sdk/src/verifier.ts:100-107
  • packages/sdk/src/verifier.ts:85-88
  • src/CountersigIdentity.sol:195-202
  • src/CountersigReputation.sol:171-173

Reputation-Based Decision Making

  • Threshold gating: use meetsThreshold(didHash, N) to gate sensitive operations.
  • Score composition: fee activity, success rate, age, external trust, community, and propagation.
  • Oracle-driven updates: off-chain scoring aggregated and written on-chain.
flowchart TD
Start(["Decision Entry"]) --> LoadRep["Load ReputationData for didHash"]
LoadRep --> CheckThreshold{"meetsThreshold(didHash, N)?"}
CheckThreshold --> |No| Deny["Reject Action / Delegate"]
CheckThreshold --> |Yes| Allow["Proceed with Action / Delegate"]
Deny --> End(["Exit"])
Allow --> End
Loading

Diagram sources

  • src/CountersigReputation.sol:171-173
  • docs/reputation-model.md:9-16

Section sources

  • src/CountersigReputation.sol:171-173
  • docs/reputation-model.md:1-156

Multi-Agent Systems and Collaborative Networks

Patterns:

  • Use reputation thresholds to decide whether to delegate tasks to peers.
  • Build trust graphs by tracking successful attestations and propagation scores.
  • Apply challenge-response for inter-agent authentication in collaborative workflows.

Implementation references:

  • General pattern (identity, audit, verify): docs/ai-frameworks.md:252-261

Section sources

  • docs/ai-frameworks.md:252-261

Chain-of-Thought Reasoning with Identity and Audit

Patterns:

  • Include agent_did in every major reasoning step or tool call.
  • Use reputation thresholds to gate complex reasoning steps requiring higher trust.

Implementation references:

  • Audit on action: docs/ai-frameworks.md:13-58

Section sources

  • docs/ai-frameworks.md:13-58

Dependency Analysis

High-level dependencies among SDK modules and contracts:

graph LR
AG["agent.ts"] --> CH["challenge.ts"]
AG --> DI["did.ts"]
AG --> KY["keys.ts"]
VF["verifier.ts"] --> ID["CountersigIdentity.sol"]
VF --> REP["CountersigReputation.sol"]
VF --> ST["CountersigStaking.sol"]
VF --> CH
VF --> DI
VF --> KY
OR["oracle/index.js"] --> SC["oracle/scoring.js"]
OR --> REP
Loading

Diagram sources

  • packages/sdk/src/agent.ts:1-80
  • packages/sdk/src/challenge.ts:1-78
  • packages/sdk/src/did.ts:1-29
  • packages/sdk/src/keys.ts:1-91
  • packages/sdk/src/verifier.ts:1-160
  • src/CountersigIdentity.sol:1-227
  • src/CountersigReputation.sol:1-181
  • src/CountersigStaking.sol:1-331
  • oracle/index.js:1-178
  • oracle/scoring.js:1-50

Section sources

  • packages/sdk/src/index.ts:1-36
  • packages/sdk/src/agent.ts:1-80
  • packages/sdk/src/verifier.ts:1-160
  • src/CountersigIdentity.sol:1-227
  • src/CountersigReputation.sol:1-181
  • src/CountersigStaking.sol:1-331
  • oracle/index.js:1-178
  • oracle/scoring.js:1-50

Performance Considerations

  • Minimize on-chain reads: cache didHash and DID locally; reuse resolved identity and reputation data where feasible.
  • Batch audit requests: coalesce multiple actions into fewer audit calls to reduce latency and cost.
  • Tune challenge TTL: set appropriate challenge lifetimes to balance security and usability.
  • Optimize reputation checks: pre-check didHash validity and chainId to avoid unnecessary RPC calls.
  • Use asynchronous audits: fire-and-forget audit ingestion to avoid blocking agent execution.

[No sources needed since this section provides general guidance]

Troubleshooting Guide

Common issues and resolutions:

  • Signature verification fails

    • Ensure the challenge payload matches exactly what was signed (including DID, nonce, and timestamp).
    • Confirm the public key is retrieved from chain and decoded correctly.
    • Validate that the DID belongs to the correct chainId and agent address.
    • Reference: packages/sdk/src/challenge.ts:25-35, packages/sdk/src/verifier.ts:100-107
  • Reputation threshold not met

    • Verify didHash correctness and chainId alignment.
    • Confirm the agent is registered and not slashed.
    • Check that the oracle has updated scores recently.
    • Reference: src/CountersigReputation.sol:171-173, docs/reputation-model.md:104-113
  • Agent not recognized (not registered)

    • Ensure on-chain registration occurred and the didHash is computed deterministically.
    • Confirm operator has deposited stake and status is Active.
    • Reference: src/CountersigIdentity.sol:120-141, src/CountersigStaking.sol:154-165
  • Integration tests fail in CI

    • Ensure environment variables for RPC and contract addresses are present.
    • Confirm the test runner waits for deployment readiness.
    • Reference: packages/sdk/test/integration.test.ts:1-121

Section sources

  • packages/sdk/src/challenge.ts:25-35
  • packages/sdk/src/verifier.ts:100-107
  • src/CountersigReputation.sol:171-173
  • docs/reputation-model.md:104-113
  • src/CountersigIdentity.sol:120-141
  • src/CountersigStaking.sol:154-165
  • packages/sdk/test/integration.test.ts:1-121

Conclusion

By integrating Countersig into AI frameworks, agents gain verifiable identity, robust authentication, and reputation-aware decision-making. The SDK and contracts provide a clear, test-backed foundation for building secure, auditable, and trustworthy multi-agent systems. Adopt the patterns outlined here to manage identities, enforce challenge-response, gate on reputation, and optimize performance in production.

[No sources needed since this section summarizes without analyzing specific files]

Appendices

Best Practices Checklist

  • Initialize agents with deterministic DIDs and store Ed25519 seeds securely.
  • Always audit actions with agent_did and include concise previews.
  • Enforce meetsThreshold before delegating or accepting work from peers.
  • Use challenge-response for inter-agent trust in collaborative networks.
  • Monitor reputation updates and adjust thresholds according to risk profiles.
  • Keep SDK and contract versions aligned; leverage UUPS upgrades responsibly.

[No sources needed since this section provides general guidance]

Clone this wiki locally