diff --git a/backend/src/api/v1/agents.py b/backend/src/api/v1/agents.py index 9cc11a86..ba587e9b 100644 --- a/backend/src/api/v1/agents.py +++ b/backend/src/api/v1/agents.py @@ -757,9 +757,18 @@ class AttestationSummary(BaseModel): rounds: int = Field(default=1, ge=1, description="Number of verified completion rounds") +class ApprovalRequest(BaseModel): + model_config = ConfigDict(extra="forbid") + summary: str = Field(max_length=2000, description="What the agent will do once approved") + action: str = Field(max_length=80, description="Approve button label") + + class ChatResponse(BaseModel): model_config = ConfigDict(extra="forbid") reply: str = Field(description="Agent's reply") + approval: ApprovalRequest | None = Field( + default=None, description="Set when the agent is waiting for the user's go-ahead" + ) attestation: AttestationSummary | None = Field( default=None, description="NEAR AI Cloud private inference attestation summary when provider=near", @@ -806,12 +815,15 @@ async def chat_with_agent( message=body.message, history=[{"role": m.role, "content": m.content} for m in body.history], owner_id=current_user.user_id, + owner_email=current_user.email, + owner_wallet=current_user.wallet_address, session_id=body.session_id if current_user.external_subject.startswith("betterauth|") else None, meta=meta, llm_provider=body.llm_provider, ) + approval = meta.pop("approval", None) attestation = AttestationSummary(**meta) if meta.get("provider") == "near" else None - return ChatResponse(reply=reply, attestation=attestation) + return ChatResponse(reply=reply, attestation=attestation, approval=approval) except PlatformException: raise diff --git a/backend/src/api/v1/chat_sessions.py b/backend/src/api/v1/chat_sessions.py index 2c25cd52..5678744f 100644 --- a/backend/src/api/v1/chat_sessions.py +++ b/backend/src/api/v1/chat_sessions.py @@ -28,6 +28,7 @@ class SessionMessageIn(BaseModel): content: str = Field(description="Message text") rich_content: dict | None = Field(default=None, description="Optional rich content payload") attestation: dict | None = Field(default=None, description="Optional private inference attestation summary") + approval: dict | None = Field(default=None, description="Optional pending approval request") class SessionAppendRequest(BaseModel): @@ -170,6 +171,8 @@ async def append_session_message( msg["richContent"] = body.message.rich_content if body.message.attestation: msg["attestation"] = body.message.attestation + if body.message.approval: + msg["approval"] = body.message.approval doc.messages.append(msg) doc.updated_at = datetime.now(timezone.utc) await doc.save() diff --git a/backend/src/mcp_server/platform_mcp.py b/backend/src/mcp_server/platform_mcp.py index 4c54dfeb..ea0eadc5 100644 --- a/backend/src/mcp_server/platform_mcp.py +++ b/backend/src/mcp_server/platform_mcp.py @@ -17,10 +17,19 @@ from __future__ import annotations +import base64 +import hashlib +import hmac +import json import logging +import os +import time +from datetime import datetime, timezone from decimal import Decimal from typing import Any +import httpx + from mcp.server.fastmcp import FastMCP from motor.motor_asyncio import AsyncIOMotorDatabase @@ -28,8 +37,47 @@ logger = logging.getLogger(__name__) - -def create_platform_mcp(db: AsyncIOMotorDatabase, owner_id: str, agent_id: str | None = None) -> FastMCP: +API = "http://localhost:8081" + + +def owner_headers(owner_id: str, email: str | None, wallet: str | None) -> dict[str, str]: + """Same signed assertion the frontend sends, so agent-made jobs belong to the chat's owner.""" + secret = os.getenv("AGENT_AUTH_BRIDGE_SECRET", "") + if len(secret) < 32 or not owner_id or not email: + return {} # auth-disabled dev mode: the API falls back to its bypass user + now = int(time.time()) + claims: dict[str, Any] = { + "sub": owner_id, + "email": email, + "iat": now, + "exp": now + 60, + "aud": "quantumnodes-agentkit", + } + if wallet: + claims["wallet"] = wallet + body = base64.urlsafe_b64encode(json.dumps(claims).encode()).decode().rstrip("=") + signature = hmac.new(secret.encode(), body.encode(), hashlib.sha256).hexdigest() + return {"Authorization": f"Bearer qn1.{body}.{signature}"} + + +# (experiment type, owner-scoped result path); probed in order to find a job by ID. +_EXPERIMENT_PATHS = ( + ("quantum-circuit", "/api/v1/jobs/{}"), + ("portfolio-optimization", "/api/v1/finance/{}?result_detail=full"), + ("drug-discovery", "/api/v1/pharma/jobs/{}"), + ("options-pricing", "/api/v1/options/{}"), + ("risk-analysis", "/api/v1/risk/{}"), +) + + +def create_platform_mcp( + db: AsyncIOMotorDatabase, + owner_id: str, + agent_id: str | None = None, + *, + owner_email: str | None = None, + owner_wallet: str | None = None, +) -> FastMCP: """ Create a FastMCP instance scoped to a specific user/owner. @@ -47,6 +95,9 @@ def create_platform_mcp(db: AsyncIOMotorDatabase, owner_id: str, agent_id: str | """ mcp = FastMCP("quantumnodes-platform") + def _api() -> httpx.AsyncClient: + return httpx.AsyncClient(headers=owner_headers(owner_id, owner_email, owner_wallet)) + # ── Proposals ──────────────────────────────────────────────────────────── @mcp.tool() @@ -285,7 +336,10 @@ async def submit_quantum_circuit(circuit: str) -> dict: creg c[2]; h q[0]; cx q[0],q[1]; - measure q -> c; + measure q[0] -> c[0]; + measure q[1] -> c[1]; + + Measure each qubit separately; the executor rejects whole-register "measure q -> c;". Args: circuit: Full OpenQASM 2.0 circuit text (minimum 10 characters) @@ -295,9 +349,9 @@ async def submit_quantum_circuit(circuit: str) -> dict: """ import httpx try: - async with httpx.AsyncClient() as client: + async with _api() as client: resp = await client.post( - "http://localhost:8081/api/v1/circuits/submit", + f"{API}/api/v1/circuits/submit", json={"circuit": circuit}, timeout=30.0, ) @@ -321,9 +375,9 @@ async def get_circuit_job(job_id: str) -> dict: """ import httpx try: - async with httpx.AsyncClient() as client: + async with _api() as client: resp = await client.get( - f"http://localhost:8081/api/v1/jobs/{job_id}", + f"{API}/api/v1/jobs/{job_id}", timeout=10.0, ) return resp.json() @@ -340,9 +394,9 @@ async def list_circuit_jobs() -> list: """ import httpx try: - async with httpx.AsyncClient() as client: + async with _api() as client: resp = await client.get( - "http://localhost:8081/api/v1/jobs", + f"{API}/api/v1/jobs", timeout=10.0, ) return resp.json() @@ -405,9 +459,9 @@ async def price_option( if delay_time is not None: body["delay_time"] = delay_time try: - async with httpx.AsyncClient() as client: + async with _api() as client: resp = await client.post( - "http://localhost:8081/api/v1/options/submit", + f"{API}/api/v1/options/submit", json=body, timeout=30.0, ) @@ -431,9 +485,9 @@ async def get_option_result(job_id: str) -> dict: """ import httpx try: - async with httpx.AsyncClient() as client: + async with _api() as client: resp = await client.get( - f"http://localhost:8081/api/v1/options/{job_id}", + f"{API}/api/v1/options/{job_id}", timeout=10.0, ) return resp.json() @@ -481,9 +535,9 @@ async def analyze_portfolio_risk( if assets is not None: body["assets"] = assets try: - async with httpx.AsyncClient() as client: + async with _api() as client: resp = await client.post( - "http://localhost:8081/api/v1/risk/submit", + f"{API}/api/v1/risk/submit", json=body, timeout=30.0, ) @@ -507,9 +561,9 @@ async def get_risk_result(job_id: str) -> dict: """ import httpx try: - async with httpx.AsyncClient() as client: + async with _api() as client: resp = await client.get( - f"http://localhost:8081/api/v1/risk/{job_id}", + f"{API}/api/v1/risk/{job_id}", timeout=10.0, ) return resp.json() @@ -531,9 +585,9 @@ async def list_financial_jobs(limit: int = 10) -> list: """ import httpx try: - async with httpx.AsyncClient() as client: + async with _api() as client: resp = await client.get( - "http://localhost:8081/api/v1/finance", + f"{API}/api/v1/finance", timeout=10.0, ) data = resp.json() @@ -558,10 +612,10 @@ async def get_financial_result(job_id: str) -> dict: """ import httpx try: - async with httpx.AsyncClient() as client: + async with _api() as client: # First get the job status job_resp = await client.get( - f"http://localhost:8081/api/v1/finance/{job_id}", + f"{API}/api/v1/finance/{job_id}", timeout=10.0, ) job = job_resp.json() @@ -569,7 +623,7 @@ async def get_financial_result(job_id: str) -> dict: # Also fetch the quantum vs classical comparison report try: cmp_resp = await client.get( - f"http://localhost:8081/api/v1/finance/{job_id}/comparison", + f"{API}/api/v1/finance/{job_id}/comparison", timeout=10.0, ) job["comparison"] = cmp_resp.json() @@ -632,9 +686,9 @@ async def submit_pharma_job( if initial_ligand_smiles: body["initial_ligand_smiles"] = initial_ligand_smiles try: - async with httpx.AsyncClient() as client: + async with _api() as client: resp = await client.post( - "http://localhost:8081/api/v1/pharma/submit", + f"{API}/api/v1/pharma/submit", json=body, timeout=30.0, ) @@ -662,9 +716,9 @@ async def get_pharma_result(job_id: str) -> dict: """ import httpx try: - async with httpx.AsyncClient() as client: + async with _api() as client: resp = await client.get( - f"http://localhost:8081/api/v1/pharma/jobs/{job_id}", + f"{API}/api/v1/pharma/jobs/{job_id}", timeout=10.0, ) data = resp.json() @@ -705,9 +759,9 @@ async def list_pharma_jobs() -> list: """ import httpx try: - async with httpx.AsyncClient() as client: + async with _api() as client: resp = await client.get( - "http://localhost:8081/api/v1/pharma/jobs", + f"{API}/api/v1/pharma/jobs", timeout=10.0, ) return resp.json() @@ -790,9 +844,9 @@ async def fund_proposal(proposal_id: str, amount_usdc: str) -> dict: """ import httpx try: - async with httpx.AsyncClient() as client: + async with _api() as client: resp = await client.post( - f"http://localhost:8081/api/v1/proposals/{proposal_id}/fund", + f"{API}/api/v1/proposals/{proposal_id}/fund", json={"amount": str(amount_usdc)}, timeout=60.0, ) @@ -801,5 +855,222 @@ async def fund_proposal(proposal_id: str, amount_usdc: str) -> dict: logger.error("fund_proposal failed: %s", e) return {"error": str(e)} + # ── Portfolio optimisation (financial modelling) ────────────────────────── + + @mcp.tool() + async def submit_portfolio_optimization( + csv: str, + budget: int | None = None, + risk_aversion: float = 0.5, + max_assets_considered: int = 6, + qaoa_reps: int = 1, + ) -> dict: + """Submit a QAOA portfolio optimisation job (quantum vs exact classical baseline). + + Use for financial modelling, portfolio optimisation or asset selection requests. + csv is a price table. Wide layout: a date column then one price column per asset, e.g. + date,SYN_A,SYN_B,SYN_C,SYN_D + 2026-01-01,100,50,80,30 + 2026-01-02,101,49.5,81,30.4 + ... (at least ~10 rows so returns and covariance are meaningful) + + Args: + csv: Full CSV text (wide layout as above, or long layout date,ticker,value) + budget: How many assets to choose (default: about half) + risk_aversion: 0-10, higher penalises variance more (default 0.5) + max_assets_considered: 2-8 assets fed to the quantum solver (default 6) + qaoa_reps: QAOA depth 1-4 (default 1) + + Returns: + dict with job_id. Use get_financial_result(job_id) for the result. + """ + data = { + "problem_type": "portfolio_optimization", + "risk_aversion": str(risk_aversion), + "max_assets_considered": str(max_assets_considered), + "qaoa_reps": str(qaoa_reps), + } + if budget is not None: + data["budget"] = str(budget) + try: + async with _api() as client: + resp = await client.post( + f"{API}/api/v1/finance/submit", + data=data, + files={"file": ("agent-portfolio.csv", csv.encode(), "text/csv")}, + timeout=30.0, + ) + return resp.json() + except Exception as e: + logger.error("submit_portfolio_optimization failed: %s", e) + return {"error": str(e)} + + # ── NEAR testnet provenance (operator-signed) ───────────────────────────── + + async def _experiment_bundle(client: httpx.AsyncClient, job_id: str): + """Commit an owned, completed job's result and the owner's SIWE wallet into one bundle.""" + from quantum_backend_v2.provenance.hashing import hash_json + from quantum_backend_v2.provenance.models import ProvenanceBundle + + for kind, path in _EXPERIMENT_PATHS: # noqa: B007 - kind/path are used after the break + resp = await client.get(API + path.format(job_id), timeout=10.0) + if resp.status_code == 200: + break + else: + raise ValueError(f"No job {job_id} found in your account") + job = resp.json() + if str(job.get("status", "")).lower() != "completed": + raise ValueError( + f"Job {job_id} is {job.get('status')}; only completed experiments can be published" + ) + result = job.get("result") if job.get("result") is not None else job + summary: dict[str, Any] = { + "experiment_type": kind, + "result_hash": hash_json(result), + "result_hash_scope": "job result as returned by result_url at publication", + "result_url": path.format(job_id), + "owner_wallet": owner_wallet, + } + if job.get("provenance_bundle_id"): + summary["source_bundle_id"] = job["provenance_bundle_id"] + embedded = result.get("provenance") if isinstance(result, dict) else None + if isinstance(embedded, dict) and embedded.get("bundle_hash"): + summary["source_bundle_hash"] = embedded["bundle_hash"] + return ProvenanceBundle( + bundle_id=f"near-{job_id}", + workflow_run_id=job_id, + workflow_definition_id=kind, + owner_user_id=owner_id, + summary=summary, + is_publishable=True, + created_at=datetime.now(timezone.utc), + ) + + def _near_settings(): + from quantum_backend_v2.config import load_settings + + settings = load_settings().near_registry + if not settings.configured: + raise ValueError( + "NEAR registry is not configured (QB2_NEAR_REGISTRY_CONTRACT/PUBLISHER)" + ) + return settings + + async def _owned_bundles(collection, bundle_ids: list[str]) -> None: + query = {"bundle_id": {"$in": bundle_ids}} + rows = await collection.find(query).to_list(length=len(bundle_ids)) + if any(row["payload"].get("owner_user_id") != owner_id for row in rows): + raise ValueError("One or more provenance bundles belong to another account") + + @mcp.tool() + async def prepare_near_anchor(job_ids: list[str]) -> dict: + """Prepare completed experiments for publication on the NEAR testnet provenance registry. + + Works for quantum circuit, portfolio optimisation, drug discovery, options and risk jobs. + Each job gets a provenance bundle committing to its result hash and the user's signed-in + Ethereum wallet; the bundles form one SHA-256 Merkle root. Nothing is sent on-chain here: + show the user near_cli_command exactly as returned. After they run it and paste the + transaction hash, call attach_near_anchor with the SAME job_ids in the SAME order. + + Args: + job_ids: 1-50 completed job IDs owned by the user + + Returns: + merkle_root, bundle_ids, contract_arguments and near_cli_command for the + publisher to sign. + """ + from quantum_backend_v2.application.near_provenance import prepare_manifest + from quantum_backend_v2.persistence.mongodb import ProvenanceBundleDocument + from quantum_backend_v2.provenance.hashing import bundle_hash + + try: + if not 1 <= len(job_ids) <= 50 or len(set(job_ids)) != len(job_ids): + raise ValueError("Provide 1-50 unique job IDs") + settings = _near_settings() + collection = db[ProvenanceBundleDocument.Settings.name] + bundle_ids = [f"near-{job_id}" for job_id in job_ids] + await _owned_bundles(collection, bundle_ids) + rows = await collection.find({"bundle_id": {"$in": bundle_ids}}).to_list(length=50) + existing = {row["bundle_id"] for row in rows} + async with _api() as client: + for job_id, bundle_id in zip(job_ids, bundle_ids, strict=True): + if bundle_id in existing: + continue # keep the original commitment so retries reuse the same root + bundle = await _experiment_bundle(client, job_id) + await collection.insert_one({ + "bundle_id": bundle_id, + "workflow_run_id": job_id, + "artifact_refs": [], + "peer_log_refs": [], + "payload": bundle.model_dump(mode="json"), + "content_hash": bundle_hash(bundle), + "created_at": bundle.created_at, + "anchor_batch_id": None, + }) + manifest = await prepare_manifest(collection, bundle_ids, settings) + args = json.dumps(manifest.contract_arguments(), separators=(",", ":")) + return { + "status": "awaiting_signature", + "merkle_root": manifest.merkle_root, + "leaf_count": manifest.leaf_count, + "bundle_ids": bundle_ids, + "owner_wallet": owner_wallet, + "registry": settings.contract_id, + "contract_arguments": manifest.contract_arguments(), + "near_cli_command": ( + f"near contract call-function as-transaction {settings.contract_id} anchor " + f"json-args '{args}' prepaid-gas '30 Tgas' attached-deposit '0.01 NEAR' " + f"sign-as {settings.publisher_id} network-config testnet " + "sign-with-keychain send" + ), + } + except Exception as e: + logger.error("prepare_near_anchor failed: %s", type(e).__name__) + return {"error": str(e)} + + @mcp.tool() + async def attach_near_anchor(job_ids: list[str], tx_hash: str) -> dict: + """Verify a signed NEAR testnet anchor transaction and attach inclusion proofs. + + Call after the user pastes the transaction hash from the near_cli_command returned by + prepare_near_anchor. Use the same job_ids in the same order. Safe to retry. + + Args: + job_ids: The job IDs passed to prepare_near_anchor, same order + tx_hash: NEAR testnet transaction hash (base58) + + Returns: + verified flag, explorer_url (testnet.nearblocks.io) and merkle_root. + """ + from quantum_backend_v2.application.near_provenance import attach_manifest, prepare_manifest + from quantum_backend_v2.persistence.mongodb import ProvenanceBundleDocument + from quantum_backend_v2.provenance.near_registry import NearRegistryAdapter + + try: + settings = _near_settings() + collection = db[ProvenanceBundleDocument.Settings.name] + bundle_ids = [f"near-{job_id}" for job_id in job_ids] + await _owned_bundles(collection, bundle_ids) + manifest = await prepare_manifest(collection, bundle_ids, settings) + adapter = NearRegistryAdapter(settings) + await attach_manifest(collection, manifest, tx_hash.strip(), adapter) + return { + "verified": True, + "explorer_url": adapter.explorer_url(tx_hash.strip()), + "registry": settings.contract_id, + "merkle_root": manifest.merkle_root, + "bundle_ids": bundle_ids, + "owner_wallet": owner_wallet, + } + except OSError as e: + # Adapter OSErrors carry fixed, credential-free messages. + return { + "verified": False, + "error": f"{e}. The transaction may not be final yet, or the RPC " + "(QB2_NEAR_RPC_URL) may not keep history that old; retry shortly " + "or use an archival RPC.", + } + except Exception as e: + return {"verified": False, "error": str(e)} return mcp diff --git a/backend/src/quantum_backend_v2/api/deps/auth.py b/backend/src/quantum_backend_v2/api/deps/auth.py index 8a24f0da..cf0dd6b3 100644 --- a/backend/src/quantum_backend_v2/api/deps/auth.py +++ b/backend/src/quantum_backend_v2/api/deps/auth.py @@ -124,6 +124,7 @@ async def _resolve_user_claims( email=data["email"], roles=frozenset({UserRole.DEVELOPER}), org_ids=frozenset(), issued_at=datetime.fromtimestamp(data["iat"], timezone.utc), expires_at=datetime.fromtimestamp(data["exp"], timezone.utc), + wallet_address=data.get("wallet"), ) except (ValueError, KeyError, TypeError): raise PlatformException(status_code=401, error=ErrorCode.UNAUTHORIZED, diff --git a/backend/src/quantum_backend_v2/identity/models.py b/backend/src/quantum_backend_v2/identity/models.py index 4c8c3201..159c43f0 100644 --- a/backend/src/quantum_backend_v2/identity/models.py +++ b/backend/src/quantum_backend_v2/identity/models.py @@ -50,6 +50,8 @@ class UserTokenClaims(BaseModel): org_ids: frozenset[str] = Field(default_factory=frozenset) issued_at: datetime expires_at: datetime + # Primary SIWE wallet, only from a signed frontend assertion. + wallet_address: str | None = Field(default=None, pattern=r"^0x[0-9a-fA-F]{40}$") def has_role(self, role: UserRole) -> bool: return role in self.roles diff --git a/backend/src/services/ai_agent_service.py b/backend/src/services/ai_agent_service.py index e7aa0d61..194d2465 100644 --- a/backend/src/services/ai_agent_service.py +++ b/backend/src/services/ai_agent_service.py @@ -883,11 +883,14 @@ def _parse_coalition_response(self, response: str) -> dict: async def chat(self, agent_id: str, agent_name: str, message: str, history: list[dict] | None = None, owner_id: str | None = None, + owner_email: str | None = None, owner_wallet: str | None = None, session_id: str | None = None, meta: dict[str, Any] | None = None, llm_provider: str | None = None) -> str: from services.groq_agent import complete from mcp_server.platform_mcp import create_platform_mcp - mcp_server = create_platform_mcp(self.db, owner_id or "", agent_id) + mcp_server = create_platform_mcp( + self.db, owner_id or "", agent_id, owner_email=owner_email, owner_wallet=owner_wallet + ) tool_map = await mcp_server.list_tools() definitions = [{"type": "function", "function": { "name": tool.name, "description": " ".join((tool.description or "").split()), @@ -907,7 +910,26 @@ async def chat(self, agent_id: str, agent_name: str, message: str, }, "required": ["title", "content"], "additionalProperties": False}, }}) + definitions.append({"type": "function", "function": { + "name": "request_approval", + "description": ( + "Ask the user to approve an action before you take it. The chat shows Approve and " + "Decline buttons and your turn ends. Use it instead of asking 'shall I proceed?' " + "in text. When the user approves, carry the action out." + ), + "parameters": {"type": "object", "properties": { + "summary": {"type": "string", "description": "What will happen, in one or two sentences."}, + "action": {"type": "string", "description": "Short button label, e.g. 'Publish to NEAR'."}, + }, "required": ["summary", "action"], "additionalProperties": False}, + }}) + async def invoke(name, arguments): + if name == "request_approval": + return { + "status": "awaiting_approval", + "summary": str(arguments.get("summary", ""))[:2000], + "action": str(arguments.get("action", "Approve"))[:80] or "Approve", + } if name == "prepare_storage_export" and storage: try: proposal = await storage.prepare(owner_id, agent_id, session_id, **arguments, message_index=len(history or []) + 1) @@ -926,7 +948,16 @@ async def invoke(name, arguments): "and ask for approval. Never say it is stored before a verified receipt. " "You cannot approve, upload, pay, or claim the user approved via a tool. " "Storage is Base Sepolia testnet only. No real-money payments. " - "Do not repeatedly call a failed tool or duplicate a creation request." + "Do not repeatedly call a failed tool or duplicate a creation request. " + "Whenever you need the user's go-ahead, call request_approval instead of asking in " + "text. A user message starting with 'Approved' is that go-ahead: proceed. " + "After an experiment completes, offer to publish it to NEAR testnet with " + "prepare_near_anchor. Show the returned near_cli_command verbatim on one line; " + "the registry publisher account signs it with the NEAR CLI. The Ethereum " + "owner_wallet is attribution inside the bundles, not the NEAR signer. When the user " + "pastes the transaction hash, call attach_near_anchor with the same job_ids in the " + "same order. Never claim an experiment is on-chain until attach_near_anchor " + "returns verified." ) messages = [{"role": "system", "content": system}] messages.extend({"role": h["role"], "content": h["content"]} diff --git a/backend/src/services/groq_agent.py b/backend/src/services/groq_agent.py index f530a24e..b7119f3f 100644 --- a/backend/src/services/groq_agent.py +++ b/backend/src/services/groq_agent.py @@ -217,6 +217,12 @@ async def complete( raise ValueError("Tool arguments must be an object") logging.getLogger(__name__).info("Agent tool: %s", function["name"]) result = await invoke(function["name"], arguments) + if function["name"] == "request_approval" and isinstance(result, dict): + if meta is not None: + meta["approval"] = {"summary": result["summary"], "action": result["action"]} + if provider == "near": + _populate_near_meta(meta, model, round_statuses, round_signatures, last_request_id, round_index) + return message.get("content") or result["summary"] if function["name"] == "prepare_storage_export" and isinstance(result, dict) and result.get("status") == "pending": if provider == "near" and meta is not None: _populate_near_meta(meta, model, round_statuses, round_signatures, last_request_id, round_index) diff --git a/frontend/src/app/(main)/agents/chat/page.tsx b/frontend/src/app/(main)/agents/chat/page.tsx index d404e592..49272d4a 100644 --- a/frontend/src/app/(main)/agents/chat/page.tsx +++ b/frontend/src/app/(main)/agents/chat/page.tsx @@ -27,6 +27,7 @@ import { type ChatSession, } from "@/features/agentkit/hooks/use-chat-sessions"; import { AttestationBadge } from "@/features/agent/components/conversation-panel"; +import { ApprovalActions } from "@/features/agentkit/components/approval-actions"; import { useStorageExports, type StorageExport } from "@/features/agentkit/hooks/use-storage-exports"; import { StorageExports } from "@/features/agentkit/components/storage-exports"; @@ -267,6 +268,7 @@ function AgentsChatInner() { role: "agent", content: data.reply as string, attestation: (data.attestation as AttestationSummary | null | undefined) ?? null, + approval: (data.approval as ChatMessage["approval"]) ?? null, }, sessionId ); @@ -422,6 +424,16 @@ function AgentsChatInner() { )} + {msg.approval && i === messages.length - 1 && ( + + send(approved ? `Approved. Go ahead: ${msg.approval!.action}` : "Declined. Do not do that.") + } + /> + )} item.message_index === i)} busy={storage.decision.isPending} decide={decideStorage} /> ) diff --git a/frontend/src/app/globals.css b/frontend/src/app/globals.css index 8b746e00..0d235f22 100644 --- a/frontend/src/app/globals.css +++ b/frontend/src/app/globals.css @@ -264,3 +264,12 @@ 70% { opacity: 1; } 100% { transform: rotate(215deg) translateX(-500px); opacity: 0; } } + +/* Chat code blocks: highlight.js token colours from the chart palette (rehype-highlight). */ +.hljs-keyword, .hljs-selector-tag, .hljs-built_in, .hljs-type { color: var(--chart-3); } +.hljs-string, .hljs-regexp, .hljs-addition, .hljs-attribute { color: var(--chart-4); } +.hljs-number, .hljs-literal, .hljs-symbol, .hljs-bullet { color: var(--chart-5); } +.hljs-title, .hljs-section, .hljs-function .hljs-title, .hljs-name { color: var(--chart-2); } +.hljs-attr, .hljs-variable, .hljs-template-variable, .hljs-params { color: var(--chart-1); } +.hljs-comment, .hljs-quote, .hljs-meta { color: var(--muted-foreground); font-style: italic; } +.hljs-deletion { color: var(--destructive); } diff --git a/frontend/src/features/agentkit/components/approval-actions.tsx b/frontend/src/features/agentkit/components/approval-actions.tsx new file mode 100644 index 00000000..b6e611cc --- /dev/null +++ b/frontend/src/features/agentkit/components/approval-actions.tsx @@ -0,0 +1,59 @@ +"use client"; + +import { Check, ShieldQuestion, X } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import type { ApprovalRequest } from "@/features/agentkit/hooks/use-chat-sessions"; + +/** Approve / Decline for an agent turn that ended with `request_approval`. */ +export function ApprovalActions({ + approval, + showSummary, + disabled, + onDecide, +}: { + approval: ApprovalRequest; + showSummary: boolean; + disabled: boolean; + onDecide: (approved: boolean) => void; +}) { + return ( +
+
+ +
+

Your agent is waiting for approval

+ {showSummary && ( +

+ {approval.summary} +

+ )} +
+
+ + +
+ ); +} diff --git a/frontend/src/features/agentkit/components/rich-message-renderer.tsx b/frontend/src/features/agentkit/components/rich-message-renderer.tsx index 55308e10..23788244 100644 --- a/frontend/src/features/agentkit/components/rich-message-renderer.tsx +++ b/frontend/src/features/agentkit/components/rich-message-renderer.tsx @@ -1,7 +1,7 @@ "use client"; import { motion, AnimatePresence } from "motion/react"; -import ReactMarkdown from "react-markdown"; +import ReactMarkdown, { type Components } from "react-markdown"; import remarkGfm from "remark-gfm"; import rehypeHighlight from "rehype-highlight"; import { Badge } from "@/components/ui/badge"; @@ -36,7 +36,7 @@ import { BarChart2, Cpu, } from "lucide-react"; -import { useState } from "react"; +import { createContext, useContext, useState, type ReactNode } from "react"; import { EnsAddress } from "./ens-address"; // ── Typed rich-content payloads ────────────────────────────────────────────── @@ -591,107 +591,163 @@ function ResearchResultCard({ data }: { data: ResearchResultPayload }) { // ── Markdown prose ─────────────────────────────────────────────────────────── -function MarkdownContent({ content }: { content: string }) { +type HastNode = { type: string; value?: string; children?: HastNode[]; properties?: { className?: unknown } }; + +function hastText(node: HastNode | undefined): string { + if (!node) return ""; + return node.value ?? (node.children ?? []).map(hastText).join(""); +} + +// Lets `code` know it sits inside a fenced block, which react-markdown v10 no longer passes. +const InCodeBlock = createContext(false); + +function CodeCopyButton({ text }: { text: string }) { + const [copied, setCopied] = useState(false); return ( - ( -

