@adminide-stack/clock-tik-browser 12.0.35-alpha.0 → 12.0.36-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/lib/pages/Home/__tests__/connectors.test.d.ts +2 -0
  2. package/lib/pages/Home/__tests__/connectors.test.d.ts.map +1 -0
  3. package/lib/pages/Home/__tests__/history.test.d.ts +2 -0
  4. package/lib/pages/Home/__tests__/history.test.d.ts.map +1 -0
  5. package/lib/pages/Home/__tests__/queue.test.d.ts +2 -0
  6. package/lib/pages/Home/__tests__/queue.test.d.ts.map +1 -0
  7. package/lib/pages/Home/__tests__/results.test.d.ts +2 -0
  8. package/lib/pages/Home/__tests__/results.test.d.ts.map +1 -0
  9. package/lib/pages/Home/chat/ChoresChat.d.ts.map +1 -1
  10. package/lib/pages/Home/chat/ChoresChat.js +409 -88
  11. package/lib/pages/Home/chat/ChoresChat.js.map +1 -1
  12. package/lib/pages/Home/chat/ChoresPanel.d.ts +10 -1
  13. package/lib/pages/Home/chat/ChoresPanel.d.ts.map +1 -1
  14. package/lib/pages/Home/chat/ChoresPanel.js +27 -18
  15. package/lib/pages/Home/chat/ChoresPanel.js.map +1 -1
  16. package/lib/pages/Home/chat/ConnectorsPanel.d.ts +23 -0
  17. package/lib/pages/Home/chat/ConnectorsPanel.d.ts.map +1 -0
  18. package/lib/pages/Home/chat/ConnectorsPanel.js +132 -0
  19. package/lib/pages/Home/chat/ConnectorsPanel.js.map +1 -0
  20. package/lib/pages/Home/chat/HistoryPanel.d.ts +27 -0
  21. package/lib/pages/Home/chat/HistoryPanel.d.ts.map +1 -0
  22. package/lib/pages/Home/chat/HistoryPanel.js +234 -0
  23. package/lib/pages/Home/chat/HistoryPanel.js.map +1 -0
  24. package/lib/pages/Home/chat/ResultCards.d.ts +16 -0
  25. package/lib/pages/Home/chat/ResultCards.d.ts.map +1 -0
  26. package/lib/pages/Home/chat/ResultCards.js +509 -0
  27. package/lib/pages/Home/chat/ResultCards.js.map +1 -0
  28. package/lib/pages/Home/chat/chatTheme.d.ts.map +1 -1
  29. package/lib/pages/Home/chat/chatTheme.js +685 -8
  30. package/lib/pages/Home/chat/chatTheme.js.map +1 -1
  31. package/lib/pages/Home/chat/chores.d.ts +10 -3
  32. package/lib/pages/Home/chat/chores.d.ts.map +1 -1
  33. package/lib/pages/Home/chat/chores.js +22 -5
  34. package/lib/pages/Home/chat/chores.js.map +1 -1
  35. package/lib/pages/Home/chat/connectors.d.ts +37 -0
  36. package/lib/pages/Home/chat/connectors.d.ts.map +1 -0
  37. package/lib/pages/Home/chat/connectors.js +73 -0
  38. package/lib/pages/Home/chat/connectors.js.map +1 -0
  39. package/lib/pages/Home/chat/history.d.ts +51 -0
  40. package/lib/pages/Home/chat/history.d.ts.map +1 -0
  41. package/lib/pages/Home/chat/history.js +186 -0
  42. package/lib/pages/Home/chat/history.js.map +1 -0
  43. package/lib/pages/Home/chat/lucy.d.ts.map +1 -1
  44. package/lib/pages/Home/chat/lucy.js +1 -1
  45. package/lib/pages/Home/chat/lucy.js.map +1 -1
  46. package/lib/pages/Home/chat/queue.d.ts +94 -0
  47. package/lib/pages/Home/chat/queue.d.ts.map +1 -0
  48. package/lib/pages/Home/chat/queue.js +88 -0
  49. package/lib/pages/Home/chat/queue.js.map +1 -0
  50. package/lib/pages/Home/chat/results.d.ts +207 -0
  51. package/lib/pages/Home/chat/results.d.ts.map +1 -0
  52. package/lib/pages/Home/chat/results.js +823 -0
  53. package/lib/pages/Home/chat/results.js.map +1 -0
  54. package/lib/pages/Home/chat/stop.d.ts +7 -6
  55. package/lib/pages/Home/chat/stop.d.ts.map +1 -1
  56. package/lib/pages/Home/chat/stop.js +7 -6
  57. package/lib/pages/Home/chat/stop.js.map +1 -1
  58. package/lib/pages/Home/chat/thread.d.ts +9 -3
  59. package/lib/pages/Home/chat/thread.d.ts.map +1 -1
  60. package/lib/pages/Home/chat/thread.js +14 -5
  61. package/lib/pages/Home/chat/thread.js.map +1 -1
  62. package/lib/pages/Home/chat/tour/tourSteps.d.ts +4 -3
  63. package/lib/pages/Home/chat/tour/tourSteps.d.ts.map +1 -1
  64. package/lib/pages/Home/chat/tour/tourSteps.js +23 -3
  65. package/lib/pages/Home/chat/tour/tourSteps.js.map +1 -1
  66. package/lib/pages/Home/chat/useChores.d.ts +5 -0
  67. package/lib/pages/Home/chat/useChores.d.ts.map +1 -1
  68. package/lib/pages/Home/chat/useChores.js +4 -1
  69. package/lib/pages/Home/chat/useChores.js.map +1 -1
  70. package/package.json +3 -3
