@vellumai/assistant 0.12.2-dev.202609181515.7e76c92 → 0.12.2-dev.202609181713.fb1ff61

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 (37) hide show
  1. package/ARCHITECTURE.md +4 -1
  2. package/package.json +1 -1
  3. package/src/__tests__/agent-loop-output-hooks.test.ts +150 -1
  4. package/src/__tests__/call-conversation-messages.test.ts +5 -0
  5. package/src/__tests__/call-recovery.test.ts +7 -2
  6. package/src/__tests__/call-routes-http.test.ts +12 -0
  7. package/src/__tests__/call-store.test.ts +7 -2
  8. package/src/__tests__/conversation-agent-loop-disk-pressure.test.ts +8 -2
  9. package/src/__tests__/conversation-agent-loop.test.ts +120 -2
  10. package/src/__tests__/deterministic-verification-control-plane.test.ts +2 -0
  11. package/src/__tests__/guardian-dispatch.test.ts +13 -0
  12. package/src/__tests__/notification-guardian-path.test.ts +7 -0
  13. package/src/__tests__/twilio-routes.test.ts +1 -0
  14. package/src/agent/loop.ts +76 -11
  15. package/src/calls/__tests__/call-controller.test.ts +94 -0
  16. package/src/calls/__tests__/call-funnel-telemetry.test.ts +204 -0
  17. package/src/{live-voice/__tests__/live-voice-metrics.test.ts → calls/__tests__/voice-metrics.test.ts} +32 -38
  18. package/src/calls/__tests__/voice-session-bridge.test.ts +342 -14
  19. package/src/calls/call-controller.ts +177 -1
  20. package/src/calls/call-domain.ts +4 -0
  21. package/src/calls/call-store.ts +87 -2
  22. package/src/calls/voice-escalation-target.ts +11 -0
  23. package/src/{live-voice/live-voice-metrics.ts → calls/voice-metrics.ts} +94 -87
  24. package/src/calls/voice-session-bridge.ts +140 -51
  25. package/src/daemon/conversation-agent-loop.ts +46 -18
  26. package/src/daemon/conversation.ts +80 -32
  27. package/src/live-voice/__tests__/live-activity-reporter.test.ts +154 -15
  28. package/src/live-voice/__tests__/live-voice-triage-escalate.test.ts +172 -0
  29. package/src/live-voice/live-activity-reporter.ts +115 -6
  30. package/src/live-voice/live-voice-session.ts +106 -31
  31. package/src/live-voice/protocol.ts +10 -2
  32. package/src/onboarding/onboarding-events-store.ts +99 -12
  33. package/src/plugin-api/vision-support.test.ts +22 -0
  34. package/src/plugin-api/vision-support.ts +17 -5
  35. package/src/runtime/routes/conversation-routes.ts +1 -1
  36. package/src/telemetry/__tests__/phone-call-funnel.test.ts +72 -0
  37. package/src/telemetry/phone-call-funnel.ts +144 -0
