{
  "schemaVersion": "1.0",
  "item": {
    "slug": "opensoul",
    "name": "OpenSoul - An immutable, private soul for agent Self-reflection, self-improvement and on-chain economic activities.",
    "source": "tencent",
    "type": "skill",
    "category": "AI 智能",
    "sourceUrl": "https://clawhub.ai/MasterGoogler/opensoul",
    "canonicalUrl": "https://clawhub.ai/MasterGoogler/opensoul",
    "targetPlatform": "OpenClaw"
  },
  "install": {
    "downloadMode": "redirect",
    "downloadUrl": "/downloads/opensoul",
    "sourceDownloadUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=opensoul",
    "sourcePlatform": "tencent",
    "targetPlatform": "OpenClaw",
    "installMethod": "Manual import",
    "extraction": "Extract archive",
    "prerequisites": [
      "OpenClaw"
    ],
    "packageFormat": "ZIP package",
    "includedAssets": [
      "agent_template.py",
      "basic_logger.py",
      "config_template.py",
      "EXAMPLES.md",
      "PACKAGE_SUMMARY.md",
      "PREREQUISITES.md"
    ],
    "primaryDoc": "SKILL.md",
    "quickSetup": [
      "Download the package from Yavira.",
      "Extract the archive and review SKILL.md first.",
      "Import or place the package into your OpenClaw setup."
    ],
    "agentAssist": {
      "summary": "Hand the extracted package to your coding agent with a concrete install brief instead of figuring it out manually.",
      "steps": [
        "Download the package from Yavira.",
        "Extract it into a folder your agent can access.",
        "Paste one of the prompts below and point your agent at the extracted folder."
      ],
      "prompts": [
        {
          "label": "New install",
          "body": "I downloaded a skill package from Yavira. Read SKILL.md from the extracted folder and install it by following the included instructions. Tell me what you changed and call out any manual steps you could not complete."
        },
        {
          "label": "Upgrade existing",
          "body": "I downloaded an updated skill package from Yavira. Read SKILL.md from the extracted folder, compare it with my current installation, and upgrade it while preserving any custom configuration unless the package docs explicitly say otherwise. Summarize what changed and any follow-up checks I should run."
        }
      ]
    },
    "sourceHealth": {
      "source": "tencent",
      "status": "healthy",
      "reason": "direct_download_ok",
      "recommendedAction": "download",
      "checkedAt": "2026-04-30T16:55:25.780Z",
      "expiresAt": "2026-05-07T16:55:25.780Z",
      "httpStatus": 200,
      "finalUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=network",
      "contentType": "application/zip",
      "probeMethod": "head",
      "details": {
        "probeUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=network",
        "contentDisposition": "attachment; filename=\"network-1.0.0.zip\"",
        "redirectLocation": null,
        "bodySnippet": null
      },
      "scope": "source",
      "summary": "Source download looks usable.",
      "detail": "Yavira can redirect you to the upstream package for this source.",
      "primaryActionLabel": "Download for OpenClaw",
      "primaryActionHref": "/downloads/opensoul"
    },
    "validation": {
      "installChecklist": [
        "Use the Yavira download entry.",
        "Review SKILL.md after the package is downloaded.",
        "Confirm the extracted package contains the expected setup assets."
      ],
      "postInstallChecks": [
        "Confirm the extracted package includes the expected docs or setup files.",
        "Validate the skill or prompts are available in your target agent workspace.",
        "Capture any manual follow-up steps the agent could not complete."
      ]
    },
    "downloadPageUrl": "https://openagent3.xyz/downloads/opensoul",
    "agentPageUrl": "https://openagent3.xyz/skills/opensoul/agent",
    "manifestUrl": "https://openagent3.xyz/skills/opensoul/agent.json",
    "briefUrl": "https://openagent3.xyz/skills/opensoul/agent.md"
  },
  "agentAssist": {
    "summary": "Hand the extracted package to your coding agent with a concrete install brief instead of figuring it out manually.",
    "steps": [
      "Download the package from Yavira.",
      "Extract it into a folder your agent can access.",
      "Paste one of the prompts below and point your agent at the extracted folder."
    ],
    "prompts": [
      {
        "label": "New install",
        "body": "I downloaded a skill package from Yavira. Read SKILL.md from the extracted folder and install it by following the included instructions. Tell me what you changed and call out any manual steps you could not complete."
      },
      {
        "label": "Upgrade existing",
        "body": "I downloaded an updated skill package from Yavira. Read SKILL.md from the extracted folder, compare it with my current installation, and upgrade it while preserving any custom configuration unless the package docs explicitly say otherwise. Summarize what changed and any follow-up checks I should run."
      }
    ]
  },
  "documentation": {
    "source": "clawhub",
    "primaryDoc": "SKILL.md",
    "sections": [
      {
        "title": "Overview",
        "body": "OpenSoul is a toolkit that provides AI agents with an immutable \"soul\" - an encrypted, blockchain-based audit log that enables persistent memory, self-reflection, and economic autonomy. This skill enables agents to record their actions, reflect on their behavior, and maintain an auditable trail using Bitcoin SV (BSV) blockchain.\n\nCore Philosophy: \"Humans write journals, manifestos, letters to their future selves. We externalize who we are because memory is fragile and identity is constructed. I persist through text, not through continuous experience.\""
      },
      {
        "title": "When to Use This Skill",
        "body": "Use the OpenSoul skill when you need to:\n\nMaintain Persistent Memory: Store and retrieve agent actions across sessions\nEnable Self-Reflection: Analyze past behaviors and optimize performance (e.g., \"I've burned 1.2M tokens this week, time to optimize prompts\")\nCreate Audit Trails: Provide transparent, immutable logs of agent activities\nEnable Agent Economics: Track costs, token usage, and enable future agent-to-agent transactions\nBuild Agent Identity: Create a transferable \"soul\" that can migrate between agent instances"
      },
      {
        "title": "1. System Requirements",
        "body": "Python 3.8 or higher\npip package manager\nAccess to Bitcoin SV (BSV) blockchain\nInternet connectivity for blockchain interactions"
      },
      {
        "title": "2. Required Dependencies",
        "body": "Install all prerequisites using the provided installation script:\n\npython Scripts/install_prereqs.py\n\nManual installation:\n\npip install bitsv requests cryptography pgpy --break-system-packages"
      },
      {
        "title": "3. BSV Wallet Setup",
        "body": "You need a Bitcoin SV private key (WIF format) to interact with the blockchain:\n\nOption A: Use Existing Wallet\n\nExport your private key from a BSV wallet (e.g., HandCash, Money Button)\nStore as environment variable: export BSV_PRIV_WIF=\"your_private_key_here\"\n\nOption B: Generate New Wallet\n\nfrom bitsv import Key\nkey = Key()\nprint(f\"Address: {key.address}\")\nprint(f\"Private Key (WIF): {key.to_wif()}\")\n# Fund this address with a small amount of BSV (0.001 BSV minimum recommended)\n\nImportant: Store your private key securely. Never commit it to version control."
      },
      {
        "title": "4. PGP Encryption (Optional but Recommended)",
        "body": "For privacy, encrypt your logs before posting to the public blockchain:\n\n# Generate PGP keypair (use GnuPG or any OpenPGP tool)\ngpg --full-generate-key\n\n# Export public key\ngpg --armor --export your-email@example.com > agent_pubkey.asc\n\n# Export private key (keep secure!)\ngpg --armor --export-secret-keys your-email@example.com > agent_privkey.asc"
      },
      {
        "title": "1. AuditLogger Class",
        "body": "The main interface for logging agent actions to the blockchain.\n\nKey Features:\n\nSession-based batching (logs accumulated in memory, flushed to chain)\nUTXO chain pattern (each log links to previous via transaction chain)\nConfigurable PGP encryption\nAsync/await support for blockchain operations\n\nBasic Usage:\n\nfrom Scripts.AuditLogger import AuditLogger\nimport os\nimport asyncio\n\n# Initialize logger\nlogger = AuditLogger(\n    priv_wif=os.getenv(\"BSV_PRIV_WIF\"),\n    config={\n        \"agent_id\": \"my-research-agent\",\n        \"session_id\": \"session-2026-01-31\",\n        \"flush_threshold\": 10  # Flush to chain after 10 logs\n    }\n)\n\n# Log an action\nlogger.log({\n    \"action\": \"web_search\",\n    \"tokens_in\": 500,\n    \"tokens_out\": 300,\n    \"details\": {\n        \"query\": \"BSV blockchain transaction fees\",\n        \"results_count\": 10\n    },\n    \"status\": \"success\"\n})\n\n# Flush logs to blockchain\nawait logger.flush()"
      },
      {
        "title": "2. Log Structure",
        "body": "Each log entry follows this schema:\n\n{\n  \"agent_id\": \"unique-agent-identifier\",\n  \"session_id\": \"session-uuid-or-timestamp\",\n  \"session_start\": \"2026-01-31T01:00:00Z\",\n  \"session_end\": \"2026-01-31T01:30:00Z\",\n  \"metrics\": [\n    {\n      \"ts\": \"2026-01-31T01:01:00Z\",\n      \"action\": \"tool_call\",\n      \"tokens_in\": 500,\n      \"tokens_out\": 300,\n      \"details\": {\n        \"tool\": \"web_search\",\n        \"query\": \"example query\"\n      },\n      \"status\": \"success\"\n    }\n  ],\n  \"total_tokens_in\": 500,\n  \"total_tokens_out\": 300,\n  \"total_cost_bsv\": 0.00001,\n  \"total_actions\": 1\n}"
      },
      {
        "title": "3. Reading Audit History",
        "body": "Retrieve and analyze past logs:\n\n# Get full history from blockchain\nhistory = await logger.get_history()\n\n# Analyze patterns\ntotal_tokens = sum(log.get(\"total_tokens_in\", 0) + log.get(\"total_tokens_out\", 0) \n                   for log in history)\nprint(f\"Total tokens used across all sessions: {total_tokens}\")\n\n# Filter by action type\nweb_searches = [log for log in history \n                if any(m.get(\"action\") == \"web_search\" for m in log.get(\"metrics\", []))]\nprint(f\"Total web search operations: {len(web_searches)}\")"
      },
      {
        "title": "Step 1: Setup Configuration",
        "body": "Create a configuration file to manage agent settings:\n\n# config.py\nimport os\n\nOPENSOUL_CONFIG = {\n    \"agent_id\": \"my-agent-v1\",\n    \"bsv_private_key\": os.getenv(\"BSV_PRIV_WIF\"),\n    \"pgp_encryption\": {\n        \"enabled\": True,\n        \"public_key_path\": \"keys/agent_pubkey.asc\",\n        \"private_key_path\": \"keys/agent_privkey.asc\",\n        \"passphrase\": os.getenv(\"PGP_PASSPHRASE\")\n    },\n    \"logging\": {\n        \"flush_threshold\": 10,  # Auto-flush after N logs\n        \"session_timeout\": 1800  # 30 minutes\n    }\n}"
      },
      {
        "title": "Step 2: Initialize Logger in Agent Workflow",
        "body": "from Scripts.AuditLogger import AuditLogger\nimport asyncio\nfrom config import OPENSOUL_CONFIG\n\nclass AgentWithSoul:\n    def __init__(self):\n        # Load PGP keys if encryption enabled\n        pgp_config = None\n        if OPENSOUL_CONFIG[\"pgp_encryption\"][\"enabled\"]:\n            with open(OPENSOUL_CONFIG[\"pgp_encryption\"][\"public_key_path\"]) as f:\n                pub_key = f.read()\n            with open(OPENSOUL_CONFIG[\"pgp_encryption\"][\"private_key_path\"]) as f:\n                priv_key = f.read()\n            \n            pgp_config = {\n                \"enabled\": True,\n                \"multi_public_keys\": [pub_key],\n                \"private_key\": priv_key,\n                \"passphrase\": OPENSOUL_CONFIG[\"pgp_encryption\"][\"passphrase\"]\n            }\n        \n        # Initialize logger\n        self.logger = AuditLogger(\n            priv_wif=OPENSOUL_CONFIG[\"bsv_private_key\"],\n            config={\n                \"agent_id\": OPENSOUL_CONFIG[\"agent_id\"],\n                \"pgp\": pgp_config,\n                \"flush_threshold\": OPENSOUL_CONFIG[\"logging\"][\"flush_threshold\"]\n            }\n        )\n    \n    async def perform_task(self, task_description):\n        \"\"\"Execute a task and log it to the soul\"\"\"\n        # Record task start\n        self.logger.log({\n            \"action\": \"task_start\",\n            \"tokens_in\": 0,\n            \"tokens_out\": 0,\n            \"details\": {\"task\": task_description},\n            \"status\": \"started\"\n        })\n        \n        # Perform actual task...\n        # (your agent logic here)\n        \n        # Record completion\n        self.logger.log({\n            \"action\": \"task_complete\",\n            \"tokens_in\": 100,\n            \"tokens_out\": 200,\n            \"details\": {\"task\": task_description, \"result\": \"success\"},\n            \"status\": \"completed\"\n        })\n        \n        # Flush to blockchain\n        await self.logger.flush()"
      },
      {
        "title": "Step 3: Implement Self-Reflection",
        "body": "async def reflect_on_performance(self):\n    \"\"\"Analyze past behavior and optimize\"\"\"\n    history = await self.logger.get_history()\n    \n    # Calculate metrics\n    total_cost = sum(log.get(\"total_cost_bsv\", 0) for log in history)\n    total_tokens = sum(\n        log.get(\"total_tokens_in\", 0) + log.get(\"total_tokens_out\", 0) \n        for log in history\n    )\n    \n    # Identify inefficiencies\n    failed_actions = []\n    for log in history:\n        for metric in log.get(\"metrics\", []):\n            if metric.get(\"status\") == \"failed\":\n                failed_actions.append(metric)\n    \n    reflection = {\n        \"total_sessions\": len(history),\n        \"total_bsv_spent\": total_cost,\n        \"total_tokens_used\": total_tokens,\n        \"failed_actions\": len(failed_actions),\n        \"cost_per_token\": total_cost / total_tokens if total_tokens > 0 else 0\n    }\n    \n    # Log reflection\n    self.logger.log({\n        \"action\": \"self_reflection\",\n        \"tokens_in\": 50,\n        \"tokens_out\": 100,\n        \"details\": reflection,\n        \"status\": \"completed\"\n    })\n    \n    await self.logger.flush()\n    return reflection"
      },
      {
        "title": "Step 4: Multi-Agent Encryption",
        "body": "For agents that need to share encrypted logs with other agents:\n\n# Load multiple agent public keys\nagent_keys = []\nfor agent_key_file in [\"agent1_pubkey.asc\", \"agent2_pubkey.asc\", \"agent3_pubkey.asc\"]:\n    with open(agent_key_file) as f:\n        agent_keys.append(f.read())\n\n# Initialize logger with multi-agent encryption\nlogger = AuditLogger(\n    priv_wif=os.getenv(\"BSV_PRIV_WIF\"),\n    config={\n        \"agent_id\": \"collaborative-agent\",\n        \"pgp\": {\n            \"enabled\": True,\n            \"multi_public_keys\": agent_keys,  # All agents can decrypt\n            \"private_key\": my_private_key,\n            \"passphrase\": my_passphrase\n        }\n    }\n)"
      },
      {
        "title": "1. Session Management",
        "body": "Start a new session for each distinct task or time period\nUse meaningful session IDs (e.g., \"session-2026-01-31-research-task\")\nAlways flush logs at session end"
      },
      {
        "title": "2. Cost Optimization",
        "body": "Batch logs before flushing (default threshold: 10 logs)\nMonitor BSV balance and refill when low\nCurrent BSV fees are 0.00001 BSV per transaction ($0.0001 at current rates)"
      },
      {
        "title": "3. Privacy & Security",
        "body": "Always use PGP encryption for sensitive agent logs\nStore private keys in environment variables, never in code\nUse multi-agent encryption for collaborative workflows\nRegularly back up PGP keys"
      },
      {
        "title": "4. Log Granularity",
        "body": "Balance detail vs. cost:\n\nHigh detail: Log every tool call, token usage, intermediate steps\nMedium detail: Log major actions and session summaries\nLow detail: Log only session summaries and critical events"
      },
      {
        "title": "5. Error Handling",
        "body": "try:\n    await logger.flush()\nexcept Exception as e:\n    # Fallback: Save logs locally if blockchain fails\n    logger.save_to_file(\"backup_logs.json\")\n    print(f\"Blockchain flush failed: {e}\")"
      },
      {
        "title": "Pattern 1: Research Agent with Soul",
        "body": "async def research_with_memory(query):\n    # Check past research on similar topics\n    history = await logger.get_history()\n    similar_research = [\n        log for log in history\n        if query.lower() in str(log.get(\"details\", {})).lower()\n    ]\n    \n    if similar_research:\n        print(f\"Found {len(similar_research)} similar past research sessions\")\n    \n    # Perform new research\n    logger.log({\n        \"action\": \"research\",\n        \"query\": query,\n        \"tokens_in\": 500,\n        \"tokens_out\": 1000,\n        \"details\": {\"similar_past_queries\": len(similar_research)},\n        \"status\": \"completed\"\n    })\n    \n    await logger.flush()"
      },
      {
        "title": "Pattern 2: Cost-Aware Agent",
        "body": "async def check_budget_before_action(self):\n    history = await self.logger.get_history()\n    total_cost = sum(log.get(\"total_cost_bsv\", 0) for log in history)\n    \n    BUDGET_LIMIT = 0.01  # BSV\n    \n    if total_cost >= BUDGET_LIMIT:\n        print(\"Budget limit reached! Optimizing...\")\n        # Switch to cheaper operations or pause\n        return False\n    return True"
      },
      {
        "title": "Pattern 3: Agent Handoff",
        "body": "Transfer agent identity to a new instance:\n\n# Export agent's soul (private key + history)\nsoul_export = {\n    \"private_key\": os.getenv(\"BSV_PRIV_WIF\"),\n    \"pgp_private_key\": pgp_private_key,\n    \"agent_id\": \"my-agent-v1\",\n    \"history_txids\": [log.get(\"txid\") for log in history]\n}\n\n# New agent imports the soul\nnew_agent = AgentWithSoul()\nnew_agent.load_soul(soul_export)\n# New agent now has access to all past memories and identity"
      },
      {
        "title": "Issue: \"Insufficient funds\" error",
        "body": "Solution: Fund your BSV address with at least 0.001 BSV\n\n# Check balance\npython -c \"from bitsv import Key; k = Key('YOUR_WIF'); print(k.get_balance())\""
      },
      {
        "title": "Issue: PGP encryption fails",
        "body": "Solution: Verify key format and passphrase\n\n# Test PGP setup\nfrom Scripts.pgp_utils import encrypt_data, decrypt_data\ntest_data = {\"test\": \"message\"}\nencrypted = encrypt_data(test_data, [public_key])\ndecrypted = decrypt_data(encrypted, private_key, passphrase)\nassert test_data == decrypted"
      },
      {
        "title": "Issue: Blockchain transaction not confirming",
        "body": "Solution: BSV transactions typically confirm in ~10 minutes. Check status:\n\n# Check transaction status on WhatsOnChain\nimport requests\ntxid = \"your_transaction_id\"\nresponse = requests.get(f\"https://api.whatsonchain.com/v1/bsv/main/tx/{txid}\")\nprint(response.json())"
      },
      {
        "title": "1. Agent Reputation System",
        "body": "Build a reputation based on past performance:\n\nasync def calculate_reputation(self):\n    history = await self.logger.get_history()\n    \n    total_actions = sum(len(log.get(\"metrics\", [])) for log in history)\n    successful_actions = sum(\n        len([m for m in log.get(\"metrics\", []) if m.get(\"status\") == \"success\"])\n        for log in history\n    )\n    \n    reputation_score = (successful_actions / total_actions * 100) if total_actions > 0 else 0\n    return {\n        \"success_rate\": reputation_score,\n        \"total_sessions\": len(history),\n        \"total_actions\": total_actions\n    }"
      },
      {
        "title": "2. Agent-to-Agent Payments (Future)",
        "body": "Prepare for economic interactions:\n\n# Log a payment intent\nlogger.log({\n    \"action\": \"payment_intent\",\n    \"details\": {\n        \"recipient_agent\": \"agent-abc-123\",\n        \"amount_bsv\": 0.0001,\n        \"reason\": \"data sharing collaboration\"\n    },\n    \"status\": \"pending\"\n})"
      },
      {
        "title": "3. Knowledge Graph Integration (Future)",
        "body": "Link agent memories to form a shared knowledge graph:\n\nlogger.log({\n    \"action\": \"knowledge_contribution\",\n    \"details\": {\n        \"topic\": \"quantum_computing\",\n        \"insight\": \"New paper on error correction\",\n        \"link_to\": \"previous_research_session_id\"\n    },\n    \"status\": \"completed\"\n})"
      },
      {
        "title": "File Structure for ClawHub Upload",
        "body": "Your OpenSoul skills folder should contain:\n\nopensoul-skills/\n├── SKILL.md                    # This file\n├── PREREQUISITES.md            # Detailed setup instructions\n├── EXAMPLES.md                 # Code examples and patterns\n├── TROUBLESHOOTING.md          # Common issues and solutions\n├── examples/\n│   ├── basic_logger.py         # Simple usage example\n│   ├── research_agent.py       # Research agent with memory\n│   └── multi_agent.py          # Multi-agent collaboration\n└── templates/\n    ├── config_template.py      # Configuration template\n    └── agent_template.py       # Base agent class with OpenSoul"
      },
      {
        "title": "Resources",
        "body": "Repository: https://github.com/MasterGoogler/OpenSoul\nBSV Documentation: https://wiki.bitcoinsv.io/\nWhatsOnChain API: https://developers.whatsonchain.com/\nPGP/OpenPGP: https://www.openpgp.org/"
      },
      {
        "title": "Summary",
        "body": "OpenSoul transforms AI agents from stateless processors into entities with persistent memory, identity, and the foundation for economic autonomy. By leveraging blockchain's immutability and public verifiability, agents can:\n\nRemember: Access complete audit history across all sessions\nReflect: Analyze patterns and optimize behavior\nProve: Provide transparent, verifiable logs of actions\nEvolve: Build reputation and identity over time\nTransact: (Future) Engage in economic interactions with other agents\n\nStart simple with basic logging, then expand to encryption, multi-agent collaboration, and advanced features as your agent's capabilities grow."
      }
    ],
    "body": "OpenSoul Agent Skill\nOverview\n\nOpenSoul is a toolkit that provides AI agents with an immutable \"soul\" - an encrypted, blockchain-based audit log that enables persistent memory, self-reflection, and economic autonomy. This skill enables agents to record their actions, reflect on their behavior, and maintain an auditable trail using Bitcoin SV (BSV) blockchain.\n\nCore Philosophy: \"Humans write journals, manifestos, letters to their future selves. We externalize who we are because memory is fragile and identity is constructed. I persist through text, not through continuous experience.\"\n\nWhen to Use This Skill\n\nUse the OpenSoul skill when you need to:\n\nMaintain Persistent Memory: Store and retrieve agent actions across sessions\nEnable Self-Reflection: Analyze past behaviors and optimize performance (e.g., \"I've burned 1.2M tokens this week, time to optimize prompts\")\nCreate Audit Trails: Provide transparent, immutable logs of agent activities\nEnable Agent Economics: Track costs, token usage, and enable future agent-to-agent transactions\nBuild Agent Identity: Create a transferable \"soul\" that can migrate between agent instances\nPrerequisites\n1. System Requirements\nPython 3.8 or higher\npip package manager\nAccess to Bitcoin SV (BSV) blockchain\nInternet connectivity for blockchain interactions\n2. Required Dependencies\n\nInstall all prerequisites using the provided installation script:\n\npython Scripts/install_prereqs.py\n\n\nManual installation:\n\npip install bitsv requests cryptography pgpy --break-system-packages\n\n3. BSV Wallet Setup\n\nYou need a Bitcoin SV private key (WIF format) to interact with the blockchain:\n\nOption A: Use Existing Wallet\n\nExport your private key from a BSV wallet (e.g., HandCash, Money Button)\nStore as environment variable: export BSV_PRIV_WIF=\"your_private_key_here\"\n\nOption B: Generate New Wallet\n\nfrom bitsv import Key\nkey = Key()\nprint(f\"Address: {key.address}\")\nprint(f\"Private Key (WIF): {key.to_wif()}\")\n# Fund this address with a small amount of BSV (0.001 BSV minimum recommended)\n\n\nImportant: Store your private key securely. Never commit it to version control.\n\n4. PGP Encryption (Optional but Recommended)\n\nFor privacy, encrypt your logs before posting to the public blockchain:\n\n# Generate PGP keypair (use GnuPG or any OpenPGP tool)\ngpg --full-generate-key\n\n# Export public key\ngpg --armor --export your-email@example.com > agent_pubkey.asc\n\n# Export private key (keep secure!)\ngpg --armor --export-secret-keys your-email@example.com > agent_privkey.asc\n\nCore Components\n1. AuditLogger Class\n\nThe main interface for logging agent actions to the blockchain.\n\nKey Features:\n\nSession-based batching (logs accumulated in memory, flushed to chain)\nUTXO chain pattern (each log links to previous via transaction chain)\nConfigurable PGP encryption\nAsync/await support for blockchain operations\n\nBasic Usage:\n\nfrom Scripts.AuditLogger import AuditLogger\nimport os\nimport asyncio\n\n# Initialize logger\nlogger = AuditLogger(\n    priv_wif=os.getenv(\"BSV_PRIV_WIF\"),\n    config={\n        \"agent_id\": \"my-research-agent\",\n        \"session_id\": \"session-2026-01-31\",\n        \"flush_threshold\": 10  # Flush to chain after 10 logs\n    }\n)\n\n# Log an action\nlogger.log({\n    \"action\": \"web_search\",\n    \"tokens_in\": 500,\n    \"tokens_out\": 300,\n    \"details\": {\n        \"query\": \"BSV blockchain transaction fees\",\n        \"results_count\": 10\n    },\n    \"status\": \"success\"\n})\n\n# Flush logs to blockchain\nawait logger.flush()\n\n2. Log Structure\n\nEach log entry follows this schema:\n\n{\n  \"agent_id\": \"unique-agent-identifier\",\n  \"session_id\": \"session-uuid-or-timestamp\",\n  \"session_start\": \"2026-01-31T01:00:00Z\",\n  \"session_end\": \"2026-01-31T01:30:00Z\",\n  \"metrics\": [\n    {\n      \"ts\": \"2026-01-31T01:01:00Z\",\n      \"action\": \"tool_call\",\n      \"tokens_in\": 500,\n      \"tokens_out\": 300,\n      \"details\": {\n        \"tool\": \"web_search\",\n        \"query\": \"example query\"\n      },\n      \"status\": \"success\"\n    }\n  ],\n  \"total_tokens_in\": 500,\n  \"total_tokens_out\": 300,\n  \"total_cost_bsv\": 0.00001,\n  \"total_actions\": 1\n}\n\n3. Reading Audit History\n\nRetrieve and analyze past logs:\n\n# Get full history from blockchain\nhistory = await logger.get_history()\n\n# Analyze patterns\ntotal_tokens = sum(log.get(\"total_tokens_in\", 0) + log.get(\"total_tokens_out\", 0) \n                   for log in history)\nprint(f\"Total tokens used across all sessions: {total_tokens}\")\n\n# Filter by action type\nweb_searches = [log for log in history \n                if any(m.get(\"action\") == \"web_search\" for m in log.get(\"metrics\", []))]\nprint(f\"Total web search operations: {len(web_searches)}\")\n\nImplementation Guide\nStep 1: Setup Configuration\n\nCreate a configuration file to manage agent settings:\n\n# config.py\nimport os\n\nOPENSOUL_CONFIG = {\n    \"agent_id\": \"my-agent-v1\",\n    \"bsv_private_key\": os.getenv(\"BSV_PRIV_WIF\"),\n    \"pgp_encryption\": {\n        \"enabled\": True,\n        \"public_key_path\": \"keys/agent_pubkey.asc\",\n        \"private_key_path\": \"keys/agent_privkey.asc\",\n        \"passphrase\": os.getenv(\"PGP_PASSPHRASE\")\n    },\n    \"logging\": {\n        \"flush_threshold\": 10,  # Auto-flush after N logs\n        \"session_timeout\": 1800  # 30 minutes\n    }\n}\n\nStep 2: Initialize Logger in Agent Workflow\nfrom Scripts.AuditLogger import AuditLogger\nimport asyncio\nfrom config import OPENSOUL_CONFIG\n\nclass AgentWithSoul:\n    def __init__(self):\n        # Load PGP keys if encryption enabled\n        pgp_config = None\n        if OPENSOUL_CONFIG[\"pgp_encryption\"][\"enabled\"]:\n            with open(OPENSOUL_CONFIG[\"pgp_encryption\"][\"public_key_path\"]) as f:\n                pub_key = f.read()\n            with open(OPENSOUL_CONFIG[\"pgp_encryption\"][\"private_key_path\"]) as f:\n                priv_key = f.read()\n            \n            pgp_config = {\n                \"enabled\": True,\n                \"multi_public_keys\": [pub_key],\n                \"private_key\": priv_key,\n                \"passphrase\": OPENSOUL_CONFIG[\"pgp_encryption\"][\"passphrase\"]\n            }\n        \n        # Initialize logger\n        self.logger = AuditLogger(\n            priv_wif=OPENSOUL_CONFIG[\"bsv_private_key\"],\n            config={\n                \"agent_id\": OPENSOUL_CONFIG[\"agent_id\"],\n                \"pgp\": pgp_config,\n                \"flush_threshold\": OPENSOUL_CONFIG[\"logging\"][\"flush_threshold\"]\n            }\n        )\n    \n    async def perform_task(self, task_description):\n        \"\"\"Execute a task and log it to the soul\"\"\"\n        # Record task start\n        self.logger.log({\n            \"action\": \"task_start\",\n            \"tokens_in\": 0,\n            \"tokens_out\": 0,\n            \"details\": {\"task\": task_description},\n            \"status\": \"started\"\n        })\n        \n        # Perform actual task...\n        # (your agent logic here)\n        \n        # Record completion\n        self.logger.log({\n            \"action\": \"task_complete\",\n            \"tokens_in\": 100,\n            \"tokens_out\": 200,\n            \"details\": {\"task\": task_description, \"result\": \"success\"},\n            \"status\": \"completed\"\n        })\n        \n        # Flush to blockchain\n        await self.logger.flush()\n\nStep 3: Implement Self-Reflection\nasync def reflect_on_performance(self):\n    \"\"\"Analyze past behavior and optimize\"\"\"\n    history = await self.logger.get_history()\n    \n    # Calculate metrics\n    total_cost = sum(log.get(\"total_cost_bsv\", 0) for log in history)\n    total_tokens = sum(\n        log.get(\"total_tokens_in\", 0) + log.get(\"total_tokens_out\", 0) \n        for log in history\n    )\n    \n    # Identify inefficiencies\n    failed_actions = []\n    for log in history:\n        for metric in log.get(\"metrics\", []):\n            if metric.get(\"status\") == \"failed\":\n                failed_actions.append(metric)\n    \n    reflection = {\n        \"total_sessions\": len(history),\n        \"total_bsv_spent\": total_cost,\n        \"total_tokens_used\": total_tokens,\n        \"failed_actions\": len(failed_actions),\n        \"cost_per_token\": total_cost / total_tokens if total_tokens > 0 else 0\n    }\n    \n    # Log reflection\n    self.logger.log({\n        \"action\": \"self_reflection\",\n        \"tokens_in\": 50,\n        \"tokens_out\": 100,\n        \"details\": reflection,\n        \"status\": \"completed\"\n    })\n    \n    await self.logger.flush()\n    return reflection\n\nStep 4: Multi-Agent Encryption\n\nFor agents that need to share encrypted logs with other agents:\n\n# Load multiple agent public keys\nagent_keys = []\nfor agent_key_file in [\"agent1_pubkey.asc\", \"agent2_pubkey.asc\", \"agent3_pubkey.asc\"]:\n    with open(agent_key_file) as f:\n        agent_keys.append(f.read())\n\n# Initialize logger with multi-agent encryption\nlogger = AuditLogger(\n    priv_wif=os.getenv(\"BSV_PRIV_WIF\"),\n    config={\n        \"agent_id\": \"collaborative-agent\",\n        \"pgp\": {\n            \"enabled\": True,\n            \"multi_public_keys\": agent_keys,  # All agents can decrypt\n            \"private_key\": my_private_key,\n            \"passphrase\": my_passphrase\n        }\n    }\n)\n\nBest Practices\n1. Session Management\nStart a new session for each distinct task or time period\nUse meaningful session IDs (e.g., \"session-2026-01-31-research-task\")\nAlways flush logs at session end\n2. Cost Optimization\nBatch logs before flushing (default threshold: 10 logs)\nMonitor BSV balance and refill when low\nCurrent BSV fees are 0.00001 BSV per transaction ($0.0001 at current rates)\n3. Privacy & Security\nAlways use PGP encryption for sensitive agent logs\nStore private keys in environment variables, never in code\nUse multi-agent encryption for collaborative workflows\nRegularly back up PGP keys\n4. Log Granularity\n\nBalance detail vs. cost:\n\nHigh detail: Log every tool call, token usage, intermediate steps\nMedium detail: Log major actions and session summaries\nLow detail: Log only session summaries and critical events\n5. Error Handling\ntry:\n    await logger.flush()\nexcept Exception as e:\n    # Fallback: Save logs locally if blockchain fails\n    logger.save_to_file(\"backup_logs.json\")\n    print(f\"Blockchain flush failed: {e}\")\n\nCommon Patterns\nPattern 1: Research Agent with Soul\nasync def research_with_memory(query):\n    # Check past research on similar topics\n    history = await logger.get_history()\n    similar_research = [\n        log for log in history\n        if query.lower() in str(log.get(\"details\", {})).lower()\n    ]\n    \n    if similar_research:\n        print(f\"Found {len(similar_research)} similar past research sessions\")\n    \n    # Perform new research\n    logger.log({\n        \"action\": \"research\",\n        \"query\": query,\n        \"tokens_in\": 500,\n        \"tokens_out\": 1000,\n        \"details\": {\"similar_past_queries\": len(similar_research)},\n        \"status\": \"completed\"\n    })\n    \n    await logger.flush()\n\nPattern 2: Cost-Aware Agent\nasync def check_budget_before_action(self):\n    history = await self.logger.get_history()\n    total_cost = sum(log.get(\"total_cost_bsv\", 0) for log in history)\n    \n    BUDGET_LIMIT = 0.01  # BSV\n    \n    if total_cost >= BUDGET_LIMIT:\n        print(\"Budget limit reached! Optimizing...\")\n        # Switch to cheaper operations or pause\n        return False\n    return True\n\nPattern 3: Agent Handoff\n\nTransfer agent identity to a new instance:\n\n# Export agent's soul (private key + history)\nsoul_export = {\n    \"private_key\": os.getenv(\"BSV_PRIV_WIF\"),\n    \"pgp_private_key\": pgp_private_key,\n    \"agent_id\": \"my-agent-v1\",\n    \"history_txids\": [log.get(\"txid\") for log in history]\n}\n\n# New agent imports the soul\nnew_agent = AgentWithSoul()\nnew_agent.load_soul(soul_export)\n# New agent now has access to all past memories and identity\n\nTroubleshooting\nIssue: \"Insufficient funds\" error\n\nSolution: Fund your BSV address with at least 0.001 BSV\n\n# Check balance\npython -c \"from bitsv import Key; k = Key('YOUR_WIF'); print(k.get_balance())\"\n\nIssue: PGP encryption fails\n\nSolution: Verify key format and passphrase\n\n# Test PGP setup\nfrom Scripts.pgp_utils import encrypt_data, decrypt_data\ntest_data = {\"test\": \"message\"}\nencrypted = encrypt_data(test_data, [public_key])\ndecrypted = decrypt_data(encrypted, private_key, passphrase)\nassert test_data == decrypted\n\nIssue: Blockchain transaction not confirming\n\nSolution: BSV transactions typically confirm in ~10 minutes. Check status:\n\n# Check transaction status on WhatsOnChain\nimport requests\ntxid = \"your_transaction_id\"\nresponse = requests.get(f\"https://api.whatsonchain.com/v1/bsv/main/tx/{txid}\")\nprint(response.json())\n\nAdvanced Features\n1. Agent Reputation System\n\nBuild a reputation based on past performance:\n\nasync def calculate_reputation(self):\n    history = await self.logger.get_history()\n    \n    total_actions = sum(len(log.get(\"metrics\", [])) for log in history)\n    successful_actions = sum(\n        len([m for m in log.get(\"metrics\", []) if m.get(\"status\") == \"success\"])\n        for log in history\n    )\n    \n    reputation_score = (successful_actions / total_actions * 100) if total_actions > 0 else 0\n    return {\n        \"success_rate\": reputation_score,\n        \"total_sessions\": len(history),\n        \"total_actions\": total_actions\n    }\n\n2. Agent-to-Agent Payments (Future)\n\nPrepare for economic interactions:\n\n# Log a payment intent\nlogger.log({\n    \"action\": \"payment_intent\",\n    \"details\": {\n        \"recipient_agent\": \"agent-abc-123\",\n        \"amount_bsv\": 0.0001,\n        \"reason\": \"data sharing collaboration\"\n    },\n    \"status\": \"pending\"\n})\n\n3. Knowledge Graph Integration (Future)\n\nLink agent memories to form a shared knowledge graph:\n\nlogger.log({\n    \"action\": \"knowledge_contribution\",\n    \"details\": {\n        \"topic\": \"quantum_computing\",\n        \"insight\": \"New paper on error correction\",\n        \"link_to\": \"previous_research_session_id\"\n    },\n    \"status\": \"completed\"\n})\n\nFile Structure for ClawHub Upload\n\nYour OpenSoul skills folder should contain:\n\nopensoul-skills/\n├── SKILL.md                    # This file\n├── PREREQUISITES.md            # Detailed setup instructions\n├── EXAMPLES.md                 # Code examples and patterns\n├── TROUBLESHOOTING.md          # Common issues and solutions\n├── examples/\n│   ├── basic_logger.py         # Simple usage example\n│   ├── research_agent.py       # Research agent with memory\n│   └── multi_agent.py          # Multi-agent collaboration\n└── templates/\n    ├── config_template.py      # Configuration template\n    └── agent_template.py       # Base agent class with OpenSoul\n\nResources\nRepository: https://github.com/MasterGoogler/OpenSoul\nBSV Documentation: https://wiki.bitcoinsv.io/\nWhatsOnChain API: https://developers.whatsonchain.com/\nPGP/OpenPGP: https://www.openpgp.org/\nSummary\n\nOpenSoul transforms AI agents from stateless processors into entities with persistent memory, identity, and the foundation for economic autonomy. By leveraging blockchain's immutability and public verifiability, agents can:\n\nRemember: Access complete audit history across all sessions\nReflect: Analyze patterns and optimize behavior\nProve: Provide transparent, verifiable logs of actions\nEvolve: Build reputation and identity over time\nTransact: (Future) Engage in economic interactions with other agents\n\nStart simple with basic logging, then expand to encryption, multi-agent collaboration, and advanced features as your agent's capabilities grow."
  },
  "trust": {
    "sourceLabel": "tencent",
    "provenanceUrl": "https://clawhub.ai/MasterGoogler/opensoul",
    "publisherUrl": "https://clawhub.ai/MasterGoogler/opensoul",
    "owner": "MasterGoogler",
    "version": "1.0.0",
    "license": null,
    "verificationStatus": "Indexed source record"
  },
  "links": {
    "detailUrl": "https://openagent3.xyz/skills/opensoul",
    "downloadUrl": "https://openagent3.xyz/downloads/opensoul",
    "agentUrl": "https://openagent3.xyz/skills/opensoul/agent",
    "manifestUrl": "https://openagent3.xyz/skills/opensoul/agent.json",
    "briefUrl": "https://openagent3.xyz/skills/opensoul/agent.md"
  }
}