@crewhaus/voice-runtime 0.8.0 → 0.8.2
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.d.ts +33 -31
- package/dist/index.js +140 -13
- package/package.json +3 -2
package/dist/index.d.ts
CHANGED
|
@@ -1,32 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Catalog R16 `voice-runtime` — Section 24 VOICE.
|
|
3
|
-
*
|
|
4
|
-
* Provider-agnostic realtime audio adapter. The user-facing surface is
|
|
5
|
-
* a small interface — `RealtimeAdapter` — with one concrete adapter in
|
|
6
|
-
* v0 (`createOpenAIRealtimeAdapter`) and a Vapi stub that lazy-loads.
|
|
7
|
-
*
|
|
8
|
-
* Audio framing: every adapter normalises to 16-bit signed-int PCM at
|
|
9
|
-
* 24kHz mono. The OpenAI adapter speaks this format natively; the Vapi
|
|
10
|
-
* adapter (when implemented) will resample its native Opus stream
|
|
11
|
-
* through a server-side helper. Frames are passed as `Int16Array` so
|
|
12
|
-
* downstream consumers (vad-engine) don't have to re-decode bytes.
|
|
13
|
-
*
|
|
14
|
-
* Event surface:
|
|
15
|
-
* - `transcript_partial { text }` — incremental transcript chunks
|
|
16
|
-
* - `transcript_final { text }` — when the user's utterance ends
|
|
17
|
-
* - `audio_chunk { pcm }` — agent's TTS audio (pcm16 24kHz)
|
|
18
|
-
* - `tool_use { id, name, input }` — agent function calls
|
|
19
|
-
* - `interrupt { reason }` — emitted on barge-in
|
|
20
|
-
* - `disconnect { code?, reason? }` — final
|
|
21
|
-
*
|
|
22
|
-
* The OpenAI adapter is HEADLESS — no microphone, no speakers. The
|
|
23
|
-
* caller pumps PCM in via `sendAudio(pcm)`; the adapter emits audio +
|
|
24
|
-
* transcript events back. This keeps the runtime usable in three
|
|
25
|
-
* deployment modes:
|
|
26
|
-
* 1. Browser → daemon over WebRTC (browser has the mic/speaker).
|
|
27
|
-
* 2. SIP gateway → daemon (telephony provides PCM).
|
|
28
|
-
* 3. Node-only smoke (synthesize PCM in TS, pipe in, assert events).
|
|
29
|
-
*/
|
|
30
1
|
import { CrewhausError } from "@crewhaus/errors";
|
|
31
2
|
export declare class VoiceRuntimeError extends CrewhausError {
|
|
32
3
|
readonly name = "VoiceRuntimeError";
|
|
@@ -71,6 +42,22 @@ export type RealtimeEvent = {
|
|
|
71
42
|
provider: ProviderId;
|
|
72
43
|
ts: string;
|
|
73
44
|
payload: unknown;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* The prompt-injection check refused the caller's input: a transcript of
|
|
48
|
+
* their speech (`itemId` is its conversation item, deleted) or text passed
|
|
49
|
+
* to `sendText` (not sent). The detector's rule ids, never the text.
|
|
50
|
+
*/
|
|
51
|
+
| {
|
|
52
|
+
kind: "input_blocked";
|
|
53
|
+
itemId?: string;
|
|
54
|
+
rules: string[];
|
|
55
|
+
}
|
|
56
|
+
/** The check kept the caller's input but flagged it. Rule ids, never the text. */
|
|
57
|
+
| {
|
|
58
|
+
kind: "input_warned";
|
|
59
|
+
itemId?: string;
|
|
60
|
+
rules: string[];
|
|
74
61
|
};
|
|
75
62
|
export type RealtimeEventHandler = (event: RealtimeEvent) => void;
|
|
76
63
|
export type RealtimeConnectOptions = {
|
|
@@ -102,13 +89,28 @@ export interface RealtimeAdapter {
|
|
|
102
89
|
* timing is too slow for a one-shot smoke). Idempotent.
|
|
103
90
|
*/
|
|
104
91
|
commitInput(): void;
|
|
105
|
-
/**
|
|
106
|
-
|
|
92
|
+
/**
|
|
93
|
+
* Inject a text turn (no audio). Useful for tests + chat-only mixed mode.
|
|
94
|
+
* The text is classified at TrustOrigin `channel` before it is sent:
|
|
95
|
+
* malicious text is not sent (an `input_blocked` event; the call goes on),
|
|
96
|
+
* suspicious text is sent with an `input_warned` event. Throws at call time
|
|
97
|
+
* when not connected; otherwise the returned promise resolves once the
|
|
98
|
+
* text is sent or refused, in call order, and never rejects (a send that
|
|
99
|
+
* fails after the check is an `error` event).
|
|
100
|
+
*/
|
|
101
|
+
sendText(text: string): void | Promise<void>;
|
|
107
102
|
/** Cancel the in-flight response. Used by `barge-in-controller`. */
|
|
108
103
|
interrupt(reason: string): void;
|
|
109
104
|
on(handler: RealtimeEventHandler): () => void;
|
|
110
105
|
disconnect(): Promise<void>;
|
|
111
106
|
}
|
|
107
|
+
/**
|
|
108
|
+
* The model a session asks to transcribe the caller's speech
|
|
109
|
+
* (`session.audio.input.transcription.model`), so each transcript can be
|
|
110
|
+
* classified before later replies build on it. The provider bills it as
|
|
111
|
+
* transcription.
|
|
112
|
+
*/
|
|
113
|
+
export declare const DEFAULT_INPUT_TRANSCRIPTION_MODEL = "gpt-transcribe";
|
|
112
114
|
/** Test injection: a factory that returns a WebSocket-like (skips `new`). */
|
|
113
115
|
export type WebSocketFactory = (url: string, init?: {
|
|
114
116
|
headers?: Record<string, string>;
|
package/dist/index.js
CHANGED
|
@@ -17,8 +17,19 @@
|
|
|
17
17
|
* - `audio_chunk { pcm }` — agent's TTS audio (pcm16 24kHz)
|
|
18
18
|
* - `tool_use { id, name, input }` — agent function calls
|
|
19
19
|
* - `interrupt { reason }` — emitted on barge-in
|
|
20
|
+
* - `input_blocked { itemId?, rules }` — the prompt-injection check
|
|
21
|
+
* refused the caller's input (a transcript of their speech, or text
|
|
22
|
+
* passed to `sendText`); the call goes on
|
|
23
|
+
* - `input_warned { itemId?, rules }` — it kept the input, flagged
|
|
20
24
|
* - `disconnect { code?, reason? }` — final
|
|
21
25
|
*
|
|
26
|
+
* The caller's input is screened at TrustOrigin `channel`. On the OpenAI
|
|
27
|
+
* Realtime adapter the session asks the provider to transcribe the caller,
|
|
28
|
+
* and each transcript is classified: a malicious one cancels the reply in
|
|
29
|
+
* progress and deletes the caller's item, so later replies do not build on
|
|
30
|
+
* it. Text passed to `sendText` is classified before it is sent, on both
|
|
31
|
+
* adapters. The two input events carry rule ids, never the text.
|
|
32
|
+
*
|
|
22
33
|
* The OpenAI adapter is HEADLESS — no microphone, no speakers. The
|
|
23
34
|
* caller pumps PCM in via `sendAudio(pcm)`; the adapter emits audio +
|
|
24
35
|
* transcript events back. This keeps the runtime usable in three
|
|
@@ -27,6 +38,7 @@
|
|
|
27
38
|
* 2. SIP gateway → daemon (telephony provides PCM).
|
|
28
39
|
* 3. Node-only smoke (synthesize PCM in TS, pipe in, assert events).
|
|
29
40
|
*/
|
|
41
|
+
import { boundaryRuleIds, classifyBoundary, } from "@crewhaus/boundary-classifier";
|
|
30
42
|
import { CrewhausError } from "@crewhaus/errors";
|
|
31
43
|
export class VoiceRuntimeError extends CrewhausError {
|
|
32
44
|
name = "VoiceRuntimeError";
|
|
@@ -34,6 +46,52 @@ export class VoiceRuntimeError extends CrewhausError {
|
|
|
34
46
|
super("runtime", message, cause);
|
|
35
47
|
}
|
|
36
48
|
}
|
|
49
|
+
/**
|
|
50
|
+
* One adapter's input lane: each check, and what follows it (a send, a
|
|
51
|
+
* cancel), runs in the order it was queued, and a failure surfaces as an
|
|
52
|
+
* `error` event, never as a rejected promise.
|
|
53
|
+
*/
|
|
54
|
+
function createInputLane(emit) {
|
|
55
|
+
let tail = Promise.resolve();
|
|
56
|
+
return (task) => {
|
|
57
|
+
const next = tail.then(task).catch((err) => {
|
|
58
|
+
emit({ kind: "error", message: `input check: ${errorText(err)}` });
|
|
59
|
+
});
|
|
60
|
+
tail = next;
|
|
61
|
+
return next;
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
/** Classify caller input at TrustOrigin `channel`: the action and the rule ids. */
|
|
65
|
+
async function checkCallerInput(text) {
|
|
66
|
+
const boundary = await classifyBoundary(text, { origin: "channel" });
|
|
67
|
+
return { action: boundary.action, rules: boundaryRuleIds(boundary.verdict) };
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* `sendText`'s body after the call-time connection check: classify, then
|
|
71
|
+
* `deliver` unless refused. A delivery that throws (the socket closed during
|
|
72
|
+
* the check) is an `error` event.
|
|
73
|
+
*/
|
|
74
|
+
function sendChecked(lane, emit, text, deliver) {
|
|
75
|
+
return lane(async () => {
|
|
76
|
+
const verdict = await checkCallerInput(text);
|
|
77
|
+
if (verdict.action === "redact") {
|
|
78
|
+
emit({ kind: "input_blocked", rules: verdict.rules });
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
try {
|
|
82
|
+
deliver();
|
|
83
|
+
}
|
|
84
|
+
catch (err) {
|
|
85
|
+
emit({ kind: "error", message: `sendText: ${errorText(err)}` });
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
if (verdict.action === "warn")
|
|
89
|
+
emit({ kind: "input_warned", rules: verdict.rules });
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
function errorText(err) {
|
|
93
|
+
return err instanceof Error ? err.message : String(err);
|
|
94
|
+
}
|
|
37
95
|
// ---------------------------------------------------------------------------
|
|
38
96
|
// OpenAI Realtime adapter — speaks the GA `/v1/realtime` WebSocket protocol.
|
|
39
97
|
//
|
|
@@ -54,6 +112,8 @@ export class VoiceRuntimeError extends CrewhausError {
|
|
|
54
112
|
// - server events renamed: `response.audio.delta` →
|
|
55
113
|
// `response.output_audio.delta`, `response.audio_transcript.{delta,done}`
|
|
56
114
|
// → `response.output_audio_transcript.{delta,done}`
|
|
115
|
+
// - input transcription is `audio.input.transcription` (the beta
|
|
116
|
+
// `input_audio_transcription` field is never sent)
|
|
57
117
|
//
|
|
58
118
|
// The READ path still accepts the legacy event names as aliases — they cost
|
|
59
119
|
// three case labels and keep the adapter usable against a gateway or proxy
|
|
@@ -68,6 +128,13 @@ const OPENAI_REALTIME_SAMPLE_RATE = 24_000;
|
|
|
68
128
|
*/
|
|
69
129
|
const DEFAULT_OPENAI_REALTIME_MODEL = "gpt-realtime";
|
|
70
130
|
const DEFAULT_OPENAI_REALTIME_URL = "wss://api.openai.com/v1/realtime";
|
|
131
|
+
/**
|
|
132
|
+
* The model a session asks to transcribe the caller's speech
|
|
133
|
+
* (`session.audio.input.transcription.model`), so each transcript can be
|
|
134
|
+
* classified before later replies build on it. The provider bills it as
|
|
135
|
+
* transcription.
|
|
136
|
+
*/
|
|
137
|
+
export const DEFAULT_INPUT_TRANSCRIPTION_MODEL = "gpt-transcribe";
|
|
71
138
|
export function createOpenAIRealtimeAdapter(opts = {}) {
|
|
72
139
|
let ws;
|
|
73
140
|
let connected = false;
|
|
@@ -83,11 +150,48 @@ export function createOpenAIRealtimeAdapter(opts = {}) {
|
|
|
83
150
|
}
|
|
84
151
|
}
|
|
85
152
|
}
|
|
86
|
-
function
|
|
153
|
+
function openSocket() {
|
|
87
154
|
if (ws === undefined || ws.readyState !== 1 /* OPEN */) {
|
|
88
155
|
throw new VoiceRuntimeError("adapter is not connected (or socket is not open)");
|
|
89
156
|
}
|
|
90
|
-
ws
|
|
157
|
+
return ws;
|
|
158
|
+
}
|
|
159
|
+
function send(message) {
|
|
160
|
+
openSocket().send(JSON.stringify(message));
|
|
161
|
+
}
|
|
162
|
+
const inputLane = createInputLane(emit);
|
|
163
|
+
/**
|
|
164
|
+
* A transcript of the caller's speech (`undefined` when the provider could
|
|
165
|
+
* not make one), classified at `channel`. Malicious, or unreadable: the
|
|
166
|
+
* reply in progress is cancelled and the caller's item deleted, so later
|
|
167
|
+
* replies do not build on it, and `input_blocked` is emitted; the call goes
|
|
168
|
+
* on. Suspicious: `input_warned`. The transcript is never emitted.
|
|
169
|
+
*/
|
|
170
|
+
function checkTranscript(itemId, transcript) {
|
|
171
|
+
void inputLane(async () => {
|
|
172
|
+
const verdict = transcript === undefined
|
|
173
|
+
? { action: "redact", rules: ["transcription-failed"] }
|
|
174
|
+
: await checkCallerInput(transcript);
|
|
175
|
+
const item = itemId !== undefined ? { itemId } : {};
|
|
176
|
+
if (verdict.action === "redact") {
|
|
177
|
+
// Each send tolerates a closed socket: the verdict is reported either way.
|
|
178
|
+
for (const message of [
|
|
179
|
+
{ type: "response.cancel" },
|
|
180
|
+
...(itemId !== undefined ? [{ type: "conversation.item.delete", item_id: itemId }] : []),
|
|
181
|
+
]) {
|
|
182
|
+
try {
|
|
183
|
+
send(message);
|
|
184
|
+
}
|
|
185
|
+
catch {
|
|
186
|
+
/* socket closed: nothing left to cancel or delete */
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
emit({ kind: "input_blocked", ...item, rules: verdict.rules });
|
|
190
|
+
}
|
|
191
|
+
else if (verdict.action === "warn") {
|
|
192
|
+
emit({ kind: "input_warned", ...item, rules: verdict.rules });
|
|
193
|
+
}
|
|
194
|
+
});
|
|
91
195
|
}
|
|
92
196
|
function handleServerEvent(raw) {
|
|
93
197
|
if (typeof raw !== "object" || raw === null)
|
|
@@ -165,6 +269,16 @@ export function createOpenAIRealtimeAdapter(opts = {}) {
|
|
|
165
269
|
case "response.cancel":
|
|
166
270
|
emit({ kind: "interrupt", reason: "response cancelled" });
|
|
167
271
|
break;
|
|
272
|
+
// The caller's own speech, transcribed because the session asks for it
|
|
273
|
+
// (the transcript events above are the AGENT's). Each one is checked.
|
|
274
|
+
case "conversation.item.input_audio_transcription.completed": {
|
|
275
|
+
const transcript = ev["transcript"];
|
|
276
|
+
checkTranscript(typeof ev["item_id"] === "string" ? ev["item_id"] : undefined, typeof transcript === "string" ? transcript : undefined);
|
|
277
|
+
break;
|
|
278
|
+
}
|
|
279
|
+
case "conversation.item.input_audio_transcription.failed":
|
|
280
|
+
checkTranscript(typeof ev["item_id"] === "string" ? ev["item_id"] : undefined, undefined);
|
|
281
|
+
break;
|
|
168
282
|
case "error": {
|
|
169
283
|
const errObj = ev["error"];
|
|
170
284
|
emit({ kind: "error", message: errObj?.message ?? "unknown error" });
|
|
@@ -243,6 +357,8 @@ export function createOpenAIRealtimeAdapter(opts = {}) {
|
|
|
243
357
|
// because GA rejects a combined ["text","audio"] request; the audio
|
|
244
358
|
// response still streams transcript deltas, which is where this
|
|
245
359
|
// adapter's transcript_partial/transcript_final events come from.
|
|
360
|
+
// `audio.input.transcription` asks for the CALLER's transcript too, so
|
|
361
|
+
// each utterance can be classified (see checkTranscript).
|
|
246
362
|
send({
|
|
247
363
|
type: "session.update",
|
|
248
364
|
session: {
|
|
@@ -256,6 +372,7 @@ export function createOpenAIRealtimeAdapter(opts = {}) {
|
|
|
256
372
|
input: {
|
|
257
373
|
format: { type: "audio/pcm", rate: OPENAI_REALTIME_SAMPLE_RATE },
|
|
258
374
|
turn_detection: connectOpts.vad === "none" ? null : { type: "server_vad" },
|
|
375
|
+
transcription: { model: DEFAULT_INPUT_TRANSCRIPTION_MODEL },
|
|
259
376
|
},
|
|
260
377
|
output: {
|
|
261
378
|
// `rate` is REQUIRED on an audio/pcm output format — the server
|
|
@@ -294,15 +411,18 @@ export function createOpenAIRealtimeAdapter(opts = {}) {
|
|
|
294
411
|
}
|
|
295
412
|
},
|
|
296
413
|
sendText(text) {
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
type: "
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
414
|
+
openSocket(); // not connected: refused at call time
|
|
415
|
+
return sendChecked(inputLane, emit, text, () => {
|
|
416
|
+
send({
|
|
417
|
+
type: "conversation.item.create",
|
|
418
|
+
item: {
|
|
419
|
+
type: "message",
|
|
420
|
+
role: "user",
|
|
421
|
+
content: [{ type: "input_text", text }],
|
|
422
|
+
},
|
|
423
|
+
});
|
|
424
|
+
send({ type: "response.create" });
|
|
304
425
|
});
|
|
305
|
-
send({ type: "response.create" });
|
|
306
426
|
},
|
|
307
427
|
interrupt(reason) {
|
|
308
428
|
try {
|
|
@@ -360,12 +480,16 @@ export function createVapiRealtimeAdapter(opts = {}) {
|
|
|
360
480
|
}
|
|
361
481
|
}
|
|
362
482
|
}
|
|
363
|
-
function
|
|
483
|
+
function openSocket() {
|
|
364
484
|
if (ws === undefined || ws.readyState !== 1) {
|
|
365
485
|
throw new VoiceRuntimeError("vapi adapter is not connected (or socket is not open)");
|
|
366
486
|
}
|
|
367
|
-
ws
|
|
487
|
+
return ws;
|
|
368
488
|
}
|
|
489
|
+
function send(message) {
|
|
490
|
+
openSocket().send(JSON.stringify(message));
|
|
491
|
+
}
|
|
492
|
+
const inputLane = createInputLane(emit);
|
|
369
493
|
return {
|
|
370
494
|
providerId: "vapi",
|
|
371
495
|
sampleRate: OPENAI_REALTIME_SAMPLE_RATE,
|
|
@@ -434,7 +558,10 @@ export function createVapiRealtimeAdapter(opts = {}) {
|
|
|
434
558
|
send({ type: "input_audio_buffer.commit" });
|
|
435
559
|
},
|
|
436
560
|
sendText(text) {
|
|
437
|
-
|
|
561
|
+
openSocket(); // not connected: refused at call time
|
|
562
|
+
return sendChecked(inputLane, emit, text, () => {
|
|
563
|
+
send({ type: "response.create", response: { modalities: ["text", "audio"], input: text } });
|
|
564
|
+
});
|
|
438
565
|
},
|
|
439
566
|
interrupt(_reason) {
|
|
440
567
|
try {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@crewhaus/voice-runtime",
|
|
3
|
-
"version": "0.8.
|
|
3
|
+
"version": "0.8.2",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Realtime voice loop — provider-agnostic RealtimeAdapter + OpenAI Realtime WebSocket adapter (Section 24 VOICE)",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -16,7 +16,8 @@
|
|
|
16
16
|
"test": "bun test src"
|
|
17
17
|
},
|
|
18
18
|
"dependencies": {
|
|
19
|
-
"@crewhaus/
|
|
19
|
+
"@crewhaus/boundary-classifier": "0.8.2",
|
|
20
|
+
"@crewhaus/errors": "0.8.2"
|
|
20
21
|
},
|
|
21
22
|
"license": "Apache-2.0",
|
|
22
23
|
"author": {
|