@vellumai/assistant 0.10.8-dev.202607122020.85b2d5c → 0.10.8-dev.202607122121.c5fc3ac

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/assistant",
3
- "version": "0.10.8-dev.202607122020.85b2d5c",
3
+ "version": "0.10.8-dev.202607122121.c5fc3ac",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -0,0 +1,47 @@
1
+ import { describe, expect, test } from "bun:test";
2
+
3
+ import {
4
+ couldBeControlMarker,
5
+ ESCALATE_MARKER,
6
+ stripInternalSpeechMarkers,
7
+ } from "../voice-control-protocol.js";
8
+
9
+ describe("[ESCALATE] control marker", () => {
10
+ test("marker constant is the expected token", () => {
11
+ expect(ESCALATE_MARKER).toBe("[ESCALATE]");
12
+ });
13
+
14
+ test("stripInternalSpeechMarkers removes [ESCALATE] so it is never spoken", () => {
15
+ expect(
16
+ stripInternalSpeechMarkers("Let me think about that. [ESCALATE]").trim(),
17
+ ).toBe("Let me think about that.");
18
+ });
19
+
20
+ test("stripping removes every [ESCALATE] occurrence", () => {
21
+ expect(
22
+ stripInternalSpeechMarkers("[ESCALATE] one [ESCALATE] two").replace(
23
+ /\s+/g,
24
+ " ",
25
+ ),
26
+ ).toBe(" one two");
27
+ });
28
+
29
+ test("couldBeControlMarker holds the complete marker (not flushed to TTS)", () => {
30
+ expect(couldBeControlMarker("[ESCALATE]")).toBe(true);
31
+ });
32
+
33
+ test("couldBeControlMarker holds a partial marker still streaming", () => {
34
+ // Any prefix of the marker must be held so a streamed "[ESCA" does not
35
+ // leak to the TTS engine before the full marker arrives.
36
+ for (const partial of ["[", "[ES", "[ESCAL", "[ESCALATE"]) {
37
+ expect(couldBeControlMarker(partial)).toBe(true);
38
+ }
39
+ });
40
+
41
+ test("ordinary text is not mistaken for the marker", () => {
42
+ expect(couldBeControlMarker("Sure, one moment")).toBe(false);
43
+ expect(stripInternalSpeechMarkers("Sure, one moment")).toBe(
44
+ "Sure, one moment",
45
+ );
46
+ });
47
+ });
@@ -28,6 +28,7 @@ import { setConfig } from "../../__tests__/helpers/set-config.js";
28
28
  import { ABORT_WATCHDOG_MS } from "../../daemon/abort-watchdog.js";
29
29
  import { CALL_OPENING_MARKER } from "../voice-control-protocol.js";
30
30
  import { startVoiceTurn } from "../voice-session-bridge.js";
31
+ import { ESCALATION_CONTINUATION_CONTENT } from "../voice-triage-escalate.js";
31
32
 
32
33
  // `resolveProcessingWaitMs` reads `workspaceGit.turnCommitMaxWaitMs`; seed it
33
34
  // so the wait-budget assertions below get a fixed, known value.
