@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
package/dist/relay.js ADDED
@@ -0,0 +1,655 @@
1
+ import { AGENT_CHECKOUT_OPERATION_PATH } from "./wire-names.js";
2
+ import { withPolicyLinks } from "./policies.js";
3
+ import { mergeInputs } from "./protocol-inputs.js";
4
+ import { RelyonAccountNotReadyError, RelyonProblemError, RelyonUnavailableError } from "./relyon.js";
5
+ import { StoreRefusal } from "./types.js";
6
+ import { claimsNothingCharged } from "./charge-claims.js";
7
+ import { handoffPaymentKey, storePaymentRecord } from "./store-payments.js";
8
+ import { describeError, handoffTokenConsumed, issuedCartToken, redactCartTokens } from "./relyon-cart-tokens.js";
9
+ import { isRecord, lowerCaseHeaders, randomId, sha256, tryParseJson, withUpperCurrency } from "./util.js";
10
+ import { withSingleValueOptions } from "./variants.js";
11
+ /**
12
+ * Relyon Problems on `complete` that the contract defines as refused before
13
+ * any charge. Every other Problem on `complete` is an unknown outcome.
14
+ */
15
+ const PRE_CHARGE_PROBLEMS = new Set(["cart_changed", "rate_limited", "protocol_not_available", "agent_refused"]);
16
+ /**
17
+ * The Idempotency-Key the kit sends Relyon for one step. With the agent's own
18
+ * key it is derived from that key. Without one, `complete` gets a key derived
19
+ * from the exact request (protocol, operation, checkout, URL, body), so
20
+ * resending the same `complete` reconciles the original attempt and a
21
+ * different request (a new instrument after a decline) gets its own key.
22
+ * The other operations keep a fresh key per call.
23
+ */
24
+ export function relayIdempotencyKey(step, url, agentKey) {
25
+ if (agentKey)
26
+ return `sk-ac-${sha256([step.protocol, step.operation, url, agentKey].join("\n"))}`;
27
+ if (step.operation === "complete") {
28
+ return `sk-ac-${sha256(["request", step.protocol, step.operation, step.sessionId ?? "", url, sha256(step.rawBody)].join("\n"))}`;
29
+ }
30
+ return randomId("sk-ac-");
31
+ }
32
+ /**
33
+ * Order-pending markers the checkout state store refused to save, per state
34
+ * store, by `<protocol>:<checkout>`. A read must never show `completed` just
35
+ * because saving the marker failed, so the kit keeps it here (in this
36
+ * process) until a later save succeeds or the order is known to exist.
37
+ */
38
+ const unsavedOrderPending = new WeakMap();
39
+ function unsavedMarkers(state) {
40
+ let markers = unsavedOrderPending.get(state);
41
+ if (!markers) {
42
+ markers = new Map();
43
+ unsavedOrderPending.set(state, markers);
44
+ }
45
+ return markers;
46
+ }
47
+ const markerKey = (protocol, sessionId) => `${protocol}:${sessionId}`;
48
+ /** Headers that describe the store's own connection; never copied onto the agent's response. */
49
+ const HOP_BY_HOP = new Set(["connection", "keep-alive", "transfer-encoding", "upgrade", "proxy-connection", "te", "trailer"]);
50
+ /**
51
+ * Relays one agent checkout step: rebuilds the agent's exact request on the
52
+ * store's public https URL, prices the cart with the store's `priceCart`,
53
+ * calls `handleAgentCheckout`, and returns Relyon's status, headers and body
54
+ * unchanged. A paid `complete` creates the store's order once; until the
55
+ * order exists the step is order pending (and so is a read of the checkout),
56
+ * never `completed`. When Relyon
57
+ * can't give a usable answer the step is refused: it never runs without Relyon.
58
+ * For `complete` that answer is an unknown payment outcome instead, unless
59
+ * Relyon refused it before any charge.
60
+ */
61
+ export async function relayStep(ctx, step) {
62
+ const stored = step.sessionId ? await ctx.state.get(step.protocol, step.sessionId) : null;
63
+ // A marker the state store refused to save still counts.
64
+ const unsaved = step.sessionId ? unsavedMarkers(ctx.state).get(markerKey(step.protocol, step.sessionId)) : undefined;
65
+ const previous = stored && unsaved && !stored.orderPending ? { ...stored, orderPending: unsaved } : stored;
66
+ let inputs = null;
67
+ if (step.operation === "create") {
68
+ inputs = mergeInputs(null, step.patch ?? {});
69
+ }
70
+ else if (step.operation === "update") {
71
+ if (!previous && !step.patch?.lines)
72
+ return { kind: "refused", code: "not_found", message: "This checkout is not known to this store. Start a new checkout." };
73
+ inputs = mergeInputs(previous?.inputs ?? null, step.patch ?? {});
74
+ }
75
+ else if (step.operation === "complete") {
76
+ if (!previous)
77
+ return { kind: "refused", code: "not_found", message: "This checkout is not known to this store. Start a new checkout." };
78
+ // Paid (or being paid) on the store's own checkout page: Relyon must never
79
+ // charge it again, so the kit answers and nothing is relayed. Only UCP's
80
+ // complete can charge at Relyon (a wallet token); ACP's never charges and
81
+ // MCP's is refused before any charge, so theirs are relayed.
82
+ if (step.protocol === "ucp" && await paidOnStore(ctx, previous)) {
83
+ ctx.logger.warn("an agent's complete names a checkout paid on the store's own page; answered by the kit, not relayed", { protocol: step.protocol });
84
+ return { kind: "refused", code: PAID_ON_STORE, status: 409, message: PAID_ON_STORE_MESSAGE };
85
+ }
86
+ inputs = previous.inputs;
87
+ }
88
+ let cart = null;
89
+ if (inputs) {
90
+ try {
91
+ // An agent needn't name an option that has only one value (Brief 86):
92
+ // fill those in from the catalog before the store prices the cart.
93
+ // Options with several values stay unset for the store to refuse with
94
+ // its choice list, and options the agent named always win.
95
+ const lines = await Promise.all(inputs.lines.map(async (line) => {
96
+ const product = ctx.catalogReads
97
+ ? await ctx.catalogReads.get(line.product_id).catch(() => null)
98
+ : ctx.catalog.get(line.product_id) ?? null;
99
+ return withSingleValueOptions(line, product);
100
+ }));
101
+ cart = await ctx.hooks.priceCart(lines, inputs.address, inputs.coupons, {
102
+ protocol: step.protocol, operation: step.operation, shippingOptionId: inputs.shipping_option_id,
103
+ agentCheckoutId: previous?.agentCheckoutId ?? null,
104
+ });
105
+ }
106
+ catch (error) {
107
+ if (error instanceof StoreRefusal)
108
+ return { kind: "refused", code: error.code, status: error.status, message: error.message };
109
+ ctx.logger.error("priceCart failed", { error: describeError(error, true) });
110
+ return { kind: "refused", code: "internal_error" };
111
+ }
112
+ cart = withUpperCurrency(cart);
113
+ if (step.operation === "complete" && previous?.locked)
114
+ cart = { ...cart, ...previous.locked };
115
+ }
116
+ const headers = lowerCaseHeaders(step.request.headers);
117
+ const publicUrl = ctx.publicUrl(step.request);
118
+ // The host the agent called: a Test loopback store keeps its port.
119
+ headers.host = new URL(publicUrl).host;
120
+ const agentRequest = {
121
+ method: step.request.method.toUpperCase(),
122
+ url: publicUrl,
123
+ headers,
124
+ ...(step.rawBody ? { body: step.rawBody } : {}),
125
+ };
126
+ const idempotencyKey = relayIdempotencyKey(step, agentRequest.url, headers["idempotency-key"]);
127
+ // ACP requires an Idempotency-Key on the agent's own request and signs only
128
+ // the body, so a keyless ACP complete carries the derived key inward too:
129
+ // Relyon's adapter then runs it and replays it on a resend. UCP can't get
130
+ // one: its RFC 9421 signature must cover idempotency-key whenever present,
131
+ // so an added header would fail verification; Relyon refuses a keyless UCP
132
+ // complete before any charge.
133
+ if (step.operation === "complete" && step.protocol === "acp" && headers["idempotency-key"] === undefined) {
134
+ headers["idempotency-key"] = idempotencyKey;
135
+ }
136
+ let result;
137
+ /** Relyon's 2xx body as received, kept to read a pending payment out of an answer the kit can't use. */
138
+ let rawAnswer;
139
+ try {
140
+ ({ data: result } = await ctx.gateway.call((client) => client.POST(AGENT_CHECKOUT_OPERATION_PATH, {
141
+ params: { path: { protocol: step.protocol, operation: step.operation }, header: { "Idempotency-Key": idempotencyKey } },
142
+ body: { request: agentRequest, ...(cart ? { cart } : {}) },
143
+ }).then((answer) => {
144
+ rawAnswer = answer.data;
145
+ return { ...answer, data: answer.data === undefined ? undefined : readResult(answer.data) };
146
+ }), (data) => data !== null && data !== undefined));
147
+ }
148
+ catch (error) {
149
+ if (step.operation === "complete")
150
+ return completeFailure(ctx, step, error, rawAnswer);
151
+ if (error instanceof RelyonUnavailableError) {
152
+ ctx.logger.warn("Relyon is unavailable; agent checkout step refused", { kind: error.kind, protocol: step.protocol, operation: step.operation });
153
+ return { kind: "refused", code: "service_unavailable" };
154
+ }
155
+ if (error instanceof RelyonAccountNotReadyError)
156
+ return accountNotReady(ctx, step, error);
157
+ if (error instanceof RelyonProblemError) {
158
+ if (error.code === "protocol_not_available")
159
+ return { kind: "refused", code: "protocol_not_available" };
160
+ if (error.code === "cart_changed")
161
+ return { kind: "refused", code: "cart_changed", status: 409, message: "The cart changed since it was shown. Read the checkout again." };
162
+ if (error.status === 429)
163
+ return { kind: "refused", code: "rate_limited", status: 429, message: "Too many requests. Try again shortly." };
164
+ ctx.logger.error("Relyon refused the store's agent checkout request", {
165
+ status: error.status, code: error.code, message: redactCartTokens(error.message), param: error.param === undefined || error.param === null ? error.param : redactCartTokens(String(error.param)),
166
+ // Each failing field and why (Relyon names them), for the store's builder.
167
+ ...(Array.isArray(error.problem?.errors) ? {
168
+ errors: error.problem.errors.slice(0, 10).filter(isRecord).map((row) => `${redactCartTokens(String(row.param ?? ""))}: ${redactCartTokens(String(row.message ?? row.code ?? ""))}`),
169
+ } : {}),
170
+ ...(error.developer_hint ? { developer_hint: error.developer_hint } : {}),
171
+ });
172
+ return { kind: "refused", code: "internal_error" };
173
+ }
174
+ throw error;
175
+ }
176
+ // Once Relyon answered `complete`, its answer reaches the agent even when the
177
+ // store's own bookkeeping fails: the kit must never turn a possible charge
178
+ // into its generic "nothing was charged" error. A resent `complete` replays
179
+ // the same answer and creates the order then.
180
+ const afterCharge = async (what, run) => {
181
+ try {
182
+ await run();
183
+ }
184
+ catch (error) {
185
+ if (step.operation !== "complete")
186
+ throw error;
187
+ ctx.logger.error(`${what} failed after Relyon answered complete; Relyon's answer is relayed`, {
188
+ protocol: step.protocol, error: describeError(error, true),
189
+ });
190
+ }
191
+ };
192
+ // Only a succeeded payment creates the order; pending or processing never does.
193
+ let orderCreated = false;
194
+ /** The succeeded payment whose order isn't created yet; null when there is none. */
195
+ let pendingPayment = null;
196
+ /** True when this complete settled the order question (created, or knowingly not yet created). */
197
+ let orderSettled = false;
198
+ if (step.operation === "complete" && cart && result.payment?.status === "succeeded") {
199
+ const payment = result.payment;
200
+ let order;
201
+ try {
202
+ order = await ctx.createOrderOnce(cart, payment);
203
+ }
204
+ catch (error) {
205
+ // The checkout state store failed around the claim: the order isn't known to exist.
206
+ ctx.logger.error("creating the store's order failed after Relyon answered complete", {
207
+ protocol: step.protocol, payment: payment.id, error: describeError(error, true),
208
+ });
209
+ order = { created: false, status: "failed", error };
210
+ }
211
+ orderCreated = order.created;
212
+ orderSettled = true;
213
+ if (order.status === "failed") {
214
+ pendingPayment = payment;
215
+ }
216
+ else if (order.status === "in_progress") {
217
+ if (typeof ctx.state.orderClaimStatus === "function") {
218
+ pendingPayment = payment;
219
+ }
220
+ else {
221
+ // Without `orderClaimStatus` the kit can't tell "another request is
222
+ // creating it" from "it was created": an order that exists must never
223
+ // be shown as pending forever, so Relyon's answer is relayed.
224
+ ctx.logger.warn("The checkout state store has no orderClaimStatus, so the kit can't tell whether the order exists; Relyon's answer is relayed", {
225
+ protocol: step.protocol, payment: payment.id,
226
+ });
227
+ }
228
+ }
229
+ }
230
+ // The Relyon hand-off link this answer carries (read only; the body is
231
+ // relayed unchanged). `kit.landing` accepts exactly the latest one, once:
232
+ // only a token that names this checkout counts, and one already landed is
233
+ // never recorded again.
234
+ const answeredSessionId = step.sessionId ?? sessionIdOf(result);
235
+ const capture = () => {
236
+ if (result.decision !== "allowed")
237
+ return null;
238
+ const token = issuedCartToken(result.body, {
239
+ ids: [answeredSessionId, result.agentCheckoutId, previous?.agentCheckoutId], hostnames: ctx.hostnames, livemode: ctx.gateway.livemode,
240
+ });
241
+ return token && !handoffTokenConsumed(ctx, token) ? token : null;
242
+ };
243
+ const issued = capture();
244
+ let recordSaved = false;
245
+ if (result.decision === "allowed" && cart && inputs) {
246
+ const sessionId = answeredSessionId;
247
+ if (sessionId) {
248
+ recordSaved = true;
249
+ // A changed cart without a new link drops the old one: it no longer stands for this cart.
250
+ const cartChanged = step.operation === "create"
251
+ || (step.operation === "update" && JSON.stringify(inputs) !== JSON.stringify(previous?.inputs ?? null));
252
+ const handoffToken = issued ?? (cartChanged ? null : previous?.handoffToken ?? null);
253
+ // When the kit first saw this link: kept while the link is the same, so
254
+ // repeating an unchanged step never extends a Test link's landing window.
255
+ const sameLink = handoffToken !== null && handoffToken === (previous?.handoffToken ?? null);
256
+ const handoffTokenAt = handoffToken === null ? null : sameLink ? previous?.handoffTokenAt ?? null : ctx.now();
257
+ // The order-pending marker: set while the order isn't created, cleared
258
+ // once it is (or the kit can't tell), kept by every other step.
259
+ const kept = previous?.orderPending ?? null;
260
+ const orderPending = pendingPayment
261
+ ? { paymentId: pendingPayment.id, since: kept?.paymentId === pendingPayment.id ? kept.since : ctx.now() }
262
+ : orderSettled ? null : kept;
263
+ const markers = unsavedMarkers(ctx.state);
264
+ const key = markerKey(step.protocol, sessionId);
265
+ let saved = false;
266
+ try {
267
+ await afterCharge("saving the checkout", async () => {
268
+ await ctx.state.put({
269
+ protocol: step.protocol, sessionId, agentCheckoutId: result.agentCheckoutId ?? previous?.agentCheckoutId ?? null,
270
+ inputs, locked: result.locked ?? previous?.locked ?? null, ...(orderPending ? { orderPending } : {}),
271
+ ...(handoffToken ? { handoffToken, ...(handoffTokenAt !== null ? { handoffTokenAt } : {}) } : {}), updatedAt: ctx.now(),
272
+ });
273
+ saved = true;
274
+ });
275
+ }
276
+ finally {
277
+ // Saved: the state store holds the truth. Not saved (afterCharge
278
+ // swallows a failed save on `complete`): a marker is kept here, and an
279
+ // order known to exist clears it.
280
+ if (saved || !orderPending)
281
+ markers.delete(key);
282
+ else
283
+ markers.set(key, orderPending);
284
+ }
285
+ }
286
+ }
287
+ // A read (or cancel) that carries a newer link than the one remembered. It
288
+ // stands for the cart the read started from: when an update changed the
289
+ // cart (or its link) meanwhile, this answer may be the older revision's. So
290
+ // it is recorded only through the state store's atomic compare-and-set,
291
+ // which writes only while the record still has the cart and link the read
292
+ // started from; a store without one never records a read's link.
293
+ if (issued && !recordSaved && stored && stored.handoffToken !== issued) {
294
+ try {
295
+ if (typeof ctx.state.setHandoffToken === "function") {
296
+ await ctx.state.setHandoffToken(stored.protocol, stored.sessionId, issued, {
297
+ expectedToken: stored.handoffToken ?? null, expectedInputs: stored.inputs, now: ctx.now(),
298
+ });
299
+ }
300
+ else {
301
+ ctx.logger.warn("The checkout state store has no setHandoffToken, so a newer Relyon hand-off link on a read isn't recorded; it lands unattributed", {
302
+ protocol: step.protocol, operation: step.operation,
303
+ });
304
+ }
305
+ }
306
+ catch (error) {
307
+ ctx.logger.error("The checkout state store failed to save a Relyon hand-off link; the agent's answer is relayed", {
308
+ protocol: step.protocol, operation: step.operation, error: describeError(error),
309
+ });
310
+ }
311
+ }
312
+ // Relyon wraps its adapter's answer in a 200, including the adapter's own
313
+ // 5xx. On an allowed `complete` that 5xx may follow a charge (its body can
314
+ // still say nothing was charged), so unless the payment is a final failure
315
+ // the agent gets the unknown-outcome answer instead of that body.
316
+ if (step.operation === "complete" && result.decision === "allowed" && result.status >= 500 && result.payment?.status !== "failed") {
317
+ const paymentStatus = reportedPending(result) ? "pending" : "unknown";
318
+ ctx.logger.error("Relyon's protocol adapter answered an agent's complete with a server error; the payment outcome is unknown", {
319
+ protocol: step.protocol, status: result.status, payment_status: paymentStatus, order_created: orderCreated,
320
+ });
321
+ return { kind: "outcome_unknown", paymentStatus, reason: `adapter:${result.status}` };
322
+ }
323
+ const succeededAnswer = result.status >= 200 && result.status < 300;
324
+ // The payment went through, and the order isn't created: never `completed`.
325
+ if (pendingPayment && succeededAnswer) {
326
+ ctx.logger.error("The store's order isn't created for a succeeded agent payment; the agent is told the order is pending", {
327
+ protocol: step.protocol, payment: pendingPayment.id,
328
+ });
329
+ return { kind: "order_pending", result, sessionId: step.sessionId ?? sessionIdOf(result), paymentId: pendingPayment.id };
330
+ }
331
+ // A read of a checkout that is still order pending shows the same state.
332
+ if (step.operation === "get" && previous?.orderPending && succeededAnswer && reportsCompleted(step.protocol, result)
333
+ && await stillOrderPending(ctx, previous)) {
334
+ if (unsaved && stored && !stored.orderPending)
335
+ await persistUnsaved(ctx, stored, unsaved);
336
+ return { kind: "order_pending", result, sessionId: step.sessionId, paymentId: previous.orderPending.paymentId };
337
+ }
338
+ // A refusal Relyon decided on a checkout the store's own page paid (Relyon's
339
+ // session is still unpaid, so its text may say nothing was charged): the
340
+ // kit answers it, never that text: order pending while the store's order
341
+ // for that payment isn't created, otherwise charge-neutral.
342
+ if (step.sessionId && step.operation !== "create" && (result.decision === "refused" || result.status >= 400)
343
+ && previous && (claimsNothingCharged(result.body ?? "") || previous.orderPending?.handoff === true)
344
+ && await paidOnStore(ctx, previous)) {
345
+ ctx.logger.warn("Relyon refused a step on a checkout paid on the store's own page; answered without its 'nothing was charged'", {
346
+ protocol: step.protocol, operation: step.operation, status: result.status,
347
+ });
348
+ return { kind: "refused", ...relayedRefusal(result) };
349
+ }
350
+ const responseHeaders = new Headers();
351
+ for (const [name, value] of Object.entries(result.headers)) {
352
+ if (!HOP_BY_HOP.has(name.toLowerCase()))
353
+ responseHeaders.set(name, value);
354
+ }
355
+ const bodyless = result.status === 204 || result.status === 304 || result.status < 200;
356
+ // The store's policy pages, in the checkout `links` UCP and ACP already carry.
357
+ // A body Relyon signed or digested is never changed.
358
+ const signed = Object.keys(result.headers).some((name) => /signature|digest/i.test(name));
359
+ const withLinks = !bodyless && !signed && result.status < 300 && result.decision !== "refused" && result.body
360
+ ? withPolicyLinks(step.protocol, result.body, ctx.policies) : null;
361
+ if (withLinks !== null)
362
+ responseHeaders.delete("content-length");
363
+ const response = new Response(bodyless ? null : withLinks ?? result.body, { status: result.status, headers: responseHeaders });
364
+ return { kind: "relayed", response, result, orderCreated };
365
+ }
366
+ /**
367
+ * `processor_not_configured`, `sandbox_test_only` or `live_not_available`:
368
+ * fail closed with Relyon's status and code and the kit's explanation, with
369
+ * no Retry-After. The kit never resends the step or a charge for these.
370
+ */
371
+ function accountNotReady(ctx, step, error) {
372
+ ctx.logger.error("Relyon refused an agent checkout step: the store's account isn't ready for this mode", {
373
+ protocol: step.protocol, operation: step.operation, status: error.status, code: error.code,
374
+ });
375
+ return { kind: "refused", code: error.code, status: error.status, message: error.message };
376
+ }
377
+ /**
378
+ * Classifies a `complete` that got no usable answer from Relyon. Only a
379
+ * Problem the contract defines as refused before any charge, or a request
380
+ * that provably never left the store (connection refused, DNS failure), is
381
+ * answered as a refusal; a timeout, any other network failure, a 5xx, an
382
+ * unreadable answer and every other Problem leave the payment's outcome unknown.
383
+ */
384
+ function completeFailure(ctx, step, error, rawAnswer) {
385
+ // Refused before any charge because the account isn't ready for this mode: final, never resent.
386
+ if (error instanceof RelyonAccountNotReadyError)
387
+ return accountNotReady(ctx, step, error);
388
+ if (error instanceof RelyonProblemError && PRE_CHARGE_PROBLEMS.has(error.code)) {
389
+ switch (error.code) {
390
+ case "protocol_not_available": return { kind: "refused", code: "protocol_not_available" };
391
+ case "cart_changed": return { kind: "refused", code: "cart_changed", status: 409, message: "The cart changed since it was shown. Read the checkout again." };
392
+ case "rate_limited": return { kind: "refused", code: "rate_limited", status: 429, message: "Too many requests. Try again shortly." };
393
+ default: return { kind: "refused", code: "agent_refused" };
394
+ }
395
+ }
396
+ if (error instanceof RelyonUnavailableError && error.kind === "unreachable" && error.notSent) {
397
+ // Connection refused or DNS failure: the request never left the store.
398
+ ctx.logger.warn("Relyon is unreachable before sending; agent complete refused", { protocol: step.protocol });
399
+ return { kind: "refused", code: "service_unavailable" };
400
+ }
401
+ const reason = error instanceof RelyonUnavailableError ? error.kind
402
+ : error instanceof RelyonProblemError ? `problem:${error.status}:${error.code}`
403
+ : "error";
404
+ const paymentStatus = reportedPending(rawAnswer) || (error instanceof RelyonProblemError && reportedPending(error.problem)) ? "pending" : "unknown";
405
+ ctx.logger.error("Relyon gave no usable answer to an agent's complete; the payment outcome is unknown", {
406
+ protocol: step.protocol, reason, payment_status: paymentStatus,
407
+ ...(error instanceof RelyonProblemError ? { status: error.status, code: error.code, message: redactCartTokens(error.message) } : {}),
408
+ ...(!(error instanceof RelyonProblemError) && !(error instanceof RelyonUnavailableError) ? { error: describeError(error, true) } : {}),
409
+ });
410
+ return { kind: "outcome_unknown", paymentStatus, reason };
411
+ }
412
+ /**
413
+ * The order-pending marker of an existing checkout (the payment succeeded
414
+ * and the store's order isn't created yet), or null when there is none or
415
+ * the order exists. Read before the kit answers any refusal of its own on a
416
+ * step that names the checkout, so a charged checkout never hears "nothing
417
+ * was charged". Counts markers the state store refused to save; never
418
+ * throws (a state store failure reads as no marker unless this process holds
419
+ * one, and the caller then answers charge-neutrally).
420
+ */
421
+ export async function orderPendingFor(ctx, protocol, sessionId) {
422
+ const unsaved = unsavedMarkers(ctx.state).get(markerKey(protocol, sessionId)) ?? null;
423
+ let stored = null;
424
+ try {
425
+ stored = await ctx.state.get(protocol, sessionId);
426
+ }
427
+ catch (error) {
428
+ ctx.logger.error("The checkout state store failed to load a checkout before a refusal", {
429
+ protocol, error: describeError(error),
430
+ });
431
+ }
432
+ const marker = stored?.orderPending ?? unsaved;
433
+ if (!marker)
434
+ return null;
435
+ if (!stored) {
436
+ // Nothing to clear in the state store: only the claim says whether the order exists.
437
+ if (typeof ctx.state.orderClaimStatus !== "function")
438
+ return marker;
439
+ try {
440
+ if (await ctx.state.orderClaimStatus(marker.paymentId, ctx.now()) !== "created")
441
+ return marker;
442
+ }
443
+ catch {
444
+ return marker;
445
+ }
446
+ unsavedMarkers(ctx.state).delete(markerKey(protocol, sessionId));
447
+ return null;
448
+ }
449
+ return await stillOrderPending(ctx, { ...stored, orderPending: marker }) ? marker : null;
450
+ }
451
+ /**
452
+ * Marks (or clears) the agent checkout a store-page payment paid (a hand-off
453
+ * cart) as order pending, so the agent's own steps on it answer order
454
+ * pending while the store's order isn't created. Clears only the marker of
455
+ * this payment. Never throws: a failed save keeps the marker in this process.
456
+ */
457
+ export async function markHandoffOrderPending(ctx, agentCheckoutId, paymentId, pending) {
458
+ let record;
459
+ try {
460
+ record = await ctx.state.byAgentCheckoutId(agentCheckoutId);
461
+ }
462
+ catch (error) {
463
+ ctx.logger.error("The checkout state store failed to load a hand-off checkout", { error: describeError(error) });
464
+ return;
465
+ }
466
+ if (!record)
467
+ return;
468
+ const markers = unsavedMarkers(ctx.state);
469
+ const key = markerKey(record.protocol, record.sessionId);
470
+ if (pending) {
471
+ const marker = { paymentId, since: record.orderPending?.paymentId === paymentId ? record.orderPending.since : ctx.now(), handoff: true };
472
+ try {
473
+ await ctx.state.put({ ...record, orderPending: marker, updatedAt: ctx.now() });
474
+ markers.delete(key);
475
+ }
476
+ catch (error) {
477
+ markers.set(key, marker);
478
+ ctx.logger.error("The checkout state store failed to mark a hand-off checkout order pending; this server keeps it", {
479
+ payment: paymentId, error: describeError(error),
480
+ });
481
+ }
482
+ return;
483
+ }
484
+ if (markers.get(key)?.paymentId === paymentId)
485
+ markers.delete(key);
486
+ if (record.orderPending?.paymentId !== paymentId)
487
+ return;
488
+ try {
489
+ await ctx.state.put({ ...record, orderPending: null, updatedAt: ctx.now() });
490
+ }
491
+ catch (error) {
492
+ // The claim says the order exists; the next read clears it.
493
+ ctx.logger.error("The checkout state store failed to clear a hand-off checkout's order-pending mark", {
494
+ payment: paymentId, error: describeError(error),
495
+ });
496
+ }
497
+ }
498
+ /** Retries saving a marker the state store refused earlier; kept in this process until it succeeds. */
499
+ async function persistUnsaved(ctx, stored, marker) {
500
+ try {
501
+ await ctx.state.put({ ...stored, orderPending: marker, updatedAt: ctx.now() });
502
+ unsavedMarkers(ctx.state).delete(markerKey(stored.protocol, stored.sessionId));
503
+ }
504
+ catch (error) {
505
+ ctx.logger.error("The checkout state store still refuses to save an order-pending checkout; this server keeps it", {
506
+ payment: marker.paymentId, error: describeError(error),
507
+ });
508
+ }
509
+ }
510
+ /** True when Relyon's answer to a read shows the checkout as completed (UCP/ACP `status`, MCP `structuredContent.status`). */
511
+ function reportsCompleted(protocol, result) {
512
+ const body = tryParseJson(result.body);
513
+ if (!isRecord(body))
514
+ return false;
515
+ if (protocol !== "mcp")
516
+ return body.status === "completed";
517
+ const structured = isRecord(body.result) && isRecord(body.result.structuredContent) ? body.result.structuredContent : null;
518
+ return structured?.status === "completed";
519
+ }
520
+ /**
521
+ * Whether an order-pending checkout is still waiting on its order. When the
522
+ * order claim is marked created (another request, maybe on another server,
523
+ * created the order) the marker is cleared and the read shows Relyon's answer.
524
+ * A store that can't report claim status keeps the marker until a resent
525
+ * complete creates the order.
526
+ */
527
+ async function stillOrderPending(ctx, record) {
528
+ const marker = record.orderPending;
529
+ if (!marker)
530
+ return false;
531
+ if (typeof ctx.state.orderClaimStatus !== "function")
532
+ return true;
533
+ let status;
534
+ try {
535
+ status = await ctx.state.orderClaimStatus(marker.paymentId, ctx.now());
536
+ }
537
+ catch (error) {
538
+ ctx.logger.error("The checkout state store failed to report an order claim; the checkout stays order pending", {
539
+ payment: marker.paymentId, error: describeError(error),
540
+ });
541
+ return true;
542
+ }
543
+ if (status !== "created")
544
+ return true;
545
+ unsavedMarkers(ctx.state).delete(markerKey(record.protocol, record.sessionId));
546
+ try {
547
+ await ctx.state.put({ ...record, orderPending: null, updatedAt: ctx.now() });
548
+ }
549
+ catch (error) {
550
+ // The order exists either way; the next read checks the claim again.
551
+ ctx.logger.error("The checkout state store failed to clear an order-pending checkout", {
552
+ payment: marker.paymentId, error: describeError(error),
553
+ });
554
+ }
555
+ return false;
556
+ }
557
+ /** True when an answer the kit can't otherwise use says its payment is pending or processing. */
558
+ function reportedPending(data) {
559
+ const payment = isRecord(data) ? data.payment : undefined;
560
+ return isRecord(payment) && (payment.status === "pending" || payment.status === "processing");
561
+ }
562
+ function sessionIdOf(result) {
563
+ const body = tryParseJson(result.body);
564
+ if (isRecord(body) && typeof body.id === "string")
565
+ return body.id;
566
+ if (isRecord(body) && isRecord(body.result)) {
567
+ const structured = isRecord(body.result.structuredContent) ? body.result.structuredContent : undefined;
568
+ if (structured && typeof structured.checkout_id === "string")
569
+ return structured.checkout_id;
570
+ }
571
+ return result.agentCheckoutId;
572
+ }
573
+ /** Reads an AgentCheckoutResult; null (treated as malformed) when it doesn't have what the kit relies on. */
574
+ export function readResult(data) {
575
+ if (!isRecord(data))
576
+ return null;
577
+ if (data.object !== "agent_checkout_result" && data.object !== "agent_checkout_step")
578
+ return null;
579
+ const decision = data.decision === "allowed" || data.decision === "accepted" ? "allowed" : data.decision === "refused" ? "refused" : null;
580
+ if (!decision)
581
+ return null;
582
+ const status = data.status;
583
+ if (typeof status !== "number" || !Number.isInteger(status) || status < 100 || status > 599)
584
+ return null;
585
+ if (!isRecord(data.headers) || !Object.values(data.headers).every((value) => typeof value === "string"))
586
+ return null;
587
+ if (typeof data.body !== "string")
588
+ return null;
589
+ const raw = data.payment ?? null;
590
+ if (raw !== null && !(isRecord(raw) && typeof raw.status === "string"))
591
+ return null;
592
+ const agentCheckoutId = typeof data.agent_checkout_id === "string" ? data.agent_checkout_id
593
+ : typeof data.checkout_session_id === "string" ? data.checkout_session_id : null;
594
+ let payment = null;
595
+ if (isRecord(raw)) {
596
+ // The contract's Payment has an id; today's server sends none on an agent
597
+ // checkout's payment. The order id (or the checkout id) stands in for it so
598
+ // createOrder still runs once per payment.
599
+ const id = typeof raw.id === "string" ? raw.id
600
+ : typeof raw.order_id === "string" ? raw.order_id
601
+ : agentCheckoutId ? `checkout:${agentCheckoutId}` : null;
602
+ if (!id)
603
+ return null;
604
+ payment = { ...raw, id, status: raw.status };
605
+ }
606
+ let locked = null;
607
+ if (isRecord(data.cart)) {
608
+ locked = {};
609
+ for (const field of ["merchant_reference", "expires_at"])
610
+ if (data.cart[field] !== undefined)
611
+ locked[field] = data.cart[field];
612
+ if (Object.keys(locked).length === 0)
613
+ locked = null;
614
+ }
615
+ return {
616
+ decision,
617
+ reason: typeof data.reason === "string" ? data.reason : null,
618
+ agentCheckoutId,
619
+ status,
620
+ headers: data.headers,
621
+ body: data.body,
622
+ payment,
623
+ locked,
624
+ };
625
+ }
626
+ /** The code of the kit's answer to an agent's `complete` on a checkout paid on the store's own page. */
627
+ export const PAID_ON_STORE = "checkout_paid_on_store";
628
+ export const PAID_ON_STORE_MESSAGE = "This checkout was paid on the store's checkout page; this request charged nothing more."
629
+ + " Read this checkout for its status; don't pay again or start a new checkout.";
630
+ /**
631
+ * True when a payment on the store's own checkout page (`payAndConfirm` with
632
+ * this agent checkout) paid this checkout or may have: a hand-off order-pending
633
+ * marker, or the store-payment memory for the agent checkout (charging, order
634
+ * pending or order created). Never throws.
635
+ */
636
+ async function paidOnStore(ctx, record) {
637
+ if (record.orderPending?.handoff)
638
+ return true;
639
+ if (!record.agentCheckoutId)
640
+ return false;
641
+ const paid = await storePaymentRecord(ctx, handoffPaymentKey(record.agentCheckoutId));
642
+ return paid !== null && paid.state !== "declined";
643
+ }
644
+ /** The code and message of a refusal Relyon decided, in any protocol's format; the message is sanitized by the caller. */
645
+ function relayedRefusal(result) {
646
+ const body = tryParseJson(result.body ?? "");
647
+ const error = isRecord(body) && isRecord(body.error) ? body.error : null;
648
+ const data = error && isRecord(error.data) ? error.data : null;
649
+ const code = isRecord(body) && typeof body.code === "string" ? body.code
650
+ : data && typeof data.error === "string" ? data.error : "agent_refused";
651
+ const message = isRecord(body) && typeof body.content === "string" ? body.content
652
+ : isRecord(body) && typeof body.message === "string" ? body.message
653
+ : error && typeof error.message === "string" ? error.message : undefined;
654
+ return { code, status: result.status >= 400 ? result.status : 403, ...(message !== undefined ? { message } : {}) };
655
+ }
@@ -0,0 +1,2 @@
1
+ import type { KitReleaseNote } from "./kit-updates.js";
2
+ export declare const KIT_RELEASE_NOTES: readonly KitReleaseNote[];