@fire-spark/ai 0.0.0-stage → 0.36.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.
package/dist/index.js ADDED
@@ -0,0 +1,3813 @@
1
+ import { createRemoteJWKSet, jwtVerify } from "jose";
2
+ import { z } from "zod";
3
+ import { Big } from "big.js";
4
+ import { acceptedContent, inputRequired } from "@modelcontextprotocol/server";
5
+ import { OrderValidationError, StorefrontHttpError, auth, createSession, genOrderId, indexMenu, services, toOrderLines } from "@fire-spark/core";
6
+ import { createMcpHandler, getPublicOrigin, metadataCorsOptionsRequestHandler, protectedResourceHandler, withMcpAuth } from "mcp-handler";
7
+ import { randomUUID } from "node:crypto";
8
+ import { RESOURCE_MIME_TYPE, registerAppResource } from "@modelcontextprotocol/ext-apps/server";
9
+ //#region src/auth.ts
10
+ const jwksByUrl = /* @__PURE__ */ new Map();
11
+ const jwksFor = (jwksUrl) => {
12
+ const cached = jwksByUrl.get(jwksUrl);
13
+ if (cached) return cached;
14
+ const next = createRemoteJWKSet(new URL(jwksUrl));
15
+ jwksByUrl.set(jwksUrl, next);
16
+ return next;
17
+ };
18
+ const audiencesOf = (aud) => {
19
+ if (typeof aud === "string" && aud.length > 0) return [aud];
20
+ if (!Array.isArray(aud)) return [];
21
+ return aud.filter((item) => typeof item === "string");
22
+ };
23
+ const scopesOf = (payload) => {
24
+ if (typeof payload.scope === "string") return payload.scope.split(/\s+/).filter(Boolean);
25
+ const scp = payload.scp;
26
+ if (!Array.isArray(scp)) return [];
27
+ return scp.filter((item) => typeof item === "string");
28
+ };
29
+ /**
30
+ * Resource-server check. FireSpark does not issue the token.
31
+ * `aud` is exactly this merchant's MCP URL, `sub` is the customer,
32
+ * and `iss` is that merchant's authorization server.
33
+ */
34
+ const verifyAgentAccessToken = async (input) => {
35
+ let payload;
36
+ try {
37
+ const options = {
38
+ issuer: input.issuer,
39
+ audience: input.audience
40
+ };
41
+ const key = input.key;
42
+ payload = (await jwtVerify(input.token, key, options)).payload;
43
+ } catch {
44
+ return null;
45
+ }
46
+ if (payload.iss !== input.issuer) return null;
47
+ const audiences = audiencesOf(payload.aud);
48
+ if (audiences.length !== 1 || audiences[0] !== input.audience) return null;
49
+ if (typeof payload.sub !== "string" || !payload.sub) return null;
50
+ if (payload.customer_id !== payload.sub) return null;
51
+ if (typeof payload.exp !== "number") return null;
52
+ const merchantClaim = payload.merchant_id;
53
+ if (typeof merchantClaim === "string" && merchantClaim !== input.merchantId) return null;
54
+ const clientClaim = payload.client_id;
55
+ let clientId = "agent-client";
56
+ if (typeof clientClaim === "string" && clientClaim) clientId = clientClaim;
57
+ const scopes = scopesOf(payload);
58
+ const b1 = {
59
+ token: input.token,
60
+ customerId: payload.sub,
61
+ clientId
62
+ };
63
+ const b2 = {
64
+ scopes,
65
+ expiresAt: payload.exp
66
+ };
67
+ return {
68
+ ...b1,
69
+ ...b2
70
+ };
71
+ };
72
+ //#endregion
73
+ //#region src/channel.ts
74
+ const readJson$1 = async (response) => {
75
+ try {
76
+ return await response.json();
77
+ } catch {
78
+ return null;
79
+ }
80
+ };
81
+ /** Integrations token route returns `{ data: { access_token } }`. */
82
+ const tokenOf = (value) => {
83
+ if (!value || typeof value !== "object") return "";
84
+ const data = value.data;
85
+ if (!data || typeof data !== "object") return "";
86
+ const token = data.access_token;
87
+ return typeof token === "string" ? token : "";
88
+ };
89
+ const isRow = (value) => {
90
+ if (!value || typeof value !== "object") return false;
91
+ const row = value;
92
+ return typeof row.id === "string" && typeof row.merchant_id === "string";
93
+ };
94
+ /**
95
+ * Every request: the merchant's integration client must list an ACTIVE
96
+ * AGENT channel whose merchant_id is the route merchant.
97
+ */
98
+ const resolveAgentChannel = async (input) => {
99
+ const fetchImpl = input.fetchImpl ?? fetch;
100
+ const { merchant, apiUrl } = input;
101
+ const tokenUrl = `${apiUrl}/api/integrations/v1/oauth/token`;
102
+ const b1 = {
103
+ grant_type: "client_credentials",
104
+ client_id: merchant.clientId
105
+ };
106
+ const b2 = {
107
+ client_secret: merchant.clientSecret,
108
+ scope: "channels:read"
109
+ };
110
+ const tokenBody = {
111
+ ...b1,
112
+ ...b2
113
+ };
114
+ const init = {
115
+ method: "POST",
116
+ headers: { "Content-Type": "application/json" },
117
+ body: JSON.stringify(tokenBody)
118
+ };
119
+ let tokenResponse;
120
+ try {
121
+ tokenResponse = await fetchImpl(tokenUrl, init);
122
+ } catch {
123
+ return {
124
+ ok: false,
125
+ reason: "upstream"
126
+ };
127
+ }
128
+ if (!tokenResponse.ok) return {
129
+ ok: false,
130
+ reason: "upstream"
131
+ };
132
+ const tokenJson = await readJson$1(tokenResponse);
133
+ const accessToken = tokenOf(tokenJson);
134
+ if (typeof accessToken !== "string" || !accessToken) return {
135
+ ok: false,
136
+ reason: "upstream"
137
+ };
138
+ const listUrl = `${apiUrl}/api/integrations/v1/channels`;
139
+ const listInit = { headers: { Authorization: `Bearer ${accessToken}` } };
140
+ let listResponse;
141
+ try {
142
+ listResponse = await fetchImpl(listUrl, listInit);
143
+ } catch {
144
+ return {
145
+ ok: false,
146
+ reason: "upstream"
147
+ };
148
+ }
149
+ if (!listResponse.ok) return {
150
+ ok: false,
151
+ reason: "upstream"
152
+ };
153
+ const listJson = await readJson$1(listResponse);
154
+ if (!listJson || typeof listJson !== "object") return {
155
+ ok: false,
156
+ reason: "upstream"
157
+ };
158
+ const data = listJson.data;
159
+ if (!Array.isArray(data)) return {
160
+ ok: false,
161
+ reason: "upstream"
162
+ };
163
+ const rows = data.filter(isRow);
164
+ if (rows.some((row) => row.merchant_id !== merchant.merchantId)) return {
165
+ ok: false,
166
+ reason: "missing"
167
+ };
168
+ const agent = rows.find((row) => {
169
+ return row.type === "AGENT" && row.status === "ACTIVE";
170
+ });
171
+ if (!agent) return {
172
+ ok: false,
173
+ reason: "missing"
174
+ };
175
+ return {
176
+ ok: true,
177
+ channel: {
178
+ merchantId: merchant.merchantId,
179
+ channelId: agent.id
180
+ }
181
+ };
182
+ };
183
+ //#endregion
184
+ //#region src/idempotency.ts
185
+ /** Client key persisted on the order. The cart handle stays `order_id`. */
186
+ const idempotencyKeySchema = z.string().trim().min(8).max(200);
187
+ //#endregion
188
+ //#region src/money.ts
189
+ /** Decimal money text. No exponent and no leading zeros, so nothing is rounded. */
190
+ const DECIMAL = /^(?:0|[1-9]\d*)(?:\.\d+)?$/;
191
+ const isDecimalString = (value) => {
192
+ if (!DECIMAL.test(value)) return false;
193
+ try {
194
+ return new Big(value).gte(0);
195
+ } catch {
196
+ return false;
197
+ }
198
+ };
199
+ /**
200
+ * `part / whole` only when the quotient is an exact JSON number.
201
+ * Otherwise the caller must send the rate.
202
+ */
203
+ const exactRate = (part, whole) => {
204
+ const base = new Big(whole);
205
+ if (base.eq(0)) return 0;
206
+ const value = new Big(part).div(base);
207
+ const asNumber = Number(value.toString());
208
+ if (!Number.isFinite(asNumber)) return null;
209
+ if (!new Big(asNumber).eq(value)) return null;
210
+ return asNumber;
211
+ };
212
+ /** Exact decimal sum. `0.1 + 0.2` stays `0.3`. */
213
+ const sumDecimals = (values) => {
214
+ let total = new Big(0);
215
+ for (const value of values) total = total.plus(value);
216
+ return total.toString();
217
+ };
218
+ /** True when two decimal strings are the same amount. `10.50` equals `10.5`. */
219
+ const decimalsEqual = (left, right) => {
220
+ return new Big(left).eq(right);
221
+ };
222
+ /**
223
+ * JSON number for the storefront API. The API schema requires a number;
224
+ * this does not pin a currency scale (`10.125` stays `10.125`).
225
+ */
226
+ const decimalToNumber = (value) => {
227
+ const amount = new Big(value);
228
+ const asNumber = Number(amount.toString());
229
+ if (!Number.isFinite(asNumber)) throw new Error("Amount is out of range");
230
+ return asNumber;
231
+ };
232
+ /** Number that arrived from JSON, rendered without a fixed scale. */
233
+ const numberToDecimal = (value) => {
234
+ if (!Number.isFinite(value)) throw new Error("Amount is out of range");
235
+ return new Big(Object.is(value, -0) ? "0" : String(value)).toString();
236
+ };
237
+ const MONEY_KEYS = /* @__PURE__ */ new Set([
238
+ "amount",
239
+ "anchor_price",
240
+ "discount_total",
241
+ "group_discount",
242
+ "group_subtotal",
243
+ "group_tax_total",
244
+ "group_total",
245
+ "price",
246
+ "refund_price",
247
+ "subtotal",
248
+ "tax_total",
249
+ "total",
250
+ "unit_discount",
251
+ "unit_group_discount",
252
+ "unit_group_subtotal",
253
+ "unit_group_tax_total",
254
+ "unit_group_total",
255
+ "unit_subtotal",
256
+ "unit_tax_total",
257
+ "unit_total"
258
+ ]);
259
+ const SECRET_KEYS = /* @__PURE__ */ new Set([
260
+ "access_token",
261
+ "agent_pay_url",
262
+ "card_number",
263
+ "card_token",
264
+ "cvv",
265
+ "cvc",
266
+ "gateway_token",
267
+ "pan",
268
+ "payment_token",
269
+ "storefront_token"
270
+ ]);
271
+ /** Tool payloads: money as decimal strings, card data removed. */
272
+ const presentMoney = (value) => {
273
+ if (Array.isArray(value)) return value.map(presentMoney);
274
+ if (!value || typeof value !== "object") return value;
275
+ const output = {};
276
+ for (const [key, item] of Object.entries(value)) {
277
+ if (SECRET_KEYS.has(key.toLowerCase())) continue;
278
+ if (MONEY_KEYS.has(key) && typeof item === "number") {
279
+ output[key] = numberToDecimal(item);
280
+ continue;
281
+ }
282
+ output[key] = presentMoney(item);
283
+ }
284
+ return output;
285
+ };
286
+ //#endregion
287
+ //#region src/mrtr.ts
288
+ const textEncoder$1 = new TextEncoder();
289
+ const bytesToBase64Url$1 = (bytes) => {
290
+ let binary = "";
291
+ for (const byte of bytes) binary += String.fromCharCode(byte);
292
+ return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
293
+ };
294
+ const base64UrlToBytes$1 = (value) => {
295
+ const padded = value.replaceAll("-", "+").replaceAll("_", "/");
296
+ const rest = padded.length % 4;
297
+ const pad = rest === 0 ? "" : "=".repeat(4 - rest);
298
+ const binary = atob(padded + pad);
299
+ const bytes = new Uint8Array(binary.length);
300
+ for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
301
+ return bytes;
302
+ };
303
+ const hmac = async (secret, body) => {
304
+ const p1 = [
305
+ "raw",
306
+ textEncoder$1.encode(secret),
307
+ {
308
+ name: "HMAC",
309
+ hash: "SHA-256"
310
+ },
311
+ false,
312
+ ["sign"]
313
+ ];
314
+ const p2 = [
315
+ "HMAC",
316
+ await crypto.subtle.importKey(...p1),
317
+ textEncoder$1.encode(body)
318
+ ];
319
+ const signed = await crypto.subtle.sign(...p2);
320
+ return new Uint8Array(signed);
321
+ };
322
+ /**
323
+ * Opaque MRTR `requestState`. The client must echo it unchanged.
324
+ * The seal is HMAC-SHA256 so a later phase can trust the total it confirmed.
325
+ */
326
+ const sealRequestState = async (payload, secret) => {
327
+ if (!secret) throw new Error("requestState secret is empty");
328
+ const body = JSON.stringify(payload);
329
+ const signature = await hmac(secret, body);
330
+ return `${bytesToBase64Url$1(textEncoder$1.encode(body))}.${bytesToBase64Url$1(signature)}`;
331
+ };
332
+ const openRequestState = async (state, secret) => {
333
+ const parts = state.split(".");
334
+ if (parts.length !== 2 || !parts[0] || !parts[1]) return null;
335
+ let body = "";
336
+ try {
337
+ body = new TextDecoder().decode(base64UrlToBytes$1(parts[0]));
338
+ } catch {
339
+ return null;
340
+ }
341
+ const expected = await hmac(secret, body);
342
+ let actual;
343
+ try {
344
+ actual = base64UrlToBytes$1(parts[1]);
345
+ } catch {
346
+ return null;
347
+ }
348
+ if (expected.length !== actual.length) return null;
349
+ let mismatch = 0;
350
+ for (let index = 0; index < expected.length; index += 1) mismatch |= (expected[index] ?? 0) ^ (actual[index] ?? 0);
351
+ if (mismatch !== 0) return null;
352
+ const parsed = JSON.parse(body);
353
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
354
+ const output = {};
355
+ for (const [key, value] of Object.entries(parsed)) {
356
+ if (typeof value !== "string") return null;
357
+ output[key] = value;
358
+ }
359
+ return output;
360
+ };
361
+ const confirmSchema = z.object({
362
+ confirmed: z.boolean(),
363
+ confirmed_total: z.string()
364
+ });
365
+ /**
366
+ * Asks the customer to confirm a total before anything is sent to pay.
367
+ * `requestState` is the sealed order total the retry must echo.
368
+ */
369
+ const confirmTotalRequest = (total, currency, requestState) => {
370
+ const fields = {
371
+ message: `Confirma el total de ${total} ${currency} antes de seguir.`,
372
+ requestedSchema: confirmSchema
373
+ };
374
+ const base = { inputRequests: { confirm_total: inputRequired.elicit(fields) } };
375
+ if (!requestState) return inputRequired(base);
376
+ return inputRequired({
377
+ ...base,
378
+ requestState
379
+ });
380
+ };
381
+ const confirmedTotal = (responses) => {
382
+ return acceptedContent(responses, "confirm_total")?.confirmed === true;
383
+ };
384
+ const consentSchema = z.object({ consent: z.boolean() });
385
+ /** Asks to charge one saved card. The seal binds the card and the total. */
386
+ const confirmSavedCardRequest = (input) => {
387
+ const fields = {
388
+ message: `Confirma el cobro de ${input.total} ${input.currency} con la tarjeta ${input.brand} ${input.last4}.`,
389
+ requestedSchema: confirmSchema
390
+ };
391
+ const base = { inputRequests: { confirm_total: inputRequired.elicit(fields) } };
392
+ if (!input.requestState) return inputRequired(base);
393
+ return inputRequired({
394
+ ...base,
395
+ requestState: input.requestState
396
+ });
397
+ };
398
+ /** Asks before a card is stored at the merchant gateway. */
399
+ const confirmCardConsentRequest = (requestState) => {
400
+ const fields = {
401
+ message: "¿Autorizas guardar una tarjeta en la pasarela de este comercio? Aquí no guardamos el número.",
402
+ requestedSchema: consentSchema
403
+ };
404
+ const base = { inputRequests: { save_card: inputRequired.elicit(fields) } };
405
+ if (!requestState) return inputRequired(base);
406
+ return inputRequired({
407
+ ...base,
408
+ requestState
409
+ });
410
+ };
411
+ const cardConsentAccepted = (responses) => {
412
+ return acceptedContent(responses, "save_card")?.consent === true;
413
+ };
414
+ /** Decimal the customer accepted. Null when they declined or it is not money. */
415
+ const confirmedAmount = (responses) => {
416
+ const content = acceptedContent(responses, "confirm_total");
417
+ if (!content || content.confirmed !== true) return null;
418
+ const raw = content.confirmed_total;
419
+ if (typeof raw !== "string" || !isDecimalString(raw)) return null;
420
+ return raw;
421
+ };
422
+ //#endregion
423
+ //#region src/scopes.ts
424
+ /** Per-tool scopes. Later phases add write tools here. */
425
+ const TOOL_SCOPES = {
426
+ list_stores: "agent:stores:read",
427
+ get_menu: "agent:menus:read",
428
+ get_menu_category: "agent:menus:read",
429
+ search_menu: "agent:menus:read",
430
+ get_product: "agent:menus:read",
431
+ build_cart: "agent:carts:write",
432
+ validate_cart: "agent:carts:validate",
433
+ create_order: "agent:orders:write",
434
+ start_payment: "agent:payments:start",
435
+ get_order_status: "agent:orders:read",
436
+ list_saved_cards: "agent:cards:read",
437
+ charge_saved_card: "agent:cards:charge",
438
+ save_card_consent: "agent:cards:consent",
439
+ revoke_saved_card: "agent:cards:revoke"
440
+ };
441
+ const requireToolScope = (scope) => {
442
+ return ({ authInfo }) => {
443
+ if (!authInfo) return void 0;
444
+ if (authInfo.scopes.includes(scope)) return void 0;
445
+ return {
446
+ scopes: [scope],
447
+ errorDescription: "No tienes permiso para usar esta herramienta."
448
+ };
449
+ };
450
+ };
451
+ //#endregion
452
+ //#region src/ui.ts
453
+ /** MCP App resources. HTML is served with `text/html;profile=mcp-app`. */
454
+ const UI_MENU = "ui://firespark/menu";
455
+ const UI_PRODUCT = "ui://firespark/product";
456
+ const UI_CART = "ui://firespark/cart";
457
+ const uiMeta = (resourceUri, visibility) => {
458
+ return { ui: {
459
+ resourceUri,
460
+ visibility
461
+ } };
462
+ };
463
+ const ORIGIN = /^https:\/\/(\*\.)?[a-z0-9.-]+(?::\d+)?$/i;
464
+ /** https origin, or a single-label wildcard such as `https://*.cdn.com`. */
465
+ const isImageOrigin = (value) => {
466
+ return ORIGIN.test(value);
467
+ };
468
+ //#endregion
469
+ //#region src/runtime.ts
470
+ const storefrontAccessToken = async (runtime, input) => {
471
+ if (runtime.storefrontToken) return runtime.storefrontToken(input);
472
+ try {
473
+ const b1 = {
474
+ baseUrl: runtime.apiUrl,
475
+ fetchImpl: runtime.fetchImpl
476
+ };
477
+ return (await auth.exchangeSubjectToken(input.subjectToken, b1)).access_token;
478
+ } catch {
479
+ throw new Error("storefront_exchange_failed");
480
+ }
481
+ };
482
+ const verificationKey = async (runtime, merchant) => {
483
+ if (runtime.verifyKey) return runtime.verifyKey(merchant);
484
+ return jwksFor(merchant.jwksUrl);
485
+ };
486
+ //#endregion
487
+ //#region src/payments/link.ts
488
+ const textEncoder = new TextEncoder();
489
+ const bytesToBase64Url = (bytes) => {
490
+ let binary = "";
491
+ for (const byte of bytes) binary += String.fromCharCode(byte);
492
+ return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
493
+ };
494
+ const base64UrlToBytes = (value) => {
495
+ const padded = value.replaceAll("-", "+").replaceAll("_", "/");
496
+ const rest = padded.length % 4;
497
+ const pad = rest === 0 ? "" : "=".repeat(4 - rest);
498
+ const binary = atob(padded + pad);
499
+ const bytes = new Uint8Array(binary.length);
500
+ for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
501
+ return bytes;
502
+ };
503
+ const PAYMENT_LINK_TTL_MS = 900 * 1e3;
504
+ const sha256 = async (secret) => {
505
+ const data = textEncoder.encode(secret);
506
+ const digest = await crypto.subtle.digest("SHA-256", data);
507
+ return new Uint8Array(digest);
508
+ };
509
+ const aesKey = async (secret) => {
510
+ const p1 = [
511
+ "raw",
512
+ await sha256(secret),
513
+ { name: "AES-GCM" },
514
+ false,
515
+ ["encrypt", "decrypt"]
516
+ ];
517
+ return crypto.subtle.importKey(...p1);
518
+ };
519
+ const PURPOSES = /* @__PURE__ */ new Set([
520
+ "pay",
521
+ "continue",
522
+ "return",
523
+ "gateway"
524
+ ]);
525
+ const text$1 = (value) => {
526
+ return typeof value === "string" && value.length > 0 ? value : "";
527
+ };
528
+ const claimsOf = (value) => {
529
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
530
+ const row = value;
531
+ const purpose = row.purpose;
532
+ if (typeof purpose !== "string" || !PURPOSES.has(purpose)) return null;
533
+ const exp = row.exp;
534
+ if (typeof exp !== "number" || !Number.isFinite(exp)) return null;
535
+ let mode;
536
+ if (row.mode === "test" || row.mode === "hosted") mode = row.mode;
537
+ else if (row.mode !== void 0) return null;
538
+ let saveCard;
539
+ if (row.saveCard === true) saveCard = true;
540
+ else if (row.saveCard !== void 0 && row.saveCard !== false) return null;
541
+ const required = {
542
+ merchantId: text$1(row.merchantId),
543
+ channelId: text$1(row.channelId),
544
+ customerId: text$1(row.customerId),
545
+ orderId: text$1(row.orderId),
546
+ returnUrl: text$1(row.returnUrl),
547
+ jti: text$1(row.jti),
548
+ storefrontToken: text$1(row.storefrontToken)
549
+ };
550
+ if (Object.values(required).some((item) => item.length === 0)) return null;
551
+ const optional = {
552
+ paymentId: text$1(row.paymentId) || void 0,
553
+ tenderId: text$1(row.tenderId) || void 0,
554
+ attemptReference: text$1(row.attemptReference) || void 0,
555
+ mode,
556
+ saveCard
557
+ };
558
+ return {
559
+ ...required,
560
+ purpose,
561
+ exp,
562
+ ...optional
563
+ };
564
+ };
565
+ const mintAgentLink = async (claims, secret) => {
566
+ if (!secret) throw new Error("payment link secret is empty");
567
+ const iv = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(12));
568
+ const key = await aesKey(secret);
569
+ const data = textEncoder.encode(JSON.stringify(claims));
570
+ const p1 = [
571
+ {
572
+ name: "AES-GCM",
573
+ iv
574
+ },
575
+ key,
576
+ data
577
+ ];
578
+ const encrypted = await crypto.subtle.encrypt(...p1);
579
+ return `${bytesToBase64Url(iv)}.${bytesToBase64Url(new Uint8Array(encrypted))}`;
580
+ };
581
+ const openAgentLink = async (token, secret, now = Date.now()) => {
582
+ const parts = token.split(".");
583
+ if (parts.length !== 2 || !parts[0] || !parts[1] || !secret) return {
584
+ ok: false,
585
+ reason: "invalid"
586
+ };
587
+ let plain = "";
588
+ try {
589
+ const iv = base64UrlToBytes(parts[0]);
590
+ const data = base64UrlToBytes(parts[1]);
591
+ const key = await aesKey(secret);
592
+ const p1 = [
593
+ {
594
+ name: "AES-GCM",
595
+ iv
596
+ },
597
+ key,
598
+ data
599
+ ];
600
+ const decoded = await crypto.subtle.decrypt(...p1);
601
+ plain = new TextDecoder().decode(decoded);
602
+ } catch {
603
+ return {
604
+ ok: false,
605
+ reason: "invalid"
606
+ };
607
+ }
608
+ let parsed;
609
+ try {
610
+ parsed = JSON.parse(plain);
611
+ } catch {
612
+ return {
613
+ ok: false,
614
+ reason: "invalid"
615
+ };
616
+ }
617
+ const claims = claimsOf(parsed);
618
+ if (!claims) return {
619
+ ok: false,
620
+ reason: "invalid"
621
+ };
622
+ if (claims.exp <= now) return {
623
+ ok: false,
624
+ reason: "expired"
625
+ };
626
+ return {
627
+ ok: true,
628
+ claims
629
+ };
630
+ };
631
+ const newLinkId = () => {
632
+ const bytes = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16));
633
+ return bytesToBase64Url(bytes);
634
+ };
635
+ //#endregion
636
+ //#region src/payments/order.ts
637
+ const PAY_USED$1 = "agent_pay_used";
638
+ const PAY_STARTED = "agent_pay_started";
639
+ const metaOf$3 = (order) => {
640
+ const meta = order.metadata;
641
+ if (!meta || typeof meta !== "object" || Array.isArray(meta)) return {};
642
+ return { ...meta };
643
+ };
644
+ const storefrontHttp = (apiUrl, token, fetchImpl) => {
645
+ return {
646
+ baseUrl: apiUrl,
647
+ accessToken: token,
648
+ fetchImpl
649
+ };
650
+ };
651
+ const patchOrderMeta = async (order, extra, http) => {
652
+ const metadata = {
653
+ ...metaOf$3(order),
654
+ ...extra
655
+ };
656
+ return await services.orders.patch(order.id, { metadata }, http) ?? order;
657
+ };
658
+ const tenderOnOrder = (order, paymentId, attemptReference) => {
659
+ const intents = order.payment_intents;
660
+ if (!Array.isArray(intents)) return null;
661
+ for (const intent of intents) {
662
+ const row = intent;
663
+ if (!Array.isArray(row.tenders)) continue;
664
+ for (const tender of row.tenders) {
665
+ const item = tender;
666
+ const sameAttempt = item.attempt_reference === attemptReference;
667
+ const samePayment = item.payment_id === paymentId;
668
+ if (!sameAttempt && !samePayment) continue;
669
+ if (typeof item.id !== "string" || !item.id) continue;
670
+ const attempt = item.attempt_reference;
671
+ const reference = typeof attempt === "string" ? attempt : attemptReference;
672
+ return {
673
+ id: item.id,
674
+ attemptReference: reference
675
+ };
676
+ }
677
+ }
678
+ return null;
679
+ };
680
+ //#endregion
681
+ //#region src/tools/cart.selection.ts
682
+ const MONEY = [
683
+ "unit_subtotal",
684
+ "unit_discount",
685
+ "unit_tax_total",
686
+ "unit_total",
687
+ "subtotal",
688
+ "discount_total",
689
+ "tax_total",
690
+ "total",
691
+ "unit_group_subtotal",
692
+ "unit_group_discount",
693
+ "unit_group_tax_total",
694
+ "unit_group_total",
695
+ "group_subtotal",
696
+ "group_discount",
697
+ "group_tax_total",
698
+ "group_total"
699
+ ];
700
+ const isMenu = (value) => {
701
+ if (!value || typeof value !== "object") return false;
702
+ const menu = value;
703
+ return Array.isArray(menu.products) && Array.isArray(menu.categories);
704
+ };
705
+ const lineOf = (line) => {
706
+ const next = { ...line };
707
+ for (const key of MONEY) {
708
+ const value = line[key];
709
+ if (typeof value === "number") next[key] = numberToDecimal(value);
710
+ }
711
+ return next;
712
+ };
713
+ const totalsOf = (lines, currency) => {
714
+ const roots = lines.filter((line) => line.parent_uid == null);
715
+ const subtotal = sumDecimals(roots.map((line) => line.group_subtotal));
716
+ const discount = sumDecimals(roots.map((line) => line.group_discount));
717
+ const tax = sumDecimals(roots.map((line) => line.group_tax_total));
718
+ const total = sumDecimals(roots.map((line) => line.group_total));
719
+ const discountRate = exactRate(discount, subtotal);
720
+ const taxRate = exactRate(tax, subtotal);
721
+ if (discountRate === null || taxRate === null) return null;
722
+ const b1 = {
723
+ currency,
724
+ subtotal,
725
+ discount_rate: discountRate
726
+ };
727
+ const b2 = {
728
+ discount_total: discount,
729
+ tax_rate: taxRate
730
+ };
731
+ const b3 = {
732
+ tax_total: tax,
733
+ total
734
+ };
735
+ return {
736
+ ...b1,
737
+ ...b2,
738
+ ...b3
739
+ };
740
+ };
741
+ /**
742
+ * Builds order lines with the same customization session the storefront
743
+ * uses, so modifier prices and required groups match menu validation.
744
+ */
745
+ const selectProduct = (menus, input) => {
746
+ const list = menus.filter(isMenu);
747
+ const menu = list.find((item) => item.products.some((row) => row.id === input.product_id)) ?? list[0];
748
+ if (!menu) return { error: "No hay un menú disponible ahora." };
749
+ let lookup;
750
+ try {
751
+ lookup = indexMenu(menu);
752
+ } catch {
753
+ return { error: "No pude leer el menú. Inténtalo de nuevo." };
754
+ }
755
+ let session;
756
+ try {
757
+ session = createSession(lookup, input.product_id);
758
+ } catch {
759
+ return { error: "No encuentro ese producto en este menú." };
760
+ }
761
+ const quantity = input.quantity ?? 1;
762
+ session.root.onChange(quantity);
763
+ for (const modifier of input.modifiers ?? []) {
764
+ const option = session.root.groups.find((item) => {
765
+ return item.data.id === modifier.group_id;
766
+ })?.modifiers.find((item) => {
767
+ return item.data.id === modifier.product_id;
768
+ });
769
+ if (!option) return { error: "Esa opción no está en el producto." };
770
+ option.onChange(modifier.quantity);
771
+ }
772
+ if (session.root.validate() !== "VALID") return { error: "Elige las opciones obligatorias antes de agregar." };
773
+ const locale = input.locale ?? "es";
774
+ const ordered = toOrderLines(session.root, locale);
775
+ if (ordered.length === 0) return { error: "No pude armar ese producto. Inténtalo de nuevo." };
776
+ const lines = ordered.map(lineOf);
777
+ const totals = totalsOf(lines, "USD");
778
+ if (!totals) return { error: "Envía los totales. No pude calcular la tasa sin redondear." };
779
+ try {
780
+ return {
781
+ lines,
782
+ totals,
783
+ apiLines: lines.map((line) => {
784
+ const next = { ...line };
785
+ for (const key of MONEY) next[key] = decimalToNumber(line[key]);
786
+ return next;
787
+ }),
788
+ apiTotals: {
789
+ currency: totals.currency,
790
+ subtotal: decimalToNumber(totals.subtotal),
791
+ discount_rate: totals.discount_rate,
792
+ discount_total: decimalToNumber(totals.discount_total),
793
+ tax_rate: totals.tax_rate,
794
+ tax_total: decimalToNumber(totals.tax_total),
795
+ total: decimalToNumber(totals.total)
796
+ }
797
+ };
798
+ } catch {
799
+ return { error: "Envía los totales. No pude calcular la tasa sin redondear." };
800
+ }
801
+ };
802
+ //#endregion
803
+ //#region src/tools/cart.view.ts
804
+ const httpsUrl$1 = (value) => {
805
+ if (typeof value !== "string" || !value.startsWith("https://")) return null;
806
+ return value;
807
+ };
808
+ const paymentUrlOf = (order) => {
809
+ if (!order || typeof order !== "object") return null;
810
+ const meta = order.metadata;
811
+ if (!meta || typeof meta !== "object") return null;
812
+ return httpsUrl$1(meta.agent_pay_url);
813
+ };
814
+ const cartViewOf = (input) => {
815
+ const items = input.lines.filter((line) => line.parent_uid == null).map((line) => {
816
+ return {
817
+ uid: line.uid,
818
+ name: line.name,
819
+ quantity: line.quantity,
820
+ total: line.group_total,
821
+ removable: true
822
+ };
823
+ });
824
+ const b1 = {
825
+ order_id: input.orderId,
826
+ store_id: input.storeId
827
+ };
828
+ const b2 = { fulfillment_id: input.fulfillmentId };
829
+ const b3 = { brand_id: input.brandId ?? null };
830
+ const b4 = { return_url: input.returnUrl ?? null };
831
+ const b5 = { payment_url: input.paymentUrl ?? null };
832
+ const b6 = {
833
+ customer: input.customer ?? null,
834
+ lines: input.lines,
835
+ items
836
+ };
837
+ return {
838
+ ...b1,
839
+ ...b2,
840
+ ...b3,
841
+ ...b4,
842
+ ...b5,
843
+ ...b6,
844
+ totals: input.totals
845
+ };
846
+ };
847
+ const compactCart = (view) => {
848
+ const items = view.items.map((item) => {
849
+ return {
850
+ uid: item.uid,
851
+ name: item.name,
852
+ quantity: item.quantity,
853
+ total: item.total
854
+ };
855
+ });
856
+ return {
857
+ order_id: view.order_id,
858
+ items,
859
+ totals: view.totals,
860
+ payment_url: view.payment_url
861
+ };
862
+ };
863
+ const idSchema = z.string().regex(/^[a-zA-Z0-9_-]+$/).min(1).max(64);
864
+ const decimalSchema = z.string().refine(isDecimalString, "Usa un monto decimal, por ejemplo 12.50");
865
+ const cartLineSchema = z.object({
866
+ type: z.enum(["PRODUCT", "FEE"]),
867
+ uid: z.uuid(),
868
+ id: idSchema,
869
+ parent_uid: z.uuid().nullable(),
870
+ parent_id: idSchema.nullable(),
871
+ group_id: idSchema.optional(),
872
+ name: z.string().trim().min(1).max(255),
873
+ quantity: z.number().min(1),
874
+ tax_rate: z.number().min(0).max(1).nullable(),
875
+ discount_rate: z.number().min(0).max(1),
876
+ unit_subtotal: decimalSchema,
877
+ unit_discount: decimalSchema,
878
+ unit_tax_total: decimalSchema,
879
+ unit_total: decimalSchema,
880
+ subtotal: decimalSchema,
881
+ discount_total: decimalSchema,
882
+ tax_total: decimalSchema,
883
+ total: decimalSchema,
884
+ unit_group_subtotal: decimalSchema,
885
+ unit_group_discount: decimalSchema,
886
+ unit_group_tax_total: decimalSchema,
887
+ unit_group_total: decimalSchema,
888
+ group_subtotal: decimalSchema,
889
+ group_discount: decimalSchema,
890
+ group_tax_total: decimalSchema,
891
+ group_total: decimalSchema
892
+ }).strict();
893
+ const totalsSchema = z.object({
894
+ currency: z.string().trim().length(3),
895
+ subtotal: decimalSchema,
896
+ discount_rate: z.number().min(0).max(1),
897
+ discount_total: decimalSchema,
898
+ tax_rate: z.number().min(0).max(1),
899
+ tax_total: decimalSchema,
900
+ total: decimalSchema
901
+ }).strict();
902
+ const customerSchema = z.object({
903
+ display_name: z.string().trim().min(1).max(255),
904
+ first_name: z.string().trim().min(1).max(255),
905
+ last_name: z.string().trim().min(1).max(255),
906
+ email: z.email(),
907
+ phone: z.string().regex(/^\+[1-9]\d{1,14}$/)
908
+ }).strict();
909
+ const listStoresSchema = z.object({
910
+ latitude: z.number().min(-90).max(90).optional(),
911
+ longitude: z.number().min(-180).max(180).optional(),
912
+ limit: z.number().int().min(1).max(50).optional(),
913
+ cursor: z.string().trim().min(1).max(220).optional(),
914
+ brand_id: idSchema.optional(),
915
+ fulfillment_id: idSchema.optional()
916
+ }).strict().superRefine((value, ctx) => {
917
+ if (value.latitude !== void 0 === (value.longitude !== void 0)) return;
918
+ ctx.addIssue({
919
+ code: "custom",
920
+ message: "Envía latitud y longitud juntas, o ninguna."
921
+ });
922
+ });
923
+ const localeSchema = z.string().trim().min(2).max(16).optional();
924
+ const pageLimit = z.number().int().min(1).max(24).optional();
925
+ const cursorSchema = z.string().trim().min(1).max(220).optional();
926
+ const getMenuSchema = z.object({
927
+ store_id: idSchema.optional(),
928
+ fulfillment_id: idSchema.optional(),
929
+ brand_id: idSchema.optional(),
930
+ category_id: idSchema.optional(),
931
+ cursor: cursorSchema,
932
+ limit: pageLimit,
933
+ locale: localeSchema
934
+ }).strict();
935
+ const getMenuCategorySchema = z.object({
936
+ handle: z.string().trim().min(8).max(500),
937
+ category_id: idSchema,
938
+ cursor: cursorSchema,
939
+ limit: pageLimit
940
+ }).strict();
941
+ const searchMenuSchema = z.object({
942
+ query: z.string().trim().min(1).max(80),
943
+ store_id: idSchema.optional(),
944
+ fulfillment_id: idSchema.optional(),
945
+ brand_id: idSchema.optional(),
946
+ handle: z.string().trim().min(8).max(500).optional(),
947
+ cursor: cursorSchema,
948
+ limit: pageLimit,
949
+ locale: localeSchema
950
+ }).strict();
951
+ const getProductSchema = z.object({
952
+ product_id: idSchema,
953
+ store_id: idSchema.optional(),
954
+ fulfillment_id: idSchema.optional(),
955
+ brand_id: idSchema.optional(),
956
+ handle: z.string().trim().min(8).max(500).optional(),
957
+ locale: localeSchema
958
+ }).strict();
959
+ const selectionModifierSchema = z.object({
960
+ group_id: idSchema,
961
+ product_id: idSchema,
962
+ quantity: z.number().int().min(1).max(99)
963
+ }).strict();
964
+ const returnUrl = z.url({ protocol: /^https$/ }).max(500).optional();
965
+ const buildCartSchema = z.object({
966
+ order_id: idSchema.optional(),
967
+ store_id: idSchema,
968
+ fulfillment_id: idSchema,
969
+ brand_id: idSchema.nullable().optional(),
970
+ is_anonymous: z.boolean().optional(),
971
+ customer: customerSchema.optional(),
972
+ lines: z.array(cartLineSchema).optional(),
973
+ totals: totalsSchema.optional(),
974
+ idempotency_key: idempotencyKeySchema,
975
+ product_id: idSchema.optional(),
976
+ quantity: z.number().int().min(1).max(99).optional(),
977
+ modifiers: z.array(selectionModifierSchema).max(40).optional(),
978
+ return_url: returnUrl,
979
+ locale: localeSchema
980
+ }).strict().superRefine((value, ctx) => {
981
+ if (value.product_id) return;
982
+ if (value.order_id && value.customer) return;
983
+ ctx.addIssue({
984
+ code: "custom",
985
+ message: "Envía el cliente y el order_id, o el producto a agregar."
986
+ });
987
+ });
988
+ const validateCartSchema = z.object({
989
+ store_id: idSchema,
990
+ fulfillment_id: idSchema,
991
+ brand_id: idSchema.nullable().optional(),
992
+ is_anonymous: z.boolean().optional(),
993
+ lines: z.array(cartLineSchema),
994
+ totals: totalsSchema
995
+ }).strict();
996
+ const orderStatusSchema = z.object({ order_id: idSchema }).strict();
997
+ /** Amounts for a new order. Currency is never accepted from the cart. */
998
+ const orderAmountSchema = z.object({
999
+ subtotal: decimalSchema,
1000
+ discount_rate: z.number().min(0).max(1),
1001
+ discount_total: decimalSchema,
1002
+ tax_rate: z.number().min(0).max(1),
1003
+ tax_total: decimalSchema,
1004
+ total: decimalSchema
1005
+ }).strict();
1006
+ const createOrderSchema = z.object({
1007
+ store_id: idSchema,
1008
+ fulfillment_id: idSchema,
1009
+ brand_id: idSchema.nullable().optional(),
1010
+ is_anonymous: z.boolean().optional(),
1011
+ customer: customerSchema,
1012
+ lines: z.array(cartLineSchema).min(1),
1013
+ totals: orderAmountSchema,
1014
+ idempotency_key: idempotencyKeySchema
1015
+ }).strict();
1016
+ const startPaymentSchema = z.object({
1017
+ order_id: idSchema,
1018
+ idempotency_key: idempotencyKeySchema,
1019
+ return_url: z.url({ protocol: /^https$/ }).max(500)
1020
+ }).strict();
1021
+ const listSavedCardsSchema = z.object({}).strict();
1022
+ const chargeSavedCardSchema = z.object({
1023
+ order_id: idSchema,
1024
+ card_ref: idSchema,
1025
+ confirmed_total: decimalSchema,
1026
+ idempotency_key: idempotencyKeySchema,
1027
+ return_url: z.url({ protocol: /^https$/ }).max(500)
1028
+ }).strict();
1029
+ const saveCardConsentSchema = z.object({
1030
+ order_id: idSchema,
1031
+ idempotency_key: idempotencyKeySchema,
1032
+ return_url: z.url({ protocol: /^https$/ }).max(500)
1033
+ }).strict();
1034
+ const revokeSavedCardSchema = z.object({
1035
+ card_ref: idSchema,
1036
+ idempotency_key: idempotencyKeySchema
1037
+ }).strict();
1038
+ //#endregion
1039
+ //#region src/tools/execute.ts
1040
+ const httpOf$3 = (ctx) => {
1041
+ return {
1042
+ baseUrl: ctx.apiUrl,
1043
+ accessToken: ctx.storefrontToken,
1044
+ fetchImpl: ctx.fetchImpl
1045
+ };
1046
+ };
1047
+ const toolError = (text) => {
1048
+ return {
1049
+ content: [{
1050
+ type: "text",
1051
+ text
1052
+ }],
1053
+ isError: true
1054
+ };
1055
+ };
1056
+ const toolOk = (payload) => {
1057
+ const safe = presentMoney(payload);
1058
+ return {
1059
+ content: [{
1060
+ type: "text",
1061
+ text: JSON.stringify(safe)
1062
+ }],
1063
+ structuredContent: safe
1064
+ };
1065
+ };
1066
+ /** Compact text for the model, rich structured content for the widget. */
1067
+ const toolView = (compact, view) => {
1068
+ return {
1069
+ content: [{
1070
+ type: "text",
1071
+ text: JSON.stringify(presentMoney(compact))
1072
+ }],
1073
+ structuredContent: presentMoney(view)
1074
+ };
1075
+ };
1076
+ const LINE_MONEY = [
1077
+ "unit_subtotal",
1078
+ "unit_discount",
1079
+ "unit_tax_total",
1080
+ "unit_total",
1081
+ "subtotal",
1082
+ "discount_total",
1083
+ "tax_total",
1084
+ "total",
1085
+ "unit_group_subtotal",
1086
+ "unit_group_discount",
1087
+ "unit_group_tax_total",
1088
+ "unit_group_total",
1089
+ "group_subtotal",
1090
+ "group_discount",
1091
+ "group_tax_total",
1092
+ "group_total"
1093
+ ];
1094
+ const lineToApi = (line) => {
1095
+ const next = { ...line };
1096
+ for (const key of LINE_MONEY) next[key] = decimalToNumber(line[key]);
1097
+ return next;
1098
+ };
1099
+ const totalsToApi = (totals) => {
1100
+ const subtotal = decimalToNumber(totals.subtotal);
1101
+ const discount = decimalToNumber(totals.discount_total);
1102
+ const tax = decimalToNumber(totals.tax_total);
1103
+ const total = decimalToNumber(totals.total);
1104
+ const b1 = {
1105
+ currency: totals.currency,
1106
+ subtotal
1107
+ };
1108
+ const b2 = {
1109
+ discount_rate: totals.discount_rate,
1110
+ discount_total: discount
1111
+ };
1112
+ const b3 = {
1113
+ tax_rate: totals.tax_rate,
1114
+ tax_total: tax,
1115
+ total
1116
+ };
1117
+ return {
1118
+ ...b1,
1119
+ ...b2,
1120
+ ...b3
1121
+ };
1122
+ };
1123
+ const computedTotals = (lines) => {
1124
+ const roots = lines.filter((line) => line.parent_uid == null);
1125
+ const subtotal = sumDecimals(roots.map((line) => line.group_subtotal));
1126
+ const discount = sumDecimals(roots.map((line) => line.group_discount));
1127
+ const tax = sumDecimals(roots.map((line) => line.group_tax_total));
1128
+ const total = sumDecimals(roots.map((line) => line.group_total));
1129
+ const discountRate = exactRate(discount, subtotal);
1130
+ const taxRate = exactRate(tax, subtotal);
1131
+ if (discountRate === null || taxRate === null) return null;
1132
+ const b1 = {
1133
+ currency: "USD",
1134
+ subtotal,
1135
+ discount_rate: discountRate
1136
+ };
1137
+ const b2 = {
1138
+ discount_total: discount,
1139
+ tax_rate: taxRate
1140
+ };
1141
+ const b3 = {
1142
+ tax_total: tax,
1143
+ total
1144
+ };
1145
+ const totals = {
1146
+ ...b1,
1147
+ ...b2,
1148
+ ...b3
1149
+ };
1150
+ return totalsToApi(totals);
1151
+ };
1152
+ const executeListStores = async (args, ctx) => {
1153
+ const http = httpOf$3(ctx);
1154
+ const b1 = {
1155
+ brand_id: args.brand_id,
1156
+ fulfillment_id: args.fulfillment_id
1157
+ };
1158
+ const b2 = {
1159
+ channel_id: ctx.channelId,
1160
+ limit: args.limit
1161
+ };
1162
+ const b3 = { cursor: args.cursor };
1163
+ const filters = {
1164
+ ...b1,
1165
+ ...b2,
1166
+ ...b3
1167
+ };
1168
+ try {
1169
+ if (args.latitude !== void 0 && args.longitude !== void 0) {
1170
+ const nearby = {
1171
+ ...filters,
1172
+ latitude: args.latitude,
1173
+ longitude: args.longitude
1174
+ };
1175
+ const stores = await services.stores.nearby(nearby, http);
1176
+ return toolOk({ stores });
1177
+ }
1178
+ const stores = await services.stores.list(filters, http);
1179
+ return toolOk({ stores });
1180
+ } catch (error) {
1181
+ return failure(error, "No pude leer las tiendas. Inténtalo de nuevo.");
1182
+ }
1183
+ };
1184
+ const loadMenus = async (scope, ctx) => {
1185
+ const http = httpOf$3(ctx);
1186
+ const menuScope = {
1187
+ store_id: scope.store_id,
1188
+ fulfillment_id: scope.fulfillment_id,
1189
+ brand_id: scope.brand_id ?? void 0,
1190
+ channel_id: ctx.channelId
1191
+ };
1192
+ const storeScope = {
1193
+ channel_id: ctx.channelId,
1194
+ fulfillment_id: scope.fulfillment_id,
1195
+ brand_id: scope.brand_id ?? void 0
1196
+ };
1197
+ const menus = services.menus.get(menuScope, http);
1198
+ const stores = services.stores.list(storeScope, http);
1199
+ const [menuRows, storeRows] = await Promise.all([menus, stores]);
1200
+ const wanted = scope.store_id;
1201
+ const list = Array.isArray(storeRows) ? storeRows : [];
1202
+ return {
1203
+ menus: menuRows,
1204
+ store: list.find((item) => {
1205
+ return !!item && typeof item === "object" && "id" in item && item.id === wanted;
1206
+ }) ?? list[0] ?? null
1207
+ };
1208
+ };
1209
+ const cartBody = (args, ctx) => {
1210
+ const lines = "lines" in args && args.lines ? args.lines : [];
1211
+ const totals = args.totals ? totalsToApi(args.totals) : computedTotals(lines);
1212
+ if (!totals) return null;
1213
+ const brand = args.brand_id ?? null;
1214
+ const anon = args.is_anonymous ?? false;
1215
+ const linesApi = lines.map(lineToApi);
1216
+ const b1 = {
1217
+ store_id: args.store_id,
1218
+ channel_id: ctx.channelId
1219
+ };
1220
+ const b2 = {
1221
+ fulfillment_id: args.fulfillment_id,
1222
+ brand_id: brand
1223
+ };
1224
+ const b3 = {
1225
+ is_anonymous: anon,
1226
+ lines: linesApi
1227
+ };
1228
+ return {
1229
+ ...b1,
1230
+ ...b2,
1231
+ ...b3,
1232
+ totals
1233
+ };
1234
+ };
1235
+ const customerOf = (raw) => {
1236
+ if (!raw || typeof raw !== "object") return null;
1237
+ const row = raw;
1238
+ const text = (value) => {
1239
+ return typeof value === "string" ? value.trim() : "";
1240
+ };
1241
+ const first = text(row.first_name);
1242
+ const last = text(row.last_name);
1243
+ const display = text(row.display_name) || `${first} ${last}`.trim();
1244
+ const parsed = customerSchema.safeParse({
1245
+ display_name: display,
1246
+ first_name: first,
1247
+ last_name: last,
1248
+ email: text(row.email),
1249
+ phone: text(row.phone)
1250
+ });
1251
+ return parsed.success ? parsed.data : null;
1252
+ };
1253
+ const loadCustomer = async (ctx) => {
1254
+ const raw = await services.customers.get(ctx.customerId, httpOf$3(ctx));
1255
+ return customerOf(raw);
1256
+ };
1257
+ const cartResult = (order, viewInput) => {
1258
+ const view = cartViewOf(viewInput);
1259
+ const payload = {
1260
+ order_id: order.id,
1261
+ order,
1262
+ view
1263
+ };
1264
+ return toolView(compactCart(view), payload);
1265
+ };
1266
+ const addProduct = async (args, ctx) => {
1267
+ if (!args.product_id) return toolError("No encuentro ese producto.");
1268
+ const loaded = await loadMenus(args, ctx);
1269
+ const customer = args.customer ?? await loadCustomer(ctx);
1270
+ if (!customer) return toolError("Completa tu nombre, correo y teléfono para armar el carrito.");
1271
+ const selected = selectProduct(loaded.menus, {
1272
+ product_id: args.product_id,
1273
+ quantity: args.quantity,
1274
+ modifiers: args.modifiers,
1275
+ locale: args.locale
1276
+ });
1277
+ if ("error" in selected) return toolError(selected.error);
1278
+ const orderId = args.order_id ?? randomUUID();
1279
+ const brand = args.brand_id ?? null;
1280
+ const b1 = {
1281
+ store_id: args.store_id,
1282
+ channel_id: ctx.channelId
1283
+ };
1284
+ const b2 = {
1285
+ fulfillment_id: args.fulfillment_id,
1286
+ brand_id: brand
1287
+ };
1288
+ const b3 = {
1289
+ is_anonymous: args.is_anonymous ?? false,
1290
+ lines: selected.apiLines
1291
+ };
1292
+ const cart = {
1293
+ ...b1,
1294
+ ...b2,
1295
+ ...b3,
1296
+ totals: selected.apiTotals
1297
+ };
1298
+ const info = { customer_info: customer };
1299
+ const metadata = { idempotency_key: args.idempotency_key };
1300
+ const body = {
1301
+ ...cart,
1302
+ id: orderId,
1303
+ customer: info,
1304
+ metadata
1305
+ };
1306
+ const order = await services.orders.post(body, httpOf$3(ctx));
1307
+ const v1 = {
1308
+ orderId: order.id,
1309
+ storeId: args.store_id
1310
+ };
1311
+ const v2 = {
1312
+ fulfillmentId: args.fulfillment_id,
1313
+ brandId: brand
1314
+ };
1315
+ const v3 = {
1316
+ returnUrl: args.return_url ?? null,
1317
+ paymentUrl: paymentUrlOf(order)
1318
+ };
1319
+ const v4 = {
1320
+ customer,
1321
+ lines: selected.lines,
1322
+ totals: selected.totals
1323
+ };
1324
+ return cartResult(order, {
1325
+ ...v1,
1326
+ ...v2,
1327
+ ...v3,
1328
+ ...v4
1329
+ });
1330
+ };
1331
+ const executeBuildCart = async (args, ctx) => {
1332
+ try {
1333
+ if (args.product_id) return await addProduct(args, ctx);
1334
+ if (!args.order_id || !args.customer) return toolError("Envía el cliente y el order_id, o el producto a agregar.");
1335
+ const cart = cartBody(args, ctx);
1336
+ if (!cart) return toolError("Envía los totales. No pude calcular la tasa sin redondear.");
1337
+ const customer = { customer_info: args.customer };
1338
+ const metadata = { idempotency_key: args.idempotency_key };
1339
+ const body = {
1340
+ ...cart,
1341
+ id: args.order_id,
1342
+ customer,
1343
+ metadata
1344
+ };
1345
+ const order = await services.orders.post(body, httpOf$3(ctx));
1346
+ const lines = args.lines ?? [];
1347
+ const v1 = {
1348
+ orderId: order.id,
1349
+ storeId: args.store_id
1350
+ };
1351
+ const v2 = {
1352
+ fulfillmentId: args.fulfillment_id,
1353
+ brandId: args.brand_id
1354
+ };
1355
+ const v3 = { returnUrl: args.return_url ?? null };
1356
+ const v4 = {
1357
+ paymentUrl: paymentUrlOf(order),
1358
+ customer: args.customer
1359
+ };
1360
+ const v5 = {
1361
+ lines,
1362
+ totals: args.totals ?? null
1363
+ };
1364
+ return cartResult(order, {
1365
+ ...v1,
1366
+ ...v2,
1367
+ ...v3,
1368
+ ...v4,
1369
+ ...v5
1370
+ });
1371
+ } catch (error) {
1372
+ return failure(error, "No pude armar el carrito. Inténtalo de nuevo.");
1373
+ }
1374
+ };
1375
+ const executeValidateCart = async (args, ctx) => {
1376
+ const sent = cartBody(args, ctx);
1377
+ if (!sent) return toolError("Envía los totales. No pude calcular la tasa sin redondear.");
1378
+ try {
1379
+ const result = await services.orders.validate(sent, httpOf$3(ctx));
1380
+ const view = cartViewOf({
1381
+ orderId: "",
1382
+ storeId: args.store_id,
1383
+ fulfillmentId: args.fulfillment_id,
1384
+ brandId: args.brand_id,
1385
+ lines: args.lines,
1386
+ totals: args.totals
1387
+ });
1388
+ const payload = {
1389
+ validation: result,
1390
+ view
1391
+ };
1392
+ return toolView(compactCart(view), payload);
1393
+ } catch (error) {
1394
+ return failure(error, "No pude validar el carrito. Inténtalo de nuevo.");
1395
+ }
1396
+ };
1397
+ const executeOrderStatus = async (args, ctx) => {
1398
+ try {
1399
+ const order = await services.orders.get(args.order_id, httpOf$3(ctx));
1400
+ if (order.channel_id !== ctx.channelId) return toolError("No encuentro ese pedido en este canal.");
1401
+ const b1 = {
1402
+ id: order.id,
1403
+ status: order.status
1404
+ };
1405
+ const b2 = { payment_status: order.payment_status };
1406
+ const b3 = { fulfillment_status: order.fulfillment_status };
1407
+ const b4 = {
1408
+ store_id: order.store_id,
1409
+ channel_id: order.channel_id
1410
+ };
1411
+ const b5 = {
1412
+ fulfillment_id: order.fulfillment_id,
1413
+ totals: order.totals
1414
+ };
1415
+ const status = {
1416
+ ...b1,
1417
+ ...b2,
1418
+ ...b3,
1419
+ ...b4,
1420
+ ...b5
1421
+ };
1422
+ return toolOk({ order: status });
1423
+ } catch (error) {
1424
+ return failure(error, "No pude leer el pedido. Inténtalo de nuevo.");
1425
+ }
1426
+ };
1427
+ const failure = (error, fallback) => {
1428
+ if (error instanceof OrderValidationError) {
1429
+ const details = {
1430
+ issues: error.issues,
1431
+ lines: error.lines
1432
+ };
1433
+ return toolError(`${fallback} ${JSON.stringify(presentMoney(details))}`);
1434
+ }
1435
+ if (error instanceof StorefrontHttpError && error.status === 404) return toolError("No encuentro eso en este canal.");
1436
+ return toolError(fallback);
1437
+ };
1438
+ //#endregion
1439
+ //#region src/tools/pay.ts
1440
+ const CONFIRMED$2 = "agent_confirmed";
1441
+ const PAY_URL = "agent_pay_url";
1442
+ const PAY_EXP = "agent_pay_exp";
1443
+ const PAY_KEY = "agent_pay_key";
1444
+ const PAY_USED = "agent_pay_used";
1445
+ const metaOf$2 = (order) => {
1446
+ const meta = order.metadata;
1447
+ if (!meta || typeof meta !== "object" || Array.isArray(meta)) return {};
1448
+ return meta;
1449
+ };
1450
+ const httpOf$2 = (ctx) => {
1451
+ return {
1452
+ baseUrl: ctx.apiUrl,
1453
+ accessToken: ctx.storefrontToken,
1454
+ fetchImpl: ctx.fetchImpl
1455
+ };
1456
+ };
1457
+ const reuse = (meta, key, now) => {
1458
+ if (meta[PAY_KEY] !== key) return "";
1459
+ if (typeof meta[PAY_URL] !== "string" || !meta[PAY_URL]) return "";
1460
+ if (typeof meta[PAY_USED] === "string" && meta[PAY_USED]) return "";
1461
+ const exp = Number(meta[PAY_EXP]);
1462
+ if (!Number.isFinite(exp) || exp <= now) return "";
1463
+ return meta[PAY_URL];
1464
+ };
1465
+ const executeStartPayment = async (args, ctx, now = Date.now(), options) => {
1466
+ const secret = ctx.linkSecret ?? "";
1467
+ const origin = ctx.origin ?? "";
1468
+ if (!secret || !origin) return toolError("El canal Agent no puede cobrar todavía.");
1469
+ try {
1470
+ const order = await services.orders.get(args.order_id, httpOf$2(ctx));
1471
+ if (order.channel_id !== ctx.channelId) return toolError("No encuentro ese pedido en este canal.");
1472
+ const meta = metaOf$2(order);
1473
+ if (meta[CONFIRMED$2] !== "true") return toolError("Confirma el total del pedido antes de pagar.");
1474
+ const again = reuse(meta, args.idempotency_key, now);
1475
+ if (again) {
1476
+ const exp = Number(meta[PAY_EXP]);
1477
+ return toolOk({
1478
+ payment_url: again,
1479
+ expires_at: new Date(exp).toISOString()
1480
+ });
1481
+ }
1482
+ const exp = now + PAYMENT_LINK_TTL_MS;
1483
+ const token = await mintAgentLink({
1484
+ purpose: "pay",
1485
+ merchantId: ctx.merchantId,
1486
+ channelId: ctx.channelId,
1487
+ customerId: ctx.customerId,
1488
+ orderId: order.id,
1489
+ returnUrl: args.return_url,
1490
+ jti: newLinkId(),
1491
+ exp,
1492
+ storefrontToken: ctx.storefrontToken,
1493
+ saveCard: options?.saveCard ? true : void 0
1494
+ }, secret);
1495
+ const paymentUrl = `${origin}/m/${encodeURIComponent(ctx.merchantId)}/pay/${token}`;
1496
+ const next = {
1497
+ ...meta,
1498
+ [PAY_URL]: paymentUrl,
1499
+ [PAY_EXP]: String(exp),
1500
+ [PAY_KEY]: args.idempotency_key,
1501
+ [PAY_USED]: ""
1502
+ };
1503
+ await services.orders.patch(order.id, { metadata: next }, httpOf$2(ctx));
1504
+ return toolOk({
1505
+ payment_url: paymentUrl,
1506
+ expires_at: new Date(exp).toISOString()
1507
+ });
1508
+ } catch (error) {
1509
+ return failure(error, "No pude abrir el pago. Inténtalo de nuevo.");
1510
+ }
1511
+ };
1512
+ //#endregion
1513
+ //#region src/tools/cards.ts
1514
+ const CHARGE_KEY = "agent_card_charge_key";
1515
+ const CHARGE_STATUS = "agent_card_charge_status";
1516
+ const CHARGE_REF = "agent_card_charge_ref";
1517
+ const CHARGE_TENDER = "agent_card_charge_tender";
1518
+ const CHARGE_ATTEMPT = "agent_card_charge_attempt";
1519
+ const CHARGE_PROVIDER_REF = "agent_card_charge_provider_ref";
1520
+ const CONSENT_KEY = "agent_card_consent_key";
1521
+ const CONSENT_AT = "agent_card_consent_at";
1522
+ const CONFIRMED$1 = "agent_confirmed";
1523
+ const CURRENCY$1 = /^[A-Z]{3}$/;
1524
+ const httpOf$1 = (ctx) => {
1525
+ return {
1526
+ baseUrl: ctx.apiUrl,
1527
+ accessToken: ctx.storefrontToken,
1528
+ fetchImpl: ctx.fetchImpl
1529
+ };
1530
+ };
1531
+ const metaOf$1 = (order) => {
1532
+ const meta = order.metadata;
1533
+ if (!meta || typeof meta !== "object" || Array.isArray(meta)) return {};
1534
+ return meta;
1535
+ };
1536
+ const readJson = async (ctx, path, init) => {
1537
+ const base = ctx.apiUrl.replace(/\/$/, "");
1538
+ const headers = new Headers(init?.headers);
1539
+ headers.set("authorization", `Bearer ${ctx.storefrontToken}`);
1540
+ if (init?.body && !headers.has("content-type")) headers.set("content-type", "application/json");
1541
+ const res = await (ctx.fetchImpl ?? fetch)(`${base}${path}`, {
1542
+ ...init,
1543
+ headers
1544
+ });
1545
+ const json = await res.json().catch(() => ({}));
1546
+ if (!res.ok) {
1547
+ const error = /* @__PURE__ */ new Error("storefront");
1548
+ error.status = res.status;
1549
+ throw error;
1550
+ }
1551
+ return json.data;
1552
+ };
1553
+ const savedCards = async (ctx) => {
1554
+ const row = await readJson(ctx, "/api/storefront/v1/saved-cards");
1555
+ return {
1556
+ available: row?.available === true,
1557
+ cards: Array.isArray(row?.cards) ? row.cards : []
1558
+ };
1559
+ };
1560
+ const publicCards = (cards) => {
1561
+ return cards.map((card) => {
1562
+ const b1 = {
1563
+ id: card.id,
1564
+ brand: card.brand,
1565
+ last4: card.last4
1566
+ };
1567
+ const b2 = {
1568
+ expiry_month: card.expiry_month,
1569
+ expiry_year: card.expiry_year
1570
+ };
1571
+ return {
1572
+ ...b1,
1573
+ ...b2
1574
+ };
1575
+ });
1576
+ };
1577
+ const totalOf$1 = (order) => {
1578
+ const total = order.totals?.total;
1579
+ const currency = order.totals?.currency;
1580
+ if (typeof total !== "number" || typeof currency !== "string") return null;
1581
+ if (!CURRENCY$1.test(currency)) return null;
1582
+ return {
1583
+ total: numberToDecimal(total),
1584
+ currency
1585
+ };
1586
+ };
1587
+ const loadOrder = async (ctx, orderId) => {
1588
+ const order = await services.orders.get(orderId, httpOf$1(ctx));
1589
+ if (order.channel_id !== ctx.channelId) return null;
1590
+ return order;
1591
+ };
1592
+ const executeListSavedCards = async (_args, ctx) => {
1593
+ try {
1594
+ const listed = await savedCards(ctx);
1595
+ if (!listed.available) return toolOk({
1596
+ available: false,
1597
+ cards: [],
1598
+ message: "Este comercio no tiene una pasarela que guarde tarjetas."
1599
+ });
1600
+ return toolOk({
1601
+ available: true,
1602
+ cards: publicCards(listed.cards)
1603
+ });
1604
+ } catch (error) {
1605
+ return failure(error, "No pude leer tus tarjetas. Inténtalo de nuevo.");
1606
+ }
1607
+ };
1608
+ const paymentFor = (payments, provider) => {
1609
+ if (!Array.isArray(payments)) return null;
1610
+ for (const item of payments) {
1611
+ const row = item;
1612
+ if (row.provider?.provider_id !== provider) continue;
1613
+ if (!(row.capabilities ?? []).includes("charge_with_token")) continue;
1614
+ if (typeof row.id !== "string") continue;
1615
+ return row;
1616
+ }
1617
+ return null;
1618
+ };
1619
+ const textMeta = (meta, key) => {
1620
+ const value = meta[key];
1621
+ return typeof value === "string" ? value : "";
1622
+ };
1623
+ const threeDsLink = async (args, ctx, money) => {
1624
+ const link = await executeStartPayment(args, ctx);
1625
+ if ("isError" in link && link.isError) return link;
1626
+ const text = link.content[0]?.text ?? "{}";
1627
+ const parsed = JSON.parse(text);
1628
+ const b1 = {
1629
+ requires_3ds: true,
1630
+ card_ref: args.card_ref
1631
+ };
1632
+ const b2 = {
1633
+ total: money.total,
1634
+ currency: money.currency
1635
+ };
1636
+ const b3 = {
1637
+ payment_url: parsed.payment_url,
1638
+ expires_at: parsed.expires_at
1639
+ };
1640
+ return toolOk({
1641
+ ...b1,
1642
+ ...b2,
1643
+ ...b3
1644
+ });
1645
+ };
1646
+ const executeChargeSavedCard = async (args, ctx, round = {}) => {
1647
+ const secret = ctx.linkSecret ?? "";
1648
+ if (!secret) return toolError("El canal Agent no puede cobrar todavía.");
1649
+ try {
1650
+ const order = await loadOrder(ctx, args.order_id);
1651
+ if (!order) return toolError("No encuentro ese pedido en este canal.");
1652
+ let meta = metaOf$1(order);
1653
+ const writeMeta = async (extra) => {
1654
+ meta = {
1655
+ ...meta,
1656
+ ...extra
1657
+ };
1658
+ await services.orders.patch(order.id, { metadata: meta }, httpOf$1(ctx));
1659
+ };
1660
+ const replayPaid = async () => {
1661
+ const tenderId = textMeta(meta, CHARGE_TENDER);
1662
+ const attempt = textMeta(meta, CHARGE_ATTEMPT);
1663
+ if (!tenderId || !attempt) return;
1664
+ const ref = textMeta(meta, CHARGE_PROVIDER_REF);
1665
+ const provider_reference = ref ? ref : void 0;
1666
+ const pay1 = {
1667
+ tender_id: tenderId,
1668
+ attempt_reference: attempt
1669
+ };
1670
+ const pay2 = {
1671
+ status: "PAID",
1672
+ provider_reference
1673
+ };
1674
+ const pay = {
1675
+ ...pay1,
1676
+ ...pay2
1677
+ };
1678
+ const http = httpOf$1(ctx);
1679
+ await services.orders.recordPayment(order.id, pay, http);
1680
+ };
1681
+ if (meta[CONFIRMED$1] !== "true") return toolError("Confirma el total del pedido antes de cobrar.");
1682
+ const money = totalOf$1(order);
1683
+ if (!money) return toolError("El pedido no tiene una moneda del comercio.");
1684
+ const sameKey = meta[CHARGE_KEY] === args.idempotency_key;
1685
+ const sameCard = meta[CHARGE_REF] === args.card_ref;
1686
+ if (sameKey && sameCard && meta[CHARGE_STATUS] === "PAID") {
1687
+ await replayPaid();
1688
+ const b1 = {
1689
+ status: "PAID",
1690
+ card_ref: args.card_ref
1691
+ };
1692
+ const b2 = {
1693
+ total: money.total,
1694
+ currency: money.currency
1695
+ };
1696
+ return toolOk({
1697
+ ...b1,
1698
+ ...b2
1699
+ });
1700
+ }
1701
+ if (sameKey && sameCard && meta[CHARGE_STATUS] === "REQUIRES_3DS") return threeDsLink(args, ctx, money);
1702
+ const listed = await savedCards(ctx);
1703
+ const card = listed.cards.find((item) => item.id === args.card_ref);
1704
+ if (!listed.available || !card) return toolError("No encuentro esa tarjeta en tu cuenta.");
1705
+ const answered = Boolean(round.inputResponses);
1706
+ const echoed = Boolean(round.requestState);
1707
+ if (!(answered || echoed)) {
1708
+ const b1 = {
1709
+ order_id: args.order_id,
1710
+ card_ref: args.card_ref
1711
+ };
1712
+ const b2 = {
1713
+ total: money.total,
1714
+ currency: money.currency
1715
+ };
1716
+ const b3 = {
1717
+ brand: card.brand,
1718
+ last4: card.last4
1719
+ };
1720
+ const b4 = { idempotency_key: args.idempotency_key };
1721
+ const sealed = await sealRequestState({
1722
+ ...b1,
1723
+ ...b2,
1724
+ ...b3,
1725
+ ...b4
1726
+ }, secret);
1727
+ return confirmSavedCardRequest({
1728
+ ...b2,
1729
+ ...b3,
1730
+ requestState: sealed
1731
+ });
1732
+ }
1733
+ const opened = await openRequestState(round.requestState ?? "", secret);
1734
+ if (!opened || opened.order_id !== args.order_id) return toolError("No pude verificar la confirmación. Empieza de nuevo.");
1735
+ if (opened.card_ref !== args.card_ref) return toolError("La tarjeta confirmada no es la que enviaste.");
1736
+ if (opened.idempotency_key !== args.idempotency_key) return toolError("No pude verificar la confirmación. Empieza de nuevo.");
1737
+ const amount = confirmedAmount(round.inputResponses);
1738
+ if (!amount) return toolError("No confirmaste el total. No hice el cobro.");
1739
+ const sameOrder = decimalsEqual(amount, money.total);
1740
+ const sameSeal = decimalsEqual(amount, opened.total ?? "");
1741
+ const sameCurrency = money.currency === opened.currency;
1742
+ const mismatch = "El total confirmado no coincide con el total del pedido.";
1743
+ if (!sameOrder || !sameSeal || !sameCurrency) return toolError(mismatch);
1744
+ const sent = args.confirmed_total;
1745
+ if (sent && !decimalsEqual(sent, money.total)) return toolError(mismatch);
1746
+ if (sameKey && meta[CHARGE_STATUS] === "pending") return toolError("Ya envié este cobro. Revisa el estado del pedido.");
1747
+ const s1 = {
1748
+ order_id: order.id,
1749
+ store_id: order.store_id
1750
+ };
1751
+ const s2 = { channel_id: ctx.channelId };
1752
+ const s3 = { fulfillment_id: order.fulfillment_id };
1753
+ const scope = {
1754
+ ...s1,
1755
+ ...s2,
1756
+ ...s3
1757
+ };
1758
+ const payments = await services.payments.list(scope, httpOf$1(ctx));
1759
+ const payment = paymentFor(payments, card.provider);
1760
+ if (!payment) return toolError("Esta pasarela no cobra con tarjeta guardada.");
1761
+ if ((payment.capabilities ?? []).includes("requires_3ds_on_token")) {
1762
+ const k1 = { [CHARGE_KEY]: args.idempotency_key };
1763
+ const k2 = {
1764
+ [CHARGE_REF]: args.card_ref,
1765
+ [CHARGE_STATUS]: "REQUIRES_3DS"
1766
+ };
1767
+ await writeMeta({
1768
+ ...k1,
1769
+ ...k2
1770
+ });
1771
+ return threeDsLink(args, ctx, money);
1772
+ }
1773
+ const attempt = newLinkId();
1774
+ const t1 = {
1775
+ method: payment.method?.method ?? "CARD",
1776
+ provider: card.provider,
1777
+ payment_id: payment.id
1778
+ };
1779
+ const t2 = {
1780
+ collect_at: "DEVICE",
1781
+ attempt_reference: attempt
1782
+ };
1783
+ const intent = { tenders: [{
1784
+ ...t1,
1785
+ ...t2
1786
+ }] };
1787
+ const http = httpOf$1(ctx);
1788
+ const started = tenderOnOrder(await services.orders.putPaymentIntent(order.id, intent, http), payment.id, attempt);
1789
+ if (!started) return toolError("No pude abrir el cobro. Inténtalo de nuevo.");
1790
+ const w1 = { [CHARGE_KEY]: args.idempotency_key };
1791
+ const w2 = {
1792
+ [CHARGE_REF]: args.card_ref,
1793
+ [CHARGE_STATUS]: "pending"
1794
+ };
1795
+ const w3 = { [CHARGE_TENDER]: started.id };
1796
+ const w4 = { [CHARGE_ATTEMPT]: started.attemptReference };
1797
+ await writeMeta({
1798
+ ...w1,
1799
+ ...w2,
1800
+ ...w3,
1801
+ ...w4
1802
+ });
1803
+ const input = {
1804
+ card_ref: args.card_ref,
1805
+ confirmed_total: money.total
1806
+ };
1807
+ const o1 = { order_id: order.id };
1808
+ const o2 = {
1809
+ attempt_reference: started.attemptReference,
1810
+ input
1811
+ };
1812
+ const body = {
1813
+ ...o1,
1814
+ ...o2
1815
+ };
1816
+ const row = await services.payments.operation(payment.id, "charge_with_token", body, http);
1817
+ if (row.requires_3ds || row.status === "REQUIRES_3DS") {
1818
+ await writeMeta({ [CHARGE_STATUS]: "REQUIRES_3DS" });
1819
+ return threeDsLink(args, ctx, money);
1820
+ }
1821
+ if (row.status !== "PAID") {
1822
+ await writeMeta({ [CHARGE_STATUS]: "FAILED" });
1823
+ return toolError("La pasarela no cobró la tarjeta. No se hizo el cargo.");
1824
+ }
1825
+ const providerRef = row.provider_reference ?? "";
1826
+ await writeMeta({
1827
+ [CHARGE_STATUS]: "PAID",
1828
+ [CHARGE_PROVIDER_REF]: providerRef
1829
+ });
1830
+ await replayPaid();
1831
+ const done = {
1832
+ status: "PAID",
1833
+ card_ref: args.card_ref
1834
+ };
1835
+ const amounts = {
1836
+ total: money.total,
1837
+ currency: money.currency
1838
+ };
1839
+ return toolOk({
1840
+ ...done,
1841
+ ...amounts
1842
+ });
1843
+ } catch (error) {
1844
+ if (error.status === 404) return toolError("No encuentro esa tarjeta en tu cuenta.");
1845
+ return failure(error, "No pude cobrar la tarjeta. Inténtalo de nuevo.");
1846
+ }
1847
+ };
1848
+ const executeSaveCardConsent = async (args, ctx, round = {}) => {
1849
+ const secret = ctx.linkSecret ?? "";
1850
+ if (!secret) return toolError("El canal Agent no puede guardar tarjetas.");
1851
+ try {
1852
+ const order = await loadOrder(ctx, args.order_id);
1853
+ if (!order) return toolError("No encuentro ese pedido en este canal.");
1854
+ const s1 = {
1855
+ order_id: order.id,
1856
+ store_id: order.store_id
1857
+ };
1858
+ const s2 = { channel_id: ctx.channelId };
1859
+ const s3 = { fulfillment_id: order.fulfillment_id };
1860
+ const scope = {
1861
+ ...s1,
1862
+ ...s2,
1863
+ ...s3
1864
+ };
1865
+ const payments = await services.payments.list(scope, httpOf$1(ctx));
1866
+ const rows = Array.isArray(payments) ? payments : [];
1867
+ const saves = (item) => {
1868
+ return (item.capabilities ?? []).includes("hosted_tokenization");
1869
+ };
1870
+ if (!rows.some(saves)) return toolError("Este comercio no puede guardar tarjetas en su pasarela.");
1871
+ const meta = metaOf$1(order);
1872
+ if (meta[CONSENT_KEY] === args.idempotency_key && meta[CONSENT_AT]) return executeStartPayment(args, ctx, Date.now(), { saveCard: true });
1873
+ const answered = Boolean(round.inputResponses);
1874
+ const echoed = Boolean(round.requestState);
1875
+ if (!(answered || echoed)) {
1876
+ const seal = { order_id: args.order_id };
1877
+ const key = { idempotency_key: args.idempotency_key };
1878
+ return confirmCardConsentRequest(await sealRequestState({
1879
+ ...seal,
1880
+ ...key
1881
+ }, secret));
1882
+ }
1883
+ const opened = await openRequestState(round.requestState ?? "", secret);
1884
+ const again = "No pude verificar el consentimiento. Empieza de nuevo.";
1885
+ if (!opened || opened.order_id !== args.order_id) return toolError(again);
1886
+ if (opened.idempotency_key !== args.idempotency_key) return toolError(again);
1887
+ if (!cardConsentAccepted(round.inputResponses)) return toolError("No autorizaste guardar la tarjeta. No la guardé.");
1888
+ const when = (/* @__PURE__ */ new Date()).toISOString();
1889
+ const c1 = {
1890
+ [CONSENT_KEY]: args.idempotency_key,
1891
+ [CONSENT_AT]: when
1892
+ };
1893
+ const patch = { metadata: {
1894
+ ...metaOf$1(order),
1895
+ ...c1
1896
+ } };
1897
+ await services.orders.patch(order.id, patch, httpOf$1(ctx));
1898
+ return executeStartPayment(args, ctx, Date.now(), { saveCard: true });
1899
+ } catch (error) {
1900
+ return failure(error, "No pude registrar el consentimiento.");
1901
+ }
1902
+ };
1903
+ const executeRevokeSavedCard = async (args, ctx) => {
1904
+ try {
1905
+ const path = `/api/storefront/v1/saved-cards/${encodeURIComponent(args.card_ref)}/revoke`;
1906
+ const row = await readJson(ctx, path, {
1907
+ method: "POST",
1908
+ body: "{}"
1909
+ });
1910
+ if (row.revoked !== true) return toolError("No pude revocar la tarjeta.");
1911
+ return toolOk({
1912
+ revoked: true,
1913
+ card_ref: row.card_ref ?? args.card_ref
1914
+ });
1915
+ } catch (error) {
1916
+ if (error.status === 404) return toolError("No encuentro esa tarjeta en tu cuenta.");
1917
+ return failure(error, "No pude revocar la tarjeta. Inténtalo de nuevo.");
1918
+ }
1919
+ };
1920
+ //#endregion
1921
+ //#region src/tools/orders.ts
1922
+ const IDEMPOTENCY = "agent_idempotency_key";
1923
+ const CONFIRMED = "agent_confirmed";
1924
+ const CURRENCY = /^[A-Z]{3}$/;
1925
+ const metaOf = (order) => {
1926
+ const meta = order.metadata;
1927
+ if (!meta || typeof meta !== "object" || Array.isArray(meta)) return {};
1928
+ return meta;
1929
+ };
1930
+ const isConfirmed = (order) => {
1931
+ return metaOf(order)[CONFIRMED] === "true";
1932
+ };
1933
+ const totalOf = (order) => {
1934
+ const total = order.totals?.total;
1935
+ const currency = order.totals?.currency;
1936
+ if (typeof total !== "number" || typeof currency !== "string") return null;
1937
+ if (!CURRENCY.test(currency)) return null;
1938
+ return {
1939
+ total: numberToDecimal(total),
1940
+ currency
1941
+ };
1942
+ };
1943
+ const summary = (order) => {
1944
+ const money = totalOf(order);
1945
+ if (!money) return null;
1946
+ const b1 = {
1947
+ order_id: order.id,
1948
+ confirmed: true
1949
+ };
1950
+ const b2 = { status: order.status ?? "OPEN" };
1951
+ const b3 = { payment_status: order.payment_status ?? "IDLE" };
1952
+ const b4 = {
1953
+ currency: money.currency,
1954
+ total: money.total
1955
+ };
1956
+ return {
1957
+ ...b1,
1958
+ ...b2,
1959
+ ...b3,
1960
+ ...b4
1961
+ };
1962
+ };
1963
+ const ask = async (order, idempotencyKey, secret) => {
1964
+ const money = totalOf(order);
1965
+ if (!money) return toolError("El pedido no tiene un total para confirmar.");
1966
+ const b1 = {
1967
+ order_id: order.id,
1968
+ total: money.total
1969
+ };
1970
+ const b2 = {
1971
+ currency: money.currency,
1972
+ idempotency_key: idempotencyKey
1973
+ };
1974
+ const sealed = await sealRequestState({
1975
+ ...b1,
1976
+ ...b2
1977
+ }, secret);
1978
+ return confirmTotalRequest(money.total, money.currency, sealed);
1979
+ };
1980
+ const currencyOf = async (args, ctx) => {
1981
+ const b1 = {
1982
+ store_id: args.store_id,
1983
+ channel_id: ctx.channelId
1984
+ };
1985
+ const b2 = { fulfillment_id: args.fulfillment_id };
1986
+ const brand = args.brand_id ? { brand_id: args.brand_id } : {};
1987
+ const scope = {
1988
+ ...b1,
1989
+ ...b2,
1990
+ ...brand
1991
+ };
1992
+ const code = (await services.preferences.get(scope, httpOf(ctx))).currency?.code?.trim().toUpperCase() ?? "";
1993
+ if (!CURRENCY.test(code)) return "";
1994
+ return code;
1995
+ };
1996
+ const httpOf = (ctx) => {
1997
+ return {
1998
+ baseUrl: ctx.apiUrl,
1999
+ accessToken: ctx.storefrontToken,
2000
+ fetchImpl: ctx.fetchImpl
2001
+ };
2002
+ };
2003
+ const findExisting = async (args, ctx) => {
2004
+ const filters = {
2005
+ channel_id: ctx.channelId,
2006
+ limit: 20
2007
+ };
2008
+ return (await services.orders.list(filters, httpOf(ctx))).find((order) => {
2009
+ return metaOf(order)[IDEMPOTENCY] === args.idempotency_key;
2010
+ });
2011
+ };
2012
+ const create = async (args, ctx, currency) => {
2013
+ const totalsIn = args.totals;
2014
+ const b1 = {
2015
+ currency,
2016
+ subtotal: decimalToNumber(totalsIn.subtotal)
2017
+ };
2018
+ const b2 = { discount_rate: totalsIn.discount_rate };
2019
+ const b3 = { discount_total: decimalToNumber(totalsIn.discount_total) };
2020
+ const b4 = { tax_rate: totalsIn.tax_rate };
2021
+ const b5 = { tax_total: decimalToNumber(totalsIn.tax_total) };
2022
+ const b6 = { total: decimalToNumber(totalsIn.total) };
2023
+ const totals = {
2024
+ ...b1,
2025
+ ...b2,
2026
+ ...b3,
2027
+ ...b4,
2028
+ ...b5,
2029
+ ...b6
2030
+ };
2031
+ const lines = args.lines.map(lineToApi);
2032
+ const brand = args.brand_id ?? null;
2033
+ const anon = args.is_anonymous ?? false;
2034
+ const meta = {
2035
+ [IDEMPOTENCY]: args.idempotency_key,
2036
+ [CONFIRMED]: "false"
2037
+ };
2038
+ const m1 = {
2039
+ idempotency_key: args.idempotency_key,
2040
+ ...meta
2041
+ };
2042
+ const c1 = {
2043
+ store_id: args.store_id,
2044
+ channel_id: ctx.channelId
2045
+ };
2046
+ const c2 = {
2047
+ fulfillment_id: args.fulfillment_id,
2048
+ brand_id: brand
2049
+ };
2050
+ const c3 = {
2051
+ is_anonymous: anon,
2052
+ lines,
2053
+ totals
2054
+ };
2055
+ const customer = { customer_info: args.customer };
2056
+ const id = genOrderId(args.store_id);
2057
+ const body = {
2058
+ ...c1,
2059
+ ...c2,
2060
+ ...c3,
2061
+ id,
2062
+ customer,
2063
+ metadata: m1
2064
+ };
2065
+ return await services.orders.post(body, httpOf(ctx));
2066
+ };
2067
+ const rejectMismatch = () => {
2068
+ return toolError("El total confirmado no coincide con el total del pedido.");
2069
+ };
2070
+ const confirm = async (args, ctx, round) => {
2071
+ const secret = ctx.linkSecret ?? "";
2072
+ if (!secret) return toolError("El canal Agent no puede confirmar todavía.");
2073
+ const opened = await openRequestState(round.requestState ?? "", secret);
2074
+ if (!opened?.order_id || opened.idempotency_key !== args.idempotency_key) return toolError("No pude verificar la confirmación. Empieza de nuevo.");
2075
+ const amount = confirmedAmount(round.inputResponses);
2076
+ if (!amount) return toolError("No confirmaste el total. El pedido sigue abierto, sin ir a pago.");
2077
+ const order = await services.orders.get(opened.order_id, httpOf(ctx));
2078
+ if (order.channel_id !== ctx.channelId) return toolError("No encuentro ese pedido en este canal.");
2079
+ const money = totalOf(order);
2080
+ if (!money || !opened.total || !opened.currency) return rejectMismatch();
2081
+ const sameOrder = decimalsEqual(amount, money.total);
2082
+ const sameSeal = decimalsEqual(amount, opened.total);
2083
+ const sameCurrency = money.currency === opened.currency;
2084
+ if (!sameOrder || !sameSeal || !sameCurrency) return rejectMismatch();
2085
+ if (isConfirmed(order)) {
2086
+ const done = summary(order);
2087
+ if (!done) return rejectMismatch();
2088
+ return toolOk(done);
2089
+ }
2090
+ const next = {
2091
+ ...metaOf(order),
2092
+ [CONFIRMED]: "true"
2093
+ };
2094
+ const patched = await services.orders.patch(order.id, { metadata: next }, httpOf(ctx));
2095
+ const done = summary(patched ?? order);
2096
+ if (!done) return rejectMismatch();
2097
+ return toolOk(done);
2098
+ };
2099
+ const executeCreateOrder = async (args, ctx, round = {}) => {
2100
+ const secret = ctx.linkSecret ?? "";
2101
+ if (!secret) return toolError("El canal Agent no puede confirmar todavía.");
2102
+ if (Boolean(round.inputResponses) || Boolean(round.requestState)) try {
2103
+ return await confirm(args, ctx, round);
2104
+ } catch (error) {
2105
+ return failure(error, "No pude confirmar el pedido. Inténtalo de nuevo.");
2106
+ }
2107
+ try {
2108
+ const existing = await findExisting(args, ctx);
2109
+ if (existing) {
2110
+ if (existing.channel_id !== ctx.channelId) return toolError("No encuentro ese pedido en este canal.");
2111
+ if (isConfirmed(existing)) {
2112
+ const done = summary(existing);
2113
+ if (!done) return toolError("El pedido no tiene un total para confirmar.");
2114
+ return toolOk(done);
2115
+ }
2116
+ return ask(existing, args.idempotency_key, secret);
2117
+ }
2118
+ const currency = await currencyOf(args, ctx);
2119
+ if (!currency) return toolError("Este comercio no tiene una moneda configurada.");
2120
+ const order = await create(args, ctx, currency);
2121
+ if (order.channel_id !== ctx.channelId) return toolError("No encuentro ese pedido en este canal.");
2122
+ return ask(order, args.idempotency_key, secret);
2123
+ } catch (error) {
2124
+ return failure(error, "No pude crear el pedido. Inténtalo de nuevo.");
2125
+ }
2126
+ };
2127
+ const COLOR = /^(#[0-9a-fA-F]{3,8}|rgba?\([^)]{1,40}\)|hsla?\([^)]{1,40}\))$/;
2128
+ const DAYS = [
2129
+ "sunday",
2130
+ "monday",
2131
+ "tuesday",
2132
+ "wednesday",
2133
+ "thursday",
2134
+ "friday",
2135
+ "saturday"
2136
+ ];
2137
+ const isRecord = (value) => {
2138
+ return !!value && typeof value === "object" && !Array.isArray(value);
2139
+ };
2140
+ const menuLocale = (value) => {
2141
+ const text = value?.trim().toLowerCase() ?? "";
2142
+ if (text.startsWith("en")) return "en";
2143
+ if (text.startsWith("pt")) return "pt";
2144
+ return "es";
2145
+ };
2146
+ const clampPage = (value) => {
2147
+ if (value === void 0 || !Number.isInteger(value)) return 24;
2148
+ if (value < 1) return 1;
2149
+ if (value > 24) return 24;
2150
+ return value;
2151
+ };
2152
+ const bytes = (value) => Buffer.from(value, "utf8").toString("base64url");
2153
+ const textOf$1 = (value) => {
2154
+ return Buffer.from(value, "base64url").toString("utf8");
2155
+ };
2156
+ const encodeHandle = (scope) => {
2157
+ const body = {
2158
+ v: 1,
2159
+ store_id: scope.store_id ?? null,
2160
+ fulfillment_id: scope.fulfillment_id ?? null,
2161
+ brand_id: scope.brand_id ?? null,
2162
+ menu_id: scope.menu_id ?? null
2163
+ };
2164
+ return bytes(JSON.stringify(body));
2165
+ };
2166
+ const decodeHandle = (handle) => {
2167
+ try {
2168
+ const parsed = JSON.parse(textOf$1(handle));
2169
+ if (parsed.v !== 1) return null;
2170
+ const scope = {};
2171
+ if (typeof parsed.store_id === "string") scope.store_id = parsed.store_id;
2172
+ if (typeof parsed.fulfillment_id === "string") scope.fulfillment_id = parsed.fulfillment_id;
2173
+ if (typeof parsed.brand_id === "string") scope.brand_id = parsed.brand_id;
2174
+ if (parsed.brand_id === null) scope.brand_id = null;
2175
+ if (typeof parsed.menu_id === "string") scope.menu_id = parsed.menu_id;
2176
+ return scope;
2177
+ } catch {
2178
+ return null;
2179
+ }
2180
+ };
2181
+ const encodeCursor = (offset) => {
2182
+ return bytes(JSON.stringify({ o: offset }));
2183
+ };
2184
+ const decodeCursor = (cursor) => {
2185
+ if (!cursor) return 0;
2186
+ try {
2187
+ const parsed = JSON.parse(textOf$1(cursor));
2188
+ if (typeof parsed.o !== "number" || !Number.isInteger(parsed.o)) return null;
2189
+ if (parsed.o < 0) return null;
2190
+ return parsed.o;
2191
+ } catch {
2192
+ return null;
2193
+ }
2194
+ };
2195
+ const labelOf = (value, locale) => {
2196
+ if (typeof value === "string") return value.trim();
2197
+ if (!isRecord(value)) return "";
2198
+ const direct = value[locale];
2199
+ if (typeof direct === "string" && direct.trim()) return direct.trim();
2200
+ const lower = locale.toLowerCase();
2201
+ for (const [key, text] of Object.entries(value)) {
2202
+ if (typeof text !== "string" || !text.trim()) continue;
2203
+ const name = key.toLowerCase();
2204
+ if (name === lower || name.startsWith(`${lower}-`)) return text.trim();
2205
+ if (name.replaceAll("_", "-") === lower) return text.trim();
2206
+ }
2207
+ for (const text of Object.values(value)) if (typeof text === "string" && text.trim()) return text.trim();
2208
+ return "";
2209
+ };
2210
+ const decimalOf = (value) => {
2211
+ if (typeof value === "string" && isDecimalString(value)) return value;
2212
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0) return numberToDecimal(value);
2213
+ return null;
2214
+ };
2215
+ const httpsUrl = (value) => {
2216
+ if (typeof value !== "string" || !value.startsWith("https://")) return null;
2217
+ try {
2218
+ const parsed = new URL(value);
2219
+ if (parsed.username || parsed.password) return null;
2220
+ return parsed.toString();
2221
+ } catch {
2222
+ return null;
2223
+ }
2224
+ };
2225
+ /** Supabase render URLs get a 320px cover thumbnail. Other CDNs stay as-is. */
2226
+ const thumbnailOf = (value) => {
2227
+ const url = httpsUrl(value);
2228
+ if (!url) return null;
2229
+ const parsed = new URL(url);
2230
+ if (!parsed.pathname.includes("/storage/v1/render/image/")) return url;
2231
+ if (!parsed.searchParams.has("width")) parsed.searchParams.set("width", "320");
2232
+ if (!parsed.searchParams.has("height")) parsed.searchParams.set("height", "320");
2233
+ if (!parsed.searchParams.has("resize")) parsed.searchParams.set("resize", "cover");
2234
+ return parsed.toString();
2235
+ };
2236
+ const colorOf = (value) => {
2237
+ if (typeof value !== "string") return null;
2238
+ const text = value.trim();
2239
+ if (!COLOR.test(text)) return null;
2240
+ return text;
2241
+ };
2242
+ const minutes = (time) => {
2243
+ const [hours = "0", mins = "0"] = time.split(":");
2244
+ return Number(hours) * 60 + Number(mins);
2245
+ };
2246
+ const covers = (period, now) => {
2247
+ if (!period.start_date || !period.end_date) return false;
2248
+ const start = Date.parse(period.start_date);
2249
+ const end = Date.parse(period.end_date);
2250
+ if (Number.isNaN(start) || Number.isNaN(end)) return false;
2251
+ const at = now.getTime();
2252
+ return start <= at && at <= end;
2253
+ };
2254
+ const inTime = (period, now) => {
2255
+ if (!period.start_time || !period.end_time) return false;
2256
+ const at = now.getHours() * 60 + now.getMinutes();
2257
+ return at >= minutes(period.start_time) && at < minutes(period.end_time);
2258
+ };
2259
+ const periodsActive = (periods, now) => {
2260
+ if (periods.length === 0) return false;
2261
+ const specific = periods.filter((period) => covers(period, now));
2262
+ const fallback = periods.filter((period) => !period.start_date || !period.end_date);
2263
+ if (specific.filter((period) => period.closed).some((period) => !period.start_time || inTime(period, now))) return false;
2264
+ const opens = specific.filter((period) => !period.closed);
2265
+ if (opens.length > 0) return opens.some((period) => inTime(period, now));
2266
+ if (fallback.some((period) => period.closed && inTime(period, now))) return false;
2267
+ const openFallback = fallback.filter((period) => !period.closed);
2268
+ if (openFallback.length === 0) return false;
2269
+ return openFallback.some((period) => inTime(period, now));
2270
+ };
2271
+ const scheduleActive = (value, now) => {
2272
+ if (value == null) return true;
2273
+ if (!Array.isArray(value) || value.length === 0) return false;
2274
+ const day = DAYS[now.getDay()];
2275
+ const entry = value.find((item) => {
2276
+ return isRecord(item) && item.day_of_week === day;
2277
+ });
2278
+ if (!isRecord(entry) || !Array.isArray(entry.periods)) return false;
2279
+ const periods = entry.periods.filter(isRecord);
2280
+ return periodsActive(periods, now);
2281
+ };
2282
+ const productAvailable = (product, now) => {
2283
+ const availability = isRecord(product.availability) ? product.availability : {};
2284
+ const status = availability.status;
2285
+ if (status === "HIDDEN" || status === "OUT_OF_STOCK") return false;
2286
+ const until = availability.out_of_stock_until;
2287
+ if (typeof until === "string" && Date.parse(until) > now.getTime()) return false;
2288
+ return scheduleActive(availability.schedules, now);
2289
+ };
2290
+ const categoryAvailable = (category, now) => {
2291
+ const availability = isRecord(category.availability) ? category.availability : {};
2292
+ const status = availability.status;
2293
+ if (status === "HIDDEN" || status === "INACTIVE") return false;
2294
+ const until = availability.inactive_until;
2295
+ if (typeof until === "string" && Date.parse(until) > now.getTime()) return false;
2296
+ return scheduleActive(availability.schedules, now);
2297
+ };
2298
+ const fold = (value) => {
2299
+ return value.normalize("NFD").replace(/\p{M}/gu, "").toLowerCase();
2300
+ };
2301
+ const cardOf = (product, locale) => {
2302
+ if (typeof product.id !== "string") return null;
2303
+ const pricing = isRecord(product.pricing) ? product.pricing : {};
2304
+ const price = decimalOf(pricing.price);
2305
+ if (!price) return null;
2306
+ const name = labelOf(product.name, locale) || product.id;
2307
+ return {
2308
+ id: product.id,
2309
+ name,
2310
+ description: labelOf(product.description, locale),
2311
+ price,
2312
+ anchor_price: decimalOf(pricing.anchor_price),
2313
+ thumbnail_url: thumbnailOf(product.image_url)
2314
+ };
2315
+ };
2316
+ const prepare = (menu, now, locale) => {
2317
+ if (!scheduleActive(menu.schedules, now)) return null;
2318
+ const rawProducts = Array.isArray(menu.products) ? menu.products : [];
2319
+ const products = /* @__PURE__ */ new Map();
2320
+ for (const item of rawProducts) {
2321
+ if (!isRecord(item) || typeof item.id !== "string") continue;
2322
+ if (!productAvailable(item, now)) continue;
2323
+ products.set(item.id, item);
2324
+ }
2325
+ const rawCategories = Array.isArray(menu.categories) ? menu.categories : [];
2326
+ const categories = [];
2327
+ for (const item of rawCategories) {
2328
+ if (!isRecord(item) || typeof item.id !== "string") continue;
2329
+ if (!categoryAvailable(item, now)) continue;
2330
+ const entries = Array.isArray(item.items) ? item.items : [];
2331
+ const product_ids = [];
2332
+ for (const entry of entries) {
2333
+ if (!isRecord(entry) || entry.type !== "PRODUCT") continue;
2334
+ if (typeof entry.id !== "string" || !products.has(entry.id)) continue;
2335
+ product_ids.push(entry.id);
2336
+ }
2337
+ if (product_ids.length === 0) continue;
2338
+ categories.push({
2339
+ id: item.id,
2340
+ name: labelOf(item.name, locale) || item.id,
2341
+ image_url: thumbnailOf(item.image_url),
2342
+ product_ids
2343
+ });
2344
+ }
2345
+ if (categories.length === 0) return null;
2346
+ return {
2347
+ menu,
2348
+ products,
2349
+ categories
2350
+ };
2351
+ };
2352
+ const brandingOf = (store, menu, locale, fallback) => {
2353
+ const meta = isRecord(store?.metadata) ? store.metadata : {};
2354
+ const menuMeta = isRecord(menu.metadata) ? menu.metadata : {};
2355
+ return {
2356
+ name: labelOf(store?.name, locale) || labelOf(menu.name, locale) || fallback,
2357
+ logo_url: httpsUrl(meta.logo_url) || httpsUrl(store?.image_url) || httpsUrl(menuMeta.logo_url),
2358
+ primary: colorOf(meta.primary_color) || colorOf(menuMeta.primary_color),
2359
+ background: colorOf(meta.background_color) || colorOf(menuMeta.background_color),
2360
+ foreground: colorOf(meta.foreground_color) || colorOf(menuMeta.foreground_color)
2361
+ };
2362
+ };
2363
+ const pickMenu = (source, now, locale) => {
2364
+ const ready = [];
2365
+ for (const item of source.menus) {
2366
+ if (!isRecord(item)) continue;
2367
+ const prepared = prepare(item, now, locale);
2368
+ if (prepared) ready.push(prepared);
2369
+ }
2370
+ if (ready.length === 0) return null;
2371
+ const wanted = source.scope.menu_id;
2372
+ if (!wanted) return ready[0] ?? null;
2373
+ return ready.find((item) => item.menu.id === wanted) ?? ready[0] ?? null;
2374
+ };
2375
+ const pageOf = (ids, products, offset, limit, locale) => {
2376
+ const slice = ids.slice(offset, offset + limit);
2377
+ const cards = [];
2378
+ for (const id of slice) {
2379
+ const product = products.get(id);
2380
+ if (!product) continue;
2381
+ const card = cardOf(product, locale);
2382
+ if (card) cards.push(card);
2383
+ }
2384
+ return {
2385
+ cards,
2386
+ next: offset + limit < ids.length ? encodeCursor(offset + limit) : null,
2387
+ total: ids.length
2388
+ };
2389
+ };
2390
+ const projectMenu = (source, input) => {
2391
+ const now = source.now ?? /* @__PURE__ */ new Date();
2392
+ const locale = menuLocale(source.locale);
2393
+ const prepared = pickMenu(source, now, locale);
2394
+ if (!prepared) return { error: "No hay un menú disponible ahora." };
2395
+ const offset = decodeCursor(input.cursor);
2396
+ if (offset === null) return { error: "Ese cursor no es válido." };
2397
+ const menuId = typeof prepared.menu.id === "string" ? prepared.menu.id : "";
2398
+ const scope = {
2399
+ ...source.scope,
2400
+ menu_id: menuId
2401
+ };
2402
+ const handle = encodeHandle(scope);
2403
+ const storeId = typeof source.store?.id === "string" && source.store.id || source.scope.store_id || "";
2404
+ const storeName = labelOf(source.store?.name, locale);
2405
+ const branding = brandingOf(source.store, prepared.menu, locale, storeName);
2406
+ const categories = prepared.categories.map((category) => {
2407
+ return {
2408
+ id: category.id,
2409
+ name: category.name,
2410
+ image_url: category.image_url,
2411
+ product_count: category.product_ids.length
2412
+ };
2413
+ });
2414
+ const limit = clampPage(input.limit);
2415
+ if (input.mode === "search") {
2416
+ const query = input.query?.trim() ?? "";
2417
+ const needle = fold(query);
2418
+ const ids = [];
2419
+ for (const category of prepared.categories) for (const id of category.product_ids) {
2420
+ if (ids.includes(id)) continue;
2421
+ const product = prepared.products.get(id);
2422
+ if (!product) continue;
2423
+ const card = cardOf(product, locale);
2424
+ if (!card) continue;
2425
+ if (fold(`${card.name} ${card.description}`).includes(needle)) ids.push(id);
2426
+ }
2427
+ const page = pageOf(ids, prepared.products, offset, limit, locale);
2428
+ const b1 = {
2429
+ mode: "search",
2430
+ handle,
2431
+ locale
2432
+ };
2433
+ const b2 = {
2434
+ store: {
2435
+ id: storeId,
2436
+ name: branding.name
2437
+ },
2438
+ branding
2439
+ };
2440
+ const b3 = {
2441
+ categories,
2442
+ category_id: null,
2443
+ products: page.cards
2444
+ };
2445
+ const b4 = {
2446
+ next_cursor: page.next,
2447
+ query
2448
+ };
2449
+ const b5 = { page: {
2450
+ offset,
2451
+ limit,
2452
+ total: page.total
2453
+ } };
2454
+ return {
2455
+ ...b1,
2456
+ ...b2,
2457
+ ...b3,
2458
+ ...b4,
2459
+ ...b5
2460
+ };
2461
+ }
2462
+ const selected = prepared.categories.find((item) => item.id === input.categoryId) ?? prepared.categories[0];
2463
+ if (!selected) return { error: "No hay un menú disponible ahora." };
2464
+ const page = pageOf(selected.product_ids, prepared.products, offset, limit, locale);
2465
+ const b1 = {
2466
+ mode: "browse",
2467
+ handle,
2468
+ locale
2469
+ };
2470
+ const b2 = {
2471
+ store: {
2472
+ id: storeId,
2473
+ name: branding.name
2474
+ },
2475
+ branding
2476
+ };
2477
+ const b3 = {
2478
+ categories,
2479
+ category_id: selected.id,
2480
+ products: page.cards
2481
+ };
2482
+ const b4 = {
2483
+ next_cursor: page.next,
2484
+ query: null
2485
+ };
2486
+ const b5 = { page: {
2487
+ offset,
2488
+ limit,
2489
+ total: page.total
2490
+ } };
2491
+ return {
2492
+ ...b1,
2493
+ ...b2,
2494
+ ...b3,
2495
+ ...b4,
2496
+ ...b5
2497
+ };
2498
+ };
2499
+ const groupOf = (menu, product, products, locale) => {
2500
+ const pricing = isRecord(product.pricing) ? product.pricing : {};
2501
+ const groupIds = Array.isArray(pricing.modifier_group_ids) ? pricing.modifier_group_ids.filter((id) => typeof id === "string") : [];
2502
+ const rawGroups = Array.isArray(menu.modifier_groups) ? menu.modifier_groups : [];
2503
+ const groups = [];
2504
+ for (const id of groupIds) {
2505
+ const raw = rawGroups.find((item) => isRecord(item) && item.id === id);
2506
+ if (!isRecord(raw) || !Array.isArray(raw.modifier_ids)) continue;
2507
+ const minimum = typeof raw.minimum_quantity === "number" ? raw.minimum_quantity : 0;
2508
+ const maximum = typeof raw.maximum_quantity === "number" ? raw.maximum_quantity : 1;
2509
+ const options = [];
2510
+ for (const modifierId of raw.modifier_ids) {
2511
+ if (typeof modifierId !== "string") continue;
2512
+ const modifier = products.get(modifierId);
2513
+ if (!modifier) continue;
2514
+ const own = isRecord(modifier.pricing) ? modifier.pricing : {};
2515
+ const entry = (Array.isArray(own.modifiers) ? own.modifiers : []).find((item) => {
2516
+ return isRecord(item) && item.modifier_group_id === id;
2517
+ });
2518
+ const listedPrice = isRecord(entry) ? entry.price : null;
2519
+ const price = decimalOf(listedPrice ?? own.price);
2520
+ if (!price) continue;
2521
+ const max = isRecord(entry) ? entry.maximum_quantity : null;
2522
+ const min = isRecord(entry) ? entry.minimum_quantity : 0;
2523
+ options.push({
2524
+ id: modifierId,
2525
+ name: labelOf(modifier.name, locale) || modifierId,
2526
+ price,
2527
+ thumbnail_url: thumbnailOf(isRecord(entry) && entry.image_url || modifier.image_url),
2528
+ minimum: typeof min === "number" ? min : 0,
2529
+ maximum: typeof max === "number" ? max : null
2530
+ });
2531
+ }
2532
+ if (options.length === 0) continue;
2533
+ groups.push({
2534
+ id,
2535
+ title: labelOf(raw.title, locale) || id,
2536
+ minimum,
2537
+ maximum,
2538
+ required: minimum > 0,
2539
+ options
2540
+ });
2541
+ }
2542
+ return groups;
2543
+ };
2544
+ const projectProduct = (source, productId) => {
2545
+ const now = source.now ?? /* @__PURE__ */ new Date();
2546
+ const locale = menuLocale(source.locale);
2547
+ const prepared = pickMenu(source, now, locale);
2548
+ if (!prepared) return { error: "No hay un menú disponible ahora." };
2549
+ const product = prepared.products.get(productId);
2550
+ if (!product) return { error: "No encuentro ese producto en este menú." };
2551
+ const card = cardOf(product, locale);
2552
+ if (!card) return { error: "No encuentro ese producto en este menú." };
2553
+ const menuId = typeof prepared.menu.id === "string" ? prepared.menu.id : "";
2554
+ const handle = encodeHandle({
2555
+ ...source.scope,
2556
+ menu_id: menuId
2557
+ });
2558
+ const branding = brandingOf(source.store, prepared.menu, locale, labelOf(source.store?.name, locale));
2559
+ const storeId = typeof source.store?.id === "string" && source.store.id || source.scope.store_id || "";
2560
+ const fulfillment = source.scope.fulfillment_id ?? "";
2561
+ const groups = groupOf(prepared.menu, product, prepared.products, locale);
2562
+ const b1 = {
2563
+ handle,
2564
+ locale,
2565
+ store_id: storeId,
2566
+ fulfillment_id: fulfillment
2567
+ };
2568
+ const b2 = {
2569
+ brand_id: source.scope.brand_id ?? null,
2570
+ branding
2571
+ };
2572
+ const detail = {
2573
+ id: card.id,
2574
+ name: card.name,
2575
+ description: card.description,
2576
+ price: card.price,
2577
+ anchor_price: card.anchor_price,
2578
+ image_url: thumbnailOf(product.image_url),
2579
+ groups
2580
+ };
2581
+ return {
2582
+ ...b1,
2583
+ ...b2,
2584
+ product: detail
2585
+ };
2586
+ };
2587
+ /** Compact model text: ids, names and decimal prices. No image URLs. */
2588
+ const compactMenu = (view) => {
2589
+ const categories = view.categories.map((category) => {
2590
+ return {
2591
+ id: category.id,
2592
+ name: category.name,
2593
+ product_count: category.product_count
2594
+ };
2595
+ });
2596
+ const products = view.products.map((product) => {
2597
+ return {
2598
+ id: product.id,
2599
+ name: product.name,
2600
+ price: product.price
2601
+ };
2602
+ });
2603
+ const b1 = {
2604
+ handle: view.handle,
2605
+ store: view.store,
2606
+ categories
2607
+ };
2608
+ const b2 = {
2609
+ category_id: view.category_id,
2610
+ products
2611
+ };
2612
+ const b3 = {
2613
+ next_cursor: view.next_cursor,
2614
+ page: view.page,
2615
+ query: view.query
2616
+ };
2617
+ return {
2618
+ ...b1,
2619
+ ...b2,
2620
+ ...b3
2621
+ };
2622
+ };
2623
+ const compactProduct = (view) => {
2624
+ const groups = view.product.groups.map((group) => {
2625
+ return {
2626
+ id: group.id,
2627
+ title: group.title,
2628
+ minimum: group.minimum,
2629
+ maximum: group.maximum,
2630
+ options: group.options.map((option) => {
2631
+ return {
2632
+ id: option.id,
2633
+ name: option.name,
2634
+ price: option.price
2635
+ };
2636
+ })
2637
+ };
2638
+ });
2639
+ const b1 = {
2640
+ handle: view.handle,
2641
+ store_id: view.store_id
2642
+ };
2643
+ const b2 = {
2644
+ fulfillment_id: view.fulfillment_id,
2645
+ product: view.product.id
2646
+ };
2647
+ const b3 = {
2648
+ name: view.product.name,
2649
+ price: view.product.price,
2650
+ groups
2651
+ };
2652
+ return {
2653
+ ...b1,
2654
+ ...b2,
2655
+ ...b3
2656
+ };
2657
+ };
2658
+ //#endregion
2659
+ //#region src/tools/menu.run.ts
2660
+ const scopeOf = (args) => {
2661
+ const decoded = args.handle ? decodeHandle(args.handle) : {};
2662
+ if (!decoded) return { error: "Ese identificador de menú no es válido." };
2663
+ return {
2664
+ store_id: args.store_id ?? decoded.store_id,
2665
+ fulfillment_id: args.fulfillment_id ?? decoded.fulfillment_id,
2666
+ brand_id: args.brand_id ?? decoded.brand_id,
2667
+ menu_id: decoded.menu_id
2668
+ };
2669
+ };
2670
+ const sourceOf = async (scope, ctx, locale) => {
2671
+ return {
2672
+ ...await loadMenus(scope, ctx),
2673
+ scope,
2674
+ locale
2675
+ };
2676
+ };
2677
+ const executeGetMenu = async (args, ctx) => {
2678
+ try {
2679
+ const scope = {
2680
+ store_id: args.store_id,
2681
+ fulfillment_id: args.fulfillment_id,
2682
+ brand_id: args.brand_id
2683
+ };
2684
+ const view = projectMenu(await sourceOf(scope, ctx, args.locale), {
2685
+ mode: "browse",
2686
+ categoryId: args.category_id,
2687
+ cursor: args.cursor,
2688
+ limit: args.limit
2689
+ });
2690
+ if ("error" in view) return toolError(view.error);
2691
+ return toolView(compactMenu(view), { view });
2692
+ } catch (error) {
2693
+ return failure(error, "No pude leer el menú. Inténtalo de nuevo.");
2694
+ }
2695
+ };
2696
+ const executeGetMenuCategory = async (args, ctx) => {
2697
+ const scope = scopeOf({ handle: args.handle });
2698
+ if ("error" in scope) return toolError(scope.error);
2699
+ try {
2700
+ const view = projectMenu(await sourceOf(scope, ctx), {
2701
+ mode: "browse",
2702
+ categoryId: args.category_id,
2703
+ cursor: args.cursor,
2704
+ limit: args.limit
2705
+ });
2706
+ if ("error" in view) return toolError(view.error);
2707
+ return toolView(compactMenu(view), { view });
2708
+ } catch (error) {
2709
+ return failure(error, "No pude leer esa categoría. Inténtalo de nuevo.");
2710
+ }
2711
+ };
2712
+ const executeSearchMenu = async (args, ctx) => {
2713
+ const scope = scopeOf(args);
2714
+ if ("error" in scope) return toolError(scope.error);
2715
+ try {
2716
+ const view = projectMenu(await sourceOf(scope, ctx, args.locale), {
2717
+ mode: "search",
2718
+ query: args.query,
2719
+ cursor: args.cursor,
2720
+ limit: args.limit
2721
+ });
2722
+ if ("error" in view) return toolError(view.error);
2723
+ return toolView(compactMenu(view), { view });
2724
+ } catch (error) {
2725
+ return failure(error, "No pude buscar en el menú. Inténtalo de nuevo.");
2726
+ }
2727
+ };
2728
+ const executeGetProduct = async (args, ctx) => {
2729
+ const scope = scopeOf(args);
2730
+ if ("error" in scope) return toolError(scope.error);
2731
+ try {
2732
+ const view = projectProduct(await sourceOf(scope, ctx, args.locale), args.product_id);
2733
+ if ("error" in view) return toolError(view.error);
2734
+ return toolView(compactProduct(view), { view });
2735
+ } catch (error) {
2736
+ return failure(error, "No pude leer el producto. Inténtalo de nuevo.");
2737
+ }
2738
+ };
2739
+ //#endregion
2740
+ //#region src/tools/register.ts
2741
+ const isFail = (value) => {
2742
+ return "isError" in value;
2743
+ };
2744
+ const merchantOf = (request) => {
2745
+ if (!request) return "";
2746
+ const match = new URL(request.url).pathname.match(/\/m\/([^/]+)\/mcp/);
2747
+ if (!match?.[1]) return "";
2748
+ return decodeURIComponent(match[1]);
2749
+ };
2750
+ const domainsOf = (runtime, request) => {
2751
+ const merchantId = merchantOf(request);
2752
+ return (runtime.imageDomains?.(merchantId) ?? []).filter(isImageOrigin);
2753
+ };
2754
+ const cspOf = (domains) => {
2755
+ return {
2756
+ connectDomains: [],
2757
+ resourceDomains: [...domains],
2758
+ frameDomains: []
2759
+ };
2760
+ };
2761
+ const FALLBACK = "<!doctype html><html><body><p>Esta vista no está compilada.</p></body></html>";
2762
+ const registerAgentUi = (server, runtime, ready) => {
2763
+ const readOnly = { readOnlyHint: true };
2764
+ const cartAnn = {
2765
+ readOnlyHint: false,
2766
+ destructiveHint: false
2767
+ };
2768
+ const widgets = runtime.widgets;
2769
+ const html = {
2770
+ menu: widgets?.menu || FALLBACK,
2771
+ product: widgets?.product || FALLBACK,
2772
+ cart: widgets?.cart || FALLBACK
2773
+ };
2774
+ const read = (name) => {
2775
+ return async (uri, ctx) => {
2776
+ const domains = domainsOf(runtime, ctx.http?.req);
2777
+ const ui = {
2778
+ csp: cspOf(domains),
2779
+ prefersBorder: true
2780
+ };
2781
+ return { contents: [{
2782
+ uri: uri.href,
2783
+ mimeType: RESOURCE_MIME_TYPE,
2784
+ text: html[name],
2785
+ _meta: { ui }
2786
+ }] };
2787
+ };
2788
+ };
2789
+ const listed = cspOf(domainsOf(runtime, void 0));
2790
+ const resource = (title) => {
2791
+ return {
2792
+ title,
2793
+ _meta: { ui: {
2794
+ csp: listed,
2795
+ prefersBorder: true
2796
+ } }
2797
+ };
2798
+ };
2799
+ registerAppResource(server, "menu", UI_MENU, resource("Menú"), read("menu"));
2800
+ registerAppResource(server, "product", UI_PRODUCT, resource("Producto"), read("product"));
2801
+ registerAppResource(server, "cart", UI_CART, resource("Carrito"), read("cart"));
2802
+ const menuScope = requireToolScope(TOOL_SCOPES.get_menu);
2803
+ const menuOpts = {
2804
+ title: "Get menu",
2805
+ description: `Trae la tienda, las categorías y la primera página del menú. No envía el menú completo. Las imágenes van solo en la vista.`,
2806
+ inputSchema: getMenuSchema,
2807
+ annotations: readOnly,
2808
+ _meta: uiMeta(UI_MENU, ["model", "app"]),
2809
+ scopeChallenge: menuScope
2810
+ };
2811
+ const menuRun = async (args, ctx) => {
2812
+ const readyCtx = await ready(ctx);
2813
+ if (isFail(readyCtx)) return readyCtx;
2814
+ return executeGetMenu(args, readyCtx);
2815
+ };
2816
+ const add = (name, config, run) => {
2817
+ server.registerTool(name, config, run);
2818
+ };
2819
+ const menuMeta = {
2820
+ ...menuOpts._meta,
2821
+ "ui/resourceUri": UI_MENU
2822
+ };
2823
+ add("get_menu", {
2824
+ ...menuOpts,
2825
+ _meta: menuMeta
2826
+ }, menuRun);
2827
+ const pageScope = requireToolScope(TOOL_SCOPES.get_menu_category);
2828
+ const pageOpts = {
2829
+ title: "Get menu category",
2830
+ description: "Página de una categoría. Solo la vista la llama, no el modelo.",
2831
+ inputSchema: getMenuCategorySchema,
2832
+ annotations: readOnly,
2833
+ _meta: uiMeta(UI_MENU, ["app"]),
2834
+ scopeChallenge: pageScope
2835
+ };
2836
+ const pageRun = async (args, ctx) => {
2837
+ const readyCtx = await ready(ctx);
2838
+ if (isFail(readyCtx)) return readyCtx;
2839
+ return executeGetMenuCategory(args, readyCtx);
2840
+ };
2841
+ const pageMeta = {
2842
+ ...pageOpts._meta,
2843
+ "ui/resourceUri": UI_MENU
2844
+ };
2845
+ add("get_menu_category", {
2846
+ ...pageOpts,
2847
+ _meta: pageMeta
2848
+ }, pageRun);
2849
+ const searchScope = requireToolScope(TOOL_SCOPES.search_menu);
2850
+ const searchOpts = {
2851
+ title: "Search menu",
2852
+ description: `Busca productos por nombre. Úsala cuando el cliente pide algo, por ejemplo pollo. No devuelve el menú completo.`,
2853
+ inputSchema: searchMenuSchema,
2854
+ annotations: readOnly,
2855
+ _meta: uiMeta(UI_MENU, ["model", "app"]),
2856
+ scopeChallenge: searchScope
2857
+ };
2858
+ const searchRun = async (args, ctx) => {
2859
+ const readyCtx = await ready(ctx);
2860
+ if (isFail(readyCtx)) return readyCtx;
2861
+ return executeSearchMenu(args, readyCtx);
2862
+ };
2863
+ const searchMeta = {
2864
+ ...searchOpts._meta,
2865
+ "ui/resourceUri": UI_MENU
2866
+ };
2867
+ add("search_menu", {
2868
+ ...searchOpts,
2869
+ _meta: searchMeta
2870
+ }, searchRun);
2871
+ const productScope = requireToolScope(TOOL_SCOPES.get_product);
2872
+ const productOpts = {
2873
+ title: "Get product",
2874
+ description: `Detalle de un producto con modificadores, mínimos y precios. Agregar arma el carrito. No pide datos de tarjeta.`,
2875
+ inputSchema: getProductSchema,
2876
+ annotations: readOnly,
2877
+ _meta: uiMeta(UI_PRODUCT, ["model", "app"]),
2878
+ scopeChallenge: productScope
2879
+ };
2880
+ const productRun = async (args, ctx) => {
2881
+ const readyCtx = await ready(ctx);
2882
+ if (isFail(readyCtx)) return readyCtx;
2883
+ return executeGetProduct(args, readyCtx);
2884
+ };
2885
+ const productMeta = {
2886
+ ...productOpts._meta,
2887
+ "ui/resourceUri": UI_PRODUCT
2888
+ };
2889
+ add("get_product", {
2890
+ ...productOpts,
2891
+ _meta: productMeta
2892
+ }, productRun);
2893
+ const cartScope = requireToolScope(TOOL_SCOPES.build_cart);
2894
+ const cartOpts = {
2895
+ title: "Build cart",
2896
+ description: `Arma el carrito. Con product_id agrega ese producto. El order_id es el identificador que usas después. No cobra.`,
2897
+ inputSchema: buildCartSchema,
2898
+ annotations: cartAnn,
2899
+ _meta: uiMeta(UI_CART, ["model", "app"]),
2900
+ scopeChallenge: cartScope
2901
+ };
2902
+ const cartRun = async (args, ctx) => {
2903
+ const readyCtx = await ready(ctx);
2904
+ if (isFail(readyCtx)) return readyCtx;
2905
+ return executeBuildCart(args, readyCtx);
2906
+ };
2907
+ const cartMeta = {
2908
+ ...cartOpts._meta,
2909
+ "ui/resourceUri": UI_CART
2910
+ };
2911
+ add("build_cart", {
2912
+ ...cartOpts,
2913
+ _meta: cartMeta
2914
+ }, cartRun);
2915
+ const valScope = requireToolScope(TOOL_SCOPES.validate_cart);
2916
+ const valOpts = {
2917
+ title: "Validate cart",
2918
+ description: "Revisa el carrito contra el menú y los totales, sin crear el pedido.",
2919
+ inputSchema: validateCartSchema,
2920
+ annotations: readOnly,
2921
+ _meta: uiMeta(UI_CART, ["model", "app"]),
2922
+ scopeChallenge: valScope
2923
+ };
2924
+ const valRun = async (args, ctx) => {
2925
+ const readyCtx = await ready(ctx);
2926
+ if (isFail(readyCtx)) return readyCtx;
2927
+ return executeValidateCart(args, readyCtx);
2928
+ };
2929
+ const valMeta = {
2930
+ ...valOpts._meta,
2931
+ "ui/resourceUri": UI_CART
2932
+ };
2933
+ add("validate_cart", {
2934
+ ...valOpts,
2935
+ _meta: valMeta
2936
+ }, valRun);
2937
+ };
2938
+ //#endregion
2939
+ //#region src/handler.ts
2940
+ const INSTRUCTIONS = [
2941
+ "Ayudas al cliente a mirar tiendas y menú, armar un carrito y crear el pedido.",
2942
+ "Antes de pagar pides confirmación del total.",
2943
+ "El pago es un enlace de un solo uso a la página de este canal.",
2944
+ "Puedes listar tarjetas guardadas, cobrar una con confirmación del total y revocarla.",
2945
+ "Si la pasarela pide 3DS, devuelves el enlace de la página de pago.",
2946
+ "No pides número de tarjeta, CVV ni un token de pasarela.",
2947
+ "Los montos van en texto decimal, sin redondear.",
2948
+ "La moneda la pone el comercio, no el carrito.",
2949
+ "El menú, el producto y el carrito también se muestran en una vista.",
2950
+ "Pagar abre el enlace de pago. No pidas el número de tarjeta."
2951
+ ].join(" ");
2952
+ const rpcError = (status, code, message) => {
2953
+ const body = {
2954
+ jsonrpc: "2.0",
2955
+ id: null,
2956
+ error: {
2957
+ code,
2958
+ message
2959
+ }
2960
+ };
2961
+ return Response.json(body, { status });
2962
+ };
2963
+ const agentResourceUrl = (request, merchantId) => {
2964
+ return `${getPublicOrigin(request)}/m/${encodeURIComponent(merchantId)}/mcp`;
2965
+ };
2966
+ const agentMetadataPath = (merchantId) => {
2967
+ return `/.well-known/oauth-protected-resource/m/${encodeURIComponent(merchantId)}/mcp`;
2968
+ };
2969
+ const toolFail = (text) => {
2970
+ return {
2971
+ content: [{
2972
+ type: "text",
2973
+ text
2974
+ }],
2975
+ isError: true
2976
+ };
2977
+ };
2978
+ const createAgentMcpHandler = (runtime) => {
2979
+ const register = (server) => {
2980
+ const readyFor = async (ctx) => {
2981
+ return readyContext(ctx.http?.authInfo, ctx.http?.req);
2982
+ };
2983
+ registerAgentUi(server, runtime, readyFor);
2984
+ const readOnly = { readOnlyHint: true };
2985
+ const cartAnn = {
2986
+ readOnlyHint: false,
2987
+ destructiveHint: false
2988
+ };
2989
+ const listB1 = {
2990
+ title: "List stores",
2991
+ description: `Lista las tiendas activas de este comercio. Si envías latitud y longitud, te devuelvo las más cercanas.`
2992
+ };
2993
+ const listB2 = {
2994
+ inputSchema: listStoresSchema,
2995
+ annotations: readOnly
2996
+ };
2997
+ const listScope = requireToolScope(TOOL_SCOPES.list_stores);
2998
+ const listOpts = {
2999
+ ...listB1,
3000
+ ...listB2,
3001
+ scopeChallenge: listScope
3002
+ };
3003
+ const listRun = async (args, ctx) => {
3004
+ const ready = await readyContext(ctx.http?.authInfo);
3005
+ if ("isError" in ready) return ready;
3006
+ return executeListStores(args, ready);
3007
+ };
3008
+ server.registerTool("list_stores", listOpts, listRun);
3009
+ const statusB1 = {
3010
+ title: "Get order status",
3011
+ description: "Consulta el estado de un pedido de este canal."
3012
+ };
3013
+ const statusB2 = {
3014
+ inputSchema: orderStatusSchema,
3015
+ annotations: readOnly
3016
+ };
3017
+ const statusScope = requireToolScope(TOOL_SCOPES.get_order_status);
3018
+ const statusOpts = {
3019
+ ...statusB1,
3020
+ ...statusB2,
3021
+ scopeChallenge: statusScope
3022
+ };
3023
+ const statusRun = async (args, ctx) => {
3024
+ const ready = await readyContext(ctx.http?.authInfo);
3025
+ if ("isError" in ready) return ready;
3026
+ return executeOrderStatus(args, ready);
3027
+ };
3028
+ server.registerTool("get_order_status", statusOpts, statusRun);
3029
+ const orderB1 = {
3030
+ title: "Create order",
3031
+ description: `Crea el pedido en este canal y pide confirmar el total. No cobra. Requiere idempotency_key.`
3032
+ };
3033
+ const orderB2 = {
3034
+ inputSchema: createOrderSchema,
3035
+ annotations: cartAnn
3036
+ };
3037
+ const orderScope = requireToolScope(TOOL_SCOPES.create_order);
3038
+ const orderOpts = {
3039
+ ...orderB1,
3040
+ ...orderB2,
3041
+ scopeChallenge: orderScope
3042
+ };
3043
+ const orderRun = async (args, ctx) => {
3044
+ const ready = await readyContext(ctx.http?.authInfo, ctx.http?.req);
3045
+ if ("isError" in ready) return ready;
3046
+ return executeCreateOrder(args, ready, {
3047
+ inputResponses: ctx.mcpReq?.inputResponses,
3048
+ requestState: stateOf(ctx)
3049
+ });
3050
+ };
3051
+ server.registerTool("create_order", orderOpts, orderRun);
3052
+ const payB1 = {
3053
+ title: "Start payment",
3054
+ description: `Devuelve un enlace de un solo uso para pagar el pedido. La página muestra solo los métodos de este comercio.`
3055
+ };
3056
+ const payB2 = {
3057
+ inputSchema: startPaymentSchema,
3058
+ annotations: cartAnn
3059
+ };
3060
+ const payScope = requireToolScope(TOOL_SCOPES.start_payment);
3061
+ const payOpts = {
3062
+ ...payB1,
3063
+ ...payB2,
3064
+ scopeChallenge: payScope
3065
+ };
3066
+ const payRun = async (args, ctx) => {
3067
+ const ready = await readyContext(ctx.http?.authInfo, ctx.http?.req);
3068
+ if ("isError" in ready) return ready;
3069
+ return executeStartPayment(args, ready);
3070
+ };
3071
+ server.registerTool("start_payment", payOpts, payRun);
3072
+ const cardsDesc = "Lista las tarjetas guardadas de este cliente. ";
3073
+ const cardsDesc2 = "Solo marca, últimos 4 y vencimiento.";
3074
+ const cardsB1 = {
3075
+ title: "List saved cards",
3076
+ description: cardsDesc
3077
+ };
3078
+ const cardsB2 = { description: `${cardsDesc}${cardsDesc2}` };
3079
+ const cardsB3 = {
3080
+ inputSchema: listSavedCardsSchema,
3081
+ annotations: readOnly
3082
+ };
3083
+ const cardsScope = requireToolScope(TOOL_SCOPES.list_saved_cards);
3084
+ const cardsOpts = {
3085
+ ...cardsB1,
3086
+ ...cardsB2,
3087
+ ...cardsB3,
3088
+ scopeChallenge: cardsScope
3089
+ };
3090
+ const cardsRun = async (_args, ctx) => {
3091
+ const ready = await readyContext(ctx.http?.authInfo, ctx.http?.req);
3092
+ if ("isError" in ready) return ready;
3093
+ return executeListSavedCards({}, ready);
3094
+ };
3095
+ server.registerTool("list_saved_cards", cardsOpts, cardsRun);
3096
+ const chargeD1 = "Cobra una tarjeta guardada en la pasarela del comercio. ";
3097
+ const chargeD2 = "Pide confirmación del total. Si hay 3DS, devuelve el enlace.";
3098
+ const chargeAnn = {
3099
+ readOnlyHint: false,
3100
+ destructiveHint: true
3101
+ };
3102
+ const chargeB1 = { title: "Charge saved card" };
3103
+ const chargeB2 = { description: `${chargeD1}${chargeD2}` };
3104
+ const chargeB3 = {
3105
+ inputSchema: chargeSavedCardSchema,
3106
+ annotations: chargeAnn
3107
+ };
3108
+ const chargeScope = requireToolScope(TOOL_SCOPES.charge_saved_card);
3109
+ const chargeReady = {
3110
+ ...chargeB1,
3111
+ ...chargeB2,
3112
+ ...chargeB3,
3113
+ scopeChallenge: chargeScope
3114
+ };
3115
+ const chargeRun = async (args, ctx) => {
3116
+ const ready = await readyContext(ctx.http?.authInfo, ctx.http?.req);
3117
+ if ("isError" in ready) return ready;
3118
+ return executeChargeSavedCard(args, ready, {
3119
+ inputResponses: ctx.mcpReq?.inputResponses,
3120
+ requestState: stateOf(ctx)
3121
+ });
3122
+ };
3123
+ server.registerTool("charge_saved_card", chargeReady, chargeRun);
3124
+ const consentD1 = "Pide consentimiento y devuelve el enlace para guardar ";
3125
+ const consentD2 = "la tarjeta en la pasarela. No recibe el número.";
3126
+ const consentB1 = { title: "Save card consent" };
3127
+ const consentB2 = { description: `${consentD1}${consentD2}` };
3128
+ const consentB3 = {
3129
+ inputSchema: saveCardConsentSchema,
3130
+ annotations: cartAnn
3131
+ };
3132
+ const consentScope = requireToolScope(TOOL_SCOPES.save_card_consent);
3133
+ const consentReady = {
3134
+ ...consentB1,
3135
+ ...consentB2,
3136
+ ...consentB3,
3137
+ scopeChallenge: consentScope
3138
+ };
3139
+ const consentRun = async (args, ctx) => {
3140
+ const ready = await readyContext(ctx.http?.authInfo, ctx.http?.req);
3141
+ if ("isError" in ready) return ready;
3142
+ return executeSaveCardConsent(args, ready, {
3143
+ inputResponses: ctx.mcpReq?.inputResponses,
3144
+ requestState: stateOf(ctx)
3145
+ });
3146
+ };
3147
+ server.registerTool("save_card_consent", consentReady, consentRun);
3148
+ const revokeD1 = "Revoca una tarjeta guardada en la pasarela y aquí.";
3149
+ const revokeAnn = {
3150
+ readOnlyHint: false,
3151
+ destructiveHint: true
3152
+ };
3153
+ const revokeB1 = {
3154
+ title: "Revoke saved card",
3155
+ description: revokeD1
3156
+ };
3157
+ const revokeB2 = {
3158
+ inputSchema: revokeSavedCardSchema,
3159
+ annotations: revokeAnn
3160
+ };
3161
+ const revokeScope = requireToolScope(TOOL_SCOPES.revoke_saved_card);
3162
+ const revokeOpts = {
3163
+ ...revokeB1,
3164
+ ...revokeB2,
3165
+ scopeChallenge: revokeScope
3166
+ };
3167
+ const revokeRun = async (args, ctx) => {
3168
+ const ready = await readyContext(ctx.http?.authInfo, ctx.http?.req);
3169
+ if ("isError" in ready) return ready;
3170
+ return executeRevokeSavedCard(args, ready);
3171
+ };
3172
+ server.registerTool("revoke_saved_card", revokeOpts, revokeRun);
3173
+ };
3174
+ const mcp = createMcpHandler(register, {
3175
+ serverInfo: {
3176
+ name: "firespark-agent",
3177
+ version: "0.14.1"
3178
+ },
3179
+ capabilities: {
3180
+ tools: {},
3181
+ resources: {}
3182
+ },
3183
+ instructions: INSTRUCTIONS
3184
+ });
3185
+ const stateOf = (ctx) => {
3186
+ const value = ctx.mcpReq?.requestState?.();
3187
+ return typeof value === "string" ? value : void 0;
3188
+ };
3189
+ const readyContext = async (authInfo, req) => {
3190
+ const customerId = authInfo?.extra?.customerId;
3191
+ const channelId = authInfo?.extra?.channelId;
3192
+ const merchantId = authInfo?.extra?.merchantId;
3193
+ if (!authInfo || typeof customerId !== "string" || !customerId) return toolFail("Tu sesión no es válida aquí.");
3194
+ if (typeof channelId !== "string" || typeof merchantId !== "string") return toolFail("Tu sesión no es válida aquí.");
3195
+ try {
3196
+ const storefrontToken = await storefrontAccessToken(runtime, {
3197
+ merchantId,
3198
+ customerId,
3199
+ subjectToken: authInfo.token
3200
+ });
3201
+ const origin = req ? new URL(req.url).origin : "";
3202
+ const b1 = {
3203
+ apiUrl: runtime.apiUrl,
3204
+ merchantId,
3205
+ channelId,
3206
+ customerId
3207
+ };
3208
+ const b2 = {
3209
+ fetchImpl: runtime.fetchImpl,
3210
+ storefrontToken
3211
+ };
3212
+ const b3 = {
3213
+ linkSecret: runtime.linkSecret ?? "",
3214
+ origin
3215
+ };
3216
+ return {
3217
+ ...b1,
3218
+ ...b2,
3219
+ ...b3
3220
+ };
3221
+ } catch {
3222
+ return toolFail("No pude abrir la sesión de la tienda. Inténtalo de nuevo.");
3223
+ }
3224
+ };
3225
+ return async (request, merchantId) => {
3226
+ const merchant = runtime.merchant(merchantId);
3227
+ if (!merchant) return rpcError(...[
3228
+ 404,
3229
+ -32004,
3230
+ "Este comercio no tiene un canal Agent activo."
3231
+ ]);
3232
+ const issued = new URL(request.url).searchParams.get("iss");
3233
+ if (issued !== null && issued !== merchant.issuer) return rpcError(401, -32001, "Tu sesión no es válida aquí.");
3234
+ const lookup = await resolveAgentChannel({
3235
+ apiUrl: runtime.apiUrl,
3236
+ merchant,
3237
+ fetchImpl: runtime.fetchImpl
3238
+ });
3239
+ if (!lookup.ok && lookup.reason === "upstream") return rpcError(...[
3240
+ 502,
3241
+ -32002,
3242
+ "No pude confirmar el canal Agent. Inténtalo de nuevo."
3243
+ ]);
3244
+ if (!lookup.ok) return rpcError(...[
3245
+ 404,
3246
+ -32004,
3247
+ "Este comercio no tiene un canal Agent activo."
3248
+ ]);
3249
+ const resourceUrl = agentResourceUrl(request, merchantId);
3250
+ const verify = async (_request, bearer) => {
3251
+ if (!bearer) return void 0;
3252
+ const key = await verificationKey(runtime, merchant);
3253
+ const b1 = {
3254
+ token: bearer,
3255
+ issuer: merchant.issuer
3256
+ };
3257
+ const b2 = {
3258
+ audience: resourceUrl,
3259
+ merchantId,
3260
+ key
3261
+ };
3262
+ const verified = await verifyAgentAccessToken({
3263
+ ...b1,
3264
+ ...b2
3265
+ });
3266
+ if (!verified) return void 0;
3267
+ const extra = {
3268
+ customerId: verified.customerId,
3269
+ merchantId,
3270
+ channelId: lookup.channel.channelId
3271
+ };
3272
+ const c1 = {
3273
+ token: verified.token,
3274
+ clientId: verified.clientId
3275
+ };
3276
+ const c2 = {
3277
+ scopes: verified.scopes,
3278
+ expiresAt: verified.expiresAt
3279
+ };
3280
+ const c3 = {
3281
+ resource: new URL(resourceUrl),
3282
+ extra
3283
+ };
3284
+ return {
3285
+ ...c1,
3286
+ ...c2,
3287
+ ...c3
3288
+ };
3289
+ };
3290
+ const authOpts = {
3291
+ required: true,
3292
+ resourceMetadataPath: agentMetadataPath(merchantId)
3293
+ };
3294
+ return withMcpAuth(mcp, verify, authOpts)(request);
3295
+ };
3296
+ };
3297
+ /**
3298
+ * RFC 9728 metadata. CIMD stays on the merchant's authorization server:
3299
+ * this route does not offer dynamic client registration.
3300
+ */
3301
+ const agentProtectedResource = (request, merchantId, runtime) => {
3302
+ const merchant = runtime.merchant(merchantId);
3303
+ if (!merchant) return Response.json({ error: "Este comercio no tiene un canal Agent activo." }, { status: 404 });
3304
+ return protectedResourceHandler({ authServerUrls: [merchant.issuer] })(request);
3305
+ };
3306
+ const agentMetadataOptions = () => {
3307
+ return metadataCorsOptionsRequestHandler()();
3308
+ };
3309
+ //#endregion
3310
+ //#region src/payments/buttons.ts
3311
+ const MANUAL = /* @__PURE__ */ new Set(["CASH", "PIN_PAD"]);
3312
+ const record = (value) => {
3313
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
3314
+ return value;
3315
+ };
3316
+ const text = (value) => {
3317
+ return typeof value === "string" ? value.trim() : "";
3318
+ };
3319
+ const checkoutOf = (config) => {
3320
+ const row = record(config);
3321
+ const checkout = record(row?.agent_checkout);
3322
+ if (!checkout) return null;
3323
+ const mode = checkout.mode;
3324
+ if (mode !== "test" && mode !== "hosted") return null;
3325
+ const operation = text(checkout.operation);
3326
+ const redirectKey = text(checkout.redirect_key);
3327
+ if (mode === "hosted" && (!operation || !redirectKey)) return null;
3328
+ return {
3329
+ mode,
3330
+ operation,
3331
+ redirectKey
3332
+ };
3333
+ };
3334
+ /** Real gateway methods. Cash, pin pads and redemptions are not buttons. */
3335
+ const paymentButtons = (payments) => {
3336
+ if (!Array.isArray(payments)) return [];
3337
+ const buttons = [];
3338
+ for (const item of payments) {
3339
+ const row = record(item);
3340
+ if (!row) continue;
3341
+ const provider = record(row.provider);
3342
+ const method = record(row.method);
3343
+ const providerId = text(provider?.provider_id);
3344
+ const methodId = text(method?.method);
3345
+ const id = text(row.id);
3346
+ if (!id || !providerId || !methodId) continue;
3347
+ if (methodId === "REDEMPTION") continue;
3348
+ if (providerId === "firespark" && MANUAL.has(methodId)) continue;
3349
+ const providerName = text(provider?.name) || providerId;
3350
+ const methodName = text(method?.name) || methodId;
3351
+ const checkout = checkoutOf(row.config);
3352
+ const caps = row.capabilities;
3353
+ const saveCard = Array.isArray(caps) && caps.includes("hosted_tokenization");
3354
+ const b1 = {
3355
+ id,
3356
+ providerId,
3357
+ providerName,
3358
+ method: methodId
3359
+ };
3360
+ const b2 = {
3361
+ methodName,
3362
+ checkout,
3363
+ saveCard
3364
+ };
3365
+ buttons.push({
3366
+ ...b1,
3367
+ ...b2
3368
+ });
3369
+ }
3370
+ return buttons;
3371
+ };
3372
+ //#endregion
3373
+ //#region src/payments/copy.ts
3374
+ const COPY = {
3375
+ "es-EC": {
3376
+ title: "Paga tu pedido",
3377
+ intro: "El cobro lo hace la pasarela de este comercio. Aquí no pedimos el número de tu tarjeta.",
3378
+ total: "Total a pagar",
3379
+ empty: "Este comercio no tiene métodos de pago aquí.",
3380
+ saveCard: "Guardar esta tarjeta para la próxima. La tokeniza la pasarela de este comercio.",
3381
+ saveCardUnavailable: "Guardar esta tarjeta para la próxima. Todavía no está disponible aquí.",
3382
+ pay: "Pagar con",
3383
+ used: "Este enlace ya se usó. Pide uno nuevo en el chat.",
3384
+ expired: "Este enlace ya venció. Pide uno nuevo en el chat.",
3385
+ invalid: "Este enlace no es válido.",
3386
+ wrongChannel: "Este enlace no es de este canal.",
3387
+ noCheckout: "Este método todavía no tiene un cobro alojado. Elige otro.",
3388
+ gatewayTitle: "Pasarela de prueba",
3389
+ gatewayBody: "Este cobro de prueba no usa una tarjeta real. La pasarela del comercio confirmaría el pago aquí.",
3390
+ gatewayButton: "Pagar ahora",
3391
+ waiting: "Todavía no vemos el pago. Cuando la pasarela lo confirme, te devolvemos al chat.",
3392
+ done: "Listo. Te devolvemos al chat.",
3393
+ back: "Volver al chat"
3394
+ },
3395
+ "en-US": {
3396
+ title: "Pay for your order",
3397
+ intro: "The merchant's payment gateway charges you. We never ask for your card number here.",
3398
+ total: "Amount due",
3399
+ empty: "This merchant has no payment methods here.",
3400
+ saveCard: "Save this card for next time. The merchant's gateway tokenizes it.",
3401
+ saveCardUnavailable: "Save this card for next time. That is not available here yet.",
3402
+ pay: "Pay with",
3403
+ used: "This link was already used. Ask for a new one in the chat.",
3404
+ expired: "This link has expired. Ask for a new one in the chat.",
3405
+ invalid: "This link is not valid.",
3406
+ wrongChannel: "This link does not belong to this channel.",
3407
+ noCheckout: "This method has no hosted checkout yet. Choose another.",
3408
+ gatewayTitle: "Test gateway",
3409
+ gatewayBody: "This test charge does not use a real card. The merchant gateway would confirm the payment here.",
3410
+ gatewayButton: "Pay now",
3411
+ waiting: "We have not seen the payment yet. When the gateway confirms it, we send you back to the chat.",
3412
+ done: "Done. We are sending you back to the chat.",
3413
+ back: "Back to the chat"
3414
+ },
3415
+ "pt-BR": {
3416
+ title: "Pague seu pedido",
3417
+ intro: "A cobrança é da adquirente deste comércio. Aqui não pedimos o número do seu cartão.",
3418
+ total: "Total a pagar",
3419
+ empty: "Este comércio não tem meios de pagamento aqui.",
3420
+ saveCard: "Salvar este cartão para a próxima. A adquirente deste comércio faz a tokenização.",
3421
+ saveCardUnavailable: "Salvar este cartão para a próxima. Isso ainda não está disponível aqui.",
3422
+ pay: "Pagar com",
3423
+ used: "Este link já foi usado. Peça outro no chat.",
3424
+ expired: "Este link venceu. Peça outro no chat.",
3425
+ invalid: "Este link não é válido.",
3426
+ wrongChannel: "Este link não é deste canal.",
3427
+ noCheckout: "Este método ainda não tem uma cobrança hospedada. Escolha outro.",
3428
+ gatewayTitle: "Adquirente de teste",
3429
+ gatewayBody: "Esta cobrança de teste não usa um cartão real. A adquirente do comércio confirmaria o pagamento aqui.",
3430
+ gatewayButton: "Pagar agora",
3431
+ waiting: "Ainda não vimos o pagamento. Quando a adquirente confirmar, te levamos de volta ao chat.",
3432
+ done: "Pronto. Estamos te levando de volta ao chat.",
3433
+ back: "Voltar ao chat"
3434
+ }
3435
+ };
3436
+ const paymentLocale = (header) => {
3437
+ const value = (header ?? "").toLowerCase();
3438
+ if (value.includes("pt")) return "pt-BR";
3439
+ if (value.includes("en")) return "en-US";
3440
+ return "es-EC";
3441
+ };
3442
+ const paymentCopy = (locale) => {
3443
+ return COPY[locale];
3444
+ };
3445
+ //#endregion
3446
+ //#region src/payments/html.ts
3447
+ const escapeHtml = (value) => {
3448
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;");
3449
+ };
3450
+ const paymentDocument = (locale, title, body) => {
3451
+ return `<!doctype html><html lang="${locale}"><head>${`<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="referrer" content="no-referrer"><title>${escapeHtml(title)}</title><style>${[
3452
+ "body{font-family:system-ui,sans-serif;margin:0;background:#f6f4f1;color:#1c1917}",
3453
+ "main{max-width:28rem;margin:0 auto;padding:2rem 1.25rem}",
3454
+ "h1{font-size:1.25rem;font-weight:600;margin:0 0 0.75rem}",
3455
+ "p{line-height:1.5}",
3456
+ "button{display:block;width:100%;margin:0.5rem 0;padding:0.75rem 1rem;",
3457
+ "border:0;border-radius:0.75rem;background:#9a3412;color:#fff;font:inherit}",
3458
+ "label{display:flex;gap:0.5rem;align-items:flex-start;color:#57534e;font-size:0.9rem}",
3459
+ "a{color:#9a3412}"
3460
+ ].join("")}</style>`}</head><body><main>${body}</main></body></html>`;
3461
+ };
3462
+ const messageBody = (copy, text) => {
3463
+ return `<h1>${escapeHtml(copy.title)}</h1><p>${escapeHtml(text)}</p>`;
3464
+ };
3465
+ const htmlResponse = (html, status = 200) => {
3466
+ return new Response(html, {
3467
+ status,
3468
+ headers: {
3469
+ "content-type": "text/html; charset=utf-8",
3470
+ "cache-control": "no-store",
3471
+ "referrer-policy": "no-referrer"
3472
+ }
3473
+ });
3474
+ };
3475
+ const redirectResponse = (url) => {
3476
+ return new Response(null, {
3477
+ status: 303,
3478
+ headers: {
3479
+ location: url,
3480
+ "cache-control": "no-store",
3481
+ "referrer-policy": "no-referrer"
3482
+ }
3483
+ });
3484
+ };
3485
+ //#endregion
3486
+ //#region src/payments/page.ts
3487
+ const textOf = (value) => {
3488
+ return typeof value === "string" ? value : "";
3489
+ };
3490
+ const originOf = (request) => {
3491
+ return new URL(request.url).origin;
3492
+ };
3493
+ const payPath = (origin, merchantId, token) => {
3494
+ return `${origin}/m/${encodeURIComponent(merchantId)}/pay/${token}`;
3495
+ };
3496
+ const returnPath = (origin, merchantId, token) => {
3497
+ return `${origin}/m/${encodeURIComponent(merchantId)}/pay/return?ref=${encodeURIComponent(token)}`;
3498
+ };
3499
+ const gatewayPath = (origin, merchantId, token) => {
3500
+ return `${origin}/m/${encodeURIComponent(merchantId)}/pay/gateway?ref=${encodeURIComponent(token)}`;
3501
+ };
3502
+ const document$1 = (locale, copy, text) => {
3503
+ const body = messageBody(copy, text);
3504
+ return htmlResponse(paymentDocument(locale, copy.title, body));
3505
+ };
3506
+ const saveBox = (copy, checked) => {
3507
+ const save = escapeHtml(copy.saveCard);
3508
+ return `<label><input type="checkbox" name="save_card" value="1"${checked ? " checked" : ""}> ${save}</label>`;
3509
+ };
3510
+ const buttonsBody = (copy, total, currency, buttons, continuation, action, saveChecked) => {
3511
+ const title = escapeHtml(copy.title);
3512
+ const intro = escapeHtml(copy.intro);
3513
+ const label = escapeHtml(copy.total);
3514
+ const amount = escapeHtml(`${total} ${currency}`);
3515
+ const anySave = buttons.some((button) => button.saveCard);
3516
+ const forms = buttons.map((button) => {
3517
+ const name = escapeHtml(`${copy.pay} ${button.providerName}`);
3518
+ const id = escapeHtml(button.id);
3519
+ const token = escapeHtml(continuation);
3520
+ return `<form method="post" action="${escapeHtml(action)}"><input type="hidden" name="continuation" value="${token}">${button.saveCard ? saveBox(copy, saveChecked) : ""}<button type="submit" name="payment_id" value="${id}">${name}</button></form>`;
3521
+ });
3522
+ const list = forms.length > 0 ? forms.join("") : `<p>${escapeHtml(copy.empty)}</p>`;
3523
+ const off = `<label><input type="checkbox" disabled> ${escapeHtml(copy.saveCardUnavailable)}</label>`;
3524
+ return `<h1>${title}</h1><p>${intro}</p><p>${label}: ${amount}</p>${list}${anySave ? "" : off}`;
3525
+ };
3526
+ const loadChannel$1 = async (runtime, merchantId) => {
3527
+ const merchant = runtime.merchant(merchantId);
3528
+ if (!merchant) return null;
3529
+ const lookup = await resolveAgentChannel({
3530
+ apiUrl: runtime.apiUrl,
3531
+ merchant,
3532
+ fetchImpl: runtime.fetchImpl
3533
+ });
3534
+ if (!lookup.ok) return null;
3535
+ return lookup.channel;
3536
+ };
3537
+ const readOrder = async (runtime, claims) => {
3538
+ const http = storefrontHttp(runtime.apiUrl, claims.storefrontToken, runtime.fetchImpl);
3539
+ const order = await services.orders.get(claims.orderId, http);
3540
+ if (order.channel_id !== claims.channelId) return null;
3541
+ return {
3542
+ order,
3543
+ http
3544
+ };
3545
+ };
3546
+ const totalText = (order) => {
3547
+ const total = order.totals?.total;
3548
+ const currency = order.totals?.currency;
3549
+ if (typeof total !== "number" || typeof currency !== "string") return null;
3550
+ return {
3551
+ total: numberToDecimal(total),
3552
+ currency
3553
+ };
3554
+ };
3555
+ const startCharge = async (request, runtime, claims, button, order, saveCard) => {
3556
+ const secret = runtime.linkSecret ?? "";
3557
+ const http = storefrontHttp(runtime.apiUrl, claims.storefrontToken, runtime.fetchImpl);
3558
+ const attempt = claims.jti;
3559
+ const intent = { tenders: [{
3560
+ method: button.method,
3561
+ provider: button.providerId,
3562
+ payment_id: button.id,
3563
+ collect_at: "DEVICE",
3564
+ attempt_reference: attempt
3565
+ }] };
3566
+ const started = tenderOnOrder(await services.orders.putPaymentIntent(order.id, intent, http), button.id, attempt);
3567
+ if (!started) return null;
3568
+ const mode = button.checkout?.mode ?? "hosted";
3569
+ const n1 = {
3570
+ ...claims,
3571
+ purpose: "return"
3572
+ };
3573
+ const n2 = {
3574
+ paymentId: button.id,
3575
+ tenderId: started.id
3576
+ };
3577
+ const n3 = {
3578
+ attemptReference: started.attemptReference,
3579
+ mode
3580
+ };
3581
+ const next = {
3582
+ ...n1,
3583
+ ...n2,
3584
+ ...n3
3585
+ };
3586
+ const returnToken = await mintAgentLink(next, secret);
3587
+ const origin = originOf(request);
3588
+ const back = returnPath(origin, claims.merchantId, returnToken);
3589
+ let payNext = "";
3590
+ if (mode === "test") {
3591
+ const gateToken = await mintAgentLink({
3592
+ ...next,
3593
+ purpose: "gateway"
3594
+ }, secret);
3595
+ payNext = gatewayPath(origin, claims.merchantId, gateToken);
3596
+ } else {
3597
+ const operation = button.checkout?.operation ?? "";
3598
+ const redirectKey = button.checkout?.redirectKey ?? "";
3599
+ const input = { response_url: back };
3600
+ const b1 = { order_id: order.id };
3601
+ const b2 = {
3602
+ attempt_reference: started.attemptReference,
3603
+ input
3604
+ };
3605
+ const body = {
3606
+ ...b1,
3607
+ ...b2
3608
+ };
3609
+ const p1 = [
3610
+ button.id,
3611
+ operation,
3612
+ body,
3613
+ http
3614
+ ];
3615
+ const redirect = (await services.payments.operation(...p1))[redirectKey];
3616
+ if (typeof redirect === "string" && redirect.startsWith("https://")) payNext = redirect;
3617
+ }
3618
+ if (saveCard && button.saveCard) {
3619
+ const input = {
3620
+ save_card: true,
3621
+ return_url: payNext.startsWith("https://") ? payNext : back
3622
+ };
3623
+ const b1 = { order_id: order.id };
3624
+ const b2 = {
3625
+ attempt_reference: started.attemptReference,
3626
+ input
3627
+ };
3628
+ const body = {
3629
+ ...b1,
3630
+ ...b2
3631
+ };
3632
+ const p1 = [
3633
+ button.id,
3634
+ "hosted_tokenization",
3635
+ body,
3636
+ http
3637
+ ];
3638
+ const redirect = (await services.payments.operation(...p1)).redirect_url;
3639
+ if (typeof redirect === "string" && redirect.startsWith("https://")) return redirect;
3640
+ }
3641
+ if (!payNext) return null;
3642
+ return payNext;
3643
+ };
3644
+ const handleAgentPayment = async (request, merchantId, token, runtime) => {
3645
+ const locale = paymentLocale(request.headers.get("accept-language"));
3646
+ const copy = paymentCopy(locale);
3647
+ const show = (text, status = 200) => {
3648
+ return document$1(locale, copy, text);
3649
+ };
3650
+ const secret = runtime.linkSecret ?? "";
3651
+ if (!secret) return show(copy.invalid, 500);
3652
+ const opened = await openAgentLink(token, secret);
3653
+ if (!opened.ok && opened.reason === "expired") return show(copy.expired);
3654
+ if (!opened.ok || opened.claims.purpose !== "pay") return show(copy.invalid);
3655
+ const claims = opened.claims;
3656
+ if (claims.merchantId !== merchantId) return show(copy.invalid);
3657
+ const channel = await loadChannel$1(runtime, merchantId);
3658
+ if (!channel || channel.channelId !== claims.channelId) return show(copy.wrongChannel, 404);
3659
+ let loaded;
3660
+ try {
3661
+ loaded = await readOrder(runtime, claims);
3662
+ } catch {
3663
+ return show(copy.invalid, 502);
3664
+ }
3665
+ if (!loaded) return show(copy.wrongChannel, 404);
3666
+ const { order, http } = loaded;
3667
+ const meta = metaOf$3(order);
3668
+ const used = meta[PAY_USED$1];
3669
+ if (request.method === "GET" && used) return show(copy.used);
3670
+ if (request.method !== "GET" && request.method !== "POST") return show(copy.invalid, 405);
3671
+ if (request.method === "GET") {
3672
+ let payments;
3673
+ try {
3674
+ payments = await services.payments.list({
3675
+ order_id: order.id,
3676
+ store_id: order.store_id,
3677
+ channel_id: claims.channelId,
3678
+ fulfillment_id: order.fulfillment_id
3679
+ }, http);
3680
+ await patchOrderMeta(order, { [PAY_USED$1]: claims.jti }, http);
3681
+ } catch {
3682
+ return show(copy.invalid, 502);
3683
+ }
3684
+ const buttons = paymentButtons(payments);
3685
+ const money = totalText(order);
3686
+ const amount = money?.total ?? "";
3687
+ const currency = money?.currency ?? "";
3688
+ const continuation = await mintAgentLink({
3689
+ ...claims,
3690
+ purpose: "continue"
3691
+ }, secret);
3692
+ const action = payPath(originOf(request), merchantId, token);
3693
+ const body = buttonsBody(copy, amount, currency, buttons, continuation, action, claims.saveCard === true);
3694
+ return htmlResponse(paymentDocument(locale, copy.title, body));
3695
+ }
3696
+ if (used !== claims.jti) return show(copy.invalid);
3697
+ if (meta["agent_pay_started"] === "true") return show(copy.used);
3698
+ const form = await request.formData().catch(() => null);
3699
+ const continuation = textOf(form?.get("continuation") ?? null);
3700
+ const paymentId = textOf(form?.get("payment_id") ?? null);
3701
+ const saveCard = textOf(form?.get("save_card") ?? null) === "1";
3702
+ const continued = await openAgentLink(continuation, secret);
3703
+ if (!continued.ok) return show(copy.invalid);
3704
+ if (continued.claims.purpose !== "continue") return show(copy.invalid);
3705
+ if (continued.claims.jti !== claims.jti) return show(copy.invalid);
3706
+ const button = paymentButtons(await services.payments.list({
3707
+ order_id: order.id,
3708
+ store_id: order.store_id,
3709
+ channel_id: claims.channelId,
3710
+ fulfillment_id: order.fulfillment_id
3711
+ }, http)).find((item) => item.id === paymentId);
3712
+ if (!button?.checkout) return show(copy.noCheckout);
3713
+ try {
3714
+ await patchOrderMeta(order, { [PAY_STARTED]: "true" }, http);
3715
+ const next = await startCharge(request, runtime, claims, button, order, saveCard);
3716
+ if (!next) return show(copy.noCheckout, 502);
3717
+ return redirectResponse(next);
3718
+ } catch {
3719
+ return show(copy.noCheckout, 502);
3720
+ }
3721
+ };
3722
+ //#endregion
3723
+ //#region src/payments/return.ts
3724
+ const botReturnUrl = (returnUrl, status) => {
3725
+ const url = new URL(returnUrl);
3726
+ url.searchParams.set("payment_status", status);
3727
+ return url.toString();
3728
+ };
3729
+ const document = (locale, copy, text) => {
3730
+ const body = messageBody(copy, text);
3731
+ return htmlResponse(paymentDocument(locale, copy.title, body));
3732
+ };
3733
+ const loadChannel = async (runtime, merchantId) => {
3734
+ const merchant = runtime.merchant(merchantId);
3735
+ if (!merchant) return null;
3736
+ const lookup = await resolveAgentChannel({
3737
+ apiUrl: runtime.apiUrl,
3738
+ merchant,
3739
+ fetchImpl: runtime.fetchImpl
3740
+ });
3741
+ if (!lookup.ok) return null;
3742
+ return lookup.channel;
3743
+ };
3744
+ const paid = (order) => {
3745
+ return order.payment_status === "PAID";
3746
+ };
3747
+ const handleAgentPaymentReturn = async (request, merchantId, runtime) => {
3748
+ const locale = paymentLocale(request.headers.get("accept-language"));
3749
+ const copy = paymentCopy(locale);
3750
+ const show = (text, status = 200) => document(locale, copy, text);
3751
+ const secret = runtime.linkSecret ?? "";
3752
+ const ref = new URL(request.url).searchParams.get("ref") ?? "";
3753
+ if (!secret || !ref) return show(copy.invalid);
3754
+ const opened = await openAgentLink(ref, secret);
3755
+ if (!opened.ok && opened.reason === "expired") return show(copy.expired);
3756
+ if (!opened.ok) return show(copy.invalid);
3757
+ const claims = opened.claims;
3758
+ const purpose = claims.purpose;
3759
+ if (purpose !== "return" && purpose !== "gateway") return show(copy.invalid);
3760
+ if (claims.merchantId !== merchantId) return show(copy.invalid);
3761
+ const channel = await loadChannel(runtime, merchantId);
3762
+ if (!channel || channel.channelId !== claims.channelId) return show(copy.wrongChannel, 404);
3763
+ const http = storefrontHttp(runtime.apiUrl, claims.storefrontToken, runtime.fetchImpl);
3764
+ let order;
3765
+ try {
3766
+ order = await services.orders.get(claims.orderId, http);
3767
+ } catch {
3768
+ return show(copy.waiting, 502);
3769
+ }
3770
+ if (order.channel_id !== claims.channelId) return show(copy.wrongChannel, 404);
3771
+ if (paid(order)) return redirectResponse(botReturnUrl(claims.returnUrl, "PAID"));
3772
+ const status = (request.method === "POST" ? await request.formData().catch(() => null) : null)?.get("status");
3773
+ if (!(claims.mode === "test" && status === "paid")) {
3774
+ const back = escapeHtml(claims.returnUrl);
3775
+ const body = `${messageBody(copy, copy.waiting)}<p><a href="${back}">${escapeHtml(copy.back)}</a></p>`;
3776
+ return htmlResponse(paymentDocument(locale, copy.title, body));
3777
+ }
3778
+ if (!claims.tenderId || !claims.attemptReference) return show(copy.waiting, 502);
3779
+ const b1 = {
3780
+ tender_id: claims.tenderId,
3781
+ status: "PAID"
3782
+ };
3783
+ const b2 = { attempt_reference: claims.attemptReference };
3784
+ try {
3785
+ const updated = await services.orders.recordPayment(claims.orderId, {
3786
+ ...b1,
3787
+ ...b2
3788
+ }, http);
3789
+ if (!paid(updated)) return show(copy.waiting, 502);
3790
+ } catch {
3791
+ return show(copy.waiting, 502);
3792
+ }
3793
+ return redirectResponse(botReturnUrl(claims.returnUrl, "PAID"));
3794
+ };
3795
+ const handleAgentTestGateway = async (request, merchantId, runtime) => {
3796
+ const locale = paymentLocale(request.headers.get("accept-language"));
3797
+ const copy = paymentCopy(locale);
3798
+ const show = (text) => document(locale, copy, text);
3799
+ const secret = runtime.linkSecret ?? "";
3800
+ const ref = new URL(request.url).searchParams.get("ref") ?? "";
3801
+ if (!secret || !ref) return show(copy.invalid);
3802
+ const opened = await openAgentLink(ref, secret);
3803
+ if (!opened.ok && opened.reason === "expired") return show(copy.expired);
3804
+ if (!opened.ok) return show(copy.invalid);
3805
+ const claims = opened.claims;
3806
+ if (claims.purpose !== "gateway" || claims.mode !== "test") return show(copy.invalid);
3807
+ if (claims.merchantId !== merchantId) return show(copy.invalid);
3808
+ const action = escapeHtml(`/m/${encodeURIComponent(merchantId)}/pay/return?ref=${encodeURIComponent(ref)}`);
3809
+ const form = `<h1>${escapeHtml(copy.gatewayTitle)}</h1><p>${escapeHtml(copy.gatewayBody)}</p><form method="post" action="${action}"><input type="hidden" name="status" value="paid"><button type="submit">${escapeHtml(copy.gatewayButton)}</button></form>`;
3810
+ return htmlResponse(paymentDocument(locale, copy.gatewayTitle, form));
3811
+ };
3812
+ //#endregion
3813
+ export { TOOL_SCOPES, UI_CART, UI_MENU, UI_PRODUCT, agentMetadataOptions, agentMetadataPath, agentProtectedResource, agentResourceUrl, botReturnUrl, buildCartSchema, cartLineSchema, chargeSavedCardSchema, confirmTotalRequest, confirmedAmount, confirmedTotal, createAgentMcpHandler, createOrderSchema, customerSchema, decimalSchema, decimalToNumber, decimalsEqual, executeBuildCart, executeChargeSavedCard, executeCreateOrder, executeGetMenu, executeGetMenuCategory, executeGetProduct, executeListSavedCards, executeListStores, executeOrderStatus, executeRevokeSavedCard, executeSaveCardConsent, executeSearchMenu, executeStartPayment, executeValidateCart, getMenuCategorySchema, getMenuSchema, getProductSchema, handleAgentPayment, handleAgentPaymentReturn, handleAgentTestGateway, idSchema, idempotencyKeySchema, isDecimalString, isImageOrigin, jwksFor, listSavedCardsSchema, listStoresSchema, mintAgentLink, numberToDecimal, openAgentLink, openRequestState, orderAmountSchema, orderStatusSchema, paymentButtons, presentMoney, requireToolScope, resolveAgentChannel, revokeSavedCardSchema, saveCardConsentSchema, sealRequestState, searchMenuSchema, startPaymentSchema, storefrontAccessToken, sumDecimals, totalsSchema, validateCartSchema, verificationKey, verifyAgentAccessToken };