@speeq/client 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1020 @@
1
+ // ../core/src/errors.ts
2
+ var ERROR_CODES = [
3
+ "UNAUTHENTICATED",
4
+ "FORBIDDEN",
5
+ "INVALID_INPUT",
6
+ "NOT_FOUND",
7
+ "CONFLICT",
8
+ "RATE_LIMITED",
9
+ "PROVIDER_ERROR",
10
+ "TOOL_ERROR",
11
+ "TOOL_TIMEOUT",
12
+ "CONFIRMATION_REQUIRED",
13
+ "SESSION_EXPIRED",
14
+ "NOT_CONFIGURED",
15
+ "INTERNAL"
16
+ ];
17
+ var ERROR_HTTP_STATUS = {
18
+ UNAUTHENTICATED: 401,
19
+ FORBIDDEN: 403,
20
+ INVALID_INPUT: 400,
21
+ NOT_FOUND: 404,
22
+ CONFLICT: 409,
23
+ RATE_LIMITED: 429,
24
+ PROVIDER_ERROR: 502,
25
+ TOOL_ERROR: 500,
26
+ TOOL_TIMEOUT: 504,
27
+ CONFIRMATION_REQUIRED: 409,
28
+ SESSION_EXPIRED: 401,
29
+ NOT_CONFIGURED: 500,
30
+ INTERNAL: 500
31
+ };
32
+ var DEFAULT_ERROR_MESSAGES = {
33
+ UNAUTHENTICATED: "Please sign in to continue.",
34
+ FORBIDDEN: "You are not allowed to do that.",
35
+ INVALID_INPUT: "The request was not valid.",
36
+ NOT_FOUND: "That could not be found.",
37
+ CONFLICT: "That was already handled.",
38
+ RATE_LIMITED: "The assistant is busy right now. Please try again in a moment.",
39
+ PROVIDER_ERROR: "The AI provider had a problem. Please try again.",
40
+ TOOL_ERROR: "An action failed to run.",
41
+ TOOL_TIMEOUT: "An action took too long and was stopped.",
42
+ CONFIRMATION_REQUIRED: "This action needs your confirmation.",
43
+ SESSION_EXPIRED: "Your session expired. Starting a new one.",
44
+ NOT_CONFIGURED: "The assistant is not configured correctly.",
45
+ INTERNAL: "Something went wrong."
46
+ };
47
+ var RETRYABLE = /* @__PURE__ */ new Set([
48
+ "RATE_LIMITED",
49
+ "PROVIDER_ERROR",
50
+ "TOOL_TIMEOUT",
51
+ "SESSION_EXPIRED"
52
+ ]);
53
+ var SpeeqError = class extends Error {
54
+ /** Brand used by {@link isSpeeqError} so checks work across bundled copies. */
55
+ isSpeeqError = true;
56
+ code;
57
+ retryable;
58
+ retryAfterMs;
59
+ details;
60
+ constructor(code, options = {}) {
61
+ super(options.message ?? DEFAULT_ERROR_MESSAGES[code], { cause: options.cause });
62
+ this.name = "SpeeqError";
63
+ this.code = code;
64
+ this.retryable = options.retryable ?? RETRYABLE.has(code);
65
+ this.retryAfterMs = options.retryAfterMs;
66
+ this.details = options.details;
67
+ }
68
+ /** HTTP status for this error. */
69
+ get status() {
70
+ return ERROR_HTTP_STATUS[this.code];
71
+ }
72
+ };
73
+ function isSpeeqError(value) {
74
+ return typeof value === "object" && value !== null && value.isSpeeqError === true && typeof value.code === "string";
75
+ }
76
+ function isErrorCode(value) {
77
+ return typeof value === "string" && ERROR_CODES.includes(value);
78
+ }
79
+ function toSpeeqError(error, fallback = "INTERNAL") {
80
+ if (isSpeeqError(error)) return error;
81
+ if (isAbortError(error))
82
+ return new SpeeqError("INTERNAL", { message: "Cancelled.", cause: error });
83
+ return new SpeeqError(fallback, { cause: error });
84
+ }
85
+ function toPublicError(error) {
86
+ const e = toSpeeqError(error);
87
+ const out = { code: e.code, message: e.message, retryable: e.retryable };
88
+ if (e.retryAfterMs !== void 0) out.retryAfterMs = e.retryAfterMs;
89
+ return out;
90
+ }
91
+ function isAbortError(error) {
92
+ return typeof error === "object" && error !== null && (error.name === "AbortError" || error.name === "TimeoutError");
93
+ }
94
+
95
+ // src/audit.ts
96
+ function record(value) {
97
+ return !!value && typeof value === "object" && !Array.isArray(value);
98
+ }
99
+ function aborted(error, signal) {
100
+ return signal?.aborted || record(error) && error.name === "AbortError";
101
+ }
102
+ function createAuditClient(options) {
103
+ const endpoint = options.endpoint.replace(/\/+$/, "");
104
+ async function get(path, signal, valid2) {
105
+ let response;
106
+ try {
107
+ response = await (options.fetch ?? globalThis.fetch)(endpoint + path, {
108
+ method: "GET",
109
+ credentials: options.credentials ?? "include",
110
+ headers: options.headers,
111
+ signal
112
+ });
113
+ } catch (error) {
114
+ if (aborted(error, signal)) throw error;
115
+ throw new SpeeqError("INTERNAL", { message: "Could not reach the server.", retryable: true });
116
+ }
117
+ let data;
118
+ try {
119
+ data = await response.json();
120
+ } catch (error) {
121
+ if (aborted(error, signal)) throw error;
122
+ throw new SpeeqError("INTERNAL");
123
+ }
124
+ if (!response.ok) {
125
+ const error = record(data) ? data.error : void 0;
126
+ if (record(error) && isErrorCode(error.code) && typeof error.message === "string" && typeof error.retryable === "boolean") {
127
+ throw new SpeeqError(error.code, { message: error.message, retryable: error.retryable });
128
+ }
129
+ throw new SpeeqError("INTERNAL");
130
+ }
131
+ if (!valid2(data)) throw new SpeeqError("INTERNAL");
132
+ return data;
133
+ }
134
+ return {
135
+ listSessions(params = {}, signal) {
136
+ const query = new URLSearchParams();
137
+ for (const key of ["userId", "from", "to", "limit", "cursor"]) {
138
+ const value = params[key];
139
+ if (value !== void 0 && value !== null && value !== "") query.set(key, String(value));
140
+ }
141
+ const suffix = query.size ? `?${query}` : "";
142
+ return get(
143
+ `/audit/sessions${suffix}`,
144
+ signal,
145
+ (data) => record(data) && Array.isArray(data.sessions)
146
+ );
147
+ },
148
+ getSession(id, signal) {
149
+ return get(
150
+ `/audit/sessions/${encodeURIComponent(id)}`,
151
+ signal,
152
+ (data) => record(data) && record(data.session) && Array.isArray(data.events)
153
+ );
154
+ }
155
+ };
156
+ }
157
+
158
+ // ../core/src/utils/emitter.ts
159
+ var TypedEmitter = class {
160
+ listeners = /* @__PURE__ */ new Map();
161
+ /** Subscribes to `event`. Returns an unsubscribe function. */
162
+ on(event, listener) {
163
+ let set = this.listeners.get(event);
164
+ if (!set) {
165
+ set = /* @__PURE__ */ new Set();
166
+ this.listeners.set(event, set);
167
+ }
168
+ set.add(listener);
169
+ return () => this.off(event, listener);
170
+ }
171
+ /** Subscribes to the next `event` only. */
172
+ once(event, listener) {
173
+ const off = this.on(event, (payload) => {
174
+ off();
175
+ listener(payload);
176
+ });
177
+ return off;
178
+ }
179
+ /** Removes a listener. */
180
+ off(event, listener) {
181
+ this.listeners.get(event)?.delete(listener);
182
+ }
183
+ /** Calls every listener for `event` with `payload`. */
184
+ emit(event, payload) {
185
+ const set = this.listeners.get(event);
186
+ if (!set) return;
187
+ for (const listener of [...set]) {
188
+ try {
189
+ listener(payload);
190
+ } catch (error) {
191
+ console.error("[speeq] event listener threw", error);
192
+ }
193
+ }
194
+ }
195
+ /** Removes every listener. */
196
+ clear() {
197
+ this.listeners.clear();
198
+ }
199
+ };
200
+
201
+ // ../core/src/utils/ids.ts
202
+ function createId(prefix) {
203
+ return `${prefix}_${globalThis.crypto.randomUUID().replace(/-/g, "")}`;
204
+ }
205
+
206
+ // ../core/src/utils/sse.ts
207
+ var SseParser = class {
208
+ buffer = "";
209
+ event = "";
210
+ data = [];
211
+ id;
212
+ /** Adds a chunk and returns every message completed by it. */
213
+ push(chunk) {
214
+ this.buffer += chunk;
215
+ const out = [];
216
+ for (; ; ) {
217
+ const match = /\r\n|\r|\n/.exec(this.buffer);
218
+ if (!match) break;
219
+ if (match[0] === "\r" && match.index === this.buffer.length - 1) break;
220
+ const line = this.buffer.slice(0, match.index);
221
+ this.buffer = this.buffer.slice(match.index + match[0].length);
222
+ const message = this.processLine(line);
223
+ if (message) out.push(message);
224
+ }
225
+ return out;
226
+ }
227
+ /** Flushes a final message that was not followed by a blank line (end of stream). */
228
+ end() {
229
+ const out = this.buffer.length > 0 ? this.push("\n") : [];
230
+ const last = this.dispatch();
231
+ return last ? [...out, last] : out;
232
+ }
233
+ processLine(line) {
234
+ if (line === "") return this.dispatch();
235
+ if (line.startsWith(":")) return null;
236
+ const colon = line.indexOf(":");
237
+ const field = colon === -1 ? line : line.slice(0, colon);
238
+ let value = colon === -1 ? "" : line.slice(colon + 1);
239
+ if (value.startsWith(" ")) value = value.slice(1);
240
+ if (field === "event") this.event = value;
241
+ else if (field === "data") this.data.push(value);
242
+ else if (field === "id") this.id = value;
243
+ return null;
244
+ }
245
+ dispatch() {
246
+ if (this.data.length === 0) {
247
+ this.event = "";
248
+ return null;
249
+ }
250
+ const message = { event: this.event || "message", data: this.data.join("\n") };
251
+ if (this.id !== void 0) message.id = this.id;
252
+ this.event = "";
253
+ this.data = [];
254
+ return message;
255
+ }
256
+ };
257
+
258
+ // ../core/src/utils/sentence-chunker.ts
259
+ var END_RE = /([.!?…。!?।॥]+["')\]]*)\s+/u;
260
+ var SentenceChunker = class {
261
+ buffer = "";
262
+ maxLength;
263
+ constructor(options = {}) {
264
+ this.maxLength = options.maxLength ?? 220;
265
+ }
266
+ /** Adds a delta and returns every sentence it completed (never empty strings). */
267
+ push(delta) {
268
+ this.buffer += delta;
269
+ const out = [];
270
+ for (let s = this.take(); s !== null; s = this.take()) {
271
+ if (s.length > 0) out.push(s);
272
+ }
273
+ return out;
274
+ }
275
+ /** Returns the buffered remainder (trimmed, may be empty) and resets the chunker. */
276
+ flush() {
277
+ const rest = this.buffer.trim();
278
+ this.buffer = "";
279
+ return rest;
280
+ }
281
+ take() {
282
+ const match = END_RE.exec(this.buffer);
283
+ const endIdx = match ? match.index + (match[1]?.length ?? 0) : -1;
284
+ const newline = this.buffer.indexOf("\n");
285
+ const candidates = [endIdx, newline].filter((i) => i >= 0);
286
+ if (candidates.length > 0) return this.cut(Math.min(...candidates));
287
+ if (this.buffer.length > this.maxLength) {
288
+ const window = this.buffer.slice(0, this.maxLength);
289
+ const soft = Math.max(window.lastIndexOf(", "), window.lastIndexOf(" "));
290
+ return this.cut(soft > this.maxLength / 3 ? soft + 1 : this.maxLength);
291
+ }
292
+ return null;
293
+ }
294
+ cut(at) {
295
+ const sentence = this.buffer.slice(0, at).trim();
296
+ this.buffer = this.buffer.slice(at).replace(/^\s+/, "");
297
+ return sentence;
298
+ }
299
+ };
300
+
301
+ // src/context.ts
302
+ function pageContext(getContext) {
303
+ let context = {};
304
+ if (typeof location !== "undefined") context.path = location.pathname + location.search;
305
+ if (typeof document !== "undefined") context.title = document.title;
306
+ try {
307
+ context = { ...context, ...getContext?.() };
308
+ } catch (error) {
309
+ console.error("[speeq] getContext threw", error);
310
+ }
311
+ return context.path ? context : void 0;
312
+ }
313
+
314
+ // src/stream.ts
315
+ var RequestError = class extends SpeeqError {
316
+ constructor(httpStatus, error) {
317
+ super(error.code, error);
318
+ this.httpStatus = httpStatus;
319
+ }
320
+ httpStatus;
321
+ };
322
+ async function post(fetcher, url, body, signal, token) {
323
+ const headers = { "content-type": "application/json" };
324
+ if (token) {
325
+ headers.authorization = `Bearer ${token}`;
326
+ headers.accept = "text/event-stream";
327
+ }
328
+ const init = { method: "POST", headers, body: JSON.stringify(body), signal };
329
+ signal.throwIfAborted();
330
+ let response;
331
+ try {
332
+ response = await fetcher(url, init);
333
+ } catch {
334
+ throw new SpeeqError("INTERNAL", {
335
+ message: "Could not reach the assistant. Check your connection.",
336
+ retryable: true
337
+ });
338
+ }
339
+ if (response.ok) return response;
340
+ const error = (await response.json().catch(() => null))?.error;
341
+ if (isErrorCode(error?.code) && typeof error.message === "string" && typeof error.retryable === "boolean") {
342
+ throw new RequestError(response.status, error);
343
+ }
344
+ throw new SpeeqError("INTERNAL", { retryable: true });
345
+ }
346
+ var known = /* @__PURE__ */ new Set([
347
+ "turn.started",
348
+ "assistant.delta",
349
+ "assistant.message",
350
+ "tool.started",
351
+ "tool.finished",
352
+ "navigate",
353
+ "confirmation.required",
354
+ "error",
355
+ "turn.finished"
356
+ ]);
357
+ function parse(data) {
358
+ try {
359
+ const value = JSON.parse(data);
360
+ if (value && typeof value === "object" && value.protocolVersion === 1 && known.has(value.type))
361
+ return value;
362
+ } catch {
363
+ }
364
+ return void 0;
365
+ }
366
+ async function* readEvents(response, signal) {
367
+ const reader = response.body?.getReader();
368
+ const interrupted = () => new SpeeqError("INTERNAL", { message: "The connection was interrupted.", retryable: true });
369
+ if (!reader) throw interrupted();
370
+ const cancel = () => {
371
+ void reader.cancel().catch(() => {
372
+ });
373
+ };
374
+ signal.addEventListener("abort", cancel);
375
+ const decoder = new TextDecoder();
376
+ const parser = new SseParser();
377
+ try {
378
+ while (!signal.aborted) {
379
+ const { value, done } = await reader.read();
380
+ const frames = parser.push(decoder.decode(value, { stream: !done }));
381
+ if (done) frames.push(...parser.end());
382
+ for (const frame of frames) {
383
+ if (signal.aborted) return;
384
+ const event = parse(frame.data);
385
+ if (event) yield event;
386
+ if (event?.type === "turn.finished") return;
387
+ }
388
+ if (done) break;
389
+ }
390
+ } catch {
391
+ throw interrupted();
392
+ } finally {
393
+ signal.removeEventListener("abort", cancel);
394
+ cancel();
395
+ reader.releaseLock();
396
+ }
397
+ if (!signal.aborted) throw interrupted();
398
+ }
399
+
400
+ // src/session.ts
401
+ function valid(s) {
402
+ const c = s?.config;
403
+ return !!s && typeof s.sessionId === "string" && !!s.sessionId && typeof s.sessionToken === "string" && !!s.sessionToken && typeof s.expiresAt === "string" && Number.isFinite(Date.parse(s.expiresAt)) && !!c && typeof c.agentName === "string" && Array.isArray(c.languages) && c.languages.length > 0 && c.languages.every((l) => typeof l === "string") && c.languages.includes(c.defaultLanguage) && !!c.features && ["navigation", "knowledge", "tools", "audit"].every(
404
+ (k) => typeof c.features[k] === "boolean"
405
+ ) && Array.isArray(c.routes) && c.routes.every((r) => typeof r?.id === "string" && typeof r.title === "string");
406
+ }
407
+ function sessions(options, onSession) {
408
+ const endpoint = options.endpoint.replace(/\/+$/, "");
409
+ const key = `speeq:session:${endpoint}`;
410
+ const fetcher = (url, init) => (options.fetch ?? globalThis.fetch)(url, init);
411
+ let current = null;
412
+ function storage(fn) {
413
+ try {
414
+ if (options.persistSession === "sessionStorage" && typeof sessionStorage !== "undefined")
415
+ return fn(sessionStorage);
416
+ } catch {
417
+ }
418
+ return void 0;
419
+ }
420
+ async function ensure(language, signal, refresh) {
421
+ let session = current ?? (refresh ? null : storage((s) => JSON.parse(s.getItem(key) ?? "null")));
422
+ if (!valid(session) || Date.parse(session.expiresAt) <= Date.now() + 3e4) {
423
+ const response = await post(
424
+ fetcher,
425
+ `${endpoint}/session`,
426
+ { language, context: pageContext(options.getContext) },
427
+ signal
428
+ );
429
+ const data = await response.json();
430
+ signal.throwIfAborted();
431
+ if (!valid(data)) throw new SpeeqError("INTERNAL", { retryable: true });
432
+ const { sessionId, sessionToken, expiresAt, config } = data;
433
+ session = { sessionId, sessionToken, expiresAt, config };
434
+ storage((s) => s.setItem(key, JSON.stringify(session)));
435
+ }
436
+ if (session !== current) {
437
+ current = session;
438
+ onSession(session);
439
+ }
440
+ return session;
441
+ }
442
+ return async (path, language, makeBody, signal) => {
443
+ let session = await ensure(language, signal, false);
444
+ signal.throwIfAborted();
445
+ const body = makeBody();
446
+ const send = () => post(
447
+ fetcher,
448
+ `${endpoint}/session/${encodeURIComponent(session.sessionId)}/${path}`,
449
+ body,
450
+ signal,
451
+ session.sessionToken
452
+ );
453
+ try {
454
+ return await send();
455
+ } catch (error) {
456
+ signal.throwIfAborted();
457
+ if (!(error instanceof RequestError) || error.httpStatus !== 401 || !["SESSION_EXPIRED", "UNAUTHENTICATED"].includes(error.code))
458
+ throw error;
459
+ current = null;
460
+ storage((s) => s.removeItem(key));
461
+ session = await ensure(language, signal, true);
462
+ return send();
463
+ }
464
+ };
465
+ }
466
+
467
+ // src/speech-queue.ts
468
+ var SpeechQueue = class {
469
+ constructor(output, enabled) {
470
+ this.output = output;
471
+ this.enabled = enabled;
472
+ }
473
+ output;
474
+ enabled;
475
+ generation = 0;
476
+ tail = Promise.resolve();
477
+ voices = /* @__PURE__ */ new Map();
478
+ pending = 0;
479
+ voice(language) {
480
+ let result = this.voices.get(language);
481
+ if (!result) {
482
+ result = Promise.resolve().then(() => this.output?.hasVoiceFor(language) ?? false).catch(() => false);
483
+ this.voices.set(language, result);
484
+ }
485
+ return result;
486
+ }
487
+ enqueue(text, language, started) {
488
+ if (!text || !this.enabled || !this.output?.supported) return Promise.resolve();
489
+ const generation = this.generation;
490
+ const output = this.output;
491
+ this.pending++;
492
+ this.tail = this.tail.then(async () => {
493
+ if (generation !== this.generation || !await this.voice(language) || generation !== this.generation)
494
+ return;
495
+ started();
496
+ if (generation === this.generation) await output.speak(text, { language });
497
+ }).catch((error) => console.error("[speeq] speech output failed", error)).finally(() => {
498
+ if (generation === this.generation) this.pending--;
499
+ });
500
+ return this.tail;
501
+ }
502
+ drain() {
503
+ return this.tail;
504
+ }
505
+ cancel() {
506
+ this.generation++;
507
+ this.pending = 0;
508
+ this.tail = Promise.resolve();
509
+ this.output?.cancel();
510
+ }
511
+ };
512
+
513
+ // src/web-speech-types.ts
514
+ function globals() {
515
+ return typeof globalThis === "undefined" ? {} : globalThis;
516
+ }
517
+ function recognitionConstructor() {
518
+ const g = globals();
519
+ const ctor = g.SpeechRecognition ?? g.webkitSpeechRecognition;
520
+ return typeof ctor === "function" ? ctor : void 0;
521
+ }
522
+ function synthesisApi() {
523
+ const { speechSynthesis: synth, SpeechSynthesisUtterance: Utterance } = globals();
524
+ if (synth && typeof Utterance === "function") return { synth, Utterance };
525
+ return void 0;
526
+ }
527
+ function detectSpeechSupport() {
528
+ return { input: !!recognitionConstructor(), output: !!synthesisApi() };
529
+ }
530
+
531
+ // src/web-speech-input.ts
532
+ function errorCode(error) {
533
+ switch (error) {
534
+ case "service-not-allowed":
535
+ case "not-allowed":
536
+ return "not-allowed";
537
+ case "aborted":
538
+ case "network":
539
+ case "no-speech":
540
+ return error;
541
+ case "language-not-supported":
542
+ return "unsupported";
543
+ default:
544
+ return "other";
545
+ }
546
+ }
547
+ var WebSpeechInput = class {
548
+ active;
549
+ get supported() {
550
+ return !!recognitionConstructor();
551
+ }
552
+ start(options, handlers) {
553
+ this.abort();
554
+ let finalText = "";
555
+ let previousInterim = "";
556
+ let aborted2 = false;
557
+ let ended = false;
558
+ let session;
559
+ const finish = () => {
560
+ if (ended) return;
561
+ ended = true;
562
+ if (this.active === session) this.active = void 0;
563
+ try {
564
+ if (!aborted2 && finalText.trim()) handlers.onFinal(finalText.trim());
565
+ } finally {
566
+ handlers.onEnd?.();
567
+ }
568
+ };
569
+ try {
570
+ const Recognition = recognitionConstructor();
571
+ if (!Recognition) throw new Error("Speech recognition is unavailable.");
572
+ const recognition = new Recognition();
573
+ session = {
574
+ stop: () => recognition.stop(),
575
+ abort: () => {
576
+ aborted2 = true;
577
+ try {
578
+ recognition.abort();
579
+ } finally {
580
+ finish();
581
+ }
582
+ }
583
+ };
584
+ this.active = session;
585
+ recognition.lang = options.language;
586
+ recognition.interimResults = options.interimResults ?? true;
587
+ recognition.continuous = false;
588
+ recognition.maxAlternatives = 1;
589
+ recognition.onresult = ({ results }) => {
590
+ if (ended || aborted2) return;
591
+ finalText = "";
592
+ let interim = "";
593
+ for (const result of Array.from(results)) {
594
+ const text = result[0]?.transcript ?? "";
595
+ if (result.isFinal) finalText += text;
596
+ else interim += text;
597
+ }
598
+ const changed = interim !== previousInterim;
599
+ previousInterim = interim;
600
+ if (changed && interim) handlers.onInterim?.(interim);
601
+ };
602
+ recognition.onerror = ({ error, message }) => {
603
+ if (ended) return;
604
+ if (error === "aborted") aborted2 = true;
605
+ handlers.onError?.({ code: errorCode(error), message: message || error });
606
+ };
607
+ recognition.onend = finish;
608
+ recognition.start();
609
+ } catch {
610
+ if (ended) return;
611
+ aborted2 = true;
612
+ try {
613
+ handlers.onError?.({ code: "unsupported", message: "Speech recognition is unavailable." });
614
+ } finally {
615
+ finish();
616
+ }
617
+ }
618
+ }
619
+ stop() {
620
+ this.active?.stop();
621
+ }
622
+ abort() {
623
+ this.active?.abort();
624
+ }
625
+ };
626
+
627
+ // src/web-speech-output.ts
628
+ function normalize(language) {
629
+ return language.replaceAll("_", "-").toLowerCase();
630
+ }
631
+ function matchVoice(language, voices) {
632
+ const tag = normalize(language);
633
+ const exact = voices.filter((v) => normalize(v.lang) === tag);
634
+ const preferred = exact.filter((v) => v.default);
635
+ const candidates = preferred.length ? preferred : exact;
636
+ return candidates.find((v) => v.localService) ?? candidates[0] ?? voices.find((v) => normalize(v.lang).split("-")[0] === tag.split("-")[0]);
637
+ }
638
+ var WebSpeechOutput = class {
639
+ constructor(options = {}) {
640
+ this.options = options;
641
+ }
642
+ options;
643
+ waiting;
644
+ pending = /* @__PURE__ */ new Set();
645
+ get supported() {
646
+ return !!synthesisApi();
647
+ }
648
+ async voice(language, synth) {
649
+ let voices = synth.getVoices();
650
+ if (!voices.length) {
651
+ this.waiting ??= new Promise((resolve) => {
652
+ const ready = () => {
653
+ clearTimeout(timer);
654
+ synth.removeEventListener("voiceschanged", ready);
655
+ resolve();
656
+ };
657
+ const timer = setTimeout(ready, Math.min(1500, this.options.voicesTimeoutMs ?? 1500));
658
+ synth.addEventListener("voiceschanged", ready);
659
+ }).finally(() => {
660
+ this.waiting = void 0;
661
+ });
662
+ await this.waiting;
663
+ voices = synth.getVoices();
664
+ }
665
+ return this.options.selectVoice?.(language, voices) ?? matchVoice(language, voices);
666
+ }
667
+ async hasVoiceFor(language) {
668
+ const api = synthesisApi();
669
+ return !!api && !!await this.voice(language, api.synth);
670
+ }
671
+ async speak(text, { language, signal }) {
672
+ if (signal?.aborted) return;
673
+ const api = synthesisApi();
674
+ if (!api) return;
675
+ await new Promise((resolve) => {
676
+ let utterance;
677
+ const abort = () => this.cancel();
678
+ const finish = () => {
679
+ this.pending.delete(finish);
680
+ signal?.removeEventListener("abort", abort);
681
+ if (utterance) utterance.onend = utterance.onerror = null;
682
+ resolve();
683
+ };
684
+ this.pending.add(finish);
685
+ signal?.addEventListener("abort", abort);
686
+ void this.voice(language, api.synth).then((voice) => {
687
+ if (!this.pending.has(finish)) return;
688
+ utterance = new api.Utterance(text);
689
+ utterance.lang = language;
690
+ if (voice) utterance.voice = voice;
691
+ utterance.rate = this.options.rate ?? 1;
692
+ utterance.pitch = this.options.pitch ?? 1;
693
+ utterance.onend = utterance.onerror = finish;
694
+ if (api.synth.paused) api.synth.resume();
695
+ api.synth.speak(utterance);
696
+ }).catch(finish);
697
+ });
698
+ }
699
+ cancel() {
700
+ try {
701
+ synthesisApi()?.synth.cancel();
702
+ } finally {
703
+ for (const finish of this.pending) finish();
704
+ }
705
+ }
706
+ };
707
+
708
+ // src/client.ts
709
+ function freeze(value) {
710
+ if (value && typeof value === "object" && !Object.isFrozen(value)) {
711
+ Object.freeze(value);
712
+ for (const child of Object.values(value)) freeze(child);
713
+ }
714
+ return value;
715
+ }
716
+ function createSpeeqClient(options) {
717
+ const { input = new WebSpeechInput(), output = new WebSpeechOutput() } = options.speech ?? {};
718
+ const language = options.language ?? options.languages?.[0] ?? "en-IN";
719
+ let snapshot = freeze({
720
+ state: "idle",
721
+ language,
722
+ languages: [...options.languages ?? [language]],
723
+ messages: [],
724
+ interimTranscript: "",
725
+ pendingConfirmation: null,
726
+ error: null,
727
+ activeTools: [],
728
+ support: {
729
+ speechInput: !!input?.supported,
730
+ speechOutput: !!output?.supported,
731
+ voiceForLanguage: null
732
+ },
733
+ config: null,
734
+ sessionId: null
735
+ });
736
+ const emitter = new TypedEmitter();
737
+ const speech = new SpeechQueue(output, options.speakReplies !== false);
738
+ let generation = 0;
739
+ let turn;
740
+ let destroyed = false;
741
+ if (snapshot.support.speechOutput) {
742
+ setTimeout(() => {
743
+ if (destroyed || snapshot.language !== language) return;
744
+ void speech.voice(language).then((voiceForLanguage) => {
745
+ if (!destroyed && snapshot.language === language && snapshot.support.voiceForLanguage !== voiceForLanguage)
746
+ update({ support: { ...snapshot.support, voiceForLanguage } });
747
+ });
748
+ }, 0);
749
+ }
750
+ function update(patch) {
751
+ const previous = snapshot;
752
+ if (Object.entries(patch).every(([key, value]) => previous[key] === value))
753
+ return;
754
+ const next = freeze({ ...previous, ...patch });
755
+ snapshot = next;
756
+ emitter.emit("change", next);
757
+ if (snapshot !== next) return;
758
+ if (next.state !== previous.state) emitter.emit("state", next.state);
759
+ if (next.error && next.error !== previous.error) emitter.emit("error", next.error);
760
+ }
761
+ const request = sessions(options, ({ sessionId, config }) => {
762
+ const languages = options.languages?.filter((l) => config.languages.includes(l)) ?? config.languages;
763
+ const language2 = languages.includes(snapshot.language) ? snapshot.language : config.defaultLanguage;
764
+ update({
765
+ sessionId,
766
+ config,
767
+ languages,
768
+ language: language2,
769
+ support: language2 === snapshot.language ? snapshot.support : { ...snapshot.support, voiceForLanguage: null }
770
+ });
771
+ });
772
+ function markStreaming(status) {
773
+ return snapshot.messages.some((m) => m.status === "streaming") ? snapshot.messages.map((m) => m.status === "streaming" ? { ...m, status } : m) : snapshot.messages;
774
+ }
775
+ function interrupt(force = false) {
776
+ generation++;
777
+ if (force || turn || speech.pending || snapshot.state === "speaking") speech.cancel();
778
+ turn?.abort();
779
+ turn = void 0;
780
+ if (snapshot.state === "listening") input?.abort();
781
+ }
782
+ function clearActivity() {
783
+ return {
784
+ messages: markStreaming("interrupted"),
785
+ interimTranscript: "",
786
+ error: null,
787
+ activeTools: snapshot.activeTools.length ? [] : snapshot.activeTools
788
+ };
789
+ }
790
+ async function run(user, confirmation) {
791
+ interrupt();
792
+ const controller = new AbortController();
793
+ turn = controller;
794
+ const { signal } = controller;
795
+ const cleared = clearActivity();
796
+ const messages = user ? [
797
+ ...cleared.messages,
798
+ { id: createId("msg"), role: "user", status: "done", text: user.text }
799
+ ] : cleared.messages;
800
+ let language2 = snapshot.language;
801
+ update({ ...cleared, messages, pendingConfirmation: null, state: "thinking" });
802
+ let chunker = new SentenceChunker();
803
+ function enqueue(text) {
804
+ if (!signal.aborted) void speech.enqueue(text, language2, () => update({ state: "speaking" }));
805
+ }
806
+ function fail(error) {
807
+ update({ error, messages: markStreaming("error") });
808
+ }
809
+ function handle(e) {
810
+ switch (e.type) {
811
+ case "assistant.delta":
812
+ case "assistant.message": {
813
+ const last = snapshot.messages.at(-1);
814
+ const streaming = last?.status === "streaming";
815
+ const final = e.type === "assistant.message";
816
+ const message = {
817
+ role: "assistant",
818
+ turnId: e.turnId,
819
+ id: streaming ? last.id : createId("msg"),
820
+ text: streaming && !final ? last.text + e.text : e.text,
821
+ status: final ? "done" : "streaming"
822
+ };
823
+ update({
824
+ messages: [
825
+ ...streaming ? snapshot.messages.slice(0, -1) : snapshot.messages,
826
+ message
827
+ ]
828
+ });
829
+ if (final) {
830
+ enqueue(chunker.flush());
831
+ chunker = new SentenceChunker();
832
+ } else for (const sentence of chunker.push(e.text)) enqueue(sentence);
833
+ break;
834
+ }
835
+ case "tool.started":
836
+ update({
837
+ activeTools: [
838
+ ...snapshot.activeTools.filter((t) => t.callId !== e.callId),
839
+ { callId: e.callId, name: e.name }
840
+ ]
841
+ });
842
+ break;
843
+ case "tool.finished":
844
+ update({ activeTools: snapshot.activeTools.filter((t) => t.callId !== e.callId) });
845
+ break;
846
+ case "navigate": {
847
+ const { routeId, href, params } = e;
848
+ const action = { routeId, href, params };
849
+ try {
850
+ options.onNavigate?.(action);
851
+ } catch (error) {
852
+ console.error("[speeq] onNavigate threw", error);
853
+ }
854
+ emitter.emit("navigate", action);
855
+ break;
856
+ }
857
+ case "confirmation.required": {
858
+ const { confirmationId, toolName, summary, args } = e;
859
+ update({ pendingConfirmation: { confirmationId, toolName, summary, args } });
860
+ break;
861
+ }
862
+ case "error": {
863
+ const { code, message, retryable, retryAfterMs } = e;
864
+ fail({ code, message, retryable, ...retryAfterMs !== void 0 && { retryAfterMs } });
865
+ break;
866
+ }
867
+ }
868
+ }
869
+ try {
870
+ const response = await request(
871
+ user ? "turn" : "confirm",
872
+ language2,
873
+ () => {
874
+ if (!snapshot.languages.includes(language2))
875
+ language2 = snapshot.config?.defaultLanguage ?? language2;
876
+ return user ? { ...user, language: language2, context: pageContext(options.getContext) } : confirmation;
877
+ },
878
+ signal
879
+ );
880
+ for await (const event of readEvents(response, signal)) {
881
+ if (signal.aborted) return;
882
+ handle(event);
883
+ emitter.emit("event", event);
884
+ }
885
+ } catch (error) {
886
+ if (!signal.aborted) fail(toPublicError(error));
887
+ }
888
+ if (signal.aborted) return;
889
+ await speech.drain();
890
+ if (signal.aborted) return;
891
+ turn = void 0;
892
+ update({
893
+ state: snapshot.error ? "error" : speech.pending ? "speaking" : "idle",
894
+ activeTools: snapshot.activeTools.length ? [] : snapshot.activeTools
895
+ });
896
+ }
897
+ function cancel() {
898
+ if (destroyed) return;
899
+ interrupt(true);
900
+ update({ ...clearActivity(), state: "idle" });
901
+ }
902
+ async function sendText(text, { inputMode = "text" } = {}) {
903
+ if (!destroyed && text.trim()) await run({ text: text.trim(), inputMode });
904
+ }
905
+ function startListening() {
906
+ if (destroyed) return;
907
+ interrupt(true);
908
+ if (!input?.supported) {
909
+ update({
910
+ ...clearActivity(),
911
+ state: "error",
912
+ error: {
913
+ code: "NOT_CONFIGURED",
914
+ message: "Voice input is not supported in this browser. Please type instead.",
915
+ retryable: false
916
+ }
917
+ });
918
+ return;
919
+ }
920
+ const id = generation;
921
+ const listening = () => generation === id && snapshot.state === "listening";
922
+ update({ ...clearActivity(), state: "listening" });
923
+ if (!listening()) return;
924
+ input.start(
925
+ { language: snapshot.language, interimResults: true },
926
+ {
927
+ onInterim(text) {
928
+ if (listening()) update({ interimTranscript: text });
929
+ },
930
+ onFinal(text) {
931
+ if (!listening()) return;
932
+ if (options.autoSendOnFinal === false || !text.trim())
933
+ update({
934
+ interimTranscript: options.autoSendOnFinal === false ? text : "",
935
+ state: "idle"
936
+ });
937
+ else void sendText(text, { inputMode: "voice" });
938
+ },
939
+ onError({ code }) {
940
+ if (!listening()) return;
941
+ if (code === "no-speech" || code === "aborted")
942
+ update({ state: "idle", interimTranscript: "" });
943
+ else
944
+ update({
945
+ state: "error",
946
+ interimTranscript: "",
947
+ error: code === "not-allowed" ? {
948
+ code: "FORBIDDEN",
949
+ message: "Microphone permission was denied.",
950
+ retryable: false
951
+ } : {
952
+ code: "INTERNAL",
953
+ message: "Voice input failed. Please try again.",
954
+ retryable: true
955
+ }
956
+ });
957
+ },
958
+ onEnd() {
959
+ if (listening()) update({ state: "idle", interimTranscript: "" });
960
+ }
961
+ }
962
+ );
963
+ }
964
+ return {
965
+ getSnapshot: () => snapshot,
966
+ subscribe: (cb) => destroyed ? () => {
967
+ } : emitter.on("change", cb),
968
+ on: (event, cb) => destroyed ? () => {
969
+ } : emitter.on(event, cb),
970
+ sendText,
971
+ startListening,
972
+ cancel,
973
+ stopListening() {
974
+ if (!destroyed && snapshot.state === "listening") input?.stop();
975
+ },
976
+ async confirm(confirmationId, approved) {
977
+ if (!destroyed) await run(null, { confirmationId, approved });
978
+ },
979
+ setLanguage(language2) {
980
+ if (destroyed) return;
981
+ if (!snapshot.languages.includes(language2))
982
+ throw new SpeeqError("INVALID_INPUT", { message: `Language not enabled: ${language2}` });
983
+ if (snapshot.state === "listening") cancel();
984
+ update({ language: language2, support: { ...snapshot.support, voiceForLanguage: null } });
985
+ if (output)
986
+ void speech.voice(language2).then((voiceForLanguage) => {
987
+ if (!destroyed && snapshot.language === language2)
988
+ update({ support: { ...snapshot.support, voiceForLanguage } });
989
+ });
990
+ },
991
+ async speak(text) {
992
+ if (destroyed) return;
993
+ const id = generation;
994
+ await speech.enqueue(text, snapshot.language, () => {
995
+ const listening = snapshot.state === "listening";
996
+ update({ state: "speaking", interimTranscript: "", ...turn ? {} : { error: null } });
997
+ if (listening && id === generation) input?.abort();
998
+ });
999
+ if (id === generation && !turn && !speech.pending && snapshot.state === "speaking")
1000
+ update({ state: snapshot.error ? "error" : "idle" });
1001
+ },
1002
+ destroy() {
1003
+ if (destroyed) return;
1004
+ destroyed = true;
1005
+ interrupt(true);
1006
+ emitter.clear();
1007
+ update({ ...clearActivity(), state: "idle" });
1008
+ }
1009
+ };
1010
+ }
1011
+ export {
1012
+ SpeeqError,
1013
+ WebSpeechInput,
1014
+ WebSpeechOutput,
1015
+ createAuditClient,
1016
+ createSpeeqClient,
1017
+ detectSpeechSupport,
1018
+ isSpeeqError
1019
+ };
1020
+ //# sourceMappingURL=index.js.map