@kuralle-syrinx/core 4.4.0 → 4.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (217) hide show
  1. package/dist/audio/alaw.d.ts +3 -0
  2. package/dist/audio/alaw.d.ts.map +1 -0
  3. package/dist/audio/alaw.js +53 -0
  4. package/dist/audio/alaw.js.map +1 -0
  5. package/dist/audio/g722.d.ts +39 -0
  6. package/dist/audio/g722.d.ts.map +1 -0
  7. package/dist/audio/g722.js +286 -0
  8. package/dist/audio/g722.js.map +1 -0
  9. package/dist/audio/index.d.ts +7 -0
  10. package/dist/audio/index.d.ts.map +1 -0
  11. package/dist/audio/index.js +8 -0
  12. package/dist/audio/index.js.map +1 -0
  13. package/dist/audio/loudness.d.ts +13 -0
  14. package/dist/audio/loudness.d.ts.map +1 -0
  15. package/dist/audio/loudness.js +65 -0
  16. package/dist/audio/loudness.js.map +1 -0
  17. package/dist/audio/mulaw.d.ts +3 -0
  18. package/dist/audio/mulaw.d.ts.map +1 -0
  19. package/dist/audio/mulaw.js +39 -0
  20. package/dist/audio/mulaw.js.map +1 -0
  21. package/dist/audio/pcm.d.ts +5 -0
  22. package/dist/audio/pcm.d.ts.map +1 -0
  23. package/dist/audio/pcm.js +40 -0
  24. package/dist/audio/pcm.js.map +1 -0
  25. package/dist/audio/resample.d.ts +12 -0
  26. package/dist/audio/resample.d.ts.map +1 -0
  27. package/dist/audio/resample.js +157 -0
  28. package/dist/audio/resample.js.map +1 -0
  29. package/dist/audio-envelope.d.ts +23 -0
  30. package/dist/audio-envelope.d.ts.map +1 -0
  31. package/dist/audio-envelope.js +114 -0
  32. package/dist/audio-envelope.js.map +1 -0
  33. package/dist/confidence-to-wait.d.ts +12 -0
  34. package/dist/confidence-to-wait.d.ts.map +1 -0
  35. package/dist/confidence-to-wait.js +18 -0
  36. package/dist/confidence-to-wait.js.map +1 -0
  37. package/dist/conversation-event.d.ts +19 -0
  38. package/dist/conversation-event.d.ts.map +1 -0
  39. package/dist/conversation-event.js +44 -0
  40. package/dist/conversation-event.js.map +1 -0
  41. package/dist/error-handler.d.ts +35 -0
  42. package/dist/error-handler.d.ts.map +1 -0
  43. package/dist/error-handler.js +136 -0
  44. package/dist/error-handler.js.map +1 -0
  45. package/dist/idle-timeout.d.ts +69 -0
  46. package/dist/idle-timeout.d.ts.map +1 -0
  47. package/dist/idle-timeout.js +149 -0
  48. package/dist/idle-timeout.js.map +1 -0
  49. package/dist/incremental-unit.d.ts +17 -0
  50. package/dist/incremental-unit.d.ts.map +1 -0
  51. package/dist/incremental-unit.js +5 -0
  52. package/dist/incremental-unit.js.map +1 -0
  53. package/dist/index.d.ts +47 -0
  54. package/dist/index.d.ts.map +1 -0
  55. package/dist/index.js +61 -0
  56. package/dist/index.js.map +1 -0
  57. package/dist/init-chain.d.ts +35 -0
  58. package/dist/init-chain.d.ts.map +1 -0
  59. package/dist/init-chain.js +102 -0
  60. package/dist/init-chain.js.map +1 -0
  61. package/dist/init-stage-order.d.ts +5 -0
  62. package/dist/init-stage-order.d.ts.map +1 -0
  63. package/dist/init-stage-order.js +74 -0
  64. package/dist/init-stage-order.js.map +1 -0
  65. package/dist/interaction-coordinator.d.ts +45 -0
  66. package/dist/interaction-coordinator.d.ts.map +1 -0
  67. package/dist/interaction-coordinator.js +197 -0
  68. package/dist/interaction-coordinator.js.map +1 -0
  69. package/dist/interaction-policy.d.ts +103 -0
  70. package/dist/interaction-policy.d.ts.map +1 -0
  71. package/dist/interaction-policy.js +6 -0
  72. package/dist/interaction-policy.js.map +1 -0
  73. package/dist/iu-ledger.d.ts +39 -0
  74. package/dist/iu-ledger.d.ts.map +1 -0
  75. package/dist/iu-ledger.js +90 -0
  76. package/dist/iu-ledger.js.map +1 -0
  77. package/dist/latency-filler-fixtures.d.ts +7 -0
  78. package/dist/latency-filler-fixtures.d.ts.map +1 -0
  79. package/dist/latency-filler-fixtures.js +10 -0
  80. package/dist/latency-filler-fixtures.js.map +1 -0
  81. package/dist/latency-filler.d.ts +29 -0
  82. package/dist/latency-filler.d.ts.map +1 -0
  83. package/dist/latency-filler.js +102 -0
  84. package/dist/latency-filler.js.map +1 -0
  85. package/dist/mode-switcher.d.ts +24 -0
  86. package/dist/mode-switcher.d.ts.map +1 -0
  87. package/dist/mode-switcher.js +83 -0
  88. package/dist/mode-switcher.js.map +1 -0
  89. package/dist/observability-observer.d.ts +36 -0
  90. package/dist/observability-observer.d.ts.map +1 -0
  91. package/dist/observability-observer.js +141 -0
  92. package/dist/observability-observer.js.map +1 -0
  93. package/dist/observability.d.ts +68 -0
  94. package/dist/observability.d.ts.map +1 -0
  95. package/dist/observability.js +70 -0
  96. package/dist/observability.js.map +1 -0
  97. package/dist/packet-factories.d.ts +58 -0
  98. package/dist/packet-factories.d.ts.map +1 -0
  99. package/dist/packet-factories.js +181 -0
  100. package/dist/packet-factories.js.map +1 -0
  101. package/dist/packets.d.ts +532 -0
  102. package/dist/packets.d.ts.map +1 -0
  103. package/dist/packets.js +51 -0
  104. package/dist/packets.js.map +1 -0
  105. package/dist/pipeline-bus.d.ts +92 -0
  106. package/dist/pipeline-bus.d.ts.map +1 -0
  107. package/dist/pipeline-bus.js +294 -0
  108. package/dist/pipeline-bus.js.map +1 -0
  109. package/dist/plugin-contract.d.ts +73 -0
  110. package/dist/plugin-contract.d.ts.map +1 -0
  111. package/dist/plugin-contract.js +30 -0
  112. package/dist/plugin-contract.js.map +1 -0
  113. package/dist/policies/defer.d.ts +11 -0
  114. package/dist/policies/defer.d.ts.map +1 -0
  115. package/dist/policies/defer.js +13 -0
  116. package/dist/policies/defer.js.map +1 -0
  117. package/dist/policies/rule-based.d.ts +35 -0
  118. package/dist/policies/rule-based.d.ts.map +1 -0
  119. package/dist/policies/rule-based.js +130 -0
  120. package/dist/policies/rule-based.js.map +1 -0
  121. package/dist/pricing.d.ts +34 -0
  122. package/dist/pricing.d.ts.map +1 -0
  123. package/dist/pricing.js +108 -0
  124. package/dist/pricing.js.map +1 -0
  125. package/dist/primary-speaker-fixtures.d.ts +12 -0
  126. package/dist/primary-speaker-fixtures.d.ts.map +1 -0
  127. package/dist/primary-speaker-fixtures.js +37 -0
  128. package/dist/primary-speaker-fixtures.js.map +1 -0
  129. package/dist/primary-speaker-gate.d.ts +42 -0
  130. package/dist/primary-speaker-gate.d.ts.map +1 -0
  131. package/dist/primary-speaker-gate.js +178 -0
  132. package/dist/primary-speaker-gate.js.map +1 -0
  133. package/dist/provider-fallback.d.ts +28 -0
  134. package/dist/provider-fallback.d.ts.map +1 -0
  135. package/dist/provider-fallback.js +72 -0
  136. package/dist/provider-fallback.js.map +1 -0
  137. package/dist/reasoner-hedge.d.ts +21 -0
  138. package/dist/reasoner-hedge.d.ts.map +1 -0
  139. package/dist/reasoner-hedge.js +170 -0
  140. package/dist/reasoner-hedge.js.map +1 -0
  141. package/dist/reasoner-route.d.ts +24 -0
  142. package/dist/reasoner-route.d.ts.map +1 -0
  143. package/dist/reasoner-route.js +87 -0
  144. package/dist/reasoner-route.js.map +1 -0
  145. package/dist/reasoner-session-store.d.ts +18 -0
  146. package/dist/reasoner-session-store.d.ts.map +1 -0
  147. package/dist/reasoner-session-store.js +21 -0
  148. package/dist/reasoner-session-store.js.map +1 -0
  149. package/dist/reasoner.d.ts +97 -0
  150. package/dist/reasoner.d.ts.map +1 -0
  151. package/dist/reasoner.js +9 -0
  152. package/dist/reasoner.js.map +1 -0
  153. package/dist/retry.d.ts +31 -0
  154. package/dist/retry.d.ts.map +1 -0
  155. package/dist/retry.js +83 -0
  156. package/dist/retry.js.map +1 -0
  157. package/dist/scheduler.d.ts +11 -0
  158. package/dist/scheduler.d.ts.map +1 -0
  159. package/dist/scheduler.js +20 -0
  160. package/dist/scheduler.js.map +1 -0
  161. package/dist/spend-cap.d.ts +27 -0
  162. package/dist/spend-cap.d.ts.map +1 -0
  163. package/dist/spend-cap.js +38 -0
  164. package/dist/spend-cap.js.map +1 -0
  165. package/dist/tts-playout-clock.d.ts +43 -0
  166. package/dist/tts-playout-clock.d.ts.map +1 -0
  167. package/dist/tts-playout-clock.js +125 -0
  168. package/dist/tts-playout-clock.js.map +1 -0
  169. package/dist/turn-arbiter.d.ts +41 -0
  170. package/dist/turn-arbiter.d.ts.map +1 -0
  171. package/dist/turn-arbiter.js +259 -0
  172. package/dist/turn-arbiter.js.map +1 -0
  173. package/dist/voice-agent-session-util.d.ts +60 -0
  174. package/dist/voice-agent-session-util.d.ts.map +1 -0
  175. package/dist/voice-agent-session-util.js +204 -0
  176. package/dist/voice-agent-session-util.js.map +1 -0
  177. package/dist/voice-agent-session.d.ts +435 -0
  178. package/dist/voice-agent-session.d.ts.map +1 -0
  179. package/dist/voice-agent-session.js +1597 -0
  180. package/dist/voice-agent-session.js.map +1 -0
  181. package/dist/voice-text.d.ts +46 -0
  182. package/dist/voice-text.d.ts.map +1 -0
  183. package/dist/voice-text.js +209 -0
  184. package/dist/voice-text.js.map +1 -0
  185. package/package.json +19 -6
  186. package/src/audio/alaw.test.ts +87 -0
  187. package/src/audio/audio.test.ts +285 -0
  188. package/src/audio/g722.test.ts +149 -0
  189. package/src/audio/loudness.test.ts +58 -0
  190. package/src/audio-envelope.test.ts +167 -0
  191. package/src/confidence-to-wait.test.ts +21 -0
  192. package/src/error-handler.test.ts +56 -0
  193. package/src/hedge-throwing-backend.test.ts +46 -0
  194. package/src/interaction-coordinator.test.ts +529 -0
  195. package/src/iu-ledger.test.ts +276 -0
  196. package/src/latency-filler.test.ts +62 -0
  197. package/src/observability-observer.test.ts +248 -0
  198. package/src/observability.test.ts +94 -0
  199. package/src/packet-factories.test.ts +126 -0
  200. package/src/pipeline-bus.g10.test.ts +145 -0
  201. package/src/pipeline-bus.test.ts +211 -0
  202. package/src/policies/defer.test.ts +86 -0
  203. package/src/policies/rule-based.test.ts +334 -0
  204. package/src/pricing.test.ts +226 -0
  205. package/src/primary-speaker-gate.test.ts +150 -0
  206. package/src/provider-fallback.test.ts +87 -0
  207. package/src/reasoner-hedge.test.ts +361 -0
  208. package/src/reasoner-route.test.ts +248 -0
  209. package/src/reasoner.test.ts +69 -0
  210. package/src/retry.test.ts +83 -0
  211. package/src/route-throwing-spec.test.ts +44 -0
  212. package/src/spend-cap.test.ts +114 -0
  213. package/src/tts-playout-clock.test.ts +125 -0
  214. package/src/turn-arbiter.characterization.test.ts +477 -0
  215. package/src/turn-arbiter.test.ts +762 -0
  216. package/src/voice-agent-session.test.ts +4165 -0
  217. package/src/voice-text.test.ts +156 -0
