Engine: Agentic ACP
The Agentic Commerce Protocol implementation: discovery, checkout sessions, Stripe delegated payment and Shared Payment Tokens, and HMAC-signed order events. Server-only; the theme's app/api/acp/** routes re-export these handlers.
Generated from packages/engine/src/agentic/acp/: 22 files, 155 exported symbols. Signatures and types are shown as written in the source.
@magenxcommerce/engine/agentic/acp/_lib/address
packages/engine/src/agentic/acp/_lib/address.ts
ACP address → Magento CartAddressInput.
Region resolution (the numeric region_id Magento requires for any country with available_regions) is identical to UCP's problem, so it's reused verbatim from ucp/_lib/address.ts rather than reimplemented — see that module's header comment for the full story.
MagentoAddressInput interface
| Member | Type | Description |
|---|---|---|
firstname | string | |
lastname | string | |
street | string[] | |
city | string | |
region? | string | |
region_id? | number | |
postcode | string | |
country_code | string | |
telephone | string | |
save_in_address_book | boolean |
AddressResult type
type AddressResult = | { ok: true; address: MagentoAddressInput } | { ok: false; code: "missing" | "invalid"; message: string; param: string }AddressContact interface
Contact details that live beside the address in ACP, not inside it.
| Member | Type | Description |
|---|---|---|
name? | string | fulfillment_details.name (or the buyer's), used when address.name is blank. |
phone? | string | fulfillment_details.phone_number, else buyer.phone_number. |
buildMagentoAddress function
buildMagentoAddress(address: Partial<AcpAddress>, contact: AddressContact, countries: ReadonlyArray<CountryOption>, basePath = "$.fulfillment_details.address"): AddressResultBuild the Magento address input for an ACP address.
Magento requires a name and phone on every physical address. ACP's Address carries the name (address.name), but the phone number lives on fulfillment_details / buyer, so the caller passes it in. param paths are rooted at basePath ($.fulfillment_details.address or $.payment_data.billing_address).
@magenxcommerce/engine/agentic/acp/_lib/apply
packages/engine/src/agentic/acp/_lib/apply.ts
Apply a platform's checkout input to the underlying Magento quote.
line_items, when present, is the complete desired set — same full-replacement semantics as UCP's line_items (see ucp/_lib/apply.ts for the reasoning). Magento calls are reused verbatim from the UCP surface: they are the exact documents the browser checkout already runs, and this surface must stay on the same allowlist-safe set (see ucp/_lib/magento.ts's header comment).
ApplyResult interface
| Member | Type | Description |
|---|---|---|
messages | AcpMessage[] | |
rejectedDiscounts | AcpRejectedDiscount[] |
desiredItems function
desiredItems(input: AcpCheckoutInput): { items: AcpItem[]; field: string } | nullThe desired items: line_items (2025-12-12+), else the legacy items.
applyCheckoutInput function
async applyCheckoutInput(cartId: string, ctx: RequestContext, input: AcpCheckoutInput, cart: CheckoutCart | null): Promise<ApplyResult>Apply input to the cart. Returns business-level messages; Magento transport/GraphQL failures surface as MagentoCallError for the caller to map (they are business outcomes too, just discovered by a throw).
applyBillingAddress function
async applyBillingAddress(cartId: string, ctx: RequestContext, address: Partial<AcpAddress>, phone: string | undefined): Promise<AcpMessage | null>Apply payment_data.billing_address before charging. Null on success.
emptyCart function
async emptyCart(cartId: string, ctx: RequestContext, cart: CheckoutCart | null): Promise<void>Empty a cart — the closest Magento analogue to abandoning a session.
@magenxcommerce/engine/agentic/acp/_lib/auth
packages/engine/src/agentic/acp/_lib/auth.ts
Platform authentication for the ACP surface: bearer credential + request signature + rate limiting.
SECURITY: like UCP (see ../../ucp/_lib/auth.ts), this is the ENTIRE authorization boundary for these routes — no session cookie, no Turnstile. ACP layers two checks where UCP has one:
Authorization: Bearer <key>— identifies the platform. Same constant-time, fail-closed design as UCP's platform-key check, and now literally the same code (../../_lib/platform-auth).Signature+Timestamp— an HMAC-SHA256 over the raw request body, proving the body wasn't tampered with in transit and rejecting stale replays. The RFC (§2.1, §7) leaves the algorithm to be "published out-of-band" by the server; this one isHMAC-SHA256(${Timestamp}.${body}, secret)— the same construction the spec fixes for webhook signing — over the header value exactly as sent.Timestampis RFC 3339 per the 2026-04-17 OAS; unix seconds are still accepted. The digest may be sent hex, base64 or base64url (the RFC showsSignature: <base64url>; earlier integrations sent hex).
Both are required to configure before the surface serves any traffic — fail CLOSED, same as UCP: no ACP_PLATFORM_KEYS or no ACP_SIGNING_SECRET means every route (including anything that would reveal the surface exists) 404s.
The signature check and this surface's error shapes stay here; they are what ACP does not share with UCP.
Platform interface
| Member | Type | Description |
|---|---|---|
label | string | Operator-assigned label for logs/metrics (never a secret). |
AuthResult type
type AuthResult = | { ok: true; platform: Platform } | { ok: false; status: 401 | 400 | 404 | 429; type: "invalid_request" | "service_unavailable"; code: string; message: string; retryAfter?: number; }isAcpSurfaceEnabled function
isAcpSurfaceEnabled(): booleanTrue when the ACP surface is fully configured and may serve traffic.
Four conditions are the switch — same reasoning as isUcpSurfaceEnabled: a partially-configured surface that advertises itself but rejects every call is worse than one that doesn't exist. The fourth, a configured Stripe delegated-payment handler, is ACP-specific: unlike UCP, this protocol defines no escalation/handoff status — complete has no fallback but to charge a delegated token — so without it there is nothing this surface can legitimately do once a cart is ready. Reuses the exact Stripe env vars UCP's optional delegated-payment path already reads (STRIPE_SECRET_KEY, STRIPE_PUBLISHABLE_KEY, STRIPE_MERCHANT_ID) — same credentials, same charge path — but is gated on those alone, not on UCP_DELEGATED_PAYMENT, so ACP can be enabled independently of UCP.
computeSignature function
computeSignature(rawBody: string, timestamp: string, secret: string): stringCompute the spec's HMAC-SHA256 signature over timestamp.body.
Exported as a test seam — production callers reach it via verifyRequestSignature below.
parseTimestamp function
parseTimestamp(value: string): number | nullTimestamp as epoch seconds: RFC 3339 (the spec) or unix seconds (legacy).
authenticate function
authenticate(headers: Headers, rawBody: string): AuthResultAuthenticate an ACP request against its raw body.
rawBody must be the EXACT bytes the platform signed — read it once with request.text() before any JSON parsing, same discipline UCP uses for Content-Length.
checkRateLimit function
checkRateLimit(platformLabel: string): AuthResult | nullBest-effort per-platform rate limit.
See createRateLimiter for the per-instance caveat; the 429 body is built here because ACP's error shape carries a type and UCP's does not.
resetRateLimits function
resetRateLimits(): voidTest seam: drop accumulated rate-limit state.
@magenxcommerce/engine/agentic/acp/_lib/complete
packages/engine/src/agentic/acp/_lib/complete.ts
Complete Checkout — the decision layer for ACP's one and only payment path.
Same money-safety rules as ucp/_lib/complete.ts (read that module's header for the full reasoning): never report an order as paid without asking Stripe, an ambiguous placeOrder failure is never reported as a clean decline, and the charge claim is released only when nothing chargeable has happened yet. The request-level replay (same key + same body ⇒ the original response) is ../request-idempotency.ts; the claim here is the layer under it that keeps a payment from ever being attempted twice.
The Stripe call sequence is reused verbatim from UCP's delegated-payment path — tokenize → attach → placeOrder — because it is the same underlying Stripe/Magento integration either protocol charges through. Two kinds of delegated credential (payment_data.instrument.credential.token):
- A Stripe Shared Payment Token (
spt_…), what agent platforms send. Stripe charges it only aspayment_method_data[shared_payment_granted_token]on the PaymentIntent, so it is handed to Magento AS the Stripe payment method and the companion module Magenx_StripeSharedPaymentTokens (magenxcommerce/module-stripe-shared-payment-tokens) rewrites the module's own confirm call. Gated byACP_SHARED_PAYMENT_TOKENS=1, set once that module is installed and enabled: without it Magento would fail the token insideplaceOrder, where the outcome is ambiguous, rather than here, where nothing has been charged. - Anything else (a card token) is exchanged for a PaymentMethod the same way UCP's
stripe_payment_tokenis —POST /v1/payment_methodswithcard[token]=<token>.
CompleteOutcome interface
| Member | Type | Description |
|---|---|---|
status | AcpCheckoutStatus | |
messages | AcpMessage[] | |
order? | AcpOrder | |
continueUrl? | string | Where the buyer finishes what the agent cannot (a Stripe 3DS challenge). |
CompleteRecord interface
What one charge claim holds. Mirrors UCP's CompleteRecord.
| Member | Type | Description |
|---|---|---|
outcome | CompleteOutcome |
completeWithDelegatedPayment function
async completeWithDelegatedPayment(sessionId: string, ctx: RequestContext, paymentData: AcpPaymentData | undefined, idempotencyKey: string, cart: CheckoutCart, platform: string): Promise<CompleteOutcome>Charge the submitted token and place the order.
cart is the pre-complete quote (its buyer email and billing lastname are what Magento's guestOrder needs to read the order back for order events) and platform the credential label that placed it.
@magenxcommerce/engine/agentic/acp/_lib/constants
packages/engine/src/agentic/acp/_lib/constants.ts
Protocol constants for the ACP (Agentic Commerce Protocol) surface.
Spec: https://github.com/agentic-commerce-protocol/agentic-commerce-protocol (spec/2026-04-17, rfcs/rfc.agentic_checkout.md)
Mirrors ucp/_lib/constants.ts: off unless ACP_ENABLE=1 AND at least one platform credential is configured (see _lib/auth.ts). When off, every route 404s, so a store that has not opted in does not advertise an ACP surface at all.
ACP_VERSION const
const ACP_VERSION = "2026-04-17"Protocol version we implement (YYYY-MM-DD, per the spec's API-Version).
SUPPORTED_VERSIONS const
const SUPPORTED_VERSIONS: readonly string[]Every API-Version this surface accepts, oldest first (the discovery document's ordering). The wire shapes changed incompatibly at every release up to this one, so only the version actually implemented is listed.
MAX_BODY_BYTES const
const MAX_BODY_BYTES = 128 * 1024Request body cap. Agent traffic carries no session cookie; keep it small.
MAX_LINE_ITEMS const
const MAX_LINE_ITEMS = 100Upper bound on line items in one create/update call.
MAX_IDEMPOTENCY_KEY_LENGTH const
const MAX_IDEMPOTENCY_KEY_LENGTH = 255Spec cap on Idempotency-Key (RFC §6.1).
RETRY_AFTER_SECONDS const
const RETRY_AFTER_SECONDS = 1Seconds a client should wait before retrying a 409 / 429 (Retry-After).
RATE_LIMIT_RETRY_AFTER_SECONDS const
const RATE_LIMIT_RETRY_AFTER_SECONDS = 60CARD_HANDLER_ID const
const CARD_HANDLER_ID = "card_tokenized"The one payment handler this business declares (capabilities.payment.handlers[].id).
DISCOUNT_EXTENSION const
const DISCOUNT_EXTENSION = "discount"Discount extension identifier, as agents list it in capabilities.extensions.
DISCOUNT_EXTENSION_SPEC const
const DISCOUNT_EXTENSION_SPEC = "https://agenticcommerce.dev/specs/discount"DISCOUNT_EXTENSION_SCHEMA const
const DISCOUNT_EXTENSION_SCHEMA = "https://agenticcommerce.dev/schemas/discount.json"isAcpEnabled function
isAcpEnabled(): booleanTrue when the operator has switched the ACP surface on.
@magenxcommerce/engine/agentic/acp/_lib/context
packages/engine/src/agentic/acp/_lib/context.ts
Environment for an ACP request: which store view to talk to, the legal links the spec requires, and the human handoff URL.
Server-only (reads the injected shop configuration), same convention as ucp/_lib/context.ts. Locale resolution (resolveLocale) is reused from there verbatim — ACP signals language via the Accept-Language header instead of a body field, but the store-view lookup it drives is identical.
RequestContext interface
| Member | Type | Description |
|---|---|---|
locale | string | |
storeCode | string | |
baseUrl | string | |
currency | string | |
links | AcpLink[] |
primaryAcceptLanguage function
primaryAcceptLanguage(headers: Headers): string | undefinedFirst Accept-Language tag, or null. en-US, fr;q=0.8 → en-US.
Exported as a test seam; resolveRequestContext is the production caller.
buildLegalLinks function
buildLegalLinks(baseUrl: string, locale: string): AcpLink[]Build the mandatory links[], sourced from the same footer config as UCP.
resolveRequestContext function
resolveRequestContext(headers: Headers): RequestContextResolve everything a handler needs from the request's Accept-Language.
@magenxcommerce/engine/agentic/acp/_lib/discounts
packages/engine/src/agentic/acp/_lib/discounts.ts
The ACP discount extension (rfcs/rfc.discount_extension.md, 2026-01-30+) on Magento coupons and cart price rules.
In: discounts.codes (or the deprecated coupons), the COMPLETE desired set — it replaces earlier codes and [] clears them. Magento's storefront GraphQL holds one coupon per quote, so the first code is applied and every further one is rejected as discount_code_combination_disallowed rather than silently dropped.
Out: discounts.codes (what Magento kept), discounts.applied (one entry per cart rule Magento reports, with per-line allocations) and, on the response to the request that submitted them, discounts.rejected plus a matching warning message — a rejected code leaves the cart valid, so the rest of the update goes ahead.
The Magento side (what a rule's label and allocations mean) is UCP's, reused through its buildDiscounts; only the wire vocabulary differs.
DiscountOutcome interface
| Member | Type | Description |
|---|---|---|
messages | AcpMessageWarning[] | |
rejected | AcpRejectedDiscount[] |
applyDiscountCodes function
async applyDiscountCodes(cartId: string, ctx: RequestContext, submitted: unknown[]): Promise<DiscountOutcome>Make the cart's coupons match submitted. Magento transport failures throw MagentoCallError.
buildDiscounts function
buildDiscounts(cart: CheckoutCart, currency: string, rejected: AcpRejectedDiscount[] = []): AcpDiscounts | undefinedThe response discounts object, or undefined when there is nothing to report.
@magenxcommerce/engine/agentic/acp/_lib/errors
packages/engine/src/agentic/acp/_lib/errors.ts
Magento / Stripe error text → ACP messages[] entries.
ACP's MessageError.code enum is coarser than UCP's, and every message carries a content_type (always plain here — Magento's text is not CommonMark) plus an optional resolution. Same posture as ucp/_lib/errors.ts otherwise: PROTOCOL errors are thrown/returned as non-2xx; everything Magento reports about a cart is a BUSINESS outcome, mapped here rather than thrown.
errorMessage function
errorMessage(code: AcpMessageCode, content: string, param?: string, resolution: AcpResolution | undefined = RESOLUTION[code]): AcpMessageErrorA MessageError in the 2026-04-17 shape.
classifyMagentoError function
classifyMagentoError(message: string): AcpMessageCodetoAcpErrorMessages function
toAcpErrorMessages(messages: ReadonlyArray<string>, param?: string): AcpMessageError[]Build ACP error messages from raw Magento error strings.
classifyStripeError function
classifyStripeError(error: StripeCallError): AcpMessageCodestripeErrorMessage function
stripeErrorMessage(error: StripeCallError): AcpMessageError@magenxcommerce/engine/agentic/acp/_lib/handler
packages/engine/src/agentic/acp/_lib/handler.ts
Request/response pipeline shared by the five ACP REST operations.
Mirrors ucp/_lib/handler.ts's role — one place that decides auth, rate limiting, versioning and response shape so the five routes cannot drift. The one structural difference: ACP signs the raw request body, so guard must read it as text ONCE, verify the signature against those exact bytes, and only then parse JSON — UCP's guard can read straight to JSON because it has no body signature to protect.
GuardOk interface
| Member | Type | Description |
|---|---|---|
ok | true | |
requestId | string | null | |
idempotencyKey | string | null | |
meta | ResponseMeta | Echoed on every response this request produces. |
platform | Platform | |
endpoint | string | The request path — the endpoint half of the idempotency scope. |
body | Record<string, unknown> | |
ctx | RequestContext |
GuardResult type
type GuardResult = GuardOk | { ok: false; response: NextResponse }AcpFailure interface
| Member | Type | Description |
|---|---|---|
status | number | |
type | AcpErrorType | |
code | string | |
message | string |
guard function
async guard(request: Request, readBody = true): Promise<GuardResult>Authenticate and parse an ACP REST request.
readBody is false for GET, which carries no payload but is still signed (over an empty body) per the spec's header table.
SIZE IS CHECKED FIRST, twice, and for every method. This surface has to read the body before it can authenticate — the HMAC covers those exact bytes — so an unauthenticated caller decides how much we buffer and how much we hash. Content-Length is rejected up front, and the real byte count is re-checked after the read in case the header lied. UCP's readJsonBody does the same two-step for the same reason, but it has the luxury of authenticating first.
API-Version is validated after authentication, so an unauthenticated caller learns nothing from it the public discovery document doesn't say.
idempotent function
idempotent(guarded: GuardOk, handler: () => Promise<NextResponse>): Promise<NextResponse>Run a POST handler under the mandatory Idempotency-Key (RFC §6).
RespondOptions interface
| Member | Type | Description |
|---|---|---|
meta | ResponseMeta | |
httpStatus? | 200 | 201 | |
messages? | AcpMessage[] | |
rejectedDiscounts? | AcpRejectedDiscount[] | |
statusOverride? | AcpCheckoutStatus | |
order? | AcpOrder | |
continueUrl? | string |
renderSession function
renderSession(cart: CheckoutCart, ctx: RequestContext, options: Omit<RespondOptions, "meta" | "httpStatus">): AcpCheckoutSessionProject a cart onto the checkout session, without wrapping it in a response.
respond function
respond(cart: CheckoutCart, ctx: RequestContext, options: RespondOptions): NextResponseRender a cart as an ACP checkout session.
readClosedSession function
async readClosedSession(sessionId: string): Promise<AcpCheckoutSession | null>The stored rendering of a completed or canceled session, if any.
closeSession function
async closeSession(session: AcpCheckoutSession): Promise<void>Remember a session that reached a terminal state. Never throws.
fetchSessionCart function
async fetchSessionCart(sessionId: string, ctx: RequestContext): Promise<{ ok: true; cart: CheckoutCart } | { ok: false; failure: AcpFailure }>Load a session's cart, as a binding-agnostic result.
loadCart function
async loadCart(sessionId: string, ctx: RequestContext, meta: ResponseMeta): Promise<{ ok: true; cart: CheckoutCart } | { ok: false; response: NextResponse }>REST rendering of fetchSessionCart.
respondWithFailure function
respondWithFailure(error: unknown, ctx: RequestContext, meta: ResponseMeta, cart: CheckoutCart | null): NextResponseTurn a thrown Magento failure into a response.
badSessionId function
badSessionId(meta: ResponseMeta): NextResponseThe 400 for a malformed session id.
@magenxcommerce/engine/agentic/acp/_lib/http
packages/engine/src/agentic/acp/_lib/http.ts
Request/response plumbing shared by the five ACP REST operations.
Same failure split as UCP (see ../../ucp/_lib/http.ts): PROTOCOL errors are a non-2xx { type, code, message, param? } body (bad auth, malformed input); BUSINESS outcomes (out of stock, address rejected) are HTTP 200 with the full checkout session and a messages[] entry. The error shape itself is flat, per the Agentic Checkout RFC §3.1 — unlike UCP's envelope, there is no wrapper object — and its type is one of the spec's three.
AcpErrorType type
type AcpErrorType = "invalid_request" | "processing_error" | "service_unavailable"ResponseMeta interface
| Member | Type | Description |
|---|---|---|
requestId | string | null | |
idempotencyKey | string | null | |
headers? | Record<string, string> | Extra response headers (e.g. Retry-After, Idempotent-Replayed). |
readRequestId function
readRequestId(headers: Headers): string | nullRead the caller's Request-Id, sanitized for safe echoing into a header.
ProtocolErrorBody interface
| Member | Type | Description |
|---|---|---|
type | AcpErrorType | |
code | string | |
message | string | |
param? | string | |
supported_versions? | string[] |
protocolError function
protocolError(status: number, type: AcpErrorType, code: string, message: string, meta: ResponseMeta = { requestId: null, idempotencyKey: null }, extra: Pick<ProtocolErrorBody, "param" | "supported_versions"> = {}): NextResponseA protocol-level error response (non-2xx), in the spec's flat shape.
checkoutResponse function
checkoutResponse(session: AcpCheckoutSession, status: 200 | 201 = 200, meta: ResponseMeta = { requestId: null, idempotencyKey: null }): NextResponseA successful checkout session response.
replayResponse function
replayResponse(status: number, body: unknown, meta: ResponseMeta): NextResponseRebuild a stored response (an idempotent replay) with the same status.
checkApiVersion function
checkApiVersion(headers: Headers, meta: ResponseMeta): NextResponse | nullValidate the API-Version request header (RFC §2.1: the client MUST send it, the server MUST validate it). Rejections carry supported_versions so an agent can retry with one it knows. Null when the version is acceptable.
BodyResult type
type BodyResult = | { ok: true; value: unknown } | { ok: false; type: AcpErrorType; code: string; message: string }exceedsDeclaredLength function
exceedsDeclaredLength(headers: Headers): booleanTrue when a declared Content-Length already exceeds the cap.
exceedsBodyLength function
exceedsBodyLength(rawBody: string): booleanTrue when the bytes actually read exceed the cap (a lying Content-Length).
payloadTooLarge function
payloadTooLarge(meta: ResponseMeta): NextResponseThe 413-equivalent protocol error, shared by both size checks.
parseJsonBody function
parseJsonBody(rawBody: string): BodyResultParse a JSON body from raw text already read for signature verification.
Unlike UCP, the body must be read exactly once as text (to feed the HMAC check) before it can be parsed — so this takes the string, not a Request. The size cap is enforced by the caller BEFORE the HMAC runs (see guard), not here; this re-check is the last line of defence.
@magenxcommerce/engine/agentic/acp/_lib/idempotency
packages/engine/src/agentic/acp/_lib/idempotency.ts
Replay protection for ACP's POST operations, plus the per-session records that outlive a Magento quote.
The store itself is shared with UCP — see ../../_lib/idempotency.ts for the three-layer reasoning and the Redis/in-memory split. This module only binds it to ACP's keyspace: acp:idem: in the SAME Redis the stack already runs for Magento's cache and sessions (REDIS_URL, or ACP_REDIS_URL to point elsewhere). Set neither and it falls back to in-memory, so the surface works with zero extra config.
claim const
const claim = store.claimpeek const
const peek = store.peeksettle const
const settle = store.settlerelease const
const release = store.releaseorderRecords const
const orderRecordsWhich session placed which order, and the email + billing lastname Magento's guestOrder needs to read it back — written by complete, read by the order event dispatcher (./order-events.ts). A year, like UCP's: long enough for returns and refunds.
requestRecords const
const requestRecordsRequest-level replay records for every POST (RFC §6): the stored HTTP status and body per platform + endpoint + key. Kept apart from store (complete's charge-outcome claims) so the two can never read each other's values.
sessionRecords const
const sessionRecordsThe final rendering of a session that reached a terminal state (completed or canceled). A completed session's quote is deactivated by placeOrder, so without this a GET after complete could only 404; and cancel needs it to answer 405 for a session that is already closed. Thirty days: well past any agent conversation that could still ask about it.
resetIdempotency function
resetIdempotency(): voidTest seam: drop accumulated in-memory state and any cached Redis client.
@magenxcommerce/engine/agentic/acp/_lib/order-events
packages/engine/src/agentic/acp/_lib/order-events.ts
ACP order events — tell the agent platform when an order it placed changes.
Spec: Agentic Checkout RFC §2.3 ("Order lifecycle updates (order_create, order_update) MUST be emitted to the application's webhook receiver") and the Agentic Checkout Webhooks OAS (spec/2026-04-17/openapi/ openapi.agentic_checkout_webhook.yaml):
POST <receiver>
Merchant-Signature: t=<unix_seconds>,v1=<hex HMAC-SHA256(t + "." + body)>
{ "type": "order_create" | "order_update",
"data": <the full Order: type "order", id, checkout_session_id,
permalink_url, status, line_items, fulfillments,
adjustments, totals> }
data MUST be the full Order object, not a delta (./order.ts builds it from the Magento order; complete returns only the identifying subset, since the order has just been placed). The legacy refunds[] is gone; refunds travel as adjustments[] and an amount_refunded total.
Unlike UCP, the receiver is not discovered from a profile: the platform hands the merchant its URL and signing key out of band, so they are configuration (ACP_WEBHOOK_URL, ACP_WEBHOOK_SECRET). The header name is Merchant-Signature per the OAS; ACP_WEBHOOK_SIGNATURE_HEADER overrides it for a receiver that expects a merchant-named variant.
How changes are found is shared with UCP (../../_lib/order-watch.ts): complete records the order and starts watching it; a dispatcher re-reads it from Magento on a decaying cadence and sends whenever the rendered event data changes — order_create until the receiver has acknowledged one, then order_update. At-least-once, with Request-Id stable per state so a receiver can deduplicate retries.
AcpOrderEventData type
type AcpOrderEventData = AcpOrderAcpOrderEvent interface
| Member | Type | Description |
|---|---|---|
type | "order_create" | "order_update" | |
data | AcpOrderEventData |
AcpOrderRecord interface
What complete records about an order, so it can be read back later.
| Member | Type | Description |
|---|---|---|
platform | string | The credential label that placed it (logs only). |
checkoutSessionId | string | |
email | string | guestOrder needs both; never sent anywhere. |
lastname | string | |
storeCode | string | |
locale | string |
isAcpOrderEventsEnabled function
isAcpOrderEventsEnabled(): booleanTrue when order events may be sent: the ACP surface is on, the platform's receiver URL and signing key are configured, and ACP_ORDER_WEBHOOKS is not 0. Unsigned events would be rejected by the receiver, so no key ⇒ none.
acpOrderPermalink function
acpOrderPermalink(baseUrl: string, locale: string, orderNumber: string): stringBuyer-facing order URL — the same one complete returns as permalink_url.
recordAcpOrder function
async recordAcpOrder(orderNumber: string, record: AcpOrderRecord): Promise<void>Record a placed order and start watching it. Never throws: it runs after Magento placed (and possibly charged) the order, where failing the request would hide a real order from the platform. A lost record costs only the events for this one order, so it is logged loudly.
buildOrderEventData function
buildOrderEventData(order: MagentoOrder, record: AcpOrderRecord, baseUrl: string = agenticConfig().store.baseUrl): AcpOrderEventDataThe event data for an order — what is hashed to detect a change.
signOrderEvent function
signOrderEvent(body: string, secret: string, timestamp: number = Math.floor(Date.now() / 1000)): stringThe Merchant-Signature value: t=<unix_seconds>,v1=<hex>, where the HMAC covers t + "." + body — the exact bytes sent.
sendAcpOrderEvent function
async sendAcpOrderEvent(body: string, eventId: string): Promise<SendResult>POST one signed order event to the configured receiver. Never throws.
processAcpOrder function
async processAcpOrder(orderNumber: string, current: WatchState | null, now: number = Date.now()): Promise<Step>Look at one watched order once: read it, and deliver an event if its data changed. Exported as the unit the tests drive.
runAcpDispatchCycle function
runAcpDispatchCycle(now: number = Date.now()): Promise<number>One dispatcher tick (test seam and manual trigger).
startAcpOrderEventDispatcher function
startAcpOrderEventDispatcher(): voidStart the background dispatcher; called once from instrumentation.ts. The enabled check runs on every tick, so configuring the receiver at runtime starts delivery without a restart.
resetAcpOrderEvents function
resetAcpOrderEvents(): voidTest seam: drop watch state, the cached store and the timer.
@magenxcommerce/engine/agentic/acp/_lib/order
packages/engine/src/agentic/acp/_lib/order.ts
Magento order → ACP Order (spec 2026-04-17, rfcs/rfc.orders.md).
The same object is the order on a completed checkout session and the data of an order webhook event (the webhook OAS composes the checkout spec's Order via $ref). Pure, like session.ts: the caller supplies the Magento order and what complete recorded about it.
line_items ← order items, with the spec's 3-field quantity
(`ordered`, `current` = ordered − canceled − refunded,
`fulfilled` = shipped, capped at current) and the status
derived from those exactly as the schema defines it.
fulfillments ← one `shipping` fulfillment per Magento shipment.
adjustments ← one `refund` per credit memo (amount positive, tax incl.).
totals ← the order's totals, plus `amount_refunded` once refunded.
TIMESTAMPS: Magento's GraphQL exposes no creation time for shipments or credit memos — the earliest comment's timestamp is used when there is one, else the order date (see ucp/_lib/order.ts, which does the same).
AcpOrderStatus type
type AcpOrderStatus = | "created" | "confirmed" | "manual_review" | "processing" | "shipped" | "completed" | "canceled"Order-level status (Order.status). Values are the schema's defined set.
acpOrderStatus function
acpOrderStatus(order: MagentoOrder): AcpOrderStatusMagento's order status → Order.status.
guestOrder returns the status LABEL ("Pending", "On Hold", "Suspected Fraud"), so it is normalized before matching. Magento knows nothing about delivery, so a physical order stops at shipped; completed (all items received) is used only for a completed order with nothing to ship (virtual/downloadable). A status this doesn't recognise (a merchant's custom one) falls back to what the shipments say, else confirmed — the order exists and was paid at complete.
AcpOrderOptions interface
| Member | Type | Description |
|---|---|---|
checkoutSessionId | string | |
permalinkUrl | string | |
fallbackCurrency | string |
buildAcpOrder function
buildAcpOrder(order: MagentoOrder, options: AcpOrderOptions): AcpOrderProject a Magento order onto the ACP Order.
@magenxcommerce/engine/agentic/acp/_lib/payment
packages/engine/src/agentic/acp/_lib/payment.ts
What payment this business supports, and how a submitted payment_data credential is validated before it reaches Stripe.
Payment handlers framework (rfcs/rfc.payment_handlers.md, 2026-01-30+): the business declares capabilities.payment.handlers[] and the agent completes with payment_data: { handler_id, instrument: { type, credential: { type, token } } }.
ACP has exactly one path to a completed order here: a delegated card token charged through Stripe, declared as the standard dev.acp.tokenized.card handler. isAcpSurfaceEnabled already refuses to serve traffic unless Stripe is configured (see auth.ts), so the handler can always be built from it.
buildPaymentHandlers function
buildPaymentHandlers(): AcpPaymentHandler[]The payment handlers declared on every checkout session.
TokenResult type
type TokenResult = { ok: true; token: string } | { ok: false; message: AcpMessageError }selectPaymentToken function
selectPaymentToken(paymentData: AcpPaymentData | undefined): TokenResultValidate the submitted payment_data and extract its delegated token.
handler_id must name the handler this session declared — a credential for any other handler cannot be charged here. The pre-2026-01-30 shape ({ token, provider: "stripe" }) is still accepted: the 2026-04-17 OAS examples continue to send it.
@magenxcommerce/engine/agentic/acp/_lib/request-idempotency
packages/engine/src/agentic/acp/_lib/request-idempotency.ts
Mandatory request idempotency for every ACP POST (Agentic Checkout RFC §6).
- No
Idempotency-Key→ 400idempotency_key_required - Same key, original in flight → 409
idempotency_in_flight+ Retry-After - Same key, different body → 422
idempotency_conflict - Same key, same body → the ORIGINAL status and body, with
Idempotent-Replayed: true - A 5xx is never stored: a retry after one runs as a fresh request.
Keys are scoped to the authenticated platform + endpoint path (§6.1), so the same key on two endpoints, or from two platforms, never collides. Body equivalence is semantic JSON equality (§6.2): key order is ignored, null and absent stay distinct, array order matters — i.e. a SHA-256 over the body re-serialized with sorted keys.
This is the middleware layer §6.8 recommends. complete keeps its own charge-outcome claim underneath (./complete.ts): that one is what guarantees a payment is never attempted twice even if this record is lost.
bodyFingerprint function
bodyFingerprint(body: unknown): stringSHA-256 of the canonical body. Exported as a test seam.
IdempotentRequest interface
| Member | Type | Description |
|---|---|---|
platform | string | |
endpoint | string | The request path, e.g. /api/acp/checkout_sessions/abc/complete. |
key | string | null | |
body | unknown | |
meta | ResponseMeta |
withIdempotency function
async withIdempotency(request: IdempotentRequest, handler: () => Promise<NextResponse>): Promise<NextResponse>Run handler under the request's Idempotency-Key.
@magenxcommerce/engine/agentic/acp/_lib/session
packages/engine/src/agentic/acp/_lib/session.ts
Magento cart → ACP checkout session (spec 2026-04-17).
Same role as ucp/_lib/session.ts: one function that projects a Magento CheckoutCart onto the protocol's resource shape, plus the status derivation that tells a platform what to do next. Kept separate from UCP's version rather than parameterized over both, because the shapes genuinely diverge — ACP wants a per-line totals[] with display_text on every entry, fulfillment_details with a nested address, and a seller-side capabilities object on every response.
Deliberately pure and dependency-light, like its UCP counterpart — no @/ alias, no #config — so it stays directly unit-testable.
SessionOptions interface
| Member | Type | Description |
|---|---|---|
fallbackCurrency | string | |
links | AcpLink[] | Legal links. |
locale? | string | The response locale (BCP 47). |
messages? | AcpMessage[] | Extra messages to merge in (e.g. errors from the mutation that just ran). |
rejectedDiscounts? | AcpRejectedDiscount[] | Discount codes this request submitted that Magento refused. |
order? | AcpOrder | Order, set once one exists. |
statusOverride? | AcpCheckoutSession["status"] | Overrides the derived status (used by cancel/complete). |
continueUrl? | string | Where the buyer can finish what the agent cannot (e.g. a 3DS challenge). |
buildCapabilities function
buildCapabilities(): AcpCapabilitiesSeller capabilities. No agent-handled interventions: 3DS runs on Stripe's side.
deriveStatus function
deriveStatus(cart: CheckoutCart): { status: AcpCheckoutSession["status"]; messages: AcpMessage[] }Derive the ACP status from what Magento still needs.
complete only ever charges a delegated token, so the only question here is whether the cart is chargeable yet.
buildCheckoutSession function
buildCheckoutSession(cart: CheckoutCart, options: SessionOptions): AcpCheckoutSessionProject a Magento checkout cart onto the ACP checkout session resource.
@magenxcommerce/engine/agentic/acp/_lib/types
packages/engine/src/agentic/acp/_lib/types.ts
ACP wire types — the JSON shapes exchanged with an agent platform.
Mirrors spec/2026-04-17 of github.com/agentic-commerce-protocol/agentic-commerce-protocol (json-schema/schema.agentic_checkout.json and the matching OpenAPI). Only the subset this storefront produces or consumes is modelled; unknown fields sent by a platform are ignored rather than rejected, same posture as ucp/_lib/types.ts.
AcpCheckoutStatus type
type AcpCheckoutStatus = | "not_ready_for_payment" | "ready_for_payment" | "complete_in_progress" | "completed" | "canceled"AcpTotalType type
type AcpTotalType = | "items_base_amount" | "items_discount" | "subtotal" | "discount" | "fulfillment" | "tax" | "fee" | "total" | "amount_refunded"AcpTotal interface
| Member | Type | Description |
|---|---|---|
type | AcpTotalType | |
display_text | string | |
amount | number | |
description? | string |
AcpContentType type
type AcpContentType = "plain" | "markdown"AcpResolution type
type AcpResolution = "recoverable" | "requires_buyer_input" | "requires_buyer_review"AcpMessageCode type
type AcpMessageCode = | "missing" | "invalid" | "out_of_stock" | "payment_declined" | "requires_sign_in" | "requires_3ds" | "coupon_invalid" | "unsupported" | "not_found" | "conflict" | "intervention_required"MessageError.code values this surface emits. Unlisted spec codes are still strings.
AcpDiscountErrorCode type
type AcpDiscountErrorCode = | "discount_code_expired" | "discount_code_invalid" | "discount_code_already_applied" | "discount_code_combination_disallowed" | "discount_code_minimum_not_met" | "discount_code_user_not_logged_in" | "discount_code_user_ineligible" | "discount_code_usage_limit_reached"AcpMessageInfo interface
| Member | Type | Description |
|---|---|---|
type | "info" | |
content_type | AcpContentType | |
content | string | |
param? | string | |
resolution? | AcpResolution |
AcpMessageWarning interface
| Member | Type | Description |
|---|---|---|
type | "warning" | |
code | AcpDiscountErrorCode | (string & {}) | |
content_type | AcpContentType | |
content | string | |
param? | string | |
resolution? | AcpResolution |
AcpMessageError interface
| Member | Type | Description |
|---|---|---|
type | "error" | |
code | AcpMessageCode | (string & {}) | |
content_type | AcpContentType | |
content | string | |
param? | string | |
resolution? | AcpResolution |
AcpMessage type
type AcpMessage = AcpMessageInfo | AcpMessageWarning | AcpMessageErrorAcpLinkType type
type AcpLinkType = | "terms_of_use" | "privacy_policy" | "return_policy" | "shipping_policy" | "contact_us" | "about_us" | "faq" | "support"AcpLink interface
| Member | Type | Description |
|---|---|---|
type | AcpLinkType | |
url | string | |
title? | string |
AcpItem interface
Request-side item: what the agent wants to buy.
| Member | Type | Description |
|---|---|---|
id | string | |
quantity? | number | Not in the 2026-04-17 Item schema (which carries no quantity at all), but the RFC's own request examples send it, so it is honoured when present and defaults to 1 otherwise. |
name? | string | |
unit_amount? | number |
AcpCustomAttribute interface
| Member | Type | Description |
|---|---|---|
display_name | string | |
value | string |
AcpLineItem interface
| Member | Type | Description |
|---|---|---|
id | string | |
item | { id: string } | |
quantity | number | |
name? | string | |
images? | string[] | |
unit_amount? | number | |
sku? | string | |
custom_attributes? | AcpCustomAttribute[] | |
totals | AcpTotal[] |
AcpAddress interface
| Member | Type | Description |
|---|---|---|
name | string | |
line_one | string | |
line_two? | string | |
city | string | |
state | string | |
country | string | ISO 3166-1 alpha-2. |
postal_code | string |
AcpFulfillmentDetails interface
| Member | Type | Description |
|---|---|---|
name? | string | |
phone_number? | string | |
email? | string | |
address? | AcpAddress |
AcpBuyer interface
| Member | Type | Description |
|---|---|---|
first_name? | string | |
last_name? | string | |
full_name? | string | |
email? | string | |
phone_number? | string |
AcpFulfillmentOption interface
| Member | Type | Description |
|---|---|---|
type | "shipping" | |
id | string | |
title | string | |
description? | string | |
carrier? | string | |
totals | AcpTotal[] |
AcpSelectedFulfillmentOption interface
| Member | Type | Description |
|---|---|---|
type | "shipping" | "digital" | "pickup" | "local_delivery" | |
option_id | string | |
item_ids | string[] |
AcpPaymentHandler interface
| Member | Type | Description |
|---|---|---|
id | string | |
name | string | |
display_name? | string | |
version | string | |
spec | string | |
requires_delegate_payment | boolean | |
requires_pci_compliance | boolean | |
psp | string | |
config_schema | string | |
instrument_schemas | string[] | |
config | Record<string, unknown> | |
display_order? | number |
AcpIntervention type
type AcpIntervention = "3ds" | "biometric" | "address_verification"AcpInterventionCapabilities interface
| Member | Type | Description |
|---|---|---|
supported | AcpIntervention[] | |
required | Array<"3ds" | "biometric"> | |
enforcement | "always" | "conditional" | "optional" |
AcpExtensionDeclaration interface
| Member | Type | Description |
|---|---|---|
name | string | |
extends? | string[] | |
schema? | string | |
spec? | string |
AcpCapabilities interface
Seller-side capabilities on a checkout session response.
| Member | Type | Description |
|---|---|---|
payment | { handlers: AcpPaymentHandler[] } | |
interventions | AcpInterventionCapabilities | |
extensions? | AcpExtensionDeclaration[] |
AcpCoupon interface
| Member | Type | Description |
|---|---|---|
id | string | |
name | string |
AcpDiscountAllocation interface
| Member | Type | Description |
|---|---|---|
path | string | |
amount | number |
AcpAppliedDiscount interface
| Member | Type | Description |
|---|---|---|
id | string | |
code? | string | |
coupon | AcpCoupon | |
amount | number | |
automatic? | boolean | |
allocations? | AcpDiscountAllocation[] |
AcpRejectedDiscount interface
| Member | Type | Description |
|---|---|---|
code | string | |
reason | AcpDiscountErrorCode | |
message? | string |
AcpDiscounts interface
| Member | Type | Description |
|---|---|---|
codes | string[] | |
applied | AcpAppliedDiscount[] | |
rejected? | AcpRejectedDiscount[] |
AcpOrderLineItemQuantity interface
| Member | Type | Description |
|---|---|---|
ordered | number | |
current | number | |
fulfilled? | number |
AcpOrderLineItem interface
| Member | Type | Description |
|---|---|---|
id | string | |
title | string | |
product_id? | string | |
quantity | AcpOrderLineItemQuantity | |
unit_price? | number | |
subtotal? | number | |
status? | string |
AcpLineItemReference interface
| Member | Type | Description |
|---|---|---|
id | string | |
quantity | number |
AcpFulfillmentEvent interface
| Member | Type | Description |
|---|---|---|
id | string | |
type | string | |
occurred_at | string | |
description? | string |
AcpFulfillment interface
| Member | Type | Description |
|---|---|---|
id | string | |
type | "shipping" | "pickup" | "digital" | |
status? | string | |
line_items? | AcpLineItemReference[] | |
carrier? | string | |
tracking_number? | string | |
tracking_url? | string | |
description? | string | |
events? | AcpFulfillmentEvent[] |
AcpAdjustment interface
| Member | Type | Description |
|---|---|---|
id | string | |
type | string | |
occurred_at | string | |
status | string | |
line_items? | AcpLineItemReference[] | |
amount? | number | |
currency? | string | |
description? | string |
AcpOrder interface
| Member | Type | Description |
|---|---|---|
type? | "order" | |
id | string | |
checkout_session_id | string | |
permalink_url | string | |
order_number? | string | |
status? | string | |
line_items? | AcpOrderLineItem[] | |
fulfillments? | AcpFulfillment[] | |
adjustments? | AcpAdjustment[] | |
totals? | AcpTotal[] |
AcpCheckoutSession interface
| Member | Type | Description |
|---|---|---|
id | string | |
protocol | { version: string } | |
capabilities | AcpCapabilities | |
status | AcpCheckoutStatus | |
currency | string | ISO 4217, lower case, per the spec. |
locale? | string | |
buyer? | AcpBuyer | |
line_items | AcpLineItem[] | |
fulfillment_details? | AcpFulfillmentDetails | |
fulfillment_options | AcpFulfillmentOption[] | |
selected_fulfillment_options? | AcpSelectedFulfillmentOption[] | |
totals | AcpTotal[] | |
messages | AcpMessage[] | |
links | AcpLink[] | |
discounts? | AcpDiscounts | |
continue_url? | string | |
order? | AcpOrder |
AcpPaymentData interface
payment_data on complete (2026-01-30+ handler shape).
| Member | Type | Description |
|---|---|---|
handler_id? | string | |
instrument? | { type?: string; credential?: { type?: string; token?: string }; } | |
billing_address? | AcpAddress | |
token? | string | Pre-2026-01-30 shape ({ token, provider }), still shown in the OAS examples. |
provider? | string |
AcpCheckoutInput interface
Everything a route may need to read from the body, ALL OPTIONAL.
The wire contract is stricter than this (line_items is required on create, payment_data on complete), but the parsed body is untrusted JSON: a route casts into this lenient shape and checks presence itself. Same posture UCP's UcpCheckoutInput takes, for the same reason (see ucp/_lib/types.ts).
| Member | Type | Description |
|---|---|---|
line_items? | AcpItem[] | |
items? | AcpItem[] | Pre-2025-12-12 name for line_items, still used in the RFC's prose examples. |
buyer? | AcpBuyer | |
fulfillment_details? | AcpFulfillmentDetails | null | |
selected_fulfillment_options? | AcpSelectedFulfillmentOption[] | null | |
discounts? | { codes?: unknown } | null | |
coupons? | unknown | Deprecated alias of discounts.codes. |
capabilities? | { interventions?: { supported?: unknown }; extensions?: unknown } | |
payment_data? | AcpPaymentData | |
intent_trace? | { reason_code?: unknown } |
@magenxcommerce/engine/agentic/acp/checkout_sessions/[id]/cancel/route
packages/engine/src/agentic/acp/checkout_sessions/[id]/cancel/route.ts
POST /api/acp/checkout_sessions/{id}/cancel — ACP "Cancel Checkout Session".
Same modelling as ucp/checkout-sessions/{id}/cancel/route.ts: Magento has no "delete quote" mutation, so cancel empties the cart rather than deleting it, and records the session as canceled so a second cancel (or one after complete) gets the spec's 405 and a later GET still shows what was dropped.
The optional intent_trace (why the buyer walked away) is logged by its reason_code only — trace_summary is free text from the agent and stays out of the logs.
POST function
async POST(request: Request, { params }: RouteContext): Promise<NextResponse>@magenxcommerce/engine/agentic/acp/checkout_sessions/[id]/complete/route
packages/engine/src/agentic/acp/checkout_sessions/[id]/complete/route.ts
POST /api/acp/checkout_sessions/{id}/complete — ACP "Complete Checkout Session".
ACP has exactly one path to a completed order here: the platform's delegated credential (payment_data, for the card_tokenized handler) is charged through Stripe and the order placed. See _lib/complete.ts for the money-safety rules; the decision logic lives there so this route can't drift from it.
A retry with the same Idempotency-Key and body is answered from the request record (_lib/request-idempotency.ts) before any of this runs — which matters here more than anywhere, because placeOrder deactivates the quote and the cart could not be read again to rebuild the response.
POST function
async POST(request: Request, { params }: RouteContext): Promise<NextResponse>@magenxcommerce/engine/agentic/acp/checkout_sessions/[id]/route
packages/engine/src/agentic/acp/checkout_sessions/[id]/route.ts
GET /api/acp/checkout_sessions/{id} — ACP "Retrieve Checkout Session". POST /api/acp/checkout_sessions/{id} — ACP "Update Checkout Session".
Update, per the spec, is POST (not PUT). line_items, when present, is the complete desired set — see _lib/apply.ts.
GET function
async GET(request: Request, { params }: RouteContext): Promise<NextResponse>POST function
async POST(request: Request, { params }: RouteContext): Promise<NextResponse>@magenxcommerce/engine/agentic/acp/checkout_sessions/route
packages/engine/src/agentic/acp/checkout_sessions/route.ts
POST /api/acp/checkout_sessions — ACP "Create Checkout Session".
Opens a Magento guest quote and applies whatever the platform already knows (line items, buyer, fulfillment details, discount codes). The returned session id IS the masked quote id, mirroring ucp/checkout-sessions/route.ts — no session store is needed.
POST function
async POST(request: Request): Promise<NextResponse>@magenxcommerce/engine/agentic/acp/discovery/route
packages/engine/src/agentic/acp/discovery/route.ts
The ACP discovery document, served at /.well-known/acp.json (rewritten to this route in next.config.ts — an App Router segment cannot be named .well-known, the same constraint as the UCP profile).
Spec: https://github.com/agentic-commerce-protocol/agentic-commerce-protocol/blob/main/rfcs/rfc.discovery.md (DiscoveryResponse in spec/2026-04-17/json-schema/schema.agentic_checkout.json)
An agent fetches it before its first checkout call to learn the protocol version, where the API lives and what it serves. Without it the well-known path fell through to the storefront's locale router and came back as an HTML page with status 200, which an agent must treat as no document at all.
PUBLIC ON PURPOSE — discovery precedes authentication. It carries only the version, the API base URL, the discount extension and the store's currency and locales — no merchant identifier (the RFC's enumeration concern). It 404s when the surface is switched off, with the SAME predicate every ACP operation uses, so a store that has not opted in advertises nothing.
GET function
async GET(request?: Request): Promise<NextResponse>