The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
feat(x402): route http_request 402 retries through the wallet service
Steven Enamakel4844d4aeef35
diff --git a/crates/openhuman-core/src/modules/x402_service.rs b/crates/openhuman-core/src/modules/x402_service.rsindex 1d218533eb..f063815cef 100644--- a/crates/openhuman-core/src/modules/x402_service.rs+++ b/crates/openhuman-core/src/modules/x402_service.rs@@ -6,13 +6,91 @@ use std::sync::OnceLock;use tinywallet_bus::names::methods;use tinywallet_bus::wire::{X402CloseRequest, X402ConfigResponse, X402ConfigureRequest, X402DetailedSpendingSummary,- X402ListPaymentsRequest, X402ListPaymentsResponse, X402ServiceHandle, X402UpdateBudgetRequest,+ X402ListPaymentsRequest, X402ListPaymentsResponse, X402PreparePaymentRequest,+ X402PreparePaymentResponse, X402RecordPaymentRequest, X402ServiceHandle, X402UpdateBudgetRequest,};use crate::config::Config;use super::wallet::{self, WalletCallError};+/// Prepare and sign a 402 challenge inside TinyWallet. Both supported rails'+/// secret material is sent only through the attested confidential call; the+/// module parses the challenge and selects the matching chain.+pub(crate) async fn prepare_payment(+ config: &Config,+ url: String,+ payment_required: String,+ owner: Option<tinywallet_bus::wire::QuoteOwner>,+) -> Result<(X402ServiceHandle, X402PreparePaymentResponse), WalletCallError> {+ let mut active = service().lock().await;+ ensure_service(config, &mut active).await?;+ let service_handle = active+ .as_ref()+ .ok_or_else(|| WalletCallError::Failed("x402 service is unavailable".into()))?+ .handle+ .clone();++ let evm = signing_secret(config, crate::web3::wallet::WalletChain::Evm).await?;+ let solana = signing_secret(config, crate::web3::wallet::WalletChain::Solana).await?;+ let mut request = X402PreparePaymentRequest {+ service: service_handle.clone(),+ url,+ payment_required,+ owner,+ secret: evm,+ additional_secrets: vec![solana],+ };+ let response = wallet::call_confidential(config, methods::X402_PREPARE_PAYMENT, &request).await;+ request.secret.mnemonic.zeroize();+ for secret in &mut request.additional_secrets {+ secret.mnemonic.zeroize();+ }+ Ok((service_handle, response?))+}++/// Record the retry result through the same module-owned payment ledger.+pub(crate) async fn record_payment(+ config: &Config,+ service: X402ServiceHandle,+ payment_id: String,+ response_status: u16,+ settlement_response: Option<String>,+) -> Result<(), WalletCallError> {+ wallet::call(+ config,+ methods::X402_RECORD_PAYMENT,+ X402RecordPaymentRequest {+ service,+ payment_id,+ response_status,+ settlement_response,+ },+ )+ .await+}++async fn signing_secret(+ config: &Config,+ chain: crate::web3::wallet::WalletChain,+) -> Result<tinywallet_bus::wire::SecretMaterial, WalletCallError> {+ let stored = crate::web3::wallet::secret_material(chain)+ .await+ .map_err(WalletCallError::Failed)?;+ let phrase = crate::security::encryption::rpc::decrypt_secret(+ config,+ &stored.encrypted_mnemonic,+ )+ .await+ .map_err(|error| WalletCallError::Failed(error.to_string()))?+ .value;+ Ok(tinywallet_bus::wire::SecretMaterial {+ mnemonic: phrase,+ derivation_path: stored.derivation_path,+ chain: chain.to_chain(),+ })+}+struct X402Service {workspace: PathBuf,config: X402ConfigResponse,diff --git a/crates/openhuman-core/src/tools/impl/network/host.rs b/crates/openhuman-core/src/tools/impl/network/host.rsindex 81e5375c5f..9e35879be9 100644--- a/crates/openhuman-core/src/tools/impl/network/host.rs+++ b/crates/openhuman-core/src/tools/impl/network/host.rs@@ -91,10 +91,9 @@ mod x402 {//! x402 machine payment for `http_request`'s `402 Payment Required` retry.use async_trait::async_trait;- use base64::engine::Engine as _;use tinytools_std::network::{PaymentAttempt, PaymentHook, PaymentOutcome};- use crate::web3::x402;+ use crate::modules::x402_service;#[derive(Debug)]pub(super) struct X402PaymentHook;@@ -106,75 +105,61 @@ mod x402 {url: &str,response_headers: &reqwest::header::HeaderMap,) -> Result<PaymentAttempt, String> {- let payment_result = x402::handle_402_and_pay(response_headers, url)+ let challenge = response_headers+ .get("PAYMENT-REQUIRED")+ .or_else(|| response_headers.get("X-PAYMENT-REQUIRED"))+ .and_then(|value| value.to_str().ok())+ .ok_or_else(|| "402 response is missing a valid PAYMENT-REQUIRED header".to_string())?;+ let config = crate::config::rpc::load_config_with_timeout().await- .map_err(|e| format!("x402 payment failed: {e}"))?;-- // Stamped with the ledger's session and the active chat thread, exactly as- // the `x402_request` tool stamps its own.- let record = x402::pending_record(&payment_result);- let record_id = record.id.clone();- let _ = x402::store::with_ledger_mut(|l| l.record_payment(record));+ .map_err(|error| format!("x402 payment failed: {error}"))?;+ let owner = crate::security::approval::APPROVAL_CHAT_CONTEXT+ .try_with(|context| tinywallet_bus::wire::QuoteOwner {+ thread_id: context.thread_id.clone(),+ client_id: context.client_id.clone(),+ })+ .ok();+ let (service, payment) = x402_service::prepare_payment(+ &config,+ url.to_owned(),+ challenge.to_owned(),+ owner,+ )+ .await+ .map_err(|error| format!("x402 payment failed: {error}"))?;log::debug!("[tool.http_request] retrying with x402 payment header amount={} asset={}",- payment_result.amount_atomic,- payment_result.asset+ payment.amount_atomic,+ payment.asset);- let url = url.to_string();+ let payment_id = payment.payment_id;+ let config = config.clone();Ok(PaymentAttempt {- headers: vec![("PAYMENT-SIGNATURE".to_string(), payment_result.header_value)],- settle: Box::new(move |outcome| settle(&record_id, &url, &outcome)),+ headers: vec![("PAYMENT-SIGNATURE".to_string(), payment.payment_header)],+ settle: Box::new(move |outcome| {+ if let Ok(runtime) = tokio::runtime::Handle::try_current() {+ runtime.spawn(async move {+ if let Err(error) = x402_service::record_payment(+ &config,+ service,+ payment_id,+ outcome.status,+ outcome.payment_response,+ )+ .await+ {+ log::warn!("[tool.http_request] x402 settlement recording failed: {error}");+ }+ });+ } else {+ log::warn!("[tool.http_request] x402 settlement not recorded: runtime unavailable");+ }+ }),})}}-- /// Write the retry's result back onto the ledger entry the payment opened.- fn settle(record_id: &str, url: &str, outcome: &PaymentOutcome) {- let settled_status = if outcome.success {- x402::PaymentStatus::Settled- } else {- x402::PaymentStatus::Failed- };- let tx_sig = outcome- .payment_response- .as_deref()- .and_then(|b64| base64::engine::general_purpose::STANDARD.decode(b64).ok())- .and_then(|bytes| serde_json::from_slice::<x402::SettlementResponse>(&bytes).ok())- .and_then(|r| {- if r.success && !r.transaction.is_empty() {- Some(r.transaction)- } else {- None- }- });-- let _ = x402::store::with_ledger_mut(|l| {- if let Some(rec) = l- .recent_payments(100)- .into_iter()- .find(|r| r.id == record_id)- {- let mut updated = rec;- updated.status = settled_status;- updated.tx_signature = tx_sig.clone();- l.record_payment(updated);- }- });-- if settled_status == x402::PaymentStatus::Settled {- log::debug!(- "[tool.http_request] x402 payment settled for {url} tx={:?}",- tx_sig- );- } else {- log::warn!(- "[tool.http_request] x402 payment retry returned status {}",- outcome.status- );- }- }}#[cfg(test)]