@voicethere/agent 0.5.3 → 0.5.4

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.
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Conversational voice showcase — greeting, name, menu (weather, count, recipe, fun fact).
3
+ *
4
+ * Build:
5
+ * npx @voicethere/agent build --entry templates/voice-showcase/agent.ts
6
+ */
7
+ import {
8
+ agentLog,
9
+ defineAgent,
10
+ parseChatText,
11
+ sendToClient,
12
+ speak,
13
+ type SpeechEvent,
14
+ } from "@voicethere/agent";
15
+
16
+ import {
17
+ createInitialState,
18
+ GREETING,
19
+ handleUtterance,
20
+ resolveWeatherTurn,
21
+ type ConversationState,
22
+ type OutboundMessage,
23
+ } from "./conversation.js";
24
+
25
+ const sessions = new Map<string, ConversationState>();
26
+
27
+ function getState(sessionId: string): ConversationState {
28
+ let state = sessions.get(sessionId);
29
+ if (!state) {
30
+ state = createInitialState();
31
+ sessions.set(sessionId, state);
32
+ }
33
+ return state;
34
+ }
35
+
36
+ function relaySpeechEvent(sessionId: string, event: SpeechEvent): void {
37
+ sendToClient(sessionId, {
38
+ type: "agent_event",
39
+ event: event.type,
40
+ text: event.text,
41
+ raw: event,
42
+ });
43
+ }
44
+
45
+ function deliverMessages(sessionId: string, messages: OutboundMessage[]): void {
46
+ for (const message of messages) {
47
+ sendToClient(sessionId, message);
48
+ }
49
+ }
50
+
51
+ function speakLines(sessionId: string, lines: string[]): void {
52
+ for (const line of lines) {
53
+ speak(sessionId, line);
54
+ }
55
+ }
56
+
57
+ async function applyTurn(
58
+ sessionId: string,
59
+ result: Awaited<ReturnType<typeof handleUtterance>>,
60
+ ): Promise<void> {
61
+ sessions.set(sessionId, result.state);
62
+ speakLines(sessionId, result.speakLines);
63
+ deliverMessages(sessionId, result.messages);
64
+
65
+ if (result.pendingWeather) {
66
+ const weatherResult = await resolveWeatherTurn(
67
+ result.state,
68
+ result.pendingWeather.city,
69
+ result.pendingWeather.country,
70
+ );
71
+ sessions.set(sessionId, weatherResult.state);
72
+ speakLines(sessionId, weatherResult.speakLines);
73
+ deliverMessages(sessionId, weatherResult.messages);
74
+ }
75
+ }
76
+
77
+ async function onUserText(sessionId: string, text: string): Promise<void> {
78
+ const state = getState(sessionId);
79
+ const result = handleUtterance(state, text);
80
+ await applyTurn(sessionId, result);
81
+ }
82
+
83
+ defineAgent({
84
+ onSessionStart({ sessionId }) {
85
+ sessions.set(sessionId, createInitialState());
86
+ sendToClient(sessionId, {
87
+ type: "agent_event",
88
+ event: "session_start",
89
+ sessionId,
90
+ });
91
+ speak(sessionId, GREETING);
92
+ sendToClient(sessionId, { type: "chat_reply", text: GREETING });
93
+ agentLog("info", `voice-showcase session_start ${sessionId}`);
94
+ },
95
+
96
+ onSpeechEvent({ sessionId }, event: SpeechEvent) {
97
+ relaySpeechEvent(sessionId, event);
98
+ },
99
+
100
+ onUserSpeechFinal({ sessionId, text }) {
101
+ void onUserText(sessionId, text);
102
+ },
103
+
104
+ onDataChannelMessage(ctx) {
105
+ const text = parseChatText(ctx.message);
106
+ if (!text) return;
107
+ void onUserText(ctx.sessionId, text);
108
+ },
109
+
110
+ onSessionEnd({ sessionId }) {
111
+ sessions.delete(sessionId);
112
+ sendToClient(sessionId, {
113
+ type: "agent_event",
114
+ event: "session_end",
115
+ sessionId,
116
+ });
117
+ agentLog("info", `voice-showcase session_end ${sessionId}`);
118
+ },
119
+ });
@@ -0,0 +1,520 @@
1
+ /**
2
+ * Pure conversation state machine for the voice-showcase template.
3
+ * Tests import this module directly — no defineAgent dependency.
4
+ */
5
+
6
+ import { formatRecipeSpeech, pickRecipe } from "./recipes.js";
7
+ import { pickFunFact } from "./fun-facts.js";
8
+ import {
9
+ formatWeatherSpeech,
10
+ lookupWeather,
11
+ parseLocationUtterance,
12
+ type FetchFn,
13
+ type WeatherResult,
14
+ } from "./weather.js";
15
+
16
+ export const GREETING =
17
+ "Hi and welcome to the Voicethere voice chat, may I know your name?";
18
+
19
+ export const HUMAN_ESCALATION_REPLY =
20
+ "This is only a showcase conversation and unfortunately there is no human support connected.";
21
+
22
+ export const NAME_DECLINE_REPLY = "OK we will continue without your name";
23
+
24
+ export const MENU_ITEMS = [
25
+ { id: 1, label: "Check the weather" },
26
+ { id: 2, label: "Count" },
27
+ { id: 3, label: "Hear a recipe" },
28
+ { id: 4, label: "Hear a fun fact" },
29
+ ] as const;
30
+
31
+ export const MENU_CHAT_TEXT = `Here is our menu:
32
+ 1. Check the weather
33
+ 2. Count
34
+ 3. Hear a recipe
35
+ 4. Hear a fun fact`;
36
+
37
+ export type ConversationPhase =
38
+ | "listeningForName"
39
+ | "awaitingMenuChoice"
40
+ | "weatherAwaitingLocation"
41
+ | "countAwaitingNumber"
42
+ | "recipeAwaitingChoice";
43
+
44
+ export interface ConversationState {
45
+ phase: ConversationPhase;
46
+ name?: string;
47
+ nameDeclined: boolean;
48
+ weatherCity?: string;
49
+ weatherCountry?: string;
50
+ weatherRetries: number;
51
+ countFailures: number;
52
+ }
53
+
54
+ export interface OutboundMessage {
55
+ type: "chat_reply" | "menu" | "agent_event";
56
+ text?: string;
57
+ event?: string;
58
+ items?: Array<{ id: number; label: string }>;
59
+ sessionId?: string;
60
+ raw?: unknown;
61
+ }
62
+
63
+ export interface ConversationTurnResult {
64
+ state: ConversationState;
65
+ speakLines: string[];
66
+ messages: OutboundMessage[];
67
+ pendingWeather?: { city: string; country?: string };
68
+ }
69
+
70
+ export function createInitialState(): ConversationState {
71
+ return {
72
+ phase: "listeningForName",
73
+ nameDeclined: false,
74
+ weatherRetries: 0,
75
+ countFailures: 0,
76
+ };
77
+ }
78
+
79
+ export function buildMenuMessages(): OutboundMessage[] {
80
+ return [
81
+ { type: "chat_reply", text: MENU_CHAT_TEXT },
82
+ {
83
+ type: "menu",
84
+ items: MENU_ITEMS.map((item) => ({ id: item.id, label: item.label })),
85
+ },
86
+ ];
87
+ }
88
+
89
+ function speakAndChat(text: string): {
90
+ speakLines: string[];
91
+ messages: OutboundMessage[];
92
+ } {
93
+ return {
94
+ speakLines: [text],
95
+ messages: [{ type: "chat_reply", text }],
96
+ };
97
+ }
98
+
99
+ export function isHumanEscalation(utterance: string): boolean {
100
+ const lower = utterance.toLowerCase();
101
+ const patterns = [
102
+ /\bhuman\b/,
103
+ /\boperator\b/,
104
+ /\breal\s+person\b/,
105
+ /\btalk\s+to\s+(?:a\s+)?(?:human|person|someone|agent)\b/,
106
+ /\bcustomer\s+support\b/,
107
+ /\bspeak\s+to\s+(?:a\s+)?(?:human|person|someone|agent)\b/,
108
+ /\bneed\s+(?:a\s+)?(?:human|person|agent)\b/,
109
+ /\bconnect\s+me\s+(?:to|with)\b/,
110
+ /\blive\s+agent\b/,
111
+ /\brepresentative\b/,
112
+ ];
113
+ return patterns.some((p) => p.test(lower));
114
+ }
115
+
116
+ export function isNameDecline(utterance: string): boolean {
117
+ const lower = utterance.toLowerCase().trim();
118
+ const declinePhrases = [
119
+ "i do not want to say my name",
120
+ "i don't want to say my name",
121
+ "i don't want to say",
122
+ "i do not want to say",
123
+ "i'd rather not",
124
+ "id rather not",
125
+ "prefer not",
126
+ "skip",
127
+ "anonymous",
128
+ "none",
129
+ ];
130
+ if (declinePhrases.some((p) => lower.includes(p))) return true;
131
+ if (/\bno\b/i.test(utterance) && !/\bknow\b/i.test(utterance)) {
132
+ const words = lower.split(/\s+/);
133
+ if (words.includes("no")) return true;
134
+ }
135
+ return false;
136
+ }
137
+
138
+ export function extractName(utterance: string): string | null {
139
+ const trimmed = utterance.trim();
140
+ const patterns = [/(?:my name is|i'm|i am|call me)\s+(.+)/i];
141
+ for (const pattern of patterns) {
142
+ const match = trimmed.match(pattern);
143
+ if (match?.[1]) {
144
+ return sanitizeName(match[1]);
145
+ }
146
+ }
147
+ if (trimmed.length > 0 && trimmed.length <= 60) {
148
+ return sanitizeName(trimmed);
149
+ }
150
+ return null;
151
+ }
152
+
153
+ function sanitizeName(raw: string): string {
154
+ let name = raw
155
+ .trim()
156
+ .replace(/[.,!?;:]+$/g, "")
157
+ .trim();
158
+ if (name.length > 40) {
159
+ name = name.slice(0, 40).trim();
160
+ }
161
+ return name;
162
+ }
163
+
164
+ function helloAfterName(state: ConversationState): string {
165
+ if (state.name && !state.nameDeclined) {
166
+ return `Hello, ${state.name}, how can I help you today? I just sent you our menu, what do you want to do?`;
167
+ }
168
+ return "Hello, how can I help you today? I just sent you our menu, what do you want to do?";
169
+ }
170
+
171
+ export function transitionAfterName(
172
+ state: ConversationState,
173
+ name: string | null,
174
+ declined: boolean,
175
+ ): ConversationTurnResult {
176
+ const next: ConversationState = {
177
+ ...state,
178
+ phase: "awaitingMenuChoice",
179
+ nameDeclined: declined,
180
+ name: declined ? undefined : (name ?? undefined),
181
+ };
182
+
183
+ const lines: string[] = [];
184
+ const messages: OutboundMessage[] = [];
185
+
186
+ if (declined) {
187
+ const decline = speakAndChat(NAME_DECLINE_REPLY);
188
+ lines.push(...decline.speakLines);
189
+ messages.push(...decline.messages);
190
+ } else if (name) {
191
+ const thanks = speakAndChat(`Great, thank you ${name}`);
192
+ lines.push(...thanks.speakLines);
193
+ messages.push(...thanks.messages);
194
+ }
195
+
196
+ const hello = speakAndChat(helloAfterName(next));
197
+ lines.push(...hello.speakLines);
198
+ messages.push(...hello.messages);
199
+ messages.push(...buildMenuMessages());
200
+
201
+ return { state: next, speakLines: lines, messages };
202
+ }
203
+
204
+ export type MenuChoice =
205
+ "weather" | "count" | "recipe" | "fun_fact" | "menu" | null;
206
+
207
+ export function parseMenuChoice(utterance: string): MenuChoice {
208
+ const lower = utterance.toLowerCase().trim();
209
+ if (
210
+ /\bmenu\b/.test(lower) ||
211
+ /\bhelp\b/.test(lower) ||
212
+ /\bgo\s+back\b/.test(lower) ||
213
+ /\bstart\s+over\b/.test(lower)
214
+ ) {
215
+ return "menu";
216
+ }
217
+ if (
218
+ lower === "1" ||
219
+ /\bweather\b/.test(lower) ||
220
+ /\bfirst\b/.test(lower) ||
221
+ /\bcheck\s+the\s+weather\b/.test(lower)
222
+ ) {
223
+ return "weather";
224
+ }
225
+ if (lower === "2" || /\bcount\b/.test(lower) || /\bsecond\b/.test(lower)) {
226
+ return "count";
227
+ }
228
+ if (lower === "3" || /\brecipe\b/.test(lower) || /\bthird\b/.test(lower)) {
229
+ return "recipe";
230
+ }
231
+ if (
232
+ lower === "4" ||
233
+ /\bfun\s+fact\b/.test(lower) ||
234
+ /\bfact\b/.test(lower) ||
235
+ /\bfourth\b/.test(lower)
236
+ ) {
237
+ return "fun_fact";
238
+ }
239
+ return null;
240
+ }
241
+
242
+ const WORD_TO_NUMBER: Record<string, number> = {
243
+ one: 1,
244
+ two: 2,
245
+ three: 3,
246
+ four: 4,
247
+ five: 5,
248
+ six: 6,
249
+ seven: 7,
250
+ eight: 8,
251
+ nine: 9,
252
+ ten: 10,
253
+ };
254
+
255
+ export function parseCountNumber(utterance: string): number | null {
256
+ const trimmed = utterance.trim().toLowerCase();
257
+ const digit = trimmed.match(/\b(\d+)\b/);
258
+ if (digit) {
259
+ const n = Number(digit[1]);
260
+ if (Number.isFinite(n)) return n;
261
+ }
262
+ for (const [word, value] of Object.entries(WORD_TO_NUMBER)) {
263
+ if (new RegExp(`\\b${word}\\b`).test(trimmed)) {
264
+ return value;
265
+ }
266
+ }
267
+ return null;
268
+ }
269
+
270
+ export function formatCountingSpeech(n: number): string {
271
+ const parts: string[] = [];
272
+ for (let i = 1; i <= n; i += 1) {
273
+ parts.push(String(i));
274
+ }
275
+ return parts.join(", ");
276
+ }
277
+
278
+ function resendMenu(state: ConversationState): ConversationTurnResult {
279
+ const menu = speakAndChat("Here is the menu again.");
280
+ return {
281
+ state: { ...state, phase: "awaitingMenuChoice" },
282
+ speakLines: menu.speakLines,
283
+ messages: [...menu.messages, ...buildMenuMessages()],
284
+ };
285
+ }
286
+
287
+ function returnToMenu(
288
+ state: ConversationState,
289
+ line: string,
290
+ ): ConversationTurnResult {
291
+ const spoken = speakAndChat(line);
292
+ return {
293
+ state: {
294
+ ...state,
295
+ phase: "awaitingMenuChoice",
296
+ weatherRetries: 0,
297
+ countFailures: 0,
298
+ weatherCity: undefined,
299
+ weatherCountry: undefined,
300
+ },
301
+ speakLines: spoken.speakLines,
302
+ messages: [...spoken.messages, ...buildMenuMessages()],
303
+ };
304
+ }
305
+
306
+ export function handleUtterance(
307
+ state: ConversationState,
308
+ utterance: string,
309
+ ): ConversationTurnResult {
310
+ const text = utterance.trim();
311
+ if (!text) {
312
+ return { state, speakLines: [], messages: [] };
313
+ }
314
+
315
+ if (isHumanEscalation(text)) {
316
+ const reply = speakAndChat(HUMAN_ESCALATION_REPLY);
317
+ return {
318
+ state,
319
+ speakLines: reply.speakLines,
320
+ messages: reply.messages,
321
+ };
322
+ }
323
+
324
+ if (state.phase !== "listeningForName" && parseMenuChoice(text) === "menu") {
325
+ return resendMenu({
326
+ ...state,
327
+ phase: "awaitingMenuChoice",
328
+ weatherRetries: 0,
329
+ countFailures: 0,
330
+ weatherCity: undefined,
331
+ weatherCountry: undefined,
332
+ });
333
+ }
334
+
335
+ switch (state.phase) {
336
+ case "listeningForName": {
337
+ if (isNameDecline(text)) {
338
+ return transitionAfterName(state, null, true);
339
+ }
340
+ const name = extractName(text);
341
+ return transitionAfterName(state, name, false);
342
+ }
343
+
344
+ case "awaitingMenuChoice": {
345
+ const choice = parseMenuChoice(text);
346
+ if (choice === "menu") return resendMenu(state);
347
+ if (choice === "weather") {
348
+ const ask = speakAndChat(
349
+ "Sure. Please tell me a city or ZIP code and the country.",
350
+ );
351
+ return {
352
+ state: {
353
+ ...state,
354
+ phase: "weatherAwaitingLocation",
355
+ weatherRetries: 0,
356
+ weatherCity: undefined,
357
+ weatherCountry: undefined,
358
+ },
359
+ speakLines: ask.speakLines,
360
+ messages: ask.messages,
361
+ };
362
+ }
363
+ if (choice === "count") {
364
+ const ask = speakAndChat(
365
+ "Pick a number from 1 to 10 and I will count up to it.",
366
+ );
367
+ return {
368
+ state: {
369
+ ...state,
370
+ phase: "countAwaitingNumber",
371
+ countFailures: 0,
372
+ },
373
+ speakLines: ask.speakLines,
374
+ messages: ask.messages,
375
+ };
376
+ }
377
+ if (choice === "recipe") {
378
+ const ask = speakAndChat(
379
+ "What do you fancy? Try pasta, soup, breakfast, cookies, or salad.",
380
+ );
381
+ return {
382
+ state: { ...state, phase: "recipeAwaitingChoice" },
383
+ speakLines: ask.speakLines,
384
+ messages: ask.messages,
385
+ };
386
+ }
387
+ if (choice === "fun_fact") {
388
+ const fact = pickFunFact();
389
+ return returnToMenu(state, `Here is a fun fact. ${fact}`);
390
+ }
391
+ const retry = speakAndChat(
392
+ "I did not catch that. Pick 1 through 4 from the menu, or say weather, count, recipe, or fun fact.",
393
+ );
394
+ return {
395
+ state,
396
+ speakLines: retry.speakLines,
397
+ messages: retry.messages,
398
+ };
399
+ }
400
+
401
+ case "weatherAwaitingLocation": {
402
+ const parsed = parseLocationUtterance(text);
403
+ const city = parsed?.city ?? state.weatherCity;
404
+ const country = parsed?.country ?? state.weatherCountry;
405
+
406
+ if (!city) {
407
+ const ask = speakAndChat(
408
+ "Please tell me a city or ZIP code and the country.",
409
+ );
410
+ return {
411
+ state: { ...state, phase: "weatherAwaitingLocation" },
412
+ speakLines: ask.speakLines,
413
+ messages: ask.messages,
414
+ };
415
+ }
416
+
417
+ if (!country && !parsed?.country && !state.weatherCountry) {
418
+ return {
419
+ state: {
420
+ ...state,
421
+ phase: "weatherAwaitingLocation",
422
+ weatherCity: city,
423
+ },
424
+ speakLines: ["Got it. Which country is that in?"],
425
+ messages: [
426
+ { type: "chat_reply", text: "Got it. Which country is that in?" },
427
+ ],
428
+ };
429
+ }
430
+
431
+ const resolvedCountry = country ?? state.weatherCountry;
432
+ return {
433
+ state: { ...state, weatherCity: city, weatherCountry: resolvedCountry },
434
+ speakLines: [],
435
+ messages: [],
436
+ pendingWeather: { city, country: resolvedCountry },
437
+ };
438
+ }
439
+
440
+ case "countAwaitingNumber": {
441
+ const n = parseCountNumber(text);
442
+ if (n === null || n < 1 || n > 10) {
443
+ const failures = state.countFailures + 1;
444
+ if (failures >= 2) {
445
+ return returnToMenu(state, "Sorry, I cannot do this.");
446
+ }
447
+ const retry = speakAndChat(
448
+ "I did not understand you. Please say a number from 1 to 10.",
449
+ );
450
+ return {
451
+ state: { ...state, countFailures: failures },
452
+ speakLines: retry.speakLines,
453
+ messages: retry.messages,
454
+ };
455
+ }
456
+ const counting = formatCountingSpeech(n);
457
+ return returnToMenu(state, `Counting: ${counting}.`);
458
+ }
459
+
460
+ case "recipeAwaitingChoice": {
461
+ const recipe = pickRecipe(text);
462
+ const speech = formatRecipeSpeech(recipe);
463
+ return returnToMenu(state, speech);
464
+ }
465
+
466
+ default:
467
+ return { state, speakLines: [], messages: [] };
468
+ }
469
+ }
470
+
471
+ export function applyWeatherSuccess(
472
+ state: ConversationState,
473
+ weather: WeatherResult,
474
+ ): ConversationTurnResult {
475
+ const line = formatWeatherSpeech(weather);
476
+ return returnToMenu(state, line);
477
+ }
478
+
479
+ export function applyWeatherFailure(
480
+ state: ConversationState,
481
+ ): ConversationTurnResult {
482
+ const retries = state.weatherRetries + 1;
483
+ if (retries >= 2) {
484
+ return returnToMenu(
485
+ { ...state, weatherRetries: retries },
486
+ "Sorry, I could not look up the weather right now.",
487
+ );
488
+ }
489
+ const retry = speakAndChat(
490
+ "I could not find that location. Please try again with a city or ZIP and country.",
491
+ );
492
+ return {
493
+ state: {
494
+ ...state,
495
+ phase: "weatherAwaitingLocation",
496
+ weatherRetries: retries,
497
+ weatherCity: undefined,
498
+ weatherCountry: undefined,
499
+ },
500
+ speakLines: retry.speakLines,
501
+ messages: retry.messages,
502
+ };
503
+ }
504
+
505
+ export async function resolveWeatherTurn(
506
+ state: ConversationState,
507
+ city: string,
508
+ country: string | undefined,
509
+ fetchFn?: FetchFn,
510
+ ): Promise<ConversationTurnResult> {
511
+ try {
512
+ const weather = await lookupWeather(city, country, fetchFn);
513
+ if (!weather) {
514
+ return applyWeatherFailure(state);
515
+ }
516
+ return applyWeatherSuccess(state, weather);
517
+ } catch {
518
+ return applyWeatherFailure(state);
519
+ }
520
+ }
@@ -0,0 +1,24 @@
1
+ /** Short fun facts for the voice showcase menu. */
2
+
3
+ export const FUN_FACTS: readonly string[] = [
4
+ "Honey never spoils — archaeologists have found edible honey in ancient Egyptian tombs.",
5
+ "Octopuses have three hearts and blue blood.",
6
+ "A day on Venus is longer than a year on Venus.",
7
+ "Bananas are berries, but strawberries are not.",
8
+ "The Eiffel Tower can grow about six inches taller in summer heat.",
9
+ "Sharks existed before trees appeared on Earth.",
10
+ ] as const;
11
+
12
+ let factIndex = 0;
13
+
14
+ /** Pick the next fun fact (rotates through the list). */
15
+ export function pickFunFact(): string {
16
+ const fact = FUN_FACTS[factIndex % FUN_FACTS.length]!;
17
+ factIndex += 1;
18
+ return fact;
19
+ }
20
+
21
+ /** Reset rotation (for tests). */
22
+ export function resetFunFactIndex(): void {
23
+ factIndex = 0;
24
+ }
@@ -0,0 +1,57 @@
1
+ /** Hardcoded short recipes for the voice showcase. */
2
+
3
+ export interface Recipe {
4
+ title: string;
5
+ keywords: string[];
6
+ steps: string;
7
+ }
8
+
9
+ export const RECIPES: readonly Recipe[] = [
10
+ {
11
+ title: "Quick garlic pasta",
12
+ keywords: ["pasta", "noodle", "spaghetti", "italian"],
13
+ steps:
14
+ "Boil pasta until al dente. Sauté minced garlic in olive oil, toss with pasta, parmesan, and black pepper. Serve hot.",
15
+ },
16
+ {
17
+ title: "Simple vegetable soup",
18
+ keywords: ["soup", "broth", "stew"],
19
+ steps:
20
+ "Sauté onion and carrot in a pot. Add vegetable stock, diced potatoes, and simmer twenty minutes. Season with salt and herbs.",
21
+ },
22
+ {
23
+ title: "Easy breakfast scramble",
24
+ keywords: ["breakfast", "eggs", "morning", "brunch"],
25
+ steps:
26
+ "Whisk three eggs with a splash of milk. Cook in a buttered pan with spinach and cheese. Fold and serve with toast.",
27
+ },
28
+ {
29
+ title: "Classic chocolate chip cookies",
30
+ keywords: ["cookie", "cookies", "dessert", "sweet", "bake"],
31
+ steps:
32
+ "Cream butter and sugar, mix in flour, egg, and chocolate chips. Drop spoonfuls on a tray and bake at one seventy five Celsius for ten minutes.",
33
+ },
34
+ {
35
+ title: "Fresh garden salad",
36
+ keywords: ["salad", "greens", "vegetable", "healthy"],
37
+ steps:
38
+ "Toss mixed greens with cherry tomatoes, cucumber, and feta. Dress with olive oil, lemon juice, salt, and pepper.",
39
+ },
40
+ ] as const;
41
+
42
+ const DEFAULT_RECIPE = RECIPES[0]!;
43
+
44
+ /** Match a recipe by keywords in the utterance, or return the default. */
45
+ export function pickRecipe(utterance: string): Recipe {
46
+ const lower = utterance.toLowerCase();
47
+ for (const recipe of RECIPES) {
48
+ if (recipe.keywords.some((kw) => lower.includes(kw))) {
49
+ return recipe;
50
+ }
51
+ }
52
+ return DEFAULT_RECIPE;
53
+ }
54
+
55
+ export function formatRecipeSpeech(recipe: Recipe): string {
56
+ return `${recipe.title}. ${recipe.steps}`;
57
+ }