@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,176 @@
1
+ import { COMPLETE_CHECKOUT_SCHEMA, GET_CHECKOUT_SCHEMA, UPDATE_CHECKOUT_SCHEMA, containsCardData, validateToolInput } from "./webmcp-schema.js";
2
+ // The checkout-page script that exposes the store's checkout to a browser
3
+ // agent through WebMCP (`navigator.modelContext`). It is served by the kit
4
+ // from the store's own origin and only talks to the store's own origin. It
5
+ // does nothing at all when the browser has no `navigator.modelContext`.
6
+ //
7
+ // <script src="/relyon/webmcp.js" data-relyon-checkout="wmc_..." defer></script>
8
+ //
9
+ // Tools: get_checkout, update_checkout (UCP-shaped), complete_checkout.
10
+ // No tool accepts card data: the agent types the card into the
11
+ // <relyon-card-fields> iframe like any shopper. complete_checkout asks the
12
+ // person through `requestUserInteraction` to approve the total first.
13
+ /** Request header the script sets on tool calls, so the kit reports them as `mcp_tool_call` (client `webmcp`). */
14
+ export const WEBMCP_TOOL_HEADER = "relyon-webmcp-tool";
15
+ export function webMcpScript() {
16
+ const schemas = JSON.stringify({ get: GET_CHECKOUT_SCHEMA, update: UPDATE_CHECKOUT_SCHEMA, complete: COMPLETE_CHECKOUT_SCHEMA });
17
+ return `/* Relyon store kit: WebMCP checkout tools. */
18
+ (function () {
19
+ "use strict";
20
+ var script = document.currentScript || document.querySelector("script[data-relyon-checkout]");
21
+ var checkoutId = script && script.getAttribute("data-relyon-checkout");
22
+ var base = (script && script.getAttribute("data-relyon-base")) || "/relyon/webmcp";
23
+ var mc = typeof navigator !== "undefined" ? navigator.modelContext : undefined;
24
+ if (!checkoutId || !mc || (typeof mc.registerTool !== "function" && typeof mc.provideContext !== "function")) return;
25
+ var SCHEMAS = ${schemas};
26
+ var validateToolInput = ${validateToolInput.toString().replace(/^function validateToolInput/, "function")};
27
+ var containsCardData = ${containsCardData.toString().replace(/^function containsCardData/, "function")};
28
+ var TOOL_HEADER = ${JSON.stringify(WEBMCP_TOOL_HEADER)};
29
+
30
+ function endpoint(suffix) { return base + "/checkouts/" + encodeURIComponent(checkoutId) + (suffix || ""); }
31
+ function result(data, isError) {
32
+ var out = { content: [{ type: "text", text: JSON.stringify(data) }], structuredContent: data };
33
+ if (isError) out.isError = true;
34
+ return out;
35
+ }
36
+ function failure(code, message) { return result({ error: { code: code, message: message } }, true); }
37
+ function call(method, suffix, body, tool) {
38
+ var headers = { accept: "application/json" };
39
+ if (body !== undefined) headers["content-type"] = "application/json";
40
+ if (tool) headers[TOOL_HEADER] = tool;
41
+ return fetch(endpoint(suffix), { method: method, credentials: "same-origin", headers: headers, body: body === undefined ? undefined : JSON.stringify(body) })
42
+ .then(function (response) {
43
+ return response.json().then(function (data) { return { ok: response.ok, status: response.status, data: data }; },
44
+ function () { return { ok: false, status: response.status, data: { error: { code: "invalid_response", message: "The store answered without JSON." } } }; });
45
+ }, function () { return { ok: false, status: 0, data: { error: { code: "store_unreachable", message: "The store could not be reached." } } }; });
46
+ }
47
+ function cardFields() { return document.querySelector("relyon-card-fields"); }
48
+ function sync(session) {
49
+ var handler = session && session.payment && session.payment.handlers && session.payment.handlers[0];
50
+ var token = handler && handler.config && handler.config.client_token;
51
+ var element = cardFields();
52
+ if (token && element && element.getAttribute("client-token") !== token) element.setAttribute("client-token", token);
53
+ try { window.dispatchEvent(new CustomEvent("relyon:checkout", { detail: session })); } catch (e) { /* old browsers */ }
54
+ }
55
+ function totalOf(session) {
56
+ var totals = (session && session.totals) || [];
57
+ for (var i = 0; i < totals.length; i += 1) if (totals[i].type === "total") return totals[i];
58
+ return null;
59
+ }
60
+ function money(amount, currency) {
61
+ try { return new Intl.NumberFormat(undefined, { style: "currency", currency: currency }).format(amount / 100); }
62
+ catch (e) { return (amount / 100).toFixed(2) + " " + currency; }
63
+ }
64
+ function approvalPanel(session) {
65
+ return new Promise(function (resolve) {
66
+ var total = totalOf(session);
67
+ var panel = document.createElement("div");
68
+ panel.id = "relyon-approval";
69
+ panel.setAttribute("role", "dialog");
70
+ panel.setAttribute("aria-modal", "true");
71
+ panel.setAttribute("aria-labelledby", "relyon-approval-title");
72
+ panel.setAttribute("data-total", total ? String(total.amount) : "");
73
+ panel.setAttribute("data-currency", session.currency || "");
74
+ panel.style.cssText = "position:fixed;inset:auto 16px 16px auto;z-index:2147483647;max-width:360px;padding:16px;background:#fff;color:#111;border:1px solid #888;border-radius:8px;box-shadow:0 4px 24px rgba(0,0,0,.25);font:14px/1.4 system-ui,sans-serif";
75
+ var title = document.createElement("p");
76
+ title.id = "relyon-approval-title";
77
+ title.style.cssText = "margin:0 0 8px;font-weight:600";
78
+ title.textContent = "An agent wants to place this order";
79
+ var amount = document.createElement("p");
80
+ amount.style.margin = "0 0 12px";
81
+ amount.textContent = "Total " + (total ? money(total.amount, session.currency) : "unknown") + ". Approve to pay with the card entered on this page.";
82
+ var approve = document.createElement("button");
83
+ approve.id = "relyon-approve"; approve.type = "button"; approve.textContent = "Approve and pay";
84
+ var decline = document.createElement("button");
85
+ decline.id = "relyon-decline"; decline.type = "button"; decline.textContent = "Decline";
86
+ decline.style.marginLeft = "8px";
87
+ function done(answer) { panel.remove(); resolve(answer); }
88
+ approve.addEventListener("click", function () { done(true); });
89
+ decline.addEventListener("click", function () { done(false); });
90
+ panel.appendChild(title); panel.appendChild(amount); panel.appendChild(approve); panel.appendChild(decline);
91
+ document.body.appendChild(panel);
92
+ approve.focus();
93
+ });
94
+ }
95
+ function checked(schema, input) {
96
+ var value = input === undefined || input === null ? {} : input;
97
+ if (containsCardData(value)) return { error: failure("card_data_refused", "No tool accepts card data. Type the card into the card fields on the page.") };
98
+ var problem = validateToolInput(schema, value, "input");
99
+ if (problem) return { error: failure("invalid_input", problem) };
100
+ return { value: value };
101
+ }
102
+
103
+ function finish(r) {
104
+ var placed = r.ok && r.data && r.data.status === "completed";
105
+ if (placed) {
106
+ sync(r.data);
107
+ try { window.dispatchEvent(new CustomEvent("relyon:order", { detail: r.data })); } catch (e) { /* old browsers */ }
108
+ } else if (r.data && r.data.checkout) {
109
+ sync(r.data.checkout);
110
+ }
111
+ return result(r.data, !placed);
112
+ }
113
+
114
+ var tools = [
115
+ {
116
+ name: "get_checkout",
117
+ description: "Read this store's checkout: lines, address, shipping options, discounts, totals and status (UCP checkout shape).",
118
+ inputSchema: SCHEMAS.get,
119
+ annotations: { readOnlyHint: true },
120
+ execute: function (input) {
121
+ var c = checked(SCHEMAS.get, input);
122
+ if (c.error) return Promise.resolve(c.error);
123
+ return call("GET", "", undefined, "get_checkout").then(function (r) { if (r.ok) sync(r.data); return result(r.data, !r.ok); });
124
+ }
125
+ },
126
+ {
127
+ name: "update_checkout",
128
+ description: "Change the cart, shipping address, shipping option or discount codes (UCP checkout update fields). Never send card data; type the card into the card fields on the page after the last update.",
129
+ inputSchema: SCHEMAS.update,
130
+ execute: function (input) {
131
+ var c = checked(SCHEMAS.update, input);
132
+ if (c.error) return Promise.resolve(c.error);
133
+ return call("POST", "", c.value, "update_checkout").then(function (r) { if (r.ok) sync(r.data); return result(r.data, !r.ok); });
134
+ }
135
+ },
136
+ {
137
+ name: "complete_checkout",
138
+ description: "Place the order. The person approves the total on the page first; the card typed into the card fields pays. Returns the order confirmation.",
139
+ inputSchema: SCHEMAS.complete,
140
+ execute: function (input, client) {
141
+ var c = checked(SCHEMAS.complete, input);
142
+ if (c.error) return Promise.resolve(c.error);
143
+ return call("GET", "", undefined, null).then(function (current) {
144
+ if (!current.ok) return result(current.data, true);
145
+ var session = current.data;
146
+ if (session.status === "completed" && session.order_confirmation) return result(session);
147
+ if (session.status === "complete_in_progress") {
148
+ // The last payment's outcome is unknown. Reconcile it: the store
149
+ // resends the original request. No approval or card re-read.
150
+ return call("POST", "/complete", { reconcile: true }, "complete_checkout").then(finish);
151
+ }
152
+ if (session.status !== "ready_for_complete") return failure("not_ready", "The checkout isn't ready: add items and a shipping address first.");
153
+ var element = cardFields();
154
+ if (!element || typeof element.tokenize !== "function") return failure("card_fields_missing", "This page has no card fields.");
155
+ if (!client || typeof client.requestUserInteraction !== "function") return failure("approval_required", "Placing the order needs the person's approval, and this browser can't ask for it.");
156
+ return Promise.resolve(client.requestUserInteraction(function () { return approvalPanel(session); })).then(function (approved) {
157
+ if (approved !== true) return failure("approval_declined", "The person did not approve the order. Nothing was charged.");
158
+ var total = totalOf(session);
159
+ // The approval is recorded for this checkout and total; the
160
+ // complete call must present it.
161
+ return call("POST", "/approval", { total: total ? total.amount : null }, null).then(function (granted) {
162
+ if (!granted.ok) return result(granted.data, true);
163
+ return Promise.resolve().then(function () { return element.tokenize(); }).then(function (method) {
164
+ return call("POST", "/complete", { payment_method: method, approval_token: granted.data.approval_token }, "complete_checkout").then(finish);
165
+ }, function () { return failure("card_incomplete", "Type the card into the card fields on the page, then try again. Nothing was charged."); });
166
+ });
167
+ });
168
+ });
169
+ }
170
+ }
171
+ ];
172
+ if (typeof mc.registerTool === "function") { for (var i = 0; i < tools.length; i += 1) mc.registerTool(tools[i]); }
173
+ else mc.provideContext({ tools: tools });
174
+ })();
175
+ `;
176
+ }
@@ -0,0 +1,102 @@
1
+ import type { WebMcpCheckout, WebMcpPendingPayment } from "./webmcp.js";
2
+ type MaybePromise<T> = T | Promise<T>;
3
+ /** What `claimApproval` writes: the approval it consumes and the payment it records as pending. */
4
+ export interface WebMcpApprovalClaim {
5
+ /** The `jti` of the approval being used. The claim succeeds only while it is the outstanding one. */
6
+ jti: string;
7
+ /** The exact payment request about to be sent, recorded in the same step. */
8
+ pendingPayment: WebMcpPendingPayment;
9
+ updatedAt: number;
10
+ }
11
+ /**
12
+ * A store for WebMCP checkouts. Every stored checkout carries a `version`
13
+ * the store assigns (any write bumps it).
14
+ *
15
+ * - `put` writes a new checkout (the kit uses it only when creating one).
16
+ * - `compareAndSet` writes only if the stored version is still `expectedVersion`,
17
+ * so a stale server can't overwrite newer state.
18
+ * - `claimApproval` consumes the approval and records the pending payment in
19
+ * one atomic step. It succeeds only while that approval is outstanding and
20
+ * nothing is pending (`applyApprovalClaim` is the rule). Only the server whose
21
+ * claim succeeds sends the payment.
22
+ *
23
+ * Both guarded writes are required: `complete` refuses (nothing charged) with a
24
+ * store that lacks them, and never falls back to an unguarded write.
25
+ */
26
+ export interface WebMcpCheckoutStore {
27
+ get(id: string): MaybePromise<WebMcpCheckout | null>;
28
+ put(checkout: WebMcpCheckout): MaybePromise<void>;
29
+ /** The stored checkout (with its new version), or null when the version moved or the checkout is gone. */
30
+ compareAndSet(checkout: WebMcpCheckout, expectedVersion: number): MaybePromise<WebMcpCheckout | null>;
31
+ /** The claimed checkout (with its new version), or null when the approval is no longer outstanding. */
32
+ claimApproval(id: string, claim: WebMcpApprovalClaim): MaybePromise<WebMcpCheckout | null>;
33
+ }
34
+ /**
35
+ * The claim rule every store applies: the checkout after the claim, or null
36
+ * when the approval with `claim.jti` is no longer outstanding, a payment is
37
+ * already pending, or the payment went through (order pending or placed).
38
+ * The version is not bumped here.
39
+ */
40
+ export declare function applyApprovalClaim(checkout: WebMcpCheckout, claim: WebMcpApprovalClaim): WebMcpCheckout | null;
41
+ /** The default store: in memory, one process. Its writes are atomic because they run synchronously. */
42
+ export declare class MemoryWebMcpCheckoutStore implements WebMcpCheckoutStore {
43
+ private readonly max;
44
+ private readonly checkouts;
45
+ constructor(max?: number);
46
+ get(id: string): WebMcpCheckout | null;
47
+ put(checkout: WebMcpCheckout): void;
48
+ compareAndSet(checkout: WebMcpCheckout, expectedVersion: number): WebMcpCheckout | null;
49
+ claimApproval(id: string, claim: WebMcpApprovalClaim): WebMcpCheckout | null;
50
+ private write;
51
+ }
52
+ /** A value and the backend's version of it (a counter, an ETag, a row version...). */
53
+ export interface VersionedValue {
54
+ value: string;
55
+ version: string | number;
56
+ }
57
+ /**
58
+ * The small atomic key-value interface the shared store needs. Any backend
59
+ * with a conditional write works: Redis (WATCH/MULTI or a Lua script),
60
+ * Postgres (`UPDATE ... WHERE version = $n`), DynamoDB (a condition
61
+ * expression), etcd, Cloudflare Durable Objects...
62
+ */
63
+ export interface AtomicKeyValueStore {
64
+ get(key: string): MaybePromise<VersionedValue | null>;
65
+ /**
66
+ * Writes `value` only if the stored version is still `expectedVersion`
67
+ * (`null`: only if the key doesn't exist). True when written. It must be
68
+ * atomic across every server sharing the store.
69
+ */
70
+ setIfVersion(key: string, value: string, expectedVersion: string | number | null): MaybePromise<boolean>;
71
+ }
72
+ /** An in-memory `AtomicKeyValueStore`: the reference implementation, and a store tests can share between kit instances. */
73
+ export declare class MemoryAtomicKeyValueStore implements AtomicKeyValueStore {
74
+ private readonly values;
75
+ get(key: string): VersionedValue | null;
76
+ setIfVersion(key: string, value: string, expectedVersion: string | number | null): boolean;
77
+ }
78
+ export interface SharedWebMcpCheckoutStoreOptions {
79
+ /** Key prefix. Default `relyon:webmcp:`. */
80
+ prefix?: string;
81
+ /** How often a claim or `put` re-reads after losing a write to an unrelated change. Default 5. */
82
+ maxRetries?: number;
83
+ }
84
+ /**
85
+ * A WebMCP checkout store shared by several servers, over any
86
+ * `AtomicKeyValueStore`. Checkouts are stored as JSON under `<prefix><id>`;
87
+ * every guarded write is the backend's own conditional write, so the claim
88
+ * and compare-and-set hold across servers.
89
+ */
90
+ export declare class SharedWebMcpCheckoutStore implements WebMcpCheckoutStore {
91
+ private readonly kv;
92
+ private readonly prefix;
93
+ private readonly maxRetries;
94
+ constructor(kv: AtomicKeyValueStore, options?: SharedWebMcpCheckoutStoreOptions);
95
+ private key;
96
+ private read;
97
+ get(id: string): Promise<WebMcpCheckout | null>;
98
+ put(checkout: WebMcpCheckout): Promise<void>;
99
+ compareAndSet(checkout: WebMcpCheckout, expectedVersion: number): Promise<WebMcpCheckout | null>;
100
+ claimApproval(id: string, claim: WebMcpApprovalClaim): Promise<WebMcpCheckout | null>;
101
+ }
102
+ export {};
@@ -0,0 +1,116 @@
1
+ /**
2
+ * The claim rule every store applies: the checkout after the claim, or null
3
+ * when the approval with `claim.jti` is no longer outstanding, a payment is
4
+ * already pending, or the payment went through (order pending or placed).
5
+ * The version is not bumped here.
6
+ */
7
+ export function applyApprovalClaim(checkout, claim) {
8
+ if (checkout.status === "completed" || checkout.status === "order_pending" || checkout.pendingPayment || !checkout.approval || checkout.approval.jti !== claim.jti)
9
+ return null;
10
+ return { ...checkout, approval: null, pendingPayment: { ...claim.pendingPayment }, updatedAt: claim.updatedAt };
11
+ }
12
+ const versionOf = (checkout) => checkout?.version ?? 0;
13
+ const copy = (checkout) => structuredClone(checkout);
14
+ /** The default store: in memory, one process. Its writes are atomic because they run synchronously. */
15
+ export class MemoryWebMcpCheckoutStore {
16
+ max;
17
+ checkouts = new Map();
18
+ constructor(max = 10_000) {
19
+ this.max = max;
20
+ }
21
+ get(id) {
22
+ const found = this.checkouts.get(id);
23
+ return found ? copy(found) : null;
24
+ }
25
+ put(checkout) {
26
+ this.write({ ...checkout, version: versionOf(this.checkouts.get(checkout.id)) + 1 });
27
+ }
28
+ compareAndSet(checkout, expectedVersion) {
29
+ const current = this.checkouts.get(checkout.id);
30
+ if (!current || versionOf(current) !== expectedVersion)
31
+ return null;
32
+ return this.write({ ...checkout, version: expectedVersion + 1 });
33
+ }
34
+ claimApproval(id, claim) {
35
+ const current = this.checkouts.get(id);
36
+ const claimed = current ? applyApprovalClaim(current, claim) : null;
37
+ return claimed ? this.write({ ...claimed, version: versionOf(current) + 1 }) : null;
38
+ }
39
+ write(checkout) {
40
+ this.checkouts.delete(checkout.id);
41
+ this.checkouts.set(checkout.id, copy(checkout));
42
+ while (this.checkouts.size > this.max)
43
+ this.checkouts.delete(this.checkouts.keys().next().value);
44
+ return copy(checkout);
45
+ }
46
+ }
47
+ /** An in-memory `AtomicKeyValueStore`: the reference implementation, and a store tests can share between kit instances. */
48
+ export class MemoryAtomicKeyValueStore {
49
+ values = new Map();
50
+ get(key) {
51
+ const found = this.values.get(key);
52
+ return found ? { ...found } : null;
53
+ }
54
+ setIfVersion(key, value, expectedVersion) {
55
+ const found = this.values.get(key);
56
+ if (expectedVersion === null ? found !== undefined : found?.version !== expectedVersion)
57
+ return false;
58
+ this.values.set(key, { value, version: (found?.version ?? 0) + 1 });
59
+ return true;
60
+ }
61
+ }
62
+ /**
63
+ * A WebMCP checkout store shared by several servers, over any
64
+ * `AtomicKeyValueStore`. Checkouts are stored as JSON under `<prefix><id>`;
65
+ * every guarded write is the backend's own conditional write, so the claim
66
+ * and compare-and-set hold across servers.
67
+ */
68
+ export class SharedWebMcpCheckoutStore {
69
+ kv;
70
+ prefix;
71
+ maxRetries;
72
+ constructor(kv, options = {}) {
73
+ this.kv = kv;
74
+ this.prefix = options.prefix ?? "relyon:webmcp:";
75
+ this.maxRetries = options.maxRetries ?? 5;
76
+ }
77
+ key(id) {
78
+ return `${this.prefix}${id}`;
79
+ }
80
+ async read(id) {
81
+ const found = await this.kv.get(this.key(id));
82
+ return found ? { checkout: JSON.parse(found.value), version: found.version } : null;
83
+ }
84
+ async get(id) {
85
+ return (await this.read(id))?.checkout ?? null;
86
+ }
87
+ async put(checkout) {
88
+ for (let attempt = 0; attempt <= this.maxRetries; attempt += 1) {
89
+ const current = await this.read(checkout.id);
90
+ const next = { ...checkout, version: versionOf(current?.checkout) + 1 };
91
+ if (await this.kv.setIfVersion(this.key(checkout.id), JSON.stringify(next), current?.version ?? null))
92
+ return;
93
+ }
94
+ throw new Error("The shared WebMCP checkout store kept changing; the checkout wasn't written.");
95
+ }
96
+ async compareAndSet(checkout, expectedVersion) {
97
+ const current = await this.read(checkout.id);
98
+ if (!current || versionOf(current.checkout) !== expectedVersion)
99
+ return null;
100
+ const next = { ...checkout, version: expectedVersion + 1 };
101
+ return (await this.kv.setIfVersion(this.key(checkout.id), JSON.stringify(next), current.version)) ? next : null;
102
+ }
103
+ async claimApproval(id, claim) {
104
+ for (let attempt = 0; attempt <= this.maxRetries; attempt += 1) {
105
+ const current = await this.read(id);
106
+ const claimed = current ? applyApprovalClaim(current.checkout, claim) : null;
107
+ if (!current || !claimed)
108
+ return null;
109
+ const next = { ...claimed, version: versionOf(current.checkout) + 1 };
110
+ // Lost to another write: re-read, since it may have been unrelated (or the winning claim).
111
+ if (await this.kv.setIfVersion(this.key(id), JSON.stringify(next), current.version))
112
+ return next;
113
+ }
114
+ throw new Error("The shared WebMCP checkout store kept changing; the approval wasn't claimed.");
115
+ }
116
+ }
@@ -0,0 +1,242 @@
1
+ import { type CardFields, type CardFieldsInput, type CreatePaymentInput, type CreatePaymentOptions, type CreatePaymentResult } from "./checkout.js";
2
+ import { type OrderConfirmation, type OrderRefusal } from "./confirmation.js";
3
+ import type { KitContext } from "./context.js";
4
+ import { type AgentIdentity } from "./identify.js";
5
+ import type { Cart, CartInputs, CartLineInput, Address, PaymentLike, RequestInfo } from "./types.js";
6
+ import { type WebMcpCheckoutStore } from "./webmcp-store.js";
7
+ export { MemoryWebMcpCheckoutStore, type WebMcpCheckoutStore } from "./webmcp-store.js";
8
+ export declare const WEBMCP_TOOLS: readonly ["get_checkout", "update_checkout", "complete_checkout"];
9
+ export type WebMcpTool = (typeof WEBMCP_TOOLS)[number];
10
+ export interface WebMcpCheckout {
11
+ id: string;
12
+ orderReference: string;
13
+ inputs: CartInputs;
14
+ cart: Cart | null;
15
+ messages: Array<{
16
+ type: "error" | "info";
17
+ code: string;
18
+ content: string;
19
+ }>;
20
+ /** The card-field session for the current total. */
21
+ paymentSession: {
22
+ id: string;
23
+ clientToken: string;
24
+ amount: number;
25
+ currency: string;
26
+ } | null;
27
+ /**
28
+ * Stored status. `order_pending`: the payment succeeded (it is in
29
+ * `succeededPayment`, nothing is pending, so nothing can send it again)
30
+ * but the store's order isn't confirmed created yet; the next complete
31
+ * creates it, then stores `completed`. The session JSON reports
32
+ * `complete_in_progress` while the order is pending or a payment outcome is unknown.
33
+ */
34
+ status: "incomplete" | "ready_for_complete" | "order_pending" | "completed";
35
+ /** Set when the payment succeeded. Shown to agents only once the checkout is `completed`. */
36
+ confirmation: OrderConfirmation | null;
37
+ /** The succeeded payment, kept from `order_pending` on: the order is created from it, never from a new payment. */
38
+ succeededPayment?: PaymentLike | null;
39
+ /**
40
+ * SHA-256 of the checkout-page session secret. The secret lives only in the
41
+ * HttpOnly, SameSite=Strict cookie the store's checkout page sets
42
+ * (`sessionCookie`); every checkout endpoint requires it. Missing = refused.
43
+ */
44
+ sessionHash?: string;
45
+ /** Server-only key that signs this checkout's approval tokens. Never sent anywhere. */
46
+ approvalKey?: string;
47
+ /** The one outstanding approval token (single use; cleared by updates and on use). */
48
+ approval?: WebMcpApproval | null;
49
+ /** Payment attempts after confirmed declines (0 = the first). Each gets its own Idempotency-Key. */
50
+ paymentAttempt?: number;
51
+ /**
52
+ * A payment whose outcome is unknown. Holds the original request (attempt
53
+ * and the card fields' encrypted payload) so a retry resends exactly it
54
+ * under the same Idempotency-Key, never re-reading the card. Cleared once
55
+ * Relyon gives a final answer.
56
+ */
57
+ pendingPayment?: WebMcpPendingPayment | null;
58
+ /**
59
+ * Assigned by the store: every write bumps it. The kit's writes after
60
+ * creation are compare-and-set on it, so a stale server can't overwrite
61
+ * newer state.
62
+ */
63
+ version?: number;
64
+ createdAt: number;
65
+ updatedAt: number;
66
+ }
67
+ export interface WebMcpApproval {
68
+ jti: string;
69
+ expiresAt: number;
70
+ }
71
+ export interface WebMcpPendingPayment {
72
+ attempt: number;
73
+ idempotencyKey: string;
74
+ /** The card fields' encrypted `tokenize()` result, exactly as first sent. */
75
+ paymentMethod: Record<string, string>;
76
+ since: number;
77
+ /**
78
+ * `sending`: the request that claimed the approval is sending it now (a
79
+ * complete arriving meanwhile, from another server, is told the approval
80
+ * was already used). `unknown` (or absent, for records written before
81
+ * this field): Relyon's answer was lost, and the next complete reconciles.
82
+ * A `sending` record older than the send lease counts as unknown, in case
83
+ * the sending server died.
84
+ */
85
+ state?: "sending" | "unknown";
86
+ }
87
+ /** The checkout-page session cookie for a checkout (`__Host-`: Secure, Path=/, no Domain). */
88
+ export declare const webMcpSessionCookieName: (checkoutId: string) => string;
89
+ /** How long an approval token stays usable. */
90
+ export declare const WEBMCP_APPROVAL_TTL_MS: number;
91
+ export interface WebMcpOptions {
92
+ /**
93
+ * Where checkouts live between steps. Default: in memory (one process). A
94
+ * store running the kit on several servers needs one shared store with the
95
+ * atomic approval claim, such as `SharedWebMcpCheckoutStore`.
96
+ */
97
+ store?: WebMcpCheckoutStore;
98
+ /** The store's confirmation page for an order reference (same origin). Returned as `order.permalink_url`. */
99
+ confirmationUrl?: (orderReference: string) => string;
100
+ }
101
+ export interface CreateWebMcpCheckoutInput {
102
+ lines: CartLineInput[];
103
+ address?: Address | null;
104
+ coupons?: string[];
105
+ shippingOptionId?: string | null;
106
+ /** The store's order reference. Default: a new `wmc-...` one. */
107
+ orderReference?: string;
108
+ }
109
+ export interface WebMcpCheckoutPage {
110
+ checkout: WebMcpCheckout;
111
+ /** The UCP-shaped session JSON the tools return. */
112
+ session: Record<string, unknown>;
113
+ /** The `<script>` tag for the checkout page. */
114
+ scriptTag: string;
115
+ /** The card fields for the current total, when the checkout is ready. */
116
+ cardFields: CardFields | null;
117
+ /**
118
+ * The `Set-Cookie` value the checkout page response must carry. It binds
119
+ * the checkout's endpoints (and its approvals) to this page session.
120
+ */
121
+ sessionCookie: string;
122
+ }
123
+ interface Hooks {
124
+ cardFields(input: CardFieldsInput): Promise<CardFields>;
125
+ createPayment(input: CreatePaymentInput, options?: CreatePaymentOptions): Promise<CreatePaymentResult>;
126
+ identify(request: Request): Promise<AgentIdentity>;
127
+ }
128
+ export declare class WebMcpCheckouts {
129
+ private readonly ctx;
130
+ private readonly hooks;
131
+ private readonly options;
132
+ private readonly store;
133
+ /** The tail of each checkout's queued steps (see `serialized`). */
134
+ private readonly inFlight;
135
+ constructor(ctx: KitContext, hooks: Hooks, options?: WebMcpOptions);
136
+ private get base();
137
+ /** The script's URL on the store's origin. */
138
+ get scriptPath(): string;
139
+ scriptTag(checkoutId: string): string;
140
+ /** Starts a checkout for the store's checkout page: prices it and, when ready, opens card fields for the total. */
141
+ create(input: CreateWebMcpCheckoutInput): Promise<WebMcpCheckoutPage>;
142
+ get(id: string): Promise<WebMcpCheckout | null>;
143
+ /** Answers the script and the checkout endpoints; null for other paths. */
144
+ handle(request: Request, info: RequestInfo, path: string): Promise<Response | null>;
145
+ /**
146
+ * Runs one checkout's steps one at a time (in this process). This is an
147
+ * extra guard: across servers, the store's atomic approval claim decides
148
+ * which request sends the payment, every later write is compare-and-set on
149
+ * the checkout's version, and Relyon's Idempotency-Key is the backstop (one
150
+ * charge per attempt key).
151
+ */
152
+ private serialized;
153
+ /** Records a tool call (when the script marked one) and answers. */
154
+ private answer;
155
+ /**
156
+ * Fail closed for identified agents; refuse by a named Relyon rule. null
157
+ * when the step may go ahead. A refusal on an order-pending checkout (the
158
+ * payment already went through) never says nothing was charged.
159
+ */
160
+ private gate;
161
+ /**
162
+ * Whether a refusal may say nothing was charged. `unpaid`: no such
163
+ * checkout, or this page session's checkout has no payment sent, pending
164
+ * or succeeded. `order_pending`: this page session's checkout was paid and
165
+ * its order is being placed. Anything else (another caller, a pending or
166
+ * finished payment, a failed read) is `unestablished`.
167
+ */
168
+ private paymentStanding;
169
+ private ownsSession;
170
+ /**
171
+ * Loads the checkout for a request from its own checkout page: the page
172
+ * session cookie must match. Anyone else (no cookie, another browser, a
173
+ * direct caller with only the checkout id) is refused and nothing happens.
174
+ */
175
+ private load;
176
+ private read;
177
+ private update;
178
+ /** The MAC input: the token is bound to the checkout, page session, attempt, total, currency and priced cart. */
179
+ private approvalMac;
180
+ /**
181
+ * Issues the approval token when the person approves on the checkout page.
182
+ * Requires the page session cookie and a same-origin browser request
183
+ * (Sec-Fetch-Site / Origin). The token is single use, expires, and is bound
184
+ * to this checkout, its page session, payment attempt, total, currency and
185
+ * priced cart; `complete` verifies all of it.
186
+ */
187
+ private approve;
188
+ /** null when the token is valid for this checkout as it is now; otherwise the refusal code. */
189
+ private approvalProblem;
190
+ /**
191
+ * Pays with an approval token. The pre-charge checks (page session, the
192
+ * agent-rules decision, the token) all run before the approval is used;
193
+ * then the store's atomic claim consumes the approval and records the
194
+ * exact payment request in one step, and only the request whose claim
195
+ * succeeded sends it. A store that can't claim refuses, nothing charged.
196
+ */
197
+ private complete;
198
+ /** Sends (or resends) the pending payment and records what Relyon answered. */
199
+ private settle;
200
+ /**
201
+ * Creates the order for an order-pending checkout (through the order
202
+ * claim, so once per payment across servers), then stores and reports
203
+ * `completed`. Until both happen the answer is order pending.
204
+ */
205
+ private finishOrder;
206
+ /**
207
+ * Writes the outcome of `pending` with compare-and-set. A newer version
208
+ * that still holds the same payment (same Idempotency-Key) is retried on;
209
+ * anything else means another request already recorded the outcome.
210
+ */
211
+ private record;
212
+ /** The payment's outcome is unknown: keep it pending (now reconcilable) and say so. */
213
+ private outcomeUnknown;
214
+ /** Relyon answered, but the store couldn't record it: the next complete reconciles once the send lease passes. */
215
+ private unrecorded;
216
+ /** True when the store has the guarded writes (atomic claim, compare-and-set) every write after creation needs. */
217
+ private guardedWrites;
218
+ /** How long a claimed payment counts as being sent: twice Relyon's timeout, plus a margin. */
219
+ private get sendLeaseMs();
220
+ private beingSent;
221
+ private approvalAlreadyUsed;
222
+ private checkoutChanged;
223
+ /** The checkout store can't make (or failed to make) a guarded write. Nothing was charged. */
224
+ private storeUnavailable;
225
+ /** The payment went through; the store's order is being placed. Never "nothing was charged", never a new approval. */
226
+ private orderPending;
227
+ /** Says the outcome is unknown and where to check the order status. */
228
+ private unknownOutcome;
229
+ private price;
230
+ /** A card-field session for the current total (sessions have a fixed amount). Mutates `checkout`. */
231
+ private ensurePaymentSession;
232
+ /** The checkout as UCP-shaped session JSON. */
233
+ session(checkout: WebMcpCheckout): Record<string, unknown>;
234
+ }
235
+ /**
236
+ * A refused or unavailable payment as an order refusal; null for other errors
237
+ * (including `PaymentOutcomeUnknownError`, which is not a refusal).
238
+ */
239
+ export declare function refusalFor(orderReference: string, error: unknown): {
240
+ status: number;
241
+ body: OrderRefusal;
242
+ } | null;