@vellumai/assistant 0.10.10-staging.1 → 0.10.10-staging.3

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.
@@ -250,9 +250,9 @@ describe("MediaStreamOutput", () => {
250
250
  expect(events).toContain("media");
251
251
  expect(events).toContain("mark");
252
252
 
253
- // The mark should be end-of-turn
253
+ // The mark should be the first sequenced end-of-turn mark
254
254
  const markMsg = sent.find((s) => JSON.parse(s).event === "mark");
255
- expect(JSON.parse(markMsg!).mark.name).toBe("end-of-turn");
255
+ expect(JSON.parse(markMsg!).mark.name).toBe("end-of-turn:1");
256
256
  });
257
257
 
258
258
  test("empty token with last: true sends only end-of-turn mark (no synthesis)", async () => {
@@ -266,7 +266,7 @@ describe("MediaStreamOutput", () => {
266
266
  expect(sent).toHaveLength(1);
267
267
  const parsed = JSON.parse(sent[0]);
268
268
  expect(parsed.event).toBe("mark");
269
- expect(parsed.mark.name).toBe("end-of-turn");
269
+ expect(parsed.mark.name).toBe("end-of-turn:1");
270
270
 
271
271
  // Synthesis should NOT have been called
272
272
  expect(mockSynthesize).not.toHaveBeenCalled();
@@ -514,6 +514,49 @@ describe("MediaStreamOutput", () => {
514
514
  output.clearBufferedAudio();
515
515
  expect(sent).toHaveLength(0);
516
516
  });
517
+
518
+ test("resolves a drain waiter for an end-of-turn mark already sent to Twilio", async () => {
519
+ // A mark sent to Twilio is dropped by `clear` and never echoes, so a
520
+ // pending end-call drain wait must resolve here rather than stall.
521
+ const { ws, sent } = createMockWs();
522
+ const output = makeOutput(ws, "MZ-stream-1");
523
+ output.sendTextToken("", true); // enqueues + sends end-of-turn:1
524
+ await drain(() => countEvents(sent, "mark") > 0);
525
+
526
+ const drained = output.awaitPlaybackDrained();
527
+ output.clearBufferedAudio();
528
+ await expect(drained).resolves.toBeUndefined();
529
+ });
530
+
531
+ test("does not resolve a drain waiter for an end-of-turn mark not yet sent", async () => {
532
+ // Slow synthesis keeps the mark queued locally (not yet sent to Twilio);
533
+ // clearBufferedAudio preserves it, so it will still play and echo.
534
+ mockSynthesize.mockImplementation(
535
+ () =>
536
+ new Promise((resolve) =>
537
+ setTimeout(
538
+ () =>
539
+ resolve({
540
+ audio: makeWavBuffer([1, 2, 3, 4]),
541
+ contentType: "audio/wav",
542
+ }),
543
+ 50,
544
+ ),
545
+ ),
546
+ );
547
+ const { ws } = createMockWs();
548
+ const output = makeOutput(ws, "MZ-stream-1");
549
+ output.sendTextToken("hello world", true); // mark queued behind synthesis
550
+
551
+ let resolved = false;
552
+ void output.awaitPlaybackDrained().then(() => {
553
+ resolved = true;
554
+ });
555
+
556
+ output.clearBufferedAudio(); // mark not sent yet — must stay pending
557
+ await drain();
558
+ expect(resolved).toBe(false);
559
+ });
517
560
  });
518
561
 
519
562
  describe("cancelPendingSpeech — turn abort", () => {
@@ -1567,4 +1610,217 @@ describe("MediaStreamOutput", () => {
1567
1610
  expect(countEvents(sent, "media")).toBe(1);
1568
1611
  });
1569
1612
  });
1613
+
1614
+ // ---------------------------------------------------------------------------
1615
+ // Playback drain tracking (sequenced end-of-turn marks)
1616
+ // ---------------------------------------------------------------------------
1617
+
1618
+ describe("playback drain", () => {
1619
+ /** Extract the names of all sent mark events, in order. */
1620
+ function markNames(sent: string[]): string[] {
1621
+ return sent
1622
+ .map((s) => JSON.parse(s))
1623
+ .filter((m) => m.event === "mark")
1624
+ .map((m) => m.mark.name);
1625
+ }
1626
+
1627
+ test("end-of-turn marks are sequenced in order", async () => {
1628
+ const { ws, sent } = createMockWs();
1629
+ const output = makeOutput(ws, "stream-1");
1630
+ output.sendTextToken("", true);
1631
+ output.sendTextToken("", true);
1632
+ output.sendTextToken("", true);
1633
+ await drain(() => countEvents(sent, "mark") >= 3);
1634
+
1635
+ expect(markNames(sent)).toEqual([
1636
+ "end-of-turn:1",
1637
+ "end-of-turn:2",
1638
+ "end-of-turn:3",
1639
+ ]);
1640
+ });
1641
+
1642
+ test("resolves immediately when no end-of-turn mark is outstanding", async () => {
1643
+ const { ws } = createMockWs();
1644
+ const output = makeOutput(ws, "stream-1");
1645
+ // Never enqueued a turn — nothing outstanding.
1646
+ await expect(output.awaitPlaybackDrained()).resolves.toBeUndefined();
1647
+ });
1648
+
1649
+ test("resolves immediately when the output is already closed", async () => {
1650
+ const { ws } = createMockWs();
1651
+ const output = makeOutput(ws, "stream-1");
1652
+ output.sendTextToken("", true); // outstanding seq 1, never echoed
1653
+ output.endSession();
1654
+ await expect(output.awaitPlaybackDrained()).resolves.toBeUndefined();
1655
+ });
1656
+
1657
+ test("stays pending until the matching end-of-turn mark is echoed", async () => {
1658
+ const { ws, sent } = createMockWs();
1659
+ const output = makeOutput(ws, "stream-1");
1660
+ output.sendTextToken("", true);
1661
+ await drain(() => countEvents(sent, "mark") > 0);
1662
+
1663
+ let resolved = false;
1664
+ const drained = output.awaitPlaybackDrained().then(() => {
1665
+ resolved = true;
1666
+ });
1667
+
1668
+ await drain();
1669
+ expect(resolved).toBe(false);
1670
+
1671
+ output.notePlaybackMarkEcho("end-of-turn:1");
1672
+ await drained;
1673
+ expect(resolved).toBe(true);
1674
+ });
1675
+
1676
+ test("a higher-seq echo (still within enqueued) resolves an earlier waiter", async () => {
1677
+ const { ws, sent } = createMockWs();
1678
+ const output = makeOutput(ws, "stream-1");
1679
+ output.sendTextToken("", true); // enqueues end-of-turn:1
1680
+ await drain(() => countEvents(sent, "mark") > 0);
1681
+
1682
+ const drained = output.awaitPlaybackDrained(); // targets seq 1
1683
+ output.sendTextToken("", true); // enqueues end-of-turn:2
1684
+ await drain(() => countEvents(sent, "mark") >= 2);
1685
+
1686
+ // Echoing seq 2 (which was enqueued) satisfies the seq-1 waiter too.
1687
+ output.notePlaybackMarkEcho("end-of-turn:2");
1688
+ await expect(drained).resolves.toBeUndefined();
1689
+ });
1690
+
1691
+ test("ignores an echo for a seq beyond what was enqueued", async () => {
1692
+ // A stale/forged future echo must not advance the high-water mark, or
1693
+ // later real turns would drain immediately before their audio played.
1694
+ const { ws, sent } = createMockWs();
1695
+ const output = makeOutput(ws, "stream-1");
1696
+ output.sendTextToken("", true); // enqueues end-of-turn:1
1697
+ await drain(() => countEvents(sent, "mark") > 0);
1698
+
1699
+ // Out-of-range echo before we ever queued seq 3 — ignored.
1700
+ output.notePlaybackMarkEcho("end-of-turn:3");
1701
+
1702
+ let resolved = false;
1703
+ void output.awaitPlaybackDrained().then(() => {
1704
+ resolved = true;
1705
+ });
1706
+ await drain();
1707
+ expect(resolved).toBe(false); // seq-1 waiter still pending
1708
+
1709
+ // The genuine seq-1 echo resolves it.
1710
+ output.notePlaybackMarkEcho("end-of-turn:1");
1711
+ await drain(() => resolved);
1712
+ expect(resolved).toBe(true);
1713
+ });
1714
+
1715
+ test("a stale lower-seq echo does not resolve a higher-seq waiter", async () => {
1716
+ const { ws, sent } = createMockWs();
1717
+ const output = makeOutput(ws, "stream-1");
1718
+ output.sendTextToken("", true);
1719
+ output.sendTextToken("", true);
1720
+ await drain(() => countEvents(sent, "mark") >= 2);
1721
+
1722
+ let resolved = false;
1723
+ void output.awaitPlaybackDrained().then(() => {
1724
+ resolved = true;
1725
+ });
1726
+
1727
+ output.notePlaybackMarkEcho("end-of-turn:1");
1728
+ await drain();
1729
+ expect(resolved).toBe(false);
1730
+
1731
+ output.notePlaybackMarkEcho("end-of-turn:2");
1732
+ await drain(() => resolved);
1733
+ expect(resolved).toBe(true);
1734
+ });
1735
+
1736
+ test("flushing the playback queue releases a pending waiter", async () => {
1737
+ const { ws, sent } = createMockWs();
1738
+ const output = makeOutput(ws, "stream-1");
1739
+ output.sendTextToken("", true);
1740
+ await drain(() => countEvents(sent, "mark") > 0);
1741
+
1742
+ const drained = output.awaitPlaybackDrained();
1743
+ output.clearAudio(); // flushes the playback queue
1744
+ await expect(drained).resolves.toBeUndefined();
1745
+ });
1746
+
1747
+ test("a waiter armed AFTER a flush does not hang on the flushed mark", async () => {
1748
+ // Barge-in flushes an outstanding end-of-turn mark before any waiter
1749
+ // exists. A later awaitPlaybackDrained() targeting that flushed seq
1750
+ // must resolve (the audio was cleared, never to be echoed) rather than
1751
+ // wait forever.
1752
+ const { ws, sent } = createMockWs();
1753
+ const output = makeOutput(ws, "stream-1");
1754
+ output.sendTextToken("", true); // enqueues end-of-turn:1
1755
+ await drain(() => countEvents(sent, "mark") > 0);
1756
+
1757
+ output.clearAudio(); // flushes end-of-turn:1 with no waiter present
1758
+
1759
+ await expect(output.awaitPlaybackDrained()).resolves.toBeUndefined();
1760
+ });
1761
+
1762
+ test("a late cleared-mark echo does not prematurely resolve a fresh turn", async () => {
1763
+ // After a flush advances the drained seq, a stale echo for the cleared
1764
+ // mark is a no-op, and the next turn's waiter still pends until its own
1765
+ // (higher-seq) mark is echoed.
1766
+ const { ws, sent } = createMockWs();
1767
+ const output = makeOutput(ws, "stream-1");
1768
+ output.sendTextToken("", true); // end-of-turn:1
1769
+ await drain(() => countEvents(sent, "mark") > 0);
1770
+ output.clearAudio(); // flush; drained seq advances to 1
1771
+
1772
+ output.sendTextToken("", true); // end-of-turn:2 (next turn)
1773
+ await drain(() => countEvents(sent, "mark") > 1);
1774
+
1775
+ let resolved = false;
1776
+ void output.awaitPlaybackDrained().then(() => {
1777
+ resolved = true;
1778
+ });
1779
+
1780
+ // Stale echo for the cleared mark must not resolve the seq-2 waiter.
1781
+ output.notePlaybackMarkEcho("end-of-turn:1");
1782
+ await drain();
1783
+ expect(resolved).toBe(false);
1784
+
1785
+ // The genuine seq-2 echo resolves it.
1786
+ output.notePlaybackMarkEcho("end-of-turn:2");
1787
+ await drain(() => resolved);
1788
+ expect(resolved).toBe(true);
1789
+ });
1790
+
1791
+ test("endSession releases a pending waiter", async () => {
1792
+ const { ws, sent } = createMockWs();
1793
+ const output = makeOutput(ws, "stream-1");
1794
+ output.sendTextToken("", true);
1795
+ await drain(() => countEvents(sent, "mark") > 0);
1796
+
1797
+ const drained = output.awaitPlaybackDrained();
1798
+ output.endSession();
1799
+ await expect(drained).resolves.toBeUndefined();
1800
+ });
1801
+
1802
+ test("ignores non-end-of-turn and malformed mark names without throwing", async () => {
1803
+ const { ws, sent } = createMockWs();
1804
+ const output = makeOutput(ws, "stream-1");
1805
+ output.sendTextToken("", true);
1806
+ await drain(() => countEvents(sent, "mark") > 0);
1807
+
1808
+ let resolved = false;
1809
+ void output.awaitPlaybackDrained().then(() => {
1810
+ resolved = true;
1811
+ });
1812
+
1813
+ // Unrelated mark name, wrong prefix, and non-numeric seq are ignored.
1814
+ output.notePlaybackMarkEcho("some-other-mark");
1815
+ output.notePlaybackMarkEcho("end-of-turn");
1816
+ output.notePlaybackMarkEcho("end-of-turn:not-a-number");
1817
+ await drain();
1818
+ expect(resolved).toBe(false);
1819
+
1820
+ // The real echo still resolves.
1821
+ output.notePlaybackMarkEcho("end-of-turn:1");
1822
+ await drain(() => resolved);
1823
+ expect(resolved).toBe(true);
1824
+ });
1825
+ });
1570
1826
  });