@@ -0,0 +1,823 @@
1
+ /**
2
+ * Lucy's search results as cards, the way the Yantra app shows them. Yantra's chat tells the agent to
3
+ * add one fenced `yantra:widget` block whenever a reply lists flights (or stays, cars, trains) or
4
+ * products to choose from (yantra-app `features/chat/result-cards/resultsCardContext.ts`), and draws a
5
+ * card from it. This chat asks for the same block (RESULT_CARDS_PROMPT, sent with Lucy's system
6
+ * prompt) and keeps what it carries: the kit's parseChatWidget strips every envelope but draws only
7
+ * media, so a `travel` or `shopping` block used to vanish, and the results with it.
8
+ *
9
+ * Each reply's result blocks come out of its words here (takeResults) and become the cards' view
10
+ * models: the copy, the badges, the links and the reply a tap sends are all decided in this file, so
11
+ * the tests pin them. ResultCards.tsx only draws them.
12
+ *
13
+ * Input shapes follow the agent's widget attachments as Yantra's cards read them (yantra-app
14
+ * `result-cards/resultCardModels.ts`): a `travel` offer carries `flight` as `@admin-layout/client`'s
15
+ * TravelFlightDetails (slices with airport-local `departAt` / `arriveAt`, never moved to the viewer's
16
+ * zone, and `connections` for the stops on the way); a stay, car or train has no `flight`; a
17
+ * `shopping` item is a result row. Every field is optional: a card shows what arrived. Kept free of
18
+ * the kit, so Jest can load it.
19
+ */
20
+ /** The widget kinds this chat draws; any other envelope (media, …) stays in the words for the kit. */
21
+ const RESULT_COMPONENTS = new Set(['travel', 'shopping']);
22
+ /** Models default to a `json` fence over `yantra:widget`, so both are read, as the kit and Yantra read them. */
23
+ const WIDGET_FENCE = /```(yantra:widget|json)\s*([\s\S]*?)```/gi;
24
+ /** The `yantra:widget` marker on its own line, however the model dressed it (the kit's rule). */
25
+ const BARE_MARKER = /(^|\n)[ \t]*(?:#{1,6}[ \t]*)?[*_`]{0,3}[ \t]*yantra:widget[ \t]*[*_`:]{0,3}[ \t]*\r?\n+/gi;
26
+ /** An opening fence between a bare marker and its object. */
27
+ const OPENING_FENCE = /^[ \t]*```[a-z:]*[ \t]*\r?\n/i;
28
+ /** An envelope dropped in the words with no fence, located by its own key. */
29
+ const BARE_ENVELOPE = /\{\s*"propsComponent"/g;
30
+ const isRecord = value => Boolean(value) && typeof value === 'object' && !Array.isArray(value);
31
+ /** JSON as a model writes it, forgiving a trailing comma before a closing bracket. */
32
+ function parseJson(body) {
33
+ const trimmed = body.trim();
34
+ try {
35
+ return JSON.parse(trimmed);
36
+ } catch {
37
+ // Below.
38
+ }
39
+ try {
40
+ return JSON.parse(trimmed.replace(/,(\s*[}\]])/g, '$1'));
41
+ } catch {
42
+ return undefined;
43
+ }
44
+ }
45
+ /** A travel or shopping envelope's payload; null for any other envelope or for plain JSON. */
46
+ function resultWidget(parsed) {
47
+ if (!isRecord(parsed) || typeof parsed.propsComponent !== 'string') return null;
48
+ const component = parsed.propsComponent.trim().toLowerCase();
49
+ if (!RESULT_COMPONENTS.has(component)) return null;
50
+ const config = parsed.propsConfiguration;
51
+ const contents = isRecord(config) ? config.contents : undefined;
52
+ const nested = isRecord(contents) ? contents.attachment : undefined;
53
+ // The canonical path, tolerating the flatter `attachment` some replies write (the kit reads both).
54
+ // An envelope with neither still comes out of the words: it simply draws no card.
55
+ const attachment = isRecord(nested) ? nested : isRecord(parsed.attachment) ? parsed.attachment : {};
56
+ return {
57
+ component: component,
58
+ attachment
59
+ };
60
+ }
61
+ /** The `{ … }` starting at `from` (after whitespace only), brace-balanced and string-aware. */
62
+ function objectAt(text, from) {
63
+ const start = text.indexOf('{', from);
64
+ if (start === -1 || !/^\s*$/.test(text.slice(from, start))) return null;
65
+ let depth = 0;
66
+ let inString = false;
67
+ let escaped = false;
68
+ for (let i = start; i < text.length; i += 1) {
69
+ const ch = text[i];
70
+ if (inString) {
71
+ if (escaped) escaped = false;else if (ch === '\\') escaped = true;else if (ch === '"') inString = false;
72
+ continue;
73
+ }
74
+ if (ch === '"') inString = true;else if (ch === '{') depth += 1;else if (ch === '}') {
75
+ depth -= 1;
76
+ if (depth === 0) return {
77
+ start,
78
+ end: i + 1
79
+ };
80
+ }
81
+ }
82
+ return null;
83
+ }
84
+ /**
85
+ * Every result block in a reply, in reply order: a bare marker line with its object (fenced or not,
86
+ * so the marker goes with it), a fenced block, an envelope dropped in the words. Any other envelope
87
+ * is not one of these: the kit takes it.
88
+ */
89
+ function blockSpans(text) {
90
+ const spans = [];
91
+ const taken = at => spans.some(span => at >= span.start && at < span.end);
92
+ for (const marker of text.matchAll(BARE_MARKER)) {
93
+ const start = (marker.index ?? 0) + (marker[1] ?? '').length;
94
+ if (taken(start)) continue;
95
+ const afterMarker = (marker.index ?? 0) + marker[0].length;
96
+ const fence = OPENING_FENCE.exec(text.slice(afterMarker));
97
+ const object = objectAt(text, afterMarker + (fence ? fence[0].length : 0));
98
+ if (!object) continue;
99
+ const widget = resultWidget(parseJson(text.slice(object.start, object.end)));
100
+ if (!widget) continue;
101
+ // The closing fence goes too, or a stray ``` is left framing nothing (and opens a code block
102
+ // over the rest): a fence under the marker, or the marker itself written as one (the marker
103
+ // rule allows "```yantra:widget"). A stray bracket the model left before it goes with it.
104
+ const opened = fence || /```[ \t]*yantra:widget/i.test(marker[0]);
105
+ const close = opened ? /^[\s{}[\],]*?```/.exec(text.slice(object.end)) : null;
106
+ spans.push({
107
+ start,
108
+ end: object.end + (close ? close[0].length : 0),
109
+ widget
110
+ });
111
+ }
112
+ for (const match of text.matchAll(WIDGET_FENCE)) {
113
+ const start = match.index ?? 0;
114
+ if (taken(start)) continue;
115
+ const body = match[2] ?? '';
116
+ // A stray bracket after the object (a model's slip) still leaves one object to read.
117
+ const object = objectAt(body, 0);
118
+ const parsed = parseJson(body) ?? (object ? parseJson(body.slice(object.start, object.end)) : undefined);
119
+ const widget = resultWidget(parsed);
120
+ if (widget) spans.push({
121
+ start,
122
+ end: start + match[0].length,
123
+ widget
124
+ });
125
+ // A block that is plainly a widget and does not parse is no use to anyone reading: it goes.
126
+ else if (parsed === undefined && (/yantra:widget/i.test(match[1] ?? '') || body.includes('"propsComponent"'))) {
127
+ spans.push({
128
+ start,
129
+ end: start + match[0].length,
130
+ widget: null
131
+ });
132
+ }
133
+ }
134
+ for (const match of text.matchAll(BARE_ENVELOPE)) {
135
+ const at = match.index ?? 0;
136
+ if (taken(at)) continue;
137
+ const object = objectAt(text, at);
138
+ if (!object) continue;
139
+ const widget = resultWidget(parseJson(text.slice(object.start, object.end)));
140
+ if (widget) spans.push({
141
+ start: object.start,
142
+ end: object.end,
143
+ widget
144
+ });
145
+ }
146
+ return spans.sort((a, b) => a.start - b.start);
147
+ }
148
+ /** True when an unclosed ```json body can still turn out to be an envelope. */
149
+ function couldBeEnvelope(body) {
150
+ const compact = body.replace(/\s+/g, '');
151
+ const key = '{"propsComponent"';
152
+ return compact === '' || key.startsWith(compact) || compact.startsWith(key) || compact.includes('"propsComponent"');
153
+ }
154
+ /** A blank line, then a line no JSON could go on with: words added after a block that broke off. */
155
+ const WORDS_AFTER = /\n[ \t]*\n(?=[ \t]*[^\s{}[\]",:\d.-])/g;
156
+ /**
157
+ * A result block still being written, so a streaming reply never shows its raw JSON: an unclosed
158
+ * widget fence, a fence label or a marker line still coming in, a bare marker or envelope whose
159
+ * object is not closed yet. It runs to the end of the reply, or to the first paragraph after it that
160
+ * is not JSON: a reply that broke off inside a block and then had a note added (Stopped, a failure)
161
+ * keeps the note. null when there is none.
162
+ */
163
+ function unfinishedSpan(text) {
164
+ const starts = [];
165
+ // A fence or a marker opens a line; one named in the middle of a sentence is just words.
166
+ const fence = /(^|\n)[ \t]*```(yantra:widget|json)(?![\w:])\s*((?:(?!```)[\s\S])*)$/i.exec(text);
167
+ if (fence && (/yantra:widget/i.test(fence[2]) || couldBeEnvelope(fence[3]))) {
168
+ starts.push(fence.index + fence[1].length);
169
+ }
170
+ const label = /(^|\n)[ \t]*```([a-z:]{1,12})$/i.exec(text);
171
+ if (label) {
172
+ const typed = label[2].toLowerCase();
173
+ if ('yantra:widget'.startsWith(typed) || 'json'.startsWith(typed)) starts.push(label.index + label[1].length);
174
+ }
175
+ const typing = /(^|\n)[ \t]*(?:#{1,6}[ \t]*)?[*_`]{0,3}[ \t]*(yantra:[a-z]*)[ \t]*[*_`:]{0,3}[ \t]*$/i.exec(text);
176
+ if (typing && 'yantra:widget'.startsWith(typing[2].toLowerCase())) starts.push(typing.index + typing[1].length);
177
+ let lastMarker = null;
178
+ for (const marker of text.matchAll(BARE_MARKER)) lastMarker = marker;
179
+ if (lastMarker) {
180
+ const afterMarker = (lastMarker.index ?? 0) + lastMarker[0].length;
181
+ const tail = text.slice(afterMarker).replace(OPENING_FENCE, '');
182
+ if ((tail.trim() === '' || tail.trimStart().startsWith('{')) && !objectAt(tail, 0)) {
183
+ starts.push((lastMarker.index ?? 0) + (lastMarker[1] ?? '').length);
184
+ }
185
+ }
186
+ for (const match of text.matchAll(BARE_ENVELOPE)) {
187
+ if (!objectAt(text, match.index ?? 0)) starts.push(match.index ?? 0);
188
+ }
189
+ const brace = text.lastIndexOf('{');
190
+ if (brace !== -1) {
191
+ const tail = text.slice(brace).replace(/\s+/g, '');
192
+ if (tail.length >= 2 && '{"propsComponent"'.startsWith(tail)) starts.push(brace);
193
+ }
194
+ if (!starts.length) return null;
195
+ const start = Math.min(...starts);
196
+ WORDS_AFTER.lastIndex = start;
197
+ const after = WORDS_AFTER.exec(text);
198
+ return {
199
+ start,
200
+ end: after ? after.index : text.length
201
+ };
202
+ }
203
+ /**
204
+ * Takes Lucy's travel and shopping blocks out of a reply: fenced, under a bare marker line, or bare.
205
+ * Any other envelope is left for the kit (media.ts draws its pictures). A reply with none comes back
206
+ * as the very same string.
207
+ */
208
+ function takeResultWidgets(content) {
209
+ if (!content || !(content.includes('```') || content.includes('{') || /yantra:/i.test(content))) {
210
+ return {
211
+ content,
212
+ widgets: []
213
+ };
214
+ }
215
+ // The words before a cut lose the spaces that led up to the block.
216
+ const before = words => words.replace(/[ \t]+$/, '');
217
+ const widgets = [];
218
+ let rest = content;
219
+ const spans = blockSpans(content);
220
+ if (spans.length) {
221
+ let cut = '';
222
+ let at = 0;
223
+ for (const span of spans) {
224
+ if (span.start < at) continue;
225
+ cut += before(content.slice(at, span.start));
226
+ at = span.end;
227
+ if (span.widget) widgets.push(span.widget);
228
+ }
229
+ rest = cut + content.slice(at);
230
+ }
231
+ const unfinished = unfinishedSpan(rest);
232
+ if (unfinished) rest = before(rest.slice(0, unfinished.start)) + rest.slice(unfinished.end);
233
+ if (rest === content) return {
234
+ content,
235
+ widgets
236
+ };
237
+ // A block leaves the blank lines that framed it.
238
+ return {
239
+ content: rest.replace(/^[ \t]+$/gm, '').replace(/\n{3,}/g, '\n\n').trim(),
240
+ widgets
241
+ };
242
+ }
243
+ // ─── Formatting ──────────────────────────────────────────────────────────
244
+ const text = (value, max = 160) => {
245
+ if (typeof value !== 'string') return undefined;
246
+ const clean = value.replace(/\s+/g, ' ').trim();
247
+ if (!clean) return undefined;
248
+ return clean.length > max ? `${clean.slice(0, max - 1).trimEnd()}…` : clean;
249
+ };
250
+ const num = value => typeof value === 'number' && Number.isFinite(value) ? value : undefined;
251
+ /** "$435" from (435, "USD"); the agent's own label wins when it sent one. */
252
+ function formatAmount(value, currency, label) {
253
+ const given = text(label, 24);
254
+ if (given) return given;
255
+ const parsed = typeof value === 'string' && /\d/.test(value) ? Number(value.replace(/[^0-9.-]/g, '')) : undefined;
256
+ const amount = num(value) ?? parsed;
257
+ if (amount === undefined || !Number.isFinite(amount) || amount < 0) return undefined;
258
+ const whole = Number.isInteger(amount);
259
+ const code = text(currency, 8)?.toUpperCase();
260
+ if (code && /^[A-Z]{3}$/.test(code)) {
261
+ try {
262
+ return new Intl.NumberFormat('en-US', {
263
+ style: 'currency',
264
+ currency: code,
265
+ minimumFractionDigits: whole ? 0 : 2,
266
+ maximumFractionDigits: whole ? 0 : 2
267
+ }).format(amount);
268
+ } catch {
269
+ // An unknown code: the plain number below.
270
+ }
271
+ }
272
+ return amount.toLocaleString('en-US', {
273
+ maximumFractionDigits: 2
274
+ });
275
+ }
276
+ /** "10:00 PM" from an airport-local "2026-12-12T22:00": the wall clock as written. */
277
+ function wallClock(iso) {
278
+ const m = typeof iso === 'string' ? iso.match(/T(\d{2}):(\d{2})/) : null;
279
+ if (!m || Number(m[1]) > 23 || Number(m[2]) > 59) return undefined;
280
+ // Newer ICU puts a narrow no-break space before AM/PM; a plain one reads the same everywhere,
281
+ // and the reply a tap sends stays plain text.
282
+ return new Date(Date.UTC(2000, 0, 1, Number(m[1]), Number(m[2]))).toLocaleTimeString('en-US', {
283
+ hour: 'numeric',
284
+ minute: '2-digit',
285
+ timeZone: 'UTC'
286
+ }).replace(/[\u202f\u00a0]/g, ' ');
287
+ }
288
+ function datePart(iso) {
289
+ const m = typeof iso === 'string' ? iso.match(/^(\d{4})-(\d{2})-(\d{2})/) : null;
290
+ if (!m) return undefined;
291
+ const parts = [Number(m[1]), Number(m[2]), Number(m[3])];
292
+ return parts[1] >= 1 && parts[1] <= 12 && parts[2] >= 1 && parts[2] <= 31 ? parts : undefined;
293
+ }
294
+ /** "Sat, Dec 12" for the date an ISO string names, whatever the viewer's zone. */
295
+ function dateLabel(iso) {
296
+ const parts = datePart(iso);
297
+ if (!parts) return undefined;
298
+ return new Date(Date.UTC(parts[0], parts[1] - 1, parts[2])).toLocaleDateString('en-US', {
299
+ weekday: 'short',
300
+ month: 'short',
301
+ day: 'numeric',
302
+ timeZone: 'UTC'
303
+ });
304
+ }
305
+ /**
306
+ * "+1" when a flight lands on a later calendar day than it left, "-1" when it lands on the day
307
+ * before (west to east over the date line).
308
+ */
309
+ function dayOffset(departAt, arriveAt) {
310
+ const from = datePart(departAt);
311
+ const to = datePart(arriveAt);
312
+ if (!from || !to) return undefined;
313
+ const days = Math.round((Date.UTC(to[0], to[1] - 1, to[2]) - Date.UTC(from[0], from[1] - 1, from[2])) / 86_400_000);
314
+ if (days > 0 && days < 4) return `+${days}`;
315
+ return days < 0 && days > -3 ? String(days) : undefined;
316
+ }
317
+ /** "28h 10m", "45m", "3h". */
318
+ function durationLabel(minutes) {
319
+ const value = num(minutes);
320
+ const total = value === undefined ? 0 : Math.round(value);
321
+ if (total <= 0) return undefined;
322
+ const h = Math.floor(total / 60);
323
+ const m = total % 60;
324
+ if (!h) return `${m}m`;
325
+ return m ? `${h}h ${m}m` : `${h}h`;
326
+ }
327
+ function stopsLabel(stops) {
328
+ if (stops === undefined || !Number.isFinite(stops) || stops < 0) return undefined;
329
+ if (stops === 0) return 'Nonstop';
330
+ return stops === 1 ? '1 stop' : `${stops} stops`;
331
+ }
332
+ /** "21.5K" for 21500 reviews. */
333
+ function compactCount(count) {
334
+ const value = num(count);
335
+ if (value === undefined || value <= 0) return undefined;
336
+ return new Intl.NumberFormat('en-US', {
337
+ notation: 'compact',
338
+ maximumFractionDigits: 1
339
+ }).format(value);
340
+ }
341
+ /**
342
+ * A link worth opening: http(s) only, so a `javascript:` or `data:` value never reaches an href. A
343
+ * long one is kept whole or not at all: a clipped link goes nowhere.
344
+ */
345
+ function safeLink(value) {
346
+ const raw = typeof value === 'string' ? value.trim() : '';
347
+ if (!raw || raw.length > 4096 || !/^https?:\/\//i.test(raw)) return undefined;
348
+ try {
349
+ const url = new URL(raw);
350
+ return url.protocol === 'https:' || url.protocol === 'http:' ? url.href : undefined;
351
+ } catch {
352
+ return undefined;
353
+ }
354
+ }
355
+ /** An image worth loading: https only, so the page never loads one in the clear. */
356
+ function safeImage(value) {
357
+ const link = safeLink(value);
358
+ return link?.startsWith('https://') ? link : undefined;
359
+ }
360
+ const HOSTNAME_RE = /^(?=.{3,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,24}$/;
361
+ /** A bare hostname from a domain or URL; undefined when it is not one. */
362
+ function cleanDomain(raw) {
363
+ const host = text(raw, 2048)?.toLowerCase().replace(/^[a-z]+:\/\//, '').replace(/^www\./, '').split(/[/?#:]/)[0];
364
+ return host && HOSTNAME_RE.test(host) ? host : undefined;
365
+ }
366
+ const FAVICON_SERVICE = 'https://www.google.com/s2/favicons';
367
+ /** The site icon for a hostname, from the favicon service Yantra's cards use. */
368
+ function faviconUrl(domain) {
369
+ return `${FAVICON_SERVICE}?domain=${encodeURIComponent(domain)}&sz=64`;
370
+ }
371
+ /**
372
+ * True for the favicon service's stand-in: a site it has no icon for comes back as a 16px globe
373
+ * behind a 404 the page cannot see. Real icons asked for at 64px come back at 32px or more.
374
+ */
375
+ function isFallbackFavicon(image) {
376
+ return image.src.startsWith(FAVICON_SERVICE) && image.naturalWidth > 0 && image.naturalWidth <= 16;
377
+ }
378
+ /** A brand's mark: an explicit https image, else its site's icon, else nothing (the card draws a monogram). */
379
+ function brandLogo(logo, domain) {
380
+ const image = safeImage(logo);
381
+ if (image) return image;
382
+ const host = cleanDomain(domain);
383
+ return host ? faviconUrl(host) : undefined;
384
+ }
385
+ /** Up to two letters for a brand tile: a flight number's carrier code, else the name's initials. */
386
+ function monogram(name, flightNumber) {
387
+ const code = flightNumber?.match(/^\s*([A-Z0-9]{2})\s*\d/i)?.[1];
388
+ if (code) return code.toUpperCase();
389
+ const words = name.replace(/[^\p{L}\p{N}\s]/gu, ' ').split(/\s+/).filter(Boolean);
390
+ return (words.length > 1 ? words[0][0] + words[1][0] : (words[0] ?? '?').slice(0, 2)).toUpperCase();
391
+ }
392
+ // Common carriers' sites, so a row gets the airline's own mark without the agent sending one (Yantra's list).
393
+ const AIRLINE_DOMAINS = {
394
+ akasaair: 'akasaair.com',
395
+ akasa: 'akasaair.com',
396
+ indigo: 'goindigo.in',
397
+ airindia: 'airindia.com',
398
+ airindiaexpress: 'airindiaexpress.com',
399
+ spicejet: 'spicejet.com',
400
+ vistara: 'airvistara.com',
401
+ allianceair: 'allianceair.in',
402
+ starair: 'starair.in',
403
+ emirates: 'emirates.com',
404
+ qatarairways: 'qatarairways.com',
405
+ etihad: 'etihad.com',
406
+ etihadairways: 'etihad.com',
407
+ singaporeairlines: 'singaporeair.com',
408
+ lufthansa: 'lufthansa.com',
409
+ britishairways: 'britishairways.com',
410
+ united: 'united.com',
411
+ unitedairlines: 'united.com',
412
+ delta: 'delta.com',
413
+ deltaairlines: 'delta.com',
414
+ americanairlines: 'aa.com',
415
+ jetblue: 'jetblue.com',
416
+ southwest: 'southwest.com',
417
+ southwestairlines: 'southwest.com',
418
+ alaskaairlines: 'alaskaair.com',
419
+ aircanada: 'aircanada.com',
420
+ ana: 'ana.co.jp',
421
+ allnipponairways: 'ana.co.jp',
422
+ jal: 'jal.co.jp',
423
+ japanairlines: 'jal.co.jp',
424
+ cathaypacific: 'cathaypacific.com',
425
+ thaiairways: 'thaiairways.com',
426
+ turkishairlines: 'turkishairlines.com',
427
+ klm: 'klm.com',
428
+ airfrance: 'airfrance.com',
429
+ ryanair: 'ryanair.com',
430
+ easyjet: 'easyjet.com',
431
+ qantas: 'qantas.com',
432
+ virginatlantic: 'virginatlantic.com',
433
+ frontier: 'flyfrontier.com',
434
+ frontierairlines: 'flyfrontier.com',
435
+ spirit: 'spirit.com',
436
+ spiritairlines: 'spirit.com'
437
+ };
438
+ function airlineDomain(airline) {
439
+ return airline ? AIRLINE_DOMAINS[airline.toLowerCase().replace(/[^a-z]/g, '')] : undefined;
440
+ }
441
+ const GOOGLE_FLIGHTS = 'https://www.google.com/travel/flights';
442
+ /**
443
+ * Google Flights opened on a route and day: its `q` reads "Flights from BLR to ATL on 2026-12-12 one
444
+ * way" (or "... through 2026-12-19") into the from, to, dates and trip type.
445
+ */
446
+ function flightSearchUrl(from, to, departDate, returnDate) {
447
+ const trip = returnDate ? `through ${returnDate}` : 'one way';
448
+ return `${GOOGLE_FLIGHTS}?q=${encodeURIComponent(`Flights from ${from} to ${to} on ${departDate} ${trip}`)}`;
449
+ }
450
+ const isoDay = iso => typeof iso === 'string' ? iso.match(/^\d{4}-\d{2}-\d{2}/)?.[0] : undefined;
451
+ const airport = value => {
452
+ const code = text(value, 8)?.toUpperCase();
453
+ return code && /^[A-Z0-9]{3,4}$/.test(code) ? code : undefined;
454
+ };
455
+ /** The most rows a card holds; Lucy is asked for up to 8 flights and 6 products. */
456
+ const MOST_ROWS = 8;
457
+ /** A price as a number, from 435 or "$1,204", for comparing offers. */
458
+ function priceValue(value) {
459
+ if (typeof value === 'number') return Number.isFinite(value) && value >= 0 ? value : undefined;
460
+ if (typeof value !== 'string' || !/\d/.test(value)) return undefined;
461
+ const parsed = Number(value.replace(/[^0-9.]/g, ''));
462
+ return Number.isFinite(parsed) ? parsed : undefined;
463
+ }
464
+ /**
465
+ * The one row holding the lowest value, for its badge: none unless two or more rows say and one alone
466
+ * is lowest. A badge on the only row that said, or on every row of a tie, would tell nothing.
467
+ */
468
+ function soleLowest(values) {
469
+ const known = values.filter(v => v !== undefined);
470
+ if (known.length < 2) return undefined;
471
+ const lowest = Math.min(...known);
472
+ const at = values.flatMap((v, i) => v === lowest ? [i] : []);
473
+ return at.length === 1 ? at[0] : undefined;
474
+ }
475
+ /** Rows that would send the same words also say their place, so Lucy can tell which one was meant. */
476
+ function tellApart(rows) {
477
+ const seen = new Map();
478
+ rows.forEach(row => seen.set(row.reply, (seen.get(row.reply) ?? 0) + 1));
479
+ return rows.map((row, index) => (seen.get(row.reply) ?? 0) > 1 ? {
480
+ ...row,
481
+ reply: `${row.reply.replace(/\.$/, '')}, option ${index + 1}.`,
482
+ action: `${row.action}, option ${index + 1}`
483
+ } : row);
484
+ }
485
+ /** True for a Google Flights page by its host (google.com, google.co.in, …), never a lookalike host. */
486
+ function isGoogleFlights(url) {
487
+ try {
488
+ const {
489
+ hostname,
490
+ pathname
491
+ } = new URL(url);
492
+ return /^(www\.)?google\.(com?\.)?[a-z]{2,3}$/i.test(hostname) && pathname.startsWith('/travel/flights');
493
+ } catch {
494
+ return false;
495
+ }
496
+ }
497
+ function flightLink(url, flight, departAt, returnAt) {
498
+ const name = [flight.airline, flight.flightNumber].filter(Boolean).join(' ');
499
+ if (url) {
500
+ const site = isGoogleFlights(url) ? 'Google Flights' : cleanDomain(url);
501
+ return {
502
+ href: url,
503
+ label: `Book ${name} on ${site ?? 'its site'}`
504
+ };
505
+ }
506
+ const day = isoDay(departAt);
507
+ if (!flight.from || !flight.to || !day) return undefined;
508
+ return {
509
+ href: flightSearchUrl(flight.from, flight.to, day, isoDay(returnAt)),
510
+ label: `Find the ${flight.departs ? `${flight.departs} ` : ''}${name} flight on Google Flights`
511
+ };
512
+ }
513
+ function legOf(slice) {
514
+ const connections = Array.isArray(slice.connections) ? slice.connections.filter(isRecord) : [];
515
+ const stops = num(slice.stops) ?? (connections.length ? connections.length : undefined);
516
+ const via = connections.map(stop => {
517
+ const code = airport(stop.airport);
518
+ if (!code) return undefined;
519
+ const wait = text(stop.layoverDuration, 12);
520
+ return wait ? `${code} ${wait}` : code;
521
+ }).filter(Boolean).join(', ');
522
+ return {
523
+ from: airport(slice.origin),
524
+ to: airport(slice.destination),
525
+ departs: wallClock(slice.departAt),
526
+ arrives: wallClock(slice.arriveAt),
527
+ dayShift: dayOffset(slice.departAt, slice.arriveAt),
528
+ date: dateLabel(slice.departAt),
529
+ duration: durationLabel(slice.durationMinutes),
530
+ stops: stopsLabel(stops),
531
+ ...(stops !== undefined && stops >= 0 ? {
532
+ stopCount: Math.floor(stops)
533
+ } : {}),
534
+ via: via || undefined,
535
+ selfTransfer: connections.some(stop => stop.selfTransfer === true)
536
+ };
537
+ }
538
+ /** "Basic · No checked bag": the fare's name and what it leaves out, as far as the agent said. */
539
+ function fareLine(flight) {
540
+ const brand = text(flight.fareBrand, 32);
541
+ const checked = num(flight.checkedBags);
542
+ const carryOn = num(flight.carryOnBags);
543
+ const bags = checked === 0 ? 'No checked bag' : checked !== undefined && checked > 0 ? `${checked} checked ${checked === 1 ? 'bag' : 'bags'}` : undefined;
544
+ const cabin = carryOn === 0 ? 'No carry-on' : undefined;
545
+ return [brand, bags, cabin].filter(Boolean).join(' · ') || undefined;
546
+ }
547
+ function cabinName(value) {
548
+ const cabin = text(value, 24)?.replace(/_/g, ' ').toLowerCase();
549
+ if (!cabin) return undefined;
550
+ return cabin.charAt(0).toUpperCase() + cabin.slice(1);
551
+ }
552
+ /** The flights in a `travel` block as rows, Lucy's pick first; null when it has none. */
553
+ function toFlightsCard(attachment, key) {
554
+ const offers = (Array.isArray(attachment.properties) ? attachment.properties : []).filter(isRecord).filter(offer => isRecord(offer.flight) && Array.isArray(offer.flight.slices) && offer.flight.slices.some(isRecord)).slice(0, MOST_ROWS);
555
+ if (!offers.length) return null;
556
+ const currency = attachment.currency;
557
+ const prices = [];
558
+ const minutes = [];
559
+ const days = new Set();
560
+ const cabins = new Set();
561
+ let roundTrips = 0;
562
+ const built = offers.map((offer, index) => {
563
+ const flight = offer.flight;
564
+ const slices = flight.slices.filter(isRecord);
565
+ const legs = slices.slice(0, 2).map(legOf);
566
+ if (slices.length > 1) roundTrips += 1;
567
+ const [out] = legs;
568
+ const back = legs[1];
569
+ const airline = text(flight.airline, 48) ?? text(offer.title, 48) ?? 'Flight';
570
+ const flightNumbers = Array.isArray(flight.flightNumbers) ? flight.flightNumbers : [];
571
+ const flightNumber = text(flightNumbers[0], 16);
572
+ const price = formatAmount(offer.price, offer.currency ?? currency, offer.priceLabel);
573
+ prices.push(priceValue(offer.price));
574
+ const legMinutes = slices.slice(0, 2).map(slice => num(slice.durationMinutes));
575
+ minutes.push(legMinutes.every(m => m !== undefined) ? legMinutes.reduce((a, m) => a + m, 0) : undefined);
576
+ days.add(isoDay(slices[0].departAt) ?? '?');
577
+ const cabin = cabinName(flight.cabinClass);
578
+ cabins.add(cabin ?? '?');
579
+ const link = flightLink(safeLink(offer.url), {
580
+ airline,
581
+ flightNumber,
582
+ departs: out.departs,
583
+ from: out.from,
584
+ to: out.to
585
+ }, slices[0].departAt, slices[1]?.departAt);
586
+ const selfTransfer = flight.selfTransfer === true || legs.some(leg => leg.selfTransfer);
587
+ const reply = [`Book the ${out.departs ? `${out.departs} ` : ''}${airline} flight`, flightNumber ? ` ${flightNumber}` : '', out.from && out.to ? ` from ${out.from} to ${out.to}` : '', out.date ? ` on ${out.date}` : '', back?.date ? `, returning ${back.date}` : '', price ? ` (${price})` : '', '.'].join('');
588
+ return {
589
+ key: `${text(offer.id, 64) ?? airline}-${index}`,
590
+ airline,
591
+ logo: brandLogo(flight.airlineLogo, flight.airlineDomain ?? airlineDomain(airline)),
592
+ monogram: monogram(airline, flightNumber),
593
+ ...(flightNumber ? {
594
+ flightNumber
595
+ } : {}),
596
+ legs,
597
+ ...(price ? {
598
+ price
599
+ } : {}),
600
+ ...(fareLine(flight) ? {
601
+ fare: fareLine(flight)
602
+ } : {}),
603
+ selfTransfer,
604
+ badges: [],
605
+ ...(link ? {
606
+ link
607
+ } : {}),
608
+ reply,
609
+ action: reply.replace(/\.$/, '')
610
+ };
611
+ });
612
+ const rows = tellApart(built);
613
+ // Lucy puts the one she recommends first; the cheapest and the quickest are read off the set.
614
+ if (rows.length > 1) {
615
+ rows[0].badges.push('pick');
616
+ const cheapest = soleLowest(prices);
617
+ const fastest = soleLowest(minutes);
618
+ if (cheapest !== undefined) rows[cheapest].badges.push('cheapest');
619
+ if (fastest !== undefined) rows[fastest].badges.push('fastest');
620
+ }
621
+ const first = rows[0].legs[0];
622
+ const oneDay = days.size === 1 && !days.has('?');
623
+ const route = first.from && first.to ? `${first.from} → ${first.to}` : 'Flights';
624
+ const title = text(attachment.title, 80) ?? route;
625
+ const total = Math.max(num(attachment.totalCount) ?? 0, rows.length);
626
+ const dayInTitle = oneDay && first.date ? titleNamesDay(title, first.date) : false;
627
+ const trip = roundTrips === rows.length ? 'Round trip' : roundTrips === 0 ? 'One way' : undefined;
628
+ const cabin = cabins.size === 1 && !cabins.has('?') ? [...cabins][0] : undefined;
629
+ const allNonstop = rows.every(row => row.legs.every(leg => leg.stops === 'Nonstop'));
630
+ const firstOffer = offers[0].flight;
631
+ const firstSlices = firstOffer.slices.filter(isRecord);
632
+ const searchDay = isoDay(firstSlices[0]?.departAt);
633
+ return {
634
+ kind: 'flights',
635
+ key,
636
+ title,
637
+ subtitle: [oneDay && !dayInTitle ? first.date : undefined, `${total} ${total === 1 ? 'flight' : 'flights'}`, trip, cabin, allNonstop ? 'nonstop' : undefined].filter(Boolean).join(' · '),
638
+ rows,
639
+ datedRows: !oneDay,
640
+ ...(first.from && first.to && searchDay ? {
641
+ more: {
642
+ href: flightSearchUrl(first.from, first.to, searchDay, isoDay(firstSlices[1]?.departAt)),
643
+ label: `More ${first.from} to ${first.to} flights on Google Flights`
644
+ }
645
+ } : {})
646
+ };
647
+ }
648
+ const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
649
+ /** True when a title already says the day ("BLR → ATL · Sat, Dec 12", "12 Dec"). */
650
+ function titleNamesDay(title, date) {
651
+ const m = date.match(/([A-Z][a-z]{2}) (\d{1,2})$/);
652
+ if (!m || !MONTHS.includes(m[1])) return false;
653
+ const [, month, day] = m;
654
+ return new RegExp(`\\b${month}[a-z]*\\.? ${day}\\b|\\b${day} ${month}`, 'i').test(title);
655
+ }
656
+ // Connector ids are not a store name a person would read.
657
+ const GENERIC_SOURCES = /^(shopping[-_ ]?search|search|web|chat|yantra.*)$/i;
658
+ function sellerName(item) {
659
+ const name = text(item.sourceLabel, 32) ?? text(item.provider, 32) ?? text(item.source, 32) ?? text(item.operator, 32);
660
+ if (!name || GENERIC_SOURCES.test(name)) return undefined;
661
+ return name.charAt(0).toUpperCase() + name.slice(1);
662
+ }
663
+ const PRICE_UNITS = {
664
+ night: '/ night',
665
+ day: '/ day',
666
+ trip: '/ trip'
667
+ };
668
+ /** "07:10 → 11:45 · 4h 35m · Direct": a train or bus row's times, as the connector writes them flat. */
669
+ function journeyLine(item) {
670
+ const departs = text(item.departTime, 8);
671
+ const arrives = text(item.arriveTime, 8);
672
+ const stops = num(item.stops);
673
+ return [departs && arrives ? `${departs} → ${arrives}` : departs, durationLabel(item.durationMinutes), stops === 0 ? 'Direct' : stops === 1 ? '1 change' : stops ? `${stops} changes` : undefined].filter(Boolean).join(' · ') || undefined;
674
+ }
675
+ function listKind(component, items) {
676
+ if (component === 'shopping') return 'products';
677
+ const kinds = new Set(items.map(item => text(item.kind, 16)?.toLowerCase() ?? ''));
678
+ if (kinds.size !== 1) return 'travel';
679
+ const [kind] = kinds;
680
+ if (kind === 'hotel' || kind === 'stay') return 'stays';
681
+ if (kind === 'car') return 'cars';
682
+ if (kind === 'train') return 'trains';
683
+ if (kind === 'bus') return 'buses';
684
+ return 'travel';
685
+ }
686
+ const LIST_TITLES = {
687
+ products: 'Products',
688
+ stays: 'Stays',
689
+ cars: 'Cars',
690
+ trains: 'Trains',
691
+ buses: 'Buses',
692
+ travel: 'Options'
693
+ };
694
+ /**
695
+ * The products in a `shopping` block, or the stays, cars and trains in a `travel` one (its rows with
696
+ * no `flight`), as list rows with Lucy's pick first; null when there are none. Next to a flights card
697
+ * from the same block, the block's title and count are the flights' own: this card names itself and
698
+ * counts its rows.
699
+ */
700
+ function toListCard(component, attachment, key, nextToFlights = false) {
701
+ const items = (Array.isArray(attachment.properties) ? attachment.properties : []).filter(isRecord).filter(item => !(component === 'travel' && isRecord(item.flight))).filter(item => text(item.title)).slice(0, MOST_ROWS);
702
+ if (!items.length) return null;
703
+ const kind = listKind(component, items);
704
+ const prices = [];
705
+ const built = items.map((item, index) => {
706
+ const title = text(item.title, 140);
707
+ const currency = item.currency ?? attachment.currency;
708
+ const price = formatAmount(item.price, currency, item.priceLabel);
709
+ // The agent's own label says it all; a plain amount gets its unit.
710
+ const priceUnit = price && !text(item.priceLabel) ? PRICE_UNITS[text(item.priceUnit, 8)?.toLowerCase() ?? ''] : undefined;
711
+ const priced = price && priceUnit ? `${price} ${priceUnit}` : price;
712
+ const wasPrice = formatAmount(item.wasPrice, currency, item.wasPriceLabel);
713
+ const rating = num(item.rating);
714
+ const reviews = compactCount(num(item.reviewCount) ?? num(item.reviews));
715
+ const seller = sellerName(item);
716
+ const href = safeLink(item.url);
717
+ prices.push(priceValue(item.price));
718
+ const detail = text(item.note, 90) ?? text(item.detail, 90) ?? (kind === 'trains' || kind === 'buses' ? journeyLine(item) : undefined) ?? text(item.city, 60);
719
+ // The store is in a product's words too: the same thing can be sold in two places at one price.
720
+ const from = seller && kind === 'products' ? ` from ${seller}` : '';
721
+ const reply = kind === 'products' ? `I'll take the ${title}${from}${priced ? ` (${priced})` : ''}.` : `Book ${title}${priced ? ` (${priced})` : ''}.`;
722
+ return {
723
+ key: `${text(item.id, 64) ?? title}-${index}`,
724
+ title,
725
+ ...(safeImage(item.imageUrl) ? {
726
+ imageUrl: safeImage(item.imageUrl)
727
+ } : {}),
728
+ ...(rating !== undefined && rating > 0 && rating <= 5 ? {
729
+ rating: rating.toFixed(1)
730
+ } : {}),
731
+ ...(reviews ? {
732
+ reviews
733
+ } : {}),
734
+ ...(detail ? {
735
+ detail
736
+ } : {}),
737
+ ...(price ? {
738
+ price
739
+ } : {}),
740
+ ...(priceUnit ? {
741
+ priceUnit
742
+ } : {}),
743
+ ...(wasPrice && wasPrice !== price ? {
744
+ wasPrice
745
+ } : {}),
746
+ ...(seller ? {
747
+ seller
748
+ } : {}),
749
+ badges: [],
750
+ ...(href ? {
751
+ link: {
752
+ href,
753
+ label: `Open ${title} on ${seller ?? cleanDomain(href) ?? 'its site'}`
754
+ }
755
+ } : {}),
756
+ reply,
757
+ action: kind === 'products' ? `Choose the ${title}${from}${priced ? `, ${priced}` : ''}` : reply.replace(/\.$/, '')
758
+ };
759
+ });
760
+ const rows = tellApart(built);
761
+ if (rows.length > 1) {
762
+ rows[0].badges.push('pick');
763
+ const cheapest = soleLowest(prices);
764
+ if (cheapest !== undefined) rows[cheapest].badges.push('cheapest');
765
+ }
766
+ const total = nextToFlights ? rows.length : Math.max(num(attachment.totalCount) ?? 0, rows.length);
767
+ const query = text(attachment.query, 80);
768
+ const city = text(attachment.city, 60);
769
+ const store = rows[0].seller;
770
+ const noun = kind === 'products' ? 'result' : kind === 'stays' ? 'stay' : 'option';
771
+ const ownTitle = city && kind === 'stays' ? `Stays in ${city}` : LIST_TITLES[kind];
772
+ return {
773
+ kind,
774
+ key,
775
+ title: nextToFlights ? ownTitle : text(attachment.title, 80) ?? (query ? query.charAt(0).toUpperCase() + query.slice(1) : undefined) ?? ownTitle,
776
+ subtitle: [`${total} ${noun}${total === 1 ? '' : 's'}`, kind === 'products' && store && rows.every(row => row.seller === store) ? `on ${store}` : undefined].filter(Boolean).join(' · '),
777
+ rows
778
+ };
779
+ }
780
+ /** The cards for a reply's result blocks, in the order she wrote them. */
781
+ function resultCards(widgets, keyPrefix = 'result') {
782
+ const cards = [];
783
+ widgets.forEach((widget, index) => {
784
+ const key = `${keyPrefix}-${index}`;
785
+ const flights = widget.component === 'travel' ? toFlightsCard(widget.attachment, `${key}-flights`) : null;
786
+ if (flights) cards.push(flights);
787
+ const list = toListCard(widget.component, widget.attachment, `${key}-list`, Boolean(flights));
788
+ if (list) cards.push(list);
789
+ });
790
+ return cards;
791
+ }
792
+ /** A reply's words, and the cards its result blocks draw. A reply with none comes back as the same string. */
793
+ function takeResults(content, keyPrefix) {
794
+ const taken = takeResultWidgets(content);
795
+ return {
796
+ content: taken.content,
797
+ cards: taken.widgets.length ? resultCards(taken.widgets, keyPrefix) : []
798
+ };
799
+ }
800
+ /**
801
+ * The pick each card already sent, by card: the first message the person sent after the cards (in
802
+ * the order sent) that is one of the card's rows' words - a tap sends exactly those. A card with a
803
+ * pick takes no other; the other cards of the same reply still take theirs.
804
+ */
805
+ function cardPicks(cards, later) {
806
+ const picks = {};
807
+ for (const card of cards) {
808
+ const replies = new Set(card.rows.map(row => row.reply));
809
+ const pick = later.find(message => replies.has(message));
810
+ if (pick) picks[card.key] = pick;
811
+ }
812
+ return picks;
813
+ }
814
+ // ─── What Lucy is asked ──────────────────────────────────────────────────
815
+ /**
816
+ * How to present results so the chat can draw them, appended to Lucy's system prompt. Yantra's chat
817
+ * sends the same note on the turns its router labels travel or shopping (resultsCardContext.ts);
818
+ * this chat has no router, so it rides every session. It only says how to present results when a
819
+ * reply has them. The flight example also shows `connections` (a stop and its wait), which this
820
+ * chat's card draws. Lucy's brief asks for a question card whenever there is a choice to make; the
821
+ * last line keeps her from asking the same choice twice.
822
+ */
823
+ const RESULT_CARDS_PROMPT = ['Result cards: when your reply lists flights (or stays, cars, trains) to choose from, add ONE fenced block so the chat shows them as a card, and keep the prose to what matters - the card carries the details:', '```yantra:widget', '{"propsComponent":"travel","propsConfiguration":{"contents":{"attachment":{"title":"BLR → ATL · Sat, Dec 12","currency":"USD","totalCount":12,"properties":[{"id":"f1","title":"Etihad","price":435,"url":"<booking or search link>","flight":{"airline":"Etihad","flightNumbers":["EY 217","EY 21"],"seller":"Google Flights","cabinClass":"economy","fareBrand":"Basic","checkedBags":0,"slices":[{"origin":"BLR","destination":"ATL","departAt":"2026-12-12T22:00","arriveAt":"2026-12-13T15:40","stops":1,"durationMinutes":1690,"connections":[{"airport":"AUH","layoverDuration":"8h 20m"}]}]}}]}}}}', '```', 'One entry per offer, up to 8, the one you recommend first. Times are the airport’s local time as written, with no zone. A round trip has a second slice for the way back. Mark separate tickets with "selfTransfer": true. Use only real prices, times and links from your results; leave a field out rather than guess, and leave out an offer that looks wrong. A stay, car or train entry has no "flight": give its title, price, priceUnit (night, day or trip), imageUrl, rating, reviewCount and url.', '', 'When your reply lists products to choose from, add ONE fenced block so the chat shows them as a card, and keep the prose to your pick and why:', '```yantra:widget', '{"propsComponent":"shopping","propsConfiguration":{"contents":{"attachment":{"title":"Black tees, size M","query":"black t-shirt size M","currency":"INR","totalCount":24,"properties":[{"title":"Jockey 2714 round-neck tee","price":579,"wasPrice":699,"rating":4.2,"reviews":21500,"note":"Cotton-rich","imageUrl":"<product image>","url":"<product page>","source":"Amazon"}]}}}}', '```', 'Up to 6 entries, the one you recommend first. Use only real prices, ratings, review counts, images and links from your results; leave a field out rather than guess.', '', 'A result card is the choice: the person picks on it (or tells you), so do not also ask which one with a question card. Use a question card only for what the card leaves open, such as dates or a city.'].join('\n');export{RESULT_CARDS_PROMPT,airlineDomain,brandLogo,cardPicks,cleanDomain,compactCount,dateLabel,dayOffset,durationLabel,faviconUrl,flightSearchUrl,formatAmount,isFallbackFavicon,monogram,resultCards,safeImage,safeLink,stopsLabel,takeResultWidgets,takeResults,toFlightsCard,toListCard,wallClock};//# sourceMappingURL=results.js.map