@skaile/forge-voice 0.0.0-stage → 0.1.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.
@@ -0,0 +1,26 @@
1
+ import { N as VoiceRelayRoute, r as VoiceRelay } from "../relay.mjs";
2
+ import { EventHandler, H3Event } from "h3";
3
+ /** What `authorize` gets as `request.context` from this adapter. */
4
+ export interface H3RelayContext {
5
+ /** The web request: the upgrade request on the WebSocket routes, URL and headers (cookies) without the body on the HTTP routes. */
6
+ request: Request;
7
+ /** The h3 event, on the HTTP routes only (crossws hands an upgrade no event). */
8
+ event?: H3Event;
9
+ }
10
+ export interface VoiceRelayRoutesOptions {
11
+ /** Where each route is served (the full request path); default `VOICE_RELAY_DEFAULT_PATHS` (`/voice/...`). */
12
+ paths?: Partial<Record<VoiceRelayRoute, string>>;
13
+ }
14
+ /**
15
+ * One h3 event handler serving all four relay routes, for a catch-all Nitro route
16
+ * (`server/routes/voice/[...].ts`: `export default defineVoiceRelayRoutes(relay)`) or `router.use`:
17
+ *
18
+ * WS /voice/transcribe-stream speech to text (wire protocol v1, `relay.admit` + `relay.stt`)
19
+ * WS /voice/speak-stream streamed speech (`relay.admit` + `relay.tts`)
20
+ * POST /voice/retranscribe one utterance, body `audio/l16` (`relay.retranscribe`)
21
+ * POST /voice/speak one clip, JSON body (`relay.speak`)
22
+ *
23
+ * The relay's host `authorize` gets an `H3RelayContext`. A refused upgrade answers its HTTP status
24
+ * with no body. Needs `experimental: { websocket: true }` in the Nitro config for the WebSocket routes.
25
+ */
26
+ export declare function defineVoiceRelayRoutes(relay: VoiceRelay<H3RelayContext>, options?: VoiceRelayRoutesOptions): EventHandler;
@@ -0,0 +1,234 @@
1
+ import { a as relayRequest, d as RETRANSCRIBE_CONTENT_TYPE, i as refusalStatusText, p as VOICE_RELAY_DEFAULT_PATHS, r as isRelayRefusal } from "../relay.mjs";
2
+ import { defineEventHandler, getRequestHeader, getRequestURL, getRequestWebStream, sendStream, setResponseHeader, setResponseStatus } from "h3";
3
+ // src/h3/index.ts
4
+ function peerSocket(peer) {
5
+ let open = true;
6
+ const onMessage = [];
7
+ const onClose = [];
8
+ return {
9
+ send(data) {
10
+ if (open) peer.send(data);
11
+ },
12
+ close(code, reason) {
13
+ peer.close(code, reason);
14
+ },
15
+ onMessage: (listener) => void onMessage.push(listener),
16
+ onClose: (listener) => void onClose.push(listener),
17
+ receive(data) {
18
+ if (open) for (const listener of onMessage) listener(data);
19
+ },
20
+ closed() {
21
+ if (!open) return;
22
+ open = false;
23
+ for (const listener of onClose) listener();
24
+ }
25
+ };
26
+ }
27
+ /**
28
+ * A text frame, or binary audio. crossws' Node adapter hands text frames over as bytes too, so a
29
+ * byte frame that is a JSON object counts as text: every control frame of the protocol is one, and
30
+ * audio that happens to parse as a JSON object is not a realistic PCM or webm chunk.
31
+ */
32
+ function frameOf(message) {
33
+ if (typeof message.rawData === "string") return message.rawData;
34
+ const bytes = message.uint8Array();
35
+ if (bytes[0] === 123) try {
36
+ const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
37
+ const parsed = JSON.parse(text);
38
+ if (parsed && typeof parsed === "object") return text;
39
+ } catch {}
40
+ return bytes;
41
+ }
42
+ /** The JSON body of `POST speak`: 10,000 characters of text at up to 4 bytes each, plus the other fields. */
43
+ const MAX_SPEAK_BODY_BYTES = 65536;
44
+ /** The request body, read while it streams in and abandoned past `max` bytes (a chunked upload has no length to check first). */
45
+ async function readLimited(event, max) {
46
+ const stream = getRequestWebStream(event);
47
+ if (!stream) return /* @__PURE__ */ new Uint8Array();
48
+ const reader = stream.getReader();
49
+ const chunks = [];
50
+ let size = 0;
51
+ for (;;) {
52
+ const { done, value } = await reader.read();
53
+ if (done) break;
54
+ size += value.byteLength;
55
+ if (size > max) {
56
+ await reader.cancel().catch(() => void 0);
57
+ return "too-large";
58
+ }
59
+ chunks.push(value);
60
+ }
61
+ const out = new Uint8Array(size);
62
+ let at = 0;
63
+ for (const chunk of chunks) {
64
+ out.set(chunk, at);
65
+ at += chunk.byteLength;
66
+ }
67
+ return out;
68
+ }
69
+ const toBody = (result) => ({
70
+ message: result.message,
71
+ ...result.code ? { code: result.code } : {}
72
+ });
73
+ /**
74
+ * One h3 event handler serving all four relay routes, for a catch-all Nitro route
75
+ * (`server/routes/voice/[...].ts`: `export default defineVoiceRelayRoutes(relay)`) or `router.use`:
76
+ *
77
+ * WS /voice/transcribe-stream speech to text (wire protocol v1, `relay.admit` + `relay.stt`)
78
+ * WS /voice/speak-stream streamed speech (`relay.admit` + `relay.tts`)
79
+ * POST /voice/retranscribe one utterance, body `audio/l16` (`relay.retranscribe`)
80
+ * POST /voice/speak one clip, JSON body (`relay.speak`)
81
+ *
82
+ * The relay's host `authorize` gets an `H3RelayContext`. A refused upgrade answers its HTTP status
83
+ * with no body. Needs `experimental: { websocket: true }` in the Nitro config for the WebSocket routes.
84
+ */
85
+ function defineVoiceRelayRoutes(relay, options = {}) {
86
+ const paths = {
87
+ ...VOICE_RELAY_DEFAULT_PATHS,
88
+ ...options.paths
89
+ };
90
+ const routeOf = (pathname) => Object.keys(paths).find((kind) => paths[kind] === pathname) ?? null;
91
+ const sockets = /* @__PURE__ */ new WeakMap();
92
+ return defineEventHandler({
93
+ websocket: {
94
+ async upgrade(request) {
95
+ const url = new URL(request.url, "http://localhost");
96
+ const kind = routeOf(url.pathname);
97
+ if (kind !== "stt" && kind !== "tts") return new Response(null, {
98
+ status: 404,
99
+ statusText: "Not Found"
100
+ });
101
+ let admitted;
102
+ try {
103
+ admitted = await relay.admit(relayRequest({
104
+ kind,
105
+ url,
106
+ headers: request.headers,
107
+ context: { request }
108
+ }));
109
+ } catch {
110
+ return new Response(null, {
111
+ status: 500,
112
+ statusText: "Internal Server Error"
113
+ });
114
+ }
115
+ if (isRelayRefusal(admitted)) return new Response(null, {
116
+ status: admitted.refuse,
117
+ statusText: refusalStatusText(admitted)
118
+ });
119
+ request.context.voiceAdmission = admitted;
120
+ },
121
+ open(peer) {
122
+ const admission = peer.context.voiceAdmission;
123
+ if (!admission) return peer.close(1011, "upstream-error");
124
+ const socket = peerSocket(peer);
125
+ sockets.set(peer, socket);
126
+ try {
127
+ if (admission.kind === "stt") relay.stt(socket, admission);
128
+ else relay.tts(socket, admission);
129
+ } catch {
130
+ admission.release();
131
+ peer.close(1011, "upstream-error");
132
+ }
133
+ },
134
+ message(peer, message) {
135
+ const socket = sockets.get(peer);
136
+ if (!socket) return;
137
+ if (peer.context.voiceAdmission?.kind === "tts" && message.uint8Array().byteLength > 65536) return peer.close(1009, "frame-too-large");
138
+ socket.receive(frameOf(message));
139
+ },
140
+ close(peer) {
141
+ sockets.get(peer)?.closed();
142
+ sockets.delete(peer);
143
+ },
144
+ error(peer) {
145
+ sockets.get(peer)?.closed();
146
+ sockets.delete(peer);
147
+ }
148
+ },
149
+ async handler(event) {
150
+ const url = getRequestURL(event);
151
+ const kind = routeOf(url.pathname);
152
+ if (kind !== "retranscribe" && kind !== "speak") {
153
+ setResponseStatus(event, kind ? 426 : 404);
154
+ return { message: kind ? "Upgrade Required" : "Not Found" };
155
+ }
156
+ if (event.method !== "POST") {
157
+ setResponseStatus(event, 405);
158
+ setResponseHeader(event, "allow", "POST");
159
+ return { message: "Method Not Allowed" };
160
+ }
161
+ const context = {
162
+ request: new Request(url, {
163
+ method: event.method,
164
+ headers: event.headers
165
+ }),
166
+ event
167
+ };
168
+ const headers = event.headers;
169
+ if (kind === "retranscribe") {
170
+ if ((getRequestHeader(event, "content-type") ?? "").split(";")[0].trim().toLowerCase() !== "audio/l16") {
171
+ setResponseStatus(event, 415);
172
+ return { message: `Content-Type must be ${RETRANSCRIBE_CONTENT_TYPE}` };
173
+ }
174
+ const length = Number(getRequestHeader(event, "content-length") ?? "0");
175
+ if (length > 0 && length > relay.limits.retranscribe.maxBytes) {
176
+ setResponseStatus(event, 413);
177
+ return { message: `audio exceeds ${relay.limits.retranscribe.maxBytes} bytes` };
178
+ }
179
+ const raw = await readLimited(event, relay.limits.retranscribe.maxBytes);
180
+ if (raw === "too-large") {
181
+ setResponseStatus(event, 413);
182
+ return { message: `audio exceeds ${relay.limits.retranscribe.maxBytes} bytes` };
183
+ }
184
+ const result = await relay.retranscribe(relayRequest({
185
+ kind,
186
+ url,
187
+ headers,
188
+ context
189
+ }), raw);
190
+ if (result.ok) return result.value;
191
+ setResponseStatus(event, result.status);
192
+ if (result.retryAfterS !== void 0) setResponseHeader(event, "retry-after", result.retryAfterS);
193
+ return toBody(result);
194
+ }
195
+ if ((getRequestHeader(event, "content-type") ?? "").split(";")[0].trim().toLowerCase() !== "application/json") {
196
+ setResponseStatus(event, 415);
197
+ return { message: "Content-Type must be application/json" };
198
+ }
199
+ const raw = await readLimited(event, MAX_SPEAK_BODY_BYTES);
200
+ if (raw === "too-large") {
201
+ setResponseStatus(event, 413);
202
+ return { message: "body too large" };
203
+ }
204
+ let body = null;
205
+ try {
206
+ body = JSON.parse(new TextDecoder().decode(raw));
207
+ } catch {}
208
+ const fields = body && typeof body === "object" ? body : {};
209
+ const result = await relay.speak(relayRequest({
210
+ kind,
211
+ url,
212
+ headers,
213
+ context,
214
+ body: fields
215
+ }), {
216
+ text: typeof fields.text === "string" ? fields.text : "",
217
+ voiceId: typeof fields.voiceId === "string" ? fields.voiceId : null,
218
+ languageCode: typeof fields.languageCode === "string" ? fields.languageCode : null,
219
+ expressive: fields.expressive === true,
220
+ lowLatency: fields.lowLatency === true
221
+ });
222
+ if (!result.ok) {
223
+ setResponseStatus(event, result.status);
224
+ if (result.retryAfterS !== void 0) setResponseHeader(event, "retry-after", result.retryAfterS);
225
+ return toBody(result);
226
+ }
227
+ setResponseHeader(event, "content-type", result.value.contentType);
228
+ return sendStream(event, result.value.body);
229
+ }
230
+ });
231
+ }
232
+ export { defineVoiceRelayRoutes };
233
+
234
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/h3/index.ts"],"sourcesContent":["// `@skaile/forge-voice/h3`: the voice relay on an h3 / Nitro app (h3 1.x with crossws websockets).\nimport {\n defineEventHandler,\n type defineWebSocket,\n type EventHandler,\n getRequestHeader,\n getRequestURL,\n getRequestWebStream,\n type H3Event,\n sendStream,\n setResponseHeader,\n setResponseStatus,\n} from 'h3'\nimport { isRelayRefusal, refusalStatusText, relayRequest, type VoiceRelay } from '../server/relay'\nimport type { RelaySocket } from '../server/sockets'\nimport type { RelayResult, VoiceAdmission } from '../server/types'\nimport {\n RETRANSCRIBE_CONTENT_TYPE,\n TTS_MAX_CLIENT_FRAME_BYTES,\n VOICE_RELAY_DEFAULT_PATHS,\n type VoiceRelayRoute,\n} from '../shared/wire'\n\n/** What `authorize` gets as `request.context` from this adapter. */\nexport interface H3RelayContext {\n /** The web request: the upgrade request on the WebSocket routes, URL and headers (cookies) without the body on the HTTP routes. */\n request: Request\n /** The h3 event, on the HTTP routes only (crossws hands an upgrade no event). */\n event?: H3Event\n}\n\nexport interface VoiceRelayRoutesOptions {\n /** Where each route is served (the full request path); default `VOICE_RELAY_DEFAULT_PATHS` (`/voice/...`). */\n paths?: Partial<Record<VoiceRelayRoute, string>>\n}\n\ntype Hooks = NonNullable<Parameters<typeof defineWebSocket>[0]>\ntype Peer = Parameters<NonNullable<Hooks['open']>>[0]\ntype Message = Parameters<NonNullable<Hooks['message']>>[1]\n\n/** The relay socket over a crossws peer, fed by the hooks below. */\ninterface PeerSocket extends RelaySocket {\n receive(data: string | Uint8Array): void\n closed(): void\n}\n\nfunction peerSocket(peer: Peer): PeerSocket {\n let open = true\n const onMessage: ((data: string | Uint8Array) => void)[] = []\n const onClose: (() => void)[] = []\n return {\n send(data) {\n if (open) peer.send(data)\n },\n close(code, reason) {\n peer.close(code, reason)\n },\n onMessage: listener => void onMessage.push(listener),\n onClose: listener => void onClose.push(listener),\n receive(data) {\n if (open) for (const listener of onMessage) listener(data)\n },\n closed() {\n if (!open) return\n open = false\n for (const listener of onClose) listener()\n },\n }\n}\n\n/**\n * A text frame, or binary audio. crossws' Node adapter hands text frames over as bytes too, so a\n * byte frame that is a JSON object counts as text: every control frame of the protocol is one, and\n * audio that happens to parse as a JSON object is not a realistic PCM or webm chunk.\n */\nfunction frameOf(message: Message): string | Uint8Array {\n if (typeof message.rawData === 'string') return message.rawData\n const bytes = message.uint8Array()\n if (bytes[0] === 0x7b) {\n try {\n const text = new TextDecoder('utf-8', { fatal: true }).decode(bytes)\n const parsed: unknown = JSON.parse(text)\n if (parsed && typeof parsed === 'object') return text\n } catch {\n // Not UTF-8 JSON: audio.\n }\n }\n return bytes\n}\n\n/** The JSON body of `POST speak`: 10,000 characters of text at up to 4 bytes each, plus the other fields. */\nconst MAX_SPEAK_BODY_BYTES = 64 * 1024\n\n/** The request body, read while it streams in and abandoned past `max` bytes (a chunked upload has no length to check first). */\nasync function readLimited(event: H3Event, max: number): Promise<Uint8Array | 'too-large'> {\n const stream = getRequestWebStream(event)\n if (!stream) return new Uint8Array()\n const reader = stream.getReader()\n const chunks: Uint8Array[] = []\n let size = 0\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n size += value.byteLength\n if (size > max) {\n await reader.cancel().catch(() => undefined)\n return 'too-large'\n }\n chunks.push(value)\n }\n const out = new Uint8Array(size)\n let at = 0\n for (const chunk of chunks) {\n out.set(chunk, at)\n at += chunk.byteLength\n }\n return out\n}\n\nconst toBody = (result: Extract<RelayResult<unknown>, { ok: false }>) => ({\n message: result.message,\n ...(result.code ? { code: result.code } : {}),\n})\n\n/**\n * One h3 event handler serving all four relay routes, for a catch-all Nitro route\n * (`server/routes/voice/[...].ts`: `export default defineVoiceRelayRoutes(relay)`) or `router.use`:\n *\n * WS /voice/transcribe-stream speech to text (wire protocol v1, `relay.admit` + `relay.stt`)\n * WS /voice/speak-stream streamed speech (`relay.admit` + `relay.tts`)\n * POST /voice/retranscribe one utterance, body `audio/l16` (`relay.retranscribe`)\n * POST /voice/speak one clip, JSON body (`relay.speak`)\n *\n * The relay's host `authorize` gets an `H3RelayContext`. A refused upgrade answers its HTTP status\n * with no body. Needs `experimental: { websocket: true }` in the Nitro config for the WebSocket routes.\n */\nexport function defineVoiceRelayRoutes(\n relay: VoiceRelay<H3RelayContext>,\n options: VoiceRelayRoutesOptions = {},\n): EventHandler {\n const paths = { ...VOICE_RELAY_DEFAULT_PATHS, ...options.paths }\n const routeOf = (pathname: string): VoiceRelayRoute | null =>\n (Object.keys(paths) as VoiceRelayRoute[]).find(kind => paths[kind] === pathname) ?? null\n const sockets = new WeakMap<object, PeerSocket>()\n\n const websocket: Hooks = {\n async upgrade(request) {\n const url = new URL(request.url, 'http://localhost')\n const kind = routeOf(url.pathname)\n if (kind !== 'stt' && kind !== 'tts') return new Response(null, { status: 404, statusText: 'Not Found' })\n let admitted: Awaited<ReturnType<typeof relay.admit>>\n try {\n admitted = await relay.admit(\n relayRequest({ kind, url, headers: request.headers, context: { request: request as Request } }),\n )\n } catch {\n // A throwing `authorize` or key read: answer the upgrade instead of leaving it hanging.\n return new Response(null, { status: 500, statusText: 'Internal Server Error' })\n }\n // No body: crossws' node adapter writes response headers percent-encoded, which would mangle a `content-type`.\n if (isRelayRefusal(admitted)) {\n return new Response(null, { status: admitted.refuse, statusText: refusalStatusText(admitted) })\n }\n // crossws creates the context before it calls the hook; `open` reads it as `peer.context`.\n request.context!.voiceAdmission = admitted\n },\n open(peer) {\n const admission = peer.context.voiceAdmission as VoiceAdmission | undefined\n if (!admission) return peer.close(1011, 'upstream-error')\n const socket = peerSocket(peer)\n sockets.set(peer, socket)\n try {\n if (admission.kind === 'stt') relay.stt(socket, admission)\n else relay.tts(socket, admission)\n } catch {\n admission.release()\n peer.close(1011, 'upstream-error')\n }\n },\n message(peer, message) {\n const socket = sockets.get(peer)\n if (!socket) return\n const admission = peer.context.voiceAdmission as VoiceAdmission | undefined\n // Every legitimate TTS client frame is a short JSON text frame.\n if (admission?.kind === 'tts' && message.uint8Array().byteLength > TTS_MAX_CLIENT_FRAME_BYTES) {\n return peer.close(1009, 'frame-too-large')\n }\n socket.receive(frameOf(message))\n },\n close(peer) {\n sockets.get(peer)?.closed()\n sockets.delete(peer)\n },\n error(peer) {\n // A malformed client frame: end this socket only, logging nothing of it.\n sockets.get(peer)?.closed()\n sockets.delete(peer)\n },\n }\n\n return defineEventHandler({\n websocket,\n async handler(event) {\n const url = getRequestURL(event)\n const kind = routeOf(url.pathname)\n if (kind !== 'retranscribe' && kind !== 'speak') {\n setResponseStatus(event, kind ? 426 : 404)\n return { message: kind ? 'Upgrade Required' : 'Not Found' }\n }\n if (event.method !== 'POST') {\n setResponseStatus(event, 405)\n setResponseHeader(event, 'allow', 'POST')\n return { message: 'Method Not Allowed' }\n }\n // Headers only: the adapter reads the body itself, with a size cap.\n const context: H3RelayContext = {\n request: new Request(url, { method: event.method, headers: event.headers }),\n event,\n }\n const headers = event.headers\n\n if (kind === 'retranscribe') {\n const type = getRequestHeader(event, 'content-type') ?? ''\n if (type.split(';')[0]!.trim().toLowerCase() !== RETRANSCRIBE_CONTENT_TYPE) {\n setResponseStatus(event, 415)\n return { message: `Content-Type must be ${RETRANSCRIBE_CONTENT_TYPE}` }\n }\n const length = Number(getRequestHeader(event, 'content-length') ?? '0')\n if (length > 0 && length > relay.limits.retranscribe.maxBytes) {\n setResponseStatus(event, 413)\n return { message: `audio exceeds ${relay.limits.retranscribe.maxBytes} bytes` }\n }\n const raw = await readLimited(event, relay.limits.retranscribe.maxBytes)\n if (raw === 'too-large') {\n setResponseStatus(event, 413)\n return { message: `audio exceeds ${relay.limits.retranscribe.maxBytes} bytes` }\n }\n const result = await relay.retranscribe(relayRequest({ kind, url, headers, context }), raw)\n if (result.ok) return result.value\n setResponseStatus(event, result.status)\n if (result.retryAfterS !== undefined) setResponseHeader(event, 'retry-after', result.retryAfterS)\n return toBody(result)\n }\n\n // JSON only: a cross-site form or `text/plain` post cannot reach a host that authorizes by cookie.\n const type = (getRequestHeader(event, 'content-type') ?? '').split(';')[0]!.trim().toLowerCase()\n if (type !== 'application/json') {\n setResponseStatus(event, 415)\n return { message: 'Content-Type must be application/json' }\n }\n const raw = await readLimited(event, MAX_SPEAK_BODY_BYTES)\n if (raw === 'too-large') {\n setResponseStatus(event, 413)\n return { message: 'body too large' }\n }\n let body: unknown = null\n try {\n body = JSON.parse(new TextDecoder().decode(raw))\n } catch {\n // Not JSON: answered as a missing text below.\n }\n const fields = body && typeof body === 'object' ? (body as Record<string, unknown>) : {}\n const result = await relay.speak(relayRequest({ kind, url, headers, context, body: fields }), {\n text: typeof fields.text === 'string' ? fields.text : '',\n voiceId: typeof fields.voiceId === 'string' ? fields.voiceId : null,\n languageCode: typeof fields.languageCode === 'string' ? fields.languageCode : null,\n expressive: fields.expressive === true,\n lowLatency: fields.lowLatency === true,\n })\n if (!result.ok) {\n setResponseStatus(event, result.status)\n if (result.retryAfterS !== undefined) setResponseHeader(event, 'retry-after', result.retryAfterS)\n return toBody(result)\n }\n setResponseHeader(event, 'content-type', result.value.contentType)\n return sendStream(event, result.value.body)\n },\n })\n}\n"],"mappings":";;;AA8CA,SAAS,WAAW,MAAwB;CAC1C,IAAI,OAAO;CACX,MAAM,YAAqD,CAAC;CAC5D,MAAM,UAA0B,CAAC;CACjC,OAAO;EACL,KAAK,MAAM;GACT,IAAI,MAAM,KAAK,KAAK,IAAI;EAC1B;EACA,MAAM,MAAM,QAAQ;GAClB,KAAK,MAAM,MAAM,MAAM;EACzB;EACA,YAAW,aAAY,KAAK,UAAU,KAAK,QAAQ;EACnD,UAAS,aAAY,KAAK,QAAQ,KAAK,QAAQ;EAC/C,QAAQ,MAAM;GACZ,IAAI,MAAM,KAAK,MAAM,YAAY,WAAW,SAAS,IAAI;EAC3D;EACA,SAAS;GACP,IAAI,CAAC,MAAM;GACX,OAAO;GACP,KAAK,MAAM,YAAY,SAAS,SAAS;EAC3C;CACF;AACF;;;;;;AAOA,SAAS,QAAQ,SAAuC;CACtD,IAAI,OAAO,QAAQ,YAAY,UAAU,OAAO,QAAQ;CACxD,MAAM,QAAQ,QAAQ,WAAW;C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gB,OAAO,MAAM,WAAW;GACjE,OAAO,WAAW,OAAO,OAAO,MAAM,IAAI;EAC5C;CACF,CAAC;AACH"}
@@ -0,0 +1,138 @@
1
+ import { A as RETRANSCRIBE_CONTENT_TYPE, B as TTS_STREAM_SAMPLE_RATE, C as SttLanguage, D as LINEAR16_SAMPLE_RATE, E as ttsLanguageCode, F as SttClientFrame, G as VOICE_WIRE_PROTOCOL_VERSION, H as TtsCloseReason, I as SttCloseReason, K as VoiceRelayRoute, L as SttEncoding, M as RelayErrorBody, N as RetranscribeResult, O as RELAY_CLOSE_CODES, P as SpeakRequestBody, R as SttServerFrame, S as STT_LANGUAGES, T as parseSttLanguage, U as TtsServerFrame, V as TtsClientFrame, W as VOICE_RELAY_DEFAULT_PATHS, _ as sameSpeechTerm, a as MAX_KEYTERMS, b as withSpeechTerm, c as MAX_SPEECH_TERM_CHARS, d as SPEECH_TERM_PATTERN, f as SpeechTerm, g as estimateKeytermTokens, h as cleanKeyterm, i as KeytermSources, j as RETRANSCRIBE_MAX_BYTES, k as RELAY_QUERY_PARAMS, l as MAX_USER_KEYTERMS, m as buildKeyterms, n as BUILT_IN_PRONUNCIATIONS, o as MAX_PRONUNCIATION_CHARS, p as USER_KEYTERM_TOKEN_BUDGET, q as parseSttEncoding, r as KEYTERM_TOKEN_BUDGET, s as MAX_SPEECH_TERMS, t as BUILT_IN_KEYTERMS, u as SPEECH_TERM_LANGUAGES, v as speechTermLanguageMatches, w as modelAcceptsLanguageCode, x as withoutSpeechTerm, y as tidySpeechTermText, z as TTS_MAX_CLIENT_FRAME_BYTES } from "./speech-terms.mjs";
2
+ /**
3
+ * Audio tags in a spoken reply: `[[whispers]]`, `[[laughs]]`. The reply-format contract between an
4
+ * agent that writes tags and the speech model that performs them. The stored text keeps them; what a
5
+ * chat shows of a voice reply, what Talk counts as heard (`heardChars`) and what a server reuses of one
6
+ * (history, search, recaps) is the text without them. Only voice replies have tags: anywhere else
7
+ * `[[...]]` is code or a wiki link. Browser and server import the same functions, so both count
8
+ * offsets the same way; keep this file free of runtime-specific imports.
9
+ */
10
+ /** The text without its audio tags. */
11
+ export declare function stripAudioTags(text: string): string;
12
+ /**
13
+ * Where `rawOffset` in the stored text lands in the stripped text. An offset inside a tag lands
14
+ * where the tag was.
15
+ */
16
+ export declare function strippedOffset(raw: string, rawOffset: number): number;
17
+ /**
18
+ * The text without any double-bracket tag, malformed ones too (`[[laughs!]]`): what Talk speaks
19
+ * on the fallback model or shows as a caption, never a `[[`. Not for offsets: `stripAudioTags`.
20
+ */
21
+ export declare function stripAnyAudioTags(text: string): string;
22
+ /**
23
+ * Where a trailing, not yet closed tag starts (`[[laug`, `[[laughs]`, or a lone final `[`), so
24
+ * Talk holds it back until it closes instead of speaking or cutting half of it; -1 otherwise.
25
+ */
26
+ export declare function pendingTagStart(text: string): number;
27
+ /**
28
+ * The ElevenLabs v4 form: `[[x]]` becomes `[x]`; a malformed double-bracket tag is dropped.
29
+ */
30
+ export declare function toElevenLabsTags(text: string): string;
31
+ /**
32
+ * What Chat shows of a voice reply: its valid tags removed, except inside code (a fenced block or
33
+ * an inline span), where `[[x]]` is the code's own (bash `[[ -d x ]]`, a wiki link).
34
+ */
35
+ export declare function stripAudioTagsForDisplay(text: string): string;
36
+ /** The [start, end) ranges of the audio tags in `raw`. */
37
+ export declare function audioTagRanges(raw: string): [number, number][];
38
+ /**
39
+ * A voice reply's text for reuse as plain text (history, search, recaps, read-aloud): every
40
+ * `[[...]]` removed, malformed ones too since Flash reads them aloud, but none inside code. Text
41
+ * without one comes back unchanged; a removed tag takes one adjacent space, nothing else is touched.
42
+ * Callers outside `/voice/speak` apply it to voice replies only. `inCodeToo`: code as well, for
43
+ * `/voice/speak`, where the fast model would read a tag aloud wherever it is.
44
+ * Not for offsets: `stripAudioTags`.
45
+ */
46
+ export declare function stripAudioTagsForText(text: string, { inCodeToo }?: {
47
+ inCodeToo?: boolean;
48
+ }): string;
49
+ /**
50
+ * The spoken language for a conversation language (a locale such as `de-DE`): the locale
51
+ * itself when the recognizer knows that region, else its bare language, else null (the
52
+ * deployment default).
53
+ */
54
+ export declare function sttLanguageForLocale(locale: string | null | undefined): SttLanguage | null;
55
+ /**
56
+ * What dictation and read-aloud use: the language the person pinned by hand, else the one
57
+ * they converse in here. A pin is never replaced; clearing it returns to following them.
58
+ */
59
+ export declare function effectiveSttLanguage(pinned: SttLanguage | null | undefined, conversationLocale: string | null | undefined): SttLanguage | null;
60
+ /**
61
+ * Splits a reply that is still streaming into sentences that can be spoken now.
62
+ * A sentence ends at `.`, `!`, `?` or `…` followed by whitespace, or at a line
63
+ * break. Very short pieces ("1.", "OK.") wait for the next one, so one request
64
+ * never carries a single syllable.
65
+ */
66
+ export declare const MIN_SENTENCE_CHARS = 12;
67
+ export type SentenceCut = {
68
+ /** Complete sentences found after `from`, trimmed and non-empty. */
69
+ sentences: string[];
70
+ /** Offset into `text` where the unspoken remainder starts. */
71
+ next: number;
72
+ };
73
+ export declare function takeCompleteSentences(text: string, from: number): SentenceCut;
74
+ /**
75
+ * Removes the markdown that would be read out as symbols: emphasis, headings,
76
+ * inline code ticks, list bullets, and link targets (the link text stays).
77
+ * Fenced code blocks are dropped entirely.
78
+ */
79
+ export declare function toSpeakableText(markdown: string): string;
80
+ /**
81
+ * Utterances the hands-free loop acts on instead of sending. Matched against the
82
+ * whole utterance, so "stop the deployment" still reaches the agent.
83
+ */
84
+ export type LoopCommand = 'end' | 'hush';
85
+ /** What a hands-free utterance asks of the loop itself; null when it is a message for the agent. */
86
+ export declare function loopCommand(utterance: string): LoopCommand | null;
87
+ /**
88
+ * True when the whole utterance is made of hush phrases (greedy longest match), so
89
+ * "Stopp, warte mal" hushes but "Stopp, was meinst du damit?" is a message.
90
+ */
91
+ export declare function isHushOnly(utterance: string): boolean;
92
+ /**
93
+ * How long the hands-free loop waits after Deepgram reports the end of speech before
94
+ * it sends what was said. Deepgram ends an utterance after 300 ms of silence, which a
95
+ * breath mid-sentence already reaches, so a sentence would leave as several messages.
96
+ * Speech inside the wait joins the same message; a transcript that stops mid-sentence
97
+ * waits longer, but is still sent, so the loop never stalls on a dropped thought.
98
+ */
99
+ /** After a finished sentence. */
100
+ export declare const UTTERANCE_HOLD_MS = 2000;
101
+ /** After a transcript that stops mid-sentence, and the cap while the user is still talking. */
102
+ export declare const UTTERANCE_HOLD_MID_SENTENCE_MS = 5000;
103
+ /** True when the transcript reads as a thought that has not finished yet. */
104
+ export declare function endsMidSentence(transcript: string): boolean;
105
+ /** The wait before sending `transcript`, the utterance collected so far. */
106
+ export declare function utteranceHoldMs(transcript: string): number;
107
+ /**
108
+ * Talk answers aloud, so it hands an utterance over sooner than dictation: after a finished
109
+ * sentence and this much silence (on top of Deepgram's 300 ms endpointing). A sentence the user
110
+ * goes on with after a longer pause still reaches the agent as one request: Talk restarts the
111
+ * turn with the whole of it.
112
+ */
113
+ export declare const TALK_HOLD_MS = 800;
114
+ /** A short answer ("Ja", "Nein, danke", "Okay."), whatever its punctuation: sent promptly. */
115
+ export declare const TALK_HOLD_SHORT_MS = 250;
116
+ /** The most Talk waits after a transcript that reads unfinished ("…, wenn ich", "mit meinen"). */
117
+ export declare const TALK_HOLD_UNFINISHED_MS = 1200;
118
+ /** Up to this many words an utterance is a short answer, unless its words end openly. */
119
+ export declare const TALK_SHORT_WORDS = 3;
120
+ /**
121
+ * True when the words themselves leave the thought open, whatever the punctuation: a joining word,
122
+ * a preposition or possessive, a filler, a subordinating word and its pronoun ("wenn ich"), or a
123
+ * modal verb still waiting for its infinitive. A question or an exclamation is finished.
124
+ */
125
+ export declare function talkOpenEnding(transcript: string): boolean;
126
+ /**
127
+ * True when a Talk transcript reads as unfinished: its words end openly, it stops on a colon, dash
128
+ * or ellipsis, or a longer one stops on a comma. A short answer's comma ("Ja,") and a missing full
129
+ * stop count for nothing; STT puts both on finished words.
130
+ */
131
+ export declare function talkLooksUnfinished(transcript: string): boolean;
132
+ export type TalkHold = {
133
+ ms: number;
134
+ reason: 'short' | 'finished' | 'unfinished';
135
+ };
136
+ /** The silence Talk waits for after the end of speech before it sends `transcript`, and why. */
137
+ export declare function talkUtteranceHold(transcript: string): TalkHold;
138
+ export { BUILT_IN_KEYTERMS, BUILT_IN_PRONUNCIATIONS, KEYTERM_TOKEN_BUDGET, KeytermSources, LINEAR16_SAMPLE_RATE, MAX_KEYTERMS, MAX_PRONUNCIATION_CHARS, MAX_SPEECH_TERMS, MAX_SPEECH_TERM_CHARS, MAX_USER_KEYTERMS, RELAY_CLOSE_CODES, RELAY_QUERY_PARAMS, RETRANSCRIBE_CONTENT_TYPE, RETRANSCRIBE_MAX_BYTES, RelayErrorBody, RetranscribeResult, SPEECH_TERM_LANGUAGES, SPEECH_TERM_PATTERN, STT_LANGUAGES, SpeakRequestBody, SpeechTerm, SttClientFrame, SttCloseReason, SttEncoding, SttLanguage, SttServerFrame, TTS_MAX_CLIENT_FRAME_BYTES, TTS_STREAM_SAMPLE_RATE, TtsClientFrame, TtsCloseReason, TtsServerFrame, USER_KEYTERM_TOKEN_BUDGET, VOICE_RELAY_DEFAULT_PATHS, VOICE_WIRE_PROTOCOL_VERSION, VoiceRelayRoute, buildKeyterms, cleanKeyterm, estimateKeytermTokens, modelAcceptsLanguageCode, parseSttEncoding, parseSttLanguage, sameSpeechTerm, speechTermLanguageMatches, tidySpeechTermText, ttsLanguageCode, withSpeechTerm, withoutSpeechTerm };
package/dist/index.mjs ADDED
@@ -0,0 +1 @@
1
+ export { k as BUILT_IN_KEYTERMS, A as BUILT_IN_PRONUNCIATIONS, j as KEYTERM_TOKEN_BUDGET, t as LINEAR16_SAMPLE_RATE, M as MAX_KEYTERMS, N as MAX_PRONUNCIATION_CHARS, P as MAX_SPEECH_TERMS, F as MAX_SPEECH_TERM_CHARS, I as MAX_USER_KEYTERMS, w as MIN_SENTENCE_CHARS, n as RELAY_CLOSE_CODES, r as RELAY_QUERY_PARAMS, i as RETRANSCRIBE_CONTENT_TYPE, a as RETRANSCRIBE_MAX_BYTES, L as SPEECH_TERM_LANGUAGES, R as SPEECH_TERM_PATTERN, J as STT_LANGUAGES, d as TALK_HOLD_MS, f as TALK_HOLD_SHORT_MS, p as TALK_HOLD_UNFINISHED_MS, m as TALK_SHORT_WORDS, o as TTS_MAX_CLIENT_FRAME_BYTES, s as TTS_STREAM_SAMPLE_RATE, z as USER_KEYTERM_TOKEN_BUDGET, h as UTTERANCE_HOLD_MID_SENTENCE_MS, g as UTTERANCE_HOLD_MS, c as VOICE_RELAY_DEFAULT_PATHS, l as VOICE_WIRE_PROTOCOL_VERSION, Q as audioTagRanges, B as buildKeyterms, V as cleanKeyterm, D as effectiveSttLanguage, _ as endsMidSentence, H as estimateKeytermTokens, S as isHushOnly, C as loopCommand, Y as modelAcceptsLanguageCode, u as parseSttEncoding, X as parseSttLanguage, $ as pendingTagStart, U as sameSpeechTerm, W as speechTermLanguageMatches, et as stripAnyAudioTags, tt as stripAudioTags, nt as stripAudioTagsForDisplay, rt as stripAudioTagsForText, it as strippedOffset, O as sttLanguageForLocale, T as takeCompleteSentences, v as talkLooksUnfinished, y as talkOpenEnding, b as talkUtteranceHold, G as tidySpeechTermText, at as toElevenLabsTags, E as toSpeakableText, Z as ttsLanguageCode, x as utteranceHoldMs, K as withSpeechTerm, q as withoutSpeechTerm } from "./wire.mjs";