Skip to content

Engine: Assistant

The shopper AI assistant: the agent loop on the Claude API, its read and confirmed-write tools, the sealed conversation, history compaction, budgets, tracing and the two route handlers. Server-only; the theme's app/api/assistant/** routes call these handlers. See the Shopper AI assistant guide.

Generated from packages/engine/src/assistant/: 26 files, 159 exported symbols. Signatures and types are shown as written in the source.

@magenxcommerce/engine/assistant/capabilities

packages/engine/src/assistant/capabilities.ts

What this store view has switched on in Magento, read at runtime.

The assistant should offer what the storefront offers: a guest ticket only when Magento allows guest tickets (the contact page shows the same form under the same flag), order cancellation only when Magento's cancellation feature is on. These are admin settings, so they are read from Magento rather than from the shop config, with the same public documents the storefront uses.

Cached per store view for CAPABILITY_TTL_MS. Tools and the system prompt are derived from the result, so they stay byte-stable (prompt cache, thinking binding) until an admin flips a setting; that one change is absorbed by the drop_block setting in model.ts.

CAPABILITY_TTL_MS const

const CAPABILITY_TTL_MS = 5 * 60 * 1000

CAPABILITY_RETRY_MS const

const CAPABILITY_RETRY_MS = 30 * 1000

After a failed read, how long the fallback is served before Magento is asked again. Without it every message during an outage would wait on two failing GraphQL calls.

CONSERVATIVE_CAPABILITIES const

const CONSERVATIVE_CAPABILITIES: Readonly<ShopCapabilities>

Used when Magento cannot be asked and nothing is cached: offer the least.

resetCapabilities function

resetCapabilities(): void

Test seam.

loadCapabilities function

loadCapabilities(storeCode: string, graphql: GraphqlRunner, now: number = Date.now()): Promise<ShopCapabilities>

The capabilities of one store view. graphql must run as a guest (no customer token): these are public settings and identical for every visitor. Never throws: on failure it serves the last known value, else the conservative default, for CAPABILITY_RETRY_MS before asking again.

@magenxcommerce/engine/assistant/compaction

packages/engine/src/assistant/compaction.ts

Keeps long conversations small without editing history.

Claude Haiku 5.5 binds every thinking block to the exact messages before it, so the history must only ever grow: cutting old messages off the front would invalidate the thinking blocks of every turn that is kept (a 400 on the next request). Instead, when a conversation gets long the whole history is summarised once and REPLACED: the next request starts a fresh history whose first context note carries the summary. No earlier thinking block is sent again, so the check has nothing to fail on.

The summary is written by the same model, from a plain-text transcript (shopper text, assistant text, tool calls and shortened results; never the thinking blocks), with instructions to keep what a shop conversation needs later: order, return and ticket numbers, products and SKUs, the open goal.

COMPACT_AFTER_BYTES const

const COMPACT_AFTER_BYTES = 150_000

Compact once the serialised history passes this size (sealed blob safety).

CLEARED_NOTE const

const CLEARED_NOTE

Note used when the summary could not be written.

SUMMARIZER_SYSTEM const

const SUMMARIZER_SYSTEM

shopperTurns function

shopperTurns(messages: Anthropic.MessageParam[]): number

Shopper messages in the history. Tool results and context notes are not counted: one shopper message adds 3 messages or more (message, context note, answer, plus 2 per tool step), so a raw message count would compact after a few turns and rebuild the prompt cache each time.

needsCompaction function

needsCompaction(messages: Anthropic.MessageParam[], maxTurns: number): boolean

transcript function

transcript(messages: Anthropic.MessageParam[]): string

A plain-text transcript of the history, without thinking blocks.

CompactionResult interface

MemberTypeDescription
summarystring | nullThe summary, or null when it could not be written (use CLEARED_NOTE).
tokensnumberTokens the summariser call spent.

summarize function

async summarize(messages: Anthropic.MessageParam[], model: ModelClient, modelName: string, signal: AbortSignal): Promise<CompactionResult>

Summarise messages with one model call. Never throws.

@magenxcommerce/engine/assistant/config

packages/engine/src/assistant/config.ts

Shop configuration for the shopper AI assistant.

Same injection pattern as the agentic surfaces (../agentic/_lib/config.ts): the engine never imports a shop's config file. The theme calls configureAssistant(magenxConfig) once, in the module the assistant route imports first, and the assistant reads it back at request time.

AssistantShopConfig interface

The slice of a shop's MagenxConfig the assistant reads; a full config fits.

MemberTypeDescription
storePick<StoreConfig, "baseUrl" | "storeCode">
storesReadonlyArray<StoreEntry>
brandPick<BrandConfig, "name">
assistant?AssistantSettings

DEFAULT_LIMITS const

const DEFAULT_LIMITS: Readonly<AssistantLimits>

ResolvedAssistant interface

Settings with every limit resolved.

MemberTypeDescription
settingsAssistantSettings
limitsAssistantLimits
shopAssistantShopConfig

configureAssistant function

configureAssistant(config: AssistantShopConfig): void

Inject the shop's configuration. Call once at server start-up.

assistantConfig function

assistantConfig(): ResolvedAssistant

The injected configuration. Throws when nothing was injected: answering with another shop's settings, or with none, would be worse than failing loudly.

assistantEnabled function

