@relyon/kit 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (225) hide show
  1. package/AGENTS.md +75 -0
  2. package/CHANGELOG.md +1053 -0
  3. package/LICENSE +21 -0
  4. package/QUICKSTART.md +239 -0
  5. package/README.md +117 -2
  6. package/dist/adapters/express.d.ts +39 -0
  7. package/dist/adapters/express.js +106 -0
  8. package/dist/adapters/hono.d.ts +16 -0
  9. package/dist/adapters/hono.js +15 -0
  10. package/dist/adapters/next.d.ts +29 -0
  11. package/dist/adapters/next.js +38 -0
  12. package/dist/agent-card.d.ts +14 -0
  13. package/dist/agent-card.js +58 -0
  14. package/dist/agent-docs.d.ts +36 -0
  15. package/dist/agent-docs.js +78 -0
  16. package/dist/agent-hooks.d.ts +66 -0
  17. package/dist/agent-hooks.js +280 -0
  18. package/dist/agents.d.ts +24 -0
  19. package/dist/agents.js +120 -0
  20. package/dist/api-key.d.ts +6 -0
  21. package/dist/api-key.js +33 -0
  22. package/dist/cache.d.ts +46 -0
  23. package/dist/cache.js +86 -0
  24. package/dist/cart-tokens.d.ts +31 -0
  25. package/dist/cart-tokens.js +58 -0
  26. package/dist/cart-transfer.d.ts +95 -0
  27. package/dist/cart-transfer.js +387 -0
  28. package/dist/catalog-enrichment.d.ts +6 -0
  29. package/dist/catalog-enrichment.js +71 -0
  30. package/dist/catalog-reads.d.ts +126 -0
  31. package/dist/catalog-reads.js +104 -0
  32. package/dist/catalog.d.ts +78 -0
  33. package/dist/catalog.js +288 -0
  34. package/dist/charge-claims.d.ts +11 -0
  35. package/dist/charge-claims.js +47 -0
  36. package/dist/check.d.ts +44 -0
  37. package/dist/check.js +152 -0
  38. package/dist/checklist-manifest.d.ts +72 -0
  39. package/dist/checklist-manifest.js +341 -0
  40. package/dist/checkout.d.ts +222 -0
  41. package/dist/checkout.js +353 -0
  42. package/dist/cli.d.ts +2 -0
  43. package/dist/cli.js +727 -0
  44. package/dist/confirmation.d.ts +78 -0
  45. package/dist/confirmation.js +124 -0
  46. package/dist/context.d.ts +81 -0
  47. package/dist/context.js +10 -0
  48. package/dist/discovery.d.ts +151 -0
  49. package/dist/discovery.js +346 -0
  50. package/dist/doctor-cart-transfer.d.ts +33 -0
  51. package/dist/doctor-cart-transfer.js +186 -0
  52. package/dist/doctor-catalog.d.ts +8 -0
  53. package/dist/doctor-catalog.js +47 -0
  54. package/dist/doctor-evidence.d.ts +22 -0
  55. package/dist/doctor-evidence.js +57 -0
  56. package/dist/doctor-merchant.d.ts +48 -0
  57. package/dist/doctor-merchant.js +74 -0
  58. package/dist/doctor-source.d.ts +5 -0
  59. package/dist/doctor-source.js +142 -0
  60. package/dist/doctor-variants.d.ts +70 -0
  61. package/dist/doctor-variants.js +102 -0
  62. package/dist/doctor.d.ts +215 -0
  63. package/dist/doctor.js +1689 -0
  64. package/dist/events.d.ts +95 -0
  65. package/dist/events.js +200 -0
  66. package/dist/feed-mapping.d.ts +114 -0
  67. package/dist/feed-mapping.js +152 -0
  68. package/dist/feed-values.d.ts +13 -0
  69. package/dist/feed-values.js +40 -0
  70. package/dist/feeds.d.ts +104 -0
  71. package/dist/feeds.js +366 -0
  72. package/dist/identify.d.ts +102 -0
  73. package/dist/identify.js +124 -0
  74. package/dist/identity.d.ts +37 -0
  75. package/dist/identity.js +54 -0
  76. package/dist/index.d.ts +42 -0
  77. package/dist/index.js +41 -0
  78. package/dist/init.d.ts +157 -0
  79. package/dist/init.js +912 -0
  80. package/dist/kit-config.d.ts +19 -0
  81. package/dist/kit-config.js +43 -0
  82. package/dist/kit-environment.d.ts +20 -0
  83. package/dist/kit-environment.js +32 -0
  84. package/dist/kit-updates.d.ts +47 -0
  85. package/dist/kit-updates.js +77 -0
  86. package/dist/kit-version-project.d.ts +18 -0
  87. package/dist/kit-version-project.js +214 -0
  88. package/dist/kit-version.d.ts +37 -0
  89. package/dist/kit-version.js +162 -0
  90. package/dist/kit.d.ts +516 -0
  91. package/dist/kit.js +1309 -0
  92. package/dist/layers/pages.d.ts +3 -0
  93. package/dist/layers/pages.js +5 -0
  94. package/dist/layers/payments.d.ts +7 -0
  95. package/dist/layers/payments.js +9 -0
  96. package/dist/layers/products.d.ts +10 -0
  97. package/dist/layers/products.js +13 -0
  98. package/dist/live.d.ts +13 -0
  99. package/dist/live.js +52 -0
  100. package/dist/mcp.d.ts +270 -0
  101. package/dist/mcp.js +312 -0
  102. package/dist/next-steps.d.ts +101 -0
  103. package/dist/next-steps.js +257 -0
  104. package/dist/order-pending.d.ts +57 -0
  105. package/dist/order-pending.js +127 -0
  106. package/dist/orders.d.ts +12 -0
  107. package/dist/orders.js +21 -0
  108. package/dist/payments-init.d.ts +19 -0
  109. package/dist/payments-init.js +70 -0
  110. package/dist/payments-routes.d.ts +54 -0
  111. package/dist/payments-routes.js +123 -0
  112. package/dist/payments.d.ts +165 -0
  113. package/dist/payments.js +192 -0
  114. package/dist/pnpm-workspace.d.ts +58 -0
  115. package/dist/pnpm-workspace.js +250 -0
  116. package/dist/policies.d.ts +111 -0
  117. package/dist/policies.js +317 -0
  118. package/dist/preview-hosts.d.ts +64 -0
  119. package/dist/preview-hosts.js +175 -0
  120. package/dist/private-config.d.ts +169 -0
  121. package/dist/private-config.js +820 -0
  122. package/dist/progress.d.ts +54 -0
  123. package/dist/progress.js +153 -0
  124. package/dist/protocol-inputs.d.ts +22 -0
  125. package/dist/protocol-inputs.js +151 -0
  126. package/dist/public-origin.d.ts +50 -0
  127. package/dist/public-origin.js +180 -0
  128. package/dist/refusals.d.ts +86 -0
  129. package/dist/refusals.js +157 -0
  130. package/dist/relay.d.ts +107 -0
  131. package/dist/relay.js +655 -0
  132. package/dist/release-notes.d.ts +2 -0
  133. package/dist/release-notes.js +290 -0
  134. package/dist/relyon-cart-tokens.d.ts +101 -0
  135. package/dist/relyon-cart-tokens.js +521 -0
  136. package/dist/relyon.d.ts +141 -0
  137. package/dist/relyon.js +238 -0
  138. package/dist/robots.d.ts +27 -0
  139. package/dist/robots.js +127 -0
  140. package/dist/rules.d.ts +144 -0
  141. package/dist/rules.js +347 -0
  142. package/dist/sdk/generated/public-api.d.ts +4816 -0
  143. package/dist/sdk/generated/public-api.js +1 -0
  144. package/dist/sdk/index.d.ts +24 -0
  145. package/dist/sdk/index.js +34 -0
  146. package/dist/sdk/signatures.d.ts +17 -0
  147. package/dist/sdk/signatures.js +33 -0
  148. package/dist/setup.d.ts +37 -0
  149. package/dist/setup.js +94 -0
  150. package/dist/signatures.d.ts +112 -0
  151. package/dist/signatures.js +443 -0
  152. package/dist/state.d.ts +185 -0
  153. package/dist/state.js +96 -0
  154. package/dist/store-payments.d.ts +48 -0
  155. package/dist/store-payments.js +143 -0
  156. package/dist/structured-fields.d.ts +26 -0
  157. package/dist/structured-fields.js +200 -0
  158. package/dist/templates.d.ts +19 -0
  159. package/dist/templates.js +193 -0
  160. package/dist/test-checkout-command.d.ts +32 -0
  161. package/dist/test-checkout-command.js +161 -0
  162. package/dist/test-checkout.d.ts +88 -0
  163. package/dist/test-checkout.js +292 -0
  164. package/dist/types.d.ts +103 -0
  165. package/dist/types.js +18 -0
  166. package/dist/ucp-versions.d.ts +57 -0
  167. package/dist/ucp-versions.js +129 -0
  168. package/dist/util.d.ts +23 -0
  169. package/dist/util.js +68 -0
  170. package/dist/variants.d.ts +67 -0
  171. package/dist/variants.js +146 -0
  172. package/dist/version.d.ts +9 -0
  173. package/dist/version.js +10 -0
  174. package/dist/waiting.d.ts +43 -0
  175. package/dist/waiting.js +57 -0
  176. package/dist/webhook-command.d.ts +48 -0
  177. package/dist/webhook-command.js +367 -0
  178. package/dist/webhook-registration.d.ts +47 -0
  179. package/dist/webhook-registration.js +69 -0
  180. package/dist/webmcp-schema.d.ts +14 -0
  181. package/dist/webmcp-schema.js +140 -0
  182. package/dist/webmcp-script.d.ts +3 -0
  183. package/dist/webmcp-script.js +176 -0
  184. package/dist/webmcp-store.d.ts +102 -0
  185. package/dist/webmcp-store.js +116 -0
  186. package/dist/webmcp.d.ts +242 -0
  187. package/dist/webmcp.js +866 -0
  188. package/dist/wire-names.d.ts +85 -0
  189. package/dist/wire-names.js +109 -0
  190. package/package.json +118 -4
  191. package/release-notes.json +290 -0
  192. package/scripts/install-notice.cjs +7 -0
  193. package/skills/relyon-agents/SKILL.md +327 -0
  194. package/skills/relyon-catalog/SKILL.md +499 -0
  195. package/skills/relyon-catalog/references/example-store.md +218 -0
  196. package/skills/relyon-checkout/SKILL.md +603 -0
  197. package/skills/relyon-checkout/references/checkout-flow.md +257 -0
  198. package/skills/relyon-checkout/references/checkout-page.md +315 -0
  199. package/skills/relyon-go-live/SKILL.md +344 -0
  200. package/skills/relyon-orders/SKILL.md +191 -0
  201. package/skills/relyon-orders/references/webhook-receiver.md +113 -0
  202. package/skills/relyon-payments/SKILL.md +117 -0
  203. package/skills/relyon-setup/SKILL.md +1061 -0
  204. package/skills/relyon-setup/references/QUICKSTART.md +239 -0
  205. package/skills/relyon-setup/references/durable-state.md +209 -0
  206. package/skills/relyon-setup/references/express-server.md +388 -0
  207. package/skills/relyon-setup/references/next-app-router.md +251 -0
  208. package/templates/common/STORE-README.md +67 -0
  209. package/templates/common/gitignore +8 -0
  210. package/templates/common/scripts/check-pricing.ts +22 -0
  211. package/templates/common/scripts/serve.mjs +13 -0
  212. package/templates/common/server/catalog.ts +79 -0
  213. package/templates/common/server/checkout-flow.d.ts +34 -0
  214. package/templates/common/server/pages.ts +184 -0
  215. package/templates/common/server/storage.ts +114 -0
  216. package/templates/common/server/store.ts +67 -0
  217. package/templates/express/server/express.ts +20 -0
  218. package/templates/express/tsconfig.build.json +6 -0
  219. package/templates/express/tsconfig.json +9 -0
  220. package/templates/next/app/[[...path]]/route.ts +24 -0
  221. package/templates/next/next.config.mjs +19 -0
  222. package/templates/next/tsconfig.json +12 -0
  223. package/templates/payments/express.ts +39 -0
  224. package/templates/payments/next.ts +38 -0
  225. package/templates/payments/node.ts +39 -0
