From 37837e3fb57f89d939235a101533ed2b1bd7df36 Mon Sep 17 00:00:00 2001 From: Yash Date: Sun, 15 Nov 2026 04:53:28 +0000 Subject: [PATCH 1/4] feat(purchases): support explicit browser purchase revisions --- .changeset/browser-purchase-revisions.md | 9 + packages/axios/src/failureMode.test.ts | 40 +++- packages/axios/src/interceptors.ts | 21 ++ packages/core/README.md | 115 +++++++---- packages/core/src/client/TransactionAPI.ts | 25 +++ .../src/client/TransactionAPI.update.test.ts | 79 ++++++++ .../core/src/client/TransactionPoller.test.ts | 45 +++++ packages/core/src/client/TransactionPoller.ts | 8 + packages/core/src/index.ts | 7 + packages/core/src/types/transaction.ts | 66 ++++++ .../src/utils/TransactionAuthorizer.test.ts | 30 +++ .../core/src/utils/TransactionAuthorizer.ts | 12 ++ .../utils/TransactionRevisionRequiredError.ts | 14 ++ packages/fetch/src/failureMode.test.ts | 40 +++- packages/fetch/src/interceptors.ts | 29 ++- packages/mcp/src/instructions.generated.ts | 189 +++++++++++++++--- packages/mcp/src/instructions.test.ts | 12 ++ packages/node-http/src/failureMode.test.ts | 44 +++- packages/node-http/src/interceptors.ts | 19 ++ 19 files changed, 737 insertions(+), 67 deletions(-) create mode 100644 .changeset/browser-purchase-revisions.md create mode 100644 packages/core/src/client/TransactionAPI.update.test.ts create mode 100644 packages/core/src/client/TransactionPoller.test.ts create mode 100644 packages/core/src/utils/TransactionRevisionRequiredError.ts diff --git a/.changeset/browser-purchase-revisions.md b/.changeset/browser-purchase-revisions.md new file mode 100644 index 000000000..132953dc4 --- /dev/null +++ b/.changeset/browser-purchase-revisions.md @@ -0,0 +1,9 @@ +--- +"@sapiom/core": minor +"@sapiom/fetch": patch +"@sapiom/axios": patch +"@sapiom/node-http": patch +"@sapiom/mcp": patch +--- + +Add versioned browser purchase updates with stable idempotency keys. Polling returns `needs_revision` with actionable reasons, and HTTP adapters block that policy decision even in failureMode open. Updates require the backend browser revision release and do not edit the merchant's cart. diff --git a/packages/axios/src/failureMode.test.ts b/packages/axios/src/failureMode.test.ts index 1ad53cd42..9609a7be7 100644 --- a/packages/axios/src/failureMode.test.ts +++ b/packages/axios/src/failureMode.test.ts @@ -5,7 +5,11 @@ import axios, { AxiosInstance } from "axios"; import MockAdapter from "axios-mock-adapter"; import { withSapiom } from "./axios"; -import { SapiomClient, TransactionAPI } from "@sapiom/core"; +import { + SapiomClient, + TransactionAPI, + TransactionRevisionRequiredError, +} from "@sapiom/core"; describe("Axios failureMode", () => { let axiosInstance: AxiosInstance; @@ -37,6 +41,40 @@ describe("Axios failureMode", () => { mockAxios.restore(); }); + it.each(["open", "closed"] as const)( + "blocks revision decisions in failureMode %s", + async (failureMode) => { + for (const mode of ["create", "existing", "poll"] as const) { + const transaction = { + id: "tx-revise", + status: "needs_revision", + nextAction: { type: "revise", actor: "agent", reasons: [] }, + }; + mockTransactionAPI.create.mockResolvedValue( + mode === "poll" + ? ({ id: "tx-revise", status: "pending" } as any) + : (transaction as any), + ); + mockTransactionAPI.get.mockResolvedValue(transaction as any); + mockAxios.onGet("/test").reply(200); + const client = withSapiom(axiosInstance, { + sapiomClient: mockSapiomClient, + failureMode, + polling: { pollInterval: 1 }, + }); + await expect( + client.get("/test", { + headers: + mode === "existing" + ? { "X-Sapiom-Transaction-Id": "tx-revise" } + : {}, + }), + ).rejects.toBeInstanceOf(TransactionRevisionRequiredError); + expect(mockAxios.history.get).toHaveLength(0); + } + }, + ); + describe('failureMode: "open" (default)', () => { it("should allow request when Sapiom API returns 500", async () => { mockAxios.onGet("/test").reply(200, { data: "success" }); diff --git a/packages/axios/src/interceptors.ts b/packages/axios/src/interceptors.ts index ee95ac892..40eaafce6 100644 --- a/packages/axios/src/interceptors.ts +++ b/packages/axios/src/interceptors.ts @@ -9,6 +9,7 @@ import { SapiomClient, TransactionPoller, TransactionStatus, + TransactionRevisionRequiredError, captureUserCallSite, extractX402Response, extractResourceFromError, @@ -304,10 +305,13 @@ export function addAuthorizationInterceptor( } switch (transaction.status) { + case TransactionStatus.NEEDS_REVISION: + throw new TransactionRevisionRequiredError(transaction); case TransactionStatus.AUTHORIZED: return axiosConfig; case TransactionStatus.PENDING: + case TransactionStatus.WAITING_APPROVAL: case TransactionStatus.PREPARING: { let authResult; try { @@ -323,6 +327,11 @@ export function addAuthorizationInterceptor( return axiosConfig; } + if (authResult.status === "needs_revision") + throw new TransactionRevisionRequiredError( + authResult.transaction, + ); + if (authResult.status === "authorized") { return axiosConfig; } else if (authResult.status === "denied") { @@ -479,6 +488,9 @@ export function addAuthorizationInterceptor( throw new AuthorizationDeniedError(transaction.id, endpoint); } + if (transaction.status === TransactionStatus.NEEDS_REVISION) + throw new TransactionRevisionRequiredError(transaction); + if (transaction.status === TransactionStatus.AUTHORIZED) { setHeader( axiosConfig.headers, @@ -504,6 +516,9 @@ export function addAuthorizationInterceptor( return axiosConfig; } + if (result.status === "needs_revision") + throw new TransactionRevisionRequiredError(result.transaction); + if (result.status === "authorized") { setHeader( axiosConfig.headers, @@ -693,6 +708,9 @@ export function addPaymentInterceptor( return Promise.reject(error); // Return original 402 error for completion } + if (transaction.status === TransactionStatus.NEEDS_REVISION) + throw new TransactionRevisionRequiredError(transaction); + if (transaction.status !== TransactionStatus.AUTHORIZED) { let result; try { @@ -708,6 +726,9 @@ export function addPaymentInterceptor( return Promise.reject(error); } + if (result.status === "needs_revision") + throw new TransactionRevisionRequiredError(result.transaction); + if (result.status !== "authorized") { // Clear payment handling flag so completion interceptor fires (originalConfig as any).__sapiomPaymentHandling = false; diff --git a/packages/core/README.md b/packages/core/README.md index 9c1a22048..cb651b10a 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -32,22 +32,22 @@ yarn add @sapiom/core ### Direct API Client ```typescript -import { SapiomClient } from '@sapiom/core'; +import { SapiomClient } from "@sapiom/core"; const client = new SapiomClient({ apiKey: process.env.SAPIOM_API_KEY, - baseURL: 'https://api.sapiom.ai' // optional + baseURL: "https://api.sapiom.ai", // optional }); // Create a transaction const transaction = await client.transactions.create({ - service: 'api', - action: 'call', - resource: 'completion', + service: "api", + action: "call", + resource: "completion", qualifiers: { - model: 'gpt-4', - tokens: 1000 - } + model: "gpt-4", + tokens: 1000, + }, }); // Check transaction status @@ -63,17 +63,20 @@ npm install @sapiom/axios axios ``` ```typescript -import axios from 'axios'; -import { withSapiom } from '@sapiom/axios'; - -const client = withSapiom(axios.create({ - baseURL: 'https://api.example.com' -}), { - apiKey: process.env.SAPIOM_API_KEY -}); +import axios from "axios"; +import { withSapiom } from "@sapiom/axios"; + +const client = withSapiom( + axios.create({ + baseURL: "https://api.example.com", + }), + { + apiKey: process.env.SAPIOM_API_KEY, + }, +); // Automatically handles 402 payment flows -const response = await client.get('/premium-endpoint'); +const response = await client.get("/premium-endpoint"); ``` See [@sapiom/axios](../axios/README.md) for complete documentation. @@ -87,14 +90,14 @@ npm install @sapiom/fetch ``` ```typescript -import { createFetch } from '@sapiom/fetch'; +import { createFetch } from "@sapiom/fetch"; const safeFetch = createFetch({ - apiKey: process.env.SAPIOM_API_KEY + apiKey: process.env.SAPIOM_API_KEY, }); // Drop-in replacement for native fetch -const response = await safeFetch('https://api.example.com/data'); +const response = await safeFetch("https://api.example.com/data"); ``` See [@sapiom/fetch](../fetch/README.md) for complete documentation. @@ -108,15 +111,15 @@ npm install @sapiom/node-http ``` ```typescript -import { createClient } from '@sapiom/node-http'; +import { createClient } from "@sapiom/node-http"; const client = createClient({ - apiKey: process.env.SAPIOM_API_KEY + apiKey: process.env.SAPIOM_API_KEY, }); const response = await client.request({ - method: 'GET', - url: 'https://api.example.com/data' + method: "GET", + url: "https://api.example.com/data", }); ``` @@ -133,6 +136,7 @@ new SapiomClient(config: SapiomClientConfig) ``` **Config options:** + - `apiKey: string` - Required: Your Sapiom API key - `baseURL?: string` - Optional: API base URL (default: https://api.sapiom.ai) - `servicesDomain?: string` - Optional: Services domain for gateway clients (default: services.sapiom.ai) @@ -173,6 +177,43 @@ wait, pass the previous purchase `version` as `since` to wait for a change. The request timeout includes five seconds beyond the server wait and preserves a larger configured client timeout. The deadline covers reading the response body. +##### transactions.update() + +A browser purchase can be revised on the same transaction ID while it needs a +revision, is waiting for approval, or is authorized but unused. Change the actual +cart first. Sapiom records your replacement statement and evaluates fresh payment +authority; it does not operate or verify the browser. + +```typescript +const current = await client.transactions.get(transactionId); +const body = { + version: current.version!, + purchase: { + type: "browser_checkout" as const, + merchant: { origin: "https://store.example" }, // preserve the entire merchant + total: { amount: "0.40", currency: "USD" }, + claimedLineItems: [{ title: "Single pen", quantity: 1 }], + }, +}; +const options = { idempotencyKey: crypto.randomUUID() }; +const updated = await client.transactions.update(transactionId, body, options); +// Follow updated.nextAction: acceptance does not mean payment is authorized. +``` + +Send a full replacement `purchase`, preserving the merchant, currency and funding. +The read view's `purchase.lineItems` maps to `purchase.claimedLineItems` on update. +Use a new key for new terms. If a browser update response is lost, read the purchase +or retry the **identical body, version and key**. A stale version requires a fresh +read and a new key. UCP uses `{ version, checkout }` on the same method; an uncertain +merchant update requires reconciliation, not an automatic retry. + +`needs_revision` / `nextAction.type: "revise"` includes the refusing rules in +`nextAction.reasons`. The poller returns this decision immediately. The authorizer +throws `TransactionRevisionRequiredError`, carrying the transaction and reasons +(or returns the decision with `throwOnDenied: false`). Fetch, Axios and Node HTTP +integrations also throw this error in both fail-open and fail-closed modes, before +sending the protected request. They never edit or resubmit a purchase themselves. + ##### Helper Methods ```typescript @@ -186,21 +227,21 @@ client.transactions.getPaymentDetails(transaction): PaymentDetails | null ```typescript // Store one secret under an external ref -await client.vault.set('agent-123', 'OPENAI_API_KEY', { - value: 'sk-...' +await client.vault.set("agent-123", "OPENAI_API_KEY", { + value: "sk-...", }); // Read one secret. Missing keys return null. -const openaiKey = await client.vault.get('agent-123', 'OPENAI_API_KEY'); +const openaiKey = await client.vault.get("agent-123", "OPENAI_API_KEY"); // Read a subset of secrets from the same ref -const secrets = await client.vault.getMany('agent-123', [ - 'OPENAI_API_KEY', - 'ANTHROPIC_API_KEY' +const secrets = await client.vault.getMany("agent-123", [ + "OPENAI_API_KEY", + "ANTHROPIC_API_KEY", ]); // Remove one key -await client.vault.deleteKey('agent-123', 'OPENAI_API_KEY'); +await client.vault.deleteKey("agent-123", "OPENAI_API_KEY"); ``` ## HTTP Integrations @@ -261,7 +302,11 @@ try { ### Custom HTTP Adapter ```typescript -import type { HttpClientAdapter, HttpRequest, HttpResponse } from '@sapiom/core'; +import type { + HttpClientAdapter, + HttpRequest, + HttpResponse, +} from "@sapiom/core"; class MyCustomAdapter implements HttpClientAdapter { async request(config: HttpRequest): Promise { @@ -273,11 +318,11 @@ class MyCustomAdapter implements HttpClientAdapter { ### Payment Error Detection ```typescript -import { isPaymentRequiredError, extractX402Response } from '@sapiom/core'; +import { isPaymentRequiredError, extractX402Response } from "@sapiom/core"; if (isPaymentRequiredError(error)) { const x402Response = extractX402Response(error); - console.log('Payment required:', x402Response); + console.log("Payment required:", x402Response); } ``` @@ -292,7 +337,7 @@ import type { HttpResponse, X402Response, X402PaymentRequirement, -} from '@sapiom/core'; +} from "@sapiom/core"; ``` ## License diff --git a/packages/core/src/client/TransactionAPI.ts b/packages/core/src/client/TransactionAPI.ts index 54114db0b..b2cc29eca 100644 --- a/packages/core/src/client/TransactionAPI.ts +++ b/packages/core/src/client/TransactionAPI.ts @@ -7,6 +7,7 @@ import { TransactionStatus, TransactionCostInput, TransactionCostResponse, + UpdatePurchaseRequest, } from "../types/transaction.js"; import type { HttpClient } from "./HttpClient.js"; @@ -19,10 +20,34 @@ export class TransactionAPI { * @returns The created transaction response */ async create(data: CreateTransactionRequest): Promise { + const { idempotencyKey, ...body } = data; return await this.httpClient.request({ method: "POST", url: "/transactions", + body, + ...(idempotencyKey && { headers: { "Idempotency-Key": idempotencyKey } }), + }); + } + + /** + * Replace an unfinished purchase. A browser timeout is safe to retry only with the identical + * body, version and key. Acceptance starts fresh governance; always follow nextAction. + */ + async update( + transactionId: string, + data: UpdatePurchaseRequest, + options: { idempotencyKey: string }, + ): Promise { + if ( + !options.idempotencyKey.trim() || + options.idempotencyKey.trim().length > 255 + ) + throw new Error("idempotencyKey must contain 1 to 255 characters"); + return this.httpClient.request({ + method: "POST", + url: `/transactions/${transactionId}/update`, body: data, + headers: { "Idempotency-Key": options.idempotencyKey }, }); } diff --git a/packages/core/src/client/TransactionAPI.update.test.ts b/packages/core/src/client/TransactionAPI.update.test.ts new file mode 100644 index 000000000..b7716eebc --- /dev/null +++ b/packages/core/src/client/TransactionAPI.update.test.ts @@ -0,0 +1,79 @@ +import { TransactionAPI } from "./TransactionAPI.js"; +import type { HttpClient } from "./HttpClient.js"; +import type { + BrowserPurchase, + UpdatePurchaseRequest, +} from "../types/transaction.js"; + +const purchase: BrowserPurchase = { + type: "browser_checkout", + merchant: { origin: "https://shop.example" }, + total: { amount: "0.40", currency: "USD" }, +}; + +describe("purchase updates", () => { + const request = jest.fn(); + const api = new TransactionAPI({ request } as unknown as HttpClient); + beforeEach(() => request.mockReset()); + + it("forwards a stable key and the exact replacement body, and preserves the result", async () => { + const result = { + id: "tx", + status: "preparing", + nextAction: { type: "wait", actor: "system" }, + }; + request.mockResolvedValue(result); + const input: UpdatePurchaseRequest = { version: "v1", purchase }; + expect(await api.update("tx", input, { idempotencyKey: "change-1" })).toBe( + result, + ); + await api.update("tx", input, { idempotencyKey: "change-1" }); + expect(request.mock.calls).toEqual( + Array(2).fill([ + { + method: "POST", + url: "/transactions/tx/update", + body: input, + headers: { "Idempotency-Key": "change-1" }, + }, + ]), + ); + }); + + it("supports UCP replacement and preserves server conflicts", async () => { + const failure = Object.assign(new Error("stale version"), { + status: 409, + code: "stale_version", + }); + request.mockRejectedValue(failure); + await expect( + api.update( + "tx", + { version: "v1", checkout: { line_items: [] } }, + { idempotencyKey: "change" }, + ), + ).rejects.toBe(failure); + }); + + it("forwards purchase creation's key in a header", async () => { + await api.create({ + purchase, + funding: { source: "external_card" }, + idempotencyKey: "create-1", + }); + expect(request).toHaveBeenCalledWith({ + method: "POST", + url: "/transactions", + body: { purchase, funding: { source: "external_card" } }, + headers: { "Idempotency-Key": "create-1" }, + }); + }); + + it("requires a nonempty bounded key before any request", async () => { + for (const idempotencyKey of [" ", "a".repeat(256)]) + await expect( + api.update("tx", { version: "v1", purchase }, { idempotencyKey }), + ).rejects.toThrow("idempotencyKey"); + expect(request).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/core/src/client/TransactionPoller.test.ts b/packages/core/src/client/TransactionPoller.test.ts new file mode 100644 index 000000000..72ff36455 --- /dev/null +++ b/packages/core/src/client/TransactionPoller.test.ts @@ -0,0 +1,45 @@ +import { TransactionPoller } from "./TransactionPoller.js"; +import { SapiomClient } from "./SapiomClient.js"; + +describe("purchase polling", () => { + it("returns the revision decision and details immediately without another poll", async () => { + const transaction = { + id: "tx", + status: "needs_revision", + nextAction: { + type: "revise", + actor: "agent", + reasons: [ + { ruleId: "r", code: "rule_denied", message: "Over the limit" }, + ], + }, + }; + const get = jest.fn().mockResolvedValue(transaction); + const poller = new TransactionPoller( + { transactions: { get } } as unknown as SapiomClient, + {}, + ); + expect(await poller.waitForAuthorization("tx")).toEqual({ + status: "needs_revision", + transaction, + }); + expect(get).toHaveBeenCalledTimes(1); + }); + + it("waits through an approval and returns authorization when it arrives", async () => { + const authorized = { id: "tx", status: "authorized" }; + const get = jest + .fn() + .mockResolvedValueOnce({ id: "tx", status: "waiting_approval" }) + .mockResolvedValue(authorized); + const poller = new TransactionPoller( + { transactions: { get } } as unknown as SapiomClient, + { pollInterval: 1 }, + ); + expect(await poller.waitForAuthorization("tx")).toEqual({ + status: "authorized", + transaction: authorized, + }); + expect(get).toHaveBeenCalledTimes(2); + }); +}); diff --git a/packages/core/src/client/TransactionPoller.ts b/packages/core/src/client/TransactionPoller.ts index cfe7278f8..0ec14539d 100644 --- a/packages/core/src/client/TransactionPoller.ts +++ b/packages/core/src/client/TransactionPoller.ts @@ -8,6 +8,7 @@ import { SapiomClient } from "./SapiomClient.js"; export type TransactionPollResult = | { status: "authorized"; transaction: TransactionResponse } | { status: "denied"; transaction: TransactionResponse } + | { status: "needs_revision"; transaction: TransactionResponse } | { status: "timeout" }; /** @@ -108,6 +109,13 @@ export class TransactionPoller { const transaction = await this.sapiomClient.transactions.get(transactionId); + if ( + transaction.status === TransactionStatus.NEEDS_REVISION || + transaction.nextAction?.type === "revise" + ) { + return { status: "needs_revision", transaction }; + } + if (transaction.status === TransactionStatus.AUTHORIZED) { return { status: "authorized", transaction }; } diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index d29c9d008..3ecb9d90f 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -1,3 +1,4 @@ +export { TransactionRevisionRequiredError } from "./utils/TransactionRevisionRequiredError.js"; /** * @sapiom/core - Core SDK for Sapiom API * @@ -73,6 +74,12 @@ export type { CompleteTransactionRequest, CompleteTransactionResult, CreateTransactionRequest, + BrowserPurchase, + UcpPurchase, + PurchaseFunding, + UpdatePurchaseRequest, + PurchaseView, + PurchaseGovernanceReason, TransactionResponse, PaymentTransactionResponse, PaymentProtocolData, diff --git a/packages/core/src/types/transaction.ts b/packages/core/src/types/transaction.ts index 2badc357f..110c6b20f 100644 --- a/packages/core/src/types/transaction.ts +++ b/packages/core/src/types/transaction.ts @@ -1,6 +1,8 @@ export enum TransactionStatus { PENDING = "pending", PREPARING = "preparing", + WAITING_APPROVAL = "waiting_approval", + NEEDS_REVISION = "needs_revision", AUTHORIZED = "authorized", COMPLETED = "completed", DENIED = "denied", @@ -19,7 +21,69 @@ export interface TransactionCostInput { costDetails?: Record; } +export interface BrowserPurchase { + type: "browser_checkout"; + merchant: { origin: string; name?: string; countryCode?: string }; + total: { amount: string; currency: string }; + description?: string; + claimedLineItems?: Array<{ + title: string; + quantity: number; + unitAmount?: string; + }>; + pageUrl?: string; +} + +export interface UcpPurchase { + type: "ucp_checkout"; + merchant: { origin: string; name?: string; countryCode?: string }; + checkout: Record; +} + +export type PurchaseFunding = + | { + paymentMethodId: string; + credentialRoute?: "real_card_number" | "network_agentic_token"; + } + | { + source: "external_card"; + paymentCardId?: string; + credentialRoute?: "real_card_number" | "network_agentic_token"; + }; + +/** Full replacement of one purchase source, under the latest version. Funding is fixed. */ +export type UpdatePurchaseRequest = { version: string } & ( + | { purchase: BrowserPurchase; checkout?: never } + | { checkout: Record; purchase?: never } +); + +export interface PurchaseView { + type: "browser_checkout" | "ucp_checkout"; + assertedBy: "agent" | "merchant"; + merchant: { origin: string; name?: string; countryCode?: string }; + total: { amount: string; currency: string } | null; + lineItems?: Array<{ + title?: string; + itemId?: string; + quantity: number; + unitAmount?: string; + }>; + revision?: number; + description?: string; + pageUrl?: string; +} + +export interface PurchaseGovernanceReason { + ruleId: string; + code: string; + message: string; +} + export interface CreateTransactionRequest { + purchase?: BrowserPurchase | UcpPurchase; + funding?: PurchaseFunding; + /** Forwarded as Idempotency-Key, never as part of the body. */ + idempotencyKey?: string; requestFacts?: { source: string; version: string; @@ -80,6 +144,7 @@ export interface TransactionCostResponse { } export interface TransactionResponse { + purchase?: PurchaseView; /** Changes with the actionable purchase state; usable with a bounded get. */ version?: string; nextAction?: { @@ -87,6 +152,7 @@ export interface TransactionResponse { actor: string; url?: string; expiresAt?: string; + reasons?: PurchaseGovernanceReason[]; [field: string]: unknown; }; id: string; diff --git a/packages/core/src/utils/TransactionAuthorizer.test.ts b/packages/core/src/utils/TransactionAuthorizer.test.ts index 671097a0e..900f8ca80 100644 --- a/packages/core/src/utils/TransactionAuthorizer.test.ts +++ b/packages/core/src/utils/TransactionAuthorizer.test.ts @@ -1,3 +1,4 @@ +import { TransactionRevisionRequiredError } from "./TransactionRevisionRequiredError"; /** * Tests for TransactionAuthorizer */ @@ -46,6 +47,35 @@ describe("TransactionAuthorizer", () => { }); }); + it.each(["create", "existing"])( + "preserves actionable revision details for %s authorization", + async (mode) => { + const transaction = { + id: "tx-123", + status: "needs_revision", + nextAction: { type: "revise", actor: "agent", reasons: [] }, + }; + (mockClient.transactions.get as jest.Mock).mockResolvedValue(transaction); + const call = () => + mode === "create" + ? authorizer.createAndAuthorize({ resourceName: "shop" }) + : authorizer.waitForExisting("tx-123"); + await expect(call()).rejects.toBeInstanceOf( + TransactionRevisionRequiredError, + ); + await expect(call()).rejects.toMatchObject({ + transaction, + nextAction: transaction.nextAction, + }); + expect(onAuthorizationSuccess).not.toHaveBeenCalled(); + authorizer = new TransactionAuthorizer({ + sapiomClient: mockClient, + throwOnDenied: false, + }); + expect(await call()).toBe(transaction); + }, + ); + describe("createAndAuthorize", () => { it("creates transaction with traceExternalId", async () => { const tx = await authorizer.createAndAuthorize({ diff --git a/packages/core/src/utils/TransactionAuthorizer.ts b/packages/core/src/utils/TransactionAuthorizer.ts index 08bc443c2..f99306f13 100644 --- a/packages/core/src/utils/TransactionAuthorizer.ts +++ b/packages/core/src/utils/TransactionAuthorizer.ts @@ -1,3 +1,4 @@ +import { TransactionRevisionRequiredError } from "./TransactionRevisionRequiredError.js"; /** * Core transaction authorization logic * @@ -264,6 +265,12 @@ export class TransactionAuthorizer { // Wait for authorization using centralized poller const result = await this.poller.waitForAuthorization(tx.id); + if (result.status === "needs_revision") { + if (this.config.throwOnDenied !== false) + throw new TransactionRevisionRequiredError(result.transaction); + return result.transaction; + } + // Handle result if (result.status === "authorized") { this.config.onAuthorizationSuccess?.( @@ -314,6 +321,11 @@ export class TransactionAuthorizer { */ async waitForExisting(transactionId: string): Promise { const result = await this.poller.waitForAuthorization(transactionId); + if (result.status === "needs_revision") { + if (this.config.throwOnDenied !== false) + throw new TransactionRevisionRequiredError(result.transaction); + return result.transaction; + } if (result.status === "authorized") { return result.transaction; diff --git a/packages/core/src/utils/TransactionRevisionRequiredError.ts b/packages/core/src/utils/TransactionRevisionRequiredError.ts new file mode 100644 index 000000000..09f21e354 --- /dev/null +++ b/packages/core/src/utils/TransactionRevisionRequiredError.ts @@ -0,0 +1,14 @@ +import type { TransactionResponse } from "../types/transaction.js"; + +/** A policy decision, not an SDK outage: callers must change the purchase before trying again. */ +export class TransactionRevisionRequiredError extends Error { + readonly transactionId: string; + readonly nextAction: TransactionResponse["nextAction"]; + + constructor(public readonly transaction: TransactionResponse) { + super(`Transaction ${transaction.id} requires a revised purchase`); + this.name = "TransactionRevisionRequiredError"; + this.transactionId = transaction.id; + this.nextAction = transaction.nextAction; + } +} diff --git a/packages/fetch/src/failureMode.test.ts b/packages/fetch/src/failureMode.test.ts index 9b82a177d..1b8cd89b3 100644 --- a/packages/fetch/src/failureMode.test.ts +++ b/packages/fetch/src/failureMode.test.ts @@ -3,7 +3,11 @@ * These tests ensure Sapiom failures don't break customer apps */ import { createFetch } from "./fetch"; -import { SapiomClient, TransactionAPI } from "@sapiom/core"; +import { + SapiomClient, + TransactionAPI, + TransactionRevisionRequiredError, +} from "@sapiom/core"; import fetchMock from "@fetch-mock/jest"; describe("Fetch failureMode", () => { @@ -37,6 +41,40 @@ describe("Fetch failureMode", () => { fetchMock.unmockGlobal(); }); + it.each(["open", "closed"] as const)( + "blocks revision decisions in failureMode %s", + async (failureMode) => { + for (const mode of ["create", "existing", "poll"] as const) { + const transaction = { + id: "tx-revise", + status: "needs_revision", + nextAction: { type: "revise", actor: "agent", reasons: [] }, + }; + mockTransactionAPI.create.mockResolvedValue( + mode === "poll" + ? ({ id: "tx-revise", status: "pending" } as any) + : (transaction as any), + ); + mockTransactionAPI.get.mockResolvedValue(transaction as any); + fetchMock.get("https://api.example.com/test", { status: 200 }); + const client = createFetch({ + sapiomClient: mockSapiomClient, + failureMode, + polling: { pollInterval: 1 }, + }); + await expect( + client("https://api.example.com/test", { + headers: + mode === "existing" + ? { "X-Sapiom-Transaction-Id": "tx-revise" } + : {}, + }), + ).rejects.toBeInstanceOf(TransactionRevisionRequiredError); + expect(fetchMock.callHistory.calls()).toHaveLength(0); + } + }, + ); + describe('failureMode: "open" (default)', () => { it("should allow request when Sapiom API returns 500", async () => { fetchMock.get("https://api.example.com/test", { diff --git a/packages/fetch/src/interceptors.ts b/packages/fetch/src/interceptors.ts index 1d8b352cd..154df4dfe 100644 --- a/packages/fetch/src/interceptors.ts +++ b/packages/fetch/src/interceptors.ts @@ -2,6 +2,7 @@ import { SapiomClient, TransactionPoller, TransactionStatus, + TransactionRevisionRequiredError, captureUserCallSite, extractX402Response, extractResourceFromError, @@ -136,10 +137,13 @@ export async function handleAuthorization( const endpoint = request.url; switch (transaction.status) { + case TransactionStatus.NEEDS_REVISION: + throw new TransactionRevisionRequiredError(transaction); case TransactionStatus.AUTHORIZED: return request; case TransactionStatus.PENDING: + case TransactionStatus.WAITING_APPROVAL: case TransactionStatus.PREPARING: { let authResult; try { @@ -153,6 +157,9 @@ export async function handleAuthorization( return request; } + if (authResult.status === "needs_revision") + throw new TransactionRevisionRequiredError(authResult.transaction); + if (authResult.status === "authorized") { return request; } else if (authResult.status === "denied") { @@ -260,10 +267,13 @@ export async function handleAuthorization( } switch (transaction.status) { + case TransactionStatus.NEEDS_REVISION: + throw new TransactionRevisionRequiredError(transaction); case TransactionStatus.AUTHORIZED: break; case TransactionStatus.PENDING: + case TransactionStatus.WAITING_APPROVAL: case TransactionStatus.PREPARING: { const poller = new TransactionPoller(config.sapiomClient, polling); @@ -279,6 +289,9 @@ export async function handleAuthorization( return request; } + if (authResult.status === "needs_revision") + throw new TransactionRevisionRequiredError(authResult.transaction); + if (authResult.status === "denied") { throw new AuthorizationDeniedError(transaction.id, endpoint); } else if (authResult.status === "timeout") { @@ -370,7 +383,10 @@ export async function handlePayment( // If no transaction ID exists (authorization was skipped/failed in failureMode:open), // create one on-demand so we can still handle the 402 payment flow. if (!existingTransactionId) { - const requestMetadata = { ...defaultMetadata, ...((request as any).__sapiom || {}) }; + const requestMetadata = { + ...defaultMetadata, + ...((request as any).__sapiom || {}), + }; const callSite = captureUserCallSite(); const parsedUrl = new URL(request.url); @@ -422,7 +438,11 @@ export async function handlePayment( // Write the transaction ID back to the original request so // handleCompletion (which reads X-Sapiom-Transaction-Id from // request headers) can complete this on-demand transaction. - setHeader(request.headers, "X-Sapiom-Transaction-Id", existingTransactionId); + setHeader( + request.headers, + "X-Sapiom-Transaction-Id", + existingTransactionId, + ); } catch (error) { if (config.failureMode === "closed") throw error; console.error( @@ -460,6 +480,8 @@ export async function handlePayment( } // Poll for authorization if not already authorized + if (transaction.status === TransactionStatus.NEEDS_REVISION) + throw new TransactionRevisionRequiredError(transaction); if (transaction.status !== TransactionStatus.AUTHORIZED) { const poller = new TransactionPoller(config.sapiomClient, polling); @@ -475,6 +497,9 @@ export async function handlePayment( return response; } + if (authResult.status === "needs_revision") + throw new TransactionRevisionRequiredError(authResult.transaction); + if (authResult.status !== "authorized") { return response; } diff --git a/packages/mcp/src/instructions.generated.ts b/packages/mcp/src/instructions.generated.ts index ffc7c7695..3b26421e8 100644 --- a/packages/mcp/src/instructions.generated.ts +++ b/packages/mcp/src/instructions.generated.ts @@ -1,5 +1,5 @@ // GENERATED by scripts/mcp-instructions-snapshot.mjs — do not edit. -// Source: GET https://api.sapiom.ai/v1/mcp/instructions +// Source: GET http://127.0.0.1:38989/v1/mcp/instructions // // This is the bundled snapshot of the authoring primer: the last source // instructions-fetch.ts falls back to, after the live copy and the last-known-good @@ -30,8 +30,8 @@ Its runtime \`tools/list\` response is authoritative; use \`tool_discover\` to f \`sapiom_*\` capability tool. If the hosted \`sapiom_check_transaction_compatibility\` tool is in your tools, call it with the merchant's domain before buying, and use UCP checkout only when \`status\` is \`supported\`. -Otherwise use browser checkout only with Sapiom's browser SDK integration, ready for the merchant's -payment flow. If the integration is unavailable or the payment flow is unsupported, stop. +Otherwise use browser checkout only with Browser Pay, ready for the merchant's +payment flow. If Browser Pay is unavailable or the payment flow is unsupported, stop. If the hosted capability server lists a transactions guide resource, it is an optional guide to the full transaction flow; tool descriptions and results stay authoritative. The endpoint may also advertise implemented cloud tools for @@ -39,6 +39,11 @@ deployed agents and governance tools, but the supported public authoring route i MCP or Agent Studio. Rule of thumb: author an agent for anything multi-step, scheduled, or deployable; use the hosted capability server or the TypeScript SDK for a single action. +A capability call that fails, for any reason, costs nothing: its usage and charge are reversed. +A paid browser session from \`sapiom_browser_session_create\` holds its payment until you close it +with \`sapiom_browser_session_terminate\`. Only the account that opened it can close it, and closing +it again returns the same receipt. A session you never close is settled within about three minutes +after its maximum duration ends (the hold is kept two minutes past it, then a sweep settles it). ## Lifecycle (in order) @@ -127,60 +132,181 @@ Payment cards, card spending limits and transactions run on the hosted capabilit (\`sapiom_list_payment_methods\`, \`sapiom_add_payment_method\`, \`sapiom_delete_payment_method\`, \`sapiom_get_card_spending_limits\`, \`sapiom_set_card_spending_limits\`, \`sapiom_request_transaction\`, \`sapiom_get_transaction\`, \`sapiom_update_transaction\` and \`sapiom_cancel_transaction\`). Follow that -server's instructions. Follow each result's \`nextAction\` or \`nextStep\`. When its actor is \`human\`, -stop: a person or trusted integrator must reconcile through the existing REST/merchant recovery; +server's instructions. Follow each result's \`nextAction\` or \`nextStep\`. Every next action you must +act on, and every transaction that ended without completing, carries an \`instruction\` (a \`note\` on +older actions) that says what to do now; follow it. When its actor is \`human\`, +stop: a person or trusted platform must reconcile through the existing REST/merchant recovery; do not act on it yourself. The update and cancel tools change only unfinished checkouts and never -place or refund an order. A \`payment_ready\` next action is not an order confirmation, and no tool -returns card details: finish paying at \`continueUrl\` with Sapiom's browser SDK integration, which -supplies the card. If it is unavailable or the merchant's payment flow is unsupported, cancel the -transaction, then stop. -A \`payment_submitted\` next action means the card went to the merchant's -payment provider, which ends Sapiom's part: stop polling, and never pay or buy again for it. +place or refund an order. A \`payment_ready\` next action is not an order confirmation. Its result +carries \`payment.placeholder\`, a stand-in card for this purchase only and not the user's card: +finish paying at \`continueUrl\` with Browser Pay, which swaps it for the user's +card on the way to the merchant. Attach Browser Pay to the browser first, with the placeholder's +\`number\` and \`injectionRef\`. Then type the placeholder's number, expiry and \`cvc\` into the card +form, and the country and postal code in \`payment.billing\` where the form asks for them. Never type +the placeholder while Browser Pay is not attached, never use it anywhere else, and do not show +it to the user. If Browser Pay is unavailable or the merchant's payment flow is unsupported, +cancel the transaction, then stop. +A \`wait\` reason of \`governing\` means Sapiom is preparing the payment; follow the +returned poll hint. A usable placeholder means \`payment_ready\`, not that payment +is being sent. Placeholder issuance and authorization commit atomically inside +Sapiom; there is no separate public issuance state. A \`wait\` reason of \`paying\` +requires current, attributable durable \`sending\` evidence with a live lease +less than 60 seconds old. It is an unresolved send attempt, not proof that the +provider call remains active or that the merchant confirmed an order. +A \`payment_submitted\` next action, or \`none\` on a card purchase whose payment reads \`completed\`, +means Sapiom handed the card to the merchant's payment provider, which ends Sapiom's part. Whether +the merchant placed the order is up to the merchant and changes nothing on Sapiom's side. Stop +polling, tell the user what the merchant's page showed, and never pay or buy again for it. +A card payment that reads \`blocked\` with reason \`payment_ended\` ended before the card was sent, so +nothing was charged (most often its approval expired, about an hour after the user confirmed the purchase). +Cancel it, then start a new transaction under a new idempotency key if the user still wants it. +Approve close to the moment you pay. This does not apply to \`payment_submitted\`, to a completed +checkout whose order the merchant has not confirmed, or to any result that says the outcome is +unconfirmed: never buy again for those. +\`continueUrl\` comes from the merchant and can be on another host than the merchant origin (a +Shopify store's \`myshopify.com\` link redirects to the store's own domain): open it, and don't +compare it with the merchant origin. The card is accepted only from a page on the merchant origin. An \`update_checkout\` next action is a normal checkout step, not a failure: the merchant needs more (often a shipping address or delivery option), which you send with \`sapiom_update_transaction\`. -\`sapiom_request_transaction\` takes an optional \`shipping\`: \`shipping.address\` is where the order -ships (with no fulfillment in the checkout, it becomes a shipping method for every line item), and -\`shipping.contact\` is how the merchant reaches the buyer. Send each only when it applies. Sapiom adds -them to the checkout create and every update. +\`sapiom_request_transaction\` takes what you buy as \`purchase\`. For a UCP merchant, send \`purchase\` of +type \`ucp_checkout\` with the merchant's origin and its checkout request. \`merchantOrigin\` with +\`checkout\` is an older form, still accepted; use \`purchase\`. + +A checkout with no usable UCP is a browser purchase: once the page you drive shows the final total, +call \`sapiom_request_transaction\` with \`purchase\` of type \`browser_checkout\`, stating the merchant +origin, that total and the items as the page shows them. The total is in the page's own currency (an +ISO 4217 code such as \`USD\`, \`EUR\` or \`JPY\`); one that can't be paid is refused at create. When +\`nextAction.type\` is \`payment_ready\`, pay on that page with Browser Pay, typing \`payment.placeholder\` as above. A browser purchase can be revised before any payment submission. If a spending rule refuses the +terms, \`needs_revision\` / \`nextAction.type: revise\` explains the measured amount and limit. Tell the +user; if they want to change the purchase, change the real cart first, then call +\`sapiom_update_transaction\` on the same transactionId with the latest version, a new idempotencyKey, +and a full replacement \`purchase\` in the create shape. Map read \`purchase.lineItems\` to update +\`purchase.claimedLineItems\`. Keep the entire merchant, currency and funding fixed. Sapiom records the +statement and evaluates new payment authority; it neither edits nor verifies the browser cart. +An unused authorized purchase or one awaiting approval can also be revised. Old confirmation links, +approvals and placeholders cannot authorize the changed terms. Follow the returned nextAction; +acceptance can mean \`wait\`, another refusal, or a new human step. Do not reopen a closed purchase. +For a lost browser-update response, read the purchase or resend the identical body, version and key; +never reuse that key for different terms. UCP's uncertain merchant updates still require reconciliation. +Insufficient budget capacity is a separate refusal: create can reject it before a transaction exists; +a later \`closed / budget_insufficient\` ends that purchase and reports the remaining funds. After you pay on that page, a +cancel can be refused with \`card_relayed\`: +the purchase can no longer be canceled here, so never pay or buy again for it. Its cancel contacts no +merchant. If it times out or may not have been saved, call \`sapiom_get_transaction\`; +if the purchase is not closed, retry the same cancellation with the same \`idempotencyKey\`. + +\`sapiom_request_transaction\` takes an optional \`shipping\` for a UCP checkout: \`shipping.address\` is +where the order ships (with no fulfillment in the checkout, it becomes a shipping method for every +line item), and \`shipping.contact\` is how the merchant reaches the user. Send each only when it +applies. Sapiom adds them to the checkout create and every update. A browser purchase takes none: +enter delivery details on the page. \`nextAction.type: wait\` with \`reason: complete_in_progress\` means the merchant is completing the order: poll \`sapiom_get_transaction\` with \`since\` (each poll also asks the merchant whether it finished) and do not retry, change, cancel or buy again. An update or cancel refused with \`completion_in_progress\` was not sent and is not retryable; wait on the transaction the same way. If -the checkout reopens instead of completing and the buyer still wants it, make it as a new change +the checkout reopens instead of completing and the user still wants it, make it as a new change under a new idempotency key. \`operation_in_flight\` means another call held the checkout; that change was not sent and can be retried with the same idempotency key. \`internal_error\` whose message says Sapiom failed sent nothing to the merchant: stop and report its \`requestId\` to support@sapiom.ai. Only an \`internal_error\` that says the transaction may still be opening, or that a change may have applied, has an unknown outcome; follow its \`nextStep\`. A \`sapiom_request_transaction\` that timed out or may still be opening is resumed only by sending the same request with the same idempotency key, -never under a new key. +never under a new key. The same applies when an MCP create returns an internal/server JSON-RPC +error after it may have reached the merchant: the transaction stays opening and its action asks +you to resend the same request under the original key. + +An ended transaction can still have an unconfirmed payment. If \`nextAction.type: closed\` carries +\`retryable: false\`, follow that warning before any cause-specific guidance below: stop, do not pay +again or start another transaction, and ask the user to check the merchant's site or email for an +order. MCP identifies the person step with \`actor: human\`. The recorded cause and merchant messages +remain available; neither a cancellation reason nor an absent current payment proves nothing was +charged. Do not poll this terminal purchase or call the checkout refresh route: it does not accept +terminal sessions. This exception can follow an unknown relay, a credential outcome, or unavailable +payment evidence. When a transaction returns \`nextAction.type: closed\` with \`reason: buyer_canceled\` or -\`confirmation_expired\`, tell the buyer the reason and stop. Do not revise or retry that transaction. -Start a new transaction with a new idempotency key only if the buyer still wants to buy. Merchant +\`confirmation_expired\`, tell the user the reason and stop. Do not revise or retry that transaction. +Start a new transaction with a new idempotency key only if the user still wants to buy. Merchant checkout cancellation runs separately; its retries never reopen the closed transaction. \`nextAction.type: closed\` with \`reason: sapiom_error\` means the transaction failed on Sapiom's side. Tell -the buyer, stop, and report the \`requestId\` to support@sapiom.ai. Do not +the user, stop, and report the \`requestId\` to support@sapiom.ai. Do not revise or retry that transaction. A \`revise\` action's \`reasons\` list \`{ruleId, code, message}\` per rule -that denied the cart; tell the buyer, then change the cart with \`sapiom_update_transaction\` if they +that denied the cart; tell the user, then change the cart with \`sapiom_update_transaction\` if they want to, or stop. \`nextAction.type: closed\` with \`reason: payments_paused\` means Sapiom has paused card payments and -closed the transaction. Tell the buyer and stop. Do not revise or retry it: a new +closed the transaction. Tell the user and stop. Do not revise or retry it: a new card transaction ends the same way until Sapiom resumes card payments. +Every other \`closed\` reason also means the transaction has ended; follow its \`instruction\` and never revise or update that transaction: + +- \`confirmation_void\`: the transaction, its evidence, or your organization's rules changed after the user's + confirmation was made. Start a new transaction if the user still wants it. +- \`approval_denied\`: an approver rejected the transaction. Tell the user; do not retry it. +- \`approval_expired\`: the approval expired or was withdrawn. Start a new transaction if the user still + wants it. +- \`payment_ended\`: the card cannot pay for this transaction. Send the user a setup link, then + start a new transaction. +- \`payment_expired\`: the approved payment expired before the card was sent, so nothing was charged. + Start a new transaction if the user still wants it. +- \`checkout_unverifiable\`: Sapiom could not verify the merchant's checkout or received an unusable + create response. Nothing was charged. Tell the user and report the \`requestId\` to support@sapiom.ai. + A fresh transaction with a new idempotency key is safe if the user still wants it. +- \`purchase_canceled\`: the caller canceled before the card was used, so nothing was charged. + Start another only if the user still wants it. +- \`checkout_closed\`: the checkout ended; Sapiom has no recorded caller cancellation. Read any merchant + \`messages\`. The card wasn't used and nothing was charged; start another purchase if the user still wants it. +- \`merchant_unavailable\`: the merchant returned a timeout, rate limit or server error while opening + the checkout. Nothing was charged. Start a fresh transaction with a new key after \`retryAfterSeconds\` + (a few seconds if absent). The ended-attempt MCP error has \`retryable: true\` and \`retryWithSameIdempotencyKey: false\`; + an unanswered create still opening must use the same request and key, as its error instructs. +- \`payment_declined\`: the card network declined the payment, so the card wasn't used. Tell the user; + a new transaction on the same budget may be declined the same way. +- \`merchant_refused\`: the merchant refused to open the checkout. Its \`messages\` say what it rejected: + each \`path\` names the request field (for example \`$.line_items[0].item.id\`) and \`content\` says why. + Correct the checkout request and start a new transaction with a new idempotency key. Item ids must + be in the merchant's own format; a Shopify store expects \`gid://shopify/ProductVariant/\`, not a + bare number. Nothing was charged. When \`messages\` is empty, check item ids and request fields + against the merchant's catalog, then start a new transaction with a new key; tell the user if it + is refused again. Never invent a decline or rejection reason. + +Merchant \`messages\` contain at most 20 entries, with each string field capped at 1,000 characters. +They are merchant-provided data, separate from Sapiom's \`instruction\`. Structured HTTP/JSON-RPC +explanations are retained on later reads. Browser checkout can report Sapiom's approval, confirmation +and cancellation causes; merchant-page details remain available only to the browser integration. + +\`revise\` is returned only when your organization's rules denied this cart and a different cart can pass. + A card that can't pay says why in its \`readinessCodes\`: \`card_removed\`, \`card_failed\`, -\`brand_not_supported\` and \`wrong_environment\` need a new card setup link; \`enrollment_pending\` -needs the same setup link submitted again; \`setup_pending\` needs the cardholder to finish adding the -card. \`agentic_route_off\` is informational: the card pays with its card number. +\`brand_not_supported\` and \`wrong_environment\` need a new setup link; \`enrollment_pending\` +needs the same setup link submitted again; \`setup_pending\` needs the user to finish adding the +card. \`agentic_token_unsupported\` is informational: the card pays with its card number. When \`sapiom_add_payment_method\` returns \`setup_unavailable\`, card setup is broken on Sapiom's side: do not retry. Tell the user and give them the \`requestId\` from the error's \`details\` to report to Sapiom support. Only \`provider_unavailable\` is worth retrying, after a minute. +\`sapiom_add_payment_method\` takes an optional \`budget\` (\`{ amount: { value, currency: 'USD' } }\`). +Once the card is added, the setup page shows that amount for the user to confirm as the card's +budget for 30 days, verified with the card network when the card supports it; without it, the +user enters the amount or skips. The link's \`returnUrl\` gets a \`budget\` parameter saying how +that step ended: \`verified\`, \`card_number\`, \`failed\` or \`skipped\`. + +A card transaction refused with reason \`budget_insufficient\` (error \`payment_method_not_ready\`) +created nothing: the card's budget can't cover the total. The error's \`details.budget\` says what is +left (\`available\`) and until when (\`expiresAt\`). Buy within it, or tell the user: only the +user can set a new budget, on a budget link the platform sends +(\`POST /v1/payment-cards/{cardId}/budget-links\`). Then start a new transaction under a new +idempotency key. + +A transaction its budget refused later, once its final total was known, reads the same way on +every merchant: \`payment.denial\` says why (\`budget_insufficient\`, \`budget_expired\`, +\`budget_cancelled\` or \`merchant_mismatch\`) and \`payment.budget\` carries the same \`available\` and +\`expiresAt\`. Nothing was charged; follow its \`nextAction\` instruction. + ## Triggers (run a deployed agent without a human) \`sapiom_dev_agents_schedule\` creates a trigger of one of four kinds on a deployed agent: @@ -236,6 +362,10 @@ Listen with an \`event\` trigger; the events API refuses it. models.coding, fileStorage, search, database, email, domains, memory, and more) — don't memorize the catalog; use autocomplete/typecheck. Schedules (cron triggers) are a top-level \`@sapiom/tools\` import, not under \`ctx.sapiom\`. +- A web search bills one search per call at the tier you ask for: \`depth: "deep"\` is the premium + deep-search tier, priced well above a standard search, so leave depth at standard unless you need + the more thorough answer. A links-only search (\`sapiom_deep_search\`, despite its name) is always + standard. - A Sapiom Postgres (\`ctx.sapiom.database.create\`) is permanent: it lives until you delete it, holds one slot of your plan's database limit while held, and never expires — there is no lifetime to pick and no \`duration\` to pass. @@ -243,6 +373,11 @@ Listen with an \`event\` trigger; the events API refuses it. 64 Unicode code points; pass the namespace they were written under. - \`ctx.sapiom.fileStorage.upload(…)\` returns \`uploadUrl\`, \`requiredHeaders\` and \`expiresAt\`: PUT the file bytes to \`uploadUrl\` yourself, with exactly those headers, before \`expiresAt\`. +- \`ctx.sapiom.domains.register\` refuses most country-code TLDs (e.g. \`.be\`, \`.fr\`, \`.eu\`) before + any charge: their registries can require a local holder or an identity check before activating + a domain. Generic TLDs (\`.com\`, \`.app\`, \`.dev\`, …) and open country codes such as \`.io\`, \`.co\`, + \`.me\` and \`.mx\` work; availability checks mark refused names as not supported. \`.ai\` is refused + too: Name.com only sells it for two years or more, and Sapiom registers domains for one year. ## Secrets, inbound events, receipts @@ -302,8 +437,8 @@ Full reference: the \`AGENTS.md\` and \`sapiom-agent-authoring\` skill inside yo project.`; /** `X-Sapiom-Content-Release` of the response this snapshot was taken from. */ -export const AUTHORING_INSTRUCTIONS_RELEASE = "2026-10-27.7"; +export const AUTHORING_INSTRUCTIONS_RELEASE = "2026-11-15.1"; /** Full sha-256 hex of {@link AUTHORING_INSTRUCTIONS}; the served header carries its first 12 characters. */ export const AUTHORING_INSTRUCTIONS_DIGEST = - "09951c71847789d4b5616a101eccd4568ba73c11cdd35af140f47f9aab2c71ed"; + "1a5996bc100fec13eab6eab04ac38f8c7bb2477d1a5390e0c875578c77626957"; diff --git a/packages/mcp/src/instructions.test.ts b/packages/mcp/src/instructions.test.ts index e6d85fb23..9a90c0ea3 100644 --- a/packages/mcp/src/instructions.test.ts +++ b/packages/mcp/src/instructions.test.ts @@ -44,6 +44,18 @@ describe("server instructions", () => { expect(sha256).toBe(AUTHORING_INSTRUCTIONS_DIGEST); }); + it("distinguishes a browser revision from an uncertain merchant update", () => { + expect(AUTHORING_INSTRUCTIONS).toContain("same transactionId"); + expect(AUTHORING_INSTRUCTIONS).toContain("purchase.claimedLineItems"); + expect(AUTHORING_INSTRUCTIONS).toContain("identical body, version and key"); + expect(AUTHORING_INSTRUCTIONS).toContain( + "neither edits nor verifies the browser cart", + ); + expect(AUTHORING_INSTRUCTIONS).toContain( + "uncertain merchant updates still require reconciliation", + ); + }); + it("primer covers the lifecycle, canonical rules, and points to the docs", () => { // Lifecycle tools an agent must drive expect(AUTHORING_INSTRUCTIONS).toContain("sapiom_authenticate"); diff --git a/packages/node-http/src/failureMode.test.ts b/packages/node-http/src/failureMode.test.ts index f40784b3b..1d8e9e5ff 100644 --- a/packages/node-http/src/failureMode.test.ts +++ b/packages/node-http/src/failureMode.test.ts @@ -3,7 +3,11 @@ * These tests ensure Sapiom failures don't break customer apps */ import { createClient } from "./node-http"; -import { SapiomClient, TransactionAPI } from "@sapiom/core"; +import { + SapiomClient, + TransactionAPI, + TransactionRevisionRequiredError, +} from "@sapiom/core"; import nock from "nock"; describe("Node-HTTP failureMode", () => { @@ -31,6 +35,44 @@ describe("Node-HTTP failureMode", () => { nock.cleanAll(); }); + it.each(["open", "closed"] as const)( + "blocks revision decisions in failureMode %s", + async (failureMode) => { + for (const mode of ["create", "existing", "poll"] as const) { + const transaction = { + id: "tx-revise", + status: "needs_revision", + nextAction: { type: "revise", actor: "agent", reasons: [] }, + }; + mockTransactionAPI.create.mockResolvedValue( + mode === "poll" + ? ({ id: "tx-revise", status: "pending" } as any) + : (transaction as any), + ); + mockTransactionAPI.get.mockResolvedValue(transaction as any); + const endpoint = nock("https://api.example.com") + .get("/test") + .reply(200); + const client = createClient({ + sapiomClient: mockSapiomClient, + failureMode, + polling: { pollInterval: 1 }, + }); + await expect( + client.request({ + method: "GET", + url: "https://api.example.com/test", + headers: + mode === "existing" + ? { "X-Sapiom-Transaction-Id": "tx-revise" } + : {}, + }), + ).rejects.toBeInstanceOf(TransactionRevisionRequiredError); + expect(endpoint.isDone()).toBe(false); + } + }, + ); + describe('failureMode: "open" (default)', () => { it("should allow request when Sapiom API returns 500", async () => { nock("https://api.example.com") diff --git a/packages/node-http/src/interceptors.ts b/packages/node-http/src/interceptors.ts index 3cf168e9d..f90264bdc 100644 --- a/packages/node-http/src/interceptors.ts +++ b/packages/node-http/src/interceptors.ts @@ -2,6 +2,7 @@ import { SapiomClient, TransactionPoller, TransactionStatus, + TransactionRevisionRequiredError, captureUserCallSite, extractX402Response, extractResourceFromError, @@ -141,10 +142,13 @@ export async function handleAuthorization( const endpoint = request.url; switch (transaction.status) { + case TransactionStatus.NEEDS_REVISION: + throw new TransactionRevisionRequiredError(transaction); case TransactionStatus.AUTHORIZED: return request; case TransactionStatus.PENDING: + case TransactionStatus.WAITING_APPROVAL: case TransactionStatus.PREPARING: { let authResult; try { @@ -158,6 +162,9 @@ export async function handleAuthorization( return request; } + if (authResult.status === "needs_revision") + throw new TransactionRevisionRequiredError(authResult.transaction); + if (authResult.status === "authorized") { return request; } else if (authResult.status === "denied") { @@ -268,6 +275,9 @@ export async function handleAuthorization( throw new AuthorizationDeniedError(transaction.id, endpoint); } + if (transaction.status === TransactionStatus.NEEDS_REVISION) + throw new TransactionRevisionRequiredError(transaction); + if (transaction.status === TransactionStatus.AUTHORIZED) { const modifiedRequest = { ...request }; modifiedRequest.headers = { ...request.headers }; @@ -292,6 +302,9 @@ export async function handleAuthorization( return request; } + if (result.status === "needs_revision") + throw new TransactionRevisionRequiredError(result.transaction); + if (result.status === "authorized") { const modifiedRequest = { ...request }; modifiedRequest.headers = { ...request.headers }; @@ -382,6 +395,9 @@ export async function handlePayment( throw error; } + if (transaction.status === TransactionStatus.NEEDS_REVISION) + throw new TransactionRevisionRequiredError(transaction); + if (transaction.status !== TransactionStatus.AUTHORIZED) { const polling = { ...DEFAULT_POLLING, ...config.polling }; let authResult; @@ -397,6 +413,9 @@ export async function handlePayment( throw error; } + if (authResult.status === "needs_revision") + throw new TransactionRevisionRequiredError(authResult.transaction); + if (authResult.status !== "authorized") { throw error; } From 2ce420ec39a312bfa9da8b835d662cf4b51c50af Mon Sep 17 00:00:00 2001 From: Yash Date: Sun, 15 Nov 2026 04:59:17 +0000 Subject: [PATCH 2/4] test(mcp): verify snapshots using their recorded source --- scripts/mcp-instructions-snapshot.test.mjs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/scripts/mcp-instructions-snapshot.test.mjs b/scripts/mcp-instructions-snapshot.test.mjs index a3f72ced6..3613bd936 100644 --- a/scripts/mcp-instructions-snapshot.test.mjs +++ b/scripts/mcp-instructions-snapshot.test.mjs @@ -169,11 +169,16 @@ test("writes a stamped body without its footer, then is a no-op on the second ru assert.equal(await readFile(out, "utf8"), generated); }); -// A hand edit anywhere in the committed snapshot, header included, fails this offline: -// the file must be exactly what the generator renders from its own constants. -test("the committed snapshot is the generator's output for its own body", async () => { +// Reproduce the snapshot from its body and recorded source. --api-url also supports a +// local backend release fixture, which must not claim to have been served by production. +test("the committed snapshot is the generator's output for its body and source", async () => { // The generated file holds no types, so it loads as JavaScript on every supported Node. const committed = await readFile(OUTPUT_PATH, "utf8"); + const source = + /^\/\/ Source: GET (https?:\/\/[^\s]+)\/v1\/mcp\/instructions$/m.exec( + committed, + ); + assert.ok(source, "snapshot records the endpoint used by the generator"); const snapshot = await import( `data:text/javascript,${encodeURIComponent(committed)}` ); @@ -182,7 +187,7 @@ test("the committed snapshot is the generator's output for its own body", async body: snapshot.AUTHORING_INSTRUCTIONS, release: snapshot.AUTHORING_INSTRUCTIONS_RELEASE, digest: snapshot.AUTHORING_INSTRUCTIONS_DIGEST, - apiURL: "https://api.sapiom.ai", + apiURL: source[1], }), { filepath: OUTPUT_PATH }, ); From a0711e48c0085f2b326db79b843cac7437b3dcb9 Mon Sep 17 00:00:00 2001 From: Yash Date: Sun, 15 Nov 2026 05:07:09 +0000 Subject: [PATCH 3/4] fix(purchases): preserve uncertain updates and unfinished revisions --- packages/axios/src/failureMode.test.ts | 60 +++++++++++++++++++ packages/core/src/client/HttpClient.ts | 7 ++- packages/core/src/client/TransactionAPI.ts | 1 + .../src/client/TransactionAPI.update.test.ts | 32 +++++++++- packages/fetch/src/failureMode.test.ts | 58 ++++++++++++++++++ packages/fetch/src/fetch.ts | 19 +++--- packages/node-http/src/failureMode.test.ts | 60 +++++++++++++++++++ packages/node-http/src/node-http.ts | 51 ++++++++++------ 8 files changed, 258 insertions(+), 30 deletions(-) diff --git a/packages/axios/src/failureMode.test.ts b/packages/axios/src/failureMode.test.ts index 9609a7be7..70aea994f 100644 --- a/packages/axios/src/failureMode.test.ts +++ b/packages/axios/src/failureMode.test.ts @@ -25,6 +25,7 @@ describe("Axios failureMode", () => { create: jest.fn(), get: jest.fn(), reauthorizeWithPayment: jest.fn(), + complete: jest.fn().mockResolvedValue({}), list: jest.fn(), isAuthorized: jest.fn(), isCompleted: jest.fn(), @@ -41,6 +42,65 @@ describe("Axios failureMode", () => { mockAxios.restore(); }); + it.each([ + ["open", false], + ["open", true], + ["closed", false], + ["closed", true], + ] as const)( + "leaves a payment revision open (%s, polled: %s)", + async (failureMode, pending) => { + const revision = { + id: "tx-revise", + status: "needs_revision", + nextAction: { type: "revise", actor: "agent", reasons: [] }, + }; + mockTransactionAPI.create.mockResolvedValue({ + id: "tx-revise", + status: "authorized", + } as any); + mockTransactionAPI.reauthorizeWithPayment.mockResolvedValue( + pending + ? ({ id: "tx-revise", status: "pending" } as any) + : (revision as any), + ); + mockTransactionAPI.get + .mockResolvedValueOnce({ + id: "tx-revise", + status: "authorized", + requiresPayment: false, + } as any) + .mockResolvedValue(revision as any); + const paymentRequired = { + x402Version: 1, + accepts: [ + { + scheme: "exact", + network: "base", + maxAmountRequired: "1000000", + resource: "https://api.example.com/test", + payTo: "0x123", + asset: "0xUSDC", + }, + ], + }; + mockAxios.onGet("/test").reply(402, paymentRequired); + const client = withSapiom(axiosInstance, { + sapiomClient: mockSapiomClient, + failureMode, + polling: { pollInterval: 1 }, + }); + await expect(client.get("/test")).rejects.toBeInstanceOf( + TransactionRevisionRequiredError, + ); + expect(mockAxios.history.get).toHaveLength(1); + expect(mockTransactionAPI.reauthorizeWithPayment).toHaveBeenCalledTimes( + 1, + ); + expect(mockTransactionAPI.complete).not.toHaveBeenCalled(); + }, + ); + it.each(["open", "closed"] as const)( "blocks revision decisions in failureMode %s", async (failureMode) => { diff --git a/packages/core/src/client/HttpClient.ts b/packages/core/src/client/HttpClient.ts index 0c5708973..7dfdcbe08 100644 --- a/packages/core/src/client/HttpClient.ts +++ b/packages/core/src/client/HttpClient.ts @@ -19,6 +19,8 @@ export interface HttpRequestConfig { headers?: Record; /** Optional budget for this request only, including bounded server waits. */ timeoutMs?: number; + /** Disable automatic replay when an operation can have an uncertain remote outcome. */ + retry?: false; } /** @@ -140,7 +142,8 @@ export class HttpClient { const configWithHeaders = { ...config, headers }; let lastError: unknown; - for (let attempt = 0; attempt < this.retry.maxAttempts; attempt++) { + const maxAttempts = config.retry === false ? 1 : this.retry.maxAttempts; + for (let attempt = 0; attempt < maxAttempts; attempt++) { try { return await this.executeRequest(configWithHeaders); } catch (error) { @@ -148,7 +151,7 @@ export class HttpClient { if (!this.isRetryable(error)) { throw error; } - if (attempt < this.retry.maxAttempts - 1) { + if (attempt < maxAttempts - 1) { const base = this.retry.baseDelayMs * Math.pow(2, attempt); const delay = Math.random() * base; // full jitter: spreads retries across [0, base] await new Promise((resolve) => setTimeout(resolve, delay)); diff --git a/packages/core/src/client/TransactionAPI.ts b/packages/core/src/client/TransactionAPI.ts index b2cc29eca..833c3998c 100644 --- a/packages/core/src/client/TransactionAPI.ts +++ b/packages/core/src/client/TransactionAPI.ts @@ -47,6 +47,7 @@ export class TransactionAPI { method: "POST", url: `/transactions/${transactionId}/update`, body: data, + retry: false, headers: { "Idempotency-Key": options.idempotencyKey }, }); } diff --git a/packages/core/src/client/TransactionAPI.update.test.ts b/packages/core/src/client/TransactionAPI.update.test.ts index b7716eebc..b095fb0c5 100644 --- a/packages/core/src/client/TransactionAPI.update.test.ts +++ b/packages/core/src/client/TransactionAPI.update.test.ts @@ -1,5 +1,5 @@ import { TransactionAPI } from "./TransactionAPI.js"; -import type { HttpClient } from "./HttpClient.js"; +import { HttpClient } from "./HttpClient.js"; import type { BrowserPurchase, UpdatePurchaseRequest, @@ -34,6 +34,7 @@ describe("purchase updates", () => { method: "POST", url: "/transactions/tx/update", body: input, + retry: false, headers: { "Idempotency-Key": "change-1" }, }, ]), @@ -55,6 +56,35 @@ describe("purchase updates", () => { ).rejects.toBe(failure); }); + it.each(["browser", "ucp"])( + "never automatically replays an uncertain %s update", + async (source) => { + const fetch = jest + .spyOn(globalThis, "fetch") + .mockResolvedValue(new Response("{}", { status: 500 })); + const real = new TransactionAPI( + new HttpClient({ + baseURL: "https://api.example.com", + timeout: 1000, + headers: {}, + retry: { maxAttempts: 3, baseDelayMs: 0 }, + }), + ); + const body: UpdatePurchaseRequest = + source === "browser" + ? { version: "v1", purchase } + : { version: "v1", checkout: { line_items: [] } }; + try { + await expect( + real.update("tx", body, { idempotencyKey: "change" }), + ).rejects.toThrow(); + expect(fetch).toHaveBeenCalledTimes(1); + } finally { + fetch.mockRestore(); + } + }, + ); + it("forwards purchase creation's key in a header", async () => { await api.create({ purchase, diff --git a/packages/fetch/src/failureMode.test.ts b/packages/fetch/src/failureMode.test.ts index 1b8cd89b3..228d855af 100644 --- a/packages/fetch/src/failureMode.test.ts +++ b/packages/fetch/src/failureMode.test.ts @@ -23,6 +23,7 @@ describe("Fetch failureMode", () => { create: jest.fn(), get: jest.fn(), reauthorizeWithPayment: jest.fn(), + complete: jest.fn().mockResolvedValue({}), list: jest.fn(), isAuthorized: jest.fn(), isCompleted: jest.fn(), @@ -35,12 +36,69 @@ describe("Fetch failureMode", () => { } as any; fetchMock.removeRoutes(); + fetchMock.clearHistory(); }); afterAll(() => { fetchMock.unmockGlobal(); }); + it.each([ + ["open", false], + ["open", true], + ["closed", false], + ["closed", true], + ] as const)( + "leaves a payment revision open (%s, polled: %s)", + async (failureMode, pending) => { + const revision = { + id: "tx-revise", + status: "needs_revision", + nextAction: { type: "revise", actor: "agent", reasons: [] }, + }; + mockTransactionAPI.create.mockResolvedValue({ + id: "tx-revise", + status: "authorized", + } as any); + mockTransactionAPI.reauthorizeWithPayment.mockResolvedValue( + pending + ? ({ id: "tx-revise", status: "pending" } as any) + : (revision as any), + ); + mockTransactionAPI.get.mockResolvedValue(revision as any); + const paymentRequired = { + x402Version: 1, + accepts: [ + { + scheme: "exact", + network: "base", + maxAmountRequired: "1000000", + resource: "https://api.example.com/test", + payTo: "0x123", + asset: "0xUSDC", + }, + ], + }; + fetchMock.get("https://api.example.com/test", { + status: 402, + body: paymentRequired, + }); + const client = createFetch({ + sapiomClient: mockSapiomClient, + failureMode, + polling: { pollInterval: 1 }, + }); + await expect( + client("https://api.example.com/test"), + ).rejects.toBeInstanceOf(TransactionRevisionRequiredError); + expect(fetchMock.callHistory.calls()).toHaveLength(1); + expect(mockTransactionAPI.reauthorizeWithPayment).toHaveBeenCalledTimes( + 1, + ); + expect(mockTransactionAPI.complete).not.toHaveBeenCalled(); + }, + ); + it.each(["open", "closed"] as const)( "blocks revision decisions in failureMode %s", async (failureMode) => { diff --git a/packages/fetch/src/fetch.ts b/packages/fetch/src/fetch.ts index ea97ee485..e24f314c9 100644 --- a/packages/fetch/src/fetch.ts +++ b/packages/fetch/src/fetch.ts @@ -1,4 +1,4 @@ -import { SapiomClient } from "@sapiom/core"; +import { SapiomClient, TransactionRevisionRequiredError } from "@sapiom/core"; import { BaseSapiomIntegrationConfig, initializeSapiomClient, @@ -168,14 +168,15 @@ export function createFetch(config?: SapiomFetchConfig): typeof fetch { throw err; } finally { // Fire-and-forget: complete the transaction - handleCompletion( - request, - response, - error, - completionConfig, - startTime, - defaultMetadata, - ); + if (!(error instanceof TransactionRevisionRequiredError)) + handleCompletion( + request, + response, + error, + completionConfig, + startTime, + defaultMetadata, + ); } }; diff --git a/packages/node-http/src/failureMode.test.ts b/packages/node-http/src/failureMode.test.ts index 1d8e9e5ff..51cd79206 100644 --- a/packages/node-http/src/failureMode.test.ts +++ b/packages/node-http/src/failureMode.test.ts @@ -19,6 +19,7 @@ describe("Node-HTTP failureMode", () => { create: jest.fn(), get: jest.fn(), reauthorizeWithPayment: jest.fn(), + complete: jest.fn().mockResolvedValue({}), list: jest.fn(), isAuthorized: jest.fn(), isCompleted: jest.fn(), @@ -35,6 +36,65 @@ describe("Node-HTTP failureMode", () => { nock.cleanAll(); }); + it.each([ + ["open", false], + ["open", true], + ["closed", false], + ["closed", true], + ] as const)( + "leaves a payment revision open (%s, polled: %s)", + async (failureMode, pending) => { + const revision = { + id: "tx-revise", + status: "needs_revision", + nextAction: { type: "revise", actor: "agent", reasons: [] }, + }; + mockTransactionAPI.create.mockResolvedValue({ + id: "tx-revise", + status: "authorized", + } as any); + mockTransactionAPI.reauthorizeWithPayment.mockResolvedValue( + pending + ? ({ id: "tx-revise", status: "pending" } as any) + : (revision as any), + ); + mockTransactionAPI.get.mockResolvedValue(revision as any); + const paymentRequired = { + x402Version: 1, + accepts: [ + { + scheme: "exact", + network: "base", + maxAmountRequired: "1000000", + resource: "https://api.example.com/test", + payTo: "0x123", + asset: "0xUSDC", + }, + ], + }; + const merchant = nock("https://api.example.com") + .get("/test") + .reply(402, paymentRequired); + const client = createClient({ + sapiomClient: mockSapiomClient, + failureMode, + polling: { pollInterval: 1 }, + }); + await expect( + client.request({ + method: "GET", + url: "https://api.example.com/test", + headers: {}, + }), + ).rejects.toBeInstanceOf(TransactionRevisionRequiredError); + expect(merchant.isDone()).toBe(true); + expect(mockTransactionAPI.reauthorizeWithPayment).toHaveBeenCalledTimes( + 1, + ); + expect(mockTransactionAPI.complete).not.toHaveBeenCalled(); + }, + ); + it.each(["open", "closed"] as const)( "blocks revision decisions in failureMode %s", async (failureMode) => { diff --git a/packages/node-http/src/node-http.ts b/packages/node-http/src/node-http.ts index c1ce920b1..bde9e27b9 100644 --- a/packages/node-http/src/node-http.ts +++ b/packages/node-http/src/node-http.ts @@ -6,6 +6,7 @@ import { HttpRequest, HttpResponse, HttpError, + TransactionRevisionRequiredError, } from "@sapiom/core"; import { BaseSapiomIntegrationConfig, @@ -127,8 +128,16 @@ export function createClient( const failureMode = config?.failureMode ?? "open"; - const authConfig: AuthorizationConfig = { sapiomClient, failureMode, polling: config?.polling }; - const paymentConfig: PaymentConfig = { sapiomClient, failureMode, polling: config?.polling }; + const authConfig: AuthorizationConfig = { + sapiomClient, + failureMode, + polling: config?.polling, + }; + const paymentConfig: PaymentConfig = { + sapiomClient, + failureMode, + polling: config?.polling, + }; const completionConfig: CompletionConfig = { sapiomClient }; async function makeRequest( @@ -262,26 +271,32 @@ export function createClient( } catch (err) { error = err as Error | HttpError; if ((error as HttpError).response?.status === 402) { - response = await handlePayment( - modifiedRequest, - error as HttpError, - paymentConfig, - makeRequest, - defaultMetadata, - ); - error = null; // Clear error since payment succeeded - return response; + try { + response = await handlePayment( + modifiedRequest, + error as HttpError, + paymentConfig, + makeRequest, + defaultMetadata, + ); + error = null; // Clear error since payment succeeded + return response; + } catch (paymentError) { + error = paymentError as Error; + throw paymentError; + } } throw err; } finally { // Fire-and-forget: complete the transaction - handleCompletion( - modifiedRequest, - response, - error, - completionConfig, - startTime, - ); + if (!(error instanceof TransactionRevisionRequiredError)) + handleCompletion( + modifiedRequest, + response, + error, + completionConfig, + startTime, + ); } }, From f5e2c9c5dbe86415181082fcd3b88fe581d2dde7 Mon Sep 17 00:00:00 2001 From: Yash Date: Mon, 16 Nov 2026 20:07:29 +0000 Subject: [PATCH 4/4] fix(purchases): honor revision actions before HTTP retries --- .changeset/browser-purchase-revisions.md | 2 + packages/axios/src/failureMode.test.ts | 86 ++++++++++++++--- packages/axios/src/interceptors.ts | 29 ++++-- packages/core/README.md | 7 +- .../core/src/client/TransactionPoller.test.ts | 49 +++++----- packages/fetch/src/failureMode.test.ts | 93 ++++++++++++++++--- packages/fetch/src/interceptors.ts | 49 +++++++--- packages/node-http/src/failureMode.test.ts | 39 +++++--- packages/node-http/src/interceptors.ts | 26 ++++-- 9 files changed, 284 insertions(+), 96 deletions(-) diff --git a/.changeset/browser-purchase-revisions.md b/.changeset/browser-purchase-revisions.md index 132953dc4..a3813a20b 100644 --- a/.changeset/browser-purchase-revisions.md +++ b/.changeset/browser-purchase-revisions.md @@ -7,3 +7,5 @@ --- Add versioned browser purchase updates with stable idempotency keys. Polling returns `needs_revision` with actionable reasons, and HTTP adapters block that policy decision even in failureMode open. Updates require the backend browser revision release and do not edit the merchant's cart. + +HTTP adapters stop on either the revision status or the revise action, including Fetch's on-demand transaction creation after an HTTP 402, before further authorization or retry. diff --git a/packages/axios/src/failureMode.test.ts b/packages/axios/src/failureMode.test.ts index 70aea994f..8cfd71a4e 100644 --- a/packages/axios/src/failureMode.test.ts +++ b/packages/axios/src/failureMode.test.ts @@ -42,18 +42,71 @@ describe("Axios failureMode", () => { mockAxios.restore(); }); + it.each(["open", "closed"] as const)( + "does not reauthorize an existing payment revision in failureMode %s", + async (failureMode) => { + const revision = { + id: "tx-revise", + status: "authorized", + requiresPayment: false, + nextAction: { type: "revise", actor: "agent", reasons: [] }, + }; + mockTransactionAPI.create.mockResolvedValue({ + id: revision.id, + status: "authorized", + } as any); + mockTransactionAPI.get.mockResolvedValue(revision as any); + mockTransactionAPI.reauthorizeWithPayment.mockResolvedValue({ + id: revision.id, + status: "authorized", + payment: { authorizationPayload: { x402Version: 1 } }, + } as any); + mockAxios.onGet("/test").reply(402, { + x402Version: 1, + accepts: [ + { + scheme: "exact", + network: "base", + maxAmountRequired: "1000000", + resource: "https://api.example.com/test", + payTo: "0x123", + asset: "0xUSDC", + }, + ], + }); + const client = withSapiom(axiosInstance, { + sapiomClient: mockSapiomClient, + failureMode, + }); + + await expect(client.get("/test")).rejects.toMatchObject({ + name: "TransactionRevisionRequiredError", + transaction: revision, + }); + expect(mockAxios.history.get).toHaveLength(1); + expect(mockTransactionAPI.reauthorizeWithPayment).not.toHaveBeenCalled(); + expect(mockTransactionAPI.complete).not.toHaveBeenCalled(); + }, + ); + it.each([ - ["open", false], - ["open", true], - ["closed", false], - ["closed", true], + ["open", false, "needs_revision"], + ["open", true, "needs_revision"], + ["closed", false, "needs_revision"], + ["closed", true, "needs_revision"], + ["open", false, "authorized"], + ["open", true, "authorized"], + ["closed", false, "authorized"], + ["closed", true, "authorized"], ] as const)( - "leaves a payment revision open (%s, polled: %s)", - async (failureMode, pending) => { + "leaves a payment revision open (%s, polled: %s, status: %s)", + async (failureMode, pending, status) => { const revision = { id: "tx-revise", - status: "needs_revision", - nextAction: { type: "revise", actor: "agent", reasons: [] }, + status, + ...(status === "authorized" && { + nextAction: { type: "revise", actor: "agent", reasons: [] }, + }), }; mockTransactionAPI.create.mockResolvedValue({ id: "tx-revise", @@ -101,14 +154,21 @@ describe("Axios failureMode", () => { }, ); - it.each(["open", "closed"] as const)( - "blocks revision decisions in failureMode %s", - async (failureMode) => { + it.each([ + ["open", "needs_revision"], + ["closed", "needs_revision"], + ["open", "authorized"], + ["closed", "authorized"], + ] as const)( + "blocks revision decisions in failureMode %s with status %s", + async (failureMode, status) => { for (const mode of ["create", "existing", "poll"] as const) { const transaction = { id: "tx-revise", - status: "needs_revision", - nextAction: { type: "revise", actor: "agent", reasons: [] }, + status, + ...(status === "authorized" && { + nextAction: { type: "revise", actor: "agent", reasons: [] }, + }), }; mockTransactionAPI.create.mockResolvedValue( mode === "poll" diff --git a/packages/axios/src/interceptors.ts b/packages/axios/src/interceptors.ts index 40eaafce6..d2810c3ff 100644 --- a/packages/axios/src/interceptors.ts +++ b/packages/axios/src/interceptors.ts @@ -304,9 +304,13 @@ export function addAuthorizationInterceptor( return axiosConfig; } + if ( + transaction.status === TransactionStatus.NEEDS_REVISION || + transaction.nextAction?.type === "revise" + ) + throw new TransactionRevisionRequiredError(transaction); + switch (transaction.status) { - case TransactionStatus.NEEDS_REVISION: - throw new TransactionRevisionRequiredError(transaction); case TransactionStatus.AUTHORIZED: return axiosConfig; @@ -481,6 +485,12 @@ export function addAuthorizationInterceptor( return axiosConfig; } + if ( + transaction.status === TransactionStatus.NEEDS_REVISION || + transaction.nextAction?.type === "revise" + ) + throw new TransactionRevisionRequiredError(transaction); + if ( transaction.status === TransactionStatus.DENIED || transaction.status === TransactionStatus.CANCELLED @@ -488,9 +498,6 @@ export function addAuthorizationInterceptor( throw new AuthorizationDeniedError(transaction.id, endpoint); } - if (transaction.status === TransactionStatus.NEEDS_REVISION) - throw new TransactionRevisionRequiredError(transaction); - if (transaction.status === TransactionStatus.AUTHORIZED) { setHeader( axiosConfig.headers, @@ -631,7 +638,8 @@ export function addPaymentInterceptor( if ( !transaction.requiresPayment && - transaction.status === TransactionStatus.AUTHORIZED + transaction.status === TransactionStatus.AUTHORIZED && + transaction.nextAction?.type !== "revise" ) { transaction = await config.sapiomClient.transactions.reauthorizeWithPayment( @@ -699,6 +707,12 @@ export function addPaymentInterceptor( } } + if ( + transaction.status === TransactionStatus.NEEDS_REVISION || + transaction.nextAction?.type === "revise" + ) + throw new TransactionRevisionRequiredError(transaction); + if ( transaction.status === TransactionStatus.DENIED || transaction.status === TransactionStatus.CANCELLED @@ -708,9 +722,6 @@ export function addPaymentInterceptor( return Promise.reject(error); // Return original 402 error for completion } - if (transaction.status === TransactionStatus.NEEDS_REVISION) - throw new TransactionRevisionRequiredError(transaction); - if (transaction.status !== TransactionStatus.AUTHORIZED) { let result; try { diff --git a/packages/core/README.md b/packages/core/README.md index cb651b10a..8dce8eb95 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -207,12 +207,15 @@ or retry the **identical body, version and key**. A stale version requires a fre read and a new key. UCP uses `{ version, checkout }` on the same method; an uncertain merchant update requires reconciliation, not an automatic retry. -`needs_revision` / `nextAction.type: "revise"` includes the refusing rules in -`nextAction.reasons`. The poller returns this decision immediately. The authorizer +A response with `status: "needs_revision"` or `nextAction.type: "revise"` requires +revised terms, with refusing rules in `nextAction.reasons`. The poller returns +this decision immediately. The authorizer throws `TransactionRevisionRequiredError`, carrying the transaction and reasons (or returns the decision with `throwOnDenied: false`). Fetch, Axios and Node HTTP integrations also throw this error in both fail-open and fail-closed modes, before sending the protected request. They never edit or resubmit a purchase themselves. +The same check applies when Fetch creates a transaction after an HTTP 402: it +stops before reauthorizing or retrying that payment and keeps the purchase open. ##### Helper Methods diff --git a/packages/core/src/client/TransactionPoller.test.ts b/packages/core/src/client/TransactionPoller.test.ts index 72ff36455..c209bc597 100644 --- a/packages/core/src/client/TransactionPoller.test.ts +++ b/packages/core/src/client/TransactionPoller.test.ts @@ -2,29 +2,32 @@ import { TransactionPoller } from "./TransactionPoller.js"; import { SapiomClient } from "./SapiomClient.js"; describe("purchase polling", () => { - it("returns the revision decision and details immediately without another poll", async () => { - const transaction = { - id: "tx", - status: "needs_revision", - nextAction: { - type: "revise", - actor: "agent", - reasons: [ - { ruleId: "r", code: "rule_denied", message: "Over the limit" }, - ], - }, - }; - const get = jest.fn().mockResolvedValue(transaction); - const poller = new TransactionPoller( - { transactions: { get } } as unknown as SapiomClient, - {}, - ); - expect(await poller.waitForAuthorization("tx")).toEqual({ - status: "needs_revision", - transaction, - }); - expect(get).toHaveBeenCalledTimes(1); - }); + it.each(["needs_revision", "authorized"])( + "returns a revision immediately with status %s", + async (status) => { + const transaction = { + id: "tx", + status, + nextAction: { + type: "revise", + actor: "agent", + reasons: [ + { ruleId: "r", code: "rule_denied", message: "Over the limit" }, + ], + }, + }; + const get = jest.fn().mockResolvedValue(transaction); + const poller = new TransactionPoller( + { transactions: { get } } as unknown as SapiomClient, + {}, + ); + expect(await poller.waitForAuthorization("tx")).toEqual({ + status: "needs_revision", + transaction, + }); + expect(get).toHaveBeenCalledTimes(1); + }, + ); it("waits through an approval and returns authorization when it arrives", async () => { const authorized = { id: "tx", status: "authorized" }; diff --git a/packages/fetch/src/failureMode.test.ts b/packages/fetch/src/failureMode.test.ts index 228d855af..2e756e51b 100644 --- a/packages/fetch/src/failureMode.test.ts +++ b/packages/fetch/src/failureMode.test.ts @@ -43,18 +43,78 @@ describe("Fetch failureMode", () => { fetchMock.unmockGlobal(); }); + it.each(["needs_revision", "authorized"])( + "leaves an on-demand revision open with status %s", + async (status) => { + const revision = { + id: "tx-on-demand", + status, + ...(status === "authorized" && { + nextAction: { type: "revise", actor: "agent", reasons: [] }, + }), + }; + mockTransactionAPI.create + .mockRejectedValueOnce( + new Error("Preemptive authorization unavailable"), + ) + .mockResolvedValueOnce(revision as any); + mockTransactionAPI.reauthorizeWithPayment.mockResolvedValue({ + id: revision.id, + status: "authorized", + payment: { authorizationPayload: { x402Version: 1 } }, + } as any); + fetchMock.get("https://api.example.com/test", { + status: 402, + body: { + x402Version: 1, + accepts: [ + { + scheme: "exact", + network: "base", + maxAmountRequired: "1000000", + resource: "https://api.example.com/test", + payTo: "0x123", + asset: "0xUSDC", + }, + ], + }, + }); + const client = createFetch({ + sapiomClient: mockSapiomClient, + failureMode: "open", + }); + + await expect( + client("https://api.example.com/test"), + ).rejects.toMatchObject({ + name: "TransactionRevisionRequiredError", + transaction: revision, + }); + expect(mockTransactionAPI.create).toHaveBeenCalledTimes(2); + expect(fetchMock.callHistory.calls()).toHaveLength(1); + expect(mockTransactionAPI.reauthorizeWithPayment).not.toHaveBeenCalled(); + expect(mockTransactionAPI.complete).not.toHaveBeenCalled(); + }, + ); + it.each([ - ["open", false], - ["open", true], - ["closed", false], - ["closed", true], + ["open", false, "needs_revision"], + ["open", true, "needs_revision"], + ["closed", false, "needs_revision"], + ["closed", true, "needs_revision"], + ["open", false, "authorized"], + ["open", true, "authorized"], + ["closed", false, "authorized"], + ["closed", true, "authorized"], ] as const)( - "leaves a payment revision open (%s, polled: %s)", - async (failureMode, pending) => { + "leaves a payment revision open (%s, polled: %s, status: %s)", + async (failureMode, pending, status) => { const revision = { id: "tx-revise", - status: "needs_revision", - nextAction: { type: "revise", actor: "agent", reasons: [] }, + status, + ...(status === "authorized" && { + nextAction: { type: "revise", actor: "agent", reasons: [] }, + }), }; mockTransactionAPI.create.mockResolvedValue({ id: "tx-revise", @@ -99,14 +159,21 @@ describe("Fetch failureMode", () => { }, ); - it.each(["open", "closed"] as const)( - "blocks revision decisions in failureMode %s", - async (failureMode) => { + it.each([ + ["open", "needs_revision"], + ["closed", "needs_revision"], + ["open", "authorized"], + ["closed", "authorized"], + ] as const)( + "blocks revision decisions in failureMode %s with status %s", + async (failureMode, status) => { for (const mode of ["create", "existing", "poll"] as const) { const transaction = { id: "tx-revise", - status: "needs_revision", - nextAction: { type: "revise", actor: "agent", reasons: [] }, + status, + ...(status === "authorized" && { + nextAction: { type: "revise", actor: "agent", reasons: [] }, + }), }; mockTransactionAPI.create.mockResolvedValue( mode === "poll" diff --git a/packages/fetch/src/interceptors.ts b/packages/fetch/src/interceptors.ts index 154df4dfe..43de0a44d 100644 --- a/packages/fetch/src/interceptors.ts +++ b/packages/fetch/src/interceptors.ts @@ -136,9 +136,13 @@ export async function handleAuthorization( const endpoint = request.url; + if ( + transaction.status === TransactionStatus.NEEDS_REVISION || + transaction.nextAction?.type === "revise" + ) + throw new TransactionRevisionRequiredError(transaction); + switch (transaction.status) { - case TransactionStatus.NEEDS_REVISION: - throw new TransactionRevisionRequiredError(transaction); case TransactionStatus.AUTHORIZED: return request; @@ -266,9 +270,13 @@ export async function handleAuthorization( return request; } + if ( + transaction.status === TransactionStatus.NEEDS_REVISION || + transaction.nextAction?.type === "revise" + ) + throw new TransactionRevisionRequiredError(transaction); + switch (transaction.status) { - case TransactionStatus.NEEDS_REVISION: - throw new TransactionRevisionRequiredError(transaction); case TransactionStatus.AUTHORIZED: break; @@ -390,8 +398,9 @@ export async function handlePayment( const callSite = captureUserCallSite(); const parsedUrl = new URL(request.url); + let newTransaction; try { - const newTransaction = await config.sapiomClient.transactions.create({ + newTransaction = await config.sapiomClient.transactions.create({ requestFacts: { source: "http-client", version: "v1", @@ -434,15 +443,6 @@ export async function handlePayment( onDemandPayment: true, }, }); - existingTransactionId = newTransaction.id; - // Write the transaction ID back to the original request so - // handleCompletion (which reads X-Sapiom-Transaction-Id from - // request headers) can complete this on-demand transaction. - setHeader( - request.headers, - "X-Sapiom-Transaction-Id", - existingTransactionId, - ); } catch (error) { if (config.failureMode === "closed") throw error; console.error( @@ -451,6 +451,22 @@ export async function handlePayment( ); return response; } + + if ( + newTransaction.status === TransactionStatus.NEEDS_REVISION || + newTransaction.nextAction?.type === "revise" + ) + throw new TransactionRevisionRequiredError(newTransaction); + + existingTransactionId = newTransaction.id; + // Write the transaction ID back to the original request so + // handleCompletion (which reads X-Sapiom-Transaction-Id from + // request headers) can complete this on-demand transaction. + setHeader( + request.headers, + "X-Sapiom-Transaction-Id", + existingTransactionId, + ); } let transaction; @@ -480,7 +496,10 @@ export async function handlePayment( } // Poll for authorization if not already authorized - if (transaction.status === TransactionStatus.NEEDS_REVISION) + if ( + transaction.status === TransactionStatus.NEEDS_REVISION || + transaction.nextAction?.type === "revise" + ) throw new TransactionRevisionRequiredError(transaction); if (transaction.status !== TransactionStatus.AUTHORIZED) { const poller = new TransactionPoller(config.sapiomClient, polling); diff --git a/packages/node-http/src/failureMode.test.ts b/packages/node-http/src/failureMode.test.ts index 51cd79206..fd676746a 100644 --- a/packages/node-http/src/failureMode.test.ts +++ b/packages/node-http/src/failureMode.test.ts @@ -37,17 +37,23 @@ describe("Node-HTTP failureMode", () => { }); it.each([ - ["open", false], - ["open", true], - ["closed", false], - ["closed", true], + ["open", false, "needs_revision"], + ["open", true, "needs_revision"], + ["closed", false, "needs_revision"], + ["closed", true, "needs_revision"], + ["open", false, "authorized"], + ["open", true, "authorized"], + ["closed", false, "authorized"], + ["closed", true, "authorized"], ] as const)( - "leaves a payment revision open (%s, polled: %s)", - async (failureMode, pending) => { + "leaves a payment revision open (%s, polled: %s, status: %s)", + async (failureMode, pending, status) => { const revision = { id: "tx-revise", - status: "needs_revision", - nextAction: { type: "revise", actor: "agent", reasons: [] }, + status, + ...(status === "authorized" && { + nextAction: { type: "revise", actor: "agent", reasons: [] }, + }), }; mockTransactionAPI.create.mockResolvedValue({ id: "tx-revise", @@ -95,14 +101,21 @@ describe("Node-HTTP failureMode", () => { }, ); - it.each(["open", "closed"] as const)( - "blocks revision decisions in failureMode %s", - async (failureMode) => { + it.each([ + ["open", "needs_revision"], + ["closed", "needs_revision"], + ["open", "authorized"], + ["closed", "authorized"], + ] as const)( + "blocks revision decisions in failureMode %s with status %s", + async (failureMode, status) => { for (const mode of ["create", "existing", "poll"] as const) { const transaction = { id: "tx-revise", - status: "needs_revision", - nextAction: { type: "revise", actor: "agent", reasons: [] }, + status, + ...(status === "authorized" && { + nextAction: { type: "revise", actor: "agent", reasons: [] }, + }), }; mockTransactionAPI.create.mockResolvedValue( mode === "poll" diff --git a/packages/node-http/src/interceptors.ts b/packages/node-http/src/interceptors.ts index f90264bdc..d4b6810dc 100644 --- a/packages/node-http/src/interceptors.ts +++ b/packages/node-http/src/interceptors.ts @@ -141,9 +141,13 @@ export async function handleAuthorization( const endpoint = request.url; + if ( + transaction.status === TransactionStatus.NEEDS_REVISION || + transaction.nextAction?.type === "revise" + ) + throw new TransactionRevisionRequiredError(transaction); + switch (transaction.status) { - case TransactionStatus.NEEDS_REVISION: - throw new TransactionRevisionRequiredError(transaction); case TransactionStatus.AUTHORIZED: return request; @@ -268,6 +272,12 @@ export async function handleAuthorization( return request; } + if ( + transaction.status === TransactionStatus.NEEDS_REVISION || + transaction.nextAction?.type === "revise" + ) + throw new TransactionRevisionRequiredError(transaction); + if ( transaction.status === TransactionStatus.DENIED || transaction.status === TransactionStatus.CANCELLED @@ -275,9 +285,6 @@ export async function handleAuthorization( throw new AuthorizationDeniedError(transaction.id, endpoint); } - if (transaction.status === TransactionStatus.NEEDS_REVISION) - throw new TransactionRevisionRequiredError(transaction); - if (transaction.status === TransactionStatus.AUTHORIZED) { const modifiedRequest = { ...request }; modifiedRequest.headers = { ...request.headers }; @@ -388,6 +395,12 @@ export async function handlePayment( throw error; } + if ( + transaction.status === TransactionStatus.NEEDS_REVISION || + transaction.nextAction?.type === "revise" + ) + throw new TransactionRevisionRequiredError(transaction); + if ( transaction.status === TransactionStatus.DENIED || transaction.status === TransactionStatus.CANCELLED @@ -395,9 +408,6 @@ export async function handlePayment( throw error; } - if (transaction.status === TransactionStatus.NEEDS_REVISION) - throw new TransactionRevisionRequiredError(transaction); - if (transaction.status !== TransactionStatus.AUTHORIZED) { const polling = { ...DEFAULT_POLLING, ...config.polling }; let authResult;