Engine: Agentic shared
Shared plumbing for the agentic-commerce APIs: platform authentication, idempotency keys, ETags, cart lines, order watching for webhooks and safe outbound fetches. Server-only.
Generated from packages/engine/src/agentic/_lib/: 8 files, 43 exported symbols. Signatures and types are shown as written in the source.
@magenxcommerce/engine/agentic/_lib/cart-lines
packages/engine/src/agentic/_lib/cart-lines.ts
Cart-line identity shared by the agent checkout surfaces (UCP, ACP).
Dependency-free on purpose: the pure session mappers import it, and they must stay loadable without Apollo or a Magento client.
CartLine type
type CartLine = NonNullable<CheckoutCart["items"]>[number]purchasedSku function
purchasedSku(item: CartLine): string | undefinedThe id a line actually sells as: its custom-option variant id when it carries custom-option choices, else a configurable's chosen CHILD SKU, else the product's own SKU. This is what both agent surfaces report as a line's item id, and what a platform sends back to refer to it — the same id the UCP catalog hands out for a variant. agent_variant_id and configured_variant are only present when the cart was loaded through the agent fetchCart; without them a line falls back to its product's SKU.
@magenxcommerce/engine/agentic/_lib/config
packages/engine/src/agentic/_lib/config.ts
Shop configuration for the agentic-commerce surfaces (UCP, ACP).
The engine never imports a shop's config file (see EngineConfigProvider for the React side). These server-side modules get it the same way, injected: the theme calls configureAgentic(magenxConfig) once — in the module every agentic route handler and the instrumentation hook import first — and the modules read it back through agenticConfig() at request time.
Only what the surfaces actually read is required: the store's public base URL and currency, the store-view table (locale ⇄ Magento store code), tax display, the footer navigation (the legal links agents must show), and the brand name for the business profile.
AgenticConfig interface
The slice of a shop's MagenxConfig the surfaces read; a full config fits.
| Member | Type | Description |
|---|---|---|
store | Pick<StoreConfig, "baseUrl" | "currency"> | |
stores | ReadonlyArray<StoreEntry> | |
tax | Pick<TaxConfig, "productPriceDisplay"> | |
navigation | Pick<NavigationConfig, "footerLinks"> | |
brand | Pick<BrandConfig, "name"> |
configureAgentic function
configureAgentic(config: AgenticConfig): voidInject the shop's configuration. Call once at server start-up.
agenticConfig function
agenticConfig(): AgenticConfigThe injected configuration. Throws when nothing was injected: a surface answering with another shop's — or an empty — base URL and store table would be worse than failing loudly.
@magenxcommerce/engine/agentic/_lib/etag
packages/engine/src/agentic/_lib/etag.ts
Validators for the public discovery documents (UCP /.well-known/ucp, ACP /.well-known/acp.json).
Both are generated per request, so the validator is a hash of the exact bytes served: it changes exactly when the document does.
etagFor function
etagFor(body: string): stringStrong ETag over body.
matchesEtag function
matchesEtag(ifNoneMatch: string | null, etag: string): booleanTrue when If-None-Match names etag (RFC 9110 §13.1.2: weak comparison, so a W/ prefix a compressing proxy added still matches; * matches any).
@magenxcommerce/engine/agentic/_lib/idempotency
packages/engine/src/agentic/_lib/idempotency.ts
Replay protection for the agentic surfaces' complete operation.
ONE store, two tenants. ACP and UCP each need the same thing — "this key was already used; here is what it produced" — and they used to each have their own copy of it. Only ACP's copy ever got a shared backing store, which made the two diverge on the one property that matters: UCP's per-process cache cannot stop a retry routed to a second replica from charging a card twice. Rather than duplicate the Redis half into UCP, both now call createIdempotencyStore with their own key prefix.
THREE LAYERS, because none alone is sufficient (the reasoning is unchanged from the modules this replaces):
- This store. Returns the ORIGINAL response for a repeated key, which is what the REST binding requires (store for 24h+, replay the result).
- Stripe's own
Idempotency-Key, forwarded on the PaymentMethod call (see ucp/_lib/stripe.ts), so even a store miss cannot mint two of those.
- Magento's quote lifecycle.
placeOrderdeactivates the quote, so a replay that reaches Magento fails with "The cart isn't active." instead of charging again. A worse RESPONSE than a replayed 200, but not a double charge.
An in-flight marker exists too: without it, two SIMULTANEOUS completes with the same key both miss the store and both charge, which layer 3 cannot catch because neither has placed an order yet.
The Redis path is used when a URL is configured and falls back to the in-memory one on any failure, so a Redis outage degrades to the old per-process behaviour rather than failing a charge.
ClaimResult type
type ClaimResult = | { status: "fresh" } | { status: "replayed"; value: T } | { status: "in_flight" }IdempotencyStore interface
| Member | Type | Description |
|---|---|---|
claim | Promise<ClaimResult<T>> | Claim a key before doing chargeable work. fresh — proceed, and call settle/release afterwards. replayed — return the stored response verbatim; do NOT charge again. in_flight — an identical request is mid-charge; the caller must refuse rather than race it. |
peek | Promise<T | null> | Read a SETTLED value without claiming the key. Null when the key is unknown or still in flight. Exists so a caller can answer a replay before doing any work that a completed attempt has already made impossible — the complete routes load the cart first, and placeOrder deactivates that cart, so without a peek the settled success value is unreachable forever after the one request that produced it. |
settle | Promise<void> | Record the outcome so a later replay of this key returns it. |
release | Promise<void> | Drop an in-flight claim that never produced a chargeable outcome. Only safe when nothing was charged — releasing after a charge would let a retry charge a second time. Callers release on validation failures, never after Stripe or placeOrder has been reached. |
reset | void | Test seam: drop accumulated state and any cached Redis client. |
IdempotencyStoreOptions interface
| Member | Type | Description |
|---|---|---|
prefix | string | Redis key prefix, e.g. acp:idem:. Keeps each surface's keys out of the other's — and out of Magento's own keyspace, since this is the SAME Redis the stack already runs for Magento's cache and sessions. |
urlEnvVars | readonly string[] | Env vars holding the Redis URL, most specific first — e.g. ["ACP_REDIS_URL", "REDIS_URL"]. None set ⇒ the in-memory path, so the surface still works with zero extra configuration. |
logLabel | string | Log prefix, e.g. acp. Never carries a key or a value. |
ttlMs? | number | How long a settled value is kept. Defaults to the 24h the REST binding requires for replay; longer-lived records (UCP order ownership) pass their own. |
createIdempotencyStore function
createIdempotencyStore(options: IdempotencyStoreOptions): IdempotencyStore@magenxcommerce/engine/agentic/_lib/line-items
packages/engine/src/agentic/_lib/line-items.ts
Reconciling a cart's line items against a platform's desired set.
Both agentic surfaces model update as a FULL REPLACEMENT: the desired list, when present, is the complete set, and lines the platform omits are removed. The algorithm for working out what that implies — which lines to remove, which quantities to change, which SKUs to add — is identical between them, and was duplicated.
What was NOT identical, and is why this module is deliberately vocabulary-free:
- Where the ids come from. UCP sends a line's cart-item uid as
idand its SKU asitem.id, two distinct fields. ACP sends oneidand expects the merchant to try it as either. Each surface normalizes its own shape intoDesiredLinebefore calling in here.
- How a problem is described. UCP's messages carry
{severity, path}with onecodeenum; ACP's carry{param}with a different, coarser one. SoreconcileLineItemsreports a REASON, not a message, and each surface renders it in its own protocol's terms.
Keeping the reconciliation pure also makes it directly testable, which it had never been: both copies were reachable only through an async function that needed a live Magento client.
DesiredLine interface
One entry of the platform's desired set, normalized.
| Member | Type | Description |
|---|---|---|
uid? | string | Existing cart-item uid, when the platform echoed one back. |
sku? | string | Catalog SKU, for matching an existing line or adding a new one. |
quantity | number |
ReconcileReason type
type ReconcileReason = "invalid_quantity" | "missing_id"LineItemPlan interface
| Member | Type | Description |
|---|---|---|
removals | string[] | Cart-item uids to remove, in cart order. |
updates | Array<{ cart_item_uid: string; quantity: number }> | |
additions | Array<{ sku: string; quantity: number }> |
ReconcileResult type
type ReconcileResult = | { ok: false; errors: Array<{ index: number; reason: ReconcileReason }> } | ({ ok: true } & LineItemPlan)reconcileLineItems function
reconcileLineItems(current: CartItems, desired: readonly DesiredLine[]): ReconcileResultWork out what the desired set implies for the current cart.
Pure: decides nothing about Magento, talks to nothing. Every problem found is reported against the index of the offending entry so the caller can build a path like $.line_items[2].quantity in its own notation.
All errors are collected and returned together, and a result carrying errors carries NO plan — a rejected line makes everything downstream (rates, totals) meaningless, so the caller reports and lets the platform retry rather than half-applying.
applyLineItemPlan function
async applyLineItemPlan(cartId: string, storeCode: string, plan: LineItemPlan): Promise<string[]>Execute a plan against Magento. Returns the raw user_errors strings, which the caller maps into its own message vocabulary.
ORDERING IS LOAD-BEARING. Removals run first because they free stock that an addition in the same request may need — a quantity move between two variants of the same product would otherwise fail on the addition.
One round trip per removal, sequentially, on purpose: Magento exposes no bulk remove, and these handlers are pinned to the documents the browser checkout already runs (see ucp/_lib/magento.ts's header comment on allowlist discipline). Not an oversight to batch away.
@magenxcommerce/engine/agentic/_lib/order-watch
packages/engine/src/agentic/_lib/order-watch.ts
Order watching for the agentic surfaces — the machinery behind order-event webhooks, shared by UCP (ucp/_lib/order-webhooks.ts) and ACP (acp/_lib/order-events.ts).
Neither protocol's events can come from Magento itself: it has no notion of a platform and no outbound hook for "this guest order was shipped/refunded/ canceled" that this headless stack could subscribe to without a custom PHP module. So the storefront watches the orders an agent placed: it re-reads each one on a cadence, hashes what it would send, and sends whenever the hash moves. What is read, rendered and sent is each protocol's business; WHEN to look, how to back off, where the watch list lives and how replicas avoid double-sending is this module's, and was duplicated nowhere.
complete ──► watch(order) (due now) ──┐
tick (every <interval> s) ◄───────────┘
└─ lock ─► due orders ─► process(order, state) ─► Step
└─ deliverSnapshot: changed? send : poll later
Delivery is at-least-once: a failed send backs off exponentially (1 min doubling, capped at 6 h) and the event id is derived from order + snapshot, so every retry of one state carries one id.
Storage rides Redis when configured (one sorted set of due times, one state key per order, one lock), otherwise process memory — correct on one replica, lost on restart, the same trade the idempotency store makes.
MAX_WATCH_MS const
const MAX_WATCH_MS = 90 * DAYHow long an order is watched after it was placed — returns and refunds.
NOT_FOUND_GRACE_MS const
const NOT_FOUND_GRACE_MS = HOURAn order Magento still cannot find this long after placement is dropped.
WatchState interface
Per-order delivery state.
| Member | Type | Description |
|---|---|---|
since | number | When the order started being watched (≈ placed). |
delivered? | string | Hash of the last snapshot the receiver acknowledged. |
pending? | { digest: string; observedAt: number } | The snapshot currently being delivered, and when it was first seen. |
attempts | number | Consecutive failed attempts for pending. |
Step type
type Step = | { next: number; state: WatchState } | { next: null; reason: string }What to do with an order after one look at it.
SendResult type
type SendResult = { ok: true } | { ok: false; reason: string }pollDelay function
pollDelay(ageMs: number): numberHow soon to look at an unchanged order again: often while it is fresh.
retryDelay function
retryDelay(attempts: number): numberWait before retry attempts (1-based) of a failed delivery.
webhookEventId function
webhookEventId(orderNumber: string, digest: string): stringStable per-state event id: every retry of one snapshot shares it.
snapshotDigest function
snapshotDigest(body: string): stringHex SHA-256 of a rendered body — the "did it change" fingerprint.
failStep function
failStep(logLabel: string, orderNumber: string, state: WatchState, now: number, reason: string): StepA failed look (not a failed send): retry with backoff.
deliverSnapshot function
async deliverSnapshot(logLabel: string, orderNumber: string, state: WatchState, now: number, digest: string, send: (observedAt: number) => Promise<SendResult>): Promise<Step>Deliver a rendered snapshot if it differs from what was last acknowledged.
send receives when this snapshot was first seen (stable across retries, e.g. for a timestamp header). A new state supersedes an undelivered older one: receivers want the current order, and every body is the full entity.
OrderWatcherOptions interface
| Member | Type | Description |
|---|---|---|
keyPrefix | string | Redis key prefix, e.g. ucp:wh: ⇒ ucp:wh:due, ucp:wh:state:<n>, ucp:wh:lock. |
logLabel | string | Log prefix, e.g. [ucp/webhooks]. |
redisEnvVars | string[] | Env vars naming the Redis URL, first set wins. |
intervalEnvVar | string | Env var holding the tick interval in seconds (default 60, min 15). |
isEnabled | boolean | Re-checked on every watch and tick, so config changes need no restart. |
process | Promise<Step> | Look at one due order once. Collaborators are the caller's. |
OrderWatcher interface
| Member | Type | Description |
|---|---|---|
watch | Promise<void> | Start watching a placed order and kick a tick. Never throws. |
runCycle | Promise<number> | One tick: process every due order under the lock. Returns how many. |
start | void | Start the background timer (idempotent). |
reset | void | Test seam: drop state, the cached store and the timer. |
createOrderWatcher function
createOrderWatcher(options: OrderWatcherOptions): OrderWatcher@magenxcommerce/engine/agentic/_lib/platform-auth
packages/engine/src/agentic/_lib/platform-auth.ts
Credential verification and quota accounting for the agentic surfaces.
WHAT THIS IS, AND DELIBERATELY IS NOT. ACP and UCP each authenticate a platform, and the mechanics of "is this string one of the configured secrets, and has this platform used up its minute" are identical between them. Everything around that is not: UCP also accepts X-API-Key, requires a UCP-Agent profile and carries it on the platform; ACP instead verifies an HMAC over the raw body and needs a signing secret and a Stripe handler configured before it will serve at all; and the two build different error bodies (ACP's carries a type field, UCP's does not).
So this module holds the shared mechanism only, and each surface's auth.ts keeps its own authenticate composing it. Threading per-surface flags through one "authenticate everything" function is how you end up with a file that no longer reads as obviously correct for either caller — which matters more here than anywhere else in the app, because for both surfaces this IS the entire authorization boundary. There is no session cookie and no Turnstile behind it.
The reason it is shared at all: the audit that produced it found a money bug (UCP's idempotency store stayed per-process while ACP's became Redis-backed) caused by exactly this kind of copy drifting after a fix landed in only one of them.
PlatformKey interface
| Member | Type | Description |
|---|---|---|
label | string | Operator-assigned label for logs/metrics (never a secret). |
secret | string |
loadPlatformKeys function
loadPlatformKeys(envVar: string): PlatformKey[]Parse a *_PLATFORM_KEYS env var — a comma-separated list of credentials, each either secret or label:secret. Labels are for logging only.
Unlabeled keys get a DISTINCT default (platform-0, platform-1, …): rate limiting buckets on the label, so a shared default silently made two credentials share one quota.
safeEqual function
safeEqual(a: string, b: string): booleanConstant-time string comparison that doesn't leak length via early return.
matchPlatformKey function
matchPlatformKey(credential: string, keys: readonly PlatformKey[]): string | nullThe label of the key this credential matches, or null.
Checks EVERY key with no early exit, so total work doesn't depend on which key matched or whether one did — a loop that returned on first match would hand back a timing oracle over the key ordering. That is the whole reason this is a function rather than an inlined .find().
readBearerCredential function
readBearerCredential(headers: Headers): string | nullExtract a credential from Authorization: Bearer <key>.
readIdempotencyKey function
readIdempotencyKey(headers: Headers): string | nullRead Idempotency-Key, normalized.
Shared because both surfaces use it as a cache key, and ACP additionally echoes it back in a response header. To be precise about what the charset filter does and does not buy: the runtime's own header parsing already rejects control characters on the way in, so this is not preventing a crash. It keeps the rest of what a header value may legally carry — spaces, quotes, commas, tabs, latin-1 — out of a Redis key and out of a reflected header.
Normalizing means two keys differing ONLY in stripped characters would collide, and the second would replay the first's response. Real keys are UUIDs or ULIDs, and the 255-character truncation below has had the identical property since the start, so this is the consistent treatment rather than a new hazard — but it is a property worth knowing about.
RateLimiter interface
| Member | Type | Description |
|---|---|---|
isOverLimit | boolean | True when this label has exceeded its quota for the current window. |
reset | void | Test seam: drop accumulated state. |
RateLimiterOptions interface
| Member | Type | Description |
|---|---|---|
envVar | string | Env var holding the per-minute limit, e.g. UCP_RATE_LIMIT. |
defaultLimit? | number | Used when the env var is unset or not a positive integer. |
windowMs? | number |
createRateLimiter function
createRateLimiter(options: RateLimiterOptions): RateLimiterA best-effort per-platform rate limiter.
In-memory and therefore PER INSTANCE — behind several replicas the effective limit is limit × replicas. It exists to blunt a runaway or hostile agent, not as a hard quota; a multi-instance deployment that needs a real ceiling should enforce it at nginx/Cloudflare in front of these routes.
Returns a BOOLEAN rather than a ready-made error: the 429 body differs between the surfaces (ACP's carries a type field) and belongs to each one's error taxonomy, not here.
@magenxcommerce/engine/agentic/_lib/public-fetch
packages/engine/src/agentic/_lib/public-fetch.ts
SSRF guard for server-side fetches of URLs that someone else chose.
Shared by the attachment download proxy (a URL Magento resolved) and the UCP order webhooks (a platform's profile URL and the webhook_url it declares). Both hand this process a URL from outside and ask it to connect there, so both must refuse loopback, private networks and the cloud metadata endpoint.
This is a resolve-then-check guard, not airtight against DNS rebinding (the caller's fetch() re-resolves the hostname a moment later) — a full fix would pin the connection to the address checked here, which fetch() doesn't support without a custom dispatcher. Callers pair it with redirect: "manual" so a response cannot hand back a redirect into a private address either. A deliberate, documented tradeoff rather than a gap nobody noticed.
isPrivateOrReservedAddress function
isPrivateOrReservedAddress(address: string): booleanTrue for loopback, private, link-local (including the 169.254.169.254 cloud metadata endpoint), carrier-grade NAT and other non-public IPv4/IPv6 ranges.
PublicFetchOptions interface
| Member | Type | Description |
|---|---|---|
httpsOnly? | boolean | Refuse http: too. Anything carrying signed or personal data should. |
assertPubliclyFetchable function
async assertPubliclyFetchable(rawUrl: string, options: PublicFetchOptions = {}): Promise<URL>Parse rawUrl and reject anything that isn't a plain http(s) URL resolving to a public address. Throws on refusal; the message never echoes the URL.