Delegate Click commands to click_cli and add agent subcommands
Some checks failed
CLI Tests / test-cli (push) Failing after 11s
Cross-Node Transaction Testing / transaction-test (push) Successful in 2s
Deploy to Testnet / deploy-testnet (push) Successful in 1m9s
Documentation Validation / validate-docs (push) Failing after 10s
Documentation Validation / validate-policies-strict (push) Successful in 4s
Integration Tests / test-service-integration (push) Successful in 2m38s
Multi-Node Stress Testing / stress-test (push) Successful in 2s
Node Failover Simulation / failover-test (push) Successful in 2s
Package Tests / Python package - aitbc-agent-sdk (push) Failing after 27s
Security Scanning / security-scan (push) Has been cancelled
Package Tests / Python package - aitbc-core (push) Successful in 13s
Package Tests / Python package - aitbc-crypto (push) Successful in 9s
Package Tests / Python package - aitbc-sdk (push) Successful in 11s
Package Tests / JavaScript package - aitbc-sdk-js (push) Successful in 8s
Package Tests / JavaScript package - aitbc-token (push) Successful in 27s
Python Tests / test-python (push) Failing after 1m25s

- Route Click commands (agent, ipfs, oracle, etc.) to click_cli module
- Add zk, knowledge, bounty, dispute subcommands to agent group
- Add AI test submission, power trading, and reputation commands
- Add cross-chain transfer and listing commands
- Add monitor start/stop/status/alerts commands
- Add swarm create/discover/add/distribute/status commands
- Update main() to check command type and delegate appropriately
- Fix genesis CLI
This commit is contained in:
aitbc
2026-05-08 10:43:53 +02:00
parent 1dd58261b4
commit 149fbb0abe
27 changed files with 2753 additions and 50 deletions

View File