@@ -0,0 +1,603 @@
1
+ ---
2
+ name: relyon-checkout
3
+ description: Build checkout on the store's own domain with @relyon/store-kit - the app's priceCart, a checkout page, kit.cardFields for the only Relyon browser element, tokenize() and kit.createPayment charging exactly the store's cart total, plus relyon_cart hand-off landings.
4
+ ---
5
+
6
+ # Relyon checkout
7
+
8
+ <!-- BEGIN relyon-store-first-rules (generated from the shared rules source; edit it there) -->
9
+ Before building, ask the user: 'Do you want to (1) accept card payments in your own app — no Relyon product catalog or shopping pages; (2) also list products so AI shopping agents can find and buy them; or (3) also have Relyon's kit build the shopping pages for you?' Don't choose for them. Then follow the matching quickstart.
10
+
11
+ ## Choose the integration before applying kit guidance
12
+
13
+ Payments: https://core.getrelyon.com/docs/payments-quickstart and `relyon-payments`.
14
+ Products and agent selling: https://core.getrelyon.com/docs (catalog,
15
+ agent checkout and AI visibility are optional additions).
16
+ Shopping pages: https://core.getrelyon.com/docs/quickstart and `relyon-setup`.
17
+ Never install the kit or build catalog, /cart or shopping pages for payments only.
18
+ The kit-specific rules below apply only after the user chooses shopping pages.
19
+ Live payments support human buyers and agents in every integration after staff
20
+ approval and processor onboarding, with existing payment safety checks intact.
21
+ Keep the secret key server-side as RELYON_API_KEY; only the publishable key is public.
22
+
23
+ When using the optional kit and uncertain about its version, run `npm view @relyon/store-kit version`.
24
+ Compare it with the store project's actually installed version; never downgrade.
25
+ Install the exact returned version with the project's package manager (npm install
26
+ --save-exact, pnpm add --save-exact, yarn add --exact, or bun add --exact), then run
27
+ `npx @relyon/store-kit doctor` afterward. If the lookup fails, say it is unavailable;
28
+ do not guess a latest version. Respect package-age holds without changing settings.
29
+
30
+ ## Test setup and hand-over
31
+
32
+ - Start the store as a separate detached background process, using the host's
33
+ process manager or `setsid nohup npm run start >store.log 2>&1 < /dev/null &`.
34
+ Never run it in the agent's own foreground session. Stop a recorded PID;
35
+ never use a `pkill` pattern that can match the shell issuing it.
36
+ - On a public Test URL, call `kit.ensureDomain(hostname)` and then
37
+ `kit.verifyDomain(domain.hostname)` after the verification route is reachable.
38
+ Domain verification is not only for Live.
39
+ - Say exactly “Test mode: no real money moves” when handing over a Test store.
40
+ Never say shoppers can buy or pay for real while the store is in Test.
41
+ - Server-only `loadTestConfig` supplies both `apiKey` and `webhookSecret`.
42
+ Wire them into `relyon.apiKey` and `rules.webhookSecret`; never expose either
43
+ in browser code or agent prompts.
44
+ - With an environment API key, `webhook` never writes a secret file.
45
+ A set `RELYON_WEBHOOK_SECRET` in environment or dotenv overrides key-only
46
+ runtime recovery. Unset it, or update it in host settings, then restart.
47
+ Rotation exits 1 if an override differs from the current secret. Do not
48
+ treat that exit as a failed rotation: the endpoint may already be rotated.
49
+ Never read or print the override value; never ask for it in an agent prompt.
50
+
51
+ ## Relyon store-first rules
52
+
53
+ These seven kit rules are identical in every Relyon skill. They apply only to the shopping-pages integration, never to payments-only apps.
54
+
55
+ 1. Install `@relyon/store-kit@0.1.52` from npm and mount its handlers on the app's own server (Express `@relyon/store-kit/express`, Next.js `@relyon/store-kit/next`, Hono `@relyon/store-kit/hono`).
56
+ 2. Catalog, cart and pricing stay in the app: the app owns `listProducts`, `getProduct`, `priceCart` and `createOrder`. Relyon never prices a cart. It charges exactly the final amount the store sends.
57
+ 3. Checkout runs on the store's own domain. The only Relyon element in the shopper's browser is the card fields component. Card numbers never touch the app's code, server or logs.
58
+ 4. The app calls Relyon only from its server, and only for payment, agent verification, fraud and limits, and recording.
59
+ 5. Agent activity reporting stays on: never stub, disable or throttle-to-zero the kit's event reporting.
60
+ 6. Start in Test. Live is enabled by Relyon staff, never approved by the agent; after staff approval, the agent activates it at the merchant's explicit instruction (set the env vars by name, redeploy, run the Live doctor for shopping pages) and never asks for or pastes a Live secret key. Build before requesting keys: missing credentials defer credential-dependent verification, never the local build. Show checkout as **waiting for a Test secret key**, record pending checks honestly, and resume them after configuring a real Test secret key without rebuilding. Never fabricate a credential, payment or order.
61
+ 7. No Relyon-hosted checkout, redirect to a Relyon page, CNAME, proxy, forwarding Worker or `quote.request`/pricing endpoint.
62
+
63
+ ### Test defaults — not merchant policy
64
+
65
+ | Item | Test default |
66
+ | --- | --- |
67
+ | Brand | Store name, unless the merchant supplies another brand. |
68
+ | MPN | SKU, unless the merchant supplies another MPN. |
69
+ | Stock | Available unless told otherwise; no invented inventory count. |
70
+ | Returns/support | Pending merchant items. Never invent them or submit placeholders as real policy data. |
71
+
72
+ Explicit merchant facts override these Test defaults. Proceed with local Test
73
+ building; ask before asserting missing merchant promises or syncing policies.
74
+ Never invent supplier claims, GTINs, tax treatment or policy terms. Pending
75
+ merchant information blocks only the checks that require it, not the build.
76
+ <!-- END relyon-store-first-rules -->
77
+
78
+ Reference only. Open a section when the quick start names it; no whole-skill prerequisite.
79
+
80
+ Contract: the approved public v1 contract dated **2026-10-30**, at
81
+ `https://core.getrelyon.com/v1/openapi.yaml` (another deployment:
82
+ `<service origin>/v1/openapi.yaml`). The kit calls `POST /v1/payment_sessions` and
83
+ `POST /v1/payments` for the app.
84
+
85
+ The canonical API base is `https://core.getrelyon.com/api`; `/v1/payments`
86
+ therefore means `https://core.getrelyon.com/api/v1/payments`. The download URL
87
+ above and the store's own routes are separate. Retain operator-confirmed API
88
+ base overrides for other deployments.
89
+
90
+ For the quick start's checkout and Test purchase, wire transactional
91
+ `createOrder` and read-only `findOrderByPaymentId`
92
+ here as checkout prerequisites, not as a deferred placeholder: a successful
93
+ purchase must save its order and safely replay it. The orders reference covers broader
94
+ order recovery and fulfilment behavior. Shipping regions, rates and tax come from the
95
+ merchant: ask, and check what `relyon-store-brief.md` says, but never invent
96
+ them.
97
+
98
+ ## Facts first: types, money, channels and the card fields
99
+
100
+ Everything here is exported by `@relyon/store-kit`; don't read the package's
101
+ build output to find it.
102
+
103
+ | Name | What it is |
104
+ | --- | --- |
105
+ | `Cart` | The priced cart `priceCart` returns: `currency`, `lines`, optional `discounts`, `shipping_options`, `shipping_option_id`, `shipping_address`, and `totals`. |
106
+ | `CartLine` | One priced line of a `Cart` (`merchant_product_id`, `title`, `quantity`, `amount`, optional `id`, `unit_amount`, `discount`, `options`). There is no `LineItem` type in the kit. |
107
+ | `CartLineInput` | One line `priceCart` receives: `{ product_id, quantity, options? }`. |
108
+ | `Address` | The shipping address (see [The address shape](#the-address-shape)). |
109
+ | `PaymentChannel` | `"web" \| "google" \| "chatgpt" \| "mcp" \| "agent"`. |
110
+ | `PriceCart`, `CreateOrder`, `FindOrderByPaymentId` | The app's functions the kit calls. |
111
+ | `CreatePaymentResult` | What `kit.createPayment` returns. |
112
+ | `CheckoutStateStore`, `AgentEventStore` | The durable stores (below). |
113
+
114
+ - **Money** is an integer in minor units (cents for USD, whole yen for JPY).
115
+ - **Currency** is an ISO 4217 code in upper case (`"USD"`, never `"usd"` or
116
+ `"$"`). One cart has one currency: `cart.currency`, `cart.totals.currency`
117
+ and the `currency` passed to `kit.cardFields` are the same code.
118
+ - **Channel.** Leave `channel` out on the store's own checkout: it is `web`.
119
+ For a handed-off shopper pass the `channel` that `kit.landing` returned
120
+ (`google` for UCP, `chatgpt` for ACP, `mcp` for MCP, `agent` for another
121
+ agent). Never set it from a browser value.
122
+ - **Card fields** come from one Relyon script, served next to the API at
123
+ `https://core.getrelyon.com/api/public/relyon-card-fields.js`.
124
+ `kit.cardFields(...)` returns the script tag and the `<relyon-card-fields>`
125
+ element for a fresh payment session; put `fields.html` in the page. The app
126
+ never writes that URL itself and never builds its own card inputs.
127
+
128
+ ```ts
129
+ import { StoreRefusal, type Address, type Cart, type CartLine, type CartLineInput, type PaymentChannel, type PriceCart } from "@relyon/store-kit";
130
+
131
+ const PRODUCTS: Record<string, { title: string; unitAmount: number }> = {
132
+ "lavender-candle": { title: "Lavender candle", unitAmount: 2400 },
133
+ };
134
+ const GROUND = { id: "ground", label: "Ground (3-5 days)", amount: 599 };
135
+
136
+ export const priceCart: PriceCart = async (lines: CartLineInput[], address: Address | null, coupons: string[]) => {
137
+ const currency = "USD"; // ISO 4217, upper case
138
+ if (coupons.length > 0) throw new StoreRefusal("coupon_invalid", "That code isn't valid.", 422);
139
+ const priced: CartLine[] = lines.map((line, index) => {
140
+ const product = PRODUCTS[line.product_id];
141
+ if (!product) throw new StoreRefusal("product_unavailable", "That product isn't sold here.", 422);
142
+ return {
143
+ id: `line_${index + 1}`,
144
+ merchant_product_id: line.product_id,
145
+ title: product.title,
146
+ quantity: line.quantity,
147
+ unit_amount: product.unitAmount,
148
+ amount: product.unitAmount * line.quantity, // minor units
149
+ };
150
+ });
151
+ const subtotal = priced.reduce((sum, line) => sum + line.amount, 0);
152
+ const shipping = address ? GROUND.amount : 0;
153
+ const cart: Cart = {
154
+ currency,
155
+ lines: priced,
156
+ shipping_options: [GROUND],
157
+ ...(address ? { shipping_option_id: GROUND.id, shipping_address: address } : {}),
158
+ totals: { currency, subtotal, discount: 0, shipping, tax: 0, total: subtotal + shipping },
159
+ };
160
+ return cart;
161
+ };
162
+
163
+ // The only values a payment channel can take.
164
+ export const CHANNELS: readonly PaymentChannel[] = ["web", "google", "chatgpt", "mcp", "agent"];
165
+ ```
166
+
167
+ ## Durable state the kit relies on
168
+
169
+ The kit keeps five kinds of state. The defaults hold them in one process's
170
+ memory, which is fine for a local Test run only. A deployed store, or any app
171
+ with more than one server process, gives the kit shared stores that survive
172
+ restarts (`state` and `events.store` when creating the kit; see `relyon-setup`
173
+ and its durable-state reference for Postgres).
174
+
175
+ | State | Where it lives | What it must guarantee |
176
+ | --- | --- | --- |
177
+ | Checkout records | `CheckoutStateStore` `get`, `byAgentCheckoutId`, `put` | `put` saves the whole `CheckoutRecord` and `get` returns it unchanged (including `orderPending`, `handoffToken` and `handoffTokenAt`); `byAgentCheckoutId` finds the newest record for Relyon's agent checkout ID. |
178
+ | Exactly-once order claims | `claimOrder`, `completeOrder`, `releaseOrder`, `orderClaimStatus` | `claimOrder` is one atomic statement: exactly one caller gets `true` per payment ID across every process. An unfinished claim may be taken over only after `leaseMs`; a claim marked by `completeOrder` never is. `releaseOrder` frees the claim only while `claimId` still holds it. `orderClaimStatus` answers `"created"`, `"creating"` or `null`. |
179
+ | Payment records and idempotency | `getStorePayment`, `putStorePayment` (both or neither) | Keyed by the payment's `Idempotency-Key` (derived from the order reference and attempt); saved before the kit answers, so another server never tells a charged shopper "nothing was charged". |
180
+ | Hand-off token claims | `claimHandoffToken` (and `setHandoffToken`) | `claimHandoffToken` returns `true` once per token digest until `expiresAt`, across every process (a unique insert). `setHandoffToken` is one compare-and-set on the record's current token and inputs that also sets `handoffTokenAt` and `updatedAt` to `now`. |
181
+ | Agent events | `AgentEventStore` `append`, `peek`, `remove`, `size` | Events stay, in order, until Relyon accepted them (`remove` is called only then); a repeated `id` is ignored; `append` is never a no-op. |
182
+
183
+ The app's own orders table is separate: make it unique on Relyon's payment ID.
184
+
185
+ ```ts
186
+ import type { AgentProtocol, CheckoutRecord, CheckoutStateStore, StorePaymentRecord } from "@relyon/store-kit";
187
+
188
+ /** The app's database client: one parameterized statement, rows back. */
189
+ export type Sql = <Row = Record<string, unknown>>(text: string, params?: unknown[]) => Promise<Row[]>;
190
+
191
+ export function checkoutState(sql: Sql): CheckoutStateStore {
192
+ return {
193
+ async get(protocol: AgentProtocol, sessionId: string) {
194
+ const [row] = await sql<{ record: CheckoutRecord }>(
195
+ "select record from relyon_checkouts where protocol = $1 and session_id = $2", [protocol, sessionId]);
196
+ return row?.record ?? null;
197
+ },
198
+ async byAgentCheckoutId(agentCheckoutId: string) {
199
+ const [row] = await sql<{ record: CheckoutRecord }>(
200
+ "select record from relyon_checkouts where agent_checkout_id = $1 order by updated_at desc limit 1", [agentCheckoutId]);
201
+ return row?.record ?? null;
202
+ },
203
+ async put(record: CheckoutRecord) {
204
+ await sql(`insert into relyon_checkouts (protocol, session_id, agent_checkout_id, record, updated_at)
205
+ values ($1, $2, $3, $4, $5) on conflict (protocol, session_id) do update
206
+ set agent_checkout_id = excluded.agent_checkout_id, record = excluded.record, updated_at = excluded.updated_at`,
207
+ [record.protocol, record.sessionId, record.agentCheckoutId, JSON.stringify(record), record.updatedAt]);
208
+ },
209
+ // Exactly once: one atomic statement; an unfinished claim is taken over only after its lease.
210
+ async claimOrder(paymentId, options) {
211
+ const claimId = options?.claimId ?? null;
212
+ const now = options?.now ?? Date.now();
213
+ const expiresAt = options ? now + options.leaseMs : null;
214
+ const rows = await sql(`insert into relyon_order_claims (payment_id, claim_id, created, expires_at)
215
+ values ($1, $2, false, $3) on conflict (payment_id) do update
216
+ set claim_id = excluded.claim_id, expires_at = excluded.expires_at
217
+ where not relyon_order_claims.created and relyon_order_claims.expires_at <= $4
218
+ returning payment_id`, [paymentId, claimId, expiresAt, now]);
219
+ return rows.length === 1;
220
+ },
221
+ async completeOrder(paymentId: string) {
222
+ await sql("update relyon_order_claims set created = true, expires_at = null where payment_id = $1", [paymentId]);
223
+ },
224
+ async releaseOrder(paymentId: string, claimId?: string) {
225
+ await sql("delete from relyon_order_claims where payment_id = $1 and not created and ($2::text is null or claim_id = $2)",
226
+ [paymentId, claimId ?? null]);
227
+ },
228
+ async orderClaimStatus(paymentId: string, now: number) {
229
+ const [row] = await sql<{ created: boolean; holding: boolean | null }>(
230
+ "select created, expires_at > $2 as holding from relyon_order_claims where payment_id = $1", [paymentId, now]);
231
+ if (!row) return null;
232
+ return row.created ? "created" : row.holding ? "creating" : null;
233
+ },
234
+ // Payment records, by Idempotency-Key.
235
+ async getStorePayment(idempotencyKey: string) {
236
+ const [row] = await sql<{ record: StorePaymentRecord }>(
237
+ "select record from relyon_store_payments where idempotency_key = $1", [idempotencyKey]);
238
+ return row?.record ?? null;
239
+ },
240
+ async putStorePayment(idempotencyKey: string, record: StorePaymentRecord) {
241
+ await sql(`insert into relyon_store_payments (idempotency_key, record) values ($1, $2)
242
+ on conflict (idempotency_key) do update set record = excluded.record`, [idempotencyKey, JSON.stringify(record)]);
243
+ },
244
+ // Hand-off tokens: one attributed landing per token digest, across every process.
245
+ async claimHandoffToken(tokenDigest, { expiresAt }) {
246
+ const rows = await sql(`insert into relyon_handoff_claims (token_digest, expires_at) values ($1, $2)
247
+ on conflict (token_digest) do nothing returning token_digest`, [tokenDigest, expiresAt]);
248
+ return rows.length === 1;
249
+ },
250
+ };
251
+ }
252
+ ```
253
+
254
+ It uses the `relyon_checkouts` and `relyon_order_claims` tables from the
255
+ `relyon-setup` durable-state reference, plus two more:
256
+
257
+ ```sql
258
+ create table if not exists relyon_store_payments (
259
+ idempotency_key text primary key,
260
+ record jsonb not null
261
+ );
262
+ create table if not exists relyon_handoff_claims (
263
+ token_digest text primary key,
264
+ expires_at bigint not null -- the kit's clock (ms)
265
+ );
266
+ ```
267
+
268
+ A claim taken without a lease (`options` absent) never expires. Expired
269
+ hand-off claims (`expires_at` in the past) may be deleted by a cleanup job.
270
+
271
+ ## A replayed payment: `already_created` and the existing order
272
+
273
+ A retry, reload or background job replays a payment with the same
274
+ `orderReference`, so Relyon returns the same payment and nothing is charged
275
+ again. When that payment's order was already saved by an earlier call,
276
+ `kit.createPayment` answers `orderCreated: false` and
277
+ `orderStatus: "already_created"`: the order exists, and `createOrder` was not
278
+ called again. Treat it as paid with its order saved.
279
+
280
+ To get that order back on the replay, give the kit the optional, read-only
281
+ `findOrderByPaymentId` when creating it. It must only look the order up by the
282
+ payment ID that `createOrder` received, never create one, and return `null`
283
+ when there is none. On `already_created` the kit puts what it returns in
284
+ `result.order`; if it is missing, returns `null` or throws (the error is
285
+ logged), `result.order` is absent and the payment still counts as succeeded.
286
+ `orderStatus: "in_progress"` means another request is still creating the order:
287
+ keep the checkout pending and ask again.
288
+
289
+ ```ts
290
+ import { createStoreKit, type Cart, type CreatePaymentResult, type PaymentLike, type PriceCart, type StoreKit } from "@relyon/store-kit";
291
+
292
+ interface Order { orderNumber: string; paymentId: string }
293
+ const orders = new Map<string, Order>(); // the app's orders table, unique on the payment ID
294
+
295
+ // storeUrl: the store's own origin from the required STORE_PUBLIC_URL (no example default).
296
+ export function createKit(apiKey: string, priceCart: PriceCart, storeUrl: string): StoreKit {
297
+ return createStoreKit({
298
+ relyon: { baseUrl: "https://core.getrelyon.com/api", apiKey },
299
+ store: { name: "Example Candle Co", hostnames: [new URL(storeUrl).hostname], publicUrl: storeUrl },
300
+ priceCart,
301
+ createOrder: (cart: Cart, payment: PaymentLike) => {
302
+ const order = { orderNumber: `#${1000 + orders.size + 1}`, paymentId: payment.id };
303
+ orders.set(payment.id, order);
304
+ return order;
305
+ },
306
+ findOrderByPaymentId: (paymentId: string) => orders.get(paymentId) ?? null,
307
+ });
308
+ }
309
+
310
+ export function savedOrder(result: CreatePaymentResult): Order | null {
311
+ if (result.payment.status !== "succeeded") return null;
312
+ if (result.orderStatus === "created" || result.orderStatus === "already_created") return (result.order as Order | undefined) ?? null;
313
+ return null; // in_progress or failed: still pending, replay the same attempt
314
+ }
315
+ ```
316
+
317
+ ## Test purchases, end to end
318
+
319
+ 1. **The card fields.** The server calls `kit.cardFields({ amount, currency,
320
+ orderReference })` and puts `fields.html` in the checkout page. That loads
321
+ the Relyon card-fields script and its `<relyon-card-fields>` element, which
322
+ fires `relyon-ready` when it can be used.
323
+ 2. **The Test card.** A new sandbox has no processor account, so in Test the
324
+ element shows "Test mode: no card details are collected" instead of card
325
+ inputs. Nobody types a card number. `tokenize()` resolves to a mock
326
+ `hosted_card` payment method that only the Test processor accepts. A
327
+ sandbox that Relyon staff connected to a processor's own test account shows
328
+ that processor's card inputs instead: use only that processor's published
329
+ test card numbers there. Never enter a real card in Test.
330
+ 3. **The outcome is set by the amount.** The Test processor reads the last two
331
+ digits of `totals.total` in minor units: `…02` is declined
332
+ (`card_declined`), `…19` is declined (`insufficient_funds`), `…65` is
333
+ declined (`authentication_required`), and `…99` is a processor error whose
334
+ outcome is unknown (handle it like any "may have gone through" answer).
335
+ Every other amount succeeds. Use a price such as 24.00 for the happy path
336
+ and a cart ending in `02` to see a decline.
337
+ 4. **A successful Test purchase looks like this:** `result.payment.status` is
338
+ `"succeeded"`, `result.payment.livemode` is `false`, `result.payment.id`
339
+ starts with `pay_`, `result.payment.channel` is `"web"` (or the hand-off
340
+ channel), `result.orderCreated` is `true` with `orderStatus: "created"`, and
341
+ the app's orders table has exactly one order holding that payment ID.
342
+ Replaying the same order reference returns the same payment ID with
343
+ `orderStatus: "already_created"`, and no second order or charge appears.
344
+ 5. If the payment is refused with `processor_not_configured`, the sandbox
345
+ can't take Test payments yet; record it as blocked (see `relyon-go-live`).
346
+
347
+ ## The address shape
348
+
349
+ `Address` is the **shipping** address: what `priceCart` receives (or `null`
350
+ before one is known) and what a cart's `shipping_address` holds. It has
351
+ `name`, `line1`, optional `line2`, `city`, optional `region`, `postal_code`
352
+ and `country`, and nothing else:
353
+
354
+ - `region` is the state, province or county. There is no `state` field.
355
+ - `country` is a two-letter ISO 3166-1 code in upper case (`"US"`).
356
+ - There is no email, phone or billing address. Keep the shopper's email and
357
+ phone in the app's own order record; the card fields handle what the
358
+ processor needs.
359
+ - `shipping_address`, `shipping_options` and `shipping_option_id` apply only to
360
+ goods that are shipped. A pickup option has no address, and `priceCart` must
361
+ price a cart without one.
362
+ - Unknown fields are refused, so map a form explicitly rather than spreading
363
+ it into the address.
364
+
365
+ ```ts
366
+ import type { Address } from "@relyon/store-kit";
367
+
368
+ /** A typical checkout form. */
369
+ interface CheckoutForm {
370
+ fullName: string;
371
+ email: string;
372
+ phone?: string;
373
+ street: string;
374
+ apartment?: string;
375
+ city: string;
376
+ state?: string;
377
+ zip: string;
378
+ country: string;
379
+ }
380
+
381
+ export function shippingAddress(form: CheckoutForm): Address {
382
+ // form.email and form.phone stay in the app's own order record.
383
+ return {
384
+ name: form.fullName.trim(),
385
+ line1: form.street.trim(),
386
+ line2: form.apartment?.trim() || undefined, // left out of the JSON when empty
387
+ city: form.city.trim(),
388
+ region: form.state?.trim() || undefined, // region, not state
389
+ postal_code: form.zip.trim(),
390
+ country: form.country.trim().toUpperCase(), // "US"
391
+ };
392
+ }
393
+ ```
394
+
395
+ ## The flow
396
+
397
+ 1. The shopper builds a cart in the app. The app stores it server-side.
398
+ Required storefront pages: /, /products/<id>, /cart, /checkout and the policy pages. /cart is a real server-rendered or routed page that answers 200, lists the cart's line items (or an empty state) and links to /checkout. A drawer may also exist but does not replace /cart.
399
+ 2. The app's checkout page (default path `/checkout`, on the store's domain)
400
+ prices the cart with the app's own `priceCart` and shows every line,
401
+ discount, shipping, tax and the total.
402
+ 3. The server calls `kit.cardFields(...)` for exactly that total and puts the
403
+ returned HTML in the page.
404
+ 4. In the browser, `tokenize()` turns the card into a payment method. The page
405
+ sends the order reference and the payment method, and nothing else, to the
406
+ app's server.
407
+ 5. The server re-prices the stored cart, checks the total hasn't changed,
408
+ records the attempt and calls `kit.createPayment(...)`. On success the kit
409
+ calls `createOrder` once.
410
+ 6. If the answer is lost anywhere (store to Relyon, or browser to store), the
411
+ checkout stays "pending": the page keeps Pay disabled, points to the order
412
+ status and asks the server, which only replays the recorded attempt.
413
+
414
+ The server half is [the checkout flow reference](references/checkout-flow.md)
415
+ (`checkout-flow.js`); a complete server is in the `relyon-setup` skill
416
+ (`references/express-server.md`); the browser script is in
417
+ [the checkout page reference](references/checkout-page.md).
418
+
419
+ ## priceCart: the store prices every cart
420
+
421
+ The kit calls the app's `priceCart` for every agent checkout step and every
422
+ hand-off landing; the app calls it for its own checkout page too.
423
+
424
+ ```js
425
+ async function priceCart(lines, address, coupons, context) { /* returns a Cart */ }
426
+ ```
427
+
428
+ - `lines`: `[{ product_id, quantity, options? }]`. `product_id` is the app's
429
+ `merchant_product_id`.
430
+ - `address`: the shipping address, or `null` before the shopper or agent gave one.
431
+ - `coupons`: codes to apply (validate them; refuse unknown ones).
432
+ - `context`: `{ protocol, operation, shippingOptionId, agentCheckoutId }`.
433
+ `protocol` is `ucp`, `acp`, `mcp` or `web`.
434
+
435
+ Return a `Cart` with one line per input line, in the same order:
436
+
437
+ ```json
438
+ {
439
+ "currency": "USD",
440
+ "lines": [
441
+ { "id": "line_1", "merchant_product_id": "lavender-candle", "title": "Lavender candle", "quantity": 2, "unit_amount": 2400, "amount": 4800 }
442
+ ],
443
+ "discounts": [{ "code": "WELCOME10", "label": "10% off your first order", "amount": 480 }],
444
+ "shipping_options": [{ "id": "ground", "label": "Ground (3-5 days)", "amount": 599 }],
445
+ "shipping_option_id": "ground",
446
+ "totals": { "currency": "USD", "subtotal": 4800, "discount": 480, "shipping": 599, "tax": 302, "total": 5221 }
447
+ }
448
+ ```
449
+
450
+ It must add up: the lines' `amount` sum to `totals.subtotal`, `discounts` sum
451
+ to `totals.discount`, and `totals.total` is subtotal − discount + shipping +
452
+ tax, all integers in minor units, with matching currencies. Relyon checks the
453
+ sums and charges exactly `totals.total`; it never changes a price. To refuse a
454
+ cart (out of stock, invalid option or coupon), throw
455
+ `new StoreRefusal(code, message, status)` from `@relyon/store-kit`: agents get
456
+ it in their protocol's error format.
457
+
458
+ ## Card fields on the store's page
459
+
460
+ ```js
461
+ const fields = await kit.cardFields({ amount: cart.totals.total, currency: cart.currency, orderReference });
462
+ // fields.html = fields.scriptTag + fields.element; fields.session is the payment session
463
+ ```
464
+
465
+ - Creates a fresh payment session (`POST /v1/payment_sessions`) for exactly
466
+ that amount. Sessions are single use: call it on every page render and
467
+ every new attempt.
468
+ - `orderReference` is the app's own reference for this checkout attempt. Store
469
+ it server-side with the cart.
470
+ - Optional: `fieldStyles` (styling passed to the fields), `elementId`,
471
+ `metadata` (no card or personal data).
472
+ - `fields.html` is the only Relyon markup in the page. Don't load other Relyon
473
+ scripts, frames or pages in the shopper's browser.
474
+ - Throws `PaymentUnavailableError` when Relyon can't be reached. Creating card
475
+ fields never charges, so show "try again shortly"; never fall back to
476
+ collecting card data yourself.
477
+
478
+ ## createPayment: charge the store's total
479
+
480
+ ```js
481
+ const result = await kit.createPayment({
482
+ cart, // re-priced on the server just now; totals.total is charged
483
+ paymentMethod, // exactly what tokenize() returned, unchanged
484
+ orderReference, // same reference the card fields were created for
485
+ channel, agentCheckoutId, // from kit.landing for a handed-off shopper; omit otherwise
486
+ request, // the shopper's Web Request, so agent rules apply at the edge
487
+ });
488
+ ```
489
+
490
+ - The `Idempotency-Key` is derived from `orderReference`: retrying with the
491
+ same reference never charges twice and returns the same payment. A new
492
+ attempt after a decline needs a new reference and new card fields.
493
+ - Re-price the stored cart before charging. If the total changed since the
494
+ card fields were created, don't charge: show the new total, create new card
495
+ fields and get the shopper's confirmation again.
496
+ - `result.payment.status === "succeeded"`: the kit called `createOrder` once
497
+ (`result.orderCreated`, `result.order`). `result.orderError` means the
498
+ payment succeeded but `createOrder` threw: the shopper was charged, so show
499
+ it as pending (never "didn't go through"), keep the attempt (cart and
500
+ payment method) and replay it with the same reference, which charges
501
+ nothing new and retries the order. A replay whose order already exists
502
+ answers `orderStatus: "already_created"` (see
503
+ [A replayed payment](#a-replayed-payment-already_created-and-the-existing-order)).
504
+ - Any other status: nothing to fulfill. Tell the shopper and let them retry.
505
+ - `PaymentOutcomeUnknownError`: Relyon answered `202 pending`, timed out,
506
+ failed or sent an unusable reply, so **a charge may have succeeded**. It
507
+ carries `orderReference`, `idempotencyKey` and `reason`. Keep the open
508
+ checkout and the exact attempt (the same cart and payment method), tell the
509
+ shopper the payment is being confirmed and not to pay again, and replay
510
+ that same attempt with the same reference (from the page or a background
511
+ job) until Relyon gives a final answer. The replay reuses the
512
+ `Idempotency-Key`, so it never charges twice. Never start a new reference,
513
+ re-price into a different cart, create an order, or tell the shopper
514
+ nothing was charged on this error.
515
+ - Other errors: `AgentRefusedError` (`agent_refused` or `channel_paused` from
516
+ the store's agent rules) and `RelyonProblemError` with a `code`:
517
+
518
+ | Code | What to do |
519
+ | --- | --- |
520
+ | `amount_mismatch` | The amount differs from the payment session or the cart doesn't add up. Fix `priceCart`, create new card fields and charge again. Nothing was charged. |
521
+ | `processor_not_configured` | No processor account in this environment yet. Relyon staff set it up; report it (see `relyon-go-live`). |
522
+ | `card_data_rejected` | A request carried something that looks like card data. Remove it; never rename or encode it. |
523
+ | `idempotency_key_reused` | The same order reference was used with a different cart or amount. Use a new reference for a new attempt. |
524
+ | `permission_denied` | The key lacks a scope. Report it; don't switch keys. |
525
+
526
+ **One cart shape:** agent checkout and `POST /v1/payments` both accept the
527
+ contract `Cart` (`currency` in any case, line `id`/`merchant_product_id`,
528
+ shipping options and address, terms) that the app's `priceCart` returns.
529
+ Leave `paymentCartFormat` unset (the default is `contract`). The old
530
+ `paymentCartFormat: "server-legacy"` still works but is deprecated: the kit
531
+ logs a warning at startup and Relyon answers with a deprecation header.
532
+ Missing discount, shipping or tax totals count as 0, and harmless extra
533
+ fields (such as `notes`) are ignored; fields that try to set an amount
534
+ (`price`, `total`, `tax_amount`, ...) are still refused, naming the field.
535
+
536
+ For known charged but unsaved orders show exactly:
537
+ "Your payment went through. Your order is still being placed".
538
+ Keep Pay disabled and the original attempt; retry order placement with that
539
+ same reference, never a second charge. Unknown payment outcomes instead keep
540
+ the cautious confirmation message. Neither case permits a completed-order or
541
+ fulfillment claim before a saved order exists.
542
+
543
+ ## Lost answers, retries and reloads: never two charges
544
+
545
+ Use `checkout-flow.js` ([checkout flow reference](references/checkout-flow.md))
546
+ or keep the same guarantees in the app's own code:
547
+
548
+ - Record the attempt (cart and payment method) with one conditional write
549
+ before calling `createPayment`. Only the request that wins it sends.
550
+ - After that, every retry, second click, status check, background job or
551
+ reload replays that recorded attempt with the same order reference, so the
552
+ `Idempotency-Key` is the same. A new payment method from the browser is
553
+ ignored.
554
+ - The browser treats a lost connection, a timeout, a `5xx` or `pending` as
555
+ "the payment may have gone through": keep Pay disabled, say so, link to the
556
+ order status and keep asking the server. Enable Pay again only when the
557
+ server says nothing was sent (`open`).
558
+ - Remember the shopper's order reference (a cookie or local storage). A
559
+ reload while it is pending shows its status, never new card fields.
560
+ - Only a final answer closes a checkout: a declined payment, or a refusal of
561
+ the first send. Then a reload starts a new checkout with a new reference.
562
+
563
+ ## Hand-off landings (`relyon_cart`)
564
+
565
+ Policy setup is explicit, not a checkout-read side effect: follow the complete
566
+ print-on-demand example in `relyon-setup`. Saved privacy/terms links and supported
567
+ shipping/return links travel in existing protocol `links`; do not invent policy
568
+ summary properties. Contact uses `support.url`, `support.email`, `support.phone`.
569
+ Only describe `defective_only` as defects/damage-only, including its reporting
570
+ window and cost. Zero days promises no reporting period; `none` accepts no
571
+ returns. Keep plain-text conditions intact and never insert them as active HTML.
572
+
573
+ When an agent hands a shopper over to the store to finish paying, the shopper
574
+ lands on the store's checkout path with `?relyon_cart=…`.
575
+ `await kit.landing(request)` returns:
576
+
577
+ - `attributed: true`, `cart` (re-priced through `priceCart` just now),
578
+ `inputs`, `agentCheckoutId`, `protocol` and `channel` for a valid link.
579
+ Charge with `channel` and `agentCheckoutId` from it.
580
+ - `refusal` when `priceCart` refused the landed cart (show its message).
581
+ - `attributed: false` for no, expired or tampered links: a normal checkout
582
+ with the app's own cart. It never throws because of the link.
583
+
584
+ The kit records the landing as agent activity. Links come from
585
+ `kit.handoffUrl(protocol, sessionId)` (see `relyon-agents`).
586
+
587
+ The same call lands a Google cart transfer (`?relyon_transfer=…`, never
588
+ attributed) and accepts a URL, `URLSearchParams` or a Next.js `searchParams`
589
+ object as well as a `Request`. Show `landing.inputs` (variant lines carry their
590
+ `options`) and put the checkout marker `data-relyon-cart-items` on the page:
591
+ see `references/checkout-page.md`.
592
+
593
+ ## Never
594
+
595
+ - Never take a price, total or discount from the browser or from an agent
596
+ message; always re-price on the server.
597
+ - Never enable Pay again, start a new order reference or tell the shopper the
598
+ payment didn't go through after a payment was sent, unless the server has a
599
+ final answer.
600
+ - Never fulfill on a thank-you page load alone. A succeeded `createPayment`
601
+ result and `createOrder` are the record of payment.
602
+ - Never collect card numbers in the app's own inputs, and never log the
603
+ payment method object.