@@ -60,6 +61,7 @@ interface FakeConversation {
60
61
  persistUserMessage: (opts: {
61
62
  content: string;
62
63
  requestId: string;
64
+ metadata?: Record<string, unknown>;
63
65
  }) => Promise<{ id: string }>;
64
66
  updateClient: (cb: unknown, reset?: boolean) => void;
65
67
  runAgentLoop: (...args: unknown[]) => Promise<void>;
@@ -78,6 +80,9 @@ function makeFakeConversation(opts: {
78
80
  }) {
79
81
  const waitForIdleCalls: WaitForIdleCall[] = [];
80
82
  let persistCount = 0;
83
+ let lastPersistOpts:
84
+ | { content: string; requestId: string; metadata?: Record<string, unknown> }
85
+ | undefined;
81
86
  const conversation: FakeConversation = {
82
87
  conversationId: "conv-voice-bridge-test",
83
88
  callSessionId: undefined,
@@ -99,8 +104,9 @@ function makeFakeConversation(opts: {
99
104
  setTurnInterfaceContext: () => {},
100
105
  setChannelCapabilities: () => {},
101
106
  setVoiceCallControlPrompt: () => {},
102
- persistUserMessage: async () => {
107
+ persistUserMessage: async (persistOpts) => {
103
108
  persistCount += 1;
109
+ lastPersistOpts = persistOpts;
104
110
  // Recorded before `onPersist` so scripted persist FAILURES also
105
111
  // appear in the event stream — ordering tests need the losing
106
112
  // attempt visible.
@@ -120,6 +126,7 @@ function makeFakeConversation(opts: {
120
126
  conversation,
121
127
  waitForIdleCalls,
122
128
  persistCount: () => persistCount,
129
+ lastPersistOpts: () => lastPersistOpts,
123
130
  setProcessingFlag: (value: boolean) => {
124
131
  opts.processing = value;
125
132
  },
@@ -254,6 +261,35 @@ const flushMicrotasks = async () => {
254
261
  // Tests
255
262
  // ---------------------------------------------------------------------------
256
263
 
264
+ describe("startVoiceTurn escalation-continuation persistence", () => {
265
+ test("persists the escalation-continuation prompt as a hidden row", async () => {
266
+ // The continuation is a pure internal instruction — it must be persisted
267
+ // `hidden` so `/messages` filters it out of the transcript after a reload,
268
+ // not merely echo-suppressed live.
269
+ const fake = makeFakeConversation({ processing: false });
270
+ fakeConversation = fake.conversation;
271
+
272
+ await startVoiceTurn({
273
+ ...makeTurnOptions(),
274
+ content: ESCALATION_CONTINUATION_CONTENT,
275
+ });
276
+
277
+ expect(fake.lastPersistOpts()?.content).toBe(
278
+ ESCALATION_CONTINUATION_CONTENT,
279
+ );
280
+ expect(fake.lastPersistOpts()?.metadata).toEqual({ hidden: true });
281
+ });
282
+
283
+ test("the opener prompt is persisted un-hidden (unchanged)", async () => {
284
+ const fake = makeFakeConversation({ processing: false });
285
+ fakeConversation = fake.conversation;
286
+
287
+ await startVoiceTurn(makeTurnOptions()); // content: CALL_OPENING_MARKER
288
+
289
+ expect(fake.lastPersistOpts()?.metadata).toBeUndefined();
290
+ });
291
+ });
292
+
257
293
  describe("startVoiceTurn conversation-lock wait", () => {
258
294
  test("an idle conversation starts the turn without consulting waitForIdle", async () => {
259
295
  const fake = makeFakeConversation({ processing: false });
@@ -0,0 +1,151 @@
1
+ import { afterEach, describe, expect, test } from "bun:test";
2
+
3
+ import { setOverridesForTesting } from "../../__tests__/feature-flag-test-helpers.js";
4
+ import { clearFeatureFlagOverridesCache } from "../../config/assistant-feature-flags.js";
5
+ import type { AssistantConfig } from "../../config/schema.js";
6
+ import { ESCALATE_MARKER } from "../voice-control-protocol.js";
7
+ import {
8
+ escalatedContinuationRule,
9
+ ESCALATION_CONTINUATION_CONTENT,
10
+ ESCALATION_PROFILE,
11
+ FRONT_DOOR_PROFILE,
12
+ frontDoorTriageRule,
13
+ isVoiceTriageEscalateEnabled,
14
+ needsFallbackBridge,
15
+ VOICE_TRIAGE_ESCALATE_FLAG,
16
+ } from "../voice-triage-escalate.js";
17
+
18
+ // The gate ignores the config arg (flags resolve from the override cache +
19
+ // bundled registry), so a bare cast is sufficient.
20
+ const CONFIG = {} as AssistantConfig;
21
+
22
+ afterEach(() => {
23
+ clearFeatureFlagOverridesCache();
24
+ });
25
+
26
+ describe("voice-triage-escalate profiles", () => {
27
+ test("front door is the fast Speed profile, escalation is the Quality profile", () => {
28
+ expect(FRONT_DOOR_PROFILE).toBe("cost-optimized");
29
+ expect(ESCALATION_PROFILE).toBe("quality-optimized");
30
+ });
31
+ });
32
+
33
+ describe("isVoiceTriageEscalateEnabled", () => {
34
+ test("is off by default (registry defaultEnabled: false)", () => {
35
+ clearFeatureFlagOverridesCache();
36
+ expect(isVoiceTriageEscalateEnabled(CONFIG)).toBe(false);
37
+ });
38
+
39
+ test("is on when the flag override is set", () => {
40
+ setOverridesForTesting({ [VOICE_TRIAGE_ESCALATE_FLAG]: true });
41
+ expect(isVoiceTriageEscalateEnabled(CONFIG)).toBe(true);
42
+ });
43
+
44
+ test("is off when the flag override is explicitly false", () => {
45
+ setOverridesForTesting({ [VOICE_TRIAGE_ESCALATE_FLAG]: false });
46
+ expect(isVoiceTriageEscalateEnabled(CONFIG)).toBe(false);
47
+ });
48
+ });
49
+
50
+ describe("front-door triage rule", () => {
51
+ const rule = frontDoorTriageRule();
52
+
53
+ test("instructs the model to triage before answering and emit [ESCALATE]", () => {
54
+ expect(rule).toContain("TRIAGE FIRST");
55
+ expect(rule).toContain(ESCALATE_MARKER);
56
+ // Must decide up front — never answer, then bail (spoken audio is final).
57
+ expect(rule.toLowerCase()).toContain("before you begin answering");
58
+ });
59
+
60
+ test("lists tool uncertainty as an escalate trigger (no fabrication)", () => {
61
+ expect(rule.toLowerCase()).toContain("tool");
62
+ });
63
+ });
64
+
65
+ describe("escalated continuation rule", () => {
66
+ const rule = escalatedContinuationRule();
67
+
68
+ test("tells the quality model to continue without re-greeting or repeating", () => {
69
+ expect(rule.toLowerCase()).toContain("continue");
70
+ expect(rule.toLowerCase()).toContain("do not greet again");
71
+ });
72
+
73
+ test("forbids the quality model from emitting [ESCALATE] again", () => {
74
+ expect(rule).toContain(ESCALATE_MARKER);
75
+ expect(rule.toLowerCase()).toContain("never emit");
76
+ });
77
+ });
78
+
79
+ describe("needsFallbackBridge", () => {
80
+ test("false when the model spoke a real holding phrase before the marker", () => {
81
+ expect(
82
+ needsFallbackBridge("Let me think about that for a second. [ESCALATE]"),
83
+ ).toBe(false);
84
+ });
85
+
86
+ test("true for a bare marker with no holding phrase", () => {
87
+ expect(needsFallbackBridge("[ESCALATE]")).toBe(true);
88
+ });
89
+
90
+ test("true when only post-marker text exists — that text was never spoken", () => {
91
+ // Regression: the fallback decision must measure text BEFORE the marker.
92
+ // Post-marker text is suppressed from TTS, so counting it would skip the
93
+ // fallback and leave the caller in silence during the hand-off.
94
+ expect(
95
+ needsFallbackBridge(
96
+ "[ESCALATE] here is my weak answer the model kept going",
97
+ ),
98
+ ).toBe(true);
99
+ });
100
+ });
101
+
102
+ describe("escalation continuation content", () => {
103
+ test("is an echo-suppressed synthetic prompt (parenthesized, non-user-speech)", () => {
104
+ expect(ESCALATION_CONTINUATION_CONTENT.startsWith("(")).toBe(true);
105
+ expect(ESCALATION_CONTINUATION_CONTENT.endsWith(")")).toBe(true);
106
+ });
107
+ });
108
+
109
+ // Controller-level orchestration in CallController.streamTtsTokens is not
110
+ // covered by unit tests here — CallController needs a live transport,
111
+ // conversation, and TTS provider to instantiate. These document the intended
112
+ // integration coverage (a harnessed call-controller test or the manual
113
+ // cli-testing flow) for the two-leg escalation path.
114
+ describe("call-controller escalation orchestration (integration — TODO)", () => {
115
+ test.todo(
116
+ "flag OFF: a single leg runs on the call-site default profile, no [ESCALATE] rule in the prompt",
117
+ () => {},
118
+ );
119
+ test.todo(
120
+ "flag ON, simple turn: the front-door (cost-optimized) leg answers and no escalation leg runs",
121
+ () => {},
122
+ );
123
+ test.todo(
124
+ "flag ON, tricky turn: [ESCALATE] triggers a second (quality-optimized) leg that shares the TTS stream and end-of-turn signal",
125
+ () => {},
126
+ );
127
+ test.todo(
128
+ "front-door text after [ESCALATE] is suppressed and never spoken; only the bridge before the marker reaches TTS",
129
+ () => {},
130
+ );
131
+ test.todo(
132
+ "post-[ESCALATE] front-door text is dropped from the completion text — no spurious [END_CALL]/[ASK_GUARDIAN], no transcript pollution",
133
+ () => {},
134
+ );
135
+ test.todo(
136
+ "the front-door leg is aborted on [ESCALATE] so a model that keeps generating does not delay the escalated leg",
137
+ () => {},
138
+ );
139
+ test.todo(
140
+ "an unpunctuated bridge is force-synthesized before the escalated leg so the caller is not left in silence during the strong-model call",
141
+ () => {},
142
+ );
143
+ test.todo(
144
+ "bare [ESCALATE] with no holding phrase injects the fallback bridge before the quality leg so there is no dead air",
145
+ () => {},
146
+ );
147
+ test.todo(
148
+ "barge-in during the bridge or hand-off aborts both legs via runSignal",
149
+ () => {},
150
+ );
151
+ });
@@ -71,6 +71,7 @@ import {
71
71
  CALL_VERIFICATION_COMPLETE_MARKER,
72
72
  couldBeControlMarker,
73
73
  END_CALL_MARKER,
74
+ ESCALATE_MARKER,
74
75
  extractBalancedJson,
75
76
  stripInternalSpeechMarkers,
76
77
  } from "./voice-control-protocol.js";
@@ -79,6 +80,15 @@ import {
79
80
  startVoiceTurn,
80
81
  type VoiceTurnHandle,
81
82
  } from "./voice-session-bridge.js";
83
+ import {
84
+ ESCALATION_CONTINUATION_CONTENT,
85
+ ESCALATION_PROFILE,
86
+ FALLBACK_ESCALATION_BRIDGE,
87
+ FRONT_DOOR_PROFILE,
88
+ isVoiceTriageEscalateEnabled,
89
+ needsFallbackBridge,
90
+ type VoiceRoutingLeg,
91
+ } from "./voice-triage-escalate.js";
82
92
 
83
93
  const log = getLogger("call-controller");
84
94
 
@@ -864,82 +874,150 @@ export class CallController {
864
874
  }
865
875
  };
866
876
 
867
- // Use a promise to track completion of the voice turn
868
- const turnComplete = new Promise<void>((resolve, reject) => {
869
- const onTextDelta = (text: string): void => {
870
- if (!this.isCurrentRun(runVersion)) return;
871
- fullResponseText += text;
872
- ttsBuffer += text;
873
- ttsBuffer = stripInternalSpeechMarkers(ttsBuffer);
874
- flushSafeText();
875
- };
876
-
877
- const onComplete = (): void => {
878
- resolve();
879
- };
880
-
881
- const onError = (message: string): void => {
882
- reject(new Error(message));
883
- };
884
-
885
- // Start the voice turn through the session bridge
886
- startVoiceTurn({
887
- conversationId: this.conversationId,
888
- callSessionId: this.callSessionId,
889
- content,
890
- assistantId: this.assistantId,
891
- trustContext: this.trustContext ?? undefined,
892
- isInbound: this.isInbound,
893
- task: this.task,
894
- skipDisclosure: this.skipDisclosure,
895
- onTextDelta,
896
- onComplete,
897
- onError,
898
- signal: runSignal,
899
- })
900
- .then((handle) => {
901
- if (this.isCurrentRun(runVersion)) {
902
- this.currentTurnHandle = handle;
903
- } else {
904
- // Turn was superseded before handle arrived; abort immediately
905
- handle.abort();
877
+ // Triage-and-escalate routing (voice-triage-escalate flag). When on, a fast
878
+ // "front-door" model fronts the turn; if it emits [ESCALATE] we run a second
879
+ // "escalated" leg on the quality model. Both legs stream through the shared
880
+ // TTS machinery below and share this turn's single end-of-turn signal, so
881
+ // the caller never gets a listening window between the spoken bridge and the
882
+ // answer. When off, exactly one leg runs on the call-site default profile —
883
+ // identical to the prior behavior.
884
+ const escalateEnabled = isVoiceTriageEscalateEnabled();
885
+
886
+ // Run a single voice-turn leg through the session bridge, streaming its
887
+ // deltas through the shared TTS closures above. Resolves with the raw text
888
+ // this leg produced (used to detect the [ESCALATE] hand-off). Errors cancel
889
+ // and drain this turn's synthesis before propagating, mirroring the prior
890
+ // single-leg behavior.
891
+ const runVoiceLeg = async (
892
+ legContent: string,
893
+ overrideProfile: string | undefined,
894
+ routingLeg: VoiceRoutingLeg | undefined,
895
+ ): Promise<string> => {
896
+ let legText = "";
897
+ // Once the front-door leg emits [ESCALATE], the leg is done as far as
898
+ // this turn is concerned: only the holding phrase preceding the marker
899
+ // reaches the caller, and nothing after the marker is spoken, recorded,
900
+ // or acted on. Guards against a model that ignores "stop after
901
+ // [ESCALATE]" and keeps answering.
902
+ let legSpeechSuppressed = false;
903
+ let legHandle: VoiceTurnHandle | null = null;
904
+ const turnComplete = new Promise<void>((resolve, reject) => {
905
+ const onTextDelta = (text: string): void => {
906
+ if (!this.isCurrentRun(runVersion)) return;
907
+ legText += text;
908
+ // After the marker, drop everything: not spoken, and not appended to
909
+ // fullResponseText — handleTurnCompletion scans that string for
910
+ // [END_CALL]/[ASK_GUARDIAN] and records it as the transcript, so an
911
+ // ignored weak answer must not reach it.
912
+ if (legSpeechSuppressed) return;
913
+ fullResponseText += text;
914
+ ttsBuffer += text;
915
+ if (routingLeg === "front-door") {
916
+ // Speak only up to the marker, then end this leg immediately.
917
+ const markerIdx = ttsBuffer.indexOf(ESCALATE_MARKER);
918
+ if (markerIdx !== -1) {
919
+ ttsBuffer = stripInternalSpeechMarkers(
920
+ ttsBuffer.slice(0, markerIdx),
921
+ );
922
+ flushSafeText();
923
+ ttsBuffer = "";
924
+ const fullMarkerIdx = fullResponseText.indexOf(ESCALATE_MARKER);
925
+ if (fullMarkerIdx !== -1) {
926
+ fullResponseText = fullResponseText.slice(0, fullMarkerIdx);
927
+ }
928
+ legSpeechSuppressed = true;
929
+ // Abort the front-door turn and settle the leg now so a model
930
+ // that keeps generating past the marker doesn't add silent
931
+ // latency before the escalated leg starts.
932
+ legHandle?.abort();
933
+ resolve();
934
+ return;
935
+ }
906
936
  }
907
- })
908
- .catch((err) => {
909
- reject(err);
910
- });
937
+ ttsBuffer = stripInternalSpeechMarkers(ttsBuffer);
938
+ flushSafeText();
939
+ };
911
940
 
912
- // Defensive: if the turn is aborted (e.g. barge-in) and the event
913
- // sink callbacks are never invoked, resolve the promise so it
914
- // doesn't hang forever.
915
- runSignal.addEventListener(
916
- "abort",
917
- () => {
941
+ const onComplete = (): void => {
918
942
  resolve();
919
- },
920
- { once: true },
921
- );
922
- });
943
+ };
923
944
 
924
- // Eagerly mark the rejection as handled so runtimes (e.g. bun) don't
925
- // flag it as an unhandled rejection when onError fires synchronously
926
- // inside the Promise constructor before this await adds its handler.
927
- // The await below still re-throws, caught by the outer try-catch.
928
- turnComplete.catch(() => {});
929
- try {
930
- await turnComplete;
931
- } catch (err) {
932
- // Cancel and settle this turn's synthesis before the error reaches
933
- // the outer handler, so no straggling segment plays the partial
934
- // answer over the recovery prompt. While this run is current no
935
- // newer run's synthesis can be in flight, so the abort is safe.
936
- if (this.isCurrentRun(runVersion)) {
937
- synthesisCancelled = true;
938
- this.abortActiveSynthesis();
945
+ const onError = (message: string): void => {
946
+ reject(new Error(message));
947
+ };
948
+
949
+ // Start the voice turn through the session bridge
950
+ startVoiceTurn({
951
+ conversationId: this.conversationId,
952
+ callSessionId: this.callSessionId,
953
+ content: legContent,
954
+ assistantId: this.assistantId,
955
+ trustContext: this.trustContext ?? undefined,
956
+ isInbound: this.isInbound,
957
+ task: this.task,
958
+ skipDisclosure: this.skipDisclosure,
959
+ onTextDelta,
960
+ onComplete,
961
+ onError,
962
+ signal: runSignal,
963
+ ...(overrideProfile != null ? { overrideProfile } : {}),
964
+ ...(routingLeg != null ? { routingLeg } : {}),
965
+ })
966
+ .then((handle) => {
967
+ legHandle = handle;
968
+ if (this.isCurrentRun(runVersion) && !legSpeechSuppressed) {
969
+ this.currentTurnHandle = handle;
970
+ } else {
971
+ // Turn was superseded, or the front-door leg already handed off
972
+ // before the handle arrived — abort immediately.
973
+ handle.abort();
974
+ }
975
+ })
976
+ .catch((err) => {
977
+ reject(err);
978
+ });
979
+
980
+ // Defensive: if the turn is aborted (e.g. barge-in) and the event
981
+ // sink callbacks are never invoked, resolve the promise so it
982
+ // doesn't hang forever.
983
+ runSignal.addEventListener(
984
+ "abort",
985
+ () => {
986
+ resolve();
987
+ },
988
+ { once: true },
989
+ );
990
+ });
991
+
992
+ // Eagerly mark the rejection as handled so runtimes (e.g. bun) don't
993
+ // flag it as an unhandled rejection when onError fires synchronously
994
+ // inside the Promise constructor before this await adds its handler.
995
+ // The await below still re-throws, caught by the outer try-catch.
996
+ turnComplete.catch(() => {});
997
+ try {
998
+ await turnComplete;
999
+ } catch (err) {
1000
+ // Cancel and settle this turn's synthesis before the error reaches
1001
+ // the outer handler, so no straggling segment plays the partial
1002
+ // answer over the recovery prompt. While this run is current no
1003
+ // newer run's synthesis can be in flight, so the abort is safe.
1004
+ if (this.isCurrentRun(runVersion)) {
1005
+ synthesisCancelled = true;
1006
+ this.abortActiveSynthesis();
1007
+ }
1008
+ await synthesisChain.catch(() => {});
1009
+ throw err;
939
1010
  }
940
- await synthesisChain.catch(() => {});
941
- throw err;
942
- }
1011
+ return legText;
1012
+ };
1013
+
1014
+ // Front-door leg: fast profile + triage rule when routing is on; otherwise
1015
+ // the caller utterance on the call-site default profile (today's behavior).
1016
+ const frontDoorText = await runVoiceLeg(
1017
+ content,
1018
+ escalateEnabled ? FRONT_DOOR_PROFILE : undefined,
1019
+ escalateEnabled ? "front-door" : undefined,
1020
+ );
943
1021
  if (!this.isCurrentRun(runVersion)) {
944
1022
  // Superseded mid-stream (barge-in): drain the segment chain — queued
945
1023
  // links short-circuit on staleness — so this turn's synthesis fully
@@ -948,6 +1026,46 @@ export class CallController {
948
1026
  return fullResponseText;
949
1027
  }
950
1028
 
1029
+ // Escalation: the front-door model handed off. Its holding phrase already
1030
+ // streamed to TTS and its onTextDelta stopped speaking, dropped the marker,
1031
+ // and aborted the leg. Clear any residual buffer before the quality leg as
1032
+ // a belt-and-suspenders guard.
1033
+ //
1034
+ // KNOWN LIMITATION (issue #37850): this suppression governs the caller's
1035
+ // AUDIO only. The bridge still broadcasts the front-door leg's raw
1036
+ // assistant_text_delta events (marker + any post-marker text) to the
1037
+ // conversation hub and persists them in the assistant message — the same
1038
+ // path [END_CALL]/[ASK_GUARDIAN] already take today, so a web/desktop
1039
+ // observer sees the raw markers on every voice turn. Stripping markers at
1040
+ // the broadcast/persist source is tracked separately.
1041
+ if (escalateEnabled && frontDoorText.includes(ESCALATE_MARKER)) {
1042
+ ttsBuffer = "";
1043
+ // If the front-door model emitted no meaningful holding phrase before the
1044
+ // marker, speak a canned bridge so the hand-off has no dead air.
1045
+ if (needsFallbackBridge(frontDoorText)) {
1046
+ emitSafeChunk(`${FALLBACK_ESCALATION_BRIDGE} `);
1047
+ }
1048
+ // Force-synthesize the bridge now. On the synthesized-TTS path text is
1049
+ // held in pendingSynthText until a sentence boundary, so an unpunctuated
1050
+ // bridge ("Give me one second") would otherwise sit unspoken until the
1051
+ // post-leg drain — leaving the caller in silence during the escalated
1052
+ // model's call, the exact gap the bridge exists to mask.
1053
+ if (synthProvider) {
1054
+ const { segments } = extractSpeakableSegments(pendingSynthText, true);
1055
+ pendingSynthText = "";
1056
+ enqueueSynthesisSegments(synthProvider, segments);
1057
+ }
1058
+ await runVoiceLeg(
1059
+ ESCALATION_CONTINUATION_CONTENT,
1060
+ ESCALATION_PROFILE,
1061
+ "escalated",
1062
+ );
1063
+ if (!this.isCurrentRun(runVersion)) {
1064
+ await synthesisChain.catch(() => {});
1065
+ return fullResponseText;
1066
+ }
1067
+ }
1068
+
951
1069
  // Final sweep: strip any remaining control markers from the buffer
952
1070
  ttsBuffer = stripInternalSpeechMarkers(ttsBuffer);
953
1071
  if (ttsBuffer.length > 0) {
@@ -14,6 +14,15 @@ export const CALL_OPENING_ACK_MARKER = "[CALL_OPENING_ACK]";
14
14
  export const CALL_VERIFICATION_COMPLETE_MARKER = "[CALL_VERIFICATION_COMPLETE]";
15
15
  export const END_CALL_MARKER = "[END_CALL]";
16
16
 
17
+ /**
18
+ * Emitted by the fast "front-door" model (triage-and-escalate voice routing)
19
+ * when a turn is too tricky for it to answer well. The front-door model speaks
20
+ * a brief holding phrase, appends this marker, and stops; the call controller
21
+ * then re-runs the turn on the stronger "quality" profile. Like the other
22
+ * markers, it is swallowed before reaching TTS — never spoken aloud.
23
+ */
24
+ export const ESCALATE_MARKER = "[ESCALATE]";
25
+
17
26
  // ---------------------------------------------------------------------------
18
27
  // Regexes
19
28
  // ---------------------------------------------------------------------------
@@ -31,6 +40,7 @@ const USER_INSTRUCTION_MARKER_REGEX = /\[USER_INSTRUCTION:\s*.+?\]/g;
31
40
  const CALL_OPENING_MARKER_REGEX = /\[CALL_OPENING\]/g;
32
41
  const CALL_OPENING_ACK_MARKER_REGEX = /\[CALL_OPENING_ACK\]/g;
33
42
  const END_CALL_MARKER_REGEX = /\[END_CALL\]/g;
43
+ const ESCALATE_MARKER_REGEX = /\[ESCALATE\]/g;
34
44
  const GUARDIAN_TIMEOUT_MARKER_REGEX = /\[GUARDIAN_TIMEOUT\]/g;
35
45
  const GUARDIAN_UNAVAILABLE_MARKER_REGEX = /\[GUARDIAN_UNAVAILABLE\]/g;
36
46
 
@@ -145,6 +155,7 @@ export function stripInternalSpeechMarkers(text: string): string {
145
155
  .replace(CALL_OPENING_MARKER_REGEX, "")
146
156
  .replace(CALL_OPENING_ACK_MARKER_REGEX, "")
147
157
  .replace(END_CALL_MARKER_REGEX, "")
158
+ .replace(ESCALATE_MARKER_REGEX, "")
148
159
  .replace(GUARDIAN_TIMEOUT_MARKER_REGEX, "")
149
160
  .replace(GUARDIAN_UNAVAILABLE_MARKER_REGEX, "");
150
161
  return result;
@@ -167,6 +178,7 @@ const CONTROL_MARKER_STRINGS = [
167
178
  "[CALL_OPENING]",
168
179
  "[CALL_OPENING_ACK]",
169
180
  "[END_CALL]",
181
+ "[ESCALATE]",
170
182
  "[GUARDIAN_TIMEOUT]",
171
183
  "[GUARDIAN_UNAVAILABLE]",
172
184
  ];
@@ -35,6 +35,12 @@ import {
35
35
  CALL_OPENING_MARKER,
36
36
  CALL_VERIFICATION_COMPLETE_MARKER,
37
37
  } from "./voice-control-protocol.js";
38
+ import {
39
+ escalatedContinuationRule,
40
+ ESCALATION_CONTINUATION_CONTENT,
41
+ frontDoorTriageRule,
42
+ type VoiceRoutingLeg,
43
+ } from "./voice-triage-escalate.js";
38
44
 
39
45
  const log = getLogger("voice-session-bridge");
40
46
 
@@ -200,6 +206,21 @@ export interface VoiceTurnOptions {
200
206
  callbacks?: VoiceTurnCallbacks;
201
207
  /** Optional AbortSignal for external cancellation (e.g. barge-in). */
202
208
  signal?: AbortSignal;
209
+ /**
210
+ * Ad-hoc inference-profile override applied to every LLM call this turn
211
+ * issues (forwarded to `runAgentLoop` with `forceOverrideProfile`). Used by
212
+ * triage-and-escalate voice routing to run the front-door leg on the fast
213
+ * profile and the escalated leg on the quality profile. Undefined = the
214
+ * call-site default (today's behavior).
215
+ */
216
+ overrideProfile?: string;
217
+ /**
218
+ * Which leg of a triaged turn this is, so the auto-built phone control prompt
219
+ * can add the front-door triage rule or the escalated continuation rule.
220
+ * Undefined = routing off; no routing rules are added. Ignored when a caller
221
+ * supplies its own `voiceControlPrompt`.
222
+ */
223
+ routingLeg?: VoiceRoutingLeg;
203
224
  }
204
225
 
205
226
  export interface VoiceTurnHandle {
@@ -226,6 +247,7 @@ function buildVoiceCallControlPrompt(opts: {
226
247
  task?: string | null;
227
248
  isCallerGuardian?: boolean;
228
249
  skipDisclosure?: boolean;
250
+ routingLeg?: VoiceRoutingLeg;
229
251
  }): string {
230
252
  const config = getConfig();
231
253
  const disclosureEnabled =
@@ -310,9 +332,19 @@ function buildVoiceCallControlPrompt(opts: {
310
332
  "9. After the opening greeting turn, treat the Task field as background context only — do not re-execute its instructions on subsequent turns.",
311
333
  '10. Do not make up information. If you are unsure, use [ASK_GUARDIAN: your question] to consult your guardian. For tool permission requests, use [ASK_GUARDIAN_APPROVAL: {"question":"...","toolName":"...","input":{...}}].',
312
334
  `11. Your text is sent directly to a text-to-speech engine. Never use markdown formatting (asterisks, headers, backticks, links) or emojis in your spoken responses. Write plain conversational text only. Protocol markers like ${opts.isCallerGuardian ? "[END_CALL]" : "[ASK_GUARDIAN: ...] and [END_CALL]"} are not spoken text and should still be used normally.`,
313
- "</voice_call_control>",
314
335
  );
315
336
 
337
+ // Triage-and-escalate routing rules (voice-triage-escalate flag). The
338
+ // front-door leg triages and may hand off; the escalated leg continues the
339
+ // answer after a holding phrase was already spoken.
340
+ if (opts.routingLeg === "front-door") {
341
+ lines.push(`12. ${frontDoorTriageRule()}`);
342
+ } else if (opts.routingLeg === "escalated") {
343
+ lines.push(`12. ${escalatedContinuationRule()}`);
344
+ }
345
+
346
+ lines.push("</voice_call_control>");
347
+
316
348
  return lines.join("\n");
317
349
  }
318
350
 
@@ -397,13 +429,25 @@ export async function startVoiceTurn(
397
429
  ? "(verification completed — transitioning into conversation)"
398
430
  : opts.content;
399
431
 
400
- // Opener / verification prompts are internal scaffolding: they persist a row
401
- // so the model wakes, but they are not user speech and must not render as a
402
- // live user bubble. Their echo is suppressed below (parity with
403
- // `isEchoSuppressedUserMessage` on the text path).
432
+ // Opener / verification / escalation-continuation prompts are internal
433
+ // scaffolding: they persist a row so the model wakes, but they are not user
434
+ // speech and must not render as a live user bubble. Their echo is suppressed
435
+ // below (parity with `isEchoSuppressedUserMessage` on the text path).
404
436
  const isSyntheticVoicePrompt =
405
437
  opts.content === CALL_OPENING_MARKER ||
406
- opts.content === CALL_VERIFICATION_COMPLETE_MARKER;
438
+ opts.content === CALL_VERIFICATION_COMPLETE_MARKER ||
439
+ opts.content === ESCALATION_CONTINUATION_CONTENT;
440
+
441
+ // The escalation-continuation prompt is a pure internal instruction ("give
442
+ // the full answer now"), not a real utterance and not the sort of scaffolding
443
+ // an opener is — it must never surface as a user message. Unlike the
444
+ // opener/verification rows (persisted un-hidden), persist it `hidden` so
445
+ // `/messages` filters it out after a refetch/reload, and flag the turn as a
446
+ // hidden prompt so prompt-as-user-speech consumers (e.g. title generation)
447
+ // skip it. The escalated model still sees the row in context — `hidden` only
448
+ // affects client display.
449
+ const isHiddenSyntheticPrompt =
450
+ opts.content === ESCALATION_CONTINUATION_CONTENT;
407
451
 
408
452
  // Build the call-control protocol prompt so the model knows how to emit
409
453
  // control markers (ASK_GUARDIAN, END_CALL, etc.) and recognize opener turns.
@@ -416,6 +460,7 @@ export async function startVoiceTurn(
416
460
  task: opts.task,
417
461
  isCallerGuardian,
418
462
  skipDisclosure: opts.skipDisclosure,
463
+ routingLeg: opts.routingLeg,
419
464
  })
420
465
  : opts.voiceControlPrompt;
421
466
 
@@ -541,6 +586,7 @@ export async function startVoiceTurn(
541
586
  const persistResult = await conversation.persistUserMessage({
542
587
  content: persistedContent,
543
588
  requestId,
589
+ ...(isHiddenSyntheticPrompt ? { metadata: { hidden: true } } : {}),
544
590
  });
545
591
  return persistResult.id;
546
592
  };
@@ -931,6 +977,21 @@ export async function startVoiceTurn(
931
977
  // Voice only reacts to the definitive tool_use_start event.
932
978
  },
933
979
  callSite: "callAgent",
980
+ // The escalation-continuation prompt is a transcript-suppressed machine
981
+ // signal (persisted `hidden`), so flag the turn to match — keeps
982
+ // prompt-as-user-speech consumers (e.g. title generation) from treating
983
+ // it as user speech.
984
+ ...(isHiddenSyntheticPrompt ? { isHiddenPrompt: true } : {}),
985
+ // Triage-and-escalate routing pins this turn to the fast front-door or
986
+ // strong escalation profile. `forceOverrideProfile` floats it above the
987
+ // callAgent call-site layers (callAgent is not `mainAgent`, so the
988
+ // override would otherwise sit below the call-site profile).
989
+ ...(opts.overrideProfile != null
990
+ ? {
991
+ overrideProfile: opts.overrideProfile,
992
+ forceOverrideProfile: true,
993
+ }
994
+ : {}),
934
995
  });
935
996
  if (lastError) {
936
997
  log.error(
@@ -0,0 +1,136 @@
1
+ /**
2
+ * Triage-and-escalate voice routing (weak -> strong model) — Phase 1.
3
+ *
4
+ * A fast "front-door" model fronts every phone-call turn. It answers simple
5
+ * turns outright (low first-token latency -> the caller hears audio fast).
6
+ * When a turn is too tricky, the front-door model speaks a brief natural
7
+ * holding phrase, appends the `[ESCALATE]` marker, and stops. The call
8
+ * controller then re-runs the same turn on the stronger "quality" model, whose
9
+ * answer streams into the same TTS pipe. Because the holding phrase is spoken,
10
+ * the caller never hears the quality model's think-time as silence.
11
+ *
12
+ * This module owns the routing policy in one place: the feature gate, the two
13
+ * profile keys, the leg-specific prompt fragments, and the fallback bridge.
14
+ *
15
+ * Phase 2/3 (not implemented here): fire the quality model the instant the
16
+ * marker is detected so its prefill overlaps the spoken bridge; model-generated
17
+ * (rather than canned) fallback bridges; a triage-threshold eval harness; and
18
+ * extending the orchestration to in-app live voice (`live-voice/`), which drives
19
+ * `startVoiceTurn` through its own session rather than the call controller.
20
+ */
21
+
22
+ import { isAssistantFeatureFlagEnabled } from "../config/assistant-feature-flags.js";
23
+ import type { DefaultProfileKey } from "../config/default-profile-names.js";
24
+ import { getConfig } from "../config/loader.js";
25
+ import type { AssistantConfig } from "../config/schema.js";
26
+ import {
27
+ ESCALATE_MARKER,
28
+ stripInternalSpeechMarkers,
29
+ } from "./voice-control-protocol.js";
30
+
31
+ /** Feature-flag key gating the whole behavior. Off by default. */
32
+ export const VOICE_TRIAGE_ESCALATE_FLAG = "voice-triage-escalate";
33
+
34
+ /** Fast/weak profile that fronts every turn when the flag is on. */
35
+ export const FRONT_DOOR_PROFILE: DefaultProfileKey = "cost-optimized";
36
+
37
+ /** Strong/quality profile a tricky turn escalates to. */
38
+ export const ESCALATION_PROFILE: DefaultProfileKey = "quality-optimized";
39
+
40
+ /**
41
+ * Which leg of a triaged turn a `startVoiceTurn` call represents. Undefined
42
+ * means routing is off and the turn runs exactly as it does today.
43
+ */
44
+ export type VoiceRoutingLeg = "front-door" | "escalated";
45
+
46
+ /**
47
+ * Spoken when the front-door model emits `[ESCALATE]` without a meaningful
48
+ * holding phrase of its own — guarantees the caller never hears dead air
49
+ * across the hand-off. When the model does speak its own bridge, that natural
50
+ * text is used instead and this is not injected.
51
+ */
52
+ export const FALLBACK_ESCALATION_BRIDGE =
53
+ "Let me think about that for a second.";
54
+
55
+ /**
56
+ * Minimum length (after marker stripping, trimmed) of the front-door leg's
57
+ * spoken text for it to count as a real bridge. Below this, the fallback
58
+ * bridge is injected before the quality leg runs.
59
+ */
60
+ export const MIN_SPOKEN_BRIDGE_CHARS = 3;
61
+
62
+ /**
63
+ * Whether a canned fallback bridge must be spoken before the escalated leg,
64
+ * given the front-door leg's full response text.
65
+ *
66
+ * Only the text BEFORE `[ESCALATE]` was actually spoken — the controller
67
+ * suppresses everything after the marker from TTS — so the decision is based on
68
+ * that slice, not the full response (which may carry ignored post-marker text
69
+ * the model emitted despite being told to stop). Without this, a bare
70
+ * `[ESCALATE]` followed by ignored weak text would skip the fallback and leave
71
+ * the caller in silence while the quality leg spins up.
72
+ */
73
+ export function needsFallbackBridge(frontDoorText: string): boolean {
74
+ const markerIdx = frontDoorText.indexOf(ESCALATE_MARKER);
75
+ const spokenBridge = stripInternalSpeechMarkers(
76
+ markerIdx === -1 ? frontDoorText : frontDoorText.slice(0, markerIdx),
77
+ ).trim();
78
+ return spokenBridge.length < MIN_SPOKEN_BRIDGE_CHARS;
79
+ }
80
+
81
+ /**
82
+ * The escalated leg runs as its own voice turn. Rather than re-persist the
83
+ * caller's utterance (it is already in history from the front-door leg), the
84
+ * escalated leg is driven by this synthetic, echo-suppressed continuation
85
+ * prompt — the same pattern the opener/verification synthetic prompts use. The
86
+ * quality model answers the caller's previous question, which sits in history
87
+ * just above it.
88
+ *
89
+ * Phase 2 could collapse the two legs into a single persisted turn; Phase 1
90
+ * keeps each leg a normal, independently-understood `startVoiceTurn`.
91
+ */
92
+ export const ESCALATION_CONTINUATION_CONTENT =
93
+ "(You just told the caller you needed a moment to think. Now give them your full, careful answer to their previous question — do not repeat the holding phrase.)";
94
+
95
+ /**
96
+ * Whether triage-and-escalate routing is active for this workspace.
97
+ * When false, every voice turn behaves exactly as before.
98
+ */
99
+ export function isVoiceTriageEscalateEnabled(
100
+ config: AssistantConfig = getConfig(),
101
+ ): boolean {
102
+ return isAssistantFeatureFlagEnabled(VOICE_TRIAGE_ESCALATE_FLAG, config);
103
+ }
104
+
105
+ /**
106
+ * Extra CALL PROTOCOL RULE injected into the front-door leg's control prompt.
107
+ * The decision must happen up front: the model triages BEFORE it starts
108
+ * answering so it never speaks half an answer and then bails — spoken audio
109
+ * cannot be un-said. Escalation triggers include anything needing careful
110
+ * reasoning, research, or a tool it is unsure of, so the weak model never
111
+ * fabricates an answer that actually required a tool.
112
+ */
113
+ export function frontDoorTriageRule(): string {
114
+ return [
115
+ "TRIAGE FIRST: Before you begin answering, judge whether this turn is within your reach.",
116
+ "If it is simple, conversational, or clearly factual, just answer it normally.",
117
+ "If it needs careful reasoning, research, multi-step work, or a tool you are unsure how to use,",
118
+ `do NOT attempt the answer. Instead say one short, natural holding phrase out loud (for example "${FALLBACK_ESCALATION_BRIDGE}" or "Give me one second to look into that"), then append ${ESCALATE_MARKER} and stop.`,
119
+ `Make this decision in your first words. Never start answering and then emit ${ESCALATE_MARKER}. Everything you say before ${ESCALATE_MARKER} is spoken to the caller; everything after it is discarded.`,
120
+ ].join(" ");
121
+ }
122
+
123
+ /**
124
+ * Extra CALL PROTOCOL RULE injected into the escalated (quality) leg's control
125
+ * prompt. The holding phrase has already been spoken, so the model must
126
+ * continue straight into the substantive answer.
127
+ */
128
+ export function escalatedContinuationRule(): string {
129
+ return [
130
+ "You have already spoken a brief holding phrase to the caller (something like",
131
+ `"${FALLBACK_ESCALATION_BRIDGE}").`,
132
+ "Continue directly into your actual answer now.",
133
+ 'Do NOT greet again, do NOT repeat the holding phrase, and do NOT say things like "as I was saying".',
134
+ `Never emit ${ESCALATE_MARKER} — you are the model that finishes the answer.`,
135
+ ].join(" ");
136
+ }
@@ -114,6 +114,14 @@
114
114
  "description": "Show the live voice conversation button in the composer",
115
115
  "defaultEnabled": false
116
116
  },
117
+ {
118
+ "id": "voice-triage-escalate",
119
+ "scope": "assistant",
120
+ "key": "voice-triage-escalate",
121
+ "label": "Voice Triage & Escalate",
122
+ "description": "Front phone-call turns with a fast model that answers simple turns and escalates tricky ones to the quality model, cutting perceived latency",
123
+ "defaultEnabled": false
124
+ },
117
125
  {
118
126
  "id": "fast-mode",
119
127
  "scope": "assistant",