Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

x402: record the chat thread separately and stamp the http_request fallback with the ledger session

Steven Enamakel53682f1983e6
diff --git a/crates/openhuman-core/src/tools/impl/network/http_request.rs b/crates/openhuman-core/src/tools/impl/network/http_request.rs
index 0882a0ce8e..ea73ac7b10 100644
--- a/crates/openhuman-core/src/tools/impl/network/http_request.rs
+++ b/crates/openhuman-core/src/tools/impl/network/http_request.rs
@@ -184,23 +184,9 @@ impl HttpRequestTool {
.await
.map_err(|e| format!("x402 payment failed: {e}"))?;
- let record = x402::PaymentRecord {
- id: uuid::Uuid::new_v4().to_string(),
- url: payment_result.url.clone(),
- asset: payment_result.asset.clone(),
- amount_atomic: payment_result.amount_atomic,
- amount_display: format!(
- "{:.6} USDC",
- payment_result.amount_atomic as f64 / 1_000_000.0
- ),
- recipient: payment_result.recipient.clone(),
- network: payment_result.network.clone(),
- tx_signature: None,
- status: x402::PaymentStatus::Pending,
- timestamp: chrono::Utc::now(),
- session_id: String::new(),
- };
-
+ // 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));
diff --git a/crates/openhuman-core/src/web3/x402/README.md b/crates/openhuman-core/src/web3/x402/README.md
index b7796c2cca..3c6b19ceaf 100644
--- a/crates/openhuman-core/src/web3/x402/README.md
+++ b/crates/openhuman-core/src/web3/x402/README.md
@@ -43,6 +43,7 @@ and does not need a stub. Signatures must match the real ones exactly;
| `mod.rs` | Facade root: feature gate; re-exports from `tinywallet_x402` (`X402Client`, `X402Error`, `X402PaymentResult`, `handle_402`, the ledger and wire types); `init_ledger`, `handle_402_and_pay`, `try_paid_request` and `request_tool`, which supply the seams; the `store` accessors used by `http_request`. |
| `seams.rs` | `WalletPaymentSigner` (the crate's `PaymentSigner`: keyring secret, decrypt, `modules::wallet::{derive_account, sign_message}`), `RuntimeProxyPolicy` (`ProxyPolicy` over `config::apply_runtime_proxy_to_builder`), and the `payments()` / `request_tool()` constructors that pair them with the wallet's `OpenHumanTransport`. |
| `budget.rs` | The spending limits: the crate's defaults plus the `OPENHUMAN_X402_*` overrides. |
+| `records.rs` | `pending_record`: the `Pending` ledger record for the `http_request` fallback (ledger session + chat thread). |
| `schemas.rs` | RPC controller schemas and handlers for the `x402` namespace: `get_summary`, `list_payments`, `update_budget`. |
| `stub.rs` | Disabled facade compiled when `web3` is off. See Compile-time gate above. |
| `seams_tests.rs`, `budget_tests.rs`, `stub_tests.rs` | Behavior tests. `stub_tests.rs` runs only in the disabled build. The protocol, builder, ledger and tool tests live in the crate. |
@@ -77,11 +78,12 @@ from the retry's outcome and the `PAYMENT-RESPONSE` header. It differs from the
generic `http_request` tool (`tools/impl/network/http_request.rs`), which
handles a 402 only as a silent fallback.
-The tool is built with `TaskLocalSession` (`seams.rs`), the host's
-`tinywallet_x402::session::SessionScope`: it reads the chat thread id from the
-`APPROVAL_CHAT_CONTEXT` task-local and the crate stamps it on every ledger
-record of the payment. Outside a chat turn (CLI, JSON-RPC, cron) it reports no
-session and the crate uses the ledger's `x402-<uuid>` boot id instead.
+The tool is built with `TaskLocalThread` (`seams.rs`), the host's
+`tinywallet_x402::thread::ThreadScope`: it reads the chat thread id from the
+`APPROVAL_CHAT_CONTEXT` task-local and the crate records it as
+`PaymentRecord.thread_id` (absent outside a chat turn). `session_id` is always
+the ledger's own `x402-<uuid>` boot id. The `http_request` 402 fallback builds
+its record with `pending_record` (`records.rs`), which applies the same rule.
## Persistence
@@ -95,10 +97,9 @@ session and the crate uses the ledger's `x402-<uuid>` boot id instead.
exceed a cap. Daily and monthly totals sum the `Settled` records for the
current UTC day / calendar month plus the amounts held by in-flight payments.
The session total reported by `get_summary` counts records whose `session_id`
- equals the ledger's `x402-<uuid>` boot id; it is not a cap. The `x402_request`
- tool stamps chat payments with the thread id (see above) and other payments
- with the boot id; the `http_request` fallback still stores an empty
- `session_id`. `init_ledger` seeds the limits from
+ equals the ledger's `x402-<uuid>` boot id, which every payment of this process
+ carries (both writers), so it is the process's total; it is not a cap. The chat
+ thread is recorded separately in `thread_id`. `init_ledger` seeds the limits from
`OPENHUMAN_X402_PER_REQUEST_MAX` / `OPENHUMAN_X402_DAILY_MAX` /
`OPENHUMAN_X402_MONTHLY_MAX` when set (`budget.rs`); `update_budget` changes
them for the running process only and does not rewrite historical records.
diff --git a/crates/openhuman-core/src/web3/x402/mod.rs b/crates/openhuman-core/src/web3/x402/mod.rs
index c4efb9921f..dd0fc67b42 100644
--- a/crates/openhuman-core/src/web3/x402/mod.rs
+++ b/crates/openhuman-core/src/web3/x402/mod.rs
@@ -33,10 +33,14 @@
#[cfg(feature = "web3")]
pub(crate) mod budget;
#[cfg(feature = "web3")]
+mod records;
+#[cfg(feature = "web3")]
mod schemas;
#[cfg(feature = "web3")]
pub(crate) mod seams;
+#[cfg(feature = "web3")]
+pub use records::pending_record;
#[cfg(feature = "web3")]
pub use schemas::all_controller_schemas as all_x402_controller_schemas;
#[cfg(feature = "web3")]
diff --git a/crates/openhuman-core/src/web3/x402/records.rs b/crates/openhuman-core/src/web3/x402/records.rs
new file mode 100644
index 0000000000..be2c348667
--- /dev/null
+++ b/crates/openhuman-core/src/web3/x402/records.rs
@@ -0,0 +1,41 @@
+//! The ledger record a payment starts with, for callers outside the
+//! `x402_request` tool (the `http_request` 402 fallback).
+//!
+//! The tool builds its own records inside the crate; this is the same rule for
+//! the host's other writer, so both attribute a payment identically:
+//! `session_id` is always the ledger's own session (so the session total counts
+//! the payment) and `thread_id` is the chat thread from `APPROVAL_CHAT_CONTEXT`.
+
+use tinywallet_x402::ledger::{self, PaymentRecord, PaymentStatus};
+use tinywallet_x402::protocol::X402PaymentResult;
+use tinywallet_x402::thread::ThreadScope;
+
+use super::seams::TaskLocalThread;
+
+/// A `Pending` record for `payment`, stamped with the ledger's session and the
+/// active chat thread (if any). Later states are written as new lines with the
+/// same `id`.
+#[allow(clippy::cast_precision_loss)] // atomic USDC amounts stay far below 2^53
+pub fn pending_record(payment: &X402PaymentResult) -> PaymentRecord {
+ // A ledger that is not initialised has no session to name; the payment
+ // would have failed at the budget check before reaching here.
+ let session_id = ledger::with_ledger(|l| l.session_id().to_string()).unwrap_or_default();
+ PaymentRecord {
+ id: uuid::Uuid::new_v4().to_string(),
+ url: payment.url.clone(),
+ asset: payment.asset.clone(),
+ amount_atomic: payment.amount_atomic,
+ amount_display: format!("{:.6} USDC", payment.amount_atomic as f64 / 1_000_000.0),
+ recipient: payment.recipient.clone(),
+ network: payment.network.clone(),
+ tx_signature: None,
+ status: PaymentStatus::Pending,
+ timestamp: chrono::Utc::now(),
+ session_id,
+ thread_id: TaskLocalThread.current_thread(),
+ }
+}
+
+#[cfg(test)]
+#[path = "records_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/web3/x402/records_tests.rs b/crates/openhuman-core/src/web3/x402/records_tests.rs
new file mode 100644
index 0000000000..2ea6df038b
--- /dev/null
+++ b/crates/openhuman-core/src/web3/x402/records_tests.rs
@@ -0,0 +1,81 @@
+use super::*;
+use crate::security::approval::{ApprovalChatContext, APPROVAL_CHAT_CONTEXT};
+use crate::web3::wallet::test_support::TEST_LOCK;
+use tinywallet_x402::ledger::{self, PaymentStatus};
+
+const SESSION: &str = "x402-boot-session";
+
+fn chat_ctx(thread: &str) -> ApprovalChatContext {
+ ApprovalChatContext {
+ thread_id: thread.to_string(),
+ client_id: "client".to_string(),
+ request_id: None,
+ }
+}
+
+/// A payment as `handle_402_and_pay` hands it back: 2500 atomic USDC held on
+/// the process-wide ledger.
+fn payment() -> X402PaymentResult {
+ X402PaymentResult {
+ header_value: "header".into(),
+ amount_atomic: 2_500,
+ asset: "usdc-mint".into(),
+ recipient: "recipient".into(),
+ network: "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp".into(),
+ url: "https://x402.example.test/thing".into(),
+ reservation: ledger::reserve(2_500).unwrap().unwrap(),
+ }
+}
+
+fn init(temp: &tempfile::TempDir) {
+ super::super::init_ledger(temp.path(), SESSION);
+}
+
+/// The fallback path's pending record carries the ledger's session, so the
+/// payment counts toward `session_total` once it settles, and the chat thread.
+#[tokio::test]
+async fn a_fallback_payment_counts_in_the_session_total_and_names_its_thread() {
+ let _lock = TEST_LOCK.lock();
+ let temp = tempfile::tempdir().unwrap();
+ init(&temp);
+ let payment = payment();
+
+ let record = APPROVAL_CHAT_CONTEXT
+ .scope(chat_ctx("thread-a"), async { pending_record(&payment) })
+ .await;
+
+ assert_eq!(record.status, PaymentStatus::Pending);
+ assert_eq!(record.session_id, SESSION);
+ assert_eq!(record.thread_id.as_deref(), Some("thread-a"));
+ assert_eq!(record.amount_atomic, 2_500);
+ assert_eq!(record.amount_display, "0.002500 USDC");
+ assert_eq!(record.url, payment.url);
+
+ let mut settled = record.clone();
+ settled.status = PaymentStatus::Settled;
+ payment.reservation.commit(settled);
+ let summary = ledger::with_ledger(|l| l.summary()).unwrap();
+ assert_eq!(summary.session_total_atomic, 2_500);
+ assert_eq!(summary.session_count, 1);
+}
+
+#[tokio::test]
+async fn a_payment_outside_a_chat_turn_has_no_thread_but_the_same_session() {
+ let _lock = TEST_LOCK.lock();
+ let temp = tempfile::tempdir().unwrap();
+ init(&temp);
+
+ let record = pending_record(&payment());
+
+ assert_eq!(record.thread_id, None);
+ assert_eq!(record.session_id, SESSION);
+}
+
+#[tokio::test]
+async fn every_payment_gets_its_own_record_id() {
+ let _lock = TEST_LOCK.lock();
+ let temp = tempfile::tempdir().unwrap();
+ init(&temp);
+
+ assert_ne!(pending_record(&payment()).id, pending_record(&payment()).id);
+}
diff --git a/crates/openhuman-core/src/web3/x402/seams.rs b/crates/openhuman-core/src/web3/x402/seams.rs
index 07e59d9a73..4f72de9ce4 100644
--- a/crates/openhuman-core/src/web3/x402/seams.rs
+++ b/crates/openhuman-core/src/web3/x402/seams.rs
@@ -12,7 +12,7 @@
//! blockhash.
//! - a [`ProxyPolicy`]: [`RuntimeProxyPolicy`] applies the runtime proxy
//! configuration to the tool's HTTP client.
-//! - a [`SessionScope`]: [`TaskLocalSession`] names the chat thread running the
+//! - a [`ThreadScope`]: [`TaskLocalThread`] names the chat thread running the
//! tool call, so the ledger can attribute the payment to it.
//!
//! Every `Err(String)` these return is the text a user sees, prefixed exactly as
@@ -25,7 +25,7 @@ use async_trait::async_trait;
use log::debug;
use tinywallet_x402::crypto::{CryptoPayments, PaymentAccount, PaymentSigner, SignScheme};
use tinywallet_x402::protocol::ProxyPolicy;
-use tinywallet_x402::session::SessionScope;
+use tinywallet_x402::thread::ThreadScope;
use tinywallet_x402::tools::X402RequestTool;
use tinywallet_x402::wire::PaymentChain;
@@ -48,17 +48,17 @@ pub(crate) struct RuntimeProxyPolicy;
///
/// `Some(thread_id)` inside an interactive chat turn (the web channel installs the
/// task-local around the run), `None` for CLI, direct JSON-RPC, cron and other
-/// non-chat callers, whose payments the crate attributes to the ledger's own
-/// session instead.
+/// non-chat callers, whose payments then carry no `thread_id`. The ledger's
+/// `session_id` never comes from here: it is always the ledger's own.
///
/// `tokio::task_local!` propagates across `.await` but **not** across
/// `tokio::spawn`; the crate calls this synchronously on the tool's own task, and
/// the regression test in `seams_tests.rs` pins that it reads the task-local.
#[derive(Debug, Clone, Copy, Default)]
-pub(crate) struct TaskLocalSession;
+pub(crate) struct TaskLocalThread;
-impl SessionScope for TaskLocalSession {
- fn current_session(&self) -> Option<String> {
+impl ThreadScope for TaskLocalThread {
+ fn current_thread(&self) -> Option<String> {
APPROVAL_CHAT_CONTEXT
.try_with(|ctx| ctx.thread_id.clone())
.ok()
@@ -204,7 +204,7 @@ pub(crate) fn request_tool() -> X402RequestTool {
Arc::new(OpenHumanTransport::new()),
Arc::new(RuntimeProxyPolicy),
)
- .with_session_scope(Arc::new(TaskLocalSession))
+ .with_thread_scope(Arc::new(TaskLocalThread))
}
#[cfg(test)]
diff --git a/crates/openhuman-core/src/web3/x402/seams_tests.rs b/crates/openhuman-core/src/web3/x402/seams_tests.rs
index 1a4d2a2cbf..6105545831 100644
--- a/crates/openhuman-core/src/web3/x402/seams_tests.rs
+++ b/crates/openhuman-core/src/web3/x402/seams_tests.rs
@@ -178,7 +178,7 @@ async fn the_payment_builder_is_object_safe_for_the_facade() {
}
// ---------------------------------------------------------------------------
-// The session seam: which chat thread a payment belongs to
+// The thread seam: which chat thread a payment belongs to
// ---------------------------------------------------------------------------
fn chat_ctx(thread: &str) -> crate::security::approval::ApprovalChatContext {
@@ -189,21 +189,20 @@ fn chat_ctx(thread: &str) -> crate::security::approval::ApprovalChatContext {
}
}
-/// The ledger stamps a payment with this read. If it stopped reading
-/// `APPROVAL_CHAT_CONTEXT`, every tool payment would silently fall back to the
-/// ledger's boot session and lose its thread.
+/// The ledger records a payment's thread from this read. If it stopped reading
+/// `APPROVAL_CHAT_CONTEXT`, every tool payment would silently lose its thread.
#[tokio::test]
-async fn the_session_scope_reads_the_approval_chat_context_task_local() {
- use tinywallet_x402::session::SessionScope;
+async fn the_thread_scope_reads_the_approval_chat_context_task_local() {
+ use tinywallet_x402::thread::ThreadScope;
assert_eq!(
- TaskLocalSession.current_session(),
+ TaskLocalThread.current_thread(),
None,
- "outside a chat turn there is no session"
+ "outside a chat turn there is no thread"
);
let inside = crate::security::approval::APPROVAL_CHAT_CONTEXT
- .scope(chat_ctx("a"), async { TaskLocalSession.current_session() })
+ .scope(chat_ctx("a"), async { TaskLocalThread.current_thread() })
.await;
assert_eq!(inside.as_deref(), Some("thread-a"));
@@ -213,10 +212,10 @@ async fn the_session_scope_reads_the_approval_chat_context_task_local() {
.scope(chat_ctx("outer"), async {
let inner = crate::security::approval::APPROVAL_CHAT_CONTEXT
.scope(chat_ctx("inner"), async {
- TaskLocalSession.current_session()
+ TaskLocalThread.current_thread()
})
.await;
- (inner, TaskLocalSession.current_session())
+ (inner, TaskLocalThread.current_thread())
})
.await;
assert_eq!(inner.as_deref(), Some("thread-inner"));