@voicethere/agent 0.5.2 → 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,1242 @@
1
+ import { createRequire } from "node:module";
2
+ const require = createRequire(import.meta.url);
3
+
4
+
5
+ // dist/runtime.js
6
+ import { randomUUID } from "node:crypto";
7
+ import { AsyncLocalStorage } from "node:async_hooks";
8
+
9
+ // dist/session-serial-queue.js
10
+ var SessionSerialQueueCancellationError = class extends Error {
11
+ sessionId;
12
+ generation;
13
+ code = "SESSION_SERIAL_QUEUE_CANCELLED";
14
+ constructor(sessionId, generation) {
15
+ super(`session serial queue cancelled (sessionId=${sessionId}, generation=${generation})`);
16
+ this.sessionId = sessionId;
17
+ this.generation = generation;
18
+ this.name = "SessionSerialQueueCancellationError";
19
+ }
20
+ };
21
+ var SessionSerialQueue = class {
22
+ sessions = /* @__PURE__ */ new Map();
23
+ /** Monotonic token source — never reused across clear/enqueue cycles. */
24
+ nextGeneration = 1;
25
+ /**
26
+ * Enqueue work for `sessionId`. Returns a promise that settles when this
27
+ * task finishes, is skipped as stale, or is cancelled by {@link clear}.
28
+ * Fire-and-forget callers may ignore the return value (compat).
29
+ */
30
+ enqueue(sessionId, task) {
31
+ const state = this.ensureState(sessionId);
32
+ const captured = state;
33
+ const generation = captured.generation;
34
+ captured.pending += 1;
35
+ const previous = captured.tail;
36
+ let taskAbort = null;
37
+ const settled = previous.catch(() => void 0).then(async () => {
38
+ if (this.sessions.get(sessionId) !== captured) {
39
+ return "cancelled";
40
+ }
41
+ const abort = new AbortController();
42
+ taskAbort = abort;
43
+ captured.abort = abort;
44
+ const context = {
45
+ sessionId,
46
+ generation,
47
+ signal: abort.signal
48
+ };
49
+ try {
50
+ await Promise.resolve(task(abort.signal, context));
51
+ if (this.sessions.get(sessionId) !== captured) {
52
+ return "cancelled";
53
+ }
54
+ return "completed";
55
+ } catch (error) {
56
+ if (abort.signal.aborted || this.sessions.get(sessionId) !== captured || error instanceof SessionSerialQueueCancellationError) {
57
+ return "cancelled";
58
+ }
59
+ return "failed";
60
+ } finally {
61
+ if (captured.abort === abort) {
62
+ captured.abort = null;
63
+ }
64
+ }
65
+ }).finally(() => {
66
+ captured.pending = Math.max(0, captured.pending - 1);
67
+ if (taskAbort && captured.abort === taskAbort) {
68
+ captured.abort = null;
69
+ }
70
+ });
71
+ captured.tail = settled;
72
+ return settled;
73
+ }
74
+ /**
75
+ * Invalidate queued + running work for `sessionId`. Aborts the live AbortSignal,
76
+ * drops the map entry, and leaves a fresh identity for the next enqueue.
77
+ * Old in-flight `finally` blocks only touch their captured state object.
78
+ */
79
+ clear(sessionId) {
80
+ const old = this.sessions.get(sessionId);
81
+ if (!old)
82
+ return;
83
+ old.abort?.abort();
84
+ old.abort = null;
85
+ this.sessions.delete(sessionId);
86
+ }
87
+ clearAll() {
88
+ for (const sessionId of [...this.sessions.keys()]) {
89
+ this.clear(sessionId);
90
+ }
91
+ }
92
+ hasPending(sessionId) {
93
+ return (this.sessions.get(sessionId)?.pending ?? 0) > 0;
94
+ }
95
+ /** Live generation token for a session, or `undefined` when cleared. */
96
+ generationOf(sessionId) {
97
+ return this.sessions.get(sessionId)?.generation;
98
+ }
99
+ /** True when `generation` is the live map entry for `sessionId`. */
100
+ isCurrentGeneration(sessionId, generation) {
101
+ return this.sessions.get(sessionId)?.generation === generation;
102
+ }
103
+ /**
104
+ * True when a queue row exists for the session (registered since first
105
+ * enqueue, until {@link clear}). Not the same as {@link hasPending}.
106
+ */
107
+ isLive(sessionId) {
108
+ return this.sessions.has(sessionId);
109
+ }
110
+ /** Registered session rows (must not grow without matching `clear` calls). */
111
+ get activeSessionCount() {
112
+ return this.sessions.size;
113
+ }
114
+ ensureState(sessionId) {
115
+ const existing = this.sessions.get(sessionId);
116
+ if (existing)
117
+ return existing;
118
+ const created = {
119
+ generation: this.nextGeneration++,
120
+ tail: Promise.resolve(),
121
+ abort: null,
122
+ pending: 0
123
+ };
124
+ this.sessions.set(sessionId, created);
125
+ return created;
126
+ }
127
+ };
128
+
129
+ // dist/runtime.js
130
+ var SESSION_START_INIT_DELAY_ENABLED_ENV = "AGENT_SESSION_START_INIT_DELAY_ENABLED";
131
+ var SESSION_START_INIT_DELAY_MS_ENV = "AGENT_SESSION_START_INIT_DELAY_MS";
132
+ var DEFAULT_SESSION_START_INIT_DELAY_MS = 500;
133
+ function isRecordingControlAckMessage(value) {
134
+ if (!value || typeof value !== "object")
135
+ return false;
136
+ const msg = value;
137
+ return msg.type === "recording_control_ack" && typeof msg.requestId === "string";
138
+ }
139
+ function isWebhookMessage(value) {
140
+ if (!value || typeof value !== "object")
141
+ return false;
142
+ const msg = value;
143
+ return msg.type === "webhook" && typeof msg.eventId === "string" && typeof msg.projectId === "string";
144
+ }
145
+ function coerceInboundBinary(value) {
146
+ if (!value)
147
+ return null;
148
+ if (Buffer.isBuffer(value))
149
+ return value;
150
+ if (value instanceof Uint8Array) {
151
+ return Buffer.from(value.buffer, value.byteOffset, value.byteLength);
152
+ }
153
+ if (value instanceof ArrayBuffer)
154
+ return Buffer.from(value);
155
+ if (ArrayBuffer.isView(value)) {
156
+ return Buffer.from(value.buffer, value.byteOffset, value.byteLength);
157
+ }
158
+ if (typeof value === "object") {
159
+ const maybeBufferLike = value;
160
+ if (maybeBufferLike.type === "Buffer" && Array.isArray(maybeBufferLike.data)) {
161
+ return Buffer.from(maybeBufferLike.data);
162
+ }
163
+ }
164
+ return null;
165
+ }
166
+ function normalizeWebhookHeaders(value) {
167
+ if (!value || typeof value !== "object")
168
+ return {};
169
+ const out = {};
170
+ for (const [key, raw] of Object.entries(value)) {
171
+ if (typeof raw === "string") {
172
+ out[key] = raw;
173
+ }
174
+ }
175
+ return out;
176
+ }
177
+ function isParentMessage(value) {
178
+ if (!value || typeof value !== "object")
179
+ return false;
180
+ const msg = value;
181
+ return msg.type === "session_start" || msg.type === "speech_event" || msg.type === "session_end" || msg.type === "data_channel_message" || msg.type === "data_channel_binary" || msg.type === "idle_timeout" || msg.type === "recording_control_ack" || msg.type === "webhook";
182
+ }
183
+ function isSessionScopedParentMessage(value) {
184
+ return isParentMessage(value) && !isWebhookMessage(value);
185
+ }
186
+ function parseDataChannelPayload(raw) {
187
+ try {
188
+ return JSON.parse(raw);
189
+ } catch {
190
+ return raw;
191
+ }
192
+ }
193
+ var peerEnvBySessionId = /* @__PURE__ */ new Map();
194
+ var endedSessionIds = /* @__PURE__ */ new Set();
195
+ var pendingRecordingAcks = /* @__PURE__ */ new Map();
196
+ function handleRecordingControlAck(message) {
197
+ const pending = pendingRecordingAcks.get(message.requestId);
198
+ if (!pending)
199
+ return;
200
+ clearTimeout(pending.timer);
201
+ pendingRecordingAcks.delete(message.requestId);
202
+ pending.resolve({
203
+ ok: message.ok,
204
+ reason: message.reason,
205
+ requestId: message.requestId
206
+ });
207
+ }
208
+ function clearPendingRecordingAcksForSession(sessionId, reason) {
209
+ for (const [requestId, pending] of pendingRecordingAcks) {
210
+ if (pending.sessionId !== sessionId)
211
+ continue;
212
+ clearTimeout(pending.timer);
213
+ pendingRecordingAcks.delete(requestId);
214
+ pending.resolve({ ok: false, reason, requestId });
215
+ }
216
+ }
217
+ var sessionExecutionContext = new AsyncLocalStorage();
218
+ var agentLogSessionContext = new AsyncLocalStorage();
219
+ var inboundQueueAuthority = null;
220
+ var childUnhandledRejectionGuardInstalled = false;
221
+ function normalizeRejectionReason(reason) {
222
+ return reason instanceof Error ? reason : new Error(String(reason));
223
+ }
224
+ function installChildUnhandledRejectionGuard() {
225
+ if (childUnhandledRejectionGuardInstalled) {
226
+ return;
227
+ }
228
+ childUnhandledRejectionGuardInstalled = true;
229
+ process.on("unhandledRejection", (reason) => {
230
+ const err = normalizeRejectionReason(reason);
231
+ const store = sessionExecutionContext.getStore();
232
+ const sessionId = store?.sessionId ?? agentLogSessionContext.getStore() ?? "";
233
+ if (!allowOutboundForSession(sessionId || void 0)) {
234
+ return;
235
+ }
236
+ agentLog("error", `unhandledRejection: ${err.message}`, sessionId || void 0);
237
+ sendParentMessage({
238
+ type: "agent_error",
239
+ sessionId,
240
+ message: err.message,
241
+ stack: err.stack
242
+ });
243
+ });
244
+ }
245
+ function allowOutboundForSession(sessionId) {
246
+ if (!sessionId) {
247
+ return true;
248
+ }
249
+ const store = sessionExecutionContext.getStore();
250
+ const queue = inboundQueueAuthority;
251
+ if (store && store.sessionId === sessionId) {
252
+ if (!queue)
253
+ return !endedSessionIds.has(sessionId);
254
+ return queue.isCurrentGeneration(sessionId, store.generation);
255
+ }
256
+ if (endedSessionIds.has(sessionId))
257
+ return false;
258
+ if (!queue)
259
+ return true;
260
+ return queue.isLive(sessionId);
261
+ }
262
+ function sendParentMessage(message) {
263
+ const sessionId = message && typeof message === "object" && "sessionId" in message && typeof message.sessionId === "string" ? message.sessionId : void 0;
264
+ if (!allowOutboundForSession(sessionId))
265
+ return;
266
+ process.send?.(message);
267
+ }
268
+ function parseBooleanEnv(value, defaultValue) {
269
+ if (value === void 0)
270
+ return defaultValue;
271
+ const normalized = value.trim().toLowerCase();
272
+ if (normalized === "")
273
+ return defaultValue;
274
+ if (["0", "false", "off", "no"].includes(normalized))
275
+ return false;
276
+ if (["1", "true", "on", "yes"].includes(normalized))
277
+ return true;
278
+ return defaultValue;
279
+ }
280
+ function parseNonNegativeIntegerEnv(value, defaultValue) {
281
+ if (value === void 0)
282
+ return defaultValue;
283
+ const parsed = Number(value);
284
+ if (!Number.isFinite(parsed) || parsed < 0)
285
+ return defaultValue;
286
+ return Math.floor(parsed);
287
+ }
288
+ function resolveSessionStartInitDelayMs() {
289
+ const enabled = parseBooleanEnv(process.env[SESSION_START_INIT_DELAY_ENABLED_ENV], true);
290
+ if (!enabled)
291
+ return 0;
292
+ return parseNonNegativeIntegerEnv(process.env[SESSION_START_INIT_DELAY_MS_ENV], DEFAULT_SESSION_START_INIT_DELAY_MS);
293
+ }
294
+ async function handleWebhookMessage(message, handlers) {
295
+ if (!handlers.onWebhook)
296
+ return;
297
+ const body = coerceInboundBinary(message.body);
298
+ if (!body) {
299
+ agentLog("warn", "webhook ipc dropped: body is not binary");
300
+ return;
301
+ }
302
+ const ctx = {
303
+ eventId: message.eventId,
304
+ projectId: message.projectId,
305
+ method: typeof message.method === "string" ? message.method : "POST",
306
+ path: typeof message.path === "string" ? message.path : "",
307
+ headers: normalizeWebhookHeaders(message.headers),
308
+ body,
309
+ contentType: typeof message.contentType === "string" ? message.contentType : null,
310
+ receivedAt: typeof message.receivedAt === "string" ? message.receivedAt : "",
311
+ sessionIds: Array.isArray(message.sessionIds) ? message.sessionIds.filter((id) => typeof id === "string" && id.length > 0) : []
312
+ };
313
+ try {
314
+ const started = Date.now();
315
+ await handlers.onWebhook(ctx);
316
+ sendParentMessage({
317
+ type: "webhook_handled",
318
+ projectId: message.projectId,
319
+ eventId: message.eventId,
320
+ durationMs: Date.now() - started
321
+ });
322
+ } catch (error) {
323
+ const err = error instanceof Error ? error : new Error(String(error));
324
+ await runErrorHook(handlers, {
325
+ sessionId: "",
326
+ projectId: message.projectId,
327
+ env: process.env,
328
+ error: err
329
+ });
330
+ sendParentMessage({
331
+ type: "agent_error",
332
+ sessionId: "",
333
+ message: err.message,
334
+ stack: err.stack
335
+ });
336
+ }
337
+ }
338
+ async function handleParentMessage(message, handlers) {
339
+ switch (message.type) {
340
+ case "session_start":
341
+ endedSessionIds.delete(message.sessionId);
342
+ peerEnvBySessionId.set(message.sessionId, message.env);
343
+ const sessionStartInitDelayMs = resolveSessionStartInitDelayMs();
344
+ if (sessionStartInitDelayMs > 0) {
345
+ await new Promise((resolve) => setTimeout(resolve, sessionStartInitDelayMs));
346
+ }
347
+ await (handlers.onClientJoin ?? handlers.onSessionStart)?.({
348
+ sessionId: message.sessionId,
349
+ env: message.env,
350
+ recordingAvailable: message.recordingAvailable ?? false
351
+ });
352
+ sendParentMessage({
353
+ type: "session_start_ack",
354
+ sessionId: message.sessionId
355
+ });
356
+ break;
357
+ case "speech_event":
358
+ await handlers.onSpeechEvent?.({ sessionId: message.sessionId }, message.event);
359
+ if (message.event.type === "user_speech_final" && typeof message.event.text === "string" && message.event.text.trim()) {
360
+ await handlers.onUserSpeechFinal?.({
361
+ sessionId: message.sessionId,
362
+ text: message.event.text.trim()
363
+ });
364
+ }
365
+ break;
366
+ case "data_channel_message":
367
+ await handlers.onDataChannelMessage?.({
368
+ sessionId: message.sessionId,
369
+ message: parseDataChannelPayload(message.payload),
370
+ raw: message.payload,
371
+ rawBinary: null,
372
+ channel: "control"
373
+ });
374
+ break;
375
+ case "data_channel_binary":
376
+ await handlers.onDataChannelBinary?.({
377
+ sessionId: message.sessionId,
378
+ message: null,
379
+ raw: null,
380
+ rawBinary: message.data,
381
+ channel: message.channel ?? "sync"
382
+ });
383
+ break;
384
+ case "session_end":
385
+ clearPendingRecordingAcksForSession(message.sessionId, "session_ended");
386
+ peerEnvBySessionId.delete(message.sessionId);
387
+ await (handlers.onClientLeave ?? handlers.onSessionEnd)?.({
388
+ sessionId: message.sessionId
389
+ });
390
+ break;
391
+ case "idle_timeout":
392
+ await runIdleTimeoutHook(handlers, message);
393
+ break;
394
+ }
395
+ }
396
+ function defineAgent(handlers) {
397
+ installChildUnhandledRejectionGuard();
398
+ const inboundBySession = new SessionSerialQueue();
399
+ inboundQueueAuthority = inboundBySession;
400
+ const agentStartReady = runAgentStartHook(handlers);
401
+ process.on("message", (message) => {
402
+ if (isRecordingControlAckMessage(message)) {
403
+ handleRecordingControlAck(message);
404
+ return;
405
+ }
406
+ if (isWebhookMessage(message)) {
407
+ void agentStartReady.then(() => handleWebhookMessage(message, handlers));
408
+ return;
409
+ }
410
+ if (!isSessionScopedParentMessage(message))
411
+ return;
412
+ if (message.type === "session_end") {
413
+ endedSessionIds.add(message.sessionId);
414
+ clearPendingRecordingAcksForSession(message.sessionId, "session_ended");
415
+ inboundBySession.clear(message.sessionId);
416
+ }
417
+ if (message.type === "session_start") {
418
+ endedSessionIds.delete(message.sessionId);
419
+ inboundBySession.clear(message.sessionId);
420
+ }
421
+ inboundBySession.enqueue(message.sessionId, async (_signal, context) => {
422
+ await agentStartReady;
423
+ try {
424
+ await sessionExecutionContext.run({
425
+ sessionId: message.sessionId,
426
+ generation: context.generation
427
+ }, async () => agentLogSessionContext.run(message.sessionId, async () => {
428
+ try {
429
+ await handleParentMessage(message, handlers);
430
+ } catch (error) {
431
+ const err = error instanceof Error ? error : new Error(String(error));
432
+ const env = peerEnvBySessionId.get(message.sessionId) ?? buildIdleEnv(message.sessionId);
433
+ await runErrorHook(handlers, {
434
+ sessionId: message.sessionId,
435
+ projectId: env.PROJECT_ID,
436
+ buildId: env.BUILD_ID,
437
+ env,
438
+ error: err,
439
+ customerContext: parseCustomerContext(env.AGENT_CUSTOMER_CONTEXT)
440
+ });
441
+ sendParentMessage({
442
+ type: "agent_error",
443
+ sessionId: message.sessionId,
444
+ message: err.message,
445
+ stack: err.stack
446
+ });
447
+ }
448
+ }));
449
+ } finally {
450
+ if (message.type === "session_end" && inboundBySession.isCurrentGeneration(message.sessionId, context.generation)) {
451
+ inboundBySession.clear(message.sessionId);
452
+ }
453
+ }
454
+ });
455
+ });
456
+ }
457
+ async function runAgentStartHook(handlers) {
458
+ if (!handlers.onAgentStart)
459
+ return;
460
+ try {
461
+ await handlers.onAgentStart({
462
+ env: process.env
463
+ });
464
+ } catch (error) {
465
+ const err = error instanceof Error ? error : new Error(String(error));
466
+ agentLog("error", `onAgentStart failed: ${err.message}`);
467
+ sendParentMessage({
468
+ type: "agent_error",
469
+ sessionId: "",
470
+ message: err.message,
471
+ stack: err.stack
472
+ });
473
+ }
474
+ }
475
+ function parseCustomerContext(raw) {
476
+ if (!raw?.trim())
477
+ return void 0;
478
+ try {
479
+ const parsed = JSON.parse(raw);
480
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
481
+ return parsed;
482
+ }
483
+ } catch {
484
+ }
485
+ return void 0;
486
+ }
487
+ async function runErrorHook(handlers, ctx) {
488
+ if (!handlers.errorHook)
489
+ return;
490
+ try {
491
+ await handlers.errorHook(ctx);
492
+ } catch (hookError) {
493
+ const message = hookError instanceof Error ? hookError.message : String(hookError);
494
+ agentLog("error", `errorHook failed: ${message}`, ctx.sessionId);
495
+ }
496
+ }
497
+ async function runIdleTimeoutHook(handlers, message) {
498
+ const onIdleTimeout = handlers.onIdleTimeout;
499
+ agentLog("info", `idle_timeout ipc received (maxGraceMs=${message.maxGraceMs}, onIdleTimeout=${typeof onIdleTimeout === "function"})`, message.sessionId);
500
+ if (!onIdleTimeout) {
501
+ sendParentMessage({
502
+ type: "idle_timeout_done",
503
+ sessionId: message.sessionId
504
+ });
505
+ agentLog("info", "idle_timeout_done ipc sent (no onIdleTimeout handler)", message.sessionId);
506
+ return;
507
+ }
508
+ const env = peerEnvBySessionId.get(message.sessionId) ?? buildIdleEnv(message.sessionId);
509
+ const idleTimeoutSeconds = Number(env.IDLE_TIMEOUT_SEC) || 0;
510
+ const ctx = {
511
+ sessionId: message.sessionId,
512
+ projectId: env.PROJECT_ID,
513
+ buildId: env.BUILD_ID,
514
+ env,
515
+ idleTimeoutSeconds
516
+ };
517
+ let error;
518
+ try {
519
+ await onIdleTimeout(ctx);
520
+ } catch (hookError) {
521
+ error = hookError instanceof Error ? hookError.message : String(hookError);
522
+ agentLog("error", `onIdleTimeout failed: ${error}`, message.sessionId);
523
+ }
524
+ sendParentMessage({
525
+ type: "idle_timeout_done",
526
+ sessionId: message.sessionId,
527
+ error
528
+ });
529
+ agentLog("info", error ? `idle_timeout_done ipc sent (onIdleTimeout error: ${error})` : "idle_timeout_done ipc sent (onIdleTimeout completed)", message.sessionId);
530
+ }
531
+ function buildIdleEnv(sessionId) {
532
+ return {
533
+ SESSION_ID: sessionId,
534
+ ...process.env.PROJECT_ID ? { PROJECT_ID: process.env.PROJECT_ID } : {},
535
+ ...process.env.BUILD_ID ? { BUILD_ID: process.env.BUILD_ID } : {},
536
+ ...process.env.IDLE_TIMEOUT_SEC ? { IDLE_TIMEOUT_SEC: process.env.IDLE_TIMEOUT_SEC } : {}
537
+ };
538
+ }
539
+ function speak(sessionId, text) {
540
+ sendParentMessage({ type: "speak", sessionId, text });
541
+ }
542
+ function sendToClient(sessionId, payload) {
543
+ sendParentMessage({ type: "send_to_client", sessionId, payload });
544
+ }
545
+ var AGENT_LOG_MESSAGE_MAX_CHARS = 2048;
546
+ var AGENT_LOG_FIELDS_MAX_CHARS = 8192;
547
+ function truncateAgentLogMessage(message) {
548
+ if (message.length <= AGENT_LOG_MESSAGE_MAX_CHARS) {
549
+ return message;
550
+ }
551
+ const suffix = "\u2026[truncated]";
552
+ return message.slice(0, AGENT_LOG_MESSAGE_MAX_CHARS - suffix.length) + suffix;
553
+ }
554
+ function isPlainObject(value) {
555
+ return typeof value === "object" && value !== null && !Array.isArray(value);
556
+ }
557
+ function sanitizeAgentLogFields(fields) {
558
+ if (Object.keys(fields).length === 0) {
559
+ return void 0;
560
+ }
561
+ try {
562
+ const serialized = JSON.stringify(fields);
563
+ if (serialized.length <= AGENT_LOG_FIELDS_MAX_CHARS) {
564
+ return fields;
565
+ }
566
+ return {
567
+ _agentLogFieldsTruncated: true,
568
+ _originalBytes: serialized.length,
569
+ _preview: serialized.slice(0, AGENT_LOG_FIELDS_MAX_CHARS - 80) + "\u2026[truncated]"
570
+ };
571
+ } catch {
572
+ return { _agentLogFieldsError: "not_serializable" };
573
+ }
574
+ }
575
+ function buildAgentLogPayload(level, message, fields, sessionId) {
576
+ const resolvedSessionId = sessionId ?? sessionExecutionContext.getStore()?.sessionId ?? agentLogSessionContext.getStore();
577
+ const sanitizedFields = fields ? sanitizeAgentLogFields(fields) : void 0;
578
+ return {
579
+ type: "log",
580
+ level,
581
+ message: truncateAgentLogMessage(message),
582
+ ts: Date.now(),
583
+ ...resolvedSessionId ? { sessionId: resolvedSessionId } : {},
584
+ ...sanitizedFields ? { fields: sanitizedFields } : {}
585
+ };
586
+ }
587
+ function agentLog(level, message, fieldsOrSessionId, sessionId) {
588
+ let fields;
589
+ let resolvedSessionId;
590
+ if (typeof fieldsOrSessionId === "string") {
591
+ resolvedSessionId = fieldsOrSessionId;
592
+ } else if (isPlainObject(fieldsOrSessionId)) {
593
+ fields = fieldsOrSessionId;
594
+ resolvedSessionId = sessionId;
595
+ } else {
596
+ resolvedSessionId = sessionId;
597
+ }
598
+ sendParentMessage(buildAgentLogPayload(level, message, fields, resolvedSessionId));
599
+ }
600
+ function parseChatText(message) {
601
+ if (!message || typeof message !== "object")
602
+ return null;
603
+ const record = message;
604
+ if (record.type !== "chat" || typeof record.text !== "string")
605
+ return null;
606
+ const trimmed = record.text.trim();
607
+ return trimmed.length > 0 ? trimmed : null;
608
+ }
609
+
610
+ // templates/voice-showcase/recipes.ts
611
+ var RECIPES = [
612
+ {
613
+ title: "Quick garlic pasta",
614
+ keywords: ["pasta", "noodle", "spaghetti", "italian"],
615
+ steps: "Boil pasta until al dente. Saut\xE9 minced garlic in olive oil, toss with pasta, parmesan, and black pepper. Serve hot."
616
+ },
617
+ {
618
+ title: "Simple vegetable soup",
619
+ keywords: ["soup", "broth", "stew"],
620
+ steps: "Saut\xE9 onion and carrot in a pot. Add vegetable stock, diced potatoes, and simmer twenty minutes. Season with salt and herbs."
621
+ },
622
+ {
623
+ title: "Easy breakfast scramble",
624
+ keywords: ["breakfast", "eggs", "morning", "brunch"],
625
+ steps: "Whisk three eggs with a splash of milk. Cook in a buttered pan with spinach and cheese. Fold and serve with toast."
626
+ },
627
+ {
628
+ title: "Classic chocolate chip cookies",
629
+ keywords: ["cookie", "cookies", "dessert", "sweet", "bake"],
630
+ steps: "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."
631
+ },
632
+ {
633
+ title: "Fresh garden salad",
634
+ keywords: ["salad", "greens", "vegetable", "healthy"],
635
+ steps: "Toss mixed greens with cherry tomatoes, cucumber, and feta. Dress with olive oil, lemon juice, salt, and pepper."
636
+ }
637
+ ];
638
+ var DEFAULT_RECIPE = RECIPES[0];
639
+ function pickRecipe(utterance) {
640
+ const lower = utterance.toLowerCase();
641
+ for (const recipe of RECIPES) {
642
+ if (recipe.keywords.some((kw) => lower.includes(kw))) {
643
+ return recipe;
644
+ }
645
+ }
646
+ return DEFAULT_RECIPE;
647
+ }
648
+ function formatRecipeSpeech(recipe) {
649
+ return `${recipe.title}. ${recipe.steps}`;
650
+ }
651
+
652
+ // templates/voice-showcase/fun-facts.ts
653
+ var FUN_FACTS = [
654
+ "Honey never spoils \u2014 archaeologists have found edible honey in ancient Egyptian tombs.",
655
+ "Octopuses have three hearts and blue blood.",
656
+ "A day on Venus is longer than a year on Venus.",
657
+ "Bananas are berries, but strawberries are not.",
658
+ "The Eiffel Tower can grow about six inches taller in summer heat.",
659
+ "Sharks existed before trees appeared on Earth."
660
+ ];
661
+ var factIndex = 0;
662
+ function pickFunFact() {
663
+ const fact = FUN_FACTS[factIndex % FUN_FACTS.length];
664
+ factIndex += 1;
665
+ return fact;
666
+ }
667
+
668
+ // templates/voice-showcase/weather.ts
669
+ var GEOCODE_URL = "https://geocoding-api.open-meteo.com/v1/search";
670
+ var FORECAST_URL = "https://api.open-meteo.com/v1/forecast";
671
+ var FETCH_TIMEOUT_MS = 8e3;
672
+ function wmoCodeToPhrase(code) {
673
+ if (code === 0) return "clear sky";
674
+ if (code <= 3) return "partly cloudy";
675
+ if (code <= 48) return "foggy";
676
+ if (code <= 57) return "drizzle";
677
+ if (code <= 67) return "rain";
678
+ if (code <= 77) return "snow";
679
+ if (code <= 82) return "rain showers";
680
+ if (code <= 86) return "snow showers";
681
+ if (code <= 99) return "thunderstorm";
682
+ return "variable conditions";
683
+ }
684
+ function formatWeatherSpeech(result) {
685
+ const temp = Math.round(result.temperatureC);
686
+ const wind = Math.round(result.windKmh);
687
+ return `In ${result.place}, it is ${temp} degrees Celsius with ${result.condition} and winds around ${wind} kilometers per hour.`;
688
+ }
689
+ function parseLocationUtterance(utterance) {
690
+ const text = utterance.trim();
691
+ if (!text) return null;
692
+ const inMatch = text.match(
693
+ /^(?:in\s+)?(.+?)\s+in\s+([a-zA-Z][\w\s.-]{1,40})$/i
694
+ );
695
+ if (inMatch) {
696
+ return { city: inMatch[1].trim(), country: inMatch[2].trim() };
697
+ }
698
+ const commaMatch = text.match(/^(.+?),\s*([a-zA-Z][\w\s.-]{1,40})$/);
699
+ if (commaMatch) {
700
+ return { city: commaMatch[1].trim(), country: commaMatch[2].trim() };
701
+ }
702
+ const countryMatch = text.match(
703
+ /^(.+?)\s+(?:country\s+)?([a-zA-Z][\w\s.-]{2,40})$/i
704
+ );
705
+ if (countryMatch && countryMatch[2].split(/\s+/).length <= 3) {
706
+ const city = countryMatch[1].trim();
707
+ const country = countryMatch[2].trim();
708
+ if (city.length >= 2 && country.length >= 2) {
709
+ return { city, country };
710
+ }
711
+ }
712
+ if (/^\d{5}(-\d{4})?$/.test(text)) {
713
+ return { city: text };
714
+ }
715
+ if (text.length >= 2 && text.length <= 60) {
716
+ return { city: text };
717
+ }
718
+ return null;
719
+ }
720
+ async function geocodeLocation(city, country, fetchFn = fetch) {
721
+ const query = country ? `${city}, ${country}` : city;
722
+ const url = new URL(GEOCODE_URL);
723
+ url.searchParams.set("name", query);
724
+ url.searchParams.set("count", "1");
725
+ url.searchParams.set("language", "en");
726
+ url.searchParams.set("format", "json");
727
+ const response = await fetchFn(url.toString(), {
728
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
729
+ });
730
+ if (!response.ok) return null;
731
+ const data = await response.json();
732
+ const hit = data.results?.[0];
733
+ if (!hit || typeof hit.latitude !== "number" || typeof hit.longitude !== "number") {
734
+ return null;
735
+ }
736
+ return {
737
+ name: hit.name ?? city,
738
+ country: hit.country ?? country ?? "",
739
+ latitude: hit.latitude,
740
+ longitude: hit.longitude
741
+ };
742
+ }
743
+ async function fetchCurrentWeather(geo, fetchFn = fetch) {
744
+ const url = new URL(FORECAST_URL);
745
+ url.searchParams.set("latitude", String(geo.latitude));
746
+ url.searchParams.set("longitude", String(geo.longitude));
747
+ url.searchParams.set("current", "temperature_2m,weather_code,wind_speed_10m");
748
+ url.searchParams.set("wind_speed_unit", "kmh");
749
+ const response = await fetchFn(url.toString(), {
750
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
751
+ });
752
+ if (!response.ok) return null;
753
+ const data = await response.json();
754
+ const current = data.current;
755
+ if (!current || typeof current.temperature_2m !== "number" || typeof current.weather_code !== "number") {
756
+ return null;
757
+ }
758
+ const place = geo.country ? `${geo.name}, ${geo.country}` : geo.name;
759
+ return {
760
+ place,
761
+ temperatureC: current.temperature_2m,
762
+ condition: wmoCodeToPhrase(current.weather_code),
763
+ windKmh: current.wind_speed_10m ?? 0
764
+ };
765
+ }
766
+ async function lookupWeather(city, country, fetchFn = fetch) {
767
+ const geo = await geocodeLocation(city, country, fetchFn);
768
+ if (!geo) return null;
769
+ return fetchCurrentWeather(geo, fetchFn);
770
+ }
771
+
772
+ // templates/voice-showcase/conversation.ts
773
+ var GREETING = "Hi and welcome to the Voicethere voice chat, may I know your name?";
774
+ var HUMAN_ESCALATION_REPLY = "This is only a showcase conversation and unfortunately there is no human support connected.";
775
+ var NAME_DECLINE_REPLY = "OK we will continue without your name";
776
+ var MENU_ITEMS = [
777
+ { id: 1, label: "Check the weather" },
778
+ { id: 2, label: "Count" },
779
+ { id: 3, label: "Hear a recipe" },
780
+ { id: 4, label: "Hear a fun fact" }
781
+ ];
782
+ var MENU_CHAT_TEXT = `Here is our menu:
783
+ 1. Check the weather
784
+ 2. Count
785
+ 3. Hear a recipe
786
+ 4. Hear a fun fact`;
787
+ function createInitialState() {
788
+ return {
789
+ phase: "listeningForName",
790
+ nameDeclined: false,
791
+ weatherRetries: 0,
792
+ countFailures: 0
793
+ };
794
+ }
795
+ function buildMenuMessages() {
796
+ return [
797
+ { type: "chat_reply", text: MENU_CHAT_TEXT },
798
+ {
799
+ type: "menu",
800
+ items: MENU_ITEMS.map((item) => ({ id: item.id, label: item.label }))
801
+ }
802
+ ];
803
+ }
804
+ function speakAndChat(text) {
805
+ return {
806
+ speakLines: [text],
807
+ messages: [{ type: "chat_reply", text }]
808
+ };
809
+ }
810
+ function isHumanEscalation(utterance) {
811
+ const lower = utterance.toLowerCase();
812
+ const patterns = [
813
+ /\bhuman\b/,
814
+ /\boperator\b/,
815
+ /\breal\s+person\b/,
816
+ /\btalk\s+to\s+(?:a\s+)?(?:human|person|someone|agent)\b/,
817
+ /\bcustomer\s+support\b/,
818
+ /\bspeak\s+to\s+(?:a\s+)?(?:human|person|someone|agent)\b/,
819
+ /\bneed\s+(?:a\s+)?(?:human|person|agent)\b/,
820
+ /\bconnect\s+me\s+(?:to|with)\b/,
821
+ /\blive\s+agent\b/,
822
+ /\brepresentative\b/
823
+ ];
824
+ return patterns.some((p) => p.test(lower));
825
+ }
826
+ function isNameDecline(utterance) {
827
+ const lower = utterance.toLowerCase().trim();
828
+ const declinePhrases = [
829
+ "i do not want to say my name",
830
+ "i don't want to say my name",
831
+ "i don't want to say",
832
+ "i do not want to say",
833
+ "i'd rather not",
834
+ "id rather not",
835
+ "prefer not",
836
+ "skip",
837
+ "anonymous",
838
+ "none"
839
+ ];
840
+ if (declinePhrases.some((p) => lower.includes(p))) return true;
841
+ if (/\bno\b/i.test(utterance) && !/\bknow\b/i.test(utterance)) {
842
+ const words = lower.split(/\s+/);
843
+ if (words.includes("no")) return true;
844
+ }
845
+ return false;
846
+ }
847
+ function extractName(utterance) {
848
+ const trimmed = utterance.trim();
849
+ const patterns = [/(?:my name is|i'm|i am|call me)\s+(.+)/i];
850
+ for (const pattern of patterns) {
851
+ const match = trimmed.match(pattern);
852
+ if (match?.[1]) {
853
+ return sanitizeName(match[1]);
854
+ }
855
+ }
856
+ if (trimmed.length > 0 && trimmed.length <= 60) {
857
+ return sanitizeName(trimmed);
858
+ }
859
+ return null;
860
+ }
861
+ function sanitizeName(raw) {
862
+ let name = raw.trim().replace(/[.,!?;:]+$/g, "").trim();
863
+ if (name.length > 40) {
864
+ name = name.slice(0, 40).trim();
865
+ }
866
+ return name;
867
+ }
868
+ function helloAfterName(state) {
869
+ if (state.name && !state.nameDeclined) {
870
+ return `Hello, ${state.name}, how can I help you today? I just sent you our menu, what do you want to do?`;
871
+ }
872
+ return "Hello, how can I help you today? I just sent you our menu, what do you want to do?";
873
+ }
874
+ function transitionAfterName(state, name, declined) {
875
+ const next = {
876
+ ...state,
877
+ phase: "awaitingMenuChoice",
878
+ nameDeclined: declined,
879
+ name: declined ? void 0 : name ?? void 0
880
+ };
881
+ const lines = [];
882
+ const messages = [];
883
+ if (declined) {
884
+ const decline = speakAndChat(NAME_DECLINE_REPLY);
885
+ lines.push(...decline.speakLines);
886
+ messages.push(...decline.messages);
887
+ } else if (name) {
888
+ const thanks = speakAndChat(`Great, thank you ${name}`);
889
+ lines.push(...thanks.speakLines);
890
+ messages.push(...thanks.messages);
891
+ }
892
+ const hello = speakAndChat(helloAfterName(next));
893
+ lines.push(...hello.speakLines);
894
+ messages.push(...hello.messages);
895
+ messages.push(...buildMenuMessages());
896
+ return { state: next, speakLines: lines, messages };
897
+ }
898
+ function parseMenuChoice(utterance) {
899
+ const lower = utterance.toLowerCase().trim();
900
+ if (/\bmenu\b/.test(lower) || /\bhelp\b/.test(lower) || /\bgo\s+back\b/.test(lower) || /\bstart\s+over\b/.test(lower)) {
901
+ return "menu";
902
+ }
903
+ if (lower === "1" || /\bweather\b/.test(lower) || /\bfirst\b/.test(lower) || /\bcheck\s+the\s+weather\b/.test(lower)) {
904
+ return "weather";
905
+ }
906
+ if (lower === "2" || /\bcount\b/.test(lower) || /\bsecond\b/.test(lower)) {
907
+ return "count";
908
+ }
909
+ if (lower === "3" || /\brecipe\b/.test(lower) || /\bthird\b/.test(lower)) {
910
+ return "recipe";
911
+ }
912
+ if (lower === "4" || /\bfun\s+fact\b/.test(lower) || /\bfact\b/.test(lower) || /\bfourth\b/.test(lower)) {
913
+ return "fun_fact";
914
+ }
915
+ return null;
916
+ }
917
+ var WORD_TO_NUMBER = {
918
+ one: 1,
919
+ two: 2,
920
+ three: 3,
921
+ four: 4,
922
+ five: 5,
923
+ six: 6,
924
+ seven: 7,
925
+ eight: 8,
926
+ nine: 9,
927
+ ten: 10
928
+ };
929
+ function parseCountNumber(utterance) {
930
+ const trimmed = utterance.trim().toLowerCase();
931
+ const digit = trimmed.match(/\b(\d+)\b/);
932
+ if (digit) {
933
+ const n = Number(digit[1]);
934
+ if (Number.isFinite(n)) return n;
935
+ }
936
+ for (const [word, value] of Object.entries(WORD_TO_NUMBER)) {
937
+ if (new RegExp(`\\b${word}\\b`).test(trimmed)) {
938
+ return value;
939
+ }
940
+ }
941
+ return null;
942
+ }
943
+ function formatCountingSpeech(n) {
944
+ const parts = [];
945
+ for (let i = 1; i <= n; i += 1) {
946
+ parts.push(String(i));
947
+ }
948
+ return parts.join(", ");
949
+ }
950
+ function resendMenu(state) {
951
+ const menu = speakAndChat("Here is the menu again.");
952
+ return {
953
+ state: { ...state, phase: "awaitingMenuChoice" },
954
+ speakLines: menu.speakLines,
955
+ messages: [...menu.messages, ...buildMenuMessages()]
956
+ };
957
+ }
958
+ function returnToMenu(state, line) {
959
+ const spoken = speakAndChat(line);
960
+ return {
961
+ state: {
962
+ ...state,
963
+ phase: "awaitingMenuChoice",
964
+ weatherRetries: 0,
965
+ countFailures: 0,
966
+ weatherCity: void 0,
967
+ weatherCountry: void 0
968
+ },
969
+ speakLines: spoken.speakLines,
970
+ messages: [...spoken.messages, ...buildMenuMessages()]
971
+ };
972
+ }
973
+ function handleUtterance(state, utterance) {
974
+ const text = utterance.trim();
975
+ if (!text) {
976
+ return { state, speakLines: [], messages: [] };
977
+ }
978
+ if (isHumanEscalation(text)) {
979
+ const reply = speakAndChat(HUMAN_ESCALATION_REPLY);
980
+ return {
981
+ state,
982
+ speakLines: reply.speakLines,
983
+ messages: reply.messages
984
+ };
985
+ }
986
+ if (state.phase !== "listeningForName" && parseMenuChoice(text) === "menu") {
987
+ return resendMenu({
988
+ ...state,
989
+ phase: "awaitingMenuChoice",
990
+ weatherRetries: 0,
991
+ countFailures: 0,
992
+ weatherCity: void 0,
993
+ weatherCountry: void 0
994
+ });
995
+ }
996
+ switch (state.phase) {
997
+ case "listeningForName": {
998
+ if (isNameDecline(text)) {
999
+ return transitionAfterName(state, null, true);
1000
+ }
1001
+ const name = extractName(text);
1002
+ return transitionAfterName(state, name, false);
1003
+ }
1004
+ case "awaitingMenuChoice": {
1005
+ const choice = parseMenuChoice(text);
1006
+ if (choice === "menu") return resendMenu(state);
1007
+ if (choice === "weather") {
1008
+ const ask = speakAndChat(
1009
+ "Sure. Please tell me a city or ZIP code and the country."
1010
+ );
1011
+ return {
1012
+ state: {
1013
+ ...state,
1014
+ phase: "weatherAwaitingLocation",
1015
+ weatherRetries: 0,
1016
+ weatherCity: void 0,
1017
+ weatherCountry: void 0
1018
+ },
1019
+ speakLines: ask.speakLines,
1020
+ messages: ask.messages
1021
+ };
1022
+ }
1023
+ if (choice === "count") {
1024
+ const ask = speakAndChat(
1025
+ "Pick a number from 1 to 10 and I will count up to it."
1026
+ );
1027
+ return {
1028
+ state: {
1029
+ ...state,
1030
+ phase: "countAwaitingNumber",
1031
+ countFailures: 0
1032
+ },
1033
+ speakLines: ask.speakLines,
1034
+ messages: ask.messages
1035
+ };
1036
+ }
1037
+ if (choice === "recipe") {
1038
+ const ask = speakAndChat(
1039
+ "What do you fancy? Try pasta, soup, breakfast, cookies, or salad."
1040
+ );
1041
+ return {
1042
+ state: { ...state, phase: "recipeAwaitingChoice" },
1043
+ speakLines: ask.speakLines,
1044
+ messages: ask.messages
1045
+ };
1046
+ }
1047
+ if (choice === "fun_fact") {
1048
+ const fact = pickFunFact();
1049
+ return returnToMenu(state, `Here is a fun fact. ${fact}`);
1050
+ }
1051
+ const retry = speakAndChat(
1052
+ "I did not catch that. Pick 1 through 4 from the menu, or say weather, count, recipe, or fun fact."
1053
+ );
1054
+ return {
1055
+ state,
1056
+ speakLines: retry.speakLines,
1057
+ messages: retry.messages
1058
+ };
1059
+ }
1060
+ case "weatherAwaitingLocation": {
1061
+ const parsed = parseLocationUtterance(text);
1062
+ const city = parsed?.city ?? state.weatherCity;
1063
+ const country = parsed?.country ?? state.weatherCountry;
1064
+ if (!city) {
1065
+ const ask = speakAndChat(
1066
+ "Please tell me a city or ZIP code and the country."
1067
+ );
1068
+ return {
1069
+ state: { ...state, phase: "weatherAwaitingLocation" },
1070
+ speakLines: ask.speakLines,
1071
+ messages: ask.messages
1072
+ };
1073
+ }
1074
+ if (!country && !parsed?.country && !state.weatherCountry) {
1075
+ return {
1076
+ state: {
1077
+ ...state,
1078
+ phase: "weatherAwaitingLocation",
1079
+ weatherCity: city
1080
+ },
1081
+ speakLines: ["Got it. Which country is that in?"],
1082
+ messages: [
1083
+ { type: "chat_reply", text: "Got it. Which country is that in?" }
1084
+ ]
1085
+ };
1086
+ }
1087
+ const resolvedCountry = country ?? state.weatherCountry;
1088
+ return {
1089
+ state: { ...state, weatherCity: city, weatherCountry: resolvedCountry },
1090
+ speakLines: [],
1091
+ messages: [],
1092
+ pendingWeather: { city, country: resolvedCountry }
1093
+ };
1094
+ }
1095
+ case "countAwaitingNumber": {
1096
+ const n = parseCountNumber(text);
1097
+ if (n === null || n < 1 || n > 10) {
1098
+ const failures = state.countFailures + 1;
1099
+ if (failures >= 2) {
1100
+ return returnToMenu(state, "Sorry, I cannot do this.");
1101
+ }
1102
+ const retry = speakAndChat(
1103
+ "I did not understand you. Please say a number from 1 to 10."
1104
+ );
1105
+ return {
1106
+ state: { ...state, countFailures: failures },
1107
+ speakLines: retry.speakLines,
1108
+ messages: retry.messages
1109
+ };
1110
+ }
1111
+ const counting = formatCountingSpeech(n);
1112
+ return returnToMenu(state, `Counting: ${counting}.`);
1113
+ }
1114
+ case "recipeAwaitingChoice": {
1115
+ const recipe = pickRecipe(text);
1116
+ const speech = formatRecipeSpeech(recipe);
1117
+ return returnToMenu(state, speech);
1118
+ }
1119
+ default:
1120
+ return { state, speakLines: [], messages: [] };
1121
+ }
1122
+ }
1123
+ function applyWeatherSuccess(state, weather) {
1124
+ const line = formatWeatherSpeech(weather);
1125
+ return returnToMenu(state, line);
1126
+ }
1127
+ function applyWeatherFailure(state) {
1128
+ const retries = state.weatherRetries + 1;
1129
+ if (retries >= 2) {
1130
+ return returnToMenu(
1131
+ { ...state, weatherRetries: retries },
1132
+ "Sorry, I could not look up the weather right now."
1133
+ );
1134
+ }
1135
+ const retry = speakAndChat(
1136
+ "I could not find that location. Please try again with a city or ZIP and country."
1137
+ );
1138
+ return {
1139
+ state: {
1140
+ ...state,
1141
+ phase: "weatherAwaitingLocation",
1142
+ weatherRetries: retries,
1143
+ weatherCity: void 0,
1144
+ weatherCountry: void 0
1145
+ },
1146
+ speakLines: retry.speakLines,
1147
+ messages: retry.messages
1148
+ };
1149
+ }
1150
+ async function resolveWeatherTurn(state, city, country, fetchFn) {
1151
+ try {
1152
+ const weather = await lookupWeather(city, country, fetchFn);
1153
+ if (!weather) {
1154
+ return applyWeatherFailure(state);
1155
+ }
1156
+ return applyWeatherSuccess(state, weather);
1157
+ } catch {
1158
+ return applyWeatherFailure(state);
1159
+ }
1160
+ }
1161
+
1162
+ // templates/voice-showcase/agent.ts
1163
+ var sessions = /* @__PURE__ */ new Map();
1164
+ function getState(sessionId) {
1165
+ let state = sessions.get(sessionId);
1166
+ if (!state) {
1167
+ state = createInitialState();
1168
+ sessions.set(sessionId, state);
1169
+ }
1170
+ return state;
1171
+ }
1172
+ function relaySpeechEvent(sessionId, event) {
1173
+ sendToClient(sessionId, {
1174
+ type: "agent_event",
1175
+ event: event.type,
1176
+ text: event.text,
1177
+ raw: event
1178
+ });
1179
+ }
1180
+ function deliverMessages(sessionId, messages) {
1181
+ for (const message of messages) {
1182
+ sendToClient(sessionId, message);
1183
+ }
1184
+ }
1185
+ function speakLines(sessionId, lines) {
1186
+ for (const line of lines) {
1187
+ speak(sessionId, line);
1188
+ }
1189
+ }
1190
+ async function applyTurn(sessionId, result) {
1191
+ sessions.set(sessionId, result.state);
1192
+ speakLines(sessionId, result.speakLines);
1193
+ deliverMessages(sessionId, result.messages);
1194
+ if (result.pendingWeather) {
1195
+ const weatherResult = await resolveWeatherTurn(
1196
+ result.state,
1197
+ result.pendingWeather.city,
1198
+ result.pendingWeather.country
1199
+ );
1200
+ sessions.set(sessionId, weatherResult.state);
1201
+ speakLines(sessionId, weatherResult.speakLines);
1202
+ deliverMessages(sessionId, weatherResult.messages);
1203
+ }
1204
+ }
1205
+ async function onUserText(sessionId, text) {
1206
+ const state = getState(sessionId);
1207
+ const result = handleUtterance(state, text);
1208
+ await applyTurn(sessionId, result);
1209
+ }
1210
+ defineAgent({
1211
+ onSessionStart({ sessionId }) {
1212
+ sessions.set(sessionId, createInitialState());
1213
+ sendToClient(sessionId, {
1214
+ type: "agent_event",
1215
+ event: "session_start",
1216
+ sessionId
1217
+ });
1218
+ speak(sessionId, GREETING);
1219
+ sendToClient(sessionId, { type: "chat_reply", text: GREETING });
1220
+ agentLog("info", `voice-showcase session_start ${sessionId}`);
1221
+ },
1222
+ onSpeechEvent({ sessionId }, event) {
1223
+ relaySpeechEvent(sessionId, event);
1224
+ },
1225
+ onUserSpeechFinal({ sessionId, text }) {
1226
+ void onUserText(sessionId, text);
1227
+ },
1228
+ onDataChannelMessage(ctx) {
1229
+ const text = parseChatText(ctx.message);
1230
+ if (!text) return;
1231
+ void onUserText(ctx.sessionId, text);
1232
+ },
1233
+ onSessionEnd({ sessionId }) {
1234
+ sessions.delete(sessionId);
1235
+ sendToClient(sessionId, {
1236
+ type: "agent_event",
1237
+ event: "session_end",
1238
+ sessionId
1239
+ });
1240
+ agentLog("info", `voice-showcase session_end ${sessionId}`);
1241
+ }
1242
+ });