@@ -0,0 +1,334 @@
1
+ // SPDX-License-Identifier: MIT
2
+
3
+ import { describe, it, expect } from "vitest";
4
+ import { PipelineBusImpl } from "../pipeline-bus.js";
5
+ import { RuleBasedInteractionPolicy, type RuleBasedInteractionPolicyDeps } from "./rule-based.js";
6
+ import { PrimarySpeakerGate } from "../primary-speaker-gate.js";
7
+ import { TtsPlayoutClock } from "../tts-playout-clock.js";
8
+
9
+ async function createPolicy(
10
+ minInterruptionMs = 280,
11
+ opts?: {
12
+ pauseThenResolveBargeIn?: boolean;
13
+ backchannel?: RuleBasedInteractionPolicyDeps["backchannel"];
14
+ },
15
+ ) {
16
+ const bus = new PipelineBusImpl();
17
+ void bus.start();
18
+ const ttsPlayout = new TtsPlayoutClock();
19
+ const policy = new RuleBasedInteractionPolicy({
20
+ bus,
21
+ primarySpeakerGate: new PrimarySpeakerGate(),
22
+ ttsPlayout,
23
+ minInterruptionMs,
24
+ pauseThenResolveBargeIn: opts?.pauseThenResolveBargeIn,
25
+ backchannel: opts?.backchannel,
26
+ });
27
+ return { bus, ttsPlayout, policy };
28
+ }
29
+
30
+ function metricNames(bus: PipelineBusImpl): string[] {
31
+ const names: string[] = [];
32
+ bus.on("metric.conversation", (pkt) => {
33
+ names.push((pkt as unknown as { name: string }).name);
34
+ });
35
+ return names;
36
+ }
37
+
38
+ async function drainBus(): Promise<void> {
39
+ await new Promise((resolve) => setTimeout(resolve, 0));
40
+ }
41
+
42
+ describe("RuleBasedInteractionPolicy", () => {
43
+ it("parity vector: sustained speech commits interrupt at activity frame", async () => {
44
+ const { ttsPlayout, policy } = await createPolicy(280);
45
+ ttsPlayout.noteAudio("assistant-turn", 100, 1000);
46
+
47
+ const t0 = 2000;
48
+ expect(
49
+ policy.observe({
50
+ kind: "vad_speech_started",
51
+ contextId: "user",
52
+ timestampMs: t0,
53
+ confidence: 0.99,
54
+ interruptedContextId: "assistant-turn",
55
+ }),
56
+ ).toEqual([]);
57
+
58
+ expect(
59
+ policy.observe({
60
+ kind: "vad_speech_activity",
61
+ contextId: "user",
62
+ timestampMs: t0 + 300,
63
+ }),
64
+ ).toEqual([{ kind: "interrupt", interruptedContextId: "assistant-turn" }]);
65
+ });
66
+
67
+ it("suppresses short speech blip without interrupt decision", async () => {
68
+ const { bus, ttsPlayout, policy } = await createPolicy(280);
69
+ const metrics = metricNames(bus);
70
+ ttsPlayout.noteAudio("assistant-turn", 100, 1000);
71
+
72
+ const t0 = 3000;
73
+ policy.observe({
74
+ kind: "vad_speech_started",
75
+ contextId: "user",
76
+ timestampMs: t0,
77
+ confidence: 0.99,
78
+ interruptedContextId: "assistant-turn",
79
+ });
80
+ policy.observe({
81
+ kind: "vad_speech_activity",
82
+ contextId: "user",
83
+ timestampMs: t0 + 90,
84
+ });
85
+ const decisions = policy.observe({
86
+ kind: "vad_speech_ended",
87
+ contextId: "user",
88
+ timestampMs: t0 + 130,
89
+ hasActiveTts: true,
90
+ });
91
+ await drainBus();
92
+
93
+ expect(decisions).toEqual([]);
94
+ expect(metrics).toContain("interrupt.suppressed_short_speech");
95
+ });
96
+
97
+ it("suppresses backchannel interim without interrupt decision", async () => {
98
+ const { bus, ttsPlayout, policy } = await createPolicy(280);
99
+ const metrics = metricNames(bus);
100
+ ttsPlayout.noteAudio("assistant-turn", 100, 1000);
101
+
102
+ policy.observe({
103
+ kind: "vad_speech_started",
104
+ contextId: "user",
105
+ timestampMs: 2000,
106
+ confidence: 0.99,
107
+ interruptedContextId: "assistant-turn",
108
+ });
109
+ policy.observe({
110
+ kind: "stt_partial",
111
+ contextId: "user",
112
+ timestampMs: 2050,
113
+ text: "uh huh",
114
+ });
115
+ const decisions = policy.observe({
116
+ kind: "vad_speech_activity",
117
+ contextId: "user",
118
+ timestampMs: 2300,
119
+ });
120
+ await drainBus();
121
+
122
+ expect(decisions).toEqual([]);
123
+ expect(metrics).toContain("interrupt.suppressed_backchannel");
124
+ });
125
+
126
+ it("IP-C3: emits no backchannel on VAD/user-pause observations", async () => {
127
+ const { policy } = await createPolicy();
128
+
129
+ expect(
130
+ policy.observe({
131
+ kind: "vad_speech_ended",
132
+ contextId: "user",
133
+ timestampMs: 5000,
134
+ hasActiveTts: false,
135
+ }),
136
+ ).toEqual([]);
137
+ expect(
138
+ policy.observe({
139
+ kind: "vad_speech_activity",
140
+ contextId: "user",
141
+ timestampMs: 5100,
142
+ }),
143
+ ).toEqual([]);
144
+ });
145
+
146
+ it("IP-C3: emits exactly one cue on started → delayed and clears on complete", async () => {
147
+ const { policy } = await createPolicy();
148
+
149
+ policy.observe({
150
+ kind: "delegate_state",
151
+ contextId: "turn-1",
152
+ timestampMs: 1000,
153
+ toolCallPhase: "started",
154
+ });
155
+ expect(
156
+ policy.observe({
157
+ kind: "delegate_state",
158
+ contextId: "turn-1",
159
+ timestampMs: 3000,
160
+ toolCallPhase: "delayed",
161
+ }),
162
+ ).toEqual([{ kind: "backchannel", cue: "mm_hmm" }]);
163
+ expect(
164
+ policy.observe({
165
+ kind: "delegate_state",
166
+ contextId: "turn-1",
167
+ timestampMs: 3200,
168
+ toolCallPhase: "delayed",
169
+ }),
170
+ ).toEqual([]);
171
+ policy.observe({
172
+ kind: "delegate_state",
173
+ contextId: "turn-1",
174
+ timestampMs: 4000,
175
+ toolCallPhase: "complete",
176
+ });
177
+ policy.observe({
178
+ kind: "delegate_state",
179
+ contextId: "turn-1",
180
+ timestampMs: 5000,
181
+ toolCallPhase: "started",
182
+ });
183
+ expect(
184
+ policy.observe({
185
+ kind: "delegate_state",
186
+ contextId: "turn-1",
187
+ timestampMs: 7000,
188
+ toolCallPhase: "delayed",
189
+ }),
190
+ ).toEqual([{ kind: "backchannel", cue: "mm_hmm" }]);
191
+ });
192
+
193
+ it("IP-C3: suppresses backchannel when TTS is active or the user is speaking", async () => {
194
+ const { ttsPlayout, policy } = await createPolicy();
195
+ ttsPlayout.noteAudio("assistant-turn", 500, 1000);
196
+
197
+ policy.observe({
198
+ kind: "delegate_state",
199
+ contextId: "turn-1",
200
+ timestampMs: 1000,
201
+ toolCallPhase: "started",
202
+ });
203
+ expect(
204
+ policy.observe({
205
+ kind: "delegate_state",
206
+ contextId: "turn-1",
207
+ timestampMs: 3000,
208
+ toolCallPhase: "delayed",
209
+ }),
210
+ ).toEqual([]);
211
+
212
+ ttsPlayout.release("assistant-turn");
213
+ policy.observe({
214
+ kind: "delegate_state",
215
+ contextId: "turn-2",
216
+ timestampMs: 4000,
217
+ toolCallPhase: "started",
218
+ });
219
+ policy.observe({
220
+ kind: "vad_speech_started",
221
+ contextId: "user",
222
+ timestampMs: 4100,
223
+ confidence: 0.9,
224
+ interruptedContextId: "",
225
+ });
226
+ expect(
227
+ policy.observe({
228
+ kind: "delegate_state",
229
+ contextId: "turn-2",
230
+ timestampMs: 6000,
231
+ toolCallPhase: "delayed",
232
+ }),
233
+ ).toEqual([]);
234
+ });
235
+
236
+ it("IP-C3: reset clears delegate-gap backchannel state", async () => {
237
+ const { policy } = await createPolicy();
238
+
239
+ policy.observe({
240
+ kind: "delegate_state",
241
+ contextId: "turn-1",
242
+ timestampMs: 1000,
243
+ toolCallPhase: "started",
244
+ });
245
+ policy.reset("turn-1");
246
+ expect(
247
+ policy.observe({
248
+ kind: "delegate_state",
249
+ contextId: "turn-1",
250
+ timestampMs: 3000,
251
+ toolCallPhase: "delayed",
252
+ }),
253
+ ).toEqual([]);
254
+ });
255
+
256
+ it("reset clears pending state", async () => {
257
+ const { ttsPlayout, policy } = await createPolicy(280);
258
+ ttsPlayout.noteAudio("assistant-turn", 100, 1000);
259
+
260
+ const t0 = 4000;
261
+ policy.observe({
262
+ kind: "vad_speech_started",
263
+ contextId: "user",
264
+ timestampMs: t0,
265
+ confidence: 0.99,
266
+ interruptedContextId: "assistant-turn",
267
+ });
268
+ policy.reset("user");
269
+
270
+ const decisions = policy.observe({
271
+ kind: "vad_speech_activity",
272
+ contextId: "user",
273
+ timestampMs: t0 + 300,
274
+ });
275
+ expect(decisions).toEqual([]);
276
+ });
277
+
278
+ it("backchannel disabled returns empty decisions", async () => {
279
+ const { policy } = await createPolicy(280, { backchannel: { enabled: false } });
280
+
281
+ policy.observe({
282
+ kind: "delegate_state",
283
+ contextId: "turn-1",
284
+ timestampMs: 1000,
285
+ toolCallPhase: "started",
286
+ });
287
+ expect(
288
+ policy.observe({
289
+ kind: "delegate_state",
290
+ contextId: "turn-1",
291
+ timestampMs: 3000,
292
+ toolCallPhase: "delayed",
293
+ }),
294
+ ).toEqual([]);
295
+ });
296
+
297
+ it("backchannel cue-set knob selects first cue", async () => {
298
+ const { policy } = await createPolicy(280, { backchannel: { cues: ["uh_huh"] } });
299
+
300
+ policy.observe({
301
+ kind: "delegate_state",
302
+ contextId: "turn-1",
303
+ timestampMs: 1000,
304
+ toolCallPhase: "started",
305
+ });
306
+ expect(
307
+ policy.observe({
308
+ kind: "delegate_state",
309
+ contextId: "turn-1",
310
+ timestampMs: 3000,
311
+ toolCallPhase: "delayed",
312
+ }),
313
+ ).toEqual([{ kind: "backchannel", cue: "uh_huh" }]);
314
+ });
315
+
316
+ it("default backchannel cue is mm_hmm", async () => {
317
+ const { policy } = await createPolicy();
318
+
319
+ policy.observe({
320
+ kind: "delegate_state",
321
+ contextId: "turn-1",
322
+ timestampMs: 1000,
323
+ toolCallPhase: "started",
324
+ });
325
+ expect(
326
+ policy.observe({
327
+ kind: "delegate_state",
328
+ contextId: "turn-1",
329
+ timestampMs: 3000,
330
+ toolCallPhase: "delayed",
331
+ }),
332
+ ).toEqual([{ kind: "backchannel", cue: "mm_hmm" }]);
333
+ });
334
+ });
@@ -0,0 +1,226 @@
1
+ // SPDX-License-Identifier: MIT
2
+
3
+ import { describe, expect, it } from "vitest";
4
+
5
+ import type { UsageRecordedPacket } from "./packets.js";
6
+ import { costOf, DEFAULT_PRICE_CATALOG, type PriceCatalog } from "./pricing.js";
7
+
8
+ function usage(fields: Omit<UsageRecordedPacket, "kind" | "timestampMs">): UsageRecordedPacket {
9
+ return { kind: "usage.recorded", timestampMs: 1, ...fields };
10
+ }
11
+
12
+ describe("costOf", () => {
13
+ it("computes STT cost from audioSeconds × catalog rate", () => {
14
+ const packet = usage({
15
+ contextId: "t1",
16
+ stage: "stt",
17
+ provider: "deepgram",
18
+ model: "nova-3",
19
+ audioSeconds: 60,
20
+ });
21
+ const result = costOf(packet, DEFAULT_PRICE_CATALOG);
22
+ expect(result.unpriced).toBeUndefined();
23
+ expect(result.usd).toBeCloseTo(0.0077, 10);
24
+ });
25
+
26
+ it("computes LLM cost from input/output tokens", () => {
27
+ const packet = usage({
28
+ contextId: "t1",
29
+ stage: "llm",
30
+ provider: "openai",
31
+ model: "gpt-4.1-mini",
32
+ inputTokens: 1_000_000,
33
+ outputTokens: 500_000,
34
+ });
35
+ const result = costOf(packet, DEFAULT_PRICE_CATALOG);
36
+ expect(result.usd).toBeCloseTo(0.4 + 0.8, 10);
37
+ });
38
+
39
+ it("computes TTS cost from characters", () => {
40
+ const packet = usage({
41
+ contextId: "t1",
42
+ stage: "tts",
43
+ provider: "cartesia",
44
+ model: "sonic-3",
45
+ characters: 1_000_000,
46
+ });
47
+ const result = costOf(packet, DEFAULT_PRICE_CATALOG);
48
+ expect(result.usd).toBe(50);
49
+ });
50
+
51
+ it("returns unpriced (not 0) for unknown provider/model", () => {
52
+ const packet = usage({
53
+ contextId: "t1",
54
+ stage: "stt",
55
+ provider: "acme",
56
+ model: "mystery",
57
+ audioSeconds: 10,
58
+ });
59
+ expect(costOf(packet, DEFAULT_PRICE_CATALOG)).toEqual({ usd: null, unpriced: true });
60
+ });
61
+
62
+ it("prices new catalog providers (google STT, gemini TTS, elevenlabs)", () => {
63
+ const stt = costOf(
64
+ usage({
65
+ contextId: "t1",
66
+ stage: "stt",
67
+ provider: "google",
68
+ model: "latest_long",
69
+ audioSeconds: 60,
70
+ }),
71
+ DEFAULT_PRICE_CATALOG,
72
+ );
73
+ expect(stt.unpriced).toBeUndefined();
74
+ expect(stt.usd).toBeCloseTo(0.016, 10);
75
+
76
+ const tts = costOf(
77
+ usage({
78
+ contextId: "t1",
79
+ stage: "tts",
80
+ provider: "gemini",
81
+ model: "gemini-2.5-flash-preview-tts",
82
+ characters: 1_000_000,
83
+ }),
84
+ DEFAULT_PRICE_CATALOG,
85
+ );
86
+ expect(tts.unpriced).toBeUndefined();
87
+ expect(tts.usd).toBe(0.5);
88
+
89
+ const elTts = costOf(
90
+ usage({
91
+ contextId: "t1",
92
+ stage: "tts",
93
+ provider: "elevenlabs",
94
+ model: "eleven_flash_v2_5",
95
+ characters: 1_000_000,
96
+ }),
97
+ DEFAULT_PRICE_CATALOG,
98
+ );
99
+ expect(elTts.unpriced).toBeUndefined();
100
+ expect(elTts.usd).toBe(50);
101
+
102
+ const elStt = costOf(
103
+ usage({
104
+ contextId: "t1",
105
+ stage: "stt",
106
+ provider: "elevenlabs",
107
+ model: "scribe_v2_realtime",
108
+ audioSeconds: 3600,
109
+ }),
110
+ DEFAULT_PRICE_CATALOG,
111
+ );
112
+ expect(elStt.unpriced).toBeUndefined();
113
+ expect(elStt.usd).toBeCloseTo(0.39, 10);
114
+ });
115
+
116
+ it("returns unpriced for grok/epsilon providers with no public list price", () => {
117
+ expect(
118
+ costOf(
119
+ usage({
120
+ contextId: "t1",
121
+ stage: "stt",
122
+ provider: "grok",
123
+ model: "stt",
124
+ audioSeconds: 10,
125
+ }),
126
+ DEFAULT_PRICE_CATALOG,
127
+ ),
128
+ ).toEqual({ usd: null, unpriced: true });
129
+ expect(
130
+ costOf(
131
+ usage({
132
+ contextId: "t1",
133
+ stage: "tts",
134
+ provider: "grok",
135
+ model: "eve",
136
+ characters: 1000,
137
+ }),
138
+ DEFAULT_PRICE_CATALOG,
139
+ ),
140
+ ).toEqual({ usd: null, unpriced: true });
141
+ expect(
142
+ costOf(
143
+ usage({
144
+ contextId: "t1",
145
+ stage: "tts",
146
+ provider: "epsilon",
147
+ model: "epsilon-tts",
148
+ characters: 1000,
149
+ }),
150
+ DEFAULT_PRICE_CATALOG,
151
+ ),
152
+ ).toEqual({ usd: null, unpriced: true });
153
+ });
154
+
155
+ it("returns unpriced when provider or model is missing", () => {
156
+ const packet = usage({
157
+ contextId: "t1",
158
+ stage: "llm",
159
+ inputTokens: 100,
160
+ outputTokens: 10,
161
+ });
162
+ expect(costOf(packet, DEFAULT_PRICE_CATALOG)).toEqual({ usd: null, unpriced: true });
163
+ });
164
+
165
+ it("returns 0 for declared-local models", () => {
166
+ expect(
167
+ costOf(
168
+ usage({
169
+ contextId: "t1",
170
+ stage: "stt",
171
+ provider: "local",
172
+ model: "whisper",
173
+ audioSeconds: 100,
174
+ }),
175
+ DEFAULT_PRICE_CATALOG,
176
+ ),
177
+ ).toEqual({ usd: 0 });
178
+ expect(
179
+ costOf(
180
+ usage({
181
+ contextId: "t1",
182
+ stage: "tts",
183
+ provider: "local",
184
+ model: "tts",
185
+ characters: 50_000,
186
+ }),
187
+ DEFAULT_PRICE_CATALOG,
188
+ ),
189
+ ).toEqual({ usd: 0 });
190
+ expect(
191
+ costOf(
192
+ usage({
193
+ contextId: "t1",
194
+ stage: "llm",
195
+ provider: "local",
196
+ model: "llm",
197
+ inputTokens: 9_000,
198
+ outputTokens: 1_000,
199
+ }),
200
+ DEFAULT_PRICE_CATALOG,
201
+ ),
202
+ ).toEqual({ usd: 0 });
203
+ });
204
+
205
+ it("uses a custom catalog when provided", () => {
206
+ const catalog: PriceCatalog = {
207
+ source: "test",
208
+ version: "0",
209
+ stt: { "deepgram/nova-3": { usdPerAudioSecond: 1 } },
210
+ llm: {},
211
+ tts: {},
212
+ };
213
+ expect(
214
+ costOf(
215
+ usage({
216
+ contextId: "t1",
217
+ stage: "stt",
218
+ provider: "deepgram",
219
+ model: "nova-3",
220
+ audioSeconds: 2.5,
221
+ }),
222
+ catalog,
223
+ ),
224
+ ).toEqual({ usd: 2.5 });
225
+ });
226
+ });
@@ -0,0 +1,150 @@
1
+ // SPDX-License-Identifier: MIT
2
+
3
+ import { describe, expect, it, vi } from "vitest";
4
+ import {
5
+ PrimarySpeakerGate,
6
+ extractSpeakerFingerprint,
7
+ fingerprintSimilarity,
8
+ } from "./primary-speaker-gate.js";
9
+ import * as primarySpeakerGateModule from "./primary-speaker-gate.js";
10
+ import {
11
+ ASSISTANT_ECHO_TONE_HZ,
12
+ BYSTANDER_SPEAKER_TONE_HZ,
13
+ PRIMARY_SPEAKER_TONE_HZ,
14
+ mixPcm16,
15
+ synthesizeTonePcm16,
16
+ } from "./primary-speaker-fixtures.js";
17
+
18
+ describe("extractSpeakerFingerprint", () => {
19
+ it("separates distinct synthetic speakers by band shape", () => {
20
+ const primary = extractSpeakerFingerprint(
21
+ synthesizeTonePcm16({ frequencyHz: PRIMARY_SPEAKER_TONE_HZ, durationMs: 40 }),
22
+ );
23
+ const bystander = extractSpeakerFingerprint(
24
+ synthesizeTonePcm16({ frequencyHz: BYSTANDER_SPEAKER_TONE_HZ, durationMs: 40 }),
25
+ );
26
+ expect(primary).not.toBeNull();
27
+ expect(bystander).not.toBeNull();
28
+ const self = fingerprintSimilarity(primary!, primary!);
29
+ const cross = fingerprintSimilarity(primary!, bystander!);
30
+ expect(self).toBeGreaterThan(0.95);
31
+ expect(cross).toBeLessThan(0.72);
32
+ });
33
+ });
34
+
35
+ describe("PrimarySpeakerGate", () => {
36
+ it("commits barge-in for primary-only sustained speech", () => {
37
+ const gate = new PrimarySpeakerGate();
38
+ const primary = synthesizeTonePcm16({ frequencyHz: PRIMARY_SPEAKER_TONE_HZ, durationMs: 32 });
39
+ gate.enrollUserTurnChunk(primary);
40
+ gate.lockProfileFromFirstTurn();
41
+ gate.beginBargeInWindow();
42
+ for (let i = 0; i < 6; i += 1) {
43
+ gate.observeBargeInChunk(primary);
44
+ }
45
+ expect(gate.shouldCommitBargeIn()).toBe(true);
46
+ });
47
+
48
+ it("suppresses bystander sustained speech", () => {
49
+ const gate = new PrimarySpeakerGate();
50
+ gate.enrollUserTurnChunk(
51
+ synthesizeTonePcm16({ frequencyHz: PRIMARY_SPEAKER_TONE_HZ, durationMs: 32 }),
52
+ );
53
+ gate.lockProfileFromFirstTurn();
54
+ gate.beginBargeInWindow();
55
+ const bystander = synthesizeTonePcm16({ frequencyHz: BYSTANDER_SPEAKER_TONE_HZ, durationMs: 32 });
56
+ for (let i = 0; i < 8; i += 1) {
57
+ gate.observeBargeInChunk(bystander);
58
+ }
59
+ expect(gate.shouldCommitBargeIn()).toBe(false);
60
+ });
61
+
62
+ it("suppresses assistant echo over primary profile", () => {
63
+ const gate = new PrimarySpeakerGate();
64
+ gate.enrollUserTurnChunk(
65
+ synthesizeTonePcm16({ frequencyHz: PRIMARY_SPEAKER_TONE_HZ, durationMs: 32 }),
66
+ );
67
+ gate.lockProfileFromFirstTurn();
68
+ const echo = synthesizeTonePcm16({
69
+ frequencyHz: ASSISTANT_ECHO_TONE_HZ,
70
+ durationMs: 32,
71
+ amplitude: 0.2,
72
+ });
73
+ gate.observeAssistantPlayout(
74
+ synthesizeTonePcm16({ frequencyHz: ASSISTANT_ECHO_TONE_HZ, durationMs: 32 }),
75
+ );
76
+ gate.beginBargeInWindow();
77
+ for (let i = 0; i < 8; i += 1) {
78
+ gate.observeBargeInChunk(echo);
79
+ }
80
+ expect(gate.shouldCommitBargeIn()).toBe(false);
81
+ });
82
+
83
+ it("falls back to permissive commit when no profile is locked", () => {
84
+ const gate = new PrimarySpeakerGate();
85
+ gate.beginBargeInWindow();
86
+ gate.observeBargeInChunk(
87
+ synthesizeTonePcm16({ frequencyHz: BYSTANDER_SPEAKER_TONE_HZ, durationMs: 32 }),
88
+ );
89
+ expect(gate.hasProfile()).toBe(false);
90
+ expect(gate.shouldCommitBargeIn()).toBe(true);
91
+ });
92
+
93
+ it("commits barge-in when primary similarity beats echo even above threshold", () => {
94
+ const gate = new PrimarySpeakerGate({ similarityThreshold: 0.72, echoDominanceMargin: 0.12 });
95
+ const primary = synthesizeTonePcm16({ frequencyHz: PRIMARY_SPEAKER_TONE_HZ, durationMs: 32 });
96
+ gate.enrollUserTurnChunk(primary);
97
+ gate.lockProfileFromFirstTurn();
98
+ gate.observeAssistantPlayout(
99
+ synthesizeTonePcm16({ frequencyHz: ASSISTANT_ECHO_TONE_HZ, durationMs: 32 }),
100
+ );
101
+
102
+ const profile = (gate as unknown as { profile: NonNullable<ReturnType<typeof extractSpeakerFingerprint>> }).profile;
103
+ const assistantProfile = (gate as unknown as {
104
+ assistantProfile: NonNullable<ReturnType<typeof extractSpeakerFingerprint>>;
105
+ }).assistantProfile;
106
+
107
+ vi.spyOn(primarySpeakerGateModule, "fingerprintSimilarity").mockImplementation((_frame, reference) => {
108
+ if (reference === profile) return 0.95;
109
+ if (reference === assistantProfile) return 0.73;
110
+ return 0;
111
+ });
112
+
113
+ gate.beginBargeInWindow();
114
+ for (let i = 0; i < 6; i += 1) {
115
+ gate.observeBargeInChunk(primary);
116
+ }
117
+ expect(gate.shouldCommitBargeIn()).toBe(true);
118
+ vi.restoreAllMocks();
119
+ });
120
+
121
+ it("allows mixed audio when primary dominates", () => {
122
+ const gate = new PrimarySpeakerGate();
123
+ const primary = synthesizeTonePcm16({ frequencyHz: PRIMARY_SPEAKER_TONE_HZ, durationMs: 32 });
124
+ gate.enrollUserTurnChunk(primary);
125
+ gate.lockProfileFromFirstTurn();
126
+ const mixed = mixPcm16(
127
+ [
128
+ synthesizeTonePcm16({ frequencyHz: PRIMARY_SPEAKER_TONE_HZ, durationMs: 32 }),
129
+ synthesizeTonePcm16({ frequencyHz: BYSTANDER_SPEAKER_TONE_HZ, durationMs: 32, amplitude: 0.08 }),
130
+ ],
131
+ [1, 1],
132
+ );
133
+ gate.beginBargeInWindow();
134
+ for (let i = 0; i < 6; i += 1) {
135
+ gate.observeBargeInChunk(mixed);
136
+ }
137
+ expect(gate.shouldCommitBargeIn()).toBe(true);
138
+ });
139
+
140
+ it("mixes PCM chunks whose byteOffset is odd", () => {
141
+ const primary = synthesizeTonePcm16({ frequencyHz: PRIMARY_SPEAKER_TONE_HZ, durationMs: 32 });
142
+ const backing = new Uint8Array(primary.byteLength + 1);
143
+ backing.set(primary, 1);
144
+ const oddOffsetPrimary = backing.subarray(1);
145
+ expect(oddOffsetPrimary.byteOffset % 2).toBe(1);
146
+
147
+ expect(() => mixPcm16([oddOffsetPrimary], [1])).not.toThrow();
148
+ expect(mixPcm16([oddOffsetPrimary], [1])).toEqual(primary);
149
+ });
150
+ });