> ## 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

# Buy tool

> Builds the one tool that buys for one shopper, in the shape every agent framework takes.

`buyTool(options)` returns the `buy` tool for one shopper. The model calls it with the shopper's words, and Agentcard finds the products, builds the cart and places the order once the shopper approves. Each framework reads its own fields from the same object, so you pick no adapter.

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

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

const buy = buyTool({
  agentcard,
  externalUserId: 'user-42', // your own id for the shopper
  sendLink: (link) => textShopper('user-42', link.url ?? ''),
});

const answer = await new Anthropic().beta.messages.toolRunner({
  model: 'claude-opus-5-5',
  max_tokens: 16000,
  tools: [buy],
  messages: [{ role: 'user', content: 'two packs of AA batteries from Amazon' }],
});
```

`textShopper` stands for your own code. The model calls `buy`, shows the shopper the cart, and confirms the cart only after the shopper says yes. Build the tool once per shopper and keep it. In a chat app, open a [turn](https://docs.agentcard.com/api-reference/commerce-sdk/turn.md) from it for each message.

## Create the tool

```ts theme={null}
buyTool(options: BuyToolOptions): BuyTool
```

Name your company's `AgentcardClient` and the shopper, or pass one shopper's own access token. The function throws a `TypeError` when you pass both `agentcard` and `accessToken`, or neither.

## Options

| Option | Type | Description |
| - | - | - |
| `agentcard` | `AgentcardClient`, required without `accessToken` | A client built with your company's credentials. Share one across every shopper's tool. |
| `accessToken` | `string`, required without `agentcard` | One shopper's own Agentcard access token, for a tool that buys only for them. |
| `externalUserId` | `string`, required with `agentcard` | Your own id for the shopper. Leave it out with `accessToken`. |
| `threadId` | `string`, optional | Your own id for the chat or thread the tool answers in, 1 to 200 characters. See [Keep a purchase per chat](#keep-a-purchase-per-chat). |
| `cartId` | `string`, optional | A saved cart the shopper brought back, by the id `listCarts` named. Every ask the tool sends works inside that cart, so the shopper's yes answers it. Leave it out when no saved cart is open. See [Bring back a saved cart](https://docs.agentcard.com/opencommerce/guides/bringing-back-a-saved-cart.md#keep-the-yes-in-the-cart). |
| `sendLink` | `(link: BuyToolLink) => void` or a promise, optional | Delivers a link to the shopper. Each call waits for it. A throw on a Vault, approval or store login link makes the call throw too. |
| `deliveryAddress` | `BuyDeliveryAddress`, optional | Where orders go, when you already hold the shopper's address. Agentcard never asks the shopper for it, and the model cannot change it. |
| `returnUrl` | `string`, optional, with `agentcard` | Where the Vault page and the approval page send the shopper once they finish, such as `yourapp://agentcard-done`. One of the links your company registered. See [Checking out inside your app](https://docs.agentcard.com/opencommerce/guides/checking-out-inside-your-app.md). |
| `wallets` | `BuyWalletName[]`, optional | The wallets your shoppers can pay with, in the order they see them: `['vault']`, `['link']`, `['vault', 'link']` or `['link', 'vault']`. Each answer's `wallets` says which of them can pay its carts. See [Paying with a Stripe Link wallet](https://docs.agentcard.com/commerce-sdk/guides/paying-with-a-link-wallet.md). |
| `wallet` | `BuyWallet`, optional | The shopper's Link wallet, `{ link, linkAccessToken, test? }`, as `linkRoutes(...).buyWallets` answers it. Required when `wallets` names `link`. Without `wallets`, Link pays in place of the Vault. |
| `lastUsedFirst` | `boolean`, optional | Shows the wallet the shopper paid with last ahead of your order. Default `true`. Set `false` to keep your order. |
| `baseUrl` | `string`, optional | With `accessToken`: where Agentcard answers. Default `https://api.agentcard.sh`. |
| `fetch` | `FetchLike`, optional | With `accessToken`: the fetch to call Agentcard with. Default: the global `fetch`. |
| `wait` | `(ms: number) => Promise<void>`, optional | The pause between two reads of the conversation. Default: a timer. |
| `onReaction` | `(emoji: string) => void` or a promise, optional | Reacts to the shopper's message with `👀`, to show as a reaction on their message. A throw costs only the reaction. |
| `onWorking` | `(message: string) => void` or a promise, optional | Sends the shopper the text that says Agentcard is on it: the line Agentcard writes for a streamed search sent straight, or a fixed line for a slow pick, confirm or answer. A throw costs only the text. |
| `onText` | `(text: string, info: { conversationId: string \| null }) => void` or a promise, optional | Hears each message Agentcard writes, the moment it is written, with every list as `• ` bullets. With no `onWorking`, it also hears the line Agentcard writes for a search. |
| `ack` | `'reaction'`, `'text'`, `'none'`, `false` or `(ask: string) => string`, optional | How the tool acknowledges a message. See [Acknowledgements](#acknowledgements). |
| `ackDelayMs` | `number`, optional | How long to wait with nothing shown to the shopper before the reaction or the fixed line goes out. Default `1000`. |
| `onResult` | `(result: BuyToolResult) => void` or a promise, optional | Hears the whole answer once per call, after its links went out and before the model reads it. |
| `onProgress` | `(progress: BuyProgress) => void`, optional | Hears each stage Agentcard reaches on a call: `searching`, `building_cart`, `checking_out` or `working`. |
| `onMerchantStatus` | `(update: BuyMerchantStatusUpdate) => void` or a promise, optional | Hears each store a call's searches ask, the moment its status changes: `searching`, then what it found. See [Showing each store as it is searched](https://docs.agentcard.com/opencommerce/guides/showing-each-store-searched.md). A throw costs only the call to it. |
| `onProducts` | `(products: BuyToolProduct[], search: { conversationId: string; asOf: string \| null; merchantName: string }) => void` or a promise, optional | Hears the products a call's search found, the moment the search answers and before Agentcard writes its reply. Show them as the answer's cards, each field as [`BuyToolProduct`](#buytoolproduct) describes it. |
| `stream` | `false`, optional | `false` waits for each whole answer. |
| `earlyCards` | `boolean`, optional | On by default: each product page a search found, at most eight, reaches `sendLink` the moment the search answers, before the reply, and needs `sendLink` or `onProducts` to hear it. `false` waits for the reply and sends only the pages it names. |
| `replyAsWritten` | `boolean`, optional | `true` sets `turn.replyAsWritten` on every turn this tool opens. Default off. |
| `candidates` | `true`, optional | Asks Agentcard, on every ask, for the products behind the cards, each with its place and why it ranks there. See [Rank the products yourself](#rank-the-products-yourself). Default off. |
| `textingStyle` | `boolean`, optional | `true` writes `turn.replyAsWritten` and each message `onText` hears in a chat's texting style, with the bullets kept. See [Show bullets and texting style](#show-bullets-and-texting-style). Default off. |

`sendLink`, `onResult`, `onReaction` and `onWorking` hear every call the tool makes, whichever shopper message the call answers. To keep the links and answers of one message apart from those of another message, pass them to [`buy.turn`](https://docs.agentcard.com/api-reference/commerce-sdk/turn) instead.

A throw from `sendLink` on a product link leaves that product's `linkSent` false, and the call goes on. A throw from `onResult` costs only that call to it. A throw from `onText` leaves `shopper_already_read_reply` false, so your model words the answer.

`onProducts` also hears the search itself: `asOf` says when the search ran, and `merchantName` which store answered. Like `sendLink`, `onProducts` hears every call, so pass it to [`buy.turn`](https://docs.agentcard.com/api-reference/commerce-sdk/turn) to hear one turn's products alone. A throw costs only the call to it.

With `onProgress`, or with `earlyCards` and `sendLink`, the tool asks Agentcard to stream the call. Pass `stream: false` to wait for each whole answer.

### Acknowledgements

Left out, `ack` reacts through `onReaction` when the tool or the turn has one, and sends text through `onWorking` otherwise. `'text'` sends text even with an `onReaction`. `'none'` and `false` send nothing. A function writes the instant reply from the shopper's words, and an empty answer sends none.

A streamed search that `buy.turn` sends straight gets one line that Agentcard writes while it searches, such as `one sec, checking target for la croix`. The line reaches `onWorking`, or `onText` with no `onWorking`, before the cards, and only while the shopper has read nothing else of the turn. When the line has not come after twice `ackDelayMs` and the call has not answered, the tool sends `one moment` once through `onWorking`, and a line of Agentcard's that comes later is dropped. A search with `stream: false` gets the tool's own template instead, once Agentcard has not answered within `ackDelayMs`.

A pick, a confirm or another answer that has shown the shopper nothing for `ackDelayMs` gets one fixed line through `onWorking`: `got it, one moment` for a pick, `on it, one moment` for a confirm, and `one moment` for anything else. A code gets none.

The [acknowledging guide](https://docs.agentcard.com/opencommerce/guides/acknowledging-the-shopper.md) shows both modes.

## Keep a purchase per chat

Build one tool per shopper and chat when your agent talks to a shopper in more than one place at once, such as several group chats, and name the chat with `threadId`:

```ts theme={null}
const buy = buyTool({ agentcard, externalUserId: 'user-42', threadId: 'group-chat-7' });
```

Agentcard keeps an open purchase for each chat. A cart, a question or an approval link from one chat never shows up in another, and the shopper keeps one Vault card, one store sign-in and one address book across all of them. A tool built without `threadId` continues the shopper's one purchase from every chat.

Each message about a chat's purchase carries that chat as `threadId`, so post it into that chat. A message about the shopper alone, such as a saved card, carries `threadId: null`, and each chat's tool can take its next step from it. A chat's tool reads only its own chat's messages and the shopper's own, and a tool built without `threadId` reads the purchases opened under no thread and the shopper's own, never a chat's.

Take the next step for a message about the shopper alone in the chat that sent the link the message ends: the card link for a saved card, or the store's sign-in link for a store sign-in. That chat's purchase is the one waiting, and [`actionLinkOutcome(link, message)`](https://docs.agentcard.com/api-reference/commerce-sdk/messages#action-link-helpers) says whether a message ends a link. Post the message's own text where only the shopper reads it, such as their own chat with your agent, so a group never sees their card. When the message ends links in several chats, or in none, take no step: the shopper carries on in each chat with their next message.

DoorDash keeps one cart per account. While one chat's DoorDash cart waits, Agentcard refuses a change or a checkout of that cart from another chat and leaves the cart as it was. The agent in the other chat gets this answer from its cart call, `POST /buy/v1/merchants/doordash/cart/items`, captured from a local run, and tells the shopper what the cart holds:

```json theme={null}
{
  "error": "Your DoorDash cart is in use in another chat, holding 1 × Margherita. Finish or clear that order in that chat first. Nothing in the cart changed.",
  "code": "cart_in_another_chat"
}
```

The shopper finishes or clears that order in its own chat first. A chat keeps its hold on the cart until its order is placed or cleared, or until 24 hours pass without activity in it, the window in which `resume` continues a purchase.

When another chat is still changing the same cart after 40 seconds, the same cart call changes nothing and answers with a 409, also captured from a local run:

```json theme={null}
{
  "error": "Another chat is changing this cart right now. Try again in a moment.",
  "code": "cart_busy"
}
```

When Agentcard cannot read the DoorDash cart to tell which chat holds it, the same cart call changes nothing and answers with a 503:

```json theme={null}
{
  "error": "Agentcard couldn't read the DoorDash cart just now to check it, so nothing in it changed. Try again in a moment.",
  "code": "cart_unreadable"
}
```

| `code` | What it means | What to do |
| - | - | - |
| `cart_in_another_chat` | Another of the shopper's chats holds the DoorDash cart, and the cart still holds that chat's items. | Finish or clear that order in its own chat, then ask again here. |
| `cart_busy` | Another chat is changing the same cart at this moment. | Ask again in a moment. |
| `cart_unreadable` | Agentcard could not read the cart to tell which chat holds it, or could not save this chat's hold, so nothing changed. | Ask again in a moment. |

## Members of the tool

| Member | Type | Description |
| - | - | - |
| `name` | `string` | The tool's name, `buy`. |
| `description` | `string` | The rules the model follows. Read it from `buy.description`. |
| `input_schema` | `BuyToolInputSchema` | The JSON Schema of the model's input, under Anthropic's field name. |
| `strict` | `true` | Asks the model API for input that always fits the schema. |
| `inputSchema` | `BuyToolStandardSchema` | The same schema as a Standard Schema, as the Vercel AI SDK reads it. |
| `openai` | `OpenAIBuyTool` | The tool in OpenAI's function-calling format. |
| `definition` | `BuyToolDefinition` | The name, description and input schema, for a framework with its own tool format. |
| `parse(input)` | `BuyToolInput` | Checks the model's input against the schema and throws a message the model can act on. |
| `run(input)` | `Promise<string>` | Runs one call and returns what the model reads, as JSON text. Anthropic's tool runner calls it. |
| `execute(input)` | `Promise<string>` | The same call, for the Vercel AI SDK. |
| `handle(args)` | `Promise<string>` | The same call for your own loop. Takes the model's arguments as an object or as their JSON text. |
| `answer(input)` | `Promise<BuyToolResult>` | Sends the model's input to Agentcard and returns the whole answer for your code. Never hand it to the model. |
| `forModel(result)` | `BuyToolModelView` | The answer as the model may read it, with every link taken out. |
| `instantAck(text)` | `string` or `null` | The instant text reply for a shopper's message, or `null` for a message that starts no search. |
| `instantReaction(text)` | `string` or `null` | The reaction for a shopper's message, `👀`, or `null`. |
| `turn(text, options)` | `BuyToolTurn` | Opens the turn of one shopper message. See [`buy.turn`](https://docs.agentcard.com/api-reference/commerce-sdk/turn). |
| `nextStep(message, options)` | `BuyToolTurn` or `null` | Opens the turn your agent takes once the shopper finishes a step outside the chat. |
| `payWith(wallet)` | `Promise<BuyToolResult>`, with `wallets` | The shopper's tap on a wallet button. See [Paying with a Stripe Link wallet](https://docs.agentcard.com/commerce-sdk/guides/paying-with-a-link-wallet.md). |
| `approve({ wallet })` | `Promise<BuyToolResult>`, with `wallets` | The shopper's press of Approve on the Approve purchase step. For Link, the answer carries Link's `approval_url`. |
| `clearCart({ store })` | `Promise<BuyClearCartResult>`, with `wallets` | The shopper's swipe left: cancels the Link payments waiting on the cart and empties it at the store. |
| `awaitWallet(options)` | `Promise<BuyToolResult \| null>`, with a Link wallet | Waits for the shopper's answer in Link, and confirms the cart once they approve. |
| `walletOutcome(message)` | `Promise<BuyWalletOutcome \| null>`, with a Link wallet | How a Link purchase ended, from a purchase message, with the line to post. |

`run`, `execute` and `handle` each return `JSON.stringify(buy.forModel(result))`. `handle` rejects a call with input outside the schema before anything reaches Agentcard. A call that fails rejects with a message that names no link, and `error.cause` keeps the original error for your logs. `answer` throws the `AgentcardApiError` itself.

Call `instantAck` or `instantReaction` the moment a message arrives, before your model runs. When either returns a reply, the tool sends none of its own for that turn, and the model reads `shopper_already_told_looking: true`.

## Frameworks

Pass `buy` as it is.

| Framework | Pass the tool | Who runs each call |
| - | - | - |
| Anthropic SDK, `client.beta.messages.toolRunner` | `tools: [buy]` | The tool runner. |
| Vercel AI SDK 7 | `tools: { buy }` | The SDK. |
| OpenAI SDK, OpenRouter's chat API, and any API that takes OpenAI's format | `tools: [buy.openai]` | Your loop, through `buy.handle`. |
| OpenRouter's agent SDK, `callModel` | `tools: [toOpenRouterTool(buy, { tool, z })]` | The SDK. |

`toOpenRouterTool(buy, { tool, z })` takes your own `tool` from `@openrouter/agent` and `z` from `zod`, so the package installs no dependencies. `toOpenRouterTool` accepts the tool or a turn. `toAnthropicTool(buy)` is deprecated and returns `buy` itself.

## The model's input

The model sends five fields and nothing else. The schema marks all five required and sets `additionalProperties` to `false`.

| Field | Type | Description |
| - | - | - |
| `ask` | `string` | What the shopper said, in their own words. |
| `confirm` | `boolean` | `true` only when the shopper said yes to the cart in the last result, asks to check out, says they added the card or approved, or asks for the approval link again. |
| `new_order` | `boolean` | `true` only when the shopper drops the cart to start a new order. |
| `product_id` | `string` or `null` | The `product_id` of the product the shopper picked from the last result's `products`. `null` when they picked none. |
| `store_id` | `string` or `null` | The `store_id` of the store the shopper picked from the last result's `stores`. `null` when they picked none. |

`parseBuyToolInput` accepts an object or its JSON text. The function trims `product_id` and `store_id`, reads an empty string as `null`, and throws a `TypeError` when both are set. Your own code may leave `product_id` and `store_id` out.

## BuyToolResult

`buy.answer` returns the whole answer for your code.

| Field | Type | Description |
| - | - | - |
| `status` | `BuyToolStatus` | Where the purchase stands. See [Status](#status). |
| `reply` | `string` | Agentcard's answer for the shopper, links included. |
| `messages` | `string[]` | The same answer as separate messages, cut at blank lines. |
| `cart` | `BuyCart` or `null` | The cart on the table. |
| `carts` | `BuyCart[]` | Every cart on the table, oldest first. |
| `products` | `BuyToolProduct[]` | The products the last search found. |
| `found_total` | `number`, optional | With `candidates: true`: how many products the search kept, inside the shopper's price limit. |
| `candidates` | `BuyToolProduct[]`, optional | With `candidates: true`: up to 16 products past the cards, in the search's order. None of them is in `products`. |
| `links` | `BuyToolLink[]` | The Vault, approval or store login link this answer needs. |
| `link_sent` | `boolean` | `true` when `sendLink` took every link in `links`. |
| `approval_expires_at` | `string` or `null` | When the approval link stops working, as an ISO 8601 timestamp. |
| `shopper_need_not_reply` | `boolean` | `true` when Agentcard tells the shopper how the order went. |
| `shopper_already_told_looking` | `boolean`, optional | `true` when this turn's reaction, the line Agentcard wrote for the search, or an instant reply reached the shopper. |
| `conversation_id` | `string` or `null` | The conversation. |
| `order_id` | `string` or `null` | The order this call placed. |
| `decline_code` | `string` or `null` | Why Agentcard did not buy. |
| `error_code` | `string` or `null` | A machine-readable failure. |
| `next_action` | `BuyNextAction` or `null` | The one step the shopper takes next. Only that step's link is in `links`. |
| `pick` | `BuyPick` or `null` | The product the model's `product_id` picked, and whether the cart now holds it. |
| `stores` | `BuyToolStore[]` | The stores the reply presents to choose from, at most eight. |
| `store_pick` | `BuyStorePick` or `null` | The store the call picked, and whether Agentcard selected it. |
| `hashes` | `string[]` | Every cart hash in this answer. |
| `cart_building` | `{ store, started_at }` or `null`, optional | The cart the store's checkout is still building. |
| `confirm_sent` | `true`, optional | Present when this call sent Agentcard a confirm: the shopper's yes, or the yes the tool carried past a step outside the chat. |
| `yes_carried` | `{ said_yes_to_cents, total_cents, currency, picked? }`, optional | Present when the call went ahead on a go-ahead the shopper already gave. See [Carry the go-ahead](#carry-the-go-ahead). |
| `choice` | `BuyChoice` or `null`, optional | The choice the reply asks the shopper to make, such as a sandwich's bread, with every value, its option id and its extra price. `null` when the reply asks none. |
| `search` | `BuySearchStatus` or `null`, optional | Every store the call's searches asked and where each stands. `null` when the call searched no store. See [BuySearchStatus](https://docs.agentcard.com/api-reference/commerce-sdk/agentcard-client.md#buysearchstatus). |
| `wallets` | `BuyWalletOption[]` or `null`, optional | With `wallets`: each wallet you offer, in the order to show them, with its button's `label` ("Your card" or "Stripe Link"), `fits`, and the `reason_text` to show beside one that cannot pay. |
| `approval` | `BuyApprovalStep` or `null`, optional | With `wallets`: the Approve purchase step to show, the same shape for both wallets. |
| `wallet_progress` | `{ wallet, approved, total }` or `null`, optional | While the shopper approves one Link payment per store: how many they approved, of how many. |
| `swipe` | `BuySwipe` or `null`, optional | With `wallets`: what a swipe right and a swipe left on the cart do now. |
| `wallet_fallback` | `BuyWalletFallback` or `null`, optional | After a wallet's payment failed with nothing charged: the buttons to show under `reply`, the other wallet first when it fits, then Try again. |
| `wallet_tip` | `{ text }` or `null`, optional | Once, after a Link purchase across several stores, when you offer the Vault: a note to show under the answer. |
| `envelope` | `Record<string, unknown>` | Agentcard's answer as it came. |

### Status

| `status` | What happened |
| - | - |
| `needs_input` | Agentcard asks the shopper something, or shows a cart. |
| `needs_card` | The shopper adds a card from a link before Agentcard can buy. |
| `approval_sent` | The shopper approves the purchase from a link. |
| `placing` | The shopper approved, and the order is going through. |
| `order_placed` | The order went through. |
| `declined` | Agentcard did not buy, and `reply` says why. |

### Waits

A call that lands while Agentcard is still placing the order pauses once for 12 seconds and reads the conversation. A call that finds the order already placed reads it at once. A request that takes Agentcard more than 110 seconds comes back before its cart is ready, so the tool reads the conversation every 5 seconds for up to a minute and returns the cart once Agentcard finishes. Pass `wait` to replace the timer between reads.

## BuyToolLink

Each link has a `kind`. The fields below belong to the kinds named in the second column.

| Field | Kinds | Type | Description |
| - | - | - | - |
| `kind` | all | `'vault'`, `'approval'`, `'store_login'`, `'product'` or `'store'` | What the link is. |
| `url` | all | `string` or `null` | The page the link opens. `null` only on a `product` link for a product with no page, such as a flight option. |
| `expiresAt` | all | `string` or `null` | When the link stops working, as an ISO 8601 timestamp. Always `null` on a `product` link. |
| `id` | `vault`, `approval`, `store_login` | `string`, optional | A stable id, such as `vault_1x9k2qd`, with no part of the URL in it. |
| `store` | `store_login`, `approval`, `product` | `string` or `null`, optional | The store the sign-in is for, the store whose cart the approval covers, or the store that sells the product, such as `Walmart`. |
| `storeDomain` | `product` | `string` or `null`, optional | The website of the store that sells the product, such as `walmart.com` or `jadeyoga.com`. `null` when Agentcard knows no website for the store. |
| `title` | `product`, `store` | `string`, optional | The product's or store's name. |
| `action` | `product` | `'buy'`, `'reserve'` or `'book'`, optional | What taking the product does, so a button can say it. |
| `price` | `product` | `string` or `null`, optional | The price as the shopper reads it, such as `\$12.99`, or `from \$10.69` for a product priced by a required choice. |
| `productId` | `product` | `string`, optional | Agentcard's id for the product, with no link in it. Hand it back as `product_id` to pick the product. |
| `imageUrl` | `product`, `store` | `string` or `null`, optional | The picture. `null` when Agentcard sent none. |
| `images` | `product` | `string[]`, optional | Every photo, `imageUrl` first, at most eight. |
| `storeId` | `store` | `string`, optional | Agentcard's id for the store. Hand it back as `store_id` to pick the store. |
| `etaMinutes` | `store` | `number` or `null`, optional | The delivery estimate in minutes. |

Show `storeDomain` as where the product comes from, never the host of `url`, which can be a tracking link.

The tool sends up to eight `product` links and eight `store` links per answer. The [Sending each link](https://docs.agentcard.com/opencommerce/guides/sending-each-link.md) guide shows how to render each kind.

## BuyToolProduct

| Field | Type | Description |
| - | - | - |
| `id` | `string` | The product's id. |
| `ref` | `string` or `null` | Agentcard's link-free id, which the model passes as `product_id`. |
| `name` | `string` | The product's name. |
| `action` | `'buy'`, `'reserve'` or `'book'` | What taking the product does. |
| `priceCents` | `number` or `null` | The price in the smallest unit of `currency`. |
| `priceFrom` | `true`, optional | Present when `priceCents` is the lowest price of a product priced by a required choice. |
| `currency` | `string` or `null` | The ISO 4217 code. |
| `imageUrl` | `string` or `null` | The main photo. |
| `images` | `string[]` | Every photo, `imageUrl` first. Empty when the product has none. |
| `store` | `string` or `null` | The store that sells it. |
| `storeDomain` | `string` or `null`, optional | The store's website, such as `walmart.com`. `null` when Agentcard knows none. |
| `url` | `string` or `null` | The product's page at its store. |
| `flight` | `BuyFlightItinerary`, optional | The itinerary, for a flight. |
| `linkSent` | `boolean` | `true` when the shopper holds this product's page. |
| `rank` | `number`, optional | With `candidates: true`: the product's place, from 1 across `products` and then `candidates`. |
| `why` | `{ code: string; text: string }[]`, optional | With `candidates: true`: why the product ranks there, such as `{ code: 'named_store', text: 'At the store you named' }`. Every product has at least one. |

`productAction(merchant)` returns `reserve` for `reservations`, `book` for `flights`, `hotels`, `cars`, `tickets`, `classes` and events, and `buy` for every other merchant. From 0.18.15 a product whose action is `book` or `reserve` gets a card through `sendLink` though it has no `url`, as a flight does.

## BuyToolStore

| Field | Type | Description |
| - | - | - |
| `id` | `string` | Agentcard's id for the store, which the model passes as `store_id`. |
| `name` | `string` | The store's name. |
| `url` | `string` or `null` | The store's page at the merchant. |
| `etaMinutes` | `number` or `null` | The delivery estimate in minutes. |
| `imageUrl` | `string` or `null` | The picture the store's card shows at the merchant. |
| `linkSent` | `boolean` | `true` when the shopper holds this store's page. |

## Rank the products yourself

Pass `candidates: true` to get the products behind the cards, so your app can rank them again against what it knows, such as a camera frame or the shopper's past orders, with no second search:

```ts theme={null}
const buy = buyTool({ agentcard, externalUserId: shopper.id, candidates: true });
const result = await buy.answer({ ask: 'running shoes under $100', confirm: false, new_order: false });
const ranked = rerank([...result.products, ...(result.candidates ?? [])], cameraFrame);
```

The answer then carries `found_total`, such as `23`, and up to 16 `candidates`. Every product and candidate carries `rank` and `why`:

```json theme={null}
{
  "name": "Trail Running Shoes",
  "store": "REI",
  "rank": 1,
  "why": [
    { "code": "named_store", "text": "At the store you named" },
    { "code": "price_read_now", "text": "Price and stock read at the store just now" }
  ]
}
```

Show `text` to the shopper as it is, or read `code` to rank. A code this version does not list can appear later, so treat an unknown code as a reason without weight.

| Code | Text |
| - | - |
| `named_store` | At the store you named |
| `kind_matches` | Matches the kind of product you asked for |
| `has_options` | Has the size and colour you asked for |
| `other_option` | A different size, colour or count than you asked for |
| `option_sold_out` | Sold out in the size or colour you asked for |
| `price_read_now` | Price and stock read at the store just now |
| `pays_here` | You can buy it here |
| `cannot_pay_here` | Buy it on the store's own site |
| `ships_elsewhere` | Does not ship to your country |
| `found_for_ask` | Found for what you asked for |

A pick, a confirm and a restaurant menu carry none of these fields. Your model never reads them: `forModel` leaves them out, so the model talks about the cards as before.

## What the model reads

`buy.forModel(result)` returns `BuyToolModelView`, the answer with every link taken out. An address with a path or a scheme is removed, and a bare one, such as `walmart.com`, reads as the site's name.

| Field | Type | Description |
| - | - | - |
| `status` | `BuyToolStatus` | See [Status](#status). |
| `next_action` | `BuyNextAction` or `null` | The one thing to ask the shopper for in this message. |
| `cart_building` | `{ store: string }`, optional | Set while the store's checkout builds the cart. |
| `reply` | `string` | Agentcard's answer, with every link taken out. |
| `cart` | `BuyToolModelCart` or `null` | The newest cart. |
| `carts` | `BuyToolModelCart[]` | Every cart on the table, the newest last. |
| `grand_totals` | `BuyToolGrandTotal[]` | What the carts add up to, one entry per currency. Empty when no cart is on the table. |
| `products` | `BuyToolModelProduct[]` | Each with `product_id`, `name`, `store`, `price` and `link_sent`. |
| `approval_expires_at` | `string` or `null` | When the approval link stops working. |
| `link_expires_in` | `string` or `null` | How long the newest link still works, in words such as `about 24 hours`. |
| `shopper_need_not_reply` | `boolean` | `true` when the shopper need not reply. |
| `shopper_already_told_looking` | `boolean` | `true` when the shopper already knows the request is being worked on. |
| `link_sent` | `boolean` | `true` when the shopper already has the link this answer needed. |
| `choice` | `{ question, groups }`, optional | The choice the reply asks the shopper to make. Each group has `name`, `required` and `options`, and each option is its label with its extra price, such as `Gluten-free bread (+$2.46)`. |
| `yes_carried` | `{ said_yes_to, total, total_changed, picked? }`, optional | Present when the answer went ahead on a go-ahead the shopper already gave. Never ask for their yes again. |
| `links_sent` | `Array<'vault' \| 'approval' \| 'store_login'>` | Which links went out with this answer. |
| `product_links_sent` | `number` | How many products the shopper holds as cards. |
| `pick` | `{ product_id, in_cart }` or `null` | The product this call picked. |
| `stores` | `BuyToolModelStore[]` | Each with `store_id`, `name`, `eta_minutes` and `link_sent`. |
| `store_links_sent` | `number` | How many store pages the shopper holds. |
| `store_pick` | `{ store_id, selected }` or `null` | The store this call picked. |

`BuyToolModelCart` has `store`, `items`, `fees`, `fee_lines`, `tip`, `total`, `total_is_estimate`, `total_leaves_out` and `max_charge`. Each item has `product_id`, `name`, `qty`, `price`, `line_total`, `options` and `variant`. Prices are text such as `\$13.31`. While `total_is_estimate` is `true`, `total_leaves_out` names what the store adds at checkout, such as `tax and shipping or delivery, which the store adds at checkout`, and leaves out a part a fee line already holds. A cart the shopper picks up never names shipping or delivery there. Once the store prices the cart, `total_leaves_out` is `null`.

Show `grand_totals` when the shopper buys from more than one store. Each entry has `amount`, the sum as text, `amount_cents`, the sum in the currency's smallest unit, `currency`, `is_estimate`, `leaves_out` and `stores`, the number of carts it adds. Each store's total already holds its tip, fees and tax, so the sum counts each once. Carts in two currencies give two entries, and they are never added together. `is_estimate` is `true` when any store's total is an estimate, and `leaves_out` then says what those stores add at checkout.

## Standalone helpers

The package root exports the functions the tool uses, for a loop that reads results itself.

| Export | Description |
| - | - |
| `BUY_TOOL_NAME` | `buy`. |
| `BUY_TOOL_DESCRIPTION` | The rules the model follows, as one string. |
| `buyToolDefinition()` | A fresh copy of the tool's name, description and input schema. |
| `parseBuyToolInput(value)` | Checks the model's input and returns `BuyToolInput`. Throws a `TypeError` the model can act on. |
| `forModel(result)` | The model's view of a `BuyToolResult`. |
| `grandTotals(carts)` | What a list of `BuyCart`s adds up to, one `BuyToolGrandTotal` per currency, as `grand_totals` reads. |
| `forModelError(error)` | The error's message with every link taken out, and the original on `cause`. A `TypeError` stays a `TypeError`. Hand errors from `buy.answer` to it before a model reads them. |
| `replyAsWritten(result, options)` | Agentcard's reply when the answer only asks the shopper something, else `null`. It leaves out the lists of products the cards show, lists the rest as `• ` bullets, and lists a `choice` one value per line. Pass `{ textingStyle: true }` for the texting style. |
| `stepAsWritten(result)` | The step's fixed short line when the answer's next step is a link the shopper holds, else `null`. See [Read the step lines](#read-the-step-lines). |
| `withoutCardList(reply, cards)` | The reply without the lists of products and stores whose cards went out. |
| `choiceLines(choice)` | A `choice`'s values, one `• ` line each with its extra price. |
| `withChoice(text, choice)` | The text with the choice's values listed one per line under its question. |
| `textingStyle(text)` | The text in a chat's texting style. |
| `asBullets(text)` | The text with every list as `• ` bullets. |
| `stripLinks(text)` | The text with every link taken out. |
| `instantAck(text, options)` | The instant reply for a message, or `null`. Takes `previous`, `nextAction`, `asked` and `stores` as options. |
| `instantReaction(text, options)` | `👀`, or `null`, decided as `instantAck` decides. |
| `ACK_REACTION` | `👀`. |
| `keepsYes(text)` | `true` when the shopper's words leave a yes they already gave standing, such as `ok` or `done`. |
| `ackFor` | The earlier name of `instantAck`. |

The `instantAck` options work as follows: `previous` is the reply you sent last, so the next one comes from another template. `nextAction` is the last answer's `next_action`. `asked` is the last message the shopper read. `stores` holds the names of the stores the last answer listed.

```ts ack.ts theme={null}
import { instantAck, instantReaction } from '@agent-cards/commerce-sdk';

instantAck('can you find me usb-c cables under $20'); // 'on it, looking for usb-c cables under $20', or another template
instantReaction('yes'); // null
```

The first call returns a reply that names the request, and the second returns `null` because `yes` starts no search.

### Show bullets and texting style

`replyAsWritten(result)`, `turn.replyAsWritten` and each message `onText` hears show every list as lines that start with `• `. That covers lines marked `- `, `* `, `• `, `1. ` or `1) `, and two or more short lines in a row after a line that ends in `:` or `?`. A short line has at most 60 characters and 8 words, and does not end in `.`, `!`, `?`, `:` or `;`.

The lead-in line stays as written, and so do prose, a single line, and a line indented under a bullet. In a streamed message, choices that open the message count as a list when the message before it ended in `:` or `?`.

A numbered list keeps its numbers where the shopper can answer with one, such as `number 3`. In `replyAsWritten`, that is a list whose items name the answer's products or stores. In a message `onText` hears, every numbered list keeps its numbers, because the cards it names sit before it.

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

asBullets('which bread do you want?\n\nSourdough\nWhole wheat');
// 'which bread do you want?\n\n• Sourdough\n• Whole wheat'
```

`textingStyle(text)` writes the text the way a chat does, with the bullets kept. It writes the first word of each sentence and the word "I" in lowercase, takes out markdown headings, bold, and a lone `- ` or `* ` marker, and turns spaced dashes into commas. A capital inside a sentence stays, and so does an all-caps word such as `USB`, a capital after an abbreviation such as `St.`, and the first word of a list line, which is usually a name.

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

textingStyle('**I found it.** Pick up at St. Louis Market - the USB cable ships today. Which one?\n- Anker cable\n- Onn cable');
// 'i found it. pick up at St. Louis Market, the USB cable ships today. which one?\n• Anker cable\n• Onn cable'
```

Pass `textingStyle: true` to `buyTool` or `buy.turn` to get `turn.replyAsWritten` and each `onText` message in that style. `replyAsWritten(result, { textingStyle: true })` does the same for one answer. The tool's description also tells your model to write the options it lists, such as sizes, breads or times, one per line, each starting with `• `, in the same paragraph as the question.

### Leave out the lists the cards show

`replyAsWritten(result)` and `turn.replyAsWritten` drop the products and stores the reply lists again when their cards went out, so the shopper never reads a card twice. `withoutCardList(reply, cards)` does the same for any reply. A card is the product or store name, or the name with its price, such as `{ name: 'Mini Soaps Gift Box', price: '$58.00' }`.

The function drops:

* each list line that names a card, with or without a marker, up to the question on the line;
* a list written on one line, item by item, such as `1) a mug ($19.00); 2) a soap box ($58.00)`;
* the line that leads into a list whose items all went, such as `here are a few:`;
* a sentence that points at a number the list gave, such as `#2 ships fastest`, and a sentence that goes on to more of the list, such as `other 6-packs are ...`.

An item for a product no card shows stays, with its lead-in. A reply may recommend one or two products in words, and those sentences stay.

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

withoutCardList(
  'i found a few options: 1) Sarcastic Coworker Mug ($19.00 at Target); 2) Lavender Candle ($24.00 at Etsy); 3) Mini Soaps Gift Box ($58.00). which one?',
  [{ name: 'Sarcastic Coworker Mug, Funny Gift', price: '$19.00' }, { name: 'Mini Soaps Gift Box', price: '$58.00' }],
);
// 'i found a few options: 2) Lavender Candle ($24.00 at Etsy). which one?'
```

The candle has no card, so its item stays. When nothing of the reply is left, `replyAsWritten` is `null` and your model words the answer.

### List a choice one per line

When the reply asks the shopper to choose, such as a sandwich's bread or a shirt's size, the answer carries `choice` with every value. `replyAsWritten(result)` and `turn.replyAsWritten` list the values one per line under the question, each starting with `• ` and followed by its extra price when it has one, even when Agentcard's reply names them inside a sentence.

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

withChoice('before i add the Chicken Pesto Caprese, which bread do you want?', result.choice);
// 'before i add the Chicken Pesto Caprese, which bread do you want?\n• Ciabatta\n• Sourdough\n• Gluten-free bread (+$2.46)'
```

`choiceLines(result.choice)` returns the lines alone. A choice of more than one group leads each group's lines with its name, such as `Size:`. When the text already lists a value on its own line, that line stays, a priced value that leaves its price out gets it at the end of its line, and the values no line holds follow the last value of their group. A bracket that holds only the values, such as `(Size: 3 oz, 4.375 oz)`, goes, because the list replaces it. A reply that asks nothing gets the list at its end.

A message that `onText` hears works the same way. When the messages the shopper read do not list every value one per line with its price, the tool sends one more message with the lines. If that message fails to send, the model words the answer.

### Read the step lines

When the answer's next step is a link the shopper holds, `replyAsWritten(result)` returns the step's fixed short line, and `stepAsWritten(result)` returns it alone. The link follows the line.

| `next_action` | The line |
| - | - |
| `add_card` | `add your card to place the order` |
| `store_login` | `sign in to Mendocino Farms to place your order` |
| `approve` | `approve the payment to place your order (up to $19.02)`, naming the most the shopper can be charged when the cart states it |

After the shopper's own words put the cart together, a line about the cart comes first as its own message, such as `1 Chicken Pesto Caprese from Mendocino Farms, $17.89`, then a blank line, then the ask. When the shopper has carts at several stores, the card they add pays for all of them, so the line names each store's cart on its own line, starting with `• `:

```text theme={null}
• 1 Kitchen Towels from Walmart, about $14.72 before tax and shipping or delivery
• 1 Dawn Dish Spray from Amazon, about $11.54 before tax and shipping or delivery

add your card to place the order
```

The cart line comes before an `add_card` or a `store_login` ask, and never before `approve`, a confirm, or a go-ahead the tool carried. When the total changed after the go-ahead, the ask opens with the new total, such as `it's $17.89 with fees and tax now. approve the payment to place your order (up to $19.02)`, or `it's about $17.89 now.` for an estimate.

When one approval pays every seller, the answer carries `basket`, and the `approve` line names each seller with its total and the card hold, then asks once for the approval's total and hold. A store that charges its final amount holds the card above its total, and the shopper pays only the final amount:

```text theme={null}
• Amazon: $10.15, card held up to $21.15
• Walmart: $13.31, card held up to $24.40

approve $23.46 once to place both orders (card held up to $45.55, you pay only the final amounts)
```

A seller the approval leaves out reads `not in this approval`, and the approval charges nothing there. Agentcard's `reply` says why the seller was left out, such as a cart that changed after the shopper's yes, and what the shopper does next. A seller paid exactly its total shows no hold.

`stepAsWritten` returns `null` when the link did not go out, when the shopper already read Agentcard's ask through `onText`, when a card or approval step has no cart or basket to place, and when the answer also showed products.

### Carry the go-ahead

After the shopper picks something, and then saves a card or signs in to the store, the next step goes straight to the approval link. The shopper does not say yes again. The approval link is their consent, because it names the most they can be charged and the order goes in only once they approve it there.

The tool carries the go-ahead in two cases, and `buy.nextStep` confirms the cart by its hash:

* The shopper said yes to the cart in the chat, and that confirm stopped for the card or the sign-in. `yes_carried` is set.
* The shopper picked what is in the cart, such as a product, a tap on its card, or a request to buy it, and answered only the checkout's questions since, such as an address, a phone number, or a name. `yes_carried` is set with `picked: true`, and `said_yes_to_cents` is the total the chat last showed.

The cart must hold the same items at the same store. A total that moved because the store priced its fees and tax in keeps the go-ahead, and `total_changed` reads `true`. Any other shopper message, a cart that changed, and a declined approval take the go-ahead back. `confirm_sent` reads `true` on the call that sent the confirm.


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