Skip to content

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

x402: stamp tool payments with the chat thread through a SessionScope seam

Steven Enamakel3dff15370af0
diff --git a/crates/openhuman-core/src/web3/x402/README.md b/crates/openhuman-core/src/web3/x402/README.md
index 54140f6f88..b7796c2cca 100644
--- a/crates/openhuman-core/src/web3/x402/README.md
+++ b/crates/openhuman-core/src/web3/x402/README.md
@@ -77,6 +77,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.
+
## Persistence
- `{workspace_dir}/x402/payments.jsonl`: one JSON `PaymentRecord` per line,
@@ -84,12 +90,15 @@ handles a 402 only as a silent fallback.
Loaded into memory by `init_ledger` and held in the crate's process-wide
ledger.
- Budget enforcement (defaults: 1 USDC per request, 10 USDC per day, 100 USDC
- per month, in atomic units) is checked against the in-memory ledger before a
- payment is built. Daily and monthly totals sum the `Settled` records for the
- current UTC day / calendar month. 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, and both writers currently store an empty `session_id`, so it
- reads as zero. `init_ledger` seeds the limits from
+ per month, in atomic units) checks and reserves the amount atomically against
+ the in-memory ledger before a payment is signed, so concurrent payments cannot
+ 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
`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/seams.rs b/crates/openhuman-core/src/web3/x402/seams.rs
index 85e0c94cb8..07e59d9a73 100644
--- a/crates/openhuman-core/src/web3/x402/seams.rs
+++ b/crates/openhuman-core/src/web3/x402/seams.rs
@@ -12,6 +12,8 @@
//! blockhash.
//! - a [`ProxyPolicy`]: [`RuntimeProxyPolicy`] applies the runtime proxy
//! configuration to the tool's HTTP client.
+//! - a [`SessionScope`]: [`TaskLocalSession`] 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
//! the payment flow did before it moved into the crate (`wallet secret: …`,
@@ -23,9 +25,11 @@ 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::tools::X402RequestTool;
use tinywallet_x402::wire::PaymentChain;
+use crate::security::approval::APPROVAL_CHAT_CONTEXT;
use crate::web3::wallet::transport::OpenHumanTransport;
use crate::web3::wallet::WalletChain;
@@ -39,6 +43,28 @@ pub(crate) struct WalletPaymentSigner;
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct RuntimeProxyPolicy;
+/// The chat thread running the current tool call, read from
+/// `APPROVAL_CHAT_CONTEXT`.
+///
+/// `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.
+///
+/// `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;
+
+impl SessionScope for TaskLocalSession {
+ fn current_session(&self) -> Option<String> {
+ APPROVAL_CHAT_CONTEXT
+ .try_with(|ctx| ctx.thread_id.clone())
+ .ok()
+ }
+}
+
/// The wallet chain a payment chain is signed as.
fn wallet_chain(chain: PaymentChain) -> WalletChain {
match chain {
@@ -178,6 +204,7 @@ pub(crate) fn request_tool() -> X402RequestTool {
Arc::new(OpenHumanTransport::new()),
Arc::new(RuntimeProxyPolicy),
)
+ .with_session_scope(Arc::new(TaskLocalSession))
}
#[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 b727412d23..1a4d2a2cbf 100644
--- a/crates/openhuman-core/src/web3/x402/seams_tests.rs
+++ b/crates/openhuman-core/src/web3/x402/seams_tests.rs
@@ -176,3 +176,49 @@ async fn the_signer_reports_a_missing_wallet_for_either_chain() {
async fn the_payment_builder_is_object_safe_for_the_facade() {
let _builder: Box<dyn PaymentBuilder> = Box::new(payments());
}
+
+// ---------------------------------------------------------------------------
+// The session seam: which chat thread a payment belongs to
+// ---------------------------------------------------------------------------
+
+fn chat_ctx(thread: &str) -> crate::security::approval::ApprovalChatContext {
+ crate::security::approval::ApprovalChatContext {
+ thread_id: format!("thread-{thread}"),
+ client_id: format!("client-{thread}"),
+ request_id: None,
+ }
+}
+
+/// 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.
+#[tokio::test]
+async fn the_session_scope_reads_the_approval_chat_context_task_local() {
+ use tinywallet_x402::session::SessionScope;
+
+ assert_eq!(
+ TaskLocalSession.current_session(),
+ None,
+ "outside a chat turn there is no session"
+ );
+
+ let inside = crate::security::approval::APPROVAL_CHAT_CONTEXT
+ .scope(chat_ctx("a"), async { TaskLocalSession.current_session() })
+ .await;
+ assert_eq!(inside.as_deref(), Some("thread-a"));
+
+ // Nested scopes answer with the innermost thread, and the outer one is
+ // restored afterwards.
+ let (inner, outer) = crate::security::approval::APPROVAL_CHAT_CONTEXT
+ .scope(chat_ctx("outer"), async {
+ let inner = crate::security::approval::APPROVAL_CHAT_CONTEXT
+ .scope(chat_ctx("inner"), async {
+ TaskLocalSession.current_session()
+ })
+ .await;
+ (inner, TaskLocalSession.current_session())
+ })
+ .await;
+ assert_eq!(inner.as_deref(), Some("thread-inner"));
+ assert_eq!(outer.as_deref(), Some("thread-outer"));
+}