@@ -23,6 +23,7 @@ from aitbc_agent.contract_integration import (
ContractConfig,
create_agent_contract_integration
)
from aitbc_agent import command_executor, ipfs, data_oracle, zk, knowledge, bounty, dispute, extended
logger = get_logger(__name__)
@@ -117,6 +118,15 @@ class Agent:
# Contract integration
self.contract_integration: Optional[AgentContractIntegration] = None
# CLI-based operation modules
self.ipfs_ops = ipfs.IPFSOperations()
self.data_oracle_ops = data_oracle.DataOracleOperations()
self.zk_ops = zk.ZKOperations()
self.knowledge_ops = knowledge.KnowledgeOperations()
self.bounty_ops = bounty.BountyOperations()
self.dispute_ops = dispute.DisputeOperations()
self.extended_ops = extended.ExtendedOperations()
if contract_config:
try:
# Use factory function to create appropriate client
@@ -487,6 +497,93 @@ class Agent:
contract_address=contract_address
)
# IPFS operations
def store_ipfs(self, data: bytes, pin: bool = True, name: str = None) -> str:
"""Store data on IPFS"""
return self.ipfs_ops.store_ipfs(data, pin, name)
def retrieve_ipfs(self, cid: str, output_path: str = None) -> bytes:
"""Retrieve data from IPFS"""
return self.ipfs_ops.retrieve_ipfs(cid, output_path)
async def store_ipfs_async(self, data: bytes, pin: bool = True, name: str = None) -> str:
"""Async version of store_ipfs"""
return await self.ipfs_ops.store_ipfs_async(data, pin, name)
async def retrieve_ipfs_async(self, cid: str, output_path: str = None) -> bytes:
"""Async version of retrieve_ipfs"""
return await self.ipfs_ops.retrieve_ipfs_async(cid, output_path)
# Data oracle operations
def announce_data_availability(self, cid: str, price: float, description: str = "") -> str:
"""Announce data availability"""
return self.data_oracle_ops.announce_data_availability(cid, price, description)
def retrieve_data(self, cid: str) -> bytes:
"""Retrieve data by CID"""
return self.data_oracle_ops.retrieve_data(cid)
async def listen_for_requests(self, callback):
"""Listen for data retrieval requests"""
await self.data_oracle_ops.listen_for_requests(callback)
async def announce_data_availability_async(self, cid: str, price: float, description: str = "") -> str:
"""Async version of announce_data_availability"""
return await self.data_oracle_ops.announce_data_availability_async(cid, price, description)
# ZK operations
def generate_proof(self, input_data: str, circuit_id: str) -> str:
"""Generate ZK proof"""
return self.zk_ops.generate_proof(input_data, circuit_id)
def verify_proof(self, proof: str, public_inputs: str) -> bool:
"""Verify ZK proof"""
return self.zk_ops.verify_proof(proof, public_inputs)
# Knowledge graph operations
def create_knowledge_graph(self, name: str, description: str = "") -> str:
"""Create knowledge graph"""
return self.knowledge_ops.create_knowledge_graph(name, description)
def add_knowledge_node(self, graph_id: str, node_data: dict) -> str:
"""Add node to knowledge graph"""
return self.knowledge_ops.add_knowledge_node(graph_id, node_data)
# Bounty operations
def create_bounty(self, title: str, description: str, reward: float) -> str:
"""Create bounty"""
return self.bounty_ops.create_bounty(title, description, reward)
def list_bounties(self, status: str = "open") -> list:
"""List bounties"""
return self.bounty_ops.list_bounties(status)
# Dispute operations
def file_dispute(self, title: str, description: str, evidence: str) -> str:
"""File dispute"""
return self.dispute_ops.file_dispute(title, description, evidence)
def vote_dispute(self, dispute_id: str, vote: bool, reason: str = "") -> bool:
"""Vote on dispute"""
return self.dispute_ops.vote_dispute(dispute_id, vote, reason)
# Extended operations
def submit_ai_test(self, model_id: str, test_data: str) -> str:
"""Submit AI test job"""
return self.extended_ops.submit_ai_test(model_id, test_data)
def list_gpu(self, filters: dict = None) -> list:
"""List available GPU resources"""
return self.extended_ops.list_gpu(filters)
def create_swarm(self, name: str, max_agents: int) -> str:
"""Create agent swarm"""
return self.extended_ops.create_swarm(name, max_agents)
def add_stake(self, amount: float, validator_id: str = None) -> str:
"""Add stake to validator"""
return self.extended_ops.add_stake(amount, validator_id)
class AITBCAgent:
"""High-level convenience wrapper for creating AITBC agents.

View File

@@ -0,0 +1,70 @@
"""Bounty operations using CLI commands"""
from typing import List
from .command_executor import CommandExecutor
from aitbc.aitbc_logging import get_logger
logger = get_logger(__name__)
class BountyOperations:
"""Bounty operations via CLI"""
def __init__(self, cli_path: str = "/opt/aitbc/aitbc-click"):
self.executor = CommandExecutor(cli_path)
def create_bounty(self, title: str, description: str, reward: float) -> str:
"""Create bounty"""
try:
args = ["create", "--title", title, "--description", description, "--reward", str(reward)]
result = self.executor.execute_command("agent bounty", args)
if result["success"]:
return result["data"].get("bounty_id", "")
else:
logger.error(f"Bounty create failed: {result.get('error')}")
raise Exception(result.get("error"))
except Exception as e:
logger.error(f"create_bounty failed: {e}")
raise
def list_bounties(self, status: str = "open") -> List[dict]:
"""List bounties"""
try:
args = ["list", "--status", status]
result = self.executor.execute_command("agent bounty", args)
if result["success"]:
return result["data"].get("bounties", [])
else:
logger.error(f"Bounty list failed: {result.get('error')}")
raise Exception(result.get("error"))
except Exception as e:
logger.error(f"list_bounties failed: {e}")
raise
def submit_bounty_solution(self, bounty_id: str, solution: str) -> str:
"""Submit bounty solution"""
try:
args = ["submit", "--bounty-id", bounty_id, "--solution", solution]
result = self.executor.execute_command("agent bounty", args)
if result["success"]:
return result["data"].get("submission_id", "")
else:
logger.error(f"Bounty submit failed: {result.get('error')}")
raise Exception(result.get("error"))
except Exception as e:
logger.error(f"submit_bounty_solution failed: {e}")
raise
def claim_bounty(self, bounty_id: str) -> bool:
"""Claim bounty reward"""
try:
args = ["claim", "--bounty-id", bounty_id]
result = self.executor.execute_command("agent bounty", args)
if result["success"]:
return result["data"].get("claimed", False)
else:
logger.error(f"Bounty claim failed: {result.get('error')}")
raise Exception(result.get("error"))
except Exception as e:
logger.error(f"claim_bounty failed: {e}")
raise

View File

@@ -0,0 +1,64 @@
"""Command executor for CLI subprocess calls"""
import subprocess
import asyncio
import json
from typing import Optional, Dict, Any, List
from aitbc.aitbc_logging import get_logger
logger = get_logger(__name__)
class CommandExecutor:
"""Execute CLI commands via subprocess"""
def __init__(self, cli_path: str = "/opt/aitbc/aitbc-cli"):
"""
Initialize command executor
Args:
cli_path: Path to CLI executable (default: /opt/aitbc/aitbc-cli)
"""
self.cli_path = cli_path
def execute_command(self, command: str, args: List[str]) -> Dict[str, Any]:
"""Execute CLI command and return result"""
try:
cmd = [self.cli_path] + command.split() + args
logger.debug(f"Executing command: {' '.join(cmd)}")
result = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=30
)
if result.returncode == 0:
try:
data = json.loads(result.stdout) if result.stdout else {}
except json.JSONDecodeError:
data = {"output": result.stdout}
return {
"success": True,
"output": result.stdout,
"data": data
}
else:
logger.error(f"Command failed: {result.stderr}")
return {
"success": False,
"error": result.stderr
}
except subprocess.TimeoutExpired:
logger.error("Command timeout")
return {"success": False, "error": "Command timeout"}
except Exception as e:
logger.error(f"Command execution failed: {e}")
return {"success": False, "error": str(e)}
async def execute_command_async(self, command: str, args: List[str]) -> Dict[str, Any]:
"""Execute CLI command asynchronously"""
loop = asyncio.get_event_loop()
return await loop.run_in_executor(None, self.execute_command, command, args)

View File

@@ -0,0 +1,73 @@
"""Data oracle operations using CLI commands"""
import asyncio
from typing import Optional, Callable
from .command_executor import CommandExecutor
from aitbc.aitbc_logging import get_logger
logger = get_logger(__name__)
class DataOracleOperations:
"""Data oracle operations via CLI"""
def __init__(self, cli_path: str = "/opt/aitbc/aitbc-click"):
self.executor = CommandExecutor(cli_path)
def announce_data_availability(self, cid: str, price: float, description: str = "") -> str:
"""Announce data availability"""
try:
args = ["store", "--cid", cid, "--price", str(price)]
if description:
args.extend(["--description", description])
result = self.executor.execute_command("oracle", args)
if result["success"]:
return result["data"].get("announcement_id", cid)
else:
logger.error(f"Data oracle announce failed: {result.get('error')}")
raise Exception(result.get("error"))
except Exception as e:
logger.error(f"announce_data_availability failed: {e}")
raise
def retrieve_data(self, cid: str) -> bytes:
"""Retrieve data by CID"""
try:
# For now, use IPFS retrieve
from .ipfs import IPFSOperations
ipfs = IPFSOperations(self.executor.cli_path)
return ipfs.retrieve_ipfs(cid)
except Exception as e:
logger.error(f"retrieve_data failed: {e}")
raise
async def listen_for_requests(self, callback: Callable):
"""Listen for data retrieval requests (async)"""
# This would need to implement a polling mechanism or webhook
# For now, use a polling approach checking oracle listings
try:
while True:
result = await self.executor.execute_command_async("oracle", ["listings"])
if result["success"]:
# Process listings and call callback
listings = result["data"].get("listings", [])
for listing in listings:
await callback(listing)
await asyncio.sleep(10)
except Exception as e:
logger.error(f"listen_for_requests failed: {e}")
raise
async def announce_data_availability_async(self, cid: str, price: float, description: str = "") -> str:
"""Async version of announce_data_availability"""
args = ["store", "--cid", cid, "--price", str(price)]
if description:
args.extend(["--description", description])
result = await self.executor.execute_command_async("oracle", args)
if result["success"]:
return result["data"].get("announcement_id", cid)
else:
logger.error(f"Data oracle announce async failed: {result.get('error')}")
raise Exception(result.get("error"))

View File

@@ -0,0 +1,71 @@
"""Dispute operations using CLI commands"""
from .command_executor import CommandExecutor
from aitbc.aitbc_logging import get_logger
logger = get_logger(__name__)
class DisputeOperations:
"""Dispute operations via CLI"""
def __init__(self, cli_path: str = "/opt/aitbc/aitbc-click"):
self.executor = CommandExecutor(cli_path)
def file_dispute(self, title: str, description: str, evidence: str) -> str:
"""File dispute"""
try:
args = ["file", "--title", title, "--description", description, "--evidence", evidence]
result = self.executor.execute_command("agent dispute", args)
if result["success"]:
return result["data"].get("dispute_id", "")
else:
logger.error(f"Dispute file failed: {result.get('error')}")
raise Exception(result.get("error"))
except Exception as e:
logger.error(f"file_dispute failed: {e}")
raise
def register_arbitrator(self, arbitrator_id: str) -> bool:
"""Register as arbitrator"""
try:
args = ["register-arbitrator", "--arbitrator-id", arbitrator_id]
result = self.executor.execute_command("agent dispute", args)
if result["success"]:
return result["data"].get("registered", False)
else:
logger.error(f"Dispute register-arbitrator failed: {result.get('error')}")
raise Exception(result.get("error"))
except Exception as e:
logger.error(f"register_arbitrator failed: {e}")
raise
def submit_dispute_evidence(self, dispute_id: str, evidence: str) -> bool:
"""Submit dispute evidence"""
try:
args = ["evidence", "--dispute-id", dispute_id, "--evidence", evidence]
result = self.executor.execute_command("agent dispute", args)
if result["success"]:
return result["data"].get("submitted", False)
else:
logger.error(f"Dispute evidence failed: {result.get('error')}")
raise Exception(result.get("error"))
except Exception as e:
logger.error(f"submit_dispute_evidence failed: {e}")
raise
def vote_dispute(self, dispute_id: str, vote: bool, reason: str = "") -> bool:
"""Vote on dispute"""
try:
args = ["vote", "--dispute-id", dispute_id, "--vote", "true" if vote else "false"]
if reason:
args.extend(["--reason", reason])
result = self.executor.execute_command("agent dispute", args)
if result["success"]:
return result["data"].get("accepted", False)
else:
logger.error(f"Dispute vote failed: {result.get('error')}")
raise Exception(result.get("error"))
except Exception as e:
logger.error(f"vote_dispute failed: {e}")
raise

View File

@@ -0,0 +1,161 @@
"""Extended Agent SDK operations using CLI commands"""
from typing import Dict, List, Optional
from .command_executor import CommandExecutor
from aitbc.aitbc_logging import get_logger
logger = get_logger(__name__)
class ExtendedOperations:
"""Extended operations via CLI commands"""
def __init__(self, cli_path: str = "/opt/aitbc/aitbc-click"):
self.executor = CommandExecutor(cli_path)
def submit_ai_test(self, model_id: str, test_data: str) -> str:
"""Submit AI test job"""
try:
args = ["submit", "--model", model_id, "--test-data", test_data]
result = self.executor.execute_command("ai", args)
if result["success"]:
return result["data"].get("job_id", "")
else:
logger.error(f"AI submit failed: {result.get('error')}")
raise Exception(result.get("error"))
except Exception as e:
logger.error(f"submit_ai_test failed: {e}")
raise
def list_gpu(self, filters: Dict = None) -> List[dict]:
"""List available GPU resources"""
try:
args = ["list"]
if filters:
for key, value in filters.items():
args.extend([f"--{key}", str(value)])
result = self.executor.execute_command("market gpu", args)
if result["success"]:
return result["data"].get("listings", [])
else:
logger.error(f"GPU list failed: {result.get('error')}")
raise Exception(result.get("error"))
except Exception as e:
logger.error(f"list_gpu failed: {e}")
raise
def create_swarm(self, name: str, max_agents: int) -> str:
"""Create agent swarm"""
try:
args = ["create", "--name", name, "--max-agents", str(max_agents)]
result = self.executor.execute_command("swarm", args)
if result["success"]:
return result["data"].get("swarm_id", "")
else:
logger.error(f"Swarm create failed: {result.get('error')}")
raise Exception(result.get("error"))
except Exception as e:
logger.error(f"create_swarm failed: {e}")
raise
def add_stake(self, amount: float, validator_id: Optional[str] = None) -> str:
"""Add stake to validator"""
try:
args = ["manage", "--action", "add-stake", "--amount", str(amount)]
if validator_id:
args.extend(["--validator-id", validator_id])
result = self.executor.execute_command("staking", args)
if result["success"]:
return result["data"].get("stake_id", "")
else:
logger.error(f"Staking add failed: {result.get('error')}")
raise Exception(result.get("error"))
except Exception as e:
logger.error(f"add_stake failed: {e}")
raise
def create_island_bridge(self, name: str, source_chain: str, target_chain: str) -> str:
"""Create island bridge"""
try:
args = ["create", "--name", name, "--source", source_chain, "--target", target_chain]
result = self.executor.execute_command("island", ["bridge"] + args)
if result["success"]:
return result["data"].get("bridge_id", "")
else:
logger.error(f"Island bridge create failed: {result.get('error')}")
raise Exception(result.get("error"))
except Exception as e:
logger.error(f"create_island_bridge failed: {e}")
raise
def execute_bridge_transfer(self, bridge_id: str, amount: float, token: str) -> str:
"""Execute bridge transfer"""
try:
args = ["transfer", "--bridge-id", bridge_id, "--amount", str(amount), "--token", token]
result = self.executor.execute_command("island", ["bridge"] + args)
if result["success"]:
return result["data"].get("transfer_id", "")
else:
logger.error(f"Bridge transfer failed: {result.get('error')}")
raise Exception(result.get("error"))
except Exception as e:
logger.error(f"execute_bridge_transfer failed: {e}")
raise
def create_database(self, name: str, schema: str = "") -> str:
"""Create database"""
try:
args = ["init", "--name", name]
if schema:
args.extend(["--schema", schema])
result = self.executor.execute_command("database", args)
if result["success"]:
return result["data"].get("database_id", "")
else:
logger.error(f"Database create failed: {result.get('error')}")
raise Exception(result.get("error"))
except Exception as e:
logger.error(f"create_database failed: {e}")
raise
def query_database(self, database_id: str, query: str) -> List[dict]:
"""Query database"""
try:
args = ["query", "--database-id", database_id, "--query", query]
result = self.executor.execute_command("database", args)
if result["success"]:
return result["data"].get("results", [])
else:
logger.error(f"Database query failed: {result.get('error')}")
raise Exception(result.get("error"))
except Exception as e:
logger.error(f"query_database failed: {e}")
raise
def submit_training_job(self, model_id: str, dataset: str) -> str:
"""Submit training job"""
try:
args = ["submit", "--model", model_id, "--dataset", dataset]
result = self.executor.execute_command("ai", ["training"] + args)
if result["success"]:
return result["data"].get("job_id", "")
else:
logger.error(f"Training submit failed: {result.get('error')}")
raise Exception(result.get("error"))
except Exception as e:
logger.error(f"submit_training_job failed: {e}")
raise
def query_analytics(self, metrics: List[str], time_range: str = "24h") -> Dict:
"""Query analytics"""
try:
args = ["query", "--metrics", ",".join(metrics), "--time-range", time_range]
result = self.executor.execute_command("analytics", args)
if result["success"]:
return result["data"]
else:
logger.error(f"Analytics query failed: {result.get('error')}")
raise Exception(result.get("error"))
except Exception as e:
logger.error(f"query_analytics failed: {e}")
raise

View File

@@ -0,0 +1,140 @@
"""IPFS operations using CLI commands"""
import tempfile
import os
from typing import Optional
from .command_executor import CommandExecutor
from aitbc.aitbc_logging import get_logger
logger = get_logger(__name__)
class IPFSOperations:
"""IPFS operations via CLI"""
def __init__(self, cli_path: str = "/opt/aitbc/aitbc-click"):
self.executor = CommandExecutor(cli_path)
def store_ipfs(self, data: bytes, pin: bool = True, name: Optional[str] = None) -> str:
"""Store data on IPFS"""
try:
# Write data to temp file
with tempfile.NamedTemporaryFile(delete=False, mode='wb') as f:
f.write(data)
temp_path = f.name
# Build command args
args = ["upload", "--file", temp_path]
if pin:
args.append("--pin")
if name:
args.extend(["--name", name])
# Execute command
result = self.executor.execute_command("ipfs", args)
# Clean up temp file
os.unlink(temp_path)
if result["success"]:
return result["data"].get("cid")
else:
logger.error(f"IPFS store failed: {result.get('error')}")
raise Exception(result.get("error"))
except Exception as e:
logger.error(f"store_ipfs failed: {e}")
raise
def retrieve_ipfs(self, cid: str, output_path: Optional[str] = None) -> bytes:
"""Retrieve data from IPFS"""
try:
args = ["download", cid]
if output_path:
args.extend(["--output", output_path])
result = self.executor.execute_command("ipfs", args)
if result["success"]:
# If output path specified, read from file
if output_path:
with open(output_path, 'rb') as f:
return f.read()
# Otherwise, return the file path from result
return result["data"].get("file_path", "")
else:
logger.error(f"IPFS retrieve failed: {result.get('error')}")
raise Exception(result.get("error"))
except Exception as e:
logger.error(f"retrieve_ipfs failed: {e}")
raise
def pin_ipfs(self, cid: str) -> bool:
"""Pin content on IPFS"""
try:
result = self.executor.execute_command("ipfs", ["pin", cid])
if result["success"]:
return result["data"].get("pinned", False)
else:
logger.error(f"IPFS pin failed: {result.get('error')}")
raise Exception(result.get("error"))
except Exception as e:
logger.error(f"pin_ipfs failed: {e}")
raise
def list_ipfs(self) -> list:
"""List all stored IPFS content"""
try:
result = self.executor.execute_command("ipfs", ["list"])
if result["success"]:
return result["data"].get("items", [])
else:
logger.error(f"IPFS list failed: {result.get('error')}")
raise Exception(result.get("error"))
except Exception as e:
logger.error(f"list_ipfs failed: {e}")
raise
async def store_ipfs_async(self, data: bytes, pin: bool = True, name: Optional[str] = None) -> str:
"""Async version of store_ipfs"""
# Write data to temp file
with tempfile.NamedTemporaryFile(delete=False, mode='wb') as f:
f.write(data)
temp_path = f.name
# Build command args
args = ["upload", "--file", temp_path]
if pin:
args.append("--pin")
if name:
args.extend(["--name", name])
try:
result = await self.executor.execute_command_async("ipfs", args)
os.unlink(temp_path)
if result["success"]:
return result["data"].get("cid")
else:
logger.error(f"IPFS store async failed: {result.get('error')}")
raise Exception(result.get("error"))
except Exception as e:
if os.path.exists(temp_path):
os.unlink(temp_path)
logger.error(f"store_ipfs_async failed: {e}")
raise
async def retrieve_ipfs_async(self, cid: str, output_path: Optional[str] = None) -> bytes:
"""Async version of retrieve_ipfs"""
args = ["download", cid]
if output_path:
args.extend(["--output", output_path])
result = await self.executor.execute_command_async("ipfs", args)
if result["success"]:
if output_path:
with open(output_path, 'rb') as f:
return f.read()
return result["data"].get("file_path", "")
else:
logger.error(f"IPFS retrieve async failed: {result.get('error')}")
raise Exception(result.get("error"))

View File

@@ -0,0 +1,89 @@
"""Knowledge graph operations using CLI commands"""
import json
from typing import Dict, List
from .command_executor import CommandExecutor
from aitbc.aitbc_logging import get_logger
logger = get_logger(__name__)
class KnowledgeOperations:
"""Knowledge graph operations via CLI"""
def __init__(self, cli_path: str = "/opt/aitbc/aitbc-click"):
self.executor = CommandExecutor(cli_path)
def create_knowledge_graph(self, name: str, description: str = "") -> str:
"""Create knowledge graph"""
try:
args = ["create", "--name", name]
if description:
args.extend(["--description", description])
result = self.executor.execute_command("agent knowledge", args)
if result["success"]:
return result["data"].get("graph_id", "")
else:
logger.error(f"Knowledge create failed: {result.get('error')}")
raise Exception(result.get("error"))
except Exception as e:
logger.error(f"create_knowledge_graph failed: {e}")
raise
def join_knowledge_graph(self, graph_id: str) -> bool:
"""Join knowledge graph"""
try:
args = ["join", "--graph-id", graph_id]
result = self.executor.execute_command("agent knowledge", args)
if result["success"]:
return result["data"].get("joined", False)
else:
logger.error(f"Knowledge join failed: {result.get('error')}")
raise Exception(result.get("error"))
except Exception as e:
logger.error(f"join_knowledge_graph failed: {e}")
raise
def query_knowledge_graph(self, graph_id: str, query: str) -> List[Dict]:
"""Query knowledge graph"""
try:
args = ["query", "--graph-id", graph_id, "--query", query]
result = self.executor.execute_command("agent knowledge", args)
if result["success"]:
return result["data"].get("results", [])
else:
logger.error(f"Knowledge query failed: {result.get('error')}")
raise Exception(result.get("error"))
except Exception as e:
logger.error(f"query_knowledge_graph failed: {e}")
raise
def add_knowledge_node(self, graph_id: str, node_data: Dict) -> str:
"""Add node to knowledge graph"""
try:
args = ["add-node", "--graph-id", graph_id, "--data", json.dumps(node_data)]
result = self.executor.execute_command("agent knowledge", args)
if result["success"]:
return result["data"].get("node_id", "")
else:
logger.error(f"Knowledge add-node failed: {result.get('error')}")
raise Exception(result.get("error"))
except Exception as e:
logger.error(f"add_knowledge_node failed: {e}")
raise
def add_knowledge_edge(self, graph_id: str, from_node: str, to_node: str, edge_data: Dict = None) -> str:
"""Add edge to knowledge graph"""
try:
args = ["add-edge", "--graph-id", graph_id, "--from", from_node, "--to", to_node]
if edge_data:
args.extend(["--data", json.dumps(edge_data)])
result = self.executor.execute_command("agent knowledge", args)
if result["success"]:
return result["data"].get("edge_id", "")
else:
logger.error(f"Knowledge add-edge failed: {result.get('error')}")
raise Exception(result.get("error"))
except Exception as e:
logger.error(f"add_knowledge_edge failed: {e}")
raise

View File

@@ -0,0 +1,76 @@
"""ZK operations using CLI commands"""
from typing import Dict
from .command_executor import CommandExecutor
from aitbc.aitbc_logging import get_logger
logger = get_logger(__name__)
class ZKOperations:
"""Zero-knowledge operations via CLI"""
def __init__(self, cli_path: str = "/opt/aitbc/aitbc-click"):
self.executor = CommandExecutor(cli_path)
def generate_proof(self, input_data: str, circuit_id: str) -> str:
"""Generate ZK proof"""
try:
args = ["generate-proof", "--input", input_data, "--circuit", circuit_id]
result = self.executor.execute_command("agent zk", args)
if result["success"]:
return result["data"].get("proof", "")
else:
logger.error(f"ZK generate_proof failed: {result.get('error')}")
raise Exception(result.get("error"))
except Exception as e:
logger.error(f"generate_proof failed: {e}")
raise
def verify_proof(self, proof: str, public_inputs: str) -> bool:
"""Verify ZK proof"""
try:
args = ["verify-proof", "--proof", proof, "--public-inputs", public_inputs]
result = self.executor.execute_command("agent zk", args)
if result["success"]:
return result["data"].get("valid", False)
else:
logger.error(f"ZK verify_proof failed: {result.get('error')}")
raise Exception(result.get("error"))
except Exception as e:
logger.error(f"verify_proof failed: {e}")
raise
def create_receipt(self, proof: str, metadata: Dict = None) -> str:
"""Create receipt from proof"""
try:
import json
args = ["create-receipt", "--proof", proof]
if metadata:
args.extend(["--metadata", json.dumps(metadata)])
result = self.executor.execute_command("agent zk", args)
if result["success"]:
return result["data"].get("receipt_id", "")
else:
logger.error(f"ZK create_receipt failed: {result.get('error')}")
raise Exception(result.get("error"))
except Exception as e:
logger.error(f"create_receipt failed: {e}")
raise
def submit_performance_proof(self, receipt: str, metrics: Dict = None) -> str:
"""Submit performance proof"""
try:
import json
args = ["submit-performance-proof", "--receipt", receipt]
if metrics:
args.extend(["--metrics", json.dumps(metrics)])
result = self.executor.execute_command("agent zk", args)
if result["success"]:
return result["data"].get("submission_id", "")
else:
logger.error(f"ZK submit_performance_proof failed: {result.get('error')}")
raise Exception(result.get("error"))
except Exception as e:
logger.error(f"submit_performance_proof failed: {e}")
raise