@@ -158,6 +158,7 @@ describe("guardian-dispatch", () => {
158
158
  ensureConversation(convId);
159
159
 
160
160
  const session = createCallSession({
161
+ direction: "inbound",
161
162
  conversationId: convId,
162
163
  provider: "twilio",
163
164
  fromNumber: "+15550001111",
@@ -209,6 +210,7 @@ describe("guardian-dispatch", () => {
209
210
  ensureConversation(convId);
210
211
 
211
212
  const session = createCallSession({
213
+ direction: "inbound",
212
214
  conversationId: convId,
213
215
  provider: "twilio",
214
216
  fromNumber: "+15550001111",
@@ -238,6 +240,7 @@ describe("guardian-dispatch", () => {
238
240
  ensureConversation(convId);
239
241
 
240
242
  const session = createCallSession({
243
+ direction: "inbound",
241
244
  conversationId: convId,
242
245
  provider: "twilio",
243
246
  fromNumber: "+15550001111",
@@ -282,6 +285,7 @@ describe("guardian-dispatch", () => {
282
285
  };
283
286
 
284
287
  const session = createCallSession({
288
+ direction: "inbound",
285
289
  conversationId: convId,
286
290
  provider: "twilio",
287
291
  fromNumber: "+15550001111",
@@ -324,6 +328,7 @@ describe("guardian-dispatch", () => {
324
328
  };
325
329
 
326
330
  const session = createCallSession({
331
+ direction: "inbound",
327
332
  conversationId: convId,
328
333
  provider: "twilio",
329
334
  fromNumber: "+15550001111",
@@ -369,6 +374,7 @@ describe("guardian-dispatch", () => {
369
374
  };
370
375
 
371
376
  const session = createCallSession({
377
+ direction: "inbound",
372
378
  conversationId: convId,
373
379
  provider: "twilio",
374
380
  fromNumber: "+15550001111",
@@ -396,6 +402,7 @@ describe("guardian-dispatch", () => {
396
402
  ensureConversation(convId);
397
403
 
398
404
  const session = createCallSession({
405
+ direction: "inbound",
399
406
  conversationId: convId,
400
407
  provider: "twilio",
401
408
  fromNumber: "+15550001111",
@@ -431,6 +438,7 @@ describe("guardian-dispatch", () => {
431
438
  ensureConversation(convId);
432
439
 
433
440
  const session = createCallSession({
441
+ direction: "inbound",
434
442
  conversationId: convId,
435
443
  provider: "twilio",
436
444
  fromNumber: "+15550001111",
@@ -456,6 +464,7 @@ describe("guardian-dispatch", () => {
456
464
  ensureConversation(convId);
457
465
 
458
466
  const session = createCallSession({
467
+ direction: "inbound",
459
468
  conversationId: convId,
460
469
  provider: "twilio",
461
470
  fromNumber: "+15550001111",
@@ -488,6 +497,7 @@ describe("guardian-dispatch", () => {
488
497
  const sharedConversationId = "conv-shared-guardian";
489
498
 
490
499
  const session = createCallSession({
500
+ direction: "inbound",
491
501
  conversationId: convId,
492
502
  provider: "twilio",
493
503
  fromNumber: "+15550001111",
@@ -576,6 +586,7 @@ describe("guardian-dispatch", () => {
576
586
  const sharedConversationId = "conv-affinity-guardian";
577
587
 
578
588
  const session = createCallSession({
589
+ direction: "inbound",
579
590
  conversationId: convId,
580
591
  provider: "twilio",
581
592
  fromNumber: "+15550001111",
@@ -648,6 +659,7 @@ describe("guardian-dispatch", () => {
648
659
  const sharedConversationId = "conv-affinity-tool-guardian";
649
660
 
650
661
  const session = createCallSession({
662
+ direction: "inbound",
651
663
  conversationId: convId,
652
664
  provider: "twilio",
653
665
  fromNumber: "+15550001111",
@@ -727,6 +739,7 @@ describe("guardian-dispatch", () => {
727
739
  const sharedConversationId = "conv-affinity-triple";
728
740
 
729
741
  const session = createCallSession({
742
+ direction: "inbound",
730
743
  conversationId: convId,
731
744
  provider: "twilio",
732
745
  fromNumber: "+15550001111",
@@ -160,6 +160,7 @@ describe("ASK_GUARDIAN notification path", () => {
160
160
  ensureConversation(convId);
161
161
 
162
162
  const session = createCallSession({
163
+ direction: "inbound",
163
164
  conversationId: convId,
164
165
  provider: "twilio",
165
166
  fromNumber: "+15550001111",
@@ -220,6 +221,7 @@ describe("ASK_GUARDIAN notification path", () => {
220
221
  };
221
222
 
222
223
  const session = createCallSession({
224
+ direction: "inbound",
223
225
  conversationId: convId,
224
226
  provider: "twilio",
225
227
  fromNumber: "+15550001111",
@@ -263,6 +265,7 @@ describe("ASK_GUARDIAN notification path", () => {
263
265
  };
264
266
 
265
267
  const session = createCallSession({
268
+ direction: "inbound",
266
269
  conversationId: convId,
267
270
  provider: "twilio",
268
271
  fromNumber: "+15550001111",
@@ -308,6 +311,7 @@ describe("ASK_GUARDIAN notification path", () => {
308
311
  };
309
312
 
310
313
  const session = createCallSession({
314
+ direction: "inbound",
311
315
  conversationId: convId,
312
316
  provider: "twilio",
313
317
  fromNumber: "+15550001111",
@@ -338,6 +342,7 @@ describe("ASK_GUARDIAN notification path", () => {
338
342
  ensureConversation(convId);
339
343
 
340
344
  const session = createCallSession({
345
+ direction: "inbound",
341
346
  conversationId: convId,
342
347
  provider: "twilio",
343
348
  fromNumber: "+15550001111",
@@ -370,6 +375,7 @@ describe("ASK_GUARDIAN notification path", () => {
370
375
  const sharedConvId = "conv-guardian-shared-thread";
371
376
 
372
377
  const session = createCallSession({
378
+ direction: "inbound",
373
379
  conversationId: convId,
374
380
  provider: "twilio",
375
381
  fromNumber: "+15550001111",
@@ -463,6 +469,7 @@ describe("ASK_GUARDIAN notification path", () => {
463
469
  };
464
470
 
465
471
  const session = createCallSession({
472
+ direction: "inbound",
466
473
  conversationId: convId,
467
474
  provider: "twilio",
468
475
  fromNumber: "+15550001111",
@@ -387,6 +387,7 @@ function createTestSession(
387
387
  ) {
388
388
  ensureConversation(convId);
389
389
  const session = createCallSession({
390
+ direction: "inbound",
390
391
  conversationId: convId,
391
392
  provider: "twilio",
392
393
  fromNumber: "+14155550111",
package/src/agent/loop.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  import type { AnsweredQuestion } from "../api/events/question-answered.js";
2
+ import { resolveCallSiteConfig } from "../config/llm-resolver.js";
3
+ import { getConfig } from "../config/loader.js";
2
4
  import type { LLMCallSite } from "../config/schemas/llm.js";
3
5
  import { SEND_USER_MESSAGE_TOOL_NAME } from "../config/send-user-message-constants.js";
4
6
  import { recordEstimate } from "../context/estimator-calibration.js";
@@ -664,6 +666,18 @@ type AgentLoopContextWindowResolver = () => {
664
666
  overflowRecovery: { enabled: boolean; safetyMarginRatio: number };
665
667
  };
666
668
 
669
+ /** Final request surface after the pre-model hook has settled. */
670
+ export interface PreparedModelCall {
671
+ callSite?: LLMCallSite;
672
+ overrideProfile?: string;
673
+ forceOverrideProfile: boolean;
674
+ /** Present when the finalized route opts out of prompt caching. */
675
+ disableCache?: true;
676
+ signal?: AbortSignal;
677
+ systemPrompt: string | null;
678
+ tools: ToolDefinition[];
679
+ }
680
+
667
681
  interface AgentLoopRunOptionsBase {
668
682
  /** Input history the run starts from; the loop appends its output onto a copy. */
669
683
  messages: Message[];
@@ -691,7 +705,10 @@ interface AgentLoopRunOptionsBase {
691
705
  onCheckpoint?: (
692
706
  checkpoint: CheckpointInfo,
693
707
  ) => CheckpointDecision | Promise<CheckpointDecision>;
708
+ /** Semantic call site exposed to hooks, events, and loop behavior. */
694
709
  callSite?: LLMCallSite;
710
+ /** Provider-resolution call site when it differs from turn semantics. */
711
+ inferenceCallSite?: LLMCallSite;
695
712
  /**
696
713
  * Route this run's user-facing text through the `send_user_message` tool
697
714
  * instead of streamed assistant text. The daemon sets it for main-agent runs
@@ -741,6 +758,8 @@ interface AgentLoopRunOptionsBase {
741
758
  */
742
759
  forceOverrideProfile?: boolean;
743
760
  resolveOverrideProfile?: () => string | undefined;
761
+ /** Observe a finalized model request without delaying provider dispatch. */
762
+ onModelCallPrepared?: (prepared: PreparedModelCall) => void;
744
763
  /**
745
764
  * When `true`, the loop owns turn-start and mid-loop compaction. The pre-call
746
765
  * budget gate runs before the very first provider call — subsuming the
@@ -1430,18 +1449,21 @@ export class AgentLoop {
1430
1449
  requestId,
1431
1450
  onCheckpoint,
1432
1451
  callSite,
1452
+ inferenceCallSite,
1433
1453
  suppressAssistantText = false,
1434
1454
  supportsDynamicUi = true,
1435
1455
  trust,
1436
1456
  overrideProfile,
1437
1457
  forceOverrideProfile = false,
1438
1458
  resolveOverrideProfile,
1459
+ onModelCallPrepared,
1439
1460
  compactInPlace = false,
1440
1461
  isNonInteractive = false,
1441
1462
  model: runModel,
1442
1463
  latencyTracker,
1443
1464
  injectionLedgerResets,
1444
1465
  } = options;
1466
+ const providerCallSite = inferenceCallSite ?? callSite;
1445
1467
  // Snapshot the system prompt once per run. The instance field is mutable
1446
1468
  // (the conversation may update it between turns), but a single run must
1447
1469
  // use one consistent prompt — an aborted run left detached after the
@@ -1887,7 +1909,7 @@ export class AgentLoop {
1887
1909
  // unexecutable client tool. The advisor consult's `advisorProfile` can
1888
1910
  // route `subagentSpawn` to a provider/model whose native-search support
1889
1911
  // differs from the construction-time default, so the gate resolves the
1890
- // routed target (callSite + overrideProfile) via
1912
+ // routed target (providerCallSite + overrideProfile) via
1891
1913
  // `supportsNativeWebSearchFor` rather than the static
1892
1914
  // `this.provider.supportsNativeWebSearch` snapshot; providers without
1893
1915
  // the routing-aware probe fall back to the static flag. This is a SERVER
@@ -1899,7 +1921,7 @@ export class AgentLoop {
1899
1921
  .supportsNativeWebSearchFor
1900
1922
  ? this.provider.supportsNativeWebSearchFor(
1901
1923
  buildNativeWebSearchProbeOptions(
1902
- callSite,
1924
+ providerCallSite,
1903
1925
  resolveEffectiveOverrideProfile(),
1904
1926
  forceOverrideProfile,
1905
1927
  this.conversationId,
@@ -1918,11 +1940,11 @@ export class AgentLoop {
1918
1940
  // 1. Per-run explicit (`runModel`)
1919
1941
  // 2. Call-site resolved values (filled by
1920
1942
  // `RetryProvider.normalizeSendMessageOptions` from
1921
- // `resolveCallSiteConfig(callSite, llm)`)
1943
+ // `resolveCallSiteConfig(providerCallSite, llm)`)
1922
1944
  // 3. Conversation defaults (`this.config.*`, from the resolved
1923
1945
  // default call-site config)
1924
1946
  //
1925
- // When `callSite` is present we deliberately leave
1947
+ // When `providerCallSite` is present we deliberately leave
1926
1948
  // `max_tokens`/`thinking`/`effort`/`speed` *unset* in `providerConfig`
1927
1949
  // so the normalizer can fill them from the call-site resolution. The
1928
1950
  // normalizer only writes these fields when they're undefined; if we
@@ -1930,10 +1952,10 @@ export class AgentLoop {
1930
1952
  // for these knobs is silently ignored.
1931
1953
  //
1932
1954
  // `toolChoice` and `cacheTtl` are not part of the call-site schema, so
1933
- // they always come from `this.config` regardless of `callSite`.
1955
+ // they always come from `this.config` regardless of `providerCallSite`.
1934
1956
  const providerConfig: Record<string, unknown> = {};
1935
1957
 
1936
- if (!callSite) {
1958
+ if (!providerCallSite) {
1937
1959
  providerConfig.max_tokens = this.config.maxTokens;
1938
1960
  }
1939
1961
 
@@ -1941,7 +1963,7 @@ export class AgentLoop {
1941
1963
  providerConfig.model = runModel;
1942
1964
  }
1943
1965
 
1944
- if (!callSite) {
1966
+ if (!providerCallSite) {
1945
1967
  const thinking = normalizeThinkingConfigForWire(this.config.thinking);
1946
1968
  if (thinking !== undefined) {
1947
1969
  providerConfig.thinking = thinking;
@@ -1980,9 +2002,9 @@ export class AgentLoop {
1980
2002
  // defaults when absent).
1981
2003
  // User-initiated conversation turns default to `mainAgent` in the
1982
2004
  // agent loop's caller; other invocation contexts (heartbeat, filing,
1983
- // analyze, etc.) pass their own `callSite`.
1984
- if (callSite) {
1985
- providerConfig.callSite = callSite;
2005
+ // analyze, etc.) pass their own provider-resolution site.
2006
+ if (providerCallSite) {
2007
+ providerConfig.callSite = providerCallSite;
1986
2008
  providerConfig.usageTracking = "manual";
1987
2009
  // Per-conversation seed for deterministic `mix`-profile expansion.
1988
2010
  // Sourced from the loop's own conversation id so every LLM call in a
@@ -2010,7 +2032,7 @@ export class AgentLoop {
2010
2032
  // `activeProfile` and any call-site named profile. Threading it on
2011
2033
  // every send (rather than once at construction) keeps subagents that
2012
2034
  // share an `AgentLoop` instance but ought to inherit a different
2013
- // profile correct — and matches how `callSite` is plumbed.
2035
+ // profile correct, matching how the provider call site is plumbed.
2014
2036
  const effectiveOverrideProfile = resolveEffectiveOverrideProfile();
2015
2037
  if (effectiveOverrideProfile) {
2016
2038
  providerConfig.overrideProfile = effectiveOverrideProfile;
@@ -2234,6 +2256,49 @@ export class AgentLoop {
2234
2256
  );
2235
2257
  }
2236
2258
 
2259
+ if (onModelCallPrepared && !signal?.aborted) {
2260
+ const preparedOverrideProfile =
2261
+ typeof providerConfig.overrideProfile === "string" &&
2262
+ providerConfig.overrideProfile.length > 0
2263
+ ? providerConfig.overrideProfile
2264
+ : undefined;
2265
+ try {
2266
+ const preparedForceOverrideProfile =
2267
+ providerConfig.forceOverrideProfile === true;
2268
+ const disableCache =
2269
+ providerCallSite !== undefined &&
2270
+ resolveCallSiteConfig(providerCallSite, getConfig().llm, {
2271
+ ...(preparedOverrideProfile !== undefined
2272
+ ? { overrideProfile: preparedOverrideProfile }
2273
+ : {}),
2274
+ ...(preparedForceOverrideProfile
2275
+ ? { forceOverrideProfile: true }
2276
+ : {}),
2277
+ ...(this.conversationId !== undefined
2278
+ ? { selectionSeed: this.conversationId }
2279
+ : {}),
2280
+ }).disableCache === true;
2281
+ onModelCallPrepared({
2282
+ ...(providerCallSite !== undefined
2283
+ ? { callSite: providerCallSite }
2284
+ : {}),
2285
+ ...(preparedOverrideProfile !== undefined
2286
+ ? { overrideProfile: preparedOverrideProfile }
2287
+ : {}),
2288
+ forceOverrideProfile: preparedForceOverrideProfile,
2289
+ ...(disableCache ? { disableCache: true as const } : {}),
2290
+ ...(signal !== undefined ? { signal } : {}),
2291
+ systemPrompt: providerOptions.systemPrompt ?? null,
2292
+ tools: currentTools,
2293
+ });
2294
+ } catch (preparedError) {
2295
+ rlog.warn(
2296
+ { err: preparedError },
2297
+ "Prepared model-call observer failed; continuing with provider dispatch",
2298
+ );
2299
+ }
2300
+ }
2301
+
2237
2302
  // Announce the LLM-call boundary so downstream handlers (the
2238
2303
  // daemon's persistence pipeline) can reserve an empty assistant row
2239
2304
  // and stamp the resulting `messageId` onto every streaming event the
@@ -421,6 +421,7 @@ function setupController(
421
421
  ) {
422
422
  ensureConversation("conv-ctrl-test");
423
423
  const session = createCallSession({
424
+ direction: "inbound",
424
425
  conversationId: "conv-ctrl-test",
425
426
  provider: "twilio",
426
427
  fromNumber: "+15551111111",
@@ -471,6 +472,7 @@ function setupControllerWithOrigin(task?: string) {
471
472
  ensureConversation("conv-ctrl-voice");
472
473
  ensureConversation("conv-ctrl-origin");
473
474
  const session = createCallSession({
475
+ direction: "inbound",
474
476
  conversationId: "conv-ctrl-voice",
475
477
  provider: "twilio",
476
478
  fromNumber: "+15551111111",
@@ -5028,4 +5030,96 @@ describe("call-controller", () => {
5028
5030
  await turnPromise.catch(() => {});
5029
5031
  });
5030
5032
  });
5033
+ describe("turn metrics", () => {
5034
+ test("a caller turn records the marks the latency numbers are built from", async () => {
5035
+ const { controller } = setupController();
5036
+
5037
+ await controller.handleCallerUtterance("What is the weather?");
5038
+
5039
+ const snapshot = controller.getMetricsSnapshot();
5040
+ expect(snapshot.recentTurns.length).toBe(1);
5041
+ const turn = snapshot.recentTurns[0];
5042
+ expect(turn.status).toBe("completed");
5043
+ // The transcript mark is seeded from when the caller stopped talking,
5044
+ // the dispatch mark from when the leg went out, and the delta mark from
5045
+ // the first token back: the three anchors every phone latency number is
5046
+ // subtracted from.
5047
+ expect(turn.timestamps.finalTranscriptAtMs).not.toBeNull();
5048
+ expect(turn.timestamps.assistantDispatchAtMs).not.toBeNull();
5049
+ expect(turn.timestamps.firstAssistantDeltaAtMs).not.toBeNull();
5050
+ expect(turn.durations.dispatchToFirstAssistantDeltaMs).not.toBeNull();
5051
+ expect(turn.durations.totalTurnDurationMs).not.toBeNull();
5052
+ // The provider's final doubles as the speech-end anchor, so the turn's
5053
+ // round trip is measurable on phone as it is in live voice.
5054
+ expect(turn.timestamps.utteranceEndAtMs).not.toBeNull();
5055
+ expect(turn.durations.roundTripMs).not.toBeNull();
5056
+
5057
+ controller.destroy();
5058
+ });
5059
+
5060
+ test("the transcript mark predates the dispatch it triggered", async () => {
5061
+ // Seeding backdates the turn to the caller's own boundary; a turn that
5062
+ // opened at dispatch time would report a felt latency that starts after
5063
+ // the caller already finished speaking.
5064
+ const { controller } = setupController();
5065
+
5066
+ await controller.handleCallerUtterance("Hello there");
5067
+
5068
+ const turn = controller.getMetricsSnapshot().recentTurns[0];
5069
+ const finalTranscriptAtMs = turn.timestamps.finalTranscriptAtMs;
5070
+ const assistantDispatchAtMs = turn.timestamps.assistantDispatchAtMs;
5071
+ expect(finalTranscriptAtMs).not.toBeNull();
5072
+ expect(assistantDispatchAtMs).not.toBeNull();
5073
+ expect(finalTranscriptAtMs!).toBeLessThanOrEqual(assistantDispatchAtMs!);
5074
+ expect(turn.timestamps.startedAtMs).toBeLessThanOrEqual(
5075
+ finalTranscriptAtMs!,
5076
+ );
5077
+
5078
+ controller.destroy();
5079
+ });
5080
+
5081
+ test("a barge-in ends the turn once, as cancelled", async () => {
5082
+ // One interruption is one cancelled turn: the count downstream reads as
5083
+ // "turns the caller cut off", so a second settle would double it.
5084
+ // A turn that never emits or completes holds the controller in the
5085
+ // pre-speech phase, which a sustained barge-in can still cut off.
5086
+ mockStartVoiceTurn.mockImplementation(
5087
+ async (opts: { onComplete: () => void }) => ({
5088
+ turnId: "run-metrics-slow",
5089
+ abort: () => opts.onComplete(),
5090
+ }),
5091
+ );
5092
+ const { controller } = setupController();
5093
+ const turnPromise = controller.handleCallerUtterance("Tell me a story");
5094
+ for (let i = 0; i < 5; i++) {
5095
+ await Promise.resolve();
5096
+ }
5097
+ expect(controller.getState()).toBe("processing");
5098
+
5099
+ expect(controller.handleBargeIn()).toBe(true);
5100
+ await turnPromise.catch(() => {});
5101
+ controller.destroy();
5102
+
5103
+ const turns = controller.getMetricsSnapshot().recentTurns;
5104
+ expect(turns.length).toBe(1);
5105
+ expect(turns[0].status).toBe("cancelled");
5106
+ expect(turns[0].cancellationReason).toBe("interrupted");
5107
+ expect(turns[0].timestamps.bargeInAtMs).not.toBeNull();
5108
+ });
5109
+
5110
+ test("no turn is invented between turns", async () => {
5111
+ // Every mark opens a turn when none is active, so a barge-in on an idle
5112
+ // controller must leave the collector empty rather than start a turn
5113
+ // that never settles.
5114
+ const { controller } = setupController();
5115
+
5116
+ expect(controller.handleBargeIn()).toBe(false);
5117
+
5118
+ const snapshot = controller.getMetricsSnapshot();
5119
+ expect(snapshot.recentTurns.length).toBe(0);
5120
+ expect(snapshot.activeTurn).toBeNull();
5121
+
5122
+ controller.destroy();
5123
+ });
5124
+ });
5031
5125
  });
@@ -0,0 +1,204 @@
1
+ /**
2
+ * Phone-call funnel rows: which ones the call store records and what they say.
3
+ *
4
+ * The recorder is mocked, as in `live-voice-session-telemetry.test.ts`: the
5
+ * outbox and its consent gate are covered by `telemetry-events-outbox.test.ts`.
6
+ * What these tests pin is the wiring that decides whether a row exists at all,
7
+ * which is where the measurement silently goes wrong: a call that never
8
+ * connects still has to count, a terminal status has to emit exactly one end
9
+ * row however many writes follow it, and a call nobody spoke on has to say so.
10
+ */
11
+
12
+ import { beforeEach, describe, expect, mock, test } from "bun:test";
13
+
14
+ const recordPhoneCallStarted = mock(() => null);
15
+ const recordPhoneCallEnded = mock(() => null);
16
+
17
+ // Spread the real module rather than replacing it: the call store pulls other
18
+ // recorders out of it, and a bare replacement makes those imports fail.
19
+ const onboardingEventsStore =
20
+ await import("../../onboarding/onboarding-events-store.js");
21
+ mock.module("../../onboarding/onboarding-events-store.js", () => ({
22
+ ...onboardingEventsStore,
23
+ recordPhoneCallStarted,
24
+ recordPhoneCallEnded,
25
+ }));
26
+
27
+ import { getDb } from "../../persistence/db-connection.js";
28
+ import { initializeDb } from "../../persistence/db-init.js";
29
+ import { conversations } from "../../persistence/schema/index.js";
30
+
31
+ await initializeDb();
32
+
33
+ // Values load after `mock.module` so the store picks up the mocked recorder.
34
+ const { createCallSession, recordCallEvent, updateCallSession } =
35
+ await import("../call-store.js");
36
+
37
+ let conversationSeq = 0;
38
+
39
+ function makeConversation(): string {
40
+ const id = `conv-funnel-${++conversationSeq}`;
41
+ const now = Date.now();
42
+ getDb()
43
+ .insert(conversations)
44
+ .values({
45
+ id,
46
+ title: `Test conversation ${id}`,
47
+ createdAt: now,
48
+ updatedAt: now,
49
+ })
50
+ .run();
51
+ return id;
52
+ }
53
+
54
+ function startCall(opts?: {
55
+ direction?: "inbound" | "outbound";
56
+ callMode?: string;
57
+ }): string {
58
+ const session = createCallSession({
59
+ conversationId: makeConversation(),
60
+ provider: "twilio",
61
+ direction: opts?.direction ?? "inbound",
62
+ fromNumber: "+15550100",
63
+ toNumber: "+15550101",
64
+ ...(opts?.callMode !== undefined ? { callMode: opts.callMode } : {}),
65
+ });
66
+ return session.id;
67
+ }
68
+
69
+ beforeEach(() => {
70
+ recordPhoneCallStarted.mockClear();
71
+ recordPhoneCallEnded.mockClear();
72
+ });
73
+
74
+ describe("call funnel start rows", () => {
75
+ test("an inbound call counts the moment its session row exists", () => {
76
+ // Before the provider has dialled and before any preflight can reject it:
77
+ // a call that never connects is the one the funnel most needs to count.
78
+ const callSessionId = startCall({ callMode: "normal" });
79
+
80
+ expect(recordPhoneCallStarted).toHaveBeenCalledTimes(1);
81
+ expect(recordPhoneCallStarted).toHaveBeenCalledWith({
82
+ callSessionId,
83
+ screen: "started_inbound:normal",
84
+ });
85
+ });
86
+
87
+ test("an outbound call is stamped by the direction it states", () => {
88
+ // Stated, not inferred: a verification or invite call dials out and
89
+ // carries no task, so task presence would misread as inbound.
90
+ startCall({ direction: "outbound", callMode: "verification" });
91
+
92
+ expect(recordPhoneCallStarted).toHaveBeenCalledWith(
93
+ expect.objectContaining({ screen: "started_outbound:verification" }),
94
+ );
95
+ });
96
+
97
+ test("an ordinary call stamps the normal mode it never writes", () => {
98
+ // createInboundVoiceSession and startCall leave callMode null; only the
99
+ // verification and invite flows set one.
100
+ startCall();
101
+
102
+ expect(recordPhoneCallStarted).toHaveBeenCalledWith(
103
+ expect.objectContaining({ screen: "started_inbound:normal" }),
104
+ );
105
+ });
106
+ });
107
+
108
+ describe("call funnel end rows", () => {
109
+ test("a completed call that took a turn reports no silence", () => {
110
+ const callSessionId = startCall({ callMode: "normal" });
111
+ updateCallSession(callSessionId, { status: "in_progress" });
112
+ recordCallEvent(callSessionId, "call_connected");
113
+ recordCallEvent(callSessionId, "caller_spoke", {
114
+ transcript: "hello",
115
+ transport: "media-stream",
116
+ });
117
+
118
+ updateCallSession(callSessionId, { status: "completed" });
119
+
120
+ expect(recordPhoneCallEnded).toHaveBeenCalledTimes(1);
121
+ expect(recordPhoneCallEnded).toHaveBeenCalledWith({
122
+ callSessionId,
123
+ screen: "ended_completed",
124
+ outcome: "completed",
125
+ });
126
+ });
127
+
128
+ test("a call that never connected is silent for that reason", () => {
129
+ const callSessionId = startCall({ callMode: "normal" });
130
+
131
+ updateCallSession(callSessionId, { status: "failed" });
132
+
133
+ expect(recordPhoneCallEnded).toHaveBeenCalledWith({
134
+ callSessionId,
135
+ screen: "ended_failed:silent_no_connect",
136
+ outcome: "failed",
137
+ });
138
+ });
139
+
140
+ test("a connected call nobody spoke on is silent on the line", () => {
141
+ // The distinction the rate lives on: the telephony leg worked and the
142
+ // conversation still never started.
143
+ const callSessionId = startCall({ callMode: "normal" });
144
+ updateCallSession(callSessionId, { status: "in_progress" });
145
+ recordCallEvent(callSessionId, "call_connected");
146
+
147
+ updateCallSession(callSessionId, { status: "completed" });
148
+
149
+ expect(recordPhoneCallEnded).toHaveBeenCalledWith(
150
+ expect.objectContaining({ screen: "ended_completed:silent_no_turn" }),
151
+ );
152
+ });
153
+
154
+ test("a call where only digits were pressed took no turn", () => {
155
+ // DTMF digits ride `caller_spoke` too; only a transcript is a turn.
156
+ const callSessionId = startCall({ callMode: "normal" });
157
+ updateCallSession(callSessionId, { status: "in_progress" });
158
+ recordCallEvent(callSessionId, "call_connected");
159
+ recordCallEvent(callSessionId, "caller_spoke", {
160
+ dtmfDigit: "4",
161
+ transport: "media-stream",
162
+ });
163
+
164
+ updateCallSession(callSessionId, { status: "completed" });
165
+
166
+ expect(recordPhoneCallEnded).toHaveBeenCalledWith(
167
+ expect.objectContaining({ screen: "ended_completed:silent_no_turn" }),
168
+ );
169
+ });
170
+
171
+ test("a cancelled call completed its course", () => {
172
+ // Only an error is a failure; a call cancelled before it connected ran
173
+ // exactly as far as it was asked to.
174
+ const callSessionId = startCall({ callMode: "normal" });
175
+
176
+ updateCallSession(callSessionId, { status: "cancelled" });
177
+
178
+ expect(recordPhoneCallEnded).toHaveBeenCalledWith(
179
+ expect.objectContaining({ outcome: "completed" }),
180
+ );
181
+ });
182
+
183
+ test("only the first terminal write records an end", () => {
184
+ // Terminal states are immutable, so the rejected second write must not
185
+ // produce a second row to pair with the one start.
186
+ const callSessionId = startCall({ callMode: "normal" });
187
+ updateCallSession(callSessionId, { status: "completed" });
188
+
189
+ updateCallSession(callSessionId, { status: "failed" });
190
+
191
+ expect(recordPhoneCallEnded).toHaveBeenCalledTimes(1);
192
+ expect(recordPhoneCallEnded).toHaveBeenCalledWith(
193
+ expect.objectContaining({ screen: "ended_completed:silent_no_connect" }),
194
+ );
195
+ });
196
+
197
+ test("a non-status update records nothing", () => {
198
+ const callSessionId = startCall({ callMode: "normal" });
199
+
200
+ updateCallSession(callSessionId, { providerCallSid: "CA-test" });
201
+
202
+ expect(recordPhoneCallEnded).not.toHaveBeenCalled();
203
+ });
204
+ });