@@ -833,6 +833,27 @@ describe("MediaStreamCallSession", () => {
833
833
  session.handleMessage(makeMarkMessage("end-of-turn"));
834
834
  });
835
835
 
836
+ test("inbound mark echo is routed into the output drain tracker", () => {
837
+ const mock = createMockWs();
838
+ const session = new MediaStreamCallSession(mock.ws, "call-1");
839
+ const noteEcho = jest.spyOn(session.getOutput(), "notePlaybackMarkEcho");
840
+
841
+ session.handleMessage(makeMarkMessage("end-of-turn:3"));
842
+
843
+ expect(noteEcho).toHaveBeenCalledWith("end-of-turn:3");
844
+ });
845
+
846
+ test("mark echo after disposal does not touch the output", () => {
847
+ const mock = createMockWs();
848
+ const session = new MediaStreamCallSession(mock.ws, "call-1");
849
+ const noteEcho = jest.spyOn(session.getOutput(), "notePlaybackMarkEcho");
850
+
851
+ session.destroy();
852
+ session.handleMessage(makeMarkMessage("end-of-turn:3"));
853
+
854
+ expect(noteEcho).not.toHaveBeenCalled();
855
+ });
856
+
836
857
  test("stop events are forwarded to the STT session", () => {
837
858
  const mock = createMockWs();
838
859
  mockSessions.set("call-1", {
@@ -906,7 +927,7 @@ describe("media-stream output egress", () => {
906
927
  expect(markMessages.length).toBeGreaterThan(0);
907
928
 
908
929
  const markParsed = JSON.parse(markMessages[0]);
909
- expect(markParsed.mark.name).toBe("end-of-turn");
930
+ expect(markParsed.mark.name).toBe("end-of-turn:1");
910
931
  });
911
932
 
912
933
  test("empty sendTextToken (end-of-turn signal) sends only a mark, no media", async () => {
@@ -97,6 +97,15 @@ function makeDtmfMessage(digit = "5"): string {
97
97
  });
98
98
  }
99
99
 
100
+ function makeMarkMessage(name = "drain-1"): string {
101
+ return JSON.stringify({
102
+ event: "mark",
103
+ sequenceNumber: "4",
104
+ streamSid: "MZ00000000000000000000000000000000",
105
+ mark: { name },
106
+ });
107
+ }
108
+
100
109
  function makeStopMessage(): string {
101
110
  return JSON.stringify({
102
111
  event: "stop",
@@ -241,6 +250,44 @@ describe("MediaStreamSttSession", () => {
241
250
  session.dispose();
242
251
  });
243
252
 
253
+ // ── onMark ──────────────────────────────────────────────────────
254
+
255
+ test("fires onMark once with the mark name for mark events", () => {
256
+ const onMark = jest.fn();
257
+ const session = new MediaStreamSttSession({}, { onMark });
258
+
259
+ session.handleMessage(makeStartMessage());
260
+ session.handleMessage(makeMarkMessage("drain-42"));
261
+
262
+ expect(onMark).toHaveBeenCalledTimes(1);
263
+ expect(onMark).toHaveBeenCalledWith("drain-42");
264
+
265
+ session.dispose();
266
+ });
267
+
268
+ test("a session without onMark does not throw on mark events", () => {
269
+ const session = new MediaStreamSttSession({}, {});
270
+
271
+ session.handleMessage(makeStartMessage());
272
+ expect(() => session.handleMessage(makeMarkMessage())).not.toThrow();
273
+
274
+ session.dispose();
275
+ });
276
+
277
+ test("non-mark frames do not fire onMark", () => {
278
+ const onMark = jest.fn();
279
+ const session = new MediaStreamSttSession({}, { onMark, onDtmf: jest.fn() });
280
+
281
+ session.handleMessage(makeStartMessage());
282
+ session.handleMessage(makeMediaMessage());
283
+ session.handleMessage(makeDtmfMessage());
284
+ session.handleMessage(makeStopMessage());
285
+
286
+ expect(onMark).not.toHaveBeenCalled();
287
+
288
+ session.dispose();
289
+ });
290
+
244
291
  // ── onStop ───────────────────────────────────────────────────────
245
292
 
246
293
  test("fires onStop when stop event is received", () => {
@@ -0,0 +1,138 @@
1
+ /**
2
+ * Boot-time provider_connection backfill: an existing user connection for
3
+ * the entry's provider must win over the mode-derived default.
4
+ *
5
+ * On managed (platform-hosted) installs the mode default is the billed
6
+ * `vellum` connection — stamping it onto a connection-less BYOK-intent
7
+ * profile permanently routes the user's own-key setup through managed
8
+ * billing. On your-own installs the mode default creates a parallel
9
+ * `<provider>-personal` row with an empty credential slot even when a
10
+ * custom-named connection already exists.
11
+ */
12
+
13
+ import { writeFileSync } from "node:fs";
14
+ import { join } from "node:path";
15
+ import { afterEach, beforeEach, expect, test } from "bun:test";
16
+
17
+ import { loadRawConfig } from "../config/loader.js";
18
+ import { getDb } from "../persistence/db-connection.js";
19
+ import { initializeDb } from "../persistence/db-init.js";
20
+ import { providerConnections } from "../persistence/schema/index.js";
21
+ import { runProviderConnectionsBackfill } from "../providers/inference/backfill.js";
22
+ import {
23
+ createConnection,
24
+ getConnection,
25
+ listConnections,
26
+ } from "../providers/inference/connections.js";
27
+
28
+ await initializeDb();
29
+
30
+ const originalIsPlatform = process.env.IS_PLATFORM;
31
+
32
+ function seedConfig(profiles: Record<string, unknown>): void {
33
+ writeFileSync(
34
+ join(process.env.VELLUM_WORKSPACE_DIR!, "config.json"),
35
+ JSON.stringify({ llm: { profiles } }),
36
+ );
37
+ }
38
+
39
+ function backfilledConnection(profileName: string): unknown {
40
+ const llm = loadRawConfig().llm as {
41
+ profiles?: Record<string, Record<string, unknown>>;
42
+ };
43
+ return llm.profiles?.[profileName]?.provider_connection;
44
+ }
45
+
46
+ beforeEach(() => {
47
+ getDb().delete(providerConnections).run();
48
+ });
49
+
50
+ afterEach(() => {
51
+ if (originalIsPlatform === undefined) {
52
+ delete process.env.IS_PLATFORM;
53
+ } else {
54
+ process.env.IS_PLATFORM = originalIsPlatform;
55
+ }
56
+ });
57
+
58
+ test("managed mode prefers an existing user connection over the vellum default", () => {
59
+ process.env.IS_PLATFORM = "true";
60
+ const created = createConnection(getDb(), {
61
+ name: "anthropic-personal",
62
+ provider: "anthropic",
63
+ auth: { type: "api_key", credential: "credential/anthropic/api_key" },
64
+ });
65
+ expect(created.ok).toBe(true);
66
+ seedConfig({ byok: { provider: "anthropic", model: "claude-fable-5" } });
67
+
68
+ runProviderConnectionsBackfill(getDb());
69
+
70
+ expect(backfilledConnection("byok")).toBe("anthropic-personal");
71
+ });
72
+
73
+ test("managed mode still stamps vellum when no user connection exists", () => {
74
+ process.env.IS_PLATFORM = "true";
75
+ seedConfig({ byok: { provider: "anthropic", model: "claude-fable-5" } });
76
+
77
+ runProviderConnectionsBackfill(getDb());
78
+
79
+ expect(backfilledConnection("byok")).toBe("vellum");
80
+ });
81
+
82
+ test("managed-owned entries keep the vellum stamp even when a user connection exists", () => {
83
+ process.env.IS_PLATFORM = "true";
84
+ const created = createConnection(getDb(), {
85
+ name: "anthropic-personal",
86
+ provider: "anthropic",
87
+ auth: { type: "api_key", credential: "credential/anthropic/api_key" },
88
+ });
89
+ expect(created.ok).toBe(true);
90
+ seedConfig({
91
+ balanced: {
92
+ source: "managed",
93
+ provider: "anthropic",
94
+ model: "claude-sonnet-4-6",
95
+ },
96
+ // Legacy seeders wrote canonical entries without `source` — still
97
+ // managed-owned (workspace migration 109's rule).
98
+ "quality-optimized": {
99
+ provider: "anthropic",
100
+ model: "claude-opus-4-8",
101
+ },
102
+ // An explicit user source on a canonical name is a shadow the user took
103
+ // ownership of — the preference applies.
104
+ "cost-optimized": {
105
+ source: "user",
106
+ provider: "anthropic",
107
+ model: "claude-haiku-4-5-20251001",
108
+ },
109
+ byok: { provider: "anthropic", model: "claude-fable-5" },
110
+ });
111
+
112
+ runProviderConnectionsBackfill(getDb());
113
+
114
+ expect(backfilledConnection("balanced")).toBe("vellum");
115
+ expect(backfilledConnection("quality-optimized")).toBe("vellum");
116
+ expect(backfilledConnection("cost-optimized")).toBe("anthropic-personal");
117
+ expect(backfilledConnection("byok")).toBe("anthropic-personal");
118
+ });
119
+
120
+ test("your-own mode reuses a custom-named connection instead of creating -personal", () => {
121
+ delete process.env.IS_PLATFORM;
122
+ const created = createConnection(getDb(), {
123
+ name: "my-anthropic",
124
+ provider: "anthropic",
125
+ auth: { type: "api_key", credential: "credential/anthropic/api_key" },
126
+ });
127
+ expect(created.ok).toBe(true);
128
+ seedConfig({ byok: { provider: "anthropic", model: "claude-fable-5" } });
129
+
130
+ runProviderConnectionsBackfill(getDb());
131
+
132
+ expect(backfilledConnection("byok")).toBe("my-anthropic");
133
+ expect(getConnection(getDb(), "anthropic-personal")).toBeNull();
134
+ // Exactly the user's connection — no parallel row was created.
135
+ expect(
136
+ listConnections(getDb(), { provider: "anthropic" }).map((c) => c.name),
137
+ ).toEqual(["my-anthropic"]);
138
+ });
@@ -72,3 +72,8 @@ export function getSilenceTimeoutMs(): number {
72
72
  export function getEndCallListenWindowMs(): number {
73
73
  return 2 * 1000;
74
74
  }
75
+
76
+ /** Max time to wait for goodbye audio to drain before forcing hangup. */
77
+ export function getEndCallDrainMaxWaitMs(): number {
78
+ return 15 * 1000;
79
+ }