@vellumai/assistant 0.12.0-dev.202609111617.f60422f → 0.12.0-dev.202609111819.3dcbf21

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.
Files changed (28) hide show
  1. package/ARCHITECTURE.md +1 -1
  2. package/package.json +1 -1
  3. package/src/__tests__/config-schema.test.ts +12 -6
  4. package/src/calls/__tests__/call-controller.test.ts +106 -0
  5. package/src/calls/__tests__/media-stream-output.test.ts +32 -0
  6. package/src/{live-voice → calls}/__tests__/progress-narration.test.ts +4 -4
  7. package/src/{live-voice → calls}/__tests__/progress-phrases.test.ts +1 -1
  8. package/src/calls/__tests__/voice-leg-coordinator.test.ts +229 -0
  9. package/src/calls/__tests__/voice-progress-cadence.test.ts +274 -0
  10. package/src/calls/call-controller.ts +190 -113
  11. package/src/calls/call-transport.ts +16 -0
  12. package/src/calls/media-stream-output.ts +32 -0
  13. package/src/{live-voice → calls}/progress-narration.ts +2 -2
  14. package/src/calls/voice-leg-coordinator.ts +189 -0
  15. package/src/calls/voice-progress-cadence.ts +423 -0
  16. package/src/config/default-profile-catalog.ts +1 -1
  17. package/src/config/schema.ts +2 -0
  18. package/src/config/schemas/__tests__/live-voice.test.ts +0 -134
  19. package/src/config/schemas/__tests__/voice.test.ts +148 -0
  20. package/src/config/schemas/live-voice.ts +1 -153
  21. package/src/config/schemas/voice.ts +150 -0
  22. package/src/live-voice/__tests__/live-voice-progress.test.ts +15 -15
  23. package/src/live-voice/__tests__/live-voice-vad.test.ts +2 -2
  24. package/src/live-voice/live-voice-session.ts +178 -521
  25. package/src/workspace/migrations/155-move-front-model-config-to-voice.ts +78 -0
  26. package/src/workspace/migrations/__tests__/155-move-front-model-config-to-voice.test.ts +102 -0
  27. package/src/workspace/migrations/registry.ts +2 -0
  28. /package/src/{live-voice → calls}/progress-phrases.ts +0 -0
@@ -5,12 +5,29 @@ import {
5
5
  MediaTurnDetector,
6
6
  type TurnDetectorConfig,
7
7
  } from "../calls/media-turn-detector.js";
8
+ import {
9
+ createVoiceProgressNarrator,
10
+ type VoiceProgressNarrator,
11
+ } from "../calls/progress-narration.js";
12
+ import {
13
+ APPROVAL_PENDING_PHRASE_BY_LANGUAGE,
14
+ approvalPendingPhraseFor,
15
+ } from "../calls/progress-phrases.js";
8
16
  import {
9
17
  SPOKEN_REPLY_LENGTH_RULE,
10
18
  SPOKEN_REPLY_PLAIN_TEXT_RULE,
11
19
  } from "../calls/spoken-reply-rules.js";
12
20
  import { sanitizeForTts } from "../calls/tts-text-sanitizer.js";
13
21
  import { createControlMarkerHoldback } from "../calls/voice-control-protocol.js";
