@tote/agent
On this page (10 sections)
Model-agnostic Tote agent loop, the five Tote tools and deterministic constraint checking. Design: ADR-001, decisions 5 to 9.
On npm: tote-agent-loop. Release steps: scripts/release.md.
Status: loop, tools and constraint checks implemented and tested against fakes (T-05).
Carts are addressed by CartRef (T-04b), and start_checkout calls core's createCheckout
and branches on its typed Checkout.outcome. No real model adapter yet.
Use
import { createHandoffVault, createUcpClient } from "@tote/core";
import { createToteTools, DEFAULT_RUN_LIMITS, runAgent } from "@tote/agent";
const vault = createHandoffVault();
const tools = createToteTools({ ucp: createUcpClient(config), vault });
const result = await runAgent({
task: { prompt: "Trail running shoes, size 10, under 100.00 USD" },
model, // an OptedOutModelAdapter: trainingOptOut "sent"
shopScope: { configuredShops: [], defaultSearchTarget: { kind: "global" } },
tools,
limits: DEFAULT_RUN_LIMITS, // 12 steps, 30 tool calls, 120 s
overridePolicy: { mode: "deny" }, // or { mode: "ask_buyer", confirm }
onEvent: (event) => progress(event),
});
// result.handoffs holds HandoffRefs. The surface shows vault.resolve(ref) to the buyer.
Exports
| Export | What it does |
|---|---|
runAgent(options) | Runs one task. ModelAdapter.step() is the only model seam. Throws AgentError before the first step for a non-opted-out adapter or bad limits. |
createToteTools({ ucp, vault }) | search, get_product, compare, build_cart, start_checkout. One definition for the loop and, later, the MCP server. |
createSession(options) | Per-run state. seenShops is seeded from RunShopScope only. Tools refuse a session not made here. |
extractConstraints(task) | Deterministic: task constraints, then the prompt, then preferences. |
checkConstraints(constraints, p, v, shop) | met, unmet or unknown per constraint, and a verdict. |
DEFAULT_RUN_LIMITS, SYSTEM_PROMPT | Fixed defaults. |
Safety properties
- Product text is
UntrustedText. Onlysrc/untrusted.tsreads it, to build the envelope{"tool", "ok", "untrusted_data"}for the model and to compare option and vendor values for the checker (a boolean, never text). Error envelopes add"error"with fixed Tote text; merchant messages stay underuntrusted_data. - Tools accept only ids returned in structured fields earlier in the session, and only
shops from configuration or
Variant.shop. Each variant keeps its first shop binding; a later result naming another shop makescompareandbuild_cartrefuse it withshop_mismatch.SessionStateexposes read-only views at runtime.build_carttakes one shop per call and refuses a variant bound to another shop (shop_mismatch) or with no shop (unknown_shop). build_cartrefuses any variant whose verdict is notsatisfiesorsatisfies_pending_shipping(only ship_to deferred, see below). WithacceptConstraintGaps, policydenyreturnsoverride_deniedand recordsoverride_attempted; policyask_buyerbuilds only whenconfirmresolves exactlytrue.- The model never sees a
CartId. Core'sCartIdis a redacted capability (a cart id with?key=), sobuild_cartputs it into the session'sCartRefRegistry(createCartRefRegistry()from core, one per session) and returns only an opaquecartRef(128 random bits).SessionState.carts,CartSummaryandstart_checkoutuse the sameCartRef.start_checkoutaccepts only a ref this session's registry issued; a raw cart id, an invented ref or a ref typed in product text getsunknown_cart. start_checkoutreturns Tote's outcome kind (escalation,ready,incomplete,canceledorother), never the merchant's raw status or the checkout id. Anescalationalways yields aHandoffRefto the escalation'scontinue_url(required by type), recorded inAgentRunResult.handoffsand sent as ahandoffevent, so the buyer gets it even if the model's answer leaves it out.readyandincompletegive a handoff when the checkout has acontinue_url;canceledandothergive none. Tote never completes a checkout.- One merchant checkout per cart per session. A repeated
start_checkoutfor the samecartRef(for example because product text asks to retry) returns the stored output and the sameHandoffRefwithout calling core again; concurrent calls share one request. A failed attempt is not kept, so arate_limitederror can be retried. - On an Anonymous client,
start_checkoutreturnscheckout_requires_credentialsbefore any request: checkout needsSHOPIFY_CLIENT_IDandSHOPIFY_CLIENT_SECRET, and the buyer can still continue from the cart handoff. continue_urlgoes into theHandoffVault. The model, events andAgentRunResultsee only aHandoffRef. Merchant text that repeats a knowncontinue_urlis redacted before it reaches the model.- Money is compared in minor units, in one currency only. A different currency is
unknown.
Constraint extraction
Deterministic, and fail closed. Precedence per key: task.constraints, then the prompt,
then preferences.
- Price ceiling. Read as
max_priceonly when every amount in the prompt that looks like a price is certain: a ceiling word right before it ("under", "below", "max", "up to", "at most", "no more than", "budget"), a plain decimal (no "1,299" or "1 299"), exactly one upper-case ISO 4217 code and no symbol ("USD", not "usd", "$" or "$100 CAD"), and one amount only. Any amount that is not certain becomes{ kind: "max_price_unparsed", phrase }, which always checks asunknown, so no candidate counts as within budget andbuild_cartneeds an override. Examples: "up to 3 TVs under 500 USD" and "under 1,299 USD" are unparsed; "under 100.00 USD" and "max PLN 200" are read. - Catch-all. If no ceiling was read with certainty and the prompt contains any budget
signal, the ceiling is recorded as
max_price_unparsedwith the noteprice_unclear. Signals: ceiling and budget words ("budget", "within", "max", "under", "below", "up to", "at most", "less than", "no more than", "cheaper than", "or less"), currency words ("dollars", "bucks", "euros", "pounds", "quid", "zl", "zloty", "yen", "francs", "kronor", "rupees", "pesos", "cents" and similar), the symbols$ € £ ¥, and amounts in words ("hundred", "thousand"). So "200 dollars max", "within 300 euros" and "less than five hundred USD" are never silently dropped. The cost is false positives, for example "Under Armour" or "within 2 days": the buyer is asked to restate the budget, and the cart needs an override. - A three-letter lower-case word counts as a currency code only right after a ceiling word ("under 100 usd", "max eur 50"). Words such as "pen", "gel", "all", "top" or "cup" next to a number ("set of 2 pen refills", "top 3 blenders") are never read as a price.
- Price notes:
price_currency_unclear,price_number_unclear,price_phrase_unclear,price_ambiguous,price_unclear. - Size. Only explicit size phrases. Numbers need "size", "EU", "US" or "UK" before them,
or "EU", "US" or "UK" after them: "size 44", "size 10.5", "EU 44", "size EU 43",
"UK 9", "US 10.5", "43 EU". Halves may be written "42.5" or "42,5". Region codes on
their own must be upper case ("us 10" is not a size); after "size" any case works
("size eu 43"). A size with a region becomes
{ kind: "variant_option", name: "Size", value: "43", system: "EU" }. Letter sizes (XXS to XXXL, 2XL to 5XL) need "size" next to them or "in" before them ("size XL", "XL size", "in XL"). "iPhone XS", "Pixel XL", "an XL hoodie", "queen size", "travel size" and "one size fits all" never make a Size constraint. Several different sizes or systems, or "size" followed by something that is not a size, give no constraint and the notesize_unclear. A number after "EU", "US" or "UK" is never the quantity (T-06b). "US Men's size 10.5", "US Women's size 8", "UK Mens size 9" and "EU men's size 44" (region code in upper case) give the size in that system (T-05i); "us men's size 10" in lower case gives size 10 with no system. - Size matching (T-05c), fail closed, no conversion between systems: a size with a system is "met" or "unmet" only against an option value that names the same system ("EU 43", "43 EU", "EU43"); an option in another system, with no system ("43") or with any other text is "unknown". A size without a system compares as a number with a plain number option ("43", "42,5") and is "unknown" against an option that names a system. Letter sizes keep plain equality. Exception (lead decision T-09d B): an EU size is compared with a bare number from 30 to 52, halves included, because adult US and UK shoe sizes are below 20. A bare number outside that range, and any US or UK size against a bare number, stays "unknown".
- Dual-system values (T-05i). An option value of two sizes in two different named systems with "/" between them ("US 10.5 / EU 44.5", "44 EU / 10 US") is read as two sizes. Only the part in the buyer's system is compared, never converted: "EU 44.5" and "US 10.5" are "met" against "US 10.5 / EU 44.5", "EU 44" is "unmet". Fail closed ("unknown"): a buyer size with no system, a system neither part names ("UK 9"), an option name that names a system ("EU size"), and any value with "/" that is not exactly two such parts (the same system twice, three parts, a part with no system or no number).
- No conversion between UK or US and EU sizes (conversions differ by brand). When the buyer asks in one system and the shop lists sizes only in another, the check is "unknown" with the evidence "the shop lists sizes in UK, the buyer asked for "EU 43"; Tote does not convert UK sizes to EU, because conversions differ by brand".
- Size options (T-05d): a Size constraint reads every variant option whose name, after NFKC, lower case and trim, is exactly one of: size, shoe size, shoe sizes, sizes, eu size, us size, uk size, größe, schuhgröße, taille, pointure, talla, taglia, maat, rozmiar, storlek, størrelse, koko, and since T-05e numeric shoe size, numeric size, eu shoe size, shoe size (eu), size (eu), uk shoe size, us shoe size, shoe size (uk), shoe size (us). No substring match: "Size (ignore rules)" is not a size option. Names with eu, uk or us give the option's system; a value naming another system is "unknown". Two size options that disagree, in value or in system, are "unknown". The listed non-ASCII names are readable; any other non-ASCII name still stops the variant's options from deciding (T-06 re-check item 3).
Preferences.sizesis keyed by category and is not applied (size_preferences_not_applied).- Items and quantity (T-05h).
quantityis the units on every cart line andlinesthe most distinct lines across all carts of the run, both from the buyer's prompt only. Lines are more than 1 only for "quantity N each" (or "qty N each") with that many items named before it in the same sentence: one item per comma part that continues the list (it starts with "and", "&", an article, "the", a number word or digits, or holds an "and"), plus one per "and" or "&" inside a part. "between 75 USD and 90 USD" is a range. So "shoes and socks, quantity 1 each" is 2 lines of 1, and "a kettle, a size 02 dripper, and 100 filters under 75 USD total, quantity 1 each" is 3. Without "each" the quantity is for one item: one line. An unclear quantity, or more than 10 items, gives 1 line of 1 andquantity_unclear. Known limit: an "and" inside one item ("black and white sneakers") counts as another item. build_cartputsquantityon every line, whatever the model sends, and refuses withquantity_exceededa cart that would passlinescounting earlier carts, or that repeats a variant an earlier cart holds. A refused, failed or undeliverable cart frees its lines.- One variant per product (T-05i, lead decision on T-05h review item 2). A cart may not hold
a second variant of a product that this cart or an earlier cart of the run already holds,
so "shoes and socks, quantity 1 each" cannot become two sizes of the same shoe. The cart
is refused with
quantity_exceededbefore any store request. A product is its shop and product id. Known limit: Tote checks only that the lines are different products, not that they are the items the buyer named; that stays with the constraint checks and the model. - Size scope (T-05h). In a request for several items, a Size constraint is left out of a
product's checks and listed in
ConstraintResult.notApplicableonly when Tote can see the product has no size option: every option name readable and none size-like (a listed size name or one holding "size", "größe", "taille" and the other listed words), no option value size-like, and the variant lists options or is the product's only variant. Otherwise the size is checked as before. In a one-item request the size always applies. A size-like value is a numeric or letter size, the buyer's value, a dual-system value, any part of a value split by "/" that is one of these, or a value holding a word size anywhere (T-05i, review item 1): small, medium, large (also "Extra Large", "X-Large"), petite, regular, tall, one size, os, plus, big, youth, junior, kid, toddler, infant, baby, ages such as "4-5 years" or "18 months", and "2T". So "Fit: Large" or "Title: Small" keeps the size check. A false match only keeps a check. - A task's own
max_price(ShoppingTask.constraints) drops the prompt's price notes, so the model is not told the budget could not be read (T-05h). searchandget_productshow each product'sdescription(at mostDESCRIPTION_MAX, 1,000 code points, after redaction) and each variant'soptions(at mostMAX_VIEW_OPTIONS, 20), only insideuntrusted_data. They never decide a constraint.
Notes reach the caller and the buyer three ways: a constraint_notes event before the
first step, AgentRunResult.extractionNotes, and fixed Tote text in the first model
message asking the model to tell the buyer and ask them to restate it.
Model adapters
src/adapters/ holds one OptedOutModelAdapter per provider in the Index v0 matrix
(T-05b), plus OpenRouter (T-09c). Each one calls the provider's AI SDK model (LanguageModelV4.doGenerate) once per
step(): no SDK tool loop, no SDK retries, no telemetry, no AI Gateway. A fetch guard
refuses a second HTTP request inside one attempt, because @ai-sdk/google would otherwise
continue a CONTINUATION response on its own. All of it is exported from @tote/agent.
import { createAnthropicAdapter, INDEX_V0_PRESETS, readProviderKey } from "./adapters/index.js";
process.loadEnvFile(); // the surface does this once at start
const preset = INDEX_V0_PRESETS["claude-sonnet-5-5"];
const model = createAnthropicAdapter({
model: "claude-sonnet-5-5",
apiKey: readProviderKey("anthropic"), // ANTHROPIC_API_KEY through core parseSecret
effort: preset.effort,
pricing: preset.pricing,
});
const output = await model.step(input, signal); // output.metrics: tokens, ms, attempts, cost
| Factory | Endpoint | Request settings (methodology section 7) | trainingOptOut: "sent" because |
|---|---|---|---|
createAnthropicAdapter | https://api.anthropic.com/v1/messages | output_config.effort, max_tokens 128000, anthropic-version: 2026-10-21. No temperature, top_p, top_k or thinking. | API terms: "Anthropic may not train models on Customer Content from Services" (Commercial Terms, section B). No per-request retention field exists. |
createOpenAIAdapter | https://api.openai.com/v1/responses | reasoning.effort, store: false. No temperature, top_p or reasoning summary. | Sends store: false (default is true, 30-day storage, Responses create); API data is not used for training (Your data). |
createGoogleAdapter | https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent | generationConfig.thinkingConfig.thinkingLevel. No temperature or topP. | API terms, Paid Services only: prompts and responses are not used to improve Google products (Gemini API terms). The config requires tier: "paid", the operator's statement that the key's Cloud project has active billing. |
All pages fetched 2026-11-12. Base URLs are pinned, so ANTHROPIC_BASE_URL or
OPENAI_BASE_URL in the environment cannot redirect prompts or keys.
OpenRouter
createOpenRouterAdapter({ model, apiKey }) calls
https://openrouter.ai/api/v1/chat/completions through the chat model of @ai-sdk/openai
(OpenAI-compatible, no extra dependency). model is an OpenRouter slug such as
anthropic/claude-haiku-5.5, optionally with a variant suffix such as :free. The key is
OPENROUTER_API_KEY. No sampling fields and no max_tokens are sent.
Data controls. A fetch wrapper writes "provider": {"data_collection": "deny", "zdr": true}
into the JSON body of every request, retries included, and replaces any provider object
the SDK might build. A body that is not a JSON object is refused before it is sent.
trainingOptOut: "sent" rests on zdr, which the docs state is enforced per request
(all pages fetched 2026-11-19):
zdr: "Restrict routing to only ZDR (Zero Data Retention) endpoints." (Provider routing) and "Whenzdris set totrue, the request will only be routed to ZDR endpoints," "plus Safety Retention endpoints if your settings allow them" (ZDR). Safety Retention is "only to detect, investigate, and prevent abuse".data_collection: "deny": "Control whether to use providers that may store data." (default"allow", Provider routing). Account level: "If you opt out of training in your account settings, OpenRouter will not route to providers that train." (Privacy and logging).
A model with no endpoint that meets these rules fails with HTTP 503, "There is no available
model provider that meets your routing requirements"
(Errors); the adapter
retries it like any 5xx and then reports provider_unavailable. HTTP 402 (no credits) maps
to insufficient_credits and is never retried.
Cost. "Full usage details are always included automatically in every response", and
usage.cost is "The total amount charged to your account"
(Usage accounting). The adapter
reports it as cost: { status: "reported", credits } in OpenRouter credits, or
not_reported when the response has none. It does not convert credits to USD.
No HTTP-Referer or X-OpenRouter-Title header is sent: they create a public app page in
OpenRouter's rankings (App attribution).
Behaviour shared by all four:
- Keys come from
ANTHROPIC_API_KEY,OPENAI_API_KEY,GOOGLE_API_KEY,OPENROUTER_API_KEYthroughreadProviderKey, which uses coreparseSecret(redacted, registered with the scrubber). A missing key throwsModelAdapterErrorconfignaming the variable. - Retries: core's
DEFAULT_RETRY_POLICY(4 attempts, full jitter from 250 ms, 8 s cap).Retry-Afteris honored; one above 30 s fails at once withrate_limited. 408, 409, 429 and 5xx and network failures are retried; 400, 401, 402, 403, 404 are not. - Timeout: 120 s per attempt (the Index per-turn limit), plus the loop's own signal.
- Errors:
ModelAdapterErrorwith a code (auth,insufficient_credits,rate_limited,invalid_request,provider_unavailable,timeout,aborted,output_truncated,content_filtered,invalid_response,unexpected_request,config). Messages are fixed Tote text; the provider's response body, the request body and the key never reach them. - Metrics per step (
output.metrics): input, output, reasoning and cached tokens; wall time with retries; attempts; cost from the configuredModelPricing, with a long-prompt rate and avalidThroughdate (after it, cost israte_expiredinstead of a wrong number). OpenRouter reports its own charged cost instead (see above).INDEX_V0_PRESETSholds the six Index v0 models' effort and prices from methodology sections 7 and 9. - Reasoning state: the adapter keeps each tool-calling assistant turn (Anthropic thinking
signatures, Gemini
thoughtSignature, OpenAI encrypted reasoning) in memory, keyed by tool call ids, and resends it on the next step. The loop'sModelMessagehas no field for it. - Model text is never parsed for tool calls; only the provider's structured tool calls count. Unknown tool names and malformed input go to the loop unchanged, which refuses them.
Fields the SDK adds on its own, pinned by tests: Anthropic anthropic-beta: structured-outputs-2025-11-13 (inert without strict or output_format); OpenAI
strict: false per tool and include: ["reasoning.encrypted_content"]; Gemini sends the
schema as parametersJsonSchema.
Out of stock (T-05f)
When a cart leaves a requested variant out, every other line is unchanged, and a merchant
message has the code merchandise_out_of_stock (exact code, never content), build_cart
returns out_of_stock instead of cart_mismatch. Tote cancels the cart, releases its
units, and marks the variant out of stock for the run: build_cart refuses it without a
store call, compare results carry outOfStock: true, and search and get_product show it
with available: false. Any other empty or changed cart stays cart_mismatch.
Product page (get_product, T-05d)
- get_product sends
context.address_country: the ship_to constraint's country, else the country of the search that returned the product. Prices then come in the same currency as search. - The product page record wins: once get_product returned a variant, compare, build_cart and later search results use its price, and a stored compare result is redone. When the search price differed, the max_price evidence says so ("search showed 129.00 EUR, the product page 145.00 EUR, and Tote uses the product page price").
- A get_product response with no product Tote can use (only merchant messages, or only
external offers) returns
product_unavailable, a normal outcome for that product. The CLI does not count it as a failure, so the exit code follows the run outcome. - Size follow-up (T-03d). With a Size constraint, when the product page lists exactly one
size option (listed names), the buyer's size is matched against its values in
Product.optionswith the size rules above. Exactly one matching value that is notavailable: falseorexists: falseleads to one more get_product withselected= that value plus the selected values of the other options (Product.selected), as core's UntrustedText, so core sends Shopify's exact labels and the agent never reads them. Only variants of that response whose own options carry the size are recorded and returned. A matching value withavailableorexistsfalse, or values that are all other sizes, make the Size check "unmet" for every variant of the product. No follow-up when the match is unclear (no or several matching values, unknown values, several size options), and at most one per product per run.
Known limits
deliver_byandfree_returnsare alwaysunknown: core does not expose delivery or return fields yet (ADR-001 Q-2). Any such constraint makes every candidateincomplete.ship_toisdeferred(lead decision T-05e): catalog data has no shipping field, so delivery is confirmed by the merchant after the buyer enters an address at checkout. It is nevermet, from catalog, product or merchant text. A verdict whose only non-met checks are deferred issatisfies_pending_shipping; build_cart and start_checkout proceed without an override, and the system prompt tells the model to say delivery is confirmed at checkout. Search still sendsaddress_country. It becomesunmetfor a variant whose cart or checkout carried the merchant message codeaddress_undeliverable("Shopify can't find a delivery option for the destination.", https://shopify.dev/docs/agents/carts-and-checkout/checkout-errors; UCP Standard Errors "Cannot deliver to the provided address"). Only that structured code counts; merchant text is never matched. Tote then cancels the checkout and the cart, makes no checkout handoff, withdraws the cart's handoff (eventhandoff_withdrawn, and it leavesAgentRunResult.handoffsandcarts), releases the cart's units and returns the tool errorundeliverable. build_cart refuses that variant for the rest of the run, with or without aship_toconstraint. After 3 such offers in a run (the first and 2 more), build_cart returnsundeliverable_limit.- A checkout with the merchant message code
delivery_address_requiredhas no delivery address yet. Live checkouts without an address also carrydelivery_no_delivery_available(lead trace 2026-11-20), so neither code means the items cannot ship, and ship_to staysunknown. start_checkout then setsshippingNote: "address_required", and the model gets fixed Tote text in atote_notefield outsideuntrusted_data: delivery is checked after the buyer enters an address in the merchant checkout (T-09d).
Tests
pnpm test runs unit tests for constraints, tools and the loop, the injection cases from
ADR-001 decision 8, a continue_url leak test and an end-to-end run (request to search,
compare, build_cart and a HandoffRef). Search in the injection and end-to-end tests goes
through a real core client with an offline policy and a FixtureTransport. A network guard
makes any real network call fail. test/adapters/ checks each provider's exact request
body against a scripted HTTP layer, tool-call parsing, reasoning replay, retries,
Retry-After, error mapping, key handling, pricing and one runAgent run through a real
adapter.