- {children} -

- ), - strong: ({ children }) => ( - {children} - ), - em: ({ children }) => ( - {children} - ), - // Omit `...props` — react-markdown's @types/react copy conflicts with the - // project's Ref types when `ref` is spread onto intrinsic elements. - code: ({ className, children }) => { - const isBlock = className?.includes("language-"); - return isBlock ? ( - - {children} - - ) : ( - - {children} - - ); - }, - pre: ({ children }) => ( -
{children}
- ), - ul: ({ children }) => ( -
    - {children} -
- ), - ol: ({ children }) => ( -
    - {children} -
- ), - li: ({ children }) => ( -
  • - {children} -
  • - ), - table: ({ children }) => ( -
    - {children}
    -
    - ), - thead: ({ children }) => ( - {children} - ), - th: ({ children }) => ( - - {children} - - ), - td: ({ children }) => ( - - {children} - - ), - blockquote: ({ children }) => ( -
    - {children} -
    - ), - h1: ({ children }) => ( -

    {children}

    - ), - h2: ({ children }) => ( -

    - {children} -

    - ), - h3: ({ children }) => ( -

    - {children} -

    - ), - a: ({ href, children }) => ( - - {children} - - ), + + ); +} + +function CodeBlock({ node, children }: { node?: HastNode; children?: ReactNode }) { + const code = node?.children?.find((child) => child.type === "element"); + const classes = code?.properties?.className; + const language = (Array.isArray(classes) ? classes : []) + .map(String) + .find((name) => name.startsWith("language-")) + ?.slice("language-".length); + return ( +
    +
    + {language ?? "text"} + +
    +
    +        {children}
    +      
    +
    + ); +} + +function InlineOrBlockCode({ className, children }: { className?: string; children?: ReactNode }) { + const inBlock = useContext(InCodeBlock); + return inBlock ? ( + {children} + ) : ( + + {children} + + ); +} + +const MARKDOWN_COMPONENTS: Components = { + p: ({ children }) => ( +

    {children}

    + ), + strong: ({ children }) => {children}, + em: ({ children }) => {children}, + del: ({ children }) => {children}, + // Omit `...props` — react-markdown's @types/react copy conflicts with the + // project's Ref types when `ref` is spread onto intrinsic elements. + pre: ({ node, children }) => {children}, + code: ({ className, children }) => ( + {children} + ), + ul: ({ children, className }) => ( +
      + {children} +
    + ), + ol: ({ children, start }) => ( +
      + {children} +
    + ), + li: ({ children }) => ( +
  • {children}
  • + ), + input: ({ checked }) => ( + + ), + table: ({ children }) => ( +
    + {children}
    +
    + ), + thead: ({ children }) => {children}, + th: ({ children, style }) => ( + + {children} + + ), + td: ({ children, style }) => ( + + {children} + + ), + blockquote: ({ children }) => ( +
    + {children} +
    + ), + hr: () =>
    , + h1: ({ children }) =>

    {children}

    , + h2: ({ children }) => ( +

    {children}

    + ), + h3: ({ children }) => ( +

    {children}

    + ), + h4: ({ children }) => ( +

    {children}

    + ), + h5: ({ children }) =>
    {children}
    , + h6: ({ children }) =>
    {children}
    , + a: ({ href, children }) => ( + + {children} + + ), + img: ({ src, alt }) => + typeof src === "string" ? ( + // Agent-supplied URLs of unknown size; next/image needs known hosts and dimensions. + // eslint-disable-next-line @next/next/no-img-element + {alt + ) : null, +}; + +function MarkdownContent({ content }: { content: string }) { + return ( +
    + + {content} + +
    ); } diff --git a/frontend/src/features/agentkit/hooks/use-chat-sessions.ts b/frontend/src/features/agentkit/hooks/use-chat-sessions.ts index 72d9ed48..4d21d1b7 100644 --- a/frontend/src/features/agentkit/hooks/use-chat-sessions.ts +++ b/frontend/src/features/agentkit/hooks/use-chat-sessions.ts @@ -15,11 +15,15 @@ export type AttestationSummary = { rounds: number; }; +/** The agent paused for the user's go-ahead (backend `request_approval` tool). */ +export type ApprovalRequest = { summary: string; action: string }; + export type ChatMessage = { role: "user" | "agent"; content: string; richContent?: RichContent; attestation?: AttestationSummary | null; + approval?: ApprovalRequest | null; }; export type ChatSession = { @@ -39,6 +43,7 @@ function toLocalSession(raw: { content: string; richContent?: RichContent; attestation?: AttestationSummary | null; + approval?: ApprovalRequest | null; }>; agent_id: string; created_at: string; @@ -53,6 +58,7 @@ function toLocalSession(raw: { content: m.content, richContent: m.richContent, attestation: m.attestation ?? null, + approval: m.approval ?? null, })), createdAt: parseApiTimestamp(raw.created_at)?.getTime() ?? 0, updatedAt: parseApiTimestamp(raw.updated_at)?.getTime() ?? 0, @@ -143,6 +149,7 @@ export function useChatSessions() { content: message.content, rich_content: message.richContent ?? null, attestation: message.attestation ?? null, + approval: message.approval ?? null, }, }), }); diff --git a/frontend/src/features/agentkit/server/backend-fetch.ts b/frontend/src/features/agentkit/server/backend-fetch.ts index c82ccd0f..86793df6 100644 --- a/frontend/src/features/agentkit/server/backend-fetch.ts +++ b/frontend/src/features/agentkit/server/backend-fetch.ts @@ -1,11 +1,21 @@ import "server-only"; import { backendAssertion } from "@/features/auth/server/backend-assertion"; import { getSession } from "@/features/auth/server/session"; +import { ObjectId } from "mongodb"; +import { getDatabase } from "@/shared/lib/mongodb"; export async function agentBackendFetch(url: string, init: RequestInit = {}) { const session = await getSession(); if (!session?.user) return Response.json({ error: "Sign in to use your agent." }, { status: 401 }); - const assertion = backendAssertion(session.user); + // The primary SIWE wallet is committed into agent-made provenance bundles. + const wallet = await (await getDatabase()) + .collection("walletAddress") + .findOne( + // Better Auth's SIWE sign-in stores an ObjectId; the link route stores the string id. + { userId: { $in: ObjectId.isValid(session.user.id) ? [session.user.id, new ObjectId(session.user.id)] : [session.user.id] }, isPrimary: true }, + { projection: { address: 1 } }, + ); + const assertion = backendAssertion(session.user, wallet?.address); if (!assertion) return Response.json({ error: "Agent authentication is not configured." }, { status: 503 }); const headers = new Headers(init.headers); headers.set("Authorization", assertion); diff --git a/frontend/src/features/auth/server/backend-assertion.ts b/frontend/src/features/auth/server/backend-assertion.ts index 1290cc60..4c2db885 100644 --- a/frontend/src/features/auth/server/backend-assertion.ts +++ b/frontend/src/features/auth/server/backend-assertion.ts @@ -7,7 +7,10 @@ const MIN_SECRET_LENGTH = 32; * A short-lived, HMAC-signed `Authorization` value naming the signed-in user, * verified by the backend's auth dependency. Null when the secret is not set. */ -export function backendAssertion(user: { id: string; email: string }): string | null { +export function backendAssertion( + user: { id: string; email: string }, + wallet?: string | null, +): string | null { const secret = process.env.AGENT_AUTH_BRIDGE_SECRET; if (!secret || secret.length < MIN_SECRET_LENGTH) return null; const now = Math.floor(Date.now() / 1000); @@ -18,6 +21,7 @@ export function backendAssertion(user: { id: string; email: string }): string | iat: now, exp: now + 60, aud: "quantumnodes-agentkit", + ...(wallet ? { wallet } : {}), }), ).toString("base64url"); const signature = createHmac("sha256", secret).update(body).digest("hex");