22
+ import {
23
+ createFrontDoorLegCoordinator,
24
+ type FrontDoorLegCoordinator,
25
+ type SpokenEscalationBridge,
26
+ } from "../calls/voice-leg-coordinator.js";
27
+ import {
28
+ createProgressCadence,
29
+ type ProgressCadence,
30
+ } from "../calls/voice-progress-cadence.js";
14
31
  import type {
15
32
  VoiceTurnHandle,
16
33
  VoiceTurnOptions,
@@ -20,19 +37,16 @@ import {
20
37
  resolveProcessingWaitMs,
21
38
  waitForPriorTurnTeardown,
22
39
  } from "../calls/voice-session-bridge.js";
23
- import {
24
- createFrontDoorVerdictMachine,
25
- ESCALATION_CONTINUATION_CONTENT,
26
- resolveSpokenEscalationBridge,
27
- type VoiceRoutingLeg,
28
- } from "../calls/voice-triage-escalate.js";
40
+ import { type VoiceRoutingLeg } from "../calls/voice-triage-escalate.js";
29
41
  import { getConfig } from "../config/loader.js";
30
42
  import {
31
43
  type LiveVoiceFluxConfig,
32
44
  LiveVoiceFluxConfigSchema,
33
- type LiveVoiceFrontModelConfig,
34
- LiveVoiceFrontModelConfigSchema,
35
45
  } from "../config/schemas/live-voice.js";
46
+ import {
47
+ type VoiceFrontModelConfig,
48
+ VoiceFrontModelConfigSchema,
49
+ } from "../config/schemas/voice.js";
36
50
  import { ABORT_WATCHDOG_MS } from "../daemon/abort-watchdog.js";
37
51
  import { isRefusedInReadOnlyPass } from "../daemon/conversation-tool-setup.js";
38
52
  import type { TrustContext } from "../daemon/trust-context-types.js";
@@ -128,17 +142,6 @@ import type {
128
142
  LiveVoiceTtsOptions,
129
143
  LiveVoiceTtsResult,
130
144
  } from "./live-voice-tts.js";
131
- import {
132
- createVoiceProgressNarrator,
133
- type VoiceProgressNarrator,
134
- type VoiceProgressTextInput,
135
- } from "./progress-narration.js";
136
- import {
137
- APPROVAL_PENDING_PHRASE_BY_LANGUAGE,
138
- approvalPendingPhraseFor,
139
- pickProgressPhrase,
140
- PROGRESS_FALLBACK_PHRASES_BY_LANGUAGE,
141
- } from "./progress-phrases.js";
142
145
  import {
143
146
  type LiveVoiceClientAttachFrameFrame,
144
147
  type LiveVoiceClientAttachImageFrame,
@@ -399,11 +402,11 @@ export interface LiveVoiceSessionOptions {
399
402
  finalizeGraceMs?: number;
400
403
  /**
401
404
  * Voice front-door endpointing and progress narration tuning. The
402
- * production factory seeds this from `liveVoice.frontModel` config when
405
+ * production factory seeds this from `voice.frontModel` config when
403
406
  * unset; absent fields fall back to the schema defaults (the constructor
404
407
  * schema-parses the partial into a complete config).
405
408
  */
406
- frontModelConfig?: Partial<LiveVoiceFrontModelConfig>;
409
+ frontModelConfig?: Partial<VoiceFrontModelConfig>;
407
410
  /**
408
411
  * Deepgram Flux turn-detection tuning. The production factory seeds this
409
412
  * from `liveVoice.flux` config when unset; absent fields fall back to the
@@ -413,7 +416,7 @@ export interface LiveVoiceSessionOptions {
413
416
  fluxConfig?: Partial<LiveVoiceFluxConfig>;
414
417
  /**
415
418
  * Progress narration service. The production factory constructs it from
416
- * `liveVoice.frontModel.progress` config when unset. `null` disables
419
+ * `voice.frontModel.progress` config when unset. `null` disables
417
420
  * generated narration, so progress updates use their static fallback.
418
421
  */
419
422
  progressNarrator?: VoiceProgressNarrator | null;
@@ -596,70 +599,6 @@ interface TtsSegmentJob {
596
599
  frames: Promise<void>;
597
600
  }
598
601
 
599
- // One tool operation observed on a turn, fed by the bridge's structured tool
600
- // callbacks. `completedAtMs`/`isError`/`resultPreview` land with tool_result.
601
- interface TurnProgressOp {
602
- toolName: string;
603
- toolUseId?: string;
604
- startedAtMs: number;
605
- completedAtMs?: number;
606
- isError?: boolean;
607
- resultPreview?: string;
608
- }
609
-
610
- // Per-turn tool-activity log and narration cadence state for spoken progress
611
- // updates (liveVoice.frontModel.progress).
612
- interface TurnProgressState {
613
- // Tool operations this turn, in start order.
614
- ops: TurnProgressOp[];
615
- // Ops accumulated toward the next ops-triggered narration. Counted once per
616
- // op, on start (not completion), so a burst of slow tools still trips the
617
- // threshold while they run.
618
- opsSinceNarration: number;
619
- // Bumped by every observable change to the turn's tool activity — an op
620
- // starting or finishing. The idle trigger compares it against
621
- // `narratedEpoch` so a tick with nothing new to report stays silent.
622
- stateEpoch: number;
623
- // The `stateEpoch` the last spoken narration described: the activity the
624
- // user has already been told about.
625
- narratedEpoch: number;
626
- // Narrations actually spoken this turn — the metrics count and the
627
- // decider's 1-based updateIndex. Rate, not count, bounds narration:
628
- // idleIntervalMs/minGapMs cap the cadence and the session duration cap
629
- // bounds the turn.
630
- updatesSpoken: number;
631
- // When the last spoken floor-holder (ack or narration) enqueued — gates the
632
- // progress.minGapMs spacing guard. Null until something speaks.
633
- lastFloorHolderAtMs: number | null;
634
- // When the turn's last TTS segment finished emitting (turn launch until
635
- // anything speaks). Together with the session-level playback-tail estimate
636
- // this anchors the dead-air countdown: idle time is measured from when the
637
- // user last heard something, not from when the turn started.
638
- lastAudibleAtMs: number;
639
- // Self-re-arming dead-air narration timer; null once cleared or fired.
640
- idleTimer: ReturnType<typeof setTimeout> | null;
641
- // A narration generation is awaiting the decider; serializes narrations.
642
- narrationInFlight: boolean;
643
- }
644
-
645
- // Newest incomplete op, optionally restricted to a tool name (the
646
- // tool_result fallback match when no toolUseId correlates).
647
- function findLastIncompleteOp(
648
- ops: TurnProgressOp[],
649
- toolName?: string,
650
- ): TurnProgressOp | undefined {
651
- for (let i = ops.length - 1; i >= 0; i -= 1) {
652
- const op = ops[i];
653
- if (
654
- op.completedAtMs === undefined &&
655
- (toolName === undefined || op.toolName === toolName)
656
- ) {
657
- return op;
658
- }
659
- }
660
- return undefined;
661
- }
662
-
663
602
  interface ActiveAssistantTurn {
664
603
  token: symbol;
665
604
  turnId: string;
@@ -675,7 +614,9 @@ interface ActiveAssistantTurn {
675
614
  handle: VoiceTurnHandle | null;
676
615
  // When the turn launched, for narration's turnElapsedMs.
677
616
  launchedAtMs: number;
678
- progress: TurnProgressState;
617
+ // Tool-activity log and spoken progress narration for the turn
618
+ // (voice.frontModel.progress), shared with the phone driver.
619
+ progress: ProgressCadence;
679
620
  assistantCompleted: boolean;
680
621
  ttsDone: boolean;
681
622
  // Latched when the turn puts something on screen (a ui tool ran); consumed
@@ -795,7 +736,9 @@ interface ActiveAssistantTurn {
795
736
  // Guards the
796
737
  // front-door leg's trailing completion from finalizing the turn, and makes
797
738
  // the hand-off idempotent.
798
- escalationHandedOff: boolean;
739
+ // The front-door leg's coordinator: whether it handed the turn off to the
740
+ // escalated leg. Null until the front-door leg starts.
741
+ frontDoor: FrontDoorLegCoordinator | null;
799
742
  ttsBuffer: string;
800
743
  // What the caller actually hears this turn, summed over the model's own
801
744
  // segments (acks and progress narration do not count). Logged at tts_done
@@ -1343,9 +1286,9 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
1343
1286
  // never emits an answer.
1344
1287
  private readonly progressNarrator: VoiceProgressNarrator | null;
1345
1288
  // Complete front-model tunables: the constructor schema-parses the partial
1346
- // option once, so every field carries its `liveVoice.frontModel` schema
1289
+ // option once, so every field carries its `voice.frontModel` schema
1347
1290
  // default when unset.
1348
- private readonly frontModelConfig: LiveVoiceFrontModelConfig;
1291
+ private readonly frontModelConfig: VoiceFrontModelConfig;
1349
1292
  // Complete Flux tunables (the constructor schema-parses the partial option
1350
1293
  // once, so every field carries its `liveVoice.flux` schema default).
1351
1294
  private readonly fluxConfig: LiveVoiceFluxConfig;
@@ -1445,7 +1388,7 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
1445
1388
  options.echoDrainSlackMs ?? DEFAULT_ECHO_DRAIN_SLACK_MS;
1446
1389
  this.finalizeGraceMs = options.finalizeGraceMs ?? FINALIZE_GRACE_MS;
1447
1390
  this.progressNarrator = options.progressNarrator ?? null;
1448
- this.frontModelConfig = LiveVoiceFrontModelConfigSchema.parse(
1391
+ this.frontModelConfig = VoiceFrontModelConfigSchema.parse(
1449
1392
  options.frontModelConfig ?? {},
1450
1393
  );
1451
1394
  this.fluxConfig = LiveVoiceFluxConfigSchema.parse(options.fluxConfig ?? {});
@@ -3504,11 +3447,15 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
3504
3447
  // down. One line, not narration: the turn is not working, it is waiting,
3505
3448
  // and it says which, in the turn's spoken language, like every other
3506
3449
  // filler phrase.
3507
- this.enqueueFillerPhrase(
3508
- turn,
3509
- approvalPendingPhraseFor(turn.language),
3510
- this.fixedPhraseLanguage(turn, APPROVAL_PENDING_PHRASE_BY_LANGUAGE),
3511
- );
3450
+ if (
3451
+ this.enqueueFillerPhrase(
3452
+ turn,
3453
+ approvalPendingPhraseFor(turn.language),
3454
+ this.fixedPhraseLanguage(turn, APPROVAL_PENDING_PHRASE_BY_LANGUAGE),
3455
+ )
3456
+ ) {
3457
+ turn.progress.noteFloorHolder();
3458
+ }
3512
3459
  }
3513
3460
 
3514
3461
  /** Clear the wait once a decision lands, so the turn narrates normally again. */
@@ -4115,13 +4062,7 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
4115
4062
  if (!alreadyReleased) {
4116
4063
  void this.releaseUtterance();
4117
4064
  }
4118
- if (
4119
- this.frontModelConfig.progress.enabled &&
4120
- this.streamTtsAudio &&
4121
- this.progressNarrator
4122
- ) {
4123
- this.armProgressIdleTimer(turn);
4124
- }
4065
+ turn.progress.arm();
4125
4066
  return true;
4126
4067
  }
4127
4068
 
@@ -5112,20 +5053,39 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
5112
5053
  abortController,
5113
5054
  handle: null,
5114
5055
  launchedAtMs: Date.now(),
5115
- progress: {
5116
- ops: [],
5117
- opsSinceNarration: 0,
5118
- // Equal epochs at launch: a turn that has done nothing observable yet
5119
- // has nothing to narrate, so the idle trigger waits for tool activity
5120
- // or the maxSilenceMs heartbeat.
5121
- stateEpoch: 0,
5122
- narratedEpoch: 0,
5123
- updatesSpoken: 0,
5124
- lastFloorHolderAtMs: null,
5125
- lastAudibleAtMs: Date.now(),
5126
- idleTimer: null,
5127
- narrationInFlight: false,
5128
- },
5056
+ progress: createProgressCadence({
5057
+ config: this.frontModelConfig.progress,
5058
+ // Without TTS there is nothing to speak (the idle trigger's static
5059
+ // fallback still needs a generation attempt to fall back from).
5060
+ narrator: this.streamTtsAudio ? this.progressNarrator : null,
5061
+ nextFallbackPhraseIndex: () => this.progressPhraseCounter++,
5062
+ host: {
5063
+ turnId,
5064
+ launchedAtMs: Date.now(),
5065
+ signal: abortController.signal,
5066
+ // Narration may speak whenever the live turn is audibly silent and
5067
+ // has not completed. Escalated turns qualify too: the bridge phrase
5068
+ // holds the floor only while its audio plays (covered by the
5069
+ // audible-idle check), and the strong leg's tool loops are the
5070
+ // longest dead air in the system. Nothing is in flight while a
5071
+ // decision is pending, so every phrase narration has would be a lie
5072
+ // about who the call is waiting on: the turn says so once, when it
5073
+ // starts waiting, and is quiet after that.
5074
+ canNarrate: () =>
5075
+ this.isActiveAssistantTurn(token) &&
5076
+ !activeTurn.assistantCompleted &&
5077
+ activeTurn.pendingApproval === null,
5078
+ isAudioIdle: () => this.turnAudioIdle(activeTurn),
5079
+ playbackTailUntilMs: () => this.assistantPlaybackTailUntilMs,
5080
+ transcriptSoFar: () =>
5081
+ activeTurn.utterance.finalTranscriptSegments.join(" ").trim(),
5082
+ language: () => activeTurn.language,
5083
+ deltaEpoch: () => activeTurn.deltaEpoch,
5084
+ speak: (phrase, language) =>
5085
+ this.enqueueFillerPhrase(activeTurn, phrase, language),
5086
+ onNarrationSpoken: () => this.markProgressSpoken(activeTurn),
5087
+ },
5088
+ }),
5129
5089
  assistantCompleted: false,
5130
5090
  ttsDone: false,
5131
5091
  minimizeRequested: false,
@@ -5153,7 +5113,7 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
5153
5113
  continuationDelivery: opts?.continuationDelivery ?? null,
5154
5114
  hiddenPrompt: opts?.hiddenPrompt === true,
5155
5115
  deltaEpoch: 0,
5156
- escalationHandedOff: false,
5116
+ frontDoor: null,
5157
5117
  ttsBuffer: "",
5158
5118
  spokenSegments: 0,
5159
5119
  spokenChars: 0,
@@ -5211,13 +5171,8 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
5211
5171
  // cadence, wherever in the turn it occurs; without TTS or a narrator there
5212
5172
  // is nothing to speak (the idle trigger's static fallback still needs a
5213
5173
  // generation attempt to fall back from).
5214
- if (
5215
- this.frontModelConfig.progress.enabled &&
5216
- this.streamTtsAudio &&
5217
- this.progressNarrator &&
5218
- !opts?.speculative
5219
- ) {
5220
- this.armProgressIdleTimer(activeTurn);
5174
+ if (!opts?.speculative) {
5175
+ activeTurn.progress.arm();
5221
5176
  }
5222
5177
 
5223
5178
  // Front-door leg: a fast model fronts every turn (the `voiceFrontDoor`
@@ -5280,17 +5235,15 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
5280
5235
  }
5281
5236
  const { token, utterance, turnId } = activeTurn;
5282
5237
 
5283
- // `rawText` accumulates this leg's full stream. A front-door leg feeds
5284
- // every delta to the shared verdict machine and acts on its steps: an
5285
- // answer flushes through the shared marker holdback, while an escalation
5286
- // buffers the post-verdict stream inside the machine until the capped
5287
- // bridge is complete, then hands off. A default/escalated leg flushes
5288
- // every delta through the same holdback, so a stray control marker from
5289
- // the main model is stripped instead of spoken.
5238
+ // `rawText` accumulates this leg's spoken stream. A front-door leg runs
5239
+ // through the shared coordinator, which reads its stream through the
5240
+ // verdict machine: released answer text flushes through the shared
5241
+ // marker holdback, while an escalation buffers the post-verdict stream
5242
+ // until the capped bridge is complete, then hands off. A default or
5243
+ // escalated leg flushes every delta through the same holdback, so a
5244
+ // stray control marker from the main model is stripped instead of
5245
+ // spoken.
5290
5246
  let rawText = "";
5291
- const verdict = createFrontDoorVerdictMachine(
5292
- activeTurn.speculativePending && activeTurn.speculativeHoldAllowed,
5293
- );
5294
5247
 
5295
5248
  const emitLegText = (chunk: string): void => {
5296
5249
  if (chunk.length === 0) {
@@ -5315,6 +5268,53 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
5315
5268
 
5316
5269
  const flushLegText = createControlMarkerHoldback(emitLegText);
5317
5270
 
5271
+ const coordinator = leg.frontDoor
5272
+ ? createFrontDoorLegCoordinator({
5273
+ // The hold branch is only classifiable while the leg is
5274
+ // speculative: its decision rule is the only one that teaches the
5275
+ // hold token.
5276
+ holdEnabled:
5277
+ activeTurn.speculativePending && activeTurn.speculativeHoldAllowed,
5278
+ host: {
5279
+ isLive: () => !activeTurn.finalized,
5280
+ language: () => activeTurn.language,
5281
+ progress: {
5282
+ // The verdict deadline goes with the narration timer: the
5283
+ // hand-off settles the verdict.
5284
+ clear: () => this.clearFillerTimers(activeTurn),
5285
+ noteFloorHolder: () => activeTurn.progress.noteFloorHolder(),
5286
+ arm: () => activeTurn.progress.arm(),
5287
+ },
5288
+ // Hold discards a speculative turn (mid-thought pause, keep
5289
+ // listening); escalate and answer both commit it: utterance
5290
+ // release, thinking frame, and timers all happen inside
5291
+ // commitSpeculativeTurn.
5292
+ onHold: () => {
5293
+ void this.holdSpeculativeTurn(activeTurn);
5294
+ },
5295
+ commit: () =>
5296
+ !activeTurn.speculativePending ||
5297
+ this.commitSpeculativeTurn(activeTurn),
5298
+ onAnswerText: (text) => {
5299
+ rawText += text;
5300
+ flushLegText(rawText);
5301
+ },
5302
+ abortLeg: () => {
5303
+ activeTurn.handle?.abort();
5304
+ activeTurn.handle = null;
5305
+ },
5306
+ speakBridge: (bridge) =>
5307
+ this.speakEscalationBridge(activeTurn, bridge),
5308
+ startEscalatedLeg: (escalated) => {
5309
+ void this.startAssistantLeg(activeTurn, escalated);
5310
+ },
5311
+ },
5312
+ })
5313
+ : null;
5314
+ if (coordinator !== null) {
5315
+ activeTurn.frontDoor = coordinator;
5316
+ }
5317
+
5318
5318
  try {
5319
5319
  // Latched before the await, not after: this flag only decides whether the
5320
5320
  // end event carries a silence classification, and the dashboard decides
@@ -5400,40 +5400,13 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
5400
5400
  if (!this.isForwardingAssistantText(token)) {
5401
5401
  return;
5402
5402
  }
5403
- if (leg.frontDoor) {
5404
- rawText += msg.text;
5403
+ if (coordinator !== null) {
5405
5404
  // Verdict-first: the leg's leading tokens decide the turn's
5406
- // fate. Hold discards a speculative turn (mid-thought pause,
5407
- // keep listening); escalate and answer both commit it —
5408
- // utterance release, thinking frame, and timers all happen
5409
- // inside commitSpeculativeTurn. The hold branch is only
5410
- // classifiable while the leg is speculative (its decision
5411
- // rule is the only one that teaches the hold token). The
5412
- // bridge hands off in one piece once the machine caps it, so
5413
- // the audio, the persisted row, and the phrase quoted to the
5414
- // escalated leg are all the same text.
5415
- const step = verdict.push(msg.text);
5416
- if (step.kind === "hold") {
5417
- void this.holdSpeculativeTurn(activeTurn);
5418
- return;
5419
- }
5420
- if (
5421
- (step.kind === "escalate" || step.kind === "answer") &&
5422
- activeTurn.speculativePending &&
5423
- !this.commitSpeculativeTurn(activeTurn)
5424
- ) {
5425
- return;
5426
- }
5427
- if (step.kind === "answer") {
5428
- flushLegText(rawText);
5429
- return;
5430
- }
5431
- if (
5432
- (step.kind === "escalate" || step.kind === "bridge") &&
5433
- step.bridge !== null
5434
- ) {
5435
- this.escalateTurn(activeTurn, step.bridge);
5436
- }
5405
+ // fate, and the coordinator acts on them. The bridge hands
5406
+ // off in one piece once the machine caps it, so the audio,
5407
+ // the persisted row, and the phrase quoted to the escalated
5408
+ // leg are all the same text.
5409
+ coordinator.push(msg.text);
5437
5410
  return;
5438
5411
  }
5439
5412
  // Defensive: speculative legs are always front-door today, but a
@@ -5469,29 +5442,21 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
5469
5442
  if (current.speculativePending) {
5470
5443
  this.commitSpeculativeTurn(current);
5471
5444
  }
5472
- // A front-door leg that stopped mid-bridge (a bare escalate
5473
- // verdict, or a holding phrase with no sentence terminator)
5474
- // hands off now with whatever arrived; the canned fallback
5475
- // covers an empty bridge. A cancellation mid-bridge falls
5476
- // through to normal cancelled finalization instead — a dead
5477
- // turn must not spawn an escalated leg.
5478
- if (
5479
- leg.frontDoor &&
5480
- msg.type === "message_complete" &&
5481
- !current.escalationHandedOff
5482
- ) {
5483
- const step = verdict.finish();
5484
- if (step.kind === "bridge") {
5485
- this.escalateTurn(current, step.bridge);
5445
+ // A front-door leg that stopped mid-bridge hands off now with
5446
+ // whatever arrived. A cancellation mid-bridge falls through to
5447
+ // normal cancelled finalization instead: a dead turn must not
5448
+ // spawn an escalated leg. A front-door leg that handed off is
5449
+ // finished; the escalated leg drives completion, so this leg's
5450
+ // own trailing completion (including the generation_cancelled
5451
+ // from its abort) is a no-op.
5452
+ if (coordinator !== null) {
5453
+ if (msg.type === "message_complete") {
5454
+ coordinator.complete();
5455
+ }
5456
+ if (coordinator.handedOff) {
5486
5457
  return;
5487
5458
  }
5488
5459
  }
5489
- // A front-door leg that handed off is finished; the escalated leg
5490
- // drives completion. The front-door leg's own trailing completion
5491
- // (including the generation_cancelled from its abort) is a no-op.
5492
- if (leg.frontDoor && current.escalationHandedOff) {
5493
- return;
5494
- }
5495
5460
  // A held "[…"-tail that never completed a marker is real text —
5496
5461
  // force-flush it before assistantCompleted closes the TTS buffer
5497
5462
  // and completeTtsForTurn signals the drain, so it is spoken and
@@ -5567,57 +5532,16 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
5567
5532
  toolName,
5568
5533
  });
5569
5534
  }
5570
- // The op counts toward the narration threshold on start (not
5571
- // completion) so a burst of slow tools still trips the ops
5572
- // trigger while they run.
5573
- current.progress.ops.push({
5574
- toolName,
5575
- ...(detail?.toolUseId !== undefined
5576
- ? { toolUseId: detail.toolUseId }
5577
- : {}),
5578
- startedAtMs: Date.now(),
5579
- });
5580
- current.progress.opsSinceNarration += 1;
5581
- current.progress.stateEpoch += 1;
5535
+ current.progress.toolStarted(toolName, detail?.toolUseId);
5582
5536
  this.refreshActivity(current);
5583
5537
  log.debug({ turnId, toolName }, "Live voice turn started tool use");
5584
- this.maybeNarrateProgress(current, "ops");
5585
5538
  },
5586
5539
  tool_result: (event) => {
5587
5540
  const current = this.activeAssistantTurn;
5588
5541
  if (current?.token !== token) {
5589
5542
  return;
5590
5543
  }
5591
- // Match by toolUseId when present; otherwise the last-started
5592
- // incomplete op with the same name (parallel same-name ops
5593
- // resolve newest-first).
5594
- const op =
5595
- (event.toolUseId !== undefined
5596
- ? current.progress.ops.find(
5597
- (o) => o.toolUseId === event.toolUseId,
5598
- )
5599
- : undefined) ??
5600
- findLastIncompleteOp(current.progress.ops, event.toolName);
5601
- // A long-running op finishing is the beat the user has been
5602
- // waiting through: it narrates immediately rather than waiting for
5603
- // `opsThreshold` more ops, which on a one-slow-tool turn never
5604
- // arrive. Short ops stay on the ops trigger — narrating every
5605
- // quick lookup is the chatter this cadence exists to avoid.
5606
- let trigger: "ops" | "op_complete" = "ops";
5607
- if (op) {
5608
- op.completedAtMs = Date.now();
5609
- if (event.isError !== undefined) {
5610
- op.isError = event.isError;
5611
- }
5612
- op.resultPreview = event.resultPreview;
5613
- if (
5614
- op.completedAtMs - op.startedAtMs >=
5615
- this.frontModelConfig.progress.longOpMs
5616
- ) {
5617
- trigger = "op_complete";
5618
- }
5619
- }
5620
- current.progress.stateEpoch += 1;
5544
+ current.progress.toolFinished(event);
5621
5545
  // Showing a surface implies revealing it: the room is a
5622
5546
  // full-screen overlay, so a surface rendered behind it is a
5623
5547
  // surface nobody sees.
@@ -5640,7 +5564,6 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
5640
5564
  }
5641
5565
  }
5642
5566
  this.refreshActivity(current);
5643
- this.maybeNarrateProgress(current, trigger);
5644
5567
  },
5645
5568
  },
5646
5569
  onError: (message) => {
@@ -5699,7 +5622,7 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
5699
5622
  }
5700
5623
  // The front-door leg may have handed off before its handle resolved;
5701
5624
  // abort it rather than exposing it as the turn's live handle.
5702
- if (leg.frontDoor && current.escalationHandedOff) {
5625
+ if (coordinator?.handedOff === true) {
5703
5626
  handle.abort();
5704
5627
  return true;
5705
5628
  }
@@ -5727,38 +5650,17 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
5727
5650
  }
5728
5651
 
5729
5652
  /**
5730
- * Hand the turn from the front-door leg to the strong "escalated" leg after
5731
- * the escalate verdict. Speaks the capped bridge (the leg's own post-verdict
5732
- * holding phrase, or the canned fallback when that was too short) in one
5733
- * piece and force-flushes it so it plays during the strong-model call, then
5734
- * starts the escalated leg on the same ActiveAssistantTurn. Idempotent.
5653
+ * Speak the escalation bridge so the strong-model call has no dead air.
5654
+ * The model's own bridge is real assistant speech (captions + TTS); the
5655
+ * canned fallback stays audio-only, matching the persisted-row hygiene (a
5656
+ * deleted row for a bridge the model never produced).
5735
5657
  */
5736
- private escalateTurn(
5658
+ private speakEscalationBridge(
5737
5659
  activeTurn: ActiveAssistantTurn,
5738
- cappedBridge: string,
5660
+ bridge: SpokenEscalationBridge,
5739
5661
  ): void {
5740
- if (activeTurn.escalationHandedOff || activeTurn.finalized) {
5741
- return;
5742
- }
5743
- activeTurn.escalationHandedOff = true;
5744
- // The escalation bridge below holds the floor, so pending progress
5745
- // narration would only stack a second filler on top of it.
5746
- this.clearFillerTimers(activeTurn);
5747
- // Abort the front-door leg so a model that keeps generating past the
5748
- // bridge cap adds no latency before the escalated leg starts.
5749
- activeTurn.handle?.abort();
5750
- activeTurn.handle = null;
5751
-
5752
- // Speak the bridge so the strong-model call has no dead air. The model's
5753
- // own bridge is real assistant speech (captions + TTS); the canned
5754
- // fallback stays audio-only, matching the persisted-row hygiene (a
5755
- // deleted row for a bridge the model never produced).
5756
- const {
5757
- spokenBridge,
5758
- usesFallback: usesFallbackBridge,
5759
- language: bridgeLanguage,
5760
- } = resolveSpokenEscalationBridge(cappedBridge, activeTurn.language);
5761
- if (!usesFallbackBridge) {
5662
+ const { spokenBridge, usesFallback, language } = bridge;
5663
+ if (!usesFallback) {
5762
5664
  this.markFirstAssistantDelta(activeTurn.utterance, activeTurn.turnId);
5763
5665
  this.markAssistantDelta(activeTurn);
5764
5666
  void this.sendFrame(
@@ -5770,43 +5672,14 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
5770
5672
  // otherwise sit buffered until a sentence boundary and leave the
5771
5673
  // caller in silence during the escalated model's call.
5772
5674
  this.flushTtsBuffer(activeTurn.token, true);
5773
- } else {
5774
- // The canned bridge is a fixed localized-table phrase, enqueued
5775
- // directly (it is already one complete sentence) so the segment can
5776
- // carry the "en" override when the table lacks the turn's language.
5777
- const speakable = sanitizeForTts(spokenBridge).trim();
5778
- if (speakable.length > 0) {
5779
- this.enqueueTtsSegment(activeTurn.token, speakable, {
5780
- language: bridgeLanguage,
5781
- });
5782
- }
5675
+ return;
5783
5676
  }
5784
-
5785
- // No overrideProfile here: the bridge pins the escalated leg to the
5786
- // conversation's own profile, the model the caller's typed turns already
5787
- // run on (see voice-triage-escalate.ts). The bridge phrase the caller
5788
- // just heard is handed along so the escalated continuation rule can
5789
- // quote it and ban a re-announcing echo ("Let me check…" twice in a
5790
- // row).
5791
- void this.startAssistantLeg(activeTurn, {
5792
- content: ESCALATION_CONTINUATION_CONTENT,
5793
- routingLeg: "escalated",
5794
- spokenEscalationBridge: spokenBridge,
5795
- });
5796
-
5797
- // Escalated legs run the slowest work in the system (strong-model
5798
- // thinking + tool loops), and the bridge only covers the first couple of
5799
- // seconds of it — exactly the dead air progress narration exists for.
5800
- // Re-arm the idle narration timer (cleared above with the ack): its
5801
- // audible-silence gating means nothing speaks until the bridge audio has
5802
- // fully drained plus a whole idle interval. Acks stay suppressed
5803
- // post-handoff — the bridge already served that role.
5804
- if (
5805
- this.frontModelConfig.progress.enabled &&
5806
- this.streamTtsAudio &&
5807
- this.progressNarrator
5808
- ) {
5809
- this.armProgressIdleTimer(activeTurn);
5677
+ // The canned bridge is a fixed localized-table phrase, enqueued
5678
+ // directly (it is already one complete sentence) so the segment can
5679
+ // carry the "en" override when the table lacks the turn's language.
5680
+ const speakable = sanitizeForTts(spokenBridge).trim();
5681
+ if (speakable.length > 0) {
5682
+ this.enqueueTtsSegment(activeTurn.token, speakable, { language });
5810
5683
  }
5811
5684
  }
5812
5685
 
@@ -5883,61 +5756,6 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
5883
5756
  turn.deltaEpoch += 1;
5884
5757
  }
5885
5758
 
5886
- // Arms (or re-arms) the dead-air narration timer. The countdown measures
5887
- // audible silence — time since the turn's audio last (estimatedly) reached
5888
- // the user's ears — not time since launch, so it covers mid-turn silences
5889
- // for the whole turn. On expiry with audio still pending, or with the
5890
- // silence not yet a full interval old, it re-arms for the remainder; only a
5891
- // full interval of audible silence reaches the narration gatekeeper. The
5892
- // interval is a polling cadence, not a speaking cadence: most ticks find
5893
- // nothing new to report and stay quiet, so what the user hears follows the
5894
- // turn's tool activity (with `maxSilenceMs` as the heartbeat ceiling).
5895
- private armProgressIdleTimer(
5896
- turn: ActiveAssistantTurn,
5897
- delayMs?: number,
5898
- ): void {
5899
- const { token } = turn;
5900
- this.clearProgressIdleTimer(turn);
5901
- turn.progress.idleTimer = setTimeout(() => {
5902
- turn.progress.idleTimer = null;
5903
- if (!this.isActiveAssistantTurn(token) || turn.assistantCompleted) {
5904
- return;
5905
- }
5906
- if (!this.turnAudioIdle(turn)) {
5907
- // Audio is buffered, queued, or still playing: a fresh silence can
5908
- // only be a full interval old one interval from now.
5909
- this.armProgressIdleTimer(turn);
5910
- return;
5911
- }
5912
- const remaining = this.progressIdleDeadlineMs(turn) - Date.now();
5913
- if (remaining > 0) {
5914
- this.armProgressIdleTimer(turn, remaining);
5915
- return;
5916
- }
5917
- this.maybeNarrateProgress(turn, "idle");
5918
- this.armProgressIdleTimer(turn);
5919
- }, delayMs ?? this.frontModelConfig.progress.idleIntervalMs);
5920
- }
5921
-
5922
- // Wall-clock instant the current audible silence turns a full interval old.
5923
- private progressIdleDeadlineMs(turn: ActiveAssistantTurn): number {
5924
- return (
5925
- this.progressSilenceSinceMs(turn) +
5926
- this.frontModelConfig.progress.idleIntervalMs
5927
- );
5928
- }
5929
-
5930
- // When the turn's current audible silence began: the latest of the last
5931
- // emitted segment, the estimated client playback end, and the last enqueued
5932
- // filler.
5933
- private progressSilenceSinceMs(turn: ActiveAssistantTurn): number {
5934
- return Math.max(
5935
- turn.progress.lastAudibleAtMs,
5936
- this.assistantPlaybackTailUntilMs,
5937
- turn.progress.lastFloorHolderAtMs ?? 0,
5938
- );
5939
- }
5940
-
5941
5759
  // No assistant audio is pending or (estimatedly) still playing: nothing
5942
5760
  // buffered toward the next sentence, every queued TTS segment fully
5943
5761
  // emitted, and the client-side playback-tail estimate expired.
@@ -5949,177 +5767,18 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
5949
5767
  );
5950
5768
  }
5951
5769
 
5952
- private clearProgressIdleTimer(turn: ActiveAssistantTurn): void {
5953
- if (turn.progress.idleTimer !== null) {
5954
- clearTimeout(turn.progress.idleTimer);
5955
- turn.progress.idleTimer = null;
5956
- }
5957
- }
5958
-
5959
5770
  // Clears progress narration and verdict timers for events that end the
5960
5771
  // current filler lifecycle.
5961
5772
  private clearFillerTimers(turn: ActiveAssistantTurn): void {
5962
- this.clearProgressIdleTimer(turn);
5773
+ turn.progress.clear();
5963
5774
  if (turn.verdictDeadlineTimer !== null) {
5964
5775
  clearTimeout(turn.verdictDeadlineTimer);
5965
5776
  turn.verdictDeadlineTimer = null;
5966
5777
  }
5967
5778
  }
5968
5779
 
5969
- // Narration may speak whenever the live turn is audibly silent and has
5970
- // not completed. Escalated turns qualify too: the bridge phrase holds the
5971
- // floor only while its audio plays (covered by the audible-idle check),
5972
- // and the strong leg's tool loops are the longest dead air in the system.
5973
- private turnCanNarrateProgress(turn: ActiveAssistantTurn): boolean {
5974
- return (
5975
- this.isActiveAssistantTurn(turn.token) &&
5976
- !turn.assistantCompleted &&
5977
- // Nothing is in flight while a decision is pending, so every phrase
5978
- // narration has would be a lie about who the call is waiting on. The
5979
- // turn says so once, when it starts waiting, and is quiet after that.
5980
- turn.pendingApproval === null &&
5981
- this.turnAudioIdle(turn)
5982
- );
5983
- }
5984
-
5985
- // The idle tick has something worth saying when the turn's tool activity has
5986
- // moved since the last narration described it, or when the silence has run
5987
- // past `maxSilenceMs` — the heartbeat ceiling that proves the assistant is
5988
- // still alive on a turn with no observable activity at all. Every other tick
5989
- // stays quiet, so the cadence follows the work rather than the clock.
5990
- private progressIdleHasSomethingToSay(turn: ActiveAssistantTurn): boolean {
5991
- const { progress } = turn;
5992
- if (progress.stateEpoch !== progress.narratedEpoch) {
5993
- return true;
5994
- }
5995
- const silentForMs = Date.now() - this.progressSilenceSinceMs(turn);
5996
- if (silentForMs >= this.frontModelConfig.progress.maxSilenceMs) {
5997
- return true;
5998
- }
5999
- log.debug(
6000
- { turnId: turn.turnId, silentForMs },
6001
- "Live voice progress narration held — nothing new since the last update",
6002
- );
6003
- return false;
6004
- }
6005
-
6006
- // Gatekeeper for progress narration. It speaks only while the turn is
6007
- // audibly silent, with one generation at a time and the configured spacing.
6008
- private maybeNarrateProgress(
6009
- turn: ActiveAssistantTurn,
6010
- trigger: "ops" | "idle" | "op_complete",
6011
- ): void {
6012
- const cfg = this.frontModelConfig.progress;
6013
- const { progress } = turn;
6014
- const progressNarrator = this.progressNarrator;
6015
- if (
6016
- !cfg.enabled ||
6017
- !this.streamTtsAudio ||
6018
- !progressNarrator ||
6019
- !this.turnCanNarrateProgress(turn) ||
6020
- progress.narrationInFlight ||
6021
- (progress.lastFloorHolderAtMs !== null &&
6022
- Date.now() - progress.lastFloorHolderAtMs < cfg.minGapMs) ||
6023
- (trigger === "ops" && progress.opsSinceNarration < cfg.opsThreshold) ||
6024
- (trigger === "idle" && !this.progressIdleHasSomethingToSay(turn))
6025
- ) {
6026
- return;
6027
- }
6028
- void this.speakProgressUpdate(turn, progressNarrator, trigger);
6029
- }
6030
-
6031
- // Generate and speak one audio-only progress narration. On a null result,
6032
- // idle narration falls back to a static phrase while activity-triggered
6033
- // narration stays silent.
6034
- private async speakProgressUpdate(
6035
- turn: ActiveAssistantTurn,
6036
- progressNarrator: VoiceProgressNarrator,
6037
- trigger: "ops" | "idle" | "op_complete",
6038
- ): Promise<void> {
6039
- const { progress } = turn;
6040
- progress.narrationInFlight = true;
6041
- // Any delta that lands while generation is in flight makes the text stale.
6042
- const deltaEpochAtLaunch = turn.deltaEpoch;
6043
- // The activity this update describes. Tool events that land mid-generation
6044
- // are news the generated text cannot carry, so they must leave the idle
6045
- // trigger armed rather than count as already narrated.
6046
- const stateEpochAtLaunch = progress.stateEpoch;
6047
- try {
6048
- const now = Date.now();
6049
- const currentOp = findLastIncompleteOp(progress.ops);
6050
- const input: VoiceProgressTextInput = {
6051
- transcriptSoFar: turn.utterance.finalTranscriptSegments
6052
- .join(" ")
6053
- .trim(),
6054
- completedOps: progress.ops
6055
- .filter(
6056
- (op): op is TurnProgressOp & { completedAtMs: number } =>
6057
- op.completedAtMs !== undefined,
6058
- )
6059
- // `ops` is in start order; the narrator wants completion
6060
- // order, which differs when parallel tools finish out of order.
6061
- .sort((a, b) => a.completedAtMs - b.completedAtMs)
6062
- .map((op) => ({
6063
- toolName: op.toolName,
6064
- ...(op.isError !== undefined ? { isError: op.isError } : {}),
6065
- ...(op.resultPreview !== undefined
6066
- ? { resultPreview: op.resultPreview }
6067
- : {}),
6068
- })),
6069
- currentOp: currentOp
6070
- ? {
6071
- toolName: currentOp.toolName,
6072
- elapsedMs: now - currentOp.startedAtMs,
6073
- }
6074
- : null,
6075
- turnElapsedMs: now - turn.launchedAtMs,
6076
- updateIndex: progress.updatesSpoken + 1,
6077
- ...(turn.language !== undefined ? { languageHint: turn.language } : {}),
6078
- };
6079
- const generated = await progressNarrator
6080
- .generateProgressText(input, turn.abortController.signal)
6081
- // The narrator contract never rejects. Keep test stubs fail-soft too.
6082
- .catch(() => null);
6083
- // Re-check liveness and staleness after the provider call.
6084
- if (
6085
- !this.turnCanNarrateProgress(turn) ||
6086
- turn.deltaEpoch !== deltaEpochAtLaunch ||
6087
- (progress.lastFloorHolderAtMs !== null &&
6088
- Date.now() - progress.lastFloorHolderAtMs <
6089
- this.frontModelConfig.progress.minGapMs)
6090
- ) {
6091
- return;
6092
- }
6093
- let raw = generated;
6094
- // Generated text is in the turn's language; only the static
6095
- // fallback comes from a localized table and may need the "en" override.
6096
- let fillerLanguage: string | undefined;
6097
- if (raw === null) {
6098
- if (trigger !== "idle") {
6099
- return;
6100
- }
6101
- raw = pickProgressPhrase(this.progressPhraseCounter++, turn.language);
6102
- fillerLanguage = this.fixedPhraseLanguage(
6103
- turn,
6104
- PROGRESS_FALLBACK_PHRASES_BY_LANGUAGE,
6105
- );
6106
- }
6107
- if (!this.enqueueFillerPhrase(turn, raw, fillerLanguage)) {
6108
- return;
6109
- }
6110
- progress.opsSinceNarration = 0;
6111
- progress.narratedEpoch = stateEpochAtLaunch;
6112
- progress.updatesSpoken += 1;
6113
- // Record only when narration audio actually enqueued.
6114
- this.markProgressSpoken(turn);
6115
- // Restart the dead-air countdown from this narration.
6116
- this.armProgressIdleTimer(turn);
6117
- } finally {
6118
- progress.narrationInFlight = false;
6119
- }
6120
- }
6121
-
6122
- // Sanitize and enqueue one progress sentence on the ordered TTS queue.
5780
+ // Sanitize and enqueue one filler sentence (narration, the approval line)
5781
+ // on the ordered TTS queue, audio-only.
6123
5782
  private enqueueFillerPhrase(
6124
5783
  turn: ActiveAssistantTurn,
6125
5784
  raw: string,
@@ -6133,8 +5792,6 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
6133
5792
  countsAsFirstSegment: false,
6134
5793
  ...(language !== undefined ? { language } : {}),
6135
5794
  });
6136
- // A spoken filler holds the floor, so narration's minGapMs spaces from it.
6137
- turn.progress.lastFloorHolderAtMs = Date.now();
6138
5795
  return true;
6139
5796
  }
6140
5797
 
@@ -6190,7 +5847,7 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
6190
5847
  log.info(
6191
5848
  {
6192
5849
  turnId: currentTurn.turnId,
6193
- escalated: currentTurn.escalationHandedOff,
5850
+ escalated: currentTurn.frontDoor?.handedOff ?? false,
6194
5851
  spokenSegments: currentTurn.spokenSegments,
6195
5852
  spokenChars: currentTurn.spokenChars,
6196
5853
  },
@@ -6431,7 +6088,7 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
6431
6088
  if (settledTurn?.token === token) {
6432
6089
  // Anchor the dead-air countdown to the end of emission; the playback
6433
6090
  // -tail estimate covers any client-side buffer still draining.
6434
- settledTurn.progress.lastAudibleAtMs = Date.now();
6091
+ settledTurn.progress.noteAudioSettled();
6435
6092
  }
6436
6093
  this.pumpTtsSynthesis(token);
6437
6094
  }
@@ -7018,8 +6675,8 @@ export function createLiveVoiceSession(
7018
6675
  const vadConfig = liveVoiceConfig?.vad;
7019
6676
  // Parsed once here into a complete config, shared by endpointing and the
7020
6677
  // session (the constructor's own parse is then a no-op re-validation).
7021
- const frontModelConfig = LiveVoiceFrontModelConfigSchema.parse(
7022
- options.frontModelConfig ?? liveVoiceConfig?.frontModel ?? {},
6678
+ const frontModelConfig = VoiceFrontModelConfigSchema.parse(
6679
+ options.frontModelConfig ?? getConfig().voice?.frontModel ?? {},
7023
6680
  );
7024
6681
  return new LiveVoiceSession(context, {
7025
6682
  ...options,