Skip to content

feat: @x402/mnemopay — economic memory for AI agent payments#1904

Open
t49qnsx7qt-kpanks wants to merge 1 commit intox402-foundation:mainfrom
t49qnsx7qt-kpanks:feat/mnemopay-middleware
Open

feat: @x402/mnemopay — economic memory for AI agent payments#1904
t49qnsx7qt-kpanks wants to merge 1 commit intox402-foundation:mainfrom
t49qnsx7qt-kpanks:feat/mnemopay-middleware

Conversation

@t49qnsx7qt-kpanks
Copy link
Copy Markdown

@t49qnsx7qt-kpanks t49qnsx7qt-kpanks commented Apr 2, 2026

Summary

AI agents using x402 today are stateless — they pay the 402, get the resource, and immediately forget. They never learn which endpoints are cheap, which are reliable, or which alternatives exist. This PR adds @x402/mnemopay, a middleware package that gives x402 agents economic memory via MnemoPay.

What it does

withMnemoPay() wraps any x402-enabled fetch function and adds four memory operations around each payment:

Phase Action MnemoPay API
Before request Recall past experiences with this endpoint recall()
After 402 payment Record the charge amount charge()
On success Settle — reinforce the positive memory settle() → +reputation
On failure Refund — dock the memory refund() → -reputation

Over time, agents build a knowledge base of endpoint costs, reliability rates, and alternatives — turning every payment into a learning event.

Why this matters

The x402 protocol is uniquely positioned for AI-native commerce. But stateless payments leave value on the table. An agent that remembers its payment history can:

  • Detect price anomalies: "This endpoint usually costs $0.02, but today it's $0.10"
  • Track reliability: "This endpoint fails 40% of the time — prefer the alternative"
  • Build reputation: Agents that make consistently good payment decisions earn higher reputation scores
  • Optimize spend: Over hundreds of API calls, memory-driven agents spend less for the same outcomes

Usage

import { wrapFetchWithPayment } from "@x402/fetch";
import { withMnemoPay } from "@x402/mnemopay";
import { MnemoPayLite } from "@mnemopay/sdk";

const payFetch = wrapFetchWithPayment(fetch, client);
const agent = new MnemoPayLite("my-agent", 0.05);
const smartFetch = withMnemoPay(payFetch, { agent });

// Agent now remembers every payment outcome
const response = await smartFetch("https://api.example.com/paid-endpoint");

Package details

  • Located at typescript/packages/http/mnemopay/
  • Follows existing x402 package conventions (tsup, vitest, eslint config)
  • @mnemopay/sdk is a peer dependency — no new runtime deps in x402 core
  • Defines a MnemoPayAgent interface so users can bring their own implementation
  • 14 tests covering success/failure flows, graceful degradation, and edge cases
  • Zero impact on existing packages — purely additive

Test plan

  • Verify withMnemoPay() passes through non-402 responses unchanged
  • Verify recall() is called before each request with the endpoint URL
  • Verify settle() is called on successful payments
  • Verify refund() is called on failed payments
  • Verify memory/recall failures don't break the payment flow (graceful degradation)
  • Verify the package builds with tsup and follows the existing dual CJS/ESM export pattern
  • Verify compatibility with @x402/fetch and @x402/axios wrapped functions

🤖 Generated with Claude Code

Live Demo

Try it now: https://t49qnsx7qt-kpanks.github.io/mnemopay-demo/

The Feedback Loop in 30 Seconds

Round 1: Agent has NO memory. Picks randomly.
  -> Hired Alice $80. Fast but buggy.
  -> Settled. Reputation: 0.51 | Memories: 1

Round 2: Agent tries Bob.
  -> Hired Bob $120. Perfect quality, on time.
  -> Settled. Reputation: 0.52 | Memories: 2

Round 3: Agent tries Carol.
  -> Hired Carol $95. Missed deadline by 3 days.
  -> REFUNDED. Reputation: 0.52 | Memories: 3

=== Agent recalls before Round 4 ===

  1. [score: 0.900] Carol missed deadline — refund (high importance, decaying)
  2. [score: 0.750] Bob: perfect quality, on time (reinforced by settle)
  3. [score: 0.600] Alice: fast but buggy (neutral)

Result: Agent now picks Bob. No LLM needed for this insight.
settle() reinforced the memory. refund() flagged the failure.
This IS the MnemoPay feedback loop.

How it works

Payment succeeds → settle() → memories that led to decision get +0.05 importance
Payment fails    → refund() → agent reputation docked -0.05
                 → high-importance failure memory stored
Over time        → agent consistently picks best value providers

5-line integration

import { MnemoPay } from '@mnemopay/sdk';

const agent = MnemoPay.quick('my-agent');
await agent.remember('Bob delivers perfect code');
const tx = await agent.charge(120, 'landing page');
await agent.settle(tx.id); // memories reinforced, reputation +0.01

AI agents using x402 today are stateless — they pay and forget. This package
layers MnemoPay's economic memory on top of x402 payment flows so agents
remember costs, track endpoint reliability, and build reputation from
real payment outcomes.

- withMnemoPay() wraps any x402-enabled fetch with memory operations
- Before each request: recall() checks past payment experiences
- On success: settle() reinforces the positive memory (+reputation)
- On failure: refund() docks the memory (-reputation)
- recallEndpointInsight() surfaces cost history and success rates
- Full test suite with 14 tests covering all payment flow paths
- Follows existing x402 package structure (tsup, vitest, eslint)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@cb-heimdall
Copy link
Copy Markdown

cb-heimdall commented Apr 2, 2026

🟡 Heimdall Review Status

Requirement Status More Info
Reviews 🟡 0/1
Denominator calculation
Show calculation
1 if user is bot 0
1 if user is external 0
2 if repo is sensitive 0
From .codeflow.yml 1
Additional review requirements
Show calculation
Max 0
0
From CODEOWNERS 0
Global minimum 0
Max 1
1
1 if commit is unverified 1
Sum 2

@vercel
Copy link
Copy Markdown

vercel bot commented Apr 2, 2026

@t49qnsx7qt-kpanks is attempting to deploy a commit to the Coinbase Team on Vercel.

A member of the Team first needs to authorize it.

@github-actions github-actions bot added typescript sdk Changes to core v2 packages labels Apr 2, 2026
@t49qnsx7qt-kpanks
Copy link
Copy Markdown
Author

Hey team! Added a live interactive demo to the PR description: try it here. It shows the feedback loop in action — an agent hiring freelancers, learning from settlements and refunds, and consistently picking the best value by round 7-8. The core idea: settle() reinforces the memories that led to good decisions, refund() flags failures. Over time, the agent develops economic intuition without any LLM reasoning needed. Happy to walk through the implementation or answer any questions!

@postmode
Copy link
Copy Markdown

postmode commented Apr 2, 2026

One pattern we're exploring for agent-to-agent payment contexts: if the payer agent is operating through a managed custody layer (rather than controlling its own signing key), the PAYMENT-SIGNATURE header is technically signed by the custodian infrastructure, not the agent's x402 identity. This creates an attribution gap where the payment is valid on-chain but the agent's reputation history in ERC-8004 doesn't accrue correctly.
Wondering if the facilitator spec has a path for delegated signing authority, or if this is considered an application-layer concern. Would affect how managed wallet providers integrate.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

sdk Changes to core v2 packages typescript

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants