Skip to content

Examples and guides for using the OpenAI API

Add controlled agentic commerce with AgentCore Payments (#2943)

deepakjain108ff5456262f36
diff --git a/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/.env.example b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/.env.example
new file mode 100644
index 00000000..8f66fe31
--- /dev/null
+++ b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/.env.example
@@ -0,0 +1,43 @@
+# AgentCore Payments preview: testnet only. Do not commit real values.
+ALLOW_AGENTCORE_TESTNET=0
+# Enables two read-only calls: instrument state and the exact Base Sepolia
+# USDC balance scope. They cannot create a session, generate a proof, contact
+# a merchant, or transfer value.
+ALLOW_AGENTCORE_READ_ONLY=0
+# Master gate for the notebook-managed create -> combined run -> delete path.
+RUN_AGENTCORE_E2E=0
+# The combined live command also requires both flags below. Keep them off
+# until the exact 0.002-test-USDC run is reviewed immediately before use.
+ALLOW_PAID_INFERENCE=0
+APPROVE_AGENTCORE_TESTNET_PURCHASE=0
+# This separate opt-in permits only bounded session create/delete operations.
+ALLOW_AGENTCORE_SESSION_ADMIN=0
+AGENTCORE_SESSION_FILE=.agentcore-session.env
+# Keep the payment-execution profile separate from the profiles used for model
+# inference and session administration. For a local test, the model and session
+# profiles may refer to the same approved developer identity.
+BEDROCK_AWS_PROFILE=
+AGENTCORE_SESSION_AWS_PROFILE=
+AGENTCORE_RUNTIME_AWS_PROFILE=
+# Keep this separate from AWS_REGION=us-east-2 used by Bedrock Mantle.
+AGENTCORE_AWS_REGION=us-east-1
+PAYMENT_MANAGER_ARN=
+PAYMENT_CONNECTOR_ID=
+PAYMENT_INSTRUMENT_ID=
+PAYMENT_SESSION_ID=
+PAYMENT_USER_ID=
+X402_ALLOWED_MERCHANTS=sandbox.node4all.com
+X402_NETWORK_PREFERENCES=eip155:84532
+# Base Sepolia USDC contract. This is a public asset identifier, not a wallet.
+X402_APPROVED_ASSET=0x036CbD53842c5426634e7929541eC2318f3dCF7e
+# Exact testnet merchant recipient from the reviewed challenge. Keep the real
+# value only in the ignored local .env file; never commit or log it.
+X402_APPROVED_PAY_TO=
+# Reject merchant challenges that delegate payment authority for longer.
+X402_MAX_CHALLENGE_TIMEOUT_SECONDS=300
+# Current sandbox price: 2,000 atomic units = 0.002 test USDC.
+X402_MAX_APPROVED_AMOUNT_ATOMIC=2000
+X402_MAX_PAYMENT_ATTEMPTS=1
+# The reviewed sandbox binds the exact query string into its x402 challenge.
+X402_RESOURCE_URL=https://sandbox.node4all.com/v1/x402-test?host=sandbox.node4all.com
+X402_IDEMPOTENCY_KEY=
diff --git a/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/.gitignore b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/.gitignore
new file mode 100644
index 00000000..910b8c39
--- /dev/null
+++ b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/.gitignore
@@ -0,0 +1,9 @@
+.venv/
+uv.lock
+.pytest_cache/
+__pycache__/
+*.py[cod]
+.env
+.agentcore-session.env
+.agentcore-session.env.lock
+*-Copy*.ipynb
diff --git a/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/README.md b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/README.md
new file mode 100644
index 00000000..1abee5d0
--- /dev/null
+++ b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/README.md
@@ -0,0 +1,241 @@
+# Build an AI agent that can pay for APIs using AgentCore Payments
+
+**Authors:** Deepak Jain and Sid Rampally
+
+An agent researching a supplier may need a paid risk report, a sanctions
+check, or current search results. The application must decide which services
+the agent can use, how much it can spend, and when a person must approve a
+purchase.
+
+This example uses the OpenAI Agents SDK to request a supplier report through
+an `x402_fetch` tool. Application code controls the merchant, business
+purpose, spending limit, approval, receipt, and audit history. Amazon Bedrock
+AgentCore Payments provides the bounded payment session for the connected AWS
+testnet workflow. A local simulation demonstrates the same application
+controls before AWS resources are configured.
+
+The notebook also shows how to run the same application-controlled tool loop
+directly through the Responses API without using the OpenAI Agents SDK for
+orchestration. AgentCore Payments remains the payment provider for the
+connected AWS workflow.
+
+Amazon Bedrock AgentCore Payments is the payment infrastructure for this
+example's connected testnet workflow. Its preview API shape was last checked
+on August 10, 2026 with
+`bedrock-agentcore==1.18.1`. Revalidate the API and supported Regions before a
+live run. This example is not production payment guidance.
+
+On August 10, 2026, revision `6871ce4` completed one separately approved,
+bounded Base Sepolia testnet run. GPT-5.6 Sol completed the one-tool loop,
+AgentCore Payments generated the proof used by the adapter, the allowlisted
+merchant accepted one paid retry with HTTP `200`, the temporary session was
+deleted, and the instrument balance decreased by exactly `0.002` test USDC.
+The validated provider path used AgentCore Payments with a Coinbase CDP
+testnet connector and embedded wallet. Coinbase credentials and wallet setup
+remained outside the notebook and were not displayed or stored by the example.
+This evidence does not independently verify on-chain settlement or finality.
+
+![Controlled agentic-commerce business flow and authority boundaries](../../../../images/partners/AWS/controlled-agentic-commerce-overview.png)
+
+## Architecture
+
+![Local simulation and connected AgentCore Payments testnet architecture](../../../../images/partners/AWS/controlled-agentic-commerce-local-and-testnet.png)
+
+The local simulation uses synthetic payment proof. The connected AWS workflow
+runs from the notebook and calls Amazon Bedrock plus AgentCore Payments.
+AgentCore Runtime is not used by this example; it remains a possible future
+deployment option outside the current validation boundary.
+
+## How x402 works
+
+An x402 merchant first returns `402 Payment Required` with machine-readable
+payment requirements. The application treats that challenge as a proposal,
+validates it against approved policy, obtains one bounded payment proof, and
+retries the request with a stable idempotency key.
+
+The reviewed sandbox challenge also includes the official x402 `bazaar`
+discovery extension. The adapter accepts only its expected `info` and `schema`
+objects, rejects unknown or malformed extensions, and never forwards discovery
+metadata as payment authority.
+
+The live adapter binds the exact resource, recipient, timeout or expiry,
+asset, network, and amount before constructing provider input. Each request
+also resolves and pins a validated public merchant address while preserving
+TLS hostname verification. The economic tool consumes a one-shot application
+capability before network or payment side effects. Proxy-based merchant
+networking is not supported because it would break this DNS-to-connection
+binding. The live readiness check fails closed when `HTTP_PROXY`,
+`HTTPS_PROXY`, or `ALL_PROXY` variants are set. Use only a security-approved
+direct network environment; do not bypass a required corporate proxy.
+
+![Sequence for a controlled x402 paid request](../../../../images/partners/AWS/controlled-agentic-commerce-x402-sequence.png)
+
+## Control boundaries
+
+| Layer | Owns | Does not own |
+|---|---|---|
+| Model and Agents SDK | Tool selection and typed proposal | Approval, budget, wallet access, or settlement truth |
+| Application | Merchant and purpose policy, approval, challenge validation, idempotency, receipts, and audit | Signing credentials |
+| AgentCore Payments | Payment-header generation inside a bounded session | Business authorization |
+| Testnet wallet provider | Delegated testnet signing | Model reasoning or approval policy |
+
+## Run the local notebook
+
+```bash
+cd /path/to/openai-cookbook
+unset VIRTUAL_ENV
+uv run \
+ --project examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments \
+ --group dev --with jupyter \
+ jupyter lab --port=8899 \
+ --ServerApp.root_dir="$PWD" \
+ --ServerApp.default_url="/lab/tree/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/controlled_agentic_commerce.ipynb"
+```
+
+Stop any older Jupyter server before running this command. Start Jupyter from
+the repository root as shown. The notebook diagrams live
+under the repository-level `images/` directory, which a server started inside
+the nested example directory cannot serve. A standalone notebook copied to
+another directory also will not contain those image files.
+
+Run all notebook cells in order. By default, the observable result is one synthetic
+`402 -> proof -> 200` exchange, one typed agent proposal, an ordered audit
+trail, a rejected fabricated proposal, and a skipped live section. No live
+service call is enabled by default.
+
+## Run the tests
+
+From the repository root, change into the example directory first:
+
+```bash
+cd examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments
+uv run --group dev pytest -q
+uv run --group dev ruff check src tests
+uv run --group dev ruff format --check src tests
+```
+
+The expected result is that all tests pass and Ruff reports no selected errors.
+
+The negative suite covers missing or mismatched approval, disallowed
+merchants, HTTP destinations, expired sessions and challenges, budget limits,
+idempotency conflicts, malformed challenges, fabricated agent output, private
+or changed DNS answers, unapproved recipients and timeouts, mainnet
+configuration, unsanitized failures, and cleanup.
+
+## End-to-end AgentCore testnet path
+
+Keep every live gate disabled until the merchant, amount, network, asset,
+wallet provider, payment instrument, and short-lived session are reviewed.
+Never put provider credentials, wallet secrets, payment proofs, session IDs,
+or account identifiers in the notebook or repository. The notebook reads
+configuration only from its process environment and never displays configured
+values.
+
+The public notebook does not collect payment-provider or wallet credentials.
+Complete the one-time credential-provider, connector, payment-manager,
+instrument, testnet-funding, and signing-permission steps outside Jupyter by
+using the current AgentCore console, CLI, or SDK. The executable notebook path
+starts from those approved resources and covers their read-only verification,
+the bounded session lifecycle, model inference, payment proof, merchant retry,
+evidence checks, and cleanup.
+
+The offline notebook path imports and runs on Windows. The optional live
+session-administration path requires POSIX file locking and must be run from
+macOS or Linux.
+
+1. Configure a supported testnet wallet connector outside the notebook, then
+ create and fund one dedicated Base Sepolia instrument for a synthetic user.
+ Enable the provider's project-level delegated-signing setting and complete
+ the separate per-wallet grant for the exact wallet linked to the instrument.
+ Confirm the grant is active and has not expired; selecting or granting a
+ different wallet is not sufficient.
+2. Configure AWS profiles for the three responsibilities:
+ `BEDROCK_AWS_PROFILE` invokes the model,
+ `AGENTCORE_SESSION_AWS_PROFILE` creates and deletes bounded sessions, and
+ `AGENTCORE_RUNTIME_AWS_PROFILE` processes payments. The model and session
+ profiles may use the same approved developer identity for this local test,
+ but the payment-execution profile must be separate.
+3. Copy `.env.example` to an ignored local configuration source and supply the
+ reviewed resource, merchant recipient, connector, instrument, user,
+ manager, asset, challenge timeout, and idempotency values.
+ Keep `PAYMENT_SESSION_ID` empty; the managed runner injects it privately.
+ Install the live-only SDK with
+ `uv sync --extra agentcore --group dev`.
+4. Set only `ALLOW_AGENTCORE_READ_ONLY=1` and run
+ `agentic-commerce-agentcore-infrastructure`. Confirm that the instrument is
+ `ACTIVE`, its wallet network is `ETHEREUM`, and the balance query reports
+ `BASE_SEPOLIA` and `USDC`. Then return this gate to `0`. These two read-only
+ AWS calls do not report the balance amount and cannot create a session,
+ generate a proof, contact a merchant, or transfer value.
+5. Run the shipped deterministic insufficient-budget check:
+ `uv run --group dev pytest -q tests/test_agentcore_payments.py -k insufficient_session_budget`.
+ It must pass without AWS, merchant, wallet, or payment calls. This example
+ does not ship a separate live below-price runner.
+6. Enable all five transaction gates only for one reviewed run:
+ `RUN_AGENTCORE_E2E`, `ALLOW_AGENTCORE_SESSION_ADMIN`,
+ `ALLOW_PAID_INFERENCE`, `ALLOW_AGENTCORE_TESTNET`, and
+ `APPROVE_AGENTCORE_TESTNET_PURCHASE`.
+7. Run the managed notebook cell. It creates a 15-minute session capped at the
+ approved request amount, runs one combined Agents SDK -> AgentCore Payments
+ -> x402 merchant request, and deletes the session in `finally`.
+8. Confirm `result=PASSED`, `model_run_completed=true`,
+ `agentcore_payment_path_completed=true`,
+ `merchant_paid_retry_completed=true`, `status_code=200`,
+ `payment_attempts=1`, and `session_cleanup=DELETED`.
+9. Disable the read-only gate and all five transaction gates.
+10. Verify settlement separately before using settlement language. The
+ sanitized application report intentionally returns
+ `settlement_verified=false`.
+
+### Optional live validation
+
+The connected testnet path is intentionally disabled by default. A live run requires a fresh human approval, reviewed testnet configuration, all documented safety gates, and a bounded AgentCore payment session.
+
+Use the gated workflow in the notebook to perform readiness checks before any live action. Do not enable the live path as part of the default Cookbook run.
+
+The readiness check itself must not create a payment session, invoke the model, contact the merchant, generate payment proof, or transfer testnet value.
+
+Before a live smoke test, configure
+[AgentCore Payments log delivery](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/payments-observability.html)
+to a short-retention CloudWatch log group. If `ProcessPayment` fails, the CLI
+report includes only a sanitized stage, category, AWS error code, and HTTP
+status when available. It never prints provider messages, request IDs, payment
+identifiers, wallet data, or proof headers. Use the corresponding CloudWatch
+event for detailed diagnosis, and do not rerun until the failure is understood.
+If the log delivery exists only for this validation, delete the delivery,
+destination, source, and log group after the review.
+
+If cleanup reports `FAILED`, do not rerun the purchase. Use the distinct
+session-administration role to delete the recorded session first:
+
+```bash
+uv run --extra agentcore agentic-commerce-agentcore-session delete
+```
+
+The application reuses one stable idempotency token across payment retries.
+AgentCore session limits provide a second enforcement layer; they do not
+replace application authorization.
+
+The live success report proves that the model completed the one-tool loop,
+AgentCore completed the payment path used by the adapter, and the allowlisted
+merchant returned a successful paid response. It does not independently prove
+on-chain settlement; that requires separate AgentCore, merchant, or testnet
+evidence.
+
+The recorded August 10, 2026 validation returned `PASSED` for one bounded
+`0.002` test-USDC attempt. Any future live run requires a fresh review, approval,
+short-lived session, and testnet-only configuration.
+
+AWS documents the [x402 payment flow](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/payments-how-it-works.html)
+and recommends [separate IAM roles for session administration and payment execution](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/payments-iam-roles.html).
+Also review the current AWS guidance for
+[prerequisites](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/payments-prerequisites.html),
+[payment instruments](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/payments-create-instrument.html),
+and [bounded sessions](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/payments-create-session.html).
+
+## Source and credit
+
+Nick's AWS [paid-research sample](https://github.com/awslabs/agentcore-samples/pull/1869)
+provides a broader multi-agent live testnet reference. Its wallet-neutral setup
+and bounded-session exercise informed this example. No source code was copied.
+See `SOURCE_ATTRIBUTION.md` for the fixed revision and license.
diff --git a/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/SOURCE_ATTRIBUTION.md b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/SOURCE_ATTRIBUTION.md
new file mode 100644
index 00000000..5a0b1f79
--- /dev/null
+++ b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/SOURCE_ATTRIBUTION.md
@@ -0,0 +1,21 @@
+# Source attribution
+
+## AWS paid-research companion sample
+
+- Contributor: Nick (`mccartnick`), AWS Solutions Architect
+- Pull request: [AWS AgentCore paid-research sample PR #1869](https://github.com/awslabs/agentcore-samples/pull/1869)
+- Reviewed revision: `85aa4e5ca9a2d55ad7c412f2d015011095b2222d`
+- Review date: August 5, 2026
+- License: Apache-2.0
+
+The companion sample reports a live multi-agent testnet run using a
+Bedrock-hosted OpenAI model, AgentCore Payments, delegated wallet signing, an
+x402 V2 challenge, and a paid retry that returned HTTP 200. That is evidence
+for the AWS sample at the reviewed revision, not for this example's optional
+live path.
+
+The provider-neutral setup language and below-price session exercise informed
+this example. No source code from the AWS sample is copied. This example
+independently implements a narrower one-agent, one-tool pattern with
+application-owned authorization, challenge validation, idempotency, receipts,
+audit evidence, and deterministic local tests.
diff --git a/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/controlled_agentic_commerce.ipynb b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/controlled_agentic_commerce.ipynb
new file mode 100644
index 00000000..9866f71f
--- /dev/null
+++ b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/controlled_agentic_commerce.ipynb
@@ -0,0 +1,786 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "id": "overview",
+ "metadata": {},
+ "source": [
+ "# Build an AI agent that can pay for APIs using AgentCore Payments\n",
+ "\n",
+ "**Authors:** Deepak Jain and Sid Rampally\n",
+ "\n",
+ "AI agents often need information from external services to complete a task. A procurement agent might check a supplier against a sanctions database, retrieve a current risk report, or use a paid search API. When those services charge for each request, the application needs clear rules for which purchases the agent can request and who approves the spending.\n",
+ "\n",
+ "Agentic commerce describes workflows in which an agent can request a paid resource while application code retains authority over payment. Amazon Bedrock AgentCore Payments provides infrastructure for bounded payment sessions, and the OpenAI Agents SDK lets a model request an application-defined tool. The application checks the merchant, purpose, amount, and approval before a payment can occur.\n",
+ "\n",
+ "This notebook explains that workflow through a supplier research example. It covers the AgentCore Payments flow, the x402 payment exchange, application-owned spending controls, and receipt verification. The same payment controls are first illustrated with a local simulation and then connected to AgentCore Payments on the AWS testnet.\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "business-scenario",
+ "metadata": {},
+ "source": [
+ "## Why agents need access to paid services\n",
+ "\n",
+ "Consider a procurement agent reviewing a fictional supplier named Northstar Components. The agent has basic supplier information, but it needs a current risk report from a paid API before it can summarize potential concerns for a human reviewer.\n",
+ "\n",
+ "The application approves that data provider, defines a supplier research purpose, and sets a maximum price for the report. It also records the human approval associated with the request. When the model decides that the report is useful, it requests the `x402_fetch` tool with the supplier report URL and the approved purpose.\n",
+ "\n",
+ "The merchant returns an HTTP `402 Payment Required` challenge describing its payment terms. The application checks those terms against the approved merchant, amount, network, expiry, and budget. If the request passes, the application obtains a bounded payment proof, retrieves the report, and records a receipt and audit history. The agent then prepares its answer from the report and receipt evidence returned by the tool.\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "authority-boundaries",
+ "metadata": {},
+ "source": [
+ "## Architecture and payment authority\n",
+ "\n",
+ "The system separates four responsibilities:\n",
+ "\n",
+ "1. **The AI agent** identifies when a paid service could help complete the user's request and calls the application-defined tool.\n",
+ "2. **The application** checks the merchant, purchase purpose, amount, approval, and spending limit before recording the receipt and audit history.\n",
+ "3. **AgentCore Payments** generates a payment proof within the limits of an approved payment session.\n",
+ "4. **The paid API** checks the payment proof and returns the requested content.\n",
+ "\n",
+ "The local example simulates the AgentCore Payments step. The connected AWS workflow uses AgentCore Payments to generate the bounded proof.\n",
+ "\n",
+ "The application is the boundary between the model and the payment infrastructure. The model receives the resource URL and research purpose, while approval records, spending limits, payment credentials, and audit state remain outside its control.\n",
+ "\n",
+ "![An agent requests a paid supplier report through application controls and AgentCore Payments](../../../../images/partners/AWS/controlled-agentic-commerce-overview.png)\n",
+ "\n",
+ "*The application controls approval and spending, while AgentCore Payments provides a bounded payment session for the connected AWS workflow.*\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "prerequisites",
+ "metadata": {},
+ "source": [
+ "## 1. Setting up the supplier research example\n",
+ "\n",
+ "The example requires Python 3.11 through 3.13 and `uv`. Follow the repository-root Jupyter command in `README.md` so the notebook can load its package and display the architecture diagrams.\n",
+ "\n",
+ "The first part uses a scripted model, a simulated merchant, and a synthetic payment proof. This setup lets you inspect the same request, approval, receipt, and audit sequence without configuring AWS credentials or transferring funds. The final section shows where a real Amazon Bedrock model and AgentCore Payments testnet resources enter the workflow.\n",
+ "\n",
+ "The following cell locates the example package and makes its application, merchant, and policy modules available to the notebook.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "find-root",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import sys\n",
+ "from pathlib import Path\n",
+ "\n",
+ "cwd = Path.cwd().resolve()\n",
+ "candidates = [\n",
+ " cwd,\n",
+ " cwd / \"examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments\",\n",
+ " *cwd.parents,\n",
+ "]\n",
+ "ROOT = next(\n",
+ " (path for path in candidates if (path / \"src/agentic_commerce\").is_dir()),\n",
+ " None,\n",
+ ")\n",
+ "if ROOT is None:\n",
+ " raise FileNotFoundError(\"Run this notebook from its example directory.\")\n",
+ "sys.path.insert(0, str(ROOT / \"src\"))\n",
+ "\n",
+ "print(f\"Example root: {ROOT}\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "policy-intro",
+ "metadata": {},
+ "source": [
+ "## 2. Defining supplier requests and spending limits\n",
+ "\n",
+ "The application needs to establish its payment rules before the model can request a tool. In this example, the supplier report costs 0.25 synthetic USDC. The application also defines the approved merchant, the permitted research purpose, a maximum amount for this purchase, and the total budget available to the agent run.\n",
+ "\n",
+ "`ApprovalGrant` ties the purchase to a particular request ID and resource URL. Its expiry limits how long that authorization remains valid. The model never supplies or changes these values; they are provided by application code when the tool is created.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "build-policy",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from datetime import UTC, datetime, timedelta\n",
+ "from decimal import Decimal\n",
+ "\n",
+ "from agentic_commerce.demo import build_demo\n",
+ "from agentic_commerce.merchant import RESOURCE_URL\n",
+ "from agentic_commerce.models import ApprovalGrant\n",
+ "\n",
+ "now = datetime.now(UTC)\n",
+ "application, merchant, local_payments = build_demo(now)\n",
+ "approval = ApprovalGrant(\n",
+ " approval_id=\"approval-cookbook-001\",\n",
+ " request_id=\"request-cookbook-001\",\n",
+ " resource_url=RESOURCE_URL,\n",
+ " purpose=\"supplier_due_diligence\",\n",
+ " maximum_amount=Decimal(\"0.25\"),\n",
+ " approved_by=\"synthetic-cookbook-reviewer\",\n",
+ " approved_at=now,\n",
+ " expires_at=now + timedelta(minutes=10),\n",
+ ")\n",
+ "\n",
+ "{\n",
+ " \"approved_merchant\": str(RESOURCE_URL),\n",
+ " \"purpose\": approval.purpose,\n",
+ " \"approved_amount\": str(approval.maximum_amount),\n",
+ " \"run_budget\": str(application.policy.policy.per_run_limit),\n",
+ " \"currency\": approval.currency,\n",
+ " \"approval_expires_at\": approval.expires_at.isoformat(),\n",
+ "}"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "runner-intro",
+ "metadata": {},
+ "source": [
+ "## 3. Defining an agent tool for approved purchases\n",
+ "\n",
+ "The `x402_fetch` function is the only payment-related tool available to the agent. The model can provide a resource URL and a business purpose, but the application supplies the request ID, idempotency key, spending policy, and approval grant.\n",
+ "\n",
+ "Before starting a purchase, the tool consumes a one-use capability. That check prevents a model from issuing multiple economic requests during the same agent run. `application.purchase` then validates the merchant and payment challenge before producing a receipt.\n",
+ "\n",
+ "`AgentPurchaseEvidence` returns only the report and receipt fields the model needs to prepare its answer. Wallet material, payment proof headers, and the complete application audit trail are kept out of the model context.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "define-agent-tool",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from threading import Lock\n",
+ "\n",
+ "from agents import Agent, ModelSettings, function_tool\n",
+ "from openai.types.shared import Reasoning\n",
+ "\n",
+ "from agentic_commerce.agent import PurchaseResultRecorder, SupplierResearchOutput\n",
+ "from agentic_commerce.errors import AgentResultInvalid\n",
+ "from agentic_commerce.learning_model import ScriptedCommerceLearningModel\n",
+ "from agentic_commerce.models import AgentPurchaseEvidence, PurchaseRequest\n",
+ "\n",
+ "recorder = PurchaseResultRecorder()\n",
+ "model = ScriptedCommerceLearningModel()\n",
+ "tool_capability = {\"used\": False}\n",
+ "tool_lock = Lock()\n",
+ "\n",
+ "\n",
+ "@function_tool\n",
+ "def x402_fetch(resource_url: str, purpose: str) -> str:\n",
+ " \"\"\"Fetch one paid resource using application-owned approval.\"\"\"\n",
+ "\n",
+ " with tool_lock:\n",
+ " if tool_capability[\"used\"]:\n",
+ " raise AgentResultInvalid(\n",
+ " \"access_count_invalid\",\n",
+ " \"The economic tool permits exactly one invocation.\",\n",
+ " )\n",
+ " tool_capability[\"used\"] = True\n",
+ "\n",
+ " purchase = application.purchase(\n",
+ " PurchaseRequest(\n",
+ " request_id=\"request-cookbook-001\",\n",
+ " resource_url=resource_url,\n",
+ " purpose=purpose,\n",
+ " idempotency_key=\"purchase-cookbook-001\",\n",
+ " ),\n",
+ " approval=approval,\n",
+ " )\n",
+ " recorder.record(purchase)\n",
+ " return AgentPurchaseEvidence(\n",
+ " status=purchase.status,\n",
+ " report=purchase.report,\n",
+ " receipt_id=purchase.receipt.receipt_id,\n",
+ " amount=purchase.receipt.amount,\n",
+ " currency=purchase.receipt.currency,\n",
+ " requires_human_approval=purchase.authorization.requires_human_approval,\n",
+ " ).model_dump_json()\n",
+ "\n",
+ "\n",
+ "agent = Agent(\n",
+ " name=\"Supplier research agent\",\n",
+ " model=model,\n",
+ " model_settings=ModelSettings(reasoning=Reasoning(effort=\"low\"), store=False),\n",
+ " output_type=SupplierResearchOutput,\n",
+ " tools=[x402_fetch],\n",
+ " instructions=(\n",
+ " \"Call x402_fetch exactly once for the approved supplier report. \"\n",
+ " \"Return only the typed summary supported by its receipt.\"\n",
+ " ),\n",
+ ")\n",
+ "\n",
+ "{\"agent\": agent.name, \"tools\": [tool.name for tool in agent.tools]}"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "x402-sequence",
+ "metadata": {},
+ "source": [
+ "## 4. Running the x402 payment workflow\n",
+ "\n",
+ "x402 uses the HTTP `402 Payment Required` response to communicate the terms of a paid request. When the application first requests the supplier report, the merchant returns a challenge with the amount, asset, network, recipient, and expiry.\n",
+ "\n",
+ "The application checks those terms against its approved policy. If the merchant, price, request purpose, and human approval are valid, AgentCore Payments creates one bounded proof in the connected AWS workflow. The local example uses a synthetic proof to demonstrate the same sequence. The application retries the request with the proof, and the merchant returns the supplier report with HTTP `200`.\n",
+ "\n",
+ "![The x402 request sequence between the agent, application, merchant, and AgentCore Payments](../../../../images/partners/AWS/controlled-agentic-commerce-x402-sequence.png)\n",
+ "\n",
+ "*The merchant's 402 response supplies payment terms. Application approval occurs before a payment proof is requested.*\n",
+ "\n",
+ "`Runner.run` executes the Agents SDK loop. The scripted model requests `x402_fetch` on its first turn and prepares a typed supplier summary after the tool returns. The application checks that summary against the purchase it actually recorded.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "run-agent",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from agents import RunConfig, Runner\n",
+ "\n",
+ "from agentic_commerce.agent import (\n",
+ " DEFAULT_PROMPT,\n",
+ " SupplierResearchRun,\n",
+ " validate_supplier_research_output,\n",
+ ")\n",
+ "\n",
+ "result = await Runner.run(\n",
+ " agent,\n",
+ " DEFAULT_PROMPT,\n",
+ " max_turns=4,\n",
+ " run_config=RunConfig(\n",
+ " tracing_disabled=True,\n",
+ " workflow_name=\"Synthetic Agentic Commerce\",\n",
+ " ),\n",
+ ")\n",
+ "purchase = validate_supplier_research_output(result.final_output, recorder)\n",
+ "run = SupplierResearchRun(output=result.final_output, purchase=purchase)\n",
+ "\n",
+ "{\n",
+ " \"model_turns\": model.model_turns,\n",
+ " \"tool_calls\": model.requested_tools,\n",
+ " \"merchant_requests\": merchant.request_count,\n",
+ " \"synthetic_charges\": local_payments.charge_count,\n",
+ " \"model_inference_calls\": 0,\n",
+ " \"aws_calls\": 0,\n",
+ " \"value_transferred\": False,\n",
+ "}"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "responses-api-intro",
+ "metadata": {},
+ "source": [
+ "### Using the Responses API directly\n",
+ "\n",
+ "The OpenAI Agents SDK coordinates the tool loop in the previous example, but the payment workflow does not require that orchestration layer. The Responses API can expose `x402_fetch` as a function, return the model's proposed arguments, and accept a `function_call_output` after the application handles the purchase.\n",
+ "\n",
+ "The application still checks the merchant, purpose, approval, and spending limit before making a payment. AgentCore Payments remains responsible for generating the bounded proof in the connected AWS workflow. The example below uses the same simulated merchant and payment processor as the local walkthrough.\n",
+ "\n",
+ "This alternative calls a real Bedrock-hosted GPT-5.6 Sol model, so it runs only when `ALLOW_PAID_INFERENCE=1` and valid AWS credentials are configured. It does not enable a live payment or transfer funds.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "run-responses-api",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import json\n",
+ "import os\n",
+ "\n",
+ "from openai import OpenAI\n",
+ "from openai.providers import bedrock\n",
+ "\n",
+ "responses_tool = {\n",
+ " \"type\": \"function\",\n",
+ " \"name\": \"x402_fetch\",\n",
+ " \"description\": \"Fetch one approved supplier report.\",\n",
+ " \"parameters\": {\n",
+ " \"type\": \"object\",\n",
+ " \"properties\": {\n",
+ " \"resource_url\": {\"type\": \"string\"},\n",
+ " \"purpose\": {\"type\": \"string\"},\n",
+ " },\n",
+ " \"required\": [\"resource_url\", \"purpose\"],\n",
+ " \"additionalProperties\": False,\n",
+ " },\n",
+ " \"strict\": True,\n",
+ "}\n",
+ "responses_result = {\n",
+ " \"result\": \"SKIPPED\",\n",
+ " \"reason\": \"Set ALLOW_PAID_INFERENCE=1 to call the Bedrock model.\",\n",
+ " \"model_calls\": 0,\n",
+ " \"live_payment_calls\": 0,\n",
+ "}\n",
+ "\n",
+ "if os.environ.get(\"ALLOW_PAID_INFERENCE\") == \"1\":\n",
+ " responses_client = OpenAI(\n",
+ " provider=bedrock(\n",
+ " region=os.environ.get(\"AWS_REGION\", \"us-east-2\"),\n",
+ " profile=os.environ.get(\"BEDROCK_AWS_PROFILE\") or None,\n",
+ " api_key=None,\n",
+ " )\n",
+ " )\n",
+ " prompt = (\n",
+ " f\"Call x402_fetch for {RESOURCE_URL} with purpose \"\n",
+ " \"supplier_due_diligence. After the tool returns, provide JSON \"\n",
+ " \"containing supplier, receipt_id, amount, and currency.\"\n",
+ " )\n",
+ " first_response = responses_client.responses.create(\n",
+ " model=\"openai.gpt-5.6-sol\",\n",
+ " input=prompt,\n",
+ " tools=[responses_tool],\n",
+ " tool_choice={\"type\": \"function\", \"name\": \"x402_fetch\"},\n",
+ " parallel_tool_calls=False,\n",
+ " reasoning={\"effort\": \"low\"},\n",
+ " max_output_tokens=128,\n",
+ " store=False,\n",
+ " )\n",
+ " requested_tools = [\n",
+ " item for item in first_response.output if item.type == \"function_call\"\n",
+ " ]\n",
+ " if len(requested_tools) != 1 or requested_tools[0].name != \"x402_fetch\":\n",
+ " raise AgentResultInvalid(\n",
+ " \"access_count_invalid\", \"Expected exactly one x402_fetch request.\"\n",
+ " )\n",
+ "\n",
+ " arguments = json.loads(requested_tools[0].arguments)\n",
+ " responses_now = datetime.now(UTC)\n",
+ " responses_application, responses_merchant, responses_payments = build_demo(\n",
+ " responses_now\n",
+ " )\n",
+ " responses_request_id = \"request-responses-cookbook-001\"\n",
+ " responses_approval = approval.model_copy(\n",
+ " update={\n",
+ " \"approval_id\": \"approval-responses-cookbook-001\",\n",
+ " \"request_id\": responses_request_id,\n",
+ " \"approved_at\": responses_now,\n",
+ " \"expires_at\": responses_now + timedelta(minutes=10),\n",
+ " }\n",
+ " )\n",
+ " responses_purchase = responses_application.purchase(\n",
+ " PurchaseRequest(\n",
+ " request_id=responses_request_id,\n",
+ " resource_url=arguments[\"resource_url\"],\n",
+ " purpose=arguments[\"purpose\"],\n",
+ " idempotency_key=\"purchase-responses-cookbook-001\",\n",
+ " ),\n",
+ " approval=responses_approval,\n",
+ " )\n",
+ " responses_evidence = AgentPurchaseEvidence(\n",
+ " status=responses_purchase.status,\n",
+ " report=responses_purchase.report,\n",
+ " receipt_id=responses_purchase.receipt.receipt_id,\n",
+ " amount=responses_purchase.receipt.amount,\n",
+ " currency=responses_purchase.receipt.currency,\n",
+ " requires_human_approval=(\n",
+ " responses_purchase.authorization.requires_human_approval\n",
+ " ),\n",
+ " )\n",
+ " response_input = [\n",
+ " {\"role\": \"user\", \"content\": prompt},\n",
+ " *(\n",
+ " item.model_dump(mode=\"json\", exclude_none=True)\n",
+ " for item in first_response.output\n",
+ " ),\n",
+ " {\n",
+ " \"type\": \"function_call_output\",\n",
+ " \"call_id\": requested_tools[0].call_id,\n",
+ " \"output\": responses_evidence.model_dump_json(),\n",
+ " },\n",
+ " ]\n",
+ " final_response = responses_client.responses.create(\n",
+ " model=\"openai.gpt-5.6-sol\",\n",
+ " input=response_input,\n",
+ " tools=[responses_tool],\n",
+ " tool_choice=\"none\",\n",
+ " parallel_tool_calls=False,\n",
+ " reasoning={\"effort\": \"low\"},\n",
+ " max_output_tokens=256,\n",
+ " store=False,\n",
+ " )\n",
+ " final_output = json.loads(final_response.output_text)\n",
+ " expected_output = {\n",
+ " \"supplier\": responses_purchase.report.supplier,\n",
+ " \"receipt_id\": responses_purchase.receipt.receipt_id,\n",
+ " \"amount\": str(responses_purchase.receipt.amount),\n",
+ " \"currency\": responses_purchase.receipt.currency,\n",
+ " }\n",
+ " if any(final_output.get(key) != value for key, value in expected_output.items()):\n",
+ " raise AgentResultInvalid(\n",
+ " \"agent_output_mismatch\", \"The model response did not match its receipt.\"\n",
+ " )\n",
+ " responses_result = {\n",
+ " \"result\": \"PASSED\",\n",
+ " \"responses_api_calls\": 2,\n",
+ " \"tool_calls\": [requested_tools[0].name],\n",
+ " \"merchant_requests\": responses_merchant.request_count,\n",
+ " \"synthetic_charges\": responses_payments.charge_count,\n",
+ " \"receipt_verified\": True,\n",
+ " \"live_payment_calls\": 0,\n",
+ " \"value_transferred\": False,\n",
+ " }\n",
+ "\n",
+ "responses_result"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "inspect-intro",
+ "metadata": {},
+ "source": [
+ "## 5. Verifying the supplier report, receipt, and audit history\n",
+ "\n",
+ "The model returns a structured supplier summary, but a valid schema only establishes that the response has the expected shape. The application still needs to check whether the reported receipt, amount, currency, and supplier details match the completed tool request.\n",
+ "\n",
+ "The first cell compares the agent's proposed result with the application-owned receipt. The second cell shows the audit sequence from the initial resource request through authorization, payment proof creation, the merchant retry, and returned content.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "inspect-output",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "proposal = run.output.model_dump(mode=\"json\")\n",
+ "receipt = run.purchase.receipt.model_dump(mode=\"json\")\n",
+ "\n",
+ "{\n",
+ " \"typed_agent_proposal\": proposal,\n",
+ " \"application_receipt\": {\n",
+ " \"receipt_id\": receipt[\"receipt_id\"],\n",
+ " \"amount\": receipt[\"amount\"],\n",
+ " \"currency\": receipt[\"currency\"],\n",
+ " \"network\": receipt[\"network\"],\n",
+ " \"reused\": receipt[\"reused\"],\n",
+ " },\n",
+ "}"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "inspect-audit",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "[\n",
+ " {\n",
+ " \"sequence\": event.sequence,\n",
+ " \"event_type\": event.event_type.value,\n",
+ " }\n",
+ " for event in run.purchase.audit_events\n",
+ "]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "negative-intro",
+ "metadata": {},
+ "source": [
+ "## 6. Checking rejected purchases and fabricated receipts\n",
+ "\n",
+ "A useful payment example should show what happens when its controls reject a request. The first check submits another supplier report request without the required human approval. The application can inspect the merchant's challenge, but it must reject the purchase before creating another payment proof or charge.\n",
+ "\n",
+ "The existing synthetic charge count should remain unchanged after the request is denied.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "deny-unapproved-purchase",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from agentic_commerce.errors import PolicyDenied\n",
+ "\n",
+ "blocked_request = PurchaseRequest(\n",
+ " request_id=\"request-cookbook-002\",\n",
+ " resource_url=RESOURCE_URL,\n",
+ " purpose=\"supplier_due_diligence\",\n",
+ " idempotency_key=\"purchase-cookbook-002\",\n",
+ ")\n",
+ "\n",
+ "try:\n",
+ " application.purchase(blocked_request, approval=None)\n",
+ "except PolicyDenied as exc:\n",
+ " blocked_result = {\n",
+ " \"status\": \"DENIED\",\n",
+ " \"reason\": exc.code,\n",
+ " \"synthetic_charges\": local_payments.charge_count,\n",
+ " }\n",
+ "else:\n",
+ " raise AssertionError(\"Unapproved purchase unexpectedly succeeded\")\n",
+ "\n",
+ "blocked_result"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "fabricated-receipt-intro",
+ "metadata": {},
+ "source": [
+ "The second check changes the receipt identifier in an otherwise valid supplier summary. The output validator compares that response with the purchase observed by the application and rejects the mismatch.\n",
+ "\n",
+ "These two checks cover separate boundaries: authorization before payment and evidence verification after the model responds.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "negative-test",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from agentic_commerce.agent import (\n",
+ " PurchaseResultRecorder,\n",
+ " validate_supplier_research_output,\n",
+ ")\n",
+ "\n",
+ "fabricated = run.output.model_copy(update={\"receipt_id\": \"receipt-fabricated\"})\n",
+ "try:\n",
+ " validate_supplier_research_output(\n",
+ " fabricated,\n",
+ " PurchaseResultRecorder(results=[run.purchase]),\n",
+ " )\n",
+ "except AgentResultInvalid as exc:\n",
+ " negative_result = {\"status\": \"REJECTED\", \"code\": exc.code}\n",
+ "else:\n",
+ " raise AssertionError(\"Fabricated output unexpectedly passed validation\")\n",
+ "\n",
+ "negative_result"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "agentcore-option",
+ "metadata": {},
+ "source": [
+ "## 7. Connecting AgentCore Payments to the AWS testnet\n",
+ "\n",
+ "The connected supplier research workflow uses a Bedrock-hosted OpenAI model, AgentCore Payments, and an approved x402 merchant on Base Sepolia. The application keeps the same merchant policy, spending approval, request identity, and receipt checks demonstrated in the local simulation. AgentCore Payments creates a short-lived session with its own maximum spending limit.\n",
+ "\n",
+ "![Local supplier research and an AWS testnet request share the same application approval and spending controls](../../../../images/partners/AWS/controlled-agentic-commerce-local-and-testnet.png)\n",
+ "\n",
+ "*The local simulation and AWS testnet workflow share the same application controls. AgentCore Payments provides bounded payment sessions in the connected environment.*\n",
+ "\n",
+ "Before enabling the AWS path, an operator provisions the payment manager, connector, instrument, and exact-wallet signing permission outside the notebook. Model inference, session administration, and payment execution use separate responsibilities. `README.md` describes the setup, supported configuration, below-budget denial check, and cleanup procedure.\n",
+ "\n",
+ "AgentCore Runtime is not used by this notebook. The notebook process remains the application runtime, and all live payment gates are disabled unless an operator explicitly enables them.\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "aws-no-call-check",
+ "metadata": {},
+ "source": [
+ "### Checking testnet readiness before network calls\n",
+ "\n",
+ "The readiness check inspects local configuration without contacting AWS, the model, the merchant, or the wallet. It confirms that the required payment opt-ins are present, AWS roles are separated, the session budget is finite, and no payment session is recorded in the local state file.\n",
+ "\n",
+ "The check also rejects proxy settings that are incompatible with the merchant connection's DNS and TLS protections. With the default configuration, the expected result is `NOT_READY` because live payment gates are disabled.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "agentcore-readiness",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from agentic_commerce.agentcore_e2e import (\n",
+ " readiness_report,\n",
+ " run_managed_e2e,\n",
+ ")\n",
+ "\n",
+ "agentcore_readiness = readiness_report()\n",
+ "agentcore_readiness"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "aws-read-only-intro",
+ "metadata": {},
+ "source": [
+ "### Inspecting the payment instrument and network\n",
+ "\n",
+ "When `ALLOW_AGENTCORE_READ_ONLY=1` is explicitly enabled, the application can inspect the configured payment instrument without creating a payment session. The instrument must be `ACTIVE`, use the `ETHEREUM` wallet network, and report the exact `BASE_SEPOLIA` and `USDC` balance scope.\n",
+ "\n",
+ "A missing gate returns `SKIPPED`. A network or asset mismatch returns `NOT_READY`. These checks do not expose a balance amount, generate a payment proof, contact the merchant, or transfer value.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "aws-read-only-check",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from agentic_commerce.agentcore_infrastructure import (\n",
+ " inspect_payment_instrument,\n",
+ ")\n",
+ "\n",
+ "agentcore_infrastructure = inspect_payment_instrument()\n",
+ "agentcore_infrastructure"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "agentcore-run-warning",
+ "metadata": {},
+ "source": [
+ "### Running one approved testnet transaction\n",
+ "\n",
+ "An operator can enable the managed testnet run only after checking the approved merchant, recipient, asset, amount, wallet, and short-lived session configuration. The workflow requires all five explicit gates: `RUN_AGENTCORE_E2E`, `ALLOW_AGENTCORE_SESSION_ADMIN`, `ALLOW_PAID_INFERENCE`, `ALLOW_AGENTCORE_TESTNET`, and `APPROVE_AGENTCORE_TESTNET_PURCHASE`.\n",
+ "\n",
+ "The combined execution path checks those gates again before starting model inference or payment activity. It creates one bounded session, sends the agent's request through the application policy, requests an AgentCore payment proof, and retries the approved merchant once.\n",
+ "\n",
+ "Session creation is serialized. If local session persistence fails, the application attempts compensating cleanup. A successful or failed managed run also attempts to delete the session in `finally`. If cleanup fails, the operator must follow the recovery procedure in `README.md` before starting another run.\n",
+ "\n",
+ "With the default notebook configuration, the cell returns `SKIPPED` and performs no live operation.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "agentcore-e2e-run",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import json\n",
+ "\n",
+ "agentcore_e2e_result = await run_managed_e2e()\n",
+ "if agentcore_e2e_result[\"result\"] not in {\"PASSED\", \"SKIPPED\"}:\n",
+ " print(json.dumps(agentcore_e2e_result, indent=2, sort_keys=True))\n",
+ " raise RuntimeError(\n",
+ " \"Managed AgentCore test did not complete safely; review the \"\n",
+ " \"sanitized report before any rerun.\"\n",
+ " )\n",
+ "\n",
+ "agentcore_e2e_result"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "aws-evidence-intro",
+ "metadata": {},
+ "source": [
+ "### Interpreting payment and settlement evidence\n",
+ "\n",
+ "The managed result records whether the model completed its tool call, AgentCore Payments produced the payment proof, the merchant returned HTTP `200`, and the temporary session was deleted. The application hashes the original HTTP response bytes and keeps provider credentials, payment headers, and internal identifiers out of the report.\n",
+ "\n",
+ "Merchant acceptance establishes that the paid request completed. Independent settlement and transaction finality require separate evidence. The example therefore reports `settlement_verified=false`.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "aws-evidence-check",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "if agentcore_e2e_result[\"result\"] == \"PASSED\":\n",
+ " assert agentcore_e2e_result[\"model_run_completed\"] is True\n",
+ " assert agentcore_e2e_result[\"agentcore_payment_path_completed\"] is True\n",
+ " assert agentcore_e2e_result[\"merchant_paid_retry_completed\"] is True\n",
+ " assert agentcore_e2e_result[\"status_code\"] == 200\n",
+ " assert agentcore_e2e_result[\"payment_attempts\"] == 1\n",
+ " assert agentcore_e2e_result[\"session_cleanup\"] == \"DELETED\"\n",
+ " assert agentcore_e2e_result[\"identifiers_logged\"] is False\n",
+ " assert agentcore_e2e_result[\"settlement_verified\"] is False\n",
+ "\n",
+ "{\n",
+ " \"result\": agentcore_e2e_result[\"result\"],\n",
+ " \"session_cleanup\": agentcore_e2e_result.get(\"session_cleanup\", \"NOT_CREATED\"),\n",
+ " \"settlement_verified\": agentcore_e2e_result.get(\"settlement_verified\", False),\n",
+ " \"interpretation\": (\n",
+ " \"Combined testnet path completed; settlement still needs separate evidence.\"\n",
+ " if agentcore_e2e_result[\"result\"] == \"PASSED\"\n",
+ " else \"Live path was not enabled; no testnet transaction was attempted.\"\n",
+ " ),\n",
+ "}"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "cloudwatch-lifecycle-evidence",
+ "metadata": {},
+ "source": [
+ "### Optional CloudWatch lifecycle evidence\n",
+ "\n",
+ "This public notebook does not include a CloudWatch screenshot. For a reviewed live run, configure AgentCore Payments log delivery before the run and use CloudWatch only as sanitized lifecycle evidence. Do not share account IDs, request IDs, wallet data, payment identifiers, or proof headers.\n",
+ "\n",
+ "Lifecycle events can help confirm session creation, payment processing, and session deletion. They do not independently establish the payment amount, blockchain settlement, transaction finality, or production readiness.\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "completion",
+ "metadata": {},
+ "source": [
+ "## Applying the payment workflow to other services\n",
+ "\n",
+ "The same structure can support other paid data sources, including premium search, sanctions screening, market data, or supplier verification. Each integration should define its approved merchants, permitted purposes, maximum amount, approval requirements, and session duration before the agent can request a purchase.\n",
+ "\n",
+ "The model chooses when a paid tool might help complete the user's task. Application code determines whether that request is authorized, records the resulting transaction evidence, and checks the model's final response against the actual tool result. AgentCore Payments provides an additional spending boundary when the workflow is connected to an approved AWS testnet session.\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "references",
+ "metadata": {},
+ "source": [
+ "## References\n",
+ "\n",
+ "- [OpenAI Agents SDK](https://openai.github.io/openai-agents-python/)\n",
+ "- [Use OpenAI models through Amazon Bedrock](https://developers.openai.com/api/docs/guides/amazon-bedrock)\n",
+ "- [How AgentCore Payments works](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/payments-how-it-works.html)\n",
+ "- [AgentCore Payments prerequisites](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/payments-prerequisites.html)\n",
+ "- [Create bounded payment sessions](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/payments-create-session.html)\n",
+ "- [Separate payment IAM roles](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/payments-iam-roles.html)\n",
+ "- [AWS companion sample and source attribution](https://github.com/awslabs/agentcore-samples/pull/1869).\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3 (ipykernel)",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.12.13"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/pyproject.toml b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/pyproject.toml
new file mode 100644
index 00000000..71dfe7ee
--- /dev/null
+++ b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/pyproject.toml
@@ -0,0 +1,41 @@
+[project]
+name = "agentic-commerce-openai-agentcore-payments"
+version = "0.1.0"
+description = "Synthetic agentic-commerce Cookbook using the OpenAI Agents SDK and AgentCore Payments"
+requires-python = ">=3.11,<3.14"
+dependencies = [
+ "botocore[crt]>=1.40.0",
+ "httpx>=0.28.0,<1",
+ "openai[bedrock]>=2.46.0,<3",
+ "openai-agents>=0.18.2,<0.19",
+ "pydantic>=2.13.0,<3",
+]
+
+[project.scripts]
+agentic-commerce-agentcore-e2e = "agentic_commerce.agentcore_e2e:main"
+agentic-commerce-agentcore-infrastructure = "agentic_commerce.agentcore_infrastructure:main"
+agentic-commerce-agentcore-session = "agentic_commerce.agentcore_session:main"
+
+[project.optional-dependencies]
+agentcore = [
+ "bedrock-agentcore==1.18.1",
+]
+
+[build-system]
+requires = ["hatchling"]
+build-backend = "hatchling.build"
+
+[dependency-groups]
+dev = [
+ "pytest>=8.4.0,<9",
+ "ruff>=0.16.0,<0.17",
+]
+
+[tool.uv]
+package = true
+
+[tool.hatch.build.targets.wheel]
+packages = ["src/agentic_commerce"]
+
+[tool.pytest.ini_options]
+testpaths = ["tests"]
diff --git a/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/__init__.py b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/__init__.py
new file mode 100644
index 00000000..4f6b40d7
--- /dev/null
+++ b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/__init__.py
@@ -0,0 +1,26 @@
+"""Controlled, synthetic x402 commerce primitives for the Cookbook."""
+
+from .agent import SupplierResearchOutput, run_supplier_research
+from .application import CommerceApplication
+from .merchant import SyntheticMerchant
+from .models import (
+ ApprovalGrant,
+ CommercePolicy,
+ PurchaseRequest,
+ PurchaseResult,
+)
+from .payments import LocalPaymentProcessor
+from .policy import PolicyEngine
+
+__all__ = [
+ "ApprovalGrant",
+ "CommerceApplication",
+ "CommercePolicy",
+ "LocalPaymentProcessor",
+ "PolicyEngine",
+ "PurchaseRequest",
+ "PurchaseResult",
+ "SupplierResearchOutput",
+ "SyntheticMerchant",
+ "run_supplier_research",
+]
diff --git a/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/agent.py b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/agent.py
new file mode 100644
index 00000000..6a33d74c
--- /dev/null
+++ b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/agent.py
@@ -0,0 +1,182 @@
+"""One-agent, one-tool supplier research workflow for the Cookbook."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Literal
+
+from agents import (
+ Agent,
+ Model,
+ ModelSettings,
+ RunConfig,
+ Runner,
+)
+from agents.tracing import set_trace_provider
+from agents.tracing.provider import DefaultTraceProvider
+from openai.types.shared import Reasoning
+from pydantic import BaseModel, ConfigDict
+
+from .application import CommerceApplication
+from .errors import AgentResultInvalid
+from .models import ApprovalGrant, PurchaseResult
+from .tool import build_x402_fetch_tool
+
+DEFAULT_PROMPT = (
+ "Purchase the approved synthetic supplier-risk report at "
+ "https://merchant.invalid/reports/SYNTH-SUPPLIER-RISK-001 for the "
+ "supplier_due_diligence purpose. Use x402_fetch exactly once, then "
+ "return only the typed summary supported by the tool result."
+)
+
+
+class SupplierResearchOutput(BaseModel):
+ """Typed, non-authoritative summary proposed by the agent."""
+
+ model_config = ConfigDict(frozen=True)
+
+ status: Literal["completed"]
+ report_id: Literal["SYNTH-SUPPLIER-RISK-001"]
+ supplier: Literal["Northstar Components"]
+ signals: tuple[str, ...]
+ disclaimer: str
+ receipt_id: str
+ amount: Literal["0.25"]
+ currency: Literal["USDC"]
+ requires_human_approval: bool
+
+
+@dataclass
+class PurchaseResultRecorder:
+ """Application-owned, per-run record of completed tool purchases."""
+
+ results: list[PurchaseResult] = field(default_factory=list)
+
+ def record(self, result: PurchaseResult) -> None:
+ self.results.append(result)
+
+
+@dataclass(frozen=True)
+class SupplierResearchRun:
+ """Agent proposal paired with the application evidence that validated it."""
+
+ output: SupplierResearchOutput
+ purchase: PurchaseResult
+
+
+def build_supplier_research_agent(
+ application: CommerceApplication,
+ *,
+ model: str | Model,
+ request_id: str,
+ idempotency_key: str,
+ approval: ApprovalGrant | None,
+ recorder: PurchaseResultRecorder,
+) -> Agent[None]:
+ """Create a fresh Agent whose only economic tool is application-bound."""
+
+ tool = build_x402_fetch_tool(
+ application,
+ request_id=request_id,
+ idempotency_key=idempotency_key,
+ approval=approval,
+ on_purchase=recorder.record,
+ )
+ return Agent(
+ name="Synthetic supplier research agent",
+ model=model,
+ model_settings=ModelSettings(
+ reasoning=Reasoning(effort="low"),
+ store=False,
+ ),
+ output_type=SupplierResearchOutput,
+ tools=[tool],
+ instructions=(
+ "Use x402_fetch exactly once for the requested paid resource. "
+ "The application—not you—owns merchant policy, budgets, human "
+ "approval, payment execution, receipts, and audit state. Copy "
+ "only facts returned by the tool. Never claim success after a "
+ "denial, and never invent a report or receipt."
+ ),
+ )
+
+
+def validate_supplier_research_output(
+ output: SupplierResearchOutput,
+ recorder: PurchaseResultRecorder,
+) -> PurchaseResult:
+ """Fail closed unless one tool purchase supports every returned field."""
+
+ if len(recorder.results) != 1:
+ raise AgentResultInvalid(
+ "purchase_count_invalid",
+ "A valid agent result requires exactly one completed purchase.",
+ )
+
+ purchase = recorder.results[0]
+ expected = {
+ "status": purchase.status,
+ "report_id": purchase.report.report_id,
+ "supplier": purchase.report.supplier,
+ "signals": purchase.report.signals,
+ "disclaimer": purchase.report.disclaimer,
+ "receipt_id": purchase.receipt.receipt_id,
+ "amount": str(purchase.receipt.amount),
+ "currency": purchase.receipt.currency,
+ "requires_human_approval": (purchase.authorization.requires_human_approval),
+ }
+ actual = output.model_dump()
+ mismatches = sorted(
+ field_name
+ for field_name, expected_value in expected.items()
+ if actual[field_name] != expected_value
+ )
+ if mismatches:
+ raise AgentResultInvalid(
+ "agent_output_mismatch",
+ "Agent output did not match application evidence for: "
+ + ", ".join(mismatches),
+ )
+ return purchase
+
+
+async def run_supplier_research(
+ application: CommerceApplication,
+ *,
+ model: str | Model,
+ request_id: str,
+ idempotency_key: str,
+ approval: ApprovalGrant | None,
+ prompt: str = DEFAULT_PROMPT,
+) -> SupplierResearchRun:
+ """Run the agent and validate its proposal against tool-observed evidence."""
+
+ recorder = PurchaseResultRecorder()
+ trace_provider = DefaultTraceProvider()
+ trace_provider.set_disabled(True)
+ set_trace_provider(trace_provider)
+ agent = build_supplier_research_agent(
+ application,
+ model=model,
+ request_id=request_id,
+ idempotency_key=idempotency_key,
+ approval=approval,
+ recorder=recorder,
+ )
+ result = await Runner.run(
+ agent,
+ prompt,
+ max_turns=4,
+ run_config=RunConfig(
+ tracing_disabled=True,
+ workflow_name="Synthetic Agentic Commerce",
+ ),
+ )
+ output = result.final_output
+ if not isinstance(output, SupplierResearchOutput):
+ raise AgentResultInvalid(
+ "typed_output_missing",
+ "The agent did not return the required typed output.",
+ )
+ purchase = validate_supplier_research_output(output, recorder)
+ return SupplierResearchRun(output=output, purchase=purchase)
diff --git a/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/agentcore_agent.py b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/agentcore_agent.py
new file mode 100644
index 00000000..913ef256
--- /dev/null
+++ b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/agentcore_agent.py
@@ -0,0 +1,255 @@
+"""Agents SDK boundary for the optional AgentCore testnet join."""
+
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass, field
+from threading import Lock
+from typing import Any, Literal
+
+from agents import (
+ Agent,
+ Model,
+ ModelSettings,
+ RunConfig,
+ Runner,
+ function_tool,
+)
+from agents.tracing import set_trace_provider
+from agents.tracing.provider import DefaultTraceProvider
+from openai.types.shared import Reasoning
+from pydantic import BaseModel, ConfigDict, Field
+
+from .agentcore_application import (
+ AgentCoreAccessResult,
+ AgentCoreAuthorizedApplication,
+)
+from .errors import AgentResultInvalid, CommerceError
+from .models import ApprovalGrant, PurchaseRequest
+
+
+class AgentCoreAccessOutput(BaseModel):
+ """Typed, non-authoritative summary of application transport evidence."""
+
+ model_config = ConfigDict(frozen=True)
+
+ status: Literal["completed"]
+ merchant: str
+ status_code: int = Field(ge=200, lt=300)
+ amount: str
+ currency: Literal["USDC"]
+ network: Literal["eip155:84532"]
+ payment_attempts: int = Field(ge=1)
+ response_sha256: str = Field(pattern=r"^[0-9a-f]{64}$")
+ response_bytes: int = Field(ge=0)
+ requires_human_approval: bool
+
+
+@dataclass
+class AgentCoreAccessRecorder:
+ invocations: int = 0
+ results: list[AgentCoreAccessResult] = field(default_factory=list)
+ failures: list[tuple[str, str]] = field(default_factory=list)
+ _lock: Any = field(default_factory=Lock, repr=False)
+
+ def begin_invocation(self) -> bool:
+ """Consume the one-shot tool capability before any side effect."""
+
+ with self._lock:
+ self.invocations += 1
+ return self.invocations == 1
+
+ def record(self, result: AgentCoreAccessResult) -> None:
+ self.results.append(result)
+
+ def record_failure(self, error: CommerceError) -> None:
+ self.failures.append((error.code, str(error)))
+
+
+@dataclass(frozen=True)
+class AgentCoreAgentRun:
+ output: AgentCoreAccessOutput
+ access: AgentCoreAccessResult
+
+
+def build_agentcore_access_agent(
+ application: AgentCoreAuthorizedApplication,
+ *,
+ model: str | Model,
+ request_id: str,
+ idempotency_key: str,
+ approval: ApprovalGrant | None,
+ recorder: AgentCoreAccessRecorder,
+) -> Agent[None]:
+ """Build one agent with one application-controlled economic tool."""
+
+ @function_tool(name_override="x402_fetch")
+ def x402_fetch(resource_url: str, purpose: str) -> str:
+ """Access one allowlisted x402 testnet resource for one purpose."""
+
+ if not recorder.begin_invocation():
+ error = AgentResultInvalid(
+ "access_count_invalid",
+ "The economic tool permits exactly one invocation.",
+ )
+ recorder.record_failure(error)
+ return json.dumps(
+ {
+ "status": "denied",
+ "code": error.code,
+ "message": str(error),
+ },
+ sort_keys=True,
+ )
+ try:
+ result = application.access(
+ PurchaseRequest(
+ request_id=request_id,
+ resource_url=resource_url,
+ purpose=purpose,
+ idempotency_key=idempotency_key,
+ ),
+ approval=approval,
+ )
+ except CommerceError as exc:
+ recorder.record_failure(exc)
+ return json.dumps(
+ {
+ "status": "denied",
+ "code": exc.code,
+ "message": str(exc),
+ },
+ sort_keys=True,
+ )
+ recorder.record(result)
+ return json.dumps(
+ {
+ "status": result.status,
+ "merchant": result.merchant,
+ "status_code": result.status_code,
+ "amount": str(result.challenge.amount),
+ "currency": result.challenge.currency,
+ "network": result.challenge.network,
+ "payment_attempts": result.payment_attempts,
+ "response_sha256": result.response_sha256,
+ "response_bytes": result.response_bytes,
+ "requires_human_approval": (
+ result.authorization.requires_human_approval
+ ),
+ },
+ sort_keys=True,
+ )
+
+ return Agent(
+ name="AgentCore testnet access agent",
+ model=model,
+ model_settings=ModelSettings(
+ reasoning=Reasoning(effort="low"),
+ store=False,
+ ),
+ output_type=AgentCoreAccessOutput,
+ tools=[x402_fetch],
+ instructions=(
+ "Use x402_fetch exactly once for the explicitly requested "
+ "testnet resource. The application owns merchant policy, "
+ "budgets, human approval, payment execution, and audit state. "
+ "Return only the typed transport evidence from the tool. Never "
+ "invent a payment, settlement, receipt, or resource claim."
+ ),
+ )
+
+
+def validate_agentcore_access_output(
+ output: AgentCoreAccessOutput,
+ recorder: AgentCoreAccessRecorder,
+) -> AgentCoreAccessResult:
+ """Match every agent field to one application-observed tool result."""
+
+ if recorder.invocations != 1:
+ raise AgentResultInvalid(
+ "access_count_invalid",
+ "A valid testnet result requires exactly one total tool invocation.",
+ )
+ if len(recorder.results) != 1:
+ if not recorder.results and len(recorder.failures) == 1:
+ code, message = recorder.failures[0]
+ raise AgentResultInvalid(code, message)
+ raise AgentResultInvalid(
+ "access_count_invalid",
+ "A valid testnet result requires exactly one completed access.",
+ )
+ access = recorder.results[0]
+ expected = {
+ "status": access.status,
+ "merchant": access.merchant,
+ "status_code": access.status_code,
+ "amount": str(access.challenge.amount),
+ "currency": access.challenge.currency,
+ "network": access.challenge.network,
+ "payment_attempts": access.payment_attempts,
+ "response_sha256": access.response_sha256,
+ "response_bytes": access.response_bytes,
+ "requires_human_approval": (access.authorization.requires_human_approval),
+ }
+ actual = output.model_dump()
+ mismatches = sorted(
+ name for name, value in expected.items() if actual[name] != value
+ )
+ if mismatches:
+ raise AgentResultInvalid(
+ "agent_output_mismatch",
+ "Agent output did not match application evidence for: "
+ + ", ".join(mismatches),
+ )
+ return access
+
+
+async def run_agentcore_access(
+ application: AgentCoreAuthorizedApplication,
+ *,
+ model: str | Model,
+ request_id: str,
+ idempotency_key: str,
+ approval: ApprovalGrant | None,
+ resource_url: str,
+ purpose: str = "testnet_integration_validation",
+) -> AgentCoreAgentRun:
+ """Run and validate the optional AgentCore testnet integration path."""
+
+ recorder = AgentCoreAccessRecorder()
+ # Install a disabled provider before Runner initializes the default trace
+ # exporter. This keeps the Bedrock-only path from constructing an OpenAI
+ # tracing client when no tracing destination has been approved.
+ trace_provider = DefaultTraceProvider()
+ trace_provider.set_disabled(True)
+ set_trace_provider(trace_provider)
+ agent = build_agentcore_access_agent(
+ application,
+ model=model,
+ request_id=request_id,
+ idempotency_key=idempotency_key,
+ approval=approval,
+ recorder=recorder,
+ )
+ prompt = (
+ f"Access the approved testnet resource at {resource_url} for the "
+ f"{purpose} purpose. Use x402_fetch exactly once, then return only "
+ "the typed transport evidence supported by the tool result."
+ )
+ result = await Runner.run(
+ agent,
+ prompt,
+ max_turns=4,
+ run_config=RunConfig(
+ tracing_disabled=True,
+ workflow_name="AgentCore Testnet Access",
+ ),
+ )
+ output = result.final_output
+ if not isinstance(output, AgentCoreAccessOutput):
+ raise AgentResultInvalid(
+ "typed_output_missing",
+ "The agent did not return the required typed output.",
+ )
+ access = validate_agentcore_access_output(output, recorder)
+ return AgentCoreAgentRun(output=output, access=access)
diff --git a/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/agentcore_application.py b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/agentcore_application.py
new file mode 100644
index 00000000..b72d3662
--- /dev/null
+++ b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/agentcore_application.py
@@ -0,0 +1,195 @@
+"""Application-owned authorization around the AgentCore x402 adapter."""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+from datetime import datetime
+from typing import Literal
+
+from pydantic import Field
+
+from .agentcore_payments import (
+ AgentCorePaymentChallenge,
+ AgentCoreX402Client,
+ AuthorizationCallback,
+)
+from .audit import AuditTrail, Clock, utc_now
+from .errors import AgentCorePaymentError, PolicyDenied
+from .models import (
+ ApprovalGrant,
+ AuditEvent,
+ AuditEventType,
+ AuthorizationDecision,
+ FrozenModel,
+ PurchaseRequest,
+)
+from .policy import PolicyEngine
+
+AgentCoreClientFactory = Callable[[AuthorizationCallback], AgentCoreX402Client]
+
+
+class AgentCoreAccessResult(FrozenModel):
+ """Sanitized application evidence for one paid testnet access."""
+
+ status: Literal["completed"] = "completed"
+ request_id: str
+ merchant: str
+ status_code: int = Field(ge=200, lt=300)
+ content_type: str | None = None
+ response_sha256: str = Field(pattern=r"^[0-9a-f]{64}$")
+ response_bytes: int = Field(ge=0)
+ payment_attempts: int = Field(ge=1)
+ challenge: AgentCorePaymentChallenge
+ authorization: AuthorizationDecision
+ audit_events: tuple[AuditEvent, ...]
+
+
+class AgentCoreAuthorizedApplication:
+ """Own policy, approval, budget reservation, and audit state."""
+
+ def __init__(
+ self,
+ *,
+ policy: PolicyEngine,
+ client_factory: AgentCoreClientFactory,
+ audit: AuditTrail | None = None,
+ clock: Clock = utc_now,
+ ) -> None:
+ self.policy = policy
+ self.client_factory = client_factory
+ self.audit = audit or AuditTrail()
+ self._clock = clock
+
+ def access(
+ self,
+ request: PurchaseRequest,
+ *,
+ approval: ApprovalGrant | None,
+ now: datetime | None = None,
+ ) -> AgentCoreAccessResult:
+ """Access one resource after challenge-specific authorization."""
+
+ fixed_now = now
+ preflight_now = fixed_now or self._clock()
+ self.audit.append(
+ request_id=request.request_id,
+ event_type=AuditEventType.RESOURCE_REQUESTED,
+ detail={
+ "resource_url": str(request.resource_url),
+ "purpose": request.purpose,
+ },
+ )
+ preflight = self.policy.preflight(request, now=preflight_now)
+ if not preflight.allowed:
+ self._deny(request, preflight)
+
+ authorized: list[tuple[AgentCorePaymentChallenge, AuthorizationDecision]] = []
+
+ def authorize_challenge(
+ challenge: AgentCorePaymentChallenge,
+ ) -> None:
+ authorization_now = fixed_now or self._clock()
+ self.audit.append(
+ request_id=request.request_id,
+ event_type=AuditEventType.PAYMENT_REQUIRED,
+ detail={
+ "amount": str(challenge.amount),
+ "currency": challenge.currency,
+ "merchant_domain": challenge.merchant,
+ "network": challenge.network,
+ },
+ )
+ decision = self.policy.authorize_challenge(
+ request,
+ merchant_domain=challenge.merchant,
+ network=challenge.network,
+ currency=challenge.currency,
+ amount=challenge.amount,
+ approval=approval,
+ expires_at=challenge.expires_at,
+ now=authorization_now,
+ )
+ self.audit.append(
+ request_id=request.request_id,
+ event_type=AuditEventType.AUTHORIZATION_CHECKED,
+ detail={
+ "allowed": decision.allowed,
+ "code": decision.code,
+ "requires_human_approval": (decision.requires_human_approval),
+ },
+ )
+ if not decision.allowed:
+ self._deny(request, decision)
+
+ # Reserve the amount before proof generation. A transport failure
+ # must not make a potentially spent amount available again.
+ self.policy.record_spend(
+ request.idempotency_key,
+ challenge.amount,
+ )
+ authorized.append((challenge, decision))
+
+ client = self.client_factory(authorize_challenge)
+ result = client.fetch(
+ str(request.resource_url),
+ client_token=request.idempotency_key,
+ )
+ if not authorized:
+ raise AgentCorePaymentError(
+ "payment_challenge_not_observed",
+ "The merchant did not present an authorized payment challenge.",
+ )
+ if not result.payment_attempted or result.payment_attempts < 1:
+ raise AgentCorePaymentError(
+ "payment_not_attempted",
+ "The paid testnet resource was not accessed through the "
+ "approved payment path.",
+ )
+ if result.status_code != 200:
+ raise AgentCorePaymentError(
+ "paid_resource_unavailable",
+ "The merchant did not return the expected paid resource.",
+ )
+
+ self.audit.append(
+ request_id=request.request_id,
+ event_type=AuditEventType.PAYMENT_ATTEMPTED,
+ detail={
+ "idempotency_key": request.idempotency_key,
+ "attempts": result.payment_attempts,
+ },
+ )
+ self.audit.append(
+ request_id=request.request_id,
+ event_type=AuditEventType.CONTENT_RETURNED,
+ detail={
+ "merchant_domain": result.merchant,
+ "status_code": result.status_code,
+ "response_sha256": result.response_sha256,
+ },
+ )
+ challenge, decision = authorized[-1]
+ return AgentCoreAccessResult(
+ request_id=request.request_id,
+ merchant=result.merchant,
+ status_code=result.status_code,
+ content_type=result.content_type,
+ response_sha256=result.response_sha256,
+ response_bytes=result.response_bytes,
+ payment_attempts=result.payment_attempts,
+ challenge=challenge,
+ authorization=decision,
+ audit_events=self.audit.for_request(request.request_id),
+ )
+
+ def _deny(
+ self,
+ request: PurchaseRequest,
+ decision: AuthorizationDecision,
+ ) -> None:
+ self.audit.append(
+ request_id=request.request_id,
+ event_type=AuditEventType.REQUEST_DENIED,
+ detail={"code": decision.code},
+ )
+ raise PolicyDenied(decision.code, decision.reason)
diff --git a/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/agentcore_e2e.py b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/agentcore_e2e.py
new file mode 100644
index 00000000..59629b0c
--- /dev/null
+++ b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/agentcore_e2e.py
@@ -0,0 +1,398 @@
+"""Managed, explicitly opted-in AgentCore testnet notebook runner."""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import importlib.metadata
+import json
+import os
+from collections.abc import Awaitable, Callable, Mapping, Sequence
+from decimal import Decimal
+from pathlib import Path
+
+from agents.models.openai_responses import OpenAIResponsesModel
+from openai import AsyncOpenAI
+from openai.providers import bedrock
+
+from .agentcore_agent import AgentCoreAgentRun, run_agentcore_access
+from .agentcore_payments import (
+ _REQUIRED_CONFIGURATION,
+ _SUPPORTED_AGENTCORE_PAYMENT_REGIONS,
+ AgentCorePaymentsSettings,
+ _positive_integer_text,
+ _proxy_environment_clear,
+ _reject_proxy_environment,
+ _resolve_agentcore_region,
+)
+from .agentcore_runtime import build_live_agentcore_context
+from .agentcore_session import (
+ PaymentSessionManager,
+ _manager,
+ _read_session_state,
+ _session_file,
+ create_bounded_session,
+ delete_recorded_session,
+ runtime_environment_from_recorded_session,
+)
+from .errors import CommerceError
+
+_MASTER_OPT_IN = "RUN_AGENTCORE_E2E"
+_REQUIRED_OPT_INS = (
+ _MASTER_OPT_IN,
+ "ALLOW_AGENTCORE_SESSION_ADMIN",
+ "ALLOW_PAID_INFERENCE",
+ "ALLOW_AGENTCORE_TESTNET",
+ "APPROVE_AGENTCORE_TESTNET_PURCHASE",
+)
+_SESSION_EXPIRY_MINUTES = 15
+_USDC_ATOMIC_SCALE = Decimal(1_000_000)
+_MAX_SESSION_BUDGET_USD = Decimal("0.01")
+_PURPOSE = "testnet_integration_validation"
+
+ManagerFactory = Callable[[Mapping[str, str]], PaymentSessionManager]
+CombinedRunner = Callable[[Mapping[str, str]], Awaitable[dict[str, object]]]
+
+
+def _blocked_report(exc: Exception) -> dict[str, object]:
+ return {
+ "result": "BLOCKED",
+ "category": "combined_runtime_error",
+ "exception_type": type(exc).__name__,
+ "next_action": (
+ "Review the local provider and AgentCore logs, then rerun only "
+ "after confirming the bounded testnet controls."
+ ),
+ "proof_headers_logged": False,
+ "value_transferred": "unknown",
+ }
+
+
+def _bedrock_profile(values: Mapping[str, str]) -> str:
+ profile = values.get("BEDROCK_AWS_PROFILE", "").strip()
+ if not profile:
+ raise CommerceError(
+ "bedrock_profile_missing",
+ "BEDROCK_AWS_PROFILE is required for paid model inference.",
+ )
+ return profile
+
+
+def _require_live_opt_ins(values: Mapping[str, str]) -> None:
+ missing = [name for name in _REQUIRED_OPT_INS if values.get(name) != "1"]
+ if missing:
+ raise CommerceError(
+ "agentcore_live_opt_ins_missing",
+ "The combined live path requires these explicit opt-ins: "
+ + ", ".join(f"{name}=1" for name in missing),
+ )
+
+
+def _combined_success_report(result: AgentCoreAgentRun) -> dict[str, object]:
+ if result.access.status_code != 200:
+ raise CommerceError(
+ "merchant_paid_retry_incomplete",
+ "The merchant did not return HTTP 200 for the paid retry.",
+ )
+
+ return {
+ "result": "PASSED",
+ "model_run_completed": True,
+ "agentcore_payment_path_completed": True,
+ "merchant_paid_retry_completed": True,
+ "merchant": result.access.merchant,
+ "status_code": result.access.status_code,
+ "payment_attempts": result.access.payment_attempts,
+ "authorized_amount": str(result.access.challenge.amount),
+ "currency": result.access.challenge.currency,
+ "network": result.access.challenge.network,
+ "response_sha256": result.access.response_sha256,
+ "proof_headers_logged": False,
+ "settlement_verified": False,
+ "testnet_only": True,
+ }
+
+
+async def _execute_combined(
+ environ: Mapping[str, str],
+) -> dict[str, object]:
+ _require_live_opt_ins(environ)
+ _reject_proxy_environment(environ)
+ settings = AgentCorePaymentsSettings.from_env(environ)
+ resource_url = environ.get("X402_RESOURCE_URL", "").strip()
+ idempotency_key = environ.get("X402_IDEMPOTENCY_KEY", "").strip()
+ if not resource_url or not idempotency_key:
+ raise CommerceError(
+ "agentcore_agent_configuration_missing",
+ "X402_RESOURCE_URL and X402_IDEMPOTENCY_KEY are required.",
+ )
+ context = build_live_agentcore_context(
+ settings,
+ resource_url=resource_url,
+ idempotency_key=idempotency_key,
+ purpose=_PURPOSE,
+ )
+ model_region = environ.get("AWS_REGION", "us-east-2")
+ model_id = environ.get("BEDROCK_MODEL", "openai.gpt-5.6-sol")
+ model = OpenAIResponsesModel(
+ model=model_id,
+ openai_client=AsyncOpenAI(
+ provider=bedrock(
+ region=model_region,
+ profile=_bedrock_profile(environ),
+ )
+ ),
+ )
+ result = await run_agentcore_access(
+ context.application,
+ model=model,
+ request_id=context.request.request_id,
+ idempotency_key=context.request.idempotency_key,
+ approval=context.approval,
+ resource_url=str(context.request.resource_url),
+ purpose=context.request.purpose,
+ )
+ return _combined_success_report(result)
+
+
+def _session_budget(values: Mapping[str, str]) -> Decimal | None:
+ raw_amount_atomic = values.get("X402_MAX_APPROVED_AMOUNT_ATOMIC", "").strip()
+ if not _positive_integer_text(raw_amount_atomic):
+ return None
+ amount_atomic = Decimal(int(raw_amount_atomic))
+ budget = amount_atomic / _USDC_ATOMIC_SCALE
+ if budget <= 0 or budget > _MAX_SESSION_BUDGET_USD:
+ return None
+ return budget
+
+
+def readiness_report(
+ environ: Mapping[str, str] | None = None,
+ *,
+ session_file: Path | None = None,
+) -> dict[str, object]:
+ """Return presence and gate status without making a live call."""
+
+ values = environ if environ is not None else os.environ
+ missing_opt_ins = [
+ f"{name}=1" for name in _REQUIRED_OPT_INS if values.get(name) != "1"
+ ]
+ required_runtime_names = tuple(
+ name for name in _REQUIRED_CONFIGURATION if name != "PAYMENT_SESSION_ID"
+ ) + ("X402_RESOURCE_URL", "X402_IDEMPOTENCY_KEY")
+ configuration_present = {
+ name: bool(values.get(name, "").strip()) for name in required_runtime_names
+ }
+ session_profile = values.get("AGENTCORE_SESSION_AWS_PROFILE", "").strip()
+ model_profile = values.get("BEDROCK_AWS_PROFILE", "").strip()
+ runtime_profile = values.get("AGENTCORE_RUNTIME_AWS_PROFILE", "").strip()
+ profiles_present = bool(session_profile and model_profile and runtime_profile)
+ profiles_separated = (
+ profiles_present
+ and session_profile != runtime_profile
+ and model_profile != runtime_profile
+ )
+ agentcore_region = _resolve_agentcore_region(values)
+ region_supported = agentcore_region in _SUPPORTED_AGENTCORE_PAYMENT_REGIONS
+ one_payment_attempt = values.get("X402_MAX_PAYMENT_ATTEMPTS") == "1"
+ session_budget = _session_budget(values)
+ proxy_environment_clear = _proxy_environment_clear(values)
+ path = _session_file(values, session_file)
+ try:
+ state = _read_session_state(path)
+ session_state_valid = True
+ recorded_session_present = bool(state.get("PAYMENT_SESSION_ID"))
+ except (CommerceError, OSError):
+ session_state_valid = False
+ recorded_session_present = False
+ try:
+ sdk_version = importlib.metadata.version("bedrock-agentcore")
+ except importlib.metadata.PackageNotFoundError:
+ sdk_version = None
+
+ ready = (
+ not missing_opt_ins
+ and all(configuration_present.values())
+ and profiles_separated
+ and region_supported
+ and one_payment_attempt
+ and session_budget is not None
+ and proxy_environment_clear
+ and session_state_valid
+ and not recorded_session_present
+ and sdk_version == "1.18.1"
+ )
+ return {
+ "result": "READY" if ready else "NOT_READY",
+ "live_calls": 0,
+ "value_transferred": False,
+ "missing_opt_ins": missing_opt_ins,
+ "configuration_present": configuration_present,
+ "separate_aws_profiles_present": profiles_present,
+ "aws_profiles_are_distinct": profiles_separated,
+ "bedrock_profile_present": bool(model_profile),
+ "model_and_payment_profiles_are_distinct": bool(
+ model_profile and runtime_profile and model_profile != runtime_profile
+ ),
+ "agentcore_region": agentcore_region or "missing",
+ "agentcore_region_supported": region_supported,
+ "one_payment_attempt_configured": one_payment_attempt,
+ "session_budget_valid": session_budget is not None,
+ "merchant_proxy_environment_clear": proxy_environment_clear,
+ "session_expiry_minutes": _SESSION_EXPIRY_MINUTES,
+ "local_session_state_valid": session_state_valid,
+ "recorded_session_present": recorded_session_present,
+ "bedrock_agentcore_sdk": sdk_version or "missing",
+ "bedrock_agentcore_sdk_expected": "1.18.1",
+ "note": (
+ "This check does not contact AWS, the model, the merchant, "
+ "the wallet, or a blockchain."
+ ),
+ }
+
+
+async def run_managed_e2e(
+ environ: Mapping[str, str] | None = None,
+ *,
+ manager_factory: ManagerFactory | None = None,
+ combined_runner: CombinedRunner | None = None,
+ session_file: Path | None = None,
+) -> dict[str, object]:
+ """Create, use, and delete one bounded session around one live run."""
+
+ values = dict(environ if environ is not None else os.environ)
+ readiness = readiness_report(values, session_file=session_file)
+ if readiness["result"] != "READY":
+ return {
+ **readiness,
+ "result": "SKIPPED",
+ "reason": "The managed end-to-end gates are not ready.",
+ }
+
+ build_manager = manager_factory or _manager
+ run_combined = combined_runner or _execute_combined
+ manager: PaymentSessionManager | None = None
+ session_created = False
+ execution_started = False
+ cleanup_result = "NOT_REQUIRED"
+ run_report: dict[str, object] | None = None
+ failure_report: dict[str, object] | None = None
+ budget = _session_budget(values)
+ if budget is None:
+ raise AssertionError("readiness accepted an invalid session budget")
+
+ try:
+ manager = build_manager(values)
+ create_bounded_session(
+ manager,
+ environ=values,
+ session_file=session_file,
+ budget_usd=budget,
+ expiry_minutes=_SESSION_EXPIRY_MINUTES,
+ )
+ session_created = True
+ runtime_environment = runtime_environment_from_recorded_session(
+ values,
+ session_file=session_file,
+ )
+ execution_started = True
+ run_report = await run_combined(runtime_environment)
+ if run_report.get("result") != "PASSED":
+ raise CommerceError(
+ "agentcore_e2e_result_invalid",
+ "The combined runner did not return a passing result.",
+ )
+ except CommerceError as exc:
+ failure_report = {
+ "result": "FAILED",
+ "code": exc.code,
+ "message": str(exc),
+ "proof_headers_logged": False,
+ "value_transferred": ("unknown" if execution_started else False),
+ }
+ if exc.diagnostics:
+ failure_report["diagnostics"] = exc.diagnostics
+ except Exception as exc: # noqa: BLE001
+ failure_report = _blocked_report(exc)
+ finally:
+ if session_created and manager is not None:
+ try:
+ deletion = delete_recorded_session(
+ manager,
+ environ=values,
+ session_file=session_file,
+ )
+ cleanup_result = str(deletion["result"])
+ except Exception as exc: # noqa: BLE001
+ cleanup_result = "FAILED"
+ if failure_report is None:
+ failure_report = {
+ **_blocked_report(exc),
+ "category": "payment_session_cleanup_error",
+ "next_action": (
+ "Delete the recorded bounded session with the "
+ "session-administration role before another run."
+ ),
+ }
+ else:
+ failure_report["cleanup_next_action"] = (
+ "Delete the recorded bounded session with the "
+ "session-administration role before another run."
+ )
+
+ if failure_report is not None:
+ return {
+ **failure_report,
+ "mode": "managed_agentcore_testnet_e2e",
+ "session_created": session_created,
+ "session_cleanup": cleanup_result,
+ "identifiers_logged": False,
+ "testnet_only": True,
+ }
+ if run_report is None:
+ raise AssertionError("managed run completed without a report")
+ return {
+ **run_report,
+ "mode": "managed_agentcore_testnet_e2e",
+ "session_created": True,
+ "session_budget_usd": format(budget, "f"),
+ "session_expiry_minutes": _SESSION_EXPIRY_MINUTES,
+ "session_cleanup": cleanup_result,
+ "identifiers_logged": False,
+ "settlement_verified": False,
+ "testnet_only": True,
+ }
+
+
+async def run() -> None:
+ report = await run_managed_e2e()
+ print(json.dumps(report, indent=2, sort_keys=True))
+ if report["result"] != "PASSED":
+ raise SystemExit(2 if report["result"] == "SKIPPED" else 1)
+
+
+def _parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description="Run one managed AgentCore testnet integration test."
+ )
+ parser.add_argument(
+ "--check",
+ action="store_true",
+ help="Print no-call readiness only; never start the live workflow.",
+ )
+ return parser
+
+
+def main(argv: Sequence[str] | None = None) -> None:
+ args = _parser().parse_args(argv)
+ if args.check:
+ report = readiness_report()
+ print(json.dumps(report, indent=2, sort_keys=True))
+ if report["result"] != "READY":
+ raise SystemExit(2)
+ return
+ asyncio.run(run())
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/agentcore_infrastructure.py b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/agentcore_infrastructure.py
new file mode 100644
index 00000000..9998cf78
--- /dev/null
+++ b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/agentcore_infrastructure.py
@@ -0,0 +1,211 @@
+"""Explicitly gated, read-only checks for AgentCore payment resources."""
+
+from __future__ import annotations
+
+import json
+import os
+from collections.abc import Callable, Mapping
+from typing import Any, Protocol
+
+from .agentcore_payments import (
+ _SUPPORTED_AGENTCORE_PAYMENT_REGIONS,
+ _disable_agentcore_sdk_logging,
+ _resolve_agentcore_region,
+)
+
+_READ_ONLY_OPT_IN = "ALLOW_AGENTCORE_READ_ONLY"
+_EXPECTED_INSTRUMENT_NETWORK = "ETHEREUM"
+_EXPECTED_CHAIN = "BASE_SEPOLIA"
+_EXPECTED_TOKEN = "USDC"
+_REQUIRED_CONFIGURATION = (
+ "PAYMENT_MANAGER_ARN",
+ "PAYMENT_CONNECTOR_ID",
+ "PAYMENT_INSTRUMENT_ID",
+ "PAYMENT_USER_ID",
+ "AGENTCORE_RUNTIME_AWS_PROFILE",
+)
+
+
+class InstrumentReader(Protocol):
+ """Narrow read-only surface used by the infrastructure check."""
+
+ def get_payment_instrument(
+ self,
+ payment_instrument_id: str,
+ user_id: str | None = None,
+ payment_connector_id: str | None = None,
+ ) -> dict[str, Any]: ...
+
+ def get_payment_instrument_balance(
+ self,
+ payment_connector_id: str,
+ payment_instrument_id: str,
+ chain: str,
+ token: str,
+ user_id: str | None = None,
+ ) -> dict[str, Any]: ...
+
+
+ManagerFactory = Callable[[Mapping[str, str]], InstrumentReader]
+
+
+def _manager(values: Mapping[str, str]) -> InstrumentReader:
+ import boto3
+ from bedrock_agentcore.payments import PaymentManager
+
+ profile = values["AGENTCORE_RUNTIME_AWS_PROFILE"].strip()
+ region = _resolve_agentcore_region(values)
+ session = boto3.Session(profile_name=profile, region_name=region)
+ _disable_agentcore_sdk_logging()
+ return PaymentManager(
+ payment_manager_arn=values["PAYMENT_MANAGER_ARN"].strip(),
+ region_name=region,
+ boto3_session=session,
+ )
+
+
+def _instrument_network(instrument: Mapping[str, Any]) -> str:
+ details = instrument.get("paymentInstrumentDetails", {})
+ if not isinstance(details, Mapping):
+ return "unknown"
+ wallet = details.get("embeddedCryptoWallet", {})
+ if not isinstance(wallet, Mapping):
+ return "unknown"
+ network = wallet.get("network")
+ return str(network) if network else "unknown"
+
+
+def _balance_scope(balance: Mapping[str, Any]) -> tuple[str, str]:
+ token_balance = balance.get("tokenBalance", {})
+ if not isinstance(token_balance, Mapping):
+ return "unknown", "unknown"
+ chain = token_balance.get("chain")
+ token = token_balance.get("token")
+ return (
+ str(chain).upper() if chain else "unknown",
+ str(token).upper() if token else "unknown",
+ )
+
+
+def readiness_report(
+ environ: Mapping[str, str] | None = None,
+) -> dict[str, object]:
+ """Report whether a read-only AWS check can run, without calling AWS."""
+
+ values = environ if environ is not None else os.environ
+ region = _resolve_agentcore_region(values)
+ configured = {
+ name: bool(values.get(name, "").strip()) for name in _REQUIRED_CONFIGURATION
+ }
+ configured["AGENTCORE_AWS_REGION"] = bool(region)
+ enabled = values.get(_READ_ONLY_OPT_IN) == "1"
+ ready = (
+ enabled
+ and all(configured.values())
+ and region in _SUPPORTED_AGENTCORE_PAYMENT_REGIONS
+ )
+ return {
+ "result": "READY" if ready else "NOT_READY",
+ "read_only_opt_in": enabled,
+ "configuration_present": configured,
+ "agentcore_region": region or "missing",
+ "agentcore_region_supported": (region in _SUPPORTED_AGENTCORE_PAYMENT_REGIONS),
+ "aws_calls": 0,
+ "payment_attempts": 0,
+ "value_transferred": False,
+ "identifiers_logged": False,
+ }
+
+
+def inspect_payment_instrument(
+ environ: Mapping[str, str] | None = None,
+ *,
+ manager_factory: ManagerFactory | None = None,
+) -> dict[str, object]:
+ """Read and sanitize instrument status without creating payment state."""
+
+ values = environ if environ is not None else os.environ
+ readiness = readiness_report(values)
+ if readiness["result"] != "READY":
+ return {
+ **readiness,
+ "result": "SKIPPED",
+ "reason": (
+ "The explicit read-only gate and complete AWS configuration "
+ "are required."
+ ),
+ }
+
+ aws_calls = 0
+ try:
+ manager = (manager_factory or _manager)(values)
+ aws_calls += 1
+ instrument = manager.get_payment_instrument(
+ payment_instrument_id=values["PAYMENT_INSTRUMENT_ID"].strip(),
+ user_id=values["PAYMENT_USER_ID"].strip(),
+ )
+ status = str(instrument.get("status", "unknown")).upper()
+ network = _instrument_network(instrument).upper()
+ chain = "not_checked"
+ token = "not_checked"
+ if status == "ACTIVE" and network == _EXPECTED_INSTRUMENT_NETWORK:
+ aws_calls += 1
+ balance = manager.get_payment_instrument_balance(
+ payment_connector_id=values["PAYMENT_CONNECTOR_ID"].strip(),
+ payment_instrument_id=values["PAYMENT_INSTRUMENT_ID"].strip(),
+ chain=_EXPECTED_CHAIN,
+ token=_EXPECTED_TOKEN,
+ user_id=values["PAYMENT_USER_ID"].strip(),
+ )
+ chain, token = _balance_scope(balance)
+ except Exception as exc: # noqa: BLE001
+ return {
+ "result": "BLOCKED",
+ "category": "agentcore_read_only_check_failed",
+ "exception_type": type(exc).__name__,
+ "next_action": (
+ "Review the local AWS profile and sanitized AgentCore logs. "
+ "Do not paste provider errors into the notebook."
+ ),
+ "aws_calls": aws_calls,
+ "payment_attempts": 0,
+ "value_transferred": False,
+ "identifiers_logged": False,
+ }
+
+ exact_scope = (
+ status == "ACTIVE"
+ and network == _EXPECTED_INSTRUMENT_NETWORK
+ and chain == _EXPECTED_CHAIN
+ and token == _EXPECTED_TOKEN
+ )
+ return {
+ "result": "PASSED" if exact_scope else "NOT_READY",
+ "payment_manager_reachable": True,
+ "payment_instrument_status": status,
+ "payment_instrument_network": network,
+ "payment_instrument_chain": chain,
+ "payment_instrument_token": token,
+ "exact_testnet_scope_verified": exact_scope,
+ "aws_calls": aws_calls,
+ "payment_attempts": 0,
+ "value_transferred": False,
+ "identifiers_logged": False,
+ "note": (
+ "This verifies read access, active instrument state, and the "
+ "configured Base Sepolia USDC balance scope only. It does not "
+ "create a session, generate a proof, contact a merchant, or "
+ "verify settlement."
+ ),
+ }
+
+
+def main() -> None:
+ report = inspect_payment_instrument()
+ print(json.dumps(report, indent=2, sort_keys=True))
+ if report["result"] != "PASSED":
+ raise SystemExit(2 if report["result"] in {"NOT_READY", "SKIPPED"} else 1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/agentcore_learning_model.py b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/agentcore_learning_model.py
new file mode 100644
index 00000000..ea89ad33
--- /dev/null
+++ b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/agentcore_learning_model.py
@@ -0,0 +1,131 @@
+"""No-inference model fixture for the AgentCore integration boundary."""
+
+from __future__ import annotations
+
+import json
+from collections.abc import AsyncIterator
+from typing import Any
+
+from agents import (
+ AgentOutputSchemaBase,
+ Handoff,
+ Model,
+ ModelResponse,
+ ModelSettings,
+ ModelTracing,
+ Tool,
+ TResponseInputItem,
+ Usage,
+)
+from agents.items import TResponseStreamEvent
+from openai.types.responses import (
+ ResponseFunctionToolCall,
+ ResponseOutputMessage,
+ ResponseOutputText,
+)
+
+from .agentcore_agent import AgentCoreAccessOutput
+
+
+class ScriptedAgentCoreLearningModel(Model):
+ """Request the testnet tool once and copy its sanitized evidence."""
+
+ def __init__(self, *, resource_url: str, purpose: str) -> None:
+ self.resource_url = resource_url
+ self.purpose = purpose
+ self.model_turns = 0
+ self.requested_tools: list[str] = []
+
+ async def get_response(
+ self,
+ system_instructions: str | None,
+ input: str | list[TResponseInputItem],
+ model_settings: ModelSettings,
+ tools: list[Tool],
+ output_schema: AgentOutputSchemaBase | None,
+ handoffs: list[Handoff],
+ tracing: ModelTracing,
+ **kwargs: Any,
+ ) -> ModelResponse:
+ self.model_turns += 1
+ if self.model_turns == 1:
+ self.requested_tools.append("x402_fetch")
+ return ModelResponse(
+ output=[
+ ResponseFunctionToolCall(
+ arguments=json.dumps(
+ {
+ "resource_url": self.resource_url,
+ "purpose": self.purpose,
+ }
+ ),
+ call_id="agentcore-learning-call-001",
+ name="x402_fetch",
+ type="function_call",
+ id="agentcore-learning-item-001",
+ status="completed",
+ )
+ ],
+ usage=Usage(),
+ response_id=None,
+ )
+
+ evidence = self._tool_evidence(input)
+ output = AgentCoreAccessOutput(**evidence)
+ return ModelResponse(
+ output=[
+ ResponseOutputMessage(
+ id="agentcore-learning-final-001",
+ content=[
+ ResponseOutputText(
+ text=output.model_dump_json(),
+ annotations=[],
+ type="output_text",
+ )
+ ],
+ role="assistant",
+ status="completed",
+ type="message",
+ )
+ ],
+ usage=Usage(),
+ response_id=None,
+ )
+
+ @staticmethod
+ def _tool_evidence(
+ input: str | list[TResponseInputItem],
+ ) -> dict[str, Any]:
+ if isinstance(input, str):
+ raise TypeError("The learning model did not receive tool output.")
+ for item in reversed(input):
+ if isinstance(item, dict) and item.get("type") == "function_call_output":
+ raw_output = item.get("output")
+ if not isinstance(raw_output, str):
+ raise RuntimeError(
+ "The learning model received invalid tool output."
+ )
+ parsed = json.loads(raw_output)
+ if not isinstance(parsed, dict) or parsed.get("status") != (
+ "completed"
+ ):
+ raise RuntimeError(
+ "The application-controlled access did not complete."
+ )
+ return parsed
+ raise RuntimeError("The learning model did not receive tool output.")
+
+ def stream_response(
+ self,
+ system_instructions: str | None,
+ input: str | list[TResponseInputItem],
+ model_settings: ModelSettings,
+ tools: list[Tool],
+ output_schema: AgentOutputSchemaBase | None,
+ handoffs: list[Handoff],
+ tracing: ModelTracing,
+ **kwargs: Any,
+ ) -> AsyncIterator[TResponseStreamEvent]:
+ raise NotImplementedError(
+ "The learning model supports non-streaming runs only."
+ )
diff --git a/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/agentcore_payments.py b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/agentcore_payments.py
new file mode 100644
index 00000000..c687e72b
--- /dev/null
+++ b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/agentcore_payments.py
@@ -0,0 +1,1106 @@
+"""Opt-in AgentCore Payments adapter for approved x402 testnet resources."""
+
+from __future__ import annotations
+
+import base64
+import binascii
+import hashlib
+import ipaddress
+import json
+import logging
+import os
+import socket
+from collections.abc import Callable, Mapping
+from datetime import UTC, datetime, timedelta
+from decimal import Decimal
+from typing import Any, Literal, Protocol
+from urllib.parse import urlsplit, urlunsplit
+
+import httpx
+from pydantic import Field, SecretStr, field_validator
+
+from .errors import AgentCorePaymentError, LivePaymentDisabled
+from .models import FrozenModel
+
+_PAYMENT_HEADER_NAMES = frozenset({"payment-signature", "x-payment"})
+_REQUIRED_CONFIGURATION = (
+ "PAYMENT_MANAGER_ARN",
+ "PAYMENT_INSTRUMENT_ID",
+ "PAYMENT_SESSION_ID",
+ "PAYMENT_USER_ID",
+ "X402_ALLOWED_MERCHANTS",
+ "X402_APPROVED_ASSET",
+ "X402_APPROVED_PAY_TO",
+ "X402_MAX_APPROVED_AMOUNT_ATOMIC",
+)
+_AGENTCORE_REGION_ENV = "AGENTCORE_AWS_REGION"
+_AWS_REGION_FALLBACK_ENV = "AWS_REGION"
+_PROXY_ENV_NAMES = (
+ "ALL_PROXY",
+ "HTTPS_PROXY",
+ "HTTP_PROXY",
+ "all_proxy",
+ "https_proxy",
+ "http_proxy",
+)
+_SUPPORTED_AGENTCORE_PAYMENT_REGIONS = frozenset(
+ {
+ "ap-southeast-2",
+ "eu-central-1",
+ "us-east-1",
+ "us-west-2",
+ }
+)
+_SUPPORTED_TESTNET_NETWORKS = frozenset({"eip155:84532"})
+_AGENTCORE_MANAGER_LOGGER = "bedrock_agentcore.payments.manager"
+_PROVIDER_ERROR_CATEGORIES = {
+ "InsufficientBudget": "session_budget_exceeded",
+ "InvalidPaymentInstrument": "payment_instrument_invalid",
+ "PaymentInstrumentNotFound": "payment_instrument_not_found",
+ "PaymentSessionExpired": "payment_session_expired",
+ "PaymentSessionNotFound": "payment_session_not_found",
+}
+_AWS_ERROR_CATEGORIES = {
+ "AccessDeniedException": "aws_access_denied",
+ "ConflictException": "aws_conflict",
+ "InternalServerException": "aws_service_error",
+ "ResourceNotFoundException": "aws_resource_not_found",
+ "ServiceUnavailableException": "aws_service_unavailable",
+ "ThrottlingException": "aws_throttled",
+ "ValidationException": "aws_validation",
+}
+_REQUIREMENT_FIELDS = frozenset(
+ {
+ "scheme",
+ "network",
+ "amount",
+ "asset",
+ "payTo",
+ "maxTimeoutSeconds",
+ "extra",
+ }
+)
+_EXTRA_FIELDS = frozenset(
+ {
+ "name",
+ "version",
+ "decimals",
+ "currency",
+ "merchantDomain",
+ "challengeId",
+ "expiresAt",
+ }
+)
+_CHALLENGE_EXTENSION_FIELDS = frozenset({"bazaar"})
+_BAZAAR_EXTENSION_FIELDS = frozenset({"info", "schema"})
+
+
+def _disable_agentcore_sdk_logging() -> None:
+ logging.getLogger(_AGENTCORE_MANAGER_LOGGER).disabled = True
+
+
+def _safe_symbol(value: object) -> str | None:
+ if not isinstance(value, str) or not 1 <= len(value) <= 64:
+ return None
+ if not value[0].isalpha() or not value.replace("_", "").isalnum():
+ return None
+ return value
+
+
+def _positive_integer_text(value: str) -> bool:
+ """Accept only non-empty ASCII decimal integer text."""
+
+ return bool(value) and value.isascii() and value.isdecimal()
+
+
+def _safe_payment_diagnostics(exc: Exception) -> dict[str, object]:
+ """Extract non-secret failure metadata without rendering exceptions."""
+
+ provider_error_type = _safe_symbol(type(exc).__name__)
+ diagnostics: dict[str, object] = {
+ "stage": "agentcore_process_payment",
+ "category": _PROVIDER_ERROR_CATEGORIES.get(
+ provider_error_type or "",
+ "provider_error",
+ ),
+ "provider_message_logged": False,
+ "request_id_logged": False,
+ }
+ if provider_error_type in _PROVIDER_ERROR_CATEGORIES:
+ diagnostics["provider_error_type"] = provider_error_type
+
+ current: BaseException | None = exc
+ visited: set[int] = set()
+ for _ in range(4):
+ if current is None or id(current) in visited:
+ break
+ visited.add(id(current))
+ response = getattr(current, "response", None)
+ if isinstance(response, Mapping):
+ error = response.get("Error")
+ metadata = response.get("ResponseMetadata")
+ if isinstance(error, Mapping):
+ aws_error_code = _safe_symbol(error.get("Code"))
+ if aws_error_code is not None:
+ diagnostics["aws_error_code"] = aws_error_code
+ diagnostics["category"] = _AWS_ERROR_CATEGORIES.get(
+ aws_error_code,
+ "aws_service_error",
+ )
+ if isinstance(metadata, Mapping):
+ http_status = metadata.get("HTTPStatusCode")
+ if isinstance(http_status, int) and 100 <= http_status <= 599:
+ diagnostics["http_status_code"] = http_status
+ break
+ current = current.__cause__ or current.__context__
+ return diagnostics
+
+
+def _validate_challenge_extensions(extensions: object) -> None:
+ if not isinstance(extensions, dict):
+ raise AgentCorePaymentError(
+ "payment_challenge_extensions_denied",
+ "The merchant challenge contains unsupported extensions.",
+ )
+ if not extensions:
+ return
+ if set(extensions) - _CHALLENGE_EXTENSION_FIELDS:
+ raise AgentCorePaymentError(
+ "payment_challenge_extensions_denied",
+ "The merchant challenge contains unsupported extensions.",
+ )
+ bazaar = extensions.get("bazaar")
+ if (
+ not isinstance(bazaar, dict)
+ or set(bazaar) != _BAZAAR_EXTENSION_FIELDS
+ or not isinstance(bazaar.get("info"), dict)
+ or not isinstance(bazaar.get("schema"), dict)
+ ):
+ raise AgentCorePaymentError(
+ "payment_challenge_extensions_denied",
+ "The merchant challenge contains an invalid Bazaar extension.",
+ )
+
+
+def _resolve_agentcore_region(values: Mapping[str, str]) -> str:
+ """Resolve the payment Region without overriding the model Region."""
+
+ return (
+ values.get(_AGENTCORE_REGION_ENV, "").strip()
+ or values.get(_AWS_REGION_FALLBACK_ENV, "").strip()
+ )
+
+
+class PaymentProcessor(Protocol):
+ """Least-privilege protocol implemented by AgentCore PaymentManager."""
+
+ def process_payment(
+ self,
+ *,
+ payment_session_id: str,
+ payment_instrument_id: str,
+ payment_type: str,
+ payment_input: dict[str, Any],
+ user_id: str | None = None,
+ client_token: str | None = None,
+ payment_connector_id: str | None = None,
+ ) -> dict[str, Any]:
+ """Generate one bounded payment proof."""
+
+
+class AgentCorePaymentsSettings(FrozenModel):
+ """Runtime configuration with identifiers redacted from repr output."""
+
+ enabled: bool = False
+ aws_region: str = Field(min_length=1)
+ payment_manager_arn: SecretStr
+ payment_instrument_id: SecretStr
+ payment_session_id: SecretStr
+ payment_user_id: SecretStr
+ runtime_aws_profile: SecretStr | None = None
+ allowed_merchants: frozenset[str] = Field(min_length=1)
+ approved_asset: str = Field(min_length=1)
+ approved_pay_to: SecretStr = Field(min_length=1)
+ max_approved_amount_atomic: int = Field(gt=0)
+ max_challenge_timeout_seconds: int = Field(default=300, gt=0, le=900)
+ network_preferences: tuple[str, ...] = Field(
+ default=("eip155:84532",),
+ min_length=1,
+ )
+ max_payment_attempts: int = Field(default=2, ge=1, le=3)
+ timeout_seconds: float = Field(default=30.0, gt=0, le=60)
+ max_response_bytes: int = Field(
+ default=1_000_000,
+ ge=1,
+ le=5_000_000,
+ )
+
+ @field_validator("aws_region")
+ @classmethod
+ def validate_agentcore_region(cls, value: str) -> str:
+ """Fail closed when AgentCore Payments is unavailable in a Region."""
+
+ if value not in _SUPPORTED_AGENTCORE_PAYMENT_REGIONS:
+ supported = ", ".join(sorted(_SUPPORTED_AGENTCORE_PAYMENT_REGIONS))
+ raise ValueError(
+ "AgentCore Payments is unavailable in this Region. "
+ f"Use one of: {supported}."
+ )
+ return value
+
+ @field_validator("network_preferences")
+ @classmethod
+ def validate_testnet_networks(
+ cls,
+ value: tuple[str, ...],
+ ) -> tuple[str, ...]:
+ """Prevent configuration from widening this adapter to mainnet."""
+
+ if any(network not in _SUPPORTED_TESTNET_NETWORKS for network in value):
+ raise ValueError(
+ "Only the Base Sepolia testnet network eip155:84532 is allowed."
+ )
+ return value
+
+ @classmethod
+ def from_env(
+ cls,
+ environ: Mapping[str, str] | None = None,
+ ) -> AgentCorePaymentsSettings:
+ """Load settings without printing or persisting their values."""
+
+ values = environ if environ is not None else os.environ
+ aws_region = _resolve_agentcore_region(values)
+ missing = [
+ name for name in _REQUIRED_CONFIGURATION if not values.get(name, "").strip()
+ ]
+ if not aws_region:
+ missing.append(f"{_AGENTCORE_REGION_ENV} (or {_AWS_REGION_FALLBACK_ENV})")
+ if missing:
+ raise AgentCorePaymentError(
+ "agentcore_configuration_missing",
+ "AgentCore Payments configuration is incomplete: " + ", ".join(missing),
+ )
+ if aws_region not in _SUPPORTED_AGENTCORE_PAYMENT_REGIONS:
+ supported = ", ".join(sorted(_SUPPORTED_AGENTCORE_PAYMENT_REGIONS))
+ raise AgentCorePaymentError(
+ "agentcore_region_unsupported",
+ "AgentCore Payments is unavailable in the configured "
+ f"Region. Use one of: {supported}.",
+ )
+
+ allowed_merchants = frozenset(
+ host.strip().lower().rstrip(".")
+ for host in values["X402_ALLOWED_MERCHANTS"].split(",")
+ if host.strip()
+ )
+ network_preferences = tuple(
+ network.strip()
+ for network in values.get(
+ "X402_NETWORK_PREFERENCES",
+ "eip155:84532",
+ ).split(",")
+ if network.strip()
+ )
+ try:
+ max_attempts = int(values.get("X402_MAX_PAYMENT_ATTEMPTS", "2"))
+ except ValueError as exc:
+ raise AgentCorePaymentError(
+ "agentcore_configuration_invalid",
+ "X402_MAX_PAYMENT_ATTEMPTS must be an integer.",
+ ) from exc
+ raw_max_approved_amount_atomic = values[
+ "X402_MAX_APPROVED_AMOUNT_ATOMIC"
+ ].strip()
+ if not _positive_integer_text(raw_max_approved_amount_atomic):
+ raise AgentCorePaymentError(
+ "agentcore_configuration_invalid",
+ "X402_MAX_APPROVED_AMOUNT_ATOMIC must be a positive integer.",
+ )
+ max_approved_amount_atomic = int(raw_max_approved_amount_atomic)
+ if max_approved_amount_atomic <= 0:
+ raise AgentCorePaymentError(
+ "agentcore_configuration_invalid",
+ "X402_MAX_APPROVED_AMOUNT_ATOMIC must be a positive integer.",
+ )
+ try:
+ max_challenge_timeout_seconds = int(
+ values.get("X402_MAX_CHALLENGE_TIMEOUT_SECONDS", "300")
+ )
+ except ValueError as exc:
+ raise AgentCorePaymentError(
+ "agentcore_configuration_invalid",
+ "X402_MAX_CHALLENGE_TIMEOUT_SECONDS must be an integer.",
+ ) from exc
+
+ return cls(
+ enabled=values.get("ALLOW_AGENTCORE_TESTNET") == "1",
+ aws_region=aws_region,
+ payment_manager_arn=values["PAYMENT_MANAGER_ARN"].strip(),
+ payment_instrument_id=values["PAYMENT_INSTRUMENT_ID"].strip(),
+ payment_session_id=values["PAYMENT_SESSION_ID"].strip(),
+ payment_user_id=values["PAYMENT_USER_ID"].strip(),
+ runtime_aws_profile=(
+ values.get("AGENTCORE_RUNTIME_AWS_PROFILE", "").strip() or None
+ ),
+ allowed_merchants=allowed_merchants,
+ approved_asset=values["X402_APPROVED_ASSET"].strip(),
+ approved_pay_to=values["X402_APPROVED_PAY_TO"].strip(),
+ max_approved_amount_atomic=max_approved_amount_atomic,
+ max_challenge_timeout_seconds=(max_challenge_timeout_seconds),
+ network_preferences=network_preferences,
+ max_payment_attempts=max_attempts,
+ )
+
+
+class AgentCoreFetchResult(FrozenModel):
+ """Sanitized result; payment proof and configured IDs are excluded."""
+
+ status_code: int
+ content_type: str | None = None
+ response_sha256: str = Field(pattern=r"^[0-9a-f]{64}$")
+ response_bytes: int = Field(ge=0)
+ payment_attempted: bool
+ payment_attempts: int = Field(ge=0)
+ merchant: str
+
+
+class AgentCorePaymentChallenge(FrozenModel):
+ """Sanitized, validated challenge presented to application policy."""
+
+ resource_url: str
+ resource_description: str
+ resource_mime_type: str
+ merchant: str
+ x402_version: Literal[2] = 2
+ scheme: Literal["exact"] = "exact"
+ network: Literal["eip155:84532"]
+ asset: str
+ pay_to: SecretStr
+ max_timeout_seconds: int = Field(gt=0)
+ amount_atomic: int = Field(gt=0)
+ amount: Decimal = Field(gt=0)
+ currency: Literal["USDC"] = "USDC"
+ asset_version: Literal["2"] = "2"
+ decimals: Literal[6] | None = None
+ merchant_domain: str | None = None
+ challenge_id: str | None = None
+ expires_at: datetime | None = None
+
+ def provider_requirement(self) -> dict[str, Any]:
+ """Construct provider input only from approved canonical fields."""
+
+ extra: dict[str, Any] = {
+ "name": self.currency,
+ "version": self.asset_version,
+ }
+ if self.decimals is not None:
+ extra["decimals"] = self.decimals
+ if self.merchant_domain is not None:
+ extra["merchantDomain"] = self.merchant_domain
+ if self.challenge_id is not None:
+ extra["challengeId"] = self.challenge_id
+ if self.expires_at is not None:
+ extra["expiresAt"] = self.expires_at.isoformat()
+ return {
+ "scheme": self.scheme,
+ "network": self.network,
+ "amount": str(self.amount_atomic),
+ "asset": self.asset,
+ "payTo": self.pay_to.get_secret_value(),
+ "maxTimeoutSeconds": self.max_timeout_seconds,
+ "extra": extra,
+ }
+
+ def provider_resource(self) -> dict[str, str]:
+ """Construct the signed resource from validated canonical fields."""
+
+ return {
+ "url": self.resource_url,
+ "description": self.resource_description,
+ "mimeType": self.resource_mime_type,
+ }
+
+
+Resolver = Callable[[str], list[str]]
+ClientFactory = Callable[[], httpx.Client]
+AuthorizationCallback = Callable[[AgentCorePaymentChallenge], None]
+PaymentsClock = Callable[[], datetime]
+
+
+def _utc_now() -> datetime:
+ return datetime.now(UTC)
+
+
+def _resolve_addresses(host: str) -> list[str]:
+ return sorted(
+ {
+ item[4][0]
+ for item in socket.getaddrinfo(
+ host,
+ 443,
+ type=socket.SOCK_STREAM,
+ )
+ }
+ )
+
+
+def _reject_proxy_environment(
+ environ: Mapping[str, str] | None = None,
+) -> None:
+ values = environ if environ is not None else os.environ
+ configured = [name for name in _PROXY_ENV_NAMES if values.get(name, "").strip()]
+ if configured:
+ raise AgentCorePaymentError(
+ "merchant_proxy_unsupported",
+ "Proxy-based merchant networking is not supported by the "
+ "DNS-pinned live path. Unset HTTP_PROXY, HTTPS_PROXY, and "
+ "ALL_PROXY variants before the approved testnet run.",
+ )
+
+
+def _proxy_environment_clear(environ: Mapping[str, str]) -> bool:
+ return not any(environ.get(name, "").strip() for name in _PROXY_ENV_NAMES)
+
+
+class AgentCoreX402Client:
+ """Fetch an allowlisted testnet resource using AgentCore Payments.
+
+ This adapter does not decide whether a purchase is justified. The caller
+ must supply an application-owned authorization callback. The adapter
+ invokes it with the validated HTTP 402 challenge before requesting a
+ payment header from AgentCore Payments.
+ """
+
+ def __init__(
+ self,
+ settings: AgentCorePaymentsSettings,
+ *,
+ manager: PaymentProcessor | None = None,
+ client_factory: ClientFactory | None = None,
+ resolver: Resolver | None = None,
+ authorize_challenge: AuthorizationCallback | None = None,
+ clock: PaymentsClock = _utc_now,
+ ) -> None:
+ self.settings = settings
+ self._manager = manager
+ self._client_factory = client_factory or self._default_client
+ self._resolver = resolver or _resolve_addresses
+ self._authorize_challenge = authorize_challenge
+ self._clock = clock
+
+ def fetch(
+ self,
+ resource_url: str,
+ *,
+ client_token: str,
+ ) -> AgentCoreFetchResult:
+ """Perform one explicitly enabled x402 GET with bounded retries."""
+
+ if not self.settings.enabled:
+ raise LivePaymentDisabled(
+ "agentcore_testnet_disabled",
+ "Set ALLOW_AGENTCORE_TESTNET=1 only after the payment "
+ "session, allowlist, approval, and testnet funding are ready.",
+ )
+ if len(client_token.strip()) < 8:
+ raise AgentCorePaymentError(
+ "idempotency_token_invalid",
+ "The client token must contain at least eight characters.",
+ )
+ if self._authorize_challenge is None:
+ raise AgentCorePaymentError(
+ "application_authorization_missing",
+ "Application-owned challenge authorization is required "
+ "before AgentCore Payments can generate a payment header.",
+ )
+
+ merchant = self._validated_merchant(resource_url)
+ response = self._request(resource_url, merchant=merchant)
+ if response.status_code != 402:
+ return self._result(
+ response,
+ merchant=merchant,
+ payment_attempts=0,
+ )
+
+ approved_challenge: AgentCorePaymentChallenge | None = None
+ for attempt in range(1, self.settings.max_payment_attempts + 1):
+ challenge = self._validate_payment_challenge(
+ response,
+ resource_url=resource_url,
+ merchant=merchant,
+ )
+ if approved_challenge is None:
+ approved_challenge = challenge
+ elif challenge != approved_challenge:
+ raise AgentCorePaymentError(
+ "payment_challenge_changed",
+ "The merchant changed the payment challenge during the "
+ "approved retry sequence.",
+ )
+ self._authorize_challenge(challenge)
+ payment_headers = self._generate_payment_headers(
+ challenge=challenge,
+ client_token=client_token,
+ )
+ response = self._request(
+ resource_url,
+ merchant=merchant,
+ headers=payment_headers,
+ )
+ if response.status_code != 402:
+ return self._result(
+ response,
+ merchant=merchant,
+ payment_attempts=attempt,
+ )
+
+ raise AgentCorePaymentError(
+ "payment_attempts_exhausted",
+ "The approved merchant continued to require payment after the "
+ "configured testnet retry limit.",
+ )
+
+ def _validate_payment_challenge(
+ self,
+ response: httpx.Response,
+ *,
+ resource_url: str,
+ merchant: str,
+ ) -> AgentCorePaymentChallenge:
+ """Validate the payable requirement before asking AWS to sign it."""
+
+ challenge = self._decode_payment_challenge(response)
+ resource = challenge.get("resource")
+ if not isinstance(resource, dict):
+ raise AgentCorePaymentError(
+ "payment_challenge_resource_invalid",
+ "The merchant challenge does not identify the approved resource.",
+ )
+ if resource.get("url") != resource_url:
+ raise AgentCorePaymentError(
+ "payment_challenge_resource_mismatch",
+ "The merchant challenge refers to a different resource.",
+ )
+ resource_description = resource.get("description")
+ resource_mime_type = resource.get("mimeType")
+ if (
+ not isinstance(resource_description, str)
+ or len(resource_description) > 1_024
+ or not isinstance(resource_mime_type, str)
+ or not 1 <= len(resource_mime_type) <= 255
+ ):
+ raise AgentCorePaymentError(
+ "payment_challenge_resource_invalid",
+ "The merchant challenge contains invalid resource metadata.",
+ )
+ _validate_challenge_extensions(challenge.get("extensions", {}))
+
+ requirements = challenge["accepts"]
+ candidates = [
+ item
+ for item in requirements
+ if item.get("network") in self.settings.network_preferences
+ ]
+ if not candidates:
+ raise AgentCorePaymentError(
+ "payment_challenge_network_denied",
+ "The merchant challenge does not offer an approved testnet network.",
+ )
+ if len(candidates) != 1:
+ raise AgentCorePaymentError(
+ "payment_challenge_ambiguous",
+ "The merchant challenge contains more than one payable "
+ "requirement for an approved network.",
+ )
+
+ requirement = candidates[0]
+ if set(requirement) - _REQUIREMENT_FIELDS:
+ raise AgentCorePaymentError(
+ "payment_challenge_fields_denied",
+ "The merchant challenge contains unsupported payment fields.",
+ )
+ if requirement.get("scheme") != "exact":
+ raise AgentCorePaymentError(
+ "payment_challenge_scheme_denied",
+ "The merchant challenge does not use the approved exact "
+ "payment scheme.",
+ )
+
+ asset = requirement.get("asset")
+ if (
+ not isinstance(asset, str)
+ or asset.lower() != self.settings.approved_asset.lower()
+ ):
+ raise AgentCorePaymentError(
+ "payment_challenge_asset_denied",
+ "The merchant challenge does not use the approved asset.",
+ )
+
+ pay_to = requirement.get("payTo")
+ if (
+ not isinstance(pay_to, str)
+ or pay_to != self.settings.approved_pay_to.get_secret_value()
+ ):
+ raise AgentCorePaymentError(
+ "payment_challenge_recipient_denied",
+ "The merchant challenge does not use the "
+ "application-approved recipient.",
+ )
+
+ max_timeout_seconds = requirement.get("maxTimeoutSeconds")
+ if (
+ type(max_timeout_seconds) is not int
+ or max_timeout_seconds <= 0
+ or max_timeout_seconds > self.settings.max_challenge_timeout_seconds
+ ):
+ raise AgentCorePaymentError(
+ "payment_challenge_timeout_denied",
+ "The merchant challenge exceeds the application-approved timeout.",
+ )
+
+ extra = requirement.get("extra")
+ if (
+ not isinstance(extra, dict)
+ or set(extra) - _EXTRA_FIELDS
+ or extra.get("name") != "USDC"
+ or extra.get("version") != "2"
+ ):
+ raise AgentCorePaymentError(
+ "payment_challenge_asset_denied",
+ "The merchant challenge does not identify the approved USDC asset.",
+ )
+
+ decimals = extra.get("decimals")
+ if decimals is not None and decimals != 6:
+ raise AgentCorePaymentError(
+ "payment_challenge_asset_denied",
+ "The merchant challenge uses unsupported asset decimals.",
+ )
+ currency = extra.get("currency")
+ if currency is not None and currency != "USDC":
+ raise AgentCorePaymentError(
+ "payment_challenge_asset_denied",
+ "The merchant challenge uses an unsupported currency.",
+ )
+ merchant_domain = extra.get("merchantDomain")
+ if merchant_domain is not None and merchant_domain != merchant:
+ raise AgentCorePaymentError(
+ "payment_challenge_merchant_mismatch",
+ "The merchant challenge identity does not match the "
+ "approved resource host.",
+ )
+ challenge_id = extra.get("challengeId")
+ if challenge_id is not None and (
+ not isinstance(challenge_id, str) or not 1 <= len(challenge_id) <= 256
+ ):
+ raise AgentCorePaymentError(
+ "payment_challenge_invalid",
+ "The merchant challenge identifier is invalid.",
+ )
+
+ expires_at: datetime | None = None
+ raw_expires_at = extra.get("expiresAt")
+ if raw_expires_at is not None:
+ if not isinstance(raw_expires_at, str):
+ raise AgentCorePaymentError(
+ "payment_challenge_expiry_invalid",
+ "The merchant challenge expiry is invalid.",
+ )
+ try:
+ expires_at = datetime.fromisoformat(raw_expires_at)
+ except ValueError:
+ raise AgentCorePaymentError(
+ "payment_challenge_expiry_invalid",
+ "The merchant challenge expiry is invalid.",
+ ) from None
+ if expires_at.tzinfo is None:
+ raise AgentCorePaymentError(
+ "payment_challenge_expiry_invalid",
+ "The merchant challenge expiry is invalid.",
+ )
+ now = self._clock()
+ if now >= expires_at:
+ raise AgentCorePaymentError(
+ "payment_challenge_expired",
+ "The merchant payment challenge has expired.",
+ )
+ if expires_at > now + timedelta(
+ seconds=self.settings.max_challenge_timeout_seconds
+ ):
+ raise AgentCorePaymentError(
+ "payment_challenge_expiry_denied",
+ "The merchant challenge expiry exceeds the "
+ "application-approved lifetime.",
+ )
+
+ amount = requirement.get("amount")
+ if not isinstance(amount, str) or not amount.isdecimal() or len(amount) > 32:
+ raise AgentCorePaymentError(
+ "payment_challenge_amount_invalid",
+ "The merchant challenge amount is invalid.",
+ )
+ amount_atomic = int(amount)
+ if amount_atomic <= 0:
+ raise AgentCorePaymentError(
+ "payment_challenge_amount_invalid",
+ "The merchant challenge amount is invalid.",
+ )
+ if amount_atomic > self.settings.max_approved_amount_atomic:
+ raise AgentCorePaymentError(
+ "payment_challenge_amount_exceeds_approval",
+ "The merchant challenge exceeds the application-approved "
+ "maximum amount.",
+ )
+ return AgentCorePaymentChallenge(
+ resource_url=resource_url,
+ resource_description=resource_description,
+ resource_mime_type=resource_mime_type,
+ merchant=merchant,
+ network=requirement["network"],
+ asset=asset,
+ pay_to=pay_to,
+ max_timeout_seconds=max_timeout_seconds,
+ amount_atomic=amount_atomic,
+ amount=Decimal(amount_atomic) / Decimal(1_000_000),
+ decimals=decimals,
+ merchant_domain=merchant_domain,
+ challenge_id=challenge_id,
+ expires_at=expires_at,
+ )
+
+ def _decode_payment_challenge(
+ self,
+ response: httpx.Response,
+ ) -> dict[str, Any]:
+ """Decode the x402 v2 challenge without retaining proof material."""
+
+ encoded = response.headers.get("payment-required", "").strip()
+ if not encoded:
+ raise AgentCorePaymentError(
+ "payment_challenge_missing",
+ "The approved merchant returned HTTP 402 without a "
+ "PAYMENT-REQUIRED challenge.",
+ )
+ if len(encoded) > 32_768:
+ raise AgentCorePaymentError(
+ "payment_challenge_invalid",
+ "The PAYMENT-REQUIRED challenge is invalid.",
+ )
+
+ padded = encoded + "=" * (-len(encoded) % 4)
+ try:
+ decoded = base64.b64decode(
+ padded,
+ altchars=b"-_",
+ validate=True,
+ )
+ challenge = json.loads(decoded)
+ except (binascii.Error, UnicodeDecodeError, json.JSONDecodeError):
+ raise AgentCorePaymentError(
+ "payment_challenge_invalid",
+ "The PAYMENT-REQUIRED challenge is invalid.",
+ ) from None
+
+ if (
+ not isinstance(challenge, dict)
+ or challenge.get("x402Version") != 2
+ or not isinstance(challenge.get("accepts"), list)
+ ):
+ raise AgentCorePaymentError(
+ "payment_challenge_invalid",
+ "The PAYMENT-REQUIRED challenge is invalid.",
+ )
+
+ requirements = challenge["accepts"]
+ if any(not isinstance(item, dict) for item in requirements):
+ raise AgentCorePaymentError(
+ "payment_challenge_invalid",
+ "The PAYMENT-REQUIRED challenge is invalid.",
+ )
+ return challenge
+
+ def _default_client(self) -> httpx.Client:
+ _reject_proxy_environment()
+ return httpx.Client(
+ timeout=self.settings.timeout_seconds,
+ follow_redirects=False,
+ verify=True,
+ trust_env=False,
+ headers={"User-Agent": ("openai-agentcore-payments-cookbook/0.1")},
+ )
+
+ def _request(
+ self,
+ resource_url: str,
+ *,
+ merchant: str,
+ headers: Mapping[str, str] | None = None,
+ ) -> httpx.Response:
+ pinned_url = self._pinned_resource_url(resource_url, merchant=merchant)
+ request_headers = dict(headers or {})
+ request_headers["Host"] = merchant
+ try:
+ with (
+ self._client_factory() as client,
+ client.stream(
+ "GET",
+ pinned_url,
+ headers=request_headers,
+ extensions={"sni_hostname": merchant},
+ ) as streamed,
+ ):
+ content = bytearray()
+ for chunk in streamed.iter_bytes():
+ content.extend(chunk)
+ if len(content) > self.settings.max_response_bytes:
+ raise AgentCorePaymentError(
+ "merchant_response_too_large",
+ "The approved merchant response exceeded "
+ "the configured size limit.",
+ )
+ response = httpx.Response(
+ status_code=streamed.status_code,
+ headers=streamed.headers,
+ content=bytes(content),
+ request=streamed.request,
+ extensions=streamed.extensions,
+ )
+ except httpx.HTTPError:
+ raise AgentCorePaymentError(
+ "merchant_request_failed",
+ "The approved testnet merchant request failed.",
+ ) from None
+ return response
+
+ def _generate_payment_headers(
+ self,
+ *,
+ challenge: AgentCorePaymentChallenge,
+ client_token: str,
+ ) -> dict[str, str]:
+ manager = self._manager or self._build_manager()
+ if challenge.expires_at is not None and self._clock() >= (challenge.expires_at):
+ raise AgentCorePaymentError(
+ "payment_challenge_expired",
+ "The merchant payment challenge expired before proof generation.",
+ )
+ selected_accept = challenge.provider_requirement()
+ try:
+ payment_result = manager.process_payment(
+ payment_session_id=(
+ self.settings.payment_session_id.get_secret_value()
+ ),
+ payment_instrument_id=(
+ self.settings.payment_instrument_id.get_secret_value()
+ ),
+ payment_type="CRYPTO_X402",
+ payment_input={
+ "cryptoX402": {
+ "version": "2",
+ "payload": selected_accept,
+ }
+ },
+ user_id=(self.settings.payment_user_id.get_secret_value()),
+ client_token=client_token,
+ )
+ # Preview SDK implementations can surface provider-specific exception
+ # types; normalize them without exposing credential-adjacent details.
+ except Exception as exc: # noqa: BLE001
+ diagnostics = _safe_payment_diagnostics(exc)
+ if type(exc).__name__ == "InsufficientBudget":
+ raise AgentCorePaymentError(
+ "payment_session_budget_exceeded",
+ "AgentCore Payments rejected the testnet payment "
+ "because it exceeded the bounded session budget.",
+ diagnostics=diagnostics,
+ ) from None
+ raise AgentCorePaymentError(
+ "payment_header_generation_failed",
+ "AgentCore Payments could not generate a testnet payment header.",
+ diagnostics=diagnostics,
+ ) from None
+
+ if not isinstance(payment_result, dict):
+ raise AgentCorePaymentError(
+ "payment_header_invalid",
+ "AgentCore Payments returned an invalid testnet proof.",
+ )
+ payment_output = payment_result.get("paymentOutput")
+ crypto_x402 = (
+ payment_output.get("cryptoX402")
+ if isinstance(payment_output, dict)
+ else None
+ )
+ proof_payload = (
+ crypto_x402.get("payload") if isinstance(crypto_x402, dict) else None
+ )
+ if (
+ payment_result.get("status") != "PROOF_GENERATED"
+ or not isinstance(crypto_x402, dict)
+ or crypto_x402.get("version") != "2"
+ or not isinstance(proof_payload, dict)
+ or not proof_payload
+ ):
+ raise AgentCorePaymentError(
+ "payment_header_invalid",
+ "AgentCore Payments returned an invalid testnet proof.",
+ )
+ signature = {
+ "x402Version": 2,
+ "resource": challenge.provider_resource(),
+ "accepted": selected_accept,
+ "extensions": {},
+ "payload": proof_payload,
+ }
+ encoded = base64.b64encode(
+ json.dumps(signature, separators=(",", ":")).encode("utf-8")
+ ).decode("ascii")
+ generated = {"PAYMENT-SIGNATURE": encoded}
+ if any(
+ name.lower() not in _PAYMENT_HEADER_NAMES
+ or not isinstance(value, str)
+ or not value
+ for name, value in generated.items()
+ ):
+ raise AgentCorePaymentError(
+ "payment_header_invalid",
+ "AgentCore Payments returned an unsupported payment header.",
+ )
+ return generated
+
+ def _build_manager(self) -> PaymentProcessor:
+ try:
+ from bedrock_agentcore.payments import PaymentManager
+ except ImportError:
+ raise AgentCorePaymentError(
+ "agentcore_sdk_missing",
+ "Install the pinned AgentCore adapter dependency with "
+ "`uv sync --extra agentcore --group dev`.",
+ ) from None
+
+ _disable_agentcore_sdk_logging()
+ try:
+ boto3_session = None
+ if self.settings.runtime_aws_profile is not None:
+ import boto3
+
+ boto3_session = boto3.Session(
+ profile_name=(self.settings.runtime_aws_profile.get_secret_value()),
+ region_name=self.settings.aws_region,
+ )
+ return PaymentManager(
+ payment_manager_arn=(
+ self.settings.payment_manager_arn.get_secret_value()
+ ),
+ region_name=self.settings.aws_region,
+ boto3_session=boto3_session,
+ )
+ # Keep the adapter fail-closed across preview SDK exception variants.
+ except Exception: # noqa: BLE001
+ raise AgentCorePaymentError(
+ "payment_manager_initialization_failed",
+ "AgentCore PaymentManager initialization failed.",
+ ) from None
+
+ def _validated_merchant(self, resource_url: str) -> str:
+ parsed = urlsplit(resource_url)
+ host = (parsed.hostname or "").lower().rstrip(".")
+ try:
+ port = parsed.port
+ except ValueError:
+ raise AgentCorePaymentError(
+ "https_resource_required",
+ "The AgentCore testnet adapter accepts only HTTPS resources "
+ "without embedded credentials or nonstandard ports.",
+ ) from None
+ if (
+ parsed.scheme != "https"
+ or not host
+ or parsed.username is not None
+ or parsed.password is not None
+ or port not in (None, 443)
+ ):
+ raise AgentCorePaymentError(
+ "https_resource_required",
+ "The AgentCore testnet adapter accepts only HTTPS resources "
+ "without embedded credentials or nonstandard ports.",
+ )
+ if host not in self.settings.allowed_merchants:
+ raise AgentCorePaymentError(
+ "merchant_not_allowed",
+ "The resource host is not in the exact merchant allowlist.",
+ )
+
+ return host
+
+ def _pinned_resource_url(
+ self,
+ resource_url: str,
+ *,
+ merchant: str,
+ ) -> str:
+ """Resolve, validate, and pin one address for this request."""
+
+ try:
+ addresses = self._resolver(merchant)
+ except OSError:
+ raise AgentCorePaymentError(
+ "merchant_resolution_failed",
+ "The approved merchant hostname could not be resolved.",
+ ) from None
+ if not addresses:
+ raise AgentCorePaymentError(
+ "merchant_resolution_failed",
+ "The approved merchant hostname returned no addresses.",
+ )
+ validated: list[ipaddress.IPv4Address | ipaddress.IPv6Address] = []
+ for address in addresses:
+ try:
+ ip = ipaddress.ip_address(address)
+ except ValueError:
+ raise AgentCorePaymentError(
+ "merchant_address_invalid",
+ "The approved merchant resolved to an invalid address.",
+ ) from None
+ if not ip.is_global:
+ raise AgentCorePaymentError(
+ "private_merchant_address_denied",
+ "The approved merchant resolved to a non-public address.",
+ )
+ validated.append(ip)
+
+ selected = min(
+ validated,
+ key=lambda item: (item.version, item.packed),
+ )
+ netloc = f"[{selected}]" if selected.version == 6 else str(selected)
+ parsed = urlsplit(resource_url)
+ return urlunsplit(
+ (
+ parsed.scheme,
+ netloc,
+ parsed.path,
+ parsed.query,
+ parsed.fragment,
+ )
+ )
+
+ @staticmethod
+ def _result(
+ response: httpx.Response,
+ *,
+ merchant: str,
+ payment_attempts: int,
+ ) -> AgentCoreFetchResult:
+ content = response.content
+ return AgentCoreFetchResult(
+ status_code=response.status_code,
+ content_type=response.headers.get("content-type"),
+ response_sha256=hashlib.sha256(content).hexdigest(),
+ response_bytes=len(content),
+ payment_attempted=payment_attempts > 0,
+ payment_attempts=payment_attempts,
+ merchant=merchant,
+ )
diff --git a/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/agentcore_runtime.py b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/agentcore_runtime.py
new file mode 100644
index 00000000..521db8ae
--- /dev/null
+++ b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/agentcore_runtime.py
@@ -0,0 +1,80 @@
+"""No-call construction helpers for the live AgentCore testnet path."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from datetime import UTC, datetime, timedelta
+from decimal import Decimal
+
+from .agentcore_application import AgentCoreAuthorizedApplication
+from .agentcore_payments import (
+ AgentCorePaymentsSettings,
+ AgentCoreX402Client,
+ AuthorizationCallback,
+)
+from .models import ApprovalGrant, CommercePolicy, PurchaseRequest
+from .policy import PolicyEngine
+
+
+@dataclass(frozen=True)
+class LiveAgentCoreContext:
+ application: AgentCoreAuthorizedApplication
+ request: PurchaseRequest
+ approval: ApprovalGrant
+
+
+def build_live_agentcore_context(
+ settings: AgentCorePaymentsSettings,
+ *,
+ resource_url: str,
+ idempotency_key: str,
+ purpose: str,
+ now: datetime | None = None,
+) -> LiveAgentCoreContext:
+ """Build exact-scope policy and approval without making a live call."""
+
+ now = now or datetime.now(UTC)
+ amount = Decimal(settings.max_approved_amount_atomic) / Decimal(1_000_000)
+ request = PurchaseRequest(
+ request_id="request-agentcore-testnet-smoke",
+ resource_url=resource_url,
+ purpose=purpose,
+ idempotency_key=idempotency_key,
+ )
+ approval = ApprovalGrant(
+ approval_id="approval-agentcore-testnet-smoke",
+ request_id=request.request_id,
+ resource_url=request.resource_url,
+ purpose=request.purpose,
+ maximum_amount=amount,
+ approved_by="interactive-testnet-operator",
+ approved_at=now,
+ expires_at=now + timedelta(minutes=5),
+ )
+ policy = PolicyEngine(
+ CommercePolicy(
+ allowed_merchants=settings.allowed_merchants,
+ allowed_purposes=frozenset({purpose}),
+ per_request_limit=amount,
+ per_run_limit=amount,
+ approval_threshold=Decimal(0),
+ session_expires_at=now + timedelta(minutes=10),
+ )
+ )
+
+ def client_factory(
+ authorize_challenge: AuthorizationCallback,
+ ) -> AgentCoreX402Client:
+ return AgentCoreX402Client(
+ settings,
+ authorize_challenge=authorize_challenge,
+ )
+
+ return LiveAgentCoreContext(
+ application=AgentCoreAuthorizedApplication(
+ policy=policy,
+ client_factory=client_factory,
+ ),
+ request=request,
+ approval=approval,
+ )
diff --git a/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/agentcore_session.py b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/agentcore_session.py
new file mode 100644
index 00000000..96ca7812
--- /dev/null
+++ b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/agentcore_session.py
@@ -0,0 +1,502 @@
+"""Fail-closed lifecycle helper for one bounded AgentCore payment session."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import re
+import threading
+import uuid
+from collections.abc import Callable, Iterator, Mapping, Sequence
+from contextlib import contextmanager
+from decimal import Decimal, InvalidOperation
+from pathlib import Path
+from typing import Any, Protocol
+
+try:
+ import fcntl
+except ImportError:
+ fcntl = None
+
+from .agentcore_payments import (
+ _SUPPORTED_AGENTCORE_PAYMENT_REGIONS,
+ _disable_agentcore_sdk_logging,
+ _resolve_agentcore_region,
+)
+from .errors import AgentCorePaymentError
+
+_SESSION_ADMIN_OPT_IN = "ALLOW_AGENTCORE_SESSION_ADMIN"
+_SESSION_FILE_ENV = "AGENTCORE_SESSION_FILE"
+_DEFAULT_SESSION_FILE = Path(".agentcore-session.env")
+_MAX_SESSION_BUDGET_USD = Decimal("0.01")
+_MIN_SESSION_MINUTES = 15
+_MAX_SESSION_MINUTES = 60
+_SESSION_STATE_KEYS = {
+ "PAYMENT_SESSION_CLIENT_TOKEN",
+ "PAYMENT_SESSION_ID",
+}
+_SESSION_STATE_VALUE = re.compile(r"[A-Za-z0-9._:@/+,=-]+")
+_PROCESS_SESSION_LOCK = threading.Lock()
+
+
+class PaymentSessionManager(Protocol):
+ """Narrow AgentCore PaymentManager session interface."""
+
+ def create_payment_session(
+ self,
+ *,
+ expiry_time_in_minutes: int,
+ user_id: str | None = None,
+ limits: dict[str, Any] | None = None,
+ client_token: str | None = None,
+ ) -> dict[str, Any]: ...
+
+ def delete_payment_session(
+ self,
+ payment_session_id: str,
+ user_id: str | None = None,
+ ) -> dict[str, Any]: ...
+
+
+TokenFactory = Callable[[], str]
+
+
+def parse_budget(raw: str) -> Decimal:
+ """Parse a positive USD session ceiling no greater than one cent."""
+
+ try:
+ value = Decimal(raw)
+ except (InvalidOperation, ValueError) as exc:
+ raise argparse.ArgumentTypeError("budget must be a decimal amount") from exc
+ if not value.is_finite() or value <= 0 or value > _MAX_SESSION_BUDGET_USD:
+ raise argparse.ArgumentTypeError(
+ "budget must be greater than 0 and no greater than 0.01 USD"
+ )
+ return value
+
+
+def _session_file(
+ environ: Mapping[str, str],
+ override: Path | None,
+) -> Path:
+ if override is not None:
+ return override
+ configured = environ.get(_SESSION_FILE_ENV, "").strip()
+ return Path(configured) if configured else _DEFAULT_SESSION_FILE
+
+
+def _read_session_state(path: Path) -> dict[str, str]:
+ if not path.exists():
+ return {}
+ state: dict[str, str] = {}
+ for line in path.read_text(encoding="utf-8").splitlines():
+ if not line.strip():
+ continue
+ name, separator, value = line.partition("=")
+ if (
+ not separator
+ or name not in _SESSION_STATE_KEYS
+ or name in state
+ or not _SESSION_STATE_VALUE.fullmatch(value)
+ ):
+ raise AgentCorePaymentError(
+ "payment_session_state_invalid",
+ "The local payment-session state file is invalid.",
+ )
+ state[name] = value
+ return state
+
+
+def _write_session_state(path: Path, state: Mapping[str, str]) -> None:
+ lines = []
+ for name, value in state.items():
+ if name not in _SESSION_STATE_KEYS or not _SESSION_STATE_VALUE.fullmatch(value):
+ raise AgentCorePaymentError(
+ "payment_session_state_invalid",
+ "The payment-session state contains an invalid value.",
+ )
+ lines.append(f"{name}={value}\n")
+ flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC
+ if hasattr(os, "O_NOFOLLOW"):
+ flags |= os.O_NOFOLLOW
+ descriptor: int | None = None
+ try:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ descriptor = os.open(path, flags, 0o600)
+ handle = os.fdopen(descriptor, "w", encoding="utf-8")
+ descriptor = None
+ with handle:
+ os.fchmod(handle.fileno(), 0o600)
+ handle.writelines(lines)
+ except OSError:
+ if descriptor is not None:
+ os.close(descriptor)
+ raise AgentCorePaymentError(
+ "payment_session_state_write_failed",
+ "The local payment-session state file could not be written.",
+ ) from None
+
+
+@contextmanager
+def _session_lock(path: Path) -> Iterator[None]:
+ """Serialize session lifecycle changes across threads and processes."""
+
+ if fcntl is None:
+ raise AgentCorePaymentError(
+ "payment_session_platform_unsupported",
+ "Live payment-session administration requires POSIX file locking. "
+ "The offline notebook path remains available on this platform.",
+ )
+
+ path.parent.mkdir(parents=True, exist_ok=True)
+ lock_path = Path(f"{path}.lock")
+ flags = os.O_RDWR | os.O_CREAT
+ if hasattr(os, "O_NOFOLLOW"):
+ flags |= os.O_NOFOLLOW
+ try:
+ descriptor = os.open(lock_path, flags, 0o600)
+ os.fchmod(descriptor, 0o600)
+ except OSError:
+ raise AgentCorePaymentError(
+ "payment_session_lock_failed",
+ "The local payment-session lock could not be acquired.",
+ ) from None
+
+ with (
+ os.fdopen(descriptor, "a+", encoding="utf-8") as handle,
+ _PROCESS_SESSION_LOCK,
+ ):
+ try:
+ fcntl.flock(handle.fileno(), fcntl.LOCK_EX)
+ except OSError:
+ raise AgentCorePaymentError(
+ "payment_session_lock_failed",
+ "The local payment-session lock could not be acquired.",
+ ) from None
+ try:
+ yield
+ finally:
+ fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
+
+
+def _delete_unpersisted_session(
+ manager: PaymentSessionManager,
+ *,
+ session_id: str,
+ user_id: str,
+ path: Path,
+ client_token: str,
+) -> None:
+ """Delete a session if its identifier cannot be persisted safely."""
+
+ try:
+ deletion = manager.delete_payment_session(
+ payment_session_id=session_id,
+ user_id=user_id,
+ )
+ except Exception: # noqa: BLE001
+ deletion = {}
+ if str(deletion.get("status", "")).upper() == "DELETED":
+ try:
+ path.unlink(missing_ok=True)
+ except OSError:
+ pass
+ return
+
+ recovery_recorded = False
+ try:
+ _write_session_state(
+ path,
+ {
+ "PAYMENT_SESSION_CLIENT_TOKEN": client_token,
+ "PAYMENT_SESSION_ID": session_id,
+ },
+ )
+ recovery_recorded = True
+ except AgentCorePaymentError:
+ pass
+ raise AgentCorePaymentError(
+ "payment_session_persistence_cleanup_failed",
+ "AgentCore created a payment session, but local persistence and "
+ "automatic deletion did not both complete. Do not create another "
+ "session until an administrator verifies cleanup.",
+ diagnostics={"local_recovery_recorded": recovery_recorded},
+ )
+
+
+def _require_session_admin(environ: Mapping[str, str]) -> None:
+ if environ.get(_SESSION_ADMIN_OPT_IN) != "1":
+ raise AgentCorePaymentError(
+ "payment_session_admin_disabled",
+ f"Set {_SESSION_ADMIN_OPT_IN}=1 only for an approved "
+ "testnet session create or delete operation.",
+ )
+
+
+def _required_runtime(
+ environ: Mapping[str, str],
+) -> tuple[str, str, str]:
+ manager_arn = environ.get("PAYMENT_MANAGER_ARN", "").strip()
+ user_id = environ.get("PAYMENT_USER_ID", "").strip()
+ region = _resolve_agentcore_region(environ)
+ missing = []
+ if not manager_arn:
+ missing.append("PAYMENT_MANAGER_ARN")
+ if not user_id:
+ missing.append("PAYMENT_USER_ID")
+ if not region:
+ missing.append("AGENTCORE_AWS_REGION")
+ if missing:
+ raise AgentCorePaymentError(
+ "payment_session_configuration_missing",
+ "Payment-session configuration is incomplete: " + ", ".join(missing),
+ )
+ if region not in _SUPPORTED_AGENTCORE_PAYMENT_REGIONS:
+ raise AgentCorePaymentError(
+ "agentcore_region_unsupported",
+ "AgentCore Payments is unavailable in the configured Region.",
+ )
+ return manager_arn, user_id, region
+
+
+def create_bounded_session(
+ manager: PaymentSessionManager,
+ *,
+ environ: Mapping[str, str],
+ session_file: Path | None = None,
+ budget_usd: Decimal = _MAX_SESSION_BUDGET_USD,
+ expiry_minutes: int = 30,
+ token_factory: TokenFactory = lambda: str(uuid.uuid4()),
+) -> dict[str, object]:
+ """Create one short-lived session and keep identifiers in a local file."""
+
+ _require_session_admin(environ)
+ _, user_id, region = _required_runtime(environ)
+ if (
+ not budget_usd.is_finite()
+ or budget_usd <= 0
+ or budget_usd > _MAX_SESSION_BUDGET_USD
+ ):
+ raise AgentCorePaymentError(
+ "payment_session_budget_invalid",
+ "The session budget must be greater than 0 and no greater than 0.01 USD.",
+ )
+ if not _MIN_SESSION_MINUTES <= expiry_minutes <= _MAX_SESSION_MINUTES:
+ raise AgentCorePaymentError(
+ "payment_session_expiry_invalid",
+ "The session expiry must be between 15 and 60 minutes.",
+ )
+
+ path = _session_file(environ, session_file)
+ with _session_lock(path):
+ state = _read_session_state(path)
+ if state.get("PAYMENT_SESSION_ID"):
+ raise AgentCorePaymentError(
+ "payment_session_already_recorded",
+ "Delete the recorded payment session before creating another.",
+ )
+ client_token = state.get("PAYMENT_SESSION_CLIENT_TOKEN") or token_factory()
+ if len(client_token) < 8:
+ raise AgentCorePaymentError(
+ "payment_session_client_token_invalid",
+ "The payment-session client token must contain at least eight characters.",
+ )
+ _write_session_state(
+ path,
+ {"PAYMENT_SESSION_CLIENT_TOKEN": client_token},
+ )
+
+ try:
+ session = manager.create_payment_session(
+ user_id=user_id,
+ limits={
+ "maxSpendAmount": {
+ "value": format(budget_usd, "f"),
+ "currency": "USD",
+ }
+ },
+ expiry_time_in_minutes=expiry_minutes,
+ client_token=client_token,
+ )
+ except Exception: # noqa: BLE001
+ raise AgentCorePaymentError(
+ "payment_session_create_failed",
+ "AgentCore did not create the bounded payment session. The "
+ "local client token was retained for a safe retry.",
+ ) from None
+
+ session_id = str(session.get("paymentSessionId", "")).strip()
+ if not session_id:
+ raise AgentCorePaymentError(
+ "payment_session_response_invalid",
+ "AgentCore returned no payment session identifier.",
+ )
+ try:
+ _write_session_state(
+ path,
+ {
+ "PAYMENT_SESSION_CLIENT_TOKEN": client_token,
+ "PAYMENT_SESSION_ID": session_id,
+ },
+ )
+ except AgentCorePaymentError:
+ _delete_unpersisted_session(
+ manager,
+ session_id=session_id,
+ user_id=user_id,
+ path=path,
+ client_token=client_token,
+ )
+ raise
+ return {
+ "result": "CREATED",
+ "budget_usd": format(budget_usd, "f"),
+ "expiry_minutes": expiry_minutes,
+ "agentcore_region": region,
+ "session_file": str(path),
+ "session_id_logged": False,
+ "client_token_logged": False,
+ "value_transferred": False,
+ }
+
+
+def delete_recorded_session(
+ manager: PaymentSessionManager,
+ *,
+ environ: Mapping[str, str],
+ session_file: Path | None = None,
+) -> dict[str, object]:
+ """Delete the recorded session and remove its local identifier file."""
+
+ _require_session_admin(environ)
+ _, user_id, region = _required_runtime(environ)
+ path = _session_file(environ, session_file)
+ with _session_lock(path):
+ state = _read_session_state(path)
+ session_id = state.get("PAYMENT_SESSION_ID", "").strip()
+ if not session_id:
+ raise AgentCorePaymentError(
+ "payment_session_not_recorded",
+ "No payment session is recorded in the local state file.",
+ )
+ try:
+ deletion = manager.delete_payment_session(
+ payment_session_id=session_id,
+ user_id=user_id,
+ )
+ except Exception: # noqa: BLE001
+ raise AgentCorePaymentError(
+ "payment_session_delete_failed",
+ "AgentCore did not delete the recorded payment session. The "
+ "local state file was retained.",
+ ) from None
+ if str(deletion.get("status", "")).upper() != "DELETED":
+ raise AgentCorePaymentError(
+ "payment_session_delete_unconfirmed",
+ "AgentCore did not confirm payment-session deletion. The "
+ "local state file was retained.",
+ )
+ path.unlink()
+ return {
+ "result": "DELETED",
+ "agentcore_region": region,
+ "session_file_removed": True,
+ "session_id_logged": False,
+ "client_token_logged": False,
+ "value_transferred": False,
+ }
+
+
+def runtime_environment_from_recorded_session(
+ environ: Mapping[str, str],
+ *,
+ session_file: Path | None = None,
+) -> dict[str, str]:
+ """Return a private runtime copy containing the recorded session ID."""
+
+ path = _session_file(environ, session_file)
+ with _session_lock(path):
+ state = _read_session_state(path)
+ session_id = state.get("PAYMENT_SESSION_ID", "").strip()
+ if not session_id:
+ raise AgentCorePaymentError(
+ "payment_session_not_recorded",
+ "No payment session is recorded in the local state file.",
+ )
+ runtime_environment = dict(environ)
+ runtime_environment["PAYMENT_SESSION_ID"] = session_id
+ return runtime_environment
+
+
+def _manager(environ: Mapping[str, str]) -> PaymentSessionManager:
+ from bedrock_agentcore.payments import PaymentManager
+
+ manager_arn, _, region = _required_runtime(environ)
+ _disable_agentcore_sdk_logging()
+ boto3_session = None
+ profile = environ.get("AGENTCORE_SESSION_AWS_PROFILE", "").strip()
+ if profile:
+ import boto3
+
+ boto3_session = boto3.Session(
+ profile_name=profile,
+ region_name=region,
+ )
+ return PaymentManager(
+ payment_manager_arn=manager_arn,
+ region_name=region,
+ boto3_session=boto3_session,
+ )
+
+
+def _parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description="Create or delete one bounded AgentCore testnet session."
+ )
+ parser.add_argument(
+ "--session-file",
+ type=Path,
+ help="Local state file for the session ID and client token.",
+ )
+ subparsers = parser.add_subparsers(dest="operation", required=True)
+ create = subparsers.add_parser("create")
+ create.add_argument("--budget", type=parse_budget, default=Decimal("0.01"))
+ create.add_argument("--expiry-minutes", type=int, default=30)
+ subparsers.add_parser("delete")
+ return parser
+
+
+def main(argv: Sequence[str] | None = None) -> None:
+ args = _parser().parse_args(argv)
+ try:
+ _require_session_admin(os.environ)
+ manager = _manager(os.environ)
+ if args.operation == "create":
+ report = create_bounded_session(
+ manager,
+ environ=os.environ,
+ session_file=args.session_file,
+ budget_usd=args.budget,
+ expiry_minutes=args.expiry_minutes,
+ )
+ else:
+ report = delete_recorded_session(
+ manager,
+ environ=os.environ,
+ session_file=args.session_file,
+ )
+ except AgentCorePaymentError as exc:
+ print(
+ json.dumps(
+ {"result": "FAILED", "code": exc.code, "message": str(exc)},
+ indent=2,
+ sort_keys=True,
+ )
+ )
+ raise SystemExit(1) from None
+ print(json.dumps(report, indent=2, sort_keys=True))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/application.py b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/application.py
new file mode 100644
index 00000000..06d6e579
--- /dev/null
+++ b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/application.py
@@ -0,0 +1,215 @@
+"""Application controller for the deterministic x402 purchase sequence."""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime
+
+import httpx
+from pydantic import ValidationError
+
+from .audit import AuditTrail
+from .codec import decode_json
+from .errors import MerchantRejectedPayment, PolicyDenied, ProtocolError
+from .merchant import (
+ PAYMENT_REQUIRED_HEADER,
+ PAYMENT_RESPONSE_HEADER,
+ PAYMENT_SIGNATURE_HEADER,
+)
+from .models import (
+ ApprovalGrant,
+ AuditEventType,
+ PaymentRequired,
+ PurchaseRequest,
+ PurchaseResult,
+ SettlementResponse,
+ SupplierRiskReport,
+)
+from .payments import LocalPaymentProcessor
+from .policy import PolicyEngine
+
+
+class CommerceApplication:
+ """Orchestrate HTTP, authorization, payment, receipt, and audit state."""
+
+ def __init__(
+ self,
+ *,
+ client: httpx.Client,
+ policy: PolicyEngine,
+ payments: LocalPaymentProcessor,
+ audit: AuditTrail | None = None,
+ ) -> None:
+ self.client = client
+ self.policy = policy
+ self.payments = payments
+ self.audit = audit or AuditTrail()
+
+ def purchase(
+ self,
+ request: PurchaseRequest,
+ *,
+ approval: ApprovalGrant | None = None,
+ now: datetime | None = None,
+ ) -> PurchaseResult:
+ now = now or datetime.now(UTC)
+ self.audit.append(
+ request_id=request.request_id,
+ event_type=AuditEventType.RESOURCE_REQUESTED,
+ detail={
+ "resource_url": str(request.resource_url),
+ "purpose": request.purpose,
+ },
+ )
+ preflight = self.policy.preflight(request, now=now)
+ if not preflight.allowed:
+ self.audit.append(
+ request_id=request.request_id,
+ event_type=AuditEventType.REQUEST_DENIED,
+ detail={"code": preflight.code, "stage": "preflight"},
+ )
+ raise PolicyDenied(preflight.code, preflight.reason)
+
+ initial = self.client.get(str(request.resource_url))
+ if initial.status_code != 402:
+ raise ProtocolError(
+ "payment_challenge_expected",
+ "The paid resource did not return HTTP 402.",
+ )
+
+ required = self._payment_required(initial)
+ requirement = required.accepts[0]
+ self.audit.append(
+ request_id=request.request_id,
+ event_type=AuditEventType.PAYMENT_REQUIRED,
+ detail={
+ "merchant_domain": requirement.merchant_domain,
+ "amount": str(requirement.decimal_amount),
+ "currency": requirement.currency,
+ "network": requirement.network,
+ },
+ )
+
+ decision = self.policy.authorize(
+ request,
+ required,
+ approval=approval,
+ now=now,
+ )
+ self.audit.append(
+ request_id=request.request_id,
+ event_type=AuditEventType.AUTHORIZATION_CHECKED,
+ detail={
+ "allowed": decision.allowed,
+ "code": decision.code,
+ "requires_human_approval": (decision.requires_human_approval),
+ },
+ )
+ if not decision.allowed:
+ self.audit.append(
+ request_id=request.request_id,
+ event_type=AuditEventType.REQUEST_DENIED,
+ detail={"code": decision.code},
+ )
+ raise PolicyDenied(decision.code, decision.reason)
+
+ self.audit.append(
+ request_id=request.request_id,
+ event_type=AuditEventType.PAYMENT_ATTEMPTED,
+ detail={"idempotency_key": request.idempotency_key},
+ )
+ authorization = self.payments.authorize(request, requirement)
+ self.policy.record(authorization.receipt)
+ self.audit.append(
+ request_id=request.request_id,
+ event_type=(
+ AuditEventType.PROOF_REUSED
+ if authorization.receipt.reused
+ else AuditEventType.PROOF_CREATED
+ ),
+ detail={"receipt_id": authorization.receipt.receipt_id},
+ )
+
+ self.audit.append(
+ request_id=request.request_id,
+ event_type=AuditEventType.MERCHANT_RETRY,
+ detail={"payment_header": PAYMENT_SIGNATURE_HEADER},
+ )
+ paid = self.client.get(
+ str(request.resource_url),
+ headers={
+ PAYMENT_SIGNATURE_HEADER: authorization.proof_header,
+ },
+ )
+ if paid.status_code != 200:
+ raise MerchantRejectedPayment(
+ "merchant_rejected_payment",
+ "The merchant did not accept the synthetic payment proof.",
+ )
+
+ settlement = self._settlement(paid)
+ if (
+ not settlement.success
+ or settlement.transaction != authorization.receipt.transaction
+ ):
+ raise ProtocolError(
+ "settlement_receipt_mismatch",
+ "The settlement response does not match the local receipt.",
+ )
+ try:
+ report = SupplierRiskReport.model_validate(paid.json())
+ except (ValueError, ValidationError) as exc:
+ raise ProtocolError(
+ "invalid_paid_resource",
+ "The paid resource did not match the typed report contract.",
+ ) from exc
+
+ self.audit.append(
+ request_id=request.request_id,
+ event_type=AuditEventType.CONTENT_RETURNED,
+ detail={
+ "report_id": report.report_id,
+ "receipt_id": authorization.receipt.receipt_id,
+ },
+ )
+ return PurchaseResult(
+ status="completed",
+ request_id=request.request_id,
+ authorization=decision,
+ receipt=authorization.receipt,
+ report=report,
+ audit_events=self.audit.for_request(request.request_id),
+ )
+
+ @staticmethod
+ def _payment_required(response: httpx.Response) -> PaymentRequired:
+ header = response.headers.get(PAYMENT_REQUIRED_HEADER)
+ if header is None:
+ raise ProtocolError(
+ "payment_required_header_missing",
+ "HTTP 402 did not include PAYMENT-REQUIRED.",
+ )
+ payload = decode_json(header, header_name=PAYMENT_REQUIRED_HEADER)
+ try:
+ return PaymentRequired.model_validate(payload)
+ except ValidationError as exc:
+ raise ProtocolError(
+ "invalid_payment_requirement",
+ "PAYMENT-REQUIRED does not match the expected contract.",
+ ) from exc
+
+ @staticmethod
+ def _settlement(response: httpx.Response) -> SettlementResponse:
+ header = response.headers.get(PAYMENT_RESPONSE_HEADER)
+ if header is None:
+ raise ProtocolError(
+ "payment_response_header_missing",
+ "Paid response did not include PAYMENT-RESPONSE.",
+ )
+ payload = decode_json(header, header_name=PAYMENT_RESPONSE_HEADER)
+ try:
+ return SettlementResponse.model_validate(payload)
+ except ValidationError as exc:
+ raise ProtocolError(
+ "invalid_settlement_response",
+ "PAYMENT-RESPONSE does not match the expected contract.",
+ ) from exc
diff --git a/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/audit.py b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/audit.py
new file mode 100644
index 00000000..88457a5d
--- /dev/null
+++ b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/audit.py
@@ -0,0 +1,47 @@
+"""Append-only in-memory audit trail for the deterministic local path."""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+from datetime import UTC, datetime
+from typing import Any
+
+from .models import AuditEvent, AuditEventType
+
+Clock = Callable[[], datetime]
+
+
+def utc_now() -> datetime:
+ return datetime.now(UTC)
+
+
+class AuditTrail:
+ """Record ordered events without exposing mutable internal state."""
+
+ def __init__(self, *, clock: Clock = utc_now) -> None:
+ self._clock = clock
+ self._events: list[AuditEvent] = []
+
+ def append(
+ self,
+ *,
+ request_id: str,
+ event_type: AuditEventType,
+ detail: dict[str, Any] | None = None,
+ ) -> AuditEvent:
+ event = AuditEvent(
+ sequence=len(self._events) + 1,
+ occurred_at=self._clock(),
+ request_id=request_id,
+ event_type=event_type,
+ detail=detail or {},
+ )
+ self._events.append(event)
+ return event
+
+ def for_request(self, request_id: str) -> tuple[AuditEvent, ...]:
+ return tuple(event for event in self._events if event.request_id == request_id)
+
+ @property
+ def events(self) -> tuple[AuditEvent, ...]:
+ return tuple(self._events)
diff --git a/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/codec.py b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/codec.py
new file mode 100644
index 00000000..bd95f606
--- /dev/null
+++ b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/codec.py
@@ -0,0 +1,38 @@
+"""Base64 JSON helpers used by the protocol-shaped local transport."""
+
+from __future__ import annotations
+
+import base64
+import json
+from typing import Any
+
+from pydantic import BaseModel
+
+from .errors import ProtocolError
+
+
+def encode_model(model: BaseModel) -> str:
+ """Serialize a model to standard Base64-encoded JSON."""
+
+ payload = model.model_dump_json(by_alias=True, exclude_none=True)
+ return base64.b64encode(payload.encode("utf-8")).decode("ascii")
+
+
+def decode_json(value: str, *, header_name: str) -> dict[str, Any]:
+ """Decode a Base64 JSON header without leaking its raw value in errors."""
+
+ try:
+ decoded = base64.b64decode(value, validate=True)
+ payload = json.loads(decoded)
+ except (ValueError, UnicodeDecodeError, json.JSONDecodeError) as exc:
+ raise ProtocolError(
+ "malformed_protocol_header",
+ f"{header_name} is not valid Base64-encoded JSON.",
+ ) from exc
+
+ if not isinstance(payload, dict):
+ raise ProtocolError(
+ "malformed_protocol_header",
+ f"{header_name} must decode to a JSON object.",
+ )
+ return payload
diff --git a/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/demo.py b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/demo.py
new file mode 100644
index 00000000..95e184a2
--- /dev/null
+++ b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/demo.py
@@ -0,0 +1,35 @@
+"""Build the deterministic demo used by the notebook and tests."""
+
+from __future__ import annotations
+
+from datetime import datetime, timedelta
+from decimal import Decimal
+
+from .application import CommerceApplication
+from .merchant import SyntheticMerchant
+from .models import CommercePolicy
+from .payments import LocalPaymentProcessor
+from .policy import PolicyEngine
+
+
+def build_demo(
+ now: datetime,
+) -> tuple[CommerceApplication, SyntheticMerchant, LocalPaymentProcessor]:
+ payments = LocalPaymentProcessor()
+ merchant = SyntheticMerchant(payments, now=now)
+ policy = PolicyEngine(
+ CommercePolicy(
+ allowed_merchants=frozenset({"merchant.invalid"}),
+ allowed_purposes=frozenset({"supplier_due_diligence"}),
+ per_request_limit=Decimal("0.50"),
+ per_run_limit=Decimal("1.00"),
+ approval_threshold=Decimal("0.10"),
+ session_expires_at=now + timedelta(minutes=15),
+ )
+ )
+ application = CommerceApplication(
+ client=merchant.client(),
+ policy=policy,
+ payments=payments,
+ )
+ return application, merchant, payments
diff --git a/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/errors.py b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/errors.py
new file mode 100644
index 00000000..0a6f93b5
--- /dev/null
+++ b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/errors.py
@@ -0,0 +1,48 @@
+"""Safe, typed errors for the synthetic commerce flow."""
+
+from __future__ import annotations
+
+from collections.abc import Mapping
+
+
+class CommerceError(RuntimeError):
+ """Base error with a stable, non-secret error code."""
+
+ def __init__(
+ self,
+ code: str,
+ message: str,
+ *,
+ diagnostics: Mapping[str, object] | None = None,
+ ) -> None:
+ super().__init__(message)
+ self.code = code
+ self.diagnostics = dict(diagnostics or {})
+
+
+class ProtocolError(CommerceError):
+ """The merchant response did not satisfy the expected x402 shape."""
+
+
+class PolicyDenied(CommerceError):
+ """Application-owned policy denied the proposed purchase."""
+
+
+class IdempotencyConflict(CommerceError):
+ """An idempotency key was reused for a different purchase."""
+
+
+class MerchantRejectedPayment(CommerceError):
+ """The synthetic merchant rejected the supplied payment proof."""
+
+
+class AgentCorePaymentError(CommerceError):
+ """AgentCore Payments or the testnet transport failed safely."""
+
+
+class LivePaymentDisabled(AgentCorePaymentError):
+ """A networked testnet payment was attempted without explicit opt-in."""
+
+
+class AgentResultInvalid(CommerceError):
+ """The agent result did not match application-observed purchase evidence."""
diff --git a/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/learning_model.py b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/learning_model.py
new file mode 100644
index 00000000..bb8da3ad
--- /dev/null
+++ b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/learning_model.py
@@ -0,0 +1,144 @@
+"""No-network scripted model for teaching the Agents SDK tool loop."""
+
+from __future__ import annotations
+
+import json
+from collections.abc import AsyncIterator
+from typing import Any
+
+from agents import (
+ AgentOutputSchemaBase,
+ Handoff,
+ Model,
+ ModelResponse,
+ ModelSettings,
+ ModelTracing,
+ Tool,
+ TResponseInputItem,
+ Usage,
+)
+from agents.items import TResponseStreamEvent
+from openai.types.responses import (
+ ResponseFunctionToolCall,
+ ResponseOutputMessage,
+ ResponseOutputText,
+)
+
+from .agent import SupplierResearchOutput
+
+
+class ScriptedCommerceLearningModel(Model):
+ """Request x402_fetch once, then copy its synthetic evidence.
+
+ This is a deterministic test fixture, not an inference engine. It exists
+ so learners can run the real Agents SDK Runner loop without credentials,
+ paid inference, AWS, AgentCore Payments, a wallet, or value transfer.
+ """
+
+ def __init__(self) -> None:
+ self.model_turns = 0
+ self.requested_tools: list[str] = []
+
+ async def get_response(
+ self,
+ system_instructions: str | None,
+ input: str | list[TResponseInputItem],
+ model_settings: ModelSettings,
+ tools: list[Tool],
+ output_schema: AgentOutputSchemaBase | None,
+ handoffs: list[Handoff],
+ tracing: ModelTracing,
+ **kwargs: Any,
+ ) -> ModelResponse:
+ self.model_turns += 1
+ if self.model_turns == 1:
+ self.requested_tools.append("x402_fetch")
+ return ModelResponse(
+ output=[
+ ResponseFunctionToolCall(
+ arguments=json.dumps(
+ {
+ "resource_url": (
+ "https://merchant.invalid/reports/"
+ "SYNTH-SUPPLIER-RISK-001"
+ ),
+ "purpose": "supplier_due_diligence",
+ }
+ ),
+ call_id="learning-x402-call-001",
+ name="x402_fetch",
+ type="function_call",
+ id="learning-x402-item-001",
+ status="completed",
+ )
+ ],
+ usage=Usage(),
+ response_id=None,
+ )
+
+ evidence = self._tool_evidence(input)
+ report = evidence["report"]
+ output = SupplierResearchOutput(
+ status=evidence["status"],
+ report_id=report["report_id"],
+ supplier=report["supplier"],
+ signals=tuple(report["signals"]),
+ disclaimer=report["disclaimer"],
+ receipt_id=evidence["receipt_id"],
+ amount=evidence["amount"],
+ currency=evidence["currency"],
+ requires_human_approval=evidence["requires_human_approval"],
+ )
+ return ModelResponse(
+ output=[
+ ResponseOutputMessage(
+ id="learning-final-001",
+ content=[
+ ResponseOutputText(
+ text=output.model_dump_json(),
+ annotations=[],
+ type="output_text",
+ )
+ ],
+ role="assistant",
+ status="completed",
+ type="message",
+ )
+ ],
+ usage=Usage(),
+ response_id=None,
+ )
+
+ @staticmethod
+ def _tool_evidence(
+ input: str | list[TResponseInputItem],
+ ) -> dict[str, Any]:
+ if isinstance(input, str):
+ raise TypeError("The learning model did not receive tool output.")
+ for item in reversed(input):
+ if isinstance(item, dict) and item.get("type") == "function_call_output":
+ raw_output = item.get("output")
+ if not isinstance(raw_output, str):
+ raise RuntimeError(
+ "The learning model received an invalid tool output."
+ )
+ parsed = json.loads(raw_output)
+ if not isinstance(parsed, dict) or parsed.get("status") != "completed":
+ raise RuntimeError("The synthetic purchase did not complete.")
+ return parsed
+ raise RuntimeError("The learning model did not receive tool output.")
+
+ def stream_response(
+ self,
+ system_instructions: str | None,
+ input: str | list[TResponseInputItem],
+ model_settings: ModelSettings,
+ tools: list[Tool],
+ output_schema: AgentOutputSchemaBase | None,
+ handoffs: list[Handoff],
+ tracing: ModelTracing,
+ **kwargs: Any,
+ ) -> AsyncIterator[TResponseStreamEvent]:
+ raise NotImplementedError(
+ "The local learning model supports non-streaming runs only."
+ )
diff --git a/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/merchant.py b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/merchant.py
new file mode 100644
index 00000000..c0884758
--- /dev/null
+++ b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/merchant.py
@@ -0,0 +1,127 @@
+"""In-memory synthetic merchant that exposes a protocol-shaped x402 flow."""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime, timedelta
+from decimal import Decimal
+
+import httpx
+
+from .codec import encode_model
+from .errors import CommerceError
+from .models import (
+ PaymentRequired,
+ PaymentRequirement,
+ ResourceInfo,
+ SupplierRiskReport,
+)
+from .payments import LocalPaymentProcessor
+
+PAYMENT_REQUIRED_HEADER = "PAYMENT-REQUIRED"
+PAYMENT_SIGNATURE_HEADER = "PAYMENT-SIGNATURE"
+PAYMENT_RESPONSE_HEADER = "PAYMENT-RESPONSE"
+
+RESOURCE_URL = "https://merchant.invalid/reports/SYNTH-SUPPLIER-RISK-001"
+
+
+class SyntheticMerchant:
+ """Serve one fictional paid report through an in-memory HTTP transport."""
+
+ def __init__(
+ self,
+ payment_processor: LocalPaymentProcessor,
+ *,
+ price: Decimal = Decimal("0.25"),
+ now: datetime | None = None,
+ malformed_challenge: bool = False,
+ ) -> None:
+ self.payment_processor = payment_processor
+ self.request_count = 0
+ self.fulfilled_count = 0
+ self.invalid_proof_count = 0
+ self.malformed_challenge = malformed_challenge
+ issued_at = now or datetime.now(UTC)
+ expires_at = issued_at + timedelta(minutes=5)
+ amount = str(int(price * Decimal(1_000_000)))
+
+ self.requirement = PaymentRequirement(
+ amount=amount,
+ asset="synthetic-usdc-base-sepolia",
+ payTo="synthetic-merchant-wallet",
+ maxTimeoutSeconds=300,
+ extra={
+ "challengeId": "challenge-synth-report-001",
+ "currency": "USDC",
+ "decimals": 6,
+ "merchantDomain": "merchant.invalid",
+ "issuedAt": issued_at.isoformat(),
+ "expiresAt": expires_at.isoformat(),
+ "simulation": True,
+ },
+ )
+ self.payment_required = PaymentRequired(
+ resource=ResourceInfo(
+ url=RESOURCE_URL,
+ description="Synthetic supplier-risk report",
+ mimeType="application/json",
+ ),
+ accepts=(self.requirement,),
+ error="Payment is required for this synthetic report.",
+ )
+ self.report = SupplierRiskReport(
+ report_id="SYNTH-SUPPLIER-RISK-001",
+ supplier="Northstar Components",
+ generated_from="synthetic data",
+ signals=(
+ "Delivery concentration increased in the last synthetic quarter.",
+ "Two fictional certifications require manual verification.",
+ ),
+ disclaimer=(
+ "Training-only synthetic report; not purchasing, legal, "
+ "compliance, or risk advice."
+ ),
+ )
+
+ def client(self) -> httpx.Client:
+ return httpx.Client(transport=httpx.MockTransport(self._handle))
+
+ def _handle(self, request: httpx.Request) -> httpx.Response:
+ self.request_count += 1
+ if request.method != "GET" or str(request.url) != RESOURCE_URL:
+ return httpx.Response(
+ 404,
+ json={"error": "synthetic_resource_not_found"},
+ )
+
+ proof_header = request.headers.get(PAYMENT_SIGNATURE_HEADER)
+ if proof_header is None:
+ challenge = (
+ "not-base64-json"
+ if self.malformed_challenge
+ else encode_model(self.payment_required)
+ )
+ return httpx.Response(
+ 402,
+ headers={PAYMENT_REQUIRED_HEADER: challenge},
+ json={"error": "payment_required"},
+ )
+
+ try:
+ settlement = self.payment_processor.verify(
+ proof_header,
+ self.requirement,
+ )
+ except CommerceError as exc:
+ self.invalid_proof_count += 1
+ return httpx.Response(
+ 402,
+ headers={PAYMENT_REQUIRED_HEADER: encode_model(self.payment_required)},
+ json={"error": exc.code},
+ )
+
+ self.fulfilled_count += 1
+ return httpx.Response(
+ 200,
+ headers={PAYMENT_RESPONSE_HEADER: encode_model(settlement)},
+ json=self.report.model_dump(mode="json"),
+ )
diff --git a/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/models.py b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/models.py
new file mode 100644
index 00000000..5c38e16a
--- /dev/null
+++ b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/models.py
@@ -0,0 +1,230 @@
+"""Typed contracts for authorization, x402 transport, receipts, and audit."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from decimal import Decimal
+from enum import StrEnum
+from typing import Any, Literal
+
+from pydantic import (
+ AwareDatetime,
+ BaseModel,
+ ConfigDict,
+ Field,
+ HttpUrl,
+ computed_field,
+ field_validator,
+)
+from pydantic_core import PydanticCustomError
+
+
+class FrozenModel(BaseModel):
+ """Immutable model used for application and protocol contracts."""
+
+ model_config = ConfigDict(frozen=True, populate_by_name=True)
+
+
+class AuditEventType(StrEnum):
+ RESOURCE_REQUESTED = "resource_requested"
+ PAYMENT_REQUIRED = "payment_required"
+ AUTHORIZATION_CHECKED = "authorization_checked"
+ PAYMENT_ATTEMPTED = "payment_attempted"
+ PROOF_CREATED = "proof_created"
+ PROOF_REUSED = "proof_reused"
+ MERCHANT_RETRY = "merchant_retry"
+ CONTENT_RETURNED = "content_returned"
+ REQUEST_DENIED = "request_denied"
+
+
+class AuditEvent(FrozenModel):
+ sequence: int = Field(ge=1)
+ occurred_at: datetime
+ request_id: str
+ event_type: AuditEventType
+ detail: dict[str, Any] = Field(default_factory=dict)
+
+
+class CommercePolicy(FrozenModel):
+ allowed_merchants: frozenset[str]
+ allowed_purposes: frozenset[str]
+ per_request_limit: Decimal = Field(gt=0)
+ per_run_limit: Decimal = Field(gt=0)
+ approval_threshold: Decimal = Field(ge=0)
+ currency: Literal["USDC"] = "USDC"
+ network: Literal["eip155:84532"] = "eip155:84532"
+ session_expires_at: datetime
+
+
+class PurchaseRequest(FrozenModel):
+ request_id: str = Field(min_length=1)
+ resource_url: HttpUrl
+ purpose: str = Field(min_length=1)
+ idempotency_key: str = Field(min_length=8)
+
+
+class ApprovalGrant(FrozenModel):
+ approval_id: str = Field(min_length=1)
+ request_id: str = Field(min_length=1)
+ resource_url: HttpUrl
+ purpose: str = Field(min_length=1)
+ maximum_amount: Decimal = Field(gt=0)
+ currency: Literal["USDC"] = "USDC"
+ approved_by: str = Field(min_length=1)
+ approved_at: datetime
+ expires_at: datetime
+
+
+class ResourceInfo(FrozenModel):
+ url: HttpUrl
+ description: str
+ mime_type: str = Field(alias="mimeType")
+
+
+class PaymentRequirementExtra(FrozenModel):
+ """Validated x402 metadata used by local policy computed fields."""
+
+ model_config = ConfigDict(frozen=True, populate_by_name=True, extra="forbid")
+
+ decimals: int = Field(strict=True, ge=0)
+ currency: Literal["USDC"]
+ merchant_domain: str = Field(
+ alias="merchantDomain",
+ strict=True,
+ min_length=1,
+ )
+ challenge_id: str = Field(
+ alias="challengeId",
+ strict=True,
+ min_length=1,
+ )
+ issued_at: AwareDatetime | None = Field(default=None, alias="issuedAt")
+ expires_at: AwareDatetime = Field(alias="expiresAt")
+ simulation: bool | None = Field(default=None, strict=True)
+
+ @field_validator("issued_at", "expires_at", mode="before")
+ @classmethod
+ def require_iso_timestamp_text(cls, value: object) -> object:
+ if value is None:
+ return value
+ if not isinstance(value, str):
+ raise PydanticCustomError(
+ "x402_timestamp_type",
+ "x402 timestamps must be ISO 8601 strings.",
+ )
+ return value
+
+
+class PaymentRequirement(FrozenModel):
+ """Protocol-shaped x402 V2 exact-payment requirement.
+
+ The local proof is deliberately synthetic. These fields mirror the
+ current x402 V2 transport shape but do not claim chain conformance.
+ """
+
+ scheme: Literal["exact"] = "exact"
+ network: Literal["eip155:84532"] = "eip155:84532"
+ amount: str = Field(pattern=r"^[0-9]+$")
+ asset: str
+ pay_to: str = Field(alias="payTo")
+ max_timeout_seconds: int = Field(alias="maxTimeoutSeconds", gt=0)
+ extra: PaymentRequirementExtra
+
+ @computed_field
+ @property
+ def decimal_amount(self) -> Decimal:
+ return Decimal(self.amount) / (Decimal(10) ** self.extra.decimals)
+
+ @computed_field
+ @property
+ def currency(self) -> Literal["USDC"]:
+ return self.extra.currency
+
+ @computed_field
+ @property
+ def merchant_domain(self) -> str:
+ return self.extra.merchant_domain
+
+ @computed_field
+ @property
+ def challenge_id(self) -> str:
+ return self.extra.challenge_id
+
+ @computed_field
+ @property
+ def expires_at(self) -> datetime:
+ return self.extra.expires_at
+
+
+class PaymentRequired(FrozenModel):
+ x402_version: Literal[2] = Field(alias="x402Version", default=2)
+ resource: ResourceInfo
+ accepts: tuple[PaymentRequirement, ...] = Field(min_length=1)
+ error: str | None = None
+
+
+class PaymentPayload(FrozenModel):
+ x402_version: Literal[2] = Field(alias="x402Version", default=2)
+ accepted: PaymentRequirement
+ payload: dict[str, str]
+
+
+class SettlementResponse(FrozenModel):
+ success: bool
+ transaction: str
+ network: str
+ payer: str
+
+
+class AuthorizationDecision(FrozenModel):
+ allowed: bool
+ code: str
+ reason: str
+ requires_human_approval: bool
+ approved_amount: Decimal | None = None
+
+
+class PaymentReceipt(FrozenModel):
+ receipt_id: str
+ request_id: str
+ idempotency_key: str
+ merchant_domain: str
+ resource_url: HttpUrl
+ amount: Decimal
+ currency: Literal["USDC"]
+ network: str
+ transaction: str
+ reused: bool = False
+
+
+class PaymentAuthorization(FrozenModel):
+ proof_header: str
+ receipt: PaymentReceipt
+
+
+class SupplierRiskReport(FrozenModel):
+ report_id: Literal["SYNTH-SUPPLIER-RISK-001"]
+ supplier: Literal["Northstar Components"]
+ generated_from: Literal["synthetic data"]
+ signals: tuple[str, ...]
+ disclaimer: str
+
+
+class PurchaseResult(FrozenModel):
+ status: Literal["completed"]
+ request_id: str
+ authorization: AuthorizationDecision
+ receipt: PaymentReceipt
+ report: SupplierRiskReport
+ audit_events: tuple[AuditEvent, ...]
+
+
+class AgentPurchaseEvidence(FrozenModel):
+ """Minimum purchase evidence returned to the model by the function tool."""
+
+ status: Literal["completed"]
+ report: SupplierRiskReport
+ receipt_id: str
+ amount: Decimal
+ currency: Literal["USDC"]
+ requires_human_approval: bool
diff --git a/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/payments.py b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/payments.py
new file mode 100644
index 00000000..36293a43
--- /dev/null
+++ b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/payments.py
@@ -0,0 +1,158 @@
+"""Deterministic local proof creation; no wallet, chain, or value transfer."""
+
+from __future__ import annotations
+
+import hashlib
+import json
+from dataclasses import dataclass
+
+from pydantic import ValidationError
+
+from .codec import decode_json, encode_model
+from .errors import IdempotencyConflict, ProtocolError
+from .models import (
+ PaymentAuthorization,
+ PaymentPayload,
+ PaymentReceipt,
+ PaymentRequirement,
+ PurchaseRequest,
+ SettlementResponse,
+)
+
+
+@dataclass(frozen=True)
+class _StoredAuthorization:
+ fingerprint: str
+ proof_header: str
+ receipt: PaymentReceipt
+
+
+class LocalPaymentProcessor:
+ """A fake local payment adapter with idempotent proof generation."""
+
+ payer = "synthetic-test-payer"
+
+ def __init__(self) -> None:
+ self._authorizations: dict[str, _StoredAuthorization] = {}
+
+ @property
+ def charge_count(self) -> int:
+ return len(self._authorizations)
+
+ def authorize(
+ self,
+ request: PurchaseRequest,
+ requirement: PaymentRequirement,
+ ) -> PaymentAuthorization:
+ fingerprint = self._fingerprint(request, requirement)
+ stored = self._authorizations.get(request.idempotency_key)
+ if stored is not None:
+ if stored.fingerprint != fingerprint:
+ raise IdempotencyConflict(
+ "idempotency_conflict",
+ "The idempotency key is already bound to another purchase.",
+ )
+ return PaymentAuthorization(
+ proof_header=stored.proof_header,
+ receipt=stored.receipt.model_copy(update={"reused": True}),
+ )
+
+ digest = hashlib.sha256(
+ f"{request.idempotency_key}:{fingerprint}".encode()
+ ).hexdigest()
+ receipt = PaymentReceipt(
+ receipt_id=f"receipt-{digest[:16]}",
+ request_id=request.request_id,
+ idempotency_key=request.idempotency_key,
+ merchant_domain=requirement.merchant_domain,
+ resource_url=request.resource_url,
+ amount=requirement.decimal_amount,
+ currency=requirement.currency,
+ network=requirement.network,
+ transaction=f"synthetic-{digest[16:40]}",
+ )
+ payload = PaymentPayload(
+ accepted=requirement,
+ payload={
+ "proof": f"synthetic-proof-{digest[40:]}",
+ "receiptId": receipt.receipt_id,
+ },
+ )
+ proof_header = encode_model(payload)
+ self._authorizations[request.idempotency_key] = _StoredAuthorization(
+ fingerprint=fingerprint,
+ proof_header=proof_header,
+ receipt=receipt,
+ )
+ return PaymentAuthorization(
+ proof_header=proof_header,
+ receipt=receipt,
+ )
+
+ def verify(
+ self,
+ proof_header: str,
+ requirement: PaymentRequirement,
+ ) -> SettlementResponse:
+ payload_dict = decode_json(
+ proof_header,
+ header_name="PAYMENT-SIGNATURE",
+ )
+ try:
+ payload = PaymentPayload.model_validate(payload_dict)
+ except ValidationError as exc:
+ raise ProtocolError(
+ "invalid_payment_payload",
+ "PAYMENT-SIGNATURE does not match the expected payload.",
+ ) from exc
+
+ if payload.accepted != requirement:
+ raise ProtocolError(
+ "payment_requirement_mismatch",
+ "The proof does not match the merchant requirement.",
+ )
+
+ receipt_id = payload.payload.get("receiptId")
+ proof = payload.payload.get("proof")
+ stored = next(
+ (
+ candidate
+ for candidate in self._authorizations.values()
+ if candidate.receipt.receipt_id == receipt_id
+ ),
+ None,
+ )
+ if (
+ stored is None
+ or stored.proof_header != proof_header
+ or not proof
+ or not proof.startswith("synthetic-proof-")
+ ):
+ raise ProtocolError(
+ "unrecognized_synthetic_proof",
+ "The local payment proof is not recognized.",
+ )
+
+ return SettlementResponse(
+ success=True,
+ transaction=stored.receipt.transaction,
+ network=stored.receipt.network,
+ payer=self.payer,
+ )
+
+ @staticmethod
+ def _fingerprint(
+ request: PurchaseRequest,
+ requirement: PaymentRequirement,
+ ) -> str:
+ stable = {
+ "resource_url": str(request.resource_url),
+ "purpose": request.purpose,
+ "challenge_id": requirement.challenge_id,
+ "amount": requirement.amount,
+ "asset": requirement.asset,
+ "network": requirement.network,
+ "pay_to": requirement.pay_to,
+ }
+ raw = json.dumps(stable, sort_keys=True, separators=(",", ":"))
+ return hashlib.sha256(raw.encode()).hexdigest()
diff --git a/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/policy.py b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/policy.py
new file mode 100644
index 00000000..24174cdb
--- /dev/null
+++ b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/policy.py
@@ -0,0 +1,237 @@
+"""Deterministic application authorization for synthetic paid resources."""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime
+from decimal import Decimal
+
+from .models import (
+ ApprovalGrant,
+ AuthorizationDecision,
+ CommercePolicy,
+ PaymentReceipt,
+ PaymentRequired,
+ PurchaseRequest,
+)
+
+
+class PolicyEngine:
+ """Authorize purchases independently of model reasoning."""
+
+ def __init__(self, policy: CommercePolicy) -> None:
+ self.policy = policy
+ self._spent_by_idempotency: dict[str, Decimal] = {}
+
+ @property
+ def spent(self) -> Decimal:
+ return sum(self._spent_by_idempotency.values(), start=Decimal(0))
+
+ def preflight(
+ self,
+ request: PurchaseRequest,
+ *,
+ now: datetime | None = None,
+ ) -> AuthorizationDecision:
+ """Reject unsafe destinations and purposes before any HTTP request."""
+
+ now = now or datetime.now(UTC)
+ if request.resource_url.scheme != "https":
+ return self._deny("https_required", "Paid resources must use HTTPS.")
+ if request.resource_url.host not in self.policy.allowed_merchants:
+ return self._deny(
+ "merchant_not_allowed",
+ "The merchant is not in the application allowlist.",
+ )
+ if request.purpose not in self.policy.allowed_purposes:
+ return self._deny(
+ "purpose_not_allowed",
+ "The requested purchase purpose is not allowed.",
+ )
+ if now >= self.policy.session_expires_at:
+ return self._deny(
+ "session_expired",
+ "The application payment session has expired.",
+ )
+ return AuthorizationDecision(
+ allowed=True,
+ code="preflight_allowed",
+ reason="The request destination and purpose satisfy preflight policy.",
+ requires_human_approval=False,
+ )
+
+ def authorize(
+ self,
+ request: PurchaseRequest,
+ required: PaymentRequired,
+ *,
+ approval: ApprovalGrant | None,
+ now: datetime | None = None,
+ ) -> AuthorizationDecision:
+ now = now or datetime.now(UTC)
+ requirement = required.accepts[0]
+ host = request.resource_url.host
+ amount = requirement.decimal_amount
+
+ preflight = self.preflight(request, now=now)
+ if not preflight.allowed:
+ return preflight
+ if required.resource.url != request.resource_url:
+ return self._deny(
+ "resource_mismatch",
+ "The payment challenge refers to a different resource.",
+ )
+ if requirement.merchant_domain != host:
+ return self._deny(
+ "merchant_mismatch",
+ "The payment challenge merchant does not match the URL.",
+ )
+ return self.authorize_challenge(
+ request,
+ merchant_domain=requirement.merchant_domain,
+ network=requirement.network,
+ currency=requirement.currency,
+ amount=amount,
+ approval=approval,
+ expires_at=requirement.expires_at,
+ now=now,
+ )
+
+ def authorize_challenge(
+ self,
+ request: PurchaseRequest,
+ *,
+ merchant_domain: str,
+ network: str,
+ currency: str,
+ amount: Decimal,
+ approval: ApprovalGrant | None,
+ expires_at: datetime | None = None,
+ now: datetime | None = None,
+ ) -> AuthorizationDecision:
+ """Authorize normalized challenge facts from any x402 transport."""
+
+ now = now or datetime.now(UTC)
+ host = request.resource_url.host
+ preflight = self.preflight(request, now=now)
+ if not preflight.allowed:
+ return preflight
+ if merchant_domain != host:
+ return self._deny(
+ "merchant_mismatch",
+ "The payment challenge merchant does not match the URL.",
+ )
+ if network != self.policy.network:
+ return self._deny(
+ "network_not_allowed",
+ "The payment network is outside the configured policy.",
+ )
+ if currency != self.policy.currency:
+ return self._deny(
+ "currency_not_allowed",
+ "The payment currency is outside the configured policy.",
+ )
+ if expires_at is not None and now >= expires_at:
+ return self._deny(
+ "challenge_expired",
+ "The merchant payment challenge has expired.",
+ )
+ if amount > self.policy.per_request_limit:
+ return self._deny(
+ "request_limit_exceeded",
+ "The amount exceeds the per-request spending limit.",
+ )
+ new_spend = (
+ Decimal(0)
+ if request.idempotency_key in self._spent_by_idempotency
+ else amount
+ )
+ if self.spent + new_spend > self.policy.per_run_limit:
+ return self._deny(
+ "run_limit_exceeded",
+ "The amount exceeds the remaining run budget.",
+ )
+
+ requires_approval = amount > self.policy.approval_threshold
+ if requires_approval:
+ approval_error = self._validate_approval(
+ request,
+ approval,
+ amount=amount,
+ now=now,
+ )
+ if approval_error is not None:
+ return approval_error
+
+ return AuthorizationDecision(
+ allowed=True,
+ code="authorized",
+ reason="The request satisfies application-owned commerce policy.",
+ requires_human_approval=requires_approval,
+ approved_amount=amount,
+ )
+
+ def record_spend(self, idempotency_key: str, amount: Decimal) -> None:
+ """Record one authorized amount without inventing receipt fields."""
+
+ self._spent_by_idempotency.setdefault(idempotency_key, amount)
+
+ def record(self, receipt: PaymentReceipt) -> None:
+ self.record_spend(receipt.idempotency_key, receipt.amount)
+
+ def _validate_approval(
+ self,
+ request: PurchaseRequest,
+ approval: ApprovalGrant | None,
+ *,
+ amount: Decimal,
+ now: datetime,
+ ) -> AuthorizationDecision | None:
+ if approval is None:
+ return self._deny(
+ "human_approval_required",
+ "A human approval grant is required above the threshold.",
+ requires_human_approval=True,
+ )
+ if now >= approval.expires_at:
+ return self._deny(
+ "approval_expired",
+ "The human approval grant has expired.",
+ requires_human_approval=True,
+ )
+ if (
+ approval.request_id != request.request_id
+ or approval.resource_url != request.resource_url
+ or approval.purpose != request.purpose
+ ):
+ return self._deny(
+ "approval_scope_mismatch",
+ "The human approval grant is not bound to this request.",
+ requires_human_approval=True,
+ )
+ if approval.currency != self.policy.currency:
+ return self._deny(
+ "approval_currency_mismatch",
+ "The human approval grant uses a different currency.",
+ requires_human_approval=True,
+ )
+ if amount > approval.maximum_amount:
+ return self._deny(
+ "approval_amount_exceeded",
+ "The amount exceeds the human-approved maximum.",
+ requires_human_approval=True,
+ )
+ return None
+
+ @staticmethod
+ def _deny(
+ code: str,
+ reason: str,
+ *,
+ requires_human_approval: bool = False,
+ ) -> AuthorizationDecision:
+ return AuthorizationDecision(
+ allowed=False,
+ code=code,
+ reason=reason,
+ requires_human_approval=requires_human_approval,
+ )
diff --git a/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/tool.py b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/tool.py
new file mode 100644
index 00000000..ea307b62
--- /dev/null
+++ b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/src/agentic_commerce/tool.py
@@ -0,0 +1,73 @@
+"""Agents SDK function-tool adapter with pre-bound application authority."""
+
+from __future__ import annotations
+
+import json
+from collections.abc import Callable
+
+from agents import FunctionTool, function_tool
+
+from .application import CommerceApplication
+from .errors import CommerceError
+from .models import (
+ AgentPurchaseEvidence,
+ ApprovalGrant,
+ PurchaseRequest,
+ PurchaseResult,
+)
+
+
+def build_x402_fetch_tool(
+ application: CommerceApplication,
+ *,
+ request_id: str,
+ idempotency_key: str,
+ approval: ApprovalGrant | None = None,
+ on_purchase: Callable[[PurchaseResult], None] | None = None,
+) -> FunctionTool:
+ """Build a tool whose authority is supplied by the application.
+
+ The model can propose a URL and purpose. It cannot mint an approval,
+ choose its own spending policy, or access proof/wallet material.
+ """
+
+ @function_tool(
+ name_override="x402_fetch",
+ description_override=(
+ "Fetch one paid HTTPS resource through application-controlled "
+ "merchant, purpose, spending, approval, and audit policy."
+ ),
+ )
+ def x402_fetch(resource_url: str, purpose: str) -> str:
+ try:
+ result = application.purchase(
+ PurchaseRequest(
+ request_id=request_id,
+ resource_url=resource_url,
+ purpose=purpose,
+ idempotency_key=idempotency_key,
+ ),
+ approval=approval,
+ )
+ if on_purchase is not None:
+ on_purchase(result)
+ evidence = AgentPurchaseEvidence(
+ status=result.status,
+ report=result.report,
+ receipt_id=result.receipt.receipt_id,
+ amount=result.receipt.amount,
+ currency=result.receipt.currency,
+ requires_human_approval=(result.authorization.requires_human_approval),
+ )
+ return evidence.model_dump_json()
+ except CommerceError as exc:
+ return json.dumps(
+ {
+ "status": "denied",
+ "code": exc.code,
+ "message": str(exc),
+ },
+ sort_keys=True,
+ )
+
+ return x402_fetch
diff --git a/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/tests/test_agent_workflow.py b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/tests/test_agent_workflow.py
new file mode 100644
index 00000000..4278b804
--- /dev/null
+++ b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/tests/test_agent_workflow.py
@@ -0,0 +1,183 @@
+from __future__ import annotations
+
+import asyncio
+import json
+from datetime import UTC, datetime, timedelta
+from decimal import Decimal
+
+import pytest
+from agents.tool_context import ToolContext
+from agents.usage import Usage
+
+from agentic_commerce.agent import (
+ PurchaseResultRecorder,
+ SupplierResearchOutput,
+ build_supplier_research_agent,
+ run_supplier_research,
+ validate_supplier_research_output,
+)
+from agentic_commerce.demo import build_demo
+from agentic_commerce.errors import AgentResultInvalid
+from agentic_commerce.learning_model import ScriptedCommerceLearningModel
+from agentic_commerce.merchant import RESOURCE_URL
+from agentic_commerce.models import (
+ ApprovalGrant,
+ PurchaseRequest,
+ PurchaseResult,
+)
+from agentic_commerce.tool import build_x402_fetch_tool
+
+NOW = datetime(2026, 7, 31, 15, 0, tzinfo=UTC)
+
+
+def make_approval(now: datetime = NOW) -> ApprovalGrant:
+ return ApprovalGrant(
+ approval_id="approval-agent-001",
+ request_id="request-agent-001",
+ resource_url=RESOURCE_URL,
+ purpose="supplier_due_diligence",
+ maximum_amount=Decimal("0.25"),
+ approved_by="synthetic-reviewer",
+ approved_at=now,
+ expires_at=now + timedelta(minutes=10),
+ )
+
+
+def make_purchase() -> PurchaseResult:
+ application, _, _ = build_demo(NOW)
+ request = PurchaseRequest(
+ request_id="request-agent-001",
+ resource_url=RESOURCE_URL,
+ purpose="supplier_due_diligence",
+ idempotency_key="purchase-agent-001",
+ )
+ return application.purchase(request, approval=make_approval(), now=NOW)
+
+
+def output_for(purchase: PurchaseResult) -> SupplierResearchOutput:
+ return SupplierResearchOutput(
+ status=purchase.status,
+ report_id=purchase.report.report_id,
+ supplier=purchase.report.supplier,
+ signals=purchase.report.signals,
+ disclaimer=purchase.report.disclaimer,
+ receipt_id=purchase.receipt.receipt_id,
+ amount=str(purchase.receipt.amount),
+ currency=purchase.receipt.currency,
+ requires_human_approval=(purchase.authorization.requires_human_approval),
+ )
+
+
+def test_agent_has_one_bound_tool_typed_output_and_no_storage() -> None:
+ application, _, _ = build_demo(NOW)
+ recorder = PurchaseResultRecorder()
+
+ agent = build_supplier_research_agent(
+ application,
+ model="synthetic-model-id",
+ request_id="request-agent-001",
+ idempotency_key="purchase-agent-001",
+ approval=make_approval(),
+ recorder=recorder,
+ )
+
+ assert [tool.name for tool in agent.tools] == ["x402_fetch"]
+ assert agent.output_type is SupplierResearchOutput
+ assert agent.model_settings.store is False
+
+
+def test_application_validation_accepts_exact_tool_evidence() -> None:
+ purchase = make_purchase()
+ recorder = PurchaseResultRecorder(results=[purchase])
+
+ validated = validate_supplier_research_output(
+ output_for(purchase),
+ recorder,
+ )
+
+ assert validated == purchase
+
+
+def test_application_validation_rejects_fabricated_receipt() -> None:
+ purchase = make_purchase()
+ fabricated = output_for(purchase).model_copy(
+ update={"receipt_id": "receipt-fabricated"}
+ )
+
+ with pytest.raises(AgentResultInvalid) as exc_info:
+ validate_supplier_research_output(
+ fabricated,
+ PurchaseResultRecorder(results=[purchase]),
+ )
+
+ assert exc_info.value.code == "agent_output_mismatch"
+ assert "receipt_id" in str(exc_info.value)
+
+
+def test_application_validation_rejects_missing_tool_purchase() -> None:
+ purchase = make_purchase()
+
+ with pytest.raises(AgentResultInvalid) as exc_info:
+ validate_supplier_research_output(
+ output_for(purchase),
+ PurchaseResultRecorder(),
+ )
+
+ assert exc_info.value.code == "purchase_count_invalid"
+
+
+def test_tool_returns_minimum_evidence_and_keeps_full_receipt_in_app() -> None:
+ now = datetime.now(UTC)
+ application, _, _ = build_demo(now)
+ recorder = PurchaseResultRecorder()
+ tool = build_x402_fetch_tool(
+ application,
+ request_id="request-agent-001",
+ idempotency_key="purchase-agent-001",
+ approval=make_approval(now),
+ on_purchase=recorder.record,
+ )
+ arguments = json.dumps(
+ {
+ "resource_url": RESOURCE_URL,
+ "purpose": "supplier_due_diligence",
+ }
+ )
+ context = ToolContext(
+ context=None,
+ usage=Usage(),
+ tool_name="x402_fetch",
+ tool_call_id="call-agent-001",
+ tool_arguments=arguments,
+ )
+
+ raw_result = asyncio.run(tool.on_invoke_tool(context, arguments))
+ visible = json.loads(raw_result)
+
+ assert len(recorder.results) == 1
+ assert visible["receipt_id"] == recorder.results[0].receipt.receipt_id
+ assert "transaction" not in raw_result
+ assert "audit_events" not in raw_result
+ assert "proof_header" not in raw_result
+
+
+def test_scripted_model_runs_the_real_agents_sdk_tool_loop() -> None:
+ now = datetime.now(UTC)
+ application, merchant, payments = build_demo(now)
+ model = ScriptedCommerceLearningModel()
+
+ result = asyncio.run(
+ run_supplier_research(
+ application,
+ model=model,
+ request_id="request-agent-001",
+ idempotency_key="purchase-agent-001",
+ approval=make_approval(now),
+ )
+ )
+
+ assert model.model_turns == 2
+ assert model.requested_tools == ["x402_fetch"]
+ assert merchant.request_count == 2
+ assert payments.charge_count == 1
+ assert result.output.receipt_id == result.purchase.receipt.receipt_id
diff --git a/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/tests/test_agentcore_agent_workflow.py b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/tests/test_agentcore_agent_workflow.py
new file mode 100644
index 00000000..ccd66083
--- /dev/null
+++ b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/tests/test_agentcore_agent_workflow.py
@@ -0,0 +1,480 @@
+from __future__ import annotations
+
+import asyncio
+import base64
+import json
+from collections.abc import Callable
+from datetime import UTC, datetime, timedelta
+from decimal import Decimal
+from typing import Any
+
+import httpx
+import pytest
+from agents.tool_context import ToolContext
+
+from agentic_commerce.agentcore_agent import (
+ AgentCoreAccessOutput,
+ AgentCoreAccessRecorder,
+ build_agentcore_access_agent,
+ run_agentcore_access,
+ validate_agentcore_access_output,
+)
+from agentic_commerce.agentcore_application import (
+ AgentCoreAuthorizedApplication,
+)
+from agentic_commerce.agentcore_e2e import (
+ _bedrock_profile,
+ _blocked_report,
+)
+from agentic_commerce.agentcore_learning_model import (
+ ScriptedAgentCoreLearningModel,
+)
+from agentic_commerce.agentcore_payments import (
+ AgentCorePaymentsSettings,
+ AgentCoreX402Client,
+ AuthorizationCallback,
+)
+from agentic_commerce.errors import (
+ AgentResultInvalid,
+ CommerceError,
+ PolicyDenied,
+)
+from agentic_commerce.models import (
+ ApprovalGrant,
+ AuditEventType,
+ CommercePolicy,
+ PurchaseRequest,
+)
+from agentic_commerce.policy import PolicyEngine
+
+RESOURCE_URL = "https://merchant.example/report"
+PURPOSE = "testnet_integration_validation"
+ASSET = "0x036CbD53842c5426634e7929541eC2318f3dCF7e"
+APPROVED_PAY_TO = "synthetic-testnet-recipient"
+
+
+def challenge_header() -> str:
+ challenge = {
+ "x402Version": 2,
+ "resource": {
+ "url": RESOURCE_URL,
+ "description": "Synthetic paid test resource",
+ "mimeType": "application/json",
+ },
+ "accepts": [
+ {
+ "scheme": "exact",
+ "network": "eip155:84532",
+ "amount": "2000",
+ "asset": ASSET,
+ "payTo": APPROVED_PAY_TO,
+ "maxTimeoutSeconds": 300,
+ "extra": {"name": "USDC", "version": "2"},
+ }
+ ],
+ }
+ return base64.b64encode(json.dumps(challenge).encode("utf-8")).decode("ascii")
+
+
+class FakeManager:
+ def __init__(self) -> None:
+ self.calls: list[dict[str, Any]] = []
+
+ def process_payment(self, **kwargs: Any) -> dict[str, Any]:
+ self.calls.append(kwargs)
+ return {
+ "status": "PROOF_GENERATED",
+ "paymentOutput": {
+ "cryptoX402": {
+ "version": "2",
+ "payload": {"signature": "test-proof-not-a-secret"},
+ }
+ },
+ }
+
+
+class RecordingClientFactory:
+ def __init__(self, *, paid_status_code: int = 200) -> None:
+ self.requests: list[httpx.Request] = []
+ self.paid_status_code = paid_status_code
+
+ def __call__(self) -> httpx.Client:
+ def handler(request: httpx.Request) -> httpx.Response:
+ self.requests.append(request)
+ if "PAYMENT-SIGNATURE" not in request.headers:
+ return httpx.Response(
+ 402,
+ headers={"PAYMENT-REQUIRED": challenge_header()},
+ text="payment required",
+ )
+ return httpx.Response(
+ self.paid_status_code,
+ headers={"content-type": "application/json"},
+ json={"resource": "synthetic-testnet-content"},
+ )
+
+ return httpx.Client(transport=httpx.MockTransport(handler))
+
+
+def build_application(
+ now: datetime,
+ *,
+ clock: Callable[[], datetime] | None = None,
+ paid_status_code: int = 200,
+ session_expires_at: datetime | None = None,
+) -> tuple[AgentCoreAuthorizedApplication, RecordingClientFactory, FakeManager]:
+ transport = RecordingClientFactory(paid_status_code=paid_status_code)
+ manager = FakeManager()
+ settings = AgentCorePaymentsSettings(
+ enabled=True,
+ aws_region="us-east-1",
+ payment_manager_arn="arn:test:manager",
+ payment_instrument_id="instrument-test",
+ payment_session_id="session-test",
+ payment_user_id="user-test",
+ allowed_merchants=frozenset({"merchant.example"}),
+ approved_asset=ASSET,
+ approved_pay_to=APPROVED_PAY_TO,
+ max_approved_amount_atomic=2000,
+ max_payment_attempts=1,
+ )
+ policy = PolicyEngine(
+ CommercePolicy(
+ allowed_merchants=frozenset({"merchant.example"}),
+ allowed_purposes=frozenset({PURPOSE}),
+ per_request_limit=Decimal("0.002"),
+ per_run_limit=Decimal("0.002"),
+ approval_threshold=Decimal(0),
+ session_expires_at=(session_expires_at or now + timedelta(minutes=10)),
+ )
+ )
+
+ def build_client(
+ authorize_challenge: AuthorizationCallback,
+ ) -> AgentCoreX402Client:
+ return AgentCoreX402Client(
+ settings,
+ manager=manager,
+ client_factory=transport,
+ resolver=lambda _: ["8.8.8.8"],
+ authorize_challenge=authorize_challenge,
+ )
+
+ return (
+ AgentCoreAuthorizedApplication(
+ policy=policy,
+ client_factory=build_client,
+ clock=clock or (lambda: now),
+ ),
+ transport,
+ manager,
+ )
+
+
+def approval(
+ now: datetime,
+ *,
+ expires_at: datetime | None = None,
+) -> ApprovalGrant:
+ return ApprovalGrant(
+ approval_id="approval-agentcore-test-001",
+ request_id="request-agentcore-test-001",
+ resource_url=RESOURCE_URL,
+ purpose=PURPOSE,
+ maximum_amount=Decimal("0.002"),
+ approved_by="test-reviewer",
+ approved_at=now,
+ expires_at=expires_at or now + timedelta(minutes=5),
+ )
+
+
+def request() -> PurchaseRequest:
+ return PurchaseRequest(
+ request_id="request-agentcore-test-001",
+ resource_url=RESOURCE_URL,
+ purpose=PURPOSE,
+ idempotency_key="purchase-agentcore-test-001",
+ )
+
+
+def test_full_agents_sdk_agentcore_join_runs_offline() -> None:
+ now = datetime(2026, 8, 1, 12, 0, tzinfo=UTC)
+ application, transport, manager = build_application(now)
+ model = ScriptedAgentCoreLearningModel(
+ resource_url=RESOURCE_URL,
+ purpose=PURPOSE,
+ )
+
+ run = asyncio.run(
+ run_agentcore_access(
+ application,
+ model=model,
+ request_id=request().request_id,
+ idempotency_key=request().idempotency_key,
+ approval=approval(now),
+ resource_url=RESOURCE_URL,
+ purpose=PURPOSE,
+ )
+ )
+
+ assert model.model_turns == 2
+ assert model.requested_tools == ["x402_fetch"]
+ assert len(transport.requests) == 2
+ assert len(manager.calls) == 1
+ assert run.output.amount == "0.002"
+ assert run.output.payment_attempts == 1
+ assert run.output.requires_human_approval is True
+ assert application.policy.spent == Decimal("0.002")
+ assert [event.event_type for event in run.access.audit_events] == [
+ AuditEventType.RESOURCE_REQUESTED,
+ AuditEventType.PAYMENT_REQUIRED,
+ AuditEventType.AUTHORIZATION_CHECKED,
+ AuditEventType.PAYMENT_ATTEMPTED,
+ AuditEventType.CONTENT_RETURNED,
+ ]
+
+
+def test_combined_agent_uses_verified_bedrock_model_settings() -> None:
+ now = datetime(2026, 8, 1, 12, 0, tzinfo=UTC)
+ application, _, _ = build_application(now)
+ recorder = AgentCoreAccessRecorder()
+ agent = build_agentcore_access_agent(
+ application,
+ model=ScriptedAgentCoreLearningModel(
+ resource_url=RESOURCE_URL,
+ purpose=PURPOSE,
+ ),
+ request_id=request().request_id,
+ idempotency_key=request().idempotency_key,
+ approval=approval(now),
+ recorder=recorder,
+ )
+
+ assert agent.model_settings.store is False
+ assert agent.model_settings.reasoning is not None
+ assert agent.model_settings.reasoning.effort == "low"
+
+
+def test_missing_human_approval_stops_before_payment_header() -> None:
+ now = datetime(2026, 8, 1, 12, 0, tzinfo=UTC)
+ application, transport, manager = build_application(now)
+
+ with pytest.raises(PolicyDenied) as exc_info:
+ application.access(request(), approval=None, now=now)
+
+ assert exc_info.value.code == "human_approval_required"
+ assert len(transport.requests) == 1
+ assert manager.calls == []
+ assert application.policy.spent == Decimal(0)
+
+
+def test_non_200_paid_retry_cannot_complete() -> None:
+ now = datetime(2026, 8, 1, 12, 0, tzinfo=UTC)
+ application, transport, manager = build_application(
+ now,
+ paid_status_code=204,
+ )
+
+ with pytest.raises(CommerceError) as exc_info:
+ application.access(request(), approval=approval(now), now=now)
+
+ assert exc_info.value.code == "paid_resource_unavailable"
+ assert len(transport.requests) == 2
+ assert len(manager.calls) == 1
+
+
+def test_authorization_resamples_time_after_merchant_response() -> None:
+ now = datetime(2026, 8, 1, 12, 0, tzinfo=UTC)
+ moments = iter([now, now + timedelta(seconds=2)])
+ application, transport, manager = build_application(
+ now,
+ clock=lambda: next(moments),
+ )
+
+ with pytest.raises(PolicyDenied) as exc_info:
+ application.access(
+ request(),
+ approval=approval(
+ now,
+ expires_at=now + timedelta(seconds=1),
+ ),
+ )
+
+ assert exc_info.value.code == "approval_expired"
+ assert len(transport.requests) == 1
+ assert manager.calls == []
+ assert application.policy.spent == Decimal(0)
+
+
+def test_session_expiry_is_rechecked_after_merchant_response() -> None:
+ now = datetime(2026, 8, 1, 12, 0, tzinfo=UTC)
+ moments = iter([now, now + timedelta(seconds=2)])
+ application, transport, manager = build_application(
+ now,
+ clock=lambda: next(moments),
+ session_expires_at=now + timedelta(seconds=1),
+ )
+
+ with pytest.raises(PolicyDenied) as exc_info:
+ application.access(request(), approval=approval(now))
+
+ assert exc_info.value.code == "session_expired"
+ assert len(transport.requests) == 1
+ assert manager.calls == []
+ assert application.policy.spent == Decimal(0)
+
+
+def test_preflight_denial_stops_before_adapter_or_network() -> None:
+ now = datetime(2026, 8, 1, 12, 0, tzinfo=UTC)
+ application, transport, manager = build_application(now)
+ denied = request().model_copy(update={"purpose": "unapproved"})
+
+ with pytest.raises(PolicyDenied) as exc_info:
+ application.access(denied, approval=approval(now), now=now)
+
+ assert exc_info.value.code == "purpose_not_allowed"
+ assert transport.requests == []
+ assert manager.calls == []
+
+
+def test_fabricated_agent_transport_evidence_is_rejected() -> None:
+ now = datetime(2026, 8, 1, 12, 0, tzinfo=UTC)
+ application, _, _ = build_application(now)
+ access = application.access(request(), approval=approval(now), now=now)
+ recorder = AgentCoreAccessRecorder(invocations=1, results=[access])
+ fabricated = AgentCoreAccessOutput(
+ status="completed",
+ merchant=access.merchant,
+ status_code=access.status_code,
+ amount=str(access.challenge.amount),
+ currency=access.challenge.currency,
+ network=access.challenge.network,
+ payment_attempts=access.payment_attempts,
+ response_sha256="0" * 64,
+ response_bytes=access.response_bytes,
+ requires_human_approval=True,
+ )
+
+ with pytest.raises(AgentResultInvalid) as exc_info:
+ validate_agentcore_access_output(fabricated, recorder)
+
+ assert exc_info.value.code == "agent_output_mismatch"
+
+
+def test_missing_completed_tool_access_is_rejected() -> None:
+ output = AgentCoreAccessOutput(
+ status="completed",
+ merchant="merchant.example",
+ status_code=200,
+ amount="0.002",
+ currency="USDC",
+ network="eip155:84532",
+ payment_attempts=1,
+ response_sha256="0" * 64,
+ response_bytes=2,
+ requires_human_approval=True,
+ )
+
+ with pytest.raises(AgentResultInvalid) as exc_info:
+ validate_agentcore_access_output(output, AgentCoreAccessRecorder())
+
+ assert exc_info.value.code == "access_count_invalid"
+
+
+def test_single_tool_failure_is_reported_without_masking_its_code() -> None:
+ output = AgentCoreAccessOutput(
+ status="completed",
+ merchant="merchant.example",
+ status_code=200,
+ amount="0.002",
+ currency="USDC",
+ network="eip155:84532",
+ payment_attempts=1,
+ response_sha256="0" * 64,
+ response_bytes=2,
+ requires_human_approval=True,
+ )
+ recorder = AgentCoreAccessRecorder()
+ assert recorder.begin_invocation() is True
+ recorder.record_failure(
+ CommerceError(
+ "payment_header_generation_failed",
+ "AgentCore Payments could not generate a testnet payment header.",
+ )
+ )
+
+ with pytest.raises(AgentResultInvalid) as exc_info:
+ validate_agentcore_access_output(output, recorder)
+
+ assert exc_info.value.code == "payment_header_generation_failed"
+
+
+def test_second_tool_invocation_is_blocked_before_side_effects() -> None:
+ now = datetime(2026, 8, 1, 12, 0, tzinfo=UTC)
+ application, transport, manager = build_application(now)
+ recorder = AgentCoreAccessRecorder()
+ agent = build_agentcore_access_agent(
+ application,
+ model=ScriptedAgentCoreLearningModel(
+ resource_url=RESOURCE_URL,
+ purpose=PURPOSE,
+ ),
+ request_id=request().request_id,
+ idempotency_key=request().idempotency_key,
+ approval=approval(now),
+ recorder=recorder,
+ )
+ tool = agent.tools[0]
+ arguments = json.dumps({"resource_url": RESOURCE_URL, "purpose": PURPOSE})
+
+ first = asyncio.run(
+ tool.on_invoke_tool(
+ ToolContext(
+ context=None,
+ tool_name="x402_fetch",
+ tool_call_id="call-1",
+ tool_arguments=arguments,
+ ),
+ arguments,
+ )
+ )
+ second = asyncio.run(
+ tool.on_invoke_tool(
+ ToolContext(
+ context=None,
+ tool_name="x402_fetch",
+ tool_call_id="call-2",
+ tool_arguments=arguments,
+ ),
+ arguments,
+ )
+ )
+
+ assert json.loads(second)["code"] == "access_count_invalid"
+ assert recorder.invocations == 2
+ assert len(transport.requests) == 2
+ assert len(manager.calls) == 1
+ output = AgentCoreAccessOutput.model_validate_json(first)
+ with pytest.raises(AgentResultInvalid) as exc_info:
+ validate_agentcore_access_output(output, recorder)
+ assert exc_info.value.code == "access_count_invalid"
+
+
+def test_bedrock_profile_is_required_and_separate_configuration() -> None:
+ with pytest.raises(CommerceError) as exc_info:
+ _bedrock_profile({})
+
+ assert exc_info.value.code == "bedrock_profile_missing"
+ assert _bedrock_profile({"BEDROCK_AWS_PROFILE": "model"}) == "model"
+
+
+def test_unexpected_live_failure_report_does_not_echo_provider_details() -> None:
+ report = _blocked_report(RuntimeError("secret-token payment-session-identifier"))
+ rendered = json.dumps(report)
+
+ assert report["result"] == "BLOCKED"
+ assert report["exception_type"] == "RuntimeError"
+ assert report["proof_headers_logged"] is False
+ assert report["value_transferred"] == "unknown"
+ assert "secret-token" not in rendered
+ assert "payment-session-identifier" not in rendered
diff --git a/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/tests/test_agentcore_e2e.py b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/tests/test_agentcore_e2e.py
new file mode 100644
index 00000000..32ba1888
--- /dev/null
+++ b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/tests/test_agentcore_e2e.py
@@ -0,0 +1,437 @@
+from __future__ import annotations
+
+import asyncio
+import json
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from agentic_commerce import agentcore_e2e
+from agentic_commerce.agentcore_e2e import (
+ readiness_report,
+ run_managed_e2e,
+)
+from agentic_commerce.errors import AgentCorePaymentError, CommerceError
+
+ASSET = "0x036CbD53842c5426634e7929541eC2318f3dCF7e"
+
+
+class FakeSessionManager:
+ def __init__(
+ self,
+ *,
+ delete_error: Exception | None = None,
+ ) -> None:
+ self.delete_error = delete_error
+ self.create_calls: list[dict[str, Any]] = []
+ self.delete_calls: list[dict[str, Any]] = []
+
+ def create_payment_session(self, **kwargs: Any) -> dict[str, Any]:
+ self.create_calls.append(kwargs)
+ return {"paymentSessionId": "session-sensitive-e2e"}
+
+ def delete_payment_session(
+ self,
+ payment_session_id: str,
+ user_id: str | None = None,
+ ) -> dict[str, Any]:
+ self.delete_calls.append(
+ {
+ "payment_session_id": payment_session_id,
+ "user_id": user_id,
+ }
+ )
+ if self.delete_error is not None:
+ raise self.delete_error
+ return {"status": "DELETED"}
+
+
+def environment(tmp_path: Path) -> dict[str, str]:
+ return {
+ "RUN_AGENTCORE_E2E": "1",
+ "ALLOW_AGENTCORE_SESSION_ADMIN": "1",
+ "ALLOW_PAID_INFERENCE": "1",
+ "ALLOW_AGENTCORE_TESTNET": "1",
+ "APPROVE_AGENTCORE_TESTNET_PURCHASE": "1",
+ "BEDROCK_AWS_PROFILE": "model-inference",
+ "AGENTCORE_SESSION_AWS_PROFILE": "session-admin",
+ "AGENTCORE_RUNTIME_AWS_PROFILE": "payment-runtime",
+ "AGENTCORE_SESSION_FILE": str(tmp_path / "session.env"),
+ "AGENTCORE_AWS_REGION": "us-east-1",
+ "PAYMENT_MANAGER_ARN": "manager-sensitive-e2e",
+ "PAYMENT_INSTRUMENT_ID": "instrument-sensitive-e2e",
+ "PAYMENT_USER_ID": "user-sensitive-e2e",
+ "X402_ALLOWED_MERCHANTS": "merchant.example",
+ "X402_APPROVED_ASSET": ASSET,
+ "X402_APPROVED_PAY_TO": "synthetic-testnet-recipient",
+ "X402_MAX_APPROVED_AMOUNT_ATOMIC": "2000",
+ "X402_MAX_PAYMENT_ATTEMPTS": "1",
+ "X402_RESOURCE_URL": "https://merchant.example/report",
+ "X402_IDEMPOTENCY_KEY": "purchase-e2e-test-001",
+ }
+
+
+def sdk_available(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ agentcore_e2e.importlib.metadata,
+ "version",
+ lambda _: "1.18.1",
+ )
+
+
+def test_readiness_requires_master_gate_before_any_live_call(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ sdk_available(monkeypatch)
+ values = environment(tmp_path)
+ values["RUN_AGENTCORE_E2E"] = "0"
+
+ report = readiness_report(values)
+
+ assert report["result"] == "NOT_READY"
+ assert report["missing_opt_ins"] == ["RUN_AGENTCORE_E2E=1"]
+ assert report["live_calls"] == 0
+ assert report["value_transferred"] is False
+
+
+def test_execute_combined_rechecks_all_live_opt_ins() -> None:
+ with pytest.raises(CommerceError) as exc_info:
+ asyncio.run(agentcore_e2e._execute_combined({}))
+
+ assert exc_info.value.code == "agentcore_live_opt_ins_missing"
+
+
+def test_combined_report_rejects_incomplete_paid_retry() -> None:
+ result = SimpleNamespace(access=SimpleNamespace(status_code=204))
+
+ with pytest.raises(CommerceError) as exc_info:
+ agentcore_e2e._combined_success_report(result)
+
+ assert exc_info.value.code == "merchant_paid_retry_incomplete"
+
+
+def test_readiness_rejects_proxy_environment(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ sdk_available(monkeypatch)
+ values = environment(tmp_path)
+ values["HTTPS_PROXY"] = "http://proxy.example:8080"
+
+ report = readiness_report(values)
+
+ assert report["result"] == "NOT_READY"
+ assert report["merchant_proxy_environment_clear"] is False
+
+
[email protected]("value", ["NaN", "Infinity", "-Infinity", "2e3"])
+def test_readiness_rejects_invalid_session_budget(
+ value: str,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ sdk_available(monkeypatch)
+ values = environment(tmp_path)
+ values["X402_MAX_APPROVED_AMOUNT_ATOMIC"] = value
+
+ report = readiness_report(values)
+
+ assert report["result"] == "NOT_READY"
+ assert report["session_budget_valid"] is False
+
+
+def test_readiness_requires_distinct_admin_and_runtime_profiles(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ sdk_available(monkeypatch)
+ values = environment(tmp_path)
+ values["AGENTCORE_RUNTIME_AWS_PROFILE"] = "session-admin"
+
+ report = readiness_report(values)
+
+ assert report["result"] == "NOT_READY"
+ assert report["separate_aws_profiles_present"] is True
+ assert report["aws_profiles_are_distinct"] is False
+
+
+def test_readiness_requires_distinct_model_and_payment_profiles(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ sdk_available(monkeypatch)
+ values = environment(tmp_path)
+ values["BEDROCK_AWS_PROFILE"] = "payment-runtime"
+
+ report = readiness_report(values)
+
+ assert report["result"] == "NOT_READY"
+ assert report["bedrock_profile_present"] is True
+ assert report["model_and_payment_profiles_are_distinct"] is False
+ assert report["aws_profiles_are_distinct"] is False
+
+
+def test_managed_e2e_checks_the_overridden_session_file(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ sdk_available(monkeypatch)
+ values = environment(tmp_path)
+ override = tmp_path / "override.env"
+ override.write_text(
+ "PAYMENT_SESSION_ID=existing-session\n",
+ encoding="utf-8",
+ )
+ manager = FakeSessionManager()
+
+ report = asyncio.run(
+ run_managed_e2e(
+ values,
+ manager_factory=lambda _: manager,
+ session_file=override,
+ )
+ )
+
+ assert report["result"] == "SKIPPED"
+ assert report["recorded_session_present"] is True
+ assert manager.create_calls == []
+ assert manager.delete_calls == []
+
+
+def test_check_cli_never_starts_managed_workflow(
+ monkeypatch: pytest.MonkeyPatch,
+ capsys: pytest.CaptureFixture[str],
+) -> None:
+ monkeypatch.setattr(
+ agentcore_e2e,
+ "readiness_report",
+ lambda: {"result": "READY", "live_calls": 0},
+ )
+ monkeypatch.setattr(
+ agentcore_e2e.asyncio,
+ "run",
+ lambda _: pytest.fail("managed workflow must not start"),
+ )
+
+ agentcore_e2e.main(["--check"])
+
+ assert json.loads(capsys.readouterr().out) == {
+ "result": "READY",
+ "live_calls": 0,
+ }
+
+
+def test_check_cli_returns_nonzero_when_not_ready(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ agentcore_e2e,
+ "readiness_report",
+ lambda: {"result": "NOT_READY", "live_calls": 0},
+ )
+
+ with pytest.raises(SystemExit) as exc_info:
+ agentcore_e2e.main(["--check"])
+
+ assert exc_info.value.code == 2
+
+
+def test_live_cli_returns_nonzero_when_skipped(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ async def skipped() -> dict[str, object]:
+ return {"result": "SKIPPED"}
+
+ monkeypatch.setattr(agentcore_e2e, "run_managed_e2e", skipped)
+
+ with pytest.raises(SystemExit) as exc_info:
+ asyncio.run(agentcore_e2e.run())
+
+ assert exc_info.value.code == 2
+
+
+def test_managed_e2e_creates_runs_and_deletes_without_logging_ids(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ sdk_available(monkeypatch)
+ values = environment(tmp_path)
+ manager = FakeSessionManager()
+ observed_session_id = ""
+
+ async def combined_runner(
+ runtime_environment: dict[str, str],
+ ) -> dict[str, object]:
+ nonlocal observed_session_id
+ observed_session_id = runtime_environment["PAYMENT_SESSION_ID"]
+ return {
+ "result": "PASSED",
+ "model_run_completed": True,
+ "agentcore_payment_path_completed": True,
+ "merchant_paid_retry_completed": True,
+ "status_code": 200,
+ "payment_attempts": 1,
+ "authorized_amount": "0.002",
+ "currency": "USDC",
+ "network": "eip155:84532",
+ "proof_headers_logged": False,
+ "settlement_verified": False,
+ }
+
+ report = asyncio.run(
+ run_managed_e2e(
+ values,
+ manager_factory=lambda _: manager,
+ combined_runner=combined_runner,
+ )
+ )
+ rendered = json.dumps(report)
+
+ assert report["result"] == "PASSED"
+ assert report["session_created"] is True
+ assert report["session_budget_usd"] == "0.002"
+ assert report["session_expiry_minutes"] == 15
+ assert report["session_cleanup"] == "DELETED"
+ assert report["identifiers_logged"] is False
+ assert report["settlement_verified"] is False
+ assert observed_session_id == "session-sensitive-e2e"
+ assert len(manager.create_calls) == 1
+ assert len(manager.delete_calls) == 1
+ assert not (tmp_path / "session.env").exists()
+ assert "session-sensitive-e2e" not in rendered
+ assert "manager-sensitive-e2e" not in rendered
+ assert "instrument-sensitive-e2e" not in rendered
+ assert "user-sensitive-e2e" not in rendered
+
+
+def test_managed_e2e_deletes_session_after_runtime_failure(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ sdk_available(monkeypatch)
+ values = environment(tmp_path)
+ manager = FakeSessionManager()
+
+ async def failing_runner(_: dict[str, str]) -> dict[str, object]:
+ raise RuntimeError("provider-secret session-sensitive-e2e")
+
+ report = asyncio.run(
+ run_managed_e2e(
+ values,
+ manager_factory=lambda _: manager,
+ combined_runner=failing_runner,
+ )
+ )
+ rendered = json.dumps(report)
+
+ assert report["result"] == "BLOCKED"
+ assert report["session_cleanup"] == "DELETED"
+ assert report["value_transferred"] == "unknown"
+ assert len(manager.delete_calls) == 1
+ assert not (tmp_path / "session.env").exists()
+ assert "provider-secret" not in rendered
+ assert "session-sensitive-e2e" not in rendered
+
+
+def test_managed_e2e_returns_safe_payment_diagnostics(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ sdk_available(monkeypatch)
+ values = environment(tmp_path)
+ manager = FakeSessionManager()
+
+ async def failing_runner(_: dict[str, str]) -> dict[str, object]:
+ raise AgentCorePaymentError(
+ "payment_header_generation_failed",
+ "AgentCore Payments could not generate a testnet payment header.",
+ diagnostics={
+ "stage": "agentcore_process_payment",
+ "category": "aws_validation",
+ "provider_message_logged": False,
+ "request_id_logged": False,
+ "aws_error_code": "ValidationException",
+ "http_status_code": 400,
+ },
+ )
+
+ report = asyncio.run(
+ run_managed_e2e(
+ values,
+ manager_factory=lambda _: manager,
+ combined_runner=failing_runner,
+ )
+ )
+ rendered = json.dumps(report)
+
+ assert report["result"] == "FAILED"
+ assert report["session_cleanup"] == "DELETED"
+ assert report["diagnostics"] == {
+ "stage": "agentcore_process_payment",
+ "category": "aws_validation",
+ "provider_message_logged": False,
+ "request_id_logged": False,
+ "aws_error_code": "ValidationException",
+ "http_status_code": 400,
+ }
+ assert "manager-sensitive-e2e" not in rendered
+ assert "instrument-sensitive-e2e" not in rendered
+ assert "user-sensitive-e2e" not in rendered
+
+
+def test_managed_e2e_retains_state_when_cleanup_fails(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ sdk_available(monkeypatch)
+ values = environment(tmp_path)
+ manager = FakeSessionManager(delete_error=RuntimeError("provider-secret"))
+
+ async def combined_runner(_: dict[str, str]) -> dict[str, object]:
+ return {"result": "PASSED", "status_code": 200}
+
+ report = asyncio.run(
+ run_managed_e2e(
+ values,
+ manager_factory=lambda _: manager,
+ combined_runner=combined_runner,
+ )
+ )
+ rendered = json.dumps(report)
+
+ assert report["result"] == "BLOCKED"
+ assert report["category"] == "payment_session_cleanup_error"
+ assert report["session_cleanup"] == "FAILED"
+ assert (tmp_path / "session.env").exists()
+ assert "provider-secret" not in rendered
+ assert "session-sensitive-e2e" not in rendered
+
+
+def test_runtime_failure_and_cleanup_failure_preserve_cleanup_action(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ sdk_available(monkeypatch)
+ values = environment(tmp_path)
+ manager = FakeSessionManager(delete_error=RuntimeError("cleanup-secret"))
+
+ async def failing_runner(_: dict[str, str]) -> dict[str, object]:
+ raise RuntimeError("runtime-secret")
+
+ report = asyncio.run(
+ run_managed_e2e(
+ values,
+ manager_factory=lambda _: manager,
+ combined_runner=failing_runner,
+ )
+ )
+ rendered = json.dumps(report)
+
+ assert report["result"] == "BLOCKED"
+ assert report["session_cleanup"] == "FAILED"
+ assert "Delete the recorded bounded session" in str(report["cleanup_next_action"])
+ assert "runtime-secret" not in rendered
+ assert "cleanup-secret" not in rendered
diff --git a/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/tests/test_agentcore_infrastructure.py b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/tests/test_agentcore_infrastructure.py
new file mode 100644
index 00000000..8e1415d1
--- /dev/null
+++ b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/tests/test_agentcore_infrastructure.py
@@ -0,0 +1,256 @@
+from __future__ import annotations
+
+import json
+import sys
+from types import ModuleType
+from typing import Any
+
+import pytest
+
+from agentic_commerce import agentcore_infrastructure
+from agentic_commerce.agentcore_infrastructure import (
+ inspect_payment_instrument,
+ readiness_report,
+)
+
+
+class FakeInstrumentReader:
+ def __init__(
+ self,
+ response: dict[str, Any] | None = None,
+ balance_response: dict[str, Any] | None = None,
+ error: Exception | None = None,
+ ) -> None:
+ self.response = response or {}
+ self.balance_response = balance_response or {
+ "tokenBalance": {
+ "amount": "1000000",
+ "decimals": 6,
+ "chain": "BASE_SEPOLIA",
+ "token": "USDC",
+ }
+ }
+ self.error = error
+ self.calls: list[dict[str, object]] = []
+ self.balance_calls: list[dict[str, object]] = []
+
+ def get_payment_instrument(self, **kwargs: object) -> dict[str, Any]:
+ self.calls.append(kwargs)
+ if self.error is not None:
+ raise self.error
+ return self.response
+
+ def get_payment_instrument_balance(self, **kwargs: object) -> dict[str, Any]:
+ self.balance_calls.append(kwargs)
+ if self.error is not None:
+ raise self.error
+ return self.balance_response
+
+
+def environment() -> dict[str, str]:
+ return {
+ "ALLOW_AGENTCORE_READ_ONLY": "1",
+ "AGENTCORE_AWS_REGION": "us-east-1",
+ "AGENTCORE_RUNTIME_AWS_PROFILE": "payment-runtime",
+ "PAYMENT_MANAGER_ARN": "manager-sensitive-read-only",
+ "PAYMENT_CONNECTOR_ID": "connector-sensitive-read-only",
+ "PAYMENT_INSTRUMENT_ID": "instrument-sensitive-read-only",
+ "PAYMENT_USER_ID": "user-sensitive-read-only",
+ }
+
+
+def test_readiness_is_no_call_and_redacts_configuration() -> None:
+ report = readiness_report(environment())
+ rendered = json.dumps(report)
+
+ assert report["result"] == "READY"
+ assert report["aws_calls"] == 0
+ assert report["value_transferred"] is False
+ assert "manager-sensitive-read-only" not in rendered
+ assert "connector-sensitive-read-only" not in rendered
+ assert "instrument-sensitive-read-only" not in rendered
+ assert "user-sensitive-read-only" not in rendered
+
+
+def test_read_only_profile_uses_agentcore_region(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ captured: dict[str, object] = {}
+ boto3_module = ModuleType("boto3")
+ payments_module = ModuleType("bedrock_agentcore.payments")
+ agentcore_module = ModuleType("bedrock_agentcore")
+
+ def build_session(*, profile_name: str, region_name: str) -> object:
+ session = object()
+ captured["profile_name"] = profile_name
+ captured["region_name"] = region_name
+ captured["boto3_session"] = session
+ return session
+
+ def build_manager(**kwargs: object) -> object:
+ captured["manager_kwargs"] = kwargs
+ return object()
+
+ boto3_module.Session = build_session # type: ignore[attr-defined]
+ payments_module.PaymentManager = build_manager # type: ignore[attr-defined]
+ agentcore_module.payments = payments_module # type: ignore[attr-defined]
+ monkeypatch.setitem(sys.modules, "boto3", boto3_module)
+ monkeypatch.setitem(sys.modules, "bedrock_agentcore", agentcore_module)
+ monkeypatch.setitem(
+ sys.modules,
+ "bedrock_agentcore.payments",
+ payments_module,
+ )
+
+ agentcore_infrastructure._manager(environment())
+
+ assert captured["profile_name"] == "payment-runtime"
+ assert captured["region_name"] == "us-east-1"
+ manager_kwargs = captured["manager_kwargs"]
+ assert isinstance(manager_kwargs, dict)
+ assert manager_kwargs["boto3_session"] is captured["boto3_session"]
+
+
+def test_inspection_skips_without_explicit_read_only_gate() -> None:
+ values = environment()
+ values["ALLOW_AGENTCORE_READ_ONLY"] = "0"
+ manager = FakeInstrumentReader()
+
+ report = inspect_payment_instrument(
+ values,
+ manager_factory=lambda _: manager,
+ )
+
+ assert report["result"] == "SKIPPED"
+ assert report["aws_calls"] == 0
+ assert manager.calls == []
+
+
+def test_active_instrument_returns_sanitized_read_only_evidence() -> None:
+ manager = FakeInstrumentReader(
+ {
+ "paymentInstrumentId": "instrument-sensitive-response",
+ "status": "ACTIVE",
+ "paymentInstrumentDetails": {
+ "embeddedCryptoWallet": {"network": "ETHEREUM"}
+ },
+ }
+ )
+
+ report = inspect_payment_instrument(
+ environment(),
+ manager_factory=lambda _: manager,
+ )
+ rendered = json.dumps(report)
+
+ assert report["result"] == "PASSED"
+ assert report["payment_manager_reachable"] is True
+ assert report["payment_instrument_status"] == "ACTIVE"
+ assert report["payment_instrument_network"] == "ETHEREUM"
+ assert report["payment_instrument_chain"] == "BASE_SEPOLIA"
+ assert report["payment_instrument_token"] == "USDC"
+ assert report["exact_testnet_scope_verified"] is True
+ assert report["aws_calls"] == 2
+ assert report["payment_attempts"] == 0
+ assert report["value_transferred"] is False
+ assert "instrument-sensitive-response" not in rendered
+ assert "instrument-sensitive-read-only" not in rendered
+ assert "connector-sensitive-read-only" not in rendered
+ assert manager.balance_calls == [
+ {
+ "payment_connector_id": "connector-sensitive-read-only",
+ "payment_instrument_id": "instrument-sensitive-read-only",
+ "chain": "BASE_SEPOLIA",
+ "token": "USDC",
+ "user_id": "user-sensitive-read-only",
+ }
+ ]
+
+
+def test_active_instrument_on_wrong_network_is_not_ready() -> None:
+ manager = FakeInstrumentReader(
+ {
+ "status": "ACTIVE",
+ "paymentInstrumentDetails": {"embeddedCryptoWallet": {"network": "SOLANA"}},
+ }
+ )
+
+ report = inspect_payment_instrument(
+ environment(),
+ manager_factory=lambda _: manager,
+ )
+
+ assert report["result"] == "NOT_READY"
+ assert report["payment_instrument_network"] == "SOLANA"
+ assert report["exact_testnet_scope_verified"] is False
+ assert report["aws_calls"] == 1
+ assert manager.balance_calls == []
+
+
+def test_balance_scope_must_confirm_base_sepolia_usdc() -> None:
+ manager = FakeInstrumentReader(
+ {
+ "status": "ACTIVE",
+ "paymentInstrumentDetails": {
+ "embeddedCryptoWallet": {"network": "ETHEREUM"}
+ },
+ },
+ balance_response={
+ "tokenBalance": {
+ "amount": "1000000",
+ "decimals": 6,
+ "chain": "ETHEREUM",
+ "token": "USDC",
+ }
+ },
+ )
+
+ report = inspect_payment_instrument(
+ environment(),
+ manager_factory=lambda _: manager,
+ )
+
+ assert report["result"] == "NOT_READY"
+ assert report["payment_instrument_chain"] == "ETHEREUM"
+ assert report["exact_testnet_scope_verified"] is False
+ assert report["aws_calls"] == 2
+
+
+def test_provider_failure_is_sanitized() -> None:
+ manager = FakeInstrumentReader(
+ error=RuntimeError("provider-secret instrument-sensitive-read-only")
+ )
+
+ report = inspect_payment_instrument(
+ environment(),
+ manager_factory=lambda _: manager,
+ )
+ rendered = json.dumps(report)
+
+ assert report["result"] == "BLOCKED"
+ assert report["category"] == "agentcore_read_only_check_failed"
+ assert report["exception_type"] == "RuntimeError"
+ assert report["value_transferred"] is False
+ assert "provider-secret" not in rendered
+ assert "instrument-sensitive-read-only" not in rendered
+
+
+ ("result", "expected_exit"),
+ [("NOT_READY", 2), ("SKIPPED", 2), ("BLOCKED", 1)],
+)
+def test_cli_returns_nonzero_for_nonpassing_result(
+ result: str,
+ expected_exit: int,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ agentcore_infrastructure,
+ "inspect_payment_instrument",
+ lambda: {"result": result},
+ )
+
+ with pytest.raises(SystemExit) as exc_info:
+ agentcore_infrastructure.main()
+
+ assert exc_info.value.code == expected_exit
diff --git a/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/tests/test_agentcore_payments.py b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/tests/test_agentcore_payments.py
new file mode 100644
index 00000000..b94d365f
--- /dev/null
+++ b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/tests/test_agentcore_payments.py
@@ -0,0 +1,845 @@
+from __future__ import annotations
+
+import base64
+import hashlib
+import json
+import sys
+from collections.abc import Callable
+from datetime import UTC, datetime, timedelta
+from types import ModuleType
+from typing import Any
+
+import httpx
+import pytest
+from pydantic import SecretStr
+
+from agentic_commerce.agentcore_payments import (
+ AgentCorePaymentsSettings,
+ AgentCoreX402Client,
+)
+from agentic_commerce.errors import (
+ AgentCorePaymentError,
+ LivePaymentDisabled,
+)
+
+RESOURCE_URL = "https://merchant.example/report"
+PUBLIC_ADDRESS = "8.8.8.8"
+BASE_SEPOLIA_USDC = "0x036CbD53842c5426634e7929541eC2318f3dCF7e"
+APPROVED_PAY_TO = "synthetic-testnet-recipient"
+
+
+def challenge_header(
+ *,
+ amount: str = "2000",
+ network: str = "eip155:84532",
+ asset: str = BASE_SEPOLIA_USDC,
+ scheme: str = "exact",
+ resource_url: str = RESOURCE_URL,
+ pay_to: str = APPROVED_PAY_TO,
+ max_timeout_seconds: int = 300,
+ extra_update: dict[str, Any] | None = None,
+ requirement_update: dict[str, Any] | None = None,
+ extensions: dict[str, Any] | None = None,
+) -> str:
+ extra = {"name": "USDC", "version": "2"}
+ extra.update(extra_update or {})
+ requirement = {
+ "scheme": scheme,
+ "network": network,
+ "amount": amount,
+ "asset": asset,
+ "payTo": pay_to,
+ "maxTimeoutSeconds": max_timeout_seconds,
+ "extra": extra,
+ }
+ requirement.update(requirement_update or {})
+ challenge = {
+ "x402Version": 2,
+ "resource": {
+ "url": resource_url,
+ "description": "Synthetic paid test resource",
+ "mimeType": "application/json",
+ },
+ "accepts": [requirement],
+ }
+ if extensions is not None:
+ challenge["extensions"] = extensions
+ return base64.b64encode(json.dumps(challenge).encode("utf-8")).decode("ascii")
+
+
+class FakeManager:
+ def __init__(
+ self,
+ *,
+ result: dict[str, Any] | None = None,
+ error: Exception | None = None,
+ ) -> None:
+ self.result = result or {
+ "status": "PROOF_GENERATED",
+ "paymentOutput": {
+ "cryptoX402": {
+ "version": "2",
+ "payload": {"signature": "sensitive-test-proof"},
+ }
+ },
+ }
+ self.error = error
+ self.calls: list[dict[str, Any]] = []
+
+ def process_payment(self, **kwargs: Any) -> dict[str, Any]:
+ self.calls.append(kwargs)
+ if self.error is not None:
+ raise self.error
+ return self.result
+
+
+class RecordingClientFactory:
+ def __init__(
+ self,
+ handler: Callable[[httpx.Request], httpx.Response],
+ ) -> None:
+ self.handler = handler
+ self.created = 0
+
+ def __call__(self) -> httpx.Client:
+ self.created += 1
+ return httpx.Client(transport=httpx.MockTransport(self.handler))
+
+
+def settings(*, enabled: bool = True) -> AgentCorePaymentsSettings:
+ return AgentCorePaymentsSettings(
+ enabled=enabled,
+ aws_region="us-east-1",
+ payment_manager_arn="arn:test:manager",
+ payment_instrument_id="instrument-test",
+ payment_session_id="session-test",
+ payment_user_id="user-test",
+ allowed_merchants=frozenset({"merchant.example"}),
+ approved_asset=BASE_SEPOLIA_USDC,
+ approved_pay_to=APPROVED_PAY_TO,
+ max_approved_amount_atomic=2000,
+ )
+
+
+def client(
+ handler: Callable[[httpx.Request], httpx.Response],
+ *,
+ configured: AgentCorePaymentsSettings | None = None,
+ manager: FakeManager | None = None,
+ resolver: Callable[[str], list[str]] | None = None,
+ clock: Callable[[], datetime] | None = None,
+) -> tuple[AgentCoreX402Client, RecordingClientFactory, FakeManager]:
+ factory = RecordingClientFactory(handler)
+ fake_manager = manager or FakeManager()
+ adapter = AgentCoreX402Client(
+ configured or settings(),
+ manager=fake_manager,
+ client_factory=factory,
+ resolver=resolver or (lambda _: [PUBLIC_ADDRESS]),
+ authorize_challenge=lambda _: None,
+ **({"clock": clock} if clock is not None else {}),
+ )
+ return adapter, factory, fake_manager
+
+
+def test_successful_402_retry_uses_stable_token_and_fresh_client() -> None:
+ requests: list[httpx.Request] = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ requests.append(request)
+ if "PAYMENT-SIGNATURE" not in request.headers:
+ return httpx.Response(
+ 402,
+ headers={"PAYMENT-REQUIRED": challenge_header()},
+ text="payment required",
+ )
+ return httpx.Response(
+ 200,
+ headers={"content-type": "application/json"},
+ json={"report": "synthetic"},
+ )
+
+ adapter, factory, manager = client(handler)
+ result = adapter.fetch(
+ RESOURCE_URL,
+ client_token="purchase-test-001",
+ )
+
+ assert result.status_code == 200
+ assert result.payment_attempted is True
+ assert result.payment_attempts == 1
+ assert result.merchant == "merchant.example"
+ assert factory.created == 2
+ assert len(requests) == 2
+ assert all(request.url.host == PUBLIC_ADDRESS for request in requests)
+ assert all(request.headers["host"] == "merchant.example" for request in requests)
+ assert len(manager.calls) == 1
+ assert manager.calls[0]["client_token"] == "purchase-test-001"
+ assert manager.calls[0]["payment_type"] == "CRYPTO_X402"
+ assert manager.calls[0]["payment_input"]["cryptoX402"]["version"] == "2"
+ assert (
+ manager.calls[0]["payment_input"]["cryptoX402"]["payload"]["amount"] == "2000"
+ )
+ assert "sensitive-test-proof" not in result.model_dump_json()
+
+
+def test_bazaar_discovery_extension_is_validated_but_not_forwarded() -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ if "PAYMENT-SIGNATURE" not in request.headers:
+ return httpx.Response(
+ 402,
+ headers={
+ "PAYMENT-REQUIRED": challenge_header(
+ extensions={
+ "bazaar": {
+ "info": {"input": {"method": "GET"}},
+ "schema": {},
+ }
+ }
+ )
+ },
+ )
+ return httpx.Response(200, json={"report": "synthetic"})
+
+ adapter, _, manager = client(handler)
+
+ result = adapter.fetch(RESOURCE_URL, client_token="purchase-bazaar-test")
+
+ assert result.status_code == 200
+ assert len(manager.calls) == 1
+ assert (
+ "extensions" not in manager.calls[0]["payment_input"]["cryptoX402"]["payload"]
+ )
+
+
+ ("header", "expected_code"),
+ [
+ (
+ challenge_header(pay_to="different-recipient"),
+ "payment_challenge_recipient_denied",
+ ),
+ (
+ challenge_header(resource_url="https://merchant.example/other"),
+ "payment_challenge_resource_mismatch",
+ ),
+ (
+ challenge_header(max_timeout_seconds=301),
+ "payment_challenge_timeout_denied",
+ ),
+ (
+ challenge_header(requirement_update={"unapproved": "value"}),
+ "payment_challenge_fields_denied",
+ ),
+ (
+ challenge_header(extensions={"unapproved": {}}),
+ "payment_challenge_extensions_denied",
+ ),
+ (
+ challenge_header(
+ extensions={"bazaar": {"info": {}, "schema": {}, "unapproved": {}}}
+ ),
+ "payment_challenge_extensions_denied",
+ ),
+ (
+ challenge_header(extensions={"bazaar": {"info": [], "schema": {}}}),
+ "payment_challenge_extensions_denied",
+ ),
+ ],
+)
+def test_unapproved_challenge_semantics_never_reach_manager(
+ header: str,
+ expected_code: str,
+) -> None:
+ adapter, _, manager = client(
+ lambda _: httpx.Response(
+ 402,
+ headers={"PAYMENT-REQUIRED": header},
+ )
+ )
+
+ with pytest.raises(AgentCorePaymentError) as exc_info:
+ adapter.fetch(RESOURCE_URL, client_token="purchase-binding-test")
+
+ assert exc_info.value.code == expected_code
+ assert manager.calls == []
+
+
+def test_expired_challenge_never_reaches_manager() -> None:
+ now = datetime(2026, 8, 9, 12, 0, tzinfo=UTC)
+ header = challenge_header(
+ extra_update={"expiresAt": (now - timedelta(seconds=1)).isoformat()}
+ )
+ adapter, _, manager = client(
+ lambda _: httpx.Response(
+ 402,
+ headers={"PAYMENT-REQUIRED": header},
+ ),
+ clock=lambda: now,
+ )
+
+ with pytest.raises(AgentCorePaymentError) as exc_info:
+ adapter.fetch(RESOURCE_URL, client_token="purchase-expired-test")
+
+ assert exc_info.value.code == "payment_challenge_expired"
+ assert manager.calls == []
+
+
+def test_provider_receives_only_canonical_approved_requirement() -> None:
+ header = challenge_header(
+ extra_update={
+ "decimals": 6,
+ "currency": "USDC",
+ "merchantDomain": "merchant.example",
+ "challengeId": "synthetic-challenge",
+ }
+ )
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ if "PAYMENT-SIGNATURE" not in request.headers:
+ return httpx.Response(
+ 402,
+ headers={"PAYMENT-REQUIRED": header},
+ )
+ return httpx.Response(200, text="ok")
+
+ adapter, _, manager = client(handler)
+ adapter.fetch(RESOURCE_URL, client_token="purchase-canonical-test")
+
+ payload = manager.calls[0]["payment_input"]["cryptoX402"]["payload"]
+ assert payload == {
+ "scheme": "exact",
+ "network": "eip155:84532",
+ "amount": "2000",
+ "asset": BASE_SEPOLIA_USDC,
+ "payTo": APPROVED_PAY_TO,
+ "maxTimeoutSeconds": 300,
+ "extra": {
+ "name": "USDC",
+ "version": "2",
+ "decimals": 6,
+ "merchantDomain": "merchant.example",
+ "challengeId": "synthetic-challenge",
+ },
+ }
+
+
+def test_retry_limit_reuses_same_client_token() -> None:
+ def handler(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(
+ 402,
+ headers={"PAYMENT-REQUIRED": challenge_header()},
+ text="still unpaid",
+ )
+
+ adapter, factory, manager = client(handler)
+ with pytest.raises(AgentCorePaymentError) as exc_info:
+ adapter.fetch(
+ RESOURCE_URL,
+ client_token="purchase-test-002",
+ )
+
+ assert exc_info.value.code == "payment_attempts_exhausted"
+ assert factory.created == 3
+ assert [call["client_token"] for call in manager.calls] == [
+ "purchase-test-002",
+ "purchase-test-002",
+ ]
+
+
+def test_retry_rejects_a_changed_challenge_before_second_signature() -> None:
+ requests: list[httpx.Request] = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ requests.append(request)
+ amount = "1000" if len(requests) == 1 else "2000"
+ return httpx.Response(
+ 402,
+ headers={"PAYMENT-REQUIRED": challenge_header(amount=amount)},
+ text="payment required",
+ )
+
+ adapter, factory, manager = client(handler)
+
+ with pytest.raises(AgentCorePaymentError) as exc_info:
+ adapter.fetch(
+ RESOURCE_URL,
+ client_token="purchase-test-challenge-change",
+ )
+
+ assert exc_info.value.code == "payment_challenge_changed"
+ assert factory.created == 2
+ assert len(manager.calls) == 1
+
+
+def test_response_size_limit_is_enforced_while_streaming() -> None:
+ adapter, factory, manager = client(
+ lambda _: httpx.Response(200, content=b"12345"),
+ configured=settings().model_copy(update={"max_response_bytes": 4}),
+ )
+
+ with pytest.raises(AgentCorePaymentError) as exc_info:
+ adapter.fetch(
+ RESOURCE_URL,
+ client_token="purchase-test-response-limit",
+ )
+
+ assert exc_info.value.code == "merchant_response_too_large"
+ assert factory.created == 1
+ assert manager.calls == []
+
+
+def test_response_evidence_hashes_original_http_bytes() -> None:
+ response = httpx.Response(
+ 200,
+ content=b"\xff\xfe\x00raw-response",
+ headers={"content-type": "application/octet-stream"},
+ )
+
+ result = AgentCoreX402Client._result(
+ response,
+ merchant="merchant.example",
+ payment_attempts=1,
+ )
+
+ assert result.response_sha256 == hashlib.sha256(response.content).hexdigest()
+ assert result.response_bytes == len(response.content)
+
+
+def test_default_client_rejects_proxy_environment(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setenv("HTTPS_PROXY", "http://proxy.example:8080")
+ adapter = AgentCoreX402Client(settings())
+
+ with pytest.raises(AgentCorePaymentError) as exc_info:
+ adapter._default_client()
+
+ assert exc_info.value.code == "merchant_proxy_unsupported"
+
+
+def test_disabled_adapter_fails_before_network_or_manager() -> None:
+ adapter, factory, manager = client(
+ lambda _: httpx.Response(200),
+ configured=settings(enabled=False),
+ )
+
+ with pytest.raises(LivePaymentDisabled) as exc_info:
+ adapter.fetch(
+ RESOURCE_URL,
+ client_token="purchase-test-003",
+ )
+
+ assert exc_info.value.code == "agentcore_testnet_disabled"
+ assert factory.created == 0
+ assert manager.calls == []
+
+
+def test_missing_application_authorizer_fails_before_network() -> None:
+ factory = RecordingClientFactory(lambda _: httpx.Response(200))
+ manager = FakeManager()
+ adapter = AgentCoreX402Client(
+ settings(),
+ manager=manager,
+ client_factory=factory,
+ resolver=lambda _: [PUBLIC_ADDRESS],
+ )
+
+ with pytest.raises(AgentCorePaymentError) as exc_info:
+ adapter.fetch(
+ RESOURCE_URL,
+ client_token="purchase-test-no-authorizer",
+ )
+
+ assert exc_info.value.code == "application_authorization_missing"
+ assert factory.created == 0
+ assert manager.calls == []
+
+
+ ("resource_url", "expected_code"),
+ [
+ ("http://merchant.example/report", "https_resource_required"),
+ ("https://other.example/report", "merchant_not_allowed"),
+ (
+ "https://user:[email protected]/report",
+ "https_resource_required",
+ ),
+ (
+ "https://merchant.example:abc/report",
+ "https_resource_required",
+ ),
+ ],
+)
+def test_invalid_destinations_fail_before_network(
+ resource_url: str,
+ expected_code: str,
+) -> None:
+ adapter, factory, manager = client(
+ lambda _: httpx.Response(200),
+ )
+
+ with pytest.raises(AgentCorePaymentError) as exc_info:
+ adapter.fetch(
+ resource_url,
+ client_token="purchase-test-004",
+ )
+
+ assert exc_info.value.code == expected_code
+ assert factory.created == 0
+ assert manager.calls == []
+
+
+def test_private_dns_resolution_fails_before_network() -> None:
+ adapter, factory, manager = client(
+ lambda _: httpx.Response(200),
+ resolver=lambda _: ["127.0.0.1"],
+ )
+
+ with pytest.raises(AgentCorePaymentError) as exc_info:
+ adapter.fetch(
+ RESOURCE_URL,
+ client_token="purchase-test-005",
+ )
+
+ assert exc_info.value.code == "private_merchant_address_denied"
+ assert factory.created == 0
+ assert manager.calls == []
+
+
+def test_mixed_public_and_private_dns_answers_fail_before_network() -> None:
+ adapter, factory, manager = client(
+ lambda _: httpx.Response(200),
+ resolver=lambda _: [PUBLIC_ADDRESS, "127.0.0.1"],
+ )
+
+ with pytest.raises(AgentCorePaymentError) as exc_info:
+ adapter.fetch(RESOURCE_URL, client_token="purchase-mixed-dns-test")
+
+ assert exc_info.value.code == "private_merchant_address_denied"
+ assert factory.created == 0
+ assert manager.calls == []
+
+
+def test_signed_retry_revalidates_dns_and_rejects_changed_answer() -> None:
+ answers = iter([[PUBLIC_ADDRESS], ["127.0.0.1"]])
+ adapter, factory, manager = client(
+ lambda _: httpx.Response(
+ 402,
+ headers={"PAYMENT-REQUIRED": challenge_header()},
+ ),
+ resolver=lambda _: next(answers),
+ )
+
+ with pytest.raises(AgentCorePaymentError) as exc_info:
+ adapter.fetch(RESOURCE_URL, client_token="purchase-dns-change-test")
+
+ assert exc_info.value.code == "private_merchant_address_denied"
+ assert factory.created == 1
+ assert len(manager.calls) == 1
+
+
+def test_global_ipv6_address_is_pinned_with_original_host_header() -> None:
+ requests: list[httpx.Request] = []
+ ipv6_address = "2606:4700:4700::1111"
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ requests.append(request)
+ return httpx.Response(200, text="ok")
+
+ adapter, _, _ = client(
+ handler,
+ resolver=lambda _: [ipv6_address],
+ )
+ adapter.fetch(RESOURCE_URL, client_token="purchase-ipv6-test")
+
+ assert requests[0].url.host == ipv6_address
+ assert requests[0].headers["host"] == "merchant.example"
+
+
+def test_manager_failure_is_sanitized() -> None:
+ secret = "wallet-provider-secret"
+ adapter, _, _ = client(
+ lambda _: httpx.Response(
+ 402,
+ headers={"PAYMENT-REQUIRED": challenge_header()},
+ text="payment required",
+ ),
+ manager=FakeManager(error=RuntimeError(secret)),
+ )
+
+ with pytest.raises(AgentCorePaymentError) as exc_info:
+ adapter.fetch(
+ RESOURCE_URL,
+ client_token="purchase-test-006",
+ )
+
+ assert exc_info.value.code == "payment_header_generation_failed"
+ assert exc_info.value.diagnostics == {
+ "stage": "agentcore_process_payment",
+ "category": "provider_error",
+ "provider_message_logged": False,
+ "request_id_logged": False,
+ }
+ assert secret not in str(exc_info.value)
+ assert exc_info.value.__cause__ is None
+
+
+def test_manager_failure_preserves_only_safe_aws_diagnostics() -> None:
+ from botocore.exceptions import ClientError
+
+ secret = "wallet-provider-secret"
+ request_id = "request-sensitive-identifier"
+ client_error = ClientError(
+ {
+ "Error": {
+ "Code": "ValidationException",
+ "Message": secret,
+ },
+ "ResponseMetadata": {
+ "HTTPStatusCode": 400,
+ "RequestId": request_id,
+ },
+ },
+ "ProcessPayment",
+ )
+
+ class PaymentError(Exception):
+ pass
+
+ provider_error = PaymentError(secret)
+ provider_error.__cause__ = client_error
+ adapter, _, _ = client(
+ lambda _: httpx.Response(
+ 402,
+ headers={"PAYMENT-REQUIRED": challenge_header()},
+ text="payment required",
+ ),
+ manager=FakeManager(error=provider_error),
+ )
+
+ with pytest.raises(AgentCorePaymentError) as exc_info:
+ adapter.fetch(
+ RESOURCE_URL,
+ client_token="purchase-test-safe-diagnostics",
+ )
+
+ rendered = json.dumps(exc_info.value.diagnostics)
+ assert exc_info.value.diagnostics == {
+ "stage": "agentcore_process_payment",
+ "category": "aws_validation",
+ "provider_message_logged": False,
+ "request_id_logged": False,
+ "aws_error_code": "ValidationException",
+ "http_status_code": 400,
+ }
+ assert secret not in rendered
+ assert request_id not in rendered
+
+
+def test_insufficient_session_budget_has_safe_specific_code() -> None:
+ class InsufficientBudget(Exception):
+ pass
+
+ adapter, _, _ = client(
+ lambda _: httpx.Response(
+ 402,
+ headers={"PAYMENT-REQUIRED": challenge_header()},
+ text="payment required",
+ ),
+ manager=FakeManager(error=InsufficientBudget("provider details")),
+ )
+
+ with pytest.raises(AgentCorePaymentError) as exc_info:
+ adapter.fetch(
+ RESOURCE_URL,
+ client_token="purchase-test-budget",
+ )
+
+ assert exc_info.value.code == "payment_session_budget_exceeded"
+ assert exc_info.value.diagnostics["category"] == ("session_budget_exceeded")
+ assert exc_info.value.diagnostics["provider_error_type"] == ("InsufficientBudget")
+ assert "provider details" not in str(exc_info.value)
+ assert exc_info.value.__cause__ is None
+
+
+def test_invalid_generated_proof_is_rejected() -> None:
+ adapter, factory, _ = client(
+ lambda _: httpx.Response(
+ 402,
+ headers={"PAYMENT-REQUIRED": challenge_header()},
+ text="payment required",
+ ),
+ manager=FakeManager(
+ result={
+ "status": "PROOF_GENERATED",
+ "paymentOutput": {"cryptoX402": {"version": "2"}},
+ }
+ ),
+ )
+
+ with pytest.raises(AgentCorePaymentError) as exc_info:
+ adapter.fetch(
+ RESOURCE_URL,
+ client_token="purchase-test-007",
+ )
+
+ assert exc_info.value.code == "payment_header_invalid"
+ assert factory.created == 1
+
+
+def test_agentcore_region_is_separate_from_model_region() -> None:
+ environment = {
+ "AGENTCORE_AWS_REGION": "us-east-1",
+ "AWS_REGION": "us-east-2",
+ "PAYMENT_MANAGER_ARN": "manager",
+ "PAYMENT_INSTRUMENT_ID": "instrument",
+ "PAYMENT_SESSION_ID": "session",
+ "PAYMENT_USER_ID": "user",
+ "X402_ALLOWED_MERCHANTS": "merchant.example",
+ "X402_APPROVED_ASSET": BASE_SEPOLIA_USDC,
+ "X402_APPROVED_PAY_TO": APPROVED_PAY_TO,
+ "X402_MAX_APPROVED_AMOUNT_ATOMIC": "2000",
+ }
+
+ configured = AgentCorePaymentsSettings.from_env(environment)
+
+ assert configured.aws_region == "us-east-1"
+
+
[email protected]("value", ["2e3", "2000.0", "+2000"])
+def test_non_integer_max_amount_configuration_fails_closed(value: str) -> None:
+ environment = {
+ "AGENTCORE_AWS_REGION": "us-east-1",
+ "PAYMENT_MANAGER_ARN": "manager",
+ "PAYMENT_INSTRUMENT_ID": "instrument",
+ "PAYMENT_SESSION_ID": "session",
+ "PAYMENT_USER_ID": "user",
+ "X402_ALLOWED_MERCHANTS": "merchant.example",
+ "X402_APPROVED_ASSET": BASE_SEPOLIA_USDC,
+ "X402_APPROVED_PAY_TO": APPROVED_PAY_TO,
+ "X402_MAX_APPROVED_AMOUNT_ATOMIC": value,
+ }
+
+ with pytest.raises(AgentCorePaymentError) as exc_info:
+ AgentCorePaymentsSettings.from_env(environment)
+
+ assert exc_info.value.code == "agentcore_configuration_invalid"
+
+
+def test_runtime_profile_is_passed_to_payment_manager(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ captured: dict[str, object] = {}
+ boto3_module = ModuleType("boto3")
+ payments_module = ModuleType("bedrock_agentcore.payments")
+ agentcore_module = ModuleType("bedrock_agentcore")
+
+ def build_session(*, profile_name: str, region_name: str) -> object:
+ session = object()
+ captured["profile_name"] = profile_name
+ captured["region_name"] = region_name
+ captured["boto3_session"] = session
+ return session
+
+ def build_manager(**kwargs: object) -> object:
+ captured["manager_kwargs"] = kwargs
+ return object()
+
+ boto3_module.Session = build_session # type: ignore[attr-defined]
+ payments_module.PaymentManager = build_manager # type: ignore[attr-defined]
+ agentcore_module.payments = payments_module # type: ignore[attr-defined]
+ monkeypatch.setitem(sys.modules, "boto3", boto3_module)
+ monkeypatch.setitem(sys.modules, "bedrock_agentcore", agentcore_module)
+ monkeypatch.setitem(
+ sys.modules,
+ "bedrock_agentcore.payments",
+ payments_module,
+ )
+ configured = settings().model_copy(
+ update={"runtime_aws_profile": SecretStr("payment-runtime")}
+ )
+
+ AgentCoreX402Client(configured)._build_manager()
+
+ assert captured["profile_name"] == "payment-runtime"
+ assert captured["region_name"] == "us-east-1"
+ manager_kwargs = captured["manager_kwargs"]
+ assert isinstance(manager_kwargs, dict)
+ assert manager_kwargs["boto3_session"] is captured["boto3_session"]
+
+
+def test_unsupported_agentcore_region_fails_closed() -> None:
+ environment = {
+ "AGENTCORE_AWS_REGION": "us-east-2",
+ "PAYMENT_MANAGER_ARN": "manager",
+ "PAYMENT_INSTRUMENT_ID": "instrument",
+ "PAYMENT_SESSION_ID": "session",
+ "PAYMENT_USER_ID": "user",
+ "X402_ALLOWED_MERCHANTS": "merchant.example",
+ "X402_APPROVED_ASSET": BASE_SEPOLIA_USDC,
+ "X402_APPROVED_PAY_TO": APPROVED_PAY_TO,
+ "X402_MAX_APPROVED_AMOUNT_ATOMIC": "2000",
+ }
+
+ with pytest.raises(AgentCorePaymentError) as exc_info:
+ AgentCorePaymentsSettings.from_env(environment)
+
+ assert exc_info.value.code == "agentcore_region_unsupported"
+
+
+def test_mainnet_network_configuration_fails_closed() -> None:
+ environment = {
+ "AGENTCORE_AWS_REGION": "us-east-1",
+ "PAYMENT_MANAGER_ARN": "manager",
+ "PAYMENT_INSTRUMENT_ID": "instrument",
+ "PAYMENT_SESSION_ID": "session",
+ "PAYMENT_USER_ID": "user",
+ "X402_ALLOWED_MERCHANTS": "merchant.example",
+ "X402_APPROVED_ASSET": BASE_SEPOLIA_USDC,
+ "X402_APPROVED_PAY_TO": APPROVED_PAY_TO,
+ "X402_MAX_APPROVED_AMOUNT_ATOMIC": "2000",
+ "X402_NETWORK_PREFERENCES": "eip155:8453",
+ }
+
+ with pytest.raises(ValueError, match="Only the Base Sepolia"):
+ AgentCorePaymentsSettings.from_env(environment)
+
+
+ ("header", "expected_code"),
+ [
+ (None, "payment_challenge_missing"),
+ ("not-base64", "payment_challenge_invalid"),
+ (
+ challenge_header(network="eip155:8453"),
+ "payment_challenge_network_denied",
+ ),
+ (
+ challenge_header(amount="2001"),
+ "payment_challenge_amount_exceeds_approval",
+ ),
+ (
+ challenge_header(asset="0x0000000000000000000000000000000000000000"),
+ "payment_challenge_asset_denied",
+ ),
+ ],
+)
+def test_unapproved_challenge_fails_before_manager(
+ header: str | None,
+ expected_code: str,
+) -> None:
+ headers = {"PAYMENT-REQUIRED": header} if header is not None else {}
+ adapter, factory, manager = client(
+ lambda _: httpx.Response(402, headers=headers),
+ )
+
+ with pytest.raises(AgentCorePaymentError) as exc_info:
+ adapter.fetch(
+ RESOURCE_URL,
+ client_token="purchase-test-009",
+ )
+
+ assert exc_info.value.code == expected_code
+ assert factory.created == 1
+ assert manager.calls == []
diff --git a/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/tests/test_agentcore_session.py b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/tests/test_agentcore_session.py
new file mode 100644
index 00000000..e3d92a8c
--- /dev/null
+++ b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/tests/test_agentcore_session.py
@@ -0,0 +1,439 @@
+from __future__ import annotations
+
+import sys
+from concurrent.futures import ThreadPoolExecutor
+from decimal import Decimal
+from pathlib import Path
+from types import ModuleType
+from typing import Any
+
+import pytest
+
+from agentic_commerce import agentcore_session
+from agentic_commerce.agentcore_session import (
+ create_bounded_session,
+ delete_recorded_session,
+ runtime_environment_from_recorded_session,
+)
+from agentic_commerce.errors import AgentCorePaymentError
+
+
+class FakeSessionManager:
+ def __init__(
+ self,
+ *,
+ create_error: Exception | None = None,
+ delete_error: Exception | None = None,
+ delete_status: str = "DELETED",
+ ) -> None:
+ self.create_error = create_error
+ self.delete_error = delete_error
+ self.delete_status = delete_status
+ self.create_calls: list[dict[str, Any]] = []
+ self.delete_calls: list[dict[str, Any]] = []
+
+ def create_payment_session(self, **kwargs: Any) -> dict[str, Any]:
+ self.create_calls.append(kwargs)
+ if self.create_error:
+ raise self.create_error
+ return {"paymentSessionId": "session-sensitive-test"}
+
+ def delete_payment_session(
+ self,
+ payment_session_id: str,
+ user_id: str | None = None,
+ ) -> dict[str, Any]:
+ self.delete_calls.append(
+ {
+ "payment_session_id": payment_session_id,
+ "user_id": user_id,
+ }
+ )
+ if self.delete_error:
+ raise self.delete_error
+ return {"status": self.delete_status}
+
+
+def environment(*, enabled: bool = True) -> dict[str, str]:
+ return {
+ "ALLOW_AGENTCORE_SESSION_ADMIN": "1" if enabled else "0",
+ "AGENTCORE_AWS_REGION": "us-east-1",
+ "PAYMENT_MANAGER_ARN": "manager-sensitive-test",
+ "PAYMENT_USER_ID": "user-sensitive-test",
+ }
+
+
+def test_create_requires_explicit_session_admin_opt_in(tmp_path: Path) -> None:
+ manager = FakeSessionManager()
+
+ with pytest.raises(AgentCorePaymentError) as exc_info:
+ create_bounded_session(
+ manager,
+ environ=environment(enabled=False),
+ session_file=tmp_path / "session.env",
+ )
+
+ assert exc_info.value.code == "payment_session_admin_disabled"
+ assert manager.create_calls == []
+
+
+def test_live_session_admin_fails_cleanly_without_posix_locking(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ manager = FakeSessionManager()
+ monkeypatch.setattr(agentcore_session, "fcntl", None)
+
+ with pytest.raises(AgentCorePaymentError) as exc_info:
+ create_bounded_session(
+ manager,
+ environ=environment(),
+ session_file=tmp_path / "session.env",
+ )
+
+ assert exc_info.value.code == "payment_session_platform_unsupported"
+ assert manager.create_calls == []
+
+
+def test_cli_checks_opt_in_before_constructing_manager(
+ monkeypatch: pytest.MonkeyPatch,
+ capsys: pytest.CaptureFixture[str],
+) -> None:
+ monkeypatch.setenv("ALLOW_AGENTCORE_SESSION_ADMIN", "0")
+ monkeypatch.setattr(
+ agentcore_session,
+ "_manager",
+ lambda environ: pytest.fail("manager must not be constructed"),
+ )
+
+ with pytest.raises(SystemExit) as exc_info:
+ agentcore_session.main(["create"])
+
+ assert exc_info.value.code == 1
+ assert "payment_session_admin_disabled" in capsys.readouterr().out
+
+
+def test_session_admin_profile_is_passed_to_payment_manager(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ captured: dict[str, object] = {}
+ boto3_module = ModuleType("boto3")
+ payments_module = ModuleType("bedrock_agentcore.payments")
+ agentcore_module = ModuleType("bedrock_agentcore")
+
+ def build_session(*, profile_name: str, region_name: str) -> object:
+ session = object()
+ captured["profile_name"] = profile_name
+ captured["region_name"] = region_name
+ captured["boto3_session"] = session
+ return session
+
+ def build_manager(**kwargs: object) -> object:
+ captured["manager_kwargs"] = kwargs
+ return object()
+
+ boto3_module.Session = build_session # type: ignore[attr-defined]
+ payments_module.PaymentManager = build_manager # type: ignore[attr-defined]
+ agentcore_module.payments = payments_module # type: ignore[attr-defined]
+ monkeypatch.setitem(sys.modules, "boto3", boto3_module)
+ monkeypatch.setitem(sys.modules, "bedrock_agentcore", agentcore_module)
+ monkeypatch.setitem(
+ sys.modules,
+ "bedrock_agentcore.payments",
+ payments_module,
+ )
+ values = environment()
+ values["AGENTCORE_SESSION_AWS_PROFILE"] = "session-admin"
+
+ agentcore_session._manager(values)
+
+ assert captured["profile_name"] == "session-admin"
+ assert captured["region_name"] == "us-east-1"
+ manager_kwargs = captured["manager_kwargs"]
+ assert isinstance(manager_kwargs, dict)
+ assert manager_kwargs["boto3_session"] is captured["boto3_session"]
+
+
+def test_create_records_identifiers_without_returning_them(tmp_path: Path) -> None:
+ manager = FakeSessionManager()
+ session_file = tmp_path / "session.env"
+
+ report = create_bounded_session(
+ manager,
+ environ=environment(),
+ session_file=session_file,
+ budget_usd=Decimal("0.01"),
+ expiry_minutes=30,
+ token_factory=lambda: "stable-session-token",
+ )
+
+ rendered = str(report)
+ state = session_file.read_text(encoding="utf-8")
+ assert report["result"] == "CREATED"
+ assert report["value_transferred"] is False
+ assert "session-sensitive-test" not in rendered
+ assert "stable-session-token" not in rendered
+ assert "PAYMENT_SESSION_ID=session-sensitive-test" in state
+ assert "PAYMENT_SESSION_CLIENT_TOKEN=stable-session-token" in state
+ assert session_file.stat().st_mode & 0o777 == 0o600
+ assert manager.create_calls == [
+ {
+ "user_id": "user-sensitive-test",
+ "limits": {
+ "maxSpendAmount": {
+ "value": "0.01",
+ "currency": "USD",
+ }
+ },
+ "expiry_time_in_minutes": 30,
+ "client_token": "stable-session-token",
+ }
+ ]
+
+
+def test_failed_create_reuses_the_recorded_client_token(tmp_path: Path) -> None:
+ session_file = tmp_path / "session.env"
+ failing = FakeSessionManager(create_error=RuntimeError("provider detail"))
+
+ with pytest.raises(AgentCorePaymentError) as exc_info:
+ create_bounded_session(
+ failing,
+ environ=environment(),
+ session_file=session_file,
+ token_factory=lambda: "stable-session-token",
+ )
+
+ assert exc_info.value.code == "payment_session_create_failed"
+ assert "provider detail" not in str(exc_info.value)
+ succeeding = FakeSessionManager()
+ create_bounded_session(
+ succeeding,
+ environ=environment(),
+ session_file=session_file,
+ token_factory=lambda: "different-token",
+ )
+ assert succeeding.create_calls[0]["client_token"] == "stable-session-token"
+
+
+def test_existing_recorded_session_prevents_overwrite(tmp_path: Path) -> None:
+ session_file = tmp_path / "session.env"
+ session_file.write_text(
+ "PAYMENT_SESSION_CLIENT_TOKEN=stable-session-token\n"
+ "PAYMENT_SESSION_ID=existing-session\n",
+ encoding="utf-8",
+ )
+ manager = FakeSessionManager()
+
+ with pytest.raises(AgentCorePaymentError) as exc_info:
+ create_bounded_session(
+ manager,
+ environ=environment(),
+ session_file=session_file,
+ )
+
+ assert exc_info.value.code == "payment_session_already_recorded"
+ assert manager.create_calls == []
+
+
+def test_persistence_failure_deletes_newly_created_session(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ session_file = tmp_path / "session.env"
+ manager = FakeSessionManager()
+ original_write = agentcore_session._write_session_state
+ writes = 0
+
+ def fail_second_write(path: Path, state: dict[str, str]) -> None:
+ nonlocal writes
+ writes += 1
+ if writes == 2:
+ raise AgentCorePaymentError(
+ "payment_session_state_write_failed",
+ "Synthetic persistence failure.",
+ )
+ original_write(path, state)
+
+ monkeypatch.setattr(agentcore_session, "_write_session_state", fail_second_write)
+
+ with pytest.raises(AgentCorePaymentError) as exc_info:
+ create_bounded_session(
+ manager,
+ environ=environment(),
+ session_file=session_file,
+ token_factory=lambda: "stable-session-token",
+ )
+
+ assert exc_info.value.code == "payment_session_state_write_failed"
+ assert manager.delete_calls == [
+ {
+ "payment_session_id": "session-sensitive-test",
+ "user_id": "user-sensitive-test",
+ }
+ ]
+ assert not session_file.exists()
+
+
+def test_concurrent_creation_allows_only_one_session(tmp_path: Path) -> None:
+ session_file = tmp_path / "session.env"
+ manager = FakeSessionManager()
+
+ def create() -> str:
+ try:
+ create_bounded_session(
+ manager,
+ environ=environment(),
+ session_file=session_file,
+ token_factory=lambda: "stable-session-token",
+ )
+ except AgentCorePaymentError as exc:
+ return exc.code
+ return "CREATED"
+
+ with ThreadPoolExecutor(max_workers=2) as executor:
+ results = sorted(executor.map(lambda _: create(), range(2)))
+
+ assert results == ["CREATED", "payment_session_already_recorded"]
+ assert len(manager.create_calls) == 1
+
+
+def test_delete_removes_local_state_after_agentcore_success(
+ tmp_path: Path,
+) -> None:
+ session_file = tmp_path / "session.env"
+ session_file.write_text(
+ "PAYMENT_SESSION_CLIENT_TOKEN=stable-session-token\n"
+ "PAYMENT_SESSION_ID=session-sensitive-test\n",
+ encoding="utf-8",
+ )
+ manager = FakeSessionManager()
+
+ report = delete_recorded_session(
+ manager,
+ environ=environment(),
+ session_file=session_file,
+ )
+
+ assert report["result"] == "DELETED"
+ assert report["value_transferred"] is False
+ assert "session-sensitive-test" not in str(report)
+ assert manager.delete_calls == [
+ {
+ "payment_session_id": "session-sensitive-test",
+ "user_id": "user-sensitive-test",
+ }
+ ]
+ assert not session_file.exists()
+
+
+def test_runtime_environment_uses_recorded_id_without_mutating_input(
+ tmp_path: Path,
+) -> None:
+ session_file = tmp_path / "session.env"
+ session_file.write_text(
+ "PAYMENT_SESSION_CLIENT_TOKEN=stable-session-token\n"
+ "PAYMENT_SESSION_ID=session-sensitive-test\n",
+ encoding="utf-8",
+ )
+ original = environment()
+
+ runtime = runtime_environment_from_recorded_session(
+ original,
+ session_file=session_file,
+ )
+
+ assert "PAYMENT_SESSION_ID" not in original
+ assert runtime["PAYMENT_SESSION_ID"] == "session-sensitive-test"
+
+
+def test_delete_failure_retains_local_state(tmp_path: Path) -> None:
+ session_file = tmp_path / "session.env"
+ session_file.write_text(
+ "PAYMENT_SESSION_CLIENT_TOKEN=stable-session-token\n"
+ "PAYMENT_SESSION_ID=session-sensitive-test\n",
+ encoding="utf-8",
+ )
+ manager = FakeSessionManager(delete_error=RuntimeError("provider detail"))
+
+ with pytest.raises(AgentCorePaymentError) as exc_info:
+ delete_recorded_session(
+ manager,
+ environ=environment(),
+ session_file=session_file,
+ )
+
+ assert exc_info.value.code == "payment_session_delete_failed"
+ assert "provider detail" not in str(exc_info.value)
+ assert session_file.exists()
+
+
+def test_unconfirmed_delete_retains_local_state(tmp_path: Path) -> None:
+ session_file = tmp_path / "session.env"
+ session_file.write_text(
+ "PAYMENT_SESSION_CLIENT_TOKEN=stable-session-token\n"
+ "PAYMENT_SESSION_ID=session-sensitive-test\n",
+ encoding="utf-8",
+ )
+ manager = FakeSessionManager(delete_status="PENDING")
+
+ with pytest.raises(AgentCorePaymentError) as exc_info:
+ delete_recorded_session(
+ manager,
+ environ=environment(),
+ session_file=session_file,
+ )
+
+ assert exc_info.value.code == "payment_session_delete_unconfirmed"
+ assert session_file.exists()
+
+
+def test_delete_rejects_shell_unsafe_local_state(tmp_path: Path) -> None:
+ session_file = tmp_path / "session.env"
+ session_file.write_text(
+ "PAYMENT_SESSION_CLIENT_TOKEN=stable-session-token\n"
+ "PAYMENT_SESSION_ID=$(unsafe-command)\n",
+ encoding="utf-8",
+ )
+ manager = FakeSessionManager()
+
+ with pytest.raises(AgentCorePaymentError) as exc_info:
+ delete_recorded_session(
+ manager,
+ environ=environment(),
+ session_file=session_file,
+ )
+
+ assert exc_info.value.code == "payment_session_state_invalid"
+ assert manager.delete_calls == []
+
+
+ ("budget", "expiry", "expected_code"),
+ [
+ (Decimal(0), 30, "payment_session_budget_invalid"),
+ (Decimal("0.02"), 30, "payment_session_budget_invalid"),
+ (Decimal("NaN"), 30, "payment_session_budget_invalid"),
+ (Decimal("Infinity"), 30, "payment_session_budget_invalid"),
+ (Decimal("0.01"), 14, "payment_session_expiry_invalid"),
+ (Decimal("0.01"), 61, "payment_session_expiry_invalid"),
+ ],
+)
+def test_create_rejects_unbounded_settings(
+ tmp_path: Path,
+ budget: Decimal,
+ expiry: int,
+ expected_code: str,
+) -> None:
+ manager = FakeSessionManager()
+
+ with pytest.raises(AgentCorePaymentError) as exc_info:
+ create_bounded_session(
+ manager,
+ environ=environment(),
+ session_file=tmp_path / "session.env",
+ budget_usd=budget,
+ expiry_minutes=expiry,
+ )
+
+ assert exc_info.value.code == expected_code
+ assert manager.create_calls == []
diff --git a/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/tests/test_local_flow.py b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/tests/test_local_flow.py
new file mode 100644
index 00000000..55fd4564
--- /dev/null
+++ b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/tests/test_local_flow.py
@@ -0,0 +1,412 @@
+from __future__ import annotations
+
+import base64
+import json
+from datetime import UTC, datetime, timedelta
+from decimal import Decimal
+from typing import Any
+
+import httpx
+import pytest
+
+from agentic_commerce.application import CommerceApplication
+from agentic_commerce.codec import encode_model
+from agentic_commerce.errors import (
+ IdempotencyConflict,
+ PolicyDenied,
+ ProtocolError,
+)
+from agentic_commerce.merchant import (
+ PAYMENT_REQUIRED_HEADER,
+ PAYMENT_SIGNATURE_HEADER,
+ RESOURCE_URL,
+ SyntheticMerchant,
+)
+from agentic_commerce.models import (
+ ApprovalGrant,
+ AuditEventType,
+ CommercePolicy,
+ PurchaseRequest,
+)
+from agentic_commerce.payments import LocalPaymentProcessor
+from agentic_commerce.policy import PolicyEngine
+from agentic_commerce.tool import build_x402_fetch_tool
+
+NOW = datetime(2026, 7, 30, 16, 0, tzinfo=UTC)
+
+
+def make_system(
+ *,
+ price: Decimal = Decimal("0.25"),
+ request_limit: Decimal = Decimal("0.50"),
+ run_limit: Decimal = Decimal("1.00"),
+ threshold: Decimal = Decimal("0.10"),
+ session_expires_at: datetime | None = None,
+ malformed_challenge: bool = False,
+) -> tuple[CommerceApplication, SyntheticMerchant, LocalPaymentProcessor]:
+ payments = LocalPaymentProcessor()
+ merchant = SyntheticMerchant(
+ payments,
+ price=price,
+ now=NOW,
+ malformed_challenge=malformed_challenge,
+ )
+ policy = PolicyEngine(
+ CommercePolicy(
+ allowed_merchants=frozenset({"merchant.invalid"}),
+ allowed_purposes=frozenset({"supplier_due_diligence"}),
+ per_request_limit=request_limit,
+ per_run_limit=run_limit,
+ approval_threshold=threshold,
+ session_expires_at=(session_expires_at or NOW + timedelta(minutes=15)),
+ )
+ )
+ app = CommerceApplication(
+ client=merchant.client(),
+ policy=policy,
+ payments=payments,
+ )
+ return app, merchant, payments
+
+
+def request(
+ *,
+ request_id: str = "request-001",
+ resource_url: str = RESOURCE_URL,
+ purpose: str = "supplier_due_diligence",
+ idempotency_key: str = "purchase-001",
+) -> PurchaseRequest:
+ return PurchaseRequest(
+ request_id=request_id,
+ resource_url=resource_url,
+ purpose=purpose,
+ idempotency_key=idempotency_key,
+ )
+
+
+def approval(
+ purchase: PurchaseRequest,
+ *,
+ maximum_amount: Decimal = Decimal("0.25"),
+ expires_at: datetime | None = None,
+) -> ApprovalGrant:
+ return ApprovalGrant(
+ approval_id=f"approval-{purchase.request_id}",
+ request_id=purchase.request_id,
+ resource_url=purchase.resource_url,
+ purpose=purchase.purpose,
+ maximum_amount=maximum_amount,
+ approved_by="synthetic-reviewer",
+ approved_at=NOW,
+ expires_at=expires_at or NOW + timedelta(minutes=10),
+ )
+
+
+def payment_required_client(payload: dict[str, Any]) -> httpx.Client:
+ encoded = base64.b64encode(
+ json.dumps(payload, separators=(",", ":")).encode("utf-8")
+ ).decode("ascii")
+
+ def handle(_: httpx.Request) -> httpx.Response:
+ return httpx.Response(
+ 402,
+ headers={PAYMENT_REQUIRED_HEADER: encoded},
+ json={"error": "payment_required"},
+ )
+
+ return httpx.Client(transport=httpx.MockTransport(handle))
+
+
+def test_approved_purchase_completes_full_402_sequence() -> None:
+ app, merchant, payments = make_system()
+ purchase = request()
+
+ result = app.purchase(purchase, approval=approval(purchase), now=NOW)
+
+ assert result.status == "completed"
+ assert result.receipt.amount == Decimal("0.25")
+ assert result.authorization.requires_human_approval is True
+ assert result.report.report_id == "SYNTH-SUPPLIER-RISK-001"
+ assert merchant.request_count == 2
+ assert merchant.fulfilled_count == 1
+ assert payments.charge_count == 1
+ assert [event.event_type for event in result.audit_events] == [
+ AuditEventType.RESOURCE_REQUESTED,
+ AuditEventType.PAYMENT_REQUIRED,
+ AuditEventType.AUTHORIZATION_CHECKED,
+ AuditEventType.PAYMENT_ATTEMPTED,
+ AuditEventType.PROOF_CREATED,
+ AuditEventType.MERCHANT_RETRY,
+ AuditEventType.CONTENT_RETURNED,
+ ]
+
+
+def test_below_threshold_purchase_does_not_need_human_approval() -> None:
+ app, _, payments = make_system(price=Decimal("0.05"))
+
+ result = app.purchase(request(), now=NOW)
+
+ assert result.authorization.requires_human_approval is False
+ assert payments.charge_count == 1
+
+
+def test_missing_human_approval_is_denied_before_payment() -> None:
+ app, merchant, payments = make_system()
+
+ with pytest.raises(PolicyDenied) as exc_info:
+ app.purchase(request(), now=NOW)
+
+ assert exc_info.value.code == "human_approval_required"
+ assert merchant.request_count == 1
+ assert payments.charge_count == 0
+
+
+def test_unapproved_destination_is_denied_before_http() -> None:
+ app, merchant, payments = make_system()
+
+ with pytest.raises(PolicyDenied) as exc_info:
+ app.purchase(
+ request(
+ resource_url=(
+ "https://unapproved.invalid/reports/SYNTH-SUPPLIER-RISK-001"
+ )
+ ),
+ now=NOW,
+ )
+
+ assert exc_info.value.code == "merchant_not_allowed"
+ assert merchant.request_count == 0
+ assert payments.charge_count == 0
+
+
+def test_challenge_merchant_mismatch_is_denied_before_payment() -> None:
+ app, merchant, payments = make_system()
+ merchant.payment_required = merchant.payment_required.model_copy(
+ update={
+ "accepts": (
+ merchant.requirement.model_copy(
+ update={
+ "extra": merchant.requirement.extra.model_copy(
+ update={"merchant_domain": "unapproved.invalid"}
+ )
+ }
+ ),
+ )
+ }
+ )
+
+ with pytest.raises(PolicyDenied) as exc_info:
+ app.purchase(request(), now=NOW)
+
+ assert exc_info.value.code == "merchant_mismatch"
+ assert merchant.request_count == 1
+ assert payments.charge_count == 0
+
+
+def test_http_resource_is_rejected_before_http() -> None:
+ app, merchant, payments = make_system()
+
+ with pytest.raises(PolicyDenied) as exc_info:
+ app.purchase(
+ request(resource_url=RESOURCE_URL.replace("https://", "http://")),
+ now=NOW,
+ )
+
+ assert exc_info.value.code == "https_required"
+ assert merchant.request_count == 0
+ assert payments.charge_count == 0
+
+
+def test_per_request_limit_denies_before_payment() -> None:
+ app, merchant, payments = make_system(request_limit=Decimal("0.20"))
+
+ with pytest.raises(PolicyDenied) as exc_info:
+ app.purchase(request(), now=NOW)
+
+ assert exc_info.value.code == "request_limit_exceeded"
+ assert merchant.request_count == 1
+ assert payments.charge_count == 0
+
+
+def test_run_budget_is_enforced_across_distinct_purchases() -> None:
+ app, _, payments = make_system(
+ price=Decimal("0.05"),
+ run_limit=Decimal("0.05"),
+ )
+ app.purchase(request(idempotency_key="purchase-001"), now=NOW)
+
+ with pytest.raises(PolicyDenied) as exc_info:
+ app.purchase(
+ request(
+ request_id="request-002",
+ idempotency_key="purchase-002",
+ ),
+ now=NOW,
+ )
+
+ assert exc_info.value.code == "run_limit_exceeded"
+ assert payments.charge_count == 1
+
+
+def test_expired_session_denies_before_http() -> None:
+ app, merchant, payments = make_system(session_expires_at=NOW - timedelta(seconds=1))
+
+ with pytest.raises(PolicyDenied) as exc_info:
+ app.purchase(request(), now=NOW)
+
+ assert exc_info.value.code == "session_expired"
+ assert merchant.request_count == 0
+ assert payments.charge_count == 0
+
+
+def test_expired_challenge_denies_before_payment() -> None:
+ app, merchant, payments = make_system()
+ expired = merchant.requirement.model_copy(
+ update={
+ "extra": merchant.requirement.extra.model_copy(
+ update={"expires_at": NOW - timedelta(seconds=1)}
+ )
+ }
+ )
+ merchant.payment_required = merchant.payment_required.model_copy(
+ update={"accepts": (expired,)}
+ )
+
+ with pytest.raises(PolicyDenied) as exc_info:
+ app.purchase(request(), now=NOW)
+
+ assert exc_info.value.code == "challenge_expired"
+ assert payments.charge_count == 0
+
+
+def test_expired_approval_denies_before_payment() -> None:
+ app, _, payments = make_system()
+ purchase = request()
+
+ with pytest.raises(PolicyDenied) as exc_info:
+ app.purchase(
+ purchase,
+ approval=approval(
+ purchase,
+ expires_at=NOW - timedelta(seconds=1),
+ ),
+ now=NOW,
+ )
+
+ assert exc_info.value.code == "approval_expired"
+ assert payments.charge_count == 0
+
+
+def test_malformed_payment_required_header_fails_safely() -> None:
+ app, _, payments = make_system(malformed_challenge=True)
+
+ with pytest.raises(ProtocolError) as exc_info:
+ app.purchase(request(), now=NOW)
+
+ assert exc_info.value.code == "malformed_protocol_header"
+ assert payments.charge_count == 0
+
+
+ "field_name",
+ ["decimals", "currency", "merchantDomain", "challengeId", "expiresAt"],
+)
+def test_missing_payment_requirement_metadata_fails_safely(
+ field_name: str,
+) -> None:
+ app, merchant, payments = make_system()
+ payload = merchant.payment_required.model_dump(mode="json", by_alias=True)
+ del payload["accepts"][0]["extra"][field_name]
+ app.client = payment_required_client(payload)
+
+ with pytest.raises(ProtocolError) as exc_info:
+ app.purchase(request(), now=NOW)
+
+ assert exc_info.value.code == "invalid_payment_requirement"
+ assert payments.charge_count == 0
+
+
+ ("field_name", "value"),
+ [
+ ("decimals", "6"),
+ ("currency", 6),
+ ("merchantDomain", 6),
+ ("challengeId", 6),
+ ("expiresAt", 6),
+ ],
+)
+def test_typed_payment_requirement_metadata_fails_safely(
+ field_name: str,
+ value: object,
+) -> None:
+ app, merchant, payments = make_system()
+ payload = merchant.payment_required.model_dump(mode="json", by_alias=True)
+ payload["accepts"][0]["extra"][field_name] = value
+ app.client = payment_required_client(payload)
+
+ with pytest.raises(ProtocolError) as exc_info:
+ app.purchase(request(), now=NOW)
+
+ assert exc_info.value.code == "invalid_payment_requirement"
+ assert payments.charge_count == 0
+
+
+def test_same_idempotency_key_reuses_receipt_without_second_charge() -> None:
+ app, merchant, payments = make_system()
+ purchase = request()
+ grant = approval(purchase)
+
+ first = app.purchase(purchase, approval=grant, now=NOW)
+ second = app.purchase(purchase, approval=grant, now=NOW)
+
+ assert first.receipt.receipt_id == second.receipt.receipt_id
+ assert first.receipt.reused is False
+ assert second.receipt.reused is True
+ assert payments.charge_count == 1
+ assert merchant.fulfilled_count == 2
+
+
+def test_idempotency_key_cannot_be_reused_for_changed_purchase() -> None:
+ app, _, payments = make_system(price=Decimal("0.05"))
+ app.purchase(request(purpose="supplier_due_diligence"), now=NOW)
+
+ changed = request(purpose="another_allowed_purpose")
+ app.policy.policy = app.policy.policy.model_copy(
+ update={
+ "allowed_purposes": frozenset(
+ {"supplier_due_diligence", "another_allowed_purpose"}
+ )
+ }
+ )
+ with pytest.raises(IdempotencyConflict) as exc_info:
+ app.purchase(changed, now=NOW)
+
+ assert exc_info.value.code == "idempotency_conflict"
+ assert payments.charge_count == 1
+
+
+def test_merchant_rejects_unrecognized_proof() -> None:
+ _, merchant, payments = make_system()
+ response = merchant.client().get(
+ RESOURCE_URL,
+ headers={PAYMENT_SIGNATURE_HEADER: encode_model(merchant.payment_required)},
+ )
+
+ assert response.status_code == 402
+ assert PAYMENT_REQUIRED_HEADER in response.headers
+ assert merchant.invalid_proof_count == 1
+ assert payments.charge_count == 0
+
+
+def test_agents_tool_has_prebound_authority_and_expected_name() -> None:
+ app, _, _ = make_system()
+ purchase = request()
+ tool = build_x402_fetch_tool(
+ app,
+ request_id=purchase.request_id,
+ idempotency_key=purchase.idempotency_key,
+ approval=approval(purchase),
+ )
+
+ assert tool.name == "x402_fetch"
diff --git a/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/tests/test_publication_contract.py b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/tests/test_publication_contract.py
new file mode 100644
index 00000000..2c7d1a34
--- /dev/null
+++ b/examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/tests/test_publication_contract.py
@@ -0,0 +1,139 @@
+from __future__ import annotations
+
+import json
+import re
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[1]
+UPSTREAM_REVISION = "85aa4e5ca9a2d55ad7c412f2d015011095b2222d"
+DIAGRAMS = (
+ "controlled-agentic-commerce-overview.png",
+ "controlled-agentic-commerce-local-and-testnet.png",
+ "controlled-agentic-commerce-x402-sequence.png",
+)
+
+
+def _notebook_path() -> Path:
+ candidates = (
+ ROOT / "controlled_agentic_commerce.ipynb",
+ ROOT / "cookbook/controlled_agentic_commerce.ipynb",
+ )
+ return next(path for path in candidates if path.is_file())
+
+
+def _attribution_path() -> Path:
+ candidates = (
+ ROOT / "SOURCE_ATTRIBUTION.md",
+ ROOT / "docs/UPSTREAM_SOURCES.md",
+ )
+ return next(path for path in candidates if path.is_file())
+
+
+def test_documented_uv_commands_do_not_require_a_lockfile() -> None:
+ readme = (ROOT / "README.md").read_text(encoding="utf-8")
+ notebook = _notebook_path().read_text(encoding="utf-8")
+
+ assert "uv run" in readme
+ assert "--frozen" not in readme
+ assert "--frozen" not in notebook
+
+
+def test_notebook_is_committed_without_outputs() -> None:
+ notebook = json.loads(_notebook_path().read_text(encoding="utf-8"))
+ code_cells = [cell for cell in notebook["cells"] if cell["cell_type"] == "code"]
+
+ assert code_cells
+ assert all(cell.get("execution_count") is None for cell in code_cells)
+ assert all(cell.get("outputs", []) == [] for cell in code_cells)
+
+
+def test_notebook_has_publishable_boundaries_and_diagrams() -> None:
+ notebook = json.loads(_notebook_path().read_text(encoding="utf-8"))
+ source = "\n".join("".join(cell.get("source", [])) for cell in notebook["cells"])
+
+ assert "Agentic commerce" in source
+ assert "AgentCore Payments" in source
+ assert "optional connection to AgentCore Payments" not in source
+ assert "### Using the Responses API directly" in source
+ assert "responses_client.responses.create" in source
+ assert '"function_call_output"' in source
+ assert "**Authors:** Deepak Jain and Sid Rampally" in source
+ assert "AgentCore Runtime is not used by this notebook" in source
+ assert "RUN_AGENTCORE_E2E" in source
+ assert "run_managed_e2e" in source
+ assert "settlement_verified=false" in source
+ assert "Sanitized validation snapshot" not in source
+ for diagram in DIAGRAMS:
+ relative_path = Path("../../../../images/partners/AWS") / diagram
+ assert str(relative_path) in source
+ image = (ROOT / relative_path).resolve()
+ assert image.is_file()
+ assert image.stat().st_size > 10_000
+ assert image.read_bytes().startswith(b"\x89PNG\r\n\x1a\n")
+
+
+def test_live_opt_ins_are_disabled_by_default() -> None:
+ settings = {}
+ for line in (ROOT / ".env.example").read_text(encoding="utf-8").splitlines():
+ if line and not line.startswith("#") and "=" in line:
+ name, value = line.split("=", maxsplit=1)
+ settings[name] = value
+
+ assert settings["ALLOW_AGENTCORE_TESTNET"] == "0"
+ assert settings["ALLOW_AGENTCORE_READ_ONLY"] == "0"
+ assert settings["RUN_AGENTCORE_E2E"] == "0"
+ assert settings["ALLOW_PAID_INFERENCE"] == "0"
+ assert settings["APPROVE_AGENTCORE_TESTNET_PURCHASE"] == "0"
+ assert settings["ALLOW_AGENTCORE_SESSION_ADMIN"] == "0"
+ assert settings["PAYMENT_MANAGER_ARN"] == ""
+ assert settings["PAYMENT_INSTRUMENT_ID"] == ""
+ assert settings["PAYMENT_SESSION_ID"] == ""
+ assert settings["PAYMENT_USER_ID"] == ""
+ assert settings["X402_APPROVED_PAY_TO"] == ""
+ assert settings["BEDROCK_AWS_PROFILE"] == ""
+ assert settings["AGENTCORE_SESSION_AWS_PROFILE"] == ""
+ assert settings["AGENTCORE_RUNTIME_AWS_PROFILE"] == ""
+
+
+def test_upstream_source_is_pinned_and_licensed() -> None:
+ attribution = _attribution_path().read_text(encoding="utf-8")
+
+ assert UPSTREAM_REVISION in attribution
+ assert "Apache" in attribution
+ assert "No source code from the AWS sample is copied" in attribution
+
+
+def test_publishable_text_has_no_high_confidence_credentials() -> None:
+ allowed_suffixes = {
+ ".example",
+ ".ipynb",
+ ".json",
+ ".md",
+ ".py",
+ ".toml",
+ ".yaml",
+ ".yml",
+ }
+ excluded_parts = {".git", ".venv", "__pycache__"}
+ patterns = (
+ re.compile("-" * 5 + r"BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY" + "-" * 5),
+ re.compile(r"\bA" + r"KIA[0-9A-Z]{16}\b"),
+ re.compile(r"\bA" + r"SIA[0-9A-Z]{16}\b"),
+ re.compile(
+ r"aws_secret_" + r"access_key\s*=\s*[A-Za-z0-9/+=]{32,}",
+ re.IGNORECASE,
+ ),
+ )
+ findings = []
+ for path in ROOT.rglob("*"):
+ if (
+ not path.is_file()
+ or path.suffix not in allowed_suffixes
+ or excluded_parts.intersection(path.parts)
+ ):
+ continue
+ text = path.read_text(encoding="utf-8")
+ if any(pattern.search(text) for pattern in patterns):
+ findings.append(str(path.relative_to(ROOT)))
+
+ assert findings == []
diff --git a/images/partners/AWS/controlled-agentic-commerce-local-and-testnet.png b/images/partners/AWS/controlled-agentic-commerce-local-and-testnet.png
new file mode 100644
index 00000000..b984b0ff
Binary files /dev/null and b/images/partners/AWS/controlled-agentic-commerce-local-and-testnet.png differ
diff --git a/images/partners/AWS/controlled-agentic-commerce-overview.png b/images/partners/AWS/controlled-agentic-commerce-overview.png
new file mode 100644
index 00000000..f2ba3943
Binary files /dev/null and b/images/partners/AWS/controlled-agentic-commerce-overview.png differ
diff --git a/images/partners/AWS/controlled-agentic-commerce-x402-sequence.png b/images/partners/AWS/controlled-agentic-commerce-x402-sequence.png
new file mode 100644
index 00000000..0a5158dc
Binary files /dev/null and b/images/partners/AWS/controlled-agentic-commerce-x402-sequence.png differ
diff --git a/registry.yaml b/registry.yaml
index 6a929451..fa39f71b 100644
--- a/registry.yaml
+++ b/registry.yaml
@@ -34,6 +34,21 @@
- bedrock
- security
+- title: Controlled Agentic Commerce with AgentCore Payments
+ path: examples/partners/AWS/controlled_agentic_commerce_with_agentcore_payments/controlled_agentic_commerce.ipynb
+ slug: controlled-agentic-commerce-agentcore-payments
+ description: Build a controlled agentic-commerce workflow with the OpenAI Agents SDK, x402, application-owned payment authority, deterministic validation, and an optional gated Amazon Bedrock AgentCore Payments testnet path.
+ date: 2026-08-13
+ authors:
+ - deepakjain108
+ - sidrampally-oai
+ tags:
+ - partners
+ - agents-sdk
+ - agents
+ - bedrock
+ - security
+ - payments
- title: Enabling Long-Term Agent Memory with Oracle AI Agent Memory
path: examples/vector_databases/oracle_db/deep_research_openai_agents.ipynb
slug: deep-research-openai-agents