@fabric-harness/sdk 6.4.0 → 6.6.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/connector-spec/voice-telephony.md +120 -104
- package/dist/agent-route.d.ts +20 -2
- package/dist/agent-route.d.ts.map +1 -1
- package/dist/agent-route.js +31 -1
- package/dist/agent-route.js.map +1 -1
- package/dist/agent-router.d.ts +42 -0
- package/dist/agent-router.d.ts.map +1 -1
- package/dist/agent-router.js +49 -1
- package/dist/agent-router.js.map +1 -1
- package/dist/agent.d.ts.map +1 -1
- package/dist/agent.js +7 -2
- package/dist/agent.js.map +1 -1
- package/dist/attachment-store.d.ts +69 -0
- package/dist/attachment-store.d.ts.map +1 -1
- package/dist/attachment-store.js +183 -14
- package/dist/attachment-store.js.map +1 -1
- package/dist/attachments.d.ts +136 -0
- package/dist/attachments.d.ts.map +1 -0
- package/dist/attachments.js +332 -0
- package/dist/attachments.js.map +1 -0
- package/dist/channel.d.ts.map +1 -1
- package/dist/channel.js +26 -3
- package/dist/channel.js.map +1 -1
- package/dist/conversation-history.d.ts +186 -0
- package/dist/conversation-history.d.ts.map +1 -0
- package/dist/conversation-history.js +481 -0
- package/dist/conversation-history.js.map +1 -0
- package/dist/conversation-ui.d.ts +43 -2
- package/dist/conversation-ui.d.ts.map +1 -1
- package/dist/conversation-ui.js +44 -14
- package/dist/conversation-ui.js.map +1 -1
- package/dist/cost-budget.d.ts +50 -0
- package/dist/cost-budget.d.ts.map +1 -1
- package/dist/cost-budget.js +74 -4
- package/dist/cost-budget.js.map +1 -1
- package/dist/cost-enforcement.d.ts +32 -0
- package/dist/cost-enforcement.d.ts.map +1 -0
- package/dist/cost-enforcement.js +116 -0
- package/dist/cost-enforcement.js.map +1 -0
- package/dist/delivered-message.d.ts +20 -6
- package/dist/delivered-message.d.ts.map +1 -1
- package/dist/delivered-message.js +37 -8
- package/dist/delivered-message.js.map +1 -1
- package/dist/events.d.ts +13 -1
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js.map +1 -1
- package/dist/experimental.d.ts +2 -2
- package/dist/experimental.d.ts.map +1 -1
- package/dist/experimental.js +1 -1
- package/dist/experimental.js.map +1 -1
- package/dist/governed-voice.d.ts +6 -0
- package/dist/governed-voice.d.ts.map +1 -1
- package/dist/governed-voice.js +142 -35
- package/dist/governed-voice.js.map +1 -1
- package/dist/history.d.ts +3 -2
- package/dist/history.d.ts.map +1 -1
- package/dist/history.js +57 -23
- package/dist/history.js.map +1 -1
- package/dist/index.d.ts +21 -14
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +11 -7
- package/dist/index.js.map +1 -1
- package/dist/loop.d.ts +25 -2
- package/dist/loop.d.ts.map +1 -1
- package/dist/loop.js +409 -60
- package/dist/loop.js.map +1 -1
- package/dist/model-pricing.d.ts +77 -4
- package/dist/model-pricing.d.ts.map +1 -1
- package/dist/model-pricing.js +259 -18
- package/dist/model-pricing.js.map +1 -1
- package/dist/model.d.ts +115 -3
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +487 -75
- package/dist/model.js.map +1 -1
- package/dist/pi-document-attachments.d.ts +43 -0
- package/dist/pi-document-attachments.d.ts.map +1 -0
- package/dist/pi-document-attachments.js +155 -0
- package/dist/pi-document-attachments.js.map +1 -0
- package/dist/pi-loop-runtime.d.ts +103 -1
- package/dist/pi-loop-runtime.d.ts.map +1 -1
- package/dist/pi-loop-runtime.js +907 -114
- package/dist/pi-loop-runtime.js.map +1 -1
- package/dist/prompt-attachments.d.ts +98 -0
- package/dist/prompt-attachments.d.ts.map +1 -0
- package/dist/prompt-attachments.js +279 -0
- package/dist/prompt-attachments.js.map +1 -0
- package/dist/session.d.ts +55 -0
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js +443 -41
- package/dist/session.js.map +1 -1
- package/dist/stream-chunks.d.ts +15 -1
- package/dist/stream-chunks.d.ts.map +1 -1
- package/dist/stream-chunks.js +39 -18
- package/dist/stream-chunks.js.map +1 -1
- package/dist/strict.d.ts +23 -16
- package/dist/strict.d.ts.map +1 -1
- package/dist/strict.js +12 -8
- package/dist/strict.js.map +1 -1
- package/dist/submission-context.d.ts +7 -0
- package/dist/submission-context.d.ts.map +1 -1
- package/dist/submission-context.js.map +1 -1
- package/dist/submission-runner.d.ts +5 -0
- package/dist/submission-runner.d.ts.map +1 -1
- package/dist/submission-runner.js +11 -2
- package/dist/submission-runner.js.map +1 -1
- package/dist/tools.d.ts +9 -0
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +1 -0
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +26 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/usage-completeness.d.ts +39 -0
- package/dist/usage-completeness.d.ts.map +1 -0
- package/dist/usage-completeness.js +135 -0
- package/dist/usage-completeness.js.map +1 -0
- package/dist/voice-openai-realtime.d.ts +24 -2
- package/dist/voice-openai-realtime.d.ts.map +1 -1
- package/dist/voice-openai-realtime.js +266 -49
- package/dist/voice-openai-realtime.js.map +1 -1
- package/dist/voice-pipeline.d.ts +81 -3
- package/dist/voice-pipeline.d.ts.map +1 -1
- package/dist/voice-pipeline.js +429 -60
- package/dist/voice-pipeline.js.map +1 -1
- package/dist/voice-stt-cartesia.d.ts +8 -0
- package/dist/voice-stt-cartesia.d.ts.map +1 -1
- package/dist/voice-stt-cartesia.js +77 -17
- package/dist/voice-stt-cartesia.js.map +1 -1
- package/dist/voice-stt-deepgram.d.ts +10 -2
- package/dist/voice-stt-deepgram.d.ts.map +1 -1
- package/dist/voice-stt-deepgram.js +78 -18
- package/dist/voice-stt-deepgram.js.map +1 -1
- package/dist/voice-stt.d.ts +13 -3
- package/dist/voice-stt.d.ts.map +1 -1
- package/dist/voice-tts-cartesia.d.ts +8 -0
- package/dist/voice-tts-cartesia.d.ts.map +1 -1
- package/dist/voice-tts-cartesia.js +48 -105
- package/dist/voice-tts-cartesia.js.map +1 -1
- package/dist/voice-tts-elevenlabs.d.ts +10 -1
- package/dist/voice-tts-elevenlabs.d.ts.map +1 -1
- package/dist/voice-tts-elevenlabs.js +50 -113
- package/dist/voice-tts-elevenlabs.js.map +1 -1
- package/dist/voice-ws-client.js +16 -3
- package/dist/voice-ws-client.js.map +1 -1
- package/dist/voice-ws-shared.d.ts +205 -6
- package/dist/voice-ws-shared.d.ts.map +1 -1
- package/dist/voice-ws-shared.js +510 -15
- package/dist/voice-ws-shared.js.map +1 -1
- package/dist/voice.d.ts +98 -4
- package/dist/voice.d.ts.map +1 -1
- package/dist/voice.js +71 -1
- package/dist/voice.js.map +1 -1
- package/package.json +3 -3
package/dist/voice-pipeline.js
CHANGED
|
@@ -15,15 +15,71 @@
|
|
|
15
15
|
*
|
|
16
16
|
* Barge-in: when the STT emits `speech_started` while we're speaking,
|
|
17
17
|
* the in-flight TTS stream is aborted and the LLM call cancelled. The
|
|
18
|
-
* caller should also stop playback in their UI.
|
|
18
|
+
* caller should also stop playback in their UI. Each `speech_started` is
|
|
19
|
+
* bound to the reply in flight when the STT reported it, so a
|
|
20
|
+
* `cancelResponse({ interruption })` handled late (after that reply ended and
|
|
21
|
+
* a newer one started) never cancels the newer reply.
|
|
22
|
+
*
|
|
23
|
+
* Tool calls and barge-in: a reply's tool calls join the conversation history
|
|
24
|
+
* only when they are relayed as `tool_call` events, after any spoken preamble.
|
|
25
|
+
* A barge-in during that preamble commits the assistant text (in full) without
|
|
26
|
+
* them, so they are never emitted, never executed, and the next model request
|
|
27
|
+
* carries no tool call without a result. Once relayed, tool calls are no longer
|
|
28
|
+
* cancelled by a barge-in: the session stays in `await_tool` (new input queues)
|
|
29
|
+
* until every result is submitted, and the continuation runs first.
|
|
30
|
+
*
|
|
31
|
+
* Ordering: a reply never emits events before every earlier reply has emitted
|
|
32
|
+
* its `response_done`. An interrupted reply's cleanup (LLM cancellation, TTS
|
|
33
|
+
* socket teardown) is awaited for at most {@link PIPELINE_TURN_SETTLE_MS};
|
|
34
|
+
* past that bound its `response_done` is emitted with the usage known so far
|
|
35
|
+
* and any usage it reports later is dropped.
|
|
36
|
+
*
|
|
37
|
+
* Queued turns: user input accepted while a reply is in flight (thinking,
|
|
38
|
+
* speaking, or awaiting tool results) is queued — at most
|
|
39
|
+
* {@link PIPELINE_MAX_PENDING_TURNS} pending turns — and answered in order, one
|
|
40
|
+
* model call and one `response_done` per queued turn, each starting after the
|
|
41
|
+
* turn before it ends. Its user `transcript` event is emitted on acceptance.
|
|
42
|
+
* `sendText()` rejects with the fixed {@link PIPELINE_TURN_QUEUE_FULL_MESSAGE}
|
|
43
|
+
* when the queue is full, without emitting a transcript. Consecutive final STT
|
|
44
|
+
* transcripts that arrive while a reply is in flight are coalesced into one
|
|
45
|
+
* pending turn (what the caller said during a single reply is one utterance),
|
|
46
|
+
* up to {@link PIPELINE_MAX_PENDING_TURN_CHARS}; a final transcript that finds
|
|
47
|
+
* the queue full is dropped and one `error` event with the same fixed message is
|
|
48
|
+
* emitted. A barge-in cancels only the reply in flight: queued turns are kept
|
|
49
|
+
* and the oldest starts at once (its events still follow the cancelled reply's
|
|
50
|
+
* `response_done`), ahead of anything said after the barge-in. A tool-call continuation belongs to the reply
|
|
51
|
+
* that requested it and runs before queued turns. `close()` discards queued
|
|
52
|
+
* turns without a model call.
|
|
53
|
+
*
|
|
54
|
+
* STT failure: when the speech-to-text stream ends without `close()` (for
|
|
55
|
+
* example the provider closes its socket with 1011) or throws, the session
|
|
56
|
+
* emits one `error` event with the fixed {@link PIPELINE_STT_CLOSED_MESSAGE}
|
|
57
|
+
* and closes, so `events()` ends and `sendAudio()` rejects.
|
|
19
58
|
*
|
|
20
59
|
* Cost: rolled up across STT seconds, LLM tokens, TTS characters into a
|
|
21
60
|
* single `usage` object on `response_done`. `costBudget` observes the
|
|
22
|
-
* total — same `cost_limit` event semantics as realtime mode.
|
|
61
|
+
* total — same `cost_limit` event semantics as realtime mode. No model call
|
|
62
|
+
* starts while a reply's budget check is in flight, including while an
|
|
63
|
+
* `onExceed: 'approve'` approval is pending: user input keeps queueing (same
|
|
64
|
+
* bound) and a tool-call continuation waits. On approval the continuation runs,
|
|
65
|
+
* then queued turns in order; on denial, or when the approver rejects, the
|
|
66
|
+
* session emits `error` and closes, discarding queued turns without a model
|
|
67
|
+
* call. The approver owns any timeout (resolve false or reject to deny).
|
|
68
|
+
*
|
|
69
|
+
* Governed voice accounts cost itself and enables the internal
|
|
70
|
+
* `HOLD_VOICE_CONTINUATIONS` hook: from then on the same latch holds every
|
|
71
|
+
* model call (tool-call continuation, queued turn, `sendText()`, final STT
|
|
72
|
+
* transcript) from the moment a reply's model call settles until governed voice
|
|
73
|
+
* has settled that reply's `response_done`. A reply cancelled while its model
|
|
74
|
+
* call is in flight holds the next turn until its own `response_done` is
|
|
75
|
+
* settled, emitting it after at most {@link PIPELINE_TURN_SETTLE_MS} when the
|
|
76
|
+
* cancellation never settles. When governed voice closes the session instead
|
|
77
|
+
* (a limit is reached), held work is discarded without a model call.
|
|
23
78
|
*/
|
|
24
79
|
import { CostLimitExceededError } from './cost-budget.js';
|
|
25
80
|
import { applyEstimatedCost, estimateCostUsd, lookupModelPrice } from './model-pricing.js';
|
|
26
81
|
import { toolsToModelSchemas } from './model.js';
|
|
82
|
+
import { CAPTURE_VOICE_CANCEL, HOLD_VOICE_CONTINUATIONS, captureVoiceCancel, stampVoiceInterruption } from './voice.js';
|
|
27
83
|
export class PipelineVoiceProvider {
|
|
28
84
|
name;
|
|
29
85
|
stt;
|
|
@@ -41,9 +97,18 @@ export class PipelineVoiceProvider {
|
|
|
41
97
|
this.interruptedLlmCostUsd = options.interruptedLlmCostUsd;
|
|
42
98
|
this.name = options.name ?? `pipeline:${options.stt.name}+${options.tts.name}`;
|
|
43
99
|
}
|
|
44
|
-
async connect(
|
|
100
|
+
async connect(requested = {}) {
|
|
101
|
+
// Resolve the codec once so STT and TTS agree: providers default rates
|
|
102
|
+
// differently (Deepgram 16 kHz, ElevenLabs 24 kHz), and the public default
|
|
103
|
+
// is 24 kHz PCM16, or 8 kHz for G.711.
|
|
104
|
+
const audioFormat = requested.audioFormat ?? 'pcm16';
|
|
105
|
+
const options = {
|
|
106
|
+
...requested,
|
|
107
|
+
audioFormat,
|
|
108
|
+
sampleRate: requested.sampleRate ?? (audioFormat === 'pcm16' ? 24_000 : 8_000),
|
|
109
|
+
};
|
|
45
110
|
const sttSession = await this.stt.open({
|
|
46
|
-
|
|
111
|
+
audioFormat,
|
|
47
112
|
...(options.sampleRate ? { sampleRate: options.sampleRate } : {}),
|
|
48
113
|
...(options.signal ? { signal: options.signal } : {}),
|
|
49
114
|
});
|
|
@@ -58,6 +123,34 @@ export class PipelineVoiceProvider {
|
|
|
58
123
|
});
|
|
59
124
|
}
|
|
60
125
|
}
|
|
126
|
+
/**
|
|
127
|
+
* Longest a reply waits for the previous, interrupted reply to finish its
|
|
128
|
+
* cancellation cleanup before emitting that reply's `response_done` itself.
|
|
129
|
+
* @internal Not exported from the package entry points.
|
|
130
|
+
*/
|
|
131
|
+
export const PIPELINE_TURN_SETTLE_MS = 2_000;
|
|
132
|
+
/**
|
|
133
|
+
* Fixed `error` event message when the speech-to-text stream ends or fails
|
|
134
|
+
* without the session being closed. It never carries provider detail.
|
|
135
|
+
* @internal Not exported from the package entry points.
|
|
136
|
+
*/
|
|
137
|
+
export const PIPELINE_STT_CLOSED_MESSAGE = 'Speech-to-text connection closed unexpectedly';
|
|
138
|
+
/**
|
|
139
|
+
* Most user turns queued while a reply is in flight.
|
|
140
|
+
* @internal Not exported from the package entry points.
|
|
141
|
+
*/
|
|
142
|
+
export const PIPELINE_MAX_PENDING_TURNS = 8;
|
|
143
|
+
/**
|
|
144
|
+
* Longest text consecutive pending STT finals are coalesced into; past it the
|
|
145
|
+
* next final starts a new pending turn.
|
|
146
|
+
*/
|
|
147
|
+
const PIPELINE_MAX_PENDING_TURN_CHARS = 16_384;
|
|
148
|
+
/**
|
|
149
|
+
* Fixed rejection / `error` message when a user turn arrives with
|
|
150
|
+
* {@link PIPELINE_MAX_PENDING_TURNS} turns already queued.
|
|
151
|
+
* @internal Not exported from the package entry points.
|
|
152
|
+
*/
|
|
153
|
+
export const PIPELINE_TURN_QUEUE_FULL_MESSAGE = 'Voice input queue is full; wait for the current reply';
|
|
61
154
|
class PipelineVoiceSession {
|
|
62
155
|
stt;
|
|
63
156
|
sttProviderName;
|
|
@@ -72,10 +165,31 @@ class PipelineVoiceSession {
|
|
|
72
165
|
queue = [];
|
|
73
166
|
waiters = [];
|
|
74
167
|
closed = false;
|
|
168
|
+
emitSpeechStopped;
|
|
75
169
|
messages = [];
|
|
76
170
|
state = 'listening';
|
|
77
|
-
|
|
171
|
+
/** The reply a cancel without an interruption targets; cleared once cancelled or finished. */
|
|
172
|
+
currentTurn;
|
|
173
|
+
/** The most recent reply, until its `response_done` is emitted (orders the next reply). */
|
|
174
|
+
lastTurn;
|
|
175
|
+
closedSignal = new AbortController();
|
|
176
|
+
/** The caller's signal, detached on close so a shared signal does not retain closed sessions. */
|
|
177
|
+
callerSignal;
|
|
178
|
+
onCallerAbort = () => { void this.close(); };
|
|
78
179
|
pendingToolCalls = [];
|
|
180
|
+
/** User turns accepted while a reply was in flight, oldest first. */
|
|
181
|
+
pendingTurns = [];
|
|
182
|
+
/**
|
|
183
|
+
* Budget checks in flight (recording a reply's cost, possibly awaiting an
|
|
184
|
+
* over-budget approval). No model call starts while this is nonzero.
|
|
185
|
+
*/
|
|
186
|
+
budgetSettling = 0;
|
|
187
|
+
/** Every tool result arrived while a budget check was in flight; continue once it settles. */
|
|
188
|
+
continuationDeferred = false;
|
|
189
|
+
/** Set by {@link HOLD_VOICE_CONTINUATIONS}: a wrapper settles each `response_done` itself. */
|
|
190
|
+
externalSettlement = false;
|
|
191
|
+
/** `response_done`s the wrapper has not settled yet; no model call starts while nonzero. */
|
|
192
|
+
externalSettling = 0;
|
|
79
193
|
// Per-turn rollup for cost telemetry.
|
|
80
194
|
sttSecondsAccounted = 0;
|
|
81
195
|
synthesisOptions;
|
|
@@ -90,6 +204,7 @@ class PipelineVoiceSession {
|
|
|
90
204
|
this.instructions = init.options.instructions;
|
|
91
205
|
this.costBudget = init.options.costBudget;
|
|
92
206
|
this.requestCostLimitApproval = init.options.requestCostLimitApproval;
|
|
207
|
+
this.emitSpeechStopped = init.options.emitSpeechStopped === true;
|
|
93
208
|
this.synthesisOptions = {
|
|
94
209
|
...(init.options.voice ? { voice: init.options.voice } : {}),
|
|
95
210
|
...(init.options.audioFormat ? { audioFormat: init.options.audioFormat } : {}),
|
|
@@ -100,20 +215,77 @@ class PipelineVoiceSession {
|
|
|
100
215
|
this.push({ type: 'session_open' });
|
|
101
216
|
// Pump STT events.
|
|
102
217
|
void this.consumeStt();
|
|
103
|
-
init.options.signal
|
|
218
|
+
const signal = init.options.signal;
|
|
219
|
+
if (signal?.aborted)
|
|
220
|
+
void this.close();
|
|
221
|
+
else if (signal) {
|
|
222
|
+
this.callerSignal = signal;
|
|
223
|
+
signal.addEventListener('abort', this.onCallerAbort, { once: true });
|
|
224
|
+
}
|
|
104
225
|
}
|
|
105
226
|
async sendAudio(frame) {
|
|
106
227
|
if (this.closed)
|
|
107
228
|
throw new Error('Voice session closed');
|
|
108
|
-
|
|
229
|
+
try {
|
|
230
|
+
// Built-in STT sessions resolve once the frame is admitted to a bounded buffer.
|
|
231
|
+
await this.stt.send(frame);
|
|
232
|
+
}
|
|
233
|
+
catch (error) {
|
|
234
|
+
await this.close();
|
|
235
|
+
throw error;
|
|
236
|
+
}
|
|
109
237
|
}
|
|
110
238
|
async sendText(text) {
|
|
111
239
|
if (this.closed)
|
|
112
240
|
throw new Error('Voice session closed');
|
|
113
241
|
if (!text)
|
|
114
242
|
return;
|
|
243
|
+
if (!this.acceptUserTurn(text, 'text'))
|
|
244
|
+
throw new Error(PIPELINE_TURN_QUEUE_FULL_MESSAGE);
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* Queue a user turn and start it if no reply is in flight. Returns false,
|
|
248
|
+
* with nothing emitted or queued, when the pending queue is full.
|
|
249
|
+
*/
|
|
250
|
+
acceptUserTurn(text, source) {
|
|
251
|
+
const tail = this.pendingTurns.at(-1);
|
|
252
|
+
if (source === 'stt' && tail?.source === 'stt' && tail.text.length + 1 + text.length <= PIPELINE_MAX_PENDING_TURN_CHARS) {
|
|
253
|
+
tail.text = `${tail.text} ${text}`;
|
|
254
|
+
}
|
|
255
|
+
else {
|
|
256
|
+
if (this.pendingTurns.length >= PIPELINE_MAX_PENDING_TURNS)
|
|
257
|
+
return false;
|
|
258
|
+
this.pendingTurns.push({ text, source });
|
|
259
|
+
}
|
|
115
260
|
this.push({ type: 'transcript', text, role: 'user' });
|
|
116
|
-
this.
|
|
261
|
+
this.startNextTurn();
|
|
262
|
+
return true;
|
|
263
|
+
}
|
|
264
|
+
/** True while a budget check or a wrapper's accounting of a reply is in flight. */
|
|
265
|
+
turnsHeld() {
|
|
266
|
+
return this.budgetSettling > 0 || this.externalSettling > 0;
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* Governed voice accounts cost itself: from now on each reply holds every
|
|
270
|
+
* model call from the moment its own model call settles until the returned
|
|
271
|
+
* callback settles its `response_done` (once per `response_done`, in order).
|
|
272
|
+
*/
|
|
273
|
+
[HOLD_VOICE_CONTINUATIONS]() {
|
|
274
|
+
this.externalSettlement = true;
|
|
275
|
+
return () => {
|
|
276
|
+
if (this.externalSettling > 0)
|
|
277
|
+
this.externalSettling--;
|
|
278
|
+
this.resumeTurns();
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
/** Start the oldest queued user turn when no reply is in flight. */
|
|
282
|
+
startNextTurn() {
|
|
283
|
+
if (this.closed || this.state !== 'listening' || this.turnsHeld())
|
|
284
|
+
return;
|
|
285
|
+
const next = this.pendingTurns.shift();
|
|
286
|
+
if (!next)
|
|
287
|
+
return;
|
|
288
|
+
this.messages.push({ role: 'user', content: next.text });
|
|
117
289
|
void this.runLlmTurn();
|
|
118
290
|
}
|
|
119
291
|
async submitToolResult(input) {
|
|
@@ -126,16 +298,68 @@ class PipelineVoiceSession {
|
|
|
126
298
|
// Remove the matching pending tool call. When all are resolved, continue.
|
|
127
299
|
this.pendingToolCalls = this.pendingToolCalls.filter((c) => c.id !== input.id);
|
|
128
300
|
if (this.pendingToolCalls.length === 0) {
|
|
301
|
+
// Stay in await_tool (queued turns stay behind the continuation) until
|
|
302
|
+
// the budget check settles; resumeTurns() then continues.
|
|
303
|
+
if (this.turnsHeld()) {
|
|
304
|
+
this.continuationDeferred = true;
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
129
307
|
// Reset state so runLlmTurn() doesn't early-return on the thinking guard.
|
|
130
308
|
this.state = 'listening';
|
|
131
309
|
void this.runLlmTurn();
|
|
132
310
|
}
|
|
133
311
|
}
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
312
|
+
/**
|
|
313
|
+
* Once no budget check is in flight, run a deferred tool-call continuation,
|
|
314
|
+
* else the oldest queued user turn.
|
|
315
|
+
*/
|
|
316
|
+
resumeTurns() {
|
|
317
|
+
if (this.closed || this.turnsHeld())
|
|
318
|
+
return;
|
|
319
|
+
if (this.continuationDeferred) {
|
|
320
|
+
this.continuationDeferred = false;
|
|
321
|
+
this.state = 'listening';
|
|
322
|
+
void this.runLlmTurn();
|
|
323
|
+
return;
|
|
324
|
+
}
|
|
325
|
+
this.startNextTurn();
|
|
326
|
+
}
|
|
327
|
+
async cancelResponse(options = {}) {
|
|
328
|
+
return captureVoiceCancel(this, options)(options);
|
|
329
|
+
}
|
|
330
|
+
/**
|
|
331
|
+
* Bind a barge-in to the reply in flight now. A `speech_started` is stamped
|
|
332
|
+
* with this at STT receipt, so a cancel handled after that reply finished
|
|
333
|
+
* and a newer one started is a no-op instead of cancelling the newer reply.
|
|
334
|
+
*/
|
|
335
|
+
[CAPTURE_VOICE_CANCEL]() {
|
|
336
|
+
const turn = this.currentTurn;
|
|
337
|
+
return async () => { this.cancelTurn(turn); };
|
|
338
|
+
}
|
|
339
|
+
cancelTurn(turn) {
|
|
340
|
+
if (!turn || this.closed)
|
|
341
|
+
return;
|
|
342
|
+
turn.abort.abort();
|
|
343
|
+
if (this.currentTurn !== turn)
|
|
344
|
+
return;
|
|
345
|
+
this.currentTurn = undefined;
|
|
137
346
|
if (this.state !== 'await_tool')
|
|
138
347
|
this.state = 'listening';
|
|
348
|
+
// A cancelled reply whose cost is already known emits nothing more: settle
|
|
349
|
+
// its response_done and budget check now, so the latch it holds never waits
|
|
350
|
+
// on TTS cleanup a provider may never finish.
|
|
351
|
+
if (turn.holdsBudget)
|
|
352
|
+
void this.finishTurn(turn);
|
|
353
|
+
// Governed voice: a reply cancelled while its model call is in flight may
|
|
354
|
+
// still be billed. Hold the next turn until its response_done is settled,
|
|
355
|
+
// emitting it after the settle bound if its cancellation never settles.
|
|
356
|
+
else if (this.externalSettlement)
|
|
357
|
+
this.holdCancelledTurn(turn);
|
|
358
|
+
// Queued input survives the barge-in. Start it now rather than after the
|
|
359
|
+
// cancelled reply's cleanup; its events still wait for that reply's
|
|
360
|
+
// response_done (bounded by the settle timeout). A budget check in flight
|
|
361
|
+
// defers the start until it settles.
|
|
362
|
+
this.startNextTurn();
|
|
139
363
|
}
|
|
140
364
|
events() {
|
|
141
365
|
return {
|
|
@@ -149,7 +373,12 @@ class PipelineVoiceSession {
|
|
|
149
373
|
if (this.closed)
|
|
150
374
|
return;
|
|
151
375
|
this.closed = true;
|
|
152
|
-
this.
|
|
376
|
+
this.callerSignal?.removeEventListener('abort', this.onCallerAbort);
|
|
377
|
+
this.callerSignal = undefined;
|
|
378
|
+
this.closedSignal.abort();
|
|
379
|
+
this.currentTurn?.abort.abort();
|
|
380
|
+
// Queued user turns are never answered once the session closes.
|
|
381
|
+
this.pendingTurns.length = 0;
|
|
153
382
|
try {
|
|
154
383
|
await this.stt.close();
|
|
155
384
|
}
|
|
@@ -177,11 +406,13 @@ class PipelineVoiceSession {
|
|
|
177
406
|
void this.close();
|
|
178
407
|
return;
|
|
179
408
|
}
|
|
409
|
+
// speech_stopped is opt-in (emitSpeechStopped) and outside the VoiceEvent union.
|
|
410
|
+
const value = event;
|
|
180
411
|
const w = this.waiters.shift();
|
|
181
412
|
if (w)
|
|
182
|
-
w({ value
|
|
413
|
+
w({ value, done: false });
|
|
183
414
|
else
|
|
184
|
-
this.queue.push(
|
|
415
|
+
this.queue.push(value);
|
|
185
416
|
}
|
|
186
417
|
async consumeStt() {
|
|
187
418
|
try {
|
|
@@ -190,9 +421,10 @@ class PipelineVoiceSession {
|
|
|
190
421
|
break;
|
|
191
422
|
switch (event.type) {
|
|
192
423
|
case 'transcript': {
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
424
|
+
if (!event.text)
|
|
425
|
+
break;
|
|
426
|
+
if (!this.acceptUserTurn(event.text, 'stt'))
|
|
427
|
+
this.push({ type: 'error', message: PIPELINE_TURN_QUEUE_FULL_MESSAGE });
|
|
196
428
|
break;
|
|
197
429
|
}
|
|
198
430
|
case 'partial': {
|
|
@@ -201,16 +433,18 @@ class PipelineVoiceSession {
|
|
|
201
433
|
break;
|
|
202
434
|
}
|
|
203
435
|
case 'speech_started': {
|
|
204
|
-
|
|
436
|
+
// Bind the interruption to the reply in flight now: consumers (governed
|
|
437
|
+
// voice, telephony bridges) may act on it only after a newer reply started.
|
|
438
|
+
const cancel = this[CAPTURE_VOICE_CANCEL]();
|
|
439
|
+
this.push(stampVoiceInterruption({ type: 'speech_started' }, this, cancel));
|
|
205
440
|
// Barge-in: cancel in-flight TTS + LLM if we were speaking.
|
|
206
|
-
if (this.state === 'speaking' || this.state === 'thinking')
|
|
207
|
-
|
|
208
|
-
this.currentTurnAbort = undefined;
|
|
209
|
-
this.state = 'listening';
|
|
210
|
-
}
|
|
441
|
+
if (this.state === 'speaking' || this.state === 'thinking')
|
|
442
|
+
await cancel();
|
|
211
443
|
break;
|
|
212
444
|
}
|
|
213
445
|
case 'speech_ended':
|
|
446
|
+
if (this.emitSpeechStopped)
|
|
447
|
+
this.push({ type: 'speech_stopped' });
|
|
214
448
|
break;
|
|
215
449
|
case 'error':
|
|
216
450
|
this.push({ type: 'error', message: event.message });
|
|
@@ -218,9 +452,16 @@ class PipelineVoiceSession {
|
|
|
218
452
|
}
|
|
219
453
|
}
|
|
220
454
|
}
|
|
221
|
-
catch
|
|
222
|
-
|
|
455
|
+
catch {
|
|
456
|
+
// Fall through: a failed STT stream ends the call like an unexpected close.
|
|
223
457
|
}
|
|
458
|
+
// The STT stream ended without our close() (for example a provider 1011
|
|
459
|
+
// close): nothing will ever transcribe the caller again, so fail the
|
|
460
|
+
// session instead of leaving a call connected with no responses.
|
|
461
|
+
if (this.closed)
|
|
462
|
+
return;
|
|
463
|
+
this.push({ type: 'error', message: PIPELINE_STT_CLOSED_MESSAGE });
|
|
464
|
+
await this.close();
|
|
224
465
|
}
|
|
225
466
|
async runLlmTurn() {
|
|
226
467
|
if (this.closed)
|
|
@@ -228,10 +469,15 @@ class PipelineVoiceSession {
|
|
|
228
469
|
if (this.state !== 'listening')
|
|
229
470
|
return;
|
|
230
471
|
this.state = 'thinking';
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
472
|
+
let markResponseDone;
|
|
473
|
+
const responseDone = new Promise(resolve => { markResponseDone = resolve; });
|
|
474
|
+
const turn = {
|
|
475
|
+
abort: new AbortController(), previous: this.lastTurn, llmUsage: undefined, ttsCharacters: 0,
|
|
476
|
+
finished: undefined, responseDone, markResponseDone, ordered: undefined, holdsBudget: false,
|
|
477
|
+
};
|
|
478
|
+
this.currentTurn = turn;
|
|
479
|
+
this.lastTurn = turn;
|
|
480
|
+
const abort = turn.abort;
|
|
235
481
|
try {
|
|
236
482
|
const response = await this.llm.generate({
|
|
237
483
|
model: this.modelId,
|
|
@@ -239,27 +485,48 @@ class PipelineVoiceSession {
|
|
|
239
485
|
...(this.tools.length > 0 ? { tools: toolsToModelSchemas(this.tools) } : {}),
|
|
240
486
|
signal: abort.signal,
|
|
241
487
|
});
|
|
242
|
-
llmUsage = response.usage;
|
|
488
|
+
turn.llmUsage = response.usage;
|
|
489
|
+
// Before anything can yield to a consumer (tool_call, transcript), hold
|
|
490
|
+
// every turn start and continuation until this reply's budget check settles.
|
|
491
|
+
this.holdBudget(turn);
|
|
243
492
|
if (abort.signal.aborted)
|
|
244
493
|
return;
|
|
494
|
+
// Emit nothing until the previous (interrupted) reply has emitted response_done.
|
|
495
|
+
await this.afterPrevious(turn);
|
|
496
|
+
if (abort.signal.aborted || this.closed)
|
|
497
|
+
return;
|
|
245
498
|
const assistantMessage = response.message;
|
|
246
499
|
const toolCalls = response.toolCalls ?? assistantMessage?.toolCalls ?? [];
|
|
247
|
-
// Record assistant turn for next
|
|
248
|
-
|
|
249
|
-
|
|
500
|
+
// Record the assistant turn for the next model call, without its tool
|
|
501
|
+
// calls: they join history only once relayed to the caller below. A
|
|
502
|
+
// barge-in during the spoken preamble therefore leaves no tool call that
|
|
503
|
+
// was never executed and that no result will ever answer (providers
|
|
504
|
+
// reject an assistant tool call without a matching tool result).
|
|
505
|
+
let committed;
|
|
506
|
+
if (assistantMessage) {
|
|
507
|
+
const { toolCalls: _unexposed, ...spoken } = assistantMessage;
|
|
508
|
+
committed = spoken;
|
|
509
|
+
this.messages.push(committed);
|
|
510
|
+
}
|
|
250
511
|
// Surface text content via TTS + text_delta events.
|
|
251
512
|
const text = assistantMessage?.content ?? '';
|
|
252
513
|
if (text) {
|
|
253
514
|
this.state = 'speaking';
|
|
254
515
|
this.push({ type: 'text_delta', delta: text, role: 'assistant' });
|
|
255
516
|
this.push({ type: 'transcript', text, role: 'assistant' });
|
|
256
|
-
ttsCharacters = text.length;
|
|
517
|
+
turn.ttsCharacters = text.length;
|
|
257
518
|
await this.streamTts(text, abort.signal);
|
|
258
519
|
}
|
|
259
520
|
if (abort.signal.aborted || this.closed)
|
|
260
521
|
return;
|
|
261
522
|
// Tool-call relay: emit and pause until results submitted.
|
|
262
523
|
if (toolCalls.length > 0) {
|
|
524
|
+
// Commit exactly the calls relayed, so every one is answered by the
|
|
525
|
+
// tool result the caller submits for it.
|
|
526
|
+
if (committed)
|
|
527
|
+
committed.toolCalls = [...toolCalls];
|
|
528
|
+
else
|
|
529
|
+
this.messages.push({ role: 'assistant', content: '', toolCalls: [...toolCalls] });
|
|
263
530
|
this.pendingToolCalls = [...toolCalls];
|
|
264
531
|
this.state = 'await_tool';
|
|
265
532
|
for (const call of toolCalls) {
|
|
@@ -271,37 +538,138 @@ class PipelineVoiceSession {
|
|
|
271
538
|
}
|
|
272
539
|
}
|
|
273
540
|
catch (err) {
|
|
541
|
+
this.holdBudget(turn);
|
|
274
542
|
if (abort.signal.aborted)
|
|
275
543
|
return;
|
|
544
|
+
await this.afterPrevious(turn);
|
|
276
545
|
this.push({ type: 'error', message: err.message });
|
|
277
|
-
this.
|
|
546
|
+
if (this.currentTurn === turn)
|
|
547
|
+
this.state = 'listening';
|
|
278
548
|
}
|
|
279
549
|
finally {
|
|
280
|
-
if (
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
550
|
+
if (this.currentTurn === turn)
|
|
551
|
+
this.currentTurn = undefined;
|
|
552
|
+
await this.afterPrevious(turn);
|
|
553
|
+
await this.finishTurn(turn);
|
|
554
|
+
// Answer the next queued user turn only after this reply's response_done
|
|
555
|
+
// (and its budget check, which may have closed the session).
|
|
556
|
+
this.startNextTurn();
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
/**
|
|
560
|
+
* Wait, at most {@link PIPELINE_TURN_SETTLE_MS}, for the previous reply to
|
|
561
|
+
* emit its `response_done`; past the bound, emit it on that reply's behalf
|
|
562
|
+
* so this reply's events still follow it.
|
|
563
|
+
*/
|
|
564
|
+
afterPrevious(turn) {
|
|
565
|
+
turn.ordered ??= (async () => {
|
|
566
|
+
const previous = turn.previous;
|
|
567
|
+
if (!previous || previous.finished)
|
|
568
|
+
return;
|
|
569
|
+
let timer;
|
|
570
|
+
const closed = this.closedSignal.signal;
|
|
571
|
+
let onClose;
|
|
572
|
+
const settled = await Promise.race([
|
|
573
|
+
previous.responseDone.then(() => true),
|
|
574
|
+
new Promise(resolve => {
|
|
575
|
+
timer = setTimeout(() => resolve(false), PIPELINE_TURN_SETTLE_MS);
|
|
576
|
+
onClose = () => resolve(true);
|
|
577
|
+
closed.addEventListener('abort', onClose, { once: true });
|
|
578
|
+
}),
|
|
579
|
+
]);
|
|
580
|
+
clearTimeout(timer);
|
|
581
|
+
if (onClose)
|
|
582
|
+
closed.removeEventListener('abort', onClose);
|
|
583
|
+
if (!settled && !this.closed)
|
|
584
|
+
void this.finishTurn(previous);
|
|
585
|
+
})();
|
|
586
|
+
return turn.ordered;
|
|
587
|
+
}
|
|
588
|
+
/**
|
|
589
|
+
* Emit a reply's `response_done` exactly once, after every earlier reply's
|
|
590
|
+
* (synchronously, so the order holds even when a later reply forces it),
|
|
591
|
+
* then apply the cost budget.
|
|
592
|
+
*/
|
|
593
|
+
finishTurn(turn) {
|
|
594
|
+
if (turn.finished)
|
|
595
|
+
return turn.finished;
|
|
596
|
+
if (turn.previous)
|
|
597
|
+
void this.finishTurn(turn.previous);
|
|
598
|
+
turn.previous = undefined;
|
|
599
|
+
let llmUsage = turn.llmUsage;
|
|
600
|
+
if (turn.abort.signal.aborted && this.interruptedLlmCostUsd !== undefined) {
|
|
601
|
+
llmUsage = { ...llmUsage };
|
|
602
|
+
applyEstimatedCost(this.modelKey(), llmUsage);
|
|
603
|
+
if (llmUsage.costUsd === undefined)
|
|
604
|
+
llmUsage.costUsd = this.interruptedLlmCostUsd;
|
|
605
|
+
}
|
|
606
|
+
const usage = this.rollupUsage(llmUsage, turn.ttsCharacters);
|
|
607
|
+
// Before the event can reach the wrapper, so its settle always has a hold to release.
|
|
608
|
+
if (this.externalSettlement && !this.closed)
|
|
609
|
+
this.externalSettling++;
|
|
610
|
+
this.push({ type: 'response_done', ...(usage ? { usage } : {}) });
|
|
611
|
+
if (this.lastTurn === turn)
|
|
612
|
+
this.lastTurn = undefined;
|
|
613
|
+
turn.markResponseDone();
|
|
614
|
+
turn.finished = this.applyTurnBudget(turn, usage);
|
|
615
|
+
return turn.finished;
|
|
616
|
+
}
|
|
617
|
+
/**
|
|
618
|
+
* Take the budget latch for a reply whose model call just settled, unless
|
|
619
|
+
* its budget check already ran (a later reply forced its response_done).
|
|
620
|
+
* Synchronous, so no consumer reaction can start a model call in between.
|
|
621
|
+
*/
|
|
622
|
+
holdBudget(turn) {
|
|
623
|
+
if (turn.holdsBudget || turn.finished || (!this.costBudget?.enabled() && !this.externalSettlement))
|
|
624
|
+
return;
|
|
625
|
+
turn.holdsBudget = true;
|
|
626
|
+
this.budgetSettling++;
|
|
627
|
+
}
|
|
628
|
+
/**
|
|
629
|
+
* Hold turn starts for a reply cancelled before its model call settled,
|
|
630
|
+
* until its `response_done` (emitted after at most
|
|
631
|
+
* {@link PIPELINE_TURN_SETTLE_MS}) has been settled by the wrapper.
|
|
632
|
+
*/
|
|
633
|
+
holdCancelledTurn(turn) {
|
|
634
|
+
if (turn.finished)
|
|
635
|
+
return;
|
|
636
|
+
this.holdBudget(turn);
|
|
637
|
+
const timer = setTimeout(() => { if (!this.closed)
|
|
638
|
+
void this.finishTurn(turn); }, PIPELINE_TURN_SETTLE_MS);
|
|
639
|
+
const clear = () => { clearTimeout(timer); this.closedSignal.signal.removeEventListener('abort', clear); };
|
|
640
|
+
void turn.responseDone.then(clear);
|
|
641
|
+
this.closedSignal.signal.addEventListener('abort', clear, { once: true });
|
|
642
|
+
}
|
|
643
|
+
async applyTurnBudget(turn, usage) {
|
|
644
|
+
const held = turn.holdsBudget;
|
|
645
|
+
turn.holdsBudget = false;
|
|
646
|
+
if (!this.costBudget?.enabled()) {
|
|
647
|
+
if (held) {
|
|
648
|
+
this.budgetSettling--;
|
|
649
|
+
this.resumeTurns();
|
|
285
650
|
}
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
}
|
|
297
|
-
catch {
|
|
298
|
-
this.push({ type: 'error', message: 'Voice cost accounting failed' });
|
|
299
|
-
await this.close();
|
|
300
|
-
}
|
|
301
|
-
}
|
|
651
|
+
return;
|
|
652
|
+
}
|
|
653
|
+
// Hold every turn start until this check (and any approval) settles.
|
|
654
|
+
if (!held)
|
|
655
|
+
this.budgetSettling++;
|
|
656
|
+
try {
|
|
657
|
+
if (usage?.costUsd === undefined) {
|
|
658
|
+
this.push({ type: 'error', message: 'Voice cost is unknown; stopping budgeted session' });
|
|
659
|
+
await this.close();
|
|
660
|
+
return;
|
|
302
661
|
}
|
|
303
|
-
|
|
304
|
-
this.
|
|
662
|
+
try {
|
|
663
|
+
await this.handleCostBudget(usage.costUsd);
|
|
664
|
+
}
|
|
665
|
+
catch {
|
|
666
|
+
this.push({ type: 'error', message: 'Voice cost accounting failed' });
|
|
667
|
+
await this.close();
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
finally {
|
|
671
|
+
this.budgetSettling--;
|
|
672
|
+
this.resumeTurns();
|
|
305
673
|
}
|
|
306
674
|
}
|
|
307
675
|
async streamTts(text, signal) {
|
|
@@ -343,8 +711,9 @@ class PipelineVoiceSession {
|
|
|
343
711
|
this.push({ type: 'cost_limit', scope: violation.scope, observedUsd: violation.observedUsd, limitUsd: violation.limitUsd, ...(violation.scopeKey ? { scopeKey: violation.scopeKey } : {}) });
|
|
344
712
|
const mode = this.costBudget?.onExceed();
|
|
345
713
|
if (mode === 'approve' && this.requestCostLimitApproval) {
|
|
346
|
-
|
|
347
|
-
|
|
714
|
+
// A rejecting approver denies: the session never continues on an unsettled overrun.
|
|
715
|
+
const approved = await this.requestCostLimitApproval(violation).then(result => result === true, () => false);
|
|
716
|
+
if (approved && !this.closed)
|
|
348
717
|
return;
|
|
349
718
|
}
|
|
350
719
|
this.push({ type: 'error', message: new CostLimitExceededError(violation).message });
|