@fabric-harness/sdk 6.9.1 → 6.11.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/agent.d.ts.map +1 -1
- package/dist/agent.js +8 -0
- package/dist/agent.js.map +1 -1
- package/dist/channel-runtime.d.ts +2 -0
- package/dist/channel-runtime.d.ts.map +1 -1
- package/dist/channel-runtime.js +1 -0
- package/dist/channel-runtime.js.map +1 -1
- package/dist/channel.d.ts +11 -0
- package/dist/channel.d.ts.map +1 -1
- package/dist/channel.js.map +1 -1
- package/dist/context.d.ts +28 -0
- package/dist/context.d.ts.map +1 -1
- package/dist/context.js +18 -0
- package/dist/context.js.map +1 -1
- package/dist/conversation-ownership.d.ts +151 -0
- package/dist/conversation-ownership.d.ts.map +1 -0
- package/dist/conversation-ownership.js +239 -0
- package/dist/conversation-ownership.js.map +1 -0
- package/dist/dispatch.d.ts +7 -0
- package/dist/dispatch.d.ts.map +1 -1
- package/dist/dispatch.js.map +1 -1
- package/dist/dynamic-agent.d.ts.map +1 -1
- package/dist/dynamic-agent.js +8 -0
- package/dist/dynamic-agent.js.map +1 -1
- package/dist/error.d.ts +1 -1
- package/dist/error.d.ts.map +1 -1
- package/dist/error.js.map +1 -1
- package/dist/events.d.ts +16 -4
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js.map +1 -1
- package/dist/governed-voice.d.ts.map +1 -1
- package/dist/governed-voice.js +192 -125
- package/dist/governed-voice.js.map +1 -1
- package/dist/index.d.ts +9 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -1
- package/dist/index.js.map +1 -1
- package/dist/loop.d.ts +8 -0
- package/dist/loop.d.ts.map +1 -1
- package/dist/loop.js +22 -1
- package/dist/loop.js.map +1 -1
- package/dist/model-pricing.js +1 -1
- package/dist/model-pricing.js.map +1 -1
- package/dist/model.d.ts +20 -2
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +88 -9
- package/dist/model.js.map +1 -1
- package/dist/operational-metrics.d.ts.map +1 -1
- package/dist/operational-metrics.js +3 -1
- package/dist/operational-metrics.js.map +1 -1
- package/dist/otel-observer.d.ts.map +1 -1
- package/dist/otel-observer.js +32 -10
- package/dist/otel-observer.js.map +1 -1
- package/dist/persistent-agent.d.ts +1 -1
- package/dist/persistent-agent.d.ts.map +1 -1
- package/dist/persistent-agent.js.map +1 -1
- package/dist/pi-loop-runtime.d.ts.map +1 -1
- package/dist/pi-loop-runtime.js +152 -8
- package/dist/pi-loop-runtime.js.map +1 -1
- package/dist/policied-sandbox.d.ts.map +1 -1
- package/dist/policied-sandbox.js +16 -3
- package/dist/policied-sandbox.js.map +1 -1
- package/dist/proposal-tool.d.ts +260 -0
- package/dist/proposal-tool.d.ts.map +1 -0
- package/dist/proposal-tool.js +562 -0
- package/dist/proposal-tool.js.map +1 -0
- package/dist/session.d.ts +55 -0
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js +528 -181
- package/dist/session.js.map +1 -1
- package/dist/stop-reason-guard.d.ts +89 -0
- package/dist/stop-reason-guard.d.ts.map +1 -0
- package/dist/stop-reason-guard.js +261 -0
- package/dist/stop-reason-guard.js.map +1 -0
- package/dist/strict.d.ts +8 -1
- package/dist/strict.d.ts.map +1 -1
- package/dist/strict.js +4 -1
- package/dist/strict.js.map +1 -1
- package/dist/tools.d.ts +2 -0
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +10 -2
- package/dist/tools.js.map +1 -1
- package/dist/trace-content.d.ts +1 -1
- package/dist/trace-content.d.ts.map +1 -1
- package/dist/trace-content.js +2 -2
- package/dist/trace-content.js.map +1 -1
- package/dist/types.d.ts +23 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/voice-pipeline.d.ts +70 -3
- package/dist/voice-pipeline.d.ts.map +1 -1
- package/dist/voice-pipeline.js +386 -44
- package/dist/voice-pipeline.js.map +1 -1
- package/dist/voice-sentences.d.ts +43 -0
- package/dist/voice-sentences.d.ts.map +1 -0
- package/dist/voice-sentences.js +99 -0
- package/dist/voice-sentences.js.map +1 -0
- package/dist/voice.d.ts +9 -0
- package/dist/voice.d.ts.map +1 -1
- package/dist/voice.js +6 -0
- package/dist/voice.js.map +1 -1
- package/package.json +30 -13
package/dist/voice-pipeline.js
CHANGED
|
@@ -32,7 +32,7 @@
|
|
|
32
32
|
* its `response_done`. An interrupted reply's cleanup (LLM cancellation, TTS
|
|
33
33
|
* socket teardown) is awaited for at most {@link PIPELINE_TURN_SETTLE_MS};
|
|
34
34
|
* past that bound its `response_done` is emitted with the usage known so far
|
|
35
|
-
*
|
|
35
|
+
* even if no new turn starts. Any usage it reports later is dropped.
|
|
36
36
|
*
|
|
37
37
|
* Queued turns: user input accepted while a reply is in flight (thinking,
|
|
38
38
|
* speaking, or awaiting tool results) is queued — at most
|
|
@@ -51,6 +51,49 @@
|
|
|
51
51
|
* that requested it and runs before queued turns. `close()` discards queued
|
|
52
52
|
* turns without a model call.
|
|
53
53
|
*
|
|
54
|
+
* Sentence streaming (`sentenceStreaming: true` with an `llm` that implements
|
|
55
|
+
* `stream()`; otherwise every reply uses `generate()`): the reply is read from
|
|
56
|
+
* the model stream and split into sentences, and each completed sentence is
|
|
57
|
+
* emitted as a `text_delta` and synthesized with its own `tts.synthesize()`
|
|
58
|
+
* call, one after another, so sentence N+1's audio follows sentence N's. No
|
|
59
|
+
* synthesis call gets more than {@link PIPELINE_MAX_SENTENCE_CHARS}; a longer
|
|
60
|
+
* sentence is cut into pieces. The model stream keeps being read while a
|
|
61
|
+
* sentence is synthesized; between chunks the read pauses while more than
|
|
62
|
+
* {@link PIPELINE_MAX_BUFFERED_SPEECH_CHARS} of complete sentences are waiting
|
|
63
|
+
* (a threshold: one large chunk is queued whole). The model request's signal
|
|
64
|
+
* belongs to the reply, not the turn: it is aborted when the reply is cancelled
|
|
65
|
+
* and when the reply ends for any other reason (completion, a model or
|
|
66
|
+
* synthesis error), and the stream is not pulled again. An unfinished stream is
|
|
67
|
+
* returned once; one whose read reported done or rejected is not.
|
|
68
|
+
* The ordering and budget rules above hold with one change of timing: the reply
|
|
69
|
+
* waits for earlier replies' `response_done` and takes the budget latch before
|
|
70
|
+
* its first event, while its model stream is still running. A reply with text
|
|
71
|
+
* that is past that wait emits one assistant `transcript`, once, not in pieces.
|
|
72
|
+
* Once the stream has ended and every sentence has been emitted as a
|
|
73
|
+
* `text_delta`, the reply's text is complete: the transcript follows its last
|
|
74
|
+
* `text_delta`, and the transcript and the committed history content equal the
|
|
75
|
+
* concatenation of its `text_delta` values, also when a barge-in, cancel or
|
|
76
|
+
* synthesis error arrives during the last sentence's synthesis. A barge-in or
|
|
77
|
+
* cancel stops the model stream and the synthesis in flight. If the reply's
|
|
78
|
+
* text was still incomplete then, the text received until then (spoken or not,
|
|
79
|
+
* so possibly text no `text_delta` carried) is committed to history and
|
|
80
|
+
* emitted as that reply's transcript before its `response_done`, matching the
|
|
81
|
+
* non-streaming path, which commits and transcribes the whole reply before
|
|
82
|
+
* speaking it. A reply cancelled while
|
|
83
|
+
* it still waits for earlier replies commits nothing and emits no transcript.
|
|
84
|
+
* Tool calls come from the stream's final `done` response and are relayed
|
|
85
|
+
* after the last sentence, under the same history rule as above. A model stream
|
|
86
|
+
* error stops speech after the sentence in flight, and a synthesis error stops
|
|
87
|
+
* it at once; either then commits and transcribes the text received if it was
|
|
88
|
+
* still incomplete (again possibly more than the deltas carried), and emits one
|
|
89
|
+
* `error` event. Usage comes from the stream's `done` chunk, kept whole only
|
|
90
|
+
* when usable (see `usableUsage`: at least one count or cost, each one present
|
|
91
|
+
* a finite number that is not negative) and otherwise dropped; a reply without usable usage (none, an
|
|
92
|
+
* empty `usage: {}`, `costUsd: NaN`, a negative count) is charged like a
|
|
93
|
+
* cancelled `generate()` (`interruptedLlmCostUsd`, else unknown cost). TTS
|
|
94
|
+
* characters are the sum of every sentence submitted, including an
|
|
95
|
+
* interrupted one.
|
|
96
|
+
*
|
|
54
97
|
* STT failure: when the speech-to-text stream ends without `close()` (for
|
|
55
98
|
* example the provider closes its socket with 1011) or throws, the session
|
|
56
99
|
* emits one `error` event with the fixed {@link PIPELINE_STT_CLOSED_MESSAGE}
|
|
@@ -76,10 +119,11 @@
|
|
|
76
119
|
* cancellation never settles. When governed voice closes the session instead
|
|
77
120
|
* (a limit is reached), held work is discarded without a model call.
|
|
78
121
|
*/
|
|
79
|
-
import { CostLimitExceededError } from './cost-budget.js';
|
|
122
|
+
import { CostLimitExceededError, isValidCostUsd } from './cost-budget.js';
|
|
80
123
|
import { applyEstimatedCost, estimateCostUsd, lookupModelPrice } from './model-pricing.js';
|
|
81
124
|
import { toolsToModelSchemas } from './model.js';
|
|
82
|
-
import {
|
|
125
|
+
import { cutSentence, splitSentences } from './voice-sentences.js';
|
|
126
|
+
import { CAPTURE_VOICE_CANCEL, HOLD_VOICE_CONTINUATIONS, captureVoiceCancel, failedVoiceResponses, stampVoiceInterruption } from './voice.js';
|
|
83
127
|
export class PipelineVoiceProvider {
|
|
84
128
|
name;
|
|
85
129
|
stt;
|
|
@@ -87,6 +131,7 @@ export class PipelineVoiceProvider {
|
|
|
87
131
|
llm;
|
|
88
132
|
model;
|
|
89
133
|
interruptedLlmCostUsd;
|
|
134
|
+
sentenceStreaming;
|
|
90
135
|
constructor(options) {
|
|
91
136
|
this.stt = options.stt;
|
|
92
137
|
this.tts = options.tts;
|
|
@@ -95,6 +140,7 @@ export class PipelineVoiceProvider {
|
|
|
95
140
|
if (options.interruptedLlmCostUsd !== undefined && (!Number.isFinite(options.interruptedLlmCostUsd) || options.interruptedLlmCostUsd <= 0))
|
|
96
141
|
throw new Error('interruptedLlmCostUsd must be a finite positive estimate');
|
|
97
142
|
this.interruptedLlmCostUsd = options.interruptedLlmCostUsd;
|
|
143
|
+
this.sentenceStreaming = options.sentenceStreaming === true;
|
|
98
144
|
this.name = options.name ?? `pipeline:${options.stt.name}+${options.tts.name}`;
|
|
99
145
|
}
|
|
100
146
|
async connect(requested = {}) {
|
|
@@ -119,13 +165,14 @@ export class PipelineVoiceProvider {
|
|
|
119
165
|
llm: this.llm,
|
|
120
166
|
model: this.model,
|
|
121
167
|
interruptedLlmCostUsd: this.interruptedLlmCostUsd,
|
|
168
|
+
sentenceStreaming: this.sentenceStreaming,
|
|
122
169
|
options,
|
|
123
170
|
});
|
|
124
171
|
}
|
|
125
172
|
}
|
|
126
173
|
/**
|
|
127
|
-
*
|
|
128
|
-
*
|
|
174
|
+
* Maximum time to wait for an interrupted reply's cancellation cleanup
|
|
175
|
+
* before emitting its `response_done` with the usage known so far.
|
|
129
176
|
* @internal Not exported from the package entry points.
|
|
130
177
|
*/
|
|
131
178
|
export const PIPELINE_TURN_SETTLE_MS = 2_000;
|
|
@@ -145,12 +192,59 @@ export const PIPELINE_MAX_PENDING_TURNS = 8;
|
|
|
145
192
|
* next final starts a new pending turn.
|
|
146
193
|
*/
|
|
147
194
|
const PIPELINE_MAX_PENDING_TURN_CHARS = 16_384;
|
|
195
|
+
/**
|
|
196
|
+
* Sentence streaming: a threshold, not a hard bound. After each model chunk,
|
|
197
|
+
* while more than this many characters of complete sentences wait for speech
|
|
198
|
+
* synthesis, the model stream is not read further; one large chunk is still
|
|
199
|
+
* queued whole.
|
|
200
|
+
* @internal Not exported from the package entry points.
|
|
201
|
+
*/
|
|
202
|
+
export const PIPELINE_MAX_BUFFERED_SPEECH_CHARS = 4_096;
|
|
203
|
+
/**
|
|
204
|
+
* Sentence streaming: most characters one `tts.synthesize()` call receives.
|
|
205
|
+
* A longer sentence, terminated or not, is cut at its last whitespace that
|
|
206
|
+
* fits (mid-word when a word alone is longer).
|
|
207
|
+
* @internal Not exported from the package entry points.
|
|
208
|
+
*/
|
|
209
|
+
export const PIPELINE_MAX_SENTENCE_CHARS = 1_000;
|
|
148
210
|
/**
|
|
149
211
|
* Fixed rejection / `error` message when a user turn arrives with
|
|
150
212
|
* {@link PIPELINE_MAX_PENDING_TURNS} turns already queued.
|
|
151
213
|
* @internal Not exported from the package entry points.
|
|
152
214
|
*/
|
|
153
215
|
export const PIPELINE_TURN_QUEUE_FULL_MESSAGE = 'Voice input queue is full; wait for the current reply';
|
|
216
|
+
/**
|
|
217
|
+
* Sentence streaming: the usage a stream's `done` chunk reported, when it is
|
|
218
|
+
* usable, else undefined, so the reply is charged as reporting no usage
|
|
219
|
+
* (`interruptedLlmCostUsd`, else unknown cost). Usable means at least one
|
|
220
|
+
* of the count and cost fields in {@link USAGE_NUMBER_FIELDS} is present, and
|
|
221
|
+
* each one present is a finite number that is not negative. Other fields
|
|
222
|
+
* (`attribution`, `costUnknown`, a provider's own metadata) are not validated.
|
|
223
|
+
* That rejects an empty `usage: {}` (an OpenAI-compatible server that ignores
|
|
224
|
+
* `stream_options.include_usage`), `costUsd: NaN`, an infinite or negative
|
|
225
|
+
* count, and a count or cost that is not a number. The object is copied first
|
|
226
|
+
* and the copy is what is checked and returned, so later changes to the
|
|
227
|
+
* provider's object do not reach accounting.
|
|
228
|
+
*/
|
|
229
|
+
const USAGE_NUMBER_FIELDS = [
|
|
230
|
+
'inputTokens', 'outputTokens', 'totalTokens', 'costUsd', 'cachedInputTokens', 'cacheWriteTokens',
|
|
231
|
+
'audioInputTokens', 'cachedAudioInputTokens', 'audioOutputTokens', 'sttSeconds', 'ttsCharacters',
|
|
232
|
+
];
|
|
233
|
+
function usableUsage(usage) {
|
|
234
|
+
if (!usage || typeof usage !== 'object')
|
|
235
|
+
return undefined;
|
|
236
|
+
let numbers = 0;
|
|
237
|
+
const copy = { ...usage };
|
|
238
|
+
for (const field of USAGE_NUMBER_FIELDS) {
|
|
239
|
+
const value = copy[field];
|
|
240
|
+
if (value === undefined)
|
|
241
|
+
continue;
|
|
242
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value < 0)
|
|
243
|
+
return undefined;
|
|
244
|
+
numbers++;
|
|
245
|
+
}
|
|
246
|
+
return numbers > 0 ? copy : undefined;
|
|
247
|
+
}
|
|
154
248
|
class PipelineVoiceSession {
|
|
155
249
|
stt;
|
|
156
250
|
sttProviderName;
|
|
@@ -158,6 +252,7 @@ class PipelineVoiceSession {
|
|
|
158
252
|
llm;
|
|
159
253
|
modelId;
|
|
160
254
|
interruptedLlmCostUsd;
|
|
255
|
+
sentenceStreaming;
|
|
161
256
|
tools;
|
|
162
257
|
instructions;
|
|
163
258
|
costBudget;
|
|
@@ -200,6 +295,7 @@ class PipelineVoiceSession {
|
|
|
200
295
|
this.llm = init.llm;
|
|
201
296
|
this.modelId = init.model;
|
|
202
297
|
this.interruptedLlmCostUsd = init.interruptedLlmCostUsd;
|
|
298
|
+
this.sentenceStreaming = init.sentenceStreaming;
|
|
203
299
|
this.tools = init.options.tools ?? [];
|
|
204
300
|
this.instructions = init.options.instructions;
|
|
205
301
|
this.costBudget = init.options.costBudget;
|
|
@@ -342,6 +438,9 @@ class PipelineVoiceSession {
|
|
|
342
438
|
turn.abort.abort();
|
|
343
439
|
if (this.currentTurn !== turn)
|
|
344
440
|
return;
|
|
441
|
+
// Sentence streaming: record the text received so far (one transcript,
|
|
442
|
+
// before this reply's response_done) ahead of any queued turn below.
|
|
443
|
+
turn.onCancel?.();
|
|
345
444
|
this.currentTurn = undefined;
|
|
346
445
|
if (this.state !== 'await_tool')
|
|
347
446
|
this.state = 'listening';
|
|
@@ -350,11 +449,12 @@ class PipelineVoiceSession {
|
|
|
350
449
|
// on TTS cleanup a provider may never finish.
|
|
351
450
|
if (turn.holdsBudget)
|
|
352
451
|
void this.finishTurn(turn);
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
this.
|
|
452
|
+
else {
|
|
453
|
+
// Governed voice holds the next turn until the wrapper accounts for any usage.
|
|
454
|
+
if (this.externalSettlement)
|
|
455
|
+
this.holdBudget(turn);
|
|
456
|
+
this.scheduleCancelledTurnSettlement(turn);
|
|
457
|
+
}
|
|
358
458
|
// Queued input survives the barge-in. Start it now rather than after the
|
|
359
459
|
// cancelled reply's cleanup; its events still wait for that reply's
|
|
360
460
|
// response_done (bounded by the settle timeout). A budget check in flight
|
|
@@ -479,12 +579,17 @@ class PipelineVoiceSession {
|
|
|
479
579
|
this.lastTurn = turn;
|
|
480
580
|
const abort = turn.abort;
|
|
481
581
|
try {
|
|
482
|
-
const
|
|
582
|
+
const request = {
|
|
483
583
|
model: this.modelId,
|
|
484
584
|
messages: this.messages,
|
|
485
585
|
...(this.tools.length > 0 ? { tools: toolsToModelSchemas(this.tools) } : {}),
|
|
486
586
|
signal: abort.signal,
|
|
487
|
-
}
|
|
587
|
+
};
|
|
588
|
+
if (this.sentenceStreaming && typeof this.llm.stream === 'function') {
|
|
589
|
+
await this.runStreamingReply(turn, request);
|
|
590
|
+
return;
|
|
591
|
+
}
|
|
592
|
+
const response = await this.llm.generate(request);
|
|
488
593
|
turn.llmUsage = response.usage;
|
|
489
594
|
// Before anything can yield to a consumer (tool_call, transcript), hold
|
|
490
595
|
// every turn start and continuation until this reply's budget check settles.
|
|
@@ -519,30 +624,20 @@ class PipelineVoiceSession {
|
|
|
519
624
|
}
|
|
520
625
|
if (abort.signal.aborted || this.closed)
|
|
521
626
|
return;
|
|
522
|
-
|
|
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] });
|
|
530
|
-
this.pendingToolCalls = [...toolCalls];
|
|
531
|
-
this.state = 'await_tool';
|
|
532
|
-
for (const call of toolCalls) {
|
|
533
|
-
this.push({ type: 'tool_call', id: call.id, name: call.name, input: call.input });
|
|
534
|
-
}
|
|
535
|
-
}
|
|
536
|
-
else {
|
|
537
|
-
this.state = 'listening';
|
|
538
|
-
}
|
|
627
|
+
this.relayToolCalls(committed, toolCalls);
|
|
539
628
|
}
|
|
540
629
|
catch (err) {
|
|
541
630
|
this.holdBudget(turn);
|
|
542
631
|
if (abort.signal.aborted)
|
|
543
632
|
return;
|
|
544
|
-
|
|
545
|
-
|
|
633
|
+
if (this.externalSettlement) {
|
|
634
|
+
// Send one terminal completion so governance can account the failed reply.
|
|
635
|
+
turn.failed = true;
|
|
636
|
+
}
|
|
637
|
+
else {
|
|
638
|
+
await this.afterPrevious(turn);
|
|
639
|
+
this.push({ type: 'error', message: err.message });
|
|
640
|
+
}
|
|
546
641
|
if (this.currentTurn === turn)
|
|
547
642
|
this.state = 'listening';
|
|
548
643
|
}
|
|
@@ -556,6 +651,254 @@ class PipelineVoiceSession {
|
|
|
556
651
|
this.startNextTurn();
|
|
557
652
|
}
|
|
558
653
|
}
|
|
654
|
+
/** Tool-call relay: emit and pause until results submitted. */
|
|
655
|
+
relayToolCalls(committed, toolCalls) {
|
|
656
|
+
if (toolCalls.length > 0) {
|
|
657
|
+
// Commit exactly the calls relayed, so every one is answered by the
|
|
658
|
+
// tool result the caller submits for it.
|
|
659
|
+
if (committed)
|
|
660
|
+
committed.toolCalls = [...toolCalls];
|
|
661
|
+
else
|
|
662
|
+
this.messages.push({ role: 'assistant', content: '', toolCalls: [...toolCalls] });
|
|
663
|
+
this.pendingToolCalls = [...toolCalls];
|
|
664
|
+
this.state = 'await_tool';
|
|
665
|
+
for (const call of toolCalls) {
|
|
666
|
+
this.push({ type: 'tool_call', id: call.id, name: call.name, input: call.input });
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
else {
|
|
670
|
+
this.state = 'listening';
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
/**
|
|
674
|
+
* Sentence streaming: read the model stream and speak each sentence as it
|
|
675
|
+
* completes. A reader task reads the stream into a sentence queue while this
|
|
676
|
+
* method speaks the queue in order, so speech synthesis does not stall the
|
|
677
|
+
* model read; the reader pauses between chunks while more than
|
|
678
|
+
* {@link PIPELINE_MAX_BUFFERED_SPEECH_CHARS} are waiting.
|
|
679
|
+
*
|
|
680
|
+
* One controller, scoped to this reply, bounds the model request: the
|
|
681
|
+
* provider's `ModelRequest.signal` is its signal and the reader stops on it.
|
|
682
|
+
* It is aborted when the turn is cancelled (the turn listener below; `close()`
|
|
683
|
+
* cancels the turn in flight) and in this method's `finally`, so the request
|
|
684
|
+
* signal is aborted once this method has returned or thrown, whatever the
|
|
685
|
+
* reason. The turn's own controller is not aborted here: a synthesis failure
|
|
686
|
+
* is not a cancel, and runLlmTurn and finishTurn read it to decide the
|
|
687
|
+
* `error` event and the charge.
|
|
688
|
+
*
|
|
689
|
+
* Throws the stream's (or synthesis's) error after recording the text
|
|
690
|
+
* received before it.
|
|
691
|
+
*/
|
|
692
|
+
async runStreamingReply(turn, request) {
|
|
693
|
+
const signal = turn.abort.signal;
|
|
694
|
+
const scope = new AbortController();
|
|
695
|
+
const replySignal = scope.signal;
|
|
696
|
+
const halted = () => replySignal.aborted;
|
|
697
|
+
const reply = {
|
|
698
|
+
/** Assistant text received from the model so far. */
|
|
699
|
+
received: '',
|
|
700
|
+
/** Concatenation of the text_delta events emitted so far. */
|
|
701
|
+
emitted: '',
|
|
702
|
+
/** The stream's final response, once its `done` chunk arrived; its usage is on the turn (see usableUsage). */
|
|
703
|
+
response: undefined,
|
|
704
|
+
/** Complete sentences not yet spoken, oldest first, and their total length. */
|
|
705
|
+
queue: [],
|
|
706
|
+
queuedChars: 0,
|
|
707
|
+
readerEnded: false,
|
|
708
|
+
/** The stream ended normally. */
|
|
709
|
+
complete: false,
|
|
710
|
+
failure: undefined,
|
|
711
|
+
/** Events may be emitted: earlier replies are done and the budget latch is held. */
|
|
712
|
+
emitting: false,
|
|
713
|
+
settled: false,
|
|
714
|
+
committed: undefined,
|
|
715
|
+
};
|
|
716
|
+
// One promise both loops wait on; replaced each time the reply's state changes.
|
|
717
|
+
let wake;
|
|
718
|
+
let changed = new Promise(resolve => { wake = resolve; });
|
|
719
|
+
const notify = () => {
|
|
720
|
+
const resolve = wake;
|
|
721
|
+
changed = new Promise(next => { wake = next; });
|
|
722
|
+
resolve();
|
|
723
|
+
};
|
|
724
|
+
const onTurnAbort = () => scope.abort();
|
|
725
|
+
// Whatever aborts the scope also detaches it from the turn and wakes both loops.
|
|
726
|
+
replySignal.addEventListener('abort', () => { signal.removeEventListener('abort', onTurnAbort); notify(); }, { once: true });
|
|
727
|
+
if (signal.aborted)
|
|
728
|
+
scope.abort();
|
|
729
|
+
else
|
|
730
|
+
signal.addEventListener('abort', onTurnAbort, { once: true });
|
|
731
|
+
// Until the stream's done chunk delivers usable usage, the reply is charged as reporting none.
|
|
732
|
+
turn.usageMissing = true;
|
|
733
|
+
// Record the reply's text once: the history message (without tool calls,
|
|
734
|
+
// which join only when relayed) and the one assistant transcript. Once the
|
|
735
|
+
// stream has ended and the queue is empty, every sentence has been emitted
|
|
736
|
+
// and the text recorded is what the text_delta events carried, whether this
|
|
737
|
+
// runs after the last text_delta or on a cancel or synthesis failure during
|
|
738
|
+
// the last sentence's synthesis. A reply cancelled or failed while its text
|
|
739
|
+
// was still incomplete records all the text received until then, emitted or
|
|
740
|
+
// not.
|
|
741
|
+
const settleText = () => {
|
|
742
|
+
if (!reply.emitting || reply.settled)
|
|
743
|
+
return;
|
|
744
|
+
reply.settled = true;
|
|
745
|
+
const text = reply.complete && reply.queue.length === 0 ? reply.emitted : reply.received;
|
|
746
|
+
const message = reply.response?.message;
|
|
747
|
+
if (message || text) {
|
|
748
|
+
const { toolCalls: _unexposed, ...spoken } = message ?? { role: 'assistant', content: '' };
|
|
749
|
+
reply.committed = { ...spoken, content: text };
|
|
750
|
+
this.messages.push(reply.committed);
|
|
751
|
+
}
|
|
752
|
+
if (text)
|
|
753
|
+
this.push({ type: 'transcript', text, role: 'assistant' });
|
|
754
|
+
};
|
|
755
|
+
turn.onCancel = settleText;
|
|
756
|
+
const recordFailure = (error) => {
|
|
757
|
+
// A rejection after the scope aborts belongs to the cancellation.
|
|
758
|
+
if (halted())
|
|
759
|
+
return;
|
|
760
|
+
reply.failure ??= { error };
|
|
761
|
+
// A barge-in can finish the reply while synthesis is still unwinding.
|
|
762
|
+
if (this.externalSettlement)
|
|
763
|
+
turn.failed = true;
|
|
764
|
+
};
|
|
765
|
+
const enqueue = (sentences) => {
|
|
766
|
+
const pieces = sentences.flatMap(sentence => cutSentence(sentence, PIPELINE_MAX_SENTENCE_CHARS));
|
|
767
|
+
for (const piece of pieces) {
|
|
768
|
+
reply.queue.push(piece);
|
|
769
|
+
reply.queuedChars += piece.length;
|
|
770
|
+
}
|
|
771
|
+
if (pieces.length > 0)
|
|
772
|
+
notify();
|
|
773
|
+
};
|
|
774
|
+
void (async () => {
|
|
775
|
+
let iterator;
|
|
776
|
+
/** Set once next() has reported done or rejected: the iterator has finished. */
|
|
777
|
+
let iteratorFinished = false;
|
|
778
|
+
// One pull, abandoned (without leaving a listener behind) when the reply scope aborts.
|
|
779
|
+
const pull = (it) => new Promise((resolve, reject) => {
|
|
780
|
+
const onStop = () => resolve('stopped');
|
|
781
|
+
replySignal.addEventListener('abort', onStop, { once: true });
|
|
782
|
+
it.next().then(result => { if (result.done)
|
|
783
|
+
iteratorFinished = true; replySignal.removeEventListener('abort', onStop); resolve(result); }, error => { iteratorFinished = true; replySignal.removeEventListener('abort', onStop); reject(error); });
|
|
784
|
+
});
|
|
785
|
+
let pending = '';
|
|
786
|
+
try {
|
|
787
|
+
const stream = this.llm.stream.call(this.llm, { ...request, signal: replySignal });
|
|
788
|
+
iterator = stream[Symbol.asyncIterator]();
|
|
789
|
+
while (!halted()) {
|
|
790
|
+
const next = await pull(iterator);
|
|
791
|
+
if (next === 'stopped' || halted())
|
|
792
|
+
return;
|
|
793
|
+
if (next.done)
|
|
794
|
+
break;
|
|
795
|
+
const chunk = next.value;
|
|
796
|
+
if (chunk.done) {
|
|
797
|
+
// The one point usage is taken from the stream: kept whole when
|
|
798
|
+
// usable, otherwise dropped here so nothing later reads it.
|
|
799
|
+
const { usage, ...response } = chunk.done;
|
|
800
|
+
reply.response = response;
|
|
801
|
+
turn.llmUsage = usableUsage(usage);
|
|
802
|
+
turn.usageMissing = turn.llmUsage === undefined;
|
|
803
|
+
}
|
|
804
|
+
if (!chunk.textDelta)
|
|
805
|
+
continue;
|
|
806
|
+
reply.received += chunk.textDelta;
|
|
807
|
+
const split = splitSentences(pending + chunk.textDelta, false);
|
|
808
|
+
pending = split.rest;
|
|
809
|
+
enqueue(split.sentences);
|
|
810
|
+
// Text without a sentence boundary is spoken in pieces once it outgrows a sentence.
|
|
811
|
+
if (pending.length > PIPELINE_MAX_SENTENCE_CHARS) {
|
|
812
|
+
const pieces = cutSentence(pending, PIPELINE_MAX_SENTENCE_CHARS);
|
|
813
|
+
if (pieces.length > 1) {
|
|
814
|
+
pending = pieces.pop() ?? '';
|
|
815
|
+
enqueue(pieces);
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
while (reply.queuedChars > PIPELINE_MAX_BUFFERED_SPEECH_CHARS && !halted())
|
|
819
|
+
await changed;
|
|
820
|
+
}
|
|
821
|
+
if (!iteratorFinished)
|
|
822
|
+
return;
|
|
823
|
+
// A provider that streams no text deltas still reports the text on `done`.
|
|
824
|
+
const finalText = reply.response?.message?.content;
|
|
825
|
+
if (!reply.received && finalText) {
|
|
826
|
+
reply.received = finalText;
|
|
827
|
+
pending = finalText;
|
|
828
|
+
}
|
|
829
|
+
enqueue(splitSentences(pending, true).sentences);
|
|
830
|
+
reply.complete = true;
|
|
831
|
+
}
|
|
832
|
+
catch (error) {
|
|
833
|
+
recordFailure(error);
|
|
834
|
+
}
|
|
835
|
+
finally {
|
|
836
|
+
// Iterator convention: return() once when abandoning an iterator that has
|
|
837
|
+
// not finished; not after next() reported done or rejected. An async
|
|
838
|
+
// generator runs return() only after its pending read settles; the
|
|
839
|
+
// request signal, aborted by now, lets a provider that honors it settle
|
|
840
|
+
// that read.
|
|
841
|
+
if (iterator && !iteratorFinished) {
|
|
842
|
+
try {
|
|
843
|
+
Promise.resolve(iterator.return?.()).catch(() => { });
|
|
844
|
+
}
|
|
845
|
+
catch { /* a throwing return() */ }
|
|
846
|
+
}
|
|
847
|
+
reply.readerEnded = true;
|
|
848
|
+
notify();
|
|
849
|
+
}
|
|
850
|
+
})();
|
|
851
|
+
try {
|
|
852
|
+
// Emit nothing until every earlier reply has emitted response_done; the
|
|
853
|
+
// model stream is read meanwhile.
|
|
854
|
+
await this.afterPrevious(turn);
|
|
855
|
+
if (halted())
|
|
856
|
+
return;
|
|
857
|
+
// Before the first event can reach a consumer, hold every turn start and
|
|
858
|
+
// continuation until this reply's budget check settles.
|
|
859
|
+
this.holdBudget(turn);
|
|
860
|
+
reply.emitting = true;
|
|
861
|
+
while (!reply.failure) {
|
|
862
|
+
if (halted())
|
|
863
|
+
return;
|
|
864
|
+
const sentence = reply.queue.shift();
|
|
865
|
+
if (sentence === undefined) {
|
|
866
|
+
if (reply.readerEnded)
|
|
867
|
+
break;
|
|
868
|
+
await changed;
|
|
869
|
+
continue;
|
|
870
|
+
}
|
|
871
|
+
reply.queuedChars -= sentence.length;
|
|
872
|
+
notify();
|
|
873
|
+
const spoken = sentence.trim();
|
|
874
|
+
this.state = 'speaking';
|
|
875
|
+
this.push({ type: 'text_delta', delta: sentence, role: 'assistant' });
|
|
876
|
+
reply.emitted += sentence;
|
|
877
|
+
// The transcript follows the last text_delta, as soon as the text is complete.
|
|
878
|
+
if (reply.complete && reply.queue.length === 0)
|
|
879
|
+
settleText();
|
|
880
|
+
turn.ttsCharacters += spoken.length;
|
|
881
|
+
await this.streamTts(spoken, signal);
|
|
882
|
+
}
|
|
883
|
+
if (halted())
|
|
884
|
+
return;
|
|
885
|
+
settleText();
|
|
886
|
+
if (reply.failure)
|
|
887
|
+
throw reply.failure.error;
|
|
888
|
+
const response = reply.response;
|
|
889
|
+
this.relayToolCalls(reply.committed, response?.toolCalls ?? response?.message?.toolCalls ?? []);
|
|
890
|
+
}
|
|
891
|
+
catch (error) {
|
|
892
|
+
// A synthesis failure records the reply's text like a model stream failure.
|
|
893
|
+
recordFailure(error);
|
|
894
|
+
if (!halted())
|
|
895
|
+
settleText();
|
|
896
|
+
throw error;
|
|
897
|
+
}
|
|
898
|
+
finally {
|
|
899
|
+
scope.abort();
|
|
900
|
+
}
|
|
901
|
+
}
|
|
559
902
|
/**
|
|
560
903
|
* Wait, at most {@link PIPELINE_TURN_SETTLE_MS}, for the previous reply to
|
|
561
904
|
* emit its `response_done`; past the bound, emit it on that reply's behalf
|
|
@@ -597,7 +940,7 @@ class PipelineVoiceSession {
|
|
|
597
940
|
void this.finishTurn(turn.previous);
|
|
598
941
|
turn.previous = undefined;
|
|
599
942
|
let llmUsage = turn.llmUsage;
|
|
600
|
-
if (turn.abort.signal.aborted && this.interruptedLlmCostUsd !== undefined) {
|
|
943
|
+
if ((turn.abort.signal.aborted || turn.usageMissing) && this.interruptedLlmCostUsd !== undefined) {
|
|
601
944
|
llmUsage = { ...llmUsage };
|
|
602
945
|
applyEstimatedCost(this.modelKey(), llmUsage);
|
|
603
946
|
if (llmUsage.costUsd === undefined)
|
|
@@ -607,7 +950,10 @@ class PipelineVoiceSession {
|
|
|
607
950
|
// Before the event can reach the wrapper, so its settle always has a hold to release.
|
|
608
951
|
if (this.externalSettlement && !this.closed)
|
|
609
952
|
this.externalSettling++;
|
|
610
|
-
|
|
953
|
+
const done = { type: 'response_done', ...(usage ? { usage } : {}) };
|
|
954
|
+
if (turn.failed)
|
|
955
|
+
failedVoiceResponses.add(done);
|
|
956
|
+
this.push(done);
|
|
611
957
|
if (this.lastTurn === turn)
|
|
612
958
|
this.lastTurn = undefined;
|
|
613
959
|
turn.markResponseDone();
|
|
@@ -616,7 +962,7 @@ class PipelineVoiceSession {
|
|
|
616
962
|
}
|
|
617
963
|
/**
|
|
618
964
|
* Take the budget latch for a reply whose model call just settled, unless
|
|
619
|
-
* its
|
|
965
|
+
* its response_done was already emitted.
|
|
620
966
|
* Synchronous, so no consumer reaction can start a model call in between.
|
|
621
967
|
*/
|
|
622
968
|
holdBudget(turn) {
|
|
@@ -625,15 +971,10 @@ class PipelineVoiceSession {
|
|
|
625
971
|
turn.holdsBudget = true;
|
|
626
972
|
this.budgetSettling++;
|
|
627
973
|
}
|
|
628
|
-
/**
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
* {@link PIPELINE_TURN_SETTLE_MS}) has been settled by the wrapper.
|
|
632
|
-
*/
|
|
633
|
-
holdCancelledTurn(turn) {
|
|
634
|
-
if (turn.finished)
|
|
974
|
+
/** Emit `response_done` if cancelled provider work fails to finish within the settle bound. */
|
|
975
|
+
scheduleCancelledTurnSettlement(turn) {
|
|
976
|
+
if (this.closed || turn.finished)
|
|
635
977
|
return;
|
|
636
|
-
this.holdBudget(turn);
|
|
637
978
|
const timer = setTimeout(() => { if (!this.closed)
|
|
638
979
|
void this.finishTurn(turn); }, PIPELINE_TURN_SETTLE_MS);
|
|
639
980
|
const clear = () => { clearTimeout(timer); this.closedSignal.signal.removeEventListener('abort', clear); };
|
|
@@ -654,13 +995,14 @@ class PipelineVoiceSession {
|
|
|
654
995
|
if (!held)
|
|
655
996
|
this.budgetSettling++;
|
|
656
997
|
try {
|
|
657
|
-
|
|
998
|
+
const cost = usage?.costUsd;
|
|
999
|
+
if (!isValidCostUsd(cost)) {
|
|
658
1000
|
this.push({ type: 'error', message: 'Voice cost is unknown; stopping budgeted session' });
|
|
659
1001
|
await this.close();
|
|
660
1002
|
return;
|
|
661
1003
|
}
|
|
662
1004
|
try {
|
|
663
|
-
await this.handleCostBudget(
|
|
1005
|
+
await this.handleCostBudget(cost);
|
|
664
1006
|
}
|
|
665
1007
|
catch {
|
|
666
1008
|
this.push({ type: 'error', message: 'Voice cost accounting failed' });
|