> ## Documentation Index
> Fetch the complete documentation index at: https://docs.agentcard.com/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Agentcard is for companies whose agent buys for their users. Pick one path: the opencommerce SDK (@agent-cards/commerce-sdk) gives your agent one buy tool that finds the product, builds the cart, gets the user's approval and places the order at real stores; the Agentcard SDK (@agent-cards/sdk) pays with the user's own card when your agent already shops in a browser (Browser Use, Kernel, Browserbase, Anchor or Notte); the Purchase API (POST /buy) does the same purchase flow over plain HTTP in any language; Issuing gives the agent its own card.
> Start with `npx agent-cards init` in the app's folder (Node 22 or later). No invite is needed: it creates your Agentcard account if you don't have one, installs the opencommerce SDK and puts the credentials in the env file, kept out of git. From a coding agent, run `npx agent-cards init --print --categories all --implementation tool --wallet vault --skip-install` to get the setup steps to apply yourself.
> Vault is by invitation: request it at https://agentcard.com/get-started?utm_source=docs&utm_medium=llms&utm_campaign=agent-instructions. opencommerce needs no invite.
> Never ask a user for a card number, expiry date or CVV in chat. Send them the Vault link; they add their card on Agentcard's page, and the agent never sees the number.
> Every purchase is approved by the user, with a passkey or Face ID, or by an auto-approval they granted. An approval covers one merchant and one exact total. If the total changes, ask again. When a result says the user already said yes, don't ask again.
> `init` writes PRODUCTION credentials, which place real orders, so test in sandbox first. For opencommerce, run `npx agent-cards credentials --mode sandbox` and put the two lines it prints in place of the production ones in the env file `init` wrote, because that command only prints them; sandbox then runs the whole flow against real stores and stops before payment, so no order is placed and nobody is charged. For Vault and Issuing, sandbox credentials issue test cards that no real merchant accepts; try the checkout against shop.agentcard.sh, a test store on Stripe test mode.
> Tell the user an order is placed only after Agentcard reports it placed.
> Vault is free up to 5,000 users (https://agentcard.com/pricing). opencommerce takes 1% of each completed order. Full docs in one file: https://docs.agentcard.com/llms-full.txt

# AgentcardClient

> Holds your company's credentials, renews the access token, and sends each purchase call to Agentcard.

`AgentcardClient` is the class every buy tool and listener shares. The class exchanges your company's client credentials for an access token, renews that token a minute before it expires, and sends purchase turns, conversation reads and Vault link requests to Agentcard. Build one and keep it for the life of your process.

```ts agent.ts theme={null}
import { AgentcardClient } from '@agent-cards/commerce-sdk';

const agentcard = new AgentcardClient({
  clientId: process.env.AGENTCARD_CLIENT_ID ?? '',
  clientSecret: process.env.AGENTCARD_CLIENT_SECRET ?? '',
});

const turn = await agentcard.buy({ ask: 'two packs of AA batteries from Amazon', external_user_id: 'user-42', resume: true });
console.log(turn.status, turn.reply);
```

The call returns one `BuyTurn` for the shopper `user-42`. Most apps never call `buy` themselves: [`buyTool`](https://docs.agentcard.com/api-reference/commerce-sdk/buy-tool) calls it for the model. See [Quickstart](https://docs.agentcard.com/commerce-sdk/quickstart.md) for the full wiring.

## Create the client

```ts theme={null}
new AgentcardClient(options)
```

Pass your company's credentials, or one shopper's own access token, and not both. The constructor throws a `TypeError` for any other combination.

| Option | Type | Description |
| - | - | - |
| `clientId` | `string`, required with `clientSecret` | Your company's client ID. |
| `clientSecret` | `string`, required with `clientId` | Your company's client secret. |
| `accessToken` | `string`, required without credentials | One shopper's own Agentcard access token. The client then buys only for that shopper. |
| `baseUrl` | `string`, optional | Where Agentcard answers. Default `https://api.agentcard.sh`. A trailing slash is dropped. |
| `fetch` | `FetchLike`, optional | The fetch to call Agentcard with. Default: the global `fetch`. The constructor throws when the runtime has none. |

## Properties

| Property | Type | Description |
| - | - | - |
| `baseUrl` | `string` | The address the client calls. |
| `company` | `boolean` | `true` when the client buys for many shoppers with company credentials, `false` under one shopper's token. |
| `sandbox` | `boolean` or `null` | `true` for sandbox credentials and `false` for live credentials, as the token exchange said. `null` until the first exchange, and under a shopper's own token. |

## Methods

### `bearer`

```ts theme={null}
agentcard.bearer(refused?: string): Promise<string>
```

Returns the access token the client sends: the shopper's own, or your company's, exchanged once and renewed a minute before it expires. Pass a company token that Agentcard refused to get a new one. The first call also sets `sandbox`.

### `buy`

```ts theme={null}
agentcard.buy(body: BuyRequest, stream?: BuyStreamHandlers): Promise<BuyTurn>
```

Sends one purchase turn and waits up to `BUY_TURN_TIMEOUT_MS`. Name the shopper once, with `external_user_id` or `user_id`, when you use company credentials, and leave both out under a shopper's own token.

The client sends a turn once, because a turn runs against live stores. The client sends again only after a `401`, once, with a renewed token. After a `timeout`, `unreachable` or `invalid_answer` error, read the conversation with `conversation` before you send the turn again.

Pass `stream` with `onProgress`, `onCatalog`, `onAck` or any of them together to ask Agentcard to stream the turn. A stream that breaks after the turn started returns a `BuyTurn` with `error_code` set to `turn_timeout`, so the caller reads the conversation for what the turn left.

| Parameter | Type | Description |
| - | - | - |
| `body` | `BuyRequest`, required | The request. See [BuyRequest](#buyrequest). |
| `stream.onProgress` | `(progress: BuyProgress) => void`, optional | Hears each stage the turn reaches: `searching`, `building_cart`, `checking_out` or `working`. |
| `stream.onCatalog` | `(update: BuyCatalogUpdate) => void`, optional | Hears the products a search found the moment the search answers. The callback may return a promise, and the client waits for it before it returns the turn. |
| `stream.onAck` | `(update: { conversationId: string \| null, text: string }) => void`, optional | Hears the line Agentcard writes for a search, such as `one sec, checking target for la croix`, before the turn's products and messages, or never. The turn's `messages` never hold it. |
| `stream.onMerchantStatus` | `(update: BuyMerchantStatusUpdate) => void`, optional | Hears each store the turn's searches ask, the moment its status changes. The fields are the camel-case form of a [BuySearchStatus](#buysearchstatus) store, with `conversationId` and `searchId`. |

### `conversation`

```ts theme={null}
agentcard.conversation(conversationId: string, who?: Shopper): Promise<BuyConversation>
```

Reads where one conversation stands: whether a turn is running, the last checkout, the orders it placed and the carts on the table. Pass `who` with company credentials. The call waits up to 30 seconds.

### `order`

```ts theme={null}
agentcard.order(orderId: string, who?: Shopper, opts?: { merchant?: string }): Promise<BuyOrderStatus>
```

Reads where one placed order is now, by the `order_id` that `order.placed` carried. Pass `who` with company credentials. An order number two stores share throws `order_id_ambiguous`, with the stores in `error.body.merchants`; pass `opts.merchant` to say which. An order number Agentcard does not know throws `order_not_found`. See [Read where an order is](https://docs.agentcard.com/commerce-sdk/guides/approving-a-purchase.md#read-where-an-order-is).

### `listCarts`

```ts theme={null}
agentcard.listCarts(opts?: { threadId?: string; cursor?: string } & Shopper): Promise<{ carts: SavedCart[]; nextCursor: string | null }>
```

Reads the shopper's saved carts, newest first: what they carted at each store, the total each store last read, the chat each cart lives in (`threadId`), a short `label` and when it was started (`createdAt`). Pass `threadId` to read one chat's carts alone. A page holds up to 20 carts; pass `nextCursor` as `cursor` for the next page, until it reads `null`. See [Bring back a saved cart](https://docs.agentcard.com/opencommerce/guides/bringing-back-a-saved-cart.md).

### `getCart`

```ts theme={null}
agentcard.getCart(cartId: string, who?: Shopper): Promise<SavedCart>
```

Reads one saved cart by the id `listCarts` named. Another shopper's cart throws `cart_not_found`.

### `warmCart`

```ts theme={null}
agentcard.warmCart(cartId: string, who?: Shopper): Promise<void>
```

Tells Agentcard the shopper came back to a chat with this cart, before they open it. The slow stores start reading at once, so the `resumeCart` that follows answers sooner. The call answers at once.

### `resumeCart`

```ts theme={null}
agentcard.resumeCart(cartId: string, who?: Shopper, opts?: { replace?: Array<{ key: string; holds: string }> }): Promise<ResumedCart>
```

Reads every store's total in a saved cart again and answers the cart with what changed at each store. Show the changes before the shopper approves. The call can take up to 90 seconds. A cart that was placed, dropped or ran out of time throws `cart_ended`. A change that reads `needs_input` with reason `replace_account_cart` waits on the shopper's yes; call again with `replace: [{ key: change.key, holds: change.holds.token }]` once they give it.

### `bringCart`

```ts theme={null}
agentcard.bringCart(cartId: string, who?: Shopper, opts?: { threadId?: string }): Promise<ResumedCart>
```

Pulls a saved cart into the chat `threadId` names: the cart moves there, never copies, and every store's total is read again, as `resumeCart` reads it. Call it only when the shopper asks for a cart from another chat or picks one in your app. `moved` names the chat the cart came from, or reads `null` when it was already here. A cart whose payment is under way in another chat throws `cart_paying`, one that ended throws `cart_ended`, and one whose retail store, DoorDash or travel seller already has a cart of its own in this chat, such as a second Amazon cart, throws `store_cart_here`. See [Pull a cart into this chat](https://docs.agentcard.com/opencommerce/guides/bringing-back-a-saved-cart.md#pull-a-cart-into-this-chat).

### `resumeCartAsText`

```ts theme={null}
agentcard.resumeCartAsText(cartId: string, who: Shopper, send: (text: string) => void | Promise<void>): Promise<ResumedCart>
```

Brings a saved cart back in a chat that shows text alone. `send` gets what the shopper saved at once, and what each store reads today once the resume answers. Answers the resume, which you pass to `savedCartSettled` for each `cart.*` event that follows.

### `setCartQuantity`

```ts theme={null}
agentcard.setCartQuantity(cartId: string, lineKey: string, edit: { version: number; item?: number; quantity: number }, who?: Shopper): Promise<SavedCart>
```

Sets one item's quantity in a store's line, at the cart `version` you read. A quantity of `0` takes the item out. The store reads the line's total again at the next resume; a Shopify store's line reads `failed` with `edited_waits_for_store` until the shopper adds the item again. A line at a retail store, at DoorDash, or for a booking or a trip throws `line_not_editable`: the shopper changes it in their chat. A cart that moved past that version throws `cart_changed`, with the cart as it stands in `error.body.cart`.

### `removeCartStore`

```ts theme={null}
agentcard.removeCartStore(cartId: string, lineKey: string, version: number, who?: Shopper): Promise<SavedCart>
```

Takes one store's whole line out of a saved cart, at the cart `version` you read. A cart left with no store ends. A line at a retail store, at DoorDash, or for a booking or a trip throws `line_not_editable`.

### `setCartDelivery`

```ts theme={null}
agentcard.setCartDelivery(cartId: string, edit: CartDeliveryEdit, who?: Shopper): Promise<CartDelivery>
```

Sets a gift's arrive-by day and note on the shopper's cart. Nothing is priced or paid: each store's delivery estimate is read against the day at the shopper's next yes, and a line that arrives late is named before the approval. Throws `gift_delivery_not_available` until gift delivery reaches your company.

### `mintVaultLink`

```ts theme={null}
agentcard.mintVaultLink(input: { externalUserId: string; returnUrl?: string; state?: string }): Promise<VaultLink>
```

Returns the Vault link a shopper opens to connect to your company and add a card. Agentcard returns the link it already opened for that shopper while the link has time left, so a shopper who asks twice gets one link. The method needs company credentials and throws a `TypeError` under a shopper's token.

`returnUrl` is where the Vault page sends the shopper once their card is saved, such as your app's own `yourapp://agentcard-done`. `returnUrl` must be one of the links your company registered. `state` comes back on that link unchanged, and a `state` without `returnUrl` throws a `TypeError`. See [Checking out inside your app](https://docs.agentcard.com/opencommerce/guides/checking-out-inside-your-app.md).

### `merchants`

```ts theme={null}
agentcard.merchants(opts?: { kind?: 'direct' | 'catalog' | 'all'; q?: string; limit?: number; cursor?: string }, who?: Shopper): Promise<BuyMerchantPage>
```

Reads one page of the merchants Agentcard buys at, each with the wallets that pay there. With company credentials and no `who`, you read each merchant as a shopper of your app reads it before signing in anywhere, so you can check a merchant before anyone connects. `kind` is `direct`, `catalog` or `all`, `direct` by default and `all` with `q`. `q` matches part of a name or domain. `limit` is 1 to 100, `50` by default. Pass the last page's `next_cursor` as `cursor`.

Each merchant's `wallets` lists `{ wallet, status }`, with `wallet` `vault` or `link`:

| `status` | What it means |
| - | - |
| `proven` | An order placed with that wallet at the merchant. |
| `expected` | No order has placed with that wallet there yet. |
| `refused` | The merchant turns that wallet away. |

The Vault reads at every merchant. Link reads at a store whose `buys_through` is `browser`, and for hotels, rental cars and flights booked through Agentcard. `wallets` is `null` from an older Agentcard.

### `sealLink`

```ts theme={null}
agentcard.sealLink(approvalId: string, sealed: Record<string, unknown>, who?: Shopper): Promise<{ status: string }>
```

Hands Agentcard the shopper's Link grant, sealed to the key the confirm named, for a Link confirm that answered `link_seal_needed`. Only the sealed envelope leaves your server, and the call is `POST /buy/v1/link-seals/{approval_id}`. Pass `who` with company credentials. The answer is `{ status: 'sealed' }`. The buy tool seals and posts for you; [Pay with Stripe Link](https://docs.agentcard.com/purchase-api/link-seal.md) shows the steps over HTTP.

### `listen`

```ts theme={null}
agentcard.listen(options: ListenOptions): AgentcardListener
```

Hears every event Agentcard sends your company over one connection your server opens. See [listen](https://docs.agentcard.com/api-reference/commerce-sdk/listen.md).

### `delivered`

```ts theme={null}
agentcard.delivered(externalUserId: string, message: ShopperMessage): void
```

Records that `message` reached the chat of the shopper you call `externalUserId`, so that shopper's next `buy.turn` hands it to your model. `listen` and `agentcardWebhook({ agentcard })` call it once `onMessage` returns, so call it yourself only for a message you delivered another way. The client keeps a message once per `eventId`, at most 20 messages per shopper, in this process's memory.

### `answered`

```ts theme={null}
agentcard.answered(externalUserId: string, message: ShopperMessage, threadId?: string): void
```

Records that your agent answers `message` with a turn of its own in the chat `threadId` names, so the shopper never reads its `text` there. For a message about one purchase, `delivered` skips the message from then on, and no later turn tells the model its text. A message about the shopper alone, such as a saved card, still reaches the next turn in the shopper's other chats. Leave out `threadId` for a tool built without one. [`buy.nextStep`](https://docs.agentcard.com/api-reference/commerce-sdk/turn#next-step) calls it.

### `unanswered`

```ts theme={null}
agentcard.unanswered(externalUserId: string, message: ShopperMessage, threadId?: string): void
```

Takes back `answered` for a message your agent's turn could not answer. Pass the `threadId` you passed to `answered`. After you post the message's text, `delivered` keeps it again. `turn.release()` calls it.

### `keptMessages`

```ts theme={null}
agentcard.keptMessages(externalUserId: string, threadId?: string): ShopperMessage[]
```

Returns the messages kept for this shopper in the chat `threadId` names, oldest first: each message about that chat's purchase or about the shopper alone that reached the shopper's chat, and that no history passed to `turn.messages` in that chat holds yet. Leave out `threadId` for a tool built without one: that tool gets the messages of the purchases made under no thread.

### `forgetMessages`

```ts theme={null}
agentcard.forgetMessages(externalUserId: string, messages: readonly ShopperMessage[], threadId?: string): void
```

Forgets these messages for this shopper in the chat `threadId` names. `turn.messages` calls it once the history it reads holds them. A message about the shopper alone stays kept for the shopper's other chats until their own histories hold it.

## Constants

| Constant | Value | Description |
| - | - | - |
| `DEFAULT_BASE_URL` | `https://api.agentcard.sh` | Where the client calls when you pass no `baseUrl`. |
| `BUY_TURN_TIMEOUT_MS` | `130000` | The wait for one purchase turn. The wait runs past Agentcard's own 110-second budget, so a slow turn answers `turn_timeout` instead of aborting. |

## BuyRequest

The body of one `buy` call. Every field is optional.

| Field | Type | Description |
| - | - | - |
| `ask` | `string` | The shopper's words. |
| `confirm` | `string` or `true` | A cart hash from an earlier answer, or `true` for the cart Agentcard last answered with. |
| `resume` | `true` | Continues the shopper's newest open conversation instead of starting one. |
| `conversation_id` | `string` | The conversation that a confirm of a cart hash belongs to, in place of `resume`. |
| `thread_id` | `string` | Your own id for the chat or thread the shopper wrote in, 1 to 200 characters. `resume` then continues the newest open conversation in that chat only. |
| `new_order` | `true` | Drops the cart on the table and starts a new order. |
| `pick` | `{ product_id: string }` or `{ store_id: string }` | The product the shopper picked from the last search, or the store they picked from the last answer. Goes with an `ask`, never with `confirm` or `new_order`. |
| `payment_source` | `'vault'` or `'link'` | Pays from the shopper's Vault, or from their Link wallet. |
| `wallets` | `BuyWalletName[]` | The wallets your app offers, in the order the shopper sees them. `buyTool({ wallets })` sends it on every request. |
| `last_used_first` | `boolean` | `true` puts the wallet the shopper paid with last first in the answer's `wallets`. |
| `link_limits` | `BuyLinkLimits` | The shopper's own Link limits in cents, `per_purchase_cents`, `daily_remaining_cents` and `monthly_remaining_cents`, each `number` or `null`. Agentcard holds a Link cart to them. |
| `link_payment` | `{ spend_request_id: string; amount_cents: number; currency: string }` | With a confirm under `payment_source: 'link'`: the Link payment the shopper approved, and the most it covers. |
| `wallet_check` | `{ wallet: 'link'; ok: boolean; error?: string }` | Your app's first read of the shopper's Link wallet, sent once, so your dashboard says whether your Link connection works. |
| `return_url` | `string` | Where an approval page this turn opens sends the shopper once they approve or decline, such as `yourapp://agentcard-done`. One of the links your company registered. `buyTool({ returnUrl })` sends it on every request. |
| `delivery_address` | `BuyDeliveryAddress` | Where the order goes, when you already hold the address. |
| `external_user_id` | `string` | Your own id for the shopper. |
| `user_id` | `string` | Agentcard's user id for the shopper. |
| `ack` | `false` | Asks for no line that says what Agentcard is looking for, because the shopper already read one. Agentcard sends the line only on a streamed ask for something new. |
| `image` | `{ url: string }` or `{ data: string, media_type: string }` | A picture the shopper showed with the ask: an `https` address, or base64 data of at most 3 MB in `image/jpeg`, `image/png`, `image/webp` or `image/gif`. Agentcard searches for the product it shows. Goes with an `ask`, never with `confirm`. [Shop from a picture](https://docs.agentcard.com/opencommerce/guides/shopping-from-a-picture.md) lists each refusal. |
| `candidates` | `true` | Asks for the products behind the cards: `catalog.found_total`, `catalog.candidates` and `catalog.store_counts`, with `rank` and `why` on every card and candidate. `buyTool({ candidates: true })` sends it on every ask. |

`BuyDeliveryAddress` has the required fields `street`, `city`, `state` and `zip`, and the optional fields `address2`, `phone`, `name`, `country` and `can_leave_at_door` (`boolean`).

## BuyTurn

One turn's answer. Every field is present, and a field an older Agentcard does not send reads as `null`.

| Field | Type | Description |
| - | - | - |
| `conversation_id` | `string` | The conversation the turn belongs to. Empty when Agentcard named none. |
| `status` | `BuyStatus` | `needs_input`, `needs_approval`, `order_placed`, `partially_placed` or `declined`. A status Agentcard adds later reads as `needs_input`. |
| `reply` | `string` | Agentcard's answer for the shopper, links included. |
| `messages` | `string[]` | Agentcard's separate messages for the shopper. |
| `cart` | `BuyCart` or `null` | The most recently shown cart. |
| `carts` | `BuyCart[]` | Every cart on the table. |
| `catalog` | `BuyCatalog` or `null` | The last product search. |
| `order_id` | `string` or `null` | Set when this turn placed an order. |
| `payment_source` | `{ source, brand, last4 }` or `null` | How the order was paid. `brand` and `last4` are `string` or `null`. |
| `decline_code` | `string` or `null` | Why Agentcard did not buy. |
| `approval_url` | `string` or `null` | The page where the shopper approves the purchase. |
| `approval_expires_at` | `string` or `null` | When the approval link stops working, as an ISO 8601 timestamp. |
| `approval_in_progress` | `boolean` or `null` | Whether an approval is under way. |
| `charge_status` | `string` or `null` | Whether money moved. |
| `error_code` | `string` or `null` | A machine-readable failure of the turn, such as `turn_timeout`. |
| `authorization_id` | `string` or `null` | The checkout authorization for this turn. |
| `merchant_total_cents` | `number` or `null` | The store's own total, in the smallest unit of `merchant_currency`. |
| `merchant_currency` | `string` or `null` | The store's currency as a lower-case code. |
| `add_card_url` | `string` or `null` | The Vault link for a shopper who has no card. |
| `add_card_expires_at` | `string` or `null` | When that link stops working. |
| `placement_announced` | `boolean` or `null` | Whether Agentcard announced the placement. |
| `next_action` | `BuyNextAction` or `null` | The one step the shopper takes next. A value this version does not know reads as `null`. |
| `bank_challenge` | `BuyBankChallenge` or `null` | The bank's check the shopper answers when `next_action` is `bank_challenge`: `kind`, `store`, `amount_cents`, `currency`, `expires_at` and `url`. |
| `store_login_url` | `string` or `null` | The page where the shopper signs in to a store's own account. |
| `store_login_expires_at` | `string` or `null` | When that page stops working. |
| `store_login_merchant_name` | `string` or `null` | The store that page signs in to. |
| `pick` | `BuyPick` or `null` | The product this turn's `pick` named, and whether the cart holds it. |
| `stores` | `BuyStores` or `null` | The stores this answer's reply presents to choose from. |
| `store_pick` | `BuyStorePick` or `null` | The store this turn picked, and whether Agentcard selected it. |
| `cart_building` | `{ store, started_at }` or `null` | The store whose checkout is still building the cart. Both fields are `string`. |
| `choice` | `BuyChoice` or `null` | The choice the reply asks the shopper to make, such as a sandwich's bread or a shirt's size, with every value. `null` when the reply asks none. |
| `search` | `BuySearchStatus` or `null` | Every store the turn searched and where each stands. `null` when the turn searched no store. See [BuySearchStatus](#buysearchstatus). |
| `wallets` | `BuyWalletOption[]`, optional | Each wallet your app offers, with `fits`, `reason`, `reason_text`, `last_used` and, for the Vault, `setup_needed`. Absent when the turn holds no cart to pay for or the request named no `wallets`. |
| `raw` | `Record<string, unknown>` | The answer as Agentcard sent it. |

`BuyChoice` has `question` (`string` or `null`), `item` (`string` or `null`, the item the choice is about), `source` and `groups`. `source` is `menu_item` for a restaurant item's options, `store_checkout` for a store's own size or colour question, and `catalog_variant` for a product's sizes or colours in stock. Each group has `name`, `required` (`boolean`), `min` and `max` (`max` is `null` for no limit), and `options`. Each option has `id` (`string` or `null`, the option id the cart takes), `label`, and `price_delta_cents` (`number` or `null`, what choosing it adds to the price).

`BuyNextAction` is one of `shipping_details`, `guest_details`, `store_login`, `add_card`, `confirm`, `verification_code`, `approve` or `bank_challenge`, in the order a purchase asks for them. `bank_challenge` comes after the approval, when the shopper's bank asks them to approve the payment too, and the turn's `bank_challenge` field carries the details.

## BuySearchStatus

Every store a turn searched. `searchAt(search, 'gap.com')` returns the same block with only that store, matched by its id, its domain or its name.

| Field | Type | Description |
| - | - | - |
| `search_id` | `string` | This turn's search. A later turn that searches again has a new one. |
| `final` | `boolean` | `true` once no store is still being searched. |
| `elapsed_ms` | `number` | Milliseconds from the first store's search to the last store's answer. |
| `merchants` | `BuyMerchantStatus[]` | Each store, in the order its search started. |
| `index` | `{ results, ms }` or `null` | How many products Agentcard's own product index answered, and how long the read took. `null` when the turn read none. |

Each `BuyMerchantStatus` has `merchant` (the store's id or domain), `merchant_name`, `status`, `results`, `confirmed`, `first_result_ms` (`number` or `null`) and `ms`. `status` is one of `searching`, `confirmed`, `recently_confirmed`, `confirmation_unavailable`, `no_results`, `timed_out`, `failed` or `unavailable`; [Showing each store as it is searched](https://docs.agentcard.com/opencommerce/guides/showing-each-store-searched.md) says what each one means. A store with a status this version does not know is left out.

`merchantStatusLine(store, named)` gives the line to show for one store, from `merchants` or from an `onMerchantStatus` update: `still loading Walmart` for an `unavailable` store the shopper named, and `null` for every other store. `named` is a store or a list of stores, each matched as `searchAt` matches it. `searchStatusLines(search, named)` gives every such line for the turn, in the order the searches started.

## BuyCart

A cart as Agentcard answers it. Every amount is in the smallest unit of `currency`.

| Field | Type | Description |
| - | - | - |
| `merchant` | `string` | Agentcard's id for the merchant. |
| `merchant_name` | `string` | The merchant's display name. |
| `store` | `{ id: string; name?: string }` or `null` | The store the cart is at. |
| `items` | `BuyCartLine[]` | The cart's lines. |
| `subtotalCents` | `number` or `null` | The items alone. |
| `serviceFeesCents` | `number` | The store's fees. |
| `merchantFeeLines` | `{ label: string; amountCents: number }[]` or `null` | The store's own fee and tax lines inside `serviceFeesCents`. |
| `tipCents` | `number` | The tip. |
| `totalCents` | `number` | The all-in total the shopper sees. |
| `totalIsEstimate` | `boolean` | `true` when the store has not priced fees and tax yet, so `totalCents` is an estimate. |
| `currency` | `string` or `null` | The ISO 4217 code the store prices the cart in. |
| `approvedCeilingCents` | `number` or `null` | The most a confirm can authorize. |
| `fulfillment` | `'pickup'`, optional | `'pickup'` when the shopper picks the order up at the store, so the store adds no shipping or delivery. Absent for a delivery. |
| `hash` | `string` | Identifies exactly this cart at this price. A confirm names it. |

### BuyCartLine

| Field | Type | Description |
| - | - | - |
| `name` | `string` | The line's name. |
| `qty` | `number` | The quantity. |
| `priceCents` | `number`, optional | One unit's price. |
| `lineTotalCents` | `number` or `null` | What the line costs with its add-ons and quantity. `null` when the price is unknown. |
| `options` | `string[]` | The choices made on the line, in the store's names. Empty when none. |
| `variant` | `string` or `null` | The variant the line is, in the store's name. |
| `product_id` | `string` or `null` | The product's id. |
| `ref` | `string` or `null` | The id of the product card this line is. A product whose `ref` or `id` equals it is in the cart. |
| `url` | `string` or `null` | The product's page, as an `http` or `https` address. |

## BuyCatalog

The products the last search found.

| Field | Type | Description |
| - | - | - |
| `merchant` | `string` | Agentcard's id for the merchant. |
| `merchant_name` | `string` | The merchant's display name. |
| `items` | `BuyCatalogItem[]` | The products. |
| `presented` | `boolean` | `true` when this answer's reply presents the products. |
| `found_total` | `number`, optional | With `candidates: true`: how many products the search kept, inside the shopper's price limit. |
| `candidates` | `BuyCatalogItem[]`, optional | With `candidates: true`: up to 16 products past `items`, in the search's order. None of them is in `items`. |
| `store_counts` | `{ store_id, store_name, found, shown }[]`, optional | With `candidates: true`: each store's kept products, and how many of them `items` shows. |

### BuyCatalogItem

| Field | Type | Description |
| - | - | - |
| `id` | `string` | The item's id. |
| `ref` | `string` or `null` | The item's id with no link in it, which `pick.product_id` also takes. |
| `name` | `string` or `null` | The product's name. |
| `priceCents` | `number` or `null` | The price in the smallest unit of `currency`. |
| `price_from` | `true`, optional | Present when `priceCents` is the lowest price of a product priced by a required choice, such as a size. |
| `currency` | `string` or `null` | The ISO 4217 code the store prices the product in. |
| `image_url` | `string` or `null` | The product's main photo. |
| `image_urls` | `string[]` | Every photo, `image_url` first, at most eight. Only `https` addresses without credentials join the list. |
| `store` | `{ id: string; name?: string; domain?: string \| null }` or `null` | The store that sells it. `domain` is the store's own website, such as `walmart.com` or `jadeyoga.com`. |
| `url` | `string` or `null` | The product's page at its store, as an `http` or `https` address. |
| `flight` | `BuyFlightItinerary`, optional | For a flight: `fareCabinClass` (`string` or `null`, optional) and `legs`, each with `origin`, `destination`, `departureAt`, `arrivalAt` and `cabinClasses`. |
| `rank` | `number`, optional | With `candidates: true`: the product's place, from 1 across `items` and then `candidates`. |
| `why` | `{ code: string; text: string }[]`, optional | With `candidates: true`: why the product ranks there. The codes are listed in [Rank the products yourself](https://docs.agentcard.com/api-reference/commerce-sdk/buy-tool.md#rank-the-products-yourself). |

Show `store.domain` as where the product is sold. The field reads `null` when Agentcard knows no website for the store, such as a restaurant, and an older API leaves it out.

### BuyPick, BuyStores and BuyStorePick

| Type | Fields |
| - | - |
| `BuyPick` | `product_id` (`string`), `ref` (`string` or `null`), `in_cart` (`boolean`). |
| `BuyStores` | `merchant` (`string`), `merchant_name` (`string`), `items` (`BuyStoreChoice[]`), `as_of` (`string` or `null`). |
| `BuyStoreChoice` | `id` (`string`, holds no link), `name` (`string`), `store_page_url` (`string` or `null`), `eta_minutes` (`number` or `null`), `image_url` (`string` or `null`). |
| `BuyStorePick` | `store_id` (`string`), `name` (`string` or `null`), `selected` (`boolean`). |

## BuyConversation

Where one conversation stands.

| Field | Type | Description |
| - | - | - |
| `conversation_id` | `string` | The conversation. |
| `status` | `'open'` or `'closed'` | Whether the conversation still takes turns. |
| `turn_in_progress` | `boolean` | `true` while Agentcard works on a turn. |
| `cart_building` | `{ store, started_at }` or `null` | The cart the store's checkout is still building. |
| `last_checkout` | `BuyLastCheckout` or `null` | The last checkout attempt. |
| `orders` | `BuyOrder[]` | The orders the conversation placed. |
| `carts` | `BuyCart[]` | The carts on the table. |
| `latest_reply` | `BuyLatestReply` or `null` | The reply Agentcard wrote after the shopper's last message, once no turn runs. A call that ended with `turn_timeout` never got this reply. `null` while a turn runs and when no reply was written since. |
| `trip` | `BuyTrip` or `null` | The trip Agentcard is planning in this conversation, with each search it runs for it. `null` for any other conversation. |
| `raw` | `Record<string, unknown>` | The answer as Agentcard sent it. |

`BuyLatestReply` has `message_id`, `text`, `messages` (`string[]`), `catalog` (`BuyCatalog` or `null`, the products the reply showed) and `created_at` (`string` or `null`).

`BuyOrder` has `order_id` (`string` or `null`), `merchant`, `merchant_name`, `status`, `total_cents` and `placed_at` (`string` or `null`). `BuyOrder` carries no `merchant_of_record`, who charged the shopper's card: that field arrives on each order in `raw.orders`, and [Send a dispute to the right place](https://docs.agentcard.com/opencommerce/guides/sending-a-dispute-to-the-right-place.md) shows how to read it and what each of its fields says. For where one order is now, read it with [`order`](#order). `BuyLastCheckout` has `at`, `merchant`, `merchant_name`, `status`, `code`, `message`, `order_id`, `decline_code`, `approval_url`, `approval_expires_at`, `placement_announced`, `approval_in_progress`, `add_card_url`, `add_card_expires_at` and `total_cents`. All of its fields except `at`, `merchant`, `merchant_name` and `status` are `null` when absent.

### Show a trip's searches

When a shopper plans a trip, Agentcard asks where and when first, then searches flights, hotels and a rental car while the conversation goes on. Read the conversation and show each search as its results arrive:

```ts theme={null}
const conversation = await agentcard.conversation(conversationId, { externalUserId });
for (const lane of conversation.trip?.lanes ?? []) {
  render(lane.lane, lane.items, lane.done ? null : lane.checking);
}
```

`conversation()` returns the trip as it stands at that read. While any lane's `status` is `queued` or `searching`, read the conversation again every few seconds and render the lanes again, and stop once none is. Right after the reply that sets the place and the dates, `lanes` can still be empty while the searches start, so keep reading until it lists a lane, then apply that rule. A `waiting` lane runs no search on its own: flights wait for the city the shopper leaves from. Read the conversation again after each reply, since a reply can start a waiting lane, and a change to the place, the dates or the party starts a new set of searches.

`BuyTrip` has `place`, `check_in`, `check_out`, `travelers`, `origin` and `lanes`. The lanes come in the order a shopper reads them: `flights` first, since the flights set when the trip lands and leaves, then `hotels`, `car`, `activities` and `payment`, the check that the shopper's card pays without stopping at checkout.

Each lane has `status`, `done`, `checking`, `results`, `items` and `decision`. Until `done` is `true`, more results can still arrive, so show `checking` beside the lane, such as `still checking hotels…`, and never present its results as the full list. Once the lane is done, its `status` says how it ended: `confirmed`, `no_results`, `failed`, `timed_out` or `cancelled`.

`items` holds up to 8 results, ordered by what the shopper said matters, such as the price or nonstop flights. Each result has `product_id`, `title`, `price_cents`, `currency` and `fulfilled_by`, the party the shopper books with, such as `{ "name": "Korean Air", "kind": "airline" }`. Show `fulfilled_by` as one quiet line on the card, such as "via Korean Air". `decision` says whether the shopper's last preference re-ranked the results the lane held, searched again, or both, with the reasons.

A `hotels` lane carries `fits_flight`, which is `false` when the flight the shopper picked lands on another day than the stay those hotels were searched for. Show the mismatch only when `fits_flight === false`: `null` means no flight is picked yet, which is no mismatch. The `payment` lane carries `ready`.

Each of these can be `null`. A result whose `fulfilled_by` is `null` shows no seller line. A lane whose `decision` is `null` has had no preference stated, so show no decision.

## BuyOrderStatus

Where one placed order is now, as [`order`](#order) reads it.

| Field | Type | Description |
| - | - | - |
| `order_id` | `string` | The order id `order.placed` carried. |
| `merchant` | `string` | The merchant's id, such as `retail` or `doordash`. |
| `merchant_name` | `string` | The store's name, such as `Amazon`. |
| `conversation_id` | `string` or `null` | The conversation that placed the order. |
| `status` | `string` | `placed`, `confirmed`, `courier_assigned`, `courier_at_store`, `ready_for_pickup`, `picked_up`, `arriving`, `delivered` or `canceled`: the stage the order has reached. |
| `status_updated_at` | `string` or `null` | When the order reached `status`, as an ISO 8601 timestamp. |
| `estimated_arrival` | `{ earliest, latest }` or `null` | The arrival window the store gave, each an ISO 8601 timestamp or `null`. |
| `tracking` | `'live'`, `'ended'` or `'not_available'` | `live` while Agentcard follows the order at the store, `ended` once it stopped, `not_available` at a store it cannot follow. |
| `checked_at` | `string` or `null` | When Agentcard last asked the store. |
| `placed_at` | `string` or `null` | When the order was placed. |
| `shipping_address` | [`BuyOrderShippingAddress`](#buyordershippingaddress) or `null` | The address the order was placed to ship or deliver to. `null` for a pickup, an order that goes to no address, and an order placed before Agentcard kept the address. |
| `retailer_order_id` | `string` or `null` | The store's own order number, once the store names it. `null` at a store with none. |
| `delivery_window` | `string` or `null` | The delivery window the store quoted, in its own words, such as `Sat, Sep 6 - Tue, Sep 9`. |
| `shipments` | [`BuyOrderShipment[]`](#buyordershipment) | Every package a carrier holds for the order. Empty until the first package ships, and at a store that delivers the order itself. |

See [Read where an order is](https://docs.agentcard.com/commerce-sdk/guides/approving-a-purchase.md#read-where-an-order-is) for what each merchant answers.

## BuyOrderShipment

One package of an order, as the carrier reports it. A value the carrier has not reported is `null`.

| Field | Type | Description |
| - | - | - |
| `carrier` | `string` or `null` | The carrier, such as `UPS`. |
| `tracking_number` | `string` or `null` | The carrier's tracking number. |
| `tracking_url` | `string` or `null` | The carrier's tracking page for the package. |
| `status` | `string` or `null` | The carrier's word for where the package is, such as `in_transit`, `out_for_delivery` or `delivered`. |
| `estimated_delivery` | `string` or `null` | The delivery date the carrier estimates, as it sent it, such as `2026-09-08`. |

## BuyOrderShippingAddress

The address a placed order ships or delivers to, as it was sent at placement.

| Field | Type | Description |
| - | - | - |
| `name` | `string` or `null` | The recipient's name. |
| `line1` | `string` | The street address. |
| `line2` | `string` or `null` | The apartment, suite or unit. |
| `city` | `string` | The city. |
| `state` | `string` or `null` | The state or province. |
| `postal_code` | `string` | The postal code. |
| `country` | `string` | The country, as an ISO 3166-1 alpha-2 code. |
| `phone` | `string` or `null` | The phone your app sent with the address, if any. |

## VaultLink

| Field | Type | Description |
| - | - | - |
| `id` | `string` | The Vault session's id. |
| `url` | `string` | The page where the shopper connects and adds a card. |
| `expiresAt` | `string` or `null` | When the link stops working, as an ISO 8601 timestamp. |
| `reused` | `boolean` | `true` when Agentcard returned a link it had already opened for this shopper. |

## Shopper

Who a call is for. Name the shopper exactly once with company credentials, and leave both fields out under a shopper's own token.

| Field | Type | Description |
| - | - | - |
| `externalUserId` | `string`, optional | Your own id for the shopper. |
| `userId` | `string`, optional | Agentcard's user id for the shopper. |

## AgentcardApiError

The error every refusal and failed call throws. `AgentcardApiError` extends `Error`.

| Property | Type | Description |
| - | - | - |
| `status` | `number` | The HTTP status. `0` when Agentcard never answered. |
| `code` | `string` | Why the call failed. Branch on it and never on `message`. |
| `body` | `Record<string, unknown>` | The error body as Agentcard sent it. |
| `conversationId` | `string` or `null` | The conversation the refusal names. |
| `carts` | `BuyCart[]` | The carts as they stand, when the refusal names them. A changed cart's fresh hash is here. |

Through `buy.answer`, five refusals still answer the shopper: they come back as `needs_input` with the reason in `reply` and the code in `error_code`. They are `cart_changed`, `nothing_to_confirm`, `conversation_closed`, a delivery address that changed since the cart was built (a code that starts with `delivery_address`), and `turn_in_progress`. Every other refusal throws an `AgentcardApiError`.

### Error codes

| `code` | What it means | What to do |
| - | - | - |
| `external_user_id_ambiguous` | Two of your shoppers share the `externalUserId` you passed. | Give each shopper their own id. |
| `oauth_failed` | Agentcard refused your client credentials. | Check `clientId` and `clientSecret`. |
| `unauthorized` | Agentcard refused the access token. | Sign the shopper in again when the token was their own. |
| `timeout` | Agentcard did not answer in time, so whether the turn ran is unknown. A purchase turn waits 130 seconds. | Read the conversation with `agentcard.conversation(conversationId, { externalUserId })`. Send the turn again only once that read shows it did not finish. |
| `unreachable` | No answer came back. The request can still have reached Agentcard. | Act as for `timeout`. |
| `invalid_answer` | Agentcard answered with a body the client cannot read. | Act as for `timeout`. |
| `cart_changed` | The cart changed since its hash was issued. The error's `carts` holds the fresh cart. | Show the shopper the new total, then confirm the new hash. |
| `nothing_to_confirm` | A confirm arrived with no cart on the table. | Ask for a cart first. |
| `conversation_closed` | A confirm named a conversation that is closed. | Start a new order. |
| `conversation_not_found` | Agentcard has no conversation by that id. | Check the id, or start a new order. |
| `thread_mismatch` | A `conversation_id` came with the `thread_id` of another chat. | Send the conversation id from that chat's own answers, or `resume: true` with its `thread_id`. |
| `user_not_connected` | The shopper has not connected to your company. | Send the shopper a Vault link. The buy tool does this for you. |
| `turn_in_progress` | Agentcard is still working on an earlier request for this conversation. | Send the message again once the earlier request finishes. |
| `pick_not_found` | The `pick` names a product or store Agentcard does not hold. | Search again with the shopper's words. |
| `link_payment_unavailable` | Link pays a store checkout Agentcard's browser types a card into, or a hotel, a rental car or a flight booked through Agentcard, and this cart is none of them. Nothing was charged. | Cancel the Link payment, and offer the Vault for that cart. |
| `link_payment_invalid` | A Link confirm left out `conversation_id`, or sent an incomplete `link_payment`. Nothing was charged. | Send the confirm with `conversation_id` and the approved payment's `spend_request_id`, `amount_cents` and `currency`. |
| `link_amount_short` | The approved Link payment is less than the store's total, or in another currency. Nothing was charged. | Ask the shopper to approve the cart's total in Link, then confirm again. |
| `link_seal_not_found`, `link_seal_answered`, `link_seal_expired`, `link_seal_invalid` | `sealLink` was refused: no such approval waits, it was already sealed or its payment ended, `seal_by` passed, or the envelope is not sealed to the approval's key. | Confirm the cart again after `link_seal_expired`, and read the conversation after `link_seal_answered`. |
| `http_<status>` | Agentcard answered with a status that carries no code, such as `http_502`. | Retry later, or read the conversation first when the call was a turn. |

Agentcard refuses a `conversation_id` sent with the `thread_id` of another chat before it reads the message, so the other chat's words never reach that purchase. The refusal comes back as a `409`:

```json theme={null}
{
  "error": "This conversation belongs to another thread. Send the conversation_id that thread was answered with, or resume: true with this thread_id.",
  "code": "thread_mismatch",
  "conversation_id": "conv_bc8fa9f7a64f121fd0af8f9b"
}
```

`buyTool` sends each purchase request once. Only a request that Agentcard refused with a `401` goes again, once, with a renewed token.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.