@saar-ai/web-widget 0.4.1 → 0.5.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/chunks/chat-tMKkYmTC.js +592 -0
- package/dist/chunks/{host-widget-C9EyGeiN.js → host-widget-B0SkhMIs.js} +1450 -103
- package/dist/format-money.d.ts +54 -17
- package/dist/format-money.d.ts.map +1 -1
- package/dist/generated/widget-css.d.ts.map +1 -1
- package/dist/host-widget.d.ts +62 -0
- package/dist/host-widget.d.ts.map +1 -1
- package/dist/index.js +3 -3
- package/dist/messages.d.ts +17 -0
- package/dist/messages.d.ts.map +1 -1
- package/dist/next/index.js +1 -1
- package/dist/turn-order.d.ts +106 -0
- package/dist/turn-order.d.ts.map +1 -0
- package/dist/use-chat-session.d.ts +128 -1
- package/dist/use-chat-session.d.ts.map +1 -1
- package/dist/use-voice-session.d.ts +31 -1
- package/dist/use-voice-session.d.ts.map +1 -1
- package/dist/voice-widget.d.ts +66 -6
- package/dist/voice-widget.d.ts.map +1 -1
- package/dist/widget-cards.d.ts.map +1 -1
- package/dist/widget.css +1 -1
- package/package.json +3 -3
- package/src/styles/concierge.css +45 -0
- package/dist/chunks/chat-DfajYOmN.js +0 -240
|
@@ -0,0 +1,592 @@
|
|
|
1
|
+
import { a as httpUrl, c as number, i as discriminatedUnion, l as object, n as array, o as literal, r as boolean, t as _enum, u as string } from "./schemas-Bl_6mxe4.js";
|
|
2
|
+
//#region ../widget-protocol/dist/chat.js
|
|
3
|
+
/**
|
|
4
|
+
* The webchat SSE wire contract, and the sidecar `widgetEvent` a tool result
|
|
5
|
+
* may carry to short-circuit into one of those events.
|
|
6
|
+
*
|
|
7
|
+
* ## Why this lives in `@saar-ai/widget-protocol`, zod, not a plain interface
|
|
8
|
+
*
|
|
9
|
+
* Two independent runtimes read this shape: `apps/api`'s
|
|
10
|
+
* `widget-chat.controller.ts` WRITES it onto an SSE response, and
|
|
11
|
+
* `@saar-ai/web-widget`'s voice leg (`use-voice-session.ts`, via the
|
|
12
|
+
* `widget.event` sidecar on the telemetry channel — see `./telemetry.ts`)
|
|
13
|
+
* PARSES `WidgetToolEventSchema` off it. A hand-maintained interface on each
|
|
14
|
+
* side drifts silently — the failure mode is a widget that renders
|
|
15
|
+
* `undefined` for a field the server renamed. Zod schemas, exported from one
|
|
16
|
+
* package both sides can import, make the shape a single source of truth and
|
|
17
|
+
* let each side `.parse()`/`.safeParse()` at its own boundary instead of
|
|
18
|
+
* trusting an unchecked cast.
|
|
19
|
+
*
|
|
20
|
+
* Moved here from the framework-inherited `@wesence/shared-types` — this
|
|
21
|
+
* package's own `AGENTS.md` explains why a widget-only contract does not
|
|
22
|
+
* belong inside a package a framework regeneration can silently clobber, and
|
|
23
|
+
* why it must not be reachable from `@saar-ai/web-widget`'s published bundle
|
|
24
|
+
* via a `@wesence/*` import path at all (docs/PACKAGE_DISTRIBUTION.md).
|
|
25
|
+
*
|
|
26
|
+
* ## The seven event types, and why cards/checkout are separate events from text
|
|
27
|
+
*
|
|
28
|
+
* A reply may interleave prose with product/price/checkout data. Prices,
|
|
29
|
+
* stock, and product attributes are NEVER stated as text by the model (see
|
|
30
|
+
* `widget-chat.service.ts`'s system-prompt guardrail) — they arrive only as
|
|
31
|
+
* `cards`, sourced from a tool result, so the widget can render them as
|
|
32
|
+
* structured UI (an image, a price, an availability badge) rather than text
|
|
33
|
+
* the model could hallucinate. The real checkout URL is likewise never typed
|
|
34
|
+
* by the model — it arrives only as `checkout`.
|
|
35
|
+
*
|
|
36
|
+
* - `text-delta` — one chunk of the assistant's streamed reply.
|
|
37
|
+
* - `cards` — one or more product/curation cards to render.
|
|
38
|
+
* - `escalated` — the conversation just moved to a human/queue; the AI
|
|
39
|
+
* will not reply further on this turn. The widget should show a "connecting
|
|
40
|
+
* you with a person" state and start polling `/widget/messages`.
|
|
41
|
+
* - `checkout` — a real Shopify cart permalink to hand the shopper off
|
|
42
|
+
* to; the widget renders a "Go to checkout" control around `url`.
|
|
43
|
+
* - `add-to-cart` — the concierge asking the WIDGET to put one item in the
|
|
44
|
+
* shopper's cart, for a shopper who asked for it in words rather than by
|
|
45
|
+
* pressing a card's button. The server never touches a cart itself — see
|
|
46
|
+
* {@link WidgetChatAddToCartEventSchema} for why that is structural.
|
|
47
|
+
* - `done` — the turn is over. Carries the turn id so the widget can
|
|
48
|
+
* correlate a later `/widget/messages` page against what it already
|
|
49
|
+
* rendered inline.
|
|
50
|
+
* - `error` — the turn failed. `message` is safe to show the visitor
|
|
51
|
+
* (never a raw exception/stack).
|
|
52
|
+
*
|
|
53
|
+
* ## `widgetEvent` — the tool-result sidecar
|
|
54
|
+
*
|
|
55
|
+
* A tool (e.g. a product-search tool) may attach `widgetEvent` to its output
|
|
56
|
+
* to ask the chat loop to forward one of these events verbatim, alongside the
|
|
57
|
+
* tool's own return value the model sees. Only `cards`, `escalated`,
|
|
58
|
+
* `checkout` and `add-to-cart` are valid sidecar events —
|
|
59
|
+
* `text-delta`/`done`/`error` are lifecycle events the runtime itself owns and
|
|
60
|
+
* a tool must never emit.
|
|
61
|
+
*/
|
|
62
|
+
/** Bound for a display string a card renders. Never free-form model prose. */
|
|
63
|
+
var CARD_TEXT_MAX = 500;
|
|
64
|
+
/** Bound for an id-shaped field (product/variant/curation ids). */
|
|
65
|
+
var ID_MAX = 200;
|
|
66
|
+
/**
|
|
67
|
+
* An ISO 4217 currency code, as a schema — three LETTERS, case preserved.
|
|
68
|
+
*
|
|
69
|
+
* Shared by every currency field on this wire so none of them can drift back
|
|
70
|
+
* to a bare `length(3)`. See {@link WidgetChatCardSchema}'s `currency` for the
|
|
71
|
+
* prompt-injection reason the charset matters and not just the length.
|
|
72
|
+
*/
|
|
73
|
+
var CURRENCY_CODE = string().regex(/^[A-Za-z]{3}$/, "must be a three-letter ISO 4217 currency code");
|
|
74
|
+
/**
|
|
75
|
+
* One product/curation card. `priceMinor` is the ISO 4217 minor-unit integer
|
|
76
|
+
* (cents, paise, …) — never a float — and `currency` is the ISO 4217 code, so
|
|
77
|
+
* the widget formats price itself rather than trusting a pre-formatted
|
|
78
|
+
* string the model could get wrong.
|
|
79
|
+
*/
|
|
80
|
+
var WidgetChatCardSchema = object({
|
|
81
|
+
productId: string().min(1).max(ID_MAX),
|
|
82
|
+
/** The INTERNAL catalog UUID (`curation_items.variant_id`) — never a platform id. See `platformVariantId` for what a storefront `addToCart` bridge actually needs. */
|
|
83
|
+
variantId: string().min(1).max(ID_MAX).optional(),
|
|
84
|
+
/**
|
|
85
|
+
* The PLATFORM-NATIVE variant id (e.g. Shopify's numeric `/cart/add.js`
|
|
86
|
+
* id) — extracted server-side from the variant's provider GID via
|
|
87
|
+
* `apps/api/src/catalog/checkout-permalink.ts`'s
|
|
88
|
+
* `parseShopifyVariantNumericId`, the SAME parser the checkout permalink
|
|
89
|
+
* uses, never a string-slice of `variantId`. `@saar-ai/web-widget`'s
|
|
90
|
+
* `resolveAddToCartHandler` calls a storefront bridge's `addToCart` with
|
|
91
|
+
* THIS field, never `variantId` (adversarial-review finding #2 — the
|
|
92
|
+
* internal UUID is meaningless to `ShopifyBridge`'s `POST /cart/add.js`).
|
|
93
|
+
* Absent whenever the underlying variant's external id isn't a
|
|
94
|
+
* recognised platform GID (§5.3's "degrade, never fabricate" — never
|
|
95
|
+
* guessed) — the widget then offers no add-to-cart action for the card
|
|
96
|
+
* and falls back to a PDP navigation instead.
|
|
97
|
+
*/
|
|
98
|
+
platformVariantId: string().min(1).max(ID_MAX).optional(),
|
|
99
|
+
title: string().min(1).max(CARD_TEXT_MAX),
|
|
100
|
+
/** http(s) only — `z.httpUrl()` refuses `javascript:`/`data:`/etc, the same scheme allowlist `conversations/attribution.ts` enforces for stored URLs. */
|
|
101
|
+
imageUrl: httpUrl().optional(),
|
|
102
|
+
/**
|
|
103
|
+
* The product's storefront handle, so the widget's card can link to its PDP.
|
|
104
|
+
*
|
|
105
|
+
* A SLUG, never a URL or a path: the widget's host builds the href from it
|
|
106
|
+
* (`widget-launcher.tsx`'s `productHref`), so anything path-like here would
|
|
107
|
+
* let a catalogue row steer where a card points. The character class below
|
|
108
|
+
* is what a Shopify handle actually is, and it cannot express a scheme, a
|
|
109
|
+
* host, a `..` segment or a leading slash.
|
|
110
|
+
*/
|
|
111
|
+
handle: string().min(1).max(ID_MAX).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/i).optional(),
|
|
112
|
+
/** ISO 4217 minor units — an integer, never a float. */
|
|
113
|
+
priceMinor: number().int().min(0),
|
|
114
|
+
/**
|
|
115
|
+
* ISO 4217 currency code, e.g. "USD".
|
|
116
|
+
*
|
|
117
|
+
* LETTERS ONLY, not merely three characters. `length(3)` alone admits
|
|
118
|
+
* `"\n- "`, and a currency code reaches the model's cart block as prose on
|
|
119
|
+
* the same line as a price (`widget-chat.service.ts`'s
|
|
120
|
+
* `formatMinorUnitsForModel`) — a newline there forges a line boundary in a
|
|
121
|
+
* block whose whole legibility rests on one line per cart line. The title
|
|
122
|
+
* beside it has always been flattened and quoted for exactly this reason;
|
|
123
|
+
* this field was the half that was not.
|
|
124
|
+
*/
|
|
125
|
+
currency: CURRENCY_CODE,
|
|
126
|
+
available: boolean(),
|
|
127
|
+
/** Short, optional "why this" — e.g. "matches your search". Never a price/stock claim. */
|
|
128
|
+
reason: string().max(CARD_TEXT_MAX).optional()
|
|
129
|
+
});
|
|
130
|
+
var WidgetChatTextDeltaEventSchema = object({
|
|
131
|
+
type: literal("text-delta"),
|
|
132
|
+
delta: string()
|
|
133
|
+
});
|
|
134
|
+
/** Max cards in one event — a chat bubble, not a catalog page. */
|
|
135
|
+
var MAX_CARDS_PER_EVENT = 20;
|
|
136
|
+
var WidgetChatCardsEventSchema = object({
|
|
137
|
+
type: literal("cards"),
|
|
138
|
+
/** Correlates this render back to whichever tool call produced it, when the tool supplies one. */
|
|
139
|
+
curationId: string().min(1).max(ID_MAX).optional(),
|
|
140
|
+
items: array(WidgetChatCardSchema).min(1).max(MAX_CARDS_PER_EVENT)
|
|
141
|
+
});
|
|
142
|
+
var WidgetChatEscalatedEventSchema = object({ type: literal("escalated") });
|
|
143
|
+
/**
|
|
144
|
+
* A real Shopify checkout handoff — `checkout_handoff` (the concierge tool)
|
|
145
|
+
* emits this as a `widgetEvent` sidecar so the widget can render a "Go to
|
|
146
|
+
* checkout" control instead of the model reciting a raw URL. `url` is a
|
|
147
|
+
* SERVER-BUILT Shopify cart permalink (`apps/api/src/catalog/checkout-permalink.ts`)
|
|
148
|
+
* — never a client- or model-supplied value; it carries no internal
|
|
149
|
+
* identifier, only Shopify variant ids/quantities and an opaque attribution
|
|
150
|
+
* token (see that module's doc comment).
|
|
151
|
+
*/
|
|
152
|
+
var WidgetChatCheckoutEventSchema = object({
|
|
153
|
+
type: literal("checkout"),
|
|
154
|
+
handoffId: string().min(1).max(ID_MAX),
|
|
155
|
+
url: httpUrl(),
|
|
156
|
+
itemCount: number().int().positive()
|
|
157
|
+
});
|
|
158
|
+
/**
|
|
159
|
+
* The concierge asking the WIDGET to put one item in the shopper's cart.
|
|
160
|
+
*
|
|
161
|
+
* ## Why an EVENT, and not the server simply adding it
|
|
162
|
+
*
|
|
163
|
+
* A shopper can already press a card's "Add to cart" button; a shopper who
|
|
164
|
+
* SAYS "add the blue cushion to my cart" — the ordinary thing to do on a voice
|
|
165
|
+
* call, where there is no button to press — could not, because nothing in the
|
|
166
|
+
* tool catalogue could act on a cart at all. The cart belongs to the HOST PAGE
|
|
167
|
+
* (`HostBridge.addToCart` — Shopify's `POST /cart/add.js`, or a merchant's own
|
|
168
|
+
* `window` bridge) and lives in the shopper's browser behind their own session
|
|
169
|
+
* cookie. The server has no way to reach it and must never pretend to:
|
|
170
|
+
* `add_to_cart` (`apps/api/src/catalog/tools/add-to-cart.tool.ts`) resolves the
|
|
171
|
+
* item against the catalogue and emits THIS event, and `@saar-ai/web-widget`'s
|
|
172
|
+
* `resolveAddToCartHandler` — the same code path the button already uses,
|
|
173
|
+
* never a second one — performs the add.
|
|
174
|
+
*
|
|
175
|
+
* ## Why the payload is a whole card
|
|
176
|
+
*
|
|
177
|
+
* `item` is a full {@link WidgetChatCardSchema}, not a narrower "cart line"
|
|
178
|
+
* shape, because every step the widget takes with it wants the whole card:
|
|
179
|
+
* `addToCart` needs `platformVariantId` OR `variantId` depending on the
|
|
180
|
+
* bridge's own `addToCartVariantIdSpace`; the `CartLineContext` a
|
|
181
|
+
* `'catalog'`-space bridge is handed needs `title`/`priceMinor`/`currency`/
|
|
182
|
+
* `imageUrl`/`handle`; and the widget's own basket row (`mergeAddedCartLine`)
|
|
183
|
+
* needs the same fields over again. A second type carrying the same eight
|
|
184
|
+
* fields would be a parallel definition of one thing, free to drift from it.
|
|
185
|
+
*
|
|
186
|
+
* ## One event, one unit — deliberately no `quantity`
|
|
187
|
+
*
|
|
188
|
+
* The widget's add path adds exactly one (`bridge.addToCart(id, 1)`), so a
|
|
189
|
+
* quantity here would be a number the widget could not honour: the failure
|
|
190
|
+
* mode is an event that says three, a cart that gains one, and a concierge
|
|
191
|
+
* confirming three out loud. The model calls the tool again for a second unit,
|
|
192
|
+
* which produces a second, DISTINCT event object the widget adds separately
|
|
193
|
+
* (see `@saar-ai/web-widget`'s AGENTS.md on consuming these by identity).
|
|
194
|
+
*
|
|
195
|
+
* ## `platformVariantId` may be absent, and that is not a rejection
|
|
196
|
+
*
|
|
197
|
+
* "Degrade, never fabricate": a variant whose `external_id` is not a
|
|
198
|
+
* recognised `gid://shopify/ProductVariant/<digits>` yields NO
|
|
199
|
+
* `platformVariantId` at all — never one sliced or guessed out of the internal
|
|
200
|
+
* UUID. The event is still emitted, because a `'catalog'`-space bridge adds by
|
|
201
|
+
* `variantId` and can act on it perfectly well; a `'platform'`-space bridge
|
|
202
|
+
* cannot, and degrades exactly as it does for a CARD with the same gap.
|
|
203
|
+
*/
|
|
204
|
+
var WidgetChatAddToCartEventSchema = object({
|
|
205
|
+
type: literal("add-to-cart"),
|
|
206
|
+
item: WidgetChatCardSchema
|
|
207
|
+
});
|
|
208
|
+
var WidgetChatDoneEventSchema = object({
|
|
209
|
+
type: literal("done"),
|
|
210
|
+
turnId: string().min(1)
|
|
211
|
+
});
|
|
212
|
+
var WidgetChatErrorEventSchema = object({
|
|
213
|
+
type: literal("error"),
|
|
214
|
+
/** Safe to show the visitor as-is — never a raw exception message or stack. */
|
|
215
|
+
message: string().min(1).max(CARD_TEXT_MAX)
|
|
216
|
+
});
|
|
217
|
+
/** The full SSE event union — every `event:`/`data:` pair `/widget/chat` may write. */
|
|
218
|
+
var WidgetChatSseEventSchema = discriminatedUnion("type", [
|
|
219
|
+
WidgetChatTextDeltaEventSchema,
|
|
220
|
+
WidgetChatCardsEventSchema,
|
|
221
|
+
WidgetChatEscalatedEventSchema,
|
|
222
|
+
WidgetChatCheckoutEventSchema,
|
|
223
|
+
WidgetChatAddToCartEventSchema,
|
|
224
|
+
WidgetChatDoneEventSchema,
|
|
225
|
+
WidgetChatErrorEventSchema
|
|
226
|
+
]);
|
|
227
|
+
/**
|
|
228
|
+
* What a tool result may carry, under an `output.widgetEvent` key, to ask the
|
|
229
|
+
* chat loop to forward one of these as its own SSE event. Deliberately a
|
|
230
|
+
* NARROWER union than {@link WidgetChatSseEventSchema} — `text-delta`,
|
|
231
|
+
* `done`, and `error` are lifecycle events the runtime alone controls; a tool
|
|
232
|
+
* asserting one of those could inject a fake "done" mid-stream or spoof a
|
|
233
|
+
* fake error to the visitor.
|
|
234
|
+
*/
|
|
235
|
+
var WidgetToolEventSchema = discriminatedUnion("type", [
|
|
236
|
+
WidgetChatCardsEventSchema,
|
|
237
|
+
WidgetChatEscalatedEventSchema,
|
|
238
|
+
WidgetChatCheckoutEventSchema,
|
|
239
|
+
WidgetChatAddToCartEventSchema
|
|
240
|
+
]);
|
|
241
|
+
/**
|
|
242
|
+
* ## Storefront reports — the OTHER direction, and why they are not messages
|
|
243
|
+
*
|
|
244
|
+
* A chat request carries EITHER a shopper `message` or a `report`: a typed
|
|
245
|
+
* statement of something the STOREFRONT did, which the shopper never typed.
|
|
246
|
+
* Today there is exactly one kind, `cart_add`, sent by
|
|
247
|
+
* `@saar-ai/web-widget`'s `ConciergeWidget` the moment a bridge add resolves,
|
|
248
|
+
* so the concierge can answer with something that goes WITH the item.
|
|
249
|
+
*
|
|
250
|
+
* It replaced a free-text `Added <title> to cart` sentence sent over the
|
|
251
|
+
* ordinary shopper message channel, which had three defects a shape fixes:
|
|
252
|
+
* a shopper who TYPED those words got the storefront's treatment; the
|
|
253
|
+
* synthetic sentence persisted as a shopper line in the operator's
|
|
254
|
+
* transcript; and the server matched it by its exact wording, so any change
|
|
255
|
+
* to how a card renders a title broke the match with nothing failing.
|
|
256
|
+
*
|
|
257
|
+
* **The sentence the model sees is composed SERVER-side** from these fields
|
|
258
|
+
* (`apps/api/src/widget/widget-chat.service.ts`'s
|
|
259
|
+
* `composeStorefrontReportText`) — the client no longer authors any part of
|
|
260
|
+
* the model's input, which is what makes shopper prose and a storefront
|
|
261
|
+
* report structurally impossible to confuse.
|
|
262
|
+
*
|
|
263
|
+
* **Still client-asserted, and that is unchanged.** A report is trusted
|
|
264
|
+
* exactly as far as the chat token that carried it: whoever holds a session
|
|
265
|
+
* can claim an add that never happened, precisely as they could type the old
|
|
266
|
+
* sentence. Cross-verifying a report against the server's own
|
|
267
|
+
* `CheckoutHandoffService.recordCartAdd` record is explicitly out of scope —
|
|
268
|
+
* the win here is typing, non-collision with shopper prose, and a turn the
|
|
269
|
+
* console can tell apart, not a new trust boundary.
|
|
270
|
+
*/
|
|
271
|
+
var REPORT_TITLE_MAX = CARD_TEXT_MAX;
|
|
272
|
+
/** A single add-to-cart press. Bounded so a report can never claim a basket-sized quantity. */
|
|
273
|
+
var REPORT_QUANTITY_MAX = 999;
|
|
274
|
+
/**
|
|
275
|
+
* The storefront reporting a completed add. `title` is the card's own
|
|
276
|
+
* display title (what the shopper saw); the ids are the catalog's, carried
|
|
277
|
+
* so a later consumer can join the report to a product without re-matching
|
|
278
|
+
* on prose.
|
|
279
|
+
*/
|
|
280
|
+
var WidgetCartAddReportSchema = object({
|
|
281
|
+
kind: literal("cart_add"),
|
|
282
|
+
/**
|
|
283
|
+
* Trimmed before it is bounded, so a whitespace-only title is a
|
|
284
|
+
* rejection rather than a report that names nothing: the server trims
|
|
285
|
+
* the title again when it composes its line, and `min(1)` on the raw
|
|
286
|
+
* string would let `" "` through to `added ""`.
|
|
287
|
+
*/
|
|
288
|
+
title: string().trim().min(1).max(REPORT_TITLE_MAX),
|
|
289
|
+
quantity: number().int().min(1).max(REPORT_QUANTITY_MAX),
|
|
290
|
+
/** The INTERNAL catalog UUID — same field, same meaning, as {@link WidgetChatCardSchema}'s. */
|
|
291
|
+
variantId: string().min(1).max(ID_MAX).optional(),
|
|
292
|
+
productId: string().min(1).max(ID_MAX).optional()
|
|
293
|
+
}).strict();
|
|
294
|
+
/**
|
|
295
|
+
* The storefront reporting an add that DID NOT happen — the mirror of
|
|
296
|
+
* {@link WidgetCartAddReportSchema}, and the only way the concierge can learn
|
|
297
|
+
* it was wrong about an add it asked for itself.
|
|
298
|
+
*
|
|
299
|
+
* ## Why this kind has to exist
|
|
300
|
+
*
|
|
301
|
+
* `add_to_cart` (`apps/api/src/catalog/tools/add-to-cart.tool.ts`) returns
|
|
302
|
+
* `status: 'requested'` and can never return more: the cart lives in the
|
|
303
|
+
* shopper's browser, behind their own session cookie, and the server has no
|
|
304
|
+
* handle on it. The add is performed afterwards by `@saar-ai/web-widget`'s
|
|
305
|
+
* `ConciergeWidget` (`performAgentCartAdd`), and when the host bridge rejects
|
|
306
|
+
* it — a sold-out variant, a 422, no `window` bridge registered at all — the
|
|
307
|
+
* widget is the ONLY party that knows. On a voice call the shopper cannot see
|
|
308
|
+
* the widget's status line either, so without this report the failure is
|
|
309
|
+
* structurally invisible to everyone in the conversation.
|
|
310
|
+
*
|
|
311
|
+
* ## What it is NOT
|
|
312
|
+
*
|
|
313
|
+
* Not `cart_add` with a flag. A discriminated union forces every consumer
|
|
314
|
+
* that switches on `kind` to handle this or fall through to its degraded
|
|
315
|
+
* branch — the server's sentence composer, the console's row summary — where
|
|
316
|
+
* a boolean somebody forgot to read would render a failure as an add.
|
|
317
|
+
*
|
|
318
|
+
* And deliberately NO `quantity`: nothing was added, so there is no number of
|
|
319
|
+
* units to state, and a quantity on a failure is the one field a model could
|
|
320
|
+
* read as "this much DID go in". `.strict()` is what enforces the absence.
|
|
321
|
+
*/
|
|
322
|
+
var WidgetCartAddFailedReportSchema = object({
|
|
323
|
+
kind: literal("cart_add_failed"),
|
|
324
|
+
/**
|
|
325
|
+
* The card's own display title — trimmed and bounded exactly as
|
|
326
|
+
* {@link WidgetCartAddReportSchema}'s, and for the same reasons.
|
|
327
|
+
*/
|
|
328
|
+
title: string().trim().min(1).max(REPORT_TITLE_MAX),
|
|
329
|
+
/** The INTERNAL catalog UUID — same field, same meaning, as {@link WidgetChatCardSchema}'s. */
|
|
330
|
+
variantId: string().min(1).max(ID_MAX).optional(),
|
|
331
|
+
productId: string().min(1).max(ID_MAX).optional()
|
|
332
|
+
}).strict();
|
|
333
|
+
/**
|
|
334
|
+
* Every report kind a chat request may carry — the shape a further kind
|
|
335
|
+
* (`cart_removed`, `checkout_started`) slots into without touching either
|
|
336
|
+
* side's parse code.
|
|
337
|
+
*
|
|
338
|
+
* An OLD API parsing a `cart_add_failed` from a NEW widget rejects it
|
|
339
|
+
* (`parseWidgetChatReport` returns `null`, and the controller answers 400),
|
|
340
|
+
* which the widget's `sendReport` turns into the `false` it already swallows.
|
|
341
|
+
* Deploy skew costs the conversation a correction it never used to get; it
|
|
342
|
+
* costs the shopper nothing, and the widget's own status line still says the
|
|
343
|
+
* add did not land.
|
|
344
|
+
*/
|
|
345
|
+
var WidgetChatReportSchema = discriminatedUnion("kind", [WidgetCartAddReportSchema, WidgetCartAddFailedReportSchema]);
|
|
346
|
+
/**
|
|
347
|
+
* Parse a request body's `report` field. Never throws — the caller decides
|
|
348
|
+
* whether `null` means "absent" (no report was sent) or "malformed", which
|
|
349
|
+
* `apps/api`'s widget chat controller distinguishes by checking presence
|
|
350
|
+
* first and rejecting a present-but-unparseable value with a 400.
|
|
351
|
+
*/
|
|
352
|
+
function parseWidgetChatReport(value) {
|
|
353
|
+
const parsed = WidgetChatReportSchema.safeParse(value);
|
|
354
|
+
return parsed.success ? parsed.data : null;
|
|
355
|
+
}
|
|
356
|
+
/** Parse a tool's raw output for an optional, well-shaped `widgetEvent`. Never throws. */
|
|
357
|
+
function extractWidgetToolEvent(output) {
|
|
358
|
+
if (typeof output !== "object" || output === null) return null;
|
|
359
|
+
const candidate = output["widgetEvent"];
|
|
360
|
+
if (candidate === void 0) return null;
|
|
361
|
+
const parsed = WidgetToolEventSchema.safeParse(candidate);
|
|
362
|
+
return parsed.success ? parsed.data : null;
|
|
363
|
+
}
|
|
364
|
+
/**
|
|
365
|
+
* Rebuild the `cards` event a curation was streamed as, for replay.
|
|
366
|
+
*
|
|
367
|
+
* **Per-item `safeParse`, not one parse of the whole array.** A catalogue is
|
|
368
|
+
* live: between the turn that curated a product and the reload that replays
|
|
369
|
+
* it, the product can lose its price (a variant deleted), gain an image URL
|
|
370
|
+
* the scheme allowlist refuses, or have its handle rewritten into something
|
|
371
|
+
* {@link WidgetChatCardSchema}'s slug regex will not accept. Parsing the
|
|
372
|
+
* whole array at once would make ONE such row cost the shopper every card in
|
|
373
|
+
* that turn; parsing per item drops only the row that no longer renders. That
|
|
374
|
+
* is the same "degrade, never fabricate" posture the live path already takes
|
|
375
|
+
* for a card with no `platformVariantId`.
|
|
376
|
+
*
|
|
377
|
+
* **Filter first, then cap.** The `MAX_CARDS_PER_EVENT` cap used to be taken
|
|
378
|
+
* as `items.slice(0, MAX)` BEFORE the drops below, so twenty rows that no
|
|
379
|
+
* longer render (a curation whose variants were deleted, leaving every
|
|
380
|
+
* `priceMinor` null) consumed the whole window and hid a perfectly good
|
|
381
|
+
* twenty-first row — the strip came back empty for a turn that had cards to
|
|
382
|
+
* show. The cap is a bound on what the widget DRAWS, so it belongs on the
|
|
383
|
+
* surviving cards, and every candidate row is now considered. The work that
|
|
384
|
+
* costs is bounded anyway: the rows come from a turn's own curations, each
|
|
385
|
+
* itself capped by `build_curation`'s 24-item input schema.
|
|
386
|
+
*
|
|
387
|
+
* Returns `null` when nothing survives — the caller then replays the turn's
|
|
388
|
+
* TEXT alone, which is strictly better than an empty card strip.
|
|
389
|
+
*/
|
|
390
|
+
function buildWidgetChatCardsEvent(curationId, items) {
|
|
391
|
+
const cards = [];
|
|
392
|
+
for (const item of items) {
|
|
393
|
+
if (item.priceMinor === null || item.currency === null) continue;
|
|
394
|
+
if (item.available !== true) continue;
|
|
395
|
+
const parsed = WidgetChatCardSchema.safeParse({
|
|
396
|
+
productId: item.productId,
|
|
397
|
+
...item.variantId !== null ? { variantId: item.variantId } : {},
|
|
398
|
+
...item.platformVariantId !== null ? { platformVariantId: item.platformVariantId } : {},
|
|
399
|
+
title: item.productTitle,
|
|
400
|
+
...item.productImageUrl !== null ? { imageUrl: item.productImageUrl } : {},
|
|
401
|
+
...item.productHandle !== null ? { handle: item.productHandle } : {},
|
|
402
|
+
priceMinor: item.priceMinor,
|
|
403
|
+
currency: item.currency,
|
|
404
|
+
available: true,
|
|
405
|
+
...item.reason !== null ? { reason: item.reason } : {}
|
|
406
|
+
});
|
|
407
|
+
if (parsed.success) cards.push(parsed.data);
|
|
408
|
+
}
|
|
409
|
+
if (cards.length === 0) return null;
|
|
410
|
+
return {
|
|
411
|
+
type: "cards",
|
|
412
|
+
curationId,
|
|
413
|
+
items: cards.slice(0, MAX_CARDS_PER_EVENT)
|
|
414
|
+
};
|
|
415
|
+
}
|
|
416
|
+
/**
|
|
417
|
+
* ## The cart the widget carries on every chat request
|
|
418
|
+
*
|
|
419
|
+
* The concierge used to learn about the basket ONLY from `cart_add` reports
|
|
420
|
+
* — one per press, and only for adds made through a widget card. It
|
|
421
|
+
* therefore could not answer "what is in my cart" (the storefront's own cart,
|
|
422
|
+
* built before the conversation started, was invisible to it) and a page
|
|
423
|
+
* reload wiped even the adds it had heard about, because the reports were
|
|
424
|
+
* turns and the running basket was never a fact anywhere.
|
|
425
|
+
*
|
|
426
|
+
* So the widget sends the basket it already holds — `ConciergeWidget`'s
|
|
427
|
+
* merged view of `bridge.readCart()` and its own `addedLines`, resolved by
|
|
428
|
+
* the ownership table in `packages/web-widget/AGENTS.md` ("Whose numbers
|
|
429
|
+
* win"), NOT a second rule invented here — as a typed field on every
|
|
430
|
+
* `POST /widget/chat`.
|
|
431
|
+
*
|
|
432
|
+
* ### Trust: CLIENT-ASSERTED, exactly like {@link WidgetCartAddReportSchema}
|
|
433
|
+
*
|
|
434
|
+
* This is a statement the storefront makes, trusted precisely as far as the
|
|
435
|
+
* chat token that carried it. Nothing verifies it: whoever holds a session
|
|
436
|
+
* can claim a basket that does not exist, exactly as they can already claim
|
|
437
|
+
* an add that never happened. It is NOT a stronger claim than the report it
|
|
438
|
+
* sits beside, and it deliberately does not weaken that report's boundary
|
|
439
|
+
* either — no `cart_add` is cross-checked against this snapshot, and this
|
|
440
|
+
* snapshot is never written to a `curations`, `checkout_handoffs` or
|
|
441
|
+
* `cart_attributions` row, nor to any other record of what the shopper
|
|
442
|
+
* actually owns. It exists for the duration of one prompt.
|
|
443
|
+
*
|
|
444
|
+
* What the worst case buys an attacker is a reply that describes a basket
|
|
445
|
+
* they invented, to themselves. The real checkout still resolves against the
|
|
446
|
+
* host's own cart or a server-built permalink
|
|
447
|
+
* (`apps/api/src/catalog/checkout-permalink.ts`), neither of which reads
|
|
448
|
+
* this field.
|
|
449
|
+
*
|
|
450
|
+
* ### The ACCEPTED cost, written down rather than argued away
|
|
451
|
+
*
|
|
452
|
+
* The guardrail this field feeds tells the model to answer cart questions
|
|
453
|
+
* from the block and to quote its figures exactly
|
|
454
|
+
* (`WIDGET_CHAT_GUARDRAILS`), which is the one place a wholly
|
|
455
|
+
* client-asserted value is granted prose authority in the merchant's own
|
|
456
|
+
* transcript. So the concierge can be made to state an arbitrary basket, and
|
|
457
|
+
* an arbitrary total, as fact — in a conversation the merchant's operators
|
|
458
|
+
* read back in the console, and that a shopper could screenshot. That is the
|
|
459
|
+
* accepted cost of answering the question at all: the storefront is the only
|
|
460
|
+
* party that knows what is in its own cart, so a concierge that will not
|
|
461
|
+
* repeat what the storefront says is a concierge that cannot answer "what is
|
|
462
|
+
* in my basket" — the exact failure this field was added to fix.
|
|
463
|
+
*
|
|
464
|
+
* Two vectors reach it, and the second is the one that is not obvious:
|
|
465
|
+
*
|
|
466
|
+
* - **A session-token holder.** Whoever holds a chat token can put anything
|
|
467
|
+
* schema-valid on the request. Same boundary as the `cart_add` report;
|
|
468
|
+
* they are lying to themselves.
|
|
469
|
+
* - **A hostile third-party script on the MERCHANT's storefront.** The cart
|
|
470
|
+
* is read through `bridge.readCart()`, a function on the host page. Any
|
|
471
|
+
* other script on that page — an analytics tag, an A/B tool, a
|
|
472
|
+
* compromised dependency — can shadow or wrap it and feed the widget
|
|
473
|
+
* whatever basket it likes, with no access to the shopper's session at
|
|
474
|
+
* all. The victim here is a shopper who did nothing wrong, and the liar
|
|
475
|
+
* is not the shopper. It is bounded by what the block can express (this
|
|
476
|
+
* schema's shape and bounds) and by the fact that nothing downstream
|
|
477
|
+
* reads it — no order, no handoff, no stored record — but the reply it
|
|
478
|
+
* produces is still the store's own voice.
|
|
479
|
+
*
|
|
480
|
+
* Not mitigated, deliberately: verifying it would mean the server keeping
|
|
481
|
+
* its own copy of the host cart, which it has no way to obtain (that is the
|
|
482
|
+
* whole reason `add-to-cart` is an EVENT — see
|
|
483
|
+
* {@link WidgetChatAddToCartEventSchema}). The mitigation that IS in place is
|
|
484
|
+
* provenance: the block names its source and says nothing verified it, so the
|
|
485
|
+
* model attributes the figures to the storefront rather than to the store.
|
|
486
|
+
* `apps/api/AGENTS.md` → "`WidgetChatInput.cart`" carries the same statement
|
|
487
|
+
* on the server side.
|
|
488
|
+
*
|
|
489
|
+
* ### Why a request field and not a periodic snapshot
|
|
490
|
+
*
|
|
491
|
+
* Three transports were considered. A separate `POST /widget/cart` that
|
|
492
|
+
* stores the latest snapshot per session would add an endpoint, a write path
|
|
493
|
+
* and a staleness question ("was the stored cart the one the shopper had when
|
|
494
|
+
* they asked?") for no gain. A periodic push has the same staleness problem
|
|
495
|
+
* plus a timer. A field on the request the model is about to answer is atomic
|
|
496
|
+
* with the question by construction: the cart the model reads is the cart the
|
|
497
|
+
* widget held at the moment the shopper hit send, and there is nothing to
|
|
498
|
+
* reconcile, expire or garbage-collect.
|
|
499
|
+
*
|
|
500
|
+
* That argument is about a TYPED turn and it is unchanged for one. It does not
|
|
501
|
+
* survive contact with a CALL, and `POST /widget/cart` exists now because of
|
|
502
|
+
* that: a caller asks out loud, `apps/agent` assembles the turn, and there is
|
|
503
|
+
* no request of theirs for a field to ride on. The stored snapshot the typed
|
|
504
|
+
* leg did not need is the only thing the spoken leg can have — and its
|
|
505
|
+
* staleness question is answered by pushing on every basket change while a
|
|
506
|
+
* call is live rather than by a timer. See `apps/api`'s
|
|
507
|
+
* `WidgetChatService.recordCart` and `@wesence/agent-core`'s
|
|
508
|
+
* `commerce/shopper-cart.ts`, which is where the RENDERING both legs share now
|
|
509
|
+
* lives (this file still owns the WIRE shape; a widget's contract does not
|
|
510
|
+
* belong in a turn-tier package, and a turn-tier renderer does not belong in a
|
|
511
|
+
* browser bundle).
|
|
512
|
+
*
|
|
513
|
+
* ### Bounded, because a request must be
|
|
514
|
+
*
|
|
515
|
+
* A cart is not unbounded in practice, but the request has to be regardless:
|
|
516
|
+
* {@link MAX_CART_LINES} rows, each with a trimmed, length-capped title and
|
|
517
|
+
* bounded integers, and `.strict()` on both objects so an unknown key is a
|
|
518
|
+
* rejection rather than something that reaches the prompt.
|
|
519
|
+
*
|
|
520
|
+
* ### What is deliberately NOT on a line
|
|
521
|
+
*
|
|
522
|
+
* No product or variant ids. The `cart_add` report carries them so a consumer
|
|
523
|
+
* can join a report to a product without re-matching prose; nothing joins
|
|
524
|
+
* this snapshot to anything — it exists to be READ, in one prompt section, by
|
|
525
|
+
* a model that has no use for a UUID and every reason not to be handed one it
|
|
526
|
+
* might repeat to a shopper.
|
|
527
|
+
*/
|
|
528
|
+
/** Bound on a cart line's display title. Tighter than a card's: fifty of these ride in one prompt section. */
|
|
529
|
+
var CART_LINE_TITLE_MAX = 200;
|
|
530
|
+
/** A basket, not a warehouse. Fifty lines is far past any real storefront cart and still a bounded prompt. */
|
|
531
|
+
var MAX_CART_LINES = 50;
|
|
532
|
+
/** A billion minor units — past any real cart line or subtotal, and far short of where an integer stops being exact. */
|
|
533
|
+
var CART_AMOUNT_MINOR_MAX = 1e9;
|
|
534
|
+
/**
|
|
535
|
+
* One basket row as the storefront reports it. `priceMinor` is the UNIT
|
|
536
|
+
* price in ISO 4217 minor units — the same integer discipline
|
|
537
|
+
* {@link WidgetChatCardSchema} keeps, and for the same reason: a float, or a
|
|
538
|
+
* pre-formatted string, is how a price ends up rendered a hundred times too
|
|
539
|
+
* large (see `apps/api/src/catalog/tools/model-safe-output.ts` for the
|
|
540
|
+
* observed instance of exactly that).
|
|
541
|
+
*/
|
|
542
|
+
var WidgetChatCartLineSchema = object({
|
|
543
|
+
/** Trimmed before it is bounded, so a whitespace-only title is a rejection rather than a line that names nothing — same reasoning as the report's `title`. */
|
|
544
|
+
title: string().trim().min(1).max(CART_LINE_TITLE_MAX),
|
|
545
|
+
quantity: number().int().min(1).max(REPORT_QUANTITY_MAX),
|
|
546
|
+
priceMinor: number().int().min(0).max(CART_AMOUNT_MINOR_MAX)
|
|
547
|
+
}).strict();
|
|
548
|
+
/**
|
|
549
|
+
* Where the lines came from, because it changes what the reply may honestly
|
|
550
|
+
* claim:
|
|
551
|
+
*
|
|
552
|
+
* - `'host'` — the storefront's own cart (`bridge.readCart()` reported
|
|
553
|
+
* `lines`). It is the WHOLE basket, including anything added before this
|
|
554
|
+
* conversation started.
|
|
555
|
+
* - `'widget'` — the widget's own accumulation of adds made through its
|
|
556
|
+
* cards, used when the host reports no `lines` array at all. It is a LOWER
|
|
557
|
+
* BOUND on the basket, and the prompt says so.
|
|
558
|
+
*
|
|
559
|
+
* The distinction is the bridge's own (`CartSnapshot.lines`: absent means
|
|
560
|
+
* "this host does not track lines", empty means "the cart is empty"), carried
|
|
561
|
+
* onto the wire rather than collapsed, so the server never has to guess which
|
|
562
|
+
* of the two it is holding.
|
|
563
|
+
*/
|
|
564
|
+
var WidgetChatCartSourceSchema = _enum(["host", "widget"]);
|
|
565
|
+
var WidgetChatCartSchema = object({
|
|
566
|
+
source: WidgetChatCartSourceSchema,
|
|
567
|
+
/** ISO 4217 currency code, e.g. "AED" — letters only, see {@link WidgetChatCardSchema}'s own `currency`. One per snapshot: the widget already resolves a single currency for the basket it renders. */
|
|
568
|
+
currency: CURRENCY_CODE,
|
|
569
|
+
/** Empty is legal and MEANINGFUL — "the storefront says the cart is empty", which is a different answer from sending no cart at all. */
|
|
570
|
+
lines: array(WidgetChatCartLineSchema).max(50),
|
|
571
|
+
/**
|
|
572
|
+
* The storefront's own total, when it has one. Preferred over anything
|
|
573
|
+
* derived from the lines, because arithmetic on unit prices cannot
|
|
574
|
+
* reproduce discounts or bundle pricing — the same rule
|
|
575
|
+
* `packages/web-widget/AGENTS.md`'s ownership table already states for
|
|
576
|
+
* what the widget RENDERS, kept identical here so the model and the
|
|
577
|
+
* basket drawn under its reply can never disagree.
|
|
578
|
+
*/
|
|
579
|
+
subtotalMinor: number().int().min(0).max(CART_AMOUNT_MINOR_MAX).optional()
|
|
580
|
+
}).strict();
|
|
581
|
+
/**
|
|
582
|
+
* Parse a request body's `cart` field. Never throws — the caller decides
|
|
583
|
+
* whether `null` means "absent" or "malformed", the same split
|
|
584
|
+
* {@link parseWidgetChatReport} leaves to `apps/api`'s widget chat
|
|
585
|
+
* controller.
|
|
586
|
+
*/
|
|
587
|
+
function parseWidgetChatCart(value) {
|
|
588
|
+
const parsed = WidgetChatCartSchema.safeParse(value);
|
|
589
|
+
return parsed.success ? parsed.data : null;
|
|
590
|
+
}
|
|
591
|
+
//#endregion
|
|
592
|
+
export { MAX_CART_LINES, WidgetCartAddFailedReportSchema, WidgetCartAddReportSchema, WidgetChatAddToCartEventSchema, WidgetChatCardSchema, WidgetChatCardsEventSchema, WidgetChatCartLineSchema, WidgetChatCartSchema, WidgetChatCartSourceSchema, WidgetChatCheckoutEventSchema, WidgetChatDoneEventSchema, WidgetChatErrorEventSchema, WidgetChatEscalatedEventSchema, WidgetChatReportSchema, WidgetChatSseEventSchema, WidgetChatTextDeltaEventSchema, WidgetToolEventSchema, buildWidgetChatCardsEvent, extractWidgetToolEvent, parseWidgetChatCart, parseWidgetChatReport };
|