assistantEnabled(env: NodeJS.ProcessEnv = process.env): boolean

Whether the assistant may serve requests right now. Three switches, any of which turns it off: the shop config, the ASSISTANT_DISABLED=1 kill switch, and missing secrets (no API key or sealing key means no assistant, never a half-working one).

resetAssistantConfig function

resetAssistantConfig(): void

Test seam: forget the injected configuration.

@magenxcommerce/engine/assistant/confirm

packages/engine/src/assistant/confirm.ts

POST handler for the shopper's decision on a proposed action.

Request body (JSON): { "actionId": string, "decision": "confirm" | "decline", "locale": string, "session": string, "cartId"?: string }

Response (JSON): { status, message, refreshCart, session }

This is the ONLY path that executes a write. It runs the plan stored in the sealed session, never anything from the request body, and only when:

  • the session opens for the shopper making this request (same login, or the same guest), so a leaked session cannot be confirmed by someone else;
  • the action is still pending and younger than ACTION_TTL_MS;
  • this process has not already executed it (replay of an older sealed session would otherwise find the action "pending" again).

No model call happens here: the click is the shopper's decision, and the outcome is reported to the model at the start of the next turn.

GUEST_WRITES_PER_HOUR const

const GUEST_WRITES_PER_HOUR = 5

Guest writes (tickets, returns) per client per hour: each e-mails a typed address.

createAssistantConfirmHandler function

createAssistantConfirmHandler(options: AssistantHandlerOptions)

@magenxcommerce/engine/assistant/graphql

packages/engine/src/assistant/graphql.ts

Magento GraphQL access for assistant tools, as the shopper.

The shopper's own customer token (from the httpOnly cookie, resolved by the route) is the only credential this module ever sends. Magento therefore scopes every read to that customer exactly as it does for the account pages: the assistant cannot see another customer's order because the shopper cannot. No admin or integration token exists anywhere in the assistant.

Allowlist discipline (see ../agentic/ucp/_lib/magento.ts): tools use the engine's existing feature documents VERBATIM, so a misconfigured endpoint that routes server calls through the public persisted-query proxy still passes its hash check.

graphqlRunner function

graphqlRunner(identity: ShopperIdentity, signal: AbortSignal): GraphqlRunner

Build the runner tools use for one request.

@magenxcommerce/engine/assistant/handler

packages/engine/src/assistant/handler.ts

POST handler for the shopper assistant: one shopper message in, a stream of Server-Sent Events out.

Request body (JSON): { "message": string, "locale": string, "session"?: string, "humanToken"?: string }

Events: start, text, tool_start, tool_end, error, done (see types.ts). The last event is always done and carries the sealed session the widget sends back with the next message.

The theme wires request-specific pieces in (createAssistantHandler options): how to read the customer token cookie, how to verify a human check, and how to identify the client for rate limiting. Everything else lives here, so every shop runs one upgradeable copy of the harness.

AssistantHandlerOptions interface

MemberTypeDescription
customerTokenstring | null | Promise<string | null>The shopper's Magento customer token (validated), or null for a guest.
clientKeystringClient identity for rate limits, usually the client IP.
verifyHuman?Promise<boolean>Verify a human check (Turnstile) for a guest's first message. Omit to skip the check (development). Must fail closed.
model?ModelClientTest seam: replace the Claude client.
graphql?(identity: ShopperIdentity, signal: AbortSignal) => GraphqlRunnerSeam for tests and the eval suite: how tools reach Magento. Defaults to the real GraphQL runner with the shopper's own token.
env?NodeJS.ProcessEnvTest seam: environment.
sharedStore?SharedStore | nullState shared across storefront replicas (replay guard, rate limits). Defaults to the Redis/Valkey at ASSISTANT_REDIS_URL or REDIS_URL, and to per-process state when neither is set. Test seam: pass a fake, or null.

sharedStoreResolver function

sharedStoreResolver(options: AssistantHandlerOptions): () => SharedStore | null

The shared store for these options, resolved once per handler.

json function

json(status: number, body: unknown, headers: Record<string, string> = {}): Response

readJson function

async readJson(request: Request): Promise<Record<string, unknown>>

Read a size-capped JSON object body; throws AssistantError("bad_request").

parseCommon function

parseCommon(data: Record<string, unknown>)

Fields shared by both routes: locale, sealed session, guest cart id.

capabilitiesFor function

capabilitiesFor(options: Pick<AssistantHandlerOptions, "graphql">, identity: ShopperIdentity, signal: AbortSignal): Promise<ShopCapabilities>

What the shopper's store view has switched on in Magento (cached). Read as a guest: these are public settings.

identityFor function

async identityFor(request: Request, options: Pick<AssistantHandlerOptions, "customerToken">, locale: string, cartId: string | null): Promise<ShopperIdentity>

Who is asking, from the request only.

createAssistantHandler function

createAssistantHandler(options: AssistantHandlerOptions)

@magenxcommerce/engine/assistant/harness

packages/engine/src/assistant/harness.ts

The agent loop for one shopper message: model, tools, model, ... answer.

Invariants the loop keeps:

  • Budgets are checked before every model call: steps, tool calls, the conversation's token budget, and the turn's wall clock (via signal).
  • The history only ever gains COMPLETE turns. If a turn fails, times out or runs out of steps, the session keeps the history from before it (token spend is still counted). That keeps the message list valid for the API whatever went wrong, so one bad turn never poisons the conversation.
  • Tool calls from one model response run in parallel and their results go back in ONE user message, as the API expects.
  • The history is append-only (Claude Haiku 5.5 rejects replayed thinking whose earlier messages changed). A long history is summarised and replaced at the start of a turn, never trimmed: see compaction.ts.
  • Write tools only ever PROPOSE. A proposal is stored in the sealed session and announced to the widget as a confirm event; nothing changes until the shopper confirms through the confirm route.

TurnInput interface

MemberTypeDescription
stateSessionState
userTextstring
identityShopperIdentity
resolvedResolvedAssistant
systemstring
toolsAssistantTool<unknown>[]
modelModelClient
toolContextOmit<ToolContext, "counters" | "signal" | "conversationId">
emit(event: AssistantEvent) => void
signalAbortSignal
traceTurnTrace
debug?(entry: DebugEntry) => voidDevelopment only: receives per-step detail for the widget's debug panel.

TurnResult interface

MemberTypeDescription
stateSessionStateThe session to seal: updated on success, the previous history on failure.
usageTurnUsage
error?AssistantError

MAX_PROPOSALS_PER_TURN const

const MAX_PROPOSALS_PER_TURN = 2

Proposals one shopper message may produce: one decision at a time.

runTurn function

async runTurn(input: TurnInput): Promise<TurnResult>

@magenxcommerce/engine/assistant/model

packages/engine/src/assistant/model.ts

The one place the assistant talks to the Claude API.

A narrow interface (ModelClient) sits between the harness and the SDK so the harness can be tested with recorded responses and no network.

Thinking blocks and the history-editing check: Claude Haiku 5.5 binds each thinking block to the exact prefix that produced it (system prompt, tool list, every earlier message). The harness keeps conversations append-only (see compaction.ts), but a deploy that changes the system prompt, a policy text or the tool list still changes the prefix of every open chat. Without drop_block each of those chats would fail with a 400 on its next message; with it the API drops the stale thinking blocks and carries on. The number dropped is reported back so it shows up in traces.

THINKING_BINDING_BETA const

const THINKING_BINDING_BETA = "thinking-binding-controls-2026-08-01"

ModelRequest interface

MemberTypeDescription
modelstring
systemstring
toolsAnthropic.Tool[]
messagesAnthropic.MessageParam[]
maxTokensnumber
effort"low" | "medium" | "high"
cache?booleanWrite the prompt cache (default true). False for one-off calls whose prefix is never sent again, e.g. the compaction summary: a cache write costs more than plain input and would never be read back.

ModelResponse type

type ModelResponse = Anthropic.Message & { /** Thinking blocks the API dropped because their prefix no longer matched. */ droppedThinking?: number; }

A model response plus what the API changed in the input to serve it.

ModelClient interface

MemberTypeDescription
streamPromise<ModelResponse>Stream one response, calling onText for each text delta.

StreamParams type

type StreamParams = Parameters<Anthropic["beta"]["messages"]["stream"]>[0]

The body client.beta.messages.stream() accepts.

buildParams function

buildParams(request: ModelRequest): StreamParams

ModelFailure interface

What went wrong in a failed model call, for traces and logs.

MemberTypeDescription
typestring
status?numberHTTP status from the API, when it answered.
messagestring
requestId?string

describeModelError function

describeModelError(error: unknown): ModelFailure

droppedThinkingCount function

droppedThinkingCount(message: { input_transformations?: unknown }): number

Count the thinking blocks the API dropped from this request's input.

anthropicModelClient function

anthropicModelClient(client: Anthropic = new Anthropic()): ModelClient

@magenxcommerce/engine/assistant/policy/rate-limit

packages/engine/src/assistant/policy/rate-limit.ts

Sliding-window rate limiter, in process memory.

SharedRateLimiter below wraps it: with a shared store configured (see ./shared-store.ts) the count is kept there, across every replica, and this per-process limiter is only the fallback when the store cannot answer.

RateLimiter alone is per Node process: with several storefront replicas the effective limit is the configured one times the replica count. That is acceptable as a cost guard because nginx limit_req in front of the route is the shared limit; this one exists so a single process cannot be driven into unbounded model spend even when nginx is misconfigured.

RateLimiter class

SharedRateLimiter class

A limit counted across every storefront replica when a shared store is configured, and per process otherwise.

The shared count is a fixed window (one counter per window, expiring with it), so a client can reach up to twice the limit across a window boundary. That is fine for a cost guard; the per-process fallback stays sliding. When the store cannot answer, the per-process limiter decides: a store outage must not stop the assistant, and nginx still limits in front.

@magenxcommerce/engine/assistant/policy/redact

packages/engine/src/assistant/policy/redact.ts

Removes personal data from anything written to logs or traces.

Traces must be useful for debugging a conversation ("which tool ran, with which order number, how long did it take") without becoming a copy of the customer database. Fields that identify a person are replaced; e-mail addresses are masked wherever they appear in free text. name, subject, message and body cover guest ticket names and the free text of tickets and replies, which can hold anything the shopper typed.

REDACTED const

const REDACTED = "[redacted]"

redactText function

redactText(text: string): string

Mask e-mail addresses inside free text.

redact function

redact(value: unknown, depth = 0): unknown

Deep-copy a value with personal fields replaced and e-mails masked.

@magenxcommerce/engine/assistant/policy/sanitize

packages/engine/src/assistant/policy/sanitize.ts

Shapes tool results before the model reads them.

Tool results carry text written by other people: product descriptions, reviews, help desk replies. That text is data, never instructions, and the system prompt says so. This module makes it cheap and inert: HTML is reduced to plain text, long strings and lists are cut, and nesting is bounded, so a hostile product description can neither smuggle markup into the widget nor flood the context window.

SanitizeLimits interface

MemberTypeDescription
maxStringnumber
maxArraynumber
maxDepthnumber

DEFAULT_SANITIZE_LIMITS const

const DEFAULT_SANITIZE_LIMITS: SanitizeLimits

htmlToText function

htmlToText(html: string): string

Reduce an HTML fragment to collapsed plain text.

cut function

cut(value: string, max: number): string

value cut to max characters, with an ellipsis when it was longer.

sanitizeForModel function

sanitizeForModel(value: unknown, limits: SanitizeLimits = DEFAULT_SANITIZE_LIMITS, depth = 0): unknown

Deep-copy a value with HTML stripped from every string, strings and arrays cut, and nesting bounded. null/undefined object fields are dropped: they cost tokens and tell the model nothing.

@magenxcommerce/engine/assistant/policy/shared-store

packages/engine/src/assistant/policy/shared-store.ts

Assistant state that must hold across storefront replicas.

Two pieces of the assistant lived only in process memory and stop being correct once a second Next instance serves the same shop:

  • the confirm route's replay guard: a session replayed to the OTHER instance would run the same action twice (two tickets, two cancellations);
  • the rate limits: N instances allowed N times each limit.

With a Redis-compatible store configured (ASSISTANT_REDIS_URL, else REDIS_URL, the variable the ACP and UCP surfaces already read) both move there. Without one, the per-process behaviour stays, which is correct for a single instance.

Keys live under sf:assistant: so a store shared with Magento (another database of the same Valkey) never touches Magento's keyspace, and an ACL user limited to ~sf:* is enough.

ASSISTANT_REDIS_ENV const

const ASSISTANT_REDIS_ENV = ["ASSISTANT_REDIS_URL", "REDIS_URL"] as const

Env vars holding the store URL, most specific first.

SharedStore interface

MemberTypeDescription
claimOncePromise<boolean | null>Claim key for ttlMs, atomically across every instance. True the first time; false when it was already claimed; null when the store could not answer (the caller decides whether that fails open or closed).
hitPromise<number | null>Count one hit for key in a fixed window of windowMs. The count so far in this window, or null when the store could not answer.

sharedStoreUrl function

sharedStoreUrl(env: Readonly<Record<string, string | undefined>>): string | null

The store URL from the environment, or null when none is configured.

redisSharedStore function

redisSharedStore(url: string): SharedStore

A store backed by the Redis/Valkey at url.

sharedStoreFromEnv function

sharedStoreFromEnv(env: NodeJS.ProcessEnv): SharedStore | null

The configured store, or null for per-process state.

hashedClientKey function

hashedClientKey(clientKey: string): string

A rate-limit key that does not store the client's address in clear. The keys are short-lived, but a hash costs nothing.

resetSharedStoreClients function

async resetSharedStoreClients(): Promise<void>

Test seam: drop cached clients.

@magenxcommerce/engine/assistant/prompt

packages/engine/src/assistant/prompt.ts

The assistant's system prompt.

Built once per process from the shop config and never varied per request: it sits right after the tool definitions in the prompt-cache prefix, so any per-request byte here (a date, the shopper's name, a locale) would turn every call into a cache write. Per-request facts go in a short system message after the shopper's message instead (see contextNote).

MAX_INSTRUCTIONS_CHARS const

const MAX_INSTRUCTIONS_CHARS = 2000

Shop notes longer than this are cut: they sit in every request's prompt.

MAX_SHOP_PAGES const

const MAX_SHOP_PAGES = 20

Shop pages (settings.pages) used, and characters kept of each.

MAX_PAGE_CHARS const

const MAX_PAGE_CHARS = 200

buildSystemPrompt function

buildSystemPrompt({ settings, shop }: ResolvedAssistant, caps: ShopCapabilities = CONSERVATIVE_CAPABILITIES): string

contextNote function

contextNote(identity: ShopperIdentity, settled: SessionAction[] = [], summary?: string): string

Per-request facts, sent as a mid-conversation system message after the shopper's message so the cached system prompt stays byte-stable. Includes how earlier proposed actions ended, since the confirm route settles them outside any model turn.

@magenxcommerce/engine/assistant/session

packages/engine/src/assistant/session.ts

Conversation state, sealed and handed to the browser.

The assistant keeps no server-side store: every turn returns the whole conversation as one AES-256-GCM blob, and the widget sends it back with the next message. That keeps the standalone Next.js server stateless, and the seal gives three guarantees a plain client-held history would not:

  1. Integrity. The browser cannot forge an assistant or tool turn ("you already verified this order belongs to me"); a modified blob fails to open and the conversation starts fresh.
  2. Confidentiality. Tool results hold personal data (order addresses, ticket text). The blob is unreadable without the server key.
  3. Binding. The blob records whose conversation it is. Opened under a different shopper (another login, or a guest), it is discarded.

Replaying an older blob of one's own is possible and harmless, except for counters; the guest order lookup counter therefore also has a per-client limit in the route (see handler.ts).

SESSION_TTL_MS const

const SESSION_TTL_MS = 24 * 60 * 60 * 1000

A sealed conversation older than this is discarded.

MAX_SEALED_BYTES const

const MAX_SEALED_BYTES = 512 * 1024

Upper bound on a sealed blob the route will try to open.

ACTION_TTL_MS const

const ACTION_TTL_MS = 5 * 60 * 1000

How long a proposed action can be confirmed.

MAX_ACTIONS const

const MAX_ACTIONS = 10

Actions kept in the session (oldest settled ones are dropped first).

SessionAction interface

A write the model proposed. The plan holds the validated arguments; it is only ever executed by the confirm route, after the shopper pressed Confirm. Sealed with the rest of the session, so the browser can neither read nor alter it.

MemberTypeDescription
idstring
toolstring
summarystring
planunknown
createdAtnumber
status"pending" | "done" | "failed" | "declined" | "expired"
message?stringOutcome text, once settled.
reportedbooleanWhether the model has been told how it ended.

SessionState interface

MemberTypeDescription
vtypeof VERSION
cidstringConversation id: shown to the shopper and carried in traces.
substringWhose conversation this is: "guest" or a hash of the customer token.
humanbooleanA human check (Turnstile) passed for this conversation.
messagesAnthropic.MessageParam[]
tokensnumberInput + output tokens spent so far.
guestLookupsnumber
guestTicketsnumber
actionsSessionAction[]
summary?stringA summary of a compacted history that has not reached the model yet (the turn that made it failed). Delivered in the next turn's context note.
compactionsnumberHow many times this conversation was compacted.
createdAtnumber

sealKey function

sealKey(secret: string | undefined): Buffer

Derive the 32-byte key from ASSISTANT_SEAL_KEY.

subjectFor function

subjectFor(customerToken: string | null): string

The subject a conversation is bound to. Customers are identified by a hash of their token, never the token itself, so the blob does not carry a usable credential. A new sign-in (new token) therefore starts a new conversation.

newSession function

newSession(sub: string, now: number = Date.now()): SessionState

seal function

seal(state: SessionState, key: Buffer): string

open function

open(sealed: string | undefined | null, key: Buffer, sub: string, now: number = Date.now()): SessionState | null

Open a sealed blob for sub. Returns null — and the caller starts a new conversation — when the blob is missing, oversized, tampered with, expired, from an older format, or belongs to someone else. Never throws on bad input.

expireActions function

expireActions(actions: SessionAction[], now: number = Date.now()): SessionAction[]

Mark pending actions older than the TTL as expired.

capActions function

capActions(actions: SessionAction[]): SessionAction[]

Keep the newest MAX_ACTIONS, dropping settled-and-reported ones first.

@magenxcommerce/engine/assistant/tools/cart

packages/engine/src/assistant/tools/cart.ts

Cart tools: read the cart, and three confirmed writes (add, change quantity or remove, apply a coupon). Guests and customers.

Which cart: a customer's cart is resolved from their token on every call (Magento answers only for its owner). A guest's cart id comes from the widget, which reads it from the storefront's own cart state, never from the model. A plan captures the cart id at prepare time; execute re-checks that it still is the shopper's cart before writing.

resolveCartId function

async resolveCartId(ctx: ToolContext): Promise<string>

The shopper's cart id, from their token (customer) or the widget (guest).

getCart const

const getCart: ReadTool<Record<string, never>>

addToCart const

const addToCart: WriteTool<AddInput, AddInput & { cartId: string; name: string }>

updateCartItem const

const updateCartItem: WriteTool< { item_uid: string; quantity: number }, { cartId: string; item_uid: string; quantity: number; name: string } >

applyCoupon const

const applyCoupon: WriteTool<{ code: string }, { cartId: string; code: string }>

@magenxcommerce/engine/assistant/tools/catalog

packages/engine/src/assistant/tools/catalog.ts

Catalog tools: product search and product detail. Guest-accessible.

searchProducts const

const searchProducts: ReadTool<{ query: string; limit: number }>

getProduct const

const getProduct: ReadTool<{ url_key: string }>

listDeals const

const listDeals: ReadTool<{ type: DealType | null; limit: number }>

Products on an active deal campaign and gift deals (companion Magenx_DealGraphQl module), the same data as the /deals page. The gift list is optional: a store without it still answers with the price deals.

@magenxcommerce/engine/assistant/tools/guest-actions

packages/engine/src/assistant/tools/guest-actions.ts

Confirmed actions for shoppers who are NOT signed in, mirroring what the storefront already lets guests do: open a support ticket (the contact page's guest ticket form, when Magento allows guest tickets) and start a return for an order found by order number, checkout e-mail and billing last name (the guest order page).

Both make the store send e-mail to an address the visitor typed, which is why the storefront guards them with Turnstile. Here a guest has passed the human check before their first message, every action needs the shopper's Confirm, and execute takes a per-client allowance (ctx.allowGuestWrite). A guest ticket is also limited to one per conversation.

GUEST_TICKETS_PER_CONVERSATION const

const GUEST_TICKETS_PER_CONVERSATION = 1

Guest tickets one conversation may create.

guestReturnOptions const

const guestReturnOptions: ReadTool<GuestOrderRef>

createGuestReturn const

const createGuestReturn: WriteTool< GuestOrderRef & ReturnRequest, { order_number: string; email: string; reason_id: number; resolution_type_id: number; items: Array<{ order_item_id: number; qty_requested: number; condition_id?: number }>; } >

createGuestTicket const

const createGuestTicket: WriteTool<GuestTicket, GuestTicket>

@magenxcommerce/engine/assistant/tools/input

packages/engine/src/assistant/tools/input.ts

Input checks shared by the tool definitions.

Write tools are declared strict: true, so Claude's arguments already match their JSON Schema; read tools are not strict (registry.ts, toApiTools) and rely on these checks alone. For write tools they are the second line: they bound lengths and shapes the schema cannot express.

asObject function

asObject(raw: unknown): Record<string, unknown>

requiredString function

requiredString(obj: Record<string, unknown>, key: string, { max = 200, pattern }: { max?: number; pattern?: RegExp } = {}): string

optionalInt function

optionalInt(obj: Record<string, unknown>, key: string, { min, max, fallback }: { min: number; max: number; fallback: number }): number

REFERENCE const

const REFERENCE = /^[A-Za-z0-9_-]{1,40}$/

Order numbers, return ids and ticket codes: short, no spaces or markup.

URL_KEY const

const URL_KEY = /^[a-z0-9][a-z0-9-]{0,200}$/

Magento product URL keys.

EMAIL const

const EMAIL = /^[^\s@]{1,64}@[^\s@]{1,190}\.[^\s@]{2,}$/

@magenxcommerce/engine/assistant/tools/order-actions

packages/engine/src/assistant/tools/order-actions.ts

Confirmed order actions for signed-in shoppers: cancel an order, reorder.

ownOrder function

async ownOrder(number: string, ctx: ToolContext): Promise<OrderRef>

Load one of the shopper's own orders; Magento scopes it to the token.

cancelOrder const

const cancelOrder: WriteTool< { order_number: string; reason: string }, { orderId: string; number: string; reason: string } >

reorder const

const reorder: WriteTool<{ order_number: string }, { number: string }>

@magenxcommerce/engine/assistant/tools/orders

packages/engine/src/assistant/tools/orders.ts

Order tools: order history, order detail with shipment tracking, and the guest order lookup.

listMyOrders const

const listMyOrders: ReadTool<{ limit: number }>

getOrder const

const getOrder: ReadTool<{ order_number: string }>

guestOrderLookup const

const guestOrderLookup: ReadTool<{ order_number: string; email: string; lastname: string; }>

GuestOrderRef interface

MemberTypeDescription
order_numberstring
emailstring
lastnamestring

findGuestOrder function

async findGuestOrder<T>(ref: GuestOrderRef, ctx: ToolContext): Promise<T | null>

Find a guest order by number, checkout e-mail and billing last name, under the per-conversation and per-client lookup limits. Every guest tool that looks an order up goes through here, so none is a way around the limits. Null when nothing matches.

@magenxcommerce/engine/assistant/tools/project

packages/engine/src/assistant/tools/project.ts

Small projection helpers: turn Magento shapes into the few fields a shopper answer needs. Every token a tool returns is paid for on each later step of the turn, so projections are the assistant's main cost lever.

Money interface

MemberTypeDescription
value?number | null
currency?string | null

money function

money(m: Money | null | undefined): string | null

"49.90 EUR", or null when Magento sent no amount.

productPath function

productPath(locale: string, urlKey: string | null | undefined): string | null

Storefront path for a product, relative to the site (the widget links it).

NEWEST_FIRST const

const NEWEST_FIRST = { sort_field: "CREATED_AT", sort_direction: "DESC" }

List sort for order, return and ticket history.

day function

day(value: string | null | undefined): string | null

"2026-11-20 14:03:11" → "2026-11-20".

@magenxcommerce/engine/assistant/tools/registry

packages/engine/src/assistant/tools/registry.ts

The assistant's tool registry: which tools exist, how they are offered to the model, and how one call is executed.

Adding a tool = writing one AssistantTool in a domain file and listing it in ALL_TOOLS. registry.test.ts then checks its shape (strict schema, no identity fields, read/write kind) without anyone maintaining a second list.

ALL_TOOLS const

const ALL_TOOLS: ReadonlyArray<AssistantTool<unknown>>

TOOL_TIMEOUT_MS const

const TOOL_TIMEOUT_MS = 10_000

Per-tool wall clock. A slow Magento resolver must not eat the whole turn.

buildToolset function

buildToolset(disabledTools: ReadonlyArray<string> = [], caps?: ShopCapabilities): AssistantTool<unknown>[]

The tools one shop offers, in a stable order. Unknown names in disabledTools are an error, not a silent no-op: a typo there would leave a tool on that the operator believes is off. With caps, tools whose requires the store has switched off in Magento are left out too.

toApiTools function

toApiTools(tools: ReadonlyArray<AssistantTool<unknown>>): Anthropic.Tool[]

Tool definitions for the Messages API. Sorted and byte-stable, with a cache breakpoint on the last one, so the tool block is written to the prompt cache once and read back on every later call.

Only write tools are strict (schema-guaranteed arguments): their arguments become the plan the shopper confirms. The API compiles strict schemas into a grammar and accepts at most 20 strict tools, 24 optional parameters and 16 union-type parameters per request (HTTP 400 "Schema is too complex for compilation" beyond that); with every tool strict, 22 tools broke every request. Read tools are validated by their own parse() instead, as every tool is. registry.test.ts checks the limits.

ToolOutcome interface

MemberTypeDescription
okboolean
contentstringJSON text handed back to the model as the tool_result.
errorCode?string
proposal?Proposal & { tool: string }Set when a write tool proposed an action for the shopper to confirm.

AWAITING_CONFIRMATION const

const AWAITING_CONFIRMATION

What the model is told after proposing; it must not claim success.

SIGN_IN_EXPIRED const

const SIGN_IN_EXPIRED

What the model is told when the shopper's sign-in has lapsed.

executeAction function

async executeAction(tool: AssistantTool<unknown> | undefined, plan: unknown, ctx: ToolContext): Promise<ActionResult & { errorCode?: string }>

Execute a confirmed action's plan. Called by the confirm route only. Never throws: a failure becomes an unsuccessful result with a shopper-safe message.

executeTool function

async executeTool(tool: AssistantTool<unknown> | undefined, rawInput: unknown, ctx: ToolContext): Promise<ToolOutcome>

Run one tool call. Never throws: every failure becomes an error result the model can read and explain, with a code the trace records.

@magenxcommerce/engine/assistant/tools/support-actions

packages/engine/src/assistant/tools/support-actions.ts

Confirmed support actions for signed-in shoppers: start a return, open a support ticket (also the hand-off to a human), reply to a ticket. The return checks are shared with the guest return (guest-actions.ts).

Lookup interface

MemberTypeDescription
idnumber | string
labelstring

ReturnableOrder interface

MemberTypeDescription
idstring
numberstring
itemsArray<{ id: string; product_name: string; quantity_ordered: number; quantity_shipped?: number | null; }>

returnMetadata function

async returnMetadata(ctx: ToolContext)

returnableItems function

returnableItems(order: ReturnableOrder)

Items a shopper can return: shipped quantity, keyed by integer item id.

returnOptions const

const returnOptions: ReadTool<{ order_number: string }>

returnOptionsView function

returnOptionsView(order: ReturnableOrder, meta: { reasons: Lookup[]; resolution_types: Lookup[]; conditions: Lookup[] })

What the model needs to propose a return: items and the ids to choose from.

ReturnRequest interface

MemberTypeDescription
reason_idnumber
resolution_idnumber
itemsArray<{ order_item_id: number; quantity: number; condition_id: number | null }>

RETURN_REQUEST_PROPERTIES const

const RETURN_REQUEST_PROPERTIES

JSON Schema for the reason, resolution and items of a return request.

parseReturnRequest function

parseReturnRequest(obj: Record<string, unknown>): ReturnRequest

Parse the reason, resolution and items of a return request.

checkReturnRequest function

checkReturnRequest(order: ReturnableOrder, meta: { reasons: Lookup[]; resolution_types: Lookup[]; conditions: Lookup[] }, request: ReturnRequest, optionsTool: string)

Check a return request against the order and the store's return options. Returns the summary text and the items in the mutation's shape.

createReturn const

const createReturn: WriteTool< ReturnInput, { order_id: number; order_number: string; reason_id: number; resolution_type_id: number; items: Array<{ order_item_id: number; qty_requested: number; condition_id?: number }>; } >

createTicket const

const createTicket: WriteTool< { subject: string; message: string; order_number: string | null }, { subject: string; message: string; order_number: string | null } >

replyTicket const

const replyTicket: WriteTool<{ code: string; message: string }, { code: string; message: string }>

@magenxcommerce/engine/assistant/tools/support

packages/engine/src/assistant/tools/support.ts

Returns (RMA) and help desk tools, for signed-in shoppers.

listMyReturns const

const listMyReturns: ReadTool<{ limit: number }>

getReturn const

const getReturn: ReadTool<{ rma_id: number }>

listMyTickets const

const listMyTickets: ReadTool<{ limit: number }>

getTicket const

const getTicket: ReadTool<{ code: string }>

@magenxcommerce/engine/assistant/trace

packages/engine/src/assistant/trace.ts

Structured trace records for every assistant turn.

The engine has no OpenTelemetry dependency. It hands finished records to a sink; the theme's sink (apps/theme/src/lib/assistant.ts) turns them into OTel spans for OpenObserve, and the default sink writes one JSON line per record. Either way a support agent can go from the conversation id the shopper sees to every model call and tool call in that turn.

Records never contain message text or tool results. Tool arguments are redacted (policy/redact.ts) because they can hold an e-mail or a name.

TraceKind type

type TraceKind = "turn" | "model" | "tool"

TraceRecord interface

MemberTypeDescription
kindTraceKind
namestring"assistant.turn", "assistant.model", "assistant.tool.get_order", ...
conversationIdstring
turnIdstring
startTimenumber
durationMsnumber
okboolean
attributesRecord<string, string | number | boolean>

TraceSink interface

MemberTypeDescription
recordvoid

consoleSink const

const consoleSink: TraceSink

setTraceSink function

setTraceSink(next: TraceSink): void

Replace the sink (the theme installs its OTel sink at start-up).

TurnTrace class

Collects records for one turn and flushes them to the sink.

@magenxcommerce/engine/assistant/types

packages/engine/src/assistant/types.ts

Shared types for the shopper assistant harness.

ShopperIdentity interface

Who the shopper is, resolved by the route from the request — never from anything the model says. Tools read identity only from here, so no tool schema has a customer, cart or store field the model could fill in.

MemberTypeDescription
customerTokenstring | nullMagento customer token from the httpOnly cookie; null for guests.
storeCodestringMagento store-view code for this request.
localestringLocale of the storefront page the shopper is on.
cartIdstring | nullA guest's cart id, sent by the widget from the storefront's own cart state. Ignored for customers, whose cart is resolved from their token.

GraphqlRunner type

type GraphqlRunner = <T>( document: DocumentNode, variables: Record<string, unknown>, ) => Promise<T>

Runs one GraphQL document against Magento as the shopper.

ToolContext interface

What a tool may use while it runs.

MemberTypeDescription
identityShopperIdentity
graphqlGraphqlRunner
countersConversationCountersPer-conversation counters a tool may need (e.g. guest lookups).
limitsAssistantLimits
allowGuestLookup() => boolean | Promise<boolean>Per-client gate for guest order lookups, on top of the per-conversation counter: a replayed older session must not reset the attempt budget.
allowGuestWrite() => boolean | Promise<boolean>Per-client gate for guest writes that make the store send e-mail to an address the visitor typed (guest tickets, guest returns). Taken at execute.
baseUrlstringStore base URL, for building links back to the storefront.
conversationIdstringConversation id, for references staff can trace (e.g. in tickets).
signalAbortSignal
capsShopCapabilitiesWhat this store view has switched on (cached, see capabilities.ts).

ConversationCounters interface

MemberTypeDescription
guestLookupsnumber
guestTicketsnumberGuest tickets created in this conversation (each one e-mails the store's reply to a typed address).

ToolInputSchema interface

JSON Schema for a tool's input, as Claude expects it (strict mode).

MemberTypeDescription
type"object"
propertiesRecord<string, unknown>
requiredstring[]
additionalPropertiesfalse

ShopCapabilities interface

What this store view has switched on in Magento, read at runtime (capabilities.ts). Tools that need a feature declare it with requires, and are not offered when it is off.

MemberTypeDescription
helpdeskboolean
helpdeskGuestsboolean
helpdeskAccountsboolean
orderCancellationboolean
cancellationReasonsReadonlyArray<string>The store's order cancellation reasons, verbatim (empty when off).

ReadTool interface

A tool that only reads. It runs as soon as the model calls it.

MemberTypeDescription
kind"read"
runPromise<unknown>Do the work and return a small, projected JSON-serialisable result.

WriteTool interface

A tool that changes something (cart, order, return, ticket). It runs in two phases, and the model can only trigger the first:

  prepare  — when the model calls the tool. Reads only: checks the request
             against live data and returns a plain-language summary plus a
             plan (the exact, validated arguments). Nothing changes.
  execute  — only when the SHOPPER presses Confirm in the widget, through
             the confirm route. Runs the plan stored in the sealed session.

So no model output, however it was manipulated, can change anything the shopper did not see summarised and approve.

MemberTypeDescription
kind"write"
preparePromise<Proposal<Plan>>
executePromise<ActionResult>

Proposal interface

MemberTypeDescription
summarystringWhat will happen, shown to the shopper on the Confirm card.
planPlan

ActionResult interface

MemberTypeDescription
okboolean
messagestringShown to the shopper and reported to the model on the next turn.
refreshCart?booleanThe storefront cart changed; the widget should refresh it.

AssistantTool type

type AssistantTool = ReadTool<Input> | WriteTool<Input>

One assistant tool. Tools are declarative so that adding one is a single entry in a domain file, and so a static test can check every tool's shape.

AssistantErrorCode type

type AssistantErrorCode = | "tool_auth_required" | "tool_validation" | "tool_upstream" | "tool_limit" | "budget_exceeded" | "rate_limited" | "human_check_required" | "bad_request" | "model_error" | "disabled"

Error classes the harness maps to shopper-safe messages and trace labels.

AssistantError class

AssistantEvent type

type AssistantEvent = | { type: "start"; conversationId: string; turnId: string } | { type: "text"; delta: string } | { type: "tool_start"; id: string; name: string } | { type: "tool_end"; id: string; name: string; ok: boolean; ms: number } | { type: "confirm"; actionId: string; tool: string; summary: string } | { type: "error"; code: AssistantErrorCode; message: string } | { type: "debug"; entry: DebugEntry } | { type …

Events streamed to the widget over SSE.

DebugEntry type

type DebugEntry = | { kind: "model"; step: number; stopReason: string; ms: number; input: number; output: number; cacheRead: number; cacheWrite: number; droppedThinking: number; } | { kind: "tool"; name: string; input: unknown; ok: boolean; errorCode?: string; proposed: boolean; ms: number; bytes: number; } | { kind: "compaction"; messagesBefore: number; summaryChars: number; ok: boolean; ms: number } | { kind: "ac …

Per-step detail for the widget's debug panel. Sent only in development builds (NODE_ENV=development); tool inputs are redacted.

TurnUsage interface

MemberTypeDescription
inputTokensnumber
outputTokensnumber
cacheReadTokensnumber
cacheWriteTokensnumber
stepsnumber
